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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Ardour/ardour | 17,648 | libs/tk/ztkmm/action.cc | // Generated by gtkmmproc -- DO NOT MODIFY!
#include <glibmm.h>
#include <ztkmm/action.h>
#include <ztkmm/private/action_p.h>
// -*- c++ -*-
/* $Id: action.ccg,v 1.1 2003/01/21 13:36:56 murrayc Exp $ */
/* Copyright 1998-2002 The gtkmm Development Team
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free
* Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <ztk/atkaction.h>
namespace
{
} // anonymous namespace
namespace Glib
{
Glib::RefPtr<Atk::Action> wrap(AtkAction* object, bool take_copy)
{
return Glib::RefPtr<Atk::Action>( dynamic_cast<Atk::Action*> (Glib::wrap_auto_interface<Atk::Action> ((GObject*)(object), take_copy)) );
//We use dynamic_cast<> in case of multiple inheritance.
}
} // namespace Glib
namespace Atk
{
/* The *_Class implementation: */
const Glib::Interface_Class& Action_Class::init()
{
if(!gtype_) // create the GType if necessary
{
// Glib::Interface_Class has to know the interface init function
// in order to add interfaces to implementing types.
class_init_func_ = &Action_Class::iface_init_function;
// We can not derive from another interface, and it is not necessary anyway.
gtype_ = atk_action_get_type();
}
return *this;
}
void Action_Class::iface_init_function(void* g_iface, void*)
{
BaseClassType *const klass = static_cast<BaseClassType*>(g_iface);
//This is just to avoid an "unused variable" warning when there are no vfuncs or signal handlers to connect.
//This is a temporary fix until I find out why I can not seem to derive a GtkFileChooser interface. murrayc
g_assert(klass != 0);
klass->do_action = &do_action_vfunc_callback;
klass->get_n_actions = &get_n_actions_vfunc_callback;
klass->get_description = &get_description_vfunc_callback;
klass->get_name = &get_name_vfunc_callback;
klass->get_keybinding = &get_keybinding_vfunc_callback;
klass->set_description = &set_description_vfunc_callback;
}
gboolean Action_Class::do_action_vfunc_callback(AtkAction* self, gint i)
{
Glib::ObjectBase *const obj_base = static_cast<Glib::ObjectBase*>(
Glib::ObjectBase::_get_current_wrapper((GObject*)self));
// Non-gtkmmproc-generated custom classes implicitly call the default
// Glib::ObjectBase constructor, which sets is_derived_. But gtkmmproc-
// generated classes can use this optimisation, which avoids the unnecessary
// parameter conversions if there is no possibility of the virtual function
// being overridden:
if(obj_base && obj_base->is_derived_())
{
CppObjectType *const obj = dynamic_cast<CppObjectType* const>(obj_base);
if(obj) // This can be NULL during destruction.
{
#ifdef GLIBMM_EXCEPTIONS_ENABLED
try // Trap C++ exceptions which would normally be lost because this is a C callback.
{
#endif //GLIBMM_EXCEPTIONS_ENABLED
// Call the virtual member method, which derived classes might override.
return static_cast<int>(obj->do_action_vfunc(i
));
#ifdef GLIBMM_EXCEPTIONS_ENABLED
}
catch(...)
{
Glib::exception_handlers_invoke();
}
#endif //GLIBMM_EXCEPTIONS_ENABLED
}
}
BaseClassType *const base = static_cast<BaseClassType*>(
g_type_interface_peek_parent( // Get the parent interface of the interface (The original underlying C interface).
g_type_interface_peek(G_OBJECT_GET_CLASS(self), CppObjectType::get_type()) // Get the interface.
) );
// Call the original underlying C function:
if(base && base->do_action)
{
gboolean retval = (*base->do_action)(self, i);
return retval;
}
typedef gboolean RType;
return RType();
}
gint Action_Class::get_n_actions_vfunc_callback(AtkAction* self)
{
Glib::ObjectBase *const obj_base = static_cast<Glib::ObjectBase*>(
Glib::ObjectBase::_get_current_wrapper((GObject*)self));
// Non-gtkmmproc-generated custom classes implicitly call the default
// Glib::ObjectBase constructor, which sets is_derived_. But gtkmmproc-
// generated classes can use this optimisation, which avoids the unnecessary
// parameter conversions if there is no possibility of the virtual function
// being overridden:
if(obj_base && obj_base->is_derived_())
{
CppObjectType *const obj = dynamic_cast<CppObjectType* const>(obj_base);
if(obj) // This can be NULL during destruction.
{
#ifdef GLIBMM_EXCEPTIONS_ENABLED
try // Trap C++ exceptions which would normally be lost because this is a C callback.
{
#endif //GLIBMM_EXCEPTIONS_ENABLED
// Call the virtual member method, which derived classes might override.
return obj->get_n_actions_vfunc();
#ifdef GLIBMM_EXCEPTIONS_ENABLED
}
catch(...)
{
Glib::exception_handlers_invoke();
}
#endif //GLIBMM_EXCEPTIONS_ENABLED
}
}
BaseClassType *const base = static_cast<BaseClassType*>(
g_type_interface_peek_parent( // Get the parent interface of the interface (The original underlying C interface).
g_type_interface_peek(G_OBJECT_GET_CLASS(self), CppObjectType::get_type()) // Get the interface.
) );
// Call the original underlying C function:
if(base && base->get_n_actions)
{
gint retval = (*base->get_n_actions)(self);
return retval;
}
typedef gint RType;
return RType();
}
const gchar* Action_Class::get_description_vfunc_callback(AtkAction* self, gint i)
{
Glib::ObjectBase *const obj_base = static_cast<Glib::ObjectBase*>(
Glib::ObjectBase::_get_current_wrapper((GObject*)self));
// Non-gtkmmproc-generated custom classes implicitly call the default
// Glib::ObjectBase constructor, which sets is_derived_. But gtkmmproc-
// generated classes can use this optimisation, which avoids the unnecessary
// parameter conversions if there is no possibility of the virtual function
// being overridden:
if(obj_base && obj_base->is_derived_())
{
CppObjectType *const obj = dynamic_cast<CppObjectType* const>(obj_base);
if(obj) // This can be NULL during destruction.
{
#ifdef GLIBMM_EXCEPTIONS_ENABLED
try // Trap C++ exceptions which would normally be lost because this is a C callback.
{
#endif //GLIBMM_EXCEPTIONS_ENABLED
// Call the virtual member method, which derived classes might override.
return obj->get_description_vfunc(i
);
#ifdef GLIBMM_EXCEPTIONS_ENABLED
}
catch(...)
{
Glib::exception_handlers_invoke();
}
#endif //GLIBMM_EXCEPTIONS_ENABLED
}
}
BaseClassType *const base = static_cast<BaseClassType*>(
g_type_interface_peek_parent( // Get the parent interface of the interface (The original underlying C interface).
g_type_interface_peek(G_OBJECT_GET_CLASS(self), CppObjectType::get_type()) // Get the interface.
) );
// Call the original underlying C function:
if(base && base->get_description)
{
const gchar* retval = (*base->get_description)(self, i);
return retval;
}
typedef const gchar* RType;
return RType();
}
const gchar* Action_Class::get_name_vfunc_callback(AtkAction* self, gint i)
{
Glib::ObjectBase *const obj_base = static_cast<Glib::ObjectBase*>(
Glib::ObjectBase::_get_current_wrapper((GObject*)self));
// Non-gtkmmproc-generated custom classes implicitly call the default
// Glib::ObjectBase constructor, which sets is_derived_. But gtkmmproc-
// generated classes can use this optimisation, which avoids the unnecessary
// parameter conversions if there is no possibility of the virtual function
// being overridden:
if(obj_base && obj_base->is_derived_())
{
CppObjectType *const obj = dynamic_cast<CppObjectType* const>(obj_base);
if(obj) // This can be NULL during destruction.
{
#ifdef GLIBMM_EXCEPTIONS_ENABLED
try // Trap C++ exceptions which would normally be lost because this is a C callback.
{
#endif //GLIBMM_EXCEPTIONS_ENABLED
// Call the virtual member method, which derived classes might override.
return obj->get_name_vfunc(i
);
#ifdef GLIBMM_EXCEPTIONS_ENABLED
}
catch(...)
{
Glib::exception_handlers_invoke();
}
#endif //GLIBMM_EXCEPTIONS_ENABLED
}
}
BaseClassType *const base = static_cast<BaseClassType*>(
g_type_interface_peek_parent( // Get the parent interface of the interface (The original underlying C interface).
g_type_interface_peek(G_OBJECT_GET_CLASS(self), CppObjectType::get_type()) // Get the interface.
) );
// Call the original underlying C function:
if(base && base->get_name)
{
const gchar* retval = (*base->get_name)(self, i);
return retval;
}
typedef const gchar* RType;
return RType();
}
const gchar* Action_Class::get_keybinding_vfunc_callback(AtkAction* self, gint i)
{
Glib::ObjectBase *const obj_base = static_cast<Glib::ObjectBase*>(
Glib::ObjectBase::_get_current_wrapper((GObject*)self));
// Non-gtkmmproc-generated custom classes implicitly call the default
// Glib::ObjectBase constructor, which sets is_derived_. But gtkmmproc-
// generated classes can use this optimisation, which avoids the unnecessary
// parameter conversions if there is no possibility of the virtual function
// being overridden:
if(obj_base && obj_base->is_derived_())
{
CppObjectType *const obj = dynamic_cast<CppObjectType* const>(obj_base);
if(obj) // This can be NULL during destruction.
{
#ifdef GLIBMM_EXCEPTIONS_ENABLED
try // Trap C++ exceptions which would normally be lost because this is a C callback.
{
#endif //GLIBMM_EXCEPTIONS_ENABLED
// Call the virtual member method, which derived classes might override.
return obj->get_keybinding_vfunc(i
);
#ifdef GLIBMM_EXCEPTIONS_ENABLED
}
catch(...)
{
Glib::exception_handlers_invoke();
}
#endif //GLIBMM_EXCEPTIONS_ENABLED
}
}
BaseClassType *const base = static_cast<BaseClassType*>(
g_type_interface_peek_parent( // Get the parent interface of the interface (The original underlying C interface).
g_type_interface_peek(G_OBJECT_GET_CLASS(self), CppObjectType::get_type()) // Get the interface.
) );
// Call the original underlying C function:
if(base && base->get_keybinding)
{
const gchar* retval = (*base->get_keybinding)(self, i);
return retval;
}
typedef const gchar* RType;
return RType();
}
gboolean Action_Class::set_description_vfunc_callback(AtkAction* self, gint i, const gchar* desc)
{
Glib::ObjectBase *const obj_base = static_cast<Glib::ObjectBase*>(
Glib::ObjectBase::_get_current_wrapper((GObject*)self));
// Non-gtkmmproc-generated custom classes implicitly call the default
// Glib::ObjectBase constructor, which sets is_derived_. But gtkmmproc-
// generated classes can use this optimisation, which avoids the unnecessary
// parameter conversions if there is no possibility of the virtual function
// being overridden:
if(obj_base && obj_base->is_derived_())
{
CppObjectType *const obj = dynamic_cast<CppObjectType* const>(obj_base);
if(obj) // This can be NULL during destruction.
{
#ifdef GLIBMM_EXCEPTIONS_ENABLED
try // Trap C++ exceptions which would normally be lost because this is a C callback.
{
#endif //GLIBMM_EXCEPTIONS_ENABLED
// Call the virtual member method, which derived classes might override.
return static_cast<int>(obj->set_description_vfunc(i
, Glib::convert_const_gchar_ptr_to_ustring(desc)
));
#ifdef GLIBMM_EXCEPTIONS_ENABLED
}
catch(...)
{
Glib::exception_handlers_invoke();
}
#endif //GLIBMM_EXCEPTIONS_ENABLED
}
}
BaseClassType *const base = static_cast<BaseClassType*>(
g_type_interface_peek_parent( // Get the parent interface of the interface (The original underlying C interface).
g_type_interface_peek(G_OBJECT_GET_CLASS(self), CppObjectType::get_type()) // Get the interface.
) );
// Call the original underlying C function:
if(base && base->set_description)
{
gboolean retval = (*base->set_description)(self, i, desc);
return retval;
}
typedef gboolean RType;
return RType();
}
Glib::ObjectBase* Action_Class::wrap_new(GObject* object)
{
return new Action((AtkAction*)(object));
}
/* The implementation: */
Action::Action()
:
Glib::Interface(action_class_.init())
{}
Action::Action(AtkAction* castitem)
:
Glib::Interface((GObject*)(castitem))
{}
Action::Action(const Glib::Interface_Class& interface_class)
: Glib::Interface(interface_class)
{
}
Action::~Action()
{}
// static
void Action::add_interface(GType gtype_implementer)
{
action_class_.init().add_interface(gtype_implementer);
}
Action::CppClassType Action::action_class_; // initialize static member
GType Action::get_type()
{
return action_class_.init().get_type();
}
GType Action::get_base_type()
{
return atk_action_get_type();
}
bool Action::do_action(int i)
{
return atk_action_do_action(gobj(), i);
}
int Action::get_n_actions() const
{
return atk_action_get_n_actions(const_cast<AtkAction*>(gobj()));
}
Glib::ustring Action::get_description(int i) const
{
return Glib::convert_const_gchar_ptr_to_ustring(atk_action_get_description(const_cast<AtkAction*>(gobj()), i));
}
Glib::ustring Action::get_name(int i) const
{
return Glib::convert_const_gchar_ptr_to_ustring(atk_action_get_name(const_cast<AtkAction*>(gobj()), i));
}
Glib::ustring Action::get_keybinding(int i)
{
return Glib::convert_const_gchar_ptr_to_ustring(atk_action_get_keybinding(gobj(), i));
}
bool Action::set_description(int i, const Glib::ustring& desc)
{
return atk_action_set_description(gobj(), i, desc.c_str());
}
Glib::ustring Action::get_localized_name(int i)
{
return Glib::convert_const_gchar_ptr_to_ustring(atk_action_get_localized_name(gobj(), i));
}
bool Atk::Action::do_action_vfunc(int i)
{
BaseClassType *const base = static_cast<BaseClassType*>(
g_type_interface_peek_parent( // Get the parent interface of the interface (The original underlying C interface).
g_type_interface_peek(G_OBJECT_GET_CLASS(gobject_), CppObjectType::get_type()) // Get the interface.
) );
if(base && base->do_action)
{
bool retval((*base->do_action)(gobj(),i));
return retval;
}
typedef bool RType;
return RType();
}
int Atk::Action::get_n_actions_vfunc() const
{
BaseClassType *const base = static_cast<BaseClassType*>(
g_type_interface_peek_parent( // Get the parent interface of the interface (The original underlying C interface).
g_type_interface_peek(G_OBJECT_GET_CLASS(gobject_), CppObjectType::get_type()) // Get the interface.
) );
if(base && base->get_n_actions)
{
int retval((*base->get_n_actions)(const_cast<AtkAction*>(gobj())));
return retval;
}
typedef int RType;
return RType();
}
const char* Atk::Action::get_description_vfunc(int i) const
{
BaseClassType *const base = static_cast<BaseClassType*>(
g_type_interface_peek_parent( // Get the parent interface of the interface (The original underlying C interface).
g_type_interface_peek(G_OBJECT_GET_CLASS(gobject_), CppObjectType::get_type()) // Get the interface.
) );
if(base && base->get_description)
{
const char* retval((*base->get_description)(const_cast<AtkAction*>(gobj()),i));
return retval;
}
typedef const char* RType;
return RType();
}
const char* Atk::Action::get_name_vfunc(int i) const
{
BaseClassType *const base = static_cast<BaseClassType*>(
g_type_interface_peek_parent( // Get the parent interface of the interface (The original underlying C interface).
g_type_interface_peek(G_OBJECT_GET_CLASS(gobject_), CppObjectType::get_type()) // Get the interface.
) );
if(base && base->get_name)
{
const char* retval((*base->get_name)(const_cast<AtkAction*>(gobj()),i));
return retval;
}
typedef const char* RType;
return RType();
}
const char* Atk::Action::get_keybinding_vfunc(int i) const
{
BaseClassType *const base = static_cast<BaseClassType*>(
g_type_interface_peek_parent( // Get the parent interface of the interface (The original underlying C interface).
g_type_interface_peek(G_OBJECT_GET_CLASS(gobject_), CppObjectType::get_type()) // Get the interface.
) );
if(base && base->get_keybinding)
{
const char* retval((*base->get_keybinding)(const_cast<AtkAction*>(gobj()),i));
return retval;
}
typedef const char* RType;
return RType();
}
bool Atk::Action::set_description_vfunc(int i, const Glib::ustring& desc)
{
BaseClassType *const base = static_cast<BaseClassType*>(
g_type_interface_peek_parent( // Get the parent interface of the interface (The original underlying C interface).
g_type_interface_peek(G_OBJECT_GET_CLASS(gobject_), CppObjectType::get_type()) // Get the interface.
) );
if(base && base->set_description)
{
bool retval((*base->set_description)(gobj(),i,desc.c_str()));
return retval;
}
typedef bool RType;
return RType();
}
} // namespace Atk
| 412 | 0.93833 | 1 | 0.93833 | game-dev | MEDIA | 0.516674 | game-dev | 0.87818 | 1 | 0.87818 |
mir-ethernity/mir-eternal | 1,242 | GameServer/GMCommands/DeductIngots.cs | using System;
using GameServer.Data;
using GameServer.Networking;
namespace GameServer
{
public sealed class DeductIngots : GMCommand
{
public override ExecutionWay ExecutionWay
{
get
{
return ExecutionWay.优先后台执行;
}
}
public override void Execute()
{
GameData GameData;
if (GameDataGateway.CharacterDataTable.Keyword.TryGetValue(this.CharName, out GameData))
{
CharacterData CharacterData = GameData as CharacterData;
if (CharacterData != null)
{
CharacterData.Ingots = Math.Max(0, CharacterData.Ingots - this.Ingots);
SConnection 网络连接 = CharacterData.ActiveConnection;
if (网络连接 != null)
{
网络连接.SendPacket(new 同步Ingots
{
Ingots = CharacterData.Ingots
});
}
MainForm.AddCommandLog(string.Format("<= @{0} command has been executed, with the current amount of treasure: {1}", base.GetType().Name, CharacterData.Ingots));
return;
}
}
MainForm.AddCommandLog("<= @" + base.GetType().Name + " Command execution failed, role does not exist");
}
public DeductIngots()
{
}
[FieldAttribute(0, Position = 0)]
public string CharName;
[FieldAttribute(0, Position = 1)]
public int Ingots;
}
}
| 412 | 0.844774 | 1 | 0.844774 | game-dev | MEDIA | 0.839089 | game-dev | 0.890074 | 1 | 0.890074 |
micdoodle8/Galacticraft | 3,959 | src/main/java/micdoodle8/mods/galacticraft/planets/venus/world/gen/dungeon/MapGenDungeonVenus.java | package micdoodle8.mods.galacticraft.planets.venus.world.gen.dungeon;
import micdoodle8.mods.galacticraft.api.world.IGalacticraftWorldProvider;
import micdoodle8.mods.galacticraft.core.world.gen.dungeon.MapGenDungeon;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraft.world.gen.structure.MapGenStructure;
import net.minecraft.world.gen.structure.MapGenStructureIO;
import net.minecraft.world.gen.structure.StructureComponent;
import net.minecraft.world.gen.structure.StructureStart;
import java.util.List;
import java.util.Random;
public class MapGenDungeonVenus extends MapGenStructure
{
private static boolean initialized;
private DungeonConfigurationVenus configuration;
static
{
try
{
MapGenDungeonVenus.initiateStructures();
}
catch (Throwable e)
{
}
}
public MapGenDungeonVenus(DungeonConfigurationVenus configuration)
{
this.configuration = configuration;
}
public static void initiateStructures() throws Throwable
{
if (!MapGenDungeonVenus.initialized)
{
MapGenStructureIO.registerStructure(MapGenDungeonVenus.Start.class, "VenusDungeon");
MapGenStructureIO.registerStructureComponent(DungeonStartVenus.class, "VenusDungeonStart");
MapGenStructureIO.registerStructureComponent(CorridorVenus.class, "VenusDungeonCorridor");
MapGenStructureIO.registerStructureComponent(RoomEmptyVenus.class, "VenusDungeonEmptyRoom");
MapGenStructureIO.registerStructureComponent(RoomBossVenus.class, "VenusDungeonBossRoom");
MapGenStructureIO.registerStructureComponent(RoomTreasureVenus.class, "VenusDungeonTreasureRoom");
MapGenStructureIO.registerStructureComponent(RoomSpawnerVenus.class, "VenusDungeonSpawnerRoom");
MapGenStructureIO.registerStructureComponent(RoomChestVenus.class, "VenusDungeonChestRoom");
MapGenStructureIO.registerStructureComponent(RoomEntranceVenus.class, "VenusDungeonEntranceRoom");
}
MapGenDungeonVenus.initialized = true;
}
@Override
public String getStructureName()
{
return "GC_Dungeon_Venus";
}
@Override
protected boolean canSpawnStructureAtCoords(int chunkX, int chunkZ)
{
long dungeonPos = MapGenDungeon.getDungeonPosForCoords(this.world, chunkX, chunkZ, ((IGalacticraftWorldProvider) this.world.provider).getDungeonSpacing());
int i = (int) (dungeonPos >> 32);
int j = (int) dungeonPos;
return i == chunkX && j == chunkZ;
}
@Override
protected StructureStart getStructureStart(int chunkX, int chunkZ)
{
return new MapGenDungeonVenus.Start(this.world, this.rand, chunkX, chunkZ, this.configuration);
}
@Override
public BlockPos getNearestStructurePos(World worldIn, BlockPos pos, boolean p_180706_3_)
{
return null;
}
public static class Start extends StructureStart
{
private DungeonConfigurationVenus configuration;
public Start()
{
}
public Start(World worldIn, Random rand, int chunkX, int chunkZ, DungeonConfigurationVenus configuration)
{
super(chunkX, chunkZ);
this.configuration = configuration;
DungeonStartVenus startPiece = new DungeonStartVenus(worldIn, configuration, rand, (chunkX << 4) + 2, (chunkZ << 4) + 2);
startPiece.buildComponent(startPiece, this.components, rand);
List<StructureComponent> list = startPiece.attachedComponents;
while (!list.isEmpty())
{
int i = rand.nextInt(list.size());
StructureComponent structurecomponent = list.remove(i);
structurecomponent.buildComponent(startPiece, this.components, rand);
}
this.updateBoundingBox();
}
}
}
| 412 | 0.631858 | 1 | 0.631858 | game-dev | MEDIA | 0.954792 | game-dev | 0.81669 | 1 | 0.81669 |
FTBTeam/FTB-Chunks | 1,533 | common/src/main/java/dev/ftb/mods/ftbchunks/client/minimap/components/BiomeComponent.java | package dev.ftb.mods.ftbchunks.client.minimap.components;
import dev.ftb.mods.ftbchunks.api.FTBChunksAPI;
import dev.ftb.mods.ftbchunks.api.client.minimap.MinimapContext;
import dev.ftb.mods.ftbchunks.api.client.minimap.MinimapInfoComponent;
import dev.ftb.mods.ftbchunks.client.FTBChunksClientConfig;
import dev.ftb.mods.ftblibrary.snbt.config.BooleanValue;
import net.minecraft.client.gui.Font;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.core.Holder;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.level.biome.Biome;
public class BiomeComponent implements MinimapInfoComponent {
public static final ResourceLocation ID = FTBChunksAPI.rl("biome");
private ResourceKey<Biome> biomeKey;
@Override
public ResourceLocation id() {
return ID;
}
@Override
public void render(MinimapContext context, GuiGraphics graphics, Font font) {
drawCenteredText(context.minecraft().font, graphics, Component.translatable("biome." + biomeKey.location().getNamespace() + "." + biomeKey.location().getPath()), 0);
}
@Override
public boolean shouldRender(MinimapContext context) {
Holder<Biome> biome = context.minecraft().level.getBiome(context.minecraft().player.blockPosition());
if (biome.unwrapKey().isPresent()) {
biomeKey = biome.unwrapKey().get();
return true;
}
return false;
}
}
| 412 | 0.817147 | 1 | 0.817147 | game-dev | MEDIA | 0.924496 | game-dev | 0.718453 | 1 | 0.718453 |
Golle/TitanV2 | 1,769 | src/Titan.Generators/Assets/AssetLoaderGenerator.cs | using Microsoft.CodeAnalysis;
using System.Collections.Immutable;
namespace Titan.Generators.Assets;
internal struct AssetLoaderType(INamedTypeSymbol loaderSymbol, INamedTypeSymbol assetSymbol)
{
public INamedTypeSymbol LoaderSymbol = loaderSymbol;
public INamedTypeSymbol AssetSymbol = assetSymbol;
}
[Generator]
public class AssetLoaderGenerator : IIncrementalGenerator
{
public void Initialize(IncrementalGeneratorInitializationContext context)
{
var structDeclarations = context.SyntaxProvider.ForAttributeWithMetadataName(
TitanTypes.AssetLoaderAttributeMetadataName,
static (node, _) => node.IsPartial() && node.IsStruct(),
static (syntaxContext, _) =>
{
var loaderType = (INamedTypeSymbol)syntaxContext.TargetSymbol;
var assetType = loaderType
.GetAttributes()
.First()
.AttributeClass!
.TypeArguments
.OfType<INamedTypeSymbol>()
.Single();
return new AssetLoaderType(loaderType, assetType);
})
;
var assetLoaderProvider = structDeclarations
.Collect()
;
context
.RegisterImplementationSourceOutput(assetLoaderProvider, static (productionContext, source) => Execute(source, productionContext));
static void Execute(ImmutableArray<AssetLoaderType> loaders, SourceProductionContext context)
{
foreach (var loader in loaders)
{
var source = AssetLoaderBuilder.Build(loader);
context.AddSource($"{loader.LoaderSymbol.Name}.g.cs", source);
}
}
}
}
| 412 | 0.893137 | 1 | 0.893137 | game-dev | MEDIA | 0.770674 | game-dev | 0.915024 | 1 | 0.915024 |
EvEmu-Project/evemu_Crucible | 9,355 | src/eve-server/manufacturing/Blueprint.h | /*
------------------------------------------------------------------------------------
LICENSE:
------------------------------------------------------------------------------------
This file is part of EVEmu: EVE Online Server Emulator
Copyright 2006 - 2021 The EVEmu Team
For the latest information visit https://evemu.dev
------------------------------------------------------------------------------------
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA, or go to
http://www.gnu.org/copyleft/lesser.txt.
------------------------------------------------------------------------------------
Author: Bloody.Rabbit
Updates: Allan
*/
#ifndef __BLUEPRINT_ITEM__H__INCL__
#define __BLUEPRINT_ITEM__H__INCL__
#include "EVEServerConfig.h"
#include "StaticDataMgr.h"
#include "inventory/ItemType.h"
#include "inventory/InventoryItem.h"
#include "manufacturing/FactoryDB.h"
/*
* Class which contains blueprint type data.
*/
class BlueprintType
: public ItemType
{
friend class ItemType; // To let our parent redirect construction to our _Load().
public:
static BlueprintType* Load(uint16 typeID);
/* Access functions */
const BlueprintType* parentBlueprintType() const { return m_parentBlueprintType; }
const ItemType& productType() const { return m_productType; }
uint8 techLevel() const { return m_data.techLevel; }
uint16 wasteFactor() const { return m_data.wasteFactor; }
uint16 productTypeID() const { return productType().id(); }
uint32 productionTime() const { return m_data.productionTime; }
uint32 researchCopyTime() const { return m_data.researchCopyTime; }
uint32 researchTechTime() const { return m_data.researchTechTime; }
uint32 materialModifier() const { return m_data.materialModifier; }
uint32 maxProductionLimit() const { return m_data.maxProductionLimit; }
uint32 researchMaterialTime() const { return m_data.researchMaterialTime; }
uint32 productivityModifier() const { return m_data.productivityModifier; }
uint32 researchProductivityTime() const { return m_data.researchProductivityTime; }
uint16 parentBlueprintTypeID() const { return (m_parentBlueprintType == nullptr ? 0 : parentBlueprintType()->id()); }
float chanceOfRE() const { return m_data.chanceOfRE; }
protected:
BlueprintType(uint16 _id, const Inv::TypeData& _data,
const BlueprintType *_parentBlueprintType, const ItemType& _productType,
const EvERam::bpTypeData& _tData);
/*
* Member functions
*/
using ItemType::_Load;
// Template loader:
template<class _Ty>
static _Ty *_LoadType(uint16 typeID, const Inv::TypeData& data) {
// check if we are really loading a blueprint
Inv::GrpData gdata = Inv::GrpData();
sDataMgr.GetGroup(data.groupID, gdata);
if (gdata.catID != EVEDB::invCategories::Blueprint ) {
_log( ITEM__ERROR, "Trying to load %s as BlueprintType.", sDataMgr.GetCategoryName(gdata.catID));
return nullptr;
}
// get blueprint type data
EvERam::bpTypeData tData = EvERam::bpTypeData();
sDataMgr.GetBpTypeData(typeID, tData);
// obtain parent blueprint type (might be NULL)
const BlueprintType* parentBlueprintType(nullptr);
if (tData.parentBlueprintTypeID) {
parentBlueprintType = sItemFactory.GetBlueprintType( tData.parentBlueprintTypeID );
if (parentBlueprintType == nullptr)
return nullptr;
}
// obtain product type
const ItemType* productType = sItemFactory.GetType( tData.productTypeID );
if (productType == nullptr)
return nullptr;
return new BlueprintType(typeID, data, parentBlueprintType, *productType, tData);
}
/*
* Data members
*/
const BlueprintType *m_parentBlueprintType;
const ItemType& m_productType;
EvERam::bpTypeData m_data;
};
class Blueprint
: public InventoryItem
{
friend class InventoryItem; // to let it construct us
public:
/* virtual functions default to base class and overridden as needed */
virtual void Delete(); //remove the item from the DB.
// overload to merge the blueprints properly
virtual bool Merge(InventoryItemRef to_merge, uint32 qty=0, bool notify=true);
// overload to split the blueprints properly
virtual InventoryItemRef Split(int32 qty_to_take, bool notify=true)
{ return SplitBlueprint( qty_to_take, notify ); }
BlueprintRef SplitBlueprint(int32 qty_to_take, bool notify=true);
static BlueprintRef Load( uint32 blueprintID);
static BlueprintRef Spawn( ItemData& data, EvERam::bpData& bdata);
// query methods
const BlueprintType& type() const { return m_bpType; }
const ItemType& productType() const { return m_bpType.productType(); }
uint32 productTypeID() const { return m_bpType.productTypeID(); }
bool copy() { return m_data.copy; }
int8 mLevel() { return m_data.mLevel; }
int8 pLevel() { return m_data.pLevel; }
int16 runs() { return m_data.runs; }
float GetPE() { return m_data.pLevel / (1 + m_data.pLevel); }
float GetME();
// set methods
void SetMLevel(int8 me) { m_data.mLevel = me; SaveBlueprint(); }
void SetPLevel(int8 pe) { m_data.pLevel = pe; SaveBlueprint(); }
void SetCopy(bool copy) { m_data.copy = copy; SaveBlueprint(); }
void SetRuns(int16 runs) { m_data.runs = runs; SaveBlueprint(); }
// update methods
void UpdateMLevel(int8 me) { m_data.mLevel += me; SaveBlueprint(); }
void UpdatePLevel(int8 pe) { m_data.pLevel += pe; SaveBlueprint(); }
void UpdateRuns(int16 runs) { m_data.runs += runs; SaveBlueprint(); }
// is this used? should it be?
bool infinite() { return (m_data.runs < 0); }
/*
* Primary public packet builders:
*/
PyDict* GetBlueprintAttributes();
protected:
Blueprint( uint32 _blueprintID, const BlueprintType& _bpType, const ItemData& _data, EvERam::bpData& _bpData);
/*
* Member functions
*/
using InventoryItem::_Load;
// Template loader:
template<class _Ty>
static RefPtr<_Ty> _LoadItem( uint32 blueprintID, const ItemType& type, const ItemData& data)
{
if (type.categoryID() != EVEDB::invCategories::Blueprint) {
_log(ITEM__ERROR, "Trying to load %s as Blueprint.", sDataMgr.GetCategoryName(type.categoryID()));
if (sConfig.debug.StackTrace)
EvE::traceStack();
return RefPtr<_Ty>(nullptr);
}
const BlueprintType& bpType = static_cast<const BlueprintType& >( type );
EvERam::bpData bdata = EvERam::bpData();
if (!FactoryDB::GetBlueprintData( blueprintID, bdata ) )
return RefPtr<_Ty>(nullptr);
return BlueprintRef( new Blueprint( blueprintID, bpType, data, bdata ) );
}
void SaveBlueprint();
static uint32 CreateItemID( ItemData& data, EvERam::bpData& bdata);
private:
const BlueprintType &m_bpType;
EvERam::bpData m_data;
};
#endif /* !__BLUEPRINT_ITEM__H__INCL__ */
/** misc data
*
* only packaged BPO sold on market
* unpacked bpo or any bpc by contract or trade
*
* bpc "packs" are every bpc to make the item (usually large items)
*
*
* research bpo (~month of research for each ME/PE at base ccp times)
* modules/ammo - ME 50 PE 20
* ships/components - ME 10 PE 10
* carrier/big ship ME 2 PE 1
*
* max run copies for type
* 300 modules, weapons
* 1500 drones, ammo
* 1 all others
*
* for invention, t1 bpc PE and ME are irrelevant
* if type is not ship or rig and runs < 10
* runs output = runs input
* else
* runs = max (10 on t2 bpc)
*
*
*
*
*
*/ | 412 | 0.89311 | 1 | 0.89311 | game-dev | MEDIA | 0.413728 | game-dev | 0.877414 | 1 | 0.877414 |
amov-lab/Prometheus | 3,399 | Modules/simulator_utils/include/map_generator.h | #ifndef MAP_GENERATOR_H
#define MAP_GENERATOR_H
#include <ros/ros.h>
#include <ros/console.h>
#include <math.h>
#include <iostream>
#include <Eigen/Eigen>
#include <random>
#include <tf/transform_broadcaster.h>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/kdtree/kdtree_flann.h>
#include <pcl_conversions/pcl_conversions.h>
#include <geometry_msgs/PoseStamped.h>
#include <geometry_msgs/Vector3.h>
#include <nav_msgs/Odometry.h>
#include <sensor_msgs/PointCloud2.h>
#include "printf_utils.h"
using namespace std;
using namespace Eigen;
#define MAX_SWRAM_NUM 41
// 节点功能:生成地图,并模拟无人机检测,模拟得到局部地图与全局地图
class Map_Generator
{
public:
Map_Generator(){};
void init(ros::NodeHandle &nh);
int swarm_num; // 集群数量
int uav_id[MAX_SWRAM_NUM]; // 编号
double map_size_x, map_size_y, map_size_z; // 地图尺寸
double map_x_min, map_x_max, map_y_min, map_y_max; // 地图xy范围
double map_z_limit;
double map_resolution; // 地图分辨率
double sensing_range, sensing_rate; // 传感器感知半径与频率
double sensing_horizon;
double obs_min_dist; // 障碍物最小间距
int large_cylinder_num, small_cylinder_num; // 圆柱体数量
double large_cylinder_radius, large_cylinder_height; // 圆柱体参数
double small_cylinder_radius, small_cylinder_height; // 圆柱体参数
double square_size, square_height; // 立方体参数
double wall_length, wall_height; // 墙参数
double line_height; // 线参数
// 无人机初始位置
double uav_init_x, uav_init_y;
// 无人机odom状态量
bool uav_odom_ok[MAX_SWRAM_NUM] = {false};
nav_msgs::Odometry uav_odom[MAX_SWRAM_NUM];
bool local_map_ready{false};
bool global_map_ok = false;
pcl::PointCloud<pcl::PointXYZ> global_map_pcl; // 全局点云地图 - pcl格式
sensor_msgs::PointCloud2 global_map_ros; // 全局点云地图 - ros_msg格式
pcl::PointCloud<pcl::PointXYZ> local_map_pcl; // 局部点云地图 - pcl格式
sensor_msgs::PointCloud2 local_map_ros; // 局部点云地图 - ros_msg格式
pcl::KdTreeFLANN<pcl::PointXYZ> kdtreeLocalMap;
// 基本形状生成函数
void generate_large_cylinder(double x, double y);
void generate_small_cylinder(double x, double y);
void generate_square(double x, double y);
void generate_row_wall(double x, double y);
void generate_column_wall(double x, double y);
void generate_line(double x, double y);
// 边界生成函数
void GenerateBorder();
// 随机地图生成函数
void GenerateRandomMap();
// planning_test地图生成函数
void GeneratePlanningTestMap();
void GeneratePlanningTestMap2();
void GeneratePlanningTestMap3();
private:
// 订阅
ros::Subscriber uav_odom_sub[MAX_SWRAM_NUM];
// 发布
ros::Publisher local_map_pub[MAX_SWRAM_NUM];
ros::Publisher global_map_pub;
// 定时器
ros::Timer pub_local_map_timer[MAX_SWRAM_NUM];
ros::Timer pub_global_map_timer;
random_device rd;
default_random_engine eng;
uniform_real_distribution<double> rand_x;
uniform_real_distribution<double> rand_y;
vector<int> pointIdxRadiusSearch;
vector<float> pointRadiusSquaredDistance;
void uav_odom_cb(const nav_msgs::Odometry::ConstPtr &odom, int uav_id);
void pub_local_map_cb(const ros::TimerEvent &event, int uav_id);
void pub_global_map_cb(const ros::TimerEvent &event);
};
#endif | 412 | 0.690354 | 1 | 0.690354 | game-dev | MEDIA | 0.640749 | game-dev | 0.557163 | 1 | 0.557163 |
Mandarancio/OpenGOO | 8,542 | src/extlibs/box2d/Box2D/Dynamics/Joints/b2PulleyJoint.cpp | /*
* Copyright (c) 2007 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#include <Box2D/Dynamics/Joints/b2PulleyJoint.h>
#include <Box2D/Dynamics/b2Body.h>
#include <Box2D/Dynamics/b2TimeStep.h>
// Pulley:
// length1 = norm(p1 - s1)
// length2 = norm(p2 - s2)
// C0 = (length1 + ratio * length2)_initial
// C = C0 - (length1 + ratio * length2)
// u1 = (p1 - s1) / norm(p1 - s1)
// u2 = (p2 - s2) / norm(p2 - s2)
// Cdot = -dot(u1, v1 + cross(w1, r1)) - ratio * dot(u2, v2 + cross(w2, r2))
// J = -[u1 cross(r1, u1) ratio * u2 ratio * cross(r2, u2)]
// K = J * invM * JT
// = invMass1 + invI1 * cross(r1, u1)^2 + ratio^2 * (invMass2 + invI2 * cross(r2, u2)^2)
void b2PulleyJointDef::Initialize(b2Body* bA, b2Body* bB,
const b2Vec2& groundA, const b2Vec2& groundB,
const b2Vec2& anchorA, const b2Vec2& anchorB,
float32 r)
{
bodyA = bA;
bodyB = bB;
groundAnchorA = groundA;
groundAnchorB = groundB;
localAnchorA = bodyA->GetLocalPoint(anchorA);
localAnchorB = bodyB->GetLocalPoint(anchorB);
b2Vec2 dA = anchorA - groundA;
lengthA = dA.Length();
b2Vec2 dB = anchorB - groundB;
lengthB = dB.Length();
ratio = r;
b2Assert(ratio > b2_epsilon);
}
b2PulleyJoint::b2PulleyJoint(const b2PulleyJointDef* def)
: b2Joint(def)
{
m_groundAnchorA = def->groundAnchorA;
m_groundAnchorB = def->groundAnchorB;
m_localAnchorA = def->localAnchorA;
m_localAnchorB = def->localAnchorB;
m_lengthA = def->lengthA;
m_lengthB = def->lengthB;
b2Assert(def->ratio != 0.0f);
m_ratio = def->ratio;
m_constant = def->lengthA + m_ratio * def->lengthB;
m_impulse = 0.0f;
}
void b2PulleyJoint::InitVelocityConstraints(const b2SolverData& data)
{
m_indexA = m_bodyA->m_islandIndex;
m_indexB = m_bodyB->m_islandIndex;
m_localCenterA = m_bodyA->m_sweep.localCenter;
m_localCenterB = m_bodyB->m_sweep.localCenter;
m_invMassA = m_bodyA->m_invMass;
m_invMassB = m_bodyB->m_invMass;
m_invIA = m_bodyA->m_invI;
m_invIB = m_bodyB->m_invI;
b2Vec2 cA = data.positions[m_indexA].c;
float32 aA = data.positions[m_indexA].a;
b2Vec2 vA = data.velocities[m_indexA].v;
float32 wA = data.velocities[m_indexA].w;
b2Vec2 cB = data.positions[m_indexB].c;
float32 aB = data.positions[m_indexB].a;
b2Vec2 vB = data.velocities[m_indexB].v;
float32 wB = data.velocities[m_indexB].w;
b2Rot qA(aA), qB(aB);
m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA);
m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB);
// Get the pulley axes.
m_uA = cA + m_rA - m_groundAnchorA;
m_uB = cB + m_rB - m_groundAnchorB;
float32 lengthA = m_uA.Length();
float32 lengthB = m_uB.Length();
if (lengthA > 10.0f * b2_linearSlop)
{
m_uA *= 1.0f / lengthA;
}
else
{
m_uA.SetZero();
}
if (lengthB > 10.0f * b2_linearSlop)
{
m_uB *= 1.0f / lengthB;
}
else
{
m_uB.SetZero();
}
// Compute effective mass.
float32 ruA = b2Cross(m_rA, m_uA);
float32 ruB = b2Cross(m_rB, m_uB);
float32 mA = m_invMassA + m_invIA * ruA * ruA;
float32 mB = m_invMassB + m_invIB * ruB * ruB;
m_mass = mA + m_ratio * m_ratio * mB;
if (m_mass > 0.0f)
{
m_mass = 1.0f / m_mass;
}
if (data.step.warmStarting)
{
// Scale impulses to support variable time steps.
m_impulse *= data.step.dtRatio;
// Warm starting.
b2Vec2 PA = -(m_impulse) * m_uA;
b2Vec2 PB = (-m_ratio * m_impulse) * m_uB;
vA += m_invMassA * PA;
wA += m_invIA * b2Cross(m_rA, PA);
vB += m_invMassB * PB;
wB += m_invIB * b2Cross(m_rB, PB);
}
else
{
m_impulse = 0.0f;
}
data.velocities[m_indexA].v = vA;
data.velocities[m_indexA].w = wA;
data.velocities[m_indexB].v = vB;
data.velocities[m_indexB].w = wB;
}
void b2PulleyJoint::SolveVelocityConstraints(const b2SolverData& data)
{
b2Vec2 vA = data.velocities[m_indexA].v;
float32 wA = data.velocities[m_indexA].w;
b2Vec2 vB = data.velocities[m_indexB].v;
float32 wB = data.velocities[m_indexB].w;
b2Vec2 vpA = vA + b2Cross(wA, m_rA);
b2Vec2 vpB = vB + b2Cross(wB, m_rB);
float32 Cdot = -b2Dot(m_uA, vpA) - m_ratio * b2Dot(m_uB, vpB);
float32 impulse = -m_mass * Cdot;
m_impulse += impulse;
b2Vec2 PA = -impulse * m_uA;
b2Vec2 PB = -m_ratio * impulse * m_uB;
vA += m_invMassA * PA;
wA += m_invIA * b2Cross(m_rA, PA);
vB += m_invMassB * PB;
wB += m_invIB * b2Cross(m_rB, PB);
data.velocities[m_indexA].v = vA;
data.velocities[m_indexA].w = wA;
data.velocities[m_indexB].v = vB;
data.velocities[m_indexB].w = wB;
}
bool b2PulleyJoint::SolvePositionConstraints(const b2SolverData& data)
{
b2Vec2 cA = data.positions[m_indexA].c;
float32 aA = data.positions[m_indexA].a;
b2Vec2 cB = data.positions[m_indexB].c;
float32 aB = data.positions[m_indexB].a;
b2Rot qA(aA), qB(aB);
b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA);
b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB);
// Get the pulley axes.
b2Vec2 uA = cA + rA - m_groundAnchorA;
b2Vec2 uB = cB + rB - m_groundAnchorB;
float32 lengthA = uA.Length();
float32 lengthB = uB.Length();
if (lengthA > 10.0f * b2_linearSlop)
{
uA *= 1.0f / lengthA;
}
else
{
uA.SetZero();
}
if (lengthB > 10.0f * b2_linearSlop)
{
uB *= 1.0f / lengthB;
}
else
{
uB.SetZero();
}
// Compute effective mass.
float32 ruA = b2Cross(rA, uA);
float32 ruB = b2Cross(rB, uB);
float32 mA = m_invMassA + m_invIA * ruA * ruA;
float32 mB = m_invMassB + m_invIB * ruB * ruB;
float32 mass = mA + m_ratio * m_ratio * mB;
if (mass > 0.0f)
{
mass = 1.0f / mass;
}
float32 C = m_constant - lengthA - m_ratio * lengthB;
float32 linearError = b2Abs(C);
float32 impulse = -mass * C;
b2Vec2 PA = -impulse * uA;
b2Vec2 PB = -m_ratio * impulse * uB;
cA += m_invMassA * PA;
aA += m_invIA * b2Cross(rA, PA);
cB += m_invMassB * PB;
aB += m_invIB * b2Cross(rB, PB);
data.positions[m_indexA].c = cA;
data.positions[m_indexA].a = aA;
data.positions[m_indexB].c = cB;
data.positions[m_indexB].a = aB;
return linearError < b2_linearSlop;
}
b2Vec2 b2PulleyJoint::GetAnchorA() const
{
return m_bodyA->GetWorldPoint(m_localAnchorA);
}
b2Vec2 b2PulleyJoint::GetAnchorB() const
{
return m_bodyB->GetWorldPoint(m_localAnchorB);
}
b2Vec2 b2PulleyJoint::GetReactionForce(float32 inv_dt) const
{
b2Vec2 P = m_impulse * m_uB;
return inv_dt * P;
}
float32 b2PulleyJoint::GetReactionTorque(float32 inv_dt) const
{
B2_NOT_USED(inv_dt);
return 0.0f;
}
b2Vec2 b2PulleyJoint::GetGroundAnchorA() const
{
return m_groundAnchorA;
}
b2Vec2 b2PulleyJoint::GetGroundAnchorB() const
{
return m_groundAnchorB;
}
float32 b2PulleyJoint::GetLengthA() const
{
b2Vec2 p = m_bodyA->GetWorldPoint(m_localAnchorA);
b2Vec2 s = m_groundAnchorA;
b2Vec2 d = p - s;
return d.Length();
}
float32 b2PulleyJoint::GetLengthB() const
{
b2Vec2 p = m_bodyB->GetWorldPoint(m_localAnchorB);
b2Vec2 s = m_groundAnchorB;
b2Vec2 d = p - s;
return d.Length();
}
float32 b2PulleyJoint::GetRatio() const
{
return m_ratio;
}
void b2PulleyJoint::Dump()
{
int32 indexA = m_bodyA->m_islandIndex;
int32 indexB = m_bodyB->m_islandIndex;
b2Log(" b2PulleyJointDef jd;\n");
b2Log(" jd.bodyA = bodies[%d];\n", indexA);
b2Log(" jd.bodyB = bodies[%d];\n", indexB);
b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected);
b2Log(" jd.groundAnchorA.Set(%.15lef, %.15lef);\n", m_groundAnchorA.x, m_groundAnchorA.y);
b2Log(" jd.groundAnchorB.Set(%.15lef, %.15lef);\n", m_groundAnchorB.x, m_groundAnchorB.y);
b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y);
b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y);
b2Log(" jd.lengthA = %.15lef;\n", m_lengthA);
b2Log(" jd.lengthB = %.15lef;\n", m_lengthB);
b2Log(" jd.ratio = %.15lef;\n", m_ratio);
b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index);
}
| 412 | 0.879275 | 1 | 0.879275 | game-dev | MEDIA | 0.846456 | game-dev | 0.958675 | 1 | 0.958675 |
ashblue/unity-skill-tree-editor | 2,596 | Assets/SkillTreePro/Editor/SkillTree/GraphEditor/GraphSidebar.cs | using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
namespace Adnc.SkillTree {
public class GraphSidebar {
public SkillTreeBase target;
public void DrawSidebar (Rect rect, float padding, Color color) {
float innerWidth = rect.width - (padding * 2f);
float innerHeight = rect.height - (padding * 2f);
GUI.BeginGroup(rect); // Container
DrawBox(new Rect(0, 0, rect.width, rect.height), color);
GUI.BeginGroup(new Rect(padding, padding, innerWidth, innerHeight)); // Padding
if (target != null) {
float y = 0f;
foreach (Transform child in target.transform) {
SkillCategoryBase cat = child.GetComponent<SkillCategoryBase>();
GUI.BeginGroup(new Rect(0f, y, innerWidth, 300f));
if (GUI.Button(new Rect(0f, 0f, 22f, 20f), "X")) {
if (EditorUtility.DisplayDialog("Delete Category?",
"Are you sure you want to delete this category? The delete action cannot be undone.",
"Delete Category",
"Cancel")) {
if (target.currentCategory == cat)
target.currentCategory = null;
GameObject.DestroyImmediate(cat.gameObject);
}
}
if (GUI.Button(new Rect(24f, 0f, innerWidth - 82f, 20f), cat.displayName)) {
target.currentCategory = cat;
Selection.activeGameObject = cat.gameObject;
GraphController.current.camera.Reset();
}
if (GUI.Button(new Rect(innerWidth - 56f, 0f, 27f, 20f), "UP")) {
child.SetSiblingIndex(child.GetSiblingIndex() - 1);
}
if (GUI.Button(new Rect(innerWidth - 27f, 0f, 27f, 20f), "DN")) {
child.SetSiblingIndex(child.GetSiblingIndex() + 1);
}
GUI.EndGroup();
y += 24f;
}
if (GUI.Button(new Rect(0f, y, innerWidth, 20f), "Create Category")) {
GameObject go = new GameObject();
go.name = "Category";
go.AddComponent(target.SkillCategory);
go.transform.SetParent(target.transform);
}
y += 25f;
if (GUI.Button(new Rect(0f, y, innerWidth, 20f), "Snap All Nodes")) {
GraphController.current.SnapAllNodesToGrid();
}
y += 25f;
GraphController.current.forceSnapping = GUI.Toggle(new Rect(0f, y, innerWidth, 20f), GraphController.current.forceSnapping, "Force Snapping");
}
GUI.EndGroup();
GUI.EndGroup(); // Container
}
void DrawBox (Rect position, Color color) {
Color oldColor = GUI.color;
GUI.color = color;
GUI.Box(position, "");
GUI.color = oldColor;
}
}
}
| 412 | 0.914892 | 1 | 0.914892 | game-dev | MEDIA | 0.969417 | game-dev | 0.989362 | 1 | 0.989362 |
asdflj/AE2Things | 2,148 | src/main/java/com/asdflj/ae2thing/api/adapter/crafting/AECraftingTerminal.java | package com.asdflj.ae2thing.api.adapter.crafting;
import static appeng.integration.modules.NEIHelpers.NEICraftingHandler.packIngredients;
import java.util.List;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.inventory.Container;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.common.util.ForgeDirection;
import appeng.client.gui.implementations.GuiCraftingTerm;
import appeng.container.implementations.ContainerCraftingTerm;
import appeng.core.AELog;
import appeng.core.sync.GuiBridge;
import appeng.core.sync.network.NetworkHandler;
import appeng.core.sync.packets.PacketNEIRecipe;
import appeng.util.Platform;
import codechicken.nei.PositionedStack;
import codechicken.nei.recipe.IRecipeHandler;
public class AECraftingTerminal implements ICraftingTerminalAdapter {
public AECraftingTerminal() {}
@Override
public boolean isTile() {
return true;
}
@Override
public void openGui(EntityPlayerMP player, TileEntity tile, ForgeDirection face, Object target) {
Platform.openGUI(player, tile, face, GuiBridge.GUI_CRAFTING_CONFIRM);
}
@Override
public Class<? extends Container> getContainer() {
return ContainerCraftingTerm.class;
}
@Override
public void moveItems(GuiContainer gui, IRecipeHandler recipe, int recipeIndex) {
try {
final List<PositionedStack> ingredients = recipe.getIngredientStacks(recipeIndex);
if (gui instanceof GuiCraftingTerm) {
PacketNEIRecipe packet = new PacketNEIRecipe(packIngredients(gui, ingredients, false));
if (packet.size() >= 32 * 1024) {
AELog.warn(
"Recipe for " + recipe.getRecipeName()
+ " has too many variants, reduced version will be used");
packet = new PacketNEIRecipe(packIngredients(gui, ingredients, true));
}
NetworkHandler.instance.sendToServer(packet);
}
} catch (final Exception | Error ignored) {}
}
}
| 412 | 0.876584 | 1 | 0.876584 | game-dev | MEDIA | 0.99134 | game-dev | 0.69766 | 1 | 0.69766 |
DeltaV-Station/Delta-v | 2,238 | Content.Server/Nyanotrasen/StationEvents/Events/MidRoundAntagRule.cs | using Content.Server.Antag;
using Content.Server.StationEvents.Components;
using Robust.Shared.Map;
namespace Content.Server.StationEvents.Events;
/// <summary>
/// Makes antags spawn at a random midround antag or vent critter spawner.
/// </summary>
public sealed class MidRoundAntagRule : StationEventSystem<MidRoundAntagRuleComponent>
{
[Dependency] private readonly SharedTransformSystem _xform = default!;
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<MidRoundAntagRuleComponent, AntagSelectLocationEvent>(OnSelectLocation);
}
private void OnSelectLocation(Entity<MidRoundAntagRuleComponent> ent, ref AntagSelectLocationEvent args)
{
if (!TryGetRandomStation(out var station))
return;
var spawns = FindSpawns(station.Value);
if (spawns.Count == 0)
{
Log.Warning($"Couldn't find any suitable midround antag spawners for {ToPrettyString(ent):rule}");
return;
}
args.Coordinates.AddRange(spawns);
}
private List<MapCoordinates> FindSpawns(EntityUid station)
{
var spawns = new List<MapCoordinates>();
var query = EntityQueryEnumerator<MidRoundAntagSpawnLocationComponent, TransformComponent>();
while (query.MoveNext(out var uid, out _, out var xform))
{
if (StationSystem.GetOwningStation(uid, xform) == station && xform.GridUid != null)
spawns.Add(_xform.GetMapCoordinates(xform));
}
// if there are any midround antag spawns mapped, use them
if (spawns.Count > 0)
return spawns;
// otherwise, fall back to vent critter spawns
Log.Info($"Station {ToPrettyString(station):station} has no midround antag spawnpoints mapped, falling back. Please map them!");
var fallbackQuery = EntityQueryEnumerator<VentCritterSpawnLocationComponent, TransformComponent>();
while (fallbackQuery.MoveNext(out var uid, out _, out var xform))
{
if (StationSystem.GetOwningStation(uid, xform) == station && xform.GridUid != null)
spawns.Add(_xform.GetMapCoordinates(xform));
}
return spawns;
}
}
| 412 | 0.894787 | 1 | 0.894787 | game-dev | MEDIA | 0.99144 | game-dev | 0.888551 | 1 | 0.888551 |
hornyyy/Osu-Toy | 3,069 | osu.Game/Screens/Multi/Lounge/Components/ParticipantInfo.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using Humanizer;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Graphics;
using osu.Game.Graphics.Containers;
using osu.Game.Graphics.Sprites;
using osu.Game.Users.Drawables;
using osuTK;
namespace osu.Game.Screens.Multi.Lounge.Components
{
public class ParticipantInfo : MultiplayerComposite
{
public ParticipantInfo()
{
RelativeSizeAxes = Axes.X;
Height = 15f;
}
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
OsuSpriteText summary;
Container flagContainer;
LinkFlowContainer hostText;
InternalChildren = new Drawable[]
{
new FillFlowContainer
{
AutoSizeAxes = Axes.X,
RelativeSizeAxes = Axes.Y,
Direction = FillDirection.Horizontal,
Spacing = new Vector2(5f, 0f),
Children = new Drawable[]
{
flagContainer = new Container
{
Width = 22f,
RelativeSizeAxes = Axes.Y,
},
hostText = new LinkFlowContainer
{
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
AutoSizeAxes = Axes.Both
}
},
},
new FillFlowContainer
{
Anchor = Anchor.CentreRight,
Origin = Anchor.CentreRight,
AutoSizeAxes = Axes.Both,
Direction = FillDirection.Horizontal,
Colour = colours.Gray9,
Children = new[]
{
summary = new OsuSpriteText
{
Text = "0 participants",
Font = OsuFont.GetFont(size: 14)
}
},
},
};
Host.BindValueChanged(host =>
{
hostText.Clear();
flagContainer.Clear();
if (host.NewValue != null)
{
hostText.AddText("hosted by ");
hostText.AddUserLink(host.NewValue, s => s.Font = s.Font.With(Typeface.Torus, weight: FontWeight.Bold, italics: true));
flagContainer.Child = new UpdateableFlag(host.NewValue.Country) { RelativeSizeAxes = Axes.Both };
}
}, true);
ParticipantCount.BindValueChanged(count => summary.Text = "participant".ToQuantity(count.NewValue), true);
}
}
}
| 412 | 0.872916 | 1 | 0.872916 | game-dev | MEDIA | 0.64852 | game-dev,desktop-app | 0.716021 | 1 | 0.716021 |
microsoft/coyote | 27,078 | Tests/Tests.Actors.BugFinding/Integration/ReplicatingStorageTests.cs | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections.Generic;
using System.Linq;
using Microsoft.Coyote.Specifications;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.Coyote.Actors.BugFinding.Tests
{
/// <summary>
/// This is a (much) simplified version of the replicating storage system described
/// in the following paper:
///
/// https://www.usenix.org/system/files/conference/fast16/fast16-papers-deligiannis.pdf
///
/// This test contains the liveness bug discussed in the above paper.
/// </summary>
public class ReplicatingStorageTests : BaseActorBugFindingTest
{
public ReplicatingStorageTests(ITestOutputHelper output)
: base(output)
{
}
private class Environment : StateMachine
{
public class NotifyNode : Event
{
public ActorId Node;
public NotifyNode(ActorId node)
: base()
{
this.Node = node;
}
}
public class FaultInject : Event
{
}
private class CreateFailure : Event
{
}
private class LocalEvent : Event
{
}
private ActorId NodeManager;
private int NumberOfReplicas;
private List<ActorId> AliveNodes;
private int NumberOfFaults;
private ActorId Client;
private ActorId FailureTimer;
[Start]
[OnEntry(nameof(EntryOnInit))]
[OnEventGotoState(typeof(LocalEvent), typeof(Configuring))]
private class Init : State
{
}
private void EntryOnInit()
{
this.NumberOfReplicas = 3;
this.NumberOfFaults = 1;
this.AliveNodes = new List<ActorId>();
this.Monitor<LivenessMonitor>(new LivenessMonitor.ConfigureEvent(this.NumberOfReplicas));
this.NodeManager = this.CreateActor(typeof(NodeManager));
this.Client = this.CreateActor(typeof(Client));
this.RaiseEvent(new LocalEvent());
}
[OnEntry(nameof(ConfiguringOnInit))]
[OnEventGotoState(typeof(LocalEvent), typeof(Active))]
[DeferEvents(typeof(FailureTimer.Timeout))]
private class Configuring : State
{
}
private void ConfiguringOnInit()
{
this.SendEvent(this.NodeManager, new NodeManager.ConfigureEvent(this.Id, this.NumberOfReplicas));
this.SendEvent(this.Client, new Client.ConfigureEvent(this.NodeManager));
this.RaiseEvent(new LocalEvent());
}
[OnEventDoAction(typeof(NotifyNode), nameof(UpdateAliveNodes))]
[OnEventDoAction(typeof(FailureTimer.Timeout), nameof(InjectFault))]
private class Active : State
{
}
private void UpdateAliveNodes(Event e)
{
var node = (e as NotifyNode).Node;
this.AliveNodes.Add(node);
if (this.AliveNodes.Count == this.NumberOfReplicas &&
this.FailureTimer is null)
{
this.FailureTimer = this.CreateActor(typeof(FailureTimer));
this.SendEvent(this.FailureTimer, new FailureTimer.ConfigureEvent(this.Id));
}
}
private void InjectFault()
{
if (this.NumberOfFaults is 0 ||
this.AliveNodes.Count is 0)
{
return;
}
int nodeId = this.RandomInteger(this.AliveNodes.Count);
var node = this.AliveNodes[nodeId];
this.SendEvent(node, new FaultInject());
this.SendEvent(this.NodeManager, new NodeManager.NotifyFailure(node));
this.AliveNodes.Remove(node);
this.NumberOfFaults--;
if (this.NumberOfFaults is 0)
{
this.SendEvent(this.FailureTimer, HaltEvent.Instance);
}
}
}
private class NodeManager : StateMachine
{
public class ConfigureEvent : Event
{
public ActorId Environment;
public int NumberOfReplicas;
public ConfigureEvent(ActorId env, int numOfReplicas)
: base()
{
this.Environment = env;
this.NumberOfReplicas = numOfReplicas;
}
}
public class NotifyFailure : Event
{
public ActorId Node;
public NotifyFailure(ActorId node)
: base()
{
this.Node = node;
}
}
internal class ShutDown : Event
{
}
private class LocalEvent : Event
{
}
private ActorId Environment;
private List<ActorId> StorageNodes;
private int NumberOfReplicas;
private Dictionary<int, bool> StorageNodeMap;
private Dictionary<int, int> DataMap;
private ActorId RepairTimer;
[Start]
[OnEntry(nameof(EntryOnInit))]
[OnEventDoAction(typeof(ConfigureEvent), nameof(SetupEvent))]
[OnEventGotoState(typeof(LocalEvent), typeof(Active))]
[DeferEvents(typeof(Client.Request), typeof(RepairTimer.Timeout))]
private class Init : State
{
}
private void EntryOnInit()
{
this.StorageNodes = new List<ActorId>();
this.StorageNodeMap = new Dictionary<int, bool>();
this.DataMap = new Dictionary<int, int>();
this.RepairTimer = this.CreateActor(typeof(RepairTimer));
this.SendEvent(this.RepairTimer, new RepairTimer.ConfigureEvent(this.Id));
}
private void SetupEvent(Event e)
{
this.Environment = (e as ConfigureEvent).Environment;
this.NumberOfReplicas = (e as ConfigureEvent).NumberOfReplicas;
for (int idx = 0; idx < this.NumberOfReplicas; idx++)
{
this.CreateNewNode();
}
this.RaiseEvent(new LocalEvent());
}
private void CreateNewNode()
{
var idx = this.StorageNodes.Count;
var node = this.CreateActor(typeof(StorageNode));
this.StorageNodes.Add(node);
this.StorageNodeMap.Add(idx, true);
this.SendEvent(node, new StorageNode.ConfigureEvent(this.Environment, this.Id, idx));
}
[OnEventDoAction(typeof(Client.Request), nameof(ProcessClientRequest))]
[OnEventDoAction(typeof(RepairTimer.Timeout), nameof(RepairNodes))]
[OnEventDoAction(typeof(StorageNode.SyncReport), nameof(ProcessSyncReport))]
[OnEventDoAction(typeof(NotifyFailure), nameof(ProcessFailure))]
private class Active : State
{
}
private void ProcessClientRequest(Event e)
{
var command = (e as Client.Request).Command;
var aliveNodeIds = this.StorageNodeMap.Where(n => n.Value).Select(n => n.Key);
foreach (var nodeId in aliveNodeIds)
{
this.SendEvent(this.StorageNodes[nodeId], new StorageNode.StoreRequest(command));
}
}
private void RepairNodes()
{
if (this.DataMap.Count is 0)
{
return;
}
var latestData = this.DataMap.Values.Max();
var numOfReplicas = this.DataMap.Count(kvp => kvp.Value == latestData);
if (numOfReplicas >= this.NumberOfReplicas)
{
return;
}
foreach (var node in this.DataMap)
{
if (node.Value != latestData)
{
this.SendEvent(this.StorageNodes[node.Key], new StorageNode.SyncRequest(latestData));
numOfReplicas++;
}
if (numOfReplicas == this.NumberOfReplicas)
{
break;
}
}
}
private void ProcessSyncReport(Event e)
{
var nodeId = (e as StorageNode.SyncReport).NodeId;
var data = (e as StorageNode.SyncReport).Data;
// LIVENESS BUG: can fail to ever repair again as it thinks there
// are enough replicas. Enable to introduce a bug fix.
// if (!this.StorageNodeMap.ContainsKey(nodeId))
// {
// return;
// }
if (!this.DataMap.ContainsKey(nodeId))
{
this.DataMap.Add(nodeId, 0);
}
this.DataMap[nodeId] = data;
}
private void ProcessFailure(Event e)
{
var node = (e as NotifyFailure).Node;
var nodeId = this.StorageNodes.IndexOf(node);
this.StorageNodeMap.Remove(nodeId);
this.DataMap.Remove(nodeId);
this.CreateNewNode();
}
}
private class StorageNode : StateMachine
{
public class ConfigureEvent : Event
{
public ActorId Environment;
public ActorId NodeManager;
public int Id;
public ConfigureEvent(ActorId env, ActorId manager, int id)
: base()
{
this.Environment = env;
this.NodeManager = manager;
this.Id = id;
}
}
public class StoreRequest : Event
{
public int Command;
public StoreRequest(int cmd)
: base()
{
this.Command = cmd;
}
}
public class SyncReport : Event
{
public int NodeId;
public int Data;
public SyncReport(int id, int data)
: base()
{
this.NodeId = id;
this.Data = data;
}
}
public class SyncRequest : Event
{
public int Data;
public SyncRequest(int data)
: base()
{
this.Data = data;
}
}
internal class ShutDown : Event
{
}
private class LocalEvent : Event
{
}
private ActorId Environment;
private ActorId NodeManager;
private int NodeId;
private int Data;
private ActorId SyncTimer;
[Start]
[OnEntry(nameof(EntryOnInit))]
[OnEventDoAction(typeof(ConfigureEvent), nameof(SetupEvent))]
[OnEventGotoState(typeof(LocalEvent), typeof(Active))]
[DeferEvents(typeof(SyncTimer.Timeout))]
private class Init : State
{
}
private void EntryOnInit()
{
this.Data = 0;
this.SyncTimer = this.CreateActor(typeof(SyncTimer));
this.SendEvent(this.SyncTimer, new SyncTimer.ConfigureEvent(this.Id));
}
private void SetupEvent(Event e)
{
this.Environment = (e as ConfigureEvent).Environment;
this.NodeManager = (e as ConfigureEvent).NodeManager;
this.NodeId = (e as ConfigureEvent).Id;
this.Monitor<LivenessMonitor>(new LivenessMonitor.NotifyNodeCreated(this.NodeId));
this.SendEvent(this.Environment, new Environment.NotifyNode(this.Id));
this.RaiseEvent(new LocalEvent());
}
[OnEventDoAction(typeof(StoreRequest), nameof(Store))]
[OnEventDoAction(typeof(SyncRequest), nameof(Sync))]
[OnEventDoAction(typeof(SyncTimer.Timeout), nameof(GenerateSyncReport))]
[OnEventDoAction(typeof(Environment.FaultInject), nameof(Terminate))]
private class Active : State
{
}
private void Store(Event e)
{
var cmd = (e as StoreRequest).Command;
this.Data += cmd;
this.Monitor<LivenessMonitor>(new LivenessMonitor.NotifyNodeUpdate(this.NodeId, this.Data));
}
private void Sync(Event e)
{
var data = (e as SyncRequest).Data;
this.Data = data;
this.Monitor<LivenessMonitor>(new LivenessMonitor.NotifyNodeUpdate(this.NodeId, this.Data));
}
private void GenerateSyncReport()
{
this.SendEvent(this.NodeManager, new SyncReport(this.NodeId, this.Data));
}
private void Terminate()
{
this.Monitor<LivenessMonitor>(new LivenessMonitor.NotifyNodeFail(this.NodeId));
this.SendEvent(this.SyncTimer, HaltEvent.Instance);
this.RaiseHaltEvent();
}
}
private class FailureTimer : StateMachine
{
internal class ConfigureEvent : Event
{
public ActorId Target;
public ConfigureEvent(ActorId id)
: base()
{
this.Target = id;
}
}
internal class StartTimerEvent : Event
{
}
internal class CancelTimer : Event
{
}
internal class Timeout : Event
{
}
private class TickEvent : Event
{
}
private ActorId Target;
[Start]
[OnEventDoAction(typeof(ConfigureEvent), nameof(SetupEvent))]
[OnEventGotoState(typeof(StartTimerEvent), typeof(Active))]
private class Init : State
{
}
private void SetupEvent(Event e)
{
this.Target = (e as ConfigureEvent).Target;
this.RaiseEvent(new StartTimerEvent());
}
[OnEntry(nameof(ActiveOnEntry))]
[OnEventDoAction(typeof(TickEvent), nameof(Tick))]
[OnEventGotoState(typeof(CancelTimer), typeof(Inactive))]
[IgnoreEvents(typeof(StartTimerEvent))]
private class Active : State
{
}
private void ActiveOnEntry()
{
this.SendEvent(this.Id, new TickEvent());
}
private void Tick()
{
if (this.RandomBoolean())
{
this.SendEvent(this.Target, new Timeout());
}
this.SendEvent(this.Id, new TickEvent());
}
[OnEventGotoState(typeof(StartTimerEvent), typeof(Active))]
[IgnoreEvents(typeof(CancelTimer), typeof(TickEvent))]
private class Inactive : State
{
}
}
private class RepairTimer : StateMachine
{
internal class ConfigureEvent : Event
{
public ActorId Target;
public ConfigureEvent(ActorId id)
: base()
{
this.Target = id;
}
}
internal class StartTimerEvent : Event
{
}
internal class CancelTimer : Event
{
}
internal class Timeout : Event
{
}
private class TickEvent : Event
{
}
private ActorId Target;
[Start]
[OnEventDoAction(typeof(ConfigureEvent), nameof(SetupEvent))]
[OnEventGotoState(typeof(StartTimerEvent), typeof(Active))]
private class Init : State
{
}
private void SetupEvent(Event e)
{
this.Target = (e as ConfigureEvent).Target;
this.RaiseEvent(new StartTimerEvent());
}
[OnEntry(nameof(ActiveOnEntry))]
[OnEventDoAction(typeof(TickEvent), nameof(Tick))]
[OnEventGotoState(typeof(CancelTimer), typeof(Inactive))]
[IgnoreEvents(typeof(StartTimerEvent))]
private class Active : State
{
}
private void ActiveOnEntry()
{
this.SendEvent(this.Id, new TickEvent());
}
private void Tick()
{
if (this.RandomBoolean())
{
this.SendEvent(this.Target, new Timeout());
}
this.SendEvent(this.Id, new TickEvent());
}
[OnEventGotoState(typeof(StartTimerEvent), typeof(Active))]
[IgnoreEvents(typeof(CancelTimer), typeof(TickEvent))]
private class Inactive : State
{
}
}
private class SyncTimer : StateMachine
{
internal class ConfigureEvent : Event
{
public ActorId Target;
public ConfigureEvent(ActorId id)
: base()
{
this.Target = id;
}
}
internal class StartTimerEvent : Event
{
}
internal class CancelTimer : Event
{
}
internal class Timeout : Event
{
}
private class TickEvent : Event
{
}
private ActorId Target;
[Start]
[OnEventDoAction(typeof(ConfigureEvent), nameof(SetupEvent))]
[OnEventGotoState(typeof(StartTimerEvent), typeof(Active))]
private class Init : State
{
}
private void SetupEvent(Event e)
{
this.Target = (e as ConfigureEvent).Target;
this.RaiseEvent(new StartTimerEvent());
}
[OnEntry(nameof(ActiveOnEntry))]
[OnEventDoAction(typeof(TickEvent), nameof(Tick))]
[OnEventGotoState(typeof(CancelTimer), typeof(Inactive))]
[IgnoreEvents(typeof(StartTimerEvent))]
private class Active : State
{
}
private void ActiveOnEntry()
{
this.SendEvent(this.Id, new TickEvent());
}
private void Tick()
{
if (this.RandomBoolean())
{
this.SendEvent(this.Target, new Timeout());
}
this.SendEvent(this.Id, new TickEvent());
}
[OnEventGotoState(typeof(StartTimerEvent), typeof(Active))]
[IgnoreEvents(typeof(CancelTimer), typeof(TickEvent))]
private class Inactive : State
{
}
}
private class Client : StateMachine
{
public class ConfigureEvent : Event
{
public ActorId NodeManager;
public ConfigureEvent(ActorId manager)
: base()
{
this.NodeManager = manager;
}
}
internal class Request : Event
{
public ActorId Client;
public int Command;
public Request(ActorId client, int cmd)
: base()
{
this.Client = client;
this.Command = cmd;
}
}
private class LocalEvent : Event
{
}
private ActorId NodeManager;
private int Counter;
[Start]
[OnEntry(nameof(InitOnEntry))]
[OnEventDoAction(typeof(ConfigureEvent), nameof(SetupEvent))]
[OnEventGotoState(typeof(LocalEvent), typeof(PumpRequest))]
private class Init : State
{
}
private void InitOnEntry()
{
this.Counter = 0;
}
private void SetupEvent(Event e)
{
this.NodeManager = (e as ConfigureEvent).NodeManager;
this.RaiseEvent(new LocalEvent());
}
[OnEntry(nameof(PumpRequestOnEntry))]
[OnEventGotoState(typeof(LocalEvent), typeof(PumpRequest))]
private class PumpRequest : State
{
}
private void PumpRequestOnEntry()
{
int command = this.RandomInteger(100) + 1;
this.Counter++;
this.SendEvent(this.NodeManager, new Request(this.Id, command));
if (this.Counter is 1)
{
this.RaiseHaltEvent();
}
else
{
this.RaiseEvent(new LocalEvent());
}
}
}
private class LivenessMonitor : Monitor
{
public class ConfigureEvent : Event
{
public int NumberOfReplicas;
public ConfigureEvent(int numOfReplicas)
: base()
{
this.NumberOfReplicas = numOfReplicas;
}
}
public class NotifyNodeCreated : Event
{
public int NodeId;
public NotifyNodeCreated(int id)
: base()
{
this.NodeId = id;
}
}
public class NotifyNodeFail : Event
{
public int NodeId;
public NotifyNodeFail(int id)
: base()
{
this.NodeId = id;
}
}
public class NotifyNodeUpdate : Event
{
public int NodeId;
public int Data;
public NotifyNodeUpdate(int id, int data)
: base()
{
this.NodeId = id;
this.Data = data;
}
}
private class LocalEvent : Event
{
}
private Dictionary<int, int> DataMap;
private int NumberOfReplicas;
[Start]
[OnEntry(nameof(InitOnEntry))]
[OnEventDoAction(typeof(ConfigureEvent), nameof(SetupEvent))]
[OnEventGotoState(typeof(LocalEvent), typeof(Repaired))]
private class Init : State
{
}
private void InitOnEntry()
{
this.DataMap = new Dictionary<int, int>();
}
private void SetupEvent(Event e)
{
this.NumberOfReplicas = (e as ConfigureEvent).NumberOfReplicas;
this.RaiseEvent(new LocalEvent());
}
[Cold]
[OnEventDoAction(typeof(NotifyNodeCreated), nameof(ProcessNodeCreated))]
[OnEventDoAction(typeof(NotifyNodeFail), nameof(FailAndCheckRepair))]
[OnEventDoAction(typeof(NotifyNodeUpdate), nameof(ProcessNodeUpdate))]
[OnEventGotoState(typeof(LocalEvent), typeof(Repairing))]
private class Repaired : State
{
}
private void ProcessNodeCreated(Event e)
{
var nodeId = (e as NotifyNodeCreated).NodeId;
this.DataMap.Add(nodeId, 0);
}
private void FailAndCheckRepair(Event e)
{
this.ProcessNodeFail(e);
this.RaiseEvent(new LocalEvent());
}
private void ProcessNodeUpdate(Event e)
{
var nodeId = (e as NotifyNodeUpdate).NodeId;
var data = (e as NotifyNodeUpdate).Data;
this.DataMap[nodeId] = data;
}
[Hot]
[OnEventDoAction(typeof(NotifyNodeCreated), nameof(ProcessNodeCreated))]
[OnEventDoAction(typeof(NotifyNodeFail), nameof(ProcessNodeFail))]
[OnEventDoAction(typeof(NotifyNodeUpdate), nameof(CheckIfRepaired))]
[OnEventGotoState(typeof(LocalEvent), typeof(Repaired))]
private class Repairing : State
{
}
private void ProcessNodeFail(Event e)
{
var nodeId = (e as NotifyNodeFail).NodeId;
this.DataMap.Remove(nodeId);
}
private void CheckIfRepaired(Event e)
{
this.ProcessNodeUpdate(e);
var consensus = this.DataMap.Select(kvp => kvp.Value).GroupBy(v => v).
OrderByDescending(v => v.Count()).FirstOrDefault();
var numOfReplicas = consensus.Count();
if (numOfReplicas >= this.NumberOfReplicas)
{
this.RaiseEvent(new LocalEvent());
}
}
}
[Theory(Timeout = 10000)]
[InlineData(1)]
public void TestReplicatingStorageLivenessBug(uint seed)
{
var configuration = this.GetConfiguration();
configuration.MaxUnfairSchedulingSteps = 200;
configuration.MaxFairSchedulingSteps = 2000;
configuration.LivenessTemperatureThreshold = 1000;
configuration.RandomGeneratorSeed = seed;
configuration.TestingIterations = 1;
this.TestWithError(r =>
{
r.RegisterMonitor<LivenessMonitor>();
r.CreateActor(typeof(Environment));
},
configuration: configuration,
expectedError: "LivenessMonitor detected potential liveness bug in hot state 'Repairing'.",
replay: true);
}
}
}
| 412 | 0.943987 | 1 | 0.943987 | game-dev | MEDIA | 0.405274 | game-dev | 0.960134 | 1 | 0.960134 |
Magneticraft-Team/Magneticraft | 21,298 | src/main/kotlin/com/cout970/magneticraft/features/multiblocks/tileentities/Machines.kt | package com.cout970.magneticraft.features.multiblocks.tileentities
import com.cout970.magneticraft.api.internal.energy.ElectricNode
import com.cout970.magneticraft.api.internal.heat.HeatNode
import com.cout970.magneticraft.features.multiblocks.structures.*
import com.cout970.magneticraft.misc.ElectricConstants
import com.cout970.magneticraft.misc.RegisterTileEntity
import com.cout970.magneticraft.misc.crafting.FurnaceCraftingProcess
import com.cout970.magneticraft.misc.crafting.GrinderCraftingProcess
import com.cout970.magneticraft.misc.crafting.HydraulicPressCraftingProcess
import com.cout970.magneticraft.misc.crafting.SieveCraftingProcess
import com.cout970.magneticraft.misc.flatten
import com.cout970.magneticraft.misc.fluid.Tank
import com.cout970.magneticraft.misc.fromCelsiusToKelvin
import com.cout970.magneticraft.misc.inventory.Inventory
import com.cout970.magneticraft.misc.inventory.InventoryCapabilityFilter
import com.cout970.magneticraft.misc.inventory.isNotEmpty
import com.cout970.magneticraft.misc.tileentity.DoNotRemove
import com.cout970.magneticraft.misc.tileentity.shouldTick
import com.cout970.magneticraft.misc.vector.createAABBUsing
import com.cout970.magneticraft.misc.vector.rotateBox
import com.cout970.magneticraft.misc.vector.rotatePoint
import com.cout970.magneticraft.misc.vector.vec3Of
import com.cout970.magneticraft.misc.world.ParticleSpawner
import com.cout970.magneticraft.misc.world.isServer
import com.cout970.magneticraft.registry.*
import com.cout970.magneticraft.systems.config.Config
import com.cout970.magneticraft.systems.multiblocks.Multiblock
import com.cout970.magneticraft.systems.tilemodules.*
import com.cout970.magneticraft.systems.tilerenderers.px
import com.cout970.vector.extensions.Vector3
import net.minecraft.init.Blocks
import net.minecraft.util.EnumFacing
import net.minecraft.util.EnumParticleTypes
import net.minecraft.util.ITickable
import net.minecraft.util.math.BlockPos
@RegisterTileEntity("grinder")
class TileGrinder : TileMultiblock(), ITickable {
override fun getMultiblock(): Multiblock = MultiblockGrinder
val node = ElectricNode(ref)
val inventory = Inventory(3)
val itemExporterModule = ModuleItemExporter(
facing = { facing },
inventory = InventoryCapabilityFilter(inventory, listOf(1, 2), listOf(1, 2)),
ports = { listOf(BlockPos(0, 0, -3) to EnumFacing.SOUTH, BlockPos(0, 0, -3) to EnumFacing.UP) }
)
val openGuiModule = ModuleOpenGui()
val ioModule: ModuleMultiblockIO = ModuleMultiblockIO(
facing = { facing },
connectionSpots = listOf(
ConnectionSpot(
capability = ELECTRIC_NODE_HANDLER!!,
pos = BlockPos(1, 1, -1),
side = EnumFacing.EAST,
getter = { energyModule }
),
ConnectionSpot(ITEM_HANDLER!!, BlockPos(0, 0, -2), EnumFacing.NORTH,
getter = { InventoryCapabilityFilter(inventory, emptyList(), listOf(1, 2)) }
),
ConnectionSpot(ITEM_HANDLER!!, BlockPos(-1, 0, -1), EnumFacing.WEST,
getter = { InventoryCapabilityFilter(inventory, listOf(0), emptyList()) }
)
) + ModuleMultiblockIO.connectionArea(ITEM_HANDLER!!, BlockPos(-1, 3, -2), BlockPos(1, 3, 0),
EnumFacing.UP, getter = { InventoryCapabilityFilter(inventory, listOf(0), emptyList()) }
)
)
val energyModule = ModuleElectricity(
electricNodes = listOf(node),
canConnectAtSide = ioModule::canConnectAtSide,
connectableDirections = ioModule::getElectricConnectPoints
)
val storageModule = ModuleInternalStorage(
mainNode = node,
initialCapacity = 10_000
)
val invModule = ModuleInventory(
inventory = inventory,
capabilityFilter = ModuleInventory.ALLOW_NONE
)
val processModule = ModuleElectricProcessing(
craftingProcess = GrinderCraftingProcess(invModule, 0, 1, 2),
storage = storageModule,
workingRate = 1f,
costPerTick = Config.grinderMaxConsumption.toFloat()
)
override val multiblockModule = ModuleMultiblockCenter(
multiblockStructure = getMultiblock(),
facingGetter = { facing },
capabilityGetter = ioModule::getCapability
)
val spawner = ParticleSpawner(30.0, EnumParticleTypes.BLOCK_DUST, Blocks.STONE.defaultState,
speed = { facing.rotatePoint(Vector3.ORIGIN, vec3Of(0, 0.1, 0)) }
) {
facing.rotateBox(vec3Of(0.5), vec3Of((-5).px, 14.px, 5.px).createAABBUsing(vec3Of(21.px, 58.px, (-21).px))).offset(pos)
}
init {
initModules(multiblockModule, energyModule, storageModule, processModule, invModule, openGuiModule, ioModule,
itemExporterModule)
}
@DoNotRemove
override fun update() {
super.update()
if (world.isServer || !processModule.working) return
if (Config.enableMachineParticles == 1) {
spawner.spawn(world)
}
}
}
@RegisterTileEntity("sieve")
class TileSieve : TileMultiblock(), ITickable {
override fun getMultiblock(): Multiblock = MultiblockSieve
val node = ElectricNode(ref)
val inventory = Inventory(4)
val itemExporterModule0 = ModuleItemExporter(
facing = { facing },
inventory = InventoryCapabilityFilter(inventory, listOf(1), listOf(1)),
ports = { listOf(BlockPos(0, -1, -1) to EnumFacing.UP) }
)
val itemExporterModule1 = ModuleItemExporter(
facing = { facing },
inventory = InventoryCapabilityFilter(inventory, listOf(2), listOf(2)),
ports = { listOf(BlockPos(0, -1, -2) to EnumFacing.UP) }
)
val itemExporterModule2 = ModuleItemExporter(
facing = { facing },
inventory = InventoryCapabilityFilter(inventory, listOf(3), listOf(3)),
ports = { listOf(BlockPos(0, -1, -3) to EnumFacing.UP) }
)
val openGuiModule = ModuleOpenGui()
val ioModule: ModuleMultiblockIO = ModuleMultiblockIO(
facing = { facing },
connectionSpots = listOf(
ConnectionSpot(
capability = ELECTRIC_NODE_HANDLER!!,
pos = BlockPos(-1, 1, 0),
side = EnumFacing.SOUTH,
getter = { energyModule }
),
ConnectionSpot(
capability = ELECTRIC_NODE_HANDLER!!,
pos = BlockPos(1, 1, 0),
side = EnumFacing.SOUTH,
getter = { energyModule }
),
ConnectionSpot(ITEM_HANDLER!!, BlockPos(0, 1, 0), EnumFacing.UP,
getter = { InventoryCapabilityFilter(inventory, listOf(0), emptyList()) }
),
ConnectionSpot(ITEM_HANDLER!!, BlockPos(0, 0, 0), EnumFacing.SOUTH,
getter = { InventoryCapabilityFilter(inventory, listOf(0), emptyList()) }
),
ConnectionSpot(ITEM_HANDLER!!, BlockPos(0, 0, -1), EnumFacing.DOWN,
getter = { InventoryCapabilityFilter(inventory, emptyList(), listOf(1)) }
),
ConnectionSpot(ITEM_HANDLER!!, BlockPos(0, 0, -2), EnumFacing.DOWN,
getter = { InventoryCapabilityFilter(inventory, emptyList(), listOf(2)) }
),
ConnectionSpot(ITEM_HANDLER!!, BlockPos(0, 0, -3), EnumFacing.DOWN,
getter = { InventoryCapabilityFilter(inventory, emptyList(), listOf(3)) }
)
)
)
val energyModule = ModuleElectricity(
electricNodes = listOf(node),
canConnectAtSide = ioModule::canConnectAtSide,
connectableDirections = ioModule::getElectricConnectPoints
)
val storageModule = ModuleInternalStorage(
mainNode = node,
initialCapacity = 10_000,
initialLowerVoltageLimit = ElectricConstants.TIER_1_MACHINES_MIN_VOLTAGE,
initialUpperVoltageLimit = ElectricConstants.TIER_1_MACHINES_MIN_VOLTAGE
)
val invModule = ModuleInventory(
inventory = inventory,
capabilityFilter = ModuleInventory.ALLOW_NONE
)
val processModule = ModuleElectricProcessing(
craftingProcess = SieveCraftingProcess(invModule, 0, 1, 2, 3),
storage = storageModule,
workingRate = 1f,
costPerTick = Config.sieveMaxConsumption.toFloat()
)
override val multiblockModule = ModuleMultiblockCenter(
multiblockStructure = getMultiblock(),
facingGetter = { facing },
capabilityGetter = ioModule::getCapability
)
val spawner1 = ParticleSpawner(20.0, EnumParticleTypes.BLOCK_DUST, Blocks.SAND.defaultState,
speed = { facing.rotatePoint(Vector3.ORIGIN, vec3Of(0, 0, -0.1)) }
) {
facing.rotateBox(vec3Of(0.5), vec3Of((-4).px, 1.5, (-4).px).createAABBUsing(vec3Of(20.px, 1.5, (-20).px))).offset(pos)
}
val spawner2 = ParticleSpawner(20.0, EnumParticleTypes.BLOCK_DUST, Blocks.SAND.defaultState,
speed = { facing.rotatePoint(Vector3.ORIGIN, vec3Of(0, 0, -0.1)) }
) {
facing.rotateBox(vec3Of(0.5), vec3Of((-4).px, 1.25, (-20).px).createAABBUsing(vec3Of(20.px, 1.25, (-36).px))).offset(pos)
}
val spawner3 = ParticleSpawner(20.0, EnumParticleTypes.BLOCK_DUST, Blocks.SAND.defaultState,
speed = { facing.rotatePoint(Vector3.ORIGIN, vec3Of(0, 0, -0.1)) }
) {
facing.rotateBox(vec3Of(0.5), vec3Of((-4).px, 1, (-36).px).createAABBUsing(vec3Of(20.px, 1, (-52).px))).offset(pos)
}
init {
initModules(multiblockModule, energyModule, storageModule, processModule, invModule, ioModule, openGuiModule,
itemExporterModule0, itemExporterModule1, itemExporterModule2)
}
@DoNotRemove
override fun update() {
super.update()
if (world.isServer || !processModule.working) return
if (Config.enableMachineParticles == 1) {
spawner1.spawn(world)
spawner2.spawn(world)
spawner3.spawn(world)
}
}
}
@RegisterTileEntity("hydraulic_press")
class TileHydraulicPress : TileMultiblock(), ITickable {
override fun getMultiblock(): Multiblock = MultiblockHydraulicPress
val inventory = Inventory(2)
val node = ElectricNode(ref)
val invModule = ModuleInventory(inventory, capabilityFilter = ModuleInventory.ALLOW_NONE)
val storageModule = ModuleInternalStorage(
mainNode = node,
initialCapacity = 10_000,
initialLowerVoltageLimit = ElectricConstants.TIER_1_MACHINES_MIN_VOLTAGE,
initialUpperVoltageLimit = ElectricConstants.TIER_1_MACHINES_MIN_VOLTAGE
)
val openGuiModule = ModuleOpenGui()
val ioModule: ModuleMultiblockIO = ModuleMultiblockIO(
facing = { facing },
connectionSpots = listOf(ConnectionSpot(
capability = ELECTRIC_NODE_HANDLER!!,
pos = BlockPos(-1, 1, -1),
side = EnumFacing.WEST,
getter = { if (active) energyModule else null }
), ConnectionSpot(
capability = ELECTRIC_NODE_HANDLER!!,
pos = BlockPos(1, 1, -1),
side = EnumFacing.EAST,
getter = { if (active) energyModule else null }
), ConnectionSpot(
capability = ITEM_HANDLER!!,
pos = BlockPos(0, 0, 0),
side = EnumFacing.SOUTH,
getter = { if (active) InventoryCapabilityFilter(inventory, listOf(0), listOf()) else null }
), ConnectionSpot(
capability = ITEM_HANDLER!!,
pos = BlockPos(0, 0, -2),
side = EnumFacing.NORTH,
getter = { if (active) InventoryCapabilityFilter(inventory, listOf(), listOf(1)) else null }
))
)
val energyModule = ModuleElectricity(
electricNodes = listOf(node),
canConnectAtSide = ioModule::canConnectAtSide,
connectableDirections = ioModule::getElectricConnectPoints
)
val hydraulicPressModule = ModuleHydraulicPress()
val processModule = ModuleElectricProcessing(
costPerTick = Config.hydraulicPressMaxConsumption.toFloat(),
workingRate = 1f,
storage = storageModule,
craftingProcess = HydraulicPressCraftingProcess(
inventory = inventory,
inputSlot = 0,
outputSlot = 1,
mode = hydraulicPressModule::mode
)
)
val itemExporterModule = ModuleItemExporter(
facing = { facing },
inventory = InventoryCapabilityFilter(inventory, listOf(1), listOf(1)),
ports = { listOf(BlockPos(0, 0, -3) to EnumFacing.SOUTH, BlockPos(0, 0, -3) to EnumFacing.UP) }
)
override val multiblockModule = ModuleMultiblockCenter(
multiblockStructure = getMultiblock(),
facingGetter = { facing },
capabilityGetter = ioModule::getCapability
)
init {
initModules(multiblockModule, invModule, energyModule, storageModule, ioModule,
openGuiModule, processModule, hydraulicPressModule, itemExporterModule)
}
@DoNotRemove
override fun update() {
super.update()
}
}
@RegisterTileEntity("big_combustion_chamber")
class TileBigCombustionChamber : TileMultiblock(), ITickable {
override fun getMultiblock(): Multiblock = MultiblockBigCombustionChamber
val inventory = Inventory(1)
val node = HeatNode(ref)
val tank = Tank(4000)
val openGuiModule = ModuleOpenGui()
val fluidModule = ModuleFluidHandler(tank)
val invModule = ModuleInventory(inventory)
val ioModule: ModuleMultiblockIO = ModuleMultiblockIO(
facing = { facing },
connectionSpots = listOf(ConnectionSpot(
capability = ITEM_HANDLER!!,
pos = BlockPos(-1, 0, -1),
side = EnumFacing.WEST,
getter = { if (active) inventory else null }
), ConnectionSpot(
capability = ITEM_HANDLER!!,
pos = BlockPos(1, 0, -1),
side = EnumFacing.EAST,
getter = { if (active) inventory else null }
), ConnectionSpot(
capability = FLUID_HANDLER!!,
pos = BlockPos(-1, 0, -1),
side = EnumFacing.WEST,
getter = { if (active) tank else null }
), ConnectionSpot(
capability = FLUID_HANDLER!!,
pos = BlockPos(1, 0, -1),
side = EnumFacing.EAST,
getter = { if (active) tank else null }
)) + ModuleMultiblockIO.connectionArea(HEAT_NODE_HANDLER!!,
BlockPos(-1, 1, -2), BlockPos(1, 1, 0), EnumFacing.UP
) { if (active) heatModule else null }
)
val heatModule = ModuleHeat(node, connectableDirections = ioModule::getHeatConnectPoints)
val bigCombustionChamberModule = ModuleBigCombustionChamber(this::facing, node, inventory, tank, 2000.fromCelsiusToKelvin())
override val multiblockModule = ModuleMultiblockCenter(
multiblockStructure = getMultiblock(),
facingGetter = this::facing,
capabilityGetter = ioModule::getCapability
)
init {
initModules(multiblockModule, invModule, fluidModule, bigCombustionChamberModule, heatModule, openGuiModule)
}
@DoNotRemove
override fun update() {
super.update()
}
}
@RegisterTileEntity("big_steam_boiler")
class TileBigSteamBoiler : TileMultiblock(), ITickable {
override fun getMultiblock(): Multiblock = MultiblockBigSteamBoiler
val input = Tank(
capacity = 16_000,
allowInput = true,
allowOutput = false,
fluidFilter = { it.fluid.name == "water" }
).apply { clientFluidName = "water" }
val output = Tank(
capacity = 128_000,
allowInput = false,
allowOutput = true,
fluidFilter = { it.fluid.name == "steam" }
).apply { clientFluidName = "steam" }
val node = HeatNode(ref)
val fluidMod = ModuleFluidHandler(input, output,
capabilityFilter = ModuleFluidHandler.ALLOW_NONE
)
val ioModule: ModuleMultiblockIO = ModuleMultiblockIO(
facing = { facing },
connectionSpots = flatten(
ModuleMultiblockIO.connectionCube(FLUID_HANDLER!!,
BlockPos(-1, 0, -2), BlockPos(1, 3, 0),
getter = { fluidMod }
),
ModuleMultiblockIO.connectionArea(HEAT_NODE_HANDLER!!,
BlockPos(-1, 0, -2), BlockPos(1, 0, 0), EnumFacing.DOWN,
getter = { if (active) heatMod else null }
)
)
)
val heatMod = ModuleHeat(node,
capabilityFilter = { false },
connectableDirections = { ioModule.getHeatConnectPoints() }
)
override val multiblockModule = ModuleMultiblockCenter(
multiblockStructure = getMultiblock(),
facingGetter = this::facing,
capabilityGetter = ioModule::getCapability
)
val extract = ModuleFluidExporter(output,
ports = { listOf(facing.rotatePoint(BlockPos.ORIGIN, BlockPos(0, 4, -1)) to EnumFacing.DOWN) }
)
val boiler = ModuleSteamBoiler(node, input, output, Config.multiblockBoilerMaxProduction)
init {
initModules(multiblockModule, ioModule, heatMod, fluidMod, boiler, extract, ModuleOpenGui())
}
@DoNotRemove
override fun update() {
super.update()
}
}
@RegisterTileEntity("big_electric_furnace")
class TileBigElectricFurnace : TileMultiblock(), ITickable {
override fun getMultiblock(): Multiblock = MultiblockBigElectricFurnace
val node = ElectricNode(ref)
val inventory = Inventory(2)
val inConveyor = ModuleConveyorBelt({ facing }, hardLimit = 8f)
val outConveyor = ModuleConveyorBelt({ facing }, frontOffset = 3)
val openGuiModule = ModuleOpenGui()
val ioModule: ModuleMultiblockIO = ModuleMultiblockIO(
facing = { facing },
connectionSpots = listOf(
ConnectionSpot(
capability = ELECTRIC_NODE_HANDLER!!,
pos = BlockPos(0, 1, -1),
side = EnumFacing.UP,
getter = { energyModule }
),
ConnectionSpot(ITEM_HANDLER!!, BlockPos(0, 0, 0), EnumFacing.SOUTH,
getter = { InventoryCapabilityFilter(inventory, listOf(0), emptyList()) }
),
ConnectionSpot(ITEM_HANDLER!!, BlockPos(0, 0, -1), EnumFacing.SOUTH,
getter = { InventoryCapabilityFilter(inventory, listOf(0), emptyList()) }
),
ConnectionSpot(ITEM_HANDLER!!, BlockPos(0, 0, -2), EnumFacing.NORTH,
getter = { InventoryCapabilityFilter(inventory, emptyList(), listOf(1)) }
),
ConnectionSpot(CONVEYOR_BELT!!, BlockPos(0, 0, 0), null,
getter = { if (active) inConveyor else null }
),
ConnectionSpot(CONVEYOR_BELT!!, BlockPos(0, 0, -2), null,
getter = { if (active) outConveyor else null }
)
)
)
val energyModule = ModuleElectricity(
electricNodes = listOf(node),
canConnectAtSide = ioModule::canConnectAtSide,
connectableDirections = ioModule::getElectricConnectPoints
)
val storageModule = ModuleInternalStorage(
mainNode = node,
initialCapacity = 10_000,
initialMaxChargeSpeed = 2000.0,
initialLowerVoltageLimit = ElectricConstants.TIER_1_MACHINES_MIN_VOLTAGE - 10.0,
initialUpperVoltageLimit = ElectricConstants.TIER_1_MACHINES_MIN_VOLTAGE
)
val invModule = ModuleInventory(
inventory = inventory,
capabilityFilter = ModuleInventory.ALLOW_NONE
)
val processModule = ModuleElectricProcessing(
craftingProcess = FurnaceCraftingProcess(invModule, 0, 1),
storage = storageModule,
workingRate = 10f,
costPerTick = Config.bigElectricFurnaceMaxConsumption.toFloat()
)
override val multiblockModule = ModuleMultiblockCenter(
multiblockStructure = getMultiblock(),
facingGetter = { facing },
capabilityGetter = ioModule::getCapability
)
val spawner1 = ParticleSpawner(10.0, EnumParticleTypes.FLAME, Blocks.FIRE.defaultState) {
facing.rotateBox(vec3Of(0.5), vec3Of(0.px, 13.px, 7.px).createAABBUsing(vec3Of(16.px, 18.px, 8.px))).offset(pos)
}
val spawner2 = ParticleSpawner(10.0, EnumParticleTypes.FLAME, Blocks.FIRE.defaultState) {
facing.rotateBox(vec3Of(0.5), vec3Of(0.px, 13.px, (-23).px).createAABBUsing(vec3Of(16.px, 18.px, (-24).px))).offset(pos)
}
init {
initModules(
multiblockModule, energyModule, storageModule, processModule, invModule, openGuiModule,
ioModule, inConveyor, outConveyor
)
}
@DoNotRemove
override fun update() {
super.update()
if (world.isServer && container.shouldTick(20)) {
val stack = inventory.extractItem(1, 64, true)
if (stack.isNotEmpty) {
if (outConveyor.addItem(stack, true)) {
val realStack = inventory.extractItem(1, 64, false)
outConveyor.addItem(realStack, false)
}
}
}
if (world.isServer || !processModule.working) return
if (Config.enableMachineParticles == 1) {
spawner1.spawn(world)
spawner2.spawn(world)
}
}
}
| 412 | 0.974556 | 1 | 0.974556 | game-dev | MEDIA | 0.983893 | game-dev | 0.947139 | 1 | 0.947139 |
Gaby-Station/Gaby-Station | 1,781 | Content.Client/SSDIndicator/SSDIndicatorSystem.cs | // SPDX-FileCopyrightText: 2023 Morb <14136326+Morb0@users.noreply.github.com>
// SPDX-FileCopyrightText: 2024 AJCM-git <60196617+AJCM-git@users.noreply.github.com>
// SPDX-FileCopyrightText: 2024 Kot <1192090+koteq@users.noreply.github.com>
// SPDX-FileCopyrightText: 2024 Piras314 <p1r4s@proton.me>
// SPDX-FileCopyrightText: 2025 Aiden <28298836+Aidenkrz@users.noreply.github.com>
//
// SPDX-License-Identifier: AGPL-3.0-or-later
using Content.Shared.CCVar;
using Content.Shared.Mind.Components;
using Content.Shared.Mobs.Systems;
using Content.Shared.NPC;
using Content.Shared.SSDIndicator;
using Content.Shared.StatusIcon.Components;
using Robust.Shared.Configuration;
using Robust.Shared.Prototypes;
namespace Content.Client.SSDIndicator;
/// <summary>
/// Handles displaying SSD indicator as status icon
/// </summary>
public sealed class SSDIndicatorSystem : EntitySystem
{
[Dependency] private readonly IPrototypeManager _prototype = default!;
[Dependency] private readonly IConfigurationManager _cfg = default!;
[Dependency] private readonly MobStateSystem _mobState = default!;
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<SSDIndicatorComponent, GetStatusIconsEvent>(OnGetStatusIcon);
}
private void OnGetStatusIcon(EntityUid uid, SSDIndicatorComponent component, ref GetStatusIconsEvent args)
{
if (component.IsSSD &&
_cfg.GetCVar(CCVars.ICShowSSDIndicator) &&
!_mobState.IsDead(uid) &&
!HasComp<ActiveNPCComponent>(uid) &&
TryComp<MindContainerComponent>(uid, out var mindContainer) &&
mindContainer.ShowExamineInfo)
{
args.StatusIcons.Add(_prototype.Index(component.Icon));
}
}
} | 412 | 0.779766 | 1 | 0.779766 | game-dev | MEDIA | 0.475919 | game-dev | 0.615665 | 1 | 0.615665 |
TerraFirmaCraft/TerraFirmaCraft | 4,334 | src/main/java/net/dries007/tfc/common/recipes/BloomeryRecipe.java | /*
* Licensed under the EUPL, Version 1.2.
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12
*/
package net.dries007.tfc.common.recipes;
import com.mojang.serialization.Codec;
import com.mojang.serialization.MapCodec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.minecraft.core.HolderLookup;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.ByteBufCodecs;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.RecipeSerializer;
import net.minecraft.world.item.crafting.RecipeType;
import net.neoforged.neoforge.common.crafting.SizedIngredient;
import net.neoforged.neoforge.fluids.FluidStack;
import net.neoforged.neoforge.fluids.crafting.SizedFluidIngredient;
import org.jetbrains.annotations.Nullable;
import net.dries007.tfc.common.recipes.outputs.ItemStackProvider;
public class BloomeryRecipe implements INoopInputRecipe
{
public static final MapCodec<BloomeryRecipe> CODEC = RecordCodecBuilder.mapCodec(i -> i.group(
SizedFluidIngredient.FLAT_CODEC.fieldOf("fluid").forGetter(c -> c.inputFluid),
SizedIngredient.FLAT_CODEC.fieldOf("catalyst").forGetter(c -> c.catalyst),
ItemStackProvider.CODEC.fieldOf("result").forGetter(c -> c.result),
Codec.INT.fieldOf("duration").forGetter(c -> c.duration)
).apply(i, BloomeryRecipe::new));
public static final StreamCodec<RegistryFriendlyByteBuf, BloomeryRecipe> STREAM_CODEC = StreamCodec.composite(
SizedFluidIngredient.STREAM_CODEC, c -> c.inputFluid,
SizedIngredient.STREAM_CODEC, c -> c.catalyst,
ItemStackProvider.STREAM_CODEC, c -> c.result,
ByteBufCodecs.VAR_INT, c -> c.duration,
BloomeryRecipe::new
);
private final SizedFluidIngredient inputFluid;
private final SizedIngredient catalyst;
private final ItemStackProvider result;
private final int duration;
public BloomeryRecipe(SizedFluidIngredient inputFluid, SizedIngredient catalyst, ItemStackProvider result, int duration)
{
this.inputFluid = inputFluid;
this.catalyst = catalyst;
this.result = result;
this.duration = duration;
}
public int getDuration()
{
return duration;
}
public SizedIngredient getCatalyst()
{
return catalyst;
}
public SizedFluidIngredient getInputFluid()
{
return inputFluid;
}
/**
* @return {@code true} if {@code stack} could be melted down to form part of the primary (fluid) input to this recipe.
*/
public boolean matchesInput(ItemStack stack)
{
return consumeInput(stack) != null;
}
/**
* @return {@code true} if {@code stack} could form part of the primary (fluid) input to this recipe.
*/
public boolean matchesInput(FluidStack stack)
{
return inputFluid.ingredient().test(stack);
}
/**
* @return {@code true} if {@code stack} is the correct catalyst for this recipe.
*/
public boolean matchesCatalyst(ItemStack stack)
{
return catalyst.test(stack);
}
/**
* @return The fluid that would be produced by the primary input {@code stack}, or {@code null} if {@code stack} is not a primary input.
*/
public @Nullable FluidStack consumeInput(ItemStack stack)
{
final HeatingRecipe heat = HeatingRecipe.getRecipe(stack);
if (heat != null)
{
// Don't test amount here, because we just want to know if this stack melts into the correct metal - not how much
final FluidStack fluid = heat.assembleFluid(stack);
if (matchesInput(fluid))
{
return fluid;
}
}
return null;
}
public ItemStack assembleOutput()
{
return result.getEmptyStack();
}
@Override
public ItemStack getResultItem(HolderLookup.Provider registries)
{
return result.getEmptyStack();
}
@Override
public RecipeSerializer<?> getSerializer()
{
return TFCRecipeSerializers.BLOOMERY.get();
}
@Override
public RecipeType<?> getType()
{
return TFCRecipeTypes.BLOOMERY.get();
}
}
| 412 | 0.858376 | 1 | 0.858376 | game-dev | MEDIA | 0.827235 | game-dev | 0.917108 | 1 | 0.917108 |
SonarSonic/Flux-Networks | 3,912 | src/main/java/sonar/fluxnetworks/client/gui/tab/GuiTabDetailedSelection.java | package sonar.fluxnetworks.client.gui.tab;
import com.mojang.blaze3d.systems.RenderSystem;
import net.minecraft.ChatFormatting;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.network.chat.Component;
import net.minecraft.world.entity.player.Player;
import sonar.fluxnetworks.api.FluxConstants;
import sonar.fluxnetworks.api.FluxTranslate;
import sonar.fluxnetworks.api.energy.EnergyType;
import sonar.fluxnetworks.common.connection.*;
import sonar.fluxnetworks.register.ClientMessages;
import javax.annotation.Nonnull;
import java.util.List;
public class GuiTabDetailedSelection extends GuiTabSelection {
private int timer = 0;
public GuiTabDetailedSelection(@Nonnull FluxMenu menu, @Nonnull Player player) {
super(menu, player);
mGridHeight = 20;
mGridPerPage = 6;
mElementWidth = 146;
mElementHeight = 19;
}
@Override
protected void renderBarAndName(GuiGraphics gr, FluxNetwork element, int x, int y, boolean selected) {
blitF(gr, x, y, mElementWidth, mElementHeight, 0, 448, mElementWidth * 2, mElementHeight * 2);
RenderSystem.setShaderColor(1.0f, 1.0f, 1.0f, 1.0f);
gr.drawString(font, element.getNetworkName(), x + 4, y + 2, selected ? 0xffffff : 0x606060);
gr.pose().pushPose();
gr.pose().scale(0.75f, 0.75f, 1);
String text = "C: " + element.getStatistics().getConnectionCount();
text += ", I: " + EnergyType.FE.getUsageCompact(element.getStatistics().energyInput);
text += ", O: " + EnergyType.FE.getUsageCompact(element.getStatistics().energyOutput);
text += ", T: " + element.getStatistics().averageTickMicro + " \u00b5s/t";
gr.drawString(font, text,
(int) ((x + 4) / 0.75), (int) ((y + 11) / 0.75), selected ? 0xffffff : 0x808080);
gr.pose().popPose();
}
@Override
protected List<Component> getElementTooltips(@Nonnull FluxNetwork element) {
final List<Component> components = super.getElementTooltips(element);
final NetworkStatistics stats = element.getStatistics();
components.add(FluxTranslate.PLUGS.makeComponent().append(ChatFormatting.GRAY + ": " +
ChatFormatting.RESET + stats.fluxPlugCount));
components.add(FluxTranslate.POINTS.makeComponent().append(ChatFormatting.GRAY + ": " +
ChatFormatting.RESET + stats.fluxPointCount));
components.add(FluxTranslate.STORAGES.makeComponent().append(ChatFormatting.GRAY + ": " +
ChatFormatting.RESET + stats.fluxStorageCount));
components.add(FluxTranslate.CONTROLLERS.makeComponent().append(ChatFormatting.GRAY + ": " +
ChatFormatting.RESET + stats.fluxControllerCount));
components.add(FluxTranslate.INPUT.makeComponent().append(ChatFormatting.GRAY + ": " + ChatFormatting.RESET +
EnergyType.FE.getUsageCompact(stats.energyInput)));
components.add(FluxTranslate.OUTPUT.makeComponent().append(ChatFormatting.GRAY + ": " + ChatFormatting.RESET +
EnergyType.FE.getUsageCompact(stats.energyOutput)));
components.add(FluxTranslate.BUFFER.makeComponent().append(ChatFormatting.GRAY + ": " + ChatFormatting.RESET +
EnergyType.FE.getStorageCompact(stats.totalBuffer)));
components.add(FluxTranslate.ENERGY.makeComponent().append(ChatFormatting.GRAY + ": " + ChatFormatting.RESET +
EnergyType.FE.getStorageCompact(stats.totalEnergy)));
components.add(FluxTranslate.AVERAGE_TICK.makeComponent().append(": " + stats.averageTickMicro + " \u00b5s/t"));
return components;
}
@Override
protected void containerTick() {
super.containerTick();
if (timer == 0) {
ClientMessages.updateNetwork(getToken(), mCurrent, FluxConstants.NBT_NET_STATISTICS);
}
timer = (timer + 1) % 20;
}
}
| 412 | 0.819796 | 1 | 0.819796 | game-dev | MEDIA | 0.756154 | game-dev | 0.881142 | 1 | 0.881142 |
FalAut/Mierno | 1,234 | kubejs/startup_scripts/register/item_model_properties_register.js | ItemEvents.modelProperties((event) => {
event.register('mierno:sun_crystal', 'mierno:solar', (stack, world, living, seed) =>
stack.nbt && stack.nbt.contains('Solar') ? stack.nbt.getInt('Solar') / 100 : 0
);
event.register('mierno:moon_stone', 'mierno:lunar', (stack, world, living, seed) =>
stack.nbt && stack.nbt.contains('Lunar') ? stack.nbt.getInt('Lunar') / 100 : 0
);
event.register('mierno:unstable_ingot', 'mierno:stable', (stack, world, living, seed) =>
stack.nbt && stack.nbt.contains('Stable') ? stack.nbt.getInt('Stable') / 100 : 0
);
event.register(
[
'mierno:addition_sigil',
'mierno:subtraction_sigil',
'mierno:multiplication_sigil',
'mierno:division_sigil',
'mierno:pseudo_inversion_sigil',
],
'mierno:activate',
(stack, world, living, seed) => (stack.hasEnchantment('mierno:activate', 1) ? 1 : 0)
);
event.register(
['potion', 'splash_potion', 'lingering_potion'],
'mierno:furious_cocktails',
(stack, world, living, seed) =>
stack.nbt && stack.nbt.contains('Potion') && stack.nbt.Potion == 'mierno:furious' ? 1 : 0
);
});
| 412 | 0.782782 | 1 | 0.782782 | game-dev | MEDIA | 0.92751 | game-dev | 0.502713 | 1 | 0.502713 |
Wynntils/Wynntils | 2,893 | common/src/main/java/com/wynntils/functions/WorldEventFunctions.java | /*
* Copyright © Wynntils 2024-2025.
* This file is released under LGPLv3. See LICENSE for full license details.
*/
package com.wynntils.functions;
import com.wynntils.core.components.Models;
import com.wynntils.core.consumers.functions.Function;
import com.wynntils.core.consumers.functions.arguments.Argument;
import com.wynntils.core.consumers.functions.arguments.FunctionArguments;
import com.wynntils.models.activities.type.WorldEvent;
import com.wynntils.utils.type.CappedValue;
import com.wynntils.utils.type.Time;
import java.util.List;
public class WorldEventFunctions {
public static class AnnihilationDryCount extends Function<Integer> {
@Override
public Integer getValue(FunctionArguments arguments) {
return Models.WorldEvent.dryAnnihilations.get();
}
@Override
protected List<String> getAliases() {
return List.of("dry_annis", "dry_anni_count");
}
}
public static class AnnihilationSunProgressFunction extends Function<CappedValue> {
@Override
public CappedValue getValue(FunctionArguments arguments) {
return Models.WorldEvent.annihilationSunBar.isActive()
? Models.WorldEvent.annihilationSunBar.getBarProgress().value()
: CappedValue.EMPTY;
}
@Override
protected List<String> getAliases() {
return List.of("sun_progress");
}
}
public static class CurrentWorldEventFunction extends Function<String> {
@Override
public String getValue(FunctionArguments arguments) {
WorldEvent currentWorldEvent = Models.WorldEvent.getCurrentWorldEvent();
if (currentWorldEvent == null) return "";
return currentWorldEvent.getName();
}
}
public static class CurrentWorldEventStartTimeFunction extends Function<Time> {
@Override
public Time getValue(FunctionArguments arguments) {
WorldEvent currentWorldEvent = Models.WorldEvent.getCurrentWorldEvent();
if (currentWorldEvent == null) return Time.NONE;
return currentWorldEvent.getStartTime();
}
}
public static class WorldEventStartTimeFunction extends Function<Time> {
@Override
public Time getValue(FunctionArguments arguments) {
String worldEventName = arguments.getArgument("worldEventName").getStringValue();
WorldEvent worldEvent = Models.WorldEvent.getWorldEvent(worldEventName);
if (worldEvent == null) return Time.NONE;
return worldEvent.getStartTime();
}
@Override
public FunctionArguments.Builder getArgumentsBuilder() {
return new FunctionArguments.RequiredArgumentBuilder(
List.of(new Argument<>("worldEventName", String.class, null)));
}
}
}
| 412 | 0.501656 | 1 | 0.501656 | game-dev | MEDIA | 0.523453 | game-dev | 0.517628 | 1 | 0.517628 |
Aussiemon/Darktide-Source-Code | 18,278 | dialogues/generated/circumstance_vo_nurgle_rot.lua | -- chunkname: @dialogues/generated/circumstance_vo_nurgle_rot.lua
return function ()
define_rule({
category = "conversations_prio_0",
database = "circumstance_vo_nurgle_rot",
name = "nurgle_circumstance_conversation_five_a",
response = "nurgle_circumstance_conversation_five_a",
wwise_route = 0,
criterias = {
{
"query_context",
"concept",
OP.EQ,
"story_talk",
},
{
"user_context",
"friends_close",
OP.GTEQ,
0,
},
{
"user_context",
"enemies_close",
OP.LT,
30,
},
{
"global_context",
"circumstance_vo_id",
OP.EQ,
"circumstance_vo_nurgle_rot",
},
{
"user_context",
"threat_level",
OP.EQ,
"low, medium",
},
{
"user_context",
"pacing_state",
OP.SET_INCLUDES,
args = {
"tension_peak_fade",
"relax",
"build_up_tension_low",
"build_up_tension_no_trickle",
},
},
{
"global_context",
"level_time",
OP.GT,
120,
},
{
"faction_memory",
"nurgle_circumstance_conversation",
OP.EQ,
0,
},
{
"faction_memory",
"time_since_last_conversation",
OP.TIMEDIFF,
OP.GT,
60,
},
},
on_done = {
{
"faction_memory",
"nurgle_circumstance_conversation",
OP.ADD,
1,
},
{
"faction_memory",
"time_since_last_conversation",
OP.TIMESET,
"0",
},
},
heard_speak_routing = {
target = "mission_givers",
},
})
define_rule({
category = "vox_prio_0",
concurrent_wwise_event = "play_vox_static_loop",
database = "circumstance_vo_nurgle_rot",
name = "nurgle_circumstance_conversation_five_b",
post_wwise_event = "play_radio_static_end",
pre_wwise_event = "play_radio_static_start",
response = "nurgle_circumstance_conversation_five_b",
wwise_route = 1,
criterias = {
{
"query_context",
"concept",
OP.EQ,
"heard_speak",
},
{
"query_context",
"dialogue_name",
OP.SET_INCLUDES,
args = {
"nurgle_circumstance_conversation_five_a",
},
},
{
"user_context",
"class_name",
OP.SET_INCLUDES,
args = {
"explicator",
},
},
},
on_done = {},
heard_speak_routing = {
target = "players",
},
on_pre_rule_execution = {
delay_vo = {
duration = 0.2,
},
},
})
define_rule({
category = "conversations_prio_0",
database = "circumstance_vo_nurgle_rot",
name = "nurgle_circumstance_conversation_five_c",
response = "nurgle_circumstance_conversation_five_c",
wwise_route = 0,
criterias = {
{
"query_context",
"concept",
OP.EQ,
"heard_speak",
},
{
"query_context",
"dialogue_name",
OP.SET_INCLUDES,
args = {
"nurgle_circumstance_conversation_five_b",
},
},
},
on_done = {},
})
define_rule({
category = "conversations_prio_0",
database = "circumstance_vo_nurgle_rot",
name = "nurgle_circumstance_conversation_four_a",
response = "nurgle_circumstance_conversation_four_a",
wwise_route = 0,
criterias = {
{
"query_context",
"concept",
OP.EQ,
"story_talk",
},
{
"user_context",
"friends_close",
OP.GTEQ,
0,
},
{
"user_context",
"enemies_close",
OP.LT,
30,
},
{
"global_context",
"circumstance_vo_id",
OP.EQ,
"circumstance_vo_nurgle_rot",
},
{
"user_context",
"threat_level",
OP.EQ,
"low, medium",
},
{
"user_context",
"pacing_state",
OP.SET_INCLUDES,
args = {
"tension_peak_fade",
"relax",
"build_up_tension_low",
"build_up_tension_no_trickle",
},
},
{
"global_context",
"level_time",
OP.GT,
120,
},
{
"faction_memory",
"nurgle_circumstance_conversation",
OP.EQ,
0,
},
{
"faction_memory",
"time_since_last_conversation",
OP.TIMEDIFF,
OP.GT,
60,
},
},
on_done = {
{
"faction_memory",
"nurgle_circumstance_conversation",
OP.ADD,
1,
},
{
"faction_memory",
"time_since_last_conversation",
OP.TIMESET,
"0",
},
},
heard_speak_routing = {
target = "mission_givers",
},
})
define_rule({
category = "vox_prio_0",
concurrent_wwise_event = "play_vox_static_loop",
database = "circumstance_vo_nurgle_rot",
name = "nurgle_circumstance_conversation_four_b",
post_wwise_event = "play_radio_static_end",
pre_wwise_event = "play_radio_static_start",
response = "nurgle_circumstance_conversation_four_b",
wwise_route = 1,
criterias = {
{
"query_context",
"concept",
OP.EQ,
"heard_speak",
},
{
"query_context",
"dialogue_name",
OP.SET_INCLUDES,
args = {
"nurgle_circumstance_conversation_four_a",
},
},
{
"user_context",
"class_name",
OP.SET_INCLUDES,
args = {
"explicator",
},
},
},
on_done = {},
heard_speak_routing = {
target = "players",
},
on_pre_rule_execution = {
delay_vo = {
duration = 0.2,
},
},
})
define_rule({
category = "conversations_prio_0",
database = "circumstance_vo_nurgle_rot",
name = "nurgle_circumstance_conversation_four_c",
response = "nurgle_circumstance_conversation_four_c",
wwise_route = 0,
criterias = {
{
"query_context",
"concept",
OP.EQ,
"heard_speak",
},
{
"query_context",
"dialogue_name",
OP.SET_INCLUDES,
args = {
"nurgle_circumstance_conversation_four_b",
},
},
},
on_done = {},
})
define_rule({
category = "conversations_prio_0",
database = "circumstance_vo_nurgle_rot",
name = "nurgle_circumstance_conversation_one_a",
response = "nurgle_circumstance_conversation_one_a",
wwise_route = 0,
criterias = {
{
"query_context",
"concept",
OP.EQ,
"story_talk",
},
{
"user_context",
"friends_close",
OP.GTEQ,
0,
},
{
"user_context",
"enemies_close",
OP.LT,
30,
},
{
"global_context",
"circumstance_vo_id",
OP.EQ,
"circumstance_vo_nurgle_rot",
},
{
"user_context",
"threat_level",
OP.EQ,
"low, medium",
},
{
"user_context",
"pacing_state",
OP.SET_INCLUDES,
args = {
"tension_peak_fade",
"relax",
"build_up_tension_low",
"build_up_tension_no_trickle",
},
},
{
"global_context",
"level_time",
OP.GT,
120,
},
{
"faction_memory",
"nurgle_circumstance_conversation",
OP.EQ,
0,
},
{
"faction_memory",
"time_since_last_conversation",
OP.TIMEDIFF,
OP.GT,
60,
},
},
on_done = {
{
"faction_memory",
"nurgle_circumstance_conversation",
OP.ADD,
1,
},
{
"faction_memory",
"time_since_last_conversation",
OP.TIMESET,
"0",
},
},
heard_speak_routing = {
target = "mission_givers",
},
})
define_rule({
category = "vox_prio_0",
concurrent_wwise_event = "play_vox_static_loop",
database = "circumstance_vo_nurgle_rot",
name = "nurgle_circumstance_conversation_one_b",
post_wwise_event = "play_radio_static_end",
pre_wwise_event = "play_radio_static_start",
response = "nurgle_circumstance_conversation_one_b",
wwise_route = 1,
criterias = {
{
"query_context",
"concept",
OP.EQ,
"heard_speak",
},
{
"query_context",
"dialogue_name",
OP.SET_INCLUDES,
args = {
"nurgle_circumstance_conversation_one_a",
},
},
{
"user_context",
"class_name",
OP.SET_INCLUDES,
args = {
"explicator",
},
},
},
on_done = {},
heard_speak_routing = {
target = "players",
},
on_pre_rule_execution = {
delay_vo = {
duration = 0.2,
},
},
})
define_rule({
category = "conversations_prio_0",
database = "circumstance_vo_nurgle_rot",
name = "nurgle_circumstance_conversation_one_c",
response = "nurgle_circumstance_conversation_one_c",
wwise_route = 0,
criterias = {
{
"query_context",
"concept",
OP.EQ,
"heard_speak",
},
{
"query_context",
"dialogue_name",
OP.SET_INCLUDES,
args = {
"nurgle_circumstance_conversation_one_b",
},
},
},
on_done = {},
})
define_rule({
category = "conversations_prio_0",
database = "circumstance_vo_nurgle_rot",
name = "nurgle_circumstance_conversation_three_a",
response = "nurgle_circumstance_conversation_three_a",
wwise_route = 0,
criterias = {
{
"query_context",
"concept",
OP.EQ,
"story_talk",
},
{
"user_context",
"friends_close",
OP.GTEQ,
0,
},
{
"user_context",
"enemies_close",
OP.LT,
30,
},
{
"global_context",
"circumstance_vo_id",
OP.EQ,
"circumstance_vo_nurgle_rot",
},
{
"user_context",
"threat_level",
OP.EQ,
"low",
},
{
"user_context",
"pacing_state",
OP.SET_INCLUDES,
args = {
"tension_peak_fade",
"relax",
"build_up_tension_low",
"build_up_tension_no_trickle",
},
},
{
"global_context",
"level_time",
OP.GT,
120,
},
{
"faction_memory",
"nurgle_circumstance_conversation",
OP.EQ,
0,
},
{
"faction_memory",
"time_since_last_conversation",
OP.TIMEDIFF,
OP.GT,
60,
},
},
on_done = {
{
"faction_memory",
"nurgle_circumstance_conversation",
OP.ADD,
1,
},
{
"faction_memory",
"time_since_last_conversation",
OP.TIMESET,
"0",
},
},
heard_speak_routing = {
target = "mission_givers",
},
})
define_rule({
category = "vox_prio_0",
concurrent_wwise_event = "play_vox_static_loop",
database = "circumstance_vo_nurgle_rot",
name = "nurgle_circumstance_conversation_three_b",
post_wwise_event = "play_radio_static_end",
pre_wwise_event = "play_radio_static_start",
response = "nurgle_circumstance_conversation_three_b",
wwise_route = 1,
criterias = {
{
"query_context",
"concept",
OP.EQ,
"heard_speak",
},
{
"query_context",
"dialogue_name",
OP.SET_INCLUDES,
args = {
"nurgle_circumstance_conversation_three_a",
},
},
{
"user_context",
"class_name",
OP.SET_INCLUDES,
args = {
"explicator",
},
},
},
on_done = {},
heard_speak_routing = {
target = "players",
},
on_pre_rule_execution = {
delay_vo = {
duration = 0.2,
},
},
})
define_rule({
category = "conversations_prio_0",
database = "circumstance_vo_nurgle_rot",
name = "nurgle_circumstance_conversation_three_c",
response = "nurgle_circumstance_conversation_three_c",
wwise_route = 0,
criterias = {
{
"query_context",
"concept",
OP.EQ,
"heard_speak",
},
{
"query_context",
"dialogue_name",
OP.SET_INCLUDES,
args = {
"nurgle_circumstance_conversation_three_b",
},
},
},
on_done = {},
})
define_rule({
category = "conversations_prio_0",
database = "circumstance_vo_nurgle_rot",
name = "nurgle_circumstance_conversation_two_a",
response = "nurgle_circumstance_conversation_two_a",
wwise_route = 0,
criterias = {
{
"query_context",
"concept",
OP.EQ,
"story_talk",
},
{
"user_context",
"friends_close",
OP.GTEQ,
0,
},
{
"user_context",
"enemies_close",
OP.LT,
30,
},
{
"global_context",
"circumstance_vo_id",
OP.EQ,
"circumstance_vo_nurgle_rot",
},
{
"user_context",
"threat_level",
OP.EQ,
"low, medium",
},
{
"user_context",
"pacing_state",
OP.SET_INCLUDES,
args = {
"tension_peak_fade",
"relax",
"build_up_tension_low",
"build_up_tension_no_trickle",
},
},
{
"global_context",
"level_time",
OP.GT,
120,
},
{
"faction_memory",
"nurgle_circumstance_conversation",
OP.EQ,
0,
},
{
"faction_memory",
"time_since_last_conversation",
OP.TIMEDIFF,
OP.GT,
60,
},
},
on_done = {
{
"faction_memory",
"nurgle_circumstance_conversation",
OP.ADD,
1,
},
{
"faction_memory",
"time_since_last_conversation",
OP.TIMESET,
"0",
},
},
heard_speak_routing = {
target = "mission_givers",
},
})
define_rule({
category = "vox_prio_0",
concurrent_wwise_event = "play_vox_static_loop",
database = "circumstance_vo_nurgle_rot",
name = "nurgle_circumstance_conversation_two_b",
post_wwise_event = "play_radio_static_end",
pre_wwise_event = "play_radio_static_start",
response = "nurgle_circumstance_conversation_two_b",
wwise_route = 1,
criterias = {
{
"query_context",
"concept",
OP.EQ,
"heard_speak",
},
{
"query_context",
"dialogue_name",
OP.SET_INCLUDES,
args = {
"nurgle_circumstance_conversation_two_a",
},
},
{
"user_context",
"class_name",
OP.SET_INCLUDES,
args = {
"explicator",
},
},
},
on_done = {},
heard_speak_routing = {
target = "players",
},
on_pre_rule_execution = {
delay_vo = {
duration = 0.2,
},
},
})
define_rule({
category = "conversations_prio_0",
database = "circumstance_vo_nurgle_rot",
name = "nurgle_circumstance_conversation_two_c",
response = "nurgle_circumstance_conversation_two_c",
wwise_route = 0,
criterias = {
{
"query_context",
"concept",
OP.EQ,
"heard_speak",
},
{
"query_context",
"dialogue_name",
OP.SET_INCLUDES,
args = {
"nurgle_circumstance_conversation_two_b",
},
},
},
on_done = {},
})
define_rule({
category = "player_prio_2",
database = "circumstance_vo_nurgle_rot",
name = "nurgle_circumstance_prop_alive",
response = "nurgle_circumstance_prop_alive",
wwise_route = 0,
criterias = {
{
"query_context",
"concept",
OP.EQ,
"look_at",
},
{
"query_context",
"look_at_tag",
OP.EQ,
"nurgle_circumstance_prop_alive",
},
{
"user_context",
"threat_level",
OP.SET_INCLUDES,
args = {
"low",
"medium",
"high",
},
},
{
"user_context",
"enemies_close",
OP.LT,
40,
},
{
"faction_memory",
"nurgle_circumstance_prop",
OP.TIMEDIFF,
OP.GT,
180,
},
},
on_done = {
{
"faction_memory",
"nurgle_circumstance_prop",
OP.TIMESET,
},
},
})
define_rule({
category = "player_prio_2",
database = "circumstance_vo_nurgle_rot",
name = "nurgle_circumstance_prop_growth",
response = "nurgle_circumstance_prop_growth",
wwise_route = 0,
criterias = {
{
"query_context",
"concept",
OP.EQ,
"look_at",
},
{
"query_context",
"look_at_tag",
OP.EQ,
"nurgle_circumstance_prop_growth",
},
{
"user_context",
"threat_level",
OP.SET_INCLUDES,
args = {
"low",
"medium",
"high",
},
},
{
"user_context",
"enemies_close",
OP.LT,
40,
},
{
"faction_memory",
"nurgle_circumstance_prop",
OP.TIMEDIFF,
OP.GT,
180,
},
},
on_done = {
{
"faction_memory",
"nurgle_circumstance_prop",
OP.TIMESET,
},
},
})
define_rule({
category = "player_prio_2",
database = "circumstance_vo_nurgle_rot",
name = "nurgle_circumstance_prop_shrine",
response = "nurgle_circumstance_prop_shrine",
wwise_route = 0,
criterias = {
{
"query_context",
"concept",
OP.EQ,
"look_at",
},
{
"query_context",
"look_at_tag",
OP.EQ,
"nurgle_circumstance_prop_shrine",
},
{
"user_context",
"threat_level",
OP.SET_INCLUDES,
args = {
"low",
"medium",
"high",
},
},
{
"user_context",
"enemies_close",
OP.LT,
40,
},
{
"faction_memory",
"nurgle_circumstance_prop",
OP.TIMEDIFF,
OP.GT,
180,
},
},
on_done = {
{
"faction_memory",
"nurgle_circumstance_prop",
OP.TIMESET,
},
},
})
define_rule({
category = "vox_prio_0",
concurrent_wwise_event = "play_vox_static_loop",
database = "circumstance_vo_nurgle_rot",
name = "nurgle_circumstance_start_a",
response = "nurgle_circumstance_start_a",
wwise_route = 1,
criterias = {
{
"query_context",
"concept",
OP.EQ,
"start_banter",
},
{
"global_context",
"circumstance_vo_id",
OP.EQ,
"circumstance_vo_nurgle_rot",
},
{
"user_context",
"class_name",
OP.SET_INCLUDES,
args = {
"sergeant",
"pilot",
"tech_priest",
"explicator",
},
},
{
"faction_memory",
"start_banter",
OP.EQ,
0,
},
},
on_done = {
{
"faction_memory",
"start_banter",
OP.ADD,
1,
},
},
heard_speak_routing = {
target = "players",
},
})
define_rule({
category = "conversations_prio_0",
database = "circumstance_vo_nurgle_rot",
name = "nurgle_circumstance_start_b",
response = "nurgle_circumstance_start_b",
wwise_route = 0,
criterias = {
{
"query_context",
"concept",
OP.EQ,
"heard_speak",
},
{
"query_context",
"dialogue_name",
OP.SET_INCLUDES,
args = {
"nurgle_circumstance_start_a",
},
},
},
on_done = {},
heard_speak_routing = {
target = "all",
},
on_pre_rule_execution = {
delay_vo = {
duration = 0.2,
},
},
})
define_rule({
category = "vox_prio_0",
concurrent_wwise_event = "play_vox_static_loop",
database = "circumstance_vo_nurgle_rot",
name = "nurgle_circumstance_start_c",
post_wwise_event = "play_radio_static_end",
pre_wwise_event = "play_radio_static_start",
response = "nurgle_circumstance_start_c",
wwise_route = 1,
criterias = {
{
"query_context",
"concept",
OP.EQ,
"heard_speak",
},
{
"query_context",
"dialogue_name",
OP.SET_INCLUDES,
args = {
"nurgle_circumstance_start_b",
},
},
{
"user_context",
"class_name",
OP.SET_INCLUDES,
args = {
"tech_priest",
},
},
},
on_done = {},
heard_speak_routing = {
target = "players",
},
on_pre_rule_execution = {
delay_vo = {
duration = 0.2,
},
},
})
end
| 412 | 0.922413 | 1 | 0.922413 | game-dev | MEDIA | 0.558176 | game-dev | 0.699359 | 1 | 0.699359 |
gscept/nebula-trifid | 8,904 | code/extlibs/bullet/bullet/src/BulletCollision/CollisionDispatch/btConvex2dConvex2dAlgorithm.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.
*/
#include "btConvex2dConvex2dAlgorithm.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"
#include "BulletCollision/CollisionDispatch/btCollisionObjectWrapper.h"
btConvex2dConvex2dAlgorithm::CreateFunc::CreateFunc(btSimplexSolverInterface* simplexSolver, btConvexPenetrationDepthSolver* pdSolver)
{
m_numPerturbationIterations = 0;
m_minimumPointsPerturbationThreshold = 3;
m_simplexSolver = simplexSolver;
m_pdSolver = pdSolver;
}
btConvex2dConvex2dAlgorithm::CreateFunc::~CreateFunc()
{
}
btConvex2dConvex2dAlgorithm::btConvex2dConvex2dAlgorithm(btPersistentManifold* mf,const btCollisionAlgorithmConstructionInfo& ci,const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap,btSimplexSolverInterface* simplexSolver, btConvexPenetrationDepthSolver* pdSolver,int numPerturbationIterations, int minimumPointsPerturbationThreshold)
: btActivatingCollisionAlgorithm(ci,body0Wrap,body1Wrap),
m_simplexSolver(simplexSolver),
m_pdSolver(pdSolver),
m_ownManifold (false),
m_manifoldPtr(mf),
m_lowLevelOfDetail(false),
m_numPerturbationIterations(numPerturbationIterations),
m_minimumPointsPerturbationThreshold(minimumPointsPerturbationThreshold)
{
(void)body0Wrap;
(void)body1Wrap;
}
btConvex2dConvex2dAlgorithm::~btConvex2dConvex2dAlgorithm()
{
if (m_ownManifold)
{
if (m_manifoldPtr)
m_dispatcher->releaseManifold(m_manifoldPtr);
}
}
void btConvex2dConvex2dAlgorithm ::setLowLevelOfDetail(bool useLowLevel)
{
m_lowLevelOfDetail = useLowLevel;
}
extern btScalar gContactBreakingThreshold;
//
// Convex-Convex collision algorithm
//
void btConvex2dConvex2dAlgorithm ::processCollision (const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut)
{
if (!m_manifoldPtr)
{
//swapped?
m_manifoldPtr = m_dispatcher->getNewManifold(body0Wrap->getCollisionObject(),body1Wrap->getCollisionObject());
m_ownManifold = true;
}
resultOut->setPersistentManifold(m_manifoldPtr);
//comment-out next line to test multi-contact generation
//resultOut->getPersistentManifold()->clearManifold();
const btConvexShape* min0 = static_cast<const btConvexShape*>(body0Wrap->getCollisionShape());
const btConvexShape* min1 = static_cast<const btConvexShape*>(body1Wrap->getCollisionShape());
btVector3 normalOnB;
btVector3 pointOnBWorld;
{
btGjkPairDetector::ClosestPointInput input;
btGjkPairDetector gjkPairDetector(min0,min1,m_simplexSolver,m_pdSolver);
//TODO: if (dispatchInfo.m_useContinuous)
gjkPairDetector.setMinkowskiA(min0);
gjkPairDetector.setMinkowskiB(min1);
{
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 = body0Wrap->getWorldTransform();
input.m_transformB = body1Wrap->getWorldTransform();
gjkPairDetector.getClosestPoints(input,*resultOut,dispatchInfo.m_debugDraw);
btVector3 v0,v1;
btVector3 sepNormalWorldSpace;
}
if (m_ownManifold)
{
resultOut->refreshContactPoints();
}
}
btScalar btConvex2dConvex2dAlgorithm::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;
//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;
}
| 412 | 0.969135 | 1 | 0.969135 | game-dev | MEDIA | 0.983343 | game-dev | 0.978832 | 1 | 0.978832 |
vektor9999/NolvusDashboard | 8,980 | Vcc.Nolvus.Instance/Core/InstanceOptions.cs | using System;
using System.Xml;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Vcc.Nolvus.Core.Interfaces;
using Vcc.Nolvus.Core.Services;
namespace Vcc.Nolvus.Instance.Core
{
public class InstanceOptions : IInstanceOptions
{
public string Nudity { get; set; } = "FALSE";
public string AlternateENB { get; set; } = "FALSE";
public string FantasyMode { get; set; } = "FALSE";
public string HardcoreMode { get; set; } = "FALSE";
public string AlternateLeveling { get; set; } = "FALSE";
public string SkinType { get; set; } = "Smooth";
public string AlternateStart { get; set; } = "FALSE";
public string CombatAnimation { get; set; } = "Fantasy";
public string StancesPerksTree { get; set; } = "TRUE";
public string DeleveledEnemies { get; set; } = "TRUE";
public string Exhaustion { get; set; } = "TRUE";
public string NerfPA { get; set; } = "Player Only";
public string EnemiesResistance { get; set; } = "TRUE";
public string Boss { get; set; } = "TRUE";
public string Poise { get; set; } = "TRUE";
public string Gore { get; set; } = "FALSE";
public string CombatScaling { get; set; } = "Hard";
public string Controller { get; set; } = "FALSE";
public string UI { get; set; } = "Untarnished UI";
public void Load(XmlNode Node)
{
Nudity = Node["Nudity"].InnerText.Trim();
AlternateENB = Node["AlternateENB"].InnerText.Trim();
if (AlternateENB == "FALSE")
{
AlternateENB = "PICHO";
}
FantasyMode = Node["FantasyMode"].InnerText.Trim();
HardcoreMode = Node["HardcoreMode"].InnerText.Trim();
AlternateLeveling = Node["AlternateLeveling"].InnerText.Trim();
if (Node["AlternateStart"] != null)
{
AlternateStart = Node["AlternateStart"].InnerText.Trim();
}
SkinType = Node["SkinType"].InnerText.Trim();
if (Node["CombatAnimation"] != null)
{
CombatAnimation = Node["CombatAnimation"].InnerText.Trim();
}
if (Node["StancesPerksTree"] != null)
{
StancesPerksTree = Node["StancesPerksTree"].InnerText.Trim();
}
if (Node["DeleveledEnemies"] != null)
{
DeleveledEnemies = Node["DeleveledEnemies"].InnerText.Trim();
}
if (Node["Exhaustion"] != null)
{
Exhaustion = Node["Exhaustion"].InnerText.Trim();
}
if (Node["NerfPA"] != null)
{
if (Node["NerfPA"].InnerText == "TRUE")
{
NerfPA = "Player Only";
}
else if (Node["NerfPA"].InnerText == "FALSE")
{
NerfPA = "None";
}
else
{
NerfPA = Node["NerfPA"].InnerText.Trim();
}
}
if (Node["EnemiesResistance"] != null)
{
EnemiesResistance = Node["EnemiesResistance"].InnerText.Trim();
}
if (Node["Boss"] != null)
{
Boss = Node["Boss"].InnerText.Trim();
}
if (Node["Poise"] != null)
{
Poise = Node["Poise"].InnerText.Trim();
}
if (Node["Gore"] != null)
{
Gore = Node["Gore"].InnerText.Trim();
}
if (Node["CombatScaling"] != null)
{
CombatScaling = Node["CombatScaling"].InnerText.Trim();
}
if (Node["Controller"] != null)
{
Controller = Node["Controller"].InnerText.Trim();
}
if (Node["UI"] != null)
{
UI = Node["UI"].InnerText.Trim();
}
ServiceSingleton.Logger.Log(string.Format("Instance nudity : {0}", Nudity));
ServiceSingleton.Logger.Log(string.Format("Instance enb : {0}", AlternateENB));
ServiceSingleton.Logger.Log(string.Format("Instance fantasy mode : {0}", FantasyMode));
ServiceSingleton.Logger.Log(string.Format("Instance hardcore mode : {0}", HardcoreMode));
ServiceSingleton.Logger.Log(string.Format("Instance alternate levelling : {0}", AlternateLeveling));
ServiceSingleton.Logger.Log(string.Format("Instance alternate start : {0}", AlternateStart));
ServiceSingleton.Logger.Log(string.Format("Instance skin type : {0}", SkinType));
ServiceSingleton.Logger.Log(string.Format("Combat animation : {0}", CombatAnimation));
ServiceSingleton.Logger.Log(string.Format("Stances perks tree : {0}", StancesPerksTree));
ServiceSingleton.Logger.Log(string.Format("Deleveled enemies : {0}", DeleveledEnemies));
ServiceSingleton.Logger.Log(string.Format("Exhaustion : {0}", Exhaustion));
ServiceSingleton.Logger.Log(string.Format("Nerf power attacks : {0}", NerfPA));
ServiceSingleton.Logger.Log(string.Format("Enemies resistance : {0}", EnemiesResistance));
ServiceSingleton.Logger.Log(string.Format("Boss encounter : {0}", Boss));
ServiceSingleton.Logger.Log(string.Format("Poise : {0}", Poise));
ServiceSingleton.Logger.Log(string.Format("Gore : {0}", Gore));
ServiceSingleton.Logger.Log(string.Format("Combat Scaling : {0}", CombatScaling));
ServiceSingleton.Logger.Log(string.Format("Controller : {0}", Controller));
ServiceSingleton.Logger.Log(string.Format("UI : {0}", UI));
}
public void Save(XmlWriter XMLWriter)
{
XMLWriter.WriteStartElement("Options");
XMLWriter.WriteStartElement("Nudity");
XMLWriter.WriteString(Nudity.Trim());
XMLWriter.WriteEndElement();
XMLWriter.WriteStartElement("AlternateENB");
XMLWriter.WriteString(AlternateENB.Trim());
XMLWriter.WriteEndElement();
XMLWriter.WriteStartElement("FantasyMode");
XMLWriter.WriteString(FantasyMode.Trim());
XMLWriter.WriteEndElement();
XMLWriter.WriteStartElement("HardcoreMode");
XMLWriter.WriteString(HardcoreMode.Trim());
XMLWriter.WriteEndElement();
XMLWriter.WriteStartElement("AlternateLeveling");
XMLWriter.WriteString(AlternateLeveling.Trim());
XMLWriter.WriteEndElement();
XMLWriter.WriteStartElement("SkinType");
XMLWriter.WriteString(SkinType.Trim());
XMLWriter.WriteEndElement();
XMLWriter.WriteStartElement("AlternateStart");
XMLWriter.WriteString(AlternateStart.Trim());
XMLWriter.WriteEndElement();
XMLWriter.WriteStartElement("CombatAnimation");
XMLWriter.WriteString(CombatAnimation.Trim());
XMLWriter.WriteEndElement();
XMLWriter.WriteStartElement("StancesPerksTree");
XMLWriter.WriteString(StancesPerksTree.Trim());
XMLWriter.WriteEndElement();
XMLWriter.WriteStartElement("DeleveledEnemies");
XMLWriter.WriteString(DeleveledEnemies.Trim());
XMLWriter.WriteEndElement();
XMLWriter.WriteStartElement("Exhaustion");
XMLWriter.WriteString(Exhaustion.Trim());
XMLWriter.WriteEndElement();
XMLWriter.WriteStartElement("NerfPA");
XMLWriter.WriteString(NerfPA.Trim());
XMLWriter.WriteEndElement();
XMLWriter.WriteStartElement("EnemiesResistance");
XMLWriter.WriteString(EnemiesResistance.Trim());
XMLWriter.WriteEndElement();
XMLWriter.WriteStartElement("Boss");
XMLWriter.WriteString(Boss.Trim());
XMLWriter.WriteEndElement();
XMLWriter.WriteStartElement("Poise");
XMLWriter.WriteString(Poise.Trim());
XMLWriter.WriteEndElement();
XMLWriter.WriteStartElement("Gore");
XMLWriter.WriteString(Gore.Trim());
XMLWriter.WriteEndElement();
XMLWriter.WriteStartElement("CombatScaling");
XMLWriter.WriteString(CombatScaling.Trim());
XMLWriter.WriteEndElement();
XMLWriter.WriteStartElement("Controller");
XMLWriter.WriteString(Controller.Trim());
XMLWriter.WriteEndElement();
XMLWriter.WriteStartElement("UI");
XMLWriter.WriteString(UI.Trim());
XMLWriter.WriteEndElement();
XMLWriter.WriteEndElement();
}
}
}
| 412 | 0.808538 | 1 | 0.808538 | game-dev | MEDIA | 0.468547 | game-dev | 0.644228 | 1 | 0.644228 |
AcChosen/VR-Stage-Lighting | 10,800 | Packages/com.acchosen.vr-stage-lighting/Editor/VRSL_FixtureDefinitions.cs | #if UNITY_EDITOR
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System;
namespace VRSL.EditorScripts
{
[Serializable]
public struct FixtureDefintion
{
public FixtureDefintion(string n)
{
name = n;
channelNames = new string[1];
foldOut = false;
}
public string name;
public string[] channelNames;
public bool foldOut;
public void SetNewChannelSize(int size)
{
string[] newChannelNames = new string[size];
int loopVal = 0;
if(channelNames != null)
{
if(newChannelNames.Length > channelNames.Length)
{
loopVal = channelNames.Length;
}
else
{
loopVal = newChannelNames.Length;
}
for(int i = 0; i < loopVal; i++)
{
newChannelNames[i] = channelNames[i];
}
channelNames = newChannelNames;
}
else
{
channelNames = new string[1];
channelNames[0] = "";
}
}
}
[CreateAssetMenuAttribute(menuName = "VRSL/DMX Fixture Definition File", fileName = "VRSL DMX Fixture Definitions")]
[System.Serializable]
public class VRSL_FixtureDefinitions : ScriptableObject
{
[HideInInspector]
public FixtureDefintion[] definitions = new FixtureDefintion[1];
public VRSL_FixtureDefinitions()
{
if(definitions != null)
{
if(definitions.Length > 0)
{
definitions[0].channelNames = new string[1];
}
}
}
public void ForceSave()
{
//string assetPath = AssetDatabase.GetAssetPath(this.GetInstanceID());
//if(targetScene != null)
//AssetDatabase.RenameAsset(assetPath, "VRSL DMX Fixture Definitions_" + targetScene.name);
UnityEditor.EditorUtility.SetDirty(this);
UnityEditor.AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
Selection.activeObject = AssetDatabase.LoadAssetAtPath<VRSL_FixtureDefinitions>(AssetDatabase.GetAssetPath(this.GetInstanceID()));
}
public string[] GetNames()
{
string[] names = new string[definitions.Length];
for(int i = 0; i < definitions.Length; i++)
{
names[i] = definitions[i].name;
}
return names;
}
public string[] GetChannelDefinition(int defID)
{
return definitions[defID].channelNames;
}
public int DefinitionsArraySize
{
get
{
return definitions.Length;
}
set
{
FixtureDefintion[] newDefinitions = new FixtureDefintion[value];
int loopVal = 0;
if(newDefinitions.Length > definitions.Length)
{
loopVal = definitions.Length;
}
else
{
loopVal = newDefinitions.Length;
}
for(int i = 0; i < loopVal; i++)
{
newDefinitions[i] = definitions[i];
}
definitions = newDefinitions;
//definitions = new FixtureDefintion[value];
}
}
}
[CustomEditor(typeof(VRSL_FixtureDefinitions))]
public class VRSL_FixtureDefinitionss_Editor: Editor
{
void GuiLine( int i_height = 1 )
{
try{
//GUIStyle g = GUIStyle.none;
//g.fixedHeight = 6;
Rect rect = EditorGUILayout.GetControlRect(false, i_height);
rect.height = i_height;
EditorGUI.DrawRect(rect, new Color ( 0.5f,0.5f,0.5f, 1 ) );
}
catch(Exception e)
{
e.GetType();
}
}
private SerializedProperty definitions;
VRSL_FixtureDefinitions fd = null;
// SerializedObject so;
private void OnEnable()
{
// // Link the properties
fd = (VRSL_FixtureDefinitions) target;
// so = new SerializedObject(fd);
definitions = serializedObject.FindProperty("definitions");
}
public override void OnInspectorGUI()
{
DrawDefaultInspector();
serializedObject.Update();
// EditorGUI.BeginChangeCheck();
if(fd != null)
{
if(definitions.isArray)
{
int size = definitions.arraySize;
EditorGUILayout.BeginHorizontal();
int newSize = EditorGUILayout.IntField("Size", size);
newSize = Mathf.Abs(newSize);
if(GUILayout.Button("-", GUILayout.Width(25f)))
{
newSize--;
if(newSize < 1){newSize = 1;}
}
if(GUILayout.Button("+", GUILayout.Width(25f)))
{
newSize++;
}
EditorGUILayout.EndHorizontal();
if(GUILayout.Button("Save Changes"))
{
serializedObject.ApplyModifiedProperties();
fd.ForceSave();
}
GuiLine();
GUILayout.Space(25);
bool mainIncreased = false;
if (newSize != size)
{
definitions.arraySize = newSize;
fd.DefinitionsArraySize = newSize;
mainIncreased = newSize > size;
}
EditorGUI.indentLevel++;
//EditorGUI.indentLevel++;
//definitions.arraySize = EditorGUILayout.IntField("Size",definitions.arraySize);
for(int i = 0; i < newSize; i++)
{
EditorGUILayout.BeginVertical("box");
SerializedProperty defProp = definitions.GetArrayElementAtIndex(i);
SerializedProperty nameProp = defProp.FindPropertyRelative("name");
EditorGUILayout.BeginHorizontal("box");
nameProp.stringValue = EditorGUILayout.TextField("Definition " + (i+1).ToString(), nameProp.stringValue);
SerializedProperty channelNamesProp = defProp.FindPropertyRelative("channelNames");
if(i >= size && mainIncreased)
{
nameProp.stringValue = "";
if(channelNamesProp.isArray)
{
channelNamesProp.arraySize = 1;
fd.definitions[i].SetNewChannelSize(1);
SerializedProperty channel = channelNamesProp.GetArrayElementAtIndex(0);
channel.stringValue = "";
}
}
else
{
int chanSize = channelNamesProp.arraySize;
int newChanSize = chanSize;
if(GUILayout.Button("-", GUILayout.Width(25f)))
{
newChanSize--;
if(newChanSize < 1){newChanSize = 1;}
}
if(GUILayout.Button("+", GUILayout.Width(25f)))
{
newChanSize++;
}
EditorGUILayout.EndHorizontal();
EditorGUI.indentLevel++;
EditorGUI.indentLevel++;
defProp.FindPropertyRelative("foldOut").boolValue = EditorGUILayout.Foldout(defProp.FindPropertyRelative("foldOut").boolValue, "Channels");
if(defProp.FindPropertyRelative("foldOut").boolValue)
{
if(channelNamesProp.isArray)
{
bool increased = false;
if (newChanSize != chanSize)
{
channelNamesProp.arraySize = newChanSize;
fd.definitions[i].SetNewChannelSize(newChanSize);
increased = newChanSize > chanSize;
}
EditorGUI.indentLevel++;
// EditorGUI.indentLevel++;
for (int j = 0; j < newChanSize; j++)
{
SerializedProperty channel = channelNamesProp.GetArrayElementAtIndex(j);
channel.stringValue = EditorGUILayout.TextField("Channel " + (j + 1).ToString(), channel.stringValue);
if(j == newChanSize-1 && increased)
{
channel.stringValue = "";
}
}
// EditorGUI.indentLevel--;
EditorGUI.indentLevel--;
}
}
EditorGUI.indentLevel--;
EditorGUI.indentLevel--;
}
EditorGUILayout.EndVertical();
GUILayout.Space(10);
}
EditorGUI.indentLevel--;
//EditorGUI.indentLevel--;
}
}
// if(EditorGUI.EndChangeCheck())
// {
serializedObject.ApplyModifiedProperties();
// if(fd != null)
// {
// fd.ForceSave()
// }
// }
}
}
}
#endif | 412 | 0.9072 | 1 | 0.9072 | game-dev | MEDIA | 0.857124 | game-dev | 0.959715 | 1 | 0.959715 |
FirstPersonKSP/AvionicsSystems | 1,090 | GameData/MOARdV/MAS_ASET/AutoPilotSwitch/MAS_APswitchNMLminus.cfg | PROP
{
name = MAS_APswitchNMLminus
MODEL
{
model = ASET/ASET_Props/Control/AutoPilotSwitch/AP_ButtonSwitch
}
MODULE
{
name = MASComponent
COLLIDER_EVENT
{
name = Collider
collider = SwitchPUSHcollider
sound = ASET/ASET_Props/Sounds/buttonbeep
volume = 0.5
onClick = mechjeb.SetSASSMode(7)
}
COLOR_SHIFT
{
name = Label Illumination
transform = SwitchNamePlate
variable = fc.Conditioned(fc.GetPersistentAsNumber("Backlight"))
passiveColor = 0,0,0,255
activeColor = COLOR_ASET_PUSHBUTTON_BACKLIGHT_ACTIVECOLOR
blend = true
}
COLOR_SHIFT
{
name = Border Illumination
transform = buttonBorder
passiveColor = 0,0,0,255
activeColor = COLOR_ASET_MJ_PUSHBUTTON_ACTIVECOLOR
variable = fc.Conditioned(mechjeb.GetSASSModeActive(7))
}
ANIMATION_PLAYER
{
name = Switch animation
animation = SwitchLightAnim
animationSpeed = 1.0
variable = mechjeb.GetSASSModeActive(7)
}
TEXTURE_SHIFT
{
name = Label
transform = SwitchNamePlate
layers = _MainTex _Emissive
startUV = 0.25, 0.00
}
}
}
| 412 | 0.658065 | 1 | 0.658065 | game-dev | MEDIA | 0.664585 | game-dev | 0.70571 | 1 | 0.70571 |
chronicler-software/ModularGameplayAbilities | 12,628 | Source/ModularGameplayAbilities/Private/ActorComponent/ModularAbilityExtensionComponent.cpp | // Copyright Chronicler.
#include "ActorComponent/ModularAbilityExtensionComponent.h"
#include "AbilitySystemInterface.h"
#include "ModularAbilityTags.h"
#include "ModularGameplayAbilitiesLogChannels.h"
#include "ModularGameplayTags.h"
#include "ModularPlayerState.h"
#include "Actor/ModularExperienceCharacter.h"
#include "ActorComponent/ModularAbilitySystemComponent.h"
#include "ActorComponent/ModularInputComponent.h"
#include "ActorComponent/ModularInputConfigComponent.h"
#include "Components/GameFrameworkComponentManager.h"
#include "DataAsset/IAbilityPawnDataInterface.h"
#include "Misc/UObjectToken.h"
#include UE_INLINE_GENERATED_CPP_BY_NAME(ModularAbilityExtensionComponent)
const FName UModularAbilityExtensionComponent::NAME_ActorFeatureName("ModularAbilityExtension");
UModularAbilityExtensionComponent::UModularAbilityExtensionComponent(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer)
{
PrimaryComponentTick.bStartWithTickEnabled = false;
PrimaryComponentTick.bCanEverTick = false;
SetIsReplicatedByDefault(true);
AbilitySystemComponent = nullptr;
}
void UModularAbilityExtensionComponent::InitializeAbilitySystem(UModularAbilitySystemComponent* InASC, AActor* InOwnerActor)
{
check(InASC);
check(InOwnerActor);
if (AbilitySystemComponent == InASC)
{
// The ability system component hasn't changed.
return;
}
if (AbilitySystemComponent)
{
// Clean up the old ability system component.
UninitializeAbilitySystem();
}
AModularExperienceCharacter* Pawn = GetPawnChecked<AModularExperienceCharacter>();
const AActor* ExistingAvatar = InASC->GetAvatarActor();
UE_LOG(LogModularGameplayAbilities, Verbose, TEXT("Setting up ASC [%s] on pawn [%s] owner [%s], existing [%s] "), *GetNameSafe(InASC), *GetNameSafe(Pawn), *GetNameSafe(InOwnerActor), *GetNameSafe(ExistingAvatar));
if ((ExistingAvatar != nullptr) && (ExistingAvatar != Pawn))
{
UE_LOG(LogModularGameplayAbilities, Log, TEXT("Existing avatar (authority=%d)"), ExistingAvatar->HasAuthority() ? 1 : 0);
// There is already a pawn acting as the ASC's avatar, so we need to kick it out
// This can happen on clients if they're lagged: their new pawn is spawned + possessed before the dead one is removed
ensure(!ExistingAvatar->HasAuthority());
if (UModularAbilityExtensionComponent* OtherExtensionComponent = ExistingAvatar->FindComponentByClass<UModularAbilityExtensionComponent>())
{
OtherExtensionComponent->UninitializeAbilitySystem();
}
}
AbilitySystemComponent = InASC;
AbilitySystemComponent->InitAbilityActorInfo(InOwnerActor, Pawn);
const UModularPawnComponent* ModularPawnComponent = Pawn->GetComponentByClass<UModularPawnComponent>();
if (const IAbilityPawnDataInterface* PawnData = ModularPawnComponent->GetPawnData<IAbilityPawnDataInterface>();
ensure(PawnData))
{
InASC->SetTagRelationshipMapping(PawnData->GetTagRelationshipMapping());
}
OnAbilitySystemInitialized.Broadcast();
}
void UModularAbilityExtensionComponent::UninitializeAbilitySystem()
{
if (!AbilitySystemComponent)
{
return;
}
// Uninitialize the ASC if we're still the avatar actor (otherwise another pawn already did it when they became the avatar actor)
if (AbilitySystemComponent->GetAvatarActor() == GetOwner())
{
FGameplayTagContainer AbilityTypesToIgnore;
AbilityTypesToIgnore.AddTag(ModularAbilityTags::Ability_Behavior_SurvivesDeath);
AbilitySystemComponent->CancelAbilities(nullptr, &AbilityTypesToIgnore);
AbilitySystemComponent->ClearAbilityInput();
AbilitySystemComponent->RemoveAllGameplayCues();
if (AbilitySystemComponent->GetOwnerActor() != nullptr)
{
AbilitySystemComponent->SetAvatarActor(nullptr);
}
else
{
// If the ASC doesn't have a valid owner, we need to clear *all* actor info, not just the avatar pairing
AbilitySystemComponent->ClearActorInfo();
}
OnAbilitySystemUninitialized.Broadcast();
}
AbilitySystemComponent = nullptr;
}
void UModularAbilityExtensionComponent::HandleControllerChanged()
{
if (AbilitySystemComponent && (AbilitySystemComponent->GetAvatarActor() == GetPawnChecked<APawn>()))
{
ensure(AbilitySystemComponent->AbilityActorInfo->OwnerActor == AbilitySystemComponent->GetOwnerActor());
if (AbilitySystemComponent->GetOwnerActor() == nullptr)
{
UninitializeAbilitySystem();
}
else
{
AbilitySystemComponent->RefreshAbilityActorInfo();
}
}
CheckDefaultInitialization();
}
void UModularAbilityExtensionComponent::InitializePlayerInput(UInputComponent* PlayerInputComponent)
{
const APawn* Pawn = GetPawn<APawn>();
if (!Pawn) return;
if (const APlayerController* PlayerController = GetController<APlayerController>(); !PlayerController) return;
InputActionMapping(PlayerInputComponent, Pawn);
}
void UModularAbilityExtensionComponent::InputActionMapping(UInputComponent* PlayerInputComponent, const APawn* Pawn)
{
const UModularPawnComponent* PawnExtComp = UModularPawnComponent::FindModularPawnComponent(Pawn);
if (!PawnExtComp) return;
const UModularPawnData* PawnData = PawnExtComp->GetPawnData<UModularPawnData>();
if (!PawnData) return;
const UModularInputConfig* InputConfig = PawnData->InputConfig;
if (!InputConfig) return;
if (UModularInputConfigComponent* InputConfigComponent = Cast<UModularInputConfigComponent>(PlayerInputComponent);
ensureMsgf(InputConfigComponent, TEXT("Unexpected Input Component class! The Gameplay Abilities will not be bound to their inputs. Change the input component to UInputConfigComponent or a subclass of it.")))
{
// This is where we actually bind and input action to a gameplay tag, which means that Gameplay Ability Blueprints will
// be triggered directly by these input actions Triggered events.
TArray<uint32> BindHandles;
InputConfigComponent->BindAbilityActions(InputConfig, this, &ThisClass::Input_AbilityInputTagPressed, &ThisClass::Input_AbilityInputTagReleased, /*out*/ BindHandles);
}
}
void UModularAbilityExtensionComponent::Input_AbilityInputTagPressed(FGameplayTag InputTag)
{
if (const APawn* Pawn = GetPawn<APawn>();
!Pawn)
{
return;
}
if (UModularAbilitySystemComponent* ModularASC = GetModularAbilitySystemComponent())
{
ModularASC->AbilityInputTagPressed(InputTag);
}
}
void UModularAbilityExtensionComponent::Input_AbilityInputTagReleased(FGameplayTag InputTag)
{
if (const APawn* Pawn = GetPawn<APawn>();
!Pawn)
{
return;
}
if (UModularAbilitySystemComponent* ModularASC = GetModularAbilitySystemComponent())
{
ModularASC->AbilityInputTagReleased(InputTag);
}
}
/**
* @ingroup IGameFrameworkInitStateInterface
* @{
*/
bool UModularAbilityExtensionComponent::CanChangeInitState(UGameFrameworkComponentManager* Manager,
FGameplayTag CurrentState, FGameplayTag DesiredState) const
{
check(Manager);
AModularExperienceCharacter* Pawn = GetPawnChecked<AModularExperienceCharacter>();
if (!CurrentState.IsValid()
&& DesiredState == ModularGameplayTags::InitState_Spawned)
{
// As long as we are on a valid pawn, we count as spawned
if (Pawn)
{
return true;
}
}
if (CurrentState == ModularGameplayTags::InitState_Spawned
&& DesiredState == ModularGameplayTags::InitState_DataAvailable)
{
// The player state is required.
if (!GetPlayerState<AModularPlayerState>())
{
return false;
}
// If we're authority or autonomous, we need to wait for a controller with registered ownership of the player state.
if (Pawn->GetLocalRole() != ROLE_SimulatedProxy)
{
AController* Controller = GetController<AController>();
const bool bHasControllerPairedWithPS = (Controller != nullptr) && \
(Controller->PlayerState != nullptr) && \
(Controller->PlayerState->GetOwner() == Controller);
if (!bHasControllerPairedWithPS)
{
return false;
}
}
const bool bIsLocallyControlled = Pawn->IsLocallyControlled();
const bool bIsBot = Pawn->IsBotControlled();
if (bIsLocallyControlled && !bIsBot)
{
AModularPlayerController* ModularPC = GetController<AModularPlayerController>();
// The input component and local player is required when locally controlled.
if (!Pawn->InputComponent || !ModularPC || !ModularPC->GetLocalPlayer())
{
return false;
}
}
return true;
}
else if (CurrentState == ModularGameplayTags::InitState_DataAvailable
&& DesiredState == ModularGameplayTags::InitState_DataInitialized)
{
// Wait for player state ASC and extension component.
const IAbilitySystemInterface* ModularPS = Cast<IAbilitySystemInterface>(GetPlayerState<AModularPlayerState>());
return ModularPS->GetAbilitySystemComponent() && Manager->HasFeatureReachedInitState(Pawn, UModularPawnComponent::NAME_ActorFeatureName, ModularGameplayTags::InitState_DataInitialized);
}
else if (CurrentState == ModularGameplayTags::InitState_DataInitialized
&& DesiredState == ModularGameplayTags::InitState_GameplayReady)
{
// @todo add ability initialization checks?
return true;
}
return false;
}
void UModularAbilityExtensionComponent::HandleChangeInitState(UGameFrameworkComponentManager* Manager,
const FGameplayTag CurrentState,
const FGameplayTag DesiredState)
{
if (CurrentState == ModularGameplayTags::InitState_DataAvailable
&& DesiredState == ModularGameplayTags::InitState_DataInitialized)
{
const APawn* Pawn = GetPawn<APawn>();
AModularPlayerState* ModularPS = GetPlayerState<AModularPlayerState>();
const IAbilitySystemInterface* ModularAbilityPS = Cast<IAbilitySystemInterface>(ModularPS);
UAbilitySystemComponent* ModularASC = ModularAbilityPS->GetAbilitySystemComponent();
if (!ensure(Pawn && ModularPS && ModularASC))
{
return;
}
// The player state holds the persistent data for this player (state that persists across deaths and multiple pawns).
// The ability system component and attribute sets live on the player state.
InitializeAbilitySystem(Cast<UModularAbilitySystemComponent>(ModularASC), ModularPS);
if (Pawn->InputComponent != nullptr)
{
InitializePlayerInput(Pawn->InputComponent);
}
}
}
void UModularAbilityExtensionComponent::OnActorInitStateChanged(const FActorInitStateChangedParams& Params)
{
if (Params.FeatureName == UModularPawnComponent::NAME_ActorFeatureName)
{
if (Params.FeatureState == ModularGameplayTags::InitState_DataInitialized)
{
// If the extension component says all all other components are initialized, try to progress to next state.
CheckDefaultInitialization();
}
}
}
void UModularAbilityExtensionComponent::CheckDefaultInitialization()
{
static const TArray<FGameplayTag> StateChain =
{
ModularGameplayTags::InitState_Spawned,
ModularGameplayTags::InitState_DataAvailable,
ModularGameplayTags::InitState_DataInitialized,
ModularGameplayTags::InitState_GameplayReady
};
// This will try to progress from spawned (which is only set in BeginPlay) through the data initialization stages
// until it gets to gameplay ready.
ContinueInitStateChain(StateChain);
}
/**
* @}
*/
void UModularAbilityExtensionComponent::OnRegister()
{
Super::OnRegister();
if (!GetPawn<APawn>())
{
UE_LOG(LogModularGameplayAbilities, Error,
TEXT("[UModularAbilityExtensionComponent::OnRegister] This component has been added to a blueprint whose base class is not a Pawn. To use this component, it MUST be placed on a Pawn Blueprint."));
#if WITH_EDITOR
if (GIsEditor)
{
static const FText Message = NSLOCTEXT("ModularAbilityExtensionComponent", "NotOnPawnError", "has been added to a blueprint whose base class is not a Pawn. To use this component, it MUST be placed on a Pawn Blueprint. This will cause a crash if you PIE!");
static const FName MessageLogName = TEXT("ModularAbilityExtensionComponent");
FMessageLog(MessageLogName).Error()
->AddToken(FUObjectToken::Create(this, FText::FromString(GetNameSafe(this))))
->AddToken(FTextToken::Create(Message));
FMessageLog(MessageLogName).Open();
}
#endif
}
else
{
// Register with the init state system early, this will only work if this is a game world.
RegisterInitStateFeature();
}
}
void UModularAbilityExtensionComponent::BeginPlay()
{
Super::BeginPlay();
// Listen for when the pawn extension component changes init state
BindOnActorInitStateChanged(UModularInputComponent::NAME_ActorFeatureName, FGameplayTag(), false);
// Notifies that we are done spawning, then try the rest of initialization
ensure(TryToChangeInitState(ModularGameplayTags::InitState_Spawned));
CheckDefaultInitialization();
}
void UModularAbilityExtensionComponent::EndPlay(const EEndPlayReason::Type EndPlayReason)
{
UnregisterInitStateFeature();
Super::EndPlay(EndPlayReason);
}
| 412 | 0.926138 | 1 | 0.926138 | game-dev | MEDIA | 0.981653 | game-dev | 0.643432 | 1 | 0.643432 |
gamingdotme/opensource-casino-v10 | 2,384 | casino/app/Games/TalesofEgypt/PragmaticLib/Multiple.php | <?php
namespace VanguardLTE\Games\TalesofEgypt\PragmaticLib;
class Multiple
{
public static function getBonanzaMultiple($slotArea, $gameSettings, $currentLog){
$tmp = explode(';', $gameSettings['prm']);
$tmp = explode('~', $tmp[0]);
$prm = $tmp[0]; // multiplier symbol
$prmMultipliers = explode(',',$tmp[1]); // array of possible multiplier values
// rebuild the playing field on reels
$reels = 6;
$tmpSlotArea = array_chunk($slotArea, $reels);
$currentSlotArea = [];
$k = 0;
while ($k < $reels) { // rearrange from rows to rows
$i = 0;
while ($i < $gameSettings['sh']) {
$currentSlotArea[$k][] = $tmpSlotArea[$i][$k];
$i++;
}
$k++;
}
$prmReady = [];
// go through all the coils from the end, and assign multipliers, write in the log which multiplier from which coil
foreach ($currentSlotArea as $reelKey => $reel) {
foreach (array_reverse($reel) as $symbolKey => $symbol) {
if ($symbol == $prm){
$symbolsCount = $gameSettings['sh'] - 1; // arrays start at 0. To find out how many symbols should be in the reel
$prmSymbol = $reelKey + ($reels * ($symbolsCount - $symbolKey)); // calculate position. Coil number, add to the coil position from the beginning
$prmReady[] = [
'Symbol' => $prm,
'Position' => $prmSymbol,
'Multiplier' => self::getMultiplier($currentLog,$prmMultipliers,$reelKey),
'Reel' => $reelKey
];
}
}
}
if ($prmReady) return $prmReady;
else return false;
}
private static function getMultiplier($currentLog, $prmMultipliers, $reelKey){
if ($currentLog && array_key_exists('Multipliers', $currentLog)){
foreach ($currentLog['Multipliers'] as $logMultiplier) {
if ($logMultiplier['Reel'] == $reelKey){
$multiplier = $logMultiplier['Multiplier'];
}
}
}
if (isset($multiplier)) return $multiplier;
else $multiplier = $prmMultipliers[array_rand($prmMultipliers)];
return $multiplier;
}
}
| 412 | 0.757718 | 1 | 0.757718 | game-dev | MEDIA | 0.741141 | game-dev | 0.773549 | 1 | 0.773549 |
rerun-io/egui_tiles | 18,942 | src/container/linear.rs | #![allow(clippy::tuple_array_conversions)]
use egui::{NumExt as _, Rect, emath::GuiRounding as _, pos2, vec2};
use itertools::Itertools as _;
use crate::behavior::EditAction;
use crate::{
Behavior, ContainerInsertion, DropContext, InsertionPoint, ResizeState, SimplifyAction, TileId,
Tiles, Tree, is_being_dragged,
};
// ----------------------------------------------------------------------------
/// How large of a share of space each child has, on a 1D axis.
///
/// Used for [`Linear`] containers (horizontal and vertical).
///
/// Also contains the shares for currently invisible tiles.
#[derive(Clone, Debug, Default, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct Shares {
/// How large of a share each child has.
///
/// For instance, the shares `[1, 2, 3]` means that the first child gets 1/6 of the space,
/// the second gets 2/6 and the third gets 3/6.
shares: ahash::HashMap<TileId, f32>,
}
impl Shares {
pub fn iter(&self) -> impl Iterator<Item = (&TileId, &f32)> {
self.shares.iter()
}
pub fn replace_with(&mut self, remove: TileId, new: TileId) {
if let Some(share) = self.shares.remove(&remove) {
self.shares.insert(new, share);
}
}
pub fn set_share(&mut self, id: TileId, share: f32) {
self.shares.insert(id, share);
}
/// Split the given width based on the share of the children.
pub fn split(&self, children: &[TileId], available_width: f32) -> Vec<f32> {
let mut num_shares = 0.0;
for &child in children {
num_shares += self[child];
}
if num_shares == 0.0 {
num_shares = 1.0;
}
children
.iter()
.map(|&child| available_width * self[child] / num_shares)
.collect()
}
pub fn retain(&mut self, keep: impl Fn(TileId) -> bool) {
self.shares.retain(|&child, _| keep(child));
}
}
impl<'a> IntoIterator for &'a Shares {
type Item = (&'a TileId, &'a f32);
type IntoIter = std::collections::hash_map::Iter<'a, TileId, f32>;
#[inline]
fn into_iter(self) -> Self::IntoIter {
self.shares.iter()
}
}
impl std::ops::Index<TileId> for Shares {
type Output = f32;
#[inline]
fn index(&self, id: TileId) -> &Self::Output {
self.shares.get(&id).unwrap_or(&1.0)
}
}
impl std::ops::IndexMut<TileId> for Shares {
#[inline]
fn index_mut(&mut self, id: TileId) -> &mut Self::Output {
self.shares.entry(id).or_insert(1.0)
}
}
// ----------------------------------------------------------------------------
/// The direction of a [`Linear`] container. Either horizontal or vertical.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum LinearDir {
#[default]
Horizontal,
Vertical,
}
/// Horizontal or vertical container.
#[derive(Clone, Debug, Default, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct Linear {
pub children: Vec<TileId>,
pub dir: LinearDir,
pub shares: Shares,
}
impl Linear {
pub fn new(dir: LinearDir, children: Vec<TileId>) -> Self {
Self {
children,
dir,
..Default::default()
}
}
fn visible_children<Pane>(&self, tiles: &Tiles<Pane>) -> Vec<TileId> {
self.children
.iter()
.copied()
.filter(|&child_id| tiles.is_visible(child_id))
.collect()
}
/// Create a binary split with the given split ratio in the 0.0 - 1.0 range.
///
/// The `fraction` is the fraction of the total width that the first child should get.
pub fn new_binary(dir: LinearDir, children: [TileId; 2], fraction: f32) -> Self {
debug_assert!(
(0.0..=1.0).contains(&fraction),
"Fraction should be in 0.0..=1.0"
);
let mut slf = Self {
children: children.into(),
dir,
..Default::default()
};
// We multiply the shares with 2.0 because the default share size is 1.0,
// and so we want the total share to be the same as the number of children.
slf.shares[children[0]] = 2.0 * (fraction);
slf.shares[children[1]] = 2.0 * (1.0 - fraction);
slf
}
pub fn add_child(&mut self, child: TileId) {
self.children.push(child);
}
pub fn layout<Pane>(
&mut self,
tiles: &mut Tiles<Pane>,
style: &egui::Style,
behavior: &mut dyn Behavior<Pane>,
rect: Rect,
) {
// GC:
let child_set: ahash::HashSet<TileId> = self.children.iter().copied().collect();
self.shares.retain(|id| child_set.contains(&id));
match self.dir {
LinearDir::Horizontal => {
self.layout_horizontal(tiles, style, behavior, rect);
}
LinearDir::Vertical => self.layout_vertical(tiles, style, behavior, rect),
}
}
fn layout_horizontal<Pane>(
&self,
tiles: &mut Tiles<Pane>,
style: &egui::Style,
behavior: &mut dyn Behavior<Pane>,
rect: Rect,
) {
let visible_children = self.visible_children(tiles);
let num_gaps = visible_children.len().saturating_sub(1);
let gap_width = behavior.gap_width(style);
let total_gap_width = gap_width * num_gaps as f32;
let available_width = (rect.width() - total_gap_width).at_least(0.0);
let widths = self.shares.split(&visible_children, available_width);
let mut x = rect.min.x;
for (child, width) in visible_children.iter().zip(widths) {
let child_rect = Rect::from_min_size(pos2(x, rect.min.y), vec2(width, rect.height()));
tiles.layout_tile(style, behavior, child_rect, *child);
x += width + gap_width;
}
}
fn layout_vertical<Pane>(
&self,
tiles: &mut Tiles<Pane>,
style: &egui::Style,
behavior: &mut dyn Behavior<Pane>,
rect: Rect,
) {
let visible_children = self.visible_children(tiles);
let num_gaps = visible_children.len().saturating_sub(1);
let gap_height = behavior.gap_width(style);
let total_gap_height = gap_height * num_gaps as f32;
let available_height = (rect.height() - total_gap_height).at_least(0.0);
let heights = self.shares.split(&visible_children, available_height);
let mut y = rect.min.y;
for (child, height) in visible_children.iter().zip(heights) {
let child_rect = Rect::from_min_size(pos2(rect.min.x, y), vec2(rect.width(), height));
tiles.layout_tile(style, behavior, child_rect, *child);
y += height + gap_height;
}
}
pub(super) fn ui<Pane>(
&mut self,
tree: &mut Tree<Pane>,
behavior: &mut dyn Behavior<Pane>,
drop_context: &mut DropContext,
ui: &egui::Ui,
tile_id: TileId,
) {
match self.dir {
LinearDir::Horizontal => self.horizontal_ui(tree, behavior, drop_context, ui, tile_id),
LinearDir::Vertical => self.vertical_ui(tree, behavior, drop_context, ui, tile_id),
}
}
fn horizontal_ui<Pane>(
&mut self,
tree: &mut Tree<Pane>,
behavior: &mut dyn Behavior<Pane>,
drop_context: &mut DropContext,
ui: &egui::Ui,
parent_id: TileId,
) {
let visible_children = self.visible_children(&tree.tiles);
for &child in &visible_children {
tree.tile_ui(behavior, drop_context, ui, child);
crate::cover_tile_if_dragged(tree, behavior, ui, child);
}
linear_drop_zones(ui.ctx(), tree, &self.children, self.dir, |rect, i| {
drop_context.suggest_rect(
InsertionPoint::new(parent_id, ContainerInsertion::Horizontal(i)),
rect,
);
});
// ------------------------
// resizing:
let parent_rect = tree.tiles.rect_or_die(parent_id);
for (i, (left, right)) in visible_children.iter().copied().tuple_windows().enumerate() {
let resize_id = ui.id().with((parent_id, "resize", i));
let left_rect = tree.tiles.rect_or_die(left);
let right_rect = tree.tiles.rect_or_die(right);
let x = egui::lerp(left_rect.right()..=right_rect.left(), 0.5);
let mut resize_state = ResizeState::Idle;
let line_rect = Rect::from_center_size(
pos2(x, parent_rect.center().y),
vec2(
2.0 * ui.style().interaction.resize_grab_radius_side,
parent_rect.height(),
),
);
let response = ui.interact(line_rect, resize_id, egui::Sense::click_and_drag());
// NOTE: Check for interaction with line_rect BEFORE entering the 'IF block' below,
// otherwise we miss the start of a drag event in certain cases (e.g. touchscreens).
if let Some(pointer) = ui.ctx().pointer_interact_pos() {
resize_state = resize_interaction(
behavior,
&mut self.shares,
&visible_children,
&response,
[left, right],
pointer.round_to_pixels(ui.pixels_per_point()).x - x,
i,
|tile_id: TileId| tree.tiles.rect_or_die(tile_id).width(),
);
if resize_state != ResizeState::Idle {
ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeHorizontal);
}
}
let stroke = behavior.resize_stroke(ui.style(), resize_state);
ui.painter().vline(x, parent_rect.y_range(), stroke);
}
}
fn vertical_ui<Pane>(
&mut self,
tree: &mut Tree<Pane>,
behavior: &mut dyn Behavior<Pane>,
drop_context: &mut DropContext,
ui: &egui::Ui,
parent_id: TileId,
) {
let visible_children = self.visible_children(&tree.tiles);
for &child in &visible_children {
tree.tile_ui(behavior, drop_context, ui, child);
crate::cover_tile_if_dragged(tree, behavior, ui, child);
}
linear_drop_zones(ui.ctx(), tree, &self.children, self.dir, |rect, i| {
drop_context.suggest_rect(
InsertionPoint::new(parent_id, ContainerInsertion::Vertical(i)),
rect,
);
});
// ------------------------
// resizing:
let parent_rect = tree.tiles.rect_or_die(parent_id);
for (i, (top, bottom)) in visible_children.iter().copied().tuple_windows().enumerate() {
let resize_id = ui.id().with((parent_id, "resize", i));
let top_rect = tree.tiles.rect_or_die(top);
let bottom_rect = tree.tiles.rect_or_die(bottom);
let y = egui::lerp(top_rect.bottom()..=bottom_rect.top(), 0.5);
let mut resize_state = ResizeState::Idle;
let line_rect = Rect::from_center_size(
pos2(parent_rect.center().x, y),
vec2(
parent_rect.width(),
2.0 * ui.style().interaction.resize_grab_radius_side,
),
);
let response = ui.interact(line_rect, resize_id, egui::Sense::click_and_drag());
// NOTE: Check for interaction with line_rect BEFORE entering the 'IF block' below,
// otherwise we miss the start of a drag event in certain cases (e.g. touchscreens).
if let Some(pointer) = ui.ctx().pointer_interact_pos() {
resize_state = resize_interaction(
behavior,
&mut self.shares,
&visible_children,
&response,
[top, bottom],
pointer.round_to_pixels(ui.pixels_per_point()).y - y,
i,
|tile_id: TileId| tree.tiles.rect_or_die(tile_id).height(),
);
if resize_state != ResizeState::Idle {
ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeVertical);
}
}
let stroke = behavior.resize_stroke(ui.style(), resize_state);
ui.painter().hline(parent_rect.x_range(), y, stroke);
}
}
pub(super) fn simplify_children(&mut self, mut simplify: impl FnMut(TileId) -> SimplifyAction) {
self.children.retain_mut(|child| match simplify(*child) {
SimplifyAction::Remove => false,
SimplifyAction::Keep => true,
SimplifyAction::Replace(new) => {
self.shares.replace_with(*child, new);
*child = new;
true
}
});
}
/// Returns child index, if found.
pub(crate) fn remove_child(&mut self, needle: TileId) -> Option<usize> {
let index = self.children.iter().position(|&child| child == needle)?;
self.children.remove(index);
Some(index)
}
}
#[allow(clippy::too_many_arguments)]
fn resize_interaction<Pane>(
behavior: &mut dyn Behavior<Pane>,
shares: &mut Shares,
children: &[TileId],
splitter_response: &egui::Response,
[left, right]: [TileId; 2],
dx: f32,
i: usize,
tile_width: impl Fn(TileId) -> f32,
) -> ResizeState {
if splitter_response.double_clicked() {
behavior.on_edit(EditAction::TileResized);
// double-click to center the split between left and right:
let mean = 0.5 * (shares[left] + shares[right]);
shares[left] = mean;
shares[right] = mean;
ResizeState::Hovering
} else if splitter_response.dragged() {
behavior.on_edit(EditAction::TileResized);
if dx < 0.0 {
// Expand right, shrink stuff to the left:
shares[right] += shrink_shares(
behavior,
shares,
&children[0..=i].iter().copied().rev().collect_vec(),
dx.abs(),
tile_width,
);
} else {
// Expand the left, shrink stuff to the right:
shares[left] +=
shrink_shares(behavior, shares, &children[i + 1..], dx.abs(), tile_width);
}
ResizeState::Dragging
} else if splitter_response.hovered() {
ResizeState::Hovering
} else {
ResizeState::Idle
}
}
/// Try shrink the children by a total of `target_in_points`,
/// making sure no child gets smaller than its minimum size.
fn shrink_shares<Pane>(
behavior: &dyn Behavior<Pane>,
shares: &mut Shares,
children: &[TileId],
target_in_points: f32,
size_in_point: impl Fn(TileId) -> f32,
) -> f32 {
if children.is_empty() {
return 0.0;
}
let mut total_shares = 0.0;
let mut total_points = 0.0;
for &child in children {
total_shares += shares[child];
total_points += size_in_point(child);
}
let shares_per_point = total_shares / total_points;
let min_size_in_shares = shares_per_point * behavior.min_size();
let target_in_shares = shares_per_point * target_in_points;
let mut total_shares_lost = 0.0;
for &child in children {
let share = &mut shares[child];
let spare_share = (*share - min_size_in_shares).at_least(0.0);
let shares_needed = (target_in_shares - total_shares_lost).at_least(0.0);
let shrink_by = f32::min(spare_share, shares_needed);
*share -= shrink_by;
total_shares_lost += shrink_by;
}
total_shares_lost
}
fn linear_drop_zones<Pane>(
egui_ctx: &egui::Context,
tree: &Tree<Pane>,
children: &[TileId],
dir: LinearDir,
add_drop_drect: impl FnMut(Rect, usize),
) {
let preview_thickness = 12.0;
let dragged_index = children
.iter()
.position(|&child| is_being_dragged(egui_ctx, tree.id, child));
let after_rect = |rect: Rect| match dir {
LinearDir::Horizontal => Rect::from_min_max(
rect.right_top() - vec2(preview_thickness, 0.0),
rect.right_bottom(),
),
LinearDir::Vertical => Rect::from_min_max(
rect.left_bottom() - vec2(0.0, preview_thickness),
rect.right_bottom(),
),
};
drop_zones(
preview_thickness,
children,
dragged_index,
dir,
|tile_id| tree.tiles.rect(tile_id),
add_drop_drect,
after_rect,
);
}
/// Register drop-zones for a linear container.
///
/// `get_rect`: return `None` for invisible tiles.
pub(super) fn drop_zones(
preview_thickness: f32,
children: &[TileId],
dragged_index: Option<usize>,
dir: LinearDir,
get_rect: impl Fn(TileId) -> Option<Rect>,
mut add_drop_drect: impl FnMut(Rect, usize),
after_rect: impl Fn(Rect) -> Rect,
) {
let before_rect = |rect: Rect| match dir {
LinearDir::Horizontal => Rect::from_min_max(
rect.left_top(),
rect.left_bottom() + vec2(preview_thickness, 0.0),
),
LinearDir::Vertical => Rect::from_min_max(
rect.left_top(),
rect.right_top() + vec2(0.0, preview_thickness),
),
};
let between_rects = |a: Rect, b: Rect| match dir {
LinearDir::Horizontal => Rect::from_center_size(
a.right_center().lerp(b.left_center(), 0.5),
vec2(preview_thickness, a.height()),
),
LinearDir::Vertical => Rect::from_center_size(
a.center_bottom().lerp(b.center_top(), 0.5),
vec2(a.width(), preview_thickness),
),
};
let mut prev_rect: Option<Rect> = None;
for (i, &child) in children.iter().enumerate() {
let Some(rect) = get_rect(child) else {
// skip invisible child
continue;
};
if Some(i) == dragged_index {
// Suggest hole as a drop-target:
add_drop_drect(rect, i);
} else if let Some(prev_rect) = prev_rect {
if Some(i - 1) != dragged_index {
// Suggest dropping between the rects:
add_drop_drect(between_rects(prev_rect, rect), i);
}
} else {
// Suggest dropping before the first child:
add_drop_drect(before_rect(rect), 0);
}
prev_rect = Some(rect);
}
if let Some(last_rect) = prev_rect {
// Suggest dropping after the last child (unless that's the one being dragged):
if dragged_index != Some(children.len() - 1) {
add_drop_drect(after_rect(last_rect), children.len());
}
}
}
| 412 | 0.973335 | 1 | 0.973335 | game-dev | MEDIA | 0.788186 | game-dev | 0.962251 | 1 | 0.962251 |
khudiiash/webgpu-renderer | 1,068 | src/data/BindGroupLayout.ts | import { Binding } from "./Binding";
export class BindGroupLayout {
public device: GPUDevice;
public name: string;
public groupName: string;
public bindings: Binding[];
public layout!: GPUBindGroupLayout;
descriptor: GPUBindGroupLayoutDescriptor;
constructor(device: GPUDevice, name: string, groupName: string, bindings: Binding[]) {
this.device = device;
this.name = name;
this.groupName = groupName;
this.bindings = bindings;
const entries: GPUBindGroupLayoutEntry[] = this.bindings.map(binding => binding.getLayoutEntry());
this.descriptor = {
label: this.name,
entries: entries,
}
this.layout = this.device.createBindGroupLayout(this.descriptor);
this.bindings.forEach(binding => binding.setBindGroupLayout(this));
}
get isGlobal() {
return this.groupName === 'Global';
}
get isMesh() {
return this.groupName === 'Mesh';
}
get isMaterial() {
return this.groupName === 'Material';
}
} | 412 | 0.676551 | 1 | 0.676551 | game-dev | MEDIA | 0.395097 | game-dev | 0.817363 | 1 | 0.817363 |
jeffcampbellmakesgames/Entitas-Redux | 3,359 | Unity/Assets/JCMG/EntitasRedux/Scripts/Editor/Tests/Generated/Test/Components/TestStandardEntityEventRemovedListenerComponent.cs | public partial class TestEntity
{
public StandardEntityEventRemovedListenerComponent StandardEntityEventRemovedListener { get { return (StandardEntityEventRemovedListenerComponent)GetComponent(TestComponentsLookup.StandardEntityEventRemovedListener); } }
public bool HasStandardEntityEventRemovedListener { get { return HasComponent(TestComponentsLookup.StandardEntityEventRemovedListener); } }
public void AddStandardEntityEventRemovedListener(System.Collections.Generic.List<IStandardEntityEventRemovedListener> newValue)
{
var index = TestComponentsLookup.StandardEntityEventRemovedListener;
var component = (StandardEntityEventRemovedListenerComponent)CreateComponent(index, typeof(StandardEntityEventRemovedListenerComponent));
#if !ENTITAS_REDUX_NO_IMPL
component.value = newValue;
#endif
AddComponent(index, component);
}
public void ReplaceStandardEntityEventRemovedListener(System.Collections.Generic.List<IStandardEntityEventRemovedListener> newValue)
{
var index = TestComponentsLookup.StandardEntityEventRemovedListener;
var component = (StandardEntityEventRemovedListenerComponent)CreateComponent(index, typeof(StandardEntityEventRemovedListenerComponent));
#if !ENTITAS_REDUX_NO_IMPL
component.value = newValue;
#endif
ReplaceComponent(index, component);
}
public void CopyStandardEntityEventRemovedListenerTo(StandardEntityEventRemovedListenerComponent copyComponent)
{
var index = TestComponentsLookup.StandardEntityEventRemovedListener;
var component = (StandardEntityEventRemovedListenerComponent)CreateComponent(index, typeof(StandardEntityEventRemovedListenerComponent));
#if !ENTITAS_REDUX_NO_IMPL
component.value = copyComponent.value;
#endif
ReplaceComponent(index, component);
}
public void RemoveStandardEntityEventRemovedListener()
{
RemoveComponent(TestComponentsLookup.StandardEntityEventRemovedListener);
}
}
public sealed partial class TestMatcher
{
static JCMG.EntitasRedux.IMatcher<TestEntity> _matcherStandardEntityEventRemovedListener;
public static JCMG.EntitasRedux.IMatcher<TestEntity> StandardEntityEventRemovedListener
{
get
{
if (_matcherStandardEntityEventRemovedListener == null)
{
var matcher = (JCMG.EntitasRedux.Matcher<TestEntity>)JCMG.EntitasRedux.Matcher<TestEntity>.AllOf(TestComponentsLookup.StandardEntityEventRemovedListener);
matcher.ComponentNames = TestComponentsLookup.ComponentNames;
_matcherStandardEntityEventRemovedListener = matcher;
}
return _matcherStandardEntityEventRemovedListener;
}
}
}
public partial class TestEntity
{
public void AddStandardEntityEventRemovedListener(IStandardEntityEventRemovedListener value)
{
var listeners = HasStandardEntityEventRemovedListener
? StandardEntityEventRemovedListener.value
: new System.Collections.Generic.List<IStandardEntityEventRemovedListener>();
listeners.Add(value);
ReplaceStandardEntityEventRemovedListener(listeners);
}
public void RemoveStandardEntityEventRemovedListener(IStandardEntityEventRemovedListener value, bool removeComponentWhenEmpty = true)
{
var listeners = StandardEntityEventRemovedListener.value;
listeners.Remove(value);
if (removeComponentWhenEmpty && listeners.Count == 0)
{
RemoveStandardEntityEventRemovedListener();
}
else
{
ReplaceStandardEntityEventRemovedListener(listeners);
}
}
}
| 412 | 0.812127 | 1 | 0.812127 | game-dev | MEDIA | 0.696994 | game-dev | 0.548748 | 1 | 0.548748 |
eramdam/sticky-fingers | 22,380 | lovely/misc_functions.lua | debug_current_card = {}
function create_drag_target_from_card(_card)
if _card and G.STAGE == G.STAGES.RUN then
debug_current_card = _card
G.DRAG_TARGETS = G.DRAG_TARGETS or {
S_buy = Moveable { T = { x = G.jokers.T.x, y = G.jokers.T.y - 0.1, w = G.consumeables.T.x + G.consumeables.T.w - G.jokers.T.x, h = G.jokers.T.h + 0.6 } },
S_buy_and_use = Moveable { T = { x = G.deck.T.x + 0.2, y = G.deck.T.y - 5.1, w = G.deck.T.w - 0.1, h = 4.5 } },
C_sell = Moveable { T = { x = G.jokers.T.x, y = G.jokers.T.y - 0.2, w = G.jokers.T.w, h = G.jokers.T.h + 0.6 } },
J_sell = Moveable { T = { x = G.consumeables.T.x + 0.3, y = G.consumeables.T.y - 0.2, w = G.consumeables.T.w - 0.3, h = G.consumeables.T.h + 0.6 } },
J_sell_vanilla = Moveable { T = { x = G.consumeables.T.x + 0.3, y = G.consumeables.T.y - 0.2, w = G.consumeables.T.w - 0.3, h = G.consumeables.T.h + 0.6 } },
C_use = Moveable { T = { x = G.deck.T.x + 0.2, y = G.deck.T.y - 5.1, w = G.deck.T.w - 0.1, h = 4.5 } },
P_select = Moveable { T = { x = G.play.T.x, y = G.play.T.y - 2, w = G.play.T.w + 2, h = G.play.T.h + 1 } },
-- for Cryptid code cards and Pokermon item/energy cards (middle center)
P_save = Moveable { T = { x = G.play.T.x, y = G.play.T.y - 2, w = G.play.T.w, h = G.play.T.h + 1 } },
-- Prism's "double cards" have a "Switch" button
P_switch = Moveable { T = { x = G.deck.T.x + 0.2, y = G.deck.T.y - 5.1, w = G.deck.T.w - 0.1, h = 4.5 } },
}
if DTM.config.vanilla_joker_sell == false then
G.DRAG_TARGETS.J_sell = Moveable { T = { x = G.deck.T.x + 0.2, y = G.deck.T.y - 5.1, w = G.deck.T.w - 0.1, h = 4.5 } }
else
G.DRAG_TARGETS.J_sell = G.DRAG_TARGETS.J_sell_vanilla
end
if _card.area then
-- is the card in one of the shop areas?
if _card.area == G.shop_jokers or _card.area == G.shop_vouchers or
_card.area == G.shop_booster then
local buy_loc = copy_table(localize((_card.ability.set == 'Voucher' and 'ml_redeem_target') or
(_card.ability.set == 'Booster' and 'ml_open_target') or 'ml_buy_target'))
buy_loc[#buy_loc + 1] = '$' .. _card.cost
drag_target({
cover = G.DRAG_TARGETS.S_buy,
colour = adjust_alpha(G.C.GREEN, 0.9),
text = buy_loc,
card = _card,
active_check = (function(other)
return sticky_can_buy(other)
end),
release_func = (function(other)
if other.ability.set == 'Joker' and sticky_can_buy(other) then
if G.OVERLAY_TUTORIAL and G.OVERLAY_TUTORIAL.button_listen == 'buy_from_shop' then
G.FUNCS.tut_next()
end
G.FUNCS.buy_from_shop({
config = {
ref_table = other,
id = 'buy'
}
})
return
elseif (other.ability.set == 'Voucher' or other.ability.set == 'Booster') and sticky_can_buy(other) then
G.FUNCS.use_card({ config = { ref_table = other } })
elseif sticky_can_buy(other) then
G.FUNCS.buy_from_shop({
config = {
ref_table = other,
id = 'buy'
}
})
end
end)
})
if sticky_can_buy_and_use(_card) then
local buy_use_loc = copy_table(localize('ml_buy_and_use_target'))
buy_use_loc[#buy_use_loc + 1] = '$' .. _card.cost
drag_target({
cover = G.DRAG_TARGETS.S_buy_and_use,
colour = adjust_alpha(G.C.ORANGE, 0.9),
text = buy_use_loc,
card = _card,
active_check = (function(other)
return sticky_can_buy_and_use(other)
end),
release_func = (function(other)
if sticky_can_buy_and_use(other) then
G.FUNCS.buy_from_shop({
config = {
ref_table = other,
id = 'buy_and_use'
}
})
return
end
end)
})
end
end
-- is the card in a pack?
if _card.area == G.pack_cards then
local is_consumeable_card_in_crazy_reverie_pack = Reverie and SMODS.OPENED_BOOSTER.label == 'Pack' and
_card.ability.consumeable and _card.area == G.pack_cards
-- is the card a consumeable?
if _card.ability.consumeable then
local draw_use_drag_target = function()
local is_planet = _card.ability.set == 'Planet'
drag_target({
cover = (is_planet and G.DRAG_TARGETS.P_select) or G.DRAG_TARGETS.C_use,
colour = adjust_alpha((is_planet and G.C.GREEN) or G.C.RED, 0.9),
text = { localize('b_use') },
card = _card,
active_check = (function(other)
return other:can_use_consumeable()
end),
release_func = (function(other)
if other:can_use_consumeable() then
G.FUNCS.use_card({ config = { ref_table = other } })
end
end)
})
end
local needs_areas = true
-- Pokermon has a "Super Rod" voucher that lets the player save any consumeable from packs and not just Energy/Item cards.
local pokermon_has_save_all = G.GAME.poke_save_all and not SMODS.OPENED_BOOSTER.label:find("Wish")
-- Cryptid's "Code" cards inside packs.
if Cryptid and _card.ability.consumeable and _card.ability.set == 'Code' then
draw_use_drag_target()
-- "Pull" drag target ("use" area is already covered above)
drag_target({
cover = G.DRAG_TARGETS.P_save,
colour = adjust_alpha(G.C.GREEN, 0.9),
text = { localize('b_pull') },
card = _card,
active_check = (function(other)
return sticky_can_reserve_card(other)
end),
release_func = (function(other)
if sticky_can_reserve_card(other) then
G.FUNCS.reserve_card({ config = { ref_table = other } })
end
end)
})
needs_areas = false
-- Pokermon Item/Energy cards inside packs.
elseif pokermon and _card.ability.consumeable and (_card.ability.set == 'Energy' or _card.ability.set == 'Item' or pokermon_has_save_all) then
if not is_consumeable_card_in_crazy_reverie_pack then
if not pokermon_has_save_all then
draw_use_drag_target()
else
drag_target({
cover = G.DRAG_TARGETS.C_use,
colour = adjust_alpha((is_planet and G.C.GREEN) or G.C.RED, 0.9),
text = { localize('b_use') },
card = _card,
active_check = (function(other)
return other:can_use_consumeable()
end),
release_func = (function(other)
if other:can_use_consumeable() then
G.FUNCS.use_card({ config = { ref_table = other } })
end
end)
})
end
-- "Save" drag target ("use" target is already covered above)
drag_target({
cover = G.DRAG_TARGETS.P_save,
colour = adjust_alpha(
pokermon_has_save_all and G.C.GREEN or G.ARGS.LOC_COLOURS.pink, 0.9),
text = { localize('b_save') },
card = _card,
active_check = function(other)
return sticky_can_reserve_card(other)
end,
release_func = function(other)
if sticky_can_reserve_card(other) then
G.FUNCS.reserve_card({ config = { ref_table = other } })
end
end,
})
needs_areas = false
end
elseif _card.ability.set == 'Cine' then
drag_target({
cover = G.DRAG_TARGETS.P_select,
colour = adjust_alpha(G.C.GREEN, 0.9),
text = { localize('b_select') },
card = _card,
active_check = (function(other)
return sticky_can_select_card(other)
end),
release_func = (function(other)
if sticky_can_select_card(other) then
G.FUNCS.use_card({ config = { ref_table = other } })
end
end),
})
needs_areas = false
elseif _card.ability.set == 'Auxiliary' then
drag_target({
cover = G.DRAG_TARGETS.P_select,
colour = adjust_alpha(G.C.GREEN, 0.9),
text = { localize('b_select') },
card = _card,
active_check = function(other)
return sticky_can_take_card(other)
end,
release_func = function(other)
if sticky_can_take_card(other) then
G.FUNCS.take_card({ config = { ref_table = other } })
end
end,
})
needs_areas = false
end
if is_consumeable_card_in_crazy_reverie_pack and needs_areas then
drag_target({
cover = G.DRAG_TARGETS.P_select,
colour = adjust_alpha(G.C.GREEN, 0.9),
text = { localize('b_select') },
card = _card,
active_check = (function(other)
return sticky_can_select_crazy_card(other)
end),
release_func = (function(other)
if sticky_can_select_crazy_card(other) then
G.FUNCS.use_card({ config = { ref_table = other } })
end
end)
})
elseif needs_areas then
draw_use_drag_target()
end
else
-- Bunco: Blind 'cards' in packs
if BUNCOMOD and _card.ability.blind_card then
drag_target({
cover = G.DRAG_TARGETS.P_select,
colour = adjust_alpha(G.C.GREEN, 0.9),
text = { localize('b_select') },
card = _card,
active_check = (function(other)
return sticky_can_use_blind_card(other)
end),
release_func = (function(other)
if sticky_can_use_blind_card(other) then
G.FUNCS.use_blind_card({ config = { ref_table = other } })
end
end)
})
else
drag_target({
cover = G.DRAG_TARGETS.P_select,
colour = adjust_alpha(G.C.GREEN, 0.9),
text = { localize('b_select') },
card = _card,
active_check = (function(other)
return sticky_can_select_card(other)
end),
release_func = (function(other)
if sticky_can_select_card(other) then
G.FUNCS.use_card({ config = { ref_table = other } })
end
end)
})
end
end
end
local draw_consumeable_use_target = function()
drag_target({
cover = G.DRAG_TARGETS.C_use,
colour = adjust_alpha(G.C.RED, 0.9),
text = { localize('b_use') },
card = _card,
active_check = (function(other)
-- huge hack for Cryptid Code cards: since their `can_use` method might check for highlighted consumeables, we need to temporarily add the card inside the highlighted table to satisfy the check while drawing the drag_target
if Cryptid and _card.ability.set == 'Code' and _card.area and not is_element_in_table(_card, _card.area.highlighted) then
_card.area.highlighted[#_card.area.highlighted + 1] = _card
local can_use = other:can_use_consumeable()
remove_highlighted_card_from_area(_card, _card.area)
return can_use
end
return other:can_use_consumeable()
end),
release_func = (function(other)
-- this is lazy but if we're here we _should_ be good anyway
if Cryptid and other.ability.set == 'Code' then
G.FUNCS.use_card({ config = { ref_table = other } })
elseif other:can_use_consumeable() then
G.FUNCS.use_card({ config = { ref_table = other } })
if G.OVERLAY_TUTORIAL and G.OVERLAY_TUTORIAL.button_listen == 'use_card' then
G.FUNCS.tut_next()
end
end
end)
})
end
-- is the card in the jokers/consumeables area?
if _card.area and (_card.area == G.jokers or _card.area == G.consumeables) then
local sell_loc = copy_table(localize('ml_sell_target'))
sell_loc[#sell_loc + 1] = '$' .. (_card.facing == 'back' and '?' or _card.sell_cost)
drag_target({
cover = _card.area == G.consumeables and G.DRAG_TARGETS.C_sell or G.DRAG_TARGETS.J_sell,
colour = adjust_alpha(G.C.GOLD, 0.9),
text = sell_loc,
card = _card,
active_check = (function(other)
return other:can_sell_card()
end),
release_func = (function(other)
G.FUNCS.sell_card { config = { ref_table = other } }
end)
})
if _card.area == G.consumeables then
draw_consumeable_use_target()
end
end
-- 'Cine' (Reverie) cards inside their own area.
if _card.area and _card.area == G.cine_quests and _card.ability.consumeable and
_card.ability.set == 'Cine' then
local sell_loc = copy_table(localize('ml_sell_target'))
sell_loc[#sell_loc + 1] = '$' .. (_card.facing == 'back' and '?' or _card.sell_cost)
-- "Sell" target.
drag_target({
cover = G.DRAG_TARGETS.C_sell,
colour = adjust_alpha(G.C.GOLD, 0.9),
text = sell_loc,
card = _card,
active_check = (function(other)
return other:can_sell_card()
end),
release_func = (function(other)
G.FUNCS.sell_card { config = { ref_table = other } }
end),
})
-- "Use" target.
drag_target({
cover = G.DRAG_TARGETS.J_sell_vanilla,
colour = adjust_alpha(G.C.RED, 0.9),
text = { localize('b_use') },
card = _card,
active_check = (function(other)
return other:can_use_consumeable()
end),
release_func = (function(other)
G.FUNCS.use_card({ config = { ref_table = other } })
end),
})
end
-- Prism's double cards from hand.
if _card.area == G.hand and G.PRISM and _card.ability.set == 'Enhanced' and
_card.ability.name == 'm_prism_double' then
-- "Switch" area.
drag_target({
cover = G.DRAG_TARGETS.P_switch,
colour = adjust_alpha(G.C.RED, 0.9),
text = { localize('prism_switch') },
card = _card,
active_check = function()
return true
end,
release_func = function(other)
G.FUNCS.switch_button({
config = {
ref_table = other,
}
})
end,
})
end
-- Cryptid's "MERGE" code card allows to merge playing cards with consumeables
if _card.area == G.hand and _card.ability.consumeable then
draw_consumeable_use_target()
end
end
end
end
function remove_highlighted_card_from_area(card, area)
for i = #area.highlighted, 1, -1 do
if area.highlighted[i] == card then
table.remove(card.area.highlighted, i)
break
end
end
end
function is_element_in_table(element, table)
for _, value in ipairs(table) do
if value == element then
return true
end
end
return false
end
sticky_can_use_blind_card = function(_card)
local temp_config = { UIBox = { states = { visible = false } }, config = { ref_table = _card } }
G.FUNCS.can_use_blind_card(temp_config)
return temp_config.config.button ~= nil;
end
sticky_can_reserve_card = function(_card)
local temp_config = { UIBox = { states = { visible = false } }, config = { ref_table = _card } }
G.FUNCS.can_reserve_card(temp_config)
return temp_config.config.button ~= nil;
end
sticky_can_select_card = function(_card)
local temp_config = { UIBox = { states = { visible = false } }, config = { ref_table = _card } }
G.FUNCS.can_select_card(temp_config)
return temp_config.config.button ~= nil;
end
sticky_can_buy = function(_card)
local temp_config = { UIBox = { states = { visible = false } }, config = { ref_table = _card } }
G.FUNCS.can_buy(temp_config)
return temp_config.config.button ~= nil;
end
sticky_can_buy_and_use = function(_card)
local temp_config = { UIBox = { states = { visible = false } }, config = { ref_table = _card } }
G.FUNCS.can_buy_and_use(temp_config)
return temp_config.config.button ~= nil;
end
sticky_can_select_crazy_card = function(_card)
local temp_config = { UIBox = { states = { visible = false } }, config = { ref_table = _card } }
G.FUNCS.can_select_crazy_card(temp_config)
return temp_config.config.button ~= nil;
end
sticky_can_take_card = function(_card)
local temp_config = { UIBox = { states = { visible = false } }, config = { ref_table = _card } }
G.FUNCS.can_take_card(temp_config)
return temp_config.config.button ~= nil;
end
| 412 | 0.927548 | 1 | 0.927548 | game-dev | MEDIA | 0.979662 | game-dev | 0.905333 | 1 | 0.905333 |
Polka37/Krastorio2-spaced-out | 3,370 | data-final-fixes.lua | require("prototypes.final-fixes.enforce-science-tier-separation")
require("prototypes.final-fixes.internal-turret-logic")
require("prototypes.final-fixes.biter-nests")
require("prototypes.final-fixes.enforce-rifle-ammo")
require("prototypes.final-fixes.enforce-k2-items")
--sync all labs inputs
data.raw["lab"]["biolab"].inputs = data.raw["lab"]["lab"].inputs
data.raw["lab"]["kr-advanced-lab"].inputs = data.raw["lab"]["lab"].inputs
data.raw["lab"]["kr-singularity-lab"].inputs = data.raw["lab"]["lab"].inputs
if mods["tech-cards-retexture-AI-powered"] then
for _, pack in pairs(data.raw.tool) do
if pack.subgroup == "science-pack" then
pack.spoil_result = "biter-egg"
pack.spoil_ticks = 3600
end
end
data.raw.item["biter-egg"].spoil_ticks = 1
end
local recycling = require("scripts.recycling")
-- Generating the recycle (reverse) recipes
for name, recipe in pairs(data.raw.recipe) do
recycling.generate_recycling_recipe(recipe)
end
local generate_self_recycling_recipe = function(item)
if item.auto_recycle == false then return end
if item.parameter then return end
if not data.raw.recipe[item.name .. "-recycling"] then
if not string.find(item.name, "-barrel") then
recycling.generate_self_recycling_recipe(item)
end
end
end
for type_name in pairs(defines.prototypes.item) do
if data.raw[type_name] then
for k, item in pairs(data.raw[type_name]) do
generate_self_recycling_recipe(item)
end
end
end
data.raw.quality.normal.hidden = false
--The code below had been made by Johannes2070
--Fix: Ensure the recycler has enough result inventory slots to handle all recycling outputs.
local recycler = data.raw["furnace"]["recycler"]
if recycler then
if recycler.result_inventory_size < 13 then
recycler.result_inventory_size = 13
end
end
--The code below had been made by Quezler
-- this file accomplishes the same as Krastroio 2's prototypes/final-fixes/steel-pipe-connectivity.lua file,
-- since there are only so many ways to write the same thing the code is earily similar,
-- therefore the contents of this file are best treated as falling under GNU LGPLv3.
local fluid_box_keys = {
"fluid_box",
"input_fluid_box",
"output_fluid_box",
"fuel_fluid_box",
"oxidizer_fluid_box",
}
local function handle_fluidbox(fluidbox)
if fluidbox == nil then return end
for _, connection in pairs(fluidbox.pipe_connections) do
if (connection.connection_type or "normal") == "normal" then
local categories = connection.connection_category or { "default" }
if #categories == 1 and categories[1] == "default" then
categories[#categories + 1] = "kr-steel-pipe"
connection.connection_category = categories
end
end
end
end
local function handle_prototype(prototype)
for _, fluid_box_key in pairs(fluid_box_keys) do
handle_fluidbox(prototype[fluid_box_key])
end
for _, fluid_box in pairs(prototype.fluid_boxes or {}) do
handle_fluidbox(fluid_box)
end
if prototype.energy_source and prototype.energy_source.type == "fluid" then
handle_fluidbox(prototype.energy_source.fluid_box)
end
end
for entity_type in pairs(defines.prototypes["entity"]) do
for _, prototype in pairs(data.raw[entity_type] or {}) do
if not names_ignored_by_steel_pipes[prototype.name] then
handle_prototype(prototype)
end
end
end
| 412 | 0.831643 | 1 | 0.831643 | game-dev | MEDIA | 0.832198 | game-dev | 0.815773 | 1 | 0.815773 |
tca/veneer | 19,671 | ck/ckeval.js | function VeneerVM() {
var toplevel = new Object(null);
function register_define(exp) {
if (pairp(exp) && exp.car === intern("define")) {
var a = pairp(exp.cdr.car) ? exp.cdr.car.car : exp.cdr.car;
toplevel[a.string] = ref(null);
}
}
function quote_desugar(exp) {
if (pairp(exp)) {
return meta(list(meta(intern("cons"), {tag:"var"}), quote_desugar(exp.car), quote_desugar(exp.cdr)), {tag:"app-builtin"});
} else if (exp == null) {
return meta(list(intern("quote"), null), { tag: "quoted" });
}else if(constantp(exp)) {
return meta(exp, {tag:"const"});
} else {
return meta(list(intern("quote"), exp), { tag: "quoted" });
}
}
function quasiquote_desugar(exp, n, env) {
if (pairp(exp)) {
if (exp.car === intern("unquote")) {
if (n === 1) {
return desugar(exp.cdr.car, env);
} else {
return list(intern("list"), list(intern("quote"), intern("unquote")),
quasiquote_desugar(exp.cdr.car, n - 1, env));
}
} else if (exp.car === intern("quasiquote")) {
return list(intern("list"), list(intern("quote"), intern("quasiquote")),
quasiquote_desugar(exp.cdr.car, n + 1, env));
} else {
return list(intern("cons"), quasiquote_desugar(exp.car, n, env),
quasiquote_desugar(exp.cdr, n, env));
}
} else {
return quote_desugar(exp);
}
}
function Meta(val, meta) {
this.val = val;
this.meta = meta || {};
}
function meta(v, meta) { return new Meta(v, meta); }
function normalize_params(params) {
var ps = null;
var rest = null;
var whole = null;
while(params !== null) {
if(symbolp(params)) {
rest = cons(params, rest);
whole = cons(params, ps);
break;
} else {
ps = cons(params.car, ps);
whole = ps;
params = params.cdr;
}
} return { normal: reverse(ps), rest: rest, whole: reverse(whole) };
}
function desugar(exp, env) {
if(exp instanceof Meta) { return exp; }
if(pairp(exp)) {
// application
var app = false;
if(symbolp(exp.car) && (lookup(exp.car, env) || toplevel.hasOwnProperty(exp.car.string))
|| pairp(exp.car)) {
return meta(map(function(e) { return desugar(e, env); }, exp),
{ tag: "app" });
}
// special forms & builtins
switch(exp.car) {
case intern("define"):
var name;
var body;
if(pairp(exp.cdr.car)) {
// (define (x y z) f) => (define x (lambda (y z) f))
name = exp.cdr.car.car;
body = cons(intern("lambda"), cons(exp.cdr.car.cdr, exp.cdr.cdr));
} else {
name = exp.cdr.car;
body = exp.cdr.cdr.car;
}
return meta(list(exp.car, name, desugar(body, env)), { tag: "define" });
case intern("quote"):
var val = quote_desugar(exp.cdr.car);
val.meta.constp = true;
return val;
case intern("quasiquote"):
return desugar(quasiquote_desugar(exp.cdr.car, 1, env), env);
case intern("zzz"):
return meta(list(exp.car, desugar(exp.cdr.car, env)),
{ tag: "zzz" });
case intern("conde"):
var clauses = map(function(row) { return cons(intern("conj"), row); }, exp.cdr);
return desugar(cons(intern("disj"), clauses), env);
case intern("conj"):
if (exp.cdr == null) { throw "error: empty conj"; }
else if (exp.cdr.cdr == null) {
var e1 = desugar(list(intern("zzz"), exp.cdr.car), env);
return e1;
} else {
var e1 = list(intern("zzz"), exp.cdr.car);
var e2 = cons(intern("conj"), exp.cdr.cdr);
return desugar(list(intern("conj/2"), e1, e2), env);
}
case intern("disj"):
if (exp.cdr == null) { throw "error: empty disj"; }
else if (exp.cdr.cdr == null) {
var e1 = desugar(list(intern("zzz"), exp.cdr.car), env);
return e1;
} else {
var e1 = list(intern("zzz"), exp.cdr.car);
var e2 = cons(intern("disj"), exp.cdr.cdr);
return desugar(list(intern("disj/2"), e1, e2), env);
}
case intern("begin"):
return meta(cons(exp.car, map(function(f) { return desugar(f, env); }, exp.cdr)),
{ tag: "begin" });
case intern("fresh"):
var bindings = exp.cdr.car;
var body = exp.cdr.cdr;
if (bindings === null) {
return desugar(cons(intern("conj"), body), env);
} else {
var fn = list(intern("lambda"), bindings, cons(intern("conj"), body));
var body1 = desugar(fn, env);
var len = desugar(length(bindings), env);
return meta(list(intern("apply/fresh-n"), len, body1),
{ tag: "fresh" });
}
case intern("lambda"):
var bindings = exp.cdr.car;
var body = exp.cdr.cdr;
var norm = normalize_params(bindings);
var env1 = foldl(norm.whole, env, function(e, b) { return cons(cons(b, b), e); });
var body1 = desugar(cons(intern("begin"), body), env1);
return meta(list(exp.car, norm.whole, body1),
{ tag: "lambda", params: norm });
default:
if(builtins.hasOwnProperty(exp.car.string)) {
return meta(cons(meta(exp.car, { tag: "var" }), map(function(f) { return desugar(f, env); }, exp.cdr)),
{ tag: "app-builtin" });
} else if (exp.car === intern("list")) {
return meta(cons(meta(exp.car, { tag: "var" }), map(function(f) { return desugar(f, env); }, exp.cdr)),
{ tag: "app-builtin" });
} else {
throw new Error("unkown exp: " + pretty_print(exp));
}
}
} else if(constantp(exp)) {
return meta(exp, { tag: "const" });
} else if(symbolp(exp)) {
return meta(exp, { tag: "var" });
} else {
throw new Error("unkown exp: " + pretty_print(exp));
}
}
function lookup(x, xs) {
while(xs !== null) {
if (x === xs.car.car) { return xs.car.cdr; }
else { xs = xs.cdr; }
} return false;
}
function extend_boxed(env, a, v) {
var envu = env.get();
var existing = lookup(a, envu);
if (existing) {
return existing;
} else {
env.set(cons(cons(a, v), envu));
return v;
}
}
function frees(exp, env, lenv, fenv) {
switch(exp.meta.tag) {
case "const": case "quoted":
return exp;
case "define":
var name = exp.val.cdr.car;
var dfenv = ref(null);
// add self to env once mutable vars works, unless toplevel
var ret = list(exp.val.car, name, frees(exp.val.cdr.cdr.car, env, lenv, dfenv));
if(dfenv.get() === null) {
return meta(ret, exp.meta);
} else {
throw ("free variables in define: " + name.string + pretty_print(map(car, dfenv.get())));
}
case "lambda":
var bindings = exp.val.cdr.car;
var body = exp.val.cdr.cdr;
var e1 = foldl(bindings, env, function(e, a) { return cons(cons(a, a), e); });
var inner_frees = ref(null);
var proper_frees = null;
var re = cons(exp.val.car, cons(bindings, map(function(x) {
return frees(x, e1, bindings, inner_frees);
}, body)));
map(function(v) {
if (!memq(v.car, bindings)) {
extend_boxed(fenv, v.car, v.cdr);
proper_frees = cons(v.cdr, proper_frees);
}
}, inner_frees.get());
exp.meta.frees = proper_frees;
return meta(re, exp.meta);
case "begin": case "zzz": case "fresh":
return meta(cons(exp.val.car, map(function(x) { return frees(x, env, lenv, fenv); }, exp.val.cdr)),
exp.meta);
case "app": case "app-builtin":
return meta(map(function(x) { return frees(x, env, lenv, fenv); }, exp.val), exp.meta);
case "var":
if (memq(exp.val, lenv)) { return exp; }
if (lookup(exp.val, env)) { return meta(extend_boxed(fenv, exp.val, exp.val), exp.meta); }
if (toplevel.hasOwnProperty(exp.val.string)) { return exp; }
if (exp.val === intern("list")) { return exp; } // TODO: remove once varargs added
if (builtins.hasOwnProperty(exp.val.string)) { return exp; }
return meta(extend_boxed(fenv, exp.val, exp.val), exp.meta);
default:
throw new Error("unkown exp: " + pretty_print(exp.val));
}
}
// instead of returning a value, it returns a function that fetches a value
// based on the offset of how far it takes to reach the variable
// values in the env are expected to be :: offset -> cenv -> value
function lookup_calc(x, xs) {
var n = 0;
while(xs !== null) {
if (x === xs.car.car) { return xs.car.cdr(n); }
else { n++; xs = xs.cdr; }
} return false;
}
function augment_cenv(env, name) {
var binding = cons(name, function (offset) { return function(aenv, cenv) { return cenv[offset]; }; });
return cons(env.car, cons(binding, env.cdr));
}
function augment_aenv(env, name) {
var binding = cons(name, function (offset) { return function(aenv, cenv) { return aenv[offset]; }; });
return cons(cons(binding, env.car), env.cdr);
}
function augment_aenv_rest(env, name) {
var binding = cons(name, function (offset) { return function(aenv, cenv) { return array_slice_list(aenv, offset); }; });
return cons(cons(binding, env.car), env.cdr);
}
function lift_frees(exp) {
var free_env = ref(null);
var exp1 = frees(exp, null, null, free_env);
var e1_c1 = foldl(free_env.get(), cons(null, 0),
function(e_c, a) {
var var1 = mkvar(e_c.cdr);
var retrieve = function(_) { return function(_) { return var1; }; };
return cons(cons(cons(a.cdr, retrieve), e_c.car), e_c.cdr + 1); });
return list(exp1, e1_c1.car, Mks(Immutable.Map(), e1_c1.cdr, null, Immutable.Map()));
}
function eval0(exp, env) {
if(exp.meta.constp) {
exp.meta.constp = false;
var val = eval0(exp, env)();
return function(cenv) { return val; };
}
switch(exp.meta.tag) {
case "app":
var clos = eval0(exp.val.car, env);
var args = foldl(reverse(exp.val.cdr), null, function(m, e) {
return cons(eval0(e, env), m);
});
var len = length(args);
return function(aenv, cenv) {
var clos1 = clos(aenv, cenv);
return clos1.car(build_env(len, args, aenv, cenv), clos1.cdr);
};
case "define":
var result = eval0(exp.val.cdr.cdr.car, env);
toplevel[exp.val.cdr.car.string].set(result());
return function(aenv, cenv) { return true; };
case "quoted":
var val = exp.val.cdr.car;
return function(aenv, cenv) { return val };
case "begin":
if (exp.val.cdr == null) { throw new Error("empty begin"); }
else if (exp.val.cdr.cdr == null) {
var e1 = eval0(exp.val.cdr.car, env);
return e1;
} else {
return generate_begin_code(length(exp.val.cdr))(exp.val.cdr, env, eval0);
}
case "lambda":
var bindings = exp.val.cdr.car;
var body = exp.val.cdr.cdr.car;
var free_env = foldl(reverse(exp.meta.frees), cons(null, null), augment_cenv);
var env1_rest = foldl(exp.meta.params.rest, free_env, augment_aenv_rest);
var env1 = foldl(reverse(exp.meta.params.normal), env1_rest, augment_aenv);
var len = length(exp.meta.frees);
var free_env1 = map(function(v) { return eval0(meta(v, { tag: "var" }), env); }, exp.meta.frees);
var closure_body = eval0(body, env1);
var closure_env_build = function(aenv, cenv) { return build_env(len, free_env1, aenv, cenv); };
var closure = function(aenv, cenv) { return cons(closure_body, closure_env_build(aenv, cenv)); };
return closure;
case "zzz":
var e1 = eval0(exp.val.cdr.car, env);
return function(aenv, cenv) { return function(mks) { return function() { return e1(aenv, cenv)(mks); }; }; };
case "fresh":
var len = exp.val.cdr.car.val;
var fn = exp.val.cdr.cdr.car;
var closure = eval0(fn, env);
return function(aenv, cenv) { return apply_fresh(len, closure, aenv, cenv); };
case "app-builtin":
if (exp.val.car.val === intern("list")) {
var args = map(function(e) { return eval0(e, env); }, exp.val.cdr);
return function(aenv, cenv) {
return map(function(a) { return a(aenv, cenv); }, args);
};
}
return builtins[exp.val.car.val.string](exp.val.cdr, env, eval0);
case "const":
var val = exp.val
return function(aenv, cenv) { return val; };
case "var":
var v;
v = lookup_calc(exp.val, env.car) || lookup_calc(exp.val, env.cdr);
if (v) {
return v;
} else if(toplevel.hasOwnProperty(exp.val.string)) {
var box = toplevel[exp.val.string];
return function(aenv, cenv) { return box.get(); };
} else {
throw new Error("unbound variable: " + pretty_print(exp.val));
}
default:
throw new Error("unkown exp: " + pretty_print(exp.val));
}
}
var builtins = new Object(null);
builtins["cons"] = generate_fn_code("cons", 2);
builtins["conj/2"] = generate_fn_code("conj", 2);
builtins["disj/2"] = generate_fn_code("disj", 2);
builtins["=="] = generate_fn_code("eqeq", 2);
builtins["=/="] = generate_fn_code("noteqeq", 2);
builtins["symbolo"] = generate_fn_code("symbolo", 1);
builtins["numbero"] = generate_fn_code("numbero", 1);
builtins["absento"] = generate_fn_code("absento", 2);
builtins["build-num"] = generate_fn_code("build_num", 1);
function generate_fn_code(name, arity) {
var c = 0;
var evalers = [];
var callers = [];
for(c = 0; c < arity; c++) {
evalers = evalers.concat(["var e", c, " = eval0(nth(args, ", c+1, "), env);\n"]);
callers = callers.concat([["e", c, "(aenv, cenv)"].join("")]);
}
var args_evald = evalers.join("");
var return_val = ["return function(aenv, cenv) { return ", name, "(", callers.join(", "), "); };"].join("");
return new Function(["args, env, eval0"], [args_evald, return_val].join("\n"));
}
function generate_begin_code(arity) {
var c = 0;
var evalers = [];
var callers = [];
for(c = 0; c < arity; c++) {
evalers = evalers.concat(["var e", c, " = eval0(nth(args, ", c+1, "), env);\n"]);
var prefix = c < arity ? "" : "return ";
callers = callers.concat([[prefix, "e", c, "(aenv, cenv)"].join("")]);
}
var args_evald = evalers.join("");
var return_val = ["return function(aenv, cenv) { ", callers.join("; "), " };"].join("");
return new Function(["args, env, eval0"], [args_evald, return_val].join("\n"));
}
function veval(exp, env) {
return eval0(exp, env)([], []);
}
function build_env(len, e, aenv, cenv) {
var new_env = new Array(len);
var i = 0;
while(e !== null) {
new_env[i++] = e.car(aenv, cenv);
e = e.cdr;
} return new_env;
}
function fresh_n(n, c) {
var m = new Array(n);
while(n-- > 0) {
m[n] = mkvar(c++);
} return [m, c];
}
function apply_fresh(len, closure, aenv, cenv) {
var closure1 = closure(aenv, cenv);
var closure_env = closure1.cdr;
var closure_fn = closure1.car;
return function(mks) {
var c = mks.counter;
var e1_c1 = fresh_n(len, c);
var mks1 = Mks(mks.substitution, e1_c1[1], mks.prefix, mks.constraint_store);
return closure_fn(e1_c1[0], closure_env)(mks1);
};
}
function map_stream(fn, stream) {
return function() {
var $ = pull(stream);
return ($ == null) ? null : cons(fn($.car), map_stream(fn, $.cdr));
};
}
function query_stream(q, qenv, mks) {
var $ = q(mks);
var run_queries = function(mks) {
var qm = map(function(p) { return cons(p.car.string, p.cdr()()); }, qenv);
return query_map(qm, mks);
};
return map_stream(run_queries, $);
}
function stream_generator($) {
var next = $;
return function() {
var cur = next();
if(cur == null) { return null; }
else { next = cur.cdr;
return cur.car; }
};
}
function run_expression(p) {
var desugared = desugar(p, null);
var lifted = lift_frees(desugared);
var exp = lifted.car;
var env = cons(null, lifted.cdr.car);
var mks = lifted.cdr.cdr.car;
var evald = veval(exp, env);
if(procedurep(evald)) {
var q$ = query_stream(evald, env.cdr, mks);
return stream_generator(q$);
} else if (env.cdr === null) {
return evald;
} else {
throw "unbound variables: " + pretty_print(map(car, env.cdr));
}
}
function run_program(p) {
var stream;
if(p == null) { throw "no program" }
map(register_define, p);
while(p != null) {
stream = run_expression(p.car);
p = p.cdr;
} return stream;
}
this.reset = function() { toplevel = new Object(null); };
this.eval = function(ast) { return run_program(ast); };
this.read_eval = function(text) { return run_program(read_program(text)); };
}
| 412 | 0.765359 | 1 | 0.765359 | game-dev | MEDIA | 0.166479 | game-dev | 0.785024 | 1 | 0.785024 |
Fluorohydride/ygopro-scripts | 2,844 | c67831115.lua | --星遺物に差す影
function c67831115.initial_effect(c)
--activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
c:RegisterEffect(e1)
--stats up
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD)
e2:SetCode(EFFECT_UPDATE_ATTACK)
e2:SetRange(LOCATION_FZONE)
e2:SetTargetRange(LOCATION_MZONE,LOCATION_MZONE)
e2:SetTarget(aux.TargetBoolFunction(Card.IsSetCard,0x104))
e2:SetValue(300)
c:RegisterEffect(e2)
local e3=e2:Clone()
e3:SetCode(EFFECT_UPDATE_DEFENSE)
c:RegisterEffect(e3)
--special summon
local e4=Effect.CreateEffect(c)
e4:SetDescription(aux.Stringid(67831115,0))
e4:SetCategory(CATEGORY_SPECIAL_SUMMON)
e4:SetType(EFFECT_TYPE_IGNITION)
e4:SetRange(LOCATION_FZONE)
e4:SetCountLimit(1)
e4:SetTarget(c67831115.sptg)
e4:SetOperation(c67831115.spop)
c:RegisterEffect(e4)
--to grave
local e5=Effect.CreateEffect(c)
e5:SetDescription(aux.Stringid(67831115,1))
e5:SetCategory(CATEGORY_TOGRAVE)
e5:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e5:SetCode(EVENT_BATTLE_DESTROYED)
e5:SetRange(LOCATION_FZONE)
e5:SetCondition(c67831115.tgcon)
e5:SetTarget(c67831115.tgtg)
e5:SetOperation(c67831115.tgop)
c:RegisterEffect(e5)
end
function c67831115.spfilter(c,e,tp)
return c:IsLevelBelow(2) and c:IsRace(RACE_INSECT) and c:IsCanBeSpecialSummoned(e,0,tp,false,false,POS_DEFENSE)
end
function c67831115.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c67831115.spfilter,tp,LOCATION_HAND,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_HAND)
end
function c67831115.spop(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<1 or not e:GetHandler():IsRelateToEffect(e) then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c67831115.spfilter,tp,LOCATION_HAND,0,1,1,nil,e,tp)
if g:GetCount()>0 then
local tc=g:GetFirst()
if Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_DEFENSE)~=0 and tc:IsFacedown() then
Duel.ConfirmCards(1-tp,tc)
end
end
end
function c67831115.cfilter(c,tp)
local rc=c:GetReasonCard()
return c:IsReason(REASON_BATTLE) and c:IsPreviousControler(tp) and c:IsType(TYPE_FLIP)
and rc and rc:IsControler(1-tp) and rc:IsRelateToBattle()
end
function c67831115.tgcon(e,tp,eg,ep,ev,re,r,rp)
local dc=eg:Filter(c67831115.cfilter,nil,tp):GetFirst()
if dc then
e:SetLabelObject(dc:GetReasonCard())
return true
else return false end
end
function c67831115.tgtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_TOGRAVE,e:GetLabelObject(),1,0,0)
end
function c67831115.tgop(e,tp,eg,ep,ev,re,r,rp)
local tc=e:GetLabelObject()
if tc and tc:IsRelateToBattle() then
Duel.SendtoGrave(tc,REASON_EFFECT)
end
end
| 412 | 0.935073 | 1 | 0.935073 | game-dev | MEDIA | 0.967618 | game-dev | 0.969952 | 1 | 0.969952 |
ChengF3ng233/Aluminium | 12,516 | src/main/java/net/minecraft/command/CommandClone.java | package net.minecraft.command;
import com.google.common.collect.Lists;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Blocks;
import net.minecraft.inventory.IInventory;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.BlockPos;
import net.minecraft.world.NextTickListEntry;
import net.minecraft.world.World;
import net.minecraft.world.gen.structure.StructureBoundingBox;
import java.util.LinkedList;
import java.util.List;
public class CommandClone extends CommandBase {
/**
* Gets the name of the command
*/
public String getCommandName() {
return "clone";
}
/**
* Return the required permission level for this command.
*/
public int getRequiredPermissionLevel() {
return 2;
}
/**
* Gets the usage string for the command.
*/
public String getCommandUsage(ICommandSender sender) {
return "commands.clone.usage";
}
/**
* Callback when the command is invoked
*/
public void processCommand(ICommandSender sender, String[] args) throws CommandException {
if (args.length < 9) {
throw new WrongUsageException("commands.clone.usage");
} else {
sender.setCommandStat(CommandResultStats.Type.AFFECTED_BLOCKS, 0);
BlockPos blockpos = parseBlockPos(sender, args, 0, false);
BlockPos blockpos1 = parseBlockPos(sender, args, 3, false);
BlockPos blockpos2 = parseBlockPos(sender, args, 6, false);
StructureBoundingBox structureboundingbox = new StructureBoundingBox(blockpos, blockpos1);
StructureBoundingBox structureboundingbox1 = new StructureBoundingBox(blockpos2, blockpos2.add(structureboundingbox.func_175896_b()));
int i = structureboundingbox.getXSize() * structureboundingbox.getYSize() * structureboundingbox.getZSize();
if (i > 32768) {
throw new CommandException("commands.clone.tooManyBlocks", Integer.valueOf(i), Integer.valueOf(32768));
} else {
boolean flag = false;
Block block = null;
int j = -1;
if ((args.length < 11 || !args[10].equals("force") && !args[10].equals("move")) && structureboundingbox.intersectsWith(structureboundingbox1)) {
throw new CommandException("commands.clone.noOverlap");
} else {
if (args.length >= 11 && args[10].equals("move")) {
flag = true;
}
if (structureboundingbox.minY >= 0 && structureboundingbox.maxY < 256 && structureboundingbox1.minY >= 0 && structureboundingbox1.maxY < 256) {
World world = sender.getEntityWorld();
if (world.isAreaLoaded(structureboundingbox) && world.isAreaLoaded(structureboundingbox1)) {
boolean flag1 = false;
if (args.length >= 10) {
if (args[9].equals("masked")) {
flag1 = true;
} else if (args[9].equals("filtered")) {
if (args.length < 12) {
throw new WrongUsageException("commands.clone.usage");
}
block = getBlockByText(sender, args[11]);
if (args.length >= 13) {
j = parseInt(args[12], 0, 15);
}
}
}
List<CommandClone.StaticCloneData> list = Lists.newArrayList();
List<CommandClone.StaticCloneData> list1 = Lists.newArrayList();
List<CommandClone.StaticCloneData> list2 = Lists.newArrayList();
LinkedList<BlockPos> linkedlist = Lists.newLinkedList();
BlockPos blockpos3 = new BlockPos(structureboundingbox1.minX - structureboundingbox.minX, structureboundingbox1.minY - structureboundingbox.minY, structureboundingbox1.minZ - structureboundingbox.minZ);
for (int k = structureboundingbox.minZ; k <= structureboundingbox.maxZ; ++k) {
for (int l = structureboundingbox.minY; l <= structureboundingbox.maxY; ++l) {
for (int i1 = structureboundingbox.minX; i1 <= structureboundingbox.maxX; ++i1) {
BlockPos blockpos4 = new BlockPos(i1, l, k);
BlockPos blockpos5 = blockpos4.add(blockpos3);
IBlockState iblockstate = world.getBlockState(blockpos4);
if ((!flag1 || iblockstate.getBlock() != Blocks.air) && (block == null || iblockstate.getBlock() == block && (j < 0 || iblockstate.getBlock().getMetaFromState(iblockstate) == j))) {
TileEntity tileentity = world.getTileEntity(blockpos4);
if (tileentity != null) {
NBTTagCompound nbttagcompound = new NBTTagCompound();
tileentity.writeToNBT(nbttagcompound);
list1.add(new CommandClone.StaticCloneData(blockpos5, iblockstate, nbttagcompound));
linkedlist.addLast(blockpos4);
} else if (!iblockstate.getBlock().isFullBlock() && !iblockstate.getBlock().isFullCube()) {
list2.add(new CommandClone.StaticCloneData(blockpos5, iblockstate, null));
linkedlist.addFirst(blockpos4);
} else {
list.add(new CommandClone.StaticCloneData(blockpos5, iblockstate, null));
linkedlist.addLast(blockpos4);
}
}
}
}
}
if (flag) {
for (BlockPos blockpos6 : linkedlist) {
TileEntity tileentity1 = world.getTileEntity(blockpos6);
if (tileentity1 instanceof IInventory) {
((IInventory) tileentity1).clear();
}
world.setBlockState(blockpos6, Blocks.barrier.getDefaultState(), 2);
}
for (BlockPos blockpos7 : linkedlist) {
world.setBlockState(blockpos7, Blocks.air.getDefaultState(), 3);
}
}
List<CommandClone.StaticCloneData> list3 = Lists.newArrayList();
list3.addAll(list);
list3.addAll(list1);
list3.addAll(list2);
List<CommandClone.StaticCloneData> list4 = Lists.reverse(list3);
for (CommandClone.StaticCloneData commandclone$staticclonedata : list4) {
TileEntity tileentity2 = world.getTileEntity(commandclone$staticclonedata.pos);
if (tileentity2 instanceof IInventory) {
((IInventory) tileentity2).clear();
}
world.setBlockState(commandclone$staticclonedata.pos, Blocks.barrier.getDefaultState(), 2);
}
i = 0;
for (CommandClone.StaticCloneData commandclone$staticclonedata1 : list3) {
if (world.setBlockState(commandclone$staticclonedata1.pos, commandclone$staticclonedata1.blockState, 2)) {
++i;
}
}
for (CommandClone.StaticCloneData commandclone$staticclonedata2 : list1) {
TileEntity tileentity3 = world.getTileEntity(commandclone$staticclonedata2.pos);
if (commandclone$staticclonedata2.compound != null && tileentity3 != null) {
commandclone$staticclonedata2.compound.setInteger("x", commandclone$staticclonedata2.pos.getX());
commandclone$staticclonedata2.compound.setInteger("y", commandclone$staticclonedata2.pos.getY());
commandclone$staticclonedata2.compound.setInteger("z", commandclone$staticclonedata2.pos.getZ());
tileentity3.readFromNBT(commandclone$staticclonedata2.compound);
tileentity3.markDirty();
}
world.setBlockState(commandclone$staticclonedata2.pos, commandclone$staticclonedata2.blockState, 2);
}
for (CommandClone.StaticCloneData commandclone$staticclonedata3 : list4) {
world.notifyNeighborsRespectDebug(commandclone$staticclonedata3.pos, commandclone$staticclonedata3.blockState.getBlock());
}
List<NextTickListEntry> list5 = world.func_175712_a(structureboundingbox, false);
if (list5 != null) {
for (NextTickListEntry nextticklistentry : list5) {
if (structureboundingbox.isVecInside(nextticklistentry.position)) {
BlockPos blockpos8 = nextticklistentry.position.add(blockpos3);
world.scheduleBlockUpdate(blockpos8, nextticklistentry.getBlock(), (int) (nextticklistentry.scheduledTime - world.getWorldInfo().getWorldTotalTime()), nextticklistentry.priority);
}
}
}
if (i <= 0) {
throw new CommandException("commands.clone.failed");
} else {
sender.setCommandStat(CommandResultStats.Type.AFFECTED_BLOCKS, i);
notifyOperators(sender, this, "commands.clone.success", Integer.valueOf(i));
}
} else {
throw new CommandException("commands.clone.outOfWorld");
}
} else {
throw new CommandException("commands.clone.outOfWorld");
}
}
}
}
}
public List<String> addTabCompletionOptions(ICommandSender sender, String[] args, BlockPos pos) {
return args.length > 0 && args.length <= 3 ? func_175771_a(args, 0, pos) : (args.length > 3 && args.length <= 6 ? func_175771_a(args, 3, pos) : (args.length > 6 && args.length <= 9 ? func_175771_a(args, 6, pos) : (args.length == 10 ? getListOfStringsMatchingLastWord(args, "replace", "masked", "filtered") : (args.length == 11 ? getListOfStringsMatchingLastWord(args, "normal", "force", "move") : (args.length == 12 && "filtered".equals(args[9]) ? getListOfStringsMatchingLastWord(args, Block.blockRegistry.getKeys()) : null)))));
}
static class StaticCloneData {
public final BlockPos pos;
public final IBlockState blockState;
public final NBTTagCompound compound;
public StaticCloneData(BlockPos posIn, IBlockState stateIn, NBTTagCompound compoundIn) {
this.pos = posIn;
this.blockState = stateIn;
this.compound = compoundIn;
}
}
}
| 412 | 0.93478 | 1 | 0.93478 | game-dev | MEDIA | 0.97654 | game-dev | 0.960959 | 1 | 0.960959 |
MadTekN1/ERModsMerger | 2,628 | SoulsFormats/Binder/BinderReader.cs | using System;
using System.Collections.Generic;
using System.IO.MemoryMappedFiles;
using DotNext.IO.MemoryMappedFiles;
namespace SoulsFormats
{
/// <summary>
/// An on-demand reader for BND3, BND4, BXF3, or BXF4 containers.
/// </summary>
public abstract class BinderReader : IDisposable
{
/// <summary>
/// A timestamp or version number, 8 characters maximum.
/// </summary>
public string Version { get; set; }
/// <summary>
/// Indicates the format of the binder.
/// </summary>
public Binder.Format Format { get; set; }
/// <summary>
/// Write bytes in big-endian order for PS3/X360.
/// </summary>
public bool BigEndian { get; set; }
/// <summary>
/// Determines ordering of flag bits.
/// </summary>
public bool BitBigEndian { get; set; }
/// <summary>
/// Metadata for files present in the binder.
/// </summary>
public List<BinderFileHeader> Files { get; set; }
/// <summary>
/// Reader to read file data from.
/// </summary>
protected BinaryReaderEx DataBR;
protected MemoryMappedFile _mappedFile;
protected IMappedMemoryOwner _mappedAccessor;
/// <summary>
/// Reads file data according to the header at the given index in Files.
/// </summary>
public Memory<byte> ReadFile(int index)
{
return ReadFile(Files[index]);
}
/// <summary>
/// Reads file data according to the given header.
/// </summary>
public Memory<byte> ReadFile(BinderFileHeader fileHeader)
{
BinderFile file = fileHeader.ReadFileData(DataBR);
return file.Bytes;
}
#region IDisposable Support
private bool disposedValue = false; // To detect redundant calls
/// <summary>
/// Releases the unmanaged resources used by the BinderReader and optionally releases the managed resources.
/// </summary>
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
_mappedAccessor?.Dispose();
_mappedFile?.Dispose();
}
disposedValue = true;
}
}
/// <summary>
/// Releases all resources used by the BinderReader.
/// </summary>
public void Dispose()
{
Dispose(true);
}
#endregion
}
}
| 412 | 0.890896 | 1 | 0.890896 | game-dev | MEDIA | 0.544086 | game-dev | 0.524181 | 1 | 0.524181 |
PaintLab/PixelFarm | 3,970 | src/PixelFarm/BackEnd.SharpZipLib/Zip/Compression/InflaterDynHeader.cs | using System;
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
namespace ICSharpCode.SharpZipLib.Zip.Compression
{
class InflaterDynHeader
{
#region Constants
const int LNUM = 0;
const int DNUM = 1;
const int BLNUM = 2;
const int BLLENS = 3;
const int LENS = 4;
const int REPS = 5;
static readonly int[] repMin = { 3, 3, 11 };
static readonly int[] repBits = { 2, 3, 7 };
static readonly int[] BL_ORDER =
{ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 };
#endregion
public bool Decode(StreamManipulator input)
{
decode_loop:
for (;;) {
switch (mode) {
case LNUM:
lnum = input.PeekBits(5);
if (lnum < 0) {
return false;
}
lnum += 257;
input.DropBits(5);
// System.err.println("LNUM: "+lnum);
mode = DNUM;
goto case DNUM; // fall through
case DNUM:
dnum = input.PeekBits(5);
if (dnum < 0) {
return false;
}
dnum++;
input.DropBits(5);
// System.err.println("DNUM: "+dnum);
num = lnum + dnum;
litdistLens = new byte[num];
mode = BLNUM;
goto case BLNUM; // fall through
case BLNUM:
blnum = input.PeekBits(4);
if (blnum < 0) {
return false;
}
blnum += 4;
input.DropBits(4);
blLens = new byte[19];
ptr = 0;
// System.err.println("BLNUM: "+blnum);
mode = BLLENS;
goto case BLLENS; // fall through
case BLLENS:
while (ptr < blnum) {
int len = input.PeekBits(3);
if (len < 0) {
return false;
}
input.DropBits(3);
// System.err.println("blLens["+BL_ORDER[ptr]+"]: "+len);
blLens[BL_ORDER[ptr]] = (byte)len;
ptr++;
}
blTree = new InflaterHuffmanTree(blLens);
blLens = null;
ptr = 0;
mode = LENS;
goto case LENS; // fall through
case LENS: {
int symbol;
while (((symbol = blTree.GetSymbol(input)) & ~15) == 0) {
/* Normal case: symbol in [0..15] */
// System.err.println("litdistLens["+ptr+"]: "+symbol);
litdistLens[ptr++] = lastLen = (byte)symbol;
if (ptr == num) {
/* Finished */
return true;
}
}
/* need more input ? */
if (symbol < 0) {
return false;
}
/* otherwise repeat code */
if (symbol >= 17) {
/* repeat zero */
// System.err.println("repeating zero");
lastLen = 0;
} else {
if (ptr == 0) {
throw new SharpZipBaseException();
}
}
repSymbol = symbol - 16;
}
mode = REPS;
goto case REPS; // fall through
case REPS: {
int bits = repBits[repSymbol];
int count = input.PeekBits(bits);
if (count < 0) {
return false;
}
input.DropBits(bits);
count += repMin[repSymbol];
// System.err.println("litdistLens repeated: "+count);
if (ptr + count > num) {
throw new SharpZipBaseException();
}
while (count-- > 0) {
litdistLens[ptr++] = lastLen;
}
if (ptr == num) {
/* Finished */
return true;
}
}
mode = LENS;
goto decode_loop;
}
}
}
public InflaterHuffmanTree BuildLitLenTree()
{
byte[] litlenLens = new byte[lnum];
Array.Copy(litdistLens, 0, litlenLens, 0, lnum);
return new InflaterHuffmanTree(litlenLens);
}
public InflaterHuffmanTree BuildDistTree()
{
byte[] distLens = new byte[dnum];
Array.Copy(litdistLens, lnum, distLens, 0, dnum);
return new InflaterHuffmanTree(distLens);
}
#region Instance Fields
byte[] blLens;
byte[] litdistLens;
InflaterHuffmanTree blTree;
/// <summary>
/// The current decode mode
/// </summary>
int mode;
int lnum, dnum, blnum, num;
int repSymbol;
byte lastLen;
int ptr;
#endregion
}
}
| 412 | 0.900662 | 1 | 0.900662 | game-dev | MEDIA | 0.415247 | game-dev | 0.992616 | 1 | 0.992616 |
The-Legion-Preservation-Project/LegionCore-7.3.5 | 5,958 | src/server/scripts/Northrend/Nexus/Oculus/boss_drakos.cpp | /*
* Copyright (C) 2008-2014 TrinityCore <http://www.trinitycore.org/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "oculus.h"
enum Spells
{
SPELL_MAGIC_PULL = 51336,
SPELL_THUNDERING_STOMP = 50774,
SPELL_UNSTABLE_SPHERE_PASSIVE = 50756,
SPELL_UNSTABLE_SPHERE_PULSE = 50757,
SPELL_UNSTABLE_SPHERE_TIMER = 50758,
NPC_UNSTABLE_SPHERE = 28166,
};
enum Yells
{
SAY_AGGRO = 0,
SAY_KILL = 1,
SAY_DEATH = 2,
SAY_PULL = 3,
SAY_STOMP = 4
};
enum DrakosAchievement
{
ACHIEV_TIMED_START_EVENT = 18153,
};
enum DrakosEvents
{
EVENT_MAGIC_PULL = 1,
EVENT_STOMP,
EVENT_BOMB_SUMMON
};
class boss_drakos : public CreatureScript
{
public:
boss_drakos() : CreatureScript("boss_drakos") { }
struct boss_drakosAI : public BossAI
{
boss_drakosAI(Creature* creature) : BossAI(creature, DATA_DRAKOS) { }
void Reset() override
{
_Reset();
events.ScheduleEvent(EVENT_MAGIC_PULL, 15000);
events.ScheduleEvent(EVENT_STOMP, 17000);
events.ScheduleEvent(EVENT_BOMB_SUMMON, 2000);
postPull = false;
}
void EnterCombat(Unit* /*who*/) override
{
_EnterCombat();
Talk(SAY_AGGRO);
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_BOMB_SUMMON:
{
Position position = me->GetPosition();
for (uint8 i = 0; i <= (postPull ? 3 : 0); i++)
{
position = me->GetRandomNearPosition(frand(0.0f, 10.0f));
me->SummonCreature(NPC_UNSTABLE_SPHERE, position);
}
}
events.ScheduleEvent(EVENT_BOMB_SUMMON, 2000);
break;
case EVENT_MAGIC_PULL:
DoCast(SPELL_MAGIC_PULL);
postPull = true;
events.ScheduleEvent(EVENT_MAGIC_PULL, 15000);
break;
case EVENT_STOMP:
Talk(SAY_STOMP);
DoCast(SPELL_THUNDERING_STOMP);
events.ScheduleEvent(EVENT_STOMP, 17000);
break;
default:
break;
}
}
DoMeleeAttackIfReady();
}
void JustDied(Unit* /*killer*/) override
{
_JustDied();
Talk(SAY_DEATH);
// start achievement timer (kill Eregos within 20 min)
instance->DoStartTimedAchievement(CRITERIA_TIMED_TYPE_EVENT2, ACHIEV_TIMED_START_EVENT);
}
void KilledUnit(Unit* /*victim*/) override
{
Talk(SAY_KILL);
}
private:
bool postPull;
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetInstanceAI<boss_drakosAI>(creature);
}
};
class npc_unstable_sphere : public CreatureScript
{
public:
npc_unstable_sphere() : CreatureScript("npc_unstable_sphere") { }
struct npc_unstable_sphereAI : public ScriptedAI
{
npc_unstable_sphereAI(Creature* creature) : ScriptedAI(creature) { }
void Reset() override
{
me->SetReactState(REACT_PASSIVE);
me->GetMotionMaster()->MoveRandom(40.0f);
me->AddAura(SPELL_UNSTABLE_SPHERE_PASSIVE, me);
me->AddAura(SPELL_UNSTABLE_SPHERE_TIMER, me);
pulseTimer = 3000;
me->DespawnOrUnsummon(19000);
}
void UpdateAI(uint32 diff) override
{
if (pulseTimer <= diff)
{
DoCast(SPELL_UNSTABLE_SPHERE_PULSE);
pulseTimer = 3 * IN_MILLISECONDS;
}
else
pulseTimer -= diff;
}
private:
uint32 pulseTimer;
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetInstanceAI<npc_unstable_sphereAI>(creature);
}
};
void AddSC_boss_drakos()
{
new boss_drakos();
new npc_unstable_sphere();
}
| 412 | 0.975089 | 1 | 0.975089 | game-dev | MEDIA | 0.992963 | game-dev | 0.986863 | 1 | 0.986863 |
3c0tr/FluidPlayGround | 3,153 | Assets/FPSPanel/FPSGraphicer.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FPSGraphicer : MonoBehaviour
{
[Header("图表设置")]
[SerializeField] private float timeWindow = 5f; // 时间窗口(秒)
[SerializeField] private float maxFPS = 240f; // 最大帧率
[SerializeField] private float graphWidth = 10f; // 图表宽度
[SerializeField] private float graphHeight = 5f; // 图表高度
[SerializeField] private int maxPoints = 100; // 最大点数
[SerializeField] private float updateInterval = 0.5f; // 每0.1秒更新一次图表
private LineRenderer lineRenderer;
private List<float> fpsHistory = new List<float>();
private List<float> timeHistory = new List<float>();
private float currentTime = 0f;
// FPS计算相关变量(和FPSPanel相同的方式)
private float fps;
private float fpsTimer;
private int frameCount;
void Start()
{
// 获取LineRenderer组件
lineRenderer = GetComponent<LineRenderer>();
if (lineRenderer == null)
{
Debug.LogError("未找到LineRenderer组件!");
return;
}
// 设置LineRenderer基本属性
// lineRenderer.useWorldSpace = false;
lineRenderer.positionCount = 0;
}
void Update()
{
currentTime += Time.deltaTime;
// 使用和FPSPanel相同的FPS计算方式
CalculateFPS();
}
private void CalculateFPS()
{
fpsTimer += Time.deltaTime;
frameCount++;
if (fpsTimer >= updateInterval)
{
fps = frameCount / fpsTimer;
fpsTimer = 0f;
frameCount = 0;
// 添加新的数据点(只在更新时添加)
AddDataPoint(fps, currentTime);
// 更新图表显示
UpdateGraph();
}
}
private void AddDataPoint(float fps, float time)
{
fpsHistory.Add(fps);
timeHistory.Add(time);
// 移除超出时间窗口的旧数据
while (timeHistory.Count > 0 && (currentTime - timeHistory[0]) > timeWindow)
{
fpsHistory.RemoveAt(0);
timeHistory.RemoveAt(0);
}
// 限制最大点数以优化性能
while (fpsHistory.Count > maxPoints)
{
fpsHistory.RemoveAt(0);
timeHistory.RemoveAt(0);
}
}
private void UpdateGraph()
{
if (fpsHistory.Count < 2) return;
// 设置LineRenderer点数
lineRenderer.positionCount = fpsHistory.Count;
// 计算图表点位置
Vector3[] positions = new Vector3[fpsHistory.Count];
for (int i = 0; i < fpsHistory.Count; i++)
{
// 时间轴映射(0到timeWindow映射到0到graphWidth)
float normalizedTime = (timeHistory[i] - (currentTime - timeWindow)) / timeWindow;
float x = normalizedTime * graphWidth;
// 帧率轴映射(0到maxFPS映射到0到graphHeight)
float normalizedFPS = Mathf.Clamp01(fpsHistory[i] / maxFPS);
float y = normalizedFPS * graphHeight;
positions[i] = new Vector3(x, y, 0);
}
// 更新LineRenderer位置
lineRenderer.SetPositions(positions);
}
}
| 412 | 0.824203 | 1 | 0.824203 | game-dev | MEDIA | 0.666201 | game-dev | 0.948126 | 1 | 0.948126 |
LandSandBoat/server | 2,847 | src/map/utils/zoneutils.h | /*
===========================================================================
Copyright (c) 2010-2015 Darkstar Dev Teams
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/
===========================================================================
*/
#pragma once
#include "common/cbasetypes.h"
#include "common/ipp.h"
#include "zone.h"
class CBaseEntity;
class CCharEntity;
class CNpcEntity;
namespace zoneutils
{
void LoadZones(const std::vector<uint16>& zoneIds);
void LoadZoneList(IPP mapIPP);
void FreeZoneList();
void InitializeWeather();
void TOTDChange(vanadiel_time::TOTD TOTD);
void SavePlayTime();
auto GetCurrentRegion(uint16 zoneId) -> REGION_TYPE;
auto GetCurrentContinent(uint16 zoneId) -> CONTINENT_TYPE;
auto GetWeatherElement(Weather weather) -> int;
auto GetZone(uint16 zoneId) -> CZone*;
auto GetTrigger(uint16 targId, uint16 zoneId) -> CNpcEntity*;
auto GetEntity(uint32 id, uint8 filter = -1) -> CBaseEntity*;
auto GetCharByName(std::string const& name) -> CCharEntity*;
auto GetCharFromWorld(uint32 charId, uint16 targId) -> CCharEntity*; // returns pointer to character by id and target id
auto GetChar(uint32 charId) -> CCharEntity*; // returns pointer to character by id
auto GetCharToUpdate(uint32 primary, uint32 ternary) -> CCharEntity*; // returns pointer to preferred char to update for party changes
auto GetZonesAssignedToThisProcess(IPP mapIPP) -> std::vector<uint16>;
auto IsZoneAssignedToThisProcess(IPP mapIPP, ZONEID zoneId) -> bool;
void ForEachZone(const std::function<void(CZone*)>& func);
void ForEachZone(const std::vector<uint16>& zoneIds, const std::function<void(CZone*)>& func);
auto GetZoneIPP(uint16 zoneId) -> uint64; // returns IPP for zone ID
auto IsResidentialArea(const CCharEntity* PChar) -> bool; // returns whether or not the area is a residential zone
auto IsAlwaysOutOfNationControl(REGION_TYPE region) -> bool; // returns true if a region should never trigger "in areas outside own nation's control" latent effect; false otherwise.
void AfterZoneIn(CBaseEntity* PEntity); // triggers after a player has finished zoning in
}; // namespace zoneutils
| 412 | 0.893699 | 1 | 0.893699 | game-dev | MEDIA | 0.394218 | game-dev | 0.715666 | 1 | 0.715666 |
ProjectIgnis/CardScripts | 2,456 | unofficial/c511005055.lua | --追従
--Flattery
--scripted by Shad3, fixed and cleaned up by MLD
Duel.EnableUnofficialProc(PROC_STATS_CHANGED)
local s,id=GetID()
function s.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(id,0))
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCategory(CATEGORY_ATKCHANGE)
e1:SetCode(511001265)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DAMAGE_STEP)
e1:SetCondition(s.condition)
e1:SetTarget(s.target)
e1:SetOperation(s.activate)
c:RegisterEffect(e1)
end
function s.cfilter(c,tp)
local val=0
if c:GetFlagEffect(284)>0 then val=c:GetFlagEffectLabel(284) end
return c:IsControler(1-tp) and c:GetAttack()~=val
end
function s.condition(e,tp,eg,ep,ev,re,r,rp)
local ph=Duel.GetCurrentPhase()
return eg:IsExists(s.cfilter,1,nil,tp) and Duel.IsBattlePhase()
end
function s.diffilter1(c,g)
local dif=0
local val=0
if c:GetFlagEffect(284)>0 then val=c:GetFlagEffectLabel(284) end
if c:GetAttack()>val then dif=c:GetAttack()-val
else dif=val-c:GetAttack() end
return g:IsExists(s.diffilter2,1,c,dif)
end
function s.diffilter2(c,dif)
local dif2=0
local val=0
if c:GetFlagEffect(284)>0 then val=c:GetFlagEffectLabel(284) end
if c:GetAttack()>val then dif2=c:GetAttack()-val
else dif2=val-c:GetAttack() end
return dif~=dif2
end
function s.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsFaceup() and chkc:IsControler(tp) end
if chk==0 then return Duel.IsExistingTarget(Card.IsFaceup,tp,LOCATION_MZONE,0,1,nil) end
local ec=eg:GetFirst()
local g=eg:Filter(s.diffilter1,nil,eg)
local g2=Group.CreateGroup()
if #g>0 then g2=g:Select(tp,1,1,nil) ec=g2:GetFirst() end
if #g2>0 then Duel.HintSelection(g2) end
local dam=0
local val=0
if ec:GetFlagEffect(284)>0 then val=ec:GetFlagEffectLabel(284) end
if ec:GetAttack()>val then dam=ec:GetAttack()-val
else dam=val-ec:GetAttack() end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP)
Duel.SelectTarget(tp,Card.IsFaceup,tp,LOCATION_MZONE,0,1,1,nil)
Duel.SetTargetParam(dam)
end
function s.activate(e,tp,eg,ep,ev,re,r,rp)
local atk=Duel.GetChainInfo(0,CHAININFO_TARGET_PARAM)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) and tc:IsFaceup() then
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetReset(RESET_EVENT|RESETS_STANDARD|RESET_PHASE|PHASE_BATTLE)
e1:SetValue(atk)
tc:RegisterEffect(e1)
end
end | 412 | 0.911207 | 1 | 0.911207 | game-dev | MEDIA | 0.983585 | game-dev | 0.932874 | 1 | 0.932874 |
dtrajko/MoravaEngine | 2,369 | MoravaEngine/src/Terrain/TerrainVoxel.cpp | #include "Terrain/TerrainVoxel.h"
TerrainVoxel::TerrainVoxel()
{
m_Scale = glm::vec3(60, 24, 60);
m_NoiseFactor = 0.05f;
m_NoiseThreshold = 0.0f;
m_PerlinNoise = new siv::PerlinNoise();
m_Voxels = std::map<std::string, Voxel*>();
}
TerrainVoxel::TerrainVoxel(glm::vec3 scale, float noiseFactor, float threshold)
{
m_Scale = scale;
m_NoiseFactor = noiseFactor;
m_NoiseThreshold = threshold;
m_PerlinNoise = new siv::PerlinNoise();
m_Voxels = std::map<std::string, Voxel*>();
Generate();
}
void TerrainVoxel::Generate(glm::vec3 scale)
{
Release();
for (int x = 0; x < m_Scale.x; x++) {
for (int y = 0; y < m_Scale.y; y++) {
for (int z = 0; z < m_Scale.z; z++) {
if (m_PerlinNoise->noise3D(x * m_NoiseFactor, y * m_NoiseFactor, z * m_NoiseFactor) >= m_NoiseThreshold) {
Voxel* voxel = new Voxel();
voxel->position = glm::vec3(x - m_Scale.x / 2.0f, y, z - m_Scale.z / 2.0f);
float colorR = voxel->position.x / m_Scale.x;
float colorG = voxel->position.y / m_Scale.y;
float colorB = voxel->position.z / m_Scale.z;
voxel->color = glm::vec4(1.0f - colorR, colorG, 1.0f - colorB, 0.6f);
voxel->textureID = -1; // no texture
m_Voxels.insert(std::make_pair(GetVoxelMapKey(voxel->position), voxel));
}
}
}
}
}
void TerrainVoxel::Release()
{
for (auto voxel : m_Voxels)
{
delete voxel.second;
}
m_Voxels.clear();
}
bool TerrainVoxel::DeleteVoxel(glm::ivec3 position)
{
for (auto it = m_Voxels.begin(); it != m_Voxels.end(); it++) {
if ((*it).second->position == position) {
it = m_Voxels.erase(it);
return true;
}
}
return false;
}
std::string TerrainVoxel::GetVoxelMapKey(glm::ivec3 position)
{
return std::to_string(position.x) + "_" + std::to_string(position.y) + "_" + std::to_string(position.z);
}
unsigned int TerrainVoxel::GetVoxelCount()
{
return (unsigned int)m_Voxels.size();
}
TerrainVoxel::~TerrainVoxel()
{
Release();
delete m_PerlinNoise;
}
float TerrainVoxel::Perlin3D(float x, float y, float z)
{
float ab = (float)m_PerlinNoise->noise2D(x, y);
float bc = (float)m_PerlinNoise->noise2D(y, z);
float ac = (float)m_PerlinNoise->noise2D(x, z);
float ba = (float)m_PerlinNoise->noise2D(y, x);
float cb = (float)m_PerlinNoise->noise2D(z, y);
float ca = (float)m_PerlinNoise->noise2D(z, x);
float abc = ab + bc + ac + ba + cb + ca;
return abc / 6.0f;
}
| 412 | 0.57049 | 1 | 0.57049 | game-dev | MEDIA | 0.536129 | game-dev,graphics-rendering | 0.850869 | 1 | 0.850869 |
AU-Avengers/TOU-Mira | 1,262 | TownOfUs/Options/Roles/Impostor/MinerOptions.cs | using MiraAPI.GameOptions;
using MiraAPI.GameOptions.Attributes;
using MiraAPI.GameOptions.OptionTypes;
using MiraAPI.Utilities;
using TownOfUs.Roles.Impostor;
namespace TownOfUs.Options.Roles.Impostor;
public sealed class MinerOptions : AbstractOptionGroup<MinerRole>
{
public override string GroupName => TouLocale.Get("TouRoleMiner", "Miner");
[ModdedNumberOption("Number Of Miner Vents Per Game", 0f, 30f, 5f, MiraNumberSuffixes.None, "0", true)]
public float MaxMines { get; set; } = 0f;
[ModdedNumberOption("Mine Cooldown", 10f, 60f, 2.5f, MiraNumberSuffixes.Seconds)]
public float MineCooldown { get; set; } = 25f;
[ModdedEnumOption("Mine Visiblity", typeof(MineVisiblityOptions), ["Immediate", "After Use"])]
public MineVisiblityOptions MineVisibility { get; set; } = MineVisiblityOptions.Immediate;
public ModdedNumberOption MineDelay { get; } = new("Mine Delay", 3f, 0f, 10f, 0.5f, MiraNumberSuffixes.Seconds)
{
Visible = () => OptionGroupSingleton<MinerOptions>.Instance.MineVisibility is MineVisiblityOptions.Immediate
};
[ModdedToggleOption("Miner Can Kill With Teammate")]
public bool MinerKill { get; set; } = true;
}
public enum MineVisiblityOptions
{
Immediate,
AfterUse
} | 412 | 0.532771 | 1 | 0.532771 | game-dev | MEDIA | 0.938276 | game-dev | 0.892978 | 1 | 0.892978 |
Pascal-Jansen/Bayesian-Optimization-for-Unity | 5,408 | Library/PackageCache/com.unity.ugui@f250afc9b68d/Tests/Runtime/UGUI/Button/ButtonTests.cs | using System.Collections;
using System.IO;
using NUnit.Framework;
using UnityEditor;
using UnityEngine.EventSystems;
using UnityEngine.TestTools;
using UnityEngine.UI;
using UnityEngine;
internal class ButtonTests : IPrebuildSetup
{
GameObject m_PrefabRoot;
const string kPrefabPath = "Assets/Resources/ButtonPrefab.prefab";
public void Setup()
{
#if UNITY_EDITOR
var rootGO = new GameObject("rootGo");
var canvasGO = new GameObject("Canvas", typeof(Canvas));
canvasGO.transform.SetParent(rootGO.transform);
var canvas = canvasGO.GetComponent<Canvas>();
canvas.referencePixelsPerUnit = 100;
GameObject eventSystemGO = new GameObject("EventSystem", typeof(EventSystem));
eventSystemGO.transform.SetParent(rootGO.transform);
GameObject TestButtonGO = new GameObject("TestButton", typeof(RectTransform), typeof(TestButton));
TestButtonGO.transform.SetParent(canvasGO.transform);
if (!Directory.Exists("Assets/Resources/"))
Directory.CreateDirectory("Assets/Resources/");
PrefabUtility.SaveAsPrefabAsset(rootGO, kPrefabPath);
GameObject.DestroyImmediate(rootGO);
#endif
}
[SetUp]
public void TestSetup()
{
m_PrefabRoot = Object.Instantiate(Resources.Load("ButtonPrefab")) as GameObject;
}
[TearDown]
public void TearDown()
{
GameObject.DestroyImmediate(m_PrefabRoot);
}
[OneTimeTearDown]
public void OneTimeTearDown()
{
#if UNITY_EDITOR
AssetDatabase.DeleteAsset(kPrefabPath);
#endif
}
[Test]
public void PressShouldCallClickHandler()
{
Button button = m_PrefabRoot.GetComponentInChildren<Button>();
bool called = false;
button.onClick.AddListener(() => { called = true; });
button.OnPointerClick(new PointerEventData(m_PrefabRoot.GetComponentInChildren<EventSystem>()) { button = PointerEventData.InputButton.Left });
Assert.True(called);
}
[Test]
public void PressInactiveShouldNotCallClickHandler()
{
Button button = m_PrefabRoot.GetComponentInChildren<Button>();
bool called = false;
button.enabled = false;
button.onClick.AddListener(() => { called = true; });
button.OnPointerClick(new PointerEventData(m_PrefabRoot.GetComponentInChildren<EventSystem>()) { button = PointerEventData.InputButton.Left });
Assert.False(called);
}
[Test]
public void PressNotInteractableShouldNotCallClickHandler()
{
Button button = m_PrefabRoot.GetComponentInChildren<Button>();
bool called = false;
button.interactable = false;
button.onClick.AddListener(() => { called = true; });
button.OnPointerClick(new PointerEventData(m_PrefabRoot.GetComponentInChildren<EventSystem>()) { button = PointerEventData.InputButton.Left });
Assert.False(called);
}
[Test]
public void SelectShouldHoldThePreviousStateAfterDisablingAndEnabling()
{
TestButton button = m_PrefabRoot.GetComponentInChildren<TestButton>();
button.onClick.AddListener(() => {
button.Select();
button.enabled = false;
});
button.OnPointerClick(new PointerEventData(m_PrefabRoot.GetComponentInChildren<EventSystem>()) { button = PointerEventData.InputButton.Left });
Assert.False(button.enabled, "Expected button to not be enabled");
button.enabled = true;
Assert.True(button.isStateSelected, "Expected selected state to be true");
}
[Test]
public void SubmitShouldCallClickHandler()
{
Button button = m_PrefabRoot.GetComponentInChildren<Button>();
bool called = false;
button.onClick.AddListener(() => { called = true; });
button.OnSubmit(null);
Assert.True(called);
}
[Test]
public void SubmitInactiveShouldNotCallClickHandler()
{
Button button = m_PrefabRoot.GetComponentInChildren<Button>();
bool called = false;
button.enabled = false;
button.onClick.AddListener(() => { called = true; });
button.OnSubmit(new PointerEventData(m_PrefabRoot.GetComponentInChildren<EventSystem>()) { button = PointerEventData.InputButton.Left });
Assert.False(called);
}
[Test]
public void SubmitNotInteractableShouldNotCallClickHandler()
{
Button button = m_PrefabRoot.GetComponentInChildren<Button>();
bool called = false;
button.interactable = false;
button.onClick.AddListener(() => { called = true; });
button.OnSubmit(new PointerEventData(m_PrefabRoot.GetComponentInChildren<EventSystem>()) { button = PointerEventData.InputButton.Left });
Assert.False(called);
}
[UnityTest]
public IEnumerator SubmitShouldTransitionToPressedStateAndBackToNormal()
{
TestButton button = m_PrefabRoot.GetComponentInChildren<TestButton>();
Assert.True(button.IsTransitionToNormal(0));
button.OnSubmit(null);
Assert.True(button.isStateNormal);
Assert.True(button.IsTransitionToPressed(1));
yield return new WaitWhile(() => button.StateTransitionCount == 2);
// 3rd transition back to normal should have started
Assert.True(button.IsTransitionToNormal(2));
yield return null;
Assert.True(button.isStateNormal);
}
}
| 412 | 0.861151 | 1 | 0.861151 | game-dev | MEDIA | 0.963443 | game-dev | 0.857979 | 1 | 0.857979 |
AkiKurisu/Real-Agents | 5,884 | Assets/Plugins/UniGLTF/Editor/UniGLTF/Gizmo/BoneSelector.cs | using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.Rendering;
namespace UniGLTF
{
public class BoneSelector : IDisposable
{
List<BoneInfo> _bones;
Animator _currentAnimator;
public Animator CurrentAnimator
{
set
{
if (_currentAnimator == value)
{
return;
}
if (value == null || value.avatar == null || !value.isHuman)
{
_currentAnimator = null;
return;
}
_currentAnimator = value;
_bones = BoneInfo.GetHumanoidBones(value);
}
}
Camera _sceneViewCamera;
CommandBuffer _commandBuffer;
const CameraEvent _cameraEvent = CameraEvent.AfterForwardAlpha;
BoneInfo _selectedBoneInfo;
public BoneInfo SelectedBoneInfo => _selectedBoneInfo;
BoneInfo _hoverBoneInfo;
public BoneInfo HoverBoneInfo => _hoverBoneInfo;
public BoneSelector(Camera camera)
{
_sceneViewCamera = camera;
_commandBuffer = new CommandBuffer();
_commandBuffer.name = "bones";
_sceneViewCamera.AddCommandBuffer(_cameraEvent, _commandBuffer);
}
public void Dispose()
{
CurrentAnimator = null;
if (_commandBuffer != null)
{
_sceneViewCamera.RemoveCommandBuffer(_cameraEvent, _commandBuffer);
_commandBuffer.Dispose();
_commandBuffer = null;
}
}
public void SetTarget(GameObject activeGameObject)
{
CurrentAnimator = activeGameObject?.GetComponentInParent<Animator>();
}
struct HitResult
{
public Vector3 pos1;
public Vector3 pos2;
public float s;
public float Distance()
{
return Vector3.Distance(pos1, pos2);
}
}
Dictionary<BoneInfo, float> _hitBones = new Dictionary<BoneInfo, float>();
public GameObject IntersectBone(Ray ray, bool isHover = false)
{
if (_bones == null)
{
return null;
}
_hitBones.Clear();
foreach (var boneInfo in _bones)
{
var direction = boneInfo.GetTailPosition() - boneInfo.GetHeadPosition();
HitResult hitResult;
if (GetClosestPosition(boneInfo.GetHeadPosition(), direction, ray, out hitResult))
{
var range = (boneInfo.GetTailPosition() - boneInfo.GetHeadPosition()).magnitude * 0.1f;
if (range > hitResult.Distance())
{
_hitBones.Add(boneInfo, hitResult.s);
}
}
}
// clear
if (isHover)
{
return _IntersectBone(ref _hoverBoneInfo);
}
else
{
return _IntersectBone(ref _selectedBoneInfo);
}
}
GameObject _IntersectBone(ref BoneInfo info)
{
info = null;
if (!_hitBones.Any())
{
return null;
}
var min = _hitBones.Aggregate((result, next) => result.Value < next.Value ? result : next);
// Debug.Log("Hit!! = " + min.Key.HeadBone);
info = min.Key;
return info.HeadObject;
}
private bool GetClosestPosition(Vector3 origin, Vector3 targetDirection, Ray ray, out HitResult hitResult)
{
Vector3 deltaPos3 = origin - ray.origin;
Vector4 deltaPos4 = new Vector4(deltaPos3.x, deltaPos3.y, deltaPos3.z, 0.0f);
Vector3 normal = Vector3.Cross(targetDirection, ray.direction);
if (normal.magnitude < 0.001f)
{
hitResult = default;
return false;
}
Matrix4x4 mat = Matrix4x4.identity;
mat.SetColumn(0, new Vector4(ray.direction.x, ray.direction.y, ray.direction.z, 0.0f));
mat.SetColumn(1, new Vector4(-targetDirection.x, -targetDirection.y, -targetDirection.z, 0.0f));
mat.SetColumn(2, new Vector4(normal.x, normal.y, normal.z, 0.0f));
mat = mat.inverse;
var s = Vector4.Dot(mat.GetRow(0), deltaPos4);
var t = Vector4.Dot(mat.GetRow(1), deltaPos4);
if (s < 0.0f)
{
hitResult = default;
return false;
}
if (s < 0.0f) s = 0.0f;
//if (s > 1.0f) s = 1.0f;
if (t < 0.0f) t = 0.0f;
if (t > 1.0f) t = 1.0f;
var pos1 = ray.direction * s + ray.origin;
var pos2 = targetDirection * t + origin;
hitResult = new HitResult()
{
pos1 = pos1,
pos2 = pos2,
s = s
};
return true;
}
public void Draw()
{
if (_bones == null)
{
return;
}
if (_commandBuffer != null)
{
_commandBuffer.Clear();
_commandBuffer.DrawBones(_bones);
if (_selectedBoneInfo != null)
{
_commandBuffer.DrawBone(_selectedBoneInfo, BoneInfoDrawer.SelectedMaterial);
}
if (_hoverBoneInfo != null && _selectedBoneInfo != _hoverBoneInfo)
{
_commandBuffer.DrawBone(_hoverBoneInfo, BoneInfoDrawer.HoverMaterial);
}
}
}
}
}
| 412 | 0.854631 | 1 | 0.854631 | game-dev | MEDIA | 0.947496 | game-dev | 0.870854 | 1 | 0.870854 |
ww-rm/SpineViewer | 61,127 | SpineRuntimes/SpineRuntime38/AnimationState.cs | /******************************************************************************
* Spine Runtimes License Agreement
* Last updated January 1, 2020. Replaces all prior versions.
*
* Copyright (c) 2013-2020, Esoteric Software LLC
*
* Integration of the Spine Runtimes into software or otherwise creating
* derivative works of the Spine Runtimes is permitted under the terms and
* conditions of Section 2 of the Spine Editor License Agreement:
* http://esotericsoftware.com/spine-editor-license
*
* Otherwise, it is permitted to integrate the Spine Runtimes into software
* or otherwise create derivative works of the Spine Runtimes (collectively,
* "Products"), provided that each user of the Products must obtain their own
* Spine Editor license and redistribution of the Products in any form must
* include this license and copyright notice.
*
* THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES,
* BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************/
using System;
using System.Collections.Generic;
namespace SpineRuntime38 {
/// <summary>
/// <para>
/// Applies animations over time, queues animations for later playback, mixes (crossfading) between animations, and applies
/// multiple animations on top of each other (layering).</para>
/// <para>
/// See <a href='http://esotericsoftware.com/spine-applying-animations/'>Applying Animations</a> in the Spine Runtimes Guide.</para>
/// </summary>
public class AnimationState {
static readonly Animation EmptyAnimation = new Animation("<empty>", new ExposedList<Timeline>(), 0);
/// 1) A previously applied timeline has set this property.<para />
/// Result: Mix from the current pose to the timeline pose.
internal const int Subsequent = 0;
/// 1) This is the first timeline to set this property.<para />
/// 2) The next track entry applied after this one does not have a timeline to set this property.<para />
/// Result: Mix from the setup pose to the timeline pose.
internal const int First = 1;
/// 1) A previously applied timeline has set this property.<br>
/// 2) The next track entry to be applied does have a timeline to set this property.<br>
/// 3) The next track entry after that one does not have a timeline to set this property.<br>
/// Result: Mix from the current pose to the timeline pose, but do not mix out. This avoids "dipping" when crossfading
/// animations that key the same property. A subsequent timeline will set this property using a mix.
internal const int HoldSubsequent = 2;
/// 1) This is the first timeline to set this property.<para />
/// 2) The next track entry to be applied does have a timeline to set this property.<para />
/// 3) The next track entry after that one does not have a timeline to set this property.<para />
/// Result: Mix from the setup pose to the timeline pose, but do not mix out. This avoids "dipping" when crossfading animations
/// that key the same property. A subsequent timeline will set this property using a mix.
internal const int HoldFirst = 3;
/// 1) This is the first timeline to set this property.<para />
/// 2) The next track entry to be applied does have a timeline to set this property.<para />
/// 3) The next track entry after that one does have a timeline to set this property.<para />
/// 4) timelineHoldMix stores the first subsequent track entry that does not have a timeline to set this property.<para />
/// Result: The same as HOLD except the mix percentage from the timelineHoldMix track entry is used. This handles when more than
/// 2 track entries in a row have a timeline that sets the same property.<para />
/// Eg, A -> B -> C -> D where A, B, and C have a timeline setting same property, but D does not. When A is applied, to avoid
/// "dipping" A is not mixed out, however D (the first entry that doesn't set the property) mixing in is used to mix out A
/// (which affects B and C). Without using D to mix out, A would be applied fully until mixing completes, then snap to the mixed
/// out position.
internal const int HoldMix = 4;
internal const int Setup = 1, Current = 2;
protected AnimationStateData data;
private readonly ExposedList<TrackEntry> tracks = new ExposedList<TrackEntry>();
private readonly ExposedList<Event> events = new ExposedList<Event>();
// difference to libgdx reference: delegates are used for event callbacks instead of 'final SnapshotArray<AnimationStateListener> listeners'.
internal void OnStart (TrackEntry entry) { if (Start != null) Start(entry); }
internal void OnInterrupt (TrackEntry entry) { if (Interrupt != null) Interrupt(entry); }
internal void OnEnd (TrackEntry entry) { if (End != null) End(entry); }
internal void OnDispose (TrackEntry entry) { if (Dispose != null) Dispose(entry); }
internal void OnComplete (TrackEntry entry) { if (Complete != null) Complete(entry); }
internal void OnEvent (TrackEntry entry, Event e) { if (Event != null) Event(entry, e); }
public delegate void TrackEntryDelegate (TrackEntry trackEntry);
public event TrackEntryDelegate Start, Interrupt, End, Dispose, Complete;
public delegate void TrackEntryEventDelegate (TrackEntry trackEntry, Event e);
public event TrackEntryEventDelegate Event;
public void AssignEventSubscribersFrom (AnimationState src) {
Event = src.Event;
Start = src.Start;
Interrupt = src.Interrupt;
End = src.End;
Dispose = src.Dispose;
Complete = src.Complete;
}
public void AddEventSubscribersFrom (AnimationState src) {
Event += src.Event;
Start += src.Start;
Interrupt += src.Interrupt;
End += src.End;
Dispose += src.Dispose;
Complete += src.Complete;
}
// end of difference
private readonly EventQueue queue; // Initialized by constructor.
private readonly HashSet<int> propertyIDs = new HashSet<int>();
private bool animationsChanged;
private float timeScale = 1;
private int unkeyedState;
private readonly Pool<TrackEntry> trackEntryPool = new Pool<TrackEntry>();
public AnimationState (AnimationStateData data) {
if (data == null) throw new ArgumentNullException("data", "data cannot be null.");
this.data = data;
this.queue = new EventQueue(
this,
delegate { this.animationsChanged = true; },
trackEntryPool
);
}
/// <summary>
/// Increments the track entry <see cref="TrackEntry.TrackTime"/>, setting queued animations as current if needed.</summary>
/// <param name="delta">delta time</param>
public void Update (float delta) {
delta *= timeScale;
var tracksItems = tracks.Items;
for (int i = 0, n = tracks.Count; i < n; i++) {
TrackEntry current = tracksItems[i];
if (current == null) continue;
current.animationLast = current.nextAnimationLast;
current.trackLast = current.nextTrackLast;
float currentDelta = delta * current.timeScale;
if (current.delay > 0) {
current.delay -= currentDelta;
if (current.delay > 0) continue;
currentDelta = -current.delay;
current.delay = 0;
}
TrackEntry next = current.next;
if (next != null) {
// When the next entry's delay is passed, change to the next entry, preserving leftover time.
float nextTime = current.trackLast - next.delay;
if (nextTime >= 0) {
next.delay = 0;
next.trackTime += current.timeScale == 0 ? 0 : (nextTime / current.timeScale + delta) * next.timeScale;
current.trackTime += currentDelta;
SetCurrent(i, next, true);
while (next.mixingFrom != null) {
next.mixTime += delta;
next = next.mixingFrom;
}
continue;
}
} else if (current.trackLast >= current.trackEnd && current.mixingFrom == null) {
// Clear the track when there is no next entry, the track end time is reached, and there is no mixingFrom.
tracksItems[i] = null;
queue.End(current);
DisposeNext(current);
continue;
}
if (current.mixingFrom != null && UpdateMixingFrom(current, delta)) {
// End mixing from entries once all have completed.
TrackEntry from = current.mixingFrom;
current.mixingFrom = null;
if (from != null) from.mixingTo = null;
while (from != null) {
queue.End(from);
from = from.mixingFrom;
}
}
current.trackTime += currentDelta;
}
queue.Drain();
}
/// <summary>Returns true when all mixing from entries are complete.</summary>
private bool UpdateMixingFrom (TrackEntry to, float delta) {
TrackEntry from = to.mixingFrom;
if (from == null) return true;
bool finished = UpdateMixingFrom(from, delta);
from.animationLast = from.nextAnimationLast;
from.trackLast = from.nextTrackLast;
// Require mixTime > 0 to ensure the mixing from entry was applied at least once.
if (to.mixTime > 0 && to.mixTime >= to.mixDuration) {
// Require totalAlpha == 0 to ensure mixing is complete, unless mixDuration == 0 (the transition is a single frame).
if (from.totalAlpha == 0 || to.mixDuration == 0) {
to.mixingFrom = from.mixingFrom;
if (from.mixingFrom != null) from.mixingFrom.mixingTo = to;
to.interruptAlpha = from.interruptAlpha;
queue.End(from);
}
return finished;
}
from.trackTime += delta * from.timeScale;
to.mixTime += delta;
return false;
}
/// <summary>
/// Poses the skeleton using the track entry animations. The animation state is not changed, so can be applied to multiple
/// skeletons to pose them identically.</summary>
/// <returns>True if any animations were applied.</returns>
public bool Apply (Skeleton skeleton) {
if (skeleton == null) throw new ArgumentNullException("skeleton", "skeleton cannot be null.");
if (animationsChanged) AnimationsChanged();
var events = this.events;
bool applied = false;
var tracksItems = tracks.Items;
for (int i = 0, n = tracks.Count; i < n; i++) {
TrackEntry current = tracksItems[i];
if (current == null || current.delay > 0) continue;
applied = true;
// Track 0 animations aren't for layering, so do not show the previously applied animations before the first key.
MixBlend blend = i == 0 ? MixBlend.First : current.mixBlend;
// Apply mixing from entries first.
float mix = current.alpha;
if (current.mixingFrom != null)
mix *= ApplyMixingFrom(current, skeleton, blend);
else if (current.trackTime >= current.trackEnd && current.next == null) //
mix = 0; // Set to setup pose the last time the entry will be applied.
// Apply current entry.
float animationLast = current.animationLast, animationTime = current.AnimationTime;
int timelineCount = current.animation.timelines.Count;
var timelines = current.animation.timelines;
var timelinesItems = timelines.Items;
if ((i == 0 && mix == 1) || blend == MixBlend.Add) {
for (int ii = 0; ii < timelineCount; ii++) {
var timeline = timelinesItems[ii];
if (timeline is AttachmentTimeline)
ApplyAttachmentTimeline((AttachmentTimeline)timeline, skeleton, animationTime, blend, true);
else
timeline.Apply(skeleton, animationLast, animationTime, events, mix, blend, MixDirection.In);
}
} else {
var timelineMode = current.timelineMode.Items;
bool firstFrame = current.timelinesRotation.Count != timelineCount << 1;
if (firstFrame) current.timelinesRotation.Resize(timelines.Count << 1);
var timelinesRotation = current.timelinesRotation.Items;
for (int ii = 0; ii < timelineCount; ii++) {
Timeline timeline = timelinesItems[ii];
MixBlend timelineBlend = timelineMode[ii] == AnimationState.Subsequent ? blend : MixBlend.Setup;
var rotateTimeline = timeline as RotateTimeline;
if (rotateTimeline != null)
ApplyRotateTimeline(rotateTimeline, skeleton, animationTime, mix, timelineBlend, timelinesRotation,
ii << 1, firstFrame);
else if (timeline is AttachmentTimeline)
ApplyAttachmentTimeline((AttachmentTimeline)timeline, skeleton, animationTime, blend, true);
else
timeline.Apply(skeleton, animationLast, animationTime, events, mix, timelineBlend, MixDirection.In);
}
}
QueueEvents(current, animationTime);
events.Clear(false);
current.nextAnimationLast = animationTime;
current.nextTrackLast = current.trackTime;
}
// Set slots attachments to the setup pose, if needed. This occurs if an animation that is mixing out sets attachments so
// subsequent timelines see any deform, but the subsequent timelines don't set an attachment (eg they are also mixing out or
// the time is before the first key).
int setupState = unkeyedState + Setup;
var slots = skeleton.slots.Items;
for (int i = 0, n = skeleton.slots.Count; i < n; i++) {
Slot slot = (Slot)slots[i];
if (slot.attachmentState == setupState) {
string attachmentName = slot.data.attachmentName;
slot.Attachment = (attachmentName == null ? null : skeleton.GetAttachment(slot.data.index, attachmentName));
}
}
unkeyedState += 2; // Increasing after each use avoids the need to reset attachmentState for every slot.
queue.Drain();
return applied;
}
/// <summary>Version of <see cref="Apply"/> only applying EventTimelines for lightweight off-screen updates.</summary>
// Note: This method is not part of the libgdx reference implementation.
public bool ApplyEventTimelinesOnly (Skeleton skeleton) {
if (skeleton == null) throw new ArgumentNullException("skeleton", "skeleton cannot be null.");
var events = this.events;
bool applied = false;
var tracksItems = tracks.Items;
for (int i = 0, n = tracks.Count; i < n; i++) {
TrackEntry current = tracksItems[i];
if (current == null || current.delay > 0) continue;
applied = true;
// Apply mixing from entries first.
if (current.mixingFrom != null)
ApplyMixingFromEventTimelinesOnly(current, skeleton);
// Apply current entry.
float animationLast = current.animationLast, animationTime = current.AnimationTime;
int timelineCount = current.animation.timelines.Count;
var timelines = current.animation.timelines;
var timelinesItems = timelines.Items;
for (int ii = 0; ii < timelineCount; ii++) {
Timeline timeline = timelinesItems[ii];
if (timeline is EventTimeline)
timeline.Apply(skeleton, animationLast, animationTime, events, 1.0f, MixBlend.Setup, MixDirection.In);
}
QueueEvents(current, animationTime);
events.Clear(false);
current.nextAnimationLast = animationTime;
current.nextTrackLast = current.trackTime;
}
queue.Drain();
return applied;
}
private float ApplyMixingFrom (TrackEntry to, Skeleton skeleton, MixBlend blend) {
TrackEntry from = to.mixingFrom;
if (from.mixingFrom != null) ApplyMixingFrom(from, skeleton, blend);
float mix;
if (to.mixDuration == 0) { // Single frame mix to undo mixingFrom changes.
mix = 1;
if (blend == MixBlend.First) blend = MixBlend.Setup; // Tracks > 0 are transparent and can't reset to setup pose.
} else {
mix = to.mixTime / to.mixDuration;
if (mix > 1) mix = 1;
if (blend != MixBlend.First) blend = from.mixBlend; // Track 0 ignores track mix blend.
}
var eventBuffer = mix < from.eventThreshold ? this.events : null;
bool attachments = mix < from.attachmentThreshold, drawOrder = mix < from.drawOrderThreshold;
float animationLast = from.animationLast, animationTime = from.AnimationTime;
var timelines = from.animation.timelines;
int timelineCount = timelines.Count;
var timelinesItems = timelines.Items;
float alphaHold = from.alpha * to.interruptAlpha, alphaMix = alphaHold * (1 - mix);
if (blend == MixBlend.Add) {
for (int i = 0; i < timelineCount; i++)
timelinesItems[i].Apply(skeleton, animationLast, animationTime, eventBuffer, alphaMix, blend, MixDirection.Out);
} else {
var timelineMode = from.timelineMode.Items;
var timelineHoldMix = from.timelineHoldMix.Items;
bool firstFrame = from.timelinesRotation.Count != timelineCount << 1;
if (firstFrame) from.timelinesRotation.Resize(timelines.Count << 1); // from.timelinesRotation.setSize
var timelinesRotation = from.timelinesRotation.Items;
from.totalAlpha = 0;
for (int i = 0; i < timelineCount; i++) {
Timeline timeline = timelinesItems[i];
MixDirection direction = MixDirection.Out;
MixBlend timelineBlend;
float alpha;
switch (timelineMode[i]) {
case AnimationState.Subsequent:
if (!drawOrder && timeline is DrawOrderTimeline) continue;
timelineBlend = blend;
alpha = alphaMix;
break;
case AnimationState.First:
timelineBlend = MixBlend.Setup;
alpha = alphaMix;
break;
case AnimationState.HoldSubsequent:
timelineBlend = blend;
alpha = alphaHold;
break;
case AnimationState.HoldFirst:
timelineBlend = MixBlend.Setup;
alpha = alphaHold;
break;
default: // HoldMix
timelineBlend = MixBlend.Setup;
TrackEntry holdMix = timelineHoldMix[i];
alpha = alphaHold * Math.Max(0, 1 - holdMix.mixTime / holdMix.mixDuration);
break;
}
from.totalAlpha += alpha;
var rotateTimeline = timeline as RotateTimeline;
if (rotateTimeline != null) {
ApplyRotateTimeline(rotateTimeline, skeleton, animationTime, alpha, timelineBlend, timelinesRotation,
i << 1, firstFrame);
} else if (timeline is AttachmentTimeline) {
ApplyAttachmentTimeline((AttachmentTimeline)timeline, skeleton, animationTime, timelineBlend, attachments);
} else {
if (drawOrder && timeline is DrawOrderTimeline && timelineBlend == MixBlend.Setup)
direction = MixDirection.In;
timeline.Apply(skeleton, animationLast, animationTime, eventBuffer, alpha, timelineBlend, direction);
}
}
}
if (to.mixDuration > 0) QueueEvents(from, animationTime);
this.events.Clear(false);
from.nextAnimationLast = animationTime;
from.nextTrackLast = from.trackTime;
return mix;
}
/// <summary>Version of <see cref="ApplyMixingFrom"/> only applying EventTimelines for lightweight off-screen updates.</summary>
// Note: This method is not part of the libgdx reference implementation.
private float ApplyMixingFromEventTimelinesOnly (TrackEntry to, Skeleton skeleton) {
TrackEntry from = to.mixingFrom;
if (from.mixingFrom != null) ApplyMixingFromEventTimelinesOnly(from, skeleton);
float mix;
if (to.mixDuration == 0) { // Single frame mix to undo mixingFrom changes.
mix = 1;
}
else {
mix = to.mixTime / to.mixDuration;
if (mix > 1) mix = 1;
}
var eventBuffer = mix < from.eventThreshold ? this.events : null;
if (eventBuffer == null)
return mix;
float animationLast = from.animationLast, animationTime = from.AnimationTime;
var timelines = from.animation.timelines;
int timelineCount = timelines.Count;
var timelinesItems = timelines.Items;
for (int i = 0; i < timelineCount; i++) {
var timeline = timelinesItems[i];
if (timeline is EventTimeline)
timeline.Apply(skeleton, animationLast, animationTime, eventBuffer, 0, MixBlend.Setup, MixDirection.Out);
}
if (to.mixDuration > 0) QueueEvents(from, animationTime);
this.events.Clear(false);
from.nextAnimationLast = animationTime;
from.nextTrackLast = from.trackTime;
return mix;
}
/// <summary> Applies the attachment timeline and sets <see cref="Slot.attachmentState"/>.</summary>
/// <param name="attachments">False when: 1) the attachment timeline is mixing out, 2) mix < attachmentThreshold, and 3) the timeline
/// is not the last timeline to set the slot's attachment. In that case the timeline is applied only so subsequent
/// timelines see any deform.</param>
private void ApplyAttachmentTimeline (AttachmentTimeline timeline, Skeleton skeleton, float time, MixBlend blend,
bool attachments) {
Slot slot = skeleton.slots.Items[timeline.slotIndex];
if (!slot.bone.active) return;
float[] frames = timeline.frames;
if (time < frames[0]) { // Time is before first frame.
if (blend == MixBlend.Setup || blend == MixBlend.First)
SetAttachment(skeleton, slot, slot.data.attachmentName, attachments);
}
else {
int frameIndex;
if (time >= frames[frames.Length - 1]) // Time is after last frame.
frameIndex = frames.Length - 1;
else
frameIndex = Animation.BinarySearch(frames, time) - 1;
SetAttachment(skeleton, slot, timeline.attachmentNames[frameIndex], attachments);
}
// If an attachment wasn't set (ie before the first frame or attachments is false), set the setup attachment later.
if (slot.attachmentState <= unkeyedState) slot.attachmentState = unkeyedState + Setup;
}
private void SetAttachment (Skeleton skeleton, Slot slot, String attachmentName, bool attachments) {
slot.Attachment = attachmentName == null ? null : skeleton.GetAttachment(slot.data.index, attachmentName);
if (attachments) slot.attachmentState = unkeyedState + Current;
}
/// <summary>
/// Applies the rotate timeline, mixing with the current pose while keeping the same rotation direction chosen as the shortest
/// the first time the mixing was applied.</summary>
static private void ApplyRotateTimeline (RotateTimeline timeline, Skeleton skeleton, float time, float alpha, MixBlend blend,
float[] timelinesRotation, int i, bool firstFrame) {
if (firstFrame) timelinesRotation[i] = 0;
if (alpha == 1) {
timeline.Apply(skeleton, 0, time, null, 1, blend, MixDirection.In);
return;
}
Bone bone = skeleton.bones.Items[timeline.boneIndex];
if (!bone.active) return;
float[] frames = timeline.frames;
float r1, r2;
if (time < frames[0]) { // Time is before first frame.
switch (blend) {
case MixBlend.Setup:
bone.rotation = bone.data.rotation;
return;
default:
return;
case MixBlend.First:
r1 = bone.rotation;
r2 = bone.data.rotation;
break;
}
} else {
r1 = blend == MixBlend.Setup ? bone.data.rotation : bone.rotation;
if (time >= frames[frames.Length - RotateTimeline.ENTRIES]) // Time is after last frame.
r2 = bone.data.rotation + frames[frames.Length + RotateTimeline.PREV_ROTATION];
else {
// Interpolate between the previous frame and the current frame.
int frame = Animation.BinarySearch(frames, time, RotateTimeline.ENTRIES);
float prevRotation = frames[frame + RotateTimeline.PREV_ROTATION];
float frameTime = frames[frame];
float percent = timeline.GetCurvePercent((frame >> 1) - 1,
1 - (time - frameTime) / (frames[frame + RotateTimeline.PREV_TIME] - frameTime));
r2 = frames[frame + RotateTimeline.ROTATION] - prevRotation;
r2 -= (16384 - (int)(16384.499999999996 - r2 / 360)) * 360;
r2 = prevRotation + r2 * percent + bone.data.rotation;
r2 -= (16384 - (int)(16384.499999999996 - r2 / 360)) * 360;
}
}
// Mix between rotations using the direction of the shortest route on the first frame.
float total, diff = r2 - r1;
diff -= (16384 - (int)(16384.499999999996 - diff / 360)) * 360;
if (diff == 0) {
total = timelinesRotation[i];
} else {
float lastTotal, lastDiff;
if (firstFrame) {
lastTotal = 0;
lastDiff = diff;
} else {
lastTotal = timelinesRotation[i]; // Angle and direction of mix, including loops.
lastDiff = timelinesRotation[i + 1]; // Difference between bones.
}
bool current = diff > 0, dir = lastTotal >= 0;
// Detect cross at 0 (not 180).
if (Math.Sign(lastDiff) != Math.Sign(diff) && Math.Abs(lastDiff) <= 90) {
// A cross after a 360 rotation is a loop.
if (Math.Abs(lastTotal) > 180) lastTotal += 360 * Math.Sign(lastTotal);
dir = current;
}
total = diff + lastTotal - lastTotal % 360; // Store loops as part of lastTotal.
if (dir != current) total += 360 * Math.Sign(lastTotal);
timelinesRotation[i] = total;
}
timelinesRotation[i + 1] = diff;
r1 += total * alpha;
bone.rotation = r1 - (16384 - (int)(16384.499999999996 - r1 / 360)) * 360;
}
private void QueueEvents (TrackEntry entry, float animationTime) {
float animationStart = entry.animationStart, animationEnd = entry.animationEnd;
float duration = animationEnd - animationStart;
float trackLastWrapped = entry.trackLast % duration;
// Queue events before complete.
var events = this.events;
var eventsItems = events.Items;
int i = 0, n = events.Count;
for (; i < n; i++) {
Event e = eventsItems[i];
if (e.time < trackLastWrapped) break;
if (e.time > animationEnd) continue; // Discard events outside animation start/end.
queue.Event(entry, e);
}
// Queue complete if completed a loop iteration or the animation.
bool complete = false;
if (entry.loop)
complete = duration == 0 || (trackLastWrapped > entry.trackTime % duration);
else
complete = animationTime >= animationEnd && entry.animationLast < animationEnd;
if (complete) queue.Complete(entry);
// Queue events after complete.
for (; i < n; i++) {
Event e = eventsItems[i];
if (e.time < animationStart) continue; // Discard events outside animation start/end.
queue.Event(entry, eventsItems[i]);
}
}
/// <summary>
/// <para>Removes all animations from all tracks, leaving skeletons in their current pose.</para>
/// <para>
/// It may be desired to use <see cref="AnimationState.SetEmptyAnimations(float)"/> to mix the skeletons back to the setup pose,
/// rather than leaving them in their current pose.</para>
/// </summary>
public void ClearTracks () {
bool oldDrainDisabled = queue.drainDisabled;
queue.drainDisabled = true;
for (int i = 0, n = tracks.Count; i < n; i++) {
ClearTrack(i);
}
tracks.Clear();
queue.drainDisabled = oldDrainDisabled;
queue.Drain();
}
/// <summary>
/// <para>Removes all animations from the track, leaving skeletons in their current pose.</para>
/// <para>
/// It may be desired to use <see cref="AnimationState.SetEmptyAnimation(int, float)"/> to mix the skeletons back to the setup pose,
/// rather than leaving them in their current pose.</para>
/// </summary>
public void ClearTrack (int trackIndex) {
if (trackIndex >= tracks.Count) return;
TrackEntry current = tracks.Items[trackIndex];
if (current == null) return;
queue.End(current);
DisposeNext(current);
TrackEntry entry = current;
while (true) {
TrackEntry from = entry.mixingFrom;
if (from == null) break;
queue.End(from);
entry.mixingFrom = null;
entry.mixingTo = null;
entry = from;
}
tracks.Items[current.trackIndex] = null;
queue.Drain();
}
/// <summary>Sets the active TrackEntry for a given track number.</summary>
private void SetCurrent (int index, TrackEntry current, bool interrupt) {
TrackEntry from = ExpandToIndex(index);
tracks.Items[index] = current;
if (from != null) {
if (interrupt) queue.Interrupt(from);
current.mixingFrom = from;
from.mixingTo = current;
current.mixTime = 0;
// Store the interrupted mix percentage.
if (from.mixingFrom != null && from.mixDuration > 0)
current.interruptAlpha *= Math.Min(1, from.mixTime / from.mixDuration);
from.timelinesRotation.Clear(); // Reset rotation for mixing out, in case entry was mixed in.
}
queue.Start(current); // triggers AnimationsChanged
}
/// <summary>Sets an animation by name. <seealso cref="SetAnimation(int, Animation, bool)" /></summary>
public TrackEntry SetAnimation (int trackIndex, string animationName, bool loop) {
Animation animation = data.skeletonData.FindAnimation(animationName);
if (animation == null) throw new ArgumentException("Animation not found: " + animationName, "animationName");
return SetAnimation(trackIndex, animation, loop);
}
/// <summary>Sets the current animation for a track, discarding any queued animations. If the formerly current track entry was never
/// applied to a skeleton, it is replaced (not mixed from).</summary>
/// <param name="loop">If true, the animation will repeat. If false it will not, instead its last frame is applied if played beyond its
/// duration. In either case<see cref="TrackEntry.TrackEnd"/> determines when the track is cleared.</param>
/// <returns> A track entry to allow further customization of animation playback. References to the track entry must not be kept
/// after the <see cref="AnimationState.Dispose"/> event occurs.</returns>
public TrackEntry SetAnimation (int trackIndex, Animation animation, bool loop) {
if (animation == null) throw new ArgumentNullException("animation", "animation cannot be null.");
bool interrupt = true;
TrackEntry current = ExpandToIndex(trackIndex);
if (current != null) {
if (current.nextTrackLast == -1) {
// Don't mix from an entry that was never applied.
tracks.Items[trackIndex] = current.mixingFrom;
queue.Interrupt(current);
queue.End(current);
DisposeNext(current);
current = current.mixingFrom;
interrupt = false; // mixingFrom is current again, but don't interrupt it twice.
} else {
DisposeNext(current);
}
}
TrackEntry entry = NewTrackEntry(trackIndex, animation, loop, current);
SetCurrent(trackIndex, entry, interrupt);
queue.Drain();
return entry;
}
/// <summary>Queues an animation by name.</summary>
/// <seealso cref="AddAnimation(int, Animation, bool, float)" />
public TrackEntry AddAnimation (int trackIndex, string animationName, bool loop, float delay) {
Animation animation = data.skeletonData.FindAnimation(animationName);
if (animation == null) throw new ArgumentException("Animation not found: " + animationName, "animationName");
return AddAnimation(trackIndex, animation, loop, delay);
}
/// <summary>Adds an animation to be played after the current or last queued animation for a track. If the track is empty, it is
/// equivalent to calling <see cref="SetAnimation(int, Animation, bool)"/>.</summary>
/// <param name="delay">
/// If > 0, sets <see cref="TrackEntry.Delay"/>. If <= 0, the delay set is the duration of the previous track entry
/// minus any mix duration (from the {@link AnimationStateData}) plus the specified <code>Delay</code> (ie the mix
/// ends at (<code>Delay</code> = 0) or before (<code>Delay</code> < 0) the previous track entry duration). If the
/// previous entry is looping, its next loop completion is used instead of its duration.
/// </param>
/// <returns>A track entry to allow further customization of animation playback. References to the track entry must not be kept
/// after the <see cref="AnimationState.Dispose"/> event occurs.</returns>
public TrackEntry AddAnimation (int trackIndex, Animation animation, bool loop, float delay) {
if (animation == null) throw new ArgumentNullException("animation", "animation cannot be null.");
TrackEntry last = ExpandToIndex(trackIndex);
if (last != null) {
while (last.next != null)
last = last.next;
}
TrackEntry entry = NewTrackEntry(trackIndex, animation, loop, last);
if (last == null) {
SetCurrent(trackIndex, entry, true);
queue.Drain();
} else {
last.next = entry;
if (delay <= 0) {
float duration = last.animationEnd - last.animationStart;
if (duration != 0) {
if (last.loop) {
delay += duration * (1 + (int)(last.trackTime / duration)); // Completion of next loop.
} else {
delay += Math.Max(duration, last.trackTime); // After duration, else next update.
}
delay -= data.GetMix(last.animation, animation);
} else
delay = last.trackTime; // Next update.
}
}
entry.delay = delay;
return entry;
}
/// <summary>
/// <para>Sets an empty animation for a track, discarding any queued animations, and sets the track entry's
/// <see cref="TrackEntry.getMixDuration()"/>. An empty animation has no timelines and serves as a placeholder for mixing in or out.</para>
/// <para>
/// Mixing out is done by setting an empty animation with a mix duration using either <see cref="AnimationState.SetEmptyAnimation(int, float)"/>,
/// <see cref="AnimationState.SetEmptyAnimations(float)"/>, or <see cref="AnimationState.AddEmptyAnimation(int, float, float)"/>. Mixing to an empty animation causes
/// the previous animation to be applied less and less over the mix duration. Properties keyed in the previous animation
/// transition to the value from lower tracks or to the setup pose value if no lower tracks key the property. A mix duration of
/// 0 still mixes out over one frame.</para>
/// <para>
/// Mixing in is done by first setting an empty animation, then adding an animation using
/// <see cref="AnimationState.AddAnimation(int, Animation, boolean, float)"/> and on the returned track entry, set the
/// <see cref="TrackEntry.SetMixDuration(float)"/>. Mixing from an empty animation causes the new animation to be applied more and
/// more over the mix duration. Properties keyed in the new animation transition from the value from lower tracks or from the
/// setup pose value if no lower tracks key the property to the value keyed in the new animation.</para>
/// </summary>
public TrackEntry SetEmptyAnimation (int trackIndex, float mixDuration) {
TrackEntry entry = SetAnimation(trackIndex, AnimationState.EmptyAnimation, false);
entry.mixDuration = mixDuration;
entry.trackEnd = mixDuration;
return entry;
}
/// <summary>
/// Adds an empty animation to be played after the current or last queued animation for a track, and sets the track entry's
/// <see cref="TrackEntry.MixDuration"/>. If the track is empty, it is equivalent to calling
/// <see cref="AnimationState.SetEmptyAnimation(int, float)"/>.</summary>
/// <seealso cref="AnimationState.SetEmptyAnimation(int, float)"/>
/// <param name="trackIndex">Track number.</param>
/// <param name="mixDuration">Mix duration.</param>
/// <param name="delay">If > 0, sets <see cref="TrackEntry.Delay"/>. If <= 0, the delay set is the duration of the previous track entry
/// minus any mix duration plus the specified <code>Delay</code> (ie the mix ends at (<code>Delay</code> = 0) or
/// before (<code>Delay</code> < 0) the previous track entry duration). If the previous entry is looping, its next
/// loop completion is used instead of its duration.</param>
/// <returns> A track entry to allow further customization of animation playback. References to the track entry must not be kept
/// after the <see cref="AnimationState.Dispose"/> event occurs.
/// </returns>
public TrackEntry AddEmptyAnimation (int trackIndex, float mixDuration, float delay) {
if (delay <= 0) delay -= mixDuration;
TrackEntry entry = AddAnimation(trackIndex, AnimationState.EmptyAnimation, false, delay);
entry.mixDuration = mixDuration;
entry.trackEnd = mixDuration;
return entry;
}
/// <summary>
/// Sets an empty animation for every track, discarding any queued animations, and mixes to it over the specified mix
/// duration.</summary>
public void SetEmptyAnimations (float mixDuration) {
bool oldDrainDisabled = queue.drainDisabled;
queue.drainDisabled = true;
for (int i = 0, n = tracks.Count; i < n; i++) {
TrackEntry current = tracks.Items[i];
if (current != null) SetEmptyAnimation(current.trackIndex, mixDuration);
}
queue.drainDisabled = oldDrainDisabled;
queue.Drain();
}
private TrackEntry ExpandToIndex (int index) {
if (index < tracks.Count) return tracks.Items[index];
tracks.Resize(index + 1);
return null;
}
/// <summary>Object-pooling version of new TrackEntry. Obtain an unused TrackEntry from the pool and clear/initialize its values.</summary>
/// <param name="last">May be null.</param>
private TrackEntry NewTrackEntry (int trackIndex, Animation animation, bool loop, TrackEntry last) {
TrackEntry entry = trackEntryPool.Obtain(); // Pooling
entry.trackIndex = trackIndex;
entry.animation = animation;
entry.loop = loop;
entry.holdPrevious = false;
entry.eventThreshold = 0;
entry.attachmentThreshold = 0;
entry.drawOrderThreshold = 0;
entry.animationStart = 0;
entry.animationEnd = animation.Duration;
entry.animationLast = -1;
entry.nextAnimationLast = -1;
entry.delay = 0;
entry.trackTime = 0;
entry.trackLast = -1;
entry.nextTrackLast = -1; // nextTrackLast == -1 signifies a TrackEntry that wasn't applied yet.
entry.trackEnd = float.MaxValue; // loop ? float.MaxValue : animation.Duration;
entry.timeScale = 1;
entry.alpha = 1;
entry.interruptAlpha = 1;
entry.mixTime = 0;
entry.mixDuration = (last == null) ? 0 : data.GetMix(last.animation, animation);
return entry;
}
/// <summary>Dispose all track entries queued after the given TrackEntry.</summary>
private void DisposeNext (TrackEntry entry) {
TrackEntry next = entry.next;
while (next != null) {
queue.Dispose(next);
next = next.next;
}
entry.next = null;
}
private void AnimationsChanged () {
animationsChanged = false;
// Process in the order that animations are applied.
propertyIDs.Clear();
var tracksItems = tracks.Items;
for (int i = 0, n = tracks.Count; i < n; i++) {
TrackEntry entry = tracksItems[i];
if (entry == null) continue;
while (entry.mixingFrom != null) // Move to last entry, then iterate in reverse.
entry = entry.mixingFrom;
do {
if (entry.mixingTo == null || entry.mixBlend != MixBlend.Add) ComputeHold(entry);
entry = entry.mixingTo;
} while (entry != null);
}
}
private void ComputeHold (TrackEntry entry) {
TrackEntry to = entry.mixingTo;
var timelines = entry.animation.timelines.Items;
int timelinesCount = entry.animation.timelines.Count;
var timelineMode = entry.timelineMode.Resize(timelinesCount).Items; //timelineMode.setSize(timelinesCount);
entry.timelineHoldMix.Clear();
var timelineHoldMix = entry.timelineHoldMix.Resize(timelinesCount).Items; //timelineHoldMix.setSize(timelinesCount);
var propertyIDs = this.propertyIDs;
if (to != null && to.holdPrevious) {
for (int i = 0; i < timelinesCount; i++)
timelineMode[i] = propertyIDs.Add(timelines[i].PropertyId) ? AnimationState.HoldFirst : AnimationState.HoldSubsequent;
return;
}
// outer:
for (int i = 0; i < timelinesCount; i++) {
Timeline timeline = timelines[i];
int id = timeline.PropertyId;
if (!propertyIDs.Add(id))
timelineMode[i] = AnimationState.Subsequent;
else if (to == null || timeline is AttachmentTimeline || timeline is DrawOrderTimeline
|| timeline is EventTimeline || !to.animation.HasTimeline(id)) {
timelineMode[i] = AnimationState.First;
} else {
for (TrackEntry next = to.mixingTo; next != null; next = next.mixingTo) {
if (next.animation.HasTimeline(id)) continue;
if (next.mixDuration > 0) {
timelineMode[i] = AnimationState.HoldMix;
timelineHoldMix[i] = next;
goto continue_outer; // continue outer;
}
break;
}
timelineMode[i] = AnimationState.HoldFirst;
}
continue_outer: {}
}
}
/// <returns>The track entry for the animation currently playing on the track, or null if no animation is currently playing.</returns>
public TrackEntry GetCurrent (int trackIndex) {
if (trackIndex >= tracks.Count) return null;
return tracks.Items[trackIndex];
}
/// <summary> Discards all listener notifications that have not yet been delivered. This can be useful to call from an
/// AnimationState event subscriber when it is known that further notifications that may have been already queued for delivery
/// are not wanted because new animations are being set.
public void ClearListenerNotifications () {
queue.Clear();
}
/// <summary>
/// <para>Multiplier for the delta time when the animation state is updated, causing time for all animations and mixes to play slower
/// or faster. Defaults to 1.</para>
/// <para>
/// See TrackEntry <see cref="TrackEntry.TimeScale"/> for affecting a single animation.</para>
/// </summary>
public float TimeScale { get { return timeScale; } set { timeScale = value; } }
/// <summary>The AnimationStateData to look up mix durations.</summary>
public AnimationStateData Data {
get {
return data;
}
set {
if (data == null) throw new ArgumentNullException("data", "data cannot be null.");
this.data = value;
}
}
/// <summary>A list of tracks that have animations, which may contain nulls.</summary>
public ExposedList<TrackEntry> Tracks { get { return tracks; } }
override public string ToString () {
var buffer = new System.Text.StringBuilder();
for (int i = 0, n = tracks.Count; i < n; i++) {
TrackEntry entry = tracks.Items[i];
if (entry == null) continue;
if (buffer.Length > 0) buffer.Append(", ");
buffer.Append(entry.ToString());
}
if (buffer.Length == 0) return "<none>";
return buffer.ToString();
}
}
/// <summary>
/// <para>
/// Stores settings and other state for the playback of an animation on an <see cref="AnimationState"/> track.</para>
/// <para>
/// References to a track entry must not be kept after the <see cref="AnimationStateListener.Dispose(TrackEntry)"/> event occurs.</para>
/// </summary>
public class TrackEntry : Pool<TrackEntry>.IPoolable {
internal Animation animation;
internal TrackEntry next, mixingFrom, mixingTo;
// difference to libgdx reference: delegates are used for event callbacks instead of 'AnimationStateListener listener'.
public event AnimationState.TrackEntryDelegate Start, Interrupt, End, Dispose, Complete;
public event AnimationState.TrackEntryEventDelegate Event;
internal void OnStart () { if (Start != null) Start(this); }
internal void OnInterrupt () { if (Interrupt != null) Interrupt(this); }
internal void OnEnd () { if (End != null) End(this); }
internal void OnDispose () { if (Dispose != null) Dispose(this); }
internal void OnComplete () { if (Complete != null) Complete(this); }
internal void OnEvent (Event e) { if (Event != null) Event(this, e); }
internal int trackIndex;
internal bool loop, holdPrevious;
internal float eventThreshold, attachmentThreshold, drawOrderThreshold;
internal float animationStart, animationEnd, animationLast, nextAnimationLast;
internal float delay, trackTime, trackLast, nextTrackLast, trackEnd, timeScale = 1f;
internal float alpha, mixTime, mixDuration, interruptAlpha, totalAlpha;
internal MixBlend mixBlend = MixBlend.Replace;
internal readonly ExposedList<int> timelineMode = new ExposedList<int>();
internal readonly ExposedList<TrackEntry> timelineHoldMix = new ExposedList<TrackEntry>();
internal readonly ExposedList<float> timelinesRotation = new ExposedList<float>();
// IPoolable.Reset()
public void Reset () {
next = null;
mixingFrom = null;
mixingTo = null;
animation = null;
// replaces 'listener = null;' since delegates are used for event callbacks
Start = null;
Interrupt = null;
End = null;
Dispose = null;
Complete = null;
Event = null;
timelineMode.Clear();
timelineHoldMix.Clear();
timelinesRotation.Clear();
}
/// <summary>The index of the track where this entry is either current or queued.</summary>
/// <seealso cref="AnimationState.GetCurrent(int)"/>
public int TrackIndex { get { return trackIndex; } }
/// <summary>The animation to apply for this track entry.</summary>
public Animation Animation { get { return animation; } }
/// <summary>
/// If true, the animation will repeat. If false it will not, instead its last frame is applied if played beyond its
/// duration.</summary>
public bool Loop { get { return loop; } set { loop = value; } }
///<summary>
/// <para>
/// Seconds to postpone playing the animation. When this track entry is the current track entry, <code>Delay</code>
/// postpones incrementing the <see cref="TrackEntry.TrackTime"/>. When this track entry is queued, <code>Delay</code> is the time from
/// the start of the previous animation to when this track entry will become the current track entry (ie when the previous
/// track entry <see cref="TrackEntry.TrackTime"/> >= this track entry's <code>Delay</code>).</para>
/// <para>
/// <see cref="TrackEntry.TimeScale"/> affects the delay.</para>
/// </summary>
public float Delay { get { return delay; } set { delay = value; } }
/// <summary>
/// Current time in seconds this track entry has been the current track entry. The track time determines
/// <see cref="TrackEntry.AnimationTime"/>. The track time can be set to start the animation at a time other than 0, without affecting
/// looping.</summary>
public float TrackTime { get { return trackTime; } set { trackTime = value; } }
/// <summary>
/// <para>
/// The track time in seconds when this animation will be removed from the track. Defaults to the highest possible float
/// value, meaning the animation will be applied until a new animation is set or the track is cleared. If the track end time
/// is reached, no other animations are queued for playback, and mixing from any previous animations is complete, then the
/// properties keyed by the animation are set to the setup pose and the track is cleared.</para>
/// <para>
/// It may be desired to use <see cref="AnimationState.AddEmptyAnimation(int, float, float)"/> rather than have the animation
/// abruptly cease being applied.</para>
/// </summary>
public float TrackEnd { get { return trackEnd; } set { trackEnd = value; } }
/// <summary>
/// <para>
/// Seconds when this animation starts, both initially and after looping. Defaults to 0.</para>
/// <para>
/// When changing the <code>AnimationStart</code> time, it often makes sense to set <see cref="TrackEntry.AnimationLast"> to the same
/// value to prevent timeline keys before the start time from triggering.</para>
/// </summary>
public float AnimationStart { get { return animationStart; } set { animationStart = value; } }
/// <summary>
/// Seconds for the last frame of this animation. Non-looping animations won't play past this time. Looping animations will
/// loop back to <see cref="TrackEntry.AnimationStart"/> at this time. Defaults to the animation <see cref="Animation.Duration"/>.
///</summary>
public float AnimationEnd { get { return animationEnd; } set { animationEnd = value; } }
/// <summary>
/// The time in seconds this animation was last applied. Some timelines use this for one-time triggers. Eg, when this
/// animation is applied, event timelines will fire all events between the <code>AnimationLast</code> time (exclusive) and
/// <code>AnimationTime</code> (inclusive). Defaults to -1 to ensure triggers on frame 0 happen the first time this animation
/// is applied.</summary>
public float AnimationLast {
get { return animationLast; }
set {
animationLast = value;
nextAnimationLast = value;
}
}
/// <summary>
/// Uses <see cref="TrackEntry.TrackTime"/> to compute the <code>AnimationTime</code>, which is between <see cref="TrackEntry.AnimationStart"/>
/// and <see cref="TrackEntry.AnimationEnd"/>. When the <code>TrackTime</code> is 0, the <code>AnimationTime</code> is equal to the
/// <code>AnimationStart</code> time.
/// </summary>
public float AnimationTime {
get {
if (loop) {
float duration = animationEnd - animationStart;
if (duration == 0) return animationStart;
return (trackTime % duration) + animationStart;
}
return Math.Min(trackTime + animationStart, animationEnd);
}
}
/// <summary>
/// <para>
/// Multiplier for the delta time when this track entry is updated, causing time for this animation to pass slower or
/// faster. Defaults to 1.</para>
/// <para>
/// <see cref="TrackEntry.MixTime"/> is not affected by track entry time scale, so <see cref="TrackEntry.MixDuration"/> may need to be adjusted to
/// match the animation speed.</para>
/// <para>
/// When using <see cref="AnimationState.AddAnimation(int, Animation, boolean, float)"> with a <code>Delay</code> <= 0, note the
/// {<see cref="TrackEntry.Delay"/> is set using the mix duration from the <see cref="AnimationStateData"/>, assuming time scale to be 1. If
/// the time scale is not 1, the delay may need to be adjusted.</para>
/// <para>
/// See AnimationState <see cref="AnimationState.TimeScale"/> for affecting all animations.</para>
/// </summary>
public float TimeScale { get { return timeScale; } set { timeScale = value; } }
/// <summary>
/// <para>
/// Values < 1 mix this animation with the skeleton's current pose (usually the pose resulting from lower tracks). Defaults
/// to 1, which overwrites the skeleton's current pose with this animation.</para>
/// <para>
/// Typically track 0 is used to completely pose the skeleton, then alpha is used on higher tracks. It doesn't make sense to
/// use alpha on track 0 if the skeleton pose is from the last frame render.</para>
/// </summary>
public float Alpha { get { return alpha; } set { alpha = value; } }
/// <summary>
/// When the mix percentage (<see cref="TrackEntry.MixTime"/> / <see cref="TrackEntry.MixDuration"/>) is less than the
/// <code>EventThreshold</code>, event timelines are applied while this animation is being mixed out. Defaults to 0, so event
/// timelines are not applied while this animation is being mixed out.
/// </summary>
public float EventThreshold { get { return eventThreshold; } set { eventThreshold = value; } }
/// <summary>
/// When the mix percentage (<see cref="TrackEntry.MixTime"/> / <see cref="TrackEntry.MixDuration"/>) is less than the
/// <code>AttachmentThreshold</code>, attachment timelines are applied while this animation is being mixed out. Defaults to
/// 0, so attachment timelines are not applied while this animation is being mixed out.
///</summary>
public float AttachmentThreshold { get { return attachmentThreshold; } set { attachmentThreshold = value; } }
/// <summary>
/// When the mix percentage (<see cref="TrackEntry.MixTime"/> / <see cref="TrackEntry.MixDuration"/>) is less than the
/// <code>DrawOrderThreshold</code>, draw order timelines are applied while this animation is being mixed out. Defaults to 0,
/// so draw order timelines are not applied while this animation is being mixed out.
/// </summary>
public float DrawOrderThreshold { get { return drawOrderThreshold; } set { drawOrderThreshold = value; } }
/// <summary>
/// The animation queued to start after this animation, or null. <code>Next</code> makes up a linked list. </summary>
public TrackEntry Next { get { return next; } }
/// <summary>
/// Returns true if at least one loop has been completed.</summary>
/// <seealso cref="TrackEntry.Complete"/>
public bool IsComplete {
get { return trackTime >= animationEnd - animationStart; }
}
/// <summary>
/// Seconds from 0 to the <see cref="TrackEntry.MixDuration"/> when mixing from the previous animation to this animation. May be
/// slightly more than <code>MixDuration</code> when the mix is complete.</summary>
public float MixTime { get { return mixTime; } set { mixTime = value; } }
/// <summary>
/// <para>
/// Seconds for mixing from the previous animation to this animation. Defaults to the value provided by AnimationStateData
/// <see cref="AnimationStateData.GetMix(Animation, Animation)"/> based on the animation before this animation (if any).</para>
/// <para>
/// The <code>MixDuration</code> can be set manually rather than use the value from
/// <see cref="AnimationStateData.GetMix(Animation, Animation)"/>. In that case, the <code>MixDuration</code> can be set for a new
/// track entry only before <see cref="AnimationState.Update(float)"/> is first called.</para>
/// <para>
/// When using <seealso cref="AnimationState.AddAnimation(int, Animation, bool, float)"/> with a <code>Delay</code> <= 0, note the
/// <see cref="TrackEntry.Delay"/> is set using the mix duration from the <see cref=" AnimationStateData"/>, not a mix duration set
/// afterward.</para>
/// </summary>
public float MixDuration { get { return mixDuration; } set { mixDuration = value; } }
/// <summary>
/// <para>
/// Controls how properties keyed in the animation are mixed with lower tracks. Defaults to <see cref="MixBlend.Replace"/>, which
/// replaces the values from the lower tracks with the animation values. <see cref="MixBlend.Add"/> adds the animation values to
/// the values from the lower tracks.</para>
/// <para>
/// The <code>MixBlend</code> can be set for a new track entry only before <see cref="AnimationState.Apply(Skeleton)"/> is first
/// called.</para>
/// </summary>
public MixBlend MixBlend { get { return mixBlend; } set { mixBlend = value; } }
/// <summary>
/// The track entry for the previous animation when mixing from the previous animation to this animation, or null if no
/// mixing is currently occuring. When mixing from multiple animations, <code>MixingFrom</code> makes up a linked list.</summary>
public TrackEntry MixingFrom { get { return mixingFrom; } }
/// <summary>
/// The track entry for the next animation when mixing from this animation to the next animation, or null if no mixing is
/// currently occuring. When mixing to multiple animations, <code>MixingTo</code> makes up a linked list.</summary>
public TrackEntry MixingTo { get { return mixingTo; } }
/// <summary>
/// <para>
/// If true, when mixing from the previous animation to this animation, the previous animation is applied as normal instead
/// of being mixed out.</para>
/// <para>
/// When mixing between animations that key the same property, if a lower track also keys that property then the value will
/// briefly dip toward the lower track value during the mix. This happens because the first animation mixes from 100% to 0%
/// while the second animation mixes from 0% to 100%. Setting <code>HoldPrevious</code> to true applies the first animation
/// at 100% during the mix so the lower track value is overwritten. Such dipping does not occur on the lowest track which
/// keys the property, only when a higher track also keys the property.</para>
/// <para>
/// Snapping will occur if <code>HoldPrevious</code> is true and this animation does not key all the same properties as the
/// previous animation.</para>
/// </summary>
public bool HoldPrevious { get { return holdPrevious; } set { holdPrevious = value; } }
/// <summary>
/// <para>
/// Resets the rotation directions for mixing this entry's rotate timelines. This can be useful to avoid bones rotating the
/// long way around when using <see cref="alpha"/> and starting animations on other tracks.</para>
/// <para>
/// Mixing with <see cref="MixBlend.Replace"/> involves finding a rotation between two others, which has two possible solutions:
/// the short way or the long way around. The two rotations likely change over time, so which direction is the short or long
/// way also changes. If the short way was always chosen, bones would flip to the other side when that direction became the
/// long way. TrackEntry chooses the short way the first time it is applied and remembers that direction.</para>
/// </summary>
public void ResetRotationDirections () {
timelinesRotation.Clear();
}
override public string ToString () {
return animation == null ? "<none>" : animation.name;
}
}
class EventQueue {
private readonly List<EventQueueEntry> eventQueueEntries = new List<EventQueueEntry>();
internal bool drainDisabled;
private readonly AnimationState state;
private readonly Pool<TrackEntry> trackEntryPool;
internal event Action AnimationsChanged;
internal EventQueue (AnimationState state, Action HandleAnimationsChanged, Pool<TrackEntry> trackEntryPool) {
this.state = state;
this.AnimationsChanged += HandleAnimationsChanged;
this.trackEntryPool = trackEntryPool;
}
struct EventQueueEntry {
public EventType type;
public TrackEntry entry;
public Event e;
public EventQueueEntry (EventType eventType, TrackEntry trackEntry, Event e = null) {
this.type = eventType;
this.entry = trackEntry;
this.e = e;
}
}
enum EventType {
Start, Interrupt, End, Dispose, Complete, Event
}
internal void Start (TrackEntry entry) {
eventQueueEntries.Add(new EventQueueEntry(EventType.Start, entry));
if (AnimationsChanged != null) AnimationsChanged();
}
internal void Interrupt (TrackEntry entry) {
eventQueueEntries.Add(new EventQueueEntry(EventType.Interrupt, entry));
}
internal void End (TrackEntry entry) {
eventQueueEntries.Add(new EventQueueEntry(EventType.End, entry));
if (AnimationsChanged != null) AnimationsChanged();
}
internal void Dispose (TrackEntry entry) {
eventQueueEntries.Add(new EventQueueEntry(EventType.Dispose, entry));
}
internal void Complete (TrackEntry entry) {
eventQueueEntries.Add(new EventQueueEntry(EventType.Complete, entry));
}
internal void Event (TrackEntry entry, Event e) {
eventQueueEntries.Add(new EventQueueEntry(EventType.Event, entry, e));
}
/// <summary>Raises all events in the queue and drains the queue.</summary>
internal void Drain () {
if (drainDisabled) return;
drainDisabled = true;
var entries = this.eventQueueEntries;
AnimationState state = this.state;
// Don't cache entries.Count so callbacks can queue their own events (eg, call SetAnimation in AnimationState_Complete).
for (int i = 0; i < entries.Count; i++) {
var queueEntry = entries[i];
TrackEntry trackEntry = queueEntry.entry;
switch (queueEntry.type) {
case EventType.Start:
trackEntry.OnStart();
state.OnStart(trackEntry);
break;
case EventType.Interrupt:
trackEntry.OnInterrupt();
state.OnInterrupt(trackEntry);
break;
case EventType.End:
trackEntry.OnEnd();
state.OnEnd(trackEntry);
goto case EventType.Dispose; // Fall through. (C#)
case EventType.Dispose:
trackEntry.OnDispose();
state.OnDispose(trackEntry);
trackEntryPool.Free(trackEntry); // Pooling
break;
case EventType.Complete:
trackEntry.OnComplete();
state.OnComplete(trackEntry);
break;
case EventType.Event:
trackEntry.OnEvent(queueEntry.e);
state.OnEvent(trackEntry, queueEntry.e);
break;
}
}
eventQueueEntries.Clear();
drainDisabled = false;
}
internal void Clear () {
eventQueueEntries.Clear();
}
}
public class Pool<T> where T : class, new() {
public readonly int max;
readonly Stack<T> freeObjects;
public int Count { get { return freeObjects.Count; } }
public int Peak { get; private set; }
public Pool (int initialCapacity = 16, int max = int.MaxValue) {
freeObjects = new Stack<T>(initialCapacity);
this.max = max;
}
public T Obtain () {
return freeObjects.Count == 0 ? new T() : freeObjects.Pop();
}
public void Free (T obj) {
if (obj == null) throw new ArgumentNullException("obj", "obj cannot be null");
if (freeObjects.Count < max) {
freeObjects.Push(obj);
Peak = Math.Max(Peak, freeObjects.Count);
}
Reset(obj);
}
// protected void FreeAll (List<T> objects) {
// if (objects == null) throw new ArgumentNullException("objects", "objects cannot be null.");
// var freeObjects = this.freeObjects;
// int max = this.max;
// for (int i = 0; i < objects.Count; i++) {
// T obj = objects[i];
// if (obj == null) continue;
// if (freeObjects.Count < max) freeObjects.Push(obj);
// Reset(obj);
// }
// Peak = Math.Max(Peak, freeObjects.Count);
// }
public void Clear () {
freeObjects.Clear();
}
protected void Reset (T obj) {
var poolable = obj as IPoolable;
if (poolable != null) poolable.Reset();
}
public interface IPoolable {
void Reset ();
}
}
}
| 412 | 0.936821 | 1 | 0.936821 | game-dev | MEDIA | 0.564122 | game-dev | 0.97053 | 1 | 0.97053 |
comfysage/cuddlefish.nvim | 8,943 | lua/cuddlefish/hl/integrations/mini.lua | local M = {}
---@param theme cuddlefish.types.theme
---@param config cuddlefish.types.config
---@return cuddlefish.types.hlgroups
M.get = function(theme, config)
local cfg = config.integrations.mini
if not cfg then
return {}
end
local hlgroups = {}
if cfg.animate then
table.insert(hlgroups, {
MiniAnimateCursor = { style = { 'reverse', 'nocombine' } },
MiniAnimateNormalFloat = { link = 'NormalFloat' },
})
end
if cfg.clue then
table.insert(hlgroups, {
MiniClueBorder = { link = 'FloatBorder' },
MiniClueDescGroup = { link = 'DiagnosticFloatingWarn' },
MiniClueDescSingle = { link = 'NormalFloat' },
MiniClueNextKey = { link = 'DiagnosticFloatingHint' },
MiniClueNextKeyWithPostkeys = { link = 'DiagnosticFloatingError' },
MiniClueSeparator = { link = 'DiagnosticFloatingInfo' },
MiniClueTitle = { link = 'FloatTitle' },
})
end
if cfg.completion then
table.insert(hlgroups, {
MiniCompletionActiveParameter = { link = 'LspSignatureActiveParameter' },
})
end
if cfg.cursorword then
table.insert(hlgroups, {
MiniCursorword = { link = 'LspReferenceText' },
MiniCursorwordCurrent = { link = 'MiniCursorword' },
})
end
if cfg.deps then
table.insert(hlgroups, {
MiniDepsChangeAdded = { link = 'diffAdded' },
MiniDepsChangeRemoved = { link = 'diffRemoved' },
MiniDepsHint = { link = 'DiagnosticHint' },
MiniDepsInfo = { link = 'DiagnosticInfo' },
MiniDepsMsgBreaking = { link = 'DiagnosticWarn' },
MiniDepsPlaceholder = { link = 'Comment' },
MiniDepsTitle = { link = 'Title' },
MiniDepsTitleError = { bg = theme.diagnostic.error, theme.crust },
MiniDepsTitleSame = { link = 'DiffText' },
MiniDepsTitleUpdate = { bg = theme.diagnostic.ok, theme.crust },
})
end
if cfg.diff then
table.insert(hlgroups, {
MiniDiffSignAdd = { theme.diff.add },
MiniDiffSignChange = { theme.diff.change },
MiniDiffSignDelete = { theme.diff.delete },
MiniDiffOverAdd = { link = 'DiffAdd' },
MiniDiffOverChange = { link = 'DiffText' },
MiniDiffOverContext = { link = 'DiffChange' },
MiniDiffOverDelete = { link = 'DiffDelete' },
})
end
if cfg.files then
table.insert(hlgroups, {
MiniFilesNormal = { link = 'NormalFloat' },
MiniFilesCursorLine = { link = 'CursorLine' },
MiniFilesDirectory = { link = 'Directory' },
MiniFilesFile = { theme.syntax.identifier },
MiniFilesBorder = { link = 'FloatBorder' },
MiniFilesBorderModified = { theme.diagnostic.warn },
MiniFilesTitle = { link = 'MiniFilesBorder' },
MiniFilesTitleFocused = { link = 'FloatTitle' },
})
end
if cfg.hipatterns then
table.insert(hlgroups, {
MiniHipatternsFixme = {
bg = theme.diagnostic.warn,
theme.crust,
style = { 'bold' },
},
MiniHipatternsHack = {
bg = theme.diagnostic.warn,
theme.crust,
style = { 'bold' },
},
MiniHipatternsNote = { bg = theme.blue, theme.crust, style = { 'bold' } },
MiniHipatternsTodo = { bg = theme.aqua, theme.crust, style = { 'bold' } },
})
end
if cfg.icons then
table.insert(hlgroups, {
MiniIconsAzure = { theme.skye },
MiniIconsBlue = { theme.blue },
MiniIconsCyan = { theme.aqua },
MiniIconsGreen = { theme.green },
MiniIconsGrey = { theme.text },
MiniIconsOrange = { theme.orange },
MiniIconsPurple = { theme.pink },
MiniIconsRed = { theme.red },
MiniIconsYellow = { theme.yellow },
})
end
if cfg.indentscope then
table.insert(hlgroups, {
MiniIndentscopeSymbol = { theme.accent },
MiniIndentscopePrefix = { style = { 'nocombine' } }, -- make it invisible
})
end
if cfg.jump then
table.insert(hlgroups, {
MiniJump = { link = 'IncSearch' },
})
end
if cfg.jump2d then
table.insert(hlgroups, {
MiniJump2dDim = { theme.overlay0 },
MiniJump2dSpot = {
theme.blue,
style = { 'bold', 'underline' },
},
MiniJump2dSpotAhead = { theme.aqua },
MiniJump2dSpotUnique = { theme.skye, style = { 'bold' } },
})
end
if cfg.map then
table.insert(hlgroups, {
MiniMapNormal = { link = 'NormalFloat' },
MiniMapSymbolCount = { link = 'Special' },
MiniMapSymbolLine = { link = 'Title' },
MiniMapSymbolView = { link = 'Delimiter' },
})
end
if cfg.notify then
table.insert(hlgroups, {
MiniNotifyBorder = { link = 'FloatBorder' },
MiniNotifyNormal = { link = 'NormalFloat' },
MiniNotifyTitle = { link = 'FloatTitle' },
})
end
if cfg.operators then
table.insert(hlgroups, {
MiniOperatorsExchangeFrom = { link = 'IncSearch' },
})
end
if cfg.pick then
table.insert(hlgroups, {
MiniPickBorder = { link = 'FloatBorder' }, -- window border.
MiniPickBorderBusy = { theme.diagnostic.warn }, -- window border while picker is busy processing.
MiniPickBorderText = { theme.subtext0 }, -- non-prompt on border.
MiniPickCursor = { theme.accent }, -- cursor during active picker (hidden by default).
MiniPickIconDirectory = { theme.overlay2 }, -- default icon for directory.
MiniPickIconFile = { theme.subtext1 }, -- default icon for file.
MiniPickHeader = { theme.subtext0 }, -- headers in info buffer and previews.
MiniPickMatchCurrent = { theme.none, theme.surface0 }, -- current matched item.
MiniPickMatchMarked = { theme.yellow, theme.surface0 }, -- marked matched items.
MiniPickMatchRanges = { link = 'IncSearch' }, -- ranges matching query elements.
MiniPickNormal = { link = 'NormalFloat' }, -- basic foreground/background highlighting.
MiniPickPreviewLine = { theme.none, theme.surface0 }, -- target line in preview.
MiniPickPreviewRegion = { theme.none, theme.surface0 }, -- target region in preview.
MiniPickPrompt = { theme.pink }, -- prompt.
})
end
if cfg.starter then
table.insert(hlgroups, {
MiniStarterCurrent = {},
MiniStarterFooter = { theme.subtext0, style = { 'italic' } },
MiniStarterHeader = { theme.syntax.constant },
MiniStarterInactive = { link = '@comment' },
MiniStarterItem = { theme.text },
MiniStarterItemBullet = { theme.blue },
MiniStarterItemPrefix = { theme.pink },
MiniStarterSection = { bg = theme.accent, theme.crust },
MiniStarterQuery = { theme.accent },
})
end
if cfg.statusline then
table.insert(hlgroups, {
MiniStatuslineDevinfo = { theme.subtext0, theme.surface1 },
MiniStatuslineFileinfo = { theme.subtext0, theme.surface1 },
MiniStatuslineFilename = { theme.text, theme.mantle },
MiniStatuslineInactive = { theme.subtext0, theme.mantle },
MiniStatuslineModeNormal = {
bg = theme.accent,
theme.crust,
style = { 'bold' },
},
MiniStatuslineModeCommand = {
bg = theme.accent,
theme.crust,
style = { 'bold' },
},
MiniStatuslineModeInsert = {
bg = theme.text,
theme.crust,
style = { 'bold' },
},
MiniStatuslineModeVisual = {
bg = theme.pink,
theme.crust,
style = { 'bold' },
},
MiniStatuslineModeReplace = {
bg = theme.text,
theme.crust,
style = { 'bold' },
},
MiniStatuslineModeOther = {
bg = theme.aqua,
theme.base,
style = { 'bold' },
},
})
end
if cfg.surround then
table.insert(hlgroups, {
MiniSurround = { link = 'IncSearch' },
})
end
if cfg.tabline then
table.insert(hlgroups, {
MiniTablineCurrent = {
theme.text,
theme.base,
style = config.style.tabline,
},
MiniTablineFill = {
link = 'TablineFill',
},
MiniTablineHidden = {
theme.text,
config.editor.transparent_background and theme.none or theme.mantle,
},
MiniTablineModifiedCurrent = {
theme.diagnostic.warn,
style = config.style.tabline,
},
MiniTablineModifiedHidden = { theme.diagnostic.warn },
MiniTablineModifiedVisible = { theme.diagnostic.warn },
MiniTablineTabpagesection = { theme.surface1, theme.base },
MiniTablineVisible = {},
})
end
if cfg.test then
table.insert(hlgroups, {
MiniTestEmphasis = { link = '@text.emphasis' },
MiniTestFail = {
bg = theme.diagnostic.error,
theme.crust,
style = { 'bold' },
},
MiniTestPass = {
bg = theme.diagnostic.ok,
theme.crust,
style = { 'bold' },
},
})
end
if cfg.trailspace then
table.insert(hlgroups, {
MiniTrailspace = { theme.diagnostic.error },
})
end
return hlgroups
end
return M
| 412 | 0.832821 | 1 | 0.832821 | game-dev | MEDIA | 0.512412 | game-dev,desktop-app | 0.906571 | 1 | 0.906571 |
ixray-team/ixray-1.6-stcop | 12,933 | src/xrGame/step_manager.cpp | #include "StdAfx.h"
#include "step_manager.h"
#include "entity_alive.h"
#include "../Include/xrRender/Kinematics.h"
#include "Level.h"
#include "GamePersistent.h"
#include "material_manager.h"
#include "IKLimbsController.h"
#include "../xrEngine/Rain.h"
#include "CustomOutfit.h"
#include "InventoryOwner.h"
#ifdef DEBUG
BOOL debug_step_info = FALSE;
BOOL debug_step_info_load = FALSE;
#endif
extern float psHUDStepSoundVolume;
static xr_hash_set<xr_string_view> exoVisuals = {};
static FS_FileSet stepExoSounds = {};
static FS_FileSet stepRainSounds = {};
static bool isExoSection = false;
CStepManager::CStepManager()
{
if (stepRainSounds.empty())
{
FS.file_list(stepRainSounds, "$game_sounds$", FS_ListFiles, R"(material\human\step\rain_*)");
}
if (m_rain_steps.empty())
{
for (auto& stepRainSound : stepRainSounds)
{
m_rain_steps.emplace_back().create(stepRainSound.name.c_str(), st_Effect, sg_SourceType);
}
}
isExoSection = pSettings->section_exist("exo_visuals");
if (!isExoSection)
{
return;
}
if (stepExoSounds.empty())
{
FS.file_list(stepExoSounds, "$game_sounds$", FS_ListFiles, R"(exo\exo_step*)");
}
if (m_exo_steps.empty())
{
for (auto& stepExoSound : stepExoSounds)
{
m_exo_steps.emplace_back().create(stepExoSound.name.c_str(), st_Effect, sg_SourceType);
}
}
if (exoVisuals.empty())
{
LPCSTR exoVisualName = {}, vall = {};
for (int k = 0; pSettings->r_line("exo_visuals", k, &exoVisualName, &vall); ++k)
{
exoVisuals.insert(exoVisualName);
}
}
}
CStepManager::~CStepManager()
{
for (auto& rainStep : m_rain_steps)
{
rainStep.destroy();
}
m_rain_steps.clear();
for (auto& exoStep : m_exo_steps)
{
exoStep.destroy();
}
m_exo_steps.clear();
}
DLL_Pure *CStepManager::_construct ()
{
m_object = smart_cast<CEntityAlive*>(this);
VERIFY (m_object);
return (m_object);
}
void CStepManager::reload(LPCSTR section)
{
m_legs_count = pSettings->r_u8 (section, "LegsCount");
LPCSTR anim_section = pSettings->r_string (section, "step_params");
if (!pSettings->section_exist(anim_section))
{
#ifdef DEBUG
Msg( "! no step_params section for :%s section :s", m_object->cName().c_str(), section );
#endif
return;
}
VERIFY((m_legs_count>=MIN_LEGS_COUNT) && (m_legs_count<=MAX_LEGS_COUNT));
SStepParam param;
param.step[0].time = 0.1f; // avoid warning
LPCSTR anim_name, val;
string16 cur_elem;
IKinematicsAnimated *skeleton_animated = m_object->Visual()->dcast_PKinematicsAnimated();
VERIFY3(skeleton_animated, "object is not animated", m_object->cNameVisual().c_str());
#ifdef DEBUG
if( debug_step_info_load )
Msg( "loading step_params for object :%s, visual: %s, section: %s, step_params section: %s ", m_object->cName().c_str(), m_object->cNameVisual().c_str(), section, anim_section );
#endif
for (u32 i=0; pSettings->r_line(anim_section,i,&anim_name,&val); ++i) {
_GetItem (val,0,cur_elem);
param.cycles = u8(atoi(cur_elem));
R_ASSERT(param.cycles >= 1);
for (u32 j=0;j<m_legs_count;j++) {
_GetItem (val,1+j*2, cur_elem); param.step[j].time = float(atof(cur_elem));
_GetItem (val,1+j*2+1, cur_elem); param.step[j].power = float(atof(cur_elem));
VERIFY (_valid(param.step[j].power));
}
MotionID motion_id = skeleton_animated->ID_Cycle_Safe(anim_name);
if (!motion_id)
{
#ifdef DEBUG
IKinematicsAnimated *KA = m_object->Visual()->dcast_PKinematicsAnimated();
VERIFY( KA );
Msg( "! (CStepManager::reload) no anim :%s object:%s, visual: %s, step_params section: %s ", anim_name, m_object->cName().c_str(), m_object->cNameVisual().c_str(), anim_section );
#endif
continue;
}
#ifdef DEBUG
if( debug_step_info_load )
{
IKinematicsAnimated *KA = m_object->Visual()->dcast_PKinematicsAnimated();
VERIFY( KA );
std::pair<LPCSTR,LPCSTR> anim_name_ = KA->LL_MotionDefName_dbg( motion_id );
Msg( "step_params loaded for object :%s, visual: %s, motion: %s, anim set: %s ", m_object->cName().c_str(), m_object->cNameVisual().c_str(), anim_name_.first, anim_name_.second );
}
#endif
m_steps_map.insert(std::make_pair(motion_id, param));
}
#ifdef DEBUG
if( m_steps_map.empty() )
Msg( "! no steps info loaded for :%s, section :s, step_params section: %s ", m_object->cName().c_str(), section, anim_section );
#endif
// reload foot bones
for (u32 i = 0; i < MAX_LEGS_COUNT; i++) m_foot_bones[i] = BI_NONE;
reload_foot_bones ();
m_time_anim_started = 0;
m_blend = nullptr;
}
void CStepManager::on_animation_start(MotionID motion_id, CBlend *blend)
{
m_blend = blend;
if (!m_blend) return;
if (!g_dedicated_server && m_object->character_ik_controller())
{
m_object->character_ik_controller()->PlayLegs(blend);
}
m_time_anim_started = Device.dwTimeGlobal;
// искать текущую анимацию в STEPS_MAP
STEPS_MAP_IT it = m_steps_map.find(motion_id);
if (it == m_steps_map.end()) {
#ifdef DEBUG
if( debug_step_info )
{
IKinematicsAnimated *KA = m_object->Visual()->dcast_PKinematicsAnimated();
VERIFY( KA );
std::pair<LPCSTR,LPCSTR> anim_name = KA->LL_MotionDefName_dbg( motion_id );
Msg( "! no step_params found for object :%s, visual: %s, motion: %s, anim set: %s ", m_object->cName().c_str(), m_object->cNameVisual().c_str(), anim_name.first, anim_name.second );
}
#endif
m_step_info.disable = true;
return;
}
m_step_info.disable = false;
m_step_info.params = it->second;
m_step_info.cur_cycle = 1; // all cycles are 1-based
for (u32 i=0; i<m_legs_count; i++) {
m_step_info.activity[i].handled = false;
m_step_info.activity[i].cycle = m_step_info.cur_cycle;
}
VERIFY (m_blend);
}
void CStepManager::update(bool b_hud_view)
{
PROF_EVENT("Step Manager")
if (m_step_info.disable) return;
if (!m_blend) return;
float dist_sqr = m_object->Position().distance_to_sqr(Device.vCameraPosition);
bool b_play = dist_sqr < 400.0f; //20m
// получить параметры шага
SStepParam &step = m_step_info.params;
u32 cur_time = Device.dwTimeGlobal;
// время одного цикла анимации
float cycle_anim_time = get_blend_time() / step.cycles;
// пройти по всем ногам и проверить время
SGameMtlPair* mtl_pair = 0;
bool material_picked = false;
for (u32 i=0; i<m_legs_count; i++)
{
// если событие уже обработано для этой ноги, то skip
if (m_step_info.activity[i].handled && (m_step_info.activity[i].cycle == m_step_info.cur_cycle))
continue;
// вычислить смещённое время шага в соответствии с параметрами анимации ходьбы
u32 offset_time = m_time_anim_started + u32(1000 * (cycle_anim_time * (m_step_info.cur_cycle-1) + cycle_anim_time * step.step[i].time));
if (offset_time <= cur_time)
{
if( !material_picked )
{
mtl_pair = m_object->material().get_current_pair();
material_picked = true;
}
if ( !mtl_pair )
break;
// Играть звук
if(b_play && is_on_ground() )
{
m_step_sound.play_next(mtl_pair, m_object, m_step_info.params.step[i].power, b_hud_view);
PlayRainStep(b_hud_view);
PlayExoStep(b_hud_view);
}
CGameObject* object = m_object->cast_game_object();
if (object)
{
object->FootStepCallback(m_step_info.params.step[i].power, b_play, is_on_ground(), b_hud_view);
}
// Играть партиклы
if(b_play && !mtl_pair->CollideParticles.empty())
{
LPCSTR ps_name = *mtl_pair->CollideParticles[::Random.randI(0, (u32)mtl_pair->CollideParticles.size())];
//отыграть партиклы столкновения материалов
xr_shared_ptr<CParticlesObject> ps = Particles::Details::Create(ps_name,TRUE);
// вычислить позицию и направленность партикла
Fmatrix pos;
// установить направление
pos.k.set(Fvector().set(0.0f,1.0f,0.0f));
Fvector::generate_orthonormal_basis(pos.k, pos.j, pos.i);
// установить позицию
pos.c.set(get_foot_position(ELegType(i)));
ps->UpdateParent(pos,Fvector().set(0.f,0.f,0.f));
GamePersistent().ps_needtoplay.push_back(ps);
}
// Play Camera FXs
event_on_step();
// обновить поле handle
m_step_info.activity[i].handled = true;
m_step_info.activity[i].cycle = m_step_info.cur_cycle;
}
}
// определить текущий цикл
if (m_step_info.cur_cycle < step.cycles)
m_step_info.cur_cycle = 1 + u8(float(cur_time - m_time_anim_started) / (1000.f * cycle_anim_time));
// если анимация циклическая...
u32 time_anim_end = m_time_anim_started + u32(get_blend_time() * 1000); // время завершения работы анимации
if (!m_blend->stop_at_end && (time_anim_end < cur_time)) {
m_time_anim_started = time_anim_end;
m_step_info.cur_cycle = 1;
for (u32 i=0; i<m_legs_count; i++) {
m_step_info.activity[i].handled = false;
m_step_info.activity[i].cycle = m_step_info.cur_cycle;
}
}
}
//////////////////////////////////////////////////////////////////////////
// Function for foot processing
//////////////////////////////////////////////////////////////////////////
Fvector CStepManager::get_foot_position(ELegType leg_type)
{
R_ASSERT2(m_foot_bones[leg_type] != BI_NONE, "foot bone had not been set");
IKinematics* pK = PKinematics(m_object->Visual());
const Fmatrix& bone_transform = pK->LL_GetBoneInstance(m_foot_bones[leg_type]).mTransform;
Fmatrix global_transform;
global_transform.mul_43(m_object->XFORM(), bone_transform);
return global_transform.c;
}
void CStepManager::load_foot_bones(CInifile::Sect& data)
{
for (CInifile::SectCIt I = data.Data.begin(); I != data.Data.end(); ++I)
{
const CInifile::Item& item = *I;
u16 index = PKinematics(m_object->Visual())->LL_BoneID(*item.second);
R_ASSERT3(index != BI_NONE, "foot bone not found", *item.second);
if (xr_strcmp(*item.first, "front_left") == 0)
{
m_foot_bones[eFrontLeft] = index;
}
else if (xr_strcmp(*item.first, "front_right") == 0)
{
m_foot_bones[eFrontRight] = index;
}
else if (xr_strcmp(*item.first, "back_right") == 0)
{
m_foot_bones[eBackRight] = index;
}
else if (xr_strcmp(*item.first, "back_left") == 0)
{
m_foot_bones[eBackLeft] = index;
}
}
}
void CStepManager::reload_foot_bones()
{
CInifile* ini = PKinematics(m_object->Visual())->LL_UserData();
if (ini && ini->section_exist("foot_bones"))
{
load_foot_bones(ini->r_section("foot_bones"));
}
else if (pSettings->line_exist(*m_object->cNameSect(), "foot_bones"))
load_foot_bones(pSettings->r_section(pSettings->r_string(*m_object->cNameSect(), "foot_bones")));
else if (!Device.IsEditorMode())
R_ASSERT2(false, "section [foot_bones] not found in monster user_data");
else
return;
// проверка на соответсвие
int count = 0;
for (u32 i = 0; i < MAX_LEGS_COUNT; i++)
if (m_foot_bones[i] != BI_NONE) count++;
VERIFY(count == m_legs_count);
}
float CStepManager::get_blend_time()
{
return (m_blend->timeTotal / m_blend->speed);
}
void CStepManager::material_sound::play_next(SGameMtlPair* mtl_pair, CEntityAlive* object, float volume, bool b_hud_mode)
{
if (mtl_pair->StepSounds.empty() )
return;
Fvector sound_pos = object->Position();
sound_pos.y += 0.5;
if( last_mtl_pair!= mtl_pair || m_last_step_sound_played == u8(-1) )
{
m_last_step_sound_played = u8( Random.randI(mtl_pair->StepSounds.size()) );
last_mtl_pair = mtl_pair;
} else
{
u8 new_played = u8 ( ( m_last_step_sound_played + 1 + Random.randI(mtl_pair->StepSounds.size()-1) ) % mtl_pair->StepSounds.size() );
m_last_step_sound_played = new_played;
}
float vol = (b_hud_mode)? volume*psHUDStepSoundVolume : volume;
if(b_hud_mode)
sound_pos.set(0,0,0);
mtl_pair->StepSounds[m_last_step_sound_played].play_no_feedback(object,
b_hud_mode? sm_2D:0,
0,
&sound_pos,
&vol );
}
inline void CStepManager::PlayRainStep(const bool bHudView)
{
if (m_rain_steps.empty())
{
return;
}
float rainVolume = g_pGamePersistent->Environment().eff_Rain->GetRainVolume();
if (rainVolume <= 0.1f)
{
return;
}
Fvector pos = m_object->Position();
if (bHudView)
{
pos = zero_vel;
}
const int count = m_rain_steps.size();
m_rain_steps[Random.randI(count)].play_no_feedback(m_object, bHudView ? sm_2D : 0, 0, &pos, &rainVolume);
}
inline void CStepManager::PlayExoStep(const bool bHudView)
{
if (!is_exo || m_exo_steps.empty())
{
return;
}
Fvector pos = m_object->Position();
if (bHudView)
{
pos = zero_vel;
}
float vol = Random.randF(2.2f, 2.8f);
const int count = m_exo_steps.size();
m_exo_steps[Random.randI(count)].play_no_feedback(m_object, bHudView ? sm_2D : 0, 0, &pos, &vol);
}
void CStepManager::CheckExo()
{
if (exoVisuals.empty())
{
return;
}
if (m_object == nullptr)
{
return;
}
const char* vis = m_object->cNameVisual().c_str();
if (vis == nullptr || vis[0] == '\0')
{
return;
}
xr_string_view visual(vis);
constexpr xr_string_view ext = ".ogf";
if (visual.ends_with(ext))
{
visual.remove_suffix(ext.size());
}
is_exo = exoVisuals.contains(visual);
} | 412 | 0.956898 | 1 | 0.956898 | game-dev | MEDIA | 0.529964 | game-dev,desktop-app | 0.885339 | 1 | 0.885339 |
ProjectIgnis/CardScripts | 3,012 | official/c73345237.lua | --サムサリック・サイクルのベンガランス
--Benghalancer the Resurgent
--Scripted by Kohana Sonogami
local s,id=GetID()
function s.initial_effect(c)
--link summon
Link.AddProcedure(c,aux.FilterBoolFunctionEx(Card.IsRace,RACE_PLANT),2)
c:EnableReviveLimit()
--tohand
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(id,0))
e1:SetCategory(CATEGORY_TOHAND+CATEGORY_DAMAGE)
e1:SetType(EFFECT_TYPE_QUICK_O)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetRange(LOCATION_MZONE)
e1:SetCountLimit(1,id)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetHintTiming(0,TIMINGS_CHECK_MONSTER|TIMING_MAIN_END)
e1:SetCondition(function(e,tp,eg,ep,ev,re,r,rp)return Duel.IsMainPhase()end)
e1:SetTarget(s.thtg)
e1:SetOperation(s.thop)
c:RegisterEffect(e1)
--special summon
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(id,1))
e2:SetCategory(CATEGORY_SPECIAL_SUMMON)
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetRange(LOCATION_GRAVE)
e2:SetCountLimit(1,id)
e2:SetCost(s.spcost)
e2:SetTarget(s.sptg)
e2:SetOperation(s.spop)
c:RegisterEffect(e2)
end
function s.thfilter(c)
return c:IsType(TYPE_EFFECT) and c:IsFaceup() and c:IsAttackAbove(1) and c:IsAbleToHand()
end
function s.thtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsControler(1-tp) and s.thfilter(chkc) end
if chk==0 then return Duel.IsExistingTarget(s.thfilter,tp,0,LOCATION_MZONE,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_RTOHAND)
local g=Duel.SelectTarget(tp,s.thfilter,tp,0,LOCATION_MZONE,1,1,nil)
local d=g:GetFirst():GetAttack()
Duel.SetTargetPlayer(tp)
Duel.SetOperationInfo(0,CATEGORY_DAMAGE,nil,0,tp,d)
end
function s.thop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
local p=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER)
if tc and tc:IsRelateToEffect(e) and Duel.Damage(p,tc:GetAttack(),REASON_EFFECT) then
Duel.SendtoHand(tc,nil,REASON_EFFECT)
end
end
function s.rmfilter(c)
return c:IsLinkMonster() and c:IsAbleToRemoveAsCost()
end
function s.spcost(e,tp,eg,ep,ev,re,r,rp,chk)
local g=Duel.GetMatchingGroup(s.rmfilter,tp,LOCATION_GRAVE,0,e:GetHandler())
if chk==0 then return g:CheckWithSumEqual(Card.GetLink,4,2,4) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local rg=g:SelectWithSumEqual(tp,Card.GetLink,4,2,4)
Duel.Remove(rg,POS_FACEUP,REASON_COST)
end
function s.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,false,false) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,LOCATION_GRAVE)
end
function s.spop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsRelateToEffect(e) and Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEUP)~=0 then
local e1=Effect.CreateEffect(c)
e1:SetDescription(3300)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_LEAVE_FIELD_REDIRECT)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_CLIENT_HINT)
e1:SetReset(RESET_EVENT|RESETS_REDIRECT)
e1:SetValue(LOCATION_REMOVED)
c:RegisterEffect(e1,true)
end
end | 412 | 0.940475 | 1 | 0.940475 | game-dev | MEDIA | 0.988494 | game-dev | 0.953075 | 1 | 0.953075 |
GeyserMC/Geyser | 7,492 | core/src/main/java/org/geysermc/geyser/registry/type/ItemMappings.java | /*
* Copyright (c) 2019-2022 GeyserMC. http://geysermc.org
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @author GeyserMC
* @link https://github.com/GeyserMC/Geyser
*/
package org.geysermc.geyser.registry.type;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.objects.Object2ObjectMap;
import lombok.Builder;
import lombok.Value;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.cloudburstmc.protocol.bedrock.data.definitions.ItemDefinition;
import org.cloudburstmc.protocol.bedrock.data.inventory.CreativeItemData;
import org.cloudburstmc.protocol.bedrock.data.inventory.CreativeItemGroup;
import org.cloudburstmc.protocol.bedrock.data.inventory.ItemData;
import org.cloudburstmc.protocol.common.DefinitionRegistry;
import org.geysermc.geyser.GeyserImpl;
import org.geysermc.geyser.api.block.custom.CustomBlockData;
import org.geysermc.geyser.inventory.GeyserItemStack;
import org.geysermc.geyser.inventory.item.StoredItemMappings;
import org.geysermc.geyser.item.Items;
import org.geysermc.geyser.item.type.Item;
import org.geysermc.mcprotocollib.protocol.data.game.item.ItemStack;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
@Builder
@Value
public class ItemMappings implements DefinitionRegistry<ItemDefinition> {
Map<String, ItemMapping> cachedJavaMappings = new WeakHashMap<>();
ItemMapping[] items;
/**
* A unique exception as this is an item in Bedrock, but not in Java.
*/
ItemMapping lodestoneCompass;
Int2ObjectMap<ItemMapping> lightBlocks;
List<CreativeItemGroup> creativeItemGroups;
List<CreativeItemData> creativeItems;
Int2ObjectMap<ItemDefinition> itemDefinitions;
StoredItemMappings storedItems;
Set<Item> javaOnlyItems;
List<ItemDefinition> buckets;
List<ItemDefinition> boats;
Int2ObjectMap<String> customIdMappings;
Object2ObjectMap<CustomBlockData, ItemDefinition> customBlockItemDefinitions;
/**
* Gets an {@link ItemMapping} from the given {@link GeyserItemStack}.
*
* @param itemStack the itemstack
* @return an item entry from the given item stack
*/
public ItemMapping getMapping(@NonNull GeyserItemStack itemStack) {
return this.getMapping(itemStack.getJavaId());
}
/**
* Gets an {@link ItemMapping} from the given {@link ItemStack}.
*
* @param itemStack the itemstack
* @return an item entry from the given java edition item stack
*/
@NonNull
public ItemMapping getMapping(@NonNull ItemStack itemStack) {
return this.getMapping(itemStack.getId());
}
/**
* Gets an {@link ItemMapping} from the given Minecraft: Java
* Edition id.
*
* @param javaId the id
* @return an item entry from the given java edition identifier
*/
@NonNull
public ItemMapping getMapping(int javaId) {
return javaId >= 0 && javaId < this.items.length ? this.items[javaId] : ItemMapping.AIR;
}
@NonNull
public ItemMapping getMapping(Item javaItem) {
return getMapping(javaItem.javaId());
}
/**
* Gets an {@link ItemMapping} from the given Minecraft: Java Edition
* block state identifier.
*
* @param javaIdentifier the block state identifier
* @return an item entry from the given java edition identifier
*/
@Nullable
public ItemMapping getMapping(String javaIdentifier) {
return this.cachedJavaMappings.computeIfAbsent(javaIdentifier, key -> {
for (ItemMapping mapping : this.items) {
if (mapping.getJavaItem().javaIdentifier().equals(key)) {
return mapping;
}
}
return null;
});
}
/**
* Gets an {@link ItemMapping} from the given {@link ItemData}.
*
* @param data the item data
* @return an item entry from the given item data
*/
@NonNull
public ItemMapping getMapping(ItemData data) {
ItemDefinition definition = data.getDefinition();
if (ItemDefinition.AIR.equals(definition)) {
return ItemMapping.AIR;
} else if (definition.getRuntimeId() == lodestoneCompass.getBedrockDefinition().getRuntimeId()) {
return lodestoneCompass;
}
ItemMapping lightBlock = lightBlocks.get(definition.getRuntimeId());
if (lightBlock != null) {
return lightBlock;
}
boolean isBlock = data.getBlockDefinition() != null;
boolean hasDamage = data.getDamage() != 0;
for (ItemMapping mapping : this.items) {
if (mapping.getBedrockDefinition().getRuntimeId() == definition.getRuntimeId()) {
if (isBlock && !hasDamage) { // Pre-1.16.220 will not use block runtime IDs at all, so we shouldn't check either
if (data.getBlockDefinition() != mapping.getBedrockBlockDefinition()) {
continue;
}
} else {
if (!(mapping.getBedrockData() == data.getDamage() ||
// Make exceptions for items whose damage values can vary
(mapping.getJavaItem().ignoreDamage() || mapping.getJavaItem() == Items.SUSPICIOUS_STEW))) {
continue;
}
}
if (!this.javaOnlyItems.contains(mapping.getJavaItem())) {
// From a Bedrock item data, we aren't getting one of these items
return mapping;
}
}
}
GeyserImpl.getInstance().getLogger().debug("Missing mapping for bedrock item " + data);
return ItemMapping.AIR;
}
@Nullable
@Override
public ItemDefinition getDefinition(int bedrockId) {
return this.itemDefinitions.get(bedrockId);
}
@Nullable
public ItemDefinition getDefinition(String bedrockIdentifier) {
for (ItemDefinition itemDefinition : this.itemDefinitions.values()) {
if (itemDefinition.getIdentifier().equals(bedrockIdentifier)) {
return itemDefinition;
}
}
return null;
}
@Override
public boolean isRegistered(ItemDefinition definition) {
return getDefinition(definition.getRuntimeId()) == definition;
}
}
| 412 | 0.890866 | 1 | 0.890866 | game-dev | MEDIA | 0.365368 | game-dev | 0.957549 | 1 | 0.957549 |
SethRobinson/proton | 1,934 | shared/Gamepad/GamepadProviderXInput.cpp | #include "PlatformPrecomp.h"
#include "GamepadProviderXInput.h"
#include "GamepadXInput.h"
#include "GamepadManager.h"
//#pragma comment (lib, "xinput.lib") //win 10+ only?
#pragma comment (lib, "XINPUT9_1_0.LIB") //so we can work with Win7
GamepadProviderXInput::GamepadProviderXInput()
{
_preallocateControllersEvenIfMissing = false;
//clear GamepadUniqueID
memset(&m_gamepadUniqueID, 0, sizeof(m_gamepadUniqueID));
}
GamepadProviderXInput::~GamepadProviderXInput()
{
}
bool GamepadProviderXInput::Init()
{
LogMsg("Initting XInput windows gamepad provider");
if (_preallocateControllersEvenIfMissing)
{
LogMsg("(_preallocateControllersEvenIfMissing flag set - Initting space for four xinput devices, whether or not they are plugged in/on or not)");
}
/*
int playerID = -1;
XINPUT_STATE state;
for (DWORD i = 0; i < XUSER_MAX_COUNT && playerID == -1; i++)
{
ZeroMemory(&state, sizeof(XINPUT_STATE));
if (_preallocateControllersEvenIfMissing || XInputGetState(i, &state) == ERROR_SUCCESS)
{
//valid gamepad
GamepadXInput* pPad = new GamepadXInput();
pPad->SetProvider(this);
GetGamepadManager()->AddGamepad(pPad);
}
}
*/
return true;
}
void GamepadProviderXInput::PreallocateControllersEvenIfMissing(bool bNew)
{
_preallocateControllersEvenIfMissing = bNew;
}
void GamepadProviderXInput::Kill()
{
}
void GamepadProviderXInput::Update()
{
//check if a controller was plugged in
for (DWORD i = 0; i < XUSER_MAX_COUNT; i++)
{
if (m_gamepadUniqueID[i] != 0) continue; //already initted this one
ZeroMemory(&m_stateTemp, sizeof(XINPUT_STATE));
if (_preallocateControllersEvenIfMissing || XInputGetState(i, &m_stateTemp) == ERROR_SUCCESS)
{
//init this new gamepad that was just plugged in
GamepadXInput* pPad = new GamepadXInput();
pPad->SetProvider(this);
GetGamepadManager()->AddGamepad(pPad);
m_gamepadUniqueID[i] = pPad->GetID();
}
}
}
| 412 | 0.804029 | 1 | 0.804029 | game-dev | MEDIA | 0.719831 | game-dev | 0.838098 | 1 | 0.838098 |
project-topaz/topaz | 2,695 | scripts/zones/Full_Moon_Fountain/Zone.lua | -----------------------------------
--
-- Zone: Full_Moon_Fountain (170)
--
-----------------------------------
local ID = require("scripts/zones/Full_Moon_Fountain/IDs")
require("scripts/globals/conquest")
require("scripts/globals/missions")
require("scripts/globals/settings")
require("scripts/globals/titles")
-----------------------------------
function onInitialize(zone)
end
function onZoneIn(player, prevZone)
local cs = -1
if player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0 then
player:setPos(-260.136, 2.09, -325.702, 188)
end
if player:getCurrentMission(WINDURST) == tpz.mission.id.windurst.FULL_MOON_FOUNTAIN and player:getCharVar("MissionStatus") == 3 then
cs = 50
elseif player:getCurrentMission(WINDURST) == tpz.mission.id.windurst.DOLL_OF_THE_DEAD and player:getCharVar("MissionStatus") == 7 then
cs = 61
end
return cs
end
function afterZoneIn(player)
player:entityVisualPacket("kilk")
player:entityVisualPacket("izum")
player:entityVisualPacket("hast")
end
function onConquestUpdate(zone, updatetype)
tpz.conq.onConquestUpdate(zone, updatetype)
end
function onRegionEnter(player, region)
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
if csid == 50 then
finishMissionTimeline(player, 3, csid, option)
elseif csid == 61 then
player:addTitle(tpz.title.GUIDING_STAR)
finishMissionTimeline(player, 3, csid, option)
elseif csid == 32004 then
local battlefield = player:getBattlefield()
if battlefield then
local inst = battlefield:getArea()
local instOffset = ID.mob.MOON_READING_OFFSET + (6 * (inst - 1))
local allyPos =
{
[1] = { ajidoPos = {340.117, 48.752, -383.747, 64}, playerPos = { 340.220, 48.557, -386.114, 190} },
[2] = { ajidoPos = { -59.98, 10.752, 16.22, 64}, playerPos = { -59.877, 10.577, 13.853, 190} },
[3] = { ajidoPos = {-379.826, -51.248, 376.227, 64}, playerPos = {-459.974, -51.423, 373.86, 190} },
}
-- spawn Yali and Yatzlwurm
for i = instOffset + 4, instOffset + 5 do
SpawnMob(i)
end
-- spawn Ajido-Marujido and set ally positions
local allies = battlefield:getAllies()
if #allies == 0 then
local ajido = battlefield:insertEntity(14184, true, true)
ajido:setSpawn(allyPos[inst].ajidoPos)
ajido:spawn()
end
player:setPos(allyPos[inst].playerPos)
end
end
end
| 412 | 0.810783 | 1 | 0.810783 | game-dev | MEDIA | 0.995621 | game-dev | 0.930134 | 1 | 0.930134 |
MJRLegends/ExtraPlanets | 3,705 | src/main/java/com/mjr/extraplanets/moons/Deimos/WorldProviderDeimos.java | package com.mjr.extraplanets.moons.Deimos;
import java.util.LinkedList;
import java.util.List;
import com.mjr.extraplanets.Config;
import com.mjr.extraplanets.Constants;
import com.mjr.extraplanets.ExtraPlanetsDimensions;
import com.mjr.extraplanets.api.prefabs.world.WorldProviderRealisticMoon;
import com.mjr.extraplanets.blocks.ExtraPlanets_Blocks;
import com.mjr.extraplanets.moons.ExtraPlanets_Moons;
import com.mjr.extraplanets.moons.Deimos.worldgen.ChunkProviderDeimos;
import net.minecraft.block.Block;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.MathHelper;
import net.minecraft.world.DimensionType;
import net.minecraft.world.gen.IChunkGenerator;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import micdoodle8.mods.galacticraft.api.galaxies.CelestialBody;
import micdoodle8.mods.galacticraft.api.vector.Vector3;
import micdoodle8.mods.galacticraft.core.util.ConfigManagerCore;
public class WorldProviderDeimos extends WorldProviderRealisticMoon {
@Override
public Vector3 getFogColor() {
float f = 1.0F - this.getStarBrightness(1.0F);
if (Config.USE_REALISTIC_ATMOS)
return new Vector3(0 / 255.0F * f, 0 / 255.0F * f, 0 / 255.0F * f);
else
return new Vector3(212F / 255F * f, 181F / 255F * f, 155F / 255F * f);
}
@Override
public Vector3 getSkyColor() {
float f = 1.0F - this.getStarBrightness(1.0F);
if (Config.USE_REALISTIC_ATMOS)
return new Vector3(0 / 255.0F * f, 0 / 255.0F * f, 0 / 255.0F * f);
else
return new Vector3(209 / 255.0F * f, 170 / 255.0F * f, 138 / 255.0F * f);
}
@Override
public boolean hasSunset() {
return false;
}
@Override
public long getDayLength() {
return 192000L;
}
@Override
public boolean shouldForceRespawn() {
return !ConfigManagerCore.forceOverworldRespawn;
}
@Override
public Class<? extends IChunkGenerator> getChunkProviderClass() {
return ChunkProviderDeimos.class;
}
@Override
@SideOnly(Side.CLIENT)
public float getStarBrightness(float par1) {
final float var2 = this.world.getCelestialAngle(par1);
float var3 = 1.0F - (MathHelper.cos(var2 * Constants.twoPI) * 2.0F + 0.25F);
if (var3 < 0.0F) {
var3 = 0.0F;
}
if (var3 > 1.0F) {
var3 = 1.0F;
}
return var3 * var3 * 0.5F + 0.3F;
}
@Override
public boolean isSkyColored() {
return false;
}
@Override
public double getHorizon() {
return 44.0D;
}
@Override
public int getAverageGroundLevel() {
return 44;
}
@Override
public boolean canCoordinateBeSpawn(int var1, int var2) {
return true;
}
@Override
public float getGravity() {
return 0.062F;
}
@Override
public double getMeteorFrequency() {
return 7.0D;
}
@Override
public double getFuelUsageMultiplier() {
return 0.9D;
}
@Override
public double getSolarEnergyMultiplier() {
return 3.0D;
}
@Override
public boolean canSpaceshipTierPass(int tier) {
return tier >= ExtraPlanets_Moons.DEIMOS.getTierRequirement();
}
@Override
public float getFallDamageModifier() {
return 0.18F;
}
@Override
public CelestialBody getCelestialBody() {
return ExtraPlanets_Moons.DEIMOS;
}
@Override
public DimensionType getDimensionType() {
return ExtraPlanetsDimensions.DEIMOS;
}
@Override
public int getDungeonSpacing() {
return 0;
}
@Override
public ResourceLocation getDungeonChestType() {
return null;
}
@Override
public List<Block> getSurfaceBlocks() {
List<Block> list = new LinkedList<>();
list.add(ExtraPlanets_Blocks.DEIMOS_BLOCKS);
return list;
}
@Override
public int getPressureLevel() {
return 90;
}
@Override
public int getSolarRadiationLevel() {
return Config.DEIMOS_RADIATION_AMOUNT;
}
}
| 412 | 0.718086 | 1 | 0.718086 | game-dev | MEDIA | 0.940167 | game-dev | 0.862885 | 1 | 0.862885 |
ss14Starlight/space-station-14 | 1,407 | Content.Shared/EntityTable/Conditions/ReoccurrenceDelayCondition.cs | using System.ComponentModel.DataAnnotations;
using System.Linq;
using Content.Shared.EntityTable.EntitySelectors;
using Content.Shared.GameTicking;
using Robust.Shared.Prototypes;
namespace Content.Shared.EntityTable.Conditions;
public sealed partial class ReoccurrenceDelayCondition : EntityTableCondition
{
/// <summary>
/// The maximum amount of times this rule can have already be run.
/// </summary>
[DataField]
public TimeSpan Delay = TimeSpan.Zero;
/// <summary>
/// The rule that is being checked for occurrences.
/// If null, it will use the value on the attached selector.
/// </summary>
[DataField]
public EntProtoId? RuleOverride;
protected override bool EvaluateImplementation(EntityTableSelector root,
IEntityManager entMan,
IPrototypeManager proto,
EntityTableContext ctx)
{
string rule;
if (RuleOverride is { } ruleOverride)
{
rule = ruleOverride;
}
else
{
rule = root is EntSelector entSelector
? entSelector.Id
: string.Empty;
}
if (rule == string.Empty)
return false;
var gameTicker = entMan.System<SharedGameTicker>();
return gameTicker.AllPreviousGameRules.Any(
p => p.Item2 == rule && p.Item1 + Delay <= gameTicker.RoundDuration());
}
}
| 412 | 0.904578 | 1 | 0.904578 | game-dev | MEDIA | 0.851495 | game-dev | 0.925279 | 1 | 0.925279 |
sutras/sard-uniapp | 1,118 | src/lib/components/style/configuration.scss | // # 灰度值
$sar-white: #fff;
$sar-gray-100: #f7f7f8;
$sar-gray-200: #ecedee;
$sar-gray-300: #e2e3e4;
$sar-gray-400: #d1d4d6;
$sar-gray-500: #b5b9bd;
$sar-gray-600: #74787c;
$sar-gray-700: #505457;
$sar-gray-800: #393c3f;
$sar-gray-900: #242628;
$sar-black: #000;
// # 颜色
$sar-blue: #3b82f6;
$sar-indigo: #6366f1;
$sar-purple: #a855f7;
$sar-pink: #ec4899;
$sar-red: #ef4444;
$sar-orange: #f97316;
$sar-yellow: #eab308;
$sar-green: #22c55e;
$sar-teal: #14b8a6;
$sar-cyan: #06b6d4;
// # 主题色列表
$sar-theme-colors: (
primary: (
var(--sar-primary),
var(--sar-primary-rgb),
),
secondary: (
var(--sar-secondary),
var(--sar-secondary-rgb),
),
success: (
var(--sar-success),
var(--sar-success-rgb),
),
info: (
var(--sar-info),
var(--sar-info-rgb),
),
warning: (
var(--sar-warning),
var(--sar-warning-rgb),
),
danger: (
var(--sar-danger),
var(--sar-danger-rgb),
),
neutral: (
var(--sar-neutral),
var(--sar-neutral-rgb),
),
);
// # bem
$sar-namespace: 'sar';
$sar-block-separator: '-';
$sar-element-separator: '__';
$sar-modifier-separator: '_';
| 412 | 0.616148 | 1 | 0.616148 | game-dev | MEDIA | 0.73921 | game-dev | 0.505264 | 1 | 0.505264 |
RustOtomeLab/RustEng | 1,166 | src/config/volume.rs | use crate::config::user::USER_CONFIG;
use crate::executor::executor::Executor;
use crate::ui::ui::MainWindow;
use serde::{Deserialize, Serialize};
use slint::Weak;
#[derive(Debug, Deserialize, Serialize)]
pub(crate) struct VolumeConfig {
main: f32,
bgm: f32,
voice: f32,
}
impl VolumeConfig {
pub fn main(&self) -> f32 {
self.main
}
pub fn bgm(&self) -> f32 {
self.bgm
}
pub fn voice(&self) -> f32 {
self.voice
}
pub fn from_weak(weak: Weak<MainWindow>) -> Self {
if let Some(window) = weak.upgrade() {
VolumeConfig {
main: window.get_main_volume(),
bgm: window.get_bgm_volume(),
voice: window.get_voice_volume(),
}
} else {
unreachable!()
}
}
}
impl Executor {
pub fn load_volume(&self) {
let weak = self.get_weak();
if let Some(window) = weak.upgrade() {
window.set_main_volume(USER_CONFIG.main_volume());
window.set_bgm_volume(USER_CONFIG.bgm_volume());
window.set_voice_volume(USER_CONFIG.voice_volume());
}
}
}
| 412 | 0.894841 | 1 | 0.894841 | game-dev | MEDIA | 0.393317 | game-dev,desktop-app | 0.914576 | 1 | 0.914576 |
MikuLeaks/KianaBH3-Beta | 1,554 | GameServer/Server/Packet/Send/Adventure/PacketGetAdventureStorySweepInfoRsp.cs | using KianaBH.KcpSharp;
using KianaBH.Proto;
namespace KianaBH.GameServer.Server.Packet.Send.Adventure;
public class PacketGetAdventureStorySweepInfoRsp : BasePacket
{
public PacketGetAdventureStorySweepInfoRsp() : base(CmdIds.GetAdventureStorySweepInfoRsp)
{
// TODO: Hardcoded
var proto = new GetAdventureStorySweepInfoRsp
{
StorySweepList =
{
new IslandStorySweepData
{
AvatarIdList =
{
20401,
20301,
20201
},
IsFinished = true,
OverTime = 1719938652,
SweepId = 282
},
new IslandStorySweepData
{
AvatarIdList =
{
3701,
3601,
3501
},
IsFinished = true,
OverTime = 1719938654,
SweepId = 282
},
new IslandStorySweepData
{
AvatarIdList =
{
3301,
3201,
3101
},
IsFinished = true,
OverTime = 1719938655,
SweepId = 282
}
}
};
SetData(proto);
}
}
| 412 | 0.733958 | 1 | 0.733958 | game-dev | MEDIA | 0.847804 | game-dev,networking | 0.578396 | 1 | 0.578396 |
ggnkua/Atari_ST_Sources | 13,786 | ASM/Various/S.J.Parys/Rollaround/SPRTEGRB.S | OPT D+
*************** INITIALISE ROUTINES **************
* MOUSE OFF,JOYSTK OFF
START MOVE.L #KEYSET,-(A7)
MOVE.L #$190001,-(A7) MOFF,JOFF USING ikbdws
TRAP #14
ADDQ #8,A7
DC.W $A000 INIT LINE A
DC.W $A00A REMOVE MOUSE
* SAVE OLD SR AND SSP AND ENTER SUPERVISOR MODE
MOVE.W SR,OLDSR+2
MOVE.L A7,-(A7)
MOVE.W #$20,-(A7) CALL super
TRAP #1
MOVE.L D0,OLDSSP+2
* ALL MFP IRQS OFF
LEA $FFFFFA01,A0 MFP HARDWARE BASE ADDRESS
MOVEQ #0,D0 SET UP ALL INTERRUPTS
MOVEP.L D0,0(A0) TO BE OFF AND IGNORED
MOVEP.L D0,8(A0) AND CLEAR IRQ MASKING ETC.
MOVEP.L D0,16(A0)
MOVE.B #$48,22(A0) VECTOR NUMBER HIGH NIBBLE
* AND S BIT SET (BIT 3)
* RESET KEYBOARD ACIA
MOVE.B #3,$FFFFFC00 HARD RESET
MOVE.B #$96,$FFFFFC00 SET RATE/PARITY ETC.
* NEW KEYBRD/JYSTK VECTOR
MOVE.L #READKEY,(A7)
MOVE.L #$D0006,-(A7) CALL mfpint
TRAP #14
ADDQ.W #8,A7
* NEW VBL ROUTINE
MOVE.L $70.W,OLDVBL+2 STORE OLD VECTOR
MOVE.L #VBL,$70.W SET TO NEW VALUE
* FIND 256 BOUNDARY WITHIN STORE
MOVE.L #STORE,D0
TST.B D0
BEQ.S SCRPOSOK
ANDI.B #0,D0
ADD.L #$100,D0
SCRPOSOK MOVE.L D0,SCRNADD+2
ADDI.L #32000,D0
MOVE.L D0,SCROLLDATA+2
ADDI.L #32000,D0
MOVE.L D0,SCROLLADD+2
* STORE CURRENT PALLATE
LEA $FFFF8240,A0
LEA SAVEPALL,A1
MOVEQ #15,D0
STOPALL MOVE.W (A0)+,(A1)+
DBF D0,STOPALL
*************** MAIN PROGRAM **************
* PRINT THE MENU AND SELECT AN OPERATION
MAIN LEA MENU,A0
BSR OUTLINE
BSR CURSORON
SELECT BSR.S KEY
CMPI.B #1,D0
BEQ.S EXIT
CMPI.B #"1",D0
BCS.S SELECT
CMPI.B #"5",D0
BHI.S SELECT
MOVE.W D0,-(A7)
BSR OUTCHAR
BSR ENDLINE
BSR CURSOROFF
MOVE.W (A7)+,D0
SUBI.W #"1",D0
LSL.W #2,D0
LEA JUMPS,A0
MOVE.L 0(A0,D0.W),A0
JSR (A0)
BRA.S MAIN
* RESTORE OPERATING SYSTEM AND EXIT
EXIT BSR CURSOROFF
OLDVBL MOVE.L #0,$70.W RESTORE OLD VBL VECTOR
JSR $FC2408
MOVE.L #KEYS1,-(A7)
MOVE.L #$190003,-(A7) RESET KYBRD,MOFF,JOFF
TRAP #14
ADDQ #8,A7
DC.W $A009 PUT MOUSE BACK
MOVE.L A7,A0
OLDSSP MOVE.L #0,A7
OLDSR MOVE.W #0,SR
MOVE.L A0,A7
CLR.W -(A7)
TRAP #1
* SUBROUTINE TO READ A KEY - RETURNS ASCII CODE IN D0
* ONLY MODIFIES D0 !
KEY MOVEQ #0,D0 GET KEY VALUE
BEQ.S NOKEY ZERO=NONE
BMI.S GETASCII IF MINUS THEN CONVERT
DUDKEY MOVEQ #0,D0 IGNORE SHIFT KEYS ETC
NOKEY RTS DONE
GETASCII CLR.B KEY+1 REMOVE OLD KEY
ANDI.W #$7F,D0 CLEAR BIT 8
CMPI.B #$60,D0 WITHIN ALLOWED RANGE ?
BHI.S DUDKEY NO
MOVE.L A0,-(A7) STORE A0
LEA ASCII,A0 GET ASCII TABLE ADDRESS
TST.B SHIFTFLAG SHIFT ON ?
BEQ.S NOSHIFT NO
LEA ASCII1,A0 GET SHIFTED ASCII TABLE
NOSHIFT MOVE.B 0(A0,D0.W),D0 GET ASCII CODE
MOVE.L (A7)+,A0 RESTORE A0
RTS
* SUBROUTINE TO OUTPUT A LINE OF TEXT
OUTLINE TST.B (A0)
BEQ.S LINEDONE
MOVE.B (A0)+,D0
MOVE.L A0,-(A7)
BSR.S OUTCHAR
MOVE.L (A7)+,A0
BRA.S OUTLINE
* SUBROUTINE TO OUTPUT A CHARACTER
* USES A TRAP SO PRESUME ONLY STACK TO BE PRESERVED
OUTCHAR ANDI.W #$FF,D0
MOVE.W D0,-(A7)
MOVE.W #2,-(A7)
TRAP #1
ADDQ #4,A7
LINEDONE RTS
* SUBROUTINE TO OUTPUT ENTER
ENDLINE MOVE.B #12,D0
BSR.S OUTCHAR
MOVE.B #13,D0
BRA.S OUTCHAR
* SUBROUTINE TO OUTPUT BACKSPACE
BACKSPACE MOVE.B #8,D0
BSR.S OUTCHAR
MOVE.B #" ",D0
BSR.S OUTCHAR
MOVE.B #8,D0
BRA.S OUTCHAR
* SUBROUTINE TO SWITCH CURSOR ON
CURSORON MOVE.B #27,D0
BSR.S OUTCHAR
MOVE.B #"e",D0
BRA.S OUTCHAR
* SUBROUTINE TO SWITCH CURSOR OFF
CURSOROFF MOVE.B #27,D0
BSR.S OUTCHAR
MOVE.B #"f",D0
BRA.S OUTCHAR
* INPUT FILENAME
GETNAME LEA FILEPROMPT,A0
BSR.S OUTLINE
* READ A LINE OF TEXT
LINEREAD BSR.S CURSORON
LEA CHARBUFF,A0
MOVE.L A0,STORECHAR+2
CLEARBUFF CLR.B (A0)+
CMP.L #ENDSTO,A0
BNE.S CLEARBUFF
READLINE BSR KEY
TST.B D0
BEQ.S READLINE
CMPI.B #$D,D0
BEQ.S CRSOROFF
CMPI.B #$8,D0
BNE.S NOTDEL
MOVE.L STORECHAR+2,A0
CMP.L #CHARBUFF,A0
BEQ.S READLINE
CLR.B -(A0)
MOVE.L A0,STORECHAR+2
BSR.S BACKSPACE
BRA.S READLINE
NOTDEL CMPI.L #ENDSTO,STORECHAR+2
BEQ.S READLINE
STORECHAR MOVE.B D0,CHARBUFF
ADDQ.L #1,STORECHAR+2
BSR OUTCHAR
BRA.S READLINE
CRSOROFF BSR.S CURSOROFF
BRA ENDLINE
* SUBROUTINE TO SAVE PRE-ROTATED DATA TO DISK
SAVEDATA BSR.S GETNAME
MOVE.L SCROLLADD+2,WRITEFILE+2
MOVE.L DATALENGTH,FLENGTH+2
MOVE.L OLDVBL+2,$70.W RESTORE OLD VBL VECTOR
BSR.S CREATEFILE
TST.W D0
BMI.S ERROCCUR1
BSR WRITEFILE
TST.W D0
BMI.S ERROCCUR1
BSR CLOSEFILE
ERROCCUR1 MOVE.L #VBL,$70.W
RTS
* SUBROUTINE TO CHECK FOR DISK CHANGE
CHCKDISK MOVE.W #0,-(A7) DRIVE A
MOVE.W #7,-(A7) GETBPB
TRAP #13 BIOS
ADDQ #4,A7
RTS
* SUBROUTINE TO CREATE A FILE NB. NAME IN CHARBUFF
CREATEFILE BSR.S CHCKDISK
MOVE.W #0,-(A7)
PEA CHARBUFF
MOVE.W #$3C,-(A7)
TRAP #1
MOVE.W D0,FHANDLE+2
ADDQ #8,A7
RTS
* SUBROUTINE TO OPEN A FILE NB. NAME IN CHARBUFF
OPENFILE BSR.S CHCKDISK
MOVE.W #2,-(A7) OPEN FILE
PEA CHARBUFF
MOVE.W #$3D,-(A7)
TRAP #1
MOVE.W D0,FHANDLE+2
ADDQ #8,A7
RTS
* SUBROUTINE TO READ FROM A FILE NB. FHANDLE+2 SET UP
READFILE PEA STORE LOAD ADDRESS
FLENGTH PEA 32000 LENGTH
FHANDLE MOVE.W #0,-(A7)
MOVE.W #$3F,-(A7) LOAD FILE
TRAP #1
ADD.L #12,A7
RTS
* SUBROUTINE TO WRITE TO A FILE NB. FHANDLE+2 SET UP
WRITEFILE PEA STORE SAVE ADDRESS
MOVE.L FLENGTH+2,-(A7) LENGTH TO SAVE
MOVE.W FHANDLE+2,-(A7)
MOVE.W #$40,-(A7)
TRAP #1
ADD.L #12,A7
RTS
* SUBROUTINE TO CLOSE A FILE NB. FHANDLE+2 SET UP
CLOSEFILE MOVE.W FHANDLE+2,-(A7) CLOSE FILE
MOVE.W #$3E,-(A7)
TRAP #1
ADDQ #4,A7
RTS
* SUBROUTINE TO LOAD AND VIEW A NEO FILE
VIEWNEO BSR GETNAME
MOVE.L OLDVBL+2,$70.W
BSR.S OPENFILE
TST.W D0
BMI ERROCCUR
MOVE.L #NEOPALL,READFILE+2
MOVE.L #128,FLENGTH+2
BSR.S READFILE
TST.W D0
BMI.S ERROCCUR
SCRNADD MOVE.L #STORE,READFILE+2
MOVE.L #32000,FLENGTH+2
BSR READFILE
TST.W D0
BMI.S ERROCCUR
BSR.S CLOSEFILE
TST.W D0
BMI.S ERROCCUR
MOVE.L #VBL,$70.W
BSR.S SETNEO
* WAIT FOR KEYPRESS
KEYWAIT TST.B KEY+1
BPL.S KEYWAIT
* RESET SCREEN ADDRESS AND PALETTE
SETMENU BSR.S WAITVBL
LEA $FFFF8201,A0
MOVE.B $44F.W,(A0)
MOVE.B $450.W,2(A0)
ADD.W #$3F,A0
LEA SAVEPALL,A1
MOVEQ #15,D0
OLDPALL MOVE.W (A1)+,(A0)+
DBF D0,OLDPALL
ERROCCUR MOVE.L #VBL,$70.W
RTS
* SWITCH SCREEN ADDRESS AND CHANGE PALETTE
SETNEO BSR.S WAITVBL
LEA $FFFF8201,A0
MOVE.B SCRNADD+3,(A0)
MOVE.B SCRNADD+4,2(A0)
ADD.W #$3F,A0
LEA NEOPALL+4,A1
MOVEQ #15,D0
NEWPALL MOVE.W (A1)+,(A0)+
DBF D0,NEWPALL
RTS
* WAIT FOR VBL
WAITVBL MOVE.B $469.W,D0
WAIT CMP.B $469.W,D0
BEQ.S WAIT
RTS
* SUBROUTINE TO SELECT THE SPRITE
GETIT BSR.S SETNEO
BADGET MOVE.W #0,XCO+2
MOVE.W #0,YCO+2
BSR SELECTPOS
MOVE.W XCO+2,X1+2
MOVE.W YCO+2,Y1+2
MOVE.L POS+2,POS1+2
MOVEQ #49,D1
WAITFIRE BSR WAITVBL
DBF D1,WAITFIRE
BSR.S SELECTPOS
XCO MOVE.W #0,D0
X1 SUBI.W #0,D0
BPL.S YCO
NEG.W D0
YCO MOVE.W #0,D1
Y1 SUBI.W #0,D1
BEQ.S YOK
BPL.S YOK1
NEG.W D1
YOK1 SUBI.W #1,D1
YOK MOVE.W D1,NLINES+2
LSR.W #1,D0 = NO OF BYTES
ADDQ #7,D0
MOVE.W D0,WIDTH+2
POS MOVE.L #0,D2
POS1 CMPI.L #0,D2
BCS.S PSTNOK
MOVE.L POS1+2,D2
PSTNOK MOVE.L D2,CONVDATA+2
ADDQ #1,D0
ADDQ #1,D1
MULU D1,D0
MOVE.W D0,SIZE+2
ANDI.L #$FFFF,D0
LSL.L #3,D0
MOVE.L D0,DATALENGTH
BRA SETMENU
* ROUTINE TO SELECT SCREEN POSITION
SELECTPOS BSR DRAWPOS
MOVE.B JOY1+1,D0
CLR.B JOY1+1
BTST #7,D0
BNE POSOFF
MOVE.W XCO+2,D1
MOVE.W YCO+2,D2
BTST #0,D0
BEQ.S NOTD1
SUBI.W #8,D2
BPL.S NOTD1
ADDI.W #8,D2
NOTD1 BTST #1,D0
BEQ.S NOTD2
ADDI.W #8,D2
CMPI.W #200,D2
BCS.S NOTD2
SUBI.W #8,D2
NOTD2 BTST #2,D0
BEQ.S NOTD3
SUBI.W #16,D1
BPL.S NOTD3
ADDI.W #16,D1
NOTD3 BTST #3,D0
BEQ.S NOTD4
ADDI.W #16,D1
CMPI.W #320,D1
BCS.S NOTD4
SUBI.W #16,D1
NOTD4 BSR WAITVBL
BSR WAITVBL
BSR WAITVBL
BSR.S POSOFF
MOVE.W D1,XCO+2
MOVE.W D2,YCO+2
BRA SELECTPOS
DRAWPOS MOVE.L SCRNADD+2,A0
MOVE.W YCO+2,D0
MULU #160,D0
ADDA.W D0,A0
MOVE.W XCO+2,D0
LSR.W #1,D0
ADDA.W D0,A0
MOVE.L A0,POS+2
POSOFF EORI.L #$FFFFFFFF,(A0)
EORI.L #$FFFFFFFF,2(A0)
RTS
* SUBROUTINE TO CONVERT GRAPHICS DATA
CONVDATA MOVE.L #STORE,A0 TOP LEFT ON SCREEN
SCROLLADD LEA STORE,A2
NLINES MOVE.W #47,D0 48 LINES
DOLINE MOVE.L A0,A1
WIDTH MOVE.W #63,D1 IN BYTES
COPYDATA MOVE.B (A1)+,(A2)+
DBF D1,COPYDATA
ADDA.W #160,A0 MOVE TO NEXT LINE
DBF D0,DOLINE
MOVE.L A2,A0 NEXT SECTION INTO A0
MOVEQ #6,D7 7 MORE COPIES-TO BE ROTATED
ROTATE MOVE.L A0,A1 A1 TO PSTN FOR NEXT SECTION
SIZE SUBA.W #$C00,A0 LAST SECTION IN A0
MOVE.W SIZE+2,D0
SUBQ #1,D0
COPYALL MOVE.B (A0)+,(A1)+ COPY ALL THE DATA
DBF D0,COPYALL
MOVE.W NLINES+2,D6 ROTATE NLINES
ROTATELINE MOVEQ #1,D5 ROTATE 2 BITS
TWOBITS MOVEQ #3,D4 4 BIT PLANES
BITPLANES MOVE.W WIDTH+2,D0 WIDTH
SUBQ #7,D0
MOVE.W 0(A0,D0.W),D0 BIT PLANE AT END OF LINE
MOVE.W WIDTH+2,D3
ADDQ #1,D3
LSR.W #3,D3
SUBQ #1,D3 N BLOCKS OF 16 PIXELS
ROXR.W #1,D0 ROTATE THE BIT INTO X
ROTATEPLANE ROXR.W (A0)
ADDQ #8,A0
DBF D3,ROTATEPLANE ALL BLOCKS THIS BIT PLANE
MOVE.W WIDTH+2,D3
SUBQ #1,D3
SUBA.W D3,A0 MOVE TO NEXT PLANE
DBF D4,BITPLANES ALL BITPLANES
SUBQ #8,A0 A0 BACK TO START OF LINE
DBF D5,TWOBITS ROTATE TWICE
ADDA.W WIDTH+2,A0 A0 TO NEXT LINE
ADDQ #1,A0
DBF D6,ROTATELINE ALL LINES
DBF D7,ROTATE ALL COPIES
RTS
EXITVIEW MOVE.L SCROLLDATA+2,A0
MOVE.L SCRNADD+2,A1
MOVE.W #7999,D0
GETSCREEN MOVE.L (A0)+,(A1)+
DBF D0,GETSCREEN
BRA SETMENU
* VIEW THE ROTATED DATA
SCROLLDATA LEA STORE,A0
MOVE.L SCRNADD+2,A1
MOVE.W #7999,D0
STOSCREEN MOVE.L (A1)+,(A0)+
DBF D0,STOSCREEN
BSR SETNEO
MOVE.W #0,SCROLLPOS+2
DOSCROLL BSR WAITVBL
LEA $FFFF8203,A0 SCREEN BASE MID-BYTE
MOVE.B (A0),D0 PUT INTO D0
WAIT1 CMP.B 4(A0),D0 RASTER AT BASE ?
BNE.S ONVIEW NO
WAIT2 TST.B 6(A0) RASTER ABOVE LINE 1 ?
BEQ.S WAIT2 YES
ONVIEW MOVE.L SCRNADD+2,A4
SCROLLPOS MOVE.W #0,D0
SPEED MOVE.W #0,D2
JOY1 MOVEQ #0,D1
CLR.B JOY1+1
BTST #7,D1
BNE.S EXITVIEW
BTST #0,D1
BEQ.S NOTUP
ADDQ #1,D2
CMPI.W #$500,D2
BHI.S TOOHI
NOTUP BTST #1,D1
BEQ.S SPEEDOK
TOOHI SUBQ.W #1,D2
BPL.S SPEEDOK
ADDQ #1,D2
SPEEDOK MOVE.W D2,SPEED+2
EORI.W #$777,$FFFF8240
BTST #3,D1
BEQ.S NOTRIGHT
ADD.W D2,D0
NOTRIGHT BTST #2,D1
BEQ.S NOTLEFT
SUB.W D2,D0
NOTLEFT TST.W D0
BPL.S CHCKLOW IF NEGATIVE THEN
ADDI.W #$A00,D0 SUBTRACT FROM MAX VALUE
BRA.S PSTNSET
CHCKLOW CMPI.W #$A00,D0
BCS.S PSTNSET IF PAST MAX THEN
SUBI.W #$A00,D0 SUBTRACT MAX
PSTNSET MOVE.W D0,SCROLLPOS+2 STORE NEW POSITION
LSR.W #4,D0 REMOVE FRACTION
MOVE.W D0,D1 COPY VALUE
ANDI.W #7,D0 DRAWING NUMBER IN D0
ANDI.W #$F8,D1 HORIZ POSITION IN D1
ADDA.W D1,A4 TOP LEFT IN A4
MOVE.L SCROLLADD+2,A0
MOVE.W SIZE+2,D2
MULU D2,D0
ADDA.L D0,A0 A0=START OF DRAWING
MOVE.L SCRNADD+2,A6
MOVE.W #1919,D7
CLS CLR.L (A6)+
DBF D7,CLS
MOVE.W NLINES+2,D1
PRINTIT MOVE.W WIDTH+2,D2
ADDQ #1,D2
LSR.W #2,D2 NO OF LONG WORDS WIDE
SUBQ #1,D2
MOVE.L A4,A5
PRINTIT1 MOVE.L (A0)+,(A5)+
DBF D2,PRINTIT1
ADDA.W #160,A4
DBF D1,PRINTIT
EORI.W #$777,$FFFF8240
BRA DOSCROLL
* VBL ROUTINE
* COUNT/MONITOR CHECK/REQUEST JOYSTICK DATA EVERY 16TH VBL
VBL MOVE.L D0,-(A7) STORE D0
MOVE.L $466.W,D0 GET COUNT
ADDQ #1,D0 ADD ONE
MOVE.L D0,$466.W STORE COUNT
ANDI.B #$0,D0 CHECK IF BITS 0-3 CLEAR
BNE.S NOT32 IF NOT THEN OK ELSE
* REQUEST JOYSTICK DATA
MOVE.L A0,-(A7) STORE A0
LEA $FFFFFC00,A0 ACIA STATUS/CONTROL
JOYWAIT MOVE.B (A0),D0 GET STATUS
BTST #1,D0 READY ?
BEQ.S JOYWAIT NO
MOVE.B #$16,2(A0) REQUEST JOYSTICK DATA
MOVE.W #$80,$FFFF8606 SELECT FDC COMMAND REG
MOVE.W $FFFF8604,D0 READ FDC STATUS REG
BTST.B #7,D0 MOTOR ON ?
BNE.S DRIVEON YES
MOVE.B #$E,$FFFF8800 ELSE DESELECT FLOPPIES
MOVE.B $FFFF8800,D0
ORI.B #7,D0
MOVE.B D0,$FFFF8802
DRIVEON MOVE.L (A7)+,A0 RESTORE A0
NOT32 MOVE.L (A7)+,D0 RESTORE D0
RTE DONE
* READ KYBRD/JOYSTICK
READKEY MOVEM.L D0/D1/A0,-(A7) STORE REGS
STILLIRQ LEA $FFFFFC00,A0 KEYBOARD STATUS/CONTROL
MOVE.B (A0),D1 READ STATUS TO CLEAR FLAGS
BTST #7,D1 IRQ ?
BEQ NOKEY2 NO
BTST #0,D1 BUFFER FULL ?
BEQ.S NOKEY1 NO
MOVE.B 2(A0),D0 READ DATA
NOKEY1 ANDI.B #$20,D1 ERROR ?
BEQ.S JKFLG NO
MOVE.B 2(A0),D1 READ AGAIN,CLEAR STATUS
BRA NOKEY2
JKFLG MOVEQ #0,D1 CHECK PACKAGE COUNT
BNE.S JOYVALS IF IN PACKAGE
CMPI.B #$FD,D0 START OF JOYSTICK PACKAGE ?
BEQ.S NEWJOY YES
MOVE.B D0,KEY+1 STORE KEY READ
CMPI.B #$2A,D0 LEFT SHIFT ON ?
BNE.S LSHFTOK
SEQ LSHIFTFLAG+1
LSHFTOK CMPI.B #$36,D0 RIGHT SHIFT ON ?
BNE.S RSHFTOK
SEQ RSHIFTFLAG+3
RSHFTOK CMPI.B #$AA,D0 LEFT SHIFT OFF ?
BNE.S LSHFTOK1 NO
CLR.B LSHIFTFLAG+1
LSHFTOK1 CMPI.B #$B6,D0 RIGHT SHIFT OFF ?
BNE.S LSHIFTFLAG NO
CLR.B RSHIFTFLAG+3
LSHIFTFLAG MOVEQ #0,D0
RSHIFTFLAG ORI.W #$0,D0
MOVE.B D0,SHIFTFLAG
BRA.S JKDONE EXIT
NEWJOY MOVEQ #2,D1 SET COUNT TO 2 BYTES
BRA.S JKDONE EXIT
JOYVALS SUBQ.B #1,D1 DECREASE PACKAGE COUNT
BEQ.S SECOND IF LAST BYTE OF PACKAGE
MOVE.B D0,JOY0+1 STORE JOYSTICK 0 DATA
BRA.S JKDONE EXIT
SECOND MOVE.B D0,JOY1+1 STORE JOYSTICK 1 DATA
JKDONE MOVE.B D1,JKFLG+1 EXIT-STORE NEW PCKGE COUNT
NOKEY2 BCLR #6,$FFFFFA11 CLEAR IRQ MASK
MOVEM.L (A7)+,D0/D1/A0 RESTORE REGS
RTE RETURN
KEYS1 DC.B $80,1 RESET KEY READ STATE
KEYSET DC.B $12,$1A MOUSE OFF,JOYSTICK OFF
MENU DC.B 27,"E",27,"Y",32,50,"MENU",12,13,12
DC.B "1. LOAD AND VIEW NEO FILE",12,13
DC.B "2. SELECT SPRITE",12,13
DC.B "3. CONVERT GRAPHICS STRIP AND PRE-ROTATE"
DC.B 12,13,"4. SCROLL STRIP-TO CHECK IT",12,13
DC.B "5. SAVE ALL STRIP DATA",12,13,12
PROMPT DC.B "WHAT NEXT ? ",0
FILEPROMPT DC.B "FILENAME ? ",0
SHIFTFLAG DC.B 0
ASCII DC.B 0,0,"1234567890-=",8,0,"QWERTYUIOP[]",13,0
DC.B "ASDFGHJKL;'`",0,"#ZXCVBNM,./",0,0,0," "
DC.B 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
DC.B 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"\"
ASCII1 DC.B 0,1,"!",34,"$%^&*()_+",8,0,"qwertyuiop{}"
DC.B 13,0,"asdfghjkl:@_",0,"~zxcvbnm<>?",0,0
DC.B 0," ",0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
DC.B 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"|"
EVEN
DATALENGTH EQU 64*48*8
CHARBUFF DC.B 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
DC.B 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
ENDSTO DC.B 0
EVEN
JOY0 DC.W 0
JUMPS DC.L VIEWNEO,GETIT,CONVDATA,SCROLLDATA,SAVEDATA
SAVEPALL DS.L 8
NEOPALL DS.L 32
STORE DSBSS.B 32000*6
END
| 412 | 0.954542 | 1 | 0.954542 | game-dev | MEDIA | 0.548107 | game-dev | 0.992683 | 1 | 0.992683 |
wedfrgt/Akebi-GC-Backup | 6,428 | cheat-library/src/user/cheat/world/VacuumLoot.cpp | #include "pch-il2cpp.h"
#include "VacuumLoot.h"
#include <helpers.h>
#include <cheat/events.h>
#include <cheat/game/EntityManager.h>
#include <cheat/game/util.h>
namespace cheat::feature
{
VacuumLoot::VacuumLoot() : Feature(),
NF(f_Enabled, "Vacuum Loot", "VacuumLoot", false),
NF(f_DelayTime, "Delay time (in ms)", "VacuumLoot", 1000),
NF(f_Distance, "Distance", "VacuumLoot", 1.5f),
NF(f_MobDropRadius, "Mob Drop Radius", "VacuumLoot", 20.0f),
NF(f_Radius, "Radius", "VacuumLoot", 20.0f),
nextTime(0)
{
InstallFilters();
events::GameUpdateEvent += MY_METHOD_HANDLER(VacuumLoot::OnGameUpdate);
}
const FeatureGUIInfo& VacuumLoot::GetGUIInfo() const
{
static const FeatureGUIInfo info{ "Vacuum Loot", "World", true };
return info;
}
void VacuumLoot::DrawMain()
{
ConfigWidget("Enabled", f_Enabled, "Vacuum Loot drops"); ImGui::SameLine(); ImGui::SetNextItemWidth(100.0f);
ConfigWidget("Delay Time (ms)", f_DelayTime, 1, 0, 1000, "Delay (in ms) between loot vacuum.");
ConfigWidget("Radius (m)", f_Radius, 0.1f, 5.0f, 100.0f, "Radius of common loot vacuum.");
ConfigWidget("Mob Drop Radius (m)", f_MobDropRadius, 0.1f, 5.0f, 100.0f, "Radius of mob drop vacuum.\n"
"(Item Drops and Equipments)");
ConfigWidget("Distance (m)", f_Distance, 0.1f, 1.0f, 10.0f, "Distance between the player and the loot.\n"
"Values under 1.5 may be too intruding.");
if (ImGui::TreeNode("Loot Types"))
{
for (auto& [section, filters] : m_Sections)
{
ImGui::PushID(section.c_str());
DrawSection(section, filters);
ImGui::PopID();
}
ImGui::TreePop();
}
}
bool VacuumLoot::NeedStatusDraw() const
{
return f_Enabled;
}
void VacuumLoot::DrawStatus()
{
ImGui::Text("VacuumLoot\n[%dms|%.01fm|%.01fm|%.01fm]",
f_DelayTime.value(),
f_Radius.value(),
f_MobDropRadius.value(),
f_Distance.value()
);
}
VacuumLoot& VacuumLoot::GetInstance()
{
static VacuumLoot instance;
return instance;
}
bool VacuumLoot::IsEntityForVac(game::Entity* entity)
{
// Go through all sections. For each section, go through all filters.
// If a filter matches the given entity and that filter is enabled, return true.
bool entityValid = std::any_of(m_Sections.begin(), m_Sections.end(),
[entity](std::pair<std::string, Filters> const& section) {
return std::any_of(section.second.begin(), section.second.end(), [entity](const FilterInfo& filterInfo) {
return filterInfo.second->IsValid(entity) && filterInfo.first; });
});
if (!entityValid) return false;
bool isMobDrop = std::any_of(m_MobDropFilter.begin(), m_MobDropFilter.end(),
[entity](const game::IEntityFilter* filter) { return filter->IsValid(entity); });
auto& manager = game::EntityManager::instance();
auto distance = manager.avatar()->distance(entity);
return distance <= (isMobDrop ? f_MobDropRadius : f_Radius);
}
void VacuumLoot::OnGameUpdate()
{
if (!f_Enabled)
return;
auto currentTime = util::GetCurrentTimeMillisec();
if (currentTime < nextTime)
return;
auto& manager = game::EntityManager::instance();
auto avatarEntity = manager.avatar();
for (const auto& entity : manager.entities())
{
if (!IsEntityForVac(entity))
continue;
entity->setRelativePosition(avatarEntity->relativePosition() + avatarEntity->forward() * f_Distance);
}
nextTime = currentTime + f_DelayTime.value();
}
void VacuumLoot::DrawSection(const std::string& section, const Filters& filters)
{
bool checked = std::all_of(filters.begin(), filters.end(), [](const FilterInfo& filter) { return filter.first; });
bool changed = false;
if (ImGui::BeginSelectableGroupPanel(section.c_str(), checked, changed, true))
{
// TODO : Get Max Container Width and Calculate Max Item Width of Checkbox + Text / or specify same width for all columns
// then divide MaxWidth by ItemWidth/ColumnWidth and asign a floor result >= 1 to columns.
// Though this is also just fine IMO.
int columns = 3;
if (ImGui::BeginTable(section.c_str(), columns == 0 ? 1 : columns )) {
int i = 0;
for (std::pair<config::Field<bool>, game::IEntityFilter*> filter : filters) {
if (i % (columns == 0 ? 1 : columns) == 0)
{
ImGui::TableNextRow();
ImGui::TableSetColumnIndex(0);
}
else
ImGui::TableNextColumn();
ImGui::PushID(&filter);
ConfigWidget(filter.first);
ImGui::PopID();
i++;
}
ImGui::EndTable();
}
}
ImGui::EndSelectableGroupPanel();
if (changed)
{
for (const auto& info : filters)
{
info.first.value() = checked;
info.first.FireChanged();
}
}
}
void VacuumLoot::AddFilter(const std::string& section, const std::string& name, game::IEntityFilter* filter)
{
if (m_Sections.count(section) == 0)
m_Sections[section] = {};
auto& filters = m_Sections[section];
bool newItem(filter);
filters.push_back({ config::CreateField<bool>(name,name,fmt::format("VacuumLoot::Filters::{}", section),false, newItem) , filter });
}
#define ADD_FILTER_FIELD(section, name) AddFilter(util::MakeCapital(#section), util::SplitWords(#name), &game::filters::##section##::##name##)
void VacuumLoot::InstallFilters()
{
ADD_FILTER_FIELD(featured, ItemDrops);
ADD_FILTER_FIELD(equipment, Artifacts);
ADD_FILTER_FIELD(equipment, Bow);
ADD_FILTER_FIELD(equipment, Catalyst);
ADD_FILTER_FIELD(equipment, Claymore);
ADD_FILTER_FIELD(equipment, Sword);
ADD_FILTER_FIELD(equipment, Pole);
ADD_FILTER_FIELD(mineral, AmethystLumpDrop);
ADD_FILTER_FIELD(mineral, CrystalChunkDrop);
ADD_FILTER_FIELD(mineral, ElectroCrystalDrop);
ADD_FILTER_FIELD(mineral, IronChunkDrop);
ADD_FILTER_FIELD(mineral, NoctilucousJadeDrop);
ADD_FILTER_FIELD(mineral, MagicalCrystalChunkDrop);
ADD_FILTER_FIELD(mineral, ScarletQuartzDrop);
ADD_FILTER_FIELD(mineral, StarsilverDrop);
ADD_FILTER_FIELD(mineral, WhiteIronChunkDrop);
ADD_FILTER_FIELD(plant, Apple);
ADD_FILTER_FIELD(plant, Cabbage);
ADD_FILTER_FIELD(plant, CarrotDrop);
ADD_FILTER_FIELD(plant, Potato);
ADD_FILTER_FIELD(plant, RadishDrop);
ADD_FILTER_FIELD(plant, Sunsettia);
ADD_FILTER_FIELD(plant, Wheat);
ADD_FILTER_FIELD(living, CrystalCore);
ADD_FILTER_FIELD(living, Meat);
ADD_FILTER_FIELD(living, Crab);
ADD_FILTER_FIELD(living, Eel);
ADD_FILTER_FIELD(living, LizardTail);
ADD_FILTER_FIELD(living, Fish);
}
#undef ADD_FILTER_FIELD
}
| 412 | 0.961615 | 1 | 0.961615 | game-dev | MEDIA | 0.824974 | game-dev | 0.943549 | 1 | 0.943549 |
UNIVALI-LITE/Portugol-Studio | 5,007 | core/src/main/java/br/univali/portugol/nucleo/simbolos/Vetor.java | package br.univali.portugol.nucleo.simbolos;
import br.univali.portugol.nucleo.asa.NoDeclaracaoBase;
import br.univali.portugol.nucleo.asa.TipoDado;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Representa um vetor alocado em memória durante a execução de um programa.
*
* @author Luiz Fernando Noschang
* @version 1.0
*/
public final class Vetor extends Simbolo
{
private List<Object> valores;
private int ultimoIndiceModificado;
public final static Integer TAMANHO_MAXIMO = 16777216;
public int getUltimoIndiceModificado()
{
return ultimoIndiceModificado;
}
/**
* Aloca um vetor em memória sem definir seu tamanho nem seus valores.
*
* @param nome o nome deste vetor.
*
* @param tipoDado o tipo de dado armazenado por este vetor.
*
* @param declaracaoOrigem a declaração que originou este vetor
*
* @since 1.0
*/
public Vetor(String nome, TipoDado tipoDado, NoDeclaracaoBase declaracaoOrigem)
{
super(nome, tipoDado, declaracaoOrigem);
setInicializado(true);
}
/**
* Aloca um vetor em memória definindo seu tamanho, mas sem definir seus
* valores.
*
* @param nome o nome deste vetor.
*
* @param tipoDado o tipo de dado armazenado por este vetor.
*
* @param declaracaoOrigem a declaração que originou este vetor
*
* @param tamanho o tamamho que este vetor terá.
*
* @since 1.0
*/
public Vetor(String nome, TipoDado tipoDado, NoDeclaracaoBase declaracaoOrigem, int tamanho)
{
this(nome, tipoDado, declaracaoOrigem);
valores = new ArrayList<>(tamanho);
for (int i = 0; i < tamanho; i++)
{
valores.add(null);
}
}
/**
* Aloca um vetor em memória definindo seu tamanho e seus valores.
*
* @param nome o nome deste vetor.
*
* @param tipoDado o tipo de dado armazenado por este vetor.
*
* @param declaracaoOrigem a declaração que originou este vetor
*
* @param tamanho o tamamho que este vetor terá.
*
* @param valores os valores que serão armazenados neste vetor.
*
* @since 1.0
*/
public Vetor(String nome, TipoDado tipoDado, NoDeclaracaoBase declaracaoOrigem, int tamanho, List<Object> valores)
{
this(nome, tipoDado, declaracaoOrigem, tamanho);
for (int i = 0; i < this.valores.size(); i++)
{
this.valores.set(i, valores.get(i));
}
setInicializado(true);
}
/**
* Aloca um vetor em memória definindo seus valores, mas sem definir seu
* tamanho. O tamanho do vetor será detectado automaticamente a partir da
* lista de valores.
*
* @param nome o nome deste vetor.
*
* @param tipoDado o tipo de dado armazenado por este vetor.
*
* @param declaracaoOrigem a declaração que originou este vetor
*
* @param valores os valores que serão armazenados neste vetor.
*
* @since 1.0
*/
public Vetor(String nome, TipoDado tipoDado, NoDeclaracaoBase declaracaoOrigem, List<Object> valores)
{
this(nome, tipoDado, declaracaoOrigem);
this.valores = new ArrayList<>(valores);
setInicializado(true);
}
/**
* Obtém o tamanho deste vetor.
*
* @return o tamanho deste vetor.
*
* @since 1.0
*/
public int getTamanho()
{
return valores.size();
}
/**
* Recupera um valor armazenado neste vetor no índice esecificado.
*
* @param indice o índice deste vetor no qual o valor se encontra.
*
* @return o valor armazenado neste vetor no índice especificado.
*
* @since 1.0
*/
public Object getValor(int indice)
{
setUtilizado(true);
return valores.get(indice);
}
/**
* Armazena um valor neste vetor no índice esecificado.
*
* @param indice o índice deste vetor no qual o valor será armazenado.
*
* @param valor o valor que será armazenado neste vetor no índice
* especificado.
*
* @since 1.0
*/
public void setValor(int indice, Object valor)
{
ultimoIndiceModificado = indice;
this.valores.set(indice, valor);
}
public void inicializarComValores(List<Object> valores)
{
this.valores = new ArrayList<>(valores);
}
/**
* {@inheritDoc }
*
* @return uma cópia deste vetor
*/
@Override
public Vetor copiar(String novoNome)
{
Vetor vetor = new Vetor(novoNome, getTipoDado(), getOrigemDoSimbolo());
vetor.valores = new ArrayList<>(this.valores.size());
Collections.copy(vetor.valores, this.valores);
return vetor;
}
public List<Object> obterValores()
{
if (valores != null)
{
return new ArrayList<>(valores);
}
return new ArrayList<>();
}
}
| 412 | 0.55784 | 1 | 0.55784 | game-dev | MEDIA | 0.545264 | game-dev | 0.506028 | 1 | 0.506028 |
OpenVSP/OpenVSP | 7,026 | src/external/GeometricTools/GeometricTools/GTE/Applications/CameraRig.h | // David Eberly, Geometric Tools, Redmond WA 98052
// Copyright (c) 1998-2023
// Distributed under the Boost Software License, Version 1.0.
// https://www.boost.org/LICENSE_1_0.txt
// https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
// Version: 6.0.2022.01.06
#pragma once
#include <Graphics/Camera.h>
#include <Graphics/ConstantBuffer.h>
#include <map>
namespace gte
{
class CameraRig
{
public:
// Construction. The camera rig is designed for moving the camera
// around in a world coordinate system. This object is used in the
// sample 3D applications.
virtual ~CameraRig() = default;
CameraRig();
CameraRig(std::shared_ptr<Camera> const& camera,
float translationSpeed, float rotationSpeed);
// Member access. The functions are for deferred construction after
// a default construction of a camera rig.
void Set(std::shared_ptr<Camera> const& camera,
float translationSpeed, float rotationSpeed);
// TODO: The camera vectors are the world axes? (INVARIANT)
void ComputeWorldAxes();
inline std::shared_ptr<Camera> const& GetCamera() const
{
return mCamera;
}
inline void SetTranslationSpeed(float translationSpeed)
{
mTranslationSpeed = translationSpeed;
}
inline float GetTranslationSpeed() const
{
return mTranslationSpeed;
}
inline void SetRotationSpeed(float rotationSpeed)
{
mRotationSpeed = rotationSpeed;
}
inline float GetRotationSpeed() const
{
return mRotationSpeed;
}
// Control of camera motion. If the camera moves, subscribers to the
// pvw-matrix update will have the system memory and GPU memory of the
// constant buffers updated. Only one motion may be active at a
// single time. When a motion is active, a call to Move() will
// execute that motion.
// The motion is controlled directly by calling SetDirect*().
inline void SetDirectMoveForward()
{
mMotion = &CameraRig::MoveForward;
}
inline void SetDirectMoveBackward()
{
mMotion = &CameraRig::MoveBackward;
}
inline void SetDirectMoveUp()
{
mMotion = &CameraRig::MoveUp;
}
inline void SetDirectMoveDown()
{
mMotion = &CameraRig::MoveDown;
}
inline void SetDirectMoveRight()
{
mMotion = &CameraRig::MoveRight;
}
inline void SetDirectMoveLeft()
{
mMotion = &CameraRig::MoveLeft;
}
inline void SetDirectTurnRight()
{
mMotion = &CameraRig::TurnRight;
}
inline void SetDirectTurnLeft()
{
mMotion = &CameraRig::TurnLeft;
}
inline void SetDirectLookUp()
{
mMotion = &CameraRig::LookUp;
}
inline void SetDirectLookDown()
{
mMotion = &CameraRig::LookDown;
}
inline void SetDirectRollClockwise()
{
mMotion = &CameraRig::RollClockwise;
}
inline void SetDirectRollCounterclockwise()
{
mMotion = &CameraRig::RollCounterclockwise;
}
// The motion is controlled indirectly. TheRegister* calls map the
// 'trigger' to the function specified by the *-suffix. If
// trigger >= 0, the function is added to a map. If trigger < 0 in
// the Register* function, the corresponding function is removed from
// the map. A call to PushMotion(trigger) will set the active motion
// if the trigger is currently mapped; the Boolean return is 'true'
// iff the trigger is mapped. A call to PopMotion(trigger) will
// disable the motion if the trigger is currently mapped; the Boolean
// return it 'true' iff the trigger is currently mapped.
inline void RegisterMoveForward(int32_t trigger)
{
Register(trigger, &CameraRig::MoveForward);
}
inline void RegisterMoveBackward(int32_t trigger)
{
Register(trigger, &CameraRig::MoveBackward);
}
inline void RegisterMoveUp(int32_t trigger)
{
Register(trigger, &CameraRig::MoveUp);
}
inline void RegisterMoveDown(int32_t trigger)
{
Register(trigger, &CameraRig::MoveDown);
}
inline void RegisterMoveRight(int32_t trigger)
{
Register(trigger, &CameraRig::MoveRight);
}
inline void RegisterMoveLeft(int32_t trigger)
{
Register(trigger, &CameraRig::MoveLeft);
}
inline void RegisterTurnRight(int32_t trigger)
{
Register(trigger, &CameraRig::TurnRight);
}
inline void RegisterTurnLeft(int32_t trigger)
{
Register(trigger, &CameraRig::TurnLeft);
}
inline void RegisterLookUp(int32_t trigger)
{
Register(trigger, &CameraRig::LookUp);
}
inline void RegisterLookDown(int32_t trigger)
{
Register(trigger, &CameraRig::LookDown);
}
inline void RegisterRollClockwise(int32_t trigger)
{
Register(trigger, &CameraRig::RollClockwise);
}
inline void RegisterRollCounterclockwise(int32_t trigger)
{
Register(trigger, &CameraRig::RollCounterclockwise);
}
bool PushMotion(int32_t trigger);
bool PopMotion(int32_t trigger);
bool Move();
void ClearMotions();
protected:
// Camera motion. These are called based on the state set in the
// public interface.
enum { MAX_ACTIVE_MOTIONS = 12 };
virtual void MoveForward();
virtual void MoveBackward();
virtual void MoveUp();
virtual void MoveDown();
virtual void MoveRight();
virtual void MoveLeft();
virtual void TurnRight();
virtual void TurnLeft();
virtual void LookUp();
virtual void LookDown();
virtual void RollClockwise();
virtual void RollCounterclockwise();
typedef void(CameraRig::* MoveFunction)(void);
void Register(int32_t trigger, MoveFunction function);
bool SetActive(MoveFunction function);
bool SetInactive(MoveFunction function);
std::shared_ptr<Camera> mCamera;
float mTranslationSpeed, mRotationSpeed;
// Maintain the world coordinate system.
Vector4<float> mWorldAxis[3];
// Move via direct or indirect triggers.
MoveFunction mMotion;
std::map<int32_t, MoveFunction> mIndirectMap;
int32_t mNumActiveMotions;
std::array<MoveFunction, MAX_ACTIVE_MOTIONS> mActiveMotions;
};
}
| 412 | 0.876429 | 1 | 0.876429 | game-dev | MEDIA | 0.721654 | game-dev | 0.823909 | 1 | 0.823909 |
AndreRH/wine | 15,356 | tools/wmc/po.c | /*
* Support for po files
*
* Copyright 2010, 2011 Alexandre Julliard
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*/
#include "config.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <assert.h>
#include <ctype.h>
#ifdef HAVE_GETTEXT_PO_H
#include <gettext-po.h>
#endif
#include "wmc.h"
#include "utils.h"
#include "lang.h"
#include "write.h"
#include "windef.h"
struct mo_file
{
unsigned int magic;
unsigned int revision;
unsigned int count;
unsigned int msgid_off;
unsigned int msgstr_off;
/* ... rest of file data here */
};
static struct lan_blk *new_top, *new_tail;
static BOOL is_english( int lan )
{
return lan == MAKELANGID( LANG_ENGLISH, SUBLANG_DEFAULT );
}
static char *convert_msgid_ascii( const struct lanmsg *msg, int error_on_invalid_char )
{
int i;
char *buffer = xmalloc( msg->len * 4 + 1 );
for (i = 0; i < msg->len; i++)
{
buffer[i] = msg->msg[i];
if (!msg->msg[i]) break;
if (msg->msg[i] >= 32 && msg->msg[i] <= 127) continue;
if (msg->msg[i] == '\t' || msg->msg[i] == '\n') continue;
if (error_on_invalid_char)
{
fprintf( stderr, "%s:%d: ", msg->file, msg->line );
error( "Invalid character %04x in source string\n", msg->msg[i] );
}
free( buffer );
return NULL;
}
buffer[i] = 0;
return buffer;
}
static char *get_message_context( char **msgid )
{
static const char magic[] = "#msgctxt#";
char *id, *context;
if (strncmp( *msgid, magic, sizeof(magic) - 1 )) return NULL;
context = *msgid + sizeof(magic) - 1;
if (!(id = strchr( context, '#' ))) return NULL;
*id = 0;
*msgid = id + 1;
return context;
}
#ifdef HAVE_LIBGETTEXTPO
static po_message_t find_message( po_file_t po, const char *msgid, const char *msgctxt,
po_message_iterator_t *iterator )
{
po_message_t msg;
const char *context;
*iterator = po_message_iterator( po, NULL );
while ((msg = po_next_message( *iterator )))
{
if (strcmp( po_message_msgid( msg ), msgid )) continue;
if (!msgctxt) break;
if (!(context = po_message_msgctxt( msg ))) continue;
if (!strcmp( context, msgctxt )) break;
}
return msg;
}
static void po_xerror( int severity, po_message_t message,
const char *filename, size_t lineno, size_t column,
int multiline_p, const char *message_text )
{
fprintf( stderr, "%s:%u:%u: %s\n",
filename, (unsigned int)lineno, (unsigned int)column, message_text );
if (severity) exit(1);
}
static void po_xerror2( int severity, po_message_t message1,
const char *filename1, size_t lineno1, size_t column1,
int multiline_p1, const char *message_text1,
po_message_t message2,
const char *filename2, size_t lineno2, size_t column2,
int multiline_p2, const char *message_text2 )
{
fprintf( stderr, "%s:%u:%u: %s\n",
filename1, (unsigned int)lineno1, (unsigned int)column1, message_text1 );
fprintf( stderr, "%s:%u:%u: %s\n",
filename2, (unsigned int)lineno2, (unsigned int)column2, message_text2 );
if (severity) exit(1);
}
static const struct po_xerror_handler po_xerror_handler = { po_xerror, po_xerror2 };
static void add_po_string( po_file_t po, const struct lanmsg *msgid, const struct lanmsg *msgstr )
{
po_message_t msg;
po_message_iterator_t iterator;
char *id, *id_buffer, *context, *str = NULL, *str_buffer = NULL;
if (msgid->len <= 1) return;
id_buffer = id = convert_msgid_ascii( msgid, 1 );
context = get_message_context( &id );
if (msgstr)
{
int len;
str_buffer = str = unicode_to_utf8( msgstr->msg, msgstr->len, &len );
if (is_english( msgstr->lan )) get_message_context( &str );
}
if (!(msg = find_message( po, id, context, &iterator )))
{
msg = po_message_create();
po_message_set_msgid( msg, id );
po_message_set_msgstr( msg, str ? str : "" );
if (context) po_message_set_msgctxt( msg, context );
po_message_insert( iterator, msg );
}
if (msgid->file) po_message_add_filepos( msg, msgid->file, msgid->line );
po_message_iterator_free( iterator );
free( id_buffer );
free( str_buffer );
}
static po_file_t create_po_file(void)
{
po_file_t po;
po_message_t msg;
po_message_iterator_t iterator;
po = po_file_create();
iterator = po_message_iterator( po, NULL );
msg = po_message_create();
po_message_set_msgid( msg, "" );
po_message_set_msgstr( msg,
"Project-Id-Version: Wine\n"
"Report-Msgid-Bugs-To: https://bugs.winehq.org\n"
"POT-Creation-Date: N/A\n"
"PO-Revision-Date: N/A\n"
"Last-Translator: Automatically generated\n"
"Language-Team: none\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n" );
po_message_insert( iterator, msg );
po_message_iterator_free( iterator );
return po;
}
void write_pot_file( const char *outname )
{
int i, j;
struct lan_blk *lbp;
po_file_t po = create_po_file();
for (lbp = lanblockhead; lbp; lbp = lbp->next)
{
if (!is_english( lbp->lan )) continue;
for (i = 0; i < lbp->nblk; i++)
{
struct block *blk = &lbp->blks[i];
for (j = 0; j < blk->nmsg; j++) add_po_string( po, blk->msgs[j], NULL );
}
}
po_file_write( po, outname, &po_xerror_handler );
po_file_free( po );
}
#else /* HAVE_LIBGETTEXTPO */
void write_pot_file( const char *outname )
{
error( "PO files not supported in this wmc build\n" );
}
#endif
static struct mo_file *mo_file;
static void byteswap( unsigned int *data, unsigned int count )
{
unsigned int i;
for (i = 0; i < count; i++)
data[i] = data[i] >> 24 | (data[i] >> 8 & 0xff00) | (data[i] << 8 & 0xff0000) | data[i] << 24;
}
static void load_mo_file( const char *name )
{
size_t size;
if (!(mo_file = read_file( name, &size ))) fatal_perror( "Failed to read %s", name );
/* sanity checks */
if (size < sizeof(*mo_file))
error( "%s is not a valid .mo file\n", name );
if (mo_file->magic == 0xde120495)
byteswap( &mo_file->revision, 4 );
else if (mo_file->magic != 0x950412de)
error( "%s is not a valid .mo file\n", name );
if ((mo_file->revision >> 16) > 1)
error( "%s: unsupported file version %x\n", name, mo_file->revision );
if (mo_file->msgid_off >= size ||
mo_file->msgstr_off >= size ||
size < sizeof(*mo_file) + 2 * 8 * mo_file->count)
error( "%s: corrupted file\n", name );
if (mo_file->magic == 0xde120495)
{
byteswap( (unsigned int *)((char *)mo_file + mo_file->msgid_off), 2 * mo_file->count );
byteswap( (unsigned int *)((char *)mo_file + mo_file->msgstr_off), 2 * mo_file->count );
}
}
static void free_mo_file(void)
{
free( mo_file );
mo_file = NULL;
}
static inline const char *get_mo_msgid( int index )
{
const char *base = (const char *)mo_file;
const unsigned int *offsets = (const unsigned int *)(base + mo_file->msgid_off);
return base + offsets[2 * index + 1];
}
static inline const char *get_mo_msgstr( int index )
{
const char *base = (const char *)mo_file;
const unsigned int *offsets = (const unsigned int *)(base + mo_file->msgstr_off);
return base + offsets[2 * index + 1];
}
static const char *get_msgstr( const char *msgid, const char *context, int *found )
{
int pos, res, min, max;
const char *ret = msgid;
char *id = NULL;
if (!mo_file) /* strings containing a context still need to be transformed */
{
if (context) (*found)++;
return ret;
}
if (context) id = strmake( "%s%c%s", context, 4, msgid );
min = 0;
max = mo_file->count - 1;
while (min <= max)
{
pos = (min + max) / 2;
res = strcmp( get_mo_msgid(pos), id ? id : msgid );
if (!res)
{
const char *str = get_mo_msgstr( pos );
if (str[0]) /* ignore empty strings */
{
ret = str;
(*found)++;
}
break;
}
if (res > 0) max = pos - 1;
else min = pos + 1;
}
free( id );
return ret;
}
static struct lanmsg *translate_string( struct lanmsg *str, int lang, int *found )
{
struct lanmsg *new;
const char *transl;
char *buffer, *msgid, *context;
if (str->len <= 1 || !(buffer = convert_msgid_ascii( str, 0 ))) return str;
msgid = buffer;
context = get_message_context( &msgid );
transl = get_msgstr( msgid, context, found );
new = xmalloc( sizeof(*new) );
new->lan = lang;
new->cp = 0; /* FIXME */
new->file = str->file;
new->line = str->line;
new->msg = utf8_to_unicode( transl, strlen(transl) + 1, &new->len );
free( buffer );
return new;
}
static void translate_block( struct block *blk, struct block *new, int lang, int *found )
{
int i;
new->idlo = blk->idlo;
new->idhi = blk->idhi;
new->size = 0;
new->msgs = xmalloc( blk->nmsg * sizeof(*new->msgs) );
new->nmsg = blk->nmsg;
for (i = 0; i < blk->nmsg; i++)
{
new->msgs[i] = translate_string( blk->msgs[i], lang, found );
new->size += ((2 * new->msgs[i]->len + 3) & ~3) + 4;
}
}
static void translate_messages( int lang )
{
int i, found;
struct lan_blk *lbp, *new;
for (lbp = lanblockhead; lbp; lbp = lbp->next)
{
if (!is_english( lbp->lan )) continue;
found = 0;
new = xmalloc( sizeof(*new) );
/* English "translations" take precedence over the original contents */
new->version = is_english( lang ) ? 1 : -1;
new->lan = lang;
new->blks = xmalloc( lbp->nblk * sizeof(*new->blks) );
new->nblk = lbp->nblk;
for (i = 0; i < lbp->nblk; i++)
translate_block( &lbp->blks[i], &new->blks[i], lang, &found );
if (found)
{
if (new_tail) new_tail->next = new;
else new_top = new;
new->prev = new_tail;
new_tail = new;
}
else
{
free( new->blks );
free( new );
}
}
}
/* Unix format is: lang[_country][.charset][@modifier]
* Windows format is: lang[-script][-country][_modifier] */
static int unix_to_win_locale( const char *unix_name, char *win_name )
{
static const char sep[] = "_.@";
const char *extra = NULL;
char buffer[LOCALE_NAME_MAX_LENGTH];
char *p, *country = NULL, *modifier = NULL;
if (strlen( unix_name ) >= LOCALE_NAME_MAX_LENGTH) return FALSE;
strcpy( buffer, unix_name );
if (!(p = strpbrk( buffer, sep )))
{
strcpy( win_name, buffer );
return TRUE;
}
if (*p == '_')
{
*p++ = 0;
country = p;
p = strpbrk( p, sep + 1 );
}
if (p && *p == '.')
{
*p++ = 0;
/* charset, ignore */
p = strchr( p, '@' );
}
if (p)
{
*p++ = 0;
modifier = p;
}
/* rebuild a Windows name */
strcpy( win_name, buffer );
if (modifier)
{
if (!strcmp( modifier, "arabic" )) strcat( win_name, "-Arab" );
else if (!strcmp( modifier, "chakma" )) strcat( win_name, "-Cakm" );
else if (!strcmp( modifier, "cherokee" )) strcat( win_name, "-Cher" );
else if (!strcmp( modifier, "cyrillic" )) strcat( win_name, "-Cyrl" );
else if (!strcmp( modifier, "devanagari" )) strcat( win_name, "-Deva" );
else if (!strcmp( modifier, "gurmukhi" )) strcat( win_name, "-Guru" );
else if (!strcmp( modifier, "javanese" )) strcat( win_name, "-Java" );
else if (!strcmp( modifier, "latin" )) strcat( win_name, "-Latn" );
else if (!strcmp( modifier, "mongolian" )) strcat( win_name, "-Mong" );
else if (!strcmp( modifier, "syriac" )) strcat( win_name, "-Syrc" );
else if (!strcmp( modifier, "tifinagh" )) strcat( win_name, "-Tfng" );
else if (!strcmp( modifier, "tibetan" )) strcat( win_name, "-Tibt" );
else if (!strcmp( modifier, "vai" )) strcat( win_name, "-Vaii" );
else if (!strcmp( modifier, "yi" )) strcat( win_name, "-Yiii" );
else if (!strcmp( modifier, "saaho" )) strcpy( win_name, "ssy" );
else if (!strcmp( modifier, "valencia" )) extra = "-valencia";
/* ignore unknown modifiers */
}
if (country)
{
p = win_name + strlen(win_name);
*p++ = '-';
strcpy( p, country );
}
if (extra) strcat( win_name, extra );
return TRUE;
}
void add_translations( const char *po_dir )
{
struct lan_blk *lbp;
char buffer[256];
char *p, *tok, *name;
FILE *f;
/* first check if we have English resources to translate */
for (lbp = lanblockhead; lbp; lbp = lbp->next) if (is_english( lbp->lan )) break;
if (!lbp) return;
if (!po_dir) /* run through the translation process to remove msg contexts */
{
translate_messages( MAKELANGID( LANG_ENGLISH, SUBLANG_DEFAULT ));
goto done;
}
new_top = new_tail = NULL;
name = strmake( "%s/LINGUAS", po_dir );
if (!(f = fopen( name, "r" ))) return;
free( name );
while (fgets( buffer, sizeof(buffer), f ))
{
if ((p = strchr( buffer, '#' ))) *p = 0;
for (tok = strtok( buffer, " \t\r\n" ); tok; tok = strtok( NULL, " \t\r\n" ))
{
char locale[LOCALE_NAME_MAX_LENGTH];
unsigned int lang;
if (!unix_to_win_locale( tok, locale ) || !(lang = get_language_from_name( locale )))
{
error( "unknown language '%s'\n", tok );
continue;
}
name = strmake( "%s/%s.mo", po_dir, tok );
load_mo_file( name );
translate_messages( lang );
free_mo_file();
free( name );
}
}
fclose( f );
done:
/* prepend the translated messages to the global list */
if (new_tail)
{
new_tail->next = lanblockhead;
lanblockhead->prev = new_tail;
lanblockhead = new_top;
}
}
| 412 | 0.920317 | 1 | 0.920317 | game-dev | MEDIA | 0.272622 | game-dev | 0.911865 | 1 | 0.911865 |
snozbot/fungus | 19,619 | Assets/Fungus/Scripts/Components/SayDialog.cs | // This code is part of the Fungus library (https://github.com/snozbot/fungus)
// It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
using UnityEngine;
using UnityEngine.UI;
using System;
using System.Collections;
using System.Collections.Generic;
namespace Fungus
{
/// <summary>
/// Display story text in a visual novel style dialog box.
/// </summary>
public class SayDialog : MonoBehaviour
{
[Tooltip("Duration to fade dialogue in/out")]
[SerializeField] protected float fadeDuration = 0.25f;
[Tooltip("The continue button UI object")]
[SerializeField] protected Button continueButton;
[Tooltip("The canvas UI object")]
[SerializeField] protected Canvas dialogCanvas;
[Tooltip("The name text UI object")]
[SerializeField] protected Text nameText;
[Tooltip("TextAdapter will search for appropriate output on this GameObject if nameText is null")]
[SerializeField] protected GameObject nameTextGO;
protected TextAdapter nameTextAdapter = new TextAdapter();
public virtual string NameText
{
get
{
return nameTextAdapter.Text;
}
set
{
nameTextAdapter.Text = value;
}
}
[Tooltip("The story text UI object")]
[SerializeField] protected Text storyText;
[Tooltip("TextAdapter will search for appropriate output on this GameObject if storyText is null")]
[SerializeField] protected GameObject storyTextGO;
protected TextAdapter storyTextAdapter = new TextAdapter();
public virtual string StoryText
{
get
{
return storyTextAdapter.Text;
}
set
{
storyTextAdapter.Text = value;
}
}
public virtual RectTransform StoryTextRectTrans
{
get
{
return storyText != null ? storyText.rectTransform : storyTextGO.GetComponent<RectTransform>();
}
}
[Tooltip("The character UI object")]
[SerializeField] protected Image characterImage;
public virtual Image CharacterImage { get { return characterImage; } }
[Tooltip("Adjust width of story text when Character Image is displayed (to avoid overlapping)")]
[SerializeField] protected bool fitTextWithImage = true;
[Tooltip("Close any other open Say Dialogs when this one is active")]
[SerializeField] protected bool closeOtherDialogs;
protected float startStoryTextWidth;
protected float startStoryTextInset;
protected WriterAudio writerAudio;
protected Writer writer;
protected CanvasGroup canvasGroup;
protected bool fadeWhenDone = true;
protected float targetAlpha = 0f;
protected float fadeCoolDownTimer = 0f;
protected Sprite currentCharacterImage;
// Most recent speaking character
protected static Character speakingCharacter;
protected StringSubstituter stringSubstituter = new StringSubstituter();
// Cache active Say Dialogs to avoid expensive scene search
protected static List<SayDialog> activeSayDialogs = new List<SayDialog>();
protected virtual void Awake()
{
if (!activeSayDialogs.Contains(this))
{
activeSayDialogs.Add(this);
}
nameTextAdapter.InitFromGameObject(nameText != null ? nameText.gameObject : nameTextGO);
storyTextAdapter.InitFromGameObject(storyText != null ? storyText.gameObject : storyTextGO);
}
protected virtual void OnDestroy()
{
activeSayDialogs.Remove(this);
}
protected virtual Writer GetWriter()
{
if (writer != null)
{
return writer;
}
writer = GetComponent<Writer>();
if (writer == null)
{
writer = gameObject.AddComponent<Writer>();
}
return writer;
}
protected virtual CanvasGroup GetCanvasGroup()
{
if (canvasGroup != null)
{
return canvasGroup;
}
canvasGroup = GetComponent<CanvasGroup>();
if (canvasGroup == null)
{
canvasGroup = gameObject.AddComponent<CanvasGroup>();
}
return canvasGroup;
}
protected virtual WriterAudio GetWriterAudio()
{
if (writerAudio != null)
{
return writerAudio;
}
writerAudio = GetComponent<WriterAudio>();
if (writerAudio == null)
{
writerAudio = gameObject.AddComponent<WriterAudio>();
}
return writerAudio;
}
protected virtual void Start()
{
// Dialog always starts invisible, will be faded in when writing starts
GetCanvasGroup().alpha = 0f;
// Add a raycaster if none already exists so we can handle dialog input
GraphicRaycaster raycaster = GetComponent<GraphicRaycaster>();
if (raycaster == null)
{
gameObject.AddComponent<GraphicRaycaster>();
}
// It's possible that SetCharacterImage() has already been called from the
// Start method of another component, so check that no image has been set yet.
// Same for nameText.
if (NameText == "")
{
SetCharacterName("", Color.white);
}
if (currentCharacterImage == null)
{
// Character image is hidden by default.
SetCharacterImage(null);
}
}
protected virtual void LateUpdate()
{
UpdateAlpha();
if (continueButton != null)
{
continueButton.gameObject.SetActive( GetWriter().IsWaitingForInput );
}
}
protected virtual void UpdateAlpha()
{
if (GetWriter().IsWriting)
{
targetAlpha = 1f;
fadeCoolDownTimer = 0.1f;
}
else if (fadeWhenDone && Mathf.Approximately(fadeCoolDownTimer, 0f))
{
targetAlpha = 0f;
}
else
{
// Add a short delay before we start fading in case there's another Say command in the next frame or two.
// This avoids a noticeable flicker between consecutive Say commands.
fadeCoolDownTimer = Mathf.Max(0f, fadeCoolDownTimer - Time.deltaTime);
}
CanvasGroup canvasGroup = GetCanvasGroup();
if (fadeDuration <= 0f)
{
canvasGroup.alpha = targetAlpha;
}
else
{
float delta = (1f / fadeDuration) * Time.deltaTime;
float alpha = Mathf.MoveTowards(canvasGroup.alpha, targetAlpha, delta);
canvasGroup.alpha = alpha;
if (alpha <= 0f)
{
// Deactivate dialog object once invisible
gameObject.SetActive(false);
}
}
}
protected virtual void ClearStoryText()
{
StoryText = "";
}
#region Public members
public Character SpeakingCharacter { get { return speakingCharacter; } }
/// <summary>
/// Currently active Say Dialog used to display Say text
/// </summary>
public static SayDialog ActiveSayDialog { get; set; }
/// <summary>
/// Returns a SayDialog by searching for one in the scene or creating one if none exists.
/// </summary>
public static SayDialog GetSayDialog()
{
if (ActiveSayDialog == null)
{
SayDialog sd = null;
// Use first active Say Dialog in the scene (if any)
if (activeSayDialogs.Count > 0)
{
sd = activeSayDialogs[0];
}
if (sd != null)
{
ActiveSayDialog = sd;
}
if (ActiveSayDialog == null)
{
// Auto spawn a say dialog object from the prefab
GameObject prefab = Resources.Load<GameObject>("Prefabs/SayDialog");
if (prefab != null)
{
GameObject go = Instantiate(prefab) as GameObject;
go.SetActive(false);
go.name = "SayDialog";
ActiveSayDialog = go.GetComponent<SayDialog>();
}
}
}
return ActiveSayDialog;
}
/// <summary>
/// Stops all active portrait tweens.
/// </summary>
public static void StopPortraitTweens()
{
// Stop all tweening portraits
var activeCharacters = Character.ActiveCharacters;
for (int i = 0; i < activeCharacters.Count; i++)
{
var c = activeCharacters[i];
if (c.State.portraitImage != null)
{
if (LeanTween.isTweening(c.State.portraitImage.gameObject))
{
LeanTween.cancel(c.State.portraitImage.gameObject, true);
PortraitController.SetRectTransform(c.State.portraitImage.rectTransform, c.State.position);
if (c.State.dimmed == true)
{
c.State.portraitImage.color = new Color(0.5f, 0.5f, 0.5f, 1f);
}
else
{
c.State.portraitImage.color = Color.white;
}
}
}
}
}
/// <summary>
/// Sets the active state of the Say Dialog gameobject.
/// </summary>
public virtual void SetActive(bool state)
{
gameObject.SetActive(state);
}
/// <summary>
/// Sets the active speaking character.
/// </summary>
/// <param name="character">The active speaking character.</param>
public virtual void SetCharacter(Character character)
{
if (character == null)
{
if (characterImage != null)
{
characterImage.gameObject.SetActive(false);
}
if (NameText != null)
{
NameText = "";
}
speakingCharacter = null;
}
else
{
var prevSpeakingCharacter = speakingCharacter;
speakingCharacter = character;
// Dim portraits of non-speaking characters
var activeStages = Stage.ActiveStages;
for (int i = 0; i < activeStages.Count; i++)
{
var stage = activeStages[i];
if (stage.DimPortraits)
{
var charactersOnStage = stage.CharactersOnStage;
for (int j = 0; j < charactersOnStage.Count; j++)
{
var c = charactersOnStage[j];
if (prevSpeakingCharacter != speakingCharacter)
{
if (c != null && !c.Equals(speakingCharacter))
{
stage.SetDimmed(c, true);
}
else
{
stage.SetDimmed(c, false);
}
}
}
}
}
string characterName = character.NameText;
if (characterName == "")
{
// Use game object name as default
characterName = character.GetObjectName();
}
SetCharacterName(characterName, character.NameColor);
}
}
/// <summary>
/// Sets the character image to display on the Say Dialog.
/// </summary>
public virtual void SetCharacterImage(Sprite image)
{
if (characterImage == null)
{
return;
}
if (image != null)
{
characterImage.overrideSprite = image;
characterImage.gameObject.SetActive(true);
currentCharacterImage = image;
}
else
{
characterImage.gameObject.SetActive(false);
if (startStoryTextWidth != 0)
{
StoryTextRectTrans.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Left,
startStoryTextInset,
startStoryTextWidth);
}
}
// Adjust story text box to not overlap image rect
if (fitTextWithImage &&
StoryText != null &&
characterImage.gameObject.activeSelf)
{
if (Mathf.Approximately(startStoryTextWidth, 0f))
{
startStoryTextWidth = StoryTextRectTrans.rect.width;
startStoryTextInset = StoryTextRectTrans.offsetMin.x;
}
// Clamp story text to left or right depending on relative position of the character image
if (StoryTextRectTrans.position.x < characterImage.rectTransform.position.x)
{
StoryTextRectTrans.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Left,
startStoryTextInset,
startStoryTextWidth - characterImage.rectTransform.rect.width);
}
else
{
StoryTextRectTrans.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Right,
startStoryTextInset,
startStoryTextWidth - characterImage.rectTransform.rect.width);
}
}
}
/// <summary>
/// Sets the character name to display on the Say Dialog.
/// Supports variable substitution e.g. John {$surname}
/// </summary>
public virtual void SetCharacterName(string name, Color color)
{
if (NameText != null)
{
var subbedName = stringSubstituter.SubstituteStrings(name);
NameText = subbedName;
nameTextAdapter.SetTextColor(color);
}
}
/// <summary>
/// Write a line of story text to the Say Dialog. Starts coroutine automatically.
/// </summary>
/// <param name="text">The text to display.</param>
/// <param name="clearPrevious">Clear any previous text in the Say Dialog.</param>
/// <param name="waitForInput">Wait for player input before continuing once text is written.</param>
/// <param name="fadeWhenDone">Fade out the Say Dialog when writing and player input has finished.</param>
/// <param name="stopVoiceover">Stop any existing voiceover audio before writing starts.</param>
/// <param name="voiceOverClip">Voice over audio clip to play.</param>
/// <param name="onComplete">Callback to execute when writing and player input have finished.</param>
public virtual void Say(string text, bool clearPrevious, bool waitForInput, bool fadeWhenDone, bool stopVoiceover, bool waitForVO, AudioClip voiceOverClip, Action onComplete)
{
StartCoroutine(DoSay(text, clearPrevious, waitForInput, fadeWhenDone, stopVoiceover, waitForVO, voiceOverClip, onComplete));
}
/// <summary>
/// Write a line of story text to the Say Dialog. Must be started as a coroutine.
/// </summary>
/// <param name="text">The text to display.</param>
/// <param name="clearPrevious">Clear any previous text in the Say Dialog.</param>
/// <param name="waitForInput">Wait for player input before continuing once text is written.</param>
/// <param name="fadeWhenDone">Fade out the Say Dialog when writing and player input has finished.</param>
/// <param name="stopVoiceover">Stop any existing voiceover audio before writing starts.</param>
/// <param name="voiceOverClip">Voice over audio clip to play.</param>
/// <param name="onComplete">Callback to execute when writing and player input have finished.</param>
public virtual IEnumerator DoSay(string text, bool clearPrevious, bool waitForInput, bool fadeWhenDone, bool stopVoiceover, bool waitForVO, AudioClip voiceOverClip, Action onComplete)
{
var writer = GetWriter();
if (writer.IsWriting || writer.IsWaitingForInput)
{
writer.Stop();
while (writer.IsWriting || writer.IsWaitingForInput)
{
yield return null;
}
}
if (closeOtherDialogs)
{
for (int i = 0; i < activeSayDialogs.Count; i++)
{
var sd = activeSayDialogs[i];
if (sd.gameObject != gameObject)
{
sd.SetActive(false);
}
}
}
gameObject.SetActive(true);
this.fadeWhenDone = fadeWhenDone;
// Voice over clip takes precedence over a character sound effect if provided
AudioClip soundEffectClip = null;
if (voiceOverClip != null)
{
WriterAudio writerAudio = GetWriterAudio();
writerAudio.OnVoiceover(voiceOverClip);
}
else if (speakingCharacter != null)
{
soundEffectClip = speakingCharacter.SoundEffect;
}
writer.AttachedWriterAudio = writerAudio;
yield return StartCoroutine(writer.Write(text, clearPrevious, waitForInput, stopVoiceover, waitForVO, soundEffectClip, onComplete));
}
/// <summary>
/// Tell the Say Dialog to fade out once writing and player input have finished.
/// </summary>
public virtual bool FadeWhenDone { get {return fadeWhenDone; } set { fadeWhenDone = value; } }
/// <summary>
/// Stop the Say Dialog while its writing text.
/// </summary>
public virtual void Stop()
{
fadeWhenDone = true;
GetWriter().Stop();
}
/// <summary>
/// Stops writing text and clears the Say Dialog.
/// </summary>
public virtual void Clear()
{
ClearStoryText();
// Kill any active write coroutine
StopAllCoroutines();
}
#endregion
}
}
| 412 | 0.938513 | 1 | 0.938513 | game-dev | MEDIA | 0.960415 | game-dev | 0.994838 | 1 | 0.994838 |
ryzom/ryzomcore | 2,683 | ryzom/common/src/game_share/item_family.h | // Ryzom - MMORPG Framework <http://dev.ryzom.com/projects/ryzom/>
// Copyright (C) 2010 Winch Gate Property Limited
//
// This source file has been modified by the following contributors:
// Copyright (C) 2020 Jan BOON (Kaetemi) <jan.boon@kaetemi.be>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#ifndef RY_ITEM_FAMILY_H
#define RY_ITEM_FAMILY_H
#include "nel/misc/types_nl.h"
namespace ITEMFAMILY
{
// Mode
enum EItemFamily
#ifdef NL_CPP14
: uint8
#endif
{
UNDEFINED = 0,
SERVICE,
ARMOR,
MELEE_WEAPON,
RANGE_WEAPON,
AMMO,
RAW_MATERIAL,
SHIELD,
CRAFTING_TOOL,
HARVEST_TOOL,
TAMING_TOOL,
TRAINING_TOOL,
AI,
BRICK,
FOOD,
JEWELRY,
CORPSE,
CARRION,
BAG,
STACK,
DEAD_SEED,
TELEPORT,
GUILD_FLAG,
LIVING_SEED,
LITTLE_SEED,
MEDIUM_SEED,
BIG_SEED,
VERY_BIG_SEED,
MISSION_ITEM,
CRYSTALLIZED_SPELL,
ITEM_SAP_RECHARGE,
PET_ANIMAL_TICKET,
GUILD_OPTION,
HANDLED_ITEM,
COSMETIC,
CONSUMABLE,
XP_CATALYSER,
SCROLL,
SCROLL_R2,
COMMAND_TICKET,
GENERIC_ITEM
};
/**
* get the right item family from the input string
* \param str the input string
* \return the EItemFamily associated to this string (UNDEFINED if the string cannot be interpreted)
*/
EItemFamily stringToItemFamily( const std::string& str );
/**
* return the item family as a string
* \param itemFamily family to transform into a string
* \return the item family as a string
*/
const std::string& toString( EItemFamily itemFamily );
/**
* returns true if items of this family are destroyed when they are completely worned out
*/
bool destroyedWhenWorned(EItemFamily family);
/// return true if this family of item can be sold to a bot
bool isSellableByPlayer( EItemFamily fam );
/// return true if this family of item can be resold to players
bool isResellable( EItemFamily fam );
/// return true if this family of item can display a custom text
bool isTextCustomizable( EItemFamily fam );
/// is craftable
}; // ITEMFAMILY
#endif // RY_ITEM_FAMILY_H
/* End of item_family.h */
| 412 | 0.837689 | 1 | 0.837689 | game-dev | MEDIA | 0.931154 | game-dev | 0.740829 | 1 | 0.740829 |
mcgill-robotics/Humanoid-MuJoCo | 24,234 | simulation/mujoco/include/mujoco/mjdata.h | // Copyright 2021 DeepMind Technologies Limited
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef MUJOCO_MJDATA_H_
#define MUJOCO_MJDATA_H_
#include <stddef.h>
#include <stdint.h>
#include <mujoco/mjtnum.h>
#include <mujoco/mjmodel.h>
#include <mujoco/mjthread.h>
//---------------------------------- primitive types (mjt) -----------------------------------------
typedef enum mjtState_ { // state elements
mjSTATE_TIME = 1<<0, // time
mjSTATE_QPOS = 1<<1, // position
mjSTATE_QVEL = 1<<2, // velocity
mjSTATE_ACT = 1<<3, // actuator activation
mjSTATE_WARMSTART = 1<<4, // acceleration used for warmstart
mjSTATE_CTRL = 1<<5, // control
mjSTATE_QFRC_APPLIED = 1<<6, // applied generalized force
mjSTATE_XFRC_APPLIED = 1<<7, // applied Cartesian force/torque
mjSTATE_EQ_ACTIVE = 1<<8, // enable/disable constraints
mjSTATE_MOCAP_POS = 1<<9, // positions of mocap bodies
mjSTATE_MOCAP_QUAT = 1<<10, // orientations of mocap bodies
mjSTATE_USERDATA = 1<<11, // user data
mjSTATE_PLUGIN = 1<<12, // plugin state
mjNSTATE = 13, // number of state elements
// convenience values for commonly used state specifications
mjSTATE_PHYSICS = mjSTATE_QPOS | mjSTATE_QVEL | mjSTATE_ACT,
mjSTATE_FULLPHYSICS = mjSTATE_PHYSICS | mjSTATE_TIME | mjSTATE_PLUGIN,
mjSTATE_USER = mjSTATE_CTRL | mjSTATE_QFRC_APPLIED | mjSTATE_XFRC_APPLIED |
mjSTATE_EQ_ACTIVE | mjSTATE_MOCAP_POS | mjSTATE_MOCAP_QUAT |
mjSTATE_USERDATA,
mjSTATE_INTEGRATION = mjSTATE_FULLPHYSICS | mjSTATE_USER | mjSTATE_WARMSTART
} mjtState;
typedef enum mjtWarning_ { // warning types
mjWARN_INERTIA = 0, // (near) singular inertia matrix
mjWARN_CONTACTFULL, // too many contacts in contact list
mjWARN_CNSTRFULL, // too many constraints
mjWARN_VGEOMFULL, // too many visual geoms
mjWARN_BADQPOS, // bad number in qpos
mjWARN_BADQVEL, // bad number in qvel
mjWARN_BADQACC, // bad number in qacc
mjWARN_BADCTRL, // bad number in ctrl
mjNWARNING // number of warnings
} mjtWarning;
typedef enum mjtTimer_ { // internal timers
// main api
mjTIMER_STEP = 0, // step
mjTIMER_FORWARD, // forward
mjTIMER_INVERSE, // inverse
// breakdown of step/forward
mjTIMER_POSITION, // fwdPosition
mjTIMER_VELOCITY, // fwdVelocity
mjTIMER_ACTUATION, // fwdActuation
mjTIMER_CONSTRAINT, // fwdConstraint
mjTIMER_ADVANCE, // mj_Euler, mj_implicit
// breakdown of fwdPosition
mjTIMER_POS_KINEMATICS, // kinematics, com, tendon, transmission
mjTIMER_POS_INERTIA, // inertia computations
mjTIMER_POS_COLLISION, // collision detection
mjTIMER_POS_MAKE, // make constraints
mjTIMER_POS_PROJECT, // project constraints
// breakdown of mj_collision
mjTIMER_COL_BROAD, // broadphase
mjTIMER_COL_MID, // midphase
mjTIMER_COL_NARROW, // narrowphase
mjNTIMER // number of timers
} mjtTimer;
//---------------------------------- mjContact -----------------------------------------------------
struct mjContact_ { // result of collision detection functions
// contact parameters set by near-phase collision function
mjtNum dist; // distance between nearest points; neg: penetration
mjtNum pos[3]; // position of contact point: midpoint between geoms
mjtNum frame[9]; // normal is in [0-2], points from geom[0] to geom[1]
// contact parameters set by mj_collideGeoms
mjtNum includemargin; // include if dist<includemargin=margin-gap
mjtNum friction[5]; // tangent1, 2, spin, roll1, 2
mjtNum solref[mjNREF]; // constraint solver reference, normal direction
mjtNum solreffriction[mjNREF]; // constraint solver reference, friction directions
mjtNum solimp[mjNIMP]; // constraint solver impedance
// internal storage used by solver
mjtNum mu; // friction of regularized cone, set by mj_makeConstraint
mjtNum H[36]; // cone Hessian, set by mj_updateConstraint
// contact descriptors set by mj_collideXXX
int dim; // contact space dimensionality: 1, 3, 4 or 6
int geom1; // id of geom 1; deprecated, use geom[0]
int geom2; // id of geom 2; deprecated, use geom[1]
int geom[2]; // geom ids; -1 for flex
int flex[2]; // flex ids; -1 for geom
int elem[2]; // element ids; -1 for geom or flex vertex
int vert[2]; // vertex ids; -1 for geom or flex element
// flag set by mj_setContact or mj_instantiateContact
int exclude; // 0: include, 1: in gap, 2: fused, 3: no dofs
// address computed by mj_instantiateContact
int efc_address; // address in efc; -1: not included
};
typedef struct mjContact_ mjContact;
//---------------------------------- diagnostics ---------------------------------------------------
struct mjWarningStat_ { // warning statistics
int lastinfo; // info from last warning
int number; // how many times was warning raised
};
typedef struct mjWarningStat_ mjWarningStat;
struct mjTimerStat_ { // timer statistics
mjtNum duration; // cumulative duration
int number; // how many times was timer called
};
typedef struct mjTimerStat_ mjTimerStat;
struct mjSolverStat_ { // per-iteration solver statistics
mjtNum improvement; // cost reduction, scaled by 1/trace(M(qpos0))
mjtNum gradient; // gradient norm (primal only, scaled)
mjtNum lineslope; // slope in linesearch
int nactive; // number of active constraints
int nchange; // number of constraint state changes
int neval; // number of cost evaluations in line search
int nupdate; // number of Cholesky updates in line search
};
typedef struct mjSolverStat_ mjSolverStat;
//---------------------------------- mjData --------------------------------------------------------
struct mjData_ {
// constant sizes
size_t narena; // size of the arena in bytes (inclusive of the stack)
size_t nbuffer; // size of main buffer in bytes
int nplugin; // number of plugin instances
// stack pointer
size_t pstack; // first available mjtNum address in stack
size_t pbase; // value of pstack when mj_markStack was last called
// arena pointer
size_t parena; // first available byte in arena
// memory utilization stats
size_t maxuse_stack; // maximum stack allocation in bytes
size_t maxuse_threadstack[mjMAXTHREADS]; // maximum stack allocation per thread in bytes
size_t maxuse_arena; // maximum arena allocation in bytes
int maxuse_con; // maximum number of contacts
int maxuse_efc; // maximum number of scalar constraints
// diagnostics
mjWarningStat warning[mjNWARNING]; // warning statistics
mjTimerStat timer[mjNTIMER]; // timer statistics
// solver statistics
mjSolverStat solver[mjNISLAND*mjNSOLVER]; // solver statistics per island, per iteration
int solver_nisland; // number of islands processed by solver
int solver_niter[mjNISLAND]; // number of solver iterations, per island
int solver_nnz[mjNISLAND]; // number of non-zeros in Hessian or efc_AR, per island
mjtNum solver_fwdinv[2]; // forward-inverse comparison: qfrc, efc
// variable sizes
int ne; // number of equality constraints
int nf; // number of friction constraints
int nl; // number of limit constraints
int nefc; // number of constraints
int nnzJ; // number of non-zeros in constraint Jacobian
int ncon; // number of detected contacts
int nisland; // number of detected constraint islands
// global properties
mjtNum time; // simulation time
mjtNum energy[2]; // potential, kinetic energy
//-------------------- end of info header
// buffers
void* buffer; // main buffer; all pointers point in it (nbuffer bytes)
void* arena; // arena+stack buffer (nstack*sizeof(mjtNum) bytes)
//-------------------- main inputs and outputs of the computation
// state
mjtNum* qpos; // position (nq x 1)
mjtNum* qvel; // velocity (nv x 1)
mjtNum* act; // actuator activation (na x 1)
mjtNum* qacc_warmstart; // acceleration used for warmstart (nv x 1)
mjtNum* plugin_state; // plugin state (npluginstate x 1)
// control
mjtNum* ctrl; // control (nu x 1)
mjtNum* qfrc_applied; // applied generalized force (nv x 1)
mjtNum* xfrc_applied; // applied Cartesian force/torque (nbody x 6)
mjtByte* eq_active; // enable/disable constraints (neq x 1)
// mocap data
mjtNum* mocap_pos; // positions of mocap bodies (nmocap x 3)
mjtNum* mocap_quat; // orientations of mocap bodies (nmocap x 4)
// dynamics
mjtNum* qacc; // acceleration (nv x 1)
mjtNum* act_dot; // time-derivative of actuator activation (na x 1)
// user data
mjtNum* userdata; // user data, not touched by engine (nuserdata x 1)
// sensors
mjtNum* sensordata; // sensor data array (nsensordata x 1)
// plugins
int* plugin; // copy of m->plugin, required for deletion (nplugin x 1)
uintptr_t* plugin_data; // pointer to plugin-managed data structure (nplugin x 1)
//-------------------- POSITION dependent
// computed by mj_fwdPosition/mj_kinematics
mjtNum* xpos; // Cartesian position of body frame (nbody x 3)
mjtNum* xquat; // Cartesian orientation of body frame (nbody x 4)
mjtNum* xmat; // Cartesian orientation of body frame (nbody x 9)
mjtNum* xipos; // Cartesian position of body com (nbody x 3)
mjtNum* ximat; // Cartesian orientation of body inertia (nbody x 9)
mjtNum* xanchor; // Cartesian position of joint anchor (njnt x 3)
mjtNum* xaxis; // Cartesian joint axis (njnt x 3)
mjtNum* geom_xpos; // Cartesian geom position (ngeom x 3)
mjtNum* geom_xmat; // Cartesian geom orientation (ngeom x 9)
mjtNum* site_xpos; // Cartesian site position (nsite x 3)
mjtNum* site_xmat; // Cartesian site orientation (nsite x 9)
mjtNum* cam_xpos; // Cartesian camera position (ncam x 3)
mjtNum* cam_xmat; // Cartesian camera orientation (ncam x 9)
mjtNum* light_xpos; // Cartesian light position (nlight x 3)
mjtNum* light_xdir; // Cartesian light direction (nlight x 3)
// computed by mj_fwdPosition/mj_comPos
mjtNum* subtree_com; // center of mass of each subtree (nbody x 3)
mjtNum* cdof; // com-based motion axis of each dof (rot:lin) (nv x 6)
mjtNum* cinert; // com-based body inertia and mass (nbody x 10)
// computed by mj_fwdPosition/mj_flex
mjtNum* flexvert_xpos; // Cartesian flex vertex positions (nflexvert x 3)
mjtNum* flexelem_aabb; // flex element bounding boxes (center, size) (nflexelem x 6)
int* flexedge_J_rownnz; // number of non-zeros in Jacobian row (nflexedge x 1)
int* flexedge_J_rowadr; // row start address in colind array (nflexedge x 1)
int* flexedge_J_colind; // column indices in sparse Jacobian (nflexedge x nv)
mjtNum* flexedge_J; // flex edge Jacobian (nflexedge x nv)
mjtNum* flexedge_length; // flex edge lengths (nflexedge x 1)
// computed by mj_fwdPosition/mj_tendon
int* ten_wrapadr; // start address of tendon's path (ntendon x 1)
int* ten_wrapnum; // number of wrap points in path (ntendon x 1)
int* ten_J_rownnz; // number of non-zeros in Jacobian row (ntendon x 1)
int* ten_J_rowadr; // row start address in colind array (ntendon x 1)
int* ten_J_colind; // column indices in sparse Jacobian (ntendon x nv)
mjtNum* ten_J; // tendon Jacobian (ntendon x nv)
mjtNum* ten_length; // tendon lengths (ntendon x 1)
int* wrap_obj; // geom id; -1: site; -2: pulley (nwrap*2 x 1)
mjtNum* wrap_xpos; // Cartesian 3D points in all path (nwrap*2 x 3)
// computed by mj_fwdPosition/mj_transmission
mjtNum* actuator_length; // actuator lengths (nu x 1)
mjtNum* actuator_moment; // actuator moments (nu x nv)
// computed by mj_fwdPosition/mj_crb
mjtNum* crb; // com-based composite inertia and mass (nbody x 10)
mjtNum* qM; // total inertia (sparse) (nM x 1)
// computed by mj_fwdPosition/mj_factorM
mjtNum* qLD; // L'*D*L factorization of M (sparse) (nM x 1)
mjtNum* qLDiagInv; // 1/diag(D) (nv x 1)
mjtNum* qLDiagSqrtInv; // 1/sqrt(diag(D)) (nv x 1)
// computed by mj_collisionTree
mjtNum* bvh_aabb_dyn; // global bounding box (center, size) (nbvhdynamic x 6)
mjtByte* bvh_active; // volume has been added to collisions (nbvh x 1)
//-------------------- POSITION, VELOCITY dependent
// computed by mj_fwdVelocity
mjtNum* flexedge_velocity; // flex edge velocities (nflexedge x 1)
mjtNum* ten_velocity; // tendon velocities (ntendon x 1)
mjtNum* actuator_velocity; // actuator velocities (nu x 1)
// computed by mj_fwdVelocity/mj_comVel
mjtNum* cvel; // com-based velocity (rot:lin) (nbody x 6)
mjtNum* cdof_dot; // time-derivative of cdof (rot:lin) (nv x 6)
// computed by mj_fwdVelocity/mj_rne (without acceleration)
mjtNum* qfrc_bias; // C(qpos,qvel) (nv x 1)
// computed by mj_fwdVelocity/mj_passive
mjtNum* qfrc_spring; // passive spring force (nv x 1)
mjtNum* qfrc_damper; // passive damper force (nv x 1)
mjtNum* qfrc_gravcomp; // passive gravity compensation force (nv x 1)
mjtNum* qfrc_fluid; // passive fluid force (nv x 1)
mjtNum* qfrc_passive; // total passive force (nv x 1)
// computed by mj_sensorVel/mj_subtreeVel if needed
mjtNum* subtree_linvel; // linear velocity of subtree com (nbody x 3)
mjtNum* subtree_angmom; // angular momentum about subtree com (nbody x 3)
// computed by mj_Euler or mj_implicit
mjtNum* qH; // L'*D*L factorization of modified M (nM x 1)
mjtNum* qHDiagInv; // 1/diag(D) of modified M (nv x 1)
// computed by mj_resetData
int* D_rownnz; // non-zeros in each row (nv x 1)
int* D_rowadr; // address of each row in D_colind (nv x 1)
int* D_colind; // column indices of non-zeros (nD x 1)
int* B_rownnz; // non-zeros in each row (nbody x 1)
int* B_rowadr; // address of each row in B_colind (nbody x 1)
int* B_colind; // column indices of non-zeros (nB x 1)
// computed by mj_implicit/mj_derivative
mjtNum* qDeriv; // d (passive + actuator - bias) / d qvel (nD x 1)
// computed by mj_implicit/mju_factorLUSparse
mjtNum* qLU; // sparse LU of (qM - dt*qDeriv) (nD x 1)
//-------------------- POSITION, VELOCITY, CONTROL/ACCELERATION dependent
// computed by mj_fwdActuation
mjtNum* actuator_force; // actuator force in actuation space (nu x 1)
mjtNum* qfrc_actuator; // actuator force (nv x 1)
// computed by mj_fwdAcceleration
mjtNum* qfrc_smooth; // net unconstrained force (nv x 1)
mjtNum* qacc_smooth; // unconstrained acceleration (nv x 1)
// computed by mj_fwdConstraint/mj_inverse
mjtNum* qfrc_constraint; // constraint force (nv x 1)
// computed by mj_inverse
mjtNum* qfrc_inverse; // net external force; should equal: (nv x 1)
// qfrc_applied + J'*xfrc_applied + qfrc_actuator
// computed by mj_sensorAcc/mj_rnePostConstraint if needed; rotation:translation format
mjtNum* cacc; // com-based acceleration (nbody x 6)
mjtNum* cfrc_int; // com-based interaction force with parent (nbody x 6)
mjtNum* cfrc_ext; // com-based external force on body (nbody x 6)
//-------------------- arena-allocated: POSITION dependent
// computed by mj_collision
mjContact* contact; // list of all detected contacts (ncon x 1)
// computed by mj_makeConstraint
int* efc_type; // constraint type (mjtConstraint) (nefc x 1)
int* efc_id; // id of object of specified type (nefc x 1)
int* efc_J_rownnz; // number of non-zeros in constraint Jacobian row (nefc x 1)
int* efc_J_rowadr; // row start address in colind array (nefc x 1)
int* efc_J_rowsuper; // number of subsequent rows in supernode (nefc x 1)
int* efc_J_colind; // column indices in constraint Jacobian (nnzJ x 1)
int* efc_JT_rownnz; // number of non-zeros in constraint Jacobian row T (nv x 1)
int* efc_JT_rowadr; // row start address in colind array T (nv x 1)
int* efc_JT_rowsuper; // number of subsequent rows in supernode T (nv x 1)
int* efc_JT_colind; // column indices in constraint Jacobian T (nnzJ x 1)
mjtNum* efc_J; // constraint Jacobian (nnzJ x 1)
mjtNum* efc_JT; // constraint Jacobian transposed (nnzJ x 1)
mjtNum* efc_pos; // constraint position (equality, contact) (nefc x 1)
mjtNum* efc_margin; // inclusion margin (contact) (nefc x 1)
mjtNum* efc_frictionloss; // frictionloss (friction) (nefc x 1)
mjtNum* efc_diagApprox; // approximation to diagonal of A (nefc x 1)
mjtNum* efc_KBIP; // stiffness, damping, impedance, imp' (nefc x 4)
mjtNum* efc_D; // constraint mass (nefc x 1)
mjtNum* efc_R; // inverse constraint mass (nefc x 1)
int* tendon_efcadr; // first efc address involving tendon; -1: none (ntendon x 1)
// computed by mj_island
int* dof_island; // island id of this dof; -1: none (nv x 1)
int* island_dofnum; // number of dofs in island (nisland x 1)
int* island_dofadr; // start address in island_dofind (nisland x 1)
int* island_dofind; // island dof indices; -1: none (nv x 1)
int* dof_islandind; // dof island indices; -1: none (nv x 1)
int* efc_island; // island id of this constraint (nefc x 1)
int* island_efcnum; // number of constraints in island (nisland x 1)
int* island_efcadr; // start address in island_efcind (nisland x 1)
int* island_efcind; // island constraint indices (nefc x 1)
// computed by mj_projectConstraint (dual solver)
int* efc_AR_rownnz; // number of non-zeros in AR (nefc x 1)
int* efc_AR_rowadr; // row start address in colind array (nefc x 1)
int* efc_AR_colind; // column indices in sparse AR (nefc x nefc)
mjtNum* efc_AR; // J*inv(M)*J' + R (nefc x nefc)
//-------------------- arena-allocated: POSITION, VELOCITY dependent
// computed by mj_fwdVelocity/mj_referenceConstraint
mjtNum* efc_vel; // velocity in constraint space: J*qvel (nefc x 1)
mjtNum* efc_aref; // reference pseudo-acceleration (nefc x 1)
//-------------------- arena-allocated: POSITION, VELOCITY, CONTROL/ACCELERATION dependent
// computed by mj_fwdConstraint/mj_inverse
mjtNum* efc_b; // linear cost term: J*qacc_smooth - aref (nefc x 1)
mjtNum* efc_force; // constraint force in constraint space (nefc x 1)
int* efc_state; // constraint state (mjtConstraintState) (nefc x 1)
// ThreadPool for multithreaded operations
uintptr_t threadpool;
};
typedef struct mjData_ mjData;
//---------------------------------- callback function types ---------------------------------------
// generic MuJoCo function
typedef void (*mjfGeneric)(const mjModel* m, mjData* d);
// contact filter: 1- discard, 0- collide
typedef int (*mjfConFilt)(const mjModel* m, mjData* d, int geom1, int geom2);
// sensor simulation
typedef void (*mjfSensor)(const mjModel* m, mjData* d, int stage);
// timer
typedef mjtNum (*mjfTime)(void);
// actuator dynamics, gain, bias
typedef mjtNum (*mjfAct)(const mjModel* m, const mjData* d, int id);
// collision detection
typedef int (*mjfCollision)(const mjModel* m, const mjData* d,
mjContact* con, int g1, int g2, mjtNum margin);
#endif // MUJOCO_MJDATA_H_
| 412 | 0.837192 | 1 | 0.837192 | game-dev | MEDIA | 0.79534 | game-dev | 0.892396 | 1 | 0.892396 |
meng-tang/rloss | 2,933 | deeplab/src/caffe/util/signal_handler.cpp | #include <boost/bind.hpp>
#include <glog/logging.h>
#include <signal.h>
#include <csignal>
#include "caffe/util/signal_handler.h"
namespace {
static volatile sig_atomic_t got_sigint = false;
static volatile sig_atomic_t got_sighup = false;
static bool already_hooked_up = false;
void handle_signal(int signal) {
switch (signal) {
case SIGHUP:
got_sighup = true;
break;
case SIGINT:
got_sigint = true;
break;
}
}
void HookupHandler() {
if (already_hooked_up) {
LOG(FATAL) << "Tried to hookup signal handlers more than once.";
}
already_hooked_up = true;
struct sigaction sa;
// Setup the handler
sa.sa_handler = &handle_signal;
// Restart the system call, if at all possible
sa.sa_flags = SA_RESTART;
// Block every signal during the handler
sigfillset(&sa.sa_mask);
// Intercept SIGHUP and SIGINT
if (sigaction(SIGHUP, &sa, NULL) == -1) {
LOG(FATAL) << "Cannot install SIGHUP handler.";
}
if (sigaction(SIGINT, &sa, NULL) == -1) {
LOG(FATAL) << "Cannot install SIGINT handler.";
}
}
// Set the signal handlers to the default.
void UnhookHandler() {
if (already_hooked_up) {
struct sigaction sa;
// Setup the sighub handler
sa.sa_handler = SIG_DFL;
// Restart the system call, if at all possible
sa.sa_flags = SA_RESTART;
// Block every signal during the handler
sigfillset(&sa.sa_mask);
// Intercept SIGHUP and SIGINT
if (sigaction(SIGHUP, &sa, NULL) == -1) {
LOG(FATAL) << "Cannot uninstall SIGHUP handler.";
}
if (sigaction(SIGINT, &sa, NULL) == -1) {
LOG(FATAL) << "Cannot uninstall SIGINT handler.";
}
already_hooked_up = false;
}
}
// Return true iff a SIGINT has been received since the last time this
// function was called.
bool GotSIGINT() {
bool result = got_sigint;
got_sigint = false;
return result;
}
// Return true iff a SIGHUP has been received since the last time this
// function was called.
bool GotSIGHUP() {
bool result = got_sighup;
got_sighup = false;
return result;
}
} // namespace
namespace caffe {
SignalHandler::SignalHandler(SolverAction::Enum SIGINT_action,
SolverAction::Enum SIGHUP_action):
SIGINT_action_(SIGINT_action),
SIGHUP_action_(SIGHUP_action) {
HookupHandler();
}
SignalHandler::~SignalHandler() {
UnhookHandler();
}
SolverAction::Enum SignalHandler::CheckForSignals() const {
if (GotSIGHUP()) {
return SIGHUP_action_;
}
if (GotSIGINT()) {
return SIGINT_action_;
}
return SolverAction::NONE;
}
// Return the function that the solver can use to find out if a snapshot or
// early exit is being requested.
ActionCallback SignalHandler::GetActionFunction() {
return boost::bind(&SignalHandler::CheckForSignals, this);
}
} // namespace caffe
| 412 | 0.734414 | 1 | 0.734414 | game-dev | MEDIA | 0.263045 | game-dev | 0.65292 | 1 | 0.65292 |
ReaTeam/ReaScripts | 3,868 | Various/timtam_IntelliFreeze/timtam_IntelliFreeze.lua | -- @noindex
-- module requirements for all actions
-- doesn't provide any action by itself, so don't map any shortcut to it or run this action
-- fixing script path for correct require calls
local path = ({reaper.get_action_context()})[2]:match('^.+[\\//]')
package.path = path .. "?.lua"
-- constants
local activeProjectIndex = 0
local function print(message)
reaper.ShowConsoleMsg("IntelliFreeze: "..tostring(message).."\n")
end
local function speak(text)
if reaper.osara_outputMessage ~= nil then
reaper.osara_outputMessage(text)
end
end
-- we retrieve all selected tracks recursively
-- all folders get resolved if param tracks is nil
-- recursiveness can be disabled too
local function getSelectedTracks(tracks, recursive)
recursive = recursive or false
if tracks == nil or tracks == {} then
if reaper.CountSelectedTracks(activeProjectIndex) == 0 then
return {}
end
tracks = {}
local i
for i = 0, reaper.CountSelectedTracks(activeProjectIndex) - 1 do
table.insert(tracks, reaper.GetSelectedTrack(activeProjectIndex, i))
end
end
if recursive == true then
for _, track in ipairs(tracks) do
local is_folder = reaper.GetMediaTrackInfo_Value(track, "I_FOLDERDEPTH")
if is_folder == 1 then
-- the track is a folder
-- in order to find the children tracks, we need to iterate over all existing tracks
-- and check if the track is the child of this track
local i
local sub_tracks = {}
for i = 0, reaper.CountTracks(activeProjectIndex) - 1 do
local sub_track = reaper.GetTrack(activeProjectIndex, i)
if sub_track ~= track and reaper.GetParentTrack(sub_track) == track then
table.insert(sub_tracks, sub_track)
end
end
if #sub_tracks > 0 then
sub_tracks = getSelectedTracks(sub_tracks, true)
for i = 1, #tracks do
table.insert(sub_tracks, tracks[i])
end
tracks = sub_tracks
end
end
end
end
return tracks
end
-- we consider a track with FX freezeable
local function getTrackRequiresFreezing(track)
local fxCount = reaper.TrackFX_GetCount(track)
return fxCount > 0
end
-- copied from https://stackoverflow.com/questions/49709998/how-to-filter-a-lua-array-inplace
local function filterArrayInplace(arr, func)
local new_index = 1
local size_orig = #arr
for old_index, v in ipairs(arr) do
if func(v, old_index) then
arr[new_index] = v
new_index = new_index + 1
end
end
for i = new_index, size_orig do arr[i] = nil end
end
-- modes
-- mode 0 = mono
-- mode 1 = stereo
-- mode 2 = multi-channel
-- mode 3 = unfreeze
local function freezeTracks(tracks, mode)
mode = mode or 0
-- save currently selected tracks first
local _, track
local selected_tracks = getSelectedTracks()
-- unselect those
for _, track in ipairs(selected_tracks) do
reaper.SetTrackSelected(track, false)
end
-- and select the tracks to be frozen
for _, track in ipairs(tracks) do
reaper.SetTrackSelected(track, true)
end
-- run the freeze command
local command_id
if mode == 0 then
command_id = 40901
elseif mode == 1 then
command_id = 41223
elseif mode == 2 then
command_id = 40877
else
command_id = 41644
end
reaper.Main_OnCommand(command_id, 0)
-- unselect and select the correct tracks again
for _, track in ipairs(tracks) do
reaper.SetTrackSelected(track, false)
end
for _, track in ipairs(selected_tracks) do
reaper.SetTrackSelected(track, true)
end
end
return {
filterArrayInplace = filterArrayInplace,
freezeTracks = freezeTracks,
getSelectedTracks = getSelectedTracks,
getTrackRequiresFreezing = getTrackRequiresFreezing,
print = print,
speak = speak
}
| 412 | 0.92223 | 1 | 0.92223 | game-dev | MEDIA | 0.343394 | game-dev | 0.928841 | 1 | 0.928841 |
dhewm/dhewm3 | 35,859 | neo/d3xp/physics/Physics_Parametric.cpp | /*
===========================================================================
Doom 3 GPL Source Code
Copyright (C) 1999-2011 id Software LLC, a ZeniMax Media company.
This file is part of the Doom 3 GPL Source Code ("Doom 3 Source Code").
Doom 3 Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Doom 3 Source Code is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Doom 3 Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Doom 3 Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 Source Code. If not, please request a copy in writing from id Software at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
#include "sys/platform.h"
#include "Entity.h"
#include "physics/Physics_Parametric.h"
CLASS_DECLARATION( idPhysics_Base, idPhysics_Parametric )
END_CLASS
/*
================
idPhysics_Parametric::Activate
================
*/
void idPhysics_Parametric::Activate( void ) {
current.atRest = -1;
self->BecomeActive( TH_PHYSICS );
}
/*
================
idPhysics_Parametric::TestIfAtRest
================
*/
bool idPhysics_Parametric::TestIfAtRest( void ) const {
if ( ( current.linearExtrapolation.GetExtrapolationType() & ~EXTRAPOLATION_NOSTOP ) == EXTRAPOLATION_NONE &&
( current.angularExtrapolation.GetExtrapolationType() & ~EXTRAPOLATION_NOSTOP ) == EXTRAPOLATION_NONE &&
current.linearInterpolation.GetDuration() == 0 &&
current.angularInterpolation.GetDuration() == 0 &&
current.spline == NULL ) {
return true;
}
if ( !current.linearExtrapolation.IsDone( current.time ) ) {
return false;
}
if ( !current.angularExtrapolation.IsDone( current.time ) ) {
return false;
}
if ( !current.linearInterpolation.IsDone( current.time ) ) {
return false;
}
if ( !current.angularInterpolation.IsDone( current.time ) ) {
return false;
}
if ( current.spline != NULL && !current.spline->IsDone( current.time ) ) {
return false;
}
return true;
}
/*
================
idPhysics_Parametric::Rest
================
*/
void idPhysics_Parametric::Rest( void ) {
current.atRest = gameLocal.time;
self->BecomeInactive( TH_PHYSICS );
}
/*
================
idPhysics_Parametric::idPhysics_Parametric
================
*/
idPhysics_Parametric::idPhysics_Parametric( void ) {
current.time = gameLocal.time;
current.atRest = -1;
current.useSplineAngles = false;
current.origin.Zero();
current.angles.Zero();
current.axis.Identity();
current.localOrigin.Zero();
current.localAngles.Zero();
current.linearExtrapolation.Init( 0, 0, vec3_zero, vec3_zero, vec3_zero, EXTRAPOLATION_NONE );
current.angularExtrapolation.Init( 0, 0, ang_zero, ang_zero, ang_zero, EXTRAPOLATION_NONE );
current.linearInterpolation.Init( 0, 0, 0, 0, vec3_zero, vec3_zero );
current.angularInterpolation.Init( 0, 0, 0, 0, ang_zero, ang_zero );
current.spline = NULL;
current.splineInterpolate.Init( 0, 1, 1, 2, 0, 0 );
saved = current;
isPusher = false;
pushFlags = 0;
clipModel = NULL;
isBlocked = false;
memset( &pushResults, 0, sizeof( pushResults ) );
hasMaster = false;
isOrientated = false;
}
/*
================
idPhysics_Parametric::~idPhysics_Parametric
================
*/
idPhysics_Parametric::~idPhysics_Parametric( void ) {
if ( clipModel != NULL ) {
delete clipModel;
clipModel = NULL;
}
if ( current.spline != NULL ) {
delete current.spline;
current.spline = NULL;
}
}
/*
================
idPhysics_Parametric_SavePState
================
*/
void idPhysics_Parametric_SavePState( idSaveGame *savefile, const parametricPState_t &state ) {
savefile->WriteInt( state.time );
savefile->WriteInt( state.atRest );
savefile->WriteBool( state.useSplineAngles );
savefile->WriteVec3( state.origin );
savefile->WriteAngles( state.angles );
savefile->WriteMat3( state.axis );
savefile->WriteVec3( state.localOrigin );
savefile->WriteAngles( state.localAngles );
savefile->WriteInt( (int)state.linearExtrapolation.GetExtrapolationType() );
savefile->WriteFloat( state.linearExtrapolation.GetStartTime() );
savefile->WriteFloat( state.linearExtrapolation.GetDuration() );
savefile->WriteVec3( state.linearExtrapolation.GetStartValue() );
savefile->WriteVec3( state.linearExtrapolation.GetBaseSpeed() );
savefile->WriteVec3( state.linearExtrapolation.GetSpeed() );
savefile->WriteInt( (int)state.angularExtrapolation.GetExtrapolationType() );
savefile->WriteFloat( state.angularExtrapolation.GetStartTime() );
savefile->WriteFloat( state.angularExtrapolation.GetDuration() );
savefile->WriteAngles( state.angularExtrapolation.GetStartValue() );
savefile->WriteAngles( state.angularExtrapolation.GetBaseSpeed() );
savefile->WriteAngles( state.angularExtrapolation.GetSpeed() );
savefile->WriteFloat( state.linearInterpolation.GetStartTime() );
savefile->WriteFloat( state.linearInterpolation.GetAcceleration() );
savefile->WriteFloat( state.linearInterpolation.GetDeceleration() );
savefile->WriteFloat( state.linearInterpolation.GetDuration() );
savefile->WriteVec3( state.linearInterpolation.GetStartValue() );
savefile->WriteVec3( state.linearInterpolation.GetEndValue() );
savefile->WriteFloat( state.angularInterpolation.GetStartTime() );
savefile->WriteFloat( state.angularInterpolation.GetAcceleration() );
savefile->WriteFloat( state.angularInterpolation.GetDeceleration() );
savefile->WriteFloat( state.angularInterpolation.GetDuration() );
savefile->WriteAngles( state.angularInterpolation.GetStartValue() );
savefile->WriteAngles( state.angularInterpolation.GetEndValue() );
// spline is handled by owner
savefile->WriteFloat( state.splineInterpolate.GetStartTime() );
savefile->WriteFloat( state.splineInterpolate.GetAcceleration() );
savefile->WriteFloat( state.splineInterpolate.GetDuration() );
savefile->WriteFloat( state.splineInterpolate.GetDeceleration() );
savefile->WriteFloat( state.splineInterpolate.GetStartValue() );
savefile->WriteFloat( state.splineInterpolate.GetEndValue() );
}
/*
================
idPhysics_Parametric_RestorePState
================
*/
void idPhysics_Parametric_RestorePState( idRestoreGame *savefile, parametricPState_t &state ) {
extrapolation_t etype;
float startTime, duration, accelTime, decelTime, startValue, endValue;
idVec3 linearStartValue, linearBaseSpeed, linearSpeed, startPos, endPos;
idAngles angularStartValue, angularBaseSpeed, angularSpeed, startAng, endAng;
savefile->ReadInt( state.time );
savefile->ReadInt( state.atRest );
savefile->ReadBool( state.useSplineAngles );
savefile->ReadVec3( state.origin );
savefile->ReadAngles( state.angles );
savefile->ReadMat3( state.axis );
savefile->ReadVec3( state.localOrigin );
savefile->ReadAngles( state.localAngles );
savefile->ReadInt( (int &)etype );
savefile->ReadFloat( startTime );
savefile->ReadFloat( duration );
savefile->ReadVec3( linearStartValue );
savefile->ReadVec3( linearBaseSpeed );
savefile->ReadVec3( linearSpeed );
state.linearExtrapolation.Init( startTime, duration, linearStartValue, linearBaseSpeed, linearSpeed, etype );
savefile->ReadInt( (int &)etype );
savefile->ReadFloat( startTime );
savefile->ReadFloat( duration );
savefile->ReadAngles( angularStartValue );
savefile->ReadAngles( angularBaseSpeed );
savefile->ReadAngles( angularSpeed );
state.angularExtrapolation.Init( startTime, duration, angularStartValue, angularBaseSpeed, angularSpeed, etype );
savefile->ReadFloat( startTime );
savefile->ReadFloat( accelTime );
savefile->ReadFloat( decelTime );
savefile->ReadFloat( duration );
savefile->ReadVec3( startPos );
savefile->ReadVec3( endPos );
state.linearInterpolation.Init( startTime, accelTime, decelTime, duration, startPos, endPos );
savefile->ReadFloat( startTime );
savefile->ReadFloat( accelTime );
savefile->ReadFloat( decelTime );
savefile->ReadFloat( duration );
savefile->ReadAngles( startAng );
savefile->ReadAngles( endAng );
state.angularInterpolation.Init( startTime, accelTime, decelTime, duration, startAng, endAng );
// spline is handled by owner
savefile->ReadFloat( startTime );
savefile->ReadFloat( accelTime );
savefile->ReadFloat( duration );
savefile->ReadFloat( decelTime );
savefile->ReadFloat( startValue );
savefile->ReadFloat( endValue );
state.splineInterpolate.Init( startTime, accelTime, decelTime, duration, startValue, endValue );
}
/*
================
idPhysics_Parametric::Save
================
*/
void idPhysics_Parametric::Save( idSaveGame *savefile ) const {
idPhysics_Parametric_SavePState( savefile, current );
idPhysics_Parametric_SavePState( savefile, saved );
savefile->WriteBool( isPusher );
savefile->WriteClipModel( clipModel );
savefile->WriteInt( pushFlags );
savefile->WriteTrace( pushResults );
savefile->WriteBool( isBlocked );
savefile->WriteBool( hasMaster );
savefile->WriteBool( isOrientated );
}
/*
================
idPhysics_Parametric::Restore
================
*/
void idPhysics_Parametric::Restore( idRestoreGame *savefile ) {
idPhysics_Parametric_RestorePState( savefile, current );
idPhysics_Parametric_RestorePState( savefile, saved );
savefile->ReadBool( isPusher );
savefile->ReadClipModel( clipModel );
savefile->ReadInt( pushFlags );
savefile->ReadTrace( pushResults );
savefile->ReadBool( isBlocked );
savefile->ReadBool( hasMaster );
savefile->ReadBool( isOrientated );
}
/*
================
idPhysics_Parametric::SetPusher
================
*/
void idPhysics_Parametric::SetPusher( int flags ) {
assert( clipModel );
isPusher = true;
pushFlags = flags;
}
/*
================
idPhysics_Parametric::IsPusher
================
*/
bool idPhysics_Parametric::IsPusher( void ) const {
return isPusher;
}
/*
================
idPhysics_Parametric::SetLinearExtrapolation
================
*/
void idPhysics_Parametric::SetLinearExtrapolation( extrapolation_t type, int time, int duration, const idVec3 &base, const idVec3 &speed, const idVec3 &baseSpeed ) {
current.time = gameLocal.time;
current.linearExtrapolation.Init( time, duration, base, baseSpeed, speed, type );
current.localOrigin = base;
Activate();
}
/*
================
idPhysics_Parametric::SetAngularExtrapolation
================
*/
void idPhysics_Parametric::SetAngularExtrapolation( extrapolation_t type, int time, int duration, const idAngles &base, const idAngles &speed, const idAngles &baseSpeed ) {
current.time = gameLocal.time;
current.angularExtrapolation.Init( time, duration, base, baseSpeed, speed, type );
current.localAngles = base;
Activate();
}
/*
================
idPhysics_Parametric::GetLinearExtrapolationType
================
*/
extrapolation_t idPhysics_Parametric::GetLinearExtrapolationType( void ) const {
return current.linearExtrapolation.GetExtrapolationType();
}
/*
================
idPhysics_Parametric::GetAngularExtrapolationType
================
*/
extrapolation_t idPhysics_Parametric::GetAngularExtrapolationType( void ) const {
return current.angularExtrapolation.GetExtrapolationType();
}
/*
================
idPhysics_Parametric::SetLinearInterpolation
================
*/
void idPhysics_Parametric::SetLinearInterpolation( int time, int accelTime, int decelTime, int duration, const idVec3 &startPos, const idVec3 &endPos ) {
current.time = gameLocal.time;
current.linearInterpolation.Init( time, accelTime, decelTime, duration, startPos, endPos );
current.localOrigin = startPos;
Activate();
}
/*
================
idPhysics_Parametric::SetAngularInterpolation
================
*/
void idPhysics_Parametric::SetAngularInterpolation( int time, int accelTime, int decelTime, int duration, const idAngles &startAng, const idAngles &endAng ) {
current.time = gameLocal.time;
current.angularInterpolation.Init( time, accelTime, decelTime, duration, startAng, endAng );
current.localAngles = startAng;
Activate();
}
/*
================
idPhysics_Parametric::SetSpline
================
*/
void idPhysics_Parametric::SetSpline( idCurve_Spline<idVec3> *spline, int accelTime, int decelTime, bool useSplineAngles ) {
if ( current.spline != NULL ) {
delete current.spline;
current.spline = NULL;
}
current.spline = spline;
if ( current.spline != NULL ) {
float startTime = current.spline->GetTime( 0 );
float endTime = current.spline->GetTime( current.spline->GetNumValues() - 1 );
float length = current.spline->GetLengthForTime( endTime );
current.splineInterpolate.Init( startTime, accelTime, decelTime, endTime - startTime, 0.0f, length );
}
current.useSplineAngles = useSplineAngles;
Activate();
}
/*
================
idPhysics_Parametric::GetSpline
================
*/
idCurve_Spline<idVec3> *idPhysics_Parametric::GetSpline( void ) const {
return current.spline;
}
/*
================
idPhysics_Parametric::GetSplineAcceleration
================
*/
int idPhysics_Parametric::GetSplineAcceleration( void ) const {
return current.splineInterpolate.GetAcceleration();
}
/*
================
idPhysics_Parametric::GetSplineDeceleration
================
*/
int idPhysics_Parametric::GetSplineDeceleration( void ) const {
return current.splineInterpolate.GetDeceleration();
}
/*
================
idPhysics_Parametric::UsingSplineAngles
================
*/
bool idPhysics_Parametric::UsingSplineAngles( void ) const {
return current.useSplineAngles;
}
/*
================
idPhysics_Parametric::GetLocalOrigin
================
*/
void idPhysics_Parametric::GetLocalOrigin( idVec3 &curOrigin ) const {
curOrigin = current.localOrigin;
}
/*
================
idPhysics_Parametric::GetLocalAngles
================
*/
void idPhysics_Parametric::GetLocalAngles( idAngles &curAngles ) const {
curAngles = current.localAngles;
}
/*
================
idPhysics_Parametric::SetClipModel
================
*/
void idPhysics_Parametric::SetClipModel( idClipModel *model, float density, int id, bool freeOld ) {
assert( self );
assert( model );
if ( clipModel && clipModel != model && freeOld ) {
delete clipModel;
}
clipModel = model;
clipModel->Link( gameLocal.clip, self, 0, current.origin, current.axis );
}
/*
================
idPhysics_Parametric::GetClipModel
================
*/
idClipModel *idPhysics_Parametric::GetClipModel( int id ) const {
return clipModel;
}
/*
================
idPhysics_Parametric::GetNumClipModels
================
*/
int idPhysics_Parametric::GetNumClipModels( void ) const {
return ( clipModel != NULL );
}
/*
================
idPhysics_Parametric::SetMass
================
*/
void idPhysics_Parametric::SetMass( float mass, int id ) {
}
/*
================
idPhysics_Parametric::GetMass
================
*/
float idPhysics_Parametric::GetMass( int id ) const {
return 0.0f;
}
/*
================
idPhysics_Parametric::SetClipMask
================
*/
void idPhysics_Parametric::SetContents( int contents, int id ) {
if ( clipModel ) {
clipModel->SetContents( contents );
}
}
/*
================
idPhysics_Parametric::SetClipMask
================
*/
int idPhysics_Parametric::GetContents( int id ) const {
if ( clipModel ) {
return clipModel->GetContents();
}
return 0;
}
/*
================
idPhysics_Parametric::GetBounds
================
*/
const idBounds &idPhysics_Parametric::GetBounds( int id ) const {
if ( clipModel ) {
return clipModel->GetBounds();
}
return idPhysics_Base::GetBounds();
}
/*
================
idPhysics_Parametric::GetAbsBounds
================
*/
const idBounds &idPhysics_Parametric::GetAbsBounds( int id ) const {
if ( clipModel ) {
return clipModel->GetAbsBounds();
}
return idPhysics_Base::GetAbsBounds();
}
/*
================
idPhysics_Parametric::Evaluate
================
*/
bool idPhysics_Parametric::Evaluate( int timeStepMSec, int endTimeMSec ) {
idVec3 oldLocalOrigin, oldOrigin, masterOrigin;
idAngles oldLocalAngles, oldAngles;
idMat3 oldAxis, masterAxis;
isBlocked = false;
oldLocalOrigin = current.localOrigin;
oldOrigin = current.origin;
oldLocalAngles = current.localAngles;
oldAngles = current.angles;
oldAxis = current.axis;
current.localOrigin.Zero();
current.localAngles.Zero();
if ( current.spline != NULL ) {
float length = current.splineInterpolate.GetCurrentValue( endTimeMSec );
float t = current.spline->GetTimeForLength( length, 0.01f );
current.localOrigin = current.spline->GetCurrentValue( t );
if ( current.useSplineAngles ) {
current.localAngles = current.spline->GetCurrentFirstDerivative( t ).ToAngles();
}
} else if ( current.linearInterpolation.GetDuration() != 0 ) {
current.localOrigin += current.linearInterpolation.GetCurrentValue( endTimeMSec );
} else {
current.localOrigin += current.linearExtrapolation.GetCurrentValue( endTimeMSec );
}
if ( current.angularInterpolation.GetDuration() != 0 ) {
current.localAngles += current.angularInterpolation.GetCurrentValue( endTimeMSec );
} else {
current.localAngles += current.angularExtrapolation.GetCurrentValue( endTimeMSec );
}
current.localAngles.Normalize360();
current.origin = current.localOrigin;
current.angles = current.localAngles;
current.axis = current.localAngles.ToMat3();
if ( hasMaster ) {
self->GetMasterPosition( masterOrigin, masterAxis );
if ( masterAxis.IsRotated() ) {
current.origin = current.origin * masterAxis + masterOrigin;
if ( isOrientated ) {
current.axis *= masterAxis;
current.angles = current.axis.ToAngles();
}
}
else {
current.origin += masterOrigin;
}
}
if ( isPusher ) {
gameLocal.push.ClipPush( pushResults, self, pushFlags, oldOrigin, oldAxis, current.origin, current.axis );
if ( pushResults.fraction < 1.0f ) {
clipModel->Link( gameLocal.clip, self, 0, oldOrigin, oldAxis );
current.localOrigin = oldLocalOrigin;
current.origin = oldOrigin;
current.localAngles = oldLocalAngles;
current.angles = oldAngles;
current.axis = oldAxis;
isBlocked = true;
return false;
}
current.angles = current.axis.ToAngles();
}
if ( clipModel ) {
clipModel->Link( gameLocal.clip, self, 0, current.origin, current.axis );
}
current.time = endTimeMSec;
if ( TestIfAtRest() ) {
Rest();
}
return ( current.origin != oldOrigin || current.axis != oldAxis );
}
/*
================
idPhysics_Parametric::UpdateTime
================
*/
void idPhysics_Parametric::UpdateTime( int endTimeMSec ) {
int timeLeap = endTimeMSec - current.time;
current.time = endTimeMSec;
// move the trajectory start times to sync the trajectory with the current endTime
current.linearExtrapolation.SetStartTime( current.linearExtrapolation.GetStartTime() + timeLeap );
current.angularExtrapolation.SetStartTime( current.angularExtrapolation.GetStartTime() + timeLeap );
current.linearInterpolation.SetStartTime( current.linearInterpolation.GetStartTime() + timeLeap );
current.angularInterpolation.SetStartTime( current.angularInterpolation.GetStartTime() + timeLeap );
if ( current.spline != NULL ) {
current.spline->ShiftTime( timeLeap );
current.splineInterpolate.SetStartTime( current.splineInterpolate.GetStartTime() + timeLeap );
}
}
/*
================
idPhysics_Parametric::GetTime
================
*/
int idPhysics_Parametric::GetTime( void ) const {
return current.time;
}
/*
================
idPhysics_Parametric::IsAtRest
================
*/
bool idPhysics_Parametric::IsAtRest( void ) const {
return current.atRest >= 0;
}
/*
================
idPhysics_Parametric::GetRestStartTime
================
*/
int idPhysics_Parametric::GetRestStartTime( void ) const {
return current.atRest;
}
/*
================
idPhysics_Parametric::IsPushable
================
*/
bool idPhysics_Parametric::IsPushable( void ) const {
return false;
}
/*
================
idPhysics_Parametric::SaveState
================
*/
void idPhysics_Parametric::SaveState( void ) {
saved = current;
}
/*
================
idPhysics_Parametric::RestoreState
================
*/
void idPhysics_Parametric::RestoreState( void ) {
current = saved;
if ( clipModel ) {
clipModel->Link( gameLocal.clip, self, 0, current.origin, current.axis );
}
}
/*
================
idPhysics_Parametric::SetOrigin
================
*/
void idPhysics_Parametric::SetOrigin( const idVec3 &newOrigin, int id ) {
idVec3 masterOrigin;
idMat3 masterAxis;
current.linearExtrapolation.SetStartValue( newOrigin );
current.linearInterpolation.SetStartValue( newOrigin );
current.localOrigin = current.linearExtrapolation.GetCurrentValue( current.time );
if ( hasMaster ) {
self->GetMasterPosition( masterOrigin, masterAxis );
current.origin = masterOrigin + current.localOrigin * masterAxis;
}
else {
current.origin = current.localOrigin;
}
if ( clipModel ) {
clipModel->Link( gameLocal.clip, self, 0, current.origin, current.axis );
}
Activate();
}
/*
================
idPhysics_Parametric::SetAxis
================
*/
void idPhysics_Parametric::SetAxis( const idMat3 &newAxis, int id ) {
idVec3 masterOrigin;
idMat3 masterAxis;
current.localAngles = newAxis.ToAngles();
current.angularExtrapolation.SetStartValue( current.localAngles );
current.angularInterpolation.SetStartValue( current.localAngles );
current.localAngles = current.angularExtrapolation.GetCurrentValue( current.time );
if ( hasMaster && isOrientated ) {
self->GetMasterPosition( masterOrigin, masterAxis );
current.axis = current.localAngles.ToMat3() * masterAxis;
current.angles = current.axis.ToAngles();
}
else {
current.axis = current.localAngles.ToMat3();
current.angles = current.localAngles;
}
if ( clipModel ) {
clipModel->Link( gameLocal.clip, self, 0, current.origin, current.axis );
}
Activate();
}
/*
================
idPhysics_Parametric::Move
================
*/
void idPhysics_Parametric::Translate( const idVec3 &translation, int id ) {
}
/*
================
idPhysics_Parametric::Rotate
================
*/
void idPhysics_Parametric::Rotate( const idRotation &rotation, int id ) {
}
/*
================
idPhysics_Parametric::GetOrigin
================
*/
const idVec3 &idPhysics_Parametric::GetOrigin( int id ) const {
return current.origin;
}
/*
================
idPhysics_Parametric::GetAxis
================
*/
const idMat3 &idPhysics_Parametric::GetAxis( int id ) const {
return current.axis;
}
/*
================
idPhysics_Parametric::GetAngles
================
*/
void idPhysics_Parametric::GetAngles( idAngles &curAngles ) const {
curAngles = current.angles;
}
/*
================
idPhysics_Parametric::SetLinearVelocity
================
*/
void idPhysics_Parametric::SetLinearVelocity( const idVec3 &newLinearVelocity, int id ) {
SetLinearExtrapolation( extrapolation_t(EXTRAPOLATION_LINEAR|EXTRAPOLATION_NOSTOP), gameLocal.time, 0, current.origin, newLinearVelocity, vec3_origin );
current.linearInterpolation.Init( 0, 0, 0, 0, vec3_zero, vec3_zero );
Activate();
}
/*
================
idPhysics_Parametric::SetAngularVelocity
================
*/
void idPhysics_Parametric::SetAngularVelocity( const idVec3 &newAngularVelocity, int id ) {
idRotation rotation;
idVec3 vec;
float angle;
vec = newAngularVelocity;
angle = vec.Normalize();
rotation.Set( vec3_origin, vec, (float) RAD2DEG( angle ) );
SetAngularExtrapolation( extrapolation_t(EXTRAPOLATION_LINEAR|EXTRAPOLATION_NOSTOP), gameLocal.time, 0, current.angles, rotation.ToAngles(), ang_zero );
current.angularInterpolation.Init( 0, 0, 0, 0, ang_zero, ang_zero );
Activate();
}
/*
================
idPhysics_Parametric::GetLinearVelocity
================
*/
const idVec3 &idPhysics_Parametric::GetLinearVelocity( int id ) const {
static idVec3 curLinearVelocity;
curLinearVelocity = current.linearExtrapolation.GetCurrentSpeed( gameLocal.time );
return curLinearVelocity;
}
/*
================
idPhysics_Parametric::GetAngularVelocity
================
*/
const idVec3 &idPhysics_Parametric::GetAngularVelocity( int id ) const {
static idVec3 curAngularVelocity;
idAngles angles;
angles = current.angularExtrapolation.GetCurrentSpeed( gameLocal.time );
curAngularVelocity = angles.ToAngularVelocity();
return curAngularVelocity;
}
/*
================
idPhysics_Parametric::DisableClip
================
*/
void idPhysics_Parametric::DisableClip( void ) {
if ( clipModel ) {
clipModel->Disable();
}
}
/*
================
idPhysics_Parametric::EnableClip
================
*/
void idPhysics_Parametric::EnableClip( void ) {
if ( clipModel ) {
clipModel->Enable();
}
}
/*
================
idPhysics_Parametric::UnlinkClip
================
*/
void idPhysics_Parametric::UnlinkClip( void ) {
if ( clipModel ) {
clipModel->Unlink();
}
}
/*
================
idPhysics_Parametric::LinkClip
================
*/
void idPhysics_Parametric::LinkClip( void ) {
if ( clipModel ) {
clipModel->Link( gameLocal.clip, self, 0, current.origin, current.axis );
}
}
/*
================
idPhysics_Parametric::GetBlockingInfo
================
*/
const trace_t *idPhysics_Parametric::GetBlockingInfo( void ) const {
return ( isBlocked ? &pushResults : NULL );
}
/*
================
idPhysics_Parametric::GetBlockingEntity
================
*/
idEntity *idPhysics_Parametric::GetBlockingEntity( void ) const {
if ( isBlocked ) {
return gameLocal.entities[ pushResults.c.entityNum ];
}
return NULL;
}
/*
================
idPhysics_Parametric::SetMaster
================
*/
void idPhysics_Parametric::SetMaster( idEntity *master, const bool orientated ) {
idVec3 masterOrigin;
idMat3 masterAxis;
if ( master ) {
if ( !hasMaster ) {
// transform from world space to master space
self->GetMasterPosition( masterOrigin, masterAxis );
current.localOrigin = ( current.origin - masterOrigin ) * masterAxis.Transpose();
if ( orientated ) {
current.localAngles = ( current.axis * masterAxis.Transpose() ).ToAngles();
}
else {
current.localAngles = current.axis.ToAngles();
}
current.linearExtrapolation.SetStartValue( current.localOrigin );
current.angularExtrapolation.SetStartValue( current.localAngles );
hasMaster = true;
isOrientated = orientated;
}
}
else {
if ( hasMaster ) {
// transform from master space to world space
current.localOrigin = current.origin;
current.localAngles = current.angles;
SetLinearExtrapolation( EXTRAPOLATION_NONE, 0, 0, current.origin, vec3_origin, vec3_origin );
SetAngularExtrapolation( EXTRAPOLATION_NONE, 0, 0, current.angles, ang_zero, ang_zero );
hasMaster = false;
}
}
}
/*
================
idPhysics_Parametric::GetLinearEndTime
================
*/
int idPhysics_Parametric::GetLinearEndTime( void ) const {
if ( current.spline != NULL ) {
if ( current.spline->GetBoundaryType() != idCurve_Spline<idVec3>::BT_CLOSED ) {
return current.spline->GetTime( current.spline->GetNumValues() - 1 );
} else {
return 0;
}
} else if ( current.linearInterpolation.GetDuration() != 0 ) {
return current.linearInterpolation.GetEndTime();
} else {
return current.linearExtrapolation.GetEndTime();
}
}
/*
================
idPhysics_Parametric::GetAngularEndTime
================
*/
int idPhysics_Parametric::GetAngularEndTime( void ) const {
if ( current.angularInterpolation.GetDuration() != 0 ) {
return current.angularInterpolation.GetEndTime();
} else {
return current.angularExtrapolation.GetEndTime();
}
}
/*
================
idPhysics_Parametric::WriteToSnapshot
================
*/
void idPhysics_Parametric::WriteToSnapshot( idBitMsgDelta &msg ) const {
msg.WriteInt( current.time );
msg.WriteInt( current.atRest );
msg.WriteFloat( current.origin[0] );
msg.WriteFloat( current.origin[1] );
msg.WriteFloat( current.origin[2] );
msg.WriteFloat( current.angles[0] );
msg.WriteFloat( current.angles[1] );
msg.WriteFloat( current.angles[2] );
msg.WriteDeltaFloat( current.origin[0], current.localOrigin[0] );
msg.WriteDeltaFloat( current.origin[1], current.localOrigin[1] );
msg.WriteDeltaFloat( current.origin[2], current.localOrigin[2] );
msg.WriteDeltaFloat( current.angles[0], current.localAngles[0] );
msg.WriteDeltaFloat( current.angles[1], current.localAngles[1] );
msg.WriteDeltaFloat( current.angles[2], current.localAngles[2] );
msg.WriteBits( current.linearExtrapolation.GetExtrapolationType(), 8 );
msg.WriteDeltaFloat( 0.0f, current.linearExtrapolation.GetStartTime() );
msg.WriteDeltaFloat( 0.0f, current.linearExtrapolation.GetDuration() );
msg.WriteDeltaFloat( 0.0f, current.linearExtrapolation.GetStartValue()[0] );
msg.WriteDeltaFloat( 0.0f, current.linearExtrapolation.GetStartValue()[1] );
msg.WriteDeltaFloat( 0.0f, current.linearExtrapolation.GetStartValue()[2] );
msg.WriteDeltaFloat( 0.0f, current.linearExtrapolation.GetSpeed()[0] );
msg.WriteDeltaFloat( 0.0f, current.linearExtrapolation.GetSpeed()[1] );
msg.WriteDeltaFloat( 0.0f, current.linearExtrapolation.GetSpeed()[2] );
msg.WriteDeltaFloat( 0.0f, current.linearExtrapolation.GetBaseSpeed()[0] );
msg.WriteDeltaFloat( 0.0f, current.linearExtrapolation.GetBaseSpeed()[1] );
msg.WriteDeltaFloat( 0.0f, current.linearExtrapolation.GetBaseSpeed()[2] );
msg.WriteBits( current.angularExtrapolation.GetExtrapolationType(), 8 );
msg.WriteDeltaFloat( 0.0f, current.angularExtrapolation.GetStartTime() );
msg.WriteDeltaFloat( 0.0f, current.angularExtrapolation.GetDuration() );
msg.WriteDeltaFloat( 0.0f, current.angularExtrapolation.GetStartValue()[0] );
msg.WriteDeltaFloat( 0.0f, current.angularExtrapolation.GetStartValue()[1] );
msg.WriteDeltaFloat( 0.0f, current.angularExtrapolation.GetStartValue()[2] );
msg.WriteDeltaFloat( 0.0f, current.angularExtrapolation.GetSpeed()[0] );
msg.WriteDeltaFloat( 0.0f, current.angularExtrapolation.GetSpeed()[1] );
msg.WriteDeltaFloat( 0.0f, current.angularExtrapolation.GetSpeed()[2] );
msg.WriteDeltaFloat( 0.0f, current.angularExtrapolation.GetBaseSpeed()[0] );
msg.WriteDeltaFloat( 0.0f, current.angularExtrapolation.GetBaseSpeed()[1] );
msg.WriteDeltaFloat( 0.0f, current.angularExtrapolation.GetBaseSpeed()[2] );
msg.WriteDeltaFloat( 0.0f, current.linearInterpolation.GetStartTime() );
msg.WriteDeltaFloat( 0.0f, current.linearInterpolation.GetAcceleration() );
msg.WriteDeltaFloat( 0.0f, current.linearInterpolation.GetDeceleration() );
msg.WriteDeltaFloat( 0.0f, current.linearInterpolation.GetDuration() );
msg.WriteDeltaFloat( 0.0f, current.linearInterpolation.GetStartValue()[0] );
msg.WriteDeltaFloat( 0.0f, current.linearInterpolation.GetStartValue()[1] );
msg.WriteDeltaFloat( 0.0f, current.linearInterpolation.GetStartValue()[2] );
msg.WriteDeltaFloat( 0.0f, current.linearInterpolation.GetEndValue()[0] );
msg.WriteDeltaFloat( 0.0f, current.linearInterpolation.GetEndValue()[1] );
msg.WriteDeltaFloat( 0.0f, current.linearInterpolation.GetEndValue()[2] );
msg.WriteDeltaFloat( 0.0f, current.angularInterpolation.GetStartTime() );
msg.WriteDeltaFloat( 0.0f, current.angularInterpolation.GetAcceleration() );
msg.WriteDeltaFloat( 0.0f, current.angularInterpolation.GetDeceleration() );
msg.WriteDeltaFloat( 0.0f, current.angularInterpolation.GetDuration() );
msg.WriteDeltaFloat( 0.0f, current.angularInterpolation.GetStartValue()[0] );
msg.WriteDeltaFloat( 0.0f, current.angularInterpolation.GetStartValue()[1] );
msg.WriteDeltaFloat( 0.0f, current.angularInterpolation.GetStartValue()[2] );
msg.WriteDeltaFloat( 0.0f, current.angularInterpolation.GetEndValue()[0] );
msg.WriteDeltaFloat( 0.0f, current.angularInterpolation.GetEndValue()[1] );
msg.WriteDeltaFloat( 0.0f, current.angularInterpolation.GetEndValue()[2] );
}
/*
================
idPhysics_Parametric::ReadFromSnapshot
================
*/
void idPhysics_Parametric::ReadFromSnapshot( const idBitMsgDelta &msg ) {
extrapolation_t linearType, angularType;
float startTime, duration, accelTime, decelTime;
idVec3 linearStartValue, linearSpeed, linearBaseSpeed, startPos, endPos;
idAngles angularStartValue, angularSpeed, angularBaseSpeed, startAng, endAng;
current.time = msg.ReadInt();
current.atRest = msg.ReadInt();
current.origin[0] = msg.ReadFloat();
current.origin[1] = msg.ReadFloat();
current.origin[2] = msg.ReadFloat();
current.angles[0] = msg.ReadFloat();
current.angles[1] = msg.ReadFloat();
current.angles[2] = msg.ReadFloat();
current.localOrigin[0] = msg.ReadDeltaFloat( current.origin[0] );
current.localOrigin[1] = msg.ReadDeltaFloat( current.origin[1] );
current.localOrigin[2] = msg.ReadDeltaFloat( current.origin[2] );
current.localAngles[0] = msg.ReadDeltaFloat( current.angles[0] );
current.localAngles[1] = msg.ReadDeltaFloat( current.angles[1] );
current.localAngles[2] = msg.ReadDeltaFloat( current.angles[2] );
linearType = (extrapolation_t) msg.ReadBits( 8 );
startTime = msg.ReadDeltaFloat( 0.0f );
duration = msg.ReadDeltaFloat( 0.0f );
linearStartValue[0] = msg.ReadDeltaFloat( 0.0f );
linearStartValue[1] = msg.ReadDeltaFloat( 0.0f );
linearStartValue[2] = msg.ReadDeltaFloat( 0.0f );
linearSpeed[0] = msg.ReadDeltaFloat( 0.0f );
linearSpeed[1] = msg.ReadDeltaFloat( 0.0f );
linearSpeed[2] = msg.ReadDeltaFloat( 0.0f );
linearBaseSpeed[0] = msg.ReadDeltaFloat( 0.0f );
linearBaseSpeed[1] = msg.ReadDeltaFloat( 0.0f );
linearBaseSpeed[2] = msg.ReadDeltaFloat( 0.0f );
current.linearExtrapolation.Init( startTime, duration, linearStartValue, linearBaseSpeed, linearSpeed, linearType );
angularType = (extrapolation_t) msg.ReadBits( 8 );
startTime = msg.ReadDeltaFloat( 0.0f );
duration = msg.ReadDeltaFloat( 0.0f );
angularStartValue[0] = msg.ReadDeltaFloat( 0.0f );
angularStartValue[1] = msg.ReadDeltaFloat( 0.0f );
angularStartValue[2] = msg.ReadDeltaFloat( 0.0f );
angularSpeed[0] = msg.ReadDeltaFloat( 0.0f );
angularSpeed[1] = msg.ReadDeltaFloat( 0.0f );
angularSpeed[2] = msg.ReadDeltaFloat( 0.0f );
angularBaseSpeed[0] = msg.ReadDeltaFloat( 0.0f );
angularBaseSpeed[1] = msg.ReadDeltaFloat( 0.0f );
angularBaseSpeed[2] = msg.ReadDeltaFloat( 0.0f );
current.angularExtrapolation.Init( startTime, duration, angularStartValue, angularBaseSpeed, angularSpeed, angularType );
startTime = msg.ReadDeltaFloat( 0.0f );
accelTime = msg.ReadDeltaFloat( 0.0f );
decelTime = msg.ReadDeltaFloat( 0.0f );
duration = msg.ReadDeltaFloat( 0.0f );
startPos[0] = msg.ReadDeltaFloat( 0.0f );
startPos[1] = msg.ReadDeltaFloat( 0.0f );
startPos[2] = msg.ReadDeltaFloat( 0.0f );
endPos[0] = msg.ReadDeltaFloat( 0.0f );
endPos[1] = msg.ReadDeltaFloat( 0.0f );
endPos[2] = msg.ReadDeltaFloat( 0.0f );
current.linearInterpolation.Init( startTime, accelTime, decelTime, duration, startPos, endPos );
startTime = msg.ReadDeltaFloat( 0.0f );
accelTime = msg.ReadDeltaFloat( 0.0f );
decelTime = msg.ReadDeltaFloat( 0.0f );
duration = msg.ReadDeltaFloat( 0.0f );
startAng[0] = msg.ReadDeltaFloat( 0.0f );
startAng[1] = msg.ReadDeltaFloat( 0.0f );
startAng[2] = msg.ReadDeltaFloat( 0.0f );
endAng[0] = msg.ReadDeltaFloat( 0.0f );
endAng[1] = msg.ReadDeltaFloat( 0.0f );
endAng[2] = msg.ReadDeltaFloat( 0.0f );
current.angularInterpolation.Init( startTime, accelTime, decelTime, duration, startAng, endAng );
current.axis = current.angles.ToMat3();
if ( clipModel ) {
clipModel->Link( gameLocal.clip, self, 0, current.origin, current.axis );
}
}
| 412 | 0.813149 | 1 | 0.813149 | game-dev | MEDIA | 0.522547 | game-dev | 0.931662 | 1 | 0.931662 |
CurativeTree/BuildCraft | 5,619 | src/main/java/ct/buildcraft/lib/expression/node/func/gen/NodeFuncBooleanBooleanBooleanToLong.java | /*
* Copyright (c) 2017 SpaceToad and the BuildCraft team
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/
*/
package ct.buildcraft.lib.expression.node.func.gen;
import java.util.Objects;
import ct.buildcraft.lib.expression.NodeInliningHelper;
import ct.buildcraft.lib.expression.api.IDependantNode;
import ct.buildcraft.lib.expression.api.IDependancyVisitor;
import ct.buildcraft.lib.expression.api.IExpressionNode.INodeBoolean;
import ct.buildcraft.lib.expression.api.IExpressionNode.INodeDouble;
import ct.buildcraft.lib.expression.api.IExpressionNode.INodeLong;
import ct.buildcraft.lib.expression.api.IExpressionNode.INodeObject;
import ct.buildcraft.lib.expression.api.INodeFunc.INodeFuncLong;
import ct.buildcraft.lib.expression.api.INodeStack;
import ct.buildcraft.lib.expression.api.InvalidExpressionException;
import ct.buildcraft.lib.expression.api.NodeTypes;
import ct.buildcraft.lib.expression.node.func.StringFunctionQuad;
import ct.buildcraft.lib.expression.node.func.NodeFuncBase;
import ct.buildcraft.lib.expression.node.func.NodeFuncBase.IFunctionNode;
import ct.buildcraft.lib.expression.node.value.NodeConstantLong;
// AUTO_GENERATED FILE, DO NOT EDIT MANUALLY!
public class NodeFuncBooleanBooleanBooleanToLong extends NodeFuncBase implements INodeFuncLong {
public final IFuncBooleanBooleanBooleanToLong function;
private final StringFunctionQuad stringFunction;
public NodeFuncBooleanBooleanBooleanToLong(String name, IFuncBooleanBooleanBooleanToLong function) {
this(function, (a, b, c) -> "[ boolean, boolean, boolean -> long ] " + name + "(" + a + ", " + b + ", " + c + ")");
}
public NodeFuncBooleanBooleanBooleanToLong(IFuncBooleanBooleanBooleanToLong function, StringFunctionQuad stringFunction) {
this.function = function;
this.stringFunction = stringFunction;
}
@Override
public String toString() {
return stringFunction.apply("{A}", "{B}", "{C}");
}
@Override
public NodeFuncBooleanBooleanBooleanToLong setNeverInline() {
super.setNeverInline();
return this;
}
@Override
public INodeLong getNode(INodeStack stack) throws InvalidExpressionException {
INodeBoolean c = stack.popBoolean();
INodeBoolean b = stack.popBoolean();
INodeBoolean a = stack.popBoolean();
return create(a, b, c);
}
/** Shortcut to create a new {@link FuncBooleanBooleanBooleanToLong} without needing to create
* and populate an {@link INodeStack} to pass to {@link #getNode(INodeStack)}. */
public FuncBooleanBooleanBooleanToLong create(INodeBoolean argA, INodeBoolean argB, INodeBoolean argC) {
return new FuncBooleanBooleanBooleanToLong(argA, argB, argC);
}
public class FuncBooleanBooleanBooleanToLong implements INodeLong, IDependantNode, IFunctionNode {
public final INodeBoolean argA;
public final INodeBoolean argB;
public final INodeBoolean argC;
public FuncBooleanBooleanBooleanToLong(INodeBoolean argA, INodeBoolean argB, INodeBoolean argC) {
this.argA = argA;
this.argB = argB;
this.argC = argC;
}
@Override
public long evaluate() {
return function.apply(argA.evaluate(), argB.evaluate(), argC.evaluate());
}
@Override
public INodeLong inline() {
if (!canInline) {
// Note that we can still inline the arguments, just not *this* function
return NodeInliningHelper.tryInline(this, argA, argB, argC,
(a, b, c) -> new FuncBooleanBooleanBooleanToLong(a, b, c),
(a, b, c) -> new FuncBooleanBooleanBooleanToLong(a, b, c)
);
}
return NodeInliningHelper.tryInline(this, argA, argB, argC,
(a, b, c) -> new FuncBooleanBooleanBooleanToLong(a, b, c),
(a, b, c) -> NodeConstantLong.of(function.apply(a.evaluate(), b.evaluate(), c.evaluate()))
);
}
@Override
public void visitDependants(IDependancyVisitor visitor) {
if (!canInline) {
if (function instanceof IDependantNode) {
visitor.dependOn((IDependantNode) function);
} else {
visitor.dependOnExplictly(this);
}
}
visitor.dependOn(argA, argB, argC);
}
@Override
public String toString() {
return stringFunction.apply(argA.toString(), argB.toString(), argC.toString());
}
@Override
public NodeFuncBase getFunction() {
return NodeFuncBooleanBooleanBooleanToLong.this;
}
@Override
public int hashCode() {
return Objects.hash(argA, argB, argC);
}
@Override
public boolean equals(Object obj) {
if (obj == this) return true;
if (obj == null || getClass() != obj.getClass()) {
return false;
}
FuncBooleanBooleanBooleanToLong other = (FuncBooleanBooleanBooleanToLong) obj;
return Objects.equals(argA, other.argA) //
&&Objects.equals(argB, other.argB) //
&&Objects.equals(argC, other.argC);
}
}
@FunctionalInterface
public interface IFuncBooleanBooleanBooleanToLong {
long apply(boolean a, boolean b, boolean c);
}
}
| 412 | 0.76759 | 1 | 0.76759 | game-dev | MEDIA | 0.880315 | game-dev | 0.718522 | 1 | 0.718522 |
bozimmerman/CoffeeMud | 10,966 | com/planet_ink/coffee_mud/Abilities/Prayers/Prayer_Restoration.java | package com.planet_ink.coffee_mud.Abilities.Prayers;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
/*
Copyright 2003-2025 Bo Zimmerman
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
public class Prayer_Restoration extends Prayer implements MendingSkill
{
@Override
public String ID()
{
return "Prayer_Restoration";
}
private final static String localizedName = CMLib.lang().L("Restoration");
@Override
public String name()
{
return localizedName;
}
@Override
public int abstractQuality()
{
return Ability.QUALITY_BENEFICIAL_OTHERS;
}
@Override
public int classificationCode()
{
return Ability.ACODE_PRAYER|Ability.DOMAIN_HEALING;
}
@Override
public long flags()
{
return Ability.FLAG_HOLY|Ability.FLAG_HEALINGMAGIC;
}
@Override
protected int overrideMana()
{
return Ability.COST_ALL;
}
@Override
public boolean supportsMending(final Physical item)
{
if(!(item instanceof MOB))
return false;
if(((((MOB)item).curState()).getHitPoints()<(((MOB)item).maxState()).getHitPoints()))
return true;
final MOB caster=CMClass.getFactoryMOB();
caster.basePhyStats().setLevel(CMProps.getIntVar(CMProps.Int.LASTPLAYERLEVEL));
caster.phyStats().setLevel(CMProps.getIntVar(CMProps.Int.LASTPLAYERLEVEL));
if(
(item.fetchEffect("Amputation")!=null)
||(item.fetchEffect("Injury")!=null)
||(item.fetchEffect("BrokenLimbs")!=null)
||(item.fetchEffect("Scarring")!=null)
||(item.fetchEffect("Fighter_AtemiStrike")!=null)
||(item.fetchEffect("Undead_EnergyDrain")!=null)
||(item.fetchEffect("Undead_WeakEnergyDrain")!=null)
||(item.fetchEffect("Undead_ColdTouch")!=null)
||((new Prayer_RestoreSmell().returnOffensiveAffects(caster,item)).size()>0)
||((new Prayer_RestoreVoice().returnOffensiveAffects(caster,item)).size()>0)
||((Prayer_RemovePoison.returnOffensiveAffects(item)).size()>0)
||((new Prayer_Freedom().returnOffensiveAffects(caster,item)).size()>0)
||((new Prayer_CureBlindness().returnOffensiveAffects(caster,item)).size()>0)
||((new Prayer_CureDeafness().returnOffensiveAffects(caster,item)).size()>0)
)
{
caster.destroy();
return true;
}
caster.destroy();
return false;
}
@Override
public int castingQuality(final MOB mob, final Physical target)
{
if(mob!=null)
{
if(target instanceof MOB)
{
if(!supportsMending(target))
return Ability.QUALITY_INDIFFERENT;
}
}
return super.castingQuality(mob,target);
}
@Override
public boolean invoke(final MOB mob, final List<String> commands, final Physical givenTarget, final boolean auto, final int asLevel)
{
final MOB target=this.getTarget(mob,commands,givenTarget);
if(target==null)
return false;
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
final boolean success=proficiencyCheck(mob,0,auto);
if(success)
{
final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?L("<T-NAME> become(s) surrounded by a bright light."):L("^S<S-NAME> @x1 over <T-NAMESELF> for restorative healing.^?",prayWord(mob)));
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
final int healing=target.maxState().getHitPoints()-target.curState().getHitPoints();
if(healing>0)
{
CMLib.combat().postHealing(mob,target,this,healing,CMMsg.MASK_ALWAYS|CMMsg.TYP_CAST_SPELL,null);
mob.location().show(target,null,CMMsg.MSG_OK_VISUAL,L("<S-NAME> look(s) much healthier!"));
target.recoverCharStats();
target.recoverPhyStats();
target.recoverMaxState();
}
Ability A;
A=target.fetchEffect("Bleeding");
if(A!=null)
{
target.delEffect(A);
mob.location().show(target,null,CMMsg.MSG_OK_VISUAL,L("<S-YOUPOSS> bleeding stops!"));
A=target.fetchAbility(A.ID());
if(A!=null)
target.delAbility(A);
target.recoverCharStats();
target.recoverPhyStats();
target.recoverMaxState();
}
A=target.fetchEffect("Amputation");
if(A!=null)
{
target.delEffect(A);
mob.location().show(target,null,CMMsg.MSG_OK_VISUAL,L("<S-YOUPOSS> missing parts are restored!"));
A=target.fetchAbility(A.ID());
if(A!=null)
target.delAbility(A);
target.recoverCharStats();
target.recoverPhyStats();
target.recoverMaxState();
}
A = target.fetchEffect("Scarring");
if (A != null)
{
mob.location().show(target,null,CMMsg.MSG_OK_VISUAL,L("<S-YOUPOSS> scars clear up!"));
A.unInvoke();
target.delEffect(A);
}
A=target.fetchEffect("BrokenLimbs");
if(A!=null)
{
target.delEffect(A);
mob.location().show(target,null,CMMsg.MSG_OK_VISUAL,L("<S-YOUPOSS> broken limbs mend!"));
A=target.fetchAbility(A.ID());
if(A!=null)
target.delAbility(A);
target.recoverCharStats();
target.recoverPhyStats();
target.recoverMaxState();
}
A=target.fetchEffect("Injury");
if(A!=null)
{
target.delEffect(A);
mob.location().show(target,null,CMMsg.MSG_OK_VISUAL,L("<S-YOUPOSS> injuries are healed!"));
A=target.fetchAbility(A.ID());
if(A!=null)
target.delAbility(A);
target.recoverCharStats();
target.recoverPhyStats();
target.recoverMaxState();
}
A=target.fetchEffect("Fighter_AtemiStrike");
if((A!=null)&&(A.canBeUninvoked()))
{
target.delEffect(A);
mob.location().show(target,null,CMMsg.MSG_OK_VISUAL,L("<S-YOUPOSS> atemi damage is healed!"));
target.recoverCharStats();
target.recoverPhyStats();
target.recoverMaxState();
}
A=target.fetchEffect("Undead_EnergyDrain");
if(A!=null)
{
A.unInvoke();
target.delEffect(A);
mob.location().show(target,null,CMMsg.MSG_OK_VISUAL,L("<S-YOUPOSS> lost levels are restored!"));
target.recoverCharStats();
target.recoverPhyStats();
target.recoverMaxState();
}
A=target.fetchEffect("Undead_WeakEnergyDrain");
if(A!=null)
{
A.unInvoke();
target.delEffect(A);
mob.location().show(target,null,CMMsg.MSG_OK_VISUAL,L("<S-YOUPOSS> lost levels are restored!"));
target.recoverCharStats();
target.recoverPhyStats();
target.recoverMaxState();
}
A=target.fetchEffect("Undead_ColdTouch");
if(A!=null)
{
A.unInvoke();
target.delEffect(A);
mob.location().show(target,null,CMMsg.MSG_OK_VISUAL,L("<S-NAME> <S-IS-ARE> no longer cold and weak!"));
target.recoverCharStats();
target.recoverPhyStats();
target.recoverMaxState();
}
List<Ability> offensiveAffects=new Prayer_RestoreSmell().returnOffensiveAffects(mob,target);
if(offensiveAffects.size()>0)
{
for(int a=offensiveAffects.size()-1;a>=0;a--)
offensiveAffects.get(a).unInvoke();
mob.location().showOthers(target,null,CMMsg.MSG_OK_VISUAL,L("<S-NAME> can smell again!"));
target.recoverCharStats();
target.recoverPhyStats();
target.recoverMaxState();
}
offensiveAffects=new Prayer_RestoreVoice().returnOffensiveAffects(mob,target);
if(offensiveAffects.size()>0)
{
for(int a=offensiveAffects.size()-1;a>=0;a--)
offensiveAffects.get(a).unInvoke();
mob.location().showOthers(target,null,CMMsg.MSG_OK_VISUAL,L("<S-NAME> can speak again!"));
target.recoverCharStats();
target.recoverPhyStats();
target.recoverMaxState();
}
offensiveAffects=Prayer_RemovePoison.returnOffensiveAffects(target);
if(offensiveAffects.size()>0)
{
for(int a=offensiveAffects.size()-1;a>=0;a--)
offensiveAffects.get(a).unInvoke();
mob.location().showOthers(target,null,CMMsg.MSG_OK_VISUAL,L("<S-NAME> is cured of <S-HIS-HER> poisonous afflication!"));
target.recoverCharStats();
target.recoverPhyStats();
target.recoverMaxState();
}
offensiveAffects=new Prayer_Freedom().returnOffensiveAffects(mob,target);
if(offensiveAffects.size()>0)
{
for(int a=offensiveAffects.size()-1;a>=0;a--)
offensiveAffects.get(a).unInvoke();
mob.location().showOthers(target,null,CMMsg.MSG_OK_VISUAL,L("<S-NAME> can move again!"));
target.recoverCharStats();
target.recoverPhyStats();
target.recoverMaxState();
}
offensiveAffects=new Prayer_CureDisease().returnOffensiveAffects(target);
if(offensiveAffects.size()>0)
{
for(int a=offensiveAffects.size()-1;a>=0;a--)
offensiveAffects.get(a).unInvoke();
mob.location().showOthers(target,null,CMMsg.MSG_OK_VISUAL,L("<S-NAME> is cured of <S-HIS-HER> disease!"));
target.recoverCharStats();
target.recoverPhyStats();
target.recoverMaxState();
}
offensiveAffects=new Prayer_CureBlindness().returnOffensiveAffects(mob,target);
if(offensiveAffects.size()>0)
{
for(int a=offensiveAffects.size()-1;a>=0;a--)
offensiveAffects.get(a).unInvoke();
mob.location().showOthers(target,null,CMMsg.MSG_OK_VISUAL,L("<S-NAME> can see again!"));
target.recoverCharStats();
target.recoverPhyStats();
target.recoverMaxState();
}
offensiveAffects=new Prayer_CureDeafness().returnOffensiveAffects(mob,target);
if(offensiveAffects.size()>0)
{
for(int a=offensiveAffects.size()-1;a>=0;a--)
offensiveAffects.get(a).unInvoke();
mob.location().showOthers(target,null,CMMsg.MSG_OK_VISUAL,L("<S-NAME> can hear again!"));
target.recoverCharStats();
target.recoverPhyStats();
target.recoverMaxState();
}
mob.location().recoverRoomStats();
}
}
else
beneficialWordsFizzle(mob,target,L("<S-NAME> @x1 over <T-NAMESELF>, but @x2 does not heed.",prayWord(mob),hisHerDiety(mob)));
// return whether it worked
return success;
}
}
| 412 | 0.939737 | 1 | 0.939737 | game-dev | MEDIA | 0.964187 | game-dev | 0.973342 | 1 | 0.973342 |
The-Legion-Preservation-Project/LegionCore-7.3.5 | 7,378 | src/server/scripts/Commands/cs_message.cpp | /*
* Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* ScriptData
Name: message_commandscript
%Complete: 100
Comment: All message related commands
Category: commandscripts
EndScriptData */
#include "ScriptMgr.h"
#include "Chat.h"
#include "ChannelMgr.h"
#include "Packets/ChatPackets.h"
class message_commandscript : public CommandScript
{
public:
message_commandscript() : CommandScript("message_commandscript") { }
std::vector<ChatCommand> GetCommands() const override
{
static std::vector<ChatCommand> channelSetCommandTable =
{
{ "ownership", SEC_ADMINISTRATOR, false, &HandleChannelSetOwnership, ""}
};
static std::vector<ChatCommand> channelCommandTable =
{
{ "set", SEC_ADMINISTRATOR, true, NULL, "", channelSetCommandTable }
};
static std::vector<ChatCommand> commandTable =
{
{ "channel", SEC_ADMINISTRATOR, true, NULL, "", channelCommandTable },
{ "nameannounce", SEC_MODERATOR, true, &HandleNameAnnounceCommand, ""},
{ "gmnameannounce", SEC_MODERATOR, true, &HandleGMNameAnnounceCommand, ""},
{ "announce", SEC_MODERATOR, true, &HandleAnnounceCommand, ""},
{ "gmannounce", SEC_MODERATOR, true, &HandleGMAnnounceCommand, ""},
{ "notify", SEC_MODERATOR, true, &HandleNotifyCommand, ""},
{ "gmnotify", SEC_MODERATOR, true, &HandleGMNotifyCommand, ""},
{ "whispers", SEC_MODERATOR, false, &HandleWhispersCommand, ""}
};
return commandTable;
}
static bool HandleChannelSetOwnership(ChatHandler* handler, char const* args)
{
if (!*args)
return false;
char const* channelStr = strtok((char*)args, " ");
char const* argStr = strtok(NULL, "");
if (!channelStr || !argStr)
return false;
Player* player = handler->GetSession()->GetPlayer();
Channel* channcel = NULL;
if (ChannelMgr* cMgr = channelMgr(player->GetTeam()))
channcel = cMgr->GetChannel(channelStr, player);
if (strcmp(argStr, "on") == 0)
{
if (channcel)
channcel->SetOwnership(true);
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHANNEL_OWNERSHIP);
stmt->setUInt8 (0, 1);
stmt->setString(1, channelStr);
CharacterDatabase.Execute(stmt);
handler->PSendSysMessage(LANG_CHANNEL_ENABLE_OWNERSHIP, channelStr);
}
else if (strcmp(argStr, "off") == 0)
{
if (channcel)
channcel->SetOwnership(false);
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHANNEL_OWNERSHIP);
stmt->setUInt8 (0, 0);
stmt->setString(1, channelStr);
CharacterDatabase.Execute(stmt);
handler->PSendSysMessage(LANG_CHANNEL_DISABLE_OWNERSHIP, channelStr);
}
else
return false;
return true;
}
static bool HandleNameAnnounceCommand(ChatHandler* handler, char const* args)
{
if (!*args)
return false;
std::string name("Console");
if (WorldSession* session = handler->GetSession())
name = session->GetPlayer()->GetName();
sWorld->SendWorldText(LANG_ANNOUNCE_COLOR, name.c_str(), args);
return true;
}
static bool HandleGMNameAnnounceCommand(ChatHandler* handler, char const* args)
{
if (!*args)
return false;
std::string name("Console");
if (WorldSession* session = handler->GetSession())
name = session->GetPlayer()->GetName();
sWorld->SendGMText(LANG_GM_ANNOUNCE_COLOR, name.c_str(), args);
return true;
}
// global announce
static bool HandleAnnounceCommand(ChatHandler* handler, char const* args)
{
if (!*args)
return false;
char buff[2048];
sprintf(buff, handler->GetTrinityString(LANG_SYSTEMMESSAGE), args);
sWorld->SendServerMessage(SERVER_MSG_STRING, buff);
return true;
}
// announce to logged in GMs
static bool HandleGMAnnounceCommand(ChatHandler* /*handler*/, char const* args)
{
if (!*args)
return false;
sWorld->SendGMText(LANG_GM_BROADCAST, args);
return true;
}
// notification player at the screen
static bool HandleNotifyCommand(ChatHandler* handler, char const* args)
{
if (!*args)
return false;
std::string str = handler->GetTrinityString(LANG_GLOBAL_NOTIFY);
str += args;
sWorld->SendGlobalMessage(WorldPackets::Chat::PrintNotification(str).Write());
return true;
}
// notification GM at the screen
static bool HandleGMNotifyCommand(ChatHandler* handler, char const* args)
{
if (!*args)
return false;
std::string str = handler->GetTrinityString(LANG_GM_NOTIFY);
str += args;
sWorld->SendGlobalGMMessage(WorldPackets::Chat::PrintNotification(str).Write());
return true;
}
// Enable\Dissable accept whispers (for GM)
static bool HandleWhispersCommand(ChatHandler* handler, char const* args)
{
if (!*args)
{
handler->PSendSysMessage(LANG_COMMAND_WHISPERACCEPTING, handler->GetSession()->GetPlayer()->isAcceptWhispers() ? handler->GetTrinityString(LANG_ON) : handler->GetTrinityString(LANG_OFF));
return true;
}
std::string argStr = (char*)args;
// whisper on
if (argStr == "on")
{
handler->GetSession()->GetPlayer()->SetAcceptWhispers(true);
handler->SendSysMessage(LANG_COMMAND_WHISPERON);
return true;
}
// whisper off
if (argStr == "off")
{
// Remove all players from the Gamemaster's whisper whitelist
handler->GetSession()->GetPlayer()->ClearWhisperWhiteList();
handler->GetSession()->GetPlayer()->SetAcceptWhispers(false);
handler->SendSysMessage(LANG_COMMAND_WHISPEROFF);
return true;
}
handler->SendSysMessage(LANG_USE_BOL);
handler->SetSentErrorMessage(true);
return false;
}
};
void AddSC_message_commandscript()
{
new message_commandscript();
}
| 412 | 0.945575 | 1 | 0.945575 | game-dev | MEDIA | 0.518258 | game-dev | 0.859038 | 1 | 0.859038 |
00-Evan/shattered-pixel-dungeon | 10,729 | core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/levels/LastLevel.java | /*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* Shattered Pixel Dungeon
* Copyright (C) 2014-2025 Evan Debenham
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.shatteredpixel.shatteredpixeldungeon.levels;
import com.shatteredpixel.shatteredpixeldungeon.Assets;
import com.shatteredpixel.shatteredpixeldungeon.Dungeon;
import com.shatteredpixel.shatteredpixeldungeon.Statistics;
import com.shatteredpixel.shatteredpixeldungeon.actors.Actor;
import com.shatteredpixel.shatteredpixeldungeon.actors.Char;
import com.shatteredpixel.shatteredpixeldungeon.actors.mobs.Mob;
import com.shatteredpixel.shatteredpixeldungeon.items.Amulet;
import com.shatteredpixel.shatteredpixeldungeon.levels.features.LevelTransition;
import com.shatteredpixel.shatteredpixeldungeon.levels.painters.Painter;
import com.shatteredpixel.shatteredpixeldungeon.messages.Messages;
import com.shatteredpixel.shatteredpixeldungeon.tiles.CustomTilemap;
import com.shatteredpixel.shatteredpixeldungeon.tiles.DungeonTileSheet;
import com.watabou.noosa.Group;
import com.watabou.noosa.Tilemap;
import com.watabou.noosa.audio.Music;
import com.watabou.utils.Bundle;
import com.watabou.utils.PathFinder;
import com.watabou.utils.Random;
import java.util.ArrayList;
import java.util.Arrays;
public class LastLevel extends Level {
{
color1 = 0x801500;
color2 = 0xa68521;
viewDistance = Math.min(4, viewDistance);
}
@Override
public void playLevelMusic() {
if (Statistics.amuletObtained) {
Music.INSTANCE.end();
} else {
Music.INSTANCE.play(Assets.Music.THEME_FINALE, true);
}
}
@Override
public String tilesTex() {
return Assets.Environment.TILES_HALLS;
}
@Override
public String waterTex() {
return Assets.Environment.WATER_HALLS;
}
@Override
public void create() {
super.create();
for (int i=0; i < length(); i++) {
int flags = Terrain.flags[map[i]];
if ((flags & Terrain.PIT) != 0){
passable[i] = avoid[i] = false;
solid[i] = true;
}
}
for (int i = (height-ROOM_TOP+2)*width; i < length; i++){
passable[i] = avoid[i] = false;
solid[i] = true;
}
for (int i = (height-ROOM_TOP+1)*width; i < length; i++){
if (i % width < 4 || i % width > 12 || i >= (length-width)){
discoverable[i] = false;
} else {
visited[i] = true;
}
}
}
private static final int ROOM_TOP = 10;
private static final int WIDTH = 16;
private static final int MID = WIDTH/2;
public static int AMULET_POS = 12*WIDTH + MID;
@Override
protected boolean build() {
setSize(16, 64);
Arrays.fill( map, Terrain.CHASM );
final int MID = width/2;
Painter.fill( this, 0, height-1, width, 1, Terrain.WALL );
Painter.fill( this, MID - 1, 10, 3, (height-11), Terrain.EMPTY);
Painter.fill( this, MID - 2, height - 3, 5, 1, Terrain.EMPTY);
Painter.fill( this, MID - 3, height - 2, 7, 1, Terrain.EMPTY);
int entrance = (height-ROOM_TOP) * width() + MID;
Painter.fill(this, 0, height - ROOM_TOP, width, 2, Terrain.WALL);
map[entrance] = Terrain.ENTRANCE;
map[entrance+width] = Terrain.ENTRANCE;
LevelTransition entry = new LevelTransition(this, entrance, LevelTransition.Type.REGULAR_ENTRANCE);
entry.left--;
entry.right++;
entry.bottom += 2;
transitions.add(entry);
Painter.fill(this, 0, height - ROOM_TOP + 2, width, 8, Terrain.EMPTY);
Painter.fill(this, MID-1, height - ROOM_TOP + 2, 3, 1, Terrain.ENTRANCE);
for (int i=0; i < length(); i++) {
if (map[i] == Terrain.EMPTY && Random.Int( 5 ) == 0) {
map[i] = Terrain.EMPTY_DECO;
}
}
Painter.fill( this, MID - 2, 9, 5, 7, Terrain.EMPTY);
Painter.fill( this, MID - 3, 10, 7, 5, Terrain.EMPTY);
feeling = Feeling.NONE;
viewDistance = 4;
CustomTilemap vis = new CustomFloor();
vis.setRect( 5, 0, 7, height - ROOM_TOP);
customTiles.add(vis);
vis = new CenterPieceVisuals();
vis.pos(0, height - ROOM_TOP);
customTiles.add(vis);
vis = new CenterPieceWalls();
vis.pos(0, height - ROOM_TOP-1);
customWalls.add(vis);
return true;
}
@Override
public Mob createMob() {
return null;
}
@Override
protected void createMobs() {
}
public Actor addRespawner() {
return null;
}
@Override
protected void createItems() {
drop( new Amulet(), AMULET_POS );
}
@Override
public int randomRespawnCell( Char ch ) {
ArrayList<Integer> candidates = new ArrayList<>();
for (int i : PathFinder.NEIGHBOURS8){
int cell = entrance() + i;
if (passable[cell]
&& Actor.findChar(cell) == null
&& (!Char.hasProp(ch, Char.Property.LARGE) || openSpace[cell])){
candidates.add(cell);
}
}
if (candidates.isEmpty()){
return -1;
} else {
return Random.element(candidates);
}
}
@Override
public String tileName( int tile ) {
switch (tile) {
case Terrain.WATER:
return Messages.get(HallsLevel.class, "water_name");
case Terrain.GRASS:
return Messages.get(HallsLevel.class, "grass_name");
case Terrain.HIGH_GRASS:
return Messages.get(HallsLevel.class, "high_grass_name");
case Terrain.STATUE:
case Terrain.STATUE_SP:
return Messages.get(HallsLevel.class, "statue_name");
case Terrain.REGION_DECO:
case Terrain.REGION_DECO_ALT:
return Messages.get(HallsLevel.class, "region_deco_name");
default:
return super.tileName( tile );
}
}
@Override
public String tileDesc(int tile) {
switch (tile) {
case Terrain.WATER:
return Messages.get(HallsLevel.class, "water_desc");
case Terrain.STATUE:
case Terrain.STATUE_SP:
return Messages.get(HallsLevel.class, "statue_desc");
case Terrain.BOOKSHELF:
return Messages.get(HallsLevel.class, "bookshelf_desc");
case Terrain.REGION_DECO:
case Terrain.REGION_DECO_ALT:
return Messages.get(HallsLevel.class, "region_deco_desc");
default:
return super.tileDesc( tile );
}
}
@Override
public Group addVisuals () {
super.addVisuals();
HallsLevel.addHallsVisuals(this, visuals);
return visuals;
}
@Override
public void restoreFromBundle(Bundle bundle) {
super.restoreFromBundle(bundle);
for (int i=0; i < length(); i++) {
int flags = Terrain.flags[map[i]];
if ((flags & Terrain.PIT) != 0){
passable[i] = avoid[i] = false;
solid[i] = true;
}
}
for (int i = (height-ROOM_TOP+2)*width; i < length; i++){
passable[i] = avoid[i] = false;
solid[i] = true;
}
for (int i = (height-ROOM_TOP+1)*width; i < length; i++){
if (i % width < 4 || i % width > 12 || i >= (length-width)){
discoverable[i] = false;
} else {
visited[i] = true;
}
}
}
public static class CustomFloor extends CustomTilemap {
{
texture = Assets.Environment.HALLS_SP;
}
private static final int[] CANDLES = new int[]{
-1, 42, 46, 46, 46, 43, -1,
42, 46, 46, 46, 46, 46, 43,
46, 46, 45, 19, 44, 46, 46,
46, 46, 19, 19, 19, 46, 46,
46, 46, 43, 19, 42, 46, 46,
44, 46, 46, 19, 46, 46, 45,
-1, 44, 45, 19, 44, 45, -1
};
@Override
public Tilemap create() {
Tilemap v = super.create();
int candlesStart = AMULET_POS - 3 - 3*Dungeon.level.width();
int cell = tileX + tileY * Dungeon.level.width();
int[] map = Dungeon.level.map;
int[] data = new int[tileW*tileH];
for (int i = 0; i < data.length; i++){
if (i % tileW == 0){
cell = tileX + (tileY + i / tileW) * Dungeon.level.width();
}
if (cell == candlesStart){
for (int candle : CANDLES) {
if (data[i] == 0) data[i] = candle;
if (data[i] == 46 && DungeonTileSheet.tileVariance[cell] >= 50){
data[i] ++;
}
if (Statistics.amuletObtained && data[i] > 40){
data[i] += 8;
}
if (map[cell] != Terrain.CHASM && map[cell+Dungeon.level.width] == Terrain.CHASM) {
data[i+tileW] = 6;
}
i++;
cell++;
if (i % tileW == 0){
cell = tileX + (tileY + i / tileW) * Dungeon.level.width();
}
}
}
if (map[cell] == Terrain.EMPTY_DECO) {
if (Statistics.amuletObtained){
data[i] = 31;
} else {
data[i] = 27;
}
} else if (map[cell] == Terrain.EMPTY) {
data[i] = 19;
} else if (data[i] == 0) {
data[i] = -1;
}
cell++;
}
v.map( data, tileW );
return v;
}
}
public static class CenterPieceVisuals extends CustomTilemap {
{
texture = Assets.Environment.HALLS_SP;
tileW = 16;
tileH = 10;
}
private static final int[] map = new int[]{
-1, -1, -1, -1, -1, -1, -1, -1, 19, -1, -1, -1, -1, -1, -1, -1,
0, 0, 0, 0, 8, 9, 10, 11, 19, 11, 12, 13, 14, 0, 0, 0,
0, 0, 0, 0, 16, 17, 18, 31, 19, 31, 20, 21, 22, 0, 0, 0,
0, 0, 0, 0, 24, 25, 26, 19, 19, 19, 28, 29, 30, 0, 0, 0,
0, 0, 0, 0, 24, 25, 26, 19, 19, 19, 28, 29, 30, 0, 0, 0,
0, 0, 0, 0, 24, 25, 26, 19, 19, 19, 28, 29, 30, 0, 0, 0,
0, 0, 0, 0, 24, 25, 34, 35, 35, 35, 34, 29, 30, 0, 0, 0,
0, 0, 0, 0, 40, 41, 36, 36, 36, 36, 36, 40, 41, 0, 0, 0,
0, 0, 0, 0, 48, 49, 36, 36, 36, 36, 36, 48, 49, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
};
@Override
public Tilemap create() {
Tilemap v = super.create();
v.map(map, tileW);
return v;
}
}
public static class CenterPieceWalls extends CustomTilemap {
{
texture = Assets.Environment.HALLS_SP;
tileW = 16;
tileH = 9;
}
private static final int[] map = new int[]{
4, 4, 4, 4, 4, 4, 4, 5, 7, 3, 4, 4, 4, 4, 4, 4,
0, 0, 0, 0, 0, 0, 0, 1, 15, 2, 0, 0, 0, 0, 0, 0,
-1, -1, -1, -1, -1, -1, -1, -1, 23, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, 32, 33, -1, -1, -1, -1, -1, 32, 33, -1, -1, -1,
-1, -1, -1, -1, 40, 41, -1, -1, -1, -1, -1, 40, 41, -1, -1, -1,
};
@Override
public Tilemap create() {
Tilemap v = super.create();
v.map(map, tileW);
return v;
}
}
}
| 412 | 0.929671 | 1 | 0.929671 | game-dev | MEDIA | 0.974056 | game-dev | 0.995938 | 1 | 0.995938 |
exult/exult | 4,990 | content/bgkeyring/src/headers/array_functions.uc | /*
*
* Copyright (C) 2006 The Exult Team
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
*
* This source file contains miscellaneous array functions.
*
* Author: Marzo Junior
* Last Modified: 2006-02-27
*/
//Returns a list of targets for friendly spells
var getFriendlyTargetList (var caster, var dist) {
if ((caster->get_npc_object()) in UI_get_party_list()) {
//Caster is in the party; return party:
return UI_get_party_list();
} else {
//Caster not in party
//Get all nearby NPCs:
var npclist = getNearbyNonPartyNPCs(dist);
var retlist = [];
//Get caster's alignment:
var align = caster->get_alignment();
for (npc in npclist) {
//For each NPC in the list,
if (align == npc->get_alignment()) {
//Add NPC to list if align matches caster's:
retlist = [retlist, npc];
}
}
if (align == 0) {
//Add party to list if caster is friendly:
retlist << UI_get_party_list();
}
return retlist;
}
}
//Returns a list of targets for offensive spells
var getEnemyTargetList (var caster, var dist) {
if ((caster->get_npc_object()) in UI_get_party_list()) {
//If caster in party, return all non-party NPCs:
return getNearbyNonPartyNPCs(dist);
} else {
//Caster not in party
//Get all nearby NPCs:
var npclist = getNearbyNonPartyNPCs(dist);
var retlist = [];
//Get caster's alignment:
var align = caster->get_alignment();
for (npc in npclist) {
//For each NPC in the list,
if (align != npc->get_alignment()) {
//Add NPC to list if align doesn't match caster's:
retlist = [retlist, npc];
}
}
if (align != 0) {
//Add party to list if caster is not friendly:
retlist << UI_get_party_list();
}
return retlist;
}
}
//Removes element # elemindex from the array and returns resulting array
var removeFromArrayByIndex (var array, var elemindex) {
//var count = 1;
var retarray = [];
for (elem in array with index) {
if (index != elemindex) {
retarray << elem;
}
}
return retarray;
}
//Given an NPC list, returns only those with a given flag set
var filterListByFlag(var list, var flag, var state) {
var ret_list = [];
for (npc in list) {
if (npc->get_item_flag(flag) == state) {
ret_list << npc;
}
}
return ret_list;
}
//Given an NPC list, returns only those equiped with a given set of objects
//in a given spot
var filterListByEquipedObject(var list, var shapes, var spot) {
var ret_list = [];
if (UI_get_array_size(shapes) == 1) {
shapes = [shapes];
}
for (npc in list) {
if ((npc->get_readied(spot))->get_item_shape() in shapes) {
ret_list << npc;
}
}
return ret_list;
}
//Given an NPC list, returns only those hit points less than (max hps)*frac/4
var filterListByRelHits(var list, var frac) {
var ret_list = [];
for (npc in list) {
var hps = 4*npc->get_npc_prop(HEALTH);
var str = npc->get_npc_prop(STRENGTH);
if (hps<str*frac) {
ret_list << npc;
}
}
return ret_list;
}
//Set-theoretical subtraction of sets; returns all the elements in list
//which are not in removes
var removeItemsFromList(var list, var removes) {
var newarray = [];
if (UI_get_array_size(removes) > 0) {
if (UI_get_array_size(removes) == 1) {
removes = [removes];
}
for (spell in list) {
if (!(spell in removes)) {
newarray << spell;
}
}
} else {
newarray = list;
}
return newarray;
}
//Set-theoretical intersection of sets; returns all the elements in list1
//which are also in list2
var intersectLists(var list1, var list2) {
var newarray = [];
if (UI_get_array_size(list2) > 0) {
if (UI_get_array_size(list2) == 1) {
list2 = [list2];
}
for (spell in list1) {
if (spell in list2) {
newarray << spell;
}
}
} else {
newarray = [];
}
return newarray;
}
var filterBodyList(var list, var body) {
var newarray = [];
if (UI_get_array_size(list) > 0) {
for (currbody in list) {
if (currbody->get_body_npc() != body->get_body_npc()) {
newarray << currbody;
}
}
} else {
newarray = [];
}
return newarray;
}
//Returns a version of <array> that has <obj> stripped from it.
var removeFromArray(var array, var obj) {
var newarray = [];
if (UI_get_array_size(array) > 0) {
for (curr in array) {
if (curr != obj) {
newarray << curr;
}
}
} else {
newarray = [];
}
return newarray;
}
| 412 | 0.957577 | 1 | 0.957577 | game-dev | MEDIA | 0.93843 | game-dev | 0.976617 | 1 | 0.976617 |
PacktPublishing/Mastering-Cpp-Game-Development | 3,222 | Chapter04/Include/bullet/BulletCollision/NarrowPhaseCollision/btDiscreteCollisionDetectorInterface.h | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef BT_DISCRETE_COLLISION_DETECTOR1_INTERFACE_H
#define BT_DISCRETE_COLLISION_DETECTOR1_INTERFACE_H
#include "LinearMath/btTransform.h"
#include "LinearMath/btVector3.h"
/// This interface is made to be used by an iterative approach to do TimeOfImpact calculations
/// This interface allows to query for closest points and penetration depth between two (convex) objects
/// the closest point is on the second object (B), and the normal points from the surface on B towards A.
/// distance is between closest points on B and closest point on A. So you can calculate closest point on A
/// by taking closestPointInA = closestPointInB + m_distance * m_normalOnSurfaceB
struct btDiscreteCollisionDetectorInterface
{
struct Result
{
virtual ~Result(){}
///setShapeIdentifiersA/B provides experimental support for per-triangle material / custom material combiner
virtual void setShapeIdentifiersA(int partId0,int index0)=0;
virtual void setShapeIdentifiersB(int partId1,int index1)=0;
virtual void addContactPoint(const btVector3& normalOnBInWorld,const btVector3& pointInWorld,btScalar depth)=0;
};
struct ClosestPointInput
{
ClosestPointInput()
:m_maximumDistanceSquared(btScalar(BT_LARGE_FLOAT))
{
}
btTransform m_transformA;
btTransform m_transformB;
btScalar m_maximumDistanceSquared;
};
virtual ~btDiscreteCollisionDetectorInterface() {};
//
// give either closest points (distance > 0) or penetration (distance)
// the normal always points from B towards A
//
virtual void getClosestPoints(const ClosestPointInput& input,Result& output,class btIDebugDraw* debugDraw,bool swapResults=false) = 0;
};
struct btStorageResult : public btDiscreteCollisionDetectorInterface::Result
{
btVector3 m_normalOnSurfaceB;
btVector3 m_closestPointInB;
btScalar m_distance; //negative means penetration !
btStorageResult() : m_distance(btScalar(BT_LARGE_FLOAT))
{
}
virtual ~btStorageResult() {};
virtual void addContactPoint(const btVector3& normalOnBInWorld,const btVector3& pointInWorld,btScalar depth)
{
if (depth < m_distance)
{
m_normalOnSurfaceB = normalOnBInWorld;
m_closestPointInB = pointInWorld;
m_distance = depth;
}
}
};
#endif //BT_DISCRETE_COLLISION_DETECTOR1_INTERFACE_H
| 412 | 0.877226 | 1 | 0.877226 | game-dev | MEDIA | 0.964302 | game-dev | 0.895184 | 1 | 0.895184 |
GodotHub/gype | 1,820 | src/support/typescript_saver.cpp | #include "support/typescript_saver.hpp"
#include "support/typescript.hpp"
#include <godot_cpp/classes/file_access.hpp>
#include <godot_cpp/classes/project_settings.hpp>
#include <godot_cpp/classes/resource.hpp>
#include <godot_cpp/classes/resource_saver.hpp>
#include <godot_cpp/classes/resource_uid.hpp>
using namespace godot;
TypeScriptSaver *TypeScriptSaver::singleton;
TypeScriptSaver *TypeScriptSaver::get_singleton() {
if (singleton) {
return singleton;
}
singleton = memnew(TypeScriptSaver);
if (likely(singleton)) {
ClassDB::_register_engine_singleton(TypeScriptSaver::get_class_static(), singleton);
}
return singleton;
}
Error TypeScriptSaver::_save(const Ref<Resource> &p_resource, const String &p_path, uint32_t p_flags) {
Ref<TypeScript> script = p_resource;
Ref<FileAccess> file = FileAccess::open(p_path, FileAccess::ModeFlags::WRITE);
String source_code = script->_get_source_code();
if (source_code != "") {
file->store_string(source_code);
}
file->close();
script->complie(false);
return Error::OK;
}
Error TypeScriptSaver::_set_uid(const String &p_path, int64_t p_uid) {
ResourceUID::get_singleton()->set_id(p_uid, p_path);
return OK;
}
bool TypeScriptSaver::_recognize(const Ref<Resource> &p_resource) const {
return true;
}
PackedStringArray TypeScriptSaver::_get_recognized_extensions(const Ref<Resource> &p_resource) const {
PackedStringArray ret = PackedStringArray();
ret.append("ts");
ret.append("js");
return ret;
}
bool TypeScriptSaver::_recognize_path(const Ref<Resource> &p_resource, const String &p_path) const {
return p_path.ends_with(".js") || p_path.ends_with(".ts");
}
godot::TypeScriptSaver::~TypeScriptSaver() {
if (singleton == this) {
ClassDB::_unregister_engine_singleton(TypeScriptSaver::get_class_static());
singleton = nullptr;
}
}
| 412 | 0.799997 | 1 | 0.799997 | game-dev | MEDIA | 0.598503 | game-dev | 0.757267 | 1 | 0.757267 |
p1pkin/demul | 42,738 | debug.c | /*
* Demul
* Copyright (C) 2006 Org, Demul Team
*
* Demul is not free software: you can't redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Demul isn't distributed in the hope that it will be useful,
* and WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
*/
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <process.h>
#include "debug.h"
#include "demul.h"
#include "memory.h"
#include "inifile.h"
#include "configure.h"
#ifdef DEMUL_DEBUG
// Private structures and definitions for entire module.
static HANDLE debug_thread;
u32 debug_active;
u32 debug_step_mode;
u32 debug_trace_mode;
u32 debug_exception_mode = 1;
u32 debug_run_after_break;
u32 debug_new_pc;
// debugger dimensions
#define DB_WIDTH 80
#define DB_HEIGHT 60
// debugger windows
#define DB_UPDATE_REGS (0x0001) // registers view window
#define DB_UPDATE_DATA (0x0002) // memory view window
#define DB_UPDATE_DISA (0x0004) // disassembly window
#define DB_UPDATE_MSGS (0x0008) // message history
#define DB_UPDATE_EDIT (0x0010) // command line
#define DB_UPDATE_STAT (0x0020) // status line
#define DB_UPDATE_ALL (0x003f) // all
#define DB_LINES 1024 // lines in message buffer
#define DB_LINELEN 256 // length of single line (including color codes)
#define DB_TOKENS 10 // max amount of command arguments
// breakpoint constants
#define BP_READ (0x00000001)
#define BP_WRITE (0x00000002)
#define BP_EXECUTE (0x00000004)
#define BP_ALL (0x00000007)
// current console window identifier
typedef enum FOCUSWND { WREGS = 0, WDATA, WDISA, WCONSOLE } FOCUSWND;
// current registers window mode (scroll by F6)
typedef enum REGWNDMODE { REGMOD_GPR = 0, REGMOD_FPR, REGMOD_MAX } REGWNDMODE;
typedef struct DebugWind {
u32 update; // update windows
FOCUSWND focus; // wregs, wdata, wdisa, wconsole
REGWNDMODE regmode; // register window mode
u32 data; // start address for data
u32 text; // start address for disa
u32 disa_cursor; // disa cursor
int show_stats; // show statistics, instead reg view. (Shift-F1 to toggle)
int regs_y; // Y registers window
int regs_h; // Height registsrs window
int data_y; // Y Data window
int data_h; // Height Data window
int disa_y; // Y Disassembler
int disa_h; // Height of Disassembler
int roll_y; // Y Scroller (updates automatically by recalcwnds() )
int roll_h; // Height scroller, updates automaically by recalcwnds()
int edit_y; // Y Edit Line
int edit_h; // Editor Line Height
int stat_y; // Y Status Line
int stat_h; // Status Line Height
u32 visible; // visible windows
} DebugWind;
typedef struct DebugRoller {
char data[DB_LINES][DB_LINELEN]; // scrolling lines
int rollpos; // Where to read (len = wind.roll_h-1)
int viewpos; // Current position of "window" which transfers to CON.buf
char statusline[256]; // console status line
char editline[DB_LINELEN]; // edit line
int editpos; // position to next char in edit line
int editlen; // edit line len
char history[256][DB_LINELEN]; // command history
int historypos; // command history position
int historycur; // current command history position
bool autoscroll; // if true, then viewpos = rollpos-1
} DebugRoller;
static DebugWind wind;
static DebugRoller roll;
int db_wraproll(int roll, int value);
void db_recalc_wnds();
void db_status(char *txt);
void db_set_autoscroll(bool value);
void db_change_focus(FOCUSWND newfocus);
void db_update(u32 mask); // check areas for refresh
void db_refresh(void); // do actual refresh for checked areas
void db_memorize_cpu_regs();
void db_update_registers();
void db_disa_reset(void);
bool db_disa_cur_visible(void);
void db_set_disa_cur(u32 addr);
void db_disa_key(char ch, int ctrl);
void db_update_disa_window(void);
void db_data_key(char ch, int ctrl);
void db_update_dump_window(void);
u32 FASTCALL db_search_breakpoint(u32 cond, u32 eaddr, u32 align);
void db_add_breakpoint(u32 cond, u32 eaddr, u32 range);
void db_clear_breakpoint(u32 number);
void db_clear_breakpoints(void);
void db_list_breakpoints(void);
void db_keep_updated(void);
void db_command(char *line);
// ---------------------------------------------------------------------------
// Regs.
// register memory
static SH4 sh4_old;
typedef struct {
char *name;
u32 x;
u32 y;
u32 *value;
u32 *old_value;
} GENREGS;
static void print_reg(GENREGS reg) {
if (*reg.value != *reg.old_value) {
ConPrintfAt(reg.x, reg.y + wind.regs_y + 1, CC_CYAN "%-3s: " CC_GREEN "%08X", reg.name, *reg.value);
*reg.old_value = *reg.value;
} else
ConPrintfAt(reg.x, reg.y + wind.regs_y + 1, CC_CYAN "%-3s: " CC_NORM "%08X", reg.name, *reg.value);
}
static GENREGS gen_regs[] = {
{ "R0", 0, 0, &sh4.r[0], &sh4_old.r[0] },
{ "R1", 0, 1, &sh4.r[1], &sh4_old.r[1] },
{ "R2", 0, 2, &sh4.r[2], &sh4_old.r[2] },
{ "R3", 0, 3, &sh4.r[3], &sh4_old.r[3] },
{ "R4", 0, 4, &sh4.r[4], &sh4_old.r[4] },
{ "R5", 0, 5, &sh4.r[5], &sh4_old.r[5] },
{ "R6", 0, 6, &sh4.r[6], &sh4_old.r[6] },
{ "R7", 0, 7, &sh4.r[7], &sh4_old.r[7] },
{ "R8", 0, 8, &sh4.r[8], &sh4_old.r[8] },
{ "R9", 0, 9, &sh4.r[9], &sh4_old.r[9] },
{ "R10", 0, 10, &sh4.r[10], &sh4_old.r[10] },
{ "R11", 0, 11, &sh4.r[11], &sh4_old.r[11] },
{ "R12", 0, 12, &sh4.r[12], &sh4_old.r[12] },
{ "R13", 0, 13, &sh4.r[13], &sh4_old.r[13] },
{ "R14", 0, 14, &sh4.r[14], &sh4_old.r[14] },
{ "R15", 0, 15, &sh4.r[15], &sh4_old.r[15] },
{ "R0.B", 15, 0, &sh4.r[16], &sh4_old.r[16] },
{ "R1.B", 15, 1, &sh4.r[17], &sh4_old.r[17] },
{ "R2.B", 15, 2, &sh4.r[18], &sh4_old.r[18] },
{ "R3.B", 15, 3, &sh4.r[19], &sh4_old.r[19] },
{ "R4.B", 15, 4, &sh4.r[20], &sh4_old.r[20] },
{ "R5.B", 15, 5, &sh4.r[21], &sh4_old.r[21] },
{ "R6.B", 15, 6, &sh4.r[22], &sh4_old.r[22] },
{ "R7.B", 15, 7, &sh4.r[23], &sh4_old.r[23] },
{ "MACH", 15, 9, &sh4.mach, &sh4_old.mach },
{ "MACL", 15, 10, &sh4.macl, &sh4_old.macl },
{ "FPUL", 15, 11, &sh4.fpul, &sh4_old.fpul },
{ "PR ", 15, 12, &sh4.pr, &sh4_old.pr },
{ "PC ", 15, 13, &sh4.pc, &sh4_old.pc },
{ "SR ", 15, 14, &sh4.sr.all, &sh4_old.sr.all },
{ "SSR", 31, 0, &sh4.ssr, &sh4_old.ssr },
{ "SPC", 31, 1, &sh4.spc, &sh4_old.spc },
{ "SGR", 31, 2, &sh4.sgr, &sh4_old.sgr },
{ "GBR", 31, 3, &sh4.gbr, &sh4_old.gbr },
{ "DBR", 31, 4, &sh4.dbr, &sh4_old.dbr },
{ "VBR", 31, 5, &sh4.vbr, &sh4_old.vbr },
};
static int gen_regs_num = sizeof(gen_regs) / sizeof(GENREGS);
static void db_print_gprs() {
int i;
for (i = 0; i < gen_regs_num; i++)
print_reg(gen_regs[i]);
}
// ---
static GENREGS fp_regs[] = {
{ "FR0 ", 0, 0, &sh4.flti[0], &sh4_old.flti[0] },
{ "FR1 ", 0, 1, &sh4.flti[1], &sh4_old.flti[1] },
{ "FR2 ", 0, 2, &sh4.flti[2], &sh4_old.flti[2] },
{ "FR3 ", 0, 3, &sh4.flti[3], &sh4_old.flti[3] },
{ "FR4 ", 0, 4, &sh4.flti[4], &sh4_old.flti[4] },
{ "FR5 ", 0, 5, &sh4.flti[5], &sh4_old.flti[5] },
{ "FR6 ", 0, 6, &sh4.flti[6], &sh4_old.flti[6] },
{ "FR7 ", 0, 7, &sh4.flti[7], &sh4_old.flti[7] },
{ "FR8 ", 0, 8, &sh4.flti[8], &sh4_old.flti[8] },
{ "FR9 ", 0, 9, &sh4.flti[9], &sh4_old.flti[9] },
{ "FR10", 0, 10, &sh4.flti[10], &sh4_old.flti[10] },
{ "FR11", 0, 11, &sh4.flti[11], &sh4_old.flti[11] },
{ "FR12", 0, 12, &sh4.flti[12], &sh4_old.flti[12] },
{ "FR13", 0, 13, &sh4.flti[13], &sh4_old.flti[13] },
{ "FR14", 0, 14, &sh4.flti[14], &sh4_old.flti[14] },
{ "FR15", 0, 15, &sh4.flti[15], &sh4_old.flti[15] },
{ "XR0 ", 16, 0, &sh4.flti[16], &sh4_old.flti[16] },
{ "XR1 ", 16, 1, &sh4.flti[17], &sh4_old.flti[17] },
{ "XR2 ", 16, 2, &sh4.flti[18], &sh4_old.flti[18] },
{ "XR3 ", 16, 3, &sh4.flti[19], &sh4_old.flti[19] },
{ "XR4 ", 16, 4, &sh4.flti[20], &sh4_old.flti[20] },
{ "XR5 ", 16, 5, &sh4.flti[21], &sh4_old.flti[21] },
{ "XR6 ", 16, 6, &sh4.flti[22], &sh4_old.flti[22] },
{ "XR7 ", 16, 7, &sh4.flti[23], &sh4_old.flti[23] },
{ "XR8 ", 16, 8, &sh4.flti[24], &sh4_old.flti[24] },
{ "XR9 ", 16, 9, &sh4.flti[25], &sh4_old.flti[25] },
{ "XR10", 16, 10, &sh4.flti[26], &sh4_old.flti[26] },
{ "XR11", 16, 11, &sh4.flti[27], &sh4_old.flti[27] },
{ "XR12", 16, 12, &sh4.flti[28], &sh4_old.flti[28] },
{ "XR13", 16, 13, &sh4.flti[29], &sh4_old.flti[29] },
{ "XR14", 16, 14, &sh4.flti[30], &sh4_old.flti[30] },
{ "XR15", 16, 15, &sh4.flti[31], &sh4_old.flti[31] },
{ "FPUL ", 32, 0, &sh4.fpul, &sh4_old.fpul },
{ "FPSCR", 32, 1, &sh4.fpscr.all, &sh4_old.fpscr.all },
};
static int fp_regs_num = sizeof(fp_regs) / sizeof(GENREGS);
static void db_print_fprs(void) {
int i;
for (i = 0; i < fp_regs_num; i++)
print_reg(fp_regs[i]);
}
// ---
void db_memorize_cpu_regs() {
memcpy(&sh4_old, &sh4, sizeof(SH4));
}
void db_update_registers() {
if (wind.show_stats) return; // show statistics instead registers.
ConFillRegion(wind.regs_y, 1, CC_BLACK CB_CYAN "-");
if (wind.focus == WREGS) ConPrintfAt(0, wind.regs_y, CC_WHITE CB_CYAN "\x1f");
ConPrintfAt(2, wind.regs_y, CC_BLACK CB_CYAN "F1");
switch (wind.regmode) {
case REGMOD_GPR: ConPrintfAt(6, wind.regs_y, CC_BLACK CB_CYAN " General Registers");
db_print_gprs();
break;
case REGMOD_FPR: ConPrintfAt(6, wind.regs_y, CC_BLACK CB_CYAN " Floating-Point Registers");
db_print_fprs();
break;
}
}
// ---------------------------------------------------------------------------
// Disassembly.
static s32 detect_branch(u32 eaddr, u16 instr) {
switch (instr & 0xF000) {
case 0x8000:
switch (instr & 0x0F00) {
case 0x0F00:
case 0x0B00:
if (!sh4.sr.t)
if ((instr & 0x0080))
return -1;
else
return 1;
else
return 0;
break;
case 0x0900:
case 0x0D00:
if (sh4.sr.t)
if (instr & 0x0080)
return -1;
else
return 1;
else
return 0;
break;
}
break;
case 0xA000:
case 0xB000:
if (instr & 0x0800)
return -1;
else
return 1;
break;
case 0x0000:
if ((instr & 0x00DF) == 0x0003) {
u32 n = (instr & 0x0F00) >> 8;
if (sh4.r[n] & 0x80000000)
return -1;
else
return 1;
}
break;
case 0x4000:
if ((instr & 0x00DF) == 0x000B) {
u32 n = (instr & 0x0F00) >> 8;
if (sh4.r[n] < eaddr)
return -1;
else
return 1;
}
break;
}
return 0;
}
static int disa_sub_h;
static int cpu_disa_line(int line, u32 instr, u32 eaddr, bool nomem) {
int addend = 1, detect;
int bg, bgcur, bgbp;
char *str, bgstr[16];
instr &= 0xFFFF;
// Dark magic for line background color :)
bgcur = (eaddr == wind.disa_cursor) ? (8) : (0);
bgbp = (db_search_breakpoint(BP_EXECUTE, eaddr, 2) != 0) ? (4) : (0);
bg = (eaddr == sh4.pc) ? (1) : (0);
bg = bg ^ bgcur ^ bgbp;
if (bg == 0) bg = 0x10; // black!
bgstr[0] = 0x2;
bgstr[1] = bg;
bgstr[2] = ' ';
bgstr[3] = 0;
ConFillRegion(line, 1, bgstr);
bgstr[2] = 0;
if (nomem) {
ConPrintfAt(0, line, CC_NORM "%s%08X ", bgstr, eaddr);
ConPrintfAt(10, line, CC_CYAN "%s???? ", bgstr);
ConPrintfAt(16, line, CC_NORM "%s???", bgstr);
return addend;
}
ConPrintfAt(0, line, CC_NORM "%s%08X ", bgstr, eaddr);
ConPrintfAt(10, line, CC_CYAN "%s%04X ", bgstr, instr);
// Disassemble SH4 Instruction
str = Disasm(eaddr, instr);
if (eaddr != sh4.pc)
ConPrintfAt(16, line, CC_NORM "%s%s", bgstr, str);
else {
detect = detect_branch(eaddr, instr);
ConPrintfAt(16, line, CC_NORM "%s%s%s", bgstr, str, detect == 0 ? "" : detect < 0 ? "[JUMP UP]" : "[JUMP DOWN]");
}
return addend;
}
static void db_disa_cpu(void) {
int line, n;
u32 instr = 0, eaddr = wind.text;
disa_sub_h = 0;
memQuietMode(true);
for (line = wind.disa_y + 1; line < wind.disa_y + wind.disa_h; line++, eaddr += 2) {
bool nomem = false;
if (!EmuRunning) {
instr = 0;
nomem = true;
} else {
instr = memRead16(eaddr);
}
n = cpu_disa_line(line, instr, eaddr, nomem);
if (n > 1) disa_sub_h += n - 1;
line += n - 1;
}
memQuietMode(false);
}
// ---
// general
void db_disa_reset(void) {
disa_sub_h = 0;
}
bool db_disa_cur_visible(void) {
u32 limit;
limit = wind.text + (wind.disa_h - 1) * 2;
return((wind.disa_cursor < limit) && (wind.disa_cursor >= wind.text));
}
void db_set_disa_cur(u32 addr) {
wind.disa_cursor = addr & (~1);
if ((wind.disa_cursor >= (wind.text + (wind.disa_h - 1) * 2)) || (wind.disa_cursor < wind.text))
wind.text = wind.disa_cursor - (wind.disa_h & (~1));
db_update(DB_UPDATE_DISA);
}
void db_disa_key(char ch, int ctrl) {
disa_sub_h = 0;
if (ctrl & CK_HOME) {
db_set_disa_cur(sh4.pc);
} else if (ctrl & CK_END) {
} else if (ctrl & CK_UP) {
if (ctrl & CK_CTRL) {
if (wind.disa_h > 4) {
wind.disa_h--;
db_recalc_wnds();
}
db_update(DB_UPDATE_DISA);
return;
}
wind.disa_cursor -= 2;
if (wind.disa_cursor < wind.text) wind.text -= 2;
} else if (ctrl & CK_DOWN) {
if (ctrl & CK_CTRL) {
if (wind.roll_h > 10) {
wind.disa_h++;
db_recalc_wnds();
}
db_update(DB_UPDATE_DISA);
return;
}
wind.disa_cursor += 2;
if (wind.disa_cursor >= (wind.text + (wind.disa_h - disa_sub_h - 1) * 2)) wind.text += 2;
} else if (ctrl & CK_PGUP) {
wind.text -= 2 * wind.disa_h;
if (!db_disa_cur_visible()) wind.disa_cursor = wind.text;
} else if (ctrl & CK_PGDN) {
wind.text += 2 * (wind.disa_h - disa_sub_h);
if (!db_disa_cur_visible()) wind.disa_cursor = wind.text + (wind.disa_h - disa_sub_h - 2) * 2;
}
db_update(DB_UPDATE_DISA);
}
void db_update_disa_window(void) {
ConFillRegion(wind.disa_y, 1, CC_BLACK CB_CYAN "-");
if (wind.focus == WDISA) ConPrintfAt(0, wind.disa_y, CC_WHITE CB_CYAN "\x1f");
ConPrintfAt(2, wind.disa_y, CC_BLACK CB_CYAN "F3");
ConPrintfAt(6, wind.disa_y, CC_BLACK CB_CYAN " SH4");
ConPrintfAt(65, wind.disa_y, CC_BLACK CB_CYAN " PC: %08X", sh4.pc);
db_disa_cpu();
}
// ---------------------------------------------------------------------------
// Memory.
#define DB_RAM pram
#define DB_RAMSIZE (0x01000000)
static void hexbyte(u32 addr, char *buf) {
u8 byte[32];
if (EmuRunning == false) {
buf[0] = buf[1] = '?'; // unmapped
buf[2] = 0;
return;
}
memQuietMode(true);
byte[0] = (u8)memRead8(addr);
memQuietMode(false);
sprintf(buf, "%02X", byte[0]);
}
static void charbyte(u32 addr, char *buf) {
u8 byte[32];
if (EmuRunning == false) {
buf[0] = '?'; // unmapped
buf[1] = 0;
return;
}
buf[0] = '.'; buf[1] = 0;
memQuietMode(true);
byte[0] = (u8)memRead8(addr);
memQuietMode(false);
if ((byte[0] >= 32) && (byte[0] <= 127)) sprintf(buf, "%c\0", byte[0]);
}
static void db_dump_cpu(void) {
int row;
for (row = 0; row < wind.data_h - 1; row++) {
int col;
char buf[16];
ConPrintfAt(0, wind.data_y + row + 1, "%08X", wind.data + row * 16);
for (col = 0; col < 8; col++) {
hexbyte(wind.data + row * 16 + col, buf);
ConPrintfAt(10 + col * 3, wind.data_y + row + 1, buf);
}
for (col = 0; col < 8; col++) {
hexbyte(wind.data + row * 16 + col + 8, buf);
ConPrintfAt(35 + col * 3, wind.data_y + row + 1, buf);
}
for (col = 0; col < 16; col++) {
charbyte(wind.data + row * 16 + col, buf);
ConPrintfAt(60 + col, wind.data_y + row + 1, buf);
}
}
}
void db_data_key(char ch, int ctrl) {
long maxadr = DB_RAMSIZE - 1;
if (ctrl & CK_HOME) {
wind.data = 0;
} else if (ctrl & CK_END) {
wind.data = DB_RAMSIZE - ((wind.data_h - 1) * 16);
} else if (ctrl & CK_PGDN) {
wind.data += ((wind.data_h - 1) * 16);
} else if (ctrl & CK_PGUP) {
wind.data -= ((wind.data_h - 1) * 16);
} else if (ctrl & CK_UP) {
if (ctrl & CK_CTRL) {
if (wind.data_h > 3) {
wind.data_h--;
db_recalc_wnds();
}
} else wind.data -= 16;
} else if (ctrl & CK_DOWN) {
if (ctrl & CK_CTRL) {
if (wind.roll_h > 10) {
wind.data_h++;
db_recalc_wnds();
}
} else wind.data += 16;
}
db_update(DB_UPDATE_DATA);
}
void db_update_dump_window(void) {
ConFillRegion(wind.data_y, 1, CC_BLACK CB_CYAN "-");
if (wind.focus == WDATA) ConPrintfAt(0, wind.data_y, CC_WHITE CB_CYAN "\x1f");
ConPrintfAt(2, wind.data_y, CC_BLACK CB_CYAN "F2");
ConPrintfAt(6, wind.data_y, CC_BLACK CB_CYAN " Main memory");
db_dump_cpu();
}
// ---------------------------------------------------------------------------
// Message output.
static void con_add_roller_line(char *txt, int err) {
char line[0x1000], *ptr = txt;
// insert error color
if (err) {
sprintf(line, CC_BRED "Break: %s", txt);
ptr = line;
}
// roll console "roller" 1 line up
roll.rollpos = db_wraproll(roll.rollpos, 1);
strncpy(roll.data[roll.rollpos], ptr, DB_LINELEN - 1);
db_update(DB_UPDATE_MSGS);
}
void Printf(char *txt, ...) {
char buf[0x1000], *s, *p;
va_list arg;
if (debug_active == false) return;
sprintf(buf, CC_NORM);
va_start(arg, txt);
vsprintf(buf + strlen(CC_NORM), txt, arg);
va_end(arg);
buf[strlen(buf) + 1] = 0;
p = buf;
while (*p) {
while (*p && *p == '\n') {
con_add_roller_line("", 0);
p++;
}
s = p;
while (*p && *p != '\n') p++;
*p = 0;
if (*s) con_add_roller_line(s, 0);
p++;
}
}
// ---
// helpers
int db_wraproll(int roll, int value) {
roll += value;
if (roll >= DB_LINES) return roll - DB_LINES;
else if (roll < 0) return roll + DB_LINES;
else return roll;
}
void db_recalc_wnds() {
wind.regs_y = 0;//+4;
if (wind.visible & DB_UPDATE_REGS)
wind.data_y = wind.regs_y + wind.regs_h;
else
wind.data_y = wind.regs_y;
if (wind.visible & DB_UPDATE_DATA)
wind.disa_y = wind.data_y + wind.data_h;
else
wind.disa_y = wind.data_y;
if (wind.visible & DB_UPDATE_DISA)
wind.roll_y = wind.disa_y + wind.disa_h;
else
wind.roll_y = wind.disa_y;
wind.roll_h = DB_HEIGHT - wind.roll_y - 2; // - statusline - editline
wind.stat_h = wind.edit_h = 1;
wind.edit_y = wind.roll_y + wind.roll_h;
wind.stat_y = wind.edit_y + 1;
ConFillRegion(0, DB_HEIGHT, CB_BLACK " ");
db_update(DB_UPDATE_ALL);
}
void db_status(char *txt) {
sprintf(roll.statusline, CB_CYAN CC_BLACK " %s\n", txt);
db_update(DB_UPDATE_STAT);
}
void db_set_autoscroll(bool value) {
roll.autoscroll = value;
if (value) db_status("Ready. Press PgUp to look behind.");
else db_status("Scroll Mode - Press PgUp, PgDown, Up, Down to scroll. Escape to back.");
}
void db_change_focus(FOCUSWND newfocus) {
FOCUSWND oldfocus = wind.focus;
if (oldfocus == newfocus)
return; // we dont need any repaint
wind.focus = newfocus;
switch (newfocus) { // switch focus to?
case WREGS: db_update(DB_UPDATE_REGS); break;
case WDATA: db_update(DB_UPDATE_DATA);
db_status("Memory view. Press Up, Down, PgUp, PgDown to scroll."); break;
case WDISA: db_update(DB_UPDATE_DISA);
db_status("Disassembly view. Press Up, Down, PgUp, PgDown to scroll."); break;
case WCONSOLE: db_update(DB_UPDATE_MSGS);
db_set_autoscroll(roll.autoscroll); break;
}
}
// ---
// roller window
static void update_scroll_window() {
int i, y, back, line;
// cleanup window and skip header line
ConFillRegion(wind.roll_y + 1, wind.roll_h - 1, " ");
ConFillRegion(wind.roll_y, 1, CB_CYAN CC_BLACK "-");
if (wind.focus == WCONSOLE) ConPrintfAt(0, wind.roll_y, CB_CYAN CC_WHITE "\x1f");
ConPrintfAt(2, wind.roll_y, CB_CYAN CC_BLACK "F4");
ConPrintfAt(6, wind.roll_y, CB_CYAN CC_BLACK " Console output");
// printing coord in buffer (skip header)
y = wind.roll_y + 1;
// shift backward
back = wind.roll_h - 1;
// where to get buffer line
line = (roll.autoscroll) ? (roll.rollpos - back) : (roll.viewpos - back);
line += 1;
for (i = 1; i < wind.roll_h; i++) {
if (line >= 0) ConPrintfAt(0, y, roll.data[line]);
line++;
y++;
}
}
// ---
// update processing
void db_update(u32 mask) {
wind.update |= mask;
}
void db_refresh(void) {
// registers
if (wind.update & DB_UPDATE_REGS) {
db_update_registers();
ConUpdateRegion(wind.regs_y, wind.regs_h);
}
// data dump window
if (wind.update & DB_UPDATE_DATA) {
db_update_dump_window();
ConUpdateRegion(wind.data_y, wind.data_h);
}
// disassembler window
if (wind.update & DB_UPDATE_DISA) {
db_update_disa_window();
ConUpdateRegion(wind.disa_y, wind.disa_h);
}
// message history
if (wind.update & DB_UPDATE_MSGS) {
update_scroll_window();
ConUpdateRegion(wind.roll_y, wind.roll_h);
}
// edit line
if (wind.update & DB_UPDATE_EDIT) {
ConFillRegion(wind.edit_y, 1, " ");
ConPrintfAt(0, wind.edit_y, "> ");
ConPrintfAt(2, wind.edit_y, roll.editline);
ConUpdateRegion(wind.edit_y, 1);
ConSetCursor(roll.editpos + 2, wind.edit_y);
}
// status line
if (wind.update & DB_UPDATE_STAT) {
ConFillRegion(wind.stat_y, 1, CB_CYAN " ");
ConPrintfAt(1, wind.stat_y, roll.statusline);
ConUpdateRegion(wind.stat_y, 1);
}
wind.update = 0;
}
// ---------------------------------------------------------------------------
// Console input.
// Sub-windows input
static void function_key(int ctrl) {
if (ctrl & CK_F(1)) {
if (wind.show_stats == false)
db_update(DB_UPDATE_REGS);
} else if (ctrl & CK_F(2))
db_change_focus(WDATA); // Data
else if (ctrl & CK_F(3))
db_change_focus(WDISA); // Disa
else if (ctrl & CK_F(4))
db_change_focus(WCONSOLE);
else if (ctrl & CK_F(6)) { // Switch regs
if (wind.show_stats) return;
wind.regmode = (REGWNDMODE)(((int)wind.regmode + 1) % REGMOD_MAX);
ConFillRegion(wind.regs_y, wind.regs_h, CB_BLACK " ");
db_update(DB_UPDATE_REGS);
}
//----
// runtime controls
else if (ctrl & CK_F(5)) { // toggle Go / Break (ALL)
if (debug_step_mode)
db_command("run");
else
db_command("pause");
} else if (ctrl & CK_F(8)) { // Set pc at cursor
db_command("pc");
} else if (ctrl & CK_F(9)) { // Set breakpoint at cursor
u32 idx;
idx = db_search_breakpoint(BP_EXECUTE, wind.disa_cursor, 2);
if (!idx)
db_add_breakpoint(BP_EXECUTE, wind.disa_cursor, 0);
else
db_clear_breakpoint(idx);
db_update(DB_UPDATE_DISA);
}
// else if(ctrl & CK_F(10)) // Step Over
// {
// db_command("thru");
// }
else if (ctrl & CK_F(11)) { // Step In
db_command("step");
} else if (ctrl & CK_F(12)) { // Skip
db_command("skip");
}
}
// ---
// Roller
// searching for beginning of each word
static void search_left() {
roll.editlen = (int)strlen(roll.editline);
// check editpos!=0 for possibility check [editpos-1]
if ((roll.editlen == 0) || (roll.editpos == 0)) return;
// we at beginning of the word? if so, move to the space
if ((roll.editline[roll.editpos] != 0x20) && (roll.editline[roll.editpos - 1] == 0x20)) roll.editpos--;
// note: no need check editpos!=0 here
if (roll.editline[roll.editpos] == 0x20) { // are we at space?
//search for first non-space
while ((roll.editpos != 0) && (roll.editline[roll.editpos] == 0x20)) roll.editpos--;
if (!roll.editpos) return;
}
// we at last char, search for first space now
while (roll.editpos != 0) {
// sure, editpos!=0 here, coz while check it first
if (roll.editline[roll.editpos - 1] == 0x20) return;
roll.editpos--;
}
}
static void search_right() {
roll.editlen = (int)strlen(roll.editline);
if ((roll.editlen == 0) || (roll.editpos == roll.editlen)) return;
if (roll.editline[roll.editpos] != 0x20) {
while (roll.editline[roll.editpos] != 0x20) {
if (roll.editpos == roll.editlen) return;
roll.editpos++;
}
}
while ((roll.editpos != roll.editlen) && (roll.editline[roll.editpos] == 0x20)) roll.editpos++;
}
static int testempty(char *str) {
int i, len = (int)strlen(str);
for (i = 0; i < len; i++) {
if (str[i] != 0x20) return 0;
}
return 1;
}
static void roll_edit_key(char ascii, int ctrl) {
if (ascii != CK_CONTROL) {
roll.editlen = (int)strlen(roll.editline);
if (roll.editlen >= 77) return;
else {
if (roll.editpos == roll.editlen) {
roll.editline[roll.editpos++] = ascii;
roll.editline[roll.editpos] = 0;
} else {
memmove(
roll.editline + roll.editpos + 1,
roll.editline + roll.editpos,
roll.editlen - roll.editpos + 1
);
roll.editline[roll.editpos++] = ascii;
}
db_update(DB_UPDATE_EDIT);
}
} else {
if (ctrl & CK_RETURN) {
roll.editlen = (int)strlen(roll.editline);
if (!roll.editlen) return;
if (testempty(roll.editline)) return;
strcpy(roll.history[roll.historypos], roll.editline);
roll.historypos++;
if (roll.historypos > 255) roll.historypos = 0;
roll.historycur = roll.historypos;
Printf(": %s", roll.editline);
db_command(roll.editline);
roll.editpos = roll.editlen = roll.editline[0] = 0;
db_update(DB_UPDATE_EDIT | DB_UPDATE_MSGS);
} else if (ctrl & CK_UP) {
if (!roll.autoscroll) {
roll.viewpos--;
if (roll.viewpos < 0) roll.viewpos = 0;
db_update(DB_UPDATE_MSGS);
} else {
if (--roll.historycur < 0) roll.historycur = 0;
else {
strcpy(roll.editline, roll.history[roll.historycur]);
roll.editpos = roll.editlen = (int)strlen(roll.editline);
db_update(DB_UPDATE_EDIT);
}
}
} else if (ctrl & CK_DOWN) {
if (!roll.autoscroll) {
roll.viewpos++;
if (roll.viewpos >= roll.rollpos) {
roll.viewpos = roll.rollpos;
db_set_autoscroll(true);
}
db_update(DB_UPDATE_MSGS);
} else {
if (++roll.historycur >= roll.historypos) {
roll.historycur = roll.historypos;
roll.editpos = roll.editlen = roll.editline[0] = 0;
db_update(DB_UPDATE_EDIT);
} else {
strcpy(roll.editline, roll.history[roll.historycur]);
roll.editpos = roll.editlen = (int)strlen(roll.editline);
db_update(DB_UPDATE_EDIT);
}
}
} else if (ctrl & CK_HOME) {
if (!roll.autoscroll) {
roll.viewpos = 0;
db_update(DB_UPDATE_MSGS);
} else {
roll.editpos = 0;
db_update(DB_UPDATE_EDIT);
}
} else if (ctrl & CK_END) {
if (!roll.autoscroll) {
roll.viewpos = roll.rollpos;
db_update(DB_UPDATE_MSGS);
} else {
roll.editpos = (int)strlen(roll.editline);
db_update(DB_UPDATE_EDIT);
}
} else if (ctrl & CK_LEFT) {
if (ctrl & CK_CTRL) search_left();
else if (roll.editpos) roll.editpos--;
db_update(DB_UPDATE_EDIT);
} else if (ctrl & CK_RIGHT) {
roll.editlen = (int)strlen(roll.editline);
if (roll.editlen && (roll.editpos != roll.editlen)) {
if (ctrl & CK_CTRL) search_right();
else if (roll.editpos < roll.editlen) roll.editpos++;
db_update(DB_UPDATE_EDIT);
}
} else if (ctrl & CK_BKSPACE) {
if (roll.editpos) {
roll.editlen = (int)strlen(roll.editline);
if (roll.editlen == roll.editpos) roll.editline[--roll.editpos] = 0;
else memmove(
roll.editline + roll.editpos - 1,
roll.editline + roll.editpos,
roll.editlen - roll.editpos + 1
), roll.editpos--;
db_update(DB_UPDATE_EDIT);
}
} else if (ctrl & CK_DEL) {
if (roll.editpos) {
roll.editlen = (int)strlen(roll.editline);
if (roll.editlen != roll.editpos) {
memmove(
roll.editline + roll.editpos,
roll.editline + roll.editpos + 1,
roll.editlen - roll.editpos - 1);
roll.editline[roll.editlen - 1] = '\0';
db_update(DB_UPDATE_EDIT);
}
}
} else if (ctrl & CK_ESC) {
if (!roll.autoscroll) {
db_set_autoscroll(true);
db_update(DB_UPDATE_MSGS);
} else {
roll.historycur = roll.historypos;
roll.editpos = roll.editlen = roll.editline[0] = 0;
db_update(DB_UPDATE_EDIT);
}
} else if (ctrl & CK_PGUP) {
if (roll.autoscroll) {
db_set_autoscroll(false);
roll.viewpos = roll.rollpos;
}
roll.viewpos -= 8;
if (roll.viewpos < 0) roll.viewpos = 0;
db_update(DB_UPDATE_MSGS);
} else if (ctrl & CK_PGDN) {
if (roll.autoscroll) {
db_set_autoscroll(false);
roll.viewpos = roll.rollpos;
}
roll.viewpos += 8;
if (roll.viewpos >= roll.rollpos) {
roll.viewpos = roll.rollpos;
db_set_autoscroll(true);
}
db_update(DB_UPDATE_MSGS);
}
}
}
// ---
static void virtual_key(char ascii, int ctrl) {
// functions F1..F12 and control
if ((ascii == CK_CONTROL) && (ctrl & CK_FKEYS)) {
function_key(ctrl);
return;
}
// switch focus to input line if symbol key
if ((ctrl & (CK_BKSPACE | 0)) || (ascii >= 0x20 && ascii < 256)) {
db_change_focus(WCONSOLE);
}
switch (wind.focus) {
case WREGS:
break;
case WDATA:
db_data_key(ascii, ctrl);
break;
case WDISA:
db_disa_key(ascii, ctrl);
break;
case WCONSOLE:
roll_edit_key(ascii, ctrl);
break;
}
}
void db_keep_updated(void) {
int ctrl;
while (debug_active) {
char ascii = ConPeekInput(&ctrl);
__asm nop
__asm nop
if (ascii != CK_NULL) virtual_key(ascii, ctrl);
__asm nop
__asm nop
db_refresh();
__asm nop
__asm nop
}
}
// ---------------------------------------------------------------------------
// Hooks and breakponts
typedef struct {
u32 number;
u32 cond;
u32 eaddr;
u32 range;
void *nextbreak;
void *prevbreak;
} BREAKPOINT;
static BREAKPOINT *first_breakpoint = NULL;
static BREAKPOINT *last_breakpoint = NULL;
static u32 idx, breakpoint_count;
u32 FASTCALL db_search_breakpoint(u32 cond, u32 eaddr, u32 align) {
if ((first_breakpoint != NULL) && cond) {
BREAKPOINT *tmpbp = first_breakpoint;
u32 mask = ~(align - 1);
while (tmpbp->nextbreak != NULL) {
if (tmpbp->cond & cond)
if (tmpbp->range) {
if ((tmpbp->eaddr <= eaddr) && (eaddr <= tmpbp->range)) return tmpbp->number;
} else
if ((tmpbp->eaddr & mask) == eaddr) return tmpbp->number;
tmpbp = tmpbp->nextbreak;
}
if (tmpbp->cond & cond)
if (tmpbp->range) {
if ((tmpbp->eaddr <= eaddr) && (eaddr <= tmpbp->range)) return tmpbp->number;
} else
if ((tmpbp->eaddr & mask) == eaddr) return tmpbp->number;
}
return 0;
}
void db_add_breakpoint(u32 cond, u32 eaddr, u32 range) {
if (first_breakpoint == NULL) {
breakpoint_count = 1;
first_breakpoint = malloc(sizeof(BREAKPOINT));
first_breakpoint->number = breakpoint_count;
first_breakpoint->cond = cond;
first_breakpoint->eaddr = eaddr;
first_breakpoint->range = range;
first_breakpoint->prevbreak = first_breakpoint;
first_breakpoint->nextbreak = NULL;
last_breakpoint = first_breakpoint;
} else {
BREAKPOINT *newbp = malloc(sizeof(BREAKPOINT));
newbp->number = ++breakpoint_count;
newbp->cond = cond;
newbp->eaddr = eaddr;
newbp->range = range;
newbp->prevbreak = last_breakpoint;
newbp->nextbreak = NULL;
last_breakpoint->nextbreak = newbp;
last_breakpoint = newbp;
}
}
void db_clear_breakpoints(void) {
BREAKPOINT *tmpbp = last_breakpoint;
if (tmpbp == NULL) return;
while (tmpbp->prevbreak != tmpbp) {
tmpbp = tmpbp->prevbreak;
free(tmpbp->nextbreak);
}
free(tmpbp);
first_breakpoint = NULL;
last_breakpoint = NULL;
}
void db_clear_breakpoint(u32 number) {
BREAKPOINT *tmpbp = first_breakpoint;
if (tmpbp == NULL) return;
if (last_breakpoint == first_breakpoint) {
free(first_breakpoint);
free(last_breakpoint);
first_breakpoint = NULL;
last_breakpoint = NULL;
return;
}
if (tmpbp->number == number) {
first_breakpoint = first_breakpoint->nextbreak;
first_breakpoint->prevbreak = first_breakpoint;
free(tmpbp);
return;
}
while (tmpbp->nextbreak != NULL) {
if (tmpbp->number == number) {
BREAKPOINT *next, *prev;
prev = tmpbp->prevbreak;
prev->nextbreak = tmpbp->nextbreak;
next = tmpbp->nextbreak;
next->prevbreak = tmpbp->prevbreak;
free(tmpbp);
return;
}
tmpbp = tmpbp->nextbreak;
}
if (tmpbp->number == number) {
last_breakpoint = last_breakpoint->prevbreak;
last_breakpoint->nextbreak = NULL;
free(tmpbp);
}
}
void db_list_breakpoints(void) {
if (first_breakpoint != NULL) {
BREAKPOINT *tmpbp = first_breakpoint;
while (tmpbp->nextbreak != NULL) {
if (tmpbp->range)
Printf(CC_CYAN "%3d" CC_WHITE " > %s%s%s %08X %08X\n",
tmpbp->number,
(tmpbp->cond & BP_READ) ? "r" : "-",
(tmpbp->cond & BP_WRITE) ? "w" : "-",
(tmpbp->cond & BP_EXECUTE) ? "x" : "-",
tmpbp->eaddr, tmpbp->range
);
else
Printf(CC_CYAN "%3d" CC_WHITE " > %s%s%s %08X\n",
tmpbp->number,
(tmpbp->cond & BP_READ) ? "r" : "-",
(tmpbp->cond & BP_WRITE) ? "w" : "-",
(tmpbp->cond & BP_EXECUTE) ? "x" : "-",
tmpbp->eaddr
);
tmpbp = tmpbp->nextbreak;
}
if (tmpbp->range)
Printf(CC_CYAN "%3d" CC_WHITE " > %s%s%s %08X %08X\n",
tmpbp->number,
(tmpbp->cond & BP_READ) ? "r" : "-",
(tmpbp->cond & BP_WRITE) ? "w" : "-",
(tmpbp->cond & BP_EXECUTE) ? "x" : "-",
tmpbp->eaddr, tmpbp->range
);
else
Printf(CC_CYAN "%3d" CC_WHITE " > %s%s%s %08X\n",
tmpbp->number,
(tmpbp->cond & BP_READ) ? "r" : "-",
(tmpbp->cond & BP_WRITE) ? "w" : "-",
(tmpbp->cond & BP_EXECUTE) ? "x" : "-",
tmpbp->eaddr
);
} else
Printf(CC_CYAN "Breakpoint list is empty!\n");
}
void db_load_breakpoints() {
/* IniFile iniFile;
if (!IniFile_open(&iniFile, DEMUL_NAME)) return false;
if(IniFile_exist(&iniFile))
{
u32 i;
breakpoint_count = IniFile_getLong(&iniFile, "debugger", "bpcount");
for(i=0; i<breakpoint_count; i++)
{
u32 cond, eaddr;
char bpname[16];
sprintf(bpname,"bp%dcond",i);
cond = IniFile_getLong(&iniFile, "debugger", bpname);
sprintf(bpname,"bp%deaddr",i);
eaddr = IniFile_getLong(&iniFile, "debugger", bpname);
db_add_breakpoint(cond, eaddr);
}
}*/
}
void db_save_breakpoints(void) {
/* IniFile iniFile;
if (!IniFile_open(&iniFile, DEMUL_NAME)) return false;
if(IniFile_exist(&iniFile))
{
if(first_breakpoint != NULL)
{
char bpname[16];
BREAKPOINT *tmpbp = first_breakpoint;
breakpoint_count = 1;
while(tmpbp->nextbreak != NULL)
{
sprintf(bpname,"bp%dcond",breakpoint_count);
IniFile_setLong(&iniFile, "debugger", bpname, tmpbp->cond);
sprintf(bpname,"bp%deaddr",breakpoint_count);
IniFile_setLong(&iniFile, "debugger", bpname, tmpbp->eaddr);
tmpbp = tmpbp->nextbreak;
breakpoint_count++;
}
sprintf(bpname,"bp%dcond",breakpoint_count);
IniFile_setLong(&iniFile, "debugger", bpname, tmpbp->cond);
sprintf(bpname,"bp%deaddr",breakpoint_count);
IniFile_setLong(&iniFile, "debugger", bpname, tmpbp->eaddr);
IniFile_setLong(&iniFile, "debugger", "bpcount", breakpoint_count);
}
}*/
}
u32 FASTCALL hookDebugExecute(u32 pc) {
debug_new_pc = pc;
if (debug_active) {
if (debug_trace_mode) {
db_set_disa_cur(pc);
db_update(DB_UPDATE_ALL);
debug_trace_mode = 0;
}
while (1) {
__asm nop // ms optimization must die!!!
__asm nop
if ((!debug_step_mode) || (debug_trace_mode)) {
__asm nop // ms optimization must die!!!
__asm nop
if ((!debug_run_after_break) && (idx = db_search_breakpoint(BP_EXECUTE, pc, 2))) {
__asm nop // ms optimization must die!!!
__asm nop
debug_step_mode = 1;
debug_run_after_break = 1;
db_set_disa_cur(pc);
db_update(DB_UPDATE_ALL);
Printf("Breakpoint #%d reached (execute)!", idx);
__asm nop // ms optimization must die!!!
__asm nop
} else break;
__asm nop // ms optimization must die!!!
__asm nop
}
__asm nop
__asm nop
}
}
debug_run_after_break = 0;
return debug_new_pc;
}
void FASTCALL hookDebugRead(u32 mem, u32 align) {
if (first_breakpoint != NULL)
if (idx = db_search_breakpoint(BP_READ, mem, align)) {
debug_step_mode = 1;
db_set_disa_cur(sh4.pc);
db_update(DB_UPDATE_ALL);
Printf("Breakpoint #%d reached (memory read)!", idx);
}
}
void FASTCALL hookDebugWrite(u32 mem, u32 align) {
if (first_breakpoint != NULL)
if (idx = db_search_breakpoint(BP_WRITE, mem, align)) {
debug_step_mode = 1;
db_set_disa_cur(sh4.pc);
db_update(DB_UPDATE_ALL);
Printf("Breakpoint #%d reached (memory write)!", idx);
}
}
void FASTCALL hookDebugException(void) {
if (debug_exception_mode) {
debug_step_mode = 1;
db_set_disa_cur(sh4.pc);
db_update(DB_UPDATE_ALL);
Printf("Processor exception!");
}
}
// ---------------------------------------------------------------------------
// Command Processor.
static char tokens[DB_TOKENS][DB_LINELEN]; // tokens parsed from command line
static int tokencount; // parsed tokens count
// command record
typedef struct DebugCmd {
char *name; // command
void (*callback)(void); // call after '%cmd% [arguments]', where arguments are placed
// in tokens array (see above).
int need_args; // need at least N arguments
char *helptext; // show after 'help %cmd%'
} DebugCmd;
// detect expression
static u32 db_convert_expression(char *str) {
u32 n, len = strlen(str);
strlwr(str);
if ((str[0] == 'r')) {
n = strtoul(&str[1], NULL, 10);
if (str[len - 1] != 'b')
return sh4.r[(n & 15)];
else
return sh4.r[(n & 7) + 16];
} else if ((str[0] == 'p') && (str[1] == 'r')) {
return sh4.pr;
}
return strtoul(str, NULL, 16);
}
#include "cmd.c"
// tokenize line into arguments
#define endl (line[p] == 0)
#define space (line[p] == 0x20)
#define quot (line[p] == '\'')
#define dquot (line[p] == '\"')
static bool db_tokenize(char *line) {
int p, start, end;
p = tokencount = start = end = 0;
memset(tokens, 0, sizeof(tokens));
// while not end line
while (!endl) {
// skip space first, if any
while (space) p++;
if (!endl && (quot || dquot)) { // quotation, need special case
p++;
start = p;
while (1) {
if (endl) {
Printf(CC_BRED "Open quotation.\n");
return false;
}
if (quot || dquot) {
end = p;
p++;
break;
} else p++;
}
if (tokencount >= DB_TOKENS) {
Printf(CC_BRED "Too many arguments (>%i) or need quotes.\n", DB_TOKENS);
return false;
}
strncpy(tokens[tokencount], line + start, end - start);
// make lower only first token
if (tokencount == 0) strlwr(tokens[tokencount]);
tokencount++;
} else if (!endl) {
start = p;
while (1) {
if (endl || space || quot || dquot) {
end = p;
break;
}
p++;
}
if (tokencount >= DB_TOKENS) {
Printf(CC_BRED "Too many arguments (>%i) or need quotes.\n", DB_TOKENS);
return false;
}
strncpy(tokens[tokencount++], line + start, end - start);
}
}
return true;
}
// execute command
void db_command(char *line) {
int i;
bool ok = db_tokenize(line); // depart command line to arguments.
if (!ok) return;
// look for command in command' list
for (i = 0; i < cmd_num; i++) {
if (!stricmp(tokens[0], cmd_list[i].name)) {
if (cmd_list[i].need_args > (tokencount - 1)) {
Printf(CC_GREEN "Command need at least %i argument(s). Type 'help %s' for more info.",
cmd_list[i].need_args, cmd_list[i].name);
return;
} else {
cmd_list[i].callback();
return;
}
}
}
Printf(CC_GREEN "Unknown command '%s', try 'help'.", tokens[0]);
}
// ---------------------------------------------------------------------------
void openDebug(void) {
debug_active = openConsole();
if (debug_active == false) return;
debug_thread = (HANDLE)_beginthread(db_keep_updated, 0, NULL);
if (debug_thread == INVALID_HANDLE_VALUE) return;
// db_load_breakpoints();
// Setup debugger windows layout
memset(&wind, 0, sizeof(wind));
memset(&roll, 0, sizeof(roll));
wind.visible = DB_UPDATE_ALL; // sub-windows
wind.focus = WCONSOLE;
wind.regs_h = 17;
wind.data_h = 8;
wind.disa_h = 19; // 16
db_recalc_wnds();
db_set_autoscroll(true); // roller
roll.rollpos = db_wraproll(0, -1);
wind.data = 0xA0000000;
db_set_disa_cur(0xA0000000);
db_disa_reset();
db_memorize_cpu_regs();
// show emulator version and copyright
#define BGR CB_GRAY
Printf(
BGR CC_CYAN CC_WHITE "This software comes with " CC_WHITE CB_BBLUE "ABSOLUTELY NO WARRANTY!!" BGR " \n"
BGR CC_CYAN CC_WHITE "You shouldnt mind if it'll fuck your system. I dont mind too. \n"
BGR CC_CYAN " \n"
BGR CC_CYAN CC_WHITE "Type " CC_WHITE CB_BBLUE "help" CC_WHITE BGR " to get first instructions. Type " CC_WHITE CB_BBLUE "help cmdname" CC_WHITE BGR " to get more \n"
BGR CC_CYAN CC_WHITE BGR "detailed information about commands. \n\n");
db_update(DB_UPDATE_ALL);
}
void closeDebug(void) {
if (debug_thread != INVALID_HANDLE_VALUE) {
TerminateThread(debug_thread, 1);
CloseHandle(debug_thread);
}
// db_save_breakpoints();
db_clear_breakpoints();
closeConsole();
Sleep(500);
debug_active = false;
}
#else // Stubs.
void Printf(char *format, ...) {
FILE *ofile;
char temp[2048];
va_list ap;
va_start(ap, format);
vsprintf(temp, format, ap);
ofile = fopen("stdout.txt", "ab");
fwrite(temp, 1, strlen(temp), ofile);
fclose(ofile);
va_end(ap);
}
#endif // DEMUL_DEBUG
void PrintfLog(char *format, ...) {
FILE *ofile;
char temp[2048];
va_list ap;
va_start(ap, format);
vsprintf(temp, format, ap);
ofile = fopen("stdout.txt", "ab");
fwrite(temp, 1, strlen(temp), ofile);
fclose(ofile);
va_end(ap);
}
#ifdef STAT_ENABLE
#define STAT_COL 8
#define STAT_ROW 65536 / STAT_COL
static LONGLONG statOpcodes[0x10000];
static u16 statOpcodesCycle[0x10000];
void statFlush() {
int i, j;
for (i = 0; i < STAT_ROW; i++) {
for (j = 0; j < STAT_COL; j++)
PrintfLog("%08x ", statOpcodes[i * STAT_COL + j]);
PrintfLog("\n");
}
memset(statOpcodes, 0, 0x10000);
}
void statUpdate(u16 code) {
code = db_mask_opcode(code);
ProfileStart(code);
}
void statFinalize(void) {
ProfileFinish();
}
static u16 codeStat;
static LARGE_INTEGER codeTime1;
static LARGE_INTEGER codeTime2;
void ProfileStart(u16 cs) {
QueryPerformanceCounter(&codeTime1);
codeStat = cs;
}
void ProfileFinish(void) {
LONGLONG d;
QueryPerformanceCounter(&codeTime2);
d = codeTime2.QuadPart - codeTime1.QuadPart;
if (statOpcodesCycle[codeStat] < 1) {
statOpcodesCycle[codeStat]++;
statOpcodes[codeStat] += d;
} else {
statOpcodesCycle[codeStat]++;
if (statOpcodesCycle[codeStat] < 65535) {
statOpcodesCycle[codeStat]++;
statOpcodes[codeStat] = ((statOpcodes[codeStat] * (statOpcodesCycle[codeStat] - 1)) + d) / statOpcodesCycle[codeStat];
}
}
// Printf("profile[%d] %d\n",n, d);
}
#endif
| 412 | 0.967695 | 1 | 0.967695 | game-dev | MEDIA | 0.775219 | game-dev | 0.858455 | 1 | 0.858455 |
pointfreeco/episode-code-samples | 2,205 | 0206-reducer-protocol-pt6/swift-composable-architecture/Examples/TicTacToe/tic-tac-toe/Tests/GameCoreTests/GameCoreTests.swift | import ComposableArchitecture
import GameCore
import XCTest
@MainActor
final class GameCoreTests: XCTestCase {
let store = TestStore(
initialState: GameState(
oPlayerName: "Blob Jr.",
xPlayerName: "Blob Sr."
),
reducer: gameReducer,
environment: GameEnvironment()
)
func testFlow_Winner_Quit() async {
await self.store.send(.cellTapped(row: 0, column: 0)) {
$0.board[0][0] = .x
$0.currentPlayer = .o
}
await self.store.send(.cellTapped(row: 2, column: 1)) {
$0.board[2][1] = .o
$0.currentPlayer = .x
}
await self.store.send(.cellTapped(row: 1, column: 0)) {
$0.board[1][0] = .x
$0.currentPlayer = .o
}
await self.store.send(.cellTapped(row: 1, column: 1)) {
$0.board[1][1] = .o
$0.currentPlayer = .x
}
await self.store.send(.cellTapped(row: 2, column: 0)) {
$0.board[2][0] = .x
}
await self.store.send(.quitButtonTapped)
}
func testFlow_Tie() async {
await self.store.send(.cellTapped(row: 0, column: 0)) {
$0.board[0][0] = .x
$0.currentPlayer = .o
}
await self.store.send(.cellTapped(row: 2, column: 2)) {
$0.board[2][2] = .o
$0.currentPlayer = .x
}
await self.store.send(.cellTapped(row: 1, column: 0)) {
$0.board[1][0] = .x
$0.currentPlayer = .o
}
await self.store.send(.cellTapped(row: 2, column: 0)) {
$0.board[2][0] = .o
$0.currentPlayer = .x
}
await self.store.send(.cellTapped(row: 2, column: 1)) {
$0.board[2][1] = .x
$0.currentPlayer = .o
}
await self.store.send(.cellTapped(row: 1, column: 2)) {
$0.board[1][2] = .o
$0.currentPlayer = .x
}
await self.store.send(.cellTapped(row: 0, column: 2)) {
$0.board[0][2] = .x
$0.currentPlayer = .o
}
await self.store.send(.cellTapped(row: 0, column: 1)) {
$0.board[0][1] = .o
$0.currentPlayer = .x
}
await self.store.send(.cellTapped(row: 1, column: 1)) {
$0.board[1][1] = .x
$0.currentPlayer = .o
}
await self.store.send(.playAgainButtonTapped) {
$0 = GameState(oPlayerName: "Blob Jr.", xPlayerName: "Blob Sr.")
}
}
}
| 412 | 0.847667 | 1 | 0.847667 | game-dev | MEDIA | 0.627116 | game-dev,testing-qa | 0.832589 | 1 | 0.832589 |
LiteLDev/LeviLamina | 2,220 | src-server/mc/world/level/block/HangingRootsBlock.h | #pragma once
#include "mc/_HeaderOutputPredefine.h"
// auto generated inclusion list
#include "mc/deps/core/utility/optional_ref.h"
#include "mc/world/level/block/BlockType.h"
// auto generated forward declare list
// clang-format off
class AABB;
class Block;
class BlockPos;
class BlockSource;
class Experiments;
class GetCollisionShapeInterface;
class IConstBlockSource;
namespace BlockEvents { class BlockQueuedTickEvent; }
// clang-format on
class HangingRootsBlock : public ::BlockType {
public:
// virtual functions
// NOLINTBEGIN
// vIndex: 5
virtual ::AABB getCollisionShape(
::Block const&,
::IConstBlockSource const&,
::BlockPos const&,
::optional_ref<::GetCollisionShapeInterface const>
) const /*override*/;
// vIndex: 79
virtual bool mayPlace(::BlockSource& region, ::BlockPos const& pos) const /*override*/;
// vIndex: 87
virtual void neighborChanged(::BlockSource& region, ::BlockPos const& pos, ::BlockPos const& neighborPos) const
/*override*/;
// vIndex: 138
virtual bool canSurvive(::BlockSource& region, ::BlockPos const& pos) const /*override*/;
// vIndex: 131
virtual void _addHardCodedBlockComponents(::Experiments const&) /*override*/;
// vIndex: 0
virtual ~HangingRootsBlock() /*override*/ = default;
// NOLINTEND
public:
// member functions
// NOLINTBEGIN
MCFOLD void tick(::BlockEvents::BlockQueuedTickEvent& eventData) const;
// NOLINTEND
public:
// virtual function thunks
// NOLINTBEGIN
MCFOLD ::AABB $getCollisionShape(
::Block const&,
::IConstBlockSource const&,
::BlockPos const&,
::optional_ref<::GetCollisionShapeInterface const>
) const;
MCFOLD bool $mayPlace(::BlockSource& region, ::BlockPos const& pos) const;
MCFOLD void $neighborChanged(::BlockSource& region, ::BlockPos const& pos, ::BlockPos const& neighborPos) const;
MCFOLD bool $canSurvive(::BlockSource& region, ::BlockPos const& pos) const;
MCAPI void $_addHardCodedBlockComponents(::Experiments const&);
// NOLINTEND
public:
// vftables
// NOLINTBEGIN
MCNAPI static void** $vftable();
// NOLINTEND
};
| 412 | 0.897745 | 1 | 0.897745 | game-dev | MEDIA | 0.623682 | game-dev | 0.569497 | 1 | 0.569497 |
EasyRPG/Player | 44,659 | tests/move_route.cpp | #include "game_player.h"
#include "doctest.h"
#include "options.h"
#include "game_map.h"
#include "game_vehicle.h"
#include "main_data.h"
#include "game_switches.h"
#include <climits>
#include <initializer_list>
#include <lcf/rpg/movecommand.h>
#include "test_move_route.h"
TEST_SUITE_BEGIN("MoveRoute");
lcf::rpg::MoveRoute MakeRoute(int code, bool repeat = false, bool skip = false) {
lcf::rpg::MoveRoute mr;
lcf::rpg::MoveCommand mc;
mc.command_id = code;
mr.move_commands = { mc };
mr.repeat = repeat;
mr.skippable = skip;
return mr;
}
lcf::rpg::MoveRoute MakeRoute(std::initializer_list<lcf::rpg::MoveCommand> cmds, bool repeat = false, bool skip = false) {
lcf::rpg::MoveRoute mr;
mr.move_commands = cmds;
mr.repeat = repeat;
mr.skippable = skip;
return mr;
}
static void testMoveRoute(
const Game_Character& ch,
bool paused, int move_frequency,
int stop_count, int max_stop_count,
int move_route_idx, bool overwritten, bool done,
const lcf::rpg::MoveRoute& mr)
{
CAPTURE(paused);
CAPTURE(move_frequency);
CAPTURE(stop_count);
CAPTURE(max_stop_count);
CAPTURE(move_route_idx);
CAPTURE(overwritten);
CAPTURE(done);
CAPTURE(mr);
REQUIRE_EQ(ch.IsPaused(), paused);
REQUIRE_EQ(ch.GetMoveFrequency(), move_frequency);
REQUIRE_EQ(ch.GetStopCount(), stop_count);
REQUIRE_EQ(ch.GetMaxStopCount(), max_stop_count);
REQUIRE_EQ(ch.GetMoveRouteIndex(), move_route_idx);
REQUIRE_EQ(ch.IsMoveRouteOverwritten(), overwritten);
REQUIRE_EQ(ch.IsMoveRouteFinished(), done);
REQUIRE_EQ(ch.GetMoveRoute(), mr);
REQUIRE_EQ(ch.IsStopCountActive(), stop_count < max_stop_count);
}
template <typename... Args>
static void testMoveRouteDir(const Game_Character& ch,
int dir, int face,
Args&&... args) {
CAPTURE(dir);
CAPTURE(face);
REQUIRE_EQ(ch.GetDirection(), dir);
REQUIRE_EQ(ch.GetFacing(), face);
testMoveRoute(ch, std::forward<Args>(args)...);
}
template <typename... Args>
static void testMoveRouteMove(const Game_Character& ch,
int x, int y, int remaining_step,
Args&&... args) {
CAPTURE(x);
CAPTURE(y);
CAPTURE(remaining_step);
REQUIRE_EQ(ch.GetX(), x);
REQUIRE_EQ(ch.GetY(), y);
REQUIRE_GE(ch.GetRemainingStep(), 0);
REQUIRE_EQ(ch.GetRemainingStep(), remaining_step);
REQUIRE(!ch.IsJumping());
if (remaining_step > 0) {
REQUIRE(ch.IsMoving());
} else {
REQUIRE(ch.IsStopping());
REQUIRE(!ch.IsMoving());
}
testMoveRouteDir(ch, std::forward<Args>(args)...);
}
template <typename... Args>
static void testMoveRouteJump(const Game_Character& ch,
int x, int y, int remaining_step,
bool is_jumping, int begin_jump_x, int begin_jump_y,
Args&&... args) {
CAPTURE(x);
CAPTURE(y);
CAPTURE(remaining_step);
CAPTURE(is_jumping);
CAPTURE(begin_jump_x);
CAPTURE(begin_jump_y);
REQUIRE_EQ(ch.GetX(), x);
REQUIRE_EQ(ch.GetY(), y);
REQUIRE_GE(ch.GetRemainingStep(), 0);
REQUIRE_EQ(ch.GetRemainingStep(), remaining_step);
REQUIRE_EQ(ch.GetBeginJumpX(), begin_jump_x);
REQUIRE_EQ(ch.GetBeginJumpY(), begin_jump_y);
if (remaining_step > 0) {
REQUIRE_EQ(ch.IsJumping(), is_jumping);
REQUIRE_EQ(ch.IsMoving(), !is_jumping);
} else {
REQUIRE(ch.IsStopping());
REQUIRE(!ch.IsJumping());
REQUIRE(!ch.IsMoving());
}
testMoveRouteDir(ch, std::forward<Args>(args)...);
}
TEST_CASE("DefaultMoveRoute") {
auto ch = MoveRouteVehicle();
testMoveRoute(ch, false, 2, 0, 0, 0, false, false, lcf::rpg::MoveRoute());
}
TEST_CASE("ForceMoveRouteEmpty") {
auto ch = MoveRouteVehicle();
ch.ForceMoveRoute(lcf::rpg::MoveRoute(), 2);
testMoveRoute(ch, false, 2, 0xFFFF, 128, 0, false, false, lcf::rpg::MoveRoute());
}
TEST_CASE("ForceMoveRouteSameFreq") {
auto ch = MoveRouteVehicle();
lcf::rpg::MoveRoute mr;
mr.move_commands.push_back({});
ch.ForceMoveRoute(mr, 2);
// Note: Same freq means don't reset max stop count
testMoveRoute(ch, false, 2, 0xFFFF, 0, 0, true, false, mr);
ch.CancelMoveRoute();
testMoveRoute(ch, false, 2, 0xFFFF, 128, 0, false, false, mr);
}
TEST_CASE("ForceMoveRouteDiffFreq") {
auto ch = MoveRouteVehicle();
auto mr = MakeRoute({{}});
mr.move_commands.push_back({});
ch.ForceMoveRoute(mr, 3);
testMoveRoute(ch, false, 3, 0xFFFF, 64, 0, true, false, mr);
// FIXME: Test original move frequency is robust to save games
ch.CancelMoveRoute();
testMoveRoute(ch, false, 2, 0xFFFF, 128, 0, false, false, mr);
}
static void testInvalidCmd(bool repeat, bool skip) {
auto ch = MoveRouteVehicle();
auto mr = MakeRoute(-1, repeat, skip);
ch.ForceMoveRoute(mr, 3);
testMoveRoute(ch, false, 3, 0xFFFF, 64, 0, true, false, mr);
ForceUpdate(ch);
if (repeat) {
testMoveRoute(ch, false, 3, 0xFFFF + 1, 64, 0, true, true, mr);
} else {
testMoveRoute(ch, false, 2, 0xFFFF + 1, 128, 1, false, false, mr);
}
}
TEST_CASE("TestMoveRouteInvalidCmd") {
const MapGuard mg;
testInvalidCmd(false, false);
testInvalidCmd(false, true);
testInvalidCmd(true, false);
testInvalidCmd(true, true);
}
template <bool success, bool repeat, bool skip>
static void testMove(lcf::rpg::MoveCommand::Code code, int x, int y, int dir, int face, int tx, int ty, int tdir, int tface, int px = 0, int py = 0) {
Main_Data::game_player->SetX(px);
Main_Data::game_player->SetY(py);
auto ch = MoveRouteVehicle();
ch.SetX(x);
ch.SetY(y);
ch.SetDirection(dir);
ch.SetFacing(face);
ch.SetAllowMovement(success);
auto mr = MakeRoute(static_cast<int>(code), repeat, skip);
CAPTURE(code);
CAPTURE(x);
CAPTURE(y);
CAPTURE(dir);
CAPTURE(face);
CAPTURE(tx);
CAPTURE(ty);
CAPTURE(tdir);
CAPTURE(tface);
CAPTURE(px);
CAPTURE(py);
CAPTURE(success);
CAPTURE(repeat);
CAPTURE(skip);
auto dx = tx - x;
auto dy = ty - y;
ch.ForceMoveRoute(mr, 3);
testMoveRouteMove(ch, x, y, 0, dir, face, false, 3, 0xFFFF, 64, 0, true, false, mr);
if (success) {
bool repeated = false;
for(int n = (repeat ? 3 : 1); n > 0; --n) {
CAPTURE(n);
for(int i = 224; i > 0; i -= 32) {
ForceUpdate(ch);
testMoveRouteMove(ch, tx, ty, i, tdir, tface, false, 3, 0, 64, 1, true, repeated, mr);
}
if (!repeat) {
ForceUpdate(ch);
testMoveRouteMove(ch, tx, ty, 0, tdir, tface, false, 2, 0, 128, 0, false, false, mr);
break;
}
repeated = true;
for (int i = 0; i <= 64; ++i) {
ForceUpdate(ch);
testMoveRouteMove(ch, tx, ty, 0, tdir, tface, false, 3, i, 64, 0, true, repeated, mr);
}
tx += dx;
ty += dy;
}
} else {
ForceUpdate(ch);
if (skip) {
if (repeat) {
for (int i = 1; i <= 3; ++i) {
testMoveRouteMove(ch, tx, ty, 0, tdir, tface, false, 3, 0xFFFF + i, 64, 0, true, true, mr);
ForceUpdate(ch);
}
} else {
testMoveRouteMove(ch, tx, ty, 0, tdir, tface, false, 2, 0xFFFF + 1, 128, 1, false, false, mr);
}
} else {
testMoveRouteMove(ch, tx, ty, 0, tdir, tface, false, 3, 0xFFFF + 1, 64, 0, true, false, mr);
}
}
}
template <typename... Args>
static void testMoveSuccess(const Args&... args) {
testMove<true, false, false>(args...);
testMove<true, false, true>(args...);
testMove<true, true, false>(args...);
testMove<true, true, true>(args...);
}
template <typename... Args>
static void testMoveSuccessNoRepeat(const Args&... args) {
testMove<true, false, false>(args...);
testMove<true, false, true>(args...);
}
static void testMoveFail(lcf::rpg::MoveCommand::Code code, int x, int y, int dir, int face, int tdir, int tface, int px = 0, int py = 0) {
testMove<false, false, false>(code, x, y, dir, face, x, y, tdir, tface, px, py);
testMove<false, true, false>(code, x, y, dir, face, x, y, tdir, tface, px, py);
}
static void testMoveSkip(lcf::rpg::MoveCommand::Code code, int x, int y, int dir, int face, int px = 0, int py = 0) {
testMove<false, false, true>(code, x, y, dir, face, x, y, dir, face, px, py);
testMove<false, true, true>(code, x, y, dir, face, x, y, dir, face, px, py);
}
TEST_CASE("CommandMove") {
const MapGuard mg;
testMoveSuccess(lcf::rpg::MoveCommand::Code::move_up, 8, 8, Down, Down, 8, 7, Up, Up);
testMoveSuccess(lcf::rpg::MoveCommand::Code::move_right, 8, 8, Down, Down, 9, 8, Right, Right);
testMoveSuccess(lcf::rpg::MoveCommand::Code::move_down, 8, 8, Down, Down, 8, 9, Down, Down);
testMoveSuccess(lcf::rpg::MoveCommand::Code::move_left, 8, 8, Down, Down, 7, 8, Left, Left);
}
TEST_CASE("CommandMoveFail") {
const MapGuard mg;
testMoveFail(lcf::rpg::MoveCommand::Code::move_up, 8, 8, Down, Down, Up, Up);
testMoveFail(lcf::rpg::MoveCommand::Code::move_right, 8, 8, Down, Down, Right, Right);
testMoveFail(lcf::rpg::MoveCommand::Code::move_down, 8, 8, Down, Down, Down, Down);
testMoveFail(lcf::rpg::MoveCommand::Code::move_left, 8, 8, Down, Down, Left, Left);
}
TEST_CASE("CommandMoveSkip") {
const MapGuard mg;
testMoveSkip(lcf::rpg::MoveCommand::Code::move_up, 8, 8, Down, Down);
testMoveSkip(lcf::rpg::MoveCommand::Code::move_right, 8, 8, Down, Down);
testMoveSkip(lcf::rpg::MoveCommand::Code::move_down, 8, 8, Down, Down);
testMoveSkip(lcf::rpg::MoveCommand::Code::move_left, 8, 8, Down, Down);
}
TEST_CASE("CommandMoveDiagonal") {
const MapGuard mg;
testMoveSuccess(lcf::rpg::MoveCommand::Code::move_upright, 8, 8, Up, Up, 9, 7, UpRight, Up);
testMoveSuccess(lcf::rpg::MoveCommand::Code::move_upright, 8, 8, Right, Right, 9, 7, UpRight, Right);
testMoveSuccess(lcf::rpg::MoveCommand::Code::move_upright, 8, 8, Down, Down, 9, 7, UpRight, Up);
testMoveSuccess(lcf::rpg::MoveCommand::Code::move_upright, 8, 8, Left, Left, 9, 7, UpRight, Right);
testMoveSuccess(lcf::rpg::MoveCommand::Code::move_downright, 8, 8, Up, Up, 9, 9, DownRight, Down);
testMoveSuccess(lcf::rpg::MoveCommand::Code::move_downright, 8, 8, Right, Right, 9, 9, DownRight, Right);
testMoveSuccess(lcf::rpg::MoveCommand::Code::move_downright, 8, 8, Down, Down, 9, 9, DownRight, Down);
testMoveSuccess(lcf::rpg::MoveCommand::Code::move_downright, 8, 8, Left, Left, 9, 9, DownRight, Right);
testMoveSuccess(lcf::rpg::MoveCommand::Code::move_downleft, 8, 8, Up, Up, 7, 9, DownLeft, Down);
testMoveSuccess(lcf::rpg::MoveCommand::Code::move_downleft, 8, 8, Right, Right, 7, 9, DownLeft, Left);
testMoveSuccess(lcf::rpg::MoveCommand::Code::move_downleft, 8, 8, Down, Down, 7, 9, DownLeft, Down);
testMoveSuccess(lcf::rpg::MoveCommand::Code::move_downleft, 8, 8, Left, Left, 7, 9, DownLeft, Left);
testMoveSuccess(lcf::rpg::MoveCommand::Code::move_upleft, 8, 8, Up, Up, 7, 7, UpLeft, Up);
testMoveSuccess(lcf::rpg::MoveCommand::Code::move_upleft, 8, 8, Right, Right, 7, 7, UpLeft, Left);
testMoveSuccess(lcf::rpg::MoveCommand::Code::move_upleft, 8, 8, Down, Down, 7, 7, UpLeft, Up);
testMoveSuccess(lcf::rpg::MoveCommand::Code::move_upleft, 8, 8, Left, Left, 7, 7, UpLeft, Left);
}
TEST_CASE("CommandMoveDiagonalFail") {
const MapGuard mg;
testMoveFail(lcf::rpg::MoveCommand::Code::move_upright, 8, 8, Up, Up, UpRight, Up);
testMoveFail(lcf::rpg::MoveCommand::Code::move_upright, 8, 8, Right, Right, UpRight, Right);
testMoveFail(lcf::rpg::MoveCommand::Code::move_upright, 8, 8, Down, Down, UpRight, Up);
testMoveFail(lcf::rpg::MoveCommand::Code::move_upright, 8, 8, Left, Left, UpRight, Right);
testMoveFail(lcf::rpg::MoveCommand::Code::move_downright, 8, 8, Up, Up, DownRight, Down);
testMoveFail(lcf::rpg::MoveCommand::Code::move_downright, 8, 8, Right, Right, DownRight, Right);
testMoveFail(lcf::rpg::MoveCommand::Code::move_downright, 8, 8, Down, Down, DownRight, Down);
testMoveFail(lcf::rpg::MoveCommand::Code::move_downright, 8, 8, Left, Left, DownRight, Right);
testMoveFail(lcf::rpg::MoveCommand::Code::move_downleft, 8, 8, Up, Up, DownLeft, Down);
testMoveFail(lcf::rpg::MoveCommand::Code::move_downleft, 8, 8, Right, Right, DownLeft, Left);
testMoveFail(lcf::rpg::MoveCommand::Code::move_downleft, 8, 8, Down, Down, DownLeft, Down);
testMoveFail(lcf::rpg::MoveCommand::Code::move_downleft, 8, 8, Left, Left, DownLeft, Left);
testMoveFail(lcf::rpg::MoveCommand::Code::move_upleft, 8, 8, Up, Up, UpLeft, Up);
testMoveFail(lcf::rpg::MoveCommand::Code::move_upleft, 8, 8, Right, Right, UpLeft, Left);
testMoveFail(lcf::rpg::MoveCommand::Code::move_upleft, 8, 8, Down, Down, UpLeft, Up);
testMoveFail(lcf::rpg::MoveCommand::Code::move_upleft, 8, 8, Left, Left, UpLeft, Left);
}
TEST_CASE("CommandMoveDiagonalSkip") {
const MapGuard mg;
testMoveSkip(lcf::rpg::MoveCommand::Code::move_upright, 8, 8, Up, Up);
testMoveSkip(lcf::rpg::MoveCommand::Code::move_upright, 8, 8, Right, Right);
testMoveSkip(lcf::rpg::MoveCommand::Code::move_upright, 8, 8, Down, Down);
testMoveSkip(lcf::rpg::MoveCommand::Code::move_upright, 8, 8, Left, Left);
testMoveSkip(lcf::rpg::MoveCommand::Code::move_downright, 8, 8, Up, Up);
testMoveSkip(lcf::rpg::MoveCommand::Code::move_downright, 8, 8, Right, Right);
testMoveSkip(lcf::rpg::MoveCommand::Code::move_downright, 8, 8, Down, Down);
testMoveSkip(lcf::rpg::MoveCommand::Code::move_downright, 8, 8, Left, Left);
testMoveSkip(lcf::rpg::MoveCommand::Code::move_downleft, 8, 8, Up, Up);
testMoveSkip(lcf::rpg::MoveCommand::Code::move_downleft, 8, 8, Right, Right);
testMoveSkip(lcf::rpg::MoveCommand::Code::move_downleft, 8, 8, Down, Down);
testMoveSkip(lcf::rpg::MoveCommand::Code::move_downleft, 8, 8, Left, Left);
testMoveSkip(lcf::rpg::MoveCommand::Code::move_upleft, 8, 8, Up, Up);
testMoveSkip(lcf::rpg::MoveCommand::Code::move_upleft, 8, 8, Right, Right);
testMoveSkip(lcf::rpg::MoveCommand::Code::move_upleft, 8, 8, Down, Down);
testMoveSkip(lcf::rpg::MoveCommand::Code::move_upleft, 8, 8, Left, Left);
}
TEST_CASE("CommandMoveForward") {
const MapGuard mg;
testMoveSuccess(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, Up, Up, 8, 7, Up, Up);
testMoveSuccess(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, Right, Right, 9, 8, Right, Right);
testMoveSuccess(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, Down, Down, 8, 9, Down, Down);
testMoveSuccess(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, Left, Left, 7, 8, Left, Left);
testMoveSuccess(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, UpRight, Up, 9, 7, UpRight, Up);
testMoveSuccess(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, UpRight, Right, 9, 7, UpRight, Right);
testMoveSuccess(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, DownRight, Down, 9, 9, DownRight, Down);
testMoveSuccess(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, DownRight, Right, 9, 9, DownRight, Right);
testMoveSuccess(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, UpLeft, Up, 7, 7, UpLeft, Up);
testMoveSuccess(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, UpLeft, Left, 7, 7, UpLeft, Left);
testMoveSuccess(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, DownLeft, Down, 7, 9, DownLeft, Down);
testMoveSuccess(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, DownLeft, Left, 7, 9, DownLeft, Left);
}
TEST_CASE("CommandMoveForwardFail") {
const MapGuard mg;
testMoveFail(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, Up, Up, Up, Up);
testMoveFail(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, Right, Right, Right, Right);
testMoveFail(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, Down, Down, Down, Down);
testMoveFail(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, Left, Left, Left, Left);
testMoveFail(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, UpRight, Up, UpRight, Up);
testMoveFail(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, UpRight, Right, UpRight, Right);
testMoveFail(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, DownRight, Down, DownRight, Down);
testMoveFail(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, DownRight, Right, DownRight, Right);
testMoveFail(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, UpLeft, Up, UpLeft, Up);
testMoveFail(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, UpLeft, Left, UpLeft, Left);
testMoveFail(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, DownLeft, Down, DownLeft, Down);
testMoveFail(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, DownLeft, Left, DownLeft, Left);
}
TEST_CASE("CommandMoveForwardSkip") {
const MapGuard mg;
testMoveSkip(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, Up, Up);
testMoveSkip(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, Right, Right);
testMoveSkip(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, Down, Down);
testMoveSkip(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, Left, Left);
testMoveSkip(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, UpRight, Up);
testMoveSkip(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, UpRight, Right);
testMoveSkip(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, DownRight, Down);
testMoveSkip(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, DownRight, Right);
testMoveSkip(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, UpLeft, Up);
testMoveSkip(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, UpLeft, Left);
testMoveSkip(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, DownLeft, Down);
testMoveSkip(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, DownLeft, Left);
}
TEST_CASE("CommandMoveRandom") {
// FIXME: TBD
}
static void testTurn(lcf::rpg::MoveCommand::Code code, int orig_dir, int dir, int face, int x = 0, int y = 0, int px = 0, int py = 0) {
Main_Data::game_player->SetX(px);
Main_Data::game_player->SetY(py);
auto ch = MoveRouteVehicle();
ch.SetX(x);
ch.SetY(y);
ch.SetDirection(orig_dir);
ch.SetFacing(orig_dir);
auto mr = MakeRoute(static_cast<int>(code));
CAPTURE(code);
CAPTURE(orig_dir);
CAPTURE(dir);
CAPTURE(face);
CAPTURE(x);
CAPTURE(y);
CAPTURE(px);
CAPTURE(py);
ch.ForceMoveRoute(mr, 2);
testMoveRouteDir(ch, orig_dir, orig_dir, false, 2, 0xFFFF, 0, 0, true, false, mr);
for(int i = 1; i <= 64; ++i) {
ForceUpdate(ch);
testMoveRouteDir(ch, dir, face, false, 2, i, 64, 1, true, false, mr);
}
ForceUpdate(ch);
testMoveRouteDir(ch, dir, face, false, 2, 65, 128, 1, false, false, mr);
}
TEST_CASE("CommandTurn") {
const MapGuard mg;
testTurn(lcf::rpg::MoveCommand::Code::face_up, Down, Up, Up);
testTurn(lcf::rpg::MoveCommand::Code::face_left, Down, Left, Left);
testTurn(lcf::rpg::MoveCommand::Code::face_right, Down, Right, Right);
testTurn(lcf::rpg::MoveCommand::Code::face_down, Down, Down, Down);
testTurn(lcf::rpg::MoveCommand::Code::turn_180_degree, Down, Up, Up);
testTurn(lcf::rpg::MoveCommand::Code::turn_180_degree, Up, Down, Down);
testTurn(lcf::rpg::MoveCommand::Code::turn_180_degree, Left, Right, Right);
testTurn(lcf::rpg::MoveCommand::Code::turn_180_degree, Right, Left, Left);
testTurn(lcf::rpg::MoveCommand::Code::turn_90_degree_right, Down, Left, Left);
testTurn(lcf::rpg::MoveCommand::Code::turn_90_degree_right, Left, Up, Up);
testTurn(lcf::rpg::MoveCommand::Code::turn_90_degree_right, Up, Right, Right);
testTurn(lcf::rpg::MoveCommand::Code::turn_90_degree_right, Right, Down, Down);
testTurn(lcf::rpg::MoveCommand::Code::turn_90_degree_left, Down, Right, Right);
testTurn(lcf::rpg::MoveCommand::Code::turn_90_degree_left, Right, Up, Up);
testTurn(lcf::rpg::MoveCommand::Code::turn_90_degree_left, Up, Left, Left);
testTurn(lcf::rpg::MoveCommand::Code::turn_90_degree_left, Left, Down, Down);
}
TEST_CASE("CommandTurnRandom") {
const MapGuard mg;
for (int i = 0; i < 10; ++i) {
auto ch = MoveRouteVehicle();
auto mr = MakeRoute(static_cast<int>(lcf::rpg::MoveCommand::Code::face_random_direction));
ch.ForceMoveRoute(mr, 3);
testMoveRouteDir(ch, Down, Down, false, 3, 0xFFFF, 64, 0, true, false, mr);
ForceUpdate(ch);
testMoveRoute(ch, false, 3, 1, 32, 1, true, false, mr);
REQUIRE_GE(ch.GetDirection(), Up);
REQUIRE_LE(ch.GetDirection(), Left);
}
}
TEST_CASE("CommandWait") {
const MapGuard mg;
auto ch = MoveRouteVehicle();
auto mr = MakeRoute(static_cast<int>(lcf::rpg::MoveCommand::Code::wait));
ch.ForceMoveRoute(mr, 2);
testMoveRouteDir(ch, Down, Down, false, 2, 0xFFFF, 0, 0, true, false, mr);
for(int i = 1; i <= 84; ++i) {
ForceUpdate(ch);
testMoveRouteDir(ch, Down, Down, false, 2, i, 84, 1, true, false, mr);
}
ForceUpdate(ch);
testMoveRouteDir(ch, Down, Down, false, 2, 85, 128, 1, false, false, mr);
}
template <bool success, bool repeat, bool skip, bool end>
static void testJump(lcf::rpg::MoveCommand::Code code, int x, int y, int dir, int face, int tx, int ty, int tdir, int tface, int px = 0, int py = 0) {
Main_Data::game_player->SetX(px);
Main_Data::game_player->SetY(py);
auto ch = MoveRouteVehicle();
ch.SetX(x);
ch.SetY(y);
ch.SetDirection(dir);
ch.SetFacing(face);
ch.SetAllowMovement(success);
auto mr = MakeRoute(static_cast<int>(lcf::rpg::MoveCommand::Code::begin_jump), repeat, skip);
if (code != lcf::rpg::MoveCommand::Code::end_jump) {
lcf::rpg::MoveCommand mc;
mc.command_id = static_cast<int>(code);
mr.move_commands.push_back(mc);
}
if (end) {
lcf::rpg::MoveCommand mc;
mc.command_id = static_cast<int>(lcf::rpg::MoveCommand::Code::end_jump);
mr.move_commands.push_back(mc);
}
auto num_cmds = static_cast<int>(mr.move_commands.size());
CAPTURE(code);
CAPTURE(x);
CAPTURE(y);
CAPTURE(dir);
CAPTURE(face);
CAPTURE(tx);
CAPTURE(ty);
CAPTURE(tdir);
CAPTURE(tface);
CAPTURE(px);
CAPTURE(py);
CAPTURE(success);
CAPTURE(repeat);
CAPTURE(skip);
auto dx = tx - x;
auto dy = ty - y;
ch.ForceMoveRoute(mr, 3);
testMoveRouteJump(ch, x, y, 0, false, 0, 0, dir, face, false, 3, 0xFFFF, 64, 0, true, false, mr);
if (!end) {
ForceUpdate(ch);
if (repeat) {
testMoveRouteJump(ch, x, y, 0, false, 0, 0, dir, face, false, 3, 0xFFFF + 1, 64, 0, true, true, mr);
} else {
testMoveRouteJump(ch, x, y, 0, false, 0, 0, dir, face, false, 2, 0xFFFF + 1, 128, num_cmds, false, false, mr);
}
return;
}
if (success) {
bool repeated = false;
for(int n = (repeat ? 3 : 1); n > 0; --n) {
CAPTURE(n);
for(int i = 232; i > 0; i -= 24) {
ForceUpdate(ch);
testMoveRouteJump(ch, tx, ty, i, true, x, y, tdir, tface, false, 3, 0, 64, num_cmds, true, repeated, mr);
}
if (!repeat) {
ForceUpdate(ch);
testMoveRouteJump(ch, tx, ty, 0, false, x, y, tdir, tface, false, 2, 0, 128, 0, false, false, mr);
break;
}
repeated = true;
for (int i = 0; i <= 64; ++i) {
ForceUpdate(ch);
testMoveRouteMove(ch, tx, ty, 0, tdir, tface, false, 3, i, 64, 0, true, repeated, mr);
}
x = tx;
y = ty;
tx += dx;
ty += dy;
}
} else {
ForceUpdate(ch);
if (skip) {
if (repeat) {
for (int i = 1; i <= 3; ++i) {
testMoveRouteJump(ch, tx, ty, 0, false, 0, 0, tdir, tface, false, 3, 0xFFFF + i, 64, 0, true, true, mr);
ForceUpdate(ch);
}
} else {
testMoveRouteJump(ch, tx, ty, 0, false, 0, 0, tdir, tface, false, 2, 0xFFFF + 1, 128, num_cmds, false, false, mr);
}
} else {
testMoveRouteJump(ch, tx, ty, 0, false, 0, 0, tdir, tface, false, 3, 0xFFFF + 1, 64, 0, true, false, mr);
}
}
}
template <typename... Args>
static void testJumpSuccess(const Args&... args) {
testJump<true, false, false, true>(args...);
testJump<true, false, true, true>(args...);
testJump<true, true, false, true>(args...);
testJump<true, true, true, true>(args...);
}
template <typename... Args>
static void testJumpSuccessNoRepeat(const Args&... args) {
testJump<true, false, false, true>(args...);
testJump<true, false, true, true>(args...);
}
static void testJumpFail(lcf::rpg::MoveCommand::Code code, int x, int y, int dir, int face, int tdir, int tface, int px = 0, int py = 0) {
testJump<false, false, false, true>(code, x, y, dir, face, x, y, tdir, tface, px, py);
testJump<false, true, false, true>(code, x, y, dir, face, x, y, tdir, tface, px, py);
}
static void testJumpSkip(lcf::rpg::MoveCommand::Code code, int x, int y, int dir, int face, int px = 0, int py = 0) {
testJump<false, false, true, true>(code, x, y, dir, face, x, y, dir, face, px, py);
testJump<false, true, true, true>(code, x, y, dir, face, x, y, dir, face, px, py);
}
static void testJumpNoEnd(lcf::rpg::MoveCommand::Code code, int x, int y, int dir, int face, int px = 0, int py = 0) {
testJump<false, false, true, false>(code, x, y, dir, face, x, y, dir, face, px, py);
testJump<false, true, true, false>(code, x, y, dir, face, x, y, dir, face, px, py);
}
TEST_CASE("CommandJumpInPlace") {
const MapGuard mg;
// FIXME: Verify this behavior
testJumpSuccess(lcf::rpg::MoveCommand::Code::end_jump, 8, 8, Up, Up, 8, 8, Down, Up);
testJumpSuccess(lcf::rpg::MoveCommand::Code::end_jump, 8, 8, Right, Right, 8, 8, Down, Right);
testJumpSuccess(lcf::rpg::MoveCommand::Code::end_jump, 8, 8, Down, Down, 8, 8, Down, Down);
testJumpSuccess(lcf::rpg::MoveCommand::Code::end_jump, 8, 8, Left, Left, 8, 8, Down, Left);
// FIXME: Test no collision
}
TEST_CASE("CommandJump") {
const MapGuard mg;
testJumpSuccess(lcf::rpg::MoveCommand::Code::move_up, 8, 8, Down, Down, 8, 7, Up, Up);
testJumpSuccess(lcf::rpg::MoveCommand::Code::move_right, 8, 8, Down, Down, 9, 8, Right, Right);
testJumpSuccess(lcf::rpg::MoveCommand::Code::move_down, 8, 8, Down, Down, 8, 9, Down, Down);
testJumpSuccess(lcf::rpg::MoveCommand::Code::move_left, 8, 8, Down, Down, 7, 8, Left, Left);
}
TEST_CASE("CommandJumpFail") {
const MapGuard mg;
testJumpFail(lcf::rpg::MoveCommand::Code::move_up, 8, 8, Down, Down, Up, Up);
testJumpFail(lcf::rpg::MoveCommand::Code::move_right, 8, 8, Down, Down, Right, Right);
testJumpFail(lcf::rpg::MoveCommand::Code::move_down, 8, 8, Down, Down, Down, Down);
testJumpFail(lcf::rpg::MoveCommand::Code::move_left, 8, 8, Down, Down, Left, Left);
}
TEST_CASE("CommandJumpSkip") {
const MapGuard mg;
testJumpSkip(lcf::rpg::MoveCommand::Code::move_up, 8, 8, Down, Down);
testJumpSkip(lcf::rpg::MoveCommand::Code::move_right, 8, 8, Down, Down);
testJumpSkip(lcf::rpg::MoveCommand::Code::move_down, 8, 8, Down, Down);
testJumpSkip(lcf::rpg::MoveCommand::Code::move_left, 8, 8, Down, Down);
}
TEST_CASE("CommandJumpDiagonal") {
const MapGuard mg;
testJumpSuccess(lcf::rpg::MoveCommand::Code::move_upright, 8, 8, Up, Up, 9, 7, Up, Up);
testJumpSuccess(lcf::rpg::MoveCommand::Code::move_upright, 8, 8, Right, Right, 9, 7, Up, Up);
testJumpSuccess(lcf::rpg::MoveCommand::Code::move_upright, 8, 8, Down, Down, 9, 7, Up, Up);
testJumpSuccess(lcf::rpg::MoveCommand::Code::move_upright, 8, 8, Left, Left, 9, 7, Up, Up);
testJumpSuccess(lcf::rpg::MoveCommand::Code::move_downright, 8, 8, Up, Up, 9, 9, Down, Down);
testJumpSuccess(lcf::rpg::MoveCommand::Code::move_downright, 8, 8, Right, Right, 9, 9, Down, Down);
testJumpSuccess(lcf::rpg::MoveCommand::Code::move_downright, 8, 8, Down, Down, 9, 9, Down, Down);
testJumpSuccess(lcf::rpg::MoveCommand::Code::move_downright, 8, 8, Left, Left, 9, 9, Down, Down);
testJumpSuccess(lcf::rpg::MoveCommand::Code::move_downleft, 8, 8, Up, Up, 7, 9, Down, Down);
testJumpSuccess(lcf::rpg::MoveCommand::Code::move_downleft, 8, 8, Right, Right, 7, 9, Down, Down);
testJumpSuccess(lcf::rpg::MoveCommand::Code::move_downleft, 8, 8, Down, Down, 7, 9, Down, Down);
testJumpSuccess(lcf::rpg::MoveCommand::Code::move_downleft, 8, 8, Left, Left, 7, 9, Down, Down);
testJumpSuccess(lcf::rpg::MoveCommand::Code::move_upleft, 8, 8, Up, Up, 7, 7, Up, Up);
testJumpSuccess(lcf::rpg::MoveCommand::Code::move_upleft, 8, 8, Right, Right, 7, 7, Up, Up);
testJumpSuccess(lcf::rpg::MoveCommand::Code::move_upleft, 8, 8, Down, Down, 7, 7, Up, Up);
testJumpSuccess(lcf::rpg::MoveCommand::Code::move_upleft, 8, 8, Left, Left, 7, 7, Up, Up);
}
TEST_CASE("CommandJumpDiagonalFail") {
const MapGuard mg;
testJumpFail(lcf::rpg::MoveCommand::Code::move_upright, 8, 8, Up, Up, Up, Up);
testJumpFail(lcf::rpg::MoveCommand::Code::move_upright, 8, 8, Right, Right, Up, Up);
testJumpFail(lcf::rpg::MoveCommand::Code::move_upright, 8, 8, Down, Down, Up, Up);
testJumpFail(lcf::rpg::MoveCommand::Code::move_upright, 8, 8, Left, Left, Up, Up);
testJumpFail(lcf::rpg::MoveCommand::Code::move_downright, 8, 8, Up, Up, Down, Down);
testJumpFail(lcf::rpg::MoveCommand::Code::move_downright, 8, 8, Right, Right, Down, Down);
testJumpFail(lcf::rpg::MoveCommand::Code::move_downright, 8, 8, Down, Down, Down, Down);
testJumpFail(lcf::rpg::MoveCommand::Code::move_downright, 8, 8, Left, Left, Down, Down);
testJumpFail(lcf::rpg::MoveCommand::Code::move_downleft, 8, 8, Up, Up, Down, Down);
testJumpFail(lcf::rpg::MoveCommand::Code::move_downleft, 8, 8, Right, Right, Down, Down);
testJumpFail(lcf::rpg::MoveCommand::Code::move_downleft, 8, 8, Down, Down, Down, Down);
testJumpFail(lcf::rpg::MoveCommand::Code::move_downleft, 8, 8, Left, Left, Down, Down);
testJumpFail(lcf::rpg::MoveCommand::Code::move_upleft, 8, 8, Up, Up, Up, Up);
testJumpFail(lcf::rpg::MoveCommand::Code::move_upleft, 8, 8, Right, Right, Up, Up);
testJumpFail(lcf::rpg::MoveCommand::Code::move_upleft, 8, 8, Down, Down, Up, Up);
testJumpFail(lcf::rpg::MoveCommand::Code::move_upleft, 8, 8, Left, Left, Up, Up);
}
TEST_CASE("CommandJumpDiagonalSkip") {
const MapGuard mg;
testJumpSkip(lcf::rpg::MoveCommand::Code::move_upright, 8, 8, Up, Up);
testJumpSkip(lcf::rpg::MoveCommand::Code::move_upright, 8, 8, Right, Right);
testJumpSkip(lcf::rpg::MoveCommand::Code::move_upright, 8, 8, Down, Down);
testJumpSkip(lcf::rpg::MoveCommand::Code::move_upright, 8, 8, Left, Left);
testJumpSkip(lcf::rpg::MoveCommand::Code::move_downright, 8, 8, Up, Up);
testJumpSkip(lcf::rpg::MoveCommand::Code::move_downright, 8, 8, Right, Right);
testJumpSkip(lcf::rpg::MoveCommand::Code::move_downright, 8, 8, Down, Down);
testJumpSkip(lcf::rpg::MoveCommand::Code::move_downright, 8, 8, Left, Left);
testJumpSkip(lcf::rpg::MoveCommand::Code::move_downleft, 8, 8, Up, Up);
testJumpSkip(lcf::rpg::MoveCommand::Code::move_downleft, 8, 8, Right, Right);
testJumpSkip(lcf::rpg::MoveCommand::Code::move_downleft, 8, 8, Down, Down);
testJumpSkip(lcf::rpg::MoveCommand::Code::move_downleft, 8, 8, Left, Left);
testJumpSkip(lcf::rpg::MoveCommand::Code::move_upleft, 8, 8, Up, Up);
testJumpSkip(lcf::rpg::MoveCommand::Code::move_upleft, 8, 8, Right, Right);
testJumpSkip(lcf::rpg::MoveCommand::Code::move_upleft, 8, 8, Down, Down);
testJumpSkip(lcf::rpg::MoveCommand::Code::move_upleft, 8, 8, Left, Left);
}
TEST_CASE("CommandJumpForward") {
const MapGuard mg;
testJumpSuccess(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, Up, Up, 8, 7, Up, Up);
testJumpSuccess(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, Right, Right, 9, 8, Right, Right);
testJumpSuccess(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, Down, Down, 8, 9, Down, Down);
testJumpSuccess(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, Left, Left, 7, 8, Left, Left);
// FIXME: For repeat, these will move diag and then up or down afterwards.
testJumpSuccessNoRepeat(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, UpRight, Up, 9, 7, Up, Up);
testJumpSuccessNoRepeat(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, UpRight, Right, 9, 7, Up, Up);
testJumpSuccessNoRepeat(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, DownRight, Down, 9, 9, Down, Down);
testJumpSuccessNoRepeat(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, DownRight, Right, 9, 9, Down, Down);
testJumpSuccessNoRepeat(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, UpLeft, Up, 7, 7, Up, Up);
testJumpSuccessNoRepeat(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, UpLeft, Left, 7, 7, Up, Up);
testJumpSuccessNoRepeat(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, DownLeft, Down, 7, 9, Down, Down);
testJumpSuccessNoRepeat(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, DownLeft, Left, 7, 9, Down, Down);
}
TEST_CASE("CommandJumpForwardFail") {
const MapGuard mg;
testJumpFail(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, Up, Up, Up, Up);
testJumpFail(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, Right, Right, Right, Right);
testJumpFail(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, Down, Down, Down, Down);
testJumpFail(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, Left, Left, Left, Left);
testJumpFail(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, UpRight, Up, Up, Up);
testJumpFail(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, UpRight, Right, Up, Up);
testJumpFail(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, DownRight, Down, Down, Down);
testJumpFail(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, DownRight, Right, Down, Down);
testJumpFail(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, UpLeft, Up, Up, Up);
testJumpFail(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, UpLeft, Left, Up, Up);
testJumpFail(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, DownLeft, Down, Down, Down);
testJumpFail(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, DownLeft, Left, Down, Down);
}
TEST_CASE("CommandJumpForwardSkip") {
const MapGuard mg;
testJumpSkip(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, Up, Up);
testJumpSkip(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, Right, Right);
testJumpSkip(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, Down, Down);
testJumpSkip(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, Left, Left);
testJumpSkip(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, UpRight, Up);
testJumpSkip(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, UpRight, Right);
testJumpSkip(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, DownRight, Down);
testJumpSkip(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, DownRight, Right);
testJumpSkip(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, UpLeft, Up);
testJumpSkip(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, UpLeft, Left);
testJumpSkip(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, DownLeft, Down);
testJumpSkip(lcf::rpg::MoveCommand::Code::move_forward, 8, 8, DownLeft, Left);
}
TEST_CASE("CommandJumpRandom") {
// FIXME: TBD
}
TEST_CASE("CommandJumpNoEnd") {
const MapGuard mg;
// This makes a move route with just "Jump"
testJumpNoEnd(lcf::rpg::MoveCommand::Code::end_jump, 8, 8, Down, Down);
}
TEST_CASE("CommandMoveTurnJumpHero") {
const MapGuard mg;
int x = 8;
int y = 8;
for (int dx = -2; dx <= 2; ++dx) {
for (int dy = -2; dy <= 2; ++dy) {
auto step_x = 0;
auto step_y = 0;
auto dir = Down;
if (std::abs(dx) > std::abs(dy)) {
dir = (dx > 0 ? Right : Left);
step_x = (dx > 0 ? 1 : -1);
} else {
dir = (dy >= 0 ? Down : Up);
step_y = (dy >= 0 ? 1 : -1);
}
auto rdir = Game_Character::GetDirection180Degree(dir);
auto px = x + dx;
auto py = y + dy;
testTurn(lcf::rpg::MoveCommand::Code::face_hero, Left, dir, dir, x, y, px, py);
testTurn(lcf::rpg::MoveCommand::Code::face_away_from_hero, Left, rdir, rdir, x, y, px, py);
testMoveSuccessNoRepeat(lcf::rpg::MoveCommand::Code::move_towards_hero, x, y, Left, Left, x + step_x, y + step_y, dir, dir, px, py);
testMoveSuccessNoRepeat(lcf::rpg::MoveCommand::Code::move_away_from_hero, x, y, Left, Left, x - step_x, y - step_y, rdir, rdir, px, py);
testMoveFail(lcf::rpg::MoveCommand::Code::move_towards_hero, x, y, Left, Left, dir, dir, px, py);
testMoveFail(lcf::rpg::MoveCommand::Code::move_away_from_hero, x, y, Left, Left, rdir, rdir, px, py);
testMoveSkip(lcf::rpg::MoveCommand::Code::move_towards_hero, x, y, Left, Left, px, py);
testMoveSkip(lcf::rpg::MoveCommand::Code::move_away_from_hero, x, y, Left, Left, px, py);
testJumpSuccessNoRepeat(lcf::rpg::MoveCommand::Code::move_towards_hero, x, y, Left, Left, x + step_x, y + step_y, dir, dir, px, py);
testJumpSuccessNoRepeat(lcf::rpg::MoveCommand::Code::move_away_from_hero, x, y, Left, Left, x - step_x, y - step_y, rdir, rdir, px, py);
testJumpFail(lcf::rpg::MoveCommand::Code::move_towards_hero, x, y, Left, Left, dir, dir, px, py);
testJumpFail(lcf::rpg::MoveCommand::Code::move_away_from_hero, x, y, Left, Left, rdir, rdir, px, py);
testJumpSkip(lcf::rpg::MoveCommand::Code::move_towards_hero, x, y, Left, Left, px, py);
testJumpSkip(lcf::rpg::MoveCommand::Code::move_away_from_hero, x, y, Left, Left, px, py);
}
}
}
void testLockFacing(lcf::rpg::EventPage::AnimType at) {
const MapGuard mg;
auto ch = MoveRouteVehicle();
ch.SetAnimationType(at);
auto mr = MakeRoute(static_cast<int>(lcf::rpg::MoveCommand::Code::lock_facing));
ch.ForceMoveRoute(mr, 2);
testMoveRoute(ch, false, 2, 0xFFFF, 0, 0, true, false, mr);
REQUIRE_EQ(ch.IsFacingLocked(), Game_Character::IsDirectionFixedAnimationType(at));
ForceUpdate(ch);
testMoveRoute(ch, false, 2, 0xFFFF + 1, 128, 1, false, false, mr);
REQUIRE(ch.IsFacingLocked());
mr = MakeRoute(static_cast<int>(lcf::rpg::MoveCommand::Code::unlock_facing));
ch.ForceMoveRoute(mr, 2);
testMoveRoute(ch, false, 2, 0xFFFF, 128, 0, true, false, mr);
REQUIRE(ch.IsFacingLocked());
ForceUpdate(ch);
testMoveRoute(ch, false, 2, 0xFFFF + 1, 128, 1, false, false, mr);
REQUIRE_EQ(ch.IsFacingLocked(), Game_Character::IsDirectionFixedAnimationType(at));
}
TEST_CASE("CommandLockFacing") {
for (int i = 0; i <= static_cast<int>(lcf::rpg::EventPage::AnimType_step_frame_fix); ++i) {
testLockFacing(static_cast<lcf::rpg::EventPage::AnimType>(i));
}
}
TEST_CASE("CommandSpeedChange") {
const MapGuard mg;
auto ch = MoveRouteVehicle();
auto mr = MakeRoute(static_cast<int>(lcf::rpg::MoveCommand::Code::increase_movement_speed));
//const int n = 10;
ch.SetMoveSpeed(1);
int prev = ch.GetMoveSpeed();
for (int i = 0; i < 10; ++i) {
ch.ForceMoveRoute(mr, 2);
testMoveRoute(ch, false, 2, 0xFFFF, (i == 0 ? 0 : 128), 0, true, false, mr);
REQUIRE_EQ(ch.GetMoveSpeed(), prev);
ForceUpdate(ch);
testMoveRoute(ch, false, 2, 0xFFFF + 1, 128, 1, false, false, mr);
REQUIRE_EQ(ch.GetMoveSpeed(), std::min(prev + 1, 6));
prev= ch.GetMoveSpeed();
}
mr = MakeRoute(static_cast<int>(lcf::rpg::MoveCommand::Code::decrease_movement_speed));
for (int i = 0; i < 10; ++i) {
ch.ForceMoveRoute(mr, 2);
testMoveRoute(ch, false, 2, 0xFFFF, 128, 0, true, false, mr);
REQUIRE_EQ(ch.GetMoveSpeed(), prev);
ForceUpdate(ch);
testMoveRoute(ch, false, 2, 0xFFFF + 1, 128, 1, false, false, mr);
REQUIRE_EQ(ch.GetMoveSpeed(), std::max(prev - 1, 1));
prev= ch.GetMoveSpeed();
}
}
TEST_CASE("CommandFreqChange") {
const MapGuard mg;
auto ch = MoveRouteVehicle();
auto mr = MakeRoute(static_cast<int>(lcf::rpg::MoveCommand::Code::increase_movement_frequence));
for (int i = 1; i < 10; ++i) {
const int freq = Utils::Clamp(i, 1, 8);
ch.ForceMoveRoute(mr, freq);
testMoveRoute(ch, false, freq, 0xFFFF, (i == 0 && freq == 2 ? 0 : Game_Character::GetMaxStopCountForStep(freq)), 0, true, false, mr);
//const int next_freq = Utils::Clamp(freq + 1, 1, 8);
ForceUpdate(ch);
// FIXME: Need another command for the frequency to not get reset when move route is done.
//testMoveRoute(ch, false, next_freq, 0xFFFF + 1, Game_Character::GetMaxStopCountForStep(next_freq), 1, false, false, mr);
testMoveRoute(ch, false, 2, 0xFFFF + 1, 128, 1, false, false, mr);
}
mr = MakeRoute(static_cast<int>(lcf::rpg::MoveCommand::Code::decrease_movement_frequence));
for (int i = 1; i < 10; ++i) {
const int freq = Utils::Clamp(i, 1, 8);
ch.ForceMoveRoute(mr, freq);
testMoveRoute(ch, false, freq, 0xFFFF, Game_Character::GetMaxStopCountForStep(freq), 0, true, false, mr);
//const int next_freq = Utils::Clamp(freq - 1, 1, 8);
ForceUpdate(ch);
// FIXME: Need another command for the frequency to not get reset when move route is done.
//testMoveRoute(ch, false, next_freq, 0xFFFF + 1, Game_Character::GetMaxStopCountForStep(next_freq), 1, false, false, mr);
testMoveRoute(ch, false, 2, 0xFFFF + 1, 128, 1, false, false, mr);
}
}
TEST_CASE("CommandTranspChange") {
const MapGuard mg;
auto ch = MoveRouteVehicle();
auto mr = MakeRoute(static_cast<int>(lcf::rpg::MoveCommand::Code::increase_transp));
//const int n = 10;
ch.SetTransparency(0);
int prev = ch.GetTransparency();
for (int i = 0; i < 10; ++i) {
ch.ForceMoveRoute(mr, 2);
testMoveRoute(ch, false, 2, 0xFFFF, (i == 0 ? 0 : 128), 0, true, false, mr);
REQUIRE_EQ(ch.GetTransparency(), prev);
ForceUpdate(ch);
testMoveRoute(ch, false, 2, 0xFFFF + 1, 128, 1, false, false, mr);
REQUIRE_EQ(ch.GetTransparency(), std::min(prev + 1, 7));
prev = ch.GetTransparency();
}
mr = MakeRoute(static_cast<int>(lcf::rpg::MoveCommand::Code::decrease_transp));
for (int i = 0; i < 10; ++i) {
ch.ForceMoveRoute(mr, 2);
testMoveRoute(ch, false, 2, 0xFFFF, 128, 0, true, false, mr);
REQUIRE_EQ(ch.GetTransparency(), prev);
ForceUpdate(ch);
testMoveRoute(ch, false, 2, 0xFFFF + 1, 128, 1, false, false, mr);
REQUIRE_EQ(ch.GetTransparency(), std::max(prev - 1, 0));
prev = ch.GetTransparency();
}
}
TEST_CASE("CommandThrough") {
const MapGuard mg;
auto ch = MoveRouteVehicle();
auto mr = MakeRoute(static_cast<int>(lcf::rpg::MoveCommand::Code::walk_everywhere_on));
auto testoff = [&]() {
REQUIRE(!ch.GetThrough());
ch.SetThrough(true);
REQUIRE(ch.GetThrough());
ch.ResetThrough();
REQUIRE(!ch.GetThrough());
};
auto teston = [&]() {
REQUIRE(ch.GetThrough());
ch.SetThrough(false);
REQUIRE(!ch.GetThrough());
ch.ResetThrough();
REQUIRE(ch.GetThrough());
};
ch.ForceMoveRoute(mr, 2);
testMoveRoute(ch, false, 2, 0xFFFF, 0, 0, true, false, mr);
testoff();
ForceUpdate(ch);
testMoveRoute(ch, false, 2, 0xFFFF + 1, 128, 1, false, false, mr);
teston();
mr = MakeRoute(static_cast<int>(lcf::rpg::MoveCommand::Code::walk_everywhere_off));
ch.ForceMoveRoute(mr, 2);
testMoveRoute(ch, false, 2, 0xFFFF, 128, 0, true, false, mr);
teston();
ForceUpdate(ch);
testMoveRoute(ch, false, 2, 0xFFFF + 1, 128, 1, false, false, mr);
testoff();
ch.SetThrough(true);
mr = MakeRoute(static_cast<int>(lcf::rpg::MoveCommand::Code::walk_everywhere_off));
ch.ForceMoveRoute(mr, 2);
testMoveRoute(ch, false, 2, 0xFFFF, 128, 0, true, false, mr);
REQUIRE(ch.GetThrough());
ForceUpdate(ch);
testMoveRoute(ch, false, 2, 0xFFFF + 1, 128, 1, false, false, mr);
testoff();
ch.SetThrough(true);
mr = MakeRoute(static_cast<int>(lcf::rpg::MoveCommand::Code::walk_everywhere_on));
ch.ForceMoveRoute(mr, 2);
REQUIRE(ch.GetThrough());
ForceUpdate(ch);
testMoveRoute(ch, false, 2, 0xFFFF + 1, 128, 1, false, false, mr);
teston();
}
TEST_CASE("CommandStopAnimation") {
const MapGuard mg;
auto ch = MoveRouteVehicle();
auto mr = MakeRoute(static_cast<int>(lcf::rpg::MoveCommand::Code::stop_animation));
ch.ForceMoveRoute(mr, 2);
testMoveRoute(ch, false, 2, 0xFFFF, 0, 0, true, false, mr);
REQUIRE(!ch.IsAnimPaused());
ForceUpdate(ch);
testMoveRoute(ch, false, 2, 0xFFFF + 1, 128, 1, false, false, mr);
REQUIRE(ch.IsAnimPaused());
mr = MakeRoute(static_cast<int>(lcf::rpg::MoveCommand::Code::start_animation));
ch.ForceMoveRoute(mr, 2);
testMoveRoute(ch, false, 2, 0xFFFF, 128, 0, true, false, mr);
REQUIRE(ch.IsAnimPaused());
ForceUpdate(ch);
testMoveRoute(ch, false, 2, 0xFFFF + 1, 128, 1, false, false, mr);
REQUIRE(!ch.IsAnimPaused());
}
TEST_CASE("CommandSwitchToggle") {
const MapGuard mg;
auto ch = MoveRouteVehicle();
auto mr = MakeRoute({{ static_cast<int>(lcf::rpg::MoveCommand::Code::switch_on), "", 3 }});
REQUIRE_NE(Main_Data::game_switches, nullptr);
ch.ForceMoveRoute(mr, 2);
testMoveRoute(ch, false, 2, 0xFFFF, 0, 0, true, false, mr);
REQUIRE(!Main_Data::game_switches->Get(3));
ForceUpdate(ch);
testMoveRoute(ch, false, 2, 0xFFFF + 1, 128, 1, false, false, mr);
REQUIRE(Main_Data::game_switches->Get(3));
mr = MakeRoute({{ static_cast<int>(lcf::rpg::MoveCommand::Code::switch_off), "", 3 }});
ch.ForceMoveRoute(mr, 2);
testMoveRoute(ch, false, 2, 0xFFFF, 128, 0, true, false, mr);
REQUIRE(Main_Data::game_switches->Get(3));
ForceUpdate(ch);
testMoveRoute(ch, false, 2, 0xFFFF + 1, 128, 1, false, false, mr);
REQUIRE(!Main_Data::game_switches->Get(3));
}
TEST_CASE("CommandChangeGraphic") {
const MapGuard mg;
auto ch = MoveRouteVehicle();
auto mr = MakeRoute({{ static_cast<int>(lcf::rpg::MoveCommand::Code::change_graphic), "x", 3 }});
ch.ForceMoveRoute(mr, 2);
testMoveRoute(ch, false, 2, 0xFFFF, 0, 0, true, false, mr);
REQUIRE_EQ(ch.GetSpriteName(), "");
REQUIRE_EQ(ch.GetSpriteIndex(), 0);
ForceUpdate(ch);
testMoveRoute(ch, false, 2, 0xFFFF + 1, 128, 1, false, false, mr);
REQUIRE_EQ(ch.GetSpriteName(), "x");
REQUIRE_EQ(ch.GetSpriteIndex(), 3);
}
TEST_CASE("CommandPlaySound") {
const MapGuard mg;
auto ch = MoveRouteVehicle();
auto mr = MakeRoute({{ static_cast<int>(lcf::rpg::MoveCommand::Code::play_sound_effect), "", 100, 100, 100 }});
ch.ForceMoveRoute(mr, 2);
testMoveRoute(ch, false, 2, 0xFFFF, 0, 0, true, false, mr);
ForceUpdate(ch);
testMoveRoute(ch, false, 2, 0xFFFF + 1, 128, 1, false, false, mr);
// FIXME: Check mocked audio subsystem?
}
TEST_CASE("ClearPause") {
auto ch = MoveRouteVehicle();
ch.SetPaused(true);
REQUIRE(ch.IsPaused());
auto mr = MakeRoute({{}});
ch.ForceMoveRoute(mr, 3);
REQUIRE(!ch.IsPaused());
}
TEST_SUITE_END();
| 412 | 0.917455 | 1 | 0.917455 | game-dev | MEDIA | 0.959481 | game-dev | 0.923742 | 1 | 0.923742 |
NEZNAMY/TAB | 8,365 | bukkit/v1_18_R1/src/main/java/me/neznamy/tab/platforms/bukkit/v1_18_R1/NMSPacketTabList.java | package me.neznamy.tab.platforms.bukkit.v1_18_R1;
import com.mojang.authlib.GameProfile;
import com.mojang.authlib.properties.Property;
import lombok.NonNull;
import lombok.SneakyThrows;
import me.neznamy.tab.shared.chat.component.TabComponent;
import me.neznamy.tab.platforms.bukkit.BukkitTabPlayer;
import me.neznamy.tab.shared.TAB;
import me.neznamy.tab.shared.platform.TabList;
import me.neznamy.tab.shared.platform.decorators.TrackedTabList;
import me.neznamy.tab.shared.util.ReflectionUtils;
import net.minecraft.network.chat.IChatBaseComponent;
import net.minecraft.network.protocol.Packet;
import net.minecraft.network.protocol.game.PacketPlayOutPlayerInfo;
import net.minecraft.network.protocol.game.PacketPlayOutPlayerInfo.EnumPlayerInfoAction;
import net.minecraft.network.protocol.game.PacketPlayOutPlayerInfo.PlayerInfoData;
import net.minecraft.network.protocol.game.PacketPlayOutPlayerListHeaderFooter;
import net.minecraft.world.level.EnumGamemode;
import org.bukkit.craftbukkit.v1_18_R1.entity.CraftPlayer;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.lang.reflect.Field;
import java.util.*;
/**
* TabList implementation using direct NMS code.
*/
public class NMSPacketTabList extends TrackedTabList<BukkitTabPlayer> {
private static final Field PLAYERS = ReflectionUtils.getOnlyField(PacketPlayOutPlayerInfo.class, List.class);
private static final EnumPlayerInfoAction ADD_PLAYER = EnumPlayerInfoAction.a;
private static final EnumPlayerInfoAction UPDATE_GAME_MODE = EnumPlayerInfoAction.b;
private static final EnumPlayerInfoAction UPDATE_LATENCY = EnumPlayerInfoAction.c;
private static final EnumPlayerInfoAction UPDATE_DISPLAY_NAME = EnumPlayerInfoAction.d;
/**
* Constructs new instance.
*
* @param player
* Player this tablist will belong to
*/
public NMSPacketTabList(@NotNull BukkitTabPlayer player) {
super(player);
}
@Override
@SneakyThrows
public void removeEntry(@NonNull UUID entry) {
sendPacket(EnumPlayerInfoAction.e, entry, "", null, 0, 0, null);
}
@Override
public void updateDisplayName0(@NonNull UUID entry, @Nullable TabComponent displayName) {
sendPacket(EnumPlayerInfoAction.d, entry, "", null, 0, 0, displayName);
}
@Override
public void updateLatency(@NonNull UUID entry, int latency) {
sendPacket(EnumPlayerInfoAction.c, entry, "", null, latency, 0, null);
}
@Override
public void updateGameMode(@NonNull UUID entry, int gameMode) {
sendPacket(EnumPlayerInfoAction.b, entry, "", null, 0, gameMode, null);
}
@Override
public void updateListed(@NonNull UUID entry, boolean listed) {
// Added in 1.19.3
}
@Override
public void updateListOrder(@NonNull UUID entry, int listOrder) {
// Added in 1.21.2
}
@Override
public void updateHat(@NonNull UUID entry, boolean showHat) {
// Added in 1.21.4
}
@Override
public void addEntry0(@NonNull Entry entry) {
sendPacket(EnumPlayerInfoAction.a, entry.getUniqueId(), entry.getName(), entry.getSkin(), entry.getLatency(),
entry.getGameMode(), entry.getDisplayName());
}
@Override
@SneakyThrows
public void setPlayerListHeaderFooter0(@NonNull TabComponent header, @NonNull TabComponent footer) {
sendPacket(new PacketPlayOutPlayerListHeaderFooter(header.convert(), footer.convert()));
}
@Override
public boolean containsEntry(@NonNull UUID entry) {
return true; // TODO?
}
@Override
@Nullable
public Skin getSkin() {
Collection<Property> properties = ((CraftPlayer)player.getPlayer()).getProfile().getProperties().get(TEXTURES_PROPERTY);
if (properties.isEmpty()) return null; // Offline mode
Property property = properties.iterator().next();
return new Skin(property.getValue(), property.getSignature());
}
@Override
@SneakyThrows
@NotNull
public Object onPacketSend(@NonNull Object packet) {
if (packet instanceof PacketPlayOutPlayerListHeaderFooter) {
PacketPlayOutPlayerListHeaderFooter tablist = (PacketPlayOutPlayerListHeaderFooter) packet;
if (header == null || footer == null) return packet;
if (tablist.a != header.convert() || tablist.b != footer.convert()) {
return new PacketPlayOutPlayerListHeaderFooter(header.convert(), footer.convert());
}
}
if (!(packet instanceof PacketPlayOutPlayerInfo)) return packet;
PacketPlayOutPlayerInfo info = (PacketPlayOutPlayerInfo) packet;
EnumPlayerInfoAction action = info.c();
List<PlayerInfoData> updatedList = new ArrayList<>();
boolean rewritePacket = false;
for (PlayerInfoData nmsData : info.b()) {
boolean rewriteEntry = false;
GameProfile profile = nmsData.a();
UUID id = profile.getId();
IChatBaseComponent displayName = nmsData.d();
int latency = nmsData.b();
int gameMode = nmsData.c().a();
if (action == UPDATE_DISPLAY_NAME || action == ADD_PLAYER) {
TabComponent forcedDisplayName = getForcedDisplayNames().get(id);
if (forcedDisplayName != null && forcedDisplayName.convert() != displayName) {
displayName = forcedDisplayName.convert();
rewriteEntry = rewritePacket = true;
}
}
if (action == UPDATE_GAME_MODE || action == ADD_PLAYER) {
Integer forcedGameMode = getForcedGameModes().get(id);
if (forcedGameMode != null && forcedGameMode != gameMode) {
gameMode = forcedGameMode;
rewriteEntry = rewritePacket = true;
}
}
if (action == UPDATE_LATENCY || action == ADD_PLAYER) {
if (getForcedLatency() != null) {
latency = getForcedLatency();
rewriteEntry = rewritePacket = true;
}
}
if (action == ADD_PLAYER) {
TAB.getInstance().getFeatureManager().onEntryAdd(player, id, profile.getName());
}
updatedList.add(rewriteEntry ? new PlayerInfoData(
profile,
latency,
EnumGamemode.a(gameMode),
displayName
) : nmsData);
}
if (rewritePacket) {
PacketPlayOutPlayerInfo newPacket = new PacketPlayOutPlayerInfo(action, Collections.emptyList());
PLAYERS.set(newPacket, updatedList);
return newPacket;
}
return packet;
}
@SneakyThrows
private void sendPacket(@NonNull EnumPlayerInfoAction action, @NonNull UUID id, @NonNull String name,
@Nullable Skin skin, int latency, int gameMode, @Nullable TabComponent displayName) {
PacketPlayOutPlayerInfo packet = new PacketPlayOutPlayerInfo(action);
PLAYERS.set(packet, Collections.singletonList(new PlayerInfoData(
createProfile(id, name, skin),
latency,
EnumGamemode.a(gameMode),
displayName == null ? null : displayName.convert())
));
sendPacket(packet);
}
/**
* Creates GameProfile from given parameters.
*
* @param id
* Profile ID
* @param name
* Profile name
* @param skin
* Player skin
* @return GameProfile from given parameters
*/
@NotNull
private GameProfile createProfile(@NonNull UUID id, @NonNull String name, @Nullable Skin skin) {
GameProfile profile = new GameProfile(id, name);
if (skin != null) {
profile.getProperties().put(TabList.TEXTURES_PROPERTY,
new Property(TabList.TEXTURES_PROPERTY, skin.getValue(), skin.getSignature()));
}
return profile;
}
/**
* Sends the packet to the player.
*
* @param packet
* Packet to send
*/
private void sendPacket(@NotNull Packet<?> packet) {
((CraftPlayer)player.getPlayer()).getHandle().b.a(packet);
}
}
| 412 | 0.939452 | 1 | 0.939452 | game-dev | MEDIA | 0.800858 | game-dev,networking | 0.980746 | 1 | 0.980746 |
atcollab/at | 2,285 | atmat/atupdateContents.m | % Updates Contents.m of AT directories
% For ATROOT: Contents will include subdirectories
% For other subdirectories, policiy is defined in case by case
ATROOT = fileparts(atroot);
OLDDIR = pwd;
%Selects directories where to create a Contents
listOfFolderNames={
fullfile(ATROOT,'atmat', 'atdemos'), ...
fullfile(ATROOT,'atmat', 'atgui'), ...
fullfile(ATROOT,'atmat', 'atmatch'), ...
fullfile(ATROOT,'atmat', 'atutils'), ...
fullfile(ATROOT,'atmat', 'atphysics'), ...
fullfile(ATROOT,'atmat', 'atphysics', 'CollectiveEffects'), ...
fullfile(ATROOT,'atmat', 'atphysics', 'LinearOptics'), ...
fullfile(ATROOT,'atmat', 'atphysics', 'LongitudinalDynamics'), ...
fullfile(ATROOT,'atmat', 'atphysics', 'Orbit'), ...
fullfile(ATROOT,'atmat', 'atphysics', 'ParameterSummaryFunctions'), ...
fullfile(ATROOT,'atmat', 'atphysics', 'TouschekPiwinski'), ...
fullfile(ATROOT,'atmat', 'atphysics', 'TuneAndChromaticity'), ...
fullfile(ATROOT,'atmat', 'atphysics', 'Radiation'), ...
fullfile(ATROOT,'atmat', 'atphysics', 'NonLinearDynamics'), ...
fullfile(ATROOT,'atmat', 'atphysics', 'nafflib'), ...
fullfile(ATROOT,'atmat', 'atplot'), ...
fullfile(ATROOT,'atmat', 'atplot', 'plotfunctions'), ...
fullfile(ATROOT,'atmat', 'attrack'), ...
fullfile(ATROOT,'atmat', 'lattice'), ...
fullfile(ATROOT,'atmat', 'lattice', 'Converters'), ...
fullfile(ATROOT,'atmat', 'lattice','element_creation'), ...
fullfile(ATROOT,'atmat', 'lattice','survey'), ...
fullfile(ATROOT,'machine_data'), ...
fullfile(ATROOT,'atintegrators'), ...
fullfile(ATROOT,'atmat', 'pubtools', 'LatticeTuningFunctions'), ...
fullfile(ATROOT,'atmat', 'pubtools', 'VacuumLifetime'), ...
fullfile(ATROOT,'atmat', 'pubtools', 'distance2curve'), ...
fullfile(ATROOT,'atmat', 'pubtools', 'haissinski'), ...
fullfile(ATROOT,'atmat', 'pubtools', 'lattice_tools'), ...
fullfile(ATROOT,'atmat', 'pubtools', 'local_lattice_params'), ...
fullfile(ATROOT,'atmat', 'pubtools', 'create_elems'), ...
};
% Generates specific Contents
for k=1:length(listOfFolderNames)
cd(listOfFolderNames{k})
fprintf('Updating Contents of folder %s\n', cd);
updateContents(cd);
end
cd(OLDDIR);
clear OLDIR ATROOT | 412 | 0.714654 | 1 | 0.714654 | game-dev | MEDIA | 0.355103 | game-dev | 0.536377 | 1 | 0.536377 |
andersonfreitas/opengl-tutorial-org | 1,562 | external/bullet-2.81-rev2613/src/BulletCollision/CollisionShapes/btEmptyShape.cpp | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "btEmptyShape.h"
#include "btCollisionShape.h"
btEmptyShape::btEmptyShape() : btConcaveShape ()
{
m_shapeType = EMPTY_SHAPE_PROXYTYPE;
}
btEmptyShape::~btEmptyShape()
{
}
///getAabb's default implementation is brute force, expected derived classes to implement a fast dedicated version
void btEmptyShape::getAabb(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const
{
btVector3 margin(getMargin(),getMargin(),getMargin());
aabbMin = t.getOrigin() - margin;
aabbMax = t.getOrigin() + margin;
}
void btEmptyShape::calculateLocalInertia(btScalar ,btVector3& ) const
{
btAssert(0);
}
| 412 | 0.81813 | 1 | 0.81813 | game-dev | MEDIA | 0.9756 | game-dev | 0.557442 | 1 | 0.557442 |
MrXiaoM/SweetMail | 29,757 | src/main/java/top/mrxiaom/sweetmail/config/gui/MenuDraftConfig.java | package top.mrxiaom.sweetmail.config.gui;
import com.google.common.collect.Lists;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.TextDecoration;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver;
import net.kyori.adventure.text.minimessage.tag.standard.StandardTags;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.MemoryConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.event.inventory.InventoryAction;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryView;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.BookMeta;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.SkullMeta;
import org.bukkit.permissions.Permissible;
import top.mrxiaom.sweetmail.Messages;
import top.mrxiaom.sweetmail.SweetMail;
import top.mrxiaom.sweetmail.attachments.AttachmentItem;
import top.mrxiaom.sweetmail.attachments.IAttachment;
import top.mrxiaom.sweetmail.config.AbstractMenuConfig;
import top.mrxiaom.sweetmail.database.entry.Mail;
import top.mrxiaom.sweetmail.depend.PAPI;
import top.mrxiaom.sweetmail.events.PlayerMailSentEvent;
import top.mrxiaom.sweetmail.func.DraftManager;
import top.mrxiaom.sweetmail.func.data.Draft;
import top.mrxiaom.sweetmail.func.data.MailIcon;
import top.mrxiaom.sweetmail.gui.AbstractDraftGui;
import top.mrxiaom.sweetmail.gui.GuiIcon;
import top.mrxiaom.sweetmail.utils.*;
import java.time.LocalDateTime;
import java.util.*;
import java.util.regex.Pattern;
import static top.mrxiaom.sweetmail.commands.CommandMain.PERM_ADMIN;
import static top.mrxiaom.sweetmail.utils.Pair.replace;
public class MenuDraftConfig extends AbstractMenuConfig<MenuDraftConfig.Gui> {
private Icon iconReceiver;
private Icon iconIcon;
private Icon iconTitle;
private Icon iconContent;
private Icon iconAdvanced;
private Icon iconReset;
private Icon iconSend;
private Icon iconAttachment;
private String iconReceiverUnset;
private String iconAdvancedRedirectKey;
public String iconReceiverPromptTips;
public String iconReceiverPromptCancel;
public String iconReceiverWarnNotExists;
public String iconReceiverRegex;
public String iconIconTitle;
public String iconIconTitleCustom;
public String iconTitlePromptTips;
public String iconTitlePromptCancel;
public boolean canSendToYourself;
private final Map<String, Double> priceMap = new HashMap<>();
private final Map<String, Integer> outdateDaysMap = new HashMap<>();
private final Map<String, Integer> outdateDraftHoursMap = new HashMap<>();
public MenuDraftConfig(SweetMail plugin) {
super(plugin, "menus/draft.yml");
}
@Override
public void reloadConfig(MemoryConfiguration cfg) {
super.reloadConfig(cfg);
canSendToYourself = cfg.getBoolean("can-send-to-yourself", false);
priceMap.clear();
ConfigurationSection section = cfg.getConfigurationSection("price");
if (section != null) for (String key : section.getKeys(false)) {
double price = section.getDouble(key);
priceMap.put(key, price > 0 ? price : 0);
}
outdateDaysMap.clear();
section = cfg.getConfigurationSection("outdate-time");
if (section != null) for (String key : section.getKeys(false)) {
int days = section.getInt(key);
outdateDaysMap.put(key, days);
}
outdateDraftHoursMap.clear();
section = cfg.getConfigurationSection("outdate-draft");
if (section != null) for (String key : section.getKeys(false)) {
int hours = section.getInt(key);
outdateDraftHoursMap.put(key, hours);
}
}
public double getPrice(Permissible permissible) {
ArrayList<Map.Entry<String, Double>> list = Lists.newArrayList(priceMap.entrySet());
list.sort(Comparator.comparingDouble(Map.Entry::getValue));
for (Map.Entry<String, Double> entry : list) {
if (permissible.hasPermission(entry.getKey())) {
return entry.getValue();
}
}
return 0;
}
public int getOutdateDays(Permissible permissible) {
ArrayList<Map.Entry<String, Integer>> list = Lists.newArrayList(outdateDaysMap.entrySet());
list.sort(Comparator.comparingInt(Map.Entry::getValue));
Collections.reverse(list);
int max = 0;
for (Map.Entry<String, Integer> entry : list) {
if (entry.getValue() <= 0 || entry.getValue() > max) {
if (permissible.hasPermission("sweetmail.outdate." + entry.getKey())) {
if (entry.getValue() <= 0) return entry.getValue();
if (entry.getValue() > max) {
max = entry.getValue();
}
}
}
}
return max;
}
public int getDraftOutdateHours(Permissible permissible) {
ArrayList<Map.Entry<String, Integer>> list = Lists.newArrayList(outdateDraftHoursMap.entrySet());
list.sort(Comparator.comparingInt(Map.Entry::getValue));
Collections.reverse(list);
int max = 0;
for (Map.Entry<String, Integer> entry : list) {
if (entry.getValue() <= 0 || entry.getValue() > max) {
if (permissible.hasPermission("sweetmail.draft.outdate." + entry.getKey())) {
if (entry.getValue() <= 0) return entry.getValue();
if (entry.getValue() > max) {
max = entry.getValue();
}
}
}
}
return max;
}
@Override
protected void clearMainIcons() {
iconReceiver = iconIcon = iconTitle = iconContent = iconAdvanced = iconReset = iconSend = iconAttachment = null;
iconReceiverUnset = iconAdvancedRedirectKey
= iconReceiverPromptTips = iconReceiverPromptCancel
= iconTitlePromptTips = iconTitlePromptCancel
= iconIconTitle = iconIconTitleCustom = null;
}
@Override
protected boolean loadMainIcon(ConfigurationSection section, String key, Icon loadedIcon) {
switch (key) {
case "接": {
iconReceiver = loadedIcon;
iconReceiverUnset = section.getString(key + ".unset", "&7未设置");
iconReceiverPromptTips = section.getString(key + ".prompt-tips", "&7[&e&l邮件&7] &b请在聊天栏发送&e“邮件接收者”&b的值 &7(输入&c cancel &7取消设置)");
iconReceiverPromptCancel = section.getString(key + ".prompt-cancel", "cancel");
iconReceiverWarnNotExists = section.getString(key + ".warn-not-exists", "%name% &7(&c从未加入过游戏&7)");
iconReceiverRegex = section.getString(key + ".regex", "^[a-zA-Z0-9_\\u4e00-\\u9fa5]{1,20}");
return true;
}
case "图": {
iconIcon = loadedIcon;
iconIconTitle = section.getString(key + ".title", "选择图标");
iconIconTitleCustom = section.getString(key + ".title-custom", "选择图标 (可在物品栏选择)");
return true;
}
case "题": {
iconTitle = loadedIcon;
iconTitlePromptTips = section.getString(key + ".prompt-tips", "&7[&e&l邮件&7] &b请在聊天栏发送&e“邮件标题”&b的值 &7(输入&c cancel &7取消设置)");
iconTitlePromptCancel = section.getString(key + ".prompt-cancel", "cancel");
return true;
}
case "文": {
iconContent = loadedIcon;
return true;
}
case "高": {
iconAdvanced = loadedIcon;
iconAdvancedRedirectKey = section.getString(key + ".redirect", "黑");
return true;
}
case "重": {
iconReset = loadedIcon;
return true;
}
case "发": {
iconSend = loadedIcon;
return true;
}
case "附": {
iconAttachment = loadedIcon;
return true;
}
}
return false;
}
@Override
protected String getTitleText(Gui gui, Player target) {
return replace(PAPI.setPlaceholders(target, title), Pair.of("%title%", gui.getDraft().title));
}
@Override
protected ItemStack tryApplyMainIcon(Gui gui, String key, Player target, int iconIndex) {
DraftManager manager = DraftManager.inst();
Draft draft = manager.getDraft(target);
switch (key) {
case "接": {
String receiver;
if (draft.receiver.isEmpty()) {
receiver = iconReceiverUnset;
} else {
String name = Util.getPlayerName(draft.receiver);
receiver = Util.getOfflinePlayer(name)
.map(OfflinePlayer::getName)
.orElseGet(() -> iconReceiverWarnNotExists.replace("%name%", name));
}
ItemStack item = iconReceiver.generateIcon(
gui, target,
Pair.of("%receiver%", receiver)
);
if (!draft.receiver.isEmpty() && item.getItemMeta() instanceof SkullMeta) {
OfflinePlayer owner = Util.getOfflinePlayerByNameOrUUID(draft.receiver).orElse(null);
if (owner != null) {
ItemMeta meta = ItemStackUtil.setSkullOwner(item.getItemMeta(), owner);
item.setItemMeta(meta);
}
}
return item;
}
case "图": {
MailIcon icon = manager.getMailIcon(draft.iconKey);
String itemKey = icon == null ? draft.iconKey.substring(1) : icon.item;
ItemStack item = ItemStackUtil.getItem(gui.getPlayer(), itemKey);
String resolvedKey = draft.iconKey;
if (icon != null && icon.display != null && !draft.iconKey.equals(icon.display)) {
resolvedKey = icon.display;
} else if (resolvedKey.startsWith("!")) {
resolvedKey = resolvedKey.substring(1);
}
return iconIcon.generateIcon(
target, item,
Pair.of("%icon%", resolvedKey)
);
}
case "题": {
return iconTitle.generateIcon(
gui, target,
Pair.of("%title%", draft.title)
);
}
case "文": {
return iconContent.generateIcon(
gui, target,
Pair.of("%content_size%", String.join("", draft.content).length())
);
}
case "高": {
if (target.hasPermission(PERM_ADMIN)) {
return iconAdvanced.generateIcon(gui, target);
} else {
Icon icon = otherIcon.get(iconAdvancedRedirectKey);
return icon == null ? null : icon.generateIcon(gui, target);
}
}
case "重": {
return iconReset.generateIcon(gui, target);
}
case "发": {
return iconSend.generateIcon(
gui, target,
Pair.of("%price%", String.format(Messages.Draft.money_format.str(), getPrice(target)))
);
}
case "附": {
if (iconIndex < draft.attachments.size()) {
IAttachment attachment = draft.attachments.get(iconIndex);
return attachment.generateDraftIcon(target);
} else {
return iconAttachment.generateIcon(gui, target);
}
}
}
return null;
}
public boolean testUsername(String name) {
Pattern regex = Pattern.compile(iconReceiverRegex);
return regex.matcher(name).matches();
}
/**
* 根据玩家拥有的权限,返回 MiniMessage 序列化器
* <ul>
* <li><code>sweetmail.format.all</code> 所有标签(不推荐给玩家)</li>
* <li><code>sweetmail.format.color.basic</code> 基本颜色和十六进制颜色</li>
* <li><code>sweetmail.format.color.gradient</code> 渐变颜色</li>
* <li><code>sweetmail.format.color.rainbow</code> 彩虹颜色</li>
* <li><code>sweetmail.format.decoration.basic</code> 加粗、斜体、下划线、删除线</li>
* <li><code>sweetmail.format.decoration.bold</code> 加粗</li>
* <li><code>sweetmail.format.decoration.italic</code> 斜体</li>
* <li><code>sweetmail.format.decoration.underline</code> 下划线</li>
* <li><code>sweetmail.format.decoration.strike</code> 删除线</li>
* <li><code>sweetmail.format.decoration.obfuscated</code> 乱码</li>
* <li><code>sweetmail.format.shadow</code> 文字阴影</li>
* <li><code>sweetmail.format.font</code> 自定义字体</li>
* <li><code>sweetmail.format.translatable</code> 客户端翻译</li>
* <li><code>sweetmail.format.keybind</code> 按键显示</li>
* <li><code>sweetmail.format.hover</code> 悬停显示</li>
* <li><code>sweetmail.format.click</code> 点击操作</li>
* <li><code>sweetmail.format.insertion</code> Shift点击插入操作</li>
* </ul>
*/
public MiniMessage getMiniMessage(Player player) {
if (player.hasPermission("sweetmail.format.all")) {
return MiniMessageConvert.miniMessage();
}
List<TagResolver> tags = new ArrayList<>();
if (player.hasPermission("sweetmail.format.color.basic")) {
tags.add(StandardTags.color());
}
if (player.hasPermission("sweetmail.format.color.gradient")) {
tags.add(StandardTags.gradient());
}
if (player.hasPermission("sweetmail.format.color.rainbow")) {
tags.add(StandardTags.rainbow());
}
if (player.hasPermission("sweetmail.format.decoration.basic")) {
tags.add(StandardTags.decorations(TextDecoration.BOLD));
tags.add(StandardTags.decorations(TextDecoration.ITALIC));
tags.add(StandardTags.decorations(TextDecoration.UNDERLINED));
tags.add(StandardTags.decorations(TextDecoration.STRIKETHROUGH));
} else {
if (player.hasPermission("sweetmail.format.decoration.bold")) {
tags.add(StandardTags.decorations(TextDecoration.BOLD));
}
if (player.hasPermission("sweetmail.format.decoration.italic")) {
tags.add(StandardTags.decorations(TextDecoration.ITALIC));
}
if (player.hasPermission("sweetmail.format.decoration.underline")) {
tags.add(StandardTags.decorations(TextDecoration.UNDERLINED));
}
if (player.hasPermission("sweetmail.format.decoration.strike")) {
tags.add(StandardTags.decorations(TextDecoration.STRIKETHROUGH));
}
}
if (player.hasPermission("sweetmail.format.decoration.obfuscated")) {
tags.add(StandardTags.decorations(TextDecoration.OBFUSCATED));
}
if (player.hasPermission("sweetmail.format.shadow")) {
tags.add(StandardTags.shadowColor());
}
if (player.hasPermission("sweetmail.format.font")) {
tags.add(StandardTags.font());
}
if (player.hasPermission("sweetmail.format.translatable")) {
tags.add(StandardTags.translatable());
tags.add(StandardTags.translatableFallback());
}
if (player.hasPermission("sweetmail.format.keybind")) {
tags.add(StandardTags.keybind());
}
if (player.hasPermission("sweetmail.format.hover")) {
tags.add(StandardTags.hoverEvent());
}
if (player.hasPermission("sweetmail.format.click")) {
tags.add(StandardTags.clickEvent());
}
if (player.hasPermission("sweetmail.format.insertion")) {
tags.add(StandardTags.insertion());
}
TagResolver[] array = tags.toArray(new TagResolver[0]);
return MiniMessage.builder().tags(TagResolver.builder().resolvers(array).build()).build();
}
public String format(Player player, String text) {
MiniMessage miniMessage = getMiniMessage(player);
Component component = MiniMessageConvert.miniMessage(text);
return miniMessage.serialize(component);
}
public List<String> format(Player player, List<String> lines) {
MiniMessage miniMessage = getMiniMessage(player);
List<String> list = new ArrayList<>();
for (String line : lines) {
Component component = MiniMessageConvert.miniMessage(line);
list.add(miniMessage.serialize(component));
}
return list;
}
public static MenuDraftConfig inst() {
return instanceOf(MenuDraftConfig.class);
}
public class Gui extends AbstractDraftGui {
public Gui(SweetMail plugin, Player player) {
super(plugin, player);
checkDraft();
}
public void checkDraft() {
int outdateHours = getDraftOutdateHours(player);
long now = Util.toTimestamp(LocalDateTime.now());
if (outdateHours > 0 && !player.hasPermission("sweetmail.draft.bypass.outdate")) {
long outdateTime = outdateHours * 3600L * 1000L;
if (draft.lastEditTime != null) {
long last = draft.lastEditTime;
if (now > last + outdateTime) {
LocalDateTime time = Util.fromTimestamp(last);
info("玩家 " + player.getName() + " 的草稿已过期重置");
t(player, plugin.prefix() + Messages.Draft.outdate_tips.str(
Pair.of("%time%", plugin.text().toStringTips(time))));
draft.reset();
}
}
LocalDateTime time = Util.fromTimestamp(now + outdateTime);
t(player, plugin.prefix() + Messages.Draft.open_tips.str(
Pair.of("%hours%", outdateHours),
Pair.of("%time%", plugin.text().toStringTips(time))));
}
// TODO: 将启用 PAPI 变量选项加到高级设置
draft.advPlaceholders = player.hasPermission("sweetmail.admin");
draft.lastEditTime = now;
draft.save();
}
@Override
public Inventory newInventory() {
created = createInventory(this, player);
applyIcons(this, created, player);
return created;
}
@Override
@SuppressWarnings({"deprecation"})
public void onClick(InventoryAction action, ClickType click, InventoryType.SlotType slotType, int slot, ItemStack currentItem, ItemStack cursor, InventoryView view, InventoryClickEvent event) {
Character c = getSlotKey(slot);
if (c == null) return;
event.setCancelled(true);
switch (String.valueOf(c)) {
case "接": {
if (click.isLeftClick() && !click.isShiftClick()) {
player.closeInventory();
ChatPrompter.prompt(
plugin, player,
iconReceiverPromptTips,
iconReceiverPromptCancel,
receiver -> {
if (testUsername(receiver)) {
OfflinePlayer offline = Util.getOfflinePlayer(receiver).orElse(null);
String id = plugin.getPlayerKey(offline);
if (id == null) {
t(player, plugin.prefix() + Messages.Draft.online__no_player.str());
reopen.run();
return;
}
draft.receiver = id;
} else {
t(player, plugin.prefix() + Messages.Draft.online__no_player.str());
}
draft.save();
reopen.run();
}, reopen
);
}
return;
}
case "图": {
if (click.isLeftClick() && !click.isShiftClick()) {
String title = player.hasPermission("sweetmail.icon.custom") ? iconIconTitleCustom : iconIconTitle;
plugin.getGuiManager().openGui(new GuiIcon(plugin, player, title));
}
return;
}
case "题": {
if (click.isLeftClick() && !click.isShiftClick()) {
player.closeInventory();
ChatPrompter.prompt(
plugin, player,
iconTitlePromptTips,
iconTitlePromptCancel,
title -> {
draft.title = format(player, title);
draft.save();
reopen.run();
}, reopen
);
}
return;
}
case "文": {
if (!click.isShiftClick()) {
if (click.isLeftClick()) {
ItemMeta rawMeta = cursor != null ? cursor.getItemMeta() : null;
if (rawMeta instanceof BookMeta) {
BookMeta meta = (BookMeta) rawMeta;
draft.content = format(player, meta.getPages());
draft.save();
applyIcon(this, view, player, slot);
Util.updateInventory(player);
} else {
Messages.Draft.cursor_no_book.tm(player);
}
}
if (click.isRightClick()) {
plugin.getBookImpl().openBook(player, draft);
}
}
return;
}
case "高": {
if (click.isLeftClick() && !click.isShiftClick()) {
if (player.hasPermission(PERM_ADMIN)) {
MenuDraftAdvanceConfig.inst()
.new Gui(plugin, player)
.open();
}
}
return;
}
case "重": {
if (click.isLeftClick() && !click.isShiftClick()) {
info("玩家 " + player.getName() + " 手动重置了草稿");
List<IAttachment> old = draft.attachments;
draft.reset();
draft.save();
for (IAttachment attachment : old) {
if (attachment.isLegal() && attachment.canGiveBack(player)) {
attachment.use(player);
}
}
reopen.run();
}
return;
}
case "发": {
if (click.isLeftClick() && !click.isShiftClick()) {
double price = getPrice(player);
if (!plugin.economy().has(player, price)) {
t(player, plugin.prefix() + Messages.Draft.no_money.str().replace("%price%", String.format(Messages.Draft.money_format.str(), price)));
return;
}
if (!canSendToYourself && draft.sender.equalsIgnoreCase(draft.receiver)) {
t(player, plugin.prefix() + Messages.Draft.cant_send_to_yourself.str());
return;
}
// 提醒发送人,计算泛接收人列表的时间可能会很长
if (draft.advReceivers != null && draft.advReceivers.startsWith("last ")) {
t(player, plugin.prefix() + Messages.Draft.send_with_adv_receivers.str());
}
player.closeInventory();
plugin.getScheduler().runAsync((t_) -> {
List<String> receivers = DraftManager.inst().generateReceivers(draft);
if (!canSendToYourself) receivers.remove(player.getName());
if (receivers.isEmpty()) {
t(player, plugin.prefix() + Messages.Draft.no_receivers.str());
return;
}
if (!plugin.economy().takeMoney(player, price)) {
t(player, plugin.prefix() + Messages.Draft.no_money.str().replace("%price%", String.format(Messages.Draft.money_format.str(), price)));
return;
}
String uuid = plugin.getMailDatabase().generateMailUUID();
if (draft.outdateDays == 0) {
draft.outdateDays = getOutdateDays(player);
}
Mail mail = draft.createMail(uuid, receivers);
plugin.getMailDatabase().sendMail(mail);
if (draft.advSenderDisplay == null) plugin.getScheduler().runNextTick((t__) -> {
PlayerMailSentEvent e = new PlayerMailSentEvent(player, draft.deepClone(), mail);
Bukkit.getPluginManager().callEvent(e);
});
draft.reset();
draft.save();
t(player, plugin.prefix() + Messages.Draft.sent.str());
});
}
return;
}
case "附": {
if (click.isLeftClick()) {
boolean hasCursorItem = cursor != null && !cursor.getType().equals(Material.AIR);
int i = getKeyIndex(c, slot);
if (i < draft.attachments.size()) {
if (!hasCursorItem) {
IAttachment attachment = draft.attachments.remove(i);
draft.save();
updateAttachmentSlots(view);
if (!player.hasPermission(PERM_ADMIN) || !click.isShiftClick()) {
if (attachment != null) plugin.getScheduler().runNextTick((t_) -> {
if (attachment.isLegal()) {
if (attachment.canGiveBack(player)) {
attachment.use(player);
}
} else {
IAttachment.Internal.useIllegalDeny(player);
}
});
}
}
} else if (!click.isShiftClick() && player.hasPermission(AttachmentItem.PERM)) {
// 快速添加物品附件
if (hasCursorItem) {
IAttachment attachment = AttachmentItem.build(cursor);
if (!attachment.isLegal()) {
t(player, plugin.prefix() + Messages.Draft.attachments__item__banned.str());
return;
}
event.setCursor(null);
draft.attachments.add(attachment);
draft.save();
updateAttachmentSlots(view);
return;
}
MenuAddAttachmentConfig.inst().new Gui(plugin, player).open();
}
}
return;
}
default: {
handleClick(player, click, c);
}
}
}
private void updateAttachmentSlots(InventoryView view) {
for (int k = 0; k < inventory.length; k++) {
if (inventory[k] == '附') {
applyIcon(this, view, player, k);
}
}
Util.updateInventory(player);
}
}
}
| 412 | 0.943299 | 1 | 0.943299 | game-dev | MEDIA | 0.91938 | game-dev | 0.986307 | 1 | 0.986307 |
SeismicSystems/seismic-revm | 1,551 | crates/handler/src/lib.rs | //! EVM execution handling.
#![cfg_attr(not(test), warn(unused_crate_dependencies))]
#![cfg_attr(not(feature = "std"), no_std)]
#[cfg(not(feature = "std"))]
extern crate alloc as std;
// Mainnet related handlers.
/// EVM execution API traits and implementations.
pub mod api;
/// Core EVM traits for execution and frame management.
pub mod evm;
/// EVM execution logic and utilities.
pub mod execution;
mod frame;
mod frame_data;
/// Handler implementation for orchestrating EVM execution.
pub mod handler;
/// EVM instruction set implementations and tables.
pub mod instructions;
mod item_or_result;
mod mainnet_builder;
mod mainnet_handler;
/// Post-execution operations including gas refunds and state finalization.
pub mod post_execution;
pub mod pre_execution;
mod precompile_provider;
/// System call implementations for special EVM operations.
pub mod system_call;
/// Transaction and environment validation utilities.
pub mod validation;
// Public exports
pub use api::{ExecuteCommitEvm, ExecuteEvm};
pub use evm::{EvmTr, FrameTr};
pub use frame::{return_create, ContextTrDbError, EthFrame};
pub use frame_data::{CallFrame, CreateFrame, FrameData, FrameResult};
pub use handler::{EvmTrError, Handler};
pub use item_or_result::{FrameInitOrResult, ItemOrResult};
pub use mainnet_builder::{MainBuilder, MainContext, MainnetContext, MainnetEvm};
pub use mainnet_handler::MainnetHandler;
pub use precompile_provider::{EthPrecompiles, PrecompileProvider};
pub use system_call::{SystemCallCommitEvm, SystemCallEvm, SystemCallTx, SYSTEM_ADDRESS};
| 412 | 0.897804 | 1 | 0.897804 | game-dev | MEDIA | 0.355164 | game-dev | 0.579169 | 1 | 0.579169 |
fuse-open/fuse-studio | 39,768 | 3rdparty/NRefactory/ICSharpCode.NRefactory.Tests/IndentationTests/TestFiles/IndentState.cs | //
// IndentState.cs
//
// Author:
// Matej Miklečić <matej.miklecic@gmail.com>
//
// Copyright (c) 2013 Matej Miklečić (matej.miklecic@gmail.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
namespace ICSharpCode.NRefactory.CSharp
{
#region IndentState
/// <summary>
/// The base class for all indentation states.
/// Each state defines the logic for indentation based on chars that
/// are pushed to it.
/// </summary>
public abstract class IndentState : ICloneable
{
#region Properties
/// <summary>
/// The indentation engine using this state.
/// </summary>
public IndentEngine Engine;
/// <summary>
/// The parent state.
/// This state can use the indentation levels of its parent.
/// When this state exits, the engine returns to the parent.
/// </summary>
public IndentState Parent;
/// <summary>
/// The indentation of the current line.
/// This is set when the state is created and will be changed to
/// <see cref="NextLineIndent"/> when the <see cref="IndentEngine.NewLineChar"/>
/// is pushed.
/// </summary>
public Indent ThisLineIndent;
/// <summary>
/// The indentation of the next line.
/// This is set when the state is created and can change depending
/// on the pushed chars.
/// </summary>
public Indent NextLineIndent;
/// <summary>
/// Stores the last sequence of characters that can form a
/// valid keyword or variable name.
/// </summary>
public StringBuilder WordToken;
#endregion
#region Constructors
/// <summary>
/// Creates a new indentation state.
/// </summary>
/// <param name="engine">
/// The indentation engine that uses this state.
/// </param>
/// <param name="parent">
/// The parent state, or null if this state doesn't have one ->
/// e.g. the state represents the global space.
/// </param>
protected IndentState(IndentEngine engine, IndentState parent = null)
{
WordToken = new StringBuilder();
Parent = parent;
Engine = engine;
InitializeState();
}
/// <summary>
/// Creates a new indentation state that is a copy of the given
/// prototype.
/// </summary>
/// <param name="prototype">
/// The prototype state.
/// </param>
protected IndentState(IndentState prototype)
{
Engine = prototype.Engine;
Parent = prototype.Parent.Clone();
WordToken = new StringBuilder(prototype.WordToken.ToString());
ThisLineIndent = prototype.ThisLineIndent.Clone();
NextLineIndent = prototype.NextLineIndent.Clone();
}
#endregion
#region IClonable
object ICloneable.Clone()
{
return Clone();
}
public abstract IndentState Clone();
#endregion
#region Methods
/// <summary>
/// Initializes the state:
/// - sets the default indentation levels.
/// </summary>
/// <remarks>
/// Each state can override this method if it needs a different
/// logic for setting up the default indentations.
/// </remarks>
public virtual void InitializeState()
{
ThisLineIndent = new Indent(Engine.TextEditorOptions);
NextLineIndent = ThisLineIndent.Clone();
}
/// <summary>
/// Actions performed when this state exits.
/// </summary>
public virtual void OnExit()
{
// if a state exits on the newline character, it has to push
// it back to its parent (and so on recursively if the parent
// state also exits). Otherwise, the parent state wouldn't
// know that the engine isn't on the same line anymore.
if (Engine.CurrentChar == Engine.NewLineChar)
{
Parent.Push(Engine.NewLineChar);
}
// when a state exits the engine stays on the same line and this
// state has to adjust the current indent of its parent so that
// it's equal to this line indent.
Parent.ThisLineIndent = ThisLineIndent.Clone();
}
/// <summary>
/// Changes the current state of the <see cref="IndentEngine"/> using the current
/// state as the parent for the new one.
/// </summary>
/// <typeparam name="T">
/// The type of the new state. Must be assignable from <see cref="IndentState"/>.
/// </typeparam>
public void ChangeState<T>()
where T : IndentState
{
Engine.CurrentState = IndentStateFactory.Create<T>(Engine.CurrentState);
}
/// <summary>
/// Exits this state by setting the current state of the
/// <see cref="IndentEngine"/> to this state's parent.
/// </summary>
public void ExitState()
{
OnExit();
Engine.CurrentState = Engine.CurrentState.Parent;
}
/// <summary>
/// Common logic behind the push method.
/// Each state can override this method and implement its own logic.
/// </summary>
/// <param name="ch">
/// The current character that's being pushed.
/// </param>
public virtual void Push(char ch)
{
// append this char to the wordbuf if it can form a valid keyword, otherwise check
// if the last sequence of chars form a valid keyword and reset the wordbuf.
if ((WordToken.Length == 0 ? char.IsLetter(ch) : char.IsLetterOrDigit(ch)) || ch == '_')
{
WordToken.Append(ch);
}
else
{
CheckKeyword(WordToken.ToString());
WordToken.Length = 0;
}
if (ch == Engine.NewLineChar)
{
if (Engine.IsLineStart && !Engine.TextEditorOptions.IndentBlankLines)
{
ThisLineIndent = new Indent(Engine.TextEditorOptions);
}
if (Engine.CurrentState == this)
{
// if we got this far, the current line indent becomes permanent,
// it's replaced with the next line indent and we can raise an
// event that can perform text-replace actions on the document.
// NOTE: It's possible that multiple states will execute its push
// methods on the same newline char, but only the current state of
// the engine should raise this event. See the OnExit method for
// an example when this will happen.
Engine.ThisLineIndentFinalized();
}
ThisLineIndent = NextLineIndent.Clone();
}
}
/// <summary>
/// When derived, checks if the given sequence of chars form
/// a valid keyword or variable name, depending on the state.
/// </summary>
/// <param name="keyword">
/// A possible keyword.
/// </param>
public virtual void CheckKeyword(string keyword)
{ }
#endregion
}
#endregion
#region IndentStateFactory
/// <summary>
/// Indentation state factory.
/// </summary>
public static class IndentStateFactory
{
/// <summary>
/// Creates a new state.
/// </summary>
/// <param name="stateType">
/// Type of the state. Must be assignable from <see cref="IndentState"/>.
/// </param>
/// <param name="engine">
/// Indentation engine for the state.
/// </param>
/// <param name="parent">
/// Parent state.
/// </param>
/// <returns>
/// A new state of type <paramref name="stateType"/>.
/// </returns>
static IndentState Create(Type stateType, IndentEngine engine, IndentState parent = null)
{
return (IndentState)Activator.CreateInstance(stateType, engine, parent);
}
/// <summary>
/// Creates a new state.
/// </summary>
/// <typeparam name="T">
/// Type of the state. Must be assignable from <see cref="IndentState"/>.
/// </typeparam>
/// <param name="engine">
/// Indentation engine for the state.
/// </param>
/// <param name="parent">
/// Parent state.
/// </param>
/// <returns>
/// A new state of type <typeparamref name="T"/>.
/// </returns>
public static IndentState Create<T>(IndentEngine engine, IndentState parent = null)
where T : IndentState
{
return Create(typeof(T), engine, parent);
}
/// <summary>
/// Creates a new state.
/// </summary>
/// <typeparam name="T">
/// Type of the state. Must be assignable from <see cref="IndentState"/>.
/// </typeparam>
/// <param name="prototype">
/// Parent state. Also, the indentation engine of the prototype is
/// used as the engine for the new state.
/// </param>
/// <returns>
/// A new state of type <typeparamref name="T"/>.
/// </returns>
public static IndentState Create<T>(IndentState prototype)
where T : IndentState
{
return Create(typeof(T), prototype.Engine, prototype);
}
/// <summary>
/// The default state, used for the global space.
/// </summary>
public static Func<IndentEngine, IndentState> Default = engine => Create<GlobalBodyState>(engine);
}
#endregion
#region Null state
/// <summary>
/// Null state.
/// </summary>
/// <remarks>
/// Doesn't define any transitions to new states.
/// </remarks>
public class NullState : IndentState
{
public NullState(IndentEngine engine, IndentState parent = null)
: base(engine, parent)
{ }
public NullState(NullState prototype)
: base(prototype)
{ }
public override void Push(char ch)
{ }
public override IndentState Clone()
{
return new NullState(this);
}
}
#endregion
#region Brackets body states
#region Brackets body base
/// <summary>
/// The base for all brackets body states.
/// </summary>
/// <remarks>
/// Represents a block of code between a pair of brackets.
/// </remarks>
public abstract class BracketsBodyBaseState : IndentState
{
/// <summary>
/// Defines transitions for all types of open brackets.
/// </summary>
public static Dictionary<char, Action<IndentState>> OpenBrackets =
new Dictionary<char, Action<IndentState>>
{
{ '{', state => state.ChangeState<BracesBodyState>() },
{ '(', state => state.ChangeState<ParenthesesBodyState>() },
{ '[', state => state.ChangeState<SquareBracketsBodyState>() },
// since the '<' char is also used as the 'less-than' operator,
// until the logic for distinguishing this two cases is implemented
// this state must not define this next transition.
// { '<', state => state.ChangeState<AngleBracketsBody>() }
};
/// <summary>
/// When derived in a concrete bracket body state, represents
/// the closed bracket character pair.
/// </summary>
public abstract char ClosedBracket { get; }
protected BracketsBodyBaseState(IndentEngine engine, IndentState parent = null)
: base(engine, parent)
{ }
protected BracketsBodyBaseState(BracketsBodyBaseState prototype)
: base(prototype)
{ }
public override void Push(char ch)
{
base.Push(ch);
if (ch == '#' && Engine.IsLineStart)
{
ChangeState<PreProcessorState>();
}
else if (ch == '/' && Engine.PreviousChar == '/')
{
ChangeState<LineCommentState>();
}
else if (ch == '*' && Engine.PreviousChar == '/')
{
ChangeState<MultiLineCommentState>();
}
else if (ch == '"')
{
if (Engine.PreviousChar == '@')
{
ChangeState<VerbatimStringState>();
}
else
{
ChangeState<StringLiteralState>();
}
}
else if (ch == '\'')
{
ChangeState<CharacterState>();
}
else if (OpenBrackets.ContainsKey(ch))
{
OpenBrackets[ch](this);
}
else if (ch == ClosedBracket)
{
ExitState();
}
}
}
#endregion
#region Global body state
/// <summary>
/// Global body state.
/// </summary>
/// <remarks>
/// Represents the global space of the program.
/// </remarks>
public class GlobalBodyState : BracketsBodyBaseState
{
public override char ClosedBracket
{
get { return '\0'; }
}
public GlobalBodyState(IndentEngine engine, IndentState parent = null)
: base(engine, parent)
{ }
public GlobalBodyState(GlobalBodyState prototype)
: base(prototype)
{ }
public override IndentState Clone()
{
return new GlobalBodyState(this);
}
}
#endregion
#region Braces body state
/// <summary>
/// Braces body state.
/// </summary>
/// <remarks>
/// Represents a block of code between { and }.
/// </remarks>
public class BracesBodyState : BracketsBodyBaseState
{
public override char ClosedBracket
{
get { return '}'; }
}
/// <summary>
/// Type of the current block body.
/// </summary>
public Body CurrentBody;
/// <summary>
/// Type of the next block body.
/// Same as <see cref="CurrentBody"/> if none of the
/// <see cref="Body"/> keywords have been read.
/// </summary>
public Body NextBody;
/// <summary>
/// Type of the current statement.
/// </summary>
public Statement CurrentStatement;
/// <summary>
/// True if the '=' char has been pushed.
/// </summary>
public bool IsRightHandExpression;
public BracesBodyState(IndentEngine engine, IndentState parent = null)
: base(engine, parent)
{
CurrentBody = NextBody = BracesBodyState.extractBody(Parent);
CurrentStatement = Statement.None;
}
public BracesBodyState(BracesBodyState prototype)
: base(prototype)
{
CurrentBody = prototype.CurrentBody;
NextBody = prototype.NextBody;
CurrentStatement = prototype.CurrentStatement;
IsRightHandExpression = prototype.IsRightHandExpression;
}
/// <summary>
/// Extracts the <see cref="CurrentBody"/> from the given state.
/// </summary>
/// <returns>
/// The correct <see cref="Body"/> type for this state.
/// </returns>
static Body extractBody(IndentState state)
{
if (state != null && state is BracesBodyState)
{
return ((BracesBodyState)state).NextBody;
}
return Body.None;
}
public override void Push(char ch)
{
if (ch == ':' && Engine.IsLineStart)
{
ThisLineIndent.Push(IndentType.Continuation);
}
if (ch == ';' || ch == ':')
{
while (NextLineIndent.Count > 0 && NextLineIndent.Peek() == IndentType.Continuation)
{
NextLineIndent.Pop();
}
NextLineIndent.ExtraSpaces = 0;
IsRightHandExpression = false;
}
else if (ch == '=' && !IsRightHandExpression)
{
IsRightHandExpression = true;
NextLineIndent.ExtraSpaces = Engine.column - NextLineIndent.CurIndent + 1;
}
else if (ch == '.' && IsRightHandExpression)
{
NextLineIndent.ExtraSpaces = Engine.column - NextLineIndent.CurIndent - 1;
}
else if (ch == Engine.NewLineChar && NextLineIndent.ExtraSpaces > 0 &&
(Engine.PreviousChar == '=' || Engine.PreviousChar == '.'))
{
// the last significant pushed char was '=' or '.' and we added
// extra spaces to align the next line, but the newline char was
// pushed afterwards so it's better to replace the extra spaces
// with one continuation indent.
NextLineIndent.ExtraSpaces = 0;
NextLineIndent.Push(IndentType.Continuation);
}
else if (ch == ClosedBracket && Engine.IsLineStart)
{
ThisLineIndent = Parent.ThisLineIndent.Clone();
}
base.Push(ch);
}
public override void InitializeState()
{
// remove all continuations and extra spaces from the previous state
Parent.ThisLineIndent.ExtraSpaces = 0;
Parent.NextLineIndent.ExtraSpaces = 0;
if (Parent.NextLineIndent.Count > 0 && Parent.NextLineIndent.Peek() == IndentType.Continuation)
{
Parent.NextLineIndent.Pop();
Parent.ThisLineIndent = Parent.NextLineIndent.Clone();
}
ThisLineIndent = Parent.ThisLineIndent.Clone();
NextLineIndent = ThisLineIndent.Clone();
AddIndentation(CurrentBody);
}
public override IndentState Clone()
{
return new BracesBodyState(this);
}
#region Helpers
/// <summary>
/// Types of braces bodies.
/// </summary>
public enum Body
{
None,
Namespace,
Class,
Struct,
Interface,
Enum,
Switch,
Case
}
/// <summary>
/// Types of statements.
/// </summary>
public enum Statement
{
None,
If,
Else,
Do,
While,
For,
Foreach,
Lock,
Using
}
/// <summary>
/// Checks if the given string is a keyword and sets the
/// <see cref="NextBody"/> and the <see cref="CurrentStatement"/>
/// variables appropriately.
/// </summary>
/// <param name="keyword">
/// A possible keyword.
/// </param>
public override void CheckKeyword(string keyword)
{
var blocks = new Dictionary<string, Body>
{
{ "namespace", Body.Namespace },
{ "class", Body.Class },
{ "struct", Body.Struct },
{ "interface", Body.Interface },
{ "enum", Body.Enum },
{ "switch", Body.Switch },
};
var statements = new Dictionary<string, Statement>
{
{ "if", Statement.If },
{ "else", Statement.Else },
{ "do", Statement.Do },
{ "while", Statement.While },
{ "for", Statement.For },
{ "foreach", Statement.Foreach },
{ "lock", Statement.Lock },
{ "using", Statement.Using },
};
if (blocks.ContainsKey(keyword))
{
NextBody = blocks[keyword];
}
else if (new string[] { "case", "default" }.Contains(keyword) && NextBody == Body.Switch)
{
ChangeState<SwitchCaseState>();
}
else if (keyword == "where" && !IsRightHandExpression)
{
ThisLineIndent.Push(IndentType.Continuation);
}
else if (statements.ContainsKey(keyword))
{
// only add continuation for 'else' in 'else if' statement.
if (!(statements[keyword] == Statement.If && CurrentStatement == Statement.Else))
{
NextLineIndent.Push(IndentType.Continuation);
}
CurrentStatement = statements[keyword];
}
}
/// <summary>
/// Pushes a new level of indentation depending on the given
/// <paramref name="braceStyle"/>.
/// </summary>
void AddIndentation(BraceStyle braceStyle)
{
switch (braceStyle)
{
case BraceStyle.DoNotChange:
case BraceStyle.EndOfLine:
case BraceStyle.EndOfLineWithoutSpace:
case BraceStyle.NextLine:
case BraceStyle.NextLineShifted:
case BraceStyle.BannerStyle:
NextLineIndent.Push(IndentType.Block);
break;
case BraceStyle.NextLineShifted2:
NextLineIndent.Push(IndentType.DoubleBlock);
break;
}
}
/// <summary>
/// Pushes a new level of indentation depending on the given
/// <paramref name="body"/>.
/// </summary>
void AddIndentation(Body body)
{
switch (body)
{
case Body.None:
NextLineIndent.Push(IndentType.Block);
break;
case Body.Namespace:
AddIndentation(Engine.Options.NamespaceBraceStyle);
break;
case Body.Class:
AddIndentation(Engine.Options.ClassBraceStyle);
break;
case Body.Struct:
AddIndentation(Engine.Options.StructBraceStyle);
break;
case Body.Interface:
AddIndentation(Engine.Options.InterfaceBraceStyle);
break;
case Body.Enum:
AddIndentation(Engine.Options.EnumBraceStyle);
break;
case Body.Switch:
if (Engine.Options.IndentSwitchBody)
NextLineIndent.Push(IndentType.Empty);
break;
default:
throw new ArgumentOutOfRangeException();
}
}
#endregion
}
#endregion
#region Switch-case body state
/// <summary>
/// Switch-case statement state.
/// </summary>
/// <remarks>
/// Represents the block of code in one switch case (including default).
/// </remarks>
public class SwitchCaseState : BracesBodyState
{
public SwitchCaseState(IndentEngine engine, IndentState parent = null)
: base(engine, parent)
{ }
public SwitchCaseState(SwitchCaseState prototype)
: base(prototype)
{ }
public override void Push(char ch)
{
if (ch == ClosedBracket)
{
ExitState();
}
base.Push(ch);
}
public override void InitializeState()
{
ThisLineIndent = Parent.ThisLineIndent.Clone();
// remove all continuations and extra spaces from this line indent
ThisLineIndent.ExtraSpaces = 0;
if (ThisLineIndent.Count > 0 && ThisLineIndent.Peek() == IndentType.Continuation)
{
ThisLineIndent.Pop();
}
NextLineIndent = ThisLineIndent.Clone();
NextLineIndent.Push(IndentType.Block);
}
public override void CheckKeyword(string keyword)
{
if (new string[] { "case", "default" }.Contains(keyword))
{
ExitState();
}
base.CheckKeyword(keyword);
}
public override void OnExit()
{ }
public override IndentState Clone()
{
return new SwitchCaseState(this);
}
}
#endregion
#region Parentheses body state
/// <summary>
/// Parentheses body state.
/// </summary>
/// <remarks>
/// Represents a block of code between ( and ).
/// </remarks>
public class ParenthesesBodyState : BracketsBodyBaseState
{
public override char ClosedBracket
{
get { return ')'; }
}
public ParenthesesBodyState(IndentEngine engine, IndentState parent = null)
: base(engine, parent)
{ }
public ParenthesesBodyState(ParenthesesBodyState prototype)
: base(prototype)
{ }
public override void InitializeState()
{
ThisLineIndent = Parent.ThisLineIndent.Clone();
NextLineIndent = ThisLineIndent.Clone();
// align the next line at the beginning of the open bracket
NextLineIndent.ExtraSpaces = Math.Max(0, Engine.column - NextLineIndent.CurIndent);
}
public override IndentState Clone()
{
return new ParenthesesBodyState(this);
}
}
#endregion
#region Square brackets body state
/// <summary>
/// Square brackets body state.
/// </summary>
/// <remarks>
/// Represents a block of code between [ and ].
/// </remarks>
public class SquareBracketsBodyState : BracketsBodyBaseState
{
public override char ClosedBracket
{
get { return ']'; }
}
public SquareBracketsBodyState(IndentEngine engine, IndentState parent = null)
: base(engine, parent)
{ }
public SquareBracketsBodyState(SquareBracketsBodyState prototype)
: base(prototype)
{ }
public override void InitializeState()
{
ThisLineIndent = Parent.ThisLineIndent.Clone();
NextLineIndent = ThisLineIndent.Clone();
// align the next line at the beginning of the open bracket
NextLineIndent.ExtraSpaces = Math.Max(0, Engine.column - NextLineIndent.CurIndent);
}
public override IndentState Clone()
{
return new SquareBracketsBodyState(this);
}
}
#endregion
#region Angle brackets body state
/// <summary>
/// Angle brackets body state.
/// </summary>
/// <remarks>
/// Represents a block of code between < and >.
/// </remarks>
public class AngleBracketsBodyState : BracketsBodyBaseState
{
public override char ClosedBracket
{
get { return '>'; }
}
public AngleBracketsBodyState(IndentEngine engine, IndentState parent = null)
: base(engine, parent)
{ }
public AngleBracketsBodyState(AngleBracketsBodyState prototype)
: base(prototype)
{ }
public override void InitializeState()
{
ThisLineIndent = Parent.ThisLineIndent.Clone();
NextLineIndent = ThisLineIndent.Clone();
// align the next line at the beginning of the open bracket
NextLineIndent.ExtraSpaces = Math.Max(0, Engine.column - NextLineIndent.CurIndent);
}
public override IndentState Clone()
{
return new AngleBracketsBodyState(this);
}
}
#endregion
#endregion
#region PreProcessor state
/// <summary>
/// PreProcessor directive state.
/// </summary>
/// <remarks>
/// Activated when the '#' char is pushed and the
/// <see cref="IndentEngine.IsLineStart"/> is true.
/// </remarks>
public class PreProcessorState : IndentState
{
/// <summary>
/// The type of the preprocessor directive.
/// </summary>
public PreProcessorDirective DirectiveType;
/// <summary>
/// If <see cref="DirectiveType"/> is set (not equal to 'None'), this
/// stores the expression of the directive.
/// </summary>
public StringBuilder DirectiveStatement;
public PreProcessorState(IndentEngine engine, IndentState parent = null)
: base(engine, parent)
{
DirectiveType = PreProcessorDirective.None;
DirectiveStatement = new StringBuilder();
}
public PreProcessorState(PreProcessorState prototype)
: base(prototype)
{
DirectiveType = prototype.DirectiveType;
DirectiveStatement = new StringBuilder(prototype.DirectiveStatement.ToString());
}
public override void Push(char ch)
{
base.Push(ch);
if (DirectiveType != PreProcessorDirective.None)
{
DirectiveStatement.Append(ch);
}
if (ch == Engine.NewLineChar)
{
ExitState();
switch (DirectiveType)
{
case PreProcessorDirective.If:
if (!Engine.IfDirectiveEvalResult)
{
Engine.IfDirectiveEvalResult = eval(DirectiveStatement.ToString());
if (Engine.IfDirectiveEvalResult)
{
// the if/elif directive is true -> continue with the previous state
}
else
{
// the if/elif directive is false -> change to a state that will
// ignore any chars until #endif or #elif
ChangeState<PreProcessorCommentState>();
}
}
else
{
// one of the if/elif directives in this block was true ->
// change to a state that will ignore any chars until #endif
ChangeState<PreProcessorCommentState>();
}
break;
case PreProcessorDirective.Else:
if (Engine.IfDirectiveEvalResult)
{
// some if/elif directive was true -> change to a state that will
// ignore any chars until #endif
ChangeState<PreProcessorCommentState>();
}
else
{
// none if/elif directives were true -> continue with the previous state
}
break;
case PreProcessorDirective.Define:
var defineSymbol = DirectiveStatement.ToString().Trim();
if (!Engine.ConditionalSymbols.Contains(defineSymbol))
{
Engine.ConditionalSymbols.Add(defineSymbol);
}
break;
case PreProcessorDirective.Undef:
var undefineSymbol = DirectiveStatement.ToString().Trim();
if (Engine.ConditionalSymbols.Contains(undefineSymbol))
{
Engine.ConditionalSymbols.Remove(undefineSymbol);
}
break;
case PreProcessorDirective.Endif:
// marks the end of this block
Engine.IfDirectiveEvalResult = false;
break;
case PreProcessorDirective.Region:
case PreProcessorDirective.Pragma:
case PreProcessorDirective.Warning:
case PreProcessorDirective.Error:
case PreProcessorDirective.Line:
// continue with the previous state
break;
}
}
}
public override void InitializeState()
{
if (Engine.Options.IndentPreprocessorStatements)
{
ThisLineIndent = Parent.ThisLineIndent.Clone();
}
else
{
ThisLineIndent = new Indent(Engine.TextEditorOptions);
}
NextLineIndent = Parent.NextLineIndent.Clone();
}
public override void CheckKeyword(string keyword)
{
if (DirectiveType != PreProcessorDirective.None)
{
// the directive type has already been set
return;
}
var preProcessorDirectives = new Dictionary<string, PreProcessorDirective>
{
{ "if", PreProcessorDirective.If },
{ "elif", PreProcessorDirective.If },
{ "else", PreProcessorDirective.Else },
{ "endif", PreProcessorDirective.Endif },
{ "region", PreProcessorDirective.Region },
{ "endregion", PreProcessorDirective.Region },
{ "pragma", PreProcessorDirective.Pragma },
{ "warning", PreProcessorDirective.Warning },
{ "error", PreProcessorDirective.Error },
{ "line", PreProcessorDirective.Line },
{ "define", PreProcessorDirective.Define },
{ "undef", PreProcessorDirective.Undef }
};
if (preProcessorDirectives.ContainsKey(keyword))
{
DirectiveType = preProcessorDirectives[keyword];
if (DirectiveType == PreProcessorDirective.Region)
{
// adjust the indentation for the region/endregion directives
ThisLineIndent = Parent.NextLineIndent.Clone();
}
}
}
public override IndentState Clone()
{
return new PreProcessorState(this);
}
/// <summary>
/// Types of preprocessor directives.
/// </summary>
public enum PreProcessorDirective
{
None,
If,
// Elif, // use If instead
Else,
Endif,
Region,
// EndRegion, // use Region instead
Pragma,
Warning,
Error,
Line,
Define,
Undef
}
#region Pre processor evaluation (from cs-tokenizer.cs)
static bool is_identifier_start_character(int c)
{
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || Char.IsLetter((char)c);
}
static bool is_identifier_part_character(char c)
{
if (c >= 'a' && c <= 'z')
return true;
if (c >= 'A' && c <= 'Z')
return true;
if (c == '_' || (c >= '0' && c <= '9'))
return true;
if (c < 0x80)
return false;
return Char.IsLetter(c) || Char.GetUnicodeCategory(c) == UnicodeCategory.ConnectorPunctuation;
}
bool eval_val(string s)
{
if (s == "true")
return true;
if (s == "false")
return false;
return Engine.ConditionalSymbols != null && Engine.ConditionalSymbols.Contains(s);
}
bool pp_primary(ref string s)
{
s = s.Trim();
int len = s.Length;
if (len > 0)
{
char c = s[0];
if (c == '(')
{
s = s.Substring(1);
bool val = pp_expr(ref s, false);
f (s.Length > 0 && s[0] == ')')
{
s = s.Substring(1);
return val;
}
return false;
}
if (is_identifier_start_character(c))
{
int j = 1;
while (j < len)
{
c = s[j];
if (is_identifier_part_character(c))
{
j++;
continue;
}
bool v = eval_val(s.Substring(0, j));
s = s.Substring(j);
return v;
}
bool vv = eval_val(s);
s = "";
return vv;
}
}
return false;
}
bool pp_unary(ref string s)
{
s = s.Trim();
int len = s.Length;
if (len > 0)
{
if (s[0] == '!')
{
if (len > 1 && s[1] == '=')
{
return false;
}
s = s.Substring(1);
return !pp_primary(ref s);
}
else
return pp_primary(ref s);
}
else
{
return false;
}
}
bool pp_eq(ref string s)
{
bool va = pp_unary(ref s);
s = s.Trim();
int len = s.Length;
if (len > 0)
{
if (s[0] == '=')
{
if (len > 2 && s[1] == '=')
{
s = s.Substring(2);
return va == pp_unary(ref s);
}
else
{
return false;
}
}
else if (s[0] == '!' && len > 1 && s[1] == '=')
{
s = s.Substring(2);
return va != pp_unary(ref s);
}
}
return va;
}
bool pp_and(ref string s)
{
bool va = pp_eq(ref s);
s = s.Trim();
int len = s.Length;
if (len > 0)
{
if (s[0] == '&')
{
if (len > 2 && s[1] == '&')
{
s = s.Substring(2);
return (va & pp_and(ref s));
}
else
{
return false;
}
}
}
return va;
}
//
// Evaluates an expression for `#if' or `#elif'
//
bool pp_expr(ref string s, bool isTerm)
{
bool va = pp_and(ref s);
s = s.Trim();
int len = s.Length;
if (len > 0)
{
char c = s[0];
if (c == '|')
{
if (len > 2 && s[1] == '|')
{
s = s.Substring(2);
return va | pp_expr(ref s, isTerm);
}
else
{
return false;
}
}
if (isTerm)
{
return false;
}
}
return va;
}
bool eval(string s)
{
bool v = pp_expr(ref s, true);
s = s.Trim();
if (s.Length != 0)
{
return false;
}
return v;
}
#endregion
}
#endregion
#region PreProcessorComment state
/// <summary>
/// PreProcessor comment state.
/// </summary>
/// <remarks>
/// Activates when the #if or #elif directive is false and ignores
/// all pushed chars until the next '#'.
/// </remarks>
public class PreProcessorCommentState : IndentState
{
public PreProcessorCommentState(IndentEngine engine, IndentState parent = null)
: base(engine, parent)
{ }
public PreProcessorCommentState(PreProcessorCommentState prototype)
: base(prototype)
{ }
public override void Push(char ch)
{
base.Push(ch);
if (ch == '#' && Engine.IsLineStart)
{
// TODO: Return back only on #if/#elif/#else/#endif
// Ignore any of the other directives (especially #define/#undef)
ExitState();
ChangeState<PreProcessorState>();
}
}
public override void InitializeState()
{
ThisLineIndent = Parent.NextLineIndent.Clone();
NextLineIndent = ThisLineIndent.Clone();
}
public override IndentState Clone()
{
return new PreProcessorCommentState(this);
}
}
#endregion
#region LineComment state
/// <summary>
/// Single-line comment state.
/// </summary>
public class LineCommentState : IndentState
{
/// <summary>
/// It's possible that this should be the DocComment state ->
/// Check if the first next pushed char is equal to '/'.
/// </summary>
public bool CheckForDocComment = true;
public LineCommentState(IndentEngine engine, IndentState parent = null)
: base(engine, parent)
{ }
public LineCommentState(LineCommentState prototype)
: base(prototype)
{
CheckForDocComment = prototype.CheckForDocComment;
}
public override void Push(char ch)
{
base.Push(ch);
if (ch == Engine.NewLineChar)
{
ExitState();
}
else if (ch == '/' && CheckForDocComment)
{
// wrong state, should be DocComment.
ExitState();
ChangeState<DocCommentState>();
}
CheckForDocComment = false;
}
public override void InitializeState()
{
ThisLineIndent = Parent.ThisLineIndent.Clone();
NextLineIndent = Parent.NextLineIndent.Clone();
}
public override IndentState Clone()
{
return new LineCommentState(this);
}
}
#endregion
#region DocComment state
/// <summary>
/// XML documentation comment state.
/// </summary>
public class DocCommentState : IndentState
{
public DocCommentState(IndentEngine engine, IndentState parent = null)
: base(engine, parent)
{ }
public DocCommentState(DocCommentState prototype)
: base(prototype)
{ }
public override void Push(char ch)
{
base.Push(ch);
if (ch == Engine.NewLineChar)
{
ExitState();
}
}
public override void InitializeState()
{
ThisLineIndent = Parent.ThisLineIndent.Clone();
NextLineIndent = Parent.NextLineIndent.Clone();
}
public override IndentState Clone()
{
return new DocCommentState(this);
}
}
#endregion
#region MultiLineComment state
/// <summary>
/// Multi-line comment state.
/// </summary>
public class MultiLineCommentState : IndentState
{
/// <summary>
/// True if any char has been pushed to this state.
/// </summary>
/// <remarks>
/// Needed to resolve an issue when the first pushed char is '/'.
/// The state would falsely exit on this sequence of chars '/*/',
/// since it only checks if the last two chars are '/' and '*'.
/// </remarks>
public bool IsAnyCharPushed;
public MultiLineCommentState(IndentEngine engine, IndentState parent = null)
: base(engine, parent)
{ }
public MultiLineCommentState(MultiLineCommentState prototype)
: base(prototype)
{
IsAnyCharPushed = prototype.IsAnyCharPushed;
}
public override void Push(char ch)
{
base.Push(ch);
if (ch == '/' && Engine.PreviousChar == '*' && IsAnyCharPushed)
{
ExitState();
}
IsAnyCharPushed = true;
}
public override void InitializeState()
{
ThisLineIndent = Parent.ThisLineIndent.Clone();
NextLineIndent = ThisLineIndent.Clone();
// add extra spaces so that the next line of the comment is align
// to the first character in the first line of the comment
NextLineIndent.ExtraSpaces = Math.Max(0, Engine.column - NextLineIndent.CurIndent + 1);
}
public override IndentState Clone()
{
return new MultiLineCommentState(this);
}
}
#endregion
#region StringLiteral state
/// <summary>
/// StringLiteral state.
/// </summary>
public class StringLiteralState : IndentState
{
/// <summary>
/// True if the next char is escaped with '\'.
/// </summary>
public bool IsEscaped;
public StringLiteralState(IndentEngine engine, IndentState parent = null)
: base(engine, parent)
{ }
public StringLiteralState(StringLiteralState prototype)
: base(prototype)
{
IsEscaped = prototype.IsEscaped;
}
public override void Push(char ch)
{
base.Push(ch);
if (ch == Engine.NewLineChar)
{
ExitState();
}
else if (!IsEscaped && ch == '"')
{
ExitState();
}
IsEscaped = ch == '\\' && !IsEscaped;
}
public override void InitializeState()
{
ThisLineIndent = Parent.ThisLineIndent.Clone();
NextLineIndent = Parent.NextLineIndent.Clone();
}
public override IndentState Clone()
{
return new StringLiteralState(this);
}
}
#endregion
#region Verbatim string state
/// <summary>
/// Verbatim string state.
/// </summary>
public class VerbatimStringState : IndentState
{
/// <summary>
/// True if there is an odd number of '"' in a row.
/// </summary>
public bool IsEscaped;
public VerbatimStringState(IndentEngine engine, IndentState parent = null)
: base(engine, parent)
{ }
public VerbatimStringState(VerbatimStringState prototype)
: base(prototype)
{
IsEscaped = prototype.IsEscaped;
}
public override void Push(char ch)
{
base.Push(ch);
if (IsEscaped && ch != '"')
{
ExitState();
// the char has been pushed to the wrong state, push it back
Engine.CurrentState.Push(ch);
}
IsEscaped = ch == '"' && !IsEscaped;
}
public override void InitializeState()
{
ThisLineIndent = Parent.ThisLineIndent.Clone();
NextLineIndent = new Indent(Engine.TextEditorOptions);
}
public override IndentState Clone()
{
return new VerbatimStringState(this);
}
}
#endregion
#region Character state
/// <summary>
/// Character state.
/// </summary>
public class CharacterState : IndentState
{
/// <summary>
/// True if the next char is escaped with '\'.
/// </summary>
public bool IsEscaped;
public CharacterState(IndentEngine engine, IndentState parent = null)
: base(engine, parent)
{ }
public CharacterState(CharacterState prototype)
: base(prototype)
{
IsEscaped = prototype.IsEscaped;
}
public override void Push(char ch)
{
base.Push(ch);
if (ch == Engine.NewLineChar)
{
ExitState();
}
else if (!IsEscaped && ch == '\'')
{
ExitState();
}
IsEscaped = ch == '\\' && !IsEscaped;
}
public override void InitializeState()
{
ThisLineIndent = Parent.ThisLineIndent.Clone();
NextLineIndent = Parent.NextLineIndent.Clone();
}
public override IndentState Clone()
{
return new CharacterState(this);
}
}
#endregion
}
| 412 | 0.86321 | 1 | 0.86321 | game-dev | MEDIA | 0.470319 | game-dev | 0.501054 | 1 | 0.501054 |
Nextpeer/Nextpeer-UFORUN | 2,629 | cocos2d-x-2.2/external/emscripten/tests/bullet/src/BulletDynamics/ConstraintSolver/btUniversalConstraint.h | /*
Bullet Continuous Collision Detection and Physics Library, http://bulletphysics.org
Copyright (C) 2006, 2007 Sony Computer Entertainment Inc.
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef BT_UNIVERSAL_CONSTRAINT_H
#define BT_UNIVERSAL_CONSTRAINT_H
#include "LinearMath/btVector3.h"
#include "btTypedConstraint.h"
#include "btGeneric6DofConstraint.h"
/// Constraint similar to ODE Universal Joint
/// has 2 rotatioonal degrees of freedom, similar to Euler rotations around Z (axis 1)
/// and Y (axis 2)
/// Description from ODE manual :
/// "Given axis 1 on body 1, and axis 2 on body 2 that is perpendicular to axis 1, it keeps them perpendicular.
/// In other words, rotation of the two bodies about the direction perpendicular to the two axes will be equal."
class btUniversalConstraint : public btGeneric6DofConstraint
{
protected:
btVector3 m_anchor;
btVector3 m_axis1;
btVector3 m_axis2;
public:
// constructor
// anchor, axis1 and axis2 are in world coordinate system
// axis1 must be orthogonal to axis2
btUniversalConstraint(btRigidBody& rbA, btRigidBody& rbB, btVector3& anchor, btVector3& axis1, btVector3& axis2);
// access
const btVector3& getAnchor() { return m_calculatedTransformA.getOrigin(); }
const btVector3& getAnchor2() { return m_calculatedTransformB.getOrigin(); }
const btVector3& getAxis1() { return m_axis1; }
const btVector3& getAxis2() { return m_axis2; }
btScalar getAngle1() { return getAngle(2); }
btScalar getAngle2() { return getAngle(1); }
// limits
void setUpperLimit(btScalar ang1max, btScalar ang2max) { setAngularUpperLimit(btVector3(0.f, ang1max, ang2max)); }
void setLowerLimit(btScalar ang1min, btScalar ang2min) { setAngularLowerLimit(btVector3(0.f, ang1min, ang2min)); }
void setAxis( const btVector3& axis1, const btVector3& axis2);
};
#endif // BT_UNIVERSAL_CONSTRAINT_H
| 412 | 0.823163 | 1 | 0.823163 | game-dev | MEDIA | 0.991735 | game-dev | 0.960166 | 1 | 0.960166 |
ProjectIgnis/CardScripts | 1,896 | official/c28297833.lua | --ネクロフェイス
--Necroface
local s,id=GetID()
function s.initial_effect(c)
--atkup
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(id,0))
e1:SetCategory(CATEGORY_TODECK+CATEGORY_ATKCHANGE)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e1:SetCode(EVENT_SUMMON_SUCCESS)
e1:SetTarget(s.tdtg)
e1:SetOperation(s.tdop)
c:RegisterEffect(e1)
--remove
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(id,1))
e2:SetCategory(CATEGORY_REMOVE)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e2:SetCode(EVENT_REMOVE)
e2:SetTarget(s.rmtg)
e2:SetOperation(s.rmop)
c:RegisterEffect(e2)
end
function s.tdtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_TODECK,nil,1,PLAYER_ALL,LOCATION_REMOVED)
end
function s.tdop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local g=Duel.GetFieldGroup(tp,LOCATION_REMOVED,LOCATION_REMOVED)
Duel.SendtoDeck(g,nil,SEQ_DECKSHUFFLE,REASON_EFFECT)
local ct=g:FilterCount(Card.IsLocation,nil,LOCATION_DECK)
if c:IsFaceup() and c:IsRelateToEffect(e) then
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetReset(RESET_EVENT|RESETS_STANDARD_DISABLE)
e1:SetValue(ct*100)
c:RegisterEffect(e1)
end
end
function s.rmtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_REMOVE,nil,5,PLAYER_ALL,LOCATION_DECK)
end
function s.rmop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local g1=Duel.GetDecktopGroup(tp,5)
local g2=Duel.GetDecktopGroup(1-tp,5)
g1:Merge(g2)
Duel.DisableShuffleCheck()
Duel.Remove(g1,POS_FACEUP,REASON_EFFECT)
if c:IsFaceup() and c:IsRelateToEffect(e) then
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetReset(RESETS_STANDARD_PHASE_END)
e1:SetValue(500)
c:RegisterEffect(e1)
end
end | 412 | 0.900098 | 1 | 0.900098 | game-dev | MEDIA | 0.9731 | game-dev | 0.9347 | 1 | 0.9347 |
pathea-games/planetexplorers | 1,312 | Assets/Scripts/ZhouXun/Camera Controller/Scripts/Modifiers/Effects/CameraSpringEffect.cs | using UnityEngine;
using System.Collections;
public class CameraSpringEffect : CamEffect
{
public Transform m_Character;
public Transform m_Bone;
private Vector3 m_LastCharPos;
private bool m_Ignore = true;
private Vector3 s = Vector3.zero;
private Vector3 v = Vector3.zero;
private Vector3 a = Vector3.zero;
private Vector3 f = Vector3.zero;
private Vector3 s0 = Vector3.zero;
public float k = 1;
public float cd = 2;
public float amp = 7;
public float sc = 4;
public float rot = 0.8f;
public override void Do ()
{
if (m_Bone == null)
return;
if (m_Character == null)
return;
Vector3 CharPos = m_Bone.position;
float dist = (m_TargetCam.transform.position - CharPos).magnitude;
if (!m_Ignore)
{
float dt = Mathf.Clamp(Time.deltaTime, 0.001f, 0.025f) * sc;
s0 = Vector3.Lerp(s0, CharPos - m_LastCharPos, 0.3f);
s0 = Vector3.ClampMagnitude(s0, 1f);
a = (s0 - s) * k;
f = -v * cd;
v = (a+f) * dt + v;
s = v * dt + s;
s = Vector3.ClampMagnitude(s, dist / amp);
Vector3 bias = -s * amp;
bias = Vector3.ClampMagnitude(bias, dist);
m_TargetCam.transform.position += bias;
//Vector3 tp = m_Character.position + bias * Mathf.Clamp01(1f-rot);
//m_TargetCam.transform.LookAt(tp);
}
m_LastCharPos = m_Bone.position;
m_Ignore = false;
}
}
| 412 | 0.662663 | 1 | 0.662663 | game-dev | MEDIA | 0.682787 | game-dev,graphics-rendering | 0.929373 | 1 | 0.929373 |
SonicEraZoR/Portal-Base | 3,147 | sp/src/game/shared/ehandle.h | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef EHANDLE_H
#define EHANDLE_H
#ifdef _WIN32
#pragma once
#endif
#if defined( _DEBUG ) && defined( GAME_DLL )
#include "tier0/dbg.h"
#include "cbase.h"
#endif
#include "const.h"
#include "basehandle.h"
#include "entitylist_base.h"
class IHandleEntity;
// -------------------------------------------------------------------------------------------------- //
// Game-code CBaseHandle implementation.
// -------------------------------------------------------------------------------------------------- //
inline IHandleEntity* CBaseHandle::Get() const
{
extern CBaseEntityList *g_pEntityList;
return g_pEntityList->LookupEntity( *this );
}
// -------------------------------------------------------------------------------------------------- //
// CHandle.
// -------------------------------------------------------------------------------------------------- //
template< class T >
class CHandle : public CBaseHandle
{
public:
CHandle();
CHandle( int iEntry, int iSerialNumber );
CHandle( const CBaseHandle &handle );
CHandle( T *pVal );
// The index should have come from a call to ToInt(). If it hasn't, you're in trouble.
static CHandle<T> FromIndex( int index );
T* Get() const;
void Set( const T* pVal );
operator T*();
operator T*() const;
bool operator !() const;
bool operator==( T *val ) const;
bool operator!=( T *val ) const;
const CBaseHandle& operator=( const T *val );
T* operator->() const;
};
// ----------------------------------------------------------------------- //
// Inlines.
// ----------------------------------------------------------------------- //
template<class T>
CHandle<T>::CHandle()
{
}
template<class T>
CHandle<T>::CHandle( int iEntry, int iSerialNumber )
{
Init( iEntry, iSerialNumber );
}
template<class T>
CHandle<T>::CHandle( const CBaseHandle &handle )
: CBaseHandle( handle )
{
}
template<class T>
CHandle<T>::CHandle( T *pObj )
{
Term();
Set( pObj );
}
template<class T>
inline CHandle<T> CHandle<T>::FromIndex( int index )
{
CHandle<T> ret;
ret.m_Index = index;
return ret;
}
template<class T>
inline T* CHandle<T>::Get() const
{
return (T*)CBaseHandle::Get();
}
template<class T>
inline CHandle<T>::operator T *()
{
return Get( );
}
template<class T>
inline CHandle<T>::operator T *() const
{
return Get( );
}
template<class T>
inline bool CHandle<T>::operator !() const
{
return !Get();
}
template<class T>
inline bool CHandle<T>::operator==( T *val ) const
{
return Get() == val;
}
template<class T>
inline bool CHandle<T>::operator!=( T *val ) const
{
return Get() != val;
}
template<class T>
void CHandle<T>::Set( const T* pVal )
{
CBaseHandle::Set( reinterpret_cast<const IHandleEntity*>(pVal) );
}
template<class T>
inline const CBaseHandle& CHandle<T>::operator=( const T *val )
{
Set( val );
return *this;
}
template<class T>
T* CHandle<T>::operator -> () const
{
return Get();
}
#endif // EHANDLE_H
| 412 | 0.97992 | 1 | 0.97992 | game-dev | MEDIA | 0.467608 | game-dev | 0.89645 | 1 | 0.89645 |
OpenMW/openmw | 9,753 | apps/openmw/mwgui/containeritemmodel.cpp | #include "containeritemmodel.hpp"
#include <algorithm>
#include "../mwmechanics/actorutil.hpp"
#include "../mwmechanics/creaturestats.hpp"
#include "../mwworld/class.hpp"
#include "../mwworld/containerstore.hpp"
#include "../mwworld/manualref.hpp"
#include "../mwbase/environment.hpp"
#include "../mwbase/mechanicsmanager.hpp"
#include "../mwbase/windowmanager.hpp"
#include "../mwbase/world.hpp"
namespace
{
bool stacks(const MWWorld::Ptr& left, const MWWorld::Ptr& right)
{
if (left == right)
return true;
// If one of the items is in an inventory and currently equipped, we need to check stacking both ways to be sure
if (left.getContainerStore() && right.getContainerStore())
return left.getContainerStore()->stacks(left, right) && right.getContainerStore()->stacks(left, right);
if (left.getContainerStore())
return left.getContainerStore()->stacks(left, right);
if (right.getContainerStore())
return right.getContainerStore()->stacks(left, right);
MWWorld::ContainerStore store;
return store.stacks(left, right);
}
}
namespace MWGui
{
ContainerItemModel::ContainerItemModel(
const std::vector<MWWorld::Ptr>& itemSources, const std::vector<MWWorld::Ptr>& worldItems)
: mWorldItems(worldItems)
, mTrading(true)
{
assert(!itemSources.empty());
// Tie resolution lifetimes to the ItemModel
mItemSources.reserve(itemSources.size());
for (const MWWorld::Ptr& source : itemSources)
{
MWWorld::ContainerStore& store = source.getClass().getContainerStore(source);
mItemSources.emplace_back(source, store.resolveTemporarily());
}
}
ContainerItemModel::ContainerItemModel(const MWWorld::Ptr& source)
: mTrading(false)
{
MWWorld::ContainerStore& store = source.getClass().getContainerStore(source);
mItemSources.emplace_back(source, store.resolveTemporarily());
}
bool ContainerItemModel::allowedToUseItems() const
{
if (mItemSources.empty())
return true;
MWWorld::Ptr ptr = MWMechanics::getPlayer();
MWWorld::Ptr victim;
// Check if the player is allowed to use items from opened container
MWBase::MechanicsManager* mm = MWBase::Environment::get().getMechanicsManager();
return mm->isAllowedToUse(ptr, mItemSources[0].first, victim);
}
ItemStack ContainerItemModel::getItem(ModelIndex index)
{
if (index < 0)
throw std::runtime_error("Invalid index supplied");
if (mItems.size() <= static_cast<size_t>(index))
throw std::runtime_error("Item index out of range");
return mItems[index];
}
size_t ContainerItemModel::getItemCount()
{
return mItems.size();
}
ItemModel::ModelIndex ContainerItemModel::getIndex(const ItemStack& item)
{
size_t i = 0;
for (ItemStack& itemStack : mItems)
{
if (itemStack == item)
return i;
++i;
}
return -1;
}
MWWorld::Ptr ContainerItemModel::addItem(const ItemStack& item, size_t count, bool allowAutoEquip)
{
auto& source = mItemSources[0];
MWWorld::ContainerStore& store = source.first.getClass().getContainerStore(source.first);
if (item.mBase.getContainerStore() == &store)
throw std::runtime_error("Item to add needs to be from a different container!");
return *store.add(item.mBase, count, allowAutoEquip);
}
MWWorld::Ptr ContainerItemModel::copyItem(const ItemStack& item, size_t count, bool allowAutoEquip)
{
auto& source = mItemSources[0];
MWWorld::ContainerStore& store = source.first.getClass().getContainerStore(source.first);
if (item.mBase.getContainerStore() == &store)
throw std::runtime_error("Item to copy needs to be from a different container!");
MWWorld::ManualRef newRef(*MWBase::Environment::get().getESMStore(), item.mBase, count);
return *store.add(newRef.getPtr(), count, allowAutoEquip);
}
void ContainerItemModel::removeItem(const ItemStack& item, size_t count)
{
int toRemove = count;
for (auto& source : mItemSources)
{
MWWorld::ContainerStore& store = source.first.getClass().getContainerStore(source.first);
for (MWWorld::ContainerStoreIterator it = store.begin(); it != store.end(); ++it)
{
if (stacks(*it, item.mBase))
{
int quantity = it->mRef->mRef.getCount(false);
// If this is a restocking quantity, just don't remove it
if (quantity < 0 && mTrading)
toRemove += quantity;
else
toRemove -= store.remove(*it, toRemove);
if (toRemove <= 0)
return;
}
}
}
for (MWWorld::Ptr& source : mWorldItems)
{
if (stacks(source, item.mBase))
{
int refCount = source.getCellRef().getCount();
if (refCount - toRemove <= 0)
MWBase::Environment::get().getWorld()->deleteObject(source);
else
source.getCellRef().setCount(std::max(0, refCount - toRemove));
toRemove -= refCount;
if (toRemove <= 0)
return;
}
}
throw std::runtime_error("Not enough items to remove could be found");
}
void ContainerItemModel::update()
{
mItems.clear();
for (auto& source : mItemSources)
{
MWWorld::ContainerStore& store = source.first.getClass().getContainerStore(source.first);
for (MWWorld::ContainerStoreIterator it = store.begin(); it != store.end(); ++it)
{
if (!(*it).getClass().showsInInventory(*it))
continue;
bool found = false;
for (ItemStack& itemStack : mItems)
{
if (stacks(*it, itemStack.mBase))
{
// we already have an item stack of this kind, add to it
itemStack.mCount += it->getCellRef().getCount();
found = true;
break;
}
}
if (!found)
{
// no stack yet, create one
ItemStack newItem(*it, this, it->getCellRef().getCount());
mItems.push_back(newItem);
}
}
}
for (MWWorld::Ptr& source : mWorldItems)
{
bool found = false;
for (ItemStack& itemStack : mItems)
{
if (stacks(source, itemStack.mBase))
{
// we already have an item stack of this kind, add to it
itemStack.mCount += source.getCellRef().getCount();
found = true;
break;
}
}
if (!found)
{
// no stack yet, create one
ItemStack newItem(source, this, source.getCellRef().getCount());
mItems.push_back(newItem);
}
}
}
bool ContainerItemModel::onDropItem(const MWWorld::Ptr& item, int count)
{
if (mItemSources.empty())
return false;
MWWorld::Ptr target = mItemSources[0].first;
if (target.getType() != ESM::Container::sRecordId)
return true;
// Check container organic flag
MWWorld::LiveCellRef<ESM::Container>* ref = target.get<ESM::Container>();
if (ref->mBase->mFlags & ESM::Container::Organic)
{
MWBase::Environment::get().getWindowManager()->messageBox("#{sContentsMessage2}");
return false;
}
// Check for container without capacity
float capacity = target.getClass().getCapacity(target);
if (capacity <= 0.0f)
{
MWBase::Environment::get().getWindowManager()->messageBox("#{sContentsMessage3}");
return false;
}
// Check the container capacity plus one increment so the expected total weight can
// fit in the container with floating-point imprecision
float newEncumbrance = target.getClass().getEncumbrance(target) + (item.getClass().getWeight(item) * count);
if (std::nextafterf(capacity, std::numeric_limits<float>::max()) < newEncumbrance)
{
MWBase::Environment::get().getWindowManager()->messageBox("#{sContentsMessage3}");
return false;
}
return true;
}
bool ContainerItemModel::onTakeItem(const MWWorld::Ptr& item, int count)
{
if (mItemSources.empty())
return false;
MWWorld::Ptr target = mItemSources[0].first;
// Looting a dead corpse is considered OK
if (target.getClass().isActor() && target.getClass().getCreatureStats(target).isDead())
return true;
MWWorld::Ptr player = MWMechanics::getPlayer();
MWBase::Environment::get().getMechanicsManager()->itemTaken(player, item, target, count);
return true;
}
bool ContainerItemModel::usesContainer(const MWWorld::Ptr& container)
{
for (const auto& source : mItemSources)
{
if (source.first == container)
return true;
}
return false;
}
}
| 412 | 0.96977 | 1 | 0.96977 | game-dev | MEDIA | 0.958165 | game-dev | 0.986675 | 1 | 0.986675 |
keijiro/KvantSprayMV | 4,482 | Assets/Kino/Vision/Editor/VisionEditor.cs | //
// Kino/Vision - Frame visualization utility
//
// Copyright (C) 2016 Keijiro Takahashi
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using UnityEngine;
using UnityEditor;
namespace Kino
{
[CustomEditor(typeof(Vision))]
public class VisionEditor : Editor
{
// Common
SerializedProperty _source;
SerializedProperty _blendRatio;
SerializedProperty _preferDepthNormals;
static GUIContent _textUseDepthNormals = new GUIContent("Use Depth Normals");
// Depth
SerializedProperty _depthRepeat;
static GUIContent _textRepeat = new GUIContent("Repeat");
// Normals
SerializedProperty _validateNormals;
static GUIContent _textCheckValidity = new GUIContent("Check Validity");
// Motion vectors
SerializedProperty _motionOverlayAmplitude;
SerializedProperty _motionVectorsAmplitude;
SerializedProperty _motionVectorsResolution;
static GUIContent _textOverlayAmplitude = new GUIContent("Overlay Amplitude");
static GUIContent _textArrowsAmplitude = new GUIContent("Arrows Amplitude");
static GUIContent _textArrowsResolution = new GUIContent("Arrows Resolution");
void OnEnable()
{
// Common
_source = serializedObject.FindProperty("_source");
_blendRatio = serializedObject.FindProperty("_blendRatio");
_preferDepthNormals = serializedObject.FindProperty("_preferDepthNormals");
// Depth
_depthRepeat = serializedObject.FindProperty("_depthRepeat");
// Normals
_validateNormals = serializedObject.FindProperty("_validateNormals");
// Motion vectors
_motionOverlayAmplitude = serializedObject.FindProperty("_motionOverlayAmplitude");
_motionVectorsAmplitude = serializedObject.FindProperty("_motionVectorsAmplitude");
_motionVectorsResolution = serializedObject.FindProperty("_motionVectorsResolution");
}
public override void OnInspectorGUI()
{
serializedObject.Update();
EditorGUILayout.PropertyField(_source);
var source = (Vision.Source)_source.enumValueIndex;
if (source == Vision.Source.Depth)
{
// Depth
EditorGUILayout.PropertyField(_depthRepeat, _textRepeat);
EditorGUILayout.PropertyField(_preferDepthNormals, _textUseDepthNormals);
}
if (source == Vision.Source.Normals)
{
// Normals
EditorGUILayout.PropertyField(_preferDepthNormals, _textUseDepthNormals);
EditorGUI.BeginDisabledGroup(_preferDepthNormals.boolValue);
EditorGUILayout.PropertyField(_validateNormals, _textCheckValidity);
EditorGUI.EndDisabledGroup();
}
if (source == Vision.Source.MotionVectors)
{
// Motion vectors
EditorGUILayout.PropertyField(_motionOverlayAmplitude, _textOverlayAmplitude);
EditorGUILayout.PropertyField(_motionVectorsAmplitude, _textArrowsAmplitude);
EditorGUILayout.PropertyField(_motionVectorsResolution, _textArrowsResolution);
}
EditorGUILayout.PropertyField(_blendRatio);
serializedObject.ApplyModifiedProperties();
}
}
}
| 412 | 0.774275 | 1 | 0.774275 | game-dev | MEDIA | 0.751693 | game-dev,graphics-rendering | 0.671494 | 1 | 0.671494 |
danenders/pokeclassic | 113,267 | src/data/battle_frontier/battle_frontier_mons.h | const struct FacilityMon gBattleFrontierMons[NUM_FRONTIER_MONS] =
{
[FRONTIER_MON_CATERPIE] = {
.species = SPECIES_CATERPIE,
.moves = {MOVE_TACKLE, MOVE_STRING_SHOT, MOVE_NONE, MOVE_NONE},
.itemTableId = BATTLE_FRONTIER_ITEM_FOCUS_BAND,
.evSpread = F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_QUIRKY
},
[FRONTIER_MON_WEEDLE] = {
.species = SPECIES_WEEDLE,
.moves = {MOVE_POISON_STING, MOVE_STRING_SHOT, MOVE_NONE, MOVE_NONE},
.itemTableId = BATTLE_FRONTIER_ITEM_FOCUS_BAND,
.evSpread = F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_QUIRKY
},
[FRONTIER_MON_MAGIKARP] = {
.species = SPECIES_MAGIKARP,
.moves = {MOVE_FLAIL, MOVE_NONE, MOVE_NONE, MOVE_NONE},
.itemTableId = BATTLE_FRONTIER_ITEM_FOCUS_BAND,
.evSpread = F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_HARDY
},
[FRONTIER_MON_METAPOD] = {
.species = SPECIES_METAPOD,
.moves = {MOVE_HARDEN, MOVE_NONE, MOVE_NONE, MOVE_NONE},
.itemTableId = BATTLE_FRONTIER_ITEM_LAX_INCENSE,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_BASHFUL
},
[FRONTIER_MON_KAKUNA] = {
.species = SPECIES_KAKUNA,
.moves = {MOVE_HARDEN, MOVE_NONE, MOVE_NONE, MOVE_NONE},
.itemTableId = BATTLE_FRONTIER_ITEM_LAX_INCENSE,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_BASHFUL
},
[FRONTIER_MON_ZUBAT] = {
.species = SPECIES_ZUBAT,
.moves = {MOVE_POISON_FANG, MOVE_WHIRLWIND, MOVE_CONFUSE_RAY, MOVE_AERIAL_ACE},
.itemTableId = BATTLE_FRONTIER_ITEM_CHERI_BERRY,
.evSpread = F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_SASSY
},
[FRONTIER_MON_PIDGEY] = {
.species = SPECIES_PIDGEY,
.moves = {MOVE_GUST, MOVE_SAND_ATTACK, MOVE_WHIRLWIND, MOVE_QUICK_ATTACK},
.itemTableId = BATTLE_FRONTIER_ITEM_SHARP_BEAK,
.evSpread = F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_LONELY
},
[FRONTIER_MON_RATTATA] = {
.species = SPECIES_RATTATA,
.moves = {MOVE_HYPER_FANG, MOVE_PURSUIT, MOVE_QUICK_ATTACK, MOVE_SWAGGER},
.itemTableId = BATTLE_FRONTIER_ITEM_KINGS_ROCK,
.evSpread = F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_DOCILE
},
[FRONTIER_MON_SPEAROW] = {
.species = SPECIES_SPEAROW,
.moves = {MOVE_FURY_ATTACK, MOVE_PURSUIT, MOVE_MIRROR_MOVE, MOVE_PROTECT},
.itemTableId = BATTLE_FRONTIER_ITEM_LIECHI_BERRY,
.evSpread = F_EV_SPREAD_SPEED | F_EV_SPREAD_HP,
.nature = NATURE_DOCILE
},
[FRONTIER_MON_DIGLETT] = {
.species = SPECIES_DIGLETT,
.moves = {MOVE_MAGNITUDE, MOVE_SLASH, MOVE_ROCK_TOMB, MOVE_SAND_ATTACK},
.itemTableId = BATTLE_FRONTIER_ITEM_KINGS_ROCK,
.evSpread = F_EV_SPREAD_SPEED | F_EV_SPREAD_ATTACK,
.nature = NATURE_NAIVE
},
[FRONTIER_MON_JIGGLYPUFF] = {
.species = SPECIES_JIGGLYPUFF,
.moves = {MOVE_SING, MOVE_WISH, MOVE_MIMIC, MOVE_DOUBLE_SLAP},
.itemTableId = BATTLE_FRONTIER_ITEM_LAX_INCENSE,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_RELAXED
},
[FRONTIER_MON_NIDORAN_M] = {
.species = SPECIES_NIDORAN_M,
.moves = {MOVE_DOUBLE_KICK, MOVE_POISON_STING, MOVE_DISABLE, MOVE_HELPING_HAND},
.itemTableId = BATTLE_FRONTIER_ITEM_SITRUS_BERRY,
.evSpread = F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_QUIRKY
},
[FRONTIER_MON_NIDORAN_F] = {
.species = SPECIES_NIDORAN_F,
.moves = {MOVE_CRUNCH, MOVE_DOUBLE_KICK, MOVE_FLATTER, MOVE_HELPING_HAND},
.itemTableId = BATTLE_FRONTIER_ITEM_SITRUS_BERRY,
.evSpread = F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_QUIRKY
},
[FRONTIER_MON_PARAS] = {
.species = SPECIES_PARAS,
.moves = {MOVE_SPORE, MOVE_LEECH_LIFE, MOVE_SLASH, MOVE_LIGHT_SCREEN},
.itemTableId = BATTLE_FRONTIER_ITEM_SITRUS_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_RELAXED
},
[FRONTIER_MON_EKANS] = {
.species = SPECIES_EKANS,
.moves = {MOVE_ACID, MOVE_DIG, MOVE_SCREECH, MOVE_TORMENT},
.itemTableId = BATTLE_FRONTIER_ITEM_POISON_BARB,
.evSpread = F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_DOCILE
},
[FRONTIER_MON_DITTO] = {
.species = SPECIES_DITTO,
.moves = {MOVE_TRANSFORM, MOVE_NONE, MOVE_NONE, MOVE_NONE},
.itemTableId = BATTLE_FRONTIER_ITEM_METAL_POWDER,
.evSpread = F_EV_SPREAD_SPEED | F_EV_SPREAD_HP,
.nature = NATURE_HARDY
},
[FRONTIER_MON_MEOWTH] = {
.species = SPECIES_MEOWTH,
.moves = {MOVE_SLASH, MOVE_BITE, MOVE_SCREECH, MOVE_FAKE_OUT},
.itemTableId = BATTLE_FRONTIER_ITEM_PERSIM_BERRY,
.evSpread = F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_QUIRKY
},
[FRONTIER_MON_HORSEA] = {
.species = SPECIES_HORSEA,
.moves = {MOVE_WATER_GUN, MOVE_AGILITY, MOVE_ICY_WIND, MOVE_TWISTER},
.itemTableId = BATTLE_FRONTIER_ITEM_PETAYA_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_RELAXED
},
[FRONTIER_MON_VULPIX] = {
.species = SPECIES_VULPIX,
.moves = {MOVE_WILL_O_WISP, MOVE_CONFUSE_RAY, MOVE_FIRE_SPIN, MOVE_QUICK_ATTACK},
.itemTableId = BATTLE_FRONTIER_ITEM_RAWST_BERRY,
.evSpread = F_EV_SPREAD_SPEED | F_EV_SPREAD_HP,
.nature = NATURE_DOCILE
},
[FRONTIER_MON_PIKACHU] = {
.species = SPECIES_PIKACHU,
.moves = {MOVE_THUNDER_PUNCH, MOVE_THUNDER_WAVE, MOVE_DOUBLE_TEAM, MOVE_QUICK_ATTACK},
.itemTableId = BATTLE_FRONTIER_ITEM_LIGHT_BALL,
.evSpread = F_EV_SPREAD_SPEED | F_EV_SPREAD_HP,
.nature = NATURE_DOCILE
},
[FRONTIER_MON_SANDSHREW] = {
.species = SPECIES_SANDSHREW,
.moves = {MOVE_DIG, MOVE_ROCK_TOMB, MOVE_SANDSTORM, MOVE_SAND_ATTACK},
.itemTableId = BATTLE_FRONTIER_ITEM_SOFT_SAND,
.evSpread = F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_DOCILE
},
[FRONTIER_MON_POLIWAG] = {
.species = SPECIES_POLIWAG,
.moves = {MOVE_HYPNOSIS, MOVE_ICY_WIND, MOVE_WATER_GUN, MOVE_RAIN_DANCE},
.itemTableId = BATTLE_FRONTIER_ITEM_MYSTIC_WATER,
.evSpread = F_EV_SPREAD_SPEED | F_EV_SPREAD_HP,
.nature = NATURE_RELAXED
},
[FRONTIER_MON_BELLSPROUT] = {
.species = SPECIES_BELLSPROUT,
.moves = {MOVE_RAZOR_LEAF, MOVE_ACID, MOVE_STUN_SPORE, MOVE_WRAP},
.itemTableId = BATTLE_FRONTIER_ITEM_SITRUS_BERRY,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_LAX
},
[FRONTIER_MON_GEODUDE] = {
.species = SPECIES_GEODUDE,
.moves = {MOVE_MAGNITUDE, MOVE_ROCK_BLAST, MOVE_STRENGTH, MOVE_PROTECT},
.itemTableId = BATTLE_FRONTIER_ITEM_FOCUS_BAND,
.evSpread = F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_BRAVE
},
[FRONTIER_MON_DRATINI] = {
.species = SPECIES_DRATINI,
.moves = {MOVE_OUTRAGE, MOVE_THUNDER_WAVE, MOVE_SUPERSONIC, MOVE_WATER_PULSE},
.itemTableId = BATTLE_FRONTIER_ITEM_PERSIM_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_DOCILE
},
[FRONTIER_MON_VENONAT] = {
.species = SPECIES_VENONAT,
.moves = {MOVE_PSYBEAM, MOVE_SUPERSONIC, MOVE_STUN_SPORE, MOVE_SKILL_SWAP},
.itemTableId = BATTLE_FRONTIER_ITEM_SITRUS_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_RELAXED
},
[FRONTIER_MON_MANKEY] = {
.species = SPECIES_MANKEY,
.moves = {MOVE_KARATE_CHOP, MOVE_LOW_KICK, MOVE_SCREECH, MOVE_SWAGGER},
.itemTableId = BATTLE_FRONTIER_ITEM_BLACK_BELT,
.evSpread = F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_NAUGHTY
},
[FRONTIER_MON_MACHOP] = {
.species = SPECIES_MACHOP,
.moves = {MOVE_SEISMIC_TOSS, MOVE_REVENGE, MOVE_ROCK_TOMB, MOVE_SCARY_FACE},
.itemTableId = BATTLE_FRONTIER_ITEM_SCOPE_LENS,
.evSpread = F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_SHELLDER] = {
.species = SPECIES_SHELLDER,
.moves = {MOVE_ICICLE_SPEAR, MOVE_SUPERSONIC, MOVE_CLAMP, MOVE_WITHDRAW},
.itemTableId = BATTLE_FRONTIER_ITEM_CHERI_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_RELAXED
},
[FRONTIER_MON_CHARMANDER] = {
.species = SPECIES_CHARMANDER,
.moves = {MOVE_FIRE_SPIN, MOVE_METAL_CLAW, MOVE_SMOKESCREEN, MOVE_SCARY_FACE},
.itemTableId = BATTLE_FRONTIER_ITEM_FOCUS_BAND,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_DOCILE
},
[FRONTIER_MON_ABRA] = {
.species = SPECIES_ABRA,
.moves = {MOVE_MIMIC, MOVE_METRONOME, MOVE_FLASH, MOVE_SEISMIC_TOSS},
.itemTableId = BATTLE_FRONTIER_ITEM_TWISTED_SPOON,
.evSpread = F_EV_SPREAD_SPEED | F_EV_SPREAD_HP,
.nature = NATURE_LONELY
},
[FRONTIER_MON_DODUO] = {
.species = SPECIES_DODUO,
.moves = {MOVE_FURY_ATTACK, MOVE_UPROAR, MOVE_MUD_SLAP, MOVE_FEINT_ATTACK},
.itemTableId = BATTLE_FRONTIER_ITEM_LIECHI_BERRY,
.evSpread = F_EV_SPREAD_SPEED | F_EV_SPREAD_HP,
.nature = NATURE_LONELY
},
[FRONTIER_MON_GASTLY] = {
.species = SPECIES_GASTLY,
.moves = {MOVE_DREAM_EATER, MOVE_HYPNOSIS, MOVE_NIGHT_SHADE, MOVE_CONFUSE_RAY},
.itemTableId = BATTLE_FRONTIER_ITEM_LAX_INCENSE,
.evSpread = F_EV_SPREAD_SPEED | F_EV_SPREAD_HP,
.nature = NATURE_LONELY
},
[FRONTIER_MON_SQUIRTLE] = {
.species = SPECIES_SQUIRTLE,
.moves = {MOVE_WATER_PULSE, MOVE_BITE, MOVE_WITHDRAW, MOVE_PROTECT},
.itemTableId = BATTLE_FRONTIER_ITEM_SITRUS_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_DOCILE
},
[FRONTIER_MON_SLOWPOKE] = {
.species = SPECIES_SLOWPOKE,
.moves = {MOVE_CONFUSION, MOVE_DISABLE, MOVE_WATER_PULSE, MOVE_YAWN},
.itemTableId = BATTLE_FRONTIER_ITEM_SITRUS_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_BRAVE
},
[FRONTIER_MON_BULBASAUR] = {
.species = SPECIES_BULBASAUR,
.moves = {MOVE_RAZOR_LEAF, MOVE_SWEET_SCENT, MOVE_SLEEP_POWDER, MOVE_LIGHT_SCREEN},
.itemTableId = BATTLE_FRONTIER_ITEM_BRIGHT_POWDER,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_RELAXED
},
[FRONTIER_MON_ODDISH] = {
.species = SPECIES_ODDISH,
.moves = {MOVE_ACID, MOVE_STUN_SPORE, MOVE_SWEET_SCENT, MOVE_MOONLIGHT},
.itemTableId = BATTLE_FRONTIER_ITEM_PECHA_BERRY,
.evSpread = F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_RELAXED
},
[FRONTIER_MON_PSYDUCK] = {
.species = SPECIES_PSYDUCK,
.moves = {MOVE_CONFUSION, MOVE_FURY_SWIPES, MOVE_AERIAL_ACE, MOVE_DISABLE},
.itemTableId = BATTLE_FRONTIER_ITEM_PERSIM_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_ATTACK,
.nature = NATURE_HASTY
},
[FRONTIER_MON_CUBONE] = {
.species = SPECIES_CUBONE,
.moves = {MOVE_BONE_CLUB, MOVE_HEADBUTT, MOVE_BRICK_BREAK, MOVE_AERIAL_ACE},
.itemTableId = BATTLE_FRONTIER_ITEM_SOFT_SAND,
.evSpread = F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_HARDY
},
[FRONTIER_MON_GOLDEEN] = {
.species = SPECIES_GOLDEEN,
.moves = {MOVE_WATERFALL, MOVE_FURY_ATTACK, MOVE_AGILITY, MOVE_PSYBEAM},
.itemTableId = BATTLE_FRONTIER_ITEM_PETAYA_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_DOCILE
},
[FRONTIER_MON_CLEFAIRY] = {
.species = SPECIES_CLEFAIRY,
.moves = {MOVE_FOLLOW_ME, MOVE_RETURN, MOVE_ENCORE, MOVE_SING},
.itemTableId = BATTLE_FRONTIER_ITEM_LAX_INCENSE,
.evSpread = F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_LONELY
},
[FRONTIER_MON_MAGNEMITE] = {
.species = SPECIES_MAGNEMITE,
.moves = {MOVE_SHOCK_WAVE, MOVE_SUPERSONIC, MOVE_METAL_SOUND, MOVE_REFLECT},
.itemTableId = BATTLE_FRONTIER_ITEM_RAWST_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_SPEED,
.nature = NATURE_GENTLE
},
[FRONTIER_MON_SEEL] = {
.species = SPECIES_SEEL,
.moves = {MOVE_AURORA_BEAM, MOVE_DIVE, MOVE_BODY_SLAM, MOVE_FAKE_OUT},
.itemTableId = BATTLE_FRONTIER_ITEM_ASPEAR_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_HARDY
},
[FRONTIER_MON_GRIMER] = {
.species = SPECIES_GRIMER,
.moves = {MOVE_SLUDGE, MOVE_ROCK_TOMB, MOVE_ACID_ARMOR, MOVE_MINIMIZE},
.itemTableId = BATTLE_FRONTIER_ITEM_PECHA_BERRY,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_QUIRKY
},
[FRONTIER_MON_KRABBY] = {
.species = SPECIES_KRABBY,
.moves = {MOVE_CRABHAMMER, MOVE_MUD_SHOT, MOVE_FLAIL, MOVE_KNOCK_OFF},
.itemTableId = BATTLE_FRONTIER_ITEM_FOCUS_BAND,
.evSpread = F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_HARDY
},
[FRONTIER_MON_EXEGGCUTE] = {
.species = SPECIES_EXEGGCUTE,
.moves = {MOVE_CONFUSION, MOVE_ANCIENT_POWER, MOVE_LEECH_SEED, MOVE_LIGHT_SCREEN},
.itemTableId = BATTLE_FRONTIER_ITEM_PERSIM_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_NAUGHTY
},
[FRONTIER_MON_EEVEE] = {
.species = SPECIES_EEVEE,
.moves = {MOVE_CHARM, MOVE_ATTRACT, MOVE_FLAIL, MOVE_ENDURE},
.itemTableId = BATTLE_FRONTIER_ITEM_SALAC_BERRY,
.evSpread = F_EV_SPREAD_SPEED | F_EV_SPREAD_HP,
.nature = NATURE_DOCILE
},
[FRONTIER_MON_DROWZEE] = {
.species = SPECIES_DROWZEE,
.moves = {MOVE_CONFUSION, MOVE_HEADBUTT, MOVE_DISABLE, MOVE_BARRIER},
.itemTableId = BATTLE_FRONTIER_ITEM_SITRUS_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_QUIRKY
},
[FRONTIER_MON_VOLTORB] = {
.species = SPECIES_VOLTORB,
.moves = {MOVE_SPARK, MOVE_SCREECH, MOVE_ROLLOUT, MOVE_LIGHT_SCREEN},
.itemTableId = BATTLE_FRONTIER_ITEM_LAX_INCENSE,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_DOCILE
},
[FRONTIER_MON_TENTACOOL] = {
.species = SPECIES_TENTACOOL,
.moves = {MOVE_BUBBLE_BEAM, MOVE_ACID, MOVE_BARRIER, MOVE_WRAP},
.itemTableId = BATTLE_FRONTIER_ITEM_PECHA_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_HARDY
},
[FRONTIER_MON_KOFFING] = {
.species = SPECIES_KOFFING,
.moves = {MOVE_SLUDGE, MOVE_SMOKESCREEN, MOVE_TORMENT, MOVE_HAZE},
.itemTableId = BATTLE_FRONTIER_ITEM_POISON_BARB,
.evSpread = F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_QUIRKY
},
[FRONTIER_MON_STARYU] = {
.species = SPECIES_STARYU,
.moves = {MOVE_BUBBLE_BEAM, MOVE_MINIMIZE, MOVE_SWIFT, MOVE_LIGHT_SCREEN},
.itemTableId = BATTLE_FRONTIER_ITEM_SHELL_BELL,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_QUIRKY
},
[FRONTIER_MON_RHYHORN] = {
.species = SPECIES_RHYHORN,
.moves = {MOVE_ROCK_BLAST, MOVE_DIG, MOVE_SCARY_FACE, MOVE_ROAR},
.itemTableId = BATTLE_FRONTIER_ITEM_FOCUS_BAND,
.evSpread = F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_HARDY
},
[FRONTIER_MON_PIDGEOTTO] = {
.species = SPECIES_PIDGEOTTO,
.moves = {MOVE_AERIAL_ACE, MOVE_QUICK_ATTACK, MOVE_FEATHER_DANCE, MOVE_SAND_ATTACK},
.itemTableId = BATTLE_FRONTIER_ITEM_WHITE_HERB,
.evSpread = F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_QUIRKY
},
[FRONTIER_MON_GROWLITHE] = {
.species = SPECIES_GROWLITHE,
.moves = {MOVE_FLAME_WHEEL, MOVE_BITE, MOVE_ROAR, MOVE_AGILITY},
.itemTableId = BATTLE_FRONTIER_ITEM_RAWST_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_DOCILE
},
[FRONTIER_MON_FARFETCHD] = {
.species = SPECIES_FARFETCHD,
.moves = {MOVE_SLASH, MOVE_KNOCK_OFF, MOVE_SWORDS_DANCE, MOVE_AGILITY},
.itemTableId = BATTLE_FRONTIER_ITEM_STICK,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_RELAXED
},
[FRONTIER_MON_OMANYTE] = {
.species = SPECIES_OMANYTE,
.moves = {MOVE_MUD_SHOT, MOVE_WATER_GUN, MOVE_ANCIENT_POWER, MOVE_TICKLE},
.itemTableId = BATTLE_FRONTIER_ITEM_SITRUS_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_QUIRKY
},
[FRONTIER_MON_KABUTO] = {
.species = SPECIES_KABUTO,
.moves = {MOVE_MEGA_DRAIN, MOVE_ANCIENT_POWER, MOVE_SAND_ATTACK, MOVE_PROTECT},
.itemTableId = BATTLE_FRONTIER_ITEM_SITRUS_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_ATTACK,
.nature = NATURE_HARDY
},
[FRONTIER_MON_NIDORINA] = {
.species = SPECIES_NIDORINA,
.moves = {MOVE_DOUBLE_KICK, MOVE_BITE, MOVE_AERIAL_ACE, MOVE_FLATTER},
.itemTableId = BATTLE_FRONTIER_ITEM_FOCUS_BAND,
.evSpread = F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_QUIRKY
},
[FRONTIER_MON_NIDORINO] = {
.species = SPECIES_NIDORINO,
.moves = {MOVE_DOUBLE_KICK, MOVE_WATER_PULSE, MOVE_MUD_SLAP, MOVE_FLATTER},
.itemTableId = BATTLE_FRONTIER_ITEM_FOCUS_BAND,
.evSpread = F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_QUIRKY
},
[FRONTIER_MON_BUTTERFREE] = {
.species = SPECIES_BUTTERFREE,
.moves = {MOVE_SILVER_WIND, MOVE_PSYBEAM, MOVE_TOXIC, MOVE_WHIRLWIND},
.itemTableId = BATTLE_FRONTIER_ITEM_PECHA_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_QUIRKY
},
[FRONTIER_MON_BEEDRILL] = {
.species = SPECIES_BEEDRILL,
.moves = {MOVE_TWINEEDLE, MOVE_PURSUIT, MOVE_ENDEAVOR, MOVE_AGILITY},
.itemTableId = BATTLE_FRONTIER_ITEM_SCOPE_LENS,
.evSpread = F_EV_SPREAD_SPEED | F_EV_SPREAD_ATTACK,
.nature = NATURE_NAUGHTY
},
[FRONTIER_MON_POLIWHIRL] = {
.species = SPECIES_POLIWHIRL,
.moves = {MOVE_WATER_PULSE, MOVE_DOUBLE_SLAP, MOVE_ICY_WIND, MOVE_RAIN_DANCE},
.itemTableId = BATTLE_FRONTIER_ITEM_PETAYA_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_QUIRKY
},
[FRONTIER_MON_ONIX] = {
.species = SPECIES_ONIX,
.moves = {MOVE_ROCK_SLIDE, MOVE_BIND, MOVE_DRAGON_BREATH, MOVE_SANDSTORM},
.itemTableId = BATTLE_FRONTIER_ITEM_SITRUS_BERRY,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_HARDY
},
[FRONTIER_MON_LICKITUNG_1] = {
.species = SPECIES_LICKITUNG,
.moves = {MOVE_SLAM, MOVE_BRICK_BREAK, MOVE_LICK, MOVE_MUD_SLAP},
.itemTableId = BATTLE_FRONTIER_ITEM_SITRUS_BERRY,
.evSpread = F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_QUIRKY
},
[FRONTIER_MON_WEEPINBELL_1] = {
.species = SPECIES_WEEPINBELL,
.moves = {MOVE_RAZOR_LEAF, MOVE_ACID, MOVE_WRAP, MOVE_SWEET_SCENT},
.itemTableId = BATTLE_FRONTIER_ITEM_SCOPE_LENS,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_QUIET
},
[FRONTIER_MON_GRAVELER_1] = {
.species = SPECIES_GRAVELER,
.moves = {MOVE_MAGNITUDE, MOVE_ROCK_THROW, MOVE_DEFENSE_CURL, MOVE_BRICK_BREAK},
.itemTableId = BATTLE_FRONTIER_ITEM_FOCUS_BAND,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_GLOOM_1] = {
.species = SPECIES_GLOOM,
.moves = {MOVE_PETAL_DANCE, MOVE_ACID, MOVE_STUN_SPORE, MOVE_MOONLIGHT},
.itemTableId = BATTLE_FRONTIER_ITEM_PERSIM_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_QUIRKY
},
[FRONTIER_MON_PORYGON_1] = {
.species = SPECIES_PORYGON,
.moves = {MOVE_PSYBEAM, MOVE_ICY_WIND, MOVE_RECYCLE, MOVE_AGILITY},
.itemTableId = BATTLE_FRONTIER_ITEM_SITRUS_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_RELAXED
},
[FRONTIER_MON_KADABRA_1] = {
.species = SPECIES_KADABRA,
.moves = {MOVE_CONFUSION, MOVE_ROLE_PLAY, MOVE_FUTURE_SIGHT, MOVE_DISABLE},
.itemTableId = BATTLE_FRONTIER_ITEM_TWISTED_SPOON,
.evSpread = F_EV_SPREAD_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_IMPISH
},
[FRONTIER_MON_IVYSAUR_1] = {
.species = SPECIES_IVYSAUR,
.moves = {MOVE_PETAL_DANCE, MOVE_GROWTH, MOVE_SWEET_SCENT, MOVE_FURY_CUTTER},
.itemTableId = BATTLE_FRONTIER_ITEM_PERSIM_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_GENTLE
},
[FRONTIER_MON_CHARMELEON_1] = {
.species = SPECIES_CHARMELEON,
.moves = {MOVE_SLASH, MOVE_FIRE_SPIN, MOVE_SWORDS_DANCE, MOVE_AERIAL_ACE},
.itemTableId = BATTLE_FRONTIER_ITEM_SCOPE_LENS,
.evSpread = F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_NAUGHTY
},
[FRONTIER_MON_WARTORTLE_1] = {
.species = SPECIES_WARTORTLE,
.moves = {MOVE_WATER_PULSE, MOVE_BITE, MOVE_MUD_SLAP, MOVE_YAWN},
.itemTableId = BATTLE_FRONTIER_ITEM_FOCUS_BAND,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_DOCILE
},
[FRONTIER_MON_PARASECT_1] = {
.species = SPECIES_PARASECT,
.moves = {MOVE_SLASH, MOVE_PSYBEAM, MOVE_STUN_SPORE, MOVE_FLASH},
.itemTableId = BATTLE_FRONTIER_ITEM_SITRUS_BERRY,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_DEFENSE,
.nature = NATURE_RASH
},
[FRONTIER_MON_MACHOKE_1] = {
.species = SPECIES_MACHOKE,
.moves = {MOVE_LOW_KICK, MOVE_ROCK_TOMB, MOVE_FORESIGHT, MOVE_SCARY_FACE},
.itemTableId = BATTLE_FRONTIER_ITEM_FOCUS_BAND,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_HAUNTER_1] = {
.species = SPECIES_HAUNTER,
.moves = {MOVE_SHADOW_PUNCH, MOVE_CONFUSE_RAY, MOVE_SPITE, MOVE_GRUDGE},
.itemTableId = BATTLE_FRONTIER_ITEM_PERSIM_BERRY,
.evSpread = F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_RASH
},
[FRONTIER_MON_PONYTA_1] = {
.species = SPECIES_PONYTA,
.moves = {MOVE_FIRE_SPIN, MOVE_BOUNCE, MOVE_QUICK_ATTACK, MOVE_TAIL_WHIP},
.itemTableId = BATTLE_FRONTIER_ITEM_RAWST_BERRY,
.evSpread = F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_HARDY
},
[FRONTIER_MON_RATICATE_1] = {
.species = SPECIES_RATICATE,
.moves = {MOVE_ENDEAVOR, MOVE_PURSUIT, MOVE_SCARY_FACE, MOVE_QUICK_ATTACK},
.itemTableId = BATTLE_FRONTIER_ITEM_SILK_SCARF,
.evSpread = F_EV_SPREAD_SPEED | F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_NAIVE
},
[FRONTIER_MON_DRAGONAIR_1] = {
.species = SPECIES_DRAGONAIR,
.moves = {MOVE_DRAGON_BREATH, MOVE_LEER, MOVE_WRAP, MOVE_SAFEGUARD},
.itemTableId = BATTLE_FRONTIER_ITEM_CHERI_BERRY,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_DOCILE
},
[FRONTIER_MON_WIGGLYTUFF_1] = {
.species = SPECIES_WIGGLYTUFF,
.moves = {MOVE_SING, MOVE_DISABLE, MOVE_WISH, MOVE_SECRET_POWER},
.itemTableId = BATTLE_FRONTIER_ITEM_SILK_SCARF,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_DEFENSE,
.nature = NATURE_RELAXED
},
[FRONTIER_MON_TANGELA_1] = {
.species = SPECIES_TANGELA,
.moves = {MOVE_MEGA_DRAIN, MOVE_SLAM, MOVE_TOXIC, MOVE_BIND},
.itemTableId = BATTLE_FRONTIER_ITEM_LAX_INCENSE,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_HARDY
},
[FRONTIER_MON_ARBOK_1] = {
.species = SPECIES_ARBOK,
.moves = {MOVE_POISON_FANG, MOVE_DIG, MOVE_BITE, MOVE_GLARE},
.itemTableId = BATTLE_FRONTIER_ITEM_PERSIM_BERRY,
.evSpread = F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_PERSIAN_1] = {
.species = SPECIES_PERSIAN,
.moves = {MOVE_FAKE_OUT, MOVE_SLASH, MOVE_TORMENT, MOVE_SWAGGER},
.itemTableId = BATTLE_FRONTIER_ITEM_SILK_SCARF,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_QUIRKY
},
[FRONTIER_MON_SEADRA_1] = {
.species = SPECIES_SEADRA,
.moves = {MOVE_AURORA_BEAM, MOVE_SMOKESCREEN, MOVE_WATER_GUN, MOVE_RAIN_DANCE},
.itemTableId = BATTLE_FRONTIER_ITEM_MYSTIC_WATER,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_SASSY
},
[FRONTIER_MON_SANDSLASH_1] = {
.species = SPECIES_SANDSLASH,
.moves = {MOVE_CRUSH_CLAW, MOVE_ROCK_SLIDE, MOVE_SWIFT, MOVE_SANDSTORM},
.itemTableId = BATTLE_FRONTIER_ITEM_SITRUS_BERRY,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_VENOMOTH_1] = {
.species = SPECIES_VENOMOTH,
.moves = {MOVE_SILVER_WIND, MOVE_PSYBEAM, MOVE_SLEEP_POWDER, MOVE_SKILL_SWAP},
.itemTableId = BATTLE_FRONTIER_ITEM_PERSIM_BERRY,
.evSpread = F_EV_SPREAD_SPEED | F_EV_SPREAD_HP,
.nature = NATURE_QUIRKY
},
[FRONTIER_MON_CHANSEY_1] = {
.species = SPECIES_CHANSEY,
.moves = {MOVE_METRONOME, MOVE_REFRESH, MOVE_DEFENSE_CURL, MOVE_MINIMIZE},
.itemTableId = BATTLE_FRONTIER_ITEM_SITRUS_BERRY,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_DEFENSE,
.nature = NATURE_RELAXED
},
[FRONTIER_MON_SEAKING_1] = {
.species = SPECIES_SEAKING,
.moves = {MOVE_WATER_PULSE, MOVE_PSYBEAM, MOVE_SWIFT, MOVE_AGILITY},
.itemTableId = BATTLE_FRONTIER_ITEM_SITRUS_BERRY,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_DOCILE
},
[FRONTIER_MON_GOLBAT_1] = {
.species = SPECIES_GOLBAT,
.moves = {MOVE_AIR_CUTTER, MOVE_CONFUSE_RAY, MOVE_TOXIC, MOVE_STEEL_WING},
.itemTableId = BATTLE_FRONTIER_ITEM_SCOPE_LENS,
.evSpread = F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_RELAXED
},
[FRONTIER_MON_PRIMEAPE_1] = {
.species = SPECIES_PRIMEAPE,
.moves = {MOVE_KARATE_CHOP, MOVE_COUNTER, MOVE_SWAGGER, MOVE_SCREECH},
.itemTableId = BATTLE_FRONTIER_ITEM_SCOPE_LENS,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_QUIRKY
},
[FRONTIER_MON_HITMONLEE_1] = {
.species = SPECIES_HITMONLEE,
.moves = {MOVE_ROLLING_KICK, MOVE_BRICK_BREAK, MOVE_FOCUS_ENERGY, MOVE_FACADE},
.itemTableId = BATTLE_FRONTIER_ITEM_BLACK_BELT,
.evSpread = F_EV_SPREAD_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_HITMONCHAN_1] = {
.species = SPECIES_HITMONCHAN,
.moves = {MOVE_MACH_PUNCH, MOVE_SKY_UPPERCUT, MOVE_DETECT, MOVE_COUNTER},
.itemTableId = BATTLE_FRONTIER_ITEM_KINGS_ROCK,
.evSpread = F_EV_SPREAD_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_MAGNETON_1] = {
.species = SPECIES_MAGNETON,
.moves = {MOVE_SHOCK_WAVE, MOVE_SONIC_BOOM, MOVE_THUNDER_WAVE, MOVE_SUPERSONIC},
.itemTableId = BATTLE_FRONTIER_ITEM_CHERI_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_SPEED,
.nature = NATURE_LONELY
},
[FRONTIER_MON_PIDGEOT_1] = {
.species = SPECIES_PIDGEOT,
.moves = {MOVE_AERIAL_ACE, MOVE_FEATHER_DANCE, MOVE_MUD_SLAP, MOVE_FEINT_ATTACK},
.itemTableId = BATTLE_FRONTIER_ITEM_SHARP_BEAK,
.evSpread = F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_HARDY
},
[FRONTIER_MON_KINGLER_1] = {
.species = SPECIES_KINGLER,
.moves = {MOVE_CRABHAMMER, MOVE_METAL_CLAW, MOVE_MUD_SHOT, MOVE_PROTECT},
.itemTableId = BATTLE_FRONTIER_ITEM_SCOPE_LENS,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_HARDY
},
[FRONTIER_MON_OMASTAR_1] = {
.species = SPECIES_OMASTAR,
.moves = {MOVE_BUBBLE_BEAM, MOVE_SPIKE_CANNON, MOVE_TICKLE, MOVE_ANCIENT_POWER},
.itemTableId = BATTLE_FRONTIER_ITEM_SHELL_BELL,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_QUIRKY
},
[FRONTIER_MON_KABUTOPS_1] = {
.species = SPECIES_KABUTOPS,
.moves = {MOVE_SLASH, MOVE_DIG, MOVE_FURY_CUTTER, MOVE_KNOCK_OFF},
.itemTableId = BATTLE_FRONTIER_ITEM_SCOPE_LENS,
.evSpread = F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_POLIWRATH_1] = {
.species = SPECIES_POLIWRATH,
.moves = {MOVE_SUBMISSION, MOVE_DIG, MOVE_ROCK_TOMB, MOVE_BUBBLE_BEAM},
.itemTableId = BATTLE_FRONTIER_ITEM_BLACK_BELT,
.evSpread = F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_SCYTHER_1] = {
.species = SPECIES_SCYTHER,
.moves = {MOVE_FURY_CUTTER, MOVE_AERIAL_ACE, MOVE_LIGHT_SCREEN, MOVE_DOUBLE_TEAM},
.itemTableId = BATTLE_FRONTIER_ITEM_LIECHI_BERRY,
.evSpread = F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_RELAXED
},
[FRONTIER_MON_PINSIR_1] = {
.species = SPECIES_PINSIR,
.moves = {MOVE_SUBMISSION, MOVE_FOCUS_ENERGY, MOVE_SWORDS_DANCE, MOVE_REVENGE},
.itemTableId = BATTLE_FRONTIER_ITEM_BLACK_BELT,
.evSpread = F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_NAUGHTY
},
[FRONTIER_MON_CLOYSTER_1] = {
.species = SPECIES_CLOYSTER,
.moves = {MOVE_AURORA_BEAM, MOVE_SPIKE_CANNON, MOVE_SUPERSONIC, MOVE_PROTECT},
.itemTableId = BATTLE_FRONTIER_ITEM_NEVER_MELT_ICE,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_SASSY
},
[FRONTIER_MON_LICKITUNG_2] = {
.species = SPECIES_LICKITUNG,
.moves = {MOVE_EARTHQUAKE, MOVE_BODY_SLAM, MOVE_SHADOW_BALL, MOVE_ROCK_SLIDE},
.itemTableId = BATTLE_FRONTIER_ITEM_CHERI_BERRY,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_DEFENSE | F_EV_SPREAD_ATTACK,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_WEEPINBELL_2] = {
.species = SPECIES_WEEPINBELL,
.moves = {MOVE_SLUDGE_BOMB, MOVE_RAZOR_LEAF, MOVE_SLEEP_POWDER, MOVE_REFLECT},
.itemTableId = BATTLE_FRONTIER_ITEM_SCOPE_LENS,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_DEFENSE,
.nature = NATURE_QUIRKY
},
[FRONTIER_MON_GRAVELER_2] = {
.species = SPECIES_GRAVELER,
.moves = {MOVE_EARTHQUAKE, MOVE_ROCK_SLIDE, MOVE_BRICK_BREAK, MOVE_COUNTER},
.itemTableId = BATTLE_FRONTIER_ITEM_FOCUS_BAND,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_GLOOM_2] = {
.species = SPECIES_GLOOM,
.moves = {MOVE_SOLAR_BEAM, MOVE_SUNNY_DAY, MOVE_SLUDGE_BOMB, MOVE_MOONLIGHT},
.itemTableId = BATTLE_FRONTIER_ITEM_PECHA_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_ATTACK,
.nature = NATURE_QUIRKY
},
[FRONTIER_MON_PORYGON_2] = {
.species = SPECIES_PORYGON,
.moves = {MOVE_TRI_ATTACK, MOVE_PSYCHIC, MOVE_THUNDER_WAVE, MOVE_RECOVER},
.itemTableId = BATTLE_FRONTIER_ITEM_CHERI_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_ATTACK,
.nature = NATURE_QUIET
},
[FRONTIER_MON_KADABRA_2] = {
.species = SPECIES_KADABRA,
.moves = {MOVE_PSYCHIC, MOVE_THUNDER_WAVE, MOVE_REFLECT, MOVE_RECOVER},
.itemTableId = BATTLE_FRONTIER_ITEM_TWISTED_SPOON,
.evSpread = F_EV_SPREAD_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_MODEST
},
[FRONTIER_MON_IVYSAUR_2] = {
.species = SPECIES_IVYSAUR,
.moves = {MOVE_GIGA_DRAIN, MOVE_SLUDGE_BOMB, MOVE_SLEEP_POWDER, MOVE_LEECH_SEED},
.itemTableId = BATTLE_FRONTIER_ITEM_BRIGHT_POWDER,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_ATTACK,
.nature = NATURE_QUIRKY
},
[FRONTIER_MON_CHARMELEON_2] = {
.species = SPECIES_CHARMELEON,
.moves = {MOVE_FLAMETHROWER, MOVE_SLASH, MOVE_ANCIENT_POWER, MOVE_DRAGON_RAGE},
.itemTableId = BATTLE_FRONTIER_ITEM_SCOPE_LENS,
.evSpread = F_EV_SPREAD_SPEED | F_EV_SPREAD_ATTACK,
.nature = NATURE_HARDY
},
[FRONTIER_MON_WARTORTLE_2] = {
.species = SPECIES_WARTORTLE,
.moves = {MOVE_SURF, MOVE_ICE_BEAM, MOVE_RAPID_SPIN, MOVE_PROTECT},
.itemTableId = BATTLE_FRONTIER_ITEM_SHELL_BELL,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_DOCILE
},
[FRONTIER_MON_PARASECT_2] = {
.species = SPECIES_PARASECT,
.moves = {MOVE_SPORE, MOVE_GIGA_DRAIN, MOVE_DIG, MOVE_DOUBLE_TEAM},
.itemTableId = BATTLE_FRONTIER_ITEM_LEFTOVERS,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_CALM
},
[FRONTIER_MON_MACHOKE_2] = {
.species = SPECIES_MACHOKE,
.moves = {MOVE_CROSS_CHOP, MOVE_ROCK_SLIDE, MOVE_FORESIGHT, MOVE_SCARY_FACE},
.itemTableId = BATTLE_FRONTIER_ITEM_SCOPE_LENS,
.evSpread = F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_HAUNTER_2] = {
.species = SPECIES_HAUNTER,
.moves = {MOVE_PSYCHIC, MOVE_HYPNOSIS, MOVE_NIGHTMARE, MOVE_CONFUSE_RAY},
.itemTableId = BATTLE_FRONTIER_ITEM_LUM_BERRY,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_RELAXED
},
[FRONTIER_MON_PONYTA_2] = {
.species = SPECIES_PONYTA,
.moves = {MOVE_FLAMETHROWER, MOVE_BODY_SLAM, MOVE_DOUBLE_KICK, MOVE_DOUBLE_TEAM},
.itemTableId = BATTLE_FRONTIER_ITEM_SITRUS_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_SPEED,
.nature = NATURE_QUIRKY
},
[FRONTIER_MON_RATICATE_2] = {
.species = SPECIES_RATICATE,
.moves = {MOVE_SUPER_FANG, MOVE_HYPER_FANG, MOVE_SHADOW_BALL, MOVE_SCARY_FACE},
.itemTableId = BATTLE_FRONTIER_ITEM_FOCUS_BAND,
.evSpread = F_EV_SPREAD_SPEED | F_EV_SPREAD_ATTACK,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_DRAGONAIR_2] = {
.species = SPECIES_DRAGONAIR,
.moves = {MOVE_RETURN, MOVE_REST, MOVE_THUNDER_WAVE, MOVE_DRAGON_DANCE},
.itemTableId = BATTLE_FRONTIER_ITEM_CHESTO_BERRY,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_WIGGLYTUFF_2] = {
.species = SPECIES_WIGGLYTUFF,
.moves = {MOVE_FAKE_TEARS, MOVE_SING, MOVE_DREAM_EATER, MOVE_BRICK_BREAK},
.itemTableId = BATTLE_FRONTIER_ITEM_SITRUS_BERRY,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_DEFENSE,
.nature = NATURE_DOCILE
},
[FRONTIER_MON_TANGELA_2] = {
.species = SPECIES_TANGELA,
.moves = {MOVE_GIGA_DRAIN, MOVE_STUN_SPORE, MOVE_REST, MOVE_AMNESIA},
.itemTableId = BATTLE_FRONTIER_ITEM_CHESTO_BERRY,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_CALM
},
[FRONTIER_MON_ARBOK_2] = {
.species = SPECIES_ARBOK,
.moves = {MOVE_SLUDGE_BOMB, MOVE_EARTHQUAKE, MOVE_IRON_TAIL, MOVE_GLARE},
.itemTableId = BATTLE_FRONTIER_ITEM_LUM_BERRY,
.evSpread = F_EV_SPREAD_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_PERSIAN_2] = {
.species = SPECIES_PERSIAN,
.moves = {MOVE_FRUSTRATION, MOVE_SHADOW_BALL, MOVE_ROAR, MOVE_FAKE_OUT},
.itemTableId = BATTLE_FRONTIER_ITEM_SILK_SCARF,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_QUIRKY
},
[FRONTIER_MON_SEADRA_2] = {
.species = SPECIES_SEADRA,
.moves = {MOVE_HYDRO_PUMP, MOVE_FRUSTRATION, MOVE_DRAGON_BREATH, MOVE_DRAGON_DANCE},
.itemTableId = BATTLE_FRONTIER_ITEM_SHELL_BELL,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_DOCILE
},
[FRONTIER_MON_SANDSLASH_2] = {
.species = SPECIES_SANDSLASH,
.moves = {MOVE_EARTHQUAKE, MOVE_ROCK_SLIDE, MOVE_CRUSH_CLAW, MOVE_SANDSTORM},
.itemTableId = BATTLE_FRONTIER_ITEM_QUICK_CLAW,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_VENOMOTH_2] = {
.species = SPECIES_VENOMOTH,
.moves = {MOVE_SIGNAL_BEAM, MOVE_PSYCHIC, MOVE_SLUDGE_BOMB, MOVE_GIGA_DRAIN},
.itemTableId = BATTLE_FRONTIER_ITEM_LUM_BERRY,
.evSpread = F_EV_SPREAD_SPEED | F_EV_SPREAD_HP,
.nature = NATURE_DOCILE
},
[FRONTIER_MON_CHANSEY_2] = {
.species = SPECIES_CHANSEY,
.moves = {MOVE_SEISMIC_TOSS, MOVE_SHADOW_BALL, MOVE_DOUBLE_TEAM, MOVE_SOFT_BOILED},
.itemTableId = BATTLE_FRONTIER_ITEM_LEFTOVERS,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_DEFENSE,
.nature = NATURE_RELAXED
},
[FRONTIER_MON_SEAKING_2] = {
.species = SPECIES_SEAKING,
.moves = {MOVE_HORN_DRILL, MOVE_MEGAHORN, MOVE_SLEEP_TALK, MOVE_REST},
.itemTableId = BATTLE_FRONTIER_ITEM_QUICK_CLAW,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_IMPISH
},
[FRONTIER_MON_GOLBAT_2] = {
.species = SPECIES_GOLBAT,
.moves = {MOVE_SLUDGE_BOMB, MOVE_SHADOW_BALL, MOVE_CONFUSE_RAY, MOVE_AIR_CUTTER},
.itemTableId = BATTLE_FRONTIER_ITEM_SCOPE_LENS,
.evSpread = F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_PRIMEAPE_2] = {
.species = SPECIES_PRIMEAPE,
.moves = {MOVE_CROSS_CHOP, MOVE_ROCK_TOMB, MOVE_OVERHEAT, MOVE_BULK_UP},
.itemTableId = BATTLE_FRONTIER_ITEM_SCOPE_LENS,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_QUIRKY
},
[FRONTIER_MON_HITMONLEE_2] = {
.species = SPECIES_HITMONLEE,
.moves = {MOVE_MEGA_KICK, MOVE_BRICK_BREAK, MOVE_FORESIGHT, MOVE_ROCK_TOMB},
.itemTableId = BATTLE_FRONTIER_ITEM_LAX_INCENSE,
.evSpread = F_EV_SPREAD_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_HITMONCHAN_2] = {
.species = SPECIES_HITMONCHAN,
.moves = {MOVE_DYNAMIC_PUNCH, MOVE_MACH_PUNCH, MOVE_DETECT, MOVE_COUNTER},
.itemTableId = BATTLE_FRONTIER_ITEM_KINGS_ROCK,
.evSpread = F_EV_SPREAD_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_MAGNETON_2] = {
.species = SPECIES_MAGNETON,
.moves = {MOVE_THUNDER, MOVE_RAIN_DANCE, MOVE_THUNDER_WAVE, MOVE_METAL_SOUND},
.itemTableId = BATTLE_FRONTIER_ITEM_LUM_BERRY,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_HARDY
},
[FRONTIER_MON_PIDGEOT_2] = {
.species = SPECIES_PIDGEOT,
.moves = {MOVE_RETURN, MOVE_AERIAL_ACE, MOVE_STEEL_WING, MOVE_MUD_SLAP},
.itemTableId = BATTLE_FRONTIER_ITEM_SCOPE_LENS,
.evSpread = F_EV_SPREAD_SPEED | F_EV_SPREAD_ATTACK,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_KINGLER_2] = {
.species = SPECIES_KINGLER,
.moves = {MOVE_GUILLOTINE, MOVE_ROCK_TOMB, MOVE_FLAIL, MOVE_ENDURE},
.itemTableId = BATTLE_FRONTIER_ITEM_SALAC_BERRY,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_OMASTAR_2] = {
.species = SPECIES_OMASTAR,
.moves = {MOVE_HYDRO_PUMP, MOVE_RAIN_DANCE, MOVE_ICE_BEAM, MOVE_PROTECT},
.itemTableId = BATTLE_FRONTIER_ITEM_SITRUS_BERRY,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_MODEST
},
[FRONTIER_MON_KABUTOPS_2] = {
.species = SPECIES_KABUTOPS,
.moves = {MOVE_SLASH, MOVE_ROCK_SLIDE, MOVE_FLAIL, MOVE_ENDURE},
.itemTableId = BATTLE_FRONTIER_ITEM_SALAC_BERRY,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_ATTACK,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_POLIWRATH_2] = {
.species = SPECIES_POLIWRATH,
.moves = {MOVE_BRICK_BREAK, MOVE_HYPNOSIS, MOVE_REST, MOVE_BELLY_DRUM},
.itemTableId = BATTLE_FRONTIER_ITEM_CHESTO_BERRY,
.evSpread = F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_SCYTHER_2] = {
.species = SPECIES_SCYTHER,
.moves = {MOVE_SILVER_WIND, MOVE_AERIAL_ACE, MOVE_SWORDS_DANCE, MOVE_DOUBLE_TEAM},
.itemTableId = BATTLE_FRONTIER_ITEM_BRIGHT_POWDER,
.evSpread = F_EV_SPREAD_SPEED | F_EV_SPREAD_ATTACK,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_PINSIR_2] = {
.species = SPECIES_PINSIR,
.moves = {MOVE_GUILLOTINE, MOVE_SWORDS_DANCE, MOVE_FLAIL, MOVE_ENDURE},
.itemTableId = BATTLE_FRONTIER_ITEM_SALAC_BERRY,
.evSpread = F_EV_SPREAD_SPEED | F_EV_SPREAD_HP,
.nature = NATURE_JOLLY
},
[FRONTIER_MON_CLOYSTER_2] = {
.species = SPECIES_CLOYSTER,
.moves = {MOVE_DIVE, MOVE_TOXIC, MOVE_DOUBLE_TEAM, MOVE_PROTECT},
.itemTableId = BATTLE_FRONTIER_ITEM_LEFTOVERS,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_CAREFUL
},
[FRONTIER_MON_DUGTRIO_1] = {
.species = SPECIES_DUGTRIO,
.moves = {MOVE_EARTHQUAKE, MOVE_TRI_ATTACK, MOVE_SLASH, MOVE_SAND_TOMB},
.itemTableId = BATTLE_FRONTIER_ITEM_SOFT_SAND,
.evSpread = F_EV_SPREAD_SPEED | F_EV_SPREAD_ATTACK,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_FEAROW_1] = {
.species = SPECIES_FEAROW,
.moves = {MOVE_DRILL_PECK, MOVE_TRI_ATTACK, MOVE_FACADE, MOVE_MUD_SLAP},
.itemTableId = BATTLE_FRONTIER_ITEM_SHARP_BEAK,
.evSpread = F_EV_SPREAD_SPEED | F_EV_SPREAD_ATTACK,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_JYNX_1] = {
.species = SPECIES_JYNX,
.moves = {MOVE_ICE_BEAM, MOVE_FAKE_OUT, MOVE_LOVELY_KISS, MOVE_ATTRACT},
.itemTableId = BATTLE_FRONTIER_ITEM_SHELL_BELL,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_MODEST
},
[FRONTIER_MON_DODRIO_1] = {
.species = SPECIES_DODRIO,
.moves = {MOVE_DRILL_PECK, MOVE_TRI_ATTACK, MOVE_SLEEP_TALK, MOVE_REST},
.itemTableId = BATTLE_FRONTIER_ITEM_CHESTO_BERRY,
.evSpread = F_EV_SPREAD_SPEED | F_EV_SPREAD_ATTACK,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_MR_MIME_1] = {
.species = SPECIES_MR_MIME,
.moves = {MOVE_PSYCHIC, MOVE_MAGICAL_LEAF, MOVE_FAKE_OUT, MOVE_REFLECT},
.itemTableId = BATTLE_FRONTIER_ITEM_LEFTOVERS,
.evSpread = F_EV_SPREAD_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_RELAXED
},
[FRONTIER_MON_MAROWAK_1] = {
.species = SPECIES_MAROWAK,
.moves = {MOVE_BONEMERANG, MOVE_ROCK_SLIDE, MOVE_ICY_WIND, MOVE_HEADBUTT},
.itemTableId = BATTLE_FRONTIER_ITEM_THICK_CLUB,
.evSpread = F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_CLEFABLE_1] = {
.species = SPECIES_CLEFABLE,
.moves = {MOVE_METRONOME, MOVE_DOUBLE_TEAM, MOVE_REFLECT, MOVE_FOLLOW_ME},
.itemTableId = BATTLE_FRONTIER_ITEM_LEFTOVERS,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_DEFENSE,
.nature = NATURE_BRAVE
},
[FRONTIER_MON_RAICHU_1] = {
.species = SPECIES_RAICHU,
.moves = {MOVE_THUNDERBOLT, MOVE_QUICK_ATTACK, MOVE_LIGHT_SCREEN, MOVE_DOUBLE_TEAM},
.itemTableId = BATTLE_FRONTIER_ITEM_BRIGHT_POWDER,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_SPEED | F_EV_SPREAD_DEFENSE,
.nature = NATURE_MODEST
},
[FRONTIER_MON_DEWGONG_1] = {
.species = SPECIES_DEWGONG,
.moves = {MOVE_ICE_BEAM, MOVE_ICY_WIND, MOVE_HEADBUTT, MOVE_FAKE_OUT},
.itemTableId = BATTLE_FRONTIER_ITEM_NEVER_MELT_ICE,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_QUIET
},
[FRONTIER_MON_VILEPLUME_1] = {
.species = SPECIES_VILEPLUME,
.moves = {MOVE_SLUDGE_BOMB, MOVE_PETAL_DANCE, MOVE_MOONLIGHT, MOVE_AROMATHERAPY},
.itemTableId = BATTLE_FRONTIER_ITEM_PERSIM_BERRY,
.evSpread = F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_IMPISH
},
[FRONTIER_MON_VICTREEBEL_1] = {
.species = SPECIES_VICTREEBEL,
.moves = {MOVE_GIGA_DRAIN, MOVE_SLEEP_POWDER, MOVE_SWEET_SCENT, MOVE_SYNTHESIS},
.itemTableId = BATTLE_FRONTIER_ITEM_SITRUS_BERRY,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_DEFENSE,
.nature = NATURE_QUIET
},
[FRONTIER_MON_ELECTRODE_1] = {
.species = SPECIES_ELECTRODE,
.moves = {MOVE_THUNDERBOLT, MOVE_SWIFT, MOVE_LIGHT_SCREEN, MOVE_PROTECT},
.itemTableId = BATTLE_FRONTIER_ITEM_FOCUS_BAND,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_QUIET
},
[FRONTIER_MON_HYPNO_1] = {
.species = SPECIES_HYPNO,
.moves = {MOVE_THUNDER_PUNCH, MOVE_FIRE_PUNCH, MOVE_ICE_PUNCH, MOVE_HYPNOSIS},
.itemTableId = BATTLE_FRONTIER_ITEM_TWISTED_SPOON,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_DEFENSE,
.nature = NATURE_QUIET
},
[FRONTIER_MON_GOLEM_1] = {
.species = SPECIES_GOLEM,
.moves = {MOVE_EARTHQUAKE, MOVE_BODY_SLAM, MOVE_COUNTER, MOVE_ROCK_TOMB},
.itemTableId = BATTLE_FRONTIER_ITEM_QUICK_CLAW,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_ATTACK,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_RHYDON_1] = {
.species = SPECIES_RHYDON,
.moves = {MOVE_EARTHQUAKE, MOVE_ROCK_TOMB, MOVE_SCARY_FACE, MOVE_BRICK_BREAK},
.itemTableId = BATTLE_FRONTIER_ITEM_QUICK_CLAW,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_ALAKAZAM_1] = {
.species = SPECIES_ALAKAZAM,
.moves = {MOVE_THUNDER_PUNCH, MOVE_FIRE_PUNCH, MOVE_ICE_PUNCH, MOVE_THUNDER_WAVE},
.itemTableId = BATTLE_FRONTIER_ITEM_FOCUS_BAND,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_DEFENSE,
.nature = NATURE_MODEST
},
[FRONTIER_MON_WEEZING_1] = {
.species = SPECIES_WEEZING,
.moves = {MOVE_SLUDGE_BOMB, MOVE_WILL_O_WISP, MOVE_SHADOW_BALL, MOVE_SMOKESCREEN},
.itemTableId = BATTLE_FRONTIER_ITEM_BRIGHT_POWDER,
.evSpread = F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_KANGASKHAN_1] = {
.species = SPECIES_KANGASKHAN,
.moves = {MOVE_DIZZY_PUNCH, MOVE_BRICK_BREAK, MOVE_COUNTER, MOVE_FAKE_OUT},
.itemTableId = BATTLE_FRONTIER_ITEM_FOCUS_BAND,
.evSpread = F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_ELECTABUZZ_1] = {
.species = SPECIES_ELECTABUZZ,
.moves = {MOVE_THUNDERBOLT, MOVE_THUNDER_WAVE, MOVE_BRICK_BREAK, MOVE_LIGHT_SCREEN},
.itemTableId = BATTLE_FRONTIER_ITEM_CHERI_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_RELAXED
},
[FRONTIER_MON_TAUROS_1] = {
.species = SPECIES_TAUROS,
.moves = {MOVE_EARTHQUAKE, MOVE_THRASH, MOVE_SWAGGER, MOVE_FACADE},
.itemTableId = BATTLE_FRONTIER_ITEM_PERSIM_BERRY,
.evSpread = F_EV_SPREAD_SPEED | F_EV_SPREAD_ATTACK,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_SLOWBRO_1] = {
.species = SPECIES_SLOWBRO,
.moves = {MOVE_SURF, MOVE_RAIN_DANCE, MOVE_HEADBUTT, MOVE_ICE_PUNCH},
.itemTableId = BATTLE_FRONTIER_ITEM_SHELL_BELL,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_QUIET
},
[FRONTIER_MON_NIDOQUEEN_1] = {
.species = SPECIES_NIDOQUEEN,
.moves = {MOVE_SLUDGE_BOMB, MOVE_DOUBLE_KICK, MOVE_BODY_SLAM, MOVE_COUNTER},
.itemTableId = BATTLE_FRONTIER_ITEM_FOCUS_BAND,
.evSpread = F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_NIDOKING_1] = {
.species = SPECIES_NIDOKING,
.moves = {MOVE_HORN_DRILL, MOVE_DOUBLE_KICK, MOVE_BODY_SLAM, MOVE_COUNTER},
.itemTableId = BATTLE_FRONTIER_ITEM_QUICK_CLAW,
.evSpread = F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_MAGMAR_1] = {
.species = SPECIES_MAGMAR,
.moves = {MOVE_FLAMETHROWER, MOVE_SMOKESCREEN, MOVE_BRICK_BREAK, MOVE_BARRIER},
.itemTableId = BATTLE_FRONTIER_ITEM_RAWST_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_RELAXED
},
[FRONTIER_MON_GOLDUCK_1] = {
.species = SPECIES_GOLDUCK,
.moves = {MOVE_HYDRO_PUMP, MOVE_DIG, MOVE_BRICK_BREAK, MOVE_LIGHT_SCREEN},
.itemTableId = BATTLE_FRONTIER_ITEM_SHELL_BELL,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_ATTACK,
.nature = NATURE_QUIET
},
[FRONTIER_MON_RAPIDASH_1] = {
.species = SPECIES_RAPIDASH,
.moves = {MOVE_FLAMETHROWER, MOVE_DOUBLE_KICK, MOVE_QUICK_ATTACK, MOVE_PROTECT},
.itemTableId = BATTLE_FRONTIER_ITEM_CHARCOAL,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_SPEED,
.nature = NATURE_QUIET
},
[FRONTIER_MON_MUK_1] = {
.species = SPECIES_MUK,
.moves = {MOVE_SLUDGE_BOMB, MOVE_BODY_SLAM, MOVE_SCREECH, MOVE_MINIMIZE},
.itemTableId = BATTLE_FRONTIER_ITEM_POISON_BARB,
.evSpread = F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_GENGAR_1] = {
.species = SPECIES_GENGAR,
.moves = {MOVE_DREAM_EATER, MOVE_HYPNOSIS, MOVE_CONFUSE_RAY, MOVE_ATTRACT},
.itemTableId = BATTLE_FRONTIER_ITEM_LEFTOVERS,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_SPEED | F_EV_SPREAD_HP,
.nature = NATURE_TIMID
},
[FRONTIER_MON_NINETALES_1] = {
.species = SPECIES_NINETALES,
.moves = {MOVE_FLAMETHROWER, MOVE_ROAR, MOVE_CONFUSE_RAY, MOVE_WILL_O_WISP},
.itemTableId = BATTLE_FRONTIER_ITEM_RAWST_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_SPEED,
.nature = NATURE_MODEST
},
[FRONTIER_MON_MACHAMP_1] = {
.species = SPECIES_MACHAMP,
.moves = {MOVE_CROSS_CHOP, MOVE_ROCK_SLIDE, MOVE_COUNTER, MOVE_SCARY_FACE},
.itemTableId = BATTLE_FRONTIER_ITEM_SCOPE_LENS,
.evSpread = F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_TENTACRUEL_1] = {
.species = SPECIES_TENTACRUEL,
.moves = {MOVE_SLUDGE_BOMB, MOVE_ICY_WIND, MOVE_BARRIER, MOVE_CONFUSE_RAY},
.itemTableId = BATTLE_FRONTIER_ITEM_PERSIM_BERRY,
.evSpread = F_EV_SPREAD_DEFENSE | F_EV_SPREAD_ATTACK,
.nature = NATURE_IMPISH
},
[FRONTIER_MON_AERODACTYL_1] = {
.species = SPECIES_AERODACTYL,
.moves = {MOVE_ANCIENT_POWER, MOVE_DRAGON_BREATH, MOVE_AERIAL_ACE, MOVE_ROAR},
.itemTableId = BATTLE_FRONTIER_ITEM_KINGS_ROCK,
.evSpread = F_EV_SPREAD_SPEED | F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_EXEGGUTOR_1] = {
.species = SPECIES_EXEGGUTOR,
.moves = {MOVE_SOLAR_BEAM, MOVE_SUNNY_DAY, MOVE_SYNTHESIS, MOVE_LIGHT_SCREEN},
.itemTableId = BATTLE_FRONTIER_ITEM_QUICK_CLAW,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_DEFENSE,
.nature = NATURE_QUIET
},
[FRONTIER_MON_STARMIE_1] = {
.species = SPECIES_STARMIE,
.moves = {MOVE_PSYCHIC, MOVE_CONFUSE_RAY, MOVE_THUNDER_WAVE, MOVE_RECOVER},
.itemTableId = BATTLE_FRONTIER_ITEM_SHELL_BELL,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_MODEST
},
[FRONTIER_MON_VENUSAUR_1] = {
.species = SPECIES_VENUSAUR,
.moves = {MOVE_GIGA_DRAIN, MOVE_SUNNY_DAY, MOVE_SYNTHESIS, MOVE_SLEEP_POWDER},
.itemTableId = BATTLE_FRONTIER_ITEM_CHESTO_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_QUIET
},
[FRONTIER_MON_VAPOREON_1] = {
.species = SPECIES_VAPOREON,
.moves = {MOVE_SURF, MOVE_ROAR, MOVE_BITE, MOVE_QUICK_ATTACK},
.itemTableId = BATTLE_FRONTIER_ITEM_MYSTIC_WATER,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_DEFENSE,
.nature = NATURE_MODEST
},
[FRONTIER_MON_JOLTEON_1] = {
.species = SPECIES_JOLTEON,
.moves = {MOVE_THUNDERBOLT, MOVE_THUNDER_WAVE, MOVE_ATTRACT, MOVE_PROTECT},
.itemTableId = BATTLE_FRONTIER_ITEM_CHERI_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_SPEED,
.nature = NATURE_MODEST
},
[FRONTIER_MON_FLAREON_1] = {
.species = SPECIES_FLAREON,
.moves = {MOVE_FLAMETHROWER, MOVE_ROAR, MOVE_BITE, MOVE_SAND_ATTACK},
.itemTableId = BATTLE_FRONTIER_ITEM_SITRUS_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_DEFENSE,
.nature = NATURE_MODEST
},
[FRONTIER_MON_BLASTOISE_1] = {
.species = SPECIES_BLASTOISE,
.moves = {MOVE_HYDRO_PUMP, MOVE_RAIN_DANCE, MOVE_BITE, MOVE_SEISMIC_TOSS},
.itemTableId = BATTLE_FRONTIER_ITEM_SHELL_BELL,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_MODEST
},
[FRONTIER_MON_CHARIZARD_1] = {
.species = SPECIES_CHARIZARD,
.moves = {MOVE_FIRE_BLAST, MOVE_SUNNY_DAY, MOVE_ROAR, MOVE_SCARY_FACE},
.itemTableId = BATTLE_FRONTIER_ITEM_FOCUS_BAND,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_SPEED,
.nature = NATURE_MODEST
},
[FRONTIER_MON_LAPRAS_1] = {
.species = SPECIES_LAPRAS,
.moves = {MOVE_SURF, MOVE_ATTRACT, MOVE_CONFUSE_RAY, MOVE_SING},
.itemTableId = BATTLE_FRONTIER_ITEM_LEFTOVERS,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_DEFENSE,
.nature = NATURE_BOLD
},
[FRONTIER_MON_GYARADOS_1] = {
.species = SPECIES_GYARADOS,
.moves = {MOVE_RETURN, MOVE_BITE, MOVE_THUNDER_WAVE, MOVE_DRAGON_DANCE},
.itemTableId = BATTLE_FRONTIER_ITEM_LUM_BERRY,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_CAREFUL
},
[FRONTIER_MON_SNORLAX_1] = {
.species = SPECIES_SNORLAX,
.moves = {MOVE_FACADE, MOVE_SHADOW_BALL, MOVE_ATTRACT, MOVE_DOUBLE_TEAM},
.itemTableId = BATTLE_FRONTIER_ITEM_LEFTOVERS,
.evSpread = F_EV_SPREAD_DEFENSE | F_EV_SPREAD_ATTACK,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_ARCANINE_1] = {
.species = SPECIES_ARCANINE,
.moves = {MOVE_FLAMETHROWER, MOVE_EXTREME_SPEED, MOVE_CRUNCH, MOVE_BODY_SLAM},
.itemTableId = BATTLE_FRONTIER_ITEM_KINGS_ROCK,
.evSpread = F_EV_SPREAD_SPEED | F_EV_SPREAD_ATTACK,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_DUGTRIO_2] = {
.species = SPECIES_DUGTRIO,
.moves = {MOVE_EARTHQUAKE, MOVE_ANCIENT_POWER, MOVE_AERIAL_ACE, MOVE_TRI_ATTACK},
.itemTableId = BATTLE_FRONTIER_ITEM_KINGS_ROCK,
.evSpread = F_EV_SPREAD_SPEED | F_EV_SPREAD_ATTACK,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_MAROWAK_2] = {
.species = SPECIES_MAROWAK,
.moves = {MOVE_EARTHQUAKE, MOVE_ROCK_SLIDE, MOVE_SWORDS_DANCE, MOVE_ICY_WIND},
.itemTableId = BATTLE_FRONTIER_ITEM_THICK_CLUB,
.evSpread = F_EV_SPREAD_SPEED | F_EV_SPREAD_ATTACK,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_FEAROW_2] = {
.species = SPECIES_FEAROW,
.moves = {MOVE_DRILL_PECK, MOVE_TRI_ATTACK, MOVE_ATTRACT, MOVE_PURSUIT},
.itemTableId = BATTLE_FRONTIER_ITEM_FOCUS_BAND,
.evSpread = F_EV_SPREAD_SPEED | F_EV_SPREAD_ATTACK,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_JYNX_2] = {
.species = SPECIES_JYNX,
.moves = {MOVE_PERISH_SONG, MOVE_MEAN_LOOK, MOVE_LOVELY_KISS, MOVE_PROTECT},
.itemTableId = BATTLE_FRONTIER_ITEM_BRIGHT_POWDER,
.evSpread = F_EV_SPREAD_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_IMPISH
},
[FRONTIER_MON_DODRIO_2] = {
.species = SPECIES_DODRIO,
.moves = {MOVE_DRILL_PECK, MOVE_DOUBLE_EDGE, MOVE_FEINT_ATTACK, MOVE_PROTECT},
.itemTableId = BATTLE_FRONTIER_ITEM_KINGS_ROCK,
.evSpread = F_EV_SPREAD_SPEED | F_EV_SPREAD_ATTACK,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_MR_MIME_2] = {
.species = SPECIES_MR_MIME,
.moves = {MOVE_BATON_PASS, MOVE_SWAGGER, MOVE_PSYCH_UP, MOVE_PSYCHIC},
.itemTableId = BATTLE_FRONTIER_ITEM_LIECHI_BERRY,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_CLEFABLE_2] = {
.species = SPECIES_CLEFABLE,
.moves = {MOVE_METEOR_MASH, MOVE_COSMIC_POWER, MOVE_DOUBLE_TEAM, MOVE_FOLLOW_ME},
.itemTableId = BATTLE_FRONTIER_ITEM_FOCUS_BAND,
.evSpread = F_EV_SPREAD_DEFENSE | F_EV_SPREAD_ATTACK,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_RAICHU_2] = {
.species = SPECIES_RAICHU,
.moves = {MOVE_THUNDERBOLT, MOVE_REVERSAL, MOVE_ENDURE, MOVE_AGILITY},
.itemTableId = BATTLE_FRONTIER_ITEM_LUM_BERRY,
.evSpread = F_EV_SPREAD_SPEED | F_EV_SPREAD_ATTACK,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_DEWGONG_2] = {
.species = SPECIES_DEWGONG,
.moves = {MOVE_BLIZZARD, MOVE_DOUBLE_EDGE, MOVE_ENCORE, MOVE_DISABLE},
.itemTableId = BATTLE_FRONTIER_ITEM_SHELL_BELL,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_ATTACK,
.nature = NATURE_DOCILE
},
[FRONTIER_MON_VILEPLUME_2] = {
.species = SPECIES_VILEPLUME,
.moves = {MOVE_INGRAIN, MOVE_DOUBLE_TEAM, MOVE_TOXIC, MOVE_GIGA_DRAIN},
.itemTableId = BATTLE_FRONTIER_ITEM_BRIGHT_POWDER,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_BOLD
},
[FRONTIER_MON_VICTREEBEL_2] = {
.species = SPECIES_VICTREEBEL,
.moves = {MOVE_GIGA_DRAIN, MOVE_SLUDGE_BOMB, MOVE_SLEEP_POWDER, MOVE_ATTRACT},
.itemTableId = BATTLE_FRONTIER_ITEM_LEFTOVERS,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_ATTACK,
.nature = NATURE_SERIOUS
},
[FRONTIER_MON_ELECTRODE_2] = {
.species = SPECIES_ELECTRODE,
.moves = {MOVE_THUNDER, MOVE_RAIN_DANCE, MOVE_DOUBLE_TEAM, MOVE_SWAGGER},
.itemTableId = BATTLE_FRONTIER_ITEM_BRIGHT_POWDER,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_MODEST
},
[FRONTIER_MON_HYPNO_2] = {
.species = SPECIES_HYPNO,
.moves = {MOVE_HYPNOSIS, MOVE_NIGHTMARE, MOVE_DREAM_EATER, MOVE_PSYCHIC},
.itemTableId = BATTLE_FRONTIER_ITEM_TWISTED_SPOON,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_DEFENSE,
.nature = NATURE_MODEST
},
[FRONTIER_MON_GOLEM_2] = {
.species = SPECIES_GOLEM,
.moves = {MOVE_FOCUS_PUNCH, MOVE_SUBSTITUTE, MOVE_DOUBLE_TEAM, MOVE_REST},
.itemTableId = BATTLE_FRONTIER_ITEM_CHESTO_BERRY,
.evSpread = F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_RHYDON_2] = {
.species = SPECIES_RHYDON,
.moves = {MOVE_EARTHQUAKE, MOVE_HORN_DRILL, MOVE_ROCK_SLIDE, MOVE_BRICK_BREAK},
.itemTableId = BATTLE_FRONTIER_ITEM_QUICK_CLAW,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_ATTACK,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_ALAKAZAM_2] = {
.species = SPECIES_ALAKAZAM,
.moves = {MOVE_PSYCHIC, MOVE_CALM_MIND, MOVE_THUNDER_WAVE, MOVE_RECOVER},
.itemTableId = BATTLE_FRONTIER_ITEM_LUM_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_DEFENSE,
.nature = NATURE_MODEST
},
[FRONTIER_MON_WEEZING_2] = {
.species = SPECIES_WEEZING,
.moves = {MOVE_MEMENTO, MOVE_SLUDGE_BOMB, MOVE_FACADE, MOVE_DESTINY_BOND},
.itemTableId = BATTLE_FRONTIER_ITEM_SITRUS_BERRY,
.evSpread = F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_KANGASKHAN_2] = {
.species = SPECIES_KANGASKHAN,
.moves = {MOVE_CRUSH_CLAW, MOVE_SHADOW_BALL, MOVE_ATTRACT, MOVE_REST},
.itemTableId = BATTLE_FRONTIER_ITEM_LUM_BERRY,
.evSpread = F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_ELECTABUZZ_2] = {
.species = SPECIES_ELECTABUZZ,
.moves = {MOVE_THUNDER, MOVE_RAIN_DANCE, MOVE_ATTRACT, MOVE_FOCUS_PUNCH},
.itemTableId = BATTLE_FRONTIER_ITEM_LEFTOVERS,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_SPEED | F_EV_SPREAD_ATTACK,
.nature = NATURE_QUIRKY
},
[FRONTIER_MON_TAUROS_2] = {
.species = SPECIES_TAUROS,
.moves = {MOVE_DOUBLE_EDGE, MOVE_EARTHQUAKE, MOVE_DOUBLE_TEAM, MOVE_REST},
.itemTableId = BATTLE_FRONTIER_ITEM_CHESTO_BERRY,
.evSpread = F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_SLOWBRO_2] = {
.species = SPECIES_SLOWBRO,
.moves = {MOVE_SURF, MOVE_ICE_BEAM, MOVE_CALM_MIND, MOVE_YAWN},
.itemTableId = BATTLE_FRONTIER_ITEM_LEFTOVERS,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_ATTACK,
.nature = NATURE_MODEST
},
[FRONTIER_MON_NIDOQUEEN_2] = {
.species = SPECIES_NIDOQUEEN,
.moves = {MOVE_DOUBLE_EDGE, MOVE_EARTHQUAKE, MOVE_AERIAL_ACE, MOVE_ROCK_SLIDE},
.itemTableId = BATTLE_FRONTIER_ITEM_SHELL_BELL,
.evSpread = F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_NIDOKING_2] = {
.species = SPECIES_NIDOKING,
.moves = {MOVE_MEGA_KICK, MOVE_EARTHQUAKE, MOVE_SHADOW_BALL, MOVE_BRICK_BREAK},
.itemTableId = BATTLE_FRONTIER_ITEM_SHELL_BELL,
.evSpread = F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_MAGMAR_2] = {
.species = SPECIES_MAGMAR,
.moves = {MOVE_FIRE_BLAST, MOVE_SMOKESCREEN, MOVE_THUNDER_PUNCH, MOVE_CONFUSE_RAY},
.itemTableId = BATTLE_FRONTIER_ITEM_QUICK_CLAW,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_SPEED,
.nature = NATURE_MODEST
},
[FRONTIER_MON_GOLDUCK_2] = {
.species = SPECIES_GOLDUCK,
.moves = {MOVE_CROSS_CHOP, MOVE_SURF, MOVE_SWAGGER, MOVE_PSYCH_UP},
.itemTableId = BATTLE_FRONTIER_ITEM_LUM_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_SPEED | F_EV_SPREAD_ATTACK,
.nature = NATURE_QUIRKY
},
[FRONTIER_MON_RAPIDASH_2] = {
.species = SPECIES_RAPIDASH,
.moves = {MOVE_FIRE_BLAST, MOVE_BOUNCE, MOVE_DOUBLE_TEAM, MOVE_ATTRACT},
.itemTableId = BATTLE_FRONTIER_ITEM_LEFTOVERS,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_SPEED | F_EV_SPREAD_ATTACK,
.nature = NATURE_DOCILE
},
[FRONTIER_MON_MUK_2] = {
.species = SPECIES_MUK,
.moves = {MOVE_CURSE, MOVE_REST, MOVE_SLUDGE_BOMB, MOVE_DYNAMIC_PUNCH},
.itemTableId = BATTLE_FRONTIER_ITEM_CHESTO_BERRY,
.evSpread = F_EV_SPREAD_DEFENSE | F_EV_SPREAD_ATTACK,
.nature = NATURE_HARDY
},
[FRONTIER_MON_GENGAR_2] = {
.species = SPECIES_GENGAR,
.moves = {MOVE_SLUDGE_BOMB, MOVE_SHADOW_BALL, MOVE_CONFUSE_RAY, MOVE_WILL_O_WISP},
.itemTableId = BATTLE_FRONTIER_ITEM_LEFTOVERS,
.evSpread = F_EV_SPREAD_SPEED | F_EV_SPREAD_ATTACK,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_NINETALES_2] = {
.species = SPECIES_NINETALES,
.moves = {MOVE_HEAT_WAVE, MOVE_BODY_SLAM, MOVE_GRUDGE, MOVE_SUNNY_DAY},
.itemTableId = BATTLE_FRONTIER_ITEM_LUM_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_SPEED,
.nature = NATURE_QUIRKY
},
[FRONTIER_MON_MACHAMP_2] = {
.species = SPECIES_MACHAMP,
.moves = {MOVE_CROSS_CHOP, MOVE_EARTHQUAKE, MOVE_BULK_UP, MOVE_REST},
.itemTableId = BATTLE_FRONTIER_ITEM_CHESTO_BERRY,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_TENTACRUEL_2] = {
.species = SPECIES_TENTACRUEL,
.moves = {MOVE_TOXIC, MOVE_GIGA_DRAIN, MOVE_CONFUSE_RAY, MOVE_SURF},
.itemTableId = BATTLE_FRONTIER_ITEM_LEFTOVERS,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_HARDY
},
[FRONTIER_MON_AERODACTYL_2] = {
.species = SPECIES_AERODACTYL,
.moves = {MOVE_HYPER_BEAM, MOVE_EARTHQUAKE, MOVE_AERIAL_ACE, MOVE_ANCIENT_POWER},
.itemTableId = BATTLE_FRONTIER_ITEM_CHOICE_BAND,
.evSpread = F_EV_SPREAD_SPEED | F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_EXEGGUTOR_2] = {
.species = SPECIES_EXEGGUTOR,
.moves = {MOVE_RETURN, MOVE_CURSE, MOVE_SLEEP_POWDER, MOVE_REST},
.itemTableId = BATTLE_FRONTIER_ITEM_CHESTO_BERRY,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_ATTACK,
.nature = NATURE_HARDY
},
[FRONTIER_MON_STARMIE_2] = {
.species = SPECIES_STARMIE,
.moves = {MOVE_HYDRO_PUMP, MOVE_THUNDER, MOVE_RAIN_DANCE, MOVE_RECOVER},
.itemTableId = BATTLE_FRONTIER_ITEM_SHELL_BELL,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_MODEST
},
[FRONTIER_MON_VENUSAUR_2] = {
.species = SPECIES_VENUSAUR,
.moves = {MOVE_LEECH_SEED, MOVE_GIGA_DRAIN, MOVE_DOUBLE_TEAM, MOVE_LIGHT_SCREEN},
.itemTableId = BATTLE_FRONTIER_ITEM_BRIGHT_POWDER,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_BOLD
},
[FRONTIER_MON_VAPOREON_2] = {
.species = SPECIES_VAPOREON,
.moves = {MOVE_SURF, MOVE_ICE_BEAM, MOVE_BODY_SLAM, MOVE_SHADOW_BALL},
.itemTableId = BATTLE_FRONTIER_ITEM_SHELL_BELL,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_DOCILE
},
[FRONTIER_MON_JOLTEON_2] = {
.species = SPECIES_JOLTEON,
.moves = {MOVE_THUNDERBOLT, MOVE_DIG, MOVE_DOUBLE_KICK, MOVE_ROAR},
.itemTableId = BATTLE_FRONTIER_ITEM_SCOPE_LENS,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_ATTACK,
.nature = NATURE_HARDY
},
[FRONTIER_MON_FLAREON_2] = {
.species = SPECIES_FLAREON,
.moves = {MOVE_CURSE, MOVE_ATTRACT, MOVE_DOUBLE_EDGE, MOVE_SHADOW_BALL},
.itemTableId = BATTLE_FRONTIER_ITEM_QUICK_CLAW,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_RELAXED
},
[FRONTIER_MON_BLASTOISE_2] = {
.species = SPECIES_BLASTOISE,
.moves = {MOVE_HYDRO_PUMP, MOVE_MEGA_KICK, MOVE_BRICK_BREAK, MOVE_MIRROR_COAT},
.itemTableId = BATTLE_FRONTIER_ITEM_SHELL_BELL,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_BRAVE
},
[FRONTIER_MON_CHARIZARD_2] = {
.species = SPECIES_CHARIZARD,
.moves = {MOVE_EARTHQUAKE, MOVE_AERIAL_ACE, MOVE_DRAGON_DANCE, MOVE_SMOKESCREEN},
.itemTableId = BATTLE_FRONTIER_ITEM_BRIGHT_POWDER,
.evSpread = F_EV_SPREAD_SPEED | F_EV_SPREAD_ATTACK,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_LAPRAS_2] = {
.species = SPECIES_LAPRAS,
.moves = {MOVE_SURF, MOVE_ICE_BEAM, MOVE_BODY_SLAM, MOVE_ROAR},
.itemTableId = BATTLE_FRONTIER_ITEM_QUICK_CLAW,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_SPEED,
.nature = NATURE_TIMID
},
[FRONTIER_MON_GYARADOS_2] = {
.species = SPECIES_GYARADOS,
.moves = {MOVE_HYDRO_PUMP, MOVE_THUNDERBOLT, MOVE_FIRE_BLAST, MOVE_BLIZZARD},
.itemTableId = BATTLE_FRONTIER_ITEM_SHELL_BELL,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_SPEED,
.nature = NATURE_MODEST
},
[FRONTIER_MON_SNORLAX_2] = {
.species = SPECIES_SNORLAX,
.moves = {MOVE_EARTHQUAKE, MOVE_ROCK_SLIDE, MOVE_CURSE, MOVE_REST},
.itemTableId = BATTLE_FRONTIER_ITEM_CHESTO_BERRY,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_ARCANINE_2] = {
.species = SPECIES_ARCANINE,
.moves = {MOVE_FIRE_BLAST, MOVE_SUNNY_DAY, MOVE_CRUNCH, MOVE_ROAR},
.itemTableId = BATTLE_FRONTIER_ITEM_LUM_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_SPEED,
.nature = NATURE_DOCILE
},
[FRONTIER_MON_DUGTRIO_3] = {
.species = SPECIES_DUGTRIO,
.moves = {MOVE_EARTHQUAKE, MOVE_DOUBLE_EDGE, MOVE_SLUDGE_BOMB, MOVE_FISSURE},
.itemTableId = BATTLE_FRONTIER_ITEM_KINGS_ROCK,
.evSpread = F_EV_SPREAD_SPEED | F_EV_SPREAD_ATTACK,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_FEAROW_3] = {
.species = SPECIES_FEAROW,
.moves = {MOVE_DRILL_PECK, MOVE_RETURN, MOVE_STEEL_WING, MOVE_FEINT_ATTACK},
.itemTableId = BATTLE_FRONTIER_ITEM_SCOPE_LENS,
.evSpread = F_EV_SPREAD_SPEED | F_EV_SPREAD_ATTACK,
.nature = NATURE_HARDY
},
[FRONTIER_MON_JYNX_3] = {
.species = SPECIES_JYNX,
.moves = {MOVE_DREAM_EATER, MOVE_LOVELY_KISS, MOVE_ATTRACT, MOVE_SUBSTITUTE},
.itemTableId = BATTLE_FRONTIER_ITEM_QUICK_CLAW,
.evSpread = F_EV_SPREAD_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_HARDY
},
[FRONTIER_MON_DODRIO_3] = {
.species = SPECIES_DODRIO,
.moves = {MOVE_DOUBLE_EDGE, MOVE_DRILL_PECK, MOVE_STEEL_WING, MOVE_FEINT_ATTACK},
.itemTableId = BATTLE_FRONTIER_ITEM_LUM_BERRY,
.evSpread = F_EV_SPREAD_SPEED | F_EV_SPREAD_ATTACK,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_MR_MIME_3] = {
.species = SPECIES_MR_MIME,
.moves = {MOVE_TRICK, MOVE_TORMENT, MOVE_PSYCHIC, MOVE_THUNDERBOLT},
.itemTableId = BATTLE_FRONTIER_ITEM_CHOICE_BAND,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_MODEST
},
[FRONTIER_MON_MAROWAK_3] = {
.species = SPECIES_MAROWAK,
.moves = {MOVE_EARTHQUAKE, MOVE_ROCK_SLIDE, MOVE_SWORDS_DANCE, MOVE_BRICK_BREAK},
.itemTableId = BATTLE_FRONTIER_ITEM_THICK_CLUB,
.evSpread = F_EV_SPREAD_SPEED | F_EV_SPREAD_ATTACK,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_CLEFABLE_3] = {
.species = SPECIES_CLEFABLE,
.moves = {MOVE_THUNDERBOLT, MOVE_ICE_BEAM, MOVE_FLAMETHROWER, MOVE_MAGICAL_LEAF},
.itemTableId = BATTLE_FRONTIER_ITEM_LUM_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_DEFENSE,
.nature = NATURE_MODEST
},
[FRONTIER_MON_RAICHU_3] = {
.species = SPECIES_RAICHU,
.moves = {MOVE_THUNDER, MOVE_RAIN_DANCE, MOVE_IRON_TAIL, MOVE_ATTRACT},
.itemTableId = BATTLE_FRONTIER_ITEM_CHERI_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_SPEED,
.nature = NATURE_DOCILE
},
[FRONTIER_MON_DEWGONG_3] = {
.species = SPECIES_DEWGONG,
.moves = {MOVE_HORN_DRILL, MOVE_SHEER_COLD, MOVE_SLEEP_TALK, MOVE_REST},
.itemTableId = BATTLE_FRONTIER_ITEM_CHESTO_BERRY,
.evSpread = F_EV_SPREAD_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_BOLD
},
[FRONTIER_MON_VILEPLUME_3] = {
.species = SPECIES_VILEPLUME,
.moves = {MOVE_ATTRACT, MOVE_STUN_SPORE, MOVE_SLUDGE_BOMB, MOVE_GIGA_DRAIN},
.itemTableId = BATTLE_FRONTIER_ITEM_LEFTOVERS,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_ATTACK,
.nature = NATURE_QUIRKY
},
[FRONTIER_MON_VICTREEBEL_3] = {
.species = SPECIES_VICTREEBEL,
.moves = {MOVE_STUN_SPORE, MOVE_INGRAIN, MOVE_GIGA_DRAIN, MOVE_SLUDGE_BOMB},
.itemTableId = BATTLE_FRONTIER_ITEM_BRIGHT_POWDER,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_ATTACK,
.nature = NATURE_QUIRKY
},
[FRONTIER_MON_ELECTRODE_3] = {
.species = SPECIES_ELECTRODE,
.moves = {MOVE_EXPLOSION, MOVE_THUNDERBOLT, MOVE_THUNDER_WAVE, MOVE_ENDURE},
.itemTableId = BATTLE_FRONTIER_ITEM_LIECHI_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_ATTACK,
.nature = NATURE_NAUGHTY
},
[FRONTIER_MON_HYPNO_3] = {
.species = SPECIES_HYPNO,
.moves = {MOVE_PSYCH_UP, MOVE_SWAGGER, MOVE_MEGA_KICK, MOVE_SHADOW_BALL},
.itemTableId = BATTLE_FRONTIER_ITEM_LUM_BERRY,
.evSpread = F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_GOLEM_3] = {
.species = SPECIES_GOLEM,
.moves = {MOVE_EXPLOSION, MOVE_EARTHQUAKE, MOVE_FLAMETHROWER, MOVE_BRICK_BREAK},
.itemTableId = BATTLE_FRONTIER_ITEM_QUICK_CLAW,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_ATTACK,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_RHYDON_3] = {
.species = SPECIES_RHYDON,
.moves = {MOVE_MEGAHORN, MOVE_CRUSH_CLAW, MOVE_EARTHQUAKE, MOVE_HORN_DRILL},
.itemTableId = BATTLE_FRONTIER_ITEM_QUICK_CLAW,
.evSpread = F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_ALAKAZAM_3] = {
.species = SPECIES_ALAKAZAM,
.moves = {MOVE_TRICK, MOVE_DISABLE, MOVE_PSYCHIC, MOVE_SKILL_SWAP},
.itemTableId = BATTLE_FRONTIER_ITEM_CHOICE_BAND,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_DEFENSE,
.nature = NATURE_MODEST
},
[FRONTIER_MON_WEEZING_3] = {
.species = SPECIES_WEEZING,
.moves = {MOVE_EXPLOSION, MOVE_SLUDGE_BOMB, MOVE_FLAMETHROWER, MOVE_THUNDERBOLT},
.itemTableId = BATTLE_FRONTIER_ITEM_FOCUS_BAND,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_ATTACK,
.nature = NATURE_QUIRKY
},
[FRONTIER_MON_KANGASKHAN_3] = {
.species = SPECIES_KANGASKHAN,
.moves = {MOVE_REVERSAL, MOVE_ENDURE, MOVE_THUNDERBOLT, MOVE_EARTHQUAKE},
.itemTableId = BATTLE_FRONTIER_ITEM_SALAC_BERRY,
.evSpread = F_EV_SPREAD_SPEED | F_EV_SPREAD_ATTACK,
.nature = NATURE_JOLLY
},
[FRONTIER_MON_ELECTABUZZ_3] = {
.species = SPECIES_ELECTABUZZ,
.moves = {MOVE_FIRE_PUNCH, MOVE_ICE_PUNCH, MOVE_THUNDERBOLT, MOVE_CROSS_CHOP},
.itemTableId = BATTLE_FRONTIER_ITEM_LUM_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_SPEED,
.nature = NATURE_QUIRKY
},
[FRONTIER_MON_TAUROS_3] = {
.species = SPECIES_TAUROS,
.moves = {MOVE_DOUBLE_EDGE, MOVE_EARTHQUAKE, MOVE_FLAMETHROWER, MOVE_ICE_BEAM},
.itemTableId = BATTLE_FRONTIER_ITEM_LEFTOVERS,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_ATTACK,
.nature = NATURE_DOCILE
},
[FRONTIER_MON_SLOWBRO_3] = {
.species = SPECIES_SLOWBRO,
.moves = {MOVE_SURF, MOVE_PSYCHIC, MOVE_SHADOW_BALL, MOVE_ATTRACT},
.itemTableId = BATTLE_FRONTIER_ITEM_QUICK_CLAW,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_SP_ATTACK,
.nature = NATURE_QUIET
},
[FRONTIER_MON_NIDOQUEEN_3] = {
.species = SPECIES_NIDOQUEEN,
.moves = {MOVE_THUNDERBOLT, MOVE_FLAMETHROWER, MOVE_ICE_BEAM, MOVE_CRUNCH},
.itemTableId = BATTLE_FRONTIER_ITEM_LUM_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_MODEST
},
[FRONTIER_MON_NIDOKING_3] = {
.species = SPECIES_NIDOKING,
.moves = {MOVE_HORN_DRILL, MOVE_FIRE_BLAST, MOVE_BLIZZARD, MOVE_SURF},
.itemTableId = BATTLE_FRONTIER_ITEM_LEPPA_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_MODEST
},
[FRONTIER_MON_MAGMAR_3] = {
.species = SPECIES_MAGMAR,
.moves = {MOVE_MEGA_KICK, MOVE_CROSS_CHOP, MOVE_IRON_TAIL, MOVE_COUNTER},
.itemTableId = BATTLE_FRONTIER_ITEM_SCOPE_LENS,
.evSpread = F_EV_SPREAD_DEFENSE | F_EV_SPREAD_ATTACK,
.nature = NATURE_IMPISH
},
[FRONTIER_MON_GOLDUCK_3] = {
.species = SPECIES_GOLDUCK,
.moves = {MOVE_HYDRO_PUMP, MOVE_CROSS_CHOP, MOVE_BLIZZARD, MOVE_PROTECT},
.itemTableId = BATTLE_FRONTIER_ITEM_SHELL_BELL,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_ATTACK,
.nature = NATURE_DOCILE
},
[FRONTIER_MON_RAPIDASH_3] = {
.species = SPECIES_RAPIDASH,
.moves = {MOVE_OVERHEAT, MOVE_SOLAR_BEAM, MOVE_SUNNY_DAY, MOVE_HYPNOSIS},
.itemTableId = BATTLE_FRONTIER_ITEM_WHITE_HERB,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_SPEED | F_EV_SPREAD_HP,
.nature = NATURE_MODEST
},
[FRONTIER_MON_MUK_3] = {
.species = SPECIES_MUK,
.moves = {MOVE_SLUDGE_BOMB, MOVE_THUNDERBOLT, MOVE_FLAMETHROWER, MOVE_ICE_PUNCH},
.itemTableId = BATTLE_FRONTIER_ITEM_LUM_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_DEFENSE,
.nature = NATURE_QUIET
},
[FRONTIER_MON_GENGAR_3] = {
.species = SPECIES_GENGAR,
.moves = {MOVE_PSYCHIC, MOVE_THUNDERBOLT, MOVE_GIGA_DRAIN, MOVE_SKILL_SWAP},
.itemTableId = BATTLE_FRONTIER_ITEM_QUICK_CLAW,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_SPEED,
.nature = NATURE_MODEST
},
[FRONTIER_MON_NINETALES_3] = {
.species = SPECIES_NINETALES,
.moves = {MOVE_FIRE_BLAST, MOVE_IRON_TAIL, MOVE_CONFUSE_RAY, MOVE_ATTRACT},
.itemTableId = BATTLE_FRONTIER_ITEM_BRIGHT_POWDER,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_SPEED,
.nature = NATURE_QUIRKY
},
[FRONTIER_MON_MACHAMP_3] = {
.species = SPECIES_MACHAMP,
.moves = {MOVE_CROSS_CHOP, MOVE_FIRE_BLAST, MOVE_THUNDER_PUNCH, MOVE_ICE_PUNCH},
.itemTableId = BATTLE_FRONTIER_ITEM_QUICK_CLAW,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_ATTACK,
.nature = NATURE_HARDY
},
[FRONTIER_MON_TENTACRUEL_3] = {
.species = SPECIES_TENTACRUEL,
.moves = {MOVE_SURF, MOVE_GIGA_DRAIN, MOVE_ICE_BEAM, MOVE_MIRROR_COAT},
.itemTableId = BATTLE_FRONTIER_ITEM_SHELL_BELL,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_SPEED | F_EV_SPREAD_DEFENSE,
.nature = NATURE_MODEST
},
[FRONTIER_MON_AERODACTYL_3] = {
.species = SPECIES_AERODACTYL,
.moves = {MOVE_DOUBLE_EDGE, MOVE_ROCK_SLIDE, MOVE_FIRE_BLAST, MOVE_DRAGON_CLAW},
.itemTableId = BATTLE_FRONTIER_ITEM_KINGS_ROCK,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_ATTACK,
.nature = NATURE_HARDY
},
[FRONTIER_MON_EXEGGUTOR_3] = {
.species = SPECIES_EXEGGUTOR,
.moves = {MOVE_LEECH_SEED, MOVE_GIGA_DRAIN, MOVE_TOXIC, MOVE_EXPLOSION},
.itemTableId = BATTLE_FRONTIER_ITEM_LEFTOVERS,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_HARDY
},
[FRONTIER_MON_STARMIE_3] = {
.species = SPECIES_STARMIE,
.moves = {MOVE_SURF, MOVE_PSYCHIC, MOVE_THUNDERBOLT, MOVE_ICE_BEAM},
.itemTableId = BATTLE_FRONTIER_ITEM_LUM_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_SPEED,
.nature = NATURE_MODEST
},
[FRONTIER_MON_VENUSAUR_3] = {
.species = SPECIES_VENUSAUR,
.moves = {MOVE_DOUBLE_EDGE, MOVE_SLUDGE_BOMB, MOVE_EARTHQUAKE, MOVE_SLEEP_POWDER},
.itemTableId = BATTLE_FRONTIER_ITEM_SCOPE_LENS,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_DEFENSE | F_EV_SPREAD_ATTACK,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_VAPOREON_3] = {
.species = SPECIES_VAPOREON,
.moves = {MOVE_SURF, MOVE_ICE_BEAM, MOVE_ACID_ARMOR, MOVE_BATON_PASS},
.itemTableId = BATTLE_FRONTIER_ITEM_QUICK_CLAW,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_CALM
},
[FRONTIER_MON_JOLTEON_3] = {
.species = SPECIES_JOLTEON,
.moves = {MOVE_THUNDERBOLT, MOVE_THUNDER_WAVE, MOVE_AGILITY, MOVE_BATON_PASS},
.itemTableId = BATTLE_FRONTIER_ITEM_BRIGHT_POWDER,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_BOLD
},
[FRONTIER_MON_FLAREON_3] = {
.species = SPECIES_FLAREON,
.moves = {MOVE_SHADOW_BALL, MOVE_FLAIL, MOVE_ENDURE, MOVE_OVERHEAT},
.itemTableId = BATTLE_FRONTIER_ITEM_QUICK_CLAW,
.evSpread = F_EV_SPREAD_SPEED | F_EV_SPREAD_ATTACK,
.nature = NATURE_JOLLY
},
[FRONTIER_MON_BLASTOISE_3] = {
.species = SPECIES_BLASTOISE,
.moves = {MOVE_SURF, MOVE_EARTHQUAKE, MOVE_ICE_BEAM, MOVE_COUNTER},
.itemTableId = BATTLE_FRONTIER_ITEM_FOCUS_BAND,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_DOCILE
},
[FRONTIER_MON_CHARIZARD_3] = {
.species = SPECIES_CHARIZARD,
.moves = {MOVE_FLAMETHROWER, MOVE_DRAGON_CLAW, MOVE_BITE, MOVE_BRICK_BREAK},
.itemTableId = BATTLE_FRONTIER_ITEM_LUM_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_SPEED,
.nature = NATURE_MODEST
},
[FRONTIER_MON_LAPRAS_3] = {
.species = SPECIES_LAPRAS,
.moves = {MOVE_DOUBLE_EDGE, MOVE_PSYCHIC, MOVE_CONFUSE_RAY, MOVE_DRAGON_DANCE},
.itemTableId = BATTLE_FRONTIER_ITEM_BRIGHT_POWDER,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_DOCILE
},
[FRONTIER_MON_GYARADOS_3] = {
.species = SPECIES_GYARADOS,
.moves = {MOVE_SURF, MOVE_THUNDER, MOVE_RAIN_DANCE, MOVE_EARTHQUAKE},
.itemTableId = BATTLE_FRONTIER_ITEM_QUICK_CLAW,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_ATTACK,
.nature = NATURE_QUIRKY
},
[FRONTIER_MON_SNORLAX_3] = {
.species = SPECIES_SNORLAX,
.moves = {MOVE_MEGA_KICK, MOVE_SHADOW_BALL, MOVE_SWAGGER, MOVE_PSYCH_UP},
.itemTableId = BATTLE_FRONTIER_ITEM_QUICK_CLAW,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_DEFENSE,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_ARCANINE_3] = {
.species = SPECIES_ARCANINE,
.moves = {MOVE_OVERHEAT, MOVE_EXTREME_SPEED, MOVE_CRUNCH, MOVE_AERIAL_ACE},
.itemTableId = BATTLE_FRONTIER_ITEM_WHITE_HERB,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_SPEED,
.nature = NATURE_MODEST
},
[FRONTIER_MON_DUGTRIO_4] = {
.species = SPECIES_DUGTRIO,
.moves = {MOVE_EARTHQUAKE, MOVE_DOUBLE_EDGE, MOVE_ROCK_SLIDE, MOVE_FISSURE},
.itemTableId = BATTLE_FRONTIER_ITEM_KINGS_ROCK,
.evSpread = F_EV_SPREAD_SPEED | F_EV_SPREAD_ATTACK,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_FEAROW_4] = {
.species = SPECIES_FEAROW,
.moves = {MOVE_DRILL_PECK, MOVE_DOUBLE_EDGE, MOVE_STEEL_WING, MOVE_SKY_ATTACK},
.itemTableId = BATTLE_FRONTIER_ITEM_LUM_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_ATTACK,
.nature = NATURE_HARDY
},
[FRONTIER_MON_JYNX_4] = {
.species = SPECIES_JYNX,
.moves = {MOVE_PSYCHIC, MOVE_ICE_BEAM, MOVE_LOVELY_KISS, MOVE_FAKE_TEARS},
.itemTableId = BATTLE_FRONTIER_ITEM_LUM_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_MODEST
},
[FRONTIER_MON_DODRIO_4] = {
.species = SPECIES_DODRIO,
.moves = {MOVE_FLAIL, MOVE_ENDURE, MOVE_DRILL_PECK, MOVE_FACADE},
.itemTableId = BATTLE_FRONTIER_ITEM_SALAC_BERRY,
.evSpread = F_EV_SPREAD_SPEED | F_EV_SPREAD_ATTACK,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_MR_MIME_4] = {
.species = SPECIES_MR_MIME,
.moves = {MOVE_PSYCHIC, MOVE_THUNDERBOLT, MOVE_ICE_PUNCH, MOVE_FIRE_PUNCH},
.itemTableId = BATTLE_FRONTIER_ITEM_BRIGHT_POWDER,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_MODEST
},
[FRONTIER_MON_MAROWAK_4] = {
.species = SPECIES_MAROWAK,
.moves = {MOVE_EARTHQUAKE, MOVE_ROCK_SLIDE, MOVE_SWORDS_DANCE, MOVE_MEGA_KICK},
.itemTableId = BATTLE_FRONTIER_ITEM_THICK_CLUB,
.evSpread = F_EV_SPREAD_SPEED | F_EV_SPREAD_ATTACK,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_CLEFABLE_4] = {
.species = SPECIES_CLEFABLE,
.moves = {MOVE_MEGA_KICK, MOVE_PSYCHIC, MOVE_SHADOW_BALL, MOVE_SOFT_BOILED},
.itemTableId = BATTLE_FRONTIER_ITEM_FOCUS_BAND,
.evSpread = F_EV_SPREAD_DEFENSE | F_EV_SPREAD_ATTACK,
.nature = NATURE_DOCILE
},
[FRONTIER_MON_RAICHU_4] = {
.species = SPECIES_RAICHU,
.moves = {MOVE_THUNDERBOLT, MOVE_THUNDER_WAVE, MOVE_PROTECT, MOVE_MEGA_KICK},
.itemTableId = BATTLE_FRONTIER_ITEM_BRIGHT_POWDER,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_ATTACK,
.nature = NATURE_DOCILE
},
[FRONTIER_MON_DEWGONG_4] = {
.species = SPECIES_DEWGONG,
.moves = {MOVE_SHEER_COLD, MOVE_ICE_BEAM, MOVE_SURF, MOVE_SIGNAL_BEAM},
.itemTableId = BATTLE_FRONTIER_ITEM_LUM_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_ATTACK,
.nature = NATURE_DOCILE
},
[FRONTIER_MON_VILEPLUME_4] = {
.species = SPECIES_VILEPLUME,
.moves = {MOVE_SOLAR_BEAM, MOVE_SLUDGE_BOMB, MOVE_SUNNY_DAY, MOVE_SYNTHESIS},
.itemTableId = BATTLE_FRONTIER_ITEM_QUICK_CLAW,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_ATTACK,
.nature = NATURE_QUIET
},
[FRONTIER_MON_VICTREEBEL_4] = {
.species = SPECIES_VICTREEBEL,
.moves = {MOVE_GIGA_DRAIN, MOVE_DOUBLE_EDGE, MOVE_SLUDGE_BOMB, MOVE_SYNTHESIS},
.itemTableId = BATTLE_FRONTIER_ITEM_BRIGHT_POWDER,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_ATTACK,
.nature = NATURE_QUIRKY
},
[FRONTIER_MON_ELECTRODE_4] = {
.species = SPECIES_ELECTRODE,
.moves = {MOVE_EXPLOSION, MOVE_THUNDERBOLT, MOVE_THUNDER_WAVE, MOVE_MIRROR_COAT},
.itemTableId = BATTLE_FRONTIER_ITEM_LUM_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_ATTACK,
.nature = NATURE_NAUGHTY
},
[FRONTIER_MON_HYPNO_4] = {
.species = SPECIES_HYPNO,
.moves = {MOVE_PSYCHIC, MOVE_THUNDER_PUNCH, MOVE_FIRE_PUNCH, MOVE_ICE_PUNCH},
.itemTableId = BATTLE_FRONTIER_ITEM_LUM_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_MODEST
},
[FRONTIER_MON_GOLEM_4] = {
.species = SPECIES_GOLEM,
.moves = {MOVE_EXPLOSION, MOVE_EARTHQUAKE, MOVE_ROCK_SLIDE, MOVE_DOUBLE_EDGE},
.itemTableId = BATTLE_FRONTIER_ITEM_QUICK_CLAW,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_ATTACK,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_RHYDON_4] = {
.species = SPECIES_RHYDON,
.moves = {MOVE_MEGAHORN, MOVE_EARTHQUAKE, MOVE_ROCK_SLIDE, MOVE_HORN_DRILL},
.itemTableId = BATTLE_FRONTIER_ITEM_QUICK_CLAW,
.evSpread = F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_ALAKAZAM_4] = {
.species = SPECIES_ALAKAZAM,
.moves = {MOVE_PSYCHIC, MOVE_THUNDER_PUNCH, MOVE_FIRE_PUNCH, MOVE_ICE_PUNCH},
.itemTableId = BATTLE_FRONTIER_ITEM_BRIGHT_POWDER,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_DEFENSE,
.nature = NATURE_MODEST
},
[FRONTIER_MON_WEEZING_4] = {
.species = SPECIES_WEEZING,
.moves = {MOVE_EXPLOSION, MOVE_SLUDGE_BOMB, MOVE_FRUSTRATION, MOVE_SHADOW_BALL},
.itemTableId = BATTLE_FRONTIER_ITEM_FOCUS_BAND,
.evSpread = F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_KANGASKHAN_4] = {
.species = SPECIES_KANGASKHAN,
.moves = {MOVE_MEGA_KICK, MOVE_EARTHQUAKE, MOVE_AERIAL_ACE, MOVE_SHADOW_BALL},
.itemTableId = BATTLE_FRONTIER_ITEM_BRIGHT_POWDER,
.evSpread = F_EV_SPREAD_SPEED | F_EV_SPREAD_ATTACK,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_ELECTABUZZ_4] = {
.species = SPECIES_ELECTABUZZ,
.moves = {MOVE_THUNDERBOLT, MOVE_PSYCHIC, MOVE_MEGA_KICK, MOVE_CROSS_CHOP},
.itemTableId = BATTLE_FRONTIER_ITEM_SCOPE_LENS,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_ATTACK,
.nature = NATURE_DOCILE
},
[FRONTIER_MON_TAUROS_4] = {
.species = SPECIES_TAUROS,
.moves = {MOVE_DOUBLE_EDGE, MOVE_ROCK_TOMB, MOVE_THUNDERBOLT, MOVE_SURF},
.itemTableId = BATTLE_FRONTIER_ITEM_BRIGHT_POWDER,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_ATTACK,
.nature = NATURE_DOCILE
},
[FRONTIER_MON_SLOWBRO_4] = {
.species = SPECIES_SLOWBRO,
.moves = {MOVE_PSYCHIC, MOVE_SURF, MOVE_EARTHQUAKE, MOVE_ICE_BEAM},
.itemTableId = BATTLE_FRONTIER_ITEM_QUICK_CLAW,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_SP_ATTACK,
.nature = NATURE_SASSY
},
[FRONTIER_MON_NIDOQUEEN_4] = {
.species = SPECIES_NIDOQUEEN,
.moves = {MOVE_SUPERPOWER, MOVE_SLUDGE_BOMB, MOVE_EARTHQUAKE, MOVE_SHADOW_BALL},
.itemTableId = BATTLE_FRONTIER_ITEM_WHITE_HERB,
.evSpread = F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_NIDOKING_4] = {
.species = SPECIES_NIDOKING,
.moves = {MOVE_MEGAHORN, MOVE_SLUDGE_BOMB, MOVE_EARTHQUAKE, MOVE_THUNDER},
.itemTableId = BATTLE_FRONTIER_ITEM_LUM_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_ATTACK,
.nature = NATURE_DOCILE
},
[FRONTIER_MON_MAGMAR_4] = {
.species = SPECIES_MAGMAR,
.moves = {MOVE_FLAMETHROWER, MOVE_PSYCHIC, MOVE_CROSS_CHOP, MOVE_CONFUSE_RAY},
.itemTableId = BATTLE_FRONTIER_ITEM_SCOPE_LENS,
.evSpread = F_EV_SPREAD_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_DOCILE
},
[FRONTIER_MON_GOLDUCK_4] = {
.species = SPECIES_GOLDUCK,
.moves = {MOVE_SURF, MOVE_CROSS_CHOP, MOVE_ICE_BEAM, MOVE_AERIAL_ACE},
.itemTableId = BATTLE_FRONTIER_ITEM_SCOPE_LENS,
.evSpread = F_EV_SPREAD_SPEED | F_EV_SPREAD_ATTACK,
.nature = NATURE_DOCILE
},
[FRONTIER_MON_RAPIDASH_4] = {
.species = SPECIES_RAPIDASH,
.moves = {MOVE_OVERHEAT, MOVE_DOUBLE_EDGE, MOVE_IRON_TAIL, MOVE_DOUBLE_KICK},
.itemTableId = BATTLE_FRONTIER_ITEM_WHITE_HERB,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_SPEED | F_EV_SPREAD_ATTACK,
.nature = NATURE_DOCILE
},
[FRONTIER_MON_MUK_4] = {
.species = SPECIES_MUK,
.moves = {MOVE_SLUDGE_BOMB, MOVE_BRICK_BREAK, MOVE_GIGA_DRAIN, MOVE_EXPLOSION},
.itemTableId = BATTLE_FRONTIER_ITEM_QUICK_CLAW,
.evSpread = F_EV_SPREAD_DEFENSE | F_EV_SPREAD_ATTACK,
.nature = NATURE_BRAVE
},
[FRONTIER_MON_GENGAR_4] = {
.species = SPECIES_GENGAR,
.moves = {MOVE_PSYCHIC, MOVE_FIRE_PUNCH, MOVE_ICE_PUNCH, MOVE_DESTINY_BOND},
.itemTableId = BATTLE_FRONTIER_ITEM_LUM_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_SPEED,
.nature = NATURE_MODEST
},
[FRONTIER_MON_NINETALES_4] = {
.species = SPECIES_NINETALES,
.moves = {MOVE_OVERHEAT, MOVE_DOUBLE_EDGE, MOVE_CONFUSE_RAY, MOVE_WILL_O_WISP},
.itemTableId = BATTLE_FRONTIER_ITEM_WHITE_HERB,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_SPEED,
.nature = NATURE_QUIRKY
},
[FRONTIER_MON_MACHAMP_4] = {
.species = SPECIES_MACHAMP,
.moves = {MOVE_CROSS_CHOP, MOVE_EARTHQUAKE, MOVE_FLAMETHROWER, MOVE_ROCK_SLIDE},
.itemTableId = BATTLE_FRONTIER_ITEM_SCOPE_LENS,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_ATTACK,
.nature = NATURE_HARDY
},
[FRONTIER_MON_TENTACRUEL_4] = {
.species = SPECIES_TENTACRUEL,
.moves = {MOVE_HYDRO_PUMP, MOVE_SLUDGE_BOMB, MOVE_ICE_BEAM, MOVE_MIRROR_COAT},
.itemTableId = BATTLE_FRONTIER_ITEM_SHELL_BELL,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_DEFENSE | F_EV_SPREAD_ATTACK,
.nature = NATURE_QUIRKY
},
[FRONTIER_MON_AERODACTYL_4] = {
.species = SPECIES_AERODACTYL,
.moves = {MOVE_DOUBLE_EDGE, MOVE_EARTHQUAKE, MOVE_FIRE_BLAST, MOVE_BITE},
.itemTableId = BATTLE_FRONTIER_ITEM_KINGS_ROCK,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_ATTACK,
.nature = NATURE_HARDY
},
[FRONTIER_MON_EXEGGUTOR_4] = {
.species = SPECIES_EXEGGUTOR,
.moves = {MOVE_PSYCHIC, MOVE_GIGA_DRAIN, MOVE_SLUDGE_BOMB, MOVE_EXPLOSION},
.itemTableId = BATTLE_FRONTIER_ITEM_BRIGHT_POWDER,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_ATTACK,
.nature = NATURE_HARDY
},
[FRONTIER_MON_STARMIE_4] = {
.species = SPECIES_STARMIE,
.moves = {MOVE_PSYCHIC, MOVE_THUNDERBOLT, MOVE_ICE_BEAM, MOVE_RECOVER},
.itemTableId = BATTLE_FRONTIER_ITEM_LUM_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_SPEED,
.nature = NATURE_MODEST
},
[FRONTIER_MON_VENUSAUR_4] = {
.species = SPECIES_VENUSAUR,
.moves = {MOVE_SOLAR_BEAM, MOVE_SLUDGE_BOMB, MOVE_SUNNY_DAY, MOVE_EARTHQUAKE},
.itemTableId = BATTLE_FRONTIER_ITEM_LUM_BERRY,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_ATTACK,
.nature = NATURE_DOCILE
},
[FRONTIER_MON_VAPOREON_4] = {
.species = SPECIES_VAPOREON,
.moves = {MOVE_SURF, MOVE_ICE_BEAM, MOVE_ACID_ARMOR, MOVE_REST},
.itemTableId = BATTLE_FRONTIER_ITEM_LUM_BERRY,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_CALM
},
[FRONTIER_MON_JOLTEON_4] = {
.species = SPECIES_JOLTEON,
.moves = {MOVE_THUNDERBOLT, MOVE_THUNDER_WAVE, MOVE_BITE, MOVE_SHADOW_BALL},
.itemTableId = BATTLE_FRONTIER_ITEM_KINGS_ROCK,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_SPEED,
.nature = NATURE_TIMID
},
[FRONTIER_MON_FLAREON_4] = {
.species = SPECIES_FLAREON,
.moves = {MOVE_OVERHEAT, MOVE_SUNNY_DAY, MOVE_DOUBLE_EDGE, MOVE_SHADOW_BALL},
.itemTableId = BATTLE_FRONTIER_ITEM_QUICK_CLAW,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_ATTACK,
.nature = NATURE_QUIET
},
[FRONTIER_MON_BLASTOISE_4] = {
.species = SPECIES_BLASTOISE,
.moves = {MOVE_SURF, MOVE_EARTHQUAKE, MOVE_ICE_BEAM, MOVE_MIRROR_COAT},
.itemTableId = BATTLE_FRONTIER_ITEM_FOCUS_BAND,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_DOCILE
},
[FRONTIER_MON_CHARIZARD_4] = {
.species = SPECIES_CHARIZARD,
.moves = {MOVE_OVERHEAT, MOVE_EARTHQUAKE, MOVE_AERIAL_ACE, MOVE_ROCK_SLIDE},
.itemTableId = BATTLE_FRONTIER_ITEM_WHITE_HERB,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_SPEED | F_EV_SPREAD_ATTACK,
.nature = NATURE_HARDY
},
[FRONTIER_MON_LAPRAS_4] = {
.species = SPECIES_LAPRAS,
.moves = {MOVE_SURF, MOVE_ICE_BEAM, MOVE_THUNDERBOLT, MOVE_PSYCHIC},
.itemTableId = BATTLE_FRONTIER_ITEM_LUM_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_MODEST
},
[FRONTIER_MON_GYARADOS_4] = {
.species = SPECIES_GYARADOS,
.moves = {MOVE_RETURN, MOVE_EARTHQUAKE, MOVE_DRAGON_DANCE, MOVE_REST},
.itemTableId = BATTLE_FRONTIER_ITEM_CHESTO_BERRY,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_SNORLAX_4] = {
.species = SPECIES_SNORLAX,
.moves = {MOVE_DOUBLE_EDGE, MOVE_SHADOW_BALL, MOVE_BRICK_BREAK, MOVE_CURSE},
.itemTableId = BATTLE_FRONTIER_ITEM_QUICK_CLAW,
.evSpread = F_EV_SPREAD_DEFENSE | F_EV_SPREAD_ATTACK,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_ARCANINE_4] = {
.species = SPECIES_ARCANINE,
.moves = {MOVE_OVERHEAT, MOVE_EXTREME_SPEED, MOVE_CRUNCH, MOVE_DOUBLE_EDGE},
.itemTableId = BATTLE_FRONTIER_ITEM_WHITE_HERB,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_SPEED,
.nature = NATURE_DOCILE
},
[FRONTIER_MON_ARTICUNO_1] = {
.species = SPECIES_ARTICUNO,
.moves = {MOVE_ICE_BEAM, MOVE_WATER_PULSE, MOVE_ICY_WIND, MOVE_ROAR},
.itemTableId = BATTLE_FRONTIER_ITEM_LUM_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_SPEED,
.nature = NATURE_MODEST
},
[FRONTIER_MON_ZAPDOS_1] = {
.species = SPECIES_ZAPDOS,
.moves = {MOVE_THUNDERBOLT, MOVE_DRILL_PECK, MOVE_THUNDER_WAVE, MOVE_ROAR},
.itemTableId = BATTLE_FRONTIER_ITEM_LUM_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_SPEED,
.nature = NATURE_DOCILE
},
[FRONTIER_MON_MOLTRES_1] = {
.species = SPECIES_MOLTRES,
.moves = {MOVE_FLAMETHROWER, MOVE_AERIAL_ACE, MOVE_MUD_SLAP, MOVE_ROAR},
.itemTableId = BATTLE_FRONTIER_ITEM_LUM_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_ATTACK,
.nature = NATURE_DOCILE
},
[FRONTIER_MON_ARTICUNO_2] = {
.species = SPECIES_ARTICUNO,
.moves = {MOVE_SUBSTITUTE, MOVE_TOXIC, MOVE_BLIZZARD, MOVE_DOUBLE_TEAM},
.itemTableId = BATTLE_FRONTIER_ITEM_LEFTOVERS,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_IMPISH
},
[FRONTIER_MON_ZAPDOS_2] = {
.species = SPECIES_ZAPDOS,
.moves = {MOVE_THUNDER, MOVE_RAIN_DANCE, MOVE_DRILL_PECK, MOVE_DOUBLE_TEAM},
.itemTableId = BATTLE_FRONTIER_ITEM_BRIGHT_POWDER,
.evSpread = F_EV_SPREAD_SPEED | F_EV_SPREAD_ATTACK,
.nature = NATURE_DOCILE
},
[FRONTIER_MON_MOLTRES_2] = {
.species = SPECIES_MOLTRES,
.moves = {MOVE_OVERHEAT, MOVE_AERIAL_ACE, MOVE_DOUBLE_TEAM, MOVE_PROTECT},
.itemTableId = BATTLE_FRONTIER_ITEM_WHITE_HERB,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_ATTACK,
.nature = NATURE_HARDY
},
[FRONTIER_MON_ARTICUNO_3] = {
.species = SPECIES_ARTICUNO,
.moves = {MOVE_ICE_BEAM, MOVE_FACADE, MOVE_AERIAL_ACE, MOVE_PROTECT},
.itemTableId = BATTLE_FRONTIER_ITEM_BRIGHT_POWDER,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_ATTACK,
.nature = NATURE_DOCILE
},
[FRONTIER_MON_ZAPDOS_3] = {
.species = SPECIES_ZAPDOS,
.moves = {MOVE_THUNDERBOLT, MOVE_DRILL_PECK, MOVE_THUNDER_WAVE, MOVE_SUBSTITUTE},
.itemTableId = BATTLE_FRONTIER_ITEM_LEFTOVERS,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_SPEED | F_EV_SPREAD_ATTACK,
.nature = NATURE_DOCILE
},
[FRONTIER_MON_MOLTRES_3] = {
.species = SPECIES_MOLTRES,
.moves = {MOVE_FIRE_BLAST, MOVE_SUNNY_DAY, MOVE_DOUBLE_TEAM, MOVE_REST},
.itemTableId = BATTLE_FRONTIER_ITEM_CHESTO_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_SPEED,
.nature = NATURE_MODEST
},
[FRONTIER_MON_ARTICUNO_4] = {
.species = SPECIES_ARTICUNO,
.moves = {MOVE_BLIZZARD, MOVE_DOUBLE_EDGE, MOVE_REST, MOVE_REFLECT},
.itemTableId = BATTLE_FRONTIER_ITEM_CHESTO_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_ATTACK,
.nature = NATURE_DOCILE
},
[FRONTIER_MON_ZAPDOS_4] = {
.species = SPECIES_ZAPDOS,
.moves = {MOVE_THUNDERBOLT, MOVE_DRILL_PECK, MOVE_THUNDER_WAVE, MOVE_LIGHT_SCREEN},
.itemTableId = BATTLE_FRONTIER_ITEM_SHELL_BELL,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_ATTACK,
.nature = NATURE_DOCILE
},
[FRONTIER_MON_MOLTRES_4] = {
.species = SPECIES_MOLTRES,
.moves = {MOVE_OVERHEAT, MOVE_DOUBLE_EDGE, MOVE_STEEL_WING, MOVE_SAFEGUARD},
.itemTableId = BATTLE_FRONTIER_ITEM_WHITE_HERB,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_ATTACK,
.nature = NATURE_QUIET
},
[FRONTIER_MON_GENGAR_5] = {
.species = SPECIES_GENGAR,
.moves = {MOVE_PSYCHIC, MOVE_SHADOW_BALL, MOVE_THUNDERBOLT, MOVE_FIRE_PUNCH},
.itemTableId = BATTLE_FRONTIER_ITEM_BRIGHT_POWDER,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_SPEED,
.nature = NATURE_MODEST
},
[FRONTIER_MON_GENGAR_6] = {
.species = SPECIES_GENGAR,
.moves = {MOVE_PSYCHIC, MOVE_SHADOW_BALL, MOVE_THUNDERBOLT, MOVE_ICE_PUNCH},
.itemTableId = BATTLE_FRONTIER_ITEM_BRIGHT_POWDER,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_SPEED,
.nature = NATURE_MODEST
},
[FRONTIER_MON_GENGAR_7] = {
.species = SPECIES_GENGAR,
.moves = {MOVE_PSYCHIC, MOVE_THUNDERBOLT, MOVE_FIRE_PUNCH, MOVE_DESTINY_BOND},
.itemTableId = BATTLE_FRONTIER_ITEM_LUM_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_SPEED,
.nature = NATURE_MODEST
},
[FRONTIER_MON_GENGAR_8] = {
.species = SPECIES_GENGAR,
.moves = {MOVE_PSYCHIC, MOVE_THUNDERBOLT, MOVE_ICE_PUNCH, MOVE_DESTINY_BOND},
.itemTableId = BATTLE_FRONTIER_ITEM_LUM_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_SPEED,
.nature = NATURE_MODEST
},
[FRONTIER_MON_MACHAMP_5] = {
.species = SPECIES_MACHAMP,
.moves = {MOVE_CROSS_CHOP, MOVE_DOUBLE_EDGE, MOVE_EARTHQUAKE, MOVE_ROCK_SLIDE},
.itemTableId = BATTLE_FRONTIER_ITEM_SCOPE_LENS,
.evSpread = F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_MACHAMP_6] = {
.species = SPECIES_MACHAMP,
.moves = {MOVE_CROSS_CHOP, MOVE_EARTHQUAKE, MOVE_COUNTER, MOVE_ROCK_TOMB},
.itemTableId = BATTLE_FRONTIER_ITEM_FOCUS_BAND,
.evSpread = F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_MACHAMP_7] = {
.species = SPECIES_MACHAMP,
.moves = {MOVE_FOCUS_PUNCH, MOVE_SUBSTITUTE, MOVE_ATTRACT, MOVE_DOUBLE_TEAM},
.itemTableId = BATTLE_FRONTIER_ITEM_BRIGHT_POWDER,
.evSpread = F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_MACHAMP_8] = {
.species = SPECIES_MACHAMP,
.moves = {MOVE_REVENGE, MOVE_ROCK_SLIDE, MOVE_FACADE, MOVE_COUNTER},
.itemTableId = BATTLE_FRONTIER_ITEM_FOCUS_BAND,
.evSpread = F_EV_SPREAD_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_STARMIE_5] = {
.species = SPECIES_STARMIE,
.moves = {MOVE_SURF, MOVE_PSYCHIC, MOVE_RECOVER, MOVE_LIGHT_SCREEN},
.itemTableId = BATTLE_FRONTIER_ITEM_LUM_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_SPEED,
.nature = NATURE_MODEST
},
[FRONTIER_MON_STARMIE_6] = {
.species = SPECIES_STARMIE,
.moves = {MOVE_SURF, MOVE_CONFUSE_RAY, MOVE_THUNDER_WAVE, MOVE_RECOVER},
.itemTableId = BATTLE_FRONTIER_ITEM_LEFTOVERS,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_CALM
},
[FRONTIER_MON_STARMIE_7] = {
.species = SPECIES_STARMIE,
.moves = {MOVE_PSYCHIC, MOVE_ICE_BEAM, MOVE_COSMIC_POWER, MOVE_RECOVER},
.itemTableId = BATTLE_FRONTIER_ITEM_BRIGHT_POWDER,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_SPEED,
.nature = NATURE_MODEST
},
[FRONTIER_MON_STARMIE_8] = {
.species = SPECIES_STARMIE,
.moves = {MOVE_SURF, MOVE_THUNDERBOLT, MOVE_COSMIC_POWER, MOVE_RECOVER},
.itemTableId = BATTLE_FRONTIER_ITEM_BRIGHT_POWDER,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_SPEED,
.nature = NATURE_MODEST
},
[FRONTIER_MON_LAPRAS_5] = {
.species = SPECIES_LAPRAS,
.moves = {MOVE_PSYCHIC, MOVE_THUNDERBOLT, MOVE_IRON_TAIL, MOVE_DOUBLE_EDGE},
.itemTableId = BATTLE_FRONTIER_ITEM_SHELL_BELL,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_ATTACK,
.nature = NATURE_DOCILE
},
[FRONTIER_MON_LAPRAS_6] = {
.species = SPECIES_LAPRAS,
.moves = {MOVE_HYDRO_PUMP, MOVE_THUNDER, MOVE_RAIN_DANCE, MOVE_BLIZZARD},
.itemTableId = BATTLE_FRONTIER_ITEM_BRIGHT_POWDER,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_MODEST
},
[FRONTIER_MON_LAPRAS_7] = {
.species = SPECIES_LAPRAS,
.moves = {MOVE_SHEER_COLD, MOVE_HORN_DRILL, MOVE_REST, MOVE_SLEEP_TALK},
.itemTableId = BATTLE_FRONTIER_ITEM_LEPPA_BERRY,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_CALM
},
[FRONTIER_MON_LAPRAS_8] = {
.species = SPECIES_LAPRAS,
.moves = {MOVE_SHEER_COLD, MOVE_HORN_DRILL, MOVE_SING, MOVE_ATTRACT},
.itemTableId = BATTLE_FRONTIER_ITEM_QUICK_CLAW,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_CALM
},
[FRONTIER_MON_SNORLAX_5] = {
.species = SPECIES_SNORLAX,
.moves = {MOVE_MEGA_KICK, MOVE_SHADOW_BALL, MOVE_BRICK_BREAK, MOVE_COUNTER},
.itemTableId = BATTLE_FRONTIER_ITEM_QUICK_CLAW,
.evSpread = F_EV_SPREAD_DEFENSE | F_EV_SPREAD_ATTACK,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_SNORLAX_6] = {
.species = SPECIES_SNORLAX,
.moves = {MOVE_EARTHQUAKE, MOVE_SHADOW_BALL, MOVE_BRICK_BREAK, MOVE_COUNTER},
.itemTableId = BATTLE_FRONTIER_ITEM_LEFTOVERS,
.evSpread = F_EV_SPREAD_DEFENSE | F_EV_SPREAD_ATTACK,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_SNORLAX_7] = {
.species = SPECIES_SNORLAX,
.moves = {MOVE_HYPER_BEAM, MOVE_SHADOW_BALL, MOVE_EARTHQUAKE, MOVE_CURSE},
.itemTableId = BATTLE_FRONTIER_ITEM_QUICK_CLAW,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_SNORLAX_8] = {
.species = SPECIES_SNORLAX,
.moves = {MOVE_RETURN, MOVE_SHADOW_BALL, MOVE_BELLY_DRUM, MOVE_REST},
.itemTableId = BATTLE_FRONTIER_ITEM_CHESTO_BERRY,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_DRAGONITE_1] = {
.species = SPECIES_DRAGONITE,
.moves = {MOVE_EARTHQUAKE, MOVE_AERIAL_ACE, MOVE_BRICK_BREAK, MOVE_DRAGON_DANCE},
.itemTableId = BATTLE_FRONTIER_ITEM_BRIGHT_POWDER,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_DRAGONITE_2] = {
.species = SPECIES_DRAGONITE,
.moves = {MOVE_EARTHQUAKE, MOVE_DOUBLE_EDGE, MOVE_AERIAL_ACE, MOVE_DRAGON_DANCE},
.itemTableId = BATTLE_FRONTIER_ITEM_BRIGHT_POWDER,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_DRAGONITE_3] = {
.species = SPECIES_DRAGONITE,
.moves = {MOVE_HYPER_BEAM, MOVE_ATTRACT, MOVE_DOUBLE_TEAM, MOVE_THUNDER_WAVE},
.itemTableId = BATTLE_FRONTIER_ITEM_LEFTOVERS,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_DEFENSE | F_EV_SPREAD_ATTACK,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_DRAGONITE_4] = {
.species = SPECIES_DRAGONITE,
.moves = {MOVE_HYPER_BEAM, MOVE_THUNDER_WAVE, MOVE_DRAGON_DANCE, MOVE_REST},
.itemTableId = BATTLE_FRONTIER_ITEM_CHESTO_BERRY,
.evSpread = F_EV_SPREAD_SP_DEFENSE | F_EV_SPREAD_DEFENSE | F_EV_SPREAD_HP,
.nature = NATURE_ADAMANT
},
[FRONTIER_MON_DRAGONITE_5] = {
.species = SPECIES_DRAGONITE,
.moves = {MOVE_OUTRAGE, MOVE_DOUBLE_EDGE, MOVE_THUNDER_WAVE, MOVE_ROAR},
.itemTableId = BATTLE_FRONTIER_ITEM_LUM_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_ATTACK,
.nature = NATURE_DOCILE
},
[FRONTIER_MON_DRAGONITE_6] = {
.species = SPECIES_DRAGONITE,
.moves = {MOVE_DRAGON_CLAW, MOVE_THUNDERBOLT, MOVE_SURF, MOVE_FLAMETHROWER},
.itemTableId = BATTLE_FRONTIER_ITEM_SHELL_BELL,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_SPEED,
.nature = NATURE_MODEST
},
[FRONTIER_MON_DRAGONITE_7] = {
.species = SPECIES_DRAGONITE,
.moves = {MOVE_DRAGON_CLAW, MOVE_THUNDERBOLT, MOVE_SURF, MOVE_ICE_BEAM},
.itemTableId = BATTLE_FRONTIER_ITEM_SHELL_BELL,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_SPEED,
.nature = NATURE_MODEST
},
[FRONTIER_MON_DRAGONITE_8] = {
.species = SPECIES_DRAGONITE,
.moves = {MOVE_DRAGON_CLAW, MOVE_FLAMETHROWER, MOVE_ICE_BEAM, MOVE_BRICK_BREAK},
.itemTableId = BATTLE_FRONTIER_ITEM_SHELL_BELL,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_SPEED,
.nature = NATURE_MODEST
},
[FRONTIER_MON_DRAGONITE_9] = {
.species = SPECIES_DRAGONITE,
.moves = {MOVE_THUNDER, MOVE_SURF, MOVE_RAIN_DANCE, MOVE_EARTHQUAKE},
.itemTableId = BATTLE_FRONTIER_ITEM_QUICK_CLAW,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_DOCILE
},
[FRONTIER_MON_DRAGONITE_10] = {
.species = SPECIES_DRAGONITE,
.moves = {MOVE_FIRE_BLAST, MOVE_BLIZZARD, MOVE_SUNNY_DAY, MOVE_EARTHQUAKE},
.itemTableId = BATTLE_FRONTIER_ITEM_QUICK_CLAW,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_HP,
.nature = NATURE_DOCILE
},
[FRONTIER_MON_ARTICUNO_5] = {
.species = SPECIES_ARTICUNO,
.moves = {MOVE_BLIZZARD, MOVE_DOUBLE_EDGE, MOVE_AGILITY, MOVE_SWAGGER},
.itemTableId = BATTLE_FRONTIER_ITEM_FOCUS_BAND,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_ATTACK,
.nature = NATURE_DOCILE
},
[FRONTIER_MON_ARTICUNO_6] = {
.species = SPECIES_ARTICUNO,
.moves = {MOVE_ICE_BEAM, MOVE_AERIAL_ACE, MOVE_REFLECT, MOVE_REST},
.itemTableId = BATTLE_FRONTIER_ITEM_CHESTO_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_ATTACK,
.nature = NATURE_DOCILE
},
[FRONTIER_MON_ZAPDOS_5] = {
.species = SPECIES_ZAPDOS,
.moves = {MOVE_THUNDERBOLT, MOVE_DRILL_PECK, MOVE_DOUBLE_EDGE, MOVE_THUNDER_WAVE},
.itemTableId = BATTLE_FRONTIER_ITEM_SCOPE_LENS,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_ATTACK,
.nature = NATURE_DOCILE
},
[FRONTIER_MON_ZAPDOS_6] = {
.species = SPECIES_ZAPDOS,
.moves = {MOVE_THUNDER, MOVE_DRILL_PECK, MOVE_RAIN_DANCE, MOVE_DOUBLE_EDGE},
.itemTableId = BATTLE_FRONTIER_ITEM_LUM_BERRY,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_SPEED | F_EV_SPREAD_ATTACK,
.nature = NATURE_DOCILE
},
[FRONTIER_MON_MOLTRES_5] = {
.species = SPECIES_MOLTRES,
.moves = {MOVE_OVERHEAT, MOVE_SUNNY_DAY, MOVE_SWAGGER, MOVE_FACADE},
.itemTableId = BATTLE_FRONTIER_ITEM_WHITE_HERB,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_SPEED,
.nature = NATURE_DOCILE
},
[FRONTIER_MON_MOLTRES_6] = {
.species = SPECIES_MOLTRES,
.moves = {MOVE_OVERHEAT, MOVE_DOUBLE_EDGE, MOVE_AERIAL_ACE, MOVE_STEEL_WING},
.itemTableId = BATTLE_FRONTIER_ITEM_WHITE_HERB,
.evSpread = F_EV_SPREAD_SP_ATTACK | F_EV_SPREAD_ATTACK,
.nature = NATURE_DOCILE
}
};
| 412 | 0.887204 | 1 | 0.887204 | game-dev | MEDIA | 0.906047 | game-dev | 0.518227 | 1 | 0.518227 |
MergHQ/CRYENGINE | 1,210 | Code/CryEngine/CryAction/Network/VoiceController.cpp | // Copyright 2001-2016 Crytek GmbH / Crytek Group. All rights reserved.
#include "StdAfx.h"
#include "VoiceController.h"
#include "GameClientChannel.h"
#include "GameContext.h"
#ifndef OLD_VOICE_SYSTEM_DEPRECATED
CVoiceController::CVoiceController(CGameContext* pGameContext)
{
m_pNetContext = pGameContext->GetNetContext();
m_pMicrophone = NULL;
m_enabled = false;
m_recording = false;
if (!pGameContext->HasContextFlag(eGSF_LocalOnly))
{
m_pMicrophone = gEnv->pAudioSystem->CreateMicrophone(0, 0, 0, 0);
if (m_pMicrophone)
m_recording = m_pMicrophone->Record(0, 16, 8000, 16000);
}
else
m_pMicrophone = 0;
}
CVoiceController::~CVoiceController()
{
if (m_pMicrophone)
m_pMicrophone->Stop();
SAFE_RELEASE(m_pMicrophone);
}
void CVoiceController::Enable(const bool e)
{
if (e != m_enabled)
{
if (m_enabled && m_recording)
m_DataReader.m_pMicrophone = 0;
if (e)
m_DataReader.m_pMicrophone = m_pMicrophone;
m_enabled = e;
}
}
bool CVoiceController::Init()
{
return true;
}
void CVoiceController::PlayerIdSet(EntityId id)
{
if (m_pNetContext && m_pNetContext->GetVoiceContext())
m_pNetContext->GetVoiceContext()->SetVoiceDataReader(id, &m_DataReader);
}
#endif
| 412 | 0.949255 | 1 | 0.949255 | game-dev | MEDIA | 0.725096 | game-dev | 0.785073 | 1 | 0.785073 |
Hubs-Foundation/hubs | 8,036 | src/components/player-info.js | import { injectCustomShaderChunks } from "../utils/media-utils";
import { AVATAR_TYPES } from "../utils/avatar-utils";
import { registerComponentInstance, deregisterComponentInstance } from "../utils/component-utils";
import defaultAvatar from "../assets/models/DefaultAvatar.glb";
import { MediaDevicesEvents } from "../utils/media-devices-utils";
import { createHeadlessModelForSkinnedMesh } from "../utils/three-utils";
import { Layers } from "../camera-layers";
import { addComponent, removeComponent } from "bitecs";
import { LocalAvatar, RemoteAvatar } from "../bit-components";
function ensureAvatarNodes(json) {
const { nodes } = json;
if (!nodes.some(node => node.name === "Head")) {
// If the avatar model doesn't have a Head node. The user has probably chosen a custom GLB.
// So, we need to construct a suitable hierarchy for avatar functionality to work.
// We re-parent the original root node to the Head node and set the scene root to a new AvatarRoot.
// Note: We assume that the first node in the primary scene is the one we care about.
const originalRoot = json.scenes[json.scene].nodes[0];
nodes.push({ name: "LeftEye", extensions: { MOZ_hubs_components: {} } });
nodes.push({ name: "RightEye", extensions: { MOZ_hubs_components: {} } });
nodes.push({
name: "Head",
children: [originalRoot, nodes.length - 1, nodes.length - 2],
extensions: { MOZ_hubs_components: { "scale-audio-feedback": "" } }
});
nodes.push({ name: "Neck", children: [nodes.length - 1] });
nodes.push({ name: "Spine", children: [nodes.length - 1] });
nodes.push({ name: "Hips", children: [nodes.length - 1] });
nodes.push({ name: "AvatarRoot", children: [nodes.length - 1] });
json.scenes[json.scene].nodes[0] = nodes.length - 1;
}
return json;
}
AFRAME.registerComponent("player-info", {
schema: {
avatarSrc: { type: "string" },
avatarType: { type: "string", default: AVATAR_TYPES.SKINNABLE },
muted: { default: false },
isSharingAvatarCamera: { default: false }
},
init() {
this.applyProperties = this.applyProperties.bind(this);
this.handleModelError = this.handleModelError.bind(this);
this.handleRemoteModelError = this.handleRemoteModelError.bind(this);
this.update = this.update.bind(this);
this.onPresenceUpdated = this.onPresenceUpdated.bind(this);
this.onMicStateChanged = this.onMicStateChanged.bind(this);
this.onAvatarModelLoaded = this.onAvatarModelLoaded.bind(this);
this.isLocalPlayerInfo = this.el.id === "avatar-rig";
this.playerSessionId = null;
this.displayName = null;
if (!this.isLocalPlayerInfo) {
NAF.utils.getNetworkedEntity(this.el).then(networkedEntity => {
this.playerSessionId = NAF.utils.getCreator(networkedEntity);
const playerPresence = window.APP.hubChannel.presence.state[this.playerSessionId];
if (playerPresence) {
this.permissions = playerPresence.metas[0].permissions;
this.displayName = playerPresence.metas[0].profile.displayName;
}
});
}
registerComponentInstance(this, "player-info");
addComponent(APP.world, this.isLocalPlayerInfo ? LocalAvatar : RemoteAvatar, this.el.object3D.eid);
},
remove() {
const avatarEl = this.el.querySelector("[avatar-audio-source]");
APP.isAudioPaused.delete(avatarEl);
deregisterComponentInstance(this, "player-info");
removeComponent(APP.world, this.isLocalPlayerInfo ? LocalAvatar : RemoteAvatar, this.el.object3D.eid);
},
onAvatarModelLoaded(e) {
this.applyProperties(e);
const modelEl = this.el.querySelector(".model");
if (this.isLocalPlayerInfo && e.target === modelEl) {
let isSkinnedAvatar = false;
modelEl.object3D.traverse(function (o) {
if (o.isSkinnedMesh) {
const headlessMesh = createHeadlessModelForSkinnedMesh(o);
if (headlessMesh) {
isSkinnedAvatar = true;
o.parent.add(headlessMesh);
}
}
});
// This is to support using arbitrary models as avatars.
// TODO We can drop support for this when we go full VRM, or at least handle it earlier in the process.
if (!isSkinnedAvatar) {
modelEl.object3D.traverse(function (o) {
if (o.isMesh) o.layers.set(Layers.CAMERA_LAYER_THIRD_PERSON_ONLY);
});
}
}
},
play() {
this.el.addEventListener("model-loaded", this.onAvatarModelLoaded);
this.el.sceneEl.addEventListener("presence_updated", this.onPresenceUpdated);
if (this.isLocalPlayerInfo) {
this.el.querySelector(".model").addEventListener("model-error", this.handleModelError);
} else {
this.el.querySelector(".model").addEventListener("model-error", this.handleRemoteModelError);
}
window.APP.store.addEventListener("statechanged", this.update);
this.el.sceneEl.addEventListener("stateadded", this.update);
this.el.sceneEl.addEventListener("stateremoved", this.update);
if (this.isLocalPlayerInfo) {
APP.dialog.on("mic-state-changed", this.onMicStateChanged);
}
},
pause() {
this.el.removeEventListener("model-loaded", this.onAvatarModelLoaded);
this.el.sceneEl.removeEventListener("presence_updated", this.onPresenceUpdated);
if (this.isLocalPlayerInfo) {
this.el.querySelector(".model").removeEventListener("model-error", this.handleModelError);
} else {
this.el.querySelector(".model").removeEventListener("model-error", this.handleRemoteModelError);
}
this.el.sceneEl.removeEventListener("stateadded", this.update);
this.el.sceneEl.removeEventListener("stateremoved", this.update);
window.APP.store.removeEventListener("statechanged", this.update);
if (this.isLocalPlayerInfo) {
APP.dialog.off("mic-state-changed", this.onMicStateChanged);
}
},
onPresenceUpdated(e) {
this.updateFromPresenceMeta(e.detail);
},
updateFromPresenceMeta(presenceMeta) {
if (!this.playerSessionId && this.isLocalPlayerInfo) {
this.playerSessionId = NAF.clientId;
}
if (!this.playerSessionId || this.playerSessionId !== presenceMeta.sessionId) return;
this.permissions = presenceMeta.permissions;
},
update(oldData) {
if (this.data.muted !== oldData.muted) {
this.el.emit("remote_mute_updated", { muted: this.data.muted });
}
this.applyProperties();
},
can(perm) {
return !!this.permissions && this.permissions[perm];
},
applyProperties(e) {
const modelEl = this.el.querySelector(".model");
if (this.data.avatarSrc && modelEl) {
modelEl.components["gltf-model-plus"].jsonPreprocessor = ensureAvatarNodes;
modelEl.setAttribute("gltf-model-plus", "src", this.data.avatarSrc);
}
if (!e || e.target === modelEl) {
const uniforms = injectCustomShaderChunks(this.el.object3D);
this.el.querySelectorAll("[hover-visuals]").forEach(el => {
el.components["hover-visuals"].uniforms = uniforms;
});
}
const videoTextureTargets = modelEl.querySelectorAll("[video-texture-target]");
const sessionId = this.isLocalPlayerInfo ? NAF.clientId : this.playerSessionId;
for (const el of Array.from(videoTextureTargets)) {
el.setAttribute("video-texture-target", {
src: this.data.isSharingAvatarCamera ? `hubs://clients/${sessionId}/video` : ""
});
if (this.isLocalPlayerInfo) {
el.setAttribute("emit-scene-event-on-remove", `event:${MediaDevicesEvents.VIDEO_SHARE_ENDED}`);
}
}
const avatarEl = this.el.querySelector("[avatar-audio-source]");
if (this.data.muted) {
APP.isAudioPaused.add(avatarEl);
} else {
APP.isAudioPaused.delete(avatarEl);
}
},
handleModelError() {
window.APP.store.resetToRandomDefaultAvatar();
},
handleRemoteModelError() {
this.data.avatarSrc = defaultAvatar;
this.applyProperties();
},
onMicStateChanged({ enabled }) {
this.el.setAttribute("player-info", { muted: !enabled });
}
});
| 412 | 0.955428 | 1 | 0.955428 | game-dev | MEDIA | 0.853934 | game-dev | 0.982818 | 1 | 0.982818 |
TheAllenChou/unity-ray-marching | 5,734 | unity-ray-marching/Assets/Shader/Ray Marching/Resources/AabbTree.cginc | /******************************************************************************/
/*
Project - Unity Ray Marching
https://github.com/TheAllenChou/unity-ray-marching
Author - Ming-Lun "Allen" Chou
Web - http://AllenChou.net
Twitter - @TheAllenChou
*/
/******************************************************************************/
#ifndef RAY_MARCHING_AABB_TREE
#define RAY_MARCHING_AABB_TREE
struct Aabb
{
float4 boundsMin;
float4 boundsMax;
};
struct AabbNode
{
Aabb aabb;
int parent;
int childA;
int childB;
int shapeIndex;
};
inline float3 aabb_center(Aabb aabb)
{
return 0.5f * (aabb.boundsMin.xyz + aabb.boundsMax.xyz);
}
inline float3 aabb_extents(Aabb aabb)
{
return aabb.boundsMax.xyz - aabb.boundsMin.xyz;
}
inline float3 aabb_half_extents(Aabb aabb)
{
return 0.5f * (aabb.boundsMax.xyz - aabb.boundsMin.xyz);
}
inline bool aabb_intersects(Aabb a, Aabb b)
{
return all(a.boundsMin <= b.boundsMax && a.boundsMax >= b.boundsMin);
}
float aabb_ray_cast(Aabb aabb, float3 from, float3 to)
{
float tMin = -kFltMax;
float tMax = +kFltMax;
float3 d = to - from;
float3 absD = abs(d);
if (any(absD < kEpsilon))
{
// parallel?
if (any(from < aabb.boundsMin.xyz) || any(aabb.boundsMax.xyz < from))
return -kFltMax;
}
else
{
float3 invD = 1.0f / d;
float3 t1 = (aabb.boundsMin.xyz - from) * invD;
float3 t2 = (aabb.boundsMax.xyz - from) * invD;
float3 minComps = min(t1, t2);
float3 maxComps = max(t1, t2);
tMin = max(minComps.x, max(minComps.y, minComps.z));
tMax = min(maxComps.x, min(maxComps.y, maxComps.z));
}
if (tMin > tMax)
return -kFltMax;
if (tMin < 0.0f)
return -kFltMax;
return tMin;
}
// stmt = statements processing shapeIndex of hit leaf AABB nodes
#define aabb_tree_ray_cast(tree, root, rayFrom, rayTo, stackSize, stmt) \
{ \
float3 rayDir = normalize(rayTo - rayFrom); \
float3 rayDirOrtho = normalize(find_ortho(rayDir)); \
float3 rayDirOrthoAbs = abs(rayDirOrtho); \
\
Aabb rayBounds; \
rayBounds.boundsMin = float4(min(rayFrom, rayTo), 0.0f); \
rayBounds.boundsMax = float4(max(rayFrom, rayTo), 0.0f); \
\
int stackTop = 0; \
int stack[stackSize]; \
stack[stackTop] = root; \
\
while (stackTop >= 0) \
{ \
int index = stack[stackTop--]; \
if (index < 0) \
continue; \
\
if (!aabb_intersects(tree[index].aabb, rayBounds)) \
continue; \
\
float3 aabbCenter = aabb_center(tree[index].aabb); \
float3 aabbHalfExtents = aabb_half_extents(tree[index].aabb); \
float separation = \
abs(dot(rayDirOrtho, rayFrom - aabbCenter)) \
- dot(rayDirOrthoAbs, aabbHalfExtents); \
if (separation > 0.0f) \
continue; \
\
if (tree[index].childA < 0) \
{ \
float t = aabb_ray_cast(tree[index].aabb, rayFrom, rayTo); \
if (t < 0.0f) \
continue; \
\
const int shapeIndex = tree[index].shapeIndex; \
\
stmt \
} \
else \
{ \
stackTop = min(stackTop + 1, stackSize - 1); \
stack[stackTop] = tree[index].childA; \
stackTop = min(stackTop + 1, stackSize - 1); \
stack[stackTop] = tree[index].childB; \
} \
} \
}
#endif
| 412 | 0.957791 | 1 | 0.957791 | game-dev | MEDIA | 0.499291 | game-dev | 0.999002 | 1 | 0.999002 |
momentumdevelopment/momentum | 5,206 | src/main/java/me/linus/momentum/module/modules/player/SpeedMine.java | package me.linus.momentum.module.modules.player;
import me.linus.momentum.module.Module;
import me.linus.momentum.setting.checkbox.Checkbox;
import me.linus.momentum.setting.color.ColorPicker;
import me.linus.momentum.setting.mode.Mode;
import me.linus.momentum.util.render.RenderUtil;
import me.linus.momentum.util.render.builder.RenderBuilder.RenderMode;
import me.linus.momentum.util.world.BlockUtil;
import me.linus.momentum.util.world.BlockUtil.BlockResistance;
import net.minecraft.init.MobEffects;
import net.minecraft.network.play.client.CPacketPlayerDigging;
import net.minecraft.potion.PotionEffect;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockPos;
import net.minecraftforge.client.event.RenderWorldLastEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
/**
* @author linustouchtips
* @since 12/03/2020
*/
public class SpeedMine extends Module {
public SpeedMine() {
super("SpeedMine", Category.PLAYER, "Allows you to mine faster");
}
public static Mode mode = new Mode("Mode", "Packet", "Damage", "Creative", "Instant", "Delay", "Vanilla", "Fake");
public static Mode renderMode = new Mode("Render Mode", "Claw", "Fill", "Outline", "Both");
public static Checkbox color = new Checkbox("Color", true);
public static ColorPicker colorPicker = new ColorPicker(color, "Color Picker", new Color(119, 0, 255, 255));
@Override
public void setup() {
addSetting(mode);
addSetting(renderMode);
addSetting(color);
}
List<BlockPos> renderBlocks = new ArrayList<>();
@Override
public void onUpdate() {
if (nullCheck())
return;
renderBlocks.removeIf(blockPos -> BlockUtil.getBlockResistance(blockPos) == BlockResistance.Blank);
if ((BlockUtil.getBlockResistance(mc.objectMouseOver.getBlockPos()) == BlockResistance.Breakable || BlockUtil.getBlockResistance(mc.objectMouseOver.getBlockPos()) == BlockResistance.Resistant) && mc.playerController.isHittingBlock) {
switch (mode.getValue()) {
case 0:
renderBlocks.add(mc.objectMouseOver.getBlockPos());
mc.player.swingArm(EnumHand.MAIN_HAND);
mc.player.connection.sendPacket(new CPacketPlayerDigging(CPacketPlayerDigging.Action.START_DESTROY_BLOCK, mc.objectMouseOver.getBlockPos(), mc.objectMouseOver.sideHit));
mc.player.connection.sendPacket(new CPacketPlayerDigging(CPacketPlayerDigging.Action.STOP_DESTROY_BLOCK, mc.objectMouseOver.getBlockPos(), mc.objectMouseOver.sideHit));
break;
case 1:
if (mc.playerController.curBlockDamageMP >= 0.5f)
mc.playerController.curBlockDamageMP = 1.0f;
break;
case 2:
mc.playerController.curBlockDamageMP = 1.0f;
break;
case 3:
mc.player.swingArm(EnumHand.MAIN_HAND);
mc.player.connection.sendPacket(new CPacketPlayerDigging(CPacketPlayerDigging.Action.START_DESTROY_BLOCK, mc.objectMouseOver.getBlockPos(), mc.objectMouseOver.sideHit));
mc.player.connection.sendPacket(new CPacketPlayerDigging(CPacketPlayerDigging.Action.STOP_DESTROY_BLOCK, mc.objectMouseOver.getBlockPos(), mc.objectMouseOver.sideHit));
mc.playerController.onPlayerDestroyBlock(mc.objectMouseOver.getBlockPos());
mc.world.setBlockToAir(mc.objectMouseOver.getBlockPos());
break;
case 4:
mc.playerController.blockHitDelay = 0;
break;
case 5:
mc.player.addPotionEffect(new PotionEffect(new PotionEffect(MobEffects.HASTE, 10000, 1, false, false)));
break;
case 6:
mc.world.setBlockToAir(mc.objectMouseOver.getBlockPos());
break;
}
}
}
@SubscribeEvent
public void onRenderWorld(RenderWorldLastEvent eventRender) {
if (nullCheck())
return;
for (BlockPos renderBlock : renderBlocks) {
switch (renderMode.getValue()) {
case 0:
RenderUtil.drawBoxBlockPos(renderBlock, 0, 0, 0, colorPicker.getColor(), RenderMode.Claw);
break;
case 1:
RenderUtil.drawBoxBlockPos(renderBlock, 0, 0, 0, new Color(colorPicker.getRed(), colorPicker.getGreen(), colorPicker.getBlue(), 144), RenderMode.Outline);
break;
case 2:
RenderUtil.drawBoxBlockPos(renderBlock, 0, 0, 0, colorPicker.getColor(), RenderMode.Fill);
break;
case 3:
RenderUtil.drawBoxBlockPos(renderBlock, 0, 0, 0, colorPicker.getColor(), RenderMode.Both);
break;
}
}
}
@Override
public String getHUDData() {
return " " + mode.getMode(mode.getValue());
}
}
| 412 | 0.89968 | 1 | 0.89968 | game-dev | MEDIA | 0.951423 | game-dev | 0.966038 | 1 | 0.966038 |
Wangsheng-Funeral-Parlor/HuTao-GS | 9,135 | src/kcpServer/game/ability/abilityUtils.ts | import Entity from '$/entity'
import Avatar from '$/entity/avatar'
import ClientGadget from '$/entity/gadget/clientGadget'
import AbilityManager from '$/manager/abilityManager'
import Vector from '$/utils/vector'
import { DynamicFloat, DynamicInt } from '$DT/BinOutput/Common/DynamicNumber'
import { HealHP, LoseHP, ReviveAvatar, ReviveDeadAvatar } from '$DT/BinOutput/Config/ConfigAbility/Action/Child'
import ConfigAbilityPredicate from '$DT/BinOutput/Config/ConfigAbility/Predicate'
import SelectTargets from '$DT/BinOutput/Config/SelectTargets'
import SelectTargetsByShape from '$DT/BinOutput/Config/SelectTargets/Child/SelectTargetsByShape'
import { AbilityTargettingEnum, EntityTypeEnum, FightPropEnum, TargetTypeEnum } from '@/types/enum'
import { getStringHash } from '@/utils/hash'
import AppliedAbility from './appliedAbility'
const MathOp = ['MUL', 'ADD']
const creatureTypes = [EntityTypeEnum.Avatar, EntityTypeEnum.Monster]
export default class AbilityUtils {
manager: AbilityManager
constructor(manager: AbilityManager) {
this.manager = manager
}
private getMathOp(input: (string | number)[]): { i: number, name: string } {
const opList = input
.map((str, i) => {
const name = str?.toString()?.toUpperCase()
return { i, name, isOp: MathOp.includes(name) }
})
.filter((e, i, list) => e.isOp && list.slice(i - 2, i).find(a => a.isOp) == null)
for (const opName of MathOp) {
const op = opList.find(o => o.name === opName)
if (op) return op
}
return null
}
private doMath(state: { ability: AppliedAbility, busy: boolean, val: number }, input: (string | number)[]) {
const op = this.getMathOp(input)
if (op == null) {
state.busy = false
return
}
const index = op.i - 2
const args: number[] = input.splice(index, 3).slice(0, -1).map(this.eval.bind(this, state.ability))
if (args.find(a => typeof a !== 'number')) return
switch (op.name) {
case 'MUL':
state.val = args[0] * args[1]
break
case 'ADD':
state.val = args[0] + args[1]
break
}
input.splice(index, 0, state.val)
}
private calc(ability: AppliedAbility, input: (string | number)[]): number {
const state = { ability, busy: true, val: 0 }
while (state.busy) this.doMath(state, input)
return state.val
}
eval(ability: AppliedAbility, val: DynamicFloat | DynamicInt, defVal: number = 0): number {
if (val == null) return defVal
if (Array.isArray(val)) return this.calc(ability, Array.from(val))
val = val.toString()
if (!isNaN(parseFloat(val))) return parseFloat(val)
// fight prop
if (val.indexOf('FIGHT_PROP_') === 0) return ability.manager.entity.getProp(FightPropEnum[val])
// override map
return Number(ability?.overrideMapContainer?.getValue({ hash: getStringHash(val), str: val })?.val || 0)
}
calcAmount(ability: AppliedAbility, caster: Entity, target: Entity, config: HealHP | LoseHP | ReviveAvatar | ReviveDeadAvatar): number {
const {
Amount,
AmountByCasterAttackRatio,
AmountByCasterMaxHPRatio,
AmountByTargetCurrentHPRatio,
AmountByTargetMaxHPRatio
} = config
let amount = this.eval(ability, Amount)
amount += caster.getProp(FightPropEnum.FIGHT_PROP_MAX_HP) * this.eval(ability, AmountByCasterMaxHPRatio)
amount += caster.getProp(FightPropEnum.FIGHT_PROP_CUR_ATTACK) * this.eval(ability, AmountByCasterAttackRatio)
amount += target.getProp(FightPropEnum.FIGHT_PROP_MAX_HP) * this.eval(ability, AmountByTargetMaxHPRatio)
amount += target.getProp(FightPropEnum.FIGHT_PROP_CUR_HP) * this.eval(ability, AmountByTargetCurrentHPRatio)
return amount
}
getCaster(): Entity {
const { manager } = this
const { entity } = manager
const { manager: entityManager } = entity
if (entityManager == null) return entity
if ((<ClientGadget>entity).ownerEntityId != null) return entityManager.getEntity((<ClientGadget>entity).ownerEntityId)
return entity
}
getTargetType(target: Entity): TargetTypeEnum {
const { manager } = this
const { entity } = manager
const { manager: entityManager } = <Avatar>entity
const ownerEntityId = (<ClientGadget>entity).ownerEntityId
const owner = ownerEntityId ? entityManager.getEntity(ownerEntityId) : entity
const ownerIsCreature = creatureTypes.includes(owner.entityType)
const targetIsCreature = creatureTypes.includes(target.entityType)
const bothAreCreatures = ownerIsCreature && targetIsCreature
switch (true) {
case (entity === target):
return TargetTypeEnum.Self
case ((<ClientGadget>target).ownerEntityId === owner.entityId):
return TargetTypeEnum.SelfCamp
case (bothAreCreatures && owner.entityType === target.entityType):
return TargetTypeEnum.Alliance
case (bothAreCreatures && owner.entityType !== target.entityType):
return TargetTypeEnum.Enemy
default:
return TargetTypeEnum.None
}
}
isTargetType(target: Entity, type: TargetTypeEnum): boolean {
const targetType = this.getTargetType(target)
switch (type) {
case TargetTypeEnum.None:
case TargetTypeEnum.All:
return true
case TargetTypeEnum.Alliance:
return targetType === TargetTypeEnum.Alliance
case TargetTypeEnum.Enemy:
return targetType === TargetTypeEnum.Enemy
case TargetTypeEnum.Self:
return targetType === TargetTypeEnum.Self
case TargetTypeEnum.SelfCamp:
return targetType === TargetTypeEnum.SelfCamp
case TargetTypeEnum.AllExceptSelf:
return targetType !== TargetTypeEnum.Self
default:
return false
}
}
getShapeCenter(_base: string) {
return this.manager.entity.motion.pos
}
isInsideShape(target: Entity, shapeName: string, center: Vector, ratio: number): boolean {
const { pos } = target.motion
if (shapeName.indexOf('Circle') === 0) {
const radius = parseFloat(shapeName.slice(shapeName.indexOf('R') + 1)) * ratio
return center.distanceTo2D(pos) <= radius
}
return true
}
selectTargetsByShape(targetList: Entity[], ability: AppliedAbility, config: SelectTargetsByShape) {
const { manager } = this
const { entity } = manager
const { manager: entityManager } = <Avatar>entity
const { ShapeName, CenterBasedOn, CampTargetType, SizeRatio } = config
const nearbyEntities = entityManager.getNearbyEntityList(entity)
for (const nearbyEntity of nearbyEntities) {
if (
!this.isTargetType(nearbyEntity, TargetTypeEnum[CampTargetType] || TargetTypeEnum.None) ||
!this.isInsideShape(nearbyEntity, ShapeName, this.getShapeCenter(CenterBasedOn), this.eval(ability, SizeRatio) || 1)
) continue
targetList.push(nearbyEntity)
}
}
getOtherTargets(ability: AppliedAbility, config: SelectTargets) {
const { $type } = config
const targetList: Entity[] = []
switch ($type) {
case 'SelectTargetsByChildren':
case 'SelectTargetsByEquipParts':
case 'SelectTargetsByLCTrigger':
case 'SelectTargetsByLCTriggerAll':
case 'SelectTargetsBySelfGroup': {
break
}
case 'SelectTargetsByShape': {
this.selectTargetsByShape(targetList, ability, config)
break
}
case 'SelectTargetsByTag': {
break
}
}
return targetList
}
getTargetList(ability: AppliedAbility, config: HealHP | LoseHP | ReviveAvatar | ConfigAbilityPredicate, target: Entity): Entity[] {
const { manager } = this
const { entity } = manager
const { manager: entityManager, player } = <Avatar>entity
const { scene } = entityManager
const { playerList } = scene
const { Target, OtherTargets } = <{ Target: string, OtherTargets?: SelectTargets }>config
const targetList: Entity[] = []
switch (AbilityTargettingEnum[Target] || AbilityTargettingEnum.Self) {
case AbilityTargettingEnum.Self: {
targetList.push(entity)
break
}
case AbilityTargettingEnum.Caster: {
targetList.push(this.getCaster())
break
}
case AbilityTargettingEnum.Target: {
targetList.push(target)
break
}
case AbilityTargettingEnum.CurTeamAvatars: {
const team = player?.teamManager?.getTeam()
if (team == null) break
targetList.push(...team.getAvatarList())
break
}
case AbilityTargettingEnum.CurLocalAvatar: {
const currentAvatar = player?.currentAvatar
if (currentAvatar == null) break
targetList.push(currentAvatar)
break
}
case AbilityTargettingEnum.AllPlayerAvatars: {
for (const p of playerList) {
const team = p?.teamManager?.getTeam()
if (team == null) continue
targetList.push(...team.getAliveAvatarList())
}
break
}
}
if (OtherTargets) targetList.push(...this.getOtherTargets(ability, OtherTargets))
return targetList.filter((t, i, arr) => arr.indexOf(t) === i)
}
} | 412 | 0.89474 | 1 | 0.89474 | game-dev | MEDIA | 0.877182 | game-dev | 0.98891 | 1 | 0.98891 |
magefree/mage | 1,826 | Mage.Sets/src/mage/cards/m/Megatog.java |
package mage.cards.m;
import java.util.UUID;
import mage.MageInt;
import mage.abilities.Ability;
import mage.abilities.common.SimpleActivatedAbility;
import mage.abilities.costs.common.SacrificeTargetCost;
import mage.abilities.effects.common.continuous.BoostSourceEffect;
import mage.abilities.effects.common.continuous.GainAbilitySourceEffect;
import mage.abilities.keyword.TrampleAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
import mage.constants.Duration;
import mage.constants.Zone;
import mage.filter.common.FilterControlledPermanent;
import mage.target.common.TargetControlledPermanent;
/**
* @author Loki
*/
public final class Megatog extends CardImpl {
private static final FilterControlledPermanent filter = new FilterControlledPermanent("an artifact");
static {
filter.add(CardType.ARTIFACT.getPredicate());
}
public Megatog(UUID ownerId, CardSetInfo setInfo) {
super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{4}{R}{R}");
this.subtype.add(SubType.ATOG);
this.power = new MageInt(3);
this.toughness = new MageInt(4);
// Sacrifice an artifact: Megatog gets +3/+3 and gains trample until end of turn.
Ability ability = new SimpleActivatedAbility(new BoostSourceEffect(3, 3, Duration.EndOfTurn)
.setText("{this} gets +3/+3"), new SacrificeTargetCost(filter));
ability.addEffect(new GainAbilitySourceEffect(TrampleAbility.getInstance(), Duration.EndOfTurn)
.setText("and gains trample until end of turn"));
this.addAbility(ability);
}
private Megatog(final Megatog card) {
super(card);
}
@Override
public Megatog copy() {
return new Megatog(this);
}
}
| 412 | 0.956472 | 1 | 0.956472 | game-dev | MEDIA | 0.980175 | game-dev | 0.993234 | 1 | 0.993234 |
mekanism/Mekanism | 3,828 | src/generators/java/mekanism/generators/client/gui/element/button/ReactorLogicButton.java | package mekanism.generators.client.gui.element.button;
import java.util.EnumMap;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.IntSupplier;
import java.util.function.Supplier;
import mekanism.api.text.EnumColor;
import mekanism.api.text.TextComponentUtil;
import mekanism.client.gui.IGuiWrapper;
import mekanism.client.gui.element.button.MekanismButton;
import mekanism.client.gui.tooltip.TooltipUtils;
import mekanism.client.render.MekanismRenderer;
import mekanism.common.util.MekanismUtils.ResourceType;
import mekanism.generators.common.MekanismGenerators;
import mekanism.generators.common.base.IReactorLogic;
import mekanism.generators.common.base.IReactorLogicMode;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.components.Tooltip;
import net.minecraft.network.chat.CommonComponents;
import net.minecraft.resources.ResourceLocation;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class ReactorLogicButton<TYPE extends Enum<TYPE> & IReactorLogicMode<TYPE>> extends MekanismButton {
private static final ResourceLocation TEXTURE = MekanismGenerators.rl(ResourceType.GUI_BUTTON.getPrefix() + "reactor_logic.png");
@NotNull
private final IReactorLogic<TYPE> tile;
private final Supplier<@Nullable TYPE> modeSupplier;
private final Map<TYPE, Tooltip> typeTooltips;
private final Consumer<TYPE> onPress;
public ReactorLogicButton(IGuiWrapper gui, int x, int y, int index, @NotNull IReactorLogic<TYPE> tile, Class<TYPE> clazz, IntSupplier indexSupplier, Supplier<TYPE[]> modeList,
Consumer<TYPE> onPress) {
this(gui, x, y, tile, clazz, onPress, () -> {
int i = indexSupplier.getAsInt() + index;
TYPE[] modes = modeList.get();
return i >= 0 && i < modes.length ? modes[i] : null;
});
}
private ReactorLogicButton(IGuiWrapper gui, int x, int y, @NotNull IReactorLogic<TYPE> tile, Class<TYPE> clazz, Consumer<TYPE> onPress, Supplier<@Nullable TYPE> modeSupplier) {
super(gui, x, y, 128, 22, CommonComponents.EMPTY, (element, mouseX, mouseY) -> ((ReactorLogicButton<?>) element).click());
this.onPress = onPress;
this.modeSupplier = modeSupplier;
this.tile = tile;
this.typeTooltips = new EnumMap<>(clazz);
}
private boolean click() {
TYPE mode = modeSupplier.get();
if (mode != null) {
onPress.accept(mode);
}
return true;
}
@Override
public void drawBackground(@NotNull GuiGraphics guiGraphics, int mouseX, int mouseY, float partialTicks) {
TYPE mode = modeSupplier.get();
if (mode != null) {
MekanismRenderer.color(guiGraphics, mode.getColor());
guiGraphics.blit(TEXTURE, getButtonX(), getButtonY(), 0, mode == tile.getMode() ? 22 : 0, getButtonWidth(), getButtonHeight(), 128, 44);
MekanismRenderer.resetColor(guiGraphics);
}
}
@Override
public void renderForeground(GuiGraphics guiGraphics, int mouseX, int mouseY) {
TYPE mode = modeSupplier.get();
if (mode != null) {
gui().renderItem(guiGraphics, mode.getRenderStack(), relativeX + 3, relativeY + 3);
drawScrollingString(guiGraphics, TextComponentUtil.build(EnumColor.WHITE, mode), 20, 2, TextAlignment.LEFT, titleTextColor(), width - 20, 2, false);
super.renderForeground(guiGraphics, mouseX, mouseY);
}
}
@Override
public void updateTooltip(int mouseX, int mouseY) {
TYPE mode = modeSupplier.get();
if (mode == null) {
clearTooltip();
} else {
setTooltip(typeTooltips.computeIfAbsent(mode, m -> TooltipUtils.create(m.getDescription())));
}
}
} | 412 | 0.770748 | 1 | 0.770748 | game-dev | MEDIA | 0.452778 | game-dev,desktop-app | 0.940404 | 1 | 0.940404 |
dragonwell-project/dragonwell17 | 5,162 | src/hotspot/share/services/management.hpp | /*
* Copyright (c) 2003, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#ifndef SHARE_SERVICES_MANAGEMENT_HPP
#define SHARE_SERVICES_MANAGEMENT_HPP
#include "jmm.h"
#include "memory/allocation.hpp"
#include "runtime/handles.hpp"
#include "runtime/os.hpp"
#include "runtime/perfData.hpp"
#include "runtime/timer.hpp"
class OopClosure;
class ThreadSnapshot;
class Management : public AllStatic {
private:
static PerfVariable* _begin_vm_creation_time;
static PerfVariable* _end_vm_creation_time;
static PerfVariable* _vm_init_done_time;
static jmmOptionalSupport _optional_support;
static TimeStamp _stamp; // Timestamp since vm init done time
// Management klasses
static InstanceKlass* _diagnosticCommandImpl_klass;
static InstanceKlass* _garbageCollectorExtImpl_klass;
static InstanceKlass* _garbageCollectorMXBean_klass;
static InstanceKlass* _gcInfo_klass;
static InstanceKlass* _managementFactoryHelper_klass;
static InstanceKlass* _memoryManagerMXBean_klass;
static InstanceKlass* _memoryPoolMXBean_klass;
static InstanceKlass* _memoryUsage_klass;
static InstanceKlass* _sensor_klass;
static InstanceKlass* _threadInfo_klass;
static InstanceKlass* load_and_initialize_klass(Symbol* sh, TRAPS);
static InstanceKlass* load_and_initialize_klass_or_null(Symbol* sh, TRAPS);
static InstanceKlass* initialize_klass(Klass* k, TRAPS);
public:
static void init();
static void initialize(TRAPS);
static jlong ticks_to_ms(jlong ticks) NOT_MANAGEMENT_RETURN_(0L);
static jlong timestamp() NOT_MANAGEMENT_RETURN_(0L);
static void* get_jmm_interface(int version);
static void get_optional_support(jmmOptionalSupport* support);
static void record_vm_startup_time(jlong begin, jlong duration)
NOT_MANAGEMENT_RETURN;
static void record_vm_init_completed() {
// Initialize the timestamp to get the current time
_vm_init_done_time->set_value(os::javaTimeMillis());
// Update the timestamp to the vm init done time
_stamp.update();
}
static jlong begin_vm_creation_time() {
return _begin_vm_creation_time->get_value();
}
static jlong vm_init_done_time() {
return _vm_init_done_time->get_value();
}
// methods to return a Klass*.
static InstanceKlass* java_lang_management_ThreadInfo_klass(TRAPS);
static InstanceKlass* java_lang_management_MemoryUsage_klass(TRAPS)
NOT_MANAGEMENT_RETURN_(NULL);
static InstanceKlass* java_lang_management_MemoryPoolMXBean_klass(TRAPS);
static InstanceKlass* java_lang_management_MemoryManagerMXBean_klass(TRAPS);
static InstanceKlass* java_lang_management_GarbageCollectorMXBean_klass(TRAPS);
static InstanceKlass* sun_management_ManagementFactoryHelper_klass(TRAPS)
NOT_MANAGEMENT_RETURN_(NULL);
static InstanceKlass* sun_management_Sensor_klass(TRAPS)
NOT_MANAGEMENT_RETURN_(NULL);
static InstanceKlass* com_sun_management_internal_GarbageCollectorExtImpl_klass(TRAPS)
NOT_MANAGEMENT_RETURN_(NULL);
static InstanceKlass* com_sun_management_GcInfo_klass(TRAPS)
NOT_MANAGEMENT_RETURN_(NULL);
static InstanceKlass* com_sun_management_internal_DiagnosticCommandImpl_klass(TRAPS)
NOT_MANAGEMENT_RETURN_(NULL);
static instanceOop create_thread_info_instance(ThreadSnapshot* snapshot, TRAPS);
static instanceOop create_thread_info_instance(ThreadSnapshot* snapshot, objArrayHandle monitors_array, typeArrayHandle depths_array, objArrayHandle synchronizers_array, TRAPS);
};
class TraceVmCreationTime : public StackObj {
private:
TimeStamp _timer;
jlong _begin_time;
public:
TraceVmCreationTime() {}
~TraceVmCreationTime() {}
void start()
{ _timer.update_to(0); _begin_time = os::javaTimeMillis(); }
jlong begin_time() const {
return _begin_time;
}
/**
* Only call this if initialization completes successfully; it will
* crash if PerfMemory_exit() has already been called (usually by
* os::shutdown() when there was an initialization failure).
*/
void end()
{ Management::record_vm_startup_time(_begin_time, _timer.milliseconds()); }
};
#endif // SHARE_SERVICES_MANAGEMENT_HPP
| 412 | 0.740758 | 1 | 0.740758 | game-dev | MEDIA | 0.646623 | game-dev | 0.877205 | 1 | 0.877205 |
Wahares/Catan | 3,287 | Assets/Packages/FishNet/Runtime/Managing/Timing/Editor/TimeManagerEditor.cs | #if UNITY_EDITOR
using UnityEditor;
using UnityEngine;
namespace FishNet.Managing.Timing.Editing
{
[CustomEditor(typeof(TimeManager), true)]
[CanEditMultipleObjects]
public class TimeManagerEditor : Editor
{
private SerializedProperty _updateOrder;
private SerializedProperty _timingType;
private SerializedProperty _tickRate;
private SerializedProperty _allowTickDropping;
private SerializedProperty _maximumFrameTicks;
private SerializedProperty _pingInterval;
//private SerializedProperty _timingInterval;
private SerializedProperty _physicsMode;
protected virtual void OnEnable()
{
_updateOrder = serializedObject.FindProperty("_updateOrder");
_timingType = serializedObject.FindProperty("_timingType");
_tickRate = serializedObject.FindProperty("_tickRate");
_allowTickDropping = serializedObject.FindProperty("_allowTickDropping");
_maximumFrameTicks = serializedObject.FindProperty("_maximumFrameTicks");
_pingInterval = serializedObject.FindProperty("_pingInterval");
//_timingInterval = serializedObject.FindProperty("_timingInterval");
_physicsMode = serializedObject.FindProperty("_physicsMode");
}
public override void OnInspectorGUI()
{
serializedObject.Update();
GUI.enabled = false;
EditorGUILayout.ObjectField("Script:", MonoScript.FromMonoBehaviour((TimeManager)target), typeof(TimeManager), false);
GUI.enabled = true;
//Timing.
EditorGUILayout.LabelField("Timing", EditorStyles.boldLabel);
EditorGUI.indentLevel++;
EditorGUILayout.PropertyField(_updateOrder);
EditorGUILayout.PropertyField(_timingType);
EditorGUILayout.PropertyField(_allowTickDropping);
if (_allowTickDropping.boolValue == true)
{
EditorGUI.indentLevel++;
EditorGUILayout.PropertyField(_maximumFrameTicks);
EditorGUI.indentLevel--;
}
EditorGUILayout.PropertyField(_tickRate);
EditorGUILayout.PropertyField(_pingInterval);
//EditorGUILayout.PropertyField(_timingInterval);
EditorGUI.indentLevel--;
EditorGUILayout.Space();
//Physics.
EditorGUILayout.LabelField("Physics", EditorStyles.boldLabel);
EditorGUI.indentLevel++;
EditorGUILayout.PropertyField(_physicsMode);
if (_physicsMode.intValue != (int)FishNet.Managing.Timing.PhysicsMode.TimeManager)
EditorGUILayout.HelpBox("If you are using physics interactions be sure to change the PhysicsMode to TimeManager and implement physics within the TimeManager tick events.", MessageType.None);
EditorGUI.indentLevel--;
////Prediction.
//EditorGUILayout.LabelField("Prediction", EditorStyles.boldLabel);
//EditorGUI.indentLevel++;
//EditorGUILayout.PropertyField(_maximumBufferedInputs);
//EditorGUI.indentLevel--;
serializedObject.ApplyModifiedProperties();
}
}
}
#endif | 412 | 0.791604 | 1 | 0.791604 | game-dev | MEDIA | 0.968548 | game-dev | 0.844329 | 1 | 0.844329 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.