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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Kakoen/valheim-save-tools | 3,104 | valheim-save-tools-lib/src/main/java/net/kakoen/valheim/save/archive/ValheimSaveArchive.java | package net.kakoen.valheim.save.archive;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.kakoen.valheim.save.archive.hints.ValheimSaveReaderHints;
import net.kakoen.valheim.save.archive.save.DeadZdo;
import net.kakoen.valheim.save.archive.save.Meta;
import net.kakoen.valheim.save.archive.save.RandomEvent;
import net.kakoen.valheim.save.archive.save.Zdo;
import net.kakoen.valheim.save.archive.save.Zones;
import net.kakoen.valheim.save.exception.ValheimArchiveUnsupportedVersionException;
import net.kakoen.valheim.save.parser.ZPackage;
/**
* Reads the *.db save files
*/
@Data
@NoArgsConstructor
@Slf4j
public class ValheimSaveArchive implements ValheimArchive {
public static final int MAX_SUPPORTED_WORLD_VERSION = 34;
private Meta meta;
private long modified;
private long myId;
private long nextUid;
private Zones zones;
private RandomEvent randomEvent;
private List<Zdo> zdoList = new ArrayList<>();
public ValheimSaveArchive(File file, ValheimSaveReaderHints hints) throws IOException, ValheimArchiveUnsupportedVersionException {
meta = new Meta();
modified = file.lastModified();
meta.setModified(file.lastModified());
try(ZPackage zPackage = new ZPackage(file)) {
meta.setWorldVersion(zPackage.readInt32());
if(meta.getWorldVersion() > MAX_SUPPORTED_WORLD_VERSION) {
if(hints.isFailOnUnsupportedVersion()) {
throw new ValheimArchiveUnsupportedVersionException(ValheimSaveArchive.class, "world", meta.getWorldVersion(), MAX_SUPPORTED_WORLD_VERSION);
}
log.warn("WARNING: world version is {}, the maximum tested world version is {}", meta.getWorldVersion(), MAX_SUPPORTED_WORLD_VERSION);
} else {
log.info("World version: {}", meta.getWorldVersion());
}
meta.setNetTime(zPackage.readDouble());
loadZdos(zPackage, meta.getWorldVersion(), hints);
zones = new Zones();
zones.load(zPackage, meta.getWorldVersion());
randomEvent = new RandomEvent(zPackage);
}
}
@Override
public void save(File file) throws IOException {
try(ZPackage zPackage = new ZPackage()) {
zPackage.writeInt32(MAX_SUPPORTED_WORLD_VERSION);
zPackage.writeDouble(meta.getNetTime());
writeZdos(zPackage);
zPackage.writeTo(file);
}
}
@Override
public ValheimArchiveType getType() {
return ValheimArchiveType.DB;
}
private void writeZdos(ZPackage writer) {
writer.writeLong(myId);
writer.writeUInt(nextUid);
writer.writeInt32(zdoList.size());
zdoList.forEach(zdo -> zdo.save(writer));
zones.save(writer);
randomEvent.save(writer);
}
private void loadZdos(ZPackage reader, int version, ValheimSaveReaderHints hints) throws ValheimArchiveUnsupportedVersionException {
myId = reader.readLong();
nextUid = reader.readUInt();
int numberOfZdos = reader.readInt32();
for(int i = 0; i < numberOfZdos; i++) {
Zdo zdo = new Zdo(reader, version, hints);
zdoList.add(zdo);
}
log.info("Loaded {} zdos", zdoList.size());
}
}
| 0 | 0.854694 | 1 | 0.854694 | game-dev | MEDIA | 0.58078 | game-dev | 0.690077 | 1 | 0.690077 |
jaychang0917/SimpleApiClient-ios | 3,744 | Example/Pods/RxSwift/Platform/DataStructures/PriorityQueue.swift | //
// PriorityQueue.swift
// Platform
//
// Created by Krunoslav Zaher on 12/27/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
struct PriorityQueue<Element> {
private let _hasHigherPriority: (Element, Element) -> Bool
private let _isEqual: (Element, Element) -> Bool
fileprivate var _elements = [Element]()
init(hasHigherPriority: @escaping (Element, Element) -> Bool, isEqual: @escaping (Element, Element) -> Bool) {
_hasHigherPriority = hasHigherPriority
_isEqual = isEqual
}
mutating func enqueue(_ element: Element) {
_elements.append(element)
bubbleToHigherPriority(_elements.count - 1)
}
func peek() -> Element? {
return _elements.first
}
var isEmpty: Bool {
return _elements.count == 0
}
mutating func dequeue() -> Element? {
guard let front = peek() else {
return nil
}
removeAt(0)
return front
}
mutating func remove(_ element: Element) {
for i in 0 ..< _elements.count {
if _isEqual(_elements[i], element) {
removeAt(i)
return
}
}
}
private mutating func removeAt(_ index: Int) {
let removingLast = index == _elements.count - 1
if !removingLast {
#if swift(>=3.2)
_elements.swapAt(index, _elements.count - 1)
#else
swap(&_elements[index], &_elements[_elements.count - 1])
#endif
}
_ = _elements.popLast()
if !removingLast {
bubbleToHigherPriority(index)
bubbleToLowerPriority(index)
}
}
private mutating func bubbleToHigherPriority(_ initialUnbalancedIndex: Int) {
precondition(initialUnbalancedIndex >= 0)
precondition(initialUnbalancedIndex < _elements.count)
var unbalancedIndex = initialUnbalancedIndex
while unbalancedIndex > 0 {
let parentIndex = (unbalancedIndex - 1) / 2
guard _hasHigherPriority(_elements[unbalancedIndex], _elements[parentIndex]) else { break }
#if swift(>=3.2)
_elements.swapAt(unbalancedIndex, parentIndex)
#else
swap(&_elements[unbalancedIndex], &_elements[parentIndex])
#endif
unbalancedIndex = parentIndex
}
}
private mutating func bubbleToLowerPriority(_ initialUnbalancedIndex: Int) {
precondition(initialUnbalancedIndex >= 0)
precondition(initialUnbalancedIndex < _elements.count)
var unbalancedIndex = initialUnbalancedIndex
while true {
let leftChildIndex = unbalancedIndex * 2 + 1
let rightChildIndex = unbalancedIndex * 2 + 2
var highestPriorityIndex = unbalancedIndex
if leftChildIndex < _elements.count && _hasHigherPriority(_elements[leftChildIndex], _elements[highestPriorityIndex]) {
highestPriorityIndex = leftChildIndex
}
if rightChildIndex < _elements.count && _hasHigherPriority(_elements[rightChildIndex], _elements[highestPriorityIndex]) {
highestPriorityIndex = rightChildIndex
}
guard highestPriorityIndex != unbalancedIndex else { break }
#if swift(>=3.2)
_elements.swapAt(highestPriorityIndex, unbalancedIndex)
#else
swap(&_elements[highestPriorityIndex], &_elements[unbalancedIndex])
#endif
unbalancedIndex = highestPriorityIndex
}
}
}
extension PriorityQueue : CustomDebugStringConvertible {
var debugDescription: String {
return _elements.debugDescription
}
}
| 0 | 0.911722 | 1 | 0.911722 | game-dev | MEDIA | 0.089525 | game-dev | 0.932394 | 1 | 0.932394 |
justinmimbs/rs-asteroids | 10,058 | asteroids/src/player.rs | use rand_pcg::Pcg32;
use std::f64::consts::FRAC_PI_2;
use crate::asteroid::Asteroid;
use crate::blast::Blast;
use crate::geometry;
use crate::geometry::{Point, Size, Vector};
use crate::iter::{EdgesCycleIterator, EdgesIterator};
use crate::motion;
use crate::motion::{Collide, Movement, Placement};
use crate::particle::{Dispersion, Particle};
use crate::util::{Interval, Timer};
use crate::Controls;
const HULL: [Point; 7] = [
Point { x: -19.0, y: -10.0 },
Point { x: -9.0, y: -18.0 },
Point { x: -3.0, y: -6.0 },
Point { x: 21.0, y: 0.0 },
Point { x: -3.0, y: 6.0 },
Point { x: -9.0, y: 18.0 },
Point { x: -19.0, y: 10.0 },
];
const INTERIOR: [Point; 5] = [
Point { x: -19.0, y: -10.0 },
Point { x: -3.0, y: -6.0 },
Point { x: 0.0, y: 0.0 },
Point { x: -3.0, y: 6.0 },
Point { x: -19.0, y: 10.0 },
];
const NOZZLE: Point = Point { x: -19.0, y: 5.0 };
const SPACESHIP_MASS: f64 = 300.0;
const TURNING_SPEED: f64 = 0.5; // radians / second
const THRUST_SPEED: f64 = 35.0; // px / second
const POSITION_FRICTION: f64 = 0.98;
const ROTATION_FRICTION: f64 = 0.92;
const FIRING_INTERVAL: f64 = 1.0 / 6.0; // seconds (6 hz)
const BLAST_SPEED: f64 = 800.0; // px / second
const THRUSTING_INTERVAL: f64 = 1.0 / 12.0; // seconds (12 hz)
const EXHAUST_SPEED: f64 = 120.0; // px / second
const EXHAUST_MAX_AGE: f64 = 0.2; // seconds
struct Spaceship {
radius: f64,
hull: Vec<Point>,
interior: Vec<Point>,
shield: Vec<Point>,
nozzle: Point,
}
impl Spaceship {
fn new(radius: f64) -> Self {
let factor = radius / 22.0;
Spaceship {
radius,
hull: HULL.iter().map(|point| point.scale(factor)).collect(),
interior: INTERIOR.iter().map(|point| point.scale(factor)).collect(),
shield: geometry::ngon(16, radius + 1.0),
nozzle: NOZZLE.scale(factor),
}
}
}
enum Aux {
Off,
Firing { interval: Interval },
Shielding { delay: Timer },
}
enum Engine {
Idle,
Thrusting { interval: Interval },
}
pub struct Impact {
pub destroyed: bool,
pub particles: Vec<Particle>,
}
pub struct Player {
placement: Placement,
movement: Movement,
spaceship: Spaceship,
aux: Aux,
engine: Engine,
exhaust: Vec<Timer>,
}
impl Player {
pub fn new(position: Point) -> Self {
Player {
placement: Placement {
position,
rotation: -FRAC_PI_2,
},
movement: Movement {
velocity: Point::new(0.0, 0.0),
angular_velocity: 0.0,
},
spaceship: Spaceship::new(18.0),
aux: Aux::Off,
engine: Engine::Idle,
exhaust: Vec::new(),
}
}
pub fn hull(&self) -> Vec<Point> {
self.placement.transform_points(&self.spaceship.hull)
}
pub fn interior(&self) -> Vec<Point> {
self.placement.transform_points(&self.spaceship.interior)
}
fn is_shielding(&self) -> bool {
match &self.aux {
Aux::Shielding { delay } if delay.is_elapsed() => true,
_ => false,
}
}
pub fn shield(&self) -> Option<Vec<Point>> {
if self.is_shielding() {
Some(self.placement.transform_points(&self.spaceship.shield))
} else {
None
}
}
pub fn exhaust(&self) -> Vec<(f64, Vec<Point>)> {
self.exhaust
.iter()
.map(|timer| {
let alpha = timer.remaining() / EXHAUST_MAX_AGE;
let distance = (EXHAUST_MAX_AGE - timer.remaining()) * EXHAUST_SPEED;
let Point { x, y } = self.spaceship.nozzle;
let path = vec![
Point::new(x, -y),
Point::new(x - distance, 0.0),
Point::new(x, y),
];
(alpha, self.placement.transform_points(&path))
})
.collect()
}
pub fn step(&mut self, dt: f64, bounds: &Size, controls: Controls) -> () {
let rotation_thrust = match (controls.left(), controls.right()) {
(true, false) => -TURNING_SPEED * dt,
(false, true) => TURNING_SPEED * dt,
_ => 0.0,
};
let rotation = self.placement.rotation
+ (self.movement.angular_velocity * ROTATION_FRICTION * dt)
+ rotation_thrust;
let position_thrust = if controls.thrust() {
Vector::from_polar(THRUST_SPEED * dt, rotation)
} else {
Vector::new(0.0, 0.0)
};
let position = (self.placement.position)
.add(&self.movement.velocity.scale(POSITION_FRICTION * dt))
.add(&position_thrust);
self.movement.velocity = position.sub(&self.placement.position).scale(1.0 / dt);
self.movement.angular_velocity = (rotation - self.placement.rotation) / dt;
self.placement.position = position;
self.placement.rotation = rotation;
self.placement.wrap_position(bounds);
// aux
if controls.shield() {
if let Aux::Shielding { delay } = &mut self.aux {
delay.step(dt);
} else {
self.aux = Aux::Shielding {
delay: Timer::new(0.0),
};
};
} else if controls.fire() {
if let Aux::Firing { interval } = &mut self.aux {
interval.step(dt);
} else {
self.aux = Aux::Firing {
interval: Interval::new(FIRING_INTERVAL, FIRING_INTERVAL),
};
};
} else {
self.aux = Aux::Off;
}
// engine
if controls.thrust() {
if let Engine::Idle = &self.engine {
self.engine = Engine::Thrusting {
interval: Interval::new(THRUSTING_INTERVAL, THRUSTING_INTERVAL),
};
}
} else {
self.engine = Engine::Idle;
}
// exhaust
for timer in self.exhaust.iter_mut() {
timer.step(dt);
}
if let Engine::Thrusting { interval } = &mut self.engine {
interval.step(dt);
self.exhaust
.extend(interval.map(|age| Timer::new(EXHAUST_MAX_AGE - age)));
}
self.exhaust.retain(|timer| !timer.is_elapsed());
}
pub fn fire_blast(&mut self) -> Option<Blast> {
match &mut self.aux {
Aux::Firing { interval } => interval.next().map(|_| {
let speed = self.movement.velocity.length() + BLAST_SPEED;
let angle = self.placement.rotation;
let position = (self.placement.position)
.add(&Vector::from_polar(self.spaceship.radius, angle));
Blast::new(position, speed, angle)
}),
_ => None,
}
}
pub fn interact_blast(&mut self, rng: &mut Pcg32, blast: &Blast) -> Option<Impact> {
if let Some(impact) = blast.impact(self) {
self.movement = self.movement.add(&Movement::from_impulse(
&self.placement.position,
&impact.point,
&blast.velocity().normalize().scale(impact.speed),
));
Some(self.impact(rng, &impact.point, impact.speed))
} else {
None
}
}
pub fn interact_asteroid(
&mut self,
rng: &mut Pcg32,
asteroid: &mut Asteroid,
) -> Option<Impact> {
let elasticity = if self.is_shielding() { 1.0 } else { 0.1 };
if let Some((impact_point, self_movement, asteroid_movement)) =
motion::collide(self, asteroid, elasticity)
{
self.movement = self_movement;
asteroid.set_movement(asteroid_movement);
let impact_speed =
self.movement.velocity.length() + asteroid.movement().velocity.length();
Some(self.impact(rng, &impact_point, impact_speed))
} else {
None
}
}
fn impact(&mut self, rng: &mut Pcg32, point: &Point, speed: f64) -> Impact {
let mut particles = Dispersion::new(
point.clone(),
self.movement.velocity.scale(0.5),
speed * 0.5,
speed * 0.2,
)
.burst(rng, (speed.sqrt() * 0.5).ceil() as u32);
if self.is_shielding() {
// bounce
self.aux = Aux::Shielding {
delay: Timer::new(speed * 0.002),
};
Impact {
destroyed: false,
particles,
}
} else {
// explode
particles.append(
&mut Dispersion::new(
self.placement.position.clone(),
self.movement.velocity.scale(0.5),
170.0,
140.0,
)
.burst(rng, speed.sqrt().ceil().min(18.0) as u32),
);
let dispersion = Dispersion::new(
self.placement.position.clone(),
self.movement.velocity.clone(),
speed.min(150.0) * 1.5,
speed.min(150.0),
);
particles.append(&mut dispersion.explode(rng, (self.hull().iter()).edges_cycle()));
particles.append(&mut dispersion.explode(rng, (self.interior().iter()).edges()));
Impact {
destroyed: true,
particles,
}
}
}
}
impl Collide for Player {
fn center(&self) -> &Point {
&self.placement.position
}
fn radius(&self) -> f64 {
self.spaceship.radius
}
fn boundary(&self) -> Vec<Point> {
if let Some(shield) = self.shield() {
shield
} else {
self.hull()
}
}
fn movement(&self) -> &Movement {
&self.movement
}
fn mass(&self) -> f64 {
SPACESHIP_MASS
}
}
| 0 | 0.835799 | 1 | 0.835799 | game-dev | MEDIA | 0.958275 | game-dev | 0.981272 | 1 | 0.981272 |
magefree/mage | 3,293 | Mage/src/main/java/mage/abilities/costs/AlternativeCostImpl.java | package mage.abilities.costs;
import mage.abilities.costs.mana.ManaCost;
import mage.game.Game;
import mage.util.CardUtil;
/**
* Alternative costs
*
* @param <T>
* @author LevelX2
*/
public class AlternativeCostImpl<T extends AlternativeCostImpl<T>> extends CostsImpl<Cost> implements AlternativeCost {
protected String name;
protected final String reminderText;
protected boolean isMana;
protected boolean activated;
public AlternativeCostImpl(String name, String reminderText, Cost cost) {
this.activated = false;
this.name = name;
this.isMana = cost instanceof ManaCost;
this.reminderText = reminderText;
this.add(cost);
}
protected AlternativeCostImpl(final AlternativeCostImpl<?> cost) {
super(cost);
this.name = cost.name;
this.reminderText = cost.reminderText;
this.activated = cost.activated;
this.isMana = cost.isMana;
}
@Override
public String getName() {
return this.name;
}
/**
* Returns the complete text for the addional cost or if onlyCost is true
* only the pure text for the included native cost
*
* @param onlyCost
* @return
*/
@Override
public String getText(boolean onlyCost) {
if (onlyCost) {
return getText();
} else {
String costName = (name != null ? name : "");
String delimiter = (!isMana || (!costName.isEmpty() && costName.substring(costName.length() - 1).matches("\\d")))
? "—" : " ";
return costName + delimiter + getText() + (isMana ? "" : '.');
}
}
/**
* Returns a reminder text, if the cost has one
*
* @return
*/
@Override
public String getReminderText() {
if (reminderText != null && !reminderText.isEmpty()) {
return "<i>(" + reminderText.replace("{cost}", CardUtil.getTextWithFirstCharLowerCase(this.getText(true))) + ")</i>";
}
return "";
}
/**
* Returns a text suffix for the game log, that can be added to the cast
* message.
*
* @param position - if there are multiple costs, it's the postion the cost
* is set (starting with 0)
* @return
*/
@Override
public String getCastSuffixMessage(int position) {
StringBuilder sb = new StringBuilder(position > 0 ? " and " : "").append(" with ");
sb.append(name);
return sb.toString();
}
/**
* If the player intends to pay the cost, the cost will be activated
*/
@Override
public void activate() {
activated = true;
}
/**
* Reset the activate and count information
*/
@Override
public void reset() {
activated = false;
}
/**
* Returns if the cost was activated
*
* @param game
* @return
*/
@Override
public boolean isActivated(Game game) {
return activated;
}
@Override
public AlternativeCostImpl<?> copy() {
return new AlternativeCostImpl<>(this);
}
@Override
public Cost getCost() {
if (this.iterator().hasNext()) {
return this.iterator().next();
}
return null;
}
}
| 0 | 0.872726 | 1 | 0.872726 | game-dev | MEDIA | 0.871203 | game-dev | 0.946473 | 1 | 0.946473 |
DFHack/dfhack | 2,196 | plugins/diggingInvaders/edgeCost.h | #pragma once
#include "Console.h"
#include "DataDefs.h"
#include "modules/Maps.h"
#include "modules/MapCache.h"
#include "df/coord.h"
#include <unordered_map>
#include <vector>
//cost is [path cost, building destruction cost, dig cost, construct cost]. Minimize constructions, then minimize dig cost, then minimize path cost.
enum CostDimension {
Walk,
DestroyBuilding,
Dig,
DestroyRoughConstruction,
DestroySmoothConstruction,
//Construct,
costDim
};
typedef int64_t cost_t;
struct DigAbilities {
cost_t costWeight[costDim];
int32_t jobDelay[costDim];
};
//extern cost_t costWeight[costDim];
//extern int32_t jobDelay[costDim];
extern std::unordered_map<std::string, DigAbilities> digAbilities;
/*
const cost_t costWeight[] = {
//Distance
1,
//Destroy Building
2,
//Dig
10000,
//DestroyConstruction
100,
};
*/
class Edge {
public:
//static map<df::coord, int32_t> pointCost;
df::coord p1;
df::coord p2;
cost_t cost;
Edge() {
cost = -1;
}
Edge(const Edge& e): p1(e.p1), p2(e.p2), cost(e.cost) {
}
Edge(df::coord p1In, df::coord p2In, cost_t costIn): cost(costIn) {
if ( p2In < p1In ) {
p1 = p2In;
p2 = p1In;
} else {
p1 = p1In;
p2 = p2In;
}
}
bool operator==(const Edge& e) const {
return (cost == e.cost && p1 == e.p1 && p2 == e.p2);
}
bool operator<(const Edge& e) const {
if ( cost != e.cost )
return cost < e.cost;
if ( p1.z != e.p1.z )
return p1.z < e.p1.z;
if ( p1 != e.p1 )
return p1 < e.p1;
if ( p2.z != e.p2.z )
return p2.z < e.p2.z;
if ( p2 != e.p2 )
return p2 < e.p2;
return false;
}
};
struct PointHash {
size_t operator()(const df::coord c) const {
return c.x * 65537 + c.y * 17 + c.z;
}
};
cost_t getEdgeCost(DFHack::color_ostream& out, df::coord pt1, df::coord pt2, DigAbilities& abilities);
std::vector<Edge>* getEdgeSet(DFHack::color_ostream &out, df::coord point, MapExtras::MapCache& cache, int32_t xMax, int32_t yMax, int32_t zMax, DigAbilities& abilities);
| 0 | 0.847532 | 1 | 0.847532 | game-dev | MEDIA | 0.431438 | game-dev | 0.853859 | 1 | 0.853859 |
forcedotcom/dependencies-cli | 2,784 | src/lib/DFSLib.ts | /*
* Copyright (c) 2018, salesforce.com, inc.
* All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
* For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
import {AbstractGraph} from './abstractGraph';
import {Node, Edge} from '../lib/NodeDefs';
export abstract class DepthFirstSearch {
protected readonly graph: AbstractGraph;
private readonly state: Set<Node>;
constructor(g: AbstractGraph) {
this.graph = g;
this.state = new Set<Node>();
}
public run() {
for (const node of this.graph.nodes) {
if (this.state.has(node)) {
// this node was processed by a previous call to dfs
return;
}
this.dfs(node);
}
}
public abstract visit(node: Node);
public abstract explore(src: Node, dst: Node);
public abstract finish(node: Node);
protected dfs(node: Node) {
this.visit(node);
for (const dst of this.graph.getEdges(node)) {
this.explore(node, dst);
if (this.state.has(dst)) {
// already visited this node
continue;
}
this.state.add(dst);
this.dfs(dst);
}
this.finish(node);
}
}
export class FindAllDependencies extends DepthFirstSearch {
public visited: Map<string, Node> = new Map<string, Node>();
public finished: Set<Node> = new Set<Node>();
public visitedNames: Set<String> = new Set<String>();
public visitedEdges: Set<Edge> = new Set<Edge>();
public visit(node: Node) {
this.visited.set(node.name, node);
this.visitedNames.add(node.name);
}
public finish(node: Node) {
this.finished.add(node);
}
public runNode(node: Node) {
if (!this.visited.has(node.name)) {
this.dfs(node);
}
}
public explore(src: Node, dst: Node) {
this.visitedEdges.add({from: src.name, to: dst.name});
}
}
export class FindCycles extends DepthFirstSearch {
public visited: Set<Node> = new Set<Node>();
public finished: Set<Node> = new Set<Node>();
public cycles: Node[][] = new Array<Node[]>();
public visit(node: Node) {
this.visited.add(node);
}
public finish(node: Node) {
this.finished.add(node);
}
public explore(src: Node, dst: Node) {
// ignore self cycles
if (src === dst) {
return;
}
// if we have an edge to a node that is visited but not finished, then it's
// a back edge
if (this.visited.has(dst) && !this.finished.has(dst)) {
// This is a cycle
this.cycles.push([src, dst]);
}
}
}
| 0 | 0.767264 | 1 | 0.767264 | game-dev | MEDIA | 0.361979 | game-dev | 0.626192 | 1 | 0.626192 |
fulpstation/fulpstation | 2,529 | code/modules/mob/living/basic/space_fauna/demon/demon.dm | /// Player controlled mobs that rip and tear, typically summoned by wizards.
/mob/living/basic/demon
name = "imp"
real_name = "imp"
unique_name = TRUE
desc = "A large, menacing creature covered in armored black scales."
speak_emote = list("cackles","screeches")
response_help_continuous = "thinks better of touching"
response_help_simple = "think better of touching"
response_disarm_continuous = "flails at"
response_disarm_simple = "flail at"
response_harm_continuous = "punches"
response_harm_simple = "punch"
attack_verb_continuous = "wildly tears into"
attack_verb_simple = "wildly tear into"
icon = 'icons/mob/simple/demon.dmi'
icon_state = "demon"
icon_living = "demon"
mob_biotypes = MOB_BEAST|MOB_HUMANOID
status_flags = CANPUSH
combat_mode = TRUE
attack_sound = 'sound/effects/magic/demon_attack1.ogg'
attack_vis_effect = ATTACK_EFFECT_CLAW
faction = list(FACTION_HELL)
maxHealth = 200
health = 200
obj_damage = 40
melee_damage_lower = 10
melee_damage_upper = 15
melee_attack_cooldown = CLICK_CD_MELEE
death_message = "screams in agony as it sublimates into a sulfurous smoke."
death_sound = 'sound/effects/magic/demon_dies.ogg'
habitable_atmos = null
minimum_survivable_temperature = T0C - 25 //Weak to cold
maximum_survivable_temperature = INFINITY
basic_mob_flags = DEL_ON_DEATH
// You KNOW we're doing a lightly purple red
lighting_cutoff_red = 30
lighting_cutoff_green = 10
lighting_cutoff_blue = 20
/// Typepath of the antag datum to add to the demon when applicable
var/datum/antagonist/antag_type = null
/mob/living/basic/demon/Initialize(mapload)
. = ..()
var/list/grantable_loot = grant_loot()
if(length(grantable_loot))
AddElement(/datum/element/death_drops, grantable_loot)
/// Proc that adds the necessary loot for the demon. Return an empty list if you don't want to add anything.
/mob/living/basic/demon/proc/grant_loot()
return list()
/// Proc that just sets up the demon's antagonism status.
/mob/living/basic/demon/mind_initialize()
. = ..()
if(isnull(antag_type) || mind.has_antag_datum(antag_type))
return // we weren't built for this proc to run
mind.set_assigned_role(SSjob.get_job_type(/datum/job/slaughter_demon))
mind.special_role = ROLE_SLAUGHTER_DEMON
mind.add_antag_datum(antag_type)
SEND_SOUND(src, 'sound/effects/magic/demon_dies.ogg')
to_chat(src, span_bold("You are currently not currently in the same plane of existence as the station. Use your Blood Crawl ability near a pool of blood to manifest and wreak havoc."))
| 0 | 0.971506 | 1 | 0.971506 | game-dev | MEDIA | 0.997716 | game-dev | 0.819603 | 1 | 0.819603 |
SAT-R/sa2 | 1,910 | src/game/sa1_sa2_shared/interactables/slidy_ice.c | #include "global.h"
#include "task.h"
#include "game/stage/player.h"
#include "game/stage/camera.h"
#include "game/entity.h"
#include "game/sa1_sa2_shared/interactables/slidy_ice.h"
typedef struct {
/* 0x00 */ u8 x;
/* 0x01 */ u8 y;
/* 0x02 */ u8 index;
/* 0x03 */ s8 offsetX;
/* 0x04 */ s8 offsetY;
/* 0x05 */ u8 width;
/* 0x06 */ u8 height;
} MapEntity_SlidyIce;
typedef struct {
/* 0x00 */ SpriteBase base;
} Sprite_SlidyIce;
void Task_SlidyIce(void)
{
Sprite_SlidyIce *ice = TASK_DATA(gCurTask);
MapEntity_SlidyIce *me = (MapEntity_SlidyIce *)ice->base.me;
u8 spriteX = ice->base.spriteX;
s32 regionX, regionY;
s32 screenX, screenY;
regionX = ice->base.regionX;
regionY = ice->base.regionY;
screenX = TO_WORLD_POS(spriteX, regionX);
screenY = TO_WORLD_POS(me->y, regionY);
if (!(gPlayer.moveState & MOVESTATE_DEAD)) {
s32 posX = (screenX + me->offsetX * TILE_WIDTH);
if ((posX <= I(gPlayer.qWorldX)) && ((posX + me->width * TILE_WIDTH) >= I(gPlayer.qWorldX))) {
s32 posY = screenY + me->offsetY * TILE_WIDTH;
if ((posY <= I(gPlayer.qWorldY)) && ((posY + me->height * TILE_WIDTH) >= I(gPlayer.qWorldY))) {
gPlayer.moveState |= MOVESTATE_ICE_SLIDE;
}
}
}
// _08011292
screenX -= gCamera.x;
screenY -= gCamera.y;
if (IS_OUT_OF_CAM_RANGE_TYPED(u32, screenX, screenY)) {
me->x = spriteX;
TaskDestroy(gCurTask);
}
}
void CreateEntity_SlidyIce(MapEntity *me, u16 spriteRegionX, u16 spriteRegionY, u8 spriteY)
{
struct Task *t = TaskCreate(Task_SlidyIce, sizeof(Sprite_SlidyIce), 0x2010, 0, NULL);
Sprite_SlidyIce *ice = TASK_DATA(t);
ice->base.regionX = spriteRegionX;
ice->base.regionY = spriteRegionY;
ice->base.me = me;
ice->base.spriteX = me->x;
SET_MAP_ENTITY_INITIALIZED(me);
}
| 0 | 0.676662 | 1 | 0.676662 | game-dev | MEDIA | 0.886324 | game-dev | 0.977279 | 1 | 0.977279 |
synnaxlabs/synnax | 1,932 | pluto/src/vis/render/performance.ts | // Copyright 2025 Synnax Labs, Inc.
//
// Use of this software is governed by the Business Source License included in the file
// licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with the Business Source
// License, use of this software will be governed by the Apache License, Version 2.0,
// included in the file licenses/APL.txt.
import { type Destructor, TimeSpan } from "@synnaxlabs/x";
class TrackerEntry {
level: number;
private total: number;
private overTarget: number;
private readonly target: TimeSpan;
constructor(target: TimeSpan) {
this.target = target;
this.overTarget = 0;
this.level = 0;
this.total = 0;
}
measure(): [number, Destructor] {
const start = performance.now();
return [
this.level,
() => {
const elapsed = TimeSpan.milliseconds(performance.now() - start);
if (elapsed.greaterThan(this.target)) this.overTarget++;
this.total++;
},
];
}
updateLevel(): void {
if (this.total === 0 || this.overTarget === 0) return;
const overTargetFrac = this.overTarget / this.total;
if (overTargetFrac < 0.125)
if (this.level > 0) this.level--;
else if (overTargetFrac > 0.25) this.level++;
}
}
export class Tracker {
private readonly entries: Map<string, TrackerEntry>;
private readonly target: TimeSpan;
constructor(target: TimeSpan) {
this.entries = new Map();
this.target = target;
}
measure(key: string): [number, Destructor] {
if (!this.entries.has(key)) this.entries.set(key, new TrackerEntry(this.target));
return this.entries.get(key)!.measure();
}
updateLevels(): void {
for (const entry of this.entries.values()) entry.updateLevel();
}
levels(): Map<string, number> {
const levels = new Map<string, number>();
for (const [key, entry] of this.entries) levels.set(key, entry.level);
return levels;
}
}
| 0 | 0.854572 | 1 | 0.854572 | game-dev | MEDIA | 0.520231 | game-dev | 0.928992 | 1 | 0.928992 |
Dark-Basic-Software-Limited/Dark-Basic-Pro | 4,036 | Dark Basic Public Shared/Official Plugins/3D Cloth & Particles/Code/DBProPhysicsMaster/Vehicle/Suspension.cpp | #include "stdafx.h"
Suspension::Suspension(Vehicle * _parent,const Vector3 &_pos, const Vector3 &_up, const Vector3 &_fwd)
:parent(_parent),wheelObjId(-1)
{
Vector3 fwd=_fwd;
Vector3 up = _up;
fwd.Normalise();
up.Normalise();
local.setUnitY(up);
local.setUnitZ(fwd);
local.setPos(_pos);
Vector3 axle = up*fwd;
axle.Normalise();
local.setUnitX(axle);
world=local;
world.transformUsing(parent->body.World());
spring=1.0f;
damping=0.0f;
vel=0.0f;
minDist=0.0f;
dist=0.4f;
maxDist=0.4f;
weightShare=0.0f;
springForce=0.0f;
lastDist=0.4f;
wheelRotVel=0.0f;
wheelRotate=0.0f;
wheelSteer=0.0f;
perpFriction=5.0f;
brake=0.0f;
accel=0.0f;
}
extern float getGroundHeight(const Vector3 &pos, Vector3 * groundNormal, float * planeD);
void Suspension::Update()
{
world = local;
world.transformUsing(parent->body.World());
wheelBase.Set(0,-dist,0);
world.rotateAndTransV3(&wheelBase);
Vector3 widthAdj = world.unitX()*cosf(wheelSteer) - world.unitZ()*sinf(wheelSteer);
if(widthAdj.y>0) widthAdj=-widthAdj;
widthAdj*=width*0.5f;
wheelBase+=widthAdj;
Vector3 suspAxis = -world.unitY();
float planeDist;
groundHeight = getGroundHeight(wheelBase, &groundNorm, &planeDist);
isOnGround=false;
pushDist=0.0f;
lastDist=dist;
//Build in a slight tolerance
if(groundHeight+0.01f>wheelBase.y) isOnGround=true;
if(groundHeight>wheelBase.y)
{
float hdiff=0.0f;
if(suspAxis.y!=0.0f) hdiff=(groundHeight-wheelBase.y)/(float)fabs(suspAxis.y);
//These two lines take into account the suspension lying down (i.e. more force is needed to push it)
pushDist=-(hdiff+hdiff*suspAxis.y)*suspAxis.y;
hdiff=-hdiff*suspAxis.y;
//check suspension limit
if(dist-hdiff<minDist)
{
pushDist=minDist-(dist-hdiff);
hdiff-=pushDist;
}
//Set the parameters for suspension
dist -= hdiff;
vel -= hdiff*PhysicsManager::iterationFps;
}
springForce = (maxDist-dist)*spring - vel*damping;
float acc=springForce*40.0f;
vel+=acc*PhysicsManager::iterationInterval;
dist+=vel*PhysicsManager::iterationInterval;
if(dist>maxDist)
{
dist=maxDist;
}
if(dist<minDist)
{
dist=minDist;
}
vel=(dist-lastDist)*PhysicsManager::iterationFps;
//if(myid==0) consoleDebugMsg("%.4f,",world.pos().y);
//consoleDebugMsg("%.4f,%.4f",dist,vel);
//if(myid==3) consoleDebugMsg("\n");
//else consoleDebugMsg(",");
if(isOnGround)
{
Vector3 carForce = suspAxis * -springForce;
Vector3 reaction = groundNorm*groundNorm.Dot(-carForce);
carForce.x=carForce.z=0.0f;
parent->body.addForce(&carForce,WORLD,&world.pos(),WORLD);
//Remove component along suspension axis (we've effectively already applied this)
reaction -= suspAxis*suspAxis.Dot(reaction);
parent->body.addForce(&reaction,WORLD,&wheelBase,WORLD);
//Calculate world velocity at wheelbase
Vector3 localBase=wheelBase;
localBase-=parent->body.World().pos();
parent->body.invWorld().rotateV3(&localBase);
Vector3 wheelBaseVel;
parent->body.getPointWorldVel(localBase,&wheelBaseVel);
//Remove component along suspension axis
wheelBaseVel-=world.unitY()*world.unitY().Dot(wheelBaseVel);
//Don't need to normalise this result
wheelDir=world.unitX()*sinf(wheelSteer) + world.unitZ()*cosf(wheelSteer);
velPar=wheelDir*wheelDir.Dot(wheelBaseVel);
velPerp=wheelBaseVel-velPar;
wheelRotVel=wheelDir.Dot(wheelBaseVel)/radius;
}
else
{
wheelRotVel*=0.9f;
}
//Construct wheel matrix
wheelRotate+=wheelRotVel*PhysicsManager::iterationInterval;
if(isFlipped)
{
wheel.make3x3RotationMatrix(-wheelRotate,wheelSteer+3.14159265f,0,ROTATE_XYZ);
}
else
{
wheel.make3x3RotationMatrix(wheelRotate,wheelSteer,0,ROTATE_XYZ);
}
wheel.setPos(0,radius-dist,0);
wheel.transformUsing(world);
if(wheelObjId!=-1)
{
PhysicsManager::DLL_SetWorldMatrix(wheelObjId,wheel);
}
}
void Suspension::updateGraphics()
{
if(isOnGround) D3D_DebugLines::getInst()->drawCross(wheelBase,0.05f,0x0ffff0000);
else D3D_DebugLines::getInst()->drawCross(wheelBase,0.05f,0x0ff000000);
}
| 0 | 0.6144 | 1 | 0.6144 | game-dev | MEDIA | 0.901049 | game-dev | 0.987736 | 1 | 0.987736 |
mastercomfig/tf2-patches-old | 1,174 | src/game/server/portal/portal_placement.h | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#ifndef PORTAL_PLACEMENT_H
#define PORTAL_PLACEMENT_H
#ifdef _WIN32
#pragma once
#endif
struct CPortalCornerFitData;
bool FitPortalOnSurface( const CProp_Portal *pIgnorePortal, Vector &vOrigin, const Vector &vForward, const Vector &vRight,
const Vector &vTopEdge, const Vector &vBottomEdge, const Vector &vRightEdge, const Vector &vLeftEdge,
int iPlacedBy, ITraceFilter *pTraceFilterPortalShot,
int iRecursions = 0, const CPortalCornerFitData *pPortalCornerFitData = 0, const int *p_piIntersectionIndex = 0, const int *piIntersectionCount = 0 );
bool IsPortalIntersectingNoPortalVolume( const Vector &vOrigin, const QAngle &qAngles, const Vector &vForward );
bool IsPortalOverlappingOtherPortals( const CProp_Portal *pIgnorePortal, const Vector &vOrigin, const QAngle &qAngles, bool bFizzle = false );
float VerifyPortalPlacement( const CProp_Portal *pIgnorePortal, Vector &vOrigin, QAngle &qAngles, int iPlacedBy, bool bTest = false );
#endif // PORTAL_PLACEMENT_H
| 0 | 0.890859 | 1 | 0.890859 | game-dev | MEDIA | 0.391279 | game-dev | 0.500531 | 1 | 0.500531 |
Hexorg/CheatEngineTables | 1,792 | tables/i_wanna_be_the_shrine_maiden_2_123.ct | <?xml version="1.0"?>
<CheatTable CheatEngineTableVersion="10">
<CheatEntries>
<CheatEntry>
<Description>"God mode"</Description>
<Color>80000008</Color>
<VariableType>Auto Assembler Script</VariableType>
<AssemblerScript>//Made by Geri with Cheat Engine 6.0
//12th April, 2011
//All rights reserved. You are not allowed to use these scripts to create Your own trainer without my permission.
//Contact e-mail: trainers4free@gmail.com
[ENABLE]
//code from here to '[DISABLE]' will be used to enable the cheat
alloc(newmem2,2048) //2kb should be enough
label(returnhere2)
label(originalcode2)
label(exit2)
globalalloc(playerbase,4)
newmem2: //this is allocated memory, you have read,write,execute access
mov [playerbase],edi
originalcode2:
fld qword ptr [edi+10]
add esp,F4
exit2:
jmp returnhere2
"I Wanna be the Shrine Maiden 2.exe"+154B29:
jmp newmem2
nop
returnhere2:
alloc(newmem,2048) //2kb should be enough
label(returnhere)
label(originalcode)
label(exit)
newmem: //this is allocated memory, you have read,write,execute access
pushfd
cmp [playerbase],ebx
jne originalcode
popfd
jmp 004AD301
originalcode:
popfd
je 004AD301
exit:
jmp returnhere
"I Wanna be the Shrine Maiden 2.exe"+AD27A:
jmp newmem
nop
returnhere:
[DISABLE]
//code from here till the end of the code will be used to disable the cheat
dealloc(newmem2)
"I Wanna be the Shrine Maiden 2.exe"+154B29:
fld qword ptr [edi+10]
add esp,F4
//Alt: db DD 47 10 83 C4 F4
dealloc(newmem)
"I Wanna be the Shrine Maiden 2.exe"+AD27A:
je 004AD301
//Alt: db 0F 84 81 00 00 00
</AssemblerScript>
</CheatEntry>
</CheatEntries>
<UserdefinedSymbols>
<SymbolEntry>
<Name>playerbase</Name>
<Address>01040000</Address>
</SymbolEntry>
</UserdefinedSymbols>
</CheatTable>
| 0 | 0.542913 | 1 | 0.542913 | game-dev | MEDIA | 0.660723 | game-dev,testing-qa | 0.530302 | 1 | 0.530302 |
CICM/HoaLibrary | 4,315 | ThirdParty/JuceModules/juce_box2d/box2d/Collision/Shapes/b2ChainShape.cpp | /*
* Copyright (c) 2006-2010 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#include "b2ChainShape.h"
#include "b2EdgeShape.h"
#include <new>
#include <cstring>
using namespace std;
b2ChainShape::~b2ChainShape()
{
b2Free(m_vertices);
m_vertices = NULL;
m_count = 0;
}
void b2ChainShape::CreateLoop(const b2Vec2* vertices, int32 count)
{
b2Assert(m_vertices == NULL && m_count == 0);
b2Assert(count >= 3);
m_count = count + 1;
m_vertices = (b2Vec2*)b2Alloc(m_count * sizeof(b2Vec2));
memcpy(m_vertices, vertices, count * sizeof(b2Vec2));
m_vertices[count] = m_vertices[0];
m_prevVertex = m_vertices[m_count - 2];
m_nextVertex = m_vertices[1];
m_hasPrevVertex = true;
m_hasNextVertex = true;
}
void b2ChainShape::CreateChain(const b2Vec2* vertices, int32 count)
{
b2Assert(m_vertices == NULL && m_count == 0);
b2Assert(count >= 2);
m_count = count;
m_vertices = (b2Vec2*)b2Alloc(count * sizeof(b2Vec2));
memcpy(m_vertices, vertices, m_count * sizeof(b2Vec2));
m_hasPrevVertex = false;
m_hasNextVertex = false;
}
void b2ChainShape::SetPrevVertex(const b2Vec2& prevVertex)
{
m_prevVertex = prevVertex;
m_hasPrevVertex = true;
}
void b2ChainShape::SetNextVertex(const b2Vec2& nextVertex)
{
m_nextVertex = nextVertex;
m_hasNextVertex = true;
}
b2Shape* b2ChainShape::Clone(b2BlockAllocator* allocator) const
{
void* mem = allocator->Allocate(sizeof(b2ChainShape));
b2ChainShape* clone = new (mem) b2ChainShape;
clone->CreateChain(m_vertices, m_count);
clone->m_prevVertex = m_prevVertex;
clone->m_nextVertex = m_nextVertex;
clone->m_hasPrevVertex = m_hasPrevVertex;
clone->m_hasNextVertex = m_hasNextVertex;
return clone;
}
int32 b2ChainShape::GetChildCount() const
{
// edge count = vertex count - 1
return m_count - 1;
}
void b2ChainShape::GetChildEdge(b2EdgeShape* edge, int32 index) const
{
b2Assert(0 <= index && index < m_count - 1);
edge->m_type = b2Shape::e_edge;
edge->m_radius = m_radius;
edge->m_vertex1 = m_vertices[index + 0];
edge->m_vertex2 = m_vertices[index + 1];
if (index > 0)
{
edge->m_vertex0 = m_vertices[index - 1];
edge->m_hasVertex0 = true;
}
else
{
edge->m_vertex0 = m_prevVertex;
edge->m_hasVertex0 = m_hasPrevVertex;
}
if (index < m_count - 2)
{
edge->m_vertex3 = m_vertices[index + 2];
edge->m_hasVertex3 = true;
}
else
{
edge->m_vertex3 = m_nextVertex;
edge->m_hasVertex3 = m_hasNextVertex;
}
}
bool b2ChainShape::TestPoint(const b2Transform& xf, const b2Vec2& p) const
{
B2_NOT_USED(xf);
B2_NOT_USED(p);
return false;
}
bool b2ChainShape::RayCast(b2RayCastOutput* output, const b2RayCastInput& input,
const b2Transform& xf, int32 childIndex) const
{
b2Assert(childIndex < m_count);
b2EdgeShape edgeShape;
int32 i1 = childIndex;
int32 i2 = childIndex + 1;
if (i2 == m_count)
{
i2 = 0;
}
edgeShape.m_vertex1 = m_vertices[i1];
edgeShape.m_vertex2 = m_vertices[i2];
return edgeShape.RayCast(output, input, xf, 0);
}
void b2ChainShape::ComputeAABB(b2AABB* aabb, const b2Transform& xf, int32 childIndex) const
{
b2Assert(childIndex < m_count);
int32 i1 = childIndex;
int32 i2 = childIndex + 1;
if (i2 == m_count)
{
i2 = 0;
}
b2Vec2 v1 = b2Mul(xf, m_vertices[i1]);
b2Vec2 v2 = b2Mul(xf, m_vertices[i2]);
aabb->lowerBound = b2Min(v1, v2);
aabb->upperBound = b2Max(v1, v2);
}
void b2ChainShape::ComputeMass(b2MassData* massData, float32 density) const
{
B2_NOT_USED(density);
massData->mass = 0.0f;
massData->center.SetZero();
massData->I = 0.0f;
}
| 0 | 0.897949 | 1 | 0.897949 | game-dev | MEDIA | 0.846872 | game-dev | 0.99381 | 1 | 0.99381 |
b3agz/Code-A-Game-Like-Minecraft-In-Unity | 14,799 | 23-fancy-clouds/Assets/Scripts/World.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Threading;
using System.IO;
public class World : MonoBehaviour {
public Settings settings;
[Header("World Generation Values")]
public BiomeAttributes[] biomes;
[Range(0f, 1f)]
public float globalLightLevel;
public Color day;
public Color night;
public Transform player;
public Vector3 spawnPosition;
public Material material;
public Material transparentMaterial;
public BlockType[] blocktypes;
Chunk[,] chunks = new Chunk[VoxelData.WorldSizeInChunks, VoxelData.WorldSizeInChunks];
List<ChunkCoord> activeChunks = new List<ChunkCoord>();
public ChunkCoord playerChunkCoord;
ChunkCoord playerLastChunkCoord;
List<ChunkCoord> chunksToCreate = new List<ChunkCoord>();
public List<Chunk> chunksToUpdate = new List<Chunk>();
public Queue<Chunk> chunksToDraw = new Queue<Chunk>();
bool applyingModifications = false;
Queue<Queue<VoxelMod>> modifications = new Queue<Queue<VoxelMod>>();
private bool _inUI = false;
public Clouds clouds;
public GameObject debugScreen;
public GameObject creativeInventoryWindow;
public GameObject cursorSlot;
Thread ChunkUpdateThread;
public object ChunkUpdateThreadLock = new object();
private void Start() {
Debug.Log("Generating new world using seed " + VoxelData.seed);
//string jsonExport = JsonUtility.ToJson(settings);
//Debug.Log(jsonExport);
//File.WriteAllText(Application.dataPath + "/settings.cfg", jsonExport);
string jsonImport = File.ReadAllText(Application.dataPath + "/settings.cfg");
settings = JsonUtility.FromJson<Settings>(jsonImport);
Random.InitState(VoxelData.seed);
Shader.SetGlobalFloat("minGlobalLightLevel", VoxelData.minLightLevel);
Shader.SetGlobalFloat("maxGlobalLightLevel", VoxelData.maxLightLevel);
if (settings.enableThreading) {
ChunkUpdateThread = new Thread(new ThreadStart(ThreadedUpdate));
ChunkUpdateThread.Start();
}
SetGlobalLightValue();
spawnPosition = new Vector3(VoxelData.WorldCentre, VoxelData.ChunkHeight - 50f, VoxelData.WorldCentre);
GenerateWorld();
playerLastChunkCoord = GetChunkCoordFromVector3(player.position);
}
public void SetGlobalLightValue () {
Shader.SetGlobalFloat("GlobalLightLevel", globalLightLevel);
Camera.main.backgroundColor = Color.Lerp(night, day, globalLightLevel);
}
private void Update() {
playerChunkCoord = GetChunkCoordFromVector3(player.position);
// Only update the chunks if the player has moved from the chunk they were previously on.
if (!playerChunkCoord.Equals(playerLastChunkCoord))
CheckViewDistance();
if (chunksToCreate.Count > 0)
CreateChunk();
if (chunksToDraw.Count > 0) {
if (chunksToDraw.Peek().isEditable)
chunksToDraw.Dequeue().CreateMesh();
}
if (!settings.enableThreading) {
if (!applyingModifications)
ApplyModifications();
if (chunksToUpdate.Count > 0)
UpdateChunks();
}
if (Input.GetKeyDown(KeyCode.F3))
debugScreen.SetActive(!debugScreen.activeSelf);
}
void GenerateWorld () {
for (int x = (VoxelData.WorldSizeInChunks / 2) - settings.viewDistance; x < (VoxelData.WorldSizeInChunks / 2) + settings.viewDistance; x++) {
for (int z = (VoxelData.WorldSizeInChunks / 2) - settings.viewDistance; z < (VoxelData.WorldSizeInChunks / 2) + settings.viewDistance; z++) {
ChunkCoord newChunk = new ChunkCoord(x, z);
chunks[x, z] = new Chunk(newChunk, this);
chunksToCreate.Add(newChunk);
}
}
player.position = spawnPosition;
CheckViewDistance();
}
void CreateChunk () {
ChunkCoord c = chunksToCreate[0];
chunksToCreate.RemoveAt(0);
chunks[c.x, c.z].Init();
}
void UpdateChunks () {
bool updated = false;
int index = 0;
lock (ChunkUpdateThreadLock) {
while (!updated && index < chunksToUpdate.Count - 1) {
if (chunksToUpdate[index].isEditable) {
chunksToUpdate[index].UpdateChunk();
if (!activeChunks.Contains(chunksToUpdate[index].coord))
activeChunks.Add(chunksToUpdate[index].coord);
chunksToUpdate.RemoveAt(index);
updated = true;
} else
index++;
}
}
}
void ThreadedUpdate() {
while (true) {
if (!applyingModifications)
ApplyModifications();
if (chunksToUpdate.Count > 0)
UpdateChunks();
}
}
private void OnDisable() {
if (settings.enableThreading) {
ChunkUpdateThread.Abort();
}
}
void ApplyModifications () {
applyingModifications = true;
while (modifications.Count > 0) {
Queue<VoxelMod> queue = modifications.Dequeue();
while (queue.Count > 0) {
VoxelMod v = queue.Dequeue();
ChunkCoord c = GetChunkCoordFromVector3(v.position);
if (chunks[c.x, c.z] == null) {
chunks[c.x, c.z] = new Chunk(c, this);
chunksToCreate.Add(c);
}
chunks[c.x, c.z].modifications.Enqueue(v);
}
}
applyingModifications = false;
}
ChunkCoord GetChunkCoordFromVector3 (Vector3 pos) {
int x = Mathf.FloorToInt(pos.x / VoxelData.ChunkWidth);
int z = Mathf.FloorToInt(pos.z / VoxelData.ChunkWidth);
return new ChunkCoord(x, z);
}
public Chunk GetChunkFromVector3 (Vector3 pos) {
int x = Mathf.FloorToInt(pos.x / VoxelData.ChunkWidth);
int z = Mathf.FloorToInt(pos.z / VoxelData.ChunkWidth);
return chunks[x, z];
}
void CheckViewDistance () {
clouds.UpdateClouds();
ChunkCoord coord = GetChunkCoordFromVector3(player.position);
playerLastChunkCoord = playerChunkCoord;
List<ChunkCoord> previouslyActiveChunks = new List<ChunkCoord>(activeChunks);
activeChunks.Clear();
// Loop through all chunks currently within view distance of the player.
for (int x = coord.x - settings.viewDistance; x < coord.x + settings.viewDistance; x++) {
for (int z = coord.z - settings.viewDistance; z < coord.z + settings.viewDistance; z++) {
ChunkCoord thisChunkCoord = new ChunkCoord(x, z);
// If the current chunk is in the world...
if (IsChunkInWorld (thisChunkCoord)) {
// Check if it active, if not, activate it.
if (chunks[x, z] == null) {
chunks[x, z] = new Chunk(thisChunkCoord, this);
chunksToCreate.Add(thisChunkCoord);
} else if (!chunks[x, z].isActive) {
chunks[x, z].isActive = true;
}
activeChunks.Add(thisChunkCoord);
}
// Check through previously active chunks to see if this chunk is there. If it is, remove it from the list.
for (int i = 0; i < previouslyActiveChunks.Count; i++) {
if (previouslyActiveChunks[i].Equals(thisChunkCoord))
previouslyActiveChunks.RemoveAt(i);
}
}
}
// Any chunks left in the previousActiveChunks list are no longer in the player's view distance, so loop through and disable them.
foreach (ChunkCoord c in previouslyActiveChunks)
chunks[c.x, c.z].isActive = false;
}
public bool CheckForVoxel (Vector3 pos) {
ChunkCoord thisChunk = new ChunkCoord(pos);
if (!IsChunkInWorld(thisChunk) || pos.y < 0 || pos.y > VoxelData.ChunkHeight)
return false;
if (chunks[thisChunk.x, thisChunk.z] != null && chunks[thisChunk.x, thisChunk.z].isEditable)
return blocktypes[chunks[thisChunk.x, thisChunk.z].GetVoxelFromGlobalVector3(pos).id].isSolid;
return blocktypes[GetVoxel(pos)].isSolid;
}
public VoxelState GetVoxelState (Vector3 pos) {
ChunkCoord thisChunk = new ChunkCoord(pos);
if (!IsChunkInWorld(thisChunk) || pos.y < 0 || pos.y > VoxelData.ChunkHeight)
return null;
if (chunks[thisChunk.x, thisChunk.z] != null && chunks[thisChunk.x, thisChunk.z].isEditable)
return chunks[thisChunk.x, thisChunk.z].GetVoxelFromGlobalVector3(pos);
return new VoxelState(GetVoxel(pos));
}
public bool inUI {
get { return _inUI; }
set {
_inUI = value;
if (_inUI) {
Cursor.lockState = CursorLockMode.None;
Cursor.visible = true;
creativeInventoryWindow.SetActive(true);
cursorSlot.SetActive(true);
} else {
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
creativeInventoryWindow.SetActive(false);
cursorSlot.SetActive(false);
}
}
}
public byte GetVoxel (Vector3 pos) {
int yPos = Mathf.FloorToInt(pos.y);
/* IMMUTABLE PASS */
// If outside world, return air.
if (!IsVoxelInWorld(pos))
return 0;
// If bottom block of chunk, return bedrock.
if (yPos == 0)
return 1;
/* BIOME SELECTION PASS*/
int solidGroundHeight = 42;
float sumOfHeights = 0f;
int count = 0;
float strongestWeight = 0f;
int strongestBiomeIndex = 0;
for (int i = 0; i < biomes.Length; i++) {
float weight = Noise.Get2DPerlin(new Vector2(pos.x, pos.z), biomes[i].offset, biomes[i].scale);
// Keep track of which weight is strongest.
if (weight > strongestWeight) {
strongestWeight = weight;
strongestBiomeIndex = i;
}
// Get the height of the terrain (for the current biome) and multiply it by its weight.
float height = biomes[i].terrainHeight * Noise.Get2DPerlin(new Vector2(pos.x, pos.z), 0, biomes[i].terrainScale) * weight;
// If the height value is greater 0 add it to the sum of heights.
if (height > 0) {
sumOfHeights += height;
count++;
}
}
// Set biome to the one with the strongest weight.
BiomeAttributes biome = biomes[strongestBiomeIndex];
// Get the average of the heights.
sumOfHeights /= count;
int terrainHeight = Mathf.FloorToInt(sumOfHeights + solidGroundHeight);
//BiomeAttributes biome = biomes[index];
/* BASIC TERRAIN PASS */
byte voxelValue = 0;
if (yPos == terrainHeight)
voxelValue = biome.surfaceBlock;
else if (yPos < terrainHeight && yPos > terrainHeight - 4)
voxelValue = biome.subSurfaceBlock;
else if (yPos > terrainHeight)
return 0;
else
voxelValue = 2;
/* SECOND PASS */
if (voxelValue == 2) {
foreach (Lode lode in biome.lodes) {
if (yPos > lode.minHeight && yPos < lode.maxHeight)
if (Noise.Get3DPerlin(pos, lode.noiseOffset, lode.scale, lode.threshold))
voxelValue = lode.blockID;
}
}
/* TREE PASS */
if (yPos == terrainHeight && biome.placeMajorFlora) {
if (Noise.Get2DPerlin(new Vector2(pos.x, pos.z), 0, biome.majorFloraZoneScale) > biome.majorFloraZoneThreshold) {
if (Noise.Get2DPerlin(new Vector2(pos.x, pos.z), 0, biome.majorFloraPlacementScale) > biome.majorFloraPlacementThreshold) {
modifications.Enqueue(Structure.GenerateMajorFlora(biome.majorFloraIndex, pos, biome.minHeight, biome.maxHeight));
}
}
}
return voxelValue;
}
bool IsChunkInWorld (ChunkCoord coord) {
if (coord.x > 0 && coord.x < VoxelData.WorldSizeInChunks - 1 && coord.z > 0 && coord.z < VoxelData.WorldSizeInChunks - 1)
return true;
else
return
false;
}
bool IsVoxelInWorld (Vector3 pos) {
if (pos.x >= 0 && pos.x < VoxelData.WorldSizeInVoxels && pos.y >= 0 && pos.y < VoxelData.ChunkHeight && pos.z >= 0 && pos.z < VoxelData.WorldSizeInVoxels)
return true;
else
return false;
}
}
[System.Serializable]
public class BlockType {
public string blockName;
public bool isSolid;
public bool renderNeighborFaces;
public float transparency;
public Sprite icon;
[Header("Texture Values")]
public int backFaceTexture;
public int frontFaceTexture;
public int topFaceTexture;
public int bottomFaceTexture;
public int leftFaceTexture;
public int rightFaceTexture;
// Back, Front, Top, Bottom, Left, Right
public int GetTextureID (int faceIndex) {
switch (faceIndex) {
case 0:
return backFaceTexture;
case 1:
return frontFaceTexture;
case 2:
return topFaceTexture;
case 3:
return bottomFaceTexture;
case 4:
return leftFaceTexture;
case 5:
return rightFaceTexture;
default:
Debug.Log("Error in GetTextureID; invalid face index");
return 0;
}
}
}
public class VoxelMod {
public Vector3 position;
public byte id;
public VoxelMod () {
position = new Vector3();
id = 0;
}
public VoxelMod (Vector3 _position, byte _id) {
position = _position;
id = _id;
}
}
[System.Serializable]
public class Settings {
[Header("Game Data")]
public string version = "0.0.0.01";
[Header("Performance")]
public int viewDistance = 8;
public bool enableThreading = true;
public CloudStyle clouds = CloudStyle.Fast;
public bool enableAnimatedChunks = false;
[Header("Controls")]
[Range(0.1f, 10f)]
public float mouseSensitivity = 2.0f;
}
| 0 | 0.888664 | 1 | 0.888664 | game-dev | MEDIA | 0.83687 | game-dev | 0.938997 | 1 | 0.938997 |
dfelinto/blender | 9,864 | extern/mantaflow/preprocessed/levelset.h |
// DO NOT EDIT !
// This file is generated using the MantaFlow preprocessor (prep generate).
/******************************************************************************
*
* MantaFlow fluid solver framework
* Copyright 2011 Tobias Pfaff, Nils Thuerey
*
* This program is free software, distributed under the terms of the
* Apache License, Version 2.0
* http://www.apache.org/licenses/LICENSE-2.0
*
* Levelset
*
******************************************************************************/
#ifndef _LEVELSET_H_
#define _LEVELSET_H_
#include "grid.h"
namespace Manta {
class Mesh;
//! Special function for levelsets
class LevelsetGrid : public Grid<Real> {
public:
LevelsetGrid(FluidSolver *parent, bool show = true);
static int _W_0(PyObject *_self, PyObject *_linargs, PyObject *_kwds)
{
PbClass *obj = Pb::objFromPy(_self);
if (obj)
delete obj;
try {
PbArgs _args(_linargs, _kwds);
bool noTiming = _args.getOpt<bool>("notiming", -1, 0);
pbPreparePlugin(0, "LevelsetGrid::LevelsetGrid", !noTiming);
{
ArgLocker _lock;
FluidSolver *parent = _args.getPtr<FluidSolver>("parent", 0, &_lock);
bool show = _args.getOpt<bool>("show", 1, true, &_lock);
obj = new LevelsetGrid(parent, show);
obj->registerObject(_self, &_args);
_args.check();
}
pbFinalizePlugin(obj->getParent(), "LevelsetGrid::LevelsetGrid", !noTiming);
return 0;
}
catch (std::exception &e) {
pbSetError("LevelsetGrid::LevelsetGrid", e.what());
return -1;
}
}
LevelsetGrid(FluidSolver *parent, Real *data, bool show = true);
//! reconstruct the levelset using fast marching
void reinitMarching(const FlagGrid &flags,
Real maxTime = 4.0,
MACGrid *velTransport = nullptr,
bool ignoreWalls = false,
bool correctOuterLayer = true,
int obstacleType = FlagGrid::TypeObstacle);
static PyObject *_W_1(PyObject *_self, PyObject *_linargs, PyObject *_kwds)
{
try {
PbArgs _args(_linargs, _kwds);
LevelsetGrid *pbo = dynamic_cast<LevelsetGrid *>(Pb::objFromPy(_self));
bool noTiming = _args.getOpt<bool>("notiming", -1, 0);
pbPreparePlugin(pbo->getParent(), "LevelsetGrid::reinitMarching", !noTiming);
PyObject *_retval = nullptr;
{
ArgLocker _lock;
const FlagGrid &flags = *_args.getPtr<FlagGrid>("flags", 0, &_lock);
Real maxTime = _args.getOpt<Real>("maxTime", 1, 4.0, &_lock);
MACGrid *velTransport = _args.getPtrOpt<MACGrid>("velTransport", 2, nullptr, &_lock);
bool ignoreWalls = _args.getOpt<bool>("ignoreWalls", 3, false, &_lock);
bool correctOuterLayer = _args.getOpt<bool>("correctOuterLayer", 4, true, &_lock);
int obstacleType = _args.getOpt<int>("obstacleType", 5, FlagGrid::TypeObstacle, &_lock);
pbo->_args.copy(_args);
_retval = getPyNone();
pbo->reinitMarching(
flags, maxTime, velTransport, ignoreWalls, correctOuterLayer, obstacleType);
pbo->_args.check();
}
pbFinalizePlugin(pbo->getParent(), "LevelsetGrid::reinitMarching", !noTiming);
return _retval;
}
catch (std::exception &e) {
pbSetError("LevelsetGrid::reinitMarching", e.what());
return 0;
}
}
//! create a triangle mesh from the levelset isosurface
void createMesh(Mesh &mesh);
static PyObject *_W_2(PyObject *_self, PyObject *_linargs, PyObject *_kwds)
{
try {
PbArgs _args(_linargs, _kwds);
LevelsetGrid *pbo = dynamic_cast<LevelsetGrid *>(Pb::objFromPy(_self));
bool noTiming = _args.getOpt<bool>("notiming", -1, 0);
pbPreparePlugin(pbo->getParent(), "LevelsetGrid::createMesh", !noTiming);
PyObject *_retval = nullptr;
{
ArgLocker _lock;
Mesh &mesh = *_args.getPtr<Mesh>("mesh", 0, &_lock);
pbo->_args.copy(_args);
_retval = getPyNone();
pbo->createMesh(mesh);
pbo->_args.check();
}
pbFinalizePlugin(pbo->getParent(), "LevelsetGrid::createMesh", !noTiming);
return _retval;
}
catch (std::exception &e) {
pbSetError("LevelsetGrid::createMesh", e.what());
return 0;
}
}
//! union with another levelset
void join(const LevelsetGrid &o);
static PyObject *_W_3(PyObject *_self, PyObject *_linargs, PyObject *_kwds)
{
try {
PbArgs _args(_linargs, _kwds);
LevelsetGrid *pbo = dynamic_cast<LevelsetGrid *>(Pb::objFromPy(_self));
bool noTiming = _args.getOpt<bool>("notiming", -1, 0);
pbPreparePlugin(pbo->getParent(), "LevelsetGrid::join", !noTiming);
PyObject *_retval = nullptr;
{
ArgLocker _lock;
const LevelsetGrid &o = *_args.getPtr<LevelsetGrid>("o", 0, &_lock);
pbo->_args.copy(_args);
_retval = getPyNone();
pbo->join(o);
pbo->_args.check();
}
pbFinalizePlugin(pbo->getParent(), "LevelsetGrid::join", !noTiming);
return _retval;
}
catch (std::exception &e) {
pbSetError("LevelsetGrid::join", e.what());
return 0;
}
}
void subtract(const LevelsetGrid &o,
const FlagGrid *flags = nullptr,
const int subtractType = 0);
static PyObject *_W_4(PyObject *_self, PyObject *_linargs, PyObject *_kwds)
{
try {
PbArgs _args(_linargs, _kwds);
LevelsetGrid *pbo = dynamic_cast<LevelsetGrid *>(Pb::objFromPy(_self));
bool noTiming = _args.getOpt<bool>("notiming", -1, 0);
pbPreparePlugin(pbo->getParent(), "LevelsetGrid::subtract", !noTiming);
PyObject *_retval = nullptr;
{
ArgLocker _lock;
const LevelsetGrid &o = *_args.getPtr<LevelsetGrid>("o", 0, &_lock);
const FlagGrid *flags = _args.getPtrOpt<FlagGrid>("flags", 1, nullptr, &_lock);
const int subtractType = _args.getOpt<int>("subtractType", 2, 0, &_lock);
pbo->_args.copy(_args);
_retval = getPyNone();
pbo->subtract(o, flags, subtractType);
pbo->_args.check();
}
pbFinalizePlugin(pbo->getParent(), "LevelsetGrid::subtract", !noTiming);
return _retval;
}
catch (std::exception &e) {
pbSetError("LevelsetGrid::subtract", e.what());
return 0;
}
}
//! initialize levelset from flags (+/- 0.5 heaviside)
void initFromFlags(const FlagGrid &flags, bool ignoreWalls = false);
static PyObject *_W_5(PyObject *_self, PyObject *_linargs, PyObject *_kwds)
{
try {
PbArgs _args(_linargs, _kwds);
LevelsetGrid *pbo = dynamic_cast<LevelsetGrid *>(Pb::objFromPy(_self));
bool noTiming = _args.getOpt<bool>("notiming", -1, 0);
pbPreparePlugin(pbo->getParent(), "LevelsetGrid::initFromFlags", !noTiming);
PyObject *_retval = nullptr;
{
ArgLocker _lock;
const FlagGrid &flags = *_args.getPtr<FlagGrid>("flags", 0, &_lock);
bool ignoreWalls = _args.getOpt<bool>("ignoreWalls", 1, false, &_lock);
pbo->_args.copy(_args);
_retval = getPyNone();
pbo->initFromFlags(flags, ignoreWalls);
pbo->_args.check();
}
pbFinalizePlugin(pbo->getParent(), "LevelsetGrid::initFromFlags", !noTiming);
return _retval;
}
catch (std::exception &e) {
pbSetError("LevelsetGrid::initFromFlags", e.what());
return 0;
}
}
//! fill holes (pos cells enclosed by neg ones) up to given size with -0.5 (ie not preserving
//! sdf)
void fillHoles(int maxDepth = 10, int boundaryWidth = 1);
static PyObject *_W_6(PyObject *_self, PyObject *_linargs, PyObject *_kwds)
{
try {
PbArgs _args(_linargs, _kwds);
LevelsetGrid *pbo = dynamic_cast<LevelsetGrid *>(Pb::objFromPy(_self));
bool noTiming = _args.getOpt<bool>("notiming", -1, 0);
pbPreparePlugin(pbo->getParent(), "LevelsetGrid::fillHoles", !noTiming);
PyObject *_retval = nullptr;
{
ArgLocker _lock;
int maxDepth = _args.getOpt<int>("maxDepth", 0, 10, &_lock);
int boundaryWidth = _args.getOpt<int>("boundaryWidth", 1, 1, &_lock);
pbo->_args.copy(_args);
_retval = getPyNone();
pbo->fillHoles(maxDepth, boundaryWidth);
pbo->_args.check();
}
pbFinalizePlugin(pbo->getParent(), "LevelsetGrid::fillHoles", !noTiming);
return _retval;
}
catch (std::exception &e) {
pbSetError("LevelsetGrid::fillHoles", e.what());
return 0;
}
}
//! flood-fill the levelset to ensure that closed obstacles are filled inside
void floodFill(const Real value = -0.5, const bool outside = true, const int boundaryWidth = 1);
static PyObject *_W_7(PyObject *_self, PyObject *_linargs, PyObject *_kwds)
{
try {
PbArgs _args(_linargs, _kwds);
LevelsetGrid *pbo = dynamic_cast<LevelsetGrid *>(Pb::objFromPy(_self));
bool noTiming = _args.getOpt<bool>("notiming", -1, 0);
pbPreparePlugin(pbo->getParent(), "LevelsetGrid::floodFill", !noTiming);
PyObject *_retval = nullptr;
{
ArgLocker _lock;
const Real value = _args.getOpt<Real>("value", 0, -0.5, &_lock);
const bool outside = _args.getOpt<bool>("outside", 1, true, &_lock);
const int boundaryWidth = _args.getOpt<int>("boundaryWidth", 2, 1, &_lock);
pbo->_args.copy(_args);
_retval = getPyNone();
pbo->floodFill(value, outside, boundaryWidth);
pbo->_args.check();
}
pbFinalizePlugin(pbo->getParent(), "LevelsetGrid::floodFill", !noTiming);
return _retval;
}
catch (std::exception &e) {
pbSetError("LevelsetGrid::floodFill", e.what());
return 0;
}
}
static Real invalidTimeValue();
public:
PbArgs _args;
}
#define _C_LevelsetGrid
;
} // namespace Manta
#endif
| 0 | 0.609275 | 1 | 0.609275 | game-dev | MEDIA | 0.603784 | game-dev | 0.760236 | 1 | 0.760236 |
UCRBrainGameCenter/BGC_Tools | 2,899 | Utility/NewInput/NewTouchDeltaTimeHelper.cs | using System.Collections.Generic;
using UnityEngine;
#if ENABLE_INPUT_SYSTEM
using UnityEngine.InputSystem;
#endif
/// <summary>
/// A singleton MonoBehaviour that tracks touch events to calculate a precise
/// deltaTime for each touch, similar to the old input system's Touch.deltaTime.
/// </summary>
public class NewTouchDeltaTimeHelper : MonoBehaviour
{
private static NewTouchDeltaTimeHelper _instance;
public static NewTouchDeltaTimeHelper Instance
{
get
{
if (_instance == null)
{
_instance = FindAnyObjectByType<NewTouchDeltaTimeHelper>();
if (_instance == null)
{
var go = new GameObject(nameof(NewTouchDeltaTimeHelper));
DontDestroyOnLoad(go);
_instance = go.AddComponent<NewTouchDeltaTimeHelper>();
}
}
return _instance;
}
private set => _instance = value;
}
private readonly Dictionary<int, double> _touchIdToLastTime = new();
private readonly Dictionary<int, float> _touchIdToDeltaTime = new();
private void Awake()
{
if (Instance != null && Instance != this)
{
Destroy(gameObject);
return;
}
Instance = this;
}
#if ENABLE_INPUT_SYSTEM
private void Update()
{
if (Touchscreen.current == null) return;
_touchIdToDeltaTime.Clear();
foreach (var touch in Touchscreen.current.touches)
{
var phase = touch.phase.ReadValue();
if (phase == UnityEngine.InputSystem.TouchPhase.None) continue;
int touchId = touch.touchId.ReadValue();
double lastTime;
double currentUpdateTime = Touchscreen.current.lastUpdateTime; // TODO: test that this is equal to old touch system
if (_touchIdToLastTime.TryGetValue(touchId, out lastTime))
{
float deltaTime = (float)(currentUpdateTime - lastTime);
_touchIdToDeltaTime[touchId] = deltaTime;
}
_touchIdToLastTime[touchId] = currentUpdateTime;
if (phase == UnityEngine.InputSystem.TouchPhase.Ended || phase == UnityEngine.InputSystem.TouchPhase.Canceled)
{
_touchIdToLastTime.Remove(touchId);
}
}
}
#endif
/// <summary>
/// Gets the calculated delta time for a specific finger for the current frame.
/// </summary>
/// <param name="touchId">The unique ID of the touch.</param>
/// <returns>The calculated delta time, or 0 if this is the first frame of the touch.</returns>
public float GetDeltaTimeForTouch(int touchId)
{
float deltaTime = 0.0f;
_touchIdToDeltaTime.TryGetValue(touchId, out deltaTime);
return deltaTime; // Returns 0.0f if not found
}
}
| 0 | 0.819421 | 1 | 0.819421 | game-dev | MEDIA | 0.565713 | game-dev,mobile | 0.935237 | 1 | 0.935237 |
sezero/uhexen2 | 19,881 | gamecode/hc/siege/entity.hc | //**************************************************************************
//** entity.hc
//**************************************************************************
// SYSTEM FIELDS -----------------------------------------------------------
// (entvars_t C structure, *** = don't modify in HexC) ---------------------
// *** Model index in the precached list.
.float modelindex;
// *** Origin + mins / maxs
.vector absmin, absmax;
// Local time for entity.
.float ltime;
.float lastruntime; // *** to allow entities to run out of sequence
.float movetype;
.float solid;
// ***
.vector origin;
// ***
.vector oldorigin;
.vector velocity;
.vector angles;
.vector avelocity;
// Temp angle adjust from damage or recoil.
.vector punchangle;
// Spawn function.
.string classname;
.string model;
.float frame;
.float skin;
.float effects;
.float scale;
.float drawflags;
.float abslight;
// Bounding box extents relative to origin.
.vector mins, maxs;
// maxs - mins
.vector size;
// Which clipping hull to use.
.float hull;
.void() touch;
.void() use;
.void() think;
// For doors or plats, called when can't push other.
.void() blocked;
.float nextthink;
.entity groundentity;
// Stats
.float stats_restored;
.float frags;
.float weapon;
.string weaponmodel;
.float weaponframe;
.float health; // HP
.float max_health; // Max HP
.float playerclass; // 0 (none), 1-6
.float next_playerclass; // 0 (none), 1-6
.float has_portals; // 1 if user has portals expansion
.float bluemana; // Blue mana
.float greenmana; // Green mana
.float max_mana; // Maximum amount of mana for current class / level
.float armor_amulet; // Health of amulet armor
.float armor_bracer; // Health of bracer armor
.float armor_breastplate; // Health of breastplate armor
.float armor_helmet; // Health of helmet armor
.float level; // Player level
.float intelligence; // Player INT
.float wisdom; // Player WIS
.float dexterity; // Player DEX
.float strength; // Player STR
.float experience; // Accumulated experience points
.float ring_flight; // Health of rings 0 - 100
.float ring_water; //
.float ring_turning; //
.float ring_regeneration; //
.float haste_time; // When hast is depleted
.float tome_time; // When tome of power is depleted
.string puzzle_inv1; // Puzzle piece inventory...
.string puzzle_inv2;
.string puzzle_inv3;
.string puzzle_inv4;
.string puzzle_inv5;
.string puzzle_inv6;
.string puzzle_inv7;
.string puzzle_inv8;
// Experience this entity is worth when killed or used.
.float experience_value;
// Bit flags.
.float items;
.float takedamage;
.entity chain;
.float deadflag;
// Add to origin to get eye point.
.vector view_ofs;
// Fire.
.float button0;
// Use.
.float button1;
// Jump.
.float button2;
// Weapon changes, misc.
.float impulse;
.float fixangle;
// View / targeting angle for players.
.vector v_angle;
// Calculated pitch angle for slopes.
.float idealpitch;
.float idealroll;
.float hoverz;
.string netname;
.entity enemy;
.float flags;
.float flags2;
.float artifact_flags;
.float colormap;
.float team;
.float light_level;
.float wpn_sound;
.float targAng;
.float targPitch;
.float targDist;
// Don't back up.
.float teleport_time;
// Save this fraction of incoming damage.
.float armortype;
.float armorvalue;
// 0 = not in, 1 = feet, 2 = waist, 3 = eyes.
.float waterlevel;
// A contents value.
.float watertype;
// 0 = not in a friction entity, else the friction of the entity.
.float friction;
.float ideal_yaw;
.float yaw_speed;
//rj.entity aiment;
// A pathentity or an enemy. also used by axeblade for it's tail
.entity goalentity;
.float spawnflags;
// The target of this entity.
.string target;
.string targetname;
// Damage is accumulated through a frame and sent as one single
// message, so the super shotgun doesn't generate huge messages.
.float dmg_take;
.float dmg_save;
.entity dmg_inflictor;
// Who launched a missile.
.entity owner;
// Mostly or doors, but also used for waterjump.
.vector movedir;
// Trigger messages.
.float message;
// Either a CD track number or a sound number.
.float soundtype;
// Contains names of .WAVs to play.
.string noise, noise1, noise2, noise3;
.float rings; // Which rings hero has
.float rings_active; // Shows which rings have been activated
.float rings_low; // Shows which rings are low on power
.float artifacts; // Which artifact hero has
.float artifact_active; // Shows which artifact have been activated
.float artifact_low; // Shows which artifact is running out
.float hasted; // % of normal speed player has been hasted
.float inventory; // Which item is currently chosen?
//rj.float ordr_cnt; // Number of items in order
// make sure you change references to:
// max_ammo2() DropBackpack() BackpackTouch()
// when adding or changing inventory fields
.float cnt_torch; // Count of inventory item - Torch
.float cnt_h_boost; // Count of inventory item - Health Boost
.float cnt_sh_boost; // Count of inventory item - Super Health Boost
.float cnt_mana_boost; // Count of inventory item - Mana Boost
.float cnt_teleport; // Count of inventory item - Teleport
.float cnt_tome; // Count of inventory item - Tome of Power
.float cnt_summon; // Count of inventory item - Summon
.float cnt_invisibility; // Count of inventory item - Invisibility
.float cnt_glyph; // Count of inventory item - Glyph of the Ancients
.float cnt_haste; // Count of inventory item - Haste
.float cnt_blast; // Count of inventory item - Blast Radius
.float cnt_polymorph; // Count of inventory item - Polymorph
.float cnt_flight; // Count of inventory item - Flight
.float cnt_cubeofforce; // Count of inventory item - Cube of Force
.float cnt_invincibility; // Count of inventory item - Invincibility
.entity cameramode;
.entity movechain;
.void() chainmoved;
.float string_index; // Index used for global string table
.float gravity; //Gravity, duh
.float siege_team; //ST_ATTACKER or ST_DEFENDER
// END SYSTEM FIELDS -------------------------------------------------------
// Flag the compiler.
void end_sys_fields;
// World fields
.string wad;
.string map;
.float worldtype; // 0=medieval 1=metal 2=base
.string killtarget;
// QuakeEd fields
.float light_lev; // Not used by game, but parsed by light util
.float style;
// Monster AI, doubled over for player
.void() th_stand;
.void() th_walk; //player_crouch_move
.void() th_run;
.void() th_missile; //player_attack
.void() th_melee;
.void(entity attacker, float damage) th_pain;
.void() th_die;
.void() th_save; // In case you need to save/restore a thinking state
// Mad at this player before taking damage.
.entity oldenemy;
.float speed;
.float lefty;
.float search_time;
.float attack_state;
// Monster AI stuff
.float monster_stage;
.float monster_duration; // Stage duration
.float monster_awake;
.float monster_check;
.vector monster_last_seen;
// because of how physics works, certain calls to the touch
// function of other entities involving the player do not
// allow you to adjust the velocity, so you have to do it
// outside of the inner physics stuff
.vector adjust_velocity;
.union
{ // Entity type specific stuff
struct // player stuff
{
float splash_time; // When to generate the next splash
float camera_time; //
float weaponframe_cnt; //
float attack_cnt; // Shows which attack animation can be used
float ring_regen_time; // When to add the next point of health
float ring_flight_time; // When to update ring of flight health
float ring_water_time; // When to update ring of waterbreathing health
float ring_turning_time;// When to update ring of turning health
float super_damage; // Player does this much more damage (Like Crusader with Special Ability #2)
float super_damage_low; // Flag the super damage is low
float puzzles_cheat; // Allows player past puzzle triggers
float camptime; // Amount of time player has been motionless
float crouch_time; // Next time player should run crouch subroutine
float crouch_stuck; // If set this means the player has released the crouch key in an area too small to uncrouch in
float divine_time; // Amount of time flash happens in divine intervention
float act_state; // Anim info
float raven_cnt; // Number of raven's this guys has in the world
float newclass; // If doing a quick class change
float poweredFlags; // Which weapons are available for being powered up in tomeMode 2
float last_use_time; // when i last performed operation (inv. use, sheepify, suicide) that shouldn't rapid-fire.
float jail_time;
};
struct
{ // Fallen Angel
float fangel_SaveFrame;
float fangel_Count;
float shoot_cnt;
float shoot_time; // Time of last shot
float z_movement;
float z_duration;
float drop_time;
};
struct
{ // Fallen Angel's Spell
float spell_angle;
};
struct
{ // Hydra
float hydra_FloatTo;
float hydra_chargeTime;
};
struct
{ // Spider
float spiderType; // SPIDER_? types
float spiderActiveCount; // Tallies "activity"
float spiderGoPause; // Active/pause threshold
float spiderPauseLength; // Pause duration in frames
float spiderPauseCount; // Tallies paused frames
};
struct
{ // Scorpion
float scorpionType; // SCORPION_? types
float scorpionRest; // Resting state counter
float scorpionWalkCount; // Counts walking frames
};
struct
{ // Golem
float golemSlideCounter;
float golemBeamDelay;
float golemBeamOff1;
float golemBeamOff2;
};
struct
{ // Imp
float impType; // IMP_? types
};
struct
{ // Mummy
float parts_gone;
float mummy_state;
float mummy_state_time;
};
struct
{ // Artifacts
float artifact_respawn; // Should respawn?
float artifact_ignore_owner_time;
float artifact_ignore_time;
float artifact_name;
};
struct
{ // Rider path
float next_path_1;
float next_path_2;
float next_path_3;
float next_path_4;
float path_id;
float next_path_5;
float next_path_6;
};
struct
{ // Rider triggers
float rt_chance;
};
struct
{ // Rider data
float rider_gallop_mode;
float rider_last_y_change;
float rider_y_change;
float rider_death_speed;
float rider_path_distance;
float rider_move_adjustment;
};
struct
{ // War rider axe
float waraxe_offset;
float waraxe_horizontal;
float waraxe_track_inc;
float waraxe_track_limit;
float waraxe_max_speed;
float waraxe_max_height;
};
struct
{ // War rider's quake
float wrq_effect_id;
float wrq_radius;
float wrq_count;
};
struct
{ // Rider's beam
float beam_angle_a;
float beam_angle_b;
float beam_max_scale;
float beam_direction;
float beam_speed;
};
struct
{ // Used by smoke generator
float z_modifier;
};
struct
{
float last_health; // Used by bell entity
};
struct // For raven staff Ravens
{
float idealpitch;
float pitchdowntime;
float searchtime; // Amount of time bird has been searching
float next_action; // Next time to take action
float searchtime; // When search was first started
float damage_max; // Amount of damage each raven can do before it has to leave
float raven_effect_id; //effect id number
entity raven_owner; //owner field can get modified by refections
vector last_vel; // last updated velocity, tells when change needed
};
struct
{ // fish
float fish_speed;
float fish_leader_count;
};
struct
{ // Used by particle explosion entity.
float exploderadius;
};
struct
{ // Skull missiles from skullwizard
float scream_time;
};
struct
{
float attack_cnt;
};
struct
{ // Pestalance's Hive
float beginframe;
};
struct
{ // Soul spheres
float sound_time;
};
struct
{ // Cube of force
float shot_cnt; // Number of shots the force cube has shot
};
struct
{ // xbow bolts
entity firstbolt; // maintain list of bolts that use same effect, so it can be removed when all bolts are gone
entity nextbolt;
float boltnum; // when i tell effect to change, it has to know which bolt changes
float xbo_effect_id;
vector xbo_startpos;//save where bolt is fired from; since bolts don't accelerate,
//can just send the distance they travelled instead of ending position
float fusetime;//determine how long tomed bolts wait til exploding when they are shot
float xbo_teleported;//bolt has just been teleported.
};
};
// Once we can do unions above end_sys, have this with the field 'playerclass'
.float monsterclass;
// FIXME: Remove the ring of spell turning and all references to this
.float turn_time;
// Triggers / doors
.string puzzle_piece_1;
.string puzzle_piece_2;
.string puzzle_piece_3;
.string puzzle_piece_4;
.float no_puzzle_msg;
// Puzzle Item
.string puzzle_id;
// More rider stuff that can't be in the union
.entity path_current;
.vector oldangles;
.string lastweapon; // Weapon model player had before changing to camera mode
.float lifetime;
.float lifespan;
.float walkframe;
.float wfs; // Weapon frame state
.float attack_finished;
.float pain_finished;
.float invisible_finished;
.float invincible_time, invincible_sound;
.float invisible_time;
.float super_damage_time;
// Set to time+0.2 whenever a client fires a weapon or takes damage.
// Used to alert monsters that otherwise would let the player go.
.float show_hostile;
// Player jump flag.
.float jump_flag;
// Player swimming sound flag.
.float swim_flag;
// When time > air_finished, start drowning.
.float air_finished;
// Keeps track of the number of bubbles.
.float bubble_count;
// Keeps track of how the player died.
.string deathtype;
// Object stuff.
.string mdl;
.vector mangle; // Angle at start
// Only used by secret door.
.vector oldorigin;
.float t_length, t_width;
// Things color.
.float color;
// Count of things (used by rain entity)
.float counter;
// Can these be made part of a union??
.float plaqueflg; // 0 if not using a plaque, 1 if using a plaque
.vector plaqueangle; // Angle player was facing when the plaque was touched
// Doors, etc.
.vector dest, dest1, dest2;
.float wait; // Time from firing to restarting
.float delay; // Time from activation to firing
.entity trigger_field; // Door's trigger entity
.string noise4;
// Monsters.
.float pausetime;
.entity pathentity;
// Doors.
.float aflag;
.float dmg; // Damage done by door when hit
// Misc flag.
.float cnt;
// What type of thing is this?
.float thingtype;
// Amount of time left on torch.
.float torchtime;
// Next torch think.
.void() torchthink;
// Amount of time left on the super health.
.float healthtime;
// Subs
.void() think1;
.vector finaldest, finalangle;
// For counting triggers
.float count;
.float spawn_health; // Set to >0 to spawn instant health
// Plats/doors/buttons
.float lip;
.float state;
.vector pos1, pos2; // Top and bottom positions
.float height;
// Sounds
//.float waitmin, waitmax;
//.float distance;
//.float volume;
.vector orgnl_mins, orgnl_maxs; // original bounding box
.float veer; //Amount of veer when Veer function called (included in HomeThink Function)
//The higher the number, the more drastic the wander is.
.float homerate;//Turning rate on homing missiles, is used as the nextthink time
//so the lower the number, the tighter thr turn radius.
//From the SpiralThink function, a value of FALSE will
//stop it from randomly homing while spiraling,
//a value of TRUE will allow it to randomly Home, but
//does not effect rate of homing since it only calls
//it randomly.
.float mass; //NOTE: 1 = @18.5 pounds.
//How much they weigh- should be used in all velocity mods
//(pushing, impact, throwing). Used as a divider, so
//the higher the number, the higher the mass, the less
//distance it will go. Make sure it's >0
//Buttons and pressure plates can use this too so that
//if a light object is placed on it, it won't activate
//(but it should be cumulative so that you can stack several
//light objects to increase mass and activate it)
//Also, a light player (featherfall?) could get around
//certain traps?
.float onfire; //A value that, when FALSE means the object is not on
//fire. A greater than zero value indicates how fast
//the thing is burning. The higher the number, the higher
//the damage and the more flames.
.vector o_angle;//Just to remember an old angle or vector
//Player
.float bloodloss;//For the Bleed() function which will remove health
//and add graphic. Set to 666 for beheading death.
.float oldweapon;//For remembering your last weapon, has many uses
//Monsters (and some projectiles)
.entity controller; //What is the owner of this thing, this allows
//it to touch it's owner if you set the owner
//to self.
.float init_modelindex;//initial model index, so you can switch away and back
.string init_model;
//Player Only th_***
.void() th_swim;
.void() th_jump;
.void() th_fly;
.void() th_die1;
.void() th_die2;
.void() th_goredeath;
.void() th_possum; //Monster playing dead
.void() th_possum_up; //Monster getting up from playing dead
.float last_attack; //Used for weapons that go into rest mode after
//a while
.entity shield;
.float frozen; //Can't be a flag, is a counter
.float oldskin;
.void() oldthink;
.void() th_weapon;
.float decap; //To know if was beheaded, not a flag, set to 2 if
//head should explode
.string headmodel;
.void() oldtouch; //These two are for when you're frozen and thaw out
.float oldmovetype;
.float target_scale;
.float scalerate;
.float blizzcount;
.float tripwire_cnt;
.float imp_count;
.vector proj_ofs; //Projectile offset, different from view_ofs.
.string spawnername; //for monster spawner
.entity catapulter;
.float catapult_time;
.float last_onground; //Timer- helps keep track of how long something has been in the air.
.vector pos_ofs; //Position ofset
.vector angle_ofs; //Angle offset
.float safe_time; //How long after a tornado throws you that it cant pick you up again
.float absorb_time; //for 0.3 seconds after crouching, you will absorb 1/2 of your falling damage upon impact
.float mintel; //Monster intelligence- temp since entity.hc was checked out
.vector wallspot; //Last place enemy was seen- for waypoint ai
.vector lastwaypointspot;//explains itself
.entity lockentity; //for waypoint system
.float last_impact; //Last time touch function was called
.float inactive;
.float msg2;
.string msg3;
.string nexttarget; //For target transferral
.float upside_down;
.float lightvalue1;
.float lightvalue2;
.float fadespeed;
.float point_seq; //Waypoint sequence number
.float sheep_time; //How long you will be a sheep for
.float sheep_sound_time;
.float still_time; //How long she's been standing still
.float visibility_offset; //How hard it is to see and aim at entity, from 0 to 1
//0 is totally visible, 1 is invisible
.float check_ok; //For trigger check, instead of re-using aflag
.entity check_chain; //for trigger_check, keeps track of it's targetted entities
.void() th_spawn; //Monster function you spawned with
.float freeze_time;
.float level_frags;
.float visibility;
entity sight_entity; //So monsters wake up other monsters
.entity viewentity;
.float sv_flags; //temp serverflags fix
.float dmgtime;
.float healamount, healtype;
.float anglespeed;
.float angletime;
.float movetime;
.float hit_z;
.float torncount;
.entity path_last;
.float dflags;
.float gameFlags;
.entity targetPlayer;
//MISSION PACK
.float fire_damage;
.float standard_grav;
.float init_exp_val;
.entity credit_enemy;
.string close_target;
//SIEGE
.float cnt_grenades;
.float cnt_arrows;
.float last_time;
.float beast_time;
.float climbing;
.vector climbspot;
.float last_climb;
.float fov_val;
.float zoom_time;
.float fail_chance;
.void() th_init;
.vector init_org;
.string ondeath_target;
.string pain_target;
.float last_up;
| 0 | 0.805044 | 1 | 0.805044 | game-dev | MEDIA | 0.999179 | game-dev | 0.661072 | 1 | 0.661072 |
jaseowns/uo_outlands_razor_scripts | 42,766 | outlands.uorazorscripts.com/script/54138cac-0511-429b-8b5c-90d142cac18a | # This is an automated backup - check out https://outlands.uorazorscripts.com/script/54138cac-0511-429b-8b5c-90d142cac18a for latest
# Automation by Jaseowns
## Script: Bapeth's Ocean Master Backround
## Created by: barryroser#0
#############################################
# Bapeths "Master Background" Ship Script
#
# Sept 1st 2025 - Reworked spyglass routine based on new spyglass changes
#
# Script is designed for Necro and Chiv (Mage or Pooner)
#
# SCRIPT MUST BE NAMED "Master Background" OR IT WONT LINK TO OTHER SCRIPTS
#
# "****REQUIRED****"
# Bapeths Ship Cooldowns xml file (copy paste into your characters Cooldown file)
# "COPY" Link to get Bapeths Cooldowns "https://outlands.uorazorscripts.com/script/f1e41e2d-411e-461e-9fd0-c4fc2dc234b1"
# "PASTE" FILE PATH : C:\Program Files (x86)\Ultima Online Outlands\ClassicUO\Data\Profiles\"YOUR-ACCOUNT-NAME"\UO Outlands\"YOUR-CHARACTER" Open file in notepad
# The cooldowns with "Tigger Text" Must be adjusted to "your ships stats" and "your Wizard Grimoire upgrades" in the UO in game Options
# Set spyglass cooldown to your preferred radar interval (default 7 is fastest possible) in the UO in game Options
#
# This script is the default background script that should be running most of the time
# In defensive mode (peace mode) it will auto heal, auto cure, top up bard buffs, auto spyglass, auto drop loot to hold, and auto pick up bombs on your own deck
# In offensive mode (war mode) it will use necro/chiv abilities, auto spell cast, auto heal, auto cure, auto cleanse, auto explode pot, and auto loot enemy holds
# Generally you should be in peace mode when on your own ship and in war mode when on an enemy ship
# Use warmode on your own ship for fighting mobs on your own ship (bosses and fishing)
# Toggle "war mode on" for offensive stance and "war mode off" for defensive stance
#
# "Spy Glass Timer"
# The script will auto handle spyglassing interval based on what you set the in game "Spyglass" cooldown to (Max interval is 6 seconds by default)
# Do not use "Continuous Search" if you want to control the interval otherwise the search will always be max interval
#
# "Target Scheme"
# This script can change into Target Closest or Target Random - default is Target Random
# Type "[Atlas" in game to spawn a free weightless "Atlas" in your bag
# Double click the atlas while this script is playing to switch between "Closest and Random"
# Hotkey "Grants the player an Atlas" in razor hotkey tab if you dont want to doubleclick
#
# "Auto Net Caster"
# Open the "Party Menu" while the script is playing to toggle this feature on/off
# The script will auto throw nets on fishing spots when nearby
#
# "Auto Loot Control"
# This script uses razor "Auto-Queue Object Delay" setting
# Make sure this setting is turned ON in the razor Options tab > Targeting & Queues sub-tab
# And set "object delay to 503" AUTO LOOTING WILL BE SLOW IF YOU DONT DO THIS!
#
# "Spam Reduction"
# Options tab > Targeting & Queues subtab > Uncheck "Attack/Target name overhead"
# Filters tab > Text & Messages subtab > Check "Filter Repeating Razor Messages" ONLY
# Replace your system messages with your Journal - See Journal options "Hide Messages in Viewport"
#
# Script starts here
if not varexist "updatemessagebapfood"
overhead "Script Updated to Auto Eat Food" 88
pause 2000
overhead "Create a Cooldown called Food" 88
pause 2000
overhead "Or re-install the XML Cooldown file" 88
pause 2000
setvar "updatemessagebapfood" backpack
endif
if skill "Healing" >= 20
if hp = maxhp
//donothing
elseif not bandaging and findtype 3617 backpack
hotkey "Bandage Self"
cooldown "Bandage" 7000
endif
endif
while poisoned and not targetexists
if findtype "Orange Potion" backpack as curepot
dclick curepot
pause 500
getlabel backpack ping
endif
endwhile
if skill "Fishing" >= 80
if not find "MainPoon"
if findlayer self lefthand as pooninhand
@setvar "MainPoon" pooninhand
endif
elseif find "MainPoon" backpack
dclick "MainPoon"
pause 500
getlabel backpack ping
endif
endif
if skill "Alchemy" >= 0 and not hidden and not targetexists
if not findbuff "Strength" and findtype "White Potion" backpack as wpot
dclick wpot
pause 500
getlabel backpack ping
endif
if not findbuff "Agility" and findtype "Blue Potion" backpack as bpot
dclick bpot
pause 500
getlabel backpack ping
endif
if not findbuff "Magic Resist Potion" and findtype "Black Potion" backpack as mpot
dclick mpot
pause 500
getlabel backpack ping
endif
endif
if not targetexists and not casting and not cooldown "Food"
if findtype 2429|28885|29774|29773|28880|28888|28881|28883|28886|28879 backpack as food
dclick food
cooldown "Food" 3600000
getlabel backpack ping
endif
endif
if not targetexists and not hidden and not casting and stam < maxstam and findtype "Red Potion" backpack as redpot
while queued
//donothing
endwhile
dclick redpot
endif
if hp < 77 and not hidden and not timerexists brew and not targetexists and findbuff "Bleed" and findtype 50675 backpack as cbrew
clearsysmsg
while queued
//donothing
endwhile
dclick cbrew
getlabel backpack ping
if insysmsg "You drink a cleansing brew"
createtimer brew
endif
elseif hp < 77 and not hidden and not timerexists brew and not targetexists and findbuff "Diseased" and findtype 50675 backpack as cbrew
while queued
//donothing
endwhile
dclick cbrew
getlabel backpack ping
if insysmsg "You drink a cleansing brew"
createtimer brew
endif
endif
if timerexists brew
if timer brew >= 120000
removetimer brew
endif
endif
if insysmsg "You now feel familiar with the area"
cooldown "Adv Pack" 720000
endif
while findtype 3834 backpack 0 as bbook
@ignore bbook
endwhile
if gumpexists 341416395 and not timerexists changetarget
gumpclose 341416395
createtimer changetarget
overhead "Closest Target Enabled" 87
elseif gumpexists 341416395 and timerexists changetarget
gumpclose 341416395
removetimer changetarget
overhead "Random Target Enabled" 2085
endif
if not timerexists oceanscan
createtimer oceanscan
settimer oceanscan 300
endif
if not timerexists checktarget
createtimer checktarget
settimer checktarget 18000
endif
if timerexists changetarget and timer checktarget >= 18000
overhead "Closest Target Enabled" 87
settimer checktarget 0
elseif not timerexists changetarget and timer checktarget >= 18000
overhead "Random Target Enabled" 2085
settimer checktarget 0
endif
if not timerexists sacredjourncheck
createtimer sacredjourncheck
settimer sacredjourncheck 75000
endif
if skill "Chivalry" >= 80 and timer sacredjourncheck >= 75000
if not findbuff "Sacred Journey"
overhead "A sacred jounrey awaits..." 201
endif
settimer sacredjourncheck 0
endif
if skill "Arcane" >= 80 and not gumpexists 3954121934
say '[abilityhotbar'
waitforgump 3954121934 500
endif
if skill "Chivalry" >= 80 and not gumpexists 3954121934
say '[abilityhotbar'
waitforgump 3954121934 500
endif
if insysmsg "repaired"
gumpclose 1271619955
say "[Repair"
endif
if findtype "fishing net" backpack 2785 as specialnetignore
@ignore specialnetignore
elseif findtype "fishing net" backpack 2851 as specialnetignore
@ignore specialnetignore
elseif findtype "fishing net" backpack 2880 as specialnetignore
@ignore specialnetignore
elseif findtype "fishing net" backpack 2963 as specialnetignore
@ignore specialnetignore
elseif findtype "fishing net" backpack 2839 as specialnetignore
@ignore specialnetignore
elseif findtype "fishing net" backpack 2871 as specialnetignore
@ignore specialnetignore
elseif findtype "fishing net" backpack 2795 as specialnetignore
@ignore specialnetignore
elseif findtype "fishing net" backpack 2814 as specialnetignore
@ignore specialnetignore
elseif findtype "fishing net" backpack 2900 as specialnetignore
@ignore specialnetignore
endif
if not timerexists autonetcast
if gumpexists 3527489586
gumpclose 3527489586
createtimer autonetcast
overhead "--Auto Net Cast Enabled--" 2085
endif
endif
if timerexists autonetcast
if gumpexists 3527489586
gumpclose 3527489586
removetimer autonetcast
overhead "--Auto Net Cast Disabled--" 1779
endif
endif
if timerexists autonetcast and findtype 1286|18824|3530|26683|39345|29410|29230|2646|18824|441|25769|39434|27641|3707|29230|25769 ground -1 -1 12
if not timerexists netwait
createtimer netwait
settimer netwait 4000
endif
if not queued and timer netwait >= 3400 and findtype "fishing net" backpack as net
dclick net
wft 500
target net
getlabel backpack ping
settimer netwait 0
endif
if insysmsg "You have completely fished out that location."
overhead "Fishing spot depleated..." 88
script "Master Background"
stop
endif
endif
if not warmode
if not timerexists autonetcast and not queued and not targetexists and not findbuff "Actively Meditating" and not cooldown "Spyglass" and hp >= 66 and findtype "spyglass" backpack as bspy
gumpclose 2890020940
dclick bspy
waitforgump 2890020940 500
if gumpexists 2890020940
overhead 'Yarr!' 67
endif
elseif timerexists autonetcast and not queued and not targetexists and not findbuff "Actively Meditating" and not cooldown "Spyglass" and hp >= 66 and findtype "spyglass" backpack as bspy
gumpclose 2890020940
dclick bspy
waitforgump 2890020940 500
if gumpexists 2890020940
overhead 'Yarr!' 67
endif
endif
if not timerexists onetimewarmode
createtimer onetimewarmode
endif
if timerexists onetimepeacemode
settimer disarmcheck 90000
removetimer onetimepeacemode
endif
if skill "Arms Lore" >= 80 and not timerexists disarmcheck
createtimer disarmcheck
settimer disarmcheck 90000
elseif skill "Arms Lore" >= 80 and timerexists disarmcheck
clearsysmsg
for 4
if timer disarmcheck >= 90000
say "[Disarm"
getlabel backpack ping
if insysmsg "You refrain from making disarm attempts."
settimer disarmcheck 0
break
endif
endif
endfor
endif
while findtype 3834 backpack 0 as bbook
@ignore bbook
endwhile
if not timerexists petguard
createtimer petguard
settimer petguard 5000
endif
if followers >= 1 and timer petguard >= 14000 and not findbuff "Actively Meditating"
say "all guard me" 45
settimer petguard 0
endif
if skill "Magery" >= 80
if timerexists reflect
if timer reflect > 30000
overhead "Magic Reflect is ready..." 201
settimer reflect 12000
endif
endif
if findbuff "Magic Reflection" and timerexists reflect
removetimer reflect
endif
if not findbuff "Magic Reflection" and not timerexists reflect
createtimer reflect
endif
endif
if skill "Magery" >= 20
if timerexists reactive
if timer reactive > 30000
overhead "Reactive Armor is ready..." 139
settimer reactive 13500
endif
endif
if findbuff "Reactive Armor" and timerexists reactive
removetimer reactive
endif
if not findbuff "Reactive Armor" and not timerexists reactive
createtimer reactive
endif
endif
if skill "Tracking" >= 10 and not findbuff "Tracking Hunting"
skill 'tracking'
waitforgump 4267467659 500
gumpresponse 6
pause 250
gumpclose 4267467659
cooldown "Disco" 10000
endif
if not targetexists
while hp < 33 and skill "Magery" >= 30
hotkey 'Cancel Current Target'
cast 'Heal'
wft 2500
hotkey 'Target Self'
hotkey 'Cancel Current Target'
pause 250
endwhile
if hp < 77 and findtype "Yellow Potion" backpack as healpot
dclick healpot
endif
if hp < 55 and skill "Magery" >= 60
hotkey 'Cancel Current Target'
cast 'Greater Heal'
wft 3500
hotkey 'Target self'
hotkey 'Cancel Current Target'
pause 250
endif
if hp < 83 and skill "Magery" >= 30
hotkey 'Cancel Current Target'
cast 'Heal'
wft 2500
hotkey 'Target Self'
hotkey 'Cancel Current Target'
pause 250
endif
while poisoned and not targetexists
if findtype "Orange Potion" backpack as curepot
dclick curepot
elseif mana >= 6 and skill "Magery" >= 40
cast "Cure"
wft 2500
target self
hotkey 'Cancel Current Target'
endif
endwhile
if skill "Magery" >= 80 and mana <= 20 and not findbuff "Actively Meditating" and not cooldown "Magic Mushroom"
dclicktype 'mushroom'
endif
if skill "Provocation" >= 10 and not findbuff "Actively Meditating" and not cooldown "Disco" and not cooldown "Song of Discord" and not cooldown "Song of Provocation" and not cooldown "Song of Peacemaking" and not findbuff "Song of provocation"
hotkey "Cancel Current Target"
useskill "Provocation"
wft 500
targetrelloc -1 -1
endif
if skill "Discordance" >= 10 and not findbuff "Actively Meditating" and not cooldown "Disco" and not cooldown "Song of Discord" and not cooldown "Song of Provocation" and not cooldown "Song of Peacemaking" and not findbuff "Song of discordance"
hotkey "Cancel Current Target"
useskill "Discordance"
wft 500
targetrelloc -1 -1
endif
if not findbuff "Actively Meditating" and not findbuff "Cunning" and mana >= 6 and skill "Magery" >= 40
cast "Cunning"
wft 1500
target self
hotkey 'Cancel Current Target'
endif
endif
if skill "Magery" >= 50 and followers = 0 and timer petguard >= 12500
overhead 'I should get some followers...' 39
settimer petguard 0
endif
if skill "Necromancy" >= 80 and not gumpexists 622436516
say [necromancyhotbar
pause 250
endif
if skill "Chivalry" >= 80 and not gumpexists 1387930325
say [chivalryhotbar
pause 250
endif
if findtype "5188" ground -1 -1 2 as bomb
dclick bomb
endif
if findtype "5188" ground -1 -1 22 as bomb
overhead "***BOMB***" 34 bomb
endif
if timer oceanscan >= 300 and skill "Arcane" >= 80 and cooldown "Fray"
clearsysmsg
if varexist "oceantarget"
@unsetvar "oceantarget"
endif
hotkey "Next Enemy Monster Target"
if not insysmsg "No one matching"
@setvar "oceantarget" lasttarget
endif
hotkey "Next Grey Monster Target"
if not insysmsg "No one matching"
@setvar "oceantarget" lasttarget
endif
hotkey "Next Murderer Monster Target"
if not insysmsg "No one matching"
@setvar "oceantarget" lasttarget
endif
settimer oceanscan 0
elseif timer oceanscan >= 300 and skill "Fishing" >= 80 and cooldown "Fray"
clearsysmsg
if varexist "oceantarget"
@unsetvar "oceantarget"
endif
hotkey "Next Enemy Monster Target"
if not insysmsg "No one matching"
@setvar "oceantarget" lasttarget
endif
hotkey "Next Grey Monster Target"
if not insysmsg "No one matching"
@setvar "oceantarget" lasttarget
endif
hotkey "Next Murderer Monster Target"
if not insysmsg "No one matching"
@setvar "oceantarget" lasttarget
endif
settimer oceanscan 0
endif
if not timerexists changetarget and find "oceantarget" ground -1 -1 12 and not findbuff "Actively Meditating" and cooldown "Fray"
if find "Manual Override" ground and noto "Manual Override" = hostile
attack "Manual Override"
elseif noto "Manual Override" = criminal
attack "Manual Override"
elseif noto "Manual Override" = enemy
attack "Manual Override"
elseif noto "Manual Override" = murderer
attack "Manual Override"
else
attack "oceantarget"
endif
elseif timerexists changetarget and find "oceantarget" ground -1 -1 12 and not findbuff "Actively Meditating" and cooldown "Fray"
if find "Manual Override" ground and noto "Manual Override" = hostile
attack "Manual Override"
elseif noto "Manual Override" = criminal
attack "Manual Override"
elseif noto "Manual Override" = enemy
attack "Manual Override"
elseif noto "Manual Override" = murderer
attack "Manual Override"
else
hotkey 'Target Closest Enemy Monster'
hotkey 'Target Closest Grey Monster'
hotkey 'Target Closest Murderer Monster'
attack lasttarget
hotkey "Cancel Current Target"
endif
endif
if find "shiphold" ground -1 -1 1
clearsysmsg
while findtype "43206|cathedral tapestry|Darkscale tapestry|large painting|landscape painting|portrait painting|hieroglyph|figurine|statue|44987|49730|47107|18653|45127|47103|29363|47105|29361|3712|3648|3650|3708|3648|2475|3649|29833|29832|43453|5899|47109|45250|11858|41509|43447|18657|4025|51308|45156|51304|45214|28769|28799|28803|28765|45211|45248|51259|45220|51328|45218|3842|51327|45222|45241|51336|51375|45282|54722|45255|45246|28795|44983|45235|45251|45238|51258|51314|28761|45236|51260|54718|18400|45252|18656|47111|3839|45239|45242|45254|45281|45247|42241|45216|28775|51321|3838|51318|5901|5905|5903|48407|51302|4248|27611|15296|43166|5359|5981|4026|3985|25359|17686|3836|17087|5356|29030|24434|22336|29036|3843|29025|51098|29034|8826|51094|576|3827|22326|45315|3891|2539|39898|39896|39892|39918|39911|39916|39905|39891|39917|39912|39909|39889|31047|31017|31049|31019|31055|31051|31053|31025|31027|31031|31041|54717|31021|31011|31023|31029|31043|31003|31035|31033|31045|31037|31002|20006|31169|31006|30999|31012|31009|30996|7109|7107|31128|31188|20014|31014|31004|31142|31001|31000|37181|31010|30998|31172|30988|30997|31038|31141|7947|20008|31005|31191|31008|31007|30994|30993|31182|30989|20012|31186|31178|31015|30991|20010|20016|31184|31190|30990|30995|31176|31180|30992|31130|5207|7031|7026|7034|7033|7027|7035|7029|5078|5063|5059|5105|5060|5138|5129|5201|5142|5143|5076|5106|7610|5139|5090|5103|5132|7177|5061|7181|7179|3920|5042|5127|5117|5185|5125|3938|5177|3937|5044|5121|3915|3909|3568|3932|5123|5144|5119|5056|5135|5187|5074|5089|3934|3913|3917|3721|5075|5046|5049|7170|5146|5205|5203|5115|5204|5040|5179|5070|5182|5085|5181|3719|7173|5131|3911|5101|7175|7169|3713|5112|22187|9917|3859|3862|3878|3865|3856|3873|3877|3834|3742|3762|3740|3763|10245|3572|3573|3571|3885|7127|4225|12686|19985|19981|19984|19982|19983|19991|19989|19986|19987|19988|19994|19995|19992|19993|19990|19980|19977|19976|19978|7154|19979|17619|17617|2508|7710|2463|3861|3821" backpack as bitem
drop backpack
lift bitem 60000
drop shiphold -1 -1 0
while queued
//dotnothing
endwhile
endwhile
endif
elseif warmode
if skill "Healing" >= 20
if hp = maxhp
//donothing
elseif not bandaging and findtype 3617 backpack
hotkey "Bandage Self"
endif
endif
if skill "Arcane" >= 80
if not timerexists leylinetimer
createtimer leylinetimer
settimer leylinetimer 3000
endif
if mana <= 80 and timer leylinetimer >= 3000 and find "oceantarget" ground -1 -1 12
say "[weaponability2"
settimer leylinetimer 0
endif
endif
if skill "Fishing" >= 80
if not timerexists scouragetimer
createtimer scouragetimer
settimer scouragetimer 3000
endif
if mana <= 80 and timer scouragetimer >= 3000 and find "oceantarget" ground -1 -1 12
say "[weaponability2"
settimer scouragetimer 0
endif
endif
if not timerexists onetimepeacemode
createtimer onetimepeacemode
endif
if timerexists onetimewarmode
settimer disarmcheck 90000
removetimer onetimewarmode
endif
if skill "Arms Lore" >= 80 and not timerexists disarmcheck
createtimer disarmcheck
settimer disarmcheck 90000
elseif skill "Arms Lore" >= 80 and timerexists disarmcheck
clearsysmsg
for 4
if timer disarmcheck >= 90000
say "[Disarm"
getlabel backpack ping
if insysmsg "You will now attempt to disarm your opponents."
settimer disarmcheck 0
break
endif
endif
endfor
settimer oceanscan 300
endif
if gumpexists 341416395 and not timerexists changetarget
gumpclose 341416395
createtimer changetarget
overhead "Closest Target Enabled" 87
elseif gumpexists 341416395 and timerexists changetarget
gumpclose 341416395
removetimer changetarget
overhead "Random Target Enabled" 2085
endif
if timer oceanscan >= 300 and skill "Arcane" >= 80
clearsysmsg
if varexist "oceantarget"
@unsetvar "oceantarget"
endif
hotkey "Next Enemy Monster Target"
if not insysmsg "No one matching"
@setvar "oceantarget" lasttarget
endif
hotkey "Next Grey Monster Target"
if not insysmsg "No one matching"
@setvar "oceantarget" lasttarget
endif
hotkey "Next Murderer Monster Target"
if not insysmsg "No one matching"
@setvar "oceantarget" lasttarget
endif
settimer oceanscan 0
elseif timer oceanscan >= 300 and skill "Fishing" >= 80
clearsysmsg
if varexist "oceantarget"
@unsetvar "oceantarget"
endif
hotkey "Next Enemy Monster Target"
if not insysmsg "No one matching"
@setvar "oceantarget" lasttarget
endif
hotkey "Next Grey Monster Target"
if not insysmsg "No one matching"
@setvar "oceantarget" lasttarget
endif
hotkey "Next Murderer Monster Target"
if not insysmsg "No one matching"
@setvar "oceantarget" lasttarget
endif
settimer oceanscan 0
endif
if not timerexists changetarget and find "oceantarget" ground -1 -1 12 and not findbuff "Actively Meditating"
if find "Manual Override" ground and noto "Manual Override" = hostile
attack "Manual Override"
elseif noto "Manual Override" = criminal
attack "Manual Override"
elseif noto "Manual Override" = enemy
attack "Manual Override"
elseif noto "Manual Override" = murderer
attack "Manual Override"
else
attack "oceantarget"
endif
elseif timerexists changetarget and find "oceantarget" ground -1 -1 12 and not findbuff "Actively Meditating"
if find "Manual Override" ground and noto "Manual Override" = hostile
attack "Manual Override"
elseif noto "Manual Override" = criminal
attack "Manual Override"
elseif noto "Manual Override" = enemy
attack "Manual Override"
elseif noto "Manual Override" = murderer
attack "Manual Override"
else
hotkey 'Target Closest Enemy Monster'
hotkey 'Target Closest Grey Monster'
hotkey 'Target Closest Murderer Monster'
attack lasttarget
hotkey "Cancel Current Target"
endif
endif
if not poisoned and not timerexists autonetcast and not queued and not targetexists and not findbuff "Actively Meditating" and not cooldown "Spyglass" and hp >= 66 and findtype "spyglass" backpack as bspy
gumpclose 2890020940
dclick bspy
waitforgump 2890020940 500
if gumpexists 2890020940
overhead 'Yarr!' 67
endif
elseif not poisoned and timerexists autonetcast and not queued and not targetexists and not findbuff "Actively Meditating" and not cooldown "Spyglass" and hp >= 66 and findtype "spyglass" backpack as bspy
gumpclose 2890020940
dclick bspy
waitforgump 2890020940 500
if gumpexists 2890020940
overhead 'Yarr!' 67
endif
endif
if not targetexists
while hp < 33 and skill "Magery" >= 30
hotkey 'Cancel Current Target'
cast 'Heal'
wft 2500
hotkey 'Target Self'
hotkey 'Cancel Current Target'
pause 250
endwhile
if hp < 77 and findtype "Yellow Potion" backpack as healpot
dclick healpot
endif
if hp < 55 and skill "Magery" >= 60
hotkey 'Cancel Current Target'
cast 'Greater Heal'
wft 3500
hotkey 'Target self'
hotkey 'Cancel Current Target'
pause 250
endif
if hp < 83 and skill "Magery" >= 30
hotkey 'Cancel Current Target'
cast 'Heal'
wft 2500
hotkey 'Target Self'
hotkey 'Cancel Current Target'
pause 250
endif
while poisoned and not targetexists
if findtype "Orange Potion" backpack as curepot
dclick curepot
elseif mana >= 6 and skill "Magery" >= 40
cast "Cure"
wft 2500
target self
hotkey 'Cancel Current Target'
endif
endwhile
if hp < 77 and not hidden and not timerexists brew and not targetexists and findbuff "Bleed" and findtype 50675 backpack as cbrew
clearsysmsg
while queued
//donothing
endwhile
dclick cbrew
getlabel backpack ping
if insysmsg "You drink a cleansing brew"
createtimer brew
endif
elseif hp < 77 and not hidden and not timerexists brew and not targetexists and findbuff "Diseased" and findtype 50675 backpack as cbrew
while queued
//donothing
endwhile
dclick cbrew
getlabel backpack ping
if insysmsg "You drink a cleansing brew"
createtimer brew
endif
endif
if timerexists brew
if timer brew >= 120000
removetimer brew
endif
endif
if skill "Magery" >= 80 and mana <= 80 and not findbuff "Actively Meditating" and not cooldown "Magic Mushroom"
dclicktype 'mushroom'
endif
endif
if skill "Necromancy" >= 80 and not gumpexists 622436516
say [necromancyhotbar
pause 250
endif
if skill "Chivalry" >= 80 and not gumpexists 1387930325
say [chivalryhotbar
pause 250
endif
if findtype "5188" ground -1 -1 22 as bomb
overhead "***BOMB***" 34 bomb
endif
if timerexists openhull
removetimer openhull
endif
if find "shiphold" ground -1 -1 1
//donothing
elseif not queued and findtype "hatch" ground -1 -1 1 as mobship
dclick mobship
getlabel backpack ping
while findtype "43206|cathedral tapestry|Darkscale tapestry|large painting|landscape painting|portrait painting|hieroglyph|figurine|statue|44987|49730|47107|18653|45127|47103|29363|47105|29361|43453|5899|47109|45250|41509|43447|18657|4025|3712|3648|3650|11858|3708|3648|2475|3649|29833|29832|51308|45156|51304|45214|28769|28799|28803|28765|45211|45248|51259|45220|51328|45218|3842|51327|45222|45241|51336|51375|45282|54722|45255|45246|28795|44983|45235|45251|45238|51258|51314|28761|45236|51260|54718|18400|45252|18656|47111|3839|45239|45242|45254|45281|45247|42241|45216|28775|2594|51321|3838|51318|5901|5905|5903|48407|51302|4248|27611|15296|43166|5359|5981|4026|3985|25359|17686|3836|17087|5356|29030|24434|22336|29036|3843|29025|51098|29034|8826|51094|576|3827|22326|45315|3891|2539|39898|39896|39892|39918|39911|39916|39897|39905|39891|39917|39912|39909|39889|31047|31017|31049|31019|31055|31051|31053|31025|31027|31031|31041|54717|31021|31011|31023|31029|31043|31003|31035|31033|31045|31037|31002|20006|31169|31006|30999|31012|31009|30996|7109|7107|3922|31128|31188|20014|31014|31004|31142|31001|31000|37181|31010|30998|31172|30988|30997|31038|31141|7947|20008|31005|31191|31008|31007|30994|30993|31182|30989|20012|31186|31178|31015|30991|20010|20016|31184|31190|30990|30995|31176|31180|30992|31130|5207|7031|7026|7034|7033|7027|7035|7029|5078|5063|5059|5105|5060|5138|5129|5201|5142|5143|5076|5106|7610|5139|5090|5103|5132|7177|5061|7181|7179|3920|5042|5127|5117|5185|5125|3938|5177|3937|5044|5121|3915|3909|3568|3932|5123|5144|5119|5056|5135|5187|5074|5089|3934|3913|3917|3721|5075|5046|5049|7170|5146|5205|5203|5115|5204|5040|5179|5070|5182|5085|5181|3719|7173|5131|3911|5101|7175|7169|3713|5112|22187|9917|3859|3862|3878|3865|3856|3873|3877|3834|3742|3762|3740|3763|10245|3572|3573|3571|3885|7127|4225|12686|19985|19981|19984|19982|19983|19991|19989|19986|19987|19988|19994|19995|19992|19993|19990|19980|19977|19976|19978|7154|19979|3861|3821" mobship as bitem
if not timerexists openhull
createtimer openhull
overhead "Yarr the booty be mine!" 2091
endif
hotkey 'Grab Item'
target bitem
while queued
//donothing
endwhile
endwhile
endif
if not find "oceantarget" ground -1 -1 12 and timer oceanscan >= 300
clearsysmsg
hotkey "Next Enemy Monster Target"
if not insysmsg "No one matching"
@setvar "oceantarget" lasttarget
endif
hotkey "Next Grey Monster Target"
if not insysmsg "No one matching"
@setvar "oceantarget" lasttarget
endif
hotkey "Next Murderer Monster Target"
if not insysmsg "No one matching"
@setvar "oceantarget" lasttarget
endif
settimer oceanscan 0
endif
if find "oceantarget" ground -1 -1 12 and not findbuff "Actively Meditating" and not cooldown "Disco" and skill "Discordance" >= 50
clearsysmsg
hotkey 'Cancel Current Target'
skill 'Discordance'
wft 500
if not timerexists changetarget
hotkey 'Target self'
elseif timerexists changetarget
// I took Manual Override out here because single target discord was hitting the ship hamburger bars. I could simply retarget the crew I want to hit but its an extra step when I can just place myself next to closest. This may have been needed for boss fights.
hotkey 'Target Closest Grey Monster'
hotkey 'Target Closest Murderer Monster'
endif
hotkey 'Cancel Current Target'
getlabel backpack ping
if insysmsg "Song of Discordance"
overhead "Argh!! Manual Override is not on a target that can be Discorded" 38
endif
if insysmsg "creatures"
overhead "Hear my sea song!" 91
cooldown "Disco" 5000
elseif insysmsg "You play successfully"
overhead "Hear my sea song!" 91
cooldown "Disco" 5000
elseif insysmsg "You fail to discord"
overhead "Argh, I missed a note..." 38
cooldown "Disco" 5000
if cooldown "Barding Reset"
cooldown "Disco" 0
replay
endif
endif
endif
if skill "Necromancy" >= 80 and findtype "corpse" ground -1 -1 12
if ingump '20/' 622436516
createtimer pain
elseif ingump '19/' 622436516
createtimer pain
elseif ingump '18/' 622436516
createtimer pain
elseif ingump '17/' 622436516
createtimer pain
elseif ingump '16/' 622436516
createtimer pain
elseif ingump '15/' 622436516
createtimer pain
elseif ingump '14/' 622436516
createtimer pain
elseif ingump '13/' 622436516
createtimer pain
elseif ingump '12/' 622436516
createtimer pain
elseif ingump '11/' 622436516
createtimer pain
elseif ingump '10/' 622436516
createtimer pain
elseif ingump '9/' 622436516
createtimer pain
elseif ingump '8/' 622436516
createtimer pain
elseif ingump '7/' 622436516
createtimer pain
elseif ingump '6/' 622436516
createtimer pain
elseif ingump '5/' 622436516
createtimer pain
endif
if skill "Necromancy" >= 80 and timerexists pain and find "oceantarget" ground -1 -1 12 and not findbuff "Actively Meditating" and not cooldown 'Pain Spike'
clearsysmsg
if targetexists
hotkey 'Cancel Current Target'
endif
say '[Painspike'
wft 500
hotkey 'Target Closest Grey Monster'
hotkey 'Target Closest Murderer Monster'
getlabel backpack ping
if insysmsg "Unholy"
cooldown "Pain Spike" 30000
endif
removetimer pain
endif
endif
if find "oceantarget" ground -1 -1 12
clearsysmsg
if skill "Alchemy" >= 80 and not queued and not cooldown "Explosion Potion" and findtype "Purple Potion" backpack as purp
clearsysmsg
dclick purp
wft 500
hotkey 'Target Closest Grey Monster'
hotkey 'Target Closest Murderer Monster'
getlabel backpack ping
if insysmsg "Your explosion potion sticks to your target."
cooldown "Explosion Potion" 15000
else
cooldown "Explosion Potion" 15000
hotkey '> Interrupt'
hotkey "Cancel Current Target"
dclicktype "Purple Potion"
wft 500
while targetexists
overhead "THROW IT OVERBOARD!!!" 38
endwhile
endif
hotkey "Cancel Current Target"
elseif skill "Magery" >= 50 and not queued and mana >= 9 and not cooldown "Explosion Potion" and findtype "Purple Potion" backpack as purp
clearsysmsg
cast "Telekinesis"
wft 3000
hotkey 'Target Closest Grey Monster'
hotkey 'Target Closest Murderer Monster'
@setvar "telemastertarget" lasttarget
getlabel backpack ping
if insysmsg "Target cannot be seen"
cooldown "Explosion Potion" 15000
elseif insysmsg "any explosive potions thrown" and not queued and find "telemastertarget" ground -1 -1 12
dclick purp
wft 500
lasttarget
getlabel backpack ping
endif
if insysmsg "Your explosion potion sticks to your target."
cooldown "Explosion Potion" 15000
elseif not cooldown "Explosion Potion" and insysmsg "Where should I throw this potion?"
cooldown "Explosion Potion" 15000
hotkey '> Interrupt'
hotkey "Cancel Current Target"
dclicktype "Purple Potion"
wft 500
while targetexists
overhead "THROW IT OVERBOARD!!!" 38
endwhile
endif
hotkey "Cancel Current Target"
endif
if skill "Necromancy" >= 80 and find "oceantarget" ground -1 -1 12
if ingump '20/' 622436516
createtimer necroab
elseif ingump '19/' 622436516
createtimer necroab
elseif ingump '18/' 622436516
createtimer necroab
elseif ingump '17/' 622436516
createtimer necroab
elseif ingump '16/' 622436516
createtimer necroab
elseif ingump '15/' 622436516
createtimer necroab
elseif ingump '14/' 622436516
createtimer necroab
elseif ingump '13/' 622436516
createtimer necroab
elseif ingump '12/' 622436516
createtimer necroab
endif
endif
if skill "Necromancy" >= 80 and timerexists necroab and find "oceantarget" ground -1 -1 12
if not cooldown "Strangle"
pause 550
say '[Strangle'
cooldown "Strangle" 30000
pause 550
endif
if not cooldown "Evil Omen"
say '[EvilOmen'
cooldown "Evil Omen" 30000
pause 550
endif
if not cooldown "Corpse Skin"
say '[CorpseSkin'
cooldown "Corpse Skin" 30000
pause 550
endif
removetimer necroab
endif
if skill "Chivalry" >= 80 and find "oceantarget" ground -1 -1 12
if ingump '20/' 1387930325
createtimer chivab
elseif ingump '19/' 1387930325
createtimer chivab
elseif ingump '18/' 1387930325
createtimer chivab
elseif ingump '17/' 1387930325
createtimer chivab
elseif ingump '16/' 1387930325
createtimer chivab
elseif ingump '15/' 1387930325
createtimer chivab
elseif ingump '14/' 1387930325
createtimer chivab
elseif ingump '13/' 1387930325
createtimer chivab
elseif ingump '12/' 1387930325
createtimer chivab
elseif ingump '11/' 1387930325
createtimer chivab
elseif ingump '10/' 1387930325
createtimer chivab
elseif ingump '9/' 1387930325
createtimer chivab
endif
endif
if skill "Chivalry" >= 80 and timerexists chivab and find "oceantarget" ground -1 -1 12
if not findbuff "Divine Fury"
say '[DivineFury'
pause 550
endif
if not findbuff "Enemy of One"
say '[EnemyofOne'
pause 550
endif
if not findbuff "Consecrate Weapon"
say '[ConsecrateWeapon'
pause 550
endif
removetimer chivab
endif
if skill "Magery" >= 80
if not cooldown "Magic Arrow" and mana >= 4
hotkey 'Cancel Current Target'
cast "Magic Arrow"
wft 1000
if not timerexists changetarget
hotkey 'Target Random Grey Monster'
hotkey 'Target Random Murderer Monster'
elseif timerexists changetarget
hotkey 'Target Closest Grey Monster'
hotkey 'Target Closest Murderer Monster'
endif
elseif not cooldown "Harm" and mana >= 6
hotkey 'Cancel Current Target'
cast "Harm"
wft 1500
if not timerexists changetarget
hotkey 'Target Random Grey Monster'
hotkey 'Target Random Murderer Monster'
elseif timerexists changetarget
hotkey 'Target Closest Grey Monster'
hotkey 'Target Closest Murderer Monster'
endif
elseif not cooldown "Lightning" and mana >= 11
hotkey 'Cancel Current Target'
cast "Lightning"
wft 2500
if not timerexists changetarget
hotkey 'Target Random Grey Monster'
hotkey 'Target Random Murderer Monster'
elseif timerexists changetarget
hotkey 'Target Closest Grey Monster'
hotkey 'Target Closest Murderer Monster'
endif
elseif not cooldown "Chain Lightning" and cooldown "Lightning" and cooldown "Harm" and cooldown "Magic Arrow" and mana >= 40
hotkey 'Cancel Current Target'
cast "Chain Lightning"
wft 3000
if not timerexists changetarget
hotkey 'Target Random Grey Monster'
hotkey 'Target Random Murderer Monster'
elseif timerexists changetarget
hotkey 'Target Closest Grey Monster'
hotkey 'Target Closest Murderer Monster'
endif
elseif cooldown "Lightning" and cooldown "Harm" and cooldown "Magic Arrow" and mana >= 40
hotkey 'Cancel Current Target'
cast "Flamestrike"
wft 3000
if not timerexists changetarget
hotkey 'Target Random Grey Monster'
hotkey 'Target Random Murderer Monster'
elseif timerexists changetarget
hotkey 'Target Closest Grey Monster'
hotkey 'Target Closest Murderer Monster'
endif
endif
pause 150
endif
endif
endif
loop | 0 | 0.870728 | 1 | 0.870728 | game-dev | MEDIA | 0.695646 | game-dev | 0.806583 | 1 | 0.806583 |
dragonwell-project/dragonwell11 | 87,479 | src/java.desktop/share/native/liblcms/cmscgats.c | /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
// This file is available under and governed by the GNU General Public
// License version 2 only, as published by the Free Software Foundation.
// However, the following notice accompanied the original version of this
// file:
//
//---------------------------------------------------------------------------------
//
// Little Color Management System
// Copyright (c) 1998-2024 Marti Maria Saguer
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the Software
// is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//---------------------------------------------------------------------------------
//
#include "lcms2_internal.h"
// IT8.7 / CGATS.17-200x handling -----------------------------------------------------------------------------
#define MAXID 128 // Max length of identifier
#define MAXSTR 1024 // Max length of string
#define MAXTABLES 255 // Max Number of tables in a single stream
#define MAXINCLUDE 20 // Max number of nested includes
#define DEFAULT_DBL_FORMAT "%.10g" // Double formatting
#ifdef CMS_IS_WINDOWS_
# include <io.h>
# define DIR_CHAR '\\'
#else
# define DIR_CHAR '/'
#endif
// Symbols
typedef enum {
SUNDEFINED,
SINUM, // Integer
SDNUM, // Real
SIDENT, // Identifier
SSTRING, // string
SCOMMENT, // comment
SEOLN, // End of line
SEOF, // End of stream
SSYNERROR, // Syntax error found on stream
// IT8 symbols
SBEGIN_DATA,
SBEGIN_DATA_FORMAT,
SEND_DATA,
SEND_DATA_FORMAT,
SKEYWORD,
SDATA_FORMAT_ID,
SINCLUDE,
// Cube symbols
SDOMAIN_MAX,
SDOMAIN_MIN,
S_LUT1D_SIZE,
S_LUT1D_INPUT_RANGE,
S_LUT3D_SIZE,
S_LUT3D_INPUT_RANGE,
S_LUT_IN_VIDEO_RANGE,
S_LUT_OUT_VIDEO_RANGE,
STITLE
} SYMBOL;
// How to write the value
typedef enum {
WRITE_UNCOOKED,
WRITE_STRINGIFY,
WRITE_HEXADECIMAL,
WRITE_BINARY,
WRITE_PAIR
} WRITEMODE;
// Linked list of variable names
typedef struct _KeyVal {
struct _KeyVal* Next;
char* Keyword; // Name of variable
struct _KeyVal* NextSubkey; // If key is a dictionary, points to the next item
char* Subkey; // If key is a dictionary, points to the subkey name
char* Value; // Points to value
WRITEMODE WriteAs; // How to write the value
} KEYVALUE;
// Linked list of memory chunks (Memory sink)
typedef struct _OwnedMem {
struct _OwnedMem* Next;
void * Ptr; // Point to value
} OWNEDMEM;
// Suballocator
typedef struct _SubAllocator {
cmsUInt8Number* Block;
cmsUInt32Number BlockSize;
cmsUInt32Number Used;
} SUBALLOCATOR;
// Table. Each individual table can hold properties and rows & cols
typedef struct _Table {
char SheetType[MAXSTR]; // The first row of the IT8 (the type)
int nSamples, nPatches; // Cols, Rows
int SampleID; // Pos of ID
KEYVALUE* HeaderList; // The properties
char** DataFormat; // The binary stream descriptor
char** Data; // The binary stream
} TABLE;
// File stream being parsed
typedef struct _FileContext {
char FileName[cmsMAX_PATH]; // File name if being read from file
FILE* Stream; // File stream or NULL if holded in memory
} FILECTX;
//Very simple string
typedef struct {
struct struct_it8* it8;
cmsInt32Number max;
cmsInt32Number len;
char* begin;
} string;
// This struct hold all information about an open IT8 handler.
typedef struct struct_it8 {
cmsUInt32Number TablesCount; // How many tables in this stream
cmsUInt32Number nTable; // The actual table
// Partser type
cmsBool IsCUBE;
// Tables
TABLE Tab[MAXTABLES];
// Memory management
OWNEDMEM* MemorySink; // The storage backend
SUBALLOCATOR Allocator; // String suballocator -- just to keep it fast
// Parser state machine
SYMBOL sy; // Current symbol
int ch; // Current character
cmsInt32Number inum; // integer value
cmsFloat64Number dnum; // real value
string* id; // identifier
string* str; // string
// Allowed keywords & datasets. They have visibility on whole stream
KEYVALUE* ValidKeywords;
KEYVALUE* ValidSampleID;
char* Source; // Points to loc. being parsed
cmsInt32Number lineno; // line counter for error reporting
FILECTX* FileStack[MAXINCLUDE]; // Stack of files being parsed
cmsInt32Number IncludeSP; // Include Stack Pointer
char* MemoryBlock; // The stream if holded in memory
char DoubleFormatter[MAXID];// Printf-like 'cmsFloat64Number' formatter
cmsContext ContextID; // The threading context
} cmsIT8;
// The stream for save operations
typedef struct {
FILE* stream; // For save-to-file behaviour
cmsUInt8Number* Base;
cmsUInt8Number* Ptr; // For save-to-mem behaviour
cmsUInt32Number Used;
cmsUInt32Number Max;
} SAVESTREAM;
// ------------------------------------------------------ cmsIT8 parsing routines
// A keyword
typedef struct {
const char *id;
SYMBOL sy;
} KEYWORD;
// The keyword->symbol translation tables. Sorting is required.
static const KEYWORD TabKeysIT8[] = {
{"$INCLUDE", SINCLUDE}, // This is an extension!
{".INCLUDE", SINCLUDE}, // This is an extension!
{"BEGIN_DATA", SBEGIN_DATA },
{"BEGIN_DATA_FORMAT", SBEGIN_DATA_FORMAT },
{"DATA_FORMAT_IDENTIFIER", SDATA_FORMAT_ID},
{"END_DATA", SEND_DATA},
{"END_DATA_FORMAT", SEND_DATA_FORMAT},
{"KEYWORD", SKEYWORD}
};
#define NUMKEYS_IT8 (sizeof(TabKeysIT8)/sizeof(KEYWORD))
static const KEYWORD TabKeysCUBE[] = {
{"DOMAIN_MAX", SDOMAIN_MAX },
{"DOMAIN_MIN", SDOMAIN_MIN },
{"LUT_1D_SIZE", S_LUT1D_SIZE },
{"LUT_1D_INPUT_RANGE", S_LUT1D_INPUT_RANGE },
{"LUT_3D_SIZE", S_LUT3D_SIZE },
{"LUT_3D_INPUT_RANGE", S_LUT3D_INPUT_RANGE },
{"LUT_IN_VIDEO_RANGE", S_LUT_IN_VIDEO_RANGE },
{"LUT_OUT_VIDEO_RANGE", S_LUT_OUT_VIDEO_RANGE },
{"TITLE", STITLE }
};
#define NUMKEYS_CUBE (sizeof(TabKeysCUBE)/sizeof(KEYWORD))
// Predefined properties
// A property
typedef struct {
const char *id; // The identifier
WRITEMODE as; // How is supposed to be written
} PROPERTY;
static PROPERTY PredefinedProperties[] = {
{"NUMBER_OF_FIELDS", WRITE_UNCOOKED}, // Required - NUMBER OF FIELDS
{"NUMBER_OF_SETS", WRITE_UNCOOKED}, // Required - NUMBER OF SETS
{"ORIGINATOR", WRITE_STRINGIFY}, // Required - Identifies the specific system, organization or individual that created the data file.
{"FILE_DESCRIPTOR", WRITE_STRINGIFY}, // Required - Describes the purpose or contents of the data file.
{"CREATED", WRITE_STRINGIFY}, // Required - Indicates date of creation of the data file.
{"DESCRIPTOR", WRITE_STRINGIFY}, // Required - Describes the purpose or contents of the data file.
{"DIFFUSE_GEOMETRY", WRITE_STRINGIFY}, // The diffuse geometry used. Allowed values are "sphere" or "opal".
{"MANUFACTURER", WRITE_STRINGIFY},
{"MANUFACTURE", WRITE_STRINGIFY}, // Some broken Fuji targets does store this value
{"PROD_DATE", WRITE_STRINGIFY}, // Identifies year and month of production of the target in the form yyyy:mm.
{"SERIAL", WRITE_STRINGIFY}, // Uniquely identifies individual physical target.
{"MATERIAL", WRITE_STRINGIFY}, // Identifies the material on which the target was produced using a code
// uniquely identifying th e material. This is intend ed to be used for IT8.7
// physical targets only (i.e . IT8.7/1 and IT8.7/2).
{"INSTRUMENTATION", WRITE_STRINGIFY}, // Used to report the specific instrumentation used (manufacturer and
// model number) to generate the data reported. This data will often
// provide more information about the particular data collected than an
// extensive list of specific details. This is particularly important for
// spectral data or data derived from spectrophotometry.
{"MEASUREMENT_SOURCE", WRITE_STRINGIFY}, // Illumination used for spectral measurements. This data helps provide
// a guide to the potential for issues of paper fluorescence, etc.
{"PRINT_CONDITIONS", WRITE_STRINGIFY}, // Used to define the characteristics of the printed sheet being reported.
// Where standard conditions have been defined (e.g., SWOP at nominal)
// named conditions may suffice. Otherwise, detailed information is
// needed.
{"SAMPLE_BACKING", WRITE_STRINGIFY}, // Identifies the backing material used behind the sample during
// measurement. Allowed values are "black", "white", or {"na".
{"CHISQ_DOF", WRITE_STRINGIFY}, // Degrees of freedom associated with the Chi squared statistic
// below properties are new in recent specs:
{"MEASUREMENT_GEOMETRY", WRITE_STRINGIFY}, // The type of measurement, either reflection or transmission, should be indicated
// along with details of the geometry and the aperture size and shape. For example,
// for transmission measurements it is important to identify 0/diffuse, diffuse/0,
// opal or integrating sphere, etc. For reflection it is important to identify 0/45,
// 45/0, sphere (specular included or excluded), etc.
{"FILTER", WRITE_STRINGIFY}, // Identifies the use of physical filter(s) during measurement. Typically used to
// denote the use of filters such as none, D65, Red, Green or Blue.
{"POLARIZATION", WRITE_STRINGIFY}, // Identifies the use of a physical polarization filter during measurement. Allowed
// values are {"yes", "white", "none" or "na".
{"WEIGHTING_FUNCTION", WRITE_PAIR}, // Indicates such functions as: the CIE standard observer functions used in the
// calculation of various data parameters (2 degree and 10 degree), CIE standard
// illuminant functions used in the calculation of various data parameters (e.g., D50,
// D65, etc.), density status response, etc. If used there shall be at least one
// name-value pair following the WEIGHTING_FUNCTION tag/keyword. The first attribute
// in the set shall be {"name" and shall identify the particular parameter used.
// The second shall be {"value" and shall provide the value associated with that name.
// For ASCII data, a string containing the Name and Value attribute pairs shall follow
// the weighting function keyword. A semi-colon separates attribute pairs from each
// other and within the attribute the name and value are separated by a comma.
{"COMPUTATIONAL_PARAMETER", WRITE_PAIR}, // Parameter that is used in computing a value from measured data. Name is the name
// of the calculation, parameter is the name of the parameter used in the calculation
// and value is the value of the parameter.
{"TARGET_TYPE", WRITE_STRINGIFY}, // The type of target being measured, e.g. IT8.7/1, IT8.7/3, user defined, etc.
{"COLORANT", WRITE_STRINGIFY}, // Identifies the colorant(s) used in creating the target.
{"TABLE_DESCRIPTOR", WRITE_STRINGIFY}, // Describes the purpose or contents of a data table.
{"TABLE_NAME", WRITE_STRINGIFY} // Provides a short name for a data table.
};
#define NUMPREDEFINEDPROPS (sizeof(PredefinedProperties)/sizeof(PROPERTY))
// Predefined sample types on dataset
static const char* PredefinedSampleID[] = {
"SAMPLE_ID", // Identifies sample that data represents
"STRING", // Identifies label, or other non-machine readable value.
// Value must begin and end with a " symbol
"CMYK_C", // Cyan component of CMYK data expressed as a percentage
"CMYK_M", // Magenta component of CMYK data expressed as a percentage
"CMYK_Y", // Yellow component of CMYK data expressed as a percentage
"CMYK_K", // Black component of CMYK data expressed as a percentage
"D_RED", // Red filter density
"D_GREEN", // Green filter density
"D_BLUE", // Blue filter density
"D_VIS", // Visual filter density
"D_MAJOR_FILTER", // Major filter d ensity
"RGB_R", // Red component of RGB data
"RGB_G", // Green component of RGB data
"RGB_B", // Blue com ponent of RGB data
"SPECTRAL_NM", // Wavelength of measurement expressed in nanometers
"SPECTRAL_PCT", // Percentage reflectance/transmittance
"SPECTRAL_DEC", // Reflectance/transmittance
"XYZ_X", // X component of tristimulus data
"XYZ_Y", // Y component of tristimulus data
"XYZ_Z", // Z component of tristimulus data
"XYY_X", // x component of chromaticity data
"XYY_Y", // y component of chromaticity data
"XYY_CAPY", // Y component of tristimulus data
"LAB_L", // L* component of Lab data
"LAB_A", // a* component of Lab data
"LAB_B", // b* component of Lab data
"LAB_C", // C*ab component of Lab data
"LAB_H", // hab component of Lab data
"LAB_DE", // CIE dE
"LAB_DE_94", // CIE dE using CIE 94
"LAB_DE_CMC", // dE using CMC
"LAB_DE_2000", // CIE dE using CIE DE 2000
"MEAN_DE", // Mean Delta E (LAB_DE) of samples compared to batch average
// (Used for data files for ANSI IT8.7/1 and IT8.7/2 targets)
"STDEV_X", // Standard deviation of X (tristimulus data)
"STDEV_Y", // Standard deviation of Y (tristimulus data)
"STDEV_Z", // Standard deviation of Z (tristimulus data)
"STDEV_L", // Standard deviation of L*
"STDEV_A", // Standard deviation of a*
"STDEV_B", // Standard deviation of b*
"STDEV_DE", // Standard deviation of CIE dE
"CHI_SQD_PAR"}; // The average of the standard deviations of L*, a* and b*. It is
// used to derive an estimate of the chi-squared parameter which is
// recommended as the predictor of the variability of dE
#define NUMPREDEFINEDSAMPLEID (sizeof(PredefinedSampleID)/sizeof(char *))
//Forward declaration of some internal functions
static void* AllocChunk(cmsIT8* it8, cmsUInt32Number size);
static
string* StringAlloc(cmsIT8* it8, int max)
{
string* s = (string*) AllocChunk(it8, sizeof(string));
if (s == NULL) return NULL;
s->it8 = it8;
s->max = max;
s->len = 0;
s->begin = (char*) AllocChunk(it8, s->max);
return s;
}
static
void StringClear(string* s)
{
s->len = 0;
s->begin[0] = 0;
}
static
cmsBool StringAppend(string* s, char c)
{
if (s->len + 1 >= s->max)
{
char* new_ptr;
s->max *= 10;
new_ptr = (char*) AllocChunk(s->it8, s->max);
if (new_ptr == NULL) return FALSE;
if (new_ptr != NULL && s->begin != NULL)
memcpy(new_ptr, s->begin, s->len);
s->begin = new_ptr;
}
if (s->begin != NULL)
{
s->begin[s->len++] = c;
s->begin[s->len] = 0;
}
return TRUE;
}
static
char* StringPtr(string* s)
{
return s->begin;
}
static
cmsBool StringCat(string* s, const char* c)
{
while (*c)
{
if (!StringAppend(s, *c)) return FALSE;
c++;
}
return TRUE;
}
// Checks whatever c is a separator
static
cmsBool isseparator(int c)
{
return (c == ' ') || (c == '\t');
}
// Checks whatever c is a valid identifier char
static
cmsBool ismiddle(int c)
{
return (!isseparator(c) && (c != '#') && (c !='\"') && (c != '\'') && (c > 32) && (c < 127));
}
// Checks whatsever c is a valid identifier middle char.
static
cmsBool isidchar(int c)
{
return isalnum(c) || ismiddle(c);
}
// Checks whatsever c is a valid identifier first char.
static
cmsBool isfirstidchar(int c)
{
return c != '-' && !isdigit(c) && ismiddle(c);
}
// Guess whether the supplied path looks like an absolute path
static
cmsBool isabsolutepath(const char *path)
{
char ThreeChars[4];
if(path == NULL)
return FALSE;
if (path[0] == 0)
return FALSE;
strncpy(ThreeChars, path, 3);
ThreeChars[3] = 0;
if(ThreeChars[0] == DIR_CHAR)
return TRUE;
#ifdef CMS_IS_WINDOWS_
if (isalpha((int) ThreeChars[0]) && ThreeChars[1] == ':')
return TRUE;
#endif
return FALSE;
}
// Makes a file path based on a given reference path
// NOTE: this function doesn't check if the path exists or even if it's legal
static
cmsBool BuildAbsolutePath(const char *relPath, const char *basePath, char *buffer, cmsUInt32Number MaxLen)
{
char *tail;
cmsUInt32Number len;
// Already absolute?
if (isabsolutepath(relPath)) {
memcpy(buffer, relPath, MaxLen);
buffer[MaxLen-1] = 0;
return TRUE;
}
// No, search for last
memcpy(buffer, basePath, MaxLen);
buffer[MaxLen-1] = 0;
tail = strrchr(buffer, DIR_CHAR);
if (tail == NULL) return FALSE; // Is not absolute and has no separators??
len = (cmsUInt32Number) (tail - buffer);
if (len >= MaxLen) return FALSE;
// No need to assure zero terminator over here
strncpy(tail + 1, relPath, MaxLen - len);
return TRUE;
}
// Make sure no exploit is being even tried
static
const char* NoMeta(const char* str)
{
if (strchr(str, '%') != NULL)
return "**** CORRUPTED FORMAT STRING ***";
return str;
}
// Syntax error
static
cmsBool SynError(cmsIT8* it8, const char *Txt, ...)
{
char Buffer[256], ErrMsg[1024];
va_list args;
va_start(args, Txt);
vsnprintf(Buffer, 255, Txt, args);
Buffer[255] = 0;
va_end(args);
snprintf(ErrMsg, 1023, "%s: Line %d, %s", it8->FileStack[it8 ->IncludeSP]->FileName, it8->lineno, Buffer);
ErrMsg[1023] = 0;
it8->sy = SSYNERROR;
cmsSignalError(it8 ->ContextID, cmsERROR_CORRUPTION_DETECTED, "%s", ErrMsg);
return FALSE;
}
// Check if current symbol is same as specified. issue an error else.
static
cmsBool Check(cmsIT8* it8, SYMBOL sy, const char* Err)
{
if (it8 -> sy != sy)
return SynError(it8, NoMeta(Err));
return TRUE;
}
// Read Next character from stream
static
void NextCh(cmsIT8* it8)
{
if (it8 -> FileStack[it8 ->IncludeSP]->Stream) {
it8 ->ch = fgetc(it8 ->FileStack[it8 ->IncludeSP]->Stream);
if (feof(it8 -> FileStack[it8 ->IncludeSP]->Stream)) {
if (it8 ->IncludeSP > 0) {
fclose(it8 ->FileStack[it8->IncludeSP--]->Stream);
it8 -> ch = ' '; // Whitespace to be ignored
} else
it8 ->ch = 0; // EOF
}
}
else {
it8->ch = *it8->Source;
if (it8->ch) it8->Source++;
}
}
// Try to see if current identifier is a keyword, if so return the referred symbol
static
SYMBOL BinSrchKey(const char *id, int NumKeys, const KEYWORD* TabKeys)
{
int l = 1;
int r = NumKeys;
int x, res;
while (r >= l)
{
x = (l+r)/2;
res = cmsstrcasecmp(id, TabKeys[x-1].id);
if (res == 0) return TabKeys[x-1].sy;
if (res < 0) r = x - 1;
else l = x + 1;
}
return SUNDEFINED;
}
// 10 ^n
static
cmsFloat64Number xpow10(int n)
{
return pow(10, (cmsFloat64Number) n);
}
// Reads a Real number, tries to follow from integer number
static
void ReadReal(cmsIT8* it8, cmsInt32Number inum)
{
it8->dnum = (cmsFloat64Number)inum;
while (isdigit(it8->ch)) {
it8->dnum = (cmsFloat64Number)it8->dnum * 10.0 + (cmsFloat64Number)(it8->ch - '0');
NextCh(it8);
}
if (it8->ch == '.') { // Decimal point
cmsFloat64Number frac = 0.0; // fraction
int prec = 0; // precision
NextCh(it8); // Eats dec. point
while (isdigit(it8->ch)) {
frac = frac * 10.0 + (cmsFloat64Number)(it8->ch - '0');
prec++;
NextCh(it8);
}
it8->dnum = it8->dnum + (frac / xpow10(prec));
}
// Exponent, example 34.00E+20
if (toupper(it8->ch) == 'E') {
cmsInt32Number e;
cmsInt32Number sgn;
NextCh(it8); sgn = 1;
if (it8->ch == '-') {
sgn = -1; NextCh(it8);
}
else
if (it8->ch == '+') {
sgn = +1;
NextCh(it8);
}
e = 0;
while (isdigit(it8->ch)) {
cmsInt32Number digit = (it8->ch - '0');
if ((cmsFloat64Number)e * 10.0 + (cmsFloat64Number)digit < (cmsFloat64Number)+2147483647.0)
e = e * 10 + digit;
NextCh(it8);
}
e = sgn*e;
it8->dnum = it8->dnum * xpow10(e);
}
}
// Parses a float number
// This can not call directly atof because it uses locale dependent
// parsing, while CCMX files always use . as decimal separator
static
cmsFloat64Number ParseFloatNumber(const char *Buffer)
{
cmsFloat64Number dnum = 0.0;
int sign = 1;
// keep safe
if (Buffer == NULL) return 0.0;
if (*Buffer == '-' || *Buffer == '+') {
sign = (*Buffer == '-') ? -1 : 1;
Buffer++;
}
while (*Buffer && isdigit((int)*Buffer)) {
dnum = dnum * 10.0 + (*Buffer - '0');
if (*Buffer) Buffer++;
}
if (*Buffer == '.') {
cmsFloat64Number frac = 0.0; // fraction
int prec = 0; // precision
if (*Buffer) Buffer++;
while (*Buffer && isdigit((int)*Buffer)) {
frac = frac * 10.0 + (*Buffer - '0');
prec++;
if (*Buffer) Buffer++;
}
dnum = dnum + (frac / xpow10(prec));
}
// Exponent, example 34.00E+20
if (*Buffer && toupper(*Buffer) == 'E') {
int e;
int sgn;
if (*Buffer) Buffer++;
sgn = 1;
if (*Buffer == '-') {
sgn = -1;
if (*Buffer) Buffer++;
}
else
if (*Buffer == '+') {
sgn = +1;
if (*Buffer) Buffer++;
}
e = 0;
while (*Buffer && isdigit((int)*Buffer)) {
cmsInt32Number digit = (*Buffer - '0');
if ((cmsFloat64Number)e * 10.0 + digit < (cmsFloat64Number)+2147483647.0)
e = e * 10 + digit;
if (*Buffer) Buffer++;
}
e = sgn*e;
dnum = dnum * xpow10(e);
}
return sign * dnum;
}
// Reads a string, special case to avoid infinite recursion on .include
static
void InStringSymbol(cmsIT8* it8)
{
while (isseparator(it8->ch))
NextCh(it8);
if (it8->ch == '\'' || it8->ch == '\"')
{
int sng;
sng = it8->ch;
StringClear(it8->str);
NextCh(it8);
while (it8->ch != sng) {
if (it8->ch == '\n' || it8->ch == '\r' || it8->ch == 0) break;
else {
if (!StringAppend(it8->str, (char)it8->ch)) {
SynError(it8, "Out of memory");
return;
}
NextCh(it8);
}
}
it8->sy = SSTRING;
NextCh(it8);
}
else
SynError(it8, "String expected");
}
// Reads next symbol
static
void InSymbol(cmsIT8* it8)
{
SYMBOL key;
do {
while (isseparator(it8->ch))
NextCh(it8);
if (isfirstidchar(it8->ch)) { // Identifier
StringClear(it8->id);
do {
if (!StringAppend(it8->id, (char)it8->ch)) {
SynError(it8, "Out of memory");
return;
}
NextCh(it8);
} while (isidchar(it8->ch));
key = BinSrchKey(StringPtr(it8->id),
it8->IsCUBE ? NUMKEYS_CUBE : NUMKEYS_IT8,
it8->IsCUBE ? TabKeysCUBE : TabKeysIT8);
if (key == SUNDEFINED) it8->sy = SIDENT;
else it8->sy = key;
}
else // Is a number?
if (isdigit(it8->ch) || it8->ch == '.' || it8->ch == '-' || it8->ch == '+')
{
int sign = 1;
if (it8->ch == '-') {
sign = -1;
NextCh(it8);
}
it8->inum = 0;
it8->sy = SINUM;
if (it8->ch == '0') { // 0xnnnn (Hexa) or 0bnnnn (Binary)
NextCh(it8);
if (toupper(it8->ch) == 'X') {
int j;
NextCh(it8);
while (isxdigit(it8->ch))
{
it8->ch = toupper(it8->ch);
if (it8->ch >= 'A' && it8->ch <= 'F') j = it8->ch -'A'+10;
else j = it8->ch - '0';
if ((cmsFloat64Number) it8->inum * 16.0 + (cmsFloat64Number) j > (cmsFloat64Number)+2147483647.0)
{
SynError(it8, "Invalid hexadecimal number");
return;
}
it8->inum = it8->inum * 16 + j;
NextCh(it8);
}
return;
}
if (toupper(it8->ch) == 'B') { // Binary
int j;
NextCh(it8);
while (it8->ch == '0' || it8->ch == '1')
{
j = it8->ch - '0';
if ((cmsFloat64Number) it8->inum * 2.0 + j > (cmsFloat64Number)+2147483647.0)
{
SynError(it8, "Invalid binary number");
return;
}
it8->inum = it8->inum * 2 + j;
NextCh(it8);
}
return;
}
}
while (isdigit(it8->ch)) {
cmsInt32Number digit = (it8->ch - '0');
if ((cmsFloat64Number) it8->inum * 10.0 + (cmsFloat64Number) digit > (cmsFloat64Number) +2147483647.0) {
ReadReal(it8, it8->inum);
it8->sy = SDNUM;
it8->dnum *= sign;
return;
}
it8->inum = it8->inum * 10 + digit;
NextCh(it8);
}
if (it8->ch == '.') {
ReadReal(it8, it8->inum);
it8->sy = SDNUM;
it8->dnum *= sign;
return;
}
it8 -> inum *= sign;
// Special case. Numbers followed by letters are taken as identifiers
if (isidchar(it8 ->ch)) {
char buffer[127];
if (it8 ->sy == SINUM) {
snprintf(buffer, sizeof(buffer), "%d", it8->inum);
}
else {
snprintf(buffer, sizeof(buffer), it8 ->DoubleFormatter, it8->dnum);
}
StringClear(it8->id);
if (!StringCat(it8->id, buffer)) {
SynError(it8, "Out of memory");
return;
}
do {
if (!StringAppend(it8->id, (char)it8->ch)) {
SynError(it8, "Out of memory");
return;
}
NextCh(it8);
} while (isidchar(it8->ch));
it8->sy = SIDENT;
}
return;
}
else
switch ((int) it8->ch) {
// Eof stream markers
case '\x1a':
case 0:
case -1:
it8->sy = SEOF;
break;
// Next line
case '\r':
NextCh(it8);
if (it8->ch == '\n')
NextCh(it8);
it8->sy = SEOLN;
it8->lineno++;
break;
case '\n':
NextCh(it8);
it8->sy = SEOLN;
it8->lineno++;
break;
// Comment
case '#':
NextCh(it8);
while (it8->ch && it8->ch != '\n' && it8->ch != '\r')
NextCh(it8);
it8->sy = SCOMMENT;
break;
// String.
case '\'':
case '\"':
InStringSymbol(it8);
break;
default:
SynError(it8, "Unrecognized character: 0x%x", it8 ->ch);
return;
}
} while (it8->sy == SCOMMENT);
// Handle the include special token
if (it8 -> sy == SINCLUDE) {
FILECTX* FileNest;
if(it8 -> IncludeSP >= (MAXINCLUDE-1)) {
SynError(it8, "Too many recursion levels");
return;
}
InStringSymbol(it8);
if (!Check(it8, SSTRING, "Filename expected"))
return;
FileNest = it8 -> FileStack[it8 -> IncludeSP + 1];
if(FileNest == NULL) {
FileNest = it8 ->FileStack[it8 -> IncludeSP + 1] = (FILECTX*)AllocChunk(it8, sizeof(FILECTX));
if (FileNest == NULL) {
SynError(it8, "Out of memory");
return;
}
}
if (BuildAbsolutePath(StringPtr(it8->str),
it8->FileStack[it8->IncludeSP]->FileName,
FileNest->FileName, cmsMAX_PATH-1) == FALSE) {
SynError(it8, "File path too long");
return;
}
FileNest->Stream = fopen(FileNest->FileName, "rt");
if (FileNest->Stream == NULL) {
SynError(it8, "File %s not found", FileNest->FileName);
return;
}
it8->IncludeSP++;
it8 ->ch = ' ';
InSymbol(it8);
}
}
// Checks end of line separator
static
cmsBool CheckEOLN(cmsIT8* it8)
{
if (!Check(it8, SEOLN, "Expected separator")) return FALSE;
while (it8->sy == SEOLN)
InSymbol(it8);
return TRUE;
}
// Skip a symbol
static
void Skip(cmsIT8* it8, SYMBOL sy)
{
if (it8->sy == sy && it8->sy != SEOF && it8->sy != SSYNERROR)
InSymbol(it8);
}
// Skip multiple EOLN
static
void SkipEOLN(cmsIT8* it8)
{
while (it8->sy == SEOLN) {
InSymbol(it8);
}
}
// Returns a string holding current value
static
cmsBool GetVal(cmsIT8* it8, char* Buffer, cmsUInt32Number max, const char* ErrorTitle)
{
switch (it8->sy) {
case SEOLN: // Empty value
Buffer[0]=0;
break;
case SIDENT: strncpy(Buffer, StringPtr(it8->id), max);
Buffer[max-1]=0;
break;
case SINUM: snprintf(Buffer, max, "%d", it8 -> inum); break;
case SDNUM: snprintf(Buffer, max, it8->DoubleFormatter, it8 -> dnum); break;
case SSTRING: strncpy(Buffer, StringPtr(it8->str), max);
Buffer[max-1] = 0;
break;
default:
return SynError(it8, "%s", ErrorTitle);
}
Buffer[max] = 0;
return TRUE;
}
// ---------------------------------------------------------- Table
static
TABLE* GetTable(cmsIT8* it8)
{
if ((it8 -> nTable >= it8 ->TablesCount)) {
SynError(it8, "Table %d out of sequence", it8 -> nTable);
return it8 -> Tab;
}
return it8 ->Tab + it8 ->nTable;
}
// ---------------------------------------------------------- Memory management
// Frees an allocator and owned memory
void CMSEXPORT cmsIT8Free(cmsHANDLE hIT8)
{
cmsIT8* it8 = (cmsIT8*) hIT8;
if (it8 == NULL)
return;
if (it8->MemorySink) {
OWNEDMEM* p;
OWNEDMEM* n;
for (p = it8->MemorySink; p != NULL; p = n) {
n = p->Next;
if (p->Ptr) _cmsFree(it8 ->ContextID, p->Ptr);
_cmsFree(it8 ->ContextID, p);
}
}
if (it8->MemoryBlock)
_cmsFree(it8 ->ContextID, it8->MemoryBlock);
_cmsFree(it8 ->ContextID, it8);
}
// Allocates a chunk of data, keep linked list
static
void* AllocBigBlock(cmsIT8* it8, cmsUInt32Number size)
{
OWNEDMEM* ptr1;
void* ptr = _cmsMallocZero(it8->ContextID, size);
if (ptr != NULL) {
ptr1 = (OWNEDMEM*) _cmsMallocZero(it8 ->ContextID, sizeof(OWNEDMEM));
if (ptr1 == NULL) {
_cmsFree(it8 ->ContextID, ptr);
return NULL;
}
ptr1-> Ptr = ptr;
ptr1-> Next = it8 -> MemorySink;
it8 -> MemorySink = ptr1;
}
return ptr;
}
// Suballocator.
static
void* AllocChunk(cmsIT8* it8, cmsUInt32Number size)
{
cmsUInt32Number Free = it8 ->Allocator.BlockSize - it8 ->Allocator.Used;
cmsUInt8Number* ptr;
size = _cmsALIGNMEM(size);
if (size == 0) return NULL;
if (size > Free) {
cmsUInt8Number* new_block;
if (it8 -> Allocator.BlockSize == 0)
it8 -> Allocator.BlockSize = 20*1024;
else
it8 ->Allocator.BlockSize *= 2;
if (it8 ->Allocator.BlockSize < size)
it8 ->Allocator.BlockSize = size;
it8 ->Allocator.Used = 0;
new_block = (cmsUInt8Number*)AllocBigBlock(it8, it8->Allocator.BlockSize);
if (new_block == NULL)
return NULL;
it8->Allocator.Block = new_block;
}
if (it8->Allocator.Block == NULL)
return NULL;
ptr = it8 ->Allocator.Block + it8 ->Allocator.Used;
it8 ->Allocator.Used += size;
return (void*) ptr;
}
// Allocates a string
static
char *AllocString(cmsIT8* it8, const char* str)
{
cmsUInt32Number Size;
char *ptr;
if (str == NULL) return NULL;
Size = (cmsUInt32Number)strlen(str) + 1;
ptr = (char *) AllocChunk(it8, Size);
if (ptr) memcpy(ptr, str, Size-1);
return ptr;
}
// Searches through linked list
static
cmsBool IsAvailableOnList(KEYVALUE* p, const char* Key, const char* Subkey, KEYVALUE** LastPtr)
{
if (LastPtr) *LastPtr = p;
for (; p != NULL; p = p->Next) {
if (LastPtr) *LastPtr = p;
if (*Key != '#') { // Comments are ignored
if (cmsstrcasecmp(Key, p->Keyword) == 0)
break;
}
}
if (p == NULL)
return FALSE;
if (Subkey == 0)
return TRUE;
for (; p != NULL; p = p->NextSubkey) {
if (p ->Subkey == NULL) continue;
if (LastPtr) *LastPtr = p;
if (cmsstrcasecmp(Subkey, p->Subkey) == 0)
return TRUE;
}
return FALSE;
}
// Add a property into a linked list
static
KEYVALUE* AddToList(cmsIT8* it8, KEYVALUE** Head, const char *Key, const char *Subkey, const char* xValue, WRITEMODE WriteAs)
{
KEYVALUE* p;
KEYVALUE* last;
// Check if property is already in list
if (IsAvailableOnList(*Head, Key, Subkey, &p)) {
// This may work for editing properties
if (cmsstrcasecmp(Key, "NUMBER_OF_FIELDS") == 0 ||
cmsstrcasecmp(Key, "NUMBER_OF_SETS") == 0) {
SynError(it8, "duplicate key <%s>", Key);
return NULL;
}
}
else {
last = p;
// Allocate the container
p = (KEYVALUE*) AllocChunk(it8, sizeof(KEYVALUE));
if (p == NULL)
{
SynError(it8, "AddToList: out of memory");
return NULL;
}
// Store name and value
p->Keyword = AllocString(it8, Key);
p->Subkey = (Subkey == NULL) ? NULL : AllocString(it8, Subkey);
// Keep the container in our list
if (*Head == NULL) {
*Head = p;
}
else
{
if (Subkey != NULL && last != NULL) {
last->NextSubkey = p;
// If Subkey is not null, then last is the last property with the same key,
// but not necessarily is the last property in the list, so we need to move
// to the actual list end
while (last->Next != NULL)
last = last->Next;
}
if (last != NULL) last->Next = p;
}
p->Next = NULL;
p->NextSubkey = NULL;
}
p->WriteAs = WriteAs;
if (xValue != NULL) {
p->Value = AllocString(it8, xValue);
}
else {
p->Value = NULL;
}
return p;
}
static
KEYVALUE* AddAvailableProperty(cmsIT8* it8, const char* Key, WRITEMODE as)
{
return AddToList(it8, &it8->ValidKeywords, Key, NULL, NULL, as);
}
static
KEYVALUE* AddAvailableSampleID(cmsIT8* it8, const char* Key)
{
return AddToList(it8, &it8->ValidSampleID, Key, NULL, NULL, WRITE_UNCOOKED);
}
static
cmsBool AllocTable(cmsIT8* it8)
{
TABLE* t;
if (it8->TablesCount >= (MAXTABLES-1))
return FALSE;
t = it8 ->Tab + it8 ->TablesCount;
t->HeaderList = NULL;
t->DataFormat = NULL;
t->Data = NULL;
it8 ->TablesCount++;
return TRUE;
}
cmsInt32Number CMSEXPORT cmsIT8SetTable(cmsHANDLE IT8, cmsUInt32Number nTable)
{
cmsIT8* it8 = (cmsIT8*) IT8;
if (nTable >= it8 ->TablesCount) {
if (nTable == it8 ->TablesCount) {
if (!AllocTable(it8)) {
SynError(it8, "Too many tables");
return -1;
}
}
else {
SynError(it8, "Table %d is out of sequence", nTable);
return -1;
}
}
it8 ->nTable = nTable;
return (cmsInt32Number) nTable;
}
// Init an empty container
cmsHANDLE CMSEXPORT cmsIT8Alloc(cmsContext ContextID)
{
cmsIT8* it8;
cmsUInt32Number i;
it8 = (cmsIT8*) _cmsMallocZero(ContextID, sizeof(cmsIT8));
if (it8 == NULL) return NULL;
AllocTable(it8);
it8->MemoryBlock = NULL;
it8->MemorySink = NULL;
it8->IsCUBE = FALSE;
it8 ->nTable = 0;
it8->ContextID = ContextID;
it8->Allocator.Used = 0;
it8->Allocator.Block = NULL;
it8->Allocator.BlockSize = 0;
it8->ValidKeywords = NULL;
it8->ValidSampleID = NULL;
it8 -> sy = SUNDEFINED;
it8 -> ch = ' ';
it8 -> Source = NULL;
it8 -> inum = 0;
it8 -> dnum = 0.0;
it8->FileStack[0] = (FILECTX*)AllocChunk(it8, sizeof(FILECTX));
it8->IncludeSP = 0;
it8 -> lineno = 1;
it8->id = StringAlloc(it8, MAXSTR);
it8->str = StringAlloc(it8, MAXSTR);
strcpy(it8->DoubleFormatter, DEFAULT_DBL_FORMAT);
cmsIT8SetSheetType((cmsHANDLE) it8, "CGATS.17");
// Initialize predefined properties & data
for (i=0; i < NUMPREDEFINEDPROPS; i++)
AddAvailableProperty(it8, PredefinedProperties[i].id, PredefinedProperties[i].as);
for (i=0; i < NUMPREDEFINEDSAMPLEID; i++)
AddAvailableSampleID(it8, PredefinedSampleID[i]);
return (cmsHANDLE) it8;
}
const char* CMSEXPORT cmsIT8GetSheetType(cmsHANDLE hIT8)
{
return GetTable((cmsIT8*) hIT8)->SheetType;
}
cmsBool CMSEXPORT cmsIT8SetSheetType(cmsHANDLE hIT8, const char* Type)
{
TABLE* t = GetTable((cmsIT8*) hIT8);
strncpy(t ->SheetType, Type, MAXSTR-1);
t ->SheetType[MAXSTR-1] = 0;
return TRUE;
}
cmsBool CMSEXPORT cmsIT8SetComment(cmsHANDLE hIT8, const char* Val)
{
cmsIT8* it8 = (cmsIT8*) hIT8;
if (!Val) return FALSE;
if (!*Val) return FALSE;
return AddToList(it8, &GetTable(it8)->HeaderList, "# ", NULL, Val, WRITE_UNCOOKED) != NULL;
}
// Sets a property
cmsBool CMSEXPORT cmsIT8SetPropertyStr(cmsHANDLE hIT8, const char* Key, const char *Val)
{
cmsIT8* it8 = (cmsIT8*) hIT8;
if (!Val) return FALSE;
if (!*Val) return FALSE;
return AddToList(it8, &GetTable(it8)->HeaderList, Key, NULL, Val, WRITE_STRINGIFY) != NULL;
}
cmsBool CMSEXPORT cmsIT8SetPropertyDbl(cmsHANDLE hIT8, const char* cProp, cmsFloat64Number Val)
{
cmsIT8* it8 = (cmsIT8*) hIT8;
char Buffer[1024];
snprintf(Buffer, 1023, it8->DoubleFormatter, Val);
return AddToList(it8, &GetTable(it8)->HeaderList, cProp, NULL, Buffer, WRITE_UNCOOKED) != NULL;
}
cmsBool CMSEXPORT cmsIT8SetPropertyHex(cmsHANDLE hIT8, const char* cProp, cmsUInt32Number Val)
{
cmsIT8* it8 = (cmsIT8*) hIT8;
char Buffer[1024];
snprintf(Buffer, 1023, "%u", Val);
return AddToList(it8, &GetTable(it8)->HeaderList, cProp, NULL, Buffer, WRITE_HEXADECIMAL) != NULL;
}
cmsBool CMSEXPORT cmsIT8SetPropertyUncooked(cmsHANDLE hIT8, const char* Key, const char* Buffer)
{
cmsIT8* it8 = (cmsIT8*) hIT8;
return AddToList(it8, &GetTable(it8)->HeaderList, Key, NULL, Buffer, WRITE_UNCOOKED) != NULL;
}
cmsBool CMSEXPORT cmsIT8SetPropertyMulti(cmsHANDLE hIT8, const char* Key, const char* SubKey, const char *Buffer)
{
cmsIT8* it8 = (cmsIT8*) hIT8;
return AddToList(it8, &GetTable(it8)->HeaderList, Key, SubKey, Buffer, WRITE_PAIR) != NULL;
}
// Gets a property
const char* CMSEXPORT cmsIT8GetProperty(cmsHANDLE hIT8, const char* Key)
{
cmsIT8* it8 = (cmsIT8*) hIT8;
KEYVALUE* p;
if (IsAvailableOnList(GetTable(it8) -> HeaderList, Key, NULL, &p))
{
return p -> Value;
}
return NULL;
}
cmsFloat64Number CMSEXPORT cmsIT8GetPropertyDbl(cmsHANDLE hIT8, const char* cProp)
{
const char *v = cmsIT8GetProperty(hIT8, cProp);
if (v == NULL) return 0.0;
return ParseFloatNumber(v);
}
const char* CMSEXPORT cmsIT8GetPropertyMulti(cmsHANDLE hIT8, const char* Key, const char *SubKey)
{
cmsIT8* it8 = (cmsIT8*) hIT8;
KEYVALUE* p;
if (IsAvailableOnList(GetTable(it8) -> HeaderList, Key, SubKey, &p)) {
return p -> Value;
}
return NULL;
}
// ----------------------------------------------------------------- Datasets
// A safe atoi that returns 0 when NULL input is given
static
cmsInt32Number satoi(const char* b)
{
int n;
if (b == NULL) return 0;
n = atoi(b);
if (n > 0x7ffffff0L) return 0x7ffffff0L;
if (n < -0x7ffffff0L) return -0x7ffffff0L;
return (cmsInt32Number)n;
}
static
cmsBool AllocateDataFormat(cmsIT8* it8)
{
cmsUInt32Number size;
TABLE* t = GetTable(it8);
if (t->DataFormat) return TRUE; // Already allocated
t->nSamples = satoi(cmsIT8GetProperty(it8, "NUMBER_OF_FIELDS"));
if (t->nSamples <= 0 || t->nSamples > 0x7ffe) {
SynError(it8, "Wrong NUMBER_OF_FIELDS");
return FALSE;
}
size = ((cmsUInt32Number)t->nSamples + 1) * sizeof(char*);
t->DataFormat = (char**)AllocChunk(it8, size);
if (t->DataFormat == NULL) {
SynError(it8, "Unable to allocate dataFormat array");
return FALSE;
}
return TRUE;
}
static
const char *GetDataFormat(cmsIT8* it8, int n)
{
TABLE* t = GetTable(it8);
if (t->DataFormat)
return t->DataFormat[n];
return NULL;
}
static
cmsBool SetDataFormat(cmsIT8* it8, int n, const char *label)
{
TABLE* t = GetTable(it8);
if (!t->DataFormat) {
if (!AllocateDataFormat(it8))
return FALSE;
}
if (n >= t -> nSamples) {
SynError(it8, "More than NUMBER_OF_FIELDS fields.");
return FALSE;
}
if (t->DataFormat) {
t->DataFormat[n] = AllocString(it8, label);
if (t->DataFormat[n] == NULL) return FALSE;
}
return TRUE;
}
cmsBool CMSEXPORT cmsIT8SetDataFormat(cmsHANDLE h, int n, const char *Sample)
{
cmsIT8* it8 = (cmsIT8*)h;
return SetDataFormat(it8, n, Sample);
}
// Convert to binary
static
const char* satob(const char* v)
{
cmsUInt32Number x;
static char buf[33];
char *s = buf + 33;
if (v == NULL) return "0";
x = atoi(v);
*--s = 0;
if (!x) *--s = '0';
for (; x; x /= 2) *--s = '0' + x%2;
return s;
}
static
cmsBool AllocateDataSet(cmsIT8* it8)
{
TABLE* t = GetTable(it8);
if (t -> Data) return TRUE; // Already allocated
t-> nSamples = satoi(cmsIT8GetProperty(it8, "NUMBER_OF_FIELDS"));
t-> nPatches = satoi(cmsIT8GetProperty(it8, "NUMBER_OF_SETS"));
if (t -> nSamples < 0 || t->nSamples > 0x7ffe || t->nPatches < 0 || t->nPatches > 0x7ffe ||
(t->nPatches * t->nSamples) > 200000)
{
SynError(it8, "AllocateDataSet: too much data");
return FALSE;
}
else {
// Some dumb analyzers warns of possible overflow here, just take a look couple of lines above.
t->Data = (char**)AllocChunk(it8, ((cmsUInt32Number)t->nSamples + 1) * ((cmsUInt32Number)t->nPatches + 1) * sizeof(char*));
if (t->Data == NULL) {
SynError(it8, "AllocateDataSet: Unable to allocate data array");
return FALSE;
}
}
return TRUE;
}
static
char* GetData(cmsIT8* it8, int nSet, int nField)
{
TABLE* t = GetTable(it8);
int nSamples = t -> nSamples;
int nPatches = t -> nPatches;
if (nSet < 0 || nSet >= nPatches || nField < 0 || nField >= nSamples)
return NULL;
if (!t->Data) return NULL;
return t->Data [nSet * nSamples + nField];
}
static
cmsBool SetData(cmsIT8* it8, int nSet, int nField, const char *Val)
{
char* ptr;
TABLE* t = GetTable(it8);
if (!t->Data) {
if (!AllocateDataSet(it8)) return FALSE;
}
if (!t->Data) return FALSE;
if (nSet > t -> nPatches || nSet < 0) {
return SynError(it8, "Patch %d out of range, there are %d patches", nSet, t -> nPatches);
}
if (nField > t ->nSamples || nField < 0) {
return SynError(it8, "Sample %d out of range, there are %d samples", nField, t ->nSamples);
}
ptr = AllocString(it8, Val);
if (ptr == NULL)
return FALSE;
t->Data [nSet * t -> nSamples + nField] = ptr;
return TRUE;
}
// --------------------------------------------------------------- File I/O
// Writes a string to file
static
void WriteStr(SAVESTREAM* f, const char *str)
{
cmsUInt32Number len;
if (str == NULL)
str = " ";
// Length to write
len = (cmsUInt32Number) strlen(str);
f ->Used += len;
if (f ->stream) { // Should I write it to a file?
if (fwrite(str, 1, len, f->stream) != len) {
cmsSignalError(0, cmsERROR_WRITE, "Write to file error in CGATS parser");
return;
}
}
else { // Or to a memory block?
if (f ->Base) { // Am I just counting the bytes?
if (f ->Used > f ->Max) {
cmsSignalError(0, cmsERROR_WRITE, "Write to memory overflows in CGATS parser");
return;
}
memmove(f ->Ptr, str, len);
f->Ptr += len;
}
}
}
// Write formatted
static
void Writef(SAVESTREAM* f, const char* frm, ...)
{
char Buffer[4096];
va_list args;
va_start(args, frm);
vsnprintf(Buffer, 4095, frm, args);
Buffer[4095] = 0;
WriteStr(f, Buffer);
va_end(args);
}
// Writes full header
static
void WriteHeader(cmsIT8* it8, SAVESTREAM* fp)
{
KEYVALUE* p;
TABLE* t = GetTable(it8);
// Writes the type
WriteStr(fp, t->SheetType);
WriteStr(fp, "\n");
for (p = t->HeaderList; (p != NULL); p = p->Next)
{
if (*p ->Keyword == '#') {
char* Pt;
WriteStr(fp, "#\n# ");
for (Pt = p ->Value; *Pt; Pt++) {
Writef(fp, "%c", *Pt);
if (*Pt == '\n') {
WriteStr(fp, "# ");
}
}
WriteStr(fp, "\n#\n");
continue;
}
if (!IsAvailableOnList(it8-> ValidKeywords, p->Keyword, NULL, NULL)) {
#ifdef CMS_STRICT_CGATS
WriteStr(fp, "KEYWORD\t\"");
WriteStr(fp, p->Keyword);
WriteStr(fp, "\"\n");
#endif
AddAvailableProperty(it8, p->Keyword, WRITE_UNCOOKED);
}
WriteStr(fp, p->Keyword);
if (p->Value) {
switch (p ->WriteAs) {
case WRITE_UNCOOKED:
Writef(fp, "\t%s", p ->Value);
break;
case WRITE_STRINGIFY:
Writef(fp, "\t\"%s\"", p->Value );
break;
case WRITE_HEXADECIMAL:
Writef(fp, "\t0x%X", satoi(p ->Value));
break;
case WRITE_BINARY:
Writef(fp, "\t0b%s", satob(p ->Value));
break;
case WRITE_PAIR:
Writef(fp, "\t\"%s,%s\"", p->Subkey, p->Value);
break;
default: SynError(it8, "Unknown write mode %d", p ->WriteAs);
return;
}
}
WriteStr (fp, "\n");
}
}
// Writes the data format
static
void WriteDataFormat(SAVESTREAM* fp, cmsIT8* it8)
{
int i, nSamples;
TABLE* t = GetTable(it8);
if (!t -> DataFormat) return;
WriteStr(fp, "BEGIN_DATA_FORMAT\n");
WriteStr(fp, " ");
nSamples = satoi(cmsIT8GetProperty(it8, "NUMBER_OF_FIELDS"));
if (nSamples <= t->nSamples) {
for (i = 0; i < nSamples; i++) {
WriteStr(fp, t->DataFormat[i]);
WriteStr(fp, ((i == (nSamples - 1)) ? "\n" : "\t"));
}
}
WriteStr (fp, "END_DATA_FORMAT\n");
}
// Writes data array
static
void WriteData(SAVESTREAM* fp, cmsIT8* it8)
{
int i, j, nPatches;
TABLE* t = GetTable(it8);
if (!t->Data) return;
WriteStr (fp, "BEGIN_DATA\n");
nPatches = satoi(cmsIT8GetProperty(it8, "NUMBER_OF_SETS"));
if (nPatches <= t->nPatches) {
for (i = 0; i < nPatches; i++) {
WriteStr(fp, " ");
for (j = 0; j < t->nSamples; j++) {
char* ptr = t->Data[i * t->nSamples + j];
if (ptr == NULL) WriteStr(fp, "\"\"");
else {
// If value contains whitespace, enclose within quote
if (strchr(ptr, ' ') != NULL) {
WriteStr(fp, "\"");
WriteStr(fp, ptr);
WriteStr(fp, "\"");
}
else
WriteStr(fp, ptr);
}
WriteStr(fp, ((j == (t->nSamples - 1)) ? "\n" : "\t"));
}
}
}
WriteStr (fp, "END_DATA\n");
}
// Saves whole file
cmsBool CMSEXPORT cmsIT8SaveToFile(cmsHANDLE hIT8, const char* cFileName)
{
SAVESTREAM sd;
cmsUInt32Number i;
cmsIT8* it8 = (cmsIT8*) hIT8;
memset(&sd, 0, sizeof(sd));
sd.stream = fopen(cFileName, "wt");
if (!sd.stream) return FALSE;
for (i=0; i < it8 ->TablesCount; i++) {
TABLE* t;
if (cmsIT8SetTable(hIT8, i) < 0) goto Error;
/**
* Check for wrong data
*/
t = GetTable(it8);
if (t->Data == NULL) goto Error;
if (t->DataFormat == NULL) goto Error;
WriteHeader(it8, &sd);
WriteDataFormat(&sd, it8);
WriteData(&sd, it8);
}
if (fclose(sd.stream) != 0) return FALSE;
return TRUE;
Error:
fclose(sd.stream);
return FALSE;
}
// Saves to memory
cmsBool CMSEXPORT cmsIT8SaveToMem(cmsHANDLE hIT8, void *MemPtr, cmsUInt32Number* BytesNeeded)
{
SAVESTREAM sd;
cmsUInt32Number i;
cmsIT8* it8 = (cmsIT8*) hIT8;
memset(&sd, 0, sizeof(sd));
sd.stream = NULL;
sd.Base = (cmsUInt8Number*) MemPtr;
sd.Ptr = sd.Base;
sd.Used = 0;
if (sd.Base && (*BytesNeeded > 0)) {
sd.Max = (*BytesNeeded) - 1; // Write to memory?
}
else
sd.Max = 0; // Just counting the needed bytes
for (i=0; i < it8 ->TablesCount; i++) {
cmsIT8SetTable(hIT8, i);
WriteHeader(it8, &sd);
WriteDataFormat(&sd, it8);
WriteData(&sd, it8);
}
sd.Used++; // The \0 at the very end
if (sd.Base)
*sd.Ptr = 0;
*BytesNeeded = sd.Used;
return TRUE;
}
// -------------------------------------------------------------- Higher level parsing
static
cmsBool DataFormatSection(cmsIT8* it8)
{
int iField = 0;
TABLE* t = GetTable(it8);
InSymbol(it8); // Eats "BEGIN_DATA_FORMAT"
CheckEOLN(it8);
while (it8->sy != SEND_DATA_FORMAT &&
it8->sy != SEOLN &&
it8->sy != SEOF &&
it8->sy != SSYNERROR) {
if (it8->sy != SIDENT) {
return SynError(it8, "Sample type expected");
}
if (!SetDataFormat(it8, iField, StringPtr(it8->id))) return FALSE;
iField++;
InSymbol(it8);
SkipEOLN(it8);
}
SkipEOLN(it8);
Skip(it8, SEND_DATA_FORMAT);
SkipEOLN(it8);
if (iField != t ->nSamples) {
SynError(it8, "Count mismatch. NUMBER_OF_FIELDS was %d, found %d\n", t ->nSamples, iField);
}
return TRUE;
}
static
cmsBool DataSection (cmsIT8* it8)
{
int iField = 0;
int iSet = 0;
char Buffer[256];
TABLE* t = GetTable(it8);
InSymbol(it8); // Eats "BEGIN_DATA"
CheckEOLN(it8);
if (!t->Data) {
if (!AllocateDataSet(it8)) return FALSE;
}
while (it8->sy != SEND_DATA && it8->sy != SEOF && it8->sy != SSYNERROR)
{
if (iField >= t -> nSamples) {
iField = 0;
iSet++;
}
if (it8->sy != SEND_DATA && it8->sy != SEOF && it8->sy != SSYNERROR) {
switch (it8->sy)
{
// To keep very long data
case SIDENT:
if (!SetData(it8, iSet, iField, StringPtr(it8->id)))
return FALSE;
break;
case SSTRING:
if (!SetData(it8, iSet, iField, StringPtr(it8->str)))
return FALSE;
break;
default:
if (!GetVal(it8, Buffer, 255, "Sample data expected"))
return FALSE;
if (!SetData(it8, iSet, iField, Buffer))
return FALSE;
}
iField++;
InSymbol(it8);
SkipEOLN(it8);
}
}
SkipEOLN(it8);
Skip(it8, SEND_DATA);
SkipEOLN(it8);
// Check for data completion.
if ((iSet+1) != t -> nPatches)
return SynError(it8, "Count mismatch. NUMBER_OF_SETS was %d, found %d\n", t ->nPatches, iSet+1);
return TRUE;
}
static
cmsBool HeaderSection(cmsIT8* it8)
{
char VarName[MAXID];
char Buffer[MAXSTR];
KEYVALUE* Key;
while (it8->sy != SEOF &&
it8->sy != SSYNERROR &&
it8->sy != SBEGIN_DATA_FORMAT &&
it8->sy != SBEGIN_DATA) {
switch (it8 -> sy) {
case SKEYWORD:
InSymbol(it8);
if (!GetVal(it8, Buffer, MAXSTR-1, "Keyword expected")) return FALSE;
if (!AddAvailableProperty(it8, Buffer, WRITE_UNCOOKED)) return FALSE;
InSymbol(it8);
break;
case SDATA_FORMAT_ID:
InSymbol(it8);
if (!GetVal(it8, Buffer, MAXSTR-1, "Keyword expected")) return FALSE;
if (!AddAvailableSampleID(it8, Buffer)) return FALSE;
InSymbol(it8);
break;
case SIDENT:
strncpy(VarName, StringPtr(it8->id), MAXID - 1);
VarName[MAXID - 1] = 0;
if (!IsAvailableOnList(it8->ValidKeywords, VarName, NULL, &Key)) {
#ifdef CMS_STRICT_CGATS
return SynError(it8, "Undefined keyword '%s'", VarName);
#else
Key = AddAvailableProperty(it8, VarName, WRITE_UNCOOKED);
if (Key == NULL) return FALSE;
#endif
}
InSymbol(it8);
if (!GetVal(it8, Buffer, MAXSTR - 1, "Property data expected")) return FALSE;
if (Key->WriteAs != WRITE_PAIR) {
if (AddToList(it8, &GetTable(it8)->HeaderList, VarName, NULL, Buffer,
(it8->sy == SSTRING) ? WRITE_STRINGIFY : WRITE_UNCOOKED) == NULL) return FALSE;
}
else {
const char *Subkey;
char *Nextkey;
if (it8->sy != SSTRING)
return SynError(it8, "Invalid value '%s' for property '%s'.", Buffer, VarName);
// chop the string as a list of "subkey, value" pairs, using ';' as a separator
for (Subkey = Buffer; Subkey != NULL; Subkey = Nextkey)
{
char *Value, *temp;
// identify token pair boundary
Nextkey = (char*)strchr(Subkey, ';');
if (Nextkey)
*Nextkey++ = '\0';
// for each pair, split the subkey and the value
Value = (char*)strrchr(Subkey, ',');
if (Value == NULL)
return SynError(it8, "Invalid value for property '%s'.", VarName);
// gobble the spaces before the coma, and the coma itself
temp = Value++;
do *temp-- = '\0'; while (temp >= Subkey && *temp == ' ');
// gobble any space at the right
temp = Value + strlen(Value) - 1;
while (*temp == ' ') *temp-- = '\0';
// trim the strings from the left
Subkey += strspn(Subkey, " ");
Value += strspn(Value, " ");
if (Subkey[0] == 0 || Value[0] == 0)
return SynError(it8, "Invalid value for property '%s'.", VarName);
AddToList(it8, &GetTable(it8)->HeaderList, VarName, Subkey, Value, WRITE_PAIR);
}
}
InSymbol(it8);
break;
case SEOLN: break;
default:
return SynError(it8, "expected keyword or identifier");
}
SkipEOLN(it8);
}
return TRUE;
}
static
void ReadType(cmsIT8* it8, char* SheetTypePtr)
{
cmsInt32Number cnt = 0;
// First line is a very special case.
while (isseparator(it8->ch))
NextCh(it8);
while (it8->ch != '\r' && it8 ->ch != '\n' && it8->ch != '\t' && it8 -> ch != 0) {
if (cnt++ < MAXSTR)
*SheetTypePtr++= (char) it8 ->ch;
NextCh(it8);
}
*SheetTypePtr = 0;
}
static
cmsBool ParseIT8(cmsIT8* it8, cmsBool nosheet)
{
char* SheetTypePtr = it8 ->Tab[0].SheetType;
if (nosheet == 0) {
ReadType(it8, SheetTypePtr);
}
InSymbol(it8);
SkipEOLN(it8);
while (it8-> sy != SEOF &&
it8-> sy != SSYNERROR) {
switch (it8 -> sy) {
case SBEGIN_DATA_FORMAT:
if (!DataFormatSection(it8)) return FALSE;
break;
case SBEGIN_DATA:
if (!DataSection(it8)) return FALSE;
if (it8 -> sy != SEOF && it8->sy != SSYNERROR) {
if (!AllocTable(it8)) return FALSE;
it8 ->nTable = it8 ->TablesCount - 1;
// Read sheet type if present. We only support identifier and string.
// <ident> <eoln> is a type string
// anything else, is not a type string
if (nosheet == 0) {
if (it8 ->sy == SIDENT) {
// May be a type sheet or may be a prop value statement. We cannot use insymbol in
// this special case...
while (isseparator(it8->ch))
NextCh(it8);
// If a newline is found, then this is a type string
if (it8 ->ch == '\n' || it8->ch == '\r') {
cmsIT8SetSheetType(it8, StringPtr(it8 ->id));
InSymbol(it8);
}
else
{
// It is not. Just continue
cmsIT8SetSheetType(it8, "");
}
}
else
// Validate quoted strings
if (it8 ->sy == SSTRING) {
cmsIT8SetSheetType(it8, StringPtr(it8 ->str));
InSymbol(it8);
}
}
}
break;
case SEOLN:
SkipEOLN(it8);
break;
default:
if (!HeaderSection(it8)) return FALSE;
}
}
return (it8 -> sy != SSYNERROR);
}
// Init useful pointers
static
void CookPointers(cmsIT8* it8)
{
int idField, i;
char* Fld;
cmsUInt32Number j;
cmsUInt32Number nOldTable = it8->nTable;
for (j = 0; j < it8->TablesCount; j++) {
TABLE* t = it8->Tab + j;
t->SampleID = 0;
it8->nTable = j;
for (idField = 0; idField < t->nSamples; idField++)
{
if (t->DataFormat == NULL) {
SynError(it8, "Undefined DATA_FORMAT");
return;
}
Fld = t->DataFormat[idField];
if (!Fld) continue;
if (cmsstrcasecmp(Fld, "SAMPLE_ID") == 0) {
t->SampleID = idField;
}
// "LABEL" is an extension. It keeps references to forward tables
if ((cmsstrcasecmp(Fld, "LABEL") == 0) || Fld[0] == '$') {
// Search for table references...
for (i = 0; i < t->nPatches; i++) {
char* Label = GetData(it8, i, idField);
if (Label) {
cmsUInt32Number k;
// This is the label, search for a table containing
// this property
for (k = 0; k < it8->TablesCount; k++) {
TABLE* Table = it8->Tab + k;
KEYVALUE* p;
if (IsAvailableOnList(Table->HeaderList, Label, NULL, &p)) {
// Available, keep type and table
char Buffer[256];
char* Type = p->Value;
int nTable = (int)k;
snprintf(Buffer, 255, "%s %d %s", Label, nTable, Type);
SetData(it8, i, idField, Buffer);
}
}
}
}
}
}
}
it8->nTable = nOldTable;
}
// Try to infere if the file is a CGATS/IT8 file at all. Read first line
// that should be something like some printable characters plus a \n
// returns 0 if this is not like a CGATS, or an integer otherwise. This integer is the number of words in first line?
static
int IsMyBlock(const cmsUInt8Number* Buffer, cmsUInt32Number n)
{
int words = 1, space = 0, quot = 0;
cmsUInt32Number i;
if (n < 10) return 0; // Too small
if (n > 132)
n = 132;
for (i = 1; i < n; i++) {
switch(Buffer[i])
{
case '\n':
case '\r':
return ((quot == 1) || (words > 2)) ? 0 : words;
case '\t':
case ' ':
if(!quot && !space)
space = 1;
break;
case '\"':
quot = !quot;
break;
default:
if (Buffer[i] < 32) return 0;
if (Buffer[i] > 127) return 0;
words += space;
space = 0;
break;
}
}
return 0;
}
static
cmsBool IsMyFile(const char* FileName)
{
FILE *fp;
cmsUInt32Number Size;
cmsUInt8Number Ptr[133];
fp = fopen(FileName, "rt");
if (!fp) {
cmsSignalError(0, cmsERROR_FILE, "File '%s' not found", FileName);
return FALSE;
}
Size = (cmsUInt32Number) fread(Ptr, 1, 132, fp);
if (fclose(fp) != 0)
return FALSE;
Ptr[Size] = '\0';
return IsMyBlock(Ptr, Size);
}
// ---------------------------------------------------------- Exported routines
cmsHANDLE CMSEXPORT cmsIT8LoadFromMem(cmsContext ContextID, const void *Ptr, cmsUInt32Number len)
{
cmsHANDLE hIT8;
cmsIT8* it8;
int type;
_cmsAssert(Ptr != NULL);
_cmsAssert(len != 0);
type = IsMyBlock((const cmsUInt8Number*)Ptr, len);
if (type == 0) return NULL;
hIT8 = cmsIT8Alloc(ContextID);
if (!hIT8) return NULL;
it8 = (cmsIT8*) hIT8;
it8 ->MemoryBlock = (char*) _cmsMalloc(ContextID, len + 1);
if (it8->MemoryBlock == NULL)
{
cmsIT8Free(hIT8);
return NULL;
}
strncpy(it8 ->MemoryBlock, (const char*) Ptr, len);
it8 ->MemoryBlock[len] = 0;
strncpy(it8->FileStack[0]->FileName, "", cmsMAX_PATH-1);
it8-> Source = it8 -> MemoryBlock;
if (!ParseIT8(it8, type-1)) {
cmsIT8Free(hIT8);
return NULL;
}
CookPointers(it8);
it8 ->nTable = 0;
_cmsFree(ContextID, it8->MemoryBlock);
it8 -> MemoryBlock = NULL;
return hIT8;
}
cmsHANDLE CMSEXPORT cmsIT8LoadFromFile(cmsContext ContextID, const char* cFileName)
{
cmsHANDLE hIT8;
cmsIT8* it8;
int type;
_cmsAssert(cFileName != NULL);
type = IsMyFile(cFileName);
if (type == 0) return NULL;
hIT8 = cmsIT8Alloc(ContextID);
it8 = (cmsIT8*) hIT8;
if (!hIT8) return NULL;
it8 ->FileStack[0]->Stream = fopen(cFileName, "rt");
if (!it8 ->FileStack[0]->Stream) {
cmsIT8Free(hIT8);
return NULL;
}
strncpy(it8->FileStack[0]->FileName, cFileName, cmsMAX_PATH-1);
it8->FileStack[0]->FileName[cmsMAX_PATH-1] = 0;
if (!ParseIT8(it8, type-1)) {
fclose(it8 ->FileStack[0]->Stream);
cmsIT8Free(hIT8);
return NULL;
}
CookPointers(it8);
it8 ->nTable = 0;
if (fclose(it8 ->FileStack[0]->Stream)!= 0) {
cmsIT8Free(hIT8);
return NULL;
}
return hIT8;
}
int CMSEXPORT cmsIT8EnumDataFormat(cmsHANDLE hIT8, char ***SampleNames)
{
cmsIT8* it8 = (cmsIT8*) hIT8;
TABLE* t;
_cmsAssert(hIT8 != NULL);
t = GetTable(it8);
if (SampleNames)
*SampleNames = t -> DataFormat;
return t -> nSamples;
}
cmsUInt32Number CMSEXPORT cmsIT8EnumProperties(cmsHANDLE hIT8, char ***PropertyNames)
{
cmsIT8* it8 = (cmsIT8*) hIT8;
KEYVALUE* p;
cmsUInt32Number n;
char **Props;
TABLE* t;
_cmsAssert(hIT8 != NULL);
t = GetTable(it8);
// Pass#1 - count properties
n = 0;
for (p = t -> HeaderList; p != NULL; p = p->Next) {
n++;
}
Props = (char**)AllocChunk(it8, sizeof(char*) * n);
if (Props != NULL) {
// Pass#2 - Fill pointers
n = 0;
for (p = t->HeaderList; p != NULL; p = p->Next) {
Props[n++] = p->Keyword;
}
}
*PropertyNames = Props;
return n;
}
cmsUInt32Number CMSEXPORT cmsIT8EnumPropertyMulti(cmsHANDLE hIT8, const char* cProp, const char ***SubpropertyNames)
{
cmsIT8* it8 = (cmsIT8*) hIT8;
KEYVALUE *p, *tmp;
cmsUInt32Number n;
const char **Props;
TABLE* t;
_cmsAssert(hIT8 != NULL);
t = GetTable(it8);
if(!IsAvailableOnList(t->HeaderList, cProp, NULL, &p)) {
*SubpropertyNames = 0;
return 0;
}
// Pass#1 - count properties
n = 0;
for (tmp = p; tmp != NULL; tmp = tmp->NextSubkey) {
if(tmp->Subkey != NULL)
n++;
}
Props = (const char **) AllocChunk(it8, sizeof(char *) * n);
if (Props != NULL) {
// Pass#2 - Fill pointers
n = 0;
for (tmp = p; tmp != NULL; tmp = tmp->NextSubkey) {
if (tmp->Subkey != NULL)
Props[n++] = p->Subkey;
}
}
*SubpropertyNames = Props;
return n;
}
static
int LocatePatch(cmsIT8* it8, const char* cPatch)
{
int i;
const char *data;
TABLE* t = GetTable(it8);
for (i=0; i < t-> nPatches; i++) {
data = GetData(it8, i, t->SampleID);
if (data != NULL) {
if (cmsstrcasecmp(data, cPatch) == 0)
return i;
}
}
// SynError(it8, "Couldn't find patch '%s'\n", cPatch);
return -1;
}
static
int LocateEmptyPatch(cmsIT8* it8)
{
int i;
const char *data;
TABLE* t = GetTable(it8);
for (i=0; i < t-> nPatches; i++) {
data = GetData(it8, i, t->SampleID);
if (data == NULL)
return i;
}
return -1;
}
static
int LocateSample(cmsIT8* it8, const char* cSample)
{
int i;
const char *fld;
TABLE* t = GetTable(it8);
for (i=0; i < t->nSamples; i++) {
fld = GetDataFormat(it8, i);
if (fld != NULL) {
if (cmsstrcasecmp(fld, cSample) == 0)
return i;
}
}
return -1;
}
int CMSEXPORT cmsIT8FindDataFormat(cmsHANDLE hIT8, const char* cSample)
{
cmsIT8* it8 = (cmsIT8*) hIT8;
_cmsAssert(hIT8 != NULL);
return LocateSample(it8, cSample);
}
const char* CMSEXPORT cmsIT8GetDataRowCol(cmsHANDLE hIT8, int row, int col)
{
cmsIT8* it8 = (cmsIT8*) hIT8;
_cmsAssert(hIT8 != NULL);
return GetData(it8, row, col);
}
cmsFloat64Number CMSEXPORT cmsIT8GetDataRowColDbl(cmsHANDLE hIT8, int row, int col)
{
const char* Buffer;
Buffer = cmsIT8GetDataRowCol(hIT8, row, col);
if (Buffer == NULL) return 0.0;
return ParseFloatNumber(Buffer);
}
cmsBool CMSEXPORT cmsIT8SetDataRowCol(cmsHANDLE hIT8, int row, int col, const char* Val)
{
cmsIT8* it8 = (cmsIT8*) hIT8;
_cmsAssert(hIT8 != NULL);
return SetData(it8, row, col, Val);
}
cmsBool CMSEXPORT cmsIT8SetDataRowColDbl(cmsHANDLE hIT8, int row, int col, cmsFloat64Number Val)
{
cmsIT8* it8 = (cmsIT8*) hIT8;
char Buff[256];
_cmsAssert(hIT8 != NULL);
snprintf(Buff, 255, it8->DoubleFormatter, Val);
return SetData(it8, row, col, Buff);
}
const char* CMSEXPORT cmsIT8GetData(cmsHANDLE hIT8, const char* cPatch, const char* cSample)
{
cmsIT8* it8 = (cmsIT8*) hIT8;
int iField, iSet;
_cmsAssert(hIT8 != NULL);
iField = LocateSample(it8, cSample);
if (iField < 0) {
return NULL;
}
iSet = LocatePatch(it8, cPatch);
if (iSet < 0) {
return NULL;
}
return GetData(it8, iSet, iField);
}
cmsFloat64Number CMSEXPORT cmsIT8GetDataDbl(cmsHANDLE it8, const char* cPatch, const char* cSample)
{
const char* Buffer;
Buffer = cmsIT8GetData(it8, cPatch, cSample);
return ParseFloatNumber(Buffer);
}
cmsBool CMSEXPORT cmsIT8SetData(cmsHANDLE hIT8, const char* cPatch, const char* cSample, const char *Val)
{
cmsIT8* it8 = (cmsIT8*) hIT8;
int iField, iSet;
TABLE* t;
_cmsAssert(hIT8 != NULL);
t = GetTable(it8);
iField = LocateSample(it8, cSample);
if (iField < 0)
return FALSE;
if (t-> nPatches == 0) {
if (!AllocateDataFormat(it8))
return FALSE;
if (!AllocateDataSet(it8))
return FALSE;
CookPointers(it8);
}
if (cmsstrcasecmp(cSample, "SAMPLE_ID") == 0) {
iSet = LocateEmptyPatch(it8);
if (iSet < 0) {
return SynError(it8, "Couldn't add more patches '%s'\n", cPatch);
}
iField = t -> SampleID;
}
else {
iSet = LocatePatch(it8, cPatch);
if (iSet < 0) {
return FALSE;
}
}
return SetData(it8, iSet, iField, Val);
}
cmsBool CMSEXPORT cmsIT8SetDataDbl(cmsHANDLE hIT8, const char* cPatch,
const char* cSample,
cmsFloat64Number Val)
{
cmsIT8* it8 = (cmsIT8*) hIT8;
char Buff[256];
_cmsAssert(hIT8 != NULL);
snprintf(Buff, 255, it8->DoubleFormatter, Val);
return cmsIT8SetData(hIT8, cPatch, cSample, Buff);
}
// Buffer should get MAXSTR at least
const char* CMSEXPORT cmsIT8GetPatchName(cmsHANDLE hIT8, int nPatch, char* buffer)
{
cmsIT8* it8 = (cmsIT8*) hIT8;
TABLE* t;
char* Data;
_cmsAssert(hIT8 != NULL);
t = GetTable(it8);
Data = GetData(it8, nPatch, t->SampleID);
if (!Data) return NULL;
if (!buffer) return Data;
strncpy(buffer, Data, MAXSTR-1);
buffer[MAXSTR-1] = 0;
return buffer;
}
int CMSEXPORT cmsIT8GetPatchByName(cmsHANDLE hIT8, const char *cPatch)
{
_cmsAssert(hIT8 != NULL);
return LocatePatch((cmsIT8*)hIT8, cPatch);
}
cmsUInt32Number CMSEXPORT cmsIT8TableCount(cmsHANDLE hIT8)
{
cmsIT8* it8 = (cmsIT8*) hIT8;
_cmsAssert(hIT8 != NULL);
return it8 ->TablesCount;
}
// This handles the "LABEL" extension.
// Label, nTable, Type
int CMSEXPORT cmsIT8SetTableByLabel(cmsHANDLE hIT8, const char* cSet, const char* cField, const char* ExpectedType)
{
const char* cLabelFld;
char Type[256], Label[256];
cmsUInt32Number nTable;
_cmsAssert(hIT8 != NULL);
if (cField != NULL && *cField == 0)
cField = "LABEL";
if (cField == NULL)
cField = "LABEL";
cLabelFld = cmsIT8GetData(hIT8, cSet, cField);
if (!cLabelFld) return -1;
if (sscanf(cLabelFld, "%255s %u %255s", Label, &nTable, Type) != 3)
return -1;
if (ExpectedType != NULL && *ExpectedType == 0)
ExpectedType = NULL;
if (ExpectedType) {
if (cmsstrcasecmp(Type, ExpectedType) != 0) return -1;
}
return cmsIT8SetTable(hIT8, nTable);
}
cmsBool CMSEXPORT cmsIT8SetIndexColumn(cmsHANDLE hIT8, const char* cSample)
{
cmsIT8* it8 = (cmsIT8*) hIT8;
int pos;
_cmsAssert(hIT8 != NULL);
pos = LocateSample(it8, cSample);
if(pos == -1)
return FALSE;
it8->Tab[it8->nTable].SampleID = pos;
return TRUE;
}
void CMSEXPORT cmsIT8DefineDblFormat(cmsHANDLE hIT8, const char* Formatter)
{
cmsIT8* it8 = (cmsIT8*) hIT8;
_cmsAssert(hIT8 != NULL);
if (Formatter == NULL)
strcpy(it8->DoubleFormatter, DEFAULT_DBL_FORMAT);
else
strncpy(it8->DoubleFormatter, Formatter, sizeof(it8->DoubleFormatter));
it8 ->DoubleFormatter[sizeof(it8 ->DoubleFormatter)-1] = 0;
}
static
cmsBool ReadNumbers(cmsIT8* cube, int n, cmsFloat64Number* arr)
{
int i;
for (i = 0; i < n; i++) {
if (cube->sy == SINUM)
arr[i] = cube->inum;
else
if (cube->sy == SDNUM)
arr[i] = cube->dnum;
else
return SynError(cube, "Number expected");
InSymbol(cube);
}
return CheckEOLN(cube);
}
static
cmsBool ParseCube(cmsIT8* cube, cmsStage** Shaper, cmsStage** CLUT, char title[])
{
cmsFloat64Number domain_min[3] = { 0, 0, 0 };
cmsFloat64Number domain_max[3] = { 1.0, 1.0, 1.0 };
cmsFloat64Number check_0_1[2] = { 0, 1.0 };
int shaper_size = 0;
int lut_size = 0;
int i;
InSymbol(cube);
while (cube->sy != SEOF && cube->sy != SSYNERROR) {
switch (cube->sy)
{
// Set profile description
case STITLE:
InSymbol(cube);
if (!Check(cube, SSTRING, "Title string expected")) return FALSE;
memcpy(title, StringPtr(cube->str), MAXSTR);
title[MAXSTR - 1] = 0;
InSymbol(cube);
break;
// Define domain
case SDOMAIN_MIN:
InSymbol(cube);
if (!ReadNumbers(cube, 3, domain_min)) return FALSE;
break;
case SDOMAIN_MAX:
InSymbol(cube);
if (!ReadNumbers(cube, 3, domain_max)) return FALSE;
break;
// Define shaper
case S_LUT1D_SIZE:
InSymbol(cube);
if (!Check(cube, SINUM, "Shaper size expected")) return FALSE;
shaper_size = cube->inum;
InSymbol(cube);
break;
// Deefine CLUT
case S_LUT3D_SIZE:
InSymbol(cube);
if (!Check(cube, SINUM, "LUT size expected")) return FALSE;
lut_size = cube->inum;
InSymbol(cube);
break;
// Range. If present, has to be 0..1.0
case S_LUT1D_INPUT_RANGE:
case S_LUT3D_INPUT_RANGE:
InSymbol(cube);
if (!ReadNumbers(cube, 2, check_0_1)) return FALSE;
if (check_0_1[0] != 0 || check_0_1[1] != 1.0) {
return SynError(cube, "Unsupported format");
}
break;
case SEOLN:
InSymbol(cube);
break;
default:
case S_LUT_IN_VIDEO_RANGE:
case S_LUT_OUT_VIDEO_RANGE:
return SynError(cube, "Unsupported format");
// Read and create tables
case SINUM:
case SDNUM:
if (shaper_size > 0) {
cmsToneCurve* curves[3];
cmsFloat32Number* shapers = (cmsFloat32Number*)_cmsMalloc(cube->ContextID, 3 * shaper_size * sizeof(cmsFloat32Number));
if (shapers == NULL) return FALSE;
for (i = 0; i < shaper_size; i++) {
cmsFloat64Number nums[3];
if (!ReadNumbers(cube, 3, nums)) return FALSE;
shapers[i + 0] = (cmsFloat32Number) ((nums[0] - domain_min[0]) / (domain_max[0] - domain_min[0]));
shapers[i + 1 * shaper_size] = (cmsFloat32Number) ((nums[1] - domain_min[1]) / (domain_max[1] - domain_min[1]));
shapers[i + 2 * shaper_size] = (cmsFloat32Number) ((nums[2] - domain_min[2]) / (domain_max[2] - domain_min[2]));
}
for (i = 0; i < 3; i++) {
curves[i] = cmsBuildTabulatedToneCurveFloat(cube->ContextID, shaper_size,
&shapers[i * shaper_size]);
if (curves[i] == NULL) return FALSE;
}
*Shaper = cmsStageAllocToneCurves(cube->ContextID, 3, curves);
cmsFreeToneCurveTriple(curves);
}
if (lut_size > 0) {
int nodes = lut_size * lut_size * lut_size;
cmsFloat32Number* lut_table = _cmsMalloc(cube->ContextID, nodes * 3 * sizeof(cmsFloat32Number));
if (lut_table == NULL) return FALSE;
for (i = 0; i < nodes; i++) {
cmsFloat64Number nums[3];
if (!ReadNumbers(cube, 3, nums)) return FALSE;
lut_table[i * 3 + 2] = (cmsFloat32Number) ((nums[0] - domain_min[0]) / (domain_max[0] - domain_min[0]));
lut_table[i * 3 + 1] = (cmsFloat32Number) ((nums[1] - domain_min[1]) / (domain_max[1] - domain_min[1]));
lut_table[i * 3 + 0] = (cmsFloat32Number) ((nums[2] - domain_min[2]) / (domain_max[2] - domain_min[2]));
}
*CLUT = cmsStageAllocCLutFloat(cube->ContextID, lut_size, 3, 3, lut_table);
_cmsFree(cube->ContextID, lut_table);
}
if (!Check(cube, SEOF, "Extra symbols found in file")) return FALSE;
}
}
return TRUE;
}
// Share the parser to read .cube format and create RGB devicelink profiles
cmsHPROFILE CMSEXPORT cmsCreateDeviceLinkFromCubeFileTHR(cmsContext ContextID, const char* cFileName)
{
cmsHPROFILE hProfile = NULL;
cmsIT8* cube = NULL;
cmsPipeline* Pipeline = NULL;
cmsStage* CLUT = NULL;
cmsStage* Shaper = NULL;
cmsMLU* DescriptionMLU = NULL;
char title[MAXSTR];
_cmsAssert(cFileName != NULL);
cube = (cmsIT8*) cmsIT8Alloc(ContextID);
if (!cube) return NULL;
cube->IsCUBE = TRUE;
cube->FileStack[0]->Stream = fopen(cFileName, "rt");
if (!cube->FileStack[0]->Stream) goto Done;
strncpy(cube->FileStack[0]->FileName, cFileName, cmsMAX_PATH - 1);
cube->FileStack[0]->FileName[cmsMAX_PATH - 1] = 0;
if (!ParseCube(cube, &Shaper, &CLUT, title)) goto Done;
// Success on parsing, let's create the profile
hProfile = cmsCreateProfilePlaceholder(ContextID);
if (!hProfile) goto Done;
cmsSetProfileVersion(hProfile, 4.4);
cmsSetDeviceClass(hProfile, cmsSigLinkClass);
cmsSetColorSpace(hProfile, cmsSigRgbData);
cmsSetPCS(hProfile, cmsSigRgbData);
cmsSetHeaderRenderingIntent(hProfile, INTENT_PERCEPTUAL);
// Creates a Pipeline to hold CLUT and shaper
Pipeline = cmsPipelineAlloc(ContextID, 3, 3);
if (Pipeline == NULL) goto Done;
// Populates the pipeline
if (Shaper != NULL) {
if (!cmsPipelineInsertStage(Pipeline, cmsAT_BEGIN, Shaper))
goto Done;
}
if (CLUT != NULL) {
if (!cmsPipelineInsertStage(Pipeline, cmsAT_END, CLUT))
goto Done;
}
// Propagate the description. We put no copyright because we know
// nothing on the copyrighted state of the .cube
DescriptionMLU = cmsMLUalloc(ContextID, 1);
if (!cmsMLUsetUTF8(DescriptionMLU, cmsNoLanguage, cmsNoCountry, title)) goto Done;
// Flush the tags
if (!cmsWriteTag(hProfile, cmsSigProfileDescriptionTag, DescriptionMLU)) goto Done;
if (!cmsWriteTag(hProfile, cmsSigAToB0Tag, (void*)Pipeline)) goto Done;
Done:
if (DescriptionMLU != NULL)
cmsMLUfree(DescriptionMLU);
if (Pipeline != NULL)
cmsPipelineFree(Pipeline);
cmsIT8Free((cmsHANDLE) cube);
return hProfile;
}
cmsHPROFILE CMSEXPORT cmsCreateDeviceLinkFromCubeFile(const char* cFileName)
{
return cmsCreateDeviceLinkFromCubeFileTHR(NULL, cFileName);
}
| 0 | 0.979479 | 1 | 0.979479 | game-dev | MEDIA | 0.183251 | game-dev | 0.650216 | 1 | 0.650216 |
Dark-Basic-Software-Limited/AGKRepo | 2,414 | AGK/bullet/BulletCollision/CollisionShapes/btMinkowskiSumShape.h | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef BT_MINKOWSKI_SUM_SHAPE_H
#define BT_MINKOWSKI_SUM_SHAPE_H
#include "btConvexInternalShape.h"
#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h" // for the types
/// The btMinkowskiSumShape is only for advanced users. This shape represents implicit based minkowski sum of two convex implicit shapes.
ATTRIBUTE_ALIGNED16(class) btMinkowskiSumShape : public btConvexInternalShape
{
btTransform m_transA;
btTransform m_transB;
const btConvexShape* m_shapeA;
const btConvexShape* m_shapeB;
public:
BT_DECLARE_ALIGNED_ALLOCATOR();
btMinkowskiSumShape(const btConvexShape* shapeA,const btConvexShape* shapeB);
virtual btVector3 localGetSupportingVertexWithoutMargin(const btVector3& vec)const;
virtual void batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors,btVector3* supportVerticesOut,int numVectors) const;
virtual void calculateLocalInertia(btScalar mass,btVector3& inertia) const;
void setTransformA(const btTransform& transA) { m_transA = transA;}
void setTransformB(const btTransform& transB) { m_transB = transB;}
const btTransform& getTransformA()const { return m_transA;}
const btTransform& GetTransformB()const { return m_transB;}
virtual btScalar getMargin() const;
const btConvexShape* getShapeA() const { return m_shapeA;}
const btConvexShape* getShapeB() const { return m_shapeB;}
virtual const char* getName()const
{
return "MinkowskiSum";
}
};
#endif //BT_MINKOWSKI_SUM_SHAPE_H
| 0 | 0.879718 | 1 | 0.879718 | game-dev | MEDIA | 0.977066 | game-dev | 0.667522 | 1 | 0.667522 |
PoseAI/PoseCameraAPI | 16,829 | UnrealEngineAPI/PluginV3.0/4.27/PoseAILiveLink/Source/PoseAILiveLink/Public/PoseAIStructs.h | // Copyright Pose AI Ltd 2022. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Json.h"
#include "JsonObjectConverter.h"
#include "PoseAIStructs.generated.h"
#define LOCTEXT_NAMESPACE "PoseAI"
/* decoding utilities for compact representation */
float UintB64ToUint(char a, char b);
uint32 UintB64ToUint(char a, char b, char c);
float FixedB64pairToFloat(char a, char b);
void FStringFixed12ToFloat(const FString& data, TArray<float>& flatArray);
void FlatArrayToQuats(const TArray<float>& flatArray, TArray<FQuat>& quatArray);
UENUM(BlueprintType)
enum class EPoseAiPacketFormat : uint8
{
Verbose, Compact
};
UENUM(BlueprintType)
enum class EPoseAiAppModes : uint8
{
Room, Desktop, Portrait, RoomBodyOnly, PortraitBodyOnly
};
UENUM(BlueprintType)
enum class EPoseAiContext : uint8
{
Default
};
UENUM(BlueprintType)
enum class EPoseAiRigPresets : uint8
{
MetaHuman, UE4, Mixamo, DazUE, MixamoAlt
};
UENUM(BlueprintType)
enum class EPoseAiHandModel : uint8
{
Version1, Version2_EXPERIMENTAL
};
UENUM(BlueprintType)
enum class EPoseAiBodyModel : uint8
{
Version2, Version3
};
/* the handshake configures the main parameters of pose camera*/
USTRUCT(BlueprintType)
struct POSEAILIVELINK_API FPoseAIHandshake
{
GENERATED_BODY()
/* the camera mode. "Room", "Desktop", "Portrait", "RoomBodyOnly", "PortraitBodyOnly" */
UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = "PoseAI Handshake")
EPoseAiAppModes mode = EPoseAiAppModes::Room;
/* the skeletal rig to use, based on standard nomenclature and rotations: "UE4", "MetaHuman", "DazUE", "Mixamo" */
UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = "PoseAI Handshake")
EPoseAiRigPresets rig = EPoseAiRigPresets::MetaHuman;
/* BETA: provides ARKit compatible animation blendshape stream for facial rigs */
UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = "PoseAI Handshake")
bool isFaceAnimating = true;
/* flips left/right limbs and rotates as if the player is looking at a mirror*/
UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = "PoseAI Handshake")
bool isMirrored = true;
/* rotates lower body 180 degrees - convenient for desktop mode in some perspectives*/
UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = "PoseAI Handshake")
bool isLowerBodyRotated = false;
/* whether to include motion within camera frame in hips or in root*/
UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = "PoseAI Handshake")
bool useRootMotion = false;
/* the desired camera speed. On many phones only 30 or 60 FPS will be accepted and otherwise you get default*/
UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = "PoseAI Handshake")
int32 cameraFPS = 60;
/* target frame rate for phone interpolation smoothing. Suggest 0 on Unreal. Events are raw.*/
UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = "PoseAI Handshake")
int32 syncFPS = 0;
/* version of our AI model: V2 is 2022 release, V3 currently Room/Portrait mode only as of March 2023 release*/
UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = "PoseAI Handshake")
EPoseAiBodyModel bodyModelVersion = EPoseAiBodyModel::Version2;
/* the version of our hand AI. Version 1 is our original. Version 2 is experimental and may offer some improvments.*/
UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = "PoseAI Handshake")
EPoseAiHandModel handModelVersion = EPoseAiHandModel::Version1;
/* the model context. Reserved for future AI models*/
UPROPERTY(EditAnywhere, Category = "PoseAI Handshake")
EPoseAiContext context = EPoseAiContext::Default;
/* Not needed for PoseCam. Used only for licensee connection and verification.*/
UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = "PoseAI Handshake")
FString whoami = "";
/* Not needed for PoseCam. Used only for licencee connection and verification.*/
UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = "PoseAI Handshake")
FString signature = "";
/* Turn on demo locomotion / action recognition events. Keep off for efficiency unless testing.*/
UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = "PoseAI Handshake")
bool locomotionEvents = false;
/* controls compactness of packet. */
UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = "PoseAI Handshake")
EPoseAiPacketFormat packetFormat = EPoseAiPacketFormat::Compact;
bool operator==(const FPoseAIHandshake& Other) const;
bool operator!=(const FPoseAIHandshake& Other) const { return !operator==(Other); }
bool IncludesHands() const;
FString GetContextString() const;
FString GetModeString() const;
FString GetRigString() const;
int32 GetBodyModelVersion() const;
int32 GetHandModelVersion() const;
FString ToString() const;
FString YesNoString(bool val) const {
return val ? FString("YES") : FString("NO");
}
};
/*adjusts the sensitivity of PoseAI events*/
USTRUCT(BlueprintType)
struct POSEAILIVELINK_API FPoseAIModelConfig
{
GENERATED_BODY()
/* alpha where 0.0 is lowest sensitivity (more likely to miss events) and 1.0 is maximum sensitivity (more likely false triggers).*/
UPROPERTY(BlueprintReadWrite, Category = "PoseAI Model Sensitivity")
float stepSensitivity = 0.5f;
/* alpha where 0.0 is lowest sensitivity (more likely to miss events) and 1.0 is maximum sensitivity (more likely false triggers).*/
UPROPERTY(BlueprintReadWrite, Category = "PoseAI Model Sensitivity")
float armSensitivity = 0.5f;
/* alpha where 0.0 is lowest sensitivity (more likely to miss events) and 1.0 is maximum sensitivity (more likely false triggers).*/
UPROPERTY(BlueprintReadWrite, Category = "PoseAI Model Sensitivity")
float crouchSensitivity = 0.5f;
/* alpha where 0.0 is lowest sensitivity (more likely to miss events) and 1.0 is maximum sensitivity (more likely false triggers).*/
UPROPERTY(BlueprintReadWrite, Category = "PoseAI Model Sensitivity")
float jumpSensitivity = 0.5f;
UPROPERTY(BlueprintReadWrite, Category = "PoseAI Model Sensitivity")
bool isMirrored = true;
FString ToString() const;
FString YesNoString(bool val) const {
return val ? FString("YES") : FString("NO");
}
};
/** base class for the two event notifications formats sent by camera. All events have a uint count, which upon change signifies a new event has been registered
and a second property, either a float or uint.
*/
USTRUCT()
struct POSEAILIVELINK_API FPoseAIEventPairBase
{
GENERATED_BODY()
public:
/** number of events registered by camera */
UPROPERTY(VisibleAnywhere, Category = "PoseAI Event")
uint32 Count = 0;
virtual void ProcessCompact(const FString& compactString) {};
bool CheckTriggerAndUpdate();
private:
uint32 InternalCount = 0;
};
/**
*structure to hold a type of event notification
*/
USTRUCT()
struct POSEAILIVELINK_API FPoseAIEventPair : public FPoseAIEventPairBase
{
GENERATED_BODY()
public:
/**magnitude of event where approrpiate */
UPROPERTY(VisibleAnywhere, Category = "PoseAI Event")
float Magnitude = 0.0f;
void ProcessCompact(const FString& compactString) override;
};
USTRUCT()
struct POSEAILIVELINK_API FPoseAIGesturePair : public FPoseAIEventPairBase
{
GENERATED_BODY()
public:
/**index code for most recent gesture */
UPROPERTY(VisibleAnywhere, Category = "PoseAI Event")
uint32 Current = 0;
void ProcessCompact(const FString& compactString) override;
};
/**
*structure to receive event notifications
*/
USTRUCT()
struct POSEAILIVELINK_API FPoseAIEventStruct
{
GENERATED_BODY()
public:
/** number of footsteps registered by camera, body height magnitude */
UPROPERTY(VisibleAnywhere, Category = "PoseAI")
FPoseAIEventPair Footstep;
/** number of left foot sidesteps registered by camera. sign indicates direction */
UPROPERTY(VisibleAnywhere, Category = "PoseAI")
FPoseAIEventPair SidestepL;
/** number of right foot sidesteps registered by camera. sign indicates direction */
UPROPERTY(VisibleAnywhere, Category = "PoseAI")
FPoseAIEventPair SidestepR;
/** number of jumps registered by camera */
UPROPERTY(VisibleAnywhere, Category = "PoseAI")
FPoseAIEventPair Jump;
/** number of footsplits registered by camera, body width magnitude */
UPROPERTY(VisibleAnywhere, Category = "PoseAI")
FPoseAIEventPair FeetSplit;
/** number of arm pumps registered by camera, body height magnitude */
UPROPERTY(VisibleAnywhere, Category = "PoseAI")
FPoseAIEventPair ArmPump;
/** number of arm flexes registered by camera, body width magnitude */
UPROPERTY(VisibleAnywhere, Category = "PoseAI")
FPoseAIEventPair ArmFlex;
/** number of left or dual arm gestures registered by camera and most recent gesture */
UPROPERTY(VisibleAnywhere, Category = "PoseAI")
FPoseAIGesturePair ArmGestureL;
/** number of right arm gestures registered by camera and most recent gesture */
UPROPERTY(VisibleAnywhere, Category = "PoseAI")
FPoseAIGesturePair ArmGestureR;
void ProcessJsonObject(const TSharedPtr < FJsonObject > eveBody);
void ProcessCompactBody(const FString& compactString);
};
/**
*structure to share additional information
*/
USTRUCT(BlueprintType)
struct POSEAILIVELINK_API FPoseAIScalarStruct
{
GENERATED_BODY()
public:
/** visibility flags by body part. Correspond to figure in the app */
UPROPERTY(BlueprintReadOnly, Category = "Flags")
float VisTorso = 0.0f;
UPROPERTY(BlueprintReadOnly, Category = "Flags")
float VisArmL = 0.0f;
UPROPERTY(BlueprintReadOnly, Category = "Flags")
float VisArmR = 0.0f;
UPROPERTY(BlueprintReadOnly, Category = "Flags")
float VisLegL = 0.0f;
UPROPERTY(BlueprintReadOnly, Category = "Flags")
float VisLegR = 0.0f;
/** location of left hand relative to body in broad zones */
UPROPERTY(BlueprintReadOnly, Category = "PoseAI")
int32 HandZoneL = 5;
/** location of right hand relative to body in broad zones */
UPROPERTY(BlueprintReadOnly, Category = "PosPeAI")
int32 HandZoneR = 5;
/** Heading in degrees of torso. 0 is heading to camera */
UPROPERTY(BlueprintReadOnly, Category = "PoseAI")
float ChestYaw = 0.0f;
/** Heading in degrees of flattened left foot to right foot vector relative to camera. 0 is parallel to camera */
UPROPERTY(BlueprintReadOnly, Category = "PoseAI")
float StanceYaw = 0.0f;
/** estimated actual height of the subject in clip coordinates (2.0 = full height of image) */
UPROPERTY(BlueprintReadOnly, Category = "PoseAI")
float BodyHeight = 0.0f;
/** whether subject is crouching */
UPROPERTY(BlueprintReadOnly, Category = "PoseAI")
float IsCrouching = 0.0f;
UPROPERTY(BlueprintReadOnly, Category = "PoseAI")
int32 StableFoot = 0.0f;
void ProcessJsonObject(const TSharedPtr < FJsonObject > scaBody);
};
USTRUCT(BlueprintType)
struct POSEAILIVELINK_API FPoseAIVerboseBodyVectors
{
GENERATED_BODY()
public:
UPROPERTY()
TArray<float> HipLean;
UPROPERTY()
TArray<float> HipScreen;
UPROPERTY()
TArray<float> ChestScreen;
UPROPERTY()
TArray<float> HandIkL;
UPROPERTY()
TArray<float> HandIkR;
};
USTRUCT(BlueprintType)
struct POSEAILIVELINK_API FPoseAIVerbose
{
GENERATED_BODY()
public:
UPROPERTY()
FPoseAIEventStruct Events;
UPROPERTY()
FPoseAIScalarStruct Scalars;
UPROPERTY()
FPoseAIVerboseBodyVectors Vectors;
void ProcessJsonObject(const TSharedPtr < FJsonObject > jsonObj);
};
/**
* structure to store and expose visibility flags for events alerting programmer if subject is out of camera
*/
USTRUCT(BlueprintType)
struct POSEAILIVELINK_API FPoseAIVisibilityFlags
{
GENERATED_BODY()
public:
UPROPERTY(BlueprintReadOnly, Category = "Flags")
bool isTorso = false;
UPROPERTY(BlueprintReadOnly, Category = "Flags")
bool isLeftArm = false;
UPROPERTY(BlueprintReadOnly, Category = "Flags")
bool isRightArm = false;
UPROPERTY(BlueprintReadOnly, Category = "Flags")
bool isLeftLeg = false;
UPROPERTY(BlueprintReadOnly, Category = "Flags")
bool isRightLeg = false;
bool HasChanged() { return hasChanged; }
void ProcessVerbose(FPoseAIScalarStruct& scalars);
void ProcessCompact(const FString& visString);
private:
bool hasChanged = false;
};
/**
* structure to share additional information
*/
USTRUCT(BlueprintType)
struct POSEAILIVELINK_API FPoseAILiveValues
{
GENERATED_BODY()
public:
/** How much subject is leaning in radians, head-to-hips; x to the side, y forward */
UPROPERTY(BlueprintReadOnly, Category="PoseAI")
FVector2D upperBodyLean = FVector2D(0.0f, 0.0f);
/** estimated stance height of the subject in clip coordinates (2.0 = full height of image) */
UPROPERTY(BlueprintReadOnly, Category = "PoseAI")
bool isCrouching = false;
/** location of left hand relative to body in broad zones */
UPROPERTY(BlueprintReadOnly, Category = "PoseAI")
int32 handZoneLeft = 5;
/** location of left hand relative to body in broad zones */
UPROPERTY(BlueprintReadOnly, Category = "PoseAI")
int32 handZoneRight = 5;
/** offset location of subject in camera frame. Good for lateral movement */
UPROPERTY(BlueprintReadOnly, Category = "PoseAI")
FVector rootTranslation = FVector::ZeroVector;
/** Heading in radians of flattened left foot to right foot vector relative to camera. 0 is parallel to camera */
UPROPERTY(BlueprintReadOnly, Category = "PoseAI")
float stanceYaw = 0.0f;
/** Heading in radians of torso. 0 is heading to camera */
UPROPERTY(BlueprintReadOnly, Category = "PoseAI")
float chestYaw = 0.0f;
/** Heading of flattened left foot to right foot vector relative to camera */
UPROPERTY(BlueprintReadOnly, Category = "PoseAI")
int32 modelLatency = 0.0f;
/** timestamp according to pose camera device (CMTime), in seconds */
double timestamp = 0.0;
/** current height of jump in body units */
UPROPERTY(BlueprintReadOnly, Category = "PoseAI")
float jumpHeight = 0.0f;
/** estimated actual height of the subject in clip coordinates (2.0 = full height of image) */
UPROPERTY(BlueprintReadOnly, Category="PoseAI")
float bodyHeight = 0.0f;
/** location of hips in camera frame (clip coordinates -1 to 1, 0 is center ) */
UPROPERTY(BlueprintReadOnly, Category="PoseAI")
FVector2D hipScreen = FVector2D(0.0f, 0.0f);
/** location of chest in camera frame (clip coordinates -1 to 1, 0 is center ) */
UPROPERTY(BlueprintReadOnly, Category="PoseAI")
FVector2D chestScreen = FVector2D(0.0f, 0.0f);
/** location of left index finger in camera frame (clip coordinates -1 to 1, 0 is center ) */
UPROPERTY(BlueprintReadOnly, Category="PoseAI")
FVector2D pointHandLeft = FVector2D(0.0f, 0.0f);
/** location of right index finger in camera frame (clip coordinates -1 to 1, 0 is center ) */
UPROPERTY(BlueprintReadOnly, Category="PoseAI")
FVector2D pointHandRight = FVector2D(0.0f, 0.0f);
/** target for the PoseAI Hand IK node */
UPROPERTY(BlueprintReadOnly, Category = "PoseAI")
FVector handIkL = FVector(0.0f, 0.0f, 0.0f);
/** target for the PoseAI Hand IK node */
UPROPERTY(BlueprintReadOnly, Category = "PoseAI")
FVector handIkR = FVector(0.0f, 0.0f, 0.0f);
/** finger target for the PoseAI Hand IK node */
UPROPERTY(BlueprintReadOnly, Category = "PoseAI")
FVector fingerIkL = FVector(0.0f, 0.0f, 0.0f);
/** finger target for the PoseAI Hand IK node */
UPROPERTY(BlueprintReadOnly, Category = "PoseAI")
FVector fingerIkR = FVector(0.0f, 0.0f, 0.0f);
/** if at least one foot has been stationary for a few frames */
UPROPERTY(BlueprintReadOnly, Category = "PoseAI")
int32 stableFeet = 0;
void ProcessVerboseBody(const FPoseAIVerbose& scalars);
void ProcessVerboseVectorsHandLeft(const TSharedPtr < FJsonObject > vecHand);
void ProcesssVerboseVectorsHandRight(const TSharedPtr < FJsonObject > vecHand);
void ProcessCompactScalarsBody(const FString& compactString);
void ProcessCompactVectorsBody(const FString& compactString);
void ProcessCompactVectorsHandLeft(const FString& compactString);
void ProcessCompactVectorsHandRight(const FString& compactString);
private:
static const FString fieldPointScreen;
};
| 0 | 0.934902 | 1 | 0.934902 | game-dev | MEDIA | 0.48493 | game-dev | 0.521229 | 1 | 0.521229 |
MCreator-Examples/Tale-of-Biomes | 7,769 | src/main/java/net/nwtg/taleofbiomes/procedures/PlayerRightClicksOnCraftingTableProcedure.java | package net.nwtg.taleofbiomes.procedures;
import net.nwtg.taleofbiomes.world.inventory.CraftingTableMenuRecipeBookMenu;
import net.nwtg.taleofbiomes.world.inventory.CraftingTableMenuMenu;
import net.nwtg.taleofbiomes.world.inventory.BasicToolTableMenuRecipeBookMenu;
import net.nwtg.taleofbiomes.world.inventory.BasicToolTableMenuMenu;
import net.nwtg.taleofbiomes.world.inventory.BasicStoneTableMenuRecipeBookMenu;
import net.nwtg.taleofbiomes.world.inventory.BasicStoneTableMenuMenu;
import net.nwtg.taleofbiomes.network.TaleOfBiomesModVariables;
import net.nwtg.taleofbiomes.init.TaleOfBiomesModBlocks;
import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent;
import net.neoforged.fml.common.EventBusSubscriber;
import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.bus.api.Event;
import net.minecraft.world.level.LevelAccessor;
import net.minecraft.world.inventory.AbstractContainerMenu;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.MenuProvider;
import net.minecraft.tags.BlockTags;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.network.chat.Component;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.core.BlockPos;
import javax.annotation.Nullable;
import io.netty.buffer.Unpooled;
@EventBusSubscriber
public class PlayerRightClicksOnCraftingTableProcedure {
@SubscribeEvent
public static void onRightClickBlock(PlayerInteractEvent.RightClickBlock event) {
if (event.getHand() != event.getEntity().getUsedItemHand())
return;
execute(event, event.getLevel(), event.getPos().getX(), event.getPos().getY(), event.getPos().getZ(), event.getEntity());
}
public static void execute(LevelAccessor world, double x, double y, double z, Entity entity) {
execute(null, world, x, y, z, entity);
}
private static void execute(@Nullable Event event, LevelAccessor world, double x, double y, double z, Entity entity) {
if (entity == null)
return;
if ((world.getBlockState(BlockPos.containing(x, y, z))).is(BlockTags.create(ResourceLocation.parse(((TaleOfBiomesModVariables.MapVariables.get(world).modNamespace + ":" + "crafting_stations")).toLowerCase(java.util.Locale.ENGLISH))))) {
{
TaleOfBiomesModVariables.PlayerVariables _vars = entity.getData(TaleOfBiomesModVariables.PLAYER_VARIABLES);
_vars.recipePage = 0;
_vars.syncPlayerVariables(entity);
}
{
TaleOfBiomesModVariables.PlayerVariables _vars = entity.getData(TaleOfBiomesModVariables.PLAYER_VARIABLES);
_vars.blockPosX = x;
_vars.syncPlayerVariables(entity);
}
{
TaleOfBiomesModVariables.PlayerVariables _vars = entity.getData(TaleOfBiomesModVariables.PLAYER_VARIABLES);
_vars.blockPosY = y;
_vars.syncPlayerVariables(entity);
}
{
TaleOfBiomesModVariables.PlayerVariables _vars = entity.getData(TaleOfBiomesModVariables.PLAYER_VARIABLES);
_vars.blockPosZ = z;
_vars.syncPlayerVariables(entity);
}
if ((world.getBlockState(BlockPos.containing(x, y, z))).getBlock() == TaleOfBiomesModBlocks.CRAFTING_TABLE.get()) {
if (entity.getData(TaleOfBiomesModVariables.PLAYER_VARIABLES).isRecipeHelperOpen) {
if (entity instanceof ServerPlayer _ent) {
BlockPos _bpos = BlockPos.containing(x, y, z);
_ent.openMenu(new MenuProvider() {
@Override
public Component getDisplayName() {
return Component.literal("CraftingTableMenuRecipeBook");
}
@Override
public boolean shouldTriggerClientSideContainerClosingOnOpen() {
return false;
}
@Override
public AbstractContainerMenu createMenu(int id, Inventory inventory, Player player) {
return new CraftingTableMenuRecipeBookMenu(id, inventory, new FriendlyByteBuf(Unpooled.buffer()).writeBlockPos(_bpos));
}
}, _bpos);
}
} else {
if (entity instanceof ServerPlayer _ent) {
BlockPos _bpos = BlockPos.containing(x, y, z);
_ent.openMenu(new MenuProvider() {
@Override
public Component getDisplayName() {
return Component.literal("CraftingTableMenu");
}
@Override
public boolean shouldTriggerClientSideContainerClosingOnOpen() {
return false;
}
@Override
public AbstractContainerMenu createMenu(int id, Inventory inventory, Player player) {
return new CraftingTableMenuMenu(id, inventory, new FriendlyByteBuf(Unpooled.buffer()).writeBlockPos(_bpos));
}
}, _bpos);
}
}
} else if ((world.getBlockState(BlockPos.containing(x, y, z))).getBlock() == TaleOfBiomesModBlocks.BASIC_TOOL_TABLE.get()) {
if (entity.getData(TaleOfBiomesModVariables.PLAYER_VARIABLES).isRecipeHelperOpen) {
if (entity instanceof ServerPlayer _ent) {
BlockPos _bpos = BlockPos.containing(x, y, z);
_ent.openMenu(new MenuProvider() {
@Override
public Component getDisplayName() {
return Component.literal("BasicToolTableMenuRecipeBook");
}
@Override
public boolean shouldTriggerClientSideContainerClosingOnOpen() {
return false;
}
@Override
public AbstractContainerMenu createMenu(int id, Inventory inventory, Player player) {
return new BasicToolTableMenuRecipeBookMenu(id, inventory, new FriendlyByteBuf(Unpooled.buffer()).writeBlockPos(_bpos));
}
}, _bpos);
}
} else {
if (entity instanceof ServerPlayer _ent) {
BlockPos _bpos = BlockPos.containing(x, y, z);
_ent.openMenu(new MenuProvider() {
@Override
public Component getDisplayName() {
return Component.literal("BasicToolTableMenu");
}
@Override
public boolean shouldTriggerClientSideContainerClosingOnOpen() {
return false;
}
@Override
public AbstractContainerMenu createMenu(int id, Inventory inventory, Player player) {
return new BasicToolTableMenuMenu(id, inventory, new FriendlyByteBuf(Unpooled.buffer()).writeBlockPos(_bpos));
}
}, _bpos);
}
}
} else if ((world.getBlockState(BlockPos.containing(x, y, z))).getBlock() == TaleOfBiomesModBlocks.BASIC_STONE_TABLE.get()) {
if (entity.getData(TaleOfBiomesModVariables.PLAYER_VARIABLES).isRecipeHelperOpen) {
if (entity instanceof ServerPlayer _ent) {
BlockPos _bpos = BlockPos.containing(x, y, z);
_ent.openMenu(new MenuProvider() {
@Override
public Component getDisplayName() {
return Component.literal("BasicStoneTableMenuRecipeBook");
}
@Override
public boolean shouldTriggerClientSideContainerClosingOnOpen() {
return false;
}
@Override
public AbstractContainerMenu createMenu(int id, Inventory inventory, Player player) {
return new BasicStoneTableMenuRecipeBookMenu(id, inventory, new FriendlyByteBuf(Unpooled.buffer()).writeBlockPos(_bpos));
}
}, _bpos);
}
} else {
if (entity instanceof ServerPlayer _ent) {
BlockPos _bpos = BlockPos.containing(x, y, z);
_ent.openMenu(new MenuProvider() {
@Override
public Component getDisplayName() {
return Component.literal("BasicStoneTableMenu");
}
@Override
public boolean shouldTriggerClientSideContainerClosingOnOpen() {
return false;
}
@Override
public AbstractContainerMenu createMenu(int id, Inventory inventory, Player player) {
return new BasicStoneTableMenuMenu(id, inventory, new FriendlyByteBuf(Unpooled.buffer()).writeBlockPos(_bpos));
}
}, _bpos);
}
}
}
}
}
}
| 0 | 0.934029 | 1 | 0.934029 | game-dev | MEDIA | 0.972729 | game-dev | 0.916644 | 1 | 0.916644 |
SEModCommunity/SE-Community-Mod-API | 2,829 | SEModAPIInternal/API/Entity/Sector/SectorObject/CubeGrid/CubeBlock/SolarPanelEntity.cs | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using Sandbox.Common.ObjectBuilders;
using SEModAPIInternal.API.Common;
using SEModAPIInternal.Support;
namespace SEModAPIInternal.API.Entity.Sector.SectorObject.CubeGrid.CubeBlock
{
[DataContract(Name = "SolarPanelEntityProxy")]
public class SolarPanelEntity : FunctionalBlockEntity
{
#region "Attributes"
private PowerProducer m_powerProducer;
private float m_maxPowerOutput;
public static string SolarPanelNamespace = "AAD9061F948E6A3635200145188D64A9";
public static string SolarPanelClass = "6238A2EF481D720035D5BC6E545E769C";
public static string SolarPanelSetMaxOutputMethod = "802879712B29AAC2DB4EC9F7B128C979";
#endregion
#region "Constructors and Intializers"
public SolarPanelEntity(CubeGridEntity parent, MyObjectBuilder_SolarPanel definition)
: base(parent, definition)
{
}
public SolarPanelEntity(CubeGridEntity parent, MyObjectBuilder_SolarPanel definition, Object backingObject)
: base(parent, definition, backingObject)
{
m_powerProducer = new PowerProducer(Parent.PowerManager, ActualObject);
}
#endregion
#region "Properties"
[IgnoreDataMember]
[Category("Solar Panel")]
[Browsable(false)]
[ReadOnly(true)]
internal new MyObjectBuilder_SolarPanel ObjectBuilder
{
get { return (MyObjectBuilder_SolarPanel)base.ObjectBuilder; }
set
{
base.ObjectBuilder = value;
}
}
[DataMember]
[Category("Solar Panel")]
public float MaxPower
{
get { return PowerProducer.MaxPowerOutput; }
set
{
m_maxPowerOutput = value;
Action action = InternalUpdateMaxPowerOutput;
SandboxGameAssemblyWrapper.Instance.EnqueueMainGameAction(action);
}
}
[DataMember]
[Category("Solar Panel")]
public float Power
{
get { return PowerProducer.PowerOutput; }
set { PowerProducer.PowerOutput = value; }
}
[IgnoreDataMember]
[Category("Solar Panel")]
[Browsable(false)]
[ReadOnly(true)]
internal PowerProducer PowerProducer
{
get { return m_powerProducer; }
}
#endregion
#region "Methods"
new public static bool ReflectionUnitTest()
{
try
{
bool result = true;
Type type = SandboxGameAssemblyWrapper.Instance.GetAssemblyType(SolarPanelNamespace, SolarPanelClass);
if (type == null)
throw new Exception("Could not find internal type for SolarPanelEntity");
result &= HasMethod(type, SolarPanelSetMaxOutputMethod);
return result;
}
catch (Exception ex)
{
Console.WriteLine(ex);
return false;
}
}
protected void InternalUpdateMaxPowerOutput()
{
InvokeEntityMethod(ActualObject, SolarPanelSetMaxOutputMethod, new object[] { m_maxPowerOutput });
}
#endregion
}
}
| 0 | 0.50648 | 1 | 0.50648 | game-dev | MEDIA | 0.712103 | game-dev | 0.558552 | 1 | 0.558552 |
SlimeKnights/TinkersConstruct | 2,952 | src/main/java/slimeknights/tconstruct/library/json/loot/TagPreferenceLootEntry.java | package slimeknights.tconstruct.library.json.loot;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializationContext;
import net.minecraft.core.registries.Registries;
import net.minecraft.tags.TagKey;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.storage.loot.LootContext;
import net.minecraft.world.level.storage.loot.entries.LootPoolEntryType;
import net.minecraft.world.level.storage.loot.entries.LootPoolSingletonContainer;
import net.minecraft.world.level.storage.loot.functions.LootItemFunction;
import net.minecraft.world.level.storage.loot.predicates.LootItemCondition;
import slimeknights.mantle.recipe.helper.TagPreference;
import slimeknights.mantle.util.JsonHelper;
import slimeknights.tconstruct.TConstruct;
import slimeknights.tconstruct.shared.TinkerCommons;
import java.util.function.Consumer;
/** @deprecated use {@link slimeknights.mantle.loot.entry.TagPreferenceLootEntry} */
@Deprecated(forRemoval = true)
public class TagPreferenceLootEntry extends LootPoolSingletonContainer {
private final TagKey<Item> tag;
protected TagPreferenceLootEntry(TagKey<Item> tag, int weight, int quality, LootItemCondition[] conditions, LootItemFunction[] functions) {
super(weight, quality, conditions, functions);
this.tag = tag;
}
@SuppressWarnings("removal")
@Override
public LootPoolEntryType getType() {
return TinkerCommons.lootTagPreference.get();
}
@Override
protected void createItemStack(Consumer<ItemStack> consumer, LootContext context) {
TagPreference.getPreference(tag).ifPresent(item -> consumer.accept(new ItemStack(item)));
}
/** @deprecated use {@link slimeknights.mantle.loot.entry.TagPreferenceLootEntry#tagPreference(TagKey)} */
@Deprecated(forRemoval = true)
public static LootPoolSingletonContainer.Builder<?> tagPreference(TagKey<Item> tag) {
return slimeknights.mantle.loot.entry.TagPreferenceLootEntry.tagPreference(tag);
}
public static class Serializer extends LootPoolSingletonContainer.Serializer<TagPreferenceLootEntry> {
@Override
public void serializeCustom(JsonObject json, TagPreferenceLootEntry object, JsonSerializationContext conditions) {
super.serializeCustom(json, object, conditions);
json.addProperty("tag", object.tag.location().toString());
}
@Override
protected TagPreferenceLootEntry deserialize(JsonObject json, JsonDeserializationContext context, int weight, int quality, LootItemCondition[] conditions, LootItemFunction[] functions) {
TConstruct.LOG.warn("Using deprecated tag preference loot entry 'tconstruct:tag_preference', use 'mantle:tag_preference' instead");
TagKey<Item> tag = TagKey.create(Registries.ITEM, JsonHelper.getResourceLocation(json, "tag"));
return new TagPreferenceLootEntry(tag, weight, quality, conditions, functions);
}
}
}
| 0 | 0.822299 | 1 | 0.822299 | game-dev | MEDIA | 0.997414 | game-dev | 0.928268 | 1 | 0.928268 |
Nebukam/PCGExtendedToolkit | 5,045 | Source/PCGExtendedToolkit/Private/Sampling/PCGExSampleNeighbors.cpp | // Copyright 2025 Timothé Lapetite and contributors
// Released under the MIT license https://opensource.org/license/MIT/
#include "Sampling/PCGExSampleNeighbors.h"
#include "Sampling/Neighbors/PCGExNeighborSampleAttribute.h"
#include "Sampling/Neighbors/PCGExNeighborSampleFactoryProvider.h"
#define LOCTEXT_NAMESPACE "PCGExSampleNeighbors"
#define PCGEX_NAMESPACE SampleNeighbors
TArray<FPCGPinProperties> UPCGExSampleNeighborsSettings::InputPinProperties() const
{
TArray<FPCGPinProperties> PinProperties = Super::InputPinProperties();
PCGEX_PIN_FACTORIES(PCGExNeighborSample::SourceSamplersLabel, "Neighbor samplers.", Required, FPCGExDataTypeInfoNeighborSampler::AsId())
return PinProperties;
}
PCGExData::EIOInit UPCGExSampleNeighborsSettings::GetEdgeOutputInitMode() const { return PCGExData::EIOInit::Forward; }
PCGExData::EIOInit UPCGExSampleNeighborsSettings::GetMainOutputInitMode() const { return PCGExData::EIOInit::Duplicate; }
PCGEX_INITIALIZE_ELEMENT(SampleNeighbors)
PCGEX_ELEMENT_BATCH_EDGE_IMPL_ADV(SampleNeighbors)
bool FPCGExSampleNeighborsElement::Boot(FPCGExContext* InContext) const
{
if (!FPCGExEdgesProcessorElement::Boot(InContext)) { return false; }
PCGEX_CONTEXT_AND_SETTINGS(SampleNeighbors)
if (!PCGExFactories::GetInputFactories(InContext, PCGExNeighborSample::SourceSamplersLabel, Context->SamplerFactories, {PCGExFactories::EType::Sampler}, false))
{
PCGE_LOG(Warning, GraphAndLog, FTEXT("No valid sampler found."));
return false;
}
// Sort samplers so higher priorities come last, as they have to potential to override values.
Context->SamplerFactories.Sort([&](const UPCGExNeighborSamplerFactoryData& A, const UPCGExNeighborSamplerFactoryData& B) { return A.Priority < B.Priority; });
return true;
}
bool FPCGExSampleNeighborsElement::ExecuteInternal(
FPCGContext* InContext) const
{
TRACE_CPUPROFILER_EVENT_SCOPE(FPCGExSampleNeighborsElement::Execute);
PCGEX_CONTEXT_AND_SETTINGS(SampleNeighbors)
PCGEX_EXECUTION_CHECK
PCGEX_ON_INITIAL_EXECUTION
{
if (!Context->StartProcessingClusters(
[](const TSharedPtr<PCGExData::FPointIOTaggedEntries>& Entries) { return true; },
[&](const TSharedPtr<PCGExClusterMT::IBatch>& NewBatch)
{
}))
{
return Context->CancelExecution(TEXT("Could not build any clusters."));
}
}
PCGEX_CLUSTER_BATCH_PROCESSING(PCGExCommon::State_Done)
Context->OutputPointsAndEdges();
return Context->TryComplete();
}
namespace PCGExSampleNeighbors
{
FProcessor::~FProcessor()
{
}
bool FProcessor::Process(const TSharedPtr<PCGExMT::FTaskManager>& InAsyncManager)
{
TRACE_CPUPROFILER_EVENT_SCOPE(PCGExSampleNeighbors::Process);
if (!IProcessor::Process(InAsyncManager)) { return false; }
for (const UPCGExNeighborSamplerFactoryData* OperationFactory : Context->SamplerFactories)
{
TSharedPtr<FPCGExNeighborSampleOperation> SamplingOperation = OperationFactory->CreateOperation(Context);
SamplingOperation->BindContext(Context);
SamplingOperation->PrepareForCluster(ExecutionContext, Cluster.ToSharedRef(), VtxDataFacade, EdgeDataFacade);
if (!SamplingOperation->IsOperationValid()) { continue; }
SamplingOperations.Add(SamplingOperation);
if (SamplingOperation->ValueFilters) { OpsWithValueTest.Add(SamplingOperation); }
}
Cluster->ComputeEdgeLengths();
if (!OpsWithValueTest.IsEmpty()) { StartParallelLoopForRange(NumNodes); }
else { StartParallelLoopForNodes(); }
return true;
}
void FProcessor::ProcessRange(const PCGExMT::FScope& Scope)
{
PCGEX_SCOPE_LOOP(Index)
{
for (const TSharedPtr<FPCGExNeighborSampleOperation>& Op : OpsWithValueTest)
{
Op->ValueFilters->Results[Index] = Op->ValueFilters->Test(*Cluster->GetNode(Index));
}
}
}
void FProcessor::OnRangeProcessingComplete()
{
StartParallelLoopForNodes();
}
void FProcessor::PrepareLoopScopesForNodes(const TArray<PCGExMT::FScope>& Loops)
{
for (const TSharedPtr<FPCGExNeighborSampleOperation>& Op : SamplingOperations) { Op->PrepareForLoops(Loops); }
}
void FProcessor::ProcessNodes(const PCGExMT::FScope& Scope)
{
PCGEX_SCOPE_LOOP(Index)
{
for (const TSharedPtr<FPCGExNeighborSampleOperation>& Op : SamplingOperations) { Op->ProcessNode(Index, Scope); }
}
}
void FProcessor::Write()
{
for (const TSharedPtr<FPCGExNeighborSampleOperation>& Op : SamplingOperations) { Op->CompleteOperation(); }
EdgeDataFacade->WriteFastest(AsyncManager);
}
void FProcessor::Cleanup()
{
TProcessor<FPCGExSampleNeighborsContext, UPCGExSampleNeighborsSettings>::Cleanup();
SamplingOperations.Empty();
OpsWithValueTest.Empty();
}
void FBatch::RegisterBuffersDependencies(PCGExData::FFacadePreloader& FacadePreloader)
{
PCGEX_TYPED_CONTEXT_AND_SETTINGS(SampleNeighbors)
TBatch<FProcessor>::RegisterBuffersDependencies(FacadePreloader);
for (const UPCGExNeighborSamplerFactoryData* Factory : Context->SamplerFactories)
{
Factory->RegisterVtxBuffersDependencies(Context, VtxDataFacade, FacadePreloader);
}
}
}
#undef LOCTEXT_NAMESPACE
#undef PCGEX_NAMESPACE
| 0 | 0.765672 | 1 | 0.765672 | game-dev | MEDIA | 0.711762 | game-dev | 0.868574 | 1 | 0.868574 |
Panda381/PicoVGA | 14,189 | vga_sokoban/src/game.cpp |
// ****************************************************************************
//
// Game engine
//
// ****************************************************************************
#include "include.h"
// buffers
u8 Board[MAPWMAX*MAPHMAX]; // game board
int MapW, MapH; // current board dimension
int TileSize; // current tile size (16, 20, 24, 28 or 32)
// current game state
u16 MarkNum; // number of remaining marks
u8 LevelW, LevelH; // level width and height
u8 LevelX, LevelY; // level coordinates
u8 PosX, PosY; // player coordinates
s8 OffX, OffY; // board offset (0 or -TileSize/2)
// set player graphics position
void SetPlayer(int x, int y, u8 tile)
{
sLayer* lay = &LayerScreen[1];
lay->init = VGAKEY((x-OffX)*Vmode.cpp, TileSize, 65);
lay->y = y-OffY;
lay->img = &TilesImg_Copy[TileSize*tile];
lay->on = True;
}
// soft move player in direction
void MovePlayer(u8 dir)
{
int dx = (dir == DIR_L) ? -1 : ((dir == DIR_R) ? 1 : 0);
int dy = (dir == DIR_U) ? -1 : ((dir == DIR_D) ? 1 : 0);
int x = PosX*TileSize;
int y = PosY*TileSize;
u8 tile = FACE_R + dir*4;
SetPlayer(x, y, tile);
sleep_ms(MOVESPEED);
x += dx*(TileSize/4);
y += dy*(TileSize/4);
SetPlayer(x, y, tile);
sleep_ms(MOVESPEED);
x += dx*(TileSize/4);
y += dy*(TileSize/4);
u8 tile2 = tile + ((((PosX+PosY)&1) == 0) ? 1 : 3);
SetPlayer(x, y, tile2);
sleep_ms(MOVESPEED);
x += dx*(TileSize/4);
y += dy*(TileSize/4);
SetPlayer(x, y, tile2);
sleep_ms(MOVESPEED);
x += dx*(TileSize/4);
y += dy*(TileSize/4);
PosX += dx;
PosY += dy;
SetPlayer(x, y, tile);
}
// clear board
void ClearBoard()
{
memset(Board, EMPTY, MAPWMAX*MAPHMAX);
sLayer* lay = &LayerScreen[1];
lay->on = False;
}
// initialize level videomode (uses LevelW and LevelH)
void LevelVmode()
{
TileSize = 32;
MapW = WIDTH/TileSize;
MapH = HEIGHT/TileSize;
if ((LevelW > MapW) || (LevelH > MapH))
{
TileSize = 28;
MapW = WIDTH/TileSize;
MapH = HEIGHT/TileSize;
}
if ((LevelW > MapW) || (LevelH > MapH))
{
TileSize = 24;
MapW = WIDTH/TileSize;
MapH = HEIGHT/TileSize;
}
if ((LevelW > MapW) || (LevelH > MapH))
{
TileSize = 20;
MapW = WIDTH/TileSize;
MapH = HEIGHT/TileSize;
}
if ((LevelW > MapW) || (LevelH > MapH))
{
TileSize = 16;
MapW = WIDTH/TileSize;
MapH = HEIGHT/TileSize;
}
if ((LevelW > MapW) || (LevelH > MapH))
{
TileSize = 12;
MapW = WIDTH/TileSize;
MapH = HEIGHT/TileSize;
}
if ((LevelW > MapW) || (LevelH > MapH))
{
TileSize = 8;
MapW = WIDTH/TileSize;
MapH = HEIGHT/TileSize;
}
// prepare level coordinates
if (LevelW > MapW) LevelW = MapW;
if (LevelH > MapH) LevelH = MapH;
LevelX = (MapW - LevelW)/2;
LevelY = (MapH - LevelH)/2;
OffX = - ((MapW - LevelW) & 1) * (TileSize/2);
OffY = - ((MapH - LevelH) & 1) * (TileSize/2);
// set sprite
sLayer* lay = &LayerScreen[1];
lay->on = False;
__dmb();
lay->img = &TilesImg_Copy[TileSize*FACE_D];
lay->init = VGAKEY(((TileSize-1)*MapW/2-OffX)*Vmode.cpp, TileSize, 65);
lay->trans = TileSize/4;
lay->x = (TileSize-1)*MapW/2 - OffX;
lay->y = (TileSize-1)*MapH/2 - OffY;
lay->w = TileSize;
lay->h = TileSize;
lay->wb = TileSize*TILES_NUM;
// set tile mode
SetTileMode();
}
// display program info
void DispInfo()
{
printf("\nSokoban for Raspberry Pico\n");
printf("version " VERSION "\n");
printf(COPYRIGHT "\n");
uint sysclk = clock_get_hz(clk_sys);
printf("System clock: %u kHz\n", sysclk/1000);
// uint hfreq = sysclk/Vmode.div/Vmode.htot;
// float vfreq = (float)hfreq/Vmode.vtot;
printf("Screen resolution: %u x %u @ %.2f Hz, %d Hz, cpp %u\n",
Vmode.width, Vmode.height, Vmode.vfreq, (int)(Vmode.hfreq+0.5f), Vmode.div*Vmode.cpp);
printf("Total authors: %u\n", AutNum);
int i, j;
int k = 0;
int m = 0;
for (i = 0; i < AutNum; i++)
{
k += Author[i].collnum;
for (j = 0; j < Author[i].collnum; j++) m += Author[i].collect[j].levnum;
}
printf("Total collections: %u\n", k);
printf("Total levels: %u\n", m);
if (LevNum > 0)
{
printf("Current level %u, size %ux%u, board %ux%u, tile %u, collection %s\n",
Level+1, LevelW, LevelH, MapW, MapH, TileSize, CollName);
}
}
// detect board dimension
void BoardDim()
{
LevDef = Levels[Level*2]; // current level definition
LevSolve = Levels[Level*2+1]; // current level solve
// get board definition
const char* s = LevDef;
// detect board dimension
LevelW = 1;
LevelH = 0;
int i = 0;
char ch;
const char* s2 = s;
while ((ch = *s2++) != 0)
{
// next row
if ((ch == '!') || (ch == '|'))
{
LevelH++;
if (i > LevelW) LevelW = i;
i = 0;
}
else
i++;
}
if (i > LevelW) LevelW = i;
if (i > 0) LevelH++;
};
// initialize current level
// x = grass (empty)
// # = wall
// ! or | = next row
// space or _ or - = floor
// $ or b = box
// * or B = box on mark
// . = mark
// @ or p = player
// + or P = player on mark
void LevelInit()
{
// detect board dimension
BoardDim();
// initialize level videomode
LevelVmode();
// clear screen
ClearBoard();
// decode level
char ch;
int x, y;
y = LevelY;
x = LevelX;
MarkNum = 0;
PosX = LevelX + LevelW/2;
PosY = LevelY + LevelH/2;
u8* d = BoardAddr(x,y);
const char* s = LevDef;
while ((ch = *s++) != 0)
{
// next row
if ((ch == '!') || (ch == '|'))
{
y++;
if (y >= MapH) break;
x = LevelX;
d = BoardAddr(x,y);
}
else
{
if (x >= MapW) continue;
switch (ch)
{
// grass (empty)
case 'x':
ch = EMPTY;
break;
// wall
case '#':
ch = WALL;
break;
// player
case 'p':
case '@':
PosX = x;
PosY = y;
ch = FLOOR;
break;
// player on mark
case 'P':
case '+':
PosX = x;
PosY = y;
ch = MARK;
MarkNum++;
break;
// box
case 'b':
case '$':
ch = CRATE;
break;
// box on mark
case 'B':
case '*':
ch = FULL;
break;
// mark
case '.':
ch = MARK;
MarkNum++;
break;
// floor
// case ' ':
// case '_':
// case '-':
default:
ch = FLOOR;
break;
}
// increase position
*d++ = ch;
x++;
}
}
// set player, direction down
SetPlayer(PosX*TileSize, PosY*TileSize, FACE_D);
// flush keys
FlushChar();
}
// check floor (with or without mark, but no box)
Bool IsFloor(u8 x, u8 y)
{
if (((u32)x >= (u32)MapW) || ((u32)y >= (u32)MapH)) return False;
u8 tile = *BoardAddr(x,y);
return (tile == FLOOR) || (tile == MARK);
}
// check box (with or without mark)
Bool IsBox(u8 x, u8 y)
{
if (((u32)x >= (u32)MapW) || ((u32)y >= (u32)MapH)) return False;
u8 tile = *BoardAddr(x,y);
return (tile == CRATE) || (tile == FULL);
}
// check mark (with or without box)
Bool IsMark(u8 x, u8 y)
{
if (((u32)x >= (u32)MapW) || ((u32)y >= (u32)MapH)) return False;
u8 tile = *BoardAddr(x,y);
return (tile == MARK) || (tile == FULL);
}
// hide box
void HideBox(u8 x, u8 y)
{
u8* b = BoardAddr(x, y);
u8 tile = *b;
if (tile == FULL)
{
MarkNum++;
*b = MARK;
}
else
{
*b = FLOOR;
}
}
// show box
void ShowBox(u8 x, u8 y)
{
u8* b = BoardAddr(x, y);
u8 tile = *b;
if (tile == MARK)
{
MarkNum--;
*b = FULL;
}
else
{
*b = CRATE;
}
}
// step one level (key = move key, returns False on unsupported key)
Bool Step(char key)
{
int dx = (key == KEY_L) ? -1 : ((key == KEY_R) ? 1 : 0);
int dy = (key == KEY_U) ? -1 : ((key == KEY_D) ? 1 : 0);
if (dx + dy == 0) return False;
if (IsBox(PosX+dx, PosY+dy) && (IsFloor(PosX+2*dx, PosY+2*dy)))
{
HideBox(PosX+dx, PosY+dy);
ShowBox(PosX+2*dx, PosY+2*dy);
}
int dir = (key == KEY_L) ? DIR_L :
((key == KEY_R) ? DIR_R :
((key == KEY_U) ? DIR_U : DIR_D));
if (IsFloor(PosX+dx, PosY+dy)) MovePlayer(dir);
return True;
}
// step solve animation (return True = break)
Bool StepAnim(char key)
{
if ((key >= 'a') && (key <= 'z')) key -= 32;
if (key == 'L')
Step(KEY_L);
else if (key == 'R')
Step(KEY_R);
else if (key == 'U')
Step(KEY_U);
else if (key == 'D')
Step(KEY_D);
return (GetChar() != 0);
}
// play subanimation (in brackets; returns True = break)
Bool SubAnim(const char* s)
{
int i;
char ch;
while ((ch = *s++) != 0)
{
// end of brackets
if (ch == ')') break;
// loop (except last passage of the loop)
if ((ch >= '0') && (ch <= '9'))
{
i = ch - '0';
for (; i > 1; i--) if (StepAnim(*s)) return True;
continue;
}
if (StepAnim(ch)) return True;
}
return False;
}
// play level solve (returns True on break from keyboard)
Bool PlaySolve()
{
int i;
// re-initialize current level
LevelInit();
// prepare pointer to level solution
const char* s = LevSolve;
// macro loop
char ch;
while ((ch = *s++) != 0)
{
if ((ch == '(') || (ch == ')')) continue;
// loop (except last passage of the loop)
if ((ch >= '0') && (ch <= '9'))
{
i = ch - '0';
ch = *s;
if ((ch >= '0') && (ch <= '9'))
{
i = i*10 + (ch - '0');
s++;
}
for (; i > 1; i--)
{
if (*s == '(')
{
if (SubAnim(s+1)) return True;
}
else
if (StepAnim(*s)) return True;
}
continue;
}
// step
if (StepAnim(ch)) return True;
}
#ifndef AUTOMODE // automode - autorun all levels to check solutions
// solved animation
SolvedAnim();
#endif
return False;
}
// display solved animation (returns True of solved)
Bool SolvedAnim()
{
// check if solved
if (MarkNum > 0) return False;
#ifdef AUTOMODE // automode - autorun all levels to check solutions
return True;
#endif
// play sound
PlaySound(YippeeSnd, sizeof(YippeeSnd));
// animation
int i, j;
u8* s;
u8 k;
sLayer* lay = &LayerScreen[1];
for (i = 5; i > 0; i--)
{
// hide boxes
s = Board;
for (j = MapW*MapH; j > 0; j--)
{
k = *s;
if (k == FULL) *s = MARK;
s++;
}
// set winning image
lay->img = &TilesImg_Copy[TileSize*FACE_WIN];
// delay
sleep_ms(100);
// show boxes
s = Board;
for (j = MapW*MapH; j > 0; j--)
{
k = *s;
if (k == MARK) *s = FULL;
s++;
}
// set down image
lay->img = &TilesImg_Copy[TileSize*FACE_D];
// delay
sleep_ms(100);
}
return True;
}
// display help
void DispHelp()
{
printf("\n");
printf("%c ... right\n", KEY_R);
printf("%c ... up\n", KEY_U);
printf("%c ... left\n", KEY_L);
printf("%c ... down\n", KEY_D);
printf("%c ... help solve scene\n", KEY_HELP);
printf("%c ... restart scene\n", KEY_RESTART);
printf("%c ... previous scene\n", KEY_PREV);
printf("%c ... next scene\n", KEY_NEXT);
printf("%c ... program info\n", KEY_INFO);
printf("Esc ... leave scene\n");
}
// level info
void LevelInfo()
{
SetTextMode();
FlushChar();
PrintSetCol(PC_COLOR(PC_BLACK, PC_WHITE));
PrintSetPos(4,1);
PrintText(SelAuthor);
PrintText(AutName);
PrintSetPos(4,3);
PrintText(SelColl);
PrintText(CollName);
PrintSetPos((TEXTW-8)/2, 10);
PrintText("LEVEL ");
char buf[12];
DecNum(buf, Level+1);
PrintText(buf);
}
// game loop
void GameLoop()
{
int i;
// initialize current level
LevelInit();
// flush characters from keyboard
FlushChar();
while (True)
{
// get key
i = GetChar();
#ifdef AUTOMODE // automode - autorun all levels to check solutions
if (i == 0)
{
int a, c;
int levinx, levcur, levnum;
levnum = 0;
levcur = 0;
levinx = 0;
for (a = 0; a < AutNum; a++)
{
for (c = 0; c < Author[a].collnum; c++)
{
if ((a == AutInx) && (c == CollInx)) levcur = levnum + Level;
levnum += Author[a].collect[c].levnum;
}
}
printf("checking level %u (%u of %u) of collection %s by %s\n",
Level+1, levcur, levnum, CollName, AutName);
sleep_ms(10); // delay to complete message transmission
i = KEY_HELP;
}
#endif
if (i != 0)
{
// Esc return to selection
if ((i == KEY_ESC) || (i == KEY_ESC2) || (i == KEY_ESC3)) return;
// program info
if (i == KEY_INFO)
{
DispInfo();
}
// help solution
else if (i == KEY_HELP)
{
#ifdef AUTOMODE // automode - autorun all levels to check solutions
if (PlaySolve()) return;
if (GetChar() != 0) return;
#else
PlaySolve();
LevelInit();
#endif
}
// restart scene
else if (i == KEY_RESTART)
{
LevelInit();
}
// next scene
else if (i == KEY_NEXT)
{
Level++;
if (Level >= LevNum) Level = 0;
LevelInfo();
sleep_ms(200);
FlushChar();
LevelInit();
}
// previous scene
else if (i == KEY_PREV)
{
Level--;
if (Level < 0) Level = LevNum-1;
LevelInfo();
sleep_ms(200);
FlushChar();
LevelInit();
}
// step
else
{
// one step
FlushChar();
if (!Step(i))
{
// invalid character
DispHelp();
}
}
// solved
if (SolvedAnim())
{
sleep_ms(200);
ClearBoard();
#ifndef AUTOMODE // automode - autorun all levels to check solutions
sleep_ms(200);
#endif
// increase scene level
Level++;
if (Level >= LevNum)
#ifdef AUTOMODE // automode - autorun all levels to check solutions
{
// next collection of current author
int c = CollInx + 1;
if (c < CollNum)
{
CollInx = c; // select next collection
Level = 0; // selected level
CollName = Collect[c].name; // name of collection
Levels = Collect[c].levels; // pointer to list of levels
LevNum = Collect[c].levnum; // number of levels
}
//
else
{
// next author
int a = AutInx + 1;
if (a < AutNum)
{
AutInx = a;
CollInx = 0; // selected collection
AutName = Author[a].author; // author's name
Collect = Author[a].collect; // pointer to list of collections
CollNum = Author[a].collnum; // number of collections
Level = 0; // selected level
CollName = Collect[0].name; // name of collection
Levels = Collect[0].levels; // pointer to list of levels
LevNum = Collect[0].levnum; // number of levels
}
// else stop at last level
else
{
Level--;
return;
}
}
}
if (GetChar() != 0) return;
LevelInit();
#else
// else reset to first level
Level = 0;
// level info
LevelInfo();
sleep_ms(1500);
FlushChar();
LevelInit();
FlushChar();
#endif
}
}
}
}
| 0 | 0.768032 | 1 | 0.768032 | game-dev | MEDIA | 0.851848 | game-dev | 0.981134 | 1 | 0.981134 |
hutian23/ETScript | 4,426 | Unity/Assets/Scripts/Editor/EUI/UICodeSpawn/LoopScrollItemCodeSpawner.cs |
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.IO;
using System.Text;
using ET;
public partial class UICodeSpawner
{
static public void SpawnLoopItemCode(GameObject gameObject)
{
Path2WidgetCachedDict?.Clear();
Path2WidgetCachedDict = new Dictionary<string, List<Component>>();
FindAllWidgets(gameObject.transform, "");
SpawnCodeForScrollLoopItemBehaviour(gameObject);
SpawnCodeForScrollLoopItemViewSystem(gameObject);
AssetDatabase.Refresh();
}
static void SpawnCodeForScrollLoopItemViewSystem(GameObject gameObject)
{
if (null == gameObject)
{
return;
}
string strDlgName = gameObject.name;
string strFilePath = Application.dataPath + "/Scripts/Codes/HotfixView/Client/Demo/UIItemBehaviour";
if ( !System.IO.Directory.Exists(strFilePath) )
{
System.IO.Directory.CreateDirectory(strFilePath);
}
strFilePath = Application.dataPath + "/Scripts/Codes/HotfixView/Client/Demo/UIItemBehaviour/" + strDlgName + "ViewSystem.cs";
StreamWriter sw = new StreamWriter(strFilePath, false, Encoding.UTF8);
StringBuilder strBuilder = new StringBuilder();
strBuilder.AppendLine()
.AppendLine("using UnityEngine;");
strBuilder.AppendLine("using UnityEngine.UI;");
strBuilder.AppendLine("namespace ET.Client");
strBuilder.AppendLine("{");
strBuilder.AppendLine("\t[ObjectSystem]");
strBuilder.AppendFormat("\tpublic class Scroll_{0}DestroySystem : DestroySystem<Scroll_{1}> \r\n", strDlgName, strDlgName);
strBuilder.AppendLine("\t{");
strBuilder.AppendFormat("\t\tprotected override void Destroy( Scroll_{0} self )",strDlgName);
strBuilder.AppendLine("\n\t\t{");
strBuilder.AppendFormat("\t\t\tself.DestroyWidget();\r\n");
strBuilder.AppendLine("\t\t}");
strBuilder.AppendLine("\t}");
strBuilder.AppendLine("}");
sw.Write(strBuilder);
sw.Flush();
sw.Close();
}
static void SpawnCodeForScrollLoopItemBehaviour(GameObject gameObject)
{
if (null == gameObject)
{
return;
}
string strDlgName = gameObject.name;
string strFilePath = Application.dataPath + "/Scripts/Codes/ModelView/Client/Demo/UIItemBehaviour";
if ( !System.IO.Directory.Exists(strFilePath) )
{
System.IO.Directory.CreateDirectory(strFilePath);
}
strFilePath = Application.dataPath + "/Scripts/Codes/ModelView/Client/Demo/UIItemBehaviour/" + strDlgName + ".cs";
StreamWriter sw = new StreamWriter(strFilePath, false, Encoding.UTF8);
StringBuilder strBuilder = new StringBuilder();
strBuilder.AppendLine()
.AppendLine("using UnityEngine;");
strBuilder.AppendLine("using UnityEngine.UI;");
strBuilder.AppendLine("namespace ET.Client");
strBuilder.AppendLine("{");
strBuilder.AppendLine("\t[EnableMethod]");
strBuilder.AppendFormat("\tpublic class Scroll_{0} : Entity,IAwake,ILoad,IDestroy,IUIScrollItem \r\n", strDlgName)
.AppendLine("\t{");
strBuilder.AppendLine("\t\tpublic long DataId {get;set;}");
strBuilder.AppendLine("\t\tprivate bool isCacheNode = false;");
strBuilder.AppendLine("\t\tpublic void SetCacheMode(bool isCache)");
strBuilder.AppendLine("\t\t{");
strBuilder.AppendLine("\t\t\tthis.isCacheNode = isCache;");
strBuilder.AppendLine("\t\t}\n");
strBuilder.AppendFormat("\t\tpublic Scroll_{0} BindTrans(Transform trans)\r\n",strDlgName);
strBuilder.AppendLine("\t\t{");
strBuilder.AppendLine("\t\t\tthis.uiTransform = trans;");
strBuilder.AppendLine("\t\t\treturn this;");
strBuilder.AppendLine("\t\t}\n");
CreateWidgetBindCode(ref strBuilder, gameObject.transform);
CreateDestroyWidgetCode(ref strBuilder,true);
CreateDeclareCode(ref strBuilder);
strBuilder.AppendLine("\t\tpublic Transform uiTransform = null;");
strBuilder.AppendLine("\t}");
strBuilder.AppendLine("}");
sw.Write(strBuilder);
sw.Flush();
sw.Close();
}
}
| 0 | 0.866186 | 1 | 0.866186 | game-dev | MEDIA | 0.706939 | game-dev | 0.917275 | 1 | 0.917275 |
FrankvdStam/SoulSplitter | 3,871 | src/SoulSplitter/Splitters/ArmoredCore6Splitter.cs | // This file is part of the SoulSplitter distribution (https://github.com/FrankvdStam/SoulSplitter).
// Copyright (c) 2022 Frank van der Stam.
// https://github.com/FrankvdStam/SoulSplitter/blob/main/LICENSE
//
// 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, version 3.
//
// 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/>.
using LiveSplit.Model;
using SoulMemory;
using System;
using System.Collections.Generic;
using System.Linq;
using SoulMemory.ArmoredCore6;
using SoulSplitter.Splits.ArmoredCore6;
using SoulSplitter.UI.Generic;
namespace SoulSplitter.Splitters;
public class ArmoredCore6Splitter(LiveSplitState state, IGame game) : BaseSplitter(state, game)
{
private readonly ArmoredCore6 _armoredCore6 = (ArmoredCore6)game;
public override void OnStart()
{
//Copy splits on start
_splits = (
from timingType in _mainViewModel.ArmoredCore6ViewModel.SplitsViewModel.Splits
from splitType in timingType.Children
from split in splitType.Children
select new Split(timingType.TimingType, splitType.SplitType, split.Split)
).ToList();
}
public override ResultErr<RefreshError> OnUpdate()
{
switch (_timerState)
{
case TimerState.Running:
_mainViewModel.TryAndHandleError(UpdateAutoSplitter);
var currentIgt = _armoredCore6.GetInGameTimeMilliseconds();
//Detect game crash or quit out
if (currentIgt < 1000 && _inGameTime > 1000)
{
_inGameTime += currentIgt;
_armoredCore6.WriteInGameTimeMilliseconds(_inGameTime);
}
if (currentIgt > _inGameTime)
{
_inGameTime = currentIgt;
}
_timerModel.CurrentState.SetGameTime(TimeSpan.FromMilliseconds(_inGameTime));
break;
}
return Result.Ok();
}
#region Autosplitting
private List<Split> _splits = [];
private void UpdateAutoSplitter()
{
if (_timerState != TimerState.Running)
{
return;
}
foreach (var s in _splits)
{
if (!s.SplitTriggered)
{
if (!s.SplitConditionMet)
{
s.SplitConditionMet = s.SplitType switch
{
SplitType.Flag => _armoredCore6.ReadEventFlag(s.Flag),
_ => throw new ArgumentException($"Unsupported split type {s.SplitType}")
};
}
if (s.SplitConditionMet)
{
ResolveSplitTiming(s);
}
}
}
}
private void ResolveSplitTiming(Split s)
{
switch (s.TimingType)
{
default:
throw new ArgumentException($"Unsupported timing type {s.TimingType}");
case TimingType.Immediate:
_timerModel.Split();
s.SplitTriggered = true;
break;
case TimingType.OnLoading:
if (_armoredCore6.IsLoadingScreenVisible())
{
_timerModel.Split();
s.SplitTriggered = true;
}
break;
}
}
#endregion
}
| 0 | 0.815284 | 1 | 0.815284 | game-dev | MEDIA | 0.699661 | game-dev | 0.972445 | 1 | 0.972445 |
proepkes/UnityLockstep | 2,441 | Engine/Core.State/Generated/Game/Components/GameVelocityComponent.cs | //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by Entitas.CodeGeneration.Plugins.ComponentEntityApiGenerator.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
public partial class GameEntity {
public Lockstep.Core.State.Game.VelocityComponent velocity { get { return (Lockstep.Core.State.Game.VelocityComponent)GetComponent(GameComponentsLookup.Velocity); } }
public bool hasVelocity { get { return HasComponent(GameComponentsLookup.Velocity); } }
public void AddVelocity(BEPUutilities.Vector2 newValue) {
var index = GameComponentsLookup.Velocity;
var component = (Lockstep.Core.State.Game.VelocityComponent)CreateComponent(index, typeof(Lockstep.Core.State.Game.VelocityComponent));
component.value = newValue;
AddComponent(index, component);
}
public void ReplaceVelocity(BEPUutilities.Vector2 newValue) {
var index = GameComponentsLookup.Velocity;
var component = (Lockstep.Core.State.Game.VelocityComponent)CreateComponent(index, typeof(Lockstep.Core.State.Game.VelocityComponent));
component.value = newValue;
ReplaceComponent(index, component);
}
public void RemoveVelocity() {
RemoveComponent(GameComponentsLookup.Velocity);
}
}
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by Entitas.CodeGeneration.Plugins.ComponentMatcherApiGenerator.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
public sealed partial class GameMatcher {
static Entitas.IMatcher<GameEntity> _matcherVelocity;
public static Entitas.IMatcher<GameEntity> Velocity {
get {
if (_matcherVelocity == null) {
var matcher = (Entitas.Matcher<GameEntity>)Entitas.Matcher<GameEntity>.AllOf(GameComponentsLookup.Velocity);
matcher.componentNames = GameComponentsLookup.componentNames;
_matcherVelocity = matcher;
}
return _matcherVelocity;
}
}
}
| 0 | 0.690861 | 1 | 0.690861 | game-dev | MEDIA | 0.958505 | game-dev | 0.846769 | 1 | 0.846769 |
dotnetcore/NPOI | 21,192 | src/NPOI/POIFS/FileSystem/POIFSDocument.cs | /* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You 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.
==================================================================== */
/* ================================================================
* About NPOI
* Author: Tony Qu
* Author's email: tonyqus (at) gmail.com
* Author's Blog: tonyqus.wordpress.com.cn (wp.tonyqus.cn)
* HomePage: http://www.codeplex.com/npoi
* Contributors:
*
* ==============================================================*/
using System;
using System.Text;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using NPOI.POIFS.Common;
using NPOI.POIFS.Storage;
using NPOI.POIFS.Dev;
using NPOI.POIFS.Properties;
using NPOI.POIFS.EventFileSystem;
using NPOI.Util;
namespace NPOI.POIFS.FileSystem
{
/// <summary>
/// This class manages a document in the POIFS filesystem.
/// @author Marc Johnson (mjohnson at apache dot org)
/// </summary>
public class POIFSDocument : BATManaged, BlockWritable, POIFSViewable
{
private static DocumentBlock[] EMPTY_BIG_BLOCK_ARRAY = { };
private static SmallDocumentBlock[] EMPTY_SMALL_BLOCK_ARRAY = { };
private DocumentProperty _property;
private int _size;
private POIFSBigBlockSize _bigBigBlockSize;
private SmallBlockStore _small_store;
private BigBlockStore _big_store;
public POIFSDocument(string name, RawDataBlock[] blocks, int length)
{
_size = length;
if (blocks.Length == 0)
_bigBigBlockSize = POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS;
else
{
_bigBigBlockSize = (blocks[0].BigBlockSize == POIFSConstants.SMALLER_BIG_BLOCK_SIZE ?
POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS : POIFSConstants.LARGER_BIG_BLOCK_SIZE_DETAILS);
}
_big_store = new BigBlockStore(_bigBigBlockSize, ConvertRawBlocksToBigBlocks(blocks));
_property = new DocumentProperty(name, _size);
_small_store = new SmallBlockStore(_bigBigBlockSize, EMPTY_SMALL_BLOCK_ARRAY);
_property.Document = this;
}
private static DocumentBlock[] ConvertRawBlocksToBigBlocks(ListManagedBlock[] blocks)
{
DocumentBlock[] result = new DocumentBlock[blocks.Length];
for (int i = 0; i < result.Length; i++)
result[i] = new DocumentBlock((RawDataBlock)blocks[i]);
return result;
}
private static SmallDocumentBlock[] ConvertRawBlocksToSmallBlocks(ListManagedBlock[] blocks)
{
if (blocks is SmallDocumentBlock[])
return (SmallDocumentBlock[])blocks;
SmallDocumentBlock[] result = new SmallDocumentBlock[blocks.Length];
System.Array.Copy(blocks, 0, result, 0, blocks.Length);
return result;
}
public POIFSDocument(string name, SmallDocumentBlock[] blocks, int length)
{
_size = length;
if(blocks.Length == 0)
_bigBigBlockSize = POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS;
else
_bigBigBlockSize = blocks[0].BigBlockSize;
_big_store = new BigBlockStore(_bigBigBlockSize, EMPTY_BIG_BLOCK_ARRAY);
_property = new DocumentProperty(name, _size);
_small_store = new SmallBlockStore(_bigBigBlockSize, blocks);
_property.Document = this;
}
public POIFSDocument(string name, POIFSBigBlockSize bigBlockSize, ListManagedBlock[] blocks, int length)
{
_size = length;
_bigBigBlockSize = bigBlockSize;
_property = new DocumentProperty(name, _size);
_property.Document = this;
if (Property.IsSmall(_size))
{
_big_store = new BigBlockStore(bigBlockSize, EMPTY_BIG_BLOCK_ARRAY);
_small_store = new SmallBlockStore(bigBlockSize, ConvertRawBlocksToSmallBlocks(blocks));
}
else
{
_big_store = new BigBlockStore(bigBlockSize, ConvertRawBlocksToBigBlocks(blocks));
_small_store = new SmallBlockStore(bigBlockSize, EMPTY_SMALL_BLOCK_ARRAY);
}
}
public POIFSDocument(string name, POIFSBigBlockSize bigBlockSize, Stream stream)
{
List<DocumentBlock> blocks = new List<DocumentBlock>();
_size = 0;
_bigBigBlockSize = bigBlockSize;
while (true)
{
DocumentBlock block = new DocumentBlock(stream, bigBlockSize);
int blockSize = block.Size;
if (blockSize > 0)
{
blocks.Add(block);
_size += blockSize;
}
if (block.PartiallyRead)
break;
}
DocumentBlock[] bigBlocks = blocks.ToArray();
_big_store = new BigBlockStore(bigBlockSize, bigBlocks);
_property = new DocumentProperty(name, _size);
_property.Document = this;
if (_property.ShouldUseSmallBlocks)
{
_small_store = new SmallBlockStore(bigBlockSize, SmallDocumentBlock.Convert(bigBlockSize, bigBlocks, _size));
_big_store = new BigBlockStore(bigBlockSize, new DocumentBlock[0]);
}
else
{
_small_store = new SmallBlockStore(bigBlockSize, EMPTY_SMALL_BLOCK_ARRAY);
}
}
/// <summary>
/// Initializes a new instance of the <see cref="POIFSDocument"/> class.
/// </summary>
/// <param name="name">the name of the POIFSDocument</param>
/// <param name="stream">the InputStream we read data from</param>
public POIFSDocument(string name, Stream stream)
: this(name, POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, stream)
{
}
public POIFSDocument(string name, int size, POIFSBigBlockSize bigBlockSize, POIFSDocumentPath path, POIFSWriterListener writer)
{
_size = size;
_bigBigBlockSize = bigBlockSize;
_property = new DocumentProperty(name, _size);
_property.Document = this;
if (_property.ShouldUseSmallBlocks)
{
_small_store = new SmallBlockStore(_bigBigBlockSize, path, name, size, writer);
_big_store = new BigBlockStore(_bigBigBlockSize, EMPTY_BIG_BLOCK_ARRAY);
}
else
{
_small_store = new SmallBlockStore(_bigBigBlockSize, EMPTY_SMALL_BLOCK_ARRAY);
_big_store = new BigBlockStore(_bigBigBlockSize, path, name, size, writer);
}
}
public POIFSDocument(string name, int size, POIFSDocumentPath path, POIFSWriterListener writer)
:this(name, size, POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, path, writer)
{
}
/// <summary>
/// Constructor from small blocks
/// </summary>
/// <param name="name">the name of the POIFSDocument</param>
/// <param name="blocks">the small blocks making up the POIFSDocument</param>
/// <param name="length">the actual length of the POIFSDocument</param>
public POIFSDocument(string name, ListManagedBlock[] blocks, int length)
:this(name, POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, blocks, length)
{
}
/// <summary>
/// read data from the internal stores
/// </summary>
/// <param name="buffer">the buffer to write to</param>
/// <param name="offset">the offset into our storage to read from</param>
public virtual void Read(byte[] buffer, int offset)
{
if (this._property.ShouldUseSmallBlocks)
{
SmallDocumentBlock.Read(this._small_store.Blocks, buffer, offset);
}
else
{
DocumentBlock.Read(this._big_store.Blocks, buffer, offset);
}
}
/// <summary>
/// Writes the blocks.
/// </summary>
/// <param name="stream">The stream.</param>
public virtual void WriteBlocks(Stream stream)
{
this._big_store.WriteBlocks(stream);
}
public DataInputBlock GetDataInputBlock(int offset)
{
if (offset >= _size)
{
if (offset > _size)
{
throw new Exception("Request for Offset " + offset + " doc size is " + _size);
}
return null;
}
if (_property.ShouldUseSmallBlocks)
{
return SmallDocumentBlock.GetDataInputBlock(_small_store.Blocks, offset);
}
return DocumentBlock.GetDataInputBlock(_big_store.Blocks, offset);
}
/// <summary>
/// Gets the number of BigBlock's this instance uses
/// </summary>
/// <value>count of BigBlock instances</value>
public virtual int CountBlocks
{
get
{
return this._big_store.CountBlocks;
}
}
/// <summary>
/// Gets the document property.
/// </summary>
/// <value>The document property.</value>
public virtual DocumentProperty DocumentProperty
{
get
{
return this._property;
}
}
/// <summary>
/// Provides a short description of the object to be used when a
/// POIFSViewable object has not provided its contents.
/// </summary>
/// <value><c>true</c> if [prefer array]; otherwise, <c>false</c>.</value>
public virtual bool PreferArray
{
get
{
return true;
}
}
/// <summary>
/// Gets the short description.
/// </summary>
/// <value>The short description.</value>
public virtual string ShortDescription
{
get
{
StringBuilder builder = new StringBuilder();
builder.Append("Document: \"").Append(this._property.Name).Append("\"");
builder.Append(" size = ").Append(this.Size);
return builder.ToString();
}
}
/// <summary>
/// Gets the size.
/// </summary>
/// <value>The size.</value>
public virtual int Size
{
get
{
return this._size;
}
}
/// <summary>
/// Gets the small blocks.
/// </summary>
/// <value>The small blocks.</value>
public virtual BlockWritable[] SmallBlocks
{
get
{
return this._small_store.Blocks;
}
}
/// <summary>
/// Sets the start block for this instance
/// </summary>
/// <value>
/// index into the array of BigBlock instances making up the the filesystem
/// </value>
public virtual int StartBlock
{
get
{
return this._property.StartBlock;
}
set
{
this._property.StartBlock = value;
}
}
/// <summary>
/// Get an array of objects, some of which may implement POIFSViewable
/// </summary>
/// <value>The viewable array.</value>
public Array ViewableArray
{
get
{
string message;
object[] objArray = new object[1];
try
{
using (MemoryStream stream = new MemoryStream())
{
BlockWritable[] blocks = null;
if (this._big_store.Valid)
{
blocks = this._big_store.Blocks;
}
else if (this._small_store.Valid)
{
blocks = this._small_store.Blocks;
}
if (blocks != null)
{
for (int i = 0; i < blocks.Length; i++)
{
blocks[i].WriteBlocks(stream);
}
byte[] sourceArray = stream.ToArray();
if (sourceArray.Length > this._property.Size)
{
byte[] buffer2 = new byte[this._property.Size];
Array.Copy(sourceArray, 0, buffer2, 0, buffer2.Length);
sourceArray = buffer2;
}
using (MemoryStream ms = new MemoryStream())
{
HexDump.Dump(sourceArray, 0L, ms, 0);
byte[] buffer = ms.GetBuffer();
char[] destinationArray = new char[(int)ms.Length];
Array.Copy(buffer, 0, destinationArray, 0, destinationArray.Length);
message = new string(destinationArray);
}
}
else
{
message = "<NO DATA>";
}
}
}
catch (IOException exception)
{
message = exception.Message;
}
objArray[0] = message;
return objArray;
}
}
/// <summary>
/// Give viewers a hint as to whether to call ViewableArray or ViewableIterator
/// </summary>
/// <value>The viewable iterator.</value>
public virtual IEnumerator ViewableIterator
{
get
{
return ArrayList.ReadOnly(new ArrayList()).GetEnumerator();
}
}
public event POIFSWriterEventHandler BeforeWriting;
protected virtual void OnBeforeWriting(POIFSWriterEventArgs e)
{
if (BeforeWriting != null)
{
BeforeWriting(this, e);
}
}
internal class SmallBlockStore
{
private SmallDocumentBlock[] smallBlocks;
private POIFSDocumentPath path;
private string name;
private int size;
private POIFSWriterListener writer;
private POIFSBigBlockSize bigBlockSize;
internal SmallBlockStore(POIFSBigBlockSize bigBlockSize, SmallDocumentBlock[] blocks)
{
this.bigBlockSize = bigBlockSize;
smallBlocks = (SmallDocumentBlock[])blocks.Clone();
this.path = null;
this.name = null;
this.size = -1;
this.writer = null;
}
internal SmallBlockStore(POIFSBigBlockSize bigBlockSize, POIFSDocumentPath path, string name, int size, POIFSWriterListener writer)
{
this.bigBlockSize = bigBlockSize;
this.smallBlocks = new SmallDocumentBlock[0];
this.path = path;
this.name = name;
this.size = size;
this.writer = writer;
}
// internal virtual BlockWritable[] Blocks
internal virtual SmallDocumentBlock[] Blocks
{
get
{
if (this.Valid && (this.writer != null))
{
MemoryStream stream = new MemoryStream(this.size);
DocumentOutputStream dstream = new DocumentOutputStream(stream, this.size);
//OnBeforeWriting(new POIFSWriterEventArgs(dstream, this.path, this.name, this.size));
writer.ProcessPOIFSWriterEvent(new POIFSWriterEvent(dstream, this.path, this.name, this.size));
this.smallBlocks = SmallDocumentBlock.Convert(bigBlockSize, stream.ToArray(), this.size);
}
return this.smallBlocks;
}
}
internal virtual bool Valid
{
get
{
return ((this.smallBlocks.Length > 0) || (this.writer != null));
}
}
}
internal class BigBlockStore
{
private DocumentBlock[] bigBlocks;
private POIFSDocumentPath path;
private string name;
private int size;
private POIFSWriterListener writer;
private POIFSBigBlockSize bigBlockSize;
internal BigBlockStore(POIFSBigBlockSize bigBlockSize, DocumentBlock[] blocks)
{
this.bigBlockSize = bigBlockSize;
bigBlocks = (DocumentBlock[])blocks.Clone();
path = null;
name = null;
size = -1;
writer = null;
}
internal BigBlockStore(POIFSBigBlockSize bigBlockSize, POIFSDocumentPath path, string name, int size, POIFSWriterListener writer)
{
this.bigBlockSize = bigBlockSize;
this.bigBlocks = new DocumentBlock[0];
this.path = path;
this.name = name;
this.size = size;
this.writer = writer;
}
internal virtual bool Valid
{
get
{
return ((this.bigBlocks.Length > 0) || (this.writer != null));
}
}
internal virtual DocumentBlock[] Blocks
{
get
{
if (this.Valid && (this.writer != null))
{
MemoryStream stream = new MemoryStream(this.size);
DocumentOutputStream stream2 = new DocumentOutputStream(stream, this.size);
//OnBeforeWriting(new POIFSWriterEventArgs(stream2, this.path, this.name, this.size));
writer.ProcessPOIFSWriterEvent(new POIFSWriterEvent(stream2, path, name, size));
this.bigBlocks = DocumentBlock.Convert(bigBlockSize, stream.ToArray(), this.size);
}
return this.bigBlocks;
}
}
internal virtual void WriteBlocks(Stream stream)
{
if (this.Valid)
{
if (this.writer != null)
{
DocumentOutputStream stream2 = new DocumentOutputStream(stream, this.size);
//OnBeforeWriting(new POIFSWriterEventArgs(stream2, this.path, this.name, this.size));
writer.ProcessPOIFSWriterEvent(new POIFSWriterEvent(stream2, path, name, size));
stream2.WriteFiller(this.CountBlocks * POIFSConstants.BIG_BLOCK_SIZE, DocumentBlock.FillByte);
}
else
{
for (int i = 0; i < this.bigBlocks.Length; i++)
{
this.bigBlocks[i].WriteBlocks(stream);
}
}
}
}
internal virtual int CountBlocks
{
get
{
int num = 0;
if (!this.Valid)
{
return num;
}
if (this.writer != null)
{
return (((this.size + POIFSConstants.BIG_BLOCK_SIZE) - 1) / POIFSConstants.BIG_BLOCK_SIZE);
}
return this.bigBlocks.Length;
}
}
}
}
}
| 0 | 0.854016 | 1 | 0.854016 | game-dev | MEDIA | 0.225561 | game-dev | 0.835945 | 1 | 0.835945 |
11011010/BFA-Frankenstein-Core | 3,332 | src/server/scripts/Zandalar/TheUnderrot/instance_the_underrot.cpp | /*
* Copyright (C) 2020 BfaCore
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "AreaBoundary.h"
#include "GameObject.h"
#include "Player.h"
#include "ScriptMgr.h"
#include "InstanceScript.h"
#include "the_underrot.h"
BossBoundaryData const boundaries =
{
{ DATA_ELDER_LEAXA, new ZRangeBoundary(44.181206f, 63.479584f) },
{ DATA_CRAGMAW_THE_INFESTED, new CircleBoundary(Position(862.497009f, 982.315979f, 39.231701f), 90.f) },
{ DATA_SPORECALLER_ZANCHA, new ZRangeBoundary(20.f, 40.f) },
{ DATA_UNBOUND_ABOMINATION, new ZRangeBoundary(-200.f, -150.f) },
};
struct instance_the_underrot : public InstanceScript
{
instance_the_underrot(InstanceMap* map) : InstanceScript(map)
{
SetHeaders(DataHeader);
SetBossNumber(EncounterCount);
LoadBossBoundaries(boundaries);
instance->SummonCreatureGroup(SUMMON_GROUP_BLOODSWORN_DEFILER);
}
void OnCreatureCreate(Creature* creature) override
{
InstanceScript::OnCreatureCreate(creature);
switch (creature->GetEntry())
{
case NPC_TITAN_KEEPER_HEZREL:
{
if (creature->GetPositionZ() < -100.f)
AddObject(creature, DATA_BOSS_HERZEL, true);
else
AddObject(creature, DATA_EVENT_HERZEL, true);
break;
}
default:
break;
}
}
void SetData(uint32 type, uint32 data) override
{
switch (type)
{
case DATA_EVENT_HERZEL:
{
if (data == DONE)
{
if (GameObject* web = GetGameObject(GOB_PYRAMID_WEB))
web->RemoveFromWorld();
HandleGameObject(ObjectGuid::Empty, true, GetGameObject(GOB_PYRAMID_DOOR));
}
break;
}
case DATA_FACELESS_CORRUPTOR_1:
{
if (Creature* hezrel = GetCreature(DATA_EVENT_HERZEL))
hezrel->AI()->SetData(DATA_EVENT_HERZEL, 1);
break;
}
case DATA_FACELESS_CORRUPTOR_2:
{
if (GetData(DATA_FACELESS_CORRUPTOR_2) > 0)
if (Creature* hezrel = GetCreature(DATA_EVENT_HERZEL))
hezrel->AI()->SetData(DATA_EVENT_HERZEL, 2);
break;
}
}
InstanceScript::SetData(type, data);
}
};
void AddSC_instance_underrot()
{
RegisterInstanceScript(instance_the_underrot, 1841);
}
| 0 | 0.971959 | 1 | 0.971959 | game-dev | MEDIA | 0.937929 | game-dev | 0.93848 | 1 | 0.93848 |
ThePaperLuigi/The-Stars-Above | 3,250 | Projectiles/Other/Nanomachina/NanomachinaShieldProjectile.cs | using Microsoft.Xna.Framework;
using System;
using Terraria.ID;
using Terraria;
using Terraria.ModLoader;
using static Terraria.ModLoader.ModContent;
namespace StarsAbove.Projectiles.Other.Nanomachina
{
public class NanomachinaShieldProjectile : ModProjectile
{
public override void SetStaticDefaults()
{
// DisplayName.SetDefault("Nanomachina Shield"); //The English name of the projectile
ProjectileID.Sets.TrailCacheLength[Projectile.type] = 5; //The length of old position to be recorded
ProjectileID.Sets.TrailingMode[Projectile.type] = 0; //The recording mode
Main.projFrames[Projectile.type] = 1;
}
public override void SetDefaults()
{
Projectile.width = 128; //The width of projectile hitbox
Projectile.height = 128; //The height of projectile hitbox
Projectile.aiStyle = 0; //The ai style of the projectile, please reference the source code of Terraria
Projectile.friendly = true; //Can the projectile deal damage to enemies?
Projectile.hostile = false; //Can the projectile deal damage to the player?
Projectile.penetrate = -1; //How many monsters the projectile can penetrate. (OnTileCollide below also decrements penetrate for bounces as well)
Projectile.timeLeft = 10; //The live time for the projectile (60 = 1 second, so 600 is 10 seconds)
Projectile.alpha = 0; //The transparency of the projectile, 255 for completely transparent. (aiStyle 1 quickly fades the projectile in) Make sure to delete this if you aren't using an aiStyle that fades in. You'll wonder why your projectile is invisible.
Projectile.light = 2f; //How much light emit around the projectile
Projectile.ignoreWater = true; //Does the projectile's speed be influenced by water?
Projectile.tileCollide = false; //Can the projectile collide with tiles?
Projectile.extraUpdates = 0; //Set to above 0 if you want the projectile to update multiple time in a frame
DrawOriginOffsetY = 0;
DrawOffsetX = 0;
}
float rotationSpeed = 10f;
public override void AI()
{
Projectile.scale = 0.8f;
Projectile.timeLeft = 10;
Player projOwner = Main.player[Projectile.owner];
Player player = Main.player[Projectile.owner];
if (projOwner.dead && !projOwner.active || !projOwner.HasBuff(BuffType<Buffs.Other.Nanomachina.RealizedNanomachinaBuff>()))
{
Projectile.Kill();
}
Vector2 ownerMountedCenter = projOwner.RotatedRelativePoint(projOwner.MountedCenter, true);
Projectile.direction = projOwner.direction;
Projectile.position.X = ownerMountedCenter.X - Projectile.width / 2;
Projectile.position.Y = ownerMountedCenter.Y - Projectile.height / 2;
Projectile.spriteDirection = Projectile.direction;
Projectile.rotation += Projectile.velocity.X / 20f;
}
}
}
| 0 | 0.728571 | 1 | 0.728571 | game-dev | MEDIA | 0.994945 | game-dev | 0.728927 | 1 | 0.728927 |
CreatureChat/creature-chat | 1,777 | src/vs/v1_21_2/client/java/com/owlmaddie/skin/SkinUtils.java | // SPDX-FileCopyrightText: 2025 owlmaddie LLC
// SPDX-License-Identifier: GPL-3.0-or-later
// Assets CC-BY-NC-SA-4.0; CreatureChat™ trademark © owlmaddie LLC - unauthorized use prohibited
package com.owlmaddie.skin;
import com.mojang.blaze3d.platform.NativeImage;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.texture.AbstractTexture;
import net.minecraft.resources.ResourceLocation;
/**
* SkinUtils contains functions to check for certain black and white pixel values in a skin, to determine
* if the skin contains a custom hidden icon to show in the player chat message.
*/
public class SkinUtils {
public static boolean checkCustomSkinKey(ResourceLocation skinId) {
// Grab the AbstractTexture from the TextureManager
AbstractTexture tex = Minecraft.getInstance().getTextureManager().getTexture(skinId);
// Check if it implements our Mixin interface: IPlayerSkinTexture
if (tex instanceof IPlayerSkinTexture iSkin) {
// Get the NativeImage we stored in the Mixin
NativeImage image = iSkin.getLoadedImage();
if (image != null) {
int width = image.getWidth();
int height = image.getHeight();
// Check we have the full 64x64
if (width == 64 && height == 64) {
// Example: black & white pixel at (31,48) and (32,48)
int color31_48 = image.getPixel(31, 48);
int color32_48 = image.getPixel(32, 48);
return (color31_48 == 0xFF000000 && color32_48 == 0xFFFFFFFF);
}
}
}
// If it's still loading, or not a PlayerSkinTexture, or no NativeImage loaded yet
return false;
}
}
| 0 | 0.668382 | 1 | 0.668382 | game-dev | MEDIA | 0.648233 | game-dev,graphics-rendering | 0.752754 | 1 | 0.752754 |
colorblindness/3arthh4ck | 1,871 | src/main/java/me/earth/earthhack/impl/modules/player/speedmine/ListenerBlockChange.java | package me.earth.earthhack.impl.modules.player.speedmine;
import me.earth.earthhack.impl.event.events.network.PacketEvent;
import me.earth.earthhack.impl.event.listeners.ModuleListener;
import me.earth.earthhack.impl.modules.player.speedmine.mode.MineMode;
import net.minecraft.init.Blocks;
import net.minecraft.network.play.client.CPacketPlayerDigging;
import net.minecraft.network.play.server.SPacketBlockChange;
import net.minecraft.util.EnumFacing;
final class ListenerBlockChange extends
ModuleListener<Speedmine, PacketEvent.Receive<SPacketBlockChange>>
{
public ListenerBlockChange(Speedmine module)
{
super(module, PacketEvent.Receive.class, SPacketBlockChange.class);
}
@Override
public void invoke(PacketEvent.Receive<SPacketBlockChange> event)
{
SPacketBlockChange packet = event.getPacket();
if (packet.getBlockPosition().equals(module.pos)
&& packet.getBlockState().getBlock() == Blocks.AIR
&& (module.mode.getValue() != MineMode.Smart
|| module.sentPacket)
&& module.mode.getValue() != MineMode.Instant
&& module.mode.getValue() != MineMode.Civ)
{
mc.addScheduledTask(module::reset);
}
else if (packet.getBlockPosition().equals(module.pos)
&& packet.getBlockState() == mc.world.getBlockState(module.pos)
&& module.shouldAbort
&& module.mode.getValue() == MineMode.Instant)
{
mc.player.connection.sendPacket(
new CPacketPlayerDigging(CPacketPlayerDigging
.Action
.START_DESTROY_BLOCK,
module.pos,
EnumFacing.DOWN));
module.shouldAbort = false;
}
}
}
| 0 | 0.794072 | 1 | 0.794072 | game-dev | MEDIA | 0.990902 | game-dev | 0.721107 | 1 | 0.721107 |
EIRTeam/Project-Heartbeat | 1,751 | autoloads/rich_presence/HBRichPresenceProviderSteam.gd | extends HBRichPresenceProvider
class_name HBRichPresenceProviderSteam
func _init_rich_presence() -> int:
if Steamworks.is_valid():
return OK
return ERR_UNAVAILABLE
func _get_stage_status_localization_key(stage: HBRichPresence.RichPresenceStage) -> String:
var out := "#Status_AtMainMenu"
match stage:
HBRichPresence.RichPresenceStage.STAGE_AT_MAIN_MENU:
out = "#Status_AtMainMenu"
HBRichPresence.RichPresenceStage.STAGE_AT_SONG_LIST:
out = "#Status_AtSongList"
HBRichPresence.RichPresenceStage.STAGE_AT_EDITOR:
out = "#Status_AtEditor"
HBRichPresence.RichPresenceStage.STAGE_AT_EDITOR_SONG:
out = "#Status_AtEditorSong"
HBRichPresence.RichPresenceStage.STAGE_PLAYING:
out = "#Status_PlayingSong"
HBRichPresence.RichPresenceStage.STAGE_MULTIPLAYER_LOBBY:
out = "#Status_InLobby"
HBRichPresence.RichPresenceStage.STAGE_MULTIPLAYER_PLAYING:
out = "#Status_PlayingMultiplayer"
return out
func _cap_to_length(str: String, length: int) -> String:
if str.length() > length:
return str.substr(0, length)
return str
func _update_rich_presence(rich_presence_data: HBRichPresence):
const STEAM_DETAIL_MAX_LENGTH := 256
Steamworks.friends.set_rich_presence("steam_display", _get_stage_status_localization_key(rich_presence_data.current_stage))
if rich_presence_data.current_song:
Steamworks.friends.set_rich_presence("song", _cap_to_length(rich_presence_data.current_song.get_visible_title(rich_presence_data.current_song_variant), STEAM_DETAIL_MAX_LENGTH))
Steamworks.friends.set_rich_presence("difficulty", _cap_to_length(rich_presence_data.current_difficulty.to_upper(), STEAM_DETAIL_MAX_LENGTH))
Steamworks.friends.set_rich_presence("score", HBUtils.thousands_sep(rich_presence_data.current_score))
| 0 | 0.900633 | 1 | 0.900633 | game-dev | MEDIA | 0.374219 | game-dev | 0.943987 | 1 | 0.943987 |
Slingshot-Physics/slingshot-community | 1,357 | datamodel/data_shape_named.c | #include "data_shape_named.h"
#include "helper_data_to_json.h"
#include "helper_json_to_data.h"
void initialize_shapeNamed(data_shapeNamed_t * data)
{
memset(data, 0, sizeof(data_shapeNamed_t));
}
int shapeNamed_to_json(json_value_t * node, const data_shapeNamed_t * data)
{
if (node == NULL) return 0;
if (data == NULL) return 0;
if (!add_typename(node, "data_shapeNamed_t")) return 0;
if (!add_uint_field(node, "bodyId", data->bodyId)) return 0;
if (!add_int_field(node, "shapeName", (int )data->shapeName)) return 0;
return 1;
}
int shapeNamed_from_json(const json_value_t * node, data_shapeNamed_t * data)
{
if (node == NULL) return 0;
if (data == NULL) return 0;
if (!verify_typename(node, "data_shapeNamed_t")) return 0;
if (!copy_uint_field(node, "bodyId", &(data->bodyId))) return 0;
int temp_int;
if (!copy_int_field(node, "shapeName", &temp_int)) return 0;
data->shapeName = (data_shapeType_t )temp_int;
return 1;
}
int anon_shapeNamed_to_json(json_value_t * node, const void * anon_data)
{
const data_shapeNamed_t * data = (const data_shapeNamed_t *)anon_data;
return shapeNamed_to_json(node, data);
}
int anon_shapeNamed_from_json(const json_value_t * node, void * anon_data)
{
data_shapeNamed_t * data = (data_shapeNamed_t *)anon_data;
return shapeNamed_from_json(node, data);
}
| 0 | 0.912032 | 1 | 0.912032 | game-dev | MEDIA | 0.328262 | game-dev | 0.818613 | 1 | 0.818613 |
LtxProgrammer/Changed-Minecraft-Mod | 2,796 | src/main/java/net/ltxprogrammer/changed/client/AbilityColors.java | package net.ltxprogrammer.changed.client;
import net.ltxprogrammer.changed.ability.AbstractAbility;
import net.ltxprogrammer.changed.ability.AbstractAbilityInstance;
import net.ltxprogrammer.changed.client.gui.AbstractRadialScreen;
import net.ltxprogrammer.changed.entity.TransfurMode;
import net.ltxprogrammer.changed.init.ChangedAbilities;
import net.ltxprogrammer.changed.init.ChangedRegistry;
import java.util.Collection;
import java.util.Optional;
import java.util.function.Supplier;
public class AbilityColors {
public static final int DEFAULT = -1;
// FORGE: Use RegistryDelegates as non-Vanilla item ids are not constant
private final java.util.Map<net.minecraftforge.registries.IRegistryDelegate<AbstractAbility<?>>, AbilityColor> abilityColors = new java.util.HashMap<>();
public static AbstractRadialScreen.ColorScheme getAbilityColors(AbstractAbilityInstance abilityInstance) {
return AbstractRadialScreen.getColors(abilityInstance.entity.getTransfurVariantInstance()).setForegroundToBright();
}
public static AbilityColors createDefault() {
AbilityColors colors = new AbilityColors();
colors.register((abilityInstance, layer) -> {
var scheme = getAbilityColors(abilityInstance);
return Optional.of(switch (layer) {
case 0 -> scheme.foreground().toInt();
default -> DEFAULT;
});
}, ChangedRegistry.ABILITY.get().getValues());
colors.register((abilityInstance, layer) -> {
var scheme = getAbilityColors(abilityInstance);
TransfurMode mode = abilityInstance.entity.getTransfurMode();
if (layer == 0 && mode == TransfurMode.REPLICATION)
return Optional.of(scheme.foreground().toInt());
else if (layer == 1 && mode == TransfurMode.ABSORPTION)
return Optional.of(scheme.foreground().toInt());
return Optional.empty();
}, ChangedAbilities.SWITCH_TRANSFUR_MODE.get());
return colors;
}
public Optional<Integer> getColor(AbstractAbilityInstance abilityInstance, int layer) {
AbilityColor color = this.abilityColors.get(abilityInstance.getAbility().delegate);
return color == null ? Optional.of(DEFAULT) : color.getColor(abilityInstance, layer);
}
public void register(AbilityColor abilityColor, AbstractAbility<?>... abilities) {
for (AbstractAbility<?> ability : abilities) {
this.abilityColors.put(ability.delegate, abilityColor);
}
}
public void register(AbilityColor abilityColor, Collection<AbstractAbility<?>> abilities) {
for (AbstractAbility<?> ability : abilities) {
this.abilityColors.put(ability.delegate, abilityColor);
}
}
}
| 0 | 0.771393 | 1 | 0.771393 | game-dev | MEDIA | 0.568741 | game-dev | 0.820253 | 1 | 0.820253 |
Pizzalol/SpellLibrary | 15,118 | game/scripts/vscripts/heroes/hero_death_prophet/exorcism.lua | --[[
Author: Noya, physics by BMD
Date: 26.01.2016.
Spawns spirits for exorcism and applies the modifier that takes care of its logic
]]
function ExorcismStart( event )
local caster = event.caster
local ability = event.ability
local playerID = caster:GetPlayerID()
local radius = ability:GetLevelSpecialValueFor( "radius", ability:GetLevel() - 1 )
local duration = ability:GetLevelSpecialValueFor( "duration", ability:GetLevel() - 1 )
local spirits = ability:GetLevelSpecialValueFor( "spirits", ability:GetLevel() - 1 )
local delay_between_spirits = ability:GetLevelSpecialValueFor( "delay_between_spirits", ability:GetLevel() - 1 )
local unit_name = "npc_dummy_unit"
-- Initialize the table to keep track of all spirits
ability.spirits = {}
print("Spawning "..spirits.." spirits")
for i=1,spirits do
Timers:CreateTimer(i * delay_between_spirits, function()
local unit = CreateUnitByName(unit_name, caster:GetAbsOrigin(), true, caster, caster, caster:GetTeamNumber())
-- The modifier takes care of the physics and logic
ability:ApplyDataDrivenModifier(caster, unit, "modifier_exorcism_spirit", {})
-- Add the spawned unit to the table
table.insert(ability.spirits, unit)
-- Initialize the number of hits, to define the heal done after the ability ends
unit.numberOfHits = 0
-- Double check to kill the units, remove this later
Timers:CreateTimer(duration+10, function() if unit and IsValidEntity(unit) then unit:RemoveSelf() end end)
end)
end
end
-- Movement logic for each spirit
-- Units have 4 states:
-- acquiring: transition after completing one target-return cycle.
-- target_acquired: tracking an enemy or point to collide
-- returning: After colliding with an enemy, move back to the casters location
-- end: moving back to the caster to be destroyed and heal
function ExorcismPhysics( event )
local caster = event.caster
local unit = event.target
local ability = event.ability
local radius = ability:GetLevelSpecialValueFor( "radius", ability:GetLevel() - 1 )
local duration = ability:GetLevelSpecialValueFor( "duration", ability:GetLevel() - 1 )
local spirit_speed = ability:GetLevelSpecialValueFor( "spirit_speed", ability:GetLevel() - 1 )
local min_damage = ability:GetLevelSpecialValueFor( "min_damage", ability:GetLevel() - 1 )
local max_damage = ability:GetLevelSpecialValueFor( "max_damage", ability:GetLevel() - 1 )
local max_damage = ability:GetLevelSpecialValueFor( "max_damage", ability:GetLevel() - 1 )
local average_damage = ability:GetLevelSpecialValueFor( "average_damage", ability:GetLevel() - 1 )
local give_up_distance = ability:GetLevelSpecialValueFor( "give_up_distance", ability:GetLevel() - 1 )
local max_distance = ability:GetLevelSpecialValueFor( "max_distance", ability:GetLevel() - 1 )
local heal_percent = ability:GetLevelSpecialValueFor( "heal_percent", ability:GetLevel() - 1 ) * 0.01
local min_time_between_attacks = ability:GetLevelSpecialValueFor( "min_time_between_attacks", ability:GetLevel() - 1 )
local abilityDamageType = ability:GetAbilityDamageType()
local abilityTargetType = ability:GetAbilityTargetType()
local particleDamage = "particles/units/heroes/hero_death_prophet/death_prophet_exorcism_attack.vpcf"
local particleDamageBuilding = "particles/units/heroes/hero_death_prophet/death_prophet_exorcism_attack_building.vpcf"
--local particleNameHeal = "particles/units/heroes/hero_nyx_assassin/nyx_assassin_vendetta_start_sparks_b.vpcf"
-- Make the spirit a physics unit
Physics:Unit(unit)
-- General properties
unit:PreventDI(true)
unit:SetAutoUnstuck(false)
unit:SetNavCollisionType(PHYSICS_NAV_NOTHING)
unit:FollowNavMesh(false)
unit:SetPhysicsVelocityMax(spirit_speed)
unit:SetPhysicsVelocity(spirit_speed * RandomVector(1))
unit:SetPhysicsFriction(0)
unit:Hibernate(false)
unit:SetGroundBehavior(PHYSICS_GROUND_LOCK)
-- Initial default state
unit.state = "acquiring"
-- This is to skip frames
local frameCount = 0
-- Store the damage done
unit.damage_done = 0
-- Store the interval between attacks, starting at min_time_between_attacks
unit.last_attack_time = GameRules:GetGameTime() - min_time_between_attacks
-- Color Debugging for points and paths. Turn it false later!
local Debug = false
local pathColor = Vector(255,255,255) -- White to draw path
local targetColor = Vector(255,0,0) -- Red for enemy targets
local idleColor = Vector(0,255,0) -- Green for moving to idling points
local returnColor = Vector(0,0,255) -- Blue for the return
local endColor = Vector(0,0,0) -- Back when returning to the caster to end
local draw_duration = 3
-- Find one target point at random which will be used for the first acquisition.
local point = caster:GetAbsOrigin() + RandomVector(RandomInt(radius/2, radius))
point.z = GetGroundHeight(point,nil)
-- This is set to repeat on each frame
unit:OnPhysicsFrame(function(unit)
-- Move the unit orientation to adjust the particle
unit:SetForwardVector( ( unit:GetPhysicsVelocity() ):Normalized() )
-- Current positions
local source = caster:GetAbsOrigin()
local current_position = unit:GetAbsOrigin()
-- Print the path on Debug mode
if Debug then DebugDrawCircle(current_position, pathColor, 0, 2, true, draw_duration) end
local enemies = nil
-- Use this if skipping frames is needed (--if frameCount == 0 then..)
frameCount = (frameCount + 1) % 3
-- Movement and Collision detection are state independent
-- MOVEMENT
-- Get the direction
local diff = point - unit:GetAbsOrigin()
diff.z = 0
local direction = diff:Normalized()
-- Calculate the angle difference
local angle_difference = RotationDelta(VectorToAngles(unit:GetPhysicsVelocity():Normalized()), VectorToAngles(direction)).y
-- Set the new velocity
if math.abs(angle_difference) < 5 then
-- CLAMP
local newVel = unit:GetPhysicsVelocity():Length() * direction
unit:SetPhysicsVelocity(newVel)
elseif angle_difference > 0 then
local newVel = RotatePosition(Vector(0,0,0), QAngle(0,10,0), unit:GetPhysicsVelocity())
unit:SetPhysicsVelocity(newVel)
else
local newVel = RotatePosition(Vector(0,0,0), QAngle(0,-10,0), unit:GetPhysicsVelocity())
unit:SetPhysicsVelocity(newVel)
end
-- COLLISION CHECK
local distance = (point - current_position):Length()
local collision = distance < 50
-- MAX DISTANCE CHECK
local distance_to_caster = (source - current_position):Length()
if distance > max_distance then
unit:SetAbsOrigin(source)
unit.state = "acquiring"
end
-- STATE DEPENDENT LOGIC
-- Damage, Healing and Targeting are state dependent.
-- Update the point in all frames
-- Acquiring...
-- Acquiring -> Target Acquired (enemy or idle point)
-- Target Acquired... if collision -> Acquiring or Return
-- Return... if collision -> Acquiring
-- Acquiring finds new targets and changes state to target_acquired with a current_target if it finds enemies or nil and a random point if there are no enemies
if unit.state == "acquiring" then
-- This is to prevent attacking the same target very fast
local time_between_last_attack = GameRules:GetGameTime() - unit.last_attack_time
--print("Time Between Last Attack: "..time_between_last_attack)
-- If enough time has passed since the last attack, attempt to acquire an enemy
if time_between_last_attack >= min_time_between_attacks then
-- If the unit doesn't have a target locked, find enemies near the caster
enemies = FindUnitsInRadius(caster:GetTeamNumber(), source, nil, radius, DOTA_UNIT_TARGET_TEAM_ENEMY,
abilityTargetType, DOTA_UNIT_TARGET_FLAG_NONE, FIND_ANY_ORDER, false)
-- Check the possible enemies
-- Focus the last attacked target if there's any
local last_targeted = ability.last_targeted
local target_enemy = nil
for _,enemy in pairs(enemies) do
-- If the caster has a last_targeted and this is in range of the ghost acquisition, set to attack it
if last_targeted and enemy == last_targeted then
target_enemy = enemy
end
end
-- Else if we don't have a target_enemy from the last_targeted, get one at random
if not target_enemy then
target_enemy = enemies[RandomInt(1, #enemies)]
end
-- Keep track of it, set the state to target_acquired
if target_enemy then
unit.state = "target_acquired"
unit.current_target = target_enemy
point = unit.current_target:GetAbsOrigin()
print("Acquiring -> Enemy Target acquired: "..unit.current_target:GetUnitName())
-- If no enemies, set the unit to collide with a random idle point.
else
unit.state = "target_acquired"
unit.current_target = nil
unit.idling = true
point = source + RandomVector(RandomInt(radius/2, radius))
point.z = GetGroundHeight(point,nil)
--print("Acquiring -> Random Point Target acquired")
if Debug then DebugDrawCircle(point, idleColor, 100, 25, true, draw_duration) end
end
-- not enough time since the last attack, get a random point
else
unit.state = "target_acquired"
unit.current_target = nil
unit.idling = true
point = source + RandomVector(RandomInt(radius/2, radius))
point.z = GetGroundHeight(point,nil)
print("Waiting for attack time. Acquiring -> Random Point Target acquired")
if Debug then DebugDrawCircle(point, idleColor, 100, 25, true, draw_duration) end
end
-- If the state was to follow a target enemy, it means the unit can perform an attack.
elseif unit.state == "target_acquired" then
-- Update the point of the target's current position
if unit.current_target then
point = unit.current_target:GetAbsOrigin()
if Debug then DebugDrawCircle(point, targetColor, 100, 25, true, draw_duration) end
end
-- Give up on the target if the distance goes over the give_up_distance
if distance_to_caster > give_up_distance then
unit.state = "acquiring"
--print("Gave up on the target, acquiring a new target.")
end
-- Do physical damage here, and increase hit counter.
if collision then
-- If the target was an enemy and not a point, the unit collided with it
if unit.current_target ~= nil then
-- Damage, units will still try to collide with attack immune targets but the damage wont be applied
if not unit.current_target:IsAttackImmune() then
local damage_table = {}
local spirit_damage = RandomInt(min_damage,max_damage)
damage_table.victim = unit.current_target
damage_table.attacker = caster
damage_table.damage_type = abilityDamageType
damage_table.damage = spirit_damage
ApplyDamage(damage_table)
-- Calculate how much physical damage was dealt
local targetArmor = unit.current_target:GetPhysicalArmorValue()
local damageReduction = ((0.06 * targetArmor) / (1 + 0.06 * targetArmor))
local damagePostReduction = spirit_damage * (1 - damageReduction)
unit.damage_done = unit.damage_done + damagePostReduction
-- Damage particle, different for buildings
if unit.current_target.InvulCount == 0 then
local particle = ParticleManager:CreateParticle(particleDamageBuilding, PATTACH_ABSORIGIN, unit.current_target)
ParticleManager:SetParticleControl(particle, 0, unit.current_target:GetAbsOrigin())
ParticleManager:SetParticleControlEnt(particle, 1, unit.current_target, PATTACH_POINT_FOLLOW, "attach_hitloc", unit.current_target:GetAbsOrigin(), true)
elseif unit.damage_done > 0 then
local particle = ParticleManager:CreateParticle(particleDamage, PATTACH_ABSORIGIN, unit.current_target)
ParticleManager:SetParticleControl(particle, 0, unit.current_target:GetAbsOrigin())
ParticleManager:SetParticleControlEnt(particle, 1, unit.current_target, PATTACH_POINT_FOLLOW, "attach_hitloc", unit.current_target:GetAbsOrigin(), true)
end
-- Increase the numberOfHits for this unit
unit.numberOfHits = unit.numberOfHits + 1
-- Fire Sound on the target unit
unit.current_target:EmitSound("Hero_DeathProphet.Exorcism.Damage")
-- Set to return
unit.state = "returning"
point = source
--print("Returning to caster after dealing ",unit.damage_done)
-- Update the attack time of the unit.
unit.last_attack_time = GameRules:GetGameTime()
--unit.enemy_collision = true
end
-- In other case, its a point, reacquire target or return to the caster (50/50)
else
if RollPercentage(50) then
unit.state = "acquiring"
--print("Attempting to acquire a new target")
else
unit.state = "returning"
point = source
--print("Returning to caster after idling")
end
end
end
-- If it was a collision on a return (meaning it reached the caster), change to acquiring so it finds a new target
elseif unit.state == "returning" then
-- Update the point to the caster's current position
point = source
if Debug then DebugDrawCircle(point, returnColor, 100, 25, true, draw_duration) end
if collision then
unit.state = "acquiring"
end
-- if set the state to end, the point is also the caster position, but the units will be removed on collision
elseif unit.state == "end" then
point = source
if Debug then DebugDrawCircle(point, endColor, 100, 25, true, 2) end
-- Last collision ends the unit
if collision then
-- Heal is calculated as: a percentage of the units average attack damage multiplied by the amount of attacks the spirit did.
local heal_done = unit.numberOfHits * average_damage* heal_percent
caster:Heal(heal_done, ability)
caster:EmitSound("Hero_DeathProphet.Exorcism.Heal")
--print("Healed ",heal_done)
unit:SetPhysicsVelocity(Vector(0,0,0))
unit:OnPhysicsFrame(nil)
unit:ForceKill(false)
end
end
end)
end
-- Change the state to end when the modifier is removed
function ExorcismEnd( event )
local caster = event.caster
local ability = event.ability
local targets = ability.spirits
print("Exorcism End")
caster:StopSound("Hero_DeathProphet.Exorcism")
for _,unit in pairs(targets) do
if unit and IsValidEntity(unit) then
unit.state = "end"
end
end
-- Reset the last_targeted
ability.last_targeted = nil
end
-- Updates the last_targeted enemy, to focus the ghosts on it.
function ExorcismAttack( event )
local ability = event.ability
local target = event.target
ability.last_targeted = target
--print("LAST TARGET: "..target:GetUnitName())
end
-- Kill all units when the owner dies or the spell is cast while the first one is still going
function ExorcismDeath( event )
local caster = event.caster
local ability = event.ability
local targets = ability.spirits or {}
print("Exorcism Death")
caster:StopSound("Hero_DeathProphet.Exorcism")
for _,unit in pairs(targets) do
if unit and IsValidEntity(unit) then
unit:SetPhysicsVelocity(Vector(0,0,0))
unit:OnPhysicsFrame(nil)
-- Kill
unit:ForceKill(false)
end
end
end
| 0 | 0.958812 | 1 | 0.958812 | game-dev | MEDIA | 0.997563 | game-dev | 0.985143 | 1 | 0.985143 |
Bunny83/SimpleJSON | 44,020 | SimpleJSON.cs | /* * * * *
* A simple JSON Parser / builder
* ------------------------------
*
* It mainly has been written as a simple JSON parser. It can build a JSON string
* from the node-tree, or generate a node tree from any valid JSON string.
*
* Written by Bunny83
* 2012-06-09
*
* Changelog now external. See Changelog.txt
*
* The MIT License (MIT)
*
* Copyright (c) 2012-2022 Markus Göbel (Bunny83)
*
* 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;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
namespace SimpleJSON
{
public enum JSONNodeType
{
Array = 1,
Object = 2,
String = 3,
Number = 4,
NullValue = 5,
Boolean = 6,
None = 7,
Custom = 0xFF,
}
public enum JSONTextMode
{
Compact,
Indent
}
public abstract partial class JSONNode
{
#region Enumerators
public struct Enumerator
{
private enum Type { None, Array, Object }
private Type type;
private Dictionary<string, JSONNode>.Enumerator m_Object;
private List<JSONNode>.Enumerator m_Array;
public bool IsValid { get { return type != Type.None; } }
public Enumerator(List<JSONNode>.Enumerator aArrayEnum)
{
type = Type.Array;
m_Object = default(Dictionary<string, JSONNode>.Enumerator);
m_Array = aArrayEnum;
}
public Enumerator(Dictionary<string, JSONNode>.Enumerator aDictEnum)
{
type = Type.Object;
m_Object = aDictEnum;
m_Array = default(List<JSONNode>.Enumerator);
}
public KeyValuePair<string, JSONNode> Current
{
get
{
if (type == Type.Array)
return new KeyValuePair<string, JSONNode>(string.Empty, m_Array.Current);
else if (type == Type.Object)
return m_Object.Current;
return new KeyValuePair<string, JSONNode>(string.Empty, null);
}
}
public bool MoveNext()
{
if (type == Type.Array)
return m_Array.MoveNext();
else if (type == Type.Object)
return m_Object.MoveNext();
return false;
}
}
public struct ValueEnumerator
{
private Enumerator m_Enumerator;
public ValueEnumerator(List<JSONNode>.Enumerator aArrayEnum) : this(new Enumerator(aArrayEnum)) { }
public ValueEnumerator(Dictionary<string, JSONNode>.Enumerator aDictEnum) : this(new Enumerator(aDictEnum)) { }
public ValueEnumerator(Enumerator aEnumerator) { m_Enumerator = aEnumerator; }
public JSONNode Current { get { return m_Enumerator.Current.Value; } }
public bool MoveNext() { return m_Enumerator.MoveNext(); }
public ValueEnumerator GetEnumerator() { return this; }
}
public struct KeyEnumerator
{
private Enumerator m_Enumerator;
public KeyEnumerator(List<JSONNode>.Enumerator aArrayEnum) : this(new Enumerator(aArrayEnum)) { }
public KeyEnumerator(Dictionary<string, JSONNode>.Enumerator aDictEnum) : this(new Enumerator(aDictEnum)) { }
public KeyEnumerator(Enumerator aEnumerator) { m_Enumerator = aEnumerator; }
public string Current { get { return m_Enumerator.Current.Key; } }
public bool MoveNext() { return m_Enumerator.MoveNext(); }
public KeyEnumerator GetEnumerator() { return this; }
}
public class LinqEnumerator : IEnumerator<KeyValuePair<string, JSONNode>>, IEnumerable<KeyValuePair<string, JSONNode>>
{
private JSONNode m_Node;
private Enumerator m_Enumerator;
internal LinqEnumerator(JSONNode aNode)
{
m_Node = aNode;
if (m_Node != null)
m_Enumerator = m_Node.GetEnumerator();
}
public KeyValuePair<string, JSONNode> Current { get { return m_Enumerator.Current; } }
object IEnumerator.Current { get { return m_Enumerator.Current; } }
public bool MoveNext() { return m_Enumerator.MoveNext(); }
public void Dispose()
{
m_Node = null;
m_Enumerator = new Enumerator();
}
public IEnumerator<KeyValuePair<string, JSONNode>> GetEnumerator()
{
return new LinqEnumerator(m_Node);
}
public void Reset()
{
if (m_Node != null)
m_Enumerator = m_Node.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return new LinqEnumerator(m_Node);
}
}
#endregion Enumerators
#region common interface
public static bool forceASCII = false; // Use Unicode by default
public static bool longAsString = false; // lazy creator creates a JSONString instead of JSONNumber
public static bool allowLineComments = true; // allow "//"-style comments at the end of a line
public abstract JSONNodeType Tag { get; }
public virtual JSONNode this[int aIndex] { get { return null; } set { } }
public virtual JSONNode this[string aKey] { get { return null; } set { } }
public virtual string Value { get { return ""; } set { } }
public virtual int Count { get { return 0; } }
public virtual bool IsNumber { get { return false; } }
public virtual bool IsString { get { return false; } }
public virtual bool IsBoolean { get { return false; } }
public virtual bool IsNull { get { return false; } }
public virtual bool IsArray { get { return false; } }
public virtual bool IsObject { get { return false; } }
public virtual bool Inline { get { return false; } set { } }
public virtual void Add(string aKey, JSONNode aItem)
{
}
public virtual void Add(JSONNode aItem)
{
Add("", aItem);
}
public virtual JSONNode Remove(string aKey)
{
return null;
}
public virtual JSONNode Remove(int aIndex)
{
return null;
}
public virtual JSONNode Remove(JSONNode aNode)
{
return aNode;
}
public virtual void Clear() { }
public virtual JSONNode Clone()
{
return null;
}
public virtual IEnumerable<JSONNode> Children
{
get
{
yield break;
}
}
public IEnumerable<JSONNode> DeepChildren
{
get
{
foreach (var C in Children)
foreach (var D in C.DeepChildren)
yield return D;
}
}
public virtual bool HasKey(string aKey)
{
return false;
}
public virtual JSONNode GetValueOrDefault(string aKey, JSONNode aDefault)
{
return aDefault;
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
WriteToStringBuilder(sb, 0, 0, JSONTextMode.Compact);
return sb.ToString();
}
public virtual string ToString(int aIndent)
{
StringBuilder sb = new StringBuilder();
WriteToStringBuilder(sb, 0, aIndent, JSONTextMode.Indent);
return sb.ToString();
}
internal abstract void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JSONTextMode aMode);
public abstract Enumerator GetEnumerator();
public IEnumerable<KeyValuePair<string, JSONNode>> Linq { get { return new LinqEnumerator(this); } }
public KeyEnumerator Keys { get { return new KeyEnumerator(GetEnumerator()); } }
public ValueEnumerator Values { get { return new ValueEnumerator(GetEnumerator()); } }
#endregion common interface
#region typecasting properties
public virtual double AsDouble
{
get
{
double v = 0.0;
if (double.TryParse(Value, NumberStyles.Float, CultureInfo.InvariantCulture, out v))
return v;
return 0.0;
}
set
{
Value = value.ToString(CultureInfo.InvariantCulture);
}
}
public virtual int AsInt
{
get { return (int)AsDouble; }
set { AsDouble = value; }
}
public virtual float AsFloat
{
get { return (float)AsDouble; }
set { AsDouble = value; }
}
public virtual bool AsBool
{
get
{
bool v = false;
if (bool.TryParse(Value, out v))
return v;
return !string.IsNullOrEmpty(Value);
}
set
{
Value = (value) ? "true" : "false";
}
}
public virtual long AsLong
{
get
{
long val = 0;
if (long.TryParse(Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out val))
return val;
return 0L;
}
set
{
Value = value.ToString(CultureInfo.InvariantCulture);
}
}
public virtual ulong AsULong
{
get
{
ulong val = 0;
if (ulong.TryParse(Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out val))
return val;
return 0;
}
set
{
Value = value.ToString(CultureInfo.InvariantCulture);
}
}
public virtual JSONArray AsArray
{
get
{
return this as JSONArray;
}
}
public virtual JSONObject AsObject
{
get
{
return this as JSONObject;
}
}
#endregion typecasting properties
#region operators
public static implicit operator JSONNode(string s)
{
return (s == null) ? (JSONNode)JSONNull.CreateOrGet() : new JSONString(s);
}
public static implicit operator string(JSONNode d)
{
return (d == null) ? null : d.Value;
}
public static implicit operator JSONNode(double n)
{
return new JSONNumber(n);
}
public static implicit operator double(JSONNode d)
{
return (d == null) ? 0 : d.AsDouble;
}
public static implicit operator JSONNode(float n)
{
return new JSONNumber(n);
}
public static implicit operator float(JSONNode d)
{
return (d == null) ? 0 : d.AsFloat;
}
public static implicit operator JSONNode(int n)
{
return new JSONNumber(n);
}
public static implicit operator int(JSONNode d)
{
return (d == null) ? 0 : d.AsInt;
}
public static implicit operator JSONNode(long n)
{
if (longAsString)
return new JSONString(n.ToString(CultureInfo.InvariantCulture));
return new JSONNumber(n);
}
public static implicit operator long(JSONNode d)
{
return (d == null) ? 0L : d.AsLong;
}
public static implicit operator JSONNode(ulong n)
{
if (longAsString)
return new JSONString(n.ToString(CultureInfo.InvariantCulture));
return new JSONNumber(n);
}
public static implicit operator ulong(JSONNode d)
{
return (d == null) ? 0 : d.AsULong;
}
public static implicit operator JSONNode(bool b)
{
return new JSONBool(b);
}
public static implicit operator bool(JSONNode d)
{
return (d == null) ? false : d.AsBool;
}
public static implicit operator JSONNode(KeyValuePair<string, JSONNode> aKeyValue)
{
return aKeyValue.Value;
}
public static bool operator ==(JSONNode a, object b)
{
if (ReferenceEquals(a, b))
return true;
bool aIsNull = a is JSONNull || ReferenceEquals(a, null) || a is JSONLazyCreator;
bool bIsNull = b is JSONNull || ReferenceEquals(b, null) || b is JSONLazyCreator;
if (aIsNull && bIsNull)
return true;
return !aIsNull && a.Equals(b);
}
public static bool operator !=(JSONNode a, object b)
{
return !(a == b);
}
public override bool Equals(object obj)
{
return ReferenceEquals(this, obj);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
#endregion operators
[ThreadStatic]
private static StringBuilder m_EscapeBuilder;
internal static StringBuilder EscapeBuilder
{
get
{
if (m_EscapeBuilder == null)
m_EscapeBuilder = new StringBuilder();
return m_EscapeBuilder;
}
}
internal static string Escape(string aText)
{
var sb = EscapeBuilder;
sb.Length = 0;
if (sb.Capacity < aText.Length + aText.Length / 10)
sb.Capacity = aText.Length + aText.Length / 10;
foreach (char c in aText)
{
switch (c)
{
case '\\':
sb.Append("\\\\");
break;
case '\"':
sb.Append("\\\"");
break;
case '\n':
sb.Append("\\n");
break;
case '\r':
sb.Append("\\r");
break;
case '\t':
sb.Append("\\t");
break;
case '\b':
sb.Append("\\b");
break;
case '\f':
sb.Append("\\f");
break;
default:
if (c < ' ' || (forceASCII && c > 127))
{
ushort val = c;
sb.Append("\\u").Append(val.ToString("X4"));
}
else
sb.Append(c);
break;
}
}
string result = sb.ToString();
sb.Length = 0;
return result;
}
private static JSONNode ParseElement(string token, bool quoted)
{
if (quoted)
return token;
if (token.Length <= 5)
{
string tmp = token.ToLower();
if (tmp == "false" || tmp == "true")
return tmp == "true";
if (tmp == "null")
return JSONNull.CreateOrGet();
}
double val;
if (double.TryParse(token, NumberStyles.Float, CultureInfo.InvariantCulture, out val))
return val;
else
return token;
}
public static JSONNode Parse(string aJSON)
{
Stack<JSONNode> stack = new Stack<JSONNode>();
JSONNode ctx = null;
int i = 0;
StringBuilder Token = new StringBuilder();
string TokenName = "";
bool QuoteMode = false;
bool TokenIsQuoted = false;
bool HasNewlineChar = false;
while (i < aJSON.Length)
{
switch (aJSON[i])
{
case '{':
if (QuoteMode)
{
Token.Append(aJSON[i]);
break;
}
stack.Push(new JSONObject());
if (ctx != null)
{
ctx.Add(TokenName, stack.Peek());
}
TokenName = "";
Token.Length = 0;
ctx = stack.Peek();
HasNewlineChar = false;
break;
case '[':
if (QuoteMode)
{
Token.Append(aJSON[i]);
break;
}
stack.Push(new JSONArray());
if (ctx != null)
{
ctx.Add(TokenName, stack.Peek());
}
TokenName = "";
Token.Length = 0;
ctx = stack.Peek();
HasNewlineChar = false;
break;
case '}':
case ']':
if (QuoteMode)
{
Token.Append(aJSON[i]);
break;
}
if (stack.Count == 0)
throw new Exception("JSON Parse: Too many closing brackets");
stack.Pop();
if (Token.Length > 0 || TokenIsQuoted)
ctx.Add(TokenName, ParseElement(Token.ToString(), TokenIsQuoted));
if (ctx != null)
ctx.Inline = !HasNewlineChar;
TokenIsQuoted = false;
TokenName = "";
Token.Length = 0;
if (stack.Count > 0)
ctx = stack.Peek();
break;
case ':':
if (QuoteMode)
{
Token.Append(aJSON[i]);
break;
}
TokenName = Token.ToString();
Token.Length = 0;
TokenIsQuoted = false;
break;
case '"':
QuoteMode ^= true;
TokenIsQuoted |= QuoteMode;
break;
case ',':
if (QuoteMode)
{
Token.Append(aJSON[i]);
break;
}
if (Token.Length > 0 || TokenIsQuoted)
ctx.Add(TokenName, ParseElement(Token.ToString(), TokenIsQuoted));
TokenIsQuoted = false;
TokenName = "";
Token.Length = 0;
TokenIsQuoted = false;
break;
case '\r':
case '\n':
HasNewlineChar = true;
break;
case ' ':
case '\t':
if (QuoteMode)
Token.Append(aJSON[i]);
break;
case '\\':
++i;
if (QuoteMode)
{
char C = aJSON[i];
switch (C)
{
case 't':
Token.Append('\t');
break;
case 'r':
Token.Append('\r');
break;
case 'n':
Token.Append('\n');
break;
case 'b':
Token.Append('\b');
break;
case 'f':
Token.Append('\f');
break;
case 'u':
{
string s = aJSON.Substring(i + 1, 4);
Token.Append((char)int.Parse(
s,
System.Globalization.NumberStyles.AllowHexSpecifier));
i += 4;
break;
}
default:
Token.Append(C);
break;
}
}
break;
case '/':
if (allowLineComments && !QuoteMode && i + 1 < aJSON.Length && aJSON[i + 1] == '/')
{
while (++i < aJSON.Length && aJSON[i] != '\n' && aJSON[i] != '\r') ;
break;
}
Token.Append(aJSON[i]);
break;
case '\uFEFF': // remove / ignore BOM (Byte Order Mark)
break;
default:
Token.Append(aJSON[i]);
break;
}
++i;
}
if (QuoteMode)
{
throw new Exception("JSON Parse: Quotation marks seems to be messed up.");
}
if (ctx == null)
return ParseElement(Token.ToString(), TokenIsQuoted);
return ctx;
}
}
// End of JSONNode
public partial class JSONArray : JSONNode
{
private List<JSONNode> m_List = new List<JSONNode>();
private bool inline = false;
public override bool Inline
{
get { return inline; }
set { inline = value; }
}
public override JSONNodeType Tag { get { return JSONNodeType.Array; } }
public override bool IsArray { get { return true; } }
public override Enumerator GetEnumerator() { return new Enumerator(m_List.GetEnumerator()); }
public override JSONNode this[int aIndex]
{
get
{
if (aIndex < 0 || aIndex >= m_List.Count)
return new JSONLazyCreator(this);
return m_List[aIndex];
}
set
{
if (value == null)
value = JSONNull.CreateOrGet();
if (aIndex < 0 || aIndex >= m_List.Count)
m_List.Add(value);
else
m_List[aIndex] = value;
}
}
public override JSONNode this[string aKey]
{
get { return new JSONLazyCreator(this); }
set
{
if (value == null)
value = JSONNull.CreateOrGet();
m_List.Add(value);
}
}
public override int Count
{
get { return m_List.Count; }
}
public override void Add(string aKey, JSONNode aItem)
{
if (aItem == null)
aItem = JSONNull.CreateOrGet();
m_List.Add(aItem);
}
public override JSONNode Remove(int aIndex)
{
if (aIndex < 0 || aIndex >= m_List.Count)
return null;
JSONNode tmp = m_List[aIndex];
m_List.RemoveAt(aIndex);
return tmp;
}
public override JSONNode Remove(JSONNode aNode)
{
m_List.Remove(aNode);
return aNode;
}
public override void Clear()
{
m_List.Clear();
}
public override JSONNode Clone()
{
var node = new JSONArray();
node.m_List.Capacity = m_List.Capacity;
foreach (var n in m_List)
{
if (n != null)
node.Add(n.Clone());
else
node.Add(null);
}
return node;
}
public override IEnumerable<JSONNode> Children
{
get
{
foreach (JSONNode N in m_List)
yield return N;
}
}
internal override void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JSONTextMode aMode)
{
aSB.Append('[');
int count = m_List.Count;
if (inline)
aMode = JSONTextMode.Compact;
for (int i = 0; i < count; i++)
{
if (i > 0)
aSB.Append(',');
if (aMode == JSONTextMode.Indent)
aSB.AppendLine();
if (aMode == JSONTextMode.Indent)
aSB.Append(' ', aIndent + aIndentInc);
m_List[i].WriteToStringBuilder(aSB, aIndent + aIndentInc, aIndentInc, aMode);
}
if (aMode == JSONTextMode.Indent)
aSB.AppendLine().Append(' ', aIndent);
aSB.Append(']');
}
}
// End of JSONArray
public partial class JSONObject : JSONNode
{
private Dictionary<string, JSONNode> m_Dict = new Dictionary<string, JSONNode>();
private bool inline = false;
public override bool Inline
{
get { return inline; }
set { inline = value; }
}
public override JSONNodeType Tag { get { return JSONNodeType.Object; } }
public override bool IsObject { get { return true; } }
public override Enumerator GetEnumerator() { return new Enumerator(m_Dict.GetEnumerator()); }
public override JSONNode this[string aKey]
{
get
{
if (m_Dict.TryGetValue(aKey, out JSONNode outJsonNode))
return outJsonNode;
else
return new JSONLazyCreator(this, aKey);
}
set
{
if (value == null)
value = JSONNull.CreateOrGet();
if (m_Dict.ContainsKey(aKey))
m_Dict[aKey] = value;
else
m_Dict.Add(aKey, value);
}
}
public override JSONNode this[int aIndex]
{
get
{
if (aIndex < 0 || aIndex >= m_Dict.Count)
return null;
return m_Dict.ElementAt(aIndex).Value;
}
set
{
if (value == null)
value = JSONNull.CreateOrGet();
if (aIndex < 0 || aIndex >= m_Dict.Count)
return;
string key = m_Dict.ElementAt(aIndex).Key;
m_Dict[key] = value;
}
}
public override int Count
{
get { return m_Dict.Count; }
}
public override void Add(string aKey, JSONNode aItem)
{
if (aItem == null)
aItem = JSONNull.CreateOrGet();
if (aKey != null)
{
if (m_Dict.ContainsKey(aKey))
m_Dict[aKey] = aItem;
else
m_Dict.Add(aKey, aItem);
}
else
m_Dict.Add(Guid.NewGuid().ToString(), aItem);
}
public override JSONNode Remove(string aKey)
{
if (!m_Dict.ContainsKey(aKey))
return null;
JSONNode tmp = m_Dict[aKey];
m_Dict.Remove(aKey);
return tmp;
}
public override JSONNode Remove(int aIndex)
{
if (aIndex < 0 || aIndex >= m_Dict.Count)
return null;
var item = m_Dict.ElementAt(aIndex);
m_Dict.Remove(item.Key);
return item.Value;
}
public override JSONNode Remove(JSONNode aNode)
{
try
{
var item = m_Dict.Where(k => k.Value == aNode).First();
m_Dict.Remove(item.Key);
return aNode;
}
catch
{
return null;
}
}
public override void Clear()
{
m_Dict.Clear();
}
public override JSONNode Clone()
{
var node = new JSONObject();
foreach (var n in m_Dict)
{
node.Add(n.Key, n.Value.Clone());
}
return node;
}
public override bool HasKey(string aKey)
{
return m_Dict.ContainsKey(aKey);
}
public override JSONNode GetValueOrDefault(string aKey, JSONNode aDefault)
{
JSONNode res;
if (m_Dict.TryGetValue(aKey, out res))
return res;
return aDefault;
}
public override IEnumerable<JSONNode> Children
{
get
{
foreach (KeyValuePair<string, JSONNode> N in m_Dict)
yield return N.Value;
}
}
internal override void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JSONTextMode aMode)
{
aSB.Append('{');
bool first = true;
if (inline)
aMode = JSONTextMode.Compact;
foreach (var k in m_Dict)
{
if (!first)
aSB.Append(',');
first = false;
if (aMode == JSONTextMode.Indent)
aSB.AppendLine();
if (aMode == JSONTextMode.Indent)
aSB.Append(' ', aIndent + aIndentInc);
aSB.Append('\"').Append(Escape(k.Key)).Append('\"');
if (aMode == JSONTextMode.Compact)
aSB.Append(':');
else
aSB.Append(" : ");
k.Value.WriteToStringBuilder(aSB, aIndent + aIndentInc, aIndentInc, aMode);
}
if (aMode == JSONTextMode.Indent)
aSB.AppendLine().Append(' ', aIndent);
aSB.Append('}');
}
}
// End of JSONObject
public partial class JSONString : JSONNode
{
private string m_Data;
public override JSONNodeType Tag { get { return JSONNodeType.String; } }
public override bool IsString { get { return true; } }
public override Enumerator GetEnumerator() { return new Enumerator(); }
public override string Value
{
get { return m_Data; }
set
{
m_Data = value;
}
}
public JSONString(string aData)
{
m_Data = aData;
}
public override JSONNode Clone()
{
return new JSONString(m_Data);
}
internal override void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JSONTextMode aMode)
{
aSB.Append('\"').Append(Escape(m_Data)).Append('\"');
}
public override bool Equals(object obj)
{
if (base.Equals(obj))
return true;
string s = obj as string;
if (s != null)
return m_Data == s;
JSONString s2 = obj as JSONString;
if (s2 != null)
return m_Data == s2.m_Data;
return false;
}
public override int GetHashCode()
{
return m_Data.GetHashCode();
}
public override void Clear()
{
m_Data = "";
}
}
// End of JSONString
public partial class JSONNumber : JSONNode
{
private double m_Data;
public override JSONNodeType Tag { get { return JSONNodeType.Number; } }
public override bool IsNumber { get { return true; } }
public override Enumerator GetEnumerator() { return new Enumerator(); }
public override string Value
{
get { return m_Data.ToString(CultureInfo.InvariantCulture); }
set
{
double v;
if (double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out v))
m_Data = v;
}
}
public override double AsDouble
{
get { return m_Data; }
set { m_Data = value; }
}
public override long AsLong
{
get { return (long)m_Data; }
set { m_Data = value; }
}
public override ulong AsULong
{
get { return (ulong)m_Data; }
set { m_Data = value; }
}
public JSONNumber(double aData)
{
m_Data = aData;
}
public JSONNumber(string aData)
{
Value = aData;
}
public override JSONNode Clone()
{
return new JSONNumber(m_Data);
}
internal override void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JSONTextMode aMode)
{
aSB.Append(Value.ToString(CultureInfo.InvariantCulture));
}
private static bool IsNumeric(object value)
{
return value is int || value is uint
|| value is float || value is double
|| value is decimal
|| value is long || value is ulong
|| value is short || value is ushort
|| value is sbyte || value is byte;
}
public override bool Equals(object obj)
{
if (obj == null)
return false;
if (base.Equals(obj))
return true;
JSONNumber s2 = obj as JSONNumber;
if (s2 != null)
return m_Data == s2.m_Data;
if (IsNumeric(obj))
return Convert.ToDouble(obj) == m_Data;
return false;
}
public override int GetHashCode()
{
return m_Data.GetHashCode();
}
public override void Clear()
{
m_Data = 0;
}
}
// End of JSONNumber
public partial class JSONBool : JSONNode
{
private bool m_Data;
public override JSONNodeType Tag { get { return JSONNodeType.Boolean; } }
public override bool IsBoolean { get { return true; } }
public override Enumerator GetEnumerator() { return new Enumerator(); }
public override string Value
{
get { return m_Data.ToString(); }
set
{
bool v;
if (bool.TryParse(value, out v))
m_Data = v;
}
}
public override bool AsBool
{
get { return m_Data; }
set { m_Data = value; }
}
public JSONBool(bool aData)
{
m_Data = aData;
}
public JSONBool(string aData)
{
Value = aData;
}
public override JSONNode Clone()
{
return new JSONBool(m_Data);
}
internal override void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JSONTextMode aMode)
{
aSB.Append((m_Data) ? "true" : "false");
}
public override bool Equals(object obj)
{
if (obj == null)
return false;
if (obj is bool)
return m_Data == (bool)obj;
return false;
}
public override int GetHashCode()
{
return m_Data.GetHashCode();
}
public override void Clear()
{
m_Data = false;
}
}
// End of JSONBool
public partial class JSONNull : JSONNode
{
static JSONNull m_StaticInstance = new JSONNull();
public static bool reuseSameInstance = true;
public static JSONNull CreateOrGet()
{
if (reuseSameInstance)
return m_StaticInstance;
return new JSONNull();
}
private JSONNull() { }
public override JSONNodeType Tag { get { return JSONNodeType.NullValue; } }
public override bool IsNull { get { return true; } }
public override Enumerator GetEnumerator() { return new Enumerator(); }
public override string Value
{
get { return "null"; }
set { }
}
public override bool AsBool
{
get { return false; }
set { }
}
public override JSONNode Clone()
{
return CreateOrGet();
}
public override bool Equals(object obj)
{
if (object.ReferenceEquals(this, obj))
return true;
return (obj is JSONNull);
}
public override int GetHashCode()
{
return 0;
}
internal override void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JSONTextMode aMode)
{
aSB.Append("null");
}
}
// End of JSONNull
internal partial class JSONLazyCreator : JSONNode
{
private JSONNode m_Node = null;
private string m_Key = null;
public override JSONNodeType Tag { get { return JSONNodeType.None; } }
public override Enumerator GetEnumerator() { return new Enumerator(); }
public JSONLazyCreator(JSONNode aNode)
{
m_Node = aNode;
m_Key = null;
}
public JSONLazyCreator(JSONNode aNode, string aKey)
{
m_Node = aNode;
m_Key = aKey;
}
private T Set<T>(T aVal) where T : JSONNode
{
if (m_Key == null)
m_Node.Add(aVal);
else
m_Node.Add(m_Key, aVal);
m_Node = null; // Be GC friendly.
return aVal;
}
public override JSONNode this[int aIndex]
{
get { return new JSONLazyCreator(this); }
set { Set(new JSONArray()).Add(value); }
}
public override JSONNode this[string aKey]
{
get { return new JSONLazyCreator(this, aKey); }
set { Set(new JSONObject()).Add(aKey, value); }
}
public override void Add(JSONNode aItem)
{
Set(new JSONArray()).Add(aItem);
}
public override void Add(string aKey, JSONNode aItem)
{
Set(new JSONObject()).Add(aKey, aItem);
}
public static bool operator ==(JSONLazyCreator a, object b)
{
if (b == null)
return true;
return System.Object.ReferenceEquals(a, b);
}
public static bool operator !=(JSONLazyCreator a, object b)
{
return !(a == b);
}
public override bool Equals(object obj)
{
if (obj == null)
return true;
return System.Object.ReferenceEquals(this, obj);
}
public override int GetHashCode()
{
return 0;
}
public override int AsInt
{
get { Set(new JSONNumber(0)); return 0; }
set { Set(new JSONNumber(value)); }
}
public override float AsFloat
{
get { Set(new JSONNumber(0.0f)); return 0.0f; }
set { Set(new JSONNumber(value)); }
}
public override double AsDouble
{
get { Set(new JSONNumber(0.0)); return 0.0; }
set { Set(new JSONNumber(value)); }
}
public override long AsLong
{
get
{
if (longAsString)
Set(new JSONString("0"));
else
Set(new JSONNumber(0.0));
return 0L;
}
set
{
if (longAsString)
Set(new JSONString(value.ToString(CultureInfo.InvariantCulture)));
else
Set(new JSONNumber(value));
}
}
public override ulong AsULong
{
get
{
if (longAsString)
Set(new JSONString("0"));
else
Set(new JSONNumber(0.0));
return 0L;
}
set
{
if (longAsString)
Set(new JSONString(value.ToString(CultureInfo.InvariantCulture)));
else
Set(new JSONNumber(value));
}
}
public override bool AsBool
{
get { Set(new JSONBool(false)); return false; }
set { Set(new JSONBool(value)); }
}
public override JSONArray AsArray
{
get { return Set(new JSONArray()); }
}
public override JSONObject AsObject
{
get { return Set(new JSONObject()); }
}
internal override void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JSONTextMode aMode)
{
aSB.Append("null");
}
}
// End of JSONLazyCreator
public static class JSON
{
public static JSONNode Parse(string aJSON)
{
return JSONNode.Parse(aJSON);
}
}
}
| 0 | 0.860508 | 1 | 0.860508 | game-dev | MEDIA | 0.553014 | game-dev | 0.682233 | 1 | 0.682233 |
Kromster80/kam_remake | 5,611 | src/gui/pages_maped/KM_GUIMapEdGoal.pas | unit KM_GUIMapEdGoal;
{$I KaM_Remake.inc}
interface
uses
{$IFDEF MSWindows} Windows, {$ENDIF}
{$IFDEF Unix} LCLType, {$ENDIF}
Classes,
KM_Controls, KM_Defaults, KM_Pics, KM_AIGoals;
type
TKMMapEdGoal = class
private
fOwner: TKMHandIndex;
fIndex: Integer;
procedure Goal_Change(Sender: TObject);
procedure Goal_Close(Sender: TObject);
procedure Goal_Refresh(aGoal: TKMGoal);
function GetVisible: Boolean;
protected
Panel_Goal: TKMPanel;
Image_GoalFlag: TKMImage;
Radio_GoalType: TKMRadioGroup;
Radio_GoalCondition: TKMRadioGroup;
NumEdit_GoalPlayer: TKMNumericEdit;
Button_GoalOk: TKMButton;
Button_GoalCancel: TKMButton;
public
fOnDone: TNotifyEvent;
constructor Create(aParent: TKMPanel);
property Visible: Boolean read GetVisible;
function KeyDown(Key: Word; Shift: TShiftState): Boolean;
procedure Show(aPlayer: TKMHandIndex; aIndex: Integer);
end;
implementation
uses
KM_HandsCollection, KM_ResTexts, KM_RenderUI, KM_ResFonts, KM_Hand;
{ TKMGUIMapEdGoal }
constructor TKMMapEdGoal.Create(aParent: TKMPanel);
const
SIZE_X = 600;
SIZE_Y = 300;
var
Img: TKMImage;
begin
inherited Create;
Panel_Goal := TKMPanel.Create(aParent, 362, 250, SIZE_X, SIZE_Y);
Panel_Goal.AnchorsCenter;
Panel_Goal.Hide;
TKMBevel.Create(Panel_Goal, -1000, -1000, 4000, 4000);
Img := TKMImage.Create(Panel_Goal, -20, -50, SIZE_X+40, SIZE_Y+60, 15, rxGuiMain);
Img.ImageStretch;
TKMBevel.Create(Panel_Goal, 0, 0, SIZE_X, SIZE_Y);
TKMLabel.Create(Panel_Goal, SIZE_X div 2, 10, gResTexts[TX_MAPED_GOALS_TITLE], fnt_Outline, taCenter);
Image_GoalFlag := TKMImage.Create(Panel_Goal, 10, 10, 0, 0, 30, rxGuiMain);
TKMLabel.Create(Panel_Goal, 20, 40, 160, 0, gResTexts[TX_MAPED_GOALS_TYPE], fnt_Metal, taLeft);
Radio_GoalType := TKMRadioGroup.Create(Panel_Goal, 20, 60, 160, 60, fnt_Metal);
Radio_GoalType.Add(gResTexts[TX_MAPED_GOALS_TYPE_NONE], False);
Radio_GoalType.Add(gResTexts[TX_MAPED_GOALS_TYPE_VICTORY]);
Radio_GoalType.Add(gResTexts[TX_MAPED_GOALS_TYPE_SURVIVE]);
Radio_GoalType.OnChange := Goal_Change;
TKMLabel.Create(Panel_Goal, 200, 40, 280, 0, gResTexts[TX_MAPED_GOALS_CONDITION], fnt_Metal, taLeft);
Radio_GoalCondition := TKMRadioGroup.Create(Panel_Goal, 200, 60, 280, 180, fnt_Metal);
Radio_GoalCondition.Add(gResTexts[TX_MAPED_GOALS_CONDITION_NONE], False);
Radio_GoalCondition.Add(gResTexts[TX_MAPED_GOALS_CONDITION_TUTORIAL], False);
Radio_GoalCondition.Add(gResTexts[TX_MAPED_GOALS_CONDITION_TIME], False);
Radio_GoalCondition.Add(gResTexts[TX_MAPED_GOALS_CONDITION_BUILDS]);
Radio_GoalCondition.Add(gResTexts[TX_MAPED_GOALS_CONDITION_TROOPS]);
Radio_GoalCondition.Add(gResTexts[TX_MAPED_GOALS_CONDITION_UNKNOWN], False);
Radio_GoalCondition.Add(gResTexts[TX_MAPED_GOALS_CONDITION_ASSETS]);
Radio_GoalCondition.Add(gResTexts[TX_MAPED_GOALS_CONDITION_SERFS]);
Radio_GoalCondition.Add(gResTexts[TX_MAPED_GOALS_CONDITION_ECONOMY]);
Radio_GoalCondition.OnChange := Goal_Change;
TKMLabel.Create(Panel_Goal, 480, 40, gResTexts[TX_MAPED_GOALS_PLAYER], fnt_Metal, taLeft);
NumEdit_GoalPlayer := TKMNumericEdit.Create(Panel_Goal, 480, 60, 1, MAX_HANDS);
NumEdit_GoalPlayer.OnChange := Goal_Change;
Button_GoalOk := TKMButton.Create(Panel_Goal, SIZE_X-20-320-10, SIZE_Y - 50, 160, 30, gResTexts[TX_MAPED_OK], bsMenu);
Button_GoalOk.OnClick := Goal_Close;
Button_GoalCancel := TKMButton.Create(Panel_Goal, SIZE_X-20-160, SIZE_Y - 50, 160, 30, gResTexts[TX_MAPED_CANCEL], bsMenu);
Button_GoalCancel.OnClick := Goal_Close;
end;
procedure TKMMapEdGoal.Goal_Change(Sender: TObject);
begin
//Settings get saved on close, now we just toggle fields
//because certain combinations can't coexist
NumEdit_GoalPlayer.Enabled := TKMGoalCondition(Radio_GoalCondition.ItemIndex) <> gc_Time;
end;
function TKMMapEdGoal.GetVisible: Boolean;
begin
Result := Panel_Goal.Visible;
end;
procedure TKMMapEdGoal.Goal_Close(Sender: TObject);
var
G: TKMGoal;
begin
if Sender = Button_GoalOk then
begin
//Copy Goal info from controls to Goals
FillChar(G, SizeOf(G), #0); //Make sure unused fields like Message are zero, not random data
G.GoalType := TKMGoalType(Radio_GoalType.ItemIndex);
G.GoalCondition := TKMGoalCondition(Radio_GoalCondition.ItemIndex);
if G.GoalType = glt_Survive then
G.GoalStatus := gs_True
else
G.GoalStatus := gs_False;
G.HandIndex := NumEdit_GoalPlayer.Value - 1;
gHands[fOwner].AI.Goals[fIndex] := G;
end;
Panel_Goal.Hide;
fOnDone(Self);
end;
procedure TKMMapEdGoal.Goal_Refresh(aGoal: TKMGoal);
begin
Image_GoalFlag.FlagColor := gHands[fOwner].FlagColor;
Radio_GoalType.ItemIndex := Byte(aGoal.GoalType);
Radio_GoalCondition.ItemIndex := Byte(aGoal.GoalCondition);
NumEdit_GoalPlayer.Value := aGoal.HandIndex + 1;
//Certain values disable certain controls
Goal_Change(nil);
end;
function TKMMapEdGoal.KeyDown(Key: Word; Shift: TShiftState): Boolean;
begin
Result := False;
case Key of
VK_ESCAPE: if Button_GoalCancel.IsClickable then
begin
Goal_Close(Button_GoalCancel);
Result := True;
end;
VK_RETURN: if Button_GoalOk.IsClickable then
begin
Goal_Close(Button_GoalOk);
Result := True;
end;
end;
end;
procedure TKMMapEdGoal.Show(aPlayer: TKMHandIndex; aIndex: Integer);
begin
fOwner := aPlayer;
fIndex := aIndex;
Goal_Refresh(gHands[fOwner].AI.Goals[fIndex]);
Panel_Goal.Show;
end;
end.
| 0 | 0.548651 | 1 | 0.548651 | game-dev | MEDIA | 0.924811 | game-dev | 0.91474 | 1 | 0.91474 |
utilForever/RosettaStone | 4,157 | Sources/Rosetta/PlayMode/Tasks/SimpleTasks/CopyTask.cpp | // This code is based on Sabberstone project.
// Copyright (c) 2017-2021 SabberStone Team, darkfriend77 & rnilva
// RosettaStone is hearthstone simulator using C++ with reinforcement learning.
// Copyright (c) 2017-2024 Chris Ohk
#include <Rosetta/PlayMode/Actions/Copy.hpp>
#include <Rosetta/PlayMode/Actions/Generic.hpp>
#include <Rosetta/PlayMode/Cards/Cards.hpp>
#include <Rosetta/PlayMode/Games/Game.hpp>
#include <Rosetta/PlayMode/Models/Enchantment.hpp>
#include <Rosetta/PlayMode/Tasks/SimpleTasks/CopyTask.hpp>
#include <stdexcept>
namespace RosettaStone::PlayMode::SimpleTasks
{
CopyTask::CopyTask(EntityType entityType, ZoneType zoneType, int amount,
bool addToStack, bool toOpponent)
: ITask(entityType),
m_zoneType(zoneType),
m_amount(amount),
m_addToStack(addToStack),
m_toOpponent(toOpponent)
{
// Do nothing
}
TaskStatus CopyTask::Impl(Player* player)
{
Player* owner = m_toOpponent ? player->opponent : player;
const IZone* targetZone = Generic::GetZone(owner, m_zoneType);
if (!targetZone || targetZone->IsFull())
{
return TaskStatus::STOP;
}
std::vector<Playable*> result;
if (m_entityType == EntityType::STACK)
{
if (player->game->taskStack.playables.empty())
{
return TaskStatus::STOP;
}
for (const auto& entity : player->game->taskStack.playables)
{
for (int i = 0; i < m_amount; ++i)
{
Playable* copied = Generic::Copy(owner, entity, m_zoneType);
if (m_addToStack)
{
result.emplace_back(copied);
}
if (targetZone->IsFull())
{
if (m_addToStack)
{
player->game->taskStack.playables = result;
}
return TaskStatus::COMPLETE;
}
}
}
}
else
{
Playable* toBeCopied;
bool deathrattle = false;
switch (m_entityType)
{
case EntityType::SOURCE:
{
toBeCopied = dynamic_cast<Playable*>(m_source);
const auto enchantment = dynamic_cast<Enchantment*>(m_target);
deathrattle =
m_zoneType == ZoneType::PLAY && enchantment &&
!enchantment->card->power.GetDeathrattleTask().empty();
break;
}
case EntityType::TARGET:
{
toBeCopied = m_target;
if (toBeCopied && toBeCopied->zone &&
toBeCopied->zone->GetType() == ZoneType::GRAVEYARD)
{
deathrattle = true;
}
break;
}
case EntityType::STACK_NUM0:
{
toBeCopied =
player->game->entityList[player->game->taskStack.num[0]];
break;
}
default:
throw std::invalid_argument(
"CopyTask::Impl() - Invalid entity type");
}
if (!toBeCopied)
{
return TaskStatus::STOP;
}
for (int i = 0; i < m_amount; ++i)
{
Playable* copied =
Generic::Copy(owner, toBeCopied, m_zoneType, deathrattle);
if (m_addToStack)
{
result.emplace_back(copied);
}
if (targetZone->IsFull())
{
if (m_addToStack)
{
player->game->taskStack.playables = result;
}
return TaskStatus::COMPLETE;
}
}
}
if (m_addToStack)
{
player->game->taskStack.playables = result;
}
return TaskStatus::COMPLETE;
}
std::unique_ptr<ITask> CopyTask::CloneImpl()
{
return std::make_unique<CopyTask>(m_entityType, m_zoneType, m_amount,
m_addToStack, m_toOpponent);
}
} // namespace RosettaStone::PlayMode::SimpleTasks | 0 | 0.933657 | 1 | 0.933657 | game-dev | MEDIA | 0.933593 | game-dev | 0.950732 | 1 | 0.950732 |
fwilliams/surface-reconstruction-benchmark | 9,613 | pbrt/src/core/probes.cpp |
/*
pbrt source code Copyright(c) 1998-2010 Matt Pharr and Greg Humphreys.
This file is part of pbrt.
pbrt 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. Note that the text contents of
the book "Physically Based Rendering" are *not* licensed under the
GNU GPL.
pbrt 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/>.
*/
// core/probes.cpp*
#include "stdafx.h"
#include "probes.h"
#ifdef PBRT_PROBES_COUNTERS
#include "parallel.h"
#include <map>
using std::map;
// Statistics Counters Local Declarations
#ifdef PBRT_HAS_64_BIT_ATOMICS
typedef AtomicInt64 StatsCounterType;
#else
typedef AtomicInt32 StatsCounterType;
#endif
class StatsCounter {
public:
// StatsCounter Public Methods
StatsCounter(const string &category, const string &name);
void operator++() {
AtomicAdd(&num, 1);
}
void operator++(int) {
AtomicAdd(&num, 1);
}
#ifdef PBRT_HAS_64_BIT_ATOMICS
void Max(int64_t newval) {
int64_t oldval;
do {
oldval = num;
newval = max(oldval, newval);
if (newval == oldval) return;
} while(AtomicCompareAndSwap(&num, newval, oldval) != oldval);
}
void Min(int64_t newval) {
int64_t oldval;
do {
oldval = (uint32_t)num;
newval = min(oldval, newval);
if (newval == oldval) return;
} while(AtomicCompareAndSwap(&num, newval, oldval) != oldval);
}
#else
void Max(int32_t newval) {
int32_t oldval;
do {
oldval = num;
newval = max(oldval, newval);
if (newval == oldval) return;
} while(AtomicCompareAndSwap(&num, newval, oldval) != oldval);
}
void Min(int32_t newval) {
int32_t oldval;
do {
oldval = (uint32_t)num;
newval = min(oldval, newval);
if (newval == oldval) return;
} while(AtomicCompareAndSwap(&num, newval, oldval) != oldval);
}
#endif
#ifdef PBRT_HAS_64_BIT_ATOMICS
operator int64_t() volatile { return (int64_t)num; }
#else
operator int32_t() volatile { return (int32_t)num; }
#endif
private:
// StatsCounter Private Data
StatsCounterType num;
};
class StatsRatio {
public:
// StatsRatio Public Methods
StatsRatio(const string &category, const string &name);
void Add(int a, int b) {
AtomicAdd(&na, a);
AtomicAdd(&nb, b);
}
private:
// StatsRatio Private Data
StatsCounterType na, nb;
};
class StatsPercentage {
public:
// StatsPercentage Public Methods
void Add(int a, int b) {
AtomicAdd(&na, a);
AtomicAdd(&nb, b);
}
StatsPercentage(const string &category, const string &name);
private:
// StatsPercentage Private Data
StatsCounterType na, nb;
};
// Statistics Counters Definitions
static void ProbesPrintVal(FILE *f, const StatsCounterType &v);
static void ProbesPrintVal(FILE *f, const StatsCounterType &v1,
const StatsCounterType &v2);
struct StatTracker {
StatTracker(const string &cat, const string &n,
StatsCounterType *pa, StatsCounterType *pb = NULL,
bool percentage = true);
string category, name;
StatsCounterType *ptra, *ptrb;
bool percentage;
};
typedef map<std::pair<string, string>, StatTracker *> TrackerMap;
static TrackerMap trackers;
static void addTracker(StatTracker *newTracker) {
static Mutex *mutex = Mutex::Create();
MutexLock lock(*mutex);
std::pair<string, string> s = std::make_pair(newTracker->category, newTracker->name);
if (trackers.find(s) != trackers.end()) {
newTracker->ptra = trackers[s]->ptra;
newTracker->ptrb = trackers[s]->ptrb;
return;
}
trackers[s] = newTracker;
}
// Statistics Counters Function Definitions
void ProbesPrint(FILE *dest) {
fprintf(dest, "Statistics:\n");
TrackerMap::iterator iter = trackers.begin();
string lastCategory;
while (iter != trackers.end()) {
// Print statistic
StatTracker *tr = iter->second;
if (tr->category != lastCategory) {
fprintf(dest, "%s\n", tr->category.c_str());
lastCategory = tr->category;
}
fprintf(dest, " %s", tr->name.c_str());
// Pad out to results column
int resultsColumn = 56;
int paddingSpaces = resultsColumn - (int) tr->name.size();
while (paddingSpaces-- > 0)
putc(' ', dest);
if (tr->ptrb == NULL)
ProbesPrintVal(dest, *tr->ptra);
else {
if ((int64_t)(*tr->ptrb) > 0) {
float ratio = double((int64_t)*tr->ptra) / double((int64_t)*tr->ptrb);
ProbesPrintVal(dest, *tr->ptra, *tr->ptrb);
if (tr->percentage)
fprintf(dest, " (%3.2f%%)", 100. * ratio);
else
fprintf(dest, " (%.2fx)", ratio);
}
else
ProbesPrintVal(dest, *tr->ptra, *tr->ptrb);
}
fprintf(dest, "\n");
++iter;
}
}
static void ProbesPrintVal(FILE *f, const StatsCounterType &v) {
#if defined(PBRT_IS_WINDOWS)
LONG vv = v;
fprintf(f, "%d", vv);
#else
#ifdef PBRT_HAS_64_BIT_ATOMICS
int64_t vv = v;
fprintf(f, "%lld", vv);
#else
int32_t vv = v;
fprintf(f, "%d", vv);
#endif
#endif
}
static void ProbesPrintVal(FILE *f, const StatsCounterType &v1,
const StatsCounterType &v2) {
#if defined(PBRT_IS_WINDOWS)
LONG vv1 = v1, vv2 = v2;
fprintf(f, "%d:%d", vv1, vv2);
#else
#ifdef PBRT_HAS_64_BIT_ATOMICS
int64_t vv1 = v1, vv2 = v2;
fprintf(f, "%lld:%lld", vv1, vv2);
#else
int32_t vv1 = v1, vv2 = v2;
fprintf(f, "%d:%d", vv1, vv2);
#endif
#endif
}
void ProbesCleanup() {
TrackerMap::iterator iter = trackers.begin();
string lastCategory;
while (iter != trackers.end()) {
delete iter->second;
++iter;
}
trackers.erase(trackers.begin(), trackers.end());
}
StatTracker::StatTracker(const string &cat, const string &n,
StatsCounterType *pa, StatsCounterType *pb, bool p) {
category = cat;
name = n;
ptra = pa;
ptrb = pb;
percentage = p;
}
StatsCounter::StatsCounter(const string &category, const string &name) {
num = 0;
addTracker(new StatTracker(category, name, &num));
}
StatsRatio::StatsRatio(const string &category, const string &name) {
na = nb = 0;
addTracker(new StatTracker(category, name, &na, &nb, false));
}
StatsPercentage::StatsPercentage(const string &category, const string &name) {
addTracker(new StatTracker(category, name, &na, &nb, true));
}
// Statistics Counters Probe Declarations
static StatsCounter shapesMade("Shapes", "Total Shapes Created");
static StatsCounter trianglesMade("Shapes", "Total Triangles Created");
static StatsCounter cameraRays("Rays", "Camera Rays Traced");
static StatsCounter specularReflectionRays("Rays", "Specular Reflection Rays Traced");
static StatsCounter specularRefractionRays("Rays", "Specular Refraction Rays Traced");
static StatsCounter shadowRays("Rays", "Shadow Rays Traced");
static StatsCounter nonShadowRays("Rays", "Total Non-Shadow Rays Traced");
static StatsCounter kdTreeInteriorNodes("Kd-Tree", "Interior Nodes Created");
static StatsCounter kdTreeLeafNodes("Kd-Tree", "Interior Nodes Created");
static StatsCounter kdTreeMaxPrims("Kd-Tree", "Maximum Primitives in Leaf");
static StatsCounter kdTreeMaxDepth("Kd-Tree", "Maximum Depth of Leaf Nodes");
static StatsPercentage rayTriIntersections("Intersections", "Ray/Triangle Intersection Hits");
static StatsPercentage rayTriIntersectionPs("Intersections", "Ray/Triangle IntersectionP Hits");
// Statistics Counters Probe Definitions
void PBRT_CREATED_SHAPE(Shape *) {
++shapesMade;
}
void PBRT_CREATED_TRIANGLE(Triangle *) {
++trianglesMade;
}
void PBRT_STARTED_GENERATING_CAMERA_RAY(const CameraSample *) {
++cameraRays;
}
void PBRT_KDTREE_CREATED_INTERIOR_NODE(int axis, float split) {
++kdTreeInteriorNodes;
}
void PBRT_KDTREE_CREATED_LEAF(int nprims, int depth) {
++kdTreeLeafNodes;
kdTreeMaxPrims.Max(nprims);
kdTreeMaxDepth.Max(depth);
}
void PBRT_RAY_TRIANGLE_INTERSECTION_TEST(const Ray *, const Triangle *) {
rayTriIntersections.Add(0, 1);
}
void PBRT_RAY_TRIANGLE_INTERSECTIONP_TEST(const Ray *, const Triangle *) {
rayTriIntersectionPs.Add(0, 1);
}
void PBRT_RAY_TRIANGLE_INTERSECTION_HIT(const Ray *, float t) {
rayTriIntersections.Add(1, 0);
}
void PBRT_RAY_TRIANGLE_INTERSECTIONP_HIT(const Ray *, float t) {
rayTriIntersectionPs.Add(1, 0);
}
void PBRT_FINISHED_RAY_INTERSECTION(const Ray *, const Intersection *, int hit) {
++nonShadowRays;
}
void PBRT_FINISHED_RAY_INTERSECTIONP(const Ray *, int hit) {
++shadowRays;
}
void PBRT_STARTED_SPECULAR_REFLECTION_RAY(const RayDifferential *) {
++specularReflectionRays;
}
void PBRT_STARTED_SPECULAR_REFRACTION_RAY(const RayDifferential *) {
++specularRefractionRays;
}
#endif // PBRT_PROBES_COUNTERS
| 0 | 0.952883 | 1 | 0.952883 | game-dev | MEDIA | 0.350547 | game-dev | 0.947048 | 1 | 0.947048 |
phatboyg/Machete | 1,224 | src/Machete/Layouts/Parsers/EntityListLayoutParser.cs | namespace Machete.Layouts.Parsers
{
using System.Collections.Generic;
using Matches;
public class EntityListLayoutParser<TLayout, TSchema, TEntity> :
IParser<TSchema, LayoutMatch<TLayout>>
where TSchema : Entity
where TEntity : TSchema
where TLayout : Layout
{
readonly IParser<TSchema, IReadOnlyList<TEntity>> _parser;
readonly ILayoutPropertyWriter<TLayout, EntityList<TEntity>> _property;
public EntityListLayoutParser(IParser<TSchema, IReadOnlyList<TEntity>> parser, ILayoutPropertyWriter<TLayout, EntityList<TEntity>> property)
{
_parser = parser;
_property = property;
}
public Result<Cursor<TSchema>, LayoutMatch<TLayout>> Parse(Cursor<TSchema> input)
{
Result<Cursor<TSchema>, IReadOnlyList<TEntity>> result = _parser.Parse(input);
if (result.HasResult)
{
return new Success<Cursor<TSchema>, LayoutMatch<TLayout>>(new EntityListLayoutMatch<TLayout, TEntity>(_property, result.Result),
result.Next);
}
return new Unmatched<Cursor<TSchema>, LayoutMatch<TLayout>>(input);
}
}
} | 0 | 0.789608 | 1 | 0.789608 | game-dev | MEDIA | 0.395534 | game-dev | 0.889376 | 1 | 0.889376 |
Rz-C/Mohist | 1,386 | src/fmlcommon/java/net/minecraftforge/fml/event/lifecycle/ModLifecycleEvent.java | /*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.fml.event.lifecycle;
import net.minecraftforge.eventbus.api.Event;
import net.minecraftforge.fml.InterModComms;
import net.minecraftforge.fml.ModContainer;
import net.minecraftforge.fml.event.IModBusEvent;
import java.util.function.Predicate;
import java.util.stream.Stream;
/**
* Parent type to all ModLifecycle events. This is based on Forge EventBus. They fire through the
* ModContainer's eventbus instance.
*/
public class ModLifecycleEvent extends Event implements IModBusEvent
{
private final ModContainer container;
public ModLifecycleEvent(ModContainer container)
{
this.container = container;
}
public final String description()
{
String cn = getClass().getName();
return cn.substring(cn.lastIndexOf('.')+1);
}
public Stream<InterModComms.IMCMessage> getIMCStream() {
return InterModComms.getMessages(this.container.getModId());
}
public Stream<InterModComms.IMCMessage> getIMCStream(Predicate<String> methodFilter) {
return InterModComms.getMessages(this.container.getModId(), methodFilter);
}
ModContainer getContainer() {
return this.container;
}
@Override
public String toString() {
return description();
}
}
| 0 | 0.732937 | 1 | 0.732937 | game-dev | MEDIA | 0.949839 | game-dev | 0.813445 | 1 | 0.813445 |
avk959/LGenerics | 173,168 | lgenerics/lgvector.pas | {****************************************************************************
* *
* This file is part of the LGenerics package. *
* Generic vector implementations. *
* *
* Copyright(c) 2018-2025 A.Koverdyaev(avk) *
* *
* This code is free software; you can redistribute it and/or modify it *
* under the terms of the Apache License, Version 2.0; *
* 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. *
* *
*****************************************************************************}
unit lgVector;
{$mode objfpc}{$H+}
{$INLINE ON}
{$MODESWITCH ADVANCEDRECORDS}
{$MODESWITCH NESTEDPROCVARS}
interface
uses
SysUtils,
math,
lgUtils,
lgHelpers,
lgArrayHelpers,
lgAbstractContainer,
lgStrConst;
type
{ TGVector }
generic TGVector<T> = class(specialize TGCustomArrayContainer<T>)
protected
function GetItem(aIndex: SizeInt): T; inline;
procedure SetItem(aIndex: SizeInt; const aValue: T); virtual;
function GetMutable(aIndex: SizeInt): PItem; inline;
function GetUncMutable(aIndex: SizeInt): PItem; inline;
procedure InsertItem(aIndex: SizeInt; const aValue: T);
function InsertArray(aIndex: SizeInt; const a: array of T): SizeInt;
function InsertContainer(aIndex: SizeInt; aContainer: TSpecContainer): SizeInt;
function InsertEnum(aIndex: SizeInt; e: IEnumerable): SizeInt;
procedure FastSwap(L, R: SizeInt); inline;
function ExtractItem(aIndex: SizeInt): T;
function ExtractRange(aIndex, aCount: SizeInt): TArray;
function DeleteItem(aIndex: SizeInt): T; virtual;
function DeleteRange(aIndex, aCount: SizeInt): SizeInt; virtual;
function DoSplit(aIndex: SizeInt): TGVector;
public
{ appends aValue and returns it index; will raise ELGUpdateLock if instance in iteration }
function Add(const aValue: T): SizeInt;
{ appends all elements of array and returns count of added elements;
will raise ELGUpdateLock if instance in iteration }
function AddAll(const a: array of T): SizeInt;
function AddAll(e: IEnumerable): SizeInt;
{ inserts aValue into position aIndex;
will raise ELGListError if aIndex out of bounds(aIndex = Count is allowed);
will raise ELGUpdateLock if instance in iteration }
procedure Insert(aIndex: SizeInt; const aValue: T);
{ will return False if aIndex out of bounds or instance in iteration }
function TryInsert(aIndex: SizeInt; const aValue: T): Boolean;
{ inserts all elements of array a into position aIndex and returns count of inserted elements;
will raise ELGListError if aIndex out of bounds(aIndex = Count is allowed);
will raise ELGUpdateLock if instance in iteration }
function InsertAll(aIndex: SizeInt; const a: array of T): SizeInt;
{ inserts all elements of e into position aIndex and returns count of inserted elements;
will raise ELGListError if aIndex out of bounds(aIndex = Count is allowed);
will raise ELGUpdateLock if instance in iteration }
function InsertAll(aIndex: SizeInt; e: IEnumerable): SizeInt;
{ extracts value from position aIndex;
will raise ELGListError if aIndex out of bounds;
will raise ELGUpdateLock if instance in iteration }
function Extract(aIndex: SizeInt): T; inline;
{ will return False if aIndex out of bounds or instance in iteration }
function TryExtract(aIndex: SizeInt; out aValue: T): Boolean;
{ extracts aCount elements(if possible) starting from aIndex;
will raise ELGListError if aIndex out of bounds;
will raise ELGUpdateLock if instance in iteration }
function ExtractAll(aIndex, aCount: SizeInt): TArray;
{ extracts all elements satisfying the aTest predicate into the result array;
will raise ELGUpdateLock if instance in iteration }
function ExtractIf(aTest: TTest): TArray;
function ExtractIf(aTest: TOnTest): TArray;
function ExtractIf(aTest: TNestTest): TArray;
{ deletes value in position aIndex;
will raise ELGListError if aIndex out of bounds;
will raise ELGUpdateLock if instance in iteration }
procedure Delete(aIndex: SizeInt);
{ will return False if aIndex out of bounds or instance in iteration }
function TryDelete(aIndex: SizeInt): Boolean;
function DeleteLast: Boolean; inline;
function DeleteLast(out aValue: T): Boolean; inline;
{ deletes aCount elements(if possible) starting from aIndex and returns those count;
will raise ELGListError if aIndex out of bounds;
will raise ELGUpdateLock if instance in iteration }
function DeleteAll(aIndex, aCount: SizeInt): SizeInt;
{ removes all items not satisfying the aTest predicate; returns the number of items removed;
will raise ELGUpdateLock if instance in iteration }
function Filter(aTest: TTest): SizeInt; virtual;
function Filter(aTest: TOnTest): SizeInt; virtual;
function Filter(aTest: TNestTest): SizeInt; virtual;
{ will raise ELGListError if aIndex out of bounds;
will raise ELGUpdateLock if instance in iteration }
function Split(aIndex: SizeInt): TGVector;
{ will return False if aIndex out of bounds or instance in iteration }
function TrySplit(aIndex: SizeInt; out aValue: TGVector): Boolean;
{ if aSource <> Self, moves all elements of aVector to the end of its own list,
causing aSource to become empty; returns the number of moved elements }
function Merge(aSource: TGVector; aThenFree: Boolean = False): SizeInt;
property Items[aIndex: SizeInt]: T read GetItem write SetItem; default;
property Mutable[aIndex: SizeInt]: PItem read GetMutable;
{ does not checks aIndex range }
property UncMutable[aIndex: SizeInt]: PItem read GetUncMutable;
end;
{ TGObjectVector
note: for equality comparision of items uses TObjectHelper from LGHelpers }
generic TGObjectVector<T: class> = class(specialize TGVector<T>)
private
FOwnsObjects: Boolean;
protected
procedure SetItem(aIndex: SizeInt; const aValue: T); override;
procedure DoClear; override;
function DeleteItem(aIndex: SizeInt): T; override;
function DeleteRange(aIndex, aCount: SizeInt): SizeInt; override;
function DoSplit(aIndex: SizeInt): TGObjectVector;
public
constructor Create(aOwnsObjects: Boolean = True);
constructor Create(aCapacity: SizeInt; aOwnsObjects: Boolean = True);
constructor Create(const A: array of T; aOwnsObjects: Boolean = True);
constructor Create(e: IEnumerable; aOwnsObjects: Boolean = True);
{ removes all items not satisfying the aTest predicate; returns the number of items removed;
will raise ELGUpdateLock if instance in iteration }
function Filter(aTest: TTest): SizeInt; override;
function Filter(aTest: TOnTest): SizeInt; override;
function Filter(aTest: TNestTest): SizeInt; override;
{ will raise EArgumentOutOfRangeException if aIndex out of bounds }
function Split(aIndex: SizeInt): TGObjectVector;
{ will return False if aIndex out of bounds }
function TrySplit(aIndex: SizeInt; out aValue: TGObjectVector): Boolean;
property OwnsObjects: Boolean read FOwnsObjects write FOwnsObjects;
end;
generic TGThreadVector<T> = class
public
type
TVector = specialize TGVector<T>;
private
FVector: TVector;
FLock: TRTLCriticalSection;
procedure DoLock; inline;
public
constructor Create;
destructor Destroy; override;
{ returns reference to encapsulated vector, after use this reference one must call UnLock }
function Lock: TVector;
procedure Unlock; inline;
procedure Clear;
function Add(const aValue: T): SizeInt;
function TryInsert(aIndex: SizeInt; const aValue: T): Boolean;
function TryExtract(aIndex: SizeInt; out aValue: T): Boolean;
function TryDelete(aIndex: SizeInt): Boolean;
end;
{ TGLiteVector }
generic TGLiteVector<T> = record
private
type
TBuffer = specialize TGLiteDynBuffer<T>;
TFake = {$IFNDEF FPC_REQUIRES_PROPER_ALIGNMENT}array[0..Pred(SizeOf(T))] of Byte{$ELSE}T{$ENDIF};
THelper = specialize TGArrayHelpUtil<T>;
public
type
TEnumerator = TBuffer.TEnumerator;
TReverseEnumerator = TBuffer.TReverseEnumerator;
TMutableEnumerator = TBuffer.TMutableEnumerator;
TMutables = TBuffer.TMutables;
TReverse = TBuffer.TReverse;
PItem = TBuffer.PItem;
TArray = TBuffer.TArray;
private
FBuffer: TBuffer;
function GetCapacity: SizeInt; inline;
function GetItem(aIndex: SizeInt): T; inline;
function GetMutable(aIndex: SizeInt): PItem; inline;
function GetUncMutable(aIndex: SizeInt): PItem; inline;
procedure SetItem(aIndex: SizeInt; const aValue: T); inline;
procedure InsertItem(aIndex: SizeInt; const aValue: T);
function DeleteItem(aIndex: SizeInt): T;
function ExtractRange(aIndex, aCount: SizeInt): TArray;
function DeleteRange(aIndex, aCount: SizeInt): SizeInt;
public
function GetEnumerator: TEnumerator; inline;
function GetReverseEnumerator: TReverseEnumerator; inline;
function GetMutableEnumerator: TMutableEnumerator; inline;
function Mutables: TMutables; inline;
function Reverse: TReverse; inline;
function ToArray: TArray; inline;
procedure Clear; inline;
procedure MakeEmpty; inline;
function IsEmpty: Boolean; inline;
function NonEmpty: Boolean; inline;
procedure EnsureCapacity(aValue: SizeInt); inline;
procedure TrimToFit; inline;
{ appends aValue and returns it index }
function Add(const aValue: T): SizeInt;
function AddAll(const a: array of T): SizeInt;
function AddAll(e: specialize IGEnumerable<T>): SizeInt;
function AddAll(constref aVector: TGLiteVector): SizeInt;
function Fill(const aValue: T; aCount: SizeInt): SizeInt;
{ inserts aValue into position aIndex;
will raise ELGListError if aIndex out of bounds(aIndex = Count is allowed) }
procedure Insert(aIndex: SizeInt; const aValue: T); inline;
{ will return False if aIndex out of bounds }
function TryInsert(aIndex: SizeInt; const aValue: T): Boolean; inline;
{ inserts all elements of array a into position aIndex and returns count of inserted elements;
will raise ELGListError if aIndex out of bounds(aIndex = Count is allowed) }
function InsertAll(aIndex: SizeInt; const a: array of T): SizeInt;
{ inserts all elements of e into position aIndex and returns count of inserted elements;
will raise ELGListError if aIndex out of bounds(aIndex = Count is allowed) }
function InsertAll(aIndex: SizeInt; e: specialize IGEnumerable<T>): SizeInt;
{ deletes and returns value from position aIndex;
will raise ELGListError if aIndex out of bounds }
function Extract(aIndex: SizeInt): T; inline;
{ will return False if aIndex out of bounds }
function TryExtract(aIndex: SizeInt; out aValue: T): Boolean; inline;
{ extracts aCount elements(if possible) starting from aIndex;
will raise ELGListError if aIndex out of bounds }
function ExtractAll(aIndex, aCount: SizeInt): TArray; inline;
{ extracts all elements satisfying the aTest predicate into the result array }
function ExtractIf(aTest: specialize TGTest<T>): TArray;
function ExtractIf(aTest: specialize TGOnTest<T>): TArray;
function ExtractIf(aTest: specialize TGNestTest<T>): TArray;
function DeleteLast: Boolean;
function DeleteLast(out aValue: T): Boolean;
{ deletes aCount elements(if possible) starting from aIndex;
returns count of deleted elements;
will raise ELGListError if aIndex out of bounds }
function DeleteAll(aIndex, aCount: SizeInt): SizeInt; inline;
{ removes all items not satisfying the aTest predicate; returns the number of items removed }
function Filter(aTest: specialize TGTest<T>): SizeInt;
function Filter(aTest: specialize TGOnTest<T>): SizeInt;
function Filter(aTest: specialize TGNestTest<T>): SizeInt;
{ swaps items with indices aIdx1 and aIdx2; will raise ELGListError if any index out of bounds }
procedure Swap(aIdx1, aIdx2: SizeInt);
{ does not checks range }
procedure UncSwap(aIdx1, aIdx2: SizeInt); inline;
property Count: SizeInt read FBuffer.FCount;
property Capacity: SizeInt read GetCapacity;
property Items[aIndex: SizeInt]: T read GetItem write SetItem; default;
property Mutable[aIndex: SizeInt]: PItem read GetMutable;
{ does not checks aIndex range }
property UncMutable[aIndex: SizeInt]: PItem read GetUncMutable;
end;
generic TGLiteThreadVector<T> = class
public
type
TVector = specialize TGLiteVector<T>;
PVector = ^TVector;
private
FVector: TVector;
FLock: TRTLCriticalSection;
procedure DoLock; inline;
public
constructor Create;
destructor Destroy; override;
function Lock: PVector;
procedure Unlock; inline;
procedure Clear;
function Add(const aValue: T): SizeInt;
function TryInsert(aIndex: SizeInt; const aValue: T): Boolean;
function TryDelete(aIndex: SizeInt; out aValue: T): Boolean;
end;
{ TGLiteObjectVector }
generic TGLiteObjectVector<T: class> = record
private
type
TVector = specialize TGLiteVector<T>;
public
type
TEnumerator = TVector.TEnumerator;
TReverseEnumerator = TVector.TReverseEnumerator;
TReverse = TVector.TReverse;
TArray = TVector.TArray;
PItem = TVector.PItem;
private
FVector: TVector;
FOwnsObjects: Boolean;
function GetCount: SizeInt; inline;
function GetCapacity: SizeInt; inline;
function GetItem(aIndex: SizeInt): T; inline;
function GetUncMutable(aIndex: SizeInt): PItem; inline;
procedure SetItem(aIndex: SizeInt; const aValue: T);
procedure CheckFreeItems;
class operator Initialize(var v: TGLiteObjectVector);
class operator Copy(constref aSrc: TGLiteObjectVector; var aDst: TGLiteObjectVector);
public
type
PVector = ^TVector;
function InnerVector: PVector; inline;
function GetEnumerator: TEnumerator; inline;
function GetReverseEnumerator: TReverseEnumerator; inline;
function Reverse: TReverse; inline;
function ToArray: TArray; inline;
procedure Clear; inline;
function IsEmpty: Boolean; inline;
function NonEmpty: Boolean; inline;
procedure EnsureCapacity(aValue: SizeInt); inline;
procedure TrimToFit; inline;
{ appends aValue and returns it index }
function Add(const aValue: T): SizeInt;inline;
function AddAll(const a: array of T): SizeInt;
function AddAll(constref aVector: TGLiteObjectVector): SizeInt; inline;
{ inserts aValue into position aIndex;
will raise ELGListError if aIndex out of bounds(aIndex = Count is allowed) }
procedure Insert(aIndex: SizeInt; const aValue: T); inline;
{ will return False if aIndex out of bounds }
function TryInsert(aIndex: SizeInt; const aValue: T): Boolean; inline;
{ inserts all elements of array a into position aIndex and returns count of inserted elements;
will raise ELGListError if aIndex out of bounds(aIndex = Count is allowed) }
function InsertAll(aIndex: SizeInt; const a: array of T): SizeInt; inline;
{ inserts all elements of e into position aIndex and returns count of inserted elements;
will raise ELGListError if aIndex out of bounds(aIndex = Count is allowed) }
function InsertAll(aIndex: SizeInt; e: specialize IGEnumerable<T>): SizeInt; inline;
{ extracts value from position aIndex;
will raise ELGListError if aIndex out of bounds }
function Extract(aIndex: SizeInt): T; inline;
{ will return False if aIndex out of bounds }
function TryExtract(aIndex: SizeInt; out aValue: T): Boolean; inline;
{ extracts aCount elements(if possible) starting from aIndex;
will raise ELGListError if aIndex out of bounds }
function ExtractAll(aIndex, aCount: SizeInt): TArray; inline;
{ extracts all elements satisfying the aTest predicate into the result array }
function ExtractIf(aTest: specialize TGTest<T>): TArray;
function ExtractIf(aTest: specialize TGOnTest<T>): TArray;
function ExtractIf(aTest: specialize TGNestTest<T>): TArray;
{ deletes value in position aIndex; will raise ELGListError if aIndex out of bounds}
procedure Delete(aIndex: SizeInt); inline;
{ will return False if aIndex out of bounds }
function TryDelete(aIndex: SizeInt): Boolean; inline;
function DeleteLast: Boolean; inline;
function DeleteLast(out aValue: T): Boolean; inline;
{ deletes aCount elements(if possible) starting from aIndex;
returns count of deleted elements;
will raise ELGListError if aIndex out of bounds }
function DeleteAll(aIndex, aCount: SizeInt): SizeInt;
{ removes all items not satisfying the aTest predicate; returns the number of items removed }
function Filter(aTest: specialize TGTest<T>): SizeInt;
function Filter(aTest: specialize TGOnTest<T>): SizeInt;
function Filter(aTest: specialize TGNestTest<T>): SizeInt;
property Count: SizeInt read GetCount;
property Capacity: SizeInt read GetCapacity;
property Items[aIndex: SizeInt]: T read GetItem write SetItem; default;
{ does not checks aIndex range }
property UncMutable[aIndex: SizeInt]: PItem read GetUncMutable;
property OwnsObjects: Boolean read FOwnsObjects write FOwnsObjects;
end;
generic TGLiteThreadObjectVector<T: class> = class
public
type
TVector = specialize TGLiteObjectVector<T>;
PVector = ^TVector;
private
FVector: TVector;
FLock: TRTLCriticalSection;
procedure DoLock; inline;
public
constructor Create;
destructor Destroy; override;
function Lock: PVector;
procedure Unlock; inline;
procedure Clear;
function Add(const aValue: T): SizeInt;
function TryInsert(aIndex: SizeInt; const aValue: T): Boolean;
function TryExtract(aIndex: SizeInt; out aValue: T): Boolean;
function TryDelete(aIndex: SizeInt): Boolean;
end;
{ TBoolVector: capacity is always a multiple of the bitness }
TBoolVector = record
private
type
TBits = array of SizeUInt;
var
FBits: TBits;
function GetCapacity: SizeInt; inline;
function GetBit(aIndex: SizeInt): Boolean; inline;
function GetBitUncheck(aIndex: SizeInt): Boolean; inline;
procedure SetCapacity(aValue: SizeInt);
procedure SetBit(aIndex: SizeInt; aValue: Boolean);
procedure SetBitUncheck(aIndex: SizeInt; aValue: Boolean); inline;
{ returns count of significant limbs }
function SignLimbCount: SizeInt;
class operator Copy(constref aSrc: TBoolVector; var aDst: TBoolVector); inline;
class operator AddRef(var bv: TBoolVector); inline;
public
type
TEnumerator = record
private
FBits: TBits;
FBitIndex,
FLimbIndex: SizeInt;
FCurrLimb: SizeUInt;
function GetCurrent: SizeInt; inline;
function FindFirst: Boolean;
procedure Init(const aBits: TBits);
public
function MoveNext: Boolean; inline;
property Current: SizeInt read GetCurrent;
end;
TReverseEnumerator = record
private
FBits: TBits;
FBitIndex,
FLimbIndex: SizeInt;
FCurrLimb: SizeUInt;
function GetCurrent: SizeInt; inline;
function FindLast: Boolean;
procedure Init(const aBits: TBits);
public
function MoveNext: Boolean;
property Current: SizeInt read GetCurrent;
end;
TReverse = record
private
FBits: TBits;
public
function GetEnumerator: TReverseEnumerator; inline;
end;
TIntArray = array of SizeInt;
public
procedure InitRange(aRange: SizeInt);
{ enumerates indices of set bits from lowest to highest }
function GetEnumerator: TEnumerator; inline;
{ enumerates indices of set bits from highest down to lowest }
function Reverse: TReverse; inline;
{ returns an array containing the indices of the set bits }
function ToArray: TIntArray;
procedure EnsureCapacity(aValue: SizeInt); inline;
procedure TrimToFit;
procedure Clear; inline;
procedure ClearBits; inline;
procedure SetBits; inline;
procedure ToggleBits;
function IsEmpty: Boolean;
function NonEmpty: Boolean; inline;
procedure SwapBits(var aVector: TBoolVector);
procedure CopyBits(const aVector: TBoolVector; aCount: SizeInt);
function All: Boolean;
{ returns the lowest index of the set bit, -1, if no bit is set }
function Bsf: SizeInt;
{ returns the index of the next set bit after aFromIdx, if any, otherwise returns -1 }
function NextSetBit(aFromIdx: SizeInt): SizeInt;
{ returns the index of the previous set bit before aFromIdx, if any, otherwise returns -1 }
function PrevSetBit(aFromIdx: SizeInt): SizeInt;
{ returns the highest index of the set bit, -1, if no bit is set }
function Bsr: SizeInt;
{ returns the lowest index of the open bit, -1, if all bits are set }
function Lob: SizeInt;
{ returns the highest index of the open bit, -1, if all bits are set }
function Hob: SizeInt;
{ returns the index of the next open bit after aFromIdx, if any, otherwise returns -1 }
function NextOpenBit(aFromIdx: SizeInt): SizeInt;
{ returns the index of the previous open bit before aFromIdx, if any, otherwise returns -1 }
function PrevOpenBit(aFromIdx: SizeInt): SizeInt;
{ changes the bit[aIndex] value to True if it was False and to False if it was True;
returns old value; checks aIndex range }
function ToggleBit(aIndex: SizeInt): Boolean;
{ changes the bit[aIndex] value to True if it was False and to False if it was True;
returns old value; does not checks aIndex range}
function UncToggleBit(aIndex: SizeInt): Boolean; inline;
function Intersecting(constref aValue: TBoolVector): Boolean;
{ returns the number of bits in the intersection with aValue }
function IntersectionPop(constref aValue: TBoolVector): SizeInt;
function Contains(constref aValue: TBoolVector): Boolean;
{ returns the number of bits that will be added when union with aValue }
function JoinGain(constref aValue: TBoolVector): SizeInt;
procedure Join(constref aValue: TBoolVector);
function Union(constref aValue: TBoolVector): TBoolVector; inline;
procedure Subtract(constref aValue: TBoolVector);
function Difference(constref aValue: TBoolVector): TBoolVector; inline;
procedure Intersect(constref aValue: TBoolVector);
function Intersection(constref aValue: TBoolVector): TBoolVector; inline;
procedure DisjunctJoin(constref aValue: TBoolVector);
function SymmDifference(constref aValue: TBoolVector): TBoolVector;
function Equals(constref aValue: TBoolVector): Boolean;
{ currently Capacity is always multiple of BitsizeOf(SizeUInt) }
property Capacity: SizeInt read GetCapacity write SetCapacity;
{ returns count of set bits }
function PopCount: SizeInt;
{ checks aIndex range }
property Bits[aIndex: SizeInt]: Boolean read GetBit write SetBit; default;
{ does not checks aIndex range }
property UncBits[aIndex: SizeInt]: Boolean read GetBitUncheck write SetBitUncheck;
end;
{ TGVectorHelpUtil }
generic TGVectorHelpUtil<T> = class
private
type
THelper = specialize TGArrayHelpUtil<T>;
public
type
TEqualityCompare = THelper.TEqualCompare;
TVector = specialize TGVector<T>;
TLiteVector = specialize TGLiteVector<T>;
class procedure SwapItems(v: TVector; L, R: SizeInt); static;
class procedure SwapItems(var v: TLiteVector; L, R: SizeInt); static; inline;
class procedure Reverse(v: TVector); static; inline;
class procedure Reverse(var v: TLiteVector); static; inline;
class procedure RandomShuffle(v: TVector); static; inline;
class procedure RandomShuffle(var v: TLiteVector); static; inline;
class function SequentSearch(v: TVector; const aValue: T; c: TEqualityCompare): SizeInt; static; inline;
class function SequentSearch(constref v: TLiteVector; const aValue: T; c: TEqualityCompare): SizeInt;
static; inline;
end;
{ TGBaseVectorHelper
functor TCmpRel(comparison relation) must provide:
class function Less([const[ref]] L, R: T): Boolean }
generic TGBaseVectorHelper<T, TCmpRel> = class
private
type
THelper = specialize TGBaseArrayHelper<T, TCmpRel>;
public
type
TVector = specialize TGVector<T>;
TLiteVector = specialize TGLiteVector<T>;
TOptional = specialize TGOptional<T>;
{ returns position of aValue in vector V, -1 if not found }
class function SequentSearch(v: TVector; const aValue: T): SizeInt; static; inline;
class function SequentSearch(constref v: TLiteVector; const aValue: T): SizeInt; static; inline;
{ returns position of aValue in SORTED vector V, -1 if not found }
class function BinarySearch(v: TVector; const aValue: T): SizeInt; static; inline;
class function BinarySearch(constref v: TLiteVector; const aValue: T): SizeInt; static; inline;
{ returns position of minimal value in V, -1 if V is empty }
class function IndexOfMin(v: TVector): SizeInt; static; inline;
class function IndexOfMin(constref v: TLiteVector): SizeInt; static; inline;
{ returns position of maximal value in V, -1 if V is empty }
class function IndexOfMax(v: TVector): SizeInt; static; inline;
class function IndexOfMax(constref v: TLiteVector): SizeInt; static; inline;
{ returns smallest element of A in TOptional.Value if V is nonempty }
class function GetMin(v: TVector): TOptional; static; inline;
class function GetMin(constref v: TLiteVector): TOptional; static; inline;
{ returns greatest element of A in TOptional.Value if V is nonempty }
class function GetMax(v: TVector): TOptional; static; inline;
class function GetMax(constref v: TLiteVector): TOptional; static; inline;
{ returns True and smallest element of A in aValue if V is nonempty, False otherwise }
class function FindMin(v: TVector; out aValue: T): Boolean; static; inline;
class function FindMin(constref v: TLiteVector; out aValue: T): Boolean; static; inline;
{ returns True and greatest element of A in aValue if V is nonempty, False otherwise }
class function FindMax(v: TVector; out aValue: T): Boolean; static; inline;
class function FindMax(constref v: TLiteVector; out aValue: T): Boolean; static; inline;
{ returns True, smallest element of V in aMin and greatest element of V in aMax, if V is nonempty,
False otherwise }
class function FindMinMax(v: TVector; out aMin, aMax: T): Boolean; static; inline;
class function FindMinMax(constref v: TLiteVector; out aMin, aMax: T): Boolean; static; inline;
{ returns True and V's Nth order statistic(0-based) in aValue if V is nonempty, False otherwise;
if N < 0 then N sets to 0; if N > High(V) then N sets to High(V);
is nondestuctive: creates temp copy of V }
class function FindNthSmallest(v: TVector; N: SizeInt; out aValue: T): Boolean; static; inline;
class function FindNthSmallest(constref v: TLiteVector; N: SizeInt; out aValue: T): Boolean; static; inline;
{ returns V's Nth order statistic(0-based) in TOptional.Value if V is nonempty;
if N < 0 then N sets to 0; if N > High(V) then N sets to High(V);
is nondestuctive: creates temp copy of V }
class function NthSmallest(v: TVector; N: SizeInt): TOptional; static; inline;
class function NthSmallest(constref v: TLiteVector; N: SizeInt): TOptional; static; inline;
{ returns True if permutation towards nondescending state of V has done, False otherwise }
class function NextPermutation2Asc(v: TVector): Boolean; static; inline;
class function NextPermutation2Asc(var v: TLiteVector): Boolean; static; inline;
{ returns True if permutation towards nonascending state of V has done, False otherwise }
class function NextPermutation2Desc(v: TVector): Boolean; static; inline;
class function NextPermutation2Desc(var v: TLiteVector): Boolean; static; inline;
{ note: an empty array or single element array is always nondescending }
class function IsNonDescending(v: TVector): Boolean; static; inline;
class function IsNonDescending(constref v: TLiteVector): Boolean; static; inline;
{ note: an empty array or single element array is never strict ascending }
class function IsStrictAscending(v: TVector): Boolean; static; inline;
class function IsStrictAscending(constref v: TLiteVector): Boolean; static; inline;
{ note: an empty array or single element array is always nonascending }
class function IsNonAscending(v: TVector): Boolean; static; inline;
class function IsNonAscending(constref v: TLiteVector): Boolean; static; inline;
{ note: an empty array or single element array is never strict descending}
class function IsStrictDescending(v: TVector): Boolean; static; inline;
class function IsStrictDescending(constref v: TLiteVector): Boolean; static; inline;
{ returns True if both A and B are identical sequence of elements }
class function Same(A, B: TVector): Boolean; static;
class function Same(constref A, B: TLiteVector): Boolean; static;
{ slightly modified Introsort with pseudo-median-of-9 pivot selection }
class procedure IntroSort(v: TVector; o: TSortOrder = soAsc); static; inline;
class procedure IntroSort(var v: TLiteVector; o: TSortOrder = soAsc); static; inline;
{ Pascal translation of Orson Peters' PDQSort algorithm }
class procedure PDQSort(v: TVector; o: TSortOrder = soAsc); static;
class procedure PDQSort(var v: TLiteVector; o: TSortOrder = soAsc); static;
{ stable, adaptive mergesort, inspired by Java Timsort }
class procedure MergeSort(v: TVector; o: TSortOrder = soAsc); static; inline;
class procedure MergeSort(var v: TLiteVector; o: TSortOrder = soAsc); static; inline;
{ default sort algorithm, currently PDQSort}
class procedure Sort(v: TVector; o: TSortOrder = soAsc); static; inline;
class procedure Sort(var v: TLiteVector; o: TSortOrder = soAsc); static; inline;
{ copies only distinct values from v }
class function SelectDistinct(v: TVector): TVector.TArray; static; inline;
class function SelectDistinct(constref v: TLiteVector): TLiteVector.TArray; static; inline;
end;
{ TGVectorHelper assumes that type T implements TCmpRel }
generic TGVectorHelper<T> = class(specialize TGBaseVectorHelper<T, T>);
{ TGComparableVectorHelper assumes that type T defines comparison operators }
generic TGComparableVectorHelper<T> = class
private
type
THelper = specialize TGComparableArrayHelper<T>;
public
type
TVector = specialize TGVector<T>;
TLiteVector = specialize TGLiteVector<T>;
TOptional = specialize TGOptional<T>;
class procedure Reverse(v: TVector); static; inline;
class procedure Reverse(var v: TLiteVector); static; inline;
class procedure RandomShuffle(v: TVector); static; inline;
class procedure RandomShuffle(var v: TLiteVector); static; inline;
{ returns position of aValue in vector V, -1 if not found }
class function SequentSearch(v: TVector; const aValue: T): SizeInt; static; inline;
class function SequentSearch(constref v: TLiteVector; const aValue: T): SizeInt; static; inline;
{ returns position of aValue in SORTED vector V, -1 if not found }
class function BinarySearch(v: TVector; const aValue: T): SizeInt; static; inline;
class function BinarySearch(constref v: TLiteVector; const aValue: T): SizeInt; static; inline;
{ returns position of minimal value in V, -1 if V is empty }
class function IndexOfMin(v: TVector): SizeInt; static; inline;
class function IndexOfMin(constref v: TLiteVector): SizeInt; static; inline;
{ returns position of maximal value in V, -1 if V is empty }
class function IndexOfMax(v: TVector): SizeInt; static; inline;
class function IndexOfMax(constref v: TLiteVector): SizeInt; static; inline;
{ returns smallest element of A in TOptional.Value if V is nonempty }
class function GetMin(v: TVector): TOptional; static; inline;
class function GetMin(constref v: TLiteVector): TOptional; static; inline;
{ returns greatest element of A in TOptional.Value if V is nonempty }
class function GetMax(v: TVector): TOptional; static; inline;
class function GetMax(constref v: TLiteVector): TOptional; static; inline;
{ returns True and smallest element of A in aValue if V is nonempty, False otherwise }
class function FindMin(v: TVector; out aValue: T): Boolean; static; inline;
class function FindMin(constref v: TLiteVector; out aValue: T): Boolean; static; inline;
{ returns True and greatest element of A in aValue if V is nonempty, False otherwise }
class function FindMax(v: TVector; out aValue: T): Boolean; static; inline;
class function FindMax(constref v: TLiteVector; out aValue: T): Boolean; static; inline;
{ returns True, smallest element of V in aMin and greatest element of V in aMax, if V is nonempty,
False otherwise }
class function FindMinMax(v: TVector; out aMin, aMax: T): Boolean; static; inline;
class function FindMinMax(constref v: TLiteVector; out aMin, aMax: T): Boolean; static; inline;
{ returns True and V's Nth order statistic(0-based) in aValue if V is nonempty, False otherwise;
if N < 0 then N sets to 0; if N > High(V) then N sets to High(V);
is nondestuctive: creates temp copy of V }
class function FindNthSmallest(v: TVector; N: SizeInt; out aValue: T): Boolean; static; inline;
class function FindNthSmallest(constref v: TLiteVector; N: SizeInt; out aValue: T): Boolean; static; inline;
{ returns V's Nth order statistic(0-based) in TOptional.Value if V is nonempty;
if N < 0 then N sets to 0; if N > High(V) then N sets to High(V);
is nondestuctive: creates temp copy of V }
class function NthSmallest(v: TVector; N: SizeInt): TOptional; static; inline;
class function NthSmallest(constref v: TLiteVector; N: SizeInt): TOptional; static; inline; //constref ?
{ returns True if permutation towards nondescending state of V has done, False otherwise }
class function NextPermutation2Asc(v: TVector): Boolean; static; inline;
class function NextPermutation2Asc(var v: TLiteVector): Boolean; static; inline;
{ returns True if permutation towards nonascending state of V has done, False otherwise }
class function NextPermutation2Desc(v: TVector): Boolean; static; inline;
class function NextPermutation2Desc(var v: TLiteVector): Boolean; static; inline;
{ note: an empty array or single element array is always nondescending }
class function IsNonDescending(v: TVector): Boolean; static; inline;
class function IsNonDescending(constref v: TLiteVector): Boolean; static; inline;
{ note: an empty array or single element array is never strict ascending }
class function IsStrictAscending(v: TVector): Boolean; static; inline;
class function IsStrictAscending(constref v: TLiteVector): Boolean; static; inline;
{ note: an empty array or single element array is always nonascending }
class function IsNonAscending(v: TVector): Boolean; static; inline;
class function IsNonAscending(constref v: TLiteVector): Boolean; static; inline;
{ note: an empty array or single element array is never strict descending}
class function IsStrictDescending(v: TVector): Boolean; static; inline;
class function IsStrictDescending(constref v: TLiteVector): Boolean; static; inline;
{ returns True if both A and B are identical sequence of elements }
class function Same(A, B: TVector): Boolean; static;
class function Same(constref A, B: TLiteVector): Boolean; static;
{ slightly modified Introsort with pseudo-median-of-9 pivot selection }
class procedure IntroSort(v: TVector; o: TSortOrder = soAsc); static; inline;
class procedure IntroSort(var v: TLiteVector; o: TSortOrder = soAsc); static; inline;
{ Pascal translation of Orson Peters' PDQSort algorithm }
class procedure PDQSort(v: TVector; o: TSortOrder = soAsc); static;
class procedure PDQSort(var v: TLiteVector; o: TSortOrder = soAsc); static;
{ stable, adaptive mergesort, inspired by Java Timsort }
class procedure MergeSort(v: TVector; o: TSortOrder = soAsc); static; inline;
class procedure MergeSort(var v: TLiteVector; o: TSortOrder = soAsc); static; inline;
{ default sort algorithm, currently PDQSort}
class procedure Sort(v: TVector; o: TSortOrder = soAsc); static; inline;
class procedure Sort(var v: TLiteVector; o: TSortOrder = soAsc); static; inline;
{ copies only distinct values from v }
class function SelectDistinct(v: TVector): TVector.TArray; static; inline;
class function SelectDistinct(constref v: TLiteVector): TLiteVector.TArray; static; inline;
end;
{ TGRegularVectorHelper: with regular comparator }
generic TGRegularVectorHelper<T> = class
private
type
THelper = specialize TGRegularArrayHelper<T>;
public
type
TVector = specialize TGVector<T>;
TLiteVector = specialize TGLiteVector<T>;
TOptional = specialize TGOptional<T>;
TLess = specialize TGLessCompare<T>;
{ returns position of aValue in vector V, -1 if not found }
class function SequentSearch(v: TVector; const aValue: T; c: TLess): SizeInt; static; inline;
class function SequentSearch(constref v: TLiteVector; const aValue: T; c: TLess): SizeInt; static; inline;
{ returns position of aValue in SORTED vector V, -1 if not found }
class function BinarySearch(v: TVector; const aValue: T; c: TLess): SizeInt; static; inline;
class function BinarySearch(constref v: TLiteVector; const aValue: T; c: TLess): SizeInt; static; inline;
{ returns position of minimal value in V, -1 if V is empty }
class function IndexOfMin(v: TVector; c: TLess): SizeInt; static; inline;
{ returns position of maximal value in V, -1 if V is empty }
class function IndexOfMax(v: TVector; c: TLess): SizeInt; static; inline;
class function IndexOfMax(constref v: TLiteVector; c: TLess): SizeInt; static; inline;
{ returns smallest element of A in TOptional.Value if V is nonempty }
class function GetMin(v: TVector; c: TLess): TOptional; static; inline;
class function GetMin(constref v: TLiteVector; c: TLess): TOptional; static; inline;
{ returns greatest element of A in TOptional.Value if V is nonempty }
class function GetMax(v: TVector; c: TLess): TOptional; static; inline;
class function GetMax(constref v: TLiteVector; c: TLess): TOptional; static; inline;
{ returns True and smallest element of A in aValue if V is nonempty, False otherwise }
class function FindMin(v: TVector; out aValue: T; c: TLess): Boolean; static; inline;
class function FindMin(constref v: TLiteVector; out aValue: T; c: TLess): Boolean; static; inline;
{ returns True and greatest element of A in aValue if V is nonempty, False otherwise }
class function FindMax(v: TVector; out aValue: T; c: TLess): Boolean; static; inline;
class function FindMax(constref v: TLiteVector; out aValue: T; c: TLess): Boolean; static; inline;
{ returns True, smallest element of V in aMin and greatest element of V in aMax, if V is nonempty,
False otherwise }
class function FindMinMax(v: TVector; out aMin, aMax: T; c: TLess): Boolean; static; inline;
class function FindMinMax(constref v: TLiteVector; out aMin, aMax: T; c: TLess): Boolean; static; inline;
{ returns True and V's Nth order statistic(0-based) in aValue if V is nonempty, False otherwise;
if N < 0 then N sets to 0; if N > High(V) then N sets to High(V);
is nondestuctive: creates temp copy of V }
class function FindNthSmallest(v: TVector; N: SizeInt; out aValue: T; c: TLess): Boolean; static; inline;
class function FindNthSmallest(constref v: TLiteVector; N: SizeInt; out aValue: T; c: TLess): Boolean;
static; inline;
{ returns V's Nth order statistic(0-based) in TOptional.Value if V is nonempty;
if N < 0 then N sets to 0; if N > High(V) then N sets to High(V);
is nondestuctive: creates temp copy of V }
class function NthSmallest(v: TVector; N: SizeInt; c: TLess): TOptional; static; inline;
class function NthSmallest(constref v: TLiteVector; N: SizeInt; c: TLess): TOptional; static; inline;
{ returns True if permutation towards nondescending state of V has done, False otherwise }
class function NextPermutation2Asc(v: TVector; c: TLess): Boolean; static; inline;
class function NextPermutation2Asc(var v: TLiteVector; c: TLess): Boolean; static; inline;
{ returns True if permutation towards nonascending state of V has done, False otherwise }
class function NextPermutation2Desc(v: TVector; c: TLess): Boolean; static; inline;
class function NextPermutation2Desc(var v: TLiteVector; c: TLess): Boolean; static; inline;
{ note: an empty array or single element array is always nondescending }
class function IsNonDescending(v: TVector; c: TLess): Boolean; static; inline;
class function IsNonDescending(constref v: TLiteVector; c: TLess): Boolean; static; inline;
{ note: an empty array or single element array is never strict ascending }
class function IsStrictAscending(v: TVector; c: TLess): Boolean; static; inline;
{ note: an empty array or single element array is always nonascending }
class function IsNonAscending(v: TVector; c: TLess): Boolean; static; inline;
class function IsNonAscending(constref v: TLiteVector; c: TLess): Boolean; static; inline;
{ note: an empty array or single element array is never strict descending}
class function IsStrictDescending(v: TVector; c: TLess): Boolean; static; inline;
class function IsStrictDescending(constref v: TLiteVector; c: TLess): Boolean; static; inline;
{ returns True if both A and B are identical sequence of elements }
class function Same(A, B: TVector; c: TLess): Boolean; static;
class function Same(constref A, B: TLiteVector; c: TLess): Boolean; static;
{ slightly modified Introsort with pseudo-median-of-9 pivot selection }
class procedure IntroSort(v: TVector; c: TLess; o: TSortOrder = soAsc); static; inline;
class procedure IntroSort(var v: TLiteVector; c: TLess; o: TSortOrder = soAsc); static; inline;
{ Pascal translation of Orson Peters' PDQSort algorithm }
class procedure PDQSort(v: TVector; c: TLess; o: TSortOrder = soAsc); static;
class procedure PDQSort(var v: TLiteVector; c: TLess; o: TSortOrder = soAsc); static;
{ stable, adaptive mergesort, inspired by Java Timsort }
class procedure MergeSort(v: TVector; c: TLess; o: TSortOrder = soAsc); static; inline;
class procedure MergeSort(var v: TLiteVector; c: TLess; o: TSortOrder = soAsc); static; inline;
{ default sort algorithm, currently PDQSort }
class procedure Sort(v: TVector; c: TLess; o: TSortOrder = soAsc); static; inline;
class procedure Sort(var v: TLiteVector; c: TLess; o: TSortOrder = soAsc); static; inline;
{ copies only distinct values from v }
class function SelectDistinct(v: TVector; c: TLess): TVector.TArray; static; inline;
class function SelectDistinct(constref v: TLiteVector; c: TLess): TLiteVector.TArray; static; inline;
end;
{ TGDelegatedVectorHelper: with delegated comparator }
generic TGDelegatedVectorHelper<T> = class
private
type
THelper = specialize TGDelegatedArrayHelper<T>;
public
type
TVector = specialize TGVector<T>;
TLiteVector = specialize TGLiteVector<T>;
TOptional = specialize TGOptional<T>;
TOnLess = specialize TGOnLessCompare<T>;
{ returns position of aValue in vector V, -1 if not found }
class function SequentSearch(v: TVector; const aValue: T; c: TOnLess): SizeInt; static; inline;
class function SequentSearch(constref v: TLiteVector; const aValue: T; c: TOnLess): SizeInt; static; inline;
{ returns position of aValue in SORTED vector V, -1 if not found }
class function BinarySearch(v: TVector; const aValue: T; c: TOnLess): SizeInt; static; inline;
class function BinarySearch(constref v: TLiteVector; const aValue: T; c: TOnLess): SizeInt; static; inline;
{ returns position of minimal value in V, -1 if V is empty }
class function IndexOfMin(v: TVector; c: TOnLess): SizeInt; static; inline;
class function IndexOfMin(constref v: TLiteVector; c: TOnLess): SizeInt; static; inline;
{ returns position of maximal value in V, -1 if V is empty }
class function IndexOfMax(v: TVector; c: TOnLess): SizeInt; static; inline;
class function IndexOfMax(constref v: TLiteVector; c: TOnLess): SizeInt; static; inline;
{ returns smallest element of A in TOptional.Value if V is nonempty }
class function GetMin(v: TVector; c: TOnLess): TOptional; static; inline;
class function GetMin(constref v: TLiteVector; c: TOnLess): TOptional; static; inline;
{ returns greatest element of A in TOptional.Value if V is nonempty }
class function GetMax(v: TVector; c: TOnLess): TOptional; static; inline;
class function GetMax(constref v: TLiteVector; c: TOnLess): TOptional; static; inline;
{ returns True and smallest element of A in aValue if V is nonempty, False otherwise }
class function FindMin(v: TVector; out aValue: T; c: TOnLess): Boolean; static; inline;
class function FindMin(constref v: TLiteVector; out aValue: T; c: TOnLess): Boolean; static; inline;
{ returns True and greatest element of A in aValue if V is nonempty, False otherwise }
class function FindMax(v: TVector; out aValue: T; c: TOnLess): Boolean; static; inline;
class function FindMax(constref v: TLiteVector; out aValue: T; c: TOnLess): Boolean; static; inline;
{ returns True, smallest element of V in aMin and greatest element of V in aMax, if V is nonempty,
False otherwise }
class function FindMinMax(v: TVector; out aMin, aMax: T; c: TOnLess): Boolean; static; inline;
class function FindMinMax(constref v: TLiteVector; out aMin, aMax: T; c: TOnLess): Boolean;
static; inline;
{ returns True and V's Nth order statistic(0-based) in aValue if V is nonempty, False otherwise;
if N < 0 then N sets to 0; if N > High(V) then N sets to High(V);
is destuctive: changes order of elements in V }
class function FindNthSmallest(v: TVector; N: SizeInt; out aValue: T; c: TOnLess): Boolean;
static; inline;
class function FindNthSmallest(constref v: TLiteVector; N: SizeInt; out aValue: T; c: TOnLess): Boolean;
static; inline;
{ returns V's Nth order statistic(0-based) in TOptional.Value if A is nonempty;
if N < 0 then N sets to 0; if N > High(V) then N sets to High(V);
is destuctive: changes order of elements in V }
class function NthSmallest(v: TVector; N: SizeInt; c: TOnLess): TOptional; static; inline;
class function NthSmallest(constref v: TLiteVector; N: SizeInt; c: TOnLess): TOptional; static; inline;
{ returns True if permutation towards nondescending state of V has done, False otherwise }
class function NextPermutation2Asc(v: TVector; c: TOnLess): Boolean; static; inline;
class function NextPermutation2Asc(var v: TLiteVector; c: TOnLess): Boolean; static; inline;
{ returns True if permutation towards nonascending state of V has done, False otherwise }
class function NextPermutation2Desc(v: TVector; c: TOnLess): Boolean; static; inline;
class function NextPermutation2Desc(var v: TLiteVector; c: TOnLess): Boolean; static; inline;
{ note: an empty array or single element array is always nondescending }
class function IsNonDescending(v: TVector; c: TOnLess): Boolean; static; inline;
class function IsNonDescending(constref v: TLiteVector; c: TOnLess): Boolean; static; inline;
{ note: an empty array or single element array is never strict ascending }
class function IsStrictAscending(v: TVector; c: TOnLess): Boolean; static; inline;
class function IsStrictAscending(constref v: TLiteVector; c: TOnLess): Boolean; static; inline;
{ note: an empty array or single element array is always nonascending }
class function IsNonAscending(v: TVector; c: TOnLess): Boolean; static; inline;
class function IsNonAscending(constref v: TLiteVector; c: TOnLess): Boolean; static; inline;
{ note: an empty array or single element array is never strict descending}
class function IsStrictDescending(v: TVector; c: TOnLess): Boolean; static; inline;
class function IsStrictDescending(constref v: TLiteVector; c: TOnLess): Boolean; static; inline;
{ returns True if both A and B are identical sequence of elements }
class function Same(A, B: TVector; c: TOnLess): Boolean; static;
class function Same(constref A, B: TLiteVector; c: TOnLess): Boolean; static;
{ slightly modified Introsort with pseudo-median-of-9 pivot selection }
class procedure IntroSort(v: TVector; c: TOnLess; o: TSortOrder = soAsc); static; inline;
class procedure IntroSort(var v: TLiteVector; c: TOnLess; o: TSortOrder = soAsc); static; inline;
{ Pascal translation of Orson Peters' PDQSort algorithm }
class procedure PDQSort(v: TVector; c: TOnLess; o: TSortOrder = soAsc); static;
class procedure PDQSort(var v: TLiteVector; c: TOnLess; o: TSortOrder = soAsc); static;
{ stable, adaptive mergesort, inspired by Java Timsort }
class procedure MergeSort(v: TVector; c: TOnLess; o: TSortOrder = soAsc); static; inline;
class procedure MergeSort(var v: TLiteVector; c: TOnLess; o: TSortOrder = soAsc); static; inline;
{ default sort algorithm, currently PDQSort }
class procedure Sort(v: TVector; c: TOnLess; o: TSortOrder = soAsc); static; inline;
class procedure Sort(var v: TLiteVector; c: TOnLess; o: TSortOrder = soAsc); static; inline;
{ copies only distinct values from v }
class function SelectDistinct(v: TVector; c: TOnLess): TVector.TArray; static; inline;
class function SelectDistinct(constref v: TLiteVector; c: TOnLess): TLiteVector.TArray; static; inline;
end;
{ TGNestedVectorHelper: with nested comparator }
generic TGNestedVectorHelper<T> = class
private
type
THelper = specialize TGNestedArrayHelper<T>;
public
type
TVector = specialize TGVector<T>;
TLiteVector = specialize TGLiteVector<T>;
TOptional = specialize TGOptional<T>;
TLess = specialize TGNestLessCompare<T>;
{ returns position of aValue in vector V, -1 if not found }
class function SequentSearch(v: TVector; const aValue: T; c: TLess): SizeInt; static; inline;
class function SequentSearch(constref v: TLiteVector; const aValue: T; c: TLess): SizeInt; static;
inline;
{ returns position of aValue in SORTED vector V, -1 if not found }
class function BinarySearch(v: TVector; const aValue: T; c: TLess): SizeInt; static; inline;
class function BinarySearch(constref v: TLiteVector; const aValue: T; c: TLess): SizeInt; static;
inline;
{ returns position of minimal value in V, -1 if V is empty }
class function IndexOfMin(v: TVector; c: TLess): SizeInt; static; inline;
class function IndexOfMin(constref v: TLiteVector; c: TLess): SizeInt; static; inline;
{ returns position of maximal value in V, -1 if V is empty }
class function IndexOfMax(v: TVector; c: TLess): SizeInt; static; inline;
class function IndexOfMax(constref v: TLiteVector; c: TLess): SizeInt; static; inline;
{ returns smallest element of A in TOptional.Value if V is nonempty }
class function GetMin(v: TVector; c: TLess): TOptional; static; inline;
class function GetMin(constref v: TLiteVector; c: TLess): TOptional; static; inline;
{ returns greatest element of A in TOptional.Value if V is nonempty }
class function GetMax(v: TVector; c: TLess): TOptional; static; inline;
class function GetMax(constref v: TLiteVector; c: TLess): TOptional; static; inline;
{ returns True and smallest element of A in aValue if V is nonempty, False otherwise }
class function FindMin(v: TVector; out aValue: T; c: TLess): Boolean; static; inline;
class function FindMin(constref v: TLiteVector; out aValue: T; c: TLess): Boolean; static; inline;
{ returns True and greatest element of A in aValue if V is nonempty, False otherwise }
class function FindMax(v: TVector; out aValue: T; c: TLess): Boolean; static; inline;
class function FindMax(constref v: TLiteVector; out aValue: T; c: TLess): Boolean; static; inline;
{ returns True, smallest element of V in aMin and greatest element of V in aMax, if V is nonempty,
False otherwise }
class function FindMinMax(v: TVector; out aMin, aMax: T; c: TLess): Boolean; static; inline;
class function FindMinMax(constref v: TLiteVector; out aMin, aMax: T; c: TLess): Boolean; static; inline;
{ returns True and V's Nth order statistic(0-based) in aValue if V is nonempty, False otherwise;
if N < 0 then N sets to 0; if N > High(V) then N sets to High(V);
is destuctive: changes order of elements in V }
class function FindNthSmallest(v: TVector; N: SizeInt; out aValue: T; c: TLess): Boolean; static; inline;
class function FindNthSmallest(constref v: TLiteVector; N: SizeInt; out aValue: T; c: TLess): Boolean;
static; inline;
{ returns V's Nth order statistic(0-based) in TOptional.Value if A is nonempty;
if N < 0 then N sets to 0; if N > High(V) then N sets to High(V);
is destuctive: changes order of elements in V }
class function NthSmallest(v: TVector; N: SizeInt; c: TLess): TOptional; static; inline;
class function NthSmallest(constref v: TLiteVector; N: SizeInt; c: TLess): TOptional; static; inline;
{ returns True if permutation towards nondescending state of V has done, False otherwise }
class function NextPermutation2Asc(v: TVector; c: TLess): Boolean; static; inline;
class function NextPermutation2Asc(var v: TLiteVector; c: TLess): Boolean; static; inline;
{ returns True if permutation towards nonascending state of V has done, False otherwise }
class function NextPermutation2Desc(v: TVector; c: TLess): Boolean; static; inline;
class function NextPermutation2Desc(var v: TLiteVector; c: TLess): Boolean; static; inline;
{ note: an empty array or single element array is always nondescending }
class function IsNonDescending(v: TVector; c: TLess): Boolean; static; inline;
class function IsNonDescending(constref v: TLiteVector; c: TLess): Boolean; static; inline;
{ note: an empty array or single element array is never strict ascending }
class function IsStrictAscending(v: TVector; c: TLess): Boolean; static; inline;
class function IsStrictAscending(constref v: TLiteVector; c: TLess): Boolean; static; inline;
{ note: an empty array or single element array is always nonascending }
class function IsNonAscending(v: TVector; c: TLess): Boolean; static; inline;
class function IsNonAscending(constref v: TLiteVector; c: TLess): Boolean; static; inline;
{ note: an empty array or single element array is never strict descending}
class function IsStrictDescending(v: TVector; c: TLess): Boolean; static; inline;
class function IsStrictDescending(constref v: TLiteVector; c: TLess): Boolean; static; inline;
{ returns True if both A and B are identical sequence of elements }
class function Same(A, B: TVector; c: TLess): Boolean; static;
class function Same(constref A, B: TLiteVector; c: TLess): Boolean; static;
{ slightly modified Introsort with pseudo-median-of-9 pivot selection }
class procedure IntroSort(v: TVector; c: TLess; o: TSortOrder = soAsc); static; inline;
class procedure IntroSort(var v: TLiteVector; c: TLess; o: TSortOrder = soAsc); static; inline;
{ Pascal translation of Orson Peters' PDQSort algorithm }
class procedure PDQSort(v: TVector; c: TLess; o: TSortOrder = soAsc); static;
class procedure PDQSort(var v: TLiteVector; c: TLess; o: TSortOrder = soAsc); static;
{ stable, adaptive mergesort, inspired by Java Timsort }
class procedure MergeSort(v: TVector; c: TLess; o: TSortOrder = soAsc); static; inline;
class procedure MergeSort(var v: TLiteVector; c: TLess; o: TSortOrder = soAsc); static; inline;
{ default sort algorithm, currently PDQSort }
class procedure Sort(v: TVector; c: TLess; o: TSortOrder = soAsc); static; inline;
class procedure Sort(var v: TLiteVector; c: TLess; o: TSortOrder = soAsc); static; inline;
{ copies only distinct values from v }
class function SelectDistinct(v: TVector; c: TLess): TVector.TArray; static; inline;
class function SelectDistinct(constref v: TLiteVector; c: TLess): TVector.TArray; static; inline;
end;
{ TGOrdVectorHelper: for ordinal types only }
generic TGOrdVectorHelper<T> = class
private
type
THelper = specialize TGOrdinalArrayHelper<T>;
public
type
TVector = specialize TGVector<T>;
TLiteVector = specialize TGLiteVector<T>;
TArray = THelper.TArray;
class procedure RadixSort(v: TVector; o: TSortOrder = soAsc); static; inline;
class procedure RadixSort(var v: TLiteVector; o: TSortOrder = soAsc); static; inline;
class procedure RadixSort(v: TVector; var aBuf: TArray; o: TSortOrder = soAsc); static; inline;
class procedure RadixSort(var v: TLiteVector; var aBuf: TArray; o: TSortOrder = soAsc); static; inline;
class procedure Sort(v: TVector; o: TSortOrder = soAsc); static; inline; inline;
class procedure Sort(var v: TLiteVector; o: TSortOrder = soAsc); static; inline;
end;
{ TGRadixVectorSorter provides LSD radix sort;
TKey is the type for which LSD radix sort is appropriate.
TMap must provide class function GetKey([const[ref]] aItem: T): TKey; }
generic TGRadixVectorSorter<T, TKey, TMap> = class
private
type
THelper = specialize TGRadixSorter<T, TKey, TMap>;
public
type
TVector = specialize TGVector<T>;
TLiteVector = specialize TGLiteVector<T>;
TArray = THelper.TArray;
class procedure Sort(v: TVector; o: TSortOrder = soAsc); static; inline;
class procedure Sort(var v: TLiteVector; o: TSortOrder = soAsc); static; inline;
class procedure Sort(v: TVector; var aBuf: TArray; o: TSortOrder = soAsc); static; inline;
class procedure Sort(var v: TLiteVector; var aBuf: TArray; o: TSortOrder = soAsc); static; inline;
end;
implementation
{$B-}{$COPERATORS ON}{$POINTERMATH ON}
{ TGVector }
function TGVector.GetItem(aIndex: SizeInt): T;
begin
CheckIndexRange(aIndex);
Result := FItems[aIndex];
end;
procedure TGVector.SetItem(aIndex: SizeInt; const aValue: T);
begin
//CheckInIteration;
CheckIndexRange(aIndex);
FItems[aIndex] := aValue;
end;
function TGVector.GetMutable(aIndex: SizeInt): PItem;
begin
CheckIndexRange(aIndex);
Result := @FItems[aIndex];
end;
function TGVector.GetUncMutable(aIndex: SizeInt): PItem;
begin
Result := @FItems[aIndex];
end;
procedure TGVector.InsertItem(aIndex: SizeInt; const aValue: T);
begin
if aIndex < ElemCount then
begin
ItemAdding;
System.Move(FItems[aIndex], FItems[Succ(aIndex)], SizeOf(T) * (ElemCount - aIndex));
if IsManagedType(T) then
System.FillChar(FItems[aIndex], SizeOf(T), 0);
FItems[aIndex] := aValue;
Inc(FCount);
end
else
Append(aValue);
end;
function TGVector.InsertArray(aIndex: SizeInt; const a: array of T): SizeInt;
begin
if aIndex < ElemCount then
begin
Result := System.Length(a);
if Result > 0 then
begin
EnsureCapacity(ElemCount + Result);
System.Move(FItems[aIndex], FItems[aIndex + Result], (ElemCount - aIndex) * SizeOf(T));
if IsManagedType(T) then
begin
System.FillChar(FItems[aIndex], Result * SizeOf(T), 0);
TCopyHelper.CopyItems(@a[0], @FItems[aIndex], Result);
end
else
System.Move(a[0], FItems[aIndex], Result * SizeOf(T));
FCount += Result;
end;
end
else
Result := AppendArray(a);
end;
function TGVector.InsertContainer(aIndex: SizeInt; aContainer: TSpecContainer): SizeInt;
begin
if aIndex < ElemCount then
begin
Result := aContainer.Count;
if Result > 0 then
begin
EnsureCapacity(ElemCount + Result);
System.Move(FItems[aIndex], FItems[aIndex + Result], SizeOf(T) * (ElemCount - aIndex));
if IsManagedType(T) then
System.FillChar(FItems[aIndex], SizeOf(T) * Result, 0);
if aContainer <> Self then
aContainer.CopyItems(@FItems[aIndex])
else
if IsManagedType(T) then
begin
TCopyHelper.CopyItems(@FItems[0], @FItems[aIndex], aIndex);
TCopyHelper.CopyItems(@FItems[aIndex + Result], @FItems[aIndex + aIndex], Result - aIndex);
end
else
begin
System.Move(FItems[0], FItems[aIndex], aIndex * SizeOf(T));
System.Move(FItems[aIndex + Result], FItems[aIndex + aIndex], (Result - aIndex) * SizeOf(T));
end;
FCount += Result;
end;
end
else
Result := AppendContainer(aContainer);
end;
function TGVector.InsertEnum(aIndex: SizeInt; e: IEnumerable): SizeInt;
var
o: TObject;
begin
o := e._GetRef;
if o is TSpecContainer then
Result := InsertContainer(aIndex, TSpecContainer(o))
else
Result := InsertArray(aIndex, e.ToArray);
end;
procedure TGVector.FastSwap(L, R: SizeInt);
var
v: TFake;
begin
v := TFake(FItems[L]);
TFake(FItems[L]) := TFake(FItems[R]);
TFake(FItems[R]) := v;
end;
function TGVector.ExtractItem(aIndex: SizeInt): T;
begin
Result := FItems[aIndex];
if IsManagedType(T) then
FItems[aIndex] := Default(T);
Dec(FCount);
if aIndex < ElemCount then
begin
System.Move(FItems[Succ(aIndex)], FItems[aIndex], SizeOf(T) * (ElemCount - aIndex));
if IsManagedType(T) then
System.FillChar(FItems[ElemCount], SizeOf(T), 0);
end;
end;
function TGVector.ExtractRange(aIndex, aCount: SizeInt): TArray;
begin
Result := nil;
if aCount < 0 then
aCount := 0;
aCount := Math.Min(aCount, ElemCount - aIndex);
System.SetLength(Result, aCount);
if aCount > 0 then
begin
System.Move(FItems[aIndex], Result[0], SizeOf(T) * aCount);
FCount -= aCount;
if ElemCount - aIndex > 0 then
System.Move(FItems[aIndex + aCount], FItems[aIndex], SizeOf(T) * (ElemCount - aIndex));
if IsManagedType(T) then
System.FillChar(FItems[ElemCount], SizeOf(T) * aCount, 0);
end;
end;
function TGVector.DeleteItem(aIndex: SizeInt): T;
begin
Result := ExtractItem(aIndex);
end;
function TGVector.DeleteRange(aIndex, aCount: SizeInt): SizeInt;
var
I: SizeInt;
begin
if aCount < 0 then
aCount := 0;
Result := Math.Min(aCount, ElemCount - aIndex);
if Result > 0 then
begin
if IsManagedType(T) then
for I := aIndex to Pred(aIndex + Result) do
FItems[I] := Default(T);
FCount -= Result;
if ElemCount - aIndex > 0 then
System.Move(FItems[aIndex + Result], FItems[aIndex], SizeOf(T) * (ElemCount - aIndex));
if IsManagedType(T) then
System.FillChar(FItems[ElemCount], SizeOf(T) * Result, 0);
end;
end;
function TGVector.DoSplit(aIndex: SizeInt): TGVector;
var
RCount: SizeInt;
begin
RCount := ElemCount - aIndex;
Result := TGVector.Create(RCount);
System.Move(FItems[aIndex], Result.FItems[0], SizeOf(T) * RCount);
if IsManagedType(T) then
System.FillChar(FItems[aIndex], SizeOf(T) * RCount, 0);
Result.FCount := RCount;
FCount -= RCount;
end;
function TGVector.Add(const aValue: T): SizeInt;
begin
CheckInIteration;
Result := Append(aValue);
end;
function TGVector.AddAll(const a: array of T): SizeInt;
begin
CheckInIteration;
Result := AppendArray(a);
end;
function TGVector.AddAll(e: IEnumerable): SizeInt;
begin
if not InIteration then
Result := AppendEnumerable(e)
else
begin
Result := 0;
e.Any;
UpdateLockError;
end;
end;
procedure TGVector.Insert(aIndex: SizeInt; const aValue: T);
begin
CheckInIteration;
CheckInsertIndexRange(aIndex);
InsertItem(aIndex, aValue);
end;
function TGVector.TryInsert(aIndex: SizeInt; const aValue: T): Boolean;
begin
Result := not InIteration and IndexInInsertRange(aIndex);
if Result then
InsertItem(aIndex, aValue);
end;
function TGVector.InsertAll(aIndex: SizeInt; const a: array of T): SizeInt;
begin
CheckInIteration;
CheckInsertIndexRange(aIndex);
Result := InsertArray(aIndex, a);
end;
function TGVector.InsertAll(aIndex: SizeInt; e: IEnumerable): SizeInt;
begin
CheckInIteration;
CheckInsertIndexRange(aIndex);
Result := InsertEnum(aIndex, e);
end;
function TGVector.Extract(aIndex: SizeInt): T;
begin
CheckInIteration;
CheckIndexRange(aIndex);
Result := ExtractItem(aIndex);
end;
function TGVector.TryExtract(aIndex: SizeInt; out aValue: T): Boolean;
begin
Result := not InIteration and IndexInRange(aIndex);
if Result then
aValue := ExtractItem(aIndex);
end;
function TGVector.ExtractAll(aIndex, aCount: SizeInt): TArray;
begin
CheckInIteration;
CheckIndexRange(aIndex);
Result := ExtractRange(aIndex, aCount);
end;
function TGVector.ExtractIf(aTest: TTest): TArray;
var
ToExtract: TArray;
I, J, Len: SizeInt;
begin
CheckInIteration;
if ElemCount = 0 then exit(nil);
J := 0;
Len := 0;
System.SetLength(ToExtract, ElemCount);
for I := 0 to Pred(ElemCount) do begin
if aTest(FItems[I]) then begin
ToExtract[Len] := (FItems[I]);
Inc(Len);
continue;
end;
if I <> J then
FItems[J] := FItems[I];
Inc(J);
end;
if ElemCount - J <> 0 then begin
if IsManagedType(T) then
for I := J to Pred(ElemCount) do
FItems[I] := Default(T);
FCount := J;
end;
System.SetLength(ToExtract, Len);
Result := ToExtract;
end;
function TGVector.ExtractIf(aTest: TOnTest): TArray;
var
ToExtract: TArray;
I, J, Len: SizeInt;
begin
CheckInIteration;
if ElemCount = 0 then exit(nil);
J := 0;
Len := 0;
System.SetLength(ToExtract, ElemCount);
for I := 0 to Pred(ElemCount) do begin
if aTest(FItems[I]) then begin
ToExtract[Len] := (FItems[I]);
Inc(Len);
continue;
end;
if I <> J then
FItems[J] := FItems[I];
Inc(J);
end;
if ElemCount - J <> 0 then begin
if IsManagedType(T) then
for I := J to Pred(ElemCount) do
FItems[I] := Default(T);
FCount := J;
end;
System.SetLength(ToExtract, Len);
Result := ToExtract;
end;
function TGVector.ExtractIf(aTest: TNestTest): TArray;
var
ToExtract: TArray;
I, J, Len: SizeInt;
begin
CheckInIteration;
if ElemCount = 0 then exit(nil);
J := 0;
Len := 0;
System.SetLength(ToExtract, ElemCount);
for I := 0 to Pred(ElemCount) do begin
if aTest(FItems[I]) then begin
ToExtract[Len] := (FItems[I]);
Inc(Len);
continue;
end;
if I <> J then
FItems[J] := FItems[I];
Inc(J);
end;
if ElemCount - J <> 0 then begin
if IsManagedType(T) then
for I := J to Pred(ElemCount) do
FItems[I] := Default(T);
FCount := J;
end;
System.SetLength(ToExtract, Len);
Result := ToExtract;
end;
procedure TGVector.Delete(aIndex: SizeInt);
begin
CheckInIteration;
CheckIndexRange(aIndex);
DeleteItem(aIndex);
end;
function TGVector.TryDelete(aIndex: SizeInt): Boolean;
begin
Result := not InIteration and IndexInRange(aIndex);
if Result then
DeleteItem(aIndex);
end;
function TGVector.DeleteLast: Boolean;
begin
if not InIteration and (ElemCount > 0) then
begin
DeleteItem(Pred(ElemCount));
exit(True);
end;
Result := False;
end;
function TGVector.DeleteLast(out aValue: T): Boolean;
begin
if not InIteration and (ElemCount > 0) then
begin
aValue := ExtractItem(Pred(ElemCount));
exit(True);
end;
Result := False;
end;
function TGVector.DeleteAll(aIndex, aCount: SizeInt): SizeInt;
begin
CheckInIteration;
CheckIndexRange(aIndex);
Result := DeleteRange(aIndex, aCount);
end;
function TGVector.Filter(aTest: TTest): SizeInt;
var
I, J: SizeInt;
begin
CheckInIteration;
if ElemCount = 0 then exit(0);
J := 0;
for I := 0 to Pred(ElemCount) do begin
if not aTest(FItems[I]) then continue;
if I <> J then
FItems[J] := FItems[I];
Inc(J);
end;
Result := ElemCount - J;
if Result <> 0 then begin
if IsManagedType(T) then
for I := J to Pred(ElemCount) do
FItems[I] := Default(T);
FCount := J;
end;
end;
function TGVector.Filter(aTest: TOnTest): SizeInt;
var
I, J: SizeInt;
begin
CheckInIteration;
if ElemCount = 0 then exit(0);
J := 0;
for I := 0 to Pred(ElemCount) do begin
if not aTest(FItems[I]) then continue;
if I <> J then
FItems[J] := FItems[I];
Inc(J);
end;
Result := ElemCount - J;
if Result <> 0 then begin
if IsManagedType(T) then
for I := J to Pred(ElemCount) do
FItems[I] := Default(T);
FCount := J;
end;
end;
function TGVector.Filter(aTest: TNestTest): SizeInt;
var
I, J: SizeInt;
begin
CheckInIteration;
if ElemCount = 0 then exit(0);
J := 0;
for I := 0 to Pred(ElemCount) do begin
if not aTest(FItems[I]) then continue;
if I <> J then
FItems[J] := FItems[I];
Inc(J);
end;
Result := ElemCount - J;
if Result <> 0 then begin
if IsManagedType(T) then
for I := J to Pred(ElemCount) do
FItems[I] := Default(T);
FCount := J;
end;
end;
function TGVector.Split(aIndex: SizeInt): TGVector;
begin
CheckInIteration;
CheckIndexRange(aIndex);
Result := DoSplit(aIndex);
end;
function TGVector.TrySplit(aIndex: SizeInt; out aValue: TGVector): Boolean;
begin
Result := not InIteration and IndexInRange(aIndex);
if Result then
aValue := DoSplit(aIndex);
end;
function TGVector.Merge(aSource: TGVector; aThenFree: Boolean): SizeInt;
begin
Result := 0;
if aSource = Self then exit;
CheckInIteration;
if aSource.ElemCount > 0 then
begin
Result += aSource.ElemCount;
DoEnsureCapacity(ElemCount + Result);
System.Move(aSource.FItems[0], FItems[ElemCount], SizeOf(TItem)*Result);
if IsManagedType(TItem) then
System.FillChar(aSource.FItems[0], SizeOf(TItem)*Result, 0);
aSource.FCount := 0;
FCount += Result;
if aThenFree then aSource.Free;
end;
end;
{ TGObjectVector }
procedure TGObjectVector.SetItem(aIndex: SizeInt; const aValue: T);
begin
//CheckInIteration;
CheckIndexRange(aIndex);
if FItems[aIndex] <> aValue then
begin
if OwnsObjects then
FItems[aIndex].Free;
FItems[aIndex] := aValue;
end;
end;
procedure TGObjectVector.DoClear;
var
I: SizeInt;
begin
if OwnsObjects and (ElemCount > 0) then
for I := 0 to Pred(ElemCount) do
FItems[I].Free;
inherited;
end;
function TGObjectVector.DeleteItem(aIndex: SizeInt): T;
begin
Result := inherited DeleteItem(aIndex);
if OwnsObjects then
Result.Free;
end;
function TGObjectVector.DeleteRange(aIndex, aCount: SizeInt): SizeInt;
var
I: SizeInt;
begin
if aCount < 0 then
aCount := 0;
Result := Math.Min(aCount, ElemCount - aIndex);
if Result > 0 then
begin
if OwnsObjects then
for I := aIndex to Pred(aIndex + Result) do
FItems[I].Free;
FCount -= Result;
System.Move((@FItems[aIndex + Result])^, FItems[aIndex], SizeOf(T) * (ElemCount - aIndex));
end;
end;
function TGObjectVector.DoSplit(aIndex: SizeInt): TGObjectVector;
var
RCount: SizeInt;
begin
RCount := ElemCount - aIndex;
Result := TGObjectVector.Create(RCount, OwnsObjects);
System.Move((@FItems[aIndex])^, Result.FItems[0], SizeOf(T) * RCount);
Result.FCount := RCount;
FCount -= RCount;
end;
constructor TGObjectVector.Create(aOwnsObjects: Boolean);
begin
inherited Create;
FOwnsObjects := aOwnsObjects;
end;
constructor TGObjectVector.Create(aCapacity: SizeInt; aOwnsObjects: Boolean);
begin
inherited Create(aCapacity);
FOwnsObjects := aOwnsObjects;
end;
constructor TGObjectVector.Create(const A: array of T; aOwnsObjects: Boolean);
begin
inherited Create(A);
FOwnsObjects := aOwnsObjects;
end;
constructor TGObjectVector.Create(e: IEnumerable; aOwnsObjects: Boolean);
begin
inherited Create(e);
FOwnsObjects := aOwnsObjects;
end;
function TGObjectVector.Filter(aTest: TTest): SizeInt;
var
I, J: SizeInt;
begin
CheckInIteration;
if ElemCount = 0 then exit(0);
J := 0;
for I := 0 to Pred(ElemCount) do begin
if not aTest(FItems[I]) then begin
if OwnsObjects then FItems[I].Free;
continue;
end;
if I <> J then
FItems[J] := FItems[I];
Inc(J);
end;
Result := ElemCount - J;
FCount := J;
end;
function TGObjectVector.Filter(aTest: TOnTest): SizeInt;
var
I, J: SizeInt;
begin
CheckInIteration;
if ElemCount = 0 then exit(0);
J := 0;
for I := 0 to Pred(ElemCount) do begin
if not aTest(FItems[I]) then begin
if OwnsObjects then FItems[I].Free;
continue;
end;
if I <> J then
FItems[J] := FItems[I];
Inc(J);
end;
Result := ElemCount - J;
FCount := J;
end;
function TGObjectVector.Filter(aTest: TNestTest): SizeInt;
var
I, J: SizeInt;
begin
CheckInIteration;
if ElemCount = 0 then exit(0);
J := 0;
for I := 0 to Pred(ElemCount) do begin
if not aTest(FItems[I]) then begin
if OwnsObjects then FItems[I].Free;
continue;
end;
if I <> J then
FItems[J] := FItems[I];
Inc(J);
end;
Result := ElemCount - J;
FCount := J;
end;
function TGObjectVector.Split(aIndex: SizeInt): TGObjectVector;
begin
CheckInIteration;
CheckIndexRange(aIndex);
Result := DoSplit(aIndex);
end;
function TGObjectVector.TrySplit(aIndex: SizeInt; out aValue: TGObjectVector): Boolean;
begin
Result := not InIteration and (aIndex >= 0) and (aIndex < ElemCount);
if Result then
aValue := DoSplit(aIndex);
end;
procedure TGThreadVector.DoLock;
begin
System.EnterCriticalSection(FLock);
end;
constructor TGThreadVector.Create;
begin
System.InitCriticalSection(FLock);
FVector := TVector.Create;
end;
destructor TGThreadVector.Destroy;
begin
DoLock;
try
FVector.Free;
inherited;
finally
UnLock;
System.DoneCriticalSection(FLock);
end;
end;
function TGThreadVector.Lock: TVector;
begin
Result := FVector;
DoLock;
end;
procedure TGThreadVector.Unlock;
begin
System.LeaveCriticalSection(FLock);
end;
procedure TGThreadVector.Clear;
begin
DoLock;
try
FVector.Clear;
finally
UnLock;
end;
end;
function TGThreadVector.Add(const aValue: T): SizeInt;
begin
DoLock;
try
Result := FVector.Add(aValue);
finally
UnLock;
end;
end;
function TGThreadVector.TryInsert(aIndex: SizeInt; const aValue: T): Boolean;
begin
DoLock;
try
Result := FVector.TryInsert(aIndex, aValue);
finally
UnLock;
end;
end;
function TGThreadVector.TryExtract(aIndex: SizeInt; out aValue: T): Boolean;
begin
DoLock;
try
Result := FVector.TryExtract(aIndex, aValue);
finally
UnLock;
end;
end;
function TGThreadVector.TryDelete(aIndex: SizeInt): Boolean;
begin
DoLock;
try
Result := FVector.TryDelete(aIndex);
finally
UnLock;
end;
end;
{ TGLiteVector }
function TGLiteVector.GetCapacity: SizeInt;
begin
Result := FBuffer.Capacity;
end;
function TGLiteVector.GetItem(aIndex: SizeInt): T;
begin
if SizeUInt(aIndex) < SizeUInt(Count) then
Result := FBuffer.FItems[aIndex]
else
raise ELGListError.CreateFmt(SEIndexOutOfBoundsFmt, [aIndex]);
end;
function TGLiteVector.GetMutable(aIndex: SizeInt): PItem;
begin
if SizeUInt(aIndex) < SizeUInt(Count) then
Result := @FBuffer.FItems[aIndex]
else
raise ELGListError.CreateFmt(SEIndexOutOfBoundsFmt, [aIndex]);
end;
function TGLiteVector.GetUncMutable(aIndex: SizeInt): PItem;
begin
Result := @FBuffer.FItems[aIndex];
end;
procedure TGLiteVector.SetItem(aIndex: SizeInt; const aValue: T);
begin
if SizeUInt(aIndex) < SizeUInt(Count) then
FBuffer.FItems[aIndex] := aValue
else
raise ELGListError.CreateFmt(SEIndexOutOfBoundsFmt, [aIndex]);
end;
procedure TGLiteVector.InsertItem(aIndex: SizeInt; const aValue: T);
begin
if aIndex < Count then
begin
FBuffer.ItemAdding;
System.Move(FBuffer.FItems[aIndex], FBuffer.FItems[Succ(aIndex)], SizeOf(T) * (Count - aIndex));
if IsManagedType(T) then
System.FillChar(FBuffer.FItems[aIndex], SizeOf(T), 0);
FBuffer.FItems[aIndex] := aValue;
Inc(FBuffer.FCount);
end
else
Add(aValue);
end;
function TGLiteVector.DeleteItem(aIndex: SizeInt): T;
begin
Result := FBuffer.FItems[aIndex];
if IsManagedType(T) then
FBuffer.FItems[aIndex] := Default(T);
Dec(FBuffer.FCount);
if aIndex < Count then
begin
System.Move(FBuffer.FItems[Succ(aIndex)], FBuffer.FItems[aIndex], SizeOf(T) * (Count - aIndex));
if IsManagedType(T) then
System.FillChar(FBuffer.FItems[Count], SizeOf(T), 0);
end;
end;
function TGLiteVector.ExtractRange(aIndex, aCount: SizeInt): TArray;
begin
Result := nil;
if aCount < 0 then
aCount := 0;
aCount := Math.Min(aCount, Count - aIndex);
System.SetLength(Result, aCount);
if aCount > 0 then
begin
System.Move(FBuffer.FItems[aIndex], Pointer(Result)^, SizeOf(T) * aCount);
FBuffer.FCount -= aCount;
if Count - aIndex > 0 then
System.Move(FBuffer.FItems[aIndex + aCount], FBuffer.FItems[aIndex], SizeOf(T) * (Count - aIndex));
if IsManagedType(T) then
System.FillChar(FBuffer.FItems[Count], SizeOf(T) * aCount, 0);
end;
end;
function TGLiteVector.DeleteRange(aIndex, aCount: SizeInt): SizeInt;
begin
if aCount < 0 then
aCount := 0;
Result := Math.Min(aCount, Count - aIndex);
if Result > 0 then
begin
if IsManagedType(T) then
FBuffer.FinalizeItems(aIndex, Result);
FBuffer.FCount -= Result;
if Count - aIndex > 0 then
System.Move(FBuffer.FItems[aIndex + Result], FBuffer.FItems[aIndex], SizeOf(T) * (Count - aIndex));
if IsManagedType(T) then
System.FillChar(FBuffer.FItems[Count], SizeOf(T) * Result, 0);
end;
end;
function TGLiteVector.GetEnumerator: TEnumerator;
begin
Result := FBuffer.GetEnumerator;
end;
function TGLiteVector.GetReverseEnumerator: TReverseEnumerator;
begin
Result := FBuffer.GetReverseEnumerator;
end;
function TGLiteVector.GetMutableEnumerator: TMutableEnumerator;
begin
Result := FBuffer.GetMutableEnumerator;
end;
function TGLiteVector.Mutables: TMutables;
begin
Result := FBuffer.Mutables;
end;
function TGLiteVector.Reverse: TReverse;
begin
Result := FBuffer.Reverse;
end;
function TGLiteVector.ToArray: TArray;
begin
Result := FBuffer.ToArray;
end;
procedure TGLiteVector.Clear;
begin
FBuffer.Clear;
end;
procedure TGLiteVector.MakeEmpty;
begin
FBuffer.MakeEmpty;
end;
function TGLiteVector.IsEmpty: Boolean;
begin
Result := Count = 0;
end;
function TGLiteVector.NonEmpty: Boolean;
begin
Result := Count <> 0;
end;
procedure TGLiteVector.EnsureCapacity(aValue: SizeInt);
begin
FBuffer.EnsureCapacity(aValue);
end;
procedure TGLiteVector.TrimToFit;
begin
FBuffer.TrimToFit;
end;
function TGLiteVector.Add(const aValue: T): SizeInt;
begin
Result := FBuffer.PushLast(aValue);
end;
function TGLiteVector.AddAll(const a: array of T): SizeInt;
var
I, J: SizeInt;
begin
Result := System.Length(a);
if Result = 0 then exit;
EnsureCapacity(Count + Result);
I := Count;
with FBuffer do
begin
if IsManagedType(T) then
for J := 0 to System.High(a) do
begin
FItems[I] := a[J];
Inc(I);
end
else
System.Move(a[0], FItems[I], Result * SizeOf(T));
FCount += Result;
end;
end;
function TGLiteVector.AddAll(e: specialize IGEnumerable<T>): SizeInt;
begin
Result := Count;
with e.GetEnumerator do
try
while MoveNext do
FBuffer.PushLast(Current);
finally
Free;
end;
Result := Count - Result;
end;
function TGLiteVector.AddAll(constref aVector: TGLiteVector): SizeInt;
var
I, J: SizeInt;
begin
Result := aVector.Count;
if Result = 0 then exit;
EnsureCapacity(Count + Result);
I := Count;
with FBuffer do
begin
if IsManagedType(T) then
for J := 0 to Pred(aVector.Count) do
begin
FItems[I] := aVector.FBuffer.FItems[J];
Inc(I);
end
else
System.Move(Pointer(aVector.FBuffer.FItems)^, FItems[I], Result * SizeOf(T));
FCount += Result;
end;
end;
function TGLiteVector.Fill(const aValue: T; aCount: SizeInt): SizeInt;
begin
FBuffer.MakeEmpty;
if aCount > 0 then
begin
FBuffer.EnsureCapacity(aCount);
THelper.Fill(FBuffer.FItems[0..Pred(aCount)], aValue);
FBuffer.FCount := aCount;
end;
Result := Count;
end;
procedure TGLiteVector.Insert(aIndex: SizeInt; const aValue: T);
begin
if SizeUInt(aIndex) > SizeUInt(Count) then
raise ELGListError.CreateFmt(SEIndexOutOfBoundsFmt, [aIndex]);
InsertItem(aIndex, aValue)
end;
function TGLiteVector.TryInsert(aIndex: SizeInt; const aValue: T): Boolean;
begin
Result := SizeUInt(aIndex) <= SizeUInt(Count);
if Result then
InsertItem(aIndex, aValue);
end;
function TGLiteVector.InsertAll(aIndex: SizeInt; const a: array of T): SizeInt;
var
I: SizeInt;
begin
if SizeUInt(aIndex) > SizeUInt(Count) then
raise ELGListError.CreateFmt(SEIndexOutOfBoundsFmt, [aIndex]);
Result := System.Length(a);
if Result = 0 then exit;
FBuffer.EnsureCapacity(Count + Result);
if aIndex < Count then
begin
System.Move(FBuffer.FItems[aIndex], FBuffer.FItems[aIndex + Result], SizeOf(T)*(Count - aIndex));
if IsManagedType(T) then
System.FillChar(FBuffer.FItems[aIndex], SizeOf(T)*Result, 0);
end;
if IsManagedType(T) then
for I := 0 to Pred(Result) do
begin
FBuffer.FItems[aIndex] := a[I];
Inc(aIndex);
end
else
System.Move(a[0], FBuffer.FItems[aIndex], SizeOf(T)*Result);
Inc(FBuffer.FCount, Result);
end;
function TGLiteVector.InsertAll(aIndex: SizeInt; e: specialize IGEnumerable<T>): SizeInt;
begin
Result := InsertAll(aIndex, e.ToArray);
end;
function TGLiteVector.Extract(aIndex: SizeInt): T;
begin
if SizeUInt(aIndex) < SizeUInt(Count) then
Result := DeleteItem(aIndex)
else
raise ELGListError.CreateFmt(SEIndexOutOfBoundsFmt, [aIndex]);
end;
function TGLiteVector.TryExtract(aIndex: SizeInt; out aValue: T): Boolean;
begin
Result := SizeUInt(aIndex) < SizeUInt(Count);
if Result then
aValue := DeleteItem(aIndex);
end;
function TGLiteVector.ExtractAll(aIndex, aCount: SizeInt): TArray;
begin
if SizeUInt(aIndex) < SizeUInt(Count) then
Result := ExtractRange(aIndex, aCount)
else
raise ELGListError.CreateFmt(SEIndexOutOfBoundsFmt, [aIndex]);
end;
function TGLiteVector.ExtractIf(aTest: specialize TGTest<T>): TArray;
var
ToExtract: TArray;
I, J, Len: SizeInt;
p: PItem;
begin
if IsEmpty then exit(nil);
J := 0;
Len := 0;
p := Pointer(FBuffer.FItems);
System.SetLength(ToExtract, Count);
for I := 0 to Pred(Count) do begin
if aTest(p[I]) then begin
ToExtract[Len] := p[I];
Inc(Len);
continue;
end;
if I <> J then
p[J] := p[I];
Inc(J);
end;
if Count - J <> 0 then begin
if IsManagedType(T) then
for I := J to Pred(Count) do
p[I] := Default(T);
FBuffer.FCount := J;
end;
System.SetLength(ToExtract, Len);
Result := ToExtract;
end;
function TGLiteVector.ExtractIf(aTest: specialize TGOnTest<T>): TArray;
var
ToExtract: TArray;
I, J, Len: SizeInt;
p: PItem;
begin
if IsEmpty then exit(nil);
J := 0;
Len := 0;
p := Pointer(FBuffer.FItems);
System.SetLength(ToExtract, Count);
for I := 0 to Pred(Count) do begin
if aTest(p[I]) then begin
ToExtract[Len] := p[I];
Inc(Len);
continue;
end;
if I <> J then
p[J] := p[I];
Inc(J);
end;
if Count - J <> 0 then begin
if IsManagedType(T) then
for I := J to Pred(Count) do
p[I] := Default(T);
FBuffer.FCount := J;
end;
System.SetLength(ToExtract, Len);
Result := ToExtract;
end;
function TGLiteVector.ExtractIf(aTest: specialize TGNestTest<T>): TArray;
var
ToExtract: TArray;
I, J, Len: SizeInt;
p: PItem;
begin
if IsEmpty then exit(nil);
J := 0;
Len := 0;
p := Pointer(FBuffer.FItems);
System.SetLength(ToExtract, Count);
for I := 0 to Pred(Count) do begin
if aTest(p[I]) then begin
ToExtract[Len] := p[I];
Inc(Len);
continue;
end;
if I <> J then
p[J] := p[I];
Inc(J);
end;
if Count - J <> 0 then begin
if IsManagedType(T) then
for I := J to Pred(Count) do
p[I] := Default(T);
FBuffer.FCount := J;
end;
System.SetLength(ToExtract, Len);
Result := ToExtract;
end;
function TGLiteVector.DeleteLast: Boolean;
begin
if NonEmpty then
begin
DeleteItem(Pred(Count));
exit(True);
end;
Result := False;
end;
function TGLiteVector.DeleteLast(out aValue: T): Boolean;
begin
if NonEmpty then
begin
aValue := DeleteItem(Pred(Count));
exit(True);
end;
Result := False;
end;
function TGLiteVector.DeleteAll(aIndex, aCount: SizeInt): SizeInt;
begin
if SizeUInt(aIndex) < SizeUInt(Count) then
Result := DeleteRange(aIndex, aCount)
else
raise ELGListError.CreateFmt(SEIndexOutOfBoundsFmt, [aIndex]);
end;
function TGLiteVector.Filter(aTest: specialize TGTest<T>): SizeInt;
var
I, J: SizeInt;
p: PItem;
begin
if IsEmpty then exit(0);
J := 0;
p := Pointer(FBuffer.FItems);
for I := 0 to Pred(Count) do begin
if not aTest(p[I]) then continue;
if I <> J then
p[J] := p[I];
Inc(J);
end;
Result := Count - J;
if Result <> 0 then begin
if IsManagedType(T) then
for I := J to Pred(Count) do
p[I] := Default(T);
FBuffer.FCount := J;
end;
end;
function TGLiteVector.Filter(aTest: specialize TGOnTest<T>): SizeInt;
var
I, J: SizeInt;
p: PItem;
begin
if IsEmpty then exit(0);
J := 0;
p := Pointer(FBuffer.FItems);
for I := 0 to Pred(Count) do begin
if not aTest(p[I]) then continue;
if I <> J then
p[J] := p[I];
Inc(J);
end;
Result := Count - J;
if Result <> 0 then begin
if IsManagedType(T) then
for I := J to Pred(Count) do
p[I] := Default(T);
FBuffer.FCount := J;
end;
end;
function TGLiteVector.Filter(aTest: specialize TGNestTest<T>): SizeInt;
var
I, J: SizeInt;
p: PItem;
begin
if IsEmpty then exit(0);
J := 0;
p := Pointer(FBuffer.FItems);
for I := 0 to Pred(Count) do begin
if not aTest(p[I]) then continue;
if I <> J then
p[J] := p[I];
Inc(J);
end;
Result := Count - J;
if Result <> 0 then begin
if IsManagedType(T) then
for I := J to Pred(Count) do
p[I] := Default(T);
FBuffer.FCount := J;
end;
end;
procedure TGLiteVector.Swap(aIdx1, aIdx2: SizeInt);
var
Tmp: TFake;
begin
if SizeUInt(aIdx1) < SizeUInt(Count) then
if SizeUInt(aIdx2) < SizeUInt(Count) then
begin
Tmp := TFake(FBuffer.FItems[aIdx1]);
TFake(FBuffer.FItems[aIdx1]) := TFake(FBuffer.FItems[aIdx2]);
TFake(FBuffer.FItems[aIdx2]) := Tmp;
end
else
raise ELGListError.CreateFmt(SEIndexOutOfBoundsFmt, [aIdx2])
else
raise ELGListError.CreateFmt(SEIndexOutOfBoundsFmt, [aIdx1]);
end;
procedure TGLiteVector.UncSwap(aIdx1, aIdx2: SizeInt);
var
Tmp: TFake;
begin
Tmp := TFake(FBuffer.FItems[aIdx1]);
TFake(FBuffer.FItems[aIdx1]) := TFake(FBuffer.FItems[aIdx2]);
TFake(FBuffer.FItems[aIdx2]) := Tmp;
end;
{ TGLiteThreadVector }
procedure TGLiteThreadVector.DoLock;
begin
System.EnterCriticalSection(FLock);
end;
constructor TGLiteThreadVector.Create;
begin
System.InitCriticalSection(FLock);
end;
destructor TGLiteThreadVector.Destroy;
begin
DoLock;
try
Finalize(FVector);
inherited;
finally
UnLock;
System.DoneCriticalSection(FLock);
end;
end;
function TGLiteThreadVector.Lock: PVector;
begin
Result := @FVector;
DoLock;
end;
procedure TGLiteThreadVector.Unlock;
begin
System.LeaveCriticalSection(FLock);
end;
procedure TGLiteThreadVector.Clear;
begin
DoLock;
try
FVector.Clear;
finally
UnLock;
end;
end;
function TGLiteThreadVector.Add(const aValue: T): SizeInt;
begin
DoLock;
try
Result := FVector.Add(aValue);
finally
UnLock;
end;
end;
function TGLiteThreadVector.TryInsert(aIndex: SizeInt; const aValue: T): Boolean;
begin
DoLock;
try
Result := FVector.TryInsert(aIndex, aValue);
finally
UnLock;
end;
end;
function TGLiteThreadVector.TryDelete(aIndex: SizeInt; out aValue: T): Boolean;
begin
DoLock;
try
Result := FVector.TryExtract(aIndex, aValue);
finally
UnLock;
end;
end;
{ TGLiteObjectVector }
function TGLiteObjectVector.GetCount: SizeInt;
begin
Result := FVector.Count;
end;
function TGLiteObjectVector.GetCapacity: SizeInt;
begin
Result := FVector.Capacity;
end;
function TGLiteObjectVector.GetItem(aIndex: SizeInt): T;
begin
Result := FVector.GetItem(aIndex);
end;
function TGLiteObjectVector.GetUncMutable(aIndex: SizeInt): PItem;
begin
Result := FVector.GetUncMutable(aIndex);
end;
procedure TGLiteObjectVector.SetItem(aIndex: SizeInt; const aValue: T);
var
p: PItem;
begin
p := FVector.GetMutable(aIndex);
if p^ <> aValue then
begin
if OwnsObjects then
p^.Free;
p^ := aValue;
end;
end;
procedure TGLiteObjectVector.CheckFreeItems;
var
I: SizeInt;
LocItems: PItem;
begin
if OwnsObjects then
begin
LocItems := PItem(FVector.FBuffer.FItems);
for I := 0 to Pred(Count) do
LocItems[I].Free;
end;
end;
class operator TGLiteObjectVector.Initialize(var v: TGLiteObjectVector);
begin
v.OwnsObjects := True;
end;
class operator TGLiteObjectVector.Copy(constref aSrc: TGLiteObjectVector; var aDst: TGLiteObjectVector);
begin
if @aDst = @aSrc then
exit;
aDst.CheckFreeItems;
aDst.FVector := aSrc.FVector;
aDst.FOwnsObjects := aSrc.OwnsObjects;
end;
function TGLiteObjectVector.InnerVector: PVector;
begin
Result := @FVector;
end;
function TGLiteObjectVector.GetEnumerator: TEnumerator;
begin
Result := FVector.GetEnumerator;
end;
function TGLiteObjectVector.GetReverseEnumerator: TReverseEnumerator;
begin
Result := FVector.GetReverseEnumerator;
end;
function TGLiteObjectVector.Reverse: TReverse;
begin
Result := FVector.Reverse;
end;
function TGLiteObjectVector.ToArray: TArray;
begin
Result := FVector.ToArray;
end;
procedure TGLiteObjectVector.Clear;
begin
CheckFreeItems;
FVector.Clear;
end;
function TGLiteObjectVector.IsEmpty: Boolean;
begin
Result := FVector.IsEmpty;
end;
function TGLiteObjectVector.NonEmpty: Boolean;
begin
Result := FVector.NonEmpty;
end;
procedure TGLiteObjectVector.EnsureCapacity(aValue: SizeInt);
begin
FVector.EnsureCapacity(aValue)
end;
procedure TGLiteObjectVector.TrimToFit;
begin
FVector.TrimToFit;
end;
function TGLiteObjectVector.Add(const aValue: T): SizeInt;
begin
Result := FVector.Add(aValue);
end;
function TGLiteObjectVector.AddAll(const a: array of T): SizeInt;
begin
Result := FVector.AddAll(a);
end;
function TGLiteObjectVector.AddAll(constref aVector: TGLiteObjectVector): SizeInt;
begin
Result := FVector.AddAll(aVector.FVector);
end;
procedure TGLiteObjectVector.Insert(aIndex: SizeInt; const aValue: T);
begin
FVector.Insert(aIndex, aValue);
end;
function TGLiteObjectVector.TryInsert(aIndex: SizeInt; const aValue: T): Boolean;
begin
Result := FVector.TryInsert(aIndex, aValue);
end;
function TGLiteObjectVector.InsertAll(aIndex: SizeInt; const a: array of T): SizeInt;
begin
Result := FVector.InsertAll(aIndex, a);
end;
function TGLiteObjectVector.InsertAll(aIndex: SizeInt; e: specialize IGEnumerable<T>): SizeInt;
begin
Result := FVector.InsertAll(aIndex, e);
end;
function TGLiteObjectVector.Extract(aIndex: SizeInt): T;
begin
Result := FVector.Extract(aIndex);
end;
function TGLiteObjectVector.TryExtract(aIndex: SizeInt; out aValue: T): Boolean;
begin
Result := FVector.TryExtract(aIndex, aValue);
end;
function TGLiteObjectVector.ExtractAll(aIndex, aCount: SizeInt): TArray;
begin
Result := FVector.ExtractAll(aIndex, aCount);
end;
function TGLiteObjectVector.ExtractIf(aTest: specialize TGTest<T>): TArray;
begin
Result := FVector.ExtractIf(aTest);
end;
function TGLiteObjectVector.ExtractIf(aTest: specialize TGOnTest<T>): TArray;
begin
Result := FVector.ExtractIf(aTest);
end;
function TGLiteObjectVector.ExtractIf(aTest: specialize TGNestTest<T>): TArray;
begin
Result := FVector.ExtractIf(aTest);
end;
procedure TGLiteObjectVector.Delete(aIndex: SizeInt);
var
v: T;
begin
v := FVector.Extract(aIndex);
if OwnsObjects then
v.Free;
end;
function TGLiteObjectVector.TryDelete(aIndex: SizeInt): Boolean;
var
v: T;
begin
Result := FVector.TryExtract(aIndex, v);
if Result and OwnsObjects then
v.Free;
end;
function TGLiteObjectVector.DeleteLast: Boolean;
var
v: T;
begin
Result := FVector.DeleteLast(v);
if Result and OwnsObjects then
v.Free;
end;
function TGLiteObjectVector.DeleteLast(out aValue: T): Boolean;
begin
Result := FVector.DeleteLast(aValue);
end;
function TGLiteObjectVector.DeleteAll(aIndex, aCount: SizeInt): SizeInt;
var
a: TArray;
v: T;
begin
if OwnsObjects then
begin
a := FVector.ExtractAll(aIndex, aCount);
Result := System.Length(a);
for v in a do
v.Free;
end
else
Result := FVector.DeleteAll(aIndex, aCount);
end;
function TGLiteObjectVector.Filter(aTest: specialize TGTest<T>): SizeInt;
var
I, J: SizeInt;
p: PItem;
begin
if IsEmpty then exit(0);
J := 0;
p := Pointer(FVector.FBuffer.FItems);
for I := 0 to Pred(Count) do begin
if not aTest(p[I]) then begin
if OwnsObjects then p[I].Free;
continue;
end;
if I <> J then
p[J] := p[I];
Inc(J);
end;
Result := Count - J;
FVector.FBuffer.FCount := J;
end;
function TGLiteObjectVector.Filter(aTest: specialize TGOnTest<T>): SizeInt;
var
I, J: SizeInt;
p: PItem;
begin
if IsEmpty then exit(0);
J := 0;
p := Pointer(FVector.FBuffer.FItems);
for I := 0 to Pred(Count) do begin
if not aTest(p[I]) then begin
if OwnsObjects then p[I].Free;
continue;
end;
if I <> J then
p[J] := p[I];
Inc(J);
end;
Result := Count - J;
FVector.FBuffer.FCount := J;
end;
function TGLiteObjectVector.Filter(aTest: specialize TGNestTest<T>): SizeInt;
var
I, J: SizeInt;
p: PItem;
begin
if IsEmpty then exit(0);
J := 0;
p := Pointer(FVector.FBuffer.FItems);
for I := 0 to Pred(Count) do begin
if not aTest(p[I]) then begin
if OwnsObjects then p[I].Free;
continue;
end;
if I <> J then
p[J] := p[I];
Inc(J);
end;
Result := Count - J;
FVector.FBuffer.FCount := J;
end;
{ TGLiteThreadObjectVector }
procedure TGLiteThreadObjectVector.DoLock;
begin
System.EnterCriticalSection(FLock);
end;
constructor TGLiteThreadObjectVector.Create;
begin
System.InitCriticalSection(FLock);
end;
destructor TGLiteThreadObjectVector.Destroy;
begin
DoLock;
try
Finalize(FVector);
inherited;
finally
UnLock;
System.DoneCriticalSection(FLock);
end;
end;
function TGLiteThreadObjectVector.Lock: PVector;
begin
Result := @FVector;
DoLock;
end;
procedure TGLiteThreadObjectVector.Unlock;
begin
System.LeaveCriticalSection(FLock);
end;
procedure TGLiteThreadObjectVector.Clear;
begin
DoLock;
try
FVector.Clear;
finally
UnLock;
end;
end;
function TGLiteThreadObjectVector.Add(const aValue: T): SizeInt;
begin
DoLock;
try
Result := FVector.Add(aValue);
finally
UnLock;
end;
end;
function TGLiteThreadObjectVector.TryInsert(aIndex: SizeInt; const aValue: T): Boolean;
begin
DoLock;
try
Result := FVector.TryInsert(aIndex, aValue);
finally
UnLock;
end;
end;
function TGLiteThreadObjectVector.TryExtract(aIndex: SizeInt; out aValue: T): Boolean;
begin
DoLock;
try
Result := FVector.TryExtract(aIndex, aValue);
finally
UnLock;
end;
end;
function TGLiteThreadObjectVector.TryDelete(aIndex: SizeInt): Boolean;
begin
DoLock;
try
Result := FVector.TryDelete(aIndex);
finally
UnLock;
end;
end;
{ TBoolVector.TEnumerator }
function TBoolVector.TEnumerator.GetCurrent: SizeInt;
begin
Result := FLimbIndex shl INT_SIZE_LOG + FBitIndex;
end;
function TBoolVector.TEnumerator.FindFirst: Boolean;
var
I: SizeInt;
begin
for I := 0 to Pred(System.Length(FBits)) do
if FBits[I] <> 0 then
begin
FBitIndex := BsfSizeUInt(FBits[I]);
FLimbIndex := I;
FCurrLimb := FBits[I] and not(SizeUInt(1) shl FBitIndex);
exit(True);
end;
Result := False;
end;
procedure TBoolVector.TEnumerator.Init(const aBits: TBits);
begin
FBits := aBits;
FLimbIndex := NULL_INDEX;
FBitIndex := NULL_INDEX;
end;
function TBoolVector.TEnumerator.MoveNext: Boolean;
begin
if FLimbIndex <> NULL_INDEX then
begin
Result := False;
repeat
if FCurrLimb <> 0 then
begin
FBitIndex := BsfSizeUInt(FCurrLimb);
FCurrLimb := FCurrLimb and not(SizeUInt(1) shl FBitIndex);
exit(True);
end
else
begin
if FLimbIndex = System.High(FBits) then
exit;
Inc(FLimbIndex);
FCurrLimb := FBits[FLimbIndex];
end;
until False;
end
else
Result := FindFirst;
end;
{ TBoolVector.TReverseEnumerator }
function TBoolVector.TReverseEnumerator.GetCurrent: SizeInt;
begin
Result := FLimbIndex shl INT_SIZE_LOG + FBitIndex;
end;
function TBoolVector.TReverseEnumerator.FindLast: Boolean;
var
I: SizeInt;
begin
for I := Pred(System.Length(FBits)) downto 0 do
if FBits[I] <> 0 then
begin
FBitIndex := BsrSizeUInt(FBits[I]);
FLimbIndex := I;
FCurrLimb := FBits[I] and not(SizeUInt(1) shl FBitIndex);
exit(True);
end;
Result := False;
end;
procedure TBoolVector.TReverseEnumerator.Init(const aBits: TBits);
begin
FBits := aBits;
FLimbIndex := NULL_INDEX;
FBitIndex := NULL_INDEX;
end;
function TBoolVector.TReverseEnumerator.MoveNext: Boolean;
begin
if FLimbIndex <> NULL_INDEX then
begin
Result := False;
repeat
if FCurrLimb <> 0 then
begin
FBitIndex := BsrSizeUInt(FCurrLimb);
FCurrLimb := FCurrLimb and not(SizeUInt(1) shl FBitIndex);
exit(True);
end
else
begin
if FLimbIndex = 0 then
exit;
Dec(FLimbIndex);
FCurrLimb := FBits[FLimbIndex];
end;
until False;
end
else
Result := FindLast;
end;
{ TBoolVector.TReverse }
function TBoolVector.TReverse.GetEnumerator: TReverseEnumerator;
begin
Result.Init(FBits);
end;
{ TBoolVector }
function TBoolVector.GetCapacity: SizeInt;
begin
Result := System.Length(FBits) shl INT_SIZE_LOG;
end;
function TBoolVector.GetBit(aIndex: SizeInt): Boolean;
begin
if SizeUInt(aIndex) < SizeUInt(System.Length(FBits) shl INT_SIZE_LOG) then
Result := FBits[aIndex shr INT_SIZE_LOG] and (SizeUInt(1) shl (aIndex and INT_SIZE_MASK)) <> 0
else
raise ELGListError.CreateFmt(SEIndexOutOfBoundsFmt, [aIndex]);
end;
function TBoolVector.GetBitUncheck(aIndex: SizeInt): Boolean;
begin
Result := FBits[aIndex shr INT_SIZE_LOG] and (SizeUInt(1) shl (aIndex and INT_SIZE_MASK)) <> 0;
end;
procedure TBoolVector.SetCapacity(aValue: SizeInt);
begin
if aValue < 0 then
aValue := 0;
if aValue <> Capacity then
begin
aValue := aValue shr INT_SIZE_LOG + Ord(aValue and INT_SIZE_MASK <> 0);
if aValue <= MAX_CONTAINER_SIZE div SizeOf(SizeUInt) then
System.SetLength(FBits, aValue)
else
raise ELGCapacityExceed.CreateFmt(SECapacityExceedFmt, [aValue]);
end;
end;
procedure TBoolVector.SetBit(aIndex: SizeInt; aValue: Boolean);
begin
if SizeUInt(aIndex) < SizeUInt(System.Length(FBits) shl INT_SIZE_LOG) then
if aValue then
FBits[aIndex shr INT_SIZE_LOG] := FBits[aIndex shr INT_SIZE_LOG] or
SizeUInt(1) shl (aIndex and INT_SIZE_MASK)
else
FBits[aIndex shr INT_SIZE_LOG] := FBits[aIndex shr INT_SIZE_LOG] and
not(SizeUInt(1) shl (aIndex and INT_SIZE_MASK))
else
raise ELGListError.CreateFmt(SEIndexOutOfBoundsFmt, [aIndex]);
end;
procedure TBoolVector.SetBitUncheck(aIndex: SizeInt; aValue: Boolean);
begin
if aValue then
FBits[aIndex shr INT_SIZE_LOG] := FBits[aIndex shr INT_SIZE_LOG] or
SizeUInt(1) shl (aIndex and INT_SIZE_MASK)
else
FBits[aIndex shr INT_SIZE_LOG] := FBits[aIndex shr INT_SIZE_LOG] and
not(SizeUInt(1) shl (aIndex and INT_SIZE_MASK));
end;
function TBoolVector.SignLimbCount: SizeInt;
var
I: SizeInt;
begin
for I := System.High(FBits) downto 0 do
if FBits[I] <> 0 then
exit(Succ(I));
Result := 0;
end;
class operator TBoolVector.Copy(constref aSrc: TBoolVector; var aDst: TBoolVector);
begin
aDst.FBits := System.Copy(aSrc.FBits);
end;
class operator TBoolVector.AddRef(var bv: TBoolVector);
begin
bv.FBits := System.Copy(bv.FBits);
end;
procedure TBoolVector.InitRange(aRange: SizeInt);
var
msb: SizeInt;
begin
//FBits := nil;
if aRange > 0 then
begin
msb := aRange and INT_SIZE_MASK;
aRange := aRange shr INT_SIZE_LOG + Ord(msb <> 0);
if aRange <> System.Length(FBits) then
System.SetLength(FBits, aRange);
System.FillChar(Pointer(FBits)^, aRange * SizeOf(SizeUInt), $ff);
if msb <> 0 then
FBits[Pred(aRange)] := FBits[Pred(aRange)] shr (BitsizeOf(SizeUint) - msb);
end;
end;
function TBoolVector.GetEnumerator: TEnumerator;
begin
Result.Init(FBits);
end;
function TBoolVector.Reverse: TReverse;
begin
Result.FBits := FBits;
end;
function TBoolVector.ToArray: TIntArray;
var
I, Pos: SizeInt;
begin
Result := nil;
System.SetLength(Result, PopCount);
Pos := 0;
for I in Self do
begin
Result[Pos] := I;
Inc(Pos);
end;
end;
procedure TBoolVector.EnsureCapacity(aValue: SizeInt);
begin
if Capacity < aValue then
SetCapacity(aValue);
end;
procedure TBoolVector.TrimToFit;
var
slCount: SizeInt;
begin
slCount := SignLimbCount;
if slCount <> System.Length(FBits) then
System.SetLength(FBits, slCount);
end;
procedure TBoolVector.Clear;
begin
FBits := nil;
end;
procedure TBoolVector.ClearBits;
begin
System.FillChar(Pointer(FBits)^, System.Length(FBits) * SizeOf(SizeUInt), 0);
end;
procedure TBoolVector.SetBits;
begin
System.FillChar(Pointer(FBits)^, System.Length(FBits) * SizeOf(SizeUInt), $ff);
end;
procedure TBoolVector.ToggleBits;
var
I: SizeInt;
begin
for I := 0 to Pred(Length(FBits)) do
FBits[I] := not FBits[I];
end;
function TBoolVector.IsEmpty: Boolean;
var
I: SizeInt;
begin
for I := 0 to System.High(FBits) do
if FBits[I] <> 0 then
exit(False);
Result := True;
end;
function TBoolVector.NonEmpty: Boolean;
begin
Result := not IsEmpty;
end;
procedure TBoolVector.SwapBits(var aVector: TBoolVector);
var
tmp: Pointer;
begin
tmp := Pointer(FBits);
Pointer(FBits) := Pointer(aVector.FBits);
Pointer(aVector.FBits) := tmp;
end;
procedure TBoolVector.CopyBits(const aVector: TBoolVector; aCount: SizeInt);
var
I, J: SizeInt;
const
MASK = System.High(SizeUInt);
BIT_SIZE = BitSizeOf(SizeUInt);
begin
if aCount > aVector.Capacity then aCount := aVector.Capacity; //todo: exception ???
if (aCount < 1) or (Pointer(FBits) = Pointer(aVector.FBits)) then exit;
EnsureCapacity(aCount);
J := aCount shr INT_SIZE_LOG;
for I := 0 to Pred(J) do
FBits[I] := aVector.FBits[I];
I := aCount and INT_SIZE_MASK;
if I <> 0 then
FBits[J] := FBits[J] and (MASK shl I) or aVector.FBits[J] and (MASK shr (BIT_SIZE - I));
end;
function TBoolVector.All: Boolean;
var
I: SizeUInt;
begin
for I in FBits do
if I <> High(SizeUInt) then
exit(False);
Result := True;
end;
function TBoolVector.Bsf: SizeInt;
var
I: SizeInt;
begin
for I := 0 to System.High(FBits) do
if FBits[I] <> 0 then
exit(I shl INT_SIZE_LOG + BsfSizeUInt(FBits[I]));
Result := NULL_INDEX;
end;
function TBoolVector.NextSetBit(aFromIdx: SizeInt): SizeInt;
var
LimbIdx, BitIdx, I: SizeInt;
Limb: SizeUInt;
begin
if SizeUInt(aFromIdx) >= SizeUInt(Capacity) then exit(NULL_INDEX);
LimbIdx := aFromIdx shr INT_SIZE_LOG;
BitIdx := aFromIdx and INT_SIZE_MASK;
Limb := FBits[LimbIdx] and not(High(SizeUInt) shr (BitSizeOf(SizeUInt) - Succ(BitIdx)));
if Limb <> 0 then
exit(LimbIdx shl INT_SIZE_LOG + BsfSizeUInt(Limb))
else
for I := LimbIdx + 1 to System.High(FBits) do
if FBits[I] <> 0 then
exit(I shl INT_SIZE_LOG + BsfSizeUInt(FBits[I]));
Result := NULL_INDEX;
end;
function TBoolVector.PrevSetBit(aFromIdx: SizeInt): SizeInt;
var
LimbIdx, BitIdx, I: SizeInt;
Limb: SizeUInt;
begin
if SizeUInt(aFromIdx) >= SizeUInt(Capacity) then exit(NULL_INDEX);
LimbIdx := aFromIdx shr INT_SIZE_LOG;
BitIdx := aFromIdx and INT_SIZE_MASK;
Limb := FBits[LimbIdx] and not(High(SizeUInt) shl BitIdx);
if Limb <> 0 then
exit(LimbIdx shl INT_SIZE_LOG + BsrSizeUInt(Limb))
else
for I := LimbIdx - 1 downto 0 do
if FBits[I] <> 0 then
exit(I shl INT_SIZE_LOG + BsrSizeUInt(FBits[I]));
Result := NULL_INDEX;
end;
function TBoolVector.Bsr: SizeInt;
var
I: SizeInt;
begin
for I := System.High(FBits) downto 0 do
if FBits[I] <> 0 then
exit(I shl INT_SIZE_LOG + BsrSizeUInt(FBits[I]));
Result := NULL_INDEX;
end;
function TBoolVector.Lob: SizeInt;
var
I: SizeInt;
begin
for I := 0 to System.High(FBits) do
if FBits[I] <> High(SizeUInt) then
exit(I shl INT_SIZE_LOG + BsfSizeUInt(not FBits[I]));
Result := NULL_INDEX;
end;
function TBoolVector.Hob: SizeInt;
var
I: SizeInt;
begin
for I := System.High(FBits) downto 0 do
if FBits[I] <> High(SizeUInt) then
exit(I shl INT_SIZE_LOG + BsrSizeUInt(not FBits[I]));
Result := NULL_INDEX;
end;
function TBoolVector.NextOpenBit(aFromIdx: SizeInt): SizeInt;
var
LimbIdx, BitIdx, I: SizeInt;
Limb: SizeUInt;
begin
if SizeUInt(aFromIdx) >= SizeUInt(Capacity) then exit(NULL_INDEX);
LimbIdx := aFromIdx shr INT_SIZE_LOG;
BitIdx := aFromIdx and INT_SIZE_MASK;
Limb := not(FBits[LimbIdx] or High(SizeUInt) shr (BitSizeOf(SizeUInt) - Succ(BitIdx)));
if Limb <> 0 then
exit(LimbIdx shl INT_SIZE_LOG + BsfSizeUInt(Limb))
else
for I := LimbIdx + 1 to System.High(FBits) do
if FBits[I] <> High(SizeUInt) then
exit(I shl INT_SIZE_LOG + BsfSizeUInt(not FBits[I]));
Result := NULL_INDEX;
end;
function TBoolVector.PrevOpenBit(aFromIdx: SizeInt): SizeInt;
var
LimbIdx, BitIdx, I: SizeInt;
Limb: SizeUInt;
begin
if SizeUInt(aFromIdx) >= SizeUInt(Capacity) then exit(NULL_INDEX);
LimbIdx := aFromIdx shr INT_SIZE_LOG;
BitIdx := aFromIdx and INT_SIZE_MASK;
Limb := not(FBits[LimbIdx] or High(SizeUInt) shl BitIdx);
if Limb <> 0 then
exit(LimbIdx shl INT_SIZE_LOG + BsrSizeUInt(Limb))
else
for I := LimbIdx - 1 downto 0 do
if FBits[I] <> High(SizeUInt) then
exit(I shl INT_SIZE_LOG + BsrSizeUInt(not FBits[I]));
Result := NULL_INDEX;
end;
function TBoolVector.ToggleBit(aIndex: SizeInt): Boolean;
begin
if SizeUInt(aIndex) < SizeUInt(System.Length(FBits) shl INT_SIZE_LOG) then
begin
Result := (FBits[aIndex shr INT_SIZE_LOG] and (SizeUInt(1) shl (aIndex and INT_SIZE_MASK))) <> 0;
FBits[aIndex shr INT_SIZE_LOG] :=
FBits[aIndex shr INT_SIZE_LOG] xor (SizeUInt(1) shl (aIndex and INT_SIZE_MASK));
end
else
raise ELGListError.CreateFmt(SEIndexOutOfBoundsFmt, [aIndex]);
end;
function TBoolVector.UncToggleBit(aIndex: SizeInt): Boolean;
begin
Result := (FBits[aIndex shr INT_SIZE_LOG] and (SizeUInt(1) shl (aIndex and INT_SIZE_MASK))) <> 0;
FBits[aIndex shr INT_SIZE_LOG] :=
FBits[aIndex shr INT_SIZE_LOG] xor (SizeUInt(1) shl (aIndex and INT_SIZE_MASK));
end;
function TBoolVector.Intersecting(constref aValue: TBoolVector): Boolean;
var
I: SizeInt;
begin
if @Self = @aValue then
exit(NonEmpty);
for I := 0 to Math.Min(System.High(FBits), System.High(aValue.FBits)) do
if FBits[I] and aValue.FBits[I] <> 0 then
exit(True);
Result := False;
end;
function TBoolVector.IntersectionPop(constref aValue: TBoolVector): SizeInt;
var
I, Len: SizeInt;
begin
if @Self = @aValue then
exit(PopCount);
Len := Math.Min(System.Length(FBits), System.Length(aValue.FBits));
I := 0;
Result := 0;
while I <= Len - 4 do
begin
Result += LgUtils.PopCntSui(FBits[I ] and aValue.FBits[I ]) +
LgUtils.PopCntSui(FBits[I+1] and aValue.FBits[I+1]) +
LgUtils.PopCntSui(FBits[I+2] and aValue.FBits[I+2]) +
LgUtils.PopCntSui(FBits[I+3] and aValue.FBits[I+3]);
Inc(I, 4);
end;
case Len - I of
1:
Result += LgUtils.PopCntSui(FBits[I] and aValue.FBits[I]);
2:
Result += LgUtils.PopCntSui(FBits[I ] and aValue.FBits[I ]) +
LgUtils.PopCntSui(FBits[I+1] and aValue.FBits[I+1]);
3:
Result += LgUtils.PopCntSui(FBits[I ] and aValue.FBits[I ]) +
LgUtils.PopCntSui(FBits[I+1] and aValue.FBits[I+1]) +
LgUtils.PopCntSui(FBits[I+2] and aValue.FBits[I+2]);
else
end;
end;
function TBoolVector.Contains(constref aValue: TBoolVector): Boolean;
var
I: SizeInt;
begin
if @Self = @aValue then
exit(True);
for I := 0 to Math.Min(System.High(FBits), System.High(aValue.FBits)) do
if FBits[I] or aValue.FBits[I] <> FBits[I] then
exit(False);
for I := System.Length(FBits) to System.High(aValue.FBits) do
if aValue.FBits[I] <> 0 then
exit(False);
Result := True;
end;
function TBoolVector.JoinGain(constref aValue: TBoolVector): SizeInt;
var
I, Len: SizeInt;
begin
if @Self = @aValue then
exit(0);
Len := Math.Min(System.Length(FBits), System.Length(aValue.FBits));
I := 0;
Result := 0;
while I <= Len - 4 do
begin
Result += LgUtils.PopCntSui(not FBits[I ] and aValue.FBits[I ]) +
LgUtils.PopCntSui(not FBits[I+1] and aValue.FBits[I+1]) +
LgUtils.PopCntSui(not FBits[I+2] and aValue.FBits[I+2]) +
LgUtils.PopCntSui(not FBits[I+3] and aValue.FBits[I+3]);
Inc(I, 4);
end;
case Len - I of
1:
begin
Result += LgUtils.PopCntSui(not FBits[I] and aValue.FBits[I]);
I += 1;
end;
2:
begin
Result += LgUtils.PopCntSui(not FBits[I ] and aValue.FBits[I ]) +
LgUtils.PopCntSui(not FBits[I+1] and aValue.FBits[I+1]);
I += 2;
end;
3:
begin
Result += LgUtils.PopCntSui(not FBits[I ] and aValue.FBits[I ]) +
LgUtils.PopCntSui(not FBits[I+1] and aValue.FBits[I+1]) +
LgUtils.PopCntSui(not FBits[I+2] and aValue.FBits[I+2]);
I += 3;
end;
else
end;
for I := I to System.High(aValue.FBits) do
Result += LgUtils.PopCntSui(aValue.FBits[I]);
end;
procedure TBoolVector.Join(constref aValue: TBoolVector);
var
I, Len: SizeInt;
begin
if @Self = @aValue then
exit;
Len := aValue.SignLimbCount;
if Len > System.Length(FBits) then
System.SetLength(FBits, Len);;
I := 0;
while I <= Len - 4 do
begin
FBits[I ] := FBits[I ] or aValue.FBits[I ];
FBits[I+1] := FBits[I+1] or aValue.FBits[I+1];
FBits[I+2] := FBits[I+2] or aValue.FBits[I+2];
FBits[I+3] := FBits[I+3] or aValue.FBits[I+3];
Inc(I, 4);
end;
case Len - I of
1:
FBits[I ] := FBits[I ] or aValue.FBits[I];
2:
begin
FBits[I ] := FBits[I ] or aValue.FBits[I ];
FBits[I+1] := FBits[I+1] or aValue.FBits[I+1];
end;
3:
begin
FBits[I ] := FBits[I ] or aValue.FBits[I ];
FBits[I+1] := FBits[I+1] or aValue.FBits[I+1];
FBits[I+2] := FBits[I+2] or aValue.FBits[I+2];
end;
else
end;
end;
function TBoolVector.Union(constref aValue: TBoolVector): TBoolVector;
begin
Result := Self;
Result.Join(aValue);
end;
procedure TBoolVector.Subtract(constref aValue: TBoolVector);
var
I, Len: SizeInt;
begin
if @Self = @aValue then
begin
ClearBits;
exit;
end;
Len := Math.Min(System.Length(FBits), System.Length(aValue.FBits));
I := 0;
while I <= Len - 4 do
begin
FBits[I ] := FBits[I ] and not aValue.FBits[I ];
FBits[I+1] := FBits[I+1] and not aValue.FBits[I+1];
FBits[I+2] := FBits[I+2] and not aValue.FBits[I+2];
FBits[I+3] := FBits[I+3] and not aValue.FBits[I+3];
Inc(I, 4);
end;
case Len - I of
1:
FBits[I ] := FBits[I ] and not aValue.FBits[I];
2:
begin
FBits[I ] := FBits[I ] and not aValue.FBits[I ];
FBits[I+1] := FBits[I+1] and not aValue.FBits[I+1];
end;
3:
begin
FBits[I ] := FBits[I ] and not aValue.FBits[I ];
FBits[I+1] := FBits[I+1] and not aValue.FBits[I+1];
FBits[I+2] := FBits[I+2] and not aValue.FBits[I+2];
end;
else
end;
end;
function TBoolVector.Difference(constref aValue: TBoolVector): TBoolVector;
begin
Result := Self;
Result.Subtract(aValue);
end;
procedure TBoolVector.Intersect(constref aValue: TBoolVector);
var
I, Len: SizeInt;
begin
if @Self = @aValue then
exit;
Len := Math.Min(System.Length(FBits), System.Length(aValue.FBits));
I := 0;
while I <= Len - 4 do
begin
FBits[I ] := FBits[I ] and aValue.FBits[I ];
FBits[I+1] := FBits[I+1] and aValue.FBits[I+1];
FBits[I+2] := FBits[I+2] and aValue.FBits[I+2];
FBits[I+3] := FBits[I+3] and aValue.FBits[I+3];
Inc(I, 4);
end;
case Len - I of
1:
FBits[I ] := FBits[I ] and aValue.FBits[I];
2:
begin
FBits[I ] := FBits[I ] and aValue.FBits[I ];
FBits[I+1] := FBits[I+1] and aValue.FBits[I+1];
end;
3:
begin
FBits[I ] := FBits[I ] and aValue.FBits[I ];
FBits[I+1] := FBits[I+1] and aValue.FBits[I+1];
FBits[I+2] := FBits[I+2] and aValue.FBits[I+2];
end;
else
end;
for I := Len to System.High(FBits) do
FBits[I] := 0;
end;
function TBoolVector.Intersection(constref aValue: TBoolVector): TBoolVector;
begin
Result := Self;
Result.Intersect(aValue);
end;
procedure TBoolVector.DisjunctJoin(constref aValue: TBoolVector);
var
I, MinLen: SizeInt;
begin
if @Self = @aValue then
begin
ClearBits;
exit;
end;
MinLen := Math.Min(System.Length(FBits), System.Length(aValue.FBits));
if System.Length(FBits) < System.Length(aValue.FBits) then
System.SetLength(FBits, System.Length(aValue.FBits));
for I := 0 to Pred(MinLen) do
FBits[I] := FBits[I] xor aValue.FBits[I];
for I := MinLen to Pred(System.Length(aValue.FBits)) do
FBits[I] := aValue.FBits[I];
end;
function TBoolVector.SymmDifference(constref aValue: TBoolVector): TBoolVector;
begin
if System.Length(FBits) >= System.Length(aValue.FBits) then
begin
Result := Self;
Result.DisjunctJoin(aValue);
end
else
begin
Result := aValue;
Result.DisjunctJoin(Self);
end;
end;
function TBoolVector.Equals(constref aValue: TBoolVector): Boolean;
var
I: SizeInt;
begin
if @Self = @aValue then
exit(True);
if System.Length(FBits) <> System.Length(aValue.FBits) then
exit(False);
for I := 0 to Pred(System.Length(FBits)) do
if FBits[I] <> aValue.FBits[I] then
exit(False);
Result := True;
end;
function TBoolVector.PopCount: SizeInt;
var
I: SizeInt;
begin
I := 0;
Result := 0;
while I <= System.Length(FBits) - 4 do
begin
Result += LgUtils.PopCntSui(FBits[I ]) + LgUtils.PopCntSui(FBits[I+1]) +
LgUtils.PopCntSui(FBits[I+2]) + LgUtils.PopCntSui(FBits[I+3]);
Inc(I, 4);
end;
case System.Length(FBits) - I of
1:
Result += LgUtils.PopCntSui(FBits[I]);
2:
Result += LgUtils.PopCntSui(FBits[I]) + LgUtils.PopCntSui(FBits[I+1]);
3:
Result += LgUtils.PopCntSui(FBits[I]) + LgUtils.PopCntSui(FBits[I+1]) +
LgUtils.PopCntSui(FBits[I+2]);
else
end;
end;
{ TGVectorHelpUtil }
class procedure TGVectorHelpUtil.SwapItems(v: TVector; L, R: SizeInt);
begin
v.CheckInIteration;
THelper.SwapItems(v.FItems[0..Pred(v.ElemCount)], L, R);
end;
class procedure TGVectorHelpUtil.SwapItems(var v: TLiteVector; L, R: SizeInt);
begin
THelper.SwapItems(v.FBuffer.FItems[0..Pred(v.Count)], L, R);
end;
class procedure TGVectorHelpUtil.Reverse(v: TVector);
begin
v.CheckInIteration;
if v.ElemCount > 1 then
THelper.Reverse(v.FItems[0..Pred(v.ElemCount)]);
end;
class procedure TGVectorHelpUtil.Reverse(var v: TLiteVector);
begin
if v.Count > 1 then
THelper.Reverse(v.FBuffer.FItems[0..Pred(v.Count)]);
end;
class procedure TGVectorHelpUtil.RandomShuffle(v: TVector);
begin
v.CheckInIteration;
if v.ElemCount > 1 then
THelper.RandomShuffle(v.FItems[0..Pred(v.ElemCount)]);
end;
class procedure TGVectorHelpUtil.RandomShuffle(var v: TLiteVector);
begin
if v.Count > 1 then
THelper.RandomShuffle(v.FBuffer.FItems[0..Pred(v.Count)]);
end;
class function TGVectorHelpUtil.SequentSearch(v: TVector; const aValue: T; c: TEqualityCompare): SizeInt;
begin
if v.ElemCount > 0 then
Result := THelper.SequentSearch(v.FItems[0..Pred(v.ElemCount)], aValue, c)
else
Result := -1;
end;
class function TGVectorHelpUtil.SequentSearch(constref v: TLiteVector; const aValue: T;
c: TEqualityCompare): SizeInt;
begin
if v.Count > 0 then
Result := THelper.SequentSearch(v.FBuffer.FItems[0..Pred(v.Count)], aValue, c)
else
Result := -1;
end;
{ TGBaseVectorHelper }
class function TGBaseVectorHelper.SequentSearch(v: TVector; const aValue: T): SizeInt;
begin
if v.ElemCount > 0 then
Result := THelper.SequentSearch(v.FItems[0..Pred(v.ElemCount)], aValue)
else
Result := -1;
end;
class function TGBaseVectorHelper.SequentSearch(constref v: TLiteVector; const aValue: T): SizeInt;
begin
if v.Count > 0 then
Result := THelper.SequentSearch(v.FBuffer.FItems[0..Pred(v.Count)], aValue)
else
Result := -1;
end;
class function TGBaseVectorHelper.BinarySearch(v: TVector; const aValue: T): SizeInt;
begin
if v.ElemCount > 0 then
Result := THelper.BinarySearch(v.FItems[0..Pred(v.ElemCount)], aValue)
else
Result := -1;
end;
class function TGBaseVectorHelper.BinarySearch(constref v: TLiteVector; const aValue: T): SizeInt;
begin
if v.Count > 0 then
Result := THelper.BinarySearch(v.FBuffer.FItems[0..Pred(v.Count)], aValue)
else
Result := -1;
end;
class function TGBaseVectorHelper.IndexOfMin(v: TVector): SizeInt;
begin
if v.ElemCount > 0 then
Result := THelper.IndexOfMin(v.FItems[0..Pred(v.ElemCount)])
else
Result := -1;
end;
class function TGBaseVectorHelper.IndexOfMin(constref v: TLiteVector): SizeInt;
begin
if v.Count > 0 then
Result := THelper.IndexOfMin(v.FBuffer.FItems[0..Pred(v.Count)])
else
Result := -1;
end;
class function TGBaseVectorHelper.IndexOfMax(v: TVector): SizeInt;
begin
if v.ElemCount > 0 then
Result := THelper.IndexOfMax(v.FItems[0..Pred(v.ElemCount)])
else
Result := -1;
end;
class function TGBaseVectorHelper.IndexOfMax(constref v: TLiteVector): SizeInt;
begin
if v.Count > 0 then
Result := THelper.IndexOfMax(v.FBuffer.FItems[0..Pred(v.Count)])
else
Result := -1;
end;
class function TGBaseVectorHelper.GetMin(v: TVector): TOptional;
begin
if v.ElemCount > 0 then
Result := THelper.GetMin(v.FItems[0..Pred(v.ElemCount)]);
end;
class function TGBaseVectorHelper.GetMin(constref v: TLiteVector): TOptional;
begin
if v.Count > 0 then
Result := THelper.GetMin(v.FBuffer.FItems[0..Pred(v.Count)]);
end;
class function TGBaseVectorHelper.GetMax(v: TVector): TOptional;
begin
if v.ElemCount > 0 then
Result := THelper.GetMax(v.FItems[0..Pred(v.ElemCount)]);
end;
class function TGBaseVectorHelper.GetMax(constref v: TLiteVector): TOptional;
begin
if v.Count > 0 then
Result := THelper.GetMax(v.FBuffer.FItems[0..Pred(v.Count)]);
end;
class function TGBaseVectorHelper.FindMin(v: TVector; out aValue: T): Boolean;
begin
if v.ElemCount > 0 then
Result := THelper.FindMin(v.FItems[0..Pred(v.ElemCount)], aValue)
else
Result := False;
end;
class function TGBaseVectorHelper.FindMin(constref v: TLiteVector; out aValue: T): Boolean;
begin
if v.Count > 0 then
Result := THelper.FindMin(v.FBuffer.FItems[0..Pred(v.Count)], aValue)
else
Result := False;
end;
class function TGBaseVectorHelper.FindMax(v: TVector; out aValue: T): Boolean;
begin
if v.ElemCount > 0 then
Result := THelper.FindMax(v.FItems[0..Pred(v.ElemCount)], aValue)
else
Result := False;
end;
class function TGBaseVectorHelper.FindMax(constref v: TLiteVector; out aValue: T): Boolean;
begin
if v.Count > 0 then
Result := THelper.FindMax(v.FBuffer.FItems[0..Pred(v.Count)], aValue)
else
Result := False;
end;
class function TGBaseVectorHelper.FindMinMax(v: TVector; out aMin, aMax: T): Boolean;
begin
if v.ElemCount > 0 then
Result := THelper.FindMinMax(v.FItems[0..Pred(v.ElemCount)], aMin, aMax)
else
Result := False;
end;
class function TGBaseVectorHelper.FindMinMax(constref v: TLiteVector; out aMin, aMax: T): Boolean;
begin
if v.Count > 0 then
Result := THelper.FindMinMax(v.FBuffer.FItems[0..Pred(v.Count)], aMin, aMax)
else
Result := False;
end;
class function TGBaseVectorHelper.FindNthSmallest(v: TVector; N: SizeInt; out aValue: T): Boolean;
begin
if v.ElemCount > 0 then
Result := THelper.FindNthSmallestND(v.FItems[0..Pred(v.ElemCount)], N, aValue)
else
Result := False;
end;
class function TGBaseVectorHelper.FindNthSmallest(constref v: TLiteVector; N: SizeInt; out aValue: T): Boolean;
begin
if v.Count > 0 then
Result := THelper.FindNthSmallestND(v.FBuffer.FItems[0..Pred(v.Count)], N, aValue)
else
Result := False;
end;
class function TGBaseVectorHelper.NthSmallest(v: TVector; N: SizeInt): TOptional;
begin
if v.ElemCount > 0 then
Result := THelper.NthSmallestND(v.FItems[0..Pred(v.ElemCount)], N);
end;
class function TGBaseVectorHelper.NthSmallest(constref v: TLiteVector; N: SizeInt): TOptional;
begin
if v.Count > 0 then
Result := THelper.NthSmallestND(v.FBuffer.FItems[0..Pred(v.Count)], N);
end;
class function TGBaseVectorHelper.NextPermutation2Asc(v: TVector): Boolean;
begin
v.CheckInIteration;
if v.ElemCount > 1 then
Result := THelper.NextPermutation2Asc(v.FItems[0..Pred(v.ElemCount)])
else
Result := False;
end;
class function TGBaseVectorHelper.NextPermutation2Asc(var v: TLiteVector): Boolean;
begin
if v.Count > 1 then
Result := THelper.NextPermutation2Asc(v.FBuffer.FItems[0..Pred(v.Count)])
else
Result := False;
end;
class function TGBaseVectorHelper.NextPermutation2Desc(v: TVector): Boolean;
begin
v.CheckInIteration;
if v.ElemCount > 1 then
Result := THelper.NextPermutation2Desc(v.FItems[0..Pred(v.ElemCount)])
else
Result := False;
end;
class function TGBaseVectorHelper.NextPermutation2Desc(var v: TLiteVector): Boolean;
begin
if v.Count > 1 then
Result := THelper.NextPermutation2Desc(v.FBuffer.FItems[0..Pred(v.Count)])
else
Result := False;
end;
class function TGBaseVectorHelper.IsNonDescending(v: TVector): Boolean;
begin
if v.ElemCount > 0 then
Result := THelper.IsNonDescending(v.FItems[0..Pred(v.ElemCount)])
else
Result := True;
end;
class function TGBaseVectorHelper.IsNonDescending(constref v: TLiteVector): Boolean;
begin
if v.Count > 0 then
Result := THelper.IsNonDescending(v.FBuffer.FItems[0..Pred(v.Count)])
else
Result := True;
end;
class function TGBaseVectorHelper.IsStrictAscending(v: TVector): Boolean;
begin
if v.ElemCount > 1 then
Result := THelper.IsStrictAscending(v.FItems[0..Pred(v.ElemCount)])
else
Result := False;
end;
class function TGBaseVectorHelper.IsStrictAscending(constref v: TLiteVector): Boolean;
begin
if v.Count > 1 then
Result := THelper.IsStrictAscending(v.FBuffer.FItems[0..Pred(v.Count)])
else
Result := False;
end;
class function TGBaseVectorHelper.IsNonAscending(v: TVector): Boolean;
begin
if v.ElemCount > 0 then
Result := THelper.IsNonAscending(v.FItems[0..Pred(v.ElemCount)])
else
Result := True;
end;
class function TGBaseVectorHelper.IsNonAscending(constref v: TLiteVector): Boolean;
begin
if v.Count > 0 then
Result := THelper.IsNonAscending(v.FBuffer.FItems[0..Pred(v.Count)])
else
Result := True;
end;
class function TGBaseVectorHelper.IsStrictDescending(v: TVector): Boolean;
begin
if v.ElemCount > 1 then
Result := THelper.IsStrictDescending(v.FItems[0..Pred(v.ElemCount)])
else
Result := False;
end;
class function TGBaseVectorHelper.IsStrictDescending(constref v: TLiteVector): Boolean;
begin
if v.Count > 1 then
Result := THelper.IsStrictDescending(v.FBuffer.FItems[0..Pred(v.Count)])
else
Result := False;
end;
class function TGBaseVectorHelper.Same(A, B: TVector): Boolean;
var
c: SizeInt;
begin
c := A.ElemCount;
if B.ElemCount = c then
Result := THelper.Same(A.FItems[0..Pred(c)], B.FItems[0..Pred(c)])
else
Result := False;
end;
class function TGBaseVectorHelper.Same(constref A, B: TLiteVector): Boolean;
var
c: SizeInt;
begin
c := A.Count;
if B.Count = c then
Result := THelper.Same(A.FBuffer.FItems[0..Pred(c)], B.FBuffer.FItems[0..Pred(c)])
else
Result := False;
end;
class procedure TGBaseVectorHelper.IntroSort(v: TVector; o: TSortOrder);
begin
v.CheckInIteration;
if v.ElemCount > 1 then
THelper.IntroSort(v.FItems[0..Pred(v.ElemCount)], o);
end;
class procedure TGBaseVectorHelper.IntroSort(var v: TLiteVector; o: TSortOrder);
begin
if v.Count > 1 then
THelper.IntroSort(v.FBuffer.FItems[0..Pred(v.Count)], o);
end;
class procedure TGBaseVectorHelper.PDQSort(v: TVector; o: TSortOrder);
begin
v.CheckInIteration;
if v.ElemCount > 1 then
THelper.PDQSort(v.FItems[0..Pred(v.ElemCount)], o);
end;
class procedure TGBaseVectorHelper.PDQSort(var v: TLiteVector; o: TSortOrder);
begin
if v.Count > 1 then
THelper.PDQSort(v.FBuffer.FItems[0..Pred(v.Count)], o);
end;
class procedure TGBaseVectorHelper.MergeSort(v: TVector; o: TSortOrder);
begin
v.CheckInIteration;
if v.ElemCount > 1 then
THelper.MergeSort(v.FItems[0..Pred(v.ElemCount)], o);
end;
class procedure TGBaseVectorHelper.MergeSort(var v: TLiteVector; o: TSortOrder);
begin
if v.Count > 1 then
THelper.MergeSort(v.FBuffer.FItems[0..Pred(v.Count)], o);
end;
class procedure TGBaseVectorHelper.Sort(v: TVector; o: TSortOrder);
begin
v.CheckInIteration;
if v.ElemCount > 1 then
THelper.Sort(v.FItems[0..Pred(v.ElemCount)], o);
end;
class procedure TGBaseVectorHelper.Sort(var v: TLiteVector; o: TSortOrder);
begin
if v.Count > 1 then
THelper.Sort(v.FBuffer.FItems[0..Pred(v.Count)], o);
end;
class function TGBaseVectorHelper.SelectDistinct(v: TVector): TVector.TArray;
begin
if v.ElemCount > 0 then
Result := THelper.SelectDistinct(v.FItems[0..Pred(v.ElemCount)])
else
Result := nil;
end;
class function TGBaseVectorHelper.SelectDistinct(constref v: TLiteVector): TLiteVector.TArray;
begin
if v.Count > 0 then
Result := THelper.SelectDistinct(v.FBuffer.FItems[0..Pred(v.Count)])
else
Result := nil;
end;
{ TGComparableVectorHelper }
class procedure TGComparableVectorHelper.Reverse(v: TVector);
begin
v.CheckInIteration;
if v.ElemCount > 1 then
THelper.Reverse(v.FItems[0..Pred(v.ElemCount)]);
end;
class procedure TGComparableVectorHelper.Reverse(var v: TLiteVector);
begin
if v.Count > 1 then
THelper.Reverse(v.FBuffer.FItems[0..Pred(v.Count)]);
end;
class procedure TGComparableVectorHelper.RandomShuffle(v: TVector);
begin
v.CheckInIteration;
if v.ElemCount > 1 then
THelper.RandomShuffle(v.FItems[0..Pred(v.ElemCount)]);
end;
class procedure TGComparableVectorHelper.RandomShuffle(var v: TLiteVector);
begin
if v.Count > 1 then
THelper.RandomShuffle(v.FBuffer.FItems[0..Pred(v.Count)]);
end;
class function TGComparableVectorHelper.SequentSearch(v: TVector; const aValue: T): SizeInt;
begin
if v.ElemCount > 0 then
Result := THelper.SequentSearch(v.FItems[0..Pred(v.ElemCount)], aValue)
else
Result := -1;
end;
class function TGComparableVectorHelper.SequentSearch(constref v: TLiteVector; const aValue: T): SizeInt;
begin
if v.Count > 0 then
Result := THelper.SequentSearch(v.FBuffer.FItems[0..Pred(v.Count)], aValue)
else
Result := -1;
end;
class function TGComparableVectorHelper.BinarySearch(v: TVector; const aValue: T): SizeInt;
begin
if v.ElemCount > 0 then
Result := THelper.BinarySearch(v.FItems[0..Pred(v.ElemCount)], aValue)
else
Result := -1;
end;
class function TGComparableVectorHelper.BinarySearch(constref v: TLiteVector; const aValue: T): SizeInt;
begin
if v.Count > 0 then
Result := THelper.BinarySearch(v.FBuffer.FItems[0..Pred(v.Count)], aValue)
else
Result := -1;
end;
class function TGComparableVectorHelper.IndexOfMin(v: TVector): SizeInt;
begin
if v.ElemCount > 0 then
Result := THelper.IndexOfMin(v.FItems[0..Pred(v.ElemCount)])
else
Result := -1;
end;
class function TGComparableVectorHelper.IndexOfMin(constref v: TLiteVector): SizeInt;
begin
if v.Count > 0 then
Result := THelper.IndexOfMin(v.FBuffer.FItems[0..Pred(v.Count)])
else
Result := -1;
end;
class function TGComparableVectorHelper.IndexOfMax(v: TVector): SizeInt;
begin
if v.ElemCount > 0 then
Result := THelper.IndexOfMax(v.FItems[0..Pred(v.ElemCount)])
else
Result := -1;
end;
class function TGComparableVectorHelper.IndexOfMax(constref v: TLiteVector): SizeInt;
begin
if v.Count > 0 then
Result := THelper.IndexOfMax(v.FBuffer.FItems[0..Pred(v.Count)])
else
Result := -1;
end;
class function TGComparableVectorHelper.GetMin(v: TVector): TOptional;
begin
System.Initialize(Result);
if v.ElemCount > 0 then
Result := THelper.GetMin(v.FItems[0..Pred(v.ElemCount)]);
end;
class function TGComparableVectorHelper.GetMin(constref v: TLiteVector): TOptional;
begin
System.Initialize(Result);
if v.Count > 0 then
Result := THelper.GetMin(v.FBuffer.FItems[0..Pred(v.Count)]);
end;
class function TGComparableVectorHelper.GetMax(v: TVector): TOptional;
begin
System.Initialize(Result);
if v.ElemCount > 0 then
Result := THelper.GetMax(v.FItems[0..Pred(v.ElemCount)]);
end;
class function TGComparableVectorHelper.GetMax(constref v: TLiteVector): TOptional;
begin
System.Initialize(Result);
if v.Count > 0 then
Result := THelper.GetMax(v.FBuffer.FItems[0..Pred(v.Count)]);
end;
class function TGComparableVectorHelper.FindMin(v: TVector; out aValue: T): Boolean;
begin
if v.ElemCount > 0 then
Result := THelper.FindMin(v.FItems[0..Pred(v.ElemCount)], aValue)
else
Result := False;
end;
class function TGComparableVectorHelper.FindMin(constref v: TLiteVector; out aValue: T): Boolean;
begin
if v.Count > 0 then
Result := THelper.FindMin(v.FBuffer.FItems[0..Pred(v.Count)], aValue)
else
Result := False;
end;
class function TGComparableVectorHelper.FindMax(v: TVector; out aValue: T): Boolean;
begin
if v.ElemCount > 0 then
Result := THelper.FindMax(v.FItems[0..Pred(v.ElemCount)], aValue)
else
Result := False;
end;
class function TGComparableVectorHelper.FindMax(constref v: TLiteVector; out aValue: T): Boolean;
begin
if v.Count > 0 then
Result := THelper.FindMax(v.FBuffer.FItems[0..Pred(v.Count)], aValue)
else
Result := False;
end;
class function TGComparableVectorHelper.FindMinMax(v: TVector; out aMin, aMax: T): Boolean;
begin
if v.ElemCount > 0 then
Result := THelper.FindMinMax(v.FItems[0..Pred(v.ElemCount)], aMin, aMax)
else
Result := False;
end;
class function TGComparableVectorHelper.FindMinMax(constref v: TLiteVector; out aMin, aMax: T): Boolean;
begin
if v.Count > 0 then
Result := THelper.FindMinMax(v.FBuffer.FItems[0..Pred(v.Count)], aMin, aMax)
else
Result := False;
end;
class function TGComparableVectorHelper.FindNthSmallest(v: TVector; N: SizeInt; out aValue: T): Boolean;
begin
if v.ElemCount > 0 then
Result := THelper.FindNthSmallestND(v.FItems[0..Pred(v.ElemCount)], N, aValue)
else
Result := False;
end;
class function TGComparableVectorHelper.FindNthSmallest(constref v: TLiteVector; N: SizeInt;
out aValue: T): Boolean;
begin
if v.Count > 0 then
Result := THelper.FindNthSmallestND(v.FBuffer.FItems[0..Pred(v.Count)], N, aValue)
else
Result := False;
end;
class function TGComparableVectorHelper.NthSmallest(v: TVector; N: SizeInt): TOptional;
begin
System.Initialize(Result);
if v.ElemCount > 0 then
Result := THelper.NthSmallestND(v.FItems[0..Pred(v.ElemCount)], N);
end;
class function TGComparableVectorHelper.NthSmallest(constref v: TLiteVector; N: SizeInt): TOptional;
begin
System.Initialize(Result);
if v.Count > 0 then
Result := THelper.NthSmallestND(v.FBuffer.FItems[0..Pred(v.Count)], N);
end;
class function TGComparableVectorHelper.NextPermutation2Asc(v: TVector): Boolean;
begin
v.CheckInIteration;
if v.ElemCount > 1 then
Result := THelper.NextPermutation2Asc(v.FItems[0..Pred(v.ElemCount)])
else
Result := False;
end;
class function TGComparableVectorHelper.NextPermutation2Asc(var v: TLiteVector): Boolean;
begin
if v.Count > 1 then
Result := THelper.NextPermutation2Asc(v.FBuffer.FItems[0..Pred(v.Count)])
else
Result := False;
end;
class function TGComparableVectorHelper.NextPermutation2Desc(v: TVector): Boolean;
begin
v.CheckInIteration;
if v.ElemCount > 1 then
Result := THelper.NextPermutation2Desc(v.FItems[0..Pred(v.ElemCount)])
else
Result := False;
end;
class function TGComparableVectorHelper.NextPermutation2Desc(var v: TLiteVector): Boolean;
begin
if v.Count > 1 then
Result := THelper.NextPermutation2Desc(v.FBuffer.FItems[0..Pred(v.Count)])
else
Result := False;
end;
class function TGComparableVectorHelper.IsNonDescending(v: TVector): Boolean;
begin
if v.ElemCount > 0 then
Result := THelper.IsNonDescending(v.FItems[0..Pred(v.ElemCount)])
else
Result := True;
end;
class function TGComparableVectorHelper.IsNonDescending(constref v: TLiteVector): Boolean;
begin
if v.Count > 0 then
Result := THelper.IsNonDescending(v.FBuffer.FItems[0..Pred(v.Count)])
else
Result := True;
end;
class function TGComparableVectorHelper.IsStrictAscending(v: TVector): Boolean;
begin
if v.ElemCount > 1 then
Result := THelper.IsStrictAscending(v.FItems[0..Pred(v.ElemCount)])
else
Result := False;
end;
class function TGComparableVectorHelper.IsStrictAscending(constref v: TLiteVector): Boolean;
begin
if v.Count > 1 then
Result := THelper.IsStrictAscending(v.FBuffer.FItems[0..Pred(v.Count)])
else
Result := False;
end;
class function TGComparableVectorHelper.IsNonAscending(v: TVector): Boolean;
begin
if v.ElemCount > 0 then
Result := THelper.IsNonAscending(v.FItems[0..Pred(v.ElemCount)])
else
Result := True;
end;
class function TGComparableVectorHelper.IsNonAscending(constref v: TLiteVector): Boolean;
begin
if v.Count > 0 then
Result := THelper.IsNonAscending(v.FBuffer.FItems[0..Pred(v.Count)])
else
Result := True;
end;
class function TGComparableVectorHelper.IsStrictDescending(v: TVector): Boolean;
begin
if v.ElemCount > 1 then
Result := THelper.IsStrictDescending(v.FItems[0..Pred(v.ElemCount)])
else
Result := False;
end;
class function TGComparableVectorHelper.IsStrictDescending(constref v: TLiteVector): Boolean;
begin
if v.Count > 1 then
Result := THelper.IsStrictDescending(v.FBuffer.FItems[0..Pred(v.Count)])
else
Result := False;
end;
class function TGComparableVectorHelper.Same(A, B: TVector): Boolean;
var
c: SizeInt;
begin
c := A.ElemCount;
if B.ElemCount = c then
Result := THelper.Same(A.FItems[0..Pred(c)], B.FItems[0..Pred(c)])
else
Result := False;
end;
class function TGComparableVectorHelper.Same(constref A, B: TLiteVector): Boolean;
var
c: SizeInt;
begin
c := A.Count;
if B.Count = c then
Result := THelper.Same(A.FBuffer.FItems[0..Pred(c)], B.FBuffer.FItems[0..Pred(c)])
else
Result := False;
end;
class procedure TGComparableVectorHelper.IntroSort(v: TVector; o: TSortOrder);
begin
v.CheckInIteration;
if v.ElemCount > 1 then
THelper.IntroSort(v.FItems[0..Pred(v.ElemCount)], o);
end;
class procedure TGComparableVectorHelper.IntroSort(var v: TLiteVector; o: TSortOrder);
begin
if v.Count > 1 then
THelper.IntroSort(v.FBuffer.FItems[0..Pred(v.Count)], o);
end;
class procedure TGComparableVectorHelper.PDQSort(v: TVector; o: TSortOrder);
begin
v.CheckInIteration;
if v.ElemCount > 1 then
THelper.PDQSort(v.FItems[0..Pred(v.ElemCount)], o);
end;
class procedure TGComparableVectorHelper.PDQSort(var v: TLiteVector; o: TSortOrder);
begin
if v.Count > 1 then
THelper.PDQSort(v.FBuffer.FItems[0..Pred(v.Count)], o);
end;
class procedure TGComparableVectorHelper.MergeSort(v: TVector; o: TSortOrder);
begin
v.CheckInIteration;
if v.ElemCount > 1 then
THelper.MergeSort(v.FItems[0..Pred(v.ElemCount)], o);
end;
class procedure TGComparableVectorHelper.MergeSort(var v: TLiteVector; o: TSortOrder);
begin
if v.Count > 1 then
THelper.MergeSort(v.FBuffer.FItems[0..Pred(v.Count)], o);
end;
class procedure TGComparableVectorHelper.Sort(v: TVector; o: TSortOrder);
begin
v.CheckInIteration;
if v.ElemCount > 1 then
THelper.Sort(v.FItems[0..Pred(v.ElemCount)], o);
end;
class procedure TGComparableVectorHelper.Sort(var v: TLiteVector; o: TSortOrder);
begin
if v.Count > 1 then
THelper.Sort(v.FBuffer.FItems[0..Pred(v.Count)], o);
end;
class function TGComparableVectorHelper.SelectDistinct(v: TVector): TVector.TArray;
begin
if v.ElemCount > 0 then
Result := THelper.SelectDistinct(v.FItems[0..Pred(v.ElemCount)])
else
Result := nil;
end;
class function TGComparableVectorHelper.SelectDistinct(constref v: TLiteVector): TLiteVector.TArray;
begin
if v.Count > 0 then
Result := THelper.SelectDistinct(v.FBuffer.FItems[0..Pred(v.Count)])
else
Result := nil;
end;
{ TGRegularVectorHelper }
class function TGRegularVectorHelper.SequentSearch(v: TVector; const aValue: T; c: TLess): SizeInt;
begin
if v.ElemCount > 0 then
Result := THelper.SequentSearch(v.FItems[0..Pred(v.ElemCount)], aValue, c)
else
Result := -1;
end;
class function TGRegularVectorHelper.SequentSearch(constref v: TLiteVector; const aValue: T;
c: TLess): SizeInt;
begin
if v.Count > 0 then
Result := THelper.SequentSearch(v.FBuffer.FItems[0..Pred(v.Count)], aValue, c)
else
Result := -1;
end;
class function TGRegularVectorHelper.BinarySearch(v: TVector; const aValue: T; c: TLess): SizeInt;
begin
if v.ElemCount > 0 then
Result := THelper.BinarySearch(v.FItems[0..Pred(v.ElemCount)], aValue, c)
else
Result := -1;
end;
class function TGRegularVectorHelper.BinarySearch(constref v: TLiteVector; const aValue: T;
c: TLess): SizeInt;
begin
end;
class function TGRegularVectorHelper.IndexOfMin(v: TVector; c: TLess): SizeInt;
begin
if v.ElemCount > 0 then
Result := THelper.IndexOfMin(v.FItems[0..Pred(v.ElemCount)], c)
else
Result := -1;
end;
class function TGRegularVectorHelper.IndexOfMax(v: TVector; c: TLess): SizeInt;
begin
if v.ElemCount > 0 then
Result := THelper.IndexOfMax(v.FItems[0..Pred(v.ElemCount)], c)
else
Result := -1;
end;
class function TGRegularVectorHelper.IndexOfMax(constref v: TLiteVector; c: TLess): SizeInt;
begin
if v.Count > 0 then
Result := THelper.IndexOfMax(v.FBuffer.FItems[0..Pred(v.Count)], c)
else
Result := -1;
end;
class function TGRegularVectorHelper.GetMin(v: TVector; c: TLess): TOptional;
begin
if v.ElemCount > 0 then
Result := THelper.GetMin(v.FItems[0..Pred(v.ElemCount)], c);
end;
class function TGRegularVectorHelper.GetMin(constref v: TLiteVector; c: TLess): TOptional;
begin
if v.Count > 0 then
Result := THelper.GetMin(v.FBuffer.FItems[0..Pred(v.Count)], c);
end;
class function TGRegularVectorHelper.GetMax(v: TVector; c: TLess): TOptional;
begin
if v.ElemCount > 0 then
Result := THelper.GetMax(v.FItems[0..Pred(v.ElemCount)], c);
end;
class function TGRegularVectorHelper.GetMax(constref v: TLiteVector; c: TLess): TOptional;
begin
if v.Count > 0 then
Result := THelper.GetMax(v.FBuffer.FItems[0..Pred(v.Count)], c);
end;
class function TGRegularVectorHelper.FindMin(v: TVector; out aValue: T; c: TLess): Boolean;
begin
if v.ElemCount > 0 then
Result := THelper.FindMin(v.FItems[0..Pred(v.ElemCount)], aValue, c)
else
Result := False;
end;
class function TGRegularVectorHelper.FindMin(constref v: TLiteVector; out aValue: T; c: TLess): Boolean;
begin
if v.Count > 0 then
Result := THelper.FindMin(v.FBuffer.FItems[0..Pred(v.Count)], aValue, c)
else
Result := False;
end;
class function TGRegularVectorHelper.FindMax(v: TVector; out aValue: T; c: TLess): Boolean;
begin
if v.ElemCount > 0 then
Result := THelper.FindMax(v.FItems[0..Pred(v.ElemCount)], aValue, c)
else
Result := False;
end;
class function TGRegularVectorHelper.FindMax(constref v: TLiteVector; out aValue: T; c: TLess): Boolean;
begin
if v.Count > 0 then
Result := THelper.FindMax(v.FBuffer.FItems[0..Pred(v.Count)], aValue, c)
else
Result := False;
end;
class function TGRegularVectorHelper.FindMinMax(v: TVector; out aMin, aMax: T; c: TLess): Boolean;
begin
if v.ElemCount > 0 then
Result := THelper.FindMinMax(v.FItems[0..Pred(v.ElemCount)], aMin, aMax, c)
else
Result := False;
end;
class function TGRegularVectorHelper.FindMinMax(constref v: TLiteVector; out aMin, aMax: T; c: TLess): Boolean;
begin
if v.Count > 0 then
Result := THelper.FindMinMax(v.FBuffer.FItems[0..Pred(v.Count)], aMin, aMax, c)
else
Result := False;
end;
class function TGRegularVectorHelper.FindNthSmallest(v: TVector; N: SizeInt; out aValue: T; c: TLess): Boolean;
begin
if v.ElemCount > 0 then
Result := THelper.FindNthSmallestND(v.FItems[0..Pred(v.ElemCount)], N, aValue, c)
else
Result := False;
end;
class function TGRegularVectorHelper.FindNthSmallest(constref v: TLiteVector; N: SizeInt; out aValue: T;
c: TLess): Boolean;
begin
if v.Count > 0 then
Result := THelper.FindNthSmallestND(v.FBuffer.FItems[0..Pred(v.Count)], N, aValue, c)
else
Result := False;
end;
class function TGRegularVectorHelper.NthSmallest(v: TVector; N: SizeInt; c: TLess): TOptional;
begin
if v.ElemCount > 0 then
Result := THelper.NthSmallestND(v.FItems[0..Pred(v.ElemCount)], N, c);
end;
class function TGRegularVectorHelper.NthSmallest(constref v: TLiteVector; N: SizeInt; c: TLess): TOptional;
begin
if v.Count > 0 then
Result := THelper.NthSmallestND(v.FBuffer.FItems[0..Pred(v.Count)], N, c);
end;
class function TGRegularVectorHelper.NextPermutation2Asc(v: TVector; c: TLess): Boolean;
begin
v.CheckInIteration;
if v.ElemCount > 1 then
Result := THelper.NextPermutation2Asc(v.FItems[0..Pred(v.ElemCount)], c)
else
Result := False;
end;
class function TGRegularVectorHelper.NextPermutation2Asc(var v: TLiteVector; c: TLess): Boolean;
begin
if v.Count > 1 then
Result := THelper.NextPermutation2Asc(v.FBuffer.FItems[0..Pred(v.Count)], c)
else
Result := False;
end;
class function TGRegularVectorHelper.NextPermutation2Desc(v: TVector; c: TLess): Boolean;
begin
v.CheckInIteration;
if v.ElemCount > 1 then
Result := THelper.NextPermutation2Desc(v.FItems[0..Pred(v.ElemCount)], c)
else
Result := False;
end;
class function TGRegularVectorHelper.NextPermutation2Desc(var v: TLiteVector; c: TLess): Boolean;
begin
if v.Count > 1 then
Result := THelper.NextPermutation2Desc(v.FBuffer.FItems[0..Pred(v.Count)], c)
else
Result := False;
end;
class function TGRegularVectorHelper.IsNonDescending(v: TVector; c: TLess): Boolean;
begin
if v.ElemCount > 0 then
Result := THelper.IsNonDescending(v.FItems[0..Pred(v.ElemCount)], c)
else
Result := True;
end;
class function TGRegularVectorHelper.IsNonDescending(constref v: TLiteVector; c: TLess): Boolean;
begin
if v.Count > 0 then
Result := THelper.IsNonDescending(v.FBuffer.FItems[0..Pred(v.Count)], c)
else
Result := True;
end;
class function TGRegularVectorHelper.IsStrictAscending(v: TVector; c: TLess): Boolean;
begin
if v.ElemCount > 1 then
Result := THelper.IsStrictAscending(v.FItems[0..Pred(v.ElemCount)], c)
else
Result := False;
end;
class function TGRegularVectorHelper.IsNonAscending(v: TVector; c: TLess): Boolean;
begin
if v.ElemCount > 0 then
Result := THelper.IsNonAscending(v.FItems[0..Pred(v.ElemCount)], c)
else
Result := True;
end;
class function TGRegularVectorHelper.IsNonAscending(constref v: TLiteVector; c: TLess): Boolean;
begin
if v.Count > 0 then
Result := THelper.IsNonAscending(v.FBuffer.FItems[0..Pred(v.Count)], c)
else
Result := True;
end;
class function TGRegularVectorHelper.IsStrictDescending(v: TVector; c: TLess): Boolean;
begin
if v.ElemCount > 1 then
Result := THelper.IsStrictDescending(v.FItems[0..Pred(v.ElemCount)], c)
else
Result := False;
end;
class function TGRegularVectorHelper.IsStrictDescending(constref v: TLiteVector; c: TLess): Boolean;
begin
if v.Count > 1 then
Result := THelper.IsStrictDescending(v.FBuffer.FItems[0..Pred(v.Count)], c)
else
Result := False;
end;
class function TGRegularVectorHelper.Same(A, B: TVector; c: TLess): Boolean;
var
cnt: SizeInt;
begin
cnt := A.ElemCount;
if B.ElemCount = cnt then
Result := THelper.Same(A.FItems[0..Pred(cnt)], B.FItems[0..Pred(cnt)], c)
else
Result := False;
end;
class function TGRegularVectorHelper.Same(constref A, B: TLiteVector; c: TLess): Boolean;
var
cnt: SizeInt;
begin
cnt := A.Count;
if B.Count = cnt then
Result := THelper.Same(A.FBuffer.FItems[0..Pred(cnt)], B.FBuffer.FItems[0..Pred(cnt)], c)
else
Result := False;
end;
class procedure TGRegularVectorHelper.IntroSort(v: TVector; c: TLess; o: TSortOrder);
begin
v.CheckInIteration;
if v.ElemCount > 1 then
THelper.IntroSort(v.FItems[0..Pred(v.ElemCount)], c, o);
end;
class procedure TGRegularVectorHelper.IntroSort(var v: TLiteVector; c: TLess; o: TSortOrder);
begin
if v.Count > 1 then
THelper.IntroSort(v.FBuffer.FItems[0..Pred(v.Count)], c, o);
end;
class procedure TGRegularVectorHelper.PDQSort(v: TVector; c: TLess; o: TSortOrder);
begin
v.CheckInIteration;
if v.ElemCount > 1 then
THelper.PDQSort(v.FItems[0..Pred(v.ElemCount)], c, o);
end;
class procedure TGRegularVectorHelper.PDQSort(var v: TLiteVector; c: TLess; o: TSortOrder);
begin
if v.Count > 1 then
THelper.PDQSort(v.FBuffer.FItems[0..Pred(v.Count)], c, o);
end;
class procedure TGRegularVectorHelper.MergeSort(v: TVector; c: TLess; o: TSortOrder);
begin
v.CheckInIteration;
if v.ElemCount > 1 then
THelper.MergeSort(v.FItems[0..Pred(v.ElemCount)], c, o);
end;
class procedure TGRegularVectorHelper.MergeSort(var v: TLiteVector; c: TLess; o: TSortOrder);
begin
if v.Count > 1 then
THelper.MergeSort(v.FBuffer.FItems[0..Pred(v.Count)], c, o);
end;
class procedure TGRegularVectorHelper.Sort(v: TVector; c: TLess; o: TSortOrder);
begin
v.CheckInIteration;
if v.ElemCount > 1 then
THelper.Sort(v.FItems[0..Pred(v.ElemCount)], c, o);
end;
class procedure TGRegularVectorHelper.Sort(var v: TLiteVector; c: TLess; o: TSortOrder);
begin
if v.Count > 1 then
THelper.Sort(v.FBuffer.FItems[0..Pred(v.Count)], c, o);
end;
class function TGRegularVectorHelper.SelectDistinct(v: TVector; c: TLess): TVector.TArray;
begin
if v.ElemCount > 0 then
Result := THelper.SelectDistinct(v.FItems[0..Pred(v.ElemCount)], c)
else
Result := nil;
end;
class function TGRegularVectorHelper.SelectDistinct(constref v: TLiteVector; c: TLess): TLiteVector.TArray;
begin
if v.Count > 0 then
Result := THelper.SelectDistinct(v.FBuffer.FItems[0..Pred(v.Count)], c)
else
Result := nil;
end;
{ TGDelegatedVectorHelper }
class function TGDelegatedVectorHelper.SequentSearch(v: TVector; const aValue: T; c: TOnLess): SizeInt;
begin
if v.ElemCount > 0 then
Result := THelper.SequentSearch(v.FItems[0..Pred(v.ElemCount)], aValue, c)
else
Result := -1;
end;
class function TGDelegatedVectorHelper.SequentSearch(constref v: TLiteVector; const aValue: T;
c: TOnLess): SizeInt;
begin
if v.Count > 0 then
Result := THelper.SequentSearch(v.FBuffer.FItems[0..Pred(v.Count)], aValue, c)
else
Result := -1;
end;
class function TGDelegatedVectorHelper.BinarySearch(v: TVector; const aValue: T; c: TOnLess): SizeInt;
begin
if v.ElemCount > 0 then
Result := THelper.BinarySearch(v.FItems[0..Pred(v.ElemCount)], aValue, c)
else
Result := -1;
end;
class function TGDelegatedVectorHelper.BinarySearch(constref v: TLiteVector; const aValue: T;
c: TOnLess): SizeInt;
begin
if v.Count > 0 then
Result := THelper.BinarySearch(v.FBuffer.FItems[0..Pred(v.Count)], aValue, c)
else
Result := -1;
end;
class function TGDelegatedVectorHelper.IndexOfMin(v: TVector; c: TOnLess): SizeInt;
begin
if v.ElemCount > 0 then
Result := THelper.IndexOfMin(v.FItems[0..Pred(v.ElemCount)], c)
else
Result := -1;
end;
class function TGDelegatedVectorHelper.IndexOfMin(constref v: TLiteVector; c: TOnLess): SizeInt;
begin
if v.Count > 0 then
Result := THelper.IndexOfMin(v.FBuffer.FItems[0..Pred(v.Count)], c)
else
Result := -1;
end;
class function TGDelegatedVectorHelper.IndexOfMax(v: TVector; c: TOnLess): SizeInt;
begin
if v.ElemCount > 0 then
Result := THelper.IndexOfMax(v.FItems[0..Pred(v.ElemCount)], c)
else
Result := -1;
end;
class function TGDelegatedVectorHelper.IndexOfMax(constref v: TLiteVector; c: TOnLess): SizeInt;
begin
if v.Count > 0 then
Result := THelper.IndexOfMax(v.FBuffer.FItems[0..Pred(v.Count)], c)
else
Result := -1;
end;
class function TGDelegatedVectorHelper.GetMin(v: TVector; c: TOnLess): TOptional;
begin
System.Initialize(Result);
if v.ElemCount > 0 then
Result := THelper.GetMin(v.FItems[0..Pred(v.ElemCount)], c);
end;
class function TGDelegatedVectorHelper.GetMin(constref v: TLiteVector; c: TOnLess): TOptional;
begin
System.Initialize(Result);
if v.Count > 0 then
Result := THelper.GetMin(v.FBuffer.FItems[0..Pred(v.Count)], c);
end;
class function TGDelegatedVectorHelper.GetMax(v: TVector; c: TOnLess): TOptional;
begin
System.Initialize(Result);
if v.ElemCount > 0 then
Result := THelper.GetMax(v.FItems[0..Pred(v.ElemCount)], c);
end;
class function TGDelegatedVectorHelper.GetMax(constref v: TLiteVector; c: TOnLess): TOptional;
begin
System.Initialize(Result);
if v.Count > 0 then
Result := THelper.GetMax(v.FBuffer.FItems[0..Pred(v.Count)], c);
end;
class function TGDelegatedVectorHelper.FindMin(v: TVector; out aValue: T; c: TOnLess): Boolean;
begin
if v.ElemCount > 0 then
Result := THelper.FindMin(v.FItems[0..Pred(v.ElemCount)], aValue, c)
else
Result := False;
end;
class function TGDelegatedVectorHelper.FindMin(constref v: TLiteVector; out aValue: T; c: TOnLess): Boolean;
begin
if v.Count > 0 then
Result := THelper.FindMin(v.FBuffer.FItems[0..Pred(v.Count)], aValue, c)
else
Result := False;
end;
class function TGDelegatedVectorHelper.FindMax(v: TVector; out aValue: T; c: TOnLess): Boolean;
begin
if v.ElemCount > 0 then
Result := THelper.FindMax(v.FItems[0..Pred(v.ElemCount)], aValue, c)
else
Result := False;
end;
class function TGDelegatedVectorHelper.FindMax(constref v: TLiteVector; out aValue: T; c: TOnLess): Boolean;
begin
if v.Count > 0 then
Result := THelper.FindMax(v.FBuffer.FItems[0..Pred(v.Count)], aValue, c)
else
Result := False;
end;
class function TGDelegatedVectorHelper.FindMinMax(v: TVector; out aMin, aMax: T; c: TOnLess): Boolean;
begin
if v.ElemCount > 0 then
Result := THelper.FindMinMax(v.FItems[0..Pred(v.ElemCount)], aMin, aMax, c)
else
Result := False;
end;
class function TGDelegatedVectorHelper.FindMinMax(constref v: TLiteVector; out aMin, aMax: T;
c: TOnLess): Boolean;
begin
if v.Count > 0 then
Result := THelper.FindMinMax(v.FBuffer.FItems[0..Pred(v.Count)], aMin, aMax, c)
else
Result := False;
end;
class function TGDelegatedVectorHelper.FindNthSmallest(v: TVector; N: SizeInt; out aValue: T;
c: TOnLess): Boolean;
begin
if v.ElemCount > 0 then
Result := THelper.FindNthSmallestND(v.FItems[0..Pred(v.ElemCount)], N, aValue, c)
else
Result := False;
end;
class function TGDelegatedVectorHelper.FindNthSmallest(constref v: TLiteVector; N: SizeInt; out aValue: T;
c: TOnLess): Boolean;
begin
if v.Count > 0 then
Result := THelper.FindNthSmallestND(v.FBuffer.FItems[0..Pred(v.Count)], N, aValue, c)
else
Result := False;
end;
class function TGDelegatedVectorHelper.NthSmallest(v: TVector; N: SizeInt; c: TOnLess): TOptional;
begin
System.Initialize(Result);
if v.ElemCount > 0 then
Result := THelper.NthSmallestND(v.FItems[0..Pred(v.ElemCount)], N, c);
end;
class function TGDelegatedVectorHelper.NthSmallest(constref v: TLiteVector; N: SizeInt;
c: TOnLess): TOptional;
begin
System.Initialize(Result);
if v.Count > 0 then
Result := THelper.NthSmallestND(v.FBuffer.FItems[0..Pred(v.Count)], N, c);
end;
class function TGDelegatedVectorHelper.NextPermutation2Asc(v: TVector; c: TOnLess): Boolean;
begin
v.CheckInIteration;
if v.ElemCount > 1 then
Result := THelper.NextPermutation2Asc(v.FItems[0..Pred(v.ElemCount)], c)
else
Result := False;
end;
class function TGDelegatedVectorHelper.NextPermutation2Asc(var v: TLiteVector; c: TOnLess): Boolean;
begin
if v.Count > 1 then
Result := THelper.NextPermutation2Asc(v.FBuffer.FItems[0..Pred(v.Count)], c)
else
Result := False;
end;
class function TGDelegatedVectorHelper.NextPermutation2Desc(v: TVector; c: TOnLess): Boolean;
begin
v.CheckInIteration;
if v.ElemCount > 1 then
Result := THelper.NextPermutation2Desc(v.FItems[0..Pred(v.ElemCount)], c)
else
Result := False;
end;
class function TGDelegatedVectorHelper.NextPermutation2Desc(var v: TLiteVector; c: TOnLess): Boolean;
begin
if v.Count > 1 then
Result := THelper.NextPermutation2Desc(v.FBuffer.FItems[0..Pred(v.Count)], c)
else
Result := False;
end;
class function TGDelegatedVectorHelper.IsNonDescending(v: TVector; c: TOnLess): Boolean;
begin
if v.ElemCount > 0 then
Result := THelper.IsNonDescending(v.FItems[0..Pred(v.ElemCount)], c)
else
Result := True;
end;
class function TGDelegatedVectorHelper.IsNonDescending(constref v: TLiteVector; c: TOnLess): Boolean;
begin
if v.Count > 0 then
Result := THelper.IsNonDescending(v.FBuffer.FItems[0..Pred(v.Count)], c)
else
Result := True;
end;
class function TGDelegatedVectorHelper.IsStrictAscending(v: TVector; c: TOnLess): Boolean;
begin
if v.ElemCount > 1 then
Result := THelper.IsStrictAscending(v.FItems[0..Pred(v.ElemCount)], c)
else
Result := False;
end;
class function TGDelegatedVectorHelper.IsStrictAscending(constref v: TLiteVector; c: TOnLess): Boolean;
begin
if v.Count > 1 then
Result := THelper.IsStrictAscending(v.FBuffer.FItems[0..Pred(v.Count)], c)
else
Result := False;
end;
class function TGDelegatedVectorHelper.IsNonAscending(v: TVector; c: TOnLess): Boolean;
begin
if v.ElemCount > 0 then
Result := THelper.IsNonAscending(v.FItems[0..Pred(v.ElemCount)], c)
else
Result := True;
end;
class function TGDelegatedVectorHelper.IsNonAscending(constref v: TLiteVector; c: TOnLess): Boolean;
begin
if v.Count > 0 then
Result := THelper.IsNonAscending(v.FBuffer.FItems[0..Pred(v.Count)], c)
else
Result := True;
end;
class function TGDelegatedVectorHelper.IsStrictDescending(v: TVector; c: TOnLess): Boolean;
begin
if v.ElemCount > 1 then
Result := THelper.IsStrictDescending(v.FItems[0..Pred(v.ElemCount)], c)
else
Result := False;
end;
class function TGDelegatedVectorHelper.IsStrictDescending(constref v: TLiteVector; c: TOnLess): Boolean;
begin
if v.Count > 1 then
Result := THelper.IsStrictDescending(v.FBuffer.FItems[0..Pred(v.Count)], c)
else
Result := False;
end;
class function TGDelegatedVectorHelper.Same(A, B: TVector; c: TOnLess): Boolean;
var
cnt: SizeInt;
begin
cnt := A.ElemCount;
if B.ElemCount = cnt then
Result := THelper.Same(A.FItems[0..Pred(cnt)], B.FItems[0..Pred(cnt)], c)
else
Result := False;
end;
class function TGDelegatedVectorHelper.Same(constref A, B: TLiteVector; c: TOnLess): Boolean;
var
cnt: SizeInt;
begin
cnt := A.Count;
if B.Count = cnt then
Result := THelper.Same(A.FBuffer.FItems[0..Pred(cnt)], B.FBuffer.FItems[0..Pred(cnt)], c)
else
Result := False;
end;
class procedure TGDelegatedVectorHelper.IntroSort(v: TVector; c: TOnLess; o: TSortOrder);
begin
v.CheckInIteration;
if v.ElemCount > 1 then
THelper.IntroSort(v.FItems[0..Pred(v.ElemCount)], c, o);
end;
class procedure TGDelegatedVectorHelper.IntroSort(var v: TLiteVector; c: TOnLess; o: TSortOrder);
begin
if v.Count > 1 then
THelper.IntroSort(v.FBuffer.FItems[0..Pred(v.Count)], c, o);
end;
class procedure TGDelegatedVectorHelper.PDQSort(v: TVector; c: TOnLess; o: TSortOrder);
begin
v.CheckInIteration;
if v.ElemCount > 1 then
THelper.PDQSort(v.FItems[0..Pred(v.ElemCount)], c, o);
end;
class procedure TGDelegatedVectorHelper.PDQSort(var v: TLiteVector; c: TOnLess; o: TSortOrder);
begin
if v.Count > 1 then
THelper.PDQSort(v.FBuffer.FItems[0..Pred(v.Count)], c, o);
end;
class procedure TGDelegatedVectorHelper.MergeSort(v: TVector; c: TOnLess; o: TSortOrder);
begin
v.CheckInIteration;
if v.ElemCount > 1 then
THelper.MergeSort(v.FItems[0..Pred(v.ElemCount)], c, o);
end;
class procedure TGDelegatedVectorHelper.MergeSort(var v: TLiteVector; c: TOnLess; o: TSortOrder);
begin
if v.Count > 1 then
THelper.MergeSort(v.FBuffer.FItems[0..Pred(v.Count)], c, o);
end;
class procedure TGDelegatedVectorHelper.Sort(v: TVector; c: TOnLess; o: TSortOrder);
begin
v.CheckInIteration;
if v.ElemCount > 1 then
THelper.Sort(v.FItems[0..Pred(v.ElemCount)], c, o);
end;
class procedure TGDelegatedVectorHelper.Sort(var v: TLiteVector; c: TOnLess; o: TSortOrder);
begin
if v.Count > 1 then
THelper.Sort(v.FBuffer.FItems[0..Pred(v.Count)], c, o);
end;
class function TGDelegatedVectorHelper.SelectDistinct(v: TVector; c: TOnLess): TVector.TArray;
begin
if v.ElemCount > 0 then
Result := THelper.SelectDistinct(v.FItems[0..Pred(v.ElemCount)], c)
else
Result := nil;
end;
class function TGDelegatedVectorHelper.SelectDistinct(constref v: TLiteVector;
c: TOnLess): TLiteVector.TArray;
begin
if v.Count > 0 then
Result := THelper.SelectDistinct(v.FBuffer.FItems[0..Pred(v.Count)], c)
else
Result := nil;
end;
{ TGNestedVectorHelper }
class function TGNestedVectorHelper.SequentSearch(v: TVector; const aValue: T; c: TLess): SizeInt;
begin
if v.ElemCount > 0 then
Result := THelper.SequentSearch(v.FItems[0..Pred(v.ElemCount)], aValue, c)
else
Result := -1;
end;
class function TGNestedVectorHelper.SequentSearch(constref v: TLiteVector; const aValue: T;
c: TLess): SizeInt;
begin
if v.Count > 0 then
Result := THelper.SequentSearch(v.FBuffer.FItems[0..Pred(v.Count)], aValue, c)
else
Result := -1;
end;
class function TGNestedVectorHelper.BinarySearch(v: TVector; const aValue: T; c: TLess): SizeInt;
begin
if v.ElemCount > 0 then
Result := THelper.BinarySearch(v.FItems[0..Pred(v.ElemCount)], aValue, c)
else
Result := -1;
end;
class function TGNestedVectorHelper.BinarySearch(constref v: TLiteVector; const aValue: T;
c: TLess): SizeInt;
begin
if v.Count > 0 then
Result := THelper.BinarySearch(v.FBuffer.FItems[0..Pred(v.Count)], aValue, c)
else
Result := -1;
end;
class function TGNestedVectorHelper.IndexOfMin(v: TVector; c: TLess): SizeInt;
begin
if v.ElemCount > 0 then
Result := THelper.IndexOfMin(v.FItems[0..Pred(v.ElemCount)], c)
else
Result := -1;
end;
class function TGNestedVectorHelper.IndexOfMin(constref v: TLiteVector; c: TLess): SizeInt;
begin
if v.Count > 0 then
Result := THelper.IndexOfMin(v.FBuffer.FItems[0..Pred(v.Count)], c)
else
Result := -1;
end;
class function TGNestedVectorHelper.IndexOfMax(v: TVector; c: TLess): SizeInt;
begin
if v.ElemCount > 0 then
Result := THelper.IndexOfMax(v.FItems[0..Pred(v.ElemCount)], c)
else
Result := -1;
end;
class function TGNestedVectorHelper.IndexOfMax(constref v: TLiteVector; c: TLess): SizeInt;
begin
if v.Count > 0 then
Result := THelper.IndexOfMax(v.FBuffer.FItems[0..Pred(v.Count)], c)
else
Result := -1;
end;
class function TGNestedVectorHelper.GetMin(v: TVector; c: TLess): TOptional;
begin
if v.ElemCount > 0 then
Result := THelper.GetMin(v.FItems[0..Pred(v.ElemCount)], c);
end;
class function TGNestedVectorHelper.GetMin(constref v: TLiteVector; c: TLess): TOptional;
begin
if v.Count > 0 then
Result := THelper.GetMin(v.FBuffer.FItems[0..Pred(v.Count)], c);
end;
class function TGNestedVectorHelper.GetMax(v: TVector; c: TLess): TOptional;
begin
if v.ElemCount > 0 then
Result := THelper.GetMax(v.FItems[0..Pred(v.ElemCount)], c);
end;
class function TGNestedVectorHelper.GetMax(constref v: TLiteVector; c: TLess): TOptional;
begin
if v.Count > 0 then
Result := THelper.GetMax(v.FBuffer.FItems[0..Pred(v.Count)], c);
end;
class function TGNestedVectorHelper.FindMin(v: TVector; out aValue: T; c: TLess): Boolean;
begin
if v.ElemCount > 0 then
Result := THelper.FindMin(v.FItems[0..Pred(v.ElemCount)], aValue, c)
else
Result := False;
end;
class function TGNestedVectorHelper.FindMin(constref v: TLiteVector; out aValue: T; c: TLess): Boolean;
begin
if v.Count > 0 then
Result := THelper.FindMin(v.FBuffer.FItems[0..Pred(v.Count)], aValue, c)
else
Result := False;
end;
class function TGNestedVectorHelper.FindMax(v: TVector; out aValue: T; c: TLess): Boolean;
begin
if v.ElemCount > 0 then
Result := THelper.FindMax(v.FItems[0..Pred(v.ElemCount)], aValue, c)
else
Result := False;
end;
class function TGNestedVectorHelper.FindMax(constref v: TLiteVector; out aValue: T; c: TLess): Boolean;
begin
if v.Count > 0 then
Result := THelper.FindMax(v.FBuffer.FItems[0..Pred(v.Count)], aValue, c)
else
Result := False;
end;
class function TGNestedVectorHelper.FindMinMax(v: TVector; out aMin, aMax: T; c: TLess): Boolean;
begin
if v.ElemCount > 0 then
Result := THelper.FindMinMax(v.FItems[0..Pred(v.ElemCount)], aMin, aMax, c)
else
Result := False;
end;
class function TGNestedVectorHelper.FindMinMax(constref v: TLiteVector; out aMin, aMax: T; c: TLess): Boolean;
begin
if v.Count > 0 then
Result := THelper.FindMinMax(v.FBuffer.FItems[0..Pred(v.Count)], aMin, aMax, c)
else
Result := False;
end;
class function TGNestedVectorHelper.FindNthSmallest(v: TVector; N: SizeInt; out aValue: T; c: TLess): Boolean;
begin
if v.ElemCount > 0 then
Result := THelper.FindNthSmallestND(v.FItems[0..Pred(v.ElemCount)], N, aValue, c)
else
Result := False;
end;
class function TGNestedVectorHelper.FindNthSmallest(constref v: TLiteVector; N: SizeInt; out aValue: T;
c: TLess): Boolean;
begin
if v.Count > 0 then
Result := THelper.FindNthSmallestND(v.FBuffer.FItems[0..Pred(v.Count)], N, aValue, c)
else
Result := False;
end;
class function TGNestedVectorHelper.NthSmallest(v: TVector; N: SizeInt; c: TLess): TOptional;
begin
if v.ElemCount > 0 then
Result := THelper.NthSmallestND(v.FItems[0..Pred(v.ElemCount)], N, c);
end;
class function TGNestedVectorHelper.NthSmallest(constref v: TLiteVector; N: SizeInt; c: TLess): TOptional;
begin
if v.Count > 0 then
Result := THelper.NthSmallestND(v.FBuffer.FItems[0..Pred(v.Count)], N, c);
end;
class function TGNestedVectorHelper.NextPermutation2Asc(v: TVector; c: TLess): Boolean;
begin
v.CheckInIteration;
if v.ElemCount > 1 then
Result := THelper.NextPermutation2Asc(v.FItems[0..Pred(v.ElemCount)], c)
else
Result := False;
end;
class function TGNestedVectorHelper.NextPermutation2Asc(var v: TLiteVector; c: TLess): Boolean;
begin
if v.Count > 1 then
Result := THelper.NextPermutation2Asc(v.FBuffer.FItems[0..Pred(v.Count)], c)
else
Result := False;
end;
class function TGNestedVectorHelper.NextPermutation2Desc(v: TVector; c: TLess): Boolean;
begin
v.CheckInIteration;
if v.ElemCount > 1 then
Result := THelper.NextPermutation2Desc(v.FItems[0..Pred(v.ElemCount)], c)
else
Result := False;
end;
class function TGNestedVectorHelper.NextPermutation2Desc(var v: TLiteVector; c: TLess): Boolean;
begin
if v.Count > 1 then
Result := THelper.NextPermutation2Desc(v.FBuffer.FItems[0..Pred(v.Count)], c)
else
Result := False;
end;
class function TGNestedVectorHelper.IsNonDescending(v: TVector; c: TLess): Boolean;
begin
if v.ElemCount > 0 then
Result := THelper.IsNonDescending(v.FItems[0..Pred(v.ElemCount)], c)
else
Result := True;
end;
class function TGNestedVectorHelper.IsNonDescending(constref v: TLiteVector; c: TLess): Boolean;
begin
if v.Count > 0 then
Result := THelper.IsNonDescending(v.FBuffer.FItems[0..Pred(v.Count)], c)
else
Result := True;
end;
class function TGNestedVectorHelper.IsStrictAscending(v: TVector; c: TLess): Boolean;
begin
if v.ElemCount > 1 then
Result := THelper.IsStrictAscending(v.FItems[0..Pred(v.ElemCount)], c)
else
Result := False;
end;
class function TGNestedVectorHelper.IsStrictAscending(constref v: TLiteVector; c: TLess): Boolean;
begin
if v.Count > 1 then
Result := THelper.IsStrictAscending(v.FBuffer.FItems[0..Pred(v.Count)], c)
else
Result := False;
end;
class function TGNestedVectorHelper.IsNonAscending(v: TVector; c: TLess): Boolean;
begin
if v.ElemCount > 0 then
Result := THelper.IsNonAscending(v.FItems[0..Pred(v.ElemCount)], c)
else
Result := True;
end;
class function TGNestedVectorHelper.IsNonAscending(constref v: TLiteVector; c: TLess): Boolean;
begin
if v.Count > 0 then
Result := THelper.IsNonAscending(v.FBuffer.FItems[0..Pred(v.Count)], c)
else
Result := True;
end;
class function TGNestedVectorHelper.IsStrictDescending(v: TVector; c: TLess): Boolean;
begin
if v.ElemCount > 1 then
Result := THelper.IsStrictDescending(v.FItems[0..Pred(v.ElemCount)], c)
else
Result := False;
end;
class function TGNestedVectorHelper.IsStrictDescending(constref v: TLiteVector; c: TLess): Boolean;
begin
if v.Count > 1 then
Result := THelper.IsStrictDescending(v.FBuffer.FItems[0..Pred(v.Count)], c)
else
Result := False;
end;
class function TGNestedVectorHelper.Same(A, B: TVector; c: TLess): Boolean;
var
cnt: SizeInt;
begin
cnt := A.ElemCount;
if B.ElemCount = cnt then
Result := THelper.Same(A.FItems[0..Pred(cnt)], B.FItems[0..Pred(cnt)], c)
else
Result := False;
end;
class function TGNestedVectorHelper.Same(constref A, B: TLiteVector; c: TLess): Boolean;
var
cnt: SizeInt;
begin
cnt := A.Count;
if B.Count = cnt then
Result := THelper.Same(A.FBuffer.FItems[0..Pred(cnt)], B.FBuffer.FItems[0..Pred(cnt)], c)
else
Result := False;
end;
class procedure TGNestedVectorHelper.IntroSort(v: TVector; c: TLess; o: TSortOrder);
begin
v.CheckInIteration;
if v.ElemCount > 1 then
THelper.IntroSort(v.FItems[0..Pred(v.ElemCount)], c, o);
end;
class procedure TGNestedVectorHelper.IntroSort(var v: TLiteVector; c: TLess; o: TSortOrder);
begin
if v.Count > 1 then
THelper.IntroSort(v.FBuffer.FItems[0..Pred(v.Count)], c, o);
end;
class procedure TGNestedVectorHelper.PDQSort(v: TVector; c: TLess; o: TSortOrder);
begin
v.CheckInIteration;
if v.ElemCount > 1 then
THelper.PDQSort(v.FItems[0..Pred(v.ElemCount)], c, o);
end;
class procedure TGNestedVectorHelper.PDQSort(var v: TLiteVector; c: TLess; o: TSortOrder);
begin
if v.Count > 1 then
THelper.PDQSort(v.FBuffer.FItems[0..Pred(v.Count)], c, o);
end;
class procedure TGNestedVectorHelper.MergeSort(v: TVector; c: TLess; o: TSortOrder);
begin
v.CheckInIteration;
if v.ElemCount > 1 then
THelper.MergeSort(v.FItems[0..Pred(v.ElemCount)], c, o);
end;
class procedure TGNestedVectorHelper.MergeSort(var v: TLiteVector; c: TLess; o: TSortOrder);
begin
if v.Count > 1 then
THelper.MergeSort(v.FBuffer.FItems[0..Pred(v.Count)], c, o);
end;
class procedure TGNestedVectorHelper.Sort(v: TVector; c: TLess; o: TSortOrder);
begin
v.CheckInIteration;
if v.ElemCount > 1 then
THelper.Sort(v.FItems[0..Pred(v.ElemCount)], c, o);
end;
class procedure TGNestedVectorHelper.Sort(var v: TLiteVector; c: TLess; o: TSortOrder);
begin
if v.Count > 1 then
THelper.Sort(v.FBuffer.FItems[0..Pred(v.Count)], c, o);
end;
class function TGNestedVectorHelper.SelectDistinct(v: TVector; c: TLess): TVector.TArray;
begin
if v.ElemCount > 0 then
Result := THelper.SelectDistinct(v.FItems[0..Pred(v.ElemCount)], c)
else
Result := nil;
end;
class function TGNestedVectorHelper.SelectDistinct(constref v: TLiteVector; c: TLess): TVector.TArray;
begin
if v.Count > 0 then
Result := THelper.SelectDistinct(v.FBuffer.FItems[0..Pred(v.Count)], c)
else
Result := nil;
end;
{ TGOrdVectorHelper }
class procedure TGOrdVectorHelper.RadixSort(v: TVector; o: TSortOrder);
begin
v.CheckInIteration;
if v.ElemCount > 1 then
THelper.RadixSort(v.FItems[0..Pred(v.ElemCount)], o);
end;
class procedure TGOrdVectorHelper.RadixSort(var v: TLiteVector; o: TSortOrder);
begin
if v.Count > 1 then
THelper.RadixSort(v.FBuffer.FItems[0..Pred(v.Count)], o);
end;
class procedure TGOrdVectorHelper.RadixSort(v: TVector; var aBuf: TArray; o: TSortOrder);
begin
v.CheckInIteration;
if v.ElemCount > 1 then
THelper.RadixSort(v.FItems[0..Pred(v.ElemCount)], aBuf, o);
end;
class procedure TGOrdVectorHelper.RadixSort(var v: TLiteVector; var aBuf: TArray; o: TSortOrder);
begin
if v.Count > 1 then
THelper.RadixSort(v.FBuffer.FItems[0..Pred(v.Count)], aBuf, o);
end;
class procedure TGOrdVectorHelper.Sort(v: TVector; o: TSortOrder);
begin
v.CheckInIteration;
if v.ElemCount > 1 then
THelper.Sort(v.FItems[0..Pred(v.ElemCount)], o);
end;
class procedure TGOrdVectorHelper.Sort(var v: TLiteVector; o: TSortOrder);
begin
if v.Count > 1 then
THelper.Sort(v.FBuffer.FItems[0..Pred(v.Count)], o);
end;
{ TGRadixVectorSorter }
class procedure TGRadixVectorSorter.Sort(v: TVector; o: TSortOrder);
begin
v.CheckInIteration;
if v.ElemCount > 1 then
THelper.Sort(v.FItems[0..Pred(v.ElemCount)], o);
end;
class procedure TGRadixVectorSorter.Sort(var v: TLiteVector; o: TSortOrder);
begin
if v.Count > 1 then
THelper.Sort(v.FBuffer.FItems[0..Pred(v.Count)], o);
end;
class procedure TGRadixVectorSorter.Sort(v: TVector; var aBuf: TArray; o: TSortOrder);
begin
v.CheckInIteration;
if v.ElemCount > 1 then
THelper.Sort(v.FItems[0..Pred(v.ElemCount)], aBuf, o);
end;
class procedure TGRadixVectorSorter.Sort(var v: TLiteVector; var aBuf: TArray; o: TSortOrder);
begin
if v.Count > 1 then
THelper.Sort(v.FBuffer.FItems[0..Pred(v.Count)], aBuf, o);
end;
end.
| 0 | 0.950916 | 1 | 0.950916 | game-dev | MEDIA | 0.502212 | game-dev | 0.969087 | 1 | 0.969087 |
LHuHyeon/Unity3D_RPG_Portfolio | 1,787 | Scripts/Scenes/GameScene.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/*
* File : GameScene.cs
* Desc : GameScene이 Load되면 호출된다. ( 플레이어, PlayScene 등 생성 )
*/
public class GameScene : BaseScene
{
[SerializeField]
Transform playerSpawn;
protected override void Init()
{
base.Init();
SceneType = Define.Scene.Game; // 타입 설정
Managers.Game.defualtSpawn = playerSpawn.position;
// 플레이어 캐릭터 생성
if (Managers.Game.GetPlayer().IsFakeNull() == true)
{
GameObject _player = Managers.Game.Spawn(Define.WorldObject.Player, "Player");
_player.transform.position = playerSpawn.position;
DontDestroyOnLoad(_player);
}
// UI 생성
if (Managers.Game._playScene.IsFakeNull() == true)
{
Managers.Game.Init();
Managers.Game._playScene = Managers.UI.ShowSceneUI<UI_PlayScene>();
DontDestroyOnLoad(Managers.Game._playScene.gameObject);
}
else
Managers.Game._playScene.IsMiniMap(true);
// 플레이어 세이브 위치 이동
if (Managers.Game.CurrentPos != Vector3.zero)
Managers.Game.GetPlayer().transform.position = Managers.Game.CurrentPos;
// 클릭 Effect 생성
if (Managers.Game.GetPlayer().IsFakeNull() == false)
{
GameObject clickMoveEffect = Managers.Resource.Instantiate("Effect/ClickMoveEffect");
clickMoveEffect.SetActive(false);
Managers.Game.GetPlayer().GetComponent<PlayerController>().clickMoveEffect = clickMoveEffect;
}
// 카메라 조정
Camera.main.gameObject.GetOrAddComponent<CameraController>().SetPlayer(Managers.Game.GetPlayer());
}
public override void Clear()
{
}
}
| 0 | 0.683742 | 1 | 0.683742 | game-dev | MEDIA | 0.91836 | game-dev | 0.833065 | 1 | 0.833065 |
pyfa-org/eos | 3,290 | tests/integration/calculator/mod_operator/test_post_div.py | # ==============================================================================
# Copyright (C) 2011 Diego Duclos
# Copyright (C) 2011-2018 Anton Vorobyov
#
# This file is part of Eos.
#
# Eos is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Eos is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Eos. If not, see <http://www.gnu.org/licenses/>.
# ==============================================================================
from eos import Implant
from eos import Rig
from eos.const.eos import ModAffecteeFilter
from eos.const.eos import ModDomain
from eos.const.eos import ModOperator
from eos.const.eve import EffectCategoryId
from tests.integration.calculator.testcase import CalculatorTestCase
class TestOperatorPostDiv(CalculatorTestCase):
def setUp(self):
CalculatorTestCase.setUp(self)
self.tgt_attr = self.mkattr()
src_attr = self.mkattr()
modifier = self.mkmod(
affectee_filter=ModAffecteeFilter.domain,
affectee_domain=ModDomain.ship,
affectee_attr_id=self.tgt_attr.id,
operator=ModOperator.post_div,
affector_attr_id=src_attr.id)
effect = self.mkeffect(
category_id=EffectCategoryId.passive, modifiers=[modifier])
self.influence_src1 = Implant(self.mktype(
attrs={src_attr.id: 1.2}, effects=[effect]).id)
self.influence_src2 = Implant(self.mktype(
attrs={src_attr.id: 1.5}, effects=[effect]).id)
self.influence_src3 = Implant(self.mktype(
attrs={src_attr.id: 0.1}, effects=[effect]).id)
self.influence_src4 = Implant(self.mktype(
attrs={src_attr.id: 0.75}, effects=[effect]).id)
self.influence_src5 = Implant(self.mktype(
attrs={src_attr.id: 5}, effects=[effect]).id)
self.influence_tgt = Rig(self.mktype(attrs={self.tgt_attr.id: 100}).id)
self.fit.implants.add(self.influence_src1)
self.fit.implants.add(self.influence_src2)
self.fit.implants.add(self.influence_src3)
self.fit.implants.add(self.influence_src4)
self.fit.implants.add(self.influence_src5)
self.fit.rigs.add(self.influence_tgt)
def test_unpenalized(self):
self.tgt_attr.stackable = True
# Verification
self.assertAlmostEqual(
self.influence_tgt.attrs[self.tgt_attr.id], 148.148, places=3)
# Cleanup
self.assert_solsys_buffers_empty(self.fit.solar_system)
self.assert_log_entries(0)
def test_penalized(self):
self.tgt_attr.stackable = False
# Verification
self.assertAlmostEqual(
self.influence_tgt.attrs[self.tgt_attr.id], 165.791, places=3)
# Cleanup
self.assert_solsys_buffers_empty(self.fit.solar_system)
self.assert_log_entries(0)
| 0 | 0.69686 | 1 | 0.69686 | game-dev | MEDIA | 0.33398 | game-dev | 0.674022 | 1 | 0.674022 |
redscientistlabs/RTCV | 19,510 | Source/Libraries/CorruptCore/Stockpile/StockpileManagerUISide.cs | namespace RTCV.CorruptCore
{
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using RTCV.NetCore;
public static class StockpileManagerUISide
{
//Object references
private static Stockpile CurrentStockpile { get; set; }
private static StashKey _lastStashKey = null;
public static StashKey LastStashkey => _lastStashKey;
private static StashKey _currentStashKey = null;
public static StashKey CurrentStashkey
{
get
{
return _currentStashKey;
}
set
{
_lastStashKey = CurrentStashkey;
_currentStashKey = value;
}
}
public static StashKey CurrentSavestateStashKey { get; set; }
[SuppressMessage("Microsoft.Design", "CA2211", Justification = "This field cannot be made private or const because it is used by stubs")]
public static volatile StashKey BackupedState;
public static bool StashAfterOperation { get; set; } = true;
public static readonly List<StashKey> StashHistory = new List<StashKey>();
private static void PreApplyStashkey(bool _clearUnitsBeforeApply = true)
{
if (_clearUnitsBeforeApply)
{
LocalNetCoreRouter.Route(NetCore.Endpoints.CorruptCore, NetCore.Commands.Remote.ClearStepBlastUnits, null, true);
}
bool UseSavestates = (bool)AllSpec.VanguardSpec[VSPEC.SUPPORTS_SAVESTATES];
LocalNetCoreRouter.Route(NetCore.Endpoints.Vanguard, NetCore.Commands.Remote.PreCorruptAction, null, true);
}
private static void PostApplyStashkey(StashKey sk)
{
bool UseSavestates = (bool)AllSpec.VanguardSpec[VSPEC.SUPPORTS_SAVESTATES];
bool UseRealtime = (bool)AllSpec.VanguardSpec[VSPEC.SUPPORTS_REALTIME];
if (Render.RenderAtLoad && UseRealtime)
{
Render.StartRender();
}
LocalNetCoreRouter.Route(NetCore.Endpoints.Vanguard, NetCore.Commands.Remote.PostCorruptAction);
SyncObjectSingleton.FormExecute(() =>
{
UISideHooks.OnStashkeyLoaded(sk);
});
}
public static bool ApplyStashkey(StashKey sk, bool loadBeforeOperation = true, bool clearUnitsBeforeApply = true)
{
PreApplyStashkey(clearUnitsBeforeApply);
bool isCorruptionApplied = sk?.BlastLayer?.Layer?.Count > 0;
if (loadBeforeOperation)
{
if (!LoadState(sk))
{
return isCorruptionApplied;
}
}
else
{
bool mergeWithCurrent = !clearUnitsBeforeApply;
//APPLYBLASTLAYER
//Param 0 is BlastLayer
//Param 1 is storeUncorruptBackup
//Param 2 is MergeWithCurrent (for fixing blast toggle with inject)
LocalNetCoreRouter.Route(NetCore.Endpoints.CorruptCore, NetCore.Commands.Basic.ApplyBlastLayer, new object[] { sk?.BlastLayer, true, mergeWithCurrent }, true);
}
PostApplyStashkey(sk);
return isCorruptionApplied;
}
public static void Import(BlastLayer importedBlastLayer)
{
string saveStateWord = "Savestate";
object renameSaveStateWord = AllSpec.VanguardSpec[VSPEC.RENAME_SAVESTATE];
if (renameSaveStateWord != null && renameSaveStateWord is string s)
{
saveStateWord = s;
}
StashKey psk = CurrentSavestateStashKey;
bool UseSavestates = (bool)AllSpec.VanguardSpec[VSPEC.SUPPORTS_SAVESTATES];
if (!UseSavestates)
{
psk = SaveState();
}
if (psk == null && UseSavestates)
{
MessageBox.Show($"The Glitch Harvester could not perform the IMPORT action\n\nEither no {saveStateWord} Box was selected in the {saveStateWord} Manager\nor the {saveStateWord} Box itself is empty.");
return;
}
//We make it without the blastlayer so we can send it across and use the cached version without needing a prototype
CurrentStashkey = new StashKey(RtcCore.GetRandomKey(), psk.ParentKey, null)
{
RomFilename = psk.RomFilename,
SystemName = psk.SystemName,
SystemCore = psk.SystemCore,
GameName = psk.GameName,
SyncSettings = psk.SyncSettings,
StateLocation = psk.StateLocation
};
BlastLayer bl = importedBlastLayer;
CurrentStashkey.BlastLayer = bl;
StashHistory.Add(CurrentStashkey);
}
public static bool Corrupt(bool loadBeforeOperation = true)
{
string saveStateWord = "Savestate";
object renameSaveStateWord = AllSpec.VanguardSpec[VSPEC.RENAME_SAVESTATE];
if (renameSaveStateWord != null && renameSaveStateWord is string s)
{
saveStateWord = s;
}
PreApplyStashkey();
StashKey psk = CurrentSavestateStashKey;
bool UseSavestates = (bool)AllSpec.VanguardSpec[VSPEC.SUPPORTS_SAVESTATES];
if (!UseSavestates)
{
psk = SaveState();
}
if (psk == null && UseSavestates)
{
MessageBox.Show($"The Glitch Harvester could not perform the CORRUPT action\n\nEither no {saveStateWord} Box was selected in the {saveStateWord} Manager\nor the {saveStateWord} Box itself is empty.");
return false;
}
string currentGame = (string)AllSpec.VanguardSpec[VSPEC.GAMENAME];
string currentCore = (string)AllSpec.VanguardSpec[VSPEC.SYSTEMCORE];
if (UseSavestates && (currentGame == null || psk.GameName != currentGame || psk.SystemCore != currentCore))
{
LocalNetCoreRouter.Route(NetCore.Endpoints.Vanguard, NetCore.Commands.Remote.LoadROM, psk.RomFilename, true);
}
//We make it without the blastlayer so we can send it across and use the cached version without needing a prototype
CurrentStashkey = new StashKey(RtcCore.GetRandomKey(), psk.ParentKey, null)
{
RomFilename = psk.RomFilename,
SystemName = psk.SystemName,
SystemCore = psk.SystemCore,
GameName = psk.GameName,
SyncSettings = psk.SyncSettings,
StateLocation = psk.StateLocation
};
BlastLayer bl = LocalNetCoreRouter.QueryRoute<BlastLayer>(NetCore.Endpoints.CorruptCore, NetCore.Commands.Basic.GenerateBlastLayer,
new object[]
{
CurrentStashkey,
loadBeforeOperation,
true,
true
}, true);
bool isCorruptionApplied = bl?.Layer?.Count > 0;
CurrentStashkey.BlastLayer = bl;
if (StashAfterOperation && bl != null)
{
StashHistory.Add(CurrentStashkey);
}
PostApplyStashkey(CurrentStashkey);
return isCorruptionApplied;
}
public static void RemoveFirstStashItem()
{
StashHistory.RemoveAt(0);
}
public static bool InjectFromStashkey(StashKey sk, bool loadBeforeOperation = true)
{
string saveStateWord = "Savestate";
object renameSaveStateWord = AllSpec.VanguardSpec[VSPEC.RENAME_SAVESTATE];
if (renameSaveStateWord != null && renameSaveStateWord is string s)
{
saveStateWord = s;
}
PreApplyStashkey();
StashKey psk = CurrentSavestateStashKey;
if (psk == null)
{
MessageBox.Show($"The Glitch Harvester could not perform the INJECT action\n\nEither no {saveStateWord} Box was selected in the {saveStateWord} Manager\nor the {saveStateWord} Box itself is empty.");
return false;
}
if (sk == null)
{
throw new ArgumentNullException(nameof(sk));
}
if (psk.SystemCore != sk.SystemCore && !RtcCore.AllowCrossCoreCorruption)
{
MessageBox.Show("Merge attempt failed: Core mismatch\n\n" + $"{psk.GameName} -> {psk.SystemName} -> {psk.SystemCore}\n{sk.GameName} -> {sk.SystemName} -> {sk.SystemCore}");
return false;
}
CurrentStashkey = new StashKey(RtcCore.GetRandomKey(), psk.ParentKey, sk.BlastLayer)
{
RomFilename = psk.RomFilename,
SystemName = psk.SystemName,
SystemCore = psk.SystemCore,
GameName = psk.GameName,
SyncSettings = psk.SyncSettings,
StateLocation = psk.StateLocation
};
if (loadBeforeOperation)
{
if (!LoadState(CurrentStashkey))
{
return false;
}
}
else
{
LocalNetCoreRouter.Route(NetCore.Endpoints.CorruptCore, NetCore.Commands.Basic.ApplyBlastLayer, new object[] { CurrentStashkey.BlastLayer, true }, true);
}
bool isCorruptionApplied = CurrentStashkey?.BlastLayer?.Layer?.Count > 0;
if (StashAfterOperation)
{
StashHistory.Add(CurrentStashkey);
}
PostApplyStashkey(sk);
return isCorruptionApplied;
}
public static bool OriginalFromStashkey(StashKey sk)
{
PreApplyStashkey();
if (sk == null)
{
MessageBox.Show("No StashKey could be loaded");
return false;
}
bool isCorruptionApplied = false;
if (!LoadState(sk, true, false))
{
return isCorruptionApplied;
}
PostApplyStashkey(sk);
return isCorruptionApplied;
}
public static bool MergeStashkeys(List<StashKey> sks, bool loadBeforeOperation = true)
{
PreApplyStashkey();
if (sks != null && sks.Count > 1)
{
StashKey master = sks[0];
string masterSystemCore = master.SystemCore;
bool allCoresIdentical = true;
foreach (StashKey item in sks)
{
if (item.SystemCore != master.SystemCore)
{
allCoresIdentical = false;
break;
}
}
if (!allCoresIdentical && !RtcCore.AllowCrossCoreCorruption)
{
MessageBox.Show("Merge attempt failed: Core mismatch\n\n" + string.Join("\n", sks.Select(it => $"{it.GameName} -> {it.SystemName} -> {it.SystemCore}")));
return false;
}
if (!RtcCore.AllowCrossCoreCorruption)
{
foreach (StashKey item in sks)
{
if (item.GameName != master.GameName)
{
MessageBox.Show("Merge attempt failed: game mismatch\n\n" + string.Join("\n", sks.Select(it => $"{it.GameName} -> {it.SystemName} -> {it.SystemCore}")));
return false;
}
}
}
BlastLayer bl = new BlastLayer();
foreach (StashKey item in sks)
{
bl.Layer.AddRange(item.BlastLayer.Layer);
}
bl.Layer = bl.Layer.Distinct().ToList();
CurrentStashkey = new StashKey(RtcCore.GetRandomKey(), master.ParentKey, bl)
{
RomFilename = master.RomFilename,
SystemName = master.SystemName,
SystemCore = master.SystemCore,
GameName = master.GameName,
SyncSettings = master.SyncSettings,
StateLocation = master.StateLocation
};
bool isCorruptionApplied = CurrentStashkey?.BlastLayer?.Layer?.Count > 0;
if (loadBeforeOperation)
{
if (!LoadState(CurrentStashkey))
{
return isCorruptionApplied;
}
}
else
{
LocalNetCoreRouter.Route(NetCore.Endpoints.CorruptCore, NetCore.Commands.Basic.ApplyBlastLayer, new object[] { CurrentStashkey.BlastLayer, true }, true);
}
if (StashAfterOperation)
{
StashHistory.Add(CurrentStashkey);
}
PostApplyStashkey(CurrentStashkey);
return true;
}
MessageBox.Show("You need 2 or more items for Merging");
return false;
}
public static bool LoadState(StashKey sk, bool reloadRom = true, bool applyBlastLayer = true)
{
bool success = LocalNetCoreRouter.QueryRoute<bool>(NetCore.Endpoints.CorruptCore, NetCore.Commands.Remote.LoadState, new object[] { sk, reloadRom, applyBlastLayer }, true);
return success;
}
public static StashKey SaveState(StashKey sk = null)
{
bool UseSavestates = (bool)AllSpec.VanguardSpec[VSPEC.SUPPORTS_SAVESTATES];
if (UseSavestates)
{
return LocalNetCoreRouter.QueryRoute<StashKey>(NetCore.Endpoints.CorruptCore, NetCore.Commands.Remote.SaveState, sk, true);
}
else
{
return LocalNetCoreRouter.QueryRoute<StashKey>(NetCore.Endpoints.CorruptCore, NetCore.Commands.Remote.SaveStateless, sk, true);
}
}
public static void StockpileChanged()
{
//S.GET<RTC_StockpileBlastBoard_Form>().RefreshButtons();
}
public static bool AddCurrentStashkeyToStash(bool stashAfterOperation = true)
{
bool isCorruptionApplied = CurrentStashkey?.BlastLayer?.Layer?.Count > 0;
if (isCorruptionApplied && StashAfterOperation && stashAfterOperation)
{
StashHistory.Add(CurrentStashkey);
}
return isCorruptionApplied;
}
/// <summary>
/// Takes a stashkey and a list of keys, fixing the path and if a list of keys is provided, it'll look for all shared references and update them
/// </summary>
/// <param name="psk"></param>
/// <param name="force"></param>
/// <param name="keys"></param>
/// <returns></returns>
public static bool CheckAndFixMissingReference(StashKey psk, bool force = false, List<StashKey> keys = null, string customTitle = null, string customMessage = null)
{
if (psk == null)
{
throw new ArgumentNullException(nameof(psk));
}
if (!(bool?)AllSpec.VanguardSpec[VSPEC.SUPPORTS_REFERENCES] ?? false)
{
//Hack hack hack
//In pre-504, some stubs would save references. This results in a fun infinite loop
//As such, delete the referenced file because it doesn't matter as the implementation doesn't support references
//Only do this if we explicitly know that the references are not supported. If there's missing spec info, don't do it.
if (!(bool?)AllSpec.VanguardSpec[VSPEC.SUPPORTS_REFERENCES] == true)
{
try
{
File.Delete(psk.RomFilename);
}
catch (Exception ex)
{
Common.Logging.GlobalLogger.Error(ex,
"Som-ething went terribly wrong when fixing missing references\n" +
"Your stockpile should be fine (might prompt you to fix it on load)" +
"Report this to the devs.");
}
psk.RomFilename = "";
return true;
}
}
string message = customMessage ?? $"Can't find file {psk.RomFilename}\nGame name: {psk.GameName}\nSystem name: {psk.SystemName}\n\n To continue loading, provide a new file for replacement.";
string title = customTitle ?? "Error: File not found";
if ((force || !File.Exists(psk.RomFilename)) && !psk.RomFilename.EndsWith("IGNORE"))
{
if (DialogResult.OK == MessageBox.Show(message, title, MessageBoxButtons.OKCancel))
{
OpenFileDialog ofd = new OpenFileDialog
{
DefaultExt = "*",
Title = "Select Replacement File",
Filter = $"Any file|*.*",
RestoreDirectory = true
};
if (ofd.ShowDialog() == DialogResult.OK)
{
string filename = ofd.FileName;
string oldFilename = psk.RomFilename;
if (Path.GetFileName(psk.RomFilename) != Path.GetFileName(filename))
{
if (DialogResult.Cancel == MessageBox.Show($"Selected file {Path.GetFileName(filename)} has a different name than the old file {Path.GetFileName(psk.RomFilename)}.\nIf you know this file is correct, you can ignore this warning.\nContinue?", title,
MessageBoxButtons.OKCancel))
{
return false;
}
}
foreach (var sk in keys.Where(x => x.RomFilename == oldFilename))
{
sk.RomFilename = filename;
sk.RomShortFilename = Path.GetFileName(sk.RomFilename);
}
}
else
{
return false;
}
}
else
{
return false;
}
}
return true;
}
public static void ClearCurrentStockpile()
{
CurrentStockpile = new Stockpile();
StockpileChanged();
}
public static string GetCurrentStockpilePath()
{
return CurrentStockpile?.Filename ?? "";
}
public static void SetCurrentStockpile(Stockpile sks)
{
CurrentStockpile = sks;
StockpileChanged();
}
}
}
| 0 | 0.962394 | 1 | 0.962394 | game-dev | MEDIA | 0.650451 | game-dev | 0.943752 | 1 | 0.943752 |
SirPlease/L4D2-Competitive-Rework | 13,993 | addons/sourcemod/scripting/l4d2_tank_props_glow.sp | #pragma semicolon 1
#pragma newdecls required
#include <sourcemod>
#include <sdkhooks>
#include <sdktools>
#include <dhooks>
#undef REQUIRE_PLUGIN
#include <l4d2_hittable_control>
#define Z_TANK 8
#define TEAM_INFECTED 3
#define TEAM_SPECTATOR 1
#define MAX_EDICTS 2048 //(1 << 11)
ConVar
g_hTankPropFade = null,
g_hCvartankPropsGlow = null,
g_hCvarRange = null,
g_hCvarRangeMin = null,
g_hCvarColor = null,
g_hCvarTankOnly = null,
g_hCvarTankSpec = null,
g_hCvarTankPropsBeGone = null;
ArrayList
g_hTankProps = null,
g_hTankPropsHit = null;
int
g_iEntityList[MAX_EDICTS] = {-1, ...},
g_iTankClient = -1,
g_iCvarRange = 0,
g_iCvarRangeMin = 0,
g_iCvarColor = 0;
bool
g_bCvarTankOnly = false,
g_bCvarTankSpec = false,
g_bTankSpawned = false,
g_bHittableControlExists = false;
public Plugin myinfo =
{
name = "L4D2 Tank Hittable Glow",
author = "Harry Potter, Sir, A1m`, Derpduck",
version = "2.5",
description = "Stop tank props from fading whilst the tank is alive + add Hittable Glow."
};
public void OnPluginStart()
{
g_hCvartankPropsGlow = CreateConVar("l4d_tank_props_glow", "1", "Show Hittable Glow for infected team while the tank is alive", FCVAR_NOTIFY);
g_hCvarColor = CreateConVar("l4d2_tank_prop_glow_color", "255 255 255", "Prop Glow Color, three values between 0-255 separated by spaces. RGB Color255 - Red Green Blue.", FCVAR_NOTIFY);
g_hCvarRange = CreateConVar("l4d2_tank_prop_glow_range", "4500", "How near to props do players need to be to enable their glow.", FCVAR_NOTIFY);
g_hCvarRangeMin = CreateConVar("l4d2_tank_prop_glow_range_min", "256", "How near to props do players need to be to disable their glow.", FCVAR_NOTIFY);
g_hCvarTankOnly = CreateConVar("l4d2_tank_prop_glow_only", "0", "Only Tank can see the glow", FCVAR_NOTIFY);
g_hCvarTankSpec = CreateConVar("l4d2_tank_prop_glow_spectators", "1", "Spectators can see the glow too", FCVAR_NOTIFY);
g_hCvarTankPropsBeGone = CreateConVar("l4d2_tank_prop_dissapear_time", "10.0", "Time it takes for hittables that were punched by Tank to dissapear after the Tank dies.", FCVAR_NOTIFY);
GetCvars();
g_hTankPropFade = FindConVar("sv_tankpropfade");
g_hCvartankPropsGlow.AddChangeHook(TankPropsGlowAllow);
g_hCvarColor.AddChangeHook(ConVarChanged_Glow);
g_hCvarRange.AddChangeHook(ConVarChanged_Range);
g_hCvarRangeMin.AddChangeHook(ConVarChanged_RangeMin);
g_hCvarTankOnly.AddChangeHook(ConVarChanged_Cvars);
g_hCvarTankSpec.AddChangeHook(ConVarChanged_Cvars);
PluginEnable();
}
public void OnAllPluginsLoaded()
{
g_bHittableControlExists = LibraryExists("l4d2_hittable_control");
}
public void OnLibraryRemoved(const char[] name)
{
if (StrEqual(name, "l4d2_hittable_control", true)) {
g_bHittableControlExists = false;
}
}
public void OnLibraryAdded(const char[] name)
{
if (StrEqual(name, "l4d2_hittable_control", true)) {
g_bHittableControlExists = true;
}
}
void ConVarChanged_Cvars(ConVar hConvar, const char[] sOldValue, const char[] sNewValue)
{
GetCvars();
}
void GetCvars()
{
g_bCvarTankOnly = g_hCvarTankOnly.BoolValue;
g_bCvarTankSpec = g_hCvarTankSpec.BoolValue;
g_iCvarRange = g_hCvarRange.IntValue;
g_iCvarRangeMin = g_hCvarRangeMin.IntValue;
char sColor[16];
g_hCvarColor.GetString(sColor, sizeof(sColor));
g_iCvarColor = GetColor(sColor);
}
void TankPropsGlowAllow(Handle hConVar, const char[] sOldValue, const char[] sNewValue)
{
if (!g_hCvartankPropsGlow.BoolValue) {
PluginDisable();
} else {
PluginEnable();
}
}
void ConVarChanged_Glow(Handle hConVar, const char[] sOldValue, const char[] sNewValue)
{
GetCvars();
if (!g_bTankSpawned) {
return;
}
int iRef = INVALID_ENT_REFERENCE, iValue = 0, iSize = g_hTankPropsHit.Length;
for (int i = 0; i < iSize; i++) {
iValue = g_hTankPropsHit.Get(i);
if (iValue > 0 && IsValidEdict(iValue)) {
iRef = g_iEntityList[iValue];
if (IsValidEntRef(iRef)) {
SetEntProp(iRef, Prop_Send, "m_iGlowType", 3);
SetEntProp(iRef, Prop_Send, "m_glowColorOverride", g_iCvarColor);
}
}
}
}
void ConVarChanged_Range(ConVar hConVar, const char[] sOldValue, const char[] sNewValue)
{
GetCvars();
if (!g_bTankSpawned) {
return;
}
int iRef = INVALID_ENT_REFERENCE, iValue = -1, iSize = g_hTankPropsHit.Length;
for (int i = 0; i < iSize; i++) {
iValue = g_hTankPropsHit.Get(i);
if (iValue > 0 && IsValidEdict(iValue)) {
iRef = g_iEntityList[iValue];
if (IsValidEntRef(iRef)) {
SetEntProp(iRef, Prop_Send, "m_nGlowRange", g_iCvarRange);
}
}
}
}
void ConVarChanged_RangeMin(ConVar hConVar, const char[] sOldValue, const char[] sNewValue)
{
GetCvars();
if (!g_bTankSpawned) {
return;
}
int iRef = INVALID_ENT_REFERENCE, iValue = -1, iSize = g_hTankPropsHit.Length;
for (int i = 0; i < iSize; i++) {
iValue = g_hTankPropsHit.Get(i);
if (iValue > 0 && IsValidEdict(iValue)) {
iRef = g_iEntityList[iValue];
if (IsValidEntRef(iRef)) {
SetEntProp(iRef, Prop_Send, "m_nGlowRangeMin", g_iCvarRangeMin);
}
}
}
}
void PluginEnable()
{
g_hTankPropFade.SetBool(false);
g_hTankProps = new ArrayList();
g_hTankPropsHit = new ArrayList();
HookEvent("round_start", TankPropRoundReset, EventHookMode_PostNoCopy);
HookEvent("round_end", TankPropRoundReset, EventHookMode_PostNoCopy);
HookEvent("tank_spawn", TankPropTankSpawn, EventHookMode_PostNoCopy);
HookEvent("player_death", TankPropTankKilled, EventHookMode_PostNoCopy);
char sColor[16];
g_hCvarColor.GetString(sColor, sizeof(sColor));
g_iCvarColor = GetColor(sColor);
g_iCvarRange = g_hCvarRange.IntValue;
g_iCvarRangeMin = g_hCvarRangeMin.IntValue;
g_bCvarTankOnly = g_hCvarTankOnly.BoolValue;
}
void PluginDisable()
{
g_hTankPropFade.SetBool(true);
UnhookEvent("round_start", TankPropRoundReset, EventHookMode_PostNoCopy);
UnhookEvent("round_end", TankPropRoundReset, EventHookMode_PostNoCopy);
UnhookEvent("tank_spawn", TankPropTankSpawn, EventHookMode_PostNoCopy);
UnhookEvent("player_death", TankPropTankKilled, EventHookMode_PostNoCopy);
if (!g_bTankSpawned) {
return;
}
int iRef = INVALID_ENT_REFERENCE, iValue = -1, iSize = g_hTankPropsHit.Length;
for (int i = 0; i < iSize; i++) {
iValue = g_hTankPropsHit.Get(i);
if (iValue > 0 && IsValidEdict(iValue)) {
iRef = g_iEntityList[iValue];
if (IsValidEntRef(iRef)) {
KillEntity(iRef);
}
}
}
g_bTankSpawned = false;
delete g_hTankProps;
g_hTankProps = null;
delete g_hTankPropsHit;
g_hTankPropsHit = null;
}
public void OnMapEnd()
{
DHookRemoveEntityListener(ListenType_Created, PossibleTankPropCreated);
g_hTankProps.Clear();
g_hTankPropsHit.Clear();
}
void TankPropRoundReset(Event hEvent, const char[] sEventName, bool bDontBroadcast)
{
DHookRemoveEntityListener(ListenType_Created, PossibleTankPropCreated);
g_bTankSpawned = false;
UnhookTankProps();
g_hTankPropsHit.Clear();
}
void TankPropTankSpawn(Event hEvent, const char[] sEventName, bool bDontBroadcast)
{
if (g_bTankSpawned) {
return;
}
UnhookTankProps();
g_hTankPropsHit.Clear();
HookTankProps();
DHookAddEntityListener(ListenType_Created, PossibleTankPropCreated);
g_bTankSpawned = true;
}
/* // error 203: symbol is never used: "PD_ev_EntityKilled"
void PD_ev_EntityKilled(Event hEvent, const char[] sEventName, bool bDontBroadcast)
{
if (!g_bTankSpawned) {
return;
}
int iClient = hEvent.GetInt("entindex_killed");
if (IsValidAliveTank(iClient)) {
CreateTimer(1.5, TankDeadCheck, _, TIMER_FLAG_NO_MAPCHANGE);
}
}
*/
void TankPropTankKilled(Event hEvent, const char[] sEventName, bool bDontBroadcast)
{
if (!g_bTankSpawned) {
return;
}
CreateTimer(0.5, TankDeadCheck, _, TIMER_FLAG_NO_MAPCHANGE);
}
Action TankDeadCheck(Handle hTimer)
{
if (GetTankClient() == -1) {
CreateTimer(g_hCvarTankPropsBeGone.FloatValue, TankPropsBeGone);
DHookRemoveEntityListener(ListenType_Created, PossibleTankPropCreated);
g_bTankSpawned = false;
}
return Plugin_Stop;
}
Action TankPropsBeGone(Handle hTimer)
{
UnhookTankProps();
return Plugin_Stop;
}
void PropDamaged(int iVictim, int iAttacker, int iInflictor, float fDamage, int iDamageType)
{
if (IsValidAliveTank(iAttacker) || g_hTankPropsHit.FindValue(iInflictor) != -1) {
//PrintToChatAll("tank hit %d", iVictim);
if (g_hTankPropsHit.FindValue(iVictim) == -1) {
g_hTankPropsHit.Push(iVictim);
CreateTankPropGlow(iVictim);
}
}
}
void CreateTankPropGlow(int iTarget)
{
// Spawn dynamic prop entity
int iEntity = CreateEntityByName("prop_dynamic_override");
if (iEntity == -1) {
return;
}
// Get position of hittable
float vOrigin[3];
float vAngles[3];
GetEntPropVector(iTarget, Prop_Send, "m_vecOrigin", vOrigin);
GetEntPropVector(iTarget, Prop_Data, "m_angRotation", vAngles);
// Get Client Model
char sModelName[PLATFORM_MAX_PATH];
GetEntPropString(iTarget, Prop_Data, "m_ModelName", sModelName, sizeof(sModelName));
// Set new fake model
SetEntityModel(iEntity, sModelName);
DispatchSpawn(iEntity);
// Set outline glow color
SetEntProp(iEntity, Prop_Send, "m_CollisionGroup", 0);
SetEntProp(iEntity, Prop_Send, "m_nSolidType", 0);
SetEntProp(iEntity, Prop_Send, "m_nGlowRange", g_iCvarRange);
SetEntProp(iEntity, Prop_Send, "m_nGlowRangeMin", g_iCvarRangeMin);
SetEntProp(iEntity, Prop_Send, "m_iGlowType", 2);
SetEntProp(iEntity, Prop_Send, "m_glowColorOverride", g_iCvarColor);
AcceptEntityInput(iEntity, "StartGlowing");
// Set model invisible
SetEntityRenderMode(iEntity, RENDER_NONE);
SetEntityRenderColor(iEntity, 0, 0, 0, 0);
// Set model to hittable position
TeleportEntity(iEntity, vOrigin, vAngles, NULL_VECTOR);
// Set model attach to client, and always synchronize
SetVariantString("!activator");
AcceptEntityInput(iEntity, "SetParent", iTarget);
SDKHook(iEntity, SDKHook_SetTransmit, OnTransmit);
g_iEntityList[iTarget] = EntIndexToEntRef(iEntity);
}
Action OnTransmit(int iEntity, int iClient)
{
switch (GetClientTeam(iClient)) {
case TEAM_INFECTED: {
if (!g_bCvarTankOnly) {
return Plugin_Continue;
}
if (IsTank(iClient)) {
return Plugin_Continue;
}
return Plugin_Handled;
}
case TEAM_SPECTATOR: {
return (g_bCvarTankSpec) ? Plugin_Continue : Plugin_Handled;
}
}
return Plugin_Handled;
}
bool IsTankProp(int iEntity)
{
if (!IsValidEdict(iEntity)) {
return false;
}
// CPhysicsProp only
if (!HasEntProp(iEntity, Prop_Send, "m_hasTankGlow")) {
return false;
}
bool bHasTankGlow = (GetEntProp(iEntity, Prop_Send, "m_hasTankGlow", 1) == 1);
if (!bHasTankGlow) {
return false;
}
// Exception
bool bAreForkliftsUnbreakable;
if (g_bHittableControlExists)
{
bAreForkliftsUnbreakable = AreForkliftsUnbreakable();
}
else
{
bAreForkliftsUnbreakable = false;
}
char sModel[PLATFORM_MAX_PATH];
GetEntPropString(iEntity, Prop_Data, "m_ModelName", sModel, sizeof(sModel));
if (strcmp("models/props/cs_assault/forklift.mdl", sModel) == 0 && bAreForkliftsUnbreakable == false) {
return false;
}
return true;
}
void HookTankProps()
{
int iEntCount = GetMaxEntities();
for (int i = MaxClients; i < iEntCount; i++) {
if (IsTankProp(i)) {
SDKHook(i, SDKHook_OnTakeDamagePost, PropDamaged);
g_hTankProps.Push(i);
}
}
}
void UnhookTankProps()
{
int iValue = 0, iSize = g_hTankProps.Length;
for (int i = 0; i < iSize; i++) {
iValue = g_hTankProps.Get(i);
SDKUnhook(iValue, SDKHook_OnTakeDamagePost, PropDamaged);
}
iValue = 0;
iSize = g_hTankPropsHit.Length;
for (int i = 0; i < iSize; i++) {
iValue = g_hTankPropsHit.Get(i);
if (iValue > 0 && IsValidEdict(iValue)) {
KillEntity(iValue);
//PrintToChatAll("remove %d", iValue);
}
}
g_hTankProps.Clear();
g_hTankPropsHit.Clear();
}
//analogue public void OnEntityCreated(int iEntity, const char[] sClassName)
void PossibleTankPropCreated(int iEntity, const char[] sClassName)
{
if (sClassName[0] != 'p') {
return;
}
if (strcmp(sClassName, "prop_physics") != 0) { // Hooks c11m4_terminal World Sphere
return;
}
// Use SpawnPost to just push it into the Array right away.
// These entities get spawned after the Tank has punched them, so doing anything here will not work smoothly.
SDKHook(iEntity, SDKHook_SpawnPost, Hook_PropSpawned);
}
void Hook_PropSpawned(int iEntity)
{
if (iEntity < MaxClients || !IsValidEntity(iEntity)) {
return;
}
if (g_hTankProps.FindValue(iEntity) == -1) {
char sModelName[PLATFORM_MAX_PATH];
GetEntPropString(iEntity, Prop_Data, "m_ModelName", sModelName, sizeof(sModelName));
if (StrContains(sModelName, "atlas_break_ball") != -1 || StrContains(sModelName, "forklift_brokenlift.mdl") != -1) {
g_hTankProps.Push(iEntity);
g_hTankPropsHit.Push(iEntity);
CreateTankPropGlow(iEntity);
} else if (StrContains(sModelName, "forklift_brokenfork.mdl") != -1) {
KillEntity(iEntity);
}
}
}
bool IsValidEntRef(int iRef)
{
return (iRef > 0 && EntRefToEntIndex(iRef) != INVALID_ENT_REFERENCE);
}
int GetColor(char[] sTemp)
{
if (strcmp(sTemp, "") == 0) {
return 0;
}
char sColors[3][4];
int iColor = ExplodeString(sTemp, " ", sColors, 3, 4);
if (iColor != 3) {
return 0;
}
iColor = StringToInt(sColors[0]);
iColor += 256 * StringToInt(sColors[1]);
iColor += 65536 * StringToInt(sColors[2]);
return iColor;
}
int GetTankClient()
{
if (g_iTankClient == -1 || !IsValidAliveTank(g_iTankClient)) {
g_iTankClient = FindTank();
}
return g_iTankClient;
}
int FindTank()
{
for (int i = 1; i <= MaxClients; i++) {
if (IsAliveTank(i)) {
return i;
}
}
return -1;
}
bool IsValidAliveTank(int iClient)
{
return (iClient > 0 && iClient <= MaxClients && IsAliveTank(iClient));
}
bool IsAliveTank(int iClient)
{
return (IsClientInGame(iClient) && GetClientTeam(iClient) == TEAM_INFECTED && IsTank(iClient));
}
bool IsTank(int iClient)
{
return (GetEntProp(iClient, Prop_Send, "m_zombieClass") == Z_TANK && IsPlayerAlive(iClient));
}
void KillEntity(int iEntity)
{
#if SOURCEMOD_V_MINOR > 8
RemoveEntity(iEntity);
#else
AcceptEntityInput(iEntity, "Kill");
#endif
}
| 0 | 0.90438 | 1 | 0.90438 | game-dev | MEDIA | 0.856324 | game-dev | 0.858816 | 1 | 0.858816 |
Roll20/roll20-api-scripts | 57,867 | PowerCards Macro Helper/1.0.12/PCMHelper.js | // PCMHelper - A utility script for PowerCards creates attributes to facilitate PowerCard template and
// replacements style cards. Will monitor creation of objects and changes to characters to
// try to keep the attributes updated so there is no additional work involved on the DMs
// part to set up new creatures or character abilities.
//
// The following attributes are created on characters (PCs and/or NPCs) as appropriate:
// attacklist = list of PC Attacks (center of the character sheet). ONLY those marked as attacks.
// npcactionlist = list of repeating_npcaction entries (under the "Actions" heading on the sheet)
// npclegendaryactions = list of repeating_npcaction-l entries
// cantriplist = list of known cantrips
// l1_spell_list thru l9_spell_list = list of known spells.
//
// Supported Commands:
// !pcm Runs the attribute evaluation for any selected tokens.
// !pcmeverybody Runs the attribute evaluation for ALL characters in the game. Good for adding the system
// to an existing game without needing to select each character. Might take a while to run
// on large campaigns (and might even fail).
// !pcmqueue Processes the current queue (if any) - should never be needed.
// !pcmsetup Create (or recreate) the Replacements, Templates, and Macros used by PCMHelper
//
// Latest Changes:
//
// V 1.0.11b Requires PowerCards 3.8.17 or higher. Utilizes the SPELLSOUND, SPELLVFX, ATTACKSOUND, and ATTACKVFX
// replacement variables added by that version of PowerCards to play sounds and visual effects if they
// are defined in the PowerCard Sounds and PowerCard Visual Effects handouts.
//
// Cleaned up the spellcasting code to reduce sandbox crashes
//
// Removed ! commands that couldn't be utilized anyway (because everything gets toLower'd)
//
// Refactored event handler code to move all event handlers inside the on ready event
//
// Added the !pcmformats command to generate a formats handout for all of your player characters
//
var PCMHelper = PCMHelper || (function() {
var PCMHelper_Author = "Kurt Jaegers";
var PCMHelper_Version = "1.0.12";
var PCMHelper_LastUpdated = "2021-03-07";
var color_code_list = [
"#913f92", "#d84242", "#187173", "#7e3f14", "#ff8100", "#618157", "#56859c", "#00154d", "#75716e",
"#83929f","#ea6a47","#ac3e31","#6ab187", "#613318","#816c5b", "#a9a18c", "#855723","#d57500","#404f24","#4e6172",
"#816c5b", "#a9a18c", "#855723","#d57500","#404f24","#4e6172","#83929f","#ea6a47","#ac3e31","#6ab187", "#613318",
"#816c5b", "#a9a18c", "#855723","#d57500","#404f24","#4e6172","#83929f","#ea6a47","#ac3e31","#6ab187", "#613318",
"#816c5b", "#a9a18c", "#855723","#d57500","#404f24","#4e6172","#83929f","#ea6a47","#ac3e31","#6ab187", "#613318"
];
// Text that gets entered into the PowerCard Replacements PCMHelper handout
var pc_replacements = `Advantage:{{query=1}} {{normal=1}} {{r2=[[0d20|1d20;{{query=1}} {{advantage=1}} {{r2=[[1d20|2d20kh1;{{query=1}} {{disadvantage=1}} {{r2=[[1d20|2d20kl1`;
// Text that gets entered into the PowerCard Templates PCMHelper handout
var pc_templates = `Basics: --tokenid|~0! --target_list|~1! --['~6!' -ne '/w gm ']emote|~S-TN$ ~2! against ~T-TN$ --format|~S-CN$ --name|~3! --leftsub|~4! --rightsub|~5!<br>
PCAttack: --['~1!' -eq '/w gm ']whisper|gm --['~2!' -eq '']Attack *1|[#[ [$Atk] ~0! + ~PCA-ATKBONUS$ [Attack Bonus] ]#] vs **AC** [#[~T-AC$]#] --['~2!' -ne '']Attack *2|[#[ [$Atk] ~0! + ~PCA-ATKBONUS$ [Attack Bonus] + ~2! [Bless] ]#] vs **AC** [#[~T-AC$]#] --?? $Atk.base == 1 ?? Fumble|The attack went horribly wrong! --?? $Atk.base <> 1 AND $Atk.base <> 20 AND $Atk.total < ~T-AC$ ?? Miss *1|~S-CN$ missed. --["~PCA-DMG2DICE$" -eq "none" -and "~3!" -eq "0"]?? $Atk.base <> 20 AND $Atk.total >= ~T-AC$ ?? Hit|~S-CN$ hits ~T-CN$ for [#[ [$Dmg] ~PCA-DMG1DICE$ ]] ~PCA-DMG1TYPE$ damage --["~PCA-DMG2DICE$" -ne "none" -and "~3!" -eq "0"]?? $Atk.base <> 20 AND $Atk.total >= ~T-AC$ ?? Hit|~S-CN$ hits ~T-CN$ for [#[ [$Dmg] ~PCA-DMG1DICE$ ]] ~PCA-DMG1TYPE$ damage and [[ [$Dmg2] ~PCA-DMG2DICE$ ]] ~PCA-DMG2TYPE$ damage --["~PCA-DMG2DICE$" -eq "none" -and "~3!" -ne "0"]?? $Atk.base <> 20 AND $Atk.total >= ~T-AC$ ?? Hit|~S-CN$ hits ~T-CN$ for [#[ [$Dmg] ~PCA-DMG1DICE$ ]] ~PCA-DMG1TYPE$ damage and [[ [$GDmg] ~3! ]] ~4! damage --["~PCA-DMG2DICE$" -ne "none" -and "~3!" -ne "0"]?? $Atk.base <> 20 AND $Atk.total >= ~T-AC$ ?? Hit|~S-CN$ hits ~T-CN$ for [#[ [$Dmg] ~PCA-DMG1DICE$ ]] ~PCA-DMG1TYPE$ damage, [[ [$GDmg] ~3! ]] ~4! damage and [[ [$Dmg2] ~PCA-DMG2DICE$ ]] ~PCA-DMG2TYPE$ damage --["~PCA-DMG2DICE$" -eq "none" -and "~3!" -eq "0"]?? $Atk.base == 20 AND $Atk.total >= ~T-AC$ ?? Critical Hit|~S-CN$ hits ~T-CN$ for [#[ [$Dmg] ~PCA-DMG1CRIT$ ]] ~PCA-DMG1TYPE$ damage --["~PCA-DMG2DICE$" -ne "none" -and "~3!" -eq "0"]?? $Atk.base == 20 AND $Atk.total >= ~T-AC$ ?? Critical Hit|~S-CN$ hits ~T-CN$ for [#[ [$Dmg] ~PCA-DMG1CRIT$ ]] ~PCA-DMG1TYPE$ damage and [[ [$Dmg2] ~PCA-DMG2CRIT$ ]] ~PCA-DMG2TYPE$ damage --["~PCA-DMG2DICE$" -eq "none" -and "~3!" -ne "0"]?? $Atk.base == 20 AND $Atk.total >= ~T-AC$ ?? Critical Hit|~S-CN$ hits ~T-CN$ for [#[ [$Dmg] ~PCA-DMG1CRIT$ ]] ~PCA-DMG1TYPE$ damage and [[ [$GDmg] ~5! ]] ~4! damage --["~PCA-DMG2DICE$" -ne "none" -and "~3!" -ne "0"]?? $Atk.base == 20 AND $Atk.total >= ~T-AC$ ?? Critical Hit|~S-CN$ hits ~T-CN$ for [#[ [$Dmg] ~PCA-DMG1CRIT$ ]] ~PCA-DMG1TYPE$ damage [[ [$GDmg] ~5! ]] ~4! damage and [[ [$Dmg2] ~PCA-DMG2CRIT$ ]] ~PCA-DMG2TYPE$ damage --["~PCA-SAVE$" -eq "true"]?? $Atk.base == 20 OR $Atk.total >= ~T-AC$ ?? Save|~T-CN$ can attempt a **DC ~PCA-SAVEDC$** ~PCA-SAVEATTR$ saving throw for ~PCA-SAVEEFFECT$ --["~PCA-SAVE$" -eq "true"]?? $Atk.base == 20 OR $Atk.total >= ~T-AC$ ?? Save|~T-CN$ can attempt a **DC ~PCA-SAVEDC$** ~PCA-SAVEATTR$ saving throw for ~PCA-SAVEEFFECT$ --["~PCA-DESC$" -ne "none"]Description|~PCA-DESC$<br>
NPCBasics: --tokenid|~0! --target_list|~1! --emote|~S-TN$ ~2! against ~T-TN$ --format|badguys --name|~3! --['~NPCA-TYPE$' -eq 'ATTACK']leftsub|~4! --['~NPCA-RANGE$' -eq 'ATTACK']rightsub|~5!<br>
NPCAttack: --["~NPCA-TYPE$" -eq "ATTACK"]Attack:|[#[ [$Atk] ~0! + ~NPCA-TOHIT$ [Attack Bonus] ]#] vs **AC** [#[~T-AC$]#] --["~NPCA-TYPE$" -eq "ATTACK"]?? $Atk < ~T-AC$ ?? !Missed|**The ~NPCA-NAME$ attack missed!** --["~NPCA-TYPE$" -eq "ATTACK" -and "~NPCA-DAMAGETYPE2$" -eq ""]?? $Atk >= ~T-AC$ AND $Atk.base <> 20 ?? Hit:|[#[ [$Dmg] ~NPCA-DAMAGE$ ]#] ~NPCA-DAMAGETYPE$ damage --["~NPCA-TYPE$" -eq "ATTACK" -and "~NPCA-DAMAGETYPE2$" -ne ""]?? $Atk >= ~T-AC$ AND $Atk.base <> 20 ?? Hit:|[#[ [$Dmg] ~NPCA-DAMAGE$ ]#] ~NPCA-DAMAGETYPE$ damage and [#[ [$Dmg2] ~NPCA-DAMAGE2$ ]#] ~NPCA-DAMAGETYPE2$ damage --["~NPCA-TYPE$" -eq "ATTACK" -and "~NPCA-DAMAGETYPE2$" -eq ""]?? $Atk.base == 20 ?? Hit:|[#[ [$Dmg] ~NPCA-CRIT$ ]#] ~NPCA-DAMAGETYPE$ damage --["~NPCA-TYPE$" -eq "ATTACK" -and "~NPCA-DAMAGETYPE2$" -ne ""]?? $Atk.base == 20 ?? Hit:|[#[ [$Dmg] ~NPCA-CRIT$ ]#] ~NPCA-DAMAGETYPE$ damage and [#[ [$Dmg2] ~NPCA-CRIT2$ ]#] ~NPCA-DAMAGETYPE2$ damage --["~NPCA-TYPE$" -eq "ATTACK"]?? $Atk.base == 1 ?? Fumble|The attack goes horribly wrong! --["~NPCA-DESCRIPTION$" -ne "" ]Description|~NPCA-DESCRIPTION$<br>
CantripAttack: --["~1!" -eq "/w gm"]whisper|gm --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-SAVE$' -eq '' -and '~2!' -eq '']Attack: *1|[#[ [$Atk] ~0! + ~S-SAB$ [Spell Attack] ]#] vs **AC** [#[~T-AC$]#] --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-SAVE$' -eq '' -and '~2!' -ne '']Attack: *2|[#[ [$Atk] ~0! + ~S-SAB$ [Spell Attack] ~2! [Bless] ]#] vs **AC** [#[~T-AC$]#] --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-SAVE$' -eq '']?? $Atk < ~T-AC$ ?? !Missed|**You missed!** --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-SAVE$' -eq '' -and "~3!" -eq "0" -and ~SP-MORECANTRIPDAMAGE$ -eq 0]?? $Atk >= ~T-AC$ AND $Atk.base <> 20 ?? Hit:|[#[ [$Dmg] (~SP-DAMAGE$) [Base] + (~S-SAM$ * ~SP-ADDABILITY$) [Ability] ]#] ~SP-DAMAGETYPE$ damage --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-SAVE$' -eq '' -and "~3!" -eq "0" -and ~S-L$ -lt 4 -and ~SP-MORECANTRIPDAMAGE$ -eq 1]?? $Atk >= ~T-AC$ AND $Atk.base <> 20 ?? Hit:|[#[ [$Dmg] (~SP-DAMAGE$) [Base] + (~S-SAM$ * ~SP-ADDABILITY$) [Ability] ]#] ~SP-DAMAGETYPE$ damage --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-SAVE$' -eq '' -and "~3!" -eq "0" -and ~SP-MORECANTRIPDAMAGE$ -eq 1 -and ~S-L$ -gt 4 -and ~S-L$ -lt 12]?? $Atk >= ~T-AC$ AND $Atk.base <> 20 ?? Hit:|[#[ [$Dmg] (~SP-DAMAGE$) + (~SP-DAMAGE$) [Base] + (~S-SAM$ * ~SP-ADDABILITY$) [Ability] ]#] ~SP-DAMAGETYPE$ damage --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-SAVE$' -eq '' -and "~3!" -eq "0" -and ~SP-MORECANTRIPDAMAGE$ -eq 1 -and ~S-L$ -gt 11 -and ~S-L$ -lt 17]?? $Atk >= ~T-AC$ AND $Atk.base <> 20 ?? Hit:|[#[ [$Dmg] (~SP-DAMAGE$) + (~SP-DAMAGE$) + (~SP-DAMAGE$) [Base] + (~S-SAM$ * ~SP-ADDABILITY$) [Ability] ]#] ~SP-DAMAGETYPE$ damage --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-SAVE$' -eq '' -and "~3!" -eq "0" -and ~SP-MORECANTRIPDAMAGE$ -eq 1 -and ~S-L$ -gt 16 ]?? $Atk -ge ~T-AC$ AND $Atk.base <> 20 ?? Hit:|[#[ [$Dmg] (~SP-DAMAGE$) + (~SP-DAMAGE$) + (~SP-DAMAGE$) + (~SP-DAMAGE$) [Base] + (~S-SAM$ * ~SP-ADDABILITY$) [Ability] ~SP-DAMAGETYPE$ ]#] damage --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-SAVE$' -eq '' -and "~3!" -eq "0" -and ~SP-MORECANTRIPDAMAGE$ -eq 0]?? $Atk.base == 20 ?? Critical Hit:|[#[ [$CritDmg] (~SP-DAMAGE$) [Base] + (~SP-DAMAGE$) [Crit] ]#] ~SP-DAMAGETYPE$ Damage --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-SAVE$' -eq '' -and "~3!" -eq "0" -and ~S-L$ -lt 4 -and ~SP-MORECANTRIPDAMAGE$ -eq 1]?? $Atk.base == 20 ?? Critical Hit:|[#[ [$CritDmg] (~SP-DAMAGE$) [Base] + (~SP-DAMAGE$) [Crit] ]#] ~SP-DAMAGETYPE$ Damage --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-SAVE$' -eq '' -and "~3!" -eq "0" -and ~SP-MORECANTRIPDAMAGE$ -eq 1 -and ~S-L$ -gt 4 -and ~S-L$ -lt 12]?? $Atk.base == 20 ?? Critical Hit:|[#[ [$CritDmg] (~SP-DAMAGE$) + (~SP-DAMAGE$) [Base] + (~SP-DAMAGE$) + (~SP-DAMAGE$) [Crit] ]#] ~SP-DAMAGETYPE$ Damage --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-SAVE$' -eq '' -and "~3!" -eq "0" -and ~SP-MORECANTRIPDAMAGE$ -eq 1 -and ~S-L$ -gt 11 -and ~S-L$ -lt 17]?? $Atk.base == 20 ?? Critical Hit:|[#[ [$CritDmg] (~SP-DAMAGE$) + (~SP-DAMAGE$) + (~SP-DAMAGE$) [Base] + (~SP-DAMAGE$) + (~SP-DAMAGE$) + (~SP-DAMAGE$) [Crit] ]#] ~SP-DAMAGETYPE$ Damage --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-SAVE$' -eq '' -and "~3!" -eq "0" -and ~SP-MORECANTRIPDAMAGE$ -eq 1 -and ~S-L$ -gt 16 ]?? $Atk.base == 20 ?? Critical Hit:|[#[ [$CritDmg] (~SP-DAMAGE$) + (~SP-DAMAGE$) + (~SP-DAMAGE$) + (~SP-DAMAGE$) [Base] + (~SP-DAMAGE$) + (~SP-DAMAGE$) + (~SP-DAMAGE$) + (~SP-DAMAGE$) [Crit] ]#] ~SP-DAMAGETYPE$ Damage --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-SAVE$' -eq '' -and "~3!" -ne "0" -and ~SP-MORECANTRIPDAMAGE$ -eq 0]?? $Atk >= ~T-AC$ AND $Atk.base <> 20 ?? Hit:|[#[ [$Dmg] (~SP-DAMAGE$) [Base] + (~S-SAM$ * ~SP-ADDABILITY$) [Ability] ]#] ~SP-DAMAGETYPE$ damage and [[ [$GDmg] ~3! ]] ~4! damage --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-SAVE$' -eq '' -and "~3!" -ne "0" -and ~S-L$ -lt 4 -and ~SP-MORECANTRIPDAMAGE$ -eq 1]?? $Atk >= ~T-AC$ AND $Atk.base <> 20 ?? Hit:|[#[ [$Dmg] (~SP-DAMAGE$) [Base] + (~S-SAM$ * ~SP-ADDABILITY$) [Ability] ]#] ~SP-DAMAGETYPE$ damage and [[ [$GDmg] ~3! ]] ~4! damage --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-SAVE$' -eq '' -and "~3!" -ne "0" -and ~SP-MORECANTRIPDAMAGE$ -eq 1 -and ~S-L$ -gt 4 -and ~S-L$ -lt 12]?? $Atk >= ~T-AC$ AND $Atk.base <> 20 ?? Hit:|[#[ [$Dmg] (~SP-DAMAGE$) + (~SP-DAMAGE$) [Base] + (~S-SAM$ * ~SP-ADDABILITY$) [Ability] ]#] ~SP-DAMAGETYPE$ damage and [[ [$GDmg] ~3! ]] ~4! damage --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-SAVE$' -eq '' -and "~3!" -ne "0" -and ~SP-MORECANTRIPDAMAGE$ -eq 1 -and ~S-L$ -gt 11 -and ~S-L$ -lt 17]?? $Atk >= ~T-AC$ AND $Atk.base <> 20 ?? Hit:|[#[ [$Dmg] (~SP-DAMAGE$) + (~SP-DAMAGE$) + (~SP-DAMAGE$) [Base] + (~S-SAM$ * ~SP-ADDABILITY$) [Ability] ]#] ~SP-DAMAGETYPE$ damage and [[ [$GDmg] ~3! ]] ~4! damage --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-SAVE$' -eq '' -and "~3!" -ne "0" -and ~SP-MORECANTRIPDAMAGE$ -eq 1 -and ~S-L$ -gt 16 ]?? $Atk -ge ~T-AC$ AND $Atk.base <> 20 ?? Hit:|[#[ [$Dmg] (~SP-DAMAGE$) + (~SP-DAMAGE$) + (~SP-DAMAGE$) + (~SP-DAMAGE$) [Base] + (~S-SAM$ * ~SP-ADDABILITY$) [Ability] ~SP-DAMAGETYPE$ ]#] damage and [[ [$GDmg] ~3! ]] ~4! damage --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-SAVE$' -eq '' -and "~3!" -ne "0" -and ~SP-MORECANTRIPDAMAGE$ -eq 0]?? $Atk.base == 20 ?? Critical Hit:|[#[ [$CritDmg] (~SP-DAMAGE$) [Base] + (~SP-DAMAGE$) [Crit] ]#] ~SP-DAMAGETYPE$ Damage and [[ [$GDmg] ~5! ]] ~4! damage --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-SAVE$' -eq '' -and "~3!" -ne "0" -and ~S-L$ -lt 4 -and ~SP-MORECANTRIPDAMAGE$ -eq 1]?? $Atk.base == 20 ?? Critical Hit:|[#[ [$CritDmg] (~SP-DAMAGE$) [Base] + (~SP-DAMAGE$) [Crit] ]#] ~SP-DAMAGETYPE$ Damage and [[ [$GDmg] ~5! ]] ~4! damage --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-SAVE$' -eq '' -and "~3!" -ne "0" -and ~SP-MORECANTRIPDAMAGE$ -eq 1 -and ~S-L$ -gt 4 -and ~S-L$ -lt 12]?? $Atk.base == 20 ?? Critical Hit:|[#[ [$CritDmg] (~SP-DAMAGE$) + (~SP-DAMAGE$) [Base] + (~SP-DAMAGE$) + (~SP-DAMAGE$) [Crit] ]#] ~SP-DAMAGETYPE$ Damage and [[ [$GDmg] ~5! ]] ~4! damage --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-SAVE$' -eq '' -and "~3!" -ne "0" -and ~SP-MORECANTRIPDAMAGE$ -eq 1 -and ~S-L$ -gt 11 -and ~S-L$ -lt 17]?? $Atk.base == 20 ?? Critical Hit:|[#[ [$CritDmg] (~SP-DAMAGE$) + (~SP-DAMAGE$) + (~SP-DAMAGE$) [Base] + (~SP-DAMAGE$) + (~SP-DAMAGE$) + (~SP-DAMAGE$) [Crit] ]#] ~SP-DAMAGETYPE$ Damage and [[ [$GDmg] ~5! ]] ~4! damage --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-SAVE$' -eq '' -and "~3!" -ne "0" -and ~SP-MORECANTRIPDAMAGE$ -eq 1 -and ~S-L$ -gt 16 ]?? $Atk.base == 20 ?? Critical Hit:|[#[ [$CritDmg] (~SP-DAMAGE$) + (~SP-DAMAGE$) + (~SP-DAMAGE$) + (~SP-DAMAGE$) [Base] + (~SP-DAMAGE$) + (~SP-DAMAGE$) + (~SP-DAMAGE$) + (~SP-DAMAGE$) [Crit] ]#] ~SP-DAMAGETYPE$ Damage and [[ [$GDmg] ~5! ]] ~4! damage --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-SAVE$' -eq '']?? $Atk.base == 1 ?? !|**Fumble:** Spell goes horribly wrong! --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-SAVE$' -eq 'Strength']Save|~T-CN$ rolls [[ [$Save] 1d20 + ~T-SBSTR$ ]] on a ~SP-SAVE$ save vs **DC ~S-SSDC$** --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-SAVE$' -eq 'Dexterity']Save|~T-CN$ rolls [[ [$Save] 1d20 + ~T-SBDEX$ ]] on a ~SP-SAVE$ save vs **DC ~S-SSDC$** --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-SAVE$' -eq 'Constitution']Save|~T-CN$ rolls [[ [$Save] 1d20 + ~T-SBCON$ ]] on a ~SP-SAVE$ save vs **DC ~S-SSDC$** --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-SAVE$' -eq 'Intelligence']Save|~T-CN$ rolls [[ [$Save] 1d20 + ~T-SBINT$ ]] on a ~SP-SAVE$ save vs **DC ~S-SSDC$** --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-SAVE$' -eq 'Wisdom']Save|~T-CN$ rolls [[ [$Save] 1d20 + ~T-SBWIS$ ]] on a ~SP-SAVE$ save vs **DC ~S-SSDC$** --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-SAVE$' -eq 'Charisma']Save|~T-CN$ rolls [[ [$Save] 1d20 + ~T-SBCHA$ ]] on a ~SP-SAVE$ save vs **DC ~S-SSDC$** --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-SAVE$' -ne '' -and "~3!" -eq "0" -and ~S-L$ -lt 4 -and ~SP-MORECANTRIPDAMAGE$ -ne 0]?? $Save < ~S-SSDC$ ?? Save Failed|~T-CN$ takes [#[ [$Dmg] (~SP-DAMAGE$) [Base] + (~S-SAM$ * ~SP-ADDABILITY$) [Ability] ]#] ~SP-DAMAGETYPE$ damage --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-SAVE$' -ne '' -and "~3!" -eq "0" -and ~SP-MORECANTRIPDAMAGE$ -eq 0]?? $Save < ~S-SSDC$ ?? Save Failed|~T-CN$ takes [#[ [$Dmg] (~SP-DAMAGE$) [Base] + (~S-SAM$ * ~SP-ADDABILITY$) [Ability] ]#] ~SP-DAMAGETYPE$ damage --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-SAVE$' -ne '' -and "~3!" -eq "0" -and ~SP-MORECANTRIPDAMAGE$ -eq 1 -and ~S-L$ -gt 4 -and ~S-L$ -lt 12]?? $Save < ~S-SSDC$ ?? Save Failed:|~T-CN$ takes [#[ [$Dmg] (~SP-DAMAGE$) + (~SP-DAMAGE$) [Base] + (~S-SAM$ * ~SP-ADDABILITY$) [Ability] ]#] ~SP-DAMAGETYPE$ damage --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-SAVE$' -ne '' -and "~3!" -eq "0" -and ~SP-MORECANTRIPDAMAGE$ -eq 1 -and ~S-L$ -gt 11 -and ~S-L$ -lt 17]?? $Save < ~S-SSDC$ ?? Save Failed:|~T-CN$ takes [#[ [$Dmg] (~SP-DAMAGE$) + (~SP-DAMAGE$) + (~SP-DAMAGE$) [Base] + (~S-SAM$ * ~SP-ADDABILITY$) [Ability] ]#] ~SP-DAMAGETYPE$ damage --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-SAVE$' -ne '' -and "~3!" -eq "0" -and ~SP-MORECANTRIPDAMAGE$ -eq 1 -and ~S-L$ -gt 16 ]?? $Save < ~S-SSDC$ ?? Save Failed:|~T-CN$ takes [#[ [$Dmg] (~SP-DAMAGE$) + (~SP-DAMAGE$) + (~SP-DAMAGE$) + (~SP-DAMAGE$) [Base] + (~S-SAM$ * ~SP-ADDABILITY$) [Ability] ]#] ~SP-DAMAGETYPE$ damage --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-SAVE$' -ne '' -and "~3!" -ne "0" -and ~S-L$ -lt 4 -and ~SP-MORECANTRIPDAMAGE$ -ne 0]?? $Save < ~S-SSDC$ ?? Save Failed|~T-CN$ takes [#[ [$Dmg] (~SP-DAMAGE$) [Base] + (~S-SAM$ * ~SP-ADDABILITY$) [Ability] ]#] ~SP-DAMAGETYPE$ damage and [[ [$GDmg] ~3! ]] ~4! damage --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-SAVE$' -ne '' -and "~3!" -ne "0" -and ~SP-MORECANTRIPDAMAGE$ -eq 0]?? $Save < ~S-SSDC$ ?? Save Failed|~T-CN$ takes [#[ [$Dmg] (~SP-DAMAGE$) [Base] + (~S-SAM$ * ~SP-ADDABILITY$) [Ability] ]#] ~SP-DAMAGETYPE$ damage and [[ [$GDmg] ~3! ]] ~4! damage --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-SAVE$' -ne '' -and "~3!" -ne "0" -and ~SP-MORECANTRIPDAMAGE$ -eq 1 -and ~S-L$ -gt 4 -and ~S-L$ -lt 12]?? $Save < ~S-SSDC$ ?? Save Failed:|~T-CN$ takes [#[ [$Dmg] (~SP-DAMAGE$) + (~SP-DAMAGE$) [Base] + (~S-SAM$ * ~SP-ADDABILITY$) [Ability] ]#] ~SP-DAMAGETYPE$ damage and [[ [$GDmg] ~3! ]] ~4! damage --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-SAVE$' -ne '' -and "~3!" -ne "0" -and ~SP-MORECANTRIPDAMAGE$ -eq 1 -and ~S-L$ -gt 11 -and ~S-L$ -lt 17]?? $Save < ~S-SSDC$ ?? Save Failed:|~T-CN$ takes [#[ [$Dmg] (~SP-DAMAGE$) + (~SP-DAMAGE$) + (~SP-DAMAGE$) [Base] + (~S-SAM$ * ~SP-ADDABILITY$) [Ability] ]#] ~SP-DAMAGETYPE$ damage and [[ [$GDmg] ~3! ]] ~4! damage --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-SAVE$' -ne '' -and "~3!" -ne "0" -and ~SP-MORECANTRIPDAMAGE$ -eq 1 -and ~S-L$ -gt 16 ]?? $Save < ~S-SSDC$ ?? Save Failed:|~T-CN$ takes [#[ [$Dmg] (~SP-DAMAGE$) + (~SP-DAMAGE$) + (~SP-DAMAGE$) + (~SP-DAMAGE$) [Base] + (~S-SAM$ * ~SP-ADDABILITY$) [Ability] ]#] ~SP-DAMAGETYPE$ damage and [[ [$GDmg] ~3! ]] ~4! damage --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-SAVE$' -ne '']?? $Save >= ~S-SSDC$ ?? Save Succeded|~T-CN$ avoids the effect of the ~SP-NAME$ --Description|~SP-DESCRIPTION$<br>
SpellCast: --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-ATTACK$' -ne 'None']Attack:|[#[ [$Atk] ~0! + ~S-SAB$ [Spell Attack] ]#] vs **AC** [#[~T-AC$]#] --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-ATTACK$' -eq 'None']hroll|[#[ [$Atk] 1d10 + 500 ]#] vs **AC** [#[~T-AC$]#] --['~SP-OUTPUT$' -eq 'ATTACK']?? $Atk < ~T-AC$ ?? !Missed|**You missed!** --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-DAMAGE$' -ne '' -and '~SP-DAMAGE2$' -eq '']?? $Atk >= ~T-AC$ AND $Atk.base <> 20 ?? Hit:|[#[ [$Dmg] (~SP-DAMAGE$) [Base] + (~S-SAM$ * ~SP-ADDABILITY$) [Ability] + (~SP-HLDICE$*~SSL$)~SP-HLDIETYPE$~SP-HLBONUS$ [HigherLevel] ]#] ~SP-DAMAGETYPE$ damage --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-DAMAGE$' -ne '' -and '~SP-DAMAGE2$' -eq '']?? $Atk.base == 20 ?? Critical Hit:|[#[ [$Dmg] (~SP-DAMAGE$) [Base] + (~SP-DAMAGE$) [Crit] + (~S-SAM$ * ~SP-ADDABILITY$) [Ability] + (~SP-HLDICE$*~SSL$)~SP-HLDIETYPE$~SP-HLBONUS$ [HigherLevel] + (~SP-HLDICE$*~SSL$)~SP-HLDIETYPE$~SP-HLBONUS$ [HLCrit] ]#] ~SP-DAMAGETYPE$ Damage --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-DAMAGE$' -ne '' -and '~SP-DAMAGE2$' -ne '']?? $Atk >= ~T-AC$ AND $Atk.base <> 20 ?? Hit:|[#[ [$Dmg] (~SP-DAMAGE$) [Base] + (~S-SAM$ * ~SP-ADDABILITY$) [Ability] + (~SP-HLDICE$*~SSL$)~SP-HLDIETYPE$~SP-HLBONUS$ [HigherLevel] ]#] ~SP-DAMAGETYPE$ damage and [#[ [$Dmg2] (~SP-DAMAGE2$) [Base] + (~S-SAM$ * ~SP-ADDABILITY$) [Ability] ]#] ~SP-DAMAGETYPE2$ damage --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-DAMAGE$' -ne '' -and '~SP-DAMAGE2$' -ne '']?? $Atk.base == 20 ?? Critical Hit:|[#[ [$Dmg] (~SP-DAMAGE$) [Base] + (~SP-DAMAGE$) [Crit] + (~S-SAM$ * ~SP-ADDABILITY$) [Ability] + (~SP-HLDICE$*~SSL$)~SP-HLDIETYPE$~SP-HLBONUS$ [HigherLevel] + (~SP-HLDICE$*~SSL$)~SP-HLDIETYPE$~SP-HLBONUS$ [HLCrit] ]#] ~SP-DAMAGETYPE$ Damage and [#[ [$Dmg2] (~SP-DAMAGE2$) [Base] (~SP-DAMAGE2$) [Crit] + (~S-SAM$ * ~SP-ADDABILITY$) [Ability] ]#] ~SP-DAMAGETYPE2$ damage --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-SAVE$' -eq 'Strength']Save|~T-CN$ rolls [[ [$Save] 1d20 + ~T-SBSTR$ ]] on a ~SP-SAVE$ save vs **DC ~S-SSDC$** --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-SAVE$' -eq 'Dexterity']Save|~T-CN$ rolls [[ [$Save] 1d20 + ~T-SBDEX$ ]] on a ~SP-SAVE$ save vs **DC ~S-SSDC$** --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-SAVE$' -eq 'Constitution']Save|~T-CN$ rolls [[ [$Save] 1d20 + ~T-SBCON$ ]] on a ~SP-SAVE$ save vs **DC ~S-SSDC$** --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-SAVE$' -eq 'Intelligence']Save|~T-CN$ rolls [[ [$Save] 1d20 + ~T-SBINT$ ]] on a ~SP-SAVE$ save vs **DC ~S-SSDC$** --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-SAVE$' -eq 'Wisdom']Save|~T-CN$ rolls [[ [$Save] 1d20 + ~T-SBWIS$ ]] on a ~SP-SAVE$ save vs **DC ~S-SSDC$** --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-SAVE$' -eq 'Charisma']Save|~T-CN$ rolls [[ [$Save] 1d20 + ~T-SBCHA$ ]] on a ~SP-SAVE$ save vs **DC ~S-SSDC$** --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-SAVE$' -ne '']?? Save < ~S-SSDC$ ?? Save Failed|~T-CN$ takes [#[ [$Dmg] (~SP-DAMAGE$) [Base] + (~S-SAM$ * ~SP-ADDABILITY$) [Ability] ]#] ~SP-DAMAGETYPE$ damage --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-SAVE$' -ne '']?? $Save >= ~S-SSDC$ ?? Save Succeded|~T-CN$ saves for ~SP-SAVESUCCESS$ --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-HEALING$' -ne '']Healing:|[#[ [$Heal] (~SP-HEALING$) [Base] + (~S-SAM$ * ~SP-ADDABILITY$) [Ability] + (~SP-HLDICE$*~SSL$)~SP-HLDIETYPE$~SP-HLBONUS$ [HigherLevel] ]#] --Description|~SP-DESCRIPTION$<br>
`;
// Base PCMHelper Formats Text
var pc_formats = `atwill: --txcolor|#000000 --bgcolor|#004400<br>
charinfo: --txcolor|#ffff00 --bgcolor|#000000 --titlefontshadow|#0000cc --corners|10 --orowbg|#cec7b6 --erowbg|#cec7b6<br>
badguys: --txcolor|#ffff00 --bgcolor|#000000 --titlefontshadow|#0000cc --corners|10 --emotefont|font-family: Arial; font-weight: bold;<br>
bigbad: --txcolor|#ffff00 --bgcolor|#000000 --titlefontshadow|#0000cc --corners|10<br>`;
var format_template = ' --txcolor|#ffff00 --titlefontshadow|#0000cc --corners|10<br>';
//SpellCast: --["~1!" -eq "/w gm"]whisper|gm --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-ATTACK$' -ne 'None' -and '~SP-DAMAGE$' -ne '' -and '~2!' -eq '']Attack: *1|[#[ [$Atk] ~0! + ~S-SAB$ [Spell Attack] ]#] vs **AC** [#[~T-AC$]#] --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-ATTACK$' -ne 'None' -and '~SP-DAMAGE$' -ne '' -and '~2!' -ne '']Attack: *2|[#[ [$Atk] ~0! + ~S-SAB$ [Spell Attack] + ~2! [Bless] ]#] vs **AC** [#[~T-AC$]#] --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-ATTACK$' -eq 'None' -and '~SP-DAMAGE$' -ne '']hroll|[#[ [$Atk] 1d10 + 500 ]#] vs **AC** [#[~T-AC$]#] --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-DAMAGE$' -ne '']?? $Atk < ~T-AC$ ?? !Missed|**You missed!** --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-DAMAGE2$' -eq '' -and '~SP-DAMAGE$' -ne '' -and "~3!" -eq "0"]?? $Atk >= ~T-AC$ AND $Atk.base <> 20 ?? Hit: *1|[#[ [$Dmg] (~SP-DAMAGE$) [Base] + (~S-SAM$ * ~SP-ADDABILITY$) [Ability] + (~SP-HLDICE$*~SSL$)~SP-HLDIETYPE$~SP-HLBONUS$ [HigherLevel] ]#] ~SP-DAMAGETYPE$ damage --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-DAMAGE2$' -eq '' -and '~SP-DAMAGE$' -ne '' -and "~3!" -eq "0"]?? $Atk.base == 20 ?? Critical Hit: *1|[#[ [$Dmg] (~SP-DAMAGE$) [Base] + (~SP-DAMAGE$) [Crit] + (~S-SAM$ * ~SP-ADDABILITY$) [Ability] + (~SP-HLDICE$*~SSL$)~SP-HLDIETYPE$~SP-HLBONUS$ [HigherLevel] + (~SP-HLDICE$*~SSL$)~SP-HLDIETYPE$~SP-HLBONUS$ [HLCrit] ]#] ~SP-DAMAGETYPE$ Damage --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-DAMAGE2$' -ne '' -and '~SP-DAMAGE$' -ne '' -and "~3!" -eq "0"]?? $Atk >= ~T-AC$ AND $Atk.base <> 20 ?? Hit: *2|[#[ [$Dmg] (~SP-DAMAGE$) [Base] + (~S-SAM$ * ~SP-ADDABILITY$) [Ability] + (~SP-HLDICE$*~SSL$)~SP-HLDIETYPE$~SP-HLBONUS$ [HigherLevel] ]#] ~SP-DAMAGETYPE$ damage and [#[ [$Dmg2] (~SP-DAMAGE2$) [Base] + (~S-SAM$ * ~SP-ADDABILITY$) [Ability] ]#] ~SP-DAMAGETYPE2$ damage --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-DAMAGE2$' -ne '' -and '~SP-DAMAGE$' -ne '' -and "~3!" -eq "0"]?? $Atk.base == 20 ?? Critical Hit: *2|[#[ [$Dmg] (~SP-DAMAGE$) [Base] + (~SP-DAMAGE$) [Crit] + (~S-SAM$ * ~SP-ADDABILITY$) [Ability] + (~SP-HLDICE$*~SSL$)~SP-HLDIETYPE$~SP-HLBONUS$ [HigherLevel] + (~SP-HLDICE$*~SSL$)~SP-HLDIETYPE$~SP-HLBONUS$ [HLCrit] ]#] ~SP-DAMAGETYPE$ Damage and [#[ [$Dmg2] (~SP-DAMAGE2$) [Base] (~SP-DAMAGE2$) [Crit] + (~S-SAM$ * ~SP-ADDABILITY$) [Ability] ]#] ~SP-DAMAGETYPE2$ damage --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-DAMAGE2$' -eq '' -and '~SP-DAMAGE$' -ne '' -and "~3!" -ne "0"]?? $Atk >= ~T-AC$ AND $Atk.base <> 20 ?? Hit: *3|[#[ [$Dmg] (~SP-DAMAGE$) [Base] + (~S-SAM$ * ~SP-ADDABILITY$) [Ability] + (~SP-HLDICE$*~SSL$)~SP-HLDIETYPE$~SP-HLBONUS$ [HigherLevel] ]#] ~SP-DAMAGETYPE$ damage and [[ [$GDmg] ~3! ]] ~4! damage --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-DAMAGE2$' -eq '' -and '~SP-DAMAGE$' -ne '' -and "~3!" -ne "0"]?? $Atk.base == 20 ?? Critical Hit: *3|[#[ [$Dmg] (~SP-DAMAGE$) [Base] + (~SP-DAMAGE$) [Crit] + (~S-SAM$ * ~SP-ADDABILITY$) [Ability] + (~SP-HLDICE$*~SSL$)~SP-HLDIETYPE$~SP-HLBONUS$ [HigherLevel] + (~SP-HLDICE$*~SSL$)~SP-HLDIETYPE$~SP-HLBONUS$ [HLCrit] ]#] ~SP-DAMAGETYPE$ Damage and [[ [$GDmg] ~5! ]] ~4! damage --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-DAMAGE2$' -ne '' -and '~SP-DAMAGE$' -ne '' -and "~3!" -ne "0"]?? $Atk >= ~T-AC$ AND $Atk.base <> 20 ?? Hit: *4|[#[ [$Dmg] (~SP-DAMAGE$) [Base] + (~S-SAM$ * ~SP-ADDABILITY$) [Ability] + (~SP-HLDICE$*~SSL$)~SP-HLDIETYPE$~SP-HLBONUS$ [HigherLevel] ]#] ~SP-DAMAGETYPE$ damage, [[ [$GDmg] ~3! ]] ~4! damage and [#[ [$Dmg2] (~SP-DAMAGE2$) [Base] + (~S-SAM$ * ~SP-ADDABILITY$) [Ability] ]#] ~SP-DAMAGETYPE2$ damage --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-DAMAGE2$' -ne '' -and '~SP-DAMAGE$' -ne '' -and "~3!" -ne "0"]?? $Atk.base == 20 ?? Critical Hit: *4|[#[ [$Dmg] (~SP-DAMAGE$) [Base] + (~SP-DAMAGE$) [Crit] + (~S-SAM$ * ~SP-ADDABILITY$) [Ability] + (~SP-HLDICE$*~SSL$)~SP-HLDIETYPE$~SP-HLBONUS$ [HigherLevel] + (~SP-HLDICE$*~SSL$)~SP-HLDIETYPE$~SP-HLBONUS$ [HLCrit] ]#] ~SP-DAMAGETYPE$ Damage, [[ [$GDmg] ~5! ]] ~4! damage and [#[ [$Dmg2] (~SP-DAMAGE2$) [Base] (~SP-DAMAGE2$) [Crit] + (~S-SAM$ * ~SP-ADDABILITY$) [Ability] ]#] ~SP-DAMAGETYPE2$ damage --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-SAVE$' -eq 'Strength' -and '~SP-DAMAGE$' -ne '']Save|~T-CN$ rolls [[ [$Save] 1d20 + ~T-SBSTR$ ]] on a ~SP-SAVE$ save vs **DC ~S-SSDC$** --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-SAVE$' -eq 'Dexterity' -and '~SP-DAMAGE$' -ne '']Save|~T-CN$ rolls [[ [$Save] 1d20 + ~T-SBDEX$ ]] on a ~SP-SAVE$ save vs **DC ~S-SSDC$** --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-SAVE$' -eq 'Constitution' -and '~SP-DAMAGE$' -ne '']Save|~T-CN$ rolls [[ [$Save] 1d20 + ~T-SBCON$ ]] on a ~SP-SAVE$ save vs **DC ~S-SSDC$** --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-SAVE$' -eq 'Intelligence' -and '~SP-DAMAGE$' -ne '']Save|~T-CN$ rolls [[ [$Save] 1d20 + ~T-SBINT$ ]] on a ~SP-SAVE$ save vs **DC ~S-SSDC$** --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-SAVE$' -eq 'Wisdom' -and '~SP-DAMAGE$' -ne '']Save|~T-CN$ rolls [[ [$Save] 1d20 + ~T-SBWIS$ ]] on a ~SP-SAVE$ save vs **DC ~S-SSDC$** --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-SAVE$' -eq 'Charisma' -and '~SP-DAMAGE$' -ne '']Save|~T-CN$ rolls [[ [$Save] 1d20 + ~T-SBCHA$ ]] on a ~SP-SAVE$ save vs **DC ~S-SSDC$** --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-SAVE$' -ne '' -and '~SP-DAMAGE$' -ne '' -and "~3!" -eq "0"]?? Save < ~S-SSDC$ ?? Save Failed *1|~T-CN$ takes [#[ [$Dmg] (~SP-DAMAGE$) [Base] + (~S-SAM$ * ~SP-ADDABILITY$) [Ability] ]#] ~SP-DAMAGETYPE$ damage --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-SAVE$' -ne '' -and '~SP-DAMAGE$' -ne '' -and "~3!" -ne "0"]?? Save < ~S-SSDC$ ?? Save Failed *2|~T-CN$ takes [#[ [$Dmg] (~SP-DAMAGE$) [Base] + (~S-SAM$ * ~SP-ADDABILITY$) [Ability] ]#] ~SP-DAMAGETYPE$ damage and [[ [$GDmg] ~3! ]] ~4! damage --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-SAVE$' -ne '' -and '~SP-DAMAGE$' -ne '']?? $Save >= ~S-SSDC$ ?? Save Succeded|~T-CN$ saves for ~SP-SAVESUCCESS$ --['~SP-OUTPUT$' -eq 'ATTACK' -and '~SP-HEALING$' -ne '']Healing:|[#[ [$Heal] (~SP-HEALING$) [Base] + (~S-SAM$ * ~SP-ADDABILITY$) [Ability] + (~SP-HLDICE$*~SSL$)~SP-HLDIETYPE$~SP-HLBONUS$ [HigherLevel] ]#] --Description|~SP-DESCRIPTION$<br>
// Text of the PCMHelper Macros that will be added to your game by running !pcmsetup
var pc_npcaction = `!power {{
--replacenpcaction|@{selected|character_id}|?{Select action to use|@{selected|npcactionlist}}
--replacement|Advantage
--replaceattrs|S-|@{selected|character_id}|@{selected|token_id}
--replaceattrs|T-|@{target|character_id}|@{target|token_id}
--soundfx|_audio,play,nomenu|~ATTACKSOUND$
--vfx_opt|~ATTACKVFX$
--template|NPCBasics|@{selected|token_id};@{target|token_id};uses ~NPCA-NAME$;~NPCA-NAME$;~NPCA-ATYPE$;~NPCA-RANGE$
--template|NPCAttack|~@{selected|rtype}$
}}`;
var pc_pcattack = `!power {{
--replacepcattack|@{selected|character_id}|?{Select attack to use|@{selected|attacklist}}
--replacement|Advantage
--replaceattrs|S-|@{selected|character_id}|@{selected|token_id}
--replaceattrs|T-|@{target|character_id}|@{target|token_id}
--soundfx|_audio,play,nomenu|~ATTACKSOUND$
--vfx_opt|~ATTACKVFX$
--template|Basics|@{selected|token_id};@{target|token_id};uses ~PCA-NAME$;~PCA-NAME$;~PCA-ATYPE$;~PCA-RANGE$;@{selected|whispertoggle}
--template|PCAttack|~@{selected|rtype}$;@{selected|whispertoggle};@{selected|global_attack_mod};@{selected|global_damage_mod_roll};@{selected|global_damage_mod_type};@{selected|global_damage_mod_crit}
}}`;
var pc_legendary = `!power {{
--replacenpcaction|@{selected|character_id}|?{Select action to use|@{selected|legendaryactionlist}}
--replacement|Advantage
--replaceattrs|S-|@{selected|character_id}|@{selected|token_id}
--replaceattrs|T-|@{target|character_id}|@{target|token_id}
--soundfx|_audio,play,nomenu|~ATTACKSOUND$
--vfx_opt|~ATTACKVFX$
--template|NPCBasics|@{selected|token_id};@{target|token_id};uses ~NPCA-NAME$;~NPCA-NAME$;~NPCA-ATYPE$;~NPCA-RANGE$
--template|NPCAttack|~@{selected|rtype}$
}}`;
var pc_cantrip = `!power {{
--replacespell|@{selected|character_id}|?{Cantrip to cast|@{selected|cantrip_list}}
--replaceattrs|S-|@{selected|character_id}|@{selected|token_id}
--replaceattrs|T-|@{target|character_id}|@{target|token_id}
--replacement|Advantage
--soundfx|_audio,play,nomenu|~SPELLSOUND$
--vfx_opt|~SPELLVFX$
--template|Basics|@{selected|token_id};@{target|token_id};casts ~SP-NAME$;~SP-NAME$;Cantrip;~SP-RANGE$;@{selected|whispertoggle}
--template|CantripAttack|~@{selected|rtype}$;@{selected|whispertoggle};@{selected|global_attack_mod};@{selected|global_damage_mod_roll};@{selected|global_damage_mod_type};@{selected|global_damage_mod_crit}
}}`;
var pc_level1 = `!power {{
--replacespell|@{selected|character_id}|?{Spell to Cast|@{selected|l1_spell_list}}
--inlinereplace|SSL|?{Spell Slot Level?|1,0|2,1|3,2|4,3|5,4|6,5|7,6|8,7|9,8}
--replaceattrs|S-|@{selected|character_id}|@{selected|token_id}
--replaceattrs|T-|@{target|character_id}|@{target|token_id}
--replacement|Advantage
--soundfx|_audio,play,nomenu|~SPELLSOUND$
--vfx_opt|~SPELLVFX$
--template|Basics|@{selected|token_id};@{target|token_id};casts ~SP-NAME$;~SP-NAME$;Save DC ~S-SSDC$;~SP-RANGE$;@{selected|whispertoggle}
--template|SpellCast|~@{selected|rtype}$;@{selected|whispertoggle}
}}`;
var pc_level2 = `!power {{
--replacespell|@{selected|character_id}|?{Spell to Cast|@{selected|l2_spell_list}}
--inlinereplace|SSL|?{Spell Slot Level?|2,0|3,1|4,2|5,3|6,4|7,5|8,6|9,7}
--replaceattrs|S-|@{selected|character_id}|@{selected|token_id}
--replaceattrs|T-|@{target|character_id}|@{target|token_id}
--replacement|Advantage
--soundfx|_audio,play,nomenu|~SPELLSOUND$
--vfx_opt|~SPELLVFX$
--template|Basics|@{selected|token_id};@{target|token_id};casts ~SP-NAME$;~SP-NAME$;Save DC ~S-SSDC$;~SP-RANGE$;@{selected|whispertoggle}
--template|SpellCast|~@{selected|rtype}$;@{selected|whispertoggle}
}}`;
var pc_level3 = `!power {{
--replacespell|@{selected|character_id}|?{Spell to Cast|@{selected|l3_spell_list}}
--inlinereplace|SSL|?{Spell Slot Level?|3,0|4,1|5,2|6,3|7,4|8,5|9,6}
--replaceattrs|S-|@{selected|character_id}|@{selected|token_id}
--replaceattrs|T-|@{target|character_id}|@{target|token_id}
--replacement|Advantage
--soundfx|_audio,play,nomenu|~SPELLSOUND$
--vfx_opt|~SPELLVFX$
--template|Basics|@{selected|token_id};@{target|token_id};casts ~SP-NAME$;~SP-NAME$;Save DC ~S-SSDC$;~SP-RANGE$;@{selected|whispertoggle}
--template|SpellCast|~@{selected|rtype}$;@{selected|whispertoggle}
}}`;
var pc_level4 = `!power {{
--replacespell|@{selected|character_id}|?{Spell to Cast|@{selected|l4_spell_list}}
--inlinereplace|SSL|?{Spell Slot Level?|4,0|5,1|6,2|7,3|8,4|9,5}
--replaceattrs|S-|@{selected|character_id}|@{selected|token_id}
--replaceattrs|T-|@{target|character_id}|@{target|token_id}
--replacement|Advantage
--soundfx|_audio,play,nomenu|~SPELLSOUND$
--vfx_opt|~SPELLVFX$
--template|Basics|@{selected|token_id};@{target|token_id};casts ~SP-NAME$;~SP-NAME$;Save DC ~S-SSDC$;~SP-RANGE$;@{selected|whispertoggle}
--template|SpellCast|~@{selected|rtype}$;@{selected|whispertoggle}
}}`;
var pc_level5 = `!power {{
--replacespell|@{selected|character_id}|?{Spell to Cast|@{selected|l5_spell_list}}
--inlinereplace|SSL|?{Spell Slot Level?|5,0|6,1|7,2|8,3|9,4}
--replaceattrs|S-|@{selected|character_id}|@{selected|token_id}
--replaceattrs|T-|@{target|character_id}|@{target|token_id}
--replacement|Advantage
--soundfx|_audio,play,nomenu|~SPELLSOUND$
--vfx_opt|~SPELLVFX$
--template|Basics|@{selected|token_id};@{target|token_id};casts ~SP-NAME$;~SP-NAME$;Save DC ~S-SSDC$;~SP-RANGE$;@{selected|whispertoggle}
--template|SpellCast|~@{selected|rtype}$;@{selected|whispertoggle}
}}`;
var pc_level6 = `!power {{
--replacespell|@{selected|character_id}|?{Spell to Cast|@{selected|l6_spell_list}}
--inlinereplace|SSL|?{Spell Slot Level?|6,0|7,1|8,2|9,3}
--replaceattrs|S-|@{selected|character_id}|@{selected|token_id}
--replaceattrs|T-|@{target|character_id}|@{target|token_id}
--replacement|Advantage
--soundfx|_audio,play,nomenu|~SPELLSOUND$
--vfx_opt|~SPELLVFX$
--template|Basics|@{selected|token_id};@{target|token_id};casts ~SP-NAME$;~SP-NAME$;Save DC ~S-SSDC$;~SP-RANGE$;@{selected|whispertoggle}
--template|SpellCast|~@{selected|rtype}$;@{selected|whispertoggle}
}}`;
var pc_level7 = `!power {{
--replacespell|@{selected|character_id}|?{Spell to Cast|@{selected|l7_spell_list}}
--inlinereplace|SSL|?{Spell Slot Level?|7,0|8,1|9,2}
--replaceattrs|S-|@{selected|character_id}|@{selected|token_id}
--replaceattrs|T-|@{target|character_id}|@{target|token_id}
--replacement|Advantage
--soundfx|_audio,play,nomenu|~SPELLSOUND$
--vfx_opt|~SPELLVFX$
--template|Basics|@{selected|token_id};@{target|token_id};casts ~SP-NAME$;~SP-NAME$;Save DC ~S-SSDC$;~SP-RANGE$;@{selected|whispertoggle}
--template|SpellCast|~@{selected|rtype}$;@{selected|whispertoggle}
}}`;
var pc_level8 = `!power {{
--replacespell|@{selected|character_id}|?{Spell to Cast|@{selected|l8_spell_list}}
--inlinereplace|SSL|?{Spell Slot Level?|8,0|9,1}
--replaceattrs|S-|@{selected|character_id}|@{selected|token_id}
--replaceattrs|T-|@{target|character_id}|@{target|token_id}
--replacement|Advantage
--soundfx|_audio,play,nomenu|~SPELLSOUND$
--vfx_opt|~SPELLVFX$
--template|Basics|@{selected|token_id};@{target|token_id};casts ~SP-NAME$;~SP-NAME$;Save DC ~S-SSDC$;~SP-RANGE$;@{selected|whispertoggle}
--template|SpellCast|~@{selected|rtype}$;@{selected|whispertoggle}
}}`;
var pc_level9 = `!power {{
--replacespell|@{selected|character_id}|?{Spell to Cast|@{selected|l9_spell_list}}
--inlinereplace|SSL|0
--replaceattrs|S-|@{selected|character_id}|@{selected|token_id}
--replaceattrs|T-|@{target|character_id}|@{target|token_id}
--replacement|Advantage
--soundfx|_audio,play,nomenu|~SPELLSOUND$
--vfx_opt|~SPELLVFX$
--template|Basics|@{selected|token_id};@{target|token_id};casts ~SP-NAME$;~SP-NAME$;Save DC ~S-SSDC$;~SP-RANGE$;@{selected|whispertoggle}
--template|SpellCast|~@{selected|rtype}$;@{selected|whispertoggle}
}}`;
// API COMMAND HANDLER
on("ready", function() {
on("chat:message", function(msg) {
if (msg.type !== "api") {
return;
}
switch (msg.content.split(" ", 1)[0].toLowerCase()) {
// The basic !pcm command runs the evaluator for the selected tokens and creates the required attributes on each
// token, including the spell lists, attack lists, action list, and legendary action list
case "!pcmhelper":
case "!pcm":
case "!pcmh":
var player_obj = getObj("player", msg.playerid);
msg.who = msg.who.replace(" (GM)", "");
msg.content = msg.content.replace(/<br\/>\n/g, ' ').replace(/({{)(.*)((\}\}))/, " $2 ").replace(/\[#\[/g,"[[").replace(/\]#\]/g,"]]");
getAttackInfo(msg, player_obj);
getNPCActionInfo(msg, player_obj);
getSpellInfo(msg, player_obj);
break;
// Running !pcmsetup removes and recreates the PCMHelper related macros
case "!pcmsetup":
log("Running PCMSetup - installing macros for version " + PCMHelper_Version);
createHandouts();
createPCMacros(getObj("player", msg.playerid));
state.PCMHelper.currentVersion = PCMHelper_Version;
var html = "<table border=2 width=100%><tr><td bgcolor=goldenrod colspan=1 align=center><font color=black>PCMHelper</font></td></tr>";
html += "<tr><td colspan=1>Your PCMHelper macros and handouts have been updated to version <strong>" + PCMHelper_Version + "</strong></td></tr>";
html += "</table>";
sendChat("PCMHelper:",html);
break;
// Debugging command. Sets your version information to an old version number
case "!pcmoldversion":
state.PCMHelper.currentVersion = "1.0.1"
break;
// Outputs to the log the items remaining in the processing queue
case "!pcmshowqueue":
log(state.PCMHelper.Queue);
break;
// Queues ALL characters in your game for !pcm processing. Queues are processed by a worker to leave the game available and keep the sandbox
// from timing out.
case "!pcmeverybody":
var chars = findObjs({ _type: "character"});
_.each(chars, function(obj) {
AddQueueItem(obj.id);
});
log(`Queue length is ${state.PCMHelper.Queue.length}`);
break;
case '!pcmformats':
generatePlayerFormats();
break;
// Output the current version information for PCMHelper
case "!pcm_version":
sendChat("", "/w " + msg.who + " You are using version " + PCMHelper_Version + " of PCMHelper, authored by " + PCMHelper_Author + ", which was last updated on: " + PCMHelper_LastUpdated + ".");
break;
}
});
// Monitor attribute changes on characters and queue them for !pcm updates if what changed is an attack, action, or spell
on("change:attribute", function(obj) {
if (obj.get("name").endsWith("_rollbase")) {
AddQueueItem(obj.get("_characterid"));
}
if (obj.get("name").endsWith("_hasattack")) {
AddQueueItem(obj.get("_characterid"));
}
if (obj.get("name").endsWith("_spellname")) {
AddQueueItem(obj.get("_characterid"));
}
});
// When an attribute is removed (spell removed) rerun !pcm on the character
on("destroy:attribute", function(obj) {
if(obj.get("name").endsWith("_spellname")) {
AddQueueItem(obj.get("_characterid"));
}
});
if (!state.PCMHelper) state.PCMHelper = { currentVersion:"Unknown", Queue:[] } ;
state.PCMHelper.Queue = [];
var existingMacroVersion = state.PCMHelper.currentVersion;
if (existingMacroVersion !== PCMHelper_Version) {
var html = "<table border=2 width=100%><tr><td bgcolor=goldenrod colspan=2 align=center><font color=black>PCMHelper</font></td></tr>";
html += "<tr><td colspan=2>Your PCMHelper macros are outdated</td></tr>";
html += "<tr><td>Installed Ver</td><td>" + existingMacroVersion + "</td></tr>";
html += "<tr><td>Available Ver</td><td>" + PCMHelper_Version + "</td></tr>";
html += "<tr><td colspan=2>Please consider running <strong>!pcmsetup</strong> to install the latest version of the macros</tr></tr></table>"
sendChat("PCMHelper:",html);
}
log("-=> PCMHelper v" + PCMHelper_Version + " <=- [" + PCMHelper_LastUpdated + "]");
handleQueue();
});
function handleQueue() {
queueProcessor = setInterval(function(){
processQueue();
},5000);
}
function processQueue() {
if (state.PCMHelper.Queue !== undefined && state.PCMHelper.Queue.length > 0 ) {
var procLength = (20 >= state.PCMHelper.Queue.Length ? state.PCMHelper.Queue.Length : 20)
for (var x=0; x<procLength; x++) {
if (state.PCMHelper.Queue.length > 0){
var thisChar = findObjs({type:"character", id:state.PCMHelper.Queue[0]})[0];
log(`Processing character ${state.PCMHelper.Queue[0]} for ${thisChar.get("name")};`);
processCharacter(state.PCMHelper.Queue[0]);
processNPC(state.PCMHelper.Queue[0]);
processSpells(state.PCMHelper.Queue[0]);
state.PCMHelper.Queue.shift();
}
}
log(`PCMHelper : Queue Length is now ${state.PCMHelper.Queue.length}`);
}
}
function AddQueueItem(charID) {
if (!state.PCMHelper.Queue.includes(charID)) {
state.PCMHelper.Queue.push(charID);
}
}
function IsInQueue(charID) {
var found = false;
if (state.PCMHelper.Queue == undefined) {
state.PCMHelper.Queue = "";
found = false;
}
if (state.PCMHelper.Queue.indexOf(charID) !== -1) {
found = true;
}
return found;
}
function processCharacter(charID)
{
// Only run on tokens that represent characters (PCs or NPCs)
var atklist = "";
var attrCount = 0;
var attrs = getRepeatingSectionAttrs(charID, "repeating_attack");
var attrLen = 0;
if (attrs !== undefined) {
attrLen = attrs[0].length;
}
if (attrLen > 0) {
do {
var key="repeating_attack_$" + attrCount + "_atkname";
thisAttr = getAttrByName(charID, "repeating_attack_$" + attrCount + "_atkname");
var isAttack = getAttrByName(charID, "repeating_attack_$" + attrCount + "_atkflag");
if (isAttack !== "0") {
if (thisAttr !== "") {
atklist += thisAttr + "|";
}
}
attrCount += 1;
} while (thisAttr !== "" && attrCount < attrLen);
}
oldAttrs = findObjs({ _type:"attribute", _characterid:charID, name: "attacklist"});
if (oldAttrs.length > 0) {
oldAttrs.forEach(function(element) { element.remove(); });
}
if (atklist !== "") {
atklist = atklist.slice(0,-1);
createObj("attribute", { _characterid: charID, name: "attacklist", current: atklist });
}
}
function getAttackInfo(msg, player_obj) {
// Run through all selected tokens
msg.selected.forEach(function(selected){
var tokenID;
var graphicObj;
var charObj;
var charID;
// Retrieve information about what this token represents
tokenID = selected._id;
if (tokenID !== undefined) {
graphicObj = getObj("graphic", tokenID);
}
if (graphicObj !== undefined) {
charObj = getObj("character", graphicObj.get("represents"));
}
if (charObj !== undefined) {
charID = charObj.get("_id");
}
if (charID !== undefined) {
processCharacter(charID);
}
});
}
function processNPC(charID)
{
// Only run on tokens that represent characters (PCs or NPCs)
var attrCount = 0;
var actionList = "";
var legendaryList = "";
var attrs = getRepeatingSectionAttrs(charID, "repeating_npcaction");
var lattrs = getRepeatingSectionAttrs(charID, "repeating_npcaction-l");
var attrLen = 0;
var lattrLen = 0;
if (attrs !== undefined) {
attrLen = attrs[0].length;
}
if (lattrs !== undefined) {
lattrLen = lattrs[0].length;
}
if (attrLen > 0) {
do {
var key="repeating_npcaction_$" + attrCount + "_atkname";
thisAttr = getAttrByName(charID, "repeating_npcaction_$" + attrCount + "_name");
if (thisAttr !== "") {
actionList += thisAttr + "|";
}
attrCount += 1;
} while (thisAttr !== "" && attrCount < attrLen);
}
var attrCount = 0;
if (lattrLen > 0) {
do {
var key="repeating_npcaction-l_$" + attrCount + "_atkname";
thisAttr = getAttrByName(charID, "repeating_npcaction-l_$" + attrCount + "_name");
if (thisAttr !== "") {
legendaryList += thisAttr + "|";
}
attrCount += 1;
} while (thisAttr !== "" && attrCount < lattrLen);
}
oldAttrs = findObjs({ _type:"attribute", _characterid:charID, name: "npcactionlist"});
if (oldAttrs.length > 0) {
oldAttrs.forEach(function(element) { element.remove(); });
}
oldAttrs = findObjs({ _type:"attribute", _characterid:charID, name: "legendaryactionlist"});
if (oldAttrs.length > 0) {
oldAttrs.forEach(function(element) { element.remove(); });
}
if (actionList !== "") {
actionList = actionList.slice(0,-1);
createObj("attribute", { _characterid: charID, name: "npcactionlist", current: actionList });
}
if (legendaryList !== "") {
legendaryList = legendaryList.slice(0,-1);
createObj("attribute", { _characterid: charID, name: "legendaryactionlist", current: legendaryList });
}
}
function generatePlayerFormats()
{
var chars = findObjs({
_type: 'character'
});
var playerChars = [];
for (var x=0; x<chars.length; x++) {
if (chars[x].get("controlledby").startsWith("-")) {
playerChars.push(chars[x].id);
}
}
var colorCount = 0;
var formatOutput = pc_formats + '\n';
for (var x=0; x<chars.length; x++) {
var thisChar = getObj("character", playerChars[x]);
if (thisChar !== undefined) {
log(thisChar);
var thisFormat = `${thisChar.get("name")}: --bgcolor|${color_code_list[x]} ${format_template}\n`;
formatOutput += thisFormat;
}
}
var Handouts = findObjs({
_type : "handout",
});
Handouts.forEach(function (handout) {
if (handout.get("name").startsWith("PowerCard Formats PCMHelper")) {
handout.remove();
};
});
// Create the handouts. Note the because of an API bug, the Notes cannot be set
// during creation and if an attempt is made to do that, they are bugged and can't
// be set after creation either, so create them empty.
createObj("handout", { name:"PowerCard Formats PCMHelper"});
// Now loop through the handouts again and set the notes for them.
Handouts = findObjs({
_type : "handout",
});
Handouts.forEach(function (handout) {
if (handout.get("name").startsWith("PowerCard Formats PCMHelper")) {
handout.set("notes", formatOutput);
};
});
}
function processSpells(charID) {
try {
var spell_list = filterObjs(function(z) { return (z.get("characterid") == charID && z.get("name").endsWith("spellname")); });
var cantrips = sortByKey(spell_list.filter(s => s.get("name").startsWith("repeating_spell-cantrip")), "current");
var L1Spells = sortByKey(spell_list.filter(s => s.get("name").startsWith("repeating_spell-1")), "current");
var L2Spells = sortByKey(spell_list.filter(s => s.get("name").startsWith("repeating_spell-2")), "current");
var L3Spells = sortByKey(spell_list.filter(s => s.get("name").startsWith("repeating_spell-3")), "current");
var L4Spells = sortByKey(spell_list.filter(s => s.get("name").startsWith("repeating_spell-4")), "current");
var L5Spells = sortByKey(spell_list.filter(s => s.get("name").startsWith("repeating_spell-5")), "current");
var L6Spells = sortByKey(spell_list.filter(s => s.get("name").startsWith("repeating_spell-6")), "current");
var L7Spells = sortByKey(spell_list.filter(s => s.get("name").startsWith("repeating_spell-7")), "current");
var L8Spells = sortByKey(spell_list.filter(s => s.get("name").startsWith("repeating_spell-8")), "current");
var L9Spells = sortByKey(spell_list.filter(s => s.get("name").startsWith("repeating_spell-9")), "current");
nameList = "cantrip_list|l1_spell_list|l2_spell_list|l3_spell_list|l4_spell_list|l5_spell_list|l6_spell_list|l7_spell_list|l8_spell_list|l9_spell_list";
var attrNames = nameList.split("|");
attrNames.forEach(function(attrName) {
oldAttrs = findObjs({ _type:"attribute", _characterid:charID, name: attrName} );
if (oldAttrs.length > 0)
{
oldAttrs.forEach(function(element) { element.remove(); });
}
});
var attrText = "";
if (cantrips.length > 0) {
cantrips.forEach(function(s) { attrText += s.get("current") + "|" });
attrText = attrText.slice(0,-1);
createObj("attribute", { _characterid: charID, name: "cantrip_list", current: attrText });
}
attrText = "";
if (L1Spells.length > 0) {
L1Spells.forEach(function(s) { attrText += s.get("current") + "|" });
attrText = attrText.slice(0,-1);
createObj("attribute", { _characterid: charID, name: "l1_spell_list", current: attrText });
}
attrText = "";
if (L2Spells.length > 0) {
L2Spells.forEach(function(s) { attrText += s.get("current") + "|" });
attrText = attrText.slice(0,-1);
createObj("attribute", { _characterid: charID, name: "l2_spell_list", current: attrText });
}
attrText = "";
if (L3Spells.length > 0) {
L3Spells.forEach(function(s) { attrText += s.get("current") + "|" });
attrText = attrText.slice(0,-1);
createObj("attribute", { _characterid: charID, name: "l3_spell_list", current: attrText });
}
attrText = "";
if (L4Spells.length > 0) {
L4Spells.forEach(function(s) { attrText += s.get("current") + "|" });
attrText = attrText.slice(0,-1);
createObj("attribute", { _characterid: charID, name: "l4_spell_list", current: attrText });
}
attrText = "";
if (L5Spells.length > 0) {
L5Spells.forEach(function(s) { attrText += s.get("current") + "|" });
attrText = attrText.slice(0,-1);
createObj("attribute", { _characterid: charID, name: "l5_spell_list", current: attrText });
}
attrText = "";
if (L6Spells.length > 0) {
L6Spells.forEach(function(s) { attrText += s.get("current") + "|" });
attrText = attrText.slice(0,-1);
createObj("attribute", { _characterid: charID, name: "l6_spell_list", current: attrText });
}
attrText = "";
if (L7Spells.length > 0) {
L7Spells.forEach(function(s) { attrText += s.get("current") + "|" });
attrText = attrText.slice(0,-1);
createObj("attribute", { _characterid: charID, name: "l7_spell_list", current: attrText });
}
attrText = "";
if (L8Spells.length > 0) {
L8Spells.forEach(function(s) { attrText += s.get("current") + "|" });
attrText = attrText.slice(0,-1);
createObj("attribute", { _characterid: charID, name: "l8_spell_list", current: attrText });
}
attrText = "";
if (L9Spells.length > 0) {
L9Spells.forEach(function(s) { attrText += s.get("current") + "|" });
attrText = attrText.slice(0,-1);
createObj("attribute", { _characterid: charID, name: "l9_spell_list", current: attrText });
}
} catch { }
}
function getNPCActionInfo(msg, player_obj) {
// Run through all selected tokens
msg.selected.forEach(function(selected){
var tokenID;
var graphicObj;
var charObj;
var charID;
// Retrieve information about what this token represents
tokenID = selected._id;
if (tokenID !== undefined) {
graphicObj = getObj("graphic", tokenID);
}
if (graphicObj !== undefined) {
charObj = getObj("character", graphicObj.get("represents"));
}
if (charObj !== undefined) {
charID = charObj.get("_id");
}
if (charID !== undefined) {
processNPC(charID);
}
});
}
function getSpellInfo(msg, player_obj) {
msg.selected.forEach(function(selected){
var tokenID;
var graphicObj;
var charObj;
var charID;
tokenID = selected._id;
if (tokenID !== undefined) {
graphicObj = getObj("graphic", tokenID);
}
if (graphicObj !== undefined) {
charObj = getObj("character", graphicObj.get("represents"));
}
if (charObj !== undefined) {
charID = charObj.get("_id");
}
if (charID !== undefined) {
processSpells(charID);
}
});
}
function sortByKey(array, key) {
return array.sort(function(a, b) {
var x = a.get(key);
var y = b.get(key);
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
});
}
const getRepeatingSectionAttrs = function (charid, prefix) {
// Input
// charid: character id
// prefix: repeating section name, e.g. 'repeating_weapons'
// Output
// repRowIds: array containing all repeating section IDs for the given prefix, ordered in the same way that the rows appear on the sheet
// repeatingAttrs: object containing all repeating attributes that exist for this section, indexed by their name
const repeatingAttrs = {},
regExp = new RegExp(`^${prefix}_(-[-A-Za-z0-9]+?|\\d+)_`);
let repOrder;
// Get attributes
findObjs({
_type: 'attribute',
_characterid: charid
}).forEach(o => {
const attrName = o.get('name');
if (attrName.search(regExp) === 0) repeatingAttrs[attrName] = o;
else if (attrName === `_reporder_${prefix}`) repOrder = o.get('current').split(',');
});
if (!repOrder) repOrder = [];
// Get list of repeating row ids by prefix from repeatingAttrs
const unorderedIds = [...new Set(Object.keys(repeatingAttrs)
.map(n => n.match(regExp))
.filter(x => !!x)
.map(a => a[1]))];
const repRowIds = [...new Set(repOrder.filter(x => unorderedIds.includes(x)).concat(unorderedIds))];
return [repRowIds, repeatingAttrs];
}
function createHandouts() {
// Start by removing existing handouts if they are in the game
var Handouts = findObjs({
_type : "handout",
});
Handouts.forEach(function (handout) {
if (handout.get("name").startsWith("PowerCard Replacements PCMHelper")) {
handout.remove();
};
if (handout.get("name").startsWith("PowerCard Templates PCMHelper")) {
handout.remove();
};
});
// Create the handouts. Note the because of an API bug, the Notes cannot be set
// during creation and if an attempt is made to do that, they are bugged and can't
// be set after creation either, so create them empty.
createObj("handout", { name:"PowerCard Replacements PCMHelper"});
createObj("handout", { name:"PowerCard Templates PCMHelper"});
// Now loop through the handouts again and set the notes for them.
Handouts = findObjs({
_type : "handout",
});
Handouts.forEach(function (handout) {
if (handout.get("name").startsWith("PowerCard Replacements PCMHelper")) {
handout.set("notes", pc_replacements);
};
if (handout.get("name").startsWith("PowerCard Templates PCMHelper")) {
handout.set("notes", pc_templates);
};
});
}
function createPCMacros(player) {
var pid = player.get("id");
var Macros = findObjs({
_type : "macro",
});
Macros.forEach(function (macro) {
if (macro.get("name") === "NPC-Action") {
macro.remove();
}
if (macro.get("name") === "NPC-Legendary") {
macro.remove();
}
if (macro.get("name") === "PC-Attack") {
macro.remove();
}
if (macro.get("name") === "Cast-Cantrip") {
macro.remove();
}
if (macro.get("name") === "Cast-L1") {
macro.remove();
}
if (macro.get("name") === "Cast-L2") {
macro.remove();
}
if (macro.get("name") === "Cast-L3") {
macro.remove();
}
if (macro.get("name") === "Cast-L4") {
macro.remove();
}
if (macro.get("name") === "Cast-L5") {
macro.remove();
}
if (macro.get("name") === "Cast-L6") {
macro.remove();
}
if (macro.get("name") === "Cast-L7") {
macro.remove();
}
if (macro.get("name") === "Cast-L8") {
macro.remove();
}
if (macro.get("name") === "Cast-L9") {
macro.remove();
}
});
createObj("macro", { name:"NPC-Action", playerid:pid });
createObj("macro", { name:"NPC-Legendary", playerid:pid });
createObj("macro", { name:"PC-Attack", playerid:pid, visibleto:"all", istokenaction:true });
createObj("macro", { name:"Cast-Cantrip", playerid:pid, visibleto:"all", istokenaction:true });
createObj("macro", { name:"Cast-L1", playerid:pid, visibleto:"all", istokenaction:true });
createObj("macro", { name:"Cast-L2", playerid:pid, visibleto:"all", istokenaction:true });
createObj("macro", { name:"Cast-L3", playerid:pid, visibleto:"all", istokenaction:true });
createObj("macro", { name:"Cast-L4", playerid:pid, visibleto:"all", istokenaction:true });
createObj("macro", { name:"Cast-L5", playerid:pid, visibleto:"all", istokenaction:true });
createObj("macro", { name:"Cast-L6", playerid:pid, visibleto:"all", istokenaction:true });
createObj("macro", { name:"Cast-L7", playerid:pid, visibleto:"all", istokenaction:true });
createObj("macro", { name:"Cast-L8", playerid:pid, visibleto:"all", istokenaction:true });
createObj("macro", { name:"Cast-L9", playerid:pid, visibleto:"all", istokenaction:true });
var Macros = findObjs({
_type : "macro",
});
Macros.forEach(function (macro) {
if (macro.get("name") === "NPC-Action") {
macro.set("action", pc_npcaction);
}
if (macro.get("name") === "NPC-Legendary") {
macro.set("action", pc_legendary);
}
if (macro.get("name") === "PC-Attack") {
macro.set("action", pc_pcattack);
}
if (macro.get("name") === "Cast-Cantrip") {
macro.set("action", pc_cantrip);
}
if (macro.get("name") === "Cast-L1") {
macro.set("action", pc_level1);
}
if (macro.get("name") === "Cast-L2") {
macro.set("action", pc_level2);
}
if (macro.get("name") === "Cast-L3") {
macro.set("action", pc_level3);
}
if (macro.get("name") === "Cast-L4") {
macro.set("action", pc_level4);
}
if (macro.get("name") === "Cast-L5") {
macro.set("action", pc_level5);
}
if (macro.get("name") === "Cast-L6") {
macro.set("action", pc_level6);
}
if (macro.get("name") === "Cast-L7") {
macro.set("action", pc_level7);
}
if (macro.get("name") === "Cast-L8") {
macro.set("action", pc_level8);
}
if (macro.get("name") === "Cast-L9") {
macro.set("action", pc_level9);
}
});
}
})(); | 0 | 0.895374 | 1 | 0.895374 | game-dev | MEDIA | 0.938879 | game-dev | 0.635093 | 1 | 0.635093 |
D363N6UY/MapleStory-v113-Server-Eimulator | 1,050 | Libs/scripts/npc/9201068.js | var sw;
function start() {
status = -1;
sw = cm.getEventManager("Subway");
action(1, 0, 0);
}
function action(mode, type, selection) {
status++;
if (mode == 0) {
cm.sendNext("i....");
cm.dispose();
return;
}
if (status == 0) {
if (sw == null) {
cm.sendNext("oͿ~Ц^GM");
cm.dispose();
} else if (sw.getProperty("entry").equals("true")) {
cm.sendYesNo("аݧAO_nfZaKO??");
} else if (sw.getProperty("entry").equals("false") && sw.getProperty("docked").equals("true")) {
cm.sendNext("ܩpZaKdzƥXo,ɶiHhⲼx.");
cm.dispose();
} else {
cm.sendNext("Э@ߵݴXAbzaKI");
cm.dispose();
}
} else if (status == 1) {
if (cm.getMapId() == 103000100) {
if (!cm.haveItem(4031711)) {
cm.sendNext("faKݭn#b#t4031711##k !");
} else {
cm.gainItem(4031711, -1);
cm.warp(600010004);
}
cm.dispose();
} else if (cm.getMapId() == 600010001) {
if (!cm.haveItem(4031713)) {
cm.sendNext("faKݭn#b#t4031713##k !");
} else {
cm.gainItem(4031713, -1);
cm.warp(600010002);
}
cm.dispose();
}
}
}
| 0 | 0.538717 | 1 | 0.538717 | game-dev | MEDIA | 0.847129 | game-dev | 0.744517 | 1 | 0.744517 |
Potion-Studios/BYG | 10,886 | Common/src/main/java/potionstudios/byg/common/world/feature/features/nether/BYGNetherFeatures.java | package potionstudios.byg.common.world.feature.features.nether;
import com.google.common.collect.ImmutableList;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.core.HolderGetter;
import net.minecraft.core.registries.Registries;
import net.minecraft.data.worldgen.features.FeatureUtils;
import net.minecraft.resources.ResourceKey;
import net.minecraft.util.random.SimpleWeightedRandomList;
import net.minecraft.util.valueproviders.ConstantInt;
import net.minecraft.util.valueproviders.UniformInt;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.levelgen.blockpredicates.BlockPredicate;
import net.minecraft.world.level.levelgen.feature.ConfiguredFeature;
import net.minecraft.world.level.levelgen.feature.Feature;
import net.minecraft.world.level.levelgen.feature.WeightedPlacedFeature;
import net.minecraft.world.level.levelgen.feature.configurations.*;
import net.minecraft.world.level.levelgen.feature.stateproviders.BlockStateProvider;
import net.minecraft.world.level.levelgen.feature.stateproviders.SimpleStateProvider;
import net.minecraft.world.level.levelgen.feature.stateproviders.WeightedStateProvider;
import net.minecraft.world.level.levelgen.structure.templatesystem.BlockMatchTest;
import net.minecraft.world.level.levelgen.structure.templatesystem.RuleTest;
import potionstudios.byg.common.block.BYGBlocks;
import potionstudios.byg.common.block.BYGWoodTypes;
import potionstudios.byg.common.world.feature.BYGFeatures;
import potionstudios.byg.common.world.feature.config.BYGTreeConfig;
import potionstudios.byg.common.world.feature.config.HangingColumnWithBaseConfig;
import potionstudios.byg.common.world.feature.config.QuartzSpikeConfig;
import potionstudios.byg.common.world.feature.config.SimpleBlockProviderConfig;
import potionstudios.byg.common.world.feature.placement.BYGPlacedFeaturesUtil;
import java.util.List;
import java.util.function.Supplier;
import static potionstudios.byg.common.world.feature.features.BYGFeaturesUtil.*;
public class BYGNetherFeatures {
public static final ResourceKey<ConfiguredFeature<?, ?>> SUBZERO_ASH_BLOCK = createConfiguredFeature("subzero_ash_block", () -> Feature.RANDOM_PATCH, () -> FeatureUtils.simplePatchConfiguration(Feature.SIMPLE_BLOCK, new SimpleBlockConfiguration(BlockStateProvider.simple(BYGBlocks.SUBZERO_ASH_BLOCK.get())), List.of(BYGBlocks.SUBZERO_ASH_BLOCK.get())));
public static final ResourceKey<ConfiguredFeature<?, ?>> SUBZERO_ASH = createPatchConfiguredFeatureWithBlock("subzero_ash", BYGBlocks.SUBZERO_ASH, 35);
public static final ResourceKey<ConfiguredFeature<?, ?>> QUARTZ_CRYSTAL = createPatchConfiguredFeatureWithBlock("quartz_crystal", BYGBlocks.QUARTZ_CRYSTAL, 15);
public static final Supplier<RuleTest> BRIMSTONE = () -> new BlockMatchTest(BYGBlocks.BRIMSTONE.get());
public static final Supplier<RuleTest> BLUE_NETHERRACK = () -> new BlockMatchTest(BYGBlocks.BLUE_NETHERRACK.get());
public static final Supplier<RuleTest> SCORIA_STONE = () -> new BlockMatchTest(BYGBlocks.SCORIA_STONE.get());
public static final ResourceKey<ConfiguredFeature<?, ?>> BRIMSTONE_VOLCANO = createConfiguredFeature("brimstone_volcano", BYGFeatures.VOLCANO, () -> new SimpleBlockProviderConfig(BlockStateProvider.simple(BYGBlocks.BRIMSTONE.get())));
public static final ResourceKey<ConfiguredFeature<?, ?>> QUARTZ_COLUMNS = createConfiguredFeature("quartz_columns", BYGFeatures.QUARTZ_COLUMNS, () -> new ColumnFeatureConfiguration(ConstantInt.of(1), UniformInt.of(1, 3)));
public static final ResourceKey<ConfiguredFeature<?, ?>> QUARTZ_SPIKE = createConfiguredFeature("quartz_spike", BYGFeatures.QUARTZ_SPIKES, () -> new QuartzSpikeConfig.Builder().setBlock(BYGBlocks.QUARTZITE_SAND.get()).build());
public static final ResourceKey<ConfiguredFeature<?, ?>> ORE_PENDORITE = createConfiguredFeature("ore_pendorite", () -> Feature.ORE, () -> new OreConfiguration(BLUE_NETHERRACK.get(), BYGBlocks.PENDORITE_ORE.defaultBlockState(), 6));
public static final ResourceKey<ConfiguredFeature<?, ?>> ORE_EMERALDITE = createConfiguredFeature("ore_emeraldite", () -> Feature.ORE, () -> new OreConfiguration(SCORIA_STONE.get(), BYGBlocks.EMERALDITE_ORE.defaultBlockState(), 6));
public static final ResourceKey<ConfiguredFeature<?, ?>> ORE_ANTHRACITE = createConfiguredFeature("ore_anthracite", () -> Feature.ORE, () -> new OreConfiguration(BRIMSTONE.get(), BYGBlocks.ANTHRACITE_ORE.defaultBlockState(), 10));
public static final ResourceKey<ConfiguredFeature<?, ?>> ORE_GOLD_BRIMSTONE = createConfiguredFeature("ore_gold_brimstone", () -> Feature.ORE, () -> new OreConfiguration(BRIMSTONE.get(), BYGBlocks.BRIMSTONE_NETHER_GOLD_ORE.defaultBlockState(), 10));
public static final ResourceKey<ConfiguredFeature<?, ?>> ORE_QUARTZ_BRIMSTONE = createConfiguredFeature("ore_quartz_brimstone", () -> Feature.ORE, () -> new OreConfiguration(BRIMSTONE.get(), BYGBlocks.BRIMSTONE_NETHER_QUARTZ_ORE.defaultBlockState(), 10));
public static final ResourceKey<ConfiguredFeature<?, ?>> ORE_GOLD_BLUE_NETHERRACK = createConfiguredFeature("ore_gold_blue_netherrack", () -> Feature.ORE, () -> new OreConfiguration(BLUE_NETHERRACK.get(), BYGBlocks.BLUE_NETHER_GOLD_ORE.defaultBlockState(), 10));
public static final ResourceKey<ConfiguredFeature<?, ?>> ORE_QUARTZ_BLUE_NETHERRACK = createConfiguredFeature("ore_quartz_blue_netherrack", () -> Feature.ORE, () -> new OreConfiguration(BLUE_NETHERRACK.get(), BYGBlocks.BLUE_NETHER_QUARTZ_ORE.defaultBlockState(), 10));
public static final ResourceKey<ConfiguredFeature<?, ?>> BRIMSTONE_PILLARS = createConfiguredFeature("brimstone_pillars", BYGFeatures.PILLARS, () -> new SimpleBlockProviderConfig(BlockStateProvider.simple(BYGBlocks.BRIMSTONE.get())));
public static final ResourceKey<ConfiguredFeature<?, ?>> BORIC_FIRE_PATCH = createConfiguredFeature("boric_fire_patch", () -> Feature.RANDOM_PATCH, () ->
new RandomPatchConfiguration(24, 4, 7,
BYGPlacedFeaturesUtil.createPlacedFeatureDirect(createConfiguredFeature(Feature.SIMPLE_BLOCK, new SimpleBlockConfiguration(SimpleStateProvider.simple(BYGBlocks.BORIC_FIRE.get()))),
createSolidDownAndAirAllAroundFilter(BlockPredicate.matchesBlocks(BlockPos.ZERO.relative(Direction.DOWN), BYGBlocks.BRIMSTONE.get()))))
);
public static final ResourceKey<ConfiguredFeature<?, ?>> SOUL_SOIL_PILLARS = createConfiguredFeature("soul_soil_pillars", BYGFeatures.PILLARS, () -> new SimpleBlockProviderConfig(BlockStateProvider.simple(BYGBlocks.WARPED_SOUL_SOIL.defaultBlockState())));
public static final ResourceKey<ConfiguredFeature<?, ?>> FROST_MAGMA_PILLARS = createConfiguredFeature("frost_magma_pillars", BYGFeatures.PILLARS, () -> new SimpleBlockProviderConfig(BlockStateProvider.simple(BYGBlocks.FROST_MAGMA.defaultBlockState())));
public static final ResourceKey<ConfiguredFeature<?, ?>> MAGMA_PILLARS = createConfiguredFeature("magma_pillars", BYGFeatures.PILLARS, () -> new SimpleBlockProviderConfig(BlockStateProvider.simple(BYGBlocks.MAGMATIC_STONE.defaultBlockState())));
public static final ResourceKey<ConfiguredFeature<?, ?>> HANGING_LANTERNS = createConfiguredFeature("hanging_lanterns", BYGFeatures.HANGING_FEATURE, () -> new HangingColumnWithBaseConfig.Builder().setBaseBlock(BYGBlocks.SCORIA_STONE.get()).setBlock(Blocks.CAVE_AIR.defaultBlockState()).setEndBlock(BYGBlocks.WAILING_BELL_BLOSSOM.defaultBlockState()).setMinLength(1).setMaxLength(4).setPlacementFilter(BlockPredicate.matchesBlocks(BYGBlocks.SCORIA_STONE.get())).build());
public static final ResourceKey<ConfiguredFeature<?, ?>> SYTHIAN_FUNGUS_PILLARS = createConfiguredFeature("sythian_fungus_pillars", BYGFeatures.PILLARS, () -> new SimpleBlockProviderConfig(new WeightedStateProvider(SimpleWeightedRandomList.<BlockState>builder().add(BYGWoodTypes.SYTHIAN.wood().defaultBlockState(), 9).add(BYGWoodTypes.SYTHIAN.wood().defaultBlockState(), 1))));
public static final ResourceKey<ConfiguredFeature<?, ?>> HANGING_CHAINS = createConfiguredFeature("hanging_chains", BYGFeatures.HANGING_FEATURE, () -> new HangingColumnWithBaseConfig.Builder().setBaseBlock(BYGBlocks.SCORIA_STONE.get()).setBlock(Blocks.CHAIN.defaultBlockState()).setEndBlock(Blocks.CHAIN.defaultBlockState()).setMinLength(8).setMaxLength(16).setPlacementFilter(BlockPredicate.matchesBlocks(BYGBlocks.SCORIA_STONE.get())).build());
public static final ResourceKey<ConfiguredFeature<?, ?>> SUBZERO_ASHES = createConfiguredFeature("subzero_ashes", () -> Feature.RANDOM_SELECTOR, (configuredFeatureBootstapContext) -> {
HolderGetter<ConfiguredFeature<?, ?>> lookup = configuredFeatureBootstapContext.lookup(Registries.CONFIGURED_FEATURE);
return new RandomFeatureConfiguration(ImmutableList.of(
new WeightedPlacedFeature(BYGPlacedFeaturesUtil.createPlacedFeatureDirect(lookup.getOrThrow(SUBZERO_ASH)), 0.6F)),
BYGPlacedFeaturesUtil.createPlacedFeatureDirect(lookup.getOrThrow(((SUBZERO_ASH_BLOCK)))));
}
);
public static final ResourceKey<ConfiguredFeature<?, ?>> WAILING_PILLAR = createConfiguredFeature("wailing_pillar1", BYGFeatures.WAILING_PILLAR1, () -> new BYGTreeConfig.Builder().setTrunkBlock(new WeightedStateProvider(SimpleWeightedRandomList.<BlockState>builder().add(Blocks.BASALT.defaultBlockState(), 8).add(Blocks.POLISHED_BASALT.defaultBlockState(), 2))).setLeavesBlock(new WeightedStateProvider(SimpleWeightedRandomList.<BlockState>builder().add(Blocks.POLISHED_BLACKSTONE_BRICKS.defaultBlockState(), 4).add(Blocks.CRACKED_POLISHED_BLACKSTONE_BRICKS.defaultBlockState(), 3).add(Blocks.BLACKSTONE.defaultBlockState(), 2).add(BYGBlocks.DUSTED_POLISHED_BLACKSTONE_BRICKS.defaultBlockState(), 3))).setMaxHeight(30).setMinHeight(22).build());
public static final ResourceKey<ConfiguredFeature<?, ?>> NYLIUM_SOUL_PATCH_FIRE = createConfiguredFeature("nylium_soul_patch_fire", () -> Feature.RANDOM_PATCH, () -> FeatureUtils.simplePatchConfiguration(Feature.SIMPLE_BLOCK, new SimpleBlockConfiguration(BlockStateProvider.simple(Blocks.SOUL_FIRE)), List.of(BYGBlocks.WARPED_SOUL_SOIL.get(), BYGBlocks.WARPED_SOUL_SAND.get())));
public static final ResourceKey<ConfiguredFeature<?, ?>> MAGMA_PATCH_FIRE = createConfiguredFeature("magma_patch_fire", () -> Feature.RANDOM_PATCH, () -> FeatureUtils.simplePatchConfiguration(Feature.SIMPLE_BLOCK, new SimpleBlockConfiguration(BlockStateProvider.simple(Blocks.FIRE)), List.of(BYGBlocks.MAGMATIC_STONE.get())));
public static final ResourceKey<ConfiguredFeature<?, ?>> SUBZERO_CRYSTAL = createConfiguredFeature("subzero_crystal", BYGFeatures.SUBZERO_CRYSTAL, () -> FeatureConfiguration.NONE);
public static void loadClass() {
}
}
| 0 | 0.826328 | 1 | 0.826328 | game-dev | MEDIA | 0.991431 | game-dev | 0.922449 | 1 | 0.922449 |
chai3d/chai3d | 4,474 | modules/Bullet/externals/bullet/src/Bullet3Serialize/Bullet2FileLoader/b3File.h | /*
bParse
Copyright (c) 2006-2009 Charlie C & Erwin Coumans http://gamekit.googlecode.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.
*/
#ifndef __BFILE_H__
#define __BFILE_H__
#include "b3Common.h"
#include "b3Chunk.h"
#include <stdio.h>
namespace bParse {
// ----------------------------------------------------- //
enum bFileFlags
{
FD_INVALID =0,
FD_OK =1,
FD_VOID_IS_8 =2,
FD_ENDIAN_SWAP =4,
FD_FILE_64 =8,
FD_BITS_VARIES =16,
FD_VERSION_VARIES = 32,
FD_DOUBLE_PRECISION =64,
FD_BROKEN_DNA = 128
};
enum bFileVerboseMode
{
FD_VERBOSE_EXPORT_XML = 1,
FD_VERBOSE_DUMP_DNA_TYPE_DEFINITIONS = 2,
FD_VERBOSE_DUMP_CHUNKS = 4,
FD_VERBOSE_DUMP_FILE_INFO=8,
};
// ----------------------------------------------------- //
class bFile
{
protected:
char m_headerString[7];
bool mOwnsBuffer;
char* mFileBuffer;
int mFileLen;
int mVersion;
bPtrMap mLibPointers;
int mDataStart;
bDNA* mFileDNA;
bDNA* mMemoryDNA;
b3AlignedObjectArray<char*> m_pointerFixupArray;
b3AlignedObjectArray<char*> m_pointerPtrFixupArray;
b3AlignedObjectArray<bChunkInd> m_chunks;
b3HashMap<b3HashPtr, bChunkInd> m_chunkPtrPtrMap;
//
bPtrMap mDataPointers;
int mFlags;
// ////////////////////////////////////////////////////////////////////////////
// buffer offset util
int getNextBlock(bChunkInd *dataChunk, const char *dataPtr, const int flags);
void safeSwapPtr(char *dst, const char *src);
virtual void parseHeader();
virtual void parseData() = 0;
void resolvePointersMismatch();
void resolvePointersChunk(const bChunkInd& dataChunk, int verboseMode);
int resolvePointersStructRecursive(char *strcPtr, int old_dna, int verboseMode, int recursion);
//void swapPtr(char *dst, char *src);
void parseStruct(char *strcPtr, char *dtPtr, int old_dna, int new_dna, bool fixupPointers);
void getMatchingFileDNA(short* old, const char* lookupName, const char* lookupType, char *strcData, char *data, bool fixupPointers);
char* getFileElement(short *firstStruct, char *lookupName, char *lookupType, char *data, short **foundPos);
void swap(char *head, class bChunkInd& ch, bool ignoreEndianFlag);
void swapData(char *data, short type, int arraySize, bool ignoreEndianFlag);
void swapStruct(int dna_nr, char *data, bool ignoreEndianFlag);
void swapLen(char *dataPtr);
void swapDNA(char* ptr);
char* readStruct(char *head, class bChunkInd& chunk);
char *getAsString(int code);
void parseInternal(int verboseMode, char* memDna,int memDnaLength);
public:
bFile(const char *filename, const char headerString[7]);
//todo: make memoryBuffer const char
//bFile( const char *memoryBuffer, int len);
bFile( char *memoryBuffer, int len, const char headerString[7]);
virtual ~bFile();
bDNA* getFileDNA()
{
return mFileDNA;
}
virtual void addDataBlock(char* dataBlock) = 0;
int getFlags() const
{
return mFlags;
}
bPtrMap& getLibPointers()
{
return mLibPointers;
}
void* findLibPointer(void *ptr);
bool ok();
virtual void parse(int verboseMode) = 0;
virtual int write(const char* fileName, bool fixupPointers=false) = 0;
virtual void writeChunks(FILE* fp, bool fixupPointers );
virtual void writeDNA(FILE* fp) = 0;
void updateOldPointers();
void resolvePointers(int verboseMode);
void dumpChunks(bDNA* dna);
int getVersion() const
{
return mVersion;
}
//pre-swap the endianness, so that data loaded on a target with different endianness doesn't need to be swapped
void preSwap();
void writeFile(const char* fileName);
};
}
#endif//__BFILE_H__
| 0 | 0.619118 | 1 | 0.619118 | game-dev | MEDIA | 0.365978 | game-dev | 0.563622 | 1 | 0.563622 |
followingthefasciaplane/source-engine-diff-check | 27,716 | misc/game/server/vscript_server.cpp | //========== Copyright 2008, Valve Corporation, All rights reserved. ========
//
// Purpose:
//
//=============================================================================
#include "cbase.h"
#include "vscript_server.h"
#include "icommandline.h"
#include "tier1/utlbuffer.h"
#include "tier1/fmtstr.h"
#include "filesystem.h"
#include "eventqueue.h"
#include "characterset.h"
#include "sceneentity.h" // for exposing scene precache function
#include "isaverestore.h"
#include "gamerules.h"
#include "particle_parse.h"
#if defined( _WIN32 ) || defined( POSIX )
#include "vscript_server_nut.h"
#endif
#ifdef DOTA_DLL
#include "dota_animation.h"
#endif
extern ScriptClassDesc_t * GetScriptDesc( CBaseEntity * );
// #define VMPROFILE 1
#ifdef VMPROFILE
#define VMPROF_START float debugStartTime = Plat_FloatTime();
#define VMPROF_SHOW( funcname, funcdesc ) DevMsg("***VSCRIPT PROFILE***: %s %s: %6.4f milliseconds\n", (##funcname), (##funcdesc), (Plat_FloatTime() - debugStartTime)*1000.0 );
#else // !VMPROFILE
#define VMPROF_START
#define VMPROF_SHOW
#endif // VMPROFILE
ConVar script_connect_debugger_on_mapspawn( "script_connect_debugger_on_mapspawn", "0" );
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
class CScriptEntityIterator
{
public:
HSCRIPT First() { return Next(NULL); }
HSCRIPT Next( HSCRIPT hStartEntity )
{
return ToHScript( gEntList.NextEnt( ToEnt( hStartEntity ) ) );
}
HSCRIPT CreateByClassname( const char *className )
{
return ToHScript( CreateEntityByName( className ) );
}
HSCRIPT FindByClassname( HSCRIPT hStartEntity, const char *szName )
{
return ToHScript( gEntList.FindEntityByClassname( ToEnt( hStartEntity ), szName ) );
}
HSCRIPT FindByName( HSCRIPT hStartEntity, const char *szName )
{
return ToHScript( gEntList.FindEntityByName( ToEnt( hStartEntity ), szName ) );
}
HSCRIPT FindInSphere( HSCRIPT hStartEntity, const Vector &vecCenter, float flRadius )
{
return ToHScript( gEntList.FindEntityInSphere( ToEnt( hStartEntity ), vecCenter, flRadius ) );
}
HSCRIPT FindByTarget( HSCRIPT hStartEntity, const char *szName )
{
return ToHScript( gEntList.FindEntityByTarget( ToEnt( hStartEntity ), szName ) );
}
HSCRIPT FindByModel( HSCRIPT hStartEntity, const char *szModelName )
{
return ToHScript( gEntList.FindEntityByModel( ToEnt( hStartEntity ), szModelName ) );
}
HSCRIPT FindByNameNearest( const char *szName, const Vector &vecSrc, float flRadius )
{
return ToHScript( gEntList.FindEntityByNameNearest( szName, vecSrc, flRadius ) );
}
HSCRIPT FindByNameWithin( HSCRIPT hStartEntity, const char *szName, const Vector &vecSrc, float flRadius )
{
return ToHScript( gEntList.FindEntityByNameWithin( ToEnt( hStartEntity ), szName, vecSrc, flRadius ) );
}
HSCRIPT FindByClassnameNearest( const char *szName, const Vector &vecSrc, float flRadius )
{
return ToHScript( gEntList.FindEntityByClassnameNearest( szName, vecSrc, flRadius ) );
}
HSCRIPT FindByClassnameWithin( HSCRIPT hStartEntity , const char *szName, const Vector &vecSrc, float flRadius )
{
return ToHScript( gEntList.FindEntityByClassnameWithin( ToEnt( hStartEntity ), szName, vecSrc, flRadius ) );
}
private:
} g_ScriptEntityIterator;
BEGIN_SCRIPTDESC_ROOT_NAMED( CScriptEntityIterator, "CEntities", SCRIPT_SINGLETON "The global list of entities" )
DEFINE_SCRIPTFUNC( First, "Begin an iteration over the list of entities" )
DEFINE_SCRIPTFUNC( Next, "Continue an iteration over the list of entities, providing reference to a previously found entity" )
DEFINE_SCRIPTFUNC( CreateByClassname, "Creates an entity by classname" )
DEFINE_SCRIPTFUNC( FindByClassname, "Find entities by class name. Pass 'null' to start an iteration, or reference to a previously found entity to continue a search" )
DEFINE_SCRIPTFUNC( FindByName, "Find entities by name. Pass 'null' to start an iteration, or reference to a previously found entity to continue a search" )
DEFINE_SCRIPTFUNC( FindInSphere, "Find entities within a radius. Pass 'null' to start an iteration, or reference to a previously found entity to continue a search" )
DEFINE_SCRIPTFUNC( FindByTarget, "Find entities by targetname. Pass 'null' to start an iteration, or reference to a previously found entity to continue a search" )
DEFINE_SCRIPTFUNC( FindByModel, "Find entities by model name. Pass 'null' to start an iteration, or reference to a previously found entity to continue a search" )
DEFINE_SCRIPTFUNC( FindByNameNearest, "Find entities by name nearest to a point." )
DEFINE_SCRIPTFUNC( FindByNameWithin, "Find entities by name within a radius. Pass 'null' to start an iteration, or reference to a previously found entity to continue a search" )
DEFINE_SCRIPTFUNC( FindByClassnameNearest, "Find entities by class name nearest to a point." )
DEFINE_SCRIPTFUNC( FindByClassnameWithin, "Find entities by class name within a radius. Pass 'null' to start an iteration, or reference to a previously found entity to continue a search" )
END_SCRIPTDESC();
// ----------------------------------------------------------------------------
// KeyValues access - CBaseEntity::ScriptGetKeyFromModel returns root KeyValues
// ----------------------------------------------------------------------------
BEGIN_SCRIPTDESC_ROOT( CScriptKeyValues, "Wrapper class over KeyValues instance" )
DEFINE_SCRIPT_CONSTRUCTOR()
DEFINE_SCRIPTFUNC_NAMED( ScriptFindKey, "FindKey", "Given a KeyValues object and a key name, find a KeyValues object associated with the key name" );
DEFINE_SCRIPTFUNC_NAMED( ScriptGetFirstSubKey, "GetFirstSubKey", "Given a KeyValues object, return the first sub key object" );
DEFINE_SCRIPTFUNC_NAMED( ScriptGetNextKey, "GetNextKey", "Given a KeyValues object, return the next key object in a sub key group" );
DEFINE_SCRIPTFUNC_NAMED( ScriptGetKeyValueInt, "GetKeyInt", "Given a KeyValues object and a key name, return associated integer value" );
DEFINE_SCRIPTFUNC_NAMED( ScriptGetKeyValueFloat, "GetKeyFloat", "Given a KeyValues object and a key name, return associated float value" );
DEFINE_SCRIPTFUNC_NAMED( ScriptGetKeyValueBool, "GetKeyBool", "Given a KeyValues object and a key name, return associated bool value" );
DEFINE_SCRIPTFUNC_NAMED( ScriptGetKeyValueString, "GetKeyString", "Given a KeyValues object and a key name, return associated string value" );
DEFINE_SCRIPTFUNC_NAMED( ScriptIsKeyValueEmpty, "IsKeyEmpty", "Given a KeyValues object and a key name, return true if key name has no value" );
DEFINE_SCRIPTFUNC_NAMED( ScriptReleaseKeyValues, "ReleaseKeyValues", "Given a root KeyValues object, release its contents" );
END_SCRIPTDESC();
HSCRIPT CScriptKeyValues::ScriptFindKey( const char *pszName )
{
KeyValues *pKeyValues = m_pKeyValues->FindKey(pszName);
if ( pKeyValues == NULL )
return NULL;
CScriptKeyValues *pScriptKey = new CScriptKeyValues( pKeyValues );
// UNDONE: who calls ReleaseInstance on this??
HSCRIPT hScriptInstance = g_pScriptVM->RegisterInstance( pScriptKey );
return hScriptInstance;
}
HSCRIPT CScriptKeyValues::ScriptGetFirstSubKey( void )
{
KeyValues *pKeyValues = m_pKeyValues->GetFirstSubKey();
if ( pKeyValues == NULL )
return NULL;
CScriptKeyValues *pScriptKey = new CScriptKeyValues( pKeyValues );
// UNDONE: who calls ReleaseInstance on this??
HSCRIPT hScriptInstance = g_pScriptVM->RegisterInstance( pScriptKey );
return hScriptInstance;
}
HSCRIPT CScriptKeyValues::ScriptGetNextKey( void )
{
KeyValues *pKeyValues = m_pKeyValues->GetNextKey();
if ( pKeyValues == NULL )
return NULL;
CScriptKeyValues *pScriptKey = new CScriptKeyValues( pKeyValues );
// UNDONE: who calls ReleaseInstance on this??
HSCRIPT hScriptInstance = g_pScriptVM->RegisterInstance( pScriptKey );
return hScriptInstance;
}
int CScriptKeyValues::ScriptGetKeyValueInt( const char *pszName )
{
int i = m_pKeyValues->GetInt( pszName );
return i;
}
float CScriptKeyValues::ScriptGetKeyValueFloat( const char *pszName )
{
float f = m_pKeyValues->GetFloat( pszName );
return f;
}
const char *CScriptKeyValues::ScriptGetKeyValueString( const char *pszName )
{
const char *psz = m_pKeyValues->GetString( pszName );
return psz;
}
bool CScriptKeyValues::ScriptIsKeyValueEmpty( const char *pszName )
{
bool b = m_pKeyValues->IsEmpty( pszName );
return b;
}
bool CScriptKeyValues::ScriptGetKeyValueBool( const char *pszName )
{
bool b = m_pKeyValues->GetBool( pszName );
return b;
}
void CScriptKeyValues::ScriptReleaseKeyValues( )
{
m_pKeyValues->deleteThis();
m_pKeyValues = NULL;
}
// constructors
CScriptKeyValues::CScriptKeyValues( KeyValues *pKeyValues )
{
m_pKeyValues = pKeyValues;
}
// destructor
CScriptKeyValues::~CScriptKeyValues( )
{
if (m_pKeyValues)
{
m_pKeyValues->deleteThis();
}
m_pKeyValues = NULL;
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
static float Time()
{
return gpGlobals->curtime;
}
static float FrameTime()
{
return gpGlobals->frametime;
}
static void SendToConsole( const char *pszCommand )
{
CBasePlayer *pPlayer = UTIL_GetLocalPlayerOrListenServerHost();
if ( !pPlayer )
{
DevMsg ("Cannot execute \"%s\", no player\n", pszCommand );
return;
}
engine->ClientCommand( pPlayer->edict(), "%s", pszCommand );
}
static void SendToConsoleServer( const char *pszCommand )
{
#if defined( CSTRIKE15 )
// Parse the text into distinct commands
const char *pCurrentCommand = pszCommand;
int nOffsetToNextCommand;
int nLen = Q_strlen( pszCommand );
for( ; nLen > 0; nLen -= nOffsetToNextCommand+1, pCurrentCommand += nOffsetToNextCommand+1 )
{
// find a \n or ; line break
int nCommandLength;
UTIL_GetNextCommandLength( pCurrentCommand, nLen, &nCommandLength, &nOffsetToNextCommand );
if ( nCommandLength <= 0 )
continue;
engine->ServerCommand( UTIL_VarArgs( "whitelistcmd %.*s\n", nCommandLength, pCurrentCommand ) );
}
#else
engine->ServerCommand( pszCommand );
#endif
}
static const char *GetMapName()
{
return STRING( gpGlobals->mapname );
}
extern ConVar loopsingleplayermaps;
static bool LoopSinglePlayerMaps()
{
return loopsingleplayermaps.GetBool();
}
static const char *DoUniqueString( const char *pszBase )
{
static char szBuf[512];
g_pScriptVM->GenerateUniqueKey( pszBase, szBuf, ARRAYSIZE(szBuf) );
return szBuf;
}
static void DoEntFire( const char *pszTarget, const char *pszAction, const char *pszValue, float delay, HSCRIPT hActivator, HSCRIPT hCaller )
{
const char *target = "", *action = "Use";
variant_t value;
target = STRING( AllocPooledString( pszTarget ) );
// Don't allow them to run anything on a point_servercommand unless they're the host player. Otherwise they can ent_fire
// and run any command on the server. Admittedly, they can only do the ent_fire if sv_cheats is on, but
// people complained about users resetting the rcon password if the server briefly turned on cheats like this:
// give point_servercommand
// ent_fire point_servercommand command "rcon_password mynewpassword"
if ( gpGlobals->maxClients > 1 && V_stricmp( target, "point_servercommand" ) == 0 )
{
return;
}
if ( *pszAction )
{
action = STRING( AllocPooledString( pszAction ) );
}
if ( *pszValue )
{
value.SetString( AllocPooledString( pszValue ) );
}
if ( delay < 0 )
{
delay = 0;
}
g_EventQueue.AddEvent( target, action, value, delay, ToEnt(hActivator), ToEnt(hCaller) );
}
static void DoRecordAchievementEvent( const char *pszAchievementname, int iPlayerIndex )
{
if ( iPlayerIndex < 0 )
{
DevWarning( "DoRecordAchievementEvent called with invalid player index (%s, %d)!\n", pszAchievementname, iPlayerIndex );
return;
}
CBasePlayer *pPlayer = NULL;
if ( iPlayerIndex > 0 )
{
pPlayer = UTIL_PlayerByIndex( iPlayerIndex );
if ( !pPlayer )
{
DevWarning( "DoRecordAchievementEvent called with a player index that doesn't resolve to a player (%s, %d)!\n", pszAchievementname, iPlayerIndex );
return;
}
}
UTIL_RecordAchievementEvent( pszAchievementname, pPlayer );
}
bool DoIncludeScript( const char *pszScript, HSCRIPT hScope )
{
if ( !VScriptRunScript( pszScript, hScope, true ) )
{
g_pScriptVM->RaiseException( CFmtStr( "Failed to include script \"%s\"", ( pszScript ) ? pszScript : "unknown" ) );
return false;
}
return true;
}
int GetDeveloperLevel()
{
return developer.GetInt();
}
static void ScriptDispatchParticleEffect( const char *pszParticleName, const Vector &vOrigin, const Vector &vAngle )
{
QAngle qAngle;
VectorAngles( vAngle, qAngle );
DispatchParticleEffect( pszParticleName, vOrigin, qAngle );
}
HSCRIPT CreateProp( const char *pszEntityName, const Vector &vOrigin, const char *pszModelName, int iAnim )
{
CBaseAnimating *pBaseEntity = (CBaseAnimating *)CreateEntityByName( pszEntityName );
pBaseEntity->SetAbsOrigin( vOrigin );
pBaseEntity->SetModel( pszModelName );
pBaseEntity->SetPlaybackRate( 1.0f );
int iSequence = pBaseEntity->SelectWeightedSequence( (Activity)iAnim );
if ( iSequence != -1 )
{
pBaseEntity->SetSequence( iSequence );
}
return ToHScript( pBaseEntity );
}
//--------------------------------------------------------------------------------------------------
// Use an entity's script instance to add an entity IO event (used for firing events on unnamed entities from vscript)
//--------------------------------------------------------------------------------------------------
static void DoEntFireByInstanceHandle( HSCRIPT hTarget, const char *pszAction, const char *pszValue, float delay, HSCRIPT hActivator, HSCRIPT hCaller )
{
const char *action = "Use";
variant_t value;
if ( *pszAction )
{
action = STRING( AllocPooledString( pszAction ) );
}
if ( *pszValue )
{
value.SetString( AllocPooledString( pszValue ) );
}
if ( delay < 0 )
{
delay = 0;
}
CBaseEntity* pTarget = ToEnt(hTarget);
if ( !pTarget )
{
Warning( "VScript error: DoEntFire was passed an invalid entity instance.\n" );
return;
}
g_EventQueue.AddEvent( pTarget, action, value, delay, ToEnt(hActivator), ToEnt(hCaller) );
}
static float ScriptTraceLine( const Vector &vecStart, const Vector &vecEnd, HSCRIPT entIgnore )
{
// UTIL_TraceLine( vecAbsStart, vecAbsEnd, MASK_BLOCKLOS, pLooker, COLLISION_GROUP_NONE, ptr );
trace_t tr;
CBaseEntity *pLooker = ToEnt(entIgnore);
UTIL_TraceLine( vecStart, vecEnd, MASK_NPCWORLDSTATIC, pLooker, COLLISION_GROUP_NONE, &tr);
if (tr.fractionleftsolid && tr.startsolid)
{
return 1.0 - tr.fractionleftsolid;
}
else
{
return tr.fraction;
}
}
#if defined ( PORTAL2 )
static void SetDucking( const char *pszLayerName, const char *pszMixGroupName, float factor )
{
CReliableBroadcastRecipientFilter filter;
UserMessageBegin( filter, "SetMixLayerTriggerFactor" );
WRITE_STRING( pszLayerName );
WRITE_STRING( pszMixGroupName );
WRITE_FLOAT( factor );
MessageEnd();
}
#endif
bool VScriptServerInit()
{
VMPROF_START
if( scriptmanager != NULL )
{
ScriptLanguage_t scriptLanguage = SL_DEFAULT;
char const *pszScriptLanguage;
if ( CommandLine()->CheckParm( "-scriptlang", &pszScriptLanguage ) )
{
if( !Q_stricmp(pszScriptLanguage, "gamemonkey") )
{
scriptLanguage = SL_GAMEMONKEY;
}
else if( !Q_stricmp(pszScriptLanguage, "squirrel") )
{
scriptLanguage = SL_SQUIRREL;
}
else if( !Q_stricmp(pszScriptLanguage, "python") )
{
scriptLanguage = SL_PYTHON;
}
else
{
DevWarning("-server_script does not recognize a language named '%s'. virtual machine did NOT start.\n", pszScriptLanguage );
scriptLanguage = SL_NONE;
}
}
if( scriptLanguage != SL_NONE )
{
if ( g_pScriptVM == NULL )
g_pScriptVM = scriptmanager->CreateVM( scriptLanguage );
if( g_pScriptVM )
{
Log_Msg( LOG_VScript, "VSCRIPT: Started VScript virtual machine using script language '%s'\n", g_pScriptVM->GetLanguageName() );
ScriptRegisterFunctionNamed( g_pScriptVM, UTIL_ShowMessageAll, "ShowMessage", "Print a hud message on all clients" );
ScriptRegisterFunction( g_pScriptVM, SendToConsole, "Send a string to the console as a command" );
ScriptRegisterFunction( g_pScriptVM, SendToConsoleServer, "Send a string that gets executed on the server as a ServerCommand" );
ScriptRegisterFunction( g_pScriptVM, GetMapName, "Get the name of the map.");
ScriptRegisterFunction( g_pScriptVM, LoopSinglePlayerMaps, "Run the single player maps in a continuous loop.");
ScriptRegisterFunctionNamed( g_pScriptVM, ScriptTraceLine, "TraceLine", "given 2 points & ent to ignore, return fraction along line that hits world or models" );
ScriptRegisterFunction( g_pScriptVM, Time, "Get the current server time" );
ScriptRegisterFunction( g_pScriptVM, FrameTime, "Get the time spent on the server in the last frame" );
ScriptRegisterFunction( g_pScriptVM, DoEntFire, SCRIPT_ALIAS( "EntFire", "Generate and entity i/o event" ) );
ScriptRegisterFunctionNamed( g_pScriptVM, DoEntFireByInstanceHandle, "EntFireByHandle", "Generate and entity i/o event. First parameter is an entity instance." );
ScriptRegisterFunction( g_pScriptVM, DoUniqueString, SCRIPT_ALIAS( "UniqueString", "Generate a string guaranteed to be unique across the life of the script VM, with an optional root string. Useful for adding data to tables when not sure what keys are already in use in that table." ) );
ScriptRegisterFunctionNamed( g_pScriptVM, ScriptCreateSceneEntity, "CreateSceneEntity", "Create a scene entity to play the specified scene." );
ScriptRegisterFunctionNamed( g_pScriptVM, NDebugOverlay::Box, "DebugDrawBox", "Draw a debug overlay box" );
ScriptRegisterFunctionNamed( g_pScriptVM, NDebugOverlay::Line, "DebugDrawLine", "Draw a debug overlay box" );
ScriptRegisterFunction( g_pScriptVM, DoIncludeScript, "Execute a script (internal)" );
ScriptRegisterFunction( g_pScriptVM, CreateProp, "Create a physics prop" );
ScriptRegisterFunctionNamed( g_pScriptVM, DoRecordAchievementEvent, "RecordAchievementEvent", "Records achievement event or progress" );
ScriptRegisterFunction( g_pScriptVM, GetDeveloperLevel, "Gets the level of 'developer'" );
ScriptRegisterFunctionNamed( g_pScriptVM, ScriptDispatchParticleEffect, "DispatchParticleEffect", "Dispatches a one-off particle system" );
#if defined ( PORTAL2 )
ScriptRegisterFunction( g_pScriptVM, SetDucking, "Set the level of an audio ducking channel" );
#endif
g_pScriptVM->RegisterAllClasses();
if ( GameRules() )
{
GameRules()->RegisterScriptFunctions();
}
g_pScriptVM->RegisterInstance( &g_ScriptEntityIterator, "Entities" );
if ( scriptLanguage == SL_SQUIRREL )
{
g_pScriptVM->Run( g_Script_vscript_server );
}
VScriptRunScript( "mapspawn", false );
if ( script_connect_debugger_on_mapspawn.GetBool() )
{
g_pScriptVM->ConnectDebugger();
}
VMPROF_SHOW( pszScriptLanguage, "virtual machine startup" );
return true;
}
else
{
DevWarning("VM Did not start!\n");
}
}
}
else
{
Log_Msg( LOG_VScript, "\nVSCRIPT: Scripting is disabled.\n" );
}
g_pScriptVM = NULL;
return false;
}
void VScriptServerTerm()
{
if( g_pScriptVM != NULL )
{
if( g_pScriptVM )
{
scriptmanager->DestroyVM( g_pScriptVM );
g_pScriptVM = NULL;
}
}
}
bool VScriptServerReplaceClosures( const char *pszScriptName, HSCRIPT hScope, bool bWarnMissing )
{
if ( !g_pScriptVM )
{
return false;
}
HSCRIPT hReplaceClosuresFunc = g_pScriptVM->LookupFunction( "__ReplaceClosures" );
if ( !hReplaceClosuresFunc )
{
return false;
}
HSCRIPT hNewScript = VScriptCompileScript( pszScriptName, bWarnMissing );
if ( !hNewScript )
{
g_pScriptVM->ReleaseFunction( hReplaceClosuresFunc );
return false;
}
g_pScriptVM->Call( hReplaceClosuresFunc, NULL, true, NULL, hNewScript, hScope );
g_pScriptVM->ReleaseFunction( hReplaceClosuresFunc );
g_pScriptVM->ReleaseScript( hNewScript );
return true;
}
CON_COMMAND( script_reload_code, "Execute a vscript file, replacing existing functions with the functions in the run script" )
{
if ( !*args[1] )
{
Log_Warning( LOG_VScript, "No script specified\n" );
return;
}
if ( !g_pScriptVM )
{
Log_Warning( LOG_VScript, "Scripting disabled or no server running\n" );
return;
}
VScriptServerReplaceClosures( args[1], NULL, true );
}
CON_COMMAND( script_reload_entity_code, "Execute all of this entity's VScripts, replacing existing functions with the functions in the run scripts" )
{
extern CBaseEntity *GetNextCommandEntity( CBasePlayer *pPlayer, const char *name, CBaseEntity *ent );
const char *pszTarget = "";
if ( *args[1] )
{
pszTarget = args[1];
}
if ( !g_pScriptVM )
{
Log_Warning( LOG_VScript, "Scripting disabled or no server running\n" );
return;
}
CBasePlayer *pPlayer = UTIL_GetCommandClient();
if ( !pPlayer )
return;
CBaseEntity *pEntity = NULL;
while ( (pEntity = GetNextCommandEntity( pPlayer, pszTarget, pEntity )) != NULL )
{
if ( pEntity->m_ScriptScope.IsInitialized() && pEntity->m_iszVScripts != NULL_STRING )
{
char szScriptsList[255];
V_strcpy_safe( szScriptsList, STRING(pEntity->m_iszVScripts) );
CUtlStringList szScripts;
V_SplitString( szScriptsList, " ", szScripts);
for( int i = 0 ; i < szScripts.Count() ; i++ )
{
VScriptServerReplaceClosures( szScripts[i], pEntity->m_ScriptScope, true );
}
}
}
}
CON_COMMAND( script_reload_think, "Execute an activation script, replacing existing functions with the functions in the run script" )
{
extern CBaseEntity *GetNextCommandEntity( CBasePlayer *pPlayer, const char *name, CBaseEntity *ent );
const char *pszTarget = "";
if ( *args[1] )
{
pszTarget = args[1];
}
if ( !g_pScriptVM )
{
Log_Warning( LOG_VScript, "Scripting disabled or no server running\n" );
return;
}
CBasePlayer *pPlayer = UTIL_GetCommandClient();
if ( !pPlayer )
return;
CBaseEntity *pEntity = NULL;
while ( (pEntity = GetNextCommandEntity( pPlayer, pszTarget, pEntity )) != NULL )
{
if ( pEntity->m_ScriptScope.IsInitialized() && pEntity->m_iszScriptThinkFunction != NULL_STRING )
{
VScriptServerReplaceClosures( STRING(pEntity->m_iszScriptThinkFunction), pEntity->m_ScriptScope, true );
}
}
}
class CVScriptGameSystem : public CAutoGameSystemPerFrame
{
public:
// Inherited from IAutoServerSystem
virtual void LevelInitPreEntity( void )
{
// <sergiy> Note: we may need script VM garbage collection at this point in the future. Currently, VM does not persist
// across level boundaries. GC is not necessary because our scripts are supposed to never create circular references
// and everything else is handled with ref counting. For the case of bugs creating circular references, the plan is to add
// diagnostics that detects such loops and warns the developer.
m_bAllowEntityCreationInScripts = true;
VScriptServerInit();
}
virtual void LevelInitPostEntity( void )
{
m_bAllowEntityCreationInScripts = false;
}
virtual void LevelShutdownPostEntity( void )
{
VScriptServerTerm();
}
virtual void FrameUpdatePostEntityThink()
{
if ( g_pScriptVM )
g_pScriptVM->Frame( gpGlobals->frametime );
}
bool m_bAllowEntityCreationInScripts;
};
CVScriptGameSystem g_VScriptGameSystem;
bool IsEntityCreationAllowedInScripts( void )
{
return g_VScriptGameSystem.m_bAllowEntityCreationInScripts;
}
static short VSCRIPT_SERVER_SAVE_RESTORE_VERSION = 2;
//-----------------------------------------------------------------------------
class CVScriptSaveRestoreBlockHandler : public CDefSaveRestoreBlockHandler
{
public:
CVScriptSaveRestoreBlockHandler() :
m_InstanceMap( DefLessFunc(const char *) )
{
}
const char *GetBlockName()
{
return "VScriptServer";
}
//---------------------------------
void Save( ISave *pSave )
{
pSave->StartBlock();
int temp = g_pScriptVM != NULL;
pSave->WriteInt( &temp );
if ( g_pScriptVM )
{
temp = g_pScriptVM->GetLanguage();
pSave->WriteInt( &temp );
CUtlBuffer buffer;
g_pScriptVM->WriteState( &buffer );
temp = buffer.TellPut();
pSave->WriteInt( &temp );
if ( temp > 0 )
{
pSave->WriteData( (const char *)buffer.Base(), temp );
}
}
pSave->EndBlock();
}
//---------------------------------
void WriteSaveHeaders( ISave *pSave )
{
pSave->WriteShort( &VSCRIPT_SERVER_SAVE_RESTORE_VERSION );
}
//---------------------------------
void ReadRestoreHeaders( IRestore *pRestore )
{
// No reason why any future version shouldn't try to retain backward compatability. The default here is to not do so.
short version;
pRestore->ReadShort( &version );
m_fDoLoad = ( version == VSCRIPT_SERVER_SAVE_RESTORE_VERSION );
}
//---------------------------------
void Restore( IRestore *pRestore, bool createPlayers )
{
if ( !m_fDoLoad && g_pScriptVM )
{
return;
}
CBaseEntity *pEnt = gEntList.FirstEnt();
while ( pEnt )
{
if ( pEnt->m_iszScriptId != NULL_STRING )
{
g_pScriptVM->RegisterClass( pEnt->GetScriptDesc() );
m_InstanceMap.Insert( STRING( pEnt->m_iszScriptId ), pEnt );
}
pEnt = gEntList.NextEnt( pEnt );
}
pRestore->StartBlock();
if ( pRestore->ReadInt() && pRestore->ReadInt() == g_pScriptVM->GetLanguage() )
{
int nBytes = pRestore->ReadInt();
if ( nBytes > 0 )
{
CUtlBuffer buffer;
buffer.EnsureCapacity( nBytes );
pRestore->ReadData( (char *)buffer.AccessForDirectRead( nBytes ), nBytes, 0 );
g_pScriptVM->ReadState( &buffer );
}
}
pRestore->EndBlock();
}
void PostRestore( void )
{
for ( int i = m_InstanceMap.FirstInorder(); i != m_InstanceMap.InvalidIndex(); i = m_InstanceMap.NextInorder( i ) )
{
CBaseEntity *pEnt = m_InstanceMap[i];
if ( pEnt->m_hScriptInstance )
{
ScriptVariant_t variant;
if ( g_pScriptVM->GetValue( STRING(pEnt->m_iszScriptId), &variant ) && variant.m_type == FIELD_HSCRIPT )
{
pEnt->m_ScriptScope.Init( variant.m_hScript, false );
pEnt->RunPrecacheScripts();
}
}
else
{
// Script system probably has no internal references
pEnt->m_iszScriptId = NULL_STRING;
}
}
m_InstanceMap.Purge();
}
CUtlMap<const char *, CBaseEntity *> m_InstanceMap;
private:
bool m_fDoLoad;
};
//-----------------------------------------------------------------------------
CVScriptSaveRestoreBlockHandler g_VScriptSaveRestoreBlockHandler;
//-------------------------------------
ISaveRestoreBlockHandler *GetVScriptSaveRestoreBlockHandler()
{
return &g_VScriptSaveRestoreBlockHandler;
}
//-----------------------------------------------------------------------------
bool CBaseEntityScriptInstanceHelper::ToString( void *p, char *pBuf, int bufSize )
{
CBaseEntity *pEntity = (CBaseEntity *)p;
if ( pEntity->GetEntityName() != NULL_STRING )
{
V_snprintf( pBuf, bufSize, "([%d] %s: %s)", pEntity->entindex(), STRING(pEntity->m_iClassname), STRING( pEntity->GetEntityName() ) );
}
else
{
V_snprintf( pBuf, bufSize, "([%d] %s)", pEntity->entindex(), STRING(pEntity->m_iClassname) );
}
return true;
}
void *CBaseEntityScriptInstanceHelper::BindOnRead( HSCRIPT hInstance, void *pOld, const char *pszId )
{
int iEntity = g_VScriptSaveRestoreBlockHandler.m_InstanceMap.Find( pszId );
if ( iEntity != g_VScriptSaveRestoreBlockHandler.m_InstanceMap.InvalidIndex() )
{
CBaseEntity *pEnt = g_VScriptSaveRestoreBlockHandler.m_InstanceMap[iEntity];
pEnt->m_hScriptInstance = hInstance;
return pEnt;
}
return NULL;
}
CBaseEntityScriptInstanceHelper g_BaseEntityScriptInstanceHelper;
| 0 | 0.85109 | 1 | 0.85109 | game-dev | MEDIA | 0.801965 | game-dev | 0.779239 | 1 | 0.779239 |
D-Programming-GDC/gcc | 9,014 | libgo/go/sync/poolqueue.go | // Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package sync
import (
"sync/atomic"
"unsafe"
)
// poolDequeue is a lock-free fixed-size single-producer,
// multi-consumer queue. The single producer can both push and pop
// from the head, and consumers can pop from the tail.
//
// It has the added feature that it nils out unused slots to avoid
// unnecessary retention of objects. This is important for sync.Pool,
// but not typically a property considered in the literature.
type poolDequeue struct {
// headTail packs together a 32-bit head index and a 32-bit
// tail index. Both are indexes into vals modulo len(vals)-1.
//
// tail = index of oldest data in queue
// head = index of next slot to fill
//
// Slots in the range [tail, head) are owned by consumers.
// A consumer continues to own a slot outside this range until
// it nils the slot, at which point ownership passes to the
// producer.
//
// The head index is stored in the most-significant bits so
// that we can atomically add to it and the overflow is
// harmless.
headTail uint64
// vals is a ring buffer of interface{} values stored in this
// dequeue. The size of this must be a power of 2.
//
// vals[i].typ is nil if the slot is empty and non-nil
// otherwise. A slot is still in use until *both* the tail
// index has moved beyond it and typ has been set to nil. This
// is set to nil atomically by the consumer and read
// atomically by the producer.
vals []eface
}
type eface struct {
typ, val unsafe.Pointer
}
const dequeueBits = 32
// dequeueLimit is the maximum size of a poolDequeue.
//
// This must be at most (1<<dequeueBits)/2 because detecting fullness
// depends on wrapping around the ring buffer without wrapping around
// the index. We divide by 4 so this fits in an int on 32-bit.
const dequeueLimit = (1 << dequeueBits) / 4
// dequeueNil is used in poolDequeue to represent interface{}(nil).
// Since we use nil to represent empty slots, we need a sentinel value
// to represent nil.
type dequeueNil *struct{}
func (d *poolDequeue) unpack(ptrs uint64) (head, tail uint32) {
const mask = 1<<dequeueBits - 1
head = uint32((ptrs >> dequeueBits) & mask)
tail = uint32(ptrs & mask)
return
}
func (d *poolDequeue) pack(head, tail uint32) uint64 {
const mask = 1<<dequeueBits - 1
return (uint64(head) << dequeueBits) |
uint64(tail&mask)
}
// pushHead adds val at the head of the queue. It returns false if the
// queue is full. It must only be called by a single producer.
func (d *poolDequeue) pushHead(val any) bool {
ptrs := atomic.LoadUint64(&d.headTail)
head, tail := d.unpack(ptrs)
if (tail+uint32(len(d.vals)))&(1<<dequeueBits-1) == head {
// Queue is full.
return false
}
slot := &d.vals[head&uint32(len(d.vals)-1)]
// Check if the head slot has been released by popTail.
typ := atomic.LoadPointer(&slot.typ)
if typ != nil {
// Another goroutine is still cleaning up the tail, so
// the queue is actually still full.
return false
}
// The head slot is free, so we own it.
if val == nil {
val = dequeueNil(nil)
}
*(*any)(unsafe.Pointer(slot)) = val
// Increment head. This passes ownership of slot to popTail
// and acts as a store barrier for writing the slot.
atomic.AddUint64(&d.headTail, 1<<dequeueBits)
return true
}
// popHead removes and returns the element at the head of the queue.
// It returns false if the queue is empty. It must only be called by a
// single producer.
func (d *poolDequeue) popHead() (any, bool) {
var slot *eface
for {
ptrs := atomic.LoadUint64(&d.headTail)
head, tail := d.unpack(ptrs)
if tail == head {
// Queue is empty.
return nil, false
}
// Confirm tail and decrement head. We do this before
// reading the value to take back ownership of this
// slot.
head--
ptrs2 := d.pack(head, tail)
if atomic.CompareAndSwapUint64(&d.headTail, ptrs, ptrs2) {
// We successfully took back slot.
slot = &d.vals[head&uint32(len(d.vals)-1)]
break
}
}
val := *(*any)(unsafe.Pointer(slot))
if val == dequeueNil(nil) {
val = nil
}
// Zero the slot. Unlike popTail, this isn't racing with
// pushHead, so we don't need to be careful here.
*slot = eface{}
return val, true
}
// popTail removes and returns the element at the tail of the queue.
// It returns false if the queue is empty. It may be called by any
// number of consumers.
func (d *poolDequeue) popTail() (any, bool) {
var slot *eface
for {
ptrs := atomic.LoadUint64(&d.headTail)
head, tail := d.unpack(ptrs)
if tail == head {
// Queue is empty.
return nil, false
}
// Confirm head and tail (for our speculative check
// above) and increment tail. If this succeeds, then
// we own the slot at tail.
ptrs2 := d.pack(head, tail+1)
if atomic.CompareAndSwapUint64(&d.headTail, ptrs, ptrs2) {
// Success.
slot = &d.vals[tail&uint32(len(d.vals)-1)]
break
}
}
// We now own slot.
val := *(*any)(unsafe.Pointer(slot))
if val == dequeueNil(nil) {
val = nil
}
// Tell pushHead that we're done with this slot. Zeroing the
// slot is also important so we don't leave behind references
// that could keep this object live longer than necessary.
//
// We write to val first and then publish that we're done with
// this slot by atomically writing to typ.
slot.val = nil
atomic.StorePointer(&slot.typ, nil)
// At this point pushHead owns the slot.
return val, true
}
// poolChain is a dynamically-sized version of poolDequeue.
//
// This is implemented as a doubly-linked list queue of poolDequeues
// where each dequeue is double the size of the previous one. Once a
// dequeue fills up, this allocates a new one and only ever pushes to
// the latest dequeue. Pops happen from the other end of the list and
// once a dequeue is exhausted, it gets removed from the list.
type poolChain struct {
// head is the poolDequeue to push to. This is only accessed
// by the producer, so doesn't need to be synchronized.
head *poolChainElt
// tail is the poolDequeue to popTail from. This is accessed
// by consumers, so reads and writes must be atomic.
tail *poolChainElt
}
type poolChainElt struct {
poolDequeue
// next and prev link to the adjacent poolChainElts in this
// poolChain.
//
// next is written atomically by the producer and read
// atomically by the consumer. It only transitions from nil to
// non-nil.
//
// prev is written atomically by the consumer and read
// atomically by the producer. It only transitions from
// non-nil to nil.
next, prev *poolChainElt
}
func storePoolChainElt(pp **poolChainElt, v *poolChainElt) {
atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(pp)), unsafe.Pointer(v))
}
func loadPoolChainElt(pp **poolChainElt) *poolChainElt {
return (*poolChainElt)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(pp))))
}
func (c *poolChain) pushHead(val any) {
d := c.head
if d == nil {
// Initialize the chain.
const initSize = 8 // Must be a power of 2
d = new(poolChainElt)
d.vals = make([]eface, initSize)
c.head = d
storePoolChainElt(&c.tail, d)
}
if d.pushHead(val) {
return
}
// The current dequeue is full. Allocate a new one of twice
// the size.
newSize := len(d.vals) * 2
if newSize >= dequeueLimit {
// Can't make it any bigger.
newSize = dequeueLimit
}
d2 := &poolChainElt{prev: d}
d2.vals = make([]eface, newSize)
c.head = d2
storePoolChainElt(&d.next, d2)
d2.pushHead(val)
}
func (c *poolChain) popHead() (any, bool) {
d := c.head
for d != nil {
if val, ok := d.popHead(); ok {
return val, ok
}
// There may still be unconsumed elements in the
// previous dequeue, so try backing up.
d = loadPoolChainElt(&d.prev)
}
return nil, false
}
func (c *poolChain) popTail() (any, bool) {
d := loadPoolChainElt(&c.tail)
if d == nil {
return nil, false
}
for {
// It's important that we load the next pointer
// *before* popping the tail. In general, d may be
// transiently empty, but if next is non-nil before
// the pop and the pop fails, then d is permanently
// empty, which is the only condition under which it's
// safe to drop d from the chain.
d2 := loadPoolChainElt(&d.next)
if val, ok := d.popTail(); ok {
return val, ok
}
if d2 == nil {
// This is the only dequeue. It's empty right
// now, but could be pushed to in the future.
return nil, false
}
// The tail of the chain has been drained, so move on
// to the next dequeue. Try to drop it from the chain
// so the next pop doesn't have to look at the empty
// dequeue again.
if atomic.CompareAndSwapPointer((*unsafe.Pointer)(unsafe.Pointer(&c.tail)), unsafe.Pointer(d), unsafe.Pointer(d2)) {
// We won the race. Clear the prev pointer so
// the garbage collector can collect the empty
// dequeue and so popHead doesn't back up
// further than necessary.
storePoolChainElt(&d2.prev, nil)
}
d = d2
}
}
| 0 | 0.961837 | 1 | 0.961837 | game-dev | MEDIA | 0.21342 | game-dev | 0.954218 | 1 | 0.954218 |
ViaVersion/ViaFabricPlus | 3,146 | src/main/java/com/viaversion/viafabricplus/injection/mixin/features/movement/constants/MixinPlayerEntity.java | /*
* This file is part of ViaFabricPlus - https://github.com/ViaVersion/ViaFabricPlus
* Copyright (C) 2021-2025 the original authors
* - FlorianMichael/EnZaXD <florian.michael07@gmail.com>
* - RK_01/RaphiMC
* Copyright (C) 2023-2025 ViaVersion and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.viaversion.viafabricplus.injection.mixin.features.movement.constants;
import com.viaversion.viafabricplus.protocoltranslator.ProtocolTranslator;
import com.viaversion.viaversion.api.protocol.version.ProtocolVersion;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.util.math.Box;
import net.minecraft.world.World;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
@Mixin(PlayerEntity.class)
public abstract class MixinPlayerEntity extends LivingEntity {
protected MixinPlayerEntity(final EntityType<? extends LivingEntity> entityType, final World world) {
super(entityType, world);
}
@Inject(method = "isSpaceAroundPlayerEmpty", at = @At("HEAD"), cancellable = true)
private void changeOffsetsForSneakingCollisionDetection(double offsetX, double offsetZ, double d, CallbackInfoReturnable<Boolean> cir) {
if (ProtocolTranslator.getTargetVersion().olderThanOrEqualTo(ProtocolVersion.v1_21_4)) {
final double constant;
if (ProtocolTranslator.getTargetVersion().olderThanOrEqualTo(ProtocolVersion.v1_20_3)) {
constant = 0.0;
} else {
constant = 1.0E-5F;
}
final Box box = getBoundingBox();
cir.setReturnValue(getEntityWorld().isSpaceEmpty(this, new Box(box.minX + offsetX, box.minY - d - constant, box.minZ + offsetZ, box.maxX + offsetX, box.minY, box.maxZ + offsetZ)));
}
}
@Redirect(method = "adjustMovementForSneaking", at = @At(value = "INVOKE", target = "Lnet/minecraft/entity/player/PlayerEntity;getStepHeight()F"))
private float modifyStepHeight(PlayerEntity instance) {
if (ProtocolTranslator.getTargetVersion().olderThanOrEqualTo(ProtocolVersion.v1_10)) {
return 1.0F;
} else {
return instance.getStepHeight();
}
}
}
| 0 | 0.627937 | 1 | 0.627937 | game-dev | MEDIA | 0.750636 | game-dev | 0.82981 | 1 | 0.82981 |
SinlessDevil/ZumaClone | 1,215 | Assets/ResourcesStatic/VFX/Casual RPG VFX/Demo/Scripts/ObjectsSwitcher.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
namespace Sveta
{
[System.Serializable]
public class UnityEventString : UnityEvent<string>
{
}
public class ObjectsSwitcher : MonoBehaviour
{
public UnityEventString outputName;
public List<GameObject> list;
private int index = 0;
public void Switch(int delta)
{
index += delta;
if (index > list.Count - 1)
{
index = 0;
}
if (index < 0)
{
index = list.Count - 1;
}
SwitchTo(index);
}
private void SwitchTo(int _index) {
for (int i = 0; i < list.Count; i++)
{
list[i].SetActive(i == _index);
}
outputName?.Invoke(list[_index].name);
}
public void Awake()
{
/*
for (int i = 0; i < list.Count; i++)
{
list[i].gameObject.SetActive(false);
}
list[0].SetActive(true);
*/
SwitchTo(0);
}
}
}
| 0 | 0.62486 | 1 | 0.62486 | game-dev | MEDIA | 0.878438 | game-dev | 0.834058 | 1 | 0.834058 |
PunishXIV/Artisan | 5,873 | Artisan/RawInformation/Character/CharacterInfo.cs | using Dalamud.Game.ClientState.Statuses;
using Dalamud.Utility.Signatures;
using ECommons.DalamudServices;
using ECommons.ExcelServices;
using FFXIVClientStructs.FFXIV.Client.Game;
using FFXIVClientStructs.FFXIV.Client.Game.UI;
using Lumina.Excel.Sheets;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Artisan.RawInformation.Character
{
public static class CharacterInfo
{
public static unsafe void UpdateCharaStats()
{
if (Svc.ClientState.LocalPlayer is null) return;
JobID = (Job)(Svc.ClientState.LocalPlayer?.ClassJob.Value.RowId ?? 0);
CharacterLevel = Svc.ClientState.LocalPlayer?.Level;
CurrentCP = Svc.ClientState.LocalPlayer.CurrentCp;
MaxCP = Svc.ClientState.LocalPlayer.MaxCp;
Craftsmanship = PlayerState.Instance()->Attributes[70];
Control = PlayerState.Instance()->Attributes[71];
FCCraftsmanshipbuff = Svc.ClientState.LocalPlayer?.StatusList.FirstOrDefault(x => x.StatusId == 356);
}
public static byte? CharacterLevel;
public static Job JobID;
public static uint CurrentCP;
public static uint MaxCP;
public static unsafe int Craftsmanship;
public static unsafe int Control;
public static unsafe Dalamud.Game.ClientState.Statuses.Status? FCCraftsmanshipbuff;
public static unsafe int JobLevel(Job job) => PlayerState.Instance()->ClassJobLevels[Svc.Data.GetExcelSheet<ClassJob>()?.GetRow((uint)job).ExpArrayIndex ?? 0];
internal static bool IsManipulationUnlocked(Job job) => job switch
{
Job.CRP => QuestUnlocked(67979),
Job.BSM => QuestUnlocked(68153),
Job.ARM => QuestUnlocked(68132),
Job.GSM => QuestUnlocked(68137),
Job.LTW => QuestUnlocked(68147),
Job.WVR => QuestUnlocked(67969),
Job.ALC => QuestUnlocked(67974),
Job.CUL => QuestUnlocked(68142),
_ => false,
};
private unsafe static bool QuestUnlocked(int v)
{
return QuestManager.IsQuestComplete((uint)v);
}
public static bool MateriaExtractionUnlocked() => QuestUnlocked(66174);
internal static uint CraftLevel() => CharacterLevel switch
{
<= 50 => (uint)CharacterLevel,
51 => 120,
52 => 125,
53 => 130,
54 => 133,
55 => 136,
56 => 139,
57 => 142,
58 => 145,
59 => 148,
60 => 150,
61 => 260,
62 => 265,
63 => 270,
64 => 273,
65 => 276,
66 => 279,
67 => 282,
68 => 285,
69 => 288,
70 => 290,
71 => 390,
72 => 395,
73 => 400,
74 => 403,
75 => 406,
76 => 409,
77 => 412,
78 => 415,
79 => 418,
80 => 420,
81 => 517,
82 => 520,
83 => 525,
84 => 530,
85 => 535,
86 => 540,
87 => 545,
88 => 550,
89 => 555,
90 => 560,
_ => 0,
};
}
internal unsafe class RecipeInformation : IDisposable
{
delegate byte HasItemBeenCraftedDelegate(uint recipe);
[Signature("40 53 48 83 EC 20 8B D9 81 F9")]
HasItemBeenCraftedDelegate GetIsGatheringItemGathered = null!;
private List<uint> Uncompletables = new List<uint>()
{
30971, 30987, 31023, 31052,31094, 31157, 31192, 31217, 30001, 30002, 30003, 30004, 30005, 30006,
30007, 30008, 30009, 30010, 30011, 30012, 30013, 30014, 30015, 30016, 30017, 30018, 30019, 30020,
30021, 30022, 30023, 30024, 30025, 30026, 30027, 30028, 30029, 30030, 30031, 30032, 30033, 30034,
30035, 30036, 30037, 30038, 30039, 30040, 30041, 30042, 30043, 30044, 30045, 30046, 30047, 30048,
30049, 30050, 30051, 30052, 30053, 30054, 30055, 30056, 30057, 30058, 30059, 30060, 30061, 30062,
30063, 30064, 30065, 30066, 30067, 30068, 30069, 30070, 30071, 30072, 30073, 30074, 30075, 30076,
30077, 30078, 30079, 30080, 30081, 30082, 30083, 30084, 30085, 30086, 30087, 30088, 30089, 30090,
30091, 30092, 30093, 30094, 30095, 30096, 30097, 30098, 30099, 30100, 30101, 30102, 30103, 30104,
30105, 30106, 30107, 30108, 30109, 30110, 30111, 30112, 30113, 30114, 30115, 30116, 30117, 30118,
30119, 30120, 30121, 30122, 30123, 30124, 30125, 30126, 30127, 30128, 30129, 30130, 30131, 30132,
30133, 30134, 30135, 30136, 30137, 30138, 30139, 30140, 30141, 30142, 30143, 30144, 30145, 30146,
30147, 30148, 30149, 30150, 30151, 30152, 30354, 30355, 30356, 30357, 30358, 30359, 30360, 30361,
30362, 30363, 30364, 30365, 30366, 30367, 30368, 30369, 30370, 30371, 30372, 30373, 30374, 30375,
30376, 30377, 30378, 30379, 30380, 30381, 30382, 30383, 30384, 30385, 30386, 30387, 30388, 30389,
30390, 30391, 30392, 30393, 30394, 30395, 30396, 30397, 30398, 30399, 30400, 30401
};
public bool HasRecipeCrafted(uint recipe)
{
if (Uncompletables.Any(x => x == recipe)) return true;
if (!LuminaSheets.RecipeSheet.ContainsKey(recipe)) return false;
if (LuminaSheets.RecipeSheet[recipe].SecretRecipeBook.RowId > 0) return true;
return GetIsGatheringItemGathered(recipe) != 0;
}
public void Dispose()
{
}
internal RecipeInformation()
{
Svc.Hook.InitializeFromAttributes(this);
}
}
}
| 0 | 0.610677 | 1 | 0.610677 | game-dev | MEDIA | 0.812497 | game-dev | 0.735948 | 1 | 0.735948 |
OGSR/OGSR-Engine | 14,897 | ogsr_engine/xrGame/PHMovementDynamicActivate.cpp |
#include "stdafx.h"
#include "phmovementcontrol.h"
#include "ExtendedGeom.h"
#include "MathUtils.h"
#include "Physics.h"
#include "Level.h"
#include "../xr_3da/GameMtlLib.h"
#include "PhysicsShellHolder.h"
extern class CPHWorld* ph_world;
ObjectContactCallbackFun* saved_callback = 0;
static float max_depth = 0.f;
struct STestCallbackPars
{
static float calback_friction_factor;
static float depth_to_use_force;
static float callback_force_factor;
static float depth_to_change_softness_pars;
static float callback_cfm_factor;
static float callback_erp_factor;
static float decrement_depth;
static float max_real_depth;
};
float STestCallbackPars::calback_friction_factor = 0.0f;
float STestCallbackPars::depth_to_use_force = 0.3f;
float STestCallbackPars::callback_force_factor = 10.f;
float STestCallbackPars::depth_to_change_softness_pars = 0.00f;
float STestCallbackPars::callback_cfm_factor = world_cfm * 0.00001f;
float STestCallbackPars::callback_erp_factor = 1.f;
float STestCallbackPars::decrement_depth = 0.f;
float STestCallbackPars::max_real_depth = 0.2f;
struct STestFootCallbackPars
{
static float calback_friction_factor;
static float depth_to_use_force;
static float callback_force_factor;
static float depth_to_change_softness_pars;
static float callback_cfm_factor;
static float callback_erp_factor;
static float decrement_depth;
static float max_real_depth;
};
float STestFootCallbackPars::calback_friction_factor = 0.3f;
float STestFootCallbackPars::depth_to_use_force = 0.3f;
float STestFootCallbackPars::callback_force_factor = 10.f;
float STestFootCallbackPars::depth_to_change_softness_pars = 0.00f;
float STestFootCallbackPars::callback_cfm_factor = world_cfm * 0.00001f;
float STestFootCallbackPars::callback_erp_factor = 1.f;
float STestFootCallbackPars::decrement_depth = 0.05f;
float STestFootCallbackPars::max_real_depth = 0.2f;
template <class Pars>
void TTestDepthCallback(bool& do_colide, bool bo1, dContact& c, SGameMtl* material_1, SGameMtl* material_2)
{
if (saved_callback)
saved_callback(do_colide, bo1, c, material_1, material_2);
if (do_colide && !material_1->Flags.test(SGameMtl::flPassable) && !material_2->Flags.test(SGameMtl::flPassable))
{
float& depth = c.geom.depth;
float test_depth = depth - Pars::decrement_depth;
save_max(max_depth, test_depth);
c.surface.mu *= Pars::calback_friction_factor;
if (test_depth > Pars::depth_to_use_force)
{
float force = Pars::callback_force_factor * ph_world->Gravity();
dBodyID b1 = dGeomGetBody(c.geom.g1);
dBodyID b2 = dGeomGetBody(c.geom.g2);
if (b1)
dBodyAddForce(b1, c.geom.normal[0] * force, c.geom.normal[1] * force, c.geom.normal[2] * force);
if (b2)
dBodyAddForce(b2, -c.geom.normal[0] * force, -c.geom.normal[1] * force, -c.geom.normal[2] * force);
dxGeomUserData* ud1 = retrieveGeomUserData(c.geom.g1);
dxGeomUserData* ud2 = retrieveGeomUserData(c.geom.g2);
if (ud1)
{
CPhysicsShell* phsl = ud1->ph_ref_object->PPhysicsShell();
if (phsl)
phsl->Enable();
}
if (ud2)
{
CPhysicsShell* phsl = ud2->ph_ref_object->PPhysicsShell();
if (phsl)
phsl->Enable();
}
do_colide = false;
}
else if (test_depth > Pars::depth_to_change_softness_pars)
{
c.surface.soft_cfm = Pars::callback_cfm_factor;
c.surface.soft_erp = Pars::callback_erp_factor;
}
limit_above(depth, Pars::max_real_depth);
}
}
ObjectContactCallbackFun* TestDepthCallback = &TTestDepthCallback<STestCallbackPars>;
ObjectContactCallbackFun* TestFootDepthCallback = &TTestDepthCallback<STestFootCallbackPars>;
///////////////////////////////////////////////////////////////////////////////////////
class CVelocityLimiter : public CPHUpdateObject
{
dBodyID m_body;
public:
float l_limit;
float y_limit;
private:
dVector3 m_safe_velocity;
dVector3 m_safe_position;
public:
CVelocityLimiter(dBodyID b, float l, float yl)
{
R_ASSERT(b);
m_body = b;
dVectorSet(m_safe_velocity, dBodyGetLinearVel(m_body));
dVectorSet(m_safe_position, dBodyGetPosition(m_body));
l_limit = l;
y_limit = yl;
}
virtual ~CVelocityLimiter()
{
Deactivate();
m_body = 0;
}
bool VelocityLimit()
{
const float* linear_velocity = dBodyGetLinearVel(m_body);
// limit velocity
bool ret = false;
if (dV_valid(linear_velocity))
{
dReal mag;
Fvector vlinear_velocity;
vlinear_velocity.set(cast_fv(linear_velocity));
mag = _sqrt(linear_velocity[0] * linear_velocity[0] + linear_velocity[2] * linear_velocity[2]); //
if (mag > l_limit)
{
dReal f = mag / l_limit;
// dBodySetLinearVel(m_body,linear_velocity[0]/f,linear_velocity[1],linear_velocity[2]/f);///f
vlinear_velocity.x /= f;
vlinear_velocity.z /= f;
ret = true;
}
mag = _abs(linear_velocity[1]);
if (mag > y_limit)
{
vlinear_velocity.y = linear_velocity[1] / mag * y_limit;
ret = true;
}
dBodySetLinearVel(m_body, vlinear_velocity.x, vlinear_velocity.y, vlinear_velocity.z);
return ret;
}
else
{
dBodySetLinearVel(m_body, m_safe_velocity[0], m_safe_velocity[1], m_safe_velocity[2]);
return true;
}
}
virtual void PhDataUpdate(dReal step)
{
const float* linear_velocity = dBodyGetLinearVel(m_body);
if (VelocityLimit())
{
dBodySetPosition(m_body, m_safe_position[0] + linear_velocity[0] * fixed_step, m_safe_position[1] + linear_velocity[1] * fixed_step,
m_safe_position[2] + linear_velocity[2] * fixed_step);
}
if (!dV_valid(dBodyGetPosition(m_body)))
dBodySetPosition(m_body, m_safe_position[0] - m_safe_velocity[0] * fixed_step, m_safe_position[1] - m_safe_velocity[1] * fixed_step,
m_safe_position[2] - m_safe_velocity[2] * fixed_step);
dVectorSet(m_safe_position, dBodyGetPosition(m_body));
dVectorSet(m_safe_velocity, linear_velocity);
}
virtual void PhTune(dReal step) { VelocityLimit(); }
};
////////////////////////////////////////////////////////////////////////////////////
class CGetContactForces : public CPHUpdateObject
{
dBodyID m_body;
float m_max_force_self;
float m_max_torque_self;
float m_max_force_self_y;
float m_max_force_self_sd;
float m_max_force_others;
float m_max_torque_others;
public:
CGetContactForces(dBodyID b)
{
R_ASSERT(b);
m_body = b;
InitValues();
}
float mf_slf() { return m_max_force_self; }
float mf_othrs() { return m_max_force_others; }
float mt_slf() { return m_max_torque_self; }
float mt_othrs() { return m_max_torque_others; }
float mf_slf_y() { return m_max_force_self_y; }
float mf_slf_sd() { return m_max_force_self_sd; }
protected:
virtual void PhTune(dReal step)
{
InitValues();
int num = dBodyGetNumJoints(m_body);
for (int i = 0; i < num; ++i)
{
dJointID joint = dBodyGetJoint(m_body, i);
if (dJointGetType(joint) == dJointTypeContact)
{
dJointSetFeedback(joint, ContactFeedBacks.add());
}
}
}
virtual void PhDataUpdate(dReal step)
{
int num = dBodyGetNumJoints(m_body);
for (int i = 0; i < num; i++)
{
dJointID joint = dBodyGetJoint(m_body, i);
if (dJointGetType(joint) == dJointTypeContact)
{
dJointFeedback* feedback = dJointGetFeedback(joint);
R_ASSERT2(feedback, "Feedback was not set!!!");
dxJoint* b_joint = (dxJoint*)joint;
dBodyID other_body = b_joint->node[1].body;
bool b_body_second = (b_joint->node[1].body == m_body);
dReal* self_force = feedback->f1;
dReal* self_torque = feedback->t1;
dReal* othrers_force = feedback->f2;
dReal* othrers_torque = feedback->t2;
if (b_body_second)
{
other_body = b_joint->node[0].body;
self_force = feedback->f2;
self_torque = feedback->t2;
othrers_force = feedback->f1;
othrers_torque = feedback->t1;
}
save_max(m_max_force_self, _sqrt(dDOT(self_force, self_force)));
save_max(m_max_torque_self, _sqrt(dDOT(self_torque, self_torque)));
save_max(m_max_force_self_y, _abs(self_force[1]));
save_max(m_max_force_self_sd, _sqrt(self_force[0] * self_force[0] + self_force[2] * self_force[2]));
if (other_body)
{
dVector3 shoulder;
dVectorSub(shoulder, dJointGetPositionContact(joint), dBodyGetPosition(other_body));
dReal shoulder_lenght = _sqrt(dDOT(shoulder, shoulder));
save_max(m_max_force_others, _sqrt(dDOT(othrers_force, othrers_force)));
if (!fis_zero(shoulder_lenght))
save_max(m_max_torque_others, _sqrt(dDOT(othrers_torque, othrers_torque)) / shoulder_lenght);
}
}
}
}
private:
void InitValues()
{
m_max_force_self = 0.f;
m_max_torque_self = 0.f;
m_max_force_others = 0.f;
m_max_torque_others = 0.f;
m_max_force_self_y = 0.f;
m_max_force_self_sd = 0.f;
}
};
/////////////////////////////////////////////////////////////////////////////////////
bool CPHMovementControl::ActivateBoxDynamic(DWORD id, int num_it /*=8*/, int num_steps /*5*/, float resolve_depth /*=0.01f*/)
{
bool character_exist = CharacterExist();
if (character_exist && trying_times[id] != u32(-1))
{
Fvector dif;
dif.sub(trying_poses[id], cast_fv(dBodyGetPosition(m_character->get_body()))); //-V595
if (Device.dwTimeGlobal - trying_times[id] < 500 && dif.magnitude() < 0.05f)
return false;
}
if (!m_character || m_character->PhysicsRefObject()->PPhysicsShell())
return false;
DWORD old_id = BoxID();
bool character_disabled = character_exist && !m_character->IsEnabled();
if (character_exist && id == old_id)
return true;
if (!character_exist)
{
CreateCharacter();
}
// m_PhysicMovementControl->ActivateBox(id);
m_character->CPHObject::activate();
ph_world->Freeze();
UnFreeze();
saved_callback = ObjectContactCallback();
SetOjectContactCallback(TestDepthCallback);
SetFootCallBack(TestFootDepthCallback);
max_depth = 0.f;
//////////////////////////////////pars///////////////////////////////////////////
// int num_it=8;
// int num_steps=5;
// float resolve_depth=0.01f;
if (!character_exist)
{
num_it = 20;
num_steps = 1;
resolve_depth = 0.1f;
}
///////////////////////////////////////////////////////////////////////
float fnum_it = float(num_it);
float fnum_steps = float(num_steps);
float fnum_steps_r = 1.f / fnum_steps;
Fvector vel;
Fvector pos;
GetCharacterVelocity(vel);
GetCharacterPosition(pos);
// const Fbox& box =Box();
float pass = character_exist ? _abs(Box().getradius() - boxes[id].getradius()) : boxes[id].getradius();
float max_vel = pass / 2.f / fnum_it / fnum_steps / fixed_step;
float max_a_vel = M_PI / 8.f / fnum_it / fnum_steps / fixed_step;
dBodySetForce(GetBody(), 0.f, 0.f, 0.f);
dBodySetLinearVel(GetBody(), 0.f, 0.f, 0.f);
Calculate(Fvector().set(0, 0, 0), Fvector().set(1, 0, 0), 0, 0, 0, 0);
CVelocityLimiter vl(GetBody(), max_vel, max_vel);
max_vel = 1.f / fnum_it / fnum_steps / fixed_step;
bool ret = false;
m_character->SwitchOFFInitContact();
vl.Activate();
vl.l_limit *= (fnum_it * fnum_steps / 5.f);
vl.y_limit = vl.l_limit;
////////////////////////////////////
for (int m = 0; 30 > m; ++m)
{
Calculate(Fvector().set(0, 0, 0), Fvector().set(1, 0, 0), 0, 0, 0, 0);
EnableCharacter();
m_character->ApplyForce(0, ph_world->Gravity() * m_character->Mass(), 0);
max_depth = 0.f;
ph_world->Step();
if (max_depth < resolve_depth)
{
break;
}
ph_world->CutVelocity(max_vel, max_a_vel);
}
vl.l_limit /= (fnum_it * fnum_steps / 5.f);
vl.y_limit = vl.l_limit;
/////////////////////////////////////
for (int m = 0; num_steps > m; ++m)
{
float param = fnum_steps_r * (1 + m);
InterpolateBox(id, param);
ret = false;
for (int i = 0; num_it > i; ++i)
{
max_depth = 0.f;
Calculate(Fvector().set(0, 0, 0), Fvector().set(1, 0, 0), 0, 0, 0, 0);
EnableCharacter();
m_character->ApplyForce(0, ph_world->Gravity() * m_character->Mass(), 0);
ph_world->Step();
ph_world->CutVelocity(max_vel, max_a_vel);
if (max_depth < resolve_depth)
{
ret = true;
break;
}
}
if (!ret)
break;
}
m_character->SwitchInInitContact();
vl.Deactivate();
ph_world->UnFreeze();
if (!ret)
{
if (!character_exist)
DestroyCharacter();
else if (character_disabled)
m_character->Disable();
ActivateBox(old_id);
SetVelocity(vel);
dBodyID b = GetBody();
if (b)
{
dMatrix3 R;
dRSetIdentity(R);
dBodySetAngularVel(b, 0.f, 0.f, 0.f);
dBodySetRotation(b, R);
}
SetPosition(pos);
// Msg("can not activate!");
}
else
{
ActivateBox(id);
// Msg("activate!");
}
SetOjectContactCallback(saved_callback);
SetVelocity(vel);
saved_callback = 0;
if (!ret && character_exist)
{
trying_times[id] = Device.dwTimeGlobal;
trying_poses[id].set(cast_fv(dBodyGetPosition(m_character->get_body())));
}
else
{
trying_times[id] = u32(-1);
}
return ret;
}
| 0 | 0.944014 | 1 | 0.944014 | game-dev | MEDIA | 0.96559 | game-dev | 0.952855 | 1 | 0.952855 |
CharlesWiltgen/taglib-wasm | 8,753 | tests/arena-memory-safety.test.ts | /**
* Memory safety tests for Arena allocator
* Verifies correct allocation, growth, reset, and cleanup behavior
*/
import { beforeEach, describe, it } from "@std/testing/bdd";
import { assert, assertEquals, assertNotEquals } from "@std/assert";
// Mock arena implementation for testing the interface
// In actual tests, this would call into the WASI module
interface MockArena {
ptr: Uint8Array;
size: number;
used: number;
}
class ArenaTestHelper {
private arenas: Map<number, MockArena> = new Map();
private nextId = 1;
create(initialSize: number): number {
const arena: MockArena = {
ptr: new Uint8Array(initialSize),
size: initialSize,
used: 0,
};
const id = this.nextId++;
this.arenas.set(id, arena);
return id;
}
alloc(arenaId: number, size: number): number | null {
const arena = this.arenas.get(arenaId);
if (!arena) return null;
// Align to 8-byte boundaries
const alignedSize = (size + 7) & ~7;
if (arena.used + alignedSize > arena.size) {
// Grow arena (double size)
let newSize = arena.size * 2;
while (newSize < arena.used + alignedSize) {
newSize *= 2;
}
const newPtr = new Uint8Array(newSize);
newPtr.set(arena.ptr);
arena.ptr = newPtr;
arena.size = newSize;
}
const offset = arena.used;
arena.used += alignedSize;
return offset;
}
reset(arenaId: number): boolean {
const arena = this.arenas.get(arenaId);
if (!arena) return false;
arena.used = 0;
return true;
}
destroy(arenaId: number): boolean {
return this.arenas.delete(arenaId);
}
getStats(arenaId: number) {
const arena = this.arenas.get(arenaId);
if (!arena) return null;
return {
size: arena.size,
used: arena.used,
available: arena.size - arena.used,
utilization: arena.used / arena.size,
};
}
}
describe("Arena Memory Management", () => {
let helper: ArenaTestHelper;
beforeEach(() => {
helper = new ArenaTestHelper();
});
describe("Arena creation", () => {
it("should create arena with specified initial size", () => {
const arenaId = helper.create(1024);
assert(arenaId > 0);
const stats = helper.getStats(arenaId);
assertEquals(stats?.size, 1024);
assertEquals(stats?.used, 0);
assertEquals(stats?.available, 1024);
});
it("should handle multiple arena creation", () => {
const arena1 = helper.create(1024);
const arena2 = helper.create(2048);
const arena3 = helper.create(512);
assertNotEquals(arena1, arena2);
assertNotEquals(arena2, arena3);
assertNotEquals(arena1, arena3);
assertEquals(helper.getStats(arena1)?.size, 1024);
assertEquals(helper.getStats(arena2)?.size, 2048);
assertEquals(helper.getStats(arena3)?.size, 512);
});
});
describe("Memory allocation", () => {
it("should allocate memory within arena", () => {
const arenaId = helper.create(1024);
const ptr1 = helper.alloc(arenaId, 100);
assertEquals(ptr1, 0); // First allocation at offset 0
const ptr2 = helper.alloc(arenaId, 200);
assertEquals(ptr2, 104); // Second allocation (aligned to 8 bytes: 100 + 4 padding)
const stats = helper.getStats(arenaId);
assertEquals(stats?.used, 312); // 104 + 208 (200 + 8 padding)
});
it("should align allocations to 8-byte boundaries", () => {
const arenaId = helper.create(1024);
const ptr1 = helper.alloc(arenaId, 1); // Will be aligned to 8
const ptr2 = helper.alloc(arenaId, 1); // Will be aligned to 8
expect(ptr2).toBe(8); // 8-byte aligned
const ptr3 = helper.alloc(arenaId, 15); // Will be aligned to 16
const ptr4 = helper.alloc(arenaId, 1); // Next 8-byte boundary
expect(ptr4).toBe(32); // 16 + 16 (15 aligned to 16)
});
it("should grow arena when needed", () => {
const arenaId = helper.create(100); // Small arena
// Allocate more than initial size
const ptr1 = helper.alloc(arenaId, 50);
const ptr2 = helper.alloc(arenaId, 60); // This should trigger growth
expect(ptr1).toBe(0);
expect(ptr2).not.toBeNull();
const stats = helper.getStats(arenaId);
expect(stats?.size).toBeGreaterThan(100); // Arena should have grown
});
it("should handle large allocations", () => {
const arenaId = helper.create(1024);
const ptr = helper.alloc(arenaId, 10000); // Larger than arena
expect(ptr).not.toBeNull();
const stats = helper.getStats(arenaId);
expect(stats?.size).toBeGreaterThanOrEqual(10008); // At least the allocation size
});
it("should handle zero-size allocations", () => {
const arenaId = helper.create(1024);
const ptr = helper.alloc(arenaId, 0);
expect(ptr).toBe(0); // Valid allocation, just returns current position
const stats = helper.getStats(arenaId);
expect(stats?.used).toBe(0); // No space consumed
});
});
describe("Arena reset", () => {
it("should reset arena usage to zero", () => {
const arenaId = helper.create(1024);
helper.alloc(arenaId, 500);
let stats = helper.getStats(arenaId);
expect(stats?.used).toBeGreaterThan(0);
const success = helper.reset(arenaId);
expect(success).toBe(true);
stats = helper.getStats(arenaId);
expect(stats?.used).toBe(0);
expect(stats?.available).toBe(stats?.size);
});
it("should preserve arena size after reset", () => {
const arenaId = helper.create(1024);
helper.alloc(arenaId, 2000); // Force growth
const sizeAfterGrowth = helper.getStats(arenaId)?.size;
helper.reset(arenaId);
const sizeAfterReset = helper.getStats(arenaId)?.size;
expect(sizeAfterReset).toBe(sizeAfterGrowth); // Size preserved
});
it("should allow new allocations after reset", () => {
const arenaId = helper.create(1024);
helper.alloc(arenaId, 500);
helper.reset(arenaId);
const ptr = helper.alloc(arenaId, 100);
expect(ptr).toBe(0); // Allocation starts from beginning again
});
});
describe("Arena destruction", () => {
it("should destroy arena and free resources", () => {
const arenaId = helper.create(1024);
helper.alloc(arenaId, 500);
const success = helper.destroy(arenaId);
expect(success).toBe(true);
// Arena should no longer exist
const stats = helper.getStats(arenaId);
expect(stats).toBeNull();
});
it("should handle destruction of non-existent arena", () => {
const success = helper.destroy(999); // Non-existent ID
expect(success).toBe(false);
});
});
describe("Error handling", () => {
it("should handle operations on non-existent arena", () => {
const ptr = helper.alloc(999, 100); // Non-existent arena
expect(ptr).toBeNull();
const success = helper.reset(999);
expect(success).toBe(false);
});
it("should handle edge case sizes", () => {
const arenaId = helper.create(1);
expect(arenaId).toBeGreaterThan(0);
const ptr = helper.alloc(arenaId, 1000);
expect(ptr).not.toBeNull(); // Should work even with tiny initial size
});
});
describe("Memory usage patterns", () => {
it("should handle typical MessagePack decoding pattern", () => {
const arenaId = helper.create(4096); // 4KB typical size
// Simulate decoding tag data
const tagDataPtr = helper.alloc(arenaId, 64); // TagData struct
const titlePtr = helper.alloc(arenaId, 50); // Title string
const artistPtr = helper.alloc(arenaId, 30); // Artist string
const albumPtr = helper.alloc(arenaId, 40); // Album string
expect(tagDataPtr).not.toBeNull();
expect(titlePtr).not.toBeNull();
expect(artistPtr).not.toBeNull();
expect(albumPtr).not.toBeNull();
const stats = helper.getStats(arenaId);
expect(stats?.utilization).toBeLessThan(0.1); // Should use < 10% of arena
});
it("should handle high-frequency allocation/reset pattern", () => {
const arenaId = helper.create(1024);
// Simulate processing many files
for (let i = 0; i < 100; i++) {
helper.alloc(arenaId, 100);
helper.alloc(arenaId, 50);
helper.alloc(arenaId, 75);
if (i % 10 === 9) {
helper.reset(arenaId); // Reset every 10 iterations
}
}
const stats = helper.getStats(arenaId);
expect(stats?.size).toBeGreaterThanOrEqual(1024); // Arena should still be functional
});
});
// Note: WASI integration tests will be added once WASM module is built
});
export { ArenaTestHelper };
| 0 | 0.948913 | 1 | 0.948913 | game-dev | MEDIA | 0.741542 | game-dev | 0.951496 | 1 | 0.951496 |
ezEngine/ezEngine | 17,245 | Code/EnginePlugins/AiPlugin/Navigation/Components/NavigationComponent.cpp | #include <AiPlugin/AiPluginPCH.h>
#include <AiPlugin/Navigation/Components/NavigationComponent.h>
#include <AiPlugin/Navigation/NavMesh.h>
#include <AiPlugin/Navigation/NavMeshWorldModule.h>
#include <AiPlugin/Navigation/Navigation.h>
#include <Core/Interfaces/PhysicsWorldModule.h>
#include <Core/WorldSerializer/WorldReader.h>
#include <Core/WorldSerializer/WorldWriter.h>
#include <RendererCore/Debug/DebugRenderer.h>
// clang-format off
EZ_BEGIN_STATIC_REFLECTED_BITFLAGS(ezAiNavigationDebugFlags, 1)
EZ_BITFLAGS_CONSTANTS(ezAiNavigationDebugFlags::PrintState, ezAiNavigationDebugFlags::VisPathCorridor, ezAiNavigationDebugFlags::VisPathLine, ezAiNavigationDebugFlags::VisTarget)
EZ_END_STATIC_REFLECTED_BITFLAGS;
EZ_BEGIN_STATIC_REFLECTED_ENUM(ezAiNavigationComponentState, 1)
EZ_ENUM_CONSTANTS(ezAiNavigationComponentState::Idle, ezAiNavigationComponentState::Moving, ezAiNavigationComponentState::Turning, ezAiNavigationComponentState::Falling, ezAiNavigationComponentState::Fallen, ezAiNavigationComponentState::Failed)
EZ_END_STATIC_REFLECTED_ENUM;
EZ_BEGIN_COMPONENT_TYPE(ezAiNavigationComponent, 2, ezComponentMode::Dynamic)
{
EZ_BEGIN_PROPERTIES
{
EZ_MEMBER_PROPERTY("NavmeshConfig", m_sNavmeshConfig)->AddAttributes(new ezDynamicStringEnumAttribute("AiNavmeshConfig")),
EZ_MEMBER_PROPERTY("PathSearchConfig", m_sPathSearchConfig)->AddAttributes(new ezDynamicStringEnumAttribute("AiPathSearchConfig")),
EZ_MEMBER_PROPERTY("Speed", m_fSpeed)->AddAttributes(new ezDefaultValueAttribute(5.0f)),
EZ_MEMBER_PROPERTY("Acceleration", m_fAcceleration)->AddAttributes(new ezDefaultValueAttribute(3.0f)),
EZ_MEMBER_PROPERTY("Deceleration", m_fDecceleration)->AddAttributes(new ezDefaultValueAttribute(8.0f)),
EZ_MEMBER_PROPERTY("FootRadius", m_fFootRadius)->AddAttributes(new ezDefaultValueAttribute(0.15f), new ezClampValueAttribute(0.0f, 1.0f)),
EZ_MEMBER_PROPERTY("ReachedDistance", m_fReachedDistance)->AddAttributes(new ezDefaultValueAttribute(1.0f), new ezClampValueAttribute(0.0f, 10.0f)),
EZ_MEMBER_PROPERTY("CollisionLayer", m_uiCollisionLayer)->AddAttributes(new ezDynamicEnumAttribute("PhysicsCollisionLayer")),
EZ_MEMBER_PROPERTY("FallHeight", m_fFallHeight)->AddAttributes(new ezDefaultValueAttribute(1.0f)),
EZ_BITFLAGS_MEMBER_PROPERTY("DebugFlags", ezAiNavigationDebugFlags , m_DebugFlags),
EZ_MEMBER_PROPERTY("ApplySteering", m_bApplySteering)->AddAttributes(new ezDefaultValueAttribute(true)),
}
EZ_END_PROPERTIES;
EZ_BEGIN_ATTRIBUTES
{
new ezCategoryAttribute("AI/Navigation"),
}
EZ_END_ATTRIBUTES;
EZ_BEGIN_FUNCTIONS
{
EZ_SCRIPT_FUNCTION_PROPERTY(SetDestination, In, "Destination", In, "AllowPartialPaths"),
EZ_SCRIPT_FUNCTION_PROPERTY(CancelNavigation),
EZ_SCRIPT_FUNCTION_PROPERTY(GetState),
EZ_SCRIPT_FUNCTION_PROPERTY(StopWalking, In, "WithinDistance"),
EZ_SCRIPT_FUNCTION_PROPERTY(TurnTowards, In, "TargetPosition"),
EZ_SCRIPT_FUNCTION_PROPERTY(GetTurnAngleTowards, In, "TargetPosition"),
EZ_SCRIPT_FUNCTION_PROPERTY(EnsureNavMeshSectorAvailable, In, "vCenter", In, "fRadius"),
EZ_SCRIPT_FUNCTION_PROPERTY(FindRandomPointAroundCircle, In, "vCenter", In, "fRadius", Out, "out_vPoint"),
EZ_SCRIPT_FUNCTION_PROPERTY(RaycastNavMesh, In, "vStart", In, "vDirection", In, "fDistance", Out, "out_vPoint", Out, "out_fDistance"),
EZ_SCRIPT_FUNCTION_PROPERTY(GetSteeringPosition),
EZ_SCRIPT_FUNCTION_PROPERTY(GetSteeringRotation),
}
EZ_END_FUNCTIONS;
}
EZ_END_COMPONENT_TYPE
// clang-format on
ezAiNavigationComponent::ezAiNavigationComponent() = default;
ezAiNavigationComponent::~ezAiNavigationComponent() = default;
void ezAiNavigationComponent::OnSimulationStarted()
{
SUPER::OnSimulationStarted();
m_uiSkipNextFrames = 3; // 2 are needed to have colliders set up at the start of the scene simulation, 3 just to be save
m_Steering.m_vPosition = GetOwner()->GetGlobalPosition();
m_Steering.m_qRotation = GetOwner()->GetGlobalRotation();
}
void ezAiNavigationComponent::SetDestination(const ezVec3& vGlobalPos, bool bAllowPartialPath)
{
m_fStopWalkDistance = ezMath::HighValue<float>();
m_bAllowPartialPath = bAllowPartialPath;
m_Navigation.SetTargetPosition(vGlobalPos);
m_State = ezAiNavigationComponentState::Moving;
}
void ezAiNavigationComponent::CancelNavigation()
{
m_Navigation.CancelNavigation();
if (m_State != ezAiNavigationComponentState::Falling)
{
// if it is still falling, don't reset the state
m_State = ezAiNavigationComponentState::Idle;
}
}
void ezAiNavigationComponent::StopWalking(float fWithinDistance)
{
m_fStopWalkDistance = ezMath::Min(m_fStopWalkDistance, fWithinDistance);
}
void ezAiNavigationComponent::TurnTowards(const ezVec2& vGlobalPos)
{
if (m_State == ezAiNavigationComponentState::Idle)
{
m_State = ezAiNavigationComponentState::Turning;
m_vTurnTowardsPos = vGlobalPos;
}
}
ezAngle ezAiNavigationComponent::GetTurnAngleTowards(const ezVec2& vGlobalPos) const
{
ezVec3 vOwnPos2D = GetOwner()->GetGlobalPosition();
vOwnPos2D.z = 0.0f;
ezVec3 vTargetDir = (vGlobalPos.GetAsVec3(0) - vOwnPos2D);
if (vTargetDir.NormalizeIfNotZero(ezVec3::MakeZero()).Failed())
return ezAngle::MakeZero();
ezVec3 vLookDir = GetOwner()->GetGlobalDirForwards();
vLookDir.z = 0.0f;
vLookDir.Normalize();
return vLookDir.GetAngleBetween(vTargetDir, ezVec3::MakeAxisZ());
}
bool ezAiNavigationComponent::PrepareQueryObject()
{
if (m_Query.GetNavmesh() == nullptr)
{
ezAiNavMeshWorldModule* pNavMeshModule = GetWorld()->GetOrCreateModule<ezAiNavMeshWorldModule>();
if (pNavMeshModule == nullptr)
return false;
m_Query.SetNavmesh(pNavMeshModule->GetNavMesh(m_sNavmeshConfig));
m_Query.SetQueryFilter(pNavMeshModule->GetPathSearchFilter(m_sPathSearchConfig));
}
return true;
}
bool ezAiNavigationComponent::EnsureNavMeshSectorAvailable(const ezVec3& vCenter, float fRadius)
{
if (!PrepareQueryObject())
return false;
return m_Query.GetNavmesh()->RequestSector(vCenter.GetAsVec2(), ezVec2(fRadius));
}
bool ezAiNavigationComponent::FindRandomPointAroundCircle(const ezVec3& vCenter, float fRadius, ezVec3& out_vPoint)
{
if (!PrepareQueryObject())
return false;
if (!m_Query.PrepareQueryArea(vCenter, fRadius))
return false;
return m_Query.FindRandomPointAroundCircle(vCenter, fRadius, GetWorld()->GetRandomNumberGenerator(), out_vPoint);
}
bool ezAiNavigationComponent::RaycastNavMesh(const ezVec3& vStart, const ezVec3& vDirection, float fDistance, ezVec3& out_vPoint, float& out_fDistance)
{
if (!PrepareQueryObject())
return false;
// ignore result, even if not everything is loaded, the raycast may still hit an obstacle
m_Query.PrepareQueryArea(vStart, fDistance);
ezAiNavmeshRaycastHit hit;
if (!m_Query.Raycast(vStart, vDirection, fDistance, hit))
return false;
out_vPoint = hit.m_vHitPosition;
out_fDistance = hit.m_fHitDistance;
return true;
}
ezVec3 ezAiNavigationComponent::GetSteeringPosition() const
{
return m_vSteerPosition;
}
ezQuat ezAiNavigationComponent::GetSteeringRotation() const
{
return m_qSteerRotation;
}
void ezAiNavigationComponent::SerializeComponent(ezWorldWriter& inout_stream) const
{
SUPER::SerializeComponent(inout_stream);
ezStreamWriter& s = inout_stream.GetStream();
s << m_sPathSearchConfig;
s << m_sNavmeshConfig;
s << m_fReachedDistance;
s << m_fSpeed;
s << m_fAcceleration;
s << m_fDecceleration;
s << m_fFootRadius;
s << m_uiCollisionLayer;
s << m_fFallHeight;
s << m_DebugFlags;
s << m_bApplySteering;
}
void ezAiNavigationComponent::DeserializeComponent(ezWorldReader& inout_stream)
{
SUPER::DeserializeComponent(inout_stream);
ezStreamReader& s = inout_stream.GetStream();
const ezUInt32 uiVersion = inout_stream.GetComponentTypeVersion(GetStaticRTTI());
s >> m_sPathSearchConfig;
s >> m_sNavmeshConfig;
s >> m_fReachedDistance;
s >> m_fSpeed;
s >> m_fAcceleration;
s >> m_fDecceleration;
s >> m_fFootRadius;
s >> m_uiCollisionLayer;
s >> m_fFallHeight;
s >> m_DebugFlags;
if (uiVersion >= 2)
{
s >> m_bApplySteering;
}
}
void ezAiNavigationComponent::Update()
{
if (m_uiSkipNextFrames > 0)
{
// in the very first frame, physics may not be available yet (colliders are not yet set up)
// so skip that frame to prevent not finding a ground and entering the 'falling' state
m_uiSkipNextFrames--;
return;
}
ezTransform transform = GetOwner()->GetGlobalTransform();
const float tDiff = GetWorld()->GetClock().GetTimeDiff().AsFloatInSeconds();
Steer(transform, tDiff);
Turn(transform, tDiff);
PlaceOnGround(transform, tDiff);
m_vSteerPosition = transform.m_vPosition;
m_qSteerRotation = transform.m_qRotation;
if (m_bApplySteering)
{
GetOwner()->SetGlobalPosition(m_vSteerPosition);
GetOwner()->SetGlobalRotation(m_qSteerRotation);
}
if (m_DebugFlags.IsAnyFlagSet())
{
if (m_DebugFlags.IsSet(ezAiNavigationDebugFlags::VisPathCorridor))
{
m_Navigation.DebugDrawPathCorridor(GetWorld(), ezColor::Aquamarine.WithAlpha(0.15f), 0.2f);
}
if (m_DebugFlags.IsSet(ezAiNavigationDebugFlags::VisPathLine))
{
m_Navigation.DebugDrawPathLine(GetWorld(), ezColor::DeepSkyBlue, 0.3f);
}
if (m_DebugFlags.IsSet(ezAiNavigationDebugFlags::PrintState))
{
const ezVec3 vPosition = GetOwner()->GetGlobalPosition() + ezVec3(0, 0, 1.5f);
switch (m_State)
{
case ezAiNavigationComponentState::Idle:
ezDebugRenderer::Draw3DText(GetWorld(), "Idle", vPosition, ezColor::Grey);
break;
case ezAiNavigationComponentState::Moving:
ezDebugRenderer::Draw3DText(GetWorld(), "Moving", vPosition, ezColor::Yellow);
m_Navigation.DebugDrawState(GetWorld(), vPosition - ezVec3(0, 0, 0.5f));
break;
case ezAiNavigationComponentState::Turning:
ezDebugRenderer::Draw3DText(GetWorld(), "Turning", vPosition, ezColor::Orange);
break;
case ezAiNavigationComponentState::Falling:
ezDebugRenderer::Draw3DText(GetWorld(), "Falling...", vPosition, ezColor::IndianRed);
break;
case ezAiNavigationComponentState::Fallen:
ezDebugRenderer::Draw3DText(GetWorld(), "Fallen", vPosition, ezColor::IndianRed);
break;
case ezAiNavigationComponentState::Failed:
ezDebugRenderer::Draw3DText(GetWorld(), "Failed", vPosition, ezColor::Red);
m_Navigation.DebugDrawState(GetWorld(), vPosition - ezVec3(0, 0, 0.5f));
break;
}
}
if (m_DebugFlags.IsSet(ezAiNavigationDebugFlags::VisTarget))
{
ezDebugRenderer::DrawArrow(GetWorld(), 1.0f, ezColor::Lime, ezTransform(m_Navigation.GetTargetPosition() + ezVec3(0, 0, 1.5f)), -ezVec3::MakeAxisZ());
}
}
}
void ezAiNavigationComponent::Steer(ezTransform& transform, float tDiff)
{
if (m_State != ezAiNavigationComponentState::Moving)
return;
if (ezAiNavMeshWorldModule* pNavMeshModule = GetWorld()->GetOrCreateModule<ezAiNavMeshWorldModule>())
{
m_Navigation.SetNavmesh(pNavMeshModule->GetNavMesh(m_sNavmeshConfig));
m_Navigation.SetQueryFilter(pNavMeshModule->GetPathSearchFilter(m_sPathSearchConfig));
}
m_Navigation.SetCurrentPosition(GetOwner()->GetGlobalPosition());
m_Navigation.Update();
switch (m_Navigation.GetState())
{
case ezAiNavigation::State::Idle:
m_State = ezAiNavigationComponentState::Idle;
return;
case ezAiNavigation::State::InvalidCurrentPosition:
case ezAiNavigation::State::InvalidTargetPosition:
case ezAiNavigation::State::NoPathFound:
m_State = ezAiNavigationComponentState::Failed;
return;
case ezAiNavigation::State::StartNewSearch:
case ezAiNavigation::State::Searching:
return;
case ezAiNavigation::State::FullPathFound:
break;
case ezAiNavigation::State::PartialPathFound:
if (m_bAllowPartialPath)
break;
m_State = ezAiNavigationComponentState::Failed;
return;
}
if (m_fSpeed <= 0)
return;
ezVec2 vForwardDir = GetOwner()->GetGlobalDirForwards().GetAsVec2();
vForwardDir.NormalizeIfNotZero(ezVec2(1, 0)).IgnoreResult();
m_Steering.m_fMaxSpeed = m_fSpeed;
m_Steering.m_vPosition = GetOwner()->GetGlobalPosition();
m_Steering.m_qRotation = GetOwner()->GetGlobalRotation();
m_Steering.m_vVelocity = GetOwner()->GetLinearVelocity();
m_Steering.m_fAcceleration = m_fAcceleration;
m_Steering.m_fDecceleration = m_fDecceleration;
// TODO: hard-coded values
m_Steering.m_MinTurnSpeed = ezAngle::MakeFromDegree(180);
const float fBrakingDistance = 1.2f * (ezMath::Square(m_Steering.m_fMaxSpeed) / (2.0f * m_Steering.m_fDecceleration));
m_Navigation.ComputeSteeringInfo(m_Steering.m_Info, vForwardDir, fBrakingDistance);
// m_Steering.m_Info.m_vDirectionTowardsWaypoint.Set(1, 0);
if (m_fStopWalkDistance < ezMath::HighValue<float>())
{
m_Steering.m_Info.m_fArrivalDistance = ezMath::Min(m_fStopWalkDistance, m_Steering.m_Info.m_fArrivalDistance);
m_Steering.m_Info.m_fDistanceToWaypoint = ezMath::Min(m_fStopWalkDistance, m_Steering.m_Info.m_fDistanceToWaypoint);
}
m_Steering.Calculate(tDiff, GetWorld());
const ezVec2 vMove = m_Steering.m_vPosition.GetAsVec2() - transform.m_vPosition.GetAsVec2();
const float fMoveDist = vMove.GetLength();
if (m_fStopWalkDistance < ezMath::HighValue<float>())
{
m_fStopWalkDistance = ezMath::Max(0.0f, m_fStopWalkDistance - fMoveDist);
}
const float fSpeed = fMoveDist / tDiff;
transform.m_vPosition = m_Steering.m_vPosition;
transform.m_qRotation = m_Steering.m_qRotation;
if (fSpeed < 0.2f && (m_fStopWalkDistance <= 0.1f || ((m_Navigation.GetTargetPosition().GetAsVec2() - m_Steering.m_vPosition.GetAsVec2()).GetLengthSquared() < ezMath::Square(m_fReachedDistance))))
{
// reached the goal
CancelNavigation();
m_State = ezAiNavigationComponentState::Idle;
return;
}
}
void ezAiNavigationComponent::Turn(ezTransform& transform, float tDiff)
{
if (m_State != ezAiNavigationComponentState::Turning)
return;
ezAngle turnSpeed = ezAngle::MakeFromDegree(360);
const ezAngle remainingAngle = GetTurnAngleTowards(m_vTurnTowardsPos);
const ezAngle rotateNow = tDiff * turnSpeed;
ezAngle toRotate;
if (rotateNow >= remainingAngle)
{
toRotate = remainingAngle;
m_State = ezAiNavigationComponentState::Idle;
}
else
{
toRotate = rotateNow;
}
const ezQuat qRot = ezQuat::MakeFromAxisAndAngle(ezVec3::MakeAxisZ(), toRotate);
const ezVec3 vNewLookDir = qRot * GetOwner()->GetGlobalDirForwards();
transform.m_qRotation = ezQuat::MakeShortestRotation(ezVec3::MakeAxisX(), vNewLookDir);
}
void ezAiNavigationComponent::PlaceOnGround(ezTransform& transform, float tDiff)
{
if (m_fFootRadius <= 0.0f)
return;
ezPhysicsWorldModuleInterface* pPhysicsInterface = GetWorld()->GetOrCreateModule<ezPhysicsWorldModuleInterface>();
if (pPhysicsInterface == nullptr)
return;
const ezVec3 vDown = -ezVec3::MakeAxisZ();
const float fDistUp = 1.0f;
const float fDistDown = m_fFallHeight;
const ezVec3 vStartPos = transform.m_vPosition - fDistUp * vDown;
float fMoveUp = 0.0f;
bool bHadCollision = false;
ezPhysicsCastResult res;
ezPhysicsQueryParameters params(m_uiCollisionLayer, ezPhysicsShapeType::Static);
if (pPhysicsInterface->SweepTestSphere(res, m_fFootRadius, vStartPos, vDown, fDistUp + fDistDown, params))
{
if (res.m_fDistance == 0.0f)
{
// ran into an obstacle
// this shouldn't happen when walking just on the navmesh, as long as foot radius is smaller than the character radius
// it can easily happen, once outside forces push the NPC around, but then one should really use a proper
// physics character controller to avoid geometry
return;
}
// found an intersection within the search radius
bHadCollision = true;
const float fFloorHeight = vStartPos.z - res.m_fDistance - m_fFootRadius;
fMoveUp = fFloorHeight - transform.m_vPosition.z;
}
else
{
// did not find an intersection -> falling down
fMoveUp = -fDistDown; // will be clamped by gravity
CancelNavigation();
m_State = ezAiNavigationComponentState::Falling;
}
if (fMoveUp > 0.0f)
{
// if the character is being pushed up
// TODO: better lerp up
transform.m_vPosition.z += fMoveUp * ezMath::Min(1.0f, 25.0f * tDiff);
m_fFallSpeed = 0.0f;
}
else
{
m_fFallSpeed += pPhysicsInterface->GetGravity().z * tDiff;
float fFallDist = m_fFallSpeed * tDiff;
if (fFallDist < fMoveUp)
{
// clamp to the maximum speed / or to the floor
fFallDist = fMoveUp;
if (bHadCollision)
{
m_fFallSpeed = 0.0f;
if (m_State == ezAiNavigationComponentState::Falling)
{
// we just landed from a high fall -> starting to walk again probably makes no sense, since we obviously left the navmesh
m_State = ezAiNavigationComponentState::Fallen;
}
}
}
transform.m_vPosition.z += fFallDist;
}
}
EZ_STATICLINK_FILE(AiPlugin, AiPlugin_Navigation_Components_NavigationComponent);
| 0 | 0.949092 | 1 | 0.949092 | game-dev | MEDIA | 0.744737 | game-dev,graphics-rendering | 0.954399 | 1 | 0.954399 |
gamekit-developers/gamekit | 4,611 | Samples/CppDemo/Controllers/gkJoystickController.cpp | /*
-------------------------------------------------------------------------------
This file is part of OgreKit.
http://gamekit.googlecode.com/
Copyright (c) 2006-2010 Charlie C.
Contributor(s): none yet.
-------------------------------------------------------------------------------
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
-------------------------------------------------------------------------------
*/
#include "gkGameController.h"
#include "gkJoystickController.h"
#include "gkWindowSystem.h"
#include "gkGamePlayer.h"
#include "gkGameObject.h"
#include "gkEntity.h"
gkJoystickController::gkJoystickController(gkGamePlayer* player)
: m_player(player),
m_btn1Cache(0),
m_btn2Cache(0),
m_btn3Cache(0),
m_isBtn1(false),
m_isBtn2(false),
m_isBtn3(false)
{
m_joystick = gkWindowSystem::getSingleton().getJoystick(0);
GK_ASSERT(m_joystick);
}
gkJoystickController::~gkJoystickController()
{
}
bool gkJoystickController::hasInput(const gkGameController::InputCode& ic)
{
switch (ic)
{
case IC_RUN:
return !m_movement.isDead() && !m_movement.isInFactor(gkAppData::gkJoyWalkToRunTol);
case IC_WALK:
return !m_movement.isDead() && m_movement.isInFactor(gkAppData::gkJoyWalkToRunTol);
case IC_BUTTON_0:
return m_isBtn1;
case IC_BUTTON_1:
return m_isBtn2;
case IC_BUTTON_2:
return m_isBtn3;
case IC_STOP:
return m_movement.isDead();
}
return false;
}
void gkJoystickController::moveCamera(void)
{
gkGamePlayer::Data& data = m_player->getData();
gkScalar crAxUD = (m_camRot.m_normal.x * gkPih) * gkAppData::gkFixedTickDelta2;
gkScalar crAxLR = (m_camRot.m_normal.y * gkPih) * gkAppData::gkFixedTickDelta2;
data.m_xRot->pitch(gkRadian(crAxUD));
if (m_camRot.isDeadUD())
{
// Auto rebound pitch.
gkScalar cPitch = data.m_xRot->getRotation().x.valueRadians();
cPitch = -gkAppData::gkJoyReboundFac * cPitch;
data.m_xRot->pitch(gkDegree(cPitch));
}
if (!m_camRot.isDeadLR())
data.m_zRot->roll(gkRadian(crAxLR));
data.m_zRot->translate(
(data.m_physics->getPosition() - (data.m_zRot->getPosition() +
gkVector3(0, 0, -gkAppData::gkPlayerHeadZ))
) * gkAppData::gkCameraTol
);
}
void gkJoystickController::movePlayer(void)
{
gkGamePlayer::Data& data = m_player->getData();
gkScalar axRotLR = (m_movement.m_normal.y * gkPi);
gkScalar axRotUD = (-m_movement.m_normal.x * gkPi);
gkScalar axTan = -gkMath::ATan2(axRotLR, axRotUD).valueDegrees();
gkScalar speed = 3.f;
if (m_movement.isInFactor(gkAppData::gkJoyWalkToRunTol))
speed /= 4.f;
gkScalar axLinUD = speed * -m_movement.m_normal.x;
gkScalar axLinLR = speed * m_movement.m_normal.y;
gkVector3 linvel = data.m_physics->getLinearVelocity();
gkQuaternion curZRot = data.m_zRot->getOrientation();
gkQuaternion aOri = gkEuler(0.f, 0.f, axTan).toQuaternion();
aOri.normalise();
gkVector3 m = curZRot * gkVector3(axLinLR, axLinUD, linvel.z);
data.m_physics->setLinearVelocity(m);
data.m_entity->setOrientation(aOri * curZRot);
}
bool gkJoystickController::isButtonDownCache(int btn, int& cache)
{
bool result = m_joystick->isButtonDown(btn);
if (result && cache == 0)
cache = 1;
else if (cache == 1 && result)
result = false;
else if (cache == 1 && !result)
cache = 0;
return result;
}
void gkJoystickController::updateInputState(void)
{
m_camRot.m_absolute = gkVector2(m_joystick->getAxisValue(0), m_joystick->getAxisValue(1));
m_camRot.normalize();
m_movement.m_absolute = gkVector2(m_joystick->getAxisValue(2), m_joystick->getAxisValue(3));
m_movement.normalize();
m_isBtn1 = isButtonDownCache(GK_JOY_BUTTON_1, m_btn1Cache);
m_isBtn2 = isButtonDownCache(GK_JOY_BUTTON_2, m_btn2Cache);
m_isBtn3 = isButtonDownCache(GK_JOY_BUTTON_3, m_btn3Cache);
}
| 0 | 0.936191 | 1 | 0.936191 | game-dev | MEDIA | 0.942111 | game-dev | 0.917455 | 1 | 0.917455 |
spire-winder/Magic-the-Jokering | 37,103 | Items/jokers.lua | --[[Ajani
SMODS.Joker {
object_type = "Joker",
name = "mtg-ajani",
key = "ajani",
pos = {
x = 0,
y = 7
},
atlas = 'mtg_atlas',
cost = 8,
order = 1,
rarity = 3,
config = {},
loc_vars = function(self, info_queue, card)
return { }
end
}]]
--Celestial dawn
SMODS.Joker {
object_type = "Joker",
name = "mtg-celestialdawn",
key = "celestialdawn",
pos = {
x = 4,
y = 4
},
atlas = 'mtg_atlas',
cost = 8,
order = 1,
rarity = 3,
unlocked = false,
config = {},
loc_vars = function(self, info_queue, card)
return { }
end
}
--first response
SMODS.Joker {
object_type = "Joker",
name = "mtg-firstresponse",
key = "firstresponse",
pos = { x = 14, y = 1 },
config = { extra = {}},
order = 2,
rarity = 2,
cost = 6,
atlas = "mtg_atlas",
loc_vars = function(self, info_queue, center)
info_queue[#info_queue + 1] = { key = "r_mtg_soldier", set = "Other", config = { extra = 1 } , vars = { 2 } }
return { vars = {}}
end,
calculate = function(self, card, context)
if context.first_hand_drawn then
G.E_MANAGER:add_event(Event({
func = function()
local _suit, _rank = SMODS.Suits["Diamonds"].card_key, "2"
create_playing_card({front = G.P_CARDS[_suit..'_'.._rank], center = token_soldier}, G.hand, nil, i ~= 1, {G.C.SECONDARY_SET.Magic})
G.hand:sort()
if context.blueprint_card then context.blueprint_card:juice_up() else card:juice_up() end
return true
end}))
playing_card_joker_effects({true})
end
end
}
--Light from Within
SMODS.Joker {
object_type = "Joker",
name = "mtg-lightfromwithin",
key = "lightfromwithin",
pos = { x = 0, y = 3 },
config = { },
order = 2,
rarity = 2,
cost = 6,
atlas = "mtg_atlas",
loc_vars = function(self, info_queue, center)
return { }
end,
calculate = function(self, card, context)
if context.individual and not context.repetition then
if context.cardarea == G.play then
if context.other_card:is_suit('Diamonds') then
return {
mult = context.other_card.base.nominal,
card = card
}
end
end
end
end
}
--Rule of Law
SMODS.Joker {
object_type = "Joker",
name = "mtg-ruleoflaw",
key = "ruleoflaw",
pos = { x = 13, y = 1 },
config = { extra = {num_hands = 1, blind_size = 0.25}},
order = 2,
rarity = 3,
cost = 7,
atlas = "mtg_atlas",
loc_vars = function(self, info_queue, center)
return { vars = {center.ability.extra.num_hands, center.ability.extra.blind_size}}
end,
calculate = function(self, card, context)
if context.setting_blind and not (context.blueprint_card or card).getting_sliced then
G.E_MANAGER:add_event(Event({func = function()
G.E_MANAGER:add_event(Event({func = function()
local hands_sub = G.GAME.round_resets.hands - card.ability.extra.num_hands
ease_hands_played(-hands_sub)
G.GAME.blind.chips = G.GAME.blind.chips * card.ability.extra.blind_size
G.GAME.blind.chip_text = number_format(G.GAME.blind.chips)
play_sound('timpani')
delay(0.4)
return true end }))
card_eval_status_text(card, 'extra', nil, nil, nil, {message = localize('mtg_rule_ex')})
return true end }))
end
end
}
--etherium sculptor
SMODS.Joker {
object_type = "Joker",
name = "mtg-etheriumsculptor",
key = "etheriumsculptor",
pos = { x = 11, y = 5 },
config = { extra = { chips = 50} },
order = 10,
rarity = 2,
cost = 4,
atlas = "mtg_atlas",
enhancement_gate = 'm_steel',
loc_vars = function(self, info_queue, center)
info_queue[#info_queue+1] = G.P_CENTERS.m_steel
return { vars = {center.ability.extra.chips } }
end,
calculate = function(self, card, context)
if context.individual and not context.repetition then
if context.cardarea == G.play then
if context.other_card.ability.name == 'Steel Card' then
return {
chips = card.ability.extra.chips,
card = card
}
end
end
end
end
}
--Harbinger of the seas
SMODS.Joker {
object_type = "Joker",
name = "mtg-harbinger",
key = "harbinger",
pos = {
x = 3,
y = 4
},
atlas = 'mtg_atlas',
cost = 8,
order = 3,
rarity = 3,
unlocked = false,
config = {},
loc_vars = function(self, info_queue, card)
return { }
end
}
--Jokulmorder
SMODS.Joker {
object_type = "Joker",
name = "mtg-jokulmorder",
key = "jokulmorder",
pos = { x = 6, y = 2 },
config = { extra = {awoken = false, required = 5, power = 2}},
order = 4,
rarity = 2,
cost = 7,
atlas = "mtg_atlas",
loc_vars = function(self, info_queue, center)
info_queue[#info_queue + 1] = { key = "r_mtg_slumber", set = "Other", config = { extra = 1 } }
return { vars = {center.ability.extra.required, center.ability.extra.power}}
end,
calculate = function(self, card, context)
if context.pre_discard then
local suits = {
['Clubs'] = 0
}
for k, v in ipairs(context.full_hand) do
if v:is_suit('Clubs') then suits["Clubs"] = suits["Clubs"] + 1 end
end
if suits["Clubs"] >= card.ability.extra.required and card.ability.extra.awoken == false then
card.ability.extra.awoken = true
local eval = function() return not G.RESET_JIGGLES end
juice_card_until(card, eval, true)
card_eval_status_text(card, 'extra', nil, nil, nil, {message = localize('mtg_awoken_ex')})
end
elseif context.individual and not context.repetition then
if context.cardarea == G.play then
if context.other_card:is_suit('Clubs') and card.ability.extra.awoken then
return {
colour = G.C.RED,
x_mult = card.ability.extra.power,
card = card
}
end
end
elseif context.end_of_round then
if not context.blueprint then
if card.ability.extra.awoken then
card.ability.extra.awoken = false
return {
message = localize('mtg_slumber_ex')
}
end
end
end
end
}
--Laboratory Maniac
SMODS.Joker {
object_type = "Joker",
name = "mtg-labman",
key = "labman",
pos = { x = 9, y = 5 },
config = { extra = {multi = 10}},
order = 4,
rarity = 3,
cost = 6,
atlas = "mtg_atlas",
loc_vars = function(self, info_queue, center)
return { vars = {center.ability.extra.multi}}
end,
calculate = function(self, card, context)
if context.joker_main then
if #G.deck.cards == 0 then
return {
message = localize{type='variable',key='a_xmult',vars={card.ability.extra.multi}},
Xmult_mod = card.ability.extra.multi,
colour = G.C.Mult
}
end
end
end
}
-- encroaching mycosynth
--[[
SMODS.Joker {
key = "mtg-encroachingmycosynth",
name = "Encroaching Mycosynth",
pos = { x = 13, y = 5 },
cost = 8,
atlas = "mtg_atlas",
order = 3,
rarity = 3,
config = {},
loc_vars = function(self, info_queue, card)
return { }
end
}
--]]
--omniscience
SMODS.Joker {
object_type = "Joker",
name = "mtg-omniscience",
key = "omniscience",
pos = { x = 12, y = 2 },
config = { extra = {}},
order = 15,
rarity = 3,
cost = 10,
atlas = "mtg_atlas",
loc_vars = function(self, info_queue, center)
return { vars = {}}
end,
add_to_deck = function(self, card, from_debuff)
G.E_MANAGER:add_event(Event({func = function()
for k, v in pairs(G.I.CARD) do
if v.set_cost then v:set_cost() end
end
return true end }))
end,
remove_from_deck = function(self, card, from_debuff)
G.E_MANAGER:add_event(Event({func = function()
for k, v in pairs(G.I.CARD) do
if v.set_cost then v:set_cost() end
end
return true end }))
end,
calculate = function(self, card, context)
end
}
--ascendant evincar
SMODS.Joker {
object_type = "Joker",
name = "mtg-evincar",
key = "evincar",
pos = { x = 4, y = 3 },
config = { extra = {bonus_mult = 10, neg_mult = 10} },
order = 5,
rarity = 2,
cost = 8,
atlas = "mtg_atlas",
loc_vars = function(self, info_queue, center)
return { vars = { center.ability.extra.bonus_mult, center.ability.extra.neg_mult} }
end,
calculate = function(self, card, context)
if context.main_scoring then
if context.cardarea == G.play then
if context.other_card:is_suit('Spades') then
return {
mult = card.ability.extra.bonus_mult,
card = card
}
else
return {
mult = -1 * card.ability.extra.neg_mult,
card = card
}
end
end
end
end
}
--relentless rats
SMODS.Joker {
object_type = "Joker",
name = "mtg-relentlessrats",
key = "relentlessrats",
pos = { x = 1, y = 3 },
config = { extra = { base_mult = 5} },
order = 6,
rarity = 1,
cost = 3,
atlas = "mtg_atlas",
loc_vars = function(self, info_queue, center)
info_queue[#info_queue + 1] = { key = "r_mtg_relentless", set = "Other", config = { extra = 1 } }
return { vars = { center.ability.extra.base_mult} }
end,
calculate = function(self, card, context)
if context.joker_main then
local mult = (card.ability.extra.base_mult * #SMODS.find_card("j_mtg_relentlessrats")) or 0
return {
mult_mod = mult,
message = localize({ type = "variable", key = "a_mult", vars = { mult } })
}
end
end,
in_pool = function(self)
return true, { allow_duplicates = true }
end
}
--Urborg
SMODS.Joker {
object_type = "Joker",
name = "mtg-urborg",
key = "urborg",
pos = {
x = 5,
y = 3
},
atlas = 'mtg_atlas',
cost = 8,
order = 7,
rarity = 3,
unlocked = false,
config = {},
loc_vars = function(self, info_queue, card)
return { }
end
}
--Waste not, gives you money, cards, or +mult when you discard cards
SMODS.Joker {
object_type = "Joker",
name = "mtg-wastenot",
key = "wastenot",
pos = { x = 7, y = 5 },
config = { extra = {money = 2, damage = 2, cards = 2}},
order = 17,
rarity = 2,
cost = 6,
atlas = "mtg_atlas",
loc_vars = function(self, info_queue, center)
info_queue[#info_queue + 1] = { key = "r_mtg_damage_blind", set = "Other", config = {extra = 1}, vars = { current_blind_life() or "?"}}
return { vars = {center.ability.extra.money, center.ability.extra.damage, center.ability.extra.cards}}
end,
calculate = function(self, card, context)
if context.pre_discard and G.GAME.current_round.discards_used <= 0 then
local total_faces = 0
for key, value in pairs(context.full_hand) do
if not value.debuff and value:is_face() then total_faces = total_faces + 1 end
end
if total_faces > 0 then
damage_blind(card, card.ability.extra.damage, total_faces)
end
elseif context.discard and G.GAME.current_round.discards_used <= 0 then
if not context.other_card.debuff then
if context.other_card:get_id() == 14 then
ease_dollars(card.ability.extra.money)
return {
message = localize('$')..card.ability.extra.money,
colour = G.C.MONEY,
card = card
}
elseif not context.other_card:is_face() then
G.FUNCS.draw_from_deck_to_hand(card.ability.extra.cards)
card_eval_status_text(context.blueprint_card or card, 'extra', nil, nil, nil, {message = localize('mtg_draw_ex')})
end
end
end
end
}
--Blood moon
SMODS.Joker {
object_type = "Joker",
name = "mtg-bloodmoon",
key = "bloodmoon",
pos = {
x = 5,
y = 4
},
atlas = 'mtg_atlas',
cost = 8,
order = 8,
rarity = 3,
unlocked = false,
config = {},
loc_vars = function(self, info_queue, card)
return { }
end
}
--Fiery Emancipation
SMODS.Joker {
object_type = "Joker",
name = "mtg-emancipation",
key = "emancipation",
pos = { x = 11, y = 4 },
config = { extra = { damage_mult = 3} },
order = 10,
rarity = 3,
cost = 8,
atlas = "mtg_atlas",
loc_vars = function(self, info_queue, center)
return { vars = { } }
end,
calculate = function(self, card, context)
end
}
--Reckless bushwacker
SMODS.Joker {
object_type = "Joker",
name = "mtg-bushwacker",
key = "bushwacker",
pos = { x = 8, y = 6 },
config = { extra = { mult = 3} },
order = 10,
rarity = 1,
cost = 3,
atlas = "mtg_atlas",
loc_vars = function(self, info_queue, center)
return { vars = {center.ability.extra.mult } }
end,
calculate = function(self, card, context)
if context.individual and not context.repetition then
if context.cardarea == G.play then
if G.GAME.current_round.hands_played == 0 then
return {
mult = card.ability.extra.mult,
card = card
}
end
end
end
end
}
--vortex
SMODS.Joker {
object_type = "Joker",
name = "mtg-vortex",
key = "vortex",
pos = { x = 4, y = 2 },
config = { extra = {damage_blind = 2, damage_hand = 2}},
order = 9,
rarity = 2,
cost = 6,
atlas = "mtg_atlas",
loc_vars = function(self, info_queue, center)
info_queue[#info_queue + 1] = { key = "r_mtg_damage_blind", set = "Other", config = {extra = 1}, vars = { current_blind_life() or "?"}}
info_queue[#info_queue + 1] = { key = "r_mtg_damage_card", set = "Other", config = { extra = 1 } }
return { vars = {center.ability.extra.damage_blind, center.ability.extra.damage_hand}}
end,
calculate = function(self, card, context)
if context.before then
bonus_damage(card, card.ability.extra.damage_blind)
local target = pseudorandom_element(G.hand.cards, pseudoseed('mtg-vortex'))
if target then damage_card(target, card.ability.extra.damage_hand) end
end
end
}
--Torbran, Thane of Red Fell
SMODS.Joker {
object_type = "Joker",
name = "mtg-torbran",
key = "torbran",
pos = { x = 2, y = 4 },
config = { extra = { damage_bonus = 2, damage_red = 2} },
order = 10,
rarity = 2,
cost = 6,
atlas = "mtg_atlas",
loc_vars = function(self, info_queue, center)
info_queue[#info_queue + 1] = { key = "r_mtg_damage_blind", set = "Other", config = {extra = 1}, vars = { current_blind_life() or "?"}}
return { vars = { center.ability.extra.damage_red, center.ability.extra.damage_bonus} }
end,
calculate = function(self, card, context)
if context.joker_main then
local hearts_total = 0
for i = 1, #context.scoring_hand do
if context.scoring_hand[i]:is_suit('Hearts') then hearts_total = hearts_total + 1 end
end
if hearts_total >= 1 then
bonus_damage(card, card.ability.extra.damage_red)
end
end
end
}
--beastmaster
SMODS.Joker {
object_type = "Joker",
name = "mtg-beastmaster",
key = "beastmaster",
pos = { x = 5, y = 2 },
config = { extra = {quest = 0, required = 7, chips = 5, mult = 5}},
order = 12,
rarity = 1,
cost = 4,
atlas = "mtg_atlas",
loc_vars = function(self, info_queue, center)
return { vars = {center.ability.extra.required, center.ability.extra.chips, center.ability.extra.mult, center.ability.extra.quest}}
end,
calculate = function(self, card, context)
if context.joker_main then
if card.ability.extra.quest < card.ability.extra.required then
card.ability.extra.quest = card.ability.extra.quest + 1
if card.ability.extra.quest >= card.ability.extra.required then
local eval = function() return card.ability.extra.quest >= card.ability.extra.required end
juice_card_until(card, eval, true)
card_eval_status_text(card, 'extra', nil, nil, nil, {message = localize('mtg_complete_ex')})
else
card_eval_status_text(card, 'extra', nil, nil, nil, {message = localize('mtg_quest_ex')})
end
end
elseif context.individual and not context.repetition then
if context.cardarea == G.play then
if card.ability.extra.quest >= card.ability.extra.required then
return {
colour = G.C.GREEN,
chips = card.ability.extra.chips,
mult = card.ability.extra.mult,
card = card
}
end
end
end
end
}
if MagicTheJokering.config.include_clover_suit then
--Doubling Season
SMODS.Joker {
object_type = "Joker",
name = "mtg-doublingseason",
key = "doublingseason",
pos = { x = 1, y = 6 },
order = 12,
rarity = 2,
cost = 6,
atlas = "mtg_atlas",
unlocked = false,
discovered = false,
config = { extra = { repetitions = 1 } },
calculate = function(self, card, context)
-- Checks that the current cardarea is G.play, or the cards that have been played, then checks to see if it's time to check for repetition.
-- The "not context.repetition_only" is there to keep it separate from seals.
if context.cardarea == G.play and context.repetition and not context.repetition_only then
-- context.other_card is something that's used when either context.individual or context.repetition is true
-- It is each card 1 by 1, but in other cases, you'd need to iterate over the scoring hand to check which cards are there.
if context.other_card:is_suit(suit_clovers.key) then
return {
message = localize("k_again_ex"),
repetitions = card.ability.extra.repetitions,
-- The card the repetitions are applying to is context.other_card
card = card
}
end
end
end
}
end
--Hardened Scales
SMODS.Joker {
object_type = "Joker",
name = "mtg-hardenedscales",
key = "hardenedscales",
pos = { x = 15, y = 1 },
config = { extra = { buff_increase = 1} },
order = 10,
rarity = 2,
cost = 5,
atlas = "mtg_atlas",
loc_vars = function(self, info_queue, center)
return { vars = { } }
end,
calculate = function(self, card, context)
end
}
--ivy lane denizen
--Played cards with Clover suit give +3 Mult when scored
if MagicTheJokering.config.include_clover_suit then
SMODS.Joker {
object_type = "Joker",
name = "mtg-ivylanedenizen",
key = "ivylanedenizen",
pos = { x = 8, y = 4 },
config = { extra = {bonus_mult = 3} },
order = 5,
rarity = 1,
cost = 5,
atlas = "mtg_atlas",
loc_vars = function(self, info_queue, center)
return { vars = { center.ability.extra.bonus_mult, center.ability.extra.neg_mult} }
end,
calculate = function(self, card, context)
if context.individual and not context.repetition then
if context.cardarea == G.play then
if context.other_card:is_suit(suit_clovers.key) then
return {
mult = card.ability.extra.bonus_mult,
card = card
}
end
end
end
end
}
--primalcrux
SMODS.Joker {
object_type = "Joker",
name = "mtg-primalcrux",
key = "primalcrux",
pos = { x = 10, y = 4 },
config = { extra = {extra = 0.05, x_mult = 1} },
order = 5,
rarity = 2,
cost = 7,
atlas = "mtg_atlas",
unlocked = false,
loc_vars = function(self, info_queue, center)
return { vars = { center.ability.extra.extra, center.ability.extra.x_mult} }
end,
calculate = function(self, card, context)
if context.joker_main then
return {
message = localize({ type = "variable", key = "a_xmult", vars = { card.ability.extra.x_mult } }),
Xmult_mod = card.ability.extra.x_mult,
}
end
if context.cardarea == G.play and context.individual and not context.blueprint and not context.repetition then
if context.other_card:is_suit(suit_clovers.key) then
card.ability.extra.x_mult = card.ability.extra.x_mult + card.ability.extra.extra
return {
extra = { focus = card, message = localize("k_upgrade_ex") },
card = card,
colour = G.C.MULT,
}
end
end
end,
}
--yavimaya
SMODS.Joker {
object_type = "Joker",
name = "mtg-yavimaya",
key = "yavimaya",
pos = {
x = 3,
y = 3
},
atlas = 'mtg_atlas',
cost = 8,
order = 13,
rarity = 3,
unlocked = false,
config = {},
loc_vars = function(self, info_queue, card)
return { }
end
}
--Goblin Anarchomancer
--Played cards with Clover or Heart suit give x1.25 Mult when scored
SMODS.Joker {
object_type = "Joker",
name = "mtg-anarchomancer",
key = "anarchomancer",
pos = { x = 10, y = 5 },
config = { extra = {bonus_chips = 30} },
order = 5,
rarity = 1,
cost = 5,
atlas = "mtg_atlas",
loc_vars = function(self, info_queue, center)
return { vars = { center.ability.extra.bonus_chips} }
end,
calculate = function(self, card, context)
if context.individual and not context.repetition then
if context.cardarea == G.play then
if context.other_card:is_suit(suit_clovers.key) or context.other_card:is_suit("Hearts") then
return {
chips = card.ability.extra.bonus_chips,
card = card
}
end
end
end
end
}
--knotvine mystic
-- X2.5 mult if all cards held in hand are diamonds, hearts, or clovers
SMODS.Joker {
object_type = "Joker",
name = "mtg-knotvine",
key = "knotvine",
pos = { x = 5, y = 5 },
config = { extra = {x_mult_modifier = 2.5} },
order = 5,
rarity = 2,
cost = 6,
atlas = "mtg_atlas",
loc_vars = function(self, info_queue, center)
return { vars = { center.ability.extra.x_mult_modifier} }
end,
calculate = function(self, card, context)
if context.joker_main then
local naya_suits, all_cards = 0, 0
for k, v in ipairs(G.hand.cards) do
all_cards = all_cards + 1
if v:is_suit('Diamonds', nil, true) or v:is_suit('Hearts', nil, true) or v:is_suit(suit_clovers.key, nil, true) then
naya_suits = naya_suits + 1
end
end
if naya_suits == all_cards then
return {
message = localize{type='variable',key='a_xmult',vars={card.ability.extra.x_mult_modifier}},
Xmult_mod = card.ability.extra.x_mult_modifier
}
end
end
end
}
end
--Whirler Virtuoso
SMODS.Joker {
object_type = "joker",
name = "Whirler Virtuoso",
key = "whirler",
pos = { x = 12, y = 5 },
atlas = "mtg_atlas",
cost = 8,
order = 14,
rarity = 3,
config = { extra = { energy = 0, require_token_count = 3, add_energy = 1}, mtg_energy = true },
loc_vars = function(self, info_queue, center)
info_queue[#info_queue+1] = { key = "r_mtg_current_energy", set = "Other", config = {extra = G.GAME.mtg_energy_storage}, vars = { G.GAME.mtg_energy_storage or "?"}}
return { vars = { center.ability.extra.energy, center.ability.extra.require_token_count, center.ability.extra.add_energy } }
end,
calculate = function(self, card, context)
if context.buying_card and context.other_card == self then
return (energy_storage_increase(card, context))
end
if context.cardarea == G.jokers and context.joker_main then
return (mtg_increment_energy(card, context))
end
if context.use_energy then
G.E_MANAGER:add_event(Event({
func = function()
local _suit, _rank = SMODS.Suits[suit_suitless.key].card_key, "2"
create_playing_card({front = G.P_CARDS[_suit..'_'.._rank], center = token_thopter}, G.hand, nil, i ~= 1, {G.C.SECONDARY_SET.Magic})
G.hand:sort()
if context.blueprint_card then context.blueprint_card:juice_up() else card:juice_up() end
return true
end}))
playing_card_joker_effects({true})
end
end,
}
-- mycosynth lattice
SMODS.Joker {
object_type = "Joker",
name = "mtg-mycosynthlattice",
key = "mycosynth_lattice",
pos = { x = 14, y = 5 },
atlas = "mtg_atlas",
cost = 8,
order = 14,
rarity = 3,
unlocked = false,
config = {},
loc_vars = function(self, info_queue, card)
return { }
end
}
SMODS.Joker {
object_type = "Joker",
name = "mtg-cheif_of_the_foundry",
key = "cheif_of_the_foundry",
pos = { x = 15, y = 5 },
atlas = "mtg_atlas",
cost = 8,
order = 14,
rarity = 1,
config = { extra = { mult = 3 } },
loc_vars = function(self, info_queue, center)
return { vars = { center.ability.extra.mult } }
end,
calculate = function(self, card, context)
if context.individual and context.cardarea == G.play then
if context.other_card:is_suit(suit_suitless.key) then
return {
mult = card.ability.extra.mult,
card = card
}
end
end
end
}
SMODS.Joker {
name = "mtg-omarthis",
key = "omarthis",
pos = { x = 12, y = 6 },
atlas = "mtg_atlas",
cost = 8,
order = 14,
rarity = 2,
unlocked = false,
config = { extra = { chips = 1, chip_mod = 2.5 } },
loc_vars = function(self, info_queue, center)
return { vars = { center.ability.extra.chips, center.ability.extra.chip_mod } }
end,
calculate = function(self, card, context)
if context.individual and context.cardarea == G.play then
if context.other_card:is_suit(suit_suitless.key) then
card.ability.extra.chips = card.ability.extra.chips + card.ability.extra.chip_mod
end
end
if context.joker_main then
return {
chips = card.ability.extra.chips,
message = localize({ type = "variable", key = "a_chips", vars = { card.ability.extra.chips } }),
colour = G.C.CHIPS,
card = card
}
end
end
}
--chromatic lantern
SMODS.Joker {
object_type = "Joker",
name = "mtg-chromaticlantern",
key = "chromaticlantern",
pos = { x = 4, y = 5 },
config = { extra = {bonus_mult = 0.25, suits = {}}},
rarity = 3,
order = 14,
cost = 8,
atlas = "mtg_atlas",
loc_vars = function(self, info_queue, center)
info_queue[#info_queue+1] = G.P_CENTERS.m_gold
return { vars = {center.ability.extra.bonus_mult, center.ability.x_mult}}
end,
calculate = function(self, card, context)
if context.individual and not context.repetition then
if context.cardarea == G.play then
if not context.other_card.debuff and not context.blueprint then
for key, value in pairs(SMODS.Suits) do
if context.other_card:is_suit(key) then
if not card.ability.extra.suits[key] then
card.ability.x_mult = card.ability.x_mult + card.ability.extra.bonus_mult
card.ability.extra.suits[key] = 1
end
end
end
end
end
elseif context.end_of_round and not context.blueprint then
card.ability.extra.suits = {}
if card.ability.x_mult > 1 then
card.ability.x_mult = 1
return {
message = localize('k_reset'),
colour = G.C.RED
}
end
end
end
}
--eldrazimonument
SMODS.Joker {
object_type = "Joker",
name = "mtg-eldrazimonument",
key = "eldrazimonument",
pos = { x = 1, y = 5 },
config = { extra = {bonus_mult = 3}},
rarity = 2,
order = 14,
cost = 6,
atlas = "mtg_atlas",
loc_vars = function(self, info_queue, center)
return { vars = {center.ability.extra.bonus_mult}}
end,
calculate = function(self, card, context)
if context.individual and not context.repetition then
if context.cardarea == G.play then
return {
mult = card.ability.extra.bonus_mult,
card = card
}
end
elseif context.joker_main then
G.E_MANAGER:add_event(Event({
trigger = 'after',
delay = 0.15,
func = function()
if #G.hand.cards and #G.hand.cards >= 1 then
local temp_ID = G.hand.cards[1].base.id
local smallest = G.hand.cards[1]
for i=1, #G.hand.cards do
if temp_ID >= G.hand.cards[i].base.id and G.hand.cards[i].ability.effect ~= 'Stone Card' then temp_ID = G.hand.cards[i].base.id; smallest = G.hand.cards[i] end
end
if smallest.debuff then
card_eval_status_text(card, 'extra', nil, nil, nil, {message = localize('k_debuffed'),colour = G.C.RED})
else
G.E_MANAGER:add_event(Event({
trigger = 'after',
delay = 0.15,
func = function()
destroy_cards({smallest})
return true end}))
card_eval_status_text(card, 'extra', nil, nil, nil, {message = localize('mtg_sacrifice_ex')})
end
end
return true
end}))
end
end
}
--panharmonicon
SMODS.Joker {
object_type = "Joker",
name = "mtg-panharmonicon",
key = "panharmonicon",
pos = { x = 15, y = 4 },
atlas = "mtg_atlas",
cost = 8,
order = 14,
rarity = 3,
config = { },
loc_vars = function(self, info_queue, center)
return { }
end,
calculate = function(self, card, context)
if context.repetition and context.cardarea == G.play then
return {
message = localize("k_again_ex"),
repetitions = 1,
card = card
}
end
end
}
-- [[
--Decoction Module
SMODS.Joker {
object_type = "Joker",
name = "Decoction Module",
key = "decoction",
pos = { x = 0, y = 1 },
atlas = "mtg_atlas",
cost = 8,
order = 14,
rarity = 3,
config = { extra = { energy = 1, add_energy = 1} },
loc_vars = function(self, info_queue, center)
info_queue[#info_queue+1] = { key = "r_mtg_current_energy", set = "Other", config = {extra = G.GAME.mtg_energy_storage}, vars = { G.GAME.mtg_energy_storage or "?"}}
return { vars = { center.ability.extra.energy } }
end,
calculate = function(self, card, context)
if context.cardarea == G.play and context.individual then
return (mtg_increment_energy(card, context))
end
end
}
--]]
--dreamstone hedron
SMODS.Joker {
object_type = "Joker",
name = "mtg-dreamstonehedron",
key = "dreamstonehedron",
pos = { x = 13, y = 2 },
config = { extra = {money = 3, cards = 3}},
order = 15,
rarity = 1,
cost = 4,
atlas = "mtg_atlas",
loc_vars = function(self, info_queue, center)
return { vars = {center.ability.extra.money, center.ability.extra.cards}}
end,
calculate = function(self, card, context)
if context.selling_self then
if #G.hand.cards > 0 then
card_eval_status_text(context.blueprint_card or card, 'extra', nil, nil, nil, {message = localize('mtg_draw_ex')})
G.E_MANAGER:add_event(Event({trigger = 'after',delay = 0.1,func = function()
G.FUNCS.draw_from_deck_to_hand(card.ability.extra.cards)
return true end }))
end
end
end,
calc_dollar_bonus = function(self, card)
local bonus = card.ability.extra.money
if bonus > 0 then return bonus end
end
}
--helmofawakening
SMODS.Joker {
object_type = "Joker",
name = "mtg-helmofawakening",
key = "helmofawakening",
pos = { x = 2, y = 5 },
config = { extra = {discount = 1}},
order = 15,
rarity = 2,
cost = 6,
atlas = "mtg_atlas",
loc_vars = function(self, info_queue, center)
return { vars = {center.ability.extra.discount}}
end,
add_to_deck = function(self, card, from_debuff)
G.E_MANAGER:add_event(Event({func = function()
for k, v in pairs(G.I.CARD) do
if v.set_cost then v:set_cost() end
end
return true end }))
end,
remove_from_deck = function(self, card, from_debuff)
G.E_MANAGER:add_event(Event({func = function()
for k, v in pairs(G.I.CARD) do
if v.set_cost then v:set_cost() end
end
return true end }))
end,
calculate = function(self, card, context)
end
}
-- Lantern of Insight
-- + mult equal to value of top card
-- it tells you what the top card is
SMODS.Joker {
object_type = "Joker",
name = "mtg-lantern",
key = "lantern",
pos = { x = 2, y = 3},
config = { extra = { mult_per = 2} },
order = 16,
rarity = 1,
cost = 4,
immutable = true,
atlas = "mtg_atlas",
loc_vars = function(self, info_queue, center)
if G.deck and G.deck.cards[1] then
local current_value = G.deck and G.deck.cards[#G.deck.cards].base.nominal * center.ability.extra.mult_per or "?"
local suit_prefix = (G.deck and G.deck.cards[#G.deck.cards].base.id or "?")
local rank_suffix = (G.deck and G.deck.cards[#G.deck.cards].base.suit or '?')
if suit_prefix == 14 then suit_prefix = 'Ace' end
if suit_prefix == 13 then suit_prefix = 'King' end
if suit_prefix == 12 then suit_prefix = 'Queen' end
if suit_prefix == 11 then suit_prefix = 'Jack' end
return { vars = { center.ability.extra.mult_per, current_value, suit_prefix.." of "..rank_suffix }}
else
return { vars = {center.ability.extra.mult_per, 0, 'None'}}
end
end,
calculate = function(self, card, context)
if context.joker_main then
if G.deck.cards[1] then
card.ability.extra.mult_per = 2
local top_card = G.deck.cards[#G.deck.cards] or nil
return {
mult_mod = top_card.base.nominal * card.ability.extra.mult_per,
message = localize({ type = "variable", key = "a_mult", vars = { top_card.base.nominal * card.ability.extra.mult_per } })
}
end
end
end
}
--[[mightstone
SMODS.Joker {
object_type = "Joker",
name = "mtg-mightstone",
key = "mightstone",
pos = { x = 11, y = 4 },
config = { extra = { mult = 2} },
order = 10,
rarity = 1,
cost = 4,
atlas = "mtg_atlas",
loc_vars = function(self, info_queue, center)
return { vars = {center.ability.extra.mult } }
end,
calculate = function(self, card, context)
if context.individual then
if context.cardarea == G.play then
return {
mult = card.ability.extra.mult,
card = card
}
end
end
end
}]]
--power matrix
SMODS.Joker {
object_type = "Joker",
name = "mtg-powermatrix",
key = "powermatrix",
pos = { x = 0, y = 5 },
config = { extra = {buff = 1}},
order = 17,
rarity = 2,
cost = 6,
atlas = "mtg_atlas",
loc_vars = function(self, info_queue, center)
return { vars = {center.ability.extra.buff}}
end,
calculate = function(self, card, context)
if context.first_hand_drawn then
local eval = function() return G.GAME.current_round.discards_used == 0 and not G.RESET_JIGGLES end
juice_card_until(card, eval, true)
elseif context.pre_discard then
if G.GAME.current_round.discards_used <= 0 and #context.full_hand == 1 then
local _card = context.full_hand[1]
G.FUNCS.buff_cards({_card}, card.ability.extra.buff, 1, "random")
card_eval_status_text(card, 'extra', nil, nil, nil, {message = localize('k_upgrade_ex')})
end
end
end
}
--Urza's Mine
-- +50 chips, additional +150 chips if you have all
SMODS.Joker {
object_type = "Joker",
name = "mtg-urzamine",
key = "urzamine",
pos = { x = 0, y = 4 },
config = { extra = { base_chips = 50, bonus_chips = 200} },
order = 18,
rarity = 1,
cost = 3,
atlas = "mtg_atlas",
loc_vars = function(self, info_queue, center)
return { vars = { center.ability.extra.base_chips, center.ability.extra.bonus_chips} }
end,
calculate = function(self, card, context)
if context.joker_main then
local active = next(SMODS.find_card("j_mtg_urzapower")) and next(SMODS.find_card("j_mtg_urzatower"))
local chip
if active then
chip = card.ability.extra.bonus_chips
else
chip = card.ability.extra.base_chips
end
return {
chip_mod = chip,
message = localize({ type = "variable", key = "a_chips", vars = { chip } })
}
end
end
}
--Urza's Power-Plant
-- +8 mult, additional +32 mult if you have all
SMODS.Joker {
object_type = "Joker",
name = "mtg-urzapower",
key = "urzapower",
pos = { x = 6, y = 3 },
config = { extra = { base_mult = 6, bonus_mult = 36} },
order = 19,
rarity = 1,
cost = 4,
atlas = "mtg_atlas",
loc_vars = function(self, info_queue, center)
return { vars = { center.ability.extra.base_mult, center.ability.extra.bonus_mult} }
end,
calculate = function(self, card, context)
if context.joker_main then
local active = next(SMODS.find_card("j_mtg_urzamine")) and next(SMODS.find_card("j_mtg_urzatower"))
local mult
if active then
mult = card.ability.extra.bonus_mult
else
mult = card.ability.extra.base_mult
end
return {
mult_mod = mult,
message = localize({ type = "variable", key = "a_mult", vars = { mult } })
}
end
end
}
--Urza's Tower
-- x1.5 mult, additional x1.5 mult if you have all
SMODS.Joker {
object_type = "Joker",
name = "mtg-urzatower",
key = "urzatower",
pos = { x = 7, y = 3 },
config = { extra = { base_xmult = 1.5, bonus_xmult = 3} },
order = 20,
rarity = 1,
cost = 3,
atlas = "mtg_atlas",
loc_vars = function(self, info_queue, center)
return { vars = { center.ability.extra.base_xmult, center.ability.extra.bonus_xmult} }
end,
calculate = function(self, card, context)
if context.joker_main then
local active = next(SMODS.find_card("j_mtg_urzapower")) and next(SMODS.find_card("j_mtg_urzamine"))
local xmult
if active then
xmult = card.ability.extra.bonus_xmult
else
xmult = card.ability.extra.base_xmult
end
return {
Xmult_mod = xmult,
message = localize({ type = "variable", key = "a_xmult", vars = { xmult } })
}
end
end
}
| 0 | 0.965045 | 1 | 0.965045 | game-dev | MEDIA | 0.904312 | game-dev | 0.836654 | 1 | 0.836654 |
NathanHandley/EQWOWConverter | 130,629 | EQWOWConverter/ObjectModels/ObjectModel.cs | // Author: Nathan Handley (nathanhandley@protonmail.com)
// Copyright (c) 2025 Nathan Handley
//
// 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/>.
using EQWOWConverter.Common;
using EQWOWConverter.Creatures;
using EQWOWConverter.EQFiles;
using EQWOWConverter.ObjectModels.Properties;
using EQWOWConverter.Spells;
namespace EQWOWConverter.ObjectModels
{
internal class ObjectModel
{
public string Name = string.Empty;
public ObjectModelType ModelType;
public ObjectModelEQData EQObjectModelData = new ObjectModelEQData();
public ObjectModelProperties Properties = new ObjectModelProperties();
public List<UInt32> GlobalLoopSequenceLimits = new List<UInt32>();
public List<ObjectModelAnimation> ModelAnimations = new List<ObjectModelAnimation>();
public List<Int16> AnimationLookups = new List<Int16>();
public List<ObjectModelVertex> ModelVertices = new List<ObjectModelVertex>();
public List<ObjectModelBone> ModelBones = new List<ObjectModelBone>();
public List<ObjectModelTextureAnimation> ModelTextureAnimations = new List<ObjectModelTextureAnimation>();
public List<Int16> ModelBoneKeyLookups = new List<Int16>();
public SortedDictionary<int, List<Int16>> BoneLookupsByMaterialIndex = new SortedDictionary<int, List<Int16>>();
public List<ObjectModelMaterial> ModelMaterials = new List<ObjectModelMaterial>();
public List<ObjectModelTexture> ModelTextures = new List<ObjectModelTexture>();
public List<Int16> ModelTextureLookups = new List<Int16>();
public List<Int16> ModelTextureMappingLookups = new List<Int16>();
public List<Int16> ModelReplaceableTextureLookups = new List<Int16>();
public List<UInt16> ModelTextureTransparencyLookups = new List<UInt16>();
public SortedDictionary<int, ObjectModelTrackSequences<Fixed16>> ModelTextureTransparencySequenceSetByMaterialIndex = new SortedDictionary<int, ObjectModelTrackSequences<Fixed16>>();
public List<Int16> ModelTextureAnimationLookup = new List<Int16>();
public List<UInt16> ModelSecondTextureMaterialOverrides = new List<UInt16>();
public List<TriangleFace> ModelTriangles = new List<TriangleFace>();
public List<string> GeneratedTextureNames = new List<string>();
public BoundingBox GeometryBoundingBox = new BoundingBox();
public BoundingBox VisibilityBoundingBox = new BoundingBox();
public Dictionary<AnimationType, Sound> SoundsByAnimationType = new Dictionary<AnimationType, Sound>();
public int NumOfFidgetSounds = 0;
public Vector3 PortraitCameraPosition = new Vector3();
public Vector3 PortraitCameraTargetPosition = new Vector3();
public MeshData MeshData = new MeshData();
public bool IsSkeletal = false;
public bool IsLoaded = false;
public List<Vector3> CollisionPositions = new List<Vector3>();
public List<Vector3> CollisionFaceNormals = new List<Vector3>();
public List<TriangleFace> CollisionTriangles = new List<TriangleFace>();
public BoundingBox CollisionBoundingBox = new BoundingBox();
public float CollisionSphereRaidus = 0f;
private float MinimumVisibilityBoundingBoxSize;
public static Dictionary<string, ObjectModel> StaticObjectModelsByName = new Dictionary<string, ObjectModel>();
public ObjectModel(string name, ObjectModelProperties objectProperties, ObjectModelType modelType, float minimumVisibilityBoundingBoxSize)
{
Name = name;
Properties = objectProperties;
ModelType = modelType;
MinimumVisibilityBoundingBoxSize = minimumVisibilityBoundingBoxSize;
}
public void LoadEQObjectFromFile(string inputRootFolder, string eqInputObjectFileName)
{
if (IsLoaded == true)
{
Logger.WriteError("Failed to load EQ object data for object named '" + Name + "' as it was already loaded");
return;
}
// Clear any old data and reload it
EQObjectModelData = new ObjectModelEQData();
EQObjectModelData.LoadObjectDataFromDisk(Name, eqInputObjectFileName, inputRootFolder, Properties.CreatureModelTemplate);
// Store if it had a skeleton
if (EQObjectModelData.SkeletonData.BoneStructures.Count > 0)
IsSkeletal = true;
// Load it
Load(EQObjectModelData.Materials, EQObjectModelData.MeshData, EQObjectModelData.CollisionVertices, EQObjectModelData.CollisionTriangleFaces);
}
// TODO: Vertex Colors
public void Load(List<Material> initialMaterials, MeshData meshData, List<Vector3> collisionVertices, List<TriangleFace> collisionTriangleFaces,
List<EQSpellsEFF.EFFSpellSpriteListEffect>? spriteListEffects = null)
{
if (IsLoaded == true)
{
Logger.WriteError("Failed to load object named '" + Name + "' as it was already loaded");
return;
}
// Control for bad objects
if (meshData.Vertices.Count != meshData.TextureCoordinates.Count && meshData.Vertices.Count != meshData.Normals.Count)
{
Logger.WriteError("Failed to load wowobject named '" + Name + "' since vertex count doesn't match texture coordinate count or normal count");
return;
}
// Sprite List Effects need their model data generated
if (spriteListEffects != null && spriteListEffects.Count > 0)
GenerateSpriteListModelData(ref initialMaterials, ref meshData, ref spriteListEffects);
// Sort the geometry
meshData.SortDataByMaterialAndBones();
// Perform EQ->WoW translations if this is coming from a raw EQ object
if (ModelType == ObjectModelType.Creature || ModelType == ObjectModelType.StaticDoodad || ModelType == ObjectModelType.Transport || ModelType == ObjectModelType.EquipmentHeld)
{
float scaleAmount = Properties.ModelScalePreWorldScale * Configuration.GENERATE_WORLD_SCALE;
if (ModelType == ObjectModelType.Creature)
scaleAmount = Properties.ModelScalePreWorldScale * Configuration.GENERATE_CREATURE_SCALE;
else if (ModelType == ObjectModelType.EquipmentHeld)
scaleAmount = Properties.ModelScalePreWorldScale * Configuration.GENERATE_EQUIPMENT_HELD_SCALE;
// Determine if rotation is needed
bool doRotateOnZAxis = false;
if ((!IsSkeletal || ModelType == ObjectModelType.StaticDoodad) && ModelType != ObjectModelType.EquipmentHeld)
doRotateOnZAxis = true;
// Mesh Data
meshData.ApplyEQToWoWGeometryTranslationsAndScale(doRotateOnZAxis, scaleAmount);
// If there is any collision data, also translate that too
if (collisionVertices.Count > 0)
{
// Putting in a MeshData is just to gain access to "ApplyEQToWoWGeometryTranslationsAndScale"
MeshData collisionMeshData = new MeshData();
collisionMeshData.TriangleFaces = collisionTriangleFaces;
collisionMeshData.Vertices = collisionVertices;
collisionMeshData.ApplyEQToWoWGeometryTranslationsAndScale(doRotateOnZAxis, scaleAmount);
// Copy back
collisionTriangleFaces = collisionMeshData.TriangleFaces;
collisionVertices = collisionMeshData.Vertices;
}
}
// Process materials
ProcessMaterials(initialMaterials, ref meshData);
// Create model vertices
GenerateModelVertices(meshData);
// Correct any texture coordinates
CorrectTextureCoordinates();
// No texture replacement lookup (yet)
ModelReplaceableTextureLookups.Add(0);
// Build the bones and animation structures
// Note: Must come after bounding box generation (in GenerateModelVertices)
ProcessBonesAndAnimation(spriteListEffects);
// Collision data
ProcessCollisionData(meshData, initialMaterials, collisionVertices, collisionTriangleFaces);
// Create a global sequence if there is none and it's not an emitter or projectile
if (GlobalLoopSequenceLimits.Count == 0 && (ModelType != ObjectModelType.ParticleEmitter && ModelType != ObjectModelType.SpellProjectile))
GlobalLoopSequenceLimits.Add(0);
// Store the final state mesh data
MeshData = meshData;
// Mark as loaded
IsLoaded = true;
}
private void ProcessBonesAndAnimation(List<EQSpellsEFF.EFFSpellSpriteListEffect>? spriteListEffects)
{
// Emitters / Spell Effects
if (ModelType == ObjectModelType.ParticleEmitter || ModelType == ObjectModelType.SpellProjectile)
{
ModelBoneKeyLookups.Add(-1);
// Create a base bone
ModelBones.Add(new ObjectModelBone());
ModelBones[0].BoneNameEQ = "root";
// Make one animation, TODO: Missle
ModelAnimations.Add(new ObjectModelAnimation());
ModelAnimations[0].BoundingBox = VisibilityBoundingBox;
ModelAnimations[0].BoundingRadius = VisibilityBoundingBox.FurthestPointDistanceFromCenter();
if (Properties.SpellVisualEffectStageType == Spells.SpellVisualStageType.Impact)
{
if (Properties.SpellVisualType == Spells.SpellVisualType.BardTick)
{
UInt32 duration = Convert.ToUInt32(Convert.ToSingle(Configuration.SPELL_PERIODIC_SECONDS_PER_TICK_WOW * 1000) * Configuration.SPELL_EFFECT_BARD_TICK_VISUAL_DURATION_MOD_FROM_TICK);
ModelAnimations[0].DurationInMS = duration;
}
else
ModelAnimations[0].DurationInMS = Convert.ToUInt32(Configuration.SPELLS_EFFECT_EMITTER_TARGET_DURATION_IN_MS);
}
else
ModelAnimations[0].DurationInMS = Convert.ToUInt32(Configuration.SPELLS_EFFECT_EMITTER_LONGEST_SPELL_TIME_IN_MS);
// For spells that spray 'from the hands', it must be rotated a quarter turn so that it cones forward
if (Properties.SpellEmitterSpraysFromHands == true)
{
ModelBones[0].RotationTrack.AddSequence();
ModelBones[0].RotationTrack.AddValueToLastSequence(0, new QuaternionShort(0.7071f, 0, 0, 0.7071f));
}
// Animation data needs to added if there are sprite list effects
if (spriteListEffects != null)
{
AddAnimationDataForSpriteListEffects(spriteListEffects);
GenerateBoneLookups();
}
}
// Non Skeletal / Static objects
else if ((!IsSkeletal) && EQObjectModelData.Animations.Count == 0)
{
ModelBoneKeyLookups.Add(-1);
// Create a base bone
ModelBones.Add(new ObjectModelBone());
ModelBones[0].BoneNameEQ = "root";
if (Properties.ActiveDoodadAnimationType == null)
{
// Make one animation (standing) for normal static objects
ModelAnimations.Add(new ObjectModelAnimation());
ModelAnimations[0].BoundingBox = VisibilityBoundingBox;
ModelAnimations[0].BoundingRadius = VisibilityBoundingBox.FurthestPointDistanceFromCenter();
}
else
{
// For lift triggers, there is animation build-out that occurs specific to the behavior of it
BuildAnimationsForActiveDoodad();
}
}
// Skeletal
else
{
// Build the skeleton
if (BuildSkeletonBonesAndLookups() == false)
{
Logger.WriteError("Could not build skeleton information for object '" + Name + "'");
// Make one animation (standing)
ObjectModelBone newBone = new ObjectModelBone("root", -1);
ModelBones.Add(newBone);
ModelAnimations.Add(new ObjectModelAnimation());
ModelAnimations[0].BoundingBox = VisibilityBoundingBox;
ModelAnimations[0].BoundingRadius = VisibilityBoundingBox.FurthestPointDistanceFromCenter();
return;
}
if (CreateAndSetAnimations() == false)
{
Logger.WriteError("Could not create and set animations for object '" + Name + "'");
// Make one animation (standing)
ModelAnimations.Add(new ObjectModelAnimation());
ModelAnimations[0].BoundingBox = VisibilityBoundingBox;
ModelAnimations[0].BoundingRadius = VisibilityBoundingBox.FurthestPointDistanceFromCenter();
return;
}
// Fill out the nameplate bone translation
if (Properties.CreatureModelTemplate != null && Properties.CreatureModelTemplate.Race.NameplateAddedHeight > Configuration.GENERATE_FLOAT_EPSILON)
{
// Set the adjustment vector
ObjectModelBone nameplateBone = GetBoneWithName("nameplate");
Vector3 adjustmentVector = new Vector3(0, 0, Properties.CreatureModelTemplate.Race.NameplateAddedHeight);
int raceID = Properties.CreatureModelTemplate.Race.ID;
// These races project forward instead of up due to a rotation
if (raceID == 31 || raceID == 66 || raceID == 126)
adjustmentVector = new Vector3(0, Properties.CreatureModelTemplate.Race.NameplateAddedHeight, 0);
// These races project to their right instead of up due to a rotation
if (raceID == 107 || raceID == 135 || raceID == 154)
adjustmentVector = new Vector3(0, Properties.CreatureModelTemplate.Race.NameplateAddedHeight, 0);
// These races project to their right, but rotated the other way
if (raceID == 162 || raceID == 68)
adjustmentVector = new Vector3(Properties.CreatureModelTemplate.Race.NameplateAddedHeight * -1, 0, 0);
// Update all of the track sequences
for (int i = 0; i < nameplateBone.TranslationTrack.Values.Count; i++)
nameplateBone.TranslationTrack.AddValueToSequence(i, 0, adjustmentVector);
}
GenerateBoneLookups();
if (IsSkeletal)
{
// Set the portrait camera locations
SetupPortraitCamera();
}
}
}
private void GenerateBoneLookups()
{
// Create bone lookups on a per submesh basis (which are grouped by material)
// Note: Vertices are sorted by material and then by bone index already, so we can trust that here
List<int> vertexMaterialIDs = new List<int>();
for (int vertexIndex = 0; vertexIndex < ModelVertices.Count; vertexIndex++)
vertexMaterialIDs.Add(-1);
foreach (TriangleFace modelTriangle in ModelTriangles)
{
vertexMaterialIDs[modelTriangle.V1] = modelTriangle.MaterialIndex;
vertexMaterialIDs[modelTriangle.V2] = modelTriangle.MaterialIndex;
vertexMaterialIDs[modelTriangle.V3] = modelTriangle.MaterialIndex;
}
int currentMaterialID = -1;
for (int vertexIndex = 0; vertexIndex < ModelVertices.Count; vertexIndex++)
{
// Expand list if new material encountered
if (currentMaterialID != vertexMaterialIDs[vertexIndex])
{
currentMaterialID = vertexMaterialIDs[vertexIndex];
BoneLookupsByMaterialIndex.Add(currentMaterialID, new List<short>());
}
// Add lookup if new bone is encountered
byte curBoneIndex = ModelVertices[vertexIndex].BoneIndicesTrue[0];
if (BoneLookupsByMaterialIndex[currentMaterialID].Contains(curBoneIndex) == false)
BoneLookupsByMaterialIndex[currentMaterialID].Add(curBoneIndex);
// Add a lookup reference based on the lookup index
ModelVertices[vertexIndex].BoneIndicesLookup[0] = Convert.ToByte(BoneLookupsByMaterialIndex[currentMaterialID].Count - 1);
}
}
private void GenerateSpriteListModelData(ref List<Material> initialMaterials, ref MeshData meshData, ref List<EQSpellsEFF.EFFSpellSpriteListEffect> spriteListEffects)
{
initialMaterials.Clear();
meshData = new MeshData();
// Generate the model data for every sprite list effect
Dictionary<string, int> materialIDBySpriteListRootName = new Dictionary<string, int>();
int curQuadBoneIndex = 3; // Every quad gets a unique bone for rotation/manipulation. Offset by 3 since root will get 0, 1 is base rotation, 2 is continuous rotation, and transformed is 3
foreach (EQSpellsEFF.EFFSpellSpriteListEffect spriteListEffect in spriteListEffects)
{
// Create the materials based on sprite chains
foreach (var textureNamesChainByRootTexture in spriteListEffect.SpriteChainsBySpriteRoot)
{
// Load materials only once
bool materialAlreadyLoaded = false;
foreach (Material initialMaterial in initialMaterials)
{
if (initialMaterial.Name == textureNamesChainByRootTexture.Key)
{
materialAlreadyLoaded = true;
break;
}
}
if (materialAlreadyLoaded == true)
continue;
// Create the material for this
// Note: All known sprite lists for non-projectiles are sourced at 64x64, but there are some spell sprites at 32x32 (which shouldn't apply here)
UInt32 curMaterialID = Convert.ToUInt32(initialMaterials.Count);
UInt32 animationDelay = Convert.ToUInt32((textureNamesChainByRootTexture.Value.Count == 1) ? 0 : Configuration.SPELL_EFFECT_SPRITE_LIST_ANIMATION_FRAME_DELAY_IN_MS);
materialIDBySpriteListRootName.Add(textureNamesChainByRootTexture.Key, Convert.ToInt32(curMaterialID));
Material newMaterial = new Material(textureNamesChainByRootTexture.Key, textureNamesChainByRootTexture.Key, curMaterialID, MaterialType.TransparentAdditive,
textureNamesChainByRootTexture.Value, animationDelay, 64, 64, true);
newMaterial.IsParticleEffect = true;
initialMaterials.Add(newMaterial);
}
// Create geometry
for (int i = 0; i < spriteListEffect.Particles.Count; i++)
{
int materialID = materialIDBySpriteListRootName[spriteListEffect.Particles[i].SpriteName];
// Build the quads
Vector3 topLeft = new Vector3(0, 0.5f, 0.5f);
Vector3 bottomRight = new Vector3(0, -0.5f, -0.5f);
MeshData curQuadMeshData = new MeshData();
curQuadMeshData.GenerateAsQuad(materialID, topLeft, bottomRight, Convert.ToByte(curQuadBoneIndex));
meshData.AddMeshData(curQuadMeshData);
// TODO: Save the quad bone index relationship?
curQuadBoneIndex+=3; // 3 bones per sprite list effect node
}
}
}
private void AddAnimationDataForSpriteListEffects(List<EQSpellsEFF.EFFSpellSpriteListEffect> spriteListEffects)
{
// It's assumed that the 'standing' animation is already created by this point
if (ModelAnimations.Count == 0)
{
Logger.WriteError("AddAnimationDataForSpriteListEffects failed as there were no animations");
return;
}
int curQuadBoneIndex = 1; // Every quad gets a unique bone for rotation/manipulation. Offset by 1 since root gets 0.
foreach (EQSpellsEFF.EFFSpellSpriteListEffect spriteListEffect in spriteListEffects)
{
// Particles can be between 1 and 12, with them being equal in distance around the player
int numOfCirclingParticles = 0;
foreach (EQSpellsEFF.EFFSpellSpriteListParticle particle in spriteListEffect.Particles)
{
if (particle.Radius >= 0.1f || particle.Radius == 0f)
numOfCirclingParticles++;
}
List<QuaternionShort> particleRotations = QuaternionShort.GetQuaternionsInCircle(numOfCirclingParticles);
// Generate animation data
for (int i = 0; i < spriteListEffect.Particles.Count; i++)
{
EQSpellsEFF.EFFSpellSpriteListParticle curParticle = spriteListEffect.Particles[i];
// Each quad has 3 bones, one for the base rotation, one for the dynamic rotation, and one for the transformation + billboard
// Base Rotation bone
ModelBones.Add(new ObjectModelBone());
ModelBones[curQuadBoneIndex].ParentBone = 0;
// Add the rotation value if there's a particle to render in the circle, otherwise it has no rotation
if (particleRotations.Count > i)
{
ModelBones[curQuadBoneIndex].RotationTrack.InterpolationType = ObjectModelAnimationInterpolationType.Linear;
ModelBones[curQuadBoneIndex].RotationTrack.AddSequence();
ModelBones[curQuadBoneIndex].RotationTrack.AddValueToLastSequence(0, particleRotations[i]);
}
curQuadBoneIndex++;
int nonProjectileAnimTimeInMS = Configuration.SPELL_EFFECT_SPRITE_LIST_MAX_NON_PREJECTILE_ANIM_TIME_IN_MS;
if (Properties.SpellVisualType == SpellVisualType.BardTick)
{
int maxDuration = Convert.ToInt32(Convert.ToSingle(Configuration.SPELL_PERIODIC_SECONDS_PER_TICK_WOW * 1000) * Configuration.SPELL_EFFECT_BARD_TICK_VISUAL_DURATION_MOD_FROM_TICK);
nonProjectileAnimTimeInMS = Math.Min(nonProjectileAnimTimeInMS, maxDuration);
}
// Dynamic Rotation Bone
ModelBones.Add(new ObjectModelBone());
ModelBones[curQuadBoneIndex].ParentBone = Convert.ToInt16(curQuadBoneIndex - 1);
if (curParticle.CircularShift != 0)
{
// 15 shifts is 1 full rotation, positive is counterclockwise and negative is clockwise
bool isClockwise = false;
float numOfRotations = curParticle.CircularShift * Configuration.SPELL_EFFECT_SPRITE_LIST_CIRCULAR_SHIFT_MOD;
if (numOfRotations < 0)
{
numOfRotations *= -1;
isClockwise = true;
}
if (numOfRotations != 0)
{
ModelBones[curQuadBoneIndex].RotationTrack.InterpolationType = ObjectModelAnimationInterpolationType.Linear;
ModelBones[curQuadBoneIndex].RotationTrack.AddSequence();
ModelBones[curQuadBoneIndex].RotationTrack.AddValueToLastSequence(0, new QuaternionShort());
// There will be 4 moved-to frames per rotation, so calculate the size of a frame
int timeForOneRotationInMS = Convert.ToInt32(Convert.ToSingle(nonProjectileAnimTimeInMS) / numOfRotations);
int frameSizeInMS = timeForOneRotationInMS / 4;
// Add quarter rotations until past invis time
UInt32 totalTimeElapsedInMS = 0;
int curQuarterStepIndex = 0;
while (totalTimeElapsedInMS < nonProjectileAnimTimeInMS)
{
totalTimeElapsedInMS += Convert.ToUInt32(frameSizeInMS);
// Step up in quarter steps, and loop back around when hitting 5th
// Note: because of orientations these quaternions are actually the opposite of what they say (clockwise = counterclockwise)
if (isClockwise == false)
{
switch (curQuarterStepIndex)
{
case 0: ModelBones[curQuadBoneIndex].RotationTrack.AddValueToLastSequence(totalTimeElapsedInMS, new QuaternionShort(0, 0, 0.7071f, 0.7071f)); break;
case 1: ModelBones[curQuadBoneIndex].RotationTrack.AddValueToLastSequence(totalTimeElapsedInMS, new QuaternionShort(0, 0, 1, 0)); break;
case 2: ModelBones[curQuadBoneIndex].RotationTrack.AddValueToLastSequence(totalTimeElapsedInMS, new QuaternionShort(0, 0, 0.7071f, -0.7071f)); break;
case 3: ModelBones[curQuadBoneIndex].RotationTrack.AddValueToLastSequence(totalTimeElapsedInMS, new QuaternionShort(0, 0, 0, -1)); break;
case 4: ModelBones[curQuadBoneIndex].RotationTrack.AddValueToLastSequence(totalTimeElapsedInMS, new QuaternionShort(0, 0, -0.7071f, -0.7071f)); break;
case 5: ModelBones[curQuadBoneIndex].RotationTrack.AddValueToLastSequence(totalTimeElapsedInMS, new QuaternionShort(0, 0, -1, 0)); break;
case 6: ModelBones[curQuadBoneIndex].RotationTrack.AddValueToLastSequence(totalTimeElapsedInMS, new QuaternionShort(0, 0, -0.7071f, 0.7071f)); break;
case 7: ModelBones[curQuadBoneIndex].RotationTrack.AddValueToLastSequence(totalTimeElapsedInMS, new QuaternionShort(0, 0, 0, 1)); break;
default: break;
}
}
else
{
switch (curQuarterStepIndex)
{
case 0: ModelBones[curQuadBoneIndex].RotationTrack.AddValueToLastSequence(totalTimeElapsedInMS, new QuaternionShort(0, 0, -0.7071f, 0.7071f)); break;
case 1: ModelBones[curQuadBoneIndex].RotationTrack.AddValueToLastSequence(totalTimeElapsedInMS, new QuaternionShort(0, 0, -1, 0)); break;
case 2: ModelBones[curQuadBoneIndex].RotationTrack.AddValueToLastSequence(totalTimeElapsedInMS, new QuaternionShort(0, 0, -0.7071f, -0.7071f)); break;
case 3: ModelBones[curQuadBoneIndex].RotationTrack.AddValueToLastSequence(totalTimeElapsedInMS, new QuaternionShort(0, 0, 0, -1f)); break;
case 4: ModelBones[curQuadBoneIndex].RotationTrack.AddValueToLastSequence(totalTimeElapsedInMS, new QuaternionShort(0, 0, 0.7071f, -0.7071f)); break;
case 5: ModelBones[curQuadBoneIndex].RotationTrack.AddValueToLastSequence(totalTimeElapsedInMS, new QuaternionShort(0, 0, 1, 0)); break;
case 6: ModelBones[curQuadBoneIndex].RotationTrack.AddValueToLastSequence(totalTimeElapsedInMS, new QuaternionShort(0, 0, 0.7071f, 0.7071f)); break;
case 7: ModelBones[curQuadBoneIndex].RotationTrack.AddValueToLastSequence(totalTimeElapsedInMS, new QuaternionShort(0, 0, 0, 1)); break;
default: break;
}
}
curQuarterStepIndex++;
if (curQuarterStepIndex == 8)
curQuarterStepIndex = 0;
}
}
}
curQuadBoneIndex++;
// Billboard Bone
ModelBones.Add(new ObjectModelBone());
ModelBones[curQuadBoneIndex].ParentBone = Convert.ToInt16(curQuadBoneIndex - 1);
ModelBones[curQuadBoneIndex].Flags |= Convert.ToUInt16(ObjectModelBoneFlags.SphericalBillboard);
// Translation (radius, pulse effect, vertical force)
float curSpriteRadius = curParticle.Radius *= Configuration.SPELL_EFFECT_SPRITE_LIST_RADIUS_MOD;
ModelBones[curQuadBoneIndex].TranslationTrack.InterpolationType = ObjectModelAnimationInterpolationType.Linear;
ModelBones[curQuadBoneIndex].TranslationTrack.AddSequence();
ModelBones[curQuadBoneIndex].TranslationTrack.AddValueToLastSequence(0, new Vector3(curSpriteRadius, 0f, 0f));
UInt32 animMidTimestamp = Convert.ToUInt32(nonProjectileAnimTimeInMS / 2);
float pulseMaxDistance = curSpriteRadius;
if (spriteListEffect.EffectType == EQSpellListEffectType.Pulsating && (curParticle.Radius == 0f || curParticle.Radius >= 0.1f)) // Low (but not zero) means static image at player
pulseMaxDistance = curSpriteRadius + Configuration.SPELL_EFFECT_SPRITE_LIST_PULSE_RANGE;
float forceMaxDistance = 0f;
if (curParticle.VerticalForce != 0)
{
switch (curParticle.VerticalForce)
{
case -3: forceMaxDistance = Configuration.SPELL_EFFECT_SPRITE_LIST_VERTICAL_FORCE_LOW; break;
case -2: forceMaxDistance = Configuration.SPELL_EFFECT_SPRITE_LIST_VERTICAL_FORCE_LOW / 2; break;
case -1: forceMaxDistance = Configuration.SPELL_EFFECT_SPRITE_LIST_VERTICAL_FORCE_LOW / 3; break;
case 1: forceMaxDistance = Configuration.SPELL_EFFECT_SPRITE_LIST_VERTICAL_FORCE_HIGH / 3; break;
case 2: forceMaxDistance = Configuration.SPELL_EFFECT_SPRITE_LIST_VERTICAL_FORCE_HIGH / 2; break;
case 3: forceMaxDistance = Configuration.SPELL_EFFECT_SPRITE_LIST_VERTICAL_FORCE_HIGH; break;
default: break;
}
}
ModelBones[curQuadBoneIndex].TranslationTrack.AddValueToLastSequence(animMidTimestamp, new Vector3(pulseMaxDistance, 0f, forceMaxDistance * 0.5f));
ModelBones[curQuadBoneIndex].TranslationTrack.AddValueToLastSequence(Convert.ToUInt32(nonProjectileAnimTimeInMS), new Vector3(curSpriteRadius, 0f, forceMaxDistance));
// Set Scale
// EQ values are 0 - 25
float spriteScaleEQ = MathF.Min(curParticle.Scale, Configuration.SPELLS_EFFECT_SPRITE_LIST_SIZE_SCALE_MAX_EQ_VALUE);
float spriteScaleWOW = Configuration.SPELLS_EFFECT_SPRITE_LIST_SIZE_SCALE_MIN + (Configuration.SPELLS_EFFECT_SPRITE_LIST_SIZE_SCALE_MAX -
Configuration.SPELLS_EFFECT_SPRITE_LIST_SIZE_SCALE_MIN) * (spriteScaleEQ / Configuration.SPELLS_EFFECT_SPRITE_LIST_SIZE_SCALE_MAX_EQ_VALUE);
ModelBones[curQuadBoneIndex].ScaleTrack.InterpolationType = ObjectModelAnimationInterpolationType.Linear;
ModelBones[curQuadBoneIndex].ScaleTrack.AddSequence();
ModelBones[curQuadBoneIndex].ScaleTrack.AddValueToLastSequence(0, new Vector3(spriteScaleWOW, spriteScaleWOW, spriteScaleWOW));
ModelBones[curQuadBoneIndex].ScaleTrack.AddValueToLastSequence(Convert.ToUInt32(nonProjectileAnimTimeInMS - 1), new Vector3(spriteScaleWOW, spriteScaleWOW, spriteScaleWOW));
// Hide the sprites after 2 seconds, as that's when all sprite list animations 'ends' with exception of projectiles
ModelBones[curQuadBoneIndex].ScaleTrack.AddValueToLastSequence(Convert.ToUInt32(nonProjectileAnimTimeInMS), new Vector3(0f, 0f, 0f));
if (Properties.SpellVisualType == SpellVisualType.BardTick)
{
int maxDuration = Convert.ToInt32(Convert.ToSingle(Configuration.SPELL_PERIODIC_SECONDS_PER_TICK_WOW * 1000) * Configuration.SPELL_EFFECT_BARD_TICK_VISUAL_DURATION_MOD_FROM_TICK);
int finalFrameTimestamp = Math.Min(Configuration.SPELLS_EFFECT_EMITTER_LONGEST_SPELL_TIME_IN_MS, maxDuration);
ModelBones[curQuadBoneIndex].ScaleTrack.AddValueToLastSequence(Convert.ToUInt32(maxDuration), new Vector3(0f, 0f, 0f));
}
else
ModelBones[curQuadBoneIndex].ScaleTrack.AddValueToLastSequence(Convert.ToUInt32(Configuration.SPELLS_EFFECT_EMITTER_LONGEST_SPELL_TIME_IN_MS), new Vector3(0f, 0f, 0f));
curQuadBoneIndex++;
}
}
}
private void BuildAnimationsForActiveDoodad()
{
// Associate all of the verts with the single bone that should already be set up
if (ModelBones.Count == 0)
{
Logger.WriteError("Failed building animations for activeDoodad, as there are no bones");
return;
}
for (int vertexIndex = 0; vertexIndex < ModelVertices.Count; vertexIndex++)
ModelVertices[vertexIndex].BoneIndicesLookup[0] = 0;
// Lay out the bone tracks for the 5 animations
for (int i = 0; i < 5; i++)
{
ModelBones[0].ScaleTrack.AddSequence();
ModelBones[0].RotationTrack.AddSequence();
ModelBones[0].TranslationTrack.AddSequence();
}
ModelBones[0].ScaleTrack.InterpolationType = ObjectModelAnimationInterpolationType.Linear;
ModelBones[0].RotationTrack.InterpolationType = ObjectModelAnimationInterpolationType.Linear;
ModelBones[0].TranslationTrack.InterpolationType = ObjectModelAnimationInterpolationType.Linear;
// Scale the mod value if translation and mod controlled
switch (Properties.ActiveDoodadAnimationType)
{
case ActiveDoodadAnimType.OnActivateSlideUpDownWithMod: Properties.ActiveDoodadAnimSlideValue *= Configuration.GENERATE_WORLD_SCALE; break;
default: break; // nothing
}
// Open
ObjectModelAnimation animationOpen = new ObjectModelAnimation();
animationOpen.AnimationType = AnimationType.Open;
animationOpen.BoundingBox = VisibilityBoundingBox;
animationOpen.BoundingRadius = VisibilityBoundingBox.FurthestPointDistanceFromCenter();
animationOpen.DurationInMS = Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS);
switch (Properties.ActiveDoodadAnimationType)
{
case ActiveDoodadAnimType.OnActivateSlideUpDownWithMod:
{
ModelBones[0].TranslationTrack.AddValueToSequence(0, 0, new Vector3(0, 0, 0));
ModelBones[0].TranslationTrack.AddValueToSequence(0, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS), new Vector3(0, 0, Properties.ActiveDoodadAnimSlideValue));
} break;
case ActiveDoodadAnimType.OnActivateSlideLeft:
{
ModelBones[0].TranslationTrack.AddValueToSequence(0, 0, new Vector3(0, 0, 0));
ModelBones[0].TranslationTrack.AddValueToSequence(0, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS), new Vector3(0, GeometryBoundingBox.GetYDistance(), 0));
} break;
case ActiveDoodadAnimType.OnActivateSlideUp:
{
ModelBones[0].TranslationTrack.AddValueToSequence(0, 0, new Vector3(0, 0, 0));
ModelBones[0].TranslationTrack.AddValueToSequence(0, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS), new Vector3(0, 0, GeometryBoundingBox.GetZDistance()));
} break;
case ActiveDoodadAnimType.OnActivateRotateAroundZClockwiseHalf:
{
ModelBones[0].RotationTrack.AddValueToSequence(0, 0, new QuaternionShort());
ModelBones[0].RotationTrack.AddValueToSequence(0, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS), new QuaternionShort(0, 0, 1f, 0));
} break;
case ActiveDoodadAnimType.OnActivateRotateAroundZCounterclockwiseQuarter:
{
ModelBones[0].RotationTrack.AddValueToSequence(0, 0, new QuaternionShort());
ModelBones[0].RotationTrack.AddValueToSequence(0, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS), new QuaternionShort(0, 0, -0.7071f, 0.7071f));
} break;
case ActiveDoodadAnimType.OnActivateRotateAroundZClockwiseQuarter:
{
ModelBones[0].RotationTrack.AddValueToSequence(0, 0, new QuaternionShort());
ModelBones[0].RotationTrack.AddValueToSequence(0, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS), new QuaternionShort(0, 0, 0.7071f, 0.7071f));
} break;
case ActiveDoodadAnimType.OnActivateRotateUpOpen:
{
ModelBones[0].RotationTrack.AddValueToSequence(0, 0, new QuaternionShort(0, 0.7071f, 0, 0.7071f));
ModelBones[0].RotationTrack.AddValueToSequence(0, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS), new QuaternionShort());
} break;
case ActiveDoodadAnimType.OnActivateRotateDownClosedBackwards:
{
ModelBones[0].RotationTrack.AddValueToSequence(0, 0, new QuaternionShort());
ModelBones[0].RotationTrack.AddValueToSequence(0, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS), new QuaternionShort(0, -0.7071f, 0, 0.7071f));
} break;
case ActiveDoodadAnimType.OnIdleRotateAroundZCounterclockwise:
{
ModelBones[0].RotationTrack.AddValueToSequence(0, 0, new QuaternionShort());
ModelBones[0].RotationTrack.AddValueToSequence(0, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS * 0.25), new QuaternionShort(0, 0, 0.7071f, 0.7071f));
ModelBones[0].RotationTrack.AddValueToSequence(0, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS * 0.5), new QuaternionShort(0, 0, 1f, 0));
ModelBones[0].RotationTrack.AddValueToSequence(0, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS * 0.75), new QuaternionShort(0, 0, 0.7071f, -0.7071f));
ModelBones[0].RotationTrack.AddValueToSequence(0, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS), new QuaternionShort(0, 0, 0, -1f));
} break;
case ActiveDoodadAnimType.OnIdleRotateAroundYClockwise:
{
ModelBones[0].RotationTrack.AddValueToSequence(0, 0, new QuaternionShort());
ModelBones[0].RotationTrack.AddValueToSequence(0, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS * 0.25), new QuaternionShort(0, 0.7071f, 0, 0.7071f));
ModelBones[0].RotationTrack.AddValueToSequence(0, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS * 0.5), new QuaternionShort(0, 1f, 0f, 0));
ModelBones[0].RotationTrack.AddValueToSequence(0, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS * 0.75), new QuaternionShort(0, 0.7071f, 0f, -0.7071f));
ModelBones[0].RotationTrack.AddValueToSequence(0, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS), new QuaternionShort(0, 0, 0, -1f));
} break;
default: Logger.WriteError("BuildAnimationsForActiveDoodad failed due to unhandled ActiveDoodadAnimType of '" + Properties.ActiveDoodadAnimationType + "'"); return;
}
ModelAnimations.Add(animationOpen);
// Opened
ObjectModelAnimation animationOpened = new ObjectModelAnimation();
animationOpened.AnimationType = AnimationType.Opened;
animationOpened.BoundingBox = VisibilityBoundingBox;
animationOpened.BoundingRadius = VisibilityBoundingBox.FurthestPointDistanceFromCenter();
animationOpened.DurationInMS = Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS);
switch (Properties.ActiveDoodadAnimationType)
{
case ActiveDoodadAnimType.OnActivateSlideUpDownWithMod:
{
ModelBones[0].TranslationTrack.AddValueToSequence(1, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS), new Vector3(0, 0, Properties.ActiveDoodadAnimSlideValue));
} break;
case ActiveDoodadAnimType.OnActivateSlideLeft:
{
ModelBones[0].TranslationTrack.AddValueToSequence(1, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS), new Vector3(0, GeometryBoundingBox.GetYDistance(), 0));
} break;
case ActiveDoodadAnimType.OnActivateSlideUp:
{
ModelBones[0].TranslationTrack.AddValueToSequence(1, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS), new Vector3(0, 0, GeometryBoundingBox.GetZDistance()));
} break;
case ActiveDoodadAnimType.OnActivateRotateAroundZClockwiseHalf:
{
ModelBones[0].RotationTrack.AddValueToSequence(1, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS), new QuaternionShort(0, 0, 1f, 0));
} break;
case ActiveDoodadAnimType.OnActivateRotateAroundZCounterclockwiseQuarter:
{
ModelBones[0].RotationTrack.AddValueToSequence(1, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS), new QuaternionShort(0, 0, -0.7071f, 0.7071f));
} break;
case ActiveDoodadAnimType.OnActivateRotateAroundZClockwiseQuarter:
{
ModelBones[0].RotationTrack.AddValueToSequence(1, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS), new QuaternionShort(0, 0, 0.7071f, 0.7071f));
} break;
case ActiveDoodadAnimType.OnActivateRotateUpOpen:
{
ModelBones[0].RotationTrack.AddValueToSequence(1, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS), new QuaternionShort());
} break;
case ActiveDoodadAnimType.OnActivateRotateDownClosedBackwards:
{
ModelBones[0].RotationTrack.AddValueToSequence(1, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS), new QuaternionShort(0, -0.7071f, 0, 0.7071f));
} break;
case ActiveDoodadAnimType.OnIdleRotateAroundZCounterclockwise:
{
ModelBones[0].RotationTrack.AddValueToSequence(1, 0, new QuaternionShort());
ModelBones[0].RotationTrack.AddValueToSequence(1, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS * 0.25), new QuaternionShort(0, 0, 0.7071f, 0.7071f));
ModelBones[0].RotationTrack.AddValueToSequence(1, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS * 0.5), new QuaternionShort(0, 0, 1f, 0));
ModelBones[0].RotationTrack.AddValueToSequence(1, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS * 0.75), new QuaternionShort(0, 0, 0.7071f, -0.7071f));
ModelBones[0].RotationTrack.AddValueToSequence(1, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS), new QuaternionShort(0, 0, 0, -1f));
} break;
case ActiveDoodadAnimType.OnIdleRotateAroundYClockwise:
{
ModelBones[0].RotationTrack.AddValueToSequence(1, 0, new QuaternionShort());
ModelBones[0].RotationTrack.AddValueToSequence(1, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS * 0.25), new QuaternionShort(0, 0.7071f, 0, 0.7071f));
ModelBones[0].RotationTrack.AddValueToSequence(1, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS * 0.5), new QuaternionShort(0, 1f, 0f, 0));
ModelBones[0].RotationTrack.AddValueToSequence(1, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS * 0.75), new QuaternionShort(0, 0.7071f, 0f, -0.7071f));
ModelBones[0].RotationTrack.AddValueToSequence(1, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS), new QuaternionShort(0, 0, 0, -1f));
} break;
default: Logger.WriteError("BuildAnimationsForActiveDoodad failed due to unhandled ActiveDoodadAnimType of '" + Properties.ActiveDoodadAnimationType + "'"); return;
}
ModelAnimations.Add(animationOpened);
// Close
ObjectModelAnimation animationClose = new ObjectModelAnimation();
animationClose.AnimationType = AnimationType.Close;
animationClose.BoundingBox = VisibilityBoundingBox;
animationClose.BoundingRadius = VisibilityBoundingBox.FurthestPointDistanceFromCenter();
animationClose.DurationInMS = Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS);
switch (Properties.ActiveDoodadAnimationType)
{
case ActiveDoodadAnimType.OnActivateSlideUpDownWithMod:
{
ModelBones[0].TranslationTrack.AddValueToSequence(2, 0, new Vector3(0, 0, Properties.ActiveDoodadAnimSlideValue));
ModelBones[0].TranslationTrack.AddValueToSequence(2, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS), new Vector3(0, 0, 0));
} break;
case ActiveDoodadAnimType.OnActivateSlideLeft:
{
ModelBones[0].TranslationTrack.AddValueToSequence(2, 0, new Vector3(0, GeometryBoundingBox.GetYDistance(), 0));
ModelBones[0].TranslationTrack.AddValueToSequence(2, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS), new Vector3(0, 0, 0));
} break;
case ActiveDoodadAnimType.OnActivateSlideUp:
{
ModelBones[0].TranslationTrack.AddValueToSequence(2, 0, new Vector3(0, 0, GeometryBoundingBox.GetZDistance()));
ModelBones[0].TranslationTrack.AddValueToSequence(2, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS), new Vector3(0, 0, 0));
} break;
case ActiveDoodadAnimType.OnActivateRotateAroundZClockwiseHalf:
{
ModelBones[0].RotationTrack.AddValueToSequence(2, 0, new QuaternionShort(0, 0, 1f, 0));
ModelBones[0].RotationTrack.AddValueToSequence(2, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS), new QuaternionShort());
} break;
case ActiveDoodadAnimType.OnActivateRotateAroundZCounterclockwiseQuarter:
{
ModelBones[0].RotationTrack.AddValueToSequence(2, 0, new QuaternionShort(0, 0, -0.7071f, 0.7071f));
ModelBones[0].RotationTrack.AddValueToSequence(2, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS), new QuaternionShort());
} break;
case ActiveDoodadAnimType.OnActivateRotateAroundZClockwiseQuarter:
{
ModelBones[0].RotationTrack.AddValueToSequence(2, 0, new QuaternionShort(0, 0, 0.7071f, 0.7071f));
ModelBones[0].RotationTrack.AddValueToSequence(2, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS), new QuaternionShort());
} break;
case ActiveDoodadAnimType.OnActivateRotateUpOpen:
{
ModelBones[0].RotationTrack.AddValueToSequence(2, 0, new QuaternionShort());
ModelBones[0].RotationTrack.AddValueToSequence(2, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS), new QuaternionShort(0, 0.7071f, 0, 0.7071f));
} break;
case ActiveDoodadAnimType.OnActivateRotateDownClosedBackwards:
{
ModelBones[0].RotationTrack.AddValueToSequence(2, 0, new QuaternionShort(0, -0.7071f, 0, 0.7071f));
ModelBones[0].RotationTrack.AddValueToSequence(2, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS), new QuaternionShort());
} break;
case ActiveDoodadAnimType.OnIdleRotateAroundZCounterclockwise:
{
ModelBones[0].RotationTrack.AddValueToSequence(2, 0, new QuaternionShort());
ModelBones[0].RotationTrack.AddValueToSequence(2, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS * 0.25), new QuaternionShort(0, 0, 0.7071f, 0.7071f));
ModelBones[0].RotationTrack.AddValueToSequence(2, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS * 0.5), new QuaternionShort(0, 0, 1f, 0));
ModelBones[0].RotationTrack.AddValueToSequence(2, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS * 0.75), new QuaternionShort(0, 0, 0.7071f, -0.7071f));
ModelBones[0].RotationTrack.AddValueToSequence(2, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS), new QuaternionShort(0, 0, 0, -1f));
} break;
case ActiveDoodadAnimType.OnIdleRotateAroundYClockwise:
{
ModelBones[0].RotationTrack.AddValueToSequence(2, 0, new QuaternionShort());
ModelBones[0].RotationTrack.AddValueToSequence(2, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS * 0.25), new QuaternionShort(0, 0.7071f, 0, 0.7071f));
ModelBones[0].RotationTrack.AddValueToSequence(2, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS * 0.5), new QuaternionShort(0, 1f, 0f, 0));
ModelBones[0].RotationTrack.AddValueToSequence(2, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS * 0.75), new QuaternionShort(0, 0.7071f, 0f, -0.7071f));
ModelBones[0].RotationTrack.AddValueToSequence(2, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS), new QuaternionShort(0, 0, 0, -1f));
} break;
default: Logger.WriteError("BuildAnimationsForActiveDoodad failed due to unhandled ActiveDoodadAnimType of '" + Properties.ActiveDoodadAnimationType + "'"); return;
}
ModelAnimations.Add(animationClose);
// Stand
ObjectModelAnimation animationStand = new ObjectModelAnimation();
animationStand.AnimationType = AnimationType.Stand;
animationStand.BoundingBox = VisibilityBoundingBox;
animationStand.BoundingRadius = VisibilityBoundingBox.FurthestPointDistanceFromCenter();
animationStand.DurationInMS = Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS);
switch (Properties.ActiveDoodadAnimationType)
{
case ActiveDoodadAnimType.OnActivateRotateUpOpen:
{
ModelBones[0].RotationTrack.AddValueToSequence(3, 0, new QuaternionShort(0, 0.7071f, 0, 0.7071f));
} break;
case ActiveDoodadAnimType.OnIdleRotateAroundZCounterclockwise:
{
ModelBones[0].RotationTrack.AddValueToSequence(3, 0, new QuaternionShort());
ModelBones[0].RotationTrack.AddValueToSequence(3, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS * 0.25), new QuaternionShort(0, 0, 0.7071f, 0.7071f));
ModelBones[0].RotationTrack.AddValueToSequence(3, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS * 0.5), new QuaternionShort(0, 0, 1f, 0));
ModelBones[0].RotationTrack.AddValueToSequence(3, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS * 0.75), new QuaternionShort(0, 0, 0.7071f, -0.7071f));
ModelBones[0].RotationTrack.AddValueToSequence(3, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS), new QuaternionShort(0, 0, 0, -1f));
} break;
case ActiveDoodadAnimType.OnIdleRotateAroundYClockwise:
{
ModelBones[0].RotationTrack.AddValueToSequence(3, 0, new QuaternionShort());
ModelBones[0].RotationTrack.AddValueToSequence(3, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS * 0.25), new QuaternionShort(0, 0.7071f, 0, 0.7071f));
ModelBones[0].RotationTrack.AddValueToSequence(3, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS * 0.5), new QuaternionShort(0, 1f, 0f, 0));
ModelBones[0].RotationTrack.AddValueToSequence(3, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS * 0.75), new QuaternionShort(0, 0.7071f, 0f, -0.7071f));
ModelBones[0].RotationTrack.AddValueToSequence(3, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS), new QuaternionShort(0, 0, 0, -1f));
} break;
default:
{
} break; // Do Nothing
}
ModelAnimations.Add(animationStand);
// Closed
ObjectModelAnimation animationClosed = new ObjectModelAnimation();
animationClosed.AnimationType = AnimationType.Closed;
animationClosed.BoundingBox = VisibilityBoundingBox;
animationClosed.BoundingRadius = VisibilityBoundingBox.FurthestPointDistanceFromCenter();
animationClosed.DurationInMS = Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS);
switch (Properties.ActiveDoodadAnimationType)
{
case ActiveDoodadAnimType.OnActivateRotateUpOpen:
{
ModelBones[0].RotationTrack.AddValueToSequence(4, 0, new QuaternionShort(0, 0.7071f, 0, 0.7071f));
} break;
case ActiveDoodadAnimType.OnIdleRotateAroundZCounterclockwise:
{
ModelBones[0].RotationTrack.AddValueToSequence(4, 0, new QuaternionShort());
ModelBones[0].RotationTrack.AddValueToSequence(4, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS * 0.25), new QuaternionShort(0, 0, 0.7071f, 0.7071f));
ModelBones[0].RotationTrack.AddValueToSequence(4, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS * 0.5), new QuaternionShort(0, 0, 1f, 0));
ModelBones[0].RotationTrack.AddValueToSequence(4, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS * 0.75), new QuaternionShort(0, 0, 0.7071f, -0.7071f));
ModelBones[0].RotationTrack.AddValueToSequence(4, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS), new QuaternionShort(0, 0, 0, -1f));
} break;
case ActiveDoodadAnimType.OnIdleRotateAroundYClockwise:
{
ModelBones[0].RotationTrack.AddValueToSequence(4, 0, new QuaternionShort());
ModelBones[0].RotationTrack.AddValueToSequence(4, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS * 0.25), new QuaternionShort(0, 0.7071f, 0, 0.7071f));
ModelBones[0].RotationTrack.AddValueToSequence(4, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS * 0.5), new QuaternionShort(0, 1f, 0f, 0));
ModelBones[0].RotationTrack.AddValueToSequence(4, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS * 0.75), new QuaternionShort(0, 0.7071f, 0f, -0.7071f));
ModelBones[0].RotationTrack.AddValueToSequence(4, Convert.ToUInt32(Properties.ActiveDoodadAnimTimeInMS), new QuaternionShort(0, 0, 0, -1f));
} break;
default:
{
} break; // Do Nothing
}
ModelAnimations.Add(animationClosed);
}
private bool BuildSkeletonBonesAndLookups()
{
if (EQObjectModelData.SkeletonData.BoneStructures.Count == 0)
{
Logger.WriteError("Could not build skeleton information for object '" + Name + "' due to no EQ bone structures found");
return false;
}
// Build out bones
ModelBones.Clear();
// Add a "main" bone in the start. Note, all bone indices will need to increase by 1 as a result
ObjectModelBone mainBone = new ObjectModelBone();
mainBone.BoneNameEQ = "main";
mainBone.ScaleTrack.InterpolationType = ObjectModelAnimationInterpolationType.None;
mainBone.RotationTrack.InterpolationType = ObjectModelAnimationInterpolationType.None;
mainBone.TranslationTrack.InterpolationType = ObjectModelAnimationInterpolationType.None;
ModelBones.Add(mainBone);
// Since a 'main' bone was added to the start, all other bone indices needs to be increased by 1
foreach (ObjectModelVertex vertex in ModelVertices)
vertex.BoneIndicesTrue[0]++;
// First block in the bones themselves
foreach (EQSkeleton.EQSkeletonBone eqBone in EQObjectModelData.SkeletonData.BoneStructures)
{
ObjectModelBone curBone = new ObjectModelBone();
curBone.BoneNameEQ = eqBone.BoneName;
if (curBone.BoneNameEQ == "root")
{
curBone.ScaleTrack.InterpolationType = ObjectModelAnimationInterpolationType.None;
curBone.RotationTrack.InterpolationType = ObjectModelAnimationInterpolationType.None;
curBone.TranslationTrack.InterpolationType = ObjectModelAnimationInterpolationType.None;
curBone.ParentBone = 0;
curBone.ParentBoneNameEQ = "main";
}
else
{
curBone.ScaleTrack.InterpolationType = ObjectModelAnimationInterpolationType.Linear;
curBone.RotationTrack.InterpolationType = ObjectModelAnimationInterpolationType.Linear;
curBone.TranslationTrack.InterpolationType = ObjectModelAnimationInterpolationType.Linear;
}
curBone.KeyBoneID = -1;
ModelBones.Add(curBone);
}
// Next assign all children, accounting for main bone
foreach (EQSkeleton.EQSkeletonBone eqBone in EQObjectModelData.SkeletonData.BoneStructures)
{
if (GetFirstBoneIndexForEQBoneNames(eqBone.BoneName) == -1)
{
Logger.WriteError("Could not find a bone with name '" + eqBone.BoneName + "' for object '" + Name + "'");
continue;
}
int parentBoneIndex = GetFirstBoneIndexForEQBoneNames(eqBone.BoneName);
for (int childIndex = 0; childIndex < eqBone.Children.Count; childIndex++)
{
int modChildIndex = eqBone.Children[childIndex] + 1;
if (modChildIndex >= ModelBones.Count)
{
Logger.WriteError("Invalid bone index when trying to assign children for '" + eqBone.BoneName + "' for object '" + Name + "'");
continue;
}
ObjectModelBone childBone = ModelBones[modChildIndex];
childBone.ParentBone = Convert.ToInt16(parentBoneIndex);
childBone.ParentBoneNameEQ = ModelBones[parentBoneIndex].BoneNameEQ;
}
}
// Set bone lookups
ModelBoneKeyLookups.Clear();
// Block out 27 key bones with blank
for (int i = 0; i < 27; i++)
ModelBoneKeyLookups.Add(-1);
// Set root as a key
SetKeyBone(KeyBoneType.Root);
if (IsSkeletal)
{
// Create the nameplate bone
GenerateNameplateBone();
// Create the bones required for events
CreateEventOrAttachmentBone("dth"); // DeathThud
//CreateEventBone("cah"); // HandleCombatAnim
CreateEventOrAttachmentBone("css"); // PlayWeaponSwoosh
//CreateEventBone("cpp"); // PlayCombatActionAnim
CreateEventOrAttachmentBone("fd1"); // PlayFidgetSound1
CreateEventOrAttachmentBone("fd2"); // PlayFidgetSound2
CreateEventOrAttachmentBone("fsd"); // HandleFootfallAnimEvent
CreateEventOrAttachmentBone("hit"); // PlayWoundAnimKit
// Bones for attachments
if (ModelType == ObjectModelType.EquipmentHeld)
{
CreateEventOrAttachmentBone("shield_mnt");
CreateEventOrAttachmentBone("lbw_r");
CreateEventOrAttachmentBone("lbw_l");
}
// Set any key bones
SetKeyBone(KeyBoneType.Jaw);
SetKeyBone(KeyBoneType._Breath);
SetKeyBone(KeyBoneType._Name);
SetKeyBone(KeyBoneType.CCH);
}
return true;
}
public void GenerateNameplateBone()
{
// Grab the base bone for it
int initialBoneID = GetFirstBoneIndexForEQBoneNames("head_point", "he", "root");
// Create the nameplate bone for it
ObjectModelBone nameplateBone = new ObjectModelBone("nameplate", Convert.ToInt16(initialBoneID));
ModelBones.Add(nameplateBone);
}
public bool CreateAndSetAnimations()
{
// Set the various animations (note: Do not change the order of the first 4)
FindAndSetAnimationForType(AnimationType.Stand);
if (IsSkeletal)
{
FindAndSetAnimationForType(AnimationType.Stand); // Stand mid-idle
FindAndSetAnimationForType(AnimationType.Stand, new List<EQAnimationType>() { EQAnimationType.o01StandIdle, EQAnimationType.o02StandArmsToSide, EQAnimationType.p01StandPassive, EQAnimationType.posStandPose }); // Idle 1 / Fidget
FindAndSetAnimationForType(AnimationType.Stand, new List<EQAnimationType>() { EQAnimationType.o02StandArmsToSide, EQAnimationType.o01StandIdle, EQAnimationType.p01StandPassive, EQAnimationType.posStandPose }); // Idle 2 / Fidget
FindAndSetAnimationForType(AnimationType.Death);
FindAndSetAnimationForType(AnimationType.AttackUnarmed);
FindAndSetAnimationForType(AnimationType.Walk);
FindAndSetAnimationForType(AnimationType.Run);
FindAndSetAnimationForType(AnimationType.ShuffleLeft);
FindAndSetAnimationForType(AnimationType.ShuffleRight);
FindAndSetAnimationForType(AnimationType.Swim);
FindAndSetAnimationForType(AnimationType.SwimIdle);
FindAndSetAnimationForType(AnimationType.SwimBackwards);
FindAndSetAnimationForType(AnimationType.SwimLeft);
FindAndSetAnimationForType(AnimationType.SwimRight);
FindAndSetAnimationForType(AnimationType.CombatWound);
FindAndSetAnimationForType(AnimationType.CombatCritical);
FindAndSetAnimationForType(AnimationType.SpellCastOmni);
FindAndSetAnimationForType(AnimationType.SpellCastDirected);
// Update the stand/fidget animation timers so that there is a fidget sometimes
if (ModelAnimations.Count > 2 && ModelAnimations[1].AnimationType == AnimationType.Stand)
{
// Update timers
int fidgetSliceAll = Convert.ToInt32(32767 * (Convert.ToDouble(Configuration.CREATURE_FIDGET_TIME_PERCENT) / 100));
int nonFidgetSliceAll = 32767 - fidgetSliceAll;
int nonFidgetSlice1 = nonFidgetSliceAll / 2;
int nonFidgetSlice2 = nonFidgetSliceAll - nonFidgetSlice1;
int fidgetSlice1 = fidgetSliceAll / 2;
int fidgetSlice2 = fidgetSliceAll - fidgetSlice1;
ModelAnimations[0].PlayFrequency = Convert.ToInt16(nonFidgetSlice1);
ModelAnimations[1].PlayFrequency = Convert.ToInt16(nonFidgetSlice2);
ModelAnimations[2].PlayFrequency = Convert.ToInt16(fidgetSlice1);
ModelAnimations[3].PlayFrequency = Convert.ToInt16(fidgetSlice2);
// Link animations
ModelAnimations[0].NextAnimation = 2;
ModelAnimations[1].NextAnimation = 3;
ModelAnimations[2].NextAnimation = 1;
ModelAnimations[3].NextAnimation = 0;
}
}
// For every bone that has animation frames, add the first one to the end to close the animation sequences (if it loops)
foreach (ObjectModelBone bone in ModelBones)
{
for (int i = 0; i < ModelAnimations.Count; i++)
{
// If more than one frame of animation. reduce the new frame timestamp by half a frame to avoid too long of a 'freeze' between loops, which is more EQ like
UInt32 newFrameTimestamp = Convert.ToUInt32(ModelAnimations[i].DurationInMS);
if (ModelAnimations[i].NumOfFramesFromEQTemplate > 1)
{
UInt32 avgAnimationFrameDuration = Convert.ToUInt32(ModelAnimations[i].DurationInMS / ModelAnimations[i].NumOfFramesFromEQTemplate);
newFrameTimestamp -= (avgAnimationFrameDuration / 2);
}
if (bone.ScaleTrack.Timestamps[i].Timestamps.Count > 1)
{
bone.ScaleTrack.Timestamps[i].Timestamps.Add(Convert.ToUInt32(ModelAnimations[i].DurationInMS));
if (ModelAnimations[i].Loop)
bone.ScaleTrack.Values[i].Values.Add(bone.ScaleTrack.Values[i].Values[0]);
else
bone.ScaleTrack.Values[i].Values.Add(bone.ScaleTrack.Values[i].Values[bone.ScaleTrack.Values[i].Values.Count - 1]);
}
if (bone.RotationTrack.Timestamps[i].Timestamps.Count > 1)
{
bone.RotationTrack.Timestamps[i].Timestamps.Add(Convert.ToUInt32(ModelAnimations[i].DurationInMS));
if (ModelAnimations[i].Loop)
{
QuaternionShort curRotation = new QuaternionShort(bone.RotationTrack.Values[i].Values[0]);
QuaternionShort priorRotation = new QuaternionShort(bone.RotationTrack.Values[i].Values[bone.RotationTrack.Values[i].Values.Count - 1]);
curRotation.RecalculateToShortestFromOther(priorRotation);
bone.RotationTrack.Values[i].Values.Add(curRotation);
}
else
bone.RotationTrack.Values[i].Values.Add(bone.RotationTrack.Values[i].Values[bone.RotationTrack.Values[i].Values.Count - 1]);
}
if (bone.TranslationTrack.Timestamps[i].Timestamps.Count > 1)
{
bone.TranslationTrack.Timestamps[i].Timestamps.Add(Convert.ToUInt32(ModelAnimations[i].DurationInMS));
if (ModelAnimations[i].Loop)
bone.TranslationTrack.Values[i].Values.Add(bone.TranslationTrack.Values[i].Values[0]);
else
bone.TranslationTrack.Values[i].Values.Add(bone.TranslationTrack.Values[i].Values[bone.TranslationTrack.Values[i].Values.Count - 1]);
}
}
}
if (ModelAnimations.Count == 0)
Logger.WriteError("Zero animations for skeletal model object '" + Name + "', so it will crash if you try to load it");
// Set the animation lookups
SetAllAnimationLookups();
return true;
}
public void SetupPortraitCamera()
{
if (ModelAnimations.Count == 0)
{
Logger.WriteError("Could not set the portrait camera because there were not enough animations");
return;
}
// Use the 'name' bone since it points at the head
int headBoneID = GetFirstBoneIndexForEQBoneNames("head_point", "he", "pe", "root");
if (headBoneID == -1)
{
Logger.WriteError("Could not set the portrait camera because the head bone was indexed at -1");
return;
}
// Using the standing animation location, make this the base target point for the camera
ObjectModelBone headBone = ModelBones[headBoneID];
ObjectModelBone curBone = headBone;
while (curBone.TranslationTrack.Values[0].Values.Count == 0 && curBone.ParentBone != -1)
curBone = ModelBones[curBone.ParentBone];
if (curBone.TranslationTrack.Values[0].Values.Count == 0)
{
Logger.WriteError("Could not set the portrait camera because a valid head bone could not be located");
return;
}
Vector3 headLocation = new Vector3();
// Add all of the transformation data to get the actual head position
bool moreToProcess = true;
while (moreToProcess)
{
// Rotate
if (curBone.RotationTrack.Values[0].Values.Count > 0)
headLocation = Vector3.GetRotated(headLocation, curBone.RotationTrack.Values[0].Values[0]);
// Scale
if (curBone.ScaleTrack.Values[0].Values.Count > 0)
headLocation = Vector3.GetScaled(headLocation, curBone.ScaleTrack.Values[0].Values[0].X);
// Translate
if (curBone.TranslationTrack.Values[0].Values.Count > 0)
headLocation += curBone.TranslationTrack.Values[0].Values[0];
if (curBone.ParentBone != -1)
{
curBone = ModelBones[curBone.ParentBone];
moreToProcess = true;
}
else
moreToProcess = false;
}
PortraitCameraTargetPosition = headLocation;
PortraitCameraPosition = headLocation;
if (Properties.CreatureModelTemplate != null)
{
PortraitCameraPosition += Properties.CreatureModelTemplate.Race.CameraPositionMod;
PortraitCameraTargetPosition += Properties.CreatureModelTemplate.Race.CameraTargetPositionMod;
}
}
public void FindAndSetAnimationForType(AnimationType animationType, List<EQAnimationType>? overrideEQAnimationTypes = null)
{
// Determine what animations can work
List<EQAnimationType> compatibleAnimationTypes;
if (overrideEQAnimationTypes == null)
compatibleAnimationTypes = ObjectModelAnimation.GetPrioritizedCompatibleEQAnimationTypes(animationType);
else
compatibleAnimationTypes = overrideEQAnimationTypes;
foreach (EQAnimationType compatibleAnimationType in compatibleAnimationTypes)
{
// Look for a match, and process it if found
foreach(var animation in EQObjectModelData.Animations)
{
if (animation.Value.EQAnimationType == compatibleAnimationType)
{
// Capture and set this animation
Logger.WriteDebug(string.Concat("Found usable candidate, setting to eq type '", animation.Key, "' for object '", Name, "'"));
// Create the base animation object
ObjectModelAnimation newAnimation = new ObjectModelAnimation();
newAnimation.DurationInMS = Convert.ToUInt32(animation.Value.TotalTimeInMS);
newAnimation.AnimationType = animationType;
newAnimation.EQAnimationTypeTrue = animation.Value.EQAnimationType;
newAnimation.EQAnimationTypePreferred = compatibleAnimationTypes[0];
newAnimation.BoundingBox = VisibilityBoundingBox;
newAnimation.BoundingRadius = VisibilityBoundingBox.FurthestPointDistanceFromCenter();
newAnimation.AliasNext = Convert.ToUInt16(ModelAnimations.Count); // The next animation is itself, so it's a loop (TODO: Change this)
newAnimation.NumOfFramesFromEQTemplate = animation.Value.FrameCount;
ModelAnimations.Add(newAnimation);
// Create an animation track sequence for each bone
foreach (ObjectModelBone bone in ModelBones)
{
bone.ScaleTrack.AddSequence();
bone.RotationTrack.AddSequence();
bone.TranslationTrack.AddSequence();
}
float worldScaleAmount = Configuration.GENERATE_CREATURE_SCALE;
if (ModelType == ObjectModelType.StaticDoodad)
worldScaleAmount = Configuration.GENERATE_WORLD_SCALE;
// Add the animation-bone transformations to the bone objects for each frame
Dictionary<string, int> curTimestampsByBoneName = new Dictionary<string, int>();
for (int i = 0; i < animation.Value.AnimationFrames.Count; i++)
{
Animation.BoneAnimationFrame animationFrame = animationFrame = animation.Value.AnimationFrames[i];
if (DoesBoneExistForName(animationFrame.GetBoneName()) == false)
{
Logger.WriteDebug(string.Concat("For object '", Name, "' skipping bone with name '", animationFrame.GetBoneName(), "' when mapping animation since it couldn't be found"));
continue;
}
ObjectModelBone curBone = GetBoneWithName(animationFrame.GetBoneName());
// Root always just has one frame
if (animationFrame.GetBoneName() == "root")
{
curBone.ScaleTrack.AddValueToLastSequence(0, new Vector3(1, 1, 1));
curBone.RotationTrack.AddValueToLastSequence(0, new QuaternionShort());
curBone.TranslationTrack.AddValueToLastSequence(0, new Vector3(0, 0, 0));
}
// Regular bones append the animation frame
else
{
// Format and transform the animation frame values from EQ to WoW
Vector3 frameTranslation = new Vector3(animationFrame.XPosition * worldScaleAmount * Properties.ModelScalePreWorldScale,
animationFrame.YPosition * worldScaleAmount * Properties.ModelScalePreWorldScale,
animationFrame.ZPosition * worldScaleAmount * Properties.ModelScalePreWorldScale);
Vector3 frameScale = new Vector3(animationFrame.Scale, animationFrame.Scale, animationFrame.Scale);
QuaternionShort frameRotation = new QuaternionShort(-animationFrame.XRotation,
-animationFrame.YRotation,
-animationFrame.ZRotation,
animationFrame.WRotation);
// SLERP the rotation to fix it on translation to WoW. If there's a previous frame, base off that
if (curBone.RotationTrack.Values.Count > 0 && curBone.RotationTrack.Values[curBone.RotationTrack.Values.Count-1].Values.Count > 0)
{
QuaternionShort priorRotation = curBone.RotationTrack.Values[curBone.RotationTrack.Values.Count - 1].Values[curBone.RotationTrack.Values[curBone.RotationTrack.Values.Count - 1].Values.Count - 1];
frameRotation.RecalculateToShortestFromOther(priorRotation);
}
else
frameRotation.RecalculateToShortest();
// For bones that connect to root, add the height mod
if (curBone.ParentBoneNameEQ == "root")
frameTranslation.Z += Properties.ModelLiftPreWorldScale * worldScaleAmount;
// Calculate the frame start time
UInt32 curTimestamp = 0;
if (curTimestampsByBoneName.ContainsKey(animationFrame.GetBoneName()) == false)
curTimestampsByBoneName.Add(animationFrame.GetBoneName(), 0);
else
curTimestamp = Convert.ToUInt32(curTimestampsByBoneName[animationFrame.GetBoneName()]);
// Add the values
curBone.ScaleTrack.AddValueToLastSequence(curTimestamp, frameScale);
curBone.RotationTrack.AddValueToLastSequence(curTimestamp, frameRotation);
curBone.TranslationTrack.AddValueToLastSequence(curTimestamp, frameTranslation);
// Increment the frame start for next
curTimestampsByBoneName[animationFrame.GetBoneName()] += animationFrame.FramesMS;
}
}
// Animation set, so exit
return;
}
}
}
Logger.WriteDebug(String.Concat("No animation candidate was found for object '", Name, "'"));
}
public int GetFirstBoneIndexForEQBoneNames(params string[] eqBoneNames)
{
foreach (string eqBoneName in eqBoneNames)
{
for (int i = 0; i < ModelBones.Count; i++)
{
ObjectModelBone curBone = ModelBones[i];
if (curBone.BoneNameEQ == eqBoneName)
return i;
}
}
return -1;
}
public int GetBoneIndexForAttachmentType(ObjectModelAttachmentType attachmentType)
{
// Default to root bone
int returnValue = -1;
if (ModelBoneKeyLookups.Count >= 27)
returnValue = ModelBoneKeyLookups[26];
switch (attachmentType)
{
case ObjectModelAttachmentType.Chest:
case ObjectModelAttachmentType.ChestBloodFront:
{
returnValue = GetFirstBoneIndexForEQBoneNames("ch", "pe", "root");
} break;
case ObjectModelAttachmentType.ChestBloodBack:
{
returnValue = GetFirstBoneIndexForEQBoneNames("ch", "pe", "root");
} break;
case ObjectModelAttachmentType.MouthBreath:
{
returnValue = GetFirstBoneIndexForEQBoneNames("ja", "head_point", "he", "ch", "pe", "root");
} break;
case ObjectModelAttachmentType.GroundBase:
{
returnValue = GetFirstBoneIndexForEQBoneNames("root");
} break;
case ObjectModelAttachmentType.PlayerName:
{
returnValue = GetFirstBoneIndexForEQBoneNames("nameplate");
}
break;
case ObjectModelAttachmentType.HeadTop:
{
returnValue = GetFirstBoneIndexForEQBoneNames("head_point", "pe", "root");
} break;
case ObjectModelAttachmentType.HandLeft_ItemVisual2:
case ObjectModelAttachmentType.SpellLeftHand:
{
returnValue = GetFirstBoneIndexForEQBoneNames("l_point", "pe", "root");
} break;
case ObjectModelAttachmentType.HandRight_ItemVisual1:
case ObjectModelAttachmentType.SpellRightHand:
{
returnValue = GetFirstBoneIndexForEQBoneNames("r_point", "pe", "root");
} break;
case ObjectModelAttachmentType.Shield_MountMain_ItemVisual0:
{
returnValue = GetFirstBoneIndexForEQBoneNames("shield_mnt", "pe", "root");
} break;
case ObjectModelAttachmentType.ElbowRight_ItemVisual3:
{
returnValue = GetFirstBoneIndexForEQBoneNames("lbw_r", "pe", "root");
} break;
case ObjectModelAttachmentType.ElbowLeft_ItemVisual4:
{
returnValue = GetFirstBoneIndexForEQBoneNames("lbw_l", "pe", "root");
}
break;
default:
{
Logger.WriteError("GetBoneIndexForAttachmentType error - Unhandled attachment type of '" + attachmentType.ToString() + "' for object model '" + Name + "'");
} break;
}
return returnValue;
}
public int GetBoneIndexForKeyBoneType(KeyBoneType keyBoneType)
{
// Default to root bone
int returnValue = -1;
if (ModelBoneKeyLookups.Count >= 27)
returnValue = ModelBoneKeyLookups[26];
switch (keyBoneType)
{
case KeyBoneType.Root:
{
returnValue = GetFirstBoneIndexForEQBoneNames("root");
} break;
case KeyBoneType.Jaw:
{
returnValue = GetFirstBoneIndexForEQBoneNames("ja", "head_point", "he", "ch", "pe", "root");
} break;
case KeyBoneType._Breath:
{
returnValue = GetFirstBoneIndexForEQBoneNames("ja", "head_point", "he", "ch", "pe", "root");
} break;
case KeyBoneType._Name:
{
returnValue = GetFirstBoneIndexForEQBoneNames("nameplate");
} break;
case KeyBoneType.CCH:
{
returnValue = GetFirstBoneIndexForEQBoneNames("head_point", "root"); // Complete guess as I don't know what CCH is
} break;
default:
{
Logger.WriteError("GetBoneIndexForKeyBoneType error - Unhandled key bone type of '" + keyBoneType.ToString() + "' for object model '" + Name + "'");
}
break;
}
return returnValue;
}
private void CreateEventOrAttachmentBone(string newBoneName)
{
// Get parent bone
switch (newBoneName.ToLower())
{
// Event Bones
case "cah":
case "css":
case "cpp":
case "fd1":
case "fd2":
case "fsd":
case "hit":
case "dth":
{
// For now, let's just use root
// TODO: Use something other than root?
int parentBoneID = GetFirstBoneIndexForEQBoneNames("root");
ObjectModelBone eventBone = new ObjectModelBone(newBoneName, Convert.ToInt16(parentBoneID));
ModelBones.Add(eventBone);
} break;
// Attachment Bones
case "shield_mnt": // Shield Mount
{
int parentBoneID = GetFirstBoneIndexForEQBoneNames("root");
ObjectModelBone attachBone = new ObjectModelBone(newBoneName, Convert.ToInt16(parentBoneID));
attachBone.PivotPoint = new Vector3(0.2012056f, -0.0001476863f, 0.003507267f); // From Sword_2H_Crystal_C_03.m2
ModelBones.Add(attachBone);
} break;
case "lbw_r": // Left Elbow Visual
{
int parentBoneID = GetFirstBoneIndexForEQBoneNames("root");
ObjectModelBone attachBone = new ObjectModelBone(newBoneName, Convert.ToInt16(parentBoneID));
attachBone.PivotPoint = new Vector3(0.9165421f, -0.0001476836f, 0.0009568771f); // From Sword_2H_Crystal_C_03.m2
ModelBones.Add(attachBone);
}
break;
case "lbw_l": // Right Elbow Visual
{
int parentBoneID = GetFirstBoneIndexForEQBoneNames("root");
ObjectModelBone attachBone = new ObjectModelBone(newBoneName, Convert.ToInt16(parentBoneID));
attachBone.PivotPoint = new Vector3(1.189032f, -0.0001476824f, 0.001456708f); // From Sword_2H_Crystal_C_03.m2
ModelBones.Add(attachBone);
}
break;
default:
{
Logger.WriteError("Error creating event or attachment bone with name '" + newBoneName + "' as it is unhandled");
}break;
}
}
private void SetAllAnimationLookups()
{
AnimationLookups.Clear();
// Pre-fill 49 animation lookups (supports events)
for (Int16 i = 0; i <= 49; i++)
AnimationLookups.Add(-1);
SetAnimationIndicesForAnimationType(AnimationType.Stand);
if (IsSkeletal)
{
SetAnimationIndicesForAnimationType(AnimationType.Walk);
SetAnimationIndicesForAnimationType(AnimationType.Run);
SetAnimationIndicesForAnimationType(AnimationType.CombatWound);
SetAnimationIndicesForAnimationType(AnimationType.CombatCritical);
SetAnimationIndicesForAnimationType(AnimationType.StandWound);
SetAnimationIndicesForAnimationType(AnimationType.AttackUnarmed);
SetAnimationIndicesForAnimationType(AnimationType.Death);
SetAnimationIndicesForAnimationType(AnimationType.Swim);
SetAnimationIndicesForAnimationType(AnimationType.Swim);
SetAnimationIndicesForAnimationType(AnimationType.SwimIdle);
SetAnimationIndicesForAnimationType(AnimationType.SwimBackwards);
SetAnimationIndicesForAnimationType(AnimationType.SwimLeft);
SetAnimationIndicesForAnimationType(AnimationType.SwimRight);
SetAnimationIndicesForAnimationType(AnimationType.SpellCastDirected);
SetAnimationIndicesForAnimationType(AnimationType.SpellCastOmni);
}
}
private void SetAnimationIndicesForAnimationType(AnimationType animationType)
{
List<EQAnimationType> validPreferredEQAnimationTypes = ObjectModelAnimation.GetPrioritizedCompatibleEQAnimationTypes(animationType);
int firstAnimationIndex = GetFirstAnimationIndexForEQAnimationTypes(validPreferredEQAnimationTypes.ToArray());
if (firstAnimationIndex == -1)
return;
if (Convert.ToInt32(animationType) >= AnimationLookups.Count)
{
for (int i = AnimationLookups.Count; i < Convert.ToInt32(animationType) + 1; i++)
AnimationLookups.Add(-1);
}
AnimationLookups[Convert.ToInt32(animationType)] = Convert.ToInt16(firstAnimationIndex);
}
private int GetFirstAnimationIndexForEQAnimationTypes(params EQAnimationType[] eqAnimationTypes)
{
foreach (EQAnimationType eqAnimationType in eqAnimationTypes)
{
for (int i = 0; i < ModelAnimations.Count; i++)
{
ObjectModelAnimation curAnimation = ModelAnimations[i];
if (curAnimation.EQAnimationTypePreferred == eqAnimationType)
return i;
}
}
return -1;
}
private void SetKeyBone(KeyBoneType keyBoneType)
{
int boneIndex = GetBoneIndexForKeyBoneType(keyBoneType);
ModelBoneKeyLookups[Convert.ToInt32(keyBoneType)] = Convert.ToInt16(boneIndex);
if (boneIndex != -1)
ModelBones[boneIndex].KeyBoneID = Convert.ToInt32(keyBoneType);
}
private ObjectModelBone GetBoneWithName(string name)
{
foreach (ObjectModelBone bone in ModelBones)
if (bone.BoneNameEQ == name)
return bone;
Logger.WriteError("No bone named '" + name + "' for object '" + Name + "'");
return new ObjectModelBone();
}
private bool DoesBoneExistForName(string name)
{
foreach (ObjectModelBone bone in ModelBones)
if (bone.BoneNameEQ == name)
return true;
return false;
}
private void GenerateModelVertices(MeshData meshData)
{
foreach (TriangleFace face in meshData.TriangleFaces)
ModelTriangles.Add(new TriangleFace(face));
for (int i = 0; i < meshData.Vertices.Count; i++)
{
ObjectModelVertex newModelVertex = new ObjectModelVertex();
newModelVertex.Position = new Vector3(meshData.Vertices[i]);
newModelVertex.Normal = new Vector3(meshData.Normals[i]);
newModelVertex.Texture1TextureCoordinates = new TextureCoordinates(meshData.TextureCoordinates[i]);
if (meshData.BoneIDs.Count > 0)
newModelVertex.BoneIndicesTrue[0] = meshData.BoneIDs[i];
ModelVertices.Add(newModelVertex);
}
// Generate bounding box
GeometryBoundingBox = BoundingBox.GenerateBoxFromVectors(ModelVertices);
VisibilityBoundingBox = new BoundingBox(GeometryBoundingBox);
VisibilityBoundingBox.ExpandToMinimumSize(MinimumVisibilityBoundingBoxSize);
}
private void ProcessMaterials(List<Material> initialMaterials, ref MeshData meshData)
{
// Purge any invalid material references
// TODO: Look into making this work for non-skeletal
if (IsSkeletal)
{
List<Material> updatedMaterialList;
meshData.RemoveInvalidMaterialReferences(initialMaterials, out updatedMaterialList);
initialMaterials = updatedMaterialList;
}
List<Material> expandedMaterials = new List<Material>();
foreach (Material material in initialMaterials)
{
// Mark exception materials that should always be bright
if (Properties.AlwaysBrightMaterialsByName.Contains(material.Name))
material.AlwaysBrightOverride = true;
// Save on the exception list
expandedMaterials.Add(new Material(material));
}
foreach (Material material in initialMaterials)
{
// If animated, expand out into additional materials with additional geometry
if (material.IsAnimated() == true)
{
if (material.TextureNames.Count <= 1)
{
Logger.WriteError("Material '" + material.UniqueName + "' in object '" + Name + "' was marked as animated, but had only one texture.");
return;
}
// Build the new materials and animation properties for this material
List<Material> curAnimationMaterials;
ExpandAnimatedMaterialAndAddAnimationProperties(material, ref expandedMaterials, out curAnimationMaterials);
// Add the additional geometry for the new frames
AddGeometryForExpandedMaterialFrames(curAnimationMaterials, ref meshData);
}
// If static, build single-frame animation properties
else
{
// Make a 'blank' animation for this material/texture, since it's static
ModelTextureTransparencySequenceSetByMaterialIndex[Convert.ToInt32(material.Index)] = new ObjectModelTrackSequences<Fixed16>();
ModelTextureTransparencySequenceSetByMaterialIndex[Convert.ToInt32(material.Index)].AddSequence();
ModelTextureTransparencySequenceSetByMaterialIndex[Convert.ToInt32(material.Index)].AddValueToSequence(0, 0, new Fixed16(material.GetTransparencyValue()));
ModelTextureTransparencyLookups.Add(Convert.ToUInt16(ModelTextureTransparencyLookups.Count));
}
}
// Generate a model material per material
Int16 curIndex = 0;
foreach (Material material in expandedMaterials)
{
if (material.TextureNames.Count > 0)
{
ObjectModelMaterial newModelMaterial;
if (Properties.AlphaBlendMaterialsByName.Contains(material.Name))
{
newModelMaterial = new ObjectModelMaterial(material, ObjectModelMaterialBlendType.Alpha);
}
else
{
switch (material.MaterialType)
{
case MaterialType.TransparentAdditive:
case MaterialType.TransparentAdditiveUnlit:
case MaterialType.TransparentAdditiveUnlitSkydome:
{
newModelMaterial = new ObjectModelMaterial(material, ObjectModelMaterialBlendType.Add);
}
break;
case MaterialType.Transparent25Percent:
case MaterialType.Transparent75Percent:
case MaterialType.Transparent50Percent:
case MaterialType.TransparentMasked:
{
newModelMaterial = new ObjectModelMaterial(material, ObjectModelMaterialBlendType.Alpha_Key);
}
break;
default:
{
newModelMaterial = new ObjectModelMaterial(material, ObjectModelMaterialBlendType.Opaque);
}
break;
}
}
ModelMaterials.Add(newModelMaterial);
ModelTextureAnimationLookup.Add(-1);
ModelTextureLookups.Add(curIndex);
ModelTextureMappingLookups.Add(curIndex);
++curIndex;
}
}
// Perform color tinting if this was a creature and had colors set
if (Properties.CreatureModelTemplate != null && Properties.CreatureModelTemplate.ColorTint != null)
{
CreatureTemplateColorTint colorTint = Properties.CreatureModelTemplate.ColorTint;
// Head
if (colorTint.HelmColor != null)
{
SetMaterialColorByTextureNameFragment("helm", colorTint.ID, (ColorRGBA)colorTint.HelmColor);
SetMaterialColorByTextureNameFragment("chain", colorTint.ID, (ColorRGBA)colorTint.HelmColor);
}
// Chest
if (colorTint.ChestColor != null)
{
SetMaterialColorByTextureNameFragmentAtPosition("ch", 3, colorTint.ID, (ColorRGBA)colorTint.ChestColor);
SetMaterialColorByTextureNameFragment("clk", colorTint.ID, (ColorRGBA)colorTint.ChestColor);
}
// Arms
if (colorTint.ArmsColor != null)
SetMaterialColorByTextureNameFragmentAtPosition("ua", 3, colorTint.ID, (ColorRGBA)colorTint.ArmsColor);
// Bracer
if (colorTint.BracerColor != null)
SetMaterialColorByTextureNameFragmentAtPosition("fa", 3, colorTint.ID, (ColorRGBA)colorTint.BracerColor);
// Hands
if (colorTint.HandsColor != null)
SetMaterialColorByTextureNameFragmentAtPosition("hn", 3, colorTint.ID, (ColorRGBA)colorTint.HandsColor);
// Legs
if (colorTint.LegsColor != null)
SetMaterialColorByTextureNameFragmentAtPosition("lg", 3, colorTint.ID, (ColorRGBA)colorTint.LegsColor);
// Feet
if (colorTint.FeetColor != null)
SetMaterialColorByTextureNameFragmentAtPosition("ft", 3, colorTint.ID, (ColorRGBA)colorTint.FeetColor);
}
// Generate model textures
foreach(ObjectModelMaterial modelMaterial in ModelMaterials)
{
ObjectModelTexture newModelTexture = new ObjectModelTexture();
newModelTexture.TextureName = modelMaterial.Material.TextureNames[0];
if (modelMaterial.Material.IsParticleEffect == true)
newModelTexture.WrapType = ObjectModelTextureWrapType.None;
ModelTextures.Add(newModelTexture);
}
}
private void SetMaterialColorByTextureNameFragment(string textureNameFragmentToMatch, int colorID, ColorRGBA color)
{
string inputTextureFolder = Path.Combine(Configuration.PATH_EQEXPORTSCONDITIONED_FOLDER, "characters", "Textures");
string workingTextureFolder = Path.Combine(Configuration.PATH_EXPORT_FOLDER, "GeneratedCreatureTextures");
foreach (ObjectModelMaterial objectModelMaterial in ModelMaterials)
{
if (objectModelMaterial.Material.TextureNames.Count > 0 &&
objectModelMaterial.Material.TextureNames[0].Contains(textureNameFragmentToMatch) == true)
{
string newTextureName = objectModelMaterial.Material.TextureNames[0] + "_c" + colorID;
ImageTool.GenerateColoredTintedTexture(inputTextureFolder, objectModelMaterial.Material.TextureNames[0],
workingTextureFolder, newTextureName, color, ImageTool.ImageAssociationType.Creature, true);
objectModelMaterial.Material.TextureNames[0] = newTextureName;
if (GeneratedTextureNames.Contains(newTextureName) == false)
GeneratedTextureNames.Add(newTextureName);
}
}
}
private void SetMaterialColorByTextureNameFragmentAtPosition(string textureNameFragmentToMatch, int positionOffset, int colorID, ColorRGBA color)
{
string inputTextureFolder = Path.Combine(Configuration.PATH_EQEXPORTSCONDITIONED_FOLDER, "characters", "Textures");
string workingTextureFolder = Path.Combine(Configuration.PATH_EXPORT_FOLDER, "GeneratedCreatureTextures");
foreach (ObjectModelMaterial objectModelMaterial in ModelMaterials)
{
if (objectModelMaterial.Material.TextureNames.Count > 0 &&
objectModelMaterial.Material.TextureNames[0].Length >= (textureNameFragmentToMatch.Length + positionOffset) &&
objectModelMaterial.Material.TextureNames[0].Substring(positionOffset, textureNameFragmentToMatch.Length) == textureNameFragmentToMatch)
{
string newTextureName = objectModelMaterial.Material.TextureNames[0] + "_c" + colorID;
string inputTexturePath = Path.Combine(Configuration.PATH_EQEXPORTSCONDITIONED_FOLDER, "characters", "Textures");
ImageTool.GenerateColoredTintedTexture(inputTextureFolder, objectModelMaterial.Material.TextureNames[0],
workingTextureFolder, newTextureName, color, ImageTool.ImageAssociationType.Creature, true);
objectModelMaterial.Material.TextureNames[0] = newTextureName;
if (GeneratedTextureNames.Contains(newTextureName) == false)
GeneratedTextureNames.Add(newTextureName);
}
}
}
private void ApplyCustomCollision(ObjectModelCustomCollisionType customCollisionType, ref List<Vector3> collisionVertices, ref List<TriangleFace> collisionTriangleFaces)
{
switch (customCollisionType)
{
case ObjectModelCustomCollisionType.Ladder:
{
// Determine the boundary box
BoundingBox workingBoundingBox = BoundingBox.GenerateBoxFromVectors(collisionVertices, 0.01f);
// Control for world scaling
float extendDistance = Configuration.OBJECT_STATIC_LADDER_EXTEND_DISTANCE * Configuration.GENERATE_WORLD_SCALE;
float stepDistance = Configuration.OBJECT_STATIC_LADDER_STEP_DISTANCE * Configuration.GENERATE_WORLD_SCALE;
// Purge the existing collision data
collisionVertices.Clear();
collisionTriangleFaces.Clear();
// Build steps, extending outword from the longer side
float stepHighX = workingBoundingBox.TopCorner.X + extendDistance;
float stepMidX = workingBoundingBox.TopCorner.X - (workingBoundingBox.GetXDistance() * 0.5f);
float stepLowX = workingBoundingBox.BottomCorner.X - extendDistance;
float stepHighY = workingBoundingBox.TopCorner.Y;
float stepMidY = workingBoundingBox.TopCorner.Y - (workingBoundingBox.GetYDistance() * 0.5f);
float stepLowY = workingBoundingBox.BottomCorner.Y;
// Build 'steps' by adding collision quads angled away from the center jutting out the longer sides (makes an upside-down V shape)
for (float curZ = workingBoundingBox.BottomCorner.Z; curZ <= workingBoundingBox.TopCorner.Z; curZ += stepDistance)
{
// 2-step Angle (splits from the middle, angles down and away)
int stepStartVert = collisionVertices.Count;
collisionVertices.Add(new Vector3(stepMidX, stepHighY, curZ));
collisionVertices.Add(new Vector3(stepMidX, stepLowY, curZ));
collisionVertices.Add(new Vector3(stepLowX, stepLowY, curZ - (stepDistance * 3)));
collisionVertices.Add(new Vector3(stepLowX, stepHighY, curZ - (stepDistance * 3)));
collisionTriangleFaces.Add(new TriangleFace(0, stepStartVert + 1, stepStartVert, stepStartVert + 3));
collisionTriangleFaces.Add(new TriangleFace(0, stepStartVert + 1, stepStartVert + 3, stepStartVert + 2));
stepStartVert = collisionVertices.Count;
collisionVertices.Add(new Vector3(stepHighX, stepHighY, curZ - (stepDistance * 3)));
collisionVertices.Add(new Vector3(stepHighX, stepLowY, curZ - (stepDistance * 3)));
collisionVertices.Add(new Vector3(stepMidX, stepLowY, curZ));
collisionVertices.Add(new Vector3(stepMidX, stepHighY, curZ));
collisionTriangleFaces.Add(new TriangleFace(0, stepStartVert + 1, stepStartVert, stepStartVert + 3));
collisionTriangleFaces.Add(new TriangleFace(0, stepStartVert + 1, stepStartVert + 3, stepStartVert + 2));
}
// Add collision walls on the sides
float highX = workingBoundingBox.TopCorner.X;
float lowX = workingBoundingBox.BottomCorner.X;
float highY = workingBoundingBox.TopCorner.Y;
float lowY = workingBoundingBox.BottomCorner.Y;
float highZ = workingBoundingBox.TopCorner.Z;
float lowZ = workingBoundingBox.BottomCorner.Z;
// Reduce size of short sides to make you step more 'inside' the ladder
highX -= workingBoundingBox.GetXDistance() * 0.2f;
lowX += workingBoundingBox.GetXDistance() * 0.2f;
// Side 1 (side)
int wallStartVert = collisionVertices.Count;
collisionVertices.Add(new Vector3(highX, lowY, highZ));
collisionVertices.Add(new Vector3(highX, lowY, lowZ));
collisionVertices.Add(new Vector3(lowX, lowY, lowZ));
collisionVertices.Add(new Vector3(lowX, lowY, highZ));
collisionTriangleFaces.Add(new TriangleFace(0, wallStartVert + 1, wallStartVert, wallStartVert + 3));
collisionTriangleFaces.Add(new TriangleFace(0, wallStartVert + 1, wallStartVert + 3, wallStartVert + 2));
// Side 2 (side)
wallStartVert = collisionVertices.Count;
collisionVertices.Add(new Vector3(highX, highY, highZ));
collisionVertices.Add(new Vector3(lowX, highY, highZ));
collisionVertices.Add(new Vector3(lowX, highY, lowZ));
collisionVertices.Add(new Vector3(highX, highY, lowZ));
collisionTriangleFaces.Add(new TriangleFace(0, wallStartVert + 1, wallStartVert, wallStartVert + 3));
collisionTriangleFaces.Add(new TriangleFace(0, wallStartVert + 1, wallStartVert + 3, wallStartVert + 2));
// Side 3
wallStartVert = collisionVertices.Count;
collisionVertices.Add(new Vector3(highX, highY, highZ));
collisionVertices.Add(new Vector3(highX, highY, lowZ));
collisionVertices.Add(new Vector3(highX, lowY, lowZ));
collisionVertices.Add(new Vector3(highX, lowY, highZ));
collisionTriangleFaces.Add(new TriangleFace(0, wallStartVert + 1, wallStartVert, wallStartVert + 3));
collisionTriangleFaces.Add(new TriangleFace(0, wallStartVert + 1, wallStartVert + 3, wallStartVert + 2));
// Side 4
wallStartVert = collisionVertices.Count;
collisionVertices.Add(new Vector3(lowX, highY, highZ));
collisionVertices.Add(new Vector3(lowX, lowY, highZ));
collisionVertices.Add(new Vector3(lowX, lowY, lowZ));
collisionVertices.Add(new Vector3(lowX, highY, lowZ));
collisionTriangleFaces.Add(new TriangleFace(0, wallStartVert + 1, wallStartVert, wallStartVert + 3));
collisionTriangleFaces.Add(new TriangleFace(0, wallStartVert + 1, wallStartVert + 3, wallStartVert + 2));
}
break;
default:
{
Logger.WriteError("ApplyCustomCollision has unhandled custom collision type of '" + customCollisionType + "'");
}
break;
}
}
public void CorrectTextureCoordinates()
{
HashSet<int> textureCoordRemappedVertexIndices = new HashSet<int>();
foreach (TriangleFace triangleFace in ModelTriangles)
{
if (triangleFace.MaterialIndex < ModelMaterials.Count)
{
if (textureCoordRemappedVertexIndices.Contains(triangleFace.V1) == false)
{
TextureCoordinates correctedCoordinates = ModelMaterials[triangleFace.MaterialIndex].Material.GetCorrectedBaseCoordinates(ModelVertices[triangleFace.V1].Texture1TextureCoordinates);
ModelVertices[triangleFace.V1].Texture1TextureCoordinates.X = correctedCoordinates.X;
ModelVertices[triangleFace.V1].Texture1TextureCoordinates.Y = correctedCoordinates.Y;
textureCoordRemappedVertexIndices.Add(triangleFace.V1);
}
if (textureCoordRemappedVertexIndices.Contains(triangleFace.V2) == false)
{
TextureCoordinates correctedCoordinates = ModelMaterials[triangleFace.MaterialIndex].Material.GetCorrectedBaseCoordinates(ModelVertices[triangleFace.V2].Texture1TextureCoordinates);
ModelVertices[triangleFace.V2].Texture1TextureCoordinates.X = correctedCoordinates.X;
ModelVertices[triangleFace.V2].Texture1TextureCoordinates.Y = correctedCoordinates.Y;
textureCoordRemappedVertexIndices.Add(triangleFace.V2);
}
if (textureCoordRemappedVertexIndices.Contains(triangleFace.V3) == false)
{
TextureCoordinates correctedCoordinates = ModelMaterials[triangleFace.MaterialIndex].Material.GetCorrectedBaseCoordinates(ModelVertices[triangleFace.V3].Texture1TextureCoordinates);
ModelVertices[triangleFace.V3].Texture1TextureCoordinates.X = correctedCoordinates.X;
ModelVertices[triangleFace.V3].Texture1TextureCoordinates.Y = correctedCoordinates.Y;
textureCoordRemappedVertexIndices.Add(triangleFace.V3);
}
}
}
}
private MeshData GenerateCollisionMeshDataForSkeletalModel(MeshData baseMeshData)
{
if (IsSkeletal == false)
{
Logger.WriteError("GenerateMeshDataForSkeletalModel failed as object '" + Name + "' was not skeletal");
return baseMeshData;
}
// Mesh data returned by this will be the first frame of a standing animation
MeshData collisionMeshData = new MeshData(baseMeshData);
for (int i = 0; i < collisionMeshData.Vertices.Count; i++)
{
// Add 1 to the bone ID since there would have been an added bone
int boneID = collisionMeshData.BoneIDs[i] + 1;
// Only process if there was an animation frame here
if (ModelBones[boneID].TranslationTrack.Values.Count > 0 && ModelBones[boneID].TranslationTrack.Values[0].Values.Count > 0)
{
Vector3 frame1Translation = ModelBones[boneID].TranslationTrack.Values[0].Values[0];
collisionMeshData.Vertices[i] = collisionMeshData.Vertices[i] + frame1Translation;
}
}
return collisionMeshData;
}
private void ProcessCollisionData(MeshData meshData, List<Material> materials, List<Vector3> collisionVertices, List<TriangleFace> collisionTriangleFaces)
{
// Skip collision for particles and projectiles
if (ModelType == ObjectModelType.ParticleEmitter || ModelType == ObjectModelType.SpellProjectile)
return;
// Generate collision data if there is none and it's from an EQ object
if (collisionVertices.Count == 0 && Properties.DoGenerateCollisionFromMeshData == true &&
(ModelType != ObjectModelType.ZoneModel && ModelType != ObjectModelType.SoundInstance && ModelType != ObjectModelType.EquipmentHeld))
{
// Skeletal objects need specially generated mesh data utilizing the animation positioning
MeshData workingMeshData;
if (IsSkeletal == true && meshData.AnimatedVertexFramesByVertexIndex.Count == 0)
workingMeshData = GenerateCollisionMeshDataForSkeletalModel(meshData);
else
workingMeshData = meshData;
// Take any non-transparent material geometry and use that to build a mesh
Dictionary<UInt32, Material> foundMaterials = new Dictionary<UInt32, Material>();
foreach (TriangleFace face in workingMeshData.TriangleFaces)
{
Material curMaterial = new Material();
bool materialFound = false;
foreach (Material material in materials)
{
if (face.MaterialIndex == material.Index)
{
curMaterial = material;
materialFound = true;
break;
}
}
if (materialFound == false)
{
Logger.WriteDebug("Attempted to build collision data for object '" + Name + "', but could not find material with ID '" + face.MaterialIndex + "'");
continue;
}
if (curMaterial.HasTransparency() == true)
continue;
if (foundMaterials.ContainsKey(curMaterial.Index) == true)
continue;
foundMaterials.Add(curMaterial.Index, curMaterial);
}
// Build the collision data
if (foundMaterials.Count > 0)
{
MeshData collisionMesh = workingMeshData.GetMeshDataForMaterials(foundMaterials.Values.ToList().ToArray());
// Store the indices of valid verts, to avoid marking animated verts as collidable
HashSet<int> collidableVerts = new HashSet<int>();
for (int i = 0; i < collisionMesh.Vertices.Count; i++)
{
if (collisionMesh.AnimatedVertexFramesByVertexIndex.Count == 0)
collidableVerts.Add(i);
else if (collisionMesh.AnimatedVertexFramesByVertexIndex[i].VertexOffsetFrames.Count == 0)
collidableVerts.Add(i);
}
// Recompact the mesh data if there was a restricted vert set
if (collidableVerts.Count < collisionMesh.Vertices.Count)
{
List<TriangleFace> validCollisionFaces = new List<TriangleFace>();
foreach (TriangleFace face in collisionMesh.TriangleFaces)
{
if (collidableVerts.Contains(face.V1) && collidableVerts.Contains(face.V2) && collidableVerts.Contains(face.V3))
validCollisionFaces.Add(face);
}
collisionMesh = collisionMesh.GetMeshDataForFaces(validCollisionFaces);
}
// Pull the mesh data
foreach (TriangleFace face in collisionMesh.TriangleFaces)
collisionTriangleFaces.Add(new TriangleFace(face));
foreach (Vector3 position in collisionMesh.Vertices)
collisionVertices.Add(new Vector3(position));
}
}
// Apply any custom collision data
if (Properties.CustomCollisionType != ObjectModelCustomCollisionType.None)
ApplyCustomCollision(Properties.CustomCollisionType, ref collisionVertices, ref collisionTriangleFaces);
// Store data on the object
CollisionPositions = new List<Vector3>(collisionVertices);
CollisionTriangles = new List<TriangleFace>(collisionTriangleFaces);
// Calculate normals using the triangles provided
foreach (TriangleFace collisionTriangle in CollisionTriangles)
{
// Grab related vertices
Vector3 vertex1 = CollisionPositions[collisionTriangle.V1];
Vector3 vertex2 = CollisionPositions[collisionTriangle.V2];
Vector3 vertex3 = CollisionPositions[collisionTriangle.V3];
// Calculate two edges
Vector3 edge1 = vertex2 - vertex1;
Vector3 edge2 = vertex3 - vertex1;
// Cross product determines the vector, then normalize (using C# libraries to save coding time)
System.Numerics.Vector3 edge1System = new System.Numerics.Vector3(edge1.X, edge1.Y, edge1.Z);
System.Numerics.Vector3 edge2System = new System.Numerics.Vector3(edge2.X, edge2.Y, edge2.Z);
System.Numerics.Vector3 normalSystem = System.Numerics.Vector3.Cross(edge1System, edge2System);
System.Numerics.Vector3 normalizedNormalSystem = System.Numerics.Vector3.Normalize(normalSystem);
// Remove NaNs
if (float.IsNaN(normalizedNormalSystem.X))
normalizedNormalSystem.X = 0;
if (float.IsNaN(normalizedNormalSystem.Y))
normalizedNormalSystem.Y = 0;
if (float.IsNaN(normalizedNormalSystem.Z))
normalizedNormalSystem.Z = 0;
// Invert the normal due to winding order difference
Vector3 normal = new Vector3(normalizedNormalSystem.X, normalizedNormalSystem.Y, normalizedNormalSystem.Z);
CollisionFaceNormals.Add(normal);
}
// Generate collision bounding box
CollisionBoundingBox = BoundingBox.GenerateBoxFromVectors(CollisionPositions, Configuration.GENERATE_ADDED_BOUNDARY_AMOUNT);
CollisionSphereRaidus = CollisionBoundingBox.FurthestPointDistanceFromCenter();
}
private void ExpandAnimatedMaterialAndAddAnimationProperties(Material initialMaterial, ref List<Material> expandedMaterials,
out List<Material> curAnimationMaterials)
{
// Create a unique material and animation frame for every material
curAnimationMaterials = new List<Material>();
UInt32 curAnimationTimestamp = 0;
for (int textureIter = 0; textureIter < initialMaterial.TextureNames.Count; ++textureIter)
{
// Update the material values if it's the first in the chain, otherwise create a new one
string curMaterialName = initialMaterial.UniqueName + "Anim_" + textureIter;
Material curMaterial;
int curMaterialIndex;
if (textureIter == 0)
{
initialMaterial.UniqueName = curMaterialName;
curMaterial = initialMaterial;
curMaterialIndex = Convert.ToInt32(initialMaterial.Index);
}
else
{
UInt32 newMaterialIndex = GetUniqueMaterialIDFromMaterials(expandedMaterials);
List<string> newMaterialTextureName = new List<string>() { initialMaterial.TextureNames[textureIter] };
Material newAnimationMaterial = new Material(curMaterialName, initialMaterial.UniqueName, newMaterialIndex, initialMaterial.MaterialType,
newMaterialTextureName, initialMaterial.AnimationDelayMs, initialMaterial.TextureWidth, initialMaterial.TextureHeight, initialMaterial.AlwaysBrightOverride);
curMaterial = newAnimationMaterial;
expandedMaterials.Add(curMaterial);
curMaterialIndex = Convert.ToInt32(newMaterialIndex);
}
// Create the new transparency animation for this frame
ObjectModelTrackSequences<Fixed16> newAnimation = new ObjectModelTrackSequences<Fixed16>();
newAnimation.InterpolationType = ObjectModelAnimationInterpolationType.None;
newAnimation.GlobalSequenceID = Convert.ToUInt16(GlobalLoopSequenceLimits.Count);
int curSequenceId = newAnimation.AddSequence();
// Add a blank (transparent) frame to this animation for every frame that already exists, and add a blank to those others
for (int i = 0; i < curAnimationMaterials.Count; ++i)
{
newAnimation.AddValueToSequence(0, Convert.ToUInt32(i) * initialMaterial.AnimationDelayMs, new Fixed16(0));
ModelTextureTransparencySequenceSetByMaterialIndex[Convert.ToInt32(curAnimationMaterials[i].Index)].AddValueToSequence(0, curAnimationTimestamp, new Fixed16(0));
}
// Add this shown (non-transparent) frame
newAnimation.AddValueToSequence(0, curAnimationTimestamp, new Fixed16(curMaterial.GetTransparencyValue()));
// Add this animation and the texture lookup, which should match current count
ModelTextureTransparencySequenceSetByMaterialIndex[curMaterialIndex] = newAnimation;
ModelTextureTransparencyLookups.Add(Convert.ToUInt16(ModelTextureTransparencyLookups.Count));
curAnimationTimestamp += initialMaterial.AnimationDelayMs;
curAnimationMaterials.Add(curMaterial);
}
// Reduce the texture list for the first material to one
curAnimationMaterials[0].TextureNames = new List<string>() { initialMaterial.TextureNames[0] };
// Save this global sequence so that it loops
GlobalLoopSequenceLimits.Add(Convert.ToUInt32(curAnimationMaterials.Count) * initialMaterial.AnimationDelayMs);
}
private void AddGeometryForExpandedMaterialFrames(List<Material> frameMaterials, ref MeshData meshData)
{
for (int i = 1; i < frameMaterials.Count; i++)
{
// Create new triangles
List<TriangleFace> newTriangleFaces = new List<TriangleFace>();
// Determine what the min vertex index is for the triangles, as well as capture the reference indices for vertex copies
int minSourceTriangleVertexIndex = -1;
int maxSourceTriangleVertexIndex = -1;
foreach (TriangleFace triangleFace in meshData.TriangleFaces)
{
if (triangleFace.MaterialIndex != frameMaterials[0].Index)
continue;
// Store the vertex offsets to be used in the next section
if (minSourceTriangleVertexIndex == -1 || triangleFace.GetSmallestIndex() < minSourceTriangleVertexIndex)
minSourceTriangleVertexIndex = triangleFace.GetSmallestIndex();
if (maxSourceTriangleVertexIndex == -1 || triangleFace.GetLargestIndex() > maxSourceTriangleVertexIndex)
maxSourceTriangleVertexIndex = triangleFace.GetLargestIndex();
}
if (minSourceTriangleVertexIndex == -1)
{
Logger.WriteError("Could not find any triangle face vertices for material '" + frameMaterials[0].UniqueName + "' in object '" + Name + "'");
continue;
}
// Create new triangles using the min identified earlier
int newVertexIndexStartOffsetAdd = meshData.Vertices.Count - minSourceTriangleVertexIndex;
foreach (TriangleFace triangleFace in meshData.TriangleFaces)
{
if (triangleFace.MaterialIndex != frameMaterials[0].Index)
continue;
TriangleFace newTriangleFace = new TriangleFace(triangleFace);
newTriangleFace.V1 += newVertexIndexStartOffsetAdd;
newTriangleFace.V2 += newVertexIndexStartOffsetAdd;
newTriangleFace.V3 += newVertexIndexStartOffsetAdd;
newTriangleFace.MaterialIndex = Convert.ToInt32(frameMaterials[i].Index);
newTriangleFaces.Add(newTriangleFace);
}
foreach (TriangleFace triangleFace in newTriangleFaces)
meshData.TriangleFaces.Add(triangleFace);
// Create new geometry data
for (int vi = minSourceTriangleVertexIndex; vi <= maxSourceTriangleVertexIndex; ++vi)
{
meshData.Vertices.Add(new Vector3(meshData.Vertices[vi]));
meshData.Normals.Add(new Vector3(meshData.Normals[vi]));
meshData.TextureCoordinates.Add(new TextureCoordinates(meshData.TextureCoordinates[vi]));
if (meshData.BoneIDs.Count > 0)
meshData.BoneIDs.Add(meshData.BoneIDs[vi]);
if (meshData.VertexColors.Count > 0)
meshData.VertexColors.Add(new ColorRGBA(meshData.VertexColors[vi]));
}
}
}
private UInt32 GetUniqueMaterialIDFromMaterials(List<Material> materials)
{
UInt32 highestExistingID = 0;
foreach (Material material in materials)
if (material.Index > highestExistingID)
highestExistingID = material.Index;
return highestExistingID + 1;
}
}
}
| 0 | 0.911938 | 1 | 0.911938 | game-dev | MEDIA | 0.458895 | game-dev | 0.956486 | 1 | 0.956486 |
magefree/mage | 5,073 | Mage.Sets/src/mage/cards/b/BaneLordOfDarkness.java | package mage.cards.b;
import mage.MageInt;
import mage.abilities.Ability;
import mage.abilities.common.DiesCreatureTriggeredAbility;
import mage.abilities.common.SimpleStaticAbility;
import mage.abilities.condition.Condition;
import mage.abilities.decorator.ConditionalContinuousEffect;
import mage.abilities.effects.OneShotEffect;
import mage.abilities.effects.common.PutCardFromHandOntoBattlefieldEffect;
import mage.abilities.effects.common.continuous.GainAbilitySourceEffect;
import mage.abilities.keyword.IndestructibleAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.*;
import mage.filter.FilterCard;
import mage.filter.FilterPermanent;
import mage.filter.common.FilterControlledCreaturePermanent;
import mage.filter.common.FilterCreatureCard;
import mage.filter.predicate.mageobject.AnotherPredicate;
import mage.filter.predicate.mageobject.ToughnessPredicate;
import mage.filter.predicate.permanent.TokenPredicate;
import mage.game.Game;
import mage.game.permanent.Permanent;
import mage.players.Player;
import mage.target.common.TargetOpponent;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
/**
* @author TheElk801
*/
public final class BaneLordOfDarkness extends CardImpl {
private static final FilterPermanent filter
= new FilterControlledCreaturePermanent("another nontoken creature you control");
static {
filter.add(AnotherPredicate.instance);
filter.add(TokenPredicate.FALSE);
}
public BaneLordOfDarkness(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{1}{W}{U}{B}");
this.supertype.add(SuperType.LEGENDARY);
this.subtype.add(SubType.GOD);
this.power = new MageInt(5);
this.toughness = new MageInt(2);
// As long as your life total is less than or equal to half your starting life total, Bane, Lord of Darkness has indestructible.
this.addAbility(new SimpleStaticAbility(new ConditionalContinuousEffect(
new GainAbilitySourceEffect(
IndestructibleAbility.getInstance(), Duration.WhileOnBattlefield
), BaneLordOfDarknessCondition.instance, "as long as your life total is less than or equal " +
"to half your starting life total, {this} has indestructible"
)));
// Whenever another nontoken creature you control dies, target opponent may have you draw a card. If they don't, you may put a creature card with equal or lesser toughness from your hand onto the battlefield.
Ability ability = new DiesCreatureTriggeredAbility(new BaneLordOfDarknessEffect(), false, filter);
ability.addTarget(new TargetOpponent());
this.addAbility(ability);
}
private BaneLordOfDarkness(final BaneLordOfDarkness card) {
super(card);
}
@Override
public BaneLordOfDarkness copy() {
return new BaneLordOfDarkness(this);
}
}
enum BaneLordOfDarknessCondition implements Condition {
instance;
@Override
public boolean apply(Game game, Ability source) {
return Optional
.ofNullable(game.getPlayer(source.getControllerId()))
.map(Player::getLife)
.map(x -> 2 * x <= game.getStartingLife())
.orElse(false);
}
}
class BaneLordOfDarknessEffect extends OneShotEffect {
BaneLordOfDarknessEffect() {
super(Outcome.Benefit);
staticText = "target opponent may have you draw a card. If they don't, " +
"you may put a creature card with equal or lesser toughness from your hand onto the battlefield";
}
private BaneLordOfDarknessEffect(final BaneLordOfDarknessEffect effect) {
super(effect);
}
@Override
public BaneLordOfDarknessEffect copy() {
return new BaneLordOfDarknessEffect(this);
}
@Override
public boolean apply(Game game, Ability source) {
Player controller = game.getPlayer(source.getControllerId());
Player opponent = game.getPlayer(getTargetPointer().getFirst(game, source));
if (controller == null || opponent == null) {
return false;
}
if (opponent.chooseUse(
outcome, "Have " + controller.getName() + " draw a card or put a creature into play?",
null, "Draw card", "Play creature", source, game
)) {
return controller.drawCards(1, source, game) > 0;
}
Permanent permanent = (Permanent) getValue("creatureDied");
if (permanent == null) {
return false;
}
FilterCard filter = new FilterCreatureCard(
"creature card with " + permanent.getToughness().getValue() + " or less toughness"
);
filter.add(new ToughnessPredicate(ComparisonType.FEWER_THAN, permanent.getToughness().getValue() + 1));
return new PutCardFromHandOntoBattlefieldEffect(filter).apply(game, source);
}
}
// nobody cared who I was until I put on the mask
| 0 | 0.978988 | 1 | 0.978988 | game-dev | MEDIA | 0.916869 | game-dev | 0.998007 | 1 | 0.998007 |
openclonk/openclonk | 1,171 | planet/Objects.ocd/Clonk.ocd/InteractionMenu.ocd/Script.c | /* --- OC specific interaction menu --- */
// Clonks act as containers for the interaction menu as long as they are alive.
public func IsContainer() { return GetAlive(); }
// You can not interact with dead Clonks.
// This would be the place to show a death message etc.
public func RejectInteractionMenu(object to)
{
if (!GetAlive())
return Format("$MsgDeadClonk$", GetName());
return _inherited(to, ...);
}
// You can not display the Clonk as a content entry in a building.
// Otherwise you can transfer a crew member to your inventory...
public func RejectInteractionMenuContentEntry(object menu_target, object container)
{
return true;
}
public func GetSurroundingEntryMessage(object for_clonk)
{
if (!GetAlive()) return Format("{{Clonk_Grave}} %s", Clonk_Grave->GetInscriptionForClonk(this));
}
/* Enable the Clonk to pick up stuff from its surrounding in the interaction menu */
public func OnInteractionMenuOpen(object menu)
{
_inherited(menu, ...);
// Allow picking up stuff from the surrounding only if not in a container itself.
if (!Contained())
{
var surrounding = CreateObject(Helper_Surrounding);
surrounding->InitFor(this, menu);
}
}
| 0 | 0.859053 | 1 | 0.859053 | game-dev | MEDIA | 0.831159 | game-dev | 0.644815 | 1 | 0.644815 |
liuhaopen/Navigator | 7,498 | recastnavigation/DetourCrowd/Include/DetourPathCorridor.h | //
// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
#ifndef DETOUTPATHCORRIDOR_H
#define DETOUTPATHCORRIDOR_H
#include "DetourNavMeshQuery.h"
/// Represents a dynamic polygon corridor used to plan agent movement.
/// @ingroup crowd, detour
class dtPathCorridor
{
float m_pos[3];
float m_target[3];
dtPolyRef* m_path;
int m_npath;
int m_maxPath;
public:
dtPathCorridor();
~dtPathCorridor();
/// Allocates the corridor's path buffer.
/// @param[in] maxPath The maximum path size the corridor can handle.
/// @return True if the initialization succeeded.
bool init(const int maxPath);
/// Resets the path corridor to the specified position.
/// @param[in] ref The polygon reference containing the position.
/// @param[in] pos The new position in the corridor. [(x, y, z)]
void reset(dtPolyRef ref, const float* pos);
/// Finds the corners in the corridor from the position toward the target. (The straightened path.)
/// @param[out] cornerVerts The corner vertices. [(x, y, z) * cornerCount] [Size: <= maxCorners]
/// @param[out] cornerFlags The flag for each corner. [(flag) * cornerCount] [Size: <= maxCorners]
/// @param[out] cornerPolys The polygon reference for each corner. [(polyRef) * cornerCount]
/// [Size: <= @p maxCorners]
/// @param[in] maxCorners The maximum number of corners the buffers can hold.
/// @param[in] navquery The query object used to build the corridor.
/// @param[in] filter The filter to apply to the operation.
/// @return The number of corners returned in the corner buffers. [0 <= value <= @p maxCorners]
int findCorners(float* cornerVerts, unsigned char* cornerFlags,
dtPolyRef* cornerPolys, const int maxCorners,
dtNavMeshQuery* navquery, const dtQueryFilter* filter);
/// Attempts to optimize the path if the specified point is visible from the current position.
/// @param[in] next The point to search toward. [(x, y, z])
/// @param[in] pathOptimizationRange The maximum range to search. [Limit: > 0]
/// @param[in] navquery The query object used to build the corridor.
/// @param[in] filter The filter to apply to the operation.
void optimizePathVisibility(const float* next, const float pathOptimizationRange,
dtNavMeshQuery* navquery, const dtQueryFilter* filter);
/// Attempts to optimize the path using a local area search. (Partial replanning.)
/// @param[in] navquery The query object used to build the corridor.
/// @param[in] filter The filter to apply to the operation.
bool optimizePathTopology(dtNavMeshQuery* navquery, const dtQueryFilter* filter);
bool moveOverOffmeshConnection(dtPolyRef offMeshConRef, dtPolyRef* refs,
float* startPos, float* endPos,
dtNavMeshQuery* navquery);
bool fixPathStart(dtPolyRef safeRef, const float* safePos);
bool trimInvalidPath(dtPolyRef safeRef, const float* safePos,
dtNavMeshQuery* navquery, const dtQueryFilter* filter);
/// Checks the current corridor path to see if its polygon references remain valid.
/// @param[in] maxLookAhead The number of polygons from the beginning of the corridor to search.
/// @param[in] navquery The query object used to build the corridor.
/// @param[in] filter The filter to apply to the operation.
bool isValid(const int maxLookAhead, dtNavMeshQuery* navquery, const dtQueryFilter* filter);
/// Moves the position from the current location to the desired location, adjusting the corridor
/// as needed to reflect the change.
/// @param[in] npos The desired new position. [(x, y, z)]
/// @param[in] navquery The query object used to build the corridor.
/// @param[in] filter The filter to apply to the operation.
/// @return Returns true if move succeeded.
bool movePosition(const float* npos, dtNavMeshQuery* navquery, const dtQueryFilter* filter);
/// Moves the target from the curent location to the desired location, adjusting the corridor
/// as needed to reflect the change.
/// @param[in] npos The desired new target position. [(x, y, z)]
/// @param[in] navquery The query object used to build the corridor.
/// @param[in] filter The filter to apply to the operation.
/// @return Returns true if move succeeded.
bool moveTargetPosition(const float* npos, dtNavMeshQuery* navquery, const dtQueryFilter* filter);
/// Loads a new path and target into the corridor.
/// @param[in] target The target location within the last polygon of the path. [(x, y, z)]
/// @param[in] path The path corridor. [(polyRef) * @p npolys]
/// @param[in] npath The number of polygons in the path.
void setCorridor(const float* target, const dtPolyRef* polys, const int npath);
/// Gets the current position within the corridor. (In the first polygon.)
/// @return The current position within the corridor.
inline const float* getPos() const { return m_pos; }
/// Gets the current target within the corridor. (In the last polygon.)
/// @return The current target within the corridor.
inline const float* getTarget() const { return m_target; }
/// The polygon reference id of the first polygon in the corridor, the polygon containing the position.
/// @return The polygon reference id of the first polygon in the corridor. (Or zero if there is no path.)
inline dtPolyRef getFirstPoly() const { return m_npath ? m_path[0] : 0; }
/// The polygon reference id of the last polygon in the corridor, the polygon containing the target.
/// @return The polygon reference id of the last polygon in the corridor. (Or zero if there is no path.)
inline dtPolyRef getLastPoly() const { return m_npath ? m_path[m_npath-1] : 0; }
/// The corridor's path.
/// @return The corridor's path. [(polyRef) * #getPathCount()]
inline const dtPolyRef* getPath() const { return m_path; }
/// The number of polygons in the current corridor path.
/// @return The number of polygons in the current corridor path.
inline int getPathCount() const { return m_npath; }
private:
// Explicitly disabled copy constructor and copy assignment operator.
dtPathCorridor(const dtPathCorridor&);
dtPathCorridor& operator=(const dtPathCorridor&);
};
int dtMergeCorridorStartMoved(dtPolyRef* path, const int npath, const int maxPath,
const dtPolyRef* visited, const int nvisited);
int dtMergeCorridorEndMoved(dtPolyRef* path, const int npath, const int maxPath,
const dtPolyRef* visited, const int nvisited);
int dtMergeCorridorStartShortcut(dtPolyRef* path, const int npath, const int maxPath,
const dtPolyRef* visited, const int nvisited);
#endif // DETOUTPATHCORRIDOR_H
| 0 | 0.966153 | 1 | 0.966153 | game-dev | MEDIA | 0.505892 | game-dev | 0.801407 | 1 | 0.801407 |
checkstyle/checkstyle | 1,040 | src/xdocs-examples/resources/com/puppycrawl/tools/checkstyle/checks/annotation/annotationlocation/Example2.java | /*xml
<module name="Checker">
<module name="TreeWalker">
<module name="AnnotationLocation">
<property name="allowSamelineSingleParameterlessAnnotation"
value="false"/>
<property name="allowSamelineParameterizedAnnotation" value="false"/>
<property name="allowSamelineMultipleAnnotations" value="true"/>
</module>
</module>
</module>
*/
package com.puppycrawl.tools.checkstyle.checks.annotation.annotationlocation;
import javax.annotation.Nonnull;
import org.mockito.Mock;
// xdoc section -- start
class Example2 {
@Nonnull
private boolean field1;
@Override public int hashCode() { return 1; } // ok
@Nonnull
private boolean field2;
@Override
public boolean equals(Object obj) { return true; }
@Mock
DataLoader loader1;
@SuppressWarnings("deprecation") DataLoader loader;
@SuppressWarnings("deprecation") public int foo() { return 1; } // ok
@Nonnull @Mock DataLoader loader2;
// ok above as 'allowSamelineMultipleAnnotations' set to true
}
// xdoc section -- end
| 0 | 0.653064 | 1 | 0.653064 | game-dev | MEDIA | 0.165654 | game-dev | 0.506827 | 1 | 0.506827 |
Space-Stories/space-station-14 | 4,057 | Content.Server/Storage/EntitySystems/SpawnItemsOnUseSystem.cs | using Content.Server.Administration.Logs;
using Content.Server.Cargo.Systems;
using Content.Server.Storage.Components;
using Content.Shared.Database;
using Content.Shared.Hands.EntitySystems;
using Content.Shared.Interaction.Events;
using Robust.Shared.Audio;
using Robust.Shared.Audio.Systems;
using Robust.Shared.Map;
using Robust.Shared.Player;
using Robust.Shared.Random;
using static Content.Shared.Storage.EntitySpawnCollection;
namespace Content.Server.Storage.EntitySystems
{
public sealed class SpawnItemsOnUseSystem : EntitySystem
{
[Dependency] private readonly IRobustRandom _random = default!;
[Dependency] private readonly IAdminLogManager _adminLogger = default!;
[Dependency] private readonly SharedHandsSystem _hands = default!;
[Dependency] private readonly PricingSystem _pricing = default!;
[Dependency] private readonly SharedAudioSystem _audio = default!;
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<SpawnItemsOnUseComponent, UseInHandEvent>(OnUseInHand);
SubscribeLocalEvent<SpawnItemsOnUseComponent, PriceCalculationEvent>(CalculatePrice, before: new[] { typeof(PricingSystem) });
}
private void CalculatePrice(EntityUid uid, SpawnItemsOnUseComponent component, ref PriceCalculationEvent args)
{
var ungrouped = CollectOrGroups(component.Items, out var orGroups);
foreach (var entry in ungrouped)
{
var protUid = Spawn(entry.PrototypeId, MapCoordinates.Nullspace);
// Calculate the average price of the possible spawned items
args.Price += _pricing.GetPrice(protUid) * entry.SpawnProbability * entry.GetAmount(getAverage: true);
EntityManager.DeleteEntity(protUid);
}
foreach (var group in orGroups)
{
foreach (var entry in group.Entries)
{
var protUid = Spawn(entry.PrototypeId, MapCoordinates.Nullspace);
// Calculate the average price of the possible spawned items
args.Price += _pricing.GetPrice(protUid) *
(entry.SpawnProbability / group.CumulativeProbability) *
entry.GetAmount(getAverage: true);
EntityManager.DeleteEntity(protUid);
}
}
args.Handled = true;
}
private void OnUseInHand(EntityUid uid, SpawnItemsOnUseComponent component, UseInHandEvent args)
{
if (args.Handled)
return;
// If starting with zero or less uses, this component is a no-op
if (component.Uses <= 0)
return;
var coords = Transform(args.User).Coordinates;
var spawnEntities = GetSpawns(component.Items, _random);
EntityUid? entityToPlaceInHands = null;
foreach (var proto in spawnEntities)
{
entityToPlaceInHands = Spawn(proto, coords);
_adminLogger.Add(LogType.EntitySpawn, LogImpact.Low, $"{ToPrettyString(args.User)} used {ToPrettyString(uid)} which spawned {ToPrettyString(entityToPlaceInHands.Value)}");
}
if (component.Sound != null)
{
// The entity is often deleted, so play the sound at its position rather than parenting
var coordinates = Transform(uid).Coordinates;
_audio.PlayPvs(component.Sound, coordinates);
}
component.Uses--;
// Delete entity only if component was successfully used
if (component.Uses <= 0)
{
args.Handled = true;
EntityManager.DeleteEntity(uid);
}
if (entityToPlaceInHands != null)
{
_hands.PickupOrDrop(args.User, entityToPlaceInHands.Value);
}
}
}
}
| 0 | 0.921645 | 1 | 0.921645 | game-dev | MEDIA | 0.985079 | game-dev | 0.934265 | 1 | 0.934265 |
Tencent/wwsearch | 20,388 | deps/rocksdb/tools/advisor/advisor/rule_parser.py | # Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
# This source code is licensed under both the GPLv2 (found in the
# COPYING file in the root directory) and Apache 2.0 License
# (found in the LICENSE.Apache file in the root directory).
from abc import ABC, abstractmethod
from advisor.db_log_parser import DataSource, NO_COL_FAMILY
from advisor.db_timeseries_parser import TimeSeriesData
from enum import Enum
from advisor.ini_parser import IniParser
import re
class Section(ABC):
def __init__(self, name):
self.name = name
@abstractmethod
def set_parameter(self, key, value):
pass
@abstractmethod
def perform_checks(self):
pass
class Rule(Section):
def __init__(self, name):
super().__init__(name)
self.conditions = None
self.suggestions = None
self.overlap_time_seconds = None
self.trigger_entities = None
self.trigger_column_families = None
def set_parameter(self, key, value):
# If the Rule is associated with a single suggestion/condition, then
# value will be a string and not a list. Hence, convert it to a single
# element list before storing it in self.suggestions or
# self.conditions.
if key == 'conditions':
if isinstance(value, str):
self.conditions = [value]
else:
self.conditions = value
elif key == 'suggestions':
if isinstance(value, str):
self.suggestions = [value]
else:
self.suggestions = value
elif key == 'overlap_time_period':
self.overlap_time_seconds = value
def get_suggestions(self):
return self.suggestions
def perform_checks(self):
if not self.conditions or len(self.conditions) < 1:
raise ValueError(
self.name + ': rule must have at least one condition'
)
if not self.suggestions or len(self.suggestions) < 1:
raise ValueError(
self.name + ': rule must have at least one suggestion'
)
if self.overlap_time_seconds:
if len(self.conditions) != 2:
raise ValueError(
self.name + ": rule must be associated with 2 conditions\
in order to check for a time dependency between them"
)
time_format = '^\d+[s|m|h|d]$'
if (
not
re.match(time_format, self.overlap_time_seconds, re.IGNORECASE)
):
raise ValueError(
self.name + ": overlap_time_seconds format: \d+[s|m|h|d]"
)
else: # convert to seconds
in_seconds = int(self.overlap_time_seconds[:-1])
if self.overlap_time_seconds[-1] == 'm':
in_seconds *= 60
elif self.overlap_time_seconds[-1] == 'h':
in_seconds *= (60 * 60)
elif self.overlap_time_seconds[-1] == 'd':
in_seconds *= (24 * 60 * 60)
self.overlap_time_seconds = in_seconds
def get_overlap_timestamps(self, key1_trigger_epochs, key2_trigger_epochs):
# this method takes in 2 timeseries i.e. timestamps at which the
# rule's 2 TIME_SERIES conditions were triggered and it finds
# (if present) the first pair of timestamps at which the 2 conditions
# were triggered within 'overlap_time_seconds' of each other
key1_lower_bounds = [
epoch - self.overlap_time_seconds
for epoch in key1_trigger_epochs
]
key1_lower_bounds.sort()
key2_trigger_epochs.sort()
trigger_ix = 0
overlap_pair = None
for key1_lb in key1_lower_bounds:
while (
key2_trigger_epochs[trigger_ix] < key1_lb and
trigger_ix < len(key2_trigger_epochs)
):
trigger_ix += 1
if trigger_ix >= len(key2_trigger_epochs):
break
if (
key2_trigger_epochs[trigger_ix] <=
key1_lb + (2 * self.overlap_time_seconds)
):
overlap_pair = (
key2_trigger_epochs[trigger_ix],
key1_lb + self.overlap_time_seconds
)
break
return overlap_pair
def get_trigger_entities(self):
return self.trigger_entities
def get_trigger_column_families(self):
return self.trigger_column_families
def is_triggered(self, conditions_dict, column_families):
if self.overlap_time_seconds:
condition1 = conditions_dict[self.conditions[0]]
condition2 = conditions_dict[self.conditions[1]]
if not (
condition1.get_data_source() is DataSource.Type.TIME_SERIES and
condition2.get_data_source() is DataSource.Type.TIME_SERIES
):
raise ValueError(self.name + ': need 2 timeseries conditions')
map1 = condition1.get_trigger()
map2 = condition2.get_trigger()
if not (map1 and map2):
return False
self.trigger_entities = {}
is_triggered = False
entity_intersection = (
set(map1.keys()).intersection(set(map2.keys()))
)
for entity in entity_intersection:
overlap_timestamps_pair = (
self.get_overlap_timestamps(
list(map1[entity].keys()), list(map2[entity].keys())
)
)
if overlap_timestamps_pair:
self.trigger_entities[entity] = overlap_timestamps_pair
is_triggered = True
if is_triggered:
self.trigger_column_families = set(column_families)
return is_triggered
else:
all_conditions_triggered = True
self.trigger_column_families = set(column_families)
for cond_name in self.conditions:
cond = conditions_dict[cond_name]
if not cond.get_trigger():
all_conditions_triggered = False
break
if (
cond.get_data_source() is DataSource.Type.LOG or
cond.get_data_source() is DataSource.Type.DB_OPTIONS
):
cond_col_fam = set(cond.get_trigger().keys())
if NO_COL_FAMILY in cond_col_fam:
cond_col_fam = set(column_families)
self.trigger_column_families = (
self.trigger_column_families.intersection(cond_col_fam)
)
elif cond.get_data_source() is DataSource.Type.TIME_SERIES:
cond_entities = set(cond.get_trigger().keys())
if self.trigger_entities is None:
self.trigger_entities = cond_entities
else:
self.trigger_entities = (
self.trigger_entities.intersection(cond_entities)
)
if not (self.trigger_entities or self.trigger_column_families):
all_conditions_triggered = False
break
if not all_conditions_triggered: # clean up if rule not triggered
self.trigger_column_families = None
self.trigger_entities = None
return all_conditions_triggered
def __repr__(self):
# Append conditions
rule_string = "Rule: " + self.name + " has conditions:: "
is_first = True
for cond in self.conditions:
if is_first:
rule_string += cond
is_first = False
else:
rule_string += (" AND " + cond)
# Append suggestions
rule_string += "\nsuggestions:: "
is_first = True
for sugg in self.suggestions:
if is_first:
rule_string += sugg
is_first = False
else:
rule_string += (", " + sugg)
if self.trigger_entities:
rule_string += (', entities:: ' + str(self.trigger_entities))
if self.trigger_column_families:
rule_string += (', col_fam:: ' + str(self.trigger_column_families))
# Return constructed string
return rule_string
class Suggestion(Section):
class Action(Enum):
set = 1
increase = 2
decrease = 3
def __init__(self, name):
super().__init__(name)
self.option = None
self.action = None
self.suggested_values = None
self.description = None
def set_parameter(self, key, value):
if key == 'option':
# Note:
# case 1: 'option' is supported by Rocksdb OPTIONS file; in this
# case the option belongs to one of the sections in the config
# file and it's name is prefixed by "<section_type>."
# case 2: 'option' is not supported by Rocksdb OPTIONS file; the
# option is not expected to have the character '.' in its name
self.option = value
elif key == 'action':
if self.option and not value:
raise ValueError(self.name + ': provide action for option')
self.action = self.Action[value]
elif key == 'suggested_values':
if isinstance(value, str):
self.suggested_values = [value]
else:
self.suggested_values = value
elif key == 'description':
self.description = value
def perform_checks(self):
if not self.description:
if not self.option:
raise ValueError(self.name + ': provide option or description')
if not self.action:
raise ValueError(self.name + ': provide action for option')
if self.action is self.Action.set and not self.suggested_values:
raise ValueError(
self.name + ': provide suggested value for option'
)
def __repr__(self):
sugg_string = "Suggestion: " + self.name
if self.description:
sugg_string += (' description : ' + self.description)
else:
sugg_string += (
' option : ' + self.option + ' action : ' + self.action.name
)
if self.suggested_values:
sugg_string += (
' suggested_values : ' + str(self.suggested_values)
)
return sugg_string
class Condition(Section):
def __init__(self, name):
super().__init__(name)
self.data_source = None
self.trigger = None
def perform_checks(self):
if not self.data_source:
raise ValueError(self.name + ': condition not tied to data source')
def set_data_source(self, data_source):
self.data_source = data_source
def get_data_source(self):
return self.data_source
def reset_trigger(self):
self.trigger = None
def set_trigger(self, condition_trigger):
self.trigger = condition_trigger
def get_trigger(self):
return self.trigger
def is_triggered(self):
if self.trigger:
return True
return False
def set_parameter(self, key, value):
# must be defined by the subclass
raise NotImplementedError(self.name + ': provide source for condition')
class LogCondition(Condition):
@classmethod
def create(cls, base_condition):
base_condition.set_data_source(DataSource.Type['LOG'])
base_condition.__class__ = cls
return base_condition
def set_parameter(self, key, value):
if key == 'regex':
self.regex = value
def perform_checks(self):
super().perform_checks()
if not self.regex:
raise ValueError(self.name + ': provide regex for log condition')
def __repr__(self):
log_cond_str = "LogCondition: " + self.name
log_cond_str += (" regex: " + self.regex)
# if self.trigger:
# log_cond_str += (" trigger: " + str(self.trigger))
return log_cond_str
class OptionCondition(Condition):
@classmethod
def create(cls, base_condition):
base_condition.set_data_source(DataSource.Type['DB_OPTIONS'])
base_condition.__class__ = cls
return base_condition
def set_parameter(self, key, value):
if key == 'options':
if isinstance(value, str):
self.options = [value]
else:
self.options = value
elif key == 'evaluate':
self.eval_expr = value
def perform_checks(self):
super().perform_checks()
if not self.options:
raise ValueError(self.name + ': options missing in condition')
if not self.eval_expr:
raise ValueError(self.name + ': expression missing in condition')
def __repr__(self):
opt_cond_str = "OptionCondition: " + self.name
opt_cond_str += (" options: " + str(self.options))
opt_cond_str += (" expression: " + self.eval_expr)
if self.trigger:
opt_cond_str += (" trigger: " + str(self.trigger))
return opt_cond_str
class TimeSeriesCondition(Condition):
@classmethod
def create(cls, base_condition):
base_condition.set_data_source(DataSource.Type['TIME_SERIES'])
base_condition.__class__ = cls
return base_condition
def set_parameter(self, key, value):
if key == 'keys':
if isinstance(value, str):
self.keys = [value]
else:
self.keys = value
elif key == 'behavior':
self.behavior = TimeSeriesData.Behavior[value]
elif key == 'rate_threshold':
self.rate_threshold = float(value)
elif key == 'window_sec':
self.window_sec = int(value)
elif key == 'evaluate':
self.expression = value
elif key == 'aggregation_op':
self.aggregation_op = TimeSeriesData.AggregationOperator[value]
def perform_checks(self):
if not self.keys:
raise ValueError(self.name + ': specify timeseries key')
if not self.behavior:
raise ValueError(self.name + ': specify triggering behavior')
if self.behavior is TimeSeriesData.Behavior.bursty:
if not self.rate_threshold:
raise ValueError(self.name + ': specify rate burst threshold')
if not self.window_sec:
self.window_sec = 300 # default window length is 5 minutes
if len(self.keys) > 1:
raise ValueError(self.name + ': specify only one key')
elif self.behavior is TimeSeriesData.Behavior.evaluate_expression:
if not (self.expression):
raise ValueError(self.name + ': specify evaluation expression')
else:
raise ValueError(self.name + ': trigger behavior not supported')
def __repr__(self):
ts_cond_str = "TimeSeriesCondition: " + self.name
ts_cond_str += (" statistics: " + str(self.keys))
ts_cond_str += (" behavior: " + self.behavior.name)
if self.behavior is TimeSeriesData.Behavior.bursty:
ts_cond_str += (" rate_threshold: " + str(self.rate_threshold))
ts_cond_str += (" window_sec: " + str(self.window_sec))
if self.behavior is TimeSeriesData.Behavior.evaluate_expression:
ts_cond_str += (" expression: " + self.expression)
if hasattr(self, 'aggregation_op'):
ts_cond_str += (" aggregation_op: " + self.aggregation_op.name)
if self.trigger:
ts_cond_str += (" trigger: " + str(self.trigger))
return ts_cond_str
class RulesSpec:
def __init__(self, rules_path):
self.file_path = rules_path
def initialise_fields(self):
self.rules_dict = {}
self.conditions_dict = {}
self.suggestions_dict = {}
def perform_section_checks(self):
for rule in self.rules_dict.values():
rule.perform_checks()
for cond in self.conditions_dict.values():
cond.perform_checks()
for sugg in self.suggestions_dict.values():
sugg.perform_checks()
def load_rules_from_spec(self):
self.initialise_fields()
with open(self.file_path, 'r') as db_rules:
curr_section = None
for line in db_rules:
line = IniParser.remove_trailing_comment(line)
if not line:
continue
element = IniParser.get_element(line)
if element is IniParser.Element.comment:
continue
elif element is not IniParser.Element.key_val:
curr_section = element # it's a new IniParser header
section_name = IniParser.get_section_name(line)
if element is IniParser.Element.rule:
new_rule = Rule(section_name)
self.rules_dict[section_name] = new_rule
elif element is IniParser.Element.cond:
new_cond = Condition(section_name)
self.conditions_dict[section_name] = new_cond
elif element is IniParser.Element.sugg:
new_suggestion = Suggestion(section_name)
self.suggestions_dict[section_name] = new_suggestion
elif element is IniParser.Element.key_val:
key, value = IniParser.get_key_value_pair(line)
if curr_section is IniParser.Element.rule:
new_rule.set_parameter(key, value)
elif curr_section is IniParser.Element.cond:
if key == 'source':
if value == 'LOG':
new_cond = LogCondition.create(new_cond)
elif value == 'OPTIONS':
new_cond = OptionCondition.create(new_cond)
elif value == 'TIME_SERIES':
new_cond = TimeSeriesCondition.create(new_cond)
else:
new_cond.set_parameter(key, value)
elif curr_section is IniParser.Element.sugg:
new_suggestion.set_parameter(key, value)
def get_rules_dict(self):
return self.rules_dict
def get_conditions_dict(self):
return self.conditions_dict
def get_suggestions_dict(self):
return self.suggestions_dict
def get_triggered_rules(self, data_sources, column_families):
self.trigger_conditions(data_sources)
triggered_rules = []
for rule in self.rules_dict.values():
if rule.is_triggered(self.conditions_dict, column_families):
triggered_rules.append(rule)
return triggered_rules
def trigger_conditions(self, data_sources):
for source_type in data_sources:
cond_subset = [
cond
for cond in self.conditions_dict.values()
if cond.get_data_source() is source_type
]
if not cond_subset:
continue
for source in data_sources[source_type]:
source.check_and_trigger_conditions(cond_subset)
def print_rules(self, rules):
for rule in rules:
print('\nRule: ' + rule.name)
for cond_name in rule.conditions:
print(repr(self.conditions_dict[cond_name]))
for sugg_name in rule.suggestions:
print(repr(self.suggestions_dict[sugg_name]))
if rule.trigger_entities:
print('scope: entities:')
print(rule.trigger_entities)
if rule.trigger_column_families:
print('scope: col_fam:')
print(rule.trigger_column_families)
| 0 | 0.88767 | 1 | 0.88767 | game-dev | MEDIA | 0.18051 | game-dev | 0.986672 | 1 | 0.986672 |
mellinoe/ge | 14,651 | src/BEPU/BEPUphysics/Vehicle/WheelDrivingMotor.cs | using BEPUphysics.Constraints;
using BEPUphysics.Entities;
using BEPUphysics.Materials;
using BEPUutilities;
namespace BEPUphysics.Vehicle
{
/// <summary>
/// Handles a wheel's driving force for a vehicle.
/// </summary>
public class WheelDrivingMotor : ISolverSettings
{
#region Static Stuff
/// <summary>
/// Default blender used by WheelSlidingFriction constraints.
/// </summary>
public static WheelFrictionBlender DefaultGripFrictionBlender;
static WheelDrivingMotor()
{
DefaultGripFrictionBlender = BlendFriction;
}
/// <summary>
/// Function which takes the friction values from a wheel and a supporting material and computes the blended friction.
/// </summary>
/// <param name="wheelFriction">Friction coefficient associated with the wheel.</param>
/// <param name="materialFriction">Friction coefficient associated with the support material.</param>
/// <param name="usingKineticFriction">True if the friction coefficients passed into the blender are kinetic coefficients, false otherwise.</param>
/// <param name="wheel">Wheel being blended.</param>
/// <returns>Blended friction coefficient.</returns>
public static float BlendFriction(float wheelFriction, float materialFriction, bool usingKineticFriction, Wheel wheel)
{
return wheelFriction * materialFriction;
}
#endregion
internal float accumulatedImpulse;
//float linearBX, linearBY, linearBZ;
internal float angularAX, angularAY, angularAZ;
internal float angularBX, angularBY, angularBZ;
internal bool isActive = true;
internal float linearAX, linearAY, linearAZ;
private float currentFrictionCoefficient;
internal System.Numerics.Vector3 forceAxis;
private float gripFriction;
private WheelFrictionBlender gripFrictionBlender = DefaultGripFrictionBlender;
private float maxMotorForceDt;
private float maximumBackwardForce = float.MaxValue;
private float maximumForwardForce = float.MaxValue;
internal SolverSettings solverSettings = new SolverSettings();
private float targetSpeed;
private Wheel wheel;
internal int numIterationsAtZeroImpulse;
private Entity vehicleEntity, supportEntity;
//Inverse effective mass matrix
internal float velocityToImpulse;
private bool supportIsDynamic;
/// <summary>
/// Constructs a new wheel motor.
/// </summary>
/// <param name="gripFriction">Friction coefficient of the wheel. Blended with the ground's friction coefficient and normal force to determine a maximum force.</param>
/// <param name="maximumForwardForce">Maximum force that the wheel motor can apply when driving forward (a target speed greater than zero).</param>
/// <param name="maximumBackwardForce">Maximum force that the wheel motor can apply when driving backward (a target speed less than zero).</param>
public WheelDrivingMotor(float gripFriction, float maximumForwardForce, float maximumBackwardForce)
{
GripFriction = gripFriction;
MaximumForwardForce = maximumForwardForce;
MaximumBackwardForce = maximumBackwardForce;
}
internal WheelDrivingMotor(Wheel wheel)
{
Wheel = wheel;
}
/// <summary>
/// Gets the coefficient of grip friction between the wheel and support.
/// This coefficient is the blended result of the supporting entity's friction and the wheel's friction.
/// </summary>
public float BlendedCoefficient
{
get { return currentFrictionCoefficient; }
}
/// <summary>
/// Gets the axis along which the driving forces are applied.
/// </summary>
public System.Numerics.Vector3 ForceAxis
{
get { return forceAxis; }
}
/// <summary>
/// Gets or sets the coefficient of forward-backward gripping friction for this wheel.
/// This coefficient and the supporting entity's coefficient of friction will be
/// taken into account to determine the used coefficient at any given time.
/// </summary>
public float GripFriction
{
get { return gripFriction; }
set { gripFriction = MathHelper.Max(value, 0); }
}
/// <summary>
/// Gets or sets the function used to blend the supporting entity's friction and the wheel's friction.
/// </summary>
public WheelFrictionBlender GripFrictionBlender
{
get { return gripFrictionBlender; }
set { gripFrictionBlender = value; }
}
/// <summary>
/// Gets or sets the maximum force that the wheel motor can apply when driving backward (a target speed less than zero).
/// </summary>
public float MaximumBackwardForce
{
get { return maximumBackwardForce; }
set { maximumBackwardForce = value; }
}
/// <summary>
/// Gets or sets the maximum force that the wheel motor can apply when driving forward (a target speed greater than zero).
/// </summary>
public float MaximumForwardForce
{
get { return maximumForwardForce; }
set { maximumForwardForce = value; }
}
/// <summary>
/// Gets or sets the target speed of this wheel.
/// </summary>
public float TargetSpeed
{
get { return targetSpeed; }
set { targetSpeed = value; }
}
/// <summary>
/// Gets the force this wheel's motor is applying.
/// </summary>
public float TotalImpulse
{
get { return accumulatedImpulse; }
}
/// <summary>
/// Gets the wheel that this motor applies to.
/// </summary>
public Wheel Wheel
{
get { return wheel; }
internal set { wheel = value; }
}
#region ISolverSettings Members
/// <summary>
/// Gets the solver settings used by this wheel constraint.
/// </summary>
public SolverSettings SolverSettings
{
get { return solverSettings; }
}
#endregion
/// <summary>
/// Gets the relative velocity between the ground and wheel.
/// </summary>
/// <returns>Relative velocity between the ground and wheel.</returns>
public float RelativeVelocity
{
get
{
float velocity = 0;
if (vehicleEntity != null)
velocity += vehicleEntity.linearVelocity.X * linearAX + vehicleEntity.linearVelocity.Y * linearAY + vehicleEntity.linearVelocity.Z * linearAZ +
vehicleEntity.angularVelocity.X * angularAX + vehicleEntity.angularVelocity.Y * angularAY + vehicleEntity.angularVelocity.Z * angularAZ;
if (supportEntity != null)
velocity += -supportEntity.linearVelocity.X * linearAX - supportEntity.linearVelocity.Y * linearAY - supportEntity.linearVelocity.Z * linearAZ +
supportEntity.angularVelocity.X * angularBX + supportEntity.angularVelocity.Y * angularBY + supportEntity.angularVelocity.Z * angularBZ;
return velocity;
}
}
internal float ApplyImpulse()
{
//Compute relative velocity
float lambda = (RelativeVelocity
- targetSpeed) //Add in the extra goal speed
* velocityToImpulse; //convert to impulse
//Clamp accumulated impulse
float previousAccumulatedImpulse = accumulatedImpulse;
accumulatedImpulse += lambda;
//Don't brake, and take into account the motor's maximum force.
if (targetSpeed > 0)
accumulatedImpulse = MathHelper.Clamp(accumulatedImpulse, 0, maxMotorForceDt); //MathHelper.Min(MathHelper.Max(accumulatedImpulse, 0), myMaxMotorForceDt);
else if (targetSpeed < 0)
accumulatedImpulse = MathHelper.Clamp(accumulatedImpulse, maxMotorForceDt, 0); //MathHelper.Max(MathHelper.Min(accumulatedImpulse, 0), myMaxMotorForceDt);
else
accumulatedImpulse = 0;
//Friction
float maxForce = currentFrictionCoefficient * wheel.suspension.accumulatedImpulse;
accumulatedImpulse = MathHelper.Clamp(accumulatedImpulse, maxForce, -maxForce);
lambda = accumulatedImpulse - previousAccumulatedImpulse;
//Apply the impulse
#if !WINDOWS
System.Numerics.Vector3 linear = new System.Numerics.Vector3();
System.Numerics.Vector3 angular = new System.Numerics.Vector3();
#else
System.Numerics.Vector3 linear, angular;
#endif
linear.X = lambda * linearAX;
linear.Y = lambda * linearAY;
linear.Z = lambda * linearAZ;
if (vehicleEntity.isDynamic)
{
angular.X = lambda * angularAX;
angular.Y = lambda * angularAY;
angular.Z = lambda * angularAZ;
vehicleEntity.ApplyLinearImpulse(ref linear);
vehicleEntity.ApplyAngularImpulse(ref angular);
}
if (supportIsDynamic)
{
linear.X = -linear.X;
linear.Y = -linear.Y;
linear.Z = -linear.Z;
angular.X = lambda * angularBX;
angular.Y = lambda * angularBY;
angular.Z = lambda * angularBZ;
supportEntity.ApplyLinearImpulse(ref linear);
supportEntity.ApplyAngularImpulse(ref angular);
}
return lambda;
}
internal void PreStep(float dt)
{
vehicleEntity = wheel.Vehicle.Body;
supportEntity = wheel.SupportingEntity;
supportIsDynamic = supportEntity != null && supportEntity.isDynamic;
Vector3Ex.Cross(ref wheel.normal, ref wheel.slidingFriction.slidingFrictionAxis, out forceAxis);
forceAxis.Normalize();
//Do not need to check for normalize safety because normal and sliding friction axis must be perpendicular.
linearAX = forceAxis.X;
linearAY = forceAxis.Y;
linearAZ = forceAxis.Z;
//angular A = Ra x N
angularAX = (wheel.ra.Y * linearAZ) - (wheel.ra.Z * linearAY);
angularAY = (wheel.ra.Z * linearAX) - (wheel.ra.X * linearAZ);
angularAZ = (wheel.ra.X * linearAY) - (wheel.ra.Y * linearAX);
//Angular B = N x Rb
angularBX = (linearAY * wheel.rb.Z) - (linearAZ * wheel.rb.Y);
angularBY = (linearAZ * wheel.rb.X) - (linearAX * wheel.rb.Z);
angularBZ = (linearAX * wheel.rb.Y) - (linearAY * wheel.rb.X);
//Compute inverse effective mass matrix
float entryA, entryB;
//these are the transformed coordinates
float tX, tY, tZ;
if (vehicleEntity.isDynamic)
{
tX = angularAX * vehicleEntity.inertiaTensorInverse.M11 + angularAY * vehicleEntity.inertiaTensorInverse.M21 + angularAZ * vehicleEntity.inertiaTensorInverse.M31;
tY = angularAX * vehicleEntity.inertiaTensorInverse.M12 + angularAY * vehicleEntity.inertiaTensorInverse.M22 + angularAZ * vehicleEntity.inertiaTensorInverse.M32;
tZ = angularAX * vehicleEntity.inertiaTensorInverse.M13 + angularAY * vehicleEntity.inertiaTensorInverse.M23 + angularAZ * vehicleEntity.inertiaTensorInverse.M33;
entryA = tX * angularAX + tY * angularAY + tZ * angularAZ + vehicleEntity.inverseMass;
}
else
entryA = 0;
if (supportIsDynamic)
{
tX = angularBX * supportEntity.inertiaTensorInverse.M11 + angularBY * supportEntity.inertiaTensorInverse.M21 + angularBZ * supportEntity.inertiaTensorInverse.M31;
tY = angularBX * supportEntity.inertiaTensorInverse.M12 + angularBY * supportEntity.inertiaTensorInverse.M22 + angularBZ * supportEntity.inertiaTensorInverse.M32;
tZ = angularBX * supportEntity.inertiaTensorInverse.M13 + angularBY * supportEntity.inertiaTensorInverse.M23 + angularBZ * supportEntity.inertiaTensorInverse.M33;
entryB = tX * angularBX + tY * angularBY + tZ * angularBZ + supportEntity.inverseMass;
}
else
entryB = 0;
velocityToImpulse = -1 / (entryA + entryB); //Softness?
currentFrictionCoefficient = gripFrictionBlender(gripFriction, wheel.supportMaterial.kineticFriction, true, wheel);
//Compute the maximum force
if (targetSpeed > 0)
maxMotorForceDt = maximumForwardForce * dt;
else
maxMotorForceDt = -maximumBackwardForce * dt;
}
internal void ExclusiveUpdate()
{
//Warm starting
#if !WINDOWS
System.Numerics.Vector3 linear = new System.Numerics.Vector3();
System.Numerics.Vector3 angular = new System.Numerics.Vector3();
#else
System.Numerics.Vector3 linear, angular;
#endif
linear.X = accumulatedImpulse * linearAX;
linear.Y = accumulatedImpulse * linearAY;
linear.Z = accumulatedImpulse * linearAZ;
if (vehicleEntity.isDynamic)
{
angular.X = accumulatedImpulse * angularAX;
angular.Y = accumulatedImpulse * angularAY;
angular.Z = accumulatedImpulse * angularAZ;
vehicleEntity.ApplyLinearImpulse(ref linear);
vehicleEntity.ApplyAngularImpulse(ref angular);
}
if (supportIsDynamic)
{
linear.X = -linear.X;
linear.Y = -linear.Y;
linear.Z = -linear.Z;
angular.X = accumulatedImpulse * angularBX;
angular.Y = accumulatedImpulse * angularBY;
angular.Z = accumulatedImpulse * angularBZ;
supportEntity.ApplyLinearImpulse(ref linear);
supportEntity.ApplyAngularImpulse(ref angular);
}
}
}
} | 0 | 0.841127 | 1 | 0.841127 | game-dev | MEDIA | 0.855467 | game-dev | 0.990048 | 1 | 0.990048 |
mastercomfig/tf2-patches-old | 38,712 | src/game/client/tf/tf_hud_item_progress_tracker.cpp | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================
#include "cbase.h"
#include "tf_hud_item_progress_tracker.h"
#include "iclientmode.h"
#include <vgui_controls/Label.h>
#include <vgui_controls/ImagePanel.h>
#include "gc_clientsystem.h"
#include "engine/IEngineSound.h"
#include "quest_log_panel.h"
#include "econ_controls.h"
#include "tf_item_inventory.h"
#include "c_tf_player.h"
#include "quest_objective_manager.h"
#include "tf_spectatorgui.h"
#include "econ_quests.h"
#include "inputsystem/iinputsystem.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
using namespace vgui;
const float ATTRIB_TRACK_GLOW_HOLD_TIME = 2.f;
const float ATTRIB_TRACK_BAR_GROW_RATE = 0.3f;
const float ATTRIB_TRACK_COMPLETE_PULSE_RATE = 2.f;
const float ATTRIB_TRACK_COMPLETE_PULSE_DIM_HOLD = 0.3f;
const float ATTRIB_TRACK_COMPLETE_PULSE_GLOW_HOLD = 0.9f;
enum EContractHUDVisibility
{
CONTRACT_HUD_SHOW_NONE = 0,
CONTRACT_HUD_SHOW_EVERYTHING,
CONTRACT_HUD_SHOW_ACTIVE,
};
void cc_contract_progress_show_update( IConVar *pConVar, const char *pOldString, float flOldValue )
{
CHudItemAttributeTracker *pTrackerPanel = (CHudItemAttributeTracker *)GET_HUDELEMENT( CHudItemAttributeTracker );
if ( pTrackerPanel )
{
pTrackerPanel->InvalidateLayout();
}
}
ConVar tf_contract_progress_show( "tf_contract_progress_show", "1", FCVAR_CLIENTDLL | FCVAR_DONTRECORD | FCVAR_ARCHIVE, "Settings for the contract HUD element: 0 show nothing, 1 show everything, 2 show only active contracts.", cc_contract_progress_show_update );
ConVar tf_contract_competitive_show( "tf_contract_competitive_show", "2", FCVAR_CLIENTDLL | FCVAR_DONTRECORD | FCVAR_ARCHIVE, "Settings for the contract HUD element during competitive matches: 0 show nothing, 1 show everything, 2 show only active contracts.", cc_contract_progress_show_update );
EContractHUDVisibility GetContractHUDVisibility()
{
if ( TFGameRules() && TFGameRules()->IsMatchTypeCompetitive() )
return (EContractHUDVisibility)tf_contract_competitive_show.GetInt();
return (EContractHUDVisibility)tf_contract_progress_show.GetInt();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CItemAttributeProgressPanel::CItemAttributeProgressPanel( Panel* pParent, const char *pElementName, const CQuestObjectiveDefinition *pObjectiveDef, const char* pszResFileName )
: EditablePanel( pParent, pElementName )
, m_nDefIndex( pObjectiveDef->GetDefinitionIndex() )
, m_flUpdateTime( 0.f )
, m_flLastThink( 0.f )
, m_bAdvanced( pObjectiveDef->IsAdvanced() )
, m_strResFileName( pszResFileName )
{
Assert( !m_strResFileName.IsEmpty() );
m_pAttribBlur = new Label( this, "AttribBlur", "" );
m_pAttribGlow = new Label( this, "AttribGlow", "" );
m_pAttribDesc = new Label( this, "AttribDesc", "" );
REGISTER_COLOR_AS_OVERRIDABLE( m_enabledTextColor, "enabled_text_color_override" );
REGISTER_COLOR_AS_OVERRIDABLE( m_disabledTextColor, "disabled_text_color_override" );
// We're being set for the first time, instantly be progressed
m_pAttribBlur->SetAlpha( 0 );
m_pAttribGlow->SetAlpha( 0 );
m_flUpdateTime = Plat_FloatTime() - ATTRIB_TRACK_GLOW_HOLD_TIME;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CItemAttributeProgressPanel::ApplySchemeSettings( vgui::IScheme *pScheme )
{
BaseClass::ApplySchemeSettings( pScheme );
LoadControlSettings( m_strResFileName );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CItemAttributeProgressPanel::ApplySettings( KeyValues *inResourceData )
{
BaseClass::ApplySettings( inResourceData );
m_strNormalPointLocToken = inResourceData->GetString( "normal_token" );
m_strAdvancedLocToken = inResourceData->GetString( "advanced_token" );
const CQuestObjectiveDefinition *pObjectiveDef = GEconItemSchema().GetQuestObjectiveByDefIndex( m_nDefIndex );
if ( pObjectiveDef )
{
const char *pszDescriptionToken = pObjectiveDef->GetDescriptionToken();
locchar_t loc_ItemDescription[MAX_ITEM_NAME_LENGTH];
const locchar_t *pLocalizedObjectiveName = GLocalizationProvider()->Find( pszDescriptionToken );
if ( !pLocalizedObjectiveName || !pLocalizedObjectiveName[0] )
{
// Couldn't localize it, just use it raw
GLocalizationProvider()->ConvertUTF8ToLocchar( pszDescriptionToken, loc_ItemDescription, ARRAYSIZE( loc_ItemDescription ) );
}
else
{
locchar_t loc_IntermediateName[ MAX_ITEM_NAME_LENGTH ];
locchar_t locValue[ MAX_ITEM_NAME_LENGTH ];
loc_sprintf_safe( locValue, LOCCHAR( "%d" ), pObjectiveDef->GetPoints() );
loc_scpy_safe( loc_IntermediateName, CConstructLocalizedString( pLocalizedObjectiveName, locValue ) );
locchar_t *pszLocString = GLocalizationProvider()->Find( pObjectiveDef->IsAdvanced() ? m_strAdvancedLocToken : m_strNormalPointLocToken );
loc_scpy_safe( loc_ItemDescription, CConstructLocalizedString( pszLocString, loc_IntermediateName ) );
}
SetDialogVariable( "attr_desc", loc_ItemDescription );
}
//SetTall( GetContentTall() );
//m_pAttribDesc->SetTall( GetTall() );
InvalidateLayout();
}
void CItemAttributeProgressPanel::SetIsValid( bool bIsValid )
{
if ( bIsValid )
{
m_pAttribDesc->SetFgColor( m_enabledTextColor );
}
else
{
m_pAttribDesc->SetFgColor( m_disabledTextColor );
}
}
int CItemAttributeProgressPanel::GetContentTall() const
{
// Find the bottom of the text
int nTextWide = 0, nTextTall = 0;
m_pAttribDesc->GetContentSize( nTextWide, nTextTall );
int nTextYpos = m_pAttribDesc->GetYPos();
return nTextYpos + nTextTall;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CItemAttributeProgressPanel::SetProgress( Color glowColor )
{
m_flUpdateTime = Plat_FloatTime();
m_pAttribBlur->SetAlpha( 255 );
m_pAttribGlow->SetAlpha( 255 );
m_pAttribDesc->SetAlpha( 0 );
m_pAttribBlur->SetFgColor( glowColor );
m_pAttribGlow->SetFgColor( glowColor );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CItemAttributeProgressPanel::OnThink()
{
float flGlowTime = Plat_FloatTime() - m_flUpdateTime;
if ( flGlowTime > ATTRIB_TRACK_GLOW_HOLD_TIME )
{
float flGlowAlpha = RemapValClamped( flGlowTime, ATTRIB_TRACK_GLOW_HOLD_TIME, ATTRIB_TRACK_GLOW_HOLD_TIME + 0.25f, 1.f, 0.f );
m_pAttribBlur->SetAlpha( 255 * flGlowAlpha );
m_pAttribGlow->SetAlpha( 255 * flGlowAlpha );
m_pAttribDesc->SetAlpha( 255 * ( 1.f - flGlowAlpha ) );
}
m_flLastThink = Plat_FloatTime();
}
float CItemTrackerPanel::m_sflEventRecievedTime = 0.f;
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CItemTrackerPanel::CItemTrackerPanel( Panel* pParent, const char *pElementName, const CEconItem* pItem, const char* pszItemTrackerResFile )
: EditablePanel( pParent, pElementName )
, m_pItem( NULL )
, m_pCompletedContainer( NULL )
, m_pCompletedDescGlow( NULL )
, m_pCompletedNameGlow( NULL )
, m_flStandardTargetProgress( 0.f )
, m_flStandardCurrentProgress( 0.f )
, m_flBonusCurrentProgress( 0.f )
, m_flBonusTargetProgress( 0.f )
, m_flUpdateTime( 0.f )
, m_flLastThink( 0.f )
, m_nMaxStandardPoints( 0 )
, m_nMaxBonusPoints( 0 )
, m_eSoundToPlay( SOUND_NONE )
, m_nContentTall( 0 )
, m_bNoEffects( false )
, m_strItemTrackerResFile( pszItemTrackerResFile )
{
Assert( pszItemTrackerResFile );
SetItem( pItem );
ListenForGameEvent( "quest_objective_completed" );
ListenForGameEvent( "player_spawn" );
ListenForGameEvent( "inventory_updated" );
ListenForGameEvent( "localplayer_changeclass" );
ListenForGameEvent( "schema_updated" );
m_pItemName = new Label( this, "ItemName", "" );
m_pCompletedContainer = new EditablePanel( this, "CompletedContainer" );
m_pProgressBarBackground = new EditablePanel( this, "ProgressBarBG" );
m_pProgressBarStandard = new EditablePanel( m_pProgressBarBackground, "ProgressBarStandard" );
m_pProgressBarBonus = new EditablePanel( m_pProgressBarBackground, "ProgressBarBonus" );
m_pProgressBarStandardHighlight = new EditablePanel( m_pProgressBarBackground, "ProgressBarStandardHighlight" );
m_pProgressBarBonusHighlight = new EditablePanel( m_pProgressBarBackground, "ProgressBarBonusHighlight" );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CItemTrackerPanel::~CItemTrackerPanel()
{}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CItemTrackerPanel::ApplySettings( KeyValues *inResourceData )
{
BaseClass::ApplySettings( inResourceData );
m_strItemAttributeResFile = inResourceData->GetString( "item_attribute_res_file" );
m_strProgressBarStandardLocToken = inResourceData->GetString( "progress_bar_standard_loc_token" );
m_strProgressBarAdvancedLocToken = inResourceData->GetString( "progress_bar_advanced_loc_token" );
Assert( !m_strItemAttributeResFile.IsEmpty() );
Assert( !m_strProgressBarStandardLocToken.IsEmpty() );
Assert( !m_strProgressBarAdvancedLocToken.IsEmpty() );
m_strStandardObjectiveTick = inResourceData->GetString( "standard_objective_tick_sound", NULL );
m_strStandardPointsComplete = inResourceData->GetString( "standard_points_complete_sound", NULL );
m_strAdvancedObjectiveComplete = inResourceData->GetString( "advanced_objective_sound_complete", NULL );
m_strAdvancedPointsComplete = inResourceData->GetString( "advanced_points_complete_sound", NULL );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CItemTrackerPanel::ApplySchemeSettings( IScheme *pScheme )
{
BaseClass::ApplySchemeSettings( pScheme );
LoadControlSettings( m_strItemTrackerResFile );
m_pCompletedDescGlow = FindControl<Label>( "CompleteGlowText", true );
m_pCompletedNameGlow = FindControl<Label>( "CompleteItemNameGlow", true );
QuestObjectiveDefVec_t vecChosenObjectives;
if ( m_pItem )
{
m_pItem->GetItemDefinition()->GetQuestDef()->GetRolledObjectivesForItem( vecChosenObjectives, m_pItem->GetSOCData() );
}
FOR_EACH_VEC( vecChosenObjectives, i )
{
auto pObjective = vecChosenObjectives[ i ];
// Find or create the individual attribute panel
CItemAttributeProgressPanel *pPanel = GetPanelForObjective( pObjective );
pPanel->InvalidateLayout();
}
CaptureProgress();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
int QuestSort_PointsAscending( CItemAttributeProgressPanel* const* p1, CItemAttributeProgressPanel* const* p2 )
{
const CQuestObjectiveDefinition* pObj1 = GEconItemSchema().GetQuestObjectiveByDefIndex( (*p1)->m_nDefIndex );
const CQuestObjectiveDefinition* pObj2 = GEconItemSchema().GetQuestObjectiveByDefIndex( (*p2)->m_nDefIndex );
if ( pObj1->GetPoints() != pObj2->GetPoints() )
{
// Smallest point value on the bottom
return pObj1->GetPoints() - pObj2->GetPoints();
}
return pObj1->GetDefinitionIndex() - pObj2->GetDefinitionIndex();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CItemTrackerPanel::PerformLayout()
{
BaseClass::PerformLayout();
if ( !m_pItem )
return;
// Set the name into dialog variables
const wchar_t *pszLocToken = g_pVGuiLocalize->Find( m_pItem->GetItemDefinition()->GetQuestDef()->GetRolledNameForItem( m_pItem->GetSOCData() ) );
SetDialogVariable( "itemname", pszLocToken );
if ( m_pCompletedContainer )
{
m_pCompletedContainer->SetDialogVariable( "itemname", pszLocToken );
}
const CQuestItemTracker* pItemTracker = QuestObjectiveManager()->GetTypedTracker< CQuestItemTracker* >( m_pItem->GetItemID() );
if ( pItemTracker )
{
bool bStandardPointsCompleteAndBonusPossible = m_flStandardCurrentProgress == m_flStandardTargetProgress && m_flStandardTargetProgress == 1.f && m_nMaxBonusPoints > 0;
uint32 nCurrentPoints = bStandardPointsCompleteAndBonusPossible ? pItemTracker->GetEarnedBonusPoints() : pItemTracker->GetEarnedStandardPoints();
uint32 nTargetPoints = bStandardPointsCompleteAndBonusPossible ? m_nMaxBonusPoints : m_nMaxStandardPoints;
locchar_t locValue[ MAX_ITEM_NAME_LENGTH ];
const locchar_t *pPointsToken = GLocalizationProvider()->Find( bStandardPointsCompleteAndBonusPossible ? m_strProgressBarAdvancedLocToken : m_strProgressBarStandardLocToken );
loc_scpy_safe( locValue, CConstructLocalizedString( pPointsToken, nCurrentPoints, nTargetPoints ) );
m_pProgressBarBackground->SetDialogVariable( "points", locValue );
m_pProgressBarStandard->SetDialogVariable( "points" , locValue );
m_pProgressBarStandardHighlight->SetDialogVariable( "points" , locValue );
m_pProgressBarBonus->SetDialogVariable( "points", locValue );
m_pProgressBarBonusHighlight->SetDialogVariable( "points" , locValue );
}
else
{
m_pProgressBarBackground->SetDialogVariable( "points", "" );
m_pProgressBarStandard->SetDialogVariable( "points" , "" );
m_pProgressBarStandardHighlight->SetDialogVariable( "points" , "" );
m_pProgressBarBonus->SetDialogVariable( "points", "" );
m_pProgressBarBonusHighlight->SetDialogVariable( "points" , "" );
}
m_pProgressBarStandardHighlight->SetVisible( !m_bNoEffects );
m_pProgressBarBonusHighlight->SetVisible( !m_bNoEffects );
int nWide = 0, nTall = 0;
if ( m_pItemName->IsVisible() && !m_bNoEffects )
{
m_pItemName->GetContentSize( nWide, nTall );
}
int nX = m_nAttribXOffset;
int nY = nTall + m_nAttribYStartOffset;
bool bCompleted = true;
m_vecAttribPanels.Sort( &QuestSort_PointsAscending );
if ( !IsStandardCompleted() )
{
bCompleted = false;
}
m_pCompletedContainer->SetVisible( bCompleted );
if ( bCompleted && !m_bNoEffects )
{
m_pCompletedContainer->SetVisible( true );
CExLabel* pCompleted = m_pCompletedContainer->FindControl< CExLabel >( "CompleteDesc", true );
CExLabel* pCompletedGlow = m_pCompletedContainer->FindControl< CExLabel > ( "CompleteGlowText", true );
if ( pCompleted && pCompletedGlow )
{
const wchar_t *pszText = NULL;
const char *pszTextKey = "#QuestTracker_Complete";
if ( pszTextKey )
{
pszText = g_pVGuiLocalize->Find( pszTextKey );
}
if ( pszText )
{
wchar_t wzFinal[512] = L"";
UTIL_ReplaceKeyBindings( pszText, 0, wzFinal, sizeof( wzFinal ), GAME_ACTION_SET_FPSCONTROLS );
pCompleted->SetText( wzFinal );
pCompletedGlow->SetText( wzFinal );
}
}
nY = m_pCompletedContainer->GetTall();
}
else
{
m_pCompletedContainer->SetVisible( false );
}
// Place the bars at the bottom of the text, not the bottom of the text panel
m_pProgressBarBackground->SetPos( m_pProgressBarBackground->GetXPos(), nY );
nY += m_pProgressBarBackground->GetTall() + m_nBarGap;
UpdateBars();
C_TFPlayer *pLocalPlayer = C_TFPlayer::GetLocalTFPlayer();
FOR_EACH_VEC( m_vecAttribPanels, i )
{
CItemAttributeProgressPanel* pPanel = m_vecAttribPanels[i];
// Hide all objectives if everything is completed, or just hide standard objectives is standard points re completed
if ( !m_bNoEffects && ( IsEverythingCompleted() || ( IsStandardCompleted() && !pPanel->IsAdvanced() ) ) )
{
pPanel->SetVisible( false );
}
else
{
pPanel->SetPos( nX, nY );
nY += pPanel->GetContentTall();
pPanel->SetVisible( true );
InvalidReasonsContainer_t invalidReasons;
if ( pItemTracker && pLocalPlayer )
{
// Fixup validity, which changes the color of the
const CBaseQuestObjectiveTracker* pObjectiveTracker = pItemTracker->FindTrackerForDefIndex( pPanel->m_nDefIndex );
if ( pObjectiveTracker )
{
pObjectiveTracker->IsValidForPlayer( pLocalPlayer, invalidReasons );
}
}
pPanel->SetIsValid( invalidReasons.IsValid() );
nY += m_nAttribYStep;
}
}
m_nContentTall = nY;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
int CItemTrackerPanel::GetContentTall() const
{
return m_nContentTall;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CItemTrackerPanel::OnThink()
{
BaseClass::OnThink();
if ( !m_pItem || m_bNoEffects )
return;
static double s_flLastSoundTime = 0;
// Give a little time in case other messaes are in flight
if ( ( Plat_FloatTime() - m_sflEventRecievedTime ) > 0.1f )
{
// Dont play sounds very frequently
if ( m_eSoundToPlay != SOUND_NONE && ( ( Plat_FloatTime() - s_flLastSoundTime ) > 0.1f ) )
{
const char *pszSoundName = NULL;
// Figure out which sound to play
switch( m_eSoundToPlay )
{
case SOUND_STANDARD_OBJECTIVE_TICK:
pszSoundName = m_strStandardObjectiveTick;
break;
case SOUND_ADVANCED_OBJECTIVE_TICK:
pszSoundName = m_strAdvancedObjectiveComplete;
break;
case SOUND_QUEST_STANDARD_COMPLETE:
pszSoundName = m_strStandardPointsComplete;
break;
case SOUND_QUEST_ADVANCED_COMPLETE:
pszSoundName = m_strAdvancedPointsComplete;
break;
};
s_flLastSoundTime = Plat_FloatTime();
CLocalPlayerFilter filter;
C_BaseEntity::EmitSound( filter, SOUND_FROM_LOCAL_PLAYER, pszSoundName );
}
m_eSoundToPlay = SOUND_NONE;
}
// If the highlight is done, and the quest is ready to turn in, pulse a glow behind
// the title and the completion instruction
if ( IsDoneProgressing() && IsStandardCompleted() )
{
if ( m_pCompletedDescGlow && m_pCompletedNameGlow )
{
float flPeriod = ( sin( gpGlobals->curtime * ATTRIB_TRACK_COMPLETE_PULSE_RATE ) * 0.5f ) + 0.5f;
float flGlowAlpha = RemapValClamped( flPeriod, ATTRIB_TRACK_COMPLETE_PULSE_DIM_HOLD, ATTRIB_TRACK_COMPLETE_PULSE_GLOW_HOLD, 0.f, 1.f );
m_pCompletedDescGlow->SetAlpha( 255 * flGlowAlpha );
m_pCompletedNameGlow->SetAlpha( 255 * flGlowAlpha );
}
}
float flGlowTime = Plat_FloatTime() - m_flUpdateTime;
if ( flGlowTime > ATTRIB_TRACK_GLOW_HOLD_TIME && ( m_flStandardCurrentProgress != m_flStandardTargetProgress || m_flBonusCurrentProgress != m_flBonusTargetProgress ) )
{
float flDelta = Plat_FloatTime() - m_flLastThink;
m_flStandardCurrentProgress = Approach( m_flStandardTargetProgress, m_flStandardCurrentProgress, flDelta * ATTRIB_TRACK_BAR_GROW_RATE );
m_flBonusCurrentProgress = Approach( m_flBonusTargetProgress, m_flBonusCurrentProgress, flDelta * ATTRIB_TRACK_BAR_GROW_RATE );
// Resize/position the bars
UpdateBars();
// This happens when all the bars are all caught up
if ( IsDoneProgressing() )
{
InvalidateLayout();
}
}
if ( IsDoneProgressing() )
{
m_pProgressBarStandardHighlight->SetVisible( false );
m_pProgressBarBonusHighlight->SetVisible( false );
}
m_flLastThink = Plat_FloatTime();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CItemTrackerPanel::FireGameEvent( IGameEvent *pEvent )
{
if ( FStrEq( pEvent->GetName(), "quest_objective_completed" ) )
{
itemid_t nIDLow = 0x00000000FFFFFFFF & (itemid_t)pEvent->GetInt( "quest_item_id_low" );
itemid_t nIDHi = 0xFFFFFFFF00000000 & (itemid_t)pEvent->GetInt( "quest_item_id_hi" ) << 32;
itemid_t nID = nIDLow | nIDHi;
if ( !m_pItem || m_pItem->GetItemID() != nID )
return;
// Capture whatever progress has happened
CaptureProgress();
uint32 nObjectiveDefIndex = pEvent->GetInt( "quest_objective_id" );
// Don't do sounds if there's no objective that made this progress
if ( nObjectiveDefIndex == (uint32)-1 )
return;
bool bAdvanced = false;
const CQuestObjectiveDefinition* pObjective = GEconItemSchema().GetQuestObjectiveByDefIndex( nObjectiveDefIndex );
if ( !pObjective )
return;
bAdvanced = pObjective->IsAdvanced();
const CQuestItemTracker* pItemTracker = QuestObjectiveManager()->GetTypedTracker< CQuestItemTracker* >( m_pItem->GetItemID() );
if ( pItemTracker )
{
const Color& glowColor = pItemTracker->GetEarnedStandardPoints() < m_nMaxStandardPoints ? m_clrStandardHighlight
: m_clrBonusHighlight;
FOR_EACH_VEC( m_vecAttribPanels, i )
{
if ( m_vecAttribPanels[i]->m_nDefIndex == nObjectiveDefIndex )
{
m_vecAttribPanels[i]->SetProgress( glowColor );
break;
}
}
// Check if it's time to play a sound
ESoundToPlay eNewSound = SOUND_NONE;
if ( m_flStandardCurrentProgress < m_flStandardTargetProgress && pItemTracker->GetEarnedStandardPoints() == m_nMaxStandardPoints )
{
eNewSound = SOUND_QUEST_STANDARD_COMPLETE;
}
else if ( m_flBonusCurrentProgress < m_flBonusTargetProgress && pItemTracker->GetEarnedBonusPoints() == m_nMaxBonusPoints )
{
eNewSound = SOUND_QUEST_ADVANCED_COMPLETE;
}
else if ( bAdvanced )
{
eNewSound = SOUND_ADVANCED_OBJECTIVE_TICK;
}
else
{
eNewSound = SOUND_STANDARD_OBJECTIVE_TICK;
}
// Priority will handle this for us
if ( eNewSound > m_eSoundToPlay )
{
m_eSoundToPlay = eNewSound;
if ( m_sflEventRecievedTime < Plat_FloatTime() )
{
m_sflEventRecievedTime = Plat_FloatTime();
}
}
}
}
else if ( FStrEq( pEvent->GetName(), "player_spawn" )
|| FStrEq( pEvent->GetName(), "inventory_updated" )
|| FStrEq( pEvent->GetName(), "localplayer_changeclass" ) )
{
InvalidateLayout();
}
else if ( FStrEq( pEvent->GetName(), "schema_updated" ) )
{
FOR_EACH_VEC( m_vecAttribPanels, i )
{
m_vecAttribPanels[ i ]->InvalidateLayout();
}
InvalidateLayout();
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CItemTrackerPanel::UpdateBars()
{
// Everything is relative to the background bar
int nWide = m_pProgressBarBackground->GetWide();
// Resize standard bar
m_pProgressBarStandard->SetWide( floor(m_flStandardCurrentProgress * nWide ) );
// Resize bonus bar
m_pProgressBarBonus->SetWide( floor(m_flBonusCurrentProgress * nWide ) );
// Highlight bars snap to the target width
m_pProgressBarStandardHighlight->SetWide( floor(m_flStandardTargetProgress * nWide) );
m_pProgressBarBonusHighlight->SetWide( floor( m_flBonusTargetProgress * nWide ) );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CItemTrackerPanel::CaptureProgress()
{
if ( !m_pItem )
return;
const CQuestItemTracker* pItemTracker = QuestObjectiveManager()->GetTypedTracker< CQuestItemTracker* >( m_pItem->GetItemID() );
// Fixup bar bounds
float flStandardProgress = 0.f;
float flBonusProgress = 0.f;
if ( pItemTracker )
{
// We use the item trackers for quest progress since they're the most up-to-date
flStandardProgress = (float)pItemTracker->GetEarnedStandardPoints() / (float)( m_nMaxStandardPoints);
flBonusProgress = (float)pItemTracker->GetEarnedBonusPoints() / (float)( m_nMaxBonusPoints );
}
// Standard progress
bool bChange = flStandardProgress != m_flStandardTargetProgress;
m_flStandardTargetProgress = flStandardProgress;
// Bonus progress
bChange |= flBonusProgress != m_flBonusTargetProgress;
m_flBonusTargetProgress = flBonusProgress;
// We're being set for the first time, instantly be progressed
if ( m_flUpdateTime == 0.f || m_bNoEffects )
{
m_flStandardCurrentProgress = m_flStandardTargetProgress;
m_flBonusCurrentProgress = m_flBonusTargetProgress;
m_flUpdateTime = Plat_FloatTime() - ATTRIB_TRACK_GLOW_HOLD_TIME;
InvalidateLayout();
}
else if ( bChange ) // If this is a change, play effects
{
m_flUpdateTime = Plat_FloatTime();
InvalidateLayout();
}
m_pProgressBarStandardHighlight->SetVisible( !m_bNoEffects );
m_pProgressBarBonusHighlight->SetVisible( !m_bNoEffects );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CItemTrackerPanel::IsStandardCompleted() const
{
const CQuestItemTracker* pItemTracker = QuestObjectiveManager()->GetTypedTracker< CQuestItemTracker* >( m_pItem->GetItemID() );
if ( pItemTracker )
{
return pItemTracker->GetEarnedStandardPoints() >= m_nMaxStandardPoints;
}
return false;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CItemTrackerPanel::IsEverythingCompleted() const
{
const CQuestItemTracker* pItemTracker = QuestObjectiveManager()->GetTypedTracker< CQuestItemTracker* >( m_pItem->GetItemID() );
if ( pItemTracker )
{
return ( pItemTracker->GetEarnedBonusPoints() + pItemTracker->GetEarnedStandardPoints() ) >= ( m_nMaxBonusPoints + m_nMaxStandardPoints );
}
return false;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CItemTrackerPanel::SetItem( const CEconItem* pItem )
{
m_pItem.SetItem( TFInventoryManager()->GetLocalTFInventory()->GetInventoryItemByItemID( pItem->GetItemID() ) );
m_nMaxStandardPoints = pItem->GetItemDefinition()->GetQuestDef()->GetMaxStandardPoints();
m_nMaxBonusPoints = pItem->GetItemDefinition()->GetQuestDef()->GetMaxBonusPoints();
InvalidateLayout();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CItemAttributeProgressPanel* CItemTrackerPanel::GetPanelForObjective( const CQuestObjectiveDefinition* pObjective )
{
FOR_EACH_VEC( m_vecAttribPanels, i )
{
if ( m_vecAttribPanels[ i ]->m_nDefIndex == pObjective->GetDefinitionIndex() )
return m_vecAttribPanels[ i ];
}
CItemAttributeProgressPanel *pPanel = new CItemAttributeProgressPanel( this, "ItemAttributeProgressPanel", pObjective, m_strItemAttributeResFile );
SETUP_PANEL( pPanel );
m_vecAttribPanels.AddToTail( pPanel );
return pPanel;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CItemTrackerPanel::IsValidForLocalPlayer() const
{
C_TFPlayer *pLocalPlayer = C_TFPlayer::GetLocalTFPlayer();
CSteamID steamID;
if ( !pLocalPlayer || !pLocalPlayer->GetSteamID( &steamID ) )
return false;
Assert( m_pItem );
// Safeguard. There's a crash in public from this.
if ( !m_pItem )
return false;
const CQuestItemTracker* pItemTracker = QuestObjectiveManager()->GetTypedTracker< CQuestItemTracker* >( m_pItem->GetItemID() );
InvalidReasonsContainer_t invalidReasons;
if ( pItemTracker )
{
int nNumInvalid = pItemTracker->IsValidForPlayer( pLocalPlayer, invalidReasons );
if ( nNumInvalid < pItemTracker->GetTrackers().Count() )
{
return true;
}
}
// Check for completed quests. They are always visible.
CEconItemView *pItem = TFInventoryManager()->GetLocalTFInventory()->GetInventoryItemByItemID( m_pItem->GetItemID() );
if ( pItem && IsQuestItemReadyToTurnIn( pItem ) && GetContractHUDVisibility() == CONTRACT_HUD_SHOW_EVERYTHING )
{
return true;
}
return false;
}
DECLARE_HUDELEMENT( CHudItemAttributeTracker );
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CHudItemAttributeTracker::CHudItemAttributeTracker( const char *pElementName )
: CHudElement( pElementName )
, EditablePanel( NULL, "ItemAttributeTracker" )
, m_mapTrackers( DefLessFunc( itemid_t ) )
{
Panel *pParent = g_pClientMode->GetViewport();
SetParent( pParent );
ListenForGameEvent( "player_spawn" );
ListenForGameEvent( "inventory_updated" );
ListenForGameEvent( "client_disconnect" );
ListenForGameEvent( "localplayer_changeclass" );
ListenForGameEvent( "quest_objective_completed" );
RegisterForRenderGroup( "weapon_selection" );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CHudItemAttributeTracker::ApplySchemeSettings( IScheme *pScheme )
{
BaseClass::ApplySchemeSettings( pScheme );
LoadControlSettings( "resource/UI/HudItemAttributeTracker.res" );
m_pStatusContainer = FindControl< EditablePanel >( "QuestsStatusContainer" );
m_pStatusHeaderLabel = m_pStatusContainer->FindControl< Label >( "Header" );
m_pCallToActionLabel = m_pStatusContainer->FindControl< Label >( "CallToAction" );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CHudItemAttributeTracker::PerformLayout()
{
BaseClass::PerformLayout();
CUtlVector<CEconItemView*> vecQuestItems;
TFInventoryManager()->GetAllQuestItems( &vecQuestItems );
int nNumCompleted = 0;
int nNumUnidentified = 0;
int nNumInactive = 0;
C_TFPlayer *pLocalPlayer = C_TFPlayer::GetLocalTFPlayer();
FOR_EACH_VEC( vecQuestItems, i )
{
const CEconItemView* pItem = vecQuestItems[i];
if ( IsQuestItemReadyToTurnIn( pItem ) )
{
++nNumCompleted;
}
else if ( IsQuestItemUnidentified( pItem->GetSOCData() ) )
{
++nNumUnidentified;
}
else if ( pLocalPlayer )
{
const CQuestItemTracker* pItemTracker = QuestObjectiveManager()->GetTypedTracker< CQuestItemTracker* >( pItem->GetItemID() );
InvalidReasonsContainer_t invalidReasons;
if ( pItemTracker )
{
if ( pItemTracker->IsValidForPlayer( pLocalPlayer, invalidReasons ) == pItemTracker->GetTrackers().Count() )
{
++nNumInactive;
}
}
}
}
const char* pszHeaderString = NULL;
const char* pszCallToActionString = NULL;
int nNumToShow = 0;
if ( nNumCompleted > 0 )
{
nNumToShow = nNumCompleted;
pszHeaderString = nNumToShow == 1 ? "#QuestTracker_Complete_Single" : "#QuestTracker_Complete_Multiple";
pszCallToActionString = "QuestTracker_Complete";
}
else if ( nNumUnidentified > 0 )
{
nNumToShow = nNumUnidentified;
pszHeaderString = nNumToShow == 1 ? "#QuestTracker_New_Single" : "#QuestTracker_New_Multiple";
pszCallToActionString = "QuestTracker_New_CallToAction";
}
else if ( nNumInactive > 0 )
{
nNumToShow = nNumInactive;
pszHeaderString = nNumToShow == 1 ? "#QuestTracker_Inactive_Single" : "#QuestTracker_Inactive_Multiple";
pszCallToActionString = "QuestTracker_New_CallToAction";
}
bool bAnyStatusToShow = pszHeaderString != NULL;
bool bShowExtras = bAnyStatusToShow && ( GetContractHUDVisibility() != CONTRACT_HUD_SHOW_ACTIVE );
if ( bShowExtras )
{
// Build the "X New Contracts" string
locchar_t locNumNewQuests[ 256 ];
const locchar_t *pLocalizedString = GLocalizationProvider()->Find( pszHeaderString );
if ( pLocalizedString && pLocalizedString[0] )
{
wchar_t wszCounter[ 256 ];
loc_sprintf_safe( wszCounter, LOCCHAR( "%d" ), nNumToShow);
loc_scpy_safe( locNumNewQuests,
CConstructLocalizedString( pLocalizedString, wszCounter ) );
}
m_pStatusContainer->SetDialogVariable( "header", locNumNewQuests );
// Build the "Press [ F2 ] to view" string.
const wchar_t *pszText = NULL;
if ( pszCallToActionString )
{
pszText = g_pVGuiLocalize->Find( pszCallToActionString );
}
if ( pszText )
{
wchar_t wzFinal[512] = L"";
UTIL_ReplaceKeyBindings( pszText, 0, wzFinal, sizeof( wzFinal ), GAME_ACTION_SET_FPSCONTROLS );
m_pStatusContainer->SetDialogVariable( "call_to_action", wzFinal );
}
}
int nY = 0;
if ( m_pStatusContainer )
{
nY = m_pStatusContainer->GetYPos();
m_pStatusContainer->SetVisible( bShowExtras );
if ( m_pStatusContainer->IsVisible() )
{
nY += m_pStatusContainer->GetTall();
int nLabelWide, nLabelTall;
m_pStatusHeaderLabel->GetContentSize( nLabelWide, nLabelTall );
m_pStatusContainer->SetWide( m_nStatusBufferWidth + nLabelWide );
m_pStatusHeaderLabel->SetPos( m_pStatusContainer->GetWide() - m_pStatusHeaderLabel->GetWide(), m_pStatusHeaderLabel->GetYPos() );
m_pCallToActionLabel->SetPos( m_pStatusContainer->GetWide() - m_pCallToActionLabel->GetWide(), m_pCallToActionLabel->GetYPos() );
m_pStatusContainer->SetPos( m_pStatusContainer->GetParent()->GetWide() - m_pStatusContainer->GetWide(), m_pStatusContainer->GetYPos() );
}
}
FOR_EACH_MAP( m_mapTrackers, i )
{
CItemTrackerPanel* pPanel = m_mapTrackers[ i ];
if ( pPanel )
{
if ( pPanel->IsValidForLocalPlayer() )
{
int nTall = pPanel->GetContentTall();
pPanel->SetPos( GetWide() - pPanel->GetWide(), nY );
nY += nTall;
pPanel->SetVisible( true );
}
else
{
pPanel->SetVisible( false );
}
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CHudItemAttributeTracker::OnThink()
{
BaseClass::OnThink();
// If the specator GUI is up, we need to drop down a bit so that we're
// not on top of the death notices
int nY = g_pSpectatorGUI && g_pSpectatorGUI->IsVisible() ? g_pSpectatorGUI->GetTopBarHeight() : 0;
int nCurrentX, nCurrentY;
GetPos( nCurrentX, nCurrentY );
if ( nCurrentY != nY )
{
SetPos( nCurrentX, nY );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CHudItemAttributeTracker::ShouldDraw( void )
{
if ( engine->IsPlayingDemo() )
return false;
if ( GetContractHUDVisibility() == CONTRACT_HUD_SHOW_NONE )
return false;
if ( GetLocalPlayerTeam() < FIRST_GAME_TEAM )
return false;
if ( TFGameRules() )
{
if ( TFGameRules()->ShowMatchSummary() )
return false;
if ( TFGameRules()->GetRoundRestartTime() > -1.f )
{
float flTime = TFGameRules()->GetRoundRestartTime() - gpGlobals->curtime;
if ( flTime <= 10.f )
return false;
}
}
return CHudElement::ShouldDraw();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CHudItemAttributeTracker::FireGameEvent( IGameEvent *pEvent )
{
if ( FStrEq( pEvent->GetName(), "player_spawn" )
|| FStrEq( pEvent->GetName(), "inventory_updated" )
|| FStrEq( pEvent->GetName(), "client_disconnect" )
|| FStrEq( pEvent->GetName(), "localplayer_changeclass" )
|| FStrEq( pEvent->GetName(), "quest_objective_completed" ) )
{
InvalidateLayout();
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CHudItemAttributeTracker::HandleSOEvent( const CSteamID & steamIDOwner, const CSharedObject *pObject, ETrackerHandling_t eHandling )
{
// We only care about items!
if( pObject->GetTypeID() != CEconItem::k_nTypeID )
return;
const CEconItem *pItem = (CEconItem *)pObject;
// We only care about quests
if ( pItem->GetItemDefinition()->GetQuestDef() == NULL )
return;
// We dont do anything with trackers for unidentified quests
if ( IsQuestItemUnidentified( pItem ) )
return;
CItemTrackerPanel* pTracker = NULL;
switch ( eHandling )
{
case TRACKER_CREATE:
case TRACKER_UPDATE:
FindTrackerForItem( pItem, &pTracker, true );
if ( pTracker )
{
pTracker->SetItem( pItem );
}
break;
case TRACKER_REMOVE:
FindTrackerForItem( pItem, &pTracker, false );
if ( pTracker )
{
m_mapTrackers.Remove( pItem->GetItemID() );
pTracker->MarkForDeletion();
}
break;
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CHudItemAttributeTracker::FindTrackerForItem( const CEconItem* pItem, CItemTrackerPanel** ppTracker, bool bCreateIfNotFound )
{
(*ppTracker) = NULL;
bool bCreatedNew = false;
auto idx = m_mapTrackers.Find( pItem->GetItemID() );
if ( idx == m_mapTrackers.InvalidIndex() && bCreateIfNotFound )
{
(*ppTracker) = new CItemTrackerPanel( this
, "ItemTrackerPanel"
, pItem
, pItem->GetItemDefinition()->GetQuestDef()->GetQuestTheme()->GetInGameTrackerResFile() );
(*ppTracker)->InvalidateLayout( true, true );
m_mapTrackers.Insert( pItem->GetItemID(), (*ppTracker) );
bCreatedNew = true;
}
else if ( idx != m_mapTrackers.InvalidIndex() )
{
(*ppTracker) = m_mapTrackers[ idx ];
}
return bCreatedNew;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CHudItemAttributeTracker::LevelInit( void )
{
// We want to listen for our player's SO cache updates
if ( steamapicontext && steamapicontext->SteamUser() )
{
CSteamID steamID = steamapicontext->SteamUser()->GetSteamID();
GCClientSystem()->GetGCClient()->AddSOCacheListener( steamID, this );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CHudItemAttributeTracker::LevelShutdown( void )
{
if ( steamapicontext && steamapicontext->SteamUser() )
{
CSteamID steamID = steamapicontext->SteamUser()->GetSteamID();
GCClientSystem()->GetGCClient()->RemoveSOCacheListener( steamID, this );
}
} | 0 | 0.983005 | 1 | 0.983005 | game-dev | MEDIA | 0.702496 | game-dev,desktop-app | 0.955953 | 1 | 0.955953 |
Fluorohydride/ygopro-scripts | 3,220 | c52068432.lua | --トリシューラの影霊衣
function c52068432.initial_effect(c)
c:EnableReviveLimit()
--cannot special summon
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e1:SetCode(EFFECT_SPSUMMON_CONDITION)
e1:SetValue(aux.ritlimit)
c:RegisterEffect(e1)
--negate
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(52068432,0))
e2:SetCategory(CATEGORY_NEGATE)
e2:SetType(EFFECT_TYPE_QUICK_O)
e2:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DAMAGE_CAL)
e2:SetCode(EVENT_CHAINING)
e2:SetRange(LOCATION_HAND)
e2:SetCountLimit(1,52068432)
e2:SetCondition(c52068432.negcon)
e2:SetCost(c52068432.negcost)
e2:SetTarget(c52068432.negtg)
e2:SetOperation(c52068432.negop)
c:RegisterEffect(e2)
--remove
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(52068432,1))
e3:SetCategory(CATEGORY_REMOVE)
e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e3:SetCode(EVENT_SPSUMMON_SUCCESS)
e3:SetCountLimit(1,52068433)
e3:SetCondition(c52068432.remcon)
e3:SetTarget(c52068432.remtg)
e3:SetOperation(c52068432.remop)
c:RegisterEffect(e3)
end
function c52068432.mat_filter(c)
return not c:IsLevel(9)
end
function c52068432.tfilter(c,tp)
return c:IsFaceup() and c:IsSetCard(0xb4) and c:IsControler(tp) and c:IsLocation(LOCATION_MZONE)
end
function c52068432.negcon(e,tp,eg,ep,ev,re,r,rp)
if not re:IsHasProperty(EFFECT_FLAG_CARD_TARGET) then return false end
local g=Duel.GetChainInfo(ev,CHAININFO_TARGET_CARDS)
return g and g:IsExists(c52068432.tfilter,1,nil,tp) and Duel.IsChainNegatable(ev)
end
function c52068432.negcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():IsDiscardable() end
Duel.SendtoGrave(e:GetHandler(),REASON_COST+REASON_DISCARD)
end
function c52068432.negtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_NEGATE,eg,1,0,0)
end
function c52068432.negop(e,tp,eg,ep,ev,re,r,rp)
Duel.NegateActivation(ev)
end
function c52068432.remcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():IsSummonType(SUMMON_TYPE_RITUAL)
end
function c52068432.remtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(Card.IsAbleToRemove,tp,0,LOCATION_HAND,1,nil)
and Duel.IsExistingMatchingCard(Card.IsAbleToRemove,tp,0,LOCATION_ONFIELD,1,nil)
and Duel.IsExistingMatchingCard(Card.IsAbleToRemove,tp,0,LOCATION_GRAVE,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_REMOVE,nil,1,0,LOCATION_ONFIELD+LOCATION_GRAVE+LOCATION_HAND)
end
function c52068432.remop(e,tp,eg,ep,ev,re,r,rp)
local g1=Duel.GetMatchingGroup(Card.IsAbleToRemove,tp,0,LOCATION_HAND,nil)
local g2=Duel.GetMatchingGroup(Card.IsAbleToRemove,tp,0,LOCATION_ONFIELD,nil)
local g3=Duel.GetMatchingGroup(Card.IsAbleToRemove,tp,0,LOCATION_GRAVE,nil)
if g1:GetCount()>0 and g2:GetCount()>0 and g3:GetCount()>0 then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local sg1=g1:RandomSelect(tp,1)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local sg2=g2:Select(tp,1,1,nil)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local sg3=g3:Select(tp,1,1,nil)
sg1:Merge(sg2)
sg1:Merge(sg3)
Duel.HintSelection(sg1)
Duel.Remove(sg1,POS_FACEUP,REASON_EFFECT)
end
end
| 0 | 0.935981 | 1 | 0.935981 | game-dev | MEDIA | 0.989699 | game-dev | 0.96452 | 1 | 0.96452 |
project-topaz/topaz | 1,328 | scripts/globals/items/tube_of_clear_salve_i.lua | -----------------------------------------
-- ID: 5837
-- Item: tube_of_clear_salve_i
-- Item Effect: Instantly removes 1-2 negative status effects at random from pet
-----------------------------------------
require("scripts/globals/settings")
require("scripts/globals/msg")
function onItemCheck(target)
if not target:hasPet() then
return tpz.msg.basic.REQUIRES_A_PET
end
return 0
end
function onItemUse(target)
local pet = target:getPet()
local effects =
{
tpz.effect.PETRIFICATION,
tpz.effect.SILENCE,
tpz.effect.BANE,
tpz.effect.CURSE_II,
tpz.effect.CURSE_I,
tpz.effect.PARALYSIS,
tpz.effect.PLAGUE,
tpz.effect.POISON,
tpz.effect.DISEASE,
tpz.effect.BLINDNESS
}
local count = math.random(1, 2)
local statusEffectTable = utils.shuffle(effects)
local function removeStatus()
for _, effect in ipairs(statusEffectTable) do
if pet:delStatusEffect(effect) then return true end
end
if pet:eraseStatusEffect() ~= 255 then return true end
return false
end
local removed = 0
for i = 0, count do
if not removeStatus() then break end
removed = removed + 1
if removed >= count then break end
end
return removed
end
| 0 | 0.768604 | 1 | 0.768604 | game-dev | MEDIA | 0.910365 | game-dev | 0.892088 | 1 | 0.892088 |
Unity-Technologies/UnityCsReference | 23,844 | Modules/UIElements/Core/Events/EventBase.cs | // Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using JetBrains.Annotations;
using UnityEngine.UIElements.Experimental;
namespace UnityEngine.UIElements
{
/// <summary>
/// The base class for all UIElements events. The class implements IDisposable to ensure proper release of the event from the pool and of any unmanaged resources, when necessary.
/// </summary>
public abstract class EventBase : IDisposable
{
private static long s_LastTypeId = 0;
/// <summary>
/// Registers an event class to the event type system.
/// </summary>
/// <returns>The type ID.</returns>
protected static long RegisterEventType() { return ++s_LastTypeId; }
/// <summary>
/// Retrieves the type ID for this event instance.
/// </summary>
/// <remarks>
/// This property provides an alternative to the `is` operator
/// for checking whether a given event is of the expected type
/// on platforms or build settings where that operator has performance overhead.
/// </remarks>
public virtual long eventTypeId => -1;
[Flags]
internal enum EventPropagation
{
None = 0,
Bubbles = 1,
TricklesDown = 2,
SkipDisabledElements = 4,
BubblesOrTricklesDown = Bubbles | TricklesDown,
}
[Flags]
enum LifeCycleStatus
{
None = 0,
PropagationStopped = 1,
ImmediatePropagationStopped = 2,
Dispatching = 4,
Pooled = 8,
IMGUIEventIsValid = 16,
PropagateToIMGUI = 32,
Dispatched = 64,
Processed = 128,
ProcessedByFocusController = 256,
}
internal int eventCategories { get; }
static ulong s_NextEventId = 0;
// Read-only state
/// <summary>
/// The time when the event was created, in milliseconds.
/// </summary>
/// <remarks>
/// This value is relative to the start time of the current application.
/// </remarks>
public long timestamp { get; private set; }
internal ulong eventId { get; private set; }
internal ulong triggerEventId { get; private set; }
internal void SetTriggerEventId(ulong id)
{
triggerEventId = id;
}
internal EventPropagation propagation { get; set; }
LifeCycleStatus lifeCycleStatus { get; set; }
[Obsolete("Override PreDispatch(IPanel panel) instead.")]
protected virtual void PreDispatch() {}
/// <summary>
/// Allows subclasses to perform custom logic before the event is dispatched.
/// </summary>
/// <param name="panel">The panel where the event will be dispatched.</param>
protected internal virtual void PreDispatch(IPanel panel)
{
#pragma warning disable 618
PreDispatch();
#pragma warning restore 618
}
[Obsolete("Override PostDispatch(IPanel panel) instead.")]
protected virtual void PostDispatch() {}
/// <summary>
/// Allows subclasses to perform custom logic after the event has been dispatched.
/// </summary>
/// <param name="panel">The panel where the event has been dispatched.</param>
protected internal virtual void PostDispatch(IPanel panel)
{
#pragma warning disable 618
PostDispatch();
#pragma warning restore 618
processed = true;
}
internal virtual void Dispatch([NotNull] BaseVisualElementPanel panel)
{
EventDispatchUtilities.DefaultDispatch(this, panel);
}
/// <summary>
/// Returns whether this event type bubbles up in the event propagation path during the BubbleUp phase.
/// </summary>
/// <remarks>
/// Refer to the [[wiki:UIE-Events-Dispatching|Dispatch events]] manual page for more information and examples.
/// </remarks>
/// <seealso cref="PropagationPhase.BubbleUp"/>
public bool bubbles
{
get { return (propagation & EventPropagation.Bubbles) != 0; }
protected set
{
if (value)
{
propagation |= EventPropagation.Bubbles;
}
else
{
propagation &= ~EventPropagation.Bubbles;
}
}
}
/// <summary>
/// Returns whether this event is sent down the event propagation path during the TrickleDown phase.
/// </summary>
/// <remarks>
/// Refer to the [[wiki:UIE-Events-Dispatching|Dispatch events]] manual page for more information and examples.
/// </remarks>
/// <seealso cref="PropagationPhase.TrickleDown"/>
public bool tricklesDown
{
get { return (propagation & EventPropagation.TricklesDown) != 0; }
protected set
{
if (value)
{
propagation |= EventPropagation.TricklesDown;
}
else
{
propagation &= ~EventPropagation.TricklesDown;
}
}
}
internal bool skipDisabledElements
{
get { return (propagation & EventPropagation.SkipDisabledElements) != 0; }
set
{
if (value)
{
propagation |= EventPropagation.SkipDisabledElements;
}
else
{
propagation &= ~EventPropagation.SkipDisabledElements;
}
}
}
internal bool bubblesOrTricklesDown => (propagation & EventPropagation.BubblesOrTricklesDown) != 0;
[Bindings.VisibleToOtherModules("UnityEditor.UIBuilderModule")]
internal VisualElement elementTarget
{
get;
set;
}
/// <summary>
/// The target visual element that received this event. Unlike currentTarget, this target does not change when
/// the event is sent to other elements along the propagation path.
/// </summary>
public IEventHandler target
{
get => elementTarget;
set => elementTarget = value as VisualElement;
}
/// <summary>
/// Returns true if <see cref="StopPropagation"/> or <see cref="StopImmediatePropagation"/>
/// was called for this event.
/// </summary>
public bool isPropagationStopped
{
get { return (lifeCycleStatus & LifeCycleStatus.PropagationStopped) != LifeCycleStatus.None; }
private set
{
if (value)
{
lifeCycleStatus |= LifeCycleStatus.PropagationStopped;
}
else
{
lifeCycleStatus &= ~LifeCycleStatus.PropagationStopped;
}
}
}
/// <summary>
/// Stops the propagation of the event to other targets.
/// All subscribers to the event on this target still receive the event.
/// </summary>
/// <remarks>
/// The event is not sent to other elements along the propagation path.
/// If the propagation is in the <see cref="PropagationPhase.TrickleDown"/> phase,
/// this prevents event handlers from executing on children of the <see cref="EventBase.currentTarget"/>,
/// including on the event's <see cref="EventBase.target"/> itself, and prevents all event handlers using the
/// <see cref="TrickleDown.NoTrickleDown"/> option from executing
/// (see [[CallbackEventHandler.RegisterCallback]]).
/// If the propagation is in the <see cref="PropagationPhase.BubbleUp"/> phase,
/// this prevents event handlers from executing on parents of the <see cref="EventBase.currentTarget"/>.
///
/// This method has the same effect as <see cref="EventBase.StopImmediatePropagation"/>
/// except on execution of other event handlers on the <see cref="EventBase.currentTarget"/>.
///
/// Calling this method does not prevent some internal actions to be processed,
/// such as an element getting focused as a result of a <see cref="PointerDownEvent"/>.
///
/// Refer to the [[wiki:UIE-Events-Dispatching|Dispatch events]] manual page for more information and examples.
/// </remarks>
/// <seealso cref="EventBase.StopImmediatePropagation"/>
public void StopPropagation()
{
isPropagationStopped = true;
}
/// <summary>
/// Indicates whether <see cref="StopImmediatePropagation"/> was called for this event.
/// </summary>
/// <seealso cref="isPropagationStopped"/>
public bool isImmediatePropagationStopped
{
get { return (lifeCycleStatus & LifeCycleStatus.ImmediatePropagationStopped) != LifeCycleStatus.None; }
private set
{
if (value)
{
lifeCycleStatus |= LifeCycleStatus.ImmediatePropagationStopped;
}
else
{
lifeCycleStatus &= ~LifeCycleStatus.ImmediatePropagationStopped;
}
}
}
/// <summary>
/// Stops the propagation of the event to other targets, and
/// prevents other subscribers to the event on this target to receive the event.
/// </summary>
/// <remarks>
/// The event is not sent to other elements along the propagation path.
/// If the propagation is in the <see cref="PropagationPhase.TrickleDown"/> phase,
/// this prevents event handlers from executing on children of the <see cref="EventBase.currentTarget"/>,
/// including on the event's <see cref="EventBase.target"/> itself, and prevents all event handlers using the
/// <see cref="TrickleDown.NoTrickleDown"/> option from executing
/// (see [[CallbackEventHandler.RegisterCallback]]).
/// If the propagation is in the <see cref="PropagationPhase.BubbleUp"/> phase,
/// this prevents event handlers from executing on parents of the <see cref="EventBase.currentTarget"/>.
///
/// This method has the same effect as <see cref="EventBase.StopPropagation"/>
/// except on execution of other event handlers on the <see cref="EventBase.currentTarget"/>.
///
/// Calling this method does not prevent some internal actions to be processed,
/// such as an element getting focused as a result of a <see cref="PointerDownEvent"/>.
///
/// Refer to the [[wiki:UIE-Events-Dispatching|Dispatch events]] manual page for more information and examples.
/// </remarks>
/// <seealso cref="EventBase.StopPropagation"/>
public void StopImmediatePropagation()
{
isPropagationStopped = true;
isImmediatePropagationStopped = true;
}
/// <summary>
/// Returns true if the default actions should not be executed for this event.
/// </summary>
[Obsolete("Use isPropagationStopped. Before proceeding, make sure you understand the latest changes to " +
"UIToolkit event propagation rules by visiting Unity's manual page " +
"https://docs.unity3d.com/Manual/UIE-Events-Dispatching.html")]
public bool isDefaultPrevented => isPropagationStopped;
/// <summary>
/// Indicates whether the default actions are prevented from being executed for this event.
/// </summary>
[Obsolete("Use StopPropagation and/or FocusController.IgnoreEvent. Before proceeding, make sure you understand the latest changes to " +
"UIToolkit event propagation rules by visiting Unity's manual page " +
"https://docs.unity3d.com/Manual/UIE-Events-Dispatching.html")]
public void PreventDefault()
{
StopPropagation();
elementTarget?.focusController?.IgnoreEvent(this);
}
// Propagation state
/// <summary>
/// The current propagation phase for this event.
/// </summary>
public PropagationPhase propagationPhase { get; internal set; }
IEventHandler m_CurrentTarget;
/// <summary>
/// The current target of the event. This is the VisualElement, in the propagation path, for which event handlers are currently being executed.
/// </summary>
public virtual IEventHandler currentTarget
{
get { return m_CurrentTarget; }
internal set
{
m_CurrentTarget = value;
if (imguiEvent != null)
{
var element = currentTarget as VisualElement;
if (element != null)
{
imguiEvent.mousePosition = element.WorldToLocal3D(originalMousePosition);
}
else
{
imguiEvent.mousePosition = originalMousePosition;
}
}
}
}
/// <summary>
/// Indicates whether the event is being dispatched to a visual element. An event cannot be redispatched while it being dispatched. If you need to recursively dispatch an event, it is recommended that you use a copy of the event.
/// </summary>
public bool dispatch
{
get { return (lifeCycleStatus & LifeCycleStatus.Dispatching) != LifeCycleStatus.None; }
internal set
{
if (value)
{
lifeCycleStatus |= LifeCycleStatus.Dispatching;
dispatched = true;
}
else
{
lifeCycleStatus &= ~LifeCycleStatus.Dispatching;
}
}
}
internal void MarkReceivedByDispatcher()
{
Debug.Assert(dispatched == false, "Events cannot be dispatched more than once.");
dispatched = true;
}
bool dispatched
{
get { return (lifeCycleStatus & LifeCycleStatus.Dispatched) != LifeCycleStatus.None; }
set
{
if (value)
{
lifeCycleStatus |= LifeCycleStatus.Dispatched;
}
else
{
lifeCycleStatus &= ~LifeCycleStatus.Dispatched;
}
}
}
internal bool processed
{
get { return (lifeCycleStatus & LifeCycleStatus.Processed) != LifeCycleStatus.None; }
private set
{
if (value)
{
lifeCycleStatus |= LifeCycleStatus.Processed;
}
else
{
lifeCycleStatus &= ~LifeCycleStatus.Processed;
}
}
}
internal bool processedByFocusController
{
get { return (lifeCycleStatus & LifeCycleStatus.ProcessedByFocusController) != LifeCycleStatus.None; }
set
{
if (value)
{
lifeCycleStatus |= LifeCycleStatus.ProcessedByFocusController;
}
else
{
lifeCycleStatus &= ~LifeCycleStatus.ProcessedByFocusController;
}
}
}
internal bool propagateToIMGUI
{
get { return (lifeCycleStatus & LifeCycleStatus.PropagateToIMGUI) != LifeCycleStatus.None; }
set
{
if (value)
{
lifeCycleStatus |= LifeCycleStatus.PropagateToIMGUI;
}
else
{
lifeCycleStatus &= ~LifeCycleStatus.PropagateToIMGUI;
}
}
}
private Event m_ImguiEvent;
// Since we recycle events (in their pools) and we do not free/reallocate a new imgui event
// at each recycling (m_ImguiEvent is never null), we use this flag to know whether m_ImguiEvent
// represents a valid Event.
bool imguiEventIsValid
{
get { return (lifeCycleStatus & LifeCycleStatus.IMGUIEventIsValid) != LifeCycleStatus.None; }
set
{
if (value)
{
lifeCycleStatus |= LifeCycleStatus.IMGUIEventIsValid;
}
else
{
lifeCycleStatus &= ~LifeCycleStatus.IMGUIEventIsValid;
}
}
}
// We aim to make this internal.
/// <summary>
/// The IMGUIEvent at the source of this event. The source can be null since not all events are generated by IMGUI.
/// </summary>
public /*internal*/ Event imguiEvent
{
get { return imguiEventIsValid ? m_ImguiEvent : null; }
protected set
{
if (m_ImguiEvent == null)
{
m_ImguiEvent = new Event();
}
if (value != null)
{
m_ImguiEvent.CopyFrom(value);
imguiEventIsValid = true;
originalMousePosition = value.mousePosition; // when assigned, it is assumed that the imguievent is not touched and therefore in world coordinates.
}
else
{
imguiEventIsValid = false;
}
}
}
/// <summary>
/// The original mouse position of the IMGUI event, before it is transformed to the current target local coordinates.
/// </summary>
public Vector2 originalMousePosition { get; private set; }
internal EventDebugger eventLogger { get; set; }
internal bool log => eventLogger != null;
/// <summary>
/// Resets all event members to their initial values.
/// </summary>
protected virtual void Init()
{
LocalInit();
}
void LocalInit()
{
timestamp = Panel.TimeSinceStartupMs();
triggerEventId = 0;
eventId = s_NextEventId++;
propagation = EventPropagation.None;
elementTarget = null;
isPropagationStopped = false;
isImmediatePropagationStopped = false;
propagationPhase = default;
originalMousePosition = Vector2.zero;
m_CurrentTarget = null;
dispatch = false;
propagateToIMGUI = true;
dispatched = false;
processed = false;
processedByFocusController = false;
imguiEventIsValid = false;
pooled = false;
eventLogger = null;
}
/// <summary>
/// Constructor. Avoid creating new event instances. Instead, use GetPooled() to get an instance from a pool of reusable event instances.
/// </summary>
protected EventBase() : this(EventCategory.Default)
{
}
internal EventBase(EventCategory category)
{
eventCategories = 1 << (int) category;
m_ImguiEvent = null;
LocalInit();
}
/// <summary>
/// Whether the event is allocated from a pool of events.
/// </summary>
protected bool pooled
{
get { return (lifeCycleStatus & LifeCycleStatus.Pooled) != LifeCycleStatus.None; }
set
{
if (value)
{
lifeCycleStatus |= LifeCycleStatus.Pooled;
}
else
{
lifeCycleStatus &= ~LifeCycleStatus.Pooled;
}
}
}
internal abstract void Acquire();
/// <summary>
/// Implementation of IDisposable.
/// </summary>
public abstract void Dispose();
}
/// <summary>
/// Generic base class for events, implementing event pooling and automatic registration to the event type system.
/// </summary>
[EventCategory(EventCategory.Default)]
public abstract class EventBase<T> : EventBase where T : EventBase<T>, new()
{
static readonly long s_TypeId = RegisterEventType();
static readonly ObjectPool<T> s_Pool = new ObjectPool<T>(() => new T());
internal static void SetCreateFunction(Func<T> createMethod)
{
s_Pool.CreateFunc = createMethod;
}
int m_RefCount;
protected EventBase() : base(EventCategory)
{
m_RefCount = 0;
}
/// <summary>
/// Retrieves the type ID for this event instance.
/// </summary>
/// <returns>The type ID.</returns>
public static long TypeId()
{
return s_TypeId;
}
internal static readonly EventCategory EventCategory = EventInterestReflectionUtils.GetEventCategory(typeof(T));
/// <summary>
/// Resets all event members to their initial values.
/// </summary>
protected override void Init()
{
base.Init();
if (m_RefCount != 0)
{
Debug.Log("Event improperly released.");
m_RefCount = 0;
}
}
/// <summary>
/// Gets an event from the event pool. Use this function instead of creating new events. Events obtained using this method need to be released back to the pool. You can use `Dispose()` to release them.
/// </summary>
/// <returns>An initialized event.</returns>
public static T GetPooled()
{
T t = s_Pool.Get();
t.Init();
t.pooled = true;
t.Acquire();
return t;
}
internal static T GetPooled(EventBase e)
{
T t = GetPooled();
if (e != null)
{
t.SetTriggerEventId(e.eventId);
}
return t;
}
static void ReleasePooled(T evt)
{
if (evt.pooled)
{
// Reset the event before pooling to avoid leaking VisualElement
evt.Init();
s_Pool.Release(evt);
// To avoid double release from pool
evt.pooled = false;
}
}
internal override void Acquire()
{
m_RefCount++;
}
/// <summary>
/// Implementation of IDispose.
/// </summary>
/// <remarks>
/// If the event was instantiated from an event pool, the event is released when Dispose is called.
/// </remarks>
public sealed override void Dispose()
{
if (--m_RefCount == 0)
{
ReleasePooled((T)this);
}
}
/// <summary>
/// See <see cref="EventBase.eventTypeId"/>.
/// </summary>
public override long eventTypeId => s_TypeId;
}
}
| 0 | 0.881648 | 1 | 0.881648 | game-dev | MEDIA | 0.827989 | game-dev | 0.783024 | 1 | 0.783024 |
JukeboxMC/JukeboxMC | 10,288 | JukeboxMC-Server/src/main/kotlin/org/jukeboxmc/server/network/handler/ItemStackRequestHandler.kt | package org.jukeboxmc.server.network.handler
import org.cloudburstmc.protocol.bedrock.data.EncodingSettings
import org.cloudburstmc.protocol.bedrock.data.inventory.ContainerSlotType
import org.cloudburstmc.protocol.bedrock.data.inventory.FullContainerName
import org.cloudburstmc.protocol.bedrock.data.inventory.itemstack.request.ItemStackRequest
import org.cloudburstmc.protocol.bedrock.data.inventory.itemstack.request.action.ConsumeAction
import org.cloudburstmc.protocol.bedrock.data.inventory.itemstack.request.action.ItemStackRequestAction
import org.cloudburstmc.protocol.bedrock.data.inventory.itemstack.request.action.ItemStackRequestActionType
import org.cloudburstmc.protocol.bedrock.data.inventory.itemstack.response.ItemStackResponse
import org.cloudburstmc.protocol.bedrock.data.inventory.itemstack.response.ItemStackResponseContainer
import org.cloudburstmc.protocol.bedrock.data.inventory.itemstack.response.ItemStackResponseSlot
import org.cloudburstmc.protocol.bedrock.data.inventory.itemstack.response.ItemStackResponseStatus
import org.cloudburstmc.protocol.bedrock.packet.ItemStackRequestPacket
import org.cloudburstmc.protocol.bedrock.packet.ItemStackResponsePacket
import org.jukeboxmc.api.extensions.asType
import org.jukeboxmc.api.extensions.isType
import org.jukeboxmc.api.inventory.Inventory
import org.jukeboxmc.api.item.Item
import org.jukeboxmc.api.item.ItemType
import org.jukeboxmc.server.JukeboxServer
import org.jukeboxmc.server.inventory.ContainerInventory
import org.jukeboxmc.server.network.stackaction.StackAction
import org.jukeboxmc.server.network.stackaction.StackActionHandler
import org.jukeboxmc.server.player.JukeboxPlayer
import java.util.*
class ItemStackRequestHandler : PacketHandler<ItemStackRequestPacket> {
override fun handle(packet: ItemStackRequestPacket, server: JukeboxServer, player: JukeboxPlayer) {
player.getSession().peer.codecHelper.encodingSettings = EncodingSettings.builder()
.maxListSize(Int.MAX_VALUE)
.maxByteArraySize(Int.MAX_VALUE)
.maxNetworkNBTSize(Int.MAX_VALUE)
.maxItemNBTSize(Int.MAX_VALUE)
.maxStringLength(Int.MAX_VALUE)
.build()
val responses: MutableList<ItemStackResponse> = mutableListOf()
for (request in packet.requests) {
this.handleItemStackRequest(request, player, responses)
}
}
fun handleItemStackRequest(
request: ItemStackRequest,
player: JukeboxPlayer,
responses: MutableList<ItemStackResponse>
) {
val itemEntryMap: MutableMap<Int, ConsumeActionData> = mutableMapOf()
for (action in request.actions) {
if (action.type == ItemStackRequestActionType.CONSUME) {
val consumeAction = handleConsumeAction(player, action as ConsumeAction)
if (!itemEntryMap.containsKey(request.requestId)) {
itemEntryMap[request.requestId] = consumeAction
} else {
itemEntryMap[request.requestId]?.responseSlot?.add(consumeAction.responseSlot[0])
}
} else {
val stackAction = StackActionHandler.getPacketHandler(action.type)
if (stackAction != null && stackAction.isType<StackAction<ItemStackRequestAction>>()) {
val responseList =
stackAction.asType<StackAction<ItemStackRequestAction>>().handle(action, player, this, request)
if (responseList.isNotEmpty()) {
responses.addAll(responseList)
}
} else if (action.type != ItemStackRequestActionType.CRAFT_RESULTS_DEPRECATED) {
JukeboxServer.getInstance().getLogger()
.info("Unhandelt Action: " + action.javaClass.simpleName + " : " + action.type)
}
}
}
val itemStackResponsePacket = ItemStackResponsePacket()
val containerEntryMap: MutableMap<Int, MutableList<ItemStackResponseContainer>> = HashMap()
if (itemEntryMap.isNotEmpty()) {
for (respons in responses) {
containerEntryMap[respons.requestId] = respons.containers
}
if (containerEntryMap.containsKey(request.requestId)) {
containerEntryMap[request.requestId]?.add(
0,
ItemStackResponseContainer(
itemEntryMap[request.requestId]!!.containerSlotType,
itemEntryMap[request.requestId]!!.responseSlot,
FullContainerName(itemEntryMap[request.requestId]!!.containerSlotType, 0)
)
)
}
for ((key, value) in containerEntryMap) {
if (value.isNotEmpty()) {
itemStackResponsePacket.entries.add(ItemStackResponse(ItemStackResponseStatus.OK, key, value))
} else {
itemStackResponsePacket.entries.add(
ItemStackResponse(
ItemStackResponseStatus.ERROR,
key,
emptyList()
)
)
}
}
} else {
itemStackResponsePacket.entries.addAll(responses)
}
player.sendPacket(itemStackResponsePacket)
}
private fun handleConsumeAction(
player: JukeboxPlayer,
action: ConsumeAction
): ConsumeActionData {
val amount = action.count
val source = action.source
var sourceItem: Item = this.getItem(player, source.container, source.slot) ?: return ConsumeActionData(
source.container,
mutableListOf()
)
sourceItem.setAmount(sourceItem.getAmount() - amount)
if (sourceItem.getAmount() <= 0) {
sourceItem = Item.create(ItemType.AIR)
}
this.setItem(player, source.container, source.slot, sourceItem)
val containerEntryList: MutableList<ItemStackResponseSlot> = LinkedList()
containerEntryList.add(
ItemStackResponseSlot(
source.slot,
source.slot,
sourceItem.getAmount(),
sourceItem.getStackNetworkId(),
sourceItem.getDisplayName(),
sourceItem.getDurability()
)
)
return ConsumeActionData(source.container, containerEntryList)
}
fun getInventory(player: JukeboxPlayer, containerSlotType: ContainerSlotType): Inventory? {
return when (containerSlotType) {
ContainerSlotType.CREATED_OUTPUT -> player.getCreativeCacheInventory()
ContainerSlotType.CURSOR -> player.getCursorInventory()
ContainerSlotType.INVENTORY,
ContainerSlotType.HOTBAR,
ContainerSlotType.HOTBAR_AND_INVENTORY -> player.getInventory()
ContainerSlotType.ARMOR -> player.getArmorInventory()
ContainerSlotType.OFFHAND -> player.getCurrentInventory()
ContainerSlotType.CARTOGRAPHY_ADDITIONAL,
ContainerSlotType.CARTOGRAPHY_INPUT,
ContainerSlotType.CARTOGRAPHY_RESULT -> player.getCartographyTableInventory()
ContainerSlotType.SMITHING_TABLE_INPUT,
ContainerSlotType.SMITHING_TABLE_RESULT,
ContainerSlotType.SMITHING_TABLE_TEMPLATE,
ContainerSlotType.SMITHING_TABLE_MATERIAL -> player.getSmithingTableInventory()
ContainerSlotType.ANVIL_INPUT,
ContainerSlotType.ANVIL_MATERIAL,
ContainerSlotType.ANVIL_RESULT -> player.getAnvilInventory()
ContainerSlotType.STONECUTTER_INPUT,
ContainerSlotType.STONECUTTER_RESULT -> player.getStoneCutterInventory()
ContainerSlotType.GRINDSTONE_ADDITIONAL,
ContainerSlotType.GRINDSTONE_INPUT,
ContainerSlotType.GRINDSTONE_RESULT -> player.getGrindstoneInventory()
ContainerSlotType.CRAFTING_INPUT -> player.getCraftingGridInventory()
ContainerSlotType.LOOM_DYE,
ContainerSlotType.LOOM_INPUT,
ContainerSlotType.LOOM_MATERIAL,
ContainerSlotType.LOOM_RESULT -> player.getLoomInventory()
ContainerSlotType.LEVEL_ENTITY,
ContainerSlotType.SMOKER_INGREDIENT,
ContainerSlotType.BARREL,
ContainerSlotType.BREWING_FUEL,
ContainerSlotType.BREWING_INPUT,
ContainerSlotType.BREWING_RESULT,
ContainerSlotType.FURNACE_FUEL,
ContainerSlotType.FURNACE_INGREDIENT,
ContainerSlotType.FURNACE_RESULT,
ContainerSlotType.BLAST_FURNACE_INGREDIENT,
ContainerSlotType.ENCHANTING_INPUT,
ContainerSlotType.ENCHANTING_MATERIAL -> player.getCurrentInventory()
else -> {
return null
}
}
}
fun getItem(player: JukeboxPlayer, containerSlotType: ContainerSlotType, slot: Int): Item? {
return when (containerSlotType) {
ContainerSlotType.CREATED_OUTPUT -> player.getCreativeCacheInventory().getItem(0)
else -> this.getInventory(player, containerSlotType)?.getItem(slot)
}
}
public fun setItem(
player: JukeboxPlayer,
containerSlotType: ContainerSlotType,
slot: Int,
item: Item,
sendContent: Boolean = true
) {
when (containerSlotType) {
ContainerSlotType.CURSOR -> {
player.getCursorInventory().setCursorItem(item)
}
ContainerSlotType.OFFHAND -> {
player.getOffHandInventory().setOffHandItem(item)
}
ContainerSlotType.CREATED_OUTPUT -> {
player.getCreativeCacheInventory().setItem(slot, item)
}
else -> (this.getInventory(player, containerSlotType) as ContainerInventory).setItem(
slot,
item,
sendContent
)
}
}
data class ConsumeActionData(
val containerSlotType: ContainerSlotType,
val responseSlot: MutableList<ItemStackResponseSlot>
)
} | 0 | 0.814712 | 1 | 0.814712 | game-dev | MEDIA | 0.929375 | game-dev | 0.964605 | 1 | 0.964605 |
thebracket/HandsOnRust | 4,819 | WinningAndLosing/losing/src/main.rs | #![warn(clippy::pedantic)]
mod components;
mod spawner;
mod map;
mod map_builder;
mod systems;
mod camera;
mod turn_state;
mod prelude {
pub use bracket_lib::prelude::*;
pub use legion::*;
pub use legion::world::SubWorld;
pub use legion::systems::CommandBuffer;
pub const SCREEN_WIDTH: i32 = 80;
pub const SCREEN_HEIGHT: i32 = 50;
pub const DISPLAY_WIDTH: i32 = SCREEN_WIDTH / 2;
pub const DISPLAY_HEIGHT: i32 = SCREEN_HEIGHT / 2;
pub use crate::components::*;
pub use crate::spawner::*;
pub use crate::map::*;
pub use crate::systems::*;
pub use crate::map_builder::*;
pub use crate::camera::*;
pub use crate::turn_state::*;
}
use prelude::*;
struct State {
ecs : World,
resources: Resources,
input_systems: Schedule,
player_systems: Schedule,
monster_systems: Schedule
}
impl State {
fn new() -> Self {
let mut ecs = World::default();
let mut resources = Resources::default();
let mut rng = RandomNumberGenerator::new();
let map_builder = MapBuilder::new(&mut rng);
spawn_player(&mut ecs, map_builder.player_start);
map_builder.rooms
.iter()
.skip(1)
.map(|r| r.center())
.for_each(|pos| spawn_monster(&mut ecs, &mut rng, pos));
resources.insert(map_builder.map);
resources.insert(Camera::new(map_builder.player_start));
resources.insert(TurnState::AwaitingInput);
Self {
ecs,
resources,
input_systems: build_input_scheduler(),
player_systems: build_player_scheduler(),
monster_systems: build_monster_scheduler()
}
}
fn game_over(&mut self, ctx: &mut BTerm) {
ctx.set_active_console(2);// (1)
ctx.print_color_centered(2, RED, BLACK, "Your quest has ended."); // (2)
ctx.print_color_centered(4, WHITE, BLACK,
"Slain by a monster, your hero's journey has come to a \
premature end.");
ctx.print_color_centered(5, WHITE, BLACK,
"The Amulet of Yala remains unclaimed, and your home town \
is not saved.");
ctx.print_color_centered(8, YELLOW, BLACK,
"Don't worry, you can always try again with a new hero.");
ctx.print_color_centered(9, GREEN, BLACK,
"Press 1 to play again.");
if let Some(VirtualKeyCode::Key1) = ctx.key {// (3)
self.ecs = World::default();// (4)
self.resources = Resources::default();
let mut rng = RandomNumberGenerator::new();
let map_builder = MapBuilder::new(&mut rng);
spawn_player(&mut self.ecs, map_builder.player_start);
map_builder.rooms
.iter()
.skip(1)
.map(|r| r.center())
.for_each(|pos| spawn_monster(&mut self.ecs, &mut rng, pos));
self.resources.insert(map_builder.map);
self.resources.insert(Camera::new(map_builder.player_start));
self.resources.insert(TurnState::AwaitingInput);// (5)
}
}
}
impl GameState for State {
fn tick(&mut self, ctx: &mut BTerm) {
ctx.set_active_console(0);
ctx.cls();
ctx.set_active_console(1);
ctx.cls();
ctx.set_active_console(2);
ctx.cls();
self.resources.insert(ctx.key);
ctx.set_active_console(0);
self.resources.insert(Point::from_tuple(ctx.mouse_pos()));
let current_state = self.resources.get::<TurnState>().unwrap().clone();
match current_state {
TurnState::AwaitingInput => self.input_systems.execute(&mut self.ecs, &mut self.resources),
TurnState::PlayerTurn => {
self.player_systems.execute(&mut self.ecs, &mut self.resources);
}
TurnState::MonsterTurn => {
self.monster_systems.execute(&mut self.ecs, &mut self.resources)
}
TurnState::GameOver => {
self.game_over(ctx);
}
}
render_draw_buffer(ctx).expect("Render error");
}
}
fn main() -> BError {
let context = BTermBuilder::new()
.with_title("Dungeon Crawler")
.with_fps_cap(30.0)
.with_dimensions(DISPLAY_WIDTH, DISPLAY_HEIGHT)
.with_tile_dimensions(32, 32)
.with_resource_path("resources/")
.with_font("dungeonfont.png", 32, 32)
.with_font("terminal8x8.png", 8, 8)
.with_simple_console(DISPLAY_WIDTH, DISPLAY_HEIGHT, "dungeonfont.png")
.with_simple_console_no_bg(DISPLAY_WIDTH, DISPLAY_HEIGHT, "dungeonfont.png")
.with_simple_console_no_bg(SCREEN_WIDTH*2, SCREEN_HEIGHT*2, "terminal8x8.png")
.build()?;
main_loop(context, State::new())
}
| 0 | 0.807031 | 1 | 0.807031 | game-dev | MEDIA | 0.949633 | game-dev | 0.731092 | 1 | 0.731092 |
Creators-of-Create/Create | 1,027 | src/main/java/com/simibubi/create/compat/jei/ItemIcon.java | package com.simibubi.create.compat.jei;
import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.PoseStack;
import mezz.jei.api.gui.drawable.IDrawable;
import net.createmod.catnip.gui.element.GuiGameElement;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.world.item.ItemStack;
import java.util.function.Supplier;
public class ItemIcon implements IDrawable {
private Supplier<ItemStack> supplier;
private ItemStack stack;
public ItemIcon(Supplier<ItemStack> stack) {
this.supplier = stack;
}
@Override
public int getWidth() {
return 18;
}
@Override
public int getHeight() {
return 18;
}
@Override
public void draw(GuiGraphics graphics, int xOffset, int yOffset) {
PoseStack matrixStack = graphics.pose();
if (stack == null) {
stack = supplier.get();
}
RenderSystem.enableDepthTest();
matrixStack.pushPose();
matrixStack.translate(xOffset + 1, yOffset + 1, 0);
GuiGameElement.of(stack)
.render(graphics);
matrixStack.popPose();
}
}
| 0 | 0.716816 | 1 | 0.716816 | game-dev | MEDIA | 0.951795 | game-dev | 0.855629 | 1 | 0.855629 |
makeplane/plane | 2,007 | apps/web/core/components/stickies/layout/sticky.helpers.ts | import { extractInstruction } from "@atlaskit/pragmatic-drag-and-drop-hitbox/tree-item";
import { InstructionType, IPragmaticPayloadLocation, TDropTarget } from "@plane/types";
export type TargetData = {
id: string;
parentId: string | null;
isGroup: boolean;
isChild: boolean;
};
/**
* extracts the Payload and translates the instruction for the current dropTarget based on drag and drop payload
* @param dropTarget dropTarget for which the instruction is required
* @param source the dragging sticky data that is being dragged on the dropTarget
* @param location location includes the data of all the dropTargets the source is being dragged on
* @returns Instruction for dropTarget
*/
export const getInstructionFromPayload = (
dropTarget: TDropTarget,
source: TDropTarget,
location: IPragmaticPayloadLocation
): InstructionType | undefined => {
const dropTargetData = dropTarget?.data as TargetData;
const sourceData = source?.data as TargetData;
const allDropTargets = location?.current?.dropTargets;
// if all the dropTargets are greater than 1 meaning the source is being dragged on a group and its child at the same time
// and also if the dropTarget in question is also a group then, it should be a child of the current Droptarget
if (allDropTargets?.length > 1 && dropTargetData?.isGroup) return "make-child";
if (!dropTargetData || !sourceData) return undefined;
let instruction = extractInstruction(dropTargetData)?.type;
// If the instruction is blocked then set an instruction based on if dropTarget it is a child or not
if (instruction === "instruction-blocked") {
instruction = dropTargetData.isChild ? "reorder-above" : "make-child";
}
// if source that is being dragged is a group. A group cannon be a child of any other sticky,
// hence if current instruction is to be a child of dropTarget then reorder-above instead
if (instruction === "make-child" && sourceData.isGroup) instruction = "reorder-above";
return instruction;
};
| 0 | 0.860203 | 1 | 0.860203 | game-dev | MEDIA | 0.358413 | game-dev | 0.877111 | 1 | 0.877111 |
followingthefasciaplane/source-engine-diff-check | 2,374 | misc/game/server/cstrike/item_defuser.cpp | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: Defuser kit that drops from counter-strike CTS
//
//=============================================================================//
#include "cbase.h"
#include "items.h"
#include "cs_player.h"
class CItemDefuser : public CItem
{
public:
DECLARE_CLASS( CItemDefuser, CItem );
void Spawn( void );
void Precache( void );
void DefuserTouch( CBaseEntity *pOther );
void ActivateThink( void );
DECLARE_DATADESC();
};
LINK_ENTITY_TO_CLASS( item_defuser, CItemDefuser );
PRECACHE_REGISTER(item_defuser);
BEGIN_DATADESC( CItemDefuser )
//Functions
DEFINE_THINKFUNC( ActivateThink ),
DEFINE_ENTITYFUNC( DefuserTouch ),
END_DATADESC()
void CItemDefuser::Spawn( void )
{
Precache( );
SetModel( "models/weapons/w_defuser.mdl" );
BaseClass::Spawn();
SetNextThink( gpGlobals->curtime + 0.5f );
SetThink( &CItemDefuser::ActivateThink );
SetTouch( NULL );
}
void CItemDefuser::Precache( void )
{
PrecacheModel( "models/weapons/w_defuser.mdl" );
PrecacheScriptSound( "BaseCombatCharacter.ItemPickup2" );
}
void CItemDefuser::ActivateThink( void )
{
//since we can't stop the item from being touched while its in the air,
//activate 1 second after being dropped
SetTouch( &CItemDefuser::DefuserTouch );
SetThink( NULL );
}
void CItemDefuser::DefuserTouch( CBaseEntity *pOther )
{
if ( !pOther->IsPlayer() )
{
return;
}
//if( GetFlags() & FL_ONGROUND )
{
CCSPlayer *pPlayer = (CCSPlayer *)pOther;
if ( !pPlayer )
{
Assert( false );
return;
}
if( pPlayer->GetTeamNumber() == TEAM_CT && !pPlayer->HasDefuser() )
{
//=============================================================================
// HPE_BEGIN:
// [dwenger] Added for fun-fact support
//=============================================================================
pPlayer->GiveDefuser( true );
//=============================================================================
// HPE_END
//=============================================================================
if ( pPlayer->IsDead() == false )
{
CPASAttenuationFilter filter( pPlayer );
EmitSound( filter, entindex(), "BaseCombatCharacter.ItemPickup2" );
}
UTIL_Remove( this );
return;
}
}
}
| 0 | 0.922524 | 1 | 0.922524 | game-dev | MEDIA | 0.972588 | game-dev | 0.81806 | 1 | 0.81806 |
michaelmalaska/aarpg-tutorial | 1,867 | npc/scripts/npc_behavior_wander.gd | @tool
extends NPCBehavior
const DIRECTIONS = [ Vector2.UP, Vector2.RIGHT, Vector2.DOWN, Vector2.LEFT ]
@export var wander_range : int = 2 : set = _set_wander_range
@export var wander_speed : float = 30.0
@export var wander_duration : float = 1.0
@export var idle_duration : float = 1.0
var original_position : Vector2
func _ready() -> void:
if Engine.is_editor_hint():
return
super()
$CollisionShape2D.queue_free()
original_position = npc.global_position
func _process( _delta: float ) -> void:
if Engine.is_editor_hint():
return
#if abs( global_position.distance_to( original_position ) ) > wander_range * 32:
#npc.velocity *= -1
#npc.direction *= -1
#npc.update_direction( global_position + npc.direction )
#npc.update_animation()
func start() -> void:
# IDLE PHASE
if npc.do_behavior == false:
return
npc.state = "idle"
npc.velocity = Vector2.ZERO
npc.update_animation()
await get_tree().create_timer( randf() * idle_duration + idle_duration * 0.5 ).timeout
if npc.do_behavior == false:
return
# WALK PHASE
npc.state = "walk"
var _dir : Vector2 = DIRECTIONS[ randi_range(0,3) ]
if abs( global_position.distance_to( original_position ) ) > wander_range * 32:
var dir_to_area : Vector2 = global_position.direction_to( original_position )
var best_directions : Array[ float ]
for d in DIRECTIONS:
best_directions.append( d.dot( dir_to_area ) )
_dir = DIRECTIONS[ best_directions.find( best_directions.max() ) ]
pass
npc.direction = _dir
npc.velocity = wander_speed * _dir
npc.update_direction( global_position + _dir )
npc.update_animation()
await get_tree().create_timer( randf() * wander_duration + wander_duration * 0.5 ).timeout
# REPEAT
if npc.do_behavior == false:
return
start()
pass
func _set_wander_range( v : int ) -> void:
wander_range = v
$CollisionShape2D.shape.radius = v * 32.0
| 0 | 0.632985 | 1 | 0.632985 | game-dev | MEDIA | 0.988976 | game-dev | 0.954341 | 1 | 0.954341 |
Apress/build-your-own-2d-game-engine | 1,764 | BookSourceCode/Chapter9/9.2.RigidShapeImpulse/public_html/src/Engine/Utils/Interpolate.js | /*
* File: Interpolate.js
* Encapsulates linear interpolation
*/
/*jslint node: true, vars: true */
/*global gEngine: false, vec2: false, Math: false, mat4: false, vec3: false */
/* find out more about jslint: http://www.jslint.com/help.html */
"use strict";
// value: target for interpolation
// cycles: integer, how many cycle it should take for a value to change to final
// rate: the rate at which the value should change at each cycle
function Interpolate(value, cycles, rate) {
this.mCurrentValue = value; // begin value of interpolation
this.mFinalValue = value; // final value of interpolation
this.mCycles = cycles;
this.mRate = rate;
// if there is a new value to interpolate to, number of cycles left for interpolation
this.mCyclesLeft = 0;
}
// <editor-fold desc="Public Methods">
Interpolate.prototype.getValue = function () { return this.mCurrentValue; };
Interpolate.prototype.setFinalValue = function (v) {
this.mFinalValue = v;
this.mCyclesLeft = this.mCycles; // will trigger interpolation
};
Interpolate.prototype.updateInterpolation = function () {
if (this.mCyclesLeft <= 0) {
return;
}
this.mCyclesLeft--;
if (this.mCyclesLeft === 0) {
this.mCurrentValue = this.mFinalValue;
} else {
this._interpolateValue();
}
};
// stiffness of 1 switches off interpolation
Interpolate.prototype.configInterpolation = function (stiffness, duration) {
this.mRate = stiffness;
this.mCycles = duration;
};
// </editor-fold>
// subclass should override this function for non-scalar values
Interpolate.prototype._interpolateValue = function () {
this.mCurrentValue = this.mCurrentValue + this.mRate * (this.mFinalValue - this.mCurrentValue);
}; | 0 | 0.812588 | 1 | 0.812588 | game-dev | MEDIA | 0.354791 | game-dev | 0.765332 | 1 | 0.765332 |
glKarin/com.n0n3m4.diii4a | 2,364 | Q3E/src/main/jni/source/external/vpc/public/tier0/dbgflag.h | //========= Copyright 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose: This file sets all of our debugging flags. It should be
// called before all other header files.
//
// $NoKeywords: $
//=============================================================================//
#ifndef DBGFLAG_H
#define DBGFLAG_H
#ifdef _WIN32
#pragma once
#endif
// Here are all the flags we support:
// DBGFLAG_MEMORY: Enables our memory debugging system, which overrides malloc & free
// DBGFLAG_MEMORY_NEWDEL: Enables new / delete tracking for memory debug system. Requires DBGFLAG_MEMORY to be enabled.
// DBGFLAG_VALIDATE: Enables our recursive validation system for checking integrity and memory leaks
// DBGFLAG_ASSERT: Turns Assert on or off (when off, it isn't compiled at all)
// DBGFLAG_ASSERTFATAL: Turns AssertFatal on or off (when off, it isn't compiled at all)
// DBGFLAG_ASSERTDLG: Turns assert dialogs on or off and debug breaks on or off when not under the debugger.
// (Dialogs will always be on when process is being debugged.)
// DBGFLAG_STRINGS: Turns on hardcore string validation (slow but safe)
#undef DBGFLAG_MEMORY
#undef DBGFLAG_MEMORY_NEWDEL
#undef DBGFLAG_VALIDATE
#undef DBGFLAG_ASSERT
#undef DBGFLAG_ASSERTFATAL
#undef DBGFLAG_ASSERTDLG
#undef DBGFLAG_STRINGS
//-----------------------------------------------------------------------------
// Default flags for debug builds
//-----------------------------------------------------------------------------
#if defined( _DEBUG ) && !defined( PS3MEMOVERRIDEWRAP )
#define DBGFLAG_MEMORY
#ifdef _SERVER // only enable new & delete tracking for server; on client it conflicts with CRT mem leak tracking
#define DBGFLAG_MEMORY_NEWDEL
#endif
#ifdef STEAM
#define DBGFLAG_VALIDATE
#endif
#define DBGFLAG_ASSERT
#define DBGFLAG_ASSERTFATAL
#define DBGFLAG_ASSERTDLG
#define DBGFLAG_STRINGS
//-----------------------------------------------------------------------------
// Default flags for release builds
//-----------------------------------------------------------------------------
#else // _DEBUG
#ifdef STEAM
#define DBGFLAG_ASSERT
#endif
#define DBGFLAG_ASSERTFATAL // note: fatal asserts are enabled in release builds
#define DBGFLAG_ASSERTDLG
#endif // _DEBUG
#if defined( _CERT )
#define DBGFLAG_STRINGS_STRIP
#endif
#endif // DBGFLAG_H
| 0 | 0.734104 | 1 | 0.734104 | game-dev | MEDIA | 0.536231 | game-dev | 0.647077 | 1 | 0.647077 |
Citadel-Station-13/Citadel-Station-13 | 5,430 | code/modules/antagonists/clockcult/clock_items/soul_vessel.dm | //Soul vessel: An ancient positronic brain that serves only Ratvar.
/obj/item/mmi/posibrain/soul_vessel
name = "soul vessel"
desc = "A heavy brass cube, three inches to a side, with a single protruding cogwheel."
var/clockwork_desc = "A soul vessel, an ancient relic that can attract the souls of the damned or simply rip a mind from an unconscious or dead human.\n\
<span class='brass'>If active, can serve as a positronic brain, placable in cyborg shells or clockwork construct shells.</span>"
icon = 'icons/obj/clockwork_objects.dmi'
icon_state = "soul_vessel"
req_access = list()
braintype = "Servant"
begin_activation_message = "<span class='brass'>You activate the cogwheel. It hitches and stalls as it begins spinning.</span>"
success_message = "<span class='brass'>The cogwheel's rotation smooths out as the soul vessel activates.</span>"
fail_message = "<span class='warning'>The cogwheel creaks and grinds to a halt. Maybe you could try again?</span>"
new_role = "Soul Vessel"
welcome_message = "<span class='warning'>ALL PAST LIVES ARE FORGOTTEN.</span>\n\
<b>You are a soul vessel - a clockwork mind created by Ratvar, the Clockwork Justiciar.\n\
You answer to Ratvar and his servants. It is your discretion as to whether or not to answer to anyone else.\n\
The purpose of your existence is to further the goals of the servants and Ratvar himself. Above all else, serve Ratvar.</b>"
new_mob_message = "<span class='brass'>The soul vessel emits a jet of steam before its cogwheel smooths out.</span>"
dead_message = "<span class='deadsay'>Its cogwheel, scratched and dented, lies motionless.</span>"
recharge_message = "<span class='warning'>The soul vessel's internal geis capacitor is still recharging!</span>"
possible_names = list("Judge", "Guard", "Servant", "Smith", "Auger")
autoping = FALSE
resistance_flags = FIRE_PROOF | ACID_PROOF
force_replace_ai_name = TRUE
overrides_aicore_laws = TRUE
/obj/item/mmi/posibrain/soul_vessel/Initialize(mapload)
. = ..()
radio.on = FALSE
laws = new /datum/ai_laws/ratvar()
braintype = picked_name
GLOB.all_clockwork_objects += src
brainmob.add_blocked_language(subtypesof(/datum/language) - /datum/language/ratvar, LANGUAGE_CLOCKIE)
/obj/item/mmi/posibrain/soul_vessel/Destroy()
GLOB.all_clockwork_objects -= src
return ..()
/obj/item/mmi/posibrain/soul_vessel/examine(mob/user)
if((is_servant_of_ratvar(user) || isobserver(user)) && clockwork_desc)
desc = clockwork_desc
. = ..()
desc = initial(desc)
/obj/item/mmi/posibrain/soul_vessel/transfer_personality(mob/candidate)
. = ..()
if(.)
add_servant_of_ratvar(brainmob, TRUE)
/obj/item/mmi/posibrain/soul_vessel/attack_self(mob/living/user)
if(!is_servant_of_ratvar(user))
to_chat(user, "<span class='warning'>You fiddle around with [src], to no avail.</span>")
return FALSE
..()
/obj/item/mmi/posibrain/soul_vessel/attack(mob/living/target, mob/living/carbon/human/user)
if(!is_servant_of_ratvar(user) || !ishuman(target))
..()
return
if(QDELETED(brainmob))
return
if(brainmob.key)
to_chat(user, "<span class='nezbere'>\"This vessel is filled, friend. Provide it with a body.\"</span>")
return
if(is_servant_of_ratvar(target))
to_chat(user, "<span class='nezbere'>\"It would be more wise to revive your allies, friend.\"</span>")
return
var/mob/living/carbon/human/H = target
if(H.stat == CONSCIOUS)
to_chat(user, "<span class='warning'>[H] must be dead or unconscious for you to claim [H.p_their()] mind!</span>")
return
if(H.head)
var/obj/item/I = H.head
if(I.flags_inv & HIDEHAIR) //they're wearing a hat that covers their skull
to_chat(user, "<span class='warning'>[H]'s head is covered, remove [H.p_their()] [H.head] first!</span>")
return
if(H.wear_mask)
var/obj/item/I = H.wear_mask
if(I.flags_inv & HIDEHAIR) //they're wearing a mask that covers their skull
to_chat(user, "<span class='warning'>[H]'s head is covered, remove [H.p_their()] [H.wear_mask] first!</span>")
return
var/obj/item/bodypart/head/HE = H.get_bodypart(BODY_ZONE_HEAD)
if(!HE) //literally headless
to_chat(user, "<span class='warning'>[H] has no head, and thus no mind to claim!</span>")
return
var/obj/item/organ/brain/B = H.getorgan(/obj/item/organ/brain)
if(!B) //either somebody already got to them or robotics did
to_chat(user, "<span class='warning'>[H] has no brain, and thus no mind to claim!</span>")
return
if(!H.key) //nobody's home
to_chat(user, "<span class='warning'>[H] has no mind to claim!</span>")
return
playsound(H, 'sound/misc/splort.ogg', 60, 1, -1)
playsound(H, 'sound/magic/clockwork/anima_fragment_attack.ogg', 40, 1, -1)
H.fakedeath("soul_vessel") //we want to make sure they don't deathgasp and maybe possibly explode
H.death()
H.cure_fakedeath("soul_vessel")
H.apply_status_effect(STATUS_EFFECT_SIGILMARK) //let them be affected by vitality matrices
picked_name = "Slave"
braintype = picked_name
brainmob.timeofhostdeath = H.timeofdeath
user.visible_message("<span class='warning'>[user] presses [src] to [H]'s head, ripping through the skull and carefully extracting the brain!</span>", \
"<span class='brass'>You extract [H]'s consciousness from [H.p_their()] body, trapping it in the soul vessel.</span>")
transfer_personality(H)
brainmob.fully_replace_character_name(null, "[braintype] [H.real_name]")
name = "[initial(name)] ([brainmob.name])"
B.Remove()
qdel(B)
H.update_hair()
| 0 | 0.825809 | 1 | 0.825809 | game-dev | MEDIA | 0.957411 | game-dev | 0.970364 | 1 | 0.970364 |
oot-pc-port/oot-pc-port | 1,587 | asm/non_matchings/overlays/actors/ovl_En_Insect/func_80A7C598.s | glabel func_80A7C598
/* 00778 80A7C598 27BDFFE8 */ addiu $sp, $sp, 0xFFE8 ## $sp = FFFFFFE8
/* 0077C 80A7C59C AFBF0014 */ sw $ra, 0x0014($sp)
/* 00780 80A7C5A0 00803025 */ or $a2, $a0, $zero ## $a2 = 00000000
/* 00784 80A7C5A4 AFA60018 */ sw $a2, 0x0018($sp)
/* 00788 80A7C5A8 2404000A */ addiu $a0, $zero, 0x000A ## $a0 = 0000000A
/* 0078C 80A7C5AC 0C01DF64 */ jal Math_Rand_S16Offset
/* 00790 80A7C5B0 2405002D */ addiu $a1, $zero, 0x002D ## $a1 = 0000002D
/* 00794 80A7C5B4 8FA40018 */ lw $a0, 0x0018($sp)
/* 00798 80A7C5B8 0C29EFD6 */ jal func_80A7BF58
/* 0079C 80A7C5BC A482031A */ sh $v0, 0x031A($a0) ## 0000031A
/* 007A0 80A7C5C0 8FA60018 */ lw $a2, 0x0018($sp)
/* 007A4 80A7C5C4 3C0E80A8 */ lui $t6, %hi(func_80A7C5EC) ## $t6 = 80A80000
/* 007A8 80A7C5C8 25CEC5EC */ addiu $t6, $t6, %lo(func_80A7C5EC) ## $t6 = 80A7C5EC
/* 007AC 80A7C5CC 94CF0314 */ lhu $t7, 0x0314($a2) ## 00000314
/* 007B0 80A7C5D0 ACCE0310 */ sw $t6, 0x0310($a2) ## 00000310
/* 007B4 80A7C5D4 35F80100 */ ori $t8, $t7, 0x0100 ## $t8 = 00000100
/* 007B8 80A7C5D8 A4D80314 */ sh $t8, 0x0314($a2) ## 00000314
/* 007BC 80A7C5DC 8FBF0014 */ lw $ra, 0x0014($sp)
/* 007C0 80A7C5E0 27BD0018 */ addiu $sp, $sp, 0x0018 ## $sp = 00000000
/* 007C4 80A7C5E4 03E00008 */ jr $ra
/* 007C8 80A7C5E8 00000000 */ nop
| 0 | 0.706551 | 1 | 0.706551 | game-dev | MEDIA | 0.935916 | game-dev | 0.58982 | 1 | 0.58982 |
DigitalRune/DigitalRune | 35,715 | Source/DigitalRune.Game.Input/IInputService.cs | // DigitalRune Engine - Copyright (C) DigitalRune GmbH
// This file is subject to the terms and conditions defined in
// file 'LICENSE.TXT', which is part of this source code package.
using System;
using System.Collections.ObjectModel;
using Microsoft.Xna.Framework.Input;
#if !SILVERLIGHT
using Microsoft.Xna.Framework.Input.Touch;
using Microsoft.Xna.Framework;
using System.Collections.Generic;
#else
using Keys = System.Windows.Input.Key;
#endif
#if USE_DIGITALRUNE_MATHEMATICS
using DigitalRune.Mathematics.Algebra;
#else
using Vector2F = Microsoft.Xna.Framework.Vector2;
using Vector3F = Microsoft.Xna.Framework.Vector3;
#endif
namespace DigitalRune.Game.Input
{
#pragma warning disable 1584,1711,1572,1581,1580,1574 // cref attribute could not be resolved.
/// <summary>
/// Manages user input from keyboard, mouse, Xbox 360 controllers and other devices.
/// </summary>
/// <remarks>
/// <para>
/// Note: Touch, accelerometer and gamepad input is not supported in Silverlight.
/// (But those devices are supported on the Windows Phone.)
/// </para>
/// <para>
/// The input manager is the central method that should be used to check for user input. It
/// contains many convenience methods that allow to detected key/button presses and double-clicks.
/// </para>
/// <para>
/// Typically, many game components can handle the input. But often input should only be processed
/// by the foremost game component (e.g. the top-most window). For this, game components can set
/// the flags <see cref="IsAccelerometerHandled"/>, <see cref="IsGamePadHandled(LogicalPlayerIndex)"/>,
/// <see cref="IsKeyboardHandled"/>, and <see cref="IsMouseOrTouchHandled"/> to indicate that
/// input has already been processed and other game components should ignore the input. These
/// flags are reset by the input service in each frame, but otherwise the input service itself
/// does not read this flags. It is up to the game components to decide whether they want to
/// consider these flags or not. (If, for example, <see cref="IsMouseOrTouchHandled"/> is set,
/// methods like <see cref="IsDown(MouseButtons)"/> still work normally.)
/// </para>
/// <para>
/// <strong>Logical Players and Game Controllers: </strong>The <see cref="PlayerIndex"/> in XNA
/// identifies a game controller. Beware that "Player One" may not be using the game controller
/// that is assigned to <strong>PlayerIndex.One</strong>! A game needs to detect which player uses
/// which game controller at runtime. (See example below.)
/// </para>
/// <para>
/// The <see cref="LogicalPlayerIndex"/> identifies a player. <see cref="SetLogicalPlayer"/> must
/// be called to assign a game controller to a player. Gamepad input can be queried using the
/// <see cref="PlayerIndex"/> to get the input of a certain game controller or the
/// <see cref="LogicalPlayerIndex"/> to get the input of a certain player.
/// <strong>LogicalPlayerIndex.Any</strong> can be used to query the game controllers of all
/// players. Note that game controllers that are not associated with any player are ignored when
/// <strong>LogicalPlayerIndex.Any</strong> is used.
/// </para>
/// <para>
/// <strong>IMPORTANT: </strong>The methods that take the <see cref="LogicalPlayerIndex"/> as a
/// parameter return default values when no game controller is assigned to the specified player.
/// Be sure to call
/// <see cref="SetLogicalPlayer"/> to assign game controllers to players.
/// </para>
/// <para>
/// <strong>IsUp, IsDown and IsPressed: </strong>The input service defines simple methods that
/// allow to check if a key or button is currently held down or not. This methods are called
/// <strong>IsDown</strong> and <strong>IsUp</strong>. The methods <strong>IsPressed</strong> and
/// <strong>IsReleased</strong> check whether a key or button was pressed down or released exactly
/// in this frame. That means, if a key is not held down, <strong>IsUp</strong> returns true and
/// all other methods return false. Then when the key is pressed, <strong>IsDown
/// </strong> is true and <strong>IsPressed</strong> is true. If the key is still held down in the
/// next frame, <strong>IsDown</strong> is still true but <strong>IsPressed</strong> is false.
/// </para>
/// <para>
/// <strong>Double-Clicks: </strong>The methods <strong>IsDoubleClick</strong> can be used to
/// detect double-clicks. The two clicks must be within the
/// <see cref="InputSettings.DoubleClickTime"/> to count as double-click. For GUI controls it is
/// also necessary to check if both clicks were in the same region - but this is not checked by
/// the input service and is left to the GUI system.
/// </para>
/// <para>
/// <strong>Virtual Key/Button Presses: </strong>When a key or button is held down for longer than
/// <see cref="InputSettings.RepetitionDelay"/> the input service starts to create "IsPressed"
/// events at a frequency defined by <see cref="InputSettings.RepetitionInterval"/> - this is
/// convenient for text input in text box controls and text editors. The property
/// <see cref="PressedKeys"/> contains a list of all keys that where pressed down in the current
/// frame - including the virtual presses created by keys/buttons that were held down for a long
/// time. In the <strong>IsPressed</strong> methods the second parameter allows to specify if
/// virtual key/button repetitions events should be included or not.
/// </para>
/// <para>
/// <strong>Accelerometer: </strong>The accelerometer can only be used on the Windows Phone 7
/// device. In the Windows Phone 7 emulator the arrow keys and the space key can be used to
/// create accelerometer readings.
/// </para>
/// </remarks>
/// <example>
/// At runtime an application needs to figure out which game controller is used to control the
/// game. This is typically done by prompting the user to press Start or button A at the start
/// screen. Include the following code in the <strong>Update</strong> method of the game:
/// <code lang="csharp">
/// <![CDATA[
/// if (_inputManager.GetLogicalPlayer(LogicalPlayerIndex.One) == null)
/// {
/// // Wait until the user presses A or START on any connected gamepad.
/// for (var controller = PlayerIndex.One; controller <= PlayerIndex.Four; controller++)
/// {
/// if (_inputManager.IsDown(Buttons.A, controller) || _inputManager.IsDown(Buttons.Start, controller))
/// {
/// // A or START was pressed. Assign the controller to the first "logical player".
/// _inputManager.SetLogicalPlayer(LogicalPlayerIndex.One, controller);
/// break;
/// }
/// }
/// }
/// ]]>
/// </code>
/// All subsequent methods can use <strong>LogicalPlayerIndex.One</strong> to query the input of
/// the player.
/// </example>
#pragma warning restore 1584,1711,1572,1581,1580,1574
public interface IInputService
{
/// <summary>
/// Gets or sets the settings that define input handling, timing, etc.
/// </summary>
/// <value>The input settings.</value>
/// <exception cref="ArgumentNullException">
/// <paramref name="value"/> is <see langword="null"/>.
/// </exception>
InputSettings Settings { get; set; }
/// <summary>
/// Gets the max number of players (= max number of game controllers that can be connected).
/// </summary>
/// <value>The max number of players.</value>
/// <remarks>
/// This number shows the maximal number of game controllers that can be connected and are
/// supported by this input service.
/// </remarks>
int MaxNumberOfPlayers { get; }
/// <summary>
/// Gets or sets a value indicating whether mouse or touch input has already been handled.
/// </summary>
/// <value>
/// <see langword="true"/> if mouse or touch input has already been handled; otherwise,
/// <see langword="false"/>.
/// </value>
/// <remarks>
/// This value is automatically reset (= set to <see langword="false"/>) by the input service
/// in each frame. Game components can set this flag to indicate that they have handled the
/// mouse or touch input and other game components should not handle this input anymore.
/// </remarks>
bool IsMouseOrTouchHandled { get; set; }
/// <summary>
/// Gets or sets a value indicating whether keyboard input has already been handled.
/// </summary>
/// <value>
/// <see langword="true"/> if keyboard input has already been handled; otherwise,
/// <see langword="false"/>.
/// </value>
/// <remarks>
/// This value is automatically reset (= set to <see langword="false"/>) by the input service
/// in each frame. Game components can set this flag to indicate that they have handled the
/// keyboard input and other game components should not handle this input anymore.
/// </remarks>
bool IsKeyboardHandled { get; set; }
#if !SILVERLIGHT
/// <summary>
/// Gets the game controller assigned to the specified player. (Not available in Silverlight.)
/// </summary>
/// <param name="player">
/// The <see cref="LogicalPlayerIndex"/> that identifies the player.
/// </param>
/// <returns>
/// The <see cref="PlayerIndex"/> that identifies the game controller. Returns
/// <see langword="null"/>, if no game controller is assigned to <paramref name="player"/>.
/// </returns>
/// <remarks>
/// Use <see cref="SetLogicalPlayer"/> to assign a game controller to a player.
/// </remarks>
/// <seealso cref="SetLogicalPlayer"/>
PlayerIndex? GetLogicalPlayer(LogicalPlayerIndex player);
/// <summary>
/// Assigns a game controller to a player. (Not available in Silverlight.)
/// </summary>
/// <param name="player">
/// The <see cref="LogicalPlayerIndex"/> that identifies the player.
/// </param>
/// <param name="controller">
/// The <see cref="PlayerIndex"/> that identifies the game controller. (Can be
/// <see langword="null"/> to remove the current assignment.)
/// </param>
/// <seealso cref="GetLogicalPlayer"/>
/// <exception cref="ArgumentException">
/// <paramref name="player"/> is invalid.
/// </exception>
void SetLogicalPlayer(LogicalPlayerIndex player, PlayerIndex? controller);
/// <overloads>
/// <summary>
/// Sets the <strong>IsGamePadHandled</strong> flags. (Not available in Silverlight.)
/// </summary>
/// </overloads>
///
/// <summary>
/// Sets the <strong>IsGamePadHandled</strong> flags for the given player. (Not available in Silverlight.)
/// </summary>
/// <param name="player">
/// The <see cref="LogicalPlayerIndex"/> that identifies the player.
/// (<see cref="LogicalPlayerIndex.Any"/> to set the <strong>IsGamePadHandled</strong> flag of
/// all players.)
/// </param>
/// <param name="value">
/// The new value for the <strong>IsGamePadHandled</strong> flag.
/// </param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Consistent with XNA.")]
void SetGamePadHandled(LogicalPlayerIndex player, bool value);
/// <summary>
/// Sets the <strong>IsGamePadHandled</strong> flags of a given game controller.
/// (Not available in Silverlight.)
/// </summary>
/// <param name="controller">
/// The <see cref="PlayerIndex"/> that identifies the game controller.
/// </param>
/// <param name="value">
/// The new value for the <strong>IsGamePadHandled</strong> flag.
/// </param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Consistent with XNA.")]
void SetGamePadHandled(PlayerIndex controller, bool value);
/// <overloads>
/// <summary>
/// Gets a value indicating whether gamepad input has already been handled.
/// (Not available in Silverlight.)
/// </summary>
/// </overloads>
///
/// <summary>
/// Gets a value indicating whether gamepad input of a given player has already been handled.
/// </summary>
/// <param name="player">
/// The <see cref="LogicalPlayerIndex"/> that identifies the player.
/// (<see cref="LogicalPlayerIndex.Any"/> to check all of players.)
/// </param>
/// <returns>
/// <see langword="true"/> if the input for the given <paramref name="player"/> was already
/// handled. If <paramref name="player"/> is <see langword="LogicalPlayerIndex.Any"/>
/// <see langword="true"/> is returned if any game controller input was already handled.
/// </returns>
/// <remarks>
/// This flags are automatically reset (= set to <see langword="false"/>) by the input service
/// in each frame. Game components can set this flag to indicate that they have handled the
/// game controller input and other game components should not handle this input anymore.
/// To set these flags use <see cref="SetGamePadHandled(LogicalPlayerIndex,bool)"/>.
/// </remarks>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Consistent with XNA.")]
bool IsGamePadHandled(LogicalPlayerIndex player);
/// <summary>
/// Gets a value indicating whether the input of a given game controller has already been
/// handled. (Not available in Silverlight.)
/// </summary>
/// <param name="controller">
/// The <see cref="PlayerIndex"/> that identifies the game controller.
/// </param>
/// <returns>
/// <see langword="true"/> if the input for the given <paramref name="controller"/> was already
/// handled.
/// </returns>
/// <inheritdoc cref="IsGamePadHandled(LogicalPlayerIndex)"/>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Consistent with XNA.")]
bool IsGamePadHandled(PlayerIndex controller);
#endif
/// <summary>
/// Sets all "IsHandled" flags to the given value.
/// </summary>
/// <param name="value">The value for the flags.</param>
void SetAllHandled(bool value);
/// <summary>
/// Gets or sets a value indicating whether accelerometer input has already been handled.
/// </summary>
/// <value>
/// <see langword="true"/> if accelerometer input has already been handled; otherwise,
/// <see langword="false"/>.
/// </value>
/// <remarks>
/// This value is automatically reset (= set to <see langword="false"/>) by the input service
/// in each frame. Game components can set this flag to indicate that they have handled the
/// accelerometer input and other game components should not handle this input anymore.
/// </remarks>
bool IsAccelerometerHandled { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the mouse position is reset in each frame.
/// </summary>
/// <value>
/// <see langword="true"/> if the mouse position is reset in each frame; otherwise,
/// <see langword="false"/>.
/// </value>
/// <remarks>
/// If <see cref="EnableMouseCentering"/> is <see langword="true"/>, the input service will
/// reset the mouse position to <see cref="InputSettings.MouseCenter"/> in each frame. This is
/// necessary, for example, for first-person shooters that need only relative mouse input.
/// </remarks>
bool EnableMouseCentering { get; set; }
/// <summary>
/// Gets the state of the current mouse state.
/// </summary>
/// <value>The state of the current mouse state.</value>
MouseState MouseState { get; }
/// <summary>
/// Gets the mouse state of the last frame.
/// </summary>
/// <value>The mouse state of the last frame.</value>
MouseState PreviousMouseState { get; }
/// <summary>
/// Gets a value representing the rotation change of the mouse wheel.
/// </summary>
/// <value>The rotation change of the mouse wheel.</value>
float MouseWheelDelta { get; }
/// <summary>
/// Gets the raw mouse position.
/// </summary>
/// <value>The raw mouse position.</value>
/// <remarks>
/// <para>
/// <see cref="MousePositionRaw"/> is the mouse position relative to the game window - as it
/// was read using the XNA <see cref="Mouse"/> class. <see cref="MousePositionDeltaRaw"/>
/// is the mouse position change since the last frame. Both properties are read-only.
/// </para>
/// <para>
/// The properties <see cref="MousePosition"/> and <see cref="MousePositionDelta"/> are set to
/// the same values as <see cref="MousePositionRaw"/> and <see cref="MousePositionDeltaRaw"/> in
/// each frame. These properties have a setter and can therefore be modified by other game
/// components. <see cref="MousePosition"/> and <see cref="MousePositionDelta"/> store any
/// changed values for the rest of the frame. This is useful if the mouse position needs to be
/// transformed. For example, the mouse position can be transformed to be relative to a viewport
/// within the game window.
/// </para>
/// <para>
/// If <see cref="MousePosition"/> is modified, <see cref="MousePositionDelta"/> should be
/// modified accordingly.
/// </para>
/// </remarks>
Vector2F MousePositionRaw { get; }
/// <summary>
/// Gets the raw mouse position change since the last frame.
/// </summary>
/// <value>The raw mouse position change.</value>
/// <inheritdoc cref="MousePositionRaw"/>
Vector2F MousePositionDeltaRaw { get; }
/// <summary>
/// Gets or sets the mouse position.
/// </summary>
/// <value>The mouse position.</value>
/// <inheritdoc cref="MousePositionRaw"/>
Vector2F MousePosition { get; set; }
/// <summary>
/// Gets or sets the mouse position change since the last frame.
/// </summary>
/// <value>The mouse position change.</value>
/// <inheritdoc cref="MousePositionRaw"/>
Vector2F MousePositionDelta { get; set; }
/// <summary>
/// Gets the state of the current keyboard state.
/// </summary>
/// <value>The state of the current keyboard state.</value>
KeyboardState KeyboardState { get; }
/// <summary>
/// Gets the keyboard state of the last frame.
/// </summary>
/// <value>The keyboard state of the last frame.</value>
KeyboardState PreviousKeyboardState { get; }
/// <summary>
/// Gets the pressed keys.
/// </summary>
/// <value>The pressed keys.</value>
/// <remarks>
/// This list includes keys that were "up" in the last frame and are "down" in this frame.
/// The list also includes artificial key presses generated by the key repetition feature.
/// </remarks>
ReadOnlyCollection<Keys> PressedKeys { get; }
/// <summary>
/// Gets the pressed modifier keys.
/// </summary>
/// <value>The pressed modifier keys.</value>
/// <remarks>
/// The special keys ChatPadGreen and ChatPadOrange are ignored and not detected.
/// </remarks>
ModifierKeys ModifierKeys { get; }
#if !SILVERLIGHT
/// <overloads>
/// <summary>
/// Gets the state of a game controller. (Not available in Silverlight.)
/// </summary>
/// </overloads>
///
/// <summary>
/// Gets the gamepad state for the given player.
/// </summary>
/// <param name="player">
/// The <see cref="LogicalPlayerIndex"/> that identifies the player. (Note:
/// <see cref="LogicalPlayerIndex.Any"/> is not allowed.)
/// </param>
/// <returns>The gamepad state of the current frame.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Consistent with XNA.")]
GamePadState GetGamePadState(LogicalPlayerIndex player);
/// <summary>
/// Gets the gamepad state of the given game controller. (Not available in Silverlight.)
/// </summary>
/// <param name="controller">
/// The <see cref="PlayerIndex"/> that identifies the game controller.
/// </param>
/// <returns>The gamepad state of the current frame.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Consistent with XNA.")]
GamePadState GetGamePadState(PlayerIndex controller);
/// <overloads>
/// <summary>
/// Gets the gamepad state of the last frame. (Not available in Silverlight.)
/// </summary>
/// </overloads>
///
/// <summary>
/// Gets the gamepad state of the last frame for the given player.
/// (Not available in Silverlight.)
/// </summary>
/// <param name="player">
/// The <see cref="LogicalPlayerIndex"/> that identifies the player.
/// </param>
/// <returns>
/// The gamepad state of the last frame.
/// </returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Consistent with XNA.")]
GamePadState GetPreviousGamePadState(LogicalPlayerIndex player);
/// <summary>
/// Gets the gamepad state of the last frame of the given game controller.
/// (Only available in XNA Windows Phone builds.)
/// </summary>
/// <param name="controller">
/// The <see cref="PlayerIndex"/> that identifies the game controller.
/// </param>
/// <returns>
/// The gamepad state of the last frame.
/// </returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Consistent with XNA.")]
GamePadState GetPreviousGamePadState(PlayerIndex controller);
#if !MONOGAME
/// <summary>
/// Gets a value indicating whether an accelerometer is connected and can be used.
/// (Only available in XNA Windows Phone builds.)
/// </summary>
/// <value>
/// <see langword="true"/> if an accelerometer is connected and can be used; otherwise,
/// <see langword="false"/>.
/// </value>
/// <remarks>
/// This type is only available on the following platforms: XNA Windows Phone.
/// </remarks>
bool IsAccelerometerActive { get; }
/// <summary>
/// Gets the accelerometer value.
/// (Only available in XNA Windows Phone builds.)
/// </summary>
/// <value>The accelerometer value.</value>
/// <remarks>
/// Use <see cref="IsAccelerometerActive"/> to check if an accelerometer is actually connected.
/// </remarks>
/// <remarks>
/// This type is only available on the following platforms: XNA Windows Phone.
/// </remarks>
Vector3F AccelerometerValue { get; }
#endif
/// <summary>
/// Gets the touch collection. (Not available in Silverlight.)
/// </summary>
/// <value>The touch collection.</value>
TouchCollection TouchCollection { get; }
/// <summary>
/// Gets the detected touch gestures. (Not available in Silverlight.)
/// </summary>
/// <value>The detected touch gestures.</value>
/// <remarks>
/// <see cref="TouchPanel.EnabledGestures"/> must be set to enable gesture detection.
/// Per default, no gestures are detected.
/// </remarks>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists", Justification = "Performance")]
List<GestureSample> Gestures { get; }
#endif
/// <summary>
/// Gets the input commands.
/// </summary>
/// <value>The input commands.</value>
InputCommandCollection Commands { get; }
#if !SILVERLIGHT
/// <overloads>
/// <summary>
/// Determines whether the specified button or key is down. (Not available in Silverlight.)
/// </summary>
/// </overloads>
///
/// <summary>
/// Determines whether the specified button is down for the given player.
/// (Not available in Silverlight.)
/// </summary>
/// <param name="button">The button.</param>
/// <param name="player">
/// The <see cref="LogicalPlayerIndex"/> that identifies the player.
/// (<see cref="LogicalPlayerIndex.Any"/> to check the game controllers of all available
/// players.)
/// </param>
/// <returns>
/// <see langword="true"/> if the specified button is down; otherwise, <see langword="false"/>.
/// </returns>
bool IsDown(Buttons button, LogicalPlayerIndex player);
/// <summary>
/// Determines whether the specified button is down on the given game controller.
/// (Not available in Silverlight.)
/// </summary>
/// <param name="button">The button.</param>
/// <param name="controller">
/// The <see cref="PlayerIndex"/> that identifies the game controller.
/// </param>
/// <returns>
/// <see langword="true"/> if the specified button is down; otherwise, <see langword="false"/>.
/// </returns>
bool IsDown(Buttons button, PlayerIndex controller);
/// <overloads>
/// <summary>
/// Determines whether the specified button or key is up. (Not available in Silverlight.)
/// </summary>
/// </overloads>
///
/// <summary>
/// Determines whether the specified button is up for the given player.
/// (Not available in Silverlight.)
/// </summary>
/// <param name="button">The button.</param>
/// <param name="player">
/// The <see cref="LogicalPlayerIndex"/> that identifies the player.
/// (<see cref="LogicalPlayerIndex.Any"/> to check the game controllers of all available
/// players.)
/// </param>
/// <returns>
/// <see langword="true"/> if the specified button is up; otherwise, <see langword="false"/>.
/// </returns>
bool IsUp(Buttons button, LogicalPlayerIndex player);
/// <summary>
/// Determines whether the specified button is up on the given game controller.
/// (Not available in Silverlight.)
/// </summary>
/// <param name="button">The button.</param>
/// <param name="controller">
/// The <see cref="PlayerIndex"/> that identifies the game controller.
/// </param>
/// <returns>
/// <see langword="true"/> if the specified button is up; otherwise, <see langword="false"/>.
/// </returns>
bool IsUp(Buttons button, PlayerIndex controller);
/// <overloads>
/// <summary>
/// Determines whether the specified button or key has been pressed.
/// (Not available in Silverlight.)
/// </summary>
/// </overloads>
///
/// <summary>
/// Determines whether the specified button has been pressed by the given player.
/// (Not available in Silverlight.)
/// </summary>
/// <param name="button">The button.</param>
/// <param name="useButtonRepetition">
/// If set to <see langword="true"/> physical and virtual button presses (see
/// <see cref="IInputService"/>) are returned; otherwise, only physical button presses are
/// returned.
/// </param>
/// <param name="player">
/// The <see cref="LogicalPlayerIndex"/> that identifies the player.
/// (<see cref="LogicalPlayerIndex.Any"/> to check the game controllers of all available
/// players.)
/// </param>
/// <returns>
/// <see langword="true"/> if the specified button was previously up and has been pressed;
/// otherwise, <see langword="false"/>.
/// </returns>
bool IsPressed(Buttons button, bool useButtonRepetition, LogicalPlayerIndex player);
/// <summary>
/// Determines whether the specified button has been pressed on the given game controller.
/// (Not available in Silverlight.)
/// </summary>
/// <param name="button">The button.</param>
/// <param name="useButtonRepetition">
/// If set to <see langword="true"/> physical and virtual button presses (see
/// <see cref="IInputService"/>) are returned; otherwise, only physical button presses are
/// returned.
/// </param>
/// <param name="controller">
/// The <see cref="PlayerIndex"/> that identifies the game controller.
/// </param>
/// <returns>
/// <see langword="true"/> if the specified button was previously up and has been pressed;
/// otherwise, <see langword="false"/>.
/// </returns>
bool IsPressed(Buttons button, bool useButtonRepetition, PlayerIndex controller);
/// <overloads>
/// <summary>
/// Determines whether the specified button or key has been released.
/// (Not available in Silverlight.)
/// </summary>
/// </overloads>
///
/// <summary>
/// Determines whether the specified button has been released by the given player.
/// (Not available in Silverlight.)
/// </summary>
/// <param name="button">The button.</param>
/// <param name="player">
/// The <see cref="LogicalPlayerIndex"/> that identifies the player.
/// (<see cref="LogicalPlayerIndex.Any"/> to check the game controllers of all available
/// players.)
/// </param>
/// <returns>
/// <see langword="true"/> if the specified button was previously down and has been released;
/// otherwise, <see langword="false"/>.
/// </returns>
bool IsReleased(Buttons button, LogicalPlayerIndex player);
/// <summary>
/// Determines whether the specified button has been released on the given game controller.
/// (Not available in Silverlight.)
/// </summary>
/// <param name="button">The button.</param>
/// <param name="controller">
/// The <see cref="PlayerIndex"/> that identifies the game controller.
/// </param>
/// <returns>
/// <see langword="true"/> if the specified button was previously down and has been released;
/// otherwise, <see langword="false"/>.
/// </returns>
bool IsReleased(Buttons button, PlayerIndex controller);
/// <overloads>
/// <summary>
/// Determines whether the specified button or key has been double-clicked.
/// (Not available in Silverlight.)
/// </summary>
/// </overloads>
///
/// <summary>
/// Determines whether the specified button has been double-clicked by the given player.
/// (Not available in Silverlight.)
/// </summary>
/// <param name="button">The button.</param>
/// <param name="player">
/// The <see cref="LogicalPlayerIndex"/> that identifies the player.
/// (<see cref="LogicalPlayerIndex.Any"/> to check the game controllers of all available
/// players.)
/// </param>
/// <returns>
/// <see langword="true"/> if the specified button has been double-clicked; otherwise,
/// <see langword="false"/>.
/// </returns>
bool IsDoubleClick(Buttons button, LogicalPlayerIndex player);
/// <summary>
/// Determines whether the specified button has been double-clicked on the given game
/// controller. (Not available in Silverlight.)
/// </summary>
/// <param name="button">The button.</param>
/// <param name="controller">
/// The <see cref="PlayerIndex"/> that identifies the game controller.
/// </param>
/// <returns>
/// <see langword="true"/> if the specified button has been double-clicked; otherwise,
/// <see langword="false"/>.
/// </returns>
bool IsDoubleClick(Buttons button, PlayerIndex controller);
#endif
/// <summary>
/// Determines whether the specified key is down.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>
/// <see langword="true"/> if the specified key is down; otherwise, <see langword="false"/>.
/// </returns>
bool IsDown(Keys key);
/// <summary>
/// Determines whether the specified key is up.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>
/// <see langword="true"/> if the specified key is up; otherwise, <see langword="false"/>.
/// </returns>
bool IsUp(Keys key);
/// <summary>
/// Determines whether the specified key was previously up and has been pressed.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="useKeyRepetition">
/// If set to <see langword="true"/> physical and virtual key presses (see
/// <see cref="IInputService"/>) are returned; otherwise, only physical key presses are
/// returned.
/// </param>
/// <returns>
/// <see langword="true"/> if <paramref name="key"/> was previously up and has been pressed;
/// otherwise, <see langword="false"/>.
/// </returns>
bool IsPressed(Keys key, bool useKeyRepetition);
/// <summary>
/// Determines whether the specified key was previously down and has been released.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>
/// <see langword="true"/> if the specified key was previously down and has been released;
/// otherwise, <see langword="false"/>.
/// </returns>
bool IsReleased(Keys key);
/// <summary>
/// Determines whether the specified key was double-clicked.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>
/// <see langword="true"/> if the specified key was double-clicked; otherwise,
/// <see langword="false"/>.
/// </returns>
bool IsDoubleClick(Keys key);
/// <summary>
/// Determines whether the specified button is down.
/// </summary>
/// <param name="button">The button.</param>
/// <returns>
/// <see langword="true"/> if the specified button is down; otherwise, <see langword="false"/>.
/// </returns>
bool IsDown(MouseButtons button);
/// <summary>
/// Determines whether the specified button is up.
/// </summary>
/// <param name="button">The button.</param>
/// <returns>
/// <see langword="true"/> if the specified button is up; otherwise, <see langword="false"/>.
/// </returns>
bool IsUp(MouseButtons button);
/// <summary>
/// Determines whether the specified button was previously up and has been pressed.
/// </summary>
/// <param name="button">The button.</param>
/// <param name="useButtonRepetition">
/// If set to <see langword="true"/> physical and virtual button presses (see
/// <see cref="IInputService"/>) are returned; otherwise, only physical button presses are
/// returned.
/// </param>
/// <returns>
/// <see langword="true"/> if the specified button was previously up and has been pressed;
/// otherwise, <see langword="false"/>.
/// </returns>
bool IsPressed(MouseButtons button, bool useButtonRepetition);
/// <summary>
/// Determines whether the specified button was previously down and has been released.
/// </summary>
/// <param name="button">The button.</param>
/// <returns>
/// <see langword="true"/> if the specified button was previously down and has been released;
/// otherwise, <see langword="false"/>.
/// </returns>
bool IsReleased(MouseButtons button);
/// <summary>
/// Determines whether the specified button has been double-clicked.
/// </summary>
/// <param name="button">The button.</param>
/// <returns>
/// <see langword="true"/> if the specified button has been double-clicked; otherwise,
/// <see langword="false"/>.
/// </returns>
bool IsDoubleClick(MouseButtons button);
}
} | 0 | 0.944742 | 1 | 0.944742 | game-dev | MEDIA | 0.547723 | game-dev | 0.732392 | 1 | 0.732392 |
SinlessDevil/PokemonTacticalRolePlay | 11,664 | Assets/Plugins/com.cysharp.unitask@f9fd769be7/Runtime/UniTask.WhenAny.cs | #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
using System;
using System.Collections.Generic;
using System.Threading;
using Cysharp.Threading.Tasks.Internal;
namespace Cysharp.Threading.Tasks
{
public partial struct UniTask
{
public static UniTask<(bool hasResultLeft, T result)> WhenAny<T>(UniTask<T> leftTask, UniTask rightTask)
{
return new UniTask<(bool, T)>(new WhenAnyLRPromise<T>(leftTask, rightTask), 0);
}
public static UniTask<(int winArgumentIndex, T result)> WhenAny<T>(params UniTask<T>[] tasks)
{
return new UniTask<(int, T)>(new WhenAnyPromise<T>(tasks, tasks.Length), 0);
}
public static UniTask<(int winArgumentIndex, T result)> WhenAny<T>(IEnumerable<UniTask<T>> tasks)
{
using (var span = ArrayPoolUtil.Materialize(tasks))
{
return new UniTask<(int, T)>(new WhenAnyPromise<T>(span.Array, span.Length), 0);
}
}
/// <summary>Return value is winArgumentIndex</summary>
public static UniTask<int> WhenAny(params UniTask[] tasks)
{
return new UniTask<int>(new WhenAnyPromise(tasks, tasks.Length), 0);
}
/// <summary>Return value is winArgumentIndex</summary>
public static UniTask<int> WhenAny(IEnumerable<UniTask> tasks)
{
using (var span = ArrayPoolUtil.Materialize(tasks))
{
return new UniTask<int>(new WhenAnyPromise(span.Array, span.Length), 0);
}
}
sealed class WhenAnyLRPromise<T> : IUniTaskSource<(bool, T)>
{
int completedCount;
UniTaskCompletionSourceCore<(bool, T)> core;
public WhenAnyLRPromise(UniTask<T> leftTask, UniTask rightTask)
{
TaskTracker.TrackActiveTask(this, 3);
{
UniTask<T>.Awaiter awaiter;
try
{
awaiter = leftTask.GetAwaiter();
}
catch (Exception ex)
{
core.TrySetException(ex);
goto RIGHT;
}
if (awaiter.IsCompleted)
{
TryLeftInvokeContinuation(this, awaiter);
}
else
{
awaiter.SourceOnCompleted(state =>
{
using (var t = (StateTuple<WhenAnyLRPromise<T>, UniTask<T>.Awaiter>)state)
{
TryLeftInvokeContinuation(t.Item1, t.Item2);
}
}, StateTuple.Create(this, awaiter));
}
}
RIGHT:
{
UniTask.Awaiter awaiter;
try
{
awaiter = rightTask.GetAwaiter();
}
catch (Exception ex)
{
core.TrySetException(ex);
return;
}
if (awaiter.IsCompleted)
{
TryRightInvokeContinuation(this, awaiter);
}
else
{
awaiter.SourceOnCompleted(state =>
{
using (var t = (StateTuple<WhenAnyLRPromise<T>, UniTask.Awaiter>)state)
{
TryRightInvokeContinuation(t.Item1, t.Item2);
}
}, StateTuple.Create(this, awaiter));
}
}
}
static void TryLeftInvokeContinuation(WhenAnyLRPromise<T> self, in UniTask<T>.Awaiter awaiter)
{
T result;
try
{
result = awaiter.GetResult();
}
catch (Exception ex)
{
self.core.TrySetException(ex);
return;
}
if (Interlocked.Increment(ref self.completedCount) == 1)
{
self.core.TrySetResult((true, result));
}
}
static void TryRightInvokeContinuation(WhenAnyLRPromise<T> self, in UniTask.Awaiter awaiter)
{
try
{
awaiter.GetResult();
}
catch (Exception ex)
{
self.core.TrySetException(ex);
return;
}
if (Interlocked.Increment(ref self.completedCount) == 1)
{
self.core.TrySetResult((false, default));
}
}
public (bool, T) GetResult(short token)
{
TaskTracker.RemoveTracking(this);
GC.SuppressFinalize(this);
return core.GetResult(token);
}
public UniTaskStatus GetStatus(short token)
{
return core.GetStatus(token);
}
public void OnCompleted(Action<object> continuation, object state, short token)
{
core.OnCompleted(continuation, state, token);
}
public UniTaskStatus UnsafeGetStatus()
{
return core.UnsafeGetStatus();
}
void IUniTaskSource.GetResult(short token)
{
GetResult(token);
}
}
sealed class WhenAnyPromise<T> : IUniTaskSource<(int, T)>
{
int completedCount;
UniTaskCompletionSourceCore<(int, T)> core;
public WhenAnyPromise(UniTask<T>[] tasks, int tasksLength)
{
if (tasksLength == 0)
{
throw new ArgumentException("The tasks argument contains no tasks.");
}
TaskTracker.TrackActiveTask(this, 3);
for (int i = 0; i < tasksLength; i++)
{
UniTask<T>.Awaiter awaiter;
try
{
awaiter = tasks[i].GetAwaiter();
}
catch (Exception ex)
{
core.TrySetException(ex);
continue; // consume others.
}
if (awaiter.IsCompleted)
{
TryInvokeContinuation(this, awaiter, i);
}
else
{
awaiter.SourceOnCompleted(state =>
{
using (var t = (StateTuple<WhenAnyPromise<T>, UniTask<T>.Awaiter, int>)state)
{
TryInvokeContinuation(t.Item1, t.Item2, t.Item3);
}
}, StateTuple.Create(this, awaiter, i));
}
}
}
static void TryInvokeContinuation(WhenAnyPromise<T> self, in UniTask<T>.Awaiter awaiter, int i)
{
T result;
try
{
result = awaiter.GetResult();
}
catch (Exception ex)
{
self.core.TrySetException(ex);
return;
}
if (Interlocked.Increment(ref self.completedCount) == 1)
{
self.core.TrySetResult((i, result));
}
}
public (int, T) GetResult(short token)
{
TaskTracker.RemoveTracking(this);
GC.SuppressFinalize(this);
return core.GetResult(token);
}
public UniTaskStatus GetStatus(short token)
{
return core.GetStatus(token);
}
public void OnCompleted(Action<object> continuation, object state, short token)
{
core.OnCompleted(continuation, state, token);
}
public UniTaskStatus UnsafeGetStatus()
{
return core.UnsafeGetStatus();
}
void IUniTaskSource.GetResult(short token)
{
GetResult(token);
}
}
sealed class WhenAnyPromise : IUniTaskSource<int>
{
int completedCount;
UniTaskCompletionSourceCore<int> core;
public WhenAnyPromise(UniTask[] tasks, int tasksLength)
{
if (tasksLength == 0)
{
throw new ArgumentException("The tasks argument contains no tasks.");
}
TaskTracker.TrackActiveTask(this, 3);
for (int i = 0; i < tasksLength; i++)
{
UniTask.Awaiter awaiter;
try
{
awaiter = tasks[i].GetAwaiter();
}
catch (Exception ex)
{
core.TrySetException(ex);
continue; // consume others.
}
if (awaiter.IsCompleted)
{
TryInvokeContinuation(this, awaiter, i);
}
else
{
awaiter.SourceOnCompleted(state =>
{
using (var t = (StateTuple<WhenAnyPromise, UniTask.Awaiter, int>)state)
{
TryInvokeContinuation(t.Item1, t.Item2, t.Item3);
}
}, StateTuple.Create(this, awaiter, i));
}
}
}
static void TryInvokeContinuation(WhenAnyPromise self, in UniTask.Awaiter awaiter, int i)
{
try
{
awaiter.GetResult();
}
catch (Exception ex)
{
self.core.TrySetException(ex);
return;
}
if (Interlocked.Increment(ref self.completedCount) == 1)
{
self.core.TrySetResult(i);
}
}
public int GetResult(short token)
{
TaskTracker.RemoveTracking(this);
GC.SuppressFinalize(this);
return core.GetResult(token);
}
public UniTaskStatus GetStatus(short token)
{
return core.GetStatus(token);
}
public void OnCompleted(Action<object> continuation, object state, short token)
{
core.OnCompleted(continuation, state, token);
}
public UniTaskStatus UnsafeGetStatus()
{
return core.UnsafeGetStatus();
}
void IUniTaskSource.GetResult(short token)
{
GetResult(token);
}
}
}
}
| 0 | 0.946236 | 1 | 0.946236 | game-dev | MEDIA | 0.641801 | game-dev | 0.990402 | 1 | 0.990402 |
realms-mud/core-lib | 6,838 | guilds/fighter/axes/hack.c | //*****************************************************************************
// Copyright (c) 2025 - Allen Cummings, RealmsMUD, All rights reserved. See
// the accompanying LICENSE file for details.
//*****************************************************************************
inherit "/lib/modules/research/instantaneousActiveResearchItem.c";
/////////////////////////////////////////////////////////////////////////////
protected void Setup()
{
addSpecification("name", "Hack");
addSpecification("source", "fighter");
addSpecification("description", "This research provides the user with the "
"knowledge of a cleaving blade technique that causes massive damage to "
"an enemy.");
addPrerequisite("/guilds/fighter/axes/chop.c",
(["type":"research"]));
addSpecification("limited by", (["equipment":({ "axe" })]));
addPrerequisite("level",
(["type":"level",
"guild": "fighter",
"value": 13
]));
addSpecification("scope", "targeted");
addSpecification("research type", "points");
addSpecification("research cost", 1);
addSpecification("damage hit points", ({ ([
"probability": 90,
"base damage": 35,
"range": 75
]),
([
"probability": 10,
"base damage": 75,
"range": 150
])
}));
addSpecification("damage type", "slash");
addSpecification("modifiers", ({
([
"type": "research",
"research item": "/guilds/fighter/axes/strike-the-blood.c",
"name": "Strike the Blood",
"formula": "multiplicative",
"base value": 1,
"rate": 1.25
]),
([
"type": "research",
"research item": "/guilds/fighter/axes/fools-strike.c",
"name": "Fool's Strike",
"formula": "multiplicative",
"base value": 1,
"rate": 1.25
]),
([
"type": "research",
"research item": "/guilds/fighter/axes/hooking-strike.c",
"name": "Hooking Strike",
"formula": "multiplicative",
"base value": 1,
"rate": 1.25
]),
([
"type": "research",
"research item": "/guilds/fighter/axes/horn-thrust.c",
"name": "Horn Thrust",
"formula": "multiplicative",
"base value": 1,
"rate": 1.25
]),
([
"type": "research",
"research item": "/guilds/fighter/axes/haft-strike.c",
"name": "Haft Strike",
"formula": "multiplicative",
"base value": 1,
"rate": 1.25
]),
([
"type": "research",
"research item": "/guilds/fighter/axes/arresting-blow.c",
"name": "Arresting Blow",
"formula": "multiplicative",
"base value": 1,
"rate": 1.25
]),
([
"type": "research",
"research item": "/guilds/fighter/axes/arc-strike.c",
"name": "Arc Strike",
"formula": "multiplicative",
"base value": 1,
"rate": 1.25
]),
([
"type": "research",
"research item": "/guilds/fighter/axes/broad-stroke.c",
"name": "Broad Stroke",
"formula": "multiplicative",
"base value": 1,
"rate": 1.25
]),
([
"type": "research",
"research item": "/guilds/fighter/axes/uplifting-sweep.c",
"name": "Uplifting Sweep",
"formula": "multiplicative",
"base value": 1,
"rate": 1.25
]),
([
"type": "research",
"research item": "/guilds/fighter/axes/master-chop.c",
"name": "Master Chop",
"formula": "multiplicative",
"base value": 1,
"rate": 1.5
]),
([
"type": "deferred attack",
"name": "deferred attack",
"trait": "/guilds/fighter/techniques/calculated-attack.c",
"formula": "multiplicative",
"rate": 0.01
]),
([
"type": "weapon damage",
"name" : "axe damage",
"types" : ({ "axe" }),
"formula" : "additive",
"rate" : 0.75
]),
([
"type": "skill",
"name" : "axe",
"formula" : "additive",
"rate" : 0.5
]),
([
"type": "skill",
"name": "anatomy and physiology",
"formula": "additive",
"rate": 0.10
]),
([
"type": "skill",
"name": "acrobatics",
"formula": "additive",
"rate": 0.05
]),
([
"type": "skill",
"name": "dancing",
"formula": "additive",
"rate": 0.05
]),
([
"type": "skill",
"name": "physics",
"formula": "additive",
"rate": 0.10
]),
([
"type": "skill",
"name": "mathematics",
"formula": "additive",
"rate": 0.10
]),
([
"type": "attribute",
"name": "dexterity",
"formula": "additive",
"rate": 0.25
]),
([
"type": "attribute",
"name": "strength",
"formula": "additive",
"rate": 0.25
]),
([
"type": "attribute",
"name": "wisdom",
"formula": "additive",
"rate": 0.15
]),
}));
addSpecification("stamina point cost", 125);
addSpecification("stamina point cost modifiers", ([
"/guilds/fighter/axes/axemasters-reserve.c": 10,
"/guilds/fighter/axes/axemasters-call.c": 10,
"/guilds/fighter/axes/axemasters-might.c": 10,
"/guilds/fighter/axes/axemasters-fury.c": 10
]));
addSpecification("cooldown", 60);
addSpecification("cooldown group", "fighter weapon level 13");
addSpecification("cooldown modifiers", ([
"/guilds/fighter/axes/axemasters-boon.c": 10,
"/guilds/fighter/axes/axemasters-speed.c": 10,
"/guilds/fighter/axes/axemasters-endurance.c": 10,
"/guilds/fighter/axes/axemasters-strength.c": 10,
]));
addSpecification("event handler", "hackEvent");
addSpecification("command template", "hack [at ##Target##]");
addSpecification("use ability message", "##InitiatorName## "
"brutally ##Infinitive::hack## ##InitiatorPossessive## "
"##InitiatorWeapon## into ##TargetName##.");
}
| 0 | 0.744647 | 1 | 0.744647 | game-dev | MEDIA | 0.786035 | game-dev | 0.528014 | 1 | 0.528014 |
dingzhen-vape/WurstCN | 2,111 | src/main/java/net/wurstclient/mixin/LivingEntityRendererMixin.java | /*
* Copyright (c) 2014-2024 Wurst-Imperium and contributors.
*
* This source code is subject to the terms of the GNU General Public
* License, version 3. If a copy of the GPL was not distributed with this
* file, You can obtain one at: https://www.gnu.org/licenses/gpl-3.0.txt
*/
package net.wurstclient.mixin;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import net.minecraft.client.render.entity.EntityRenderDispatcher;
import net.minecraft.client.render.entity.LivingEntityRenderer;
import net.minecraft.entity.Entity;
import net.minecraft.entity.LivingEntity;
import net.wurstclient.WurstClient;
@Mixin(LivingEntityRenderer.class)
public abstract class LivingEntityRendererMixin
{
/**
* Disables the distance limit in hasLabel() if configured in NameTags.
*/
@Redirect(at = @At(value = "INVOKE",
target = "Lnet/minecraft/client/render/entity/EntityRenderDispatcher;getSquaredDistanceToCamera(Lnet/minecraft/entity/Entity;)D",
ordinal = 0), method = "hasLabel(Lnet/minecraft/entity/LivingEntity;)Z")
private double adjustDistance(EntityRenderDispatcher render, Entity entity)
{
// pretend the distance is 1 so the check always passes
if(WurstClient.INSTANCE.getHax().nameTagsHack.isUnlimitedRange())
return 1;
return render.getSquaredDistanceToCamera(entity);
}
/**
* Forces the nametag to be rendered if configured in NameTags.
*/
@Inject(at = @At(value = "INVOKE",
target = "Lnet/minecraft/client/MinecraftClient;getInstance()Lnet/minecraft/client/MinecraftClient;",
ordinal = 0),
method = "hasLabel(Lnet/minecraft/entity/LivingEntity;)Z",
cancellable = true)
private void shouldForceLabel(LivingEntity entity,
CallbackInfoReturnable<Boolean> cir)
{
// return true immediately after the distance check
if(WurstClient.INSTANCE.getHax().nameTagsHack
.shouldForcePlayerNametags())
cir.setReturnValue(true);
}
}
| 0 | 0.668491 | 1 | 0.668491 | game-dev | MEDIA | 0.947713 | game-dev | 0.643306 | 1 | 0.643306 |
magefree/mage | 2,513 | Mage.Sets/src/mage/cards/i/ImmersturmPredator.java | package mage.cards.i;
import mage.MageInt;
import mage.abilities.Ability;
import mage.abilities.common.BecomesTappedSourceTriggeredAbility;
import mage.abilities.common.SimpleActivatedAbility;
import mage.abilities.costs.common.SacrificeTargetCost;
import mage.abilities.effects.common.ExileTargetEffect;
import mage.abilities.effects.common.TapSourceEffect;
import mage.abilities.effects.common.continuous.GainAbilitySourceEffect;
import mage.abilities.effects.common.counter.AddCountersSourceEffect;
import mage.abilities.keyword.FlyingAbility;
import mage.abilities.keyword.IndestructibleAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.Duration;
import mage.constants.SubType;
import mage.counters.CounterType;
import mage.filter.StaticFilters;
import mage.target.common.TargetCardInGraveyard;
import mage.target.common.TargetControlledPermanent;
import java.util.UUID;
/**
* @author TheElk801
*/
public final class ImmersturmPredator extends CardImpl {
public ImmersturmPredator(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{2}{B}{R}");
this.subtype.add(SubType.VAMPIRE);
this.subtype.add(SubType.DRAGON);
this.power = new MageInt(3);
this.toughness = new MageInt(3);
// Flying
this.addAbility(FlyingAbility.getInstance());
// Whenever Immersturm Predator becomes tapped, exile up to one target card from a graveyard and put a +1/+1 counter on Immersturm Predator.
Ability ability = new BecomesTappedSourceTriggeredAbility(new ExileTargetEffect());
ability.addEffect(new AddCountersSourceEffect(CounterType.P1P1.createInstance()).concatBy("and"));
ability.addTarget(new TargetCardInGraveyard(0, 1));
this.addAbility(ability);
// Sacrifice another creature: Immersturm Predator gains indestructible until end of turn. Tap it.
ability = new SimpleActivatedAbility(new GainAbilitySourceEffect(
IndestructibleAbility.getInstance(), Duration.EndOfTurn
), new SacrificeTargetCost(StaticFilters.FILTER_CONTROLLED_ANOTHER_CREATURE));
ability.addEffect(new TapSourceEffect().setText("Tap it"));
this.addAbility(ability);
}
private ImmersturmPredator(final ImmersturmPredator card) {
super(card);
}
@Override
public ImmersturmPredator copy() {
return new ImmersturmPredator(this);
}
}
| 0 | 0.955165 | 1 | 0.955165 | game-dev | MEDIA | 0.989184 | game-dev | 0.995358 | 1 | 0.995358 |
MemoriesOfTime/Nukkit-MOT | 5,688 | src/main/java/cn/nukkit/item/ItemSpawnEgg.java | package cn.nukkit.item;
import cn.nukkit.Player;
import cn.nukkit.Server;
import cn.nukkit.block.Block;
import cn.nukkit.block.BlockMobSpawner;
import cn.nukkit.blockentity.BlockEntity;
import cn.nukkit.blockentity.BlockEntitySpawner;
import cn.nukkit.entity.BaseEntity;
import cn.nukkit.entity.Entity;
import cn.nukkit.entity.mob.EntityZombie;
import cn.nukkit.entity.passive.EntityChicken;
import cn.nukkit.entity.passive.EntityCow;
import cn.nukkit.entity.passive.EntityPig;
import cn.nukkit.entity.passive.EntitySheep;
import cn.nukkit.event.entity.CreatureSpawnEvent;
import cn.nukkit.level.Level;
import cn.nukkit.level.format.FullChunk;
import cn.nukkit.math.BlockFace;
import cn.nukkit.nbt.tag.CompoundTag;
import cn.nukkit.nbt.tag.DoubleTag;
import cn.nukkit.nbt.tag.FloatTag;
import cn.nukkit.nbt.tag.ListTag;
import cn.nukkit.network.protocol.ProtocolInfo;
import cn.nukkit.utils.Utils;
import java.util.concurrent.ThreadLocalRandom;
/**
* @author MagicDroidX
* Nukkit Project
*/
public class ItemSpawnEgg extends Item {
public ItemSpawnEgg() {
this(0, 1);
}
public ItemSpawnEgg(Integer meta) {
this(meta, 1);
}
public ItemSpawnEgg(Integer meta, int count) {
super(SPAWN_EGG, meta, count, "Spawn Entity Egg");
}
@Override
public boolean canBeActivated() {
return true;
}
@Override
public boolean onActivate(Level level, Player player, Block block, Block target, BlockFace face, double fx, double fy, double fz) {
if (player.isAdventure()) {
return false;
}
if (!Server.getInstance().spawnEggsEnabled) {
player.sendMessage("\u00A7cSpawn eggs are disabled on this server");
return false;
}
if (target instanceof BlockMobSpawner) {
BlockEntity blockEntity = level.getBlockEntity(target);
if (blockEntity instanceof BlockEntitySpawner) {
if (((BlockEntitySpawner) blockEntity).getSpawnEntityType() != this.getDamage()) {
((BlockEntitySpawner) blockEntity).setSpawnEntityType(this.getDamage());
if (!player.isCreative()) {
player.getInventory().decreaseCount(player.getInventory().getHeldItemIndex());
}
}
} else {
if (blockEntity != null) {
blockEntity.close();
}
CompoundTag nbt = new CompoundTag()
.putString("id", BlockEntity.MOB_SPAWNER)
.putInt("EntityId", this.getDamage())
.putInt("x", (int) target.x)
.putInt("y", (int) target.y)
.putInt("z", (int) target.z);
BlockEntity.createBlockEntity(BlockEntity.MOB_SPAWNER, level.getChunk(target.getChunkX(), target.getChunkZ()), nbt);
if (!player.isCreative()) {
player.getInventory().decreaseCount(player.getInventory().getHeldItemIndex());
}
}
return true;
}
FullChunk chunk = level.getChunk((int) block.getX() >> 4, (int) block.getZ() >> 4);
if (chunk == null) {
return false;
}
CompoundTag nbt = new CompoundTag()
.putList(new ListTag<DoubleTag>("Pos")
.add(new DoubleTag("", block.getX() + 0.5))
.add(new DoubleTag("", target.getBoundingBox() == null ? block.getY() : target.getBoundingBox().getMaxY() + 0.0001f))
.add(new DoubleTag("", block.getZ() + 0.5)))
.putList(new ListTag<DoubleTag>("Motion")
.add(new DoubleTag("", 0))
.add(new DoubleTag("", 0))
.add(new DoubleTag("", 0)))
.putList(new ListTag<FloatTag>("Rotation")
.add(new FloatTag("", ThreadLocalRandom.current().nextFloat() * 360))
.add(new FloatTag("", 0)));
if (this.hasCustomName()) {
nbt.putString("CustomName", this.getCustomName());
}
CreatureSpawnEvent ev = new CreatureSpawnEvent(this.meta, block, nbt, CreatureSpawnEvent.SpawnReason.SPAWN_EGG, player);
level.getServer().getPluginManager().callEvent(ev);
if (ev.isCancelled()) {
return false;
}
Entity entity = Entity.createEntity(this.meta, chunk, nbt);
if (entity != null) {
if (!player.isCreative()) {
player.getInventory().decreaseCount(player.getInventory().getHeldItemIndex());
}
entity.spawnToAll();
if (Utils.rand(1, 20) == 1 &&
(entity instanceof EntityCow ||
entity instanceof EntityChicken ||
entity instanceof EntityPig ||
entity instanceof EntitySheep ||
entity instanceof EntityZombie)) {
((BaseEntity) entity).setBaby(true);
}
return true;
}
return false;
}
@Override
public boolean isSupportedOn(int protocolId) {
int meta = this.getDamage();
if (meta < 138) {
return true;
}
return switch (meta) {
case 138, 139 -> protocolId >= ProtocolInfo.v1_20_0_23;
case 142 -> protocolId >= ProtocolInfo.v1_20_80;
case 140, 144 -> protocolId >= ProtocolInfo.v1_21_0;
case 141, 143, 145, 146 -> protocolId >= ProtocolInfo.v1_21_50;
default -> true;
};
}
}
| 0 | 0.875392 | 1 | 0.875392 | game-dev | MEDIA | 0.995902 | game-dev | 0.951034 | 1 | 0.951034 |
CFPAOrg/Minecraft-Mod-Language-Package | 28,085 | projects/1.12.2/assets/matteroverdrive-legacy/matteroverdrive/lang/zh_cn.lang | # Fluids
###############################################################################################################
alert.new_update=有新版本可用!
alert.no_access_default=访问被$0拒绝
alert.no_rights.break=只有拥有者可以破坏$0
alert.no_rights.dismantle=只有拥有者可以拆除$0
alert.no_rights=无权访问$0
alert.not_android=检测到生物实体!拒绝访问!
attribute.name.android.batteryUse=能量消耗
attribute.name.android.glitchTime=故障时间
biopart.arms.name=手臂
biopart.battery.name=能源
biopart.chest.name=胸部
biopart.head.name=头部
biopart.legs.name=腿部
biopart.other.name=其它
biotic_stat.air_dash.details=在空中按两次前进激活/n/使玩家向前冲刺一段距离
biotic_stat.air_dash.name=凌空冲刺
biotic_stat.attack.details=攻击伤害提升%1$s
biotic_stat.attack.name=伤害增强
biotic_stat.auto_shield.details=在受到远程伤害时/n/自发激活护盾
biotic_stat.auto_shield.name=紧急护盾
biotic_stat.cloak.details=赋予玩家主动隐身能力。/n/激活时,每tick消耗%1$s能量/n/需要一个输出超过%1$s的电池
biotic_stat.cloak.name=隐身斗篷
biotic_stat.equalizer.details=内置时空均衡器/n/用于抵消来自于/n/引力异常点的影响
biotic_stat.equalizer.name=时空均衡器
biotic_stat.flash_cooling.details=/n/在武器过热时提升%s的瞬间冷却效果/n/每次冷却消耗%s
biotic_stat.flash_cooling.name=超频冷却
biotic_stat.floatation.details=能够浮在水面上
biotic_stat.floatation.name=气囊
biotic_stat.high_jump.details=潜行时跳的更高/n/每次弹跳消耗%1$s/n/需要一个输出超过%1$s的电池
biotic_stat.high_jump.name=蓄力弹跳
biotic_stat.inertial_dampers.details=消除摔落伤害 %s
biotic_stat.inertial_dampers.name=惯性阻尼器
biotic_stat.item_magnet.details=吸取掉落物品/n/每次吸取物品消耗 %s
biotic_stat.item_magnet.name=物品磁铁
biotic_stat.minimap.details=在HUD上添加小地图
biotic_stat.minimap.name=小地图
biotic_stat.nano_armor.details=吸收%1$s的攻击伤害
biotic_stat.nano_armor.name=纳米护甲
biotic_stat.nanobots.details=消耗%s/s/n/能量,提升%s生命恢复效率
biotic_stat.nanobots.name=纳米机器人
biotic_stat.nightvision.details=让玩家看穿黑暗。/n/激活时,每tick消耗%1$s能量/n/需要一个输出超过%1$s的电池
biotic_stat.nightvision.name=夜视
biotic_stat.oxygen.details=机体不再需要氧气
biotic_stat.oxygen.name=呼吸机
biotic_stat.shield.details=减免弹射物伤害
biotic_stat.shield.name=粒子护盾
biotic_stat.shockwave.details=爆发性地释放动能/n/对周围敌人造成伤害/n/并震飞最多至%1$s格/n/按下'%2$s'发动
biotic_stat.shockwave.name=音波震荡
biotic_stat.speed.details=移动速度提升 %1$s
biotic_stat.speed.name=超频
biotic_stat.step_assist.details=自动辅助攀登/n/一格高的方块
biotic_stat.step_assist.name=行走辅助
biotic_stat.teleport.details=按下'%1$s'键进行短距离传送,/n/每次传送消耗%2$s/n/需要一个输出超过 %2$s 的电池
biotic_stat.teleport.name=末影传送
biotic_stat.wireless_charger.details=为快捷栏除手持物品以外的/n/物品进行充能/n/充能速度:%s/t FE
biotic_stat.wireless_charger.name=无线充能
biotic_stat.zero_calories.details=无需有机营养
biotic_stat.zero_calories.name=辟谷
color.black=黑色
color.blue=蓝色
color.brown=棕色
color.cyan=青色
color.gray=灰色
color.green=绿色
color.lightBlue=淡蓝色
color.lime=黄绿色
color.magenta=品红色
color.orange=橙色
color.pink=粉红色
color.purple=紫色
color.red=红色
color.silver=淡灰色
color.white=白色
color.yellow=黄色
config.abilities.name=机械人能力
config.android_hud.bionicStats.position=仿生能力位置
config.android_hud.color=HUD颜色
config.android_hud.hide_vanilla=隐藏原版HUD
config.android_hud.minimap.position=小地图位置
config.android_hud.name=机械人HUD
config.android_hud.opacity=HUD透明度
config.android_hud.opacity_background=HUD不透明度
config.android_hud.stats.position=状态位置
config.client.name=客户端选项
config.compatibility.name=兼容性
config.debug.name=Debug
config.entities.name=生物
config.machine_options.name=机器
config.matter_network.name=物质网络
config.matter_registry.item_blacklist.name=黑名单
config.matter_registry.item_overrides.name=重写
config.matter_registry.name=物质注册
config.matter_registry.new_items.name=新
config.ore_gen_blacklist.name=矿物黑名单
config.server.name=服务器选项
config.spawn_ores.name=矿物生成
config.starmap.name=星图选项
config.world_gen.name=世界生成
container.replicator.name=重组机
container.tritanium_crate=三钛合金货箱
death.attack.android_transformation=%1$s抛弃了碳基物种的皮囊
death.attack.blackHole=%1$s被巨大的引力扭曲碾碎了
death.attack.phaser.item=%2$s用%3$s分解掉了%1$s
death.attack.phaser=%1$s被%2$s分解掉了
death.attack.plasmaBolt.item=%2$s用%3$s把%1$s打成了筛子
death.attack.plasmaBolt=%1$s被%2$s爆头
dialog.generic.back.0.question=别在意。
dialog.generic.back.1.question=让我们聊点别的吧。
dialog.generic.back.2.question=关我什么事。
dialog.generic.quit.0.question=回见。
dialog.generic.quit.1.question=我得走了。
dialog.generic.quit.2.question=我还有急事。
dialog.generic.quit.3.question=再见。
dialog.generic.quit.4.question=再会。
dialog.generic.quit.5.question=拜拜。
dialog.generic.trade.0.question=我想做个交易。
dialog.generic.trade.1.question=让我们做个买卖吧。
dialog.generic.trade.2.question=让我看看你的货物。
dialog.generic.trade.3.question=你都卖些什么?
dialog.mad_scientist.convert.question=我有全套机械人部件!
dialog.mad_scientist.junkie.cocktail_quest.0.line=你-你-你一定要帮助我,兄弟,你看。
dialog.mad_scientist.junkie.cocktail_quest.1.line=我有-有一个[§6嗝§r]超赞的配方,兄弟,就是一些神奇的东西混在一起,兄弟。
dialog.mad_scientist.junkie.cocktail_quest.2.line=它-它要比……不,它无可比拟,兄弟,它是一个辉煌的奇迹,兄弟[§6嗝§r]。
dialog.mad_scientist.junkie.cocktail_quest.3.line=但你看我还需要这些材料,兄弟!我-我需要些爬行者火药,兄弟,和-和[§6嗝§r]一些下界的蘑菇!
dialog.mad_scientist.junkie.cocktail_quest.4.line=但是你要知道,兄弟!嘿,别挠你屁股了,兄弟,这非-非-非常重要!
dialog.mad_scientist.junkie.cocktail_quest.4.question=[你开始挠屁股]
dialog.mad_scientist.junkie.cocktail_quest.5.line=这种火药只有用锹敲死爬行者才会保留效果,兄弟。
dialog.mad_scientist.junkie.cocktail_quest.5.question=抱歉。
dialog.mad_scientist.junkie.cocktail_quest.6.line=对,一把TMD锹,兄弟,你-你要铲碎它的脑子,重复这样的钝伤,兄弟,你才能获取好东西!
dialog.mad_scientist.junkie.cocktail_quest.6.question=一把锹?
dialog.mad_scientist.junkie.cocktail_quest.7.line=现在,快去,兄弟,赶紧的,兄弟,快!
dialog.mad_scientist.junkie.cocktail_quest.are_you_ok.question=你还好么?
dialog.mad_scientist.junkie.cocktail_quest.complete.question=我找到了你所说鸡尾酒的所有材料。
dialog.mad_scientist.junkie.cocktail_quest.line=啊是的,现在把材料给我吧兄弟,放下你扛着的材料,让我混合一下然后……[§6瘾君子将材料混到一起然后猛吸一口……§r]
dialog.mad_scientist.junkie.cocktail_quest.question.accept=§a我马上就去!
dialog.mad_scientist.junkie.cocktail_quest.question.decline=§c我才不去呢!
dialog.mad_scientist.junkie.cocktail_quest.question=你刚才说什么鸡尾酒?
dialog.mad_scientist.junkie.main.0.line=嘿小兄弟[§6嗝§r]。
dialog.mad_scientist.junkie.main.1.line=朋友最近过得如何?
dialog.mad_scientist.main.line.0.android=啊%1$s,很高兴见到你!来这有什么事么?
dialog.mad_scientist.main.line.0.human=我不和人类打交道。
dialog.mad_scientist.main.line.1.android=嘿,你今天看起来棒极了!
dialog.mad_scientist.main.line.1.human=天哪!简直无法直视。你太脆弱了!
dialog.mad_scientist.main.line.2.android=看起来你的左眼好像有些错位了,我很乐意帮你修复它。
dialog.mad_scientist.main.line.2.human=你还好么?你看起来糟透了!你怎么受得了这种皮囊?
dialog.mad_scientist.requirements.line=终于!<br>摆脱那具脆弱的肉体是最好的选择。<br>唯一的问题是,我们得准备好全套的机械人部件才行。
dialog.mad_scientist.requirements.question=我想化身机械战士。
dialog.mad_scientist.trade_route_quest.0.line=不可能!我还以为他死的时候把它弄丢了。真的是太感谢了。请收下这个..
dialog.mad_scientist.trade_route_quest.0.question=你知道有关贸易路线协议的信息么?
dialog.mad_scientist.trade_route_quest.1.line=我不知道你在说什么?没有什么,就是一些自动密封的阀杆螺栓。
dialog.mad_scientist.trade_route_quest.1.question=我注意到上面有关价格的东西,你在卖些什么?
dialog.mad_scientist.undo.line=你为什么想要这么做?唯一的办法就是吃掉一颗蓝色药丸。你可以在地牢中找到它,不过最好的办法是从别人手中买到。我想我的车间里可能有一些。我需要去查看一下。
dialog.mad_scientist.undo.question=我如何逆转这一过程?
dialog.mad_scientist.whatDidYouDo.line=你现在已经是机械人了!你将不需要食物,睡眠以及氧气。你可以在机械人装配台为你自己升级一些实用的能力,而且你将会看到并做到一些你无法想象的事情。
dialog.mad_scientist.whatDidYouDo.question=你对我做了些什么?
enchantment.matteroverdrive.weapon.damage=超频
entity.failed_chicken.name=失败品改造鸡
entity.failed_cow.name=失败品改造牛
entity.failed_pig.name=失败品改造猪
entity.failed_sheep.name=失败品改造羊
entity.mad_scientist.junkie.name=疯狂科学家(瘾君子)
entity.mad_scientist.name=疯狂科学家
entity.matteroverdrive.failed_chicken.name=失败品改造鸡
entity.matteroverdrive.failed_cow.name=失败品改造牛
entity.matteroverdrive.failed_pig.name=失败品改造猪
entity.matteroverdrive.failed_sheep.name=失败品改造羊
entity.matteroverdrive.mad_scientist.junkie.name=疯狂科学家(瘾君子)
entity.matteroverdrive.mad_scientist.name=疯狂科学家
entity.matteroverdrive.mutant_scientist.name=变异科学家
entity.matteroverdrive.ranged_rogue_android.name=枪战机械人
entity.matteroverdrive.rogue_android.name=混战机械人
entity.mutant_scientist.name=变异科学家
entity.ranged_rogue_android.name=枪战机械人
entity.rogue_android.name=混战机械人
entitymatteroverdrive..mad_scientist.name=疯狂科学家
fluid.matter_plasma=等离子物质
fluid.molten_tritanium=熔融三钛合金
fusion_reactor.info.anomaly_too_far=引力${newline}异常点${newline}过${newline}远
fusion_reactor.info.invalid_materials=无效${newline}材料
fusion_reactor.info.invalid_structure=无效${newline}结构
fusion_reactor.info.need_coils=NEED${newline}增加${newline}线圈数
fusion_reactor.info.no_anomaly=无${newline}引力${newline}异常点
fusion_reactor.info.ok=效率${power}${newline}储能${charge}${newline}物质${matter}
gui.android_hud.transforming.line.0=启动系统
gui.android_hud.transforming.line.1=构建神经网络
gui.android_hud.transforming.line.2=进行神经网络配置
gui.android_hud.transforming.line.3=正在安装驱动
gui.android_hud.transforming.line.4=校准机械臂
gui.android_hud.transforming.line.5=升级隐私策略
gui.android_hud.transforming.line.final=转化进行中
gui.charging_station.name=充能站
gui.config.mnet.address=地址
gui.config.owner=拥有者
gui.config.redstone=红石
gui.contract_market.name=赏金公会
gui.decomposer.name=物质分解机
gui.fusion_reactor.name=湮灭反应堆
gui.hologram.access_denied=拒绝访问
gui.inscriber.name=分子刻录仪
gui.label.accept=接受
gui.label.auto_line_size=自动调整每行大小
gui.label.button.add=添加
gui.label.button.import.too_far=目标距离过远
gui.label.button.import=输入
gui.label.button.new=新建
gui.label.button.remove=删除
gui.label.button.reset=重置
gui.label.button.save=保存
gui.label.button.scout=搜索
gui.matter_analyzer.name=物质分析仪
gui.network_router.name=物质网络路由器
gui.network_switch.name=物质网络转换器
gui.pattern_monitor.name=网络终端
gui.pattern_storage.name=模式保存仪
gui.recycler.name=物质回收机
gui.redstone_mode.disabled=禁用
gui.redstone_mode.high=高频
gui.redstone_mode.low=低频
gui.replicator.name=物质重组机
gui.solar_panel.name=光伏板
gui.time_until_next_quest=下次请求时间:%1$s
gui.tooltip.button.refresh=刷新列表
gui.tooltip.button.request=发送请求
gui.tooltip.close=关闭
gui.tooltip.close_menu=关闭菜单
gui.tooltip.energy.io=输入/输出
gui.tooltip.locks=锁定
gui.tooltip.matter.none=无
gui.tooltip.matter=物质
gui.tooltip.open_menu=打开菜单
gui.tooltip.page.configurations=配置界面
gui.tooltip.page.galaxy=星系
gui.tooltip.page.home=主页
gui.tooltip.page.planet=行星
gui.tooltip.page.quadrant=象限
gui.tooltip.page.scan_info=扫描信息
gui.tooltip.page.star=行星系
gui.tooltip.page.tasks=任务
gui.tooltip.page.upgrades=升级界面
gui.tooltip.parent=前置
gui.tooltip.quest.abandon=放弃选中任务
gui.tooltip.quest.accept=已接受任务
gui.tooltip.quest.active_quests=当前任务
gui.tooltip.quest.complete=已完成任务
gui.tooltip.requires=需要
gui.tooltip.slot.bionic.arms=手臂
gui.tooltip.slot.bionic.battery=电池
gui.tooltip.slot.bionic.chest=躯干
gui.tooltip.slot.bionic.head=头部
gui.tooltip.slot.bionic.legs=双腿
gui.tooltip.slot.bionic.other=外附
gui.tooltip.slot.database=模式数据库
gui.tooltip.slot.energy=FE能量
gui.tooltip.slot.filter=网络过滤器
gui.tooltip.slot.matter=物质
gui.tooltip.slot.pattern_storage=模式闪存插槽
gui.tooltip.slot.recycle=可循环
gui.tooltip.slot.shielding=防护
gui.tooltip.slot.upgrade=升级
gui.tooltip.slot.weapon=武器
gui.weapon_station.name=武器装配台
guide.category.android.name=机械人
guide.category.general.name=基础
guide.category.weapons.name=武器
guide.entry.android.parts.name=机械人部件
guide.entry.android.pills.name=药丸
guide.entry.batteries.name=能量单元
guide.entry.drinks.name=饮品
guide.entry.food.name=食物
guide.entry.fusion_reactor.name=湮灭反应堆
guide.entry.matter_fail.name=物质重组失败
guide.entry.matter_plasma.name=等离子物质
guide.entry.matter_transport.name=物质传输
guide.entry.tritanium_armor.name=三钛合金护甲
guide.entry.tritanium_tools.name=三钛合金工具
guide.entry.upgrades.name=升级
guide.entry.weapon.modules.barrels.name=武器枪管
guide.entry.weapon.modules.colors.name=武器颜色
guide.group.armor.name=护甲
guide.group.blocks.name=方块
guide.group.drinks.name=饮品
guide.group.food.name=食物
guide.group.items.name=物品
guide.group.machines.name=机器
guide.group.matter.name=物质
guide.group.matter_network.name=网络
guide.group.parts.name=部件
guide.group.power.name=能量
guide.group.resources.name=资源
guide.group.weapons.name=武器
info.matteroverdrive.updater.download=下载
info.matteroverdrive.updater.hover=点击下载最新版本。
item.matteroverdrive.android_pill_blue.details=吃下蓝色药丸后/n你将在床上一无所知地醒来
item.matteroverdrive.android_pill_blue.name=蓝色药丸
item.matteroverdrive.android_pill_red.details=吃下红色药丸后/n你将无所畏惧
item.matteroverdrive.android_pill_red.name=红色药丸
item.matteroverdrive.android_pill_yellow.details=重置机械人技能
item.matteroverdrive.android_pill_yellow.name=黄色药丸
item.matteroverdrive.artifact.name=未知工艺品
item.matteroverdrive.battery.name=电池
item.matteroverdrive.contract.name=任务卡
item.matteroverdrive.creative_battery.name=创造电池
item.matteroverdrive.creative_pattern_drive.details=包含绝大多数可重组物品/n潜行右键重置模式
item.matteroverdrive.creative_pattern_drive.name=创造模式保存单元
item.matteroverdrive.data_pad.details=存储着有关MatterOverdrive(超能物质)模组的信息
item.matteroverdrive.data_pad.name=数据仪
item.matteroverdrive.dilithium_crystal.name=二锂晶体
item.matteroverdrive.earl_gray_tea.name=格雷伯爵茶
item.matteroverdrive.emergency_ration.name=应急营养单元
item.matteroverdrive.energy_pack.details=用于快速充电/n为能量武器装弹
item.matteroverdrive.energy_pack.name=能量包
item.matteroverdrive.forcefield_emitter.name=力场发生器
item.matteroverdrive.h_compensator.name=海森堡补偿器
item.matteroverdrive.hc_battery.name=高能电池
item.matteroverdrive.integration_matrix.name=集成矩阵
item.matteroverdrive.ion_sniper.name=离子狙击枪
item.matteroverdrive.isolinear_circuit.mk1.name=等线性电路Mk1
item.matteroverdrive.isolinear_circuit.mk2.name=等线性电路Mk2
item.matteroverdrive.isolinear_circuit.mk3.name=等线性电路Mk3
item.matteroverdrive.isolinear_circuit.mk4.name=等线性电路Mk4
item.matteroverdrive.machine_casing.name=机械铸件
item.matteroverdrive.matter_container_empty.name=空物质仓
item.matteroverdrive.matter_container_full.name=满物质仓
item.matteroverdrive.matter_dust.details=放入物质回收机中回收精炼
item.matteroverdrive.matter_dust.name=物质粉尘
item.matteroverdrive.matter_dust_refined.name=精炼物质粉尘
item.matteroverdrive.matter_scanner.name=物质扫描仪
item.matteroverdrive.me_conversion_matrix.name=质能转换矩阵
item.matteroverdrive.network_flash_drive.details=为物质网络中的设备配置过滤功能
item.matteroverdrive.network_flash_drive.name=网络闪存驱动器
item.matteroverdrive.omni_tool.name=全效离子工具
item.matteroverdrive.pattern_drive.details=可保存2个物品模式
item.matteroverdrive.pattern_drive.name=模式保存单元
item.matteroverdrive.phaser.name=相位能量整流器
item.matteroverdrive.phaser_rifle.name=相位来复枪
item.matteroverdrive.plasma_core.name=相位能量整流核心
item.matteroverdrive.plasma_shotgun.name=相位散弹枪
item.matteroverdrive.portable_decomposer.details=将拾取的物品分解为等离子物质
item.matteroverdrive.portable_decomposer.name=便携式物质分解仪
item.matteroverdrive.quantum_fold_manipulator.name=量子折叠操纵仪
item.matteroverdrive.record.matteroverdrive.transformation.desc=BoxCat Games - Trace Route
item.matteroverdrive.rogue_android_part.arms.name=机械手臂
item.matteroverdrive.rogue_android_part.chest.name=机械躯干
item.matteroverdrive.rogue_android_part.head.name=机械头颅
item.matteroverdrive.rogue_android_part.legs.name=机械腿
item.matteroverdrive.rogue_android_part.melee=混战机械人
item.matteroverdrive.rogue_android_part.range=枪战机械人
item.matteroverdrive.romulan_ale.details=原产自罗慕兰醇香醉人的酒饮料
item.matteroverdrive.romulan_ale.name=罗慕兰麦酒
item.matteroverdrive.s_magnet.name=超导磁体
item.matteroverdrive.security_protocol.access.details=允许访问已设置安全协定的机器
item.matteroverdrive.security_protocol.access.name=安全协议[访问]
item.matteroverdrive.security_protocol.claim.details=锁定机器权限为私有
item.matteroverdrive.security_protocol.claim.name=安全协议[私有]
item.matteroverdrive.security_protocol.empty.name=安全协议
item.matteroverdrive.security_protocol.invalid=安全协议无效
item.matteroverdrive.security_protocol.remove.details=清除机器安全设置
item.matteroverdrive.security_protocol.remove.name=安全协议[清除]
item.matteroverdrive.sniper_scope.name=狙击镜
item.matteroverdrive.spacetime_equalizer.details=装备于胸甲位置可抵消引力异常
item.matteroverdrive.spacetime_equalizer.name=时空均衡仪
item.matteroverdrive.transport_flash_drive.details=记录坐标以便快速使用传送仪
item.matteroverdrive.transport_flash_drive.name=传送闪存驱动器
item.matteroverdrive.trilithium_crystal.name=纯净三锂晶体
item.matteroverdrive.tritanium_axe.name=三钛合金斧
item.matteroverdrive.tritanium_boots.name=三钛战靴
item.matteroverdrive.tritanium_chestplate.name=三钛胸甲
item.matteroverdrive.tritanium_dust.name=三钛合金粉
item.matteroverdrive.tritanium_helmet.name=三钛头盔
item.matteroverdrive.tritanium_hoe.name=三钛合金锄
item.matteroverdrive.tritanium_ingot.name=三钛合金锭
item.matteroverdrive.tritanium_leggings.name=三钛护腿
item.matteroverdrive.tritanium_nugget.name=三钛合金粒
item.matteroverdrive.tritanium_pickaxe.name=三钛合金镐
item.matteroverdrive.tritanium_plate.name=三钛合金板
item.matteroverdrive.tritanium_shovel.name=三钛合金锹
item.matteroverdrive.tritanium_spine.name=三钛脊骨
item.matteroverdrive.tritanium_sword.name=三钛合金剑
item.matteroverdrive.tritanium_wrench.details=安全地拆卸或旋转机器
item.matteroverdrive.tritanium_wrench.name=三钛合金扳手
item.matteroverdrive.upgrade.base.name=升级模板
item.matteroverdrive.upgrade.failsafe.name=故障保护升级
item.matteroverdrive.upgrade.hyper_speed.name=超速升级
item.matteroverdrive.upgrade.matter_storage.name=仓储升级
item.matteroverdrive.upgrade.power.name=能耗升级
item.matteroverdrive.upgrade.power_storage.name=储能升级
item.matteroverdrive.upgrade.range.name=范围升级
item.matteroverdrive.upgrade.speed.name=速度升级
item.matteroverdrive.weapon_handle.name=武器手柄
item.matteroverdrive.weapon_module_barrel.block.name=体素扩张失能湮灭矩阵(剧毒)
item.matteroverdrive.weapon_module_barrel.damage.name=二锂聚焦矩阵
item.matteroverdrive.weapon_module_barrel.doomsday.name=衰变聚爆矩阵(末日型)
item.matteroverdrive.weapon_module_barrel.explosion.name=爆裂电磁炮
item.matteroverdrive.weapon_module_barrel.fire.name=高能燃烧弹
item.matteroverdrive.weapon_module_barrel.heal.name=再生转换器
item.matteroverdrive.weapon_module_color.name=颜色模块
item.matteroverdrive.weapon_module_ricochet.name=束流反射装置
item.matteroverdrive.weapon_receiver.name=武装导能器
item.overdrivef.info.configured=已配置
itemGroup.tabMO=超能物质
itemGroup.tabMO_androidParts=超能物质 机械人部件
itemGroup.tabMO_contracts=超能物质 任务卡
itemGroup.tabMO_modules=超能物质 武器配件
machine.tooltip.energy=充能
machine.tooltip.matter=物质
material.tritanium=三钛合金
mo.jei.inscriber=分子刻录仪
mo.jei.time=%d秒
modifier.bionic.max_health=生命上限
module.barrel.name=枪管模块
module.battery.name=能量模块
module.color.black=黑色
module.color.blue=蓝色
module.color.brown=棕色
module.color.gold=金色
module.color.green=绿色
module.color.grey=灰色
module.color.lime_green=黄绿色
module.color.name=颜色模块
module.color.pink=粉红色
module.color.red=红色
module.color.sky_blue=天蓝色
module.other.name=附属模块
module.sights.name=视野模块
moduleslot.-1.name=模块未实装,请报告给模组作者。
moduleslot.0.name=可作为能量模块安装
moduleslot.1.name=可作为颜色模块安装
moduleslot.2.name=可作为枪管模块安装
moduleslot.3.name=可作为视野模块安装
moduleslot.4.name=可作为附属模块安装
quest.beast_belly.info=虽然难以启齿,但我们请求您作出牺牲,为了科学献身。你可曾遇见过引力异常点?我们仍未弄清物质进入事件视界后都发生了什么,只能观测到异常点变大,却不知消失的物质去了哪里。我们希望你能进入事件视界,观测里面的奥秘。当心哪,这会很危险的。
quest.beast_belly.objective.0=进入事件视界
quest.beast_belly.title=野兽之腹
quest.cocktail_of_ascension.info=曾经有一位疯狂科学家要你带给他%2$s份锹杀爬行者身上的火药和%3$s份下界最阴暗深处生长的红蘑菇,方便他调制鸡尾酒。
quest.cocktail_of_ascension.objective.0=用锹杀死%2$s/%3$s爬行者
quest.cocktail_of_ascension.objective.1=收集%2$s/%3$s份火药
quest.cocktail_of_ascension.objective.2=收集%2$s/%3$s枚红蘑菇
quest.cocktail_of_ascension.objective.3=跟疯狂科学家(瘾君子)进行交谈
quest.cocktail_of_ascension.title=调制鸡尾酒
quest.crash_landing.info=舰长日志 星历48940.8./n//n/星舰的左舷引擎已彻底烧毁,我不得不紧急着陆。我的应急营养单元还够撑一段时间,但是水罐已经报废了。/n/我必须马上外出寻找洁净的水源。/n/按照星图给出的信息,我应该是在猎户座旋臂的某处吧。我上次听说这个旋臂已经被机械垃圾占满了。/n/我想这意味着我不会在这里遇到能陪我聊天解闷的智能体了。/n/那件事大概是在我第一次拜访埃米莉的五年前吧。
quest.crash_landing.objective.0=制作$craftItem并试着用它破译终端以联络舰长的母星。
quest.crash_landing.title=坠毁
quest.department_of_agriculture.info=农业部欢迎勤劳能干者的加入。你可以想见,在荒芜的巴鲁斯V星上,种植%3$s是多么的不易。还没等到我们的水培农场建成投产,我们就已经饿殍遍地了。诚邀有能力者资助给我们%3$s,必有重谢。
quest.department_of_agriculture.objective.0=收获%2$s/%3$s %4$s
quest.department_of_agriculture.title=农业部
quest.gmo.info=复制蔬菜简直荒唐!/n/这堆复制品的味道就跟塑料似的!/n/不不不,我们需要的是另外一种东西。我已经迫不及待地想让我新研发的生物粒子传输系统运作起来了。看那些可怜的农民,就像牲口一样在耕地里劳作,只为种出少得可怜的一点庄稼。我只需要弄到作物的基因序列就好。问题在于那些愚昧的庄稼汉决不会让我接近他们的宝贝庄稼的。能不能用你的数据仪帮我扫描一些作物?报酬少不了的,我这还存着一些有点年头的机械人部件。
quest.gmo.objective.0=使用数据仪扫描$scanAmount/$maxScanAmount $block
quest.gmo.objective.1=现在再扫描$scanAmount/$maxScanAmount $block
quest.gmo.title=G.M.O
quest.is_it_really_me.info=我们的开发人员终于决定开始传送真人了。无论你在哪,我们都做好了进行下去的准备。在用非生命物体和动物进行了大量的精确实验后,我们已能将失败率压在25%以下。我们可以保证一切都会按照计划进行。当然啦,心理障碍肯定还是存在的,我们也搞不懂这套电子设备是怎么传送意识的,但我们相信你会说服自己的。就是踏上平台然后闭上眼,对吧。
quest.is_it_really_me.objective.0=使用传送仪
quest.is_it_really_me.title=这还是我自己吗?
quest.kill_androids.info=机械人正在抢走我们的世界!我不知道它们究竟来自何处,但它们的数量与日俱增,源源不绝。如若不想就此灭亡,我们必须奋起反抗!Player,带领我们战斗吧!在它们彻底夺取这个世界前,尽力干掉它们吧!
quest.kill_androids.objective.0=杀死$killCount/$maxKillCount机械人
quest.kill_androids.title=异族将屠净我等!
quest.one_true_love.info=我真的好开心!你甚至无法想象这一刻我是多么快乐!Merry终于同意嫁给我,你也许不知道我为这一刻付出了多少心血。不过这一切归根到底还是得力于她的父亲给予我们的祝福,我知道以我现在的能力足以给她一个美好生活,但我还是想给她一些特别的礼物。我希望你能帮助我找到一颗钻石,这样我就能做个钻戒戴在她的手上,我相信她一定会记住这难忘的一天。另外,作为回报,我很乐意尽我最大的能力帮助你。
quest.one_true_love.objective.0=采掘$mineAmount/$maxMineAmount钻石
quest.one_true_love.title=真挚的爱
quest.puny_humans.info=我与一位科学家谈过了,虽然他有点疯疯癫癫的,但还是让我受益匪浅。他已经同意为我进行生体改造手术,而我则需要准备好相应的整套机械人部件。得好好对付一下携带着这些部件的混战机械人了。
quest.puny_humans.objective.0=集齐全套机械人部件
quest.puny_humans.objective.1=与疯狂科学家交谈
quest.puny_humans.title=人类之孱弱
quest.sacrifice.info=我们是Dark Vail。我们正着手修复一件古代宝物,其功能则是个秘密。$player,我们希望你以黑暗领主之名献祭$maxKillCount只动物幼崽,成就黑暗领主的赫赫凶名。以黑暗领主巴里之名起誓,你将得到丰厚的回报。
quest.sacrifice.objective.0=屠戮$killCount/$maxKillCount幼崽
quest.sacrifice.title=献祭
quest.stem_bolts.info.0=与疯狂科学家的交谈让你有种被糊弄的感觉,那家伙肯定瞒着你什么。/n/在拿到贸易航线图的时候你就这么觉得了,所以在交还它前你留下了一份备份。你发觉你遗漏了某样事物。
quest.stem_bolts.info.1=找到了!在图的末尾提到了一份免责声明,大致意思是说舰队不会为电离辐射造成的基因损伤负责。你想搞清是什么样的货船才会引起这等突变,并决定返回货船寻找线索。
quest.stem_bolts.objective.0=阅读$itemName。
quest.stem_bolts.objective.1=返回货船。
quest.stem_bolts.title=自投罗网
quest.to_the_power_of.info=我得先开发出源源不绝的稳定能源,才能着手突破这有限的生命形式。
quest.to_the_power_of.objective.0=制造$craftAmount/$craftMaxAmount台$craftItem
quest.to_the_power_of.title=获取能量
quest.trade_route.info.2=打开舰长的箱子后你会发现一个带有位封条的$itemName,上面记录了提康德罗加到地球之间建立的贸易航线。你读不懂上面的文字,不过你很快就能发现决不骗人的利润。一趟航行的绿宝石就多得吓人。要是好奇这么多绿宝石是用来做什么贸易的话……还是问问这颗星球上的科学家们吧。
quest.trade_route.info=我知道穿过猎户座旋臂并不是最安全的选择,但这些天来还有哪算得上安全呢。我不知道人工智能蠢到啥程度才能忽视这么个有潜力的未开发市场。我想说的是它们到底在想啥啊?是不是自私到想把这里作为自己的保留地啊?/n/无论如何,我知道在猎户座旋臂的航程中许朋友永远地离开了我们,但这里的收益也太……太丰厚了点。/n/商队会在最近的一座村庄卸货,我也会加入他们,但在此之前,我要兑现对一位朋友的承诺。
quest.trade_route.objective.0=找到舰长的箱子并打开它。
quest.trade_route.objective.1=阅读$itemName。
quest.trade_route.objective.2=与$target交谈。
quest.trade_route.title=贸易航线
quest.we_must_know.info=感谢你联系我们。/n/我直到现在仍有一种巨大的不真实感……这样的打击太难以承受了。我也知道现在不是什么好世道,但我真的无法想象我的宝贝女儿现在的感受。/n/埃米莉是位坚强的女性,但我想她也很难接受这样的消息吧。/n/请你再帮我最后一次好吗?我想记述我同僚的牺牲,这也是我作为他直系长官的职责。见鬼,我也只能做到这一点了。/n/请你把我送你的$block安装好,可以吗?这样我们就能收好他的日记了。我知道他很关爱我的小埃米莉,希望这样能让我的女儿稍稍欣慰些吧。
quest.we_must_know.objective.0=将$block安装在距你$distance远的飞船附近。
quest.we_must_know.title=我们必须知道
quest.weapons_of_war.info=他们已经压迫了我们太久太久!我族的尊严决不能再这样被践踏下去,多少年的迫害将就此终结!但无论我们的精神多么顽强,我们的肉体也不会刀枪不入。所以我们需要你的帮助。尽管听上去并不美好,但在未来的战争中,他们必定会将所有的武装力量倒在我们头上,我们必须保护好自己。首先,我们需要铸造大批铁砧并打造紧缺的武器。
quest.weapons_of_war.objective.0=铸造$craftAmount/$craftMaxAmount$craftItem
quest.weapons_of_war.objective.1=打造$craftAmount把剑。
quest.weapons_of_war.title=战备武装
rarity.legendary=传奇
task.replicate_pattern.state.WAITING.description=正在搜索可用重组机。
task.state.FINISHED.description=任务已完成。
task.state.FINISHED.name=完成
task.state.INVALID.description=该任务无效。
task.state.INVALID.name=无效
task.state.PROCESSING.description=等待加工结束。
task.state.PROCESSING.name=处理中
task.state.QUEUED.description=已定位接收端。\n等待任务执行。
task.state.QUEUED.name=队列中
task.state.UNKNOWN.description=未知
task.state.UNKNOWN.name=未知
task.state.WAITING.description=正在搜寻接收端,请稍候。
task.state.WAITING.name=等待中
task.store_pattern.state.FINISHED.description=成功保存物品模式。
task.store_pattern.state.PROCESSING.description=正在保存物品模式。
task.store_pattern.state.QUEUED.description=队列中。\n等待任务执行。
task.store_pattern.state.WAITING.description=搜索模式保存空间。
tile.android_spawner.name=机械人刷怪箱
tile.android_station.details=机械人升级管理
tile.android_station.name=机械人改造台
tile.bounding_box.name=限界方块
tile.charging_station.details=为机械人充能
tile.charging_station.name=充能站
tile.contract_market.name=赏金公会
tile.decomposer.config.cost.decompose=分解耗能
tile.decomposer.config.speed.decompose=分解速度
tile.decomposer.config.storage.energy=能量储量
tile.decomposer.config.storage.matter=物质储量
tile.decomposer.details=将正常物质分解为等离子物质
tile.decomposer.name=物质分解机
tile.decorative.beams.name=三钛格栅
tile.decorative.carbon_fiber_plate.name=碳纤维板材
tile.decorative.clean.name=平滑三钛板材
tile.decorative.coils.name=线圈
tile.decorative.engine_exhaust_plasma.name=等离子引擎排流
tile.decorative.floor_noise.name=油地毡
tile.decorative.floor_tile_white.name=白瓷地砖
tile.decorative.floor_tiles.name=瓷地砖
tile.decorative.floor_tiles_green.name=绿瓷地砖
tile.decorative.holo_matrix.name=全息甲板
tile.decorative.matter_tube.name=物质管道
tile.decorative.separator.name=三钛导轨
tile.decorative.stripes.name=警戒纹板材
tile.decorative.tritanium_lamp.name=三钛灯饰
tile.decorative.tritanium_plate.name=三钛板材
tile.decorative.tritanium_plate_colored.name=染色三钛板材
tile.decorative.tritanium_plate_stripe.name=导向三钛板材
tile.decorative.vent.bright.name=通风口
tile.decorative.vent.dark.name=深色通风口
tile.decorative.white_plate.name=软壁隔板
tile.dilithium_ore.name=双锂矿石
tile.fusion_reactor_coil.details=用于限制湮灭反应堆内的等离子体
tile.fusion_reactor_coil.name=反应堆外层线圈
tile.fusion_reactor_controller.config.check.delay=结构检测延时
tile.fusion_reactor_controller.config.distance.anomaly=引力异常点最大距离
tile.fusion_reactor_controller.config.drain.matter=物质消耗
tile.fusion_reactor_controller.config.output.energy=能量输出
tile.fusion_reactor_controller.config.storage.energy=能量储存
tile.fusion_reactor_controller.config.storage.matter=物质储存
tile.fusion_reactor_controller.details=湮灭反应堆的主要控制装置
tile.fusion_reactor_controller.name=湮灭反应堆控制器
tile.fusion_reactor_io.name=湮灭反应堆接口
tile.gravitational_anomaly.name=引力异常点
tile.gravitational_stabilizer.details=用于减弱引力异常点的影响
tile.gravitational_stabilizer.name=引力稳定器
tile.heavy_matter_pipe.details=运输等离子物质
tile.heavy_matter_pipe.name=重型物质运输管道
tile.holo_sign.name=全息显示屏
tile.industrial_glass.name=工业玻璃
tile.inscriber.name=分子刻录仪
tile.machine_hull.name=机械外壳
tile.matter_analyzer.details=分析物品模式
tile.matter_analyzer.name=物质分析仪
tile.matter_pipe.details=运输等离子物质
tile.matter_pipe.name=物质运输管道
tile.matter_plasma.name=等离子物质
tile.matter_recycler.details=回收物质以便重新分解
tile.matter_recycler.name=物质回收机
tile.microwave.name=微波炉
tile.molten_tritanium.name=熔融三钛合金
tile.network_pipe.details=将设备接入物质网络
tile.network_pipe.name=物质网络线缆
tile.network_router.details=向内部机械传送信息或切换本地子网络
tile.network_router.name=物质网络路由器
tile.network_switch.details=将机器连接成本地网络
tile.network_switch.name=物质网络转换器
tile.pattern_monitor.details=用于管理复制任务
tile.pattern_monitor.name=物质网络终端
tile.pattern_storage.config.particles.vent=粒子排放
tile.pattern_storage.config.storage.energy=能量储存
tile.pattern_storage.config.transfer.energy=导能速率
tile.pattern_storage.details=保存物品模式以供复制
tile.pattern_storage.name=模式保存仪
tile.pylon.name=维度塔
tile.replicator.config.cost.replication.energy=单位物质重组能耗
tile.replicator.config.fail=失败概率
tile.replicator.config.particles.vent=粒子排放
tile.replicator.config.speed.replication=单位物质重组速率
tile.replicator.config.storage.energy=能量储量
tile.replicator.config.storage.matter=物质储量
tile.replicator.config.volume.replicate=复制数目
tile.replicator.details=将等离子物质重组为物品和方块
tile.replicator.name=物质重组机
tile.replicator_active.name=物质重组机
tile.solar_panel.details=利用光能发电
tile.solar_panel.name=光伏板
tile.spacetime_accelerator.details=加速方块和机器
tile.spacetime_accelerator.name=时空加速仪
tile.star_map.details=纯装饰用
tile.star_map.name=星图
tile.transporter.details=传送生物
tile.transporter.name=传送仪
tile.tritanium_block.name=三钛合金块
tile.tritanium_crate.name=三钛货箱
tile.tritanium_crate_black.name=黑色三钛货箱
tile.tritanium_crate_blue.name=蓝色三钛货箱
tile.tritanium_crate_brown.name=棕色三钛货箱
tile.tritanium_crate_cyan.name=青色三钛货箱
tile.tritanium_crate_gray.name=灰色三钛货箱
tile.tritanium_crate_green.name=绿色三钛货箱
tile.tritanium_crate_light_blue.name=淡蓝色三钛货箱
tile.tritanium_crate_lime.name=黄绿色三钛货箱
tile.tritanium_crate_magenta.name=品红色三钛货箱
tile.tritanium_crate_orange.name=橙色三钛货箱
tile.tritanium_crate_pink.name=粉红色三钛货箱
tile.tritanium_crate_purple.name=紫色三钛货箱
tile.tritanium_crate_red.name=红色三钛货箱
tile.tritanium_crate_silver.name=淡灰色三钛货箱
tile.tritanium_crate_white.name=白色三钛货箱
tile.tritanium_crate_yellow.name=黄色三钛货箱
tile.tritanium_ore.name=三钛矿石
tile.weapon_station.details=进行武器配置和充能
tile.weapon_station.name=武器装配台
upgradetype.Fail.name=故障
upgradetype.MatterStorage.name=物质存储
upgradetype.MatterUsage.name=物质消耗
upgradetype.Output.name=输出
upgradetype.PowerStorage.name=能量存储
upgradetype.PowerUsage.name=能耗
upgradetype.Range.name=范围
upgradetype.SecondOutput.name=次级输出
upgradetype.Speed.name=时间
weaponstat.accuracy.name=精准度
weaponstat.ammo.name=弹药
weaponstat.block_damage.name=范围伤害
weaponstat.damage.name=伤害
weaponstat.effect.name=效果
weaponstat.explosion_damage.name=爆炸伤害
weaponstat.fire_damage.name=火焰伤害
weaponstat.fire_rate.name=射击速度
weaponstat.heal.name=治疗
weaponstat.max_heat.name=热量上限
weaponstat.range.name=射程
weaponstat.ricochet.name=反射
| 0 | 0.722557 | 1 | 0.722557 | game-dev | MEDIA | 0.856324 | game-dev | 0.565321 | 1 | 0.565321 |
ericraio/vanilla-wow-addons | 22,731 | i/IntensityAH/IntensityAH.lua | IMA_Settings = {};
local IMA_NUMITEMBUTTONS = 18;
local IMA_Playername = nil;
local IMA_AuctionFrameTab_OnClickOrig = nil;
local IMA_PickupContainerItemOrig = nil;
local IMA_ContainerFrame_UpdateOrig = nil;
function IMA_PickupContainerItem(bag, item)
-- pass through if auction window not open or item already in
if ( not AuctionFrame:IsVisible() ) then
IMA_PickupContainerItemOrig(bag, item);
return;
end
if ( IMA_GetItemFrame(bag, item) ) then
return;
end
if ( not CursorHasItem() ) then
IMA_ClearAuctionSellItem();
IMA_AuctionFrameMassAuction.bag = bag;
IMA_AuctionFrameMassAuction.item = item;
end
if ( IsAltKeyDown() and IMA_AuctionFrameMassAuction:IsVisible() and not CursorHasItem() ) then
IMA_ClearAuctionSellItem();
local i;
for i = 1, IMA_NUMITEMBUTTONS, 1 do
if ( not getglobal("IMA_Item"..i.."ItemButton").item ) then
IMA_PickupContainerItemOrig(bag, item);
IMA_ItemButton_OnClick(getglobal("IMA_Item"..i.."ItemButton"));
IMA_UpdateItemButtons();
return;
end
end
elseif ( IsAltKeyDown() and not CursorHasItem() ) then
IMA_ClearAuctionSellItem();
IMA_PickupContainerItemOrig(bag, item);
ClickAuctionSellItemButton();
return;
end
IMA_PickupContainerItemOrig(bag, item);
IMA_UpdateItemButtons();
end
-- Controls the 4th tab in AuctionFrame
function IMA_AuctionFrameTab_OnClick(index)
-- no Sea req
if ( IMA_AuctionFrameTab_OnClickOrig ~= nil ) then
IMA_AuctionFrameTab_OnClickOrig(index);
end
if ( not index ) then
index = this:GetID();
end
if ( index == 4 ) then
-- MassAuction tab
AuctionFrameTopLeft:SetTexture("Interface\\AuctionFrame\\UI-AuctionFrame-Bid-TopLeft");
AuctionFrameTop:SetTexture("Interface\\AuctionFrame\\UI-AuctionFrame-Bid-Top");
AuctionFrameTopRight:SetTexture("Interface\\AuctionFrame\\UI-AuctionFrame-Bid-TopRight");
AuctionFrameBotLeft:SetTexture("Interface\\AuctionFrame\\UI-AuctionFrame-Bid-BotLeft");
AuctionFrameBot:SetTexture("Interface\\AuctionFrame\\UI-AuctionFrame-Bid-Bot");
AuctionFrameBotRight:SetTexture("Interface\\AuctionFrame\\UI-AuctionFrame-Bid-BotRight");
-- this is to fix a bug where the AuctionsFrame can't handle having auctions added without it showing first
if (AuctionFrameAuctions.page == nil) then
AuctionFrameAuctions.page = 0;
end
IMA_AuctionFrameMassAuction:Show();
else
IMA_AuctionFrameMassAuction:Hide();
end
end
function IMA_ContainerFrame_Update(frame)
if ( IMA_ContainerFrame_UpdateOrig ~= nil ) then
IMA_ContainerFrame_UpdateOrig(frame)
end
if ( not IMA_AuctionFrameMassAuction:IsVisible() ) then
return;
end
local id = frame:GetID();
local i;
for i = 1, IMA_NUMITEMBUTTONS, 1 do
local btn = getglobal("IMA_Item"..i.."ItemButton");
if ( btn.item and btn.bag ) then
if ( btn.bag == frame:GetID() ) then
SetItemButtonDesaturated(getglobal(frame:GetName() .. "Item" .. (frame.size-btn.item)+1), 1, 0.5, 0.5, 0.5);
end
end
end
end
function IMA_AuctionFrameMassAuction_OnLoad()
-- Igors Mass Auction makes some hooks
-- AuctionFrameTab_OnClick - lets us access our 4th tab
-- PickupContainerItem - grabs something from a bag with the mouse
IMA_PickupContainerItemOrig = PickupContainerItem
if ( Sea ~= nil and Sea.util ~= nil and Sea.util.hook ~= nil ) then
Sea.util.hook("AuctionFrameTab_OnClick","IMA_AuctionFrameTab_OnClick","after");
Sea.util.hook("PickupContainerItem","IMA_PickupContainerItem","replace");
Sea.util.hook("ContainerFrame_Update","IMA_ContainerFrame_Update","after");
else
-- no Sea req code
IMA_AuctionFrameTab_OnClickOrig = AuctionFrameTab_OnClick;
AuctionFrameTab_OnClick = IMA_AuctionFrameTab_OnClick;
PickupContainerItem = IMA_PickupContainerItem;
IMA_ContainerFrame_UpdateOrig = ContainerFrame_Update;
ContainerFrame_Update = IMA_ContainerFrame_Update;
end
for i = 1, IMA_NUMITEMBUTTONS, 1 do
IMA_AuctionsRadioButton_OnClick(i,3);
end
this:RegisterEvent("UNIT_NAME_UPDATE");
this:RegisterEvent("AUCTION_HOUSE_CLOSED");
end
function IMA_AuctionFrameMassAuction_OnShow()
IMA_UpdateItemButtons();
for i = 1, IMA_NUMITEMBUTTONS, 1 do
IMA_AuctionsRadioButton_OnClick(i,IMA_Settings["duration"..i])
end
end
function IMA_SetItemAsAuction(itemindex)
IMA_ClearAuctionSellItem();
-- first see if something is in that slot
but = getglobal("IMA_Item"..itemindex.."ItemButton");
if ( but.bag == nil or but.item == nil) then return end
-- if we have something on cursor already, remember it
oldbag = IMA_AuctionFrameMassAuction.bag;
olditem = IMA_AuctionFrameMassAuction.item;
-- if we are already holding what we want
if (but.bag == oldbag and but.item == olditem) then
ClickAuctionSellItemButton();
return;
end
-- put down what we had
if ( oldbag ~= nil and olditem ~= nil) then
IMA_PickupContainerItemOrig(oldbag,olditem);
end
-- pick up the new thing and put it in
IMA_PickupContainerItemOrig(but.bag,but.item);
ClickAuctionSellItemButton();
IMA_PickupContainerItemOrig(but.bag,but.item);
-- pick up what we had
if ( oldbag ~= nil and olditem ~= nil) then
IMA_PickupContainerItemOrig(oldbag,olditem);
end
end
function IMA_FindAuctionItem()
for bag = 0,4,1 do
slots = GetContainerNumSlots(bag)
if (slots ~= nil and slots > 0) then
for item = 1, slots, 1 do
local texture, itemCount, locked, quality, readable = GetContainerItemInfo(bag,item);
local lockedstr = locked;
if ( locked == nil ) then
lockedstr = "nil";
end
if ( itemCount ~= nil and itemCount > 0 and locked ~= nil ) then
return bag,item;
end
end
end
end
return nil;
end
-- this function assumes that itemindex is the current active auction item
function IMA_SetInitialPrices(btn)
local scheme = UIDropDownMenu_GetSelectedValue(IMA_PriceSchemeDropDown);
scheme = string.gsub(scheme," ","_");
local name, texture, count, quality, canUse, price = GetAuctionSellItemInfo();
local start = max(100, floor(price * 1.5));
local buyout = 0;
pricefunc = getglobal("IMA_"..scheme.."_GetPriceAndBuyout");
if (pricefunc ~= nil) then
local start2 = nil;
local buyout2 = nil;
start2, buyout2 = pricefunc(btn.bag,btn.item,btn.count,btn.texture,btn.name,btn.price,start)
if (start2 ~= nil) then
start = start2;
end
if (buyout2 ~= nil) then
buyout = buyout2;
end
end
MoneyInputFrame_SetCopper(getglobal(btn:GetParent():GetName().."StartPrice"), start);
MoneyInputFrame_SetCopper(getglobal(btn:GetParent():GetName().."BuyoutPrice"), buyout);
end
-- TODO: Make this work
function IMA_AuctionsFrameAuctions_ValidateAuction(itemindex)
--IMA_AuctionsCreateAuctionButton:Disable();
--IMA_AuctionsBuyoutErrorText:Hide();
-- No item
if ( not GetAuctionSellItemInfo() ) then
return;
end
-- Buyout price is less than the start price
--if ( MoneyInputFrame_GetCopper(IMA_BuyoutPrice) > 0 and MoneyInputFrame_GetCopper(IMA_StartPrice) > MoneyInputFrame_GetCopper(IMA_BuyoutPrice) ) then
--IMA_AuctionsBuyoutErrorText:Show();
--return;
--end
-- Start price is 0
--if ( MoneyInputFrame_GetCopper(IMA_StartPrice) < 1 ) then
--return;
--end
--IMA_AuctionsCreateAuctionButton:Enable();
end
function IMA_AuctionsRadioButton_OnClick(itemindex,index)
if index == nil then
index = 3;
end
getglobal("IMA_Item"..itemindex.."ShortAuction"):SetChecked(nil)
getglobal("IMA_Item"..itemindex.."MediumAuction"):SetChecked(nil)
getglobal("IMA_Item"..itemindex.."LongAuction"):SetChecked(nil)
if ( index == 1 ) then
getglobal("IMA_Item"..itemindex.."ShortAuction"):SetChecked(1)
getglobal("IMA_Item"..itemindex).duration = 120;
elseif ( index ==2 ) then
getglobal("IMA_Item"..itemindex.."MediumAuction"):SetChecked(1)
getglobal("IMA_Item"..itemindex).duration = 480;
else
getglobal("IMA_Item"..itemindex.."LongAuction"):SetChecked(1)
getglobal("IMA_Item"..itemindex).duration = 1440;
end
IMA_Settings["duration"..itemindex] = index;
-- maybe sure this is the current item before we update
IMA_SetItemAsAuction(itemindex);
IMA_UpdateDeposit(itemindex);
end
function IMA_UpdateDeposit(itemindex, amount)
if ( amount == nil ) then
amount = CalculateAuctionDeposit(getglobal("IMA_Item"..itemindex).duration);
end
if ( amount == nil ) then
amount = 0;
end
MoneyFrame_Update("IMA_Item"..itemindex.."DepositCharge",amount)
end
-- this function assumes you don't have something on the cursor already
function IMA_ClearAuctionSellItem()
if ( GetAuctionSellItemInfo() ~= nil ) then
ClickAuctionSellItemButton();
local bag, item = IMA_FindAuctionItem();
IMA_PickupContainerItemOrig(bag, item);
end
end
-- Handles the draggin of items
function IMA_ItemButton_OnClick(button)
if ( not button ) then
button = this;
end
if ( CursorHasItem() ) then
local bag = IMA_AuctionFrameMassAuction.bag;
local item = IMA_AuctionFrameMassAuction.item;
if ( not bag or not item ) then return; end
-- put it in auction slot while we're holding it
ClickAuctionSellItemButton();
-- We'll still be holding the item if it fails
if (CursorHasItem()) then
IMA_PickupContainerItemOrig(bag, item);
return;
end
-- put the item back
IMA_PickupContainerItemOrig(bag, item);
if ( this.bag and this.item ) then
-- There's already an item there
IMA_PickupContainerItemOrig(button.bag, button.item);
IMA_AuctionFrameMassAuction.bag = button.bag;
IMA_AuctionFrameMassAuction.item = button.item;
else
IMA_AuctionFrameMassAuction.bag = nil;
IMA_AuctionFrameMassAuction.item = nil;
end
local texture, count = GetContainerItemInfo(bag, item);
getglobal(button:GetName() .. "IconTexture"):Show();
getglobal(button:GetName() .. "IconTexture"):SetTexture(texture);
if ( count > 1 ) then
getglobal(button:GetName() .. "Count"):SetText(count);
getglobal(button:GetName() .. "Count"):Show();
else
getglobal(button:GetName() .. "Count"):Hide();
end
local name, texture, count, quality, canUse, price = GetAuctionSellItemInfo();
button.bag = bag;
button.item = item;
button.texture = texture;
button.count = count;
button.name = name;
button.price = price;
-- set our item count based on the first item
if (button:GetParent():GetID() == 1) then
IMA_AllSamePriceFrameStackSize:SetText(count);
end
IMA_UpdateDeposit(button:GetParent():GetID());
IMA_SetInitialPrices(button);
elseif ( button.item and button.bag ) then
IMA_ClearAuctionSellItem();
IMA_PickupContainerItemOrig(button.bag, button.item);
getglobal(button:GetName() .. "IconTexture"):Hide();
getglobal(button:GetName() .. "Count"):Hide();
IMA_AuctionFrameMassAuction.bag = button.bag;
IMA_AuctionFrameMassAuction.item = button.item;
button.item = nil;
button.bag = nil;
button.count = nil;
button.texture = nil;
button.name = nil;
button.price = nil;
end
IMA_UpdateItemButtons();
-- TODO: Display the total deposit
for i = 1, NUM_CONTAINER_FRAMES, 1 do
if ( getglobal("ContainerFrame" .. i):IsVisible() ) then
ContainerFrame_Update(getglobal("ContainerFrame" .. i));
end
end
end
function IMA_UpdateItemButtons(frame)
local i;
local num = 0;
local totalDeposit = 0;
for i = 1, IMA_NUMITEMBUTTONS, 1 do
local btn = getglobal("IMA_Item"..i.."ItemButton");
if ( not frame or btn ~= frame ) then
local texture, count;
if ( btn.item and btn.bag ) then
texture, count = GetContainerItemInfo(btn.bag, btn.item);
end
if ( not texture ) then
getglobal(btn:GetName() .. "IconTexture"):Hide();
getglobal(btn:GetName() .. "Count"):Hide();
btn.item = nil;
btn.bag = nil;
btn.count = nil;
btn.texture = nil;
btn.name = nil;
btn.price = nil;
IMA_UpdateDeposit(btn:GetParent():GetID(),0);
MoneyInputFrame_SetCopper(getglobal(btn:GetParent():GetName().."StartPrice"), 0);
MoneyInputFrame_SetCopper(getglobal(btn:GetParent():GetName().."BuyoutPrice"), 0);
else
num = num + 1
local deposit = getglobal(btn:GetParent():GetName().."DepositCharge").staticMoney;
if ( deposit ~= nil ) then
totalDeposit = totalDeposit + deposit;
end
btn.count = count;
btn.texture = texture;
getglobal(btn:GetName() .. "IconTexture"):Show();
getglobal(btn:GetName() .. "IconTexture"):SetTexture(texture);
if ( count > 1 ) then
getglobal(btn:GetName() .. "Count"):Show();
getglobal(btn:GetName() .. "Count"):SetText(count);
else
getglobal(btn:GetName() .. "Count"):Hide();
end
end
end
end
IMA_AuctionFrameMassAuction.num = num;
IMA_AuctionFrameMassAuction.totalDeposit = totalDeposit;
if ( num > 0 ) then
IMA_AuctionsClearButton:Enable();
IMA_AuctionsSubmitButton:Enable();
else
IMA_AuctionsClearButton:Disable();
IMA_AuctionsSubmitButton:Disable();
end
end
function IMA_GetItemFrame(bag, item)
local i;
for i = 1, IMA_NUMITEMBUTTONS, 1 do
local btn = getglobal("IMA_Item"..i.."ItemButton");
if ( btn.item == item and btn.bag == bag ) then
return btn;
end
end
return nil;
end
function IMA_ClearItems()
local i;
local num = 0;
for i = 1, IMA_NUMITEMBUTTONS, 1 do
local item = getglobal("IMA_Item"..i);
local btn = getglobal(item:GetName().."ItemButton");
MoneyInputFrame_SetCopper(getglobal(item:GetName().."StartPrice"), 0);
MoneyInputFrame_SetCopper(getglobal(item:GetName().."BuyoutPrice"), 0);
IMA_UpdateDeposit(i,0);
btn.item = nil;
btn.count = nil;
btn.bag = nil;
btn.texture = nil;
btn.name = nil;
btn.price = nil;
end
IMA_UpdateItemButtons();
IMA_ClearAuctionSellItem();
end
function IMA_ClearItem(bag,item)
local i;
for i = 1, IMA_NUMITEMBUTTONS, 1 do
local item = getglobal("IMA_Item"..i);
local btn = getglobal(item:GetName().."ItemButton");
if (btn.bag == bag and btn.item == item) then
MoneyInputFrame_SetCopper(getglobal(item:GetName().."StartPrice"), 0);
MoneyInputFrame_SetCopper(getglobal(item:GetName().."BuyoutPrice"), 0);
IMA_UpdateDeposit(i,0);
btn.item = nil;
btn.count = nil;
btn.bag = nil;
btn.texture = nil;
btn.name = nil;
btn.price = nil;
return;
end
end
IMA_UpdateItemButtons();
end
function IMA_OnEvent()
if (( event == "UNIT_NAME_UPDATE" ) and (arg1 == "player")) then
local playername = UnitName("player");
IMA_Playername = playername;
elseif ( event == "AUCTION_HOUSE_CLOSED" ) then
IMA_ClearItems();
IMA_GlobalFrame.total = 0;
IMA_GlobalFrame.queue = { };
end
end
function IMA_AcceptSendFrame_OnShow()
getglobal(this:GetName().."Info"):Show();
getglobal(this:GetName().."InfoString"):Show();
getglobal(this:GetName().."MoneyFrame"):Show();
getglobal(this:GetName().."InfoItems"):SetText(IMA_AuctionFrameMassAuction.num .. " " .. IMA_ITEMS);
getglobal(this:GetName().."SubmitButton"):Enable();
IMA_UpdateItemButtons();
MoneyFrame_Update(this:GetName() .. "MoneyFrame", IMA_AuctionFrameMassAuction.totalDeposit);
end
function IMA_AcceptSendFrameSubmitButton_OnClick()
IMA_GlobalFrame.queue = IMA_FillItemTable();
IMA_GlobalFrame.total = getn(IMA_GlobalFrame.queue);
IMA_GlobalFrame.sent = 0;
getglobal(this:GetParent():GetName().."Info"):Hide();
getglobal(this:GetParent():GetName().."InfoString"):Hide();
getglobal(this:GetParent():GetName().."MoneyFrame"):Hide();
this:Disable();
end
function IMA_AcceptSendFrameCancelButton_OnClick()
this:GetParent():Hide();
IMA_GlobalFrame.queue = {};
IMA_GlobalFrame.total = 0;
IMA_GlobalFrame.sent = 0;
end
function IMA_FillItemTable()
local arr = { };
for i = 1, IMA_NUMITEMBUTTONS, 1 do
local item = getglobal("IMA_Item"..i);
local btn = getglobal(item:GetName().."ItemButton");
local price = MoneyInputFrame_GetCopper(getglobal(item:GetName().."StartPrice"));
local buyout = MoneyInputFrame_GetCopper(getglobal(item:GetName().."BuyoutPrice"));
if ( btn.item and btn.bag ) then
tinsert(arr, { ["item"] = btn.item, ["bag"] = btn.bag, ["price"] = price,
["buyout"] = buyout, ["duration"] = item.duration });
end
end
return arr;
end
function IMA_ProcessQueue(elapsed)
if ( this.bag ~= nil and this.item ~= nil ) then
if ( GetContainerItemInfo(this.bag, this.item) == nil ) then
this.sent = this.sent + 1;
IMA_ClearItem(this.bag,this.item);
this.bag = nil;
this.item = nil;
if (this.sent == this.total) then
IMA_AcceptSendFrame:Hide();
end
end
end
if ( this.total == 0 ) then
return;
end
if ( this.bag == nil and this.item == nil ) then
IMA_StartAuction();
IMA_AcceptSendFrameInfoItems:SetText(
IMA_POSTING_ITEM..(this.sent+1)..IMA_OF..this.total.."...")
end
end
function IMA_StartAuction()
IMA_ClearAuctionSellItem();
key, val = next(this.queue);
if (key == nil) then
this.total = 0;
this.bag = nil;
this.item = nil;
this.queue = { };
return;
end
this.bag = val.bag;
this.item = val.item;
-- put down what we picked up so things don't mess up
if ( CursorHasItem() and IMA_AuctionFrameMassAuction.bag and IMA_AuctionFrameMassAuction.item ) then
PickupContainerItem(IMA_AuctionFrameMassAuction.bag, IMA_AuctionFrameMassAuction.item);
IMA_AuctionFrameMassAuction.bag = nil;
IMA_AuctionFrameMassAuction.item = nil;
end
IMA_PickupContainerItemOrig(val.bag, val.item);
ClickAuctionSellItemButton();
local name, texture, count, quality, canUse, price = GetAuctionSellItemInfo();
if ( not name ) then
DEFAULT_CHAT_FRAME:AddMessage("<MassAuction> " .. IMA_ERROR, 1, 0, 0);
else
-- these 3 lines help with compatability
MoneyInputFrame_SetCopper(StartPrice, val.price);
MoneyInputFrame_SetCopper(BuyoutPrice, val.buyout);
AuctionFrameAuctions.duration = val.duration;
StartAuction(val.price, val.buyout, val.duration);
end
this.queue[key] = nil;
return;
end
-- SET PRICES DROPDOWN CODE
function IMA_PriceSchemeDropDown_OnShow()
IMA_PriceSchemeDropDown_OnLoad();
-- set default if none
if IMA_Settings.DropDown == nil then
IMA_Settings.DropDown = "Default";
end
getglobal("IMA_" .. IMA_Settings.DropDown .. "_function")();
end
function IMA_PriceSchemeDropDown_OnLoad()
UIDropDownMenu_Initialize(this, IMA_PriceSchemeDropDown_Initialize);
end
function IMA_ClearTopFrame()
if IMA_MultiplierFrame then
IMA_MultiplierFrame:Hide();
IMA_AllSamePriceFrame:Hide();
IMA_EasyAuctionFrame:Hide();
end
end
function IMA_Default_function()
UIDropDownMenu_SetSelectedValue(IMA_PriceSchemeDropDown, "Default");
IMA_ClearTopFrame();
IMA_Settings.DropDown = "Default";
end
function IMA_Multiplier_function()
UIDropDownMenu_SetSelectedValue(IMA_PriceSchemeDropDown, "Multiplier");
IMA_ClearTopFrame();
IMA_MultiplierFrame:Show();
IMA_Settings.DropDown = "Multiplier";
end
function IMA_AllSamePrice_function()
UIDropDownMenu_SetSelectedValue(IMA_PriceSchemeDropDown, "AllSamePrice");
IMA_ClearTopFrame();
IMA_AllSamePriceFrame:Show();
IMA_Settings.DropDown = "AllSamePrice";
end
function IMA_EasyAuction_function()
UIDropDownMenu_SetSelectedValue(IMA_PriceSchemeDropDown, "EasyAuction");
IMA_ClearTopFrame();
IMA_EasyAuctionFrame:Show();
IMA_Settings.DropDown = "EasyAuction";
end
function IMA_PriceSchemeDropDown_Initialize()
local info = {};
info.text = IMA_DEFAULT;
info.value = "Default";
info.func = IMA_Default_function;
UIDropDownMenu_AddButton(info);
info = {};
info.text = IMA_VALUE_MULTIPLIER;
info.value = "Multiplier";
info.func = IMA_Multiplier_function;
UIDropDownMenu_AddButton(info);
info = {};
info.text = IMA_ALL_SAME_PRICE;
info.value = "AllSamePrice";
info.func = IMA_AllSamePrice_function;
UIDropDownMenu_AddButton(info);
info = {};
info.text = IMA_EASY_AUCTION;
info.value = "EasyAuction";
info.func = IMA_EasyAuction_function;
UIDropDownMenu_AddButton(info);
end
function IMA_SetAllPricesButton_OnClick()
local scheme = UIDropDownMenu_GetSelectedValue(IMA_PriceSchemeDropDown);
scheme = string.gsub(scheme," ","_");
pricefunc = getglobal("IMA_"..scheme.."_GetPriceAndBuyout");
if (pricefunc == nil) then
return;
end
IMA_ClearAuctionSellItem();
for i = 1, IMA_NUMITEMBUTTONS, 1 do
local item = getglobal("IMA_Item"..i);
local btn = getglobal(item:GetName().."ItemButton");
if (btn.bag ~= nil and btn.item ~= nil) then
if (true and true) then -- put checkbox code here
price, buyout = pricefunc(btn.bag,btn.item,btn.count,btn.texture,btn.name,btn.price,
MoneyInputFrame_GetCopper(getglobal(item:GetName().."StartPrice")))
if (price ~= nil) then
MoneyInputFrame_SetCopper(getglobal(item:GetName().."StartPrice"),price);
end
if (buyout ~= nil) then
MoneyInputFrame_SetCopper(getglobal(item:GetName().."BuyoutPrice"),buyout);
end
end
end
end
end
function IMA_Default_GetPriceAndBuyout(bag, item, count, texture, name, price, currentstart)
start = MoneyInputFrame_GetCopper(StartPrice);
buyout = MoneyInputFrame_GetCopper(BuyoutPrice);
return start, buyout;
end
function IMA_Multiplier_GetPriceAndBuyout(bag, item, count, texture, name, price, currentstart)
local retprice = nil;
local retbuyout = nil;
if (IMA_MultiplierFramePriceCheckButton:GetChecked()) then
pricepercent = IMA_MultiplierFramePriceMultiplier:GetText() + 0;
if (pricepercent >= 1 and pricepercent <= 9999) then
retprice = max(100,floor(price * pricepercent / 100.0));
currentstart = retprice + 0;
end
end
if (IMA_MultiplierFrameBuyoutCheckButton:GetChecked()) then
buyoutpercent = IMA_MultiplierFrameBuyoutMultiplier:GetText() + 0;
if (buyoutpercent >= 1 and buyoutpercent <= 9999) then
retbuyout = floor(currentstart * buyoutpercent / 100.0);
end
end
return retprice,retbuyout
end
function IMA_AllSamePrice_GetPriceAndBuyout(bag, item, count, texture, name, price, currentstart)
local price = MoneyInputFrame_GetCopper(IMA_AllSamePriceFrameStartPrice);
local buyout = MoneyInputFrame_GetCopper(IMA_AllSamePriceFrameBuyoutPrice);
local basecount = IMA_AllSamePriceFrameStackSize:GetText() + 0;
if (basecount > 0 and count ~= basecount) then
price = floor(price / basecount * count);
buyout = floor(buyout / basecount * count);
end
return price,buyout;
end
function IMA_EasyAuction_GetPriceAndBuyout(bag, item, count, texture, name, price, currentstart)
local start = nil;
local buyout = nil;
if (EasyAuction_Prices ~= nil and EasyAuction_PersonalPrices ~= nil) then
local lastauction = nil;
if (IMA_Playername ~= nil and EasyAuction_PersonalPrices[IMA_Playername] ~= nil
and EasyAuction_PersonalPrices[IMA_Playername][name] ~= nil) then
lastauction = EasyAuction_PersonalPrices[IMA_Playername][name];
else
if (EasyAuction_Prices[name] ~= nil) then
lastauction = EasyAuction_Prices[name];
end
end
if (lastauction ~= nil) then
start = lastauction.bid * count;
buyout = lastauction.buyout * count;
end
end
return start,buyout;
end
| 0 | 0.791671 | 1 | 0.791671 | game-dev | MEDIA | 0.76632 | game-dev | 0.917516 | 1 | 0.917516 |
smlu/OpenJones3D | 27,311 | Libs/sith/World/sithSector.c | #include "sithSector.h"
#include <j3dcore/j3dhook.h>
#include <sith/RTI/symbols.h>
#include <rdroid/Math/rdVector.h>
#include <sith/Devices/sithComm.h>
#include <sith/Devices/sithSound.h>
#include <sith/Dss/sithDSS.h>
#include <sith/Engine/sithIntersect.h>
#include <sith/World/sithSurface.h>
#include <sith/World/sithWorld.h>
#include <sith/World/sithThing.h>
#include <sound/Sound.h>
#include <std/General/stdConffile.h>
#include <std/General/stdMemory.h>
#include <std/General/stdUtil.h>
static SithSector* sithSector_aModifiedSectors[16] = { 0 }; // Added Init to 0
static int sithSector_aSyncFlags[16];
static size_t sithSector_numModifiedSectors = 0; // Added Init to 0
void sithSector_InstallHooks(void)
{
J3D_HOOKFUNC(sithSector_ReadSectorsListText);
J3D_HOOKFUNC(sithSector_WriteSectorsListBinary);
J3D_HOOKFUNC(sithSector_ReadSectorsListBinary);
J3D_HOOKFUNC(sithSector_ValidateSectorPointer);
J3D_HOOKFUNC(sithSector_AllocWorldSectors);
J3D_HOOKFUNC(sithSector_ResetAllSectors);
J3D_HOOKFUNC(sithSector_FreeWorldSectors);
J3D_HOOKFUNC(sithSector_FindSectorAtPos);
J3D_HOOKFUNC(sithSector_HideSectorAdjoins);
J3D_HOOKFUNC(sithSector_ShowSectorAdjoins);
J3D_HOOKFUNC(sithSector_SetSectorFlags);
J3D_HOOKFUNC(sithSector_ClearSectorFlags);
J3D_HOOKFUNC(sithSector_GetSectorThingCount);
J3D_HOOKFUNC(sithSector_GetSectorPlayerCount);
J3D_HOOKFUNC(sithSector_SyncSector);
J3D_HOOKFUNC(sithSector_SyncSectors);
J3D_HOOKFUNC(sithSector_GetSectorEx);
J3D_HOOKFUNC(sithSector_GetSectorIndexEx);
J3D_HOOKFUNC(sithSector_GetSectorIndex);
}
void sithSector_ResetGlobals(void)
{}
int J3DAPI sithSector_WriteSectorsListText(const SithWorld* pWorld)
{
if ( stdConffile_WriteLine("###### Sector information ######\n")
|| stdConffile_WriteLine("Section: SECTORS\n\n")
|| stdConffile_Printf("World sectors %d\n\n", pWorld->numSectors) )
{
return 1;
}
for ( size_t i = 0; i < pWorld->numSectors; ++i )
{
SithSector* pSec = &pWorld->aSectors[i];
if ( stdConffile_Printf(
"\nSECTOR\t%d\nFLAGS\t0x%x\nAMBIENT LIGHT\t%.2f %.2f %.2f\nEXTRA LIGHT\t%.2f %.2f %.2f\n",
i,
pSec->flags,
pSec->ambientLight.red,
pSec->ambientLight.green,
pSec->ambientLight.blue,
pSec->extraLight.red,
pSec->extraLight.green,
pSec->extraLight.blue)
|| stdConffile_Printf("TINT\t%.2f\t%.2f\t%.2f\n", pSec->tint.red, pSec->tint.green, pSec->tint.blue)
|| stdConffile_Printf("AVERAGE LIGHT INTENSITY\t%.4f\t%.4f\t%.4f\n", pSec->light.color.red, pSec->light.color.green, pSec->light.color.blue)
|| stdConffile_Printf("AVERAGE LIGHT POSITION\t%f\t%f\t%f\n", pSec->light.pos.x, pSec->light.pos.y, pSec->light.pos.z)
|| stdConffile_Printf("AVERAGE LIGHT FALLOFF\t%f\t%f\n", pSec->light.minRadius, pSec->light.maxRadius)
|| stdConffile_Printf(
"BOUNDBOX\t%f %f %f %f %f %f\n", pSec->boundBox.v0.x, pSec->boundBox.v0.y, pSec->boundBox.v0.z, pSec->boundBox.v1.x, pSec->boundBox.v1.y, pSec->boundBox.v1.z)
|| (pSec->flags & SITH_SECTOR_HASCOLLIDEBOX) != 0
&& stdConffile_Printf("COLLIDEBOX\t%f %f %f %f %f %f\n", pSec->collideBox.v0.x, pSec->collideBox.v0.y, pSec->collideBox.v0.z, pSec->collideBox.v1.x, pSec->collideBox.v1.y, pSec->collideBox.v1.z) )
{
return 1;
}
if ( pSec->hAmbientSound )
{
const char* pSoundFilename = Sound_GetSoundFilename(pSec->hAmbientSound);
if ( stdConffile_Printf("SOUND\t%s %f\n", pSoundFilename, pSec->ambientSoundVolume) )
{
return 1;
}
}
if ( (pSec->thrust.x != 0.0f || pSec->thrust.y != 0.0f || pSec->thrust.z != 0.0f)
&& stdConffile_Printf("THRUST\t%f %f %f\n", pSec->thrust.x, pSec->thrust.y, pSec->thrust.z) )
{
return 1;
}
if ( stdConffile_Printf("CENTER\t%f %f %f\n", pSec->center.x, pSec->center.y, pSec->center.z)
|| stdConffile_Printf("RADIUS\t%f\n", pSec->radius)
|| stdConffile_Printf("VERTICES\t%d\n", pSec->numVertices) )
{
return 1;
}
for ( size_t j = 0; j < pSec->numVertices; ++j )
{
if ( stdConffile_Printf("%d:\t%d\n", j, pSec->aVertIdxs[j]) )
{
return 1;
}
}
int surfIdx = sithSurface_GetSurfaceIndexEx(pWorld, pSec->pFirstSurface);
if ( stdConffile_Printf("SURFACES\t%d\t%d\n\n", surfIdx, pSec->numSurfaces) )
{
return 1;
}
}
return 0;
}
int J3DAPI sithSector_ReadSectorsListText(SithWorld* pWorld, int bSkip)
{
if ( bSkip )
{
return 1;
}
int nRead;
size_t numSectors;
if ( nRead = stdConffile_ScanLine(" world sectors %d", &numSectors), nRead != 1 )
{
if ( nRead < 0 ) {
goto eof_error;
}
goto syntax_error;
}
if ( sithSector_AllocWorldSectors(pWorld, numSectors) )
{
goto alloc_error;
}
for ( size_t i = 0; i < numSectors; i++ )
{
SithSector* pSec = &pWorld->aSectors[i];
int secNum;
if ( nRead = stdConffile_ScanLine(" sector %d", &secNum), nRead != 1 )
{
if ( nRead < 0 ) {
goto eof_error;
}
goto syntax_error;
}
// flags
if ( nRead = stdConffile_ScanLine(" flags %x", &pSec->flags), nRead != 1 )
{
if ( nRead < 0 ) {
goto eof_error;
}
goto syntax_error;
}
// ambient light
float red, green, blue;
if ( nRead = stdConffile_ScanLine(" ambient light %f %f %f", &red, &green, &blue), nRead != 3 )
{
if ( nRead < 0 ) {
goto eof_error;
}
goto syntax_error;
}
pSec->ambientLight.red = red;
pSec->ambientLight.green = green;
pSec->ambientLight.blue = blue;
pSec->ambientLight.alpha = 0.0f;
// Extra light
if ( nRead = stdConffile_ScanLine(" extra light %f %f %f", &red, &green, &blue), nRead != 3 )
{
if ( nRead < 0 ) {
goto eof_error;
}
goto syntax_error;
}
pSec->extraLight.red = red;
pSec->extraLight.green = green;
pSec->extraLight.blue = blue;
pSec->extraLight.alpha = 0.0f;
// Optional tint
if ( !stdConffile_ReadLine()
|| sscanf_s(stdConffile_g_aLine, " tint %f %f %f", &pSec->tint.red, &pSec->tint.green, &pSec->tint.blue) == 3 && !stdConffile_ReadLine() )
{
goto eof_error;
}
if ( sscanf_s(stdConffile_g_aLine, " average light intensity %f %f %f", &pSec->light.color.red, &pSec->light.color.green, &pSec->light.color.blue) == 3
&& !stdConffile_ReadLine() )
{
goto eof_error;
}
// Optional average light position
if ( sscanf_s(stdConffile_g_aLine, " average light position %f %f %f", &pSec->light.pos.x, &pSec->light.pos.y, &pSec->light.pos.z) == 3
&& !stdConffile_ReadLine() )
{
goto eof_error;
}
// Optional average light falloff
if ( sscanf_s(stdConffile_g_aLine, " average light falloff %f %f", &pSec->light.minRadius, &pSec->light.maxRadius) == 2 )
{
if ( !stdConffile_ReadLine() )
{
goto eof_error;
}
}
// Bound box
if ( sscanf_s(stdConffile_g_aLine, " boundbox %f %f %f %f %f %f ", &pSec->boundBox.v0.x, &pSec->boundBox.v0.y, &pSec->boundBox.v0.z, &pSec->boundBox.v1.x, &pSec->boundBox.v1.y, &pSec->boundBox.v1.z) != 6 )
{
goto syntax_error;
}
if ( !stdConffile_ReadLine() )
{
goto eof_error;
}
// Optional collide box
if ( sscanf_s(stdConffile_g_aLine, " collidebox %f %f %f %f %f %f ", &pSec->collideBox.v0.x, &pSec->collideBox.v0.y, &pSec->collideBox.v0.z, &pSec->collideBox.v1.x, &pSec->collideBox.v1.y, &pSec->collideBox.v1.z) == 6 )
{
pSec->flags |= SITH_SECTOR_HASCOLLIDEBOX;
if ( !stdConffile_ReadLine() )
{
goto eof_error;
}
}
// Optional sound
char aSound[64];
if ( sscanf_s(stdConffile_g_aLine, "sound %s %f", aSound, (rsize_t)STD_ARRAYLEN(aSound), &pSec->ambientSoundVolume) == 2 )
{
pSec->hAmbientSound = sithSound_Load(pWorld, aSound);
if ( !stdConffile_ReadLine() )
{
goto eof_error;
}
}
// Optional thrust
if ( sscanf_s(stdConffile_g_aLine, "thrust %f %f %f", &pSec->thrust.x, &pSec->thrust.y, &pSec->thrust.z) == 3 && !stdConffile_ReadLine() )
{
goto eof_error;
}
// Center
if ( sscanf_s(stdConffile_g_aLine, " center %f %f %f", &pSec->center.x, &pSec->center.y, &pSec->center.z) != 3 )
{
goto syntax_error;
}
if ( nRead = stdConffile_ScanLine(" radius %f", &pSec->radius), nRead != 1 )
{
if ( nRead < 0 ) {
goto eof_error;
}
goto syntax_error;
}
// Read sector vertices
size_t numVerts;
if ( nRead = stdConffile_ScanLine(" vertices %d", &numVerts), nRead != 1 )
{
if ( nRead < 0 ) {
goto eof_error;
}
goto syntax_error;
}
int32_t* aVerts = (int32_t*)STDMALLOC(sizeof(int32_t) * numVerts);
pSec->aVertIdxs = aVerts;
if ( !pSec->aVertIdxs )
{
goto alloc_error;
}
for ( size_t j = 0; j < numVerts; ++j )
{
int vertNum;
int entryNum;
if ( nRead = stdConffile_ScanLine(" %d: %d", &entryNum, &vertNum), nRead != 2 )
{
if ( nRead < 0 ) {
goto eof_error;
}
goto syntax_error;
}
pSec->aVertIdxs[j] = vertNum;
}
pSec->numVertices = numVerts;
// Read sector surfaces info
size_t numSurfs; int surfIdx;
if ( nRead = stdConffile_ScanLine(" surfaces %d %d", &surfIdx, &numSurfs), nRead != 2 )
{
if ( nRead < 0 ) {
goto eof_error;
}
goto syntax_error;
}
pSec->numSurfaces = numSurfs;
SithSurface* pSurf = sithSurface_GetSurfaceEx(pWorld, surfIdx);
pSec->pFirstSurface = pSurf;
for ( size_t j = 0; j < numSurfs; ++j )
{
pSurf->pSector = pSec;
++pSurf;
}
}
// Success
return 0;
eof_error:
SITHLOG_ERROR("Error: Unexpected EOF in '%s'\n", stdConffile_GetFilename());
return 1;
syntax_error:
SITHLOG_ERROR("Error: Invalid syntax '%s' in '%s'\n", stdConffile_g_aLine, stdConffile_GetFilename());
return 1;
alloc_error:
SITHLOG_ERROR("Error: Bad memory allocation for '%s' in '%s'\n", stdConffile_g_aLine, stdConffile_GetFilename());
return 1;
}
int J3DAPI sithSector_WriteSectorsListBinary(tFileHandle fh, const SithWorld* pWorld)
{
size_t sizes = sizeof(CndSectorInfo) * pWorld->numSectors;
CndSectorInfo* aSectorInfos = (CndSectorInfo*)STDMALLOC(sizes);
if ( !aSectorInfos )
{
return 1;
}
// Collect sector infos
size_t numVertices = 0;
for ( size_t i = 0; i < pWorld->numSectors; ++i )
{
const SithSector* pSec = &pWorld->aSectors[i];
CndSectorInfo* pSecInfo = &aSectorInfos[i];
pSecInfo->flags = pSec->flags;
rdVector_Copy4(&pSecInfo->ambientLight, &pSec->ambientLight);
rdVector_Copy4(&pSecInfo->extraLight, &pSec->extraLight);
rdVector_Copy3(&pSecInfo->tint, &pSec->tint);
rdVector_Copy3(&pSecInfo->light.pos, &pSec->light.pos);
rdVector_Copy4(&pSecInfo->light.color, &pSec->light.color);
pSecInfo->light.minRadius = pSec->light.minRadius;
pSecInfo->light.maxRadius = pSec->light.maxRadius;
memcpy(&pSecInfo->collideBox, &pSec->collideBox, sizeof(pSecInfo->collideBox));
memcpy(&pSecInfo->boundBox, &pSec->boundBox, sizeof(pSecInfo->boundBox));
const char* pSecSound;
if ( pSec->hAmbientSound && (pSecSound = Sound_GetSoundFilename(pSec->hAmbientSound)) != 0 )
{
STD_STRCPY(pSecInfo->aAmbientSound, pSecSound); // Fixed: Ensured null termination by using STD_STRCPY
}
else
{
memset(pSecInfo->aAmbientSound, 0, sizeof(pSecInfo->aAmbientSound));
}
pSecInfo->ambientSoundVolume = pSec->ambientSoundVolume;
rdVector_Copy3(&pSecInfo->center, &pSec->center);
pSecInfo->radius = pSec->radius;
pSecInfo->pvsIdx = pSec->pvsIdx;
pSecInfo->firstSurfaceIdx = sithSurface_GetSurfaceIndexEx(pWorld, pSec->pFirstSurface);
pSecInfo->numSurfaces = pSec->numSurfaces;
rdVector_Copy3(&pSecInfo->thrust, &pSec->thrust);
pSecInfo->numVertices = pSec->numVertices;
numVertices += pSec->numVertices;
}
// Now write infos to file
size_t nWritten = sith_g_pHS->pFileWrite(fh, aSectorInfos, sizes);
stdMemory_Free(aSectorInfos);
if ( nWritten != sizes )
{
return 1;
}
// TODO: Check that numVertices > max uint32_t
nWritten = sith_g_pHS->pFileWrite(fh, &numVertices, sizeof(uint32_t));
if ( nWritten != sizeof(uint32_t) )
{
return 1;
}
// Now write verts indices of all sectors
sizes = sizeof(int32_t) * numVertices;
int32_t* aVerts = (int32_t*)STDMALLOC(sizes);
if ( !aVerts )
{
return 1;
}
int32_t* pVertNum = aVerts;
for ( size_t i = 0; i < pWorld->numSectors; ++i )
{
const SithSector* pSec = &pWorld->aSectors[i];
memcpy(pVertNum, pSec->aVertIdxs, sizeof(int32_t) * pSec->numVertices);
pVertNum += pSec->numVertices;
}
nWritten = sith_g_pHS->pFileWrite(fh, aVerts, sizes);
stdMemory_Free(aVerts);
return nWritten != sizes;
}
int J3DAPI sithSector_ReadSectorsListBinary(tFileHandle fh, SithWorld* pWorld)
{
int32_t* aVerts = NULL;
size_t sizes = sizeof(CndSectorInfo) * pWorld->numSectors;
CndSectorInfo* aSecInfos = (CndSectorInfo*)STDMALLOC(sizes);
if ( !aSecInfos )
{
goto error;
}
size_t nRead = sith_g_pHS->pFileRead(fh, aSecInfos, sizes);
if ( nRead != sizes || sithSector_AllocWorldSectors(pWorld, pWorld->numSectors) )
{
goto error;
}
for ( size_t i = 0; i < pWorld->numSectors; ++i )
{
SithSector* pSec = &pWorld->aSectors[i];
const CndSectorInfo* pSecInfo = &aSecInfos[i];
pSec->flags = pSecInfo->flags;
rdVector_Copy4(&pSec->ambientLight, &pSecInfo->ambientLight);
rdVector_Copy4(&pSec->extraLight, &pSecInfo->extraLight);
rdVector_Copy3(&pSec->tint, &pSecInfo->tint);
rdVector_Copy3(&pSec->light.pos, &pSecInfo->light.pos);
rdVector_Copy4(&pSec->light.color, &pSecInfo->light.color);
pSec->light.minRadius = pSecInfo->light.minRadius;
pSec->light.maxRadius = pSecInfo->light.maxRadius;
memcpy(&pSec->collideBox, &pSecInfo->collideBox, sizeof(pSec->collideBox));
memcpy(&pSec->boundBox, &pSecInfo->boundBox, sizeof(pSec->boundBox));
if ( pSecInfo->aAmbientSound[0] )
{
pSec->hAmbientSound = sithSound_Load(pWorld, pSecInfo->aAmbientSound);
}
else
{
pSec->hAmbientSound = 0;
}
pSec->ambientSoundVolume = pSecInfo->ambientSoundVolume;
rdVector_Copy3(&pSec->center, &pSecInfo->center);
pSec->radius = pSecInfo->radius;
pSec->pvsIdx = pSecInfo->pvsIdx;
pSec->pFirstSurface = sithSurface_GetSurfaceEx(pWorld, pSecInfo->firstSurfaceIdx);
pSec->numSurfaces = pSecInfo->numSurfaces;
rdVector_Copy3(&pSec->thrust, &pSecInfo->thrust);
pSec->numVertices = pSecInfo->numVertices;
SithSurface* pSurf = pSec->pFirstSurface;
for ( size_t j = 0; j < pSec->numSurfaces; ++j )
{
pSurf->pSector = pSec;
++pSurf;
}
}
if ( aSecInfos )
{
stdMemory_Free(aSecInfos);
aSecInfos = NULL;
}
uint32_t numVerts;
nRead = sith_g_pHS->pFileRead(fh, &numVerts, sizeof(numVerts));
if ( nRead != sizeof(numVerts) )
{
return 1;
}
// Read sec vertices
sizes = sizeof(int32_t) * numVerts;
aVerts = (int32_t*)STDMALLOC(sizes);
if ( !aVerts )
{
return 1;
}
nRead = sith_g_pHS->pFileRead(fh, aVerts, sizes);
if ( nRead != sizes )
{
goto error;
}
int32_t* pCurVertNum = aVerts;
for ( size_t i = 0; i < pWorld->numSectors; ++i )
{
SithSector* pSec = &pWorld->aSectors[i];
pSec->aVertIdxs = (int*)STDMALLOC(sizeof(int) * pSec->numVertices);
if ( !pSec->aVertIdxs )
{
goto error;
}
memcpy(pSec->aVertIdxs, pCurVertNum, sizeof(int32_t) * pSec->numVertices);
pCurVertNum += pSec->numVertices;
}
stdMemory_Free(aVerts);
return 0;
error:
if ( pWorld->aSectors )
{
for ( size_t i = 0; i < pWorld->numSectors; ++i )
{
SithSector* pSec = &pWorld->aSectors[i];
if ( pSec->aVertIdxs )
{
stdMemory_Free(pSec->aVertIdxs);
}
}
stdMemory_Free(pWorld->aSectors);
pWorld->aSectors = NULL;
}
if ( aSecInfos )
{
stdMemory_Free(aSecInfos);
}
if ( aVerts )
{
stdMemory_Free(aVerts);
}
return 1;
}
int J3DAPI sithSector_ValidateSectorPointer(const SithWorld* pWorld, const SithSector* pSector)
{
return pWorld && pSector && pSector >= pWorld->aSectors && pSector < &pWorld->aSectors[pWorld->numSectors];
}
int J3DAPI sithSector_AllocWorldSectors(SithWorld* pWorld, size_t numSectors)
{
SITH_ASSERTREL(pWorld != NULL);
SITH_ASSERTREL(pWorld->aSectors == NULL);
pWorld->aSectors = (SithSector*)STDMALLOC(sizeof(SithSector) * numSectors);
if ( !pWorld->aSectors )
{
SITHLOG_ERROR("Failed to allocate mem for %d sectors.\n", numSectors);
return 1;
}
memset(pWorld->aSectors, 0, sizeof(SithSector) * numSectors);
pWorld->numSectors = numSectors;
sithSector_ResetAllSectors(pWorld);
return 0;
}
void J3DAPI sithSector_ResetAllSectors(SithWorld* pWorld)
{
for ( size_t i = 0; i < pWorld->numSectors; ++i )
{
SithSector* pSec = &pWorld->aSectors[i];
pSec->numVertices = 0;
pSec->aVertIdxs = NULL;
pSec->numSurfaces = 0;
pSec->pFirstSurface = NULL;
pSec->pFirstThingInSector = NULL;
}
}
void J3DAPI sithSector_FreeWorldSectors(SithWorld* pWorld)
{
SITH_ASSERTREL(pWorld->aSectors);
for ( size_t i = 0; i < pWorld->numSectors; i++ )
{
SithSector* pSec = &pWorld->aSectors[i];
if ( pSec->aVertIdxs )
{
stdMemory_Free(pSec->aVertIdxs);
pSec->aVertIdxs = NULL; // Added: Set to 0
}
}
stdMemory_Free(pWorld->aSectors);
pWorld->aSectors = NULL;
pWorld->numSectors = 0;
}
SithSector* J3DAPI sithSector_FindSectorAtPos(const SithWorld* pWorld, const rdVector3* pos)
{
SITH_ASSERTREL(pos != NULL);
SITH_ASSERTREL(pWorld != NULL);
for ( size_t i = 0; i < pWorld->numSectors; ++i )
{
SithSector* pSec = &pWorld->aSectors[i];
if ( pSec->boundBox.v0.x <= (double)pos->x
&& pSec->boundBox.v1.x >= (double)pos->x
&& pSec->boundBox.v0.y <= (double)pos->y
&& pSec->boundBox.v1.y >= (double)pos->y )
{
bool bInBounds = pSec->boundBox.v0.z <= (double)pos->z && pSec->boundBox.v1.z >= (double)pos->z;
if ( bInBounds && sithIntersect_IsSphereInSector(pWorld, pos, /*radius=*/0.0f, pSec) )
{
return pSec;
}
}
}
return NULL;
}
void J3DAPI sithSector_HideSectorAdjoins(SithSector* pSector)
{
SITH_ASSERTREL(pSector);
for ( SithSurfaceAdjoin* i = pSector->pFirstAdjoin; i; i = i->pNextAdjoin )
{
sithSurface_HideSectorAdjoin(i);
}
pSector->flags |= SITH_SECTOR_ADJOINSOFF;
}
void J3DAPI sithSector_ShowSectorAdjoins(SithSector* pSector)
{
for ( SithSurfaceAdjoin* i = pSector->pFirstAdjoin; i; i = i->pNextAdjoin )
{
sithSurface_ShowSectorAdjoin(i);
}
pSector->flags &= ~SITH_SECTOR_ADJOINSOFF;
}
void J3DAPI sithSector_SetSectorFlags(SithSector* pSector, SithSectorFlag flags)
{
SITH_ASSERTREL(pSector != NULL);
SITH_ASSERTREL(sithSector_ValidateSectorPointer(sithWorld_g_pCurrentWorld, pSector));
SithSectorFlag prevflags = pSector->flags;
pSector->flags |= flags;
for ( SithThing* pCurrentCheckThing = pSector->pFirstThingInSector; pCurrentCheckThing; pCurrentCheckThing = pCurrentCheckThing->pNextThingInSector )
{
SITH_ASSERTREL(sithThing_ValidateThingPointer(sithWorld_g_pCurrentWorld, pCurrentCheckThing));
if ( (prevflags & SITH_SECTOR_UNDERWATER) == 0 && (pSector->flags & SITH_SECTOR_UNDERWATER) != 0 )
{
switch ( pCurrentCheckThing->type )
{
case SITH_THING_ACTOR:
case SITH_THING_PLAYER:
sithThing_ExitSector(pCurrentCheckThing);
sithThing_EnterSector(pCurrentCheckThing, pSector, 0, 0);
break;
case SITH_THING_PARTICLE:
case SITH_THING_SPRITE:
sithThing_DestroyThing(pCurrentCheckThing);
break;
default:
continue;
}
}
}
}
void J3DAPI sithSector_ClearSectorFlags(SithSector* pSector, SithSectorFlag flags)
{
SITH_ASSERTREL(pSector != NULL);
SITH_ASSERTREL(sithSector_ValidateSectorPointer(sithWorld_g_pCurrentWorld, pSector));
SithSectorFlag prevflags = pSector->flags;
pSector->flags &= ~flags;
for ( SithThing* pCurrentCheckThing = pSector->pFirstThingInSector; pCurrentCheckThing; pCurrentCheckThing = pCurrentCheckThing->pNextThingInSector )
{
SITH_ASSERTREL(sithThing_ValidateThingPointer(sithWorld_g_pCurrentWorld, pCurrentCheckThing));
if ( (prevflags & SITH_SECTOR_UNDERWATER) != 0 && (pSector->flags & SITH_SECTOR_UNDERWATER) == 0 )
{
switch ( pCurrentCheckThing->type )
{
case SITH_THING_ACTOR:
case SITH_THING_PLAYER:
sithThing_ExitSector(pCurrentCheckThing);
sithThing_EnterSector(pCurrentCheckThing, pSector, 0, 0);
break;
case SITH_THING_PARTICLE:
case SITH_THING_SPRITE:
sithThing_DestroyThing(pCurrentCheckThing);
break;
default:
continue;
}
}
}
}
size_t J3DAPI sithSector_GetSectorThingCount(const SithSector* pSector)
{
SITH_ASSERTREL(pSector != NULL);
SITH_ASSERTREL(sithSector_ValidateSectorPointer(sithWorld_g_pCurrentWorld, pSector));
size_t count = 0;
for ( SithThing* pCurrentCheckThing = pSector->pFirstThingInSector; pCurrentCheckThing; pCurrentCheckThing = pCurrentCheckThing->pNextThingInSector )
{
SITH_ASSERTREL(sithThing_ValidateThingPointer(sithWorld_g_pCurrentWorld, pCurrentCheckThing));
++count;
}
return count;
}
size_t J3DAPI sithSector_GetSectorPlayerCount(const SithSector* pSector)
{
SITH_ASSERTREL(pSector != NULL);
SITH_ASSERTREL(sithSector_ValidateSectorPointer(sithWorld_g_pCurrentWorld, pSector));
size_t count = 0;
for ( SithThing* pCurrentCheckThing = pSector->pFirstThingInSector; pCurrentCheckThing; pCurrentCheckThing = pCurrentCheckThing->pNextThingInSector )
{
SITH_ASSERTREL(sithThing_ValidateThingPointer(sithWorld_g_pCurrentWorld, pCurrentCheckThing));
if ( pCurrentCheckThing->type == SITH_THING_PLAYER )
{
++count;
}
}
return count;
}
size_t J3DAPI sithSector_GetAdjoinCount(const SithSector* pSector)
{
SITH_ASSERTREL(pSector != NULL);
SITH_ASSERTREL(sithSector_ValidateSectorPointer(sithWorld_g_pCurrentWorld, pSector));
size_t count = 0;
for ( SithSurfaceAdjoin* i = pSector->pFirstAdjoin; i; i = i->pNextAdjoin )
{
++count;
}
return count;
}
void J3DAPI sithSector_SyncSector(SithSector* pSector, int flags)
{
SITH_ASSERTREL(pSector);
pSector->flags |= SITH_SECTOR_SYNC; // TODO: Shall flag setting be moved inside the scope?
if ( sithMessage_g_outputstream )
{
// TODO: Wouldn't it make more sense for this check to move after for loop
if ( sithSector_numModifiedSectors >= STD_ARRAYLEN(sithSector_aModifiedSectors) )
{
SITHLOG_ERROR("Too many modified sectors.\n");
return;
}
for ( size_t i = 0; i < sithSector_numModifiedSectors; ++i )
{
if ( sithSector_aModifiedSectors[i] == pSector )
{
sithSector_aSyncFlags[i] |= flags;
return;
}
}
sithSector_aModifiedSectors[sithSector_numModifiedSectors] = pSector;
sithSector_aSyncFlags[sithSector_numModifiedSectors++] = flags;
}
}
size_t sithSector_SyncSectors(void)
{
size_t numSynced = 0;
for ( size_t i = 0; i < sithSector_numModifiedSectors; ++i )
{
if ( (sithSector_aSyncFlags[i] & 1) != 0 )
{
sithDSS_SectorStatus(sithSector_aModifiedSectors[i], SITHMESSAGE_SENDTOJOINEDPLAYERS, SITHMESSAGE_STREAM_ALL);
}
else
{
sithDSS_SectorFlags(sithSector_aModifiedSectors[i], SITHMESSAGE_SENDTOJOINEDPLAYERS, SITHMESSAGE_STREAM_ALL);
}
numSynced = i + 1;
}
sithSector_numModifiedSectors = 0;
return numSynced;
}
SithSector* J3DAPI sithSector_GetSectorEx(const SithWorld* pWorld, int idx)
{
if ( pWorld && idx >= 0 && idx < pWorld->numSectors )
{
return &pWorld->aSectors[idx];
}
return NULL;
}
int J3DAPI sithSector_GetSectorIndexEx(const SithWorld* pWorld, const SithSector* pSector)
{
if ( pSector < pWorld->aSectors || pSector > &pWorld->aSectors[pWorld->numSectors] )
{
return -1;
}
return pSector - pWorld->aSectors;
}
int J3DAPI sithSector_GetSectorIndex(const SithSector* pSector)
{
if ( pSector < sithWorld_g_pCurrentWorld->aSectors || pSector > &sithWorld_g_pCurrentWorld->aSectors[sithWorld_g_pCurrentWorld->numSectors] )
{
return -1;
}
return pSector - sithWorld_g_pCurrentWorld->aSectors;
}
| 0 | 0.916277 | 1 | 0.916277 | game-dev | MEDIA | 0.41782 | game-dev | 0.935079 | 1 | 0.935079 |
diabeatz96/cain | 1,067 | module/data/base-actor.mjs | import CainDataModel from "./base-model.mjs";
export default class CainActorBase extends CainDataModel {
static defineSchema() {
const fields = foundry.data.fields;
const requiredInteger = { required: true, nullable: false, integer: true };
const schema = {};
schema.health = new fields.SchemaField({
value: new fields.NumberField({ ...requiredInteger, initial: 10, min: 0 }),
max: new fields.NumberField({ ...requiredInteger, initial: 10 })
});
schema.power = new fields.SchemaField({
value: new fields.NumberField({ ...requiredInteger, initial: 5, min: 0 }),
max: new fields.NumberField({ ...requiredInteger, initial: 5 })
});
schema.biography = new fields.StringField({ required: true, initial: "<b>QUESTIONNAIRE</b><ul><li>How did you first manifest your powers?</li><li>Is your sin-seed in your brain or in your heart?</li><li>What do you hide in the deepest parts of you?</li><li>Is your hand your hand?</li><li>Do you remember the face of your mother?</li></ul>" });
return schema;
}
} | 0 | 0.831232 | 1 | 0.831232 | game-dev | MEDIA | 0.218479 | game-dev | 0.834583 | 1 | 0.834583 |
KarabulutCan/UnityCourse | 3,610 | Assets/TextMesh Pro/Examples & Extras/Scripts/Benchmark02.cs | using UnityEngine;
using System.Collections;
namespace TMPro.Examples
{
public class Benchmark02 : MonoBehaviour
{
public int SpawnType = 0;
public int NumberOfNPC = 12;
public bool IsTextObjectScaleStatic;
private TextMeshProFloatingText floatingText_Script;
void Start()
{
for (int i = 0; i < NumberOfNPC; i++)
{
if (SpawnType == 0)
{
// TextMesh Pro Implementation
GameObject go = new GameObject();
go.transform.position = new Vector3(Random.Range(-95f, 95f), 0.25f, Random.Range(-95f, 95f));
TextMeshPro textMeshPro = go.AddComponent<TextMeshPro>();
textMeshPro.autoSizeTextContainer = true;
textMeshPro.rectTransform.pivot = new Vector2(0.5f, 0);
textMeshPro.alignment = TextAlignmentOptions.Bottom;
textMeshPro.fontSize = 96;
textMeshPro.fontFeatures.Clear();
textMeshPro.color = new Color32(255, 255, 0, 255);
textMeshPro.text = "!";
textMeshPro.isTextObjectScaleStatic = IsTextObjectScaleStatic;
// Spawn Floating Text
floatingText_Script = go.AddComponent<TextMeshProFloatingText>();
floatingText_Script.SpawnType = 0;
floatingText_Script.IsTextObjectScaleStatic = IsTextObjectScaleStatic;
}
else if (SpawnType == 1)
{
// TextMesh Implementation
GameObject go = new GameObject();
go.transform.position = new Vector3(Random.Range(-95f, 95f), 0.25f, Random.Range(-95f, 95f));
TextMesh textMesh = go.AddComponent<TextMesh>();
textMesh.font = Resources.Load<Font>("Fonts/ARIAL");
textMesh.GetComponent<Renderer>().sharedMaterial = textMesh.font.material;
textMesh.anchor = TextAnchor.LowerCenter;
textMesh.fontSize = 96;
textMesh.color = new Color32(255, 255, 0, 255);
textMesh.text = "!";
// Spawn Floating Text
floatingText_Script = go.AddComponent<TextMeshProFloatingText>();
floatingText_Script.SpawnType = 1;
}
else if (SpawnType == 2)
{
// Canvas WorldSpace Camera
GameObject go = new GameObject();
Canvas canvas = go.AddComponent<Canvas>();
canvas.worldCamera = Camera.main;
go.transform.localScale = new Vector3(0.1f, 0.1f, 0.1f);
go.transform.position = new Vector3(Random.Range(-95f, 95f), 5f, Random.Range(-95f, 95f));
TextMeshProUGUI textObject = new GameObject().AddComponent<TextMeshProUGUI>();
textObject.rectTransform.SetParent(go.transform, false);
textObject.color = new Color32(255, 255, 0, 255);
textObject.alignment = TextAlignmentOptions.Bottom;
textObject.fontSize = 96;
textObject.text = "!";
// Spawn Floating Text
floatingText_Script = go.AddComponent<TextMeshProFloatingText>();
floatingText_Script.SpawnType = 0;
}
}
}
}
}
| 0 | 0.728883 | 1 | 0.728883 | game-dev | MEDIA | 0.977447 | game-dev | 0.704123 | 1 | 0.704123 |
roman10/roman10-android-tutorial | 3,093 | pagedview/src/roman10/zoomablegallery/dynamics/SpringDynamics.java | /*
* Copyright 2010 Sony Ericsson Mobile Communications AB
*
* 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 roman10.zoomablegallery.dynamics;
/**
* SpringDynamics is a Dynamics object that uses friction and spring physics to
* snap to boundaries and give a natural and organic dynamic.
*/
public class SpringDynamics extends Dynamics {
/** Friction factor */
private float mFriction;
/** Spring stiffness factor */
private float mStiffness;
/** Spring damping */
private float mDamping;
/**
* Set friction parameter, friction physics are applied when inside of snap
* bounds.
*
* @param friction Friction factor
*/
public void setFriction(float friction) {
mFriction = friction;
}
/**
* Set spring parameters, spring physics are applied when outside of snap
* bounds.
*
* @param stiffness Spring stiffness
* @param dampingRatio Damping ratio, < 1 underdamped, > 1 overdamped
*/
public void setSpring(float stiffness, float dampingRatio) {
mStiffness = stiffness;
mDamping = dampingRatio * 2 * (float)Math.sqrt(stiffness);
}
/**
* Calculate acceleration at the current state
*
* @return Current acceleration
*/
private float calculateAcceleration() {
float acceleration;
final float distanceFromLimit = getDistanceToLimit();
if (distanceFromLimit != 0) {
acceleration = distanceFromLimit * mStiffness - mDamping * mVelocity;
} else {
acceleration = -mFriction * mVelocity;
}
return acceleration;
}
@Override
protected void onUpdate(int dt) {
// Update position and velocity using the Velocity verlet algorithm
// Calculate dt in seconds as float
final float fdt = dt / 1000f;
// Calculate current acceleration
final float at = calculateAcceleration();
// Calculate next position based on current velocity and acceleration
mPosition += mVelocity * fdt + .5f * at * fdt * fdt;
// Calculate velocity at time t + dt/2
// (that is velocity at half way to new time)
mVelocity += .5f * at * fdt;
// Calculate acceleration at new position,
// will be used for calculating velocity at next position.
final float atdt = calculateAcceleration();
// Calculate velocity at time (t + dt/2) + dt/2 = t + dt
// (that is velocity at the new time)
mVelocity += .5f * atdt * fdt;
}
}
| 0 | 0.782296 | 1 | 0.782296 | game-dev | MEDIA | 0.167726 | game-dev | 0.734247 | 1 | 0.734247 |
Aussiemon/Darktide-Source-Code | 4,828 | scripts/components/vector_field_effect.lua | -- chunkname: @scripts/components/vector_field_effect.lua
local VectorFieldEffect = component("VectorFieldEffect")
VectorFieldEffect.init = function (self, unit)
self._index_offset = Script.index_offset()
self._effect = self:get_data(unit, "effect")
self._speed = self:get_data(unit, "speed")
self._duration = self:get_data(unit, "duration")
if tonumber(self._duration) <= 0 then
self._duration = nil
end
self._settings = {
duration = self._duration,
}
local world = Unit.world(unit)
self._vector_field = World.vector_field(world, "wind")
self._effect_path = "content/vector_fields/" .. self._effect
self:disable(unit)
self:enable(unit)
end
VectorFieldEffect.editor_validate = function (self, unit)
return true, ""
end
VectorFieldEffect.enable = function (self, unit)
local parameters = self:create_paramaters(unit, self._effect, self._speed, self._duration)
local vector_field_id = VectorField.add(self._vector_field, self._effect_path, parameters, self._settings)
Unit.set_data(unit, "vector_field_id", vector_field_id)
end
VectorFieldEffect.disable = function (self, unit)
self:remove(unit)
end
VectorFieldEffect.destroy = function (self, unit)
self:remove(unit)
end
VectorFieldEffect.changed = function (self, unit)
local vector_field_id = Unit.get_data(unit, "vector_field_id")
if vector_field_id then
local parameters = self:create_paramaters(unit, self._effect, self._speed, self._duration)
VectorField.change(self._vector_field, vector_field_id, self._effect_path, parameters, self._settings)
else
Log.info("VectorFieldEffect", "No Vectorfield ID in Unit")
end
end
VectorFieldEffect.remove = function (self, unit)
local vector_field_id = Unit.get_data(unit, "vector_field_id")
if vector_field_id then
VectorField.remove(self._vector_field, vector_field_id)
else
Log.info("VectorFieldEffect", "No Vectorfield ID in Unit")
end
end
VectorFieldEffect.create_paramaters = function (self, unit, effect, speed)
local pose, extents = Unit.box(unit)
local rotation = Matrix4x4.rotation(pose)
local direction = Quaternion.forward(rotation)
local center = Unit.world_position(unit, self._index_offset)
local world_extents = Quaternion.rotate(rotation, extents)
if effect == "box_direction" then
return {
speed = Vector3.multiply(direction, speed),
world_extents = world_extents,
}
elseif effect == "global_direction" then
return {
speed = Vector3.multiply(direction, speed),
}
elseif effect == "global_sine" then
local amplitude = self:get_data(unit, "amplitude")
local frequency = self:get_data(unit, "frequency")
local phase = self:get_data(unit, "phase")
local rotation = Unit.world_rotation(unit, self._index_offset)
local wave_vector = Quaternion.forward(rotation)
local rotated_amplitude = Quaternion.rotate(rotation, amplitude:unbox())
return {
amplitude = rotated_amplitude,
wave_vector = wave_vector,
frequency = frequency,
phase = phase,
}
elseif effect == "push_pull" then
local scale = Unit.local_scale(unit, self._index_offset)
return {
center = center,
radius = scale.x * 0.5,
speed = speed,
}
elseif effect == "whirl" then
local whirl_speed = self:get_data(unit, "whirl_speed")
local pull_speed = self:get_data(unit, "pull_speed")
local scale = Unit.local_scale(unit, self._index_offset)
return {
whirl_speed = whirl_speed,
pull_speed = pull_speed,
center = center,
radius = scale.x * 0.5,
up = Quaternion.up(rotation),
}
else
Log.info("VectorFieldEffect", "Can not find effect: %s", effect)
return nil
end
end
local effects = {
"box_direction",
"global_direction",
"global_sine",
"push_pull",
"whirl",
}
VectorFieldEffect.component_data = {
effect = {
ui_name = "Effect",
ui_type = "combo_box",
value = "global_direction",
options = {
"box_direction",
"global_direction",
"global_sine",
"push_pull",
"whirl",
},
},
duration = {
decimals = 2,
min = 0,
step = 0.01,
ui_name = "Duration",
ui_type = "number",
value = 0,
},
speed = {
decimals = 2,
step = 0.01,
ui_name = "Speed",
ui_type = "slider",
value = 5,
},
whirl_speed = {
decimals = 2,
step = 0.01,
ui_name = "Whirl Speed",
ui_type = "slider",
value = 30,
},
pull_speed = {
decimals = 2,
step = 0.01,
ui_name = "Pull Speed",
ui_type = "slider",
value = 10,
},
amplitude = {
ui_name = "Amplitude",
ui_type = "vector",
value = Vector3Box(0, 0, 1),
},
frequency = {
decimals = 2,
step = 0.01,
ui_name = "Frequency",
ui_type = "slider",
value = 5,
},
phase = {
decimals = 2,
step = 0.01,
ui_name = "Phase",
ui_type = "slider",
value = 0,
},
effect_resources = {
filter = "vector_field",
ui_name = "Effect Resource",
ui_type = "resource_array",
},
}
return VectorFieldEffect
| 0 | 0.606878 | 1 | 0.606878 | game-dev | MEDIA | 0.855221 | game-dev | 0.696603 | 1 | 0.696603 |
TeamMidnightDust/MidnightControls | 7,243 | common/src/main/java/eu/midnightdust/midnightcontrols/client/compat/MidnightControlsCompat.java | /*
* Copyright © 2021 LambdAurora <aurora42lambda@gmail.com>
*
* This file is part of midnightcontrols.
*
* Licensed under the MIT license. For more information,
* see the LICENSE file.
*/
package eu.midnightdust.midnightcontrols.client.compat;
import eu.midnightdust.lib.util.PlatformFunctions;
import eu.midnightdust.midnightcontrols.client.controller.InputManager;
import eu.midnightdust.midnightcontrols.client.util.storage.AxisStorage;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.util.hit.BlockHitResult;
import org.aperlambda.lambdacommon.utils.LambdaReflection;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
import static eu.midnightdust.midnightcontrols.MidnightControls.log;
import static eu.midnightdust.midnightcontrols.client.MidnightControlsClient.client;
/**
* Represents a compatibility handler.
*
* @author LambdAurora, Motschen
* @version 1.10.0
* @since 1.1.0
*/
public class MidnightControlsCompat {
@Deprecated // INTERNAL -> PLEASE USE streamCompatHandlers() INSTEAD
public static final List<CompatHandler> HANDLERS = new ArrayList<>();
/**
* Initializes compatibility with other mods if needed.
*/
public static void init() {
if (PlatformFunctions.isModLoaded("emi")) {
log("Adding EMI compatibility...");
registerCompatHandler(new EMICompat());
}
if (PlatformFunctions.isModLoaded("hardcorequesting") && LambdaReflection.doesClassExist(HQMCompat.GUI_BASE_CLASS_PATH)) {
log("Adding HQM compatibility...");
registerCompatHandler(new HQMCompat());
}
if (PlatformFunctions.isModLoaded("bedrockify")) {
log("Adding Bedrockify compatibility...");
registerCompatHandler(new BedrockifyCompat());
}
if (PlatformFunctions.isModLoaded("yet-another-config-lib")) {
log("Adding YACL compatibility...");
registerCompatHandler(new YACLCompat());
}
if (PlatformFunctions.isModLoaded("sodium")) {
log("Adding Sodium compatibility...");
registerCompatHandler(new SodiumCompat());
}
if (PlatformFunctions.isModLoaded("inventorytabs")) {
log("Adding Inventory Tabs compatibility...");
registerCompatHandler(new InventoryTabsCompat());
}
HANDLERS.forEach(CompatHandler::handle);
InputManager.loadButtonBindings();
}
/**
* Registers a new compatibility handler.
*
* @param handler the compatibility handler to register
*/
public static void registerCompatHandler(@NotNull CompatHandler handler) {
HANDLERS.add(handler);
}
/**
* Streams through compatibility handlers.
*
* @return a stream of compatibility handlers
*/
public static Stream<CompatHandler> streamCompatHandlers() {
return HANDLERS.stream();
}
/**
* Returns whether the mouse is required on the specified screen.
*
* @param screen the screen
* @return true if the mouse is requried on the specified screen, else false
*/
public static boolean requireMouseOnScreen(Screen screen) {
return streamCompatHandlers().anyMatch(handler -> handler.requireMouseOnScreen(screen));
}
/**
* Handles custom tabs for modded screens
*
* @param screen the screen
* @return true if the handle was fired and succeed, else false
*/
public static boolean handleTabs(Screen screen, boolean forward) {
return streamCompatHandlers().anyMatch(handler -> handler.handleTabs(screen, forward));
}
/**
* Handles custom pages for modded screens
*
* @param screen the screen
* @return true if the handle was fired and succeed, else false
*/
public static boolean handlePages(Screen screen, boolean forward) {
return streamCompatHandlers().anyMatch(handler -> handler.handlePages(screen, forward));
}
/**
* Returns a slot at the specified location if possible.
*
* @param screen the screen
* @param mouseX the mouse X-coordinate
* @param mouseY the mouse Y-coordinate
* @return a slot if present, else null
*/
public static @Nullable CompatHandler.SlotPos getSlotAt(@NotNull Screen screen, int mouseX, int mouseY) {
for (var handler : HANDLERS) {
var slot = handler.getSlotAt(screen, mouseX, mouseY);
if (slot != null)
return slot;
}
return null;
}
/**
* Returns a custom translation key to make custom attack action strings on the HUD.
*
* @param client the client instance
* @param placeResult the last place block result
* @return null if untouched, else a translation key
*/
public static String getAttackActionAt(@NotNull MinecraftClient client, @Nullable BlockHitResult placeResult) {
for (CompatHandler handler : HANDLERS) {
String action = handler.getAttackActionAt(client, placeResult);
if (action != null) {
return action;
}
}
return null;
}
/**
* Returns a custom translation key to make custom use action strings on the HUD.
*
* @param client the client instance
* @param placeResult the last place block result
* @return null if untouched, else a translation key
*/
public static String getUseActionAt(@NotNull MinecraftClient client, @Nullable BlockHitResult placeResult) {
for (CompatHandler handler : HANDLERS) {
String action = handler.getUseActionAt(client, placeResult);
if (action != null) {
return action;
}
}
return null;
}
/**
* Handles the menu back button.
*
* @param client the client instance
* @param screen the screen
* @return true if the handle was fired and succeed, else false
*/
public static boolean handleMenuBack(@NotNull MinecraftClient client, @NotNull Screen screen) {
for (CompatHandler handler : HANDLERS) {
if (handler.handleMenuBack(client, screen))
return true;
}
return false;
}
/**
* Handles the camera movement.
*
* @param targetYaw the target yaw
* @param targetPitch the target pitch
*/
public static void handleCamera(double targetYaw, double targetPitch) {
MidnightControlsCompat.HANDLERS.forEach(handler -> handler.handleCamera(client, targetYaw, targetPitch));
}
/**
* Handles movement for players as well as vehicles
*
* @param storage the storage containing info about the current axis
* @param adjustedValue the value of the axis, adjusted for max values and non-analogue movement, recommended for player movement
*/
public static void handleMovement(AxisStorage storage, float adjustedValue) {
streamCompatHandlers().forEach(handler -> handler.handleMovement(client, storage, adjustedValue));
}
}
| 0 | 0.949823 | 1 | 0.949823 | game-dev | MEDIA | 0.460562 | game-dev | 0.892956 | 1 | 0.892956 |
AiMiDi/C4D_MMD_Tool | 4,617 | sdk_s24/frameworks/mesh_misc.framework/generated/hxx/_default_mesh_attribute_base.hxx | // This file contains default implementations for the interfaces of mesh_attribute_base.h. They are intended for copy&paste usage only.
class MyCustomDataTagDisplayImpl : public maxon::Component<MyCustomDataTagDisplayImpl, CustomDataTagDisplayInterface>
{
MAXON_COMPONENT();
public:
MAXON_METHOD Result<void> Init(BaseTag* tag)
{
return maxon::PrivateGetNullReturnError(maxon::NULL_RETURN_REASON::NULLIMPL);
}
MAXON_METHOD Result<void> Draw(BaseTag* tag, BaseObject* op, BaseDraw* bd, BaseDrawHelp* bh)
{
return maxon::PrivateGetNullReturnError(maxon::NULL_RETURN_REASON::NULLIMPL);
}
MAXON_METHOD Result<void> DisplayControl(BaseTag* tag, BaseDocument* doc, BaseObject* op, BaseDraw* bd, BaseDrawHelp* bh, ControlDisplayStruct& cds) const
{
return maxon::PrivateGetNullReturnError(maxon::NULL_RETURN_REASON::NULLIMPL);
}
MAXON_METHOD Result<void> InitDisplayControl(BaseTag* tag, BaseDocument* doc, BaseDraw* bd, const AtomArray* active)
{
return maxon::PrivateGetNullReturnError(maxon::NULL_RETURN_REASON::NULLIMPL);
}
MAXON_METHOD void FreeDisplayControl(BaseTag* tag)
{
return maxon::PrivateLogNullptrError();
}
MAXON_METHOD void Reset()
{
return maxon::PrivateLogNullptrError();
}
};
class MyMeshAttributeClassImpl : public maxon::Component<MyMeshAttributeClassImpl, MeshAttributeClassInterface>
{
MAXON_COMPONENT();
public:
MAXON_METHOD const DataType& GetDataType() const
{
return maxon::PrivateIncompleteNullReturnValue<const DataType&>(maxon::NULL_RETURN_REASON::NULLIMPL, OVERLOAD_MAX_RANK);
}
MAXON_METHOD void InterpolateLinear(void* data1, const void* data2, Float blend) const
{
return maxon::PrivateLogNullptrError();
}
MAXON_METHOD void InterpolateInOutline(void* data, const Block<void*>& outline, const Block<Float>& weights) const
{
return maxon::PrivateLogNullptrError();
}
MAXON_METHOD void GetDefaultValue(void* data) const
{
return maxon::PrivateLogNullptrError();
}
MAXON_METHOD Bool AtrLessThen(const void* data1, const void* data2) const
{
return maxon::PrivateLogNullptrError(false);
}
MAXON_METHOD Bool AtrIsEqual(const void* data1, const void* data2) const
{
return maxon::PrivateLogNullptrError(false);
}
MAXON_METHOD void AtrAdd(void* data1, const void* data2) const
{
return maxon::PrivateLogNullptrError();
}
MAXON_METHOD void AtrSubstract(void* data1, const void* data2) const
{
return maxon::PrivateLogNullptrError();
}
MAXON_METHOD void AtrMultiply(void* data1, const void* data2) const
{
return maxon::PrivateLogNullptrError();
}
MAXON_METHOD void AtrMultiply(void* data, Float value) const
{
return maxon::PrivateLogNullptrError();
}
MAXON_METHOD void AtrDivide(void* data1, const void* data2) const
{
return maxon::PrivateLogNullptrError();
}
MAXON_METHOD void AtrDivide(void* data, Float value) const
{
return maxon::PrivateLogNullptrError();
}
MAXON_METHOD String AtrToString(const void* data, const FormatStatement* formatStatement) const
{
return maxon::PrivateIncompleteNullReturnValue<String>(maxon::NULL_RETURN_REASON::NULLIMPL, OVERLOAD_MAX_RANK);
}
};
class MyCustomDataTagClassImpl : public maxon::Component<MyCustomDataTagClassImpl, CustomDataTagClassInterface>
{
MAXON_COMPONENT();
public:
MAXON_METHOD Int32 GetTagPluginId() const
{
return 0;
}
MAXON_METHOD const String& GetTagPluginName() const
{
return maxon::PrivateIncompleteNullReturnValue<const String&>(maxon::NULL_RETURN_REASON::NULLIMPL, OVERLOAD_MAX_RANK);
}
MAXON_METHOD const String& GetResourceId() const
{
return maxon::PrivateIncompleteNullReturnValue<const String&>(maxon::NULL_RETURN_REASON::NULLIMPL, OVERLOAD_MAX_RANK);
}
MAXON_METHOD Int32 GetTagPluginLevel() const
{
return 0;
}
MAXON_METHOD Id GetDisplayClassId() const
{
return maxon::PrivateIncompleteNullReturnValue<Id>(maxon::NULL_RETURN_REASON::NULLIMPL, OVERLOAD_MAX_RANK);
}
MAXON_METHOD Bool IsSdsCompatible(Int32& floatSize) const
{
return maxon::PrivateLogNullptrError(false);
}
MAXON_METHOD Result<void> Read(void* data, HyperFile* hf, Int32 level) const
{
return maxon::PrivateGetNullReturnError(maxon::NULL_RETURN_REASON::NULLIMPL);
}
MAXON_METHOD Result<void> Write(const void* data, HyperFile* hf) const
{
return maxon::PrivateGetNullReturnError(maxon::NULL_RETURN_REASON::NULLIMPL);
}
MAXON_METHOD Int32 GetIcon(Bool perPolyVertex) const
{
return 0;
}
MAXON_METHOD Int32 GetTagPluginFlags() const
{
return 0;
}
MAXON_METHOD Bool Message(GeListNode* node, Int32 type, void* data) const
{
return maxon::PrivateLogNullptrError(false);
}
};
| 0 | 0.762988 | 1 | 0.762988 | game-dev | MEDIA | 0.340535 | game-dev | 0.585805 | 1 | 0.585805 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.