Dataset Viewer
Auto-converted to Parquet Duplicate
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
End of preview. Expand in Data Studio

No dataset card yet

Downloads last month
11