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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
maulik9898/barrage | 2,632 | components/TorrentButtons.tsx | import { TorrentState } from "../deluge/types";
import { ActionIcon, Menu } from "@mantine/core";
import {
IconDeviceSdCard, IconPlayerPause,
IconPlayerPlay,
IconTrash
} from "@tabler/icons";
import { trpc } from "../utils/trpc";
const TorrentButtons = ({
id,
state,
refetch,
}: {
id: string;
state: TorrentState;
refetch: () => void;
}) => {
const pauseTorrent = trpc.deluge.pause.useMutation({
onSuccess: () => {
refetch();
},
});
const resumeTorrent = trpc.deluge.resume.useMutation({
onSuccess: () => {
refetch();
},
});
const deleteTorrent = trpc.deluge.delete.useMutation({
onSuccess: () => {
refetch();
},
});
return (
<>
{state !== TorrentState.paused ? (
<ActionIcon
sx={(theme) => ({
borderWidth: 1,
borderColor: theme.colors.gray[6],
})}
size={"lg"}
variant="light"
onClick={() => {
pauseTorrent.mutate({ id: id });
}}
>
<IconPlayerPause size={20} />
</ActionIcon>
) : (
<ActionIcon
sx={(theme) => ({
borderWidth: 1,
borderColor: theme.colors.gray[6],
})}
size={"lg"}
variant="light"
onClick={() => {
resumeTorrent.mutate({ id: id });
}}
>
<IconPlayerPlay size={20} />
</ActionIcon>
)}
<Menu
shadow="md"
width={200}
withinPortal
closeOnClickOutside
closeOnEscape
withArrow
position="bottom-end"
>
<Menu.Target>
<ActionIcon
sx={(theme) => ({
borderWidth: 1,
borderColor: theme.colors.red,
})}
color={"red"}
size={"lg"}
variant="light"
>
<IconTrash size={20} />
</ActionIcon>
</Menu.Target>
<Menu.Dropdown>
<Menu.Label>Delete Torrent</Menu.Label>
<Menu.Item
onClick={() => {
deleteTorrent.mutate({ id: id, removeData: false });
}}
icon={<IconTrash size={14} />}
>
Delete
</Menu.Item>
<Menu.Item
onClick={() => {
deleteTorrent.mutate({ id: id, removeData: true });
}}
color={"red"}
icon={<IconDeviceSdCard size={14} />}
>
Delete with data
</Menu.Item>
</Menu.Dropdown>
</Menu>
</>
);
};
export default TorrentButtons;
| 0 | 0.895488 | 1 | 0.895488 | game-dev | MEDIA | 0.65588 | game-dev | 0.984618 | 1 | 0.984618 |
gaucho-matrero/altoclef | 16,580 | src/main/java/adris/altoclef/trackers/EntityTracker.java | package adris.altoclef.trackers;
import adris.altoclef.Debug;
import adris.altoclef.eventbus.EventBus;
import adris.altoclef.eventbus.events.PlayerCollidedWithEntityEvent;
import adris.altoclef.mixins.PersistentProjectileEntityAccessor;
import adris.altoclef.trackers.blacklisting.EntityLocateBlacklist;
import adris.altoclef.util.ItemTarget;
import adris.altoclef.util.helpers.BaritoneHelper;
import adris.altoclef.util.baritone.CachedProjectile;
import adris.altoclef.util.helpers.EntityHelper;
import adris.altoclef.util.helpers.ProjectileHelper;
import adris.altoclef.util.helpers.WorldHelper;
import net.minecraft.client.MinecraftClient;
import net.minecraft.entity.Entity;
import net.minecraft.entity.ItemEntity;
import net.minecraft.entity.mob.*;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.projectile.FishingBobberEntity;
import net.minecraft.entity.projectile.PersistentProjectileEntity;
import net.minecraft.entity.projectile.ProjectileEntity;
import net.minecraft.entity.projectile.thrown.EnderPearlEntity;
import net.minecraft.entity.projectile.thrown.ExperienceBottleEntity;
import net.minecraft.item.Item;
import net.minecraft.util.math.Vec3d;
import java.util.*;
import java.util.function.Predicate;
/**
* Keeps track of entities so we can search/grab them.
*/
@SuppressWarnings("rawtypes")
public class EntityTracker extends Tracker {
private final HashMap<Item, List<ItemEntity>> _itemDropLocations = new HashMap<>();
private final HashMap<Class, List<Entity>> _entityMap = new HashMap<>();
private final List<Entity> _closeEntities = new ArrayList<>();
private final List<Entity> _hostiles = new ArrayList<>();
private final List<CachedProjectile> _projectiles = new ArrayList<>();
private final HashMap<String, PlayerEntity> _playerMap = new HashMap<>();
private final HashMap<String, Vec3d> _playerLastCoordinates = new HashMap<>();
private final EntityLocateBlacklist _entityBlacklist = new EntityLocateBlacklist();
private final HashMap<PlayerEntity, List<Entity>> _entitiesCollidingWithPlayerAccumulator = new HashMap<>();
private final HashMap<PlayerEntity, HashSet<Entity>> _entitiesCollidingWithPlayer = new HashMap<>();
public EntityTracker(TrackerManager manager) {
super(manager);
// Listen for player collisions
EventBus.subscribe(PlayerCollidedWithEntityEvent.class, evt -> registerPlayerCollision(evt.player, evt.other));
}
private void registerPlayerCollision(PlayerEntity player, Entity entity) {
if (!_entitiesCollidingWithPlayerAccumulator.containsKey(player)) {
_entitiesCollidingWithPlayerAccumulator.put(player, new ArrayList<>());
}
_entitiesCollidingWithPlayerAccumulator.get(player).add(entity);
}
/**
* Squash a class that may have sub classes into one distinguishable class type.
* For ease of use.
*
* @param type: An entity class that may have a 'simpler' class to squash to
* @return what the given entity class should be read as/catalogued as.
*/
private static Class squashType(Class type) {
// Squash types for ease of use
if (PlayerEntity.class.isAssignableFrom(type)) {
return PlayerEntity.class;
}
return type;
}
public boolean isCollidingWithPlayer(PlayerEntity player, Entity entity) {
return _entitiesCollidingWithPlayer.containsKey(player) && _entitiesCollidingWithPlayer.get(player).contains(entity);
}
public boolean isCollidingWithPlayer(Entity entity) {
return isCollidingWithPlayer(_mod.getPlayer(), entity);
}
public Optional<ItemEntity> getClosestItemDrop(Item... items) {
return getClosestItemDrop(_mod.getPlayer().getPos(), items);
}
public Optional<ItemEntity> getClosestItemDrop(Vec3d position, Item... items) {
return getClosestItemDrop(position, entity -> true, items);
}
public Optional<ItemEntity> getClosestItemDrop(Vec3d position, ItemTarget... items) {
return getClosestItemDrop(position, entity -> true, items);
}
public Optional<ItemEntity> getClosestItemDrop(Predicate<ItemEntity> acceptPredicate, Item... items) {
return getClosestItemDrop(_mod.getPlayer().getPos(), acceptPredicate, items);
}
public Optional<ItemEntity> getClosestItemDrop(Vec3d position, Predicate<ItemEntity> acceptPredicate, Item... items) {
ensureUpdated();
ItemTarget[] tempTargetList = new ItemTarget[items.length];
for (int i = 0; i < items.length; ++i) {
tempTargetList[i] = new ItemTarget(items[i], 9999999);
}
return getClosestItemDrop(position, acceptPredicate, tempTargetList);
}
public Optional<ItemEntity> getClosestItemDrop(Vec3d position, Predicate<ItemEntity> acceptPredicate, ItemTarget... targets) {
ensureUpdated();
if (targets.length == 0) {
Debug.logError("You asked for the drop position of zero items... Most likely a typo.");
return Optional.empty();
}
if (!itemDropped(targets)) {
return Optional.empty();
}
ItemEntity closestEntity = null;
float minCost = Float.POSITIVE_INFINITY;
for (ItemTarget target : targets) {
for (Item item : target.getMatches()) {
if (!itemDropped(item)) continue;
for (ItemEntity entity : _itemDropLocations.get(item)) {
if (_entityBlacklist.unreachable(entity)) continue;
if (!entity.getStack().getItem().equals(item)) continue;
if (!acceptPredicate.test(entity)) continue;
float cost = (float) BaritoneHelper.calculateGenericHeuristic(position, entity.getPos());
if (cost < minCost) {
minCost = cost;
closestEntity = entity;
}
}
}
}
return Optional.ofNullable(closestEntity);
}
public Optional<Entity> getClosestEntity(Class... entityTypes) {
return getClosestEntity(_mod.getPlayer().getPos(), entityTypes);
}
public Optional<Entity> getClosestEntity(Vec3d position, Class... entityTypes) {
return this.getClosestEntity(position, (entity) -> true, entityTypes);
}
public Optional<Entity> getClosestEntity(Predicate<Entity> acceptPredicate, Class... entityTypes) {
return getClosestEntity(_mod.getPlayer().getPos(), acceptPredicate, entityTypes);
}
public Optional<Entity> getClosestEntity(Vec3d position, Predicate<Entity> acceptPredicate, Class... entityTypes) {
Entity closestEntity = null;
double minCost = Float.POSITIVE_INFINITY;
for (Class toFind : entityTypes) {
synchronized (BaritoneHelper.MINECRAFT_LOCK) {
if (_entityMap.containsKey(toFind)) {
for (Entity entity : _entityMap.get(toFind)) {
// Don't accept entities that no longer exist
if (!entity.isAlive()) continue;
if (!acceptPredicate.test(entity)) continue;
double cost = entity.squaredDistanceTo(position);
if (cost < minCost) {
minCost = cost;
closestEntity = entity;
}
}
}
}
}
return Optional.ofNullable(closestEntity);
}
public boolean itemDropped(Item... items) {
ensureUpdated();
for (Item item : items) {
if (_itemDropLocations.containsKey(item)) {
// Find a non-blacklisted item
for (ItemEntity entity : _itemDropLocations.get(item)) {
if (!_entityBlacklist.unreachable(entity)) return true;
}
}
}
return false;
}
public boolean itemDropped(ItemTarget... targets) {
ensureUpdated();
for (ItemTarget target : targets) {
if (itemDropped(target.getMatches())) return true;
}
return false;
}
public List<ItemEntity> getDroppedItems() {
ensureUpdated();
return _itemDropLocations.values().stream().reduce(new ArrayList<>(), (result, drops) -> {
result.addAll(drops);
return result;
});
}
public boolean entityFound(Predicate<Entity> shouldAccept, Class... types) {
ensureUpdated();
for (Class type : types) {
synchronized (BaritoneHelper.MINECRAFT_LOCK) {
for (Entity entity : _entityMap.getOrDefault(type, Collections.emptyList())) {
if (shouldAccept.test(entity))
return true;
}
}
}
return false;
}
public boolean entityFound(Class ...types) {
return entityFound(check -> true, types);
}
public <T extends Entity> List<T> getTrackedEntities(Class<T> type) {
ensureUpdated();
if (!entityFound(type)) {
return Collections.emptyList();
}
synchronized (BaritoneHelper.MINECRAFT_LOCK) {
//noinspection unchecked
return (List<T>) _entityMap.get(type);
}
}
/**
* Gets all entities that are within our interact range
*/
public List<Entity> getCloseEntities() {
ensureUpdated();
synchronized (BaritoneHelper.MINECRAFT_LOCK) {
return _closeEntities;
}
}
/**
* Gets a list of projectiles that we've cached/stored information about.
*/
public List<CachedProjectile> getProjectiles() {
ensureUpdated();
synchronized (BaritoneHelper.MINECRAFT_LOCK) {
return _projectiles;
}
}
public List<Entity> getHostiles() {
ensureUpdated();
synchronized (BaritoneHelper.MINECRAFT_LOCK) {
return _hostiles;
}
}
/**
* Is a player loaded/within render distance?
* @param name Username on a multiplayer server
*/
public boolean isPlayerLoaded(String name) {
ensureUpdated();
synchronized (BaritoneHelper.MINECRAFT_LOCK) {
return _playerMap.containsKey(name);
}
}
/**
* Get where we last saw a player, if we saw them at all.
* @return Username on a multiplayer server.
*/
public Optional<Vec3d> getPlayerMostRecentPosition(String name) {
ensureUpdated();
synchronized (BaritoneHelper.MINECRAFT_LOCK) {
return Optional.ofNullable(_playerLastCoordinates.getOrDefault(name, null));
}
}
/**
* Gets the player entity corresponding to a username, if they're loaded/within render distance.
* @param name Username on a multiplayer server.
*/
public Optional<PlayerEntity> getPlayerEntity(String name) {
if (isPlayerLoaded(name)) {
synchronized (BaritoneHelper.MINECRAFT_LOCK) {
return Optional.of(_playerMap.get(name));
}
}
return Optional.empty();
}
/**
* Tells the entity tracker that we were unable to reach this entity.
*/
public void requestEntityUnreachable(Entity entity) {
_entityBlacklist.blackListItem(_mod, entity, 3);
}
/**
* Whether we have decided that this entity is unreachable.
*/
public boolean isEntityReachable(Entity entity) {
return !_entityBlacklist.unreachable(entity);
}
@Override
protected synchronized void updateState() {
synchronized (BaritoneHelper.MINECRAFT_LOCK) {
_itemDropLocations.clear();
_entityMap.clear();
_closeEntities.clear();
_projectiles.clear();
_hostiles.clear();
_playerMap.clear();
if (MinecraftClient.getInstance().world == null) return;
// Store/Register All accumulated player collisions for this frame.
_entitiesCollidingWithPlayer.clear();
for (Map.Entry<PlayerEntity, List<Entity>> collisions : _entitiesCollidingWithPlayerAccumulator.entrySet()) {
_entitiesCollidingWithPlayer.put(collisions.getKey(), new HashSet<>());
_entitiesCollidingWithPlayer.get(collisions.getKey()).addAll(collisions.getValue());
}
_entitiesCollidingWithPlayerAccumulator.clear();
// Loop through all entities and track 'em
for (Entity entity : MinecraftClient.getInstance().world.getEntities()) {
// Catalogue based on type. Some types may get "squashed" or combined into one.
Class type = entity.getClass();
type = squashType(type);
//noinspection ConstantConditions
if (entity == null || !entity.isAlive()) continue;
// Don't catalogue our own player.
if (type == PlayerEntity.class && entity.equals(_mod.getPlayer())) continue;
if (!_entityMap.containsKey(type)) {
_entityMap.put(type, new ArrayList<>());
}
_entityMap.get(type).add(entity);
if (_mod.getControllerExtras().inRange(entity)) {
_closeEntities.add(entity);
}
if (entity instanceof ItemEntity ientity) {
Item droppedItem = ientity.getStack().getItem();
// Only cared about GROUNDED item entities
if (ientity.isOnGround() || ientity.isTouchingWater() || WorldHelper.isSolid(_mod, ientity.getBlockPos().down(2)) || WorldHelper.isSolid(_mod, ientity.getBlockPos().down(3))) {
if (!_itemDropLocations.containsKey(droppedItem)) {
_itemDropLocations.put(droppedItem, new ArrayList<>());
}
_itemDropLocations.get(droppedItem).add(ientity);
}
} else if (entity instanceof MobEntity) {
//noinspection ConstantConditions
if (entity instanceof HostileEntity || entity instanceof HoglinEntity || entity instanceof ZoglinEntity) {
if (EntityHelper.isAngryAtPlayer(_mod, entity)) {
// Check if the mob is facing us or is close enough
boolean closeEnough = entity.isInRange(_mod.getPlayer(), 26);
//Debug.logInternal("TARGET: " + hostile.is);
if (closeEnough) {
_hostiles.add(entity);
}
}
}
} else if (entity instanceof ProjectileEntity projEntity) {
if (!_mod.getBehaviour().shouldAvoidDodgingProjectile(entity)) {
CachedProjectile proj = new CachedProjectile();
boolean inGround = false;
// Get projectile "inGround" variable
if (entity instanceof PersistentProjectileEntity) {
inGround = ((PersistentProjectileEntityAccessor) entity).isInGround();
}
// Ignore some of the harlmess projectiles
if (projEntity instanceof FishingBobberEntity || projEntity instanceof EnderPearlEntity || projEntity instanceof ExperienceBottleEntity)
continue;
if (!inGround) {
proj.position = projEntity.getPos();
proj.velocity = projEntity.getVelocity();
proj.gravity = ProjectileHelper.hasGravity(projEntity) ? ProjectileHelper.ARROW_GRAVITY_ACCEL : 0;
proj.projectileType = projEntity.getClass();
_projectiles.add(proj);
}
}
} else if (entity instanceof PlayerEntity player) {
String name = player.getName().getString();
_playerMap.put(name, player);
_playerLastCoordinates.put(name, player.getPos());
}
}
}
}
@Override
protected void reset() {
// Dirty clears everything else.
_entityBlacklist.clear();
}
}
| 0 | 0.940254 | 1 | 0.940254 | game-dev | MEDIA | 0.936491 | game-dev | 0.982274 | 1 | 0.982274 |
ActiveState/code | 3,435 | recipes/Python/141602_Barebones_VC_code_invoking_PythCOM_factory/recipe-141602.py | # Python code
from win32com . server . register import UseCommandLine
from win32api import MessageBox
from win32com . client import Dispatch
from win32ui import MessageBox
class StemmerFactory :
_reg_clsid_ = "{602D10EB-426C-4D6F-A4DF-C05572EB780B}"
_reg_desc_ = "LangTech Stemmer"
_reg_progid_ = "LangTech.Stemmer"
_public_methods_ = [ 'new' ]
def new ( self, scriptFile ) :
self . scriptFile = scriptFile
stemmer = Dispatch ( "LangTech.Stemmer.Product" )
return stemmer
class Stemmer :
_reg_clsid_ = "{B306454A-CAE6-4A74-ACAD-0BB11EF256DD}"
_reg_desc_ = "LangTech Stemmer Product"
_reg_progid_ = "LangTech.Stemmer.Product"
_public_methods_ = [ 'stemWord' ]
def stemWord ( self, word ) :
# extremely simple stemming: if the word ends in 's' then drop the 's'
if word [ -1 ] == "s":
return word [ : -1 ]
else:
return word
if __name__ == '__main__' :
UseCommandLine ( StemmerFactory )
UseCommandLine ( Stemmer )
#----------------------------------------
#
# C++
#include <comdef.h>
#include <initguid.h>
DEFINE_GUID(CLSID_StemmerFactory,
0x602D10EB, 0x426C, 0x4D6F, 0xA4, 0xDF, 0xC0, 0x55, 0x72, 0xEB, 0x78, 0x0B);
DISPID rgDispId ;
OLECHAR * rgszNames [ ] = { OLESTR ( "new" ) };
DISPPARAMS DispParams;
VARIANT VarResult;
EXCEPINFO excepinfo;
UINT uArgErr;
VARIANTARG * pvarg = NULL;
_bstr_t stemmedWord;
HRESULT hr;
IDispatch * stemmerFactory;
IDispatch * stemmer;
if ( FAILED ( hr = CoInitialize ( NULL ) ) ) {
MessageBox ( 0, "CoInitialize failure", "Fault", MB_OK );
break;
}
if ( FAILED ( hr = CoCreateInstance (
CLSID_StemmerFactory,
NULL,
CLSCTX_INPROC_SERVER,
IID_IDispatch,
( LPVOID * ) & stemmerFactory ) ) ) {
MessageBox ( 0, "CoCreateInstance failure", "Fault", MB_OK );
break;
}
if ( FAILED ( hr = stemmerFactory -> GetIDsOfNames (
IID_NULL,
rgszNames,
1,
LOCALE_SYSTEM_DEFAULT,
& rgDispId
) ) ) {
MessageBox ( 0, "GetIDsOfNames failure", "Fault", MB_OK );
break;
}
DispParams.cArgs = 1;
DispParams.cNamedArgs = 0;
DispParams.rgdispidNamedArgs = 0;
pvarg = new VARIANTARG [ DispParams . cArgs ];
if ( pvarg == NULL ) {
MessageBox ( 0, "Insufficient 1st memory", "Fault", MB_OK );
break;
}
pvarg -> vt = VT_BSTR;
pvarg -> bstrVal = SysAllocString ( L"engRules.pl" );
DispParams.rgvarg = pvarg;
if ( FAILED ( hr = stemmerFactory -> Invoke (
rgDispId,
IID_NULL,
LOCALE_SYSTEM_DEFAULT,
DISPATCH_METHOD,
& DispParams,
& VarResult,
& excepinfo,
& uArgErr
) ) ) {
MessageBox ( 0, "1st Invoke failure", "Fault", MB_OK );
break;
}
delete ( pvarg );
stemmer = VarResult.pdispVal;
pvarg = new VARIANTARG [ DispParams . cArgs ];
if ( pvarg == NULL ) {
MessageBox ( 0, "Insufficient 2nd memory", "Fault", MB_OK );
break;
}
pvarg -> vt = VT_BSTR;
pvarg -> bstrVal = SysAllocString ( L"cats" );
DispParams.rgvarg = pvarg;
if ( FAILED ( hr = stemmer -> Invoke (
rgDispId,
IID_NULL,
LOCALE_SYSTEM_DEFAULT,
DISPATCH_METHOD,
& DispParams,
& VarResult,
& excepinfo,
& uArgErr
) ) ) {
MessageBox ( 0, "2nd Invoke failure", "Fault", MB_OK );
break;
}
delete ( pvarg );
stemmedWord = VarResult.bstrVal;
MessageBox (
0,
( const char * ) stemmedWord,
"Resulting Stemmed Word",
MB_OK
);
CoUninitialize ( );
| 0 | 0.878728 | 1 | 0.878728 | game-dev | MEDIA | 0.443371 | game-dev | 0.895579 | 1 | 0.895579 |
Bukkit/Bukkit | 4,490 | src/main/java/org/bukkit/event/player/AsyncPlayerChatEvent.java | package org.bukkit.event.player;
import java.util.IllegalFormatException;
import java.util.Set;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
import org.bukkit.event.HandlerList;
/**
* This event will sometimes fire synchronously, depending on how it was
* triggered.
* <p>
* The constructor provides a boolean to indicate if the event was fired
* synchronously or asynchronously. When asynchronous, this event can be
* called from any thread, sans the main thread, and has limited access to the
* API.
* <p>
* If a player is the direct cause of this event by an incoming packet, this
* event will be asynchronous. If a plugin triggers this event by compelling a
* player to chat, this event will be synchronous.
* <p>
* Care should be taken to check {@link #isAsynchronous()} and treat the event
* appropriately.
*/
public class AsyncPlayerChatEvent extends PlayerEvent implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private boolean cancel = false;
private String message;
private String format = "<%1$s> %2$s";
private final Set<Player> recipients;
/**
*
* @param async This changes the event to a synchronous state.
* @param who the chat sender
* @param message the message sent
* @param players the players to receive the message. This may be a lazy
* or unmodifiable collection.
*/
public AsyncPlayerChatEvent(final boolean async, final Player who, final String message, final Set<Player> players) {
super(who, async);
this.message = message;
recipients = players;
}
/**
* Gets the message that the player is attempting to send. This message
* will be used with {@link #getFormat()}.
*
* @return Message the player is attempting to send
*/
public String getMessage() {
return message;
}
/**
* Sets the message that the player will send. This message will be used
* with {@link #getFormat()}.
*
* @param message New message that the player will send
*/
public void setMessage(String message) {
this.message = message;
}
/**
* Gets the format to use to display this chat message.
* <p>
* When this event finishes execution, the first format parameter is the
* {@link Player#getDisplayName()} and the second parameter is {@link
* #getMessage()}
*
* @return {@link String#format(String, Object...)} compatible format
* string
*/
public String getFormat() {
return format;
}
/**
* Sets the format to use to display this chat message.
* <p>
* When this event finishes execution, the first format parameter is the
* {@link Player#getDisplayName()} and the second parameter is {@link
* #getMessage()}
*
* @param format {@link String#format(String, Object...)} compatible
* format string
* @throws IllegalFormatException if the underlying API throws the
* exception
* @throws NullPointerException if format is null
* @see String#format(String, Object...)
*/
public void setFormat(final String format) throws IllegalFormatException, NullPointerException {
// Oh for a better way to do this!
try {
String.format(format, player, message);
} catch (RuntimeException ex) {
ex.fillInStackTrace();
throw ex;
}
this.format = format;
}
/**
* Gets a set of recipients that this chat message will be displayed to.
* <p>
* The set returned is not guaranteed to be mutable and may auto-populate
* on access. Any listener accessing the returned set should be aware that
* it may reduce performance for a lazy set implementation.
* <p>
* Listeners should be aware that modifying the list may throw {@link
* UnsupportedOperationException} if the event caller provides an
* unmodifiable set.
*
* @return All Players who will see this chat message
*/
public Set<Player> getRecipients() {
return recipients;
}
public boolean isCancelled() {
return cancel ;
}
public void setCancelled(boolean cancel) {
this.cancel = cancel;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
}
| 0 | 0.922456 | 1 | 0.922456 | game-dev | MEDIA | 0.652188 | game-dev | 0.983048 | 1 | 0.983048 |
shit-ware/IW4 | 31,645 | maps/mp/killstreaks/_airstrike.gsc | #include maps\mp\_utility;
#include maps\mp\killstreaks\_harrier;
#include maps\mp\gametypes\_hud_util;
#include common_scripts\utility;
init()
{
precacheLocationSelector( "map_artillery_selector" );
precacheString( &"MP_WAR_AIRSTRIKE_INBOUND_NEAR_YOUR_POSITION" );
precacheString( &"MP_WAR_AIRSTRIKE_INBOUND" );
precacheString( &"MP_CIVILIAN_AIR_TRAFFIC" );
precacheString( &"MP_AIR_SPACE_TOO_CROWDED" );
precacheItem( "stealth_bomb_mp" );
precacheItem( "artillery_mp" );
precacheItem("harrier_missile_mp");
precacheModel( "vehicle_av8b_harrier_jet_mp" );
precacheModel( "vehicle_av8b_harrier_jet_opfor_mp" );
precacheModel( "weapon_minigun" );
precacheModel( "vehicle_b2_bomber" );
PrecacheVehicle( "harrier_mp" );
precacheTurret( "harrier_FFAR_mp" );
PrecacheMiniMapIcon( "compass_objpoint_airstrike_friendly" );
PrecacheMiniMapIcon( "compass_objpoint_airstrike_busy" );
PrecacheMiniMapIcon( "compass_objpoint_b2_airstrike_friendly" );
PrecacheMiniMapIcon( "compass_objpoint_b2_airstrike_enemy" );
PrecacheMiniMapIcon( "hud_minimap_harrier_green" );
PrecacheMiniMapIcon( "hud_minimap_harrier_red" );
level.onfirefx = loadfx ("fire/fire_smoke_trail_L");
level.airstrikefx = loadfx ("explosions/clusterbomb");
level.mortareffect = loadfx ("explosions/artilleryExp_dirt_brown");
level.bombstrike = loadfx ("explosions/wall_explosion_pm_a");
level.stealthbombfx = loadfx ("explosions/stealth_bomb_mp");
level.airplane = [];
level.harriers = [];
level.planes = 0;
level.harrier_smoke = loadfx("fire/jet_afterburner_harrier_damaged");
level.harrier_deathfx = loadfx ("explosions/aerial_explosion_harrier");
level.harrier_afterburnerfx = loadfx ("fire/jet_afterburner_harrier");
level.fx_airstrike_afterburner = loadfx ("fire/jet_afterburner");
level.fx_airstrike_contrail = loadfx ("smoke/jet_contrail");
// airstrike danger area is the circle of radius artilleryDangerMaxRadius
// stretched by a factor of artilleryDangerOvalScale in the direction of the incoming airstrike,
// moved by artilleryDangerForwardPush * artilleryDangerMaxRadius in the same direction.
// use scr_Airstrikedebug to visualize.
level.dangerMaxRadius["stealth"] = 900;
level.dangerMinRadius["stealth"] = 750;
level.dangerForwardPush["stealth"] = 1;
level.dangerOvalScale["stealth"] = 6.0;
level.dangerMaxRadius["default"] = 550;
level.dangerMinRadius["default"] = 300;
level.dangerForwardPush["default"] = 1.5;
level.dangerOvalScale["default"] = 6.0;
level.dangerMaxRadius["precision"] = 550;
level.dangerMinRadius["precision"] = 300;
level.dangerForwardPush["precision"] = 2.0;
level.dangerOvalScale["precision"] = 6.0;
level.dangerMaxRadius["harrier"] = 550;
level.dangerMinRadius["harrier"] = 300;
level.dangerForwardPush["harrier"] = 1.5;
level.dangerOvalScale["harrier"] = 6.0;
level.artilleryDangerCenters = [];
level.killStreakFuncs["airstrike"] = ::tryUseAirstrike;
level.killStreakFuncs["precision_airstrike"] = ::tryUsePrecisionAirstrike;
level.killStreakFuncs["super_airstrike"] = ::tryUseSuperAirstrike;
level.killStreakFuncs["harrier_airstrike"] = ::tryUseHarrierAirstrike;
level.killStreakFuncs["stealth_airstrike"] = ::tryUseStealthAirstrike;
}
tryUsePrecisionAirstrike( lifeId )
{
return tryUseAirstrike( lifeId, "precision" );
}
tryUseStealthAirstrike( lifeId )
{
return tryUseAirstrike( lifeId, "stealth" );
}
tryUseSuperAirstrike( lifeId )
{
return tryUseAirstrike( lifeId, "super" );
}
tryUseHarrierAirstrike( lifeId )
{
return tryUseAirstrike( lifeId, "harrier" );
}
tryUseAirstrike( lifeId, airStrikeType )
{
if ( isDefined( level.civilianJetFlyBy ) )
{
self iPrintLnBold( &"MP_CIVILIAN_AIR_TRAFFIC" );
return false;
}
if ( self isUsingRemote() )
{
return false;
}
if ( !isDefined( airStrikeType ) )
airStrikeType = "none";
switch( airStrikeType )
{
case "precision":
break;
case "stealth":
break;
case "harrier":
if ( level.planes > 1 )
{
self iPrintLnBold( &"MP_AIR_SPACE_TOO_CROWDED" );
return false;
}
break;
case "super":
break;
}
result = self selectAirstrikeLocation( lifeId, airStrikeType );
if ( !isDefined( result ) || !result )
return false;
return true;
}
doAirstrike( lifeId, origin, yaw, owner, team )
{
assert( isDefined( origin ) );
assert( isDefined( yaw ) );
if ( isDefined( self.airStrikeType ) )
airstrikeType = self.airStrikeType;
else
airstrikeType = "default";
if ( airStrikeType == "harrier" )
level.planes++;
if ( isDefined( level.airstrikeInProgress ) )
{
while ( isDefined( level.airstrikeInProgress ) )
level waittill ( "begin_airstrike" );
level.airstrikeInProgress = true;
wait ( 2.0 );
}
if ( !isDefined( owner ) )
{
if ( airStrikeType == "harrier" )
level.planes--;
return;
}
level.airstrikeInProgress = true;
num = 17 + randomint(3);
trace = bullettrace(origin, origin + (0,0,-1000000), false, undefined);
targetpos = trace["position"];
if ( level.teambased )
{
players = level.players;
for ( i = 0; i < level.players.size; i++ )
{
player = level.players[i];
playerteam = player.pers["team"];
if ( isdefined( playerteam ) )
{
if ( playerteam == team && self.airStrikeType != "stealth" )
player iprintln( &"MP_WAR_AIRSTRIKE_INBOUND", owner );
}
}
}
else
{
if ( !level.hardcoreMode )
{
if ( pointIsInAirstrikeArea( owner.origin, targetpos, yaw, airstrikeType ) )
owner iprintlnbold(&"MP_WAR_AIRSTRIKE_INBOUND_NEAR_YOUR_POSITION");
}
}
dangerCenter = spawnstruct();
dangerCenter.origin = targetpos;
dangerCenter.forward = anglesToForward( (0,yaw,0) );
dangerCenter.airstrikeType = airstrikeType;
level.artilleryDangerCenters[ level.artilleryDangerCenters.size ] = dangerCenter;
/# level thread debugArtilleryDangerCenters( airstrikeType ); #/
harrierEnt = callStrike( lifeId, owner, targetpos, yaw );
wait( 1.0 );
level.airstrikeInProgress = undefined;
owner notify ( "begin_airstrike" );
level notify ( "begin_airstrike" );
wait 7.5;
found = false;
newarray = [];
for ( i = 0; i < level.artilleryDangerCenters.size; i++ )
{
if ( !found && level.artilleryDangerCenters[i].origin == targetpos )
{
found = true;
continue;
}
newarray[ newarray.size ] = level.artilleryDangerCenters[i];
}
assert( found );
assert( newarray.size == level.artilleryDangerCenters.size - 1 );
level.artilleryDangerCenters = newarray;
if ( airStrikeType != "harrier" )
return;
while ( isDefined( harrierEnt ) )
wait ( 0.1 );
level.planes--;
}
clearProgress( delay )
{
wait ( 2.0 );
level.airstrikeInProgress = undefined;
}
/#
debugArtilleryDangerCenters( airstrikeType )
{
level notify("debugArtilleryDangerCenters_thread");
level endon("debugArtilleryDangerCenters_thread");
if ( getdvarint("scr_airstrikedebug") != 1 && getdvarint("scr_spawnpointdebug") == 0 )
{
return;
}
while( level.artilleryDangerCenters.size > 0 )
{
for ( i = 0; i < level.artilleryDangerCenters.size; i++ )
{
origin = level.artilleryDangerCenters[i].origin;
forward = level.artilleryDangerCenters[i].forward;
origin += forward * level.dangerForwardPush[airstrikeType] * level.dangerMaxRadius[airstrikeType];
previnnerpos = (0,0,0);
prevouterpos = (0,0,0);
for ( j = 0; j <= 40; j++ )
{
frac = (j * 1.0) / 40;
angle = frac * 360;
dir = anglesToForward((0,angle,0));
forwardPart = vectordot( dir, forward ) * forward;
perpendicularPart = dir - forwardPart;
pos = forwardPart * level.dangerOvalScale[airstrikeType] + perpendicularPart;
innerpos = pos * level.dangerMinRadius[airstrikeType];
innerpos += origin;
outerpos = pos * level.dangerMaxRadius[airstrikeType];
outerpos += origin;
if ( j > 0 )
{
line( innerpos, previnnerpos, (1, 0, 0) );
line( outerpos, prevouterpos, (1,.5,.5) );
}
previnnerpos = innerpos;
prevouterpos = outerpos;
}
}
wait .05;
}
}
#/
getAirstrikeDanger( point )
{
danger = 0;
for ( i = 0; i < level.artilleryDangerCenters.size; i++ )
{
origin = level.artilleryDangerCenters[i].origin;
forward = level.artilleryDangerCenters[i].forward;
airstrikeType = level.artilleryDangerCenters[i].airstrikeType;
danger += getSingleAirstrikeDanger( point, origin, forward, airstrikeType );
}
return danger;
}
getSingleAirstrikeDanger( point, origin, forward, airstrikeType )
{
center = origin + level.dangerForwardPush[airstrikeType] * level.dangerMaxRadius[airstrikeType] * forward;
diff = point - center;
diff = (diff[0], diff[1], 0);
forwardPart = vectorDot( diff, forward ) * forward;
perpendicularPart = diff - forwardPart;
circlePos = perpendicularPart + forwardPart / level.dangerOvalScale[airstrikeType];
/* /#
if ( getdvar("scr_airstrikedebug") == "1" )
{
thread airstrikeLine( center, center + perpendicularPart, (1,1,1), 50 );
thread airstrikeLine( center + perpendicularPart, center + circlePos, (1,1,1), 50 );
thread airstrikeLine( center + circlePos, point, (.5,.5,.5), 50 );
}
#/ */
distsq = lengthSquared( circlePos );
if ( distsq > level.dangerMaxRadius[airstrikeType] * level.dangerMaxRadius[airstrikeType] )
return 0;
if ( distsq < level.dangerMinRadius[airstrikeType] * level.dangerMinRadius[airstrikeType] )
return 1;
dist = sqrt( distsq );
distFrac = (dist - level.dangerMinRadius[airstrikeType]) / (level.dangerMaxRadius[airstrikeType] - level.dangerMinRadius[airstrikeType]);
assertEx( distFrac >= 0 && distFrac <= 1, distFrac );
return 1 - distFrac;
}
pointIsInAirstrikeArea( point, targetpos, yaw, airstrikeType )
{
return distance2d( point, targetpos ) <= level.dangerMaxRadius[airstrikeType] * 1.25;
// TODO
//return getSingleAirstrikeDanger( point, targetpos, yaw ) > 0;
}
losRadiusDamage( pos, radius, max, min, owner, eInflictor, sWeapon )
{
ents = maps\mp\gametypes\_weapons::getDamageableEnts(pos, radius, true);
glassRadiusDamage( pos, radius, max, min );
for (i = 0; i < ents.size; i++)
{
if (ents[i].entity == self)
continue;
dist = distance(pos, ents[i].damageCenter);
if ( ents[i].isPlayer || ( isDefined( ents[i].isSentry ) && ents[i].isSentry ) )
{
// check if there is a path to this entity 130 units above his feet. if not, they're probably indoors
indoors = !BulletTracePassed( ents[i].entity.origin, ents[i].entity.origin + (0,0,130), false, undefined );
if ( indoors )
{
indoors = !BulletTracePassed( ents[i].entity.origin + (0,0,130), pos + (0,0,130 - 16), false, undefined );
if ( indoors )
{
// give them a distance advantage for being indoors.
dist *= 4;
if ( dist > radius )
continue;
}
}
}
ents[i].damage = int(max + (min-max)*dist/radius);
ents[i].pos = pos;
ents[i].damageOwner = owner;
ents[i].eInflictor = eInflictor;
level.airStrikeDamagedEnts[level.airStrikeDamagedEntsCount] = ents[i];
level.airStrikeDamagedEntsCount++;
}
thread airstrikeDamageEntsThread( sWeapon );
}
airstrikeDamageEntsThread( sWeapon )
{
self notify ( "airstrikeDamageEntsThread" );
self endon ( "airstrikeDamageEntsThread" );
for ( ; level.airstrikeDamagedEntsIndex < level.airstrikeDamagedEntsCount; level.airstrikeDamagedEntsIndex++ )
{
if ( !isDefined( level.airstrikeDamagedEnts[level.airstrikeDamagedEntsIndex] ) )
continue;
ent = level.airstrikeDamagedEnts[level.airstrikeDamagedEntsIndex];
if ( !isDefined( ent.entity ) )
continue;
if ( !ent.isPlayer || isAlive( ent.entity ) )
{
ent maps\mp\gametypes\_weapons::damageEnt(
ent.eInflictor, // eInflictor = the entity that causes the damage (e.g. a claymore)
ent.damageOwner, // eAttacker = the player that is attacking
ent.damage, // iDamage = the amount of damage to do
"MOD_PROJECTILE_SPLASH", // sMeansOfDeath = string specifying the method of death (e.g. "MOD_PROJECTILE_SPLASH")
sWeapon, // sWeapon = string specifying the weapon used (e.g. "claymore_mp")
ent.pos, // damagepos = the position damage is coming from
vectornormalize(ent.damageCenter - ent.pos) // damagedir = the direction damage is moving in
);
level.airstrikeDamagedEnts[level.airstrikeDamagedEntsIndex] = undefined;
if ( ent.isPlayer )
wait ( 0.05 );
}
else
{
level.airstrikeDamagedEnts[level.airstrikeDamagedEntsIndex] = undefined;
}
}
}
radiusArtilleryShellshock(pos, radius, maxduration, minduration, team )
{
players = level.players;
foreach ( player in level.players )
{
if ( !isAlive( player ) )
continue;
if ( player.team == team || player.team == "spectator" )
continue;
playerPos = player.origin + (0,0,32);
dist = distance( pos, playerPos );
if ( dist > radius )
continue;
duration = int(maxduration + (minduration-maxduration)*dist/radius);
player thread artilleryShellshock( "default", duration );
}
}
artilleryShellshock(type, duration)
{
self endon ( "disconnect" );
if (isdefined(self.beingArtilleryShellshocked) && self.beingArtilleryShellshocked)
return;
self.beingArtilleryShellshocked = true;
self shellshock(type, duration);
wait(duration + 1);
self.beingArtilleryShellshocked = false;
}
/#
airstrikeLine( start, end, color, duration )
{
frames = duration * 20;
for ( i = 0; i < frames; i++ )
{
line(start,end,color);
wait .05;
}
}
traceBomb()
{
self endon("death");
prevpos = self.origin;
while(1)
{
thread airstrikeLine( prevpos, self.origin, (.5,1,0), 40 );
prevpos = self.origin;
wait .2;
}
}
#/
doBomberStrike( lifeId, owner, requiredDeathCount, bombsite, startPoint, endPoint, bombTime, flyTime, direction, airStrikeType )
{
// plane spawning randomness = up to 125 units, biased towards 0
// radius of bomb damage is 512
if ( !isDefined( owner ) )
return;
startPathRandomness = 100;
endPathRandomness = 150;
pathStart = startPoint + ( (randomfloat(2) - 1)*startPathRandomness, (randomfloat(2) - 1)*startPathRandomness, 0 );
pathEnd = endPoint + ( (randomfloat(2) - 1)*endPathRandomness , (randomfloat(2) - 1)*endPathRandomness , 0 );
// Spawn the planes
plane = spawnplane( owner, "script_model", pathStart, "compass_objpoint_b2_airstrike_friendly", "compass_objpoint_b2_airstrike_enemy" );
plane playLoopSound( "veh_b2_dist_loop" );
plane setModel( "vehicle_b2_bomber" );
plane thread handleEMP( owner );
plane.lifeId = lifeId;
plane.angles = direction;
forward = anglesToForward( direction );
plane moveTo( pathEnd, flyTime, 0, 0 );
thread stealthBomber_killCam( plane, pathEnd, flyTime, airStrikeType );
thread bomberDropBombs( plane, bombsite, owner );
// Delete the plane after its flyby
wait ( flyTime );
plane notify( "delete" );
plane delete();
}
bomberDropBombs( plane, bombSite, owner )
{
while ( !targetIsClose( plane, bombsite, 5000 ) )
wait ( 0.05 );
//playfxontag( level.stealthbombfx, plane, "tag_left_alamo_missile" );
//playfxontag( level.stealthbombfx, plane, "tag_right_alamo_missile" );
showFx = true;
sonicBoom = false;
plane notify ( "start_bombing" );
plane thread playBombFx();
for ( dist = targetGetDist( plane, bombsite ); dist < 5000; dist = targetGetDist( plane, bombsite ) )
{
if ( dist < 1500 && !sonicBoom )
{
plane playSound( "veh_b2_sonic_boom" );
sonicBoom = true;
}
showFx = !showFx;
if ( dist < 4500 )
plane thread callStrike_bomb( plane.origin, owner, (0,0,0), showFx );
wait ( 0.1 );
}
plane notify ( "stop_bombing" );
//stopfxontag( level.stealthbombfx, plane, "tag_left_alamo_missile" );
//stopfxontag( level.stealthbombfx, plane, "tag_right_alamo_missile" );
}
playBombFx()
{
self endon ( "stop_bombing" );
for ( ;; )
{
playFxOnTag( level.stealthbombfx, self, "tag_left_alamo_missile" );
playFxOnTag( level.stealthbombfx, self, "tag_right_alamo_missile" );
wait ( 0.5 );
}
}
stealthBomber_killCam( plane, pathEnd, flyTime, typeOfStrike )
{
plane waittill ( "start_bombing" );
planedir = anglesToForward( plane.angles );
killCamEnt = spawn( "script_model", plane.origin + (0,0,100) - planedir * 200 );
plane.killCamEnt = killCamEnt;
plane.airstrikeType = typeOfStrike;
killCamEnt.startTime = gettime();
killCamEnt thread deleteAfterTime( 15.0 );
killCamEnt linkTo( plane, "tag_origin", (-256,768,768), ( 0,0,0 ) );
}
callStrike_bomb( coord, owner, offset, showFx )
{
if ( !isDefined( owner ) || owner isEMPed() )
{
self notify( "stop_bombing" );
return;
}
accuracyRadius = 512;
randVec = ( 0, randomint( 360 ), 0 );
bombPoint = coord + vector_multiply( anglestoforward( randVec ), randomFloat( accuracyRadius ) );
trace = bulletTrace( bombPoint, bombPoint + (0,0,-10000), false, undefined );
bombPoint = trace["position"];
bombHeight = distance( coord, bombPoint );
if ( bombHeight > 5000 )
return;
wait ( 0.85 * (bombHeight / 2000) );
if ( !isDefined( owner ) || owner isEMPed() )
{
self notify( "stop_bombing" );
return;
}
if ( showFx )
{
playFx( level.mortareffect, bombPoint );
PlayRumbleOnPosition( "grenade_rumble", bombPoint );
earthquake( 1.0, 0.6, bombPoint, 2000 );
}
thread playSoundInSpace( "exp_airstrike_bomb", bombPoint );
radiusArtilleryShellshock( bombPoint, 512, 8, 4, owner.team );
losRadiusDamage( bombPoint + (0,0,16), 896, 300, 50, owner, self, "stealth_bomb_mp" ); // targetpos, radius, maxdamage, mindamage, player causing damage
}
doPlaneStrike( lifeId, owner, requiredDeathCount, bombsite, startPoint, endPoint, bombTime, flyTime, direction, typeOfStrike )
{
// plane spawning randomness = up to 125 units, biased towards 0
// radius of bomb damage is 512
if ( !isDefined( owner ) )
return;
startPathRandomness = 100;
endPathRandomness = 150;
pathStart = startPoint + ( (randomfloat(2) - 1)*startPathRandomness, (randomfloat(2) - 1)*startPathRandomness, 0 );
pathEnd = endPoint + ( (randomfloat(2) - 1)*endPathRandomness , (randomfloat(2) - 1)*endPathRandomness , 0 );
// Spawn the planes
if( typeOfStrike == "harrier" )
plane = spawnplane( owner, "script_model", pathStart, "hud_minimap_harrier_green", "hud_minimap_harrier_red" );
else
plane = spawnplane( owner, "script_model", pathStart, "compass_objpoint_airstrike_friendly", "compass_objpoint_airstrike_busy" );
if( typeOfStrike == "harrier" )
{
if ( owner.team == "allies" )
plane setModel( "vehicle_av8b_harrier_jet_mp" );
else
plane setModel( "vehicle_av8b_harrier_jet_opfor_mp" );
}
else
plane setModel( "vehicle_mig29_desert" );
plane playloopsound( "veh_mig29_dist_loop" );
plane thread handleEMP( owner );
plane.lifeId = lifeId;
plane.angles = direction;
forward = anglesToForward( direction );
plane thread playPlaneFx();
plane moveTo( pathEnd, flyTime, 0, 0 );
/#
if ( getdvar("scr_airstrikedebug") == "1" )
thread airstrikeLine( pathStart, pathEnd, (1,1,1), 20 );
#/
//thread callStrike_planeSound( plane, bombsite );
thread callStrike_bombEffect( plane, pathEnd, flyTime, bombTime - 1.0, owner, requiredDeathCount, typeOfStrike );
// Delete the plane after its flyby
wait flyTime;
plane notify( "delete" );
plane delete();
}
callStrike_bombEffect( plane, pathEnd, flyTime, launchTime, owner, requiredDeathCount, typeOfStrike )
{
wait ( launchTime );
if ( !isDefined( owner )|| owner isEMPed() )
return;
plane playSound( "veh_mig29_sonic_boom" );
planedir = anglesToForward( plane.angles );
bomb = spawnbomb( plane.origin, plane.angles );
bomb moveGravity( vector_multiply( anglestoforward( plane.angles ), 7000/1.5 ), 3.0 );
bomb.lifeId = requiredDeathCount;
killCamEnt = spawn( "script_model", plane.origin + (0,0,100) - planedir * 200 );
bomb.killCamEnt = killCamEnt;
bomb.airstrikeType = typeOfStrike;
killCamEnt.startTime = gettime();
killCamEnt thread deleteAfterTime( 15.0 );
killCamEnt.angles = planedir;
killCamEnt moveTo( pathEnd + (0,0,100), flyTime, 0, 0 );
/#
if ( getdvar("scr_airstrikedebug") == "1" )
bomb thread traceBomb();
#/
wait .4;
//plane stoploopsound();
killCamEnt moveTo( killCamEnt.origin + planedir * 4000, 1, 0, 0 );
wait .45;
killCamEnt moveTo( killCamEnt.origin + (planedir + (0,0,-.2)) * 3500, 2, 0, 0 );
wait ( 0.15 );
newBomb = spawn( "script_model", bomb.origin );
newBomb setModel( "tag_origin" );
newBomb.origin = bomb.origin;
newBomb.angles = bomb.angles;
bomb setModel( "tag_origin" );
wait (0.10); // wait two server frames before playing fx
bombOrigin = newBomb.origin;
bombAngles = newBomb.angles;
playfxontag( level.airstrikefx, newBomb, "tag_origin" );
wait .05;
killCamEnt moveTo( killCamEnt.origin + (planedir + (0,0,-.25)) * 2500, 2, 0, 0 );
wait .25;
killCamEnt moveTo( killCamEnt.origin + (planedir + (0,0,-.35)) * 2000, 2, 0, 0 );
wait .2;
killCamEnt moveTo( killCamEnt.origin + (planedir + (0,0,-.45)) * 1500, 2, 0, 0 );
wait ( 0.5 );
repeat = 12;
minAngles = 5;
maxAngles = 55;
angleDiff = (maxAngles - minAngles) / repeat;
hitpos = (0,0,0);
for( i = 0; i < repeat; i++ )
{
traceDir = anglesToForward( bombAngles + (maxAngles-(angleDiff * i),randomInt( 10 )-5,0) );
traceEnd = bombOrigin + vector_multiply( traceDir, 10000 );
trace = bulletTrace( bombOrigin, traceEnd, false, undefined );
traceHit = trace["position"];
hitpos += traceHit;
/#
if ( getdvar("scr_airstrikedebug") == "1" )
thread airstrikeLine( bombOrigin, traceHit, (1,0,0), 40 );
#/
thread losRadiusDamage( traceHit + (0,0,16), 512, 200, 30, owner, bomb, "artillery_mp" ); // targetpos, radius, maxdamage, mindamage, player causing damage, entity that player used to cause damage
if ( i%3 == 0 )
{
thread playsoundinspace( "exp_airstrike_bomb", traceHit );
playRumbleOnPosition( "artillery_rumble", traceHit );
earthquake( 0.7, 0.75, traceHit, 1000 );
}
wait ( 0.05 );
}
hitpos = hitpos / repeat + (0,0,128);
killCamEnt moveto( bomb.killCamEnt.origin * .35 + hitpos * .65, 1.5, 0, .5 );
wait ( 5.0 );
newBomb delete();
bomb delete();
}
spawnbomb( origin, angles )
{
bomb = spawn( "script_model", origin );
bomb.angles = angles;
bomb setModel( "projectile_cbu97_clusterbomb" );
return bomb;
}
deleteAfterTime( time )
{
self endon ( "death" );
wait ( 10.0 );
self delete();
}
playPlaneFx()
{
self endon ( "death" );
wait( 0.5);
playfxontag( level.fx_airstrike_afterburner, self, "tag_engine_right" );
wait( 0.5);
playfxontag( level.fx_airstrike_afterburner, self, "tag_engine_left" );
wait( 0.5);
playfxontag( level.fx_airstrike_contrail, self, "tag_right_wingtip" );
wait( 0.5);
playfxontag( level.fx_airstrike_contrail, self, "tag_left_wingtip" );
}
callStrike( lifeId, owner, coord, yaw )
{
heightEnt = undefined;
planeBombExplodeDistance = 0;
// Get starting and ending point for the plane
direction = ( 0, yaw, 0 );
heightEnt = GetEnt( "airstrikeheight", "targetname" );
if ( self.airStrikeType == "stealth" )
{
thread teamPlayerCardSplash( "used_stealth_airstrike", owner, owner.team );
planeHalfDistance = 12000;
planeFlySpeed = 2000;
if ( !isDefined( heightEnt ) )//old system
{
println( "NO DEFINED AIRSTRIKE HEIGHT SCRIPT_ORIGIN IN LEVEL" );
planeFlyHeight = 950;
planeBombExplodeDistance = 1500;
if ( isdefined( level.airstrikeHeightScale ) )
planeFlyHeight *= level.airstrikeHeightScale;
}
else
{
planeFlyHeight = heightEnt.origin[2];
planeBombExplodeDistance = getExplodeDistance( planeFlyHeight );
}
}
else
{
planeHalfDistance = 24000;
planeFlySpeed = 7000;
if ( !isDefined( heightEnt ) )//old system
{
println( "NO DEFINED AIRSTRIKE HEIGHT SCRIPT_ORIGIN IN LEVEL" );
planeFlyHeight = 850;
planeBombExplodeDistance = 1500;
if ( isdefined( level.airstrikeHeightScale ) )
planeFlyHeight *= level.airstrikeHeightScale;
}
else
{
planeFlyHeight = heightEnt.origin[2];
planeBombExplodeDistance = getExplodeDistance( planeFlyHeight );
}
}
startPoint = coord + vector_multiply( anglestoforward( direction ), -1 * planeHalfDistance );
if ( isDefined( heightEnt ) )// used in the new height system
startPoint *= (1,1,0);
startPoint += ( 0, 0, planeFlyHeight );
if ( self.airStrikeType == "stealth" )
endPoint = coord + vector_multiply( anglestoforward( direction ), planeHalfDistance*4 );
else
endPoint = coord + vector_multiply( anglestoforward( direction ), planeHalfDistance );
if ( isDefined( heightEnt ) )// used in the new height system
endPoint *= (1,1,0);
endPoint += ( 0, 0, planeFlyHeight );
// Make the plane fly by
d = length( startPoint - endPoint );
flyTime = ( d / planeFlySpeed );
// bomb explodes planeBombExplodeDistance after the plane passes the center
d = abs( d/2 + planeBombExplodeDistance );
bombTime = ( d / planeFlySpeed );
assert( flyTime > bombTime );
owner endon("disconnect");
requiredDeathCount = lifeId;
level.airstrikeDamagedEnts = [];
level.airStrikeDamagedEntsCount = 0;
level.airStrikeDamagedEntsIndex = 0;
if ( self.airStrikeType == "harrier" )
{
level thread doPlaneStrike( lifeId, owner, requiredDeathCount, coord, startPoint+(0,0,randomInt(500)), endPoint+(0,0,randomInt(500)), bombTime, flyTime, direction, self.airStrikeType );
wait randomfloatrange( 1.5, 2.5 );
maps\mp\gametypes\_hostmigration::waitTillHostMigrationDone();
level thread doPlaneStrike( lifeId, owner, requiredDeathCount, coord, startPoint+(0,0,randomInt(200)), endPoint+(0,0,randomInt(200)), bombTime, flyTime, direction, self.airStrikeType );
wait randomfloatrange( 1.5, 2.5 );
maps\mp\gametypes\_hostmigration::waitTillHostMigrationDone();
harrier = beginHarrier( lifeId, startPoint, coord );
owner thread defendLocation( harrier );
return harrier;
//owner thread harrierMissileStrike( startPoint, coord );
}
else if ( self.airStrikeType == "stealth" )
{
level thread doBomberStrike( lifeId, owner, requiredDeathCount, coord, startPoint+(0,0,randomInt(1000)), endPoint+(0,0,randomInt(1000)), bombTime, flyTime, direction, self.airStrikeType );
}
else //common airstrike
{
level thread doPlaneStrike( lifeId, owner, requiredDeathCount, coord, startPoint+(0,0,randomInt(500)), endPoint+(0,0,randomInt(500)), bombTime, flyTime, direction, self.airStrikeType );
wait randomfloatrange( 1.5, 2.5 );
maps\mp\gametypes\_hostmigration::waitTillHostMigrationDone();
level thread doPlaneStrike( lifeId, owner, requiredDeathCount, coord, startPoint+(0,0,randomInt(200)), endPoint+(0,0,randomInt(200)), bombTime, flyTime, direction, self.airStrikeType );
wait randomfloatrange( 1.5, 2.5 );
maps\mp\gametypes\_hostmigration::waitTillHostMigrationDone();
level thread doPlaneStrike( lifeId, owner, requiredDeathCount, coord, startPoint+(0,0,randomInt(200)), endPoint+(0,0,randomInt(200)), bombTime, flyTime, direction, self.airStrikeType );
if ( self.airStrikeType == "super" )
{
wait randomfloatrange( 2.5, 3.5 );
maps\mp\gametypes\_hostmigration::waitTillHostMigrationDone();
level thread doPlaneStrike( lifeId, owner, requiredDeathCount, coord, startPoint+(0,0,randomInt(200)), endPoint+(0,0,randomInt(200)), bombTime, flyTime, direction, self.airStrikeType );
}
}
}
getExplodeDistance( height )
{
standardHeight = 850;
standardDistance = 1500;
distanceFrac = standardHeight/height;
newDistance = distanceFrac * standardDistance;
return newDistance;
}
targetGetDist( other, target )
{
infront = targetisinfront( other, target );
if( infront )
dir = 1;
else
dir = -1;
a = flat_origin( other.origin );
b = a+vector_multiply( anglestoforward(flat_angle(other.angles)), (dir*100000) );
point = pointOnSegmentNearestToPoint(a,b, target);
dist = distance(a,point);
return dist;
}
targetisclose(other, target, closeDist)
{
if ( !isDefined( closeDist ) )
closeDist = 3000;
infront = targetisinfront(other, target);
if(infront)
dir = 1;
else
dir = -1;
a = flat_origin(other.origin);
b = a+vector_multiply(anglestoforward(flat_angle(other.angles)), (dir*100000));
point = pointOnSegmentNearestToPoint(a,b, target);
dist = distance(a,point);
if (dist < closeDist)
return true;
else
return false;
}
targetisinfront(other, target)
{
forwardvec = anglestoforward(flat_angle(other.angles));
normalvec = vectorNormalize(flat_origin(target)-other.origin);
dot = vectordot(forwardvec,normalvec);
if(dot > 0)
return true;
else
return false;
}
waitForAirstrikeCancel()
{
self waittill( "cancel_location" );
self setblurforplayer( 0, 0.3 );
}
selectAirstrikeLocation( lifeId, airStrikeType )
{
assert( isDefined( airStrikeType ) );
self.airStrikeType = airStrikeType;
if ( airStrikeType == "precision" || airStrikeType == "stealth" )
chooseDirection = true;
else
chooseDirection = false;
targetSize = level.mapSize / 5.625; // 138 in 720
if ( level.splitscreen )
targetSize *= 1.5;
self beginLocationSelection( "map_artillery_selector", chooseDirection, targetSize );
self.selectingLocation = true;
self setblurforplayer( 4.0, 0.3 );
self thread waitForAirstrikeCancel();
self thread endSelectionOn( "cancel_location" );
self thread endSelectionOn( "death" );
self thread endSelectionOn( "disconnect" );
self thread endSelectionOn( "used" ); // so that this thread doesn't kill itself when we use an airstrike
self thread endSelectionOnGameEnd();
self thread endSelectionOnEMP();
self endon( "stop_location_selection" );
// wait for the selection. randomize the yaw if we're not doing a precision airstrike.
self waittill( "confirm_location", location, directionYaw );
if ( !chooseDirection )
directionYaw = randomint(360);
self setblurforplayer( 0, 0.3 );
if ( airStrikeType == "harrier" && level.planes > 1 )
{
self notify ( "cancel_location" );
self iPrintLnBold( &"MP_AIR_SPACE_TOO_CROWDED" );
return false;
}
self thread finishAirstrikeUsage( lifeId, location, directionYaw );
return true;
}
finishAirstrikeUsage( lifeId, location, directionYaw )
{
self notify( "used" );
// find underside of top of skybox
trace = bullettrace( level.mapCenter + (0,0,1000000), level.mapCenter, false, undefined );
location = (location[0], location[1], trace["position"][2] - 514);
thread doAirstrike( lifeId, location, directionYaw, self, self.pers["team"] );
}
endSelectionOn( waitfor )
{
self endon( "stop_location_selection" );
self waittill( waitfor );
self thread stopAirstrikeLocationSelection( (waitfor == "disconnect") );
}
endSelectionOnGameEnd()
{
self endon( "stop_location_selection" );
level waittill( "game_ended" );
self thread stopAirstrikeLocationSelection( false );
}
endSelectionOnEMP()
{
self endon( "stop_location_selection" );
for ( ;; )
{
level waittill( "emp_update" );
if ( !self isEMPed() )
continue;
self thread stopAirstrikeLocationSelection( false );
return;
}
}
stopAirstrikeLocationSelection( disconnected )
{
if ( !disconnected )
{
self setblurforplayer( 0, 0.3 );
self endLocationSelection();
self.selectingLocation = undefined;
}
self notify( "stop_location_selection" );
}
useAirstrike( lifeId, pos, yaw )
{
}
handleEMP( owner )
{
self endon ( "death" );
if ( owner isEMPed() )
{
playFxOnTag( level.onfirefx, self, "tag_engine_right" );
playFxOnTag( level.onfirefx, self, "tag_engine_left" );
return;
}
for ( ;; )
{
level waittill ( "emp_update" );
if ( !owner isEMPed() )
continue;
playFxOnTag( level.onfirefx, self, "tag_engine_right" );
playFxOnTag( level.onfirefx, self, "tag_engine_left" );
}
} | 0 | 0.928872 | 1 | 0.928872 | game-dev | MEDIA | 0.99334 | game-dev | 0.879061 | 1 | 0.879061 |
ProjectIgnis/CardScripts | 2,699 | official/c60551528.lua | --インフェルノイド・シャイターン
--Infernoid Pirmais
local s,id=GetID()
function s.initial_effect(c)
c:EnableReviveLimit()
Infernoid.RegisterSummonProcedure(c,1)
--Return 1 Spell/Trap to the deck
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_TODECK)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_MZONE)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCountLimit(1)
e1:SetTarget(s.tdtg)
e1:SetOperation(s.tdop)
c:RegisterEffect(e1)
--Tribute 1 monster and banish
local e2=Effect.CreateEffect(c)
e2:SetCategory(CATEGORY_REMOVE)
e2:SetType(EFFECT_TYPE_QUICK_O)
e2:SetCode(EVENT_FREE_CHAIN)
e2:SetRange(LOCATION_MZONE)
e2:SetProperty(EFFECT_FLAG_CARD_TARGET)
e2:SetCountLimit(1)
e2:SetCondition(function(_,tp) return Duel.IsTurnPlayer(1-tp) end)
e2:SetCost(s.rmcost)
e2:SetTarget(s.rmtg)
e2:SetOperation(s.rmop)
c:RegisterEffect(e2)
end
s.listed_series={SET_INFERNOID}
function s.tdfilter(c)
return c:IsFacedown() and c:IsAbleToDeck()
end
function s.tdtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsOnField() and s.tdfilter(chkc) end
if chk==0 then return Duel.IsExistingTarget(s.tdfilter,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TODECK)
local g=Duel.SelectTarget(tp,s.tdfilter,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_TODECK,g,1,0,0)
local tc=g:GetFirst()
Duel.SetChainLimit(function(e,lp,tp) return e:GetHandler()~=tc end)
end
function s.tdop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.SendtoDeck(tc,nil,SEQ_DECKSHUFFLE,REASON_EFFECT)
end
end
function s.rmfilter(c,e)
return c:IsAbleToRemove() and aux.SpElimFilter(c) and (not e or c:IsCanBeEffectTarget(e))
end
function s.rmcost(e,tp,eg,ep,ev,re,r,rp,chk)
local dg=Duel.GetMatchingGroup(s.rmfilter,tp,0,LOCATION_MZONE|LOCATION_GRAVE,nil,e)
if chk==0 then return Duel.CheckReleaseGroupCost(tp,nil,1,false,aux.ReleaseCheckTarget,nil,dg) end
local g=Duel.SelectReleaseGroupCost(tp,nil,1,1,false,aux.ReleaseCheckTarget,nil,dg)
Duel.Release(g,REASON_COST)
end
function s.rmtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE|LOCATION_GRAVE) and chkc:IsControler(1-tp) and s.rmfilter(chkc) end
if chk==0 then return Duel.IsExistingTarget(s.rmfilter,tp,0,LOCATION_MZONE|LOCATION_GRAVE,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local g=Duel.SelectTarget(tp,s.rmfilter,tp,0,LOCATION_MZONE|LOCATION_GRAVE,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_REMOVE,g,1,0,0)
end
function s.rmop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.Remove(tc,POS_FACEUP,REASON_EFFECT)
end
end | 0 | 0.911615 | 1 | 0.911615 | game-dev | MEDIA | 0.976655 | game-dev | 0.949532 | 1 | 0.949532 |
oot-pc-port/oot-pc-port | 4,422 | asm/non_matchings/overlays/actors/ovl_En_Cow/func_809DEE9C.s | glabel func_809DEE9C
/* 0009C 809DEE9C 44800000 */ mtc1 $zero, $f0 ## $f0 = 0.00
/* 000A0 809DEEA0 27BDFFD8 */ addiu $sp, $sp, 0xFFD8 ## $sp = FFFFFFD8
/* 000A4 809DEEA4 3C0141F0 */ lui $at, 0x41F0 ## $at = 41F00000
/* 000A8 809DEEA8 44812000 */ mtc1 $at, $f4 ## $f4 = 30.00
/* 000AC 809DEEAC AFBF0014 */ sw $ra, 0x0014($sp)
/* 000B0 809DEEB0 00803025 */ or $a2, $a0, $zero ## $a2 = 00000000
/* 000B4 809DEEB4 E7A00020 */ swc1 $f0, 0x0020($sp)
/* 000B8 809DEEB8 E7A0001C */ swc1 $f0, 0x001C($sp)
/* 000BC 809DEEBC E7A40024 */ swc1 $f4, 0x0024($sp)
/* 000C0 809DEEC0 84C500B6 */ lh $a1, 0x00B6($a2) ## 000000B6
/* 000C4 809DEEC4 AFA60028 */ sw $a2, 0x0028($sp)
/* 000C8 809DEEC8 0C277B80 */ jal func_809DEE00
/* 000CC 809DEECC 27A4001C */ addiu $a0, $sp, 0x001C ## $a0 = FFFFFFF4
/* 000D0 809DEED0 8FA60028 */ lw $a2, 0x0028($sp)
/* 000D4 809DEED4 C7A8001C */ lwc1 $f8, 0x001C($sp)
/* 000D8 809DEED8 44800000 */ mtc1 $zero, $f0 ## $f0 = 0.00
/* 000DC 809DEEDC C4C60024 */ lwc1 $f6, 0x0024($a2) ## 00000024
/* 000E0 809DEEE0 C4D20028 */ lwc1 $f18, 0x0028($a2) ## 00000028
/* 000E4 809DEEE4 3C01C1A0 */ lui $at, 0xC1A0 ## $at = C1A00000
/* 000E8 809DEEE8 46083280 */ add.s $f10, $f6, $f8
/* 000EC 809DEEEC C4C6002C */ lwc1 $f6, 0x002C($a2) ## 0000002C
/* 000F0 809DEEF0 27A4001C */ addiu $a0, $sp, 0x001C ## $a0 = FFFFFFF4
/* 000F4 809DEEF4 4600910D */ trunc.w.s $f4, $f18
/* 000F8 809DEEF8 44819000 */ mtc1 $at, $f18 ## $f18 = -20.00
/* 000FC 809DEEFC 4600540D */ trunc.w.s $f16, $f10
/* 00100 809DEF00 44192000 */ mfc1 $t9, $f4
/* 00104 809DEF04 440F8000 */ mfc1 $t7, $f16
/* 00108 809DEF08 A4D90194 */ sh $t9, 0x0194($a2) ## 00000194
/* 0010C 809DEF0C A4CF0192 */ sh $t7, 0x0192($a2) ## 00000192
/* 00110 809DEF10 C7A80024 */ lwc1 $f8, 0x0024($sp)
/* 00114 809DEF14 46083280 */ add.s $f10, $f6, $f8
/* 00118 809DEF18 4600540D */ trunc.w.s $f16, $f10
/* 0011C 809DEF1C 44098000 */ mfc1 $t1, $f16
/* 00120 809DEF20 00000000 */ nop
/* 00124 809DEF24 A4C90196 */ sh $t1, 0x0196($a2) ## 00000196
/* 00128 809DEF28 E7A0001C */ swc1 $f0, 0x001C($sp)
/* 0012C 809DEF2C E7A00020 */ swc1 $f0, 0x0020($sp)
/* 00130 809DEF30 E7B20024 */ swc1 $f18, 0x0024($sp)
/* 00134 809DEF34 0C277B80 */ jal func_809DEE00
/* 00138 809DEF38 84C500B6 */ lh $a1, 0x00B6($a2) ## 000000B6
/* 0013C 809DEF3C 8FA60028 */ lw $a2, 0x0028($sp)
/* 00140 809DEF40 C7A6001C */ lwc1 $f6, 0x001C($sp)
/* 00144 809DEF44 C4C40024 */ lwc1 $f4, 0x0024($a2) ## 00000024
/* 00148 809DEF48 C4D00028 */ lwc1 $f16, 0x0028($a2) ## 00000028
/* 0014C 809DEF4C 46062200 */ add.s $f8, $f4, $f6
/* 00150 809DEF50 C4C4002C */ lwc1 $f4, 0x002C($a2) ## 0000002C
/* 00154 809DEF54 4600848D */ trunc.w.s $f18, $f16
/* 00158 809DEF58 4600428D */ trunc.w.s $f10, $f8
/* 0015C 809DEF5C 440D9000 */ mfc1 $t5, $f18
/* 00160 809DEF60 440B5000 */ mfc1 $t3, $f10
/* 00164 809DEF64 A4CD01E0 */ sh $t5, 0x01E0($a2) ## 000001E0
/* 00168 809DEF68 A4CB01DE */ sh $t3, 0x01DE($a2) ## 000001DE
/* 0016C 809DEF6C C7A60024 */ lwc1 $f6, 0x0024($sp)
/* 00170 809DEF70 46062200 */ add.s $f8, $f4, $f6
/* 00174 809DEF74 4600428D */ trunc.w.s $f10, $f8
/* 00178 809DEF78 440F5000 */ mfc1 $t7, $f10
/* 0017C 809DEF7C 00000000 */ nop
/* 00180 809DEF80 A4CF01E2 */ sh $t7, 0x01E2($a2) ## 000001E2
/* 00184 809DEF84 8FBF0014 */ lw $ra, 0x0014($sp)
/* 00188 809DEF88 27BD0028 */ addiu $sp, $sp, 0x0028 ## $sp = 00000000
/* 0018C 809DEF8C 03E00008 */ jr $ra
/* 00190 809DEF90 00000000 */ nop
| 0 | 0.821781 | 1 | 0.821781 | game-dev | MEDIA | 0.687316 | game-dev | 0.692885 | 1 | 0.692885 |
databasedav/jonmo | 1,468 | src/utils.rs | use bevy_ecs::prelude::*;
use bevy_platform::sync::{Arc, OnceLock};
#[doc(no_inline)]
pub use enclose::enclose as clone;
/// A deferred, thread-safe, clone-able handle to an [`Entity`]. Useful when the existence of an
/// entity is known at compile time but it can't be referenced until after it's spawned, e.g. in the
/// bodies of systems.
#[derive(Default, Clone)]
pub struct LazyEntity(Arc<OnceLock<Entity>>);
impl LazyEntity {
#[allow(missing_docs)]
pub fn new() -> Self {
Self::default()
}
/// Set the [`Entity`], panicking if it was already set.
pub fn set(&self, entity: Entity) {
self.0.set(entity).expect("EntityHolder already contains an Entity");
}
/// Get the [`Entity`], panicking if it was not set.
pub fn get(&self) -> Entity {
self.0.get().copied().expect("EntityHolder does not contain an Entity")
}
}
pub(crate) fn get_ancestor(child_ofs: &Query<&ChildOf>, entity: Entity, generations: usize) -> Option<Entity> {
[entity]
.into_iter()
.chain(child_ofs.iter_ancestors(entity))
.nth(generations)
}
pub(crate) fn ancestor_map(generations: usize) -> impl Fn(In<Entity>, Query<&ChildOf>) -> Option<Entity> {
move |In(entity): In<Entity>, child_ofs: Query<&ChildOf>| get_ancestor(&child_ofs, entity, generations)
}
/// Convenience trait for [`Send`] + [`Sync`] + 'static.
pub trait SSs: Send + Sync + 'static {}
impl<T: Send + Sync + 'static> SSs for T {}
| 0 | 0.878221 | 1 | 0.878221 | game-dev | MEDIA | 0.721459 | game-dev | 0.930806 | 1 | 0.930806 |
demilich1/metastone | 1,266 | game/src/main/java/net/demilich/metastone/game/spells/DoubleAttackSpell.java | package net.demilich.metastone.game.spells;
import java.util.Map;
import net.demilich.metastone.game.Attribute;
import net.demilich.metastone.game.GameContext;
import net.demilich.metastone.game.Player;
import net.demilich.metastone.game.entities.Actor;
import net.demilich.metastone.game.entities.Entity;
import net.demilich.metastone.game.spells.desc.SpellArg;
import net.demilich.metastone.game.spells.desc.SpellDesc;
import net.demilich.metastone.game.targeting.EntityReference;
public class DoubleAttackSpell extends Spell {
public static SpellDesc create() {
return create(null);
}
public static SpellDesc create(EntityReference target) {
Map<SpellArg, Object> arguments = SpellDesc.build(DoubleAttackSpell.class);
arguments.put(SpellArg.TARGET, target);
return new SpellDesc(arguments);
}
@Override
protected void onCast(GameContext context, Player player, SpellDesc desc, Entity source, Entity target) {
Actor targetActor = (Actor) target;
targetActor.modifyAttribute(Attribute.ATTACK_BONUS, targetActor.getAttributeValue(Attribute.ATTACK) + targetActor.getAttributeValue(Attribute.ATTACK_BONUS));
targetActor.modifyAttribute(Attribute.TEMPORARY_ATTACK_BONUS, targetActor.getAttributeValue(Attribute.TEMPORARY_ATTACK_BONUS));
}
}
| 0 | 0.674693 | 1 | 0.674693 | game-dev | MEDIA | 0.917151 | game-dev | 0.792521 | 1 | 0.792521 |
thlsrms/tictactoe-stdb-bevy | 4,717 | server/src/game_table.rs | use spacetimedb::{client_visibility_filter, Filter, Identity, ReducerContext, Table};
use crate::game_turn_scheduler::set_turn_expiration_schedule;
use crate::types::{GameState, Player};
// RLS
#[client_visibility_filter]
const GAME_ACCESS_FILTER: Filter =
Filter::Sql("SELECT * FROM game WHERE x_player = :sender OR o_player = :sender");
#[spacetimedb::table(name = game, public)]
#[derive(Clone)]
pub struct Game {
#[primary_key]
pub id: String, // Investigate the possibility to use GameId with FilterableValue
pub x_player: Identity,
pub o_player: Identity,
pub turn_owner: Player,
pub x_mask: u16,
pub o_mask: u16,
pub state: GameState,
pub turn: u8,
pub time_expired: bool,
}
#[spacetimedb::reducer]
pub fn mark_cell(ctx: &ReducerContext, game_id: String, cell: u16) -> Result<(), String> {
let Some(mut game) = ctx.db.game().id().find(game_id.clone()) else {
return Err("Invalid Game '{game_id}'".to_string());
};
if !game.game_in_progress() {
return Err("Game '{game_id}' not in progress.".to_string());
}
if !game.validate_turn_owner(ctx.sender) {
return Err("Not your turn".to_string());
}
game.toggle_cell(cell)?;
game.result_or_next_turn();
// Schedule Turn Expiration
set_turn_expiration_schedule(ctx, game_id, game.turn);
ctx.db.game().id().update(game);
Ok(())
}
#[spacetimedb::reducer]
pub fn leave_game(ctx: &ReducerContext, game_id: String) {
let Some(game) = ctx.db.game().id().find(game_id) else {
return;
};
if (ctx.sender == game.x_player) || (ctx.sender == game.o_player) {
ctx.db.game().delete(game);
}
}
impl Game {
pub fn new(x_player: Identity, o_player: Identity, id: String) -> Self {
Self {
id,
x_player,
o_player,
turn_owner: Player::X,
x_mask: 0,
o_mask: 0,
state: GameState::InProgress,
turn: 0,
time_expired: false,
}
}
pub fn game_in_progress(&self) -> bool {
// GameState InProgress
matches!(self.state, GameState::InProgress)
}
pub fn validate_turn_owner(&self, player: Identity) -> bool {
match self.turn_owner {
Player::X => self.x_player == player,
Player::O => self.o_player == player,
}
}
pub fn result_or_next_turn(&mut self) {
/*
* Bitboard:
* Map each board cell to one of nine bits (positions 0 to 8):
* (0,0) -> bit 0, (1,0) -> bit 1, (2,0) -> bit 2, (0,1) -> bit 3, ..., (2,2) -> bit 8.
*/
const WINNING_MASKS: [u16; 8] = [
0b000_000_111, // row 0
0b000_111_000, // row 1
0b111_000_000, // row 2
0b001_001_001, // col 0
0b010_010_010, // col 1
0b100_100_100, // col 2
0b100_010_001, // main diagonal
0b001_010_100, // anti-diagonal
];
let curr_player_cells = match self.turn_owner {
Player::X => self.x_mask,
Player::O => self.o_mask,
};
let mut any_open = false;
for &mask in WINNING_MASKS.iter() {
// Check for a win on this mask
if (curr_player_cells & mask) == mask {
self.state = GameState::Winner(self.turn_owner);
return;
}
// Check if the line is not yet fully blocked (i.e. it's still open for a win)
// Note: We use logical OR so that once any_open is true, it stays true.
any_open |= !((mask & self.x_mask != 0) && (mask & self.o_mask != 0));
}
if any_open {
self.next_turn();
} else {
// Every mask is blocked, it's a draw.
self.state = GameState::Draw;
}
}
fn next_turn(&mut self) {
self.time_expired = false;
self.turn_owner = match self.turn_owner {
Player::X => Player::O,
Player::O => Player::X,
};
self.turn += 1;
}
pub fn turn_expired(&mut self) {
self.turn_owner = match self.turn_owner {
Player::X => Player::O,
Player::O => Player::X,
};
self.time_expired = true;
}
pub fn toggle_cell(&mut self, cell: u16) -> Result<(), String> {
// Check if cell if free
if !((self.x_mask & cell == 0) && (self.o_mask & cell == 0)) {
return Err("Cell already taken".to_string());
}
match self.turn_owner {
Player::X => self.x_mask |= cell,
Player::O => self.o_mask |= cell,
};
Ok(())
}
}
| 0 | 0.877748 | 1 | 0.877748 | game-dev | MEDIA | 0.653651 | game-dev,web-backend | 0.95793 | 1 | 0.95793 |
Dimbreath/AzurLaneData | 2,228 | ko-KR/view/level/cell/enemyspinecellview.lua | slot0 = class("EnemySpineCellView", import("view.level.cell.EnemyEggCellView"))
function slot0.Ctor(slot0, slot1)
uv0.super.Ctor(slot0, slot1)
end
slot0.buffheight = 220
function slot0.Update(slot0)
slot1 = slot0.info
slot2 = slot0.config
slot3 = slot1.row
slot4 = slot1.column
if slot1.attachment == ChapterConst.AttachAmbush and slot1.flag == 2 then
-- Nothing
elseif slot1.flag == 0 then
if slot0:UpdateGO(slot0._aliveTpl) then
slot0.tf.anchoredPosition = Vector2(0, 0)
SetActive(findTF(slot0.tf, "icon"), false)
slot6 = findTF(slot0.tf, "titleContain/bg_boss")
slot6.localScale = Vector3(0.5, 0.5, 1)
slot6.anchoredPosition = Vector2(61.1, -30.6)
slot0:GetLoader():GetSpine(slot2.icon, function (slot0)
slot1 = uv0.scale * 0.01
slot0.transform.localScale = Vector3(0.4 * slot1, 0.4 * slot1, 1)
slot0.transform:GetComponent("SpineAnimUI"):SetAction(ChapterConst.ShipIdleAction, 0)
slot0.transform:GetComponent("SkeletonGraphic").raycastTarget = false
slot0.transform:SetParent(uv1.tf, false)
slot0.transform:SetAsFirstSibling()
end, "LoadedSpine")
slot0:ExtraUpdate(slot2)
end
setActive(findTF(slot0.tf, slot1.attachment == ChapterConst.AttachBoss and "effect_found_boss" or "effect_found"), slot1.trait == ChapterConst.TraitVirgin)
if slot1.trait == ChapterConst.TraitVirgin then
pg.CriMgr.GetInstance():PlaySoundEffect_V3(SFX_UI_WEIGHANCHOR_ENEMY)
end
setActive(findTF(slot0.tf, "fighting"), slot0.chapter:existFleet(FleetType.Normal, slot3, slot4))
setActive(findTF(slot0.tf, "damage_count"), slot1.data > 0)
elseif slot1.flag == 1 and slot0:UpdateGO(slot0._deadTpl) and slot1.attachment ~= ChapterConst.AttachAmbush then
setActive(slot0.tf:Find("huoqiubaozha"), slot0._live2death)
slot0._live2death = nil
end
end
function slot0.ReturnSpine(slot0)
if slot0.loader then
slot0.loader:ClearRequest("LoadedSpine")
end
end
function slot0.DestroyGO(slot0)
slot0:ReturnSpine()
uv0.super.DestroyGO(slot0)
end
function slot0.Clear(slot0)
if not IsNil(findTF(slot0.tf, "titleContain/bg_boss")) then
slot1.localScale = Vector3.one
slot1.anchoredPosition = Vector2(39.5, -23.2)
end
uv0.super.Clear(slot0)
end
return slot0
| 0 | 0.79317 | 1 | 0.79317 | game-dev | MEDIA | 0.978916 | game-dev | 0.964033 | 1 | 0.964033 |
Decencies/CheatBreaker | 2,368 | CheatBreaker/src/main/java/net/minecraft/src/ReflectorConstructor.java | package net.minecraft.src;
import java.lang.reflect.Constructor;
public class ReflectorConstructor
{
private ReflectorClass reflectorClass = null;
private Class[] parameterTypes = null;
private boolean checked = false;
private Constructor targetConstructor = null;
public ReflectorConstructor(ReflectorClass reflectorClass, Class[] parameterTypes)
{
this.reflectorClass = reflectorClass;
this.parameterTypes = parameterTypes;
Constructor c = this.getTargetConstructor();
}
public Constructor getTargetConstructor()
{
if (this.checked)
{
return this.targetConstructor;
}
else
{
this.checked = true;
Class cls = this.reflectorClass.getTargetClass();
if (cls == null)
{
return null;
}
else
{
try
{
this.targetConstructor = findConstructor(cls, this.parameterTypes);
if (this.targetConstructor == null)
{
Config.dbg("(Reflector) Constructor not present: " + cls.getName() + ", params: " + Config.arrayToString((Object[])this.parameterTypes));
}
if (this.targetConstructor != null)
{
this.targetConstructor.setAccessible(true);
}
}
catch (Throwable var3)
{
var3.printStackTrace();
}
return this.targetConstructor;
}
}
}
private static Constructor findConstructor(Class cls, Class[] paramTypes)
{
Constructor[] cs = cls.getDeclaredConstructors();
for (int i = 0; i < cs.length; ++i)
{
Constructor c = cs[i];
Class[] types = c.getParameterTypes();
if (Reflector.matchesTypes(paramTypes, types))
{
return c;
}
}
return null;
}
public boolean exists()
{
return this.checked ? this.targetConstructor != null : this.getTargetConstructor() != null;
}
public void deactivate()
{
this.checked = true;
this.targetConstructor = null;
}
}
| 0 | 0.657757 | 1 | 0.657757 | game-dev | MEDIA | 0.372197 | game-dev | 0.867938 | 1 | 0.867938 |
cocos2d-x/plugin-x | 13,701 | samples/HelloPluginsLua/src/TestFBShareScene.lua | local visibleSize = cc.Director:getInstance():getVisibleSize()
local origin = cc.Director:getInstance():getVisibleOrigin()
local posBR = cc.p(origin.x + visibleSize.width, origin.y)
local TestFBShareScene = class("TestFBShareScene",function()
return cc.Scene:create()
end)
function TestFBShareScene.create()
local scene = TestFBShareScene.new()
return scene
end
function TestFBShareScene:ctor()
local title = cc.Label:createWithSystemFont("Test Facebook share", "Arial", 32)
title:setPosition(origin.x + visibleSize.width / 2, origin.y + visibleSize.height - 50)
self:addChild(title)
local sdkVersion = "SDK Version is: " .. plugin.FacebookAgent:getInstance():getSDKVersion()
local subTitle = cc.Label:createWithSystemFont(sdkVersion, "Arial", 12)
subTitle:setPosition(origin.x + visibleSize.width / 2, origin.y + visibleSize.height - 74)
self:addChild(subTitle)
self:createLayerMenu()
end
function TestFBShareScene:sceenshot(filename)
local visibleSize = cc.Director:getInstance():getVisibleSize()
local origin = cc.Director:getInstance():getVisibleOrigin()
local tex = cc.RenderTexture:create(visibleSize.width, visibleSize.height, cc.TEXTURE2_D_PIXEL_FORMAT_RGB_A8888)
tex:setPosition((origin.x + visibleSize.width) / 2, (origin.y + visibleSize.height) / 2)
tex:begin()
cc.Director:getInstance():getRunningScene():visit()
tex:endToLua()
local imgPath = cc.FileUtils:getInstance():getWritablePath()
if imgPath == "" then
return ""
end
local ret = tex:saveToFile(filename, cc.IMAGE_FORMAT_JPEG)
if ret then
imgPath = imgPath .. filename
print(string.format("save image to %s", imgPath))
return imgPath
end
return ""
end
local secondMenuItem_SL = {
{"share a simple link", function(tag, sender)
local params = {
dialog = "share_link",
link = "http://www.cocos2d-x.org",
}
if plugin.FacebookAgent:getInstance():canPresentDialogWithParams(params) then
plugin.FacebookAgent:getInstance():dialog(params, function(ret, msg)
print(msg)
end)
else
params.dialog = "feed_dialog"
plugin.FacebookAgent:getInstance():dialog(params, function(ret, msg)
print(msg)
end)
end
end},
{"share a Text link", function(tag, sender)
local params = {
dialog = "share_link",
name = "Cocos2dx-lua web site",
caption = "Cocos2dx-lua caption",
description = "Cocos2dx-lua description",
link = "http://www.cocos2d-x.org",
}
if plugin.FacebookAgent:getInstance():canPresentDialogWithParams(params) then
plugin.FacebookAgent:getInstance():dialog(params, function(ret, msg)
print(msg)
end)
else
params.dialog = "feed_dialog"
plugin.FacebookAgent:getInstance():dialog(params, function(ret, msg)
print(msg)
end)
end
end},
{"share a Picture link", function(tag, sender)
local params = {
dialog = "share_link",
name = "Cocos2dx-lua web site",
caption = "Cocos2dx-lua caption",
description = "Cocos2dx-lua description",
to = "100006738453912",--android only web view support
picture = "http://files.cocos2d-x.org/images/orgsite/logo.png",
link = "http://www.cocos2d-x.org",
}
if plugin.FacebookAgent:getInstance():canPresentDialogWithParams(params) then
plugin.FacebookAgent:getInstance():dialog(params, function(ret, msg)
print(msg)
end)
else
params.dialog = "feed_dialog"
plugin.FacebookAgent:getInstance():dialog(params, function(ret, msg)
print(msg)
end)
end
end},
{"share a media link", function(tag, sender)
local params = {
dialog = "share_link",
name = "Cocos2dx-lua web site",
caption = "Cocos2dx-lua caption",
description = "Cocos2dx-lua description",
media_source = "http://221.203.1.212/youku/6775B002C8F48839F6AFA63BDA/0300200100540438A173C515AA2BED245C4903-F675-B311-EF1A-4544B5C04370.mp4",
link = "http://www.cocos2d-x.org",
}
-- only support in web dialog
plugin.FacebookAgent:getInstance():dialog(params, function(ret, msg)
print(msg)
end)
end},
}
local secondMenuItem_AR = {
{"Invites request", function(tag, sender)
local params = {
message = "Cocos2dx-lua is a great game engine",
title = "Cocos2dx-lua title",
}
plugin.FacebookAgent:getInstance():appRequest(params, function(ret, msg)
print(msg)
end)
end},
{"Target invite request", function(tag, sender)
local params = {
message = "Cocos2dx-lua is a great game engine",
title = "Cocos2dx-lua title",
to = "100006738453912, 10204182777160522",
}
--android only web view support to
plugin.FacebookAgent:getInstance():appRequest(params, function(ret, msg)
print(msg)
end)
end},
{"Specific lists of friends", function(tag, sender)
local params = {
message = "Cocos2dx-lua is a great game engine",
title = "Cocos2dx-lua title",
filters = "[{\"name\":\"company\", \"user_ids\":[\"100006738453912\",\"10204182777160522\"]}]",
}
-- android not support filters
plugin.FacebookAgent:getInstance():appRequest(params, function(ret, msg)
print(msg)
end)
end},
{"Sending requests explicitly", function(tag, sender)
local params = {
message = "Cocos2dx-lua is a great game engine",
to = "100006738453912",
action_type = "send",
object_id = "191181717736427",-- 191181717736427 1426774790893461
}
--android not support action_type
plugin.FacebookAgent:getInstance():appRequest(params, function(ret, msg)
print(msg)
end)
end},
{"Turn-based games", function(tag, sender)
local params = {
message = "Cocos2dx-lua is a great game engine",
title = "Cocos2dx-lua title",
to = "100006738453912",
action_type = "turn",
}
-- android not support action_type
plugin.FacebookAgent:getInstance():appRequest(params, function(ret, msg)
print(msg)
end)
end},
}
function TestFBShareScene:showSecondMenu(tag)
local secondMenu = self:getChildByTag(2)
if nil ~= secondMenu then
local visibleSize = cc.Director:getInstance():getVisibleSize()
local origin = cc.Director:getInstance():getVisibleOrigin()
local posBR = cc.p(origin.x + visibleSize.width, origin.y)
secondMenu:removeAllChildren()
local top = 90
if 0 == tag then
for i = 1, table.getn(secondMenuItem_SL) do
local label = cc.Label:createWithSystemFont(secondMenuItem_SL[i][1], "Arial", 18)
local menuItem = cc.MenuItemLabel:create(label)
menuItem:registerScriptTapHandler(secondMenuItem_SL[i][2])
menuItem:setPosition(cc.p(visibleSize.width / 9, visibleSize.height - top))
secondMenu:addChild(menuItem, 0, i - 1 )
top = top + 50
end
else
for i = 1, table.getn(secondMenuItem_AR) do
local label = cc.Label:createWithSystemFont(secondMenuItem_AR[i][1], "Arial", 18)
local menuItem = cc.MenuItemLabel:create(label)
menuItem:registerScriptTapHandler(secondMenuItem_AR[i][2])
menuItem:setPosition(cc.p(visibleSize.width / 9, visibleSize.height - top))
secondMenu:addChild(menuItem, 0, i - 1 )
top = top + 50
end
end
end
end
function TestFBShareScene:createLayerMenu()
local backItem = cc.MenuItemFont:create("Back")
backItem:registerScriptTapHandler(function()
cc.Director:getInstance():replaceScene(require("HelloWorldScene").create())
end)
local backSize = backItem:getContentSize()
backItem:setPosition(posBR.x - backSize.width / 2, posBR.y + backSize.height / 2)
local menu = cc.Menu:create(backItem)
menu:setPosition(cc.p(0,0))
self:addChild(menu, 0, 1)
local menuItemNames =
{
{"Share link", function(tag, sender)
self:showSecondMenu(0)
end},
{"Share open graph", function(tag, sender)
local params = {
dialog = "share_open_graph",
action_type = "cocostestmyfc:share",
preview_property_name = "cocos_document",
title = "Cocos2dx-lua Game Engine",
image = "http://files.cocos2d-x.org/images/orgsite/logo.png",
url = "http://cocos2d-x.org/docs/catalog/en",
description = "cocos document",
}
if plugin.FacebookAgent:getInstance():canPresentDialogWithParams(params) then
plugin.FacebookAgent:getInstance():dialog(params, function(ret, msg)
print(msg)
end)
else
print("Can't open dialog for share_open_graph")
end
end},
{"Share photo", function(tag, sender)
local fileName = "facebookshare.jpg"
local imgPath = self:sceenshot(fileName)
local delay = cc.DelayTime:create(2.0)
local share = cc.CallFunc:create(function( ... )
local params = {
dialog = "share_photo",
photo = imgPath,
}
if plugin.FacebookAgent:getInstance():canPresentDialogWithParams(params) then
plugin.FacebookAgent:getInstance():dialog(params, function(ret, msg)
print(msg)
end)
else
print("Can't open dialog for share_open_graph")
end
end)
local seq = cc.Sequence:create(delay, share)
self:runAction(seq)
end},
{"Link message", function(tag, sender)
local params = {
dialog = "message_link",
description = "Cocos2dx-lua is a great game engine",
title = "Cocos2dx-lua",
link = "http://www.cocos2d-x.org",
imageUrl = "http://files.cocos2d-x.org/images/orgsite/logo.png",
}
if plugin.FacebookAgent:getInstance():canPresentDialogWithParams(params) then
plugin.FacebookAgent:getInstance():dialog(params, function(ret, msg )
print(msg)
end)
else
print("Can't open dialog for message_link")
end
end},
{"Open graph message", function(tag, sender)
local params = {
dialog = "share_open_graph",
action_type = "cocostestmyfc:share",
preview_property_name = "cocos_document",
title = "Cocos2dx-lua Game Engine",
image = "http://files.cocos2d-x.org/images/orgsite/logo.png",
url = "http://cocos2d-x.org/docs/catalog/en",
description = "cocos document",
}
if plugin.FacebookAgent:getInstance():canPresentDialogWithParams(params) then
plugin.FacebookAgent:getInstance():dialog(params, function(ret, msg )
print(msg)
end)
else
print("Can't open dialog for message_open_graph")
end
end},
{"Photo message", function(tag, sender)
local fileName = "facebookmessage.jpg"
local imgPath = self:sceenshot(fileName)
local delay = cc.DelayTime:create(2.0)
local share = cc.CallFunc:create(function()
local params = {
dialog = "message_photo",
photo = imgPath,
}
if plugin.FacebookAgent:getInstance():canPresentDialogWithParams(params) then
plugin.FacebookAgent:getInstance():dialog(params, function(ret, msg )
print(msg)
end)
else
print("Can't open dialog for message_photo")
end
end)
local seq = cc.Sequence:create(delay, share)
self:runAction(seq)
end},
{"App request", function(tag, sender)
self:showSecondMenu(1)
end},
}
local y_pos = 0
for i = 1, table.getn(menuItemNames) do
local label = cc.Label:createWithSystemFont(menuItemNames[i][1], "Arial", 22)
local menuItem = cc.MenuItemLabel:create(label)
menuItem:registerScriptTapHandler(menuItemNames[i][2])
y_pos = visibleSize.height - 35 * (i - 1) - 100
menuItem:setPosition(origin.x + 100, y_pos)
menu:addChild(menuItem, 0, i -1 )
end
--create second menu
local secondMenu = cc.Menu:create()
secondMenu:setPosition(cc.p(340, 0))
self:addChild(secondMenu, 0, 2)
end
return TestFBShareScene
| 0 | 0.864554 | 1 | 0.864554 | game-dev | MEDIA | 0.637353 | game-dev | 0.855158 | 1 | 0.855158 |
defold/defold | 18,343 | external/bullet3d/package/bullet-2.77/src/BulletCollision/CollisionDispatch/btConvexConvexAlgorithm.cpp | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
///Specialized capsule-capsule collision algorithm has been added for Bullet 2.75 release to increase ragdoll performance
///If you experience problems with capsule-capsule collision, try to define BT_DISABLE_CAPSULE_CAPSULE_COLLIDER and report it in the Bullet forums
///with reproduction case
//define BT_DISABLE_CAPSULE_CAPSULE_COLLIDER 1
#include "btConvexConvexAlgorithm.h"
//#include <stdio.h>
#include "BulletCollision/NarrowPhaseCollision/btDiscreteCollisionDetectorInterface.h"
#include "BulletCollision/BroadphaseCollision/btBroadphaseInterface.h"
#include "BulletCollision/CollisionDispatch/btCollisionObject.h"
#include "BulletCollision/CollisionShapes/btConvexShape.h"
#include "BulletCollision/CollisionShapes/btCapsuleShape.h"
#include "BulletCollision/NarrowPhaseCollision/btGjkPairDetector.h"
#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h"
#include "BulletCollision/CollisionDispatch/btCollisionDispatcher.h"
#include "BulletCollision/CollisionShapes/btBoxShape.h"
#include "BulletCollision/CollisionDispatch/btManifoldResult.h"
#include "BulletCollision/NarrowPhaseCollision/btConvexPenetrationDepthSolver.h"
#include "BulletCollision/NarrowPhaseCollision/btContinuousConvexCollision.h"
#include "BulletCollision/NarrowPhaseCollision/btSubSimplexConvexCast.h"
#include "BulletCollision/NarrowPhaseCollision/btGjkConvexCast.h"
#include "BulletCollision/NarrowPhaseCollision/btVoronoiSimplexSolver.h"
#include "BulletCollision/CollisionShapes/btSphereShape.h"
#include "BulletCollision/NarrowPhaseCollision/btMinkowskiPenetrationDepthSolver.h"
#include "BulletCollision/NarrowPhaseCollision/btGjkEpa2.h"
#include "BulletCollision/NarrowPhaseCollision/btGjkEpaPenetrationDepthSolver.h"
///////////
static SIMD_FORCE_INLINE void segmentsClosestPoints(
btVector3& ptsVector,
btVector3& offsetA,
btVector3& offsetB,
btScalar& tA, btScalar& tB,
const btVector3& translation,
const btVector3& dirA, btScalar hlenA,
const btVector3& dirB, btScalar hlenB )
{
// compute the parameters of the closest points on each line segment
btScalar dirA_dot_dirB = btDot(dirA,dirB);
btScalar dirA_dot_trans = btDot(dirA,translation);
btScalar dirB_dot_trans = btDot(dirB,translation);
btScalar denom = 1.0f - dirA_dot_dirB * dirA_dot_dirB;
if ( denom == 0.0f ) {
tA = 0.0f;
} else {
tA = ( dirA_dot_trans - dirB_dot_trans * dirA_dot_dirB ) / denom;
if ( tA < -hlenA )
tA = -hlenA;
else if ( tA > hlenA )
tA = hlenA;
}
tB = tA * dirA_dot_dirB - dirB_dot_trans;
if ( tB < -hlenB ) {
tB = -hlenB;
tA = tB * dirA_dot_dirB + dirA_dot_trans;
if ( tA < -hlenA )
tA = -hlenA;
else if ( tA > hlenA )
tA = hlenA;
} else if ( tB > hlenB ) {
tB = hlenB;
tA = tB * dirA_dot_dirB + dirA_dot_trans;
if ( tA < -hlenA )
tA = -hlenA;
else if ( tA > hlenA )
tA = hlenA;
}
// compute the closest points relative to segment centers.
offsetA = dirA * tA;
offsetB = dirB * tB;
ptsVector = translation - offsetA + offsetB;
}
static SIMD_FORCE_INLINE btScalar capsuleCapsuleDistance(
btVector3& normalOnB,
btVector3& pointOnB,
btScalar capsuleLengthA,
btScalar capsuleRadiusA,
btScalar capsuleLengthB,
btScalar capsuleRadiusB,
int capsuleAxisA,
int capsuleAxisB,
const btTransform& transformA,
const btTransform& transformB,
btScalar distanceThreshold )
{
btVector3 directionA = transformA.getBasis().getColumn(capsuleAxisA);
btVector3 translationA = transformA.getOrigin();
btVector3 directionB = transformB.getBasis().getColumn(capsuleAxisB);
btVector3 translationB = transformB.getOrigin();
// translation between centers
btVector3 translation = translationB - translationA;
// compute the closest points of the capsule line segments
btVector3 ptsVector; // the vector between the closest points
btVector3 offsetA, offsetB; // offsets from segment centers to their closest points
btScalar tA, tB; // parameters on line segment
segmentsClosestPoints( ptsVector, offsetA, offsetB, tA, tB, translation,
directionA, capsuleLengthA, directionB, capsuleLengthB );
btScalar distance = ptsVector.length() - capsuleRadiusA - capsuleRadiusB;
if ( distance > distanceThreshold )
return distance;
btScalar lenSqr = ptsVector.length2();
if (lenSqr<= (SIMD_EPSILON*SIMD_EPSILON))
{
//degenerate case where 2 capsules are likely at the same location: take a vector tangential to 'directionA'
btVector3 q;
btPlaneSpace1(directionA,normalOnB,q);
} else
{
// compute the contact normal
normalOnB = ptsVector*-btRecipSqrt(lenSqr);
}
pointOnB = transformB.getOrigin()+offsetB + normalOnB * capsuleRadiusB;
return distance;
}
//////////
btConvexConvexAlgorithm::CreateFunc::CreateFunc(btSimplexSolverInterface* simplexSolver, btConvexPenetrationDepthSolver* pdSolver)
{
m_numPerturbationIterations = 0;
m_minimumPointsPerturbationThreshold = 3;
m_simplexSolver = simplexSolver;
m_pdSolver = pdSolver;
}
btConvexConvexAlgorithm::CreateFunc::~CreateFunc()
{
}
btConvexConvexAlgorithm::btConvexConvexAlgorithm(btPersistentManifold* mf,const btCollisionAlgorithmConstructionInfo& ci,btCollisionObject* body0,btCollisionObject* body1,btSimplexSolverInterface* simplexSolver, btConvexPenetrationDepthSolver* pdSolver,int numPerturbationIterations, int minimumPointsPerturbationThreshold)
: btActivatingCollisionAlgorithm(ci,body0,body1),
m_simplexSolver(simplexSolver),
m_pdSolver(pdSolver),
m_ownManifold (false),
m_manifoldPtr(mf),
m_lowLevelOfDetail(false),
#ifdef USE_SEPDISTANCE_UTIL2
m_sepDistance((static_cast<btConvexShape*>(body0->getCollisionShape()))->getAngularMotionDisc(),
(static_cast<btConvexShape*>(body1->getCollisionShape()))->getAngularMotionDisc()),
#endif
m_numPerturbationIterations(numPerturbationIterations),
m_minimumPointsPerturbationThreshold(minimumPointsPerturbationThreshold)
{
(void)body0;
(void)body1;
}
btConvexConvexAlgorithm::~btConvexConvexAlgorithm()
{
if (m_ownManifold)
{
if (m_manifoldPtr)
m_dispatcher->releaseManifold(m_manifoldPtr);
}
}
void btConvexConvexAlgorithm ::setLowLevelOfDetail(bool useLowLevel)
{
m_lowLevelOfDetail = useLowLevel;
}
struct btPerturbedContactResult : public btManifoldResult
{
btManifoldResult* m_originalManifoldResult;
btTransform m_transformA;
btTransform m_transformB;
btTransform m_unPerturbedTransform;
bool m_perturbA;
btIDebugDraw* m_debugDrawer;
btPerturbedContactResult(btManifoldResult* originalResult,const btTransform& transformA,const btTransform& transformB,const btTransform& unPerturbedTransform,bool perturbA,btIDebugDraw* debugDrawer)
:m_originalManifoldResult(originalResult),
m_transformA(transformA),
m_transformB(transformB),
m_unPerturbedTransform(unPerturbedTransform),
m_perturbA(perturbA),
m_debugDrawer(debugDrawer)
{
}
virtual ~ btPerturbedContactResult()
{
}
virtual void addContactPoint(const btVector3& normalOnBInWorld,const btVector3& pointInWorld,btScalar orgDepth)
{
btVector3 endPt,startPt;
btScalar newDepth;
btVector3 newNormal;
if (m_perturbA)
{
btVector3 endPtOrg = pointInWorld + normalOnBInWorld*orgDepth;
endPt = (m_unPerturbedTransform*m_transformA.inverse())(endPtOrg);
newDepth = (endPt - pointInWorld).dot(normalOnBInWorld);
startPt = endPt+normalOnBInWorld*newDepth;
} else
{
endPt = pointInWorld + normalOnBInWorld*orgDepth;
startPt = (m_unPerturbedTransform*m_transformB.inverse())(pointInWorld);
newDepth = (endPt - startPt).dot(normalOnBInWorld);
}
//#define DEBUG_CONTACTS 1
#ifdef DEBUG_CONTACTS
m_debugDrawer->drawLine(startPt,endPt,btVector3(1,0,0));
m_debugDrawer->drawSphere(startPt,0.05,btVector3(0,1,0));
m_debugDrawer->drawSphere(endPt,0.05,btVector3(0,0,1));
#endif //DEBUG_CONTACTS
m_originalManifoldResult->addContactPoint(normalOnBInWorld,startPt,newDepth);
}
};
extern btScalar gContactBreakingThreshold;
//
// Convex-Convex collision algorithm
//
void btConvexConvexAlgorithm ::processCollision (btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut)
{
if (!m_manifoldPtr)
{
//swapped?
m_manifoldPtr = m_dispatcher->getNewManifold(body0,body1);
m_ownManifold = true;
}
resultOut->setPersistentManifold(m_manifoldPtr);
//comment-out next line to test multi-contact generation
//resultOut->getPersistentManifold()->clearManifold();
btConvexShape* min0 = static_cast<btConvexShape*>(body0->getCollisionShape());
btConvexShape* min1 = static_cast<btConvexShape*>(body1->getCollisionShape());
btVector3 normalOnB;
btVector3 pointOnBWorld;
#ifndef BT_DISABLE_CAPSULE_CAPSULE_COLLIDER
if ((min0->getShapeType() == CAPSULE_SHAPE_PROXYTYPE) && (min1->getShapeType() == CAPSULE_SHAPE_PROXYTYPE))
{
btCapsuleShape* capsuleA = (btCapsuleShape*) min0;
btCapsuleShape* capsuleB = (btCapsuleShape*) min1;
btVector3 localScalingA = capsuleA->getLocalScaling();
btVector3 localScalingB = capsuleB->getLocalScaling();
btScalar threshold = m_manifoldPtr->getContactBreakingThreshold();
btScalar dist = capsuleCapsuleDistance(normalOnB, pointOnBWorld,capsuleA->getHalfHeight(),capsuleA->getRadius(),
capsuleB->getHalfHeight(),capsuleB->getRadius(),capsuleA->getUpAxis(),capsuleB->getUpAxis(),
body0->getWorldTransform(),body1->getWorldTransform(),threshold);
if (dist<threshold)
{
btAssert(normalOnB.length2()>=(SIMD_EPSILON*SIMD_EPSILON));
resultOut->addContactPoint(normalOnB,pointOnBWorld,dist);
}
resultOut->refreshContactPoints();
return;
}
#endif //BT_DISABLE_CAPSULE_CAPSULE_COLLIDER
#ifdef USE_SEPDISTANCE_UTIL2
if (dispatchInfo.m_useConvexConservativeDistanceUtil)
{
m_sepDistance.updateSeparatingDistance(body0->getWorldTransform(),body1->getWorldTransform());
}
if (!dispatchInfo.m_useConvexConservativeDistanceUtil || m_sepDistance.getConservativeSeparatingDistance()<=0.f)
#endif //USE_SEPDISTANCE_UTIL2
{
btGjkPairDetector::ClosestPointInput input;
btGjkPairDetector gjkPairDetector(min0,min1,m_simplexSolver,m_pdSolver);
//TODO: if (dispatchInfo.m_useContinuous)
gjkPairDetector.setMinkowskiA(min0);
gjkPairDetector.setMinkowskiB(min1);
#ifdef USE_SEPDISTANCE_UTIL2
if (dispatchInfo.m_useConvexConservativeDistanceUtil)
{
input.m_maximumDistanceSquared = BT_LARGE_FLOAT;
} else
#endif //USE_SEPDISTANCE_UTIL2
{
input.m_maximumDistanceSquared = min0->getMargin() + min1->getMargin() + m_manifoldPtr->getContactBreakingThreshold();
input.m_maximumDistanceSquared*= input.m_maximumDistanceSquared;
}
input.m_stackAlloc = dispatchInfo.m_stackAllocator;
input.m_transformA = body0->getWorldTransform();
input.m_transformB = body1->getWorldTransform();
gjkPairDetector.getClosestPoints(input,*resultOut,dispatchInfo.m_debugDraw);
#ifdef USE_SEPDISTANCE_UTIL2
btScalar sepDist = 0.f;
if (dispatchInfo.m_useConvexConservativeDistanceUtil)
{
sepDist = gjkPairDetector.getCachedSeparatingDistance();
if (sepDist>SIMD_EPSILON)
{
sepDist += dispatchInfo.m_convexConservativeDistanceThreshold;
//now perturbe directions to get multiple contact points
}
}
#endif //USE_SEPDISTANCE_UTIL2
//now perform 'm_numPerturbationIterations' collision queries with the perturbated collision objects
//perform perturbation when more then 'm_minimumPointsPerturbationThreshold' points
if (m_numPerturbationIterations && resultOut->getPersistentManifold()->getNumContacts() < m_minimumPointsPerturbationThreshold)
{
int i;
btVector3 v0,v1;
btVector3 sepNormalWorldSpace;
sepNormalWorldSpace = gjkPairDetector.getCachedSeparatingAxis().normalized();
btPlaneSpace1(sepNormalWorldSpace,v0,v1);
bool perturbeA = true;
const btScalar angleLimit = 0.125f * SIMD_PI;
btScalar perturbeAngle;
btScalar radiusA = min0->getAngularMotionDisc();
btScalar radiusB = min1->getAngularMotionDisc();
if (radiusA < radiusB)
{
perturbeAngle = gContactBreakingThreshold /radiusA;
perturbeA = true;
} else
{
perturbeAngle = gContactBreakingThreshold / radiusB;
perturbeA = false;
}
if ( perturbeAngle > angleLimit )
perturbeAngle = angleLimit;
btTransform unPerturbedTransform;
if (perturbeA)
{
unPerturbedTransform = input.m_transformA;
} else
{
unPerturbedTransform = input.m_transformB;
}
for ( i=0;i<m_numPerturbationIterations;i++)
{
if (v0.length2()>SIMD_EPSILON)
{
btQuaternion perturbeRot(v0,perturbeAngle);
btScalar iterationAngle = i*(SIMD_2_PI/btScalar(m_numPerturbationIterations));
btQuaternion rotq(sepNormalWorldSpace,iterationAngle);
if (perturbeA)
{
input.m_transformA.setBasis( btMatrix3x3(rotq.inverse()*perturbeRot*rotq)*body0->getWorldTransform().getBasis());
input.m_transformB = body1->getWorldTransform();
#ifdef DEBUG_CONTACTS
dispatchInfo.m_debugDraw->drawTransform(input.m_transformA,10.0);
#endif //DEBUG_CONTACTS
} else
{
input.m_transformA = body0->getWorldTransform();
input.m_transformB.setBasis( btMatrix3x3(rotq.inverse()*perturbeRot*rotq)*body1->getWorldTransform().getBasis());
#ifdef DEBUG_CONTACTS
dispatchInfo.m_debugDraw->drawTransform(input.m_transformB,10.0);
#endif
}
btPerturbedContactResult perturbedResultOut(resultOut,input.m_transformA,input.m_transformB,unPerturbedTransform,perturbeA,dispatchInfo.m_debugDraw);
gjkPairDetector.getClosestPoints(input,perturbedResultOut,dispatchInfo.m_debugDraw);
}
}
}
#ifdef USE_SEPDISTANCE_UTIL2
if (dispatchInfo.m_useConvexConservativeDistanceUtil && (sepDist>SIMD_EPSILON))
{
m_sepDistance.initSeparatingDistance(gjkPairDetector.getCachedSeparatingAxis(),sepDist,body0->getWorldTransform(),body1->getWorldTransform());
}
#endif //USE_SEPDISTANCE_UTIL2
}
if (m_ownManifold)
{
resultOut->refreshContactPoints();
}
}
bool disableCcd = false;
btScalar btConvexConvexAlgorithm::calculateTimeOfImpact(btCollisionObject* col0,btCollisionObject* col1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut)
{
(void)resultOut;
(void)dispatchInfo;
///Rather then checking ALL pairs, only calculate TOI when motion exceeds threshold
///Linear motion for one of objects needs to exceed m_ccdSquareMotionThreshold
///col0->m_worldTransform,
btScalar resultFraction = btScalar(1.);
btScalar squareMot0 = (col0->getInterpolationWorldTransform().getOrigin() - col0->getWorldTransform().getOrigin()).length2();
btScalar squareMot1 = (col1->getInterpolationWorldTransform().getOrigin() - col1->getWorldTransform().getOrigin()).length2();
if (squareMot0 < col0->getCcdSquareMotionThreshold() &&
squareMot1 < col1->getCcdSquareMotionThreshold())
return resultFraction;
if (disableCcd)
return btScalar(1.);
//An adhoc way of testing the Continuous Collision Detection algorithms
//One object is approximated as a sphere, to simplify things
//Starting in penetration should report no time of impact
//For proper CCD, better accuracy and handling of 'allowed' penetration should be added
//also the mainloop of the physics should have a kind of toi queue (something like Brian Mirtich's application of Timewarp for Rigidbodies)
/// Convex0 against sphere for Convex1
{
btConvexShape* convex0 = static_cast<btConvexShape*>(col0->getCollisionShape());
btSphereShape sphere1(col1->getCcdSweptSphereRadius()); //todo: allow non-zero sphere sizes, for better approximation
btConvexCast::CastResult result;
btVoronoiSimplexSolver voronoiSimplex;
//SubsimplexConvexCast ccd0(&sphere,min0,&voronoiSimplex);
///Simplification, one object is simplified as a sphere
btGjkConvexCast ccd1( convex0 ,&sphere1,&voronoiSimplex);
//ContinuousConvexCollision ccd(min0,min1,&voronoiSimplex,0);
if (ccd1.calcTimeOfImpact(col0->getWorldTransform(),col0->getInterpolationWorldTransform(),
col1->getWorldTransform(),col1->getInterpolationWorldTransform(),result))
{
//store result.m_fraction in both bodies
if (col0->getHitFraction()> result.m_fraction)
col0->setHitFraction( result.m_fraction );
if (col1->getHitFraction() > result.m_fraction)
col1->setHitFraction( result.m_fraction);
if (resultFraction > result.m_fraction)
resultFraction = result.m_fraction;
}
}
/// Sphere (for convex0) against Convex1
{
btConvexShape* convex1 = static_cast<btConvexShape*>(col1->getCollisionShape());
btSphereShape sphere0(col0->getCcdSweptSphereRadius()); //todo: allow non-zero sphere sizes, for better approximation
btConvexCast::CastResult result;
btVoronoiSimplexSolver voronoiSimplex;
//SubsimplexConvexCast ccd0(&sphere,min0,&voronoiSimplex);
///Simplification, one object is simplified as a sphere
btGjkConvexCast ccd1(&sphere0,convex1,&voronoiSimplex);
//ContinuousConvexCollision ccd(min0,min1,&voronoiSimplex,0);
if (ccd1.calcTimeOfImpact(col0->getWorldTransform(),col0->getInterpolationWorldTransform(),
col1->getWorldTransform(),col1->getInterpolationWorldTransform(),result))
{
//store result.m_fraction in both bodies
if (col0->getHitFraction() > result.m_fraction)
col0->setHitFraction( result.m_fraction);
if (col1->getHitFraction() > result.m_fraction)
col1->setHitFraction( result.m_fraction);
if (resultFraction > result.m_fraction)
resultFraction = result.m_fraction;
}
}
return resultFraction;
}
| 0 | 0.981405 | 1 | 0.981405 | game-dev | MEDIA | 0.98767 | game-dev | 0.990176 | 1 | 0.990176 |
postspectacular/toxiclibs | 2,156 | examples/physics/ParticleStringCircle/Physics.pde | void initPhysics() {
physics=new VerletPhysics2D();
// set screen bounds as bounds for physics sim
physics.setWorldBounds(new Rect(0,0,width,height));
// add gravity along positive Y axis
physics.addBehavior(new GravityBehavior2D(new Vec2D(0,0.1)));
// compute spacing for string particles
float delta=(float)width/(STRING_RES-1);
for(int i=0; i<STRING_RES; i++) {
// create particles along X axis
VerletParticle2D p=new VerletParticle2D(i*delta,height/2);
physics.addParticle(p);
// define a repulsion field around each particle
// this is used to push the ball away
physics.addBehavior(new AttractionBehavior2D(p,delta*1.5,-20));
// connect each particle to its previous neighbour
if (i>0) {
VerletParticle2D q=physics.particles.get(i-1);
VerletSpring2D s=new VerletSpring2D(p,q,delta*0.5,0.1);
physics.addSpring(s);
}
}
// lock 1st & last particles
physics.particles.get(0).lock();
physics.particles.get(physics.particles.size()-1).lock();
// create ball
// first create a particle as the ball centre
VerletParticle2D c=new VerletParticle2D(width/2,100);
physics.addParticle(c);
// list to store all ball perimeter particles
List<VerletParticle2D> cparts=new ArrayList<VerletParticle2D>();
for(int i=0; i<BALL_RES; i++) {
// create a rotation vector, scale it to the radius and move relative to ball center
Vec2D pos=Vec2D.fromTheta(i*TWO_PI/BALL_RES).scaleSelf(BALL_RADIUS).addSelf(c);
// create particle and add to lists
VerletParticle2D p = new VerletParticle2D(pos);
cparts.add(p);
physics.addParticle(p);
// connect to ball center for extra stability
physics.addSpring(new VerletSpring2D(c,p,BALL_RADIUS,0.01));
// also connect all perimeter particles sequentially
if (i>0) {
VerletParticle2D q=cparts.get(i-1);
physics.addSpring(new VerletSpring2D(p,q,p.distanceTo(q),1));
}
}
// finally close ball perimeter by connecting first & last particle
VerletParticle2D p=cparts.get(0);
VerletParticle2D q=cparts.get(BALL_RES-1);
physics.addSpring(new VerletSpring2D(p,q,p.distanceTo(q),1));
}
| 0 | 0.742177 | 1 | 0.742177 | game-dev | MEDIA | 0.638363 | game-dev,graphics-rendering | 0.685088 | 1 | 0.685088 |
AirConsole/airconsole-unity-plugin | 10,117 | Assets/AirConsole/scripts/Editor/Inspector.cs | #if !DISABLE_AIRCONSOLE && UNITY_EDITOR
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;
using UnityEngine;
using UnityEditor;
using Debug = UnityEngine.Debug;
namespace NDream.AirConsole.Editor {
[CustomEditor(typeof(AirConsole))]
public class Inspector : UnityEditor.Editor {
private GUIStyle styleBlack = new();
private Texture2D bg;
private Texture logo;
private AirConsole controller;
private SerializedProperty gameId;
private SerializedProperty gameVersion;
private bool translationValue;
private bool inactivePlayersSilencedValue;
private bool nativeGameSizingSupportedValue;
private const string TRANSLATION_ACTIVE = "var AIRCONSOLE_TRANSLATION = true;";
private const string TRANSLATION_INACTIVE = "var AIRCONSOLE_TRANSLATION = false;";
private const string INACTIVE_PLAYERS_SILENCED_ACTIVE = "var AIRCONSOLE_INACTIVE_PLAYERS_SILENCED = true;";
private const string INACTIVE_PLAYERS_SILENCED_INACTIVE = "var AIRCONSOLE_INACTIVE_PLAYERS_SILENCED = false;";
private const string ANDROID_NATIVE_GAME_SIZING_ACTIVE = "var AIRCONSOLE_ANDROID_NATIVE_GAMESIZING = true;";
private const string ANDROID_NATIVE_GAME_SIZING_INACTIVE = "var AIRCONSOLE_ANDROID_NATIVE_GAMESIZING = false;";
private static string SettingsPath => Application.dataPath + Settings.WEBTEMPLATE_PATH + "/airconsole-settings.js";
[InitializeOnLoadMethod]
private static void Migration() {
MigrateVersion250(Application.dataPath + Settings.WEBTEMPLATE_PATH + "/translation.js", SettingsPath);
}
public void Awake() {
ReadConstructorSettings();
}
public void OnEnable() {
LoadResources();
SetupStyle();
}
private void LoadResources() {
bg = (Texture2D)Resources.Load("AirConsoleBg");
logo = (Texture)Resources.Load("AirConsoleLogoText");
}
private void SetupStyle() {
styleBlack.normal.background = bg;
styleBlack.normal.textColor = Color.white;
styleBlack.alignment = TextAnchor.MiddleRight;
styleBlack.margin.top = 5;
styleBlack.margin.bottom = 5;
styleBlack.padding.right = 2;
styleBlack.padding.bottom = 2;
}
public override void OnInspectorGUI() {
controller = (AirConsole)target;
ShowLogoAndVersion();
ShowDefaultProperties();
DrawSettingsToggles();
#if UNITY_ANDROID
ValidateAndroidGameVersion();
#endif
ShowAdditionalProperties();
ShowButtons();
}
private void ShowLogoAndVersion() {
EditorGUILayout.BeginHorizontal(styleBlack, GUILayout.Height(30));
GUILayout.Label(logo, GUILayout.Width(128), GUILayout.Height(30));
GUILayout.FlexibleSpace();
GUILayout.Label("v" + Settings.VERSION, styleBlack);
EditorGUILayout.EndHorizontal();
}
private void ShowDefaultProperties() {
serializedObject.Update();
EditorGUILayout.PropertyField(serializedObject.FindProperty("controllerHtml"));
EditorGUILayout.PropertyField(serializedObject.FindProperty("autoScaleCanvas"));
}
[Conditional("UNITY_ANDROID")]
private void AndroidOnlyHelpBox(string message, MessageType messageType = MessageType.Info) {
EditorGUILayout.HelpBox(message, messageType, true);
}
private void DrawSettingsToggles() {
DrawToggle("Translation", ref translationValue);
DrawToggle("Silence Player", ref inactivePlayersSilencedValue);
DrawToggle(new GUIContent("Native Game Sizing", "Enables SafeArea support with fullscreen webview overlay"),
ref nativeGameSizingSupportedValue);
if (!nativeGameSizingSupportedValue) {
AndroidOnlyHelpBox("Android for Automotive requires you to enable this and to implement the OnSafeAreaChanged "
+ "event handler provided by the AirConsole instance, enabling you to only render your game content"
+ " in relevant area", MessageType.Warning);
}
}
private void DrawToggle(string label, ref bool value) {
bool oldValue = value;
value = EditorGUILayout.Toggle(label, value);
if (oldValue != value) {
WriteConstructorSettings();
}
}
private void DrawToggle(GUIContent content, ref bool value) {
bool oldValue = value;
value = EditorGUILayout.Toggle(content, value);
if (oldValue != value) {
WriteConstructorSettings();
}
}
private void ValidateAndroidGameVersion() {
string androidGameVersion = serializedObject.FindProperty("androidGameVersion").stringValue;
if (string.IsNullOrEmpty(androidGameVersion) || !Regex.IsMatch(androidGameVersion, @"^\d{4}-\d{2}-\d{2}-\d{2}-\d{2}-\d{2}$")) {
EditorGUILayout.HelpBox("Please enter a valid Game Version for Android", MessageType.Error);
}
}
private void ShowAdditionalProperties() {
EditorGUILayout.PropertyField(serializedObject.FindProperty("androidGameVersion"));
EditorGUILayout.PropertyField(serializedObject.FindProperty("androidUIResizeMode"));
if (serializedObject.FindProperty("androidUIResizeMode").enumValueIndex > (int)AndroidUIResizeMode.ResizeCamera
&& nativeGameSizingSupportedValue) {
AndroidOnlyHelpBox("Android with native game sizing requires SafeAreas.\n"
+ "In this mode, AirConsole no longer supports UI Reference Resolution Scaling.",
MessageType.Warning);
}
EditorGUILayout.PropertyField(serializedObject.FindProperty("webViewLoadingSprite"));
EditorGUILayout.PropertyField(serializedObject.FindProperty("browserStartMode"));
EditorGUILayout.PropertyField(serializedObject.FindProperty("devGameId"));
EditorGUILayout.PropertyField(serializedObject.FindProperty("devLanguage"));
EditorGUILayout.PropertyField(serializedObject.FindProperty("LocalIpOverride"));
serializedObject.ApplyModifiedProperties();
}
private void ShowButtons() {
EditorGUILayout.BeginHorizontal(styleBlack);
// check if a port was exported
if (File.Exists(EditorPrefs.GetString("airconsolePortPath") + "/screen.html")) {
if (GUILayout.Button("Open Exported Port", GUILayout.MaxWidth(130))) {
Extentions.OpenBrowser(controller, EditorPrefs.GetString("airconsolePortPath"));
}
}
GUILayout.FlexibleSpace();
if (GUILayout.Button("Settings")) {
SettingWindow window = (SettingWindow)EditorWindow.GetWindow(typeof(SettingWindow));
window.Show();
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal(styleBlack);
if (GUILayout.Button("Upgrade instructions", GUILayout.MaxWidth(130))) {
OpenUpgradeInstructions();
}
GUILayout.FlexibleSpace();
EditorGUILayout.EndHorizontal();
}
internal void UpdateAirConsoleConstructorSettings() {
ReadConstructorSettings();
WriteConstructorSettings();
}
private void ReadConstructorSettings() {
if (!File.Exists(SettingsPath)) {
return;
}
string persistedSettings = File.ReadAllText(SettingsPath);
translationValue = persistedSettings.Contains(TRANSLATION_ACTIVE);
inactivePlayersSilencedValue = !persistedSettings.Contains(INACTIVE_PLAYERS_SILENCED_INACTIVE);
nativeGameSizingSupportedValue = !persistedSettings.Contains(ANDROID_NATIVE_GAME_SIZING_INACTIVE);
}
private void WriteConstructorSettings() {
try {
File.WriteAllText(SettingsPath,
$"{(translationValue ? TRANSLATION_ACTIVE : TRANSLATION_INACTIVE)}\n"
+ $"{(inactivePlayersSilencedValue ? INACTIVE_PLAYERS_SILENCED_ACTIVE : INACTIVE_PLAYERS_SILENCED_INACTIVE)}\n"
+ $"{(nativeGameSizingSupportedValue ? ANDROID_NATIVE_GAME_SIZING_ACTIVE : ANDROID_NATIVE_GAME_SIZING_INACTIVE)}\n"
+ GenerateGameInformation());
} catch (IOException e) {
AirConsoleLogger.LogError(() => $"Failed to write settings file at {SettingsPath}: {e.Message}");
}
}
private static string GenerateGameInformation() =>
$"window.UNITY_VERSION = '{Application.unityVersion}';\n"
+ $"window.AIRCONSOLE_VERSION = '{Settings.VERSION}';";
private static void MigrateVersion250(string originalPath, string newPath) {
if (!File.Exists(originalPath)) {
return;
}
if (!File.Exists(newPath)) {
AirConsoleLogger.LogWarning(() => "Update settings file to new version, renaming from translation.js to game-settings.js");
File.Move(originalPath, newPath);
File.AppendAllText(newPath, $"\n{INACTIVE_PLAYERS_SILENCED_INACTIVE}");
} else {
AirConsoleLogger.LogError(() => $"game-settings.js found [{newPath}]. Deleting prior translation.js [{originalPath}].");
File.Delete(originalPath);
}
}
private static void OpenUpgradeInstructions() {
Application.OpenURL(
"https://github.com/AirConsole/airconsole-unity-plugin/wiki/Upgrading-the-Unity-Plugin-to-a-newer-version");
}
}
}
#endif | 0 | 0.920042 | 1 | 0.920042 | game-dev | MEDIA | 0.926192 | game-dev | 0.919102 | 1 | 0.919102 |
defold/defold | 17,708 | editor/src/clj/editor/protobuf_forms.clj | ;; Copyright 2020-2025 The Defold Foundation
;; Copyright 2014-2020 King
;; Copyright 2009-2014 Ragnar Svensson, Christian Murray
;; Licensed under the Defold License version 1.0 (the "License"); you may not use
;; this file except in compliance with the License.
;;
;; You may obtain a copy of the License, together with FAQs at
;; https://www.defold.com/license
;;
;; 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.
(ns editor.protobuf-forms
(:require [clojure.string :as str]
[dynamo.graph :as g]
[editor.protobuf :as protobuf]
[editor.util :as util]
[util.fn :as fn])
(:import [com.defold.extension.pipeline.texture ITextureCompressor TextureCompression TextureCompressorUncompressed]
[com.dynamo.graphics.proto Graphics$PlatformProfile Graphics$PlatformProfile$OS Graphics$TextureImage$TextureFormat Graphics$TextureProfiles]
[com.dynamo.input.proto Input$Gamepad Input$GamepadMaps Input$GamepadType Input$InputBinding Input$Key Input$Mouse Input$Text Input$Touch]))
(set! *warn-on-reflection* true)
(defn- clear-form-op [{:keys [node-id]} path]
(g/update-property node-id :pb util/dissoc-in path))
(defn- set-form-op [{:keys [node-id]} path value]
(g/update-property node-id :pb assoc-in path value))
(defn- longest-prefix-size [enum-values]
(case (count enum-values)
(0 1) 0
(->> enum-values
(mapv #(-> % first name))
(apply map hash-set)
(take-while #(= 1 (count %)))
count)))
(defn- display-name-or-default [[val {:keys [display-name]}] prefix-size]
(if (str/blank? display-name)
(str/join " " (-> val
name
(subs prefix-size)
str/capitalize
(str/split #"-")))
display-name))
(defn make-options [enum-values]
(let [prefix-size (longest-prefix-size enum-values)]
(mapv (juxt first #(display-name-or-default % prefix-size)) enum-values)))
(defn- make-enum-options-raw [^Class pb-enum-class]
(make-options (protobuf/enum-values pb-enum-class)))
(def make-enum-options (fn/memoize make-enum-options-raw))
(defn- default-form-ops [node-id]
{:form-ops {:user-data {:node-id node-id}
:set set-form-op
:clear clear-form-op}})
(defn- make-values [pb keys]
(into {} (map #(do [[%] (pb %)]) keys)))
(defn- form-values [form-data pb]
(let [keys (map (comp first :path) (mapcat :fields (:sections form-data)))]
(make-values pb keys)))
(defmulti protobuf-form-data (fn [_node-id _pb def] (:pb-class def)))
(defmethod protobuf-form-data Input$InputBinding [_node-id _pb _def]
(let [key-values (butlast (protobuf/enum-values Input$Key)) ; skip MAX_KEY_COUNT
mouse-values (butlast (protobuf/enum-values Input$Mouse)) ; skip MAX_MOUSE_COUNT
gamepad-values (butlast (protobuf/enum-values Input$Gamepad)) ; skip MAX_GAMEPAD_COUNT
touch-values (butlast (protobuf/enum-values Input$Touch)) ; skip MAX_TOUCH_COUNT
text-values (butlast (protobuf/enum-values Input$Text))] ; skip MAX_TEXT_COUNT
{:navigation false
:sections [{:title "Input Bindings"
:fields [{:path [:key-trigger]
:label "Key Triggers"
:type :table
:columns [{:path [:input]
:label "Input"
:type :choicebox
:options (sort-by first (make-options key-values))
:default (ffirst key-values)}
{:path [:action] :label "Action" :type :string}]}
{:path [:mouse-trigger]
:label "Mouse Triggers"
:type :table
:columns [{:path [:input]
:label "Input"
:type :choicebox
:options (sort-by first (make-options mouse-values))
:default (ffirst mouse-values)}
{:path [:action] :label "Action" :type :string}]}
{:path [:gamepad-trigger]
:label "Gamepad Triggers"
:type :table
:columns [{:path [:input]
:label "Input"
:type :choicebox
:options (sort-by first (make-options gamepad-values))
:default (ffirst gamepad-values)}
{:path [:action] :label "Action" :type :string}]}
{:path [:touch-trigger]
:label "Touch Triggers"
:type :table
:columns [{:path [:input]
:label "Input"
:type :choicebox
:options (sort-by first (make-options touch-values))
:default (ffirst touch-values)}
{:path [:action] :label "Action" :type :string}]}
{:path [:text-trigger]
:label "Text Triggers"
:type :table
:columns [{:path [:input]
:label "Input"
:type :choicebox
:options (make-options text-values) ; Unsorted.
:default (ffirst text-values)}
{:path [:action] :label "Action" :type :string}]}]}]}))
(defn- gamepad-pb->form-pb [pb]
(letfn [(mods->bools [modlist]
(let [mods (set (map :mod modlist))]
{:negate (boolean (mods :gamepad-modifier-negate))
:clamp (boolean (mods :gamepad-modifier-clamp))
:scale (boolean (mods :gamepad-modifier-scale))}))
(map->form-pb [m]
(merge (dissoc m :mod) (mods->bools (m :mod))))
(device->form-pb [device]
(update device :map #(mapv map->form-pb %)))]
(update pb :driver #(mapv device->form-pb %))))
(defn- form-pb->gamepad-pb [form-pb]
(letfn [(bools->mods [{:keys [negate clamp scale]}]
{:mod
(vec
(concat
(when negate [{:mod :gamepad-modifier-negate}])
(when clamp [{:mod :gamepad-modifier-clamp}])
(when scale [{:mod :gamepad-modifier-scale}])))})
(f-map->map [f-map]
(merge (dissoc f-map :negate :clamp :scale) (bools->mods f-map)))
(f-device->device [f-device]
(update f-device :map #(mapv f-map->map %)))]
(update form-pb :driver #(mapv f-device->device %))))
(defn- gamepad-set-form-op [{:keys [node-id]} path value]
(let [old-pb (g/node-value node-id :pb)
old-form-pb (gamepad-pb->form-pb old-pb)
upd-form-pb (assoc-in old-form-pb path value)]
(g/set-property node-id :pb (form-pb->gamepad-pb upd-form-pb))))
(defmethod protobuf-form-data Input$GamepadMaps [node-id pb _def]
(let [gamepad-values (butlast (protobuf/enum-values Input$Gamepad)) ; skip MAX_GAMEPAD_COUNT
gamepad-type-values (protobuf/enum-values Input$GamepadType)]
{:navigation false
:form-ops {:user-data {:node-id node-id}
:set gamepad-set-form-op}
:sections [{:title "Gamepads"
:fields
[{:path [:driver]
:label "Gamepad"
:type :2panel
:panel-key {:path [:device] :type :string}
:panel-form {:sections
[{:fields
[{:path [:device]
:label "Device"
:type :string
:default "New device"}
{:path [:platform]
:label "Platform"
:type :string}
{:path [:dead-zone]
:label "Dead zone"
:type :number}
{:path [:map]
:label "Map"
:type :table
:columns [{:path [:input]
:label "Input"
:type :choicebox
:options (sort-by first (make-options gamepad-values))
:default (ffirst gamepad-values)}
{:path [:type]
:label "Type"
:type :choicebox
:options (sort-by first (make-options gamepad-type-values))
:default (ffirst gamepad-type-values)}
{:path [:index]
:label "Index"
:type :integer}
{:path [:negate]
:label "Negate"
:type :boolean}
{:path [:scale]
:label "Scale"
:type :boolean}
{:path [:clamp]
:label "Clamp"
:type :boolean}
{:path [:hat-mask]
:label "Hat Mask"
:type :integer}]}]}]}}]}]
:values (make-values (gamepad-pb->form-pb pb) [:driver])}))
(def texture-profiles-unsupported-formats
#{:texture-format-rgb16f
:texture-format-rgb32f
:texture-format-rgba16f
:texture-format-rgba32f
:texture-format-r16f
:texture-format-rg16f
:texture-format-r32f
:texture-format-rg32f
:texture-format-r-bc4
:texture-format-rg-bc5
:texture-format-rgb-bc1
:texture-format-rgb-etc1
:texture-format-rgba-pvrtc-2bppv1
:texture-format-rgba-pvrtc-4bppv1
:texture-format-rgb-pvrtc-2bppv1
:texture-format-rgb-pvrtc-4bppv1
:texture-format-rgba-bc3
:texture-format-rgba-bc7
:texture-format-rgba-etc2})
(defmethod protobuf-form-data Graphics$TextureProfiles [_node-id pb _def]
(let [os-values (protobuf/enum-values Graphics$PlatformProfile$OS)
format-values (distinct (protobuf/enum-values Graphics$TextureImage$TextureFormat))
format-values-filtered (filterv
(fn [fmt]
(not (contains? texture-profiles-unsupported-formats (first fmt))))
format-values)
profile-options (mapv #(do [% %]) (map :name (:profiles pb)))
;; name + compressor instance
available-compressors (mapv #(vector % (TextureCompression/getCompressor %)) (TextureCompression/getInstalledCompressorNames))]
{:navigation false
:sections
[{:title "Texture Profiles"
:fields
[{:path [:path-settings]
:label "Path Settings"
:type :table
:columns [{:path [:path]
:label "Path"
:type :string
:default "**"}
{:path [:profile]
:label "Profile"
:type :choicebox
:from-string str
:to-string str ; allow manual entry
:options (sort-by first profile-options)
:default "Default"}]}
{:path [:profiles]
:label "Profiles"
:type :2panel
:panel-key {:path [:name] :type :string :default "Default"}
:panel-form {:sections
[{:fields
[{:path [:platforms]
:label "Platforms"
:type :2panel
:panel-key {:path [:os]
:type :choicebox
:options (sort-by first (make-options os-values))
:default (ffirst os-values)}
:panel-form {:sections
[{:fields
[{:path [:formats]
:label "Formats"
:type :2panel
:panel-key {:path [:format]
:label "Format"
:type :choicebox
:options (sort-by first (make-options format-values-filtered))
:default (ffirst format-values-filtered)}
:panel-form-fn
(fn panel-form-fn [selected-format]
(let [texture-format (when (:format selected-format)
(protobuf/val->pb-enum Graphics$TextureImage$TextureFormat (:format selected-format)))
available-compressors-for-format (keep (fn [[compressor-name compressor-instance]]
(when (.supportsTextureFormat ^ITextureCompressor compressor-instance texture-format)
[compressor-name compressor-name]))
available-compressors)
available-presets-for-compressor (mapv
(fn [preset-name]
[preset-name (.getDisplayName (TextureCompression/getPreset preset-name))])
(TextureCompression/getPresetNamesForCompressor (:compressor selected-format)))]
{:sections
[{:fields
[{:path [:compressor]
:label "Compressor"
:type :choicebox
:options (make-options available-compressors-for-format) ; Unsorted.
:default (TextureCompressorUncompressed/TextureCompressorName)}
{:path [:compressor-preset]
:label "Compressor Preset"
:type :choicebox
:options available-presets-for-compressor ; Unsorted.
:default (ffirst available-presets-for-compressor)}]}]}))}
{:path [:mipmaps]
:type :boolean
:label "Mipmaps"}
{:path [:max-texture-size]
:type :integer
:label "Max texture size"
:default (protobuf/default Graphics$PlatformProfile :max-texture-size)
:optional true}
{:path [:premultiply-alpha]
:type :boolean
:label "Premultiply alpha"
:default (protobuf/default Graphics$PlatformProfile :premultiply-alpha)
:optional true}]}]}}]}]}}]}]}))
(defn produce-form-data
([node-id pb def]
(produce-form-data node-id pb def (protobuf-form-data node-id pb def)))
([node-id pb _def form-data]
(let [form-data (merge (default-form-ops node-id) form-data)]
(if (contains? form-data :values)
form-data
(assoc form-data :values (form-values form-data pb))))))
| 0 | 0.837224 | 1 | 0.837224 | game-dev | MEDIA | 0.405331 | game-dev | 0.69647 | 1 | 0.69647 |
vlad250906/Create-UfoPort | 27,414 | modules/create/src/main/java/com/simibubi/create/content/logistics/tunnel/BrassTunnelBlockEntity.java | package com.simibubi.create.content.logistics.tunnel;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.Set;
import javax.annotation.Nullable;
import org.apache.commons.lang3.tuple.Pair;
import com.simibubi.create.AllBlocks;
import com.simibubi.create.Create;
import com.simibubi.create.content.equipment.goggles.IHaveGoggleInformation;
import com.simibubi.create.content.kinetics.belt.BeltBlockEntity;
import com.simibubi.create.content.kinetics.belt.BeltHelper;
import com.simibubi.create.content.kinetics.belt.behaviour.DirectBeltInputBehaviour;
import com.simibubi.create.content.logistics.funnel.BeltFunnelBlock;
import com.simibubi.create.content.logistics.funnel.BeltFunnelBlock.Shape;
import com.simibubi.create.content.logistics.funnel.FunnelBlock;
import com.simibubi.create.foundation.blockEntity.behaviour.BlockEntityBehaviour;
import com.simibubi.create.foundation.blockEntity.behaviour.filtering.FilteringBehaviour;
import com.simibubi.create.foundation.blockEntity.behaviour.filtering.SidedFilteringBehaviour;
import com.simibubi.create.foundation.blockEntity.behaviour.scrollValue.INamedIconOptions;
import com.simibubi.create.foundation.blockEntity.behaviour.scrollValue.ScrollOptionBehaviour;
import com.simibubi.create.foundation.gui.AllIcons;
import com.simibubi.create.foundation.utility.BlockHelper;
import com.simibubi.create.foundation.utility.Components;
import com.simibubi.create.foundation.utility.Couple;
import com.simibubi.create.foundation.utility.Iterate;
import com.simibubi.create.foundation.utility.Lang;
import com.simibubi.create.foundation.utility.NBTHelper;
import com.simibubi.create.foundation.utility.NbtFixer;
import com.simibubi.create.infrastructure.config.AllConfigs;
import io.github.fabricators_of_create.porting_lib_ufo.transfer.item.ItemHandlerHelper;
import io.github.fabricators_of_create.porting_lib_ufo.util.NBTSerializer;
import net.fabricmc.fabric.api.transfer.v1.item.ItemVariant;
import net.fabricmc.fabric.api.transfer.v1.storage.Storage;
import net.fabricmc.fabric.api.transfer.v1.storage.base.SidedStorageBlockEntity;
import net.fabricmc.fabric.api.transfer.v1.transaction.TransactionContext;
import net.fabricmc.fabric.api.transfer.v1.transaction.base.SnapshotParticipant;
import net.minecraft.ChatFormatting;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.core.Direction.Axis;
import net.minecraft.core.Direction.AxisDirection;
import net.minecraft.core.HolderLookup.Provider;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.NbtUtils;
import net.minecraft.nbt.Tag;
import net.minecraft.network.chat.Component;
import net.minecraft.world.entity.item.ItemEntity;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.phys.Vec3;
public class BrassTunnelBlockEntity extends BeltTunnelBlockEntity implements IHaveGoggleInformation, SidedStorageBlockEntity {
SidedFilteringBehaviour filtering;
boolean connectedLeft;
boolean connectedRight;
ItemStack stackToDistribute;
Direction stackEnteredFrom;
float distributionProgress;
int distributionDistanceLeft;
int distributionDistanceRight;
int previousOutputIndex;
// <filtered, non-filtered>
Couple<List<Pair<BlockPos, Direction>>> distributionTargets;
private boolean syncedOutputActive;
private Set<BrassTunnelBlockEntity> syncSet;
protected ScrollOptionBehaviour<SelectionMode> selectionMode;
private BrassTunnelItemHandler tunnelCapability;
public final SnapshotParticipant<Data> snapshotParticipant = new SnapshotParticipant<>() {
@Override
protected Data createSnapshot() {
return new Data(stackToDistribute.copy(), distributionProgress, stackEnteredFrom);
}
@Override
protected void readSnapshot(Data snapshot) {
stackToDistribute = snapshot.stack;
distributionProgress = snapshot.progress;
stackEnteredFrom = snapshot.enteredFrom;
}
};
private record Data(ItemStack stack, float progress, Direction enteredFrom) {
}
public BrassTunnelBlockEntity(BlockEntityType<?> type, BlockPos pos, BlockState state) {
super(type, pos, state);
distributionTargets = Couple.create(ArrayList::new);
syncSet = new HashSet<>();
stackToDistribute = ItemStack.EMPTY;
stackEnteredFrom = null;
// fabric: beltCapability moved to cache, initialized on level set
tunnelCapability = new BrassTunnelItemHandler(this);
previousOutputIndex = 0;
syncedOutputActive = false;
}
@Override
public void addBehaviours(List<BlockEntityBehaviour> behaviours) {
super.addBehaviours(behaviours);
behaviours.add(selectionMode = new ScrollOptionBehaviour<>(SelectionMode.class,
Lang.translateDirect("logistics.when_multiple_outputs_available"), this, new BrassTunnelModeSlot()));
selectionMode.onlyActiveWhen(this::hasDistributionBehaviour);
// Propagate settings across connected tunnels
selectionMode.withCallback(setting -> {
for (boolean side : Iterate.trueAndFalse) {
if (!isConnected(side))
continue;
BrassTunnelBlockEntity adjacent = getAdjacent(side);
if (adjacent != null)
adjacent.selectionMode.setValue(setting);
}
});
}
@Override
public void tick() {
super.tick();
BeltBlockEntity beltBelow = BeltHelper.getSegmentBE(level, worldPosition.below());
if (distributionProgress > 0)
distributionProgress--;
if (beltBelow == null || beltBelow.getSpeed() == 0)
return;
if (stackToDistribute.isEmpty() && !syncedOutputActive)
return;
if (level.isClientSide && !isVirtual())
return;
if (distributionProgress == -1) {
distributionTargets.forEach(List::clear);
distributionDistanceLeft = 0;
distributionDistanceRight = 0;
syncSet.clear();
List<Pair<BrassTunnelBlockEntity, Direction>> validOutputs = gatherValidOutputs();
if (selectionMode.get() == SelectionMode.SYNCHRONIZE) {
boolean allEmpty = true;
boolean allFull = true;
for (BrassTunnelBlockEntity be : syncSet) {
boolean hasStack = !be.stackToDistribute.isEmpty();
allEmpty &= !hasStack;
allFull &= hasStack;
}
final boolean notifySyncedOut = !allEmpty;
if (allFull || allEmpty)
syncSet.forEach(be -> be.syncedOutputActive = notifySyncedOut);
}
if (validOutputs == null)
return;
if (stackToDistribute.isEmpty())
return;
for (Pair<BrassTunnelBlockEntity, Direction> pair : validOutputs) {
BrassTunnelBlockEntity tunnel = pair.getKey();
Direction output = pair.getValue();
if (insertIntoTunnel(tunnel, output, stackToDistribute, true) == null)
continue;
distributionTargets.get(!tunnel.flapFilterEmpty(output))
.add(Pair.of(tunnel.worldPosition, output));
int distance = tunnel.worldPosition.getX() + tunnel.worldPosition.getZ() - worldPosition.getX()
- worldPosition.getZ();
if (distance < 0)
distributionDistanceLeft = Math.max(distributionDistanceLeft, -distance);
else
distributionDistanceRight = Math.max(distributionDistanceRight, distance);
}
if (distributionTargets.getFirst()
.isEmpty()
&& distributionTargets.getSecond()
.isEmpty())
return;
if (selectionMode.get() != SelectionMode.SYNCHRONIZE || syncedOutputActive) {
distributionProgress = AllConfigs.server().logistics.brassTunnelTimer.get();
sendData();
}
return;
}
if (distributionProgress != 0)
return;
distributionTargets.forEach(list -> {
if (stackToDistribute.isEmpty())
return;
List<Pair<BrassTunnelBlockEntity, Direction>> validTargets = new ArrayList<>();
for (Pair<BlockPos, Direction> pair : list) {
BlockPos tunnelPos = pair.getKey();
Direction output = pair.getValue();
if (tunnelPos.equals(worldPosition) && output == stackEnteredFrom)
continue;
BlockEntity be = level.getBlockEntity(tunnelPos);
if (!(be instanceof BrassTunnelBlockEntity))
continue;
validTargets.add(Pair.of((BrassTunnelBlockEntity) be, output));
}
distribute(validTargets);
distributionProgress = -1;
});
}
private static Random rand = new Random();
private static Map<Pair<BrassTunnelBlockEntity, Direction>, ItemStack> distributed = new IdentityHashMap<>();
private static Set<Pair<BrassTunnelBlockEntity, Direction>> full = new HashSet<>();
private void distribute(List<Pair<BrassTunnelBlockEntity, Direction>> validTargets) {
int amountTargets = validTargets.size();
if (amountTargets == 0)
return;
distributed.clear();
full.clear();
int indexStart = previousOutputIndex % amountTargets;
SelectionMode mode = selectionMode.get();
boolean force = mode == SelectionMode.FORCED_ROUND_ROBIN || mode == SelectionMode.FORCED_SPLIT;
boolean split = mode == SelectionMode.FORCED_SPLIT || mode == SelectionMode.SPLIT;
boolean robin = mode == SelectionMode.FORCED_ROUND_ROBIN || mode == SelectionMode.ROUND_ROBIN;
if (mode == SelectionMode.RANDOMIZE)
indexStart = rand.nextInt(amountTargets);
if (mode == SelectionMode.PREFER_NEAREST || mode == SelectionMode.SYNCHRONIZE)
indexStart = 0;
ItemStack toDistribute = stackToDistribute.copy();
for (boolean distributeAgain : Iterate.trueAndFalse) {
ItemStack toDistributeThisCycle = null;
int remainingOutputs = amountTargets;
int leftovers = 0;
for (boolean simulate : Iterate.trueAndFalse) {
if (remainingOutputs == 0)
break;
leftovers = 0;
int index = indexStart;
int stackSize = toDistribute.getCount();
int splitStackSize = stackSize / remainingOutputs;
int splitRemainder = stackSize % remainingOutputs;
int visited = 0;
toDistributeThisCycle = toDistribute.copy();
if (!(force || split) && simulate)
continue;
while (visited < amountTargets) {
Pair<BrassTunnelBlockEntity, Direction> pair = validTargets.get(index);
BrassTunnelBlockEntity tunnel = pair.getKey();
Direction side = pair.getValue();
index = (index + 1) % amountTargets;
visited++;
if (full.contains(pair)) {
if (split && simulate)
remainingOutputs--;
continue;
}
int count = split ? splitStackSize + (splitRemainder > 0 ? 1 : 0) : stackSize;
ItemStack toOutput = ItemHandlerHelper.copyStackWithSize(toDistributeThisCycle, count);
// Grow by 1 to determine if target is full even after a successful transfer
boolean testWithIncreasedCount = distributed.containsKey(pair);
int increasedCount = testWithIncreasedCount ? distributed.get(pair)
.getCount() : 0;
if (testWithIncreasedCount)
toOutput.grow(increasedCount);
ItemStack remainder = insertIntoTunnel(tunnel, side, toOutput, true);
if (remainder == null || remainder.getCount() == (testWithIncreasedCount ? count + 1 : count)) {
if (force)
return;
if (split && simulate)
remainingOutputs--;
if (!simulate)
full.add(pair);
if (robin)
break;
continue;
} else if (!remainder.isEmpty() && !simulate) {
full.add(pair);
}
if (!simulate) {
toOutput.shrink(remainder.getCount());
distributed.put(pair, toOutput);
}
leftovers += remainder.getCount();
toDistributeThisCycle.shrink(count);
if (toDistributeThisCycle.isEmpty())
break;
splitRemainder--;
if (!split)
break;
}
}
toDistribute.setCount(toDistributeThisCycle.getCount() + leftovers);
if (leftovers == 0 && distributeAgain)
break;
if (!split)
break;
}
int failedTransferrals = 0;
for (Entry<Pair<BrassTunnelBlockEntity, Direction>, ItemStack> entry : distributed.entrySet()) {
Pair<BrassTunnelBlockEntity, Direction> pair = entry.getKey();
failedTransferrals += insertIntoTunnel(pair.getKey(), pair.getValue(), entry.getValue(), false).getCount();
}
toDistribute.grow(failedTransferrals);
stackToDistribute = ItemHandlerHelper.copyStackWithSize(stackToDistribute, toDistribute.getCount());
if (stackToDistribute.isEmpty())
stackEnteredFrom = null;
previousOutputIndex++;
previousOutputIndex %= amountTargets;
notifyUpdate();
}
public void setStackToDistribute(ItemStack stack, @Nullable Direction enteredFrom, @Nullable TransactionContext ctx) {
if (ctx != null) {
snapshotParticipant.updateSnapshots(ctx);
}
stackToDistribute = stack;
stackEnteredFrom = enteredFrom;
distributionProgress = -1;
}
public ItemStack getStackToDistribute() {
return stackToDistribute;
}
public List<ItemStack> grabAllStacksOfGroup(boolean simulate) {
List<ItemStack> list = new ArrayList<>();
ItemStack own = getStackToDistribute();
if (!own.isEmpty()) {
list.add(own);
if (!simulate)
setStackToDistribute(ItemStack.EMPTY, null, null);
}
for (boolean left : Iterate.trueAndFalse) {
BrassTunnelBlockEntity adjacent = this;
while (adjacent != null) {
if (!level.isLoaded(adjacent.getBlockPos()))
return null;
adjacent = adjacent.getAdjacent(left);
if (adjacent == null)
continue;
ItemStack other = adjacent.getStackToDistribute();
if (other.isEmpty())
continue;
list.add(other);
if (!simulate)
adjacent.setStackToDistribute(ItemStack.EMPTY, null, null);
}
}
return list;
}
@Nullable
protected ItemStack insertIntoTunnel(BrassTunnelBlockEntity tunnel, Direction side, ItemStack stack,
boolean simulate) {
if (stack.isEmpty())
return stack;
if (!tunnel.testFlapFilter(side, stack))
return null;
BeltBlockEntity below = BeltHelper.getSegmentBE(level, tunnel.worldPosition.below());
if (below == null)
return null;
BlockPos offset = tunnel.getBlockPos()
.below()
.relative(side);
DirectBeltInputBehaviour sideOutput = BlockEntityBehaviour.get(level, offset, DirectBeltInputBehaviour.TYPE);
if (sideOutput != null) {
if (!sideOutput.canInsertFromSide(side))
return null;
ItemStack result = sideOutput.handleInsertion(stack, side, simulate);
if (result.isEmpty() && !simulate)
tunnel.flap(side, false);
return result;
}
Direction movementFacing = below.getMovementFacing();
if (side == movementFacing)
if (!BlockHelper.hasBlockSolidSide(level.getBlockState(offset), level, offset, side.getOpposite())) {
BeltBlockEntity controllerBE = below.getControllerBE();
if (controllerBE == null)
return null;
if (!simulate) {
tunnel.flap(side, true);
ItemStack ejected = stack;
float beltMovementSpeed = below.getDirectionAwareBeltMovementSpeed();
float movementSpeed = Math.max(Math.abs(beltMovementSpeed), 1 / 8f);
int additionalOffset = beltMovementSpeed > 0 ? 1 : 0;
Vec3 outPos = BeltHelper.getVectorForOffset(controllerBE, below.index + additionalOffset);
Vec3 outMotion = Vec3.atLowerCornerOf(side.getNormal())
.scale(movementSpeed)
.add(0, 1 / 8f, 0);
outPos.add(outMotion.normalize());
ItemEntity entity = new ItemEntity(level, outPos.x, outPos.y + 6 / 16f, outPos.z, ejected);
entity.setDeltaMovement(outMotion);
entity.setDefaultPickUpDelay();
entity.hurtMarked = true;
level.addFreshEntity(entity);
}
return ItemStack.EMPTY;
}
return null;
}
public boolean testFlapFilter(Direction side, ItemStack stack) {
if (filtering == null)
return false;
if (filtering.get(side) == null) {
FilteringBehaviour adjacentFilter =
BlockEntityBehaviour.get(level, worldPosition.relative(side), FilteringBehaviour.TYPE);
if (adjacentFilter == null)
return true;
return adjacentFilter.test(stack);
}
return filtering.test(side, stack);
}
public boolean flapFilterEmpty(Direction side) {
if (filtering == null)
return false;
if (filtering.get(side) == null) {
FilteringBehaviour adjacentFilter =
BlockEntityBehaviour.get(level, worldPosition.relative(side), FilteringBehaviour.TYPE);
if (adjacentFilter == null)
return true;
return adjacentFilter.getFilter()
.isEmpty();
}
return filtering.getFilter(side)
.isEmpty();
}
@Override
public void initialize() {
if (filtering == null) {
filtering = createSidedFilter();
attachBehaviourLate(filtering);
}
super.initialize();
}
public boolean canInsert(Direction side, ItemStack stack) {
if (filtering != null && !filtering.test(side, stack))
return false;
if (!hasDistributionBehaviour())
return true;
if (!stackToDistribute.isEmpty())
return false;
return true;
}
public boolean hasDistributionBehaviour() {
if (flaps.isEmpty())
return false;
if (connectedLeft || connectedRight)
return true;
BlockState blockState = getBlockState();
if (!AllBlocks.BRASS_TUNNEL.has(blockState))
return false;
Axis axis = blockState.getValue(BrassTunnelBlock.HORIZONTAL_AXIS);
for (Direction direction : flaps.keySet())
if (direction.getAxis() != axis)
return true;
return false;
}
private List<Pair<BrassTunnelBlockEntity, Direction>> gatherValidOutputs() {
List<Pair<BrassTunnelBlockEntity, Direction>> validOutputs = new ArrayList<>();
boolean synchronize = selectionMode.get() == SelectionMode.SYNCHRONIZE;
addValidOutputsOf(this, validOutputs);
for (boolean left : Iterate.trueAndFalse) {
BrassTunnelBlockEntity adjacent = this;
while (adjacent != null) {
if (!level.isLoaded(adjacent.getBlockPos()))
return null;
adjacent = adjacent.getAdjacent(left);
if (adjacent == null)
continue;
addValidOutputsOf(adjacent, validOutputs);
}
}
if (!syncedOutputActive && synchronize)
return null;
return validOutputs;
}
private void addValidOutputsOf(BrassTunnelBlockEntity tunnelBE,
List<Pair<BrassTunnelBlockEntity, Direction>> validOutputs) {
syncSet.add(tunnelBE);
BeltBlockEntity below = BeltHelper.getSegmentBE(level, tunnelBE.worldPosition.below());
if (below == null)
return;
Direction movementFacing = below.getMovementFacing();
BlockState blockState = getBlockState();
if (!AllBlocks.BRASS_TUNNEL.has(blockState))
return;
boolean prioritizeSides = tunnelBE == this;
for (boolean sidePass : Iterate.trueAndFalse) {
if (!prioritizeSides && sidePass)
continue;
for (Direction direction : Iterate.horizontalDirections) {
if (direction == movementFacing && below.getSpeed() == 0)
continue;
if (prioritizeSides && sidePass == (direction.getAxis() == movementFacing.getAxis()))
continue;
if (direction == movementFacing.getOpposite())
continue;
if (!tunnelBE.sides.contains(direction))
continue;
BlockPos offset = tunnelBE.worldPosition.below()
.relative(direction);
BlockState potentialFunnel = level.getBlockState(offset.above());
if (potentialFunnel.getBlock() instanceof BeltFunnelBlock
&& potentialFunnel.getValue(BeltFunnelBlock.SHAPE) == Shape.PULLING
&& FunnelBlock.getFunnelFacing(potentialFunnel) == direction)
continue;
DirectBeltInputBehaviour inputBehaviour =
BlockEntityBehaviour.get(level, offset, DirectBeltInputBehaviour.TYPE);
if (inputBehaviour == null) {
if (direction == movementFacing)
if (!BlockHelper.hasBlockSolidSide(level.getBlockState(offset), level, offset,
direction.getOpposite()))
validOutputs.add(Pair.of(tunnelBE, direction));
continue;
}
if (inputBehaviour.canInsertFromSide(direction))
validOutputs.add(Pair.of(tunnelBE, direction));
continue;
}
}
}
@Override
public void addBehavioursDeferred(List<BlockEntityBehaviour> behaviours) {
super.addBehavioursDeferred(behaviours);
filtering = createSidedFilter();
behaviours.add(filtering);
}
protected SidedFilteringBehaviour createSidedFilter() {
return new SidedFilteringBehaviour(this, new BrassTunnelFilterSlot(), this::makeFilter,
this::isValidFaceForFilter);
}
private FilteringBehaviour makeFilter(Direction side, FilteringBehaviour filter) {
return filter;
}
private boolean isValidFaceForFilter(Direction side) {
return sides.contains(side);
}
@Override
public void write(CompoundTag compound, boolean clientPacket) {
compound.putBoolean("SyncedOutput", syncedOutputActive);
compound.putBoolean("ConnectedLeft", connectedLeft);
compound.putBoolean("ConnectedRight", connectedRight);
compound.put("StackToDistribute", NBTSerializer.serializeNBT(stackToDistribute));
if (stackEnteredFrom != null)
NBTHelper.writeEnum(compound, "StackEnteredFrom", stackEnteredFrom);
compound.putFloat("DistributionProgress", distributionProgress);
compound.putInt("PreviousIndex", previousOutputIndex);
compound.putInt("DistanceLeft", distributionDistanceLeft);
compound.putInt("DistanceRight", distributionDistanceRight);
for (boolean filtered : Iterate.trueAndFalse) {
compound.put(filtered ? "FilteredTargets" : "Targets",
NBTHelper.writeCompoundList(distributionTargets.get(filtered), pair -> {
CompoundTag nbt = new CompoundTag();
nbt.put("Pos", NbtUtils.writeBlockPos(pair.getKey()));
nbt.putInt("Face", pair.getValue()
.get3DDataValue());
return nbt;
}));
}
super.write(compound, clientPacket);
}
@Override
protected void read(CompoundTag compound, Provider reg, boolean clientPacket) {
boolean wasConnectedLeft = connectedLeft;
boolean wasConnectedRight = connectedRight;
syncedOutputActive = compound.getBoolean("SyncedOutput");
connectedLeft = compound.getBoolean("ConnectedLeft");
connectedRight = compound.getBoolean("ConnectedRight");
stackToDistribute = ItemStack.parseOptional(Create.getRegistryAccess(), compound.getCompound("StackToDistribute"));
stackEnteredFrom =
compound.contains("StackEnteredFrom") ? NBTHelper.readEnum(compound, "StackEnteredFrom", Direction.class)
: null;
distributionProgress = compound.getFloat("DistributionProgress");
previousOutputIndex = compound.getInt("PreviousIndex");
distributionDistanceLeft = compound.getInt("DistanceLeft");
distributionDistanceRight = compound.getInt("DistanceRight");
for (boolean filtered : Iterate.trueAndFalse) {
distributionTargets.set(filtered, NBTHelper
.readCompoundList(compound.getList(filtered ? "FilteredTargets" : "Targets", Tag.TAG_COMPOUND), nbt -> {
BlockPos pos = NbtFixer.readBlockPos(nbt, "Pos");
Direction face = Direction.from3DDataValue(nbt.getInt("Face"));
return Pair.of(pos, face);
}));
}
super.read(compound, reg, clientPacket);
if (!clientPacket)
return;
if (wasConnectedLeft != connectedLeft || wasConnectedRight != connectedRight) {
// requestModelDataUpdate();
if (hasLevel())
level.sendBlockUpdated(getBlockPos(), getBlockState(), getBlockState(), 16);
}
filtering.updateFilterPresence();
}
public boolean isConnected(boolean leftSide) {
return leftSide ? connectedLeft : connectedRight;
}
@Override
public void updateTunnelConnections() {
super.updateTunnelConnections();
boolean connectivityChanged = false;
boolean nowConnectedLeft = determineIfConnected(true);
boolean nowConnectedRight = determineIfConnected(false);
if (connectedLeft != nowConnectedLeft) {
connectedLeft = nowConnectedLeft;
connectivityChanged = true;
BrassTunnelBlockEntity adjacent = getAdjacent(true);
if (adjacent != null && !level.isClientSide) {
adjacent.updateTunnelConnections();
adjacent.selectionMode.setValue(selectionMode.getValue());
}
}
if (connectedRight != nowConnectedRight) {
connectedRight = nowConnectedRight;
connectivityChanged = true;
BrassTunnelBlockEntity adjacent = getAdjacent(false);
if (adjacent != null && !level.isClientSide) {
adjacent.updateTunnelConnections();
adjacent.selectionMode.setValue(selectionMode.getValue());
}
}
if (filtering != null)
filtering.updateFilterPresence();
if (connectivityChanged)
sendData();
}
protected boolean determineIfConnected(boolean leftSide) {
if (flaps.isEmpty())
return false;
BrassTunnelBlockEntity adjacentTunnelBE = getAdjacent(leftSide);
return adjacentTunnelBE != null && !adjacentTunnelBE.flaps.isEmpty();
}
@Nullable
protected BrassTunnelBlockEntity getAdjacent(boolean leftSide) {
if (!hasLevel())
return null;
BlockState blockState = getBlockState();
if (!AllBlocks.BRASS_TUNNEL.has(blockState))
return null;
Axis axis = blockState.getValue(BrassTunnelBlock.HORIZONTAL_AXIS);
Direction baseDirection = Direction.get(AxisDirection.POSITIVE, axis);
Direction direction = leftSide ? baseDirection.getCounterClockWise() : baseDirection.getClockWise();
BlockPos adjacentPos = worldPosition.relative(direction);
BlockState adjacentBlockState = level.getBlockState(adjacentPos);
if (!AllBlocks.BRASS_TUNNEL.has(adjacentBlockState))
return null;
if (adjacentBlockState.getValue(BrassTunnelBlock.HORIZONTAL_AXIS) != axis)
return null;
BlockEntity adjacentBE = level.getBlockEntity(adjacentPos);
if (adjacentBE.isRemoved())
return null;
if (!(adjacentBE instanceof BrassTunnelBlockEntity))
return null;
return (BrassTunnelBlockEntity) adjacentBE;
}
@Override
public void invalidate() {
super.invalidate();
}
@Override
public void destroy() {
super.destroy();
Block.popResource(level, worldPosition, stackToDistribute);
stackEnteredFrom = null;
}
@Override
public Storage<ItemVariant> getItemStorage(@Nullable Direction face) {
return tunnelCapability;
}
public Storage<ItemVariant> getBeltCapability() {
return belowProvider != null ? belowProvider.get(Direction.UP) : null;
}
public enum SelectionMode implements INamedIconOptions {
SPLIT(AllIcons.I_TUNNEL_SPLIT),
FORCED_SPLIT(AllIcons.I_TUNNEL_FORCED_SPLIT),
ROUND_ROBIN(AllIcons.I_TUNNEL_ROUND_ROBIN),
FORCED_ROUND_ROBIN(AllIcons.I_TUNNEL_FORCED_ROUND_ROBIN),
PREFER_NEAREST(AllIcons.I_TUNNEL_PREFER_NEAREST),
RANDOMIZE(AllIcons.I_TUNNEL_RANDOMIZE),
SYNCHRONIZE(AllIcons.I_TUNNEL_SYNCHRONIZE),
;
private final String translationKey;
private final AllIcons icon;
SelectionMode(AllIcons icon) {
this.icon = icon;
this.translationKey = "tunnel.selection_mode." + Lang.asId(name());
}
@Override
public AllIcons getIcon() {
return icon;
}
@Override
public String getTranslationKey() {
return translationKey;
}
}
public boolean canTakeItems() {
return stackToDistribute.isEmpty() && !syncedOutputActive;
}
@Override
public boolean addToGoggleTooltip(List<Component> tooltip, boolean isPlayerSneaking) {
List<ItemStack> allStacks = grabAllStacksOfGroup(true);
if (allStacks.isEmpty())
return false;
tooltip.add(componentSpacing.plainCopy()
.append(Lang.translateDirect("tooltip.brass_tunnel.contains"))
.withStyle(ChatFormatting.WHITE));
for (ItemStack item : allStacks) {
tooltip.add(componentSpacing.plainCopy()
.append(Lang.translateDirect("tooltip.brass_tunnel.contains_entry",
Components.translatable(item.getDescriptionId())
.getString(),
item.getCount()))
.withStyle(ChatFormatting.GRAY));
}
tooltip.add(componentSpacing.plainCopy()
.append(Lang.translateDirect("tooltip.brass_tunnel.retrieve"))
.withStyle(ChatFormatting.DARK_GRAY));
return true;
}
}
| 0 | 0.961107 | 1 | 0.961107 | game-dev | MEDIA | 0.939028 | game-dev | 0.973118 | 1 | 0.973118 |
orts/server | 24,124 | data/npc/scripts/Hairycles.lua | local keywordHandler = KeywordHandler:new()
local npcHandler = NpcHandler:new(keywordHandler)
NpcSystem.parseParameters(npcHandler)
function onCreatureAppear(cid) npcHandler:onCreatureAppear(cid) end
function onCreatureDisappear(cid) npcHandler:onCreatureDisappear(cid) end
function onCreatureSay(cid, type, msg) npcHandler:onCreatureSay(cid, type, msg) end
function onThink() npcHandler:onThink() end
local function greetCallback(cid)
if Player(cid):getStorageValue(Storage.TheApeCity.Questline) < 12 then
npcHandler:setMessage(MESSAGE_GREET, 'Oh! Hello! Hello! Did not notice! So {busy}.')
else
npcHandler:setMessage(MESSAGE_GREET, 'Be greeted, friend of the ape people. If you want to {trade}, just ask for my offers. If you are injured, ask for healing.')
end
return true
end
local function releasePlayer(cid)
if not Player(cid) then
return
end
npcHandler:releaseFocus(cid)
npcHandler:resetNpc(cid)
end
local function creatureSayCallback(cid, type, msg)
if not npcHandler:isFocused(cid) then
return false
end
local player = Player(cid)
local questProgress = player:getStorageValue(Storage.TheApeCity.Questline)
if msgcontains(msg, 'mission') then
if questProgress < 1 then
npcHandler:say('These are dire times for our people. Problems plenty are in this times. But me people not grant trust easy. Are you willing to prove you friend of ape people?', cid)
npcHandler.topic[cid] = 1
elseif questProgress == 1 then
if player:getStorageValue(Storage.QuestChests.WhisperMoss) == 1 then
npcHandler:say('Oh, you brought me whisper moss? Good hairless ape you are! Can me take it?', cid)
npcHandler.topic[cid] = 3
else
npcHandler:say('Please hurry. Bring me whisper moss from dworc lair. Make sure it is from dworc lair! Take it yourself only! If you need to hear background of all again, ask Hairycles for {background}.', cid)
end
elseif questProgress == 2 then
npcHandler:say({
'Whisper moss strong is, but me need liquid that humans have to make it work ...',
'Our raiders brought it from human settlement, it\'s called cough syrup. Go ask healer there for it.'
}, cid)
player:setStorageValue(Storage.TheApeCity.Questline, 3)
elseif questProgress == 3 then
npcHandler:say('You brought me that cough syrup from human healer me asked for?', cid)
npcHandler.topic[cid] = 4
elseif questProgress == 4 then
npcHandler:say('Little ape should be healthy soon. Me so happy is. Thank you again! But me suspect we in more trouble than we thought. Will you help us again?', cid)
npcHandler.topic[cid] = 5
elseif questProgress == 5 then
npcHandler:say('You got scroll from lizard village in south east?', cid)
npcHandler.topic[cid] = 7
elseif questProgress == 6 then
npcHandler:say({
'Ah yes that scroll. Sadly me not could read it yet. But the holy banana me insight gave! In dreams Hairycles saw where to find solution. ...',
'Me saw a stone with lizard signs and other signs at once. If you read signs and tell Hairycles, me will know how to read signs. ...',
'You go east to big desert. In desert there city. East of city under sand hidden tomb is. You will have to dig until you find it, so take shovel. ...',
'Go down in tomb until come to big level and then go down another. There you find a stone with signs between two huge red stones. ...',
'Read it and return to me. Are you up to that challenge?'
}, cid)
npcHandler.topic[cid] = 8
elseif questProgress == 7 then
if player:getStorageValue(Storage.TheApeCity.ParchmentDecyphering) == 1 then
npcHandler:say('Ah yes, you read the signs in tomb? Good! May me look into your mind to see what you saw?', cid)
npcHandler.topic[cid] = 9
else
npcHandler:say('You still don\'t know signs on stone, go and look for it in tomb east in desert.', cid)
end
elseif questProgress == 8 then
npcHandler:say({
'So much there is to do for Hairycles to prepare charm that will protect all ape people. ...',
'You can help more. To create charm of life me need mighty token of life! Best is egg of a regenerating beast as a hydra is. ...',
'Bring me egg of hydra please. You may find it in lair of Hydra at little lake south east of our lovely city Banuta! You think you can do?'
}, cid)
npcHandler.topic[cid] = 10
elseif questProgress == 9 then
npcHandler:say('You bring Hairycles egg of hydra?', cid)
npcHandler.topic[cid] = 11
elseif questProgress == 10 then
npcHandler:say({
'Last ingredient for charm of life is thing to lure magic. Only thing me know like that is mushroom called witches\' cap. Me was told it be found in isle called Fibula, where humans live. ...',
'Hidden under Fibula is a secret dungeon. There you will find witches\' cap. Are you willing to go there for good ape people?'
}, cid)
npcHandler.topic[cid] = 12
elseif questProgress == 11 then
npcHandler:say('You brought Hairycles witches\' cap from Fibula?', cid)
npcHandler.topic[cid] = 13
elseif questProgress == 12 then
npcHandler:say({
'Mighty life charm is protecting us now! But my people are still in danger. Danger from within. ...',
'Some of my people try to mimic lizards to become strong. Like lizards did before, this cult drinks strange fluid that lizards left when fled. ...',
'Under the city still the underground temple of lizards is. There you find casks with red fluid. Take crowbar and destroy three of them to stop this madness. Are you willing to do that?'
}, cid)
npcHandler.topic[cid] = 14
elseif questProgress == 13 then
if player:getStorageValue(Storage.TheApeCity.Casks) == 3 then
npcHandler:say('You do please Hairycles again, friend. Me hope madness will not spread further now. Perhaps you are ready for other mission.', cid)
player:setStorageValue(Storage.TheApeCity.Questline, 14)
else
npcHandler:say('Please destroy three casks in the complex beneath Banuta, so my people will come to senses again.', cid)
end
elseif questProgress == 14 then
npcHandler:say({
'Now that the false cult was stopped, we need to strengthen the spirit of my people. We need a symbol of our faith that ape people can see and touch. ...',
'Since you have proven a friend of the ape people I will grant you permission to enter the forbidden land. ...',
'To enter the forbidden land in the north-east of the jungle, look for a cave in the mountains east of it. There you will find the blind prophet. ...',
'Tell him Hairycles you sent and he will grant you entrance. ...',
'Forbidden land is home of Bong. Holy giant ape big as mountain. Don\'t annoy him in any way but look for a hair of holy ape. ...',
'You might find at places he has been, should be easy to see them since Bong is big. ...',
'Return a hair of the holy ape to me. Will you do this for Hairycles?'
}, cid)
npcHandler.topic[cid] = 15
elseif questProgress == 15 then
if player:getStorageValue(Storage.TheApeCity.HolyApeHair) == 1 then
npcHandler:say('You brought hair of holy ape?', cid)
npcHandler.topic[cid] = 16
else
npcHandler:say('Get a hair of holy ape from forbidden land in east. Speak with blind prophet in cave.', cid)
end
elseif questProgress == 16 then
npcHandler:say({
'You have proven yourself a friend, me will grant you permission to enter the deepest catacombs under Banuta which we have sealed in the past. ...',
'Me still can sense the evil presence there. We did not dare to go deeper and fight creatures of evil there. ...',
'You may go there, fight the evil and find the monument of the serpent god and destroy it with hammer me give to you. ...',
'Only then my people will be safe. Please tell Hairycles, will you go there?'
}, cid)
npcHandler.topic[cid] = 17
elseif questProgress == 17 then
if player:getStorageValue(Storage.TheApeCity.SnakeDestroyer) == 1 then
npcHandler:say({
'Finally my people are safe! You have done incredible good for ape people and one day even me brethren will recognise that. ...',
'I wish I could speak for all when me call you true friend but my people need time to get accustomed to change. ...',
'Let us hope one day whole Banuta will greet you as a friend. Perhaps you want to check me offers for special friends... or shamanic powers.'
}, cid)
player:setStorageValue(Storage.TheApeCity.Questline, 18)
player:addAchievement('Friend of the Apes')
else
npcHandler:say('Me know its much me asked for but go into the deepest catacombs under Banuta and destroy the monument of the serpent god.', cid)
end
else
npcHandler:say('No more missions await you right now, friend. Perhaps you want to check me offers for special friends... or shamanic powers.', cid)
end
elseif msgcontains(msg, 'background') then
if questProgress == 1
and player:getStorageValue(Storage.QuestChests.WhisperMoss) ~= 1 then
npcHandler:say({
'So listen, little ape was struck by plague. Hairycles not does know what plague it is. That is strange. Hairycles should know. But Hairycles learnt lots and lots ...',
'Me sure to make cure so strong to drive away all plague. But to create great cure me need powerful components ...',
'Me need whisper moss. Whisper moss growing south of human settlement is. Problem is, evil little dworcs harvest all whisper moss immediately ...',
'Me know they hoard some in their underground lair. My people raided dworcs often before humans came. So we know the moss is hidden in east of upper level of dworc lair ...',
'You go there and take good moss from evil dworcs. Talk with me about mission when having moss.'
}, cid)
end
elseif msgcontains(msg, 'outfit') or msgcontains(msg, 'shamanic') then
if questProgress == 18 then
if player:getStorageValue(Storage.TheApeCity.ShamanOutfit) ~= 1 then
npcHandler:say('Me truly proud of you, friend. You learn many about plants, charms and ape people. Me want grant you shamanic power now. You ready?', cid)
npcHandler.topic[cid] = 18
else
npcHandler:say('You already are shaman and doctor. Me proud of you.', cid)
end
else
npcHandler:say('You not have finished journey for wisdom yet, young human.', cid)
end
elseif msgcontains(msg, 'heal') then
if questProgress > 11 then
if player:getHealth() < 50 then
player:addHealth(50 - player:getHealth())
player:getPosition():sendMagicEffect(CONST_ME_MAGIC_BLUE)
elseif player:getCondition(CONDITION_FIRE) then
player:removeCondition(CONDITION_FIRE)
player:getPosition():sendMagicEffect(CONST_ME_MAGIC_GREEN)
elseif player:getCondition(CONDITION_POISON) then
player:removeCondition(CONDITION_POISON)
player:getPosition():sendMagicEffect(CONST_ME_MAGIC_RED)
else
npcHandler:say('You look for food and rest.', cid)
end
else
npcHandler:say('You look for food and rest.', cid)
end
elseif npcHandler.topic[cid] == 1 then
if msgcontains(msg, 'yes') then
npcHandler:say('To become friend of ape people a long and difficult way is. We do not trust easy but help is needed. Will you listen to story of Hairycles?', cid)
npcHandler.topic[cid] = 2
elseif msgcontains(msg, 'no') then
npcHandler:say('Hairycles sad is now. But perhaps you will change mind one day.', cid)
npcHandler.topic[cid] = 0
end
elseif npcHandler.topic[cid] == 2 then
if msgcontains(msg, 'yes') then
npcHandler:say({
'So listen, little ape was struck by plague. Hairycles not does know what plague it is. That is strange. Hairycles should know. But Hairycles learnt lots and lots ...',
'Me sure to make cure so strong to drive away all plague. But to create great cure me need powerful components ...',
'Me need whisper moss. Whisper moss growing south of human settlement is. Problem is, evil little dworcs harvest all whisper moss immediately ...',
'Me know they hoard some in their underground lair. My people raided dworcs often before humans came. So we know the moss is hidden in east of upper level of dworc lair ...',
'You go there and take good moss from evil dworcs. Talk with me about mission when having moss.'
}, cid)
player:setStorageValue(Storage.TheApeCity.Started, 1)
player:setStorageValue(Storage.TheApeCity.Questline, 1)
player:setStorageValue(Storage.TheApeCity.DworcDoor, 1)
elseif msgcontains(msg, 'no') then
npcHandler:say('Hairycles thought better of you.', cid)
addEvent(releasePlayer, 1000, cid)
end
npcHandler.topic[cid] = 0
elseif npcHandler.topic[cid] == 3 then
if msgcontains(msg, 'yes') then
if not player:removeItem(4838, 1) then
npcHandler:say('Stupid, you no have the moss me need. Go get it. It\'s somewhere in dworc lair. If you lost it, they might restocked it meanwhile. If you need to hear background of all again, ask Hairycles for {background}.', cid)
player:setStorageValue(Storage.QuestChests.WhisperMoss, -1)
return true
end
npcHandler:say('Ah yes! That\'s it. Thank you for bringing mighty whisper moss to Hairycles. It will help but still much is to be done. Just ask for other mission if you ready.', cid)
player:setStorageValue(Storage.TheApeCity.Questline, 2)
elseif msgcontains(msg, 'no') then
npcHandler:say('Strange being you are! Our people need help!', cid)
end
npcHandler.topic[cid] = 0
elseif npcHandler.topic[cid] == 4 then
if msgcontains(msg, 'yes') then
if not player:removeItem(4839, 1) then
npcHandler:say('No no, not right syrup you have. Go get other, get right health syrup.', cid)
return true
end
npcHandler:say('You so good! Brought syrup to me! Thank you, will prepare cure now. Just ask for {mission} if you want help again.', cid)
player:setStorageValue(Storage.TheApeCity.Questline, 4)
elseif msgcontains(msg, 'no') then
npcHandler:say('Please hurry, urgent it is!', cid)
end
npcHandler.topic[cid] = 0
elseif npcHandler.topic[cid] == 5 then
if msgcontains(msg, 'yes') then
npcHandler:say({
'So listen, please. Plague was not ordinary plague. That\'s why Hairycles could not heal at first. It is new curse of evil lizard people ...',
'I think curse on little one was only a try. We have to be prepared for big strike ...',
'Me need papers of lizard magician! For sure you find it in his hut in their dwelling. It\'s south east of jungle. Go look there please! Are you willing to go?'
}, cid)
npcHandler.topic[cid] = 6
elseif msgcontains(msg, 'no') then
npcHandler:say('Me sad. Me expected better from you!', cid)
addEvent(releasePlayer, 1000, cid)
npcHandler.topic[cid] = 0
end
elseif npcHandler.topic[cid] == 6 then
if msgcontains(msg, 'yes') then
npcHandler:say('Good thing that is! Report about your mission when have scroll.', cid)
player:setStorageValue(Storage.TheApeCity.Questline, 5)
player:setStorageValue(Storage.TheApeCity.ChorDoor, 1)
elseif msgcontains(msg, 'no') then
npcHandler:say('Me sad. Me expected better from you!', cid)
addEvent(releasePlayer, 1000, cid)
end
npcHandler.topic[cid] = 0
elseif npcHandler.topic[cid] == 7 then
if msgcontains(msg, 'yes') then
if not player:removeItem(5956, 1) then
if player:getStorageValue(Storage.QuestChests.OldParchment) == 1 then
npcHandler:say('That\'s bad news. If you lost it, only way to get other is to kill holy serpents. But you can\'t go there so you must ask adventurers who can.', cid)
else
npcHandler:say('No! That not scroll me looking for. Silly hairless ape you are. Go to village of lizards and get it there on your own!', cid)
end
return true
end
npcHandler:say('You brought scroll with lizard text? Good! I will see what text tells me! Come back when ready for other mission.', cid)
player:setStorageValue(Storage.TheApeCity.Questline, 6)
elseif msgcontains(msg, 'no') then
npcHandler:say('That\'s bad news. If you lost it, only way to get other is to kill holy serpents. But you can\'t go there so you must ask adventurers who can.', cid)
end
npcHandler.topic[cid] = 0
elseif npcHandler.topic[cid] == 8 then
if msgcontains(msg, 'yes') then
npcHandler:say('Good thing that is! Report about mission when you have read those signs.', cid)
player:setStorageValue(Storage.TheApeCity.Questline, 7)
elseif msgcontains(msg, 'no') then
npcHandler:say('Me sad. Me expected better from you!', cid)
addEvent(releasePlayer, 1000, cid)
end
npcHandler.topic[cid] = 0
elseif npcHandler.topic[cid] == 9 then
if msgcontains(msg, 'yes') then
npcHandler:say('Oh, so clear is all now! Easy it will be to read the signs now! Soon we will know what to do! Thank you again! Ask for mission if you feel ready.', cid)
player:setStorageValue(Storage.TheApeCity.Questline, 8)
player:getPosition():sendMagicEffect(CONST_ME_MAGIC_BLUE)
elseif msgcontains(msg, 'no') then
npcHandler:say('Me need to see it in your mind, other there is no way to proceed.', cid)
end
npcHandler.topic[cid] = 0
elseif npcHandler.topic[cid] == 10 then
if msgcontains(msg, 'yes') then
npcHandler:say('You brave hairless ape! Get me hydra egg. If you lose egg, you probably have to fight many, many hydras to get another.', cid)
player:setStorageValue(Storage.TheApeCity.Questline, 9)
elseif msgcontains(msg, 'no') then
npcHandler:say('Me sad. Me expected better from you!', cid)
addEvent(releasePlayer, 1000, cid)
end
npcHandler.topic[cid] = 0
elseif npcHandler.topic[cid] == 11 then
if msgcontains(msg, 'yes') then
if not player:removeItem(4850, 1) then
npcHandler:say('You not have egg of hydra. Please get one!', cid)
return true
end
npcHandler:say('Ah, the egg! Mighty warrior you be! Thank you. Hairycles will put it at safe place immediately.', cid)
player:setStorageValue(Storage.TheApeCity.Questline, 10)
elseif msgcontains(msg, 'no') then
npcHandler:say('Please hurry. Hairycles not knows when evil lizards strike again.', cid)
end
npcHandler.topic[cid] = 0
elseif npcHandler.topic[cid] == 12 then
if msgcontains(msg, 'yes') then
npcHandler:say('Long journey it will take, good luck to you.', cid)
player:setStorageValue(Storage.TheApeCity.Questline, 11)
player:setStorageValue(Storage.TheApeCity.FibulaDoor, 1)
elseif msgcontains(msg, 'no') then
npcHandler:say('Me sad. Me expected better from you!', cid)
addEvent(releasePlayer, 1000, cid)
end
npcHandler.topic[cid] = 0
elseif npcHandler.topic[cid] == 13 then
if msgcontains(msg, 'yes') then
if not player:removeItem(4840, 1) then
npcHandler:say('Not right mushroom you have. Find me a witches\' cap on Fibula!', cid)
return true
end
npcHandler:say('Incredible, you brought a witches\' cap! Now me can prepare mighty charm of life. Yet still other {missions} will await you, friend.', cid)
player:setStorageValue(Storage.TheApeCity.Questline, 12)
player:setStorageValue(Storage.TheApeCity.FibulaDoor, -1)
elseif msgcontains(msg, 'no') then
npcHandler:say('Please try to find me a witches\' cap on Fibula.', cid)
addEvent(releasePlayer, 1000, cid)
end
npcHandler.topic[cid] = 0
elseif npcHandler.topic[cid] == 14 then
if msgcontains(msg, 'yes') then
npcHandler:say('Hairycles sure you will make it. Good luck, friend.', cid)
player:setStorageValue(Storage.TheApeCity.Questline, 13)
player:setStorageValue(Storage.TheApeCity.CasksDoor, 1)
elseif msgcontains(msg, 'no') then
npcHandler:say('Me sad. Please reconsider.', cid)
end
npcHandler.topic[cid] = 0
elseif npcHandler.topic[cid] == 15 then
if msgcontains(msg, 'yes') then
npcHandler:say('Hairycles proud of you. Go and find holy hair. Good luck, friend.', cid)
player:setStorageValue(Storage.TheApeCity.Questline, 15)
elseif msgcontains(msg, 'no') then
npcHandler:say('Me sad. Please reconsider.', cid)
end
npcHandler.topic[cid] = 0
elseif npcHandler.topic[cid] == 16 then
if msgcontains(msg, 'yes') then
if not player:removeItem(4843, 1) then
npcHandler:say('You no have hair. You lost it? Go and look again.', cid)
player:setStorageValue(Storage.TheApeCity.HolyApeHair, -1)
return true
end
npcHandler:say('Incredible! You got a hair of holy Bong! This will raise the spirit of my people. You are truly a friend. But one last mission awaits you.', cid)
player:setStorageValue(Storage.TheApeCity.Questline, 16)
elseif msgcontains(msg, 'no') then
npcHandler:say('You no have hair. You lost it? Go and look again.', cid)
end
npcHandler.topic[cid] = 0
elseif npcHandler.topic[cid] == 17 then
if msgcontains(msg, 'yes') then
npcHandler:say('Hairycles sure you will make it. Just use hammer on all that looks like snake or lizard. Tell Hairycles if you succeed with mission.', cid)
player:setStorageValue(Storage.TheApeCity.Questline, 17)
player:addItem(4846, 1)
elseif msgcontains(msg, 'no') then
npcHandler:say('Me sad. Please reconsider.', cid)
end
npcHandler.topic[cid] = 0
elseif npcHandler.topic[cid] == 18 then
if msgcontains(msg, 'yes') then
npcHandler:say('Friend of the ape people! Take my gift and become me apprentice! Here is shaman clothing for you!', cid)
player:addOutfit(154)
player:addOutfit(158)
player:setStorageValue(Storage.TheApeCity.ShamanOutfit, 1)
player:getPosition():sendMagicEffect(CONST_ME_MAGIC_BLUE)
elseif msgcontains(msg, 'no') then
npcHandler:say('Come back if change mind.', cid)
end
npcHandler.topic[cid] = 0
elseif npcHandler.topic[cid] == 19 then
if msgcontains(msg, 'yes') then
if not player:removeItem(8111, 1) then
npcHandler:say('You have no cookie that I\'d like.', cid)
return true
end
player:setStorageValue(Storage.WhatAFoolishQuest.CookieDelivery.Hairycles, 1)
if player:getCookiesDelivered() == 10 then
player:addAchievement('Allow Cookies?')
end
Npc():getPosition():sendMagicEffect(CONST_ME_GIFT_WRAPS)
npcHandler:say('Thank you, you are ... YOU SON OF LIZARD!', cid)
addEvent(releasePlayer, 1000, cid)
elseif msgcontains(msg, 'no') then
npcHandler:say('I see.', cid)
end
npcHandler.topic[cid] = 0
end
return true
end
keywordHandler:addKeyword({'busy'}, StdModule.say, {npcHandler = npcHandler, text = 'Me great {wizard}. Me great doctor of {ape people}. Me know many plants. Me old and me have seen many things.'})
keywordHandler:addKeyword({'wizard'}, StdModule.say, {npcHandler = npcHandler, text = 'We see many things and learning quick. Merlkin magic learn quick, quick. We just watch and learn. Sometimes we try and learn.'})
keywordHandler:addKeyword({'things'}, StdModule.say, {npcHandler = npcHandler, text = 'Things not good now. Need helper to do {mission} for me people.'})
keywordHandler:addKeyword({'ape people'}, StdModule.say, {npcHandler = npcHandler, text = 'We be {kongra}, {sibang} and {merlkin}. Strange hairless ape people live in city called Port Hope.'})
keywordHandler:addKeyword({'kongra'}, StdModule.say, {npcHandler = npcHandler, text = 'Kongra verry strong. Kongra verry angry verry fast. Take care when kongra comes. Better climb on highest tree.'})
keywordHandler:addKeyword({'sibang'}, StdModule.say, {npcHandler = npcHandler, text = 'Sibang verry fast and funny. Sibang good gather food. Sibang know {jungle} well.'})
keywordHandler:addKeyword({'merlkin'}, StdModule.say, {npcHandler = npcHandler, text = 'Merlkin we are. Merlkin verry wise, merlkin learn many things quick. Teach other apes things a lot. Making {heal} and making {magic}.'})
keywordHandler:addKeyword({'magic'}, StdModule.say, {npcHandler = npcHandler, text = 'We see many things and learning quick. Merlkin magic learn quick, quick. We just watch and learn. Sometimes we try and learn.'})
keywordHandler:addKeyword({'jungle'}, StdModule.say, {npcHandler = npcHandler, text = 'Jungle is dangerous. Jungle also provides us food. Take care when in jungle and safe you be.'})
npcHandler:setCallback(CALLBACK_GREET, greetCallback)
npcHandler:setCallback(CALLBACK_MESSAGE_DEFAULT, creatureSayCallback)
npcHandler:addModule(FocusModule:new())
| 0 | 0.911539 | 1 | 0.911539 | game-dev | MEDIA | 0.950338 | game-dev | 0.754481 | 1 | 0.754481 |
mangosArchives/Mangos-One-server-old | 4,212 | src/game/TargetedMovementGenerator.h | /*
* Copyright (C) 2005-2013 MaNGOS <http://getmangos.com/>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef MANGOS_TARGETEDMOVEMENTGENERATOR_H
#define MANGOS_TARGETEDMOVEMENTGENERATOR_H
#include "MovementGenerator.h"
#include "FollowerReference.h"
#include "PathFinder.h"
#include "Unit.h"
class MANGOS_DLL_SPEC TargetedMovementGeneratorBase
{
public:
TargetedMovementGeneratorBase(Unit& target) { i_target.link(&target, this); }
void stopFollowing() { }
protected:
FollowerReference i_target;
};
template<class T, typename D>
class MANGOS_DLL_SPEC TargetedMovementGeneratorMedium
: public MovementGeneratorMedium< T, D >, public TargetedMovementGeneratorBase
{
protected:
TargetedMovementGeneratorMedium(Unit& target, float offset, float angle) :
TargetedMovementGeneratorBase(target), i_offset(offset), i_angle(angle),
m_speedChanged(false), i_targetReached(false), i_recheckDistance(0),
i_path(NULL)
{
}
~TargetedMovementGeneratorMedium() { delete i_path; }
public:
bool Update(T&, const uint32&);
bool IsReachable() const
{
return (i_path) ? (i_path->getPathType() & PATHFIND_NORMAL) : true;
}
Unit* GetTarget() const { return i_target.getTarget(); }
void unitSpeedChanged() { m_speedChanged = true; }
protected:
void _setTargetLocation(T&, bool updateDestination);
ShortTimeTracker i_recheckDistance;
float i_offset;
float i_angle;
bool m_speedChanged : 1;
bool i_targetReached : 1;
PathFinder* i_path;
};
template<class T>
class MANGOS_DLL_SPEC ChaseMovementGenerator : public TargetedMovementGeneratorMedium<T, ChaseMovementGenerator<T> >
{
public:
ChaseMovementGenerator(Unit& target)
: TargetedMovementGeneratorMedium<T, ChaseMovementGenerator<T> >(target) {}
ChaseMovementGenerator(Unit& target, float offset, float angle)
: TargetedMovementGeneratorMedium<T, ChaseMovementGenerator<T> >(target, offset, angle) {}
~ChaseMovementGenerator() {}
MovementGeneratorType GetMovementGeneratorType() const override { return CHASE_MOTION_TYPE; }
void Initialize(T&);
void Finalize(T&);
void Interrupt(T&);
void Reset(T&);
static void _clearUnitStateMove(T& u) { u.clearUnitState(UNIT_STAT_CHASE_MOVE); }
static void _addUnitStateMove(T& u) { u.addUnitState(UNIT_STAT_CHASE_MOVE); }
bool EnableWalking() const { return false;}
bool _lostTarget(T& u) const { return u.getVictim() != this->GetTarget(); }
void _reachTarget(T&);
};
template<class T>
class MANGOS_DLL_SPEC FollowMovementGenerator : public TargetedMovementGeneratorMedium<T, FollowMovementGenerator<T> >
{
public:
FollowMovementGenerator(Unit& target)
: TargetedMovementGeneratorMedium<T, FollowMovementGenerator<T> >(target) {}
FollowMovementGenerator(Unit& target, float offset, float angle)
: TargetedMovementGeneratorMedium<T, FollowMovementGenerator<T> >(target, offset, angle) {}
~FollowMovementGenerator() {}
MovementGeneratorType GetMovementGeneratorType() const override { return FOLLOW_MOTION_TYPE; }
void Initialize(T&);
void Finalize(T&);
void Interrupt(T&);
void Reset(T&);
static void _clearUnitStateMove(T& u) { u.clearUnitState(UNIT_STAT_FOLLOW_MOVE); }
static void _addUnitStateMove(T& u) { u.addUnitState(UNIT_STAT_FOLLOW_MOVE); }
bool EnableWalking() const;
bool _lostTarget(T&) const { return false; }
void _reachTarget(T&) {}
private:
void _updateSpeed(T& u);
};
#endif
| 0 | 0.8892 | 1 | 0.8892 | game-dev | MEDIA | 0.953797 | game-dev | 0.952041 | 1 | 0.952041 |
SimonN/LixD | 4,753 | src/physics/job/miner.d | module physics.job.miner;
import std.algorithm; // max
import hardware.sound;
import physics.job;
import physics.mask;
import physics.terchang;
class Miner : Job {
private:
// Counts how many pixels the miner has been moved down during the frames
// where the lix is not moving forward. This can happen due to terrain
// being removed below the lix. When this counter exceeds 4, the lix stops
// mining. This counter is reset after a miner swing.
int movedDownSinceSwing;
// Right before the miner advances forward, we check if the pixels the
// lix will move to are solid. So the i-th bit of this bitfield tells us if
// the pixel at the i-th future position is solid. Basically, the miner
// behaves as it has always behaved before August 2015 if no terrain is
// removed under him. It is only allowed to move down in two cases:
// (1) It's not moving forward.
// (2) It's moving forward, but the path was solid before moving.
bool[futureLength] futureGroundIsSolid;
public:
enum futureLength = 4;
enum maxGapDepth = 3;
override PhyuOrder updateOrder() const { return PhyuOrder.remover; }
override void perform()
{
lixxie.advanceFrame();
if (frame == 1) {
checkFutureGround();
antiShock(maxGapDepth);
}
else if (frame == 2) {
removeEarth();
movedDownSinceSwing = 0;
antiShock(maxGapDepth + 1); // DTODOGEOO: why +1?
}
else if (frame >= 3 && frame < 7) {
antiShock(maxGapDepth + 1);
}
else if (frame >= 7 && frame < 12) {
normalMovement();
}
else if (frame >= 12 || frame == 0) {
antiShock(maxGapDepth);
}
}
private:
void antiShock(in int resiliance) {
int downThisFrame = antiShockMoveDown(resiliance);
if (! lixxie.isSolid || movedDownSinceSwing > resiliance)
Faller.becomeWithAlreadyFallenPixels(lixxie, downThisFrame);
}
int antiShockMoveDown(in int maxDepth)
{
int downThisFrame = 0;
while (downThisFrame < maxDepth
&& ! lixxie.isSolid(0, 2 + downThisFrame)
) {
++downThisFrame;
++movedDownSinceSwing;
}
if (lixxie.isSolid(0, 2 + downThisFrame)) {
lixxie.moveDown(downThisFrame);
return downThisFrame;
}
else
// not solid: do nothing, we'll cancel the miner later
return 0;
}
void removeEarth()
{
TerrainDeletion tc;
tc.update = lixxie.outsideWorld.state.age;
tc.type = lixxie.facingRight
? TerrainDeletion.Type.mineRight : TerrainDeletion.Type.mineLeft;
tc.x = lixxie.ex - masks[tc.type].offsetX;
tc.y = lixxie.ey - masks[tc.type].offsetY;
lixxie.outsideWorld.physicsDrawer.add(tc);
if (lixxie.wouldHitSteel(masks[tc.type])) {
lixxie.outsideWorld.effect.addPickaxe(
lixxie.outsideWorld.state.age,
lixxie.outsideWorld.passport, lixxie.foot, lixxie.dir);
lixxie.turn();
lixxie.become(Ac.walker);
}
}
void checkFutureGround()
{
for (int j = 0; j < futureLength; ++j)
futureGroundIsSolid[j] = lixxie.isSolid(2 * j + 2,
// Use (movedDownSinceSwing - j) because the lix might have
// been moved down this frame already, and then it advances
// horizontally for a few frames
2 + (j+1) + max(movedDownSinceSwing - j, 0));
}
// normal movement == not the anti-shock movement
void normalMovement()
{
int downThisFrame;
if (frame != 9) {
lixxie.moveAhead();
if (movedDownSinceSwing == 0) {
lixxie.moveDown(1);
downThisFrame = 1;
}
else
movedDownSinceSwing -= 1;
}
assert (frame >= 7 && frame < 12);
immutable int future =
frame == 7 ? 0
: frame == 8 || frame == 9 ? 1
: frame == 10 ? 2 : 3;
if (futureGroundIsSolid[future])
// += instead of = should fix what I think is a bug in C++
downThisFrame += antiShockMoveDown(maxGapDepth);
immutable bool downTooFar = movedDownSinceSwing > maxGapDepth;
immutable bool solid = lixxie.isSolid(0, 2)
|| futureGroundIsSolid[future];
immutable bool leeway
= (frame == 7 || frame == 10) && lixxie.isSolid(0, 3);
if (downTooFar || (! solid && ! leeway))
Faller.becomeWithAlreadyFallenPixels(lixxie, downThisFrame);
}
}
| 0 | 0.910774 | 1 | 0.910774 | game-dev | MEDIA | 0.932909 | game-dev | 0.993794 | 1 | 0.993794 |
mr-kelly/KEngine | 3,969 | KEngine.UnityProject/Assets/KEngine.Editor/Editor/SettingModuleBuildHandler.cs | #region Copyright (c) 2015 KEngine / Kelly <http://github.com/mr-kelly>, All rights reserved.
// KEngine - Toolset and framework for Unity3D
// ===================================
//
// Date: 2015/12/03
// Author: Kelly
// Email: [email protected]
// Github: https://github.com/mr-kelly/KEngine
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library.
#endregion
using System;
using UnityEngine;
using System.IO;
using KEngine;
using UnityEditor;
using UnityEditor.Callbacks;
namespace KSFramework.Editor
{
/// <summary>
/// Build App阶段,进行处理的钩子
/// </summary>
public class SettingModuleBuildHandler
{
/// <summary>
/// 标记是否重复执行BeforeBuildApp
/// </summary>
private static bool _hasBeforeBuildApp = false;
/// <summary>
/// 复制文件事件, 可以进行加密行为
/// </summary>
public static Action<string> OnCopyFile;
/// <summary>
/// 完成Scene后,编译DLL后,未出APK前
/// </summary>
[PostProcessScene]
private static void OnPostProcessScene()
{
if (!_hasBeforeBuildApp && !EditorApplication.isPlayingOrWillChangePlaymode)
{
_hasBeforeBuildApp = true;
// 这里是编译前, Setting目录的配置文件拷贝进去StreamingAssetse
Debug.Log("[SettingModuleBuildHandler]Start copy settings...");
var editorLuaScriptPath = AppEngine.GetConfig("KEngine.Setting", "SettingCompiledPath");
//var ext = AppEngine.GetConfig("KEngine", "AssetBundleExt");
var luaCount = 0;
//var editorLuaScriptPath = Path.Combine(KResourceModule.EditorProductFullPath, compilePath);
editorLuaScriptPath = editorLuaScriptPath.Replace("\\", "/");
if (!Directory.Exists(editorLuaScriptPath))
{
return;
}
var toDir = "Assets/StreamingAssets/" + AppEngine.GetConfig("KEngine.Setting", "SettingResourcesPath"); // 文件夹名称获取
// 删除所有,确保没冗余
if (Directory.Exists(toDir))
{
Directory.Delete(toDir, true);
}
// 所有的Lua脚本拷贝到StreamingAssets
foreach (var path in Directory.GetFiles(editorLuaScriptPath, "*", SearchOption.AllDirectories))
{
var cleanPath = path.Replace("\\", "/");
var relativePath = cleanPath.Replace(editorLuaScriptPath + "/", "");
var toPath = Path.Combine(toDir, relativePath);
if (!Directory.Exists(Path.GetDirectoryName(toPath)))
Directory.CreateDirectory(Path.GetDirectoryName(toPath));
File.Copy(cleanPath, toPath, true);
if (OnCopyFile != null)
OnCopyFile(toPath);
luaCount++;
}
AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);
Debug.Log(string.Format("[SettingModuleBuildHandler]compile setting file count: {0}", luaCount));
}
}
/// <summary>
/// 构建完成,恢复标记
/// </summary>
[PostProcessBuild()]
static void OnPostProcessBuild(BuildTarget buildTarget, string pathToBuiltProject)
{
_hasBeforeBuildApp = false;
}
}
}
| 0 | 0.935688 | 1 | 0.935688 | game-dev | MEDIA | 0.849487 | game-dev | 0.858465 | 1 | 0.858465 |
DeltaV-Station/Delta-v | 3,997 | Content.Shared/_DV/Salvage/Systems/MiningPointsSystem.cs | using Content.Shared.Access.Systems;
using Content.Shared._DV.Salvage.Components;
using Content.Shared.Lathe;
using Robust.Shared.Audio.Systems;
namespace Content.Shared._DV.Salvage.Systems;
public sealed class MiningPointsSystem : EntitySystem
{
[Dependency] private readonly SharedAudioSystem _audio = default!;
[Dependency] private readonly SharedIdCardSystem _idCard = default!;
private EntityQuery<MiningPointsComponent> _query;
public override void Initialize()
{
base.Initialize();
_query = GetEntityQuery<MiningPointsComponent>();
SubscribeLocalEvent<MiningPointsLatheComponent, LatheStartPrintingEvent>(OnStartPrinting);
Subs.BuiEvents<MiningPointsLatheComponent>(LatheUiKey.Key, subs =>
{
subs.Event<LatheClaimMiningPointsMessage>(OnClaimMiningPoints);
});
}
#region Event Handlers
private void OnStartPrinting(Entity<MiningPointsLatheComponent> ent, ref LatheStartPrintingEvent args)
{
var points = args.Recipe.MiningPoints;
if (points > 0)
AddPoints(ent.Owner, points);
}
private void OnClaimMiningPoints(Entity<MiningPointsLatheComponent> ent, ref LatheClaimMiningPointsMessage args)
{
var user = args.Actor;
if (TryFindIdCard(user) is {} dest)
TransferAll(ent.Owner, dest);
}
#endregion
#region Public API
/// <summary>
/// Tries to find the user's id card and gets its <see cref="MiningPointsComponent"/>.
/// </summary>
/// <remarks>
/// Component is nullable for easy usage with the API due to Entity<T> not being usable for Entity<T?> arguments.
/// </remarks>
public Entity<MiningPointsComponent?>? TryFindIdCard(EntityUid user)
{
if (!_idCard.TryFindIdCard(user, out var idCard))
return null;
if (!_query.TryComp(idCard, out var comp))
return null;
return (idCard, comp);
}
/// <summary>
/// Returns true if the user has at least some number of points on their ID card.
/// </summary>
public bool UserHasPoints(EntityUid user, uint points)
{
if (TryFindIdCard(user)?.Comp is not {} comp)
return false;
return comp.Points >= points;
}
/// <summary>
/// Removes points from a holder, returning true if it succeeded.
/// </summary>
public bool RemovePoints(Entity<MiningPointsComponent?> ent, uint amount)
{
if (!_query.Resolve(ent, ref ent.Comp) || amount > ent.Comp.Points)
return false;
ent.Comp.Points -= amount;
Dirty(ent);
return true;
}
/// <summary>
/// Add points to a holder.
/// </summary>
public bool AddPoints(Entity<MiningPointsComponent?> ent, uint amount)
{
if (!_query.Resolve(ent, ref ent.Comp))
return false;
ent.Comp.Points += amount;
Dirty(ent);
return true;
}
/// <summary>
/// Transfer a number of points from source to destination.
/// Returns true if the transfer succeeded.
/// </summary>
public bool Transfer(Entity<MiningPointsComponent?> src, Entity<MiningPointsComponent?> dest, uint amount)
{
// don't make a sound or anything
if (amount == 0)
return true;
if (!_query.Resolve(src, ref src.Comp) || !_query.Resolve(dest, ref dest.Comp))
return false;
if (!RemovePoints(src, amount))
return false;
AddPoints(dest, amount);
_audio.PlayPvs(src.Comp.TransferSound, src);
return true;
}
/// <summary>
/// Transfers all points from source to destination.
/// Returns true if the transfer succeeded.
/// </summary>
public bool TransferAll(Entity<MiningPointsComponent?> src, Entity<MiningPointsComponent?> dest)
{
return _query.Resolve(src, ref src.Comp) && Transfer(src, dest, src.Comp.Points);
}
#endregion
}
| 0 | 0.962056 | 1 | 0.962056 | game-dev | MEDIA | 0.940918 | game-dev | 0.913907 | 1 | 0.913907 |
magefree/mage | 1,671 | Mage.Sets/src/mage/cards/b/BantCharm.java |
package mage.cards.b;
import java.util.UUID;
import mage.abilities.Mode;
import mage.abilities.effects.common.CounterTargetEffect;
import mage.abilities.effects.common.DestroyTargetEffect;
import mage.abilities.effects.common.PutOnLibraryTargetEffect;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.filter.FilterSpell;
import mage.target.TargetSpell;
import mage.target.common.TargetArtifactPermanent;
import mage.target.common.TargetCreaturePermanent;
/**
*
* @author North
*/
public final class BantCharm extends CardImpl {
private static final FilterSpell filter = new FilterSpell("instant spell");
static {
filter.add(CardType.INSTANT.getPredicate());
}
public BantCharm(UUID ownerId, CardSetInfo setInfo) {
super(ownerId,setInfo,new CardType[]{CardType.INSTANT},"{G}{W}{U}");
// Choose one - Destroy target artifact;
this.getSpellAbility().addEffect(new DestroyTargetEffect());
this.getSpellAbility().addTarget(new TargetArtifactPermanent());
// or put target creature on the bottom of its owner's library;
Mode mode = new Mode(new PutOnLibraryTargetEffect(false));
mode.addTarget(new TargetCreaturePermanent());
this.getSpellAbility().addMode(mode);
// or counter target instant spell.
mode = new Mode(new CounterTargetEffect());
mode.addTarget(new TargetSpell(filter));
this.getSpellAbility().addMode(mode);
}
private BantCharm(final BantCharm card) {
super(card);
}
@Override
public BantCharm copy() {
return new BantCharm(this);
}
}
| 0 | 0.906563 | 1 | 0.906563 | game-dev | MEDIA | 0.975902 | game-dev | 0.979774 | 1 | 0.979774 |
JamesTKhan/Mundus | 17,612 | editor/src/main/com/mbrlabs/mundus/editor/ui/modules/dialogs/AddTerrainChunksDialog.kt | package com.mbrlabs.mundus.editor.ui.modules.dialogs
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.graphics.g2d.Batch
import com.badlogic.gdx.math.Vector2
import com.badlogic.gdx.scenes.scene2d.ui.Label
import com.badlogic.gdx.utils.Array
import com.kotcrab.vis.ui.util.dialog.Dialogs
import com.kotcrab.vis.ui.widget.VisDialog
import com.kotcrab.vis.ui.widget.VisTable
import com.kotcrab.vis.ui.widget.VisTextButton
import com.kotcrab.vis.ui.widget.tabbedpane.Tab
import com.kotcrab.vis.ui.widget.tabbedpane.TabbedPane
import com.kotcrab.vis.ui.widget.tabbedpane.TabbedPaneListener
import com.mbrlabs.mundus.commons.assets.TerrainAsset
import com.mbrlabs.mundus.commons.assets.TextureAsset
import com.mbrlabs.mundus.commons.scene3d.GameObject
import com.mbrlabs.mundus.commons.scene3d.components.Component
import com.mbrlabs.mundus.commons.scene3d.components.TerrainComponent
import com.mbrlabs.mundus.commons.scene3d.components.TerrainManagerComponent
import com.mbrlabs.mundus.commons.scene3d.components.TerrainManagerComponent.ProceduralGeneration
import com.mbrlabs.mundus.commons.terrain.LodLevel
import com.mbrlabs.mundus.commons.terrain.Terrain
import com.mbrlabs.mundus.commons.terrain.TerrainLoader
import com.mbrlabs.mundus.editor.Mundus
import com.mbrlabs.mundus.editor.assets.EditorAssetManager
import com.mbrlabs.mundus.editor.assets.MetaSaver
import com.mbrlabs.mundus.editor.core.io.IOManager
import com.mbrlabs.mundus.editor.core.io.IOManagerProvider
import com.mbrlabs.mundus.editor.core.project.ProjectManager
import com.mbrlabs.mundus.editor.events.AssetImportEvent
import com.mbrlabs.mundus.editor.events.SceneGraphChangedEvent
import com.mbrlabs.mundus.editor.ui.UI
import com.mbrlabs.mundus.editor.ui.modules.dialogs.terrain.HeightMapTerrainTab
import com.mbrlabs.mundus.editor.ui.modules.dialogs.terrain.ProceduralTerrainTab
import com.mbrlabs.mundus.editor.utils.LoDUtils
import com.mbrlabs.mundus.editor.utils.ThreadLocalPools
import com.mbrlabs.mundus.editor.utils.createTerrainGO
import com.mbrlabs.mundus.editorcommons.exceptions.AssetAlreadyExistsException
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import java.util.concurrent.atomic.AtomicInteger
import kotlin.math.abs
/**
* @author JamesTKhan
* @version October 24, 2022
*/
class AddTerrainChunksDialog : BaseDialog("Add Terrain"), TabbedPaneListener {
private var loadingDialog: VisDialog? = null
private var parentGO: GameObject? = null
val root = VisTable()
private val tabbedPane = TabbedPane()
private val tabContainer = VisTable()
private val proceduralTerrainTab = ProceduralTerrainTab(this)
private val heightmapTerrainTab = HeightMapTerrainTab(this)
private var projectManager : ProjectManager
private val ioManager: IOManager
private var metaSaver : MetaSaver
init {
isResizable = true
projectManager = Mundus.inject()
ioManager = Mundus.inject<IOManagerProvider>().ioManager
metaSaver = Mundus.inject()
tabbedPane.addListener(this)
tabbedPane.add(proceduralTerrainTab)
tabbedPane.add(heightmapTerrainTab)
root.add(tabbedPane.table).growX().row()
root.add(tabContainer).expand().fill().row()
tabbedPane.switchTab(0)
root.padTop(6f).padRight(6f).padBottom(22f)
add(root).expand().fill().row()
}
private var generatingTerrain = false
private var generateLoD = false
private var terraformingThreads: AtomicInteger = AtomicInteger(0)
private var creationThreads: AtomicInteger = AtomicInteger(0)
private var assetsToTerraform = ConcurrentHashMap<Vector2, TerrainComponent>()
private var assetsToCreate = Array<IntArray>()
private var terrainChunkMatrix: TerrainChunkMatrix? = null
private var terrainName: String? = null
private var executor: ExecutorService? = null
private var terraformExecutor: ExecutorService? = null
override fun draw(batch: Batch?, parentAlpha: Float) {
val assetsToCreate = assetsToCreate.size > 0
if (assetsToCreate) {
runCreationThreads()
} else if (assetsToTerraform.size > 0) {
runTerraformingThreads()
}
if (terrainChunkMatrix?.isDone() == true) {
setupNeighborTerrains()
}
if (generatingTerrain) {
color.a = 0.4f
val label = loadingDialog!!.contentTable.getChild(0) as Label
label.setText("Creation threads: ${creationThreads.get()}\n"
+ "Terraform threads: ${terraformingThreads.get()}\n"
+ "Terraform Queue: ${assetsToTerraform.size}\n")
loadingDialog!!.pack()
if (!assetsToCreate && creationThreads.get() == 0 && assetsToTerraform.isEmpty()) {
generatingTerrain = false
color.a = 1.0f
loadingDialog?.hide()
Mundus.postEvent(SceneGraphChangedEvent())
// If we don't shut it down, may keep app running in background
executor?.shutdown()
executor = null
terraformExecutor?.shutdown()
terraformExecutor = null
}
}
super.draw(batch, parentAlpha)
}
fun createTerrainChunk(res: Int, width: Int, multipleTerrain: Boolean, xIteration: Int, yIteration: Int, name: String, splatMapResolution: Int, genLoD: Boolean) {
terrainName = name
executor = Executors.newFixedThreadPool(4)
terraformExecutor = Executors.newSingleThreadExecutor()
generateLoD = genLoD
val context = projectManager.current()
val sceneGraph = context.currScene.sceneGraph
val goID = projectManager.current().obtainID()
// Save context here so that the ID above is persisted in .pro file
ioManager.saveProjectContext(projectManager.current())
if (multipleTerrain) {
parentGO = GameObject(context.currScene.sceneGraph, "$terrainName Manager", goID)
parentGO!!.addComponent(createTerrainManagerComponent(parentGO!!))
} else {
parentGO = null
}
val layerName = "${terrainName}.layer"
if (projectManager.current().assetManager.assetExists(layerName)) {
Dialogs.showErrorDialog(UI, "Terrain Layer with name $terrainName already exists. Pick a different name or\nremove existing asset.")
return
}
// Before we start, make sure the terrain name does not already exist
val assetExists: Boolean
if (multipleTerrain) {
assetExists = checkMultipleTerrainAssetsExist(res, width, splatMapResolution, xIteration, yIteration)
} else {
assetExists = checkSingleTerrainAssetExists(res, width, splatMapResolution)
}
if (assetExists) return
terrainChunkMatrix = TerrainChunkMatrix(xIteration, yIteration)
generatingTerrain = true
loadingDialog = Dialogs.showOKDialog(UI, "Generating Terrain", "Generating ")
val button = loadingDialog!!.buttonsTable.getChild(0) as VisTextButton
button.isDisabled = true
if (multipleTerrain) {
sceneGraph.addGameObject(parentGO)
Mundus.postEvent(SceneGraphChangedEvent())
}
}
private fun checkMultipleTerrainAssetsExist(res: Int, width: Int, splatMapResolution: Int, xIteration: Int, yIteration: Int): Boolean {
var assetExists = false
for (i in 0 until xIteration) {
for (j in 0 until yIteration) {
// Before we start, make sure the terrain name does not already exist
val terraFileName = "${terrainName}$i-$j.terra.meta"
if (projectManager.current().assetManager.assetExists(terraFileName)) {
assetExists = true
assetsToCreate.clear()
Dialogs.showErrorDialog(UI, "Terrain with name $terrainName already exists. Pick a different name or\nremove existing asset.")
break
}
assetsToCreate.add(intArrayOf(res, width, splatMapResolution, i, j))
}
if (assetExists) break
}
return assetExists
}
private fun checkSingleTerrainAssetExists(res: Int, width: Int, splatMapResolution: Int): Boolean {
var assetExists = false
val terraFileName = "${terrainName}.terra.meta"
if (projectManager.current().assetManager.assetExists(terraFileName)) {
assetExists = true
assetsToCreate.clear()
Dialogs.showErrorDialog(UI, "Terrain with name $terrainName already exists. Pick a different name or\nremove existing asset.")
} else {
assetsToCreate.add(intArrayOf(res, width, splatMapResolution, 0, 0))
}
return assetExists
}
private fun createTerrainManagerComponent(parentGO: GameObject): TerrainManagerComponent {
var proceduralGeneration: ProceduralGeneration? = null
if (tabbedPane.activeTab is ProceduralTerrainTab) {
val proceduralTerrainTab = tabbedPane.activeTab as ProceduralTerrainTab
proceduralGeneration = ProceduralGeneration()
proceduralGeneration.minHeight = proceduralTerrainTab.getMinHeightValue()
proceduralGeneration.maxHeight = proceduralTerrainTab.getMaxHeightValue()
proceduralTerrainTab.uploadNoiseModifiers(proceduralGeneration.noiseModifiers)
}
return TerrainManagerComponent(parentGO, proceduralGeneration)
}
private fun runCreationThreads() {
val context = projectManager.current()
val sceneGraph = context.currScene.sceneGraph
// Start a new thread pool for creating the assets
// Create a new layer asset to assign to all terrain chunks
val terrainLayerAsset = projectManager.current().assetManager.createTerrainLayerAsset(terrainName!!)
// set base texture
val chessboard =
projectManager.current().assetManager.findAssetByID(EditorAssetManager.STANDARD_ASSET_TEXTURE_CHESSBOARD)
if (chessboard != null) {
terrainLayerAsset.splatBase = chessboard as TextureAsset
terrainLayerAsset.resolveDependencies(projectManager.current().assetManager.assetMap)
terrainLayerAsset.applyDependencies()
}
projectManager.current().assetManager.addAsset(terrainLayerAsset)
projectManager.current().assetManager.addModifiedAsset(terrainLayerAsset)
projectManager.current().assetManager.saveAsset(terrainLayerAsset)
for (arr in assetsToCreate) {
val goID = projectManager.current().obtainID()
// Submit thread job
this.executor?.submit {
creationThreads.addAndGet(1)
val res = arr[0]
val width = arr[1]
val splatMapResolution = arr[2]
val i = arr[3]
val j = arr[4]
val asset: TerrainAsset
val loader: TerrainLoader
try {
asset = createTerrainAsset(res, width, splatMapResolution, i, j)
asset.meta.terrain.terrainLayerAssetId = terrainLayerAsset.id
asset.lodLevels = if (generateLoD) arrayOf<LodLevel>() else null
loader = asset.startAsyncLoad()
} catch (ex: AssetAlreadyExistsException) {
Dialogs.showErrorDialog(stage, "An asset with that name already exists.")
executor?.shutdownNow()
creationThreads.decrementAndGet()
//break
return@submit
}
// post a Runnable to the rendering thread that processes the result
Gdx.app.postRunnable {
creationThreads.decrementAndGet()
asset.finishSyncLoad(loader)
asset.resolveDependencies(context.assetManager.assetMap)
metaSaver.save(asset.meta)
projectManager.current().assetManager.addAsset(asset)
val goName = if (isMultipleTerrain()) "${terrainName}$i-$j" else "$terrainName"
val terrainGO = createTerrainGO(sceneGraph, goID, goName, asset)
terrainGO.setLocalPosition((i * width).toFloat(), 0f, (j * width).toFloat())
val component = terrainGO.findComponentByType(Component.Type.TERRAIN) as TerrainComponent
context.currScene.terrains.add(component)
projectManager.current().assetManager.addNewAsset(asset)
Mundus.postEvent(AssetImportEvent(asset))
if (isMultipleTerrain()) {
parentGO!!.addChild(terrainGO)
} else {
sceneGraph.addGameObject(terrainGO)
Mundus.postEvent(SceneGraphChangedEvent())
}
// Now Queue it up for terraforming
assetsToTerraform[Vector2(i.toFloat(), j.toFloat())] = component
// Add generated terrain chunk to matrix
terrainChunkMatrix!!.addTerrain(i, j, component)
}
}
}
// After the jobs are submitted, clear the queue and shutdown executor (shuts down AFTER jobs complete)
assetsToCreate.clear()
}
private fun runTerraformingThreads() {
val grid = assetsToTerraform.entries.first().key
val component = assetsToTerraform.entries.first().value
val asset = component.terrainAsset
assetsToTerraform.remove(grid)
terraformExecutor?.submit {
terraformingThreads.addAndGet(1)
var minHeight = 0f
var maxHeight = 0f
if (tabbedPane.activeTab is ProceduralTerrainTab) {
minHeight = proceduralTerrainTab.getMinHeightValue()
maxHeight = proceduralTerrainTab.getMaxHeightValue()
proceduralTerrainTab.terraform(grid.x.toInt(), grid.y.toInt(), component)
} else if (tabbedPane.activeTab is HeightMapTerrainTab) {
minHeight = heightmapTerrainTab.getMinHeightValue()
maxHeight = heightmapTerrainTab.getMaxHeightValue()
heightmapTerrainTab.terraform(grid.x.toInt(), grid.y.toInt(), component)
}
asset.updateTerrainMaterial()
asset.terrain.update(ThreadLocalPools.vector3ThreadPool.get())
// post a Runnable to the rendering thread that processes the result
Gdx.app.postRunnable {
component.updateDimensions()
if (generateLoD) {
// Generate simplified results for LoD
val results = LoDUtils.buildTerrainLod(component, Terrain.LOD_SIMPLIFICATION_FACTORS, abs(maxHeight - minHeight))
// Convert to LodLevels with actual meshes
asset.lodLevels = LoDUtils.convertToLodLevels(asset.terrain.model, results)
}
terraformingThreads.decrementAndGet()
}
}
}
private fun createTerrainAsset(resolution: Int, width: Int, splatMapResolution: Int, i: Int, j: Int): TerrainAsset {
val terrainAssetName = if (isMultipleTerrain()) "${terrainName}$i-$j" else terrainName!!
// create asset
val asset: TerrainAsset = projectManager.current().assetManager.createTerraAssetAsync(
terrainAssetName, resolution, width, splatMapResolution)
return asset
}
/**
* Setups neighbor terrains for each terrain.
*/
private fun setupNeighborTerrains() {
val terrainComponents = terrainChunkMatrix!!.terrainComponents
// Bottom right corner is 0,0. Top neighbor is +y, right neighbor is +x
for (x in 0 until terrainComponents.size) {
for (y in 0 until terrainComponents[x].size) {
if (y+1 < terrainComponents[x].size) {
terrainComponents[x][y]!!.topNeighbor = terrainComponents[x][y+1]
}
if (x-1 >= 0) {
terrainComponents[x][y]!!.rightNeighbor = terrainComponents[x-1][y]
}
if (y-1 >= 0) {
terrainComponents[x][y]!!.bottomNeighbor = terrainComponents[x][y-1]
}
if (x+1 < terrainComponents.size) {
terrainComponents[x][y]!!.leftNeighbor = terrainComponents[x+1][y]
}
}
}
terrainChunkMatrix = null
}
private fun isMultipleTerrain(): Boolean = parentGO != null
inner class TerrainChunkMatrix(x: Int, y: Int) {
private var remainingTerrainComponents = x * y
val terrainComponents = Array(x) { Array<TerrainComponent?>(y) {null} }
fun addTerrain(x: Int, y: Int, terrainComponent: TerrainComponent) {
--remainingTerrainComponents
terrainComponents[x][y] = terrainComponent
}
fun isDone(): Boolean = remainingTerrainComponents == 0
}
override fun switchedTab(tab: Tab?) {
tabContainer.clearChildren()
tabContainer.add(tab?.contentTable).expand().fill()
}
override fun removedTab(tab: Tab?) {
}
override fun removedAllTabs() {
}
}
| 0 | 0.965996 | 1 | 0.965996 | game-dev | MEDIA | 0.749581 | game-dev | 0.972256 | 1 | 0.972256 |
FoxMCTeam/TenacityRecode-master | 5,169 | src/java/net/minecraft/command/CommandTitle.java | package net.minecraft.command;
import com.google.gson.JsonParseException;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.network.play.server.S45PacketTitle;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.BlockPos;
import net.minecraft.util.ChatComponentProcessor;
import net.minecraft.util.IChatComponent;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.List;
public class CommandTitle extends CommandBase
{
private static final Logger LOGGER = LogManager.getLogger();
/**
* Gets the name of the command
*/
public String getCommandName()
{
return "title";
}
/**
* Return the required permission level for this command.
*/
public int getRequiredPermissionLevel()
{
return 2;
}
/**
* Gets the usage string for the command.
*/
public String getCommandUsage(ICommandSender sender)
{
return "commands.title.usage";
}
/**
* Callback when the command is invoked
*/
public void processCommand(ICommandSender sender, String[] args) throws CommandException
{
if (args.length < 2)
{
throw new WrongUsageException("commands.title.usage", new Object[0]);
}
else
{
if (args.length < 3)
{
if ("title".equals(args[1]) || "subtitle".equals(args[1]))
{
throw new WrongUsageException("commands.title.usage.title", new Object[0]);
}
if ("times".equals(args[1]))
{
throw new WrongUsageException("commands.title.usage.times", new Object[0]);
}
}
EntityPlayerMP entityplayermp = getPlayer(sender, args[0]);
S45PacketTitle.Type s45packettitle$type = S45PacketTitle.Type.byName(args[1]);
if (s45packettitle$type != S45PacketTitle.Type.CLEAR && s45packettitle$type != S45PacketTitle.Type.RESET)
{
if (s45packettitle$type == S45PacketTitle.Type.TIMES)
{
if (args.length != 5)
{
throw new WrongUsageException("commands.title.usage", new Object[0]);
}
else
{
int i = parseInt(args[2]);
int j = parseInt(args[3]);
int k = parseInt(args[4]);
S45PacketTitle s45packettitle2 = new S45PacketTitle(i, j, k);
entityplayermp.playerNetServerHandler.sendPacket(s45packettitle2);
notifyOperators(sender, this, "commands.title.success", new Object[0]);
}
}
else if (args.length < 3)
{
throw new WrongUsageException("commands.title.usage", new Object[0]);
}
else
{
String s = buildString(args, 2);
IChatComponent ichatcomponent;
try
{
ichatcomponent = IChatComponent.Serializer.jsonToComponent(s);
}
catch (JsonParseException jsonparseexception)
{
Throwable throwable = ExceptionUtils.getRootCause(jsonparseexception);
throw new SyntaxErrorException("commands.tellraw.jsonException", new Object[] {throwable == null ? "" : throwable.getMessage()});
}
S45PacketTitle s45packettitle1 = new S45PacketTitle(s45packettitle$type, ChatComponentProcessor.processComponent(sender, ichatcomponent, entityplayermp));
entityplayermp.playerNetServerHandler.sendPacket(s45packettitle1);
notifyOperators(sender, this, "commands.title.success", new Object[0]);
}
}
else if (args.length != 2)
{
throw new WrongUsageException("commands.title.usage", new Object[0]);
}
else
{
S45PacketTitle s45packettitle = new S45PacketTitle(s45packettitle$type, (IChatComponent)null);
entityplayermp.playerNetServerHandler.sendPacket(s45packettitle);
notifyOperators(sender, this, "commands.title.success", new Object[0]);
}
}
}
public List<String> addTabCompletionOptions(ICommandSender sender, String[] args, BlockPos pos)
{
return args.length == 1 ? getListOfStringsMatchingLastWord(args, MinecraftServer.getServer().getAllUsernames()) : (args.length == 2 ? getListOfStringsMatchingLastWord(args, S45PacketTitle.Type.getNames()) : null);
}
/**
* Return whether the specified command parameter index is a username parameter.
*/
public boolean isUsernameIndex(String[] args, int index)
{
return index == 0;
}
}
| 0 | 0.893393 | 1 | 0.893393 | game-dev | MEDIA | 0.891012 | game-dev | 0.950917 | 1 | 0.950917 |
magcius/noclip.website | 48,322 | src/HeavyIron/HIEvent.ts | import { HIGame } from "./HIScene.js";
enum HIEventBFBB {
Unknown,
Enable,
Disable,
Visible,
Invisible,
EnterPlayer,
ExitPlayer,
TouchPlayer,
ControlOff,
ControlOn,
Reset,
Increment,
Decrement,
Open,
Close,
Toggle,
TeleportPlayer,
OutOfBounds,
Run,
Stop,
Expired,
Move,
Destroy,
Pause,
Play,
PlayOne,
PlayMaybe,
RoomStart,
Invalidate,
Tilt,
Untilt,
Arrive,
Mount,
Dismount,
Break,
Pickup,
Death,
Kill,
On,
Off,
NPCPatrolOn,
NPCPatrolOff,
NPCWanderOn,
NPCWanderOff,
NPCDetectOn,
NPCDetectOff,
NPCChaseOn,
NPCChaseOff,
NPCGoToSleep,
NPCWakeUp,
NPCRespawn,
PlayerDeath,
GiveChance,
GiveShinyObjects,
GiveHealth,
Press,
Unpress,
ArriveHalfway,
Hit,
ButtonPressAction,
Evaluate,
True,
False,
PadPressX,
PadPressSquare,
PadPressO,
PadPressTriangle,
PadPressL1,
PadPressL2,
PadPressR1,
PadPressR2,
PadPressStart,
PadPressSelect,
PadPressUp,
PadPressDown,
PadPressRight,
PadPressLeft,
FontBackdropOn,
FontBackdropOff,
UISelect,
UIUnselect,
UIFocusOn,
UIFocusOff,
CollisionOn,
CollisionOff,
Collision_Visible_On,
Collision_Visible_Off,
SceneBegin,
SceneEnd,
RoomBegin,
RoomEnd,
LobMasterShoot,
LobMasterReset,
FallToDeath,
UIFocusOn_Select,
UIFocusOff_Unselect,
Dispatcher_PadCfg_PresetA,
Dispatcher_PadCfg_PresetB,
Dispatcher_PadCfg_PresetC,
Dispatcher_PadCfg_PresetD,
Dispatcher_PadVibrateOn,
Dispatcher_PadVibrateOff,
Dispatcher_SoundMono,
Dispatcher_SoundStereo,
Dispatcher_SoundMasterIncrease,
Dispatcher_SoundMasterDecrease,
Dispatcher_SoundMusicIncrease,
Dispatcher_SoundMusicDecrease,
Dispatcher_SoundSFXIncrease,
Dispatcher_SoundSFXDecrease,
Dispatcher_IntroState_Sony,
Dispatcher_IntroState_Publisher,
Dispatcher_IntroState_Developer,
Dispatcher_IntroState_License,
Dispatcher_IntroState_Count,
Dispatcher_TitleState_Start,
Dispatcher_TitleState_Attract,
Dispatcher_TitleState_Count,
Dispatcher_LoadState_SelectMemCard,
Dispatcher_LoadState_SelectSlot,
Dispatcher_LoadState_Loading,
Dispatcher_LoadState_Count,
Dispatcher_OptionsState_Options,
Dispatcher_OptionsState_Count,
Dispatcher_SaveState_SelectMemCard,
Dispatcher_SaveState_SelectSlot,
Dispatcher_SaveState_Saving,
Dispatcher_SaveState_Count,
Dispatcher_PauseState_Pause,
Dispatcher_PauseState_Options,
Dispatcher_PauseState_Count,
Dispatcher_GameState_FirstTime,
Dispatcher_GameState_Play,
Dispatcher_GameState_LoseChance,
Dispatcher_GameState_GameOver,
Dispatcher_GameState_SceneSwitch,
Dispatcher_GameState_Dead,
Dispatcher_SetIntroState_Sony,
Dispatcher_SetIntroState_Publisher,
Dispatcher_SetIntroState_Developer,
Dispatcher_SetIntroState_License,
Dispatcher_SetIntroState_Count,
Dispatcher_SetTitleState_Start,
Dispatcher_SetTitleState_Attract,
Dispatcher_SetTitleState_Count,
Dispatcher_SetLoadState_SelectMemCard,
Dispatcher_SetLoadState_SelectSlot,
Dispatcher_SetLoadState_Loading,
Dispatcher_SetLoadState_Count,
Dispatcher_SetOptionsState_Options,
Dispatcher_SetOptionsState_Count,
Dispatcher_SetSaveState_SelectMemCard,
Dispatcher_SetSaveState_SelectSlot,
Dispatcher_SetSaveState_Saving,
Dispatcher_SetSaveState_Count,
Dispatcher_SetPauseState_Pause,
Dispatcher_SetPauseState_Options,
Dispatcher_SetPauseState_Count,
Dispatcher_SetGameState_FirstTime,
Dispatcher_SetGameState_Play,
Dispatcher_SetGameState_LoseChance,
Dispatcher_SetGameState_GameOver,
Dispatcher_SetGameState_SceneSwitch,
Dispatcher_SetGameState_Dead,
Digup,
Dispatcher_GameState_Exit,
Dispatcher_SetGameState_Exit,
LobMasterShootFromWidget,
Dispatcher_SLBack,
Dispatcher_SLCancel,
Dispatcher_SLRetry,
Dispatcher_SLSelectCard,
Dispatcher_SLSelectSlot,
Dispatcher_SLOkay,
VilHurtBoss,
Attack,
AttackOn,
AttackOff,
Drop,
VilReport_StartingIdle,
VilReport_StartingSleep,
VilReport_StartingGuard,
VilReport_StartingPatrol,
VilReport_StartingDazed,
VilReport_StartingLook,
VilReport_StartingListen,
VilReport_StartingInvestigate,
VilReport_StartingChase,
VilReport_StartingAttack,
VilReport_StartingRetreat,
Preload,
Done,
Arcto,
DigupReaction,
Dispatcher_StoreCheckPoint,
AnimPlay,
AnimPlayLoop,
AnimStop,
AnimPause,
AnimResume,
AnimTogglePause,
AnimPlayRandom,
AnimPlayMaybe,
SetSpeed,
Accelerate,
MoveToTarget,
SwingerFollow,
ShaggyMount,
ShaggyWitchDrop,
ShaggySwap,
ShaggyState,
ShaggyAction,
EnterEntity,
ExitEntity,
EnterEntityFLAG,
ExitEntityFLAG,
Drivenby,
FollowTarget,
FaceTarget,
WatchTarget,
ShaggyCollideOnly,
Shaggy1_ThrowTarget,
Shaggy8_CallEnable,
Shaggy8_CallDisable,
Shaggy8_SetMagnet,
Shaggy8_ClearMagnet,
StartMoving,
StopMoving,
Swoosh,
ShaggySetDown,
ShaggyGrabEnable,
ShaggyGrabDisable,
ShaggyGrabbed,
ShaggyThrown,
VilDoAction,
GangDoBossAction,
VilFakeChaseOn,
VilFakeChaseOff,
BossMMPushButton,
VilReport_DecayComplete,
VilGuardWidget,
TextureAnimateOn,
TextureAnimateOff,
TextureAnimateToggle,
ColorEffectOn,
ColorEffectOff,
ColorEffectToggle,
SetTextureAnimGroup,
SetTextureAnimSpeed,
TextureAnimateStep,
Emit,
Emitted,
TranslucentOn,
TranslucentOff,
TranslucentToggle,
VilGangTalkOn,
VilGangTalkOff,
GivePowerUp,
UnlockR001,
UnlockS001,
UnlockE001,
UnlockF001,
DisableGroupContents,
ShaggyPhysHack,
OccludeOn,
OccludeOff,
WaveSetLinear,
WaveSetRipple,
SituationLaugh,
SituationBossBattleGreenGhost,
SituationBossBattleRedBeard,
SituationBossBattleMasterMind,
SituationBossBattleBlacknight,
SituationPlayerScare,
SituationPlayerSafe,
SituationPlayerDanger,
SituationPlayerChaseBegin,
SituationPlayerChaseEnd,
SituationPlayerSeeShaggy,
SituationPlayerSeeFood,
SituationPlayerSeeToken,
SituationPlayerSeeScoobySnack,
SituationPlayerSeePowerup,
SituationPlayerSeeMonster,
SituationPlayerSuccess,
SituationPlayerFailure,
Dispatcher_ShowHud,
Dispatcher_HideHud,
Dispatcher_FadeOut,
SetRain,
SetSnow,
ShaggyMowerStopMode,
ScriptReset,
WaitForInput,
PlayMovie,
DefeatedMM,
Dispatcher_SetGameState_GameStats,
PlayMusic,
Forward,
Reverse,
PlayerRumbleTest,
PlayerRumbleLight,
PlayerRumbleMedium,
PlayerRumbleHeavy,
DispatcherScreenAdjustON,
DispatcherScreenAdjustOFF,
SetSkyDome,
ConnectToChild,
DuploWaveBegin,
DuploWaveComplete,
DuploNPCBorn,
DuploNPCKilled,
DuploExpiredMaxNPC,
DuploPause,
DuploResume,
SetGoo,
NPCScript_ScriptBegin,
NPCScript_ScriptEnd,
NPCScript_ScriptReady,
NPCScript_Halt,
NPCScript_SetPos,
NPCScript_SetDir,
NPCScript_LookNormal,
NPCScript_LookAlert,
NPCScript_FaceWidget,
NPCScript_FaceWidgetDone,
NPCScript_GotoWidget,
NPCScript_GotoWidgetDone,
NPCScript_AttackWidget,
NPCScript_AttackWidgetDone,
NPCScript_FollowWidget,
NPCScript_PlayAnim,
NPCScript_PlayAnimDone,
NPCScript_LeadPlayer,
SetText,
StartConversation,
EndConversation,
Switch,
AddText,
ClearText,
OpenTBox,
CloseTBox,
TalkBox_OnSignal0,
TalkBox_OnSignal1,
TalkBox_OnSignal2,
TalkBox_OnSignal3,
TalkBox_OnSignal4,
TalkBox_OnSignal5,
TalkBox_OnSignal6,
TalkBox_OnSignal7,
TalkBox_OnSignal8,
TalkBox_OnSignal9,
TalkBox_StopWait,
TalkBox_OnStart,
TalkBox_OnStop,
Hit_Melee,
Hit_BubbleBounce,
Hit_BubbleBash,
Hit_BubbleBowl,
Hit_PatrickSlam,
Hit_Throw,
Hit_PaddleLeft,
Hit_PaddleRight,
TaskBox_Initiate,
TaskBox_SetSuccess,
TaskBox_SetFailure,
TaskBox_OnAccept,
TaskBox_OnDecline,
TaskBox_OnComplete,
GenerateBoulder,
LaunchBoulderAtWidget,
LaunchBoulderAtPoint,
LaunchBoulderAtPlayer,
DuploSuperDuperDone,
DuploDuperIsDoner,
BusStopSwitchChr,
GroupUpdateTogether,
SetUpdateDistance,
TranslLocalX,
TranslLocalY,
TranslLocalZ,
TranslWorldX,
TranslWorldY,
TranslWorldZ,
RotLocalX,
RotLocalY,
RotLocalZ,
RotWorldX,
RotWorldY,
RotWorldZ,
TranslLocalXDone,
TranslLocalYDone,
TranslLocalZDone,
TranslWorldXDone,
TranslWorldYDone,
TranslWorldZDone,
RotLocalXDone,
RotLocalYDone,
RotLocalZDone,
RotWorldXDone,
RotWorldYDone,
RotWorldZDone,
Count1,
Count2,
Count3,
Count4,
Count5,
Count6,
Count7,
Count8,
Count9,
Count10,
Count11,
Count12,
Count13,
Count14,
Count15,
Count16,
Count17,
Count18,
Count19,
Count20,
SetState,
EnterSpongeBob,
EnterPatrick,
EnterSandy,
ExitSpongeBob,
ExitPatrick,
ExitSandy,
NPCSpecial_PlatformSnap,
NPCSpecial_PlatformFall,
GooSetWarb,
GooSetFreezeDuration,
GooMelt,
SetStateRange,
SetStateDelay,
SetTransitionDelay,
NPCFightOn,
NPCFightOff,
NPCSplineOKOn,
NPCSplineOKOff,
NPCKillQuietly,
HitHead,
HitUpperBody,
HitLeftArm,
HitRightArm,
HitLeftLeg,
HitRightLeg,
HitLowerBody,
GiveCurrLevelSocks,
GiveCurrLevelPickup,
SetCurrLevelSocks,
SetCurrLevelPickup,
TalkBox_OnYes,
TalkBox_OnNo,
Hit_Cruise,
DuploKillKids,
TalkBox_OnSignal10,
TalkBox_OnSignal11,
TalkBox_OnSignal12,
TalkBox_OnSignal13,
TalkBox_OnSignal14,
TalkBox_OnSignal15,
TalkBox_OnSignal16,
TalkBox_OnSignal17,
TalkBox_OnSignal18,
TalkBox_OnSignal19,
SpongeballOn,
SpongeballOff,
LaunchShrapnel,
NPCHPIncremented,
NPCHPDecremented,
NPCSetActiveOn,
NPCSetActiveOff,
PlrSwitchCharacter,
LevelBegin,
SceneReset,
SceneEnter,
SituationDestroyedTiki,
SituationDestroyedRobot,
SituationSeeWoodTiki,
SituationSeeLoveyTiki,
SituationSeeShhhTiki,
SituationSeeThunderTiki,
SituationSeeStoneTiki,
SituationSeeFodder,
SituationSeeHammer,
SituationSeeTarTar,
SituationSeeGLove,
SituationSeeMonsoon,
SituationSeeSleepyTime,
SituationSeeArf,
SituationSeeTubelets,
SituationSeeSlick,
SituationSeeKingJellyfish,
SituationSeePrawn,
SituationSeeDutchman,
SituationSeeSandyBoss,
SituationSeePatrickBoss,
SituationSeeSpongeBobBoss,
SituationSeeRobotPlankton,
UIChangeTexture,
NPCCheerForMe,
FastVisible,
FastInvisible,
ZipLineMount,
ZipLineDismount,
Target,
Fire,
CameraFXShake,
BulletTime,
Thrown,
UpdateAnimMatrices,
EnterCruise,
ExitCruise,
CruiseFired,
CruiseDied,
CruiseAddLife,
CruiseSetLife,
CruiseResetLife,
CameraCollideOff,
CameraCollideOn,
OnSliding,
OffSliding,
TimerSet,
TimerAdd,
NPCForceConverseStart,
MakeASplash,
CreditsStart,
CreditsStop,
CreditsEnded,
BubbleWipe,
SetLightKit,
SetOpacity,
TakeSocks,
DispatcherAssert,
Born,
PlatPause,
PlatUnpause,
StoreOptions,
RestoreOptions,
Count
}
enum HIEventTSSM
{
Unknown,
Enable,
Disable,
Visible,
Invisible,
EnterPlayer,
ExitPlayer,
TouchPlayer,
ControlOff,
ControlOn,
Reset,
Increment,
Decrement,
Open,
Close,
Toggle,
TeleportPlayer,
OutOfBounds,
Run,
Stop,
Expired,
Move,
Destroy,
Pause,
Play,
PlayOne,
PlayMaybe,
RoomStart,
Invalidate,
Tilt,
Untilt,
Arrive,
Mount,
Dismount,
Break,
Pickup,
Death,
Kill,
On,
Off,
NPCPatrolOn,
NPCPatrolOff,
NPCWanderOn,
NPCWanderOff,
NPCDetectOn,
NPCDetectOff,
NPCChaseOn,
NPCChaseOff,
NPCGoToSleep,
NPCWakeUp,
NPCRespawn,
PlayerDeath,
GiveChance,
GiveShinyObjects,
GiveHealth,
Press,
Unpress,
ArriveHalfway,
Hit,
ButtonPressAction,
Evaluate,
True,
False,
PadPressX,
PadPressSquare,
PadPressO,
PadPressTriangle,
PadPressL1,
PadPressL2,
PadPressR1,
PadPressR2,
PadPressStart,
PadPressSelect,
PadPressUp,
PadPressDown,
PadPressRight,
PadPressLeft,
FontBackdropOn,
FontBackdropOff,
UISelect,
UIUnselect,
UIFocusOn,
UIFocusOff,
CollisionOn,
CollisionOff,
Collision_Visible_On,
Collision_Visible_Off,
SceneBegin,
SceneEnd,
RoomBegin,
RoomEnd,
LobMasterShoot,
LobMasterReset,
FallToDeath,
UIFocusOn_Select,
UIFocusOff_Unselect,
Dispatcher_PadCfg_PresetA,
Dispatcher_PadCfg_PresetB,
Dispatcher_PadCfg_PresetC,
Dispatcher_PadCfg_PresetD,
Dispatcher_PadVibrateOn,
Dispatcher_PadVibrateOff,
Dispatcher_SoundMono,
Dispatcher_SoundStereo,
Dispatcher_SoundMasterIncrease,
Dispatcher_SoundMasterDecrease,
Dispatcher_SoundMusicIncrease,
Dispatcher_SoundMusicDecrease,
Dispatcher_SoundSFXIncrease,
Dispatcher_SoundSFXDecrease,
Dispatcher_IntroState_Sony,
Dispatcher_IntroState_Publisher,
Dispatcher_IntroState_Developer,
Dispatcher_IntroState_License,
Dispatcher_IntroState_Count,
Dispatcher_TitleState_Start,
Dispatcher_TitleState_Attract,
Dispatcher_TitleState_Count,
Dispatcher_LoadState_SelectMemCard,
Dispatcher_LoadState_SelectSlot,
Dispatcher_LoadState_Loading,
Dispatcher_LoadState_Count,
Dispatcher_OptionsState_Options,
Dispatcher_OptionsState_Count,
Dispatcher_SaveState_SelectMemCard,
Dispatcher_SaveState_SelectSlot,
Dispatcher_SaveState_Saving,
Dispatcher_SaveState_Count,
Dispatcher_PauseState_Pause,
Dispatcher_PauseState_Options,
Dispatcher_PauseState_Count,
Dispatcher_GameState_FirstTime,
Dispatcher_GameState_Play,
Dispatcher_GameState_LoseChance,
Dispatcher_GameState_GameOver,
Dispatcher_GameState_SceneSwitch,
Dispatcher_GameState_Dead,
Dispatcher_SetIntroState_Sony,
Dispatcher_SetIntroState_Publisher,
Dispatcher_SetIntroState_Developer,
Dispatcher_SetIntroState_License,
Dispatcher_SetIntroState_Count,
Dispatcher_SetTitleState_Start,
Dispatcher_SetTitleState_Attract,
Dispatcher_SetTitleState_Count,
Dispatcher_SetLoadState_SelectMemCard,
Dispatcher_SetLoadState_SelectSlot,
Dispatcher_SetLoadState_Loading,
Dispatcher_SetLoadState_Count,
Dispatcher_SetOptionsState_Options,
Dispatcher_SetOptionsState_Count,
Dispatcher_SetSaveState_SelectMemCard,
Dispatcher_SetSaveState_SelectSlot,
Dispatcher_SetSaveState_Saving,
Dispatcher_SetSaveState_Count,
Dispatcher_SetPauseState_Pause,
Dispatcher_SetPauseState_Options,
Dispatcher_SetPauseState_Count,
Dispatcher_SetGameState_FirstTime,
Dispatcher_SetGameState_Play,
Dispatcher_SetGameState_LoseChance,
Dispatcher_SetGameState_GameOver,
Dispatcher_SetGameState_SceneSwitch,
Dispatcher_SetGameState_Dead,
Digup,
Dispatcher_GameState_Exit,
Dispatcher_SetGameState_Exit,
LobMasterShootFromWidget,
Dispatcher_SLBack,
Dispatcher_SLCancel,
Dispatcher_SLRetry,
Dispatcher_SLSelectCard,
Dispatcher_SLSelectSlot,
Dispatcher_SLOkay,
VilHurtBoss,
Attack,
AttackOn,
AttackOff,
Drop,
UIAddChar,
UIDelChar,
UIStringEmpty,
UIStringFull,
UISendStringAsCheat,
UISetMaxChars,
UICheatOK,
UICheatBad,
VilReport_StartingChase,
VilReport_StartingAttack,
VilReport_StartingRetreat,
Preload,
Done,
Arcto,
DigupReaction,
Dispatcher_StoreCheckPoint,
AnimPlay,
AnimPlayLoop,
AnimStop,
AnimPause,
AnimResume,
AnimTogglePause,
AnimPlayRandom,
AnimPlayMaybe,
SetSpeed,
Accelerate,
MoveToTarget,
SwingerFollow,
Impact,
StartTimer,
FinishedTimer,
UIReset,
SetScaleFactor,
EnterEntity,
ExitEntity,
EnterEntityFLAG,
ExitEntityFLAG,
Drivenby,
FollowTarget,
FaceTarget,
WatchTarget,
CarChangeLaneRight,
CarChangeLaneLeft,
CarStart,
CarSetSwerveMode,
IncreaseSpeed,
DecreaseSpeed,
StartMoving,
StopMoving,
Swoosh,
TurretDestroyed,
NPCSpeakStop,
StartRumbleEffect,
NavigateTo,
NPCSpeakStart,
NPCAlert,
NPCPatrolDelay,
NPCScrambleActionEnd,
VilFakeChaseOff,
BossMMPushButton,
VilReport_DecayComplete,
VilGuardWidget,
TextureAnimateOn,
TextureAnimateOff,
TextureAnimateToggle,
ColorEffectOn,
ColorEffectOff,
ColorEffectToggle,
SetTextureAnimGroup,
SetTextureAnimSpeed,
TextureAnimateStep,
Emit,
Emitted,
TranslucentOn,
TranslucentOff,
TranslucentToggle,
ZipLineEnvDamage,
VilGangTalkOff,
GivePowerUp,
RaceTimerReset,
FireCruiseBubble,
CarSuccessAnimPlay,
CarFailureAnimPlay,
DisableGroupContents,
NPCCharge,
OccludeOn,
OccludeOff,
RaceTimerPause,
RaceTimerResume,
RaceTimerSetBestTime,
RaceTimerWarning1,
RaceTimerWarning2,
RaceTimerWarning3,
RingChallengeStart,
CarStop,
RingChallengeRun,
RingChallengeReset,
RingChallengeSuccess,
RingChallengeFailed,
FormationChanged,
ChargeResume,
ChargePause,
NPCChargeStop,
NPCChargeCompleted,
FormationChargeStart,
SituationPlayerSuccess,
SituationPlayerFailure,
Dispatcher_ShowHud,
Dispatcher_HideHud,
Dispatcher_FadeOut,
SetRain,
SetSnow,
ScriptNoop,
ScriptReset,
WaitForInput,
PlayMovie,
CelebrationAnimPlay,
Dispatcher_SetGameState_GameStats,
MusicNewSong,
Forward,
Reverse,
DeprecatedRumbleTest,
DeprecatedRumbleLight,
DeprecatedRumbleMedium,
DeprecatedRumbleHeavy,
DispatcherScreenAdjustON,
DispatcherScreenAdjustOFF,
SetSkyDome,
ConnectToChild,
DuploWaveBegin,
DuploWaveComplete,
DuploNPCBorn,
DuploNPCKilled,
DuploExpiredMaxNPC,
DuploPause,
DuploResume,
SetGoo,
NPCScript_ScriptBegin,
NPCScript_ScriptEnd,
NPCScript_ScriptReady,
NPCScript_Halt,
NPCScript_SetPos,
NPCScript_SetDir,
NPCScript_LookNormal,
NPCScript_LookAlert,
NPCScript_FaceWidget,
NPCScript_FaceWidgetDone,
NPCScript_GotoWidget,
NPCScript_GotoWidgetDone,
NPCScript_AttackWidget,
NPCScript_AttackWidgetDone,
NPCScript_FollowWidget,
NPCScript_PlayAnim,
NPCScript_PlayAnimDone,
NPCScript_LeadPlayer,
SetText,
StartConversation,
EndConversation,
Switch,
AddText,
ClearText,
OpenTBox,
CloseTBox,
TalkBox_OnSignal0,
TalkBox_OnSignal1,
TalkBox_OnSignal2,
TalkBox_OnSignal3,
TalkBox_OnSignal4,
TalkBox_OnSignal5,
TalkBox_OnSignal6,
TalkBox_OnSignal7,
TalkBox_OnSignal8,
TalkBox_OnSignal9,
TalkBox_StopWait,
TalkBox_OnStart,
TalkBox_OnStop,
Hit_Melee,
Hit_BubbleBounce,
Hit_BubbleBash,
Hit_BubbleBowl,
Hit_PatrickSlam,
Hit_Throw,
Hit_PaddleLeft,
Hit_PaddleRight,
TaskBox_Initiate,
TaskBox_SetSuccess,
TaskBox_SetFailure,
TaskBox_OnAccept,
TaskBox_OnDecline,
TaskBox_OnComplete,
GenerateBoulder,
LaunchBoulderAtWidget,
LaunchBoulderAtPoint,
LaunchBoulderAtPlayer,
DuploSuperDuperDone,
DuploDuperIsDoner,
BusStopSwitchChr,
GroupUpdateTogether,
SetUpdateDistance,
TranslLocalX,
TranslLocalY,
TranslLocalZ,
TranslWorldX,
TranslWorldY,
TranslWorldZ,
RotLocalX,
RotLocalY,
RotLocalZ,
RotWorldX,
RotWorldY,
RotWorldZ,
TranslLocalXDone,
TranslLocalYDone,
TranslLocalZDone,
TranslWorldXDone,
TranslWorldYDone,
TranslWorldZDone,
RotLocalXDone,
RotLocalYDone,
RotLocalZDone,
RotWorldXDone,
RotWorldYDone,
RotWorldZDone,
Count1,
Count2,
Count3,
Count4,
Count5,
Count6,
Count7,
Count8,
Count9,
Count10,
Count11,
Count12,
Count13,
Count14,
Count15,
Count16,
Count17,
Count18,
Count19,
Count20,
SetState,
EnterSpongeBob,
EnterPatrick,
EnterSandyUNUSED,
ExitSpongeBob,
ExitPatrick,
ExitSandyUNUSED,
NPCSpecial_PlatformSnap,
NPCSpecial_PlatformFall,
GooSetWarb,
GooSetFreezeDuration,
GooMelt,
SetStateRange,
SetStateDelay,
SetTransitionDelay,
NPCFightOn,
NPCFightOff,
NPCSplineOKOn,
NPCSplineOKOff,
NPCKillQuietly,
HitHead,
HitUpperBody,
HitLeftArm,
HitRightArm,
HitLeftLeg,
HitRightLeg,
HitLowerBody,
GiveCurrLevelSocks,
GiveCurrLevelPickup,
SetCurrLevelSocks,
SetCurrLevelPickup,
TalkBox_OnYes,
TalkBox_OnNo,
Hit_Cruise,
DuploKillKids,
TalkBox_OnSignal10,
TalkBox_OnSignal11,
TalkBox_OnSignal12,
TalkBox_OnSignal13,
TalkBox_OnSignal14,
TalkBox_OnSignal15,
TalkBox_OnSignal16,
TalkBox_OnSignal17,
TalkBox_OnSignal18,
TalkBox_OnSignal19,
SpongeballOn,
SpongeballOff,
LaunchShrapnel,
NPCHPIncremented,
NPCHPDecremented,
NPCSetActiveOn,
NPCSetActiveOff,
PlrSwitchCharacter,
LevelBegin,
SceneReset,
SceneEnter,
SituationDestroyedTiki,
SituationDestroyedRobot,
SituationSeeWoodTiki,
SituationSeeLoveyTiki,
SituationSeeShhhTiki,
SituationSeeThunderTiki,
SituationSeeStoneTiki,
SituationSeeFodder,
SituationSeeHammer,
SituationSeeTarTar,
SituationSeeGLove,
SituationSeeMonsoon,
SituationSeeSleepyTime,
SituationSeeArf,
SituationSeeTubelets,
SituationSeeSlick,
SituationSeeKingJellyfish,
SituationSeePrawn,
SituationSeeDutchman,
SituationSeeSandyBossUNUSED,
SituationSeePatrickBoss,
SituationSeeSpongeBobBoss,
SituationSeeRobotPlankton,
UIChangeTexture,
NPCCheerForMe,
FastVisible,
FastInvisible,
ZipLineMount,
ZipLineDismount,
Target,
Fire,
CameraFXShake,
BulletTime,
Thrown,
NPCPatrol,
EnterCruise,
ExitCruise,
CruiseFired,
CruiseDied,
CruiseAddLife,
CruiseSetLife,
CruiseResetLife,
CameraCollideOff,
CameraCollideOn,
OnSliding,
OffSliding,
TimerSet,
TimerAdd,
NPCForceConverseStart,
MakeASplash,
CreditsStart,
CreditsStop,
CreditsEnded,
BubbleWipe,
SetLightKit,
SetOpacity,
Dispatcher_SetSoundEffect,
Scale,
SetReference,
WarpSetWorld,
WarpSetTask,
WarpGo,
SetCount,
GetDashSpeed,
DashTrip,
DashBurst,
DashFast,
DashNormal,
DashSlow,
TakeSocks,
DispatcherAssert,
Born,
PlatPause,
PlatUnpause,
StoreOptions,
RestoreOptions,
UISetMotion,
UIMotionFinished,
UIMotionLoop,
DestructibleLaunch,
DestructibleRespawn,
KaboomStart,
KaboomStop,
NPCAttack,
NPCDefend,
TrainCarSpeed,
TrainJunctOut1,
TrainJunctOut2,
TrainJunctSwitch,
TrainJunctPassed,
TrainCarDetach,
TrainCarExplode,
Net_InitNetAPI,
Net_UpdateConnection,
Net_UpdateOnlineTask,
Net_UpdateUserList,
Net_CheckForNewContent,
Net_SelectDevice,
Net_SelectContent,
Net_VerifyContent,
Net_RemoveContent,
Net_SelectDeviceAfterRemove,
Net_ConfirmUseContentIdx,
Net_ConfirmNoUseContentIdx,
Net_NoContentInstalled,
Net_NoContentAvailable,
Net_NewContentAvailable,
SceneEnableDraw,
SceneDisableDraw,
LightningStart,
LightningStop,
ChangeBossUIStage,
StaticCameraStart,
StaticCameraEnd,
SetCameraStartOrientation,
NMESetMovepointPath,
NMEScareBegin,
NMEScareSkip,
NMESetMovepointGroup,
VentSetStateIdle,
VentSetStateWarn,
VentSetStateDamage,
VentSetStateOff,
WaterhoseStart,
WaterhoseStop,
WaterhoseSetLength,
Carried,
Explode,
JumpTo,
JumpOnSpawn,
PlayerHit,
StartFade,
FadeDownDone,
FadeUpDone,
Bounce,
LaunchNPC,
UpgradePowerUp,
BulletStreak,
SetFollowCameraOrientation,
HDRFade,
Start,
Success,
Failure,
EnableRestore,
DisableRestore,
NPCSpawn,
SpawnDone,
SpawnedNPCKilled,
SpawnedNPCNoHealth,
SpawnedNPCAllKilled,
SpawnedNPCAllNoHealth,
DashTimerSet,
DashNotOutOfTime,
DashOutOfTime,
ForceSceneReset,
NPCActive,
NPCInactive,
DuplicatorActive,
DuplicatorInactive,
DashEnterTunnel,
DashExitTunnel,
StopRumbleEffect,
DashChaseLasersOn,
DashChaseLasersOff,
JumpRandomOnSpawn,
Hit_Cartwheel,
UIVisible_FocusOn_Select,
UIFocusOff_Unselect_Invisible,
CopyReference,
UIMotionFinishedIn,
UIMotionFinishedOut,
UISignalActivateScreen,
UISignalDeactivateScreen,
UISignalActivatedScreen,
UISignalSwitchScreens,
UISignalStartFadeOut,
UISignalStartFadeIn,
UISignalScreenMotionInDone,
UISignalScreenMotionOutDone,
UISignalMainBoxInDone,
UISignalMainBoxOutDone,
UIResetMotion,
UIEnableHDR,
UIDisableHDR,
UIBrighten,
UIUnbrighten,
UISignalDeactivatedScreen,
NPCDetectAlways,
NPCDetectNever,
NPCDetectNormal,
NPCFightDefault,
CameraCollidePartial,
MusicTempSong,
ateCounterValue,
Count0,
RotToAbsoluteX,
RotToAbsoluteY,
RotToAbsoluteZ,
TriggerAnim,
TriggeredAnimDone,
UISignalMore,
UISignalNoMore,
UISignalLess,
UISignalNoLess,
UISignalUp,
UISignalDown,
UISignalSyncToCurrent,
UISignalEffect,
FreezePlayer,
UnfreezePlayer,
UISignalMapStart,
UISignalMapEnd,
TransToAbsoluteX,
TransToAbsoluteY,
TransToAbsoluteZ,
JSPVisibilityIncrement,
JSPVisibilityDecrement,
EnterCamera,
ExitCamera,
PadPressE,
SetDashJumpParameters,
ViperFacePlayer,
ViperFaceMovement,
RequestStart,
UIAutoMenuRun,
UIAutoMenuRunUp,
UIAutoMenuRunDown,
UIAutoMenuRunLeft,
UIAutoMenuRunRight,
IncrementSuccess,
DecrementSuccess,
IncrementFailed,
DecrementFailed,
MusicTempSongStop,
NPCScrambleActionBegin,
NPCScrambleAlert,
NPCSetTurretAttackRadius,
GooFreezeStart,
GooMeltStart,
NPCNotice,
BossStageSet,
BossStageBegan,
BossStageEnded,
BossStageBeganA,
BossStageEndedA,
BossStageBeganB,
BossStageEndedB,
BossStageBeganC,
BossStageEndedC,
VisibilityCullOn,
VisibilityCullOff,
RBandCameraStart,
RBandCameraEnd,
MindyStart,
MindyEnd,
FlamethrowerStart,
FlamethrowerStop,
FlamethrowerSetLength,
NPCTakeNoDamageOn,
NPCTakeNoDamageOff,
StaticCameraStartFOVFilter,
StaticCameraRestoreFOV,
UIXboxDemoExitToLauncher,
Spawn,
Spawned,
CreditsSetDest,
AllowAttractMode,
DisallowAttractMode,
RocketAttack,
CollisionReset,
AutoSave,
OpenBonus,
FlagLevel,
LevelEnd,
Net_GetLocalContentDevice,
Dispatcher_PauseGame_Safe,
OverrideFreqency,
ResetFrequency,
SetShotDelay,
SetShotsInGroup,
Dispatcher_UserSelectYes,
Dispatcher_UserSelectNo,
Dispatcher_UserSelectBack,
LaunchFireWorks,
Dispatcher_UserSelectionReset,
SetAsBounceBack,
UIResetUnlockables,
UISysMessageWaitResponse,
UISysMessageWaitConfirm,
UISysMessageConfirm,
UISysMessageAccept,
UISysMessageDecline,
SetAsBounceBack_Cancel,
Dispatcher_PauseGame,
PattyWagonStartEngine,
PattyWagonStopEngine,
SpawnBubblesOn,
SpawnBubblesOff,
Net_XBLiveToggleSignIn,
Net_XBLiveManageFriends,
ApplyOnResetOn,
ApplyOnResetOff,
SnapTo,
Throw,
FirstZipLine,
FirstLedgeGrab,
FirstIncredimeterPickup,
UISparkTrail,
UIGetBattleScenes,
UIBattleScenesAvailable,
UIBattleScenesNotAvailable,
Net_XBLiveToggleAppearOnline,
Sys_ReturnPrevScreen,
Sys_Nope,
Dispatcher_SubtitlesOn,
Dispatcher_SubtitlesOff,
UISetBoxMapping,
TBoxPlayerEjected,
DamagePlayer,
FirstHealthPickup,
TokenPickupComplete,
Dispatcher_LoadSavePromptDead,
UIFlipVisibility,
Net_XBLiveRebootToDashboard,
FirstPowerupPoint,
Count
}
export enum HIEvent {
// BFBB
Unknown,
Enable,
Disable,
Visible,
Invisible,
EnterPlayer,
ExitPlayer,
TouchPlayer,
ControlOff,
ControlOn,
Reset,
Increment,
Decrement,
Open,
Close,
Toggle,
TeleportPlayer,
OutOfBounds,
Run,
Stop,
Expired,
Move,
Destroy,
Pause,
Play,
PlayOne,
PlayMaybe,
RoomStart,
Invalidate,
Tilt,
Untilt,
Arrive,
Mount,
Dismount,
Break,
Pickup,
Death,
Kill,
On,
Off,
NPCPatrolOn,
NPCPatrolOff,
NPCWanderOn,
NPCWanderOff,
NPCDetectOn,
NPCDetectOff,
NPCChaseOn,
NPCChaseOff,
NPCGoToSleep,
NPCWakeUp,
NPCRespawn,
PlayerDeath,
GiveChance,
GiveShinyObjects,
GiveHealth,
Press,
Unpress,
ArriveHalfway,
Hit,
ButtonPressAction,
Evaluate,
True,
False,
PadPressX,
PadPressSquare,
PadPressO,
PadPressTriangle,
PadPressL1,
PadPressL2,
PadPressR1,
PadPressR2,
PadPressStart,
PadPressSelect,
PadPressUp,
PadPressDown,
PadPressRight,
PadPressLeft,
FontBackdropOn,
FontBackdropOff,
UISelect,
UIUnselect,
UIFocusOn,
UIFocusOff,
CollisionOn,
CollisionOff,
Collision_Visible_On,
Collision_Visible_Off,
SceneBegin,
SceneEnd,
RoomBegin,
RoomEnd,
LobMasterShoot,
LobMasterReset,
FallToDeath,
UIFocusOn_Select,
UIFocusOff_Unselect,
Dispatcher_PadCfg_PresetA,
Dispatcher_PadCfg_PresetB,
Dispatcher_PadCfg_PresetC,
Dispatcher_PadCfg_PresetD,
Dispatcher_PadVibrateOn,
Dispatcher_PadVibrateOff,
Dispatcher_SoundMono,
Dispatcher_SoundStereo,
Dispatcher_SoundMasterIncrease,
Dispatcher_SoundMasterDecrease,
Dispatcher_SoundMusicIncrease,
Dispatcher_SoundMusicDecrease,
Dispatcher_SoundSFXIncrease,
Dispatcher_SoundSFXDecrease,
Dispatcher_IntroState_Sony,
Dispatcher_IntroState_Publisher,
Dispatcher_IntroState_Developer,
Dispatcher_IntroState_License,
Dispatcher_IntroState_Count,
Dispatcher_TitleState_Start,
Dispatcher_TitleState_Attract,
Dispatcher_TitleState_Count,
Dispatcher_LoadState_SelectMemCard,
Dispatcher_LoadState_SelectSlot,
Dispatcher_LoadState_Loading,
Dispatcher_LoadState_Count,
Dispatcher_OptionsState_Options,
Dispatcher_OptionsState_Count,
Dispatcher_SaveState_SelectMemCard,
Dispatcher_SaveState_SelectSlot,
Dispatcher_SaveState_Saving,
Dispatcher_SaveState_Count,
Dispatcher_PauseState_Pause,
Dispatcher_PauseState_Options,
Dispatcher_PauseState_Count,
Dispatcher_GameState_FirstTime,
Dispatcher_GameState_Play,
Dispatcher_GameState_LoseChance,
Dispatcher_GameState_GameOver,
Dispatcher_GameState_SceneSwitch,
Dispatcher_GameState_Dead,
Dispatcher_SetIntroState_Sony,
Dispatcher_SetIntroState_Publisher,
Dispatcher_SetIntroState_Developer,
Dispatcher_SetIntroState_License,
Dispatcher_SetIntroState_Count,
Dispatcher_SetTitleState_Start,
Dispatcher_SetTitleState_Attract,
Dispatcher_SetTitleState_Count,
Dispatcher_SetLoadState_SelectMemCard,
Dispatcher_SetLoadState_SelectSlot,
Dispatcher_SetLoadState_Loading,
Dispatcher_SetLoadState_Count,
Dispatcher_SetOptionsState_Options,
Dispatcher_SetOptionsState_Count,
Dispatcher_SetSaveState_SelectMemCard,
Dispatcher_SetSaveState_SelectSlot,
Dispatcher_SetSaveState_Saving,
Dispatcher_SetSaveState_Count,
Dispatcher_SetPauseState_Pause,
Dispatcher_SetPauseState_Options,
Dispatcher_SetPauseState_Count,
Dispatcher_SetGameState_FirstTime,
Dispatcher_SetGameState_Play,
Dispatcher_SetGameState_LoseChance,
Dispatcher_SetGameState_GameOver,
Dispatcher_SetGameState_SceneSwitch,
Dispatcher_SetGameState_Dead,
Digup,
Dispatcher_GameState_Exit,
Dispatcher_SetGameState_Exit,
LobMasterShootFromWidget,
Dispatcher_SLBack,
Dispatcher_SLCancel,
Dispatcher_SLRetry,
Dispatcher_SLSelectCard,
Dispatcher_SLSelectSlot,
Dispatcher_SLOkay,
VilHurtBoss,
Attack,
AttackOn,
AttackOff,
Drop,
VilReport_StartingIdle,
VilReport_StartingSleep,
VilReport_StartingGuard,
VilReport_StartingPatrol,
VilReport_StartingDazed,
VilReport_StartingLook,
VilReport_StartingListen,
VilReport_StartingInvestigate,
VilReport_StartingChase,
VilReport_StartingAttack,
VilReport_StartingRetreat,
Preload,
Done,
Arcto,
DigupReaction,
Dispatcher_StoreCheckPoint,
AnimPlay,
AnimPlayLoop,
AnimStop,
AnimPause,
AnimResume,
AnimTogglePause,
AnimPlayRandom,
AnimPlayMaybe,
SetSpeed,
Accelerate,
MoveToTarget,
SwingerFollow,
ShaggyMount,
ShaggyWitchDrop,
ShaggySwap,
ShaggyState,
ShaggyAction,
EnterEntity,
ExitEntity,
EnterEntityFLAG,
ExitEntityFLAG,
Drivenby,
FollowTarget,
FaceTarget,
WatchTarget,
ShaggyCollideOnly,
Shaggy1_ThrowTarget,
Shaggy8_CallEnable,
Shaggy8_CallDisable,
Shaggy8_SetMagnet,
Shaggy8_ClearMagnet,
StartMoving,
StopMoving,
Swoosh,
ShaggySetDown,
ShaggyGrabEnable,
ShaggyGrabDisable,
ShaggyGrabbed,
ShaggyThrown,
VilDoAction,
GangDoBossAction,
VilFakeChaseOn,
VilFakeChaseOff,
BossMMPushButton,
VilReport_DecayComplete,
VilGuardWidget,
TextureAnimateOn,
TextureAnimateOff,
TextureAnimateToggle,
ColorEffectOn,
ColorEffectOff,
ColorEffectToggle,
SetTextureAnimGroup,
SetTextureAnimSpeed,
TextureAnimateStep,
Emit,
Emitted,
TranslucentOn,
TranslucentOff,
TranslucentToggle,
VilGangTalkOn,
VilGangTalkOff,
GivePowerUp,
UnlockR001,
UnlockS001,
UnlockE001,
UnlockF001,
DisableGroupContents,
ShaggyPhysHack,
OccludeOn,
OccludeOff,
WaveSetLinear,
WaveSetRipple,
SituationLaugh,
SituationBossBattleGreenGhost,
SituationBossBattleRedBeard,
SituationBossBattleMasterMind,
SituationBossBattleBlacknight,
SituationPlayerScare,
SituationPlayerSafe,
SituationPlayerDanger,
SituationPlayerChaseBegin,
SituationPlayerChaseEnd,
SituationPlayerSeeShaggy,
SituationPlayerSeeFood,
SituationPlayerSeeToken,
SituationPlayerSeeScoobySnack,
SituationPlayerSeePowerup,
SituationPlayerSeeMonster,
SituationPlayerSuccess,
SituationPlayerFailure,
Dispatcher_ShowHud,
Dispatcher_HideHud,
Dispatcher_FadeOut,
SetRain,
SetSnow,
ShaggyMowerStopMode,
ScriptReset,
WaitForInput,
PlayMovie,
DefeatedMM,
Dispatcher_SetGameState_GameStats,
PlayMusic,
Forward,
Reverse,
PlayerRumbleTest,
PlayerRumbleLight,
PlayerRumbleMedium,
PlayerRumbleHeavy,
DispatcherScreenAdjustON,
DispatcherScreenAdjustOFF,
SetSkyDome,
ConnectToChild,
DuploWaveBegin,
DuploWaveComplete,
DuploNPCBorn,
DuploNPCKilled,
DuploExpiredMaxNPC,
DuploPause,
DuploResume,
SetGoo,
NPCScript_ScriptBegin,
NPCScript_ScriptEnd,
NPCScript_ScriptReady,
NPCScript_Halt,
NPCScript_SetPos,
NPCScript_SetDir,
NPCScript_LookNormal,
NPCScript_LookAlert,
NPCScript_FaceWidget,
NPCScript_FaceWidgetDone,
NPCScript_GotoWidget,
NPCScript_GotoWidgetDone,
NPCScript_AttackWidget,
NPCScript_AttackWidgetDone,
NPCScript_FollowWidget,
NPCScript_PlayAnim,
NPCScript_PlayAnimDone,
NPCScript_LeadPlayer,
SetText,
StartConversation,
EndConversation,
Switch,
AddText,
ClearText,
OpenTBox,
CloseTBox,
TalkBox_OnSignal0,
TalkBox_OnSignal1,
TalkBox_OnSignal2,
TalkBox_OnSignal3,
TalkBox_OnSignal4,
TalkBox_OnSignal5,
TalkBox_OnSignal6,
TalkBox_OnSignal7,
TalkBox_OnSignal8,
TalkBox_OnSignal9,
TalkBox_StopWait,
TalkBox_OnStart,
TalkBox_OnStop,
Hit_Melee,
Hit_BubbleBounce,
Hit_BubbleBash,
Hit_BubbleBowl,
Hit_PatrickSlam,
Hit_Throw,
Hit_PaddleLeft,
Hit_PaddleRight,
TaskBox_Initiate,
TaskBox_SetSuccess,
TaskBox_SetFailure,
TaskBox_OnAccept,
TaskBox_OnDecline,
TaskBox_OnComplete,
GenerateBoulder,
LaunchBoulderAtWidget,
LaunchBoulderAtPoint,
LaunchBoulderAtPlayer,
DuploSuperDuperDone,
DuploDuperIsDoner,
BusStopSwitchChr,
GroupUpdateTogether,
SetUpdateDistance,
TranslLocalX,
TranslLocalY,
TranslLocalZ,
TranslWorldX,
TranslWorldY,
TranslWorldZ,
RotLocalX,
RotLocalY,
RotLocalZ,
RotWorldX,
RotWorldY,
RotWorldZ,
TranslLocalXDone,
TranslLocalYDone,
TranslLocalZDone,
TranslWorldXDone,
TranslWorldYDone,
TranslWorldZDone,
RotLocalXDone,
RotLocalYDone,
RotLocalZDone,
RotWorldXDone,
RotWorldYDone,
RotWorldZDone,
Count1,
Count2,
Count3,
Count4,
Count5,
Count6,
Count7,
Count8,
Count9,
Count10,
Count11,
Count12,
Count13,
Count14,
Count15,
Count16,
Count17,
Count18,
Count19,
Count20,
SetState,
EnterSpongeBob,
EnterPatrick,
EnterSandy,
ExitSpongeBob,
ExitPatrick,
ExitSandy,
NPCSpecial_PlatformSnap,
NPCSpecial_PlatformFall,
GooSetWarb,
GooSetFreezeDuration,
GooMelt,
SetStateRange,
SetStateDelay,
SetTransitionDelay,
NPCFightOn,
NPCFightOff,
NPCSplineOKOn,
NPCSplineOKOff,
NPCKillQuietly,
HitHead,
HitUpperBody,
HitLeftArm,
HitRightArm,
HitLeftLeg,
HitRightLeg,
HitLowerBody,
GiveCurrLevelSocks,
GiveCurrLevelPickup,
SetCurrLevelSocks,
SetCurrLevelPickup,
TalkBox_OnYes,
TalkBox_OnNo,
Hit_Cruise,
DuploKillKids,
TalkBox_OnSignal10,
TalkBox_OnSignal11,
TalkBox_OnSignal12,
TalkBox_OnSignal13,
TalkBox_OnSignal14,
TalkBox_OnSignal15,
TalkBox_OnSignal16,
TalkBox_OnSignal17,
TalkBox_OnSignal18,
TalkBox_OnSignal19,
SpongeballOn,
SpongeballOff,
LaunchShrapnel,
NPCHPIncremented,
NPCHPDecremented,
NPCSetActiveOn,
NPCSetActiveOff,
PlrSwitchCharacter,
LevelBegin,
SceneReset,
SceneEnter,
SituationDestroyedTiki,
SituationDestroyedRobot,
SituationSeeWoodTiki,
SituationSeeLoveyTiki,
SituationSeeShhhTiki,
SituationSeeThunderTiki,
SituationSeeStoneTiki,
SituationSeeFodder,
SituationSeeHammer,
SituationSeeTarTar,
SituationSeeGLove,
SituationSeeMonsoon,
SituationSeeSleepyTime,
SituationSeeArf,
SituationSeeTubelets,
SituationSeeSlick,
SituationSeeKingJellyfish,
SituationSeePrawn,
SituationSeeDutchman,
SituationSeeSandyBoss,
SituationSeePatrickBoss,
SituationSeeSpongeBobBoss,
SituationSeeRobotPlankton,
UIChangeTexture,
NPCCheerForMe,
FastVisible,
FastInvisible,
ZipLineMount,
ZipLineDismount,
Target,
Fire,
CameraFXShake,
BulletTime,
Thrown,
UpdateAnimMatrices,
EnterCruise,
ExitCruise,
CruiseFired,
CruiseDied,
CruiseAddLife,
CruiseSetLife,
CruiseResetLife,
CameraCollideOff,
CameraCollideOn,
OnSliding,
OffSliding,
TimerSet,
TimerAdd,
NPCForceConverseStart,
MakeASplash,
CreditsStart,
CreditsStop,
CreditsEnded,
BubbleWipe,
SetLightKit,
SetOpacity,
TakeSocks,
DispatcherAssert,
Born,
PlatPause,
PlatUnpause,
StoreOptions,
RestoreOptions,
// TSSM
UIAddChar,
UIDelChar,
UIStringEmpty,
UIStringFull,
UISendStringAsCheat,
UISetMaxChars,
UICheatOK,
UICheatBad,
Impact,
StartTimer,
FinishedTimer,
UIReset,
SetScaleFactor,
CarChangeLaneRight,
CarChangeLaneLeft,
CarStart,
CarSetSwerveMode,
IncreaseSpeed,
DecreaseSpeed,
TurretDestroyed,
NPCSpeakStop,
StartRumbleEffect,
NavigateTo,
NPCSpeakStart,
NPCAlert,
NPCPatrolDelay,
NPCScrambleActionEnd,
ZipLineEnvDamage,
RaceTimerReset,
FireCruiseBubble,
CarSuccessAnimPlay,
CarFailureAnimPlay,
NPCCharge,
RaceTimerPause,
RaceTimerResume,
RaceTimerSetBestTime,
RaceTimerWarning1,
RaceTimerWarning2,
RaceTimerWarning3,
RingChallengeStart,
CarStop,
RingChallengeRun,
RingChallengeReset,
RingChallengeSuccess,
RingChallengeFailed,
FormationChanged,
ChargeResume,
ChargePause,
NPCChargeStop,
NPCChargeCompleted,
FormationChargeStart,
ScriptNoop,
CelebrationAnimPlay,
MusicNewSong,
DeprecatedRumbleTest,
DeprecatedRumbleLight,
DeprecatedRumbleMedium,
DeprecatedRumbleHeavy,
EnterSandyUNUSED,
ExitSandyUNUSED,
SituationSeeSandyBossUNUSED,
NPCPatrol,
Dispatcher_SetSoundEffect,
Scale,
SetReference,
WarpSetWorld,
WarpSetTask,
WarpGo,
SetCount,
GetDashSpeed,
DashTrip,
DashBurst,
DashFast,
DashNormal,
DashSlow,
UISetMotion,
UIMotionFinished,
UIMotionLoop,
DestructibleLaunch,
DestructibleRespawn,
KaboomStart,
KaboomStop,
NPCAttack,
NPCDefend,
TrainCarSpeed,
TrainJunctOut1,
TrainJunctOut2,
TrainJunctSwitch,
TrainJunctPassed,
TrainCarDetach,
TrainCarExplode,
Net_InitNetAPI,
Net_UpdateConnection,
Net_UpdateOnlineTask,
Net_UpdateUserList,
Net_CheckForNewContent,
Net_SelectDevice,
Net_SelectContent,
Net_VerifyContent,
Net_RemoveContent,
Net_SelectDeviceAfterRemove,
Net_ConfirmUseContentIdx,
Net_ConfirmNoUseContentIdx,
Net_NoContentInstalled,
Net_NoContentAvailable,
Net_NewContentAvailable,
SceneEnableDraw,
SceneDisableDraw,
LightningStart,
LightningStop,
ChangeBossUIStage,
StaticCameraStart,
StaticCameraEnd,
SetCameraStartOrientation,
NMESetMovepointPath,
NMEScareBegin,
NMEScareSkip,
NMESetMovepointGroup,
VentSetStateIdle,
VentSetStateWarn,
VentSetStateDamage,
VentSetStateOff,
WaterhoseStart,
WaterhoseStop,
WaterhoseSetLength,
Carried,
Explode,
JumpTo,
JumpOnSpawn,
PlayerHit,
StartFade,
FadeDownDone,
FadeUpDone,
Bounce,
LaunchNPC,
UpgradePowerUp,
BulletStreak,
SetFollowCameraOrientation,
HDRFade,
Start,
Success,
Failure,
EnableRestore,
DisableRestore,
NPCSpawn,
SpawnDone,
SpawnedNPCKilled,
SpawnedNPCNoHealth,
SpawnedNPCAllKilled,
SpawnedNPCAllNoHealth,
DashTimerSet,
DashNotOutOfTime,
DashOutOfTime,
ForceSceneReset,
NPCActive,
NPCInactive,
DuplicatorActive,
DuplicatorInactive,
DashEnterTunnel,
DashExitTunnel,
StopRumbleEffect,
DashChaseLasersOn,
DashChaseLasersOff,
JumpRandomOnSpawn,
Hit_Cartwheel,
UIVisible_FocusOn_Select,
UIFocusOff_Unselect_Invisible,
CopyReference,
UIMotionFinishedIn,
UIMotionFinishedOut,
UISignalActivateScreen,
UISignalDeactivateScreen,
UISignalActivatedScreen,
UISignalSwitchScreens,
UISignalStartFadeOut,
UISignalStartFadeIn,
UISignalScreenMotionInDone,
UISignalScreenMotionOutDone,
UISignalMainBoxInDone,
UISignalMainBoxOutDone,
UIResetMotion,
UIEnableHDR,
UIDisableHDR,
UIBrighten,
UIUnbrighten,
UISignalDeactivatedScreen,
NPCDetectAlways,
NPCDetectNever,
NPCDetectNormal,
NPCFightDefault,
CameraCollidePartial,
MusicTempSong,
ateCounterValue,
Count0,
RotToAbsoluteX,
RotToAbsoluteY,
RotToAbsoluteZ,
TriggerAnim,
TriggeredAnimDone,
UISignalMore,
UISignalNoMore,
UISignalLess,
UISignalNoLess,
UISignalUp,
UISignalDown,
UISignalSyncToCurrent,
UISignalEffect,
FreezePlayer,
UnfreezePlayer,
UISignalMapStart,
UISignalMapEnd,
TransToAbsoluteX,
TransToAbsoluteY,
TransToAbsoluteZ,
JSPVisibilityIncrement,
JSPVisibilityDecrement,
EnterCamera,
ExitCamera,
PadPressE,
SetDashJumpParameters,
ViperFacePlayer,
ViperFaceMovement,
RequestStart,
UIAutoMenuRun,
UIAutoMenuRunUp,
UIAutoMenuRunDown,
UIAutoMenuRunLeft,
UIAutoMenuRunRight,
IncrementSuccess,
DecrementSuccess,
IncrementFailed,
DecrementFailed,
MusicTempSongStop,
NPCScrambleActionBegin,
NPCScrambleAlert,
NPCSetTurretAttackRadius,
GooFreezeStart,
GooMeltStart,
NPCNotice,
BossStageSet,
BossStageBegan,
BossStageEnded,
BossStageBeganA,
BossStageEndedA,
BossStageBeganB,
BossStageEndedB,
BossStageBeganC,
BossStageEndedC,
VisibilityCullOn,
VisibilityCullOff,
RBandCameraStart,
RBandCameraEnd,
MindyStart,
MindyEnd,
FlamethrowerStart,
FlamethrowerStop,
FlamethrowerSetLength,
NPCTakeNoDamageOn,
NPCTakeNoDamageOff,
StaticCameraStartFOVFilter,
StaticCameraRestoreFOV,
UIXboxDemoExitToLauncher,
Spawn,
Spawned,
CreditsSetDest,
AllowAttractMode,
DisallowAttractMode,
RocketAttack,
CollisionReset,
AutoSave,
OpenBonus,
FlagLevel,
LevelEnd,
Net_GetLocalContentDevice,
Dispatcher_PauseGame_Safe,
OverrideFreqency,
ResetFrequency,
SetShotDelay,
SetShotsInGroup,
Dispatcher_UserSelectYes,
Dispatcher_UserSelectNo,
Dispatcher_UserSelectBack,
LaunchFireWorks,
Dispatcher_UserSelectionReset,
SetAsBounceBack,
UIResetUnlockables,
UISysMessageWaitResponse,
UISysMessageWaitConfirm,
UISysMessageConfirm,
UISysMessageAccept,
UISysMessageDecline,
SetAsBounceBack_Cancel,
Dispatcher_PauseGame,
PattyWagonStartEngine,
PattyWagonStopEngine,
SpawnBubblesOn,
SpawnBubblesOff,
Net_XBLiveToggleSignIn,
Net_XBLiveManageFriends,
ApplyOnResetOn,
ApplyOnResetOff,
SnapTo,
Throw,
FirstZipLine,
FirstLedgeGrab,
FirstIncredimeterPickup,
UISparkTrail,
UIGetBattleScenes,
UIBattleScenesAvailable,
UIBattleScenesNotAvailable,
Net_XBLiveToggleAppearOnline,
Sys_ReturnPrevScreen,
Sys_Nope,
Dispatcher_SubtitlesOn,
Dispatcher_SubtitlesOff,
UISetBoxMapping,
TBoxPlayerEjected,
DamagePlayer,
FirstHealthPickup,
TokenPickupComplete,
Dispatcher_LoadSavePromptDead,
UIFlipVisibility,
Net_XBLiveRebootToDashboard,
FirstPowerupPoint,
}
export function convertToHIEvent(event: number, game: HIGame): HIEvent {
switch (game) {
case HIGame.BFBBBeta:
case HIGame.BFBB:
return HIEvent[HIEventBFBB[event] as keyof typeof HIEvent];
case HIGame.TSSM:
return HIEvent[HIEventTSSM[event] as keyof typeof HIEvent];
}
}
export function convertFromHIEvent(event: HIEvent, game: HIGame): number {
switch (game) {
case HIGame.BFBBBeta:
case HIGame.BFBB:
return HIEventBFBB[HIEvent[event] as keyof typeof HIEventBFBB];
case HIGame.TSSM:
return HIEventTSSM[HIEvent[event] as keyof typeof HIEventTSSM];
}
} | 0 | 0.780082 | 1 | 0.780082 | game-dev | MEDIA | 0.703593 | game-dev | 0.840172 | 1 | 0.840172 |
jeffsponaugle/roscoe | 2,792 | src/Roscoe/Emulator/Shared/libsdl/libsdlsrc/include/SDL_clipboard.h | /*
Simple DirectMedia Layer
Copyright (C) 1997-2022 Sam Lantinga <[email protected]>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/**
* \file SDL_clipboard.h
*
* Include file for SDL clipboard handling
*/
#ifndef SDL_clipboard_h_
#define SDL_clipboard_h_
#include "SDL_stdinc.h"
#include "begin_code.h"
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
extern "C" {
#endif
/* Function prototypes */
/**
* Put UTF-8 text into the clipboard.
*
* \param text the text to store in the clipboard
* \returns 0 on success or a negative error code on failure; call
* SDL_GetError() for more information.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_GetClipboardText
* \sa SDL_HasClipboardText
*/
extern DECLSPEC int SDLCALL SDL_SetClipboardText(const char *text);
/**
* Get UTF-8 text from the clipboard, which must be freed with SDL_free().
*
* This functions returns empty string if there was not enough memory left for
* a copy of the clipboard's content.
*
* \returns the clipboard text on success or an empty string on failure; call
* SDL_GetError() for more information. Caller must call SDL_free()
* on the returned pointer when done with it (even if there was an
* error).
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_HasClipboardText
* \sa SDL_SetClipboardText
*/
extern DECLSPEC char * SDLCALL SDL_GetClipboardText(void);
/**
* Query whether the clipboard exists and contains a non-empty text string.
*
* \returns SDL_TRUE if the clipboard has text, or SDL_FALSE if it does not.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_GetClipboardText
* \sa SDL_SetClipboardText
*/
extern DECLSPEC SDL_bool SDLCALL SDL_HasClipboardText(void);
/* Ends C function definitions when using C++ */
#ifdef __cplusplus
}
#endif
#include "close_code.h"
#endif /* SDL_clipboard_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| 0 | 0.849385 | 1 | 0.849385 | game-dev | MEDIA | 0.748799 | game-dev | 0.512147 | 1 | 0.512147 |
Loyalists/gflh2 | 1,409 | mods/gfl/aitype/team3_merc_smg.gsc | // H2 GSC SOURCE
// Decompiled by https://github.com/xensik/gsc-tool
main()
{
self.animtree = "";
self.additionalassets = "";
self.team = "team3";
self.type = "human";
self.subclass = "regular";
self.accuracy = 0.2;
self.health = 150;
self.grenadeweapon = "fraggrenade";
self.grenadeammo = 0;
self.secondaryweapon = "";
self.sidearm = "pp2000";
if ( isai( self ) )
{
self setengagementmindist( 128.0, 0.0 );
self setengagementmaxdist( 512.0, 768.0 );
}
switch ( codescripts\character::get_random_weapon( 6 ) )
{
case 0:
self.weapon = "p90";
break;
case 1:
self.weapon = "p90_acog";
break;
case 2:
self.weapon = "p90_reflex";
break;
case 3:
self.weapon = "uzi";
break;
case 4:
self.weapon = "uzi";
break;
case 5:
self.weapon = "iw5_mp11_sp";
break;
}
character\gfl\randomizer_merc_smg::main();
}
spawner()
{
self setspawnerteam( "team3" );
}
precache()
{
character\gfl\randomizer_merc_smg::precache();
precacheitem( "p90" );
precacheitem( "p90_acog" );
precacheitem( "p90_reflex" );
precacheitem( "uzi" );
precacheitem( "uzi" );
precacheitem( "pp2000" );
precacheitem( "fraggrenade" );
}
| 0 | 0.885944 | 1 | 0.885944 | game-dev | MEDIA | 0.963591 | game-dev | 0.6163 | 1 | 0.6163 |
JetBoom/zombiesurvival | 1,807 | gamemodes/zombiesurvival/entities/entities/projectile_flashbomb/init.lua | INC_SERVER()
function ENT:Initialize()
self:SetModel("models/weapons/w_eq_flashbang_thrown.mdl")
self:PhysicsInit(SOLID_VPHYSICS)
self:SetSolid(SOLID_VPHYSICS)
self:SetCollisionGroup(COLLISION_GROUP_PROJECTILE)
local phys = self:GetPhysicsObject()
if phys:IsValid() then
phys:Wake()
phys:SetMass(1)
phys:SetMaterial("metal")
end
self.DieTime = CurTime() + self.LifeTime
self:NextThink(self.DieTime)
end
function ENT:PhysicsCollide(data, phys)
if 20 < data.Speed and 0.25 < data.DeltaTime then
self:EmitSound("weapons/flashbang/grenade_hit1.wav")
end
end
function ENT:Think()
if CurTime() >= self.DieTime then
self:Remove()
end
end
function ENT:OnRemove()
self:Explode()
end
function ENT:Explode()
if self.Exploded then return end
self.Exploded = true
local owner = self:GetOwner()
local pos = self:GetPos()
for _, ent in pairs(ents.FindInSphere(pos, self.Radius)) do
if ent:IsValid() and ent:IsPlayer() and ent:Alive() and (ent:Team() == TEAM_UNDEAD or ent == owner) then
local eyepos = ent:EyePos()
if TrueVisibleFilters(pos, eyepos, self, ent) then
local eyevec = ent:GetAimVector()
local strength = (1 - eyepos:Distance(pos) / self.Radius) ^ 0.5 * (0.3 + math.Clamp((pos - eyepos):GetNormalized():Dot(eyevec), 0, 1) * 0.7)
ent:AddLegDamage(strength)
local time = (0.5 + strength * 1.5) * (ent.VisionAlterDurationMul or 1)
ent:ScreenFade(SCREENFADE.IN, nil, time, time)
ent:SetDSP(36)
if strength > 0.4 then ent:GiveStatus("disorientation", time * 2) end
if ent:Team() == TEAM_UNDEAD then
ent:TakeDamage(1, owner, self)
end
end
end
end
self:EmitSound("weapons/flashbang/flashbang_explode2.wav")
local effectdata = EffectData()
effectdata:SetOrigin(pos)
util.Effect("HelicopterMegaBomb", effectdata)
end
| 0 | 0.903511 | 1 | 0.903511 | game-dev | MEDIA | 0.994078 | game-dev | 0.926055 | 1 | 0.926055 |
FTBTeam/FTB-Quests | 1,468 | common/src/main/java/dev/ftb/mods/ftbquests/net/NotifyRewardMessage.java | package dev.ftb.mods.ftbquests.net;
import dev.architectury.networking.NetworkManager;
import dev.ftb.mods.ftblibrary.icon.Icon;
import dev.ftb.mods.ftbquests.api.FTBQuestsAPI;
import dev.ftb.mods.ftbquests.client.FTBQuestsNetClient;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.ComponentSerialization;
import net.minecraft.network.codec.ByteBufCodecs;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
public record NotifyRewardMessage(long id, Component text, Icon icon, boolean disableBlur) implements CustomPacketPayload {
public static final Type<NotifyRewardMessage> TYPE = new Type<>(FTBQuestsAPI.rl("notify_reward_message"));
public static final StreamCodec<RegistryFriendlyByteBuf, NotifyRewardMessage> STREAM_CODEC = StreamCodec.composite(
ByteBufCodecs.VAR_LONG, NotifyRewardMessage::id,
ComponentSerialization.STREAM_CODEC, NotifyRewardMessage::text,
Icon.STREAM_CODEC, NotifyRewardMessage::icon,
ByteBufCodecs.BOOL, NotifyRewardMessage::disableBlur,
NotifyRewardMessage::new
);
@Override
public Type<NotifyRewardMessage> type() {
return TYPE;
}
public static void handle(NotifyRewardMessage message, NetworkManager.PacketContext context) {
context.queue(() -> FTBQuestsNetClient.displayRewardToast(message.id, message.text, message.icon, message.disableBlur));
}
} | 0 | 0.758713 | 1 | 0.758713 | game-dev | MEDIA | 0.894104 | game-dev,networking | 0.529287 | 1 | 0.529287 |
aevum/libgdx-cpp | 1,642 | src/Box2D/Dynamics/Contacts/b2ChainAndCircleContact.h | /*
* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#ifndef B2_CHAIN_AND_CIRCLE_CONTACT_H
#define B2_CHAIN_AND_CIRCLE_CONTACT_H
#include <Box2D/Dynamics/Contacts/b2Contact.h>
#include "Box2D/Common/b2Settings.h"
class b2BlockAllocator;
class b2Fixture;
struct b2Manifold;
struct b2Transform;
class b2ChainAndCircleContact : public b2Contact
{
public:
static b2Contact* Create( b2Fixture* fixtureA, int32 indexA,
b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator);
static void Destroy(b2Contact* contact, b2BlockAllocator* allocator);
b2ChainAndCircleContact(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB);
~b2ChainAndCircleContact() {}
void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) override;
};
#endif
| 0 | 0.901882 | 1 | 0.901882 | game-dev | MEDIA | 0.638103 | game-dev | 0.858476 | 1 | 0.858476 |
scikit-image/scikit-image | 43,515 | tools/precompute/mc_meta/MarchingCubes.cpp | /**
* @file MarchingCubes.cpp
* @author Thomas Lewiner <[email protected]>
* @author Math Dept, PUC-Rio
* @version 0.2
* @date 12/08/2002
*
* @brief MarchingCubes Algorithm
*/
//________________________________________________
#if !defined(WIN32) || defined(__CYGWIN__)
#pragma implementation
#endif // WIN32
#include <math.h>
#include <time.h>
#include <memory.h>
#include <stdlib.h>
#include <float.h>
#include "MarchingCubes.h"
#include "ply.h"
#include "LookUpTable.h"
// step size of the arrays of vertices and triangles
#define ALLOC_SIZE 65536
//_____________________________________________________________________________
// print cube for debug
void MarchingCubes::print_cube() { printf( "\t%f %f %f %f %f %f %f %f\n", _cube[0], _cube[1], _cube[2], _cube[3], _cube[4], _cube[5], _cube[6], _cube[7]) ; }
//_____________________________________________________________________________
//_____________________________________________________________________________
// Constructor
MarchingCubes::MarchingCubes( const int size_x /*= -1*/, const int size_y /*= -1*/, const int size_z /*= -1*/ ) :
//-----------------------------------------------------------------------------
_originalMC(false),
_ext_data (false),
_size_x (size_x),
_size_y (size_y),
_size_z (size_z),
_data ((real *)NULL),
_x_verts (( int *)NULL),
_y_verts (( int *)NULL),
_z_verts (( int *)NULL),
_nverts (0),
_ntrigs (0),
_Nverts (0),
_Ntrigs (0),
_vertices (( Vertex *)NULL),
_triangles ((Triangle*)NULL)
{}
//_____________________________________________________________________________
//_____________________________________________________________________________
// Destructor
MarchingCubes::~MarchingCubes()
//-----------------------------------------------------------------------------
{
clean_all() ;
}
//_____________________________________________________________________________
//_____________________________________________________________________________
// main algorithm
void MarchingCubes::run( real iso )
//-----------------------------------------------------------------------------
{
clock_t time = clock() ;
compute_intersection_points( iso ) ;
for( _k = 0 ; _k < _size_z-1 ; _k++ )
for( _j = 0 ; _j < _size_y-1 ; _j++ )
for( _i = 0 ; _i < _size_x-1 ; _i++ )
{
_lut_entry = 0 ;
for( int p = 0 ; p < 8 ; ++p )
{
_cube[p] = get_data( _i+((p^(p>>1))&1), _j+((p>>1)&1), _k+((p>>2)&1) ) - iso ;
if( fabs( _cube[p] ) < FLT_EPSILON ) _cube[p] = FLT_EPSILON ;
if( _cube[p] > 0 ) _lut_entry += 1 << p ;
}
/*
if( ( _cube[0] = get_data( _i , _j , _k ) ) > 0 ) _lut_entry += 1 ;
if( ( _cube[1] = get_data(_i+1, _j , _k ) ) > 0 ) _lut_entry += 2 ;
if( ( _cube[2] = get_data(_i+1,_j+1, _k ) ) > 0 ) _lut_entry += 4 ;
if( ( _cube[3] = get_data( _i ,_j+1, _k ) ) > 0 ) _lut_entry += 8 ;
if( ( _cube[4] = get_data( _i , _j ,_k+1) ) > 0 ) _lut_entry += 16 ;
if( ( _cube[5] = get_data(_i+1, _j ,_k+1) ) > 0 ) _lut_entry += 32 ;
if( ( _cube[6] = get_data(_i+1,_j+1,_k+1) ) > 0 ) _lut_entry += 64 ;
if( ( _cube[7] = get_data( _i ,_j+1,_k+1) ) > 0 ) _lut_entry += 128 ;
*/
process_cube( ) ;
}
printf("Marching Cubes ran in %lf secs.\n", (double)(clock() - time)/CLOCKS_PER_SEC) ;
}
//_____________________________________________________________________________
//_____________________________________________________________________________
// init temporary structures (must set sizes before call)
void MarchingCubes::init_temps()
//-----------------------------------------------------------------------------
{
if( !_ext_data )
_data = new real [_size_x * _size_y * _size_z] ;
_x_verts = new int [_size_x * _size_y * _size_z] ;
_y_verts = new int [_size_x * _size_y * _size_z] ;
_z_verts = new int [_size_x * _size_y * _size_z] ;
memset( _x_verts, -1, _size_x * _size_y * _size_z * sizeof( int ) ) ;
memset( _y_verts, -1, _size_x * _size_y * _size_z * sizeof( int ) ) ;
memset( _z_verts, -1, _size_x * _size_y * _size_z * sizeof( int ) ) ;
}
//_____________________________________________________________________________
//_____________________________________________________________________________
// init all structures (must set sizes before call)
void MarchingCubes::init_all ()
//-----------------------------------------------------------------------------
{
init_temps() ;
_nverts = _ntrigs = 0 ;
_Nverts = _Ntrigs = ALLOC_SIZE ;
_vertices = new Vertex [_Nverts] ;
_triangles = new Triangle[_Ntrigs] ;
}
//_____________________________________________________________________________
//_____________________________________________________________________________
// clean temporary structures
void MarchingCubes::clean_temps()
//-----------------------------------------------------------------------------
{
if( !_ext_data )
delete [] _data;
delete [] _x_verts;
delete [] _y_verts;
delete [] _z_verts;
if( !_ext_data )
_data = (real*)NULL ;
_x_verts = (int*)NULL ;
_y_verts = (int*)NULL ;
_z_verts = (int*)NULL ;
}
//_____________________________________________________________________________
//_____________________________________________________________________________
// clean all structures
void MarchingCubes::clean_all()
//-----------------------------------------------------------------------------
{
clean_temps() ;
delete [] _vertices ;
delete [] _triangles ;
_vertices = (Vertex *)NULL ;
_triangles = (Triangle *)NULL ;
_nverts = _ntrigs = 0 ;
_Nverts = _Ntrigs = 0 ;
_size_x = _size_y = _size_z = -1 ;
}
//_____________________________________________________________________________
//_____________________________________________________________________________
//_____________________________________________________________________________
//_____________________________________________________________________________
// Compute the intersection points
void MarchingCubes::compute_intersection_points( real iso )
//-----------------------------------------------------------------------------
{
for( _k = 0 ; _k < _size_z ; _k++ )
for( _j = 0 ; _j < _size_y ; _j++ )
for( _i = 0 ; _i < _size_x ; _i++ )
{
_cube[0] = get_data( _i, _j, _k ) - iso ;
if( _i < _size_x - 1 ) _cube[1] = get_data(_i+1, _j , _k ) - iso ;
else _cube[1] = _cube[0] ;
if( _j < _size_y - 1 ) _cube[3] = get_data( _i ,_j+1, _k ) - iso ;
else _cube[3] = _cube[0] ;
if( _k < _size_z - 1 ) _cube[4] = get_data( _i , _j ,_k+1) - iso ;
else _cube[4] = _cube[0] ;
if( fabs( _cube[0] ) < FLT_EPSILON ) _cube[0] = FLT_EPSILON ;
if( fabs( _cube[1] ) < FLT_EPSILON ) _cube[1] = FLT_EPSILON ;
if( fabs( _cube[3] ) < FLT_EPSILON ) _cube[3] = FLT_EPSILON ;
if( fabs( _cube[4] ) < FLT_EPSILON ) _cube[4] = FLT_EPSILON ;
if( _cube[0] < 0 )
{
if( _cube[1] > 0 ) set_x_vert( add_x_vertex( ), _i,_j,_k ) ;
if( _cube[3] > 0 ) set_y_vert( add_y_vertex( ), _i,_j,_k ) ;
if( _cube[4] > 0 ) set_z_vert( add_z_vertex( ), _i,_j,_k ) ;
}
else
{
if( _cube[1] < 0 ) set_x_vert( add_x_vertex( ), _i,_j,_k ) ;
if( _cube[3] < 0 ) set_y_vert( add_y_vertex( ), _i,_j,_k ) ;
if( _cube[4] < 0 ) set_z_vert( add_z_vertex( ), _i,_j,_k ) ;
}
}
}
//_____________________________________________________________________________
//_____________________________________________________________________________
// Test a face
// if face>0 return true if the face contains a part of the surface
bool MarchingCubes::test_face( schar face )
//-----------------------------------------------------------------------------
{
real A,B,C,D ;
switch( face )
{
case -1 : case 1 : A = _cube[0] ; B = _cube[4] ; C = _cube[5] ; D = _cube[1] ; break ;
case -2 : case 2 : A = _cube[1] ; B = _cube[5] ; C = _cube[6] ; D = _cube[2] ; break ;
case -3 : case 3 : A = _cube[2] ; B = _cube[6] ; C = _cube[7] ; D = _cube[3] ; break ;
case -4 : case 4 : A = _cube[3] ; B = _cube[7] ; C = _cube[4] ; D = _cube[0] ; break ;
case -5 : case 5 : A = _cube[0] ; B = _cube[3] ; C = _cube[2] ; D = _cube[1] ; break ;
case -6 : case 6 : A = _cube[4] ; B = _cube[7] ; C = _cube[6] ; D = _cube[5] ; break ;
default : printf( "Invalid face code %d\n", face ) ; print_cube() ; A = B = C = D = 0 ;
};
if( fabs( A*C - B*D ) < FLT_EPSILON )
return face >= 0 ;
return face * A * ( A*C - B*D ) >= 0 ; // face and A invert signs
}
//_____________________________________________________________________________
//_____________________________________________________________________________
// Test the interior of a cube
// if s == 7, return true if the interior is empty
// if s ==-7, return false if the interior is empty
bool MarchingCubes::test_interior( schar s )
//-----------------------------------------------------------------------------
{
real t, At=0, Bt=0, Ct=0, Dt=0, a, b ;
char test = 0 ;
char edge = -1 ; // reference edge of the triangulation
switch( _case )
{
case 4 :
case 10 :
a = ( _cube[4] - _cube[0] ) * ( _cube[6] - _cube[2] ) - ( _cube[7] - _cube[3] ) * ( _cube[5] - _cube[1] ) ;
b = _cube[2] * ( _cube[4] - _cube[0] ) + _cube[0] * ( _cube[6] - _cube[2] )
- _cube[1] * ( _cube[7] - _cube[3] ) - _cube[3] * ( _cube[5] - _cube[1] ) ;
t = - b / (2*a) ;
if( t<0 || t>1 ) return s>0 ;
At = _cube[0] + ( _cube[4] - _cube[0] ) * t ;
Bt = _cube[3] + ( _cube[7] - _cube[3] ) * t ;
Ct = _cube[2] + ( _cube[6] - _cube[2] ) * t ;
Dt = _cube[1] + ( _cube[5] - _cube[1] ) * t ;
break ;
case 6 :
case 7 :
case 12 :
case 13 :
switch( _case )
{
case 6 : edge = test6 [_config][2] ; break ;
case 7 : edge = test7 [_config][4] ; break ;
case 12 : edge = test12[_config][3] ; break ;
case 13 : edge = tiling13_5_1[_config][_subconfig][0] ; break ;
}
switch( edge )
{
case 0 :
t = _cube[0] / ( _cube[0] - _cube[1] ) ;
At = 0 ;
Bt = _cube[3] + ( _cube[2] - _cube[3] ) * t ;
Ct = _cube[7] + ( _cube[6] - _cube[7] ) * t ;
Dt = _cube[4] + ( _cube[5] - _cube[4] ) * t ;
break ;
case 1 :
t = _cube[1] / ( _cube[1] - _cube[2] ) ;
At = 0 ;
Bt = _cube[0] + ( _cube[3] - _cube[0] ) * t ;
Ct = _cube[4] + ( _cube[7] - _cube[4] ) * t ;
Dt = _cube[5] + ( _cube[6] - _cube[5] ) * t ;
break ;
case 2 :
t = _cube[2] / ( _cube[2] - _cube[3] ) ;
At = 0 ;
Bt = _cube[1] + ( _cube[0] - _cube[1] ) * t ;
Ct = _cube[5] + ( _cube[4] - _cube[5] ) * t ;
Dt = _cube[6] + ( _cube[7] - _cube[6] ) * t ;
break ;
case 3 :
t = _cube[3] / ( _cube[3] - _cube[0] ) ;
At = 0 ;
Bt = _cube[2] + ( _cube[1] - _cube[2] ) * t ;
Ct = _cube[6] + ( _cube[5] - _cube[6] ) * t ;
Dt = _cube[7] + ( _cube[4] - _cube[7] ) * t ;
break ;
case 4 :
t = _cube[4] / ( _cube[4] - _cube[5] ) ;
At = 0 ;
Bt = _cube[7] + ( _cube[6] - _cube[7] ) * t ;
Ct = _cube[3] + ( _cube[2] - _cube[3] ) * t ;
Dt = _cube[0] + ( _cube[1] - _cube[0] ) * t ;
break ;
case 5 :
t = _cube[5] / ( _cube[5] - _cube[6] ) ;
At = 0 ;
Bt = _cube[4] + ( _cube[7] - _cube[4] ) * t ;
Ct = _cube[0] + ( _cube[3] - _cube[0] ) * t ;
Dt = _cube[1] + ( _cube[2] - _cube[1] ) * t ;
break ;
case 6 :
t = _cube[6] / ( _cube[6] - _cube[7] ) ;
At = 0 ;
Bt = _cube[5] + ( _cube[4] - _cube[5] ) * t ;
Ct = _cube[1] + ( _cube[0] - _cube[1] ) * t ;
Dt = _cube[2] + ( _cube[3] - _cube[2] ) * t ;
break ;
case 7 :
t = _cube[7] / ( _cube[7] - _cube[4] ) ;
At = 0 ;
Bt = _cube[6] + ( _cube[5] - _cube[6] ) * t ;
Ct = _cube[2] + ( _cube[1] - _cube[2] ) * t ;
Dt = _cube[3] + ( _cube[0] - _cube[3] ) * t ;
break ;
case 8 :
t = _cube[0] / ( _cube[0] - _cube[4] ) ;
At = 0 ;
Bt = _cube[3] + ( _cube[7] - _cube[3] ) * t ;
Ct = _cube[2] + ( _cube[6] - _cube[2] ) * t ;
Dt = _cube[1] + ( _cube[5] - _cube[1] ) * t ;
break ;
case 9 :
t = _cube[1] / ( _cube[1] - _cube[5] ) ;
At = 0 ;
Bt = _cube[0] + ( _cube[4] - _cube[0] ) * t ;
Ct = _cube[3] + ( _cube[7] - _cube[3] ) * t ;
Dt = _cube[2] + ( _cube[6] - _cube[2] ) * t ;
break ;
case 10 :
t = _cube[2] / ( _cube[2] - _cube[6] ) ;
At = 0 ;
Bt = _cube[1] + ( _cube[5] - _cube[1] ) * t ;
Ct = _cube[0] + ( _cube[4] - _cube[0] ) * t ;
Dt = _cube[3] + ( _cube[7] - _cube[3] ) * t ;
break ;
case 11 :
t = _cube[3] / ( _cube[3] - _cube[7] ) ;
At = 0 ;
Bt = _cube[2] + ( _cube[6] - _cube[2] ) * t ;
Ct = _cube[1] + ( _cube[5] - _cube[1] ) * t ;
Dt = _cube[0] + ( _cube[4] - _cube[0] ) * t ;
break ;
default : printf( "Invalid edge %d\n", edge ) ; print_cube() ; break ;
}
break ;
default : printf( "Invalid ambiguous case %d\n", _case ) ; print_cube() ; break ;
}
if( At >= 0 ) test ++ ;
if( Bt >= 0 ) test += 2 ;
if( Ct >= 0 ) test += 4 ;
if( Dt >= 0 ) test += 8 ;
switch( test )
{
case 0 : return s>0 ;
case 1 : return s>0 ;
case 2 : return s>0 ;
case 3 : return s>0 ;
case 4 : return s>0 ;
case 5 : if( At * Ct - Bt * Dt < FLT_EPSILON ) return s>0 ; break ;
case 6 : return s>0 ;
case 7 : return s<0 ;
case 8 : return s>0 ;
case 9 : return s>0 ;
case 10 : if( At * Ct - Bt * Dt >= FLT_EPSILON ) return s>0 ; break ;
case 11 : return s<0 ;
case 12 : return s>0 ;
case 13 : return s<0 ;
case 14 : return s<0 ;
case 15 : return s<0 ;
}
return s<0 ;
}
//_____________________________________________________________________________
//_____________________________________________________________________________
// Process a unit cube
void MarchingCubes::process_cube( )
//-----------------------------------------------------------------------------
{
if( _originalMC )
{
char nt = 0 ;
while( casesClassic[_lut_entry][3*nt] != -1 ) nt++ ;
add_triangle( casesClassic[_lut_entry], nt ) ;
return ;
}
int v12 = -1 ;
_case = cases[_lut_entry][0] ;
_config = cases[_lut_entry][1] ;
_subconfig = 0 ;
switch( _case )
{
case 0 :
break ;
case 1 :
add_triangle( tiling1[_config], 1 ) ;
break ;
case 2 :
add_triangle( tiling2[_config], 2 ) ;
break ;
case 3 :
if( test_face( test3[_config]) )
add_triangle( tiling3_2[_config], 4 ) ; // 3.2
else
add_triangle( tiling3_1[_config], 2 ) ; // 3.1
break ;
case 4 :
if( test_interior( test4[_config]) )
add_triangle( tiling4_1[_config], 2 ) ; // 4.1.1
else
add_triangle( tiling4_2[_config], 6 ) ; // 4.1.2
break ;
case 5 :
add_triangle( tiling5[_config], 3 ) ;
break ;
case 6 :
if( test_face( test6[_config][0]) )
add_triangle( tiling6_2[_config], 5 ) ; // 6.2
else
{
if( test_interior( test6[_config][1]) )
add_triangle( tiling6_1_1[_config], 3 ) ; // 6.1.1
else
{
v12 = add_c_vertex() ;
add_triangle( tiling6_1_2[_config], 9 , v12) ; // 6.1.2
}
}
break ;
case 7 :
if( test_face( test7[_config][0] ) ) _subconfig += 1 ;
if( test_face( test7[_config][1] ) ) _subconfig += 2 ;
if( test_face( test7[_config][2] ) ) _subconfig += 4 ;
switch( _subconfig )
{
case 0 :
add_triangle( tiling7_1[_config], 3 ) ; break ;
case 1 :
add_triangle( tiling7_2[_config][0], 5 ) ; break ;
case 2 :
add_triangle( tiling7_2[_config][1], 5 ) ; break ;
case 3 :
v12 = add_c_vertex() ;
add_triangle( tiling7_3[_config][0], 9, v12 ) ; break ;
case 4 :
add_triangle( tiling7_2[_config][2], 5 ) ; break ;
case 5 :
v12 = add_c_vertex() ;
add_triangle( tiling7_3[_config][1], 9, v12 ) ; break ;
case 6 :
v12 = add_c_vertex() ;
add_triangle( tiling7_3[_config][2], 9, v12 ) ; break ;
case 7 :
if( test_interior( test7[_config][3]) )
add_triangle( tiling7_4_2[_config], 9 ) ;
else
add_triangle( tiling7_4_1[_config], 5 ) ;
break ;
};
break ;
case 8 :
add_triangle( tiling8[_config], 2 ) ;
break ;
case 9 :
add_triangle( tiling9[_config], 4 ) ;
break ;
case 10 :
if( test_face( test10[_config][0]) )
{
if( test_face( test10[_config][1]) )
add_triangle( tiling10_1_1_[_config], 4 ) ; // 10.1.1
else
{
v12 = add_c_vertex() ;
add_triangle( tiling10_2[_config], 8, v12 ) ; // 10.2
}
}
else
{
if( test_face( test10[_config][1]) )
{
v12 = add_c_vertex() ;
add_triangle( tiling10_2_[_config], 8, v12 ) ; // 10.2
}
else
{
if( test_interior( test10[_config][2]) )
add_triangle( tiling10_1_1[_config], 4 ) ; // 10.1.1
else
add_triangle( tiling10_1_2[_config], 8 ) ; // 10.1.2
}
}
break ;
case 11 :
add_triangle( tiling11[_config], 4 ) ;
break ;
case 12 :
if( test_face( test12[_config][0]) )
{
if( test_face( test12[_config][1]) )
add_triangle( tiling12_1_1_[_config], 4 ) ; // 12.1.1
else
{
v12 = add_c_vertex() ;
add_triangle( tiling12_2[_config], 8, v12 ) ; // 12.2
}
}
else
{
if( test_face( test12[_config][1]) )
{
v12 = add_c_vertex() ;
add_triangle( tiling12_2_[_config], 8, v12 ) ; // 12.2
}
else
{
if( test_interior( test12[_config][2]) )
add_triangle( tiling12_1_1[_config], 4 ) ; // 12.1.1
else
add_triangle( tiling12_1_2[_config], 8 ) ; // 12.1.2
}
}
break ;
case 13 :
if( test_face( test13[_config][0] ) ) _subconfig += 1 ;
if( test_face( test13[_config][1] ) ) _subconfig += 2 ;
if( test_face( test13[_config][2] ) ) _subconfig += 4 ;
if( test_face( test13[_config][3] ) ) _subconfig += 8 ;
if( test_face( test13[_config][4] ) ) _subconfig += 16 ;
if( test_face( test13[_config][5] ) ) _subconfig += 32 ;
switch( subconfig13[_subconfig] )
{
case 0 :/* 13.1 */
add_triangle( tiling13_1[_config], 4 ) ; break ;
case 1 :/* 13.2 */
add_triangle( tiling13_2[_config][0], 6 ) ; break ;
case 2 :/* 13.2 */
add_triangle( tiling13_2[_config][1], 6 ) ; break ;
case 3 :/* 13.2 */
add_triangle( tiling13_2[_config][2], 6 ) ; break ;
case 4 :/* 13.2 */
add_triangle( tiling13_2[_config][3], 6 ) ; break ;
case 5 :/* 13.2 */
add_triangle( tiling13_2[_config][4], 6 ) ; break ;
case 6 :/* 13.2 */
add_triangle( tiling13_2[_config][5], 6 ) ; break ;
case 7 :/* 13.3 */
v12 = add_c_vertex() ;
add_triangle( tiling13_3[_config][0], 10, v12 ) ; break ;
case 8 :/* 13.3 */
v12 = add_c_vertex() ;
add_triangle( tiling13_3[_config][1], 10, v12 ) ; break ;
case 9 :/* 13.3 */
v12 = add_c_vertex() ;
add_triangle( tiling13_3[_config][2], 10, v12 ) ; break ;
case 10 :/* 13.3 */
v12 = add_c_vertex() ;
add_triangle( tiling13_3[_config][3], 10, v12 ) ; break ;
case 11 :/* 13.3 */
v12 = add_c_vertex() ;
add_triangle( tiling13_3[_config][4], 10, v12 ) ; break ;
case 12 :/* 13.3 */
v12 = add_c_vertex() ;
add_triangle( tiling13_3[_config][5], 10, v12 ) ; break ;
case 13 :/* 13.3 */
v12 = add_c_vertex() ;
add_triangle( tiling13_3[_config][6], 10, v12 ) ; break ;
case 14 :/* 13.3 */
v12 = add_c_vertex() ;
add_triangle( tiling13_3[_config][7], 10, v12 ) ; break ;
case 15 :/* 13.3 */
v12 = add_c_vertex() ;
add_triangle( tiling13_3[_config][8], 10, v12 ) ; break ;
case 16 :/* 13.3 */
v12 = add_c_vertex() ;
add_triangle( tiling13_3[_config][9], 10, v12 ) ; break ;
case 17 :/* 13.3 */
v12 = add_c_vertex() ;
add_triangle( tiling13_3[_config][10], 10, v12 ) ; break ;
case 18 :/* 13.3 */
v12 = add_c_vertex() ;
add_triangle( tiling13_3[_config][11], 10, v12 ) ; break ;
case 19 :/* 13.4 */
v12 = add_c_vertex() ;
add_triangle( tiling13_4[_config][0], 12, v12 ) ; break ;
case 20 :/* 13.4 */
v12 = add_c_vertex() ;
add_triangle( tiling13_4[_config][1], 12, v12 ) ; break ;
case 21 :/* 13.4 */
v12 = add_c_vertex() ;
add_triangle( tiling13_4[_config][2], 12, v12 ) ; break ;
case 22 :/* 13.4 */
v12 = add_c_vertex() ;
add_triangle( tiling13_4[_config][3], 12, v12 ) ; break ;
case 23 :/* 13.5 */
_subconfig = 0 ;
if( test_interior( test13[_config][6] ) )
add_triangle( tiling13_5_1[_config][0], 6 ) ;
else
add_triangle( tiling13_5_2[_config][0], 10 ) ;
break ;
case 24 :/* 13.5 */
_subconfig = 1 ;
if( test_interior( test13[_config][6] ) )
add_triangle( tiling13_5_1[_config][1], 6 ) ;
else
add_triangle( tiling13_5_2[_config][1], 10 ) ;
break ;
case 25 :/* 13.5 */
_subconfig = 2 ;
if( test_interior( test13[_config][6] ) )
add_triangle( tiling13_5_1[_config][2], 6 ) ;
else
add_triangle( tiling13_5_2[_config][2], 10 ) ;
break ;
case 26 :/* 13.5 */
_subconfig = 3 ;
if( test_interior( test13[_config][6] ) )
add_triangle( tiling13_5_1[_config][3], 6 ) ;
else
add_triangle( tiling13_5_2[_config][3], 10 ) ;
break ;
case 27 :/* 13.3 */
v12 = add_c_vertex() ;
add_triangle( tiling13_3_[_config][0], 10, v12 ) ; break ;
case 28 :/* 13.3 */
v12 = add_c_vertex() ;
add_triangle( tiling13_3_[_config][1], 10, v12 ) ; break ;
case 29 :/* 13.3 */
v12 = add_c_vertex() ;
add_triangle( tiling13_3_[_config][2], 10, v12 ) ; break ;
case 30 :/* 13.3 */
v12 = add_c_vertex() ;
add_triangle( tiling13_3_[_config][3], 10, v12 ) ; break ;
case 31 :/* 13.3 */
v12 = add_c_vertex() ;
add_triangle( tiling13_3_[_config][4], 10, v12 ) ; break ;
case 32 :/* 13.3 */
v12 = add_c_vertex() ;
add_triangle( tiling13_3_[_config][5], 10, v12 ) ; break ;
case 33 :/* 13.3 */
v12 = add_c_vertex() ;
add_triangle( tiling13_3_[_config][6], 10, v12 ) ; break ;
case 34 :/* 13.3 */
v12 = add_c_vertex() ;
add_triangle( tiling13_3_[_config][7], 10, v12 ) ; break ;
case 35 :/* 13.3 */
v12 = add_c_vertex() ;
add_triangle( tiling13_3_[_config][8], 10, v12 ) ; break ;
case 36 :/* 13.3 */
v12 = add_c_vertex() ;
add_triangle( tiling13_3_[_config][9], 10, v12 ) ; break ;
case 37 :/* 13.3 */
v12 = add_c_vertex() ;
add_triangle( tiling13_3_[_config][10], 10, v12 ) ; break ;
case 38 :/* 13.3 */
v12 = add_c_vertex() ;
add_triangle( tiling13_3_[_config][11], 10, v12 ) ; break ;
case 39 :/* 13.2 */
add_triangle( tiling13_2_[_config][0], 6 ) ; break ;
case 40 :/* 13.2 */
add_triangle( tiling13_2_[_config][1], 6 ) ; break ;
case 41 :/* 13.2 */
add_triangle( tiling13_2_[_config][2], 6 ) ; break ;
case 42 :/* 13.2 */
add_triangle( tiling13_2_[_config][3], 6 ) ; break ;
case 43 :/* 13.2 */
add_triangle( tiling13_2_[_config][4], 6 ) ; break ;
case 44 :/* 13.2 */
add_triangle( tiling13_2_[_config][5], 6 ) ; break ;
case 45 :/* 13.1 */
add_triangle( tiling13_1_[_config], 4 ) ; break ;
default :
printf("Marching Cubes: Impossible case 13?\n" ) ; print_cube() ;
}
break ;
case 14 :
add_triangle( tiling14[_config], 4 ) ;
break ;
};
}
//_____________________________________________________________________________
//_____________________________________________________________________________
// Adding triangles
void MarchingCubes::add_triangle( const char* trig, char n, int v12 )
//-----------------------------------------------------------------------------
{
int tv[3] ;
for( int t = 0 ; t < 3*n ; t++ )
{
switch( trig[t] )
{
case 0 : tv[ t % 3 ] = get_x_vert( _i , _j , _k ) ; break ;
case 1 : tv[ t % 3 ] = get_y_vert(_i+1, _j , _k ) ; break ;
case 2 : tv[ t % 3 ] = get_x_vert( _i ,_j+1, _k ) ; break ;
case 3 : tv[ t % 3 ] = get_y_vert( _i , _j , _k ) ; break ;
case 4 : tv[ t % 3 ] = get_x_vert( _i , _j ,_k+1) ; break ;
case 5 : tv[ t % 3 ] = get_y_vert(_i+1, _j ,_k+1) ; break ;
case 6 : tv[ t % 3 ] = get_x_vert( _i ,_j+1,_k+1) ; break ;
case 7 : tv[ t % 3 ] = get_y_vert( _i , _j ,_k+1) ; break ;
case 8 : tv[ t % 3 ] = get_z_vert( _i , _j , _k ) ; break ;
case 9 : tv[ t % 3 ] = get_z_vert(_i+1, _j , _k ) ; break ;
case 10 : tv[ t % 3 ] = get_z_vert(_i+1,_j+1, _k ) ; break ;
case 11 : tv[ t % 3 ] = get_z_vert( _i ,_j+1, _k ) ; break ;
case 12 : tv[ t % 3 ] = v12 ; break ;
default : break ;
}
if( tv[t%3] == -1 )
{
printf("Marching Cubes: invalid triangle %d\n", _ntrigs+1) ;
print_cube() ;
}
if( t%3 == 2 )
{
if( _ntrigs >= _Ntrigs )
{
Triangle *temp = _triangles ;
_triangles = new Triangle[ 2*_Ntrigs ] ;
memcpy( _triangles, temp, _Ntrigs*sizeof(Triangle) ) ;
delete[] temp ;
printf("%d allocated triangles\n", _Ntrigs) ;
_Ntrigs *= 2 ;
}
Triangle *T = _triangles + _ntrigs++ ;
T->v1 = tv[0] ;
T->v2 = tv[1] ;
T->v3 = tv[2] ;
}
}
}
//_____________________________________________________________________________
//_____________________________________________________________________________
// Calculating gradient
real MarchingCubes::get_x_grad( const int i, const int j, const int k ) const
//-----------------------------------------------------------------------------
{
if( i > 0 )
{
if ( i < _size_x - 1 )
return ( get_data( i+1, j, k ) - get_data( i-1, j, k ) ) / 2 ;
else
return get_data( i, j, k ) - get_data( i-1, j, k ) ;
}
else
return get_data( i+1, j, k ) - get_data( i, j, k ) ;
}
//-----------------------------------------------------------------------------
real MarchingCubes::get_y_grad( const int i, const int j, const int k ) const
//-----------------------------------------------------------------------------
{
if( j > 0 )
{
if ( j < _size_y - 1 )
return ( get_data( i, j+1, k ) - get_data( i, j-1, k ) ) / 2 ;
else
return get_data( i, j, k ) - get_data( i, j-1, k ) ;
}
else
return get_data( i, j+1, k ) - get_data( i, j, k ) ;
}
//-----------------------------------------------------------------------------
real MarchingCubes::get_z_grad( const int i, const int j, const int k ) const
//-----------------------------------------------------------------------------
{
if( k > 0 )
{
if ( k < _size_z - 1 )
return ( get_data( i, j, k+1 ) - get_data( i, j, k-1 ) ) / 2 ;
else
return get_data( i, j, k ) - get_data( i, j, k-1 ) ;
}
else
return get_data( i, j, k+1 ) - get_data( i, j, k ) ;
}
//_____________________________________________________________________________
//_____________________________________________________________________________
// Adding vertices
void MarchingCubes::test_vertex_addition()
{
if( _nverts >= _Nverts )
{
Vertex *temp = _vertices ;
_vertices = new Vertex[ _Nverts*2 ] ;
memcpy( _vertices, temp, _Nverts*sizeof(Vertex) ) ;
delete[] temp ;
printf("%d allocated vertices\n", _Nverts) ;
_Nverts *= 2 ;
}
}
int MarchingCubes::add_x_vertex( )
//-----------------------------------------------------------------------------
{
test_vertex_addition() ;
Vertex *vert = _vertices + _nverts++ ;
real u = ( _cube[0] ) / ( _cube[0] - _cube[1] ) ;
vert->x = (real)_i+u;
vert->y = (real) _j ;
vert->z = (real) _k ;
vert->nx = (1-u)*get_x_grad(_i,_j,_k) + u*get_x_grad(_i+1,_j,_k) ;
vert->ny = (1-u)*get_y_grad(_i,_j,_k) + u*get_y_grad(_i+1,_j,_k) ;
vert->nz = (1-u)*get_z_grad(_i,_j,_k) + u*get_z_grad(_i+1,_j,_k) ;
u = (real) sqrt( vert->nx * vert->nx + vert->ny * vert->ny +vert->nz * vert->nz ) ;
if( u > 0 )
{
vert->nx /= u ;
vert->ny /= u ;
vert->nz /= u ;
}
return _nverts-1 ;
}
//-----------------------------------------------------------------------------
int MarchingCubes::add_y_vertex( )
//-----------------------------------------------------------------------------
{
test_vertex_addition() ;
Vertex *vert = _vertices + _nverts++ ;
real u = ( _cube[0] ) / ( _cube[0] - _cube[3] ) ;
vert->x = (real) _i ;
vert->y = (real)_j+u;
vert->z = (real) _k ;
vert->nx = (1-u)*get_x_grad(_i,_j,_k) + u*get_x_grad(_i,_j+1,_k) ;
vert->ny = (1-u)*get_y_grad(_i,_j,_k) + u*get_y_grad(_i,_j+1,_k) ;
vert->nz = (1-u)*get_z_grad(_i,_j,_k) + u*get_z_grad(_i,_j+1,_k) ;
u = (real) sqrt( vert->nx * vert->nx + vert->ny * vert->ny +vert->nz * vert->nz ) ;
if( u > 0 )
{
vert->nx /= u ;
vert->ny /= u ;
vert->nz /= u ;
}
return _nverts-1 ;
}
//-----------------------------------------------------------------------------
int MarchingCubes::add_z_vertex( )
//-----------------------------------------------------------------------------
{
test_vertex_addition() ;
Vertex *vert = _vertices + _nverts++ ;
real u = ( _cube[0] ) / ( _cube[0] - _cube[4] ) ;
vert->x = (real) _i ;
vert->y = (real) _j ;
vert->z = (real)_k+u;
vert->nx = (1-u)*get_x_grad(_i,_j,_k) + u*get_x_grad(_i,_j,_k+1) ;
vert->ny = (1-u)*get_y_grad(_i,_j,_k) + u*get_y_grad(_i,_j,_k+1) ;
vert->nz = (1-u)*get_z_grad(_i,_j,_k) + u*get_z_grad(_i,_j,_k+1) ;
u = (real) sqrt( vert->nx * vert->nx + vert->ny * vert->ny +vert->nz * vert->nz ) ;
if( u > 0 )
{
vert->nx /= u ;
vert->ny /= u ;
vert->nz /= u ;
}
return _nverts-1 ;
}
int MarchingCubes::add_c_vertex( )
//-----------------------------------------------------------------------------
{
test_vertex_addition() ;
Vertex *vert = _vertices + _nverts++ ;
real u = 0 ;
int vid ;
vert->x = vert->y = vert->z = vert->nx = vert->ny = vert->nz = 0 ;
// Computes the average of the intersection points of the cube
vid = get_x_vert( _i , _j , _k ) ;
if( vid != -1 ) { ++u ; const Vertex &v = _vertices[vid] ; vert->x += v.x ; vert->y += v.y ; vert->z += v.z ; vert->nx += v.nx ; vert->ny += v.ny ; vert->nz += v.nz ; }
vid = get_y_vert(_i+1, _j , _k ) ;
if( vid != -1 ) { ++u ; const Vertex &v = _vertices[vid] ; vert->x += v.x ; vert->y += v.y ; vert->z += v.z ; vert->nx += v.nx ; vert->ny += v.ny ; vert->nz += v.nz ; }
vid = get_x_vert( _i ,_j+1, _k ) ;
if( vid != -1 ) { ++u ; const Vertex &v = _vertices[vid] ; vert->x += v.x ; vert->y += v.y ; vert->z += v.z ; vert->nx += v.nx ; vert->ny += v.ny ; vert->nz += v.nz ; }
vid = get_y_vert( _i , _j , _k ) ;
if( vid != -1 ) { ++u ; const Vertex &v = _vertices[vid] ; vert->x += v.x ; vert->y += v.y ; vert->z += v.z ; vert->nx += v.nx ; vert->ny += v.ny ; vert->nz += v.nz ; }
vid = get_x_vert( _i , _j ,_k+1) ;
if( vid != -1 ) { ++u ; const Vertex &v = _vertices[vid] ; vert->x += v.x ; vert->y += v.y ; vert->z += v.z ; vert->nx += v.nx ; vert->ny += v.ny ; vert->nz += v.nz ; }
vid = get_y_vert(_i+1, _j ,_k+1) ;
if( vid != -1 ) { ++u ; const Vertex &v = _vertices[vid] ; vert->x += v.x ; vert->y += v.y ; vert->z += v.z ; vert->nx += v.nx ; vert->ny += v.ny ; vert->nz += v.nz ; }
vid = get_x_vert( _i ,_j+1,_k+1) ;
if( vid != -1 ) { ++u ; const Vertex &v = _vertices[vid] ; vert->x += v.x ; vert->y += v.y ; vert->z += v.z ; vert->nx += v.nx ; vert->ny += v.ny ; vert->nz += v.nz ; }
vid = get_y_vert( _i , _j ,_k+1) ;
if( vid != -1 ) { ++u ; const Vertex &v = _vertices[vid] ; vert->x += v.x ; vert->y += v.y ; vert->z += v.z ; vert->nx += v.nx ; vert->ny += v.ny ; vert->nz += v.nz ; }
vid = get_z_vert( _i , _j , _k ) ;
if( vid != -1 ) { ++u ; const Vertex &v = _vertices[vid] ; vert->x += v.x ; vert->y += v.y ; vert->z += v.z ; vert->nx += v.nx ; vert->ny += v.ny ; vert->nz += v.nz ; }
vid = get_z_vert(_i+1, _j , _k ) ;
if( vid != -1 ) { ++u ; const Vertex &v = _vertices[vid] ; vert->x += v.x ; vert->y += v.y ; vert->z += v.z ; vert->nx += v.nx ; vert->ny += v.ny ; vert->nz += v.nz ; }
vid = get_z_vert(_i+1,_j+1, _k ) ;
if( vid != -1 ) { ++u ; const Vertex &v = _vertices[vid] ; vert->x += v.x ; vert->y += v.y ; vert->z += v.z ; vert->nx += v.nx ; vert->ny += v.ny ; vert->nz += v.nz ; }
vid = get_z_vert( _i ,_j+1, _k ) ;
if( vid != -1 ) { ++u ; const Vertex &v = _vertices[vid] ; vert->x += v.x ; vert->y += v.y ; vert->z += v.z ; vert->nx += v.nx ; vert->ny += v.ny ; vert->nz += v.nz ; }
vert->x /= u ;
vert->y /= u ;
vert->z /= u ;
u = (real) sqrt( vert->nx * vert->nx + vert->ny * vert->ny +vert->nz * vert->nz ) ;
if( u > 0 )
{
vert->nx /= u ;
vert->ny /= u ;
vert->nz /= u ;
}
return _nverts-1 ;
}
//_____________________________________________________________________________
//_____________________________________________________________________________
//_____________________________________________________________________________
//_____________________________________________________________________________
// Grid exportation
void MarchingCubes::writeISO(const char *fn )
//-----------------------------------------------------------------------------
{
unsigned char buf[sizeof(float)] ;
FILE *fp = fopen( fn, "wb" ) ;
// header
* (int*) buf = _size_x ;
fwrite(buf, sizeof(float), 1, fp);
* (int*) buf = _size_y ;
fwrite(buf, sizeof(float), 1, fp);
* (int*) buf = _size_z ;
fwrite(buf, sizeof(float), 1, fp);
* (float*) buf = -1.0f ;
fwrite(buf, sizeof(float), 1, fp);
* (float*) buf = 1.0f ;
fwrite(buf, sizeof(float), 1, fp);
* (float*) buf = -1.0f ;
fwrite(buf, sizeof(float), 1, fp);
* (float*) buf = 1.0f ;
fwrite(buf, sizeof(float), 1, fp);
* (float*) buf = -1.0f ;
fwrite(buf, sizeof(float), 1, fp);
* (float*) buf = 1.0f ;
fwrite(buf, sizeof(float), 1, fp);
for( int i = 0 ; i < _size_x ; i++ )
{
for( int j = 0 ; j < _size_y ; j++ )
{
for( int k = 0 ; k < _size_z ; k++ )
{
* (float*) buf = (float)get_data( i,j,k ) ;
fwrite(buf, sizeof(float), 1, fp);
}
}
}
fclose(fp) ;
}
//_____________________________________________________________________________
//_____________________________________________________________________________
// PLY exportation
void MarchingCubes::writePLY(const char *fn, bool bin )
//-----------------------------------------------------------------------------
{
typedef struct PlyFace {
unsigned char nverts; /* number of Vertex indices in list */
int *verts; /* Vertex index list */
} PlyFace;
PlyProperty vert_props[] = { /* list of property information for a PlyVertex */
{"x", Float32, Float32, offsetof( Vertex,x ), 0, 0, 0, 0},
{"y", Float32, Float32, offsetof( Vertex,y ), 0, 0, 0, 0},
{"z", Float32, Float32, offsetof( Vertex,z ), 0, 0, 0, 0},
{"nx", Float32, Float32, offsetof( Vertex,nx ), 0, 0, 0, 0},
{"ny", Float32, Float32, offsetof( Vertex,ny ), 0, 0, 0, 0},
{"nz", Float32, Float32, offsetof( Vertex,nz ), 0, 0, 0, 0}
};
PlyProperty face_props[] = { /* list of property information for a PlyFace */
{"vertex_indices", Int32, Int32, offsetof( PlyFace,verts ),
1, Uint8, Uint8, offsetof( PlyFace,nverts )},
};
PlyFile *ply;
FILE *fp = fopen( fn, "w" );
int i ;
PlyFace face ;
int verts[3] ;
char *elem_names[] = { "vertex", "face" };
printf("Marching Cubes::writePLY(%s)...", fn ) ;
ply = write_ply ( fp, 2, elem_names, bin? PLY_BINARY_LE : PLY_ASCII );
/* describe what properties go into the PlyVertex elements */
describe_element_ply ( ply, "vertex", _nverts );
describe_property_ply ( ply, &vert_props[0] );
describe_property_ply ( ply, &vert_props[1] );
describe_property_ply ( ply, &vert_props[2] );
describe_property_ply ( ply, &vert_props[3] );
describe_property_ply ( ply, &vert_props[4] );
describe_property_ply ( ply, &vert_props[5] );
/* describe PlyFace properties (just list of PlyVertex indices) */
describe_element_ply ( ply, "face", _ntrigs );
describe_property_ply ( ply, &face_props[0] );
header_complete_ply ( ply );
/* set up and write the PlyVertex elements */
put_element_setup_ply ( ply, "vertex" );
for ( i = 0; i < _nverts; i++ )
put_element_ply ( ply, ( void * ) &(_vertices[i]) );
printf(" %d vertices written\n", _nverts ) ;
/* set up and write the PlyFace elements */
put_element_setup_ply ( ply, "face" );
face.nverts = 3 ;
face.verts = verts ;
for ( i = 0; i < _ntrigs; i++ )
{
face.verts[0] = _triangles[i].v1 ;
face.verts[1] = _triangles[i].v2 ;
face.verts[2] = _triangles[i].v3 ;
put_element_ply ( ply, ( void * ) &face );
}
printf(" %d triangles written\n", _ntrigs ) ;
close_ply ( ply );
free_ply ( ply );
fclose( fp ) ;
}
//_____________________________________________________________________________
//_____________________________________________________________________________
// PLY importation
void MarchingCubes::readPLY(const char *fn )
//-----------------------------------------------------------------------------
{
typedef struct PlyFace {
unsigned char nverts; /* number of Vertex indices in list */
int *verts; /* Vertex index list */
} PlyFace;
PlyProperty vert_props[] = { /* list of property information for a PlyVertex */
{"x", Float32, Float32, offsetof( Vertex,x ), 0, 0, 0, 0},
{"y", Float32, Float32, offsetof( Vertex,y ), 0, 0, 0, 0},
{"z", Float32, Float32, offsetof( Vertex,z ), 0, 0, 0, 0},
{"nx", Float32, Float32, offsetof( Vertex,nx ), 0, 0, 0, 0},
{"ny", Float32, Float32, offsetof( Vertex,ny ), 0, 0, 0, 0},
{"nz", Float32, Float32, offsetof( Vertex,nz ), 0, 0, 0, 0}
};
PlyProperty face_props[] = { /* list of property information for a PlyFace */
{"vertex_indices", Int32, Int32, offsetof( PlyFace,verts ),
1, Uint8, Uint8, offsetof( PlyFace,nverts )},
};
FILE *fp = fopen( fn, "r" );
if( !fp ) return ;
PlyFile *ply = read_ply ( fp );
printf("Marching Cubes::readPLY(%s)...", fn ) ;
//-----------------------------------------------------------------------------
// gets the number of faces and vertices
for ( int i = 0; i < ply->num_elem_types; ++i )
{
int elem_count ;
char *elem_name = setup_element_read_ply ( ply, i, &elem_count );
if ( equal_strings ( "vertex", elem_name ) )
_Nverts = _nverts = elem_count;
if ( equal_strings ( "face", elem_name ) )
_Ntrigs = _ntrigs = elem_count;
}
delete [] _vertices ;
_vertices = new Vertex [_Nverts] ;
delete [] _triangles ;
_triangles = new Triangle[_Ntrigs] ;
//-----------------------------------------------------------------------------
/* examine each element type that is in the file (PlyVertex, PlyFace) */
for ( int i = 0; i < ply->num_elem_types; ++i )
{
/* prepare to read the i'th list of elements */
int elem_count ;
char *elem_name = setup_element_read_ply ( ply, i, &elem_count );
//-----------------------------------------------------------------------------
if ( equal_strings ( "vertex", elem_name ) )
{
/* set up for getting PlyVertex elements */
setup_property_ply ( ply, &vert_props[0] );
setup_property_ply ( ply, &vert_props[1] );
setup_property_ply ( ply, &vert_props[2] );
setup_property_ply ( ply, &vert_props[3] );
setup_property_ply ( ply, &vert_props[4] );
setup_property_ply ( ply, &vert_props[5] );
for ( int j = 0; j < _nverts; ++j )
{
get_element_ply ( ply, ( void * ) (_vertices + j) );
}
printf(" %d vertices read\n", _nverts ) ;
}
//-----------------------------------------------------------------------------
else if ( equal_strings ( "face", elem_name ) )
{
/* set up for getting PlyFace elements */
/* (all we need are PlyVertex indices) */
setup_property_ply ( ply, &face_props[0] ) ;
PlyFace face ;
for ( int j = 0; j < _ntrigs; ++j )
{
get_element_ply ( ply, ( void * ) &face );
if( face.nverts != 3 )
{
printf( "not a triangulated surface: polygon %d has %d sides\n", j, face.nverts ) ;
return ;
}
_triangles[j].v1 = face.verts[0] ;
_triangles[j].v2 = face.verts[1] ;
_triangles[j].v3 = face.verts[2] ;
free( face.verts ) ;
}
printf(" %d triangles read\n", _ntrigs ) ;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
else /* all non-PlyVertex and non-PlyFace elements are grabbed here */
get_other_element_ply ( ply );
//-----------------------------------------------------------------------------
}
close_ply ( ply );
free_ply ( ply );
// fit_to_bbox() ;
fclose( fp ) ;
}
//_____________________________________________________________________________
//_____________________________________________________________________________
// Open Inventor / VRML 1.0 ascii exportation
void MarchingCubes::writeIV(const char *fn )
//-----------------------------------------------------------------------------
{
FILE *fp = fopen( fn, "w" ) ;
int i ;
printf("Marching Cubes::exportIV(%s)...", fn) ;
fprintf( fp, "#Inventor V2.1 ascii \n\nSeparator { \n ShapeHints {\n vertexOrdering COUNTERCLOCKWISE\n shapeType UNKNOWN_SHAPE_TYPE\n creaseAngle 0.0\n }\n Coordinate3 { \n point [ \n" ) ;
for ( i = 0; i < _nverts; i++ )
fprintf( fp, " %f %f %f,\n", _vertices[i].x, _vertices[i].y, _vertices[i].z ) ;
printf(" %d vertices written\n", _nverts ) ;
fprintf( fp, "\n ] \n} \nNormal { \nvector [ \n" ) ;
for ( i = 0; i < _nverts; i++ )
fprintf( fp, " %f %f %f,\n", _vertices[i].nx, _vertices[i].ny, _vertices[i].nz ) ;
fprintf( fp, "\n ] \n} \nIndexedFaceSet { \ncoordIndex [ \n" ) ;
for ( i = 0; i < _ntrigs; i++ )
fprintf( fp, "%d, %d, %d, -1,\n", _triangles[i].v1, _triangles[i].v2, _triangles[i].v3 ) ;
fprintf( fp, " ] \n } \n } \n" ) ;
fclose( fp ) ;
printf(" %d triangles written\n", _ntrigs ) ;
}
//_____________________________________________________________________________
| 0 | 0.955464 | 1 | 0.955464 | game-dev | MEDIA | 0.461375 | game-dev,graphics-rendering | 0.996795 | 1 | 0.996795 |
mir-ethernity/mir-eternal | 2,934 | Mir3DEditor/Eliot.UELib/Core/Classes/Values/UValueArrayProperty.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace UELib.Core.Classes.Values
{
public class UValueArrayProperty : UValueProperty
{
public UValueProperty[] Array { get; set; }
public override void Deserialize(IUnrealStream stream)
{
var position = stream.Position;
int arraySize = stream.ReadIndex();
Array = new UValueProperty[arraySize];
if (arraySize == 0)
return;
var buffLength = (int)(stream.Length - position - 4);
var expectedEqualsItemSize = (Size - 4) / arraySize;
var propertyType = "StructProperty";
var outer = Property._Outer ?? Property._Container.Class as UStruct;
var foundSpecificType = false;
for (var structField = outer; structField != null; structField = structField.Super as UStruct)
{
var nextField = outer.Children;
while (nextField != null)
{
if (nextField is UProperty && nextField.Name == Property.Name)
{
if (nextField is UArrayProperty arrayField && arrayField.InnerProperty != null)
{
propertyType = arrayField.InnerProperty.Type.ToString();
foundSpecificType = true;
break;
}
}
nextField = nextField.NextField;
}
if (foundSpecificType) break;
}
if (!foundSpecificType)
{
if (expectedEqualsItemSize == 0) expectedEqualsItemSize = 16;
if (expectedEqualsItemSize == 4) propertyType = "IntProperty";
else if (expectedEqualsItemSize == 16) propertyType = "Guid";
else if (expectedEqualsItemSize == 8) propertyType = "Name";
else if (expectedEqualsItemSize < 16) propertyType = "Unknown";
}
for (var i = 0; i < arraySize; i++)
{
//var arrayItemPos = stream.Position;
//var arrayItemSize = (int)(Size - (arrayItemPos - position));
//if (arrayItemSize <= 0) break;
Array[i] = UValuePropertyFactory.Create(Property, stream, propertyType, expectedEqualsItemSize);
}
}
public override void Serialize(IUnrealStream stream)
{
stream.WriteIndex(Array.Length);
for (var i = 0; i < Array.Length; i++)
Array[i].Serialize(stream);
}
public override string ToString()
{
var items = Array.Select((x, i) => $"[{i}] {x}").ToArray();
return string.Join(Environment.NewLine, items);
}
}
}
| 0 | 0.645463 | 1 | 0.645463 | game-dev | MEDIA | 0.771397 | game-dev | 0.952362 | 1 | 0.952362 |
dan200/ComputerCraft | 2,511 | src/main/java/dan200/computercraft/server/proxy/ComputerCraftProxyServer.java | /*
* This file is part of ComputerCraft - http://www.computercraft.info
* Copyright Daniel Ratcliffe, 2011-2017. Do not distribute without permission.
* Send enquiries to [email protected]
*/
package dan200.computercraft.server.proxy;
import dan200.computercraft.shared.computer.blocks.TileComputer;
import dan200.computercraft.shared.peripheral.diskdrive.TileDiskDrive;
import dan200.computercraft.shared.peripheral.printer.TilePrinter;
import dan200.computercraft.shared.proxy.ComputerCraftProxyCommon;
import dan200.computercraft.shared.turtle.blocks.TileTurtle;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.util.EnumHand;
import net.minecraft.util.SoundEvent;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.common.DimensionManager;
import java.io.File;
public class ComputerCraftProxyServer extends ComputerCraftProxyCommon
{
public ComputerCraftProxyServer()
{
}
// IComputerCraftProxy implementation
@Override
public void init()
{
super.init();
}
@Override
public Object getTurtleGUI( InventoryPlayer inventory, TileTurtle turtle )
{
return null;
}
@Override
public boolean isClient()
{
return false;
}
@Override
public boolean getGlobalCursorBlink()
{
return false;
}
@Override
public long getRenderFrame()
{
return 0;
}
@Override
public Object getFixedWidthFontRenderer()
{
return null;
}
@Override
public void playRecord( SoundEvent record, String recordInfo, World world, BlockPos pos )
{
}
@Override
public Object getDiskDriveGUI( InventoryPlayer inventory, TileDiskDrive drive )
{
return null;
}
@Override
public Object getComputerGUI( TileComputer computer )
{
return null;
}
@Override
public Object getPrinterGUI( InventoryPlayer inventory, TilePrinter printer )
{
return null;
}
@Override
public Object getPrintoutGUI( EntityPlayer player, EnumHand hand )
{
return null;
}
@Override
public Object getPocketComputerGUI( EntityPlayer player, EnumHand hand )
{
return null;
}
@Override
public File getWorldDir( World world )
{
return DimensionManager.getWorld( 0 ).getSaveHandler().getWorldDirectory();
}
}
| 0 | 0.621372 | 1 | 0.621372 | game-dev | MEDIA | 0.98208 | game-dev | 0.730883 | 1 | 0.730883 |
herzbube/littlego | 3,349 | src/go/GoUtilities.h | // -----------------------------------------------------------------------------
// Copyright 2011-2024 Patrick Näf ([email protected])
//
// 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.
// -----------------------------------------------------------------------------
// Forward declarations
@class GoGame;
@class GoGameRules;
@class GoMove;
@class GoNode;
@class GoPlayer;
@class GoPoint;
// -----------------------------------------------------------------------------
/// @brief The GoUtilities class is a container for various utility functions
/// that operate on all sorts of objects from the Go module.
///
/// @ingroup go
///
/// All functions in GoUtilities are class methods, so there is no need to
/// create an instance of GoUtilities.
// -----------------------------------------------------------------------------
@interface GoUtilities : NSObject
{
}
+ (void) movePointToNewRegion:(GoPoint*)thePoint;
+ (NSArray*) verticesForHandicap:(int)handicap boardSize:(enum GoBoardSize)boardSize;
+ (NSArray*) pointsForHandicap:(int)handicap inGame:(GoGame*)game;
+ (int) maximumHandicapForBoardSize:(enum GoBoardSize)boardSize;
+ (GoPlayer*) playerAfter:(GoMove*)move inCurrentGameVariation:(GoGame*)game;
+ (NSArray*) pointsInRectangleDelimitedByCornerPoint:(GoPoint*)pointA
oppositeCornerPoint:(GoPoint*)pointB
inGame:(GoGame*)game;
+ (NSArray*) pointsInRowWithPoint:(GoPoint*)point;
+ (NSArray*) pointsInColumnWithPoint:(GoPoint*)point;
+ (NSArray*) pointsInBothFirstArray:(NSArray*)firstArray
andSecondArray:(NSArray*)secondArray;
+ (double) defaultKomiForHandicap:(int)handicap scoringSystem:(enum GoScoringSystem)scoringSystem;
+ (GoGameRules*) rulesForRuleset:(enum GoRuleset)ruleset;
+ (enum GoRuleset) rulesetForRules:(GoGameRules*)rules;
+ (enum GoColor) alternatingColorForColor:(enum GoColor)color;
+ (bool) isGameInResumedPlayState:(GoGame*)game;
+ (bool) shouldAllowResumePlay:(GoGame*)game;
+ (NSString*) verticesStringForPoints:(NSArray*)points;
+ (void) recalculateZobristHashes:(GoGame*)game;
+ (void) relinkMoves:(GoGame*)game;
+ (GoNode*) nodeWithMostRecentMove:(GoNode*)node;
+ (GoNode*) nodeWithNextMove:(GoNode*)node inCurrentGameVariation:(GoGame*)game;
+ (bool) nodeWithNextMoveExists:(GoNode*)node inCurrentGameVariation:(GoGame*)game;
+ (int) numberOfMovesBeforeNode:(GoNode*)node;
+ (int) numberOfMovesAfterNode:(GoNode*)node inCurrentGameVariation:(GoGame*)game;
+ (GoNode*) nodeWithMostRecentSetup:(GoNode*)node inCurrentGameVariation:(GoGame*)game;
+ (GoNode*) nodeWithMostRecentBoardStateChange:(GoNode*)node;
+ (bool) showInfoIndicatorForNode:(GoNode*)node;
+ (bool) showHotspotIndicatorForNode:(GoNode*)node;
+ (enum NodeTreeViewCellSymbol) symbolForNode:(GoNode*)node inGame:(GoGame*)game;
@end
| 0 | 0.854493 | 1 | 0.854493 | game-dev | MEDIA | 0.975742 | game-dev | 0.77477 | 1 | 0.77477 |
microsoft/MixedReality-WorldLockingTools-Unity | 1,560 | Assets/MRTK/Core/Inspectors/PropertyDrawers/ExperimentalDrawer.cs | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using UnityEditor;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Editor
{
/// <summary>
/// Draws a customer decorator drawer that displays a help box with rich text tagging implementation as experimental.
/// </summary>
[CustomPropertyDrawer(typeof(ExperimentalAttribute))]
public class ExperimentalDrawer : DecoratorDrawer
{
/// <summary>
/// Unity calls this function to draw the GUI.
/// </summary>
/// <param name="position">Rectangle to display the GUI in</param>
public override void OnGUI(Rect position)
{
if (attribute is ExperimentalAttribute experimental)
{
var defaultValue = EditorStyles.helpBox.richText;
EditorStyles.helpBox.richText = true;
EditorGUI.HelpBox(position, experimental.Text, MessageType.Warning);
EditorStyles.helpBox.richText = defaultValue;
}
}
/// <summary>
/// Returns the height required to display UI elements drawn by OnGUI.
/// </summary>
/// <returns>The height required by OnGUI.</returns>
public override float GetHeight()
{
if (attribute is ExperimentalAttribute experimental)
{
return EditorStyles.helpBox.CalcHeight(new GUIContent(experimental.Text), EditorGUIUtility.currentViewWidth);
}
return base.GetHeight();
}
}
} | 0 | 0.734696 | 1 | 0.734696 | game-dev | MEDIA | 0.619358 | game-dev | 0.712519 | 1 | 0.712519 |
OskarSigvardsson/quickfracture | 4,864 | Assets/PostProcessing/Editor/Models/BuiltinDebugViewsEditor.cs | using UnityEngine.PostProcessing;
namespace UnityEditor.PostProcessing
{
using Mode = BuiltinDebugViewsModel.Mode;
using Settings = BuiltinDebugViewsModel.Settings;
[PostProcessingModelEditor(typeof(BuiltinDebugViewsModel), alwaysEnabled: true)]
public class BuiltinDebugViewsEditor : PostProcessingModelEditor
{
struct DepthSettings
{
public SerializedProperty scale;
}
struct MotionVectorsSettings
{
public SerializedProperty sourceOpacity;
public SerializedProperty motionImageOpacity;
public SerializedProperty motionImageAmplitude;
public SerializedProperty motionVectorsOpacity;
public SerializedProperty motionVectorsResolution;
public SerializedProperty motionVectorsAmplitude;
}
SerializedProperty m_Mode;
DepthSettings m_Depth;
MotionVectorsSettings m_MotionVectors;
public override void OnEnable()
{
m_Mode = FindSetting((Settings x) => x.mode);
m_Depth = new DepthSettings
{
scale = FindSetting((Settings x) => x.depth.scale)
};
m_MotionVectors = new MotionVectorsSettings
{
sourceOpacity = FindSetting((Settings x) => x.motionVectors.sourceOpacity),
motionImageOpacity = FindSetting((Settings x) => x.motionVectors.motionImageOpacity),
motionImageAmplitude = FindSetting((Settings x) => x.motionVectors.motionImageAmplitude),
motionVectorsOpacity = FindSetting((Settings x) => x.motionVectors.motionVectorsOpacity),
motionVectorsResolution = FindSetting((Settings x) => x.motionVectors.motionVectorsResolution),
motionVectorsAmplitude = FindSetting((Settings x) => x.motionVectors.motionVectorsAmplitude),
};
}
public override void OnInspectorGUI()
{
EditorGUILayout.PropertyField(m_Mode);
int mode = m_Mode.intValue;
if (mode == (int)Mode.Depth)
{
EditorGUILayout.PropertyField(m_Depth.scale);
}
else if (mode == (int)Mode.MotionVectors)
{
EditorGUILayout.HelpBox("Switch to play mode to see motion vectors.", MessageType.Info);
EditorGUILayout.LabelField("Source Image", EditorStyles.boldLabel);
EditorGUI.indentLevel++;
EditorGUILayout.PropertyField(m_MotionVectors.sourceOpacity, EditorGUIHelper.GetContent("Opacity"));
EditorGUI.indentLevel--;
EditorGUILayout.Space();
EditorGUILayout.LabelField("Motion Vectors (overlay)", EditorStyles.boldLabel);
EditorGUI.indentLevel++;
if (m_MotionVectors.motionImageOpacity.floatValue > 0f)
EditorGUILayout.HelpBox("Please keep opacity to 0 if you're subject to motion sickness.", MessageType.Warning);
EditorGUILayout.PropertyField(m_MotionVectors.motionImageOpacity, EditorGUIHelper.GetContent("Opacity"));
EditorGUILayout.PropertyField(m_MotionVectors.motionImageAmplitude, EditorGUIHelper.GetContent("Amplitude"));
EditorGUI.indentLevel--;
EditorGUILayout.Space();
EditorGUILayout.LabelField("Motion Vectors (arrows)", EditorStyles.boldLabel);
EditorGUI.indentLevel++;
EditorGUILayout.PropertyField(m_MotionVectors.motionVectorsOpacity, EditorGUIHelper.GetContent("Opacity"));
EditorGUILayout.PropertyField(m_MotionVectors.motionVectorsResolution, EditorGUIHelper.GetContent("Resolution"));
EditorGUILayout.PropertyField(m_MotionVectors.motionVectorsAmplitude, EditorGUIHelper.GetContent("Amplitude"));
EditorGUI.indentLevel--;
}
else
{
CheckActiveEffect(mode == (int)Mode.AmbientOcclusion && !profile.ambientOcclusion.enabled, "Ambient Occlusion");
CheckActiveEffect(mode == (int)Mode.FocusPlane && !profile.depthOfField.enabled, "Depth Of Field");
CheckActiveEffect(mode == (int)Mode.EyeAdaptation && !profile.eyeAdaptation.enabled, "Eye Adaptation");
CheckActiveEffect((mode == (int)Mode.LogLut || mode == (int)Mode.PreGradingLog) && !profile.colorGrading.enabled, "Color Grading");
CheckActiveEffect(mode == (int)Mode.UserLut && !profile.userLut.enabled, "User Lut");
}
}
void CheckActiveEffect(bool expr, string name)
{
if (expr)
EditorGUILayout.HelpBox(string.Format("{0} isn't enabled, the debug view won't work.", name), MessageType.Warning);
}
}
}
| 0 | 0.790992 | 1 | 0.790992 | game-dev | MEDIA | 0.610387 | game-dev | 0.956835 | 1 | 0.956835 |
Pan4ur/ThunderHack-Recode | 2,117 | src/main/java/thunder/hack/features/hud/impl/FpsCounter.java | package thunder.hack.features.hud.impl;
import com.mojang.blaze3d.platform.GlStateManager;
import com.mojang.blaze3d.systems.RenderSystem;
import net.minecraft.client.gui.DrawContext;
import net.minecraft.util.Formatting;
import thunder.hack.gui.font.FontRenderers;
import thunder.hack.features.hud.HudElement;
import thunder.hack.features.modules.client.HudEditor;
import thunder.hack.utility.math.FrameRateCounter;
import thunder.hack.utility.render.Render2DEngine;
import thunder.hack.utility.render.TextureStorage;
import java.awt.*;
public class FpsCounter extends HudElement {
public FpsCounter() {
super("Fps", 50, 10);
}
public void onRender2D(DrawContext context) {
super.onRender2D(context);
String str = "FPS " + Formatting.WHITE + FrameRateCounter.INSTANCE.getFps();
float pX = getPosX() > mc.getWindow().getScaledWidth() / 2f ? getPosX() - FontRenderers.getModulesRenderer().getStringWidth(str) : getPosX();
if (HudEditor.hudStyle.is(HudEditor.HudStyle.Blurry)) {
Render2DEngine.drawRoundedBlur(context.getMatrices(), pX, getPosY(), FontRenderers.getModulesRenderer().getStringWidth(str) + 21, 13f, 3, HudEditor.blurColor.getValue().getColorObject());
Render2DEngine.drawRect(context.getMatrices(), pX + 14, getPosY() + 2, 0.5f, 8, new Color(0x44FFFFFF, true));
Render2DEngine.setupRender();
RenderSystem.blendFunc(GlStateManager.SrcFactor.SRC_ALPHA, GlStateManager.DstFactor.ONE);
RenderSystem.setShaderTexture(0, TextureStorage.fpsIcon);
Render2DEngine.renderGradientTexture(context.getMatrices(), pX + 2, getPosY() + 1, 10, 10, 0, 0, 512, 512, 512, 512,
HudEditor.getColor(270), HudEditor.getColor(0), HudEditor.getColor(180), HudEditor.getColor(90));
Render2DEngine.endRender();
}
FontRenderers.getModulesRenderer().drawString(context.getMatrices(), str, pX + 18, getPosY() + 5, HudEditor.getColor(1).getRGB());
setBounds(pX, getPosY(), FontRenderers.getModulesRenderer().getStringWidth(str) + 21, 13f);
}
}
| 0 | 0.839302 | 1 | 0.839302 | game-dev | MEDIA | 0.736251 | game-dev,graphics-rendering | 0.99446 | 1 | 0.99446 |
beyond-aion/aion-server | 3,273 | game-server/data/handlers/admincommands/UseSkill.java | package admincommands;
import org.apache.commons.lang3.math.NumberUtils;
import com.aionemu.gameserver.dataholders.DataManager;
import com.aionemu.gameserver.model.gameobjects.Creature;
import com.aionemu.gameserver.model.gameobjects.VisibleObject;
import com.aionemu.gameserver.model.gameobjects.player.Player;
import com.aionemu.gameserver.network.aion.serverpackets.SM_SYSTEM_MESSAGE;
import com.aionemu.gameserver.skillengine.SkillEngine;
import com.aionemu.gameserver.skillengine.model.Skill;
import com.aionemu.gameserver.skillengine.model.SkillTemplate;
import com.aionemu.gameserver.utils.PacketSendUtility;
import com.aionemu.gameserver.utils.chathandlers.AdminCommand;
/**
* @author Source, kecimis, Estrayl, Neon
*/
public class UseSkill extends AdminCommand {
public UseSkill() {
super("useskill", "Use (or let a target use) any skill, even those not in skill list.");
// @formatter:off
setSyntaxInfo(
"<id> [lvl] [f] - Uses the skill with the specified skill level on your target (f = force use).",
"<me|self|target> <id> [lvl] [f] - Let's your target use the skill on you, itself or its target (f = force use)."
);
// @formatter:on
}
@Override
protected void execute(Player admin, String... params) {
if (params.length == 0) {
sendInfo(admin);
return;
}
try {
String targetMode = params[0].toLowerCase();
int i = 0;
switch (targetMode) {
case "me":
case "self":
case "target":
i++;
break;
default:
targetMode = null;
}
SkillTemplate template = DataManager.SKILL_DATA.getSkillTemplate(Integer.parseInt(params[i++]));
if (template != null) {
int skillLevel = params.length > i && NumberUtils.isNumber(params[i]) ? Integer.parseInt(params[i++]) : template.getLvl();
boolean forceUse = params.length > i && params[i].equals("f");
if (useSkill(admin, template, skillLevel, targetMode, forceUse))
sendInfo(admin, "Used skill: " + template.getL10n());
else
sendInfo(admin, "Could not use skill (" + (forceUse ? "missing preconditions" : "add parameter 'f' to force use") + ").");
} else {
sendInfo(admin, "Invalid skill id.");
}
} catch (NumberFormatException e) {
sendInfo(admin, "Invalid skill id or level.");
}
}
private boolean useSkill(Player player, SkillTemplate template, int skillLevel, String targetMode, boolean forceUse) {
Creature effector;
VisibleObject target;
if (targetMode != null) {
if (!(player.getTarget() instanceof Creature creatureTarget)) {
PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.STR_INVALID_TARGET());
return false;
}
effector = creatureTarget;
target = getTarget(player, targetMode);
} else {
effector = player;
target = player.getTarget();
}
Skill skill = SkillEngine.getInstance().getSkill(effector, template.getSkillId(), skillLevel, target);
if (skill != null)
return forceUse ? skill.useWithoutPropSkill() : skill.useNoAnimationSkill();
return false;
}
private VisibleObject getTarget(Player player, String targetMode) {
return switch (targetMode) {
case "me" -> player;
case "self" -> player.getTarget();
case "target" -> player.getTarget() == null ? null : player.getTarget().getTarget();
default -> null;
};
}
}
| 0 | 0.889353 | 1 | 0.889353 | game-dev | MEDIA | 0.947154 | game-dev | 0.964711 | 1 | 0.964711 |
cnlohr/embeddedDOOM | 18,144 | src/p_inter.c | // Emacs style mode select -*- C++ -*-
//-----------------------------------------------------------------------------
//
// $Id:$
//
// Copyright (C) 1993-1996 by id Software, Inc.
//
// This source is available for distribution and/or modification
// only under the terms of the DOOM Source Code License as
// published by id Software. All rights reserved.
//
// The source is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// FITNESS FOR A PARTICULAR PURPOSE. See the DOOM Source Code License
// for more details.
//
// $Log:$
//
// DESCRIPTION:
// Handling interactions (i.e., collisions).
//
//-----------------------------------------------------------------------------
//static const char
//rcsid[] = "$Id: p_inter.c,v 1.4 1997/02/03 22:45:11 b1 Exp $";
// Data.
#include "doomdef.h"
#include "dstrings.h"
#include "sounds.h"
#include "doomstat.h"
#include "m_random.h"
#include "i_system.h"
#include "am_map.h"
#include "p_local.h"
#include "s_sound.h"
#ifdef __GNUG__
#pragma implementation "p_inter.h"
#endif
#include "p_inter.h"
#define BONUSADD 6
// a weapon is found with two clip loads,
// a big item has five clip loads
int maxammo[NUMAMMO] = {200, 50, 300, 50};
int clipammo[NUMAMMO] = {10, 4, 20, 1};
//
// GET STUFF
//
//
// P_GiveAmmo
// Num is the number of clip loads,
// not the individual count (0= 1/2 clip).
// Returns false if the ammo can't be picked up at all
//
boolean
P_GiveAmmo
( player_t* player,
ammotype_t ammo,
int num )
{
int oldammo;
if (ammo == am_noammo)
return false;
if (ammo < 0 || ammo > NUMAMMO)
I_Error ("P_GiveAmmo: bad type %i", ammo);
if ( player->ammo[ammo] == player->maxammo[ammo] )
return false;
if (num)
num *= clipammo[ammo];
else
num = clipammo[ammo]/2;
if (gameskill == sk_baby
|| gameskill == sk_nightmare)
{
// give double ammo in trainer mode,
// you'll need in nightmare
num <<= 1;
}
oldammo = player->ammo[ammo];
player->ammo[ammo] += num;
if (player->ammo[ammo] > player->maxammo[ammo])
player->ammo[ammo] = player->maxammo[ammo];
// If non zero ammo,
// don't change up weapons,
// player was lower on purpose.
if (oldammo)
return true;
// We were down to zero,
// so select a new weapon.
// Preferences are not user selectable.
switch (ammo)
{
case am_clip:
if (player->readyweapon == wp_fist)
{
if (player->weaponowned[wp_chaingun])
player->pendingweapon = wp_chaingun;
else
player->pendingweapon = wp_pistol;
}
break;
case am_shell:
if (player->readyweapon == wp_fist
|| player->readyweapon == wp_pistol)
{
if (player->weaponowned[wp_shotgun])
player->pendingweapon = wp_shotgun;
}
break;
case am_cell:
if (player->readyweapon == wp_fist
|| player->readyweapon == wp_pistol)
{
if (player->weaponowned[wp_plasma])
player->pendingweapon = wp_plasma;
}
break;
case am_misl:
if (player->readyweapon == wp_fist)
{
if (player->weaponowned[wp_missile])
player->pendingweapon = wp_missile;
}
default:
break;
}
return true;
}
//
// P_GiveWeapon
// The weapon name may have a MF_DROPPED flag ored in.
//
boolean
P_GiveWeapon
( player_t* player,
weapontype_t weapon,
boolean dropped )
{
boolean gaveammo;
boolean gaveweapon;
if (netgame
&& (deathmatch!=2)
&& !dropped )
{
// leave placed weapons forever on net games
if (player->weaponowned[weapon])
return false;
player->bonuscount += BONUSADD;
player->weaponowned[weapon] = true;
if (deathmatch)
P_GiveAmmo (player, weaponinfo[weapon].ammo, 5);
else
P_GiveAmmo (player, weaponinfo[weapon].ammo, 2);
player->pendingweapon = weapon;
if (player == &players[consoleplayer])
S_StartSound (NULL, sfx_wpnup);
return false;
}
if (weaponinfo[weapon].ammo != am_noammo)
{
// give one clip with a dropped weapon,
// two clips with a found weapon
if (dropped)
gaveammo = P_GiveAmmo (player, weaponinfo[weapon].ammo, 1);
else
gaveammo = P_GiveAmmo (player, weaponinfo[weapon].ammo, 2);
}
else
gaveammo = false;
if (player->weaponowned[weapon])
gaveweapon = false;
else
{
gaveweapon = true;
player->weaponowned[weapon] = true;
player->pendingweapon = weapon;
}
return (gaveweapon || gaveammo);
}
//
// P_GiveBody
// Returns false if the body isn't needed at all
//
boolean
P_GiveBody
( player_t* player,
int num )
{
if (player->health >= MAXHEALTH)
return false;
player->health += num;
if (player->health > MAXHEALTH)
player->health = MAXHEALTH;
player->mo->health = player->health;
return true;
}
//
// P_GiveArmor
// Returns false if the armor is worse
// than the current armor.
//
boolean
P_GiveArmor
( player_t* player,
int armortype )
{
int hits;
hits = armortype*100;
if (player->armorpoints >= hits)
return false; // don't pick up
player->armortype = armortype;
player->armorpoints = hits;
return true;
}
//
// P_GiveCard
//
void
P_GiveCard
( player_t* player,
card_t card )
{
if (player->cards[card])
return;
player->bonuscount = BONUSADD;
player->cards[card] = 1;
}
//
// P_GivePower
//
boolean
P_GivePower
( player_t* player,
int /*powertype_t*/ power )
{
if (power == pw_invulnerability)
{
player->powers[power] = INVULNTICS;
return true;
}
if (power == pw_invisibility)
{
player->powers[power] = INVISTICS;
player->mo->flags |= MF_SHADOW;
return true;
}
if (power == pw_infrared)
{
player->powers[power] = INFRATICS;
return true;
}
if (power == pw_ironfeet)
{
player->powers[power] = IRONTICS;
return true;
}
if (power == pw_strength)
{
P_GiveBody (player, 100);
player->powers[power] = 1;
return true;
}
if (player->powers[power])
return false; // already got it
player->powers[power] = 1;
return true;
}
//
// P_TouchSpecialThing
//
void
P_TouchSpecialThing
( mobj_t* special,
mobj_t* toucher )
{
player_t* player;
int i;
fixed_t delta;
int sound;
delta = special->z - toucher->z;
if (delta > toucher->height
|| delta < -8*FRACUNIT)
{
// out of reach
return;
}
sound = sfx_itemup;
player = toucher->player;
// Dead thing touching.
// Can happen with a sliding player corpse.
if (toucher->health <= 0)
return;
// Identify by sprite.
switch (special->sprite)
{
// armor
case SPR_ARM1:
if (!P_GiveArmor (player, 1))
return;
player->message = GOTARMOR;
break;
case SPR_ARM2:
if (!P_GiveArmor (player, 2))
return;
player->message = GOTMEGA;
break;
// bonus items
case SPR_BON1:
player->health++; // can go over 100%
if (player->health > 200)
player->health = 200;
player->mo->health = player->health;
player->message = GOTHTHBONUS;
break;
case SPR_BON2:
player->armorpoints++; // can go over 100%
if (player->armorpoints > 200)
player->armorpoints = 200;
if (!player->armortype)
player->armortype = 1;
player->message = GOTARMBONUS;
break;
case SPR_SOUL:
player->health += 100;
if (player->health > 200)
player->health = 200;
player->mo->health = player->health;
player->message = GOTSUPER;
sound = sfx_getpow;
break;
case SPR_MEGA:
if (gamemode != commercial)
return;
player->health = 200;
player->mo->health = player->health;
P_GiveArmor (player,2);
player->message = GOTMSPHERE;
sound = sfx_getpow;
break;
// cards
// leave cards for everyone
case SPR_BKEY:
if (!player->cards[it_bluecard])
player->message = GOTBLUECARD;
P_GiveCard (player, it_bluecard);
if (!netgame)
break;
return;
case SPR_YKEY:
if (!player->cards[it_yellowcard])
player->message = GOTYELWCARD;
P_GiveCard (player, it_yellowcard);
if (!netgame)
break;
return;
case SPR_RKEY:
if (!player->cards[it_redcard])
player->message = GOTREDCARD;
P_GiveCard (player, it_redcard);
if (!netgame)
break;
return;
case SPR_BSKU:
if (!player->cards[it_blueskull])
player->message = GOTBLUESKUL;
P_GiveCard (player, it_blueskull);
if (!netgame)
break;
return;
case SPR_YSKU:
if (!player->cards[it_yellowskull])
player->message = GOTYELWSKUL;
P_GiveCard (player, it_yellowskull);
if (!netgame)
break;
return;
case SPR_RSKU:
if (!player->cards[it_redskull])
player->message = GOTREDSKULL;
P_GiveCard (player, it_redskull);
if (!netgame)
break;
return;
// medikits, heals
case SPR_STIM:
if (!P_GiveBody (player, 10))
return;
player->message = GOTSTIM;
break;
case SPR_MEDI:
if (!P_GiveBody (player, 25))
return;
if (player->health < 25)
player->message = GOTMEDINEED;
else
player->message = GOTMEDIKIT;
break;
// power ups
case SPR_PINV:
if (!P_GivePower (player, pw_invulnerability))
return;
player->message = GOTINVUL;
sound = sfx_getpow;
break;
case SPR_PSTR:
if (!P_GivePower (player, pw_strength))
return;
player->message = GOTBERSERK;
if (player->readyweapon != wp_fist)
player->pendingweapon = wp_fist;
sound = sfx_getpow;
break;
case SPR_PINS:
if (!P_GivePower (player, pw_invisibility))
return;
player->message = GOTINVIS;
sound = sfx_getpow;
break;
case SPR_SUIT:
if (!P_GivePower (player, pw_ironfeet))
return;
player->message = GOTSUIT;
sound = sfx_getpow;
break;
case SPR_PMAP:
if (!P_GivePower (player, pw_allmap))
return;
player->message = GOTMAP;
sound = sfx_getpow;
break;
case SPR_PVIS:
if (!P_GivePower (player, pw_infrared))
return;
player->message = GOTVISOR;
sound = sfx_getpow;
break;
// ammo
case SPR_CLIP:
if (special->flags & MF_DROPPED)
{
if (!P_GiveAmmo (player,am_clip,0))
return;
}
else
{
if (!P_GiveAmmo (player,am_clip,1))
return;
}
player->message = GOTCLIP;
break;
case SPR_AMMO:
if (!P_GiveAmmo (player, am_clip,5))
return;
player->message = GOTCLIPBOX;
break;
case SPR_ROCK:
if (!P_GiveAmmo (player, am_misl,1))
return;
player->message = GOTROCKET;
break;
case SPR_BROK:
if (!P_GiveAmmo (player, am_misl,5))
return;
player->message = GOTROCKBOX;
break;
case SPR_CELL:
if (!P_GiveAmmo (player, am_cell,1))
return;
player->message = GOTCELL;
break;
case SPR_CELP:
if (!P_GiveAmmo (player, am_cell,5))
return;
player->message = GOTCELLBOX;
break;
case SPR_SHEL:
if (!P_GiveAmmo (player, am_shell,1))
return;
player->message = GOTSHELLS;
break;
case SPR_SBOX:
if (!P_GiveAmmo (player, am_shell,5))
return;
player->message = GOTSHELLBOX;
break;
case SPR_BPAK:
if (!player->backpack)
{
for (i=0 ; i<NUMAMMO ; i++)
player->maxammo[i] *= 2;
player->backpack = true;
}
for (i=0 ; i<NUMAMMO ; i++)
P_GiveAmmo (player, i, 1);
player->message = GOTBACKPACK;
break;
// weapons
case SPR_BFUG:
if (!P_GiveWeapon (player, wp_bfg, false) )
return;
player->message = GOTBFG9000;
sound = sfx_wpnup;
break;
case SPR_MGUN:
if (!P_GiveWeapon (player, wp_chaingun, special->flags&MF_DROPPED) )
return;
player->message = GOTCHAINGUN;
sound = sfx_wpnup;
break;
case SPR_CSAW:
if (!P_GiveWeapon (player, wp_chainsaw, false) )
return;
player->message = GOTCHAINSAW;
sound = sfx_wpnup;
break;
case SPR_LAUN:
if (!P_GiveWeapon (player, wp_missile, false) )
return;
player->message = GOTLAUNCHER;
sound = sfx_wpnup;
break;
case SPR_PLAS:
if (!P_GiveWeapon (player, wp_plasma, false) )
return;
player->message = GOTPLASMA;
sound = sfx_wpnup;
break;
case SPR_SHOT:
if (!P_GiveWeapon (player, wp_shotgun, special->flags&MF_DROPPED ) )
return;
player->message = GOTSHOTGUN;
sound = sfx_wpnup;
break;
case SPR_SGN2:
if (!P_GiveWeapon (player, wp_supershotgun, special->flags&MF_DROPPED ) )
return;
player->message = GOTSHOTGUN2;
sound = sfx_wpnup;
break;
default:
I_Error ("P_SpecialThing: Unknown gettable thing");
}
if (special->flags & MF_COUNTITEM)
player->itemcount++;
P_RemoveMobj (special);
player->bonuscount += BONUSADD;
if (player == &players[consoleplayer])
S_StartSound (NULL, sound);
}
//
// KillMobj
//
void
P_KillMobj
( mobj_t* source,
mobj_t* target )
{
mobjtype_t item;
mobj_t* mo;
target->flags &= ~(MF_SHOOTABLE|MF_FLOAT|MF_SKULLFLY);
if (target->type != MT_SKULL)
target->flags &= ~MF_NOGRAVITY;
target->flags |= MF_CORPSE|MF_DROPOFF;
target->height >>= 2;
if (source && source->player)
{
// count for intermission
if (target->flags & MF_COUNTKILL)
source->player->killcount++;
if (target->player)
source->player->frags[target->player-players]++;
}
else if (!netgame && (target->flags & MF_COUNTKILL) )
{
// count all monster deaths,
// even those caused by other monsters
players[0].killcount++;
}
if (target->player)
{
// count environment kills against you
if (!source)
target->player->frags[target->player-players]++;
target->flags &= ~MF_SOLID;
target->player->playerstate = PST_DEAD;
P_DropWeapon (target->player);
if (target->player == &players[consoleplayer]
&& automapactive)
{
// don't die in auto map,
// switch view prior to dying
AM_Stop ();
}
}
if (target->health < -target->info->spawnhealth
&& target->info->xdeathstate)
{
P_SetMobjState (target, target->info->xdeathstate);
}
else
P_SetMobjState (target, target->info->deathstate);
target->tics -= P_Random()&3;
if (target->tics < 1)
target->tics = 1;
// I_StartSound (&actor->r, actor->info->deathsound);
// Drop stuff.
// This determines the kind of object spawned
// during the death frame of a thing.
switch (target->type)
{
case MT_WOLFSS:
case MT_POSSESSED:
item = MT_CLIP;
break;
case MT_SHOTGUY:
item = MT_SHOTGUN;
break;
case MT_CHAINGUY:
item = MT_CHAINGUN;
break;
default:
return;
}
mo = P_SpawnMobj (target->x,target->y,ONFLOORZ, item);
mo->flags |= MF_DROPPED; // special versions of items
}
//
// P_DamageMobj
// Damages both enemies and players
// "inflictor" is the thing that caused the damage
// creature or missile, can be NULL (slime, etc)
// "source" is the thing to target after taking damage
// creature or NULL
// Source and inflictor are the same for melee attacks.
// Source can be NULL for slime, barrel explosions
// and other environmental stuff.
//
void
P_DamageMobj
( mobj_t* target,
mobj_t* inflictor,
mobj_t* source,
int damage )
{
unsigned ang;
int saved;
player_t* player;
fixed_t thrust;
int temp;
if ( !(target->flags & MF_SHOOTABLE) )
return; // shouldn't happen...
if (target->health <= 0)
return;
if ( target->flags & MF_SKULLFLY )
{
target->momx = target->momy = target->momz = 0;
}
player = target->player;
if (player && gameskill == sk_baby)
damage >>= 1; // take half damage in trainer mode
// Some close combat weapons should not
// inflict thrust and push the victim out of reach,
// thus kick away unless using the chainsaw.
if (inflictor
&& !(target->flags & MF_NOCLIP)
&& (!source
|| !source->player
|| source->player->readyweapon != wp_chainsaw))
{
ang = R_PointToAngle2 ( inflictor->x,
inflictor->y,
target->x,
target->y);
thrust = damage*(FRACUNIT>>3)*100/target->info->mass;
// make fall forwards sometimes
if ( damage < 40
&& damage > target->health
&& target->z - inflictor->z > 64*FRACUNIT
&& (P_Random ()&1) )
{
ang += ANG180;
thrust *= 4;
}
ang >>= ANGLETOFINESHIFT;
target->momx += FixedMul (thrust, finecosine[ang]);
target->momy += FixedMul (thrust, finesine[ang]);
}
// player specific
if (player)
{
// end of game hell hack
if (target->subsector->sector->special == 11
&& damage >= target->health)
{
damage = target->health - 1;
}
// Below certain threshold,
// ignore damage in GOD mode, or with INVUL power.
if ( damage < 1000
&& ( (player->cheats&CF_GODMODE)
|| player->powers[pw_invulnerability] ) )
{
return;
}
if (player->armortype)
{
if (player->armortype == 1)
saved = damage/3;
else
saved = damage/2;
if (player->armorpoints <= saved)
{
// armor is used up
saved = player->armorpoints;
player->armortype = 0;
}
player->armorpoints -= saved;
damage -= saved;
}
player->health -= damage; // mirror mobj health here for Dave
if (player->health < 0)
player->health = 0;
player->attacker = source;
player->damagecount += damage; // add damage after armor / invuln
if (player->damagecount > 100)
player->damagecount = 100; // teleport stomp does 10k points...
temp = damage < 100 ? damage : 100;
if (player == &players[consoleplayer])
I_Tactile (40,10,40+temp*2);
}
// do the damage
target->health -= damage;
if (target->health <= 0)
{
P_KillMobj (source, target);
return;
}
if ( (P_Random () < target->info->painchance)
&& !(target->flags&MF_SKULLFLY) )
{
target->flags |= MF_JUSTHIT; // fight back!
P_SetMobjState (target, target->info->painstate);
}
target->reactiontime = 0; // we're awake now...
if ( (!target->threshold || target->type == MT_VILE)
&& source && source != target
&& source->type != MT_VILE)
{
// if not intent on another player,
// chase after this one
target->target = source;
target->threshold = BASETHRESHOLD;
if (target->state == &states[target->info->spawnstate]
&& target->info->seestate != S_NULL)
P_SetMobjState (target, target->info->seestate);
}
}
| 0 | 0.989056 | 1 | 0.989056 | game-dev | MEDIA | 0.974895 | game-dev | 0.976348 | 1 | 0.976348 |
stevefolta/SFZero | 11,299 | module/SFZero/SFZero/SFZReader.cpp | #include "SFZReader.h"
#include "SFZRegion.h"
#include "SFZSound.h"
#include "StringSlice.h"
#include "SFZDebug.h"
using namespace SFZero;
SFZReader::SFZReader(SFZSound* soundIn)
: sound(soundIn), line(1)
{
}
SFZReader::~SFZReader()
{
}
void SFZReader::read(const File& file)
{
MemoryBlock contents;
bool ok = file.loadFileAsData(contents);
if (!ok) {
sound->addError("Couldn't read \"" + file.getFullPathName() + "\"");
return;
}
read((const char*) contents.getData(), contents.getSize());
}
void SFZReader::read(const char* text, unsigned int length)
{
const char* p = text;
const char* end = text + length;
char c;
SFZRegion curGroup;
SFZRegion curRegion;
SFZRegion* buildingRegion = NULL;
bool inControl = false;
String defaultPath;
while (p < end) {
// We're at the start of a line; skip any whitespace.
while (p < end) {
c = *p;
if (c != ' ' && c != '\t')
break;
p += 1;
}
if (p >= end)
break;
// Check if it's a comment line.
if (c == '/') {
// Skip to end of line.
while (p < end) {
c = *++p;
if (c == '\n' || c == '\r')
break;
}
p = handleLineEnd(p);
continue;
}
// Check if it's a blank line.
if (c == '\r' || c == '\n') {
p = handleLineEnd(p);
continue;
}
// Handle elements on the line.
while (p < end) {
c = *p;
// Tag.
if (c == '<') {
p += 1;
const char* tagStart = p;
while (p < end) {
c = *p++;
if (c == '\n' || c == '\r') {
error("Unterminated tag");
goto fatalError;
}
else if (c == '>')
break;
}
if (p >= end) {
error("Unterminated tag");
goto fatalError;
}
StringSlice tag(tagStart, p - 1);
if (tag == "region") {
if (buildingRegion && buildingRegion == &curRegion)
finishRegion(&curRegion);
curRegion = curGroup;
buildingRegion = &curRegion;
inControl = false;
}
else if (tag == "group") {
if (buildingRegion && buildingRegion == &curRegion)
finishRegion(&curRegion);
curGroup.clear();
buildingRegion = &curGroup;
inControl = false;
}
else if (tag == "control") {
if (buildingRegion && buildingRegion == &curRegion)
finishRegion(&curRegion);
curGroup.clear();
buildingRegion = NULL;
inControl = true;
}
else
error("Illegal tag");
}
// Comment.
else if (c == '/') {
// Skip to end of line.
while (p < end) {
c = *p;
if (c == '\r' || c == '\n')
break;
p += 1;
}
}
// Parameter.
else {
// Get the parameter name.
const char* parameterStart = p;
while (p < end) {
c = *p++;
if (c == '=' || c == ' ' || c == '\t' || c == '\r' || c == '\n')
break;
}
if (p >= end || c != '=') {
error("Malformed parameter");
goto nextElement;
}
StringSlice opcode(parameterStart, p - 1);
if (inControl) {
if (opcode == "default_path")
p = readPathInto(&defaultPath, p, end);
else {
const char* valueStart = p;
while (p < end) {
c = *p;
if (c == ' ' || c == '\t' || c == '\n' || c == '\r')
break;
p++;
}
String value(valueStart, p - valueStart);
String fauxOpcode =
String(opcode.start, opcode.length()) + " (in <control>)";
sound->addUnsupportedOpcode(fauxOpcode);
}
}
else if (opcode == "sample") {
String path;
p = readPathInto(&path, p, end);
if (!path.isEmpty()) {
if (buildingRegion)
buildingRegion->sample = sound->addSample(path, defaultPath);
else
error("Adding sample outside a group or region");
}
else
error("Empty sample path");
}
else {
const char* valueStart = p;
while (p < end) {
c = *p;
if (c == ' ' || c == '\t' || c == '\n' || c == '\r')
break;
p++;
}
String value(valueStart, p - valueStart);
if (buildingRegion == NULL)
error("Setting a parameter outside a region or group");
else if (opcode == "lokey")
buildingRegion->lokey = keyValue(value);
else if (opcode == "hikey")
buildingRegion->hikey = keyValue(value);
else if (opcode == "key") {
buildingRegion->hikey =
buildingRegion->lokey =
buildingRegion->pitch_keycenter =
keyValue(value);
}
else if (opcode == "lovel")
buildingRegion->lovel = value.getIntValue();
else if (opcode == "hivel")
buildingRegion->hivel = value.getIntValue();
else if (opcode == "trigger")
buildingRegion->trigger = (SFZRegion::Trigger) triggerValue(value);
else if (opcode == "group")
buildingRegion->group = (unsigned long) value.getLargeIntValue();
else if (opcode == "off_by")
buildingRegion->off_by = (unsigned long) value.getLargeIntValue();
else if (opcode == "offset")
buildingRegion->offset = (unsigned long) value.getLargeIntValue();
else if (opcode == "end") {
int64 end = (unsigned long) value.getLargeIntValue();
if (end < 0)
buildingRegion->negative_end = true;
else
buildingRegion->end = end;
}
else if (opcode == "loop_mode") {
bool modeIsSupported =
value == "no_loop" ||
value == "one_shot" ||
value == "loop_continuous";
if (modeIsSupported)
buildingRegion->loop_mode = (SFZRegion::LoopMode) loopModeValue(value);
else {
String fauxOpcode =
String(opcode.start, opcode.length()) + "=" + value;
sound->addUnsupportedOpcode(fauxOpcode);
}
}
else if (opcode == "loop_start")
buildingRegion->loop_start = (unsigned long) value.getLargeIntValue();
else if (opcode == "loop_end")
buildingRegion->loop_end = (unsigned long) value.getLargeIntValue();
else if (opcode == "transpose")
buildingRegion->transpose = value.getIntValue();
else if (opcode == "tune")
buildingRegion->tune = value.getIntValue();
else if (opcode == "pitch_keycenter")
buildingRegion->pitch_keycenter = keyValue(value);
else if (opcode == "pitch_keytrack")
buildingRegion->pitch_keytrack = value.getIntValue();
else if (opcode == "bend_up")
buildingRegion->bend_up = value.getIntValue();
else if (opcode == "bend_down")
buildingRegion->bend_down = value.getIntValue();
else if (opcode == "volume")
buildingRegion->volume = value.getFloatValue();
else if (opcode == "pan")
buildingRegion->pan = value.getFloatValue();
else if (opcode == "amp_veltrack")
buildingRegion->amp_veltrack = value.getFloatValue();
else if (opcode == "ampeg_delay")
buildingRegion->ampeg.delay = value.getFloatValue();
else if (opcode == "ampeg_start")
buildingRegion->ampeg.start = value.getFloatValue();
else if (opcode == "ampeg_attack")
buildingRegion->ampeg.attack = value.getFloatValue();
else if (opcode == "ampeg_hold")
buildingRegion->ampeg.hold = value.getFloatValue();
else if (opcode == "ampeg_decay")
buildingRegion->ampeg.decay = value.getFloatValue();
else if (opcode == "ampeg_sustain")
buildingRegion->ampeg.sustain = value.getFloatValue();
else if (opcode == "ampeg_release")
buildingRegion->ampeg.release = value.getFloatValue();
else if (opcode == "ampeg_vel2delay")
buildingRegion->ampeg_veltrack.delay = value.getFloatValue();
else if (opcode == "ampeg_vel2attack")
buildingRegion->ampeg_veltrack.attack = value.getFloatValue();
else if (opcode == "ampeg_vel2hold")
buildingRegion->ampeg_veltrack.hold = value.getFloatValue();
else if (opcode == "ampeg_vel2decay")
buildingRegion->ampeg_veltrack.decay = value.getFloatValue();
else if (opcode == "ampeg_vel2sustain")
buildingRegion->ampeg_veltrack.sustain = value.getFloatValue();
else if (opcode == "ampeg_vel2release")
buildingRegion->ampeg_veltrack.release = value.getFloatValue();
else if (opcode == "default_path")
error("\"default_path\" outside of <control> tag");
else
sound->addUnsupportedOpcode(String(opcode.start, opcode.length()));
}
}
// Skip to next element.
nextElement:
c = 0;
while (p < end) {
c = *p;
if (c != ' ' && c != '\t')
break;
p += 1;
}
if (c == '\r' || c == '\n') {
p = handleLineEnd(p);
break;
}
}
}
fatalError:
if (buildingRegion && buildingRegion == &curRegion)
finishRegion(buildingRegion);
}
const char* SFZReader::handleLineEnd(const char* p)
{
// Check for DOS-style line ending.
char lineEndChar = *p++;
if (lineEndChar == '\r' && *p == '\n')
p += 1;
line += 1;
return p;
}
const char* SFZReader::readPathInto(
String* pathOut, const char* pIn, const char* endIn)
{
// Paths are kind of funny to parse because they can contain whitespace.
const char* p = pIn;
const char* end = endIn;
const char* pathStart = p;
const char* potentialEnd = NULL;
while (p < end) {
char c = *p;
if (c == ' ') {
// Is this space part of the path? Or the start of the next opcode? We
// don't know yet.
potentialEnd = p;
p += 1;
// Skip any more spaces.
while (p < end && *p == ' ')
p += 1;
}
else if (c == '\n' || c == '\r' || c == '\t')
break;
else if (c == '=') {
// We've been looking at an opcode; we need to rewind to
// potentialEnd.
p = potentialEnd;
break;
}
p += 1;
}
if (p > pathStart) {
// Can't do this:
// String path(CharPointer_UTF8(pathStart), CharPointer_UTF8(p));
// It won't compile for some unfathomable reason.
CharPointer_UTF8 end(p);
String path(CharPointer_UTF8(pathStart), end);
*pathOut = path;
}
else
*pathOut = String::empty;
return p;
}
int SFZReader::keyValue(const String& str)
{
char c = str[0];
if (c >= '0' && c <= '9')
return str.getIntValue();
int note = 0;
static const int notes[] = {
12 + 0, 12 + 2, 3, 5, 7, 8, 10,
};
if (c >= 'A' && c <= 'G')
note = notes[c - 'A'];
else if (c >= 'a' && c <= 'g')
note = notes[c - 'a'];
int octaveStart = 1;
c = str[1];
if (c == 'b' || c == '#') {
octaveStart += 1;
if (c == 'b')
note -= 1;
else
note += 1;
}
int octave = str.substring(octaveStart).getIntValue();
// A3 == 57.
int result = octave * 12 + note + (57 - 4 * 12);
return result;
}
int SFZReader::triggerValue(const String& str)
{
if (str == "release")
return SFZRegion::release;
else if (str == "first")
return SFZRegion::first;
else if (str == "legato")
return SFZRegion::legato;
return SFZRegion::attack;
}
int SFZReader::loopModeValue(const String& str)
{
if (str == "no_loop")
return SFZRegion::no_loop;
else if (str == "one_shot")
return SFZRegion::one_shot;
else if (str == "loop_continuous")
return SFZRegion::loop_continuous;
else if (str == "loop_sustain")
return SFZRegion::loop_sustain;
return SFZRegion::sample_loop;
}
void SFZReader::finishRegion(SFZRegion* region)
{
SFZRegion* newRegion = new SFZRegion();
*newRegion = *region;
sound->addRegion(newRegion);
}
void SFZReader::error(const String& message)
{
String fullMessage = message;
fullMessage += " (line " + String(line) + ").";
sound->addError(fullMessage);
}
| 0 | 0.915593 | 1 | 0.915593 | game-dev | MEDIA | 0.250264 | game-dev | 0.922738 | 1 | 0.922738 |
darklordabc/Legends-of-Dota-Redux | 1,188 | src/game/scripts/vscripts/abilities/marksmanship_str.lua | --[[
Author: kritth
Date: 1.1.2015.
Check number of units every interval
Note: Might be possible to do entirely in datadriven, however, I seem to crash everytime I tried
to do so, insteads, I just use simple script
]]
function marksmanship_detection( keys )
local caster = keys.caster
local ability = keys.ability
local radius = ability:GetLevelSpecialValueFor( "radius", ( ability:GetLevel() - 1 ) )
local modifierName = "modifier_marksmanship_str_effect_datadriven"
-- Count units in radius
local units = FindUnitsInRadius( caster:GetTeamNumber(), caster:GetAbsOrigin(), caster, radius,
DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO, 0, 0, false )
local count = 0
for k, v in pairs( units ) do
count = count + 1
end
-- If Passives are Disabled, set count to 1, which for this specific ability, will lead to it being disabled
if caster:PassivesDisabled() then
count = 1
end
-- Apply and destroy
if count == 0 and not caster:HasModifier( modifierName ) then
ability:ApplyDataDrivenModifier( caster, caster, modifierName, {} )
elseif count ~= 0 and caster:HasModifier( modifierName ) then
caster:RemoveModifierByName( modifierName )
end
end
| 0 | 0.770106 | 1 | 0.770106 | game-dev | MEDIA | 0.986532 | game-dev | 0.982975 | 1 | 0.982975 |
Oyyou/MonoGame_Tutorials | 5,411 | MonoGame_Tutorials/Tutorial030/Game1.cs | using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using System;
using System.Collections.Generic;
using Tutorial030.Emitters;
using Tutorial030.Misc;
using Tutorial030.Models;
using Tutorial030.Sprites;
using Tutorial030.States;
namespace Tutorial030
{
/// <summary>
/// This is the main type for your game.
/// </summary>
public class Game1 : Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
public static int ScreenWidth = 1280;
public static int ScreenHeight = 720;
public static Random Random;
private GameModel _gameModel;
private State _currentState;
private LevelModel _sunnyLevel;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
graphics.PreferredBackBufferWidth = ScreenWidth;
graphics.PreferredBackBufferHeight = ScreenHeight;
graphics.ApplyChanges();
Random = new Random();
IsMouseVisible = true;
base.Initialize();
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
_gameModel = new GameModel()
{
ContentManger = Content,
GraphicsDeviceManager = graphics,
SpriteBatch = spriteBatch,
};
_currentState = new LevelSelectorState(_gameModel);
_currentState.LoadContent();
var player = new Player(new Dictionary<string, Animation>()
{
{ "Running", new Animation(Content.Load<Texture2D>("Player/Running"), 4) },
{ "Jumping", new Animation(Content.Load<Texture2D>("Player/Jumping"), 4) },
{ "Falling", new Animation(Content.Load<Texture2D>("Player/Falling"), 4) },
})
{
BaseAttributes = new Attributes()
{
Speed = 3f,
},
Position = new Vector2(50, 300),
Layer = 1f,
};
_sunnyLevel = new LevelModel(player)
{
//Emitter = new SnowEmitter(new Particle(Content.Load<Texture2D>("Particles/Snow"))),
ScrollingBackgrounds = new List<ScrollingBackground>()
{
new ScrollingBackground(Content.Load<Texture2D>("Levels/Sunny/Trees"), player, 60f)
{
Layer = 0.99f,
},
new ScrollingBackground(Content.Load<Texture2D>("Levels/Sunny/Floor"), player, 60f)
{
Layer = 0.9f,
},
new ScrollingBackground(Content.Load<Texture2D>("Levels/Sunny/Hills_Front"), player, 40f)
{
Layer = 0.8f,
},
new ScrollingBackground(Content.Load<Texture2D>("Levels/Sunny/Hills_Middle"), player, 30f)
{
Layer = 0.79f,
},
new ScrollingBackground(Content.Load<Texture2D>("Levels/Sunny/Clouds_Fast"), player, 25f, true)
{
Layer = 0.78f,
},
new ScrollingBackground(Content.Load<Texture2D>("Levels/Sunny/Hills_Back"), player, 0f)
{
Layer = 0.77f,
},
new ScrollingBackground(Content.Load<Texture2D>("Levels/Sunny/Clouds_Slow"), player, 10f, true)
{
Layer = 0.7f,
},
new ScrollingBackground(Content.Load<Texture2D>("Levels/Sunny/Sky"), player, 0f)
{
Layer = 0.1f,
},
}
};
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// game-specific content.
/// </summary>
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
switch (_currentState)
{
case LevelSelectorState levelSelectorState:
_currentState = new PlayingState(_gameModel, _sunnyLevel);
_currentState.LoadContent();
break;
case CustomiseState customiseState:
break;
case PlayingState playingState:
break;
default:
throw new Exception("Unknown state: " + _currentState.ToString());
}
_currentState.Update(gameTime);
base.Update(gameTime);
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
_currentState.Draw(gameTime);
base.Draw(gameTime);
}
}
}
| 0 | 0.59481 | 1 | 0.59481 | game-dev | MEDIA | 0.814931 | game-dev | 0.914115 | 1 | 0.914115 |
TaiyitistMC/Taiyitist | 1,790 | modules/taiyitist-server/src/main/java/org/bukkit/craftbukkit/entity/CraftLlama.java | package org.bukkit.craftbukkit.entity;
import com.google.common.base.Preconditions;
import org.bukkit.craftbukkit.CraftServer;
import org.bukkit.craftbukkit.inventory.CraftInventoryLlama;
import org.bukkit.entity.Horse;
import org.bukkit.entity.Llama;
import org.bukkit.inventory.LlamaInventory;
public class CraftLlama extends CraftChestedHorse implements Llama {
public CraftLlama(CraftServer server, net.minecraft.world.entity.animal.horse.Llama entity) {
super(server, entity);
}
@Override
public net.minecraft.world.entity.animal.horse.Llama getHandle() {
return (net.minecraft.world.entity.animal.horse.Llama) super.getHandle();
}
@Override
public Color getColor() {
return Color.values()[this.getHandle().getVariant().ordinal()];
}
@Override
public void setColor(Color color) {
Preconditions.checkArgument(color != null, "color");
this.getHandle().setVariant(net.minecraft.world.entity.animal.horse.Llama.Variant.byId(color.ordinal()));
}
@Override
public LlamaInventory getInventory() {
return new CraftInventoryLlama(this.getHandle().inventory, this.getHandle().getBodyArmorAccess());
}
@Override
public int getStrength() {
return this.getHandle().getStrength();
}
@Override
public void setStrength(int strength) {
Preconditions.checkArgument(1 <= strength && strength <= 5, "strength must be [1,5]");
if (strength == this.getStrength()) return;
this.getHandle().setStrength(strength);
this.getHandle().createInventory();
}
@Override
public Horse.Variant getVariant() {
return Horse.Variant.LLAMA;
}
@Override
public String toString() {
return "CraftLlama";
}
}
| 0 | 0.77215 | 1 | 0.77215 | game-dev | MEDIA | 0.996943 | game-dev | 0.66167 | 1 | 0.66167 |
StranikS-Scan/WorldOfTanks-Decompiled | 2,846 | source/res/scripts/client/vehicle_systems/components/shot_damage_components.py | # Python bytecode 2.7 (decompiled from Python 2.7)
# Embedded file name: scripts/client/vehicle_systems/components/shot_damage_components.py
from cgf_script.component_meta_class import ComponentProperty, CGFMetaTypes, registerComponent
from cgf_script.managers_registrator import autoregister, onAddedQuery, onRemovedQuery
import CGF
import Math
import BigWorld
import GenericComponents
from items import vehicles
from vehicle_systems.tankStructure import TankPartNames
class ShotDamageComponent(object):
def __init__(self, partName, compound):
self.partName = partName
self.compound = compound
@registerComponent
class DamageStickerComponent(object):
category = 'Render'
domain = CGF.DomainOption.DomainClient
damageSticker = ComponentProperty(type=CGFMetaTypes.STRING, editorName='Damage sticker', value='')
lodDistance = ComponentProperty(type=CGFMetaTypes.FLOAT, editorName='Lod Distance', value=100)
fadeoutTime = ComponentProperty(type=CGFMetaTypes.FLOAT, editorName='Fadeout time', value=0)
offset = ComponentProperty(type=CGFMetaTypes.FLOAT, editorName='Offset', value=1.0)
def __init__(self):
super(DamageStickerComponent, self).__init__()
self.stickerModel = None
return
@autoregister(presentInAllWorlds=True)
class DamageStickerManager(CGF.ComponentManager):
@onAddedQuery(ShotDamageComponent, DamageStickerComponent, GenericComponents.TransformComponent)
def onAddedSticker(self, shotDamage, damageSticker, transform):
if shotDamage.partName == TankPartNames.CHASSIS:
return
damageSticker.stickerModel = BigWorld.StickerModel(self.spaceID)
geometryLink = shotDamage.compound.getPartGeometryLink(TankPartNames.getIdx(shotDamage.partName))
m = Math.Matrix()
m.setIdentity()
stickerModel = damageSticker.stickerModel
stickerModel.setupSuperModel(geometryLink, m)
node = shotDamage.compound.node(shotDamage.partName)
node.attach(damageSticker.stickerModel)
stickerModel.setLODDistance(damageSticker.lodDistance)
stickerId = vehicles.g_cache.damageStickers['ids'][damageSticker.damageSticker]
segStart = transform.transform.applyPoint(Math.Vector3(0, 0, -damageSticker.offset))
segEnd = transform.transform.applyPoint(Math.Vector3(0, 0, damageSticker.offset))
stickerModel.addDamageSticker(stickerId, segStart, segEnd, True)
stickerModel.setupFadeout(damageSticker.fadeoutTime)
@onRemovedQuery(ShotDamageComponent, DamageStickerComponent)
def onRemovedSticker(self, shotDamage, damageSticker):
if damageSticker.stickerModel is None:
return
else:
node = shotDamage.compound.node(shotDamage.partName)
node.detach(damageSticker.stickerModel)
return
| 0 | 0.893197 | 1 | 0.893197 | game-dev | MEDIA | 0.777989 | game-dev | 0.872631 | 1 | 0.872631 |
cliqz-oss/browser-f | 55,304 | mozilla-release/dom/gamepad/GamepadRemapping.cpp | /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
// Based on
// https://cs.chromium.org/chromium/src/device/gamepad/gamepad_standard_mappings.h
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "mozilla/dom/GamepadRemapping.h"
namespace mozilla {
namespace dom {
// Follow the canonical ordering recommendation for the "Standard Gamepad"
// from https://www.w3.org/TR/gamepad/#remapping.
enum CanonicalButtonIndex {
BUTTON_INDEX_PRIMARY,
BUTTON_INDEX_SECONDARY,
BUTTON_INDEX_TERTIARY,
BUTTON_INDEX_QUATERNARY,
BUTTON_INDEX_LEFT_SHOULDER,
BUTTON_INDEX_RIGHT_SHOULDER,
BUTTON_INDEX_LEFT_TRIGGER,
BUTTON_INDEX_RIGHT_TRIGGER,
BUTTON_INDEX_BACK_SELECT,
BUTTON_INDEX_START,
BUTTON_INDEX_LEFT_THUMBSTICK,
BUTTON_INDEX_RIGHT_THUMBSTICK,
BUTTON_INDEX_DPAD_UP,
BUTTON_INDEX_DPAD_DOWN,
BUTTON_INDEX_DPAD_LEFT,
BUTTON_INDEX_DPAD_RIGHT,
BUTTON_INDEX_META,
BUTTON_INDEX_COUNT
};
enum CanonicalAxisIndex {
AXIS_INDEX_LEFT_STICK_X,
AXIS_INDEX_LEFT_STICK_Y,
AXIS_INDEX_RIGHT_STICK_X,
AXIS_INDEX_RIGHT_STICK_Y,
AXIS_INDEX_COUNT
};
float NormalizeTouch(long aValue, long aMin, long aMax) {
return (2.f * (aValue - aMin) / static_cast<float>(aMax - aMin)) - 1.f;
}
bool AxisNegativeAsButton(float input) {
const float value = (input < -0.5f) ? 1.f : 0.f;
return value > 0.1f;
}
bool AxisPositiveAsButton(float input) {
const float value = (input > 0.5f) ? 1.f : 0.f;
return value > 0.1f;
}
void FetchDpadFromAxis(uint32_t aIndex, double dir) {
bool up = false;
bool right = false;
bool down = false;
bool left = false;
// Dpad is mapped as a direction on one axis, where -1 is up and it
// increases clockwise to 1, which is up + left. It's set to a large (> 1.f)
// number when nothing is depressed, except on start up, sometimes it's 0.0
// for no data, rather than the large number.
if (dir != 0.0f) {
up = (dir >= -1.f && dir < -0.7f) || (dir >= .95f && dir <= 1.f);
right = dir >= -.75f && dir < -.1f;
down = dir >= -.2f && dir < .45f;
left = dir >= .4f && dir <= 1.f;
}
RefPtr<GamepadPlatformService> service =
GamepadPlatformService::GetParentService();
if (!service) {
return;
}
service->NewButtonEvent(aIndex, BUTTON_INDEX_DPAD_UP, up);
service->NewButtonEvent(aIndex, BUTTON_INDEX_DPAD_RIGHT, right);
service->NewButtonEvent(aIndex, BUTTON_INDEX_DPAD_DOWN, down);
service->NewButtonEvent(aIndex, BUTTON_INDEX_DPAD_LEFT, left);
}
class DefaultRemapper final : public GamepadRemapper {
public:
virtual uint32_t GetAxisCount() const override { return numAxes; }
virtual uint32_t GetButtonCount() const override { return numButtons; }
virtual void SetAxisCount(uint32_t aAxisCount) override {
numAxes = aAxisCount;
}
virtual void SetButtonCount(uint32_t aButtonCount) override {
numButtons = aButtonCount;
}
virtual GamepadMappingType GetMappingType() const override {
return GamepadMappingType::_empty;
}
virtual void RemapAxisMoveEvent(uint32_t aIndex, uint32_t aAxis,
double aValue) const override {
if (GetAxisCount() <= aAxis) {
NS_WARNING(
nsPrintfCString("Axis idx '%d' doesn't support in DefaultRemapper().",
aAxis)
.get());
return;
}
RefPtr<GamepadPlatformService> service =
GamepadPlatformService::GetParentService();
if (!service) {
return;
}
service->NewAxisMoveEvent(aIndex, aAxis, aValue);
}
virtual void RemapButtonEvent(uint32_t aIndex, uint32_t aButton,
bool aPressed) const override {
if (GetButtonCount() <= aButton) {
NS_WARNING(
nsPrintfCString(
"Button idx '%d' doesn't support in DefaultRemapper().", aButton)
.get());
return;
}
RefPtr<GamepadPlatformService> service =
GamepadPlatformService::GetParentService();
if (!service) {
return;
}
service->NewButtonEvent(aIndex, aButton, aPressed);
}
private:
uint32_t numAxes;
uint32_t numButtons;
};
class ADT1Remapper final : public GamepadRemapper {
public:
virtual uint32_t GetAxisCount() const override { return AXIS_INDEX_COUNT; }
virtual uint32_t GetButtonCount() const override {
return BUTTON_INDEX_COUNT;
}
virtual void RemapAxisMoveEvent(uint32_t aIndex, uint32_t aAxis,
double aValue) const override {
RefPtr<GamepadPlatformService> service =
GamepadPlatformService::GetParentService();
if (!service) {
return;
}
switch (aAxis) {
case 0:
service->NewAxisMoveEvent(aIndex, AXIS_INDEX_LEFT_STICK_X, aValue);
break;
case 1:
service->NewAxisMoveEvent(aIndex, AXIS_INDEX_LEFT_STICK_Y, aValue);
break;
case 2:
service->NewAxisMoveEvent(aIndex, AXIS_INDEX_RIGHT_STICK_X, aValue);
break;
case 3:
service->NewButtonEvent(aIndex, BUTTON_INDEX_RIGHT_TRIGGER,
aValue > 0.1f);
break;
case 4:
service->NewButtonEvent(aIndex, BUTTON_INDEX_LEFT_TRIGGER,
aValue > 0.1f);
break;
case 5:
service->NewAxisMoveEvent(aIndex, AXIS_INDEX_RIGHT_STICK_Y, aValue);
break;
case 9:
FetchDpadFromAxis(aIndex, aValue);
break;
default:
NS_WARNING(
nsPrintfCString("Axis idx '%d' doesn't support in ADT1Remapper().",
aAxis)
.get());
break;
}
}
virtual void RemapButtonEvent(uint32_t aIndex, uint32_t aButton,
bool aPressed) const override {
RefPtr<GamepadPlatformService> service =
GamepadPlatformService::GetParentService();
if (!service) {
return;
}
if (GetButtonCount() <= aButton) {
NS_WARNING(
nsPrintfCString("Button idx '%d' doesn't support in ADT1Remapper().",
aButton)
.get());
return;
}
const std::map<uint32_t, uint32_t> buttonMapping = {
{3, BUTTON_INDEX_TERTIARY},
{4, BUTTON_INDEX_QUATERNARY},
{6, BUTTON_INDEX_LEFT_SHOULDER},
{7, BUTTON_INDEX_RIGHT_SHOULDER},
{12, BUTTON_INDEX_META},
{13, BUTTON_INDEX_LEFT_THUMBSTICK},
{14, BUTTON_INDEX_RIGHT_THUMBSTICK}};
auto find = buttonMapping.find(aButton);
if (find != buttonMapping.end()) {
service->NewButtonEvent(aIndex, find->second, aPressed);
} else {
service->NewButtonEvent(aIndex, aButton, aPressed);
}
}
};
class TwoAxesEightKeysRemapper final : public GamepadRemapper {
public:
virtual uint32_t GetAxisCount() const override { return 0; }
virtual uint32_t GetButtonCount() const override {
return BUTTON_INDEX_COUNT - 1;
}
virtual void RemapAxisMoveEvent(uint32_t aIndex, uint32_t aAxis,
double aValue) const override {
RefPtr<GamepadPlatformService> service =
GamepadPlatformService::GetParentService();
if (!service) {
return;
}
switch (aAxis) {
case 0:
service->NewButtonEvent(aIndex, BUTTON_INDEX_DPAD_LEFT,
AxisNegativeAsButton(aValue));
service->NewButtonEvent(aIndex, BUTTON_INDEX_DPAD_RIGHT,
AxisPositiveAsButton(aValue));
break;
case 1:
service->NewButtonEvent(aIndex, BUTTON_INDEX_DPAD_UP,
AxisNegativeAsButton(aValue));
service->NewButtonEvent(aIndex, BUTTON_INDEX_DPAD_DOWN,
AxisPositiveAsButton(aValue));
break;
default:
NS_WARNING(
nsPrintfCString(
"Axis idx '%d' doesn't support in TwoAxesEightKeysRemapper().",
aAxis)
.get());
break;
}
}
virtual void RemapButtonEvent(uint32_t aIndex, uint32_t aButton,
bool aPressed) const override {
RefPtr<GamepadPlatformService> service =
GamepadPlatformService::GetParentService();
if (!service) {
return;
}
if (GetButtonCount() <= aButton) {
NS_WARNING(
nsPrintfCString(
"Button idx '%d' doesn't support in TwoAxesEightKeysRemapper().",
aButton)
.get());
return;
}
const std::map<uint32_t, uint32_t> buttonMapping = {
{0, BUTTON_INDEX_QUATERNARY},
{2, BUTTON_INDEX_PRIMARY},
{3, BUTTON_INDEX_TERTIARY}};
auto find = buttonMapping.find(aButton);
if (find != buttonMapping.end()) {
service->NewButtonEvent(aIndex, find->second, aPressed);
} else {
service->NewButtonEvent(aIndex, aButton, aPressed);
}
}
};
class StadiaControllerRemapper final : public GamepadRemapper {
public:
virtual uint32_t GetAxisCount() const override { return AXIS_INDEX_COUNT; }
virtual uint32_t GetButtonCount() const override {
return STADIA_BUTTON_COUNT;
}
virtual void RemapAxisMoveEvent(uint32_t aIndex, uint32_t aAxis,
double aValue) const override {
RefPtr<GamepadPlatformService> service =
GamepadPlatformService::GetParentService();
if (!service) {
return;
}
switch (aAxis) {
case 0:
service->NewAxisMoveEvent(aIndex, AXIS_INDEX_LEFT_STICK_X, aValue);
break;
case 1:
service->NewAxisMoveEvent(aIndex, AXIS_INDEX_LEFT_STICK_Y, aValue);
break;
case 2:
service->NewAxisMoveEvent(aIndex, AXIS_INDEX_RIGHT_STICK_X, aValue);
break;
case 3:
service->NewAxisMoveEvent(aIndex, AXIS_INDEX_RIGHT_STICK_Y, aValue);
break;
case 4:
service->NewButtonEvent(aIndex, BUTTON_INDEX_LEFT_TRIGGER, aValue);
break;
case 5:
service->NewButtonEvent(aIndex, BUTTON_INDEX_RIGHT_TRIGGER, aValue);
break;
default:
NS_WARNING(
nsPrintfCString(
"Axis idx '%d' doesn't support in StadiaControllerRemapper().",
aAxis)
.get());
break;
}
}
virtual void RemapButtonEvent(uint32_t aIndex, uint32_t aButton,
bool aPressed) const override {
RefPtr<GamepadPlatformService> service =
GamepadPlatformService::GetParentService();
if (!service) {
return;
}
if (STADIA_BUTTON_COUNT <= aButton) {
NS_WARNING(
nsPrintfCString(
"Button idx '%d' doesn't support in StadiaControllerRemapper().",
aButton)
.get());
return;
}
service->NewButtonEvent(aIndex, aButton, aPressed);
}
private:
enum STADIAButtons {
STADIA_BUTTON_EXTRA1 = BUTTON_INDEX_COUNT,
STADIA_BUTTON_EXTRA2,
STADIA_BUTTON_COUNT
};
};
class Playstation3Remapper final : public GamepadRemapper {
public:
Playstation3Remapper() = default;
uint32_t GetAxisCount() const override { return AXIS_INDEX_COUNT; }
uint32_t GetButtonCount() const override { return BUTTON_INDEX_COUNT; }
void RemapAxisMoveEvent(uint32_t aIndex, uint32_t aAxis,
double aValue) const override {
RefPtr<GamepadPlatformService> service =
GamepadPlatformService::GetParentService();
if (!service) {
return;
}
switch (aAxis) {
case 0:
service->NewAxisMoveEvent(aIndex, AXIS_INDEX_LEFT_STICK_X, aValue);
break;
case 1:
service->NewAxisMoveEvent(aIndex, AXIS_INDEX_LEFT_STICK_Y, aValue);
break;
case 2:
service->NewAxisMoveEvent(aIndex, AXIS_INDEX_RIGHT_STICK_X, aValue);
break;
case 5:
service->NewAxisMoveEvent(aIndex, AXIS_INDEX_RIGHT_STICK_Y, aValue);
break;
default:
NS_WARNING(
nsPrintfCString(
"Axis idx '%d' doesn't support in Dualshock4Remapper().", aAxis)
.get());
break;
}
}
void RemapButtonEvent(uint32_t aIndex, uint32_t aButton,
bool aPressed) const override {
RefPtr<GamepadPlatformService> service =
GamepadPlatformService::GetParentService();
if (!service) {
return;
}
const std::vector<uint32_t> buttonMapping = {BUTTON_INDEX_BACK_SELECT,
BUTTON_INDEX_LEFT_THUMBSTICK,
BUTTON_INDEX_RIGHT_THUMBSTICK,
BUTTON_INDEX_START,
BUTTON_INDEX_DPAD_UP,
BUTTON_INDEX_DPAD_RIGHT,
BUTTON_INDEX_DPAD_DOWN,
BUTTON_INDEX_DPAD_LEFT,
BUTTON_INDEX_LEFT_TRIGGER,
BUTTON_INDEX_RIGHT_TRIGGER,
BUTTON_INDEX_LEFT_SHOULDER,
BUTTON_INDEX_RIGHT_SHOULDER,
BUTTON_INDEX_QUATERNARY,
BUTTON_INDEX_SECONDARY,
BUTTON_INDEX_PRIMARY,
BUTTON_INDEX_TERTIARY,
BUTTON_INDEX_META};
if (buttonMapping.size() <= aButton) {
NS_WARNING(
nsPrintfCString(
"Button idx '%d' doesn't support in Playstation3Remapper().",
aButton)
.get());
return;
}
service->NewButtonEvent(aIndex, buttonMapping[aButton], aPressed);
}
};
class Dualshock4Remapper final : public GamepadRemapper {
public:
Dualshock4Remapper() {
mLastTouches.SetLength(TOUCH_EVENT_COUNT);
mLastTouchId.SetLength(TOUCH_EVENT_COUNT);
}
virtual uint32_t GetAxisCount() const override { return AXIS_INDEX_COUNT; }
virtual uint32_t GetButtonCount() const override {
return DUALSHOCK_BUTTON_COUNT;
}
virtual uint32_t GetLightIndicatorCount() const override {
return LIGHT_INDICATOR_COUNT;
}
virtual void GetLightIndicators(
nsTArray<GamepadLightIndicatorType>& aTypes) const override {
const uint32_t len = GetLightIndicatorCount();
aTypes.SetLength(len);
for (uint32_t i = 0; i < len; ++i) {
aTypes[i] = GamepadLightIndicatorType::Rgb;
}
}
virtual uint32_t GetTouchEventCount() const override {
return TOUCH_EVENT_COUNT;
}
virtual void GetLightColorReport(
uint8_t aRed, uint8_t aGreen, uint8_t aBlue,
std::vector<uint8_t>& aReport) const override {
const size_t report_length = 32;
aReport.resize(report_length);
aReport.assign(report_length, 0);
aReport[0] = 0x05; // report ID USB only
aReport[1] = 0x02; // LED only
aReport[6] = aRed;
aReport[7] = aGreen;
aReport[8] = aBlue;
}
virtual uint32_t GetMaxInputReportLength() const override {
return MAX_INPUT_LEN;
}
virtual void ProcessTouchData(uint32_t aIndex, void* aInput) override {
nsTArray<GamepadTouchState> touches(TOUCH_EVENT_COUNT);
touches.SetLength(TOUCH_EVENT_COUNT);
uint8_t* rawData = (uint8_t*)aInput;
const uint32_t kTouchDimensionX = 1920;
const uint32_t kTouchDimensionY = 942;
bool touch0Pressed = (((rawData[35] & 0xff) >> 7) == 0);
bool touch1Pressed = (((rawData[39] & 0xff) >> 7) == 0);
if ((touch0Pressed && (rawData[35] & 0xff) < mLastTouchId[0]) ||
(touch1Pressed && (rawData[39] & 0xff) < mLastTouchId[1])) {
mTouchIdBase += 128;
}
if (touch0Pressed) {
touches[0].touchId = mTouchIdBase + (rawData[35] & 0x7f);
touches[0].surfaceId = 0;
touches[0].position[0] = NormalizeTouch(
((rawData[37] & 0xf) << 8) | rawData[36], 0, (kTouchDimensionX - 1));
touches[0].position[1] =
NormalizeTouch(rawData[38] << 4 | ((rawData[37] & 0xf0) >> 4), 0,
(kTouchDimensionY - 1));
touches[0].surfaceDimensions[0] = kTouchDimensionX;
touches[0].surfaceDimensions[1] = kTouchDimensionY;
touches[0].isSurfaceDimensionsValid = true;
mLastTouchId[0] = rawData[35] & 0x7f;
}
if (touch1Pressed) {
touches[1].touchId = mTouchIdBase + (rawData[39] & 0x7f);
touches[1].surfaceId = 0;
touches[1].position[0] =
NormalizeTouch((((rawData[41] & 0xf) << 8) | rawData[40]) + 1, 0,
(kTouchDimensionX - 1));
touches[1].position[1] =
NormalizeTouch(rawData[42] << 4 | ((rawData[41] & 0xf0) >> 4), 0,
(kTouchDimensionY - 1));
touches[1].surfaceDimensions[0] = kTouchDimensionX;
touches[1].surfaceDimensions[1] = kTouchDimensionY;
touches[1].isSurfaceDimensionsValid = true;
mLastTouchId[1] = rawData[39] & 0x7f;
}
RefPtr<GamepadPlatformService> service =
GamepadPlatformService::GetParentService();
if (!service) {
return;
}
// Avoid to send duplicate untouched events to the gamepad service.
if ((mLastTouches[0] != touch0Pressed) || touch0Pressed) {
service->NewMultiTouchEvent(aIndex, 0, touches[0]);
}
if ((mLastTouches[1] != touch1Pressed) || touch1Pressed) {
service->NewMultiTouchEvent(aIndex, 1, touches[1]);
}
mLastTouches[0] = touch0Pressed;
mLastTouches[1] = touch1Pressed;
}
virtual void RemapAxisMoveEvent(uint32_t aIndex, uint32_t aAxis,
double aValue) const override {
RefPtr<GamepadPlatformService> service =
GamepadPlatformService::GetParentService();
if (!service) {
return;
}
switch (aAxis) {
case 0:
service->NewAxisMoveEvent(aIndex, AXIS_INDEX_LEFT_STICK_X, aValue);
break;
case 1:
service->NewAxisMoveEvent(aIndex, AXIS_INDEX_LEFT_STICK_Y, aValue);
break;
case 2:
service->NewAxisMoveEvent(aIndex, AXIS_INDEX_RIGHT_STICK_X, aValue);
break;
case 3:
service->NewButtonEvent(aIndex, BUTTON_INDEX_LEFT_TRIGGER,
aValue > 0.1f);
break;
case 4:
service->NewButtonEvent(aIndex, BUTTON_INDEX_RIGHT_TRIGGER,
aValue > 0.1f);
break;
case 5:
service->NewAxisMoveEvent(aIndex, AXIS_INDEX_RIGHT_STICK_Y, aValue);
break;
case 9:
FetchDpadFromAxis(aIndex, aValue);
break;
default:
NS_WARNING(
nsPrintfCString(
"Axis idx '%d' doesn't support in Dualshock4Remapper().", aAxis)
.get());
break;
}
}
virtual void RemapButtonEvent(uint32_t aIndex, uint32_t aButton,
bool aPressed) const override {
RefPtr<GamepadPlatformService> service =
GamepadPlatformService::GetParentService();
if (!service) {
return;
}
const std::vector<uint32_t> buttonMapping = {BUTTON_INDEX_TERTIARY,
BUTTON_INDEX_PRIMARY,
BUTTON_INDEX_SECONDARY,
BUTTON_INDEX_QUATERNARY,
BUTTON_INDEX_LEFT_SHOULDER,
BUTTON_INDEX_RIGHT_SHOULDER,
BUTTON_INDEX_LEFT_TRIGGER,
BUTTON_INDEX_RIGHT_TRIGGER,
BUTTON_INDEX_BACK_SELECT,
BUTTON_INDEX_START,
BUTTON_INDEX_LEFT_THUMBSTICK,
BUTTON_INDEX_RIGHT_THUMBSTICK,
BUTTON_INDEX_META,
DUALSHOCK_BUTTON_TOUCHPAD};
if (buttonMapping.size() <= aButton) {
NS_WARNING(nsPrintfCString(
"Button idx '%d' doesn't support in Dualshock4Remapper().",
aButton)
.get());
return;
}
service->NewButtonEvent(aIndex, buttonMapping[aButton], aPressed);
}
private:
enum Dualshock4Buttons {
DUALSHOCK_BUTTON_TOUCHPAD = BUTTON_INDEX_COUNT,
DUALSHOCK_BUTTON_COUNT
};
static const uint32_t LIGHT_INDICATOR_COUNT = 1;
static const uint32_t TOUCH_EVENT_COUNT = 2;
static const uint32_t MAX_INPUT_LEN = 68;
nsTArray<unsigned long> mLastTouchId;
nsTArray<bool> mLastTouches;
unsigned long mTouchIdBase = 0;
};
class LogitechDInputRemapper final : public GamepadRemapper {
public:
virtual uint32_t GetAxisCount() const override { return AXIS_INDEX_COUNT; }
virtual uint32_t GetButtonCount() const override {
// The Logitech button (BUTTON_INDEX_META) is not accessible through the
// device's D-mode.
return BUTTON_INDEX_COUNT - 1;
}
virtual void RemapAxisMoveEvent(uint32_t aIndex, uint32_t aAxis,
double aValue) const override {
RefPtr<GamepadPlatformService> service =
GamepadPlatformService::GetParentService();
if (!service) {
return;
}
switch (aAxis) {
case 0:
service->NewAxisMoveEvent(aIndex, AXIS_INDEX_LEFT_STICK_X, aValue);
break;
case 1:
service->NewAxisMoveEvent(aIndex, AXIS_INDEX_LEFT_STICK_Y, aValue);
break;
case 2:
service->NewAxisMoveEvent(aIndex, AXIS_INDEX_RIGHT_STICK_X, aValue);
break;
case 5:
service->NewAxisMoveEvent(aIndex, AXIS_INDEX_RIGHT_STICK_Y, aValue);
break;
case 9:
FetchDpadFromAxis(aIndex, aValue);
break;
default:
NS_WARNING(
nsPrintfCString(
"Axis idx '%d' doesn't support in LogitechDInputRemapper().",
aAxis)
.get());
break;
}
}
virtual void RemapButtonEvent(uint32_t aIndex, uint32_t aButton,
bool aPressed) const override {
RefPtr<GamepadPlatformService> service =
GamepadPlatformService::GetParentService();
if (!service) {
return;
}
if (GetButtonCount() <= aButton) {
NS_WARNING(
nsPrintfCString(
"Button idx '%d' doesn't support in LogitechDInputRemapper().",
aButton)
.get());
return;
}
const std::map<uint32_t, uint32_t> buttonMapping = {
{0, BUTTON_INDEX_TERTIARY},
{1, BUTTON_INDEX_PRIMARY},
{2, BUTTON_INDEX_SECONDARY}};
auto find = buttonMapping.find(aButton);
if (find != buttonMapping.end()) {
service->NewButtonEvent(aIndex, find->second, aPressed);
} else {
service->NewButtonEvent(aIndex, aButton, aPressed);
}
}
};
class SwitchJoyConRemapper final : public GamepadRemapper {
public:
virtual uint32_t GetAxisCount() const override { return 2; }
virtual uint32_t GetButtonCount() const override {
return BUTTON_INDEX_COUNT;
}
virtual void RemapAxisMoveEvent(uint32_t aIndex, uint32_t aAxis,
double aValue) const override {
if (GetAxisCount() <= aAxis) {
NS_WARNING(
nsPrintfCString(
"Axis idx '%d' doesn't support in SwitchJoyConRemapper().", aAxis)
.get());
return;
}
RefPtr<GamepadPlatformService> service =
GamepadPlatformService::GetParentService();
if (!service) {
return;
}
service->NewAxisMoveEvent(aIndex, AXIS_INDEX_LEFT_STICK_X, aValue);
}
virtual void RemapButtonEvent(uint32_t aIndex, uint32_t aButton,
bool aPressed) const override {
RefPtr<GamepadPlatformService> service =
GamepadPlatformService::GetParentService();
if (!service) {
return;
}
service->NewButtonEvent(aIndex, aButton, aPressed);
}
};
class SwitchProRemapper final : public GamepadRemapper {
public:
virtual uint32_t GetAxisCount() const override { return AXIS_INDEX_COUNT; }
virtual uint32_t GetButtonCount() const override {
// The Switch Pro controller has a Capture button that has no equivalent in
// the Standard Gamepad.
return SWITCHPRO_BUTTON_COUNT;
}
virtual void RemapAxisMoveEvent(uint32_t aIndex, uint32_t aAxis,
double aValue) const override {
if (GetAxisCount() <= aAxis) {
NS_WARNING(
nsPrintfCString(
"Axis idx '%d' doesn't support in SwitchProRemapper().", aAxis)
.get());
return;
}
RefPtr<GamepadPlatformService> service =
GamepadPlatformService::GetParentService();
if (!service) {
return;
}
service->NewAxisMoveEvent(aIndex, AXIS_INDEX_LEFT_STICK_X, aValue);
}
virtual void RemapButtonEvent(uint32_t aIndex, uint32_t aButton,
bool aPressed) const override {
RefPtr<GamepadPlatformService> service =
GamepadPlatformService::GetParentService();
if (!service) {
return;
}
service->NewButtonEvent(aIndex, aButton, aPressed);
}
private:
enum SwitchProButtons {
SWITCHPRO_BUTTON_EXTRA = BUTTON_INDEX_COUNT,
SWITCHPRO_BUTTON_COUNT
};
};
class NvShieldRemapper final : public GamepadRemapper {
public:
virtual uint32_t GetAxisCount() const override { return AXIS_INDEX_COUNT; }
virtual uint32_t GetButtonCount() const override {
return SHIELD_BUTTON_COUNT;
}
virtual void RemapAxisMoveEvent(uint32_t aIndex, uint32_t aAxis,
double aValue) const override {
RefPtr<GamepadPlatformService> service =
GamepadPlatformService::GetParentService();
if (!service) {
return;
}
switch (aAxis) {
case 0:
service->NewAxisMoveEvent(aIndex, AXIS_INDEX_LEFT_STICK_X, aValue);
break;
case 1:
service->NewAxisMoveEvent(aIndex, AXIS_INDEX_LEFT_STICK_Y, aValue);
break;
case 2:
service->NewAxisMoveEvent(aIndex, AXIS_INDEX_RIGHT_STICK_X, aValue);
break;
case 3:
service->NewButtonEvent(aIndex, BUTTON_INDEX_RIGHT_TRIGGER,
aValue > 0.1f);
break;
case 4:
service->NewButtonEvent(aIndex, BUTTON_INDEX_LEFT_TRIGGER,
aValue > 0.1f);
break;
case 5:
service->NewAxisMoveEvent(aIndex, AXIS_INDEX_RIGHT_STICK_Y, aValue);
break;
case 9:
FetchDpadFromAxis(aIndex, aValue);
break;
default:
NS_WARNING(
nsPrintfCString(
"Axis idx '%d' doesn't support in NvShieldRemapper().", aAxis)
.get());
break;
}
}
virtual void RemapButtonEvent(uint32_t aIndex, uint32_t aButton,
bool aPressed) const override {
RefPtr<GamepadPlatformService> service =
GamepadPlatformService::GetParentService();
if (!service) {
return;
}
if (GetButtonCount() <= aButton) {
NS_WARNING(
nsPrintfCString(
"Button idx '%d' doesn't support in NvShieldRemapper().", aButton)
.get());
return;
}
const std::map<uint32_t, uint32_t> buttonMapping = {
{2, BUTTON_INDEX_META},
{3, BUTTON_INDEX_TERTIARY},
{4, BUTTON_INDEX_QUATERNARY},
{5, SHIELD_BUTTON_CIRCLE},
{6, BUTTON_INDEX_LEFT_SHOULDER},
{7, BUTTON_INDEX_RIGHT_SHOULDER},
{9, BUTTON_INDEX_BACK_SELECT},
{11, BUTTON_INDEX_START},
{13, BUTTON_INDEX_LEFT_THUMBSTICK},
{14, BUTTON_INDEX_RIGHT_THUMBSTICK}};
auto find = buttonMapping.find(aButton);
if (find != buttonMapping.end()) {
service->NewButtonEvent(aIndex, find->second, aPressed);
} else {
service->NewButtonEvent(aIndex, aButton, aPressed);
}
}
private:
enum ShieldButtons {
SHIELD_BUTTON_CIRCLE = BUTTON_INDEX_COUNT,
SHIELD_BUTTON_COUNT
};
};
class NvShield2017Remapper final : public GamepadRemapper {
public:
virtual uint32_t GetAxisCount() const override { return AXIS_INDEX_COUNT; }
virtual uint32_t GetButtonCount() const override {
return SHIELD2017_BUTTON_COUNT;
}
virtual void RemapAxisMoveEvent(uint32_t aIndex, uint32_t aAxis,
double aValue) const override {
RefPtr<GamepadPlatformService> service =
GamepadPlatformService::GetParentService();
if (!service) {
return;
}
switch (aAxis) {
case 0:
service->NewAxisMoveEvent(aIndex, AXIS_INDEX_LEFT_STICK_X, aValue);
break;
case 1:
service->NewAxisMoveEvent(aIndex, AXIS_INDEX_LEFT_STICK_Y, aValue);
break;
case 2:
service->NewAxisMoveEvent(aIndex, AXIS_INDEX_RIGHT_STICK_X, aValue);
break;
case 3:
service->NewButtonEvent(aIndex, BUTTON_INDEX_RIGHT_TRIGGER,
aValue > 0.1f);
break;
case 4:
service->NewButtonEvent(aIndex, BUTTON_INDEX_LEFT_TRIGGER,
aValue > 0.1f);
break;
case 5:
service->NewAxisMoveEvent(aIndex, AXIS_INDEX_RIGHT_STICK_Y, aValue);
break;
case 9:
FetchDpadFromAxis(aIndex, aValue);
break;
default:
NS_WARNING(
nsPrintfCString(
"Axis idx '%d' doesn't support in NvShield2017Remapper().",
aAxis)
.get());
break;
}
}
virtual void RemapButtonEvent(uint32_t aIndex, uint32_t aButton,
bool aPressed) const override {
RefPtr<GamepadPlatformService> service =
GamepadPlatformService::GetParentService();
if (!service) {
return;
}
if (GetButtonCount() <= aButton) {
NS_WARNING(
nsPrintfCString(
"Button idx '%d' doesn't support in NvShield2017Remapper().",
aButton)
.get());
return;
}
const std::map<uint32_t, uint32_t> buttonMapping = {
{2, BUTTON_INDEX_META},
{3, BUTTON_INDEX_TERTIARY},
{4, BUTTON_INDEX_QUATERNARY},
{5, BUTTON_INDEX_START},
{6, BUTTON_INDEX_LEFT_SHOULDER},
{7, BUTTON_INDEX_RIGHT_SHOULDER},
{8, BUTTON_INDEX_BACK_SELECT},
{11, SHIELD2017_BUTTON_PLAYPAUSE},
{13, BUTTON_INDEX_LEFT_THUMBSTICK},
{14, BUTTON_INDEX_RIGHT_THUMBSTICK}};
auto find = buttonMapping.find(aButton);
if (find != buttonMapping.end()) {
service->NewButtonEvent(aIndex, find->second, aPressed);
} else {
service->NewButtonEvent(aIndex, aButton, aPressed);
}
}
private:
enum Shield2017Buttons {
SHIELD2017_BUTTON_PLAYPAUSE = BUTTON_INDEX_COUNT,
SHIELD2017_BUTTON_COUNT
};
};
class IBuffaloRemapper final : public GamepadRemapper {
public:
virtual uint32_t GetAxisCount() const override { return 2; }
virtual uint32_t GetButtonCount() const override {
return BUTTON_INDEX_COUNT - 1; /* no meta */
}
virtual void RemapAxisMoveEvent(uint32_t aIndex, uint32_t aAxis,
double aValue) const override {
RefPtr<GamepadPlatformService> service =
GamepadPlatformService::GetParentService();
if (!service) {
return;
}
switch (aAxis) {
case 0:
service->NewAxisMoveEvent(aIndex, AXIS_INDEX_LEFT_STICK_X, aValue);
service->NewButtonEvent(aIndex, BUTTON_INDEX_DPAD_LEFT,
AxisNegativeAsButton(aValue));
service->NewButtonEvent(aIndex, BUTTON_INDEX_DPAD_RIGHT,
AxisPositiveAsButton(aValue));
break;
case 1:
service->NewAxisMoveEvent(aIndex, AXIS_INDEX_LEFT_STICK_Y, aValue);
service->NewButtonEvent(aIndex, BUTTON_INDEX_DPAD_UP,
AxisNegativeAsButton(aValue));
service->NewButtonEvent(aIndex, BUTTON_INDEX_DPAD_DOWN,
AxisPositiveAsButton(aValue));
break;
default:
NS_WARNING(
nsPrintfCString(
"Axis idx '%d' doesn't support in IBuffaloRemapper().", aAxis)
.get());
break;
}
}
virtual void RemapButtonEvent(uint32_t aIndex, uint32_t aButton,
bool aPressed) const override {
RefPtr<GamepadPlatformService> service =
GamepadPlatformService::GetParentService();
if (!service) {
return;
}
if (GetButtonCount() <= aButton) {
NS_WARNING(
nsPrintfCString(
"Button idx '%d' doesn't support in IBuffaloRemapper().", aButton)
.get());
return;
}
const std::map<uint32_t, uint32_t> buttonMapping = {
{0, BUTTON_INDEX_SECONDARY}, {1, BUTTON_INDEX_PRIMARY},
{2, BUTTON_INDEX_QUATERNARY}, {3, BUTTON_INDEX_TERTIARY},
{5, BUTTON_INDEX_RIGHT_TRIGGER}, {6, BUTTON_INDEX_BACK_SELECT},
{7, BUTTON_INDEX_START}};
auto find = buttonMapping.find(aButton);
if (find != buttonMapping.end()) {
service->NewButtonEvent(aIndex, find->second, aPressed);
} else {
service->NewButtonEvent(aIndex, aButton, aPressed);
}
}
};
class XSkillsRemapper final : public GamepadRemapper {
public:
virtual uint32_t GetAxisCount() const override { return AXIS_INDEX_COUNT; }
virtual uint32_t GetButtonCount() const override {
return GAMECUBE_BUTTON_COUNT;
}
virtual void RemapAxisMoveEvent(uint32_t aIndex, uint32_t aAxis,
double aValue) const override {
RefPtr<GamepadPlatformService> service =
GamepadPlatformService::GetParentService();
if (!service) {
return;
}
switch (aAxis) {
case 0:
service->NewAxisMoveEvent(aIndex, AXIS_INDEX_LEFT_STICK_X, aValue);
break;
case 1:
service->NewAxisMoveEvent(aIndex, AXIS_INDEX_LEFT_STICK_Y, aValue);
break;
case 2:
service->NewAxisMoveEvent(aIndex, AXIS_INDEX_RIGHT_STICK_Y, aValue);
break;
case 3:
service->NewButtonEvent(aIndex, BUTTON_INDEX_RIGHT_TRIGGER,
aValue > 0.1f);
break;
case 4:
service->NewButtonEvent(aIndex, BUTTON_INDEX_LEFT_TRIGGER,
aValue > 0.1f);
break;
case 5:
service->NewAxisMoveEvent(aIndex, AXIS_INDEX_RIGHT_STICK_X, aValue);
break;
default:
NS_WARNING(
nsPrintfCString(
"Axis idx '%d' doesn't support in XSkillsRemapper().", aAxis)
.get());
break;
}
}
virtual void RemapButtonEvent(uint32_t aIndex, uint32_t aButton,
bool aPressed) const override {
RefPtr<GamepadPlatformService> service =
GamepadPlatformService::GetParentService();
if (!service) {
return;
}
if (GetButtonCount() <= aIndex) {
NS_WARNING(
nsPrintfCString(
"Button idx '%d' doesn't support in XSkillsRemapper().", aButton)
.get());
return;
}
const std::map<uint32_t, uint32_t> buttonMapping = {
{0, BUTTON_INDEX_PRIMARY}, // A
{1, BUTTON_INDEX_TERTIARY}, // B
{2, BUTTON_INDEX_SECONDARY}, // X
{3, BUTTON_INDEX_QUATERNARY}, // Y
{4, GAMECUBE_BUTTON_LEFT_TRIGGER_CLICK},
{5, GAMECUBE_BUTTON_RIGHT_TRIGGER_CLICK},
{6, BUTTON_INDEX_RIGHT_SHOULDER},
{7, BUTTON_INDEX_START},
{8, BUTTON_INDEX_DPAD_LEFT},
{9, BUTTON_INDEX_DPAD_RIGHT},
{10, BUTTON_INDEX_DPAD_DOWN},
{11, BUTTON_INDEX_DPAD_UP}};
auto find = buttonMapping.find(aButton);
if (find != buttonMapping.end()) {
service->NewButtonEvent(aIndex, find->second, aPressed);
} else {
service->NewButtonEvent(aIndex, aButton, aPressed);
}
}
private:
enum GamecubeButtons {
GAMECUBE_BUTTON_LEFT_TRIGGER_CLICK = BUTTON_INDEX_COUNT,
GAMECUBE_BUTTON_RIGHT_TRIGGER_CLICK,
GAMECUBE_BUTTON_COUNT
};
};
class BoomN64PsxRemapper final : public GamepadRemapper {
public:
virtual uint32_t GetAxisCount() const override { return AXIS_INDEX_COUNT; }
virtual uint32_t GetButtonCount() const override {
return BUTTON_INDEX_COUNT - 1; // no meta
}
virtual void RemapAxisMoveEvent(uint32_t aIndex, uint32_t aAxis,
double aValue) const override {
RefPtr<GamepadPlatformService> service =
GamepadPlatformService::GetParentService();
if (!service) {
return;
}
switch (aAxis) {
case 0:
service->NewAxisMoveEvent(aIndex, AXIS_INDEX_LEFT_STICK_X, aValue);
break;
case 1:
service->NewAxisMoveEvent(aIndex, AXIS_INDEX_LEFT_STICK_Y, aValue);
break;
case 2:
service->NewAxisMoveEvent(aIndex, AXIS_INDEX_RIGHT_STICK_X, aValue);
break;
case 5:
service->NewAxisMoveEvent(aIndex, AXIS_INDEX_RIGHT_STICK_Y, aValue);
break;
default:
NS_WARNING(
nsPrintfCString(
"Axis idx '%d' doesn't support in BoomN64PsxRemapper().", aAxis)
.get());
break;
}
}
virtual void RemapButtonEvent(uint32_t aIndex, uint32_t aButton,
bool aPressed) const override {
RefPtr<GamepadPlatformService> service =
GamepadPlatformService::GetParentService();
if (!service) {
return;
}
const std::vector<uint32_t> buttonMapping = {
BUTTON_INDEX_QUATERNARY, BUTTON_INDEX_SECONDARY,
BUTTON_INDEX_PRIMARY, BUTTON_INDEX_TERTIARY,
BUTTON_INDEX_LEFT_TRIGGER, BUTTON_INDEX_RIGHT_TRIGGER,
BUTTON_INDEX_LEFT_SHOULDER, BUTTON_INDEX_RIGHT_SHOULDER,
BUTTON_INDEX_BACK_SELECT, BUTTON_INDEX_LEFT_THUMBSTICK,
BUTTON_INDEX_RIGHT_THUMBSTICK, BUTTON_INDEX_START,
BUTTON_INDEX_DPAD_UP, BUTTON_INDEX_DPAD_RIGHT,
BUTTON_INDEX_DPAD_DOWN, BUTTON_INDEX_DPAD_LEFT};
if (buttonMapping.size() <= aButton) {
NS_WARNING(nsPrintfCString(
"Button idx '%d' doesn't support in BoomN64PsxRemapper().",
aButton)
.get());
return;
}
service->NewButtonEvent(aIndex, buttonMapping[aButton], aPressed);
}
private:
enum GamecubeButtons {
GAMECUBE_BUTTON_LEFT_TRIGGER_CLICK = BUTTON_INDEX_COUNT,
GAMECUBE_BUTTON_RIGHT_TRIGGER_CLICK,
GAMECUBE_BUTTON_COUNT
};
};
class AnalogGamepadRemapper final : public GamepadRemapper {
public:
virtual uint32_t GetAxisCount() const override { return AXIS_INDEX_COUNT; }
virtual uint32_t GetButtonCount() const override {
return ANALOG_GAMEPAD_BUTTON_COUNT;
}
virtual void RemapAxisMoveEvent(uint32_t aIndex, uint32_t aAxis,
double aValue) const override {
RefPtr<GamepadPlatformService> service =
GamepadPlatformService::GetParentService();
if (!service) {
return;
}
switch (aAxis) {
case 0:
service->NewAxisMoveEvent(aIndex, AXIS_INDEX_LEFT_STICK_X, aValue);
break;
case 1:
service->NewAxisMoveEvent(aIndex, AXIS_INDEX_LEFT_STICK_Y, aValue);
break;
case 2:
service->NewAxisMoveEvent(aIndex, AXIS_INDEX_RIGHT_STICK_X, aValue);
break;
case 3:
service->NewButtonEvent(aIndex, BUTTON_INDEX_RIGHT_TRIGGER,
aValue > 0.1f);
break;
case 4:
service->NewButtonEvent(aIndex, BUTTON_INDEX_LEFT_TRIGGER,
aValue > 0.1f);
break;
case 5:
service->NewAxisMoveEvent(aIndex, AXIS_INDEX_RIGHT_STICK_Y, aValue);
break;
case 9:
FetchDpadFromAxis(aIndex, aValue);
break;
default:
NS_WARNING(
nsPrintfCString(
"Axis idx '%d' doesn't support in AnalogGamepadRemapper().",
aAxis)
.get());
break;
}
}
virtual void RemapButtonEvent(uint32_t aIndex, uint32_t aButton,
bool aPressed) const override {
RefPtr<GamepadPlatformService> service =
GamepadPlatformService::GetParentService();
if (!service) {
return;
}
if (GetButtonCount() <= aButton) {
NS_WARNING(
nsPrintfCString(
"Button idx '%d' doesn't support in AnalogGamepadRemapper().",
aButton)
.get());
return;
}
const std::map<uint32_t, uint32_t> buttonMapping = {
{3, BUTTON_INDEX_TERTIARY},
{4, BUTTON_INDEX_QUATERNARY},
{6, BUTTON_INDEX_LEFT_SHOULDER},
{7, BUTTON_INDEX_RIGHT_SHOULDER},
{10, BUTTON_INDEX_BACK_SELECT},
{11, BUTTON_INDEX_META},
{12, BUTTON_INDEX_START},
{13, BUTTON_INDEX_LEFT_THUMBSTICK},
{14, BUTTON_INDEX_RIGHT_THUMBSTICK},
{16, ANALOG_GAMEPAD_BUTTON_EXTRA},
{17, ANALOG_GAMEPAD_BUTTON_EXTRA2}};
auto find = buttonMapping.find(aButton);
if (find != buttonMapping.end()) {
service->NewButtonEvent(aIndex, find->second, aPressed);
} else {
service->NewButtonEvent(aIndex, aButton, aPressed);
}
}
private:
enum AnalogGamepadButtons {
ANALOG_GAMEPAD_BUTTON_EXTRA = BUTTON_INDEX_COUNT,
ANALOG_GAMEPAD_BUTTON_EXTRA2,
ANALOG_GAMEPAD_BUTTON_COUNT
};
};
class RazerServalRemapper final : public GamepadRemapper {
public:
virtual uint32_t GetAxisCount() const override { return AXIS_INDEX_COUNT; }
virtual uint32_t GetButtonCount() const override {
return BUTTON_INDEX_COUNT - 1; /* no meta */
}
virtual void RemapAxisMoveEvent(uint32_t aIndex, uint32_t aAxis,
double aValue) const override {
RefPtr<GamepadPlatformService> service =
GamepadPlatformService::GetParentService();
if (!service) {
return;
}
switch (aAxis) {
case 0:
service->NewAxisMoveEvent(aIndex, AXIS_INDEX_LEFT_STICK_X, aValue);
break;
case 1:
service->NewAxisMoveEvent(aIndex, AXIS_INDEX_LEFT_STICK_Y, aValue);
break;
case 2:
service->NewAxisMoveEvent(aIndex, AXIS_INDEX_RIGHT_STICK_X, aValue);
break;
case 3:
service->NewButtonEvent(aIndex, BUTTON_INDEX_RIGHT_TRIGGER,
aValue > 0.1f);
break;
case 4:
service->NewButtonEvent(aIndex, BUTTON_INDEX_LEFT_TRIGGER,
aValue > 0.1f);
break;
case 5:
service->NewAxisMoveEvent(aIndex, AXIS_INDEX_RIGHT_STICK_Y, aValue);
break;
case 9:
FetchDpadFromAxis(aIndex, aValue);
break;
default:
NS_WARNING(
nsPrintfCString(
"Axis idx '%d' doesn't support in RazerServalRemapper().",
aAxis)
.get());
break;
}
}
virtual void RemapButtonEvent(uint32_t aIndex, uint32_t aButton,
bool aPressed) const override {
RefPtr<GamepadPlatformService> service =
GamepadPlatformService::GetParentService();
if (!service) {
return;
}
if (GetButtonCount() <= aButton) {
NS_WARNING(
nsPrintfCString(
"Button idx '%d' doesn't support in RazerServalRemapper().",
aButton)
.get());
return;
}
const std::map<uint32_t, uint32_t> buttonMapping = {
{3, BUTTON_INDEX_TERTIARY}, {4, BUTTON_INDEX_QUATERNARY},
{6, BUTTON_INDEX_LEFT_SHOULDER}, {7, BUTTON_INDEX_RIGHT_SHOULDER},
{10, BUTTON_INDEX_BACK_SELECT}, {11, BUTTON_INDEX_START},
{12, BUTTON_INDEX_START}, {13, BUTTON_INDEX_LEFT_THUMBSTICK},
{14, BUTTON_INDEX_RIGHT_THUMBSTICK}};
auto find = buttonMapping.find(aButton);
if (find != buttonMapping.end()) {
service->NewButtonEvent(aIndex, find->second, aPressed);
} else {
service->NewButtonEvent(aIndex, aButton, aPressed);
}
}
};
class MogaProRemapper final : public GamepadRemapper {
public:
virtual uint32_t GetAxisCount() const override { return AXIS_INDEX_COUNT; }
virtual uint32_t GetButtonCount() const override {
return BUTTON_INDEX_COUNT - 1; /* no meta */
}
virtual void RemapAxisMoveEvent(uint32_t aIndex, uint32_t aAxis,
double aValue) const override {
RefPtr<GamepadPlatformService> service =
GamepadPlatformService::GetParentService();
if (!service) {
return;
}
switch (aAxis) {
case 0:
service->NewAxisMoveEvent(aIndex, AXIS_INDEX_LEFT_STICK_X, aValue);
break;
case 1:
service->NewAxisMoveEvent(aIndex, AXIS_INDEX_LEFT_STICK_Y, aValue);
break;
case 2:
service->NewAxisMoveEvent(aIndex, AXIS_INDEX_RIGHT_STICK_X, aValue);
break;
case 3:
service->NewButtonEvent(aIndex, BUTTON_INDEX_RIGHT_TRIGGER,
aValue > 0.1f);
break;
case 4:
service->NewButtonEvent(aIndex, BUTTON_INDEX_LEFT_TRIGGER,
aValue > 0.1f);
break;
case 5:
service->NewAxisMoveEvent(aIndex, AXIS_INDEX_RIGHT_STICK_Y, aValue);
break;
case 9:
FetchDpadFromAxis(aIndex, aValue);
break;
default:
NS_WARNING(
nsPrintfCString(
"Axis idx '%d' doesn't support in MogaProRemapper().", aAxis)
.get());
break;
}
}
virtual void RemapButtonEvent(uint32_t aIndex, uint32_t aButton,
bool aPressed) const override {
RefPtr<GamepadPlatformService> service =
GamepadPlatformService::GetParentService();
if (!service) {
return;
}
if (GetButtonCount() <= aButton) {
NS_WARNING(
nsPrintfCString(
"Button idx '%d' doesn't support in MogaProRemapper().", aButton)
.get());
return;
}
const std::map<uint32_t, uint32_t> buttonMapping = {
{3, BUTTON_INDEX_TERTIARY}, {4, BUTTON_INDEX_QUATERNARY},
{6, BUTTON_INDEX_LEFT_SHOULDER}, {7, BUTTON_INDEX_RIGHT_SHOULDER},
{11, BUTTON_INDEX_START}, {13, BUTTON_INDEX_LEFT_THUMBSTICK},
{14, BUTTON_INDEX_RIGHT_THUMBSTICK}};
auto find = buttonMapping.find(aButton);
if (find != buttonMapping.end()) {
service->NewButtonEvent(aIndex, find->second, aPressed);
} else {
service->NewButtonEvent(aIndex, aButton, aPressed);
}
}
};
class OnLiveWirelessRemapper final : public GamepadRemapper {
public:
virtual uint32_t GetAxisCount() const override { return AXIS_INDEX_COUNT; }
virtual uint32_t GetButtonCount() const override {
return BUTTON_INDEX_COUNT;
}
virtual void RemapAxisMoveEvent(uint32_t aIndex, uint32_t aAxis,
double aValue) const override {
RefPtr<GamepadPlatformService> service =
GamepadPlatformService::GetParentService();
if (!service) {
return;
}
switch (aAxis) {
case 0:
service->NewAxisMoveEvent(aIndex, AXIS_INDEX_LEFT_STICK_X, aValue);
break;
case 1:
service->NewAxisMoveEvent(aIndex, AXIS_INDEX_LEFT_STICK_Y, aValue);
break;
case 2:
service->NewButtonEvent(aIndex, BUTTON_INDEX_LEFT_TRIGGER,
aValue > 0.1f);
break;
case 3:
service->NewAxisMoveEvent(aIndex, AXIS_INDEX_RIGHT_STICK_X, aValue);
break;
case 4:
service->NewAxisMoveEvent(aIndex, AXIS_INDEX_RIGHT_STICK_Y, aValue);
break;
case 5:
service->NewButtonEvent(aIndex, BUTTON_INDEX_RIGHT_TRIGGER,
aValue > 0.1f);
break;
case 9:
FetchDpadFromAxis(aIndex, aValue);
break;
default:
NS_WARNING(
nsPrintfCString(
"Axis idx '%d' doesn't support in OnLiveWirelessRemapper().",
aAxis)
.get());
break;
}
}
virtual void RemapButtonEvent(uint32_t aIndex, uint32_t aButton,
bool aPressed) const override {
RefPtr<GamepadPlatformService> service =
GamepadPlatformService::GetParentService();
if (!service) {
return;
}
if (GetButtonCount() <= aButton) {
NS_WARNING(
nsPrintfCString(
"Button idx '%d' doesn't support in OnLiveWirelessRemapper().",
aButton)
.get());
return;
}
const std::map<uint32_t, uint32_t> buttonMapping = {
{3, BUTTON_INDEX_TERTIARY},
{4, BUTTON_INDEX_QUATERNARY},
{6, BUTTON_INDEX_LEFT_SHOULDER},
{7, BUTTON_INDEX_RIGHT_SHOULDER},
{12, BUTTON_INDEX_META},
{13, BUTTON_INDEX_LEFT_THUMBSTICK},
{14, BUTTON_INDEX_RIGHT_THUMBSTICK}};
auto find = buttonMapping.find(aButton);
if (find != buttonMapping.end()) {
service->NewButtonEvent(aIndex, find->second, aPressed);
} else {
service->NewButtonEvent(aIndex, aButton, aPressed);
}
}
};
class OUYARemapper final : public GamepadRemapper {
public:
virtual uint32_t GetAxisCount() const override { return AXIS_INDEX_COUNT; }
virtual uint32_t GetButtonCount() const override {
return BUTTON_INDEX_COUNT;
}
virtual void RemapAxisMoveEvent(uint32_t aIndex, uint32_t aAxis,
double aValue) const override {
RefPtr<GamepadPlatformService> service =
GamepadPlatformService::GetParentService();
if (!service) {
return;
}
switch (aAxis) {
case 0:
service->NewAxisMoveEvent(aIndex, AXIS_INDEX_LEFT_STICK_X, aValue);
break;
case 1:
service->NewAxisMoveEvent(aIndex, AXIS_INDEX_LEFT_STICK_Y, aValue);
break;
case 2:
service->NewButtonEvent(aIndex, BUTTON_INDEX_LEFT_TRIGGER,
aValue > 0.1f);
break;
case 3:
service->NewAxisMoveEvent(aIndex, AXIS_INDEX_RIGHT_STICK_X, aValue);
break;
case 4:
service->NewAxisMoveEvent(aIndex, AXIS_INDEX_RIGHT_STICK_Y, aValue);
break;
case 5:
service->NewButtonEvent(aIndex, BUTTON_INDEX_RIGHT_TRIGGER,
aValue > 0.1f);
break;
default:
NS_WARNING(
nsPrintfCString("Axis idx '%d' doesn't support in OUYARemapper().",
aAxis)
.get());
break;
}
}
virtual void RemapButtonEvent(uint32_t aIndex, uint32_t aButton,
bool aPressed) const override {
RefPtr<GamepadPlatformService> service =
GamepadPlatformService::GetParentService();
if (!service) {
return;
}
if (GetButtonCount() <= aButton) {
NS_WARNING(
nsPrintfCString("Button idx '%d' doesn't support in OUYARemapper().",
aButton)
.get());
return;
}
const std::map<uint32_t, uint32_t> buttonMapping = {
{1, BUTTON_INDEX_TERTIARY}, {2, BUTTON_INDEX_QUATERNARY},
{3, BUTTON_INDEX_SECONDARY}, {6, BUTTON_INDEX_LEFT_THUMBSTICK},
{7, BUTTON_INDEX_RIGHT_THUMBSTICK}, {8, BUTTON_INDEX_DPAD_UP},
{9, BUTTON_INDEX_DPAD_DOWN}, {10, BUTTON_INDEX_DPAD_LEFT},
{11, BUTTON_INDEX_DPAD_RIGHT}, {15, BUTTON_INDEX_META}};
auto find = buttonMapping.find(aButton);
if (find != buttonMapping.end()) {
service->NewButtonEvent(aIndex, find->second, aPressed);
} else {
service->NewButtonEvent(aIndex, aButton, aPressed);
}
}
};
already_AddRefed<GamepadRemapper> GetGamepadRemapper(const uint16_t aVendorId,
const uint16_t aProductId,
bool& aUsingDefault) {
const std::vector<GamepadRemappingData> remappingRules = {
{GamepadId::kAsusTekProduct4500, new ADT1Remapper()},
{GamepadId::kDragonRiseProduct0011, new TwoAxesEightKeysRemapper()},
{GamepadId::kGoogleProduct2c40, new ADT1Remapper()},
{GamepadId::kGoogleProduct9400, new StadiaControllerRemapper()},
{GamepadId::kLogitechProductc216, new LogitechDInputRemapper()},
{GamepadId::kLogitechProductc218, new LogitechDInputRemapper()},
{GamepadId::kLogitechProductc219, new LogitechDInputRemapper()},
{GamepadId::kNintendoProduct2006, new SwitchJoyConRemapper()},
{GamepadId::kNintendoProduct2007, new SwitchJoyConRemapper()},
{GamepadId::kNintendoProduct2009, new SwitchProRemapper()},
{GamepadId::kNintendoProduct200e, new SwitchProRemapper()},
{GamepadId::kNvidiaProduct7210, new NvShieldRemapper()},
{GamepadId::kNvidiaProduct7214, new NvShield2017Remapper()},
{GamepadId::kPadixProduct2060, new IBuffaloRemapper()},
{GamepadId::kPlayComProduct0005, new XSkillsRemapper()},
{GamepadId::kPrototypeVendorProduct0667, new BoomN64PsxRemapper()},
{GamepadId::kPrototypeVendorProduct9401, new AnalogGamepadRemapper()},
{GamepadId::kRazer1532Product0900, new RazerServalRemapper()},
{GamepadId::kSonyProduct0268, new Playstation3Remapper()},
{GamepadId::kSonyProduct05c4, new Dualshock4Remapper()},
{GamepadId::kSonyProduct09cc, new Dualshock4Remapper()},
{GamepadId::kSonyProduct0ba0, new Dualshock4Remapper()},
{GamepadId::kVendor20d6Product6271, new MogaProRemapper()},
{GamepadId::kVendor2378Product1008, new OnLiveWirelessRemapper()},
{GamepadId::kVendor2378Product100a, new OnLiveWirelessRemapper()},
{GamepadId::kVendor2836Product0001, new OUYARemapper()}};
const GamepadId id = static_cast<GamepadId>((aVendorId << 16) | aProductId);
for (uint32_t i = 0; i < remappingRules.size(); ++i) {
if (id == remappingRules[i].id) {
aUsingDefault = false;
return do_AddRef(remappingRules[i].remapping.get());
}
}
static RefPtr<GamepadRemapper> defaultRemapper = new DefaultRemapper();
aUsingDefault = true;
return do_AddRef(defaultRemapper.get());
}
} // namespace dom
} // namespace mozilla | 0 | 0.978446 | 1 | 0.978446 | game-dev | MEDIA | 0.620825 | game-dev,drivers | 0.935878 | 1 | 0.935878 |
Grarak/DSVita | 43,613 | src/core/graphics/gpu_3d/registers_3d.rs | use crate::core::cpu_regs::InterruptFlag;
use crate::core::emu::Emu;
use crate::core::graphics::gpu::{DISPLAY_HEIGHT, DISPLAY_WIDTH};
use crate::core::graphics::gpu_3d::matrix_vec::MatrixVec;
use crate::core::graphics::gpu_3d::renderer_3d::Gpu3DRendererContent;
use crate::core::memory::dma::DmaTransferMode;
use crate::core::CpuType::ARM9;
use crate::fixed_fifo::FixedFifo;
use crate::logging::debug_println;
use crate::math::{vmult_mat4, Matrix, Vectori16, Vectori32, MTX_IDENTITY};
use crate::utils::HeapMem;
use bilge::prelude::*;
use paste::paste;
use std::arch::arm::{int32x4_t, vld1q_s32, vld1q_s32_x3, vld1q_s32_x4, vsetq_lane_s32, vst1q_s32_x4};
use std::cmp::{max, min};
use std::hint::assert_unchecked;
use std::intrinsics::{likely, unlikely};
use std::mem::MaybeUninit;
use std::{mem, ptr};
pub const POLYGON_LIMIT: usize = 8192;
pub const VERTEX_LIMIT: usize = POLYGON_LIMIT * 4;
#[bitsize(32)]
#[derive(Copy, Clone, FromBits)]
pub struct GxStat {
box_pos_vec_test_busy: bool,
box_test_result: bool,
not_used: u6,
pos_vec_mtx_stack_lvl: u5,
proj_mtx_stack_lvl: u1,
mtx_stack_busy: bool,
mtx_stack_overflow_underflow_err: bool,
num_entries_cmd_fifo: u9,
cmd_fifo_less_half_full: bool,
cmd_fifo_empty: bool,
geometry_busy: bool,
not_used2: u2,
cmd_fifo_irq: u2,
}
impl Default for GxStat {
fn default() -> Self {
0x04000000.into()
}
}
#[bitsize(32)]
#[derive(Copy, Clone, FromBits)]
pub struct Viewport {
pub x1: u8,
pub y1: u8,
pub x2: u8,
pub y2: u8,
}
impl Default for Viewport {
fn default() -> Self {
let mut viewport = Viewport::from(0);
viewport.set_x2(DISPLAY_WIDTH as u8);
viewport.set_y2(DISPLAY_HEIGHT as u8);
viewport
}
}
#[bitsize(32)]
#[derive(Copy, Clone, DebugBits, Default, FromBits)]
pub struct TexImageParam {
pub vram_offset: u16,
pub repeat_s: bool,
pub repeat_t: bool,
pub flip_s: bool,
pub flip_t: bool,
pub size_s_shift: u3,
pub size_t_shift: u3,
pub format: u3,
color_0_transparent: bool,
pub coord_trans_mode: u2,
}
#[bitsize(32)]
#[derive(Copy, Clone, Default, FromBits)]
struct NormalVector {
x: u10,
y: u10,
z: u10,
not_used: u2,
}
#[bitsize(32)]
#[derive(Copy, Clone, Default, FromBits)]
struct TexCoord {
s: u16,
t: u16,
}
#[bitsize(32)]
#[derive(Copy, Clone, Default, FromBits)]
struct LightVector {
x: u10,
y: u10,
z: u10,
num: u2,
}
#[bitsize(32)]
#[derive(Copy, Clone, Default, FromBits)]
struct LightColor {
color: u15,
not_used: u15,
num: u2,
}
#[bitsize(32)]
#[derive(Copy, Clone, Default, FromBits)]
struct MaterialColor0 {
dif: u15,
set_vertex_color: bool,
amb: u15,
not_used: u1,
}
#[bitsize(32)]
#[derive(Copy, Clone, Default, FromBits)]
struct MaterialColor1 {
spe: u15,
set_shininess: bool,
em: u15,
not_used: u1,
}
#[bitsize(32)]
#[derive(Copy, Clone, Default, FromBits)]
struct Shininess {
shininess0: u8,
shininess1: u8,
shininess2: u8,
shininess3: u8,
}
#[bitsize(32)]
#[derive(Copy, Clone, DebugBits, Default, FromBits)]
pub struct PolygonAttr {
pub enable_lights: u4,
pub mode: u2,
pub render_back: bool,
pub render_front: bool,
not_used: u3,
pub trans_new_depth: bool,
pub render_far_plane: bool,
pub render_1_bot_polygons: bool,
pub depth_test_equal: bool,
pub fog: bool,
pub alpha: u5,
not_used2: u3,
pub id: u6,
not_used3: u2,
}
#[bitsize(8)]
#[derive(Copy, Clone, Default, FromBits)]
pub struct SwapBuffers {
pub manual_sort_translucent_polygon: bool,
pub depth_buffering_w: bool,
not_used: u6,
}
#[bitsize(8)]
#[derive(Copy, Clone, Default, FromBits)]
pub struct FifoParam {
param_count: u6,
is_test: bool,
can_skip: bool,
}
const fn count(c: u8) -> u8 {
assert!(c <= 32);
c
}
const fn skip(c: u8) -> u8 {
count(c) | (1 << 7)
}
const fn test(c: u8) -> u8 {
count(c) | (1 << 6)
}
#[rustfmt::skip]
const FIFO_PARAM_COUNTS: [u8; 128] = [
skip(0), skip(0), skip(0), skip(0), skip(0), skip(0), skip(0), skip(0), skip(0), skip(0), skip(0), skip(0), skip(0), skip(0), skip(0), skip(0), // 0x00-0x0F
count(1), count(0), count(1), count(1), count(1), count(0), count(16), count(12), count(16), count(12), count(9), count(3), count(3), skip(0), skip(0), skip(0), // 0x10-0x1F
count(1), skip(1), skip(1), skip(2), skip(1), skip(1), skip(1), skip(1), skip(1), count(1), count(1), count(1), skip(0), skip(0), skip(0), skip(0), // 0x20-0x2F
count(1), count(1), count(1), count(1), count(32), skip(0), skip(0), skip(0), skip(0), skip(0), skip(0), skip(0), skip(0), skip(0), skip(0), skip(0), // 0x30-0x3F
skip(1), skip(0), skip(0), skip(0), skip(0), skip(0), skip(0), skip(0), skip(0), skip(0), skip(0), skip(0), skip(0), skip(0), skip(0), skip(0), // 0x40-0x4F
count(1), skip(0), skip(0), skip(0), skip(0), skip(0), skip(0), skip(0), skip(0), skip(0), skip(0), skip(0), skip(0), skip(0), skip(0), skip(0), // 0x50-0x5F
count(1), skip(0), skip(0), skip(0), skip(0), skip(0), skip(0), skip(0), skip(0), skip(0), skip(0), skip(0), skip(0), skip(0), skip(0), skip(0), // 0x60-0x6F
test(3), test(2), test(1), skip(0), skip(0), skip(0), skip(0), skip(0), skip(0), skip(0), skip(0), skip(0), skip(0), skip(0), skip(0), skip(0), // 0x70-0x7F
];
const FUNC_GROUP_LUT: [fn(&mut Gpu3DRegisters, cmd: usize, params: &[u32; 32]); 8] = [
Gpu3DRegisters::exe_empty_group,
Gpu3DRegisters::exe_mat_group,
Gpu3DRegisters::exe_vert_group,
Gpu3DRegisters::exe_attr_group,
Gpu3DRegisters::exe_begin_vtxs,
Gpu3DRegisters::exe_swap_buffers,
Gpu3DRegisters::exe_viewport,
Gpu3DRegisters::exe_test_group,
];
#[derive(Copy, Clone, Default, Eq, PartialEq)]
#[repr(u8)]
pub enum PolygonMode {
#[default]
Modulation = 0,
Decal = 1,
Toon = 2,
Shadow = 3,
}
impl From<u8> for PolygonMode {
fn from(value: u8) -> Self {
debug_assert!(value <= PolygonMode::Shadow as u8);
unsafe { mem::transmute(value) }
}
}
#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
#[repr(u8)]
pub enum TextureFormat {
#[default]
None = 0,
A3I5Translucent = 1,
Color4Palette = 2,
Color16Palette = 3,
Color256Palette = 4,
Texel4x4Compressed = 5,
A5I3Translucent = 6,
Direct = 7,
}
impl From<u8> for TextureFormat {
fn from(value: u8) -> Self {
debug_assert!(value <= TextureFormat::Direct as u8);
unsafe { mem::transmute(value) }
}
}
#[derive(Copy, Clone, Default, Eq, PartialEq)]
#[repr(u8)]
pub enum TextureCoordTransMode {
#[default]
None = 0,
TexCoord = 1,
Normal = 2,
Vertex = 3,
}
impl From<u8> for TextureCoordTransMode {
fn from(value: u8) -> Self {
debug_assert!(value <= TextureCoordTransMode::Vertex as u8);
unsafe { mem::transmute(value) }
}
}
#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
#[repr(u8)]
pub enum PrimitiveType {
#[default]
SeparateTriangles = 0,
SeparateQuadliterals = 1,
TriangleStrips = 2,
QuadliteralStrips = 3,
}
impl PrimitiveType {
pub fn vertex_count(self) -> u8 {
match self {
PrimitiveType::SeparateTriangles => 3,
PrimitiveType::SeparateQuadliterals => 4,
PrimitiveType::TriangleStrips => 3,
PrimitiveType::QuadliteralStrips => 4,
}
}
}
impl From<u8> for PrimitiveType {
fn from(value: u8) -> Self {
debug_assert!(value <= PrimitiveType::QuadliteralStrips as u8);
unsafe { mem::transmute(value) }
}
}
#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
#[repr(u8)]
enum MtxMode {
#[default]
Projection = 0,
ModelView = 1,
ModelViewVec = 2,
Texture = 3,
}
impl From<u8> for MtxMode {
fn from(value: u8) -> Self {
debug_assert!(value <= MtxMode::Texture as u8);
unsafe { mem::transmute(value) }
}
}
#[repr(C)]
#[derive(Default)]
struct Matrices {
proj: Matrix,
coord: Matrix,
dir: Matrix,
tex: Matrix,
proj_stack: Matrix,
coord_stack: [Matrix; 32],
dir_stack: [Matrix; 32],
tex_stack: Matrix,
}
#[derive(Copy, Clone, Default)]
pub struct Vertex {
pub coords: Vectori32<4>,
pub tex_coords: Vectori16<2>,
pub color: u16,
pub tex_coord_trans_mode: TextureCoordTransMode,
pub tex_matrix_index: u16,
pub clip_matrix_index: u16,
}
#[derive(Copy, Clone, Default)]
pub struct Polygon {
pub normal: Vectori16<3>,
pub attr: PolygonAttr,
pub tex_image_param: TexImageParam,
pub palette_addr: u16,
pub polygon_type: PrimitiveType,
pub vertices_index: u16,
pub viewport: Viewport,
}
#[bitsize(8)]
#[derive(Copy, Clone, Default, FromBits)]
struct MatrixFlags {
clip_dirty: u2,
tex_push: bool,
clip_push: bool,
unused: u4,
}
impl MatrixFlags {
fn is_clip_dirty(self) -> bool {
u8::from(self.clip_dirty()) != 0
}
fn set_clip_dirty_bool(&mut self, dirty: bool) {
self.set_clip_dirty(u2::new(dirty as u8));
}
}
#[derive(Default)]
pub struct Gpu3DRegisters {
cmd_fifo: FixedFifo<u32, 1024>,
cmd_remaining_params: u8,
test_queue: u8,
pub last_total_cycles: u32,
pub flushed: bool,
swap_buffers: SwapBuffers,
pub gx_stat: GxStat,
mtx_mode: MtxMode,
matrices: Matrices,
cur_viewport: Viewport,
vertex_list_primitive_type: PrimitiveType,
vertex_list_size: u16,
vertices: HeapMem<Vertex, VERTEX_LIMIT>,
cur_vtx: Vertex,
vertices_size: u16,
polygons: HeapMem<Polygon, POLYGON_LIMIT>,
cur_polygon: Polygon,
polygons_size: u16,
clip_matrix: Matrix,
clip_matrices: MatrixVec,
tex_matrices: MatrixVec,
mtx_flags: MatrixFlags,
cur_polygon_attr: PolygonAttr,
material_color0: MaterialColor0,
material_color1: MaterialColor1,
pos_result: Vectori32<4>,
vec_result: Vectori16<3>,
pub skip: bool,
pub consume: bool,
pub pow_cnt1: u16,
pub current_pow_cnt1: u16,
}
macro_rules! unpacked_cmd {
($name:ident, $cmd:expr) => {
paste! {
pub fn [<regs _ 3d _ set _ $name>](&mut self, mask: u32, value: u32) {
self.regs_3d_queue_unpacked_value::<$cmd>(value & mask);
}
}
};
}
impl Emu {
pub fn regs_3d_run_cmds(&mut self, total_cycles: u32) {
let regs_3d = &mut self.gpu.gpu_3d_regs;
if unlikely(regs_3d.cmd_fifo.is_empty() || regs_3d.flushed) {
regs_3d.last_total_cycles = total_cycles;
return;
}
let is_cmd_fifo_half_full = regs_3d.is_cmd_fifo_half_full();
let cycle_diff = total_cycles - regs_3d.last_total_cycles;
regs_3d.last_total_cycles = total_cycles;
let mut executed_cycles = 0;
let mut params: [u32; 32] = unsafe { MaybeUninit::uninit().assume_init() };
'outer: while !regs_3d.cmd_fifo.is_empty() {
let mut value = *regs_3d.cmd_fifo.front();
regs_3d.cmd_fifo.pop_front();
while value != 0 {
let cmd = (value & 0x7F) as usize;
let current_value = value;
value >>= 8;
if unlikely(cmd == 0) {
continue;
}
let param_count = FifoParam::from(unsafe { *FIFO_PARAM_COUNTS.get_unchecked(cmd) });
let count = u8::from(param_count.param_count()) as usize;
if unlikely(count > regs_3d.cmd_fifo.len()) {
regs_3d.cmd_fifo.push_front(current_value);
break 'outer;
}
let skippable = param_count.can_skip();
if !regs_3d.skip || likely(!skippable) {
for i in 0..count {
unsafe { *params.get_unchecked_mut(i) = *regs_3d.cmd_fifo.front() };
regs_3d.cmd_fifo.pop_front();
}
let func = unsafe { FUNC_GROUP_LUT.get_unchecked(cmd >> 4) };
func(regs_3d, cmd & 0xF, ¶ms);
} else {
regs_3d.cmd_fifo.pop_front_multiple(count);
}
executed_cycles += 4;
if executed_cycles >= cycle_diff || cmd == 0x50 {
if value != 0 {
regs_3d.cmd_fifo.push_front(value);
}
break 'outer;
}
}
}
if is_cmd_fifo_half_full && !regs_3d.is_cmd_fifo_half_full() {
self.dma_trigger_all(ARM9, DmaTransferMode::GeometryCmdFifo);
}
let regs_3d = &mut self.gpu.gpu_3d_regs;
let irq = u8::from(regs_3d.gx_stat.cmd_fifo_irq());
if (irq == 1 && !regs_3d.is_cmd_fifo_half_full()) || (irq == 2 && regs_3d.is_cmd_fifo_empty()) {
self.cpu_send_interrupt(ARM9, InterruptFlag::GeometryCmdFifo);
}
let regs_3d = &mut self.gpu.gpu_3d_regs;
if !regs_3d.is_cmd_fifo_full() {
self.cpu_unhalt(ARM9, 1);
}
let regs_3d = &mut self.gpu.gpu_3d_regs;
if !regs_3d.skip && regs_3d.flushed {
regs_3d.pow_cnt1 = regs_3d.current_pow_cnt1;
}
}
#[inline(always)]
fn regs_3d_post_queue_entry(&mut self) {
if unlikely(self.gpu.gpu_3d_regs.is_cmd_fifo_full()) {
self.breakout_imm = true;
self.cpu_halt(ARM9, 1);
}
}
pub fn regs_3d_get_clip_mtx_result(&mut self, index: usize) -> u32 {
self.gpu.gpu_3d_regs.get_clip_matrix()[index] as u32
}
pub fn regs_3d_get_vec_mtx_result(&self, index: usize) -> u32 {
self.gpu.gpu_3d_regs.matrices.dir[(index / 3) * 4 + index % 3] as u32
}
pub fn regs_3d_get_gx_stat(&self) -> u32 {
let regs_3d = &self.gpu.gpu_3d_regs;
let mut gx_stat = regs_3d.gx_stat;
gx_stat.set_geometry_busy(!regs_3d.cmd_fifo.is_empty());
gx_stat.set_num_entries_cmd_fifo(u9::new(regs_3d.get_cmd_fifo_len() as u16));
gx_stat.set_cmd_fifo_less_half_full(!regs_3d.is_cmd_fifo_half_full());
gx_stat.set_cmd_fifo_empty(regs_3d.is_cmd_fifo_empty());
gx_stat.set_box_pos_vec_test_busy(regs_3d.test_queue != 0);
u32::from(gx_stat)
}
pub fn regs_3d_get_ram_count(&self) -> u32 {
((self.gpu.gpu_3d_regs.vertices_size as u32) << 16) | (self.gpu.gpu_3d_regs.polygons_size as u32)
}
pub fn regs_3d_get_pos_result(&self, index: usize) -> u32 {
self.gpu.gpu_3d_regs.pos_result[index] as u32
}
pub fn regs_3d_get_vec_result(&self, index: usize) -> u16 {
self.gpu.gpu_3d_regs.vec_result[index] as u16
}
#[inline(always)]
pub fn regs_3d_set_gx_fifo(&mut self, mask: u32, value: u32) {
let value = value & mask;
let regs_3d = &mut self.gpu.gpu_3d_regs;
let mut remaining_params = regs_3d.cmd_remaining_params;
let mut test_queue = regs_3d.test_queue;
if remaining_params == 0 {
for i in 0..4 {
let cmd = ((value as usize) >> (i << 3)) & 0x7F;
let param = unsafe { *FIFO_PARAM_COUNTS.get_unchecked(cmd) };
remaining_params += param & 0x3F;
test_queue += (param >> 6) & 1;
}
} else {
remaining_params -= 1;
}
regs_3d.cmd_remaining_params = remaining_params;
regs_3d.test_queue = test_queue;
regs_3d.cmd_fifo.push_back(value);
self.regs_3d_post_queue_entry();
}
#[inline(always)]
pub fn regs_3d_set_gx_fifo_multiple(&mut self, values: &[u32]) {
unsafe { assert_unchecked(!values.is_empty()) };
let regs_3d = &mut self.gpu.gpu_3d_regs;
let mut remaining_params = regs_3d.cmd_remaining_params;
let mut test_queue = regs_3d.test_queue;
let mut consumed = 0;
while consumed < values.len() {
if remaining_params == 0 {
let value = values[consumed];
for i in 0..4 {
let cmd = ((value as usize) >> (i << 3)) & 0x7F;
let param = unsafe { *FIFO_PARAM_COUNTS.get_unchecked(cmd) };
remaining_params += param & 0x3F;
test_queue += (param >> 6) & 1;
}
consumed += 1;
regs_3d.cmd_fifo.push_back(value);
}
if unlikely(consumed >= values.len()) {
break;
}
let values = &values[consumed..];
let can_consume = min(remaining_params as usize, values.len());
regs_3d.cmd_fifo.push_back_multiple(&values[..can_consume]);
remaining_params -= can_consume as u8;
consumed += can_consume;
}
regs_3d.cmd_remaining_params = remaining_params;
regs_3d.test_queue = test_queue;
self.regs_3d_post_queue_entry();
}
fn regs_3d_queue_unpacked_value<const CMD: u8>(&mut self, value: u32) {
let regs_3d = &mut self.gpu.gpu_3d_regs;
if regs_3d.cmd_remaining_params == 0 {
regs_3d.cmd_remaining_params = u8::from(FifoParam::from(FIFO_PARAM_COUNTS[CMD as usize]).param_count());
regs_3d.cmd_fifo.push_back(CMD as u32);
if regs_3d.cmd_remaining_params > 0 {
regs_3d.cmd_remaining_params -= 1;
regs_3d.cmd_fifo.push_back(value);
}
match CMD {
0x70 | 0x71 | 0x72 => regs_3d.test_queue += 1,
_ => {}
}
} else {
regs_3d.cmd_remaining_params -= 1;
regs_3d.cmd_fifo.push_back(value);
}
self.regs_3d_post_queue_entry();
}
unpacked_cmd!(mtx_mode, 0x10);
unpacked_cmd!(mtx_push, 0x11);
unpacked_cmd!(mtx_pop, 0x12);
unpacked_cmd!(mtx_store, 0x13);
unpacked_cmd!(mtx_restore, 0x14);
unpacked_cmd!(mtx_identity, 0x15);
unpacked_cmd!(mtx_load44, 0x16);
unpacked_cmd!(mtx_load43, 0x17);
unpacked_cmd!(mtx_mult44, 0x18);
unpacked_cmd!(mtx_mult43, 0x19);
unpacked_cmd!(mtx_mult33, 0x1A);
unpacked_cmd!(mtx_scale, 0x1B);
unpacked_cmd!(mtx_trans, 0x1C);
unpacked_cmd!(color, 0x20);
unpacked_cmd!(normal, 0x21);
unpacked_cmd!(tex_coord, 0x22);
unpacked_cmd!(vtx16, 0x23);
unpacked_cmd!(vtx10, 0x24);
unpacked_cmd!(vtx_x_y, 0x25);
unpacked_cmd!(vtx_x_z, 0x26);
unpacked_cmd!(vtx_y_z, 0x27);
unpacked_cmd!(vtx_diff, 0x28);
unpacked_cmd!(polygon_attr, 0x29);
unpacked_cmd!(tex_image_param, 0x2A);
unpacked_cmd!(pltt_base, 0x2B);
unpacked_cmd!(dif_amb, 0x30);
unpacked_cmd!(spe_emi, 0x31);
unpacked_cmd!(light_vector, 0x32);
unpacked_cmd!(light_color, 0x33);
unpacked_cmd!(shininess, 0x34);
unpacked_cmd!(begin_vtxs, 0x40);
unpacked_cmd!(end_vtxs, 0x41);
unpacked_cmd!(swap_buffers, 0x50);
unpacked_cmd!(viewport, 0x60);
unpacked_cmd!(box_test, 0x70);
unpacked_cmd!(pos_test, 0x71);
unpacked_cmd!(vec_test, 0x72);
pub fn regs_3d_set_gx_stat(&mut self, mut mask: u32, value: u32) {
if value & (1 << 15) != 0 {
self.gpu.gpu_3d_regs.gx_stat = (u32::from(self.gpu.gpu_3d_regs.gx_stat) & !0xA000).into();
}
mask &= 0xC0000000;
self.gpu.gpu_3d_regs.gx_stat = ((u32::from(self.gpu.gpu_3d_regs.gx_stat) & !mask) | (value & mask)).into();
}
}
impl Gpu3DRegisters {
pub fn new() -> Self {
let mut mtx_flags = MatrixFlags::from(0);
mtx_flags.set_clip_push(true);
mtx_flags.set_tex_push(true);
Gpu3DRegisters {
mtx_flags,
..Gpu3DRegisters::default()
}
}
fn is_cmd_fifo_full(&self) -> bool {
self.cmd_fifo.len() >= 260
}
pub fn is_cmd_fifo_half_full(&self) -> bool {
self.cmd_fifo.len() >= 132
}
fn is_cmd_fifo_empty(&self) -> bool {
self.cmd_fifo.len() <= 4
}
fn get_cmd_fifo_len(&self) -> usize {
max(self.cmd_fifo.len() as isize - 4, 0) as usize
}
fn get_clip_matrix(&mut self) -> &Matrix {
if unlikely(self.mtx_flags.is_clip_dirty()) {
self.mtx_flags.set_clip_dirty_bool(false);
self.mtx_flags.set_clip_push(true);
unsafe { vmult_mat4(self.matrices.coord.vld(), self.matrices.proj.vld(), &mut self.clip_matrix.0) };
}
&self.clip_matrix
}
fn exe_mat_group(&mut self, cmd: usize, params: &[u32; 32]) {
unsafe { assert_unchecked(cmd <= 0xF) };
const FUNC_LUT: [fn(&mut Gpu3DRegisters, params: &[u32; 32]); 16] = [
Gpu3DRegisters::exe_mtx_mode,
Gpu3DRegisters::exe_mtx_push,
Gpu3DRegisters::exe_mtx_pop,
Gpu3DRegisters::exe_mtx_store,
Gpu3DRegisters::exe_mtx_restore,
Gpu3DRegisters::exe_mtx_identity,
Gpu3DRegisters::exe_mtx_load44,
Gpu3DRegisters::exe_mtx_load43,
Gpu3DRegisters::exe_mtx_mult44,
Gpu3DRegisters::exe_mtx_mult43,
Gpu3DRegisters::exe_mtx_mult33,
Gpu3DRegisters::exe_mtx_scale,
Gpu3DRegisters::exe_mtx_trans,
Gpu3DRegisters::exe_empty,
Gpu3DRegisters::exe_empty,
Gpu3DRegisters::exe_empty,
];
const FUNC_NAMES_LUT: [&str; 16] = [
"exe_mtx_mode",
"exe_mtx_push",
"exe_mtx_pop",
"exe_mtx_store",
"exe_mtx_restore",
"exe_mtx_identity",
"exe_mtx_load44",
"exe_mtx_load43",
"exe_mtx_mult44",
"exe_mtx_mult43",
"exe_mtx_mult33",
"exe_mtx_scale",
"exe_mtx_trans",
"exe_empty",
"exe_empty",
"exe_empty",
];
debug_println!("execute mat group {cmd:x}: {}", FUNC_NAMES_LUT[cmd]);
FUNC_LUT[cmd](self, params);
}
fn exe_vert_group(&mut self, cmd: usize, params: &[u32; 32]) {
unsafe { assert_unchecked(cmd <= 0xF) };
const FUNC_LUT: [fn(&mut Gpu3DRegisters, params: &[u32; 32]); 16] = [
Gpu3DRegisters::exe_color,
Gpu3DRegisters::exe_normal,
Gpu3DRegisters::exe_tex_coord,
Gpu3DRegisters::exe_vtx16,
Gpu3DRegisters::exe_vtx10,
Gpu3DRegisters::exe_vtx_x_y,
Gpu3DRegisters::exe_vtx_x_z,
Gpu3DRegisters::exe_vtx_y_z,
Gpu3DRegisters::exe_vtx_diff,
Gpu3DRegisters::exe_polygon_attr,
Gpu3DRegisters::exe_tex_image_param,
Gpu3DRegisters::exe_pltt_base,
Gpu3DRegisters::exe_empty,
Gpu3DRegisters::exe_empty,
Gpu3DRegisters::exe_empty,
Gpu3DRegisters::exe_empty,
];
const FUNC_NAMES_LUT: [&str; 16] = [
"exe_color",
"exe_normal",
"exe_tex_coord",
"exe_vtx16",
"exe_vtx10",
"exe_vtx_x_y",
"exe_vtx_x_z",
"exe_vtx_y_z",
"exe_vtx_diff",
"exe_polygon_attr",
"exe_tex_image_param",
"exe_pltt_base",
"exe_empty",
"exe_empty",
"exe_empty",
"exe_empty",
];
debug_println!("execute vert group {cmd:x}: {}", FUNC_NAMES_LUT[cmd]);
FUNC_LUT[cmd](self, params);
}
fn exe_attr_group(&mut self, cmd: usize, params: &[u32; 32]) {
unsafe { assert_unchecked(cmd <= 0xF) };
match cmd {
0 => {
debug_println!("execute attr group {cmd:x}: exe_dif_amb");
self.exe_dif_amb(params);
}
1 => {
debug_println!("execute attr group {cmd:x}: exe_spe_emi");
self.exe_spe_emi(params);
}
2 => {
debug_println!("execute attr group {cmd:x}: exe_light_vector");
self.exe_light_vector(params);
}
3 => {
debug_println!("execute attr group {cmd:x}: exe_light_color");
self.exe_light_color(params);
}
4 => {
debug_println!("execute attr group {cmd:x}: exe_shininess");
self.exe_shininess(params);
}
_ => debug_println!("execute attr group {cmd:x}: exe_empty"),
}
}
fn exe_test_group(&mut self, cmd: usize, params: &[u32; 32]) {
unsafe { assert_unchecked(cmd <= 0xF) };
match cmd {
0 => {
debug_println!("execute test group {cmd:x}: exe_box_test");
self.exe_box_test(params);
}
1 => {
debug_println!("execute test group {cmd:x}: exe_pos_test");
self.exe_pos_test(params);
}
2 => {
debug_println!("execute test group {cmd:x}: exe_vec_test");
self.exe_vec_test(params);
}
_ => debug_println!("execute test group {cmd:x}: exe_empty"),
}
}
fn exe_empty_group(&mut self, _: usize, _: &[u32; 32]) {}
fn exe_empty(&mut self, _: &[u32; 32]) {}
fn exe_mtx_mode(&mut self, params: &[u32; 32]) {
self.mtx_mode = MtxMode::from((params[0] & 0x3) as u8);
}
fn exe_mtx_push(&mut self, _: &[u32; 32]) {
match self.mtx_mode {
MtxMode::Projection => {
if u8::from(self.gx_stat.proj_mtx_stack_lvl()) == 0 {
self.matrices.proj_stack = self.matrices.proj.clone();
self.gx_stat.set_proj_mtx_stack_lvl(u1::new(1));
} else {
self.gx_stat.set_mtx_stack_overflow_underflow_err(true);
}
}
MtxMode::ModelView | MtxMode::ModelViewVec => {
let ptr = u8::from(self.gx_stat.pos_vec_mtx_stack_lvl());
if ptr >= 30 {
self.gx_stat.set_mtx_stack_overflow_underflow_err(true);
}
if ptr < 31 {
self.matrices.coord_stack[ptr as usize] = self.matrices.coord.clone();
self.matrices.dir_stack[ptr as usize] = self.matrices.dir.clone();
self.gx_stat.set_pos_vec_mtx_stack_lvl(u5::new(ptr + 1));
}
}
MtxMode::Texture => self.matrices.tex_stack = self.matrices.tex.clone(),
}
}
fn exe_mtx_pop(&mut self, params: &[u32; 32]) {
match self.mtx_mode {
MtxMode::Projection => {
if u8::from(self.gx_stat.proj_mtx_stack_lvl()) == 1 {
self.matrices.proj = self.matrices.proj_stack.clone();
self.gx_stat.set_proj_mtx_stack_lvl(u1::new(0));
self.mtx_flags.set_clip_dirty_bool(true);
} else {
self.gx_stat.set_mtx_stack_overflow_underflow_err(true);
}
}
MtxMode::ModelView | MtxMode::ModelViewVec => {
let ptr = (u8::from(self.gx_stat.pos_vec_mtx_stack_lvl()) as i8 - (((params[0] << 2) as i8) >> 2)) as u8;
if ptr >= 30 {
self.gx_stat.set_mtx_stack_overflow_underflow_err(true);
}
if ptr < 31 {
self.gx_stat.set_pos_vec_mtx_stack_lvl(u5::new(ptr));
self.matrices.coord = self.matrices.coord_stack[ptr as usize].clone();
self.matrices.dir = self.matrices.dir_stack[ptr as usize].clone();
self.mtx_flags.set_clip_dirty_bool(true);
}
}
MtxMode::Texture => {
self.matrices.tex = self.matrices.tex_stack.clone();
self.mtx_flags.set_tex_push(true);
}
}
}
fn exe_mtx_store(&mut self, params: &[u32; 32]) {
match self.mtx_mode {
MtxMode::Projection => self.matrices.proj_stack = self.matrices.proj.clone(),
MtxMode::ModelView | MtxMode::ModelViewVec => {
let addr = params[0] & 0x1F;
if addr == 31 {
self.gx_stat.set_mtx_stack_overflow_underflow_err(true);
}
self.matrices.coord_stack[addr as usize] = self.matrices.coord.clone();
self.matrices.dir_stack[addr as usize] = self.matrices.dir.clone();
}
MtxMode::Texture => self.matrices.tex_stack = self.matrices.tex.clone(),
}
}
fn exe_mtx_restore(&mut self, params: &[u32; 32]) {
let mode = self.mtx_mode as u8 + 1;
self.mtx_flags.value |= mode; // Overflows to 4 when mode is texture, which sets the appropriate flags
match self.mtx_mode {
MtxMode::Projection => self.matrices.proj = self.matrices.proj_stack.clone(),
MtxMode::ModelView | MtxMode::ModelViewVec => {
let addr = params[0] & 0x1F;
if addr == 31 {
self.gx_stat.set_mtx_stack_overflow_underflow_err(true);
}
self.matrices.coord = self.matrices.coord_stack[addr as usize].clone();
self.matrices.dir = self.matrices.dir_stack[addr as usize].clone();
}
MtxMode::Texture => self.matrices.tex = self.matrices.tex_stack.clone(),
}
}
fn exe_mtx_identity(&mut self, _: &[u32; 32]) {
let mode = self.mtx_mode as u8 + 1;
self.mtx_flags.value |= mode;
let dst = unsafe { ptr::addr_of_mut!(self.matrices.proj).add(self.mtx_mode as usize).as_mut_unchecked() };
unsafe {
let mtx = Matrix::vld_identity();
vst1q_s32_x4(dst.0.as_mut_ptr(), mem::transmute(mtx));
if unlikely(self.mtx_mode == MtxMode::ModelViewVec) {
vst1q_s32_x4(self.matrices.coord.0.as_mut_ptr(), mem::transmute(mtx));
}
}
}
fn exe_mtx_load44(&mut self, params: &[u32; 32]) {
let mode = self.mtx_mode as u8 + 1;
self.mtx_flags.value |= mode;
let params: &[u32; 16] = unsafe { mem::transmute(params) };
let mtx: &Matrix = unsafe { mem::transmute(params) };
let dst = unsafe { ptr::addr_of_mut!(self.matrices.proj).add(self.mtx_mode as usize).as_mut_unchecked() };
unsafe {
let mtx = mtx.vld();
vst1q_s32_x4(dst.0.as_mut_ptr(), mem::transmute(mtx));
if unlikely(self.mtx_mode == MtxMode::ModelViewVec) {
vst1q_s32_x4(self.matrices.coord.0.as_mut_ptr(), mem::transmute(mtx));
}
}
}
fn exe_mtx_load43(&mut self, params: &[u32; 32]) {
let mode = self.mtx_mode as u8 + 1;
self.mtx_flags.value |= mode;
let load = |mtx: &mut Matrix| {
for i in 0..4 {
mtx.as_mut()[i * 4..i * 4 + 3].copy_from_slice(unsafe { mem::transmute(¶ms[i * 3..i * 3 + 3]) });
}
mtx[3] = 0;
mtx[7] = 0;
mtx[11] = 0;
mtx[15] = 1 << 12;
};
let dst = unsafe { ptr::addr_of_mut!(self.matrices.proj).add(self.mtx_mode as usize).as_mut_unchecked() };
load(dst);
if unlikely(self.mtx_mode == MtxMode::ModelViewVec) {
load(&mut self.matrices.coord);
}
}
#[inline(always)]
fn mtx_mult(&mut self, mtx: [int32x4_t; 4]) {
let mode = self.mtx_mode as u8 + 1;
self.mtx_flags.value |= mode;
let dst = unsafe { ptr::addr_of_mut!(self.matrices.proj).add(self.mtx_mode as usize).as_mut_unchecked() };
unsafe { vmult_mat4(mtx, dst.vld(), &mut dst.0) };
if unlikely(self.mtx_mode == MtxMode::ModelViewVec) {
unsafe { vmult_mat4(mtx, self.matrices.coord.vld(), &mut self.matrices.coord.0) };
}
}
fn exe_mtx_mult44(&mut self, params: &[u32; 32]) {
let mtx: &Matrix = unsafe { mem::transmute(params) };
self.mtx_mult(unsafe { mtx.vld() });
}
fn exe_mtx_mult43(&mut self, params: &[u32; 32]) {
unsafe {
let r0 = vld1q_s32(params.as_ptr() as *const i32);
let r0 = vsetq_lane_s32::<3>(0, r0);
let r1 = vld1q_s32((params.as_ptr() as *const i32).add(3));
let r1 = vsetq_lane_s32::<3>(0, r1);
let r2 = vld1q_s32((params.as_ptr() as *const i32).add(6));
let r2 = vsetq_lane_s32::<3>(0, r2);
let r3 = vld1q_s32((params.as_ptr() as *const i32).add(9));
let r3 = vsetq_lane_s32::<3>(1 << 12, r3);
self.mtx_mult([r0, r1, r2, r3]);
}
}
fn exe_mtx_mult33(&mut self, params: &[u32; 32]) {
unsafe {
let r0 = vld1q_s32(params.as_ptr() as *const i32);
let r0 = vsetq_lane_s32::<3>(0, r0);
let r1 = vld1q_s32((params.as_ptr() as *const i32).add(3));
let r1 = vsetq_lane_s32::<3>(0, r1);
let r2 = vld1q_s32((params.as_ptr() as *const i32).add(6));
let r2 = vsetq_lane_s32::<3>(0, r2);
let r3 = vld1q_s32([0, 0, 0, 1 << 12].as_ptr());
self.mtx_mult([r0, r1, r2, r3]);
}
}
fn exe_mtx_scale(&mut self, params: &[u32; 32]) {
let mode = self.mtx_mode as u8 + 1;
self.mtx_flags.value |= mode;
static mut SCALE_MTX: [i32; 16] = MTX_IDENTITY;
unsafe {
SCALE_MTX[0] = params[0] as i32;
SCALE_MTX[5] = params[1] as i32;
SCALE_MTX[10] = params[2] as i32;
let mtx = vld1q_s32_x4(SCALE_MTX.as_ptr());
let rm = if self.mtx_mode == MtxMode::ModelViewVec {
&mut self.matrices.coord
} else {
ptr::addr_of_mut!(self.matrices.proj).add(self.mtx_mode as usize).as_mut_unchecked()
};
vmult_mat4(mem::transmute(mtx), rm.vld(), &mut rm.0);
}
}
fn exe_mtx_trans(&mut self, params: &[u32; 32]) {
unsafe {
(params.as_ptr().add(3) as *mut u32).write_volatile(1 << 12);
let mtx = vld1q_s32_x3(MTX_IDENTITY.as_ptr());
let trans_vector = vld1q_s32(params.as_ptr() as _);
self.mtx_mult([mtx.0, mtx.1, mtx.2, trans_vector]);
}
}
fn exe_color(&mut self, params: &[u32; 32]) {
self.cur_vtx.color = params[0] as u16;
}
fn exe_normal(&mut self, params: &[u32; 32]) {
let normal_vector_param = NormalVector::from(params[0]);
self.cur_polygon.normal[0] = ((u16::from(normal_vector_param.x()) << 6) as i16) >> 3;
self.cur_polygon.normal[1] = ((u16::from(normal_vector_param.y()) << 6) as i16) >> 3;
self.cur_polygon.normal[2] = ((u16::from(normal_vector_param.z()) << 6) as i16) >> 3;
if self.cur_vtx.tex_coord_trans_mode == TextureCoordTransMode::Normal && self.mtx_flags.tex_push() {
self.tex_matrices.push(&self.matrices.tex);
self.mtx_flags.set_tex_push(false);
}
self.cur_vtx.tex_matrix_index = (self.tex_matrices.len() as u16).wrapping_sub(1);
}
fn exe_tex_coord(&mut self, params: &[u32; 32]) {
let tex_coord = TexCoord::from(params[0]);
self.cur_vtx.tex_coords[0] = tex_coord.s() as i16;
self.cur_vtx.tex_coords[1] = tex_coord.t() as i16;
if self.cur_vtx.tex_coord_trans_mode == TextureCoordTransMode::TexCoord && self.mtx_flags.tex_push() {
self.tex_matrices.push(&self.matrices.tex);
self.mtx_flags.set_tex_push(false);
}
self.cur_vtx.tex_matrix_index = (self.tex_matrices.len() as u16).wrapping_sub(1);
}
fn exe_vtx16(&mut self, params: &[u32; 32]) {
self.cur_vtx.coords[0] = params[0] as i16 as i32;
self.cur_vtx.coords[1] = (params[0] >> 16) as i16 as i32;
self.cur_vtx.coords[2] = params[1] as i16 as i32;
self.add_vertex();
}
fn exe_vtx10(&mut self, params: &[u32; 32]) {
self.cur_vtx.coords[0] = ((params[0] & 0x3FF) << 6) as i16 as i32;
self.cur_vtx.coords[1] = ((params[0] & 0xFFC00) >> 4) as i16 as i32;
self.cur_vtx.coords[2] = ((params[0] & 0x3FF00000) >> 14) as i16 as i32;
self.add_vertex();
}
fn exe_vtx_x_y(&mut self, params: &[u32; 32]) {
self.cur_vtx.coords[0] = params[0] as i16 as i32;
self.cur_vtx.coords[1] = (params[0] >> 16) as i16 as i32;
self.add_vertex();
}
fn exe_vtx_x_z(&mut self, params: &[u32; 32]) {
self.cur_vtx.coords[0] = params[0] as i16 as i32;
self.cur_vtx.coords[2] = (params[0] >> 16) as i16 as i32;
self.add_vertex();
}
fn exe_vtx_y_z(&mut self, params: &[u32; 32]) {
self.cur_vtx.coords[1] = params[0] as i16 as i32;
self.cur_vtx.coords[2] = (params[0] >> 16) as i16 as i32;
self.add_vertex();
}
fn exe_vtx_diff(&mut self, params: &[u32; 32]) {
self.cur_vtx.coords[0] += (((params[0] & 0x3FF) << 6) as i16 as i32) >> 6;
self.cur_vtx.coords[1] += (((params[0] & 0xFFC00) >> 4) as i16 as i32) >> 6;
self.cur_vtx.coords[2] += (((params[0] & 0x3FF00000) >> 14) as i16 as i32) >> 6;
self.add_vertex();
}
fn exe_polygon_attr(&mut self, params: &[u32; 32]) {
self.cur_polygon_attr = params[0].into();
}
fn exe_tex_image_param(&mut self, params: &[u32; 32]) {
self.cur_polygon.tex_image_param = TexImageParam::from(params[0]);
self.cur_vtx.tex_coord_trans_mode = TextureCoordTransMode::from(u8::from(self.cur_polygon.tex_image_param.coord_trans_mode()));
}
fn exe_pltt_base(&mut self, params: &[u32; 32]) {
self.cur_polygon.palette_addr = (params[0] & 0x1FFF) as u16;
}
fn exe_dif_amb(&mut self, params: &[u32; 32]) {
self.material_color0 = MaterialColor0::from(params[0]);
if self.material_color0.set_vertex_color() {
self.cur_vtx.color = u16::from(self.material_color0.dif());
}
}
fn exe_spe_emi(&mut self, params: &[u32; 32]) {
self.material_color1 = MaterialColor1::from(params[0]);
}
fn exe_light_vector(&mut self, params: &[u32; 32]) {
// TODO
}
fn exe_light_color(&mut self, params: &[u32; 32]) {
// TODO
}
fn exe_shininess(&mut self, params: &[u32; 32]) {
// TODO
}
fn exe_begin_vtxs(&mut self, cmd: usize, params: &[u32; 32]) {
if unlikely(cmd != 0) {
return;
}
debug_println!("execute exe_begin_vtxs {cmd:x}");
if self.vertex_list_size < self.vertex_list_primitive_type.vertex_count() as u16 {
self.vertices_size -= self.vertex_list_size;
}
self.vertex_list_primitive_type = PrimitiveType::from((params[0] & 0x3) as u8);
self.vertex_list_size = 0;
self.cur_polygon.attr = self.cur_polygon_attr;
self.cur_polygon.viewport = self.cur_viewport;
}
fn exe_swap_buffers(&mut self, cmd: usize, params: &[u32; 32]) {
if unlikely(cmd != 0) {
return;
}
debug_println!("execute exe_swap_buffers {cmd:x}");
self.flushed = true;
self.swap_buffers = SwapBuffers::from(params[0] as u8)
}
fn exe_viewport(&mut self, cmd: usize, params: &[u32; 32]) {
if unlikely(cmd != 0) {
return;
}
debug_println!("execute exe_viewport {cmd:x}");
self.cur_viewport = Viewport::from(params[0]);
}
fn exe_box_test(&mut self, _: &[u32; 32]) {
self.gx_stat.set_box_test_result(true);
self.test_queue -= 1;
}
fn exe_pos_test(&mut self, params: &[u32; 32]) {
self.cur_vtx.coords[0] = params[0] as i16 as i32;
self.cur_vtx.coords[1] = (params[0] >> 16) as i16 as i32;
self.cur_vtx.coords[2] = params[1] as i16 as i32;
self.cur_vtx.coords[3] = 1 << 12;
self.pos_result = self.cur_vtx.coords * self.get_clip_matrix();
self.test_queue -= 1;
}
fn exe_vec_test(&mut self, params: &[u32; 32]) {
let mut vector = Vectori32::<3>::new([
(((params[0] & 0x000003FF) << 6) as i16 as i32) >> 3,
(((params[0] & 0x000FFC00) >> 4) as i16 as i32) >> 3,
(((params[0] & 0x3FF00000) >> 14) as i16 as i32) >> 3,
]);
vector *= &self.matrices.dir;
self.vec_result[0] = ((vector[0] << 3) as i16) >> 3;
self.vec_result[1] = ((vector[1] << 3) as i16) >> 3;
self.vec_result[2] = ((vector[2] << 3) as i16) >> 3;
self.test_queue -= 1;
}
pub fn swap_buffers(&mut self) {
self.flushed = false;
if !self.skip {
self.consume = true;
}
self.skip = self.consume;
}
pub fn swap_to_renderer(&mut self, content: &mut Gpu3DRendererContent) {
mem::swap(&mut self.vertices, &mut content.vertices);
content.vertices_size = self.vertices_size;
self.vertices_size = 0;
self.vertex_list_size = 0;
mem::swap(&mut self.polygons, &mut content.polygons);
content.polygons_size = self.polygons_size;
self.polygons_size = 0;
mem::swap(&mut self.clip_matrices, &mut content.clip_matrices);
self.clip_matrices.clear();
self.mtx_flags.set_clip_push(true);
mem::swap(&mut self.tex_matrices, &mut content.tex_matrices);
self.tex_matrices.clear();
self.mtx_flags.set_tex_push(true);
content.swap_buffers = self.swap_buffers;
content.pow_cnt1 = self.pow_cnt1;
}
fn add_vertex(&mut self) {
if self.vertices_size >= VERTEX_LIMIT as u16 {
return;
}
self.get_clip_matrix();
if unlikely(self.mtx_flags.clip_push()) {
self.clip_matrices.push(&self.clip_matrix);
self.mtx_flags.set_clip_push(false);
}
if self.cur_vtx.tex_coord_trans_mode == TextureCoordTransMode::Vertex && unlikely(self.mtx_flags.tex_push()) {
self.tex_matrices.push(&self.matrices.tex);
self.mtx_flags.set_tex_push(false);
}
self.cur_vtx.tex_matrix_index = (self.tex_matrices.len() as u16).wrapping_sub(1);
unsafe {
*self.vertices.get_unchecked_mut(self.vertices_size as usize) = self.cur_vtx;
self.vertices.get_unchecked_mut(self.vertices_size as usize).clip_matrix_index = self.clip_matrices.len() as u16 - 1;
}
self.vertices_size += 1;
self.vertex_list_size += 1;
if unlikely(match self.vertex_list_primitive_type {
PrimitiveType::SeparateTriangles => self.vertex_list_size % 3 == 0,
PrimitiveType::SeparateQuadliterals => self.vertex_list_size % 4 == 0,
PrimitiveType::TriangleStrips => self.vertex_list_size >= 3,
PrimitiveType::QuadliteralStrips => self.vertex_list_size >= 4 && self.vertex_list_size % 2 == 0,
}) {
self.add_polygon();
}
}
fn add_polygon(&mut self) {
if self.polygons_size as usize >= POLYGON_LIMIT {
return;
}
let size = self.vertex_list_primitive_type.vertex_count();
let polygon = &mut self.polygons[self.polygons_size as usize];
*polygon = self.cur_polygon;
polygon.polygon_type = self.vertex_list_primitive_type;
polygon.vertices_index = self.vertices_size - size as u16;
self.polygons_size += 1;
}
}
| 0 | 0.757073 | 1 | 0.757073 | game-dev | MEDIA | 0.466611 | game-dev,graphics-rendering | 0.919463 | 1 | 0.919463 |
cloudhu/ChineseChessVR | 7,079 | Assets/VRTK/Editor/VRTK_ObjectSetup.cs | namespace VRTK
{
using UnityEngine;
using UnityEditor;
using VRTK.GrabAttachMechanics;
using VRTK.SecondaryControllerGrabActions;
public class VRTK_ObjectSetup : EditorWindow
{
private enum PrimaryGrab
{
ChildOfController,
FixedJoint,
Climbable,
CustomJoint,
RotatorTrack,
SpringJoint,
TrackObject
}
private enum SecondaryGrab
{
SwapControllers,
ControlDirection,
AxisScale
}
private bool useGrab = true;
private bool holdGrab = false;
private bool useUse = false;
private bool useIfGrabbed = false;
private bool holdUse = false;
private PrimaryGrab primGrab;
private SecondaryGrab secGrab;
private bool disableIdle = true;
private bool addrb = true;
private bool addHaptics = true;
private Color touchColor = Color.clear;
[MenuItem("Window/VRTK/Setup Interactable Object")]
private static void Init()
{
VRTK_ObjectSetup window = (VRTK_ObjectSetup)EditorWindow.GetWindow(typeof(VRTK_ObjectSetup));
window.minSize = new Vector2( 300f, 300f );
window.maxSize = new Vector2( 400f, 300f );
window.autoRepaintOnSceneChange = true;
window.titleContent.text = "Setup Object";
window.Show();
}
private void OnGUI()
{
EditorGUILayout.Space();
EditorGUILayout.LabelField("Touch Options", EditorStyles.boldLabel);
touchColor = EditorGUILayout.ColorField("Touch Highlight Color", touchColor);
EditorGUILayout.Space();
EditorGUILayout.LabelField("Grab Options", EditorStyles.boldLabel);
useGrab = EditorGUILayout.Toggle("Is Grabbable", useGrab);
holdGrab = EditorGUILayout.Toggle("Hold Button To Grab", holdGrab);
EditorGUILayout.Space();
primGrab = (PrimaryGrab)EditorGUILayout.EnumPopup("Grab Attach Mechanic", primGrab);
secGrab = (SecondaryGrab)EditorGUILayout.EnumPopup("Secondary Grab Attach", secGrab);
EditorGUILayout.Space();
EditorGUILayout.LabelField("Use Options", EditorStyles.boldLabel);
useUse = EditorGUILayout.Toggle("Is Usable", useUse);
holdUse = EditorGUILayout.Toggle("Hold Button To Use", holdUse);
useIfGrabbed = EditorGUILayout.Toggle("Use Only If Grabbed", useIfGrabbed);
EditorGUILayout.Space();
EditorGUILayout.LabelField("Misc Options", EditorStyles.boldLabel);
disableIdle = EditorGUILayout.Toggle("Disable On Idle", disableIdle);
addrb = EditorGUILayout.Toggle("Add RigidBody", addrb);
addHaptics = EditorGUILayout.Toggle("Add Haptics", addHaptics);
EditorGUILayout.Space();
if(GUILayout.Button("Setup selected object", GUILayout.Height(40)))
{
SetupObject();
}
}
private void SetupObject()
{
GameObject go = Selection.activeGameObject;
if(go)
{
VRTK_InteractableObject intObj = go.GetComponent<VRTK_InteractableObject>();
if(intObj == null)
{
intObj = go.AddComponent<VRTK_InteractableObject>();
}
intObj.touchHighlightColor = touchColor;
intObj.isGrabbable = useGrab;
intObj.holdButtonToGrab = holdGrab;
intObj.isUsable = useUse;
intObj.disableWhenIdle = disableIdle;
intObj.grabOverrideButton = VRTK_ControllerEvents.ButtonAlias.Undefined;
intObj.useOverrideButton = VRTK_ControllerEvents.ButtonAlias.Undefined;
VRTK_BaseGrabAttach grab = go.GetComponent<VRTK_BaseGrabAttach>();
if(grab != null)
{
DestroyImmediate(grab);
}
switch(primGrab)
{
case PrimaryGrab.ChildOfController:
grab = go.AddComponent<VRTK_ChildOfControllerGrabAttach>();
break;
case PrimaryGrab.FixedJoint:
grab = go.AddComponent<VRTK_FixedJointGrabAttach>();
break;
case PrimaryGrab.Climbable:
grab = go.AddComponent<VRTK_ClimbableGrabAttach>();
break;
case PrimaryGrab.CustomJoint:
grab = go.AddComponent<VRTK_CustomJointGrabAttach>();
break;
case PrimaryGrab.RotatorTrack:
grab = go.AddComponent<VRTK_RotatorTrackGrabAttach>();
break;
case PrimaryGrab.SpringJoint:
grab = go.AddComponent<VRTK_SpringJointGrabAttach>();
break;
case PrimaryGrab.TrackObject:
grab = go.AddComponent<VRTK_TrackObjectGrabAttach>();
break;
default:
grab = go.AddComponent<VRTK_ChildOfControllerGrabAttach>();
break;
}
intObj.grabAttachMechanicScript = grab;
VRTK_BaseGrabAction grab2 = go.GetComponent<VRTK_BaseGrabAction>();
if(grab2 != null)
{
DestroyImmediate(grab2);
}
switch(secGrab)
{
case SecondaryGrab.SwapControllers:
grab2 = go.AddComponent<VRTK_SwapControllerGrabAction>();
break;
case SecondaryGrab.ControlDirection:
grab2 = go.AddComponent<VRTK_ControlDirectionGrabAction>();
break;
case SecondaryGrab.AxisScale:
grab2 = go.AddComponent<VRTK_AxisScaleGrabAction>();
break;
default:
grab2 = go.AddComponent<VRTK_SwapControllerGrabAction>();
break;
}
intObj.secondaryGrabActionScript = grab2;
if(addrb)
{
Rigidbody rb = go.GetComponent<Rigidbody>();
if(rb == null)
{
go.AddComponent<Rigidbody>();
}
}
if(addHaptics)
{
VRTK_InteractHaptics haptics = go.GetComponent<VRTK_InteractHaptics>();
if(haptics == null)
{
go.AddComponent<VRTK_InteractHaptics>();
}
}
}
}
}
}
| 0 | 0.938961 | 1 | 0.938961 | game-dev | MEDIA | 0.633874 | game-dev | 0.947102 | 1 | 0.947102 |
adderbyte/GYM_XPLANE_ML | 5,758 | gym_xplane_final_version/reloadingScript.lua | -- first we need ffi module (variable must be declared local)
local ffi = require("ffi")
--local sh = require('sh')
--local xdotool = require('xdotool')
-- find the right lib to load
local XPLMlib = ""
if SYSTEM == "IBM" then
-- Windows OS (no path and file extension needed)
if SYSTEM_ARCHITECTURE == 64 then
XPLMlib = "XPLM_64" -- 64bit
else
XPLMlib = "XPLM" -- 32bit
end
elseif SYSTEM == "LIN" then
-- Linux OS (we need the path "Resources/plugins/" here for some reason)
if SYSTEM_ARCHITECTURE == 64 then
XPLMlib = "Resources/plugins/XPLM_64.so" -- 64bit
else
XPLMlib = "Resources/plugins/XPLM.so" -- 32bit
end
elseif SYSTEM == "APL" then
-- Mac OS (we need the path "Resources/plugins/" here for some reason)
XPLMlib = "Resources/plugins/XPLM.framework/XPLM" -- 64bit and 32 bit
else
return -- this should not happen
end
-- load the lib and store in local variable
local XPLM = ffi.load(XPLMlib)
-- define the XPLMReloadScenery() C-function to be used from Lua
ffi.cdef( "void XPLMReloadScenery(void)" )
-- ffi.cdef("int XPLMGetMyID(void)")
-- collect variables in dictionary, this allows
-- tracking scope of variables
controlVariables = { ["closeScenery_flag"] = true,
["count"] = 0,
["counter_check"] = 90,
["scenery_restart"] = true
}
-- function to get count
function get_count(count)
if count < controlVariables.counter_check then
count = count + 1
elseif count >= controlVariables.counter_check then
count = 0
end
logMsg(count) -- for debugging
return count
end
-- function to sleep for a while
-- from stack overflow
local clock = os.clock
function sleeps(n) -- seconds
local t0 = clock()
while clock() - t0 <= n do end
end
--DataRef("yp", "sim/cockpit2/controls/yoke_pitch_ratio")
--DataRef("yr", "sim/cockpit2/controls/yoke_roll_ratio")
--DataRef("sb", "sim/cockpit2/controls/speedbrake_ratio")
--DataRef("fr", "sim/cockpit2/controls/flap_ratio")
--DataRef("ws", "sim/cockpit2/controls/wingsweep_ratio")
DataRef("ground", "sim/flightmodel2/gear/on_ground")
DataRef("crasher", "sim/flightmodel/engine/ENGN_running",0)
DataRef("gear", "sim/cockpit/switches/gear_handle_status", "writable")
gear=0.0
logMsg("Target height ...",gear )
command_once("sim/autopilot/hsi_select_gps")
set("sim/cockpit/switches/gear_handle_status", 0) -- set gear status to zero since not landing
-- define local function
function let_XPLM_reload_the_scenery()
--[[ This function reloads the scene if the
count is less than countercheck.
The command do_often runs this function often
on the frame. Try do_sometimes or do_every_frame
The add_macro puts makes it possible to set this
function as macro on xplane under the flyWithLua menu
]]
if ground >= 1 then
logMsg(controlVariables.count)
controlVariables.count = 0
logMsg("I am ground")
print("reloading")
--sleeps(2)
--command_once('sim/FMS/next')
--command_once('sim/FMS2/next')
--WID='xdotool search' --title "X-System" | head -1`
--xdotool windowfocus $WID
--xdotool key ctrl+V
--reload_scenery()
-- this XPLM.XPLMReloadScenery()
---XPLMSpeakString("X Plane reloading")
load_situation(SYSTEM_DIRECTORY .. "/Output/situations/keepHeading.sit" )
--XPLM.XPLMReloadScenery()
end
if crasher<=0 then
logMsg(controlVariables.count)
controlVariables.count = 0
logMsg("I am crasher")
print("reloading")
--sleeps(2)
--command_once('sim/FMS/next')
--command_once('sim/FMS2/next')
--WID='xdotool search' --title "X-System" | head -1`
--xdotool windowfocus $WID
--xdotool key ctrl+V
--reload_scenery()
-- this XPLM.XPLMReloadScenery()
---XPLMSpeakString("X Plane reloading")
load_situation(SYSTEM_DIRECTORY .. "/Output/situations/keepHeading.sit" )
--XPLM.XPLMReloadScenery()
end
if controlVariables.count >= controlVariables.counter_check then
logMsg(controlVariables.count)
logMsg("I am control")
--sleeps(1)
--XPLM.XPLMReloadScenery()
controlVariables.count = get_count(controlVariables.count)
--command_once('sim/FMS/next')
--command_once('sim/FMS2/next')
--WID='xdotool search' --title "X-System" | head -1`
--xdotool windowfocus $WID
--xdotool key ctrl+V
--reload_scenery()
-- this XPLM.XPLMReloadScenery()
---XPLMSpeakString("X Plane reloading")
load_situation(SYSTEM_DIRECTORY .. "/Output/situations/keepHeading.sit" )
--XPLM.XPLMReloadScenery()
--logMsg(count)
--XPLM.XPLMReloadScenery()
else
--command_once('sim/FMS2/next')
--command_once('sim/FMS2/next')
logMsg("I am counter altitude")
--print(ground)
--print(crasher)
controlVariables.count = get_count(controlVariables.count)
--if controlVariables.count == 1 and controlVariables.scenery_restart then
--load_situation(SYSTEM_DIRECTORY .. "/Output/situations/cruise.sit" )
--end
end
--load_aircraft()
--[[ elseif count < 4 then
--flag = true
command_once('sim/operation/close_windows')
count = sleep(count)
XPLMSpeakString("Running check check ...")
end]]
end
do_often("let_XPLM_reload_the_scenery()")
--if count < counter_check then
--add_macro("Reloader", "autopilot_helper_active = true", "autopilot_helper_active = false", "activate")
--add_macro("Reloader", "autopilot_helper_active = true", "autopilot_helper_active = false", "deactivate")
if controlVariables.count >= controlVariables.counter_check then
add_macro("Reloader", "closeScenery_flag = true", "closeScenery_flag = false", "activate")
--else
--add_macro("Reloader", "autopilot_helper_active = true", "autopilot_helper_active = false", "deactivate")
end
| 0 | 0.743844 | 1 | 0.743844 | game-dev | MEDIA | 0.541926 | game-dev | 0.938583 | 1 | 0.938583 |
OpenSAGE/OpenSAGE | 4,922 | src/OpenSage.Game/Scripting/Waypoints.cs | #nullable enable
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Numerics;
using OpenSage.Data.Map;
using OpenSage.Mathematics;
using OpenSage.Utilities.Extensions;
namespace OpenSage.Scripting;
public sealed class WaypointCollection
{
private readonly Dictionary<int, Waypoint> _waypointsByID;
private readonly Dictionary<string, Waypoint> _waypointsByName;
private readonly Dictionary<string, HashSet<Waypoint>> _waypointsByPathLabel;
public Waypoint this[string name] => _waypointsByName[name];
public WaypointCollection()
{
// Note that we explicitly allow duplicate waypoint names.
_waypointsByName = [];
_waypointsByID = [];
_waypointsByPathLabel = [];
}
public WaypointCollection(IEnumerable<Waypoint> waypoints, IEnumerable<WaypointPath> paths)
: this()
{
foreach (var waypoint in waypoints)
{
_waypointsByName[waypoint.Name] = waypoint;
_waypointsByID[waypoint.ID] = waypoint;
foreach (var pathLabel in waypoint.PathLabels)
{
if (!_waypointsByPathLabel.TryGetValue(pathLabel, out var collection))
{
collection = [];
_waypointsByPathLabel.Add(pathLabel, collection);
}
collection.Add(waypoint);
}
}
foreach (var path in paths)
{
if (_waypointsByID.TryGetValue(path.StartWaypointID, out var startWaypoint) &&
_waypointsByID.TryGetValue(path.EndWaypointID, out var endWaypoint))
{
startWaypoint.AddConnectionTo(endWaypoint);
}
}
}
public bool TryGetByName(string name, out Waypoint? waypoint)
{
return _waypointsByName.TryGetValue(name, out waypoint);
}
public bool TryGetById(int id, out Waypoint? waypoint)
{
return _waypointsByID.TryGetValue(id, out waypoint);
}
public IReadOnlyCollection<Waypoint> GetByPathLabel(string pathLabel)
{
return _waypointsByPathLabel.TryGetValue(pathLabel, out var waypoints) ? waypoints : Array.Empty<Waypoint>();
}
public bool TryGetPlayerStart(int playerIndex, out Waypoint? waypoint)
{
// Generals uses 0-based player indices, but 1-based indices for waypoints.
// However we already use 1-based indices for both, so we don't need to adjust here.
return TryGetByName($"Player_{playerIndex}_Start", out waypoint);
}
}
[DebuggerDisplay("ID = {ID}, Name = {Name}")]
public sealed class Waypoint
{
public const uint InvalidId = 0x7FFFFFFF;
public const string ObjectTypeName = "*Waypoints/Waypoint";
private List<Waypoint>? _connectedWaypoints;
public int ID { get; }
public string Name { get; }
public Vector3 Position { get; }
public IEnumerable<string> PathLabels { get; }
internal Waypoint(MapObject mapObject)
{
ID = (int)mapObject.Properties["waypointID"].Value;
Name = (string)mapObject.Properties["waypointName"].Value;
Position = mapObject.Position;
// It seems that if one of the label properties exists, all of them do
if (mapObject.Properties.TryGetValue("waypointPathLabel1", out var label1))
{
PathLabels = new[]
{
(string) label1.Value,
(string) mapObject.Properties["waypointPathLabel2"].Value,
(string) mapObject.Properties["waypointPathLabel3"].Value
}.WhereNot(string.IsNullOrWhiteSpace).ToSet();
}
else
{
PathLabels = [];
}
}
public void AddConnectionTo(Waypoint waypoint)
{
_connectedWaypoints ??= [];
_connectedWaypoints.Add(waypoint);
}
public IReadOnlyList<Waypoint> ConnectedWaypoints =>
(IReadOnlyList<Waypoint>?)_connectedWaypoints ?? [];
/// <summary>
/// Follows a waypoint path starting with this waypoint.
/// A path can contain branches and loops, which means that
/// a) we need a random number generator to pick a path when there is more than one and
/// b) the returned enumerable is potentially infinite, so avoid materializing it by
/// calling <see cref="Enumerable.ToList"/> and co.
/// </summary>
public IEnumerable<Vector3> FollowPath(IRandom random)
{
var currentWaypoint = this;
while (currentWaypoint != null)
{
yield return currentWaypoint.Position;
var connectedWaypoints = currentWaypoint.ConnectedWaypoints;
currentWaypoint = connectedWaypoints.Count switch
{
0 => null,
1 => connectedWaypoints[0],
int n => connectedWaypoints[random.Next(0, n - 1)]
};
}
}
}
| 0 | 0.70124 | 1 | 0.70124 | game-dev | MEDIA | 0.731912 | game-dev | 0.929052 | 1 | 0.929052 |
WeDias/StardewValley | 54,240 | Menus/CarpenterMenu.cs | // Decompiled with JetBrains decompiler
// Type: StardewValley.Menus.CarpenterMenu
// Assembly: Stardew Valley, Version=1.5.6.22018, Culture=neutral, PublicKeyToken=null
// MVID: BEBB6D18-4941-4529-AC12-B54F0C61CC20
// Assembly location: C:\Program Files (x86)\Steam\steamapps\common\Stardew Valley\Stardew Valley.dll
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Netcode;
using StardewValley.BellsAndWhistles;
using StardewValley.Buildings;
using StardewValley.Locations;
using StardewValley.Objects;
using System;
using System.Collections.Generic;
using System.Linq;
using xTile.Dimensions;
namespace StardewValley.Menus
{
public class CarpenterMenu : IClickableMenu
{
public const int region_backButton = 101;
public const int region_forwardButton = 102;
public const int region_upgradeIcon = 103;
public const int region_demolishButton = 104;
public const int region_moveBuitton = 105;
public const int region_okButton = 106;
public const int region_cancelButton = 107;
public const int region_paintButton = 108;
public int maxWidthOfBuildingViewer = 448;
public int maxHeightOfBuildingViewer = 512;
public int maxWidthOfDescription = 416;
private List<BluePrint> blueprints;
private int currentBlueprintIndex;
public ClickableTextureComponent okButton;
public ClickableTextureComponent cancelButton;
public ClickableTextureComponent backButton;
public ClickableTextureComponent forwardButton;
public ClickableTextureComponent upgradeIcon;
public ClickableTextureComponent demolishButton;
public ClickableTextureComponent moveButton;
public ClickableTextureComponent paintButton;
private Building currentBuilding;
private Building buildingToMove;
private string buildingDescription;
private string buildingName;
private List<Item> ingredients = new List<Item>();
private int price;
private bool onFarm;
private bool drawBG = true;
private bool freeze;
private bool upgrading;
private bool demolishing;
private bool moving;
private bool magicalConstruction;
private bool painting;
protected BluePrint _demolishCheckBlueprint;
private string hoverText = "";
public bool readOnly
{
set
{
if (!value)
return;
this.upgradeIcon.visible = false;
this.demolishButton.visible = false;
this.moveButton.visible = false;
this.okButton.visible = false;
this.paintButton.visible = false;
this.cancelButton.leftNeighborID = 102;
}
}
public BluePrint CurrentBlueprint => this.blueprints[this.currentBlueprintIndex];
public CarpenterMenu(bool magicalConstruction = false)
{
this.magicalConstruction = magicalConstruction;
Game1.player.forceCanMove();
this.resetBounds();
this.blueprints = new List<BluePrint>();
if (magicalConstruction)
{
this.blueprints.Add(new BluePrint("Junimo Hut"));
this.blueprints.Add(new BluePrint("Earth Obelisk"));
this.blueprints.Add(new BluePrint("Water Obelisk"));
this.blueprints.Add(new BluePrint("Desert Obelisk"));
if (Game1.stats.getStat("boatRidesToIsland") >= 1U)
this.blueprints.Add(new BluePrint("Island Obelisk"));
this.blueprints.Add(new BluePrint("Gold Clock"));
}
else
{
this.blueprints.Add(new BluePrint("Coop"));
this.blueprints.Add(new BluePrint("Barn"));
this.blueprints.Add(new BluePrint("Well"));
this.blueprints.Add(new BluePrint("Silo"));
this.blueprints.Add(new BluePrint("Mill"));
this.blueprints.Add(new BluePrint("Shed"));
this.blueprints.Add(new BluePrint("Fish Pond"));
int buildingsConstructed = Game1.getFarm().getNumberBuildingsConstructed("Cabin");
if (Game1.IsMasterGame && buildingsConstructed < Game1.CurrentPlayerLimit - 1)
{
this.blueprints.Add(new BluePrint("Stone Cabin"));
this.blueprints.Add(new BluePrint("Plank Cabin"));
this.blueprints.Add(new BluePrint("Log Cabin"));
}
if (Game1.getFarm().getNumberBuildingsConstructed("Stable") < buildingsConstructed + 1)
this.blueprints.Add(new BluePrint("Stable"));
this.blueprints.Add(new BluePrint("Slime Hutch"));
if (Game1.getFarm().isBuildingConstructed("Coop"))
this.blueprints.Add(new BluePrint("Big Coop"));
if (Game1.getFarm().isBuildingConstructed("Big Coop"))
this.blueprints.Add(new BluePrint("Deluxe Coop"));
if (Game1.getFarm().isBuildingConstructed("Barn"))
this.blueprints.Add(new BluePrint("Big Barn"));
if (Game1.getFarm().isBuildingConstructed("Big Barn"))
this.blueprints.Add(new BluePrint("Deluxe Barn"));
if (Game1.getFarm().isBuildingConstructed("Shed"))
this.blueprints.Add(new BluePrint("Big Shed"));
this.blueprints.Add(new BluePrint("Shipping Bin"));
}
this.setNewActiveBlueprint();
if (!Game1.options.SnappyMenus)
return;
this.populateClickableComponentList();
this.snapToDefaultClickableComponent();
}
public override bool shouldClampGamePadCursor() => this.onFarm;
public override void snapToDefaultClickableComponent()
{
this.currentlySnappedComponent = this.getComponentWithID(107);
this.snapCursorToCurrentSnappedComponent();
}
private void resetBounds()
{
this.xPositionOnScreen = Game1.uiViewport.Width / 2 - this.maxWidthOfBuildingViewer - IClickableMenu.spaceToClearSideBorder;
this.yPositionOnScreen = Game1.uiViewport.Height / 2 - this.maxHeightOfBuildingViewer / 2 - IClickableMenu.spaceToClearTopBorder + 32;
this.width = this.maxWidthOfBuildingViewer + this.maxWidthOfDescription + IClickableMenu.spaceToClearSideBorder * 2 + 64;
this.height = this.maxHeightOfBuildingViewer + IClickableMenu.spaceToClearTopBorder;
this.initialize(this.xPositionOnScreen, this.yPositionOnScreen, this.width, this.height, true);
ClickableTextureComponent textureComponent1 = new ClickableTextureComponent("OK", new Microsoft.Xna.Framework.Rectangle(this.xPositionOnScreen + this.width - IClickableMenu.borderWidth - IClickableMenu.spaceToClearSideBorder - 192 - 12, this.yPositionOnScreen + this.maxHeightOfBuildingViewer + 64, 64, 64), (string) null, (string) null, Game1.mouseCursors, new Microsoft.Xna.Framework.Rectangle(366, 373, 16, 16), 4f);
textureComponent1.myID = 106;
textureComponent1.rightNeighborID = 104;
textureComponent1.leftNeighborID = 105;
this.okButton = textureComponent1;
ClickableTextureComponent textureComponent2 = new ClickableTextureComponent("OK", new Microsoft.Xna.Framework.Rectangle(this.xPositionOnScreen + this.width - IClickableMenu.borderWidth - IClickableMenu.spaceToClearSideBorder - 64, this.yPositionOnScreen + this.maxHeightOfBuildingViewer + 64, 64, 64), (string) null, (string) null, Game1.mouseCursors, Game1.getSourceRectForStandardTileSheet(Game1.mouseCursors, 47), 1f);
textureComponent2.myID = 107;
textureComponent2.leftNeighborID = 104;
this.cancelButton = textureComponent2;
ClickableTextureComponent textureComponent3 = new ClickableTextureComponent(new Microsoft.Xna.Framework.Rectangle(this.xPositionOnScreen + 64, this.yPositionOnScreen + this.maxHeightOfBuildingViewer + 64, 48, 44), Game1.mouseCursors, new Microsoft.Xna.Framework.Rectangle(352, 495, 12, 11), 4f);
textureComponent3.myID = 101;
textureComponent3.rightNeighborID = 102;
this.backButton = textureComponent3;
ClickableTextureComponent textureComponent4 = new ClickableTextureComponent(new Microsoft.Xna.Framework.Rectangle(this.xPositionOnScreen + this.maxWidthOfBuildingViewer - 256 + 16, this.yPositionOnScreen + this.maxHeightOfBuildingViewer + 64, 48, 44), Game1.mouseCursors, new Microsoft.Xna.Framework.Rectangle(365, 495, 12, 11), 4f);
textureComponent4.myID = 102;
textureComponent4.leftNeighborID = 101;
textureComponent4.rightNeighborID = -99998;
this.forwardButton = textureComponent4;
ClickableTextureComponent textureComponent5 = new ClickableTextureComponent(Game1.content.LoadString("Strings\\UI:Carpenter_Demolish"), new Microsoft.Xna.Framework.Rectangle(this.xPositionOnScreen + this.width - IClickableMenu.borderWidth - IClickableMenu.spaceToClearSideBorder - 128 - 8, this.yPositionOnScreen + this.maxHeightOfBuildingViewer + 64 - 4, 64, 64), (string) null, (string) null, Game1.mouseCursors, new Microsoft.Xna.Framework.Rectangle(348, 372, 17, 17), 4f);
textureComponent5.myID = 104;
textureComponent5.rightNeighborID = 107;
textureComponent5.leftNeighborID = 106;
this.demolishButton = textureComponent5;
ClickableTextureComponent textureComponent6 = new ClickableTextureComponent(new Microsoft.Xna.Framework.Rectangle(this.xPositionOnScreen + this.maxWidthOfBuildingViewer - 128 + 32, this.yPositionOnScreen + 8, 36, 52), Game1.mouseCursors, new Microsoft.Xna.Framework.Rectangle(402, 328, 9, 13), 4f);
textureComponent6.myID = 103;
textureComponent6.rightNeighborID = 104;
textureComponent6.leftNeighborID = 105;
this.upgradeIcon = textureComponent6;
ClickableTextureComponent textureComponent7 = new ClickableTextureComponent(Game1.content.LoadString("Strings\\UI:Carpenter_MoveBuildings"), new Microsoft.Xna.Framework.Rectangle(this.xPositionOnScreen + this.width - IClickableMenu.borderWidth - IClickableMenu.spaceToClearSideBorder - 256 - 20, this.yPositionOnScreen + this.maxHeightOfBuildingViewer + 64, 64, 64), (string) null, (string) null, Game1.mouseCursors, new Microsoft.Xna.Framework.Rectangle(257, 284, 16, 16), 4f);
textureComponent7.myID = 105;
textureComponent7.rightNeighborID = 106;
textureComponent7.leftNeighborID = -99998;
this.moveButton = textureComponent7;
ClickableTextureComponent textureComponent8 = new ClickableTextureComponent(Game1.content.LoadString("Strings\\UI:Carpenter_PaintBuildings"), new Microsoft.Xna.Framework.Rectangle(this.xPositionOnScreen + this.width - IClickableMenu.borderWidth - IClickableMenu.spaceToClearSideBorder - 320 - 20, this.yPositionOnScreen + this.maxHeightOfBuildingViewer + 64, 64, 64), (string) null, (string) null, Game1.mouseCursors2, new Microsoft.Xna.Framework.Rectangle(80, 208, 16, 16), 4f);
textureComponent8.myID = 105;
textureComponent8.rightNeighborID = -99998;
textureComponent8.leftNeighborID = -99998;
this.paintButton = textureComponent8;
bool flag1 = false;
bool flag2 = this.CanPaintHouse() && this.HasPermissionsToPaint((Building) null);
foreach (Building building in Game1.getFarm().buildings)
{
if (building.hasCarpenterPermissions())
flag1 = true;
if (building.CanBePainted() && this.HasPermissionsToPaint(building))
flag2 = true;
}
this.demolishButton.visible = Game1.IsMasterGame;
this.moveButton.visible = Game1.IsMasterGame || Game1.player.team.farmhandsCanMoveBuildings.Value == FarmerTeam.RemoteBuildingPermissions.On || Game1.player.team.farmhandsCanMoveBuildings.Value == FarmerTeam.RemoteBuildingPermissions.OwnedBuildings & flag1;
this.paintButton.visible = flag2;
if (this.magicalConstruction)
this.paintButton.visible = false;
if (!this.demolishButton.visible)
{
this.upgradeIcon.rightNeighborID = this.demolishButton.rightNeighborID;
this.okButton.rightNeighborID = this.demolishButton.rightNeighborID;
this.cancelButton.leftNeighborID = this.demolishButton.leftNeighborID;
}
if (this.moveButton.visible)
return;
this.upgradeIcon.leftNeighborID = this.moveButton.leftNeighborID;
this.forwardButton.rightNeighborID = -99998;
this.okButton.leftNeighborID = this.moveButton.leftNeighborID;
}
public void setNewActiveBlueprint()
{
this.currentBuilding = !this.blueprints[this.currentBlueprintIndex].name.Contains("Coop") ? (!this.blueprints[this.currentBlueprintIndex].name.Contains("Barn") ? (!this.blueprints[this.currentBlueprintIndex].name.Contains("Mill") ? (!this.blueprints[this.currentBlueprintIndex].name.Contains("Junimo Hut") ? (!this.blueprints[this.currentBlueprintIndex].name.Contains("Shipping Bin") ? (!this.blueprints[this.currentBlueprintIndex].name.Contains("Fish Pond") ? (!this.blueprints[this.currentBlueprintIndex].name.Contains("Greenhouse") ? new Building(this.blueprints[this.currentBlueprintIndex], Vector2.Zero) : (Building) new GreenhouseBuilding(this.blueprints[this.currentBlueprintIndex], Vector2.Zero)) : (Building) new FishPond(this.blueprints[this.currentBlueprintIndex], Vector2.Zero)) : (Building) new ShippingBin(this.blueprints[this.currentBlueprintIndex], Vector2.Zero)) : (Building) new JunimoHut(this.blueprints[this.currentBlueprintIndex], Vector2.Zero)) : (Building) new Mill(this.blueprints[this.currentBlueprintIndex], Vector2.Zero)) : (Building) new Barn(this.blueprints[this.currentBlueprintIndex], Vector2.Zero)) : (Building) new Coop(this.blueprints[this.currentBlueprintIndex], Vector2.Zero);
this.price = this.blueprints[this.currentBlueprintIndex].moneyRequired;
this.ingredients.Clear();
foreach (KeyValuePair<int, int> keyValuePair in this.blueprints[this.currentBlueprintIndex].itemsRequired)
this.ingredients.Add((Item) new StardewValley.Object(keyValuePair.Key, keyValuePair.Value));
this.buildingDescription = this.blueprints[this.currentBlueprintIndex].description;
this.buildingName = this.blueprints[this.currentBlueprintIndex].displayName;
}
public override void performHoverAction(int x, int y)
{
this.cancelButton.tryHover(x, y);
base.performHoverAction(x, y);
if (!this.onFarm)
{
this.backButton.tryHover(x, y, 1f);
this.forwardButton.tryHover(x, y, 1f);
this.okButton.tryHover(x, y);
this.demolishButton.tryHover(x, y);
this.moveButton.tryHover(x, y);
this.paintButton.tryHover(x, y);
if (this.CurrentBlueprint.isUpgrade() && this.upgradeIcon.containsPoint(x, y))
this.hoverText = Game1.content.LoadString("Strings\\UI:Carpenter_Upgrade", (object) new BluePrint(this.CurrentBlueprint.nameOfBuildingToUpgrade).displayName);
else if (this.demolishButton.containsPoint(x, y) && this.CanDemolishThis(this.CurrentBlueprint))
this.hoverText = Game1.content.LoadString("Strings\\UI:Carpenter_Demolish");
else if (this.moveButton.containsPoint(x, y))
this.hoverText = Game1.content.LoadString("Strings\\UI:Carpenter_MoveBuildings");
else if (this.okButton.containsPoint(x, y) && this.CurrentBlueprint.doesFarmerHaveEnoughResourcesToBuild())
this.hoverText = Game1.content.LoadString("Strings\\UI:Carpenter_Build");
else if (this.paintButton.containsPoint(x, y))
this.hoverText = this.paintButton.name;
else
this.hoverText = "";
}
else
{
if (!this.upgrading && !this.demolishing && !this.moving && !this.painting || this.freeze)
return;
Farm farm = Game1.getFarm();
Vector2 vector2 = new Vector2((float) ((Game1.viewport.X + Game1.getOldMouseX(false)) / 64), (float) ((Game1.viewport.Y + Game1.getOldMouseY(false)) / 64));
if (this.painting && farm.GetHouseRect().Contains(Utility.Vector2ToPoint(vector2)) && this.HasPermissionsToPaint((Building) null) && this.CanPaintHouse())
farm.frameHouseColor = new Color?(Color.Lime);
foreach (Building building in ((BuildableGameLocation) Game1.getLocationFromName("Farm")).buildings)
building.color.Value = Color.White;
Building building1 = ((BuildableGameLocation) Game1.getLocationFromName("Farm")).getBuildingAt(vector2) ?? ((BuildableGameLocation) Game1.getLocationFromName("Farm")).getBuildingAt(new Vector2((float) ((Game1.viewport.X + Game1.getOldMouseX(false)) / 64), (float) ((Game1.viewport.Y + Game1.getOldMouseY(false) + 128) / 64))) ?? ((BuildableGameLocation) Game1.getLocationFromName("Farm")).getBuildingAt(new Vector2((float) ((Game1.viewport.X + Game1.getOldMouseX(false)) / 64), (float) ((Game1.viewport.Y + Game1.getOldMouseY(false) + 192) / 64)));
if (this.upgrading)
{
if (building1 != null && this.CurrentBlueprint.nameOfBuildingToUpgrade != null && this.CurrentBlueprint.nameOfBuildingToUpgrade.Equals((string) (NetFieldBase<string, NetString>) building1.buildingType))
{
building1.color.Value = Color.Lime * 0.8f;
}
else
{
if (building1 == null)
return;
building1.color.Value = Color.Red * 0.8f;
}
}
else if (this.demolishing)
{
if (building1 == null || !this.hasPermissionsToDemolish(building1) || !this.CanDemolishThis(building1))
return;
building1.color.Value = Color.Red * 0.8f;
}
else if (this.moving)
{
if (building1 == null || !this.hasPermissionsToMove(building1))
return;
building1.color.Value = Color.Lime * 0.8f;
}
else
{
if (!this.painting || building1 == null || !building1.CanBePainted() || !this.HasPermissionsToPaint(building1))
return;
building1.color.Value = Color.Lime * 0.8f;
}
}
}
public bool hasPermissionsToDemolish(Building b) => Game1.IsMasterGame && this.CanDemolishThis(b);
public bool CanPaintHouse() => Game1.MasterPlayer.HouseUpgradeLevel >= 2;
public bool HasPermissionsToPaint(Building b)
{
if (b == null)
return Game1.player.UniqueMultiplayerID == Game1.MasterPlayer.UniqueMultiplayerID || Game1.player.spouse == Game1.MasterPlayer.UniqueMultiplayerID.ToString();
if (!b.isCabin || !(b.indoors.Value is Cabin))
return true;
Farmer owner = (b.indoors.Value as Cabin).owner;
return Game1.player.UniqueMultiplayerID == owner.UniqueMultiplayerID || Game1.player.spouse == owner.UniqueMultiplayerID.ToString();
}
public bool hasPermissionsToMove(Building b) => (Game1.getFarm().greenhouseUnlocked.Value || !(b is GreenhouseBuilding)) && (Game1.IsMasterGame || Game1.player.team.farmhandsCanMoveBuildings.Value == FarmerTeam.RemoteBuildingPermissions.On || Game1.player.team.farmhandsCanMoveBuildings.Value == FarmerTeam.RemoteBuildingPermissions.OwnedBuildings && b.hasCarpenterPermissions());
public override void receiveGamePadButton(Buttons b)
{
base.receiveGamePadButton(b);
if (!this.onFarm && b == Buttons.LeftTrigger)
{
--this.currentBlueprintIndex;
if (this.currentBlueprintIndex < 0)
this.currentBlueprintIndex = this.blueprints.Count - 1;
this.setNewActiveBlueprint();
Game1.playSound("shwip");
}
if (this.onFarm || b != Buttons.RightTrigger)
return;
this.currentBlueprintIndex = (this.currentBlueprintIndex + 1) % this.blueprints.Count;
this.setNewActiveBlueprint();
Game1.playSound("shwip");
}
public override void receiveKeyPress(Keys key)
{
if (this.freeze)
return;
if (!this.onFarm)
base.receiveKeyPress(key);
if (Game1.IsFading() || !this.onFarm)
return;
if (Game1.options.doesInputListContain(Game1.options.menuButton, key) && this.readyToClose() && Game1.locationRequest == null)
{
this.returnToCarpentryMenu();
}
else
{
if (Game1.options.SnappyMenus)
return;
if (Game1.options.doesInputListContain(Game1.options.moveDownButton, key))
Game1.panScreen(0, 4);
else if (Game1.options.doesInputListContain(Game1.options.moveRightButton, key))
Game1.panScreen(4, 0);
else if (Game1.options.doesInputListContain(Game1.options.moveUpButton, key))
{
Game1.panScreen(0, -4);
}
else
{
if (!Game1.options.doesInputListContain(Game1.options.moveLeftButton, key))
return;
Game1.panScreen(-4, 0);
}
}
}
public override void update(GameTime time)
{
base.update(time);
if (!this.onFarm || Game1.IsFading())
return;
int num1 = Game1.getOldMouseX(false) + Game1.viewport.X;
int num2 = Game1.getOldMouseY(false) + Game1.viewport.Y;
if (num1 - Game1.viewport.X < 64)
Game1.panScreen(-8, 0);
else if (num1 - (Game1.viewport.X + Game1.viewport.Width) >= (int) sbyte.MinValue)
Game1.panScreen(8, 0);
if (num2 - Game1.viewport.Y < 64)
Game1.panScreen(0, -8);
else if (num2 - (Game1.viewport.Y + Game1.viewport.Height) >= -64)
Game1.panScreen(0, 8);
foreach (Keys pressedKey in Game1.oldKBState.GetPressedKeys())
this.receiveKeyPress(pressedKey);
if (Game1.IsMultiplayer)
return;
Farm farm = Game1.getFarm();
foreach (Character character in farm.animals.Values)
character.MovePosition(Game1.currentGameTime, Game1.viewport, (GameLocation) farm);
}
public override void receiveLeftClick(int x, int y, bool playSound = true)
{
if (this.freeze)
return;
if (!this.onFarm)
base.receiveLeftClick(x, y, playSound);
if (this.cancelButton.containsPoint(x, y))
{
if (!this.onFarm)
{
this.exitThisMenu();
Game1.player.forceCanMove();
Game1.playSound("bigDeSelect");
}
else
{
if (this.moving && this.buildingToMove != null)
{
Game1.playSound("cancel");
return;
}
this.returnToCarpentryMenu();
Game1.playSound("smallSelect");
return;
}
}
if (!this.onFarm && this.backButton.containsPoint(x, y))
{
--this.currentBlueprintIndex;
if (this.currentBlueprintIndex < 0)
this.currentBlueprintIndex = this.blueprints.Count - 1;
this.setNewActiveBlueprint();
Game1.playSound("shwip");
this.backButton.scale = this.backButton.baseScale;
}
if (!this.onFarm && this.forwardButton.containsPoint(x, y))
{
this.currentBlueprintIndex = (this.currentBlueprintIndex + 1) % this.blueprints.Count;
this.setNewActiveBlueprint();
this.backButton.scale = this.backButton.baseScale;
Game1.playSound("shwip");
}
if (!this.onFarm && this.demolishButton.containsPoint(x, y) && this.demolishButton.visible && this.CanDemolishThis(this.blueprints[this.currentBlueprintIndex]))
{
Game1.globalFadeToBlack(new Game1.afterFadeFunction(this.setUpForBuildingPlacement));
Game1.playSound("smallSelect");
this.onFarm = true;
this.demolishing = true;
}
if (!this.onFarm && this.moveButton.containsPoint(x, y) && this.moveButton.visible)
{
Game1.globalFadeToBlack(new Game1.afterFadeFunction(this.setUpForBuildingPlacement));
Game1.playSound("smallSelect");
this.onFarm = true;
this.moving = true;
}
if (!this.onFarm && this.paintButton.containsPoint(x, y) && this.paintButton.visible)
{
Game1.globalFadeToBlack(new Game1.afterFadeFunction(this.setUpForBuildingPlacement));
Game1.playSound("smallSelect");
this.onFarm = true;
this.painting = true;
}
if (this.okButton.containsPoint(x, y) && !this.onFarm && this.price >= 0 && Game1.player.Money >= this.price && this.blueprints[this.currentBlueprintIndex].doesFarmerHaveEnoughResourcesToBuild())
{
Game1.globalFadeToBlack(new Game1.afterFadeFunction(this.setUpForBuildingPlacement));
Game1.playSound("smallSelect");
this.onFarm = true;
}
if (!this.onFarm || this.freeze || Game1.IsFading())
return;
if (this.demolishing)
{
Farm farm = Game1.getLocationFromName("Farm") as Farm;
Building destroyed = farm.getBuildingAt(new Vector2((float) ((Game1.viewport.X + Game1.getOldMouseX(false)) / 64), (float) ((Game1.viewport.Y + Game1.getOldMouseY(false)) / 64)));
Action buildingLockFailed = (Action) (() =>
{
if (!this.demolishing)
return;
Game1.addHUDMessage(new HUDMessage(Game1.content.LoadString("Strings\\UI:Carpenter_CantDemolish_LockFailed"), Color.Red, 3500f));
});
Action continueDemolish = (Action) (() =>
{
if (!this.demolishing || destroyed == null || !farm.buildings.Contains(destroyed))
return;
if ((int) (NetFieldBase<int, NetInt>) destroyed.daysOfConstructionLeft > 0 || (int) (NetFieldBase<int, NetInt>) destroyed.daysUntilUpgrade > 0)
Game1.addHUDMessage(new HUDMessage(Game1.content.LoadString("Strings\\UI:Carpenter_CantDemolish_DuringConstruction"), Color.Red, 3500f));
else if (destroyed.indoors.Value != null && destroyed.indoors.Value is AnimalHouse && (destroyed.indoors.Value as AnimalHouse).animalsThatLiveHere.Count > 0)
Game1.addHUDMessage(new HUDMessage(Game1.content.LoadString("Strings\\UI:Carpenter_CantDemolish_AnimalsHere"), Color.Red, 3500f));
else if (destroyed.indoors.Value != null && destroyed.indoors.Value.farmers.Any())
{
Game1.addHUDMessage(new HUDMessage(Game1.content.LoadString("Strings\\UI:Carpenter_CantDemolish_PlayerHere"), Color.Red, 3500f));
}
else
{
if (destroyed.indoors.Value != null && destroyed.indoors.Value is Cabin)
{
foreach (Farmer allFarmer in Game1.getAllFarmers())
{
if (allFarmer.currentLocation != null && allFarmer.currentLocation.Name == (destroyed.indoors.Value as Cabin).GetCellarName())
{
Game1.addHUDMessage(new HUDMessage(Game1.content.LoadString("Strings\\UI:Carpenter_CantDemolish_PlayerHere"), Color.Red, 3500f));
return;
}
}
}
if (destroyed.indoors.Value is Cabin && (destroyed.indoors.Value as Cabin).farmhand.Value.isActive())
{
Game1.addHUDMessage(new HUDMessage(Game1.content.LoadString("Strings\\UI:Carpenter_CantDemolish_FarmhandOnline"), Color.Red, 3500f));
}
else
{
destroyed.BeforeDemolish();
Chest chest = (Chest) null;
if (destroyed.indoors.Value is Cabin)
{
List<Item> list = (destroyed.indoors.Value as Cabin).demolish();
if (list.Count > 0)
{
chest = new Chest(true);
chest.fixLidFrame();
chest.items.Set((IList<Item>) list);
}
}
if (!farm.destroyStructure(destroyed))
return;
int tileY = (int) (NetFieldBase<int, NetInt>) destroyed.tileY;
int tilesHigh = (int) (NetFieldBase<int, NetInt>) destroyed.tilesHigh;
Game1.flashAlpha = 1f;
destroyed.showDestroyedAnimation((GameLocation) Game1.getFarm());
Game1.playSound("explosion");
Utility.spreadAnimalsAround(destroyed, farm);
DelayedAction.functionAfterDelay(new DelayedAction.delayedBehavior(this.returnToCarpentryMenu), 1500);
this.freeze = true;
if (chest == null)
return;
farm.objects[new Vector2((float) ((int) (NetFieldBase<int, NetInt>) destroyed.tileX + (int) (NetFieldBase<int, NetInt>) destroyed.tilesWide / 2), (float) ((int) (NetFieldBase<int, NetInt>) destroyed.tileY + (int) (NetFieldBase<int, NetInt>) destroyed.tilesHigh / 2))] = (StardewValley.Object) chest;
}
}
});
if (destroyed != null)
{
if (destroyed.indoors.Value != null && destroyed.indoors.Value is Cabin && !Game1.IsMasterGame)
{
Game1.addHUDMessage(new HUDMessage(Game1.content.LoadString("Strings\\UI:Carpenter_CantDemolish_LockFailed"), Color.Red, 3500f));
destroyed = (Building) null;
return;
}
if (!this.CanDemolishThis(destroyed))
{
destroyed = (Building) null;
return;
}
if (!Game1.IsMasterGame && !this.hasPermissionsToDemolish(destroyed))
{
destroyed = (Building) null;
return;
}
}
if (destroyed != null && destroyed.indoors.Value is Cabin)
{
Cabin cabin = destroyed.indoors.Value as Cabin;
if (cabin.farmhand.Value != null && (bool) (NetFieldBase<bool, NetBool>) cabin.farmhand.Value.isCustomized)
{
Game1.currentLocation.createQuestionDialogue(Game1.content.LoadString("Strings\\UI:Carpenter_DemolishCabinConfirm", (object) cabin.farmhand.Value.Name), Game1.currentLocation.createYesNoResponses(), (GameLocation.afterQuestionBehavior) ((f, answer) =>
{
if (answer == "Yes")
{
Game1.activeClickableMenu = (IClickableMenu) this;
Game1.player.team.demolishLock.RequestLock(continueDemolish, buildingLockFailed);
}
else
DelayedAction.functionAfterDelay(new DelayedAction.delayedBehavior(this.returnToCarpentryMenu), 500);
}));
return;
}
}
if (destroyed == null)
return;
Game1.player.team.demolishLock.RequestLock(continueDemolish, buildingLockFailed);
}
else if (this.upgrading)
{
Building buildingAt = ((BuildableGameLocation) Game1.getLocationFromName("Farm")).getBuildingAt(new Vector2((float) ((Game1.viewport.X + Game1.getOldMouseX(false)) / 64), (float) ((Game1.viewport.Y + Game1.getOldMouseY(false)) / 64)));
if (buildingAt != null && this.CurrentBlueprint.name != null && buildingAt.buildingType.Equals((object) this.CurrentBlueprint.nameOfBuildingToUpgrade))
{
this.CurrentBlueprint.consumeResources();
buildingAt.daysUntilUpgrade.Value = 2;
buildingAt.showUpgradeAnimation((GameLocation) Game1.getFarm());
Game1.playSound("axe");
DelayedAction.functionAfterDelay(new DelayedAction.delayedBehavior(this.returnToCarpentryMenuAfterSuccessfulBuild), 1500);
this.freeze = true;
Game1.multiplayer.globalChatInfoMessage("BuildingBuild", Game1.player.Name, Utility.AOrAn(this.CurrentBlueprint.displayName), this.CurrentBlueprint.displayName, (string) (NetFieldBase<string, NetString>) Game1.player.farmName);
}
else
{
if (buildingAt == null)
return;
Game1.addHUDMessage(new HUDMessage(Game1.content.LoadString("Strings\\UI:Carpenter_CantUpgrade_BuildingType"), Color.Red, 3500f));
}
}
else if (this.painting)
{
Farm farm_location = Game1.getFarm();
Vector2 vector2 = new Vector2((float) ((Game1.viewport.X + Game1.getMouseX(false)) / 64), (float) ((Game1.viewport.Y + Game1.getMouseY(false)) / 64));
Building buildingAt = farm_location.getBuildingAt(vector2);
if (buildingAt != null)
{
if (!buildingAt.CanBePainted())
Game1.addHUDMessage(new HUDMessage(Game1.content.LoadString("Strings\\UI:Carpenter_CannotPaint"), Color.Red, 3500f));
else if (!this.HasPermissionsToPaint(buildingAt))
{
Game1.addHUDMessage(new HUDMessage(Game1.content.LoadString("Strings\\UI:Carpenter_CannotPaint_Permission"), Color.Red, 3500f));
}
else
{
buildingAt.color.Value = Color.White;
this.SetChildMenu((IClickableMenu) new BuildingPaintMenu(buildingAt));
}
}
else
{
if (!farm_location.GetHouseRect().Contains(Utility.Vector2ToPoint(vector2)))
return;
if (!this.CanPaintHouse())
Game1.addHUDMessage(new HUDMessage(Game1.content.LoadString("Strings\\UI:Carpenter_CannotPaint"), Color.Red, 3500f));
else if (!this.HasPermissionsToPaint((Building) null))
Game1.addHUDMessage(new HUDMessage(Game1.content.LoadString("Strings\\UI:Carpenter_CannotPaint_Permission"), Color.Red, 3500f));
else
this.SetChildMenu((IClickableMenu) new BuildingPaintMenu("House", (Func<Texture2D>) (() => farm_location.paintedHouseTexture != null ? farm_location.paintedHouseTexture : Farm.houseTextures), farm_location.houseSource.Value, farm_location.housePaintColor.Value));
}
}
else if (this.moving)
{
if (this.buildingToMove == null)
{
this.buildingToMove = ((BuildableGameLocation) Game1.getLocationFromName("Farm")).getBuildingAt(new Vector2((float) ((Game1.viewport.X + Game1.getMouseX(false)) / 64), (float) ((Game1.viewport.Y + Game1.getMouseY(false)) / 64)));
if (this.buildingToMove == null)
return;
if ((int) (NetFieldBase<int, NetInt>) this.buildingToMove.daysOfConstructionLeft > 0)
this.buildingToMove = (Building) null;
else if (!this.hasPermissionsToMove(this.buildingToMove))
{
this.buildingToMove = (Building) null;
}
else
{
this.buildingToMove.isMoving = true;
Game1.playSound("axchop");
}
}
else if (((BuildableGameLocation) Game1.getLocationFromName("Farm")).buildStructure(this.buildingToMove, new Vector2((float) ((Game1.viewport.X + Game1.getMouseX(false)) / 64), (float) ((Game1.viewport.Y + Game1.getMouseY(false)) / 64)), Game1.player))
{
this.buildingToMove.isMoving = false;
if (this.buildingToMove is ShippingBin)
(this.buildingToMove as ShippingBin).initLid();
if (this.buildingToMove is GreenhouseBuilding)
Game1.getFarm().greenhouseMoved.Value = true;
this.buildingToMove.performActionOnBuildingPlacement();
this.buildingToMove = (Building) null;
Game1.playSound("axchop");
DelayedAction.playSoundAfterDelay("dirtyHit", 50);
DelayedAction.playSoundAfterDelay("dirtyHit", 150);
}
else
Game1.playSound("cancel");
}
else
Game1.player.team.buildLock.RequestLock((Action) (() =>
{
if (this.onFarm && Game1.locationRequest == null)
{
if (this.tryToBuild())
{
this.CurrentBlueprint.consumeResources();
DelayedAction.functionAfterDelay(new DelayedAction.delayedBehavior(this.returnToCarpentryMenuAfterSuccessfulBuild), 2000);
this.freeze = true;
}
else
Game1.addHUDMessage(new HUDMessage(Game1.content.LoadString("Strings\\UI:Carpenter_CantBuild"), Color.Red, 3500f));
}
Game1.player.team.buildLock.ReleaseLock();
}));
}
public bool tryToBuild() => ((BuildableGameLocation) Game1.getLocationFromName("Farm")).buildStructure(this.CurrentBlueprint, new Vector2((float) ((Game1.viewport.X + Game1.getOldMouseX(false)) / 64), (float) ((Game1.viewport.Y + Game1.getOldMouseY(false)) / 64)), Game1.player, this.magicalConstruction);
public void returnToCarpentryMenu()
{
LocationRequest locationRequest = Game1.getLocationRequest(this.magicalConstruction ? "WizardHouse" : "ScienceHouse");
locationRequest.OnWarp += (LocationRequest.Callback) (() =>
{
this.onFarm = false;
Game1.player.viewingLocation.Value = (string) null;
this.resetBounds();
this.upgrading = false;
this.moving = false;
this.painting = false;
this.buildingToMove = (Building) null;
this.freeze = false;
Game1.displayHUD = true;
Game1.viewportFreeze = false;
Game1.viewport.Location = new Location(320, 1536);
this.drawBG = true;
this.demolishing = false;
Game1.displayFarmer = true;
if (!Game1.options.SnappyMenus)
return;
this.populateClickableComponentList();
this.snapToDefaultClickableComponent();
});
Game1.warpFarmer(locationRequest, Game1.player.getTileX(), Game1.player.getTileY(), (int) Game1.player.facingDirection);
}
public void returnToCarpentryMenuAfterSuccessfulBuild()
{
LocationRequest locationRequest = Game1.getLocationRequest(this.magicalConstruction ? "WizardHouse" : "ScienceHouse");
locationRequest.OnWarp += (LocationRequest.Callback) (() =>
{
Game1.displayHUD = true;
Game1.player.viewingLocation.Value = (string) null;
Game1.viewportFreeze = false;
Game1.viewport.Location = new Location(320, 1536);
this.freeze = true;
Game1.displayFarmer = true;
this.robinConstructionMessage();
});
Game1.warpFarmer(locationRequest, Game1.player.getTileX(), Game1.player.getTileY(), (int) Game1.player.facingDirection);
}
public void robinConstructionMessage()
{
this.exitThisMenu();
Game1.player.forceCanMove();
if (this.magicalConstruction)
return;
string str = "Data\\ExtraDialogue:Robin_" + (this.upgrading ? "Upgrade" : "New") + "Construction";
if (Utility.isFestivalDay(Game1.dayOfMonth + 1, Game1.currentSeason))
str += "_Festival";
if (this.CurrentBlueprint.daysToConstruct <= 0)
{
Game1.drawDialogue(Game1.getCharacterFromName("Robin"), Game1.content.LoadString("Data\\ExtraDialogue:Robin_Instant", LocalizedContentManager.CurrentLanguageCode == LocalizedContentManager.LanguageCode.de ? (object) this.CurrentBlueprint.displayName : (object) this.CurrentBlueprint.displayName.ToLower()));
}
else
{
NPC characterFromName = Game1.getCharacterFromName("Robin");
LocalizedContentManager content = Game1.content;
string path = str;
string sub1 = LocalizedContentManager.CurrentLanguageCode == LocalizedContentManager.LanguageCode.de ? this.CurrentBlueprint.displayName : this.CurrentBlueprint.displayName.ToLower();
string sub2;
switch (LocalizedContentManager.CurrentLanguageCode)
{
case LocalizedContentManager.LanguageCode.pt:
case LocalizedContentManager.LanguageCode.es:
case LocalizedContentManager.LanguageCode.it:
sub2 = ((IEnumerable<string>) this.CurrentBlueprint.displayName.ToLower().Split(' ')).First<string>();
break;
case LocalizedContentManager.LanguageCode.de:
sub2 = ((IEnumerable<string>) ((IEnumerable<string>) this.CurrentBlueprint.displayName.Split(' ')).Last<string>().Split('-')).Last<string>();
break;
default:
sub2 = ((IEnumerable<string>) this.CurrentBlueprint.displayName.ToLower().Split(' ')).Last<string>();
break;
}
string dialogue = content.LoadString(path, (object) sub1, (object) sub2);
Game1.drawDialogue(characterFromName, dialogue);
}
}
public override bool overrideSnappyMenuCursorMovementBan() => this.onFarm;
public void setUpForBuildingPlacement()
{
Game1.currentLocation.cleanupBeforePlayerExit();
this.hoverText = "";
Game1.currentLocation = Game1.getLocationFromName("Farm");
Game1.player.viewingLocation.Value = "Farm";
Game1.currentLocation.resetForPlayerEntry();
Game1.globalFadeToClear();
this.onFarm = true;
this.cancelButton.bounds.X = Game1.uiViewport.Width - 128;
this.cancelButton.bounds.Y = Game1.uiViewport.Height - 128;
Game1.displayHUD = false;
Game1.viewportFreeze = true;
Game1.viewport.Location = new Location(3136, 320);
Game1.panScreen(0, 0);
this.drawBG = false;
this.freeze = false;
Game1.displayFarmer = false;
if (this.demolishing || this.CurrentBlueprint.nameOfBuildingToUpgrade == null || this.CurrentBlueprint.nameOfBuildingToUpgrade.Length <= 0 || this.moving || this.painting)
return;
this.upgrading = true;
}
public override void gameWindowSizeChanged(Microsoft.Xna.Framework.Rectangle oldBounds, Microsoft.Xna.Framework.Rectangle newBounds) => this.resetBounds();
public virtual bool CanDemolishThis(Building building)
{
if (building == null)
return false;
if (this._demolishCheckBlueprint == null || this._demolishCheckBlueprint.name != building.buildingType.Value)
this._demolishCheckBlueprint = new BluePrint((string) (NetFieldBase<string, NetString>) building.buildingType);
return this._demolishCheckBlueprint == null || this.CanDemolishThis(this._demolishCheckBlueprint);
}
public virtual bool CanDemolishThis(BluePrint blueprint)
{
if (blueprint.moneyRequired < 0)
return false;
if (blueprint.name == "Shipping Bin")
{
int num = 0;
foreach (Building building in Game1.getFarm().buildings)
{
if (building is ShippingBin)
++num;
if (num > 1)
break;
}
if (num <= 1)
return false;
}
return true;
}
public override void draw(SpriteBatch b)
{
if (this.drawBG)
b.Draw(Game1.fadeToBlackRect, Game1.graphics.GraphicsDevice.Viewport.Bounds, Color.Black * 0.5f);
if (Game1.IsFading() || this.freeze)
return;
if (!this.onFarm)
{
base.draw(b);
IClickableMenu.drawTextureBox(b, this.xPositionOnScreen - 96, this.yPositionOnScreen - 16, this.maxWidthOfBuildingViewer + 64, this.maxHeightOfBuildingViewer + 64, this.magicalConstruction ? Color.RoyalBlue : Color.White);
this.currentBuilding.drawInMenu(b, this.xPositionOnScreen + this.maxWidthOfBuildingViewer / 2 - (int) (NetFieldBase<int, NetInt>) this.currentBuilding.tilesWide * 64 / 2 - 64, this.yPositionOnScreen + this.maxHeightOfBuildingViewer / 2 - this.currentBuilding.getSourceRectForMenu().Height * 4 / 2);
if (this.CurrentBlueprint.isUpgrade())
this.upgradeIcon.draw(b);
string s = " Deluxe Barn ";
if (SpriteText.getWidthOfString(this.buildingName) >= SpriteText.getWidthOfString(s))
s = this.buildingName + " ";
SpriteText.drawStringWithScrollCenteredAt(b, this.buildingName, this.xPositionOnScreen + this.maxWidthOfBuildingViewer - IClickableMenu.spaceToClearSideBorder - 16 + 64 + (this.width - (this.maxWidthOfBuildingViewer + 128)) / 2, this.yPositionOnScreen, SpriteText.getWidthOfString(s));
int width;
switch (LocalizedContentManager.CurrentLanguageCode)
{
case LocalizedContentManager.LanguageCode.es:
width = this.maxWidthOfDescription + 64 + (this.CurrentBlueprint?.name == "Deluxe Barn" ? 96 : 0);
break;
case LocalizedContentManager.LanguageCode.fr:
width = this.maxWidthOfDescription + 96 + (this.CurrentBlueprint?.name == "Slime Hutch" || this.CurrentBlueprint?.name == "Deluxe Coop" || this.CurrentBlueprint?.name == "Deluxe Barn" ? 72 : 0);
break;
case LocalizedContentManager.LanguageCode.ko:
width = this.maxWidthOfDescription + 96 + (this.CurrentBlueprint?.name == "Slime Hutch" ? 64 : (this.CurrentBlueprint?.name == "Deluxe Coop" ? 96 : (this.CurrentBlueprint?.name == "Deluxe Barn" ? 112 : (this.CurrentBlueprint?.name == "Big Barn" ? 64 : 0))));
break;
case LocalizedContentManager.LanguageCode.it:
width = this.maxWidthOfDescription + 96;
break;
default:
width = this.maxWidthOfDescription + 64;
break;
}
IClickableMenu.drawTextureBox(b, this.xPositionOnScreen + this.maxWidthOfBuildingViewer - 16, this.yPositionOnScreen + 80, width, this.maxHeightOfBuildingViewer - 32, this.magicalConstruction ? Color.RoyalBlue : Color.White);
if (this.magicalConstruction)
{
Utility.drawTextWithShadow(b, Game1.parseText(this.buildingDescription, Game1.dialogueFont, width - 32), Game1.dialogueFont, new Vector2((float) (this.xPositionOnScreen + this.maxWidthOfBuildingViewer - 4), (float) (this.yPositionOnScreen + 80 + 16 + 4)), Game1.textColor * 0.25f, shadowIntensity: 0.0f);
Utility.drawTextWithShadow(b, Game1.parseText(this.buildingDescription, Game1.dialogueFont, width - 32), Game1.dialogueFont, new Vector2((float) (this.xPositionOnScreen + this.maxWidthOfBuildingViewer - 1), (float) (this.yPositionOnScreen + 80 + 16 + 4)), Game1.textColor * 0.25f, shadowIntensity: 0.0f);
}
Utility.drawTextWithShadow(b, Game1.parseText(this.buildingDescription, Game1.dialogueFont, width - 32), Game1.dialogueFont, new Vector2((float) (this.xPositionOnScreen + this.maxWidthOfBuildingViewer), (float) (this.yPositionOnScreen + 80 + 16)), this.magicalConstruction ? Color.PaleGoldenrod : Game1.textColor, shadowIntensity: (this.magicalConstruction ? 0.0f : 0.75f));
Vector2 location = new Vector2((float) (this.xPositionOnScreen + this.maxWidthOfBuildingViewer + 16), (float) (this.yPositionOnScreen + 256 + 32));
if (this.ingredients.Count < 3 && (LocalizedContentManager.CurrentLanguageCode == LocalizedContentManager.LanguageCode.fr || LocalizedContentManager.CurrentLanguageCode == LocalizedContentManager.LanguageCode.ko || LocalizedContentManager.CurrentLanguageCode == LocalizedContentManager.LanguageCode.pt))
location.Y += 64f;
if (this.price >= 0)
{
SpriteText.drawString(b, "$", (int) location.X, (int) location.Y);
string numberWithCommas = Utility.getNumberWithCommas(this.price);
if (this.magicalConstruction)
{
Utility.drawTextWithShadow(b, Game1.content.LoadString("Strings\\StringsFromCSFiles:LoadGameMenu.cs.11020", (object) numberWithCommas), Game1.dialogueFont, new Vector2(location.X + 64f, location.Y + 8f), Game1.textColor * 0.5f, shadowIntensity: (this.magicalConstruction ? 0.0f : 0.25f));
Utility.drawTextWithShadow(b, Game1.content.LoadString("Strings\\StringsFromCSFiles:LoadGameMenu.cs.11020", (object) numberWithCommas), Game1.dialogueFont, new Vector2((float) ((double) location.X + 64.0 + 4.0 - 1.0), location.Y + 8f), Game1.textColor * 0.25f, shadowIntensity: (this.magicalConstruction ? 0.0f : 0.25f));
}
Utility.drawTextWithShadow(b, Game1.content.LoadString("Strings\\StringsFromCSFiles:LoadGameMenu.cs.11020", (object) numberWithCommas), Game1.dialogueFont, new Vector2((float) ((double) location.X + 64.0 + 4.0), location.Y + 4f), Game1.player.Money >= this.price ? (this.magicalConstruction ? Color.PaleGoldenrod : Game1.textColor) : Color.Red, shadowIntensity: (this.magicalConstruction ? 0.0f : 0.25f));
}
location.X -= 16f;
location.Y -= 21f;
foreach (Item ingredient in this.ingredients)
{
location.Y += 68f;
ingredient.drawInMenu(b, location, 1f);
bool flag = !(ingredient is StardewValley.Object) || Game1.player.hasItemInInventory((int) (NetFieldBase<int, NetInt>) (ingredient as StardewValley.Object).parentSheetIndex, ingredient.Stack);
if (this.magicalConstruction)
{
Utility.drawTextWithShadow(b, ingredient.DisplayName, Game1.dialogueFont, new Vector2((float) ((double) location.X + 64.0 + 12.0), location.Y + 24f), Game1.textColor * 0.25f, shadowIntensity: (this.magicalConstruction ? 0.0f : 0.25f));
Utility.drawTextWithShadow(b, ingredient.DisplayName, Game1.dialogueFont, new Vector2((float) ((double) location.X + 64.0 + 16.0 - 1.0), location.Y + 24f), Game1.textColor * 0.25f, shadowIntensity: (this.magicalConstruction ? 0.0f : 0.25f));
}
Utility.drawTextWithShadow(b, ingredient.DisplayName, Game1.dialogueFont, new Vector2((float) ((double) location.X + 64.0 + 16.0), location.Y + 20f), flag ? (this.magicalConstruction ? Color.PaleGoldenrod : Game1.textColor) : Color.Red, shadowIntensity: (this.magicalConstruction ? 0.0f : 0.25f));
}
this.backButton.draw(b);
this.forwardButton.draw(b);
this.okButton.draw(b, this.blueprints[this.currentBlueprintIndex].doesFarmerHaveEnoughResourcesToBuild() ? Color.White : Color.Gray * 0.8f, 0.88f);
this.demolishButton.draw(b, this.CanDemolishThis(this.blueprints[this.currentBlueprintIndex]) ? Color.White : Color.Gray * 0.8f, 0.88f);
this.moveButton.draw(b);
this.paintButton.draw(b);
}
else
{
string s = !this.upgrading ? (!this.demolishing ? (!this.painting ? Game1.content.LoadString("Strings\\UI:Carpenter_ChooseLocation") : Game1.content.LoadString("Strings\\UI:Carpenter_SelectBuilding_Paint")) : Game1.content.LoadString("Strings\\UI:Carpenter_SelectBuilding_Demolish")) : Game1.content.LoadString("Strings\\UI:Carpenter_SelectBuilding_Upgrade", (object) new BluePrint(this.CurrentBlueprint.nameOfBuildingToUpgrade).displayName);
SpriteText.drawStringWithScrollBackground(b, s, Game1.uiViewport.Width / 2 - SpriteText.getWidthOfString(s) / 2, 16);
Game1.StartWorldDrawInUI(b);
if (!this.upgrading && !this.demolishing && !this.moving && !this.painting)
{
Vector2 vector2 = new Vector2((float) ((Game1.viewport.X + Game1.getOldMouseX(false)) / 64), (float) ((Game1.viewport.Y + Game1.getOldMouseY(false)) / 64));
for (int y = 0; y < this.CurrentBlueprint.tilesHeight; ++y)
{
for (int x = 0; x < this.CurrentBlueprint.tilesWidth; ++x)
{
int structurePlacementTile = this.CurrentBlueprint.getTileSheetIndexForStructurePlacementTile(x, y);
Vector2 tileLocation = new Vector2(vector2.X + (float) x, vector2.Y + (float) y);
if (!(Game1.currentLocation as BuildableGameLocation).isBuildable(tileLocation))
++structurePlacementTile;
b.Draw(Game1.mouseCursors, Game1.GlobalToLocal(Game1.viewport, tileLocation * 64f), new Microsoft.Xna.Framework.Rectangle?(new Microsoft.Xna.Framework.Rectangle(194 + structurePlacementTile * 16, 388, 16, 16)), Color.White, 0.0f, Vector2.Zero, 4f, SpriteEffects.None, 0.999f);
}
}
foreach (Point additionalPlacementTile in this.CurrentBlueprint.additionalPlacementTiles)
{
int x = additionalPlacementTile.X;
int y = additionalPlacementTile.Y;
int structurePlacementTile = this.CurrentBlueprint.getTileSheetIndexForStructurePlacementTile(x, y);
Vector2 tileLocation = new Vector2(vector2.X + (float) x, vector2.Y + (float) y);
if (!(Game1.currentLocation as BuildableGameLocation).isBuildable(tileLocation))
++structurePlacementTile;
b.Draw(Game1.mouseCursors, Game1.GlobalToLocal(Game1.viewport, tileLocation * 64f), new Microsoft.Xna.Framework.Rectangle?(new Microsoft.Xna.Framework.Rectangle(194 + structurePlacementTile * 16, 388, 16, 16)), Color.White, 0.0f, Vector2.Zero, 4f, SpriteEffects.None, 0.999f);
}
}
else if (!this.painting && this.moving && this.buildingToMove != null)
{
Vector2 vector2_1 = new Vector2((float) ((Game1.viewport.X + Game1.getOldMouseX(false)) / 64), (float) ((Game1.viewport.Y + Game1.getOldMouseY(false)) / 64));
BuildableGameLocation currentLocation = Game1.currentLocation as BuildableGameLocation;
for (int y = 0; y < (int) (NetFieldBase<int, NetInt>) this.buildingToMove.tilesHigh; ++y)
{
for (int x = 0; x < (int) (NetFieldBase<int, NetInt>) this.buildingToMove.tilesWide; ++x)
{
int structurePlacementTile = this.buildingToMove.getTileSheetIndexForStructurePlacementTile(x, y);
Vector2 vector2_2 = new Vector2(vector2_1.X + (float) x, vector2_1.Y + (float) y);
bool flag = currentLocation.buildings.Contains(this.buildingToMove) && this.buildingToMove.occupiesTile(vector2_2);
if (!currentLocation.isBuildable(vector2_2) && !flag)
++structurePlacementTile;
b.Draw(Game1.mouseCursors, Game1.GlobalToLocal(Game1.viewport, vector2_2 * 64f), new Microsoft.Xna.Framework.Rectangle?(new Microsoft.Xna.Framework.Rectangle(194 + structurePlacementTile * 16, 388, 16, 16)), Color.White, 0.0f, Vector2.Zero, 4f, SpriteEffects.None, 0.999f);
}
}
foreach (Point additionalPlacementTile in this.buildingToMove.additionalPlacementTiles)
{
int x = additionalPlacementTile.X;
int y = additionalPlacementTile.Y;
int structurePlacementTile = this.buildingToMove.getTileSheetIndexForStructurePlacementTile(x, y);
Vector2 vector2_3 = new Vector2(vector2_1.X + (float) x, vector2_1.Y + (float) y);
bool flag = currentLocation.buildings.Contains(this.buildingToMove) && this.buildingToMove.occupiesTile(vector2_3);
if (!currentLocation.isBuildable(vector2_3) && !flag)
++structurePlacementTile;
b.Draw(Game1.mouseCursors, Game1.GlobalToLocal(Game1.viewport, vector2_3 * 64f), new Microsoft.Xna.Framework.Rectangle?(new Microsoft.Xna.Framework.Rectangle(194 + structurePlacementTile * 16, 388, 16, 16)), Color.White, 0.0f, Vector2.Zero, 4f, SpriteEffects.None, 0.999f);
}
}
Game1.EndWorldDrawInUI(b);
}
this.cancelButton.draw(b);
this.drawMouse(b);
if (this.hoverText.Length <= 0)
return;
IClickableMenu.drawHoverText(b, this.hoverText, Game1.dialogueFont);
}
public override void receiveRightClick(int x, int y, bool playSound = true)
{
}
}
}
| 0 | 0.924012 | 1 | 0.924012 | game-dev | MEDIA | 0.698106 | game-dev,desktop-app | 0.971647 | 1 | 0.971647 |
11011010/BFA-Frankenstein-Core | 17,215 | src/server/scripts/BrokenIsles/HallsOfValor/boss_hyrja.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 "AreaTrigger.h"
#include "AreaTriggerAI.h"
#include "GameObject.h"
#include "ScriptMgr.h"
#include "halls_of_valor.h"
enum hyrjaSpells
{
SPELL_MYSTIC_EMPOWEREMENT_THUNDER_VISUAL = 192008,
SPELL_MYSTIC_EMPOWEREMENT_THUNDER = 192132,
SPELL_MYSTIC_EMPOWEREMENT_HOLY_VISUAL = 191924,
SPELL_MYSTIC_EMPOWEREMENT_HOLY = 192133,
};
enum hyrjaEvents
{
EVENT_MYSTIC_EMPOWEREMENT,
EVENT_CHOOSE_SPECIAL,
};
enum olmyrSpells
{
SPELL_SANCTIFY = 192307,
SPELL_SANCTIFY_DAMAGE = 192206,
SPELL_SANCTIFY_AREATRIGGER = 192163,
SPELL_SEARING_LIGHT = 192288,
SPELL_OLMYR_SPAWN_COSMETIC = 191899,
SPELL_SHIELD_OF_LIGHT = 192018,
SPELL_EXPEL_LIGHT = 192048,
SPELL_EXPEL_LIGHT_EXPLODE = 192067,
SPELL_EYE_OF_THE_STORM = 200901,
SPELL_EYE_OF_THE_STORM_2 = 200902,
SPELL_EYE_OF_THE_STORM_ACTIVE = 200906,
SPELL_EYE_OF_THE_STORM_DMG = 200682,
SPELL_SOLSTEN_SPAWN_COSMETIC = 192147,
SPELL_ARCING_BOLT = 191976,
SPELL_EYE_OF_THE_STORM_ABSORB = 203963,
};
enum olmyrEvents
{
EVENT_SANCTIFY,
EVENT_SEARING_LIGHT,
EVENT_SHIELD_OF_LIGHT,
EVENT_EYE_OF_THE_STORM,
EVENT_ARCING_BOLT,
EVENT_STORM,
};
enum hyrjaSays
{
SAY_COMBAT = 0,
SAY_KILLED = 1,
SAY_SANCTIFY = 2,
SAY_STORM = 3,
SAY_DIED = 4,
};
struct boss_hyrja : public BossAI
{
boss_hyrja(Creature* creature) : BossAI(creature, DATA_HYRJA)
{
me->SetReactState(REACT_DEFENSIVE);
me->SetCanFly(false);
me->AddUnitFlag(UNIT_FLAG_NON_ATTACKABLE);
me->AddUnitFlag(UNIT_FLAG_NOT_SELECTABLE);
}
std::list<Creature*> creatureList;
bool inCombat = false;
uint8 count;
void Reset() override
{
_Reset();
count = 0;
}
void EnterCombat(Unit* /*who*/) override
{
_EnterCombat();
me->GetMotionMaster()->MoveJump(3148.366f, 325.743f, 655.16f, 0.80f, 15.0f, 15.0f);
events.ScheduleEvent(EVENT_MYSTIC_EMPOWEREMENT, 5 * IN_MILLISECONDS);
events.ScheduleEvent(EVENT_CHOOSE_SPECIAL, 10 * IN_MILLISECONDS);
events.ScheduleEvent(EVENT_SHIELD_OF_LIGHT, 16 * IN_MILLISECONDS);
}
void JustDied(Unit* /*killer*/) override
{
_JustDied();
if (GameObject* go = instance->GetGameObject(GOB_DOOR_ODYN_PASSAGE))
{
go->SetLootState(GO_READY);
go->UseDoorOrButton(3000000, false);
go->setActive(true);
}
}
void DoAction(int32 action) override
{
if (action == ACTION_CAN_JOIN_COMBAT)
CanJoinCombat();
}
void CanJoinCombat()
{
if (inCombat)
return;
uint8 count1 = 0;
if (instance->GetCreature(NPC_OLMYR_GHOST))
count1++;
else if (Creature* olmyr = instance->GetCreature(NPC_OLMYR_THE_ENLIGHTENED))
{
if (Creature* olmyrghost = me->SummonCreature(NPC_OLMYR_GHOST, olmyr->GetPositionX(), olmyr->GetPositionY(), olmyr->GetPositionZ(), olmyr->GetOrientation(), TEMPSUMMON_MANUAL_DESPAWN))
olmyrghost->CastSpell(olmyrghost, SPELL_OLMYR_SPAWN_COSMETIC, true);
count1++;
}
if (instance->GetCreature(NPC_SOLSTEN_GHOST))
count1++;
else if (Creature* solsten = instance->GetCreature(NPC_SOLSTEN))
{
if (Creature* solstenghost = me->SummonCreature(NPC_SOLSTEN_GHOST, solsten->GetPositionX(), solsten->GetPositionY(), solsten->GetPositionZ(), solsten->GetOrientation(), TEMPSUMMON_MANUAL_DESPAWN))
solstenghost->CastSpell(solstenghost, SPELL_SOLSTEN_SPAWN_COSMETIC, true);
count1++;
}
if (count1 >= 2)
{
me->RemoveUnitFlag(UNIT_FLAG_NON_ATTACKABLE);
me->RemoveUnitFlag(UNIT_FLAG_NOT_SELECTABLE);
inCombat = true;
EnterCombat(me);
}
}
void ChooseSpecial()
{
uint32 spellId = 0;
switch (urand(1, 4))
{
case 1:
Talk(SAY_STORM);
me->CastSpell(me, SPELL_EYE_OF_THE_STORM_2, true);
events.ScheduleEvent(EVENT_STORM, 1 * IN_MILLISECONDS);
count = 0;
spellId = SPELL_EYE_OF_THE_STORM;
break;
case 2:
spellId = SPELL_ARCING_BOLT;
break;
case 3:
Talk(SAY_SANCTIFY);
spellId = SPELL_SANCTIFY;
break;
case 4:
spellId = SPELL_EXPEL_LIGHT;
break;
}
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 5.0f, true, 0))
me->CastSpell(target, spellId, true);
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_CHOOSE_SPECIAL:
ChooseSpecial();
if (me->HasAura(SPELL_MYSTIC_EMPOWEREMENT_HOLY) || me->HasAura(SPELL_MYSTIC_EMPOWEREMENT_THUNDER))
events.ScheduleEvent(EVENT_MYSTIC_EMPOWEREMENT, 4 * IN_MILLISECONDS);
else
events.ScheduleEvent(EVENT_MYSTIC_EMPOWEREMENT, 30 * IN_MILLISECONDS);
events.ScheduleEvent(EVENT_CHOOSE_SPECIAL, 20 * IN_MILLISECONDS);
break;
case EVENT_SHIELD_OF_LIGHT:
if (Unit* target = me->GetVictim())
me->CastSpell(target, SPELL_SHIELD_OF_LIGHT, true);
events.ScheduleEvent(EVENT_SHIELD_OF_LIGHT, 16 * IN_MILLISECONDS);
break;
case EVENT_STORM:
me->CastSpell(me, SPELL_EYE_OF_THE_STORM_DMG, true);
++count;
if (count <= 8)
events.ScheduleEvent(EVENT_STORM, 1 * IN_MILLISECONDS);
break;
default:
break;
}
}
DoMeleeAttackIfReady();
}
};
struct npc_olmyr_the_enlightened : public BossAI
{
npc_olmyr_the_enlightened(Creature* creature) : BossAI(creature, DATA_OLMYR)
{
me->SetDisableGravity(false);
me->SetCanFly(false);
}
void EnterCombat(Unit* /*who*/) override
{
_EnterCombat();
events.ScheduleEvent(EVENT_SANCTIFY, 3 * IN_MILLISECONDS);
events.ScheduleEvent(EVENT_SEARING_LIGHT, 8 * IN_MILLISECONDS);
}
void JustDied(Unit* killer) override
{
_JustDied();
if (Creature* creature = me->SummonCreature(NPC_OLMYR_GHOST, 0.0f, 0.0f, 0.0f, 0.0f, TEMPSUMMON_MANUAL_DESPAWN))
creature->CastSpell(creature, SPELL_OLMYR_SPAWN_COSMETIC, true);
if (Creature* hyrja = instance->GetCreature(BOSS_HYRJA))
{
hyrja->AI()->DoAction(ACTION_CAN_JOIN_COMBAT);
hyrja->SetTarget(killer->GetGUID());
}
}
void UpdateAI(uint32 diff) override
{
events.Update(diff);
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_SANCTIFY:
me->CastSpell(me, SPELL_SANCTIFY, true);
events.ScheduleEvent(EVENT_SANCTIFY, 12 * IN_MILLISECONDS);
break;
case EVENT_SEARING_LIGHT:
me->CastSpell(me, SPELL_SEARING_LIGHT, true);
events.ScheduleEvent(EVENT_SEARING_LIGHT, 21 * IN_MILLISECONDS);
break;
default:
break;
}
}
DoMeleeAttackIfReady();
}
};
struct npc_olmyr_ghost : public ScriptedAI
{
npc_olmyr_ghost(Creature* creature) : ScriptedAI(creature)
{
me->SetDisableGravity(false);
me->SetCanFly(false);
}
enum Events
{
EVENT_MYSTIC_EMPOWERMENT,
};
void Reset() override
{
events.Reset();
events.ScheduleEvent(EVENT_MYSTIC_EMPOWERMENT, 1 * IN_MILLISECONDS);
}
void UpdateAI(uint32 diff) override
{
events.Update(diff);
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_MYSTIC_EMPOWERMENT:
if (Creature* hyrja = instance->GetCreature(BOSS_HYRJA))
{
if (hyrja && me->GetDistance2d(hyrja->GetPositionX(), hyrja->GetPositionY()) < 5.0f)
me->CastSpell(hyrja, SPELL_MYSTIC_EMPOWEREMENT_HOLY, true);
else if (hyrja && me->GetDistance2d(hyrja->GetPositionX(), hyrja->GetPositionY()) < 20.0f)
{
me->CastSpell(hyrja, SPELL_MYSTIC_EMPOWEREMENT_HOLY_VISUAL, true);
/*if (hyrja->HasAura(SPELL_MYSTIC_EMPOWEREMENT_HOLY))
hyrja->RemoveAurasDueToSpell(SPELL_MYSTIC_EMPOWEREMENT_HOLY);*/
}
/*else if (hyrja->HasAura(SPELL_MYSTIC_EMPOWEREMENT_HOLY_VISUAL))
hyrja->RemoveAurasDueToSpell(SPELL_MYSTIC_EMPOWEREMENT_HOLY_VISUAL);*/
}
events.ScheduleEvent(EVENT_MYSTIC_EMPOWERMENT, 5 * IN_MILLISECONDS);
break;
default:
break;
}
}
}
};
struct npc_solsten : public BossAI
{
npc_solsten(Creature* creature) : BossAI(creature, DATA_SOLSTEN)
{
me->SetDisableGravity(false);
me->SetCanFly(false);
}
uint8 count;
void Reset() override
{
_Reset();
count = 0;
}
void EnterCombat(Unit* /*who*/) override
{
_EnterCombat();
events.ScheduleEvent(EVENT_EYE_OF_THE_STORM, 5 * IN_MILLISECONDS);
}
void JustDied(Unit* killer) override
{
_JustDied();
if (Creature* creature = me->SummonCreature(NPC_SOLSTEN_GHOST, 0.0f, 0.0f, 0.0f, 0.0f, TEMPSUMMON_MANUAL_DESPAWN))
creature->CastSpell(creature, SPELL_SOLSTEN_SPAWN_COSMETIC, true);
if (Creature* hyrja = instance->GetCreature(BOSS_HYRJA))
{
hyrja->AI()->DoAction(ACTION_CAN_JOIN_COMBAT);
hyrja->SetTarget(killer->GetGUID());
}
}
void UpdateAI(uint32 diff) override
{
events.Update(diff);
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_STORM:
me->CastSpell(me, SPELL_EYE_OF_THE_STORM_DMG, true);
++count;
if (count <= 8)
events.ScheduleEvent(EVENT_STORM, 1 * IN_MILLISECONDS);
break;
case EVENT_EYE_OF_THE_STORM:
if (Unit* target = me->GetVictim())
{
me->CastSpell(target, SPELL_EYE_OF_THE_STORM, true);
me->CastSpell(me, SPELL_EYE_OF_THE_STORM_2, true);
events.ScheduleEvent(EVENT_STORM, 1 * IN_MILLISECONDS);
}
events.ScheduleEvent(EVENT_EYE_OF_THE_STORM, 30 * IN_MILLISECONDS);
break;
default:
break;
}
}
DoMeleeAttackIfReady();
}
};
struct npc_solsten_ghost : public ScriptedAI
{
npc_solsten_ghost(Creature* creature) : ScriptedAI(creature)
{
me->SetDisableGravity(false);
me->SetCanFly(false);
}
enum Events
{
EVENT_MYSTIC_EMPOWERMENT,
};
void Reset() override
{
events.Reset();
events.ScheduleEvent(EVENT_MYSTIC_EMPOWERMENT, 1 * IN_MILLISECONDS);
}
void UpdateAI(uint32 diff) override
{
events.Update(diff);
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_MYSTIC_EMPOWERMENT:
if (Creature* hyrja = instance->GetCreature(BOSS_HYRJA))
{
if (hyrja && me->GetDistance2d(hyrja->GetPositionX(), hyrja->GetPositionY()) < 5.0f)
me->CastSpell(hyrja, SPELL_MYSTIC_EMPOWEREMENT_THUNDER, true);
else if (hyrja && me->GetDistance2d(hyrja->GetPositionX(), hyrja->GetPositionY()) < 20.0f)
{
me->CastSpell(hyrja, SPELL_MYSTIC_EMPOWEREMENT_THUNDER_VISUAL, true);
/*if (hyrja->HasAura(SPELL_MYSTIC_EMPOWEREMENT_THUNDER))
hyrja->RemoveAurasDueToSpell(SPELL_MYSTIC_EMPOWEREMENT_THUNDER);*/
}
/*else if (hyrja->HasAura(SPELL_MYSTIC_EMPOWEREMENT_THUNDER_VISUAL))
hyrja->RemoveAurasDueToSpell(SPELL_MYSTIC_EMPOWEREMENT_THUNDER_VISUAL);*/
}
events.ScheduleEvent(EVENT_MYSTIC_EMPOWERMENT, 5 * IN_MILLISECONDS);
break;
default:
break;
}
}
}
};
// 10675
struct at_center_eye_of_the_storm : AreaTriggerAI
{
at_center_eye_of_the_storm(AreaTrigger* areatrigger) : AreaTriggerAI(areatrigger) { }
void OnUnitEnter(Unit* target) override
{
if (!target->HasAura(SPELL_EYE_OF_THE_STORM_ABSORB))
target->CastSpell(target, SPELL_EYE_OF_THE_STORM_ABSORB, true);
}
void OnUnitExit(Unit* target) override
{
target->RemoveAurasDueToSpell(SPELL_EYE_OF_THE_STORM_ABSORB);
}
};
// 10374
struct at_eye_of_the_storm : AreaTriggerAI
{
at_eye_of_the_storm(AreaTrigger* areatrigger) : AreaTriggerAI(areatrigger) { }
void OnUnitEnter(Unit* target) override
{
if (!target->HasAura(SPELL_EYE_OF_THE_STORM_ACTIVE))
target->CastSpell(target, SPELL_EYE_OF_THE_STORM_ACTIVE, true);
}
void OnUnitExit(Unit* target) override
{
target->RemoveAurasDueToSpell(SPELL_EYE_OF_THE_STORM_ACTIVE);
}
};
struct at_sanctify : AreaTriggerAI
{
at_sanctify(AreaTrigger* areatrigger) : AreaTriggerAI(areatrigger) { }
void OnInitialize() override
{
at->SetPeriodicProcTimer(2000);
}
void OnUnitEnter(Unit* target) override
{
target->CastSpell(target, SPELL_SANCTIFY_DAMAGE, true);
}
void OnPeriodicProc() override
{
if (Unit* caster = at->GetCaster())
for (ObjectGuid guid : at->GetInsideUnits())
if (Unit* unit = ObjectAccessor::GetUnit(*at, guid))
if (caster->IsValidAttackTarget(unit))
caster->CastSpell(unit, SPELL_SANCTIFY_DAMAGE, true);
}
};
// 192048 - Expel Light
class spell_expel_light : public AuraScript
{
PrepareAuraScript(spell_expel_light);
void HandleEffectRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/)
{
GetCaster()->CastSpell(GetCaster(), SPELL_EXPEL_LIGHT_EXPLODE, true);
}
void Register() override
{
AfterEffectRemove += AuraEffectRemoveFn(spell_expel_light::HandleEffectRemove, EFFECT_0, SPELL_AURA_PERIODIC_DUMMY, AURA_EFFECT_HANDLE_REAL);
}
};
// 192307
class spell_sanctify : public AuraScript
{
PrepareAuraScript(spell_sanctify);
void HandleEffectPeriodic(AuraEffect const* /*aurEff*/)
{
Position pos = GetTarget()->GetRandomPoint(GetTarget()->GetPosition(), 30.0f);
GetTarget()->CastSpell(pos, SPELL_SANCTIFY_AREATRIGGER, true);
}
void Register() override
{
OnEffectPeriodic += AuraEffectPeriodicFn(spell_sanctify::HandleEffectPeriodic, EFFECT_0, SPELL_AURA_PERIODIC_DUMMY);
}
};
void AddSC_boss_hyrja()
{
RegisterCreatureAI(boss_hyrja);
RegisterCreatureAI(npc_olmyr_the_enlightened);
RegisterCreatureAI(npc_solsten);
RegisterAreaTriggerAI(at_center_eye_of_the_storm);
RegisterAreaTriggerAI(at_eye_of_the_storm);
RegisterAreaTriggerAI(at_sanctify);
RegisterAuraScript(spell_expel_light);
RegisterAuraScript(spell_sanctify);
RegisterCreatureAI(npc_olmyr_ghost);
RegisterCreatureAI(npc_solsten_ghost);
}
| 0 | 0.955085 | 1 | 0.955085 | game-dev | MEDIA | 0.987408 | game-dev | 0.970856 | 1 | 0.970856 |
latte-soft/datamodelpatch | 1,489 | src/PatchRoot/DataModelInstances/CorePackages/Packages/_Index/DeveloperTools/DeveloperTools/Roact17/Classes/Roact17TargetWatcher.luau | local l_Parent_0 = script.Parent.Parent.Parent;
local l_Parent_1 = l_Parent_0.Parent;
local _ = require(l_Parent_0.Roact17.types);
local v3 = require(l_Parent_0.Roact17.Classes.Roact17Worker);
local v4 = require(l_Parent_1.Dash);
local l_collect_0 = v4.collect;
local l_collectSet_0 = v4.collectSet;
local l_class_0 = v4.class;
local l_forEach_0 = v4.forEach;
local v11 = l_class_0("Roact17TargetWatcher", function(v9, v10)
return {
debugInterface = v9,
devtools = v10,
rootToTarget = {}
};
end);
v11._init = function(v12)
v12.devtools.store:addListener("roots", function()
v12:_updateTargets();
end);
end;
v11._updateTargets = function(v13)
local l_store_0 = v13.devtools.store;
local v15 = l_store_0:getRoots();
local v16 = l_collectSet_0(v15);
local l_rootToTarget_0 = v13.rootToTarget;
l_forEach_0(l_rootToTarget_0, function(v18)
if v16[v18.root] == nil then
v13.debugInterface:removeTarget(v18);
end;
end);
v13.rootToTarget = l_collect_0(v15, function(_, v20)
local v21 = v13.devtools.hook.rendererInterfaces[l_store_0:getRendererIDForElement(v20)]:getDisplayNameForRoot(v20);
if v21 == "Anonymous" then
v21 = "#" .. v20;
end;
return v20, l_rootToTarget_0[v20] or v13.debugInterface:addTarget(v21, function(v22, v23)
return v3.new(v13.debugInterface, v22, v23, v13.devtools, v20);
end);
end);
end;
return v11;
| 0 | 0.627937 | 1 | 0.627937 | game-dev | MEDIA | 0.607397 | game-dev | 0.790014 | 1 | 0.790014 |
BuildCraft/BuildCraft | 12,278 | src_old_license/buildcraft/factory/refining/ComplexRefiningManager.java | package buildcraft.factory.refining;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.client.renderer.block.model.IBakedModel;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.client.renderer.block.model.ModelRotation;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraftforge.client.event.ModelBakeEvent;
import net.minecraftforge.client.event.TextureStitchEvent;
import net.minecraftforge.client.model.IModel;
import net.minecraftforge.client.model.ModelFluid;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.fluids.FluidRegistry;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import buildcraft.BuildCraftEnergy;
import buildcraft.api.fuels.BuildcraftFuelRegistry;
import buildcraft.api.recipes.BuildcraftRecipeRegistry;
import buildcraft.api.recipes.IComplexRefineryRecipeManager;
import buildcraft.core.lib.client.sprite.SpriteColourMapper;
import buildcraft.core.lib.fluids.FluidDefinition;
import buildcraft.core.lib.utils.ModelHelper;
public class ComplexRefiningManager {
public static FluidDefinition[] crudeOil;
/** All 3 fuels (no residue) */
public static FluidDefinition[] oilDistilled;
/** The 3 heaviest components (fuelLight, fuelDense and oilResidue) */
public static FluidDefinition[] oilHeavy;
/** The 2 lightest fuels (no dense fuel) */
public static FluidDefinition[] fuelMixedLight;
/** The 2 heaviest fuels (no gaseous fuel) */
public static FluidDefinition[] fuelMixedHeavy;
/** The 2 heaviest products (fuelDense and oilResidue) */
public static FluidDefinition[] oilDense;
// End products in order from least to most dense
public static FluidDefinition[] fuelGaseous;
public static FluidDefinition[] fuelLight;
public static FluidDefinition[] fuelDense;
public static FluidDefinition[] oilResidue;
public static FluidDefinition tar;
public static FluidDefinition steam;
private static final List<FluidDefinition> allFluids = new ArrayList<>();
public static void preInit() {
int[][] colours = {// All colours.
{ 0x50_50_50, 0x05_05_05 }, // Crude Oil
{ 0x10_0F_10, 0x42_10F_42 },// Residue
{ 0xA0_8F_1F, 0x42_35_20 },// Heavy Oil
{ 0x87_6E_77, 0x42_24_24 },// Dense Oil
{ 0xE4_BF_78, 0xA4_8F_00 },// Distilled Oil
{ 0xFF_AF_3F, 0xE0_7F_00 },// Dense Fuel
{ 0xF2_A7_00, 0xC4_87_00 },// Mixed Dense + Light Fuel
{ 0xFF_FF_30, 0xE4_CF_00 },// Light Fuel
{ 0xF6_D7_00, 0xC4_B7_00 },// Mixed Light + Gas Fuel
{ 0xFA_F6_30, 0xE0_D9_00 },// Gas Fuel
{ 0x3F_3F_3F, 0x30_30_30 },// Tar
{ 0xFF_FF_FF, 0xAF_AF_AF } // Steam
};
int index = 0;
// Add all of the fluid states
crudeOil = defineFluids("oil", 4000, 4000, 3, 4, colours[index][0], colours[index++][1]);
oilResidue = defineFluids("oilResidue", 6000, 8000, 3, 4, colours[index][0], colours[index++][1]);
oilHeavy = defineFluids("oilHeavy", 4000, 4000, 3, 2, colours[index][0], colours[index++][1]);
oilDense = defineFluids("oilDense", 5000, 5000, 3, 4, colours[index][0], colours[index++][1]);
oilDistilled = defineFluids("oilDistilled", 3000, 3500, 3, 2, colours[index][0], colours[index++][1]);
fuelDense = defineFluids("fuelDense", 2000, 5000, 3, 2, colours[index][0], colours[index++][1]);
fuelMixedHeavy = defineFluids("fuelMixedHeavy", 1200, 700, 3, 2, colours[index][0], colours[index++][1]);
fuelLight = new FluidDefinition[] {
// @formatter:off
defineFluid("fuel", 1000, 900, 0, 1, colours[index][0], colours[index][1]),
defineFluid("fuelLight", 1000, 900, 1, 1, colours[index][0], colours[index][1]),
defineFluid("fuelLight", 1000, 900, 2, 1, colours[index][0], colours[index][1]),
defineFluid("fuelLight", 1000, 900, 3, 1, colours[index][0], colours[index++][1]),
// @formatter:on
};
fuelLight[0].fluid.setHeatable(true);
fuelMixedLight = defineFluids("fuelMixedLight", 800, 700, 3, 1, colours[index][0], colours[index++][1]);
fuelGaseous = defineFluids("fuelGaseous", 300, 600, 3, 0, colours[index][0], colours[index++][1]);
tar = defineFluid("tar", 7000, 8000, 0, 4, colours[index][0], colours[index++][1]);
steam = defineFluid("steam", 100, 1000, 2, 1, colours[index][0], colours[index++][1]);
BuildCraftEnergy.oil = crudeOil[0];
BuildCraftEnergy.oil.block.setDense(true);
BuildCraftEnergy.fuel = fuelLight[0];
}
private static FluidDefinition[] defineFluids(String name, int density, int baseViscocity, int maxHeat, int boilPoint, int texColourLight,
int texColourDark) {
FluidDefinition[] arr = new FluidDefinition[maxHeat + 1];
for (int h = 0; h <= maxHeat; h++) {
arr[h] = defineFluid(name, density, baseViscocity, h, boilPoint, texColourLight, texColourDark);
}
if (maxHeat > 0) arr[0].fluid.setHeatable(true);
return arr;
}
private static FluidDefinition defineFluid(String name, int density, int baseViscocity, int heat, int boilPoint, int texColourLight,
int texColourDark) {
String fullName = name + (heat == 0 ? "" : "_heat_" + heat);
int tempAdjustedViscocity = baseViscocity * (5 - heat) / 5;
int boilAdjustedDensity = density * (heat >= boilPoint ? -1 : 1);
FluidDefinition def = new FluidDefinition(fullName, fullName, boilAdjustedDensity, tempAdjustedViscocity, 0xFF_00_00_00 | texColourLight,
0xFF_00_00_00 | texColourDark);
if (def.bucket != null && heat != 0) {
def.bucket.setCreativeTab(null);
}
def.fluid.setHeat(heat);
def.fluid.setUnlocalizedName(name);
def.fluid.setTemperature(300 + 20 * heat);
if (heat > 0) def.fluid.setHeatable(true);
allFluids.add(def);
return def;
}
public static void init() {
// Add the heatables
addBiDirectionalHeatExchange(crudeOil, 10, 7);
addBiDirectionalHeatExchange(oilDistilled, 10, 4);
addBiDirectionalHeatExchange(oilHeavy, 10, 6);
addBiDirectionalHeatExchange(oilDense, 10, 6);
addBiDirectionalHeatExchange(fuelMixedHeavy, 10, 5);
addBiDirectionalHeatExchange(fuelMixedLight, 10, 4);
addBiDirectionalHeatExchange(oilResidue, 10, 8);
addBiDirectionalHeatExchange(fuelDense, 10, 5);
addBiDirectionalHeatExchange(fuelLight, 10, 4);
addBiDirectionalHeatExchange(fuelGaseous, 10, 3);
BuildcraftRecipeRegistry.complexRefinery.addHeatableRecipe(new FluidStack(FluidRegistry.WATER, 10), steam.createFluidStack(10), 0, 2, 3,
false);
// single
final int _oil = 4;
final int _gas = 32;
final int _light = 8;
final int _dense = 2;
final int _residue = 1;
// double
final int _gas_light = 10;
final int _light_dense = 5;
final int _dense_residue = 2;
// triple
final int _light_dense_residue = 5;
final int _gas_light_dense = 10;
// 4 split up
addDistilationRecipe(crudeOil[1], _oil, fuelGaseous[1], _gas, oilHeavy[1], _light_dense_residue, 12);
addDistilationRecipe(crudeOil[2], _oil, fuelMixedLight[2], _gas_light, oilDense[2], _dense_residue, 8);
addDistilationRecipe(crudeOil[3], _oil, oilDistilled[3], _gas_light_dense, oilResidue[3], _residue, 4);
// 3 split up
addDistilationRecipe(oilDistilled[1], _gas_light_dense, fuelGaseous[1], _gas, fuelMixedHeavy[1], _light_dense, 6);
addDistilationRecipe(oilDistilled[2], _gas_light_dense, fuelMixedLight[2], _gas_light, fuelDense[2], _dense, 4);
addDistilationRecipe(oilHeavy[2], _light_dense_residue, fuelLight[2], _light, oilDense[2], _dense_residue, 4);
addDistilationRecipe(oilHeavy[3], _light_dense_residue, fuelMixedHeavy[3], _light_dense, oilResidue[3], _residue, 4);
// 2 split up
addDistilationRecipe(fuelMixedLight[1], _gas_light, fuelGaseous[1], _gas, fuelLight[1], _light, 6);
addDistilationRecipe(fuelMixedHeavy[2], _light_dense, fuelLight[2], _light, fuelDense[2], _dense, 6);
addDistilationRecipe(oilDense[3], _dense_residue, fuelDense[3], _dense, oilResidue[3], _residue, 6);
addNormalFuel(fuelGaseous[0], _gas, 8, 1);
addNormalFuel(fuelLight[0], _light, 6, 1);
addNormalFuel(fuelDense[0], _dense, 4, 1);
addNormalFuel(fuelMixedLight[0], _gas_light, 6.5, 0.75);
addNormalFuel(fuelMixedHeavy[0], _light_dense, 4.5, 0.75);
addDirtyFuel(oilDense[0], _dense_residue, 2, 0.75);
addNormalFuel(oilDistilled[0], _gas_light_dense, 3.5, 0.5);
addDirtyFuel(oilHeavy[0], _light_dense_residue, 2.5, 0.5);
addDirtyFuel(crudeOil[0], _oil, 3, 0.25);
}
private static void addBiDirectionalHeatExchange(FluidDefinition[] coldToHot, int amount, int ticks) {
IComplexRefineryRecipeManager manager = BuildcraftRecipeRegistry.complexRefinery;
for (int h = 1; h < coldToHot.length; h++) {
FluidDefinition cold = coldToHot[h - 1];
FluidDefinition hot = coldToHot[h];
manager.addHeatableRecipe(cold.createFluidStack(amount), hot.createFluidStack(amount), h - 1, h, ticks, false);
manager.addCoolableRecipe(hot.createFluidStack(amount), cold.createFluidStack(amount), h, h - 1, ticks, false);
}
}
private static void addDistilationRecipe(FluidDefinition from, int fromAmount, FluidDefinition gas, int gasAmount, FluidDefinition liquid,
int liquidAmount, int ticks) {
FluidStack in = from.createFluidStack(fromAmount);
FluidStack outGas = gas.createFluidStack(gasAmount);
FluidStack outLiquid = liquid.createFluidStack(liquidAmount);
BuildcraftRecipeRegistry.complexRefinery.addDistilationRecipe(in, outGas, outLiquid, ticks, false);
}
private static void addNormalFuel(FluidDefinition def, int amountDiff, double multiplier, double efficiencyMultiplier) {
final int powerBase = 10;
final int timeBase = 256_000;
int powerPerCycle = (int) (multiplier * powerBase);
int totalTime = (int) (timeBase * efficiencyMultiplier / multiplier / amountDiff);
BuildcraftFuelRegistry.fuel.addFuel(def.fluid, powerPerCycle, totalTime);
}
private static void addDirtyFuel(FluidDefinition def, int amountDiff, double multiplier, double efficiencyMultiplier) {
final int powerBase = 10;
final int timeBase = 256_000;
int powerPerCycle = (int) (multiplier * powerBase);
int totalTime = (int) (timeBase * efficiencyMultiplier / multiplier / amountDiff);
BuildcraftFuelRegistry.fuel.addDirtyFuel(def.fluid, powerPerCycle, totalTime, oilResidue[0].createFluidStack(1000 / amountDiff));
}
@SideOnly(Side.CLIENT)
public static void registerModels(ModelBakeEvent event) {
for (FluidDefinition def : allFluids) {
IModel model = new ModelFluid(def.fluid);
IBakedModel baked = model.bake(ModelRotation.X0_Y0, DefaultVertexFormats.BLOCK, ModelLoader.defaultTextureGetter());
ModelResourceLocation loc = ModelHelper.getBlockResourceLocation(def.block);
event.getModelRegistry().putObject(loc, baked);
}
}
@SideOnly(Side.CLIENT)
public static void textureStitchPre(TextureStitchEvent.Pre event) {
for (FluidDefinition def : allFluids) {
int heat = def.fluid.getHeatValue();
String from = "buildcraftenergy:blocks/fluids/heat_" + heat;
SpriteColourMapper mapper = new SpriteColourMapper(def.fluid, from + "_still", true);
event.getMap().setTextureEntry(mapper);
mapper = new SpriteColourMapper(def.fluid, from + "_flow", false);
event.getMap().setTextureEntry(mapper);
}
}
}
| 0 | 0.682138 | 1 | 0.682138 | game-dev | MEDIA | 0.549751 | game-dev | 0.784139 | 1 | 0.784139 |
dengzibiao/moba | 1,534 | Assets/Script/Player/GoodsBorderIcon.cs | using UnityEngine;
using System.Collections;
public class GoodsBorderIcon : GUISingleItemList
{
public GUISingleButton icon;
public Transform xuanZhongIcon;
private RoleIconAttrNode item;
public static GoodsBorderIcon _instance;
protected override void InitItem()
{
_instance = this;
icon = transform.Find("Icon").GetComponent<GUISingleButton>();
xuanZhongIcon = transform.Find("XuanZhongIcon");
if (index == 0)
{
transform.gameObject.SetActive(true);
}
icon.onClick = OnIconClick;
}
private void OnIconClick()
{
Globe.seletIndex = index;
ChangeIconBorder._instance.roleIconBorder.spriteName = item.icon_name;
UIRole.Instance.roleIconBorder.spriteName = item.icon_name;
playerData.GetInstance().iconFrameData.iconFrame_id = item.icon_id;
UIRoleInfo.Instance.roleIconBorder.spriteName = item.icon_name;
// ClientSendDataMgr.GetSingle().GetRoleSend().SendIcon();
}
public override void Info(object obj)
{
if (null == obj)
{
}
else
{
item = (RoleIconAttrNode)obj;
Debug.Log(item.icon_name);
icon.spriteName = item.icon_name;
}
}
public void Update()
{
if (index == Globe.seletIndex)
{
xuanZhongIcon.gameObject.SetActive(true);
}
else
{
xuanZhongIcon.gameObject.SetActive(false);
}
}
}
| 0 | 0.560471 | 1 | 0.560471 | game-dev | MEDIA | 0.978776 | game-dev | 0.740386 | 1 | 0.740386 |
dingxiaowei/Aladdin_XLua | 2,433 | AladdinLuaFrameWork/Assets/AladdinLuaFramework/NGUI/Scripts/UI/UILocalize.cs | //----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2015 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// Simple script that lets you localize a UIWidget.
/// </summary>
[ExecuteInEditMode]
[RequireComponent(typeof(UIWidget))]
[AddComponentMenu("NGUI/UI/Localize")]
public class UILocalize : MonoBehaviour
{
/// <summary>
/// Localization key.
/// </summary>
public string key;
/// <summary>
/// Manually change the value of whatever the localization component is attached to.
/// </summary>
public string value
{
set
{
if (!string.IsNullOrEmpty(value))
{
UIWidget w = GetComponent<UIWidget>();
UILabel lbl = w as UILabel;
UISprite sp = w as UISprite;
if (lbl != null)
{
// If this is a label used by input, we should localize its default value instead
UIInput input = NGUITools.FindInParents<UIInput>(lbl.gameObject);
if (input != null && input.label == lbl) input.defaultText = value;
else lbl.text = value;
#if UNITY_EDITOR
if (!Application.isPlaying) NGUITools.SetDirty(lbl);
#endif
}
else if (sp != null)
{
UIButton btn = NGUITools.FindInParents<UIButton>(sp.gameObject);
if (btn != null && btn.tweenTarget == sp.gameObject)
btn.normalSprite = value;
sp.spriteName = value;
sp.MakePixelPerfect();
#if UNITY_EDITOR
if (!Application.isPlaying) NGUITools.SetDirty(sp);
#endif
}
}
}
}
bool mStarted = false;
/// <summary>
/// Localize the widget on enable, but only if it has been started already.
/// </summary>
void OnEnable ()
{
#if UNITY_EDITOR
if (!Application.isPlaying) return;
#endif
if (mStarted) OnLocalize();
}
/// <summary>
/// Localize the widget on start.
/// </summary>
void Start ()
{
#if UNITY_EDITOR
if (!Application.isPlaying) return;
#endif
mStarted = true;
OnLocalize();
}
/// <summary>
/// This function is called by the Localization manager via a broadcast SendMessage.
/// </summary>
void OnLocalize ()
{
// If no localization key has been specified, use the label's text as the key
if (string.IsNullOrEmpty(key))
{
UILabel lbl = GetComponent<UILabel>();
if (lbl != null) key = lbl.text;
}
// If we still don't have a key, leave the value as blank
if (!string.IsNullOrEmpty(key)) value = Localization.Get(key);
}
}
| 0 | 0.854757 | 1 | 0.854757 | game-dev | MEDIA | 0.753471 | game-dev | 0.978293 | 1 | 0.978293 |
JiepengTan/LockstepECS | 25,159 | Client.Unity/DataAndTools/Src/Tools.UnsafeECS.ECSOutput/Src/Generated/Model/CodeGen__Entities_Interfaces.cs |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by Tools.MacroExpansion, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null.
// https://github.com/JiepengTan/LockstepEngine
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
//Power by ME //src: https://github.com/JiepengTan/ME
//#define DONT_USE_GENERATE_CODE
using System.Linq;
using Lockstep.Serialization;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System;
using Lockstep.InternalUnsafeECS;
using System.Collections;
using Lockstep.Math;
using System.Collections.Generic;
using Lockstep.Logging;
using Lockstep.Util;
namespace Lockstep.UnsafeECS.Game {
public unsafe partial class _EntityManager {
internal NativeEntityArray<PlayerCube> _PlayerCubeAry;
internal unsafe void Alloc(){
_PlayerCubeAry.Alloc((int)EEntityType.PlayerCube,PlayerCube.INIT_COUNT);
}
internal unsafe void Free(){
_PlayerCubeAry.Free();
}
internal _EntityManager Clone(){
var ret = new _EntityManager();
CopyTo(ret);
return ret;
}
internal void CopyTo(_EntityManager dst){
_PlayerCubeAry.CopyTo(ref dst._PlayerCubeAry);
}
internal unsafe PlayerCube* CreateTempPlayerCube(Context context) {
return _PlayerCubeAry.CreateTempEntity(context);
}
internal unsafe PlayerCube* GetTempPlayerCube(int idx) {
return _PlayerCubeAry.GetTempEntity(idx);
}
internal unsafe void ClearTempPlayerCubeAry(){
if (_PlayerCubeAry._WaitCreateCount > 0) {
var len = _PlayerCubeAry._WaitCreateCount;
var ptr = _PlayerCubeAry._WaitCreateAry.GetPointer(0);
for(int i =0;i < len; ++i,++ptr){
*ptr = _DefaultDefine.PlayerCube;
ptr->_entity._ref._type = (int)EEntityType.PlayerCube;
}
_PlayerCubeAry._WaitCreateCount = 0;
}
}
internal NativeArray<int> GetAllAnimator_Pad(E_EntityOfAnimator entity){
switch(entity){
}
return new NativeArray<int>();
}
internal NativeArray<CollisionShape> GetAllCollisionAgent_Collider(E_EntityOfCollisionAgent entity){
switch(entity){
}
return new NativeArray<CollisionShape>();
}
internal NativeArray<bool> GetAllCollisionAgent_IsTrigger(E_EntityOfCollisionAgent entity){
switch(entity){
}
return new NativeArray<bool>();
}
internal NativeArray<int> GetAllCollisionAgent_Layer(E_EntityOfCollisionAgent entity){
switch(entity){
}
return new NativeArray<int>();
}
internal NativeArray<bool> GetAllCollisionAgent_IsEnable(E_EntityOfCollisionAgent entity){
switch(entity){
}
return new NativeArray<bool>();
}
internal NativeArray<bool> GetAllCollisionAgent_IsSleep(E_EntityOfCollisionAgent entity){
switch(entity){
}
return new NativeArray<bool>();
}
internal NativeArray<LFloat> GetAllCollisionAgent_Mass(E_EntityOfCollisionAgent entity){
switch(entity){
}
return new NativeArray<LFloat>();
}
internal NativeArray<LFloat> GetAllCollisionAgent_AngularSpeed(E_EntityOfCollisionAgent entity){
switch(entity){
}
return new NativeArray<LFloat>();
}
internal NativeArray<LVector3> GetAllCollisionAgent_Speed(E_EntityOfCollisionAgent entity){
switch(entity){
}
return new NativeArray<LVector3>();
}
internal NativeArray<int> GetAllNavMeshAgent_Pad(E_EntityOfNavMeshAgent entity){
switch(entity){
}
return new NativeArray<int>();
}
internal NativeArray<int> GetAllPrefab_AssetId(E_EntityOfPrefab entity){
switch(entity){
case E_EntityOfPrefab.PlayerCube: return _GetAllPlayerCube_Prefab<int>(_GetOffsetOfPrefab_AssetId()); break;
}
return new NativeArray<int>();
}
internal NativeArray<LVector2> GetAllTransform2D_Position(E_EntityOfTransform2D entity){
switch(entity){
}
return new NativeArray<LVector2>();
}
internal NativeArray<LFloat> GetAllTransform2D_Deg(E_EntityOfTransform2D entity){
switch(entity){
}
return new NativeArray<LFloat>();
}
internal NativeArray<LFloat> GetAllTransform2D_Scale(E_EntityOfTransform2D entity){
switch(entity){
}
return new NativeArray<LFloat>();
}
internal NativeArray<LVector3> GetAllTransform3D_Position(E_EntityOfTransform3D entity){
switch(entity){
case E_EntityOfTransform3D.PlayerCube: return _GetAllPlayerCube_Transform3D<LVector3>(_GetOffsetOfTransform3D_Position()); break;
}
return new NativeArray<LVector3>();
}
internal NativeArray<LVector3> GetAllTransform3D_Forward(E_EntityOfTransform3D entity){
switch(entity){
case E_EntityOfTransform3D.PlayerCube: return _GetAllPlayerCube_Transform3D<LVector3>(_GetOffsetOfTransform3D_Forward()); break;
}
return new NativeArray<LVector3>();
}
internal NativeArray<LFloat> GetAllTransform3D_Scale(E_EntityOfTransform3D entity){
switch(entity){
case E_EntityOfTransform3D.PlayerCube: return _GetAllPlayerCube_Transform3D<LFloat>(_GetOffsetOfTransform3D_Scale()); break;
}
return new NativeArray<LFloat>();
}
internal NativeArray<int> GetAllPlayerCubeTag_Pad(E_EntityOfPlayerCubeTag entity){
switch(entity){
case E_EntityOfPlayerCubeTag.PlayerCube: return _GetAllPlayerCube_PlayerCubeTag<int>(_GetOffsetOfPlayerCubeTag_Pad()); break;
}
return new NativeArray<int>();
}
internal NativeArray<int> GetAllAssetData_AssetId(E_EntityOfAssetData entity){
switch(entity){
}
return new NativeArray<int>();
}
internal NativeArray<int> GetAllPlayerData_Score(E_EntityOfPlayerData entity){
switch(entity){
case E_EntityOfPlayerData.PlayerCube: return _GetAllPlayerCube_PlayerData<int>(_GetOffsetOfPlayerData_Score()); break;
}
return new NativeArray<int>();
}
internal NativeArray<int> GetAllPlayerData_LocalId(E_EntityOfPlayerData entity){
switch(entity){
case E_EntityOfPlayerData.PlayerCube: return _GetAllPlayerCube_PlayerData<int>(_GetOffsetOfPlayerData_LocalId()); break;
}
return new NativeArray<int>();
}
internal NativeArray<LFloat> GetAllMoveData_MoveSpd(E_EntityOfMoveData entity){
switch(entity){
case E_EntityOfMoveData.PlayerCube: return _GetAllPlayerCube_MoveData<LFloat>(_GetOffsetOfMoveData_MoveSpd()); break;
}
return new NativeArray<LFloat>();
}
internal NativeArray<LFloat> GetAllMoveData_AcceleratedSpd(E_EntityOfMoveData entity){
switch(entity){
case E_EntityOfMoveData.PlayerCube: return _GetAllPlayerCube_MoveData<LFloat>(_GetOffsetOfMoveData_AcceleratedSpd()); break;
}
return new NativeArray<LFloat>();
}
internal NativeArray<LFloat> GetAllMoveData_CurSpd(E_EntityOfMoveData entity){
switch(entity){
case E_EntityOfMoveData.PlayerCube: return _GetAllPlayerCube_MoveData<LFloat>(_GetOffsetOfMoveData_CurSpd()); break;
}
return new NativeArray<LFloat>();
}
internal NativeArray<LFloat> GetAllMoveData_AngularSpd(E_EntityOfMoveData entity){
switch(entity){
case E_EntityOfMoveData.PlayerCube: return _GetAllPlayerCube_MoveData<LFloat>(_GetOffsetOfMoveData_AngularSpd()); break;
}
return new NativeArray<LFloat>();
}
internal NativeArray<LFloat> GetAllMoveData_DeltaDeg(E_EntityOfMoveData entity){
switch(entity){
case E_EntityOfMoveData.PlayerCube: return _GetAllPlayerCube_MoveData<LFloat>(_GetOffsetOfMoveData_DeltaDeg()); break;
}
return new NativeArray<LFloat>();
}
internal NativeArray<int> GetAllAnimator_Pad(E_EntityOfAnimator entity,FuncEntityFilter<Entity> filterFunc,out int length){
switch(entity){
}
length = 0;return new NativeArray<int>();
}
internal NativeArray<CollisionShape> GetAllCollisionAgent_Collider(E_EntityOfCollisionAgent entity,FuncEntityFilter<Entity> filterFunc,out int length){
switch(entity){
}
length = 0;return new NativeArray<CollisionShape>();
}
internal NativeArray<bool> GetAllCollisionAgent_IsTrigger(E_EntityOfCollisionAgent entity,FuncEntityFilter<Entity> filterFunc,out int length){
switch(entity){
}
length = 0;return new NativeArray<bool>();
}
internal NativeArray<int> GetAllCollisionAgent_Layer(E_EntityOfCollisionAgent entity,FuncEntityFilter<Entity> filterFunc,out int length){
switch(entity){
}
length = 0;return new NativeArray<int>();
}
internal NativeArray<bool> GetAllCollisionAgent_IsEnable(E_EntityOfCollisionAgent entity,FuncEntityFilter<Entity> filterFunc,out int length){
switch(entity){
}
length = 0;return new NativeArray<bool>();
}
internal NativeArray<bool> GetAllCollisionAgent_IsSleep(E_EntityOfCollisionAgent entity,FuncEntityFilter<Entity> filterFunc,out int length){
switch(entity){
}
length = 0;return new NativeArray<bool>();
}
internal NativeArray<LFloat> GetAllCollisionAgent_Mass(E_EntityOfCollisionAgent entity,FuncEntityFilter<Entity> filterFunc,out int length){
switch(entity){
}
length = 0;return new NativeArray<LFloat>();
}
internal NativeArray<LFloat> GetAllCollisionAgent_AngularSpeed(E_EntityOfCollisionAgent entity,FuncEntityFilter<Entity> filterFunc,out int length){
switch(entity){
}
length = 0;return new NativeArray<LFloat>();
}
internal NativeArray<LVector3> GetAllCollisionAgent_Speed(E_EntityOfCollisionAgent entity,FuncEntityFilter<Entity> filterFunc,out int length){
switch(entity){
}
length = 0;return new NativeArray<LVector3>();
}
internal NativeArray<int> GetAllNavMeshAgent_Pad(E_EntityOfNavMeshAgent entity,FuncEntityFilter<Entity> filterFunc,out int length){
switch(entity){
}
length = 0;return new NativeArray<int>();
}
internal NativeArray<int> GetAllPrefab_AssetId(E_EntityOfPrefab entity,FuncEntityFilter<Entity> filterFunc,out int length){
switch(entity){
case E_EntityOfPrefab.PlayerCube: return _GetAllPlayerCube_Prefab<int>(_GetOffsetOfPrefab_AssetId(),filterFunc,out length); break;
}
length = 0;return new NativeArray<int>();
}
internal NativeArray<LVector2> GetAllTransform2D_Position(E_EntityOfTransform2D entity,FuncEntityFilter<Entity> filterFunc,out int length){
switch(entity){
}
length = 0;return new NativeArray<LVector2>();
}
internal NativeArray<LFloat> GetAllTransform2D_Deg(E_EntityOfTransform2D entity,FuncEntityFilter<Entity> filterFunc,out int length){
switch(entity){
}
length = 0;return new NativeArray<LFloat>();
}
internal NativeArray<LFloat> GetAllTransform2D_Scale(E_EntityOfTransform2D entity,FuncEntityFilter<Entity> filterFunc,out int length){
switch(entity){
}
length = 0;return new NativeArray<LFloat>();
}
internal NativeArray<LVector3> GetAllTransform3D_Position(E_EntityOfTransform3D entity,FuncEntityFilter<Entity> filterFunc,out int length){
switch(entity){
case E_EntityOfTransform3D.PlayerCube: return _GetAllPlayerCube_Transform3D<LVector3>(_GetOffsetOfTransform3D_Position(),filterFunc,out length); break;
}
length = 0;return new NativeArray<LVector3>();
}
internal NativeArray<LVector3> GetAllTransform3D_Forward(E_EntityOfTransform3D entity,FuncEntityFilter<Entity> filterFunc,out int length){
switch(entity){
case E_EntityOfTransform3D.PlayerCube: return _GetAllPlayerCube_Transform3D<LVector3>(_GetOffsetOfTransform3D_Forward(),filterFunc,out length); break;
}
length = 0;return new NativeArray<LVector3>();
}
internal NativeArray<LFloat> GetAllTransform3D_Scale(E_EntityOfTransform3D entity,FuncEntityFilter<Entity> filterFunc,out int length){
switch(entity){
case E_EntityOfTransform3D.PlayerCube: return _GetAllPlayerCube_Transform3D<LFloat>(_GetOffsetOfTransform3D_Scale(),filterFunc,out length); break;
}
length = 0;return new NativeArray<LFloat>();
}
internal NativeArray<int> GetAllPlayerCubeTag_Pad(E_EntityOfPlayerCubeTag entity,FuncEntityFilter<Entity> filterFunc,out int length){
switch(entity){
case E_EntityOfPlayerCubeTag.PlayerCube: return _GetAllPlayerCube_PlayerCubeTag<int>(_GetOffsetOfPlayerCubeTag_Pad(),filterFunc,out length); break;
}
length = 0;return new NativeArray<int>();
}
internal NativeArray<int> GetAllAssetData_AssetId(E_EntityOfAssetData entity,FuncEntityFilter<Entity> filterFunc,out int length){
switch(entity){
}
length = 0;return new NativeArray<int>();
}
internal NativeArray<int> GetAllPlayerData_Score(E_EntityOfPlayerData entity,FuncEntityFilter<Entity> filterFunc,out int length){
switch(entity){
case E_EntityOfPlayerData.PlayerCube: return _GetAllPlayerCube_PlayerData<int>(_GetOffsetOfPlayerData_Score(),filterFunc,out length); break;
}
length = 0;return new NativeArray<int>();
}
internal NativeArray<int> GetAllPlayerData_LocalId(E_EntityOfPlayerData entity,FuncEntityFilter<Entity> filterFunc,out int length){
switch(entity){
case E_EntityOfPlayerData.PlayerCube: return _GetAllPlayerCube_PlayerData<int>(_GetOffsetOfPlayerData_LocalId(),filterFunc,out length); break;
}
length = 0;return new NativeArray<int>();
}
internal NativeArray<LFloat> GetAllMoveData_MoveSpd(E_EntityOfMoveData entity,FuncEntityFilter<Entity> filterFunc,out int length){
switch(entity){
case E_EntityOfMoveData.PlayerCube: return _GetAllPlayerCube_MoveData<LFloat>(_GetOffsetOfMoveData_MoveSpd(),filterFunc,out length); break;
}
length = 0;return new NativeArray<LFloat>();
}
internal NativeArray<LFloat> GetAllMoveData_AcceleratedSpd(E_EntityOfMoveData entity,FuncEntityFilter<Entity> filterFunc,out int length){
switch(entity){
case E_EntityOfMoveData.PlayerCube: return _GetAllPlayerCube_MoveData<LFloat>(_GetOffsetOfMoveData_AcceleratedSpd(),filterFunc,out length); break;
}
length = 0;return new NativeArray<LFloat>();
}
internal NativeArray<LFloat> GetAllMoveData_CurSpd(E_EntityOfMoveData entity,FuncEntityFilter<Entity> filterFunc,out int length){
switch(entity){
case E_EntityOfMoveData.PlayerCube: return _GetAllPlayerCube_MoveData<LFloat>(_GetOffsetOfMoveData_CurSpd(),filterFunc,out length); break;
}
length = 0;return new NativeArray<LFloat>();
}
internal NativeArray<LFloat> GetAllMoveData_AngularSpd(E_EntityOfMoveData entity,FuncEntityFilter<Entity> filterFunc,out int length){
switch(entity){
case E_EntityOfMoveData.PlayerCube: return _GetAllPlayerCube_MoveData<LFloat>(_GetOffsetOfMoveData_AngularSpd(),filterFunc,out length); break;
}
length = 0;return new NativeArray<LFloat>();
}
internal NativeArray<LFloat> GetAllMoveData_DeltaDeg(E_EntityOfMoveData entity,FuncEntityFilter<Entity> filterFunc,out int length){
switch(entity){
case E_EntityOfMoveData.PlayerCube: return _GetAllPlayerCube_MoveData<LFloat>(_GetOffsetOfMoveData_DeltaDeg(),filterFunc,out length); break;
}
length = 0;return new NativeArray<LFloat>();
}
internal NativeArray<Animator> GetAllAnimator(E_EntityOfAnimator entity){
switch(entity){
}
return new NativeArray<Animator>();
}
internal NativeArray<CollisionAgent> GetAllCollisionAgent(E_EntityOfCollisionAgent entity){
switch(entity){
}
return new NativeArray<CollisionAgent>();
}
internal NativeArray<NavMeshAgent> GetAllNavMeshAgent(E_EntityOfNavMeshAgent entity){
switch(entity){
}
return new NativeArray<NavMeshAgent>();
}
internal NativeArray<Prefab> GetAllPrefab(E_EntityOfPrefab entity){
switch(entity){
case E_EntityOfPrefab.PlayerCube: return _GetAllPlayerCube_Prefab<Prefab>(0); break;
}
return new NativeArray<Prefab>();
}
internal NativeArray<Transform2D> GetAllTransform2D(E_EntityOfTransform2D entity){
switch(entity){
}
return new NativeArray<Transform2D>();
}
internal NativeArray<Transform3D> GetAllTransform3D(E_EntityOfTransform3D entity){
switch(entity){
case E_EntityOfTransform3D.PlayerCube: return _GetAllPlayerCube_Transform3D<Transform3D>(0); break;
}
return new NativeArray<Transform3D>();
}
internal NativeArray<PlayerCubeTag> GetAllPlayerCubeTag(E_EntityOfPlayerCubeTag entity){
switch(entity){
case E_EntityOfPlayerCubeTag.PlayerCube: return _GetAllPlayerCube_PlayerCubeTag<PlayerCubeTag>(0); break;
}
return new NativeArray<PlayerCubeTag>();
}
internal NativeArray<AssetData> GetAllAssetData(E_EntityOfAssetData entity){
switch(entity){
}
return new NativeArray<AssetData>();
}
internal NativeArray<PlayerData> GetAllPlayerData(E_EntityOfPlayerData entity){
switch(entity){
case E_EntityOfPlayerData.PlayerCube: return _GetAllPlayerCube_PlayerData<PlayerData>(0); break;
}
return new NativeArray<PlayerData>();
}
internal NativeArray<MoveData> GetAllMoveData(E_EntityOfMoveData entity){
switch(entity){
case E_EntityOfMoveData.PlayerCube: return _GetAllPlayerCube_MoveData<MoveData>(0); break;
}
return new NativeArray<MoveData>();
}
internal NativeArray<Animator> GetAllAnimator(E_EntityOfAnimator entity,FuncEntityFilter<Entity> filterFunc,out int length){
switch(entity){
}
length = 0;
return new NativeArray<Animator>();
}
internal NativeArray<CollisionAgent> GetAllCollisionAgent(E_EntityOfCollisionAgent entity,FuncEntityFilter<Entity> filterFunc,out int length){
switch(entity){
}
length = 0;
return new NativeArray<CollisionAgent>();
}
internal NativeArray<NavMeshAgent> GetAllNavMeshAgent(E_EntityOfNavMeshAgent entity,FuncEntityFilter<Entity> filterFunc,out int length){
switch(entity){
}
length = 0;
return new NativeArray<NavMeshAgent>();
}
internal NativeArray<Prefab> GetAllPrefab(E_EntityOfPrefab entity,FuncEntityFilter<Entity> filterFunc,out int length){
switch(entity){
case E_EntityOfPrefab.PlayerCube: return _GetAllPlayerCube_Prefab<Prefab>(0,filterFunc,out length); break;
}
length = 0;
return new NativeArray<Prefab>();
}
internal NativeArray<Transform2D> GetAllTransform2D(E_EntityOfTransform2D entity,FuncEntityFilter<Entity> filterFunc,out int length){
switch(entity){
}
length = 0;
return new NativeArray<Transform2D>();
}
internal NativeArray<Transform3D> GetAllTransform3D(E_EntityOfTransform3D entity,FuncEntityFilter<Entity> filterFunc,out int length){
switch(entity){
case E_EntityOfTransform3D.PlayerCube: return _GetAllPlayerCube_Transform3D<Transform3D>(0,filterFunc,out length); break;
}
length = 0;
return new NativeArray<Transform3D>();
}
internal NativeArray<PlayerCubeTag> GetAllPlayerCubeTag(E_EntityOfPlayerCubeTag entity,FuncEntityFilter<Entity> filterFunc,out int length){
switch(entity){
case E_EntityOfPlayerCubeTag.PlayerCube: return _GetAllPlayerCube_PlayerCubeTag<PlayerCubeTag>(0,filterFunc,out length); break;
}
length = 0;
return new NativeArray<PlayerCubeTag>();
}
internal NativeArray<AssetData> GetAllAssetData(E_EntityOfAssetData entity,FuncEntityFilter<Entity> filterFunc,out int length){
switch(entity){
}
length = 0;
return new NativeArray<AssetData>();
}
internal NativeArray<PlayerData> GetAllPlayerData(E_EntityOfPlayerData entity,FuncEntityFilter<Entity> filterFunc,out int length){
switch(entity){
case E_EntityOfPlayerData.PlayerCube: return _GetAllPlayerCube_PlayerData<PlayerData>(0,filterFunc,out length); break;
}
length = 0;
return new NativeArray<PlayerData>();
}
internal NativeArray<MoveData> GetAllMoveData(E_EntityOfMoveData entity,FuncEntityFilter<Entity> filterFunc,out int length){
switch(entity){
case E_EntityOfMoveData.PlayerCube: return _GetAllPlayerCube_MoveData<MoveData>(0,filterFunc,out length); break;
}
length = 0;
return new NativeArray<MoveData>();
}
internal int CurPlayerCubeCount => _PlayerCubeAry.CurEntityCount;
internal int MaxPlayerCubeIndex => _PlayerCubeAry.Length - 1;
[MethodImpl(MethodImplOptions.AggressiveInlining)] internal unsafe PlayerCube* GetPlayerCube(int index) { return _PlayerCubeAry.GetEntity(index); }
[MethodImpl(MethodImplOptions.AggressiveInlining)] internal unsafe PlayerCube* GetPlayerCube(EntityRef entityRef){
var ptr = _PlayerCubeAry.GetEntity(entityRef._index);
if (ptr->EntityRef != entityRef) return null;
return ptr;
}
}
}
| 0 | 0.822808 | 1 | 0.822808 | game-dev | MEDIA | 0.963807 | game-dev | 0.763594 | 1 | 0.763594 |
Sandrem/FlyCasual | 2,808 | Assets/Scripts/View/UI/Stats/DiceStatsValues.cs | using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class DiceStatsValues : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
for (int i = 1; i < 3; i++)
{
int overallAT = 0;
int overallDT = 0;
int overallAll = 0;
string statsString = DiceStatsTracker.DiceStats[Tools.IntToPlayer(i)].ToString();
string[] statBlocks = statsString.Split('|');
foreach (var statBlock in statBlocks)
{
string[] diceBlock = statBlock.Split('-');
if (diceBlock[0] == "AT") overallAT = int.Parse(diceBlock[1]);
else if (diceBlock[0] == "DT") overallDT = int.Parse(diceBlock[1]);
}
overallAll = overallAT + overallDT;
this.transform.Find("Row" + i + "/T").GetComponent<Text>().text = overallAll.ToString();
foreach (var statBlock in statBlocks)
{
string[] diceBlock = statBlock.Split('-');
string diceStatsText = "";
switch (diceBlock[0])
{
case "AC":
diceStatsText = GenerateDiceStatText(int.Parse(diceBlock[1]), 1f / 8f, overallAT);
break;
case "AE":
case "AB":
diceStatsText = GenerateDiceStatText(int.Parse(diceBlock[1]), 2f / 8f, overallAT);
break;
case "DE":
diceStatsText = GenerateDiceStatText(int.Parse(diceBlock[1]), 2f / 8f, overallDT);
break;
case "AS":
diceStatsText = GenerateDiceStatText(int.Parse(diceBlock[1]), 3f / 8f, overallAT);
break;
case "DS":
case "DB":
diceStatsText = GenerateDiceStatText(int.Parse(diceBlock[1]), 3f / 8f, overallDT);
break;
default:
diceStatsText = diceBlock[1];
break;
}
this.transform.Find("Row" + i + "/" + diceBlock[0]).GetComponent<Text>().text = diceStatsText;
}
}
}
private string GenerateDiceStatText(float realCount, float expectedChance, float overall)
{
float realChance = realCount / overall;
string result = "0";
if (overall != 0) { result = String.Format("{0} ({1:+0.00;-0.00;0.00}%)", realCount, (realChance - expectedChance) * 100); }
return result;
}
// Update is called once per frame
void Update()
{
}
}
| 0 | 0.865304 | 1 | 0.865304 | game-dev | MEDIA | 0.746937 | game-dev | 0.952599 | 1 | 0.952599 |
narknon/WukongB1 | 6,171 | Plugins/CustomLightSystem/Source/CustomLightSystem/Public/CLSLightManager.h | #pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "CLSMaterialParametersCollectionProperty.h"
#include "CLSLightManager.generated.h"
class ACLSVolumeManager;
class ADirectionalLight;
class AExponentialHeightFog;
class ASkyAtmosphere;
class ASkyLight;
class UCLSTagComponent;
class UMaterialParameterCollection;
UCLASS(Blueprintable, NotPlaceable)
class CUSTOMLIGHTSYSTEM_API ACLSLightManager : public AActor {
GENERATED_BODY()
public:
UPROPERTY(BlueprintReadWrite, EditAnywhere, Transient, meta=(AllowPrivateAccess=true))
ACLSVolumeManager* VolumeManager;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
int32 LightManagerID;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
TArray<ADirectionalLight*> DirectionalLightList;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
TArray<ASkyLight*> SkyLightList;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
TArray<ASkyAtmosphere*> AtmosphericFogList;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
TArray<AExponentialHeightFog*> ExponentialHeightFogList;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
float SpeedAlpha;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
bool bIsSwitchActive;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
bool bIsAllActorActive;
UPROPERTY(BlueprintReadWrite, EditAnywhere, Transient, meta=(AllowPrivateAccess=true))
ADirectionalLight* TargetDLight;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
ADirectionalLight* DLight;
UPROPERTY(BlueprintReadWrite, EditAnywhere, Transient, meta=(AllowPrivateAccess=true))
ASkyLight* TargetSLight;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
ASkyLight* SLight;
UPROPERTY(BlueprintReadWrite, EditAnywhere, Transient, meta=(AllowPrivateAccess=true))
ASkyAtmosphere* TargetAFog;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
ASkyAtmosphere* AFog;
UPROPERTY(BlueprintReadWrite, EditAnywhere, Transient, meta=(AllowPrivateAccess=true))
AExponentialHeightFog* TargetEHFog;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
AExponentialHeightFog* EHFog;
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true))
UMaterialParameterCollection* MPC;
UPROPERTY(BlueprintReadWrite, EditAnywhere, Transient, meta=(AllowPrivateAccess=true))
ADirectionalLight* OriginalDirectionalLight;
UPROPERTY(BlueprintReadWrite, EditAnywhere, Transient, meta=(AllowPrivateAccess=true))
ASkyLight* OriginalSkyLight;
UPROPERTY(BlueprintReadWrite, EditAnywhere, Transient, meta=(AllowPrivateAccess=true))
ASkyAtmosphere* OriginalAtmosphericFog;
UPROPERTY(BlueprintReadWrite, EditAnywhere, Transient, meta=(AllowPrivateAccess=true))
AExponentialHeightFog* OriginalExponentialHeightFog;
UPROPERTY(BlueprintReadWrite, EditAnywhere, Transient, meta=(AllowPrivateAccess=true))
float OriginalVloumePercentage;
UPROPERTY(BlueprintReadWrite, EditAnywhere, Transient, meta=(AllowPrivateAccess=true))
ADirectionalLight* TargetDirectionalLight;
UPROPERTY(BlueprintReadWrite, EditAnywhere, Transient, meta=(AllowPrivateAccess=true))
ASkyLight* TargetSkyLight;
UPROPERTY(BlueprintReadWrite, EditAnywhere, Transient, meta=(AllowPrivateAccess=true))
ASkyAtmosphere* TargetAtmosphericFog;
UPROPERTY(BlueprintReadWrite, EditAnywhere, Transient, meta=(AllowPrivateAccess=true))
AExponentialHeightFog* TargetExponentialHeightFog;
UPROPERTY(BlueprintReadWrite, EditAnywhere, Transient, meta=(AllowPrivateAccess=true))
FCLSMaterialParametersCollectionProperty TargetCLSVolumeMPCProperty;
UPROPERTY(BlueprintReadWrite, EditAnywhere, Transient, meta=(AllowPrivateAccess=true))
FCLSMaterialParametersCollectionProperty OriginalCLSVolumeMPCProperty;
UPROPERTY(BlueprintReadWrite, EditAnywhere, Transient, meta=(AllowPrivateAccess=true))
float TargetVolumePercentage;
UPROPERTY(BlueprintReadWrite, EditAnywhere, Transient, meta=(AllowPrivateAccess=true))
float TickTargetVolumePercentage;
UPROPERTY(BlueprintReadWrite, EditAnywhere, Transient, meta=(AllowPrivateAccess=true))
bool bOriginlaVolumeChanged;
ACLSLightManager(const FObjectInitializer& ObjectInitializer);
UFUNCTION(BlueprintCallable)
void SyncLightsAndFogs(ADirectionalLight* InTargetDirectionalLight, ASkyLight* InTargetSkyLight, ASkyAtmosphere* InTargetAtmosphericFog, AExponentialHeightFog* InTargetExponentialHeightFog, FCLSMaterialParametersCollectionProperty InTargetCLSVolumeMPCProperty, FCLSMaterialParametersCollectionProperty InOriginalCLSVolumeMPCProperty, float InTargetVolumePercentage, bool ForceUpdate);
UFUNCTION(BlueprintCallable)
bool SwitchSkyLight(int32 Index);
UFUNCTION(BlueprintCallable)
void SwitchLightAndFog(float Percentage);
UFUNCTION(BlueprintCallable)
bool SwitchExponentialHeightFog(int32 Index);
UFUNCTION(BlueprintCallable)
bool SwitchDirectionalLight(int32 Index);
UFUNCTION(BlueprintCallable)
bool SwitchAtmosphericFog(int32 Index);
UFUNCTION(BlueprintCallable)
bool SwitchAllLightAndFog(int32 Index);
UFUNCTION(BlueprintCallable)
void SetLightManagerActive(bool NewActive);
UFUNCTION(BlueprintCallable)
bool InitializeTagActor(UCLSTagComponent* TagComponent);
UFUNCTION(BlueprintCallable)
void ForceUpdateTagComponents();
UFUNCTION(BlueprintCallable)
void ForceUpdateParameters();
UFUNCTION(BlueprintCallable, BlueprintPure=false)
void DisableAllActor() const;
UFUNCTION(BlueprintCallable)
bool CheckReforenceListValid();
};
| 0 | 0.874751 | 1 | 0.874751 | game-dev | MEDIA | 0.858586 | game-dev | 0.572867 | 1 | 0.572867 |
ReikaKalseki/ChromatiCraft | 2,755 | Auxiliary/RecipeManagers/CastingRecipes/Tiles/AdjacencyRecipe.java | /*******************************************************************************
* @author Reika Kalseki
*
* Copyright 2017
*
* All rights reserved.
* Distribution of the software in any form is only allowed with
* explicit, prior permission from the owner.
******************************************************************************/
package Reika.ChromatiCraft.Auxiliary.RecipeManagers.CastingRecipes.Tiles;
import java.util.Collection;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import Reika.ChromatiCraft.Auxiliary.ChromaStacks;
import Reika.ChromatiCraft.Auxiliary.RecipeManagers.CastingRecipe.PylonCastingRecipe;
import Reika.ChromatiCraft.Base.TileEntity.TileEntityAdjacencyUpgrade;
import Reika.ChromatiCraft.Magic.Progression.ProgressStage;
import Reika.ChromatiCraft.Registry.AdjacencyUpgrades;
import Reika.ChromatiCraft.Registry.CrystalElement;
public class AdjacencyRecipe extends PylonCastingRecipe {
private static final Item[] upgrade = {Items.iron_ingot, Items.iron_ingot, Items.gold_ingot, Items.gold_ingot,
Items.diamond, Items.emerald, Items.nether_star};
private final int tier;
public AdjacencyRecipe(CrystalElement e, int n) {
super(getItem(e, n), getMainItem(e, n));
tier = n;
ItemStack corner = tier == 0 ? new ItemStack(Items.diamond) : new ItemStack(upgrade[tier-1]);
this.addAuxItem(corner, -2, -2);
this.addAuxItem(corner, 2, -2);
this.addAuxItem(corner, 2, 2);
this.addAuxItem(corner, -2, 2);
ItemStack shard = this.getChargedShard(e);
this.addAuxItem(shard, 0, -2);
this.addAuxItem(shard, 2, 0);
this.addAuxItem(shard, 0, 2);
this.addAuxItem(shard, -2, 0);
this.addAuraRequirement(e, 20000*(tier*2+1));
this.addAuraRequirement(CrystalElement.YELLOW, 500*(tier+1));
this.addRuneRingRune(e);
}
@Override
public int getDuration() {
return super.getDuration()*(int)(1+tier/2D);
}
private static ItemStack getMainItem(CrystalElement e, int tier) {
return tier == 0 ? ChromaStacks.crystalStar : getItem(e, tier-1);
}
private static ItemStack getItem(CrystalElement e, int tier) {
return AdjacencyUpgrades.upgrades[e.ordinal()].getStackOfTier(tier);
}
@Override
public int getTypicalCraftedAmount() {
return 32;
}
@Override
public void getRequiredProgress(Collection<ProgressStage> c) {
switch(tier) {
case TileEntityAdjacencyUpgrade.MAX_TIER-1:
c.add(ProgressStage.CTM);
break;
case TileEntityAdjacencyUpgrade.MAX_TIER-2:
c.add(ProgressStage.ALLCORES);
break;
case TileEntityAdjacencyUpgrade.MAX_TIER-3:
c.add(ProgressStage.STRUCTCOMPLETE);
break;
case TileEntityAdjacencyUpgrade.MAX_TIER-4:
c.add(ProgressStage.DIMENSION);
break;
}
}
}
| 0 | 0.915674 | 1 | 0.915674 | game-dev | MEDIA | 0.983011 | game-dev | 0.948309 | 1 | 0.948309 |
esoui/esoui | 15,221 | esoui/libraries/zo_scene/zo_scene.lua | do
local ORIGIN_COLOR =
{
[SCENE_MANAGER_MESSAGE_ORIGIN_PREGAME] = ZO_ColorDef:New(1, 0.6, 0.6),
[SCENE_MANAGER_MESSAGE_ORIGIN_INGAME] = ZO_ColorDef:New(0.6, 1, 0.6),
[SCENE_MANAGER_MESSAGE_ORIGIN_INTERNAL] = ZO_ColorDef:New(0.6, 0.6, 1),
}
function ZO_Scene_GetOriginColor()
return ORIGIN_COLOR[ZO_REMOTE_SCENE_CHANGE_ORIGIN]
end
end
----------
--Scene
----------
local g_loggingEnabled = false
-- Alias
SCENE_SHOWING = ZO_STATE.SHOWING
SCENE_SHOWN = ZO_STATE.SHOWN
SCENE_HIDING = ZO_STATE.HIDING
SCENE_HIDDEN = ZO_STATE.HIDDEN
ZO_Scene = ZO_InitializingCallbackObject:Subclass()
function ZO_Scene:Initialize(name, sceneManager)
self.name = name
self.state = SCENE_HIDDEN
self.sceneManager = sceneManager
self.fragments = {}
self.restoresHUDSceneToggleUIMode = false
self.restoresHUDSceneToggleGameMenu = false
self.disallowEvaluateTransitionCompleteCount = 0
sceneManager:Add(self)
end
function ZO_Scene:AddFragment(fragment)
if not self:HasFragment(fragment) then
table.insert(self.fragments, fragment)
fragment:SetSceneManager(self.sceneManager)
fragment:Refresh()
end
end
function ZO_Scene:RemoveFragment(fragment)
for i = 1, #self.fragments do
if(self.fragments[i] == fragment) then
table.remove(self.fragments, i)
fragment:Refresh()
break
end
end
end
function ZO_Scene:HasFragment(fragment)
for i = 1, #self.fragments do
if(self.fragments[i] == fragment) then
return true
end
end
return false
end
function ZO_Scene:GetFragments()
return self.fragments
end
function ZO_Scene:FragmentIterator(filterFunctions)
return ZO_FilteredNumericallyIndexedTableIterator(self.fragments, filterFunctions)
end
function ZO_Scene:AddTemporaryFragment(fragment)
if not self:HasFragment(fragment) then
if(not self.temporaryFragments) then
self.temporaryFragments = {}
end
self.temporaryFragments[fragment] = true
self:AddFragment(fragment)
fragment:SetSceneManager(self.sceneManager)
fragment:Refresh()
end
end
function ZO_Scene:RemoveTemporaryFragment(fragment)
if self.temporaryFragments and self.temporaryFragments[fragment] then
self.temporaryFragments[fragment] = nil
self:RemoveFragment(fragment)
fragment:Refresh()
end
end
function ZO_Scene:AddFragmentGroup(fragments)
for _, fragment in pairs(fragments) do
self:AddFragment(fragment)
end
end
function ZO_Scene:RemoveFragmentGroup(fragments)
for _, fragment in pairs(fragments) do
self:RemoveFragment(fragment)
end
end
function ZO_Scene:GetName()
return self.name
end
function ZO_Scene:GetState()
return self.state
end
function ZO_Scene:IsShowing()
return self.state == SCENE_SHOWN or self.state == SCENE_SHOWING
end
function ZO_Scene:IsHiding()
return self.state == SCENE_HIDING or self.state == SCENE_HIDDEN
end
function ZO_Scene:HasFragmentWithCategory(category)
return self:GetFragmentWithCategory(category) ~= nil
end
function ZO_Scene:GetFragmentWithCategory(category)
for _, fragment in ipairs(self.fragments) do
local fragmentCategory = fragment:GetCategory()
if(fragmentCategory == category) then
return fragment
end
end
end
function ZO_Scene:SetState(newState)
if self.state ~= newState then
self:Log(string.format("Scene %s", newState))
local oldState = self.state
--Making a local for the scene name so it appears in the traceback in case of errors
local name = self.name
self.sceneManager:OnPreSceneStateChange(self, oldState, newState)
self.state = newState
if self.state == SCENE_SHOWING then
self.wasShownInGamepadPreferredMode = IsInGamepadPreferredMode()
self:UpdateFragmentsToCurrentSceneManager()
end
--We will DetermineIfTransitionIsComplete when calling RefreshFragments below. Allowing DetermineIfTransitionIsComplete before then will not have allowed the fragments to react the scene state change which
--can cause the scene to finish the transition before some fragments even got a chance to try hiding or showing. The specific case that triggered this was removing a temporary fragment in the scene hiding callback.
self:DisallowEvaluateTransitionComplete()
self:FireCallbacks("StateChange", oldState, newState)
self.sceneManager:OnSceneStateChange(self, oldState, newState)
if self.state == SCENE_HIDDEN then
self:RemoveTemporaryFragments()
end
self:AllowEvaluateTransitionComplete()
local AS_A_RESULT_OF_SCENE_STATE_CHANGE = true
self:RefreshFragments(AS_A_RESULT_OF_SCENE_STATE_CHANGE)
end
end
function ZO_Scene:OnRemovedFromQueue()
--Meant to be overriden
end
function ZO_Scene:RemoveTemporaryFragments()
if(self.temporaryFragments) then
for tempFragment in pairs(self.temporaryFragments) do
self:RemoveFragment(tempFragment)
tempFragment:Refresh()
end
self.temporaryFragments = nil
end
end
function ZO_Scene:RefreshFragmentsHelper(asAResultOfSceneStateChange, ...)
local NO_CUSTOM_SHOW_PARAMETER = nil
local NO_CUSTOM_HIDE_PARAMETER = nil
for i = 1, select("#", ...) do
local fragment = select(i, ...)
fragment:Refresh(NO_CUSTOM_SHOW_PARAMETER, NO_CUSTOM_HIDE_PARAMETER, asAResultOfSceneStateChange, self)
end
end
function ZO_Scene:RefreshFragments(asAResultOfSceneStateChange)
--wait until after we have refreshed all fragments to evaluate if we're done
self:DisallowEvaluateTransitionComplete()
--Protect against fragments being added or removed during iteration by unpacking onto the stack
self:RefreshFragmentsHelper(asAResultOfSceneStateChange, unpack(self.fragments))
self:AllowEvaluateTransitionComplete()
self:DetermineIfTransitionIsComplete()
end
function ZO_Scene:UpdateFragmentsToCurrentSceneManager()
for _, fragment in ipairs(self.fragments) do
fragment:SetSceneManager(self.sceneManager)
end
end
function ZO_Scene:OnSceneFragmentStateChange(fragment, oldState, newState)
self:DetermineIfTransitionIsComplete()
end
function ZO_Scene:HideAllHideOnSceneHiddenFragments(...)
local allHiddenImmediately = true
for i = 1, select("#", ...) do
local fragment = select(i, ...)
if fragment:GetHideOnSceneHidden() and not fragment:ComputeIfFragmentShouldShow() then
fragment:Hide()
if fragment:GetState() ~= SCENE_FRAGMENT_HIDDEN then
allHiddenImmediately = false
end
end
end
return allHiddenImmediately
end
function ZO_Scene:IsTransitionComplete()
local hasHideOnSceneHiddenFragments = false
if self.state == SCENE_SHOWING or self.state == SCENE_HIDING then
for _, fragment in ipairs(self.fragments) do
local fragmentState = fragment:GetState()
if self.state == SCENE_SHOWING then
--If we waited for a fragment with a conditional to show before considering the scene shown we may wait forever,
--because the conditional may not be true. So we just ignore them on show.
if not fragment:HasConditional() and fragmentState ~= SCENE_FRAGMENT_SHOWN then
return false
end
elseif self.state == SCENE_HIDING then
if fragmentState == SCENE_FRAGMENT_HIDING then
if fragment:GetHideOnSceneHidden() then
hasHideOnSceneHiddenFragments = true
else
return false
end
end
end
end
end
if hasHideOnSceneHiddenFragments then
--dont evaluate whether we should transition as a result of hiding a fragment here
--since we're already evaluating that right now and will return the correct result
self:DisallowEvaluateTransitionComplete()
--Protect against fragments being added or removed during iteration by unpacking onto the stack
local allHiddenImmediately = self:HideAllHideOnSceneHiddenFragments(unpack(self.fragments))
self:AllowEvaluateTransitionComplete()
return allHiddenImmediately
end
return true
end
function ZO_Scene:AllowEvaluateTransitionComplete()
self.disallowEvaluateTransitionCompleteCount = self.disallowEvaluateTransitionCompleteCount - 1
end
function ZO_Scene:DisallowEvaluateTransitionComplete()
self.disallowEvaluateTransitionCompleteCount = self.disallowEvaluateTransitionCompleteCount + 1
end
function ZO_Scene:DetermineIfTransitionIsComplete()
if self.disallowEvaluateTransitionCompleteCount ~= 0 then
return
end
local nextState = nil
if self.state == SCENE_SHOWING then
nextState = SCENE_SHOWN
elseif self.state == SCENE_HIDING then
nextState = SCENE_HIDDEN
end
if not nextState then
return
end
if self:IsTransitionComplete() then
self:OnTransitionComplete(nextState)
end
end
function ZO_Scene:OnTransitionComplete(nextState)
self:SetState(nextState)
end
function ZO_Scene:GetSceneGroup()
return self.sceneGroup
end
function ZO_Scene:SetSceneGroup(sceneGroup)
self.sceneGroup = sceneGroup
end
function ZO_Scene:SetHideSceneConfirmationCallback(callback)
self.hideSceneConfirmationCallback = callback
end
function ZO_Scene:HasHideSceneConfirmation()
return self.hideSceneConfirmationCallback ~= nil
end
function ZO_Scene:ConfirmHideScene(nextSceneName, push, nextSceneClearsSceneStack, numScenesNextScenePops, bypassHideSceneConfirmationReason)
self.hideSceneConfirmationNextSceneName = nextSceneName
self.hideSceneConfirmationPush = push
self.hideSceneConfirmationNextSceneClearsSceneStack = nextSceneClearsSceneStack
self.hideSceneConfirmationNumScenesNextScenePops = numScenesNextScenePops
self.hideSceneConfirmationCallback(self, nextSceneName, bypassHideSceneConfirmationReason)
end
local function ClearHideSceneConfirmationState(self)
self.hideSceneConfirmationNextSceneName = nil
self.hideSceneConfirmationPush = nil
self.hideSceneConfirmationNextSceneClearsSceneStack = nil
self.hideSceneConfirmationNumScenesNextScenePops = nil
self:UnregisterAllCallbacks("HideSceneConfirmationResult")
end
function ZO_Scene:AcceptHideScene()
local nextSceneName = self.hideSceneConfirmationNextSceneName
local push = self.hideSceneConfirmationPush
local nextSceneClearsSceneStack = self.hideSceneConfirmationNextSceneClearsSceneStack
local numScenesNextScenePops = self.hideSceneConfirmationNumScenesNextScenePops
self:FireCallbacks("HideSceneConfirmationResult", true)
ClearHideSceneConfirmationState(self)
SCENE_MANAGER:Show(nextSceneName, push, nextSceneClearsSceneStack, numScenesNextScenePops, ZO_BHSCR_ALREADY_SEEN)
end
function ZO_Scene:RejectHideScene()
self:FireCallbacks("HideSceneConfirmationResult", false)
ClearHideSceneConfirmationState(self)
end
function ZO_Scene:SetInputPreferredMode(mode)
self.inputPreferredMode = mode
end
function ZO_Scene:WasShownInGamepadPreferredMode()
return self.wasShownInGamepadPreferredMode
end
function ZO_Scene:WasRequestedToShowInGamepadPreferredMode()
return self.wasRequestedToShowInGamepadPreferredMode or self.inputPreferredMode == INPUT_PREFERRED_MODE_ALWAYS_GAMEPAD
end
function ZO_Scene:SetWasRequestedToShowInGamepadPreferredMode(gamepad)
self.wasRequestedToShowInGamepadPreferredMode = gamepad
end
function ZO_Scene:IsRemoteScene()
return false
end
function ZO_Scene:DoesSceneRestoreHUDSceneFromToggleUIMode()
return self.restoresHUDSceneToggleUIMode
end
function ZO_Scene:DoesSceneRestoreHUDSceneFromToggleGameMenu()
return self.restoresHUDSceneToggleGameMenu
end
function ZO_Scene:SetSceneRestoreHUDSceneToggleUIMode(restoreScene)
self.restoresHUDSceneToggleUIMode = restoreScene
end
function ZO_Scene:SetSceneRestoreHUDSceneToggleGameMenu(restoreScene)
self.restoresHUDSceneToggleGameMenu = restoreScene
end
function ZO_Scene:SetHandleGamepadPreferredModeChangedCallback(handleGamepadPreferredModeChangedCallback)
self.handleGamepadPreferredModeChangedCallback = handleGamepadPreferredModeChangedCallback
end
function ZO_Scene:GetHandleGamepadPreferredModeChangedCallback()
return self.handleGamepadPreferredModeChangedCallback
end
function ZO_Scene:Log(message)
if WriteToInterfaceLog and g_loggingEnabled then
WriteToInterfaceLog(string.format("%s - %s - %s", ZO_Scene_GetOriginColor():Colorize(GetString("SI_SCENEMANAGERMESSAGEORIGIN", ZO_REMOTE_SCENE_CHANGE_ORIGIN)), self.name, message))
end
end
----------
--Remote Scene
----------
ZO_RemoteScene = ZO_Scene:Subclass()
function ZO_RemoteScene:New(...)
return ZO_Scene.New(self, ...)
end
function ZO_RemoteScene:Initialize(name, sceneManager)
ZO_Scene.Initialize(self, name, sceneManager)
self.waitingOnRemoteFragmentTransition = false
self.fragmentsFinishedTransition = false
end
function ZO_RemoteScene:SetState(newState)
if self.state ~= newState then
if newState == SCENE_HIDING or newState == SCENE_SHOWING then
self.waitingOnRemoteFragmentTransition = true
self.fragmentsFinishedTransition = false
else
self.waitingOnRemoteFragmentTransition = false
end
-- call parent SetState after we send out message because it could
-- trigger another call to SetState and the events would be out of order
ZO_Scene.SetState(self, newState)
end
end
function ZO_RemoteScene:OnTransitionComplete(nextState)
self.fragmentsFinishedTransition = true
self:Log("Local Fragments Done Transitioning")
SCENE_MANAGER:SendFragmentCompleteMessage()
-- we are done, but some remote scene might not have reported that it is also done
-- only set the state if both scenes have completed their transition
if not self.waitingOnRemoteFragmentTransition then
ZO_Scene.OnTransitionComplete(self, nextState)
end
end
function ZO_RemoteScene:IsRemoteScene()
return true
end
function ZO_RemoteScene:SetSequenceNumber(sequenceNumber)
self.sequenceNumber = sequenceNumber
end
function ZO_RemoteScene:GetSequenceNumber()
return self.sequenceNumber
end
function ZO_RemoteScene:AreFragmentsDoneTransitioning()
return self.fragmentsFinishedTransition
end
function ZO_RemoteScene:OnRemoteSceneFinishedFragmentTransition(sequenceNumber)
if self.waitingOnRemoteFragmentTransition then
self:Log("Was Notified Remote Fragments Complete")
if self:GetSequenceNumber() == sequenceNumber then
self.waitingOnRemoteFragmentTransition = false
self:DetermineIfTransitionIsComplete()
else
self:Log(string.format("Sequence Numbers did not match. Expected %d, got %d", self:GetSequenceNumber(), sequenceNumber))
end
end
end
| 0 | 0.926633 | 1 | 0.926633 | game-dev | MEDIA | 0.64011 | game-dev | 0.937381 | 1 | 0.937381 |
Secrets-of-Sosaria/World | 2,039 | Data/Scripts/Magic/Knight/DivineFury.cs | using System;
using System.Collections;
using Server.Network;
using Server.Items;
using Server.Targeting;
namespace Server.Spells.Chivalry
{
public class DivineFurySpell : PaladinSpell
{
private static SpellInfo m_Info = new SpellInfo(
"Divine Fury", "Divinum Furis",
-1,
9002
);
public override TimeSpan CastDelayBase { get { return TimeSpan.FromSeconds( 1.0 ); } }
public override double RequiredSkill{ get{ return 25.0; } }
public override int RequiredMana{ get{ return 15; } }
public override int RequiredTithing{ get{ return 10; } }
public override int MantraNumber{ get{ return 1060722; } } // Divinum Furis
public override bool BlocksMovement{ get{ return false; } }
public DivineFurySpell( Mobile caster, Item scroll ) : base( caster, scroll, m_Info )
{
}
public override void OnCast()
{
if ( CheckSequence() )
{
Caster.PlaySound( 0x20F );
Caster.PlaySound( Caster.Female ? 0x338 : 0x44A );
Caster.FixedParticles( 0x376A, 1, 31, 9961, 1160, 0, EffectLayer.Waist );
Caster.FixedParticles( 0x37C4, 1, 31, 9502, 43, 2, EffectLayer.Waist );
Caster.Stam = Caster.StamMax;
Timer t = (Timer)m_Table[Caster];
if ( t != null )
t.Stop();
int delay = ComputePowerValue( 10 );
// TODO: Should caps be applied?
if ( delay < 7 )
delay = 7;
else if ( delay > 24 )
delay = 24;
m_Table[Caster] = t = Timer.DelayCall( TimeSpan.FromSeconds( delay ), new TimerStateCallback( Expire_Callback ), Caster );
Caster.Delta( MobileDelta.WeaponDamage );
BuffInfo.AddBuff(Caster, new BuffInfo(BuffIcon.DivineFury, 1060589, 1075634, TimeSpan.FromSeconds(delay), Caster));
}
FinishSequence();
}
private static Hashtable m_Table = new Hashtable();
public static bool UnderEffect( Mobile m )
{
return m_Table.Contains( m );
}
private static void Expire_Callback( object state )
{
Mobile m = (Mobile)state;
m_Table.Remove( m );
m.Delta( MobileDelta.WeaponDamage );
m.PlaySound( 0xF8 );
}
}
} | 0 | 0.938352 | 1 | 0.938352 | game-dev | MEDIA | 0.94403 | game-dev | 0.986268 | 1 | 0.986268 |
vattam/BSDGames | 3,222 | trek/compkl.c | /* $NetBSD: compkl.c,v 1.6 2004/01/27 20:30:30 jsm Exp $ */
/*
* Copyright (c) 1980, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include <sys/cdefs.h>
#ifndef lint
#if 0
static char sccsid[] = "@(#)compkl.c 8.1 (Berkeley) 5/31/93";
#else
__RCSID("$NetBSD: compkl.c,v 1.6 2004/01/27 20:30:30 jsm Exp $");
#endif
#endif /* not lint */
#include <math.h>
#include "trek.h"
/*
** compute klingon distances
**
** The klingon list has the distances for all klingons recomputed
** and sorted. The parameter is a Boolean flag which is set if
** we have just entered a new quadrant.
**
** This routine is used every time the Enterprise or the Klingons
** move.
*/
static void sortkl(void);
void
compkldist(f)
int f; /* set if new quadrant */
{
int i, dx, dy;
double d;
double temp;
if (Etc.nkling == 0)
return;
for (i = 0; i < Etc.nkling; i++)
{
/* compute distance to the Klingon */
dx = Ship.sectx - Etc.klingon[i].x;
dy = Ship.secty - Etc.klingon[i].y;
d = dx * dx + dy * dy;
d = sqrt(d);
/* compute average of new and old distances to Klingon */
if (!f)
{
temp = Etc.klingon[i].dist;
Etc.klingon[i].avgdist = 0.5 * (temp + d);
}
else
{
/* new quadrant: average is current */
Etc.klingon[i].avgdist = d;
}
Etc.klingon[i].dist = d;
}
/* leave them sorted */
sortkl();
}
/*
** sort klingons
**
** bubble sort on ascending distance
*/
static void
sortkl()
{
struct kling t;
int f, i, m;
m = Etc.nkling - 1;
f = 1;
while (f)
{
f = 0;
for (i = 0; i < m; i++)
if (Etc.klingon[i].dist > Etc.klingon[i+1].dist)
{
t = Etc.klingon[i];
Etc.klingon[i] = Etc.klingon[i+1];
Etc.klingon[i+1] = t;
f = 1;
}
}
}
| 0 | 0.588359 | 1 | 0.588359 | game-dev | MEDIA | 0.309303 | game-dev | 0.680526 | 1 | 0.680526 |
Creators-of-Create/Create | 5,567 | src/main/java/com/simibubi/create/content/equipment/blueprint/BlueprintScreen.java | package com.simibubi.create.content.equipment.blueprint;
import com.google.common.collect.ImmutableList;
import com.simibubi.create.AllPackets;
import com.simibubi.create.AllPartialModels;
import com.simibubi.create.content.logistics.filter.FilterScreenPacket;
import com.simibubi.create.content.logistics.filter.FilterScreenPacket.Option;
import com.simibubi.create.foundation.gui.AllGuiTextures;
import com.simibubi.create.foundation.gui.AllIcons;
import com.simibubi.create.foundation.gui.menu.AbstractSimiContainerScreen;
import com.simibubi.create.foundation.gui.widget.IconButton;
import com.simibubi.create.foundation.utility.CreateLang;
import net.createmod.catnip.gui.element.GuiGameElement;
import net.minecraft.ChatFormatting;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.renderer.Rect2i;
import net.minecraft.network.chat.Component;
import net.minecraft.world.entity.player.Inventory;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import static com.simibubi.create.foundation.gui.AllGuiTextures.PLAYER_INVENTORY;
public class BlueprintScreen extends AbstractSimiContainerScreen<BlueprintMenu> {
protected AllGuiTextures background;
private List<Rect2i> extraAreas = Collections.emptyList();
private IconButton resetButton;
private IconButton confirmButton;
public BlueprintScreen(BlueprintMenu menu, Inventory inv, Component title) {
super(menu, inv, title);
this.background = AllGuiTextures.BLUEPRINT;
}
@Override
protected void init() {
setWindowSize(background.getWidth(), background.getHeight() + 4 + PLAYER_INVENTORY.getHeight());
setWindowOffset(1, 0);
super.init();
int x = leftPos;
int y = topPos;
resetButton = new IconButton(x + background.getWidth() - 62, y + background.getHeight() - 24, AllIcons.I_TRASH);
resetButton.withCallback(() -> {
menu.clearContents();
contentsCleared();
menu.sendClearPacket();
});
confirmButton = new IconButton(x + background.getWidth() - 33, y + background.getHeight() - 24, AllIcons.I_CONFIRM);
confirmButton.withCallback(() -> {
minecraft.player.closeContainer();
});
addRenderableWidget(resetButton);
addRenderableWidget(confirmButton);
extraAreas = ImmutableList.of(new Rect2i(x + background.getWidth(), y + background.getHeight() - 36, 56, 44));
}
@Override
protected void renderBg(GuiGraphics graphics, float partialTicks, int mouseX, int mouseY) {
int invX = getLeftOfCentered(PLAYER_INVENTORY.getWidth());
int invY = topPos + background.getHeight() + 4;
renderPlayerInventory(graphics, invX, invY);
int x = leftPos;
int y = topPos;
background.render(graphics, x, y);
graphics.drawString(font, title, x + 15, y + 4, 0xFFFFFF, false);
GuiGameElement.of(AllPartialModels.CRAFTING_BLUEPRINT_1x1).<GuiGameElement
.GuiRenderBuilder>at(x + background.getWidth() + 20, y + background.getHeight() - 32, 0)
.rotate(45, -45, 22.5f)
.scale(40)
.render(graphics);
}
@Override
protected void renderTooltip(GuiGraphics graphics, int x, int y) {
if (!menu.getCarried()
.isEmpty() || this.hoveredSlot == null || hoveredSlot.container == menu.playerInventory) {
super.renderTooltip(graphics, x, y);
return;
}
List<Component> list = new LinkedList<>();
if (hoveredSlot.hasItem())
list = getTooltipFromContainerItem(hoveredSlot.getItem());
graphics.renderComponentTooltip(font, addToTooltip(list, hoveredSlot.getSlotIndex(), true), x, y);
}
private List<Component> addToTooltip(List<Component> list, int slot, boolean isEmptySlot) {
if (slot < 0 || slot > 10)
return list;
if (slot < 9) {
list.add(CreateLang.translateDirect("crafting_blueprint.crafting_slot")
.withStyle(ChatFormatting.GOLD));
if (isEmptySlot)
list.add(CreateLang.translateDirect("crafting_blueprint.filter_items_viable")
.withStyle(ChatFormatting.GRAY));
} else if (slot == 9) {
list.add(CreateLang.translateDirect("crafting_blueprint.display_slot")
.withStyle(ChatFormatting.GOLD));
if (!isEmptySlot)
list.add(CreateLang
.translateDirect(
"crafting_blueprint." + (menu.contentHolder.inferredIcon ? "inferred" : "manually_assigned"))
.withStyle(ChatFormatting.GRAY));
} else if (slot == 10) {
list.add(CreateLang.translateDirect("crafting_blueprint.secondary_display_slot")
.withStyle(ChatFormatting.GOLD));
if (isEmptySlot)
list.add(CreateLang.translateDirect("crafting_blueprint.optional")
.withStyle(ChatFormatting.GRAY));
}
return list;
}
@Override
protected void containerTick() {
if (!menu.contentHolder.isEntityAlive())
menu.player.closeContainer();
super.containerTick();
// handleTooltips();
}
// protected void handleTooltips() {
// List<IconButton> tooltipButtons = getTooltipButtons();
//
// for (IconButton button : tooltipButtons) {
// if (!button.getToolTip()
// .isEmpty()) {
// button.setToolTip(button.getToolTip()
// .get(0));
// button.getToolTip()
// .add(TooltipHelper.holdShift(Palette.Yellow, hasShiftDown()));
// }
// }
//
// if (hasShiftDown()) {
// List<IFormattableTextComponent> tooltipDescriptions = getTooltipDescriptions();
// for (int i = 0; i < tooltipButtons.size(); i++)
// fillToolTip(tooltipButtons.get(i), tooltipDescriptions.get(i));
// }
// }
protected void contentsCleared() {}
protected void sendOptionUpdate(Option option) {
AllPackets.getChannel().sendToServer(new FilterScreenPacket(option));
}
@Override
public List<Rect2i> getExtraAreas() {
return extraAreas;
}
}
| 0 | 0.855188 | 1 | 0.855188 | game-dev | MEDIA | 0.978109 | game-dev | 0.971143 | 1 | 0.971143 |
Aizistral-Studios/Enigmatic-Legacy | 3,595 | src/main/java/com/aizistral/enigmaticlegacy/items/MonsterCharm.java | package com.aizistral.enigmaticlegacy.items;
import java.util.List;
import javax.annotation.Nullable;
import com.aizistral.enigmaticlegacy.EnigmaticLegacy;
import com.aizistral.enigmaticlegacy.api.generic.SubscribeConfig;
import com.aizistral.enigmaticlegacy.helpers.ItemLoreHelper;
import com.aizistral.enigmaticlegacy.items.generic.ItemBaseCurio;
import com.aizistral.omniconfig.wrappers.Omniconfig;
import com.aizistral.omniconfig.wrappers.OmniconfigWrapper;
import net.minecraft.ChatFormatting;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.damagesource.DamageSource;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Rarity;
import net.minecraft.world.item.TooltipFlag;
import net.minecraft.world.level.Level;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import top.theillusivec4.curios.api.SlotContext;
public class MonsterCharm extends ItemBaseCurio {
public static Omniconfig.PerhapsParameter undeadDamageBonus;
public static Omniconfig.PerhapsParameter hostileDamageBonus;
public static Omniconfig.BooleanParameter bonusLootingEnabled;
public static Omniconfig.BooleanParameter doubleXPEnabled;
@SubscribeConfig
public static void onConfig(OmniconfigWrapper builder) {
builder.pushPrefix("MonsterCharm");
undeadDamageBonus = builder
.comment("Damage bonus against undead enemies for Emblem of Monster Slayer. Defined as percentage.")
.max(1000)
.getPerhaps("UndeadDamage", 25);
hostileDamageBonus = builder
.comment("Damage bonus against agressive creatures for Emblem of Monster Slayer. Defined as percentage.")
.max(1000)
.getPerhaps("HostileDamage", 10);
bonusLootingEnabled = builder
.comment("Whether or not Emblem of Monster Slayer should provide +1 Looting Level.")
.getBoolean("BonusLooting", true);
doubleXPEnabled = builder
.comment("Whether or not Emblem of Monster Slayer should provide double experience drop from monsters.")
.getBoolean("DoubleXP", true);
builder.popPrefix();
}
public float bonusXPModifier = 2.0F;
public MonsterCharm() {
super(ItemBaseCurio.getDefaultProperties().rarity(Rarity.EPIC));
}
@Override
@OnlyIn(Dist.CLIENT)
public void appendHoverText(ItemStack stack, @Nullable Level worldIn, List<Component> list, TooltipFlag flagIn) {
ItemLoreHelper.addLocalizedString(list, "tooltip.enigmaticlegacy.void");
if (Screen.hasShiftDown()) {
ItemLoreHelper.addLocalizedString(list, "tooltip.enigmaticlegacy.monsterCharm1", ChatFormatting.GOLD, undeadDamageBonus.getValue().asPercentage() + "%");
ItemLoreHelper.addLocalizedString(list, "tooltip.enigmaticlegacy.monsterCharm2", ChatFormatting.GOLD, hostileDamageBonus.getValue().asPercentage() + "%");
if (bonusLootingEnabled.getValue()) {
ItemLoreHelper.addLocalizedString(list, "tooltip.enigmaticlegacy.monsterCharm3");
}
if (doubleXPEnabled.getValue()) {
ItemLoreHelper.addLocalizedString(list, "tooltip.enigmaticlegacy.void");
ItemLoreHelper.addLocalizedString(list, "tooltip.enigmaticlegacy.monsterCharm4");
}
} else {
ItemLoreHelper.addLocalizedString(list, "tooltip.enigmaticlegacy.holdShift");
}
}
@Override
public int getLootingLevel(SlotContext slotContext, DamageSource source, LivingEntity target, int baseLooting, ItemStack curio) {
return super.getLootingLevel(slotContext, source, target, baseLooting, curio) + 1;
}
}
| 0 | 0.897494 | 1 | 0.897494 | game-dev | MEDIA | 0.931749 | game-dev | 0.961151 | 1 | 0.961151 |
gabber235/Typewriter | 2,656 | extensions/EntityExtension/src/main/kotlin/com/typewritermc/entity/entries/entity/minecraft/DroppedItemEntity.kt | package com.typewritermc.entity.entries.entity.minecraft
import com.github.retrooper.packetevents.protocol.entity.type.EntityTypes
import com.typewritermc.core.books.pages.Colors
import com.typewritermc.core.entries.Ref
import com.typewritermc.core.entries.emptyRef
import com.typewritermc.core.extension.annotations.Entry
import com.typewritermc.core.extension.annotations.OnlyTags
import com.typewritermc.core.extension.annotations.Tags
import com.typewritermc.core.utils.point.Position
import com.typewritermc.engine.paper.entry.entity.FakeEntity
import com.typewritermc.engine.paper.entry.entity.SimpleEntityDefinition
import com.typewritermc.engine.paper.entry.entity.SimpleEntityInstance
import com.typewritermc.engine.paper.entry.entries.*
import com.typewritermc.engine.paper.utils.Sound
import com.typewritermc.entity.entries.data.minecraft.applyGenericEntityData
import com.typewritermc.entity.entries.data.minecraft.display.item.ItemProperty
import com.typewritermc.entity.entries.data.minecraft.display.item.applyItemData
import com.typewritermc.entity.entries.entity.WrapperFakeEntity
import org.bukkit.entity.Player
@Entry("dropped_item_entity_definition", "A dropped item entity", Colors.ORANGE, "material-symbols:pin-drop")
@Tags("dropped_item_entity_definition")
class DroppedItemEntityDefinition(
override val id: String = "",
override val name: String = "",
override val displayName: Var<String> = ConstVar(""),
override val sound: Var<Sound> = ConstVar(Sound.EMPTY),
@OnlyTags("generic_entity_data", "item_data")
override val data: List<Ref<EntityData<*>>> = emptyList(),
) : SimpleEntityDefinition {
override fun create(player: Player): FakeEntity {
return DroppedItemEntity(player)
}
}
@Entry("dropped_item_entity_instance", "An instance of a dropped item entity", Colors.YELLOW, "material-symbols:pin-drop")
class DroppedItemEntityInstance(
override val id: String = "",
override val name: String = "",
override val definition: Ref<DroppedItemEntityDefinition> = emptyRef(),
override val spawnLocation: Position = Position.ORIGIN,
@OnlyTags("generic_entity_data", "item_data")
override val data: List<Ref<EntityData<*>>> = emptyList(),
override val activity: Ref<out EntityActivityEntry> = emptyRef(),
) : SimpleEntityInstance
class DroppedItemEntity(player: Player) : WrapperFakeEntity(
EntityTypes.ITEM,
player,
) {
override fun applyProperty(property: EntityProperty) {
when (property) {
is ItemProperty -> applyItemData(entity, property, player)
}
if (applyGenericEntityData(entity, property)) return
}
}
| 0 | 0.808235 | 1 | 0.808235 | game-dev | MEDIA | 0.987 | game-dev | 0.866275 | 1 | 0.866275 |
ScreamingSandals/BedWars | 3,196 | plugin/common/src/main/java/org/screamingsandals/bedwars/special/AutoIgniteableTNTImpl.java | /*
* Copyright (C) 2025 ScreamingSandals
*
* This file is part of Screaming BedWars.
*
* Screaming BedWars 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.
*
* Screaming BedWars 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 Screaming BedWars. If not, see <https://www.gnu.org/licenses/>.
*/
package org.screamingsandals.bedwars.special;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import org.screamingsandals.bedwars.api.special.AutoIgniteableTNT;
import org.screamingsandals.bedwars.entities.EntitiesManagerImpl;
import org.screamingsandals.bedwars.game.GameImpl;
import org.screamingsandals.bedwars.game.TeamImpl;
import org.screamingsandals.bedwars.player.BedWarsPlayer;
import org.screamingsandals.lib.api.types.server.LocationHolder;
import org.screamingsandals.lib.entity.PrimedTnt;
import org.screamingsandals.lib.entity.type.EntityType;
import org.screamingsandals.lib.tasker.DefaultThreads;
import org.screamingsandals.lib.tasker.Tasker;
import org.screamingsandals.lib.tasker.TaskerTime;
import org.screamingsandals.lib.world.Location;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
@Getter
@EqualsAndHashCode(callSuper = true)
public class AutoIgniteableTNTImpl extends SpecialItemImpl implements AutoIgniteableTNT {
public static final Map<Integer, UUID> PROTECTED_PLAYERS = new ConcurrentHashMap<>();
private final int explosionTime;
private final float damage;
private final boolean allowedDamagingPlacer;
public AutoIgniteableTNTImpl(GameImpl game, BedWarsPlayer player, TeamImpl team, int explosionTime, boolean damagePlacer, float damage) {
super(game, player, team);
this.explosionTime = explosionTime;
this.allowedDamagingPlacer = damagePlacer;
this.damage = damage;
}
@Override
public void spawn(LocationHolder location) {
spawn(location.as(Location.class));
}
public void spawn(Location location) {
var tnt = Objects.requireNonNull(EntityType.of("tnt").spawn(location, en -> {
var tnt1 = (PrimedTnt) en;
tnt1.yield(damage);
tnt1.fuseTicks(explosionTime * 20);
if (!allowedDamagingPlacer) {
PROTECTED_PLAYERS.put(tnt1.getEntityId(), player.getUuid());
}
}));
EntitiesManagerImpl.getInstance().addEntityToGame(tnt, game);
Tasker.runDelayed(DefaultThreads.GLOBAL_THREAD, () -> {
EntitiesManagerImpl.getInstance().removeEntityFromGame(tnt);
AutoIgniteableTNTImpl.PROTECTED_PLAYERS.remove(tnt.getEntityId());
}, explosionTime + 10, TaskerTime.TICKS);
}
}
| 0 | 0.95258 | 1 | 0.95258 | game-dev | MEDIA | 0.929332 | game-dev | 0.99101 | 1 | 0.99101 |
mdechatech/Sonic-Realms | 5,446 | Assets/Scripts/SonicRealms/Core/Moves/AirControl.cs | using SonicRealms.Core.Utils;
using UnityEngine;
namespace SonicRealms.Core.Moves
{
public class AirControl : Move
{
#region Control Fields
/// <summary>
/// The name of the input axis.
/// </summary>
[ControlFoldout]
[Tooltip("The name of the input axis.")]
public string MovementAxis;
/// <summary>
/// Whether to invert the axis input.
/// </summary>
[ControlFoldout]
[Tooltip("Whether to invert the axis input.")]
public bool InvertAxis;
#endregion
#region Physics Fields
/// <summary>
/// Air acceleration in units per second squared.
/// </summary>
[SerializeField, PhysicsFoldout]
[Tooltip("Air acceleration in units per second squared.")]
public float Acceleration;
/// <summary>
/// Air deceleration in units per second squared.
/// </summary>
[SerializeField, PhysicsFoldout]
[Tooltip("Air deceleration in units per second squared.")]
public float Deceleration;
/// <summary>
/// Top air speed in units per second.
/// </summary>
[SerializeField, PhysicsFoldout]
[Tooltip("Top air speed in units per second.")]
public float TopSpeed;
#endregion
/// <summary>
/// If true, disables input.
/// </summary>
[HideInInspector]
public bool ControlLock;
private float _axis;
public override MoveLayer Layer
{
get { return MoveLayer.Control; }
}
public override void Reset()
{
base.Reset();
MovementAxis = "Horizontal";
InvertAxis = false;
Acceleration = 3.375f;
Deceleration = 3.375f;
TopSpeed = 3.6f;
}
public override void Awake()
{
base.Awake();
_axis = 0.0f;
}
public override void OnManagerAdd()
{
if (!Controller.Grounded) Perform(true);
Controller.OnDetach.AddListener(OnDetach);
}
public void OnDetach()
{
Perform();
}
public override void OnActiveEnter()
{
Manager.End<GroundControl>();
}
public override void OnActiveUpdate()
{
if (ControlLock) _axis = 0.0f;
else _axis = InvertAxis ? -Input.GetAxis(MovementAxis) : Input.GetAxis(MovementAxis);
if (DMath.Equalsf(_axis)) return;
Controller.FacingForward = _axis > 0.0f;
}
public override void OnActiveFixedUpdate()
{
Accelerate(_axis);
}
/// <summary>
/// Accelerates the controller forward.
/// </summary>
/// <param name="magnitude">A value between 0 and 1, 0 being no acceleration and 1 being the amount
/// defined by Acceleration.</param>
public void AccelerateForward(float magnitude = 1.0f)
{
Accelerate(magnitude);
}
/// <summary>
/// Accelerates the controller backward.
/// </summary>
/// <param name="magnitude">A value between 0 and 1, 0 being no acceleration and 1 being the amount
/// defined by Acceleration.</param>
public void AccelerateBackward(float magnitude = 1.0f)
{
Accelerate(-magnitude);
}
/// <summary>
/// Accelerates the controller using Time.fixedDeltaTime as the timestep.
/// </summary>
/// <param name="magnitude">A value between -1 and 1, positive moving it forward and negative moving
/// it back.</param>
public void Accelerate(float magnitude)
{
Accelerate(magnitude, Time.deltaTime);
}
/// <summary>
/// Accelerates the controller.
/// </summary>
/// <param name="magnitude">A value between -1 and 1, positive moving it forward and negative moving
/// it back.</param>
/// <param name="timestep">The timestep, in seconds</param>
public void Accelerate(float magnitude, float timestep)
{
if(DMath.Equalsf(magnitude)) return;
magnitude = Mathf.Clamp(magnitude, -1.0f, 1.0f);
if (magnitude < 0.0f)
{
var xNew = Controller.RelativeVelocity.x;
if (Controller.RelativeVelocity.x > 0.0f)
{
xNew += Deceleration*magnitude*timestep;
}
else if (Controller.RelativeVelocity.x > -TopSpeed)
{
xNew += Acceleration*magnitude*timestep;
}
Controller.RelativeVelocity = new Vector2(xNew, Controller.RelativeVelocity.y);
}
else if (magnitude > 0.0f)
{
var xNew = Controller.RelativeVelocity.x;
if (Controller.RelativeVelocity.x < 0.0f)
{
xNew += Deceleration*magnitude*timestep;
}
else if (Controller.RelativeVelocity.x < TopSpeed)
{
xNew += Acceleration*magnitude*timestep;
}
Controller.RelativeVelocity = new Vector2(xNew, Controller.RelativeVelocity.y);
}
}
}
}
| 0 | 0.859006 | 1 | 0.859006 | game-dev | MEDIA | 0.943139 | game-dev | 0.928129 | 1 | 0.928129 |
ForkGG/Fork | 1,289 | Frontend/Razor/Components/Entity/Tabs/ConsoleTab/Playerlist/Banlist.razor | @using ForkCommon.Model.Entity.Pocos
@using ForkCommon.Model.Entity.Pocos.Player
@using ForkFrontend.Logic.Services.Managers
@implements ISimplePlayerlist
<div class="h-full bg-new-panel pt-3">
@* Ban count *@
<span class="px-7 py-3 text-label-hover">@(Server?.Banlist.Count ?? 0) - Banned</span>
@* Player list *@
<div class="h-full overflow-y-auto mt-3">
@if (Server?.Banlist != null)
{
Server.Banlist.Sort();
foreach (Player? player in Server.Banlist)
{
<CascadingValue Value="this">
<PlayerComponent Value="player"></PlayerComponent>
</CascadingValue>
}
}
</div>
</div>
@code {
[CascadingParameter] public EntityStateManager? EntityState { get; set; }
private Server? Server => EntityState?.Entity as Server;
public Player? ActivePlayer { get; set; }
public void SelectPlayer(PlayerComponent playerComponent)
{
ActivePlayer = playerComponent.Value;
StateHasChanged();
}
protected override void OnInitialized()
{
EntityState!.UpdateBanlistPlayerNotificationHandler.After += _ =>
{
StateHasChanged();
return Task.CompletedTask;
};
}
} | 0 | 0.862555 | 1 | 0.862555 | game-dev | MEDIA | 0.736347 | game-dev | 0.947387 | 1 | 0.947387 |
ServUO/ServUO | 18,573 | Scripts/Items/Functional/BaseDoor.cs | using System;
using System.Collections.Generic;
using Server.Commands;
using Server.Network;
using Server.Targeting;
namespace Server.Items
{
public abstract class BaseDoor : Item, ILockable, ITelekinesisable
{
private static readonly Point3D[] m_Offsets = new Point3D[]
{
new Point3D(-1, 1, 0),
new Point3D(1, 1, 0),
new Point3D(-1, 0, 0),
new Point3D(1,-1, 0),
new Point3D(1, 1, 0),
new Point3D(1,-1, 0),
new Point3D(0, 0, 0),
new Point3D(0,-1, 0),
new Point3D(0, 0, 0),
new Point3D(0, 0, 0),
new Point3D(0, 0, 0),
new Point3D(0, 0, 0)
};
private bool m_Open, m_Locked;
private int m_OpenedID, m_OpenedSound;
private int m_ClosedID, m_ClosedSound;
private Point3D m_Offset;
private BaseDoor m_Link;
private uint m_KeyValue;
private Timer m_Timer;
public BaseDoor(int closedID, int openedID, int openedSound, int closedSound, Point3D offset)
: base(closedID)
{
m_OpenedID = openedID;
m_ClosedID = closedID;
m_OpenedSound = openedSound;
m_ClosedSound = closedSound;
m_Offset = offset;
m_Timer = new InternalTimer(this);
Movable = false;
}
public BaseDoor(Serial serial)
: base(serial)
{
}
[CommandProperty(AccessLevel.GameMaster)]
public bool Locked
{
get
{
return m_Locked;
}
set
{
m_Locked = value;
}
}
[CommandProperty(AccessLevel.GameMaster)]
public uint KeyValue
{
get
{
return m_KeyValue;
}
set
{
m_KeyValue = value;
}
}
[CommandProperty(AccessLevel.GameMaster)]
public bool Open
{
get
{
return m_Open;
}
set
{
if (m_Open != value)
{
m_Open = value;
ItemID = m_Open ? m_OpenedID : m_ClosedID;
if (m_Open)
Location = new Point3D(X + m_Offset.X, Y + m_Offset.Y, Z + m_Offset.Z);
else
Location = new Point3D(X - m_Offset.X, Y - m_Offset.Y, Z - m_Offset.Z);
Effects.PlaySound(this, Map, m_Open ? m_OpenedSound : m_ClosedSound);
if (m_Open)
m_Timer.Start();
else
m_Timer.Stop();
}
}
}
[CommandProperty(AccessLevel.GameMaster)]
public int OpenedID
{
get
{
return m_OpenedID;
}
set
{
m_OpenedID = value;
}
}
[CommandProperty(AccessLevel.GameMaster)]
public int ClosedID
{
get
{
return m_ClosedID;
}
set
{
m_ClosedID = value;
}
}
[CommandProperty(AccessLevel.GameMaster)]
public int OpenedSound
{
get
{
return m_OpenedSound;
}
set
{
m_OpenedSound = value;
}
}
[CommandProperty(AccessLevel.GameMaster)]
public int ClosedSound
{
get
{
return m_ClosedSound;
}
set
{
m_ClosedSound = value;
}
}
[CommandProperty(AccessLevel.GameMaster)]
public Point3D Offset
{
get
{
return m_Offset;
}
set
{
m_Offset = value;
}
}
[CommandProperty(AccessLevel.GameMaster)]
public BaseDoor Link
{
get
{
if (m_Link != null && m_Link.Deleted)
m_Link = null;
return m_Link;
}
set
{
m_Link = value;
}
}
public virtual bool UseChainedFunctionality
{
get
{
return false;
}
}
// Called by RunUO
public static void Initialize()
{
EventSink.OpenDoorMacroUsed += new OpenDoorMacroEventHandler(EventSink_OpenDoorMacroUsed);
CommandSystem.Register("Link", AccessLevel.GameMaster, new CommandEventHandler(Link_OnCommand));
CommandSystem.Register("ChainLink", AccessLevel.GameMaster, new CommandEventHandler(ChainLink_OnCommand));
}
public static Point3D GetOffset(DoorFacing facing)
{
return m_Offsets[(int)facing];
}
public bool CanClose()
{
if (!m_Open)
return true;
Map map = Map;
if (map == null)
return false;
Point3D p = new Point3D(X - m_Offset.X, Y - m_Offset.Y, Z - m_Offset.Z);
return CheckFit(map, p, 16);
}
public List<BaseDoor> GetChain()
{
List<BaseDoor> list = new List<BaseDoor>();
BaseDoor c = this;
do
{
list.Add(c);
c = c.Link;
}
while (c != null && !list.Contains(c));
return list;
}
public bool IsFreeToClose()
{
if (!UseChainedFunctionality)
return CanClose();
List<BaseDoor> list = GetChain();
bool freeToClose = true;
for (int i = 0; freeToClose && i < list.Count; ++i)
freeToClose = list[i].CanClose();
return freeToClose;
}
public virtual void OnTelekinesis(Mobile from)
{
Effects.SendLocationParticles(EffectItem.Create(Location, Map, EffectItem.DefaultDuration), 0x376A, 9, 32, 5022);
Effects.PlaySound(Location, Map, 0x1F5);
Use(from);
}
public virtual bool IsInside(Mobile from)
{
return false;
}
public virtual bool UseLocks()
{
return true;
}
public virtual void Use(Mobile from)
{
if (m_Locked && !m_Open && UseLocks())
{
if (from.AccessLevel >= AccessLevel.GameMaster)
{
from.LocalOverheadMessage(MessageType.Regular, 0x3B2, 502502); // That is locked, but you open it with your godly powers.
//from.Send( new MessageLocalized( Serial, ItemID, MessageType.Regular, 0x3B2, 3, 502502, "", "" ) ); // That is locked, but you open it with your godly powers.
}
else if (Key.ContainsKey(from.Backpack, KeyValue))
{
from.LocalOverheadMessage(MessageType.Regular, 0x3B2, 501282); // You quickly unlock, open, and relock the door
}
else if (IsInside(from))
{
from.LocalOverheadMessage(MessageType.Regular, 0x3B2, 501280); // That is locked, but is usable from the inside.
}
else
{
if (Hue == 0x44E && Map == Map.Malas) // doom door into healer room in doom
SendLocalizedMessageTo(from, 1060014); // Only the dead may pass.
else
from.LocalOverheadMessage(MessageType.Regular, 0x3B2, 502503); // That is locked.
return;
}
}
if (m_Open && !IsFreeToClose())
return;
if (m_Open)
OnClosed(from);
else
OnOpened(from);
if (UseChainedFunctionality)
{
bool open = !m_Open;
List<BaseDoor> list = GetChain();
for (int i = 0; i < list.Count; ++i)
list[i].Open = open;
}
else
{
Open = !m_Open;
BaseDoor link = Link;
if (m_Open && link != null && !link.Open)
link.Open = true;
}
}
public virtual void OnOpened(Mobile from)
{
}
public virtual void OnClosed(Mobile from)
{
}
public override void OnDoubleClick(Mobile from)
{
if (from.IsPlayer() && (/*!from.InLOS( this ) || */!from.InRange(GetWorldLocation(), 2)))
from.LocalOverheadMessage(MessageType.Regular, 0x3B2, 1019045); // I can't reach that.
else
Use(from);
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
writer.Write(m_KeyValue);
writer.Write(m_Open);
writer.Write(m_Locked);
writer.Write(m_OpenedID);
writer.Write(m_ClosedID);
writer.Write(m_OpenedSound);
writer.Write(m_ClosedSound);
writer.Write(m_Offset);
writer.Write(m_Link);
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
switch ( version )
{
case 0:
{
m_KeyValue = reader.ReadUInt();
m_Open = reader.ReadBool();
m_Locked = reader.ReadBool();
m_OpenedID = reader.ReadInt();
m_ClosedID = reader.ReadInt();
m_OpenedSound = reader.ReadInt();
m_ClosedSound = reader.ReadInt();
m_Offset = reader.ReadPoint3D();
m_Link = reader.ReadItem() as BaseDoor;
m_Timer = new InternalTimer(this);
if (m_Open)
m_Timer.Start();
break;
}
}
}
[Usage("Link")]
[Description("Links two targeted doors together.")]
private static void Link_OnCommand(CommandEventArgs e)
{
e.Mobile.BeginTarget(-1, false, TargetFlags.None, new TargetCallback(Link_OnFirstTarget));
e.Mobile.SendMessage("Target the first door to link.");
}
private static void Link_OnFirstTarget(Mobile from, object targeted)
{
BaseDoor door = targeted as BaseDoor;
if (door == null)
{
from.BeginTarget(-1, false, TargetFlags.None, new TargetCallback(Link_OnFirstTarget));
from.SendMessage("That is not a door. Try again.");
}
else
{
from.BeginTarget(-1, false, TargetFlags.None, new TargetStateCallback(Link_OnSecondTarget), door);
from.SendMessage("Target the second door to link.");
}
}
private static void Link_OnSecondTarget(Mobile from, object targeted, object state)
{
BaseDoor first = (BaseDoor)state;
BaseDoor second = targeted as BaseDoor;
if (second == null)
{
from.BeginTarget(-1, false, TargetFlags.None, new TargetStateCallback(Link_OnSecondTarget), first);
from.SendMessage("That is not a door. Try again.");
}
else
{
first.Link = second;
second.Link = first;
from.SendMessage("The doors have been linked.");
}
}
[Usage("ChainLink")]
[Description("Chain-links two or more targeted doors together.")]
private static void ChainLink_OnCommand(CommandEventArgs e)
{
e.Mobile.BeginTarget(-1, false, TargetFlags.None, new TargetStateCallback(ChainLink_OnTarget), new List<BaseDoor>());
e.Mobile.SendMessage("Target the first of a sequence of doors to link.");
}
private static void ChainLink_OnTarget(Mobile from, object targeted, object state)
{
BaseDoor door = targeted as BaseDoor;
if (door == null)
{
from.BeginTarget(-1, false, TargetFlags.None, new TargetStateCallback(ChainLink_OnTarget), state);
from.SendMessage("That is not a door. Try again.");
}
else
{
List<BaseDoor> list = (List<BaseDoor>)state;
if (list.Count > 0 && list[0] == door)
{
if (list.Count >= 2)
{
for (int i = 0; i < list.Count; ++i)
list[i].Link = list[(i + 1) % list.Count];
from.SendMessage("The chain of doors have been linked.");
}
else
{
from.BeginTarget(-1, false, TargetFlags.None, new TargetStateCallback(ChainLink_OnTarget), state);
from.SendMessage("You have not yet targeted two unique doors. Target the second door to link.");
}
}
else if (list.Contains(door))
{
from.BeginTarget(-1, false, TargetFlags.None, new TargetStateCallback(ChainLink_OnTarget), state);
from.SendMessage("You have already targeted that door. Target another door, or retarget the first door to complete the chain.");
}
else
{
list.Add(door);
from.BeginTarget(-1, false, TargetFlags.None, new TargetStateCallback(ChainLink_OnTarget), state);
if (list.Count == 1)
from.SendMessage("Target the second door to link.");
else
from.SendMessage("Target another door to link. To complete the chain, retarget the first door.");
}
}
}
private static void EventSink_OpenDoorMacroUsed(OpenDoorMacroEventArgs args)
{
Mobile m = args.Mobile;
if (m.Map != null)
{
int x = m.X, y = m.Y;
switch ( m.Direction & Direction.Mask )
{
case Direction.North:
--y;
break;
case Direction.Right:
++x;
--y;
break;
case Direction.East:
++x;
break;
case Direction.Down:
++x;
++y;
break;
case Direction.South:
++y;
break;
case Direction.Left:
--x;
++y;
break;
case Direction.West:
--x;
break;
case Direction.Up:
--x;
--y;
break;
}
Sector sector = m.Map.GetSector(x, y);
foreach (Item item in sector.Items)
{
if (item.Location.X == x && item.Location.Y == y && (item.Z + item.ItemData.Height) > m.Z && (m.Z + 16) > item.Z && item is BaseDoor && m.CanSee(item) && m.InLOS(item))
{
if (m.CheckAlive())
{
m.SendLocalizedMessage(500024); // Opening door...
item.OnDoubleClick(m);
}
break;
}
}
}
}
private bool CheckFit(Map map, Point3D p, int height)
{
if (map == Map.Internal)
return false;
int x = p.X;
int y = p.Y;
int z = p.Z;
Sector sector = map.GetSector(x, y);
List<Item> items = sector.Items;
List<Mobile> mobs = sector.Mobiles;
for (int i = 0; i < items.Count; ++i)
{
Item item = items[i];
if (!(item is BaseMulti) && item.ItemID <= TileData.MaxItemValue && item.AtWorldPoint(x, y) && !(item is BaseDoor))
{
ItemData id = item.ItemData;
bool surface = id.Surface;
bool impassable = id.Impassable;
if ((surface || impassable) && (item.Z + id.CalcHeight) > z && (z + height) > item.Z)
return false;
}
}
for (int i = 0; i < mobs.Count; ++i)
{
Mobile m = mobs[i];
if (m.Location.X == x && m.Location.Y == y)
{
if (m.Hidden && m.IsPlayer())
continue;
if (!m.Alive)
continue;
if ((m.Z + 16) > z && (z + height) > m.Z)
return false;
}
}
return true;
}
private class InternalTimer : Timer
{
private readonly BaseDoor m_Door;
public InternalTimer(BaseDoor door)
: base(TimeSpan.FromSeconds(20.0), TimeSpan.FromSeconds(10.0))
{
Priority = TimerPriority.OneSecond;
m_Door = door;
}
protected override void OnTick()
{
if (m_Door.Open && m_Door.IsFreeToClose())
m_Door.Open = false;
}
}
}
} | 0 | 0.990342 | 1 | 0.990342 | game-dev | MEDIA | 0.828744 | game-dev | 0.90715 | 1 | 0.90715 |
redot-rex/rex-engine | 3,738 | modules/jolt_physics/shapes/jolt_sphere_shape_3d.cpp | /**************************************************************************/
/* jolt_sphere_shape_3d.cpp */
/**************************************************************************/
/* This file is part of: */
/* REDOT ENGINE */
/* https://redotengine.org */
/**************************************************************************/
/* Copyright (c) 2024-present Redot Engine contributors */
/* (see REDOT_AUTHORS.md) */
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/**************************************************************************/
#include "jolt_sphere_shape_3d.h"
#include "../misc/jolt_type_conversions.h"
#include "Jolt/Physics/Collision/Shape/SphereShape.h"
JPH::ShapeRefC JoltSphereShape3D::_build() const {
ERR_FAIL_COND_V_MSG(radius <= 0.0f, nullptr, vformat("Failed to build Jolt Physics sphere shape with %s. Its radius must be greater than 0. This shape belongs to %s.", to_string(), _owners_to_string()));
const JPH::SphereShapeSettings shape_settings(radius);
const JPH::ShapeSettings::ShapeResult shape_result = shape_settings.Create();
ERR_FAIL_COND_V_MSG(shape_result.HasError(), nullptr, vformat("Failed to build Jolt Physics sphere shape with %s. It returned the following error: '%s'. This shape belongs to %s.", to_string(), to_godot(shape_result.GetError()), _owners_to_string()));
return shape_result.Get();
}
Variant JoltSphereShape3D::get_data() const {
return radius;
}
void JoltSphereShape3D::set_data(const Variant &p_data) {
ERR_FAIL_COND(p_data.get_type() != Variant::FLOAT);
const float new_radius = p_data;
if (unlikely(new_radius == radius)) {
return;
}
radius = new_radius;
destroy();
}
AABB JoltSphereShape3D::get_aabb() const {
const Vector3 half_extents(radius, radius, radius);
return AABB(-half_extents, half_extents * 2.0f);
}
String JoltSphereShape3D::to_string() const {
return vformat("{radius=%f}", radius);
}
| 0 | 0.893452 | 1 | 0.893452 | game-dev | MEDIA | 0.797731 | game-dev | 0.809281 | 1 | 0.809281 |
philkr/pystk | 2,579 | lib/bullet/src/BulletCollision/CollisionDispatch/btSimulationIslandManager.h | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef BT_SIMULATION_ISLAND_MANAGER_H
#define BT_SIMULATION_ISLAND_MANAGER_H
#include "BulletCollision/CollisionDispatch/btUnionFind.h"
#include "btCollisionCreateFunc.h"
#include "LinearMath/btAlignedObjectArray.h"
#include "btCollisionObject.h"
class btCollisionObject;
class btCollisionWorld;
class btDispatcher;
class btPersistentManifold;
///SimulationIslandManager creates and handles simulation islands, using btUnionFind
class btSimulationIslandManager
{
btUnionFind m_unionFind;
btAlignedObjectArray<btPersistentManifold*> m_islandmanifold;
btAlignedObjectArray<btCollisionObject* > m_islandBodies;
bool m_splitIslands;
public:
btSimulationIslandManager();
virtual ~btSimulationIslandManager();
void initUnionFind(int n);
btUnionFind& getUnionFind() { return m_unionFind;}
virtual void updateActivationState(btCollisionWorld* colWorld,btDispatcher* dispatcher);
virtual void storeIslandActivationState(btCollisionWorld* world);
void findUnions(btDispatcher* dispatcher,btCollisionWorld* colWorld);
struct IslandCallback
{
virtual ~IslandCallback() {};
virtual void ProcessIsland(btCollisionObject** bodies,int numBodies,class btPersistentManifold** manifolds,int numManifolds, int islandId) = 0;
};
void buildAndProcessIslands(btDispatcher* dispatcher,btCollisionWorld* collisionWorld, IslandCallback* callback);
void buildIslands(btDispatcher* dispatcher,btCollisionWorld* colWorld);
bool getSplitIslands()
{
return m_splitIslands;
}
void setSplitIslands(bool doSplitIslands)
{
m_splitIslands = doSplitIslands;
}
};
#endif //BT_SIMULATION_ISLAND_MANAGER_H
| 0 | 0.757357 | 1 | 0.757357 | game-dev | MEDIA | 0.973616 | game-dev | 0.673225 | 1 | 0.673225 |
CommitAndChill/BlueprintTaskForge | 2,310 | Source/BlueprintTaskForge/Public/Subsystem/BtfSubsystem.h | // Copyright (c) 2025 BlueprintTaskForge Maintainers
//
// This file is part of the BlueprintTaskForge Plugin for Unreal Engine.
//
// Licensed under the BlueprintTaskForge Open Plugin License v1.0 (BTFPL-1.0).
// You may obtain a copy of the license at:
// https://github.com/CommitAndChill/BlueprintTaskForge/blob/main/LICENSE.md
//
// SPDX-License-Identifier: BTFPL-1.0
#pragma once
#include "BtfTaskForge.h"
#include "BftMacros.h"
#include <Subsystems/EngineSubsystem.h>
#include <Subsystems/WorldSubsystem.h>
#include "BtfSubsystem.generated.h"
// --------------------------------------------------------------------------------------------------------------------
USTRUCT()
struct FBtf_OutersBlueprintTasksArrayWrapper
{
GENERATED_BODY()
TArray<TWeakObjectPtr<class UBtf_TaskForge>> Tasks;
};
// --------------------------------------------------------------------------------------------------------------------
UCLASS()
class BLUEPRINTTASKFORGE_API UBtf_WorldSubsystem : public UWorldSubsystem
{
GENERATED_BODY()
public:
virtual void Deinitialize() override;
void TrackTask(UBtf_TaskForge* InTask);
void UntrackTask(UBtf_TaskForge* InTask);
TMap<TWeakObjectPtr<UObject>, FBtf_OutersBlueprintTasksArrayWrapper> GetTaskTree();
private:
UPROPERTY(Transient)
TSet<TObjectPtr<UBtf_TaskForge>> BlueprintTasks;
UPROPERTY()
TMap<TWeakObjectPtr<UObject>, FBtf_OutersBlueprintTasksArrayWrapper> ObjectsAndTheirTasks;
};
// --------------------------------------------------------------------------------------------------------------------
UCLASS()
class BLUEPRINTTASKFORGE_API UBtf_EngineSubsystem : public UEngineSubsystem
{
GENERATED_BODY()
public:
void Add(FGuid InTaskNodeGuid, UBtf_TaskForge* InTaskInstance);
void Remove(UBtf_TaskForge* InTaskInstance);
void Remove(FGuid InTaskNodeGuid);
void Clear();
UBtf_TaskForge* FindTaskInstanceWithGuid(FGuid InTaskNodeGuid);
private:
#if WITH_EDITORONLY_DATA
UPROPERTY()
TMap<FGuid, TWeakObjectPtr<UBtf_TaskForge>> TaskNodeGuidToTaskInstance;
UPROPERTY()
TMap<TWeakObjectPtr<UBtf_TaskForge>, FGuid> TaskInstanceTaskNodeGuid;
# endif
};
// -------------------------------------------------------------------------------------------------------------------- | 0 | 0.909457 | 1 | 0.909457 | game-dev | MEDIA | 0.900398 | game-dev | 0.586227 | 1 | 0.586227 |
LambdAurora/SpruceUI | 2,574 | src/main/java/dev/lambdaurora/spruceui/option/SpruceToggleBooleanOption.java | /*
* Copyright © 2020 LambdAurora <[email protected]>
*
* This file is part of SpruceUI.
*
* Licensed under the MIT license. For more information,
* see the LICENSE file.
*/
package dev.lambdaurora.spruceui.option;
import dev.lambdaurora.spruceui.Position;
import dev.lambdaurora.spruceui.tooltip.TooltipData;
import dev.lambdaurora.spruceui.widget.SpruceToggleSwitch;
import dev.lambdaurora.spruceui.widget.SpruceWidget;
import net.minecraft.network.chat.Text;
import org.jetbrains.annotations.NotNull;
import java.util.function.Consumer;
import java.util.function.Supplier;
/**
* Represents a boolean option.
* <p>
* Works the as {@link SpruceBooleanOption} but uses a toggle switch instead.
*
* @author LambdAurora
* @version 8.0.0
* @since 2.0.0
*/
public class SpruceToggleBooleanOption extends SpruceBooleanOption {
private final boolean showMessage;
public SpruceToggleBooleanOption(
String key, Supplier<Boolean> getter, Consumer<Boolean> setter,
@NotNull TooltipData tooltip, boolean showMessage
) {
super(key, getter, setter, tooltip, false);
this.showMessage = showMessage;
}
public SpruceToggleBooleanOption(
String key, Supplier<Boolean> getter, Consumer<Boolean> setter,
@NotNull TooltipData tooltip
) {
this(key, getter, setter, tooltip, true);
}
@Override
public SpruceWidget createWidget(Position position, int width) {
var button = new SpruceToggleSwitch(
position, width, 20, this.getDisplayText(),
(btn, newValue) -> {
this.set();
btn.setMessage(this.getDisplayText());
this.getTooltip().ifPresent(btn::setTooltip);
},
this.get(), this.showMessage
);
this.getTooltip().ifPresent(button::setTooltip);
return button;
}
@Override
public Text getDisplayText() {
return this.getPrefix();
}
@Override
public Text getDisplayText(Text value) {
return this.getPrefix();
}
public static class Builder extends SpruceBooleanOption.BaseBuilder<Builder, SpruceToggleBooleanOption> {
private boolean showMessage = true;
public Builder(String key, Supplier<Boolean> getter, Consumer<Boolean> setter) {
super(key, getter, setter);
}
public Builder showMessage() {
return this.showMessage(true);
}
public Builder showMessage(boolean showMessage) {
this.showMessage = showMessage;
return this;
}
@Override
protected Builder self() {
return this;
}
public SpruceToggleBooleanOption build() {
return new SpruceToggleBooleanOption(
this.key, this.getter, this.setter,
this.tooltip, this.showMessage
);
}
}
}
| 0 | 0.789678 | 1 | 0.789678 | game-dev | MEDIA | 0.263877 | game-dev | 0.739149 | 1 | 0.739149 |
RevereInc/alley-practice | 1,810 | src/main/java/dev/revere/alley/feature/duel/DuelRequest.java | package dev.revere.alley.feature.duel;
import dev.revere.alley.feature.arena.Arena;
import dev.revere.alley.feature.kit.Kit;
import lombok.Getter;
import lombok.Setter;
import org.bukkit.entity.Player;
/**
* @author Emmy
* @project Alley
* @date 17/10/2024 - 20:04
*/
@Getter
@Setter
public class DuelRequest {
private final Player sender;
private final Player target;
private Kit kit;
private Arena arena;
private final long expireTime;
private boolean party;
/**
* Instantiates a new Duel request.
*
* @param sender the sender
* @param target the target
* @param kit the kit
* @param arena the arena
*/
public DuelRequest(Player sender, Player target, Kit kit, Arena arena, boolean party) {
this.sender = sender;
this.target = target;
this.kit = kit;
this.arena = arena;
this.party = party;
this.expireTime = System.currentTimeMillis() + 30000L;
}
/**
* Check if the duel request has expired.
*
* @return true if the duel request has expired, false otherwise
*/
public boolean hasExpired() {
return System.currentTimeMillis() > expireTime;
}
/**
* Get the remaining time until the duel request expires.
*
* @return the remaining time until the duel request expires
*/
public long getRemainingTime() {
return expireTime - System.currentTimeMillis();
}
/**
* Get the remaining time formatted as a string.
*
* @return the remaining time formatted as a string
*/
public String getRemainingTimeFormatted() {
long seconds = getRemainingTime() / 1000;
long minutes = seconds / 60;
return String.format("%02d:%02d", minutes, seconds % 60);
}
}
| 0 | 0.575698 | 1 | 0.575698 | game-dev | MEDIA | 0.698728 | game-dev | 0.874989 | 1 | 0.874989 |
tterrag1098/Registrate | 18,894 | src/main/java/com/tterrag/registrate/builders/BlockBuilder.java | package com.tterrag.registrate.builders;
import java.util.function.Function;
import java.util.function.Supplier;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import com.google.common.base.Preconditions;
import com.tterrag.registrate.AbstractRegistrate;
import com.tterrag.registrate.builders.BlockEntityBuilder.BlockEntityFactory;
import com.tterrag.registrate.providers.DataGenContext;
import com.tterrag.registrate.providers.GeneratorType;
import com.tterrag.registrate.providers.ProviderType;
import com.tterrag.registrate.providers.RegistrateLangProvider;
import com.tterrag.registrate.providers.generators.RegistrateBlockModelGenerator;
import com.tterrag.registrate.providers.generators.RegistrateRecipeProvider;
import com.tterrag.registrate.providers.loot.RegistrateBlockLootTables;
import com.tterrag.registrate.providers.loot.RegistrateLootTableProvider.LootType;
import com.tterrag.registrate.util.OneTimeEventReceiver;
import com.tterrag.registrate.util.RegistrateDistExecutor;
import com.tterrag.registrate.util.entry.BlockEntry;
import com.tterrag.registrate.util.entry.RegistryEntry;
import com.tterrag.registrate.util.nullness.NonNullBiConsumer;
import com.tterrag.registrate.util.nullness.NonNullBiFunction;
import com.tterrag.registrate.util.nullness.NonNullFunction;
import com.tterrag.registrate.util.nullness.NonNullSupplier;
import com.tterrag.registrate.util.nullness.NonNullUnaryOperator;
import net.minecraft.client.color.block.BlockColor;
import net.minecraft.client.renderer.ItemBlockRenderTypes;
import net.minecraft.client.renderer.block.model.SingleVariant;
import net.minecraft.client.renderer.block.model.Variant;
import net.minecraft.client.renderer.chunk.ChunkSectionLayer;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.tags.TagKey;
import net.minecraft.world.item.BlockItem;
import net.minecraft.world.item.Item;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockBehaviour;
import net.neoforged.api.distmarker.Dist;
import net.neoforged.fml.event.lifecycle.FMLClientSetupEvent;
import net.neoforged.neoforge.client.event.RegisterColorHandlersEvent;
import net.neoforged.neoforge.client.extensions.common.IClientBlockExtensions;
import net.neoforged.neoforge.client.extensions.common.RegisterClientExtensionsEvent;
import net.neoforged.neoforge.registries.DeferredHolder;
/**
* A builder for blocks, allows for customization of the {@link Block.Properties}, creation of block items, and configuration of data associated with blocks (loot tables, recipes, etc.).
*
* @param <T>
* The type of block being built
* @param <P>
* Parent object type
*/
public class BlockBuilder<T extends Block, P> extends AbstractBuilder<Block, T, P, BlockBuilder<T, P>> {
/**
* Create a new {@link BlockBuilder} and configure data. Used in lieu of adding side-effects to constructor, so that alternate initialization strategies can be done in subclasses.
* <p>
* The block will be assigned the following data:
* <ul>
* <li>A default blockstate file mapping all states to one model (via {@link #defaultBlockstate()})</li>
* <li>A simple cube_all model (used in the blockstate) with one texture (via {@link #defaultBlockstate()})</li>
* <li>A self-dropping loot table (via {@link #defaultLoot()})</li>
* <li>The default translation (via {@link #defaultLang()})</li>
* </ul>
*
* @param <T>
* The type of the builder
* @param <P>
* Parent object type
* @param owner
* The owning {@link AbstractRegistrate} object
* @param parent
* The parent object
* @param name
* Name of the entry being built
* @param callback
* A callback used to actually register the built entry
* @param factory
* Factory to create the block
* @return A new {@link BlockBuilder} with reasonable default data generators.
*/
public static <T extends Block, P> BlockBuilder<T, P> create(AbstractRegistrate<?> owner, P parent, String name, BuilderCallback callback, NonNullFunction<BlockBehaviour.Properties, T> factory) {
return new BlockBuilder<>(owner, parent, name, callback, factory, () -> BlockBehaviour.Properties.of())
.defaultBlockstate().defaultLoot().defaultLang();
}
private final NonNullFunction<BlockBehaviour.Properties, T> factory;
private NonNullSupplier<BlockBehaviour.Properties> initialProperties;
private NonNullFunction<BlockBehaviour.Properties, BlockBehaviour.Properties> propertiesCallback = NonNullUnaryOperator.identity();
@Nullable
private Supplier<Supplier<ChunkSectionLayer>> renderLayer;
@Nullable
private NonNullSupplier<Supplier<BlockColor>> colorHandler;
protected BlockBuilder(AbstractRegistrate<?> owner, P parent, String name, BuilderCallback callback, NonNullFunction<BlockBehaviour.Properties, T> factory, NonNullSupplier<BlockBehaviour.Properties> initialProperties) {
super(owner, parent, name, callback, Registries.BLOCK);
this.factory = factory;
this.initialProperties = initialProperties;
}
/**
* Modify the properties of the block. Modifications are done lazily, but the passed function is composed with the current one, and as such this method can be called multiple times to perform
* different operations.
* <p>
* If a different properties instance is returned, it will replace the existing one entirely.
*
* @param func
* The action to perform on the properties
* @return this {@link BlockBuilder}
*/
public BlockBuilder<T, P> properties(NonNullUnaryOperator<BlockBehaviour.Properties> func) {
propertiesCallback = propertiesCallback.andThen(func);
return this;
}
/**
* Replace the initial state of the block properties, without replacing or removing any modifications done via {@link #properties(NonNullUnaryOperator)}.
*
* @param block
* The block to create the initial properties from (via {@link Block.Properties#ofFullCopy(BlockBehaviour)})
* @return this {@link BlockBuilder}
*/
public BlockBuilder<T, P> initialProperties(NonNullSupplier<? extends Block> block) {
initialProperties = () -> BlockBehaviour.Properties.ofFullCopy(block.get());
return this;
}
/**
* @deprecated Set your render type in your model's JSON ({@link net.neoforged.neoforge.client.model.generators.template.ExtendedModelTemplateBuilder#renderType(ResourceLocation)})
*/
@Deprecated(forRemoval = true)
public BlockBuilder<T, P> addLayer(Supplier<Supplier<ChunkSectionLayer>> layer) {
if (this.renderLayer == null) {
onRegister(this::registerLayers);
this.renderLayer = layer;
} else {
throw new IllegalStateException("Only a single layer can be registered for a block");
}
return this;
}
@SuppressWarnings("deprecation")
protected void registerLayers(T entry) {
RegistrateDistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> {
OneTimeEventReceiver.addModListener(getOwner(), FMLClientSetupEvent.class, $ -> {
if (renderLayer != null) {
ChunkSectionLayer layer = renderLayer.get().get();
ItemBlockRenderTypes.setRenderLayer(entry, layer);
}
});
});
}
/**
* Create a standard {@link BlockItem} for this block, building it immediately, and not allowing for further configuration.
* <p>
* The item will have no lang entry (since it would duplicate the block's)
*
* @return this {@link BlockBuilder}
* @see #item()
*/
public BlockBuilder<T, P> simpleItem() {
return item().build();
}
/**
* Create a standard {@link BlockItem} for this block, and return the builder for it so that further customization can be done.
* <p>
* The item will have no lang entry (since it would duplicate the block's)
*
* @return the {@link ItemBuilder} for the {@link BlockItem}
*/
public ItemBuilder<BlockItem, BlockBuilder<T, P>> item() {
return item(BlockItem::new);
}
/**
* Create a {@link BlockItem} for this block, which is created by the given factory, and return the builder for it so that further customization can be done.
* <p>
* By default, the item will have no lang entry (since it would duplicate the block's) and a simple block item model.
*
* @param <I>
* The type of the item
* @param factory
* A factory for the item, which accepts the block object and properties and returns a new item
* @return the {@link ItemBuilder} for the {@link BlockItem}
*/
public <I extends Item> ItemBuilder<I, BlockBuilder<T, P>> item(NonNullBiFunction<? super T, Item.Properties, ? extends I> factory) {
return getOwner().<I, BlockBuilder<T, P>> item(this, getName(), p -> factory.apply(getEntry(), p.useBlockDescriptionPrefix()))
.setData(ProviderType.LANG, NonNullBiConsumer.noop()) // FIXME Need a beetter API for "unsetting" providers
.model(() -> (ctx, prov) -> {
getOwner().getDataProvider(ProviderType.BLOCKSTATE)
.map(g -> g.seenBlockstates.get(getEntry()))
.flatMap(b -> b.simpleModels())
.map(b -> b.models().get(""))
.map(unbaked -> {
if (unbaked instanceof SingleVariant.Unbaked(Variant variant)) {
return variant.modelLocation();
}
return null;
})
.ifPresent(model -> prov.createWithExistingModel(ctx.get(), model));
});
}
/**
* Create a {@link BlockEntity} for this block, which is created by the given factory, and assigned this block as its one and only valid block.
*
* @param <BE>
* The type of the block entity
* @param factory
* A factory for the block entity
* @return this {@link BlockBuilder}
*/
public <BE extends BlockEntity> BlockBuilder<T, P> simpleBlockEntity(BlockEntityFactory<BE> factory) {
return blockEntity(factory).build();
}
/**
* Create a {@link BlockEntity} for this block, which is created by the given factory, and assigned this block as its one and only valid block.
* <p>
* The created {@link BlockEntityBuilder} is returned for further configuration.
*
* @param <BE>
* The type of the block entity
* @param factory
* A factory for the block entity
* @return the {@link BlockEntityBuilder}
*/
public <BE extends BlockEntity> BlockEntityBuilder<BE, BlockBuilder<T, P>> blockEntity(BlockEntityFactory<BE> factory) {
return getOwner().<BE, BlockBuilder<T, P>>blockEntity(this, getName(), factory).validBlock(asSupplier());
}
/**
* Register a block color handler for this block. The {@link BlockColor} instance can be shared across many blocks.
*
* @param colorHandler
* The color handler to register for this block
* @return this {@link BlockBuilder}
*/
// TODO it might be worthwhile to abstract this more and add the capability to automatically copy to the item
public BlockBuilder<T, P> color(NonNullSupplier<Supplier<BlockColor>> colorHandler) {
if (this.colorHandler == null) {
RegistrateDistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> this::registerBlockColor);
}
this.colorHandler = colorHandler;
return this;
}
protected void registerBlockColor() {
OneTimeEventReceiver.addModListener(getOwner(), RegisterColorHandlersEvent.Block.class, e -> {
NonNullSupplier<Supplier<BlockColor>> colorHandler = this.colorHandler;
if (colorHandler != null) {
e.register(colorHandler.get().get(), getEntry());
}
});
}
/**
* Assign the default blockstate, which maps all states to a single model file (via {@link RegistrateBlockModelGenerator#createTrivialCube(Block)}). This is the default, so it is generally not necessary
* to call, unless for undoing previous changes.
*
* @return this {@link BlockBuilder}
*/
public BlockBuilder<T, P> defaultBlockstate() {
return blockstate(() -> (ctx, prov) -> prov.createTrivialCube(ctx.getEntry()));
}
/**
* Configure the blockstate/models for this block.
*
* @param cons
* The callback which will be invoked during data generation.
* @return this {@link BlockBuilder}
* @see #setData(GeneratorType, NonNullBiConsumer)
*/
public BlockBuilder<T, P> blockstate(NonNullSupplier<NonNullBiConsumer<DataGenContext<Block, T>, RegistrateBlockModelGenerator>> cons) {
if (!getOwner().doDatagen().get()) return this;
return setData(ProviderType.BLOCKSTATE, cons.get());
}
/**
* Assign the default translation, as specified by {@link RegistrateLangProvider#getAutomaticName(NonNullSupplier, net.minecraft.resources.ResourceKey)}. This is the default, so it is generally
* not necessary to call, unless for undoing previous changes.
*
* @return this {@link BlockBuilder}
*/
public BlockBuilder<T, P> defaultLang() {
return lang(Block::getDescriptionId);
}
/**
* Set the translation for this block.
*
* @param name
* A localized English name
* @return this {@link BlockBuilder}
*/
public BlockBuilder<T, P> lang(String name) {
return lang(Block::getDescriptionId, name);
}
/**
* Assign the default loot table, as specified by {@link RegistrateBlockLootTables#dropSelf(Block)}. This is the default, so it is generally not necessary to call, unless for
* undoing previous changes.
*
* @return this {@link BlockBuilder}
*/
public BlockBuilder<T, P> defaultLoot() {
return loot(RegistrateBlockLootTables::dropSelf);
}
/**
* Configure the loot table for this block. This is different than most data gen callbacks as the callback does not accept a {@link DataGenContext}, but instead a
* {@link RegistrateBlockLootTables}, for creating specifically block loot tables.
* <p>
* If the block does not have a loot table (i.e. {@link Block.Properties#noLootTable()} is called) this action will be <em>skipped</em>.
*
* @param cons
* The callback which will be invoked during block loot table creation.
* @return this {@link BlockBuilder}
*/
public BlockBuilder<T, P> loot(NonNullBiConsumer<RegistrateBlockLootTables, T> cons) {
return setData(ProviderType.LOOT, (ctx, prov) -> prov.addLootAction(LootType.BLOCK, tb -> {
if (ctx.getEntry().getLootTable().isPresent()) {
cons.accept(tb, ctx.getEntry());
}
}));
}
/**
* Configure the recipe(s) for this block.
*
* @param cons
* The callback which will be invoked during data generation.
* @return this {@link BlockBuilder}
* @see #setData(GeneratorType, NonNullBiConsumer)
*/
public BlockBuilder<T, P> recipe(NonNullBiConsumer<DataGenContext<Block, T>, RegistrateRecipeProvider> cons) {
return setData(ProviderType.RECIPE, cons);
}
@Nullable
private Function<T, NonNullSupplier<Supplier<IClientBlockExtensions>>> clientExtensionFunc;
/**
* Register a client extension for this block.
* The {@link IClientBlockExtensions} instance can be shared across many items.
*
* @param clientExtension
* The client extension to register for this block
* @return this {@link BlockBuilder}
*/
public BlockBuilder<T, P> clientExtension(NonNullSupplier<Supplier<IClientBlockExtensions>> clientExtension) {
if (this.clientExtensionFunc == null) {
RegistrateDistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> this::registerClientExtension);
}
this.clientExtensionFunc = block -> clientExtension;
return this;
}
/**
* Register a client extension for this block.
* The {@link IClientBlockExtensions} instance can be shared across many items.
*
* @param clientExtension
* The client extension to register for this block
* @return this {@link BlockBuilder}
*/
@Deprecated(forRemoval = true)
public BlockBuilder<T, P> clientExtension(Function<T, NonNullSupplier<Supplier<IClientBlockExtensions>>> clientExtension) {
if (this.clientExtensionFunc == null) {
RegistrateDistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> this::registerClientExtension);
}
this.clientExtensionFunc = clientExtension;
return this;
}
protected void registerClientExtension() {
OneTimeEventReceiver.addModListener(getOwner(), RegisterClientExtensionsEvent.class, e -> {
if (this.clientExtensionFunc != null) {
NonNullSupplier<Supplier<IClientBlockExtensions>> clientExtension = this.clientExtensionFunc.apply(getEntry());
e.registerBlock(clientExtension.get().get(), getEntry());
}
});
}
/**
* Assign {@link TagKey}{@code s} to this block. Multiple calls will add additional tags.
*
* @param tags
* The tags to assign
* @return this {@link BlockBuilder}
*/
@SafeVarargs
public final BlockBuilder<T, P> tag(TagKey<Block>... tags) {
return tag(ProviderType.BLOCK_TAGS, tags);
}
@Override
protected T createEntry() {
@Nonnull BlockBehaviour.Properties properties = this.initialProperties.get();
//TODO why do we need this?
// ObfuscationReflectionHelper.setPrivateValue(BlockBehaviour.Properties.class, properties, null, "drops");
properties = propertiesCallback.apply(properties);
return factory.apply(properties.setId(getResourceKey()));
}
@Override
protected RegistryEntry<Block, T> createEntryWrapper(DeferredHolder<Block, T> delegate) {
return new BlockEntry<>(getOwner(), delegate);
}
@Override
public BlockEntry<T> register() {
return (BlockEntry<T>) super.register();
}
}
| 0 | 0.900364 | 1 | 0.900364 | game-dev | MEDIA | 0.930635 | game-dev | 0.839683 | 1 | 0.839683 |
saucepleez/taskt | 8,150 | taskt/Core/Automation/Commands/Loop/BeginLoopForDictionaryCommand.cs | using System;
using System.Linq;
using System.Xml.Serialization;
using taskt.Core.Automation.Attributes.PropertyAttributes;
using taskt.Core.Automation.Engine;
namespace taskt.Core.Automation.Commands
{
[Serializable]
[Attributes.ClassAttributes.Group("Loop")]
[Attributes.ClassAttributes.CommandSettings("Loop For Dictionary")]
[Attributes.ClassAttributes.Description("This command allows you to Repeat actions on the values held by Dictionary. This command must have a following 'End Loop' command.")]
[Attributes.ClassAttributes.UsesDescription("")]
[Attributes.ClassAttributes.ImplementationDescription("")]
[Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_startloop))]
[Attributes.ClassAttributes.EnableAutomateRender(true)]
[Attributes.ClassAttributes.EnableAutomateDisplayText(true)]
public sealed class BeginLoopForDictionaryCommand : ADictionaryInputDictionaryCommands, IHaveLoopAdditionalCommands
{
//[XmlAttribute]
//public string v_Dictionary { get; set; }
[XmlAttribute]
[PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))]
[PropertyDescription("Variable Name to Store Dictionary Value (Readonly)")]
[PropertyIsOptional(true)]
[PropertyValidationRule("Dictionary Value", PropertyValidationRule.ValidationRuleFlags.None)]
[PropertyDisplayText(true, "Dictionary Value")]
[PropertyParameterOrder(6000)]
public string v_Value { get; set; }
[XmlAttribute]
[PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))]
[PropertyDescription("Variable Name to Store Dictionary Key (Readonly)")]
[PropertyIsOptional(true)]
[PropertyValidationRule("Dictionary Key", PropertyValidationRule.ValidationRuleFlags.None)]
[PropertyDisplayText(true, "Dictionary Key")]
[PropertyParameterOrder(6001)]
public string v_Key { get; set; }
[XmlAttribute]
[PropertyVirtualProperty(nameof(SelectionItemsControls), nameof(SelectionItemsControls.v_YesNoComboBox))]
[PropertyDescription("Reverse Loop")]
[PropertyIsOptional(true, "No")]
[PropertyFirstValue("No")]
[PropertyDisplayText(false, "")]
[PropertyValidationRule("", PropertyValidationRule.ValidationRuleFlags.None)]
[PropertyParameterOrder(6003)]
public string v_ReverseLoop { get; set; }
[XmlAttribute]
[PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))]
[PropertyDescription("Variable Name to Store Current Loop Times (First Time Value is '1')")]
[PropertyIsOptional(true)]
[PropertyValidationRule("Loop Current Times Variable", PropertyValidationRule.ValidationRuleFlags.None)]
[PropertyDisplayText(true, "Current Times")]
[PropertyParameterOrder(6004)]
public string v_CurrentTimes { get; set; }
[XmlAttribute]
[PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))]
[PropertyDescription("Variable Name to Store the Number of Loops (First Time Value is 0)")]
[PropertyIsOptional(true)]
[PropertyValidationRule("Number of Loops", PropertyValidationRule.ValidationRuleFlags.None)]
[PropertyDisplayText(true, "Number of Loops")]
[PropertyParameterOrder(6005)]
public string v_NumberOfLoops { get; set; }
public BeginLoopForDictionaryCommand()
{
}
public override void RunCommand(Engine.AutomationEngineInstance engine, Script.ScriptAction parentCommand)
{
var loopCommand = (BeginLoopForDictionaryCommand)parentCommand.ScriptCommand;
var rawVariable = v_Dictionary.GetRawVariable(engine);
var dicToLoop = this.ExpandUserVariableAsDictionary(engine);
var keys = dicToLoop.Keys.ToList();
int loopTimes = keys.Count;
Action<string> dicValueAction;
if (string.IsNullOrEmpty(v_Value))
{
dicValueAction = new Action<string>(str => { }); // nothing
}
else
{
dicValueAction = new Action<string>(str => { str.StoreInUserVariable(engine, v_Value); });
}
Action<string> dicKeyAction;
if (string.IsNullOrEmpty(v_Key))
{
dicKeyAction = new Action<string>(idx => { }); // nothing
}
else
{
dicKeyAction = new Action<string>(idx => { idx.StoreInUserVariable(engine, v_Key); });
}
Action<int> loopTimesAction;
if (string.IsNullOrEmpty(v_CurrentTimes))
{
loopTimesAction = new Action<int>(num =>
{
SystemVariables.Update_LoopCurrentIndex(num);
});
}
else
{
loopTimesAction = new Action<int>(num =>
{
SystemVariables.Update_LoopCurrentIndex(num);
num.StoreInUserVariable(engine, v_CurrentTimes);
});
}
Action<int> loopNumAction;
if (string.IsNullOrEmpty(v_NumberOfLoops))
{
loopNumAction = new Action<int>(num => { }); // nothing
}
else
{
loopNumAction = new Action<int>(num => { num.StoreInUserVariable(engine, v_NumberOfLoops); });
}
int count = 0; // loop counter
var loopBodyProcess = new Action<int>(index =>
{
rawVariable.CurrentPosition = index; // TODO: it's no good
engine.ReportProgress($"Starting Loop Number {(count + 1)}/{loopTimes} From Line {loopCommand.LineNumber}");
foreach (var cmd in parentCommand.AdditionalScriptCommands)
{
if (engine.IsCancellationPending)
{
return;
}
var key = keys[index];
// store variables value
dicValueAction(dicToLoop[key]);
dicKeyAction(key);
loopTimesAction(count + 1);
loopNumAction(count);
engine.ExecuteCommand(cmd);
if (engine.CurrentLoopCancelled)
{
engine.ReportProgress($"Exiting Loop From Line {loopCommand.LineNumber}");
//engine.CurrentLoopCancelled = false;
return;
}
if (engine.CurrentLoopContinuing)
{
engine.ReportProgress($"Continuing Next Loop From Line {loopCommand.LineNumber}");
engine.CurrentLoopContinuing = false;
break;
}
}
engine.ReportProgress($"Finished Loop From Line {loopCommand.LineNumber}");
});
if (this.ExpandValueOrUserVariableAsYesNo(nameof(v_ReverseLoop), engine))
{
// reverse loop
for (int i = keys.Count - 1; i >= 0; i--, count++)
{
loopBodyProcess(i);
if (engine.CurrentLoopCancelled)
{
engine.CurrentLoopCancelled = false;
break;
}
}
}
else
{
// normal loop
for (int i = 0; i < keys.Count; i++, count++)
{
loopBodyProcess(i);
if (engine.CurrentLoopCancelled)
{
engine.CurrentLoopCancelled = false;
break;
}
}
}
}
}
} | 0 | 0.79254 | 1 | 0.79254 | game-dev | MEDIA | 0.368536 | game-dev | 0.91717 | 1 | 0.91717 |
MacSergey/NodeMarkup | 5,340 | IMT/MarkingItems/Filler/Style/2D/Grid.cs | using IMT.API;
using IMT.UI.Editors;
using IMT.Utilities;
using IMT.Utilities.API;
using ModsCommon.UI;
using ModsCommon.Utilities;
using System.Collections.Generic;
using System.Xml.Linq;
using UnityEngine;
namespace IMT.Manager
{
public class GridFillerStyle : PeriodicFillerStyle, IPeriodicFiller, IRotateFiller, IWidthStyle, IColorStyle, IEffectStyle
{
public override StyleType Type => StyleType.FillerGrid;
public override MarkingLOD SupportLOD => MarkingLOD.NoLOD;
public bool KeepColor => true;
protected override float DefaultStep => DefaultStepGrid;
public PropertyValue<float> Angle { get; }
private static Dictionary<string, int> PropertyIndicesDic { get; } = CreatePropertyIndices(PropertyIndicesList);
private static IEnumerable<string> PropertyIndicesList
{
get
{
yield return nameof(Color);
yield return nameof(Width);
yield return nameof(Step);
yield return nameof(Angle);
yield return nameof(Offset);
yield return nameof(Texture);
yield return nameof(Cracks);
yield return nameof(Voids);
#if DEBUG
yield return nameof(Debug);
yield return nameof(RenderOnly);
yield return nameof(Start);
yield return nameof(End);
yield return nameof(StartBorder);
yield return nameof(EndBorder);
#endif
}
}
public override Dictionary<string, int> PropertyIndices => PropertyIndicesDic;
public override IEnumerable<IStylePropertyData> Properties
{
get
{
yield return new StylePropertyDataProvider<Color32>(nameof(Color), Color);
yield return new StylePropertyDataProvider<float>(nameof(Width), Width);
yield return new StylePropertyDataProvider<float>(nameof(Step), Step);
yield return new StylePropertyDataProvider<float>(nameof(Angle), Angle);
//yield return new StylePropertyDataProvider<float>(nameof(LineOffset), LineOffset);
//yield return new StylePropertyDataProvider<float>(nameof(MedianOffset), MedianOffset);
yield return new StylePropertyDataProvider<float>(nameof(Texture), Texture);
yield return new StylePropertyDataProvider<Vector2>(nameof(Cracks), Cracks);
yield return new StylePropertyDataProvider<Vector2>(nameof(Voids), Voids);
}
}
public GridFillerStyle(Color32 color, float width, Vector2 cracks, Vector2 voids, float texture, float angle, float step, Vector2 offset) : base(color, width, cracks, voids, texture, step, offset)
{
Angle = GetAngleProperty(angle);
}
public override BaseFillerStyle CopyStyle() => new GridFillerStyle(Color, Width, Cracks, Voids, Texture, Angle, Step, Offset);
public override void CopyTo(BaseFillerStyle target)
{
base.CopyTo(target);
if (target is IRotateFiller rotateTarget)
rotateTarget.Angle.Value = Angle;
if (target is IPeriodicFiller periodicTarget)
periodicTarget.Step.Value = Step;
}
protected override void GetUIComponents(MarkingFiller filler, EditorProvider provider)
{
base.GetUIComponents(filler, provider);
provider.AddProperty(new PropertyInfo<FloatPropertyPanel>(this, nameof(Step), MainCategory, AddStepProperty));
if (!provider.isTemplate)
provider.AddProperty(new PropertyInfo<FloatPropertyPanel>(this, nameof(Angle), MainCategory, AddAngleProperty));
}
protected override ITrajectory[] GetGuides(MarkingFiller filler, ContourGroup contours)
{
return new ITrajectory[]
{
GetGuide(contours.Limits, filler.Marking.Height, Angle),
GetGuide(contours.Limits, filler.Marking.Height, Angle < 0 ? Angle + 90 : Angle - 90)
};
}
#if DEBUG_PERIODIC_FILLER
protected override List<Part> GetParts(ITrajectory guide, EdgeSetGroup contours, MarkingLOD lod, Action<IStyleData> addData)
#else
protected override List<Part> GetParts(ITrajectory guide, ContourGroup contours, MarkingLOD lod)
#endif
{
var width = Width.Value;
var trajectories = GetPartTrajectories(guide, contours.Limits, width, width * (Step - 1));
var parts = new List<Part>(trajectories.Count);
for (var i = 0; i < trajectories.Count; i += 1)
{
var part = new Part(trajectories[i], null, null, 90f, true);
if (part.CanIntersect(contours, true))
parts.Add(part);
}
return parts;
}
public override XElement ToXml()
{
var config = base.ToXml();
Angle.ToXml(config);
return config;
}
public override void FromXml(XElement config, ObjectsMap map, bool invert, bool typeChanged)
{
base.FromXml(config, map, invert, typeChanged);
Angle.FromXml(config, DefaultAngle);
}
}
}
| 0 | 0.953905 | 1 | 0.953905 | game-dev | MEDIA | 0.521834 | game-dev,graphics-rendering | 0.986721 | 1 | 0.986721 |
aaronbloomfield/pdr | 1,162 | slides/code/02-lists/findMax.cpp | // This code requires the IntCell.h/cpp code from the 02-cpp slide set
#include <iostream>
#include <vector>
#include <string>
#include "IntCell.h"
using namespace std;
template <typename Comparable>
const Comparable & findMax (const vector<Comparable> & a) {
int maxIndex = 0;
for( int i = 1; i < a.size( ); i++ )
if( a[ maxIndex ] < a[ i ] ) // note the use of '<'
maxIndex = i;
return a[ maxIndex ];
}
int main() {
vector<int> v1(37);
vector<double> v2(40);
vector<string> v3(80);
vector<IntCell> v4(75);
v1.push_back(3);
v1.push_back(7);
v1.push_back(5);
v2.push_back(3.14);
v2.push_back(2.718);
v2.push_back(-1.0);
v3.push_back("aardvark");
v3.push_back("sloth");
v3.push_back("platypus");
v3.push_back("zebra");
v4.push_back(IntCell(3));
v4.push_back(IntCell(7));
v4.push_back(IntCell(5));
cout << findMax(v1) << endl; // ok: Comparable = int
cout << findMax(v2) << endl; // ok: Comparable = double
cout << findMax(v3) << endl; // ok: Comparable = string
//cout << findMax(v4) << endl; // Illegal: no operator<
return 0;
}
| 0 | 0.52885 | 1 | 0.52885 | game-dev | MEDIA | 0.670038 | game-dev | 0.687861 | 1 | 0.687861 |
LordOfDragons/dragengine | 5,735 | src/deigde/deigde/shared/src/gameproject/igdeGameProject.cpp | /*
* MIT License
*
* Copyright (C) 2024, DragonDreams GmbH ([email protected])
*
* 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 <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "igdeGameProject.h"
#include "../environment/igdeEnvironment.h"
#include "../gamedefinition/igdeGameDefinition.h"
#include <dragengine/deEngine.h>
#include <dragengine/common/exceptions.h>
#include <dragengine/common/file/decPath.h>
#include <dragengine/common/utils/decTimer.h>
#include <dragengine/logger/deLogger.h>
// Definitions
////////////////
#define LOGSOURCE "IGDE"
// Class igdeGameProject
//////////////////////////
// Constructor, destructor
////////////////////////////
igdeGameProject::igdeGameProject( igdeEnvironment &environment ) :
pEnvironment( environment ),
pChanged( false ),
pName( "New Project" ),
pPathData( "data" ),
pPathCache( "cache" ),
pPathLocal( "local" ),
pProjectGameDefinition( NULL ),
pXMLEClassGameDefinition( NULL ),
pFoundGameDefinition( NULL ),
pGameDefinition( NULL )
{
pGameDefinition = new igdeGameDefinition( environment );
pXMLEClassGameDefinition = new igdeGameDefinition( environment );
pFoundGameDefinition = new igdeGameDefinition( environment );
}
igdeGameProject::~igdeGameProject(){
pCleanUp();
}
// Management
///////////////
void igdeGameProject::SetFilePath( const char *path ){
if( pPathFile == path ){
return;
}
decPath pathDirectory;
pPathFile = path;
pathDirectory.SetFromNative( path );
if( pathDirectory.GetComponentCount() > 1 ){
pathDirectory.RemoveLastComponent();
}else{
pathDirectory.SetFromUnix( "/" );
}
pPathDirectory = pathDirectory.GetPathNative();
}
void igdeGameProject::SetName( const char *name ){
pName = name;
}
void igdeGameProject::SetDescription( const char *description ){
pDescription = description;
}
void igdeGameProject::SetPathData( const char *path ){
pPathData = path;
}
void igdeGameProject::SetPathCache( const char *path ){
pPathCache = path;
}
void igdeGameProject::SetPathLocal( const char *path ){
pPathLocal = path;
}
void igdeGameProject::SetPathProjectGameDefinition( const char *path ){
pPathProjectGameDefinition = path;
}
void igdeGameProject::SetProjectGameDefinition( igdeGameDefinition *gameDefinition ){
if( pProjectGameDefinition == gameDefinition ){
return;
}
if( pProjectGameDefinition ){
pProjectGameDefinition->FreeReference();
}
pProjectGameDefinition = gameDefinition;
if( gameDefinition ){
gameDefinition->AddReference();
}
}
void igdeGameProject::MergeGameDefinitions(){
if( ! pProjectGameDefinition ){
DETHROW( deeInvalidParam );
}
decTimer timer;
const int baseGameDefCount = pBaseGameDefinitionList.GetCount();
igdeGameDefinition *merged = NULL;
int i;
try{
// merge game definition
merged = new igdeGameDefinition( pEnvironment );
merged->UpdateWith( *pEnvironment.GetGameDefinition() );
for( i=0; i<baseGameDefCount; i++ ){
merged->UpdateWith( *pBaseGameDefinitionList.GetAt( i ) );
}
merged->UpdateWith( *pProjectGameDefinition );
merged->SetFilename( pProjectGameDefinition->GetFilename() );
merged->SetID( pProjectGameDefinition->GetID() );
merged->SetDescription( pProjectGameDefinition->GetDescription() );
merged->SetBasePath( pProjectGameDefinition->GetBasePath() );
merged->ResolveInheritClasses();
merged->UpdateWithElementClasses( *pXMLEClassGameDefinition );
merged->UpdateWithFound( *pFoundGameDefinition );
merged->UpdateTags();
// replace game definition
if( pGameDefinition ){
pGameDefinition->FreeReference();
}
pGameDefinition = merged;
}catch( const deException & ){
if( merged ){
merged->FreeReference();
}
throw;
}
pEnvironment.GetLogger()->LogInfoFormat( LOGSOURCE,
"Merged game definition in %.1fs", timer.GetElapsedTime() );
}
void igdeGameProject::SetScriptModule( const char* moduleName ){
pScriptModule = moduleName;
}
void igdeGameProject::SetScriptModuleVersion( const char *version ){
pScriptModuleVersion = version;
}
void igdeGameProject::SetChanged( bool changed ){
if( changed == pChanged ){
return;
}
pChanged = changed;
NotifyStateChanged();
}
void igdeGameProject::NotifyStateChanged(){
}
void igdeGameProject::NotifyUndoChanged(){
}
// Private Functions
//////////////////////
void igdeGameProject::pCleanUp(){
if( pGameDefinition ){
pGameDefinition->FreeReference();
}
if( pFoundGameDefinition ){
pFoundGameDefinition->FreeReference();
}
if( pXMLEClassGameDefinition ){
pXMLEClassGameDefinition->FreeReference();
}
if( pProjectGameDefinition ){
pProjectGameDefinition->FreeReference();
}
pBaseGameDefinitionList.RemoveAll();
}
| 0 | 0.917639 | 1 | 0.917639 | game-dev | MEDIA | 0.79067 | game-dev | 0.776406 | 1 | 0.776406 |
CleanstoneMC/Cleanstone | 2,268 | src/main/java/rocks/cleanstone/game/SimpleOpenWorldGame.java | package rocks.cleanstone.game;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.SmartLifecycle;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import rocks.cleanstone.game.config.GameConfig;
import rocks.cleanstone.game.world.World;
import rocks.cleanstone.game.world.WorldManager;
import rocks.cleanstone.game.world.config.WorldConfig;
import javax.annotation.Nonnull;
@Lazy
@Slf4j
@Component("game")
public class SimpleOpenWorldGame implements OpenWorldGame, SmartLifecycle {
private final WorldManager worldManager;
private final GameConfig gameConfig;
private World firstSpawnWorld;
private boolean running = false;
@Autowired
public SimpleOpenWorldGame(WorldManager worldManager, GameConfig gameConfig) {
this.worldManager = worldManager;
this.gameConfig = gameConfig;
}
@Override
public World getFirstSpawnWorld() {
return firstSpawnWorld;
}
@Override
public void start() {
gameConfig.getWorlds().stream()
.filter(WorldConfig::isAutoload)
.forEach(this::loadWorld);
log.info("Started OpenWorldGame");
running = true;
}
private void loadWorld(WorldConfig worldConfig) {
try {
World world = this.worldManager.loadWorld(worldConfig).completable().join();
if (worldConfig.isFirstSpawnWorld()) {
firstSpawnWorld = world;
}
} catch (Exception e) {
log.error("Failed to load auto-load world " + worldConfig.getName(), e);
}
}
@Override
public void stop() {
this.worldManager.getLoadedWorlds().forEach(world -> this.worldManager.unloadWorld(world.getWorldConfig()));
log.info("Stopped OpenWorldGame");
running = false;
}
@Override
public boolean isRunning() {
return running;
}
@Override
public boolean isAutoStartup() {
return true;
}
@Override
public void stop(@Nonnull Runnable callback) {
stop();
callback.run();
}
@Override
public int getPhase() {
return 5;
}
}
| 0 | 0.704952 | 1 | 0.704952 | game-dev | MEDIA | 0.618023 | game-dev,web-backend | 0.745784 | 1 | 0.745784 |
goldeneye-source/ges-code | 12,708 | game/server/team_control_point_round.cpp | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//===========================================================================//
#include "cbase.h"
#include "team_control_point_master.h"
#include "teamplayroundbased_gamerules.h"
#include "team_control_point_round.h"
#if defined ( TF_DLL )
#include "tf_gamerules.h"
#endif
BEGIN_DATADESC( CTeamControlPointRound )
DEFINE_KEYFIELD( m_bDisabled, FIELD_BOOLEAN, "StartDisabled" ),
DEFINE_KEYFIELD( m_iszCPNames, FIELD_STRING, "cpr_cp_names" ),
DEFINE_KEYFIELD( m_nPriority, FIELD_INTEGER, "cpr_priority" ),
DEFINE_KEYFIELD( m_iInvalidCapWinner, FIELD_INTEGER, "cpr_restrict_team_cap_win" ),
DEFINE_KEYFIELD( m_iszPrintName, FIELD_STRING, "cpr_printname" ),
// DEFINE_FIELD( m_ControlPoints, CUtlVector < CHandle < CTeamControlPoint > > ),
DEFINE_INPUTFUNC( FIELD_VOID, "Enable", InputEnable ),
DEFINE_INPUTFUNC( FIELD_VOID, "Disable", InputDisable ),
DEFINE_INPUTFUNC( FIELD_VOID, "RoundSpawn", InputRoundSpawn ),
DEFINE_OUTPUT( m_OnStart, "OnStart" ),
DEFINE_OUTPUT( m_OnEnd, "OnEnd" ),
DEFINE_OUTPUT( m_OnWonByTeam1, "OnWonByTeam1" ),
DEFINE_OUTPUT( m_OnWonByTeam2, "OnWonByTeam2" ),
END_DATADESC()
LINK_ENTITY_TO_CLASS( team_control_point_round, CTeamControlPointRound );
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTeamControlPointRound::Spawn( void )
{
SetTouch( NULL );
BaseClass::Spawn();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTeamControlPointRound::Activate( void )
{
BaseClass::Activate();
FindControlPoints();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTeamControlPointRound::FindControlPoints( void )
{
// Let out control point masters know that the round has started
CTeamControlPointMaster *pMaster = g_hControlPointMasters.Count() ? g_hControlPointMasters[0] : NULL;
if ( pMaster )
{
// go through all the points
CBaseEntity *pEnt = gEntList.FindEntityByClassname( NULL, pMaster->GetControlPointName() );
while( pEnt )
{
CTeamControlPoint *pPoint = assert_cast<CTeamControlPoint *>(pEnt);
if ( pPoint )
{
const char *pString = STRING( m_iszCPNames );
const char *pName = STRING( pPoint->GetEntityName() );
// HACK to work around a problem with cp_a being returned for an entity name with cp_A
const char *pos = Q_stristr( pString, pName );
if ( pos )
{
int len = Q_strlen( STRING( pPoint->GetEntityName() ) );
if ( *(pos + len) == ' ' || *(pos + len) == '\0' )
{
if( m_ControlPoints.Find( pPoint ) == m_ControlPoints.InvalidIndex() )
{
DevMsg( 2, "Adding control point %s to control point round %s\n", pPoint->GetEntityName().ToCStr(), GetEntityName().ToCStr() );
m_ControlPoints.AddToHead( pPoint );
}
}
}
}
pEnt = gEntList.FindEntityByClassname( pEnt, pMaster->GetControlPointName() );
}
}
if( m_ControlPoints.Count() == 0 )
{
Warning( "Error! No control points found in map for team_game_round %s!\n", GetEntityName().ToCStr() );
}
}
//-----------------------------------------------------------------------------
// Purpose: Check that the points aren't all held by one team if they are
// this will reset the round and will reset all the points
//-----------------------------------------------------------------------------
int CTeamControlPointRound::CheckWinConditions( void )
{
int iWinners = TeamOwnsAllPoints();
if ( ( m_iInvalidCapWinner != 1 ) &&
( iWinners >= FIRST_GAME_TEAM ) &&
( iWinners != m_iInvalidCapWinner ) )
{
bool bWinner = true;
#if defined( TF_DLL)
if ( TFGameRules() && TFGameRules()->IsInKothMode() )
{
CTeamRoundTimer *pTimer = NULL;
if ( iWinners == TF_TEAM_RED )
{
pTimer = TFGameRules()->GetRedKothRoundTimer();
}
else if ( iWinners == TF_TEAM_BLUE )
{
pTimer = TFGameRules()->GetBlueKothRoundTimer();
}
if ( pTimer )
{
if ( pTimer->GetTimeRemaining() > 0 || TFGameRules()->TimerMayExpire() == false )
{
bWinner = false;
}
}
}
#endif
if ( bWinner )
{
FireTeamWinOutput( iWinners );
return iWinners;
}
}
return -1;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTeamControlPointRound::FireTeamWinOutput( int iWinningTeam )
{
// Remap team so that first game team = 1
switch( iWinningTeam - FIRST_GAME_TEAM+1 )
{
case 1:
m_OnWonByTeam1.FireOutput( this, this );
break;
case 2:
m_OnWonByTeam2.FireOutput( this, this );
break;
default:
Assert(0);
break;
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
int CTeamControlPointRound::GetPointOwner( int point )
{
Assert( point >= 0 );
Assert( point < MAX_CONTROL_POINTS );
CTeamControlPoint *pPoint = m_ControlPoints[point];
if ( pPoint )
return pPoint->GetOwner();
return TEAM_UNASSIGNED;
}
//-----------------------------------------------------------------------------
// Purpose: This function returns the team that owns all the cap points.
// If its not the case that one team owns them all, it returns 0.
//
// Can be passed an overriding team. If this is not null, the passed team
// number will be used for that cp. Used to predict if that CP changing would
// win the game.
//-----------------------------------------------------------------------------
int CTeamControlPointRound::TeamOwnsAllPoints( CTeamControlPoint *pOverridePoint /* = NULL */, int iOverrideNewTeam /* = TEAM_UNASSIGNED */ )
{
int i;
int iWinningTeam[MAX_CONTROL_POINT_GROUPS];
for( i = 0 ; i < MAX_CONTROL_POINT_GROUPS ; i++ )
{
iWinningTeam[i] = TEAM_INVALID;
}
// if TEAM_INVALID, haven't found a flag for this group yet
// if TEAM_UNASSIGNED, the group is still being contested
// for each control point
for( i = 0 ; i < m_ControlPoints.Count() ; i++ )
{
int group = m_ControlPoints[i]->GetCPGroup();
int owner = m_ControlPoints[i]->GetOwner();
if ( pOverridePoint == m_ControlPoints[i] )
{
owner = iOverrideNewTeam;
}
// the first one we find in this group, set the win to true
if ( iWinningTeam[group] == TEAM_INVALID )
{
iWinningTeam[group] = owner;
}
// unassigned means this group is already contested, move on
else if ( iWinningTeam[group] == TEAM_UNASSIGNED )
{
continue;
}
// if we find another one in the group that isn't the same owner, set the win to false
else if ( owner != iWinningTeam[group] )
{
iWinningTeam[group] = TEAM_UNASSIGNED;
}
}
// report the first win we find as the winner
for ( i = 0 ; i < MAX_CONTROL_POINT_GROUPS ; i++ )
{
if ( iWinningTeam[i] >= FIRST_GAME_TEAM )
return iWinningTeam[i];
}
// no wins yet
return TEAM_UNASSIGNED;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CTeamControlPointRound::WouldNewCPOwnerWinGame( CTeamControlPoint *pPoint, int iNewOwner )
{
return ( TeamOwnsAllPoints( pPoint, iNewOwner ) == iNewOwner );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTeamControlPointRound::InputEnable( inputdata_t &input )
{
m_bDisabled = false;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTeamControlPointRound::InputDisable( inputdata_t &input )
{
m_bDisabled = true;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTeamControlPointRound::InputRoundSpawn( inputdata_t &input )
{
// clear out old control points
m_ControlPoints.RemoveAll();
// find the control points
FindControlPoints();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTeamControlPointRound::SetupSpawnPoints( void )
{
CTeamplayRoundBasedRules *pRules = TeamplayRoundBasedRules();
if ( pRules )
{
pRules->SetupSpawnPointsForRound();
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTeamControlPointRound::SelectedToPlay( void )
{
SetupSpawnPoints();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTeamControlPointRound::FireOnStartOutput( void )
{
m_OnStart.FireOutput( this, this );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTeamControlPointRound::FireOnEndOutput( void )
{
m_OnEnd.FireOutput( this, this );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CTeamControlPointRound::IsControlPointInRound( CTeamControlPoint *pPoint )
{
if ( !pPoint )
{
return false;
}
return ( m_ControlPoints.Find( pPoint ) != m_ControlPoints.InvalidIndex() );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CTeamControlPointRound::IsPlayable( void )
{
int iWinners = TeamOwnsAllPoints();
if ( m_iInvalidCapWinner == 1 ) // neither team can win this round by capping
{
return true;
}
if ( ( iWinners >= FIRST_GAME_TEAM ) &&
( iWinners != m_iInvalidCapWinner ) )
{
return false; // someone has already won this round
}
return true;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CTeamControlPointRound::MakePlayable( void )
{
CTeamControlPointMaster *pMaster = g_hControlPointMasters.Count() ? g_hControlPointMasters[0] : NULL;
if ( pMaster )
{
if ( !IsPlayable() )
{
// we need to try switching the owners of the teams to make this round playable
for ( int iTeam = FIRST_GAME_TEAM ; iTeam < GetNumberOfTeams() ; iTeam++ )
{
for ( int iControlPoint = 0 ; iControlPoint < m_ControlPoints.Count() ; iControlPoint++ )
{
if ( ( !pMaster->IsBaseControlPoint( m_ControlPoints[iControlPoint]->GetPointIndex() ) ) && // this is NOT the base point for one of the teams (we don't want to assign the base to the wrong team)
( !WouldNewCPOwnerWinGame( m_ControlPoints[iControlPoint], iTeam ) ) ) // making this change would make this round playable
{
// need to find the trigger area associated with this point
for ( int iObj=0; iObj<ITriggerAreaCaptureAutoList::AutoList().Count(); ++iObj )
{
CTriggerAreaCapture *pArea = static_cast< CTriggerAreaCapture * >( ITriggerAreaCaptureAutoList::AutoList()[iObj] );
if ( pArea->TeamCanCap( iTeam ) )
{
CHandle<CTeamControlPoint> hPoint = pArea->GetControlPoint();
if ( hPoint == m_ControlPoints[iControlPoint] )
{
// found!
pArea->ForceOwner( iTeam ); // this updates the trigger_area *and* the control_point
return true;
}
}
}
}
}
}
}
}
return false;
}
//-----------------------------------------------------------------------------
// Purpose: returns the first point found that the given team owns
//-----------------------------------------------------------------------------
CHandle<CTeamControlPoint> CTeamControlPointRound::GetPointOwnedBy( int iTeam )
{
for( int i = 0 ; i < m_ControlPoints.Count() ; i++ )
{
if ( m_ControlPoints[i]->GetOwner() == iTeam )
{
return m_ControlPoints[i];
}
}
return NULL;
}
| 0 | 0.976115 | 1 | 0.976115 | game-dev | MEDIA | 0.685285 | game-dev | 0.965177 | 1 | 0.965177 |
sergev/4.4BSD-Lite2 | 5,679 | usr/src/games/trek/kill.c | /*
* Copyright (c) 1980, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#ifndef lint
static char sccsid[] = "@(#)kill.c 8.1 (Berkeley) 5/31/93";
#endif /* not lint */
# include "trek.h"
/*
** KILL KILL KILL !!!
**
** This file handles the killing off of almost anything.
*/
/*
** Handle a Klingon's death
**
** The Klingon at the sector given by the parameters is killed
** and removed from the Klingon list. Notice that it is not
** removed from the event list; this is done later, when the
** the event is to be caught. Also, the time left is recomputed,
** and the game is won if that was the last klingon.
*/
killk(ix, iy)
int ix, iy;
{
register int i, j;
printf(" *** Klingon at %d,%d destroyed ***\n", ix, iy);
/* remove the scoundrel */
Now.klings -= 1;
Sect[ix][iy] = EMPTY;
Quad[Ship.quadx][Ship.quady].klings -= 1;
/* %%% IS THIS SAFE???? %%% */
Quad[Ship.quadx][Ship.quady].scanned -= 100;
Game.killk += 1;
/* find the Klingon in the Klingon list */
for (i = 0; i < Etc.nkling; i++)
if (ix == Etc.klingon[i].x && iy == Etc.klingon[i].y)
{
/* purge him from the list */
Etc.nkling -= 1;
for (; i < Etc.nkling; i++)
bmove(&Etc.klingon[i+1], &Etc.klingon[i], sizeof Etc.klingon[i]);
break;
}
/* find out if that was the last one */
if (Now.klings <= 0)
win();
/* recompute time left */
Now.time = Now.resource / Now.klings;
return;
}
/*
** handle a starbase's death
*/
killb(qx, qy)
int qx, qy;
{
register struct quad *q;
register struct xy *b;
q = &Quad[qx][qy];
if (q->bases <= 0)
return;
if (!damaged(SSRADIO))
/* then update starchart */
if (q->scanned < 1000)
q->scanned -= 10;
else
if (q->scanned > 1000)
q->scanned = -1;
q->bases = 0;
Now.bases -= 1;
for (b = Now.base; ; b++)
if (qx == b->x && qy == b->y)
break;
bmove(&Now.base[Now.bases], b, sizeof *b);
if (qx == Ship.quadx && qy == Ship.quady)
{
Sect[Etc.starbase.x][Etc.starbase.y] = EMPTY;
if (Ship.cond == DOCKED)
undock();
printf("Starbase at %d,%d destroyed\n", Etc.starbase.x, Etc.starbase.y);
}
else
{
if (!damaged(SSRADIO))
{
printf("Uhura: Starfleet command reports that the starbase in\n");
printf(" quadrant %d,%d has been destroyed\n", qx, qy);
}
else
schedule(E_KATSB | E_GHOST, 1e50, qx, qy, 0);
}
}
/**
** kill an inhabited starsystem
**/
kills(x, y, f)
int x, y; /* quad coords if f == 0, else sector coords */
int f; /* f != 0 -- this quad; f < 0 -- Enterprise's fault */
{
register struct quad *q;
register struct event *e;
register char *name;
char *systemname();
if (f)
{
/* current quadrant */
q = &Quad[Ship.quadx][Ship.quady];
Sect[x][y] = EMPTY;
name = systemname(q);
if (name == 0)
return;
printf("Inhabited starsystem %s at %d,%d destroyed\n",
name, x, y);
if (f < 0)
Game.killinhab += 1;
}
else
{
/* different quadrant */
q = &Quad[x][y];
}
if (q->qsystemname & Q_DISTRESSED)
{
/* distressed starsystem */
e = &Event[q->qsystemname & Q_SYSTEM];
printf("Distress call for %s invalidated\n",
Systemname[e->systemname]);
unschedule(e);
}
q->qsystemname = 0;
q->stars -= 1;
}
/**
** "kill" a distress call
**/
killd(x, y, f)
int x, y; /* quadrant coordinates */
int f; /* set if user is to be informed */
{
register struct event *e;
register int i;
register struct quad *q;
q = &Quad[x][y];
for (i = 0; i < MAXEVENTS; i++)
{
e = &Event[i];
if (e->x != x || e->y != y)
continue;
switch (e->evcode)
{
case E_KDESB:
if (f)
{
printf("Distress call for starbase in %d,%d nullified\n",
x, y);
unschedule(e);
}
break;
case E_ENSLV:
case E_REPRO:
if (f)
{
printf("Distress call for %s in quadrant %d,%d nullified\n",
Systemname[e->systemname], x, y);
q->qsystemname = e->systemname;
unschedule(e);
}
else
{
e->evcode |= E_GHOST;
}
}
}
}
| 0 | 0.850423 | 1 | 0.850423 | game-dev | MEDIA | 0.835031 | game-dev | 0.884201 | 1 | 0.884201 |
ezEngine/ezEngine | 14,476 | Code/UnitTests/GameEngineTest/StateMachineTest/StateMachineBuiltinsTest.cpp | #include <GameEngineTest/GameEngineTestPCH.h>
#include "StateMachineTest.h"
#include <GameEngine/StateMachine/StateMachineBuiltins.h>
namespace
{
class TestState : public ezStateMachineState
{
EZ_ADD_DYNAMIC_REFLECTION(TestState, ezStateMachineState);
public:
TestState(ezStringView sName = ezStringView())
: ezStateMachineState(sName)
{
}
virtual void OnEnter(ezStateMachineInstance& ref_instance, void* pInstanceData, const ezStateMachineState* pFromState) const override
{
auto pData = static_cast<InstanceData*>(pInstanceData);
pData->m_Counter.m_uiEnterCounter++;
m_CounterTable[&ref_instance] = pData->m_Counter;
}
virtual void OnExit(ezStateMachineInstance& ref_instance, void* pInstanceData, const ezStateMachineState* pToState) const override
{
auto pData = static_cast<InstanceData*>(pInstanceData);
pData->m_Counter.m_uiExitCounter++;
m_CounterTable[&ref_instance] = pData->m_Counter;
}
virtual bool GetInstanceDataDesc(ezInstanceDataDesc& out_desc) override
{
out_desc.FillFromType<InstanceData>();
return true;
}
struct Counter
{
ezUInt32 m_uiEnterCounter = 0;
ezUInt32 m_uiExitCounter = 0;
};
mutable ezHashTable<ezStateMachineInstance*, Counter> m_CounterTable;
struct InstanceData
{
InstanceData() { s_uiConstructionCounter++; }
~InstanceData() { s_uiDestructionCounter++; }
Counter m_Counter;
static ezUInt32 s_uiConstructionCounter;
static ezUInt32 s_uiDestructionCounter;
};
};
ezUInt32 TestState::InstanceData::s_uiConstructionCounter = 0;
ezUInt32 TestState::InstanceData::s_uiDestructionCounter = 0;
// clang-format off
EZ_BEGIN_DYNAMIC_REFLECTED_TYPE(TestState, 1, ezRTTIDefaultAllocator<TestState>)
EZ_END_DYNAMIC_REFLECTED_TYPE;
// clang-format on
class TestTransition : public ezStateMachineTransition
{
public:
bool IsConditionMet(ezStateMachineInstance& ref_instance, void* pInstanceData) const override
{
auto pData = static_cast<InstanceData*>(pInstanceData);
pData->m_uiConditionCounter++;
return pData->m_uiConditionCounter > 1;
}
bool GetInstanceDataDesc(ezInstanceDataDesc& out_desc) override
{
out_desc.FillFromType<InstanceData>();
return true;
}
struct InstanceData
{
InstanceData() { s_uiConstructionCounter++; }
~InstanceData() { s_uiDestructionCounter++; }
ezUInt32 m_uiConditionCounter;
static ezUInt32 s_uiConstructionCounter;
static ezUInt32 s_uiDestructionCounter;
};
};
ezUInt32 TestTransition::InstanceData::s_uiConstructionCounter = 0;
ezUInt32 TestTransition::InstanceData::s_uiDestructionCounter = 0;
static void ResetCounter()
{
TestState::InstanceData::s_uiConstructionCounter = 0;
TestState::InstanceData::s_uiDestructionCounter = 0;
TestTransition::InstanceData::s_uiConstructionCounter = 0;
TestTransition::InstanceData::s_uiDestructionCounter = 0;
}
static ezTime s_TimeStep = ezTime::MakeFromMilliseconds(10);
} // namespace
void ezGameEngineTestStateMachine::RunBuiltinsTest()
{
ezReflectedClass fakeOwner;
EZ_TEST_BLOCK(ezTestBlock::Enabled, "Simple States")
{
ResetCounter();
ezSharedPtr<ezStateMachineDescription> pDesc = EZ_DEFAULT_NEW(ezStateMachineDescription);
auto pStateA = EZ_DEFAULT_NEW(TestState, "A");
pDesc->AddState(pStateA);
auto pStateB = EZ_DEFAULT_NEW(TestState, "B");
pDesc->AddState(pStateB);
auto pTransition = EZ_DEFAULT_NEW(TestTransition);
pDesc->AddTransition(1, 0, pTransition);
ezStateMachineInstance* pInstance = nullptr;
{
ezStateMachineInstance sm(fakeOwner, pDesc);
EZ_TEST_INT(TestState::InstanceData::s_uiConstructionCounter, 2);
EZ_TEST_INT(TestTransition::InstanceData::s_uiConstructionCounter, 1);
EZ_TEST_INT(pStateA->m_CounterTable[&sm].m_uiEnterCounter, 0);
EZ_TEST_INT(pStateA->m_CounterTable[&sm].m_uiExitCounter, 0);
EZ_TEST_INT(pStateB->m_CounterTable[&sm].m_uiEnterCounter, 0);
EZ_TEST_INT(pStateB->m_CounterTable[&sm].m_uiExitCounter, 0);
ezHashedString sStateName; // intentionally left empty to go to fallback state (state with index 0 -> state "A")
EZ_TEST_BOOL(sm.SetStateOrFallback(sStateName).Succeeded());
EZ_TEST_INT(pStateA->m_CounterTable[&sm].m_uiEnterCounter, 1);
EZ_TEST_INT(pStateA->m_CounterTable[&sm].m_uiExitCounter, 0);
EZ_TEST_INT(pStateB->m_CounterTable[&sm].m_uiEnterCounter, 0);
EZ_TEST_INT(pStateB->m_CounterTable[&sm].m_uiExitCounter, 0);
EZ_TEST_BOOL(sm.SetState(pStateB).Succeeded());
EZ_TEST_INT(pStateA->m_CounterTable[&sm].m_uiEnterCounter, 1);
EZ_TEST_INT(pStateA->m_CounterTable[&sm].m_uiExitCounter, 1);
EZ_TEST_INT(pStateB->m_CounterTable[&sm].m_uiEnterCounter, 1);
EZ_TEST_INT(pStateB->m_CounterTable[&sm].m_uiExitCounter, 0);
sStateName.Assign("C");
EZ_TEST_BOOL(sm.SetState(sStateName).Failed());
// no transition yet
sm.Update(s_TimeStep);
EZ_TEST_INT(pStateA->m_CounterTable[&sm].m_uiEnterCounter, 1);
EZ_TEST_INT(pStateA->m_CounterTable[&sm].m_uiExitCounter, 1);
EZ_TEST_INT(pStateB->m_CounterTable[&sm].m_uiEnterCounter, 1);
EZ_TEST_INT(pStateB->m_CounterTable[&sm].m_uiExitCounter, 0);
// go back to "A"
sm.Update(s_TimeStep);
EZ_TEST_INT(pStateA->m_CounterTable[&sm].m_uiEnterCounter, 2);
EZ_TEST_INT(pStateA->m_CounterTable[&sm].m_uiExitCounter, 1);
EZ_TEST_INT(pStateB->m_CounterTable[&sm].m_uiEnterCounter, 1);
EZ_TEST_INT(pStateB->m_CounterTable[&sm].m_uiExitCounter, 1);
pInstance = &sm; // will be dead after this line but we only need the pointer
}
EZ_TEST_INT(TestState::InstanceData::s_uiDestructionCounter, 2);
EZ_TEST_INT(TestTransition::InstanceData::s_uiDestructionCounter, 1);
EZ_TEST_INT(pStateA->m_CounterTable[pInstance].m_uiEnterCounter, 2);
EZ_TEST_INT(pStateA->m_CounterTable[pInstance].m_uiExitCounter, 2);
EZ_TEST_INT(pStateB->m_CounterTable[pInstance].m_uiEnterCounter, 1);
EZ_TEST_INT(pStateB->m_CounterTable[pInstance].m_uiExitCounter, 1);
}
EZ_TEST_BLOCK(ezTestBlock::Enabled, "Blackboard Transition")
{
ResetCounter();
ezSharedPtr<ezStateMachineDescription> pDesc = EZ_DEFAULT_NEW(ezStateMachineDescription);
auto pStateA = EZ_DEFAULT_NEW(TestState, "A");
pDesc->AddState(pStateA);
auto pStateB = EZ_DEFAULT_NEW(TestState, "B");
pDesc->AddState(pStateB);
auto pStateC = EZ_DEFAULT_NEW(TestState, "C");
pDesc->AddState(pStateC);
ezHashedString sTestVal = ezMakeHashedString("TestVal");
ezHashedString sTestVal2 = ezMakeHashedString("TestVal2");
{
auto pTransition = EZ_DEFAULT_NEW(ezStateMachineTransition_BlackboardConditions);
auto& cond = pTransition->m_Conditions.ExpandAndGetRef();
cond.m_sEntryName = sTestVal;
cond.m_fComparisonValue = 2;
cond.m_Operator = ezComparisonOperator::Greater;
auto& cond2 = pTransition->m_Conditions.ExpandAndGetRef();
cond2.m_sEntryName = sTestVal2;
cond2.m_fComparisonValue = 10;
cond2.m_Operator = ezComparisonOperator::Equal;
pDesc->AddTransition(0, 1, pTransition);
}
{
auto pTransition = EZ_DEFAULT_NEW(ezStateMachineTransition_BlackboardConditions);
pTransition->m_Operator = ezStateMachineLogicOperator::Or;
auto& cond = pTransition->m_Conditions.ExpandAndGetRef();
cond.m_sEntryName = sTestVal;
cond.m_fComparisonValue = 3;
cond.m_Operator = ezComparisonOperator::Greater;
auto& cond2 = pTransition->m_Conditions.ExpandAndGetRef();
cond2.m_sEntryName = sTestVal2;
cond2.m_fComparisonValue = 20;
cond2.m_Operator = ezComparisonOperator::Equal;
pDesc->AddTransition(1, 2, pTransition);
}
{
ezSharedPtr<ezBlackboard> pBlackboard = ezBlackboard::Create();
pBlackboard->SetEntryValue(sTestVal, 2);
pBlackboard->SetEntryValue(sTestVal2, 0);
ezStateMachineInstance sm(fakeOwner, pDesc);
sm.SetBlackboard(pBlackboard);
EZ_TEST_BOOL(sm.SetState(pStateA).Succeeded());
// no transition yet since only part of the conditions is true
pBlackboard->SetEntryValue(sTestVal, 3);
sm.Update(s_TimeStep);
EZ_TEST_INT(pStateA->m_CounterTable[&sm].m_uiEnterCounter, 1);
EZ_TEST_INT(pStateA->m_CounterTable[&sm].m_uiExitCounter, 0);
EZ_TEST_INT(pStateB->m_CounterTable[&sm].m_uiEnterCounter, 0);
EZ_TEST_INT(pStateB->m_CounterTable[&sm].m_uiExitCounter, 0);
EZ_TEST_INT(pStateC->m_CounterTable[&sm].m_uiEnterCounter, 0);
EZ_TEST_INT(pStateC->m_CounterTable[&sm].m_uiExitCounter, 0);
// transition to B
pBlackboard->SetEntryValue(sTestVal2, 10);
sm.Update(s_TimeStep);
EZ_TEST_INT(pStateA->m_CounterTable[&sm].m_uiEnterCounter, 1);
EZ_TEST_INT(pStateA->m_CounterTable[&sm].m_uiExitCounter, 1);
EZ_TEST_INT(pStateB->m_CounterTable[&sm].m_uiEnterCounter, 1);
EZ_TEST_INT(pStateB->m_CounterTable[&sm].m_uiExitCounter, 0);
EZ_TEST_INT(pStateC->m_CounterTable[&sm].m_uiEnterCounter, 0);
EZ_TEST_INT(pStateC->m_CounterTable[&sm].m_uiExitCounter, 0);
// transition to C, only part of the condition needed because of 'OR' operator
pBlackboard->SetEntryValue(sTestVal2, 20);
sm.Update(s_TimeStep);
EZ_TEST_INT(pStateA->m_CounterTable[&sm].m_uiEnterCounter, 1);
EZ_TEST_INT(pStateA->m_CounterTable[&sm].m_uiExitCounter, 1);
EZ_TEST_INT(pStateB->m_CounterTable[&sm].m_uiEnterCounter, 1);
EZ_TEST_INT(pStateB->m_CounterTable[&sm].m_uiExitCounter, 1);
EZ_TEST_INT(pStateC->m_CounterTable[&sm].m_uiEnterCounter, 1);
EZ_TEST_INT(pStateC->m_CounterTable[&sm].m_uiExitCounter, 0);
}
}
EZ_TEST_BLOCK(ezTestBlock::Enabled, "Timeout Transition")
{
ResetCounter();
ezSharedPtr<ezStateMachineDescription> pDesc = EZ_DEFAULT_NEW(ezStateMachineDescription);
auto pStateA = EZ_DEFAULT_NEW(TestState, "A");
pDesc->AddState(pStateA);
auto pStateB = EZ_DEFAULT_NEW(TestState, "B");
pDesc->AddState(pStateB);
auto pTransition = EZ_DEFAULT_NEW(ezStateMachineTransition_Timeout);
pTransition->m_Timeout = ezTime::MakeFromMilliseconds(5);
pDesc->AddTransition(0, 1, pTransition);
{
ezStateMachineInstance sm(fakeOwner, pDesc);
EZ_TEST_BOOL(sm.SetState(pStateA).Succeeded());
sm.Update(s_TimeStep);
EZ_TEST_INT(pStateA->m_CounterTable[&sm].m_uiEnterCounter, 1);
EZ_TEST_INT(pStateA->m_CounterTable[&sm].m_uiExitCounter, 0);
EZ_TEST_INT(pStateB->m_CounterTable[&sm].m_uiEnterCounter, 0);
EZ_TEST_INT(pStateB->m_CounterTable[&sm].m_uiExitCounter, 0);
sm.Update(s_TimeStep);
EZ_TEST_INT(pStateA->m_CounterTable[&sm].m_uiEnterCounter, 1);
EZ_TEST_INT(pStateA->m_CounterTable[&sm].m_uiExitCounter, 1);
EZ_TEST_INT(pStateB->m_CounterTable[&sm].m_uiEnterCounter, 1);
EZ_TEST_INT(pStateB->m_CounterTable[&sm].m_uiExitCounter, 0);
}
}
EZ_TEST_BLOCK(ezTestBlock::Enabled, "Compounds")
{
ResetCounter();
ezSharedPtr<ezStateMachineDescription> pDesc = EZ_DEFAULT_NEW(ezStateMachineDescription);
auto pCompoundState = EZ_DEFAULT_NEW(ezStateMachineState_Compound, "A");
{
auto pAllocator = ezGetStaticRTTI<TestState>()->GetAllocator();
pCompoundState->m_SubStates.PushBack(pAllocator->Allocate<TestState>());
pCompoundState->m_SubStates.PushBack(pAllocator->Allocate<TestState>());
}
pDesc->AddState(pCompoundState);
auto pStateB = EZ_DEFAULT_NEW(TestState, "B");
pDesc->AddState(pStateB);
ezHashedString sTestVal = ezMakeHashedString("TestVal");
{
auto pCompoundTransition = EZ_DEFAULT_NEW(ezStateMachineTransition_Compound);
{
auto pAllocator = ezGetStaticRTTI<ezStateMachineTransition_BlackboardConditions>()->GetAllocator();
auto pSubTransition = pAllocator->Allocate<ezStateMachineTransition_BlackboardConditions>();
auto& cond = pSubTransition->m_Conditions.ExpandAndGetRef();
cond.m_sEntryName = sTestVal;
cond.m_fComparisonValue = 2;
cond.m_Operator = ezComparisonOperator::Greater;
pCompoundTransition->m_SubTransitions.PushBack(pSubTransition);
}
{
auto pAllocator = ezGetStaticRTTI<ezStateMachineTransition_Timeout>()->GetAllocator();
auto pSubTransition = pAllocator->Allocate<ezStateMachineTransition_Timeout>();
pSubTransition->m_Timeout = ezTime::MakeFromMilliseconds(5);
pCompoundTransition->m_SubTransitions.PushBack(pSubTransition);
}
pDesc->AddTransition(0, 1, pCompoundTransition);
}
{
ezSharedPtr<ezBlackboard> pBlackboard = ezBlackboard::Create();
pBlackboard->SetEntryValue(sTestVal, 2);
ezStateMachineInstance sm(fakeOwner, pDesc);
sm.SetBlackboard(pBlackboard);
EZ_TEST_INT(TestState::InstanceData::s_uiConstructionCounter, 1); // Compound instance data not constructed yet
EZ_TEST_BOOL(sm.SetState(pCompoundState).Succeeded());
EZ_TEST_INT(TestState::InstanceData::s_uiConstructionCounter, 3);
EZ_TEST_INT(ezStaticCast<TestState*>(pCompoundState->m_SubStates[0])->m_CounterTable[&sm].m_uiEnterCounter, 1);
EZ_TEST_INT(ezStaticCast<TestState*>(pCompoundState->m_SubStates[1])->m_CounterTable[&sm].m_uiEnterCounter, 1);
EZ_TEST_INT(pStateB->m_CounterTable[&sm].m_uiEnterCounter, 0);
EZ_TEST_INT(pStateB->m_CounterTable[&sm].m_uiExitCounter, 0);
// no transition yet because timeout is not reached yet
pBlackboard->SetEntryValue(sTestVal, 3);
sm.Update(s_TimeStep);
EZ_TEST_INT(pStateB->m_CounterTable[&sm].m_uiEnterCounter, 0);
EZ_TEST_INT(pStateB->m_CounterTable[&sm].m_uiExitCounter, 0);
// all conditions met, transition to B
sm.Update(s_TimeStep);
EZ_TEST_INT(ezStaticCast<TestState*>(pCompoundState->m_SubStates[0])->m_CounterTable[&sm].m_uiExitCounter, 1);
EZ_TEST_INT(ezStaticCast<TestState*>(pCompoundState->m_SubStates[1])->m_CounterTable[&sm].m_uiExitCounter, 1);
EZ_TEST_INT(pStateB->m_CounterTable[&sm].m_uiEnterCounter, 1);
EZ_TEST_INT(pStateB->m_CounterTable[&sm].m_uiExitCounter, 0);
}
EZ_TEST_INT(TestState::InstanceData::s_uiDestructionCounter, 3);
}
}
| 0 | 0.923395 | 1 | 0.923395 | game-dev | MEDIA | 0.67197 | game-dev | 0.840821 | 1 | 0.840821 |
2004Scape/Server | 60,633 | data/src/scripts/areas/area_karamja/scripts/trufitus.rs2 | // NOTE: rs classic dialogue is slightly different, so this may be the updated dialogue after more jungle vines, more wall fungus, and seqs with sounds were added: https://www.youtube.com/watch?v=qm8ZwROiW8s
[opnpcu,trufitus]
if(%junglepotion_progress >= ^junglepotion_complete) {
switch_obj (last_useitem) {
case zqcorpse :
~mesbox("You show Trufitus the remains...");
~chatplayer("<p,neutral>Could you have a look at this..");
~chatnpc("<p,neutral>This is truly incredible bwana... So these are the remains of the dread Queen Rashiliyia?");
~chatplayer("<p,neutral>Yes, I think so.");
@multi2("What should I do with them?", trufitus_whatcorpse, "Can you take them off my hands?", trufitus_takethem);
case zqbonekey :
~chatplayer("<p,neutral>Have a look at this!");
~chatnpc("<p,neutral>This is amazing Bwana, the level of detail is incredible. Where did you find it?");
@multi2("I made it from the bone shard that Zadimus gave me.", trufitus_bonezadimus, "Do you know what it opens?", trufitus_opens);
case zqdeadbeads :
if(%zombiequeen_progress >= ^zombiequeen_complete) @trufitus_postquest_item;
~mesbox("You show Trufitus the 'Beads of the Dead'.");
~chatplayer("<p,neutral>Take a look at this...");
~chatnpc("<p,neutral>This is very impressive Bwana, I'm quite surprised at your ingenuity. This should be a good protection against Rashiliyia if you ever find her Tomb.");
case zqberviriusscroll2 :
if(%zombiequeen_progress >= ^zombiequeen_complete) @trufitus_postquest_item;
~mesbox("You hand the notes over to Trufitus.");
~chatnpc("<p,neutral>Hmm, these notes are quite extraordinary Bwana. They give location details of Rashiliyia's tomb, and some information on how to use the crystal.");
~chatnpc("<p,neutral>The information is quite specific, North of Ah Za Rhoon! That's a great place to start looking!");
case zqbonebeads :
~mesbox("You show Trufitus the beads that you crafted.");
~chatplayer("<p,neutral>Take a look at these.");
~chatnpc("<p,neutral>Hmm, very interesting Bwana, your abilities are much more focused than I had initially thought. I presume these are to be part of the ward to protect you from Rashiliyia?");
case zqboneshard :
~mesbox("You show Trufitus the Bone Shard.");
~chatplayer("<p,neutral>Could you have a look at this please?");
~mesbox("Trufitus looks at the object for a moment.");
~chatnpc("<p,neutral>It looks like a simple shard of bone. Why do you think it is significant?");
@multi2("It appeared when I buried Zadimus' corpse.", trufitus_zadimuscorp, "No reason really.", trufitus_noreason);
case zqzadimusbones :
~mesbox("You show Trufitus the corpse.");
~chatplayer("<p,neutral>What do you make of this?");
~chatnpc("<p,neutral>! GASP ! That's incredible, where did you find it?");
~chatplayer("<p,neutral>I found the corpse in a decomposing gallows. I get a very strange feeling every time I try to bury the body.");
~chatnpc("<p,neutral>Hmmm, that sounds very strange. I sense a spirit in torment, you should try to bury the remains.");
switch_int(~p_choice2("Is there any sacred ground around here?", 1, "Can you dispose of this for me?", 2)) {
case 1 : @trufitus_sacredground;
case 2 :
~chatplayer("<p,neutral>Can you dispose of this for me?");
~mesbox("Trufitus pulls away from you...");
~chatnpc("<p,neutral>I dare not touch it. I am a spiritual man and the spirit of this being may possess me and turn me into a minion of Rashiliyia.");
}
case zqplaque :
if(%zombiequeen_progress >= ^zombiequeen_complete) @trufitus_postquest_item;
~mesbox("You hand over the Stone Plaque to Trufitus.");
~chatplayer("<p,neutral>Can you decipher this please?");
~chatnpc("<p,neutral>This is an ancient artefact!");
~mesbox("Trufitus looks at the item in awe.");
~chatnpc("<p,neutral>I can certainly try! Hmm, incredible, it seems very ancient and mentions something about Zadimus and Ah Za Rhoon. It says, 'Here lies the traitor Zadimus, let his spirit be forever tormented'.");
if(testbit(%zq_map_mechanisms, ^zq_deciphered_plaque) = ^false) %zq_map_mechanisms = setbit(%zq_map_mechanisms, ^zq_deciphered_plaque); // todo: is this set here or before?
~mesbox("Trufitus hands the Stone Plaque back.");
case zqcrystal :
if(%zombiequeen_progress >= ^zombiequeen_complete) @trufitus_postquest_item;
~mesbox("You show Trufitus the Locating Crystal.");
~chatnpc("<p,neutral>This is incredible Bwana.");
~chatplayer("<p,neutral>It is?");
~chatnpc("<p,neutral>Absolutely! This will help you to locate the entrance to Rashiliyia's tomb. Simply activate it when you think you are near, and it should glow different colours to show how near you are.");
case zqberviriusscroll :
if(%zombiequeen_progress >= ^zombiequeen_complete) @trufitus_postquest_item;
~mesbox("You hand the tattered scroll to Trufitus.");
~chatplayer("<p,neutral>What do you make of this?");
~chatnpc("<p,neutral>Truly amazing Bwana, this scroll must be ancient. I'm not sure if I get more meaning from it than you though. Perhaps Bervirius' tomb is still accessible?");
~mesbox("Trufitus hands the tattered scroll back to you.");
case zqrashiliyiascroll :
if(%zombiequeen_progress >= ^zombiequeen_complete) @trufitus_postquest_item;
~mesbox("You hand the crumpled scroll to Trufitus.");
~chatplayer("<p,neutral>Have a look at this, tell me what you think.");
~chatnpc("<p,neutral>I am speechless Bwana, this is truly ancient. Where did you find it?");
~chatplayer("<p,neutral>In an underground building of some sort.");
~chatnpc("<p,neutral>You must truly have found the temple of Ah Za Rhoon! The scroll gives some interesting details about Rashiliyia, some things I didn't know before.");
~mesbox("Trufitus gives back the scroll.");
@multi2("Anything that can help?", trufitus_anything, "Ok, thanks!", trufitus_okthanks2);
case zqbevsword :
~mesbox("You show Trufitus the sword pommel.");
~chatnpc("<p,neutral>It is a very nice item Bwana. It may be just what you need to gain access to Rashiliyia's tomb. While you were away, I did some research.");
~chatnpc("<p,neutral>Rashiliyia would spare the lives of those who wore bronze necklaces. This pommel may have some significance to Bervirius. Perhaps you can craft something from it that can help?");
~chatnpc("<p,neutral>My guess is that you will need some protection from Rashiliyia if you intend to enter her tomb!");
@multi2("How do I make a bronze necklace?", trufitus_bronzeneck, "What should I put on the necklace?", trufitus_putneck);
case mosol_wampum_belt :
if(%zombiequeen_progress = ^zombiequeen_not_started) {
~objbox(mosol_wampum_belt, "You show Trufitus the Wampum belt, he studies it for a long time.", 250, 0, divide(^objbox_height, 2));
~chatnpc("<p,neutral>Hello Bwana, this message from Mosol Rei bears bad news... Yes, things do look very bad indeed.");
@multi2("What do you know about Rashiliyia?", trufitus_rashiliyia, "Mosol Rei said something about a legend?", trufitus_legend);
} else {
~chatnpc("<p,neutral>You've already given me one of these Bwana. I'm aware of the situation with Rashiliyia.");
}
case snake_weed, ardrigal, sito_foil, volencia_moss, rogues_purse :
def_obj $herb = last_useitem;
~chatnpc("<p,neutral>Many thanks for the herb Bwana. I'll add it to my collection.");
def_int $coins_amount = ~random_range(1, 4);
inv_del(inv, $herb, 1);
inv_add(inv, coins, $coins_amount);
if ($coins_amount = 1) {
if ($herb = rogues_purse) {
mes("Trufitus gives you a coin for the rogues purse.");
} else {
mes("Trufitus gives you a coin for the <lowercase(oc_name($herb))>");
}
} else {
if ($herb = rogues_purse) {
mes("Trufitus gives you <tostring($coins_amount)> coins for the rogues purse.");
} else {
mes("Trufitus gives you <tostring($coins_amount)> coins for the <lowercase(oc_name($herb))>.");
}
}
case unidentified_ardrigal, unidentified_rogues_purse, unidentified_sito_foil, unidentified_snake_weed, unidentified_volencia_moss : @trufitus_decline_herb;
case default :
mes("You hand over the item.");
p_delay(2); // 3t
~chatnpc("<p,neutral>I'm sorry Bwana but I just don't have a use for that!");
}
return;
}
if((%junglepotion_progress = ^junglepotion_not_started) | (last_useitem ! unidentified_snake_weed & last_useitem ! unidentified_ardrigal &
last_useitem ! unidentified_sito_foil & last_useitem ! unidentified_volencia_moss & last_useitem ! unidentified_rogues_purse &
last_useitem ! snake_weed & last_useitem ! ardrigal & last_useitem ! sito_foil &
last_useitem ! volencia_moss & last_useitem ! rogues_purse)) {
~displaymessage(^dm_default);
return;
}
switch_int(%junglepotion_progress) {
case ^junglepotion_get_snake_weed, ^junglepotion_found_snake_weed :
if (last_useitem = snake_weed) {
@trufitus_accept_herb(last_useitem);
} else if (last_useitem = unidentified_snake_weed) {
@trufitus_decline_herb;
}
case ^junglepotion_get_ardrigal, ^junglepotion_found_ardrigal :
if (last_useitem = ardrigal) {
@trufitus_accept_herb(last_useitem);
} else if (last_useitem = unidentified_ardrigal) {
@trufitus_decline_herb;
}
case ^junglepotion_get_sito_foil, ^junglepotion_found_sito_foil :
if (last_useitem = sito_foil) {
@trufitus_accept_herb(last_useitem);
}else if (last_useitem = unidentified_sito_foil) {
@trufitus_decline_herb;
}
case ^junglepotion_get_volencia_moss, ^junglepotion_found_volencia_moss :
if (last_useitem = volencia_moss) {
@trufitus_accept_herb(last_useitem);
}else if (last_useitem = unidentified_volencia_moss) {
@trufitus_decline_herb;
}
case ^junglepotion_get_rogues_purse, ^junglepotion_found_rogues_purse :
if (last_useitem = rogues_purse) {
@trufitus_accept_herb(last_useitem);
} else if (last_useitem = unidentified_rogues_purse) {
@trufitus_decline_herb;
}
}
@trufitus_wrong_herb;
[opnpc1,trufitus]
if(%zombiequeen_progress > ^zombiequeen_not_started) {
switch_int(%zombiequeen_progress) {
case ^zombiequeen_complete_spoken_trufitus2 :
~chatplayer("<p,neutral>Hello Bwana!");
~chatnpc("<p,neutral>Greetings! I hope things are going well for you now. I have no new information since last we spoke. Needless to say, that if something does come up I will certainly get in touch directly.");
case ^zombiequeen_complete_spoken_trufitus1 :
~chatplayer("<p,neutral>Hello!");
%zombiequeen_progress = ^zombiequeen_complete_spoken_trufitus2;
~chatnpc("<p,neutral>Hello again Bwana! Well Done again for helping to defeat Rashiliyia. Hopefully things will return to normal around here now.");
case ^zombiequeen_complete :
~chatplayer("<p,neutral>Greetings.");
%zombiequeen_progress = ^zombiequeen_complete_spoken_trufitus1;
~chatnpc("<p,neutral>Hello Bwana. I conclude that you have been successful. Mosol sent word that the village is clearing of zombies. You have done us all a great deed!");
case ^zombiequeen_entered_with_beads, ^zombiequeen_unlocked_tombdoor, ^zombiequeen_retrieved_corpse :
~chatplayer("<p,neutral>Hello.");
~chatnpc("<p,neutral>Greetings again Bwana. I hope that you have managed to locate Rashiliyia's Tomb. Again, if you found anything interesting, please show it to me.");
def_int $op = ~p_choice2("What should I do now?", 1, "Thanks!", 2);
if($op = 2) @trufitus_thanks;
~chatplayer("<p,neutral>What should I do now?");
~mesbox("Trufitus scratches his head.");
~chatnpc("<p,neutral>Well Bwana, if you have Rashiliyia's remains, you need to find a way to put her spirit to rest. Perhaps there was a clue with one of the artefacts that you have?");
~chatnpc("<p,neutral>Why not have a look through the artefacts that you have found and see if there is some clue that might help? If you do not have her remains, you will need to find them.");
// nothing happens when talking at stage 10
case ^zombiequeen_entered_tomb_bervirius :
~chatplayer("<p,neutral>Greetings...");
~chatnpc("<p,neutral>Greetings Bwana, did you find Bervirius' Tomb?");
@multi4("I think I found Bervirius' Tomb.", trufitus_bervtomb, "I have some items that I need help with.", trufitus_items, "I need some help with the Temple of Ah Za Rhoon.", trufitus_helptemple, "No, I didn't find a thing.", trufitus_didntfind);
case ^zombiequeen_entered_ah_za_rhoon, ^zombiequeen_left_ah_za_rhoon :
~chatplayer("<p,neutral>Greetings...");
~chatnpc("<p,neutral>Greetings Bwana, you have been away! The situation with Rashiliyia is worsening! I pray that you have some good news for me.");
~chatplayer("<p,happy>I think I found the temple of Ah Za Rhoon.");
~chatnpc("<p,happy>Well that sounds great Bwana. Tell me, what did you find?");
@multi4("I have some items that I need help with.", trufitus_items, "I need help with Zadimus.", trufitus_zadimus, "I need help with Rashiliyia.", trufitus_helprash, "I need some help with the Temple of Ah Za Rhoon.", trufitus_helptemple);
case ^zombiequeen_lit_mound, ^zombiequeen_roped_mound :
~chatplayer("<p,neutral>Greetings...");
~chatnpc("<p,neutral>Greetings Bwana, you have been away! The situation with Rashiliyia is worsening! I pray that you have some good news for me.");
~chatplayer("<p,neutral>I think I have found the temple of Ah Za Rhoon. I excavated a hole and illuminated it, there is a fissure with a large drop.");
~chatnpc("<p,neutral>Trufitus|Perhaps you should explore it? If it's the temple of Ah Za Rhoon, it may be our only chance against Rashiliyia. I implore you to investigate Bwana.");
case ^zombiequeen_dug_mound :
~chatplayer("<p,neutral>Greetings...");
~chatnpc("<p,neutral>Greetings Bwana, you have been away! The situation with Rashiliyia is worsening! I pray that you have some good news for me.");
~chatplayer("<p,neutral>I think I have found the temple of Ah Za Rhoon.");
~chatplayer("<p,neutral>I excavated a hole and found a fissure. Should I go through it?");
~chatnpc("<p,neutral>Well, I would certainly investigate it..");
@multi2("What's a fissure?", trufitus_fissure, "Are fissures dangerous?", trufitus_fissuredanger);
case ^zombiequeen_searched_mound :
~chatplayer("<p,neutral>Greetings...");
~chatnpc("<p,neutral>Greetings Bwana, you have been away! The situation with Rashiliyia is worsening! I pray that you have some good news for me.");
~chatplayer("<p,neutral>I think I found something, but I am not sure what it is.");
~chatnpc("<p,neutral>Well, investigate it further, you may find something interesting!");
case ^zombiequeen_found_mound, ^zombiequeen_started : @trufitus_started_zombiequeen;
}
} else {
switch_int(%junglepotion_progress) {
case ^junglepotion_not_started : @trufitus_pre_quest;
case ^junglepotion_get_snake_weed, ^junglepotion_found_snake_weed : @trufitus_give_herb(snake_weed, unidentified_snake_weed);
case ^junglepotion_get_ardrigal, ^junglepotion_found_ardrigal : @trufitus_give_herb(ardrigal, unidentified_ardrigal);
case ^junglepotion_get_sito_foil, ^junglepotion_found_sito_foil : @trufitus_give_herb(sito_foil, unidentified_sito_foil);
case ^junglepotion_get_volencia_moss, ^junglepotion_found_volencia_moss : @trufitus_give_herb(volencia_moss, unidentified_volencia_moss);
case ^junglepotion_get_rogues_purse, ^junglepotion_found_rogues_purse : @trufitus_give_herb(rogues_purse, unidentified_rogues_purse);
case ^junglepotion_found_all_herbs : @trufitus_finish_quest;
case ^junglepotion_complete : @trufitus_greatest_respects;
case ^junglepotion_complete_after_spoken : @trufitus_post_quest;
}
}
[label,trufitus_pre_quest]
~chatnpc("<p,happy>Greetings Bwana!|I am <npc_name> Shakaya|of the Tai Bwo Wannai village.");
~chatnpc("<p,happy>Welcome to our humble village.");
def_int $option = ~p_choice3("What does Bwana mean?", 1, "Tai Bwo Wannai? What does that mean?", 2, "It's a nice village, where is everyone?", 3);
if($option = 1) {
~chatplayer("<p,happy>What does Bwana mean?");
~chatnpc("<p,happy>It means friend,|and friends come in peace.|I assume that you come in peace?");
def_int $option2 = ~p_choice2("Yes, of course I do.", 1, "What does a warrior like me know about peace?", 2);
if($option2 = 1) {
~chatplayer("<p,happy>Yes, of course I do.");
~chatnpc("<p,happy>Well, that is good news,|as I may have a proposition for you.");
def_int $option3 = ~p_choice2("A proposition eh? Sounds interesting!", 1, "I am sorry, but I am very busy.", 2);
if($option3 = 1) {
~chatplayer("<p,happy>A proposition eh? Sounds interesting!");
~chatnpc("<p,neutral>I hoped you would think so.|My people are afraid to stay in the village.");
~chatnpc("<p,neutral>They have returned to the jungle|and I need to commune with the gods");
~chatnpc("<p,neutral>to see what fate befalls us.|You can help me by collecting|some herbs that I need.");
def_int $option4 = ~p_choice2("Me? How can I help?", 1, "I am very sorry, but I don't have time for that.", 2);
if($option4 = 1) {
@start_junglepotion;
} else if($option4 = 2) {
~chatplayer("<p,happy>I am very sorry, but I don't have time for that.");
@trufitus_farewell;
}
} else if($option3 = 2) {
@trufitus_sorry;
}
} else if($option2 = 2) {
~chatplayer("<p,happy>What does a warrior like me know about peace?");
~chatnpc("<p,sad>When you grow weary of violence|and seek a more enlightened path,|please pay me a visit");
~chatnpc("<p,sad>as I may have a proposition for you.|Now I need to attend to the plight|of my people. Please excuse me...");
}
} else if($option = 2) {
~chatplayer("<p,happy>Tai Bwo Wannai? What does that mean?");
~chatnpc("<p,happy>It means 'small clearing in the jungle' but it is now the name of our village.");
@multi2("It's a nice village, where is everyone?", trufitus_ask_village, "I am sorry, but I am very busy.", trufitus_sorry);
} else if($option = 3) {
@trufitus_ask_village;
}
[label,start_junglepotion]
~chatplayer("<p,happy>Me? How can I help?");
~chatnpc("<p,neutral>I need to make a special brew!|A potion that helps me to commune with the gods.|For this potion, I need very|special herbs, that are only found in the deep jungle.");
~chatnpc("<p,neutral>I can only guide you so far as the herbs are not easy to find. With some luck, you will find each herb in turn and bring to me. I will give you details of where to find the next herb.");
~chatnpc("<p,neutral>In return for this great favour I will give you training in Herblore.");
def_int $option5 = ~p_choice2("Hmmm, sounds difficult, I don't know if I am ready for the challenge.", 1, "It sounds like just the challenge for me.", 2);
if($option5 = 2) {
if (%druid_progress = ^druid_complete) {
~chatplayer("<p,happy>It sounds like just the challenge for me.|And it would make a nice break from killing things!");
%junglepotion_progress = ^junglepotion_get_snake_weed;
~send_quest_progress(questlist:junglepotion, %junglepotion_progress, ^junglepotion_complete);
~chatnpc("<p,neutral>That is excellent Bwana!|The first herb that you need to gather is called");
~chatnpc("<p,neutral>Snake Weed.");
~chatnpc("<p,neutral>It grows near the vines in an area to the south west where");
~chatnpc("<p,neutral>the ground turns soft and the water kisses your feet.");
} else {
~mesbox("You do not meet all of the requirements to start|the Jungle Potion quest."); // todo: what happens originally?
}
} else if($option5 = 1) {
~chatplayer("<p,happy>Hmmm, sounds difficult, I don't know if I am ready for the challenge.");
~chatnpc("<p,neutral>Very well then Bwana,|maybe you will return to me invigorated|and ready to take up the challenge one day?");
}
[label,trufitus_sorry]
~chatplayer("<p,happy>I am sorry, but I am very busy.");
@trufitus_farewell;
[label,trufitus_farewell]
~chatnpc("<p,neutral>Very well then,|may your journeys bring you much joy.");
~chatnpc("<p,neutral>Maybe you will pass this way again and|you then take up my proposal?");
~chatnpc("<p,neutral>But for now, fare thee well.");
[label,trufitus_ask_village]
~chatplayer("<p,happy>It's a nice village, where is everyone?");
~chatnpc("<p,sad>My people are afraid to stay in the village.|They have returned to the jungle.|I need to commune with the gods|to see what fate befalls us.");
~chatnpc("<p,sad>You may be able to help with this.");
@multi2("Me? How can I help?", start_junglepotion, "I am sorry, but I am very busy.", trufitus_sorry);
[label,trufitus_give_herb](namedobj $herb, namedobj $unid)
switch_int(%junglepotion_progress) {
case ^junglepotion_get_snake_weed, ^junglepotion_found_snake_weed : ~chatnpc("<p,neutral>Hello Bwana, do you have the Snake Weed?");
case ^junglepotion_get_ardrigal, ^junglepotion_found_ardrigal : ~chatnpc("<p,neutral>Hello Bwana, have you been able to get the Ardrigal?");
case ^junglepotion_get_rogues_purse, ^junglepotion_found_rogues_purse : ~chatnpc("<p,happy>Greetings Bwana, have you been successful in getting the Rogues Purse?");
case ^junglepotion_get_volencia_moss, ^junglepotion_found_volencia_moss : ~chatnpc("<p,happy>Greetings Bwana, have you been successful in getting the Volencia Moss?");
case ^junglepotion_get_sito_foil, ^junglepotion_found_sito_foil : ~chatnpc("<p,happy>Greetings Bwana, have you been successful in getting the Sito Foil?");
}
def_int $option6 = ~p_choice2("Of course!", 1, "Not yet, sorry, what's the clue again?", 2);
if($option6 = 1) {
~chatplayer("<p,happy>Of course!");
if(inv_total(inv, $herb) > 0) {
@trufitus_accept_herb($herb);
} else if(inv_total(inv, $unid) > 0) {
@trufitus_decline_herb;
} else {
switch_int(%junglepotion_progress) {
case ^junglepotion_get_volencia_moss, ^junglepotion_found_volencia_moss :
~chatnpc("<p,neutral>Please don't try to deceive me!|I really need that Volencia Moss if I am to make this potion.");
case ^junglepotion_get_rogues_purse, ^junglepotion_found_rogues_purse :
~chatnpc("<p,neutral>Please don't try to deceive me,|I really need that Rogues Purse if I am to make this potion.");
case default :
~chatnpc("<p,neutral>Please don't try to deceive me.");
~trufitus_mention_herb($herb);
}
}
} else if($option6 = 2) {
if(%junglepotion_progress = ^junglepotion_get_ardrigal | %junglepotion_progress = ^junglepotion_found_ardrigal) {
~chatplayer("<p,happy>Not yet, sorry, what's the clue again ?");
} else {
~chatplayer("<p,happy>Not yet, sorry, what's the clue again?");
}
switch_int(%junglepotion_progress) {
case ^junglepotion_get_snake_weed, ^junglepotion_found_snake_weed :
~chatnpc("<p,neutral>It grows near vines in an area to the south west|where the ground turns soft and the water kisses your feet.");
case ^junglepotion_get_ardrigal, ^junglepotion_found_ardrigal :
~chatnpc("<p,neutral>You are looking for Ardrigal.|It is related to the palm and grows|in its brother's shady profusion.");
~chatnpc("<p,neutral>To the east you will find a small peninsula, it is just after the cliffs come down to meet the sands, here is where you should search for it.");
case ^junglepotion_get_sito_foil, ^junglepotion_found_sito_foil :
~chatnpc("<p,neutral>You are looking for Sito Foil, and it grows best|where the ground has been blackened|by living flame.");
case ^junglepotion_get_volencia_moss, ^junglepotion_found_volencia_moss :
~chatnpc("<p,neutral>You are looking for Volencia Moss.|It clings to rocks for its existence.|It is difficult to see, so you must search for it well.");
~chatnpc("<p,neutral>It prefers rocks of high metal content and a frequently disturbed environment. There is some, I believe to the south east of this village.");
case ^junglepotion_get_rogues_purse, ^junglepotion_found_rogues_purse :
~chatnpc("<p,neutral>You are looking for Rogues Purse.");
~chatnpc("<p,neutral>It inhabits the darkness of the underground, and grows in caverns to the north. A secret entrance to the caverns is set into the northern cliffs, be careful Bwana.");
}
~trufitus_mention_herb($herb);
}
[label,trufitus_accept_herb](obj $herb)
switch_int(%junglepotion_progress) {
case ^junglepotion_get_snake_weed, ^junglepotion_get_ardrigal, ^junglepotion_get_sito_foil, ^junglepotion_get_volencia_moss, ^junglepotion_get_rogues_purse : @trufitus_given_unid($herb); // todo: need to confirm dialogue for the different unid herbs.
case ^junglepotion_found_snake_weed :
%junglepotion_progress = ^junglepotion_get_ardrigal;
inv_del(inv, $herb, 1);
~objbox($herb, "You give the Snake Weed to <npc_name>.", 250, 0, divide(^objbox_height, 2));
~chatnpc("<p,neutral>Great, you have the Snake Weed!|Many thanks. Ok, the next herb is called <oc_name(ardrigal)>.|It is related to the palm and grows|to the east in its brother's shady profusion.");
~chatnpc("<p,neutral>To the east you will find a small peninsula, it is just after the cliffs come down to meet the sands, here is where you should search for it.");
case ^junglepotion_found_ardrigal :
%junglepotion_progress = ^junglepotion_get_sito_foil;
inv_del(inv, $herb, 1);
~objbox($herb, "You give the Ardrigal to <npc_name>.", 250, 0, divide(^objbox_height, 2));
~chatnpc("<p,neutral>Great, you have the Ardrigal! Many thanks.");
~chatnpc("<p,neutral>You are doing well Bwana. The next|herb is called Sito Foil, and it grows best|where the ground has been blackened|by the living flame.");
case ^junglepotion_found_sito_foil :
%junglepotion_progress = ^junglepotion_get_volencia_moss;
inv_del(inv, $herb, 1);
~objbox($herb, "You give the Sito Foil to <npc_name>.", 250, 0, divide(^objbox_height, 2));
~chatnpc("<p,neutral>Well done Bwana, just two more herbs to collect.");
~chatnpc("<p,neutral>The next herb is called Volencia Moss.|It clings to rocks for its existence.|It is difficult to see, so you must search for it well.");
~chatnpc("<p,neutral>It prefers rocks of high metal content and a frequently disturbed environment. There is some, I believe to the south east of this village.");
case ^junglepotion_found_volencia_moss :
%junglepotion_progress = ^junglepotion_get_rogues_purse;
inv_del(inv, $herb, 1);
~objbox($herb, "You give the Volencia Moss to <npc_name>.", 250, 0, divide(^objbox_height, 2));
~chatnpc("<p,neutral>Ah Volencia Moss, beautiful. One final herb and the potion will be complete. This is the most difficult to find as it inhabits the darkness of the underground. It is called Rogues Purse, and is only to be found in");
~chatnpc("<p,neutral>caverns in the northern part of this island. A secret entrance to the caverns is set into the northern cliffs of this land. Take care Bwana as it may be dangerous.");
case ^junglepotion_found_rogues_purse :
// https://youtu.be/9LG-opZVpfY?si=fQ-DSP4VpQUVWiSb&t=835
%junglepotion_progress = ^junglepotion_found_all_herbs;
inv_del(inv, $herb, 1);
~objbox($herb, "You give the Rogues Purse to <npc_name>.", 250, 0, divide(^objbox_height, 2));
~chatnpc("<p,neutral>Most excellent Bwana!|You have returned all the herbs to me|and, I can finish the preparations|for the potion, and at last divine with the gods.");
~chatnpc("<p,neutral>Many blessings on you!|I must now prepare,|please excuse me while I make|the arrangements.");
@trufitus_finish_quest;
}
[label,trufitus_given_unid](obj $herb)
// only rogues and snake weed are obtaininable in OSRS, theres a stage for each so i'm assuming a dialogue internally exists for all herbs
switch_obj($herb) {
case rogues_purse : ~chatnpc("<p,angry>That's not fresh Rogues Purse, did you pick it yourself? Go get me some fresh Rogues Purse and remember to pick it yourself.");
case default : ~chatnpc("<p,angry>That's not fresh <lowercase(oc_name($herb))>, did you pick it yourself? Go get me some fresh <lowercase(oc_name($herb))> and remember to pick it yourself.");
}
[label,trufitus_decline_herb]
~chatnpc("<p,confused>Sorry, Bwana, that herb is so dirty that I can't even tell whether it is fresh. Please clean it first.");
[label,trufitus_wrong_herb]
~chatnpc("<p,neutral>Many thanks Bwana, but I don't need that herb at the moment. Can you please get me the herb I asked for?");
[proc,trufitus_mention_herb](namedobj $herb)
switch_namedobj($herb) {
case snake_weed : ~chatnpc("<p,neutral>I really need that Snake Weed if I am to make this potion.");
case sito_foil : ~chatnpc("<p,neutral>I really need that Sito Foil if I am to make this potion.");
case ardrigal : ~chatnpc("<p,neutral>I really need that Ardrigal if I am to make this potion.");
case rogues_purse : ~chatnpc("<p,neutral>I really need that Rogues Purse if I am to make this potion.");
case volencia_moss : ~chatnpc("<p,neutral>I really need that Volencia Moss if I am to make this potion.");
}
[label,trufitus_finish_quest]
~mesbox("<npc_name> shows you some techniques in Herblore.|You gain some experience in Herblore.");
queue(junglepotion_quest_complete, 0);
[label,trufitus_greatest_respects]
// this dialogue repeats until talking to Timfraku (sept 2004+), in RSC it will go to trifitus_post_quest
~chatnpc("<p,neutral>My greatest respects Bwana,|I have communed with my gods and the future");
~chatnpc("<p,neutral>looks good for my people.|We are happy now that the gods are not angry with us.");
~chatnpc("<p,neutral>With some blessings we will be safe here.");
%junglepotion_progress = ^junglepotion_complete_after_spoken;
//~chatnpc("<p,happy>You should deliver the good news to bwana Timfraku, chief of Tai Bwo Wannai. He lives in a raised hut not far from here.");
[label,trufitus_post_quest]
if(inv_total(inv, mosol_wampum_belt) > 0) {
~chatplayer("<p,neutral>Greetings.");
~chatnpc("<p,neutral>Greetings Bwana!|You look like you have some serious news.");
~chatplayer("<p,neutral>Well, I think I may have. I have just spoken to Mosol Rei and he says that Rashiliyia has returned...");
~chatnpc("<p,neutral>Oh dear, it is more serious than I have imagined.");
@multi3("What do you know about Rashiliyia?", trufitus_rashiliyia, "What do you know about Mosol Rei?", trufitus_mosolrei, "Mosol gave me something to show you.", trufitus_mosolgave);
}
~chatnpc("<p,neutral>Greetings once again Bwana,");
~chatnpc("<p,neutral>I have no more news since we last spoke.");
[label,trufitus_rashiliyia]
~chatplayer("<p,neutral>What do you know about Rashiliyia?");
~chatnpc("<p,neutral>Hmmm, it's been a long time since I heard that name. Rashiliyia is the Queen of the Undead. And a more fearsome enemy you will be unlikely to find.");
~chatnpc("<p,neutral>I fear that you bring me news that she has returned to plague us once again? Alas I know of no weakness that she has.");
@multi3("So there is nothing we can do?", trufitus_nothing, "Should I start to evacuate the island?", trufitus_evacuate, "Mosol Rei said something about a legend?", trufitus_legend);
[label,trufitus_nothing]
~chatplayer("<p,neutral>So there is nothing we can do?");
~chatnpc("<p,neutral>Not that I can think of.");
@multi2("Oh, ok!", trufitus_ohok, "Should I start to evacuate the Island?", trufitus_evacuate);
[label,trufitus_ohok]
~chatplayer("<p,neutral>Oh, ok!");
~chatnpc("<p,neutral>Yes, it's a bit sad really, I liked that village.");
~mesbox("Trufitus seems deeply touched...");
~chatnpc("<p,neutral>Well, I hope you will excuse me, but I need to get back to my studies.");
[label,trufitus_evacuate]
~chatplayer("<p,neutral>Should I start to evacuate the island?");
~chatnpc("<p,neutral>Yes, that may be a good idea. Many people could die! If only there was a way to defeat her!");
@multi2("Mosol Rei said something about a legend?", trufitus_legend, "Will you pack your things now?", trufitus_pack);
[label,trufitus_pack]
~chatplayer("<p,neutral>Will you pack your things now?");
~chatnpc("<p,neutral>I will wait and see what will happen. Maybe Rashiliyia does not have the power to strike too far from her resting place? But there are many things that I need to do now.");
@multi2("Is her resting place important?", trufitus_restingplace, "Oh, ok!", trufitus_ohok);
[label,trufitus_restingplace]
~chatplayer("<p,neutral>Is her resting place important?");
~chatnpc("<p,neutral>I believe it is! It might be that her physical remains are the focal point of her supernatural powers. It is said that many years ago, a group of adventurers once infiltrated her tomb to try to rid the world of Rashiliyia.");
~chatnpc("<p,neutral>These adventurers reported seeing a wraith- like creature.");
~chatnpc("<p,neutral>Although the adventurers disturbed Rashiliyia's bones, they were not able to properly sanctify them. And this is the most likely reason why she still plagues us today.");
~chatnpc("<p,neutral>Of course, she only has to order one of her minions to move her bones and she can quite quickly and easily set up a new headquarters anywhere and continue to launch her plague of undead.");
@multi3("What are minions?", trufitus_minions, "What are onions?", trufitus_onions, "Does she have any weaknesses?", trufitus_weakness);
[label,trufitus_minions]
~chatplayer("<p,neutral>What are minions?");
~chatnpc("<p,neutral>Minions are the fiendish undead creatures that she controls. She has very few living worshippers, but they need to be dealt with at some point.");
~chatnpc("<p,neutral>Usually a strong creature of some sort will be guarding her remains. And of course, she is a very powerful spell caster herself. Not to be tackled lightly.");
@multi2("Thanks for the information!", trufitus_info, "Does she have any weaknesses?", trufitus_weakness);
[label,trufitus_info]
~chatplayer("<p,neutral>Thanks for the information!");
~chatnpc("<p,neutral>What information?");
~chatplayer("<p,neutral>About Ah Za Rhoon and where it is.");
~mesbox("Trufitus looks at you blankly...");
~chatnpc("<p,neutral>Hmmm, well, you are welcome bwana.");
[label,trufitus_weakness]
~chatplayer("<p,neutral>Does she have any weaknesses?");
~chatnpc("<p,neutral>I am not sure, but the legend about her certainly is long. It's a pity that the temple of Ah Za Rhoon has crumbled as there may be some clues that could help us to defeat her.");
~chatnpc("<p,neutral>I think the largest problem will be in locating her resting place.");
@multi2("Why was it called Ah Za Rhoon?", trufitus_why_ah_za_rhoon, "Is her resting place important?", trufitus_restingplace);
[label,trufitus_why_ah_za_rhoon]
~chatplayer("<p,neutarl>Why was it called Ah Za Rhoon?");
~chatnpc("<p,neutral>It is from an ancient language. The direct translation is... 'Magnificence floating on water'. But my research makes me believe that the temple was built on land.");
~chatnpc("<p,neutral>And most likely between large bodies of water, for example large lakes. However, many people have searched for the temple, and have failed. I would hate to see you waste your time on a pointless search like that.");
@multi4("Thanks for the information!", trufitus_info, "Do you know anything more about the temple?", trufitus_temple, "I am going to search for Ah Za Rhoon!", trufitus_searchfor, "It's a pity that I can't search for Ah Za Rhoon now.", trufitus_pity);
[label,trufitus_pity]
~chatplayer("<p,neutral>It's a pity that I can't search for Ah Za Rhoon now.");
~chatnpc("<p,neutral>Well, I understand. Perhaps you can search for it another time? Come back when you think you're ready. Excuse me now won't you while I return to my studies.");
mes("Trufitus goes back to his studies."); // this is the only dialogue mentioning his studies that will send this mes
[label,trufitus_temple]
~chatplayer("<p,neutral>Do you know anything more about the temple?");
~chatnpc("<p,neutral>Not much... I would say that is about it...");
~chatnpc("<p,neutral>Even the great priest Zadimus who built the temple did not survive. Some say that Rashiliyia caused the temple to collapse.");
~chatnpc("<p,neutral>She was angry at Zadimus for not returning her affections. She was a great sorceress even before they met.");
@multi3("Tell me more.", trufitus_tellmemore, "Are there any traps there?", trufitus_traps, "Thanks for the information!", trufitus_info);
[label,trufitus_tellmemore]
~chatplayer("<p,neutral>Tell me more.");
~chatnpc("<p,neutral>I don't know anymore. You're very demanding aren't you!");
@multi4("Thanks for the information!", trufitus_info, "Do you know anything more about the temple?", trufitus_temple, "I am going to search for Ah Za Rhoon!", trufitus_searchfor, "It's a pity that I can't search for Ah Za Rhoon now.", trufitus_pity);
[label,trufitus_traps]
~chatplayer("<p,neutral>Are there any traps there?");
~chatnpc("<p,neutral>How am I supposed to know? A lot of what I know is most probably wrong but some of it seems right to me. Excuse me but I must get back to my studies.");
[label,trufitus_searchfor]
~chatplayer("<p,neutral>I am going to search for Ah Za Rhoon!");
~chatnpc("<p,quiz>What?! You must be crazy! That place has passed into myth and legend, it has been buried under rubble for years. It's most likely buried 20 men deep, and that's if you can actually find it.");
~chatnpc("<p,neutral>Are you sure you're going to go and look for it? I may be able to do some research into this if you agree. Only I don't want to waste my time if you're not serious about this!");
// https://youtu.be/WyLiVLF4VnA?si=tIKWSVB4AqwRbI5L&t=217, i'm pretty sure the period is just cut off here
switch_int(~p_choice2("Yes, I will seriously look for Ah Za Rhoon and I'd appreciate your help.", 1, "Actually, now it comes to it, I'm having second thoughts.", 2)) {
case 1 :
~chatplayer("<p,neutral>Yes, I will seriously look for Ah Za Rhoon and I'd appreciate your help.");
~chatnpc("<p,neutral>Ok then Bwana, good luck with your quest, and remember to stock up well with adventuring supplies before setting off. You never know how useful some fairly ordinary things might be when you're adventuring.");
%zombiequeen_progress = ^zombiequeen_started;
~send_quest_progress(questlist:zombiequeen, %zombiequeen_progress, ^zombiequeen_complete);
inv_del(inv, mosol_wampum_belt, 1);
~chatnpc("<p,neutral>I'll hold on to this Wampum belt for you for the time being. I'll give it back to you when we have completed this quest.");
case 2 :
~chatplayer("<p,neutral>Actually, now it comes to it, I'm having second thoughts.");
~chatnpc("<p,neutral>Well, I understand. Perhaps you can search for it another time? Come back when you think you're ready. Excuse me now won't you while I return to my studies.");
}
[label,trufitus_legend]
~chatplayer("<p,neutral>Mosol Rei said something about a legend?");
~chatnpc("<p,neutral>Ah, yes, there is a legend, but it is lost in the midst of antiquity...");
~chatnpc("<p,neutral>The last place to hold any details regarding this mystery was in the temple of Ah Za Rhoon....and that has long since vanished... it crumbled into dust...");
@multi2("Why was it called Ah Za Rhoon?", trufitus_why_ah_za_rhoon, "Do you know anything more about the temple?", trufitus_temple);
[label,trufitus_mosolrei]
~chatplayer("<p,neutral>What do you know about Mosol Rei?");
~chatnpc("<p,neutral>I know he is a brave warrior, he lives in a village south of here. Your journeys have taken you far!");
@multi2("What do you know about Rashiliyia?", trufitus_rashiliyia, "Do you trust him?", trufitus_trust);
[label,trufitus_trust]
~chatplayer("<p,neutral>Do you trust him?");
~chatnpc("<p,neutral>He is a little headstrong, but for the right reasons. I think he is generally to be trusted.");
@multi2("What do you know about Rashiliyia?", trufitus_rashiliyia, "Mosol Rei said something about a legend?", trufitus_legend);
[label,trufitus_mosolgave]
~chatplayer("<p,neutral>Mosol gave me something to show you.");
~chatnpc("<p,neutral>Oh yes, let me see it then.");
~objbox(mosol_wampum_belt, "You show Trufitus the Wampum belt, he studies it for a long time.", 250, 0, divide(^objbox_height, 2));
~chatnpc("<p,neutral>Yes, things do look very bad indeed.");
@multi2("What do you know about Rashiliyia?", trufitus_rashiliyia, "Mosol Rei said something about a legend?", trufitus_legend);
[label,trufitus_onions]
~chatplayer("<p,neutral>What are onions?");
~mesbox("Trufitus looks at you blankly"); // no period
~chatnpc("<p,neutral>Surely you mean Minions?");
~chatplayer("<p,neutral>Yes of course, I mean Minions, what made you think I said Onions?");
~mesbox("Trufitus frowns at you but continues about...minions...");
~chatnpc("<p,neutral>Minions are the fiendish undead creatures that Rashiliyia controls. She has very few living worshippers, but they need to be dealt with at some point.");
~chatnpc("<p,neutral>Usually a strong creature of some sort will be guarding the bones and it is not to be tackled lightly.");
[label,trufitus_floating]
~chatplayer("<p,neutral>Do you think it was floating on water?");
~chatnpc("<p,neutral>It's very doubtful. I suspect it was built to 'appear' as if it was floating on water. Perhaps on an island or between large bodies of water.");
~chatnpc("<p,neutral>If you search for somewhere like this, you may find something worth investigating.");
[label,trufitus_okthanks]
~chatplayer("<p,neutral>Ok thanks for your help.");
~chatnpc("<p,neutral>You're welcome Bwana, I only hope it helped.");
[label,trufitus_started_zombiequeen]
~chatnpc("<p,neutral>Hello Bwana, how goes your quest to find Ah Za Rhoon?");
switch_int(~p_choice2("Well thanks...", 1, "Erm, I don't know where to look?", 2)) {
case 1 :
~chatplayer("<p,neutral>Well thanks...");
~chatnpc("<p,neutral>Well that's very good news. Let me know if you find anything useful, I may be able to help out.");
case 2 :
~chatplayer("<p,neutral>Erm, I don't know where to look?");
~chatnpc("<p,neutral>Hmm, that doesn't surprise me. The only information I have refers to its name. Ah Za Rhoon, its name means 'Magnificence Floating on Water'.");
%zombiequeen_progress = ^zombiequeen_found_mound; // for whatever reason it sets progress up here lol
@multi2("Do you think it was floating on water?", trufitus_floating, "Ok thanks for your help.", trufitus_okthanks);
}
[label,trufitus_fissure]
~chatplayer("<p,neutral>What's a fissure?");
~chatnpc("<p,neutral>A fissure is a long, narrow crack, usually in rock. Just the kind of thing that adventurers love to find and explore.");
@multi2("Are fissures dangerous?", trufitus_fissuredanger, "Ok, thanks!", trufitus_okthanks2);
[label,trufitus_fissuredanger]
~chatplayer("<p,neutral>");
~chatnpc("<p,neutral>It most likely is, but that isn't normally a barrier to most adventurers! And it may very well lead to something very interesting.");
@multi2("What's a fissure?", trufitus_fissure, "Ok, thanks!", trufitus_okthanks2);
[label,trufitus_okthanks2]
~chatplayer("<p,neutral>Ok, thanks!");
~chatnpc("<p,neutral>You're quite welcome Bwana.");
[label,trufitus_items]
~chatplayer("<p,neutral>I have some items that I need help with.");
~chatnpc("<p,neutral>Well, just let me see the item and I'll help as much as I can.");
if(~obj_gettotal(zqplaque) > 0) {
~chatnpc("<p,neutral>We need to identify that the place you have found is indeed Ah Za Rhoon.");
} else {
~chatnpc("<p,neutral>Look for something that can identify the place. Leave no stone unturned.");
}
if(%zombiequeen_progress >= ^zombiequeen_entered_tomb_bervirius | ~obj_gettotal(zqberviriusscroll) > 0) {
~chatnpc("<p,neutral>Any scrolls or information about Rashiliyia's kin would be helpful.");
} else {
~chatnpc("<p,neutral>Look for details of Rashiliyia's kin, these may be well hidden.");
}
if(~obj_gettotal(zqrashiliyiascroll) > 0) {
~chatnpc("<p,neutral>Have you got any items concerning Rashiliyia? If so, please show me them.");
} else {
~chatnpc("<p,neutral>There is a legend about Rashiliyia, look for it in the temple.");
}
if(~obj_gettotal(zqzadimusbones) > 0) {
~chatnpc("<p,neutral>There must be something relating to Zadimus at the temple. Did you find anything? If so, let me see it.");
} else {
~chatnpc("<p,neutral>Look for something relating to Zadimus at the temple. He was the Priest who built the temple.");
}
~chatnpc("<p,neutral>And best of luck!");
@trufitus_tombops;
[label,trufitus_zadimus]
~chatplayer("<p,neutral>I need help with Zadimus.");
if(~obj_gettotal(zqzadimusbones) > 0) {
~chatnpc("<p,neutral>Zadimus is a spirit yearning for freedom. Bury him in a sacred place to release his spirit.");
@multi5("Is there any sacred ground around here?", trufitus_sacredground, "I need help with Bervirius.", trufitus_bervirius, "I need help with Rashiliyia.", trufitus_helprash, "I need some help with the Temple of Ah Za Rhoon.", trufitus_helptemple, "Ok, thanks!", trufitus_okthanks2);
}
~chatnpc("<p,neutral>All I know is that Zadimus was a high priest of Zamorak. Rashiliyia loved him, but he did not return her affections.");
~chatnpc("<p,neutral>When she became a more powerful sorceress she attacked Ah Za Rhoon, reducing it to rubble. What Zadimus' fate was, I do not know.");
~chatnpc("<p,neutral>If you find anything relating to him at the temple of Ah Za Rhoon, please let me see it.");
@trufitus_tombops2;
[label,trufitus_helprash]
~chatplayer("<p,neutral>I need help with Rashiliyia.");
~chatnpc("<p,neutral>We need to find Rashiliyia's resting place and learn how to put her spirit to rest. You may find some clues to her resting place in Ah Za Rhoon or Bervirius' Tomb.");
@trufitus_tombops;
[label,trufitus_helptemple]
~chatplayer("<p,neutral>I need some help with the Temple of Ah Za Rhoon.");
~chatnpc("<p,neutral>If you have found the temple, you should search it thoroughly and see if there are any clues about Rashiliyia.");
if(~obj_gettotal(zqplaque) > 0) {
~chatnpc("<p,neutral>We need to identify that the place you have found is indeed Ah Za Rhoon.");
} else {
~chatnpc("<p,neutral>Look for something that can identify the place. Leave no stone unturned.");
}
if(%zombiequeen_progress >= ^zombiequeen_entered_tomb_bervirius | ~obj_gettotal(zqberviriusscroll) > 0) {
~chatnpc("<p,neutral>Any scrolls or information about Rashiliyia's kin would be helpful.");
} else {
~chatnpc("<p,neutral>Look for details of Rashiliyia's kin, these may be well hidden.");
}
if(~obj_gettotal(zqrashiliyiascroll) > 0) {
~chatnpc("<p,neutral>Have you got any items concerning Rashiliyia? If so, please show me them.");
} else {
~chatnpc("<p,neutral>There is a legend about Rashiliyia, look for it in the temple.");
}
if(~obj_gettotal(zqzadimusbones) > 0) {
~chatnpc("<p,neutral>There must be something relating to Zadimus at the temple. Did you find anything? If so, let me see it.");
} else {
~chatnpc("<p,neutral>Look for something relating to Zadimus at the temple. He was the Priest who built the temple.");
}
~chatnpc("<p,happy>And best of luck!");
@trufitus_tombops;
[label,trufitus_bervtomb]
~chatplayer("<p,neutral>I think I found Bervirius' Tomb.");
~chatnpc("<p,neutral>Congratulations Bwana. Show me any items you have found though. I may be able to help.");
@multi2("I actually need help with something else.", trufitus_somethingelse, "I didn't find anything in the tomb.", trufitus_didnttomb);
[label,trufitus_somethingelse]
~chatplayer("<p,neutral>I actually need help with something else.");
~chatnpc("<p,neutral>What could I possibly help you with Bwana?");
@multi5("I need help with Rashiliyia.", trufitus_helprash, "I need help with Zadimus.", trufitus_zadimus, "I have some items that I need help with.", trufitus_items, "I need help with Bervirius.", trufitus_bervirius, "Ok, thanks!", trufitus_okthanks2);
[label,trufitus_didntfind]
~chatplayer("<p,neutral>No, I didn't find a thing.");
~chatnpc("<p,neutral>That is a shame Bwana. We really do need to act against Rashiliyia soon if we are ever to stand a chance of defeating her.");
@multi3("Actually I did find the tomb, I was just joking.", trufitus_joking, "I actually need help with something else.", trufitus_somethingelse, "I didn't find anything in the tomb.", trufitus_didnttomb);
[label,trufitus_joking]
~chatplayer("<p,neutral>Actually I did find the tomb, I was just joking.");
~chatnpc("<p,angry>Well, Bwana, this is no laughing matter. We need to take this very seriously and act now! If you have found any items at the tomb that you need help with please let me see them and I will help as much as I can.");
@multi2("I didn't find anything in the tomb.", trufitus_didnttomb, "I actually need help with something else.", trufitus_somethingelse);
[label,trufitus_didnttomb]
~chatplayer("<p,neutral>I didn't find anything in the tomb.");
~chatnpc("<p,neutral>Maybe you need to look around a little more. There must be some small detail at least that can help us.");
switch_int(~p_choice2("I have some items that I need some help with.", 1, "I actually need help with something else.", 2)) {
case 1 :
~chatplayer("<p,neutral>I have some items that I need some help with.");
~chatnpc("<p,neutral>Well, just show me the items and I'll help as much as I can.");
@multi2("I actually need help with something else.", trufitus_somethingelse, "Thanks!", trufitus_thanks);
case 2 : @trufitus_somethingelse;
}
[label,trufitus_thanks]
~chatplayer("<p,neutral>Thanks!");
~chatnpc("<p,neutral>You're more than welcome Bwana! Good luck for the rest of your quest.");
[label,trufitus_bronzeneck]
~chatplayer("<p,neutral>How do I make a bronze necklace?");
~chatnpc("<p,neutral>Well, Bwana, I would guess that you would need to get some bronze metal and work it into something that could be turned into a necklace?");
@multi2("What should I put on the necklace?", trufitus_putneck, "Thanks!", trufitus_thanks);
[label,trufitus_putneck]
~chatplayer("<p,neutral>What should I put on the necklace?");
~chatnpc("<p,neutral>Perhaps Zadimus' clue has the answer? Now, what was it that he said again? Something about kin and keys? That sword pommel belonged to Bervirius didn't it?");
@multi2("How do I make a bronze necklace?", trufitus_bronzeneck, "Thanks!", trufitus_thanks);
[label,trufitus_anything]
~chatplayer("<p,neutral>Anything that can help?");
~chatnpc("<p,neutral>Hmmm, well just that part about the wards...");
~mesbox("Trufitus seems to drift off in thought.");
~chatnpc("<p,neutral>It may be possible to make a ward like that... But what is the best thing to make it from? Perhaps something close to Bervirius, an item of some significance to him.");
[label,trufitus_bervirius]
~chatplayer("<p,neutral>I need help with Bervirius.");
~chatnpc("<p,neutral>Bervirius is the son of Rashiliyia. His tomb may hold some clues as to how Rashiliyia may be defeated.");
@trufitus_tombops;
[label,trufitus_zadimuscorp]
~chatplayer("<p,neutral>It appeared when I buried Zadimus' corpse.");
~chatnpc("<p,neutral>Ah, interesting, so you think that Zadimus gave you the bone? What makes you say that?");
@multi2("He said something after he gave it to me.", trufitus_said, "I'm not sure.", trufitus_notsure);
[label,trufitus_said]
~chatplayer("<p,neutral>He said something after he gave it to me.");
~chatnpc("<p,neutral>What did he say?");
@trufitus_spiritops;
[label,trufitus_spiritops]
switch_int(~p_choice2("The spirit said something about keys and kin?", 1, "The spirit rambled on about some nonsense.", 2)) {
case 1 :
~chatplayer("<p,neutral>The spirit said something about keys and kin?");
~chatnpc("<p,neutral>Hmmm, maybe it's a clue of some kind?");
~chatnpc("<p,neutral>Rashiliyia's only kin was a son, 'Bervirius'. His remains were entombed on a small island which lies to the South West. I will do some research into this to see if I can find any other details.");
if(~zqhaspommel = false) {
~chatnpc("<p,neutral>But I think we must take Zadimus' clue literally and get some item that belonged to Bervirius as it may be the only way to approach Rashiliyia. Perhaps something like this exists in his tomb?");
} else {
~chatnpc("<p,neutral>I still think we need to take this clue quite literally. Perhaps you found something at Bervirius' Tomb that could help to protect you from Rashiliyia's attacks?");
}
case 2 :
~chatplayer("<p,neutral>The spirit rambled on about some nonsense.");
~chatnpc("<p,neutral>Oh, so it most likely was not very important then.");
}
[label,trufitus_noreason]
~chatplayer("<p,neutral>No reason really.");
~chatnpc("<p,neutral>Well why are you showing it to me then?");
@multi2("It appeared when I buried Zadimus' corpse.", trufitus_zadimuscorp, "I'm not sure.", trufitus_notsure);
[label,trufitus_notsure]
~chatplayer("<p,neutral>I'm not sure.");
~chatnpc("<p,neutral>Oh, right. Come back and talk with me if you get an idea.");
[label,trufitus_sacredground]
~chatplayer("<p,neutral>Is there any sacred ground around here?");
~chatnpc("<p,neutral>The ground in the centre of the village is very sacred to us. Maybe you could try there?");
[label,trufitus_opens]
~chatplayer("<p,neutral>Do you know what it opens?");
~chatnpc("<p,neutral>You must already know what it opens to have carved it so pefectly. Perhaps in your travels you have come across some unique doors with a unique lock? I hope this helps with your quest.");
[label,trufitus_bonezadimus]
~chatplayer("<p,neutral>I made it from the bone shard that Zadimus gave me.");
~chatnpc("<p,neutral>How very inventive Bwana. You must have seen the lock to have crafted it so well. Does the key work?");
@multi2("Yes and I explored inside some sort of cavern.", trufitus_cavern, "I don't know, I haven't tried it yet.", trufitus_tried);
[label,trufitus_tried]
~chatplayer("<p,neutral>I don't know, I haven't tried it yet.");
~chatnpc("<p,neutral>It may be an idea to try it and then scout out the area. If it relates to Rashiliyia, it might help us to defeat her.");
[label,trufitus_cavern]
~chatplayer("<p,neutral>Yes and I explored inside some sort of cavern.");
~chatnpc("<p,neutral>How interesting Bwana, did you find anything?");
switch_int(~p_choice2("Not really.", 1, "Yes, I found lots of things.", 2)) {
case 1 :
~chatplayer("<p,neutral>Not really.");
~chatnpc("<p,neutral>Maybe you should go back and try to find some more things.");
~chatnpc("<p,neutral>Maybe there are more items to be found at Ah Za Rhoon?");
case 2 :
~chatplayer("<p,neutral>Yes, I found lots of things.");
~chatnpc("<p,neutral>If you let me see them Bwana, perhaps I can offer you some extra information.");
}
[label,trufitus_buried]
~chatplayer("<p,neutral>I have just buried Zadimus' corpse.");
~chatnpc("<p,neutral>Something seems different about you. You look like you have seen a ghost?");
~chatplayer("<p,neutral>It just so happens that I have!");
~chatnpc("<p,neutral>Oh! So you managed to bury Zadimus's corpse?");
~chatplayer("<p,neutral>Yes, it was pretty grisly!");
@trufitus_spiritops;
[label,trufitus_takethem]
~chatplayer("<p,neutral>Can you take them off my hands?");
~chatnpc("<p,neutral>I dare not take them, I may be taken over by the evil spirit of Rashiliyia!");
@multi2("What should I do with them?", trufitus_whatcorpse, "Thanks!", trufitus_thanks);
[label,trufitus_whatcorpse]
~chatplayer("<p,neutral>What should I do with them?");
~chatnpc("<p,neutral>Hmm, I'm not exactly sure... Perhaps there is a clue in one of the artefacts you have found?");
@multi2("Can you take them off my hands?", trufitus_takethem, "Thanks!", trufitus_thanks);
[label,trufitus_postquest_item]
~chatplayer("<p,neutral>Have a look at this.");
~chatnpc("<p,neutral>Hmmm, I'm not sure you will get much use out of this. Why not see if you can sell it in Shilo Village.");
[label,trufitus_tombops]
if(%zombiequeen_progress >= ^zombiequeen_entered_tomb_bervirius & ~obj_gettotal(zqboneshard) > 0) @multi5("I have just buried Zadimus' corpse.", trufitus_buried, "I need help with Bervirius.", trufitus_bervirius, "I have some items that I need help with.", trufitus_items, "I need some help with the Temple of Ah Za Rhoon.", trufitus_helptemple, "I need help with Zadimus.", trufitus_zadimus);
else if(%zombiequeen_progress >= ^zombiequeen_entered_tomb_bervirius) @multi5("I need help with Bervirius.", trufitus_bervirius, "I have some items that I need help with.", trufitus_items, "I need help with Zadimus.", trufitus_zadimus, "I need help with Rashiliyia.", trufitus_helprash, "I need some help with the Temple of Ah Za Rhoon.", trufitus_helptemple);
else if(~obj_gettotal(zqboneshard) > 0) @multi5("I have just buried Zadimus' corpse.", trufitus_buried, "I have some items that I need help with.", trufitus_items, "I need some help with the Temple of Ah Za Rhoon.", trufitus_helptemple, "I need help with Zadimus.", trufitus_zadimus, "I need help with Rashiliyia.", trufitus_helprash);
else @multi4("I have some items that I need help with.", trufitus_items, "I need help with Zadimus.", trufitus_zadimus, "I need help with Rashiliyia.", trufitus_helprash, "I need some help with the Temple of Ah Za Rhoon.", trufitus_helptemple);
[label,trufitus_tombops2]
if(%zombiequeen_progress >= ^zombiequeen_entered_tomb_bervirius & ~obj_gettotal(zqboneshard) > 0) @multi5("I have just buried Zadimus' corpse.", trufitus_buried, "I need help with Bervirius.", trufitus_bervirius, "I have some items that I need help with.", trufitus_items, "I need some help with the Temple of Ah Za Rhoon.", trufitus_helptemple, "I need help with Rashiliyia.", trufitus_helprash);
else if(%zombiequeen_progress >= ^zombiequeen_entered_tomb_bervirius) @multi5("I need help with Bervirius.", trufitus_bervirius, "I have some items that I need help with.", trufitus_items, "I need help with Zadimus.", trufitus_zadimus, "I need help with Rashiliyia.", trufitus_helprash, "I need some help with the Temple of Ah Za Rhoon.", trufitus_helptemple);
else if(~obj_gettotal(zqboneshard) > 0) @multi5("I have just buried Zadimus' corpse.", trufitus_buried, "I have some items that I need help with.", trufitus_items, "I need some help with the Temple of Ah Za Rhoon.", trufitus_helptemple, "I need help with Zadimus.", trufitus_zadimus, "I need help with Rashiliyia.", trufitus_helprash);
else @multi4("I have some items that I need help with.", trufitus_items, "I need help with Zadimus.", trufitus_zadimus, "I need help with Rashiliyia.", trufitus_helprash, "I need some help with the Temple of Ah Za Rhoon.", trufitus_helptemple); | 0 | 0.694153 | 1 | 0.694153 | game-dev | MEDIA | 0.732832 | game-dev | 0.608015 | 1 | 0.608015 |
boy0001/FastAsyncWorldedit | 1,911 | core/src/main/java/com/boydti/fawe/object/mask/PlaneMask.java | package com.boydti.fawe.object.mask;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.function.mask.AbstractMask;
import com.sk89q.worldedit.function.mask.Mask2D;
import javax.annotation.Nullable;
/**
* Restricts the
*/
public class PlaneMask extends AbstractMask implements ResettableMask {
private transient int mode = -1;
private transient int originX = Integer.MAX_VALUE, originY = Integer.MAX_VALUE, originZ = Integer.MAX_VALUE;
@Override
public boolean test(Vector vector) {
switch (mode) {
case -1:
originX = vector.getBlockX();
originY = vector.getBlockY();
originZ = vector.getBlockZ();
mode = 0;
return true;
case 0:
case 1:
case 2:
case 4:
int original = mode;
if (originX != vector.getBlockX()) {
mode &= 1;
}
if (originY != vector.getBlockY()) {
mode &= 2;
}
if (originZ != vector.getBlockZ()) {
mode &= 4;
}
if (Integer.bitCount(mode) >= 3) {
mode = original;
return false;
}
default:
if (originX != vector.getBlockX() && (mode & 1) == 0) {
return false;
}
if (originZ != vector.getBlockZ() && (mode & 4) == 0) {
return false;
}
if (originY != vector.getBlockY() && (mode & 2) == 0) {
return false;
}
return true;
}
}
@Override
public void reset() {
mode = -1;
}
@Nullable
@Override
public Mask2D toMask2D() {
return null;
}
}
| 0 | 0.657927 | 1 | 0.657927 | game-dev | MEDIA | 0.584995 | game-dev,graphics-rendering | 0.910791 | 1 | 0.910791 |
HIllya51/LunaTranslator | 1,199 | src/cpp/LunaHook/LunaHook/engine32/GameMaker.cpp | #include "GameMaker.h"
bool InsertGameMakerHook()
{
/*
* Sample games:
* VA-11 Hall A
*/
const BYTE bytes[] = {
0x85, 0xF6, // test esi,esi
0x74, XX, // je "VA-11 Hall A.exe"+D5014
0x85, 0xC0, // test eax,eax
0x74, XX, // je "VA-11 Hall A.exe"+D5014
0x50, // push eax
0x56 // push esi << hook here
};
enum
{
addr_offset = sizeof(bytes) - 1
};
ULONG range = min(processStopAddress - processStartAddress, MAX_REL_ADDR);
ULONG addr = MemDbg::findBytes(bytes, sizeof(bytes), processStartAddress, processStartAddress + range);
if (!addr)
{
ConsoleOutput("GameMaker: pattern not found");
return false;
}
HookParam hp;
hp.address = addr + addr_offset;
hp.offset = regoffset(eax);
hp.type = USING_STRING | NO_CONTEXT;
hp.filter_fun = [](TextBuffer *buffer, HookParam *)
{
CharFilter(buffer, '#');
};
ConsoleOutput(" INSERT GameMaker");
ConsoleOutput("GameMaker: use regex filter .+\\]");
return NewHook(hp, "GameMaker");
}
bool GameMaker::attach_function()
{
return InsertGameMakerHook();
} | 0 | 0.621204 | 1 | 0.621204 | game-dev | MEDIA | 0.619645 | game-dev | 0.678596 | 1 | 0.678596 |
Armourers-Workshop/Armourers-Workshop | 3,026 | common/src/main/java/moe/plushie/armourers_workshop/core/crafting/recipe/SkinningRecipe.java | package moe.plushie.armourers_workshop.core.crafting.recipe;
import moe.plushie.armourers_workshop.core.skin.SkinDescriptor;
import moe.plushie.armourers_workshop.core.skin.SkinType;
import moe.plushie.armourers_workshop.init.ModDataComponents;
import moe.plushie.armourers_workshop.init.ModItems;
import net.minecraft.world.Container;
import net.minecraft.world.item.ItemStack;
public abstract class SkinningRecipe {
protected SkinType skinType;
public SkinningRecipe(SkinType skinType) {
this.skinType = skinType;
}
public void apply(Container inventory) {
var skinStack = ItemStack.EMPTY;
var targetStack = ItemStack.EMPTY;
int size = inventory.getContainerSize();
for (int i = 1; i < size; ++i) { // 0 is output
var itemStack = inventory.getItem(i);
if (itemStack.isEmpty()) {
continue;
}
if (isValidSkin(itemStack)) {
skinStack = itemStack;
continue;
}
if (isValidTarget(itemStack)) {
targetStack = itemStack;
continue;
}
return;
}
if (targetStack.isEmpty() || skinStack.isEmpty()) {
return;
}
shrink(targetStack, skinStack);
}
public ItemStack test(Container inventory, SkinDescriptor.Options options) {
var skinStack = ItemStack.EMPTY;
var targetStack = ItemStack.EMPTY;
int size = inventory.getContainerSize();
for (int i = 1; i < size; ++i) { // 0 is output
var itemStack = inventory.getItem(i);
if (itemStack.isEmpty()) {
continue;
}
if (isValidSkin(itemStack)) {
skinStack = itemStack;
continue;
}
if (isValidTarget(itemStack)) {
targetStack = itemStack;
continue;
}
return ItemStack.EMPTY;
}
if (targetStack.isEmpty() || skinStack.isEmpty()) {
return ItemStack.EMPTY;
}
return build(targetStack, skinStack, options);
}
protected void shrink(ItemStack targetStack, ItemStack skinStack) {
targetStack.shrink(1);
skinStack.shrink(1);
}
protected ItemStack build(ItemStack targetStack, ItemStack skinStack, SkinDescriptor.Options options) {
var skin = skinStack.getOrDefault(ModDataComponents.SKIN.get(), SkinDescriptor.EMPTY);
var newItemStack = targetStack.copy();
newItemStack.setCount(1);
newItemStack.set(ModDataComponents.SKIN.get(), skin.withOptions(options));
return newItemStack;
}
protected boolean isValidSkin(ItemStack itemStack) {
return ModItems.SKIN.get() == itemStack.getItem() && SkinDescriptor.of(itemStack).type() == skinType;
}
protected boolean isValidTarget(ItemStack itemStack) {
return ModItems.SKIN.get() != itemStack.getItem();
}
}
| 0 | 0.68502 | 1 | 0.68502 | game-dev | MEDIA | 0.986288 | game-dev | 0.502128 | 1 | 0.502128 |
goatcorp/Dalamud | 35,792 | Dalamud/Interface/ManagedFontAtlas/Internals/GamePrebakedFontHandle.cs | using System.Buffers;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reactive.Disposables;
using Dalamud.Bindings.ImGui;
using Dalamud.Game.Text;
using Dalamud.Interface.GameFonts;
using Dalamud.Interface.Internal;
using Dalamud.Interface.Textures.TextureWraps;
using Dalamud.Interface.Utility;
using Dalamud.Utility;
using Lumina.Data.Files;
using Vector4 = System.Numerics.Vector4;
namespace Dalamud.Interface.ManagedFontAtlas.Internals;
/// <summary>
/// A font handle that uses the game's built-in fonts, optionally with some styling.
/// </summary>
internal class GamePrebakedFontHandle : FontHandle
{
/// <summary>
/// The smallest value of <see cref="SeIconChar"/>.
/// </summary>
public static readonly char SeIconCharMin = (char)Enum.GetValues<SeIconChar>().Min();
/// <summary>
/// The largest value of <see cref="SeIconChar"/>.
/// </summary>
public static readonly char SeIconCharMax = (char)Enum.GetValues<SeIconChar>().Max();
/// <summary>
/// Initializes a new instance of the <see cref="GamePrebakedFontHandle"/> class.
/// </summary>
/// <param name="manager">An instance of <see cref="IFontHandleManager"/>.</param>
/// <param name="style">Font to use.</param>
public GamePrebakedFontHandle(IFontHandleManager manager, GameFontStyle style)
: base(manager)
{
if (!Enum.IsDefined(style.FamilyAndSize) || style.FamilyAndSize == GameFontFamilyAndSize.Undefined)
throw new ArgumentOutOfRangeException(nameof(style), style, null);
if (style.SizePt <= 0)
throw new ArgumentException($"{nameof(style.SizePt)} must be a positive number.", nameof(style));
this.FontStyle = style;
}
/// <summary>
/// Provider for <see cref="IDalamudTextureWrap"/> for `common/font/fontNN.tex`.
/// </summary>
public interface IGameFontTextureProvider
{
/// <summary>
/// Creates the <see cref="FdtFileView"/> for the <see cref="GameFontFamilyAndSize"/>.<br />
/// <strong>Dispose after use.</strong>
/// </summary>
/// <param name="gffas">The font family and size.</param>
/// <param name="fdtFileView">The view.</param>
/// <returns>Dispose this after use..</returns>
public MemoryHandle CreateFdtFileView(GameFontFamilyAndSize gffas, out FdtFileView fdtFileView);
/// <summary>
/// Gets the number of font textures.
/// </summary>
/// <param name="texPathFormat">Format of .tex path.</param>
/// <returns>The number of textures.</returns>
public int GetFontTextureCount(string texPathFormat);
/// <summary>
/// Gets the <see cref="TexFile"/> for the given index of a font.
/// </summary>
/// <param name="texPathFormat">Format of .tex path.</param>
/// <param name="index">The index of .tex file.</param>
/// <returns>The <see cref="TexFile"/>.</returns>
public TexFile GetTexFile(string texPathFormat, int index);
/// <summary>
/// Gets a new reference of the font texture.
/// </summary>
/// <param name="texPathFormat">Format of .tex path.</param>
/// <param name="textureIndex">Texture index.</param>
/// <returns>The texture.</returns>
public IDalamudTextureWrap NewFontTextureRef(string texPathFormat, int textureIndex);
}
/// <summary>
/// Gets the font style.
/// </summary>
public GameFontStyle FontStyle { get; }
/// <inheritdoc/>
public override string ToString() => $"{nameof(GamePrebakedFontHandle)}({this.FontStyle})";
/// <summary>
/// Manager for <see cref="GamePrebakedFontHandle"/>s.
/// </summary>
internal sealed class HandleManager : IFontHandleManager
{
private readonly Dictionary<GameFontStyle, int> gameFontsRc = new();
private readonly HashSet<GamePrebakedFontHandle> handles = new();
private readonly object syncRoot = new();
/// <summary>
/// Initializes a new instance of the <see cref="HandleManager"/> class.
/// </summary>
/// <param name="atlasName">The name of the owner atlas.</param>
/// <param name="gameFontTextureProvider">An instance of <see cref="IGameFontTextureProvider"/>.</param>
public HandleManager(string atlasName, IGameFontTextureProvider gameFontTextureProvider)
{
this.GameFontTextureProvider = gameFontTextureProvider;
this.Name = $"{atlasName}:{nameof(GamePrebakedFontHandle)}:Manager";
}
/// <inheritdoc/>
public event Action? RebuildRecommend;
/// <inheritdoc/>
public string Name { get; }
/// <inheritdoc/>
public IFontHandleSubstance? Substance { get; set; }
/// <summary>
/// Gets an instance of <see cref="IGameFontTextureProvider"/>.
/// </summary>
public IGameFontTextureProvider GameFontTextureProvider { get; }
/// <inheritdoc/>
public void Dispose()
{
// empty
}
/// <inheritdoc cref="IFontAtlas.NewGameFontHandle"/>
public IFontHandle NewFontHandle(GameFontStyle style)
{
var handle = new GamePrebakedFontHandle(this, style);
bool suggestRebuild;
lock (this.syncRoot)
{
this.handles.Add(handle);
this.gameFontsRc[style] = this.gameFontsRc.GetValueOrDefault(style, 0) + 1;
suggestRebuild = this.Substance?.GetFontPtr(handle).IsNotNullAndLoaded() is not true;
}
if (suggestRebuild)
this.RebuildRecommend.InvokeSafely();
return handle;
}
/// <inheritdoc/>
public void FreeFontHandle(IFontHandle handle)
{
if (handle is not GamePrebakedFontHandle ggfh)
return;
lock (this.syncRoot)
{
this.handles.Remove(ggfh);
if (!this.gameFontsRc.ContainsKey(ggfh.FontStyle))
return;
if ((this.gameFontsRc[ggfh.FontStyle] -= 1) == 0)
this.gameFontsRc.Remove(ggfh.FontStyle);
}
}
/// <inheritdoc/>
public IFontHandleSubstance NewSubstance(IRefCountable dataRoot)
{
lock (this.syncRoot)
return new HandleSubstance(this, dataRoot, this.handles.ToArray(), this.gameFontsRc.Keys);
}
}
/// <summary>
/// Substance from <see cref="HandleManager"/>.
/// </summary>
internal sealed class HandleSubstance : IFontHandleSubstance
{
private readonly HandleManager handleManager;
private readonly HashSet<GameFontStyle> gameFontStyles;
// Owned by this class, but ImFontPtr values still do not belong to this.
private readonly Dictionary<GameFontStyle, FontDrawPlan> fonts = new();
private readonly Dictionary<GameFontStyle, Exception?> buildExceptions = new();
private readonly List<(ImFontPtr Font, GameFontStyle Style, ushort[]? Ranges)> attachments = new();
private readonly HashSet<ImFontPtr> templatedFonts = new();
/// <summary>
/// Initializes a new instance of the <see cref="HandleSubstance"/> class.
/// </summary>
/// <param name="manager">The manager.</param>
/// <param name="dataRoot">The data root.</param>
/// <param name="relevantHandles">The relevant handles.</param>
/// <param name="gameFontStyles">The game font styles.</param>
public HandleSubstance(
HandleManager manager,
IRefCountable dataRoot,
GamePrebakedFontHandle[] relevantHandles,
IEnumerable<GameFontStyle> gameFontStyles)
{
// We do not call dataRoot.AddRef; this object is dependant on lifetime of dataRoot.
this.handleManager = manager;
this.DataRoot = dataRoot;
this.RelevantHandles = relevantHandles;
this.gameFontStyles = new(gameFontStyles);
}
/// <summary>
/// Gets the relevant handles.
/// </summary>
// Not owned by this class. Do not dispose.
public GamePrebakedFontHandle[] RelevantHandles { get; }
/// <inheritdoc/>
ICollection<FontHandle> IFontHandleSubstance.RelevantHandles => this.RelevantHandles;
/// <inheritdoc/>
public IRefCountable DataRoot { get; }
/// <inheritdoc/>
public IFontHandleManager Manager => this.handleManager;
/// <inheritdoc/>
public void Dispose()
{
// empty
}
/// <summary>
/// Attaches game symbols to the given font. If font is null, it will be created.
/// </summary>
/// <param name="toolkitPreBuild">The toolkitPostBuild.</param>
/// <param name="font">The font to attach to.</param>
/// <param name="style">The game font style.</param>
/// <param name="glyphRanges">The intended glyph ranges.</param>
/// <returns><paramref name="font"/> if it is not empty; otherwise a new font.</returns>
public ImFontPtr AttachGameGlyphs(
IFontAtlasBuildToolkitPreBuild toolkitPreBuild,
ImFontPtr font,
GameFontStyle style,
ushort[]? glyphRanges = null)
{
if (font.IsNull)
font = this.CreateTemplateFont(toolkitPreBuild, style.SizePx);
this.attachments.Add((font, style, glyphRanges));
return font;
}
/// <summary>
/// Creates or gets a relevant <see cref="ImFontPtr"/> for the given <see cref="GameFontStyle"/>.
/// </summary>
/// <param name="style">The game font style.</param>
/// <param name="toolkitPreBuild">The toolkitPostBuild.</param>
/// <returns>The font.</returns>
public ImFontPtr GetOrCreateFont(GameFontStyle style, IFontAtlasBuildToolkitPreBuild toolkitPreBuild)
{
try
{
if (!this.fonts.TryGetValue(style, out var plan))
{
plan = new(
style,
toolkitPreBuild.Scale,
this.handleManager.GameFontTextureProvider,
this.CreateTemplateFont(toolkitPreBuild, style.SizePx));
this.fonts[style] = plan;
}
plan.AttachFont(plan.FullRangeFont);
return plan.FullRangeFont;
}
catch (Exception e)
{
this.buildExceptions[style] = e;
throw;
}
}
/// <inheritdoc/>
public ImFontPtr GetFontPtr(IFontHandle handle) =>
handle is GamePrebakedFontHandle ggfh
? this.fonts.GetValueOrDefault(ggfh.FontStyle)?.FullRangeFont ?? default
: default;
/// <inheritdoc/>
public Exception? GetBuildException(IFontHandle handle) =>
handle is GamePrebakedFontHandle ggfh ? this.buildExceptions.GetValueOrDefault(ggfh.FontStyle) : default;
/// <inheritdoc/>
public void OnPreBuild(IFontAtlasBuildToolkitPreBuild toolkitPreBuild)
{
foreach (var style in this.gameFontStyles)
{
if (this.fonts.ContainsKey(style))
continue;
try
{
_ = this.GetOrCreateFont(style, toolkitPreBuild);
}
catch
{
// ignore; it should have been recorded from the call
}
}
}
/// <inheritdoc/>
public void OnPreBuildCleanup(IFontAtlasBuildToolkitPreBuild toolkitPreBuild)
{
foreach (var (font, style, ranges) in this.attachments)
{
if (!this.fonts.TryGetValue(style, out var plan))
{
switch (toolkitPreBuild.GetFontScaleMode(font))
{
case FontScaleMode.Default:
default:
plan = new(
style,
toolkitPreBuild.Scale,
this.handleManager.GameFontTextureProvider,
this.CreateTemplateFont(toolkitPreBuild, style.SizePx));
break;
case FontScaleMode.SkipHandling:
plan = new(
style,
1f,
this.handleManager.GameFontTextureProvider,
this.CreateTemplateFont(toolkitPreBuild, style.SizePx));
break;
case FontScaleMode.UndoGlobalScale:
plan = new(
style.Scale(1 / toolkitPreBuild.Scale),
toolkitPreBuild.Scale,
this.handleManager.GameFontTextureProvider,
this.CreateTemplateFont(toolkitPreBuild, style.SizePx));
break;
}
this.fonts[style] = plan;
}
plan.AttachFont(font, ranges);
}
foreach (var plan in this.fonts.Values)
{
plan.EnsureGlyphs(toolkitPreBuild.NewImAtlas);
}
}
/// <inheritdoc/>
public unsafe void OnPostBuild(IFontAtlasBuildToolkitPostBuild toolkitPostBuild)
{
var allTextureIndices = new Dictionary<string, int[]>();
var allTexFiles = new Dictionary<string, TexFile[]>();
using var rentReturn = Disposable.Create(
() =>
{
foreach (var x in allTextureIndices.Values)
ArrayPool<int>.Shared.Return(x);
foreach (var x in allTexFiles.Values)
ArrayPool<TexFile>.Shared.Return(x);
});
var pixels8Array = new byte*[toolkitPostBuild.NewImAtlas.Textures.Size];
var widths = new int[toolkitPostBuild.NewImAtlas.Textures.Size];
for (var i = 0; i < pixels8Array.Length; i++)
{
var width = 0;
toolkitPostBuild.NewImAtlas.GetTexDataAsAlpha8(i, ref pixels8Array[i], ref widths[i], ref width);
}
foreach (var (style, plan) in this.fonts)
{
try
{
foreach (var font in plan.Ranges.Keys)
this.PatchFontMetricsIfNecessary(style, font, toolkitPostBuild.Scale);
plan.SetFullRangeFontGlyphs(toolkitPostBuild, allTexFiles, allTextureIndices, pixels8Array, widths);
plan.CopyGlyphsToRanges(toolkitPostBuild);
plan.PostProcessFullRangeFont(toolkitPostBuild.Scale);
}
catch (Exception e)
{
this.buildExceptions[style] = e;
this.fonts[style] = default;
}
}
}
/// <summary>
/// Creates a new template font.
/// </summary>
/// <param name="toolkitPreBuild">The toolkitPostBuild.</param>
/// <param name="sizePx">The size of the font.</param>
/// <returns>The font.</returns>
private ImFontPtr CreateTemplateFont(IFontAtlasBuildToolkitPreBuild toolkitPreBuild, float sizePx)
{
var font = toolkitPreBuild.AddDalamudAssetFont(
DalamudAsset.NotoSansJpMedium,
new()
{
GlyphRanges = new ushort[] { ' ', ' ', '\0' },
SizePx = sizePx,
});
this.templatedFonts.Add(font);
return font;
}
private unsafe void PatchFontMetricsIfNecessary(GameFontStyle style, ImFontPtr font, float atlasScale)
{
if (!this.templatedFonts.Contains(font))
return;
var fas = style.Scale(atlasScale).FamilyAndSize;
using var handle = this.handleManager.GameFontTextureProvider.CreateFdtFileView(fas, out var fdt);
ref var fdtFontHeader = ref fdt.FontHeader;
var fontPtr = font.Handle;
var scale = style.SizePt / fdtFontHeader.Size;
fontPtr->Ascent = fdtFontHeader.Ascent * scale;
fontPtr->Descent = fdtFontHeader.Descent * scale;
fontPtr->EllipsisChar = '…';
}
}
[SuppressMessage(
"StyleCop.CSharp.MaintainabilityRules",
"SA1401:Fields should be private",
Justification = "Internal")]
private sealed class FontDrawPlan : IDisposable
{
public readonly GameFontStyle Style;
public readonly GameFontStyle BaseStyle;
public readonly GameFontFamilyAndSizeAttribute BaseAttr;
public readonly int TexCount;
public readonly Dictionary<ImFontPtr, BitArray> Ranges = new();
public readonly List<(int RectId, int FdtGlyphIndex)> Rects = new();
public readonly ushort[] RectLookup = new ushort[0x10000];
public readonly FdtFileView Fdt;
public readonly ImFontPtr FullRangeFont;
private readonly IDisposable fdtHandle;
private readonly IGameFontTextureProvider gftp;
public FontDrawPlan(
GameFontStyle style,
float scale,
IGameFontTextureProvider gameFontTextureProvider,
ImFontPtr fullRangeFont)
{
this.Style = style;
this.BaseStyle = style.Scale(scale);
this.BaseAttr = this.BaseStyle.FamilyAndSize.GetAttribute<GameFontFamilyAndSizeAttribute>()!;
this.gftp = gameFontTextureProvider;
this.TexCount = this.gftp.GetFontTextureCount(this.BaseAttr.TexPathFormat);
this.fdtHandle = this.gftp.CreateFdtFileView(this.BaseStyle.FamilyAndSize, out this.Fdt);
this.RectLookup.AsSpan().Fill(ushort.MaxValue);
this.FullRangeFont = fullRangeFont;
this.Ranges[fullRangeFont] = new(0x10000);
}
public void Dispose()
{
this.fdtHandle.Dispose();
}
public void AttachFont(ImFontPtr font, ushort[]? glyphRanges = null)
{
if (!this.Ranges.TryGetValue(font, out var rangeBitArray))
rangeBitArray = this.Ranges[font] = new(0x10000);
if (glyphRanges is null)
{
foreach (ref var g in this.Fdt.Glyphs)
{
var c = g.CharInt;
if (c is >= 0x20 and <= 0xFFFE)
rangeBitArray[c] = true;
}
return;
}
for (var i = 0; i < glyphRanges.Length - 1; i += 2)
{
if (glyphRanges[i] == 0)
break;
var from = (int)glyphRanges[i];
var to = (int)glyphRanges[i + 1];
for (var j = from; j <= to; j++)
rangeBitArray[j] = true;
}
}
public unsafe void EnsureGlyphs(ImFontAtlasPtr atlas)
{
var glyphs = this.Fdt.Glyphs;
var ranges = this.Ranges[this.FullRangeFont];
foreach (var (font, extraRange) in this.Ranges)
{
if (font.Handle != this.FullRangeFont.Handle)
ranges.Or(extraRange);
}
if (this.Style is not { Weight: 0, SkewStrength: 0 })
{
for (var fdtGlyphIndex = 0; fdtGlyphIndex < glyphs.Length; fdtGlyphIndex++)
{
ref var glyph = ref glyphs[fdtGlyphIndex];
var cint = glyph.CharInt;
if (cint > char.MaxValue)
continue;
if (!ranges[cint] || this.RectLookup[cint] != ushort.MaxValue)
continue;
var widthAdjustment = this.BaseStyle.CalculateBaseWidthAdjustment(this.Fdt.FontHeader, glyph);
this.RectLookup[cint] = (ushort)this.Rects.Count;
this.Rects.Add(
(
atlas.AddCustomRectFontGlyph(
this.FullRangeFont,
(char)cint,
glyph.BoundingWidth + widthAdjustment,
glyph.BoundingHeight,
glyph.AdvanceWidth,
new(this.BaseAttr.HorizontalOffset, glyph.CurrentOffsetY)),
fdtGlyphIndex));
}
}
else
{
for (var fdtGlyphIndex = 0; fdtGlyphIndex < glyphs.Length; fdtGlyphIndex++)
{
ref var glyph = ref glyphs[fdtGlyphIndex];
var cint = glyph.CharInt;
if (cint > char.MaxValue)
continue;
if (!ranges[cint] || this.RectLookup[cint] != ushort.MaxValue)
continue;
this.RectLookup[cint] = (ushort)this.Rects.Count;
this.Rects.Add((-1, fdtGlyphIndex));
}
}
}
public unsafe void PostProcessFullRangeFont(float atlasScale)
{
var round = 1 / atlasScale;
var pfrf = this.FullRangeFont.Handle;
ref var frf = ref *pfrf;
frf.FontSize = MathF.Round(frf.FontSize / round) * round;
frf.Ascent = MathF.Round(frf.Ascent / round) * round;
frf.Descent = MathF.Round(frf.Descent / round) * round;
var scale = this.Style.SizePt / this.Fdt.FontHeader.Size;
foreach (ref var g in this.FullRangeFont.GlyphsWrapped().DataSpan)
{
var w = (g.X1 - g.X0) * scale;
var h = (g.Y1 - g.Y0) * scale;
g.X0 = MathF.Round((g.X0 * scale) / round) * round;
g.Y0 = MathF.Round((g.Y0 * scale) / round) * round;
g.X1 = g.X0 + w;
g.Y1 = g.Y0 + h;
g.AdvanceX = MathF.Round((g.AdvanceX * scale) / round) * round;
}
var fullRange = this.Ranges[this.FullRangeFont];
foreach (ref var k in this.Fdt.PairAdjustments)
{
var (leftInt, rightInt) = (k.LeftInt, k.RightInt);
if (leftInt > char.MaxValue || rightInt > char.MaxValue)
continue;
if (!fullRange[leftInt] || !fullRange[rightInt])
continue;
pfrf->AddKerningPair(
(ushort)leftInt,
(ushort)rightInt,
MathF.Round((k.RightOffset * scale) / round) * round);
}
pfrf->FallbackGlyph = null;
pfrf->BuildLookupTable();
foreach (var fallbackCharCandidate in FontAtlasFactory.FallbackCodepoints)
{
var glyph = pfrf->FindGlyphNoFallback(fallbackCharCandidate);
if ((nint)glyph == IntPtr.Zero)
continue;
frf.FallbackChar = fallbackCharCandidate;
frf.FallbackGlyph = glyph;
frf.FallbackHotData =
(ImFontGlyphHotData*)frf.IndexedHotData.Address<ImGuiHelpers.ImFontGlyphHotDataReal>(
fallbackCharCandidate);
break;
}
}
public unsafe void CopyGlyphsToRanges(IFontAtlasBuildToolkitPostBuild toolkitPostBuild)
{
var scale = this.Style.SizePt / this.Fdt.FontHeader.Size;
foreach (var (font, rangeBits) in this.Ranges)
{
if (font.Handle == this.FullRangeFont.Handle)
continue;
var fontScaleMode = toolkitPostBuild.GetFontScaleMode(font);
var round = fontScaleMode == FontScaleMode.SkipHandling ? 1 : 1 / toolkitPostBuild.Scale;
var lookup = font.IndexLookupWrapped();
var glyphs = font.GlyphsWrapped();
foreach (ref var sourceGlyph in this.FullRangeFont.GlyphsWrapped().DataSpan)
{
if (!rangeBits[sourceGlyph.Codepoint])
continue;
var glyphIndex = ushort.MaxValue;
if (sourceGlyph.Codepoint < lookup.Length)
glyphIndex = lookup[sourceGlyph.Codepoint];
if (glyphIndex == ushort.MaxValue)
{
glyphIndex = (ushort)glyphs.Length;
glyphs.Add(default);
}
ref var g = ref glyphs[glyphIndex];
g = sourceGlyph;
if (fontScaleMode == FontScaleMode.SkipHandling)
{
g.XY *= scale;
g.AdvanceX *= scale;
}
else
{
var w = (g.X1 - g.X0) * scale;
var h = (g.Y1 - g.Y0) * scale;
g.X0 = MathF.Round((g.X0 * scale) / round) * round;
g.Y0 = MathF.Round((g.Y0 * scale) / round) * round;
g.X1 = g.X0 + w;
g.Y1 = g.Y0 + h;
g.AdvanceX = MathF.Round((g.AdvanceX * scale) / round) * round;
}
}
foreach (ref var k in this.Fdt.PairAdjustments)
{
var (leftInt, rightInt) = (k.LeftInt, k.RightInt);
if (leftInt > char.MaxValue || rightInt > char.MaxValue)
continue;
if (!rangeBits[leftInt] || !rangeBits[rightInt])
continue;
if (fontScaleMode == FontScaleMode.SkipHandling)
{
font.AddKerningPair((ushort)leftInt, (ushort)rightInt, k.RightOffset * scale);
}
else
{
font.AddKerningPair(
(ushort)leftInt,
(ushort)rightInt,
MathF.Round((k.RightOffset * scale) / round) * round);
}
}
font.Handle->FallbackGlyph = null;
font.BuildLookupTable();
foreach (var fallbackCharCandidate in FontAtlasFactory.FallbackCodepoints)
{
var glyph = font.FindGlyphNoFallback(fallbackCharCandidate);
if (glyph == null)
continue;
ref var frf = ref *font.Handle;
frf.FallbackChar = fallbackCharCandidate;
frf.FallbackGlyph = glyph;
frf.FallbackHotData =
(ImFontGlyphHotData*)frf.IndexedHotData.Address<ImGuiHelpers.ImFontGlyphHotDataReal>(
fallbackCharCandidate);
break;
}
}
}
public unsafe void SetFullRangeFontGlyphs(
IFontAtlasBuildToolkitPostBuild toolkitPostBuild,
Dictionary<string, TexFile[]> allTexFiles,
Dictionary<string, int[]> allTextureIndices,
byte*[] pixels8Array,
int[] widths)
{
var glyphs = this.FullRangeFont.GlyphsWrapped();
var lookups = this.FullRangeFont.IndexLookupWrapped();
ref var fdtFontHeader = ref this.Fdt.FontHeader;
var fdtGlyphs = this.Fdt.Glyphs;
var fdtTexSize = new Vector4(
this.Fdt.FontHeader.TextureWidth,
this.Fdt.FontHeader.TextureHeight,
this.Fdt.FontHeader.TextureWidth,
this.Fdt.FontHeader.TextureHeight);
if (!allTexFiles.TryGetValue(this.BaseAttr.TexPathFormat, out var texFiles))
{
allTexFiles.Add(
this.BaseAttr.TexPathFormat,
texFiles = ArrayPool<TexFile>.Shared.Rent(this.TexCount));
}
if (!allTextureIndices.TryGetValue(this.BaseAttr.TexPathFormat, out var textureIndices))
{
allTextureIndices.Add(
this.BaseAttr.TexPathFormat,
textureIndices = ArrayPool<int>.Shared.Rent(this.TexCount));
textureIndices.AsSpan(0, this.TexCount).Fill(-1);
}
var pixelWidth = Math.Max(1, (int)MathF.Ceiling(this.BaseStyle.Weight + 1));
var pixelStrength = stackalloc byte[pixelWidth];
for (var i = 0; i < pixelWidth; i++)
pixelStrength[i] = (byte)(255 * Math.Min(1f, (this.BaseStyle.Weight + 1) - i));
var minGlyphY = 0;
var maxGlyphY = 0;
foreach (ref var g in fdtGlyphs)
{
minGlyphY = Math.Min(g.CurrentOffsetY, minGlyphY);
maxGlyphY = Math.Max(g.BoundingHeight + g.CurrentOffsetY, maxGlyphY);
}
var horzShift = stackalloc int[maxGlyphY - minGlyphY];
var horzBlend = stackalloc byte[maxGlyphY - minGlyphY];
horzShift -= minGlyphY;
horzBlend -= minGlyphY;
if (this.BaseStyle.BaseSkewStrength != 0)
{
for (var i = minGlyphY; i < maxGlyphY; i++)
{
float blend = this.BaseStyle.BaseSkewStrength switch
{
> 0 => fdtFontHeader.LineHeight - i,
< 0 => -i,
_ => throw new InvalidOperationException(),
};
blend *= this.BaseStyle.BaseSkewStrength / fdtFontHeader.LineHeight;
horzShift[i] = (int)MathF.Floor(blend);
horzBlend[i] = (byte)(255 * (blend - horzShift[i]));
}
}
foreach (var (rectId, fdtGlyphIndex) in this.Rects)
{
ref var fdtGlyph = ref fdtGlyphs[fdtGlyphIndex];
if (rectId == -1)
{
ref var textureIndex = ref textureIndices[fdtGlyph.TextureIndex];
if (textureIndex == -1)
{
textureIndex = toolkitPostBuild.StoreTexture(
this.gftp.NewFontTextureRef(this.BaseAttr.TexPathFormat, fdtGlyph.TextureIndex),
true);
}
var glyph = new ImGuiHelpers.ImFontGlyphReal
{
AdvanceX = fdtGlyph.AdvanceWidth,
Codepoint = fdtGlyph.Char,
Colored = false,
TextureIndex = textureIndex,
Visible = true,
X0 = this.BaseAttr.HorizontalOffset,
Y0 = fdtGlyph.CurrentOffsetY,
U0 = fdtGlyph.TextureOffsetX,
V0 = fdtGlyph.TextureOffsetY,
U1 = fdtGlyph.BoundingWidth,
V1 = fdtGlyph.BoundingHeight,
};
glyph.XY1 = glyph.XY0 + glyph.UV1;
glyph.UV1 += glyph.UV0;
glyph.UV /= fdtTexSize;
glyphs.Add(glyph);
}
else
{
ref var rc = ref *(ImGuiHelpers.ImFontAtlasCustomRectReal*)toolkitPostBuild.NewImAtlas
.GetCustomRectByIndex(rectId);
var widthAdjustment = this.BaseStyle.CalculateBaseWidthAdjustment(fdtFontHeader, fdtGlyph);
// Glyph is scaled at this point; undo that.
ref var glyph = ref glyphs[lookups[rc.GlyphId]];
glyph.X0 = this.BaseAttr.HorizontalOffset;
glyph.Y0 = fdtGlyph.CurrentOffsetY;
glyph.X1 = glyph.X0 + fdtGlyph.BoundingWidth + widthAdjustment;
glyph.Y1 = glyph.Y0 + fdtGlyph.BoundingHeight;
glyph.AdvanceX = fdtGlyph.AdvanceWidth;
var pixels8 = pixels8Array[rc.TextureIndex];
var width = widths[rc.TextureIndex];
texFiles[fdtGlyph.TextureFileIndex] ??=
this.gftp.GetTexFile(this.BaseAttr.TexPathFormat, fdtGlyph.TextureFileIndex);
var sourceBuffer = texFiles[fdtGlyph.TextureFileIndex].ImageData;
var sourceBufferDelta = fdtGlyph.TextureChannelByteIndex;
for (var y = 0; y < fdtGlyph.BoundingHeight; y++)
{
var sourcePixelIndex =
((fdtGlyph.TextureOffsetY + y) * fdtFontHeader.TextureWidth) + fdtGlyph.TextureOffsetX;
sourcePixelIndex *= 4;
sourcePixelIndex += sourceBufferDelta;
var blend1 = horzBlend[fdtGlyph.CurrentOffsetY + y];
var targetOffset = ((rc.Y + y) * width) + rc.X;
for (var x = 0; x < rc.Width; x++)
pixels8[targetOffset + x] = 0;
targetOffset += horzShift[fdtGlyph.CurrentOffsetY + y];
if (blend1 == 0)
{
for (var x = 0; x < fdtGlyph.BoundingWidth; x++, sourcePixelIndex += 4, targetOffset++)
{
var n = sourceBuffer[sourcePixelIndex + 4];
for (var boldOffset = 0; boldOffset < pixelWidth; boldOffset++)
{
ref var p = ref pixels8[targetOffset + boldOffset];
p = Math.Max(p, (byte)((pixelStrength[boldOffset] * n) / 255));
}
}
}
else
{
var blend2 = 255 - blend1;
for (var x = 0; x < fdtGlyph.BoundingWidth; x++, sourcePixelIndex += 4, targetOffset++)
{
var a1 = sourceBuffer[sourcePixelIndex];
var a2 = x == fdtGlyph.BoundingWidth - 1 ? 0 : sourceBuffer[sourcePixelIndex + 4];
var n = (a1 * blend1) + (a2 * blend2);
for (var boldOffset = 0; boldOffset < pixelWidth; boldOffset++)
{
ref var p = ref pixels8[targetOffset + boldOffset];
p = Math.Max(p, (byte)((pixelStrength[boldOffset] * n) / 255 / 255));
}
}
}
}
}
}
}
}
}
| 0 | 0.895528 | 1 | 0.895528 | game-dev | MEDIA | 0.954585 | game-dev | 0.990265 | 1 | 0.990265 |
berezaa/minershaven | 1,178 | src/Workspace/Innovator/Innovator.server.lua |
game.ReplicatedStorage.RequestQuest.OnServerEvent:connect(function(Player)
if not Player.InnoResearchClaimed.Value then
Player.InnoResearchClaimed.Value = true
game.ServerStorage.AwardItem:Invoke(Player, 503)
end
end)
game.ServerStorage.PlayerDataLoaded.Event:connect(function(Player)
wait(3)
game.ReplicatedStorage.Splash:FireClient(Player,"InnoStart")
end)
function game.ReplicatedStorage.ClaimEvent.OnServerInvoke(Player, event)
if event == 1 then
if Player.InnoEventProgress.Value >= 1000 and not Player.InnoRocketComplete.Value then
Player.InnoRocketComplete.Value = true
game.ReplicatedStorage.Splash:FireClient(Player,"InnoEnd")
game.ServerStorage.AwardBadge:Invoke(Player, 1334714065)
return true
end
elseif event == 2 then
if Player.InnoElementPending.Value and not Player.InnoElementComplete.Value then
Player.InnoElementPending.Value = false
Player.InnoElementComplete.Value = true
game.ReplicatedStorage.Splash:FireClient(Player,"InnoEnd")
game.ServerStorage.AwardBadge:Invoke(Player, 1334713630)
game.ServerStorage.InnovationRobotDog:Clone().Parent = Player.Backpack
return true
end
end
return false
end | 0 | 0.852152 | 1 | 0.852152 | game-dev | MEDIA | 0.512494 | game-dev | 0.684135 | 1 | 0.684135 |
ValkyrienSkies/Valkyrien-Skies | 5,298 | src/main/java/org/valkyrienskies/mod/common/ships/physics_data/BasicCenterOfMassProvider.java | package org.valkyrienskies.mod.common.ships.physics_data;
import net.minecraft.block.state.IBlockState;
import net.minecraft.util.math.BlockPos;
import org.joml.Matrix3d;
import org.joml.Vector3d;
import org.valkyrienskies.mod.common.physics.BlockPhysicsDetails;
import org.valkyrienskies.mod.common.ships.physics_data.IPhysicsObjectCenterOfMassProvider;
import org.valkyrienskies.mod.common.ships.physics_data.ShipInertiaData;
public class BasicCenterOfMassProvider implements IPhysicsObjectCenterOfMassProvider {
private static final double INERTIA_OFFSET = .4D;
@Override
public void onSetBlockState(ShipInertiaData inertiaData, BlockPos pos, IBlockState oldState, IBlockState newState) {
if (!newState.equals(oldState)) {
double oldMass = BlockPhysicsDetails.getMassFromState(oldState);
double newMass = BlockPhysicsDetails.getMassFromState(newState);
double deltaMass = newMass - oldMass;
// Don't change anything if the mass is the same
if (Math.abs(deltaMass) > .00001) {
double x = pos.getX() + .5;
double y = pos.getY() + .5;
double z = pos.getZ() + .5;
deltaMass /= 9;
addMassAt(inertiaData, x, y, z, deltaMass);
addMassAt(inertiaData, x + INERTIA_OFFSET, y + INERTIA_OFFSET, z + INERTIA_OFFSET, deltaMass);
addMassAt(inertiaData, x + INERTIA_OFFSET, y + INERTIA_OFFSET, z - INERTIA_OFFSET, deltaMass);
addMassAt(inertiaData, x + INERTIA_OFFSET, y - INERTIA_OFFSET, z + INERTIA_OFFSET, deltaMass);
addMassAt(inertiaData, x + INERTIA_OFFSET, y - INERTIA_OFFSET, z - INERTIA_OFFSET, deltaMass);
addMassAt(inertiaData, x - INERTIA_OFFSET, y + INERTIA_OFFSET, z + INERTIA_OFFSET, deltaMass);
addMassAt(inertiaData, x - INERTIA_OFFSET, y + INERTIA_OFFSET, z - INERTIA_OFFSET, deltaMass);
addMassAt(inertiaData, x - INERTIA_OFFSET, y - INERTIA_OFFSET, z + INERTIA_OFFSET, deltaMass);
addMassAt(inertiaData, x - INERTIA_OFFSET, y - INERTIA_OFFSET, z - INERTIA_OFFSET, deltaMass);
}
}
}
/**
* Updates the center of mass and rotation inertia tensor matrix of the ShipInertiaData, using the rigid body
* inertia tensor equations. Reference http://www.kwon3d.com/theory/moi/triten.html eqs. 13 & 14.
*/
private void addMassAt(ShipInertiaData inertiaData, double x, double y, double z, double addedMass) {
double[] gameMoITensor = new double[9];
Matrix3d transposed = inertiaData.getGameMoITensor().transpose(new Matrix3d());
transposed.get(gameMoITensor);
double gameTickMass = inertiaData.getGameTickMass();
Vector3d prevCenterOfMass = new Vector3d(inertiaData.getGameTickCenterOfMass());
if (gameTickMass > .0001D) {
Vector3d newCenterOfMass = inertiaData.getGameTickCenterOfMass().mul(gameTickMass, new Vector3d());
newCenterOfMass.add(x * addedMass, y * addedMass, z * addedMass);
newCenterOfMass.mul(1.0 / (gameTickMass + addedMass));
inertiaData.setGameTickCenterOfMass(newCenterOfMass);
} else {
inertiaData.setGameTickCenterOfMass(new Vector3d(x, y, z));
inertiaData.setGameMoITensor(new Matrix3d().zero());
}
// This code is pretty awful in hindsight, but it gets the job done.
double cmShiftX = prevCenterOfMass.x - inertiaData.getGameTickCenterOfMass().x();
double cmShiftY = prevCenterOfMass.y - inertiaData.getGameTickCenterOfMass().y();
double cmShiftZ = prevCenterOfMass.z - inertiaData.getGameTickCenterOfMass().z();
double rx = x - inertiaData.getGameTickCenterOfMass().x();
double ry = y - inertiaData.getGameTickCenterOfMass().y();
double rz = z - inertiaData.getGameTickCenterOfMass().z();
gameMoITensor[0] = gameMoITensor[0] + (cmShiftY * cmShiftY + cmShiftZ * cmShiftZ) * gameTickMass
+ (ry * ry + rz * rz) * addedMass;
gameMoITensor[1] = gameMoITensor[1] - cmShiftX * cmShiftY * gameTickMass - rx * ry * addedMass;
gameMoITensor[2] = gameMoITensor[2] - cmShiftX * cmShiftZ * gameTickMass - rx * rz * addedMass;
gameMoITensor[3] = gameMoITensor[1];
gameMoITensor[4] = gameMoITensor[4] + (cmShiftX * cmShiftX + cmShiftZ * cmShiftZ) * gameTickMass
+ (rx * rx + rz * rz) * addedMass;
gameMoITensor[5] = gameMoITensor[5] - cmShiftY * cmShiftZ * gameTickMass - ry * rz * addedMass;
gameMoITensor[6] = gameMoITensor[2];
gameMoITensor[7] = gameMoITensor[5];
gameMoITensor[8] = gameMoITensor[8] + (cmShiftX * cmShiftX + cmShiftY * cmShiftY) * gameTickMass
+ (rx * rx + ry * ry) * addedMass;
inertiaData.setGameMoITensor(new Matrix3d().set(gameMoITensor).transpose());
// Do this to avoid a mass of zero, which runs the risk of dividing by zero and
// crashing the program.
if (inertiaData.getGameTickMass() + addedMass < .0001) {
inertiaData.setGameTickMass(0);
} else {
inertiaData.setGameTickMass(inertiaData.getGameTickMass() + addedMass);
}
}
}
| 0 | 0.717986 | 1 | 0.717986 | game-dev | MEDIA | 0.911902 | game-dev | 0.935105 | 1 | 0.935105 |
565564274/WechatBot | 5,039 | Bot/plugins/caige.py | import time
import threading
import requests
from wcferry import WxMsg
from utils.log import logger_manager
logger = logger_manager.logger
class Caige:
def __init__(self, Robot):
self.robot = Robot
self.thread_status = {}
self.thread_stop = False
self.explain = ""
def start(self, msg: WxMsg, is_continue=False):
if is_continue:
if not self._stop_thread():
self.robot.when_game_init(msg.roomid)
logger.info(f"thread_status:{self.thread_status}\nthread_stop:{self.thread_stop}")
return self.robot.sendTextMsg("继续开始游戏失败,请重新开始。", msg.roomid)
status, data = self.get_music()
if status:
self.robot.sendTextMsg("【猜歌】已开始,请直接输入歌名作答,60s后自动结束!", msg.roomid)
self.robot.chatroom_game[msg.roomid]["game_name"] = "caige"
self.robot.chatroom_game[msg.roomid]["status"] = True
self.robot.chatroom_game[msg.roomid]["data"] = {"answer": data["name"]}
self.robot.chatroom_game[msg.roomid].update({"start_time": int(time.time())})
self.robot.wcf.send_rich_text(
name="",
account="",
title="🎶🎶请听歌曲,并作答🎶🎶",
digest=f"",
url=data["url"],
thumburl=data["picurl"],
receiver=msg.roomid
)
t = threading.Thread(target=self._count_down, args=(msg,))
t.start()
else:
return self.robot.sendTextMsg(data, msg.roomid)
def _count_down(self, msg: WxMsg):
self.thread_status["_count_down"] = True
promt = True
while not self.thread_stop:
if not self.robot.chatroom_game[msg.roomid]["status"]:
break
if (int(time.time()) - self.robot.chatroom_game[msg.roomid]["start_time"]) >= 30 and promt:
promt = False
answer = self.robot.chatroom_game[msg.roomid]["data"]["answer"]
self.robot.sendTextMsg(f"时间过半,提示信息:{answer[0]}{' __ ' * (len(answer) - 1)}", msg.roomid)
if (int(time.time()) - self.robot.chatroom_game[msg.roomid]["start_time"]) >= 60:
answer = self.robot.chatroom_game[msg.roomid]["data"]["answer"]
self.robot.sendTextMsg(f"60s内无正确答案,自动结束!\n正确答案:{answer}", msg.roomid)
self.robot.when_game_init(msg.roomid)
return
else:
time.sleep(1)
continue
self.thread_status["_count_down"] = False
def _stop_thread(self):
self.thread_stop = True
for _ in range(5):
if self.thread_status["_count_down"]:
time.sleep(0.5)
continue
else:
self.thread_stop = False
return True
return False
def process(self, msg: WxMsg):
if msg.content == self.robot.chatroom_game[msg.roomid]["data"]["answer"]:
name = self.robot.wcf.get_alias_in_chatroom(msg.sender, msg.roomid)
resp = f"🎉🎉恭喜【{name}】答对🎉🎉"
self.robot.sendTextMsg(resp + self.explain, msg.roomid)
game_data = self.robot.bot_data.get_game_caige(roomid=msg.roomid, wxid=msg.sender)
if not game_data:
self.robot.bot_data.add_game_caige(msg.roomid, msg.sender)
else:
self.robot.bot_data.update_game_caige(msg.roomid, msg.sender, score=game_data.score + 1)
all_game_data = self.robot.bot_data.get_game_caige_score(roomid=msg.roomid)
resp = "[排名][得分][昵称]"
for i in range(len(all_game_data)):
if i == 0:
icon = "🥇"
elif i == 1:
icon = "🥈"
elif i == 2:
icon = "🥉"
else:
icon = "💯"
name = self.robot.wcf.get_alias_in_chatroom(all_game_data[i].wxid, all_game_data[i].roomid)
resp += f"\n{i + 1}.{icon}[{all_game_data[i].score}]👉{name}"
self.robot.sendTextMsg(resp, msg.roomid)
self.start(msg, is_continue=True)
return
else:
return
def get_music(self):
url = f"https://free.wqwlkj.cn/wqwlapi/wyy_random.php"
error_msg = "[猜歌]插件出现故障,请联系开发者"
try:
resp = requests.get(url)
logger.info(str(resp.json()))
if resp.status_code != 200:
assert False, "response code is not 200"
if resp.json()["code"] != 1:
assert False, "resp.json()[\"code\"] code is not 200"
data = resp.json()["data"]
self.explain = (f'\n'
f'【歌名】{data["name"]}\n'
f'【演唱】{data["artistsname"]}\n'
f'【专辑】{data["alname"]}\n')
return True, data
except Exception as e:
logger.error(str(e))
return False, error_msg
| 0 | 0.629603 | 1 | 0.629603 | game-dev | MEDIA | 0.484167 | game-dev | 0.813011 | 1 | 0.813011 |
Me-Maped/Gameframework-at-FairyGUI | 1,886 | Client/Assets/UnityGameFramework/Scripts/Runtime/UniTask/Linq/ToArray.cs | using Cysharp.Threading.Tasks.Internal;
using System;
using System.Collections.Generic;
using System.Threading;
namespace Cysharp.Threading.Tasks.Linq
{
public static partial class UniTaskAsyncEnumerable
{
public static UniTask<TSource[]> ToArrayAsync<TSource>(this IUniTaskAsyncEnumerable<TSource> source, CancellationToken cancellationToken = default)
{
Error.ThrowArgumentNullException(source, nameof(source));
return Cysharp.Threading.Tasks.Linq.ToArray.ToArrayAsync(source, cancellationToken);
}
}
internal static class ToArray
{
internal static async UniTask<TSource[]> ToArrayAsync<TSource>(IUniTaskAsyncEnumerable<TSource> source, CancellationToken cancellationToken)
{
var pool = ArrayPool<TSource>.Shared;
var array = pool.Rent(16);
TSource[] result = default;
IUniTaskAsyncEnumerator<TSource> e = default;
try
{
e = source.GetAsyncEnumerator(cancellationToken);
var i = 0;
while (await e.MoveNextAsync())
{
ArrayPoolUtil.EnsureCapacity(ref array, i, pool);
array[i++] = e.Current;
}
if (i == 0)
{
result = Array.Empty<TSource>();
}
else
{
result = new TSource[i];
Array.Copy(array, result, i);
}
}
finally
{
pool.Return(array, clearArray: !RuntimeHelpersAbstraction.IsWellKnownNoReferenceContainsType<TSource>());
if (e != null)
{
await e.DisposeAsync();
}
}
return result;
}
}
} | 0 | 0.649029 | 1 | 0.649029 | game-dev | MEDIA | 0.632815 | game-dev | 0.773509 | 1 | 0.773509 |
vittorioromeo/quakevr | 26,612 | QC_other/QC_hipnotic/PLAYER.QC |
void() bubble_bob;
/*
==============================================================================
PLAYER
==============================================================================
*/
$cd id1/models/player_4
$origin 0 -6 24
$base base
$skin skin
//
// running
//
$frame axrun1 axrun2 axrun3 axrun4 axrun5 axrun6
$frame rockrun1 rockrun2 rockrun3 rockrun4 rockrun5 rockrun6
//
// standing
//
$frame stand1 stand2 stand3 stand4 stand5
$frame axstnd1 axstnd2 axstnd3 axstnd4 axstnd5 axstnd6
$frame axstnd7 axstnd8 axstnd9 axstnd10 axstnd11 axstnd12
//
// pain
//
$frame axpain1 axpain2 axpain3 axpain4 axpain5 axpain6
$frame pain1 pain2 pain3 pain4 pain5 pain6
//
// death
//
$frame axdeth1 axdeth2 axdeth3 axdeth4 axdeth5 axdeth6
$frame axdeth7 axdeth8 axdeth9
$frame deatha1 deatha2 deatha3 deatha4 deatha5 deatha6 deatha7 deatha8
$frame deatha9 deatha10 deatha11
$frame deathb1 deathb2 deathb3 deathb4 deathb5 deathb6 deathb7 deathb8
$frame deathb9
$frame deathc1 deathc2 deathc3 deathc4 deathc5 deathc6 deathc7 deathc8
$frame deathc9 deathc10 deathc11 deathc12 deathc13 deathc14 deathc15
$frame deathd1 deathd2 deathd3 deathd4 deathd5 deathd6 deathd7
$frame deathd8 deathd9
$frame deathe1 deathe2 deathe3 deathe4 deathe5 deathe6 deathe7
$frame deathe8 deathe9
//
// attacks
//
$frame nailatt1 nailatt2
$frame light1 light2
$frame rockatt1 rockatt2 rockatt3 rockatt4 rockatt5 rockatt6
$frame shotatt1 shotatt2 shotatt3 shotatt4 shotatt5 shotatt6
$frame axatt1 axatt2 axatt3 axatt4 axatt5 axatt6
$frame axattb1 axattb2 axattb3 axattb4 axattb5 axattb6
$frame axattc1 axattc2 axattc3 axattc4 axattc5 axattc6
$frame axattd1 axattd2 axattd3 axattd4 axattd5 axattd6
/*
==============================================================================
PLAYER
==============================================================================
*/
void() player_run;
void() player_stand1 =[ $axstnd1, player_stand1 ]
{
self.weaponframe=0;
if (self.velocity_x || self.velocity_y)
{
self.walkframe=0;
player_run();
return;
}
if (self.weapon == IT_AXE)
{
if (self.walkframe >= 12)
self.walkframe = 0;
self.frame = $axstnd1 + self.walkframe;
}
else if (self.weapon == IT_MJOLNIR)
{
if (self.walkframe >= 12)
self.walkframe = 0;
self.frame = 6 + self.walkframe;
}
else
{
if (self.walkframe >= 5)
self.walkframe = 0;
self.frame = $stand1 + self.walkframe;
}
self.walkframe = self.walkframe + 1;
};
void() player_run =[ $rockrun1, player_run ]
{
self.weaponframe=0;
if (!self.velocity_x && !self.velocity_y)
{
self.walkframe=0;
player_stand1();
return;
}
if (self.weapon == IT_AXE)
{
if (self.walkframe == 6)
self.walkframe = 0;
self.frame = $axrun1 + self.walkframe;
}
else if (self.weapon == IT_MJOLNIR)
{
if (self.walkframe == 6)
self.walkframe = 0;
self.frame = self.walkframe;
}
else
{
if (self.walkframe == 6)
self.walkframe = 0;
self.frame = self.frame + self.walkframe;
}
if (footsteps == 1)
{
self.spawnsilent = self.spawnsilent + vlen(self.origin - self.old_velocity);
self.old_velocity = self.origin;
if (self.flags & FL_ONGROUND)
{
if (self.spawnsilent > 95)
{
local float r;
if (self.spawnsilent > 190)
self.spawnsilent = 0;
else
{
self.spawnsilent = 0.5*(self.spawnsilent - 95);
}
r = random();
if (r < 0.14)
sound (self, CHAN_VOICE, "misc/foot1.wav", 0.5, ATTN_NORM);
else if (r < 0.29)
sound (self, CHAN_VOICE, "misc/foot2.wav", 0.5, ATTN_NORM);
else if (r < 0.43)
sound (self, CHAN_VOICE, "misc/foot3.wav", 0.5, ATTN_NORM);
else if (r < 0.58)
sound (self, CHAN_VOICE, "misc/foot4.wav", 0.5, ATTN_NORM);
else if (r < 0.72)
sound (self, CHAN_VOICE, "misc/foot5.wav", 0.5, ATTN_NORM);
else if (r < 0.86)
sound (self, CHAN_VOICE, "misc/foot6.wav", 0.5, ATTN_NORM);
else
sound (self, CHAN_VOICE, "misc/foot7.wav", 0.5, ATTN_NORM);
}
}
}
self.walkframe = self.walkframe + 1;
};
void() player_shot1 = [$shotatt1, player_shot2 ] {self.weaponframe=1;
self.effects = self.effects | EF_MUZZLEFLASH;};
void() player_shot2 = [$shotatt2, player_shot3 ] {self.weaponframe=2;};
void() player_shot3 = [$shotatt3, player_shot4 ] {self.weaponframe=3;};
void() player_shot4 = [$shotatt4, player_shot5 ] {self.weaponframe=4;};
void() player_shot5 = [$shotatt5, player_shot6 ] {self.weaponframe=5;};
void() player_shot6 = [$shotatt6, player_run ] {self.weaponframe=6;};
void() player_axe1 = [$axatt1, player_axe2 ] {self.weaponframe=1;};
void() player_axe2 = [$axatt2, player_axe3 ] {self.weaponframe=2;};
void() player_axe3 = [$axatt3, player_axe4 ] {self.weaponframe=3;W_FireAxe();};
void() player_axe4 = [$axatt4, player_run ] {self.weaponframe=4;};
void() player_axeb1 = [$axattb1, player_axeb2 ] {self.weaponframe=5;};
void() player_axeb2 = [$axattb2, player_axeb3 ] {self.weaponframe=6;};
void() player_axeb3 = [$axattb3, player_axeb4 ] {self.weaponframe=7;W_FireAxe();};
void() player_axeb4 = [$axattb4, player_run ] {self.weaponframe=8;};
void() player_axec1 = [$axattc1, player_axec2 ] {self.weaponframe=1;};
void() player_axec2 = [$axattc2, player_axec3 ] {self.weaponframe=2;};
void() player_axec3 = [$axattc3, player_axec4 ] {self.weaponframe=3;W_FireAxe();};
void() player_axec4 = [$axattc4, player_run ] {self.weaponframe=4;};
void() player_axed1 = [$axattd1, player_axed2 ] {self.weaponframe=5;};
void() player_axed2 = [$axattd2, player_axed3 ] {self.weaponframe=6;};
void() player_axed3 = [$axattd3, player_axed4 ] {self.weaponframe=7;W_FireAxe();};
void() player_axed4 = [$axattd4, player_run ] {self.weaponframe=8;};
//============================================================================
void() player_nail1 =[$nailatt1, player_nail2 ]
{
self.effects = self.effects | EF_MUZZLEFLASH;
if (!self.button0)
{player_run ();return;}
self.weaponframe = self.weaponframe + 1;
if (self.weaponframe == 9)
self.weaponframe = 1;
SuperDamageSound();
W_FireSpikes (4);
self.attack_finished = time + 0.2;
};
void() player_nail2 =[$nailatt2, player_nail1 ]
{
self.effects = self.effects | EF_MUZZLEFLASH;
if (!self.button0)
{player_run ();return;}
self.weaponframe = self.weaponframe + 1;
if (self.weaponframe == 9)
self.weaponframe = 1;
SuperDamageSound();
W_FireSpikes (-4);
self.attack_finished = time + 0.2;
};
//============================================================================
void() player_light1 =[$light1, player_light2 ]
{
self.effects = self.effects | EF_MUZZLEFLASH;
if (!self.button0)
{player_run ();return;}
self.weaponframe = self.weaponframe + 1;
if (self.weaponframe == 5)
self.weaponframe = 1;
SuperDamageSound();
W_FireLightning();
self.attack_finished = time + 0.2;
};
void() player_light2 =[$light2, player_light1 ]
{
self.effects = self.effects | EF_MUZZLEFLASH;
if (!self.button0)
{player_run ();return;}
self.weaponframe = self.weaponframe + 1;
if (self.weaponframe == 5)
self.weaponframe = 1;
SuperDamageSound();
W_FireLightning();
self.attack_finished = time + 0.2;
};
//MED 10/18/96 added HIPWEAPONS
//============================================================================
void() player_hammer1 = [32, player_hammer2 ] {self.weaponframe=1;};
void() player_hammer2 = [33, player_hammer3 ] {self.weaponframe=2;};
void() player_hammer3 = [34, player_hammer4 ] {self.weaponframe=3;};
void() player_hammer4 = [35, player_hammer5 ] {self.weaponframe=4;HIP_FireMjolnir();};
void() player_hammer5 = [36, player_hammer6 ] {self.weaponframe=4;};
void() player_hammer6 = [37, player_run ] {self.weaponframe=4;};
void() player_mjolnir1 = [38, player_mjolnir2 ] {self.weaponframe=1;};
void() player_mjolnir2 = [39, player_mjolnir3 ] {self.weaponframe=2;};
void() player_mjolnir3 = [40, player_mjolnir4 ] {self.weaponframe=3;};
void() player_mjolnir4 = [41, player_mjolnir5 ] {self.weaponframe=4;HIP_FireMjolnir();};
void() player_mjolnir5 = [42, player_mjolnir6 ] {self.weaponframe=4;};
void() player_mjolnir6 = [43, player_run ] {self.weaponframe=4;};
//============================================================================
//MED 10/18/96 added HIPSWEAPONS
//void() player_laser1 =[$nailatt1, player_laser2 ] {self.attack_finished = time + 0.1;self.weaponframe=1;self.nextthink = time + 0.09;HIP_FireLaser(0);};
//void() player_laser2 =[$nailatt2, player_laser4 ] {self.attack_finished = time + 0.1;self.weaponframe=2;self.nextthink = time + 0.09;};
//void() player_laser3 =[$nailatt1, player_laser4 ] {self.attack_finished = time + 0.1;self.weaponframe=3;self.nextthink = time + 0.09;};
//void() player_laser4 =[$nailatt2, player_laser5 ] {self.attack_finished = time + 0.1;self.weaponframe=4;self.nextthink = time + 0.09;HIP_FireLaser(1);};
//void() player_laser5 =[$nailatt1, player_laser1 ] {self.attack_finished = time + 0.1;self.weaponframe=5;self.nextthink = time + 0.09;};
//void() player_laser6 =[$nailatt2, player_laser1 ] {self.attack_finished = time + 0.1;self.weaponframe=6;self.nextthink = time + 0.09;};
void() player_laser1 =[$nailatt1, player_laser3 ] {self.attack_finished = time + 0.1;self.weaponframe=1;self.nextthink = time + 0.1;HIP_FireLaser(0);};
void() player_laser2 =[$nailatt2, player_laser3 ] {self.attack_finished = time + 0.1;self.weaponframe=2;self.nextthink = time + 0.1;};
void() player_laser3 =[$nailatt2, player_laser1 ] {self.attack_finished = time + 0.1;self.weaponframe=4;self.nextthink = time + 0.1;HIP_FireLaser(1);};
void() player_laser4 =[$nailatt1, player_laser1 ] {self.attack_finished = time + 0.1;self.weaponframe=5;self.nextthink = time + 0.1;};
//============================================================================
void() player_rocket1 =[$rockatt1, player_rocket2 ] {self.weaponframe=1;
self.effects = self.effects | EF_MUZZLEFLASH;};
void() player_rocket2 =[$rockatt2, player_rocket3 ] {self.weaponframe=2;};
void() player_rocket3 =[$rockatt3, player_rocket4 ] {self.weaponframe=3;};
void() player_rocket4 =[$rockatt4, player_rocket5 ] {self.weaponframe=4;};
void() player_rocket5 =[$rockatt5, player_rocket6 ] {self.weaponframe=5;};
void() player_rocket6 =[$rockatt6, player_run ] {self.weaponframe=6;};
void(float num_bubbles) DeathBubbles;
void() PainSound =
{
local float rs;
if (self.health < 0)
return;
if (damage_attacker.classname == "teledeath")
{
sound (self, CHAN_VOICE, "player/teledth1.wav", 1, ATTN_NONE);
return;
}
// water pain sounds
if (self.watertype == CONTENT_WATER && self.waterlevel == 3)
{
DeathBubbles(1);
if (random() > 0.5)
sound (self, CHAN_VOICE, "player/drown1.wav", 1, ATTN_NORM);
else
sound (self, CHAN_VOICE, "player/drown2.wav", 1, ATTN_NORM);
return;
}
// slime pain sounds
if (self.watertype == CONTENT_SLIME)
{
// FIX ME put in some steam here
if (random() > 0.5)
sound (self, CHAN_VOICE, "player/lburn1.wav", 1, ATTN_NORM);
else
sound (self, CHAN_VOICE, "player/lburn2.wav", 1, ATTN_NORM);
return;
}
if (self.watertype == CONTENT_LAVA)
{
if (random() > 0.5)
sound (self, CHAN_VOICE, "player/lburn1.wav", 1, ATTN_NORM);
else
sound (self, CHAN_VOICE, "player/lburn2.wav", 1, ATTN_NORM);
return;
}
if (self.pain_finished > time)
{
self.axhitme = 0;
return;
}
self.pain_finished = time + 0.5;
// don't make multiple pain sounds right after each other
// ax pain sound
if (self.axhitme == 1)
{
self.axhitme = 0;
sound (self, CHAN_VOICE, "player/axhit1.wav", 1, ATTN_NORM);
return;
}
rs = rint((random() * 5) + 1);
self.noise = "";
if (rs == 1)
self.noise = "player/pain1.wav";
else if (rs == 2)
self.noise = "player/pain2.wav";
else if (rs == 3)
self.noise = "player/pain3.wav";
else if (rs == 4)
self.noise = "player/pain4.wav";
else if (rs == 5)
self.noise = "player/pain5.wav";
else
self.noise = "player/pain6.wav";
sound (self, CHAN_VOICE, self.noise, 1, ATTN_NORM);
return;
};
void() player_pain1 = [ $pain1, player_pain2 ] {PainSound();self.weaponframe=0;};
void() player_pain2 = [ $pain2, player_pain3 ] {};
void() player_pain3 = [ $pain3, player_pain4 ] {};
void() player_pain4 = [ $pain4, player_pain5 ] {};
void() player_pain5 = [ $pain5, player_pain6 ] {};
void() player_pain6 = [ $pain6, player_run ] {};
void() player_axpain1 = [ $axpain1, player_axpain2 ] {PainSound();self.weaponframe=0;};
void() player_axpain2 = [ $axpain2, player_axpain3 ] {};
void() player_axpain3 = [ $axpain3, player_axpain4 ] {};
void() player_axpain4 = [ $axpain4, player_axpain5 ] {};
void() player_axpain5 = [ $axpain5, player_axpain6 ] {};
void() player_axpain6 = [ $axpain6, player_run ] {};
void() player_hampain1 = [ 18, player_hampain2 ] {PainSound();self.weaponframe=0;};
void() player_hampain2 = [ 19, player_hampain3 ] {};
void() player_hampain3 = [ 20, player_hampain4 ] {};
void() player_hampain4 = [ 21, player_hampain5 ] {};
void() player_hampain5 = [ 22, player_hampain6 ] {};
void() player_hampain6 = [ 23, player_run ] {};
void() player_pain =
{
if (self.weaponframe)
return;
if (self.invisible_finished > time)
return; // eyes don't have pain frames
if (self.weapon == IT_AXE)
player_axpain1 ();
else if (self.weapon == IT_MJOLNIR)
player_hampain1 ();
else
player_pain1 ();
};
void() player_diea1;
void() player_dieb1;
void() player_diec1;
void() player_died1;
void() player_diee1;
void() player_die_ax1;
void() player_die_ham1;
void() DeathBubblesSpawn =
{
local entity bubble;
if (self.owner.waterlevel != 3)
return;
bubble = spawn();
setmodel (bubble, "progs/s_bubble.spr");
setorigin (bubble, self.owner.origin + '0 0 24');
bubble.movetype = MOVETYPE_NOCLIP;
bubble.solid = SOLID_NOT;
bubble.velocity = '0 0 15';
bubble.nextthink = time + 0.5;
bubble.think = bubble_bob;
bubble.classname = "bubble";
bubble.frame = 0;
bubble.cnt = 0;
setsize (bubble, '-8 -8 -8', '8 8 8');
self.nextthink = time + 0.1;
self.think = DeathBubblesSpawn;
self.air_finished = self.air_finished + 1;
if (self.air_finished >= self.bubble_count)
remove(self);
};
void(float num_bubbles) DeathBubbles =
{
local entity bubble_spawner;
bubble_spawner = spawn();
setorigin (bubble_spawner, self.origin);
bubble_spawner.movetype = MOVETYPE_NONE;
bubble_spawner.solid = SOLID_NOT;
bubble_spawner.nextthink = time + 0.1;
bubble_spawner.think = DeathBubblesSpawn;
bubble_spawner.air_finished = 0;
bubble_spawner.owner = self;
bubble_spawner.bubble_count = num_bubbles;
return;
};
void() DeathSound =
{
local float rs;
// water death sounds
if (self.waterlevel == 3)
{
DeathBubbles(20);
sound (self, CHAN_VOICE, "player/h2odeath.wav", 1, ATTN_NONE);
return;
}
rs = rint ((random() * 4) + 1);
if (rs == 1)
self.noise = "player/death1.wav";
if (rs == 2)
self.noise = "player/death2.wav";
if (rs == 3)
self.noise = "player/death3.wav";
if (rs == 4)
self.noise = "player/death4.wav";
if (rs == 5)
self.noise = "player/death5.wav";
sound (self, CHAN_VOICE, self.noise, 1, ATTN_NONE);
return;
};
void() PlayerDead =
{
self.nextthink = -1;
// allow respawn after a certain time
self.deadflag = DEAD_DEAD;
};
vector(float dm) VelocityForDamage =
{
local vector v;
//MED 01/17/97
if (vlen(damage_inflictor.velocity)>0)
{
v = 0.2 * damage_inflictor.velocity;
v = v + (25 * normalize(self.origin-damage_inflictor.origin));
v_z = 100 + 100 * random();
v_x = v_x + (50 * crandom());
v_y = v_y + (50 * crandom());
}
else
{
v_x = 100 * crandom();
v_y = 100 * crandom();
v_z = 200 + 100 * random();
}
if (dm > -50)
{
// dprint ("level 1\n");
v = v * 0.7;
}
else if (dm > -200)
{
// dprint ("level 3\n");
v = v * 2;
}
else
v = v * 10;
return v;
};
void(string gibname, float dm) ThrowGib =
{
local entity new;
new = spawn();
new.origin = self.origin;
setmodel (new, gibname);
setsize (new, '0 0 0', '0 0 0');
new.velocity = VelocityForDamage (dm);
new.movetype = MOVETYPE_BOUNCE;
new.solid = SOLID_NOT;
new.avelocity_x = random()*600;
new.avelocity_y = random()*600;
new.avelocity_z = random()*600;
new.think = SUB_Remove;
new.ltime = time;
new.nextthink = time + 10 + random()*10;
new.frame = 0;
new.flags = 0;
};
//MED
void() HeadThink =
{
self.nextthink = -1;
if (world.worldtype != 2)
{
if (random()<0.1)
sound (self, 6, "misc/flys.wav", 0.7, ATTN_STATIC);
}
};
void(string gibname, float dm) ThrowHead =
{
setmodel (self, gibname);
self.frame = 0;
// self.nextthink = -1;
//MED
self.nextthink = time + 1.5;
self.movetype = MOVETYPE_BOUNCE;
self.takedamage = DAMAGE_NO;
self.solid = SOLID_NOT;
self.view_ofs = '0 0 8';
setsize (self, '-16 -16 0', '16 16 56');
self.velocity = VelocityForDamage (dm);
self.origin_z = self.origin_z - 24;
self.flags = self.flags - (self.flags & FL_ONGROUND);
self.avelocity = crandom() * '0 600 0';
//MED
self.gorging = TRUE;
self.think = HeadThink;
};
void() GibPlayer =
{
ThrowHead ("progs/h_player.mdl", self.health);
ThrowGib ("progs/gib1.mdl", self.health);
ThrowGib ("progs/gib2.mdl", self.health);
ThrowGib ("progs/gib3.mdl", self.health);
self.deadflag = DEAD_DEAD;
if (damage_attacker.classname == "teledeath")
{
sound (self, CHAN_VOICE, "player/teledth1.wav", 1, ATTN_NONE);
return;
}
if (damage_attacker.classname == "teledeath2")
{
sound (self, CHAN_VOICE, "player/teledth1.wav", 1, ATTN_NONE);
return;
}
if (random() < 0.5)
sound (self, CHAN_VOICE, "player/gib.wav", 1, ATTN_NONE);
else
sound (self, CHAN_VOICE, "player/udeath.wav", 1, ATTN_NONE);
};
void() PlayerDie =
{
local float i;
// self.items = self.items - (self.items & IT_INVISIBILITY);
self.items = self.items - (self.items &
(IT_INVISIBILITY | IT_INVULNERABILITY | IT_SUIT | IT_QUAD) );
self.invisible_finished = 0; // don't die as eyes
self.invincible_finished = 0;
self.super_damage_finished = 0;
self.radsuit_finished = 0;
//JIM
self.wetsuit_finished = 0;
self.effects = 0; // 1998-07-23 Glowing corpse of players which had quad/pentagram until respawn fix by Maddes
self.modelindex = modelindex_player; // don't use eyes
//JIM
self.empathy_finished = 0;
self.items2 = self.items2 - (self.items2 & HIP_IT_EMPATHY_SHIELDS);
if (deathmatch || coop)
DropBackpack();
self.weaponmodel="";
self.view_ofs = '0 0 -8';
self.deadflag = DEAD_DYING;
self.solid = SOLID_NOT;
self.flags = self.flags - (self.flags & FL_ONGROUND);
self.movetype = MOVETYPE_TOSS;
if (self.velocity_z < 10)
self.velocity_z = self.velocity_z + random()*300;
if (self.health < -40)
{
GibPlayer ();
return;
}
DeathSound();
self.angles_x = 0;
self.angles_z = 0;
if (self.weapon == IT_AXE)
{
player_die_ax1 ();
return;
}
//MED 12/04/96
else if (self.weapon == IT_MJOLNIR)
{
self.modelindex = modelindex_hammer; // use hammer model
player_die_ham1();
return;
}
i = cvar("temp1");
if (!i)
i = 1 + floor(random()*6);
if (i == 1)
player_diea1();
else if (i == 2)
player_dieb1();
else if (i == 3)
player_diec1();
else if (i == 4)
player_died1();
else
player_diee1();
};
void() set_suicide_frame =
{ // used by klill command and diconnect command
if (self.model != "progs/player.mdl")
return; // allready gibbed
self.frame = $deatha11;
self.solid = SOLID_NOT;
self.movetype = MOVETYPE_TOSS;
self.deadflag = DEAD_DEAD;
self.nextthink = -1;
};
void() player_diea1 = [ $deatha1, player_diea2 ] {};
void() player_diea2 = [ $deatha2, player_diea3 ] {};
void() player_diea3 = [ $deatha3, player_diea4 ] {};
void() player_diea4 = [ $deatha4, player_diea5 ] {};
void() player_diea5 = [ $deatha5, player_diea6 ] {};
void() player_diea6 = [ $deatha6, player_diea7 ] {};
void() player_diea7 = [ $deatha7, player_diea8 ] {};
void() player_diea8 = [ $deatha8, player_diea9 ] {};
void() player_diea9 = [ $deatha9, player_diea10 ] {};
void() player_diea10 = [ $deatha10, player_diea11 ] {};
void() player_diea11 = [ $deatha11, player_diea11 ] {PlayerDead();};
void() player_dieb1 = [ $deathb1, player_dieb2 ] {};
void() player_dieb2 = [ $deathb2, player_dieb3 ] {};
void() player_dieb3 = [ $deathb3, player_dieb4 ] {};
void() player_dieb4 = [ $deathb4, player_dieb5 ] {};
void() player_dieb5 = [ $deathb5, player_dieb6 ] {};
void() player_dieb6 = [ $deathb6, player_dieb7 ] {};
void() player_dieb7 = [ $deathb7, player_dieb8 ] {};
void() player_dieb8 = [ $deathb8, player_dieb9 ] {};
void() player_dieb9 = [ $deathb9, player_dieb9 ] {PlayerDead();};
void() player_diec1 = [ $deathc1, player_diec2 ] {};
void() player_diec2 = [ $deathc2, player_diec3 ] {};
void() player_diec3 = [ $deathc3, player_diec4 ] {};
void() player_diec4 = [ $deathc4, player_diec5 ] {};
void() player_diec5 = [ $deathc5, player_diec6 ] {};
void() player_diec6 = [ $deathc6, player_diec7 ] {};
void() player_diec7 = [ $deathc7, player_diec8 ] {};
void() player_diec8 = [ $deathc8, player_diec9 ] {};
void() player_diec9 = [ $deathc9, player_diec10 ] {};
void() player_diec10 = [ $deathc10, player_diec11 ] {};
void() player_diec11 = [ $deathc11, player_diec12 ] {};
void() player_diec12 = [ $deathc12, player_diec13 ] {};
void() player_diec13 = [ $deathc13, player_diec14 ] {};
void() player_diec14 = [ $deathc14, player_diec15 ] {};
void() player_diec15 = [ $deathc15, player_diec15 ] {PlayerDead();};
void() player_died1 = [ $deathd1, player_died2 ] {};
void() player_died2 = [ $deathd2, player_died3 ] {};
void() player_died3 = [ $deathd3, player_died4 ] {};
void() player_died4 = [ $deathd4, player_died5 ] {};
void() player_died5 = [ $deathd5, player_died6 ] {};
void() player_died6 = [ $deathd6, player_died7 ] {};
void() player_died7 = [ $deathd7, player_died8 ] {};
void() player_died8 = [ $deathd8, player_died9 ] {};
void() player_died9 = [ $deathd9, player_died9 ] {PlayerDead();};
void() player_diee1 = [ $deathe1, player_diee2 ] {};
void() player_diee2 = [ $deathe2, player_diee3 ] {};
void() player_diee3 = [ $deathe3, player_diee4 ] {};
void() player_diee4 = [ $deathe4, player_diee5 ] {};
void() player_diee5 = [ $deathe5, player_diee6 ] {};
void() player_diee6 = [ $deathe6, player_diee7 ] {};
void() player_diee7 = [ $deathe7, player_diee8 ] {};
void() player_diee8 = [ $deathe8, player_diee9 ] {};
void() player_diee9 = [ $deathe9, player_diee9 ] {PlayerDead();};
void() player_die_ax1 = [ $axdeth1, player_die_ax2 ] {};
void() player_die_ax2 = [ $axdeth2, player_die_ax3 ] {};
void() player_die_ax3 = [ $axdeth3, player_die_ax4 ] {};
void() player_die_ax4 = [ $axdeth4, player_die_ax5 ] {};
void() player_die_ax5 = [ $axdeth5, player_die_ax6 ] {};
void() player_die_ax6 = [ $axdeth6, player_die_ax7 ] {};
void() player_die_ax7 = [ $axdeth7, player_die_ax8 ] {};
void() player_die_ax8 = [ $axdeth8, player_die_ax9 ] {};
void() player_die_ax9 = [ $axdeth9, player_die_ax9 ] {PlayerDead();};
void() player_die_ham1 = [ 24 , player_die_ham2 ] {};
void() player_die_ham2 = [ 25 , player_die_ham3 ] {};
void() player_die_ham3 = [ 26 , player_die_ham4 ] {};
void() player_die_ham4 = [ 27 , player_die_ham5 ] {};
void() player_die_ham5 = [ 28 , player_die_ham6 ] {};
void() player_die_ham6 = [ 29 , player_die_ham7 ] {};
void() player_die_ham7 = [ 30 , player_die_ham8 ] {};
void() player_die_ham8 = [ 31 , player_die_ham8 ] {PlayerDead();};
| 0 | 0.913544 | 1 | 0.913544 | game-dev | MEDIA | 0.994929 | game-dev | 0.686906 | 1 | 0.686906 |
traas-stack/kapacity | 5,433 | pkg/portrait/provider/common.go | /*
Copyright 2023 The Kapacity Authors.
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 provider
import (
"context"
"fmt"
"sync"
"time"
"github.com/mitchellh/hashstructure/v2"
"github.com/robfig/cron/v3"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/event"
autoscalingv1alpha1 "github.com/traas-stack/kapacity/apis/autoscaling/v1alpha1"
"github.com/traas-stack/kapacity/pkg/util"
)
type cronTask struct {
Hash uint64
Crontabs []*cron.Cron
}
func (c *cronTask) Stop() {
for _, crontab := range c.Crontabs {
crontab.Stop()
}
}
func (c *cronTask) Start() {
for _, crontab := range c.Crontabs {
crontab.Start()
}
}
type cronTaskTriggerManager struct {
cronTaskMap sync.Map // map[types.NamespacedName]*cronTask
eventTrigger chan event.GenericEvent
}
func newCronTaskTriggerManager(eventTrigger chan event.GenericEvent) *cronTaskTriggerManager {
return &cronTaskTriggerManager{
eventTrigger: eventTrigger,
}
}
func (m *cronTaskTriggerManager) StartCronTaskTrigger(taskKey types.NamespacedName, ihpa *autoscalingv1alpha1.IntelligentHorizontalPodAutoscaler, crons []autoscalingv1alpha1.ReplicaCron) error {
hash, err := hashstructure.Hash(crons, hashstructure.FormatV2, nil)
if err != nil {
return fmt.Errorf("failed to hash crons: %v", err)
}
taskV, ok := m.cronTaskMap.Load(taskKey)
if ok {
task := taskV.(*cronTask)
if hash == task.Hash {
return nil
}
task.Stop()
m.cronTaskMap.Delete(taskKey)
}
task := &cronTask{
Hash: hash,
Crontabs: make([]*cron.Cron, 0, len(crons)),
}
for _, cronData := range crons {
location, err := time.LoadLocation(cronData.TimeZone)
if err != nil {
return fmt.Errorf("failed to load time zone of cron %q: %v", cronData.Name, err)
}
ihpaEvent := event.GenericEvent{Object: ihpa}
crontab := cron.New(cron.WithLocation(location))
if _, err := crontab.AddFunc(cronData.Start, func() {
m.eventTrigger <- ihpaEvent
}); err != nil {
return fmt.Errorf("failed to add crontab start function of cron %q: %v", cronData.Name, err)
}
if _, err := crontab.AddFunc(cronData.End, func() {
m.eventTrigger <- ihpaEvent
}); err != nil {
return fmt.Errorf("failed to add crontab end function of cron %q: %v", cronData.Name, err)
}
task.Crontabs = append(task.Crontabs, crontab)
}
m.cronTaskMap.Store(taskKey, task)
task.Start()
return nil
}
func (m *cronTaskTriggerManager) StopCronTaskTrigger(taskKey types.NamespacedName) {
taskV, ok := m.cronTaskMap.Load(taskKey)
if ok {
task := taskV.(*cronTask)
task.Stop()
m.cronTaskMap.Delete(taskKey)
}
}
func getActiveReplicaCron(crons []autoscalingv1alpha1.ReplicaCron) (*autoscalingv1alpha1.ReplicaCron, time.Time, error) {
var (
active *autoscalingv1alpha1.ReplicaCron
expireTime time.Time
)
now := time.Now()
for i := range crons {
rc := &crons[i]
location, err := time.LoadLocation(rc.TimeZone)
if err != nil {
return nil, time.Time{}, fmt.Errorf("failed to load time zone of cron %q: %v", rc.Name, err)
}
t := now.In(location)
isActive, cronExpireTime, err := util.IsCronActive(t, rc.Start, rc.End)
if err != nil {
return nil, time.Time{}, fmt.Errorf("failed to check active for cron %q: %v", rc.Name, err)
}
if isActive {
if active != nil {
return nil, time.Time{}, fmt.Errorf("found overlapping cron %q and %q", active.Name, rc.Name)
}
active = rc
expireTime = cronExpireTime
}
}
return active, expireTime, nil
}
type timerCanceller struct {
T time.Time
Cancel context.CancelFunc
}
type timerTriggerManager struct {
timerCancellerMap sync.Map // map[types.NamespacedName]*timerCanceller
eventTrigger chan event.GenericEvent
}
func newTimerTriggerManager(eventTrigger chan event.GenericEvent) *timerTriggerManager {
return &timerTriggerManager{
eventTrigger: eventTrigger,
}
}
func (m *timerTriggerManager) StartTimerTrigger(ctx context.Context, timerKey types.NamespacedName, ihpa *autoscalingv1alpha1.IntelligentHorizontalPodAutoscaler, t time.Time) {
cancellerV, ok := m.timerCancellerMap.Load(timerKey)
if ok {
canceller := cancellerV.(*timerCanceller)
if t.Equal(canceller.T) {
return
}
canceller.Cancel()
m.timerCancellerMap.Delete(timerKey)
}
timerContext, cancel := context.WithCancel(ctx)
m.timerCancellerMap.Store(timerKey, &timerCanceller{
T: t,
Cancel: cancel,
})
go func() {
d := time.Until(t)
if d <= 0 {
m.eventTrigger <- event.GenericEvent{Object: ihpa}
return
}
timer := time.NewTimer(d)
select {
case <-timer.C:
m.eventTrigger <- event.GenericEvent{Object: ihpa}
case <-timerContext.Done():
timer.Stop()
}
}()
}
func (m *timerTriggerManager) StopTimerTrigger(timerKey types.NamespacedName) {
cancellerV, ok := m.timerCancellerMap.Load(timerKey)
if ok {
canceller := cancellerV.(*timerCanceller)
canceller.Cancel()
m.timerCancellerMap.Delete(timerKey)
}
}
| 0 | 0.946549 | 1 | 0.946549 | game-dev | MEDIA | 0.221348 | game-dev | 0.953497 | 1 | 0.953497 |
InvadingOctopus/octopuskit | 1,441 | QuickStart/Universal/Components/GlobalDataComponent.swift | //
// GlobalDataComponent.swift
// OctopusKitQuickStart
//
// Created by [email protected] on 2018/07/27.
// Copyright © 2020 Invading Octopus. Licensed under Apache License v2.0 (see LICENSE.txt)
//
import SpriteKit
import GameplayKit
import OctopusCore
import OctopusKit
/// A custom component for the QuickStart project that holds some simple data to be shared across multiple game states and scenes.
final class GlobalDataComponent: OKComponent, RequiresUpdatesPerFrame, ObservableObject {
public var secondsElapsed: TimeInterval = 0
/// A more slowly-updated version of `secondsElapsed`. Should reduce strain on SwiftUI updates? :)
public var secondsElapsedRounded: Int = 0 {
willSet {
// ℹ️ We don't use @Published here because that causes a SwiftUI update every frame, even when this value does not change between seconds.
if newValue != secondsElapsedRounded {
self.objectWillChange.send()
}
}
}
@Published
public var emojiCount: Int = 0 {
didSet {
emojiHighScore = max(emojiCount, emojiHighScore)
}
}
@OKUserDefault(key: "emojiHighScore", defaultValue: 50) public var emojiHighScore: Int
override func update(deltaTime seconds: TimeInterval) {
secondsElapsed += seconds
secondsElapsedRounded = Int(secondsElapsed.rounded(.down))
}
}
| 0 | 0.859474 | 1 | 0.859474 | game-dev | MEDIA | 0.611143 | game-dev | 0.944266 | 1 | 0.944266 |
DanceManiac/Advanced-X-Ray-Public | 3,466 | SourcesAXR/xrGameCS/doors_manager.cpp | ////////////////////////////////////////////////////////////////////////////
// Created : 23.06.2009
// Author : Dmitriy Iassenev
// Copyright (C) GSC Game World - 2009
////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "doors_manager.h"
#include "gameobject.h"
#include "doors_door.h"
#include "doors_actor.h"
#include <quadtree.h>
using doors::actor;
using doors::manager;
using doors::door;
manager::manager ( Fbox const& bounding_box ) :
m_doors ( bounding_box, 2.f, 512, 2048 )
{
}
manager::~manager ( )
{
VERIFY2 ( m_doors.empty(), make_string("there are %d still registered doors", m_doors.size()) );
}
//#include "level.h"
//#include "script_game_object.h"
//
//void manager::check_bug_door ( ) const
//{
// CObject const* const object = Level().Objects.FindObjectByName("shkaf_work_01_door_0000");
// if ( !object ) {
// Msg ( "there is now object[\"shkaf_work_01_door_0000\"] found" );
// return;
// }
//
// CGameObject const* const game_object = smart_cast<CGameObject const*>(object);
// VERIFY ( game_object );
// if ( !game_object->lua_game_object()->m_door ) {
// Msg ( "object[\"shkaf_work_01_door_0000\"] has not been registered as a door yet" );
// return;
// }
//
// door const* const found = m_doors.find( game_object->lua_game_object()->m_door->position() );
// if ( !found ) {
// Msg ( "object[\"shkaf_work_01_door_0000\"] has been unregistered already[0x%08x]?", game_object->lua_game_object()->m_door );
// return;
// }
//
// Msg ( "object[\"shkaf_work_01_door_0000\"] has been registered as a door" );
//}
//
door* manager::register_door ( CPhysicObject& object )
{
door* const result = xr_new<door>( &object );
//if ( !xr_strcmp(result->get_name(),"shkaf_work_01_door_0000") ) {
// Msg ( "registering door[\"shkaf_work_01_door_0000\"][%f][%f][%f]", VPUSH(result->position()) );
//}
//check_bug_door ( );
m_doors.insert ( result );
//check_bug_door ( );
return result;
}
void manager::unregister_door ( door*& door )
{
//if ( !xr_strcmp(door->get_name(),"shkaf_work_01_door_0000") ) {
// Msg ( "UNregistering door[\"shkaf_work_01_door_0000\"][%f][%f][%f]", VPUSH(door->position()) );
//}
//check_bug_door ( );
m_doors.remove ( door );
//check_bug_door ( );
xr_delete ( door );
}
bool manager::actualize_doors_state ( actor& actor, float const average_speed )
{
float const radius = average_speed*g_door_open_time + g_door_length;
Fvector const& position = actor.get_position();
//check_bug_door ( );
m_doors.nearest ( position, radius, m_nearest_doors );
//check_bug_door ( );
if ( m_nearest_doors.empty() && !actor.need_update() )
return true;
return actor.update_doors( m_nearest_doors, average_speed );
}
void manager::on_door_is_open ( door* door )
{
door->on_change_state ( door_state_open );
}
void manager::on_door_is_closed ( door* door )
{
door->on_change_state ( door_state_closed );
}
bool manager::is_door_locked ( door const* door ) const
{
return door->is_locked( doors::door_state_open ) || door->is_locked( doors::door_state_closed );
}
void manager::lock_door ( door* const door )
{
door->lock ( );
}
void manager::unlock_door ( door* const door )
{
door->unlock ( );
}
bool manager::is_door_blocked ( door* const door ) const
{
return door->is_blocked(door_state_open) || door->is_blocked(door_state_closed);
} | 0 | 0.914028 | 1 | 0.914028 | game-dev | MEDIA | 0.885381 | game-dev | 0.828608 | 1 | 0.828608 |
dmolony/DiskBrowser | 20,706 | src/com/bytezone/diskbrowser/wizardry/Wizardry4BootDisk.java | package com.bytezone.diskbrowser.wizardry;
import java.util.ArrayList;
import java.util.List;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import com.bytezone.diskbrowser.applefile.AbstractFile;
import com.bytezone.diskbrowser.disk.AppleDisk;
import com.bytezone.diskbrowser.disk.DefaultAppleFileSource;
import com.bytezone.diskbrowser.disk.Disk;
import com.bytezone.diskbrowser.disk.DiskAddress;
import com.bytezone.diskbrowser.pascal.FileEntry;
import com.bytezone.diskbrowser.pascal.PascalDisk;
import com.bytezone.diskbrowser.utilities.HexFormatter;
import com.bytezone.diskbrowser.utilities.Utility;
import com.bytezone.diskbrowser.wizardry.Header.ScenarioData;
// -----------------------------------------------------------------------------------//
public class Wizardry4BootDisk extends PascalDisk
// -----------------------------------------------------------------------------------//
{
private Header scenarioHeader;
private Relocator relocator;
private MessageBlock messageBlock;
private Huffman huffman;
private final int version;
private List<CharacterV4> characters = new ArrayList<> ();
private List<CharacterParty> parties = new ArrayList<> ();
private List<ItemV4> items = new ArrayList<> ();
private List<MonsterV4> monsters = new ArrayList<> ();
private List<String> spellNames = new ArrayList<> ();
// ---------------------------------------------------------------------------------//
public Wizardry4BootDisk (AppleDisk[] dataDisks)
// ---------------------------------------------------------------------------------//
{
super (dataDisks[0]);
version = dataDisks.length == 7 ? 4 : dataDisks.length == 10 ? 5 : 0;
DefaultTreeModel model = (DefaultTreeModel) catalogTree.getModel ();
DefaultMutableTreeNode currentRoot = (DefaultMutableTreeNode) model.getRoot ();
// get the relocation table
DefaultMutableTreeNode relocNode = findNode (currentRoot, "SYSTEM.RELOC");
FileEntry fileEntry = (FileEntry) relocNode.getUserObject ();
if (fileEntry != null)
{
relocator = new Relocator (fileEntry.getUniqueName (), fileEntry.getDataSource ().buffer);
relocator.createNewBuffer (dataDisks);
fileEntry.setFile (relocator);
}
// reset the code segment so that it rebuilds itself from the new data
DefaultMutableTreeNode pascalNode = findNode (currentRoot, "SYSTEM.PASCAL");
fileEntry = (FileEntry) pascalNode.getUserObject ();
if (fileEntry != null)
{
fileEntry.setFile (null);
fileEntry.getDataSource ();
}
DefaultMutableTreeNode huffNode = findNode (currentRoot, "ASCII.HUFF");
fileEntry = (FileEntry) huffNode.getUserObject ();
if (fileEntry != null)
{
huffman = new Huffman ("Huffman tree", fileEntry.getDataSource ().buffer);
fileEntry.setFile (huffman);
}
DefaultMutableTreeNode messagesNode = findNode (currentRoot, "ASCII.KRN");
fileEntry = (FileEntry) messagesNode.getUserObject ();
if (fileEntry != null)
{
messageBlock = new MessageBlock (fileEntry.getDataSource ().buffer, huffman);
fileEntry.setFile (messageBlock);
messagesNode.setAllowsChildren (true);
List<DiskAddress> blocks = fileEntry.getSectors ();
int count = 0;
for (MessageDataBlock mdb : messageBlock)
{
List<DiskAddress> messageBlocks = new ArrayList<> ();
messageBlocks.add (blocks.get (count++));
addToNode (mdb, messagesNode, messageBlocks);
}
}
// scenario data
if (version == 4)
{
DefaultMutableTreeNode scenarioNode = findNode (currentRoot, "SCENARIO.DATA");
fileEntry = (FileEntry) scenarioNode.getUserObject ();
if (fileEntry != null)
{
fileEntry.setFile (null);
scenarioNode.setAllowsChildren (true);
scenarioHeader = new Header (scenarioNode, this);
readSpells ();
linkCharacters4 (scenarioNode, fileEntry);
linkParties ();
linkMazeLevels4 (scenarioNode, fileEntry);
linkMonstersV4 (scenarioNode, fileEntry);
linkItemsV4 (scenarioNode, fileEntry);
}
}
else if (version == 5)
{
DefaultMutableTreeNode scenarioNode = findNode (currentRoot, "DRAGON.DATA");
fileEntry = (FileEntry) scenarioNode.getUserObject ();
if (fileEntry != null)
{
fileEntry.setFile (null);
scenarioNode.setAllowsChildren (true);
linkMazeLevels5 (scenarioNode, fileEntry);
linkBlock1 (scenarioNode, fileEntry);
linkOracle (scenarioNode, fileEntry);
linkBlock2 (scenarioNode, fileEntry);
}
}
else
System.out.println ("No Wizardry version set");
// monster images
if (version == 4)
{
DefaultMutableTreeNode monstersNode = findNode (currentRoot, "200.MONSTERS");
fileEntry = (FileEntry) monstersNode.getUserObject ();
if (fileEntry != null)
{
monstersNode.setAllowsChildren (true);
linkMonsterImages4 (monstersNode, fileEntry);
}
}
else if (version == 5)
{
DefaultMutableTreeNode monstersNode = findNode (currentRoot, "200.MONSTERS");
fileEntry = (FileEntry) monstersNode.getUserObject ();
if (fileEntry != null)
{
monstersNode.setAllowsChildren (true);
linkMonsterImages5 (monstersNode, fileEntry);
}
}
}
// ---------------------------------------------------------------------------------//
private void linkCharacters4 (DefaultMutableTreeNode scenarioNode, FileEntry fileEntry)
// ---------------------------------------------------------------------------------//
{
ScenarioData sd = scenarioHeader.get (Header.CHARACTER_AREA);
byte[] buffer = fileEntry.getDataSource ().buffer;
List<DiskAddress> blocks = fileEntry.getSectors ();
DefaultMutableTreeNode charactersNode = linkNode ("Characters", "Characters", scenarioNode);
List<DiskAddress> allCharacterBlocks = new ArrayList<> ();
int ptr = sd.dataOffset * 512;
for (int i = 0; i < 500; i++)
{
byte[] out = huffman.decodeMessage (buffer, ptr);
String name = HexFormatter.getPascalString (out, 1);
CharacterV4 c = new CharacterV4 (name, out, i);
characters.add (c);
if (!name.isEmpty ())
{
List<DiskAddress> characterBlocks = new ArrayList<> ();
DiskAddress da = blocks.get (ptr / 512);
characterBlocks.add (da);
addToNode (c, charactersNode, characterBlocks);
if (!allCharacterBlocks.contains (da))
allCharacterBlocks.add (da);
}
ptr += sd.totalBlocks;
}
DefaultAppleFileSource afs = (DefaultAppleFileSource) charactersNode.getUserObject ();
afs.setSectors (allCharacterBlocks);
}
// ---------------------------------------------------------------------------------//
private void linkParties ()
// ---------------------------------------------------------------------------------//
{
for (CharacterV4 character : characters)
{
if (character.isInParty () || character.getName ().isEmpty ())
continue;
CharacterParty party = new CharacterParty ();
parties.add (party);
link (character, party);
}
}
// ---------------------------------------------------------------------------------//
private void readSpells ()
// ---------------------------------------------------------------------------------//
{
for (int i = 0; i < 51; i++)
{
String spellName = messageBlock.getMessageLine (i + 5000);
if (spellName.startsWith ("*"))
spellName = spellName.substring (1);
spellNames.add (spellName);
}
}
// ---------------------------------------------------------------------------------//
private void link (CharacterV4 character, CharacterParty party)
// ---------------------------------------------------------------------------------//
{
if (character.isInParty ())
return;
party.add (character);
if (character.nextCharacterId > 0)
link (characters.get (character.nextCharacterId), party);
}
// ---------------------------------------------------------------------------------//
private void linkMonstersV4 (DefaultMutableTreeNode scenarioNode, FileEntry fileEntry)
// ---------------------------------------------------------------------------------//
{
ScenarioData sd = scenarioHeader.get (Header.MONSTER_AREA);
byte[] buffer = fileEntry.getDataSource ().buffer;
List<DiskAddress> blocks = fileEntry.getSectors ();
DefaultMutableTreeNode monstersNode = linkNode ("Monsters", "Monsters", scenarioNode);
List<DiskAddress> allMonsterBlocks = new ArrayList<> ();
String[] monsterNames = new String[4];
int ptr = sd.dataOffset * 512;
for (int i = 0; i < sd.total; i++)
{
byte[] out = huffman.decodeMessage (buffer, ptr);
int len = out[0] & 0xFF;
if (len > out.length)
System.out.printf ("Decoded array too short: (#%3d) %3d > %3d%n", i, len, out.length);
for (int j = 0; j < monsterNames.length; j++)
monsterNames[j] = messageBlock.getMessageLine (i * 4 + 13000 + j);
MonsterV4 monster = new MonsterV4 (monsterNames, out, i);
monsters.add (monster);
// System.out.println (monster.getName ());
List<DiskAddress> monsterBlocks = new ArrayList<> ();
DiskAddress da = blocks.get (ptr / 512);
monsterBlocks.add (da);
addToNode (monster, monstersNode, monsterBlocks);
if (!allMonsterBlocks.contains (da))
allMonsterBlocks.add (da);
ptr += sd.totalBlocks;
}
DefaultAppleFileSource afs = (DefaultAppleFileSource) monstersNode.getUserObject ();
afs.setSectors (allMonsterBlocks);
}
// ---------------------------------------------------------------------------------//
private void linkItemsV4 (DefaultMutableTreeNode scenarioNode, FileEntry fileEntry)
// ---------------------------------------------------------------------------------//
{
ScenarioData sd = scenarioHeader.get (Header.ITEM_AREA);
byte[] buffer = fileEntry.getDataSource ().buffer;
List<DiskAddress> blocks = fileEntry.getSectors ();
DefaultMutableTreeNode itemsNode = linkNode ("Items", "Items", scenarioNode);
List<DiskAddress> allItemBlocks = new ArrayList<> ();
String[] itemNames = new String[2];
int ptr = sd.dataOffset * 512;
for (int i = 0; i < sd.total; i++)
{
byte[] out = huffman.decodeMessage (buffer, ptr);
for (int j = 0; j < itemNames.length; j++)
{
itemNames[j] = messageBlock.getMessageLine (i * 2 + 14000 + j);
if (itemNames[j] == null)
itemNames[j] = "Broken Item";
}
ItemV4 item = new ItemV4 (itemNames, out, i);
items.add (item);
List<DiskAddress> itemBlocks = new ArrayList<> ();
DiskAddress da = blocks.get (ptr / 512);
itemBlocks.add (da);
addToNode (item, itemsNode, itemBlocks);
if (!allItemBlocks.contains (da))
allItemBlocks.add (da);
ptr += sd.totalBlocks;
}
DefaultAppleFileSource afs = (DefaultAppleFileSource) itemsNode.getUserObject ();
afs.setSectors (allItemBlocks);
for (CharacterV4 character : characters)
character.addPossessions (items);
// for (int i = 0; i < items.size (); i++)
// System.out.printf ("%3d %s%n", i, items.get (i));
for (ItemV4 item : items)
item.link (items, spellNames);
}
// ---------------------------------------------------------------------------------//
private void linkMazeLevels4 (DefaultMutableTreeNode scenarioNode, FileEntry fileEntry)
// ---------------------------------------------------------------------------------//
{
ScenarioData mazeData = scenarioHeader.get (Header.MAZE_AREA);
byte[] buffer = fileEntry.getDataSource ().buffer;
List<DiskAddress> blocks = fileEntry.getSectors ();
DefaultMutableTreeNode mazeNode = linkNode ("Maze", "Levels string", scenarioNode);
List<DiskAddress> allMazeBlocks = new ArrayList<> ();
for (int i = 0; i < mazeData.total; i++)
{
int blockPtr = mazeData.dataOffset + i * 2;
byte[] level = new byte[0x380]; // 896
System.arraycopy (buffer, blockPtr * 512, level, 0, level.length);
List<DiskAddress> mazeBlocks = new ArrayList<> ();
mazeBlocks.add (blocks.get (blockPtr));
mazeBlocks.add (blocks.get (blockPtr + 1));
addToNode (new MazeLevel (level, i), mazeNode, mazeBlocks);
allMazeBlocks.addAll (mazeBlocks);
}
DefaultAppleFileSource afs = (DefaultAppleFileSource) mazeNode.getUserObject ();
afs.setSectors (allMazeBlocks);
}
// ---------------------------------------------------------------------------------//
private void linkMonsterImages4 (DefaultMutableTreeNode monstersNode, FileEntry fileEntry)
// ---------------------------------------------------------------------------------//
{
List<DiskAddress> pictureBlocks = fileEntry.getSectors ();
Wiz4Monsters w4monsters = new Wiz4Monsters ("monsters", fileEntry.getDataSource ().buffer);
fileEntry.setFile (w4monsters);
int count = 0;
for (Wiz4Image image : w4monsters.images)
{
List<DiskAddress> monsterBlocks = new ArrayList<> ();
monsterBlocks.add (pictureBlocks.get (w4monsters.blocks.get (count++)));
addToNode (image, monstersNode, monsterBlocks);
}
}
// ---------------------------------------------------------------------------------//
private void linkMonsterImages5 (DefaultMutableTreeNode monstersNode, FileEntry fileEntry)
// ---------------------------------------------------------------------------------//
{
List<DiskAddress> pictureBlocks = fileEntry.getSectors ();
Wiz5Monsters w5monsters = new Wiz5Monsters ("monsters", fileEntry.getDataSource ().buffer);
fileEntry.setFile (w5monsters);
for (Wiz5Monsters.Monster monster : w5monsters)
{
List<DiskAddress> monsterBlocks = new ArrayList<> ();
for (Integer blockId : monster.getBlocks ())
monsterBlocks.add (pictureBlocks.get (blockId));
addToNode (monster.getImage (), monstersNode, monsterBlocks);
}
}
// ---------------------------------------------------------------------------------//
private void linkMazeLevels5 (DefaultMutableTreeNode scenarioNode, FileEntry fileEntry)
// ---------------------------------------------------------------------------------//
{
byte[] buffer = fileEntry.getDataSource ().buffer;
List<DiskAddress> blocks = fileEntry.getSectors ();
DefaultMutableTreeNode mazeNode = linkNode ("Maze", "Level 5 mazes", scenarioNode);
List<DiskAddress> allMazeBlocks = new ArrayList<> ();
int dataSize = 0x39A;
int base = 0x1800;
for (int i = 0; i < 8; i++)
{
int offset = base + i * 0x400;
byte[] data = new byte[0x800];
System.arraycopy (buffer, offset, data, 0, dataSize);
System.arraycopy (buffer, offset + 0x2000, data, 0x400, dataSize);
MazeGridV5 grid = new MazeGridV5 ("Maze level " + (i + 1), data, messageBlock);
List<DiskAddress> mazeBlocks = new ArrayList<> ();
for (int j = 0; j < 4; j++)
mazeBlocks.add (blocks.get (12 + i * 4 + j));
allMazeBlocks.addAll (mazeBlocks);
addToNode (grid, mazeNode, mazeBlocks);
}
DefaultAppleFileSource afs = (DefaultAppleFileSource) mazeNode.getUserObject ();
afs.setSectors (allMazeBlocks);
}
// ---------------------------------------------------------------------------------//
private void linkBlock1 (DefaultMutableTreeNode scenarioNode, FileEntry fileEntry)
// ---------------------------------------------------------------------------------//
{
byte[] buffer = fileEntry.getDataSource ().buffer;
List<DiskAddress> blocks = fileEntry.getSectors ();
StringBuilder text = new StringBuilder ();
List<DiskAddress> allBlocks = new ArrayList<> ();
for (int i = 0; i < 23; i++)
{
allBlocks.add (blocks.get (44 + i));
}
int offset = 0x5800;
int length = 66;
for (int i = 0; i < 179; i++)
{
text.append (String.format ("%04X : %s%n", (offset + i * length),
HexFormatter.getHexString (buffer, offset + i * length, length)));
}
DefaultMutableTreeNode oracleNode = linkNode ("Block1", text.toString (), scenarioNode);
oracleNode.setAllowsChildren (false);
DefaultAppleFileSource afs = (DefaultAppleFileSource) oracleNode.getUserObject ();
afs.setSectors (allBlocks);
}
// ---------------------------------------------------------------------------------//
private void linkBlock2 (DefaultMutableTreeNode scenarioNode, FileEntry fileEntry)
// ---------------------------------------------------------------------------------//
{
byte[] buffer = fileEntry.getDataSource ().buffer;
List<DiskAddress> blocks = fileEntry.getSectors ();
StringBuilder text = new StringBuilder ();
List<DiskAddress> allBlocks = new ArrayList<> ();
for (int i = 0; i < 19; i++)
{
allBlocks.add (blocks.get (87 + i));
}
int offset = 0xAE00;
int length = 60;
for (int i = 0; i < 150; i++)
{
text.append (String.format ("%04X : %s%n", (offset + i * length),
HexFormatter.getHexString (buffer, offset + i * length, length)));
}
DefaultMutableTreeNode oracleNode = linkNode ("Block2", text.toString (), scenarioNode);
oracleNode.setAllowsChildren (false);
DefaultAppleFileSource afs = (DefaultAppleFileSource) oracleNode.getUserObject ();
afs.setSectors (allBlocks);
}
// ---------------------------------------------------------------------------------//
private void linkOracle (DefaultMutableTreeNode scenarioNode, FileEntry fileEntry)
// ---------------------------------------------------------------------------------//
{
byte[] buffer = fileEntry.getDataSource ().buffer;
List<DiskAddress> blocks = fileEntry.getSectors ();
StringBuilder text = new StringBuilder ();
for (int i = 0; i < 320; i++)
{
// System.out.println (HexFormatter.format (buffer, 0x08600 + i * 32, 32));
int offset = 0x08600 + i * 32 + 18;
int key = Utility.getShort (buffer, offset);
if (key > 0)
text.append (
String.format ("%04X %04X * %s%n", offset, key, messageBlock.getMessageLine (key)));
key = Utility.getShort (buffer, offset + 8);
if (key > 0)
text.append (String.format ("%04X %04X %s%n", offset + 8, key,
messageBlock.getMessageLine (key)));
}
List<DiskAddress> allOracleBlocks = new ArrayList<> ();
for (int i = 0; i < 20; i++)
{
allOracleBlocks.add (blocks.get (67 + i));
}
DefaultMutableTreeNode oracleNode = linkNode ("Oracle", text.toString (), scenarioNode);
oracleNode.setAllowsChildren (false);
DefaultAppleFileSource afs = (DefaultAppleFileSource) oracleNode.getUserObject ();
afs.setSectors (allOracleBlocks);
}
// ---------------------------------------------------------------------------------//
private void addToNode (AbstractFile af, DefaultMutableTreeNode node, List<DiskAddress> blocks)
// ---------------------------------------------------------------------------------//
{
DefaultAppleFileSource dafs = new DefaultAppleFileSource (af.getName (), af, this, blocks);
DefaultMutableTreeNode childNode = new DefaultMutableTreeNode (dafs);
childNode.setAllowsChildren (false);
node.add (childNode);
}
// ---------------------------------------------------------------------------------//
private DefaultMutableTreeNode linkNode (String name, String text, DefaultMutableTreeNode parent)
// ---------------------------------------------------------------------------------//
{
DefaultAppleFileSource afs = new DefaultAppleFileSource (name, text, this);
DefaultMutableTreeNode node = new DefaultMutableTreeNode (afs);
parent.add (node);
return node;
}
// ---------------------------------------------------------------------------------//
public static boolean isWizardryIVorV (Disk disk, boolean debug)
// ---------------------------------------------------------------------------------//
{
// Wizardry IV or V boot code
byte[] header = { 0x00, (byte) 0xEA, (byte) 0xA9, 0x60, (byte) 0x8D, 0x01, 0x08 };
byte[] buffer = disk.readBlock (0);
if (!Utility.matches (buffer, 0, header))
return false;
buffer = disk.readBlock (1);
return buffer[510] == 1 && buffer[511] == 0; // disk #1
}
} | 0 | 0.948868 | 1 | 0.948868 | game-dev | MEDIA | 0.713512 | game-dev | 0.997098 | 1 | 0.997098 |
aumuell/open-inventor | 13,708 | lib/database/src/so/nodes/SoArray.c++ | /*
*
* Copyright (C) 2000 Silicon Graphics, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Further, this software is distributed without any warranty that it is
* free of the rightful claim of any third person regarding infringement
* or the like. Any license provided herein, whether implied or
* otherwise, applies only to this software file. Patent licenses, if
* any, provided herein do not apply to combinations of this program with
* other software, or any other product whatsoever.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pkwy,
* Mountain View, CA 94043, or:
*
* http://www.sgi.com
*
* For further information regarding this notice, see:
*
* http://oss.sgi.com/projects/GenInfo/NoticeExplan/
*
*/
/*
* Copyright (C) 1990,91 Silicon Graphics, Inc.
*
_______________________________________________________________________
______________ S I L I C O N G R A P H I C S I N C . ____________
|
| $Revision: 1.2 $
|
| Classes:
| SoArray
|
| Author(s) : Paul S. Strauss
|
______________ S I L I C O N G R A P H I C S I N C . ____________
_______________________________________________________________________
*/
#include <Inventor/actions/SoCallbackAction.h>
#include <Inventor/actions/SoGLRenderAction.h>
#include <Inventor/actions/SoGetBoundingBoxAction.h>
#include <Inventor/actions/SoGetMatrixAction.h>
#include <Inventor/actions/SoHandleEventAction.h>
#include <Inventor/actions/SoPickAction.h>
#include <Inventor/actions/SoSearchAction.h>
#include <Inventor/elements/SoModelMatrixElement.h>
#include <Inventor/elements/SoSwitchElement.h>
#include <Inventor/misc/SoChildList.h>
#include <Inventor/misc/SoState.h>
#include <Inventor/nodes/SoArray.h>
#include <Inventor/nodes/SoSwitch.h>
SO_NODE_SOURCE(SoArray);
////////////////////////////////////////////////////////////////////////
//
// Description:
// Constructor
//
// Use: public
SoArray::SoArray()
//
////////////////////////////////////////////////////////////////////////
{
SO_NODE_CONSTRUCTOR(SoArray);
SO_NODE_ADD_FIELD(numElements1, (1));
SO_NODE_ADD_FIELD(numElements2, (1));
SO_NODE_ADD_FIELD(numElements3, (1));
SO_NODE_ADD_FIELD(separation1, (SbVec3f(1.0, 0.0, 0.0)));
SO_NODE_ADD_FIELD(separation2, (SbVec3f(0.0, 1.0, 0.0)));
SO_NODE_ADD_FIELD(separation3, (SbVec3f(0.0, 0.0, 1.0)));
SO_NODE_ADD_FIELD(origin, (FIRST));
// Set up static info for enumerated type field
SO_NODE_DEFINE_ENUM_VALUE(Origin, FIRST);
SO_NODE_DEFINE_ENUM_VALUE(Origin, CENTER);
SO_NODE_DEFINE_ENUM_VALUE(Origin, LAST);
// Set up info in enumerated type field
SO_NODE_SET_SF_ENUM_TYPE(origin, Origin);
isBuiltIn = TRUE;
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Destructor
//
// Use: private
SoArray::~SoArray()
//
////////////////////////////////////////////////////////////////////////
{
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Overrides method in SoNode to return FALSE.
//
// Use: public
SbBool
SoArray::affectsState() const
//
////////////////////////////////////////////////////////////////////////
{
return FALSE;
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Implements typical action traversal.
//
// Use: extender
void
SoArray::doAction(SoAction *action)
//
////////////////////////////////////////////////////////////////////////
{
int numIndices;
const int *indices;
int lastChild;
int n1, n2, n3, i1, i2, i3, curIndex;
SbVec3f sepVec1, sepVec2, sepVec3;
SbBool translateArray, gettingBBox;
SbVec3f totalCenter(0,0,0); // For bbox
int numCenters = 0, i; // For bbox
// We have to do some extra stuff here for computing bboxes
gettingBBox = action->isOfType(SoGetBoundingBoxAction::getClassTypeId());
// Determine which children to traverse, if any
switch (action->getPathCode(numIndices, indices)) {
case SoAction::NO_PATH:
case SoAction::BELOW_PATH:
lastChild = getNumChildren() - 1;
break;
case SoAction::IN_PATH:
// If this node is in a path, that means the path goes to one
// of its children. There's no need to traverse this path more
// than once in this case.
lastChild = indices[numIndices - 1];
action->getState()->push();
children->traverse(action, 0, lastChild);
action->getState()->pop();
return;
case SoAction::OFF_PATH:
// This differs from SoGroup: if the array is not on the
// path, don't bother traversing its children. Effectively the
// same as a separator to the rest of the graph.
return;
}
n1 = numElements1.getValue();
n2 = numElements2.getValue();
n3 = numElements3.getValue();
translateArray = (! origin.isIgnored() && origin.getValue() != FIRST);
if (translateArray) {
SbVec3f vecToCenter = -(separation1.getValue() * (n1 - 1) +
separation2.getValue() * (n2 - 1) +
separation3.getValue() * (n3 - 1));
if (origin.getValue() == CENTER)
vecToCenter *= 0.5;
action->getState()->push();
// Use model matrix to translate the array to the correct place
SoModelMatrixElement::translateBy(action->getState(),
this, vecToCenter);
}
curIndex = 0;
sepVec3.setValue(0.0, 0.0, 0.0);
for (i3 = 0; i3 < n3; i3++) {
sepVec2 = sepVec3;
for (i2 = 0; i2 < n2; i2++) {
sepVec1 = sepVec2;
for (i1 = 0; i1 < n1; i1++) {
action->getState()->push();
// Set value in switch element to current index
SoSwitchElement::set(action->getState(), curIndex++);
// Translate element to correct place
SoModelMatrixElement::translateBy(action->getState(),
this, sepVec1);
// Set the center correctly after each child
if (gettingBBox) {
SoGetBoundingBoxAction *bba =
(SoGetBoundingBoxAction *) action;
for (i = 0; i <= lastChild; i++) {
children->traverse(action, i, i);
if (bba->isCenterSet()) {
totalCenter += bba->getCenter();
numCenters++;
bba->resetCenter();
}
}
}
else
children->traverse(action, 0, lastChild);
action->getState()->pop();
sepVec1 += separation1.getValue();
}
sepVec2 += separation2.getValue();
}
sepVec3 += separation3.getValue();
}
// Restore state if it was pushed because of centering translation
if (translateArray)
action->getState()->pop();
if (gettingBBox && numCenters > 0)
((SoGetBoundingBoxAction *) action)->setCenter(totalCenter/numCenters,
FALSE);
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Traversal for callback action.
//
// Use: extender
void
SoArray::callback(SoCallbackAction *action)
//
////////////////////////////////////////////////////////////////////////
{
SoArray::doAction(action);
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Traversal for GL rendering
//
// Use: extender
void
SoArray::GLRender(SoGLRenderAction *action)
//
////////////////////////////////////////////////////////////////////////
{
SoArray::doAction(action);
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Traversal for picking
//
// Use: extender
void
SoArray::pick(SoPickAction *action)
//
////////////////////////////////////////////////////////////////////////
{
// Disable pick culling. If it is enabled, this is what happens:
// if one of our children is a separator, we traverse it N times
// to do the pick. For each of those times, the separator (if it
// does pick culling) applies an SoGetBoundingBoxAction to the
// current path (which goes through this array). The array then
// computes the bbox of all N elements, so we get NxN behavior,
// which takes too long.
SbBool saveCullingFlag = action->isCullingEnabled();
action->enableCulling(FALSE);
SoArray::doAction(action);
action->enableCulling(saveCullingFlag);
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Traversal for get bounding box
//
// Use: extender
void
SoArray::getBoundingBox(SoGetBoundingBoxAction *action)
//
////////////////////////////////////////////////////////////////////////
{
// We can't do any tricks that assume that the extents of the
// bounding box of the array are formed by the corner elements,
// since some child may do something a little weird, such as using
// a switch to translate one element to an extreme position. We'll
// just do the standard multi-element traversal.
SoArray::doAction(action);
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Traversal for handle event
//
// Use: extender
void
SoArray::handleEvent(SoHandleEventAction *action)
//
////////////////////////////////////////////////////////////////////////
{
// Again, as in getBoundingBox(), someone could use a switch to
// determine whether to handle an event. So we need to traverse
// all of our children multiple times. But the matrix elements are
// not enabled for this action, so we don't want to do any translation.
int numIndices;
const int *indices;
int lastChild;
int n1, n2, n3, i1, i2, i3, curIndex;
// Determine which children to traverse, if any
switch (action->getPathCode(numIndices, indices)) {
case SoAction::NO_PATH:
case SoAction::BELOW_PATH:
lastChild = getNumChildren() - 1;
break;
case SoAction::IN_PATH:
lastChild = indices[numIndices - 1];
break;
case SoAction::OFF_PATH:
return;
}
n1 = numElements1.getValue();
n2 = numElements2.getValue();
n3 = numElements3.getValue();
curIndex = 0;
for (i3 = 0; i3 < n3; i3++) {
for (i2 = 0; i2 < n2; i2++) {
for (i1 = 0; i1 < n1; i1++) {
action->getState()->push();
SoSwitchElement::set(action->getState(), curIndex++);
children->traverse(action, 0, lastChild);
action->getState()->pop();
}
}
}
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Implements getMatrix action.
//
// Use: extender
void
SoArray::getMatrix(SoGetMatrixAction *action)
//
////////////////////////////////////////////////////////////////////////
{
int numIndices;
const int *indices;
// Only need to compute matrix if array is a node in middle of
// current path chain. We don't need to push or pop the state,
// since this shouldn't have any effect on other nodes being
// traversed.
if (action->getPathCode(numIndices, indices) == SoAction::IN_PATH) {
// Translate entire array if necessary
if (! origin.isIgnored() && origin.getValue() != FIRST) {
int n1 = numElements1.getValue();
int n2 = numElements2.getValue();
int n3 = numElements3.getValue();
SbVec3f vecToCenter = -(separation1.getValue() * (n1 - 1) +
separation2.getValue() * (n2 - 1) +
separation3.getValue() * (n3 - 1));
if (origin.getValue() == CENTER)
vecToCenter *= 0.5;
// Translate the matrices in the action
SbMatrix m;
m.setTranslate(vecToCenter);
action->getMatrix().multLeft(m);
m.setTranslate(-vecToCenter);
action->getInverse().multRight(m);
}
children->traverse(action, 0, indices[numIndices - 1]);
}
}
////////////////////////////////////////////////////////////////////////
//
// Description:
// Implements search action. If we are not searching all the
// children we have to set the switch element correctly in case any
// child contains a switch node that inherits the switch value. The
// best approximation we can make here is to set it to traverse all
// children. This is preferable to missing children.
//
// Use: extender
void
SoArray::search(SoSearchAction *action)
//
////////////////////////////////////////////////////////////////////////
{
int numIndices;
const int *indices;
int lastChild;
// First see if the caller is searching for this node
SoNode::search(action);
if (action->isFound())
return;
// See if we're supposed to search only if the stuff under the
// array is relevant to the search path
switch (action->getPathCode(numIndices, indices)) {
case SoAction::NO_PATH:
case SoAction::BELOW_PATH:
lastChild = getNumChildren() - 1;
break;
case SoAction::IN_PATH:
lastChild = indices[numIndices - 1];
break;
case SoAction::OFF_PATH:
if (! action->isSearchingAll())
return;
lastChild = getNumChildren() - 1;
break;
}
action->getState()->push();
// Set value in switch element to traverse all children
SoSwitchElement::set(action->getState(), SO_SWITCH_ALL);
children->traverse(action, 0, lastChild);
action->getState()->pop();
}
| 0 | 0.853193 | 1 | 0.853193 | game-dev | MEDIA | 0.613858 | game-dev | 0.859742 | 1 | 0.859742 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.