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
golang/gofrontend
2,632
libgo/go/syscall/js/func.go
// Copyright 2018 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. //go:build js && wasm package js import "sync" var ( funcsMu sync.Mutex funcs = make(map[uint32]func(Value, []Value) any) nextFuncID uint32 = 1 ) // Func is a wrapped Go function to be called by JavaScript. type Func struct { Value // the JavaScript function that invokes the Go function id uint32 } // FuncOf returns a function to be used by JavaScript. // // The Go function fn is called with the value of JavaScript's "this" keyword and the // arguments of the invocation. The return value of the invocation is // the result of the Go function mapped back to JavaScript according to ValueOf. // // Invoking the wrapped Go function from JavaScript will // pause the event loop and spawn a new goroutine. // Other wrapped functions which are triggered during a call from Go to JavaScript // get executed on the same goroutine. // // As a consequence, if one wrapped function blocks, JavaScript's event loop // is blocked until that function returns. Hence, calling any async JavaScript // API, which requires the event loop, like fetch (http.Client), will cause an // immediate deadlock. Therefore a blocking function should explicitly start a // new goroutine. // // Func.Release must be called to free up resources when the function will not be invoked any more. func FuncOf(fn func(this Value, args []Value) any) Func { funcsMu.Lock() id := nextFuncID nextFuncID++ funcs[id] = fn funcsMu.Unlock() return Func{ id: id, Value: jsGo.Call("_makeFuncWrapper", id), } } // Release frees up resources allocated for the function. // The function must not be invoked after calling Release. // It is allowed to call Release while the function is still running. func (c Func) Release() { funcsMu.Lock() delete(funcs, c.id) funcsMu.Unlock() } // setEventHandler is defined in the runtime package. func setEventHandler(fn func()) func init() { setEventHandler(handleEvent) } func handleEvent() { cb := jsGo.Get("_pendingEvent") if cb.IsNull() { return } jsGo.Set("_pendingEvent", Null()) id := uint32(cb.Get("id").Int()) if id == 0 { // zero indicates deadlock select {} } funcsMu.Lock() f, ok := funcs[id] funcsMu.Unlock() if !ok { Global().Get("console").Call("error", "call to released function") return } this := cb.Get("this") argsObj := cb.Get("args") args := make([]Value, argsObj.Length()) for i := range args { args[i] = argsObj.Index(i) } result := f(this, args) cb.Set("result", result) }
411
0.74746
1
0.74746
game-dev
MEDIA
0.279611
game-dev
0.741553
1
0.741553
kool-engine/kool
1,034
kool-editor-model/src/jsMain/kotlin/de/fabmax/kool/editor/api/BehaviorLoader.js.kt
package de.fabmax.kool.editor.api @Suppress("EXPECT_ACTUAL_CLASSIFIERS_ARE_IN_BETA_WARNING") actual object BehaviorLoader { var appBehaviorLoader: AppBehaviorLoader? = null private val loader: AppBehaviorLoader get() = appBehaviorLoader ?: throw IllegalStateException("BehaviorLoader.appBehaviorLoader not initialized") actual fun newInstance(behaviorClassName: String): KoolBehavior { return loader.newInstance(behaviorClassName) } actual fun getProperty(behavior: KoolBehavior, propertyName: String): Any? { return loader.getProperty(behavior, propertyName) } actual fun setProperty(behavior: KoolBehavior, propertyName: String, value: Any?) { loader.setProperty(behavior, propertyName, value) } interface AppBehaviorLoader { fun newInstance(behaviorClassName: String): KoolBehavior fun getProperty(behavior: KoolBehavior, propertyName: String): Any? fun setProperty(behavior: KoolBehavior, propertyName: String, value: Any?) } }
411
0.555889
1
0.555889
game-dev
MEDIA
0.655034
game-dev
0.513534
1
0.513534
folgerwang/UnrealEngine
8,465
Engine/Source/ThirdParty/IntelEmbree/Embree2140/src/kernels/common/scene_quad_mesh.h
// ======================================================================== // // Copyright 2009-2017 Intel Corporation // // // // 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. // // ======================================================================== // #pragma once #include "geometry.h" #include "buffer.h" namespace embree { /*! Quad Mesh */ struct QuadMesh : public Geometry { /*! type of this geometry */ static const Geometry::Type geom_type = Geometry::QUAD_MESH; /*! triangle indices */ struct Quad { uint32_t v[4]; /*! outputs triangle indices */ __forceinline friend std::ostream &operator<<(std::ostream& cout, const Quad& q) { return cout << "Quad {" << q.v[0] << ", " << q.v[1] << ", " << q.v[2] << ", " << q.v[3] << " }"; } }; public: /*! quad mesh construction */ QuadMesh (Scene* parent, RTCGeometryFlags flags, size_t numQuads, size_t numVertices, size_t numTimeSteps); /* geometry interface */ public: void enabling(); void disabling(); void setMask (unsigned mask); void setBuffer(RTCBufferType type, void* ptr, size_t offset, size_t stride, size_t size); void* map(RTCBufferType type); void unmap(RTCBufferType type); void immutable (); bool verify (); void interpolate(unsigned primID, float u, float v, RTCBufferType buffer, float* P, float* dPdu, float* dPdv, float* ddPdudu, float* ddPdvdv, float* ddPdudv, size_t numFloats); // FIXME: implement interpolateN public: /*! returns number of quads */ __forceinline size_t size() const { return quads.size(); } /*! returns number of vertices */ __forceinline size_t numVertices() const { return vertices[0].size(); } /*! returns i'th quad */ __forceinline const Quad& quad(size_t i) const { return quads[i]; } /*! returns i'th vertex of itime'th timestep */ __forceinline const Vec3fa vertex(size_t i) const { return vertices0[i]; } /*! returns i'th vertex of itime'th timestep */ __forceinline const char* vertexPtr(size_t i) const { return vertices0.getPtr(i); } /*! returns i'th vertex of itime'th timestep */ __forceinline const Vec3fa vertex(size_t i, size_t itime) const { return vertices[itime][i]; } /*! returns i'th vertex of itime'th timestep */ __forceinline const char* vertexPtr(size_t i, size_t itime) const { return vertices[itime].getPtr(i); } /*! calculates the bounds of the i'th quad */ __forceinline BBox3fa bounds(size_t i) const { const Quad& q = quad(i); const Vec3fa v0 = vertex(q.v[0]); const Vec3fa v1 = vertex(q.v[1]); const Vec3fa v2 = vertex(q.v[2]); const Vec3fa v3 = vertex(q.v[3]); return BBox3fa(min(v0,v1,v2,v3),max(v0,v1,v2,v3)); } /*! calculates the bounds of the i'th quad at the itime'th timestep */ __forceinline BBox3fa bounds(size_t i, size_t itime) const { const Quad& q = quad(i); const Vec3fa v0 = vertex(q.v[0],itime); const Vec3fa v1 = vertex(q.v[1],itime); const Vec3fa v2 = vertex(q.v[2],itime); const Vec3fa v3 = vertex(q.v[3],itime); return BBox3fa(min(v0,v1,v2,v3),max(v0,v1,v2,v3)); } /*! check if the i'th primitive is valid at the itime'th timestep */ __forceinline bool valid(size_t i, size_t itime) const { const Quad& q = quad(i); if (q.v[0] >= numVertices()) return false; if (q.v[1] >= numVertices()) return false; if (q.v[2] >= numVertices()) return false; if (q.v[3] >= numVertices()) return false; const Vec3fa v0 = vertex(q.v[0],itime); const Vec3fa v1 = vertex(q.v[1],itime); const Vec3fa v2 = vertex(q.v[2],itime); const Vec3fa v3 = vertex(q.v[3],itime); if (unlikely(!isvalid(v0) || !isvalid(v1) || !isvalid(v2) || !isvalid(v3))) return false; return true; } /*! calculates the linear bounds of the i'th quad at the itimeGlobal'th time segment */ __forceinline LBBox3fa linearBounds(size_t i, size_t itimeGlobal, size_t numTimeStepsGlobal) const { return Geometry::linearBounds([&] (size_t itime) { return bounds(i, itime); }, itimeGlobal, numTimeStepsGlobal, numTimeSteps); } /*! calculates the build bounds of the i'th primitive, if it's valid */ __forceinline bool buildBounds(size_t i, BBox3fa* bbox = nullptr) const { const Quad& q = quad(i); if (q.v[0] >= numVertices()) return false; if (q.v[1] >= numVertices()) return false; if (q.v[2] >= numVertices()) return false; if (q.v[3] >= numVertices()) return false; for (size_t t=0; t<numTimeSteps; t++) { const Vec3fa v0 = vertex(q.v[0],t); const Vec3fa v1 = vertex(q.v[1],t); const Vec3fa v2 = vertex(q.v[2],t); const Vec3fa v3 = vertex(q.v[3],t); if (unlikely(!isvalid(v0) || !isvalid(v1) || !isvalid(v2) || !isvalid(v3))) return false; } if (bbox) *bbox = bounds(i); return true; } /*! calculates the build bounds of the i'th primitive at the itime'th time segment, if it's valid */ __forceinline bool buildBounds(size_t i, size_t itime, BBox3fa& bbox) const { const Quad& q = quad(i); if (unlikely(q.v[0] >= numVertices())) return false; if (unlikely(q.v[1] >= numVertices())) return false; if (unlikely(q.v[2] >= numVertices())) return false; if (unlikely(q.v[3] >= numVertices())) return false; assert(itime+1 < numTimeSteps); const Vec3fa a0 = vertex(q.v[0],itime+0); if (unlikely(!isvalid(a0))) return false; const Vec3fa a1 = vertex(q.v[1],itime+0); if (unlikely(!isvalid(a1))) return false; const Vec3fa a2 = vertex(q.v[2],itime+0); if (unlikely(!isvalid(a2))) return false; const Vec3fa a3 = vertex(q.v[3],itime+0); if (unlikely(!isvalid(a3))) return false; const Vec3fa b0 = vertex(q.v[0],itime+1); if (unlikely(!isvalid(b0))) return false; const Vec3fa b1 = vertex(q.v[1],itime+1); if (unlikely(!isvalid(b1))) return false; const Vec3fa b2 = vertex(q.v[2],itime+1); if (unlikely(!isvalid(b2))) return false; const Vec3fa b3 = vertex(q.v[3],itime+1); if (unlikely(!isvalid(b3))) return false; /* use bounds of first time step in builder */ bbox = BBox3fa(min(a0,a1,a2,a3),max(a0,a1,a2,a3)); return true; } /*! calculates the build bounds of the i'th primitive at the itimeGlobal'th time segment, if it's valid */ __forceinline bool buildBounds(size_t i, size_t itimeGlobal, size_t numTimeStepsGlobal, BBox3fa& bbox) const { return Geometry::buildBounds([&] (size_t itime, BBox3fa& bbox) -> bool { if (unlikely(!valid(i, itime))) return false; bbox = bounds(i, itime); return true; }, itimeGlobal, numTimeStepsGlobal, numTimeSteps, bbox); } public: APIBuffer<Quad> quads; //!< array of quads BufferRefT<Vec3fa> vertices0; //!< fast access to first vertex buffer vector<APIBuffer<Vec3fa>> vertices; //!< vertex array for each timestep vector<APIBuffer<char>> userbuffers; //!< user buffers }; }
411
0.936476
1
0.936476
game-dev
MEDIA
0.484801
game-dev,graphics-rendering
0.989564
1
0.989564
emileb/OpenGames
24,681
opengames/src/main/jni/quake2/src/xsrc/g_spawn.c
#include "g_local.h" typedef struct { char *name; void (*spawn)(edict_t *ent); } spawn_t; void SP_item_health (edict_t *self); void SP_item_health_small (edict_t *self); void SP_item_health_large (edict_t *self); void SP_item_health_mega (edict_t *self); void SP_info_player_start (edict_t *ent); void SP_info_player_deathmatch (edict_t *ent); void SP_info_player_coop (edict_t *ent); void SP_info_player_intermission (edict_t *ent); void SP_func_plat (edict_t *ent); void SP_func_rotating (edict_t *ent); void SP_func_button (edict_t *ent); void SP_func_door (edict_t *ent); void SP_func_door_secret (edict_t *ent); void SP_func_door_rotating (edict_t *ent); void SP_func_water (edict_t *ent); void SP_func_train (edict_t *ent); void SP_func_conveyor (edict_t *self); void SP_func_wall (edict_t *self); void SP_func_object (edict_t *self); void SP_func_explosive (edict_t *self); void SP_func_timer (edict_t *self); void SP_func_areaportal (edict_t *ent); void SP_func_clock (edict_t *ent); void SP_func_killbox (edict_t *ent); void SP_trigger_always (edict_t *ent); void SP_trigger_once (edict_t *ent); void SP_trigger_multiple (edict_t *ent); void SP_trigger_relay (edict_t *ent); void SP_trigger_push (edict_t *ent); void SP_trigger_hurt (edict_t *ent); void SP_trigger_key (edict_t *ent); void SP_trigger_counter (edict_t *ent); void SP_trigger_elevator (edict_t *ent); void SP_trigger_gravity (edict_t *ent); void SP_trigger_monsterjump (edict_t *ent); void SP_target_temp_entity (edict_t *ent); void SP_target_speaker (edict_t *ent); void SP_target_explosion (edict_t *ent); void SP_target_changelevel (edict_t *ent); void SP_target_secret (edict_t *ent); void SP_target_goal (edict_t *ent); void SP_target_splash (edict_t *ent); void SP_target_spawner (edict_t *ent); void SP_target_blaster (edict_t *ent); void SP_target_crosslevel_trigger (edict_t *ent); void SP_target_crosslevel_target (edict_t *ent); void SP_target_laser (edict_t *self); void SP_target_help (edict_t *ent); void SP_target_actor (edict_t *ent); void SP_target_lightramp (edict_t *self); void SP_target_earthquake (edict_t *ent); void SP_target_character (edict_t *ent); void SP_target_string (edict_t *ent); void SP_worldspawn (edict_t *ent); void SP_viewthing (edict_t *ent); void SP_light (edict_t *self); void SP_light_mine1 (edict_t *ent); void SP_light_mine2 (edict_t *ent); void SP_info_null (edict_t *self); void SP_info_notnull (edict_t *self); void SP_path_corner (edict_t *self); void SP_point_combat (edict_t *self); void SP_misc_explobox (edict_t *self); void SP_misc_banner (edict_t *self); void SP_misc_satellite_dish (edict_t *self); void SP_misc_actor (edict_t *self); void SP_misc_gib_arm (edict_t *self); void SP_misc_gib_leg (edict_t *self); void SP_misc_gib_head (edict_t *self); void SP_misc_insane (edict_t *self); void SP_misc_deadsoldier (edict_t *self); void SP_misc_viper (edict_t *self); void SP_misc_viper_bomb (edict_t *self); void SP_misc_bigviper (edict_t *self); void SP_misc_strogg_ship (edict_t *self); void SP_misc_teleporter (edict_t *self); void SP_misc_teleporter_dest (edict_t *self); void SP_misc_blackhole (edict_t *self); void SP_misc_eastertank (edict_t *self); void SP_misc_easterchick (edict_t *self); void SP_misc_easterchick2 (edict_t *self); void SP_monster_berserk (edict_t *self); void SP_monster_gladiator (edict_t *self); void SP_monster_gunner (edict_t *self); void SP_monster_infantry (edict_t *self); void SP_monster_soldier_light (edict_t *self); void SP_monster_soldier (edict_t *self); void SP_monster_soldier_ss (edict_t *self); void SP_monster_tank (edict_t *self); void SP_monster_medic (edict_t *self); void SP_monster_flipper (edict_t *self); void SP_monster_chick (edict_t *self); void SP_monster_parasite (edict_t *self); void SP_monster_flyer (edict_t *self); void SP_monster_brain (edict_t *self); void SP_monster_floater (edict_t *self); void SP_monster_hover (edict_t *self); void SP_monster_mutant (edict_t *self); void SP_monster_supertank (edict_t *self); void SP_monster_boss2 (edict_t *self); void SP_monster_jorg (edict_t *self); void SP_monster_boss3_stand (edict_t *self); void SP_monster_commander_body (edict_t *self); void SP_turret_breach (edict_t *self); void SP_turret_base (edict_t *self); void SP_turret_driver (edict_t *self); // RAFAEL 14-APR-98 void SP_monster_soldier_hypergun (edict_t *self); void SP_monster_soldier_lasergun (edict_t *self); void SP_monster_soldier_ripper (edict_t *self); void SP_monster_fixbot (edict_t *self); void SP_monster_gekk (edict_t *self); void SP_monster_chick_heat (edict_t *self); void SP_monster_gladb (edict_t *self); void SP_monster_boss5 (edict_t *self); void SP_rotating_light (edict_t *self); void SP_object_repair (edict_t *self); void SP_misc_crashviper (edict_t *ent); void SP_misc_viper_missile (edict_t *self); void SP_misc_amb4 (edict_t *ent); void SP_target_mal_laser (edict_t *ent); void SP_misc_transport (edict_t *ent); // END 14-APR-98 void SP_misc_nuke (edict_t *ent); spawn_t spawns[] = { {"item_health", SP_item_health}, {"item_health_small", SP_item_health_small}, {"item_health_large", SP_item_health_large}, {"item_health_mega", SP_item_health_mega}, {"info_player_start", SP_info_player_start}, {"info_player_deathmatch", SP_info_player_deathmatch}, {"info_player_coop", SP_info_player_coop}, {"info_player_intermission", SP_info_player_intermission}, {"func_plat", SP_func_plat}, {"func_button", SP_func_button}, {"func_door", SP_func_door}, {"func_door_secret", SP_func_door_secret}, {"func_door_rotating", SP_func_door_rotating}, {"func_rotating", SP_func_rotating}, {"func_train", SP_func_train}, {"func_water", SP_func_water}, {"func_conveyor", SP_func_conveyor}, {"func_areaportal", SP_func_areaportal}, {"func_clock", SP_func_clock}, {"func_wall", SP_func_wall}, {"func_object", SP_func_object}, {"func_timer", SP_func_timer}, {"func_explosive", SP_func_explosive}, {"func_killbox", SP_func_killbox}, // RAFAEL {"func_object_repair", SP_object_repair}, {"rotating_light", SP_rotating_light}, {"trigger_always", SP_trigger_always}, {"trigger_once", SP_trigger_once}, {"trigger_multiple", SP_trigger_multiple}, {"trigger_relay", SP_trigger_relay}, {"trigger_push", SP_trigger_push}, {"trigger_hurt", SP_trigger_hurt}, {"trigger_key", SP_trigger_key}, {"trigger_counter", SP_trigger_counter}, {"trigger_elevator", SP_trigger_elevator}, {"trigger_gravity", SP_trigger_gravity}, {"trigger_monsterjump", SP_trigger_monsterjump}, {"target_temp_entity", SP_target_temp_entity}, {"target_speaker", SP_target_speaker}, {"target_explosion", SP_target_explosion}, {"target_changelevel", SP_target_changelevel}, {"target_secret", SP_target_secret}, {"target_goal", SP_target_goal}, {"target_splash", SP_target_splash}, {"target_spawner", SP_target_spawner}, {"target_blaster", SP_target_blaster}, {"target_crosslevel_trigger", SP_target_crosslevel_trigger}, {"target_crosslevel_target", SP_target_crosslevel_target}, {"target_laser", SP_target_laser}, {"target_help", SP_target_help}, {"target_actor", SP_target_actor}, {"target_lightramp", SP_target_lightramp}, {"target_earthquake", SP_target_earthquake}, {"target_character", SP_target_character}, {"target_string", SP_target_string}, // RAFAEL 15-APR-98 {"target_mal_laser", SP_target_mal_laser}, {"worldspawn", SP_worldspawn}, {"viewthing", SP_viewthing}, {"light", SP_light}, {"light_mine1", SP_light_mine1}, {"light_mine2", SP_light_mine2}, {"info_null", SP_info_null}, {"func_group", SP_info_null}, {"info_notnull", SP_info_notnull}, {"path_corner", SP_path_corner}, {"point_combat", SP_point_combat}, {"misc_explobox", SP_misc_explobox}, {"misc_banner", SP_misc_banner}, {"misc_satellite_dish", SP_misc_satellite_dish}, {"misc_actor", SP_misc_actor}, {"misc_gib_arm", SP_misc_gib_arm}, {"misc_gib_leg", SP_misc_gib_leg}, {"misc_gib_head", SP_misc_gib_head}, {"misc_insane", SP_misc_insane}, {"misc_deadsoldier", SP_misc_deadsoldier}, {"misc_viper", SP_misc_viper}, {"misc_viper_bomb", SP_misc_viper_bomb}, {"misc_bigviper", SP_misc_bigviper}, {"misc_strogg_ship", SP_misc_strogg_ship}, {"misc_teleporter", SP_misc_teleporter}, {"misc_teleporter_dest", SP_misc_teleporter_dest}, {"misc_blackhole", SP_misc_blackhole}, {"misc_eastertank", SP_misc_eastertank}, {"misc_easterchick", SP_misc_easterchick}, {"misc_easterchick2", SP_misc_easterchick2}, // RAFAEL {"misc_crashviper", SP_misc_crashviper}, {"misc_viper_missile", SP_misc_viper_missile}, {"misc_amb4", SP_misc_amb4}, // RAFAEL 17-APR-98 {"misc_transport", SP_misc_transport}, // END 17-APR-98 // RAFAEL 12-MAY-98 {"misc_nuke", SP_misc_nuke}, {"monster_berserk", SP_monster_berserk}, {"monster_gladiator", SP_monster_gladiator}, {"monster_gunner", SP_monster_gunner}, {"monster_infantry", SP_monster_infantry}, {"monster_soldier_light", SP_monster_soldier_light}, {"monster_soldier", SP_monster_soldier}, {"monster_soldier_ss", SP_monster_soldier_ss}, {"monster_tank", SP_monster_tank}, {"monster_tank_commander", SP_monster_tank}, {"monster_medic", SP_monster_medic}, {"monster_flipper", SP_monster_flipper}, {"monster_chick", SP_monster_chick}, {"monster_parasite", SP_monster_parasite}, {"monster_flyer", SP_monster_flyer}, {"monster_brain", SP_monster_brain}, {"monster_floater", SP_monster_floater}, {"monster_hover", SP_monster_hover}, {"monster_mutant", SP_monster_mutant}, {"monster_supertank", SP_monster_supertank}, {"monster_boss2", SP_monster_boss2}, {"monster_boss3_stand", SP_monster_boss3_stand}, {"monster_jorg", SP_monster_jorg}, {"monster_commander_body", SP_monster_commander_body}, // RAFAEL 14-APR-98 {"monster_soldier_hypergun", SP_monster_soldier_hypergun}, {"monster_soldier_lasergun", SP_monster_soldier_lasergun}, {"monster_soldier_ripper", SP_monster_soldier_ripper}, {"monster_fixbot", SP_monster_fixbot}, {"monster_gekk", SP_monster_gekk}, {"monster_chick_heat", SP_monster_chick_heat}, {"monster_gladb", SP_monster_gladb}, {"monster_boss5", SP_monster_boss5}, // END 14-APR-98 {"turret_breach", SP_turret_breach}, {"turret_base", SP_turret_base}, {"turret_driver", SP_turret_driver}, {NULL, NULL} }; /* =============== ED_CallSpawn Finds the spawn function for the entity and calls it =============== */ void ED_CallSpawn (edict_t *ent) { spawn_t *s; gitem_t *item; int i; if (!ent->classname) { gi.dprintf ("ED_CallSpawn: NULL classname\n"); return; } // check item spawn functions for (i=0,item=itemlist ; i<game.num_items ; i++,item++) { if (!item->classname) continue; if (!strcmp(item->classname, ent->classname)) { // found it SpawnItem (ent, item); return; } } // check normal spawn functions for (s=spawns ; s->name ; s++) { if (!strcmp(s->name, ent->classname)) { // found it s->spawn (ent); return; } } gi.dprintf ("%s doesn't have a spawn function\n", ent->classname); } /* ============= ED_NewString ============= */ char *ED_NewString (char *string) { char *newb, *new_p; int i,l; l = strlen(string) + 1; newb = gi.TagMalloc (l, TAG_LEVEL); new_p = newb; for (i=0 ; i< l ; i++) { if (string[i] == '\\' && i < l-1) { i++; if (string[i] == 'n') *new_p++ = '\n'; else *new_p++ = '\\'; } else *new_p++ = string[i]; } return newb; } /* =============== ED_ParseField Takes a key/value pair and sets the binary values in an edict =============== */ void ED_ParseField (char *key, char *value, edict_t *ent) { field_t *f; byte *b; float v; vec3_t vec; for (f=fields ; f->name ; f++) { if (!(f->flags & FFL_NOSPAWN) && !Q_stricmp(f->name, key)) { // found it if (f->flags & FFL_SPAWNTEMP) b = (byte *)&st; else b = (byte *)ent; switch (f->type) { case F_LSTRING: *(char **)(b+f->ofs) = ED_NewString (value); break; case F_VECTOR: sscanf (value, "%f %f %f", &vec[0], &vec[1], &vec[2]); ((float *)(b+f->ofs))[0] = vec[0]; ((float *)(b+f->ofs))[1] = vec[1]; ((float *)(b+f->ofs))[2] = vec[2]; break; case F_INT: *(int *)(b+f->ofs) = atoi(value); break; case F_FLOAT: *(float *)(b+f->ofs) = atof(value); break; case F_ANGLEHACK: v = atof(value); ((float *)(b+f->ofs))[0] = 0; ((float *)(b+f->ofs))[1] = v; ((float *)(b+f->ofs))[2] = 0; break; case F_IGNORE: break; } return; } } gi.dprintf ("%s is not a field\n", key); } /* ==================== ED_ParseEdict Parses an edict out of the given string, returning the new position ed should be a properly initialized empty edict. ==================== */ char *ED_ParseEdict (char *data, edict_t *ent) { qboolean init; char keyname[256]; char *com_token; init = false; memset (&st, 0, sizeof(st)); // go through all the dictionary pairs while (1) { // parse key com_token = COM_Parse (&data); if (com_token[0] == '}') break; if (!data) gi.error ("ED_ParseEntity: EOF without closing brace"); strncpy (keyname, com_token, sizeof(keyname)-1); // parse value com_token = COM_Parse (&data); if (!data) gi.error ("ED_ParseEntity: EOF without closing brace"); if (com_token[0] == '}') gi.error ("ED_ParseEntity: closing brace without data"); init = true; // keynames with a leading underscore are used for utility comments, // and are immediately discarded by quake if (keyname[0] == '_') continue; ED_ParseField (keyname, com_token, ent); } if (!init) memset (ent, 0, sizeof(*ent)); return data; } /* ================ G_FindTeams Chain together all entities with a matching team field. All but the first will have the FL_TEAMSLAVE flag set. All but the last will have the teamchain field set to the next one ================ */ void G_FindTeams (void) { edict_t *e, *e2, *chain; int i, j; int c, c2; c = 0; c2 = 0; for (i=1, e=g_edicts+i ; i < globals.num_edicts ; i++,e++) { if (!e->inuse) continue; if (!e->team) continue; if (e->flags & FL_TEAMSLAVE) continue; chain = e; e->teammaster = e; c++; c2++; for (j=i+1, e2=e+1 ; j < globals.num_edicts ; j++,e2++) { if (!e2->inuse) continue; if (!e2->team) continue; if (e2->flags & FL_TEAMSLAVE) continue; if (!strcmp(e->team, e2->team)) { c2++; chain->teamchain = e2; e2->teammaster = e; chain = e2; e2->flags |= FL_TEAMSLAVE; } } } gi.dprintf ("%i teams with %i entities\n", c, c2); } /* ============== SpawnEntities Creates a server's entity / program execution context by parsing textual entity definitions out of an ent file. ============== */ void SpawnEntities (char *mapname, char *entities, char *spawnpoint) { edict_t *ent; int inhibit; char *com_token; int i; float skill_level; skill_level = floor (skill->value); if (skill_level < 0) skill_level = 0; if (skill_level > 3) skill_level = 3; if (skill->value != skill_level) gi.cvar_forceset("skill", va("%f", skill_level)); SaveClientData (); gi.FreeTags (TAG_LEVEL); memset (&level, 0, sizeof(level)); memset (g_edicts, 0, game.maxentities * sizeof (g_edicts[0])); strncpy (level.mapname, mapname, sizeof(level.mapname)-1); strncpy (game.spawnpoint, spawnpoint, sizeof(game.spawnpoint)-1); // set client fields on player ents for (i=0 ; i<game.maxclients ; i++) g_edicts[i+1].client = game.clients + i; ent = NULL; inhibit = 0; // parse ents while (1) { // parse the opening brace com_token = COM_Parse (&entities); if (!entities) break; if (com_token[0] != '{') gi.error ("ED_LoadFromFile: found %s when expecting {",com_token); if (!ent) ent = g_edicts; else ent = G_Spawn (); entities = ED_ParseEdict (entities, ent); // yet another map hack if (!stricmp(level.mapname, "command") && !stricmp(ent->classname, "trigger_once") && !stricmp(ent->model, "*27")) ent->spawnflags &= ~SPAWNFLAG_NOT_HARD; // remove things (except the world) from different skill levels or deathmatch if (ent != g_edicts) { if (deathmatch->value) { if ( ent->spawnflags & SPAWNFLAG_NOT_DEATHMATCH ) { G_FreeEdict (ent); inhibit++; continue; } } else { if ( /* ((coop->value) && (ent->spawnflags & SPAWNFLAG_NOT_COOP)) || */ ((skill->value == 0) && (ent->spawnflags & SPAWNFLAG_NOT_EASY)) || ((skill->value == 1) && (ent->spawnflags & SPAWNFLAG_NOT_MEDIUM)) || (((skill->value == 2) || (skill->value == 3)) && (ent->spawnflags & SPAWNFLAG_NOT_HARD)) ) { G_FreeEdict (ent); inhibit++; continue; } } ent->spawnflags &= ~(SPAWNFLAG_NOT_EASY|SPAWNFLAG_NOT_MEDIUM|SPAWNFLAG_NOT_HARD|SPAWNFLAG_NOT_COOP|SPAWNFLAG_NOT_DEATHMATCH); } ED_CallSpawn (ent); } gi.dprintf ("%i entities inhibited\n", inhibit); #ifdef DEBUG i = 1; ent = EDICT_NUM(i); while (i < globals.num_edicts) { if (ent->inuse != 0 || ent->inuse != 1) Com_DPrintf("Invalid entity %d\n", i); i++, ent++; } #endif G_FindTeams (); PlayerTrail_Init (); } //=================================================================== #if 0 // cursor positioning xl <value> xr <value> yb <value> yt <value> xv <value> yv <value> // drawing statpic <name> pic <stat> num <fieldwidth> <stat> string <stat> // control if <stat> ifeq <stat> <value> ifbit <stat> <value> endif #endif char *single_statusbar = "yb -24 " // health "xv 0 " "hnum " "xv 50 " "pic 0 " // ammo "if 2 " " xv 100 " " anum " " xv 150 " " pic 2 " "endif " // armor "if 4 " " xv 200 " " rnum " " xv 250 " " pic 4 " "endif " // selected item "if 6 " " xv 296 " " pic 6 " "endif " "yb -50 " // picked up item "if 7 " " xv 0 " " pic 7 " " xv 26 " " yb -42 " " stat_string 8 " " yb -50 " "endif " // timer "if 9 " " xv 262 " " num 2 10 " " xv 296 " " pic 9 " "endif " // help / weapon icon "if 11 " " xv 148 " " pic 11 " "endif " ; char *dm_statusbar = "yb -24 " // health "xv 0 " "hnum " "xv 50 " "pic 0 " // ammo "if 2 " " xv 100 " " anum " " xv 150 " " pic 2 " "endif " // armor "if 4 " " xv 200 " " rnum " " xv 250 " " pic 4 " "endif " // selected item "if 6 " " xv 296 " " pic 6 " "endif " "yb -50 " // picked up item "if 7 " " xv 0 " " pic 7 " " xv 26 " " yb -42 " " stat_string 8 " " yb -50 " "endif " // timer "if 9 " " xv 246 " " num 2 10 " " xv 296 " " pic 9 " "endif " // help / weapon icon "if 11 " " xv 148 " " pic 11 " "endif " // frags "xr -50 " "yt 2 " "num 3 14 " // spectator "if 17 " "xv 0 " "yb -58 " "string2 \"SPECTATOR MODE\" " "endif " // chase camera "if 16 " "xv 0 " "yb -68 " "string \"Chasing\" " "xv 64 " "stat_string 16 " "endif " ; /*QUAKED worldspawn (0 0 0) ? Only used for the world. "sky" environment map name "skyaxis" vector axis for rotating sky "skyrotate" speed of rotation in degrees/second "sounds" music cd track number "gravity" 800 is default gravity "message" text to print at user logon */ void SP_worldspawn (edict_t *ent) { ent->movetype = MOVETYPE_PUSH; ent->solid = SOLID_BSP; ent->inuse = true; // since the world doesn't use G_Spawn() ent->s.modelindex = 1; // world model is always index 1 //--------------- // reserve some spots for dead player bodies for coop / deathmatch InitBodyQue (); // set configstrings for items SetItemNames (); if (st.nextmap) strcpy (level.nextmap, st.nextmap); // make some data visible to the server if (ent->message && ent->message[0]) { gi.configstring (CS_NAME, ent->message); strncpy (level.level_name, ent->message, sizeof(level.level_name)); } else strncpy (level.level_name, level.mapname, sizeof(level.level_name)); if (st.sky && st.sky[0]) gi.configstring (CS_SKY, st.sky); else gi.configstring (CS_SKY, "unit1_"); gi.configstring (CS_SKYROTATE, va("%f", st.skyrotate) ); gi.configstring (CS_SKYAXIS, va("%f %f %f", st.skyaxis[0], st.skyaxis[1], st.skyaxis[2]) ); gi.configstring (CS_CDTRACK, va("%i", ent->sounds) ); gi.configstring (CS_MAXCLIENTS, va("%i", (int)(maxclients->value) ) ); // status bar program if (deathmatch->value) gi.configstring (CS_STATUSBAR, dm_statusbar); else gi.configstring (CS_STATUSBAR, single_statusbar); //--------------- // help icon for statusbar gi.imageindex ("i_help"); level.pic_health = gi.imageindex ("i_health"); gi.imageindex ("help"); gi.imageindex ("field_3"); if (!st.gravity) gi.cvar_set("sv_gravity", "800"); else gi.cvar_set("sv_gravity", st.gravity); snd_fry = gi.soundindex ("player/fry.wav"); // standing in lava / slime PrecacheItem (FindItem ("Blaster")); gi.soundindex ("player/lava1.wav"); gi.soundindex ("player/lava2.wav"); gi.soundindex ("misc/pc_up.wav"); gi.soundindex ("misc/talk1.wav"); gi.soundindex ("misc/udeath.wav"); // gibs gi.soundindex ("items/respawn1.wav"); // sexed sounds gi.soundindex ("*death1.wav"); gi.soundindex ("*death2.wav"); gi.soundindex ("*death3.wav"); gi.soundindex ("*death4.wav"); gi.soundindex ("*fall1.wav"); gi.soundindex ("*fall2.wav"); gi.soundindex ("*gurp1.wav"); // drowning damage gi.soundindex ("*gurp2.wav"); gi.soundindex ("*jump1.wav"); // player jump gi.soundindex ("*pain25_1.wav"); gi.soundindex ("*pain25_2.wav"); gi.soundindex ("*pain50_1.wav"); gi.soundindex ("*pain50_2.wav"); gi.soundindex ("*pain75_1.wav"); gi.soundindex ("*pain75_2.wav"); gi.soundindex ("*pain100_1.wav"); gi.soundindex ("*pain100_2.wav"); // sexed models // THIS ORDER MUST MATCH THE DEFINES IN g_local.h // you can add more, max 19 (pete change) // these models are only loaded in coop or deathmatch. not singleplayer. if (coop->value || deathmatch->value) { gi.modelindex ("#w_blaster.md2"); gi.modelindex ("#w_shotgun.md2"); gi.modelindex ("#w_sshotgun.md2"); gi.modelindex ("#w_machinegun.md2"); gi.modelindex ("#w_chaingun.md2"); gi.modelindex ("#a_grenades.md2"); gi.modelindex ("#w_glauncher.md2"); gi.modelindex ("#w_rlauncher.md2"); gi.modelindex ("#w_hyperblaster.md2"); gi.modelindex ("#w_railgun.md2"); gi.modelindex ("#w_bfg.md2"); gi.modelindex ("#w_phalanx.md2"); gi.modelindex ("#w_ripper.md2"); } //------------------- gi.soundindex ("player/gasp1.wav"); // gasping for air gi.soundindex ("player/gasp2.wav"); // head breaking surface, not gasping gi.soundindex ("player/watr_in.wav"); // feet hitting water gi.soundindex ("player/watr_out.wav"); // feet leaving water gi.soundindex ("player/watr_un.wav"); // head going underwater gi.soundindex ("player/u_breath1.wav"); gi.soundindex ("player/u_breath2.wav"); gi.soundindex ("items/pkup.wav"); // bonus item pickup gi.soundindex ("world/land.wav"); // landing thud gi.soundindex ("misc/h2ohit1.wav"); // landing splash gi.soundindex ("items/damage.wav"); gi.soundindex ("items/protect.wav"); gi.soundindex ("items/protect4.wav"); gi.soundindex ("weapons/noammo.wav"); gi.soundindex ("infantry/inflies1.wav"); sm_meat_index = gi.modelindex ("models/objects/gibs/sm_meat/tris.md2"); gi.modelindex ("models/objects/gibs/arm/tris.md2"); gi.modelindex ("models/objects/gibs/bone/tris.md2"); gi.modelindex ("models/objects/gibs/bone2/tris.md2"); gi.modelindex ("models/objects/gibs/chest/tris.md2"); gi.modelindex ("models/objects/gibs/skull/tris.md2"); gi.modelindex ("models/objects/gibs/head2/tris.md2"); // // Setup light animation tables. 'a' is total darkness, 'z' is doublebright. // // 0 normal gi.configstring(CS_LIGHTS+0, "m"); // 1 FLICKER (first variety) gi.configstring(CS_LIGHTS+1, "mmnmmommommnonmmonqnmmo"); // 2 SLOW STRONG PULSE gi.configstring(CS_LIGHTS+2, "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba"); // 3 CANDLE (first variety) gi.configstring(CS_LIGHTS+3, "mmmmmaaaaammmmmaaaaaabcdefgabcdefg"); // 4 FAST STROBE gi.configstring(CS_LIGHTS+4, "mamamamamama"); // 5 GENTLE PULSE 1 gi.configstring(CS_LIGHTS+5,"jklmnopqrstuvwxyzyxwvutsrqponmlkj"); // 6 FLICKER (second variety) gi.configstring(CS_LIGHTS+6, "nmonqnmomnmomomno"); // 7 CANDLE (second variety) gi.configstring(CS_LIGHTS+7, "mmmaaaabcdefgmmmmaaaammmaamm"); // 8 CANDLE (third variety) gi.configstring(CS_LIGHTS+8, "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa"); // 9 SLOW STROBE (fourth variety) gi.configstring(CS_LIGHTS+9, "aaaaaaaazzzzzzzz"); // 10 FLUORESCENT FLICKER gi.configstring(CS_LIGHTS+10, "mmamammmmammamamaaamammma"); // 11 SLOW PULSE NOT FADE TO BLACK gi.configstring(CS_LIGHTS+11, "abcdefghijklmnopqrrqponmlkjihgfedcba"); // styles 32-62 are assigned by the light program for switchable lights // 63 testing gi.configstring(CS_LIGHTS+63, "a"); }
411
0.874701
1
0.874701
game-dev
MEDIA
0.733952
game-dev
0.554427
1
0.554427
rbfx/rbfx
5,691
Source/ThirdParty/openssl/crypto/engine/eng_cnf.c
/* * Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the OpenSSL license (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include "eng_local.h" #include <openssl/conf.h> /* #define ENGINE_CONF_DEBUG */ /* ENGINE config module */ static const char *skip_dot(const char *name) { const char *p = strchr(name, '.'); if (p != NULL) return p + 1; return name; } static STACK_OF(ENGINE) *initialized_engines = NULL; static int int_engine_init(ENGINE *e) { if (!ENGINE_init(e)) return 0; if (!initialized_engines) initialized_engines = sk_ENGINE_new_null(); if (!initialized_engines || !sk_ENGINE_push(initialized_engines, e)) { ENGINE_finish(e); return 0; } return 1; } static int int_engine_configure(const char *name, const char *value, const CONF *cnf) { int i; int ret = 0; long do_init = -1; STACK_OF(CONF_VALUE) *ecmds; CONF_VALUE *ecmd = NULL; const char *ctrlname, *ctrlvalue; ENGINE *e = NULL; int soft = 0; name = skip_dot(name); #ifdef ENGINE_CONF_DEBUG fprintf(stderr, "Configuring engine %s\n", name); #endif /* Value is a section containing ENGINE commands */ ecmds = NCONF_get_section(cnf, value); if (!ecmds) { ENGINEerr(ENGINE_F_INT_ENGINE_CONFIGURE, ENGINE_R_ENGINE_SECTION_ERROR); return 0; } for (i = 0; i < sk_CONF_VALUE_num(ecmds); i++) { ecmd = sk_CONF_VALUE_value(ecmds, i); ctrlname = skip_dot(ecmd->name); ctrlvalue = ecmd->value; #ifdef ENGINE_CONF_DEBUG fprintf(stderr, "ENGINE conf: doing ctrl(%s,%s)\n", ctrlname, ctrlvalue); #endif /* First handle some special pseudo ctrls */ /* Override engine name to use */ if (strcmp(ctrlname, "engine_id") == 0) name = ctrlvalue; else if (strcmp(ctrlname, "soft_load") == 0) soft = 1; /* Load a dynamic ENGINE */ else if (strcmp(ctrlname, "dynamic_path") == 0) { e = ENGINE_by_id("dynamic"); if (!e) goto err; if (!ENGINE_ctrl_cmd_string(e, "SO_PATH", ctrlvalue, 0)) goto err; if (!ENGINE_ctrl_cmd_string(e, "LIST_ADD", "2", 0)) goto err; if (!ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0)) goto err; } /* ... add other pseudos here ... */ else { /* * At this point we need an ENGINE structural reference if we * don't already have one. */ if (!e) { e = ENGINE_by_id(name); if (!e && soft) { ERR_clear_error(); return 1; } if (!e) goto err; } /* * Allow "EMPTY" to mean no value: this allows a valid "value" to * be passed to ctrls of type NO_INPUT */ if (strcmp(ctrlvalue, "EMPTY") == 0) ctrlvalue = NULL; if (strcmp(ctrlname, "init") == 0) { if (!NCONF_get_number_e(cnf, value, "init", &do_init)) goto err; if (do_init == 1) { if (!int_engine_init(e)) goto err; } else if (do_init != 0) { ENGINEerr(ENGINE_F_INT_ENGINE_CONFIGURE, ENGINE_R_INVALID_INIT_VALUE); goto err; } } else if (strcmp(ctrlname, "default_algorithms") == 0) { if (!ENGINE_set_default_string(e, ctrlvalue)) goto err; } else if (!ENGINE_ctrl_cmd_string(e, ctrlname, ctrlvalue, 0)) goto err; } } if (e && (do_init == -1) && !int_engine_init(e)) { ecmd = NULL; goto err; } ret = 1; err: if (ret != 1) { ENGINEerr(ENGINE_F_INT_ENGINE_CONFIGURE, ENGINE_R_ENGINE_CONFIGURATION_ERROR); if (ecmd) ERR_add_error_data(6, "section=", ecmd->section, ", name=", ecmd->name, ", value=", ecmd->value); } ENGINE_free(e); return ret; } static int int_engine_module_init(CONF_IMODULE *md, const CONF *cnf) { STACK_OF(CONF_VALUE) *elist; CONF_VALUE *cval; int i; #ifdef ENGINE_CONF_DEBUG fprintf(stderr, "Called engine module: name %s, value %s\n", CONF_imodule_get_name(md), CONF_imodule_get_value(md)); #endif /* Value is a section containing ENGINEs to configure */ elist = NCONF_get_section(cnf, CONF_imodule_get_value(md)); if (!elist) { ENGINEerr(ENGINE_F_INT_ENGINE_MODULE_INIT, ENGINE_R_ENGINES_SECTION_ERROR); return 0; } for (i = 0; i < sk_CONF_VALUE_num(elist); i++) { cval = sk_CONF_VALUE_value(elist, i); if (!int_engine_configure(cval->name, cval->value, cnf)) return 0; } return 1; } static void int_engine_module_finish(CONF_IMODULE *md) { ENGINE *e; while ((e = sk_ENGINE_pop(initialized_engines))) ENGINE_finish(e); sk_ENGINE_free(initialized_engines); initialized_engines = NULL; } void ENGINE_add_conf_module(void) { CONF_module_add("engines", int_engine_module_init, int_engine_module_finish); }
411
0.918549
1
0.918549
game-dev
MEDIA
0.291668
game-dev
0.81311
1
0.81311
magefree/mage
2,095
Mage/src/main/java/mage/abilities/common/DealsCombatDamageToAPlayerTriggeredAbility.java
package mage.abilities.common; import mage.abilities.TriggeredAbilityImpl; import mage.abilities.effects.Effect; import mage.constants.Zone; import mage.game.Game; import mage.game.events.DamagedEvent; import mage.game.events.GameEvent; import mage.target.targetpointer.FixedTarget; /** * @author BetaSteward_at_googlemail.com */ public class DealsCombatDamageToAPlayerTriggeredAbility extends TriggeredAbilityImpl { protected final boolean setTargetPointer; public DealsCombatDamageToAPlayerTriggeredAbility(Effect effect) { this(effect, false); } public DealsCombatDamageToAPlayerTriggeredAbility(Effect effect, boolean optional) { this(effect, optional, false); } public DealsCombatDamageToAPlayerTriggeredAbility(Effect effect, boolean optional, boolean setTargetPointer) { super(Zone.BATTLEFIELD, effect, optional); this.setTargetPointer = setTargetPointer; setTriggerPhrase(getWhen() + "{this} deals combat damage to a player, "); this.withRuleTextReplacement(true); } protected DealsCombatDamageToAPlayerTriggeredAbility(final DealsCombatDamageToAPlayerTriggeredAbility ability) { super(ability); this.setTargetPointer = ability.setTargetPointer; } @Override public DealsCombatDamageToAPlayerTriggeredAbility copy() { return new DealsCombatDamageToAPlayerTriggeredAbility(this); } @Override public boolean checkEventType(GameEvent event, Game game) { return event.getType() == GameEvent.EventType.DAMAGED_PLAYER; } @Override public boolean checkTrigger(GameEvent event, Game game) { if (!event.getSourceId().equals(getSourceId()) || !((DamagedEvent) event).isCombatDamage()) { return false; } getAllEffects().setValue("damage", event.getAmount()); getAllEffects().setValue("damagedPlayer", event.getPlayerId()); if (setTargetPointer) { getAllEffects().setTargetPointer(new FixedTarget(event.getPlayerId())); } return true; } }
411
0.956359
1
0.956359
game-dev
MEDIA
0.960404
game-dev
0.955218
1
0.955218
armory3d/armory
17,549
lib/haxebullet/bullet/BulletCollision/NarrowPhaseCollision/btVoronoiSimplexSolver.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. Elsevier CDROM license agreements grants nonexclusive license to use the software for any purpose, commercial or non-commercial as long as the following credit is included identifying the original source of the software: Parts of the source are "from the book Real-Time Collision Detection by Christer Ericson, published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc." */ #include "btVoronoiSimplexSolver.h" #define VERTA 0 #define VERTB 1 #define VERTC 2 #define VERTD 3 #define CATCH_DEGENERATE_TETRAHEDRON 1 void btVoronoiSimplexSolver::removeVertex(int index) { btAssert(m_numVertices>0); m_numVertices--; m_simplexVectorW[index] = m_simplexVectorW[m_numVertices]; m_simplexPointsP[index] = m_simplexPointsP[m_numVertices]; m_simplexPointsQ[index] = m_simplexPointsQ[m_numVertices]; } void btVoronoiSimplexSolver::reduceVertices (const btUsageBitfield& usedVerts) { if ((numVertices() >= 4) && (!usedVerts.usedVertexD)) removeVertex(3); if ((numVertices() >= 3) && (!usedVerts.usedVertexC)) removeVertex(2); if ((numVertices() >= 2) && (!usedVerts.usedVertexB)) removeVertex(1); if ((numVertices() >= 1) && (!usedVerts.usedVertexA)) removeVertex(0); } //clear the simplex, remove all the vertices void btVoronoiSimplexSolver::reset() { m_cachedValidClosest = false; m_numVertices = 0; m_needsUpdate = true; m_lastW = btVector3(btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT),btScalar(BT_LARGE_FLOAT)); m_cachedBC.reset(); } //add a vertex void btVoronoiSimplexSolver::addVertex(const btVector3& w, const btVector3& p, const btVector3& q) { m_lastW = w; m_needsUpdate = true; m_simplexVectorW[m_numVertices] = w; m_simplexPointsP[m_numVertices] = p; m_simplexPointsQ[m_numVertices] = q; m_numVertices++; } bool btVoronoiSimplexSolver::updateClosestVectorAndPoints() { if (m_needsUpdate) { m_cachedBC.reset(); m_needsUpdate = false; switch (numVertices()) { case 0: m_cachedValidClosest = false; break; case 1: { m_cachedP1 = m_simplexPointsP[0]; m_cachedP2 = m_simplexPointsQ[0]; m_cachedV = m_cachedP1-m_cachedP2; //== m_simplexVectorW[0] m_cachedBC.reset(); m_cachedBC.setBarycentricCoordinates(btScalar(1.),btScalar(0.),btScalar(0.),btScalar(0.)); m_cachedValidClosest = m_cachedBC.isValid(); break; }; case 2: { //closest point origin from line segment const btVector3& from = m_simplexVectorW[0]; const btVector3& to = m_simplexVectorW[1]; btVector3 nearest; btVector3 p (btScalar(0.),btScalar(0.),btScalar(0.)); btVector3 diff = p - from; btVector3 v = to - from; btScalar t = v.dot(diff); if (t > 0) { btScalar dotVV = v.dot(v); if (t < dotVV) { t /= dotVV; diff -= t*v; m_cachedBC.m_usedVertices.usedVertexA = true; m_cachedBC.m_usedVertices.usedVertexB = true; } else { t = 1; diff -= v; //reduce to 1 point m_cachedBC.m_usedVertices.usedVertexB = true; } } else { t = 0; //reduce to 1 point m_cachedBC.m_usedVertices.usedVertexA = true; } m_cachedBC.setBarycentricCoordinates(1-t,t); nearest = from + t*v; m_cachedP1 = m_simplexPointsP[0] + t * (m_simplexPointsP[1] - m_simplexPointsP[0]); m_cachedP2 = m_simplexPointsQ[0] + t * (m_simplexPointsQ[1] - m_simplexPointsQ[0]); m_cachedV = m_cachedP1 - m_cachedP2; reduceVertices(m_cachedBC.m_usedVertices); m_cachedValidClosest = m_cachedBC.isValid(); break; } case 3: { //closest point origin from triangle btVector3 p (btScalar(0.),btScalar(0.),btScalar(0.)); const btVector3& a = m_simplexVectorW[0]; const btVector3& b = m_simplexVectorW[1]; const btVector3& c = m_simplexVectorW[2]; closestPtPointTriangle(p,a,b,c,m_cachedBC); m_cachedP1 = m_simplexPointsP[0] * m_cachedBC.m_barycentricCoords[0] + m_simplexPointsP[1] * m_cachedBC.m_barycentricCoords[1] + m_simplexPointsP[2] * m_cachedBC.m_barycentricCoords[2]; m_cachedP2 = m_simplexPointsQ[0] * m_cachedBC.m_barycentricCoords[0] + m_simplexPointsQ[1] * m_cachedBC.m_barycentricCoords[1] + m_simplexPointsQ[2] * m_cachedBC.m_barycentricCoords[2]; m_cachedV = m_cachedP1-m_cachedP2; reduceVertices (m_cachedBC.m_usedVertices); m_cachedValidClosest = m_cachedBC.isValid(); break; } case 4: { btVector3 p (btScalar(0.),btScalar(0.),btScalar(0.)); const btVector3& a = m_simplexVectorW[0]; const btVector3& b = m_simplexVectorW[1]; const btVector3& c = m_simplexVectorW[2]; const btVector3& d = m_simplexVectorW[3]; bool hasSeperation = closestPtPointTetrahedron(p,a,b,c,d,m_cachedBC); if (hasSeperation) { m_cachedP1 = m_simplexPointsP[0] * m_cachedBC.m_barycentricCoords[0] + m_simplexPointsP[1] * m_cachedBC.m_barycentricCoords[1] + m_simplexPointsP[2] * m_cachedBC.m_barycentricCoords[2] + m_simplexPointsP[3] * m_cachedBC.m_barycentricCoords[3]; m_cachedP2 = m_simplexPointsQ[0] * m_cachedBC.m_barycentricCoords[0] + m_simplexPointsQ[1] * m_cachedBC.m_barycentricCoords[1] + m_simplexPointsQ[2] * m_cachedBC.m_barycentricCoords[2] + m_simplexPointsQ[3] * m_cachedBC.m_barycentricCoords[3]; m_cachedV = m_cachedP1-m_cachedP2; reduceVertices (m_cachedBC.m_usedVertices); } else { // printf("sub distance got penetration\n"); if (m_cachedBC.m_degenerate) { m_cachedValidClosest = false; } else { m_cachedValidClosest = true; //degenerate case == false, penetration = true + zero m_cachedV.setValue(btScalar(0.),btScalar(0.),btScalar(0.)); } break; } m_cachedValidClosest = m_cachedBC.isValid(); //closest point origin from tetrahedron break; } default: { m_cachedValidClosest = false; } }; } return m_cachedValidClosest; } //return/calculate the closest vertex bool btVoronoiSimplexSolver::closest(btVector3& v) { bool succes = updateClosestVectorAndPoints(); v = m_cachedV; return succes; } btScalar btVoronoiSimplexSolver::maxVertex() { int i, numverts = numVertices(); btScalar maxV = btScalar(0.); for (i=0;i<numverts;i++) { btScalar curLen2 = m_simplexVectorW[i].length2(); if (maxV < curLen2) maxV = curLen2; } return maxV; } //return the current simplex int btVoronoiSimplexSolver::getSimplex(btVector3 *pBuf, btVector3 *qBuf, btVector3 *yBuf) const { int i; for (i=0;i<numVertices();i++) { yBuf[i] = m_simplexVectorW[i]; pBuf[i] = m_simplexPointsP[i]; qBuf[i] = m_simplexPointsQ[i]; } return numVertices(); } bool btVoronoiSimplexSolver::inSimplex(const btVector3& w) { bool found = false; int i, numverts = numVertices(); //btScalar maxV = btScalar(0.); //w is in the current (reduced) simplex for (i=0;i<numverts;i++) { #ifdef BT_USE_EQUAL_VERTEX_THRESHOLD if ( m_simplexVectorW[i].distance2(w) <= m_equalVertexThreshold) #else if (m_simplexVectorW[i] == w) #endif { found = true; break; } } //check in case lastW is already removed if (w == m_lastW) return true; return found; } void btVoronoiSimplexSolver::backup_closest(btVector3& v) { v = m_cachedV; } bool btVoronoiSimplexSolver::emptySimplex() const { return (numVertices() == 0); } void btVoronoiSimplexSolver::compute_points(btVector3& p1, btVector3& p2) { updateClosestVectorAndPoints(); p1 = m_cachedP1; p2 = m_cachedP2; } bool btVoronoiSimplexSolver::closestPtPointTriangle(const btVector3& p, const btVector3& a, const btVector3& b, const btVector3& c,btSubSimplexClosestResult& result) { result.m_usedVertices.reset(); // Check if P in vertex region outside A btVector3 ab = b - a; btVector3 ac = c - a; btVector3 ap = p - a; btScalar d1 = ab.dot(ap); btScalar d2 = ac.dot(ap); if (d1 <= btScalar(0.0) && d2 <= btScalar(0.0)) { result.m_closestPointOnSimplex = a; result.m_usedVertices.usedVertexA = true; result.setBarycentricCoordinates(1,0,0); return true;// a; // barycentric coordinates (1,0,0) } // Check if P in vertex region outside B btVector3 bp = p - b; btScalar d3 = ab.dot(bp); btScalar d4 = ac.dot(bp); if (d3 >= btScalar(0.0) && d4 <= d3) { result.m_closestPointOnSimplex = b; result.m_usedVertices.usedVertexB = true; result.setBarycentricCoordinates(0,1,0); return true; // b; // barycentric coordinates (0,1,0) } // Check if P in edge region of AB, if so return projection of P onto AB btScalar vc = d1*d4 - d3*d2; if (vc <= btScalar(0.0) && d1 >= btScalar(0.0) && d3 <= btScalar(0.0)) { btScalar v = d1 / (d1 - d3); result.m_closestPointOnSimplex = a + v * ab; result.m_usedVertices.usedVertexA = true; result.m_usedVertices.usedVertexB = true; result.setBarycentricCoordinates(1-v,v,0); return true; //return a + v * ab; // barycentric coordinates (1-v,v,0) } // Check if P in vertex region outside C btVector3 cp = p - c; btScalar d5 = ab.dot(cp); btScalar d6 = ac.dot(cp); if (d6 >= btScalar(0.0) && d5 <= d6) { result.m_closestPointOnSimplex = c; result.m_usedVertices.usedVertexC = true; result.setBarycentricCoordinates(0,0,1); return true;//c; // barycentric coordinates (0,0,1) } // Check if P in edge region of AC, if so return projection of P onto AC btScalar vb = d5*d2 - d1*d6; if (vb <= btScalar(0.0) && d2 >= btScalar(0.0) && d6 <= btScalar(0.0)) { btScalar w = d2 / (d2 - d6); result.m_closestPointOnSimplex = a + w * ac; result.m_usedVertices.usedVertexA = true; result.m_usedVertices.usedVertexC = true; result.setBarycentricCoordinates(1-w,0,w); return true; //return a + w * ac; // barycentric coordinates (1-w,0,w) } // Check if P in edge region of BC, if so return projection of P onto BC btScalar va = d3*d6 - d5*d4; if (va <= btScalar(0.0) && (d4 - d3) >= btScalar(0.0) && (d5 - d6) >= btScalar(0.0)) { btScalar w = (d4 - d3) / ((d4 - d3) + (d5 - d6)); result.m_closestPointOnSimplex = b + w * (c - b); result.m_usedVertices.usedVertexB = true; result.m_usedVertices.usedVertexC = true; result.setBarycentricCoordinates(0,1-w,w); return true; // return b + w * (c - b); // barycentric coordinates (0,1-w,w) } // P inside face region. Compute Q through its barycentric coordinates (u,v,w) btScalar denom = btScalar(1.0) / (va + vb + vc); btScalar v = vb * denom; btScalar w = vc * denom; result.m_closestPointOnSimplex = a + ab * v + ac * w; result.m_usedVertices.usedVertexA = true; result.m_usedVertices.usedVertexB = true; result.m_usedVertices.usedVertexC = true; result.setBarycentricCoordinates(1-v-w,v,w); return true; // return a + ab * v + ac * w; // = u*a + v*b + w*c, u = va * denom = btScalar(1.0) - v - w } /// Test if point p and d lie on opposite sides of plane through abc int btVoronoiSimplexSolver::pointOutsideOfPlane(const btVector3& p, const btVector3& a, const btVector3& b, const btVector3& c, const btVector3& d) { btVector3 normal = (b-a).cross(c-a); btScalar signp = (p - a).dot(normal); // [AP AB AC] btScalar signd = (d - a).dot( normal); // [AD AB AC] #ifdef CATCH_DEGENERATE_TETRAHEDRON #ifdef BT_USE_DOUBLE_PRECISION if (signd * signd < (btScalar(1e-8) * btScalar(1e-8))) { return -1; } #else if (signd * signd < (btScalar(1e-4) * btScalar(1e-4))) { // printf("affine dependent/degenerate\n");// return -1; } #endif #endif // Points on opposite sides if expression signs are opposite return signp * signd < btScalar(0.); } bool btVoronoiSimplexSolver::closestPtPointTetrahedron(const btVector3& p, const btVector3& a, const btVector3& b, const btVector3& c, const btVector3& d, btSubSimplexClosestResult& finalResult) { btSubSimplexClosestResult tempResult; // Start out assuming point inside all halfspaces, so closest to itself finalResult.m_closestPointOnSimplex = p; finalResult.m_usedVertices.reset(); finalResult.m_usedVertices.usedVertexA = true; finalResult.m_usedVertices.usedVertexB = true; finalResult.m_usedVertices.usedVertexC = true; finalResult.m_usedVertices.usedVertexD = true; int pointOutsideABC = pointOutsideOfPlane(p, a, b, c, d); int pointOutsideACD = pointOutsideOfPlane(p, a, c, d, b); int pointOutsideADB = pointOutsideOfPlane(p, a, d, b, c); int pointOutsideBDC = pointOutsideOfPlane(p, b, d, c, a); if (pointOutsideABC < 0 || pointOutsideACD < 0 || pointOutsideADB < 0 || pointOutsideBDC < 0) { finalResult.m_degenerate = true; return false; } if (!pointOutsideABC && !pointOutsideACD && !pointOutsideADB && !pointOutsideBDC) { return false; } btScalar bestSqDist = FLT_MAX; // If point outside face abc then compute closest point on abc if (pointOutsideABC) { closestPtPointTriangle(p, a, b, c,tempResult); btVector3 q = tempResult.m_closestPointOnSimplex; btScalar sqDist = (q - p).dot( q - p); // Update best closest point if (squared) distance is less than current best if (sqDist < bestSqDist) { bestSqDist = sqDist; finalResult.m_closestPointOnSimplex = q; //convert result bitmask! finalResult.m_usedVertices.reset(); finalResult.m_usedVertices.usedVertexA = tempResult.m_usedVertices.usedVertexA; finalResult.m_usedVertices.usedVertexB = tempResult.m_usedVertices.usedVertexB; finalResult.m_usedVertices.usedVertexC = tempResult.m_usedVertices.usedVertexC; finalResult.setBarycentricCoordinates( tempResult.m_barycentricCoords[VERTA], tempResult.m_barycentricCoords[VERTB], tempResult.m_barycentricCoords[VERTC], 0 ); } } // Repeat test for face acd if (pointOutsideACD) { closestPtPointTriangle(p, a, c, d,tempResult); btVector3 q = tempResult.m_closestPointOnSimplex; //convert result bitmask! btScalar sqDist = (q - p).dot( q - p); if (sqDist < bestSqDist) { bestSqDist = sqDist; finalResult.m_closestPointOnSimplex = q; finalResult.m_usedVertices.reset(); finalResult.m_usedVertices.usedVertexA = tempResult.m_usedVertices.usedVertexA; finalResult.m_usedVertices.usedVertexC = tempResult.m_usedVertices.usedVertexB; finalResult.m_usedVertices.usedVertexD = tempResult.m_usedVertices.usedVertexC; finalResult.setBarycentricCoordinates( tempResult.m_barycentricCoords[VERTA], 0, tempResult.m_barycentricCoords[VERTB], tempResult.m_barycentricCoords[VERTC] ); } } // Repeat test for face adb if (pointOutsideADB) { closestPtPointTriangle(p, a, d, b,tempResult); btVector3 q = tempResult.m_closestPointOnSimplex; //convert result bitmask! btScalar sqDist = (q - p).dot( q - p); if (sqDist < bestSqDist) { bestSqDist = sqDist; finalResult.m_closestPointOnSimplex = q; finalResult.m_usedVertices.reset(); finalResult.m_usedVertices.usedVertexA = tempResult.m_usedVertices.usedVertexA; finalResult.m_usedVertices.usedVertexB = tempResult.m_usedVertices.usedVertexC; finalResult.m_usedVertices.usedVertexD = tempResult.m_usedVertices.usedVertexB; finalResult.setBarycentricCoordinates( tempResult.m_barycentricCoords[VERTA], tempResult.m_barycentricCoords[VERTC], 0, tempResult.m_barycentricCoords[VERTB] ); } } // Repeat test for face bdc if (pointOutsideBDC) { closestPtPointTriangle(p, b, d, c,tempResult); btVector3 q = tempResult.m_closestPointOnSimplex; //convert result bitmask! btScalar sqDist = (q - p).dot( q - p); if (sqDist < bestSqDist) { bestSqDist = sqDist; finalResult.m_closestPointOnSimplex = q; finalResult.m_usedVertices.reset(); // finalResult.m_usedVertices.usedVertexB = tempResult.m_usedVertices.usedVertexA; finalResult.m_usedVertices.usedVertexC = tempResult.m_usedVertices.usedVertexC; finalResult.m_usedVertices.usedVertexD = tempResult.m_usedVertices.usedVertexB; finalResult.setBarycentricCoordinates( 0, tempResult.m_barycentricCoords[VERTA], tempResult.m_barycentricCoords[VERTC], tempResult.m_barycentricCoords[VERTB] ); } } //help! we ended up full ! if (finalResult.m_usedVertices.usedVertexA && finalResult.m_usedVertices.usedVertexB && finalResult.m_usedVertices.usedVertexC && finalResult.m_usedVertices.usedVertexD) { return true; } return true; }
411
0.919712
1
0.919712
game-dev
MEDIA
0.809446
game-dev
0.993487
1
0.993487
atlasacademy/fgo-game-data-api
15,645
export/niceexport.py
import json from collections import defaultdict from pathlib import Path from typing import Any, Callable, NamedTuple, Union from app.config import Settings from app.core.utils import get_traits_list from app.schemas.common import Region from app.schemas.enums import TRAIT_NAME, Trait, get_class_name from app.schemas.gameenums import ( AI_COND_CHECK_NAME, AI_COND_NAME, AI_COND_PARAMETER_NAME, AI_COND_REFINE_NAME, AI_COND_TARGET_NAME, ATTRIBUTE_NAME, BUFF_ACTION_NAME, BUFF_LIMIT_NAME, BUFF_TYPE_NAME, CARD_TYPE_NAME, GIFT_TYPE_NAME, SERVANT_FRAME_TYPE_NAME, AiCond, BuffAction, ) CONSTANT_INCLUDE = { "ATTACK_RATE", "ATTACK_RATE_RANDOM_MAX", "ATTACK_RATE_RANDOM_MIN", "BACKSIDE_CLASS_IMAGE_ID", "BACKSIDE_SVT_EQUIP_IMAGE_ID", "BACKSIDE_SVT_IMAGE_ID", "BATTLE_EFFECT_ID_AVOIDANCE", "BATTLE_EFFECT_ID_AVOIDANCE_PIERCE", "BATTLE_EFFECT_ID_INVINCIBLE", "BATTLE_EFFECT_ID_INVINCIBLE_PIERCE", "BATTLE_ITEM_DISP_COLUMN", "BP_EXPRESSION", "CHAINBONUS_ARTS_RATE", "CHAINBONUS_BUSTER_RATE", "CHAINBONUS_QUICK", "COMMAND_ARTS", "COMMAND_BUSTER", "COMMAND_CARD_PRM_UP_MAX", "COMMAND_CODE_DETACHING_ITEM_ID", "COMMAND_QUICK", "CRITICAL_ATTACK_RATE", "CRITICAL_INDIVIDUALITY", "CRITICAL_RATE_PER_STAR", "CRITICAL_STAR_RATE", "CRITICAL_TD_POINT_RATE", "DECK_MAX", "ENEMY_ATTACK_RATE_ARTS", "ENEMY_ATTACK_RATE_BUSTER", "ENEMY_ATTACK_RATE_QUICK", "ENEMY_MAX_BATTLE_COUNT", "EXTRA_ATTACK_RATE_GRAND", "EXTRA_ATTACK_RATE_SINGLE", "EXTRA_CRITICAL_RATE", "FOLLOWER_LIST_EXPIRE_AT", "FOLLOWER_REFRESH_RESET_TIME", "FOLLOW_FRIEND_POINT", "FULL_TD_POINT", "HEROINE_CHANGECARDVOICE", "HYDE_SVT_ID", "JEKYLL_SVT_ID", "LARGE_SUCCESS_MULT_EXP", "LARGE_SUCCESS_RATE", "MASHU_CHANGE_QUEST_ID", "MASHU_CHANGE_WAR_ID", "MASHU_SVT_ID1", "MASHU_SVT_ID2", "MAX_BLACK_LIST_NUM", "MAX_COMMAND_SPELL", "MAX_DROP_FACTOR", "MAX_EVENT_POINT", "MAX_EXP_FACTOR", "MAX_FRIENDPOINT", "MAX_FRIENDPOINT_BOOST_ITEM_DAILY_RECEIVE", "MAX_FRIENDPOINT_BOOST_ITEM_USE", "MAX_FRIENDSHIP_RANK", "MAX_FRIEND_CODE", "MAX_FRIEND_HISTORY_NUM", "MAX_FRIEND_SHIP_UP_RATIO", "MAX_MANA", "MAX_NEAR_PRESENT_OFFSET_NUM", "MAX_PRESENT_BOX_HISTORY_NUM", "MAX_PRESENT_BOX_NUM", "MAX_PRESENT_RECEIVE_NUM", "MAX_QP", "MAX_QP_DROP_UP_RATIO", "MAX_QP_FACTOR", "MAX_RARE_PRI", "MAX_RP", "MAX_STONE", "MAX_USER_COMMAND_CODE", "MAX_USER_EQUIP_EXP_UP_RATIO", "MAX_USER_ITEM", "MAX_USER_LV", "MAX_USER_SVT", "MAX_USER_SVT_EQUIP", "MAX_USER_SVT_EQUIP_STORAGE", "MAX_USER_SVT_STORAGE", "MENU_CHANGE", "OVER_KILL_NP_RATE", "OVER_KILL_STAR_ADD", "OVER_KILL_STAR_RATE", "STAR_RATE_MAX", "STATUS_UP_ADJUST_ATK", "STATUS_UP_ADJUST_HP", "STATUS_UP_BUFF", "SUPER_SUCCESS_MULT_EXP", "SUPER_SUCCESS_RATE", "SUPPORT_DECK_MAX", "SWIMSUIT_MELT_SVT_ID", "TAMAMOCAT_STUN_BUFF_ID", "TAMAMOCAT_TREASURE_DEVICE_ID_1", "TAMAMOCAT_TREASURE_DEVICE_ID_2", "TEMPORARY_IGNORE_SLEEP_MODE_FOR_TREASURE_DEVICE_SVT_ID_1", "TEMPORARY_IGNORE_SLEEP_MODE_FOR_TREASURE_DEVICE_SVT_ID_2", "TREASUREDEVICE_ID_MASHU3", "FRIEND_NUM", "USER_COST", "USER_ACT", } def get_nice_constant(raw_data: Any) -> dict[str, int]: return { constant["name"]: constant["value"] for constant in raw_data if constant["name"] in CONSTANT_INCLUDE } CONSTANT_STR_INCLUDE = { "BIRTHDAY_BEFORE_VALENTINE_SVT_ID", "COIN_ROOM_CLOSED_MESSAGE", "COMBINE_SCENE_VOICE_RETURN", "COMBINE_SCENE_VOICE_WELCOME", "EFFECT_INVINCIBLE_AVOID_OFFSET_Z", "EVENT_BOARD_GAME_DICE_BUTTON_POS", "EVENT_BOARD_GAME_DICE_VOICE_INFO", "EVENT_BOARD_GAME_MAP_ID_LIST", "EVENT_BOARD_GAME_MAP_POSITION", "EVENT_BOARD_GAME_QUEST_ARRIVAL_VOICE_SVT_ID_LIST", "EVENT_ITEM_REPLACE_BEFORE_EVENT_NAME", "EVENT_ITEM_REPLACE_EVENT_NAME", "EVENT_SVT_WITH_GACHA_LIST", "EVENT_TOWER_FADEOUT_DELAY_TIME", "EXTEND_TURN_BUFF_TYPE", "FULL_SCREEN_NP_CHRS", "HIDE_DEFF_TYPE", "IGNORE_AURA_BUFF", "IGNORE_FORM_CHANGE_SVT_ID", "LEGACY_ASPECT_MOVIES", "MATERIAL_MAIN_INTERLUDE_WAR_ID", "NOT_REDUCE_COUNT_WITH_NO_DAMAGE_BUFF", "OPEN_MAIN_SCENARIO_TITLE", "PRESENT_BOX_FILTER_SVT_EQUIP_MATERIAL", "PROLOGUE_WAR_AFTER_QUEST_CLEAR_IDS", "PROLOGUE_WAR_IDS", "QPEVENT_NEXT_DISPLAY_DATA", "REPRINT_LAST_WAR_RAID_EVENT_ID_LIST", "SCENARIO_SPEED_DEFAULT", "SCENARIO_SPEED_HIGH", "SCENARIO_SPEED_LOW", "SCENARIO_SPEED_STEP", "SHOP_SCENE_VOICE_ANONYMOUS", "SHOP_SCENE_VOICE_BACK1", "SHOP_SCENE_VOICE_BACK2", "SHOP_SCENE_VOICE_CANCEL", "SHOP_SCENE_VOICE_DECIDE", "SHOP_SCENE_VOICE_EQFRAME", "SHOP_SCENE_VOICE_EQSTORAGE", "SHOP_SCENE_VOICE_EVENT", "SHOP_SCENE_VOICE_EXCHANGE", "SHOP_SCENE_VOICE_FRAGMENT", "SHOP_SCENE_VOICE_GRAIL_FRAGMENTS", "SHOP_SCENE_VOICE_MANA", "SHOP_SCENE_VOICE_RARE_PRI", "SHOP_SCENE_VOICE_SELL", "SHOP_SCENE_VOICE_SHOP04", "SHOP_SCENE_VOICE_SPECIAL", "SHOP_SCENE_VOICE_STARTUPSUMMON", "SHOP_SCENE_VOICE_STONE", "SHOP_SCENE_VOICE_SVTFRAME", "SHOP_SCENE_VOICE_SVTSTORAGE", "SHOP_SCENE_VOICE_WELCOME", "SHORT_DEAD_EFFECT_SHADOW_SVT_ID", "STAR_REFRESH_BUFF_TYPE", "SUB_PT_BUFF_INDIVI", "SVT_EXIT_PT_BUFF_INDIVI", "TIME_STATUS_COND_QUEST_DATA", "TOWEREVENT_TOWER_CLEAR_DISABLE", "WAR_BOARD_BATTLE_END_RESET_BUFF_TYPES", "WAR_BOARD_PROGRESS_SELF_BUFF_TYPES", "WAR_IDS_OF_COUNTING_QUEST_ONLY_REACHABLE_MAPS", "X_SCALE_APPLY_SVTIDS", } def get_nice_constant_str(raw_data: Any) -> dict[str, str]: return { constant["name"]: constant["value"] for constant in raw_data if constant["name"] in CONSTANT_STR_INCLUDE } def get_nice_gift(raw_gift: Any) -> dict[Any, Any]: return { "id": raw_gift["id"], "type": GIFT_TYPE_NAME[raw_gift["type"]], "objectId": raw_gift["objectId"], "priority": raw_gift["priority"], "num": raw_gift["num"], } def get_nice_class(raw_data: Any) -> Any: return [ { "id": class_data["id"], "className": get_class_name(class_data["id"]), "name": class_data["name"], "individuality": ( TRAIT_NAME.get(class_data["individuality"], Trait.unknown) if class_data["individuality"] else Trait.unknown ), "attackRate": class_data["attackRate"], "imageId": class_data["imageId"], "iconImageId": class_data["iconImageId"], "frameId": class_data["frameId"], "priority": class_data["priority"], "groupType": class_data["groupType"], "relationId": class_data["relationId"], "supportGroup": class_data["supportGroup"], "autoSelSupportType": class_data["autoSelSupportType"], } for class_data in raw_data ] def get_nice_attackrate(raw_data: Any) -> Any: return { get_class_name(class_data["id"]): class_data["attackRate"] for class_data in raw_data } def get_nice_card_data(raw_data: Any) -> Any: out_data: dict[str, dict[int, Any]] = {} for card in raw_data: card_id = card["id"] card_index = card["num"] card["individuality"] = [ trait.dict(exclude_unset=True) for trait in get_traits_list(card["individuality"]) ] card.pop("id") card.pop("num") if card_id in CARD_TYPE_NAME: card_name = CARD_TYPE_NAME[card_id] if card_name in out_data: out_data[card_name][card_index] = card else: out_data[card_name] = {card_index: card} return out_data def get_nice_attri_relation(raw_data: Any) -> Any: out_data: dict[str, dict[str, int]] = {} for attribute_relation in raw_data: atkAttri = ATTRIBUTE_NAME[attribute_relation["atkAttri"]] defAttri = ATTRIBUTE_NAME[attribute_relation["defAttri"]] attackRate = attribute_relation["attackRate"] if atkAttri in out_data: out_data[atkAttri][defAttri] = attackRate else: out_data[atkAttri] = {defAttri: attackRate} return out_data def get_nice_class_relation(raw_data: Any) -> Any: out_data: dict[str, dict[str, int]] = {} for class_relation in raw_data: atkAttri = get_class_name(class_relation["atkClass"]) defAttri = get_class_name(class_relation["defClass"]) if atkAttri and defAttri: attackRate = class_relation["attackRate"] if atkAttri in out_data: out_data[atkAttri][defAttri] = attackRate else: out_data[atkAttri] = {defAttri: attackRate} return out_data def get_nice_svt_exceed(raw_data: Any) -> Any: def find_previous_exceed_qp(rarity: int, exceed: int) -> int: previous_exceed = next( svt_exceed for svt_exceed in raw_data if svt_exceed["rarity"] == rarity and svt_exceed["exceedCount"] == exceed - 1 ) previous_exceed_qp: int = previous_exceed["qp"] return previous_exceed_qp out_data: dict[int, dict[int, dict[str, Union[int, str]]]] = defaultdict( lambda: defaultdict(dict) ) for svtExceed in raw_data: if svtExceed["exceedCount"] != 0: out_data[svtExceed["rarity"]][svtExceed["exceedCount"]] = { "qp": find_previous_exceed_qp( svtExceed["rarity"], svtExceed["exceedCount"] ), "addLvMax": svtExceed["addLvMax"], "frameType": SERVANT_FRAME_TYPE_NAME[svtExceed["frameType"]], } return out_data def get_nice_buff_action(raw_data: Any) -> Any: def get_max_rate(buff_types: list[int]) -> list[int]: return list( {buff["maxRate"] for buff in raw_data if buff["type"] in buff_types} ) with open( Path(__file__).parent / "BuffList.ActionList.json", "r", encoding="utf-8" ) as fp: data = json.load(fp) out_data = {} for buff_action in data: out_item = data[buff_action] out_item["limit"] = BUFF_LIMIT_NAME[out_item["limit"]] out_item["maxRate"] = get_max_rate( out_item["plusTypes"] + out_item["minusTypes"] ) out_item["plusTypes"] = [ BUFF_TYPE_NAME[bufft] for bufft in out_item["plusTypes"] ] out_item["minusTypes"] = [ BUFF_TYPE_NAME[bufft] for bufft in out_item["minusTypes"] ] out_data[BUFF_ACTION_NAME[BuffAction[buff_action].value]] = out_item return out_data def get_nice_ai_cond(region: Region, export_path: Path) -> None: with open( Path(__file__).parent / "AiConditionInformation.json", "r", encoding="utf-8" ) as fp: data = json.load(fp) out_data = {} for ai_cond in data: out_item = data[ai_cond] out_item["target"] = AI_COND_TARGET_NAME[out_item["target"]] out_item["paramater"] = AI_COND_PARAMETER_NAME[out_item["paramater"]] out_item["check"] = AI_COND_CHECK_NAME[out_item["check"]] out_item["refine"] = AI_COND_REFINE_NAME[out_item["refine"]] out_data[AI_COND_NAME[AiCond[ai_cond].value]] = out_item export_file = export_path / region.value / "NiceAiConditionInformation.json" with open(export_file, "w", encoding="utf-8") as fp: json.dump(out_data, fp, ensure_ascii=False) class ExportParam(NamedTuple): input: str converter: Callable[[Any], Any] output: str TO_EXPORT = [ ExportParam( input="mstConstant", converter=get_nice_constant, output="NiceConstant" ), ExportParam( input="mstConstantStr", converter=get_nice_constant_str, output="NiceConstantStr", ), ExportParam( input="mstClass", converter=get_nice_class, output="NiceClass", ), ExportParam( input="mstClass", converter=get_nice_attackrate, output="NiceClassAttackRate" ), ExportParam(input="mstCard", converter=get_nice_card_data, output="NiceCard"), ExportParam( input="mstAttriRelation", converter=get_nice_attri_relation, output="NiceAttributeRelation", ), ExportParam( input="mstClassRelation", converter=get_nice_class_relation, output="NiceClassRelation", ), ExportParam( input="mstBuff", converter=get_nice_buff_action, output="NiceBuffList.ActionList", ), ExportParam( input="mstSvtExceed", converter=get_nice_svt_exceed, output="NiceSvtGrailCost", ), ] def export_constant(region: Region, master_path: Path, export_path: Path) -> None: for export in TO_EXPORT: print(f"Exporting {export.input} ...") with open( master_path / "master" / f"{export.input}.json", "r", encoding="utf-8" ) as fp: raw_data = json.load(fp) export_file = export_path / region.value / f"{export.output}.json" with open(export_file, "w", encoding="utf-8") as fp: json.dump(export.converter(raw_data), fp, ensure_ascii=False) def export_nice_master_lvl(region: Region, master_path: Path, export_path: Path) -> Any: print("Exporting nice master level ...") constant_path = export_path / region.value / f"{TO_EXPORT[0].output}.json" with open(constant_path, "r", encoding="utf-8") as fp: constant = json.load(fp) with open(master_path / "master" / "mstUserExp.json", "r", encoding="utf-8") as fp: mstUserExp: list[dict[str, int]] = json.load(fp) with open(master_path / "master" / "mstGift.json", "r", encoding="utf-8") as fp: mstGiftId: dict[int, dict[str, int]] = { gift["id"]: gift for gift in json.load(fp) } def get_current_value(base: int, key: str, current: int) -> int: return base + sum(user_exp[key] for user_exp in mstUserExp[: current + 1]) def get_total_exp(current: int) -> int: if current == 0: return 0 else: return mstUserExp[current - 1]["exp"] nice_data = { lvl["lv"]: { "requiredExp": get_total_exp(lvli), "maxAp": get_current_value(constant["USER_ACT"], "addActMax", lvli), "maxCost": get_current_value(constant["USER_COST"], "addCostMax", lvli), "maxFriend": get_current_value( constant["FRIEND_NUM"], "addFriendMax", lvli ), "gift": ( get_nice_gift(mstGiftId[lvl["giftId"]]) if lvl["giftId"] != 0 else None ), } for lvli, lvl in enumerate(mstUserExp) } export_file = export_path / region.value / "NiceUserLevel.json" with open(export_file, "w", encoding="utf-8") as fp: json.dump(nice_data, fp, ensure_ascii=False) def main() -> None: settings = Settings() export_path = Path(__file__).resolve().parents[1] / "export" for region, region_data in settings.data.items(): print(region) export_constant(region, region_data.gamedata, export_path) export_nice_master_lvl(region, region_data.gamedata, export_path) get_nice_ai_cond(region, export_path) if __name__ == "__main__": main()
411
0.802046
1
0.802046
game-dev
MEDIA
0.927558
game-dev
0.952988
1
0.952988
PacktPublishing/CPP-Game-Development-By-Example
3,718
Chapter08/8.OpenGLProject/OpenGLProject/Dependencies/bullet/include/BulletCollision/CollisionShapes/btPolyhedralConvexShape.h
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef BT_POLYHEDRAL_CONVEX_SHAPE_H #define BT_POLYHEDRAL_CONVEX_SHAPE_H #include "LinearMath/btMatrix3x3.h" #include "btConvexInternalShape.h" class btConvexPolyhedron; ///The btPolyhedralConvexShape is an internal interface class for polyhedral convex shapes. ATTRIBUTE_ALIGNED16(class) btPolyhedralConvexShape : public btConvexInternalShape { protected: btConvexPolyhedron* m_polyhedron; public: BT_DECLARE_ALIGNED_ALLOCATOR(); btPolyhedralConvexShape(); virtual ~btPolyhedralConvexShape(); ///optional method mainly used to generate multiple contact points by clipping polyhedral features (faces/edges) ///experimental/work-in-progress virtual bool initializePolyhedralFeatures(int shiftVerticesByMargin=0); const btConvexPolyhedron* getConvexPolyhedron() const { return m_polyhedron; } //brute force implementations virtual btVector3 localGetSupportingVertexWithoutMargin(const btVector3& vec)const; virtual void batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors,btVector3* supportVerticesOut,int numVectors) const; virtual void calculateLocalInertia(btScalar mass,btVector3& inertia) const; virtual int getNumVertices() const = 0 ; virtual int getNumEdges() const = 0; virtual void getEdge(int i,btVector3& pa,btVector3& pb) const = 0; virtual void getVertex(int i,btVector3& vtx) const = 0; virtual int getNumPlanes() const = 0; virtual void getPlane(btVector3& planeNormal,btVector3& planeSupport,int i ) const = 0; // virtual int getIndex(int i) const = 0 ; virtual bool isInside(const btVector3& pt,btScalar tolerance) const = 0; }; ///The btPolyhedralConvexAabbCachingShape adds aabb caching to the btPolyhedralConvexShape class btPolyhedralConvexAabbCachingShape : public btPolyhedralConvexShape { btVector3 m_localAabbMin; btVector3 m_localAabbMax; bool m_isLocalAabbValid; protected: void setCachedLocalAabb (const btVector3& aabbMin, const btVector3& aabbMax) { m_isLocalAabbValid = true; m_localAabbMin = aabbMin; m_localAabbMax = aabbMax; } inline void getCachedLocalAabb (btVector3& aabbMin, btVector3& aabbMax) const { btAssert(m_isLocalAabbValid); aabbMin = m_localAabbMin; aabbMax = m_localAabbMax; } protected: btPolyhedralConvexAabbCachingShape(); public: inline void getNonvirtualAabb(const btTransform& trans,btVector3& aabbMin,btVector3& aabbMax, btScalar margin) const { //lazy evaluation of local aabb btAssert(m_isLocalAabbValid); btTransformAabb(m_localAabbMin,m_localAabbMax,margin,trans,aabbMin,aabbMax); } virtual void setLocalScaling(const btVector3& scaling); virtual void getAabb(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const; void recalcLocalAabb(); }; #endif //BT_POLYHEDRAL_CONVEX_SHAPE_H
411
0.862857
1
0.862857
game-dev
MEDIA
0.987196
game-dev
0.830072
1
0.830072
dphfox/rdc-2024-fusion-demo
3,111
src/Libraries/Fusion/Animation/unpackType.luau
--!strict --!nolint LocalUnused --!nolint LocalShadow local task = nil -- Disable usage of Roblox's task scheduler --[[ Unpacks an animatable type into an array of numbers. If the type is not animatable, an empty array will be returned. ]] local Package = script.Parent.Parent local Oklab = require(Package.Colour.Oklab) local function unpackType( value: unknown, typeString: string ): {number} if typeString == "number" then local value = value :: number return {value} elseif typeString == "CFrame" then local value = value :: CFrame -- FUTURE: is there a better way of doing this? doing distance -- calculations on `angle` may be incorrect local axis, angle = value:ToAxisAngle() return {value.X, value.Y, value.Z, axis.X, axis.Y, axis.Z, angle} elseif typeString == "Color3" then local value = value :: Color3 local lab = Oklab.fromSRGB(value) return {lab.X, lab.Y, lab.Z} elseif typeString == "ColorSequenceKeypoint" then local value = value :: ColorSequenceKeypoint local lab = Oklab.fromSRGB(value.Value) return {lab.X, lab.Y, lab.Z, value.Time} elseif typeString == "DateTime" then local value = value :: DateTime return {value.UnixTimestampMillis} elseif typeString == "NumberRange" then local value = value :: NumberRange return {value.Min, value.Max} elseif typeString == "NumberSequenceKeypoint" then local value = value :: NumberSequenceKeypoint return {value.Value, value.Time, value.Envelope} elseif typeString == "PhysicalProperties" then local value = value :: PhysicalProperties return {value.Density, value.Friction, value.Elasticity, value.FrictionWeight, value.ElasticityWeight} elseif typeString == "Ray" then local value = value :: Ray return {value.Origin.X, value.Origin.Y, value.Origin.Z, value.Direction.X, value.Direction.Y, value.Direction.Z} elseif typeString == "Rect" then local value = value :: Rect return {value.Min.X, value.Min.Y, value.Max.X, value.Max.Y} elseif typeString == "Region3" then local value = value :: Region3 -- FUTURE: support rotated Region3s if/when they become constructable return { value.CFrame.X, value.CFrame.Y, value.CFrame.Z, value.Size.X, value.Size.Y, value.Size.Z } elseif typeString == "Region3int16" then local value = value :: Region3int16 return {value.Min.X, value.Min.Y, value.Min.Z, value.Max.X, value.Max.Y, value.Max.Z} elseif typeString == "UDim" then local value = value :: UDim return {value.Scale, value.Offset} elseif typeString == "UDim2" then local value = value :: UDim2 return {value.X.Scale, value.X.Offset, value.Y.Scale, value.Y.Offset} elseif typeString == "Vector2" then local value = value :: Vector2 return {value.X, value.Y} elseif typeString == "Vector2int16" then local value = value :: Vector2int16 return {value.X, value.Y} elseif typeString == "Vector3" then local value = value :: Vector3 return {value.X, value.Y, value.Z} elseif typeString == "Vector3int16" then local value = value :: Vector3int16 return {value.X, value.Y, value.Z} else return {} end end return unpackType
411
0.715633
1
0.715633
game-dev
MEDIA
0.924357
game-dev
0.788057
1
0.788057
5zig/The-5zig-Mod
2,382
The 5zig Mod/src/eu/the5zig/mod/server/gomme/GommeHDRageModeListener.java
package eu.the5zig.mod.server.gomme; import eu.the5zig.mod.server.AbstractGameListener; import eu.the5zig.mod.server.GameState; import eu.the5zig.mod.server.IPatternResult; public class GommeHDRageModeListener extends AbstractGameListener<ServerGommeHD.RageMode> { @Override public Class<ServerGommeHD.RageMode> getGameMode() { return ServerGommeHD.RageMode.class; } @Override public boolean matchLobby(String lobby) { return lobby.equals("RageMode"); } @Override public void onMatch(ServerGommeHD.RageMode gameMode, String key, IPatternResult match) { if (gameMode.getState() == GameState.LOBBY) { if (key.equals("rm.lobby.starting")) { gameMode.setTime(System.currentTimeMillis() + Integer.parseInt(match.get(0)) * 1000L); } if (key.equals("rm.lobby.start")) { gameMode.setState(GameState.STARTING); } } if (gameMode.getState() == GameState.STARTING) { if (key.equals("rm.starting")) { gameMode.setTime(System.currentTimeMillis() + Integer.parseInt(match.get(0)) * 1000L); } if (key.equals("rm.start")) { gameMode.setState(GameState.GAME); gameMode.setTime(System.currentTimeMillis()); } } if (gameMode.getState() == GameState.GAME) { if (key.equals("rm.kill")) { gameMode.setKills(gameMode.getKills() + 1); gameMode.setKillStreak(gameMode.getKillStreak() + 1); gameMode.setEmeralds(gameMode.getEmeralds() + 1); } if (key.equals("rm.kill.nemesis")) { gameMode.setEmeralds(gameMode.getEmeralds() + 1); } if (key.equals("rm.death.axe") || key.equals("rm.death.suicide")) { gameMode.setDeaths(gameMode.getDeaths() + 1); gameMode.setKillStreak(0); } if (key.equals("rm.shop")) { String item = match.get(0); if (item.equals("Mine")) { gameMode.setEmeralds(gameMode.getEmeralds() - 5); } else if (item.equals("Hundestaffel") || item.equals("Rüstung")) { gameMode.setEmeralds(gameMode.getEmeralds() - 10); } else if (item.equals("Geschwindigkeit")) { gameMode.setEmeralds(gameMode.getEmeralds() - 15); } else if (item.equals("Airstrike")) { gameMode.setEmeralds(gameMode.getEmeralds() - 25); } else if (item.equals("Gottes Licht")) { gameMode.setEmeralds(gameMode.getEmeralds() - 30); } } if (key.equals("rm.win")) { gameMode.setWinner(match.get(0)); gameMode.setState(GameState.FINISHED); } } } }
411
0.572759
1
0.572759
game-dev
MEDIA
0.675514
game-dev
0.73603
1
0.73603
watabou/pixel-dungeon
2,132
src/com/watabou/pixeldungeon/windows/WndOptions.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * 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.watabou.pixeldungeon.windows; import com.watabou.noosa.BitmapTextMultiline; import com.watabou.pixeldungeon.scenes.PixelScene; import com.watabou.pixeldungeon.ui.RedButton; import com.watabou.pixeldungeon.ui.Window; public class WndOptions extends Window { private static final int WIDTH = 120; private static final int MARGIN = 2; private static final int BUTTON_HEIGHT = 20; public WndOptions( String title, String message, String... options ) { super(); BitmapTextMultiline tfTitle = PixelScene.createMultiline( title, 9 ); tfTitle.hardlight( TITLE_COLOR ); tfTitle.x = tfTitle.y = MARGIN; tfTitle.maxWidth = WIDTH - MARGIN * 2; tfTitle.measure(); add( tfTitle ); BitmapTextMultiline tfMesage = PixelScene.createMultiline( message, 8 ); tfMesage.maxWidth = WIDTH - MARGIN * 2; tfMesage.measure(); tfMesage.x = MARGIN; tfMesage.y = tfTitle.y + tfTitle.height() + MARGIN; add( tfMesage ); float pos = tfMesage.y + tfMesage.height() + MARGIN; for (int i=0; i < options.length; i++) { final int index = i; RedButton btn = new RedButton( options[i] ) { @Override protected void onClick() { hide(); onSelect( index ); } }; btn.setRect( MARGIN, pos, WIDTH - MARGIN * 2, BUTTON_HEIGHT ); add( btn ); pos += BUTTON_HEIGHT + MARGIN; } resize( WIDTH, (int)pos ); } protected void onSelect( int index ) {}; }
411
0.51535
1
0.51535
game-dev
MEDIA
0.674641
game-dev
0.650005
1
0.650005
andjelatodorovic/DesignPatterns
7,161
11_observerstate/11_observerstate/state/ex4/PlayerState.cpp
#include <string> #include <iostream> using namespace std; /* dogadjaj na tastaturi, npr. igrac pomera igraca i pritiska odredjene tastere da bi pomerao igraca na odredjeni nacin */ class KeyboardEvent { public: KeyboardEvent(const string& code) { if (code == "A" || code == "a") m_code = "LEFT_ARROW"; else if (code == "D" || code == "d") m_code = "RIGHT_ARROW"; else if (code == "W" || code == "w") m_code = "UP_ARROW"; else if (code == "S" || code == "s") m_code = "DOWN_ARROW"; else m_code = "UNKNOWN"; } string GetCode() { return m_code; } protected: string m_code; }; class PlayerState; class PlayerStandingState; class PlayerSittingState; class PlayerJumpingState; class PlayerMovingRightState; class PlayerMovingLeftState; /* kontekst, igrac u igri, koji tokom igre moze da se nadje u razlicitim stanjima, u zavisnosti od trenutnog stanja i nacin kretanja igraca na komandu onog ko igra bice razlicita */ class Player { public: Player(); virtual ~Player() {} virtual void HandleInput(KeyboardEvent &event); virtual void SetState(PlayerState* state) { m_state = state; } virtual void Show(); protected: PlayerState* m_state; }; /* apstraktno stanje, ima metod da razresi trenutni dogadjaj na tastaturi, prosledjuje se i referenca na igraca na kom se desio dogadjaj */ class PlayerState { public: PlayerState() {} virtual ~PlayerState() {} virtual void HandleInput(Player& player, KeyboardEvent& event) = 0; virtual void Show() = 0; }; /* konkretno stanje, predstavlja stanje kada igrac stoji */ class PlayerStandingState: public PlayerState { public: PlayerStandingState() {} virtual ~PlayerStandingState() {} virtual void HandleInput(Player& player, KeyboardEvent& event); virtual void Show() { cout << "Player is standing" << endl; } }; /* konkretno stanje, predstavlja stanje kada se igrac krece na levo */ class PlayerMovingLeftState: public PlayerState { public: PlayerMovingLeftState() {} virtual ~PlayerMovingLeftState() {} virtual void HandleInput(Player& player, KeyboardEvent& event); virtual void Show() { cout << "Player is moving left" << endl; } }; /* konkretno stanje, predstavlja stanje kada se igrac krece na desno */ class PlayerMovingRightState: public PlayerState { public: PlayerMovingRightState() {} virtual ~PlayerMovingRightState() {} virtual void HandleInput(Player& player, KeyboardEvent& event); virtual void Show() { cout << "Player is moving right" << endl; } }; /* konkretno stanje, predstavlja stanje kada igrac sedi */ class PlayerSittingState: public PlayerState { public: PlayerSittingState() {} virtual ~PlayerSittingState() {} virtual void HandleInput(Player& player, KeyboardEvent& event); virtual void Show() { cout << "Player is sitting" << endl; } }; /* konkretno stanje, predstavlja stanje kada igrac skace */ class PlayerJumpingState: public PlayerState { public: PlayerJumpingState() {} virtual ~PlayerJumpingState() {} virtual void HandleInput(Player& player, KeyboardEvent& event); virtual void Show() { cout << "Player is jumping" << endl; } }; Player::Player() { m_state = new PlayerStandingState(); } void Player::Show() { cout << "[Player] "; m_state->Show(); } void Player::HandleInput(KeyboardEvent &event) { m_state->HandleInput(*this, event); } /* class PlayerStandingState; class PlayerSittingState; class PlayerJumpingState; class PlayerMovingRightState; class PlayerMovingLeftState; */ /* implementacije metoda HandleInput (Handle sa seme) za razlicita konkretna stanja */ void PlayerStandingState::HandleInput(Player& player, KeyboardEvent& event) { if (event.GetCode() == "LEFT_ARROW") { player.SetState(new PlayerMovingLeftState()); } else if (event.GetCode() == "RIGHT_ARROW") { player.SetState(new PlayerMovingRightState()); } else if (event.GetCode() == "DOWN_ARROW") { player.SetState(new PlayerSittingState()); } else if (event.GetCode() == "UP_ARROW") { player.SetState(new PlayerJumpingState()); } else { cout << "ERROR: Can't do " << event.GetCode() << " while standing." << endl; } } void PlayerSittingState::HandleInput(Player& player, KeyboardEvent& event) { if (event.GetCode() == "LEFT_ARROW") { cout << "ERROR: Can't do " << event.GetCode() << " while sitting." << endl; } else if (event.GetCode() == "RIGHT_ARROW") { cout << "ERROR: Can't do " << event.GetCode() << " while sitting." << endl; } else if (event.GetCode() == "DOWN_ARROW") { cout << "ERROR: I'm already sitting" << endl; } else if (event.GetCode() == "UP_ARROW") { player.SetState(new PlayerStandingState()); } else { cout << "ERROR: Can't do " << event.GetCode() << " while sitting." << endl; } } void PlayerJumpingState::HandleInput(Player& player, KeyboardEvent& event) { if (event.GetCode() == "LEFT_ARROW") { player.SetState(new PlayerMovingLeftState()); } else if (event.GetCode() == "RIGHT_ARROW") { player.SetState(new PlayerMovingRightState()); } else if (event.GetCode() == "DOWN_ARROW") { player.SetState(new PlayerSittingState()); } else if (event.GetCode() == "UP_ARROW") { player.SetState(new PlayerJumpingState()); } else { cout << "ERROR: Can't do " << event.GetCode() << " while standing." << endl; } } void PlayerMovingRightState::HandleInput(Player& player, KeyboardEvent& event) { if (event.GetCode() == "LEFT_ARROW") { player.SetState(new PlayerStandingState()); } else if (event.GetCode() == "RIGHT_ARROW") { player.SetState(new PlayerMovingRightState()); } else if (event.GetCode() == "DOWN_ARROW") { player.SetState(new PlayerSittingState()); } else if (event.GetCode() == "UP_ARROW") { player.SetState(new PlayerJumpingState()); } else { cout << "ERROR: Can't do " << event.GetCode() << " while standing." << endl; } } void PlayerMovingLeftState::HandleInput(Player& player, KeyboardEvent& event) { if (event.GetCode() == "LEFT_ARROW") { player.SetState(new PlayerMovingLeftState()); } else if (event.GetCode() == "RIGHT_ARROW") { player.SetState(new PlayerStandingState()); } else if (event.GetCode() == "DOWN_ARROW") { player.SetState(new PlayerSittingState()); } else if (event.GetCode() == "UP_ARROW") { player.SetState(new PlayerJumpingState()); } else { cout << "ERROR: Can't do " << event.GetCode() << " while standing." << endl; } } /* kreiramo igraca, zatim pitamo korisnika sta zeli da radi sa igracem, nakon toga se prikaze trenutno stanje igraca */ int main() { Player player; string comm; do { cout << "What to do: [A] Move left, [D] Move right, [S] Sit down, [W] Jump, [Q] Quit: "; cin >> comm; KeyboardEvent event(comm); player.HandleInput(event); player.Show(); } while (comm != "Q" && comm != "q"); return 0; }
411
0.796288
1
0.796288
game-dev
MEDIA
0.799706
game-dev
0.870578
1
0.870578
leoetlino/botw
4,669
Actor/AIProgram/Item_Conductor.aiprog.yml
!io version: 0 type: xml param_root: !list objects: DemoAIActionIdx: !obj Demo_Bind: 3 Demo_CancelGet: 4 Demo_GetItem: 5 Demo_Idling: 6 Demo_Join: 7 Demo_OpenGetDemo: 8 Demo_PlayASForDemo: 9 Demo_PlayASForTimeline: 10 Demo_ResetBoneCtrl: 11 Demo_SendCatchWeaponMsgToPlayer: 12 Demo_SendSignal: 13 Demo_SetGetFlag: 14 Demo_SuccessGet: 15 Demo_TrigNullASPlay: 16 Demo_UpdateDataByGetDemo: 17 Demo_VisibleOff: 18 Demo_XLinkEventCreate: 19 Demo_XLinkEventFade: 20 Demo_XLinkEventKill: 21 lists: AI: !list objects: {} lists: AI_0: !list objects: Def: !obj {Name: Root, ClassName: !str32 ItemConductor, GroupName: ''} ChildIdx: !obj {持たれる: 1, 通常: 2} lists: {} Action: !list objects: {} lists: Action_0: !list objects: Def: !obj {Name: 持たれる, ClassName: !str32 ArmorBindNodeAction, GroupName: Root} lists: {} Action_1: !list objects: Def: !obj {Name: 通常, ClassName: !str32 ArmorBindNodeAction, GroupName: Root} lists: {} Action_2: !list objects: Def: !obj {Name: Demo_Bind, ClassName: !str32 ItemConductorDemoBind, GroupName: ''} lists: {} Action_3: !list objects: Def: !obj {Name: Demo_CancelGet, ClassName: !str32 EventCancelGet, GroupName: ''} lists: {} Action_4: !list objects: Def: !obj {Name: Demo_GetItem, ClassName: !str32 DemoGetItem, GroupName: ''} lists: {} Action_5: !list objects: Def: !obj {Name: Demo_Idling, ClassName: !str32 IdleAction, GroupName: ''} lists: {} Action_6: !list objects: Def: !obj {Name: Demo_Join, ClassName: !str32 DummyTriggerAction, GroupName: ''} lists: {} Action_7: !list objects: Def: !obj {Name: Demo_OpenGetDemo, ClassName: !str32 EventOpenGetDemo, GroupName: ''} lists: {} Action_8: !list objects: Def: !obj {Name: Demo_PlayASForDemo, ClassName: !str32 PlayASForDemo, GroupName: ''} SInst: !obj {AnimeDrivenSettings: 1} lists: {} Action_9: !list objects: Def: !obj {Name: Demo_PlayASForTimeline, ClassName: !str32 PlayASForTimeline, GroupName: ''} SInst: !obj {AnimeDrivenSettings: 1} lists: {} Action_10: !list objects: Def: !obj {Name: Demo_ResetBoneCtrl, ClassName: !str32 DemoResetBoneCtrl, GroupName: ''} lists: {} Action_11: !list objects: Def: !obj {Name: Demo_SendCatchWeaponMsgToPlayer, ClassName: !str32 EventSendCatchWeaponMsgToPlayer, GroupName: ''} lists: {} Action_12: !list objects: Def: !obj {Name: Demo_SendSignal, ClassName: !str32 SendSignalAction, GroupName: ''} lists: {} Action_13: !list objects: Def: !obj {Name: Demo_SetGetFlag, ClassName: !str32 SetGetFlag, GroupName: ''} lists: {} Action_14: !list objects: Def: !obj {Name: Demo_SuccessGet, ClassName: !str32 EventSuccessGet, GroupName: ''} lists: {} Action_15: !list objects: Def: !obj {Name: Demo_TrigNullASPlay, ClassName: !str32 EventTrigNullASPlay, GroupName: ''} lists: {} Action_16: !list objects: Def: !obj {Name: Demo_UpdateDataByGetDemo, ClassName: !str32 UpdateDataByGetDemoAction, GroupName: ''} lists: {} Action_17: !list objects: Def: !obj {Name: Demo_VisibleOff, ClassName: !str32 DemoVisibleOff, GroupName: ''} lists: {} Action_18: !list objects: Def: !obj {Name: Demo_XLinkEventCreate, ClassName: !str32 XLinkEventCreateAction, GroupName: ''} lists: {} Action_19: !list objects: Def: !obj {Name: Demo_XLinkEventFade, ClassName: !str32 XLinkEventFadeAction, GroupName: ''} lists: {} Action_20: !list objects: Def: !obj {Name: Demo_XLinkEventKill, ClassName: !str32 XLinkEventKillAction, GroupName: ''} lists: {} Behavior: !list objects: {} lists: {} Query: !list objects: {} lists: {}
411
0.50891
1
0.50891
game-dev
MEDIA
0.802048
game-dev
0.658109
1
0.658109
sshuair/torchsat
1,624
torchsat/datasets/patternnet.py
from .folder import DatasetFolder from .utils import default_loader CLASSES_TO_IDX = { 'airplane': 0, 'baseball_field': 1, 'basketball_court': 2, 'beach': 3, 'bridge': 4, 'cemetery': 5, 'chaparral': 6, 'christmas_tree_farm': 7, 'closed_road': 8, 'coastal_mansion': 9, 'crosswalk': 10, 'dense_residential': 11, 'ferry_terminal': 12, 'football_field': 13, 'forest': 14, 'freeway': 15, 'golf_course': 16, 'harbor': 17, 'intersection': 18, 'mobile_home_park': 19, 'nursing_home': 20, 'oil_gas_field': 21, 'oil_well': 22, 'overpass': 23, 'parking_lot': 24, 'parking_space': 25, 'railway': 26, 'river': 27, 'runway': 28, 'runway_marking': 29, 'shipping_yard': 30, 'solar_panel': 31, 'sparse_residential': 32, 'storage_tank': 33, 'swimming_pool': 34, 'tennis_court': 35, 'transformer_station': 36, 'wastewater_treatment_plant': 37, } class PatternNet(DatasetFolder): url = 'https://doc-0k-9c-docs.googleusercontent.com/docs/securesc/s4mst7k8sdlkn5gslv2v17dousor99pe/5kjb9nqbn6uv3dnpsqu7n7vbc2sjkm9n/1553925600000/13306064760021495251/10775530989497868365/127lxXYqzO6Bd0yZhvEbgIfz95HaEnr9K?e=download' def __init__(self, root, download=False, **kwargs): if download: download() extensions = ['.jpg'] classes = list(CLASSES_TO_IDX.keys()) super(PatternNet, self).__init__(root, default_loader, extensions, classes=classes ,class_to_idx=CLASSES_TO_IDX, **kwargs) def download(): pass
411
0.513486
1
0.513486
game-dev
MEDIA
0.231509
game-dev
0.695944
1
0.695944
fgsfdsfgs/vitaXash3D
88,815
engine/client/cl_game.c
/* cl_game.c - client dll interaction Copyright (C) 2008 Uncle Mike 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. */ #ifndef XASH_DEDICATED #include "common.h" #include "client.h" #include "const.h" #include "triangleapi.h" #include "r_efx.h" #include "demo_api.h" #include "ivoicetweak.h" #include "pm_local.h" #include "cl_tent.h" #include "input.h" #include "shake.h" #include "sprite.h" #include "gl_local.h" #include "library.h" #include "vgui_draw.h" #include "sound.h" // SND_STOP_LOOPING #define MAX_LINELENGTH 80 #define MAX_TEXTCHANNELS 8 // must be power of two (GoldSrc uses 4 channels) #define TEXT_MSGNAME "TextMessage%i" char cl_textbuffer[MAX_TEXTCHANNELS][512]; client_textmessage_t cl_textmessage[MAX_TEXTCHANNELS]; static struct crosshair_s { // crosshair members const model_t *pCrosshair; wrect_t rcCrosshair; rgba_t rgbaCrosshair; } crosshair_state; extern rgba_t g_color_table[8]; static dllfunc_t cdll_exports[] = { { "Initialize", (void **)&clgame.dllFuncs.pfnInitialize }, { "HUD_VidInit", (void **)&clgame.dllFuncs.pfnVidInit }, { "HUD_Init", (void **)&clgame.dllFuncs.pfnInit }, { "HUD_Shutdown", (void **)&clgame.dllFuncs.pfnShutdown }, { "HUD_Redraw", (void **)&clgame.dllFuncs.pfnRedraw }, { "HUD_UpdateClientData", (void **)&clgame.dllFuncs.pfnUpdateClientData }, { "HUD_Reset", (void **)&clgame.dllFuncs.pfnReset }, { "HUD_PlayerMove", (void **)&clgame.dllFuncs.pfnPlayerMove }, { "HUD_PlayerMoveInit", (void **)&clgame.dllFuncs.pfnPlayerMoveInit }, { "HUD_PlayerMoveTexture", (void **)&clgame.dllFuncs.pfnPlayerMoveTexture }, { "HUD_ConnectionlessPacket", (void **)&clgame.dllFuncs.pfnConnectionlessPacket }, { "HUD_GetHullBounds", (void **)&clgame.dllFuncs.pfnGetHullBounds }, { "HUD_Frame", (void **)&clgame.dllFuncs.pfnFrame }, { "HUD_PostRunCmd", (void **)&clgame.dllFuncs.pfnPostRunCmd }, { "HUD_Key_Event", (void **)&clgame.dllFuncs.pfnKey_Event }, { "HUD_AddEntity", (void **)&clgame.dllFuncs.pfnAddEntity }, { "HUD_CreateEntities", (void **)&clgame.dllFuncs.pfnCreateEntities }, { "HUD_StudioEvent", (void **)&clgame.dllFuncs.pfnStudioEvent }, { "HUD_TxferLocalOverrides", (void **)&clgame.dllFuncs.pfnTxferLocalOverrides }, { "HUD_ProcessPlayerState", (void **)&clgame.dllFuncs.pfnProcessPlayerState }, { "HUD_TxferPredictionData", (void **)&clgame.dllFuncs.pfnTxferPredictionData }, { "HUD_TempEntUpdate", (void **)&clgame.dllFuncs.pfnTempEntUpdate }, { "HUD_DrawNormalTriangles", (void **)&clgame.dllFuncs.pfnDrawNormalTriangles }, { "HUD_DrawTransparentTriangles", (void **)&clgame.dllFuncs.pfnDrawTransparentTriangles }, { "HUD_GetUserEntity", (void **)&clgame.dllFuncs.pfnGetUserEntity }, { "Demo_ReadBuffer", (void **)&clgame.dllFuncs.pfnDemo_ReadBuffer }, { "CAM_Think", (void **)&clgame.dllFuncs.CAM_Think }, { "CL_IsThirdPerson", (void **)&clgame.dllFuncs.CL_IsThirdPerson }, { "CL_CameraOffset", (void **)&clgame.dllFuncs.CL_CameraOffset }, { "CL_CreateMove", (void **)&clgame.dllFuncs.CL_CreateMove }, { "IN_ActivateMouse", (void **)&clgame.dllFuncs.IN_ActivateMouse }, { "IN_DeactivateMouse", (void **)&clgame.dllFuncs.IN_DeactivateMouse }, { "IN_MouseEvent", (void **)&clgame.dllFuncs.IN_MouseEvent }, { "IN_Accumulate", (void **)&clgame.dllFuncs.IN_Accumulate }, { "IN_ClearStates", (void **)&clgame.dllFuncs.IN_ClearStates }, { "V_CalcRefdef", (void **)&clgame.dllFuncs.pfnCalcRefdef }, { "KB_Find", (void **)&clgame.dllFuncs.KB_Find }, { NULL, NULL } }; // optional exports static dllfunc_t cdll_new_exports[] = // allowed only in SDK 2.3 and higher { { "HUD_GetStudioModelInterface", (void **)&clgame.dllFuncs.pfnGetStudioModelInterface }, { "HUD_DirectorMessage", (void **)&clgame.dllFuncs.pfnDirectorMessage }, { "HUD_VoiceStatus", (void **)&clgame.dllFuncs.pfnVoiceStatus }, { "HUD_ChatInputPosition", (void **)&clgame.dllFuncs.pfnChatInputPosition }, { "HUD_GetRenderInterface", (void **)&clgame.dllFuncs.pfnGetRenderInterface }, // Xash3D ext { "HUD_GetPlayerTeam", (void **)&clgame.dllFuncs.pfnGetPlayerTeam }, { "HUD_ClipMoveToEntity", (void **)&clgame.dllFuncs.pfnClipMoveToEntity }, // Xash3D ext { "IN_ClientTouchEvent", (void **)&clgame.dllFuncs.pfnTouchEvent}, // Xash3D ext { "IN_ClientMoveEvent", (void **)&clgame.dllFuncs.pfnMoveEvent}, // Xash3D ext { "IN_ClientLookEvent", (void **)&clgame.dllFuncs.pfnLookEvent}, // Xash3D ext { NULL, NULL } }; /* ==================== CL_GetEntityByIndex Render callback for studio models ==================== */ cl_entity_t *GAME_EXPORT CL_GetEntityByIndex( int index ) { if( !clgame.entities ) // not in game yet return NULL; if( index == 0 ) return cl.world; if( index < 0 ) return clgame.dllFuncs.pfnGetUserEntity( -index ); if( index >= clgame.maxEntities ) return NULL; return CL_EDICT_NUM( index ); } /* ==================== CL_GetServerTime don't clamped time that come from server ==================== */ float CL_GetServerTime( void ) { return cl.mtime[0]; } /* ==================== CL_GetLerpFrac returns current lerp fraction ==================== */ float CL_GetLerpFrac( void ) { return cl.lerpFrac; } /* ==================== CL_IsThirdPerson returns true if thirdperson is enabled ==================== */ qboolean CL_IsThirdPersonE( void ) { return cl.thirdperson; } /* ==================== CL_GetPlayerInfo get player info by render request ==================== */ player_info_t *CL_GetPlayerInfo( int playerIndex ) { if( playerIndex < 0 || playerIndex >= cl.maxclients ) return NULL; return &cl.players[playerIndex]; } /* ==================== CL_CreatePlaylist Create a default valve playlist ==================== */ void CL_CreatePlaylist( const char *filename ) { file_t *f; f = FS_Open( filename, "w", false ); if( !f ) return; // make standard cdaudio playlist FS_Print( f, "blank\n" ); // #1 FS_Print( f, "Half-Life01.mp3\n" ); // #2 FS_Print( f, "Prospero01.mp3\n" ); // #3 FS_Print( f, "Half-Life12.mp3\n" ); // #4 FS_Print( f, "Half-Life07.mp3\n" ); // #5 FS_Print( f, "Half-Life10.mp3\n" ); // #6 FS_Print( f, "Suspense01.mp3\n" ); // #7 FS_Print( f, "Suspense03.mp3\n" ); // #8 FS_Print( f, "Half-Life09.mp3\n" ); // #9 FS_Print( f, "Half-Life02.mp3\n" ); // #10 FS_Print( f, "Half-Life13.mp3\n" ); // #11 FS_Print( f, "Half-Life04.mp3\n" ); // #12 FS_Print( f, "Half-Life15.mp3\n" ); // #13 FS_Print( f, "Half-Life14.mp3\n" ); // #14 FS_Print( f, "Half-Life16.mp3\n" ); // #15 FS_Print( f, "Suspense02.mp3\n" ); // #16 FS_Print( f, "Half-Life03.mp3\n" ); // #17 FS_Print( f, "Half-Life08.mp3\n" ); // #18 FS_Print( f, "Prospero02.mp3\n" ); // #19 FS_Print( f, "Half-Life05.mp3\n" ); // #20 FS_Print( f, "Prospero04.mp3\n" ); // #21 FS_Print( f, "Half-Life11.mp3\n" ); // #22 FS_Print( f, "Half-Life06.mp3\n" ); // #23 FS_Print( f, "Prospero03.mp3\n" ); // #24 FS_Print( f, "Half-Life17.mp3\n" ); // #25 FS_Print( f, "Prospero05.mp3\n" ); // #26 FS_Print( f, "Suspense05.mp3\n" ); // #27 FS_Print( f, "Suspense07.mp3\n" ); // #28 FS_Close( f ); } /* ==================== CL_InitCDAudio Initialize CD playlist ==================== */ void CL_InitCDAudio( const char *filename ) { char *afile, *pfile; string token; int c = 0; if( !FS_FileExists( filename, false )) { // create a default playlist CL_CreatePlaylist( filename ); } afile = (char *)FS_LoadFile( filename, NULL, false ); if( !afile ) return; pfile = afile; // format: trackname\n [num] while(( pfile = COM_ParseFile( pfile, token )) != NULL ) { if( !Q_stricmp( token, "blank" )) token[0] = '\0'; Q_strncpy( clgame.cdtracks[c], token, sizeof( clgame.cdtracks[0] )); if( ++c > MAX_CDTRACKS - 1 ) { MsgDev( D_WARN, "CD_Init: too many tracks %i in %s (only %d allowed)\n", c, filename, MAX_CDTRACKS ); break; } } Mem_Free( afile ); } /* ==================== CL_PointContents Return contents for point ==================== */ int CL_PointContents( const vec3_t p ) { int cont = CL_TruePointContents( p ); if( cont <= CONTENTS_CURRENT_0 && cont >= CONTENTS_CURRENT_DOWN ) cont = CONTENTS_WATER; return cont; } /* ==================== StudioEvent Event callback for studio models ==================== */ void CL_StudioEvent( struct mstudioevent_s *event, cl_entity_t *pEdict ) { clgame.dllFuncs.pfnStudioEvent( event, pEdict ); } /* ============= CL_AdjustXPos adjust text by x pos ============= */ static int CL_AdjustXPos( float x, int width, int totalWidth ) { int xPos; if( x == -1 ) { xPos = ( clgame.scrInfo.iWidth - width ) * 0.5f; } else { if ( x < 0 ) xPos = (1.0f + x) * clgame.scrInfo.iWidth - totalWidth; // Alight right else // align left xPos = x * clgame.scrInfo.iWidth; } if( xPos + width > clgame.scrInfo.iWidth ) xPos = clgame.scrInfo.iWidth - width; else if( xPos < 0 ) xPos = 0; return xPos; } /* ============= CL_AdjustYPos adjust text by y pos ============= */ static int CL_AdjustYPos( float y, int height ) { int yPos; if( y == -1 ) // centered? { yPos = ( clgame.scrInfo.iHeight - height ) * 0.5f; } else { // Alight bottom? if( y < 0 ) yPos = (1.0f + y) * clgame.scrInfo.iHeight - height; // Alight bottom else // align top yPos = y * clgame.scrInfo.iHeight; } if( yPos + height > clgame.scrInfo.iHeight ) yPos = clgame.scrInfo.iHeight - height; else if( yPos < 0 ) yPos = 0; return yPos; } /* ============= CL_CenterPrint print centerscreen message ============= */ void CL_CenterPrint( const char *text, float y ) { byte *s; int width = 0; int length = 0; clgame.centerPrint.lines = 1; clgame.centerPrint.totalWidth = 0; clgame.centerPrint.time = cl.mtime[0]; // allow pause for centerprint Q_strncpy( clgame.centerPrint.message, text, sizeof( clgame.centerPrint.message )); s = clgame.centerPrint.message; // count the number of lines for centering while( *s ) { if( *s == '\n' ) { clgame.centerPrint.lines++; if( width > clgame.centerPrint.totalWidth ) clgame.centerPrint.totalWidth = width; width = 0; } else width += clgame.scrInfo.charWidths[*s]; s++; length++; } clgame.centerPrint.totalHeight = ( clgame.centerPrint.lines * clgame.scrInfo.iCharHeight ); clgame.centerPrint.y = CL_AdjustYPos( y, clgame.centerPrint.totalHeight ); } /* ==================== SPR_AdjustSize draw hudsprite routine ==================== */ void SPR_AdjustSize( float *x, float *y, float *w, float *h ) { float xscale, yscale; ASSERT( x || y || w || h ); // scale for screen sizes xscale = scr_width->value / (float)clgame.scrInfo.iWidth; yscale = scr_height->value / (float)clgame.scrInfo.iHeight; if( x ) *x *= xscale; if( y ) *y *= yscale; if( w ) *w *= xscale; if( h ) *h *= yscale; } /* ==================== TextAdjustSize draw hudsprite routine ==================== */ void TextAdjustSize( int *x, int *y, int *w, int *h ) { float xscale, yscale; ASSERT( x || y || w || h ); if( !clgame.ds.adjust_size ) return; // scale for screen sizes xscale = scr_width->value / (float)clgame.scrInfo.iWidth; yscale = scr_height->value / (float)clgame.scrInfo.iHeight; if( x ) *x *= xscale; if( y ) *y *= yscale; if( w ) *w *= xscale; if( h ) *h *= yscale; } /* ==================== PictAdjustSize draw hudsprite routine ==================== */ void PicAdjustSize( float *x, float *y, float *w, float *h ) { float xscale, yscale; if( !clgame.ds.adjust_size ) return; if( !x && !y && !w && !h ) return; // scale for screen sizes xscale = scr_width->value / (float)clgame.scrInfo.iWidth; yscale = scr_height->value / (float)clgame.scrInfo.iHeight; if( x ) *x *= xscale; if( y ) *y *= yscale; if( w ) *w *= xscale; if( h ) *h *= yscale; } static qboolean SPR_Scissor( float *x, float *y, float *width, float *height, float *u0, float *v0, float *u1, float *v1 ) { float dudx, dvdy; // clip sub rect to sprite if(( width == 0 ) || ( height == 0 )) return false; if( *x + *width <= clgame.ds.scissor_x ) return false; if( *x >= clgame.ds.scissor_x + clgame.ds.scissor_width ) return false; if( *y + *height <= clgame.ds.scissor_y ) return false; if( *y >= clgame.ds.scissor_y + clgame.ds.scissor_height ) return false; dudx = (*u1 - *u0) / *width; dvdy = (*v1 - *v0) / *height; if( *x < clgame.ds.scissor_x ) { *u0 += (clgame.ds.scissor_x - *x) * dudx; *width -= clgame.ds.scissor_x - *x; *x = clgame.ds.scissor_x; } if( *x + *width > clgame.ds.scissor_x + clgame.ds.scissor_width ) { *u1 -= (*x + *width - (clgame.ds.scissor_x + clgame.ds.scissor_width)) * dudx; *width = clgame.ds.scissor_x + clgame.ds.scissor_width - *x; } if( *y < clgame.ds.scissor_y ) { *v0 += (clgame.ds.scissor_y - *y) * dvdy; *height -= clgame.ds.scissor_y - *y; *y = clgame.ds.scissor_y; } if( *y + *height > clgame.ds.scissor_y + clgame.ds.scissor_height ) { *v1 -= (*y + *height - (clgame.ds.scissor_y + clgame.ds.scissor_height)) * dvdy; *height = clgame.ds.scissor_y + clgame.ds.scissor_height - *y; } return true; } /* ==================== SPR_DrawGeneric draw hudsprite routine ==================== */ static void SPR_DrawGeneric( int frame, float x, float y, float width, float height, const wrect_t *prc ) { float s1, s2, t1, t2; int texnum; if( width == -1 && height == -1 ) { int w, h; // assume we get sizes from image R_GetSpriteParms( &w, &h, NULL, frame, clgame.ds.pSprite ); width = w; height = h; } if( prc ) { wrect_t rc; rc = *prc; // Sigh! some stupid modmakers set wrong rectangles in hud.txt if( rc.left <= 0 || rc.left >= width ) rc.left = 0; if( rc.top <= 0 || rc.top >= height ) rc.top = 0; if( rc.right <= 0 || rc.right > width ) rc.right = width; if( rc.bottom <= 0 || rc.bottom > height ) rc.bottom = height; // calc user-defined rectangle s1 = (float)rc.left / width; t1 = (float)rc.top / height; s2 = (float)rc.right / width; t2 = (float)rc.bottom / height; width = rc.right - rc.left; height = rc.bottom - rc.top; } else { s1 = t1 = 0.0f; s2 = t2 = 1.0f; } // pass scissor test if supposed if( clgame.ds.scissor_test && !SPR_Scissor( &x, &y, &width, &height, &s1, &t1, &s2, &t2 )) return; // scale for screen sizes SPR_AdjustSize( &x, &y, &width, &height ); texnum = R_GetSpriteTexture( clgame.ds.pSprite, frame ); pglColor4ubv( clgame.ds.spriteColor ); R_DrawStretchPic( x, y, width, height, s1, t1, s2, t2, texnum ); } /* ============= CL_DrawCenterPrint called each frame ============= */ void CL_DrawCenterPrint( void ) { char *pText; int i, j, x, y; int width, lineLength; byte *colorDefault, line[MAX_LINELENGTH]; int charWidth, charHeight; if( !clgame.centerPrint.time ) return; if(( cl.time - clgame.centerPrint.time ) >= scr_centertime->value ) { // time expired clgame.centerPrint.time = 0.0f; return; } y = clgame.centerPrint.y; // start y colorDefault = g_color_table[7]; pText = clgame.centerPrint.message; Con_DrawCharacterLen( 0, NULL, &charHeight ); for( i = 0; i < clgame.centerPrint.lines; i++ ) { lineLength = 0; width = 0; while( *pText && *pText != '\n' && lineLength < MAX_LINELENGTH ) { byte c = *pText; line[lineLength] = c; Con_DrawCharacterLen( c, &charWidth, NULL ); width += charWidth; lineLength++; pText++; } if( lineLength == MAX_LINELENGTH ) lineLength--; pText++; // Skip LineFeed line[lineLength] = 0; x = CL_AdjustXPos( -1, width, clgame.centerPrint.totalWidth ); for( j = 0; j < lineLength; j++ ) { if( x >= 0 && y >= 0 && x <= clgame.scrInfo.iWidth ) x += Con_DrawCharacter( x, y, line[j], colorDefault ); } y += charHeight; } } /* ============= CL_DrawScreenFade fill screen with specfied color can be modulated ============= */ void CL_DrawScreenFade( void ) { screenfade_t *sf = &clgame.fade; int iFadeAlpha, testFlags; // keep pushing reset time out indefinitely if( sf->fadeFlags & FFADE_STAYOUT ) sf->fadeReset = cl.time + 0.1f; if( sf->fadeReset == 0.0f && sf->fadeEnd == 0.0f ) return; // inactive // all done? if(( cl.time > sf->fadeReset ) && ( cl.time > sf->fadeEnd )) { Q_memset( &clgame.fade, 0, sizeof( clgame.fade )); return; } testFlags = (sf->fadeFlags & ~FFADE_MODULATE); // fading... if( testFlags == FFADE_STAYOUT ) { iFadeAlpha = sf->fadealpha; } else { iFadeAlpha = sf->fadeSpeed * ( sf->fadeEnd - cl.time ); if( sf->fadeFlags & FFADE_OUT ) iFadeAlpha += sf->fadealpha; iFadeAlpha = bound( 0, iFadeAlpha, sf->fadealpha ); } pglColor4ub( sf->fader, sf->fadeg, sf->fadeb, iFadeAlpha ); if( sf->fadeFlags & FFADE_MODULATE ) GL_SetRenderMode( kRenderTransAdd ); else GL_SetRenderMode( kRenderTransTexture ); R_DrawStretchPic( 0, 0, scr_width->integer, scr_height->integer, 0, 0, 1, 1, cls.fillImage ); pglColor4ub( 255, 255, 255, 255 ); } /* ==================== CL_InitTitles parse all messages that declared in titles.txt and hold them into permament memory pool ==================== */ static void CL_InitTitles( const char *filename ) { fs_offset_t fileSize; byte *pMemFile; int i; // initialize text messages (game_text) for( i = 0; i < MAX_TEXTCHANNELS; i++ ) { cl_textmessage[i].pName = _copystring( clgame.mempool, va( TEXT_MSGNAME, i ), __FILE__, __LINE__ ); cl_textmessage[i].pMessage = cl_textbuffer[i]; } // clear out any old data that's sitting around. if( clgame.titles ) Mem_Free( clgame.titles ); clgame.titles = NULL; clgame.numTitles = 0; pMemFile = FS_LoadFile( filename, &fileSize, false ); if( !pMemFile ) return; CL_TextMessageParse( pMemFile, (int)fileSize ); Mem_Free( pMemFile ); } /* ==================== CL_ParseTextMessage Parse TE_TEXTMESSAGE ==================== */ void CL_ParseTextMessage( sizebuf_t *msg ) { static int msgindex = 0; client_textmessage_t *text; int channel; // read channel ( 0 - auto) channel = BF_ReadByte( msg ); if( channel <= 0 || channel > ( MAX_TEXTCHANNELS - 1 )) { // invalid channel specified, use internal counter if( channel != 0 ) MsgDev( D_ERROR, "HudText: invalid channel %i\n", channel ); channel = msgindex; msgindex = (msgindex + 1) & (MAX_TEXTCHANNELS - 1); } // grab message channel text = &cl_textmessage[channel]; text->x = (float)(BF_ReadShort( msg ) / 8192.0f); text->y = (float)(BF_ReadShort( msg ) / 8192.0f); text->effect = BF_ReadByte( msg ); text->r1 = BF_ReadByte( msg ); text->g1 = BF_ReadByte( msg ); text->b1 = BF_ReadByte( msg ); text->a1 = BF_ReadByte( msg ); text->r2 = BF_ReadByte( msg ); text->g2 = BF_ReadByte( msg ); text->b2 = BF_ReadByte( msg ); text->a2 = BF_ReadByte( msg ); text->fadein = (float)(BF_ReadShort( msg ) / 256.0f ); text->fadeout = (float)(BF_ReadShort( msg ) / 256.0f ); text->holdtime = (float)(BF_ReadShort( msg ) / 256.0f ); if( text->effect == 2 ) text->fxtime = (float)(BF_ReadShort( msg ) / 256.0f ); else text->fxtime = 0.0f; // to prevent grab too long messages Q_strncpy( (char *)text->pMessage, BF_ReadString( msg ), 512 ); // NOTE: a "HudText" message contain only 'string' with message name, so we // don't needs to use MSG_ routines here, just directly write msgname into netbuffer CL_DispatchUserMessage( "HudText", Q_strlen( text->pName ) + 1, (void *)text->pName ); } /* ==================== CL_GetLocalPlayer Render callback for studio models ==================== */ cl_entity_t *GAME_EXPORT CL_GetLocalPlayer( void ) { cl_entity_t *player; player = CL_EDICT_NUM( cl.playernum + 1 ); //ASSERT( player != NULL ); return player; } /* ==================== CL_GetMaxlients Render callback for studio models ==================== */ int GAME_EXPORT CL_GetMaxClients( void ) { return cl.maxclients; } /* ==================== CL_SoundFromIndex return soundname from index ==================== */ const char *GAME_EXPORT CL_SoundFromIndex( int index ) { sfx_t *sfx = NULL; int hSound; // make sure that we're within bounds index = bound( 0, index, MAX_SOUNDS ); hSound = cl.sound_index[index]; if( !hSound ) { MsgDev( D_ERROR, "CL_SoundFromIndex: invalid sound index %i\n", index ); return NULL; } sfx = S_GetSfxByHandle( hSound ); if( !sfx ) { MsgDev( D_ERROR, "CL_SoundFromIndex: bad sfx for index %i\n", index ); return NULL; } return sfx->name; } /* ========= SPR_EnableScissor ========= */ static void GAME_EXPORT SPR_EnableScissor( int x, int y, int width, int height ) { // check bounds x = bound( 0, x, clgame.scrInfo.iWidth ); y = bound( 0, y, clgame.scrInfo.iHeight ); width = bound( 0, width, clgame.scrInfo.iWidth - x ); height = bound( 0, height, clgame.scrInfo.iHeight - y ); clgame.ds.scissor_x = x; clgame.ds.scissor_width = width; clgame.ds.scissor_y = y; clgame.ds.scissor_height = height; clgame.ds.scissor_test = true; } /* ========= SPR_DisableScissor ========= */ static void GAME_EXPORT SPR_DisableScissor( void ) { clgame.ds.scissor_x = 0; clgame.ds.scissor_width = 0; clgame.ds.scissor_y = 0; clgame.ds.scissor_height = 0; clgame.ds.scissor_test = false; } /* ==================== CL_DrawCrosshair Render crosshair ==================== */ void CL_DrawCrosshair( void ) { int x, y, width, height; cl_entity_t *pPlayer; if( !crosshair_state.pCrosshair || cl.refdef.crosshairangle[2] || !cl_crosshair->integer ) return; pPlayer = CL_GetLocalPlayer(); if( cl.frame.client.deadflag != DEAD_NO || cl.frame.client.flags & FL_FROZEN ) return; // any camera on if( cl.refdef.viewentity != pPlayer->index ) return; // get crosshair dimension width = crosshair_state.rcCrosshair.right - crosshair_state.rcCrosshair.left; height = crosshair_state.rcCrosshair.bottom - crosshair_state.rcCrosshair.top; x = clgame.scrInfo.iWidth / 2; y = clgame.scrInfo.iHeight / 2; // g-cont - cl.refdef.crosshairangle is the autoaim angle. // if we're not using autoaim, just draw in the middle of the screen if( !VectorIsNull( cl.refdef.crosshairangle )) { vec3_t angles; vec3_t forward; vec3_t point, screen; VectorAdd( cl.refdef.viewangles, cl.refdef.crosshairangle, angles ); AngleVectors( angles, forward, NULL, NULL ); VectorAdd( cl.refdef.vieworg, forward, point ); R_WorldToScreen( point, screen ); x += 0.5f * screen[0] * scr_width->value + 0.5f; y += 0.5f * screen[1] * scr_height->value + 0.5f; } clgame.ds.pSprite = crosshair_state.pCrosshair; GL_SetRenderMode( kRenderTransTexture ); *(int *)clgame.ds.spriteColor = *(int *)crosshair_state.rgbaCrosshair; SPR_EnableScissor( x - 0.5f * width, y - 0.5f * height, width, height ); SPR_DrawGeneric( 0, x - 0.5f * width, y - 0.5f * height, -1, -1, &crosshair_state.rcCrosshair ); SPR_DisableScissor(); } /* ============= CL_DrawLoading draw loading progress bar ============= */ static void CL_DrawLoading( float percent ) { int x, y, width, height, right; float xscale, yscale, step, s2; R_GetTextureParms( &width, &height, cls.loadingBar ); x = ( clgame.scrInfo.iWidth - width ) >> 1; y = ( clgame.scrInfo.iHeight - height) >> 1; xscale = scr_width->value / (float)clgame.scrInfo.iWidth; yscale = scr_height->value / (float)clgame.scrInfo.iHeight; x *= xscale; y *= yscale; width *= xscale; height *= yscale; if( cl_allow_levelshots->integer ) { pglColor4ub( 128, 128, 128, 255 ); GL_SetRenderMode( kRenderTransTexture ); R_DrawStretchPic( x, y, width, height, 0, 0, 1, 1, cls.loadingBar ); step = (float)width / 100.0f; right = (int)ceil( percent * step ); s2 = (float)right / width; width = right; pglColor4ub( 208, 152, 0, 255 ); GL_SetRenderMode( kRenderTransTexture ); R_DrawStretchPic( x, y, width, height, 0, 0, s2, 1, cls.loadingBar ); pglColor4ub( 255, 255, 255, 255 ); } else { pglColor4ub( 255, 255, 255, 255 ); GL_SetRenderMode( kRenderTransTexture ); R_DrawStretchPic( x, y, width, height, 0, 0, 1, 1, cls.loadingBar ); } } /* ============= CL_DrawPause draw pause sign ============= */ static void CL_DrawPause( void ) { int x, y, width, height; float xscale, yscale; R_GetTextureParms( &width, &height, cls.pauseIcon ); x = ( clgame.scrInfo.iWidth - width ) >> 1; y = ( clgame.scrInfo.iHeight - height) >> 1; xscale = scr_width->value / (float)clgame.scrInfo.iWidth; yscale = scr_height->value / (float)clgame.scrInfo.iHeight; x *= xscale; y *= yscale; width *= xscale; height *= yscale; pglColor4ub( 255, 255, 255, 255 ); GL_SetRenderMode( kRenderTransTexture ); R_DrawStretchPic( x, y, width, height, 0, 0, 1, 1, cls.pauseIcon ); } void CL_DrawHUD( int state ) { if( state == CL_ACTIVE && !cl.video_prepped ) state = CL_LOADING; if( state == CL_ACTIVE && cl.refdef.paused ) state = CL_PAUSED; switch( state ) { case CL_ACTIVE: CL_DrawScreenFade (); CL_DrawCrosshair (); CL_DrawCenterPrint (); clgame.dllFuncs.pfnRedraw( cl.time, cl.refdef.intermission ); break; case CL_PAUSED: CL_DrawScreenFade (); CL_DrawCrosshair (); CL_DrawCenterPrint (); clgame.dllFuncs.pfnRedraw( cl.time, cl.refdef.intermission ); CL_DrawPause(); break; case CL_LOADING: CL_DrawLoading( scr_loading->value ); break; case CL_CHANGELEVEL: if( cls.draw_changelevel ) { CL_DrawLoading( 100.0f ); cls.draw_changelevel = false; } break; } } static void CL_ClearUserMessage( char *pszName, int svc_num ) { int i; for( i = 0; i < MAX_USER_MESSAGES && clgame.msg[i].name[0]; i++ ) if( ( clgame.msg[i].number == svc_num ) && Q_strcmp( clgame.msg[i].name, pszName ) ) clgame.msg[i].number = 0; } void CL_LinkUserMessage( char *pszName, const int svc_num, int iSize ) { int i; if( !pszName || !*pszName ) Host_Error( "CL_LinkUserMessage: bad message name\n" ); if( svc_num < svc_lastmsg ) Host_Error( "CL_LinkUserMessage: tried to hook a system message \"%s\"\n", svc_strings[svc_num] ); // see if already hooked for( i = 0; i < MAX_USER_MESSAGES && clgame.msg[i].name[0]; i++ ) { // NOTE: no check for DispatchFunc, check only name if( !Q_strcmp( clgame.msg[i].name, pszName )) { clgame.msg[i].number = svc_num; clgame.msg[i].size = iSize; CL_ClearUserMessage( pszName, svc_num ); return; } } if( i == MAX_USER_MESSAGES ) { Host_Error( "CL_LinkUserMessage: MAX_USER_MESSAGES hit!\n" ); return; } // register new message without DispatchFunc, so we should parse it properly Q_strncpy( clgame.msg[i].name, pszName, sizeof( clgame.msg[i].name )); clgame.msg[i].number = svc_num; clgame.msg[i].size = iSize; CL_ClearUserMessage( pszName, svc_num ); } void CL_FreeEntity( cl_entity_t *pEdict ) { ASSERT( pEdict ); R_RemoveEfrags( pEdict ); CL_KillDeadBeams( pEdict ); } void CL_ClearWorld( void ) { cl.world = clgame.entities; cl.world->curstate.modelindex = 1; // world model cl.world->curstate.solid = SOLID_BSP; cl.world->curstate.movetype = MOVETYPE_PUSH; cl.world->model = cl.worldmodel; cl.world->index = 0; clgame.ds.cullMode = GL_FRONT; clgame.numStatics = 0; } void CL_InitEdicts( void ) { ASSERT( clgame.entities == NULL ); if( !clgame.mempool ) return; // Host_Error without client CL_UPDATE_BACKUP = ( cl.maxclients == 1 ) ? SINGLEPLAYER_BACKUP : MULTIPLAYER_BACKUP; cls.num_client_entities = CL_UPDATE_BACKUP * 64; cls.packet_entities = Z_Realloc( cls.packet_entities, sizeof( entity_state_t ) * cls.num_client_entities ); clgame.entities = Mem_Alloc( clgame.mempool, sizeof( cl_entity_t ) * clgame.maxEntities ); clgame.static_entities = Mem_Alloc( clgame.mempool, sizeof( cl_entity_t ) * MAX_STATIC_ENTITIES ); clgame.numStatics = 0; if(( clgame.maxRemapInfos - 1 ) != clgame.maxEntities ) { CL_ClearAllRemaps (); // purge old remap info clgame.maxRemapInfos = clgame.maxEntities + 1; clgame.remap_info = (remap_info_t **)Mem_Alloc( clgame.mempool, sizeof( remap_info_t* ) * clgame.maxRemapInfos ); } } void CL_FreeEdicts( void ) { Z_Free( clgame.entities ); clgame.entities = NULL; Z_Free( clgame.static_entities ); clgame.static_entities = NULL; Z_Free( cls.packet_entities ); cls.packet_entities = NULL; cls.num_client_entities = 0; cls.next_client_entities = 0; clgame.numStatics = 0; } void CL_ClearEdicts( void ) { if( clgame.entities != NULL ) return; // in case we stopped with error clgame.maxEntities = 2; CL_InitEdicts(); } /* =============================================================================== CGame Builtin Functions =============================================================================== */ static qboolean CL_LoadHudSprite( const char *szSpriteName, model_t *m_pSprite, qboolean mapSprite, uint texFlags ) { byte *buf; fs_offset_t size; qboolean loaded; ASSERT( m_pSprite != NULL ); buf = FS_LoadFile( szSpriteName, &size, false ); if( !buf ) return false; Q_strncpy( m_pSprite->name, szSpriteName, sizeof( m_pSprite->name )); m_pSprite->flags = 256; // it's hud sprite, make difference names to prevent free shared textures if( mapSprite ) Mod_LoadMapSprite( m_pSprite, buf, (size_t)size, &loaded ); else Mod_LoadSpriteModel( m_pSprite, buf, &loaded, texFlags ); Mem_Free( buf ); if( !loaded ) { Mod_UnloadSpriteModel( m_pSprite ); return false; } return true; } /* ========= pfnSPR_LoadExt ========= */ HSPRITE pfnSPR_LoadExt( const char *szPicName, uint texFlags ) { char name[64]; int i; if( !szPicName || !*szPicName ) { MsgDev( D_ERROR, "CL_LoadSprite: bad name!\n" ); return 0; } Q_strncpy( name, szPicName, sizeof( name )); COM_FixSlashes( name ); // slot 0 isn't used for( i = 1; i < MAX_IMAGES; i++ ) { if( !Q_stricmp( clgame.sprites[i].name, name )) { // prolonge registration clgame.sprites[i].needload = clgame.load_sequence; return i; } } // find a free model slot spot for( i = 1; i < MAX_IMAGES; i++ ) { if( !clgame.sprites[i].name[0] ) break; // this is a valid spot } if( i >= MAX_IMAGES ) { MsgDev( D_ERROR, "SPR_Load: can't load %s, MAX_HSPRITES limit exceeded\n", szPicName ); return 0; } // load new model if( CL_LoadHudSprite( name, &clgame.sprites[i], false, texFlags )) { if( i < MAX_IMAGES - 1 ) { clgame.sprites[i].needload = clgame.load_sequence; } return i; } return 0; } /* ========= pfnSPR_Load ========= */ HSPRITE GAME_EXPORT pfnSPR_Load( const char *szPicName ) { int texFlags = TF_NOPICMIP; if( cl_sprite_nearest->integer ) texFlags |= TF_NEAREST; return pfnSPR_LoadExt( szPicName, texFlags ); } /* ============= CL_GetSpritePointer ============= */ const model_t *GAME_EXPORT CL_GetSpritePointer( HSPRITE hSprite ) { if( hSprite <= 0 || hSprite > ( MAX_IMAGES - 1 )) return NULL; // bad image return &clgame.sprites[hSprite]; } /* ========= pfnSPR_Frames ========= */ static int GAME_EXPORT pfnSPR_Frames( HSPRITE hPic ) { int numFrames; R_GetSpriteParms( NULL, NULL, &numFrames, 0, CL_GetSpritePointer( hPic )); return numFrames; } /* ========= pfnSPR_Height ========= */ static int GAME_EXPORT pfnSPR_Height( HSPRITE hPic, int frame ) { int sprHeight; R_GetSpriteParms( NULL, &sprHeight, NULL, frame, CL_GetSpritePointer( hPic )); return sprHeight; } /* ========= pfnSPR_Width ========= */ static int GAME_EXPORT pfnSPR_Width( HSPRITE hPic, int frame ) { int sprWidth; R_GetSpriteParms( &sprWidth, NULL, NULL, frame, CL_GetSpritePointer( hPic )); return sprWidth; } /* ========= pfnSPR_Set ========= */ static void GAME_EXPORT pfnSPR_Set( HSPRITE hPic, int r, int g, int b ) { clgame.ds.pSprite = CL_GetSpritePointer( hPic ); clgame.ds.spriteColor[0] = bound( 0, r, 255 ); clgame.ds.spriteColor[1] = bound( 0, g, 255 ); clgame.ds.spriteColor[2] = bound( 0, b, 255 ); clgame.ds.spriteColor[3] = 255; // set default state pglDisable( GL_BLEND ); pglDisable( GL_ALPHA_TEST ); pglTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ); } /* ========= pfnSPR_Draw ========= */ static void GAME_EXPORT pfnSPR_Draw( int frame, int x, int y, const wrect_t *prc ) { pglEnable( GL_ALPHA_TEST ); SPR_DrawGeneric( frame, x, y, -1, -1, prc ); } /* ========= pfnSPR_DrawHoles ========= */ static void GAME_EXPORT pfnSPR_DrawHoles( int frame, int x, int y, const wrect_t *prc ) { GL_SetRenderMode( kRenderTransAlpha ); SPR_DrawGeneric( frame, x, y, -1, -1, prc ); } /* ========= pfnSPR_DrawAdditive ========= */ static void GAME_EXPORT pfnSPR_DrawAdditive( int frame, int x, int y, const wrect_t *prc ) { GL_SetRenderMode( kRenderTransAdd ); SPR_DrawGeneric( frame, x, y, -1, -1, prc ); } /* ========= pfnSPR_GetList for parsing half-life scripts - hud.txt etc ========= */ static client_sprite_t *GAME_EXPORT pfnSPR_GetList( char *psz, int *piCount ) { client_sprite_t *pList; int index, numSprites = 0; char *afile, *pfile; string token; byte *pool; if( piCount ) *piCount = 0; if( !clgame.itemspath[0] ) // typically it's sprites\*.txt FS_ExtractFilePath( psz, clgame.itemspath ); afile = (char *)FS_LoadFile( psz, NULL, false ); if( !afile ) return NULL; pfile = afile; pfile = COM_ParseFile( pfile, token ); numSprites = Q_atoi( token ); if( !cl.video_prepped ) pool = cls.mempool; // static memory else pool = com_studiocache; // temporary // name, res, pic, x, y, w, h // NOTE: we must use com_studiocache because it will be purge on next restart or change map pList = Mem_Alloc( pool, sizeof( client_sprite_t ) * numSprites ); for( index = 0; index < numSprites; index++ ) { if(( pfile = COM_ParseFile( pfile, token )) == NULL ) break; Q_strncpy( pList[index].szName, token, sizeof( pList[index].szName )); // read resolution pfile = COM_ParseFile( pfile, token ); pList[index].iRes = Q_atoi( token ); // read spritename pfile = COM_ParseFile( pfile, token ); Q_strncpy( pList[index].szSprite, token, sizeof( pList[index].szSprite )); // parse rectangle pfile = COM_ParseFile( pfile, token ); pList[index].rc.left = Q_atoi( token ); pfile = COM_ParseFile( pfile, token ); pList[index].rc.top = Q_atoi( token ); pfile = COM_ParseFile( pfile, token ); pList[index].rc.right = pList[index].rc.left + Q_atoi( token ); pfile = COM_ParseFile( pfile, token ); pList[index].rc.bottom = pList[index].rc.top + Q_atoi( token ); if( piCount ) (*piCount)++; } if( index < numSprites ) MsgDev( D_WARN, "SPR_GetList: unexpected end of %s (%i should be %i)\n", psz, numSprites, index ); Mem_Free( afile ); return pList; } /* ============= pfnFillRGBA ============= */ void GAME_EXPORT CL_FillRGBA( int x, int y, int width, int height, int r, int g, int b, int a ) { float x1 = x, y1 = y, w1 = width, h1 = height; r = bound( 0, r, 255 ); g = bound( 0, g, 255 ); b = bound( 0, b, 255 ); a = bound( 0, a, 255 ); pglColor4ub( r, g, b, a ); SPR_AdjustSize( &x1, &y1, &w1, &h1 ); GL_SetRenderMode( kRenderTransAdd ); R_DrawStretchPic( x1, y1, w1, h1, 0, 0, 1, 1, cls.fillImage ); pglColor4ub( 255, 255, 255, 255 ); } /* ============= pfnGetScreenInfo get actual screen info ============= */ int GAME_EXPORT pfnGetScreenInfo( SCREENINFO *pscrinfo ) { // setup screen info float scale_factor = hud_scale->value; clgame.scrInfo.iSize = sizeof( clgame.scrInfo ); if( scale_factor && scale_factor != 1.0f) { clgame.scrInfo.iWidth = scr_width->value / scale_factor; clgame.scrInfo.iHeight = scr_height->value / scale_factor; clgame.scrInfo.iFlags |= SCRINFO_STRETCHED; } else { clgame.scrInfo.iWidth = scr_width->integer; clgame.scrInfo.iHeight = scr_height->integer; clgame.scrInfo.iFlags &= ~SCRINFO_STRETCHED; } if( !pscrinfo ) return 0; if( pscrinfo->iSize != clgame.scrInfo.iSize ) clgame.scrInfo.iSize = pscrinfo->iSize; // copy screeninfo out Q_memcpy( pscrinfo, &clgame.scrInfo, clgame.scrInfo.iSize ); return 1; } /* ============= pfnSetCrosshair setup crosshair ============= */ static void GAME_EXPORT pfnSetCrosshair( HSPRITE hspr, wrect_t rc, int r, int g, int b ) { crosshair_state.rgbaCrosshair[0] = (byte)r; crosshair_state.rgbaCrosshair[1] = (byte)g; crosshair_state.rgbaCrosshair[2] = (byte)b; crosshair_state.rgbaCrosshair[3] = (byte)0xFF; crosshair_state.pCrosshair = CL_GetSpritePointer( hspr ); crosshair_state.rcCrosshair = rc; } /* ============= pfnHookUserMsg ============= */ static int GAME_EXPORT pfnHookUserMsg( const char *pszName, pfnUserMsgHook pfn ) { int i; // ignore blank names or invalid callbacks if( !pszName || !*pszName || !pfn ) return 0; for( i = 0; i < MAX_USER_MESSAGES && clgame.msg[i].name[0]; i++ ) { // see if already hooked if( !Q_strcmp( clgame.msg[i].name, pszName )) return 1; } if( i == MAX_USER_MESSAGES ) { Host_Error( "HookUserMsg: MAX_USER_MESSAGES hit!\n" ); return 0; } // hook new message Q_strncpy( clgame.msg[i].name, pszName, sizeof( clgame.msg[i].name )); clgame.msg[i].func = pfn; return 1; } /* ============= pfnServerCmd ============= */ static int GAME_EXPORT pfnServerCmd( const char *szCmdString ) { string buf; if( !szCmdString || !szCmdString[0] ) return 0; // just like the client typed "cmd xxxxx" at the console Q_snprintf( buf, sizeof( buf ) - 1, "cmd %s\n", szCmdString ); Cbuf_AddText( buf ); return 1; } /* ============= pfnClientCmd ============= */ static int GAME_EXPORT pfnClientCmd( const char *szCmdString ) { if( !szCmdString || !szCmdString[0] ) return 0; Cbuf_AddText( szCmdString ); Cbuf_AddText( "\n" ); return 1; } /* ============= pfnGetPlayerInfo ============= */ static void GAME_EXPORT pfnGetPlayerInfo( int ent_num, hud_player_info_t *pinfo ) { player_info_t *player; cl_entity_t *ent; qboolean spec = false; ent = CL_GetEntityByIndex( ent_num ); ent_num -= 1; // player list if offset by 1 from ents if( ent_num >= cl.maxclients || ent_num < 0 || !cl.players[ent_num].name[0] ) { Q_memset( pinfo, 0, sizeof( *pinfo )); return; } player = &cl.players[ent_num]; pinfo->thisplayer = ( ent_num == cl.playernum ) ? true : false; if( ent ) spec = ent->curstate.spectator; pinfo->name = player->name; pinfo->model = player->model; pinfo->spectator = spec; pinfo->ping = player->ping; pinfo->packetloss = player->packet_loss; pinfo->topcolor = Q_atoi( Info_ValueForKey( player->userinfo, "topcolor" )); pinfo->bottomcolor = Q_atoi( Info_ValueForKey( player->userinfo, "bottomcolor" )); } /* ============= pfnPlaySoundByName ============= */ static void GAME_EXPORT pfnPlaySoundByName( const char *szSound, float volume ) { int hSound = S_RegisterSound( szSound ); S_StartSound( NULL, cl.refdef.viewentity, CHAN_ITEM, hSound, volume, ATTN_NORM, PITCH_NORM, SND_STOP_LOOPING ); } /* ============= pfnPlaySoundByIndex ============= */ static void GAME_EXPORT pfnPlaySoundByIndex( int iSound, float volume ) { int hSound; // make sure what we in-bounds iSound = bound( 0, iSound, MAX_SOUNDS ); hSound = cl.sound_index[iSound]; if( !hSound ) { MsgDev( D_ERROR, "CL_PlaySoundByIndex: invalid sound handle %i\n", iSound ); return; } S_StartSound( NULL, cl.refdef.viewentity, CHAN_ITEM, hSound, volume, ATTN_NORM, PITCH_NORM, SND_STOP_LOOPING ); } /* ============= pfnTextMessageGet returns specified message from titles.txt ============= */ client_textmessage_t *GAME_EXPORT CL_TextMessageGet( const char *pName ) { int i; // first check internal messages for( i = 0; i < MAX_TEXTCHANNELS; i++ ) { if( !Q_strcmp( pName, va( TEXT_MSGNAME, i ))) return cl_textmessage + i; } // find desired message for( i = 0; i < clgame.numTitles; i++ ) { if( !Q_stricmp( pName, clgame.titles[i].pName )) return clgame.titles + i; } return NULL; // found nothing } /* ============= pfnDrawCharacter returns drawed chachter width (in real screen pixels) ============= */ int GAME_EXPORT pfnDrawCharacter( int x, int y, int number, int r, int g, int b ) { if( !cls.creditsFont.valid ) return 0; number &= 255; if( hud_utf8->integer ) number = Con_UtfProcessChar( number ); if( number < 32 ) return 0; if( y < -clgame.scrInfo.iCharHeight ) return 0; clgame.ds.adjust_size = true; pfnPIC_Set( cls.creditsFont.hFontTexture, r, g, b, 255 ); pfnPIC_DrawAdditive( x, y, -1, -1, &cls.creditsFont.fontRc[number] ); clgame.ds.adjust_size = false; return clgame.scrInfo.charWidths[number]; } /* ============= pfnDrawConsoleString drawing string like a console string ============= */ int GAME_EXPORT pfnDrawConsoleString( int x, int y, char *string ) { int drawLen; if( !string || !*string ) return 0; // silent ignore clgame.ds.adjust_size = true; Con_SetFont( con_fontsize->integer ); drawLen = Con_DrawString( x, y, string, clgame.ds.textColor ); MakeRGBA( clgame.ds.textColor, 255, 255, 255, 255 ); clgame.ds.adjust_size = false; Con_RestoreFont(); return (x + drawLen); // exclude color prexfixes } /* ============= pfnDrawSetTextColor set color for anything ============= */ void GAME_EXPORT pfnDrawSetTextColor( float r, float g, float b ) { // bound color and convert to byte clgame.ds.textColor[0] = (byte)bound( 0, r * 255, 255 ); clgame.ds.textColor[1] = (byte)bound( 0, g * 255, 255 ); clgame.ds.textColor[2] = (byte)bound( 0, b * 255, 255 ); clgame.ds.textColor[3] = (byte)0xFF; } /* ============= pfnDrawConsoleStringLen compute string length in screen pixels ============= */ void GAME_EXPORT pfnDrawConsoleStringLen( const char *pText, int *length, int *height ) { Con_SetFont( con_fontsize->integer ); Con_DrawStringLen( pText, length, height ); Con_RestoreFont(); } /* ============= pfnConsolePrint prints directly into console (can skip notify) ============= */ static void GAME_EXPORT pfnConsolePrint( const char *string ) { if( !string || !*string ) return; if( *string != 1 ) Msg( "%s", string ); // show notify else Con_NPrintf( 0, "%s", (char *)string + 1 ); // skip notify } /* ============= pfnCenterPrint holds and fade message at center of screen like trigger_multiple message in q1 ============= */ static void GAME_EXPORT pfnCenterPrint( const char *string ) { if( !string || !*string ) return; // someone stupid joke CL_CenterPrint( string, 0.25f ); } /* ========= GetWindowCenterX ========= */ static int GAME_EXPORT pfnGetWindowCenterX( void ) { int x = 0; #ifdef _WIN32 if( m_ignore->integer ) { POINT pos; GetCursorPos( &pos ); return pos.x; } #endif #ifdef XASH_SDL SDL_GetWindowPosition( host.hWnd, &x, NULL ); #endif return host.window_center_x + x; } /* ========= GetWindowCenterY ========= */ static int GAME_EXPORT pfnGetWindowCenterY( void ) { int y = 0; #ifdef _WIN32 if( m_ignore->integer ) { POINT pos; GetCursorPos( &pos ); return pos.y; } #endif #ifdef XASH_SDL SDL_GetWindowPosition( host.hWnd, NULL, &y ); #endif return host.window_center_y + y; } /* ============= pfnGetViewAngles return interpolated angles from previous frame ============= */ static void GAME_EXPORT pfnGetViewAngles( float *angles ) { if( angles ) VectorCopy( cl.refdef.cl_viewangles, angles ); } /* ============= pfnSetViewAngles return interpolated angles from previous frame ============= */ static void GAME_EXPORT pfnSetViewAngles( float *angles ) { if( angles ) VectorCopy( angles, cl.refdef.cl_viewangles ); } /* ============= pfnPhysInfo_ValueForKey ============= */ static const char* GAME_EXPORT pfnPhysInfo_ValueForKey( const char *key ) { return Info_ValueForKey( cl.frame.client.physinfo, key ); } /* ============= pfnServerInfo_ValueForKey ============= */ static const char* GAME_EXPORT pfnServerInfo_ValueForKey( const char *key ) { return Info_ValueForKey( cl.serverinfo, key ); } /* ============= pfnGetClientMaxspeed value that come from server ============= */ static float GAME_EXPORT pfnGetClientMaxspeed( void ) { return cl.frame.client.maxspeed; } /* ============= pfnCheckParm ============= */ static int GAME_EXPORT pfnCheckParm( char *parm, char **ppnext ) { static char str[64]; if( Sys_GetParmFromCmdLine( parm, str )) { // get the pointer on cmdline param if( ppnext ) *ppnext = str; return 1; } return 0; } /* ============= pfnGetMousePosition ============= */ void GAME_EXPORT CL_GetMousePosition( int *mx, int *my ) { #ifdef XASH_SDL SDL_GetMouseState(mx, my); #else mx=my=0; #endif } /* ============= pfnIsNoClipping ============= */ int GAME_EXPORT pfnIsNoClipping( void ) { cl_entity_t *pl = CL_GetLocalPlayer(); if( !pl ) return false; return pl->curstate.movetype == MOVETYPE_NOCLIP; } /* ============= pfnGetViewModel ============= */ static cl_entity_t* GAME_EXPORT pfnGetViewModel( void ) { return &clgame.viewent; } /* ============= pfnGetClientTime ============= */ static float GAME_EXPORT pfnGetClientTime( void ) { return cl.time; } /* ============= pfnCalcShake ============= */ void GAME_EXPORT pfnCalcShake( void ) { int i; float fraction, freq; float localAmp; if( clgame.shake.time == 0 ) return; if(( cl.time > clgame.shake.time ) || clgame.shake.amplitude <= 0 || clgame.shake.frequency <= 0 ) { Q_memset( &clgame.shake, 0, sizeof( clgame.shake )); return; } if( cl.time > clgame.shake.next_shake ) { // higher frequency means we recalc the extents more often and perturb the display again clgame.shake.next_shake = cl.time + ( 1.0f / clgame.shake.frequency ); // compute random shake extents (the shake will settle down from this) for( i = 0; i < 3; i++ ) clgame.shake.offset[i] = Com_RandomFloat( -clgame.shake.amplitude, clgame.shake.amplitude ); clgame.shake.angle = Com_RandomFloat( -clgame.shake.amplitude * 0.25f, clgame.shake.amplitude * 0.25f ); } // ramp down amplitude over duration (fraction goes from 1 to 0 linearly with slope 1/duration) fraction = ( clgame.shake.time - cl.time ) / clgame.shake.duration; // ramp up frequency over duration if( fraction ) { freq = ( clgame.shake.frequency / fraction ); } else { freq = 0; } // square fraction to approach zero more quickly fraction *= fraction; // Sine wave that slowly settles to zero fraction = fraction * sin( cl.time * freq ); // add to view origin VectorScale( clgame.shake.offset, fraction, clgame.shake.applied_offset ); // add to roll clgame.shake.applied_angle = clgame.shake.angle * fraction; // drop amplitude a bit, less for higher frequency shakes localAmp = clgame.shake.amplitude * ( host.frametime / ( clgame.shake.duration * clgame.shake.frequency )); clgame.shake.amplitude -= localAmp; } /* ============= pfnApplyShake ============= */ void GAME_EXPORT pfnApplyShake( float *origin, float *angles, float factor ) { if( origin ) VectorMA( origin, factor, clgame.shake.applied_offset, origin ); if( angles ) angles[ROLL] += clgame.shake.applied_angle * factor; } /* ============= pfnIsSpectateOnly ============= */ static int GAME_EXPORT pfnIsSpectateOnly( void ) { cl_entity_t *pPlayer = CL_GetLocalPlayer(); return pPlayer ? (pPlayer->curstate.spectator != 0) : 0; } /* ============= pfnPointContents ============= */ static int GAME_EXPORT pfnPointContents( const float *p, int *truecontents ) { int cont, truecont; truecont = cont = CL_TruePointContents( p ); if( truecontents ) *truecontents = truecont; if( cont <= CONTENTS_CURRENT_0 && cont >= CONTENTS_CURRENT_DOWN ) cont = CONTENTS_WATER; return cont; } /* ============= pfnTraceLine ============= */ static pmtrace_t *GAME_EXPORT pfnTraceLine( float *start, float *end, int flags, int usehull, int ignore_pe ) { static pmtrace_t tr; int old_usehull; old_usehull = clgame.pmove->usehull; clgame.pmove->usehull = usehull; switch( flags ) { case PM_TRACELINE_PHYSENTSONLY: tr = PM_PlayerTraceExt( clgame.pmove, start, end, 0, clgame.pmove->numphysent, clgame.pmove->physents, ignore_pe, NULL ); break; case PM_TRACELINE_ANYVISIBLE: tr = PM_PlayerTraceExt( clgame.pmove, start, end, 0, clgame.pmove->numvisent, clgame.pmove->visents, ignore_pe, NULL ); break; } clgame.pmove->usehull = old_usehull; return &tr; } static void GAME_EXPORT pfnPlaySoundByNameAtLocation( char *szSound, float volume, float *origin ) { int hSound = S_RegisterSound( szSound ); S_StartSound( origin, 0, CHAN_AUTO, hSound, volume, ATTN_NORM, PITCH_NORM, 0 ); } /* ============= pfnPrecacheEvent ============= */ static word GAME_EXPORT pfnPrecacheEvent( int type, const char* psz ) { return CL_EventIndex( psz ); } /* ============= pfnHookEvent ============= */ static void GAME_EXPORT pfnHookEvent( const char *filename, pfnEventHook pfn ) { char name[64]; cl_user_event_t *ev; int i; // ignore blank names if( !filename || !*filename ) return; Q_strncpy( name, filename, sizeof( name )); COM_FixSlashes( name ); // find an empty slot for( i = 0; i < MAX_EVENTS; i++ ) { ev = clgame.events[i]; if( !ev ) break; if( !Q_stricmp( name, ev->name ) && ev->func != NULL ) { MsgDev( D_WARN, "CL_HookEvent: %s already hooked!\n", name ); return; } } CL_RegisterEvent( i, name, pfn ); } /* ============= pfnKillEvent ============= */ static void GAME_EXPORT pfnKillEvents( int entnum, const char *eventname ) { int i; event_state_t *es; event_info_t *ei; int eventIndex = CL_EventIndex( eventname ); if( eventIndex < 0 || eventIndex >= MAX_EVENTS ) return; if( entnum < 0 || entnum > clgame.maxEntities ) return; es = &cl.events; // find all events with specified index and kill it for( i = 0; i < MAX_EVENT_QUEUE; i++ ) { ei = &es->ei[i]; if( ei->index == eventIndex && ei->entity_index == entnum ) { CL_ResetEvent( ei ); break; } } } /* ============= pfnPlaySound ============= */ void GAME_EXPORT pfnPlaySound( int ent, float *org, int chan, const char *samp, float vol, float attn, int flags, int pitch ) { S_StartSound( org, ent, chan, S_RegisterSound( samp ), vol, attn, pitch, flags ); } /* ============= CL_FindModelIndex ============= */ int GAME_EXPORT CL_FindModelIndex( const char *m ) { int i; if( !m || !m[0] ) return 0; for( i = 1; i < MAX_MODELS && cl.model_precache[i][0]; i++ ) { if( !Q_stricmp( cl.model_precache[i], m )) return i; } if( cls.state == ca_active && Q_strnicmp( m, "models/player/", 14 )) { // tell user about problem (but don't spam console about playermodel) MsgDev( D_NOTE, "CL_ModelIndex: %s not precached\n", m ); } return 0; } /* ============= pfnIsLocal ============= */ int GAME_EXPORT pfnIsLocal( int playernum ) { if( playernum == cl.playernum ) return true; return false; } /* ============= pfnLocalPlayerDucking ============= */ int GAME_EXPORT pfnLocalPlayerDucking( void ) { return cl.predicted.usehull == 1; } /* ============= pfnLocalPlayerViewheight ============= */ void GAME_EXPORT pfnLocalPlayerViewheight( float *view_ofs ) { // predicted or smoothed if( !view_ofs ) return; if( CL_IsPredicted( )) VectorCopy( cl.predicted.viewofs, view_ofs ); else VectorCopy( cl.frame.client.view_ofs, view_ofs ); } /* ============= pfnLocalPlayerBounds ============= */ void GAME_EXPORT pfnLocalPlayerBounds( int hull, float *mins, float *maxs ) { if( hull >= 0 && hull < 4 ) { if( mins ) VectorCopy( clgame.pmove->player_mins[hull], mins ); if( maxs ) VectorCopy( clgame.pmove->player_maxs[hull], maxs ); } } /* ============= pfnIndexFromTrace ============= */ int GAME_EXPORT pfnIndexFromTrace( struct pmtrace_s *pTrace ) { if( pTrace->ent >= 0 && pTrace->ent < clgame.pmove->numphysent ) { // return cl.entities number return clgame.pmove->physents[pTrace->ent].info; } return -1; } /* ============= pfnGetPhysent ============= */ physent_t *GAME_EXPORT pfnGetPhysent( int idx ) { if( idx >= 0 && idx < clgame.pmove->numphysent ) { // return physent return &clgame.pmove->physents[idx]; } return NULL; } /* ============= pfnSetTraceHull ============= */ void GAME_EXPORT CL_SetTraceHull( int hull ) { //clgame.old_trace_hull = clgame.pmove->usehull; clgame.pmove->usehull = bound( 0, hull, 3 ); } /* ============= pfnPlayerTrace ============= */ void GAME_EXPORT CL_PlayerTrace( float *start, float *end, int traceFlags, int ignore_pe, pmtrace_t *tr ) { if( !tr ) return; *tr = PM_PlayerTraceExt( clgame.pmove, start, end, traceFlags, clgame.pmove->numphysent, clgame.pmove->physents, ignore_pe, NULL ); //clgame.pmove->usehull = clgame.old_trace_hull; // restore old trace hull } /* ============= pfnPlayerTraceExt ============= */ void GAME_EXPORT CL_PlayerTraceExt( float *start, float *end, int traceFlags, int (*pfnIgnore)( physent_t *pe ), pmtrace_t *tr ) { if( !tr ) return; *tr = PM_PlayerTraceExt( clgame.pmove, start, end, traceFlags, clgame.pmove->numphysent, clgame.pmove->physents, -1, pfnIgnore ); //clgame.pmove->usehull = clgame.old_trace_hull; // restore old trace hull } /* ============= pfnTraceTexture ============= */ static const char *GAME_EXPORT pfnTraceTexture( int ground, float *vstart, float *vend ) { physent_t *pe; if( ground < 0 || ground >= clgame.pmove->numphysent ) return NULL; // bad ground pe = &clgame.pmove->physents[ground]; return PM_TraceTexture( pe, vstart, vend ); } /* ============= pfnTraceSurface ============= */ static struct msurface_s *GAME_EXPORT pfnTraceSurface( int ground, float *vstart, float *vend ) { physent_t *pe; if( ground < 0 || ground >= clgame.pmove->numphysent ) return NULL; // bad ground pe = &clgame.pmove->physents[ground]; return PM_TraceSurface( pe, vstart, vend ); } /* ============= pfnStopAllSounds ============= */ void GAME_EXPORT pfnStopAllSounds( int ent, int entchannel ) { S_StopSound( ent, entchannel, NULL ); } /* ============= CL_LoadModel ============= */ model_t *GAME_EXPORT CL_LoadModel( const char *modelname, int *index ) { int idx; idx = CL_FindModelIndex( modelname ); if( !idx ) return NULL; if( index ) *index = idx; return Mod_Handle( idx ); } int GAME_EXPORT CL_AddEntity( int entityType, cl_entity_t *pEnt ) { if( !pEnt ) return false; // clear effects for all temp entities if( !pEnt->index ) pEnt->curstate.effects = 0; // let the render reject entity without model return CL_AddVisibleEntity( pEnt, entityType ); } /* ============= pfnGetGameDirectory ============= */ const char *GAME_EXPORT pfnGetGameDirectory( void ) { static char szGetGameDir[MAX_SYSPATH]; Q_sprintf( szGetGameDir, "%s", GI->gamedir ); return szGetGameDir; } /* ============= Key_LookupBinding ============= */ const char *GAME_EXPORT Key_LookupBinding( const char *pBinding ) { return Key_KeynumToString( Key_GetKey( pBinding )); } /* ============= pfnGetLevelName ============= */ static const char *GAME_EXPORT pfnGetLevelName( void ) { static char mapname[64]; if( cls.state >= ca_connected ) Q_snprintf( mapname, sizeof( mapname ), "maps/%s.bsp", clgame.mapname ); else mapname[0] = '\0'; // not in game return mapname; } /* ============= pfnGetScreenFade ============= */ static void GAME_EXPORT pfnGetScreenFade( struct screenfade_s *fade ) { if( fade ) *fade = clgame.fade; } /* ============= pfnSetScreenFade ============= */ static void GAME_EXPORT pfnSetScreenFade( struct screenfade_s *fade ) { if( fade ) clgame.fade = *fade; } /* ============= pfnLoadMapSprite ============= */ model_t *GAME_EXPORT pfnLoadMapSprite( const char *filename ) { char name[64]; int i; int texFlags = TF_NOPICMIP; if( cl_sprite_nearest->integer ) texFlags |= TF_NEAREST; if( !filename || !*filename ) { MsgDev( D_ERROR, "CL_LoadMapSprite: bad name!\n" ); return NULL; } Q_strncpy( name, filename, sizeof( name )); COM_FixSlashes( name ); // slot 0 isn't used for( i = 1; i < MAX_IMAGES; i++ ) { if( !Q_stricmp( clgame.sprites[i].name, name )) { // prolonge registration clgame.sprites[i].needload = clgame.load_sequence; return &clgame.sprites[i]; } } // find a free model slot spot for( i = 1; i < MAX_IMAGES; i++ ) { if( !clgame.sprites[i].name[0] ) break; // this is a valid spot } if( i == MAX_IMAGES ) { MsgDev( D_ERROR, "LoadMapSprite: can't load %s, MAX_HSPRITES limit exceeded\n", filename ); return NULL; } // load new map sprite if( CL_LoadHudSprite( name, &clgame.sprites[i], true, texFlags )) { clgame.sprites[i].needload = clgame.load_sequence; return &clgame.sprites[i]; } return NULL; } /* ============= PlayerInfo_ValueForKey ============= */ const char *GAME_EXPORT PlayerInfo_ValueForKey( int playerNum, const char *key ) { // find the player if(( playerNum > cl.maxclients ) || ( playerNum < 1 )) return NULL; if( !cl.players[playerNum-1].name[0] ) return NULL; return Info_ValueForKey( cl.players[playerNum-1].userinfo, key ); } /* ============= PlayerInfo_SetValueForKey ============= */ void GAME_EXPORT PlayerInfo_SetValueForKey( const char *key, const char *value ) { cvar_t *var; var = (cvar_t *)Cvar_FindVar( key ); if( !var || !(var->flags & CVAR_USERINFO )) return; Cvar_DirectSet( var, value ); } /* ============= pfnGetPlayerUniqueID ============= */ qboolean GAME_EXPORT pfnGetPlayerUniqueID( int iPlayer, char playerID[16] ) { // TODO: implement playerID[0] = '\0'; return false; } /* ============= pfnGetTrackerIDForPlayer ============= */ int GAME_EXPORT pfnGetTrackerIDForPlayer( int playerSlot ) { playerSlot -= 1; // make into a client index if( !cl.players[playerSlot].userinfo[0] || !cl.players[playerSlot].name[0] ) return 0; return Q_atoi( Info_ValueForKey( cl.players[playerSlot].userinfo, "*tracker" )); } /* ============= pfnGetPlayerForTrackerID ============= */ int GAME_EXPORT pfnGetPlayerForTrackerID( int trackerID ) { int i; for( i = 0; i < MAX_CLIENTS; i++ ) { if( !cl.players[i].userinfo[0] || !cl.players[i].name[0] ) continue; if( Q_atoi( Info_ValueForKey( cl.players[i].userinfo, "*tracker" )) == trackerID ) { // make into a player slot return (i+1); } } return 0; } /* ============= pfnServerCmdUnreliable ============= */ int GAME_EXPORT pfnServerCmdUnreliable( char *szCmdString ) { if( !szCmdString || !szCmdString[0] ) return 0; BF_WriteByte( &cls.datagram, clc_stringcmd ); BF_WriteString( &cls.datagram, szCmdString ); return 1; } /* ============= pfnGetMousePos ============= */ void GAME_EXPORT pfnGetMousePos( POINT *ppt ) { #ifdef XASH_SDL SDL_GetMouseState(&ppt->x, &ppt->y); #else ppt->x=ppt->y=0; #endif } /* ============= pfnSetMousePos ============= */ void GAME_EXPORT pfnSetMousePos( int mx, int my ) { #ifdef XASH_SDL SDL_WarpMouseInWindow(host.hWnd, mx, my); #endif } /* ============= pfnSetMouseEnable ============= */ void GAME_EXPORT pfnSetMouseEnable( qboolean fEnable ) { if( fEnable ) IN_ActivateMouse( false ); else IN_DeactivateMouse(); } /* ============= pfnGetServerTime ============= */ float GAME_EXPORT pfnGetClientOldTime( void ) { return cl.oldtime; } /* ============= pfnGetGravity ============= */ float GAME_EXPORT pfnGetGravity( void ) { return clgame.movevars.gravity; } /* ============= pfnEnableTexSort TODO: implement ============= */ void GAME_EXPORT pfnEnableTexSort( int enable ) { } /* ============= pfnSetLightmapColor TODO: implement ============= */ void GAME_EXPORT pfnSetLightmapColor( float red, float green, float blue ) { } /* ============= pfnSetLightmapScale TODO: implement ============= */ void GAME_EXPORT pfnSetLightmapScale( float scale ) { } /* ============= pfnSPR_DrawGeneric ============= */ void GAME_EXPORT pfnSPR_DrawGeneric( int frame, int x, int y, const wrect_t *prc, int blendsrc, int blenddst, int width, int height ) { pglEnable( GL_BLEND ); pglBlendFunc( blendsrc, blenddst ); // g-cont. are params is valid? SPR_DrawGeneric( frame, x, y, width, height, prc ); } /* ============= LocalPlayerInfo_ValueForKey ============= */ const char *GAME_EXPORT LocalPlayerInfo_ValueForKey( const char* key ) { return Info_ValueForKey( Cvar_Userinfo(), key ); } /* ============= pfnVGUI2DrawCharacter ============= */ int GAME_EXPORT pfnVGUI2DrawCharacter( int x, int y, int number, unsigned int font ) { if( !cls.creditsFont.valid ) return 0; number &= 255; number = Con_UtfProcessChar( number ); if( number < 32 ) return 0; if( y < -clgame.scrInfo.iCharHeight ) return 0; clgame.ds.adjust_size = true; menu.ds.gl_texturenum = cls.creditsFont.hFontTexture; pfnPIC_DrawAdditive( x, y, -1, -1, &cls.creditsFont.fontRc[number] ); clgame.ds.adjust_size = false; return clgame.scrInfo.charWidths[number]; } /* ============= pfnVGUI2DrawCharacterAdditive ============= */ int GAME_EXPORT pfnVGUI2DrawCharacterAdditive( int x, int y, int ch, int r, int g, int b, unsigned int font ) { if( !hud_utf8->integer ) ch = Con_UtfProcessChar( ch ); return pfnDrawCharacter( x, y, ch, r, g, b ); } /* ============= pfnDrawString ============= */ int GAME_EXPORT pfnDrawString( int x, int y, const char *str, int r, int g, int b ) { Con_UtfProcessChar(0); // draw the string until we hit the null character or a newline character for ( ; *str != 0 && *str != '\n'; str++ ) { x += pfnVGUI2DrawCharacterAdditive( x, y, (unsigned char)*str, r, g, b, 0 ); } return x; } /* ============= pfnDrawStringReverse ============= */ int GAME_EXPORT pfnDrawStringReverse( int x, int y, const char *str, int r, int g, int b ) { // find the end of the string char *szIt; for( szIt = (char*)str; *szIt != 0; szIt++ ) x -= clgame.scrInfo.charWidths[ (unsigned char) *szIt ]; pfnDrawString( x, y, str, r, g, b ); return x; } /* ============= GetCareerGameInterface ============= */ void *GAME_EXPORT GetCareerGameInterface( void ) { Msg( "^1Career GameInterface called!\n" ); return NULL; } /* ============= pfnPlaySoundVoiceByName ============= */ void GAME_EXPORT pfnPlaySoundVoiceByName( char *filename, float volume, int pitch ) { int hSound = S_RegisterSound( filename ); S_StartSound( NULL, cl.refdef.viewentity, CHAN_AUTO, hSound, volume, ATTN_NORM, pitch, SND_STOP_LOOPING ); } /* ============= pfnMP3_InitStream ============= */ void GAME_EXPORT pfnMP3_InitStream( char *filename, int looping ) { if( !filename ) { S_StopBackgroundTrack(); return; } if( looping ) { S_StartBackgroundTrack( filename, filename, 0 ); } else { S_StartBackgroundTrack( filename, NULL, 0 ); } } /* ============= pfnPlaySoundByNameAtPitch ============= */ void GAME_EXPORT pfnPlaySoundByNameAtPitch( char *filename, float volume, int pitch ) { int hSound = S_RegisterSound( filename ); S_StartSound( NULL, cl.refdef.viewentity, CHAN_STATIC, hSound, volume, ATTN_NORM, pitch, SND_STOP_LOOPING ); } /* ============= pfnFillRGBABlend ============= */ void GAME_EXPORT CL_FillRGBABlend( int x, int y, int width, int height, int r, int g, int b, int a ) { float x1 = x, y1 = y, w1 = width, h1 = height; r = bound( 0, r, 255 ); g = bound( 0, g, 255 ); b = bound( 0, b, 255 ); a = bound( 0, a, 255 ); pglColor4ub( r, g, b, a ); SPR_AdjustSize( &x1, &y1, &w1, &h1 ); GL_SetRenderMode( kRenderTransTexture ); R_DrawStretchPic( x1, y1, w1, h1, 0, 0, 1, 1, cls.fillImage ); pglColor4ub( 255, 255, 255, 255 ); } /* ============= pfnGetAppID ============= */ int GAME_EXPORT pfnGetAppID( void ) { return 130; //return 220; // standard Valve value } /* ============= pfnVguiWrap2_GetMouseDelta TODO: implement ============= */ void GAME_EXPORT pfnVguiWrap2_GetMouseDelta( int *x, int *y ) { } /* ================= TriApi implementation ================= */ /* ============= TriRenderMode set rendermode ============= */ void GAME_EXPORT TriRenderMode( int mode ) { switch( mode ) { case kRenderNormal: default: pglDisable( GL_BLEND ); pglDisable( GL_ALPHA_TEST ); pglTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ); break; case kRenderTransColor: case kRenderTransAlpha: case kRenderTransTexture: // NOTE: TriAPI doesn't have 'solid' mode pglEnable( GL_BLEND ); pglDisable( GL_ALPHA_TEST ); pglBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); pglTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ); break; case kRenderGlow: case kRenderTransAdd: pglEnable( GL_BLEND ); pglDisable( GL_ALPHA_TEST ); pglBlendFunc( GL_SRC_ALPHA, GL_ONE ); pglTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ); break; } } #ifdef __vita__ static int tri_mode = 0; static int tri_numverts = 0; static float *tri_vertp = NULL; static float *tri_colorp = NULL; static float *tri_texp = NULL; #endif /* ============= TriBegin begin triangle sequence ============= */ void GAME_EXPORT TriBegin( int mode ) { switch( mode ) { case TRI_POINTS: mode = GL_POINTS; break; case TRI_TRIANGLES: mode = GL_TRIANGLES; break; case TRI_TRIANGLE_FAN: mode = GL_TRIANGLE_FAN; break; case TRI_QUADS: mode = GL_QUADS; break; case TRI_LINES: mode = GL_LINES; break; case TRI_TRIANGLE_STRIP: mode = GL_TRIANGLE_STRIP; break; case TRI_QUAD_STRIP: mode = GL_QUAD_STRIP; break; case TRI_POLYGON: default: mode = GL_POLYGON; break; } #ifdef __vita__ if( mode == GL_POLYGON || mode == GL_QUADS ) mode = GL_TRIANGLE_FAN; else if ( mode == GL_QUAD_STRIP ) mode = GL_TRIANGLE_STRIP; tri_mode = mode; tri_vertp = gl_vgl_verts; tri_colorp = gl_vgl_colors; tri_texp = gl_vgl_texcoords; tri_numverts = 0; #else pglBegin( mode ); #endif } /* ============= TriEnd draw triangle sequence ============= */ void GAME_EXPORT TriEnd( void ) { #ifdef __vita__ if( tri_numverts && tri_vertp != gl_vgl_verts ) { pglEnableClientState( GL_VERTEX_ARRAY ); Vita_VertexPointer( 3, GL_FLOAT, 0, tri_numverts, gl_vgl_verts ); if( tri_texp != gl_vgl_texcoords ) { pglEnableClientState( GL_TEXTURE_COORD_ARRAY ); Vita_TexCoordPointer( 2, GL_FLOAT, 0, tri_numverts, gl_vgl_texcoords ); } if( tri_colorp != gl_vgl_colors ) { pglEnableClientState( GL_COLOR_ARRAY ); Vita_ColorPointer( 4, GL_FLOAT, 0, tri_numverts, gl_vgl_colors ); } Vita_DrawGLPoly( tri_mode, tri_numverts, GL_TRUE ); pglDisableClientState( GL_VERTEX_ARRAY ); pglDisableClientState( GL_TEXTURE_COORD_ARRAY ); pglDisableClientState( GL_COLOR_ARRAY ); } tri_mode = 0; tri_numverts = 0; #else pglEnd(); #endif pglDisable( GL_ALPHA_TEST ); } /* ============= TriColor4f ============= */ void GAME_EXPORT TriColor4f( float r, float g, float b, float a ) { clgame.ds.triColor[0] = (byte)bound( 0, (r * 255.0f), 255 ); clgame.ds.triColor[1] = (byte)bound( 0, (g * 255.0f), 255 ); clgame.ds.triColor[2] = (byte)bound( 0, (b * 255.0f), 255 ); clgame.ds.triColor[3] = (byte)bound( 0, (a * 255.0f), 255 ); pglColor4ub( clgame.ds.triColor[0], clgame.ds.triColor[1], clgame.ds.triColor[2], clgame.ds.triColor[3] ); #ifdef __vita__ if( !tri_mode ) return; *(tri_colorp++) = r; *(tri_colorp++) = g; *(tri_colorp++) = b; *(tri_colorp++) = a; #endif } /* ============= TriColor4ub ============= */ void GAME_EXPORT TriColor4ub( byte r, byte g, byte b, byte a ) { clgame.ds.triColor[0] = r; clgame.ds.triColor[1] = g; clgame.ds.triColor[2] = b; clgame.ds.triColor[3] = a; pglColor4ub( r, g, b, a ); #ifdef __vita__ if( !tri_mode ) return; *(tri_colorp++) = r / 255.f; *(tri_colorp++) = g / 255.f; *(tri_colorp++) = b / 255.f; *(tri_colorp++) = a / 255.f; #endif } /* ============= TriTexCoord2f ============= */ void GAME_EXPORT TriTexCoord2f( float u, float v ) { #ifdef __vita__ *(tri_texp++) = u; *(tri_texp++) = v; #else pglTexCoord2f( u, v ); #endif } /* ============= TriVertex3fv ============= */ void GAME_EXPORT TriVertex3fv( const float *v ) { #ifdef __vita__ *(tri_vertp++) = v[0]; *(tri_vertp++) = v[1]; *(tri_vertp++) = v[2]; tri_numverts++; #else pglVertex3fv( v ); #endif } /* ============= TriVertex3f ============= */ void GAME_EXPORT TriVertex3f( float x, float y, float z ) { #ifdef __vita__ *(tri_vertp++) = x; *(tri_vertp++) = y; *(tri_vertp++) = z; tri_numverts++; #else pglVertex3f( x, y, z ); #endif } /* ============= TriBrightness ============= */ void GAME_EXPORT TriBrightness( float brightness ) { rgba_t rgba; brightness = max( 0.0f, brightness ); rgba[0] = clgame.ds.triColor[0] * brightness; rgba[1] = clgame.ds.triColor[1] * brightness; rgba[2] = clgame.ds.triColor[2] * brightness; rgba[3] = clgame.ds.triColor[3] * brightness; pglColor4ubv( rgba ); #ifdef __vita__ if( !tri_mode ) return; *(tri_colorp++) = rgba[0] / 255.f; *(tri_colorp++) = rgba[1] / 255.f; *(tri_colorp++) = rgba[2] / 255.f; *(tri_colorp++) = rgba[3] / 255.f; #endif } /* ============= TriCullFace ============= */ void GAME_EXPORT TriCullFace( TRICULLSTYLE mode ) { switch( mode ) { case TRI_FRONT: clgame.ds.cullMode = GL_FRONT; break; default: clgame.ds.cullMode = GL_NONE; break; } GL_Cull( clgame.ds.cullMode ); } /* ============= TriSpriteTexture bind current texture ============= */ int GAME_EXPORT TriSpriteTexture( model_t *pSpriteModel, int frame ) { int gl_texturenum; msprite_t *psprite; if(( gl_texturenum = R_GetSpriteTexture( pSpriteModel, frame )) == 0 ) return 0; if( gl_texturenum <= 0 || gl_texturenum > MAX_TEXTURES ) { MsgDev( D_ERROR, "TriSpriteTexture: bad index %i\n", gl_texturenum ); gl_texturenum = tr.defaultTexture; } psprite = pSpriteModel->cache.data; if( psprite->texFormat == SPR_ALPHTEST ) { pglEnable( GL_ALPHA_TEST ); pglAlphaFunc( GL_GREATER, 0.0f ); } GL_Bind( XASH_TEXTURE0, gl_texturenum ); return 1; } /* ============= TriWorldToScreen convert world coordinates (x,y,z) into screen (x, y) ============= */ int TriWorldToScreen( float *world, float *screen ) { int retval; retval = R_WorldToScreen( world, screen ); screen[0] = 0.5f * screen[0] * (float)cl.refdef.viewport[2]; screen[1] = -0.5f * screen[1] * (float)cl.refdef.viewport[3]; screen[0] += 0.5f * (float)cl.refdef.viewport[2]; screen[1] += 0.5f * (float)cl.refdef.viewport[3]; return retval; } /* ============= TriFog enables global fog on the level ============= */ void GAME_EXPORT TriFog( float flFogColor[3], float flStart, float flEnd, int bOn ) { if( RI.fogEnabled ) return; RI.fogCustom = true; #ifdef __vita__ return; // FIXME: add fog later #endif if( !bOn ) { pglDisable( GL_FOG ); RI.fogCustom = false; return; } // copy fog params RI.fogColor[0] = flFogColor[0] / 255.0f; RI.fogColor[1] = flFogColor[1] / 255.0f; RI.fogColor[2] = flFogColor[2] / 255.0f; RI.fogColor[3] = 1.0f; RI.fogStart = flStart; RI.fogDensity = 0.0f; RI.fogEnd = flEnd; if( VectorIsNull( RI.fogColor )) { pglDisable( GL_FOG ); return; } pglEnable( GL_FOG ); pglFogi( GL_FOG_MODE, GL_LINEAR ); pglFogf( GL_FOG_START, RI.fogStart ); pglFogf( GL_FOG_END, RI.fogEnd ); pglFogfv( GL_FOG_COLOR, RI.fogColor ); pglHint( GL_FOG_HINT, GL_NICEST ); } /* ============= TriGetMatrix very strange export ============= */ void GAME_EXPORT TriGetMatrix( const int pname, float *matrix ) { pglGetFloatv( pname, matrix ); } /* ============= TriBoxInPVS check box in pvs (absmin, absmax) ============= */ int GAME_EXPORT TriBoxInPVS( float *mins, float *maxs ) { return Mod_BoxVisible( mins, maxs, Mod_GetCurrentVis( )); } /* ============= TriLightAtPoint NOTE: dlights are ignored ============= */ void GAME_EXPORT TriLightAtPoint( float *pos, float *value ) { color24 ambient; if( !pos || !value ) return; R_LightForPoint( pos, &ambient, false, false, 0.0f ); value[0] = (float)ambient.r * 255.0f; value[1] = (float)ambient.g * 255.0f; value[2] = (float)ambient.b * 255.0f; } /* ============= TriColor4fRendermode Heavy legacy of Quake... ============= */ void GAME_EXPORT TriColor4fRendermode( float r, float g, float b, float a, int rendermode ) { #ifdef __vita__ if( rendermode == kRenderTransAlpha ) { *(tri_colorp++) = r; *(tri_colorp++) = g; *(tri_colorp++) = b; *(tri_colorp++) = a; } else { *(tri_colorp++) = r*a; *(tri_colorp++) = g*a; *(tri_colorp++) = b*a; *(tri_colorp++) = 1.f; } if( tri_mode ) return; #endif if( rendermode == kRenderTransAlpha ) pglColor4f( r, g, b, a ); else pglColor4f( r * a, g * a, b * a, 1.0f ); } /* ============= TriForParams ============= */ void GAME_EXPORT TriFogParams( float flDensity, int iFogSkybox ) { RI.fogDensity = flDensity; RI.fogCustom = iFogSkybox; } /* ================= DemoApi implementation ================= */ /* ================= Demo_IsRecording ================= */ static int GAME_EXPORT Demo_IsRecording( void ) { return cls.demorecording; } /* ================= Demo_IsPlayingback ================= */ static int GAME_EXPORT Demo_IsPlayingback( void ) { return cls.demoplayback; } /* ================= Demo_IsTimeDemo ================= */ static int GAME_EXPORT Demo_IsTimeDemo( void ) { return cls.timedemo; } /* ================= Demo_WriteBuffer ================= */ static void GAME_EXPORT Demo_WriteBuffer( int size, byte *buffer ) { CL_WriteDemoUserMessage( buffer, size ); } /* ================= NetworkApi implementation ================= */ /* ================= NetAPI_InitNetworking ================= */ void GAME_EXPORT NetAPI_InitNetworking( void ) { NET_Config( true ); // allow remote } /* ================= NetAPI_InitNetworking ================= */ void GAME_EXPORT NetAPI_Status( net_status_t *status ) { ASSERT( status != NULL ); status->connected = NET_IsLocalAddress( cls.netchan.remote_address ) ? false : true; status->connection_time = host.realtime - cls.netchan.connect_time; status->remote_address = cls.netchan.remote_address; status->packet_loss = cls.packet_loss / 100; // percent status->latency = cl.frame.latency; status->local_address = net_local; status->rate = cls.netchan.rate; } /* ================= NetAPI_SendRequest ================= */ void GAME_EXPORT NetAPI_SendRequest( int context, int request, int flags, double timeout, netadr_t *remote_address, net_api_response_func_t response ) { net_request_t *nr = NULL; string req; int i; if( !response ) { MsgDev( D_ERROR, "Net_SendRequest: no callbcak specified for request with context %i!\n", context ); return; } // find a free request for( i = 0; i < MAX_REQUESTS; i++ ) { nr = &clgame.net_requests[i]; if( !nr->pfnFunc || nr->timeout < host.realtime ) break; } if( i == MAX_REQUESTS ) { double max_timeout = 0; // no free requests? use older for( i = 0, nr = NULL; i < MAX_REQUESTS; i++ ) { if(( host.realtime - clgame.net_requests[i].timesend ) > max_timeout ) { max_timeout = host.realtime - clgame.net_requests[i].timesend; nr = &clgame.net_requests[i]; } } } ASSERT( nr != NULL ); // clear slot Q_memset( nr, 0, sizeof( *nr )); // create a new request nr->timesend = host.realtime; nr->timeout = nr->timesend + timeout; nr->pfnFunc = response; nr->resp.context = context; nr->resp.type = request; nr->resp.remote_address = *remote_address; nr->flags = flags; if( request == NETAPI_REQUEST_SERVERLIST ) { // UNDONE: build request for master-server } else { // send request over the net Q_snprintf( req, sizeof( req ), "netinfo %i %i %i", PROTOCOL_VERSION, context, request ); Netchan_OutOfBandPrint( NS_CLIENT, nr->resp.remote_address, req ); } } /* ================= NetAPI_CancelRequest ================= */ void GAME_EXPORT NetAPI_CancelRequest( int context ) { int i; // find a specified request for( i = 0; i < MAX_REQUESTS; i++ ) { if( clgame.net_requests[i].resp.context == context ) { MsgDev( D_NOTE, "Request with context %i cancelled\n", context ); Q_memset( &clgame.net_requests[i], 0, sizeof( net_request_t )); break; } } } /* ================= NetAPI_CancelAllRequests ================= */ void GAME_EXPORT NetAPI_CancelAllRequests( void ) { Q_memset( clgame.net_requests, 0, sizeof( clgame.net_requests )); } /* ================= NetAPI_AdrToString ================= */ char *GAME_EXPORT NetAPI_AdrToString( netadr_t *a ) { return NET_AdrToString( *a ); } /* ================= NetAPI_CompareAdr ================= */ int GAME_EXPORT NetAPI_CompareAdr( netadr_t *a, netadr_t *b ) { return NET_CompareAdr( *a, *b ); } /* ================= NetAPI_StringToAdr ================= */ int GAME_EXPORT NetAPI_StringToAdr( char *s, netadr_t *a ) { return NET_StringToAdr( s, a ); } /* ================= NetAPI_ValueForKey ================= */ const char *GAME_EXPORT NetAPI_ValueForKey( const char *s, const char *key ) { return Info_ValueForKey( s, key ); } /* ================= NetAPI_RemoveKey ================= */ void GAME_EXPORT NetAPI_RemoveKey( char *s, const char *key ) { Info_RemoveKey( s, key ); } /* ================= NetAPI_SetValueForKey ================= */ void GAME_EXPORT NetAPI_SetValueForKey( char *s, const char *key, const char *value, int maxsize ) { if( key[0] == '*' ) return; Info_SetValueForStarKey( s, key, value, maxsize ); } void GAME_EXPORT VGui_ViewportPaintBackground( int extents[4] ) { // stub } #ifndef XASH_VGUI void *VGui_GetPanel() { // stub return NULL; } #endif /* ================= IVoiceTweak implementation ================= */ /* ================= Voice_StartVoiceTweakMode ================= */ int GAME_EXPORT Voice_StartVoiceTweakMode( void ) { // TODO: implement return 0; } /* ================= Voice_EndVoiceTweakMode ================= */ void GAME_EXPORT Voice_EndVoiceTweakMode( void ) { // TODO: implement } /* ================= Voice_SetControlFloat ================= */ void GAME_EXPORT Voice_SetControlFloat( VoiceTweakControl iControl, float value ) { // TODO: implement } /* ================= Voice_GetControlFloat ================= */ float GAME_EXPORT Voice_GetControlFloat( VoiceTweakControl iControl ) { // TODO: implement return 1.0f; } /* ================= Voice_GetSpeakingVolume ================= */ int GAME_EXPORT Voice_GetSpeakingVolume( void ) { // TODO: implement return 255; } // shared between client and server triangleapi_t gTriApi = { TRI_API_VERSION, TriRenderMode, TriBegin, TriEnd, TriColor4f, TriColor4ub, TriTexCoord2f, (void*)TriVertex3fv, TriVertex3f, TriBrightness, TriCullFace, TriSpriteTexture, (void*)R_WorldToScreen, // NOTE: XPROJECT, YPROJECT should be done in client.dll TriFog, (void*)R_ScreenToWorld, TriGetMatrix, TriBoxInPVS, TriLightAtPoint, TriColor4fRendermode, TriFogParams, }; static efx_api_t gEfxApi = { CL_AllocParticle, (void*)CL_BlobExplosion, (void*)CL_Blood, (void*)CL_BloodSprite, (void*)CL_BloodStream, (void*)CL_BreakModel, (void*)CL_Bubbles, (void*)CL_BubbleTrail, (void*)CL_BulletImpactParticles, CL_EntityParticles, CL_Explosion, CL_FizzEffect, CL_FireField, (void*)CL_FlickerParticles, (void*)CL_FunnelSprite, (void*)CL_Implosion, (void*)CL_Large_Funnel, (void*)CL_LavaSplash, (void*)CL_MultiGunshot, (void*)CL_MuzzleFlash, (void*)CL_ParticleBox, (void*)CL_ParticleBurst, (void*)CL_ParticleExplosion, (void*)CL_ParticleExplosion2, (void*)CL_ParticleLine, CL_PlayerSprites, (void*)CL_Projectile, (void*)CL_RicochetSound, (void*)CL_RicochetSprite, (void*)CL_RocketFlare, CL_RocketTrail, (void*)CL_RunParticleEffect, (void*)CL_ShowLine, (void*)CL_SparkEffect, (void*)CL_SparkShower, (void*)CL_SparkStreaks, (void*)CL_Spray, CL_Sprite_Explode, CL_Sprite_Smoke, (void*)CL_Sprite_Spray, (void*)CL_Sprite_Trail, CL_Sprite_WallPuff, (void*)CL_StreakSplash, (void*)CL_TracerEffect, CL_UserTracerParticle, CL_TracerParticles, (void*)CL_TeleportSplash, (void*)CL_TempSphereModel, (void*)CL_TempModel, (void*)CL_DefaultSprite, (void*)CL_TempSprite, CL_DecalIndex, (void*)CL_DecalIndexFromName, CL_DecalShoot, CL_AttachTentToPlayer, CL_KillAttachedTents, (void*)CL_BeamCirclePoints, (void*)CL_BeamEntPoint, CL_BeamEnts, CL_BeamFollow, CL_BeamKill, (void*)CL_BeamLightning, (void*)CL_BeamPoints, (void*)CL_BeamRing, CL_AllocDlight, CL_AllocElight, (void*)CL_TempEntAlloc, (void*)CL_TempEntAllocNoModel, (void*)CL_TempEntAllocHigh, (void*)CL_TempEntAllocCustom, CL_GetPackedColor, CL_LookupColor, CL_DecalRemoveAll, CL_FireCustomDecal, }; static event_api_t gEventApi = { EVENT_API_VERSION, pfnPlaySound, S_StopSound, CL_FindModelIndex, pfnIsLocal, pfnLocalPlayerDucking, pfnLocalPlayerViewheight, pfnLocalPlayerBounds, pfnIndexFromTrace, pfnGetPhysent, CL_SetUpPlayerPrediction, CL_PushPMStates, CL_PopPMStates, CL_SetSolidPlayers, CL_SetTraceHull, CL_PlayerTrace, CL_WeaponAnim, pfnPrecacheEvent, CL_PlaybackEvent, pfnTraceTexture, pfnStopAllSounds, pfnKillEvents, CL_EventIndex, CL_IndexEvent, CL_PlayerTraceExt, CL_SoundFromIndex, pfnTraceSurface, }; static demo_api_t gDemoApi = { Demo_IsRecording, Demo_IsPlayingback, Demo_IsTimeDemo, Demo_WriteBuffer, }; static net_api_t gNetApi = { NetAPI_InitNetworking, NetAPI_Status, NetAPI_SendRequest, NetAPI_CancelRequest, NetAPI_CancelAllRequests, NetAPI_AdrToString, NetAPI_CompareAdr, NetAPI_StringToAdr, NetAPI_ValueForKey, NetAPI_RemoveKey, NetAPI_SetValueForKey, }; static IVoiceTweak gVoiceApi = { Voice_StartVoiceTweakMode, Voice_EndVoiceTweakMode, Voice_SetControlFloat, Voice_GetControlFloat, Voice_GetSpeakingVolume, }; // engine callbacks static cl_enginefunc_t gEngfuncs = { pfnSPR_Load, pfnSPR_Frames, pfnSPR_Height, pfnSPR_Width, pfnSPR_Set, pfnSPR_Draw, pfnSPR_DrawHoles, pfnSPR_DrawAdditive, SPR_EnableScissor, SPR_DisableScissor, pfnSPR_GetList, CL_FillRGBA, pfnGetScreenInfo, pfnSetCrosshair, (void*)pfnCvar_RegisterVariable, (void*)Cvar_VariableValue, (void*)Cvar_VariableString, (void*)pfnAddClientCommand, (void*)pfnHookUserMsg, (void*)pfnServerCmd, (void*)pfnClientCmd, pfnGetPlayerInfo, (void*)pfnPlaySoundByName, pfnPlaySoundByIndex, AngleVectors, CL_TextMessageGet, pfnDrawCharacter, pfnDrawConsoleString, pfnDrawSetTextColor, pfnDrawConsoleStringLen, pfnConsolePrint, pfnCenterPrint, pfnGetWindowCenterX, pfnGetWindowCenterY, pfnGetViewAngles, pfnSetViewAngles, CL_GetMaxClients, (void*)Cvar_SetFloat, Cmd_Argc, Cmd_Argv, Con_Printf, Con_DPrintf, Con_NPrintf, Con_NXPrintf, pfnPhysInfo_ValueForKey, pfnServerInfo_ValueForKey, pfnGetClientMaxspeed, pfnCheckParm, (void*)Key_Event, CL_GetMousePosition, pfnIsNoClipping, CL_GetLocalPlayer, pfnGetViewModel, CL_GetEntityByIndex, pfnGetClientTime, pfnCalcShake, pfnApplyShake, (void*)pfnPointContents, (void*)CL_WaterEntity, pfnTraceLine, CL_LoadModel, CL_AddEntity, CL_GetSpritePointer, pfnPlaySoundByNameAtLocation, pfnPrecacheEvent, CL_PlaybackEvent, CL_WeaponAnim, Com_RandomFloat, Com_RandomLong, (void*)pfnHookEvent, (void*)Con_Visible, pfnGetGameDirectory, pfnCVarGetPointer, Key_LookupBinding, pfnGetLevelName, pfnGetScreenFade, pfnSetScreenFade, VGui_GetPanel, VGui_ViewportPaintBackground, (void*)COM_LoadFile, COM_ParseFile, COM_FreeFile, &gTriApi, &gEfxApi, &gEventApi, &gDemoApi, &gNetApi, &gVoiceApi, pfnIsSpectateOnly, pfnLoadMapSprite, COM_AddAppDirectoryToSearchPath, COM_ExpandFilename, PlayerInfo_ValueForKey, PlayerInfo_SetValueForKey, pfnGetPlayerUniqueID, pfnGetTrackerIDForPlayer, pfnGetPlayerForTrackerID, pfnServerCmdUnreliable, pfnGetMousePos, pfnSetMousePos, pfnSetMouseEnable, Cvar_GetList, (void*)Cmd_GetFirstFunctionHandle, (void*)Cmd_GetNextFunctionHandle, (void*)Cmd_GetName, pfnGetClientOldTime, pfnGetGravity, Mod_Handle, pfnEnableTexSort, pfnSetLightmapColor, pfnSetLightmapScale, pfnSequenceGet, pfnSPR_DrawGeneric, pfnSequencePickSentence, pfnDrawString, pfnDrawStringReverse, LocalPlayerInfo_ValueForKey, pfnVGUI2DrawCharacter, pfnVGUI2DrawCharacterAdditive, (void*)Sound_GetApproxWavePlayLen, GetCareerGameInterface, (void*)Cvar_Set, pfnIsCareerMatch, pfnPlaySoundVoiceByName, pfnMP3_InitStream, Sys_DoubleTime, pfnProcessTutorMessageDecayBuffer, pfnConstructTutorMessageDecayBuffer, pfnResetTutorMessageDecayData, pfnPlaySoundByNameAtPitch, CL_FillRGBABlend, pfnGetAppID, Cmd_AliasGetList, pfnVguiWrap2_GetMouseDelta, }; void CL_UnloadProgs( void ) { if( !clgame.hInstance ) return; CL_FreeEdicts(); CL_FreeTempEnts(); CL_FreeViewBeams(); CL_FreeParticles(); CL_ClearAllRemaps(); Mod_ClearUserData(); // NOTE: HLFX 0.5 has strange bug: hanging on exit if no map was loaded if( !( !Q_stricmp( GI->gamedir, "hlfx" ) && GI->version == 0.5f )) clgame.dllFuncs.pfnShutdown(); Cvar_FullSet( "cl_background", "0", CVAR_READ_ONLY ); Cvar_FullSet( "host_clientloaded", "0", CVAR_INIT ); Com_FreeLibrary( clgame.hInstance ); #ifdef XASH_VGUI VGui_Shutdown(); #endif Mem_FreePool( &cls.mempool ); Mem_FreePool( &clgame.mempool ); Q_memset( &clgame, 0, sizeof( clgame )); Cvar_Unlink(); Cmd_Unlink( CMD_CLIENTDLL ); } void Sequence_Init( void ); qboolean CL_LoadProgs( const char *name ) { static playermove_t gpMove; const dllfunc_t *func; CL_EXPORT_FUNCS F; // export 'F' qboolean critical_exports = true; if( clgame.hInstance ) CL_UnloadProgs(); // setup globals cl.refdef.movevars = &clgame.movevars; // initialize PlayerMove clgame.pmove = &gpMove; cls.mempool = Mem_AllocPool( "Client Static Pool" ); clgame.mempool = Mem_AllocPool( "Client Edicts Zone" ); clgame.entities = NULL; // NOTE: important stuff! // vgui must startup BEFORE loading client.dll to avoid get error ERROR_NOACESS // during LoadLibrary #ifdef XASH_VGUI VGui_Startup (menu.globals->scrWidth, menu.globals->scrHeight); #endif clgame.hInstance = Com_LoadLibrary( name, false ); if( !clgame.hInstance ) return false; // clear exports for( func = cdll_exports; func && func->name; func++ ) *func->func = NULL; // trying to get single export named 'F' if(( F = (void *)Com_GetProcAddress( clgame.hInstance, "F" )) != NULL ) { MsgDev( D_NOTE, "CL_LoadProgs: found single callback export\n" ); // trying to fill interface now F( &clgame.dllFuncs ); // check critical functions again for( func = cdll_exports; func && func->name; func++ ) { if( func->func == NULL ) break; // BAH critical function was missed } // because all the exports are loaded through function 'F" if( !func || !func->name ) critical_exports = false; } for( func = cdll_exports; func && func->name != NULL; func++ ) { if( *func->func != NULL ) continue; // already get through 'F' // functions are cleared before all the extensions are evaluated if(!( *func->func = (void *)Com_GetProcAddress( clgame.hInstance, func->name ))) { MsgDev( D_NOTE, "CL_LoadProgs: failed to get address of %s proc\n", func->name ); if( critical_exports ) { Com_FreeLibrary( clgame.hInstance ); clgame.hInstance = NULL; return false; } } } // it may be loaded through 'F' so we don't need to clear them if( critical_exports ) { // clear new exports for( func = cdll_new_exports; func && func->name; func++ ) *func->func = NULL; } for( func = cdll_new_exports; func && func->name != NULL; func++ ) { if( *func->func != NULL ) continue; // already get through 'F' // functions are cleared before all the extensions are evaluated // NOTE: new exports can be missed without stop the engine if(!( *func->func = (void *)Com_GetProcAddress( clgame.hInstance, func->name ))) MsgDev( D_NOTE, "CL_LoadProgs: failed to get address of %s proc\n", func->name ); } if( !clgame.dllFuncs.pfnInitialize( &gEngfuncs, CLDLL_INTERFACE_VERSION )) { Com_FreeLibrary( clgame.hInstance ); MsgDev( D_NOTE, "CL_LoadProgs: can't init client API\n" ); clgame.hInstance = NULL; return false; } Cvar_Get( "cl_nopred", "1", CVAR_ARCHIVE|CVAR_USERINFO, "disable client movement predicting" ); cl_lw = Cvar_Get( "cl_lw", "0", CVAR_ARCHIVE|CVAR_USERINFO, "enable client weapon predicting" ); Cvar_Get( "cl_lc", "0", CVAR_ARCHIVE|CVAR_USERINFO, "enable lag compensation" ); Cvar_FullSet( "host_clientloaded", "1", CVAR_INIT ); clgame.maxRemapInfos = 0; // will be alloc on first call CL_InitEdicts(); clgame.maxEntities = 2; // world + localclient (have valid entities not in game) CL_InitCDAudio( "media/cdaudio.txt" ); CL_InitTitles( "titles.txt" ); CL_InitParticles (); CL_InitViewBeams (); CL_InitTempEnts (); CL_InitEdicts (); // initailize local player and world CL_InitClientMove(); // initialize pm_shared if( !R_InitRenderAPI()) // Xash3D extension { MsgDev( D_WARN, "CL_LoadProgs: couldn't get render API\n" ); } Mobile_Init(); // Xash3D extension: mobile interface Sequence_Init(); // NOTE: some usermessages are handled into the engine pfnHookUserMsg( "ScreenFade", CL_ParseScreenFade ); pfnHookUserMsg( "ScreenShake", CL_ParseScreenShake ); // initialize game clgame.dllFuncs.pfnInit(); CL_InitStudioAPI( ); return true; } #endif // XASH_DEDICATED
411
0.813171
1
0.813171
game-dev
MEDIA
0.879062
game-dev
0.831767
1
0.831767
DenizenScript/Denizen
2,678
plugin/src/main/java/com/denizenscript/denizen/events/entity/EntityExplosionPrimesScriptEvent.java
package com.denizenscript.denizen.events.entity; import com.denizenscript.denizen.objects.EntityTag; import com.denizenscript.denizen.events.BukkitScriptEvent; import com.denizenscript.denizencore.objects.Argument; import com.denizenscript.denizencore.objects.core.ElementTag; import com.denizenscript.denizencore.objects.ArgumentHelper; import com.denizenscript.denizencore.objects.ObjectTag; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.entity.ExplosionPrimeEvent; public class EntityExplosionPrimesScriptEvent extends BukkitScriptEvent implements Listener { // <--[event] // @Events // <entity> explosion primes // // @Group Entity // // @Location true // // @Cancellable true // // @Triggers when an entity decides to explode. // // @Context // <context.entity> returns the EntityTag. // <context.radius> returns an ElementTag of the explosion's radius. // <context.fire> returns an ElementTag with a value of "true" if the explosion will create fire and "false" otherwise. // --> public EntityExplosionPrimesScriptEvent() { registerCouldMatcher("<entity> explosion primes"); } public EntityTag entity; public ExplosionPrimeEvent event; @Override public boolean matches(ScriptPath path) { if (!path.tryArgObject(0, entity)) { return false; } if (!runInCheck(path, entity.getLocation())) { return false; } return super.matches(path); } @Override public boolean applyDetermination(ScriptPath path, ObjectTag determinationObj) { String determination = determinationObj.toString(); if (ArgumentHelper.matchesDouble(determination)) { event.setRadius(Float.parseFloat(determination)); return true; } if (Argument.valueOf(determination).matchesBoolean()) { event.setFire(determination.equalsIgnoreCase("true")); return true; } return super.applyDetermination(path, determinationObj); } @Override public ObjectTag getContext(String name) { switch (name) { case "entity": return entity; case "radius": return new ElementTag(event.getRadius()); case "fire": return new ElementTag(event.getFire()); } return super.getContext(name); } @EventHandler public void onEntityExplosionPrimes(ExplosionPrimeEvent event) { entity = new EntityTag(event.getEntity()); this.event = event; fire(event); } }
411
0.905351
1
0.905351
game-dev
MEDIA
0.946294
game-dev
0.824851
1
0.824851
SwagSoftware/KisakCOD
11,749
src/script/scr_main.cpp
#include "scr_main.h" #include "scr_stringlist.h" #include <universal/assertive.h> #include <universal/q_shared.h> #include "scr_compiler.h" #include <win32/win_net_debug.h> #include "scr_vm.h" #include <universal/profile.h> #include "scr_evaluate.h" #include "scr_animtree.h" #include "scr_parsetree.h" #include "scr_yacc.h" #undef GetObject bool Scr_IsInOpcodeMemory(char const* pos) { iassert(scrVarPub.programBuffer); iassert(pos); return pos - scrVarPub.programBuffer < scrCompilePub.programLen; } bool Scr_IsIdentifier(char const* token) { while (*token) { if (!I_iscsym(*token)) return 0; ++token; } return 1; } unsigned int SL_TransferToCanonicalString(unsigned int stringValue) { iassert(stringValue); SL_TransferRefToUser(stringValue, 2u); if (scrCompilePub.canonicalStrings[stringValue]) return scrCompilePub.canonicalStrings[stringValue]; scrCompilePub.canonicalStrings[stringValue] = ++scrVarPub.canonicalStrCount; return scrVarPub.canonicalStrCount; } unsigned int __cdecl SL_GetCanonicalString(const char* str) { unsigned int v1; // eax unsigned int v3; // eax v1 = SL_FindString(str); if (scrCompilePub.canonicalStrings[v1]) return scrCompilePub.canonicalStrings[v1]; v3 = SL_GetString_(str, 0, 16); return SL_TransferToCanonicalString(v3); } void SL_BeginLoadScripts() { memset((unsigned __int8*)scrCompilePub.canonicalStrings, 0, sizeof(scrCompilePub.canonicalStrings)); scrVarPub.canonicalStrCount = 0; } int __cdecl Scr_ScanFile(unsigned char *buf, int max_size) { char c; // [esp+3h] [ebp-5h] int n; // [esp+4h] [ebp-4h] c = 42; for (n = 0; n < max_size; ++n) { c = *scrCompilePub.in_ptr++; if (!c || c == 10) break; buf[n] = c; } if (c == 10) { buf[n++] = c; } else if (!c) { if (scrCompilePub.parseBuf) { scrCompilePub.in_ptr = scrCompilePub.parseBuf; scrCompilePub.parseBuf = 0; } else { --scrCompilePub.in_ptr; } } return n; } void __cdecl Scr_SetLoadedImpureScript(bool loadedImpureScript) { g_loadedImpureScript = loadedImpureScript; } void __cdecl Scr_BeginLoadScripts() { scrVarPub.varUsagePos = "<script compile variable>"; if (scrCompilePub.script_loading) MyAssertHandler(".\\script\\scr_main.cpp", 156, 0, "%s", "!scrCompilePub.script_loading"); scrCompilePub.script_loading = 1; Scr_InitOpcodeLookup(); Scr_InitDebuggerMain(); if (scrCompilePub.loadedscripts) MyAssertHandler(".\\script\\scr_main.cpp", 164, 0, "%s", "!scrCompilePub.loadedscripts"); scrCompilePub.loadedscripts = Scr_AllocArray(); if (scrVarDebugPub) ++scrVarDebugPub->extRefCount[scrCompilePub.loadedscripts]; if (!Sys_IsRemoteDebugClient()) { memset(profileScript.profileScriptNames, 0, sizeof(profileScript.profileScriptNames)); scrVmPub.showError = scrVarPub.developer; if (scrCompilePub.scripts) MyAssertHandler(".\\script\\scr_main.cpp", 184, 0, "%s", "!scrCompilePub.scripts"); scrCompilePub.scripts = Scr_AllocArray(); if (scrVarDebugPub) ++scrVarDebugPub->extRefCount[scrCompilePub.scripts]; if (scrCompilePub.builtinFunc) MyAssertHandler(".\\script\\scr_main.cpp", 191, 0, "%s", "!scrCompilePub.builtinFunc"); scrCompilePub.builtinFunc = Scr_AllocArray(); if (scrVarDebugPub) ++scrVarDebugPub->extRefCount[scrCompilePub.builtinFunc]; if (scrCompilePub.builtinMeth) MyAssertHandler(".\\script\\scr_main.cpp", 198, 0, "%s", "!scrCompilePub.builtinMeth"); scrCompilePub.builtinMeth = Scr_AllocArray(); if (scrVarDebugPub) ++scrVarDebugPub->extRefCount[scrCompilePub.builtinMeth]; scrVarPub.programHunkUser = Hunk_UserCreate(0x100000, "Scr_BeginLoadScripts", 1, 0, 7); TempMemoryReset(scrVarPub.programHunkUser); scrVarPub.programBuffer = TempMalloc(0); if (((int)scrVarPub.programBuffer & 0x1F) != 0) MyAssertHandler( ".\\script\\scr_main.cpp", 209, 0, "%s\n\t((int)scrVarPub.programBuffer) = %i", "(!((int)scrVarPub.programBuffer & 31))", scrVarPub.programBuffer); scrCompilePub.programLen = 0; scrVarPub.endScriptBuffer = 0; SL_BeginLoadScripts(); Scr_InitEvaluate(); scrVarPub.fieldBuffer = 0; scrCompilePub.value_count = 0; Scr_ClearErrorMessage(); scrCompilePub.func_table_size = 0; scrAnimPub.animTreeNames = 0; Scr_SetLoadedImpureScript(0); Scr_BeginLoadAnimTrees(1); } } void __cdecl Scr_EndLoadScripts() { if (!Sys_IsRemoteDebugClient()) { Scr_EndLoadEvaluate(); KISAK_NULLSUB(); SL_ShutdownSystem(2); } Scr_InitDebugger(); scrCompilePub.script_loading = 0; if (!scrCompilePub.loadedscripts) MyAssertHandler(".\\script\\scr_main.cpp", 415, 0, "%s", "scrCompilePub.loadedscripts"); ClearObject(scrCompilePub.loadedscripts); if (scrVarDebugPub) --scrVarDebugPub->extRefCount[scrCompilePub.loadedscripts]; RemoveRefToObject(scrCompilePub.loadedscripts); scrCompilePub.loadedscripts = 0; if (!Sys_IsRemoteDebugClient()) { if (!scrCompilePub.scripts) MyAssertHandler(".\\script\\scr_main.cpp", 429, 0, "%s", "scrCompilePub.scripts"); ClearObject(scrCompilePub.scripts); if (scrVarDebugPub) --scrVarDebugPub->extRefCount[scrCompilePub.scripts]; RemoveRefToObject(scrCompilePub.scripts); scrCompilePub.scripts = 0; if (!scrCompilePub.builtinFunc) MyAssertHandler(".\\script\\scr_main.cpp", 438, 0, "%s", "scrCompilePub.builtinFunc"); ClearObject(scrCompilePub.builtinFunc); if (scrVarDebugPub) --scrVarDebugPub->extRefCount[scrCompilePub.builtinFunc]; RemoveRefToObject(scrCompilePub.builtinFunc); scrCompilePub.builtinFunc = 0; if (!scrCompilePub.builtinMeth) MyAssertHandler(".\\script\\scr_main.cpp", 447, 0, "%s", "scrCompilePub.builtinMeth"); ClearObject(scrCompilePub.builtinMeth); if (scrVarDebugPub) --scrVarDebugPub->extRefCount[scrCompilePub.builtinMeth]; RemoveRefToObject(scrCompilePub.builtinMeth); scrCompilePub.builtinMeth = 0; } } void __cdecl Scr_BeginLoadAnimTrees(int user) { scrVarPub.varUsagePos = "<script compile variable>"; iassert(!scrAnimPub.animtree_loading); scrAnimPub.animtree_loading = 1; scrAnimPub.xanim_num[user] = 0; scrAnimPub.xanim_lookup[user][0].anims = 0; iassert(!scrAnimPub.animtrees); scrAnimPub.animtrees = Scr_AllocArray(); if (scrVarDebugPub) ++scrVarDebugPub->extRefCount[scrAnimPub.animtrees]; scrAnimPub.animtree_node = 0; scrCompilePub.developer_statement = 0; } unsigned int __cdecl Scr_LoadScriptInternal(const char *filename, PrecacheEntry *entries, int entriesCount) { unsigned int Variable; // eax VariableValueInternal_u Object; // [esp+0h] [ebp-7Ch] char extFilename[64]; // [esp+14h] [ebp-68h] BYREF unsigned int filePtr; // [esp+58h] [ebp-24h] char *sourceBuffer; // [esp+5Ch] [ebp-20h] const char *oldFilename; // [esp+60h] [ebp-1Ch] unsigned int name; // [esp+64h] [ebp-18h] unsigned int oldAnimTreeNames; // [esp+68h] [ebp-14h] const char *oldSourceBuf; // [esp+6Ch] [ebp-10h] unsigned int scriptId; // [esp+70h] [ebp-Ch] sval_u parseData; // [esp+74h] [ebp-8h] BYREF unsigned int fileId; // [esp+78h] [ebp-4h] iassert(scrCompilePub.script_loading); iassert(strlen(filename) < MAX_QPATH); Hunk_CheckTempMemoryHighClear(); name = Scr_CreateCanonicalFilename(filename).prev; if (FindVariable(scrCompilePub.loadedscripts, name)) { SL_RemoveRefToString(name); filePtr = FindVariable(scrCompilePub.scripts, name); if (!filePtr) return 0; Object = FindObject(filePtr); return Object.u.intValue; } else { scriptId = GetNewVariable(scrCompilePub.loadedscripts, name); SL_RemoveRefToString(name); Com_sprintf(extFilename, 64, "%s.gsc", SL_ConvertToString(name)); oldSourceBuf = scrParserPub.sourceBuf; ProfLoad_Begin("Scr_AddSourceBuffer"); sourceBuffer = Scr_AddSourceBuffer(SL_ConvertToString(name), extFilename, TempMalloc(0), 1); ProfLoad_End(); if (sourceBuffer) { oldAnimTreeNames = scrAnimPub.animTreeNames; scrAnimPub.animTreeNames = 0; scrCompilePub.far_function_count = 0; Scr_InitAllocNode(); oldFilename = scrParserPub.scriptfilename; scrParserPub.scriptfilename = extFilename; scrCompilePub.in_ptr = "+"; scrCompilePub.parseBuf = sourceBuffer; ScriptParse(&parseData, 0); Variable = GetVariable(scrCompilePub.scripts, name); fileId = GetObject(Variable); ProfLoad_Begin("ScriptCompile"); ScriptCompile(parseData, fileId, scriptId, entries, entriesCount); ProfLoad_End(); scrParserPub.scriptfilename = oldFilename; scrParserPub.sourceBuf = oldSourceBuf; scrAnimPub.animTreeNames = oldAnimTreeNames; Hunk_CheckTempMemoryHighClear(); return fileId; } else { return 0; } } } unsigned int __cdecl Scr_LoadScript(const char *filename) { PrecacheEntry entries[1024]; // [esp+0h] [ebp-2000h] BYREF return Scr_LoadScriptInternal(filename, &entries[0], 0); } void __cdecl Scr_PostCompileScripts() { iassert(scrCompilePub.programLen == static_cast<uint>(TempMalloc(0) - scrVarPub.programBuffer)); iassert(!scrAnimPub.animTreeNames); } void __cdecl Scr_PrecacheAnimTrees(void *(__cdecl *Alloc)(int), int user) { unsigned int i; // [esp+0h] [ebp-4h] for (i = 1; i <= scrAnimPub.xanim_num[user]; ++i) Scr_LoadAnimTreeAtIndex(i, Alloc, user); } void __cdecl Scr_EndLoadAnimTrees() { iassert(scrAnimPub.animtrees); ClearObject(scrAnimPub.animtrees); if (scrVarDebugPub) --scrVarDebugPub->extRefCount[scrAnimPub.animtrees]; RemoveRefToObject(scrAnimPub.animtrees); scrAnimPub.animtrees = 0; if (scrAnimPub.animtree_node) RemoveRefToObject(scrAnimPub.animtree_node); SL_ShutdownSystem(2); if (scrVarPub.programBuffer && !scrVarPub.endScriptBuffer) scrVarPub.endScriptBuffer = TempMalloc(0); scrAnimPub.animtree_loading = 0; scrVarPub.varUsagePos = 0; } void __cdecl Scr_FreeScripts(unsigned __int8 sys) { if (sys != 1) MyAssertHandler(".\\script\\scr_main.cpp", 498, 0, "%s", "sys == SCR_SYS_GAME"); Hunk_CheckTempMemoryClear(); if (scrCompilePub.script_loading) { scrCompilePub.script_loading = 0; Scr_EndLoadScripts(); } if (scrAnimPub.animtree_loading) { scrAnimPub.animtree_loading = 0; Scr_EndLoadAnimTrees(); } Scr_ShutdownDebugger(); Scr_ShutdownDebuggerMain(); Scr_ShutdownEvaluate(); SL_ShutdownSystem(1); Scr_ShutdownOpcodeLookup(); if (scrVarPub.programHunkUser) { Hunk_UserDestroy(scrVarPub.programHunkUser); scrVarPub.programHunkUser = 0; } scrVarPub.programBuffer = 0; scrCompilePub.programLen = 0; scrVarPub.endScriptBuffer = 0; scrVarPub.checksum = 0; }
411
0.857823
1
0.857823
game-dev
MEDIA
0.268333
game-dev
0.793113
1
0.793113
google/flatbuffers
2,360
swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_10.swift
import FlatBuffers import Foundation func run() { // create a `FlatBufferBuilder`, which will be used to serialize objects let builder = FlatBufferBuilder(initialSize: 1024) let weapon1Name = builder.create(string: "Sword") let weapon2Name = builder.create(string: "Axe") // start creating the weapon by calling startWeapon let weapon1Start = Weapon.startWeapon(&builder) Weapon.add(name: weapon1Name, &builder) Weapon.add(damage: 3, &builder) // end the object by passing the start point for the weapon 1 let sword = Weapon.endWeapon(&builder, start: weapon1Start) let weapon2Start = Weapon.startWeapon(&builder) Weapon.add(name: weapon2Name, &builder) Weapon.add(damage: 5, &builder) let axe = Weapon.endWeapon(&builder, start: weapon2Start) // Create a FlatBuffer `vector` that contains offsets to the sword and axe // we created above. let weaponsOffset = builder.createVector(ofOffsets: [sword, axe]) // Name of the Monster. let name = builder.create(string: "Orc") let pathOffset = fbb.createVector(ofStructs: [ Vec3(x: 0, y: 0), Vec3(x: 5, y: 5), ]) // startVector(len, elementSize: MemoryLayout<Offset>.size) // for o in offsets.reversed() { // push(element: o) // } // endVector(len: len) let orc = Monster.createMonster( &builder, pos: Vec3(x: 1, y: 2), hp: 300, nameOffset: name, color: .red, weaponsVectorOffset: weaponsOffset, equippedType: .weapon, equippedOffset: axe, pathOffset: pathOffset) // let start = Monster.startMonster(&builder) // Monster.add(pos: Vec3(x: 1, y: 2), &builder) // Monster.add(hp: 300, &builder) // Monster.add(name: name, &builder) // Monster.add(color: .red, &builder) // Monster.addVectorOf(weapons: weaponsOffset, &builder) // Monster.add(equippedType: .weapon, &builder) // Monster.addVectorOf(paths: weaponsOffset, &builder) // Monster.add(equipped: axe, &builder) // var orc = Monster.endMonster(&builder, start: start) // Call `finish(offset:)` to instruct the builder that this monster is complete. builder.finish(offset: orc) // This must be called after `finish()`. // `sizedByteArray` returns the finished buf of type [UInt8]. let buf = builder.sizedByteArray // or you can use to get an object of type Data let bufData = ByteBuffer(data: builder.sizedBuffer) }
411
0.591426
1
0.591426
game-dev
MEDIA
0.975464
game-dev
0.789979
1
0.789979
RedPandaProjects/STALKERonUE
34,749
gamedata_cs/configs/misc/outfit.ltx
;#include "outfit_upgrades\outfit_delayed_action_fuse.ltx" ;#include "outfit_upgrades\outfit_upgrades_properties.ltx" ;#include "outfit_upgrades\outfit_upgrades.ltx" #include "outfit_upgrades\o_novice_outfit_up.ltx" #include "outfit_upgrades\o_bandit_outfit_up.ltx" #include "outfit_upgrades\o_stalker_outfit_up.ltx" #include "outfit_upgrades\o_cs_light_outfit_up.ltx" #include "outfit_upgrades\o_svoboda_light_outfit_up.ltx" #include "outfit_upgrades\o_scientific_outfit_up.ltx" #include "outfit_upgrades\o_cs_heavy_outfit_up.ltx" #include "outfit_upgrades\o_dolg_outfit_up.ltx" #include "outfit_upgrades\o_svoboda_heavy_outfit_up.ltx" #include "outfit_upgrades\o_specops_outfit_up.ltx" #include "outfit_upgrades\o_exo_outfit_up.ltx" #include "outfit_upgrades\o_dolg_heavy_outfit_up.ltx" #include "outfit_upgrades\o_svoboda_exo_outfit_up.ltx" #include "outfit_upgrades\o_military_outfit_up.ltx" [outfit_base] ; delete full_scale_icon next update- obsolete, use full_icon_name instead !!! additional_inventory_weight = 0 ; +max_walk_weight additional_inventory_weight2 = 0 ; +40 kg full_icon_name = npc_icon_without_outfit nightvision_sect = default_to_ruck = false sprint_allowed = true control_inertion_factor = 1 player_hud_section = actor_hud_01 [without_outfit]:outfit_base ; - . - + full_scale_icon = 6,6 ;--------------------------------------------------------------------------------------------- ; ;--------------------------------------------------------------------------------------------- [novice_outfit]:outfit_base GroupControlSection = spawn_group discovery_dependency = $spawn = "outfit\novice_outfit" ;$prefetch = 32 class = E_STLK cform = skeleton visual = dynamics\outfit\novice_outfit actor_visual = actors\stalker_hero\stalker_hero_1.ogf player_hud_section = actor_hud_01 ef_equipment_type = 3 inv_name = novice_outfit_name inv_name_short = novice_outfit_name description = novice_outfit_description inv_weight = 3.0 ;inv_grid_width = 2 ;inv_grid_height = 2 ;inv_grid_x = 12 ;inv_grid_y = 0 inv_grid_width = 2 inv_grid_height = 2 inv_grid_x = 0 inv_grid_y = 18 full_icon_name = npc_icon_novice_outfit cost = 500 slot = 6 full_scale_icon = 0,11 ; immunities_sect = sect_novice_outfit_immunities ; NO RESISTANCE burn_protection = 0.005 shock_protection = 0.005 radiation_protection = 0.005 chemical_burn_protection = 0.005 telepatic_protection = 0.0 strike_protection = 0.15 explosion_protection = 0.15 wound_protection = 0.15 fire_wound_protection = 0.1 physic_strike_wound_immunity = 0.1 bones_koeff_protection = actor_armor_suit hit_fraction_actor = 0.5 artefact_count = 0 upgrades = up_gr_ab_novice_outfit, up_gr_cd_novice_outfit, up_gr_ef_novice_outfit, up_gr_g_novice_outfit installed_upgrades = upgrade_scheme = upgrade_scheme_u8a [sect_novice_outfit_immunities] burn_immunity = 0.05 ; strike_immunity = 0.0 shock_immunity = 0.0 wound_immunity = 0.05 radiation_immunity = 0.0 telepatic_immunity = 0.0 chemical_burn_immunity = 0.05 explosion_immunity = 0.05 fire_wound_immunity = 0.02 ;--------------------------------------------------------------------------------------------- ; ;--------------------------------------------------------------------------------------------- [bandit_outfit]:outfit_base GroupControlSection = spawn_group discovery_dependency = $spawn = "outfit\bandit_outfit" ;$prefetch = 32 class = E_STLK cform = skeleton visual = dynamics\outfit\bandit_outfit actor_visual = actors\stalker_bandit\stalker_bandit_1.ogf player_hud_section = actor_hud_05 ef_equipment_type = 3 inv_name = bandit_outfit_name inv_name_short = bandit_outfit_name description = bandit_outfit_description inv_weight = 3.0 inv_grid_width = 2 inv_grid_height = 2 inv_grid_x = 12 inv_grid_y = 0 full_icon_name = npc_icon_bandit_outfit cost = 500 slot = 6 full_scale_icon = 0,6 ; immunities_sect = sect_bandit_outfit_immunities ; NO RESISTANCE burn_protection = 0.005 shock_protection = 0.005 radiation_protection = 0.005 chemical_burn_protection = 0.005 telepatic_protection = 0.0 strike_protection = 0.15 explosion_protection = 0.15 wound_protection = 0.15 fire_wound_protection = 0.1 physic_strike_wound_immunity = 0.1 bones_koeff_protection = actor_armor_suit hit_fraction_actor = 0.3 artefact_count = 0 upgrades = up_gr_ab_bandit_outfit, up_gr_cd_bandit_outfit, up_gr_ef_bandit_outfit, up_gr_g_bandit_outfit installed_upgrades = upgrade_scheme = upgrade_scheme_u7 [sect_bandit_outfit_immunities] burn_immunity = 0.05 ; strike_immunity = 0.0 shock_immunity = 0.0 wound_immunity = 0.05 radiation_immunity = 0.0 telepatic_immunity = 0.0 chemical_burn_immunity = 0.05 explosion_immunity = 0.05 fire_wound_immunity = 0.02 ;--------------------------------------------------------------------------------------------- ; ;--------------------------------------------------------------------------------------------- [cs_light_outfit]:outfit_base GroupControlSection = spawn_group discovery_dependency = $spawn = "outfit\cs_light_outfit" ;$prefetch = 32 class = E_STLK cform = skeleton visual = dynamics\outfit\cs_light_outfit actor_visual = actors\stalker_nebo\stalker_nebo_1 player_hud_section = actor_hud_04 ef_equipment_type = 3 inv_name = csky_light_outfit_name inv_name_short = csky_light_outfit_name description = csky_light_outfit_description inv_weight = 4.0 inv_grid_width = 2 inv_grid_height = 3 inv_grid_x = 9 inv_grid_y = 27 full_icon_name = npc_icon_svoboda_light_outfit cost = 5000 slot = 6 full_scale_icon = 10,11 ; immunities_sect = sect_cs_light_outfit_immunities ; LOW RESISTANCE burn_protection = 0.013 shock_protection = 0.013 radiation_protection = 0.013 chemical_burn_protection = 0.013 telepatic_protection = 0.0 strike_protection = 0.25 explosion_protection = 0.25 wound_protection = 0.25 fire_wound_protection = 0.0 physic_strike_wound_immunity = 0.15 bones_koeff_protection = actor_light_armor hit_fraction_actor = 0.3 artefact_count = 1 control_inertion_factor = 1.2 upgrades = up_gr_ab_cs_light_outfit, up_gr_cd_cs_light_outfit, up_gr_ef_cs_light_outfit, up_gr_gh_cs_light_outfit, up_gr_i_cs_light_outfit installed_upgrades = upgrade_scheme = upgrade_scheme_u14b [sect_cs_light_outfit_immunities] burn_immunity = 0.04 ; strike_immunity = 0.0 shock_immunity = 0.0 wound_immunity = 0.04 radiation_immunity = 0.0 telepatic_immunity = 0.0 chemical_burn_immunity = 0.04 explosion_immunity = 0.04 fire_wound_immunity = 0.02 [sect_cs_light_outfit_immunities_1] burn_immunity = 0.02 ; strike_immunity = 0.0 shock_immunity = 0.0 wound_immunity = 0.02 radiation_immunity = 0.0 telepatic_immunity = 0.0 chemical_burn_immunity = 0.02 explosion_immunity = 0.02 fire_wound_immunity = 0.015 ;--------------------------------------------------------------------------------------------- ; ;--------------------------------------------------------------------------------------------- [stalker_outfit]:outfit_base GroupControlSection = spawn_group discovery_dependency = $spawn = "outfit\stalker_outfit" ;$prefetch = 32 class = E_STLK cform = skeleton visual = dynamics\outfit\stalker_outfit actor_visual = actors\stalker_neutral\stalker_neutral_2.ogf player_hud_section = actor_hud_01 ef_equipment_type = 3 inv_name = stalker_outfit_name inv_name_short = stalker_outfit_name description = stalker_outfit_description inv_weight = 5.0 inv_grid_width = 2 inv_grid_height = 3 inv_grid_x = 6 inv_grid_y = 15 full_icon_name = npc_icon_stalker_outfit cost = 6250 slot = 6 full_scale_icon = 14,11 ; nightvision_sect = ;effector_nightvision_bad additional_inventory_weight = 0 ; +max_walk_weight additional_inventory_weight2 = 0 ; +40 kg artefact_count = 2 default_to_ruck = false immunities_sect = sect_stalker_outfit_immunities ; LOW RESISTANCE burn_protection = 0.015 shock_protection = 0.015 radiation_protection = 0.015 chemical_burn_protection = 0.015 telepatic_protection = 0.0 strike_protection = 0.25 explosion_protection = 0.25 wound_protection = 0.25 fire_wound_protection = 0.0 physic_strike_wound_immunity = 0.15 power_loss = 1.0 bones_koeff_protection = actor_light_armor hit_fraction_actor = 0.3 control_inertion_factor = 1.2 upgrades = up_gr_ab_stalker_outfit, up_gr_cd_stalker_outfit, up_gr_ef_stalker_outfit, up_gr_gh_stalker_outfit, up_gr_i_stalker_outfit installed_upgrades = upgrade_scheme = upgrade_scheme_u15a [sect_stalker_outfit_immunities] burn_immunity = 0.03 ; strike_immunity = 0.0 shock_immunity = 0.0 wound_immunity = 0.03 radiation_immunity = 0.0 telepatic_immunity = 0.0 chemical_burn_immunity = 0.03 explosion_immunity = 0.03 fire_wound_immunity = 0.015 [sect_stalker_outfit_immunities_1] burn_immunity = 0.015 ; strike_immunity = 0.0 shock_immunity = 0.0 wound_immunity = 0.015 radiation_immunity = 0.0 telepatic_immunity = 0.0 chemical_burn_immunity = 0.015 explosion_immunity = 0.015 fire_wound_immunity = 0.010 ;--------------------------------------------------------------------------------------------- ; ;--------------------------------------------------------------------------------------------- [svoboda_light_outfit]:outfit_base GroupControlSection = spawn_group discovery_dependency = $spawn = "outfit\svoboda_light_outfit" ;$prefetch = 32 class = E_STLK cform = skeleton visual = dynamics\outfit\svoboda_light_outfit actor_visual = actors\stalker_freedom\stalker_freedom_1.ogf player_hud_section = actor_hud_03 ef_equipment_type = 3 inv_name = svoboda_light_outfit_name inv_name_short = svoboda_light_outfit_name description = svoboda_light_outfit_description inv_weight = 3.0 inv_grid_width = 2 inv_grid_height = 3 inv_grid_x = 12 inv_grid_y = 13 full_icon_name = npc_icon_svoboda_light_outfit cost = 7500 slot = 6 full_scale_icon = 10,11 ; immunities_sect = sect_svoboda_light_outfit_immunities ; LOW RESISTANCE radiation_protection = 0.011 chemical_burn_protection = 0.011 burn_protection = 0.011 shock_protection = 0.011 telepatic_protection = 0.0 strike_protection = 0.25 explosion_protection = 0.25 wound_protection = 0.25 fire_wound_protection = 0.2 physic_strike_wound_immunity = 0.2 bones_koeff_protection = actor_light_armor hit_fraction_actor = 0.3 artefact_count = 2 control_inertion_factor = 1.2 upgrades = up_gr_ab_svoboda_light_outfit, up_gr_cd_svoboda_light_outfit, up_gr_ef_svoboda_light_outfit, up_gr_gh_svoboda_light_outfit, up_gr_i_svoboda_light_outfit installed_upgrades = upgrade_scheme = upgrade_scheme_u13a [sect_svoboda_light_outfit_immunities] burn_immunity = 0.05 ; strike_immunity = 0.0 shock_immunity = 0.0 wound_immunity = 0.05 radiation_immunity = 0.0 telepatic_immunity = 0.0 chemical_burn_immunity = 0.05 explosion_immunity = 0.05 fire_wound_immunity = 0.015 [sect_svoboda_light_outfit_immunities_1] burn_immunity = 0.03 ; strike_immunity = 0.0 shock_immunity = 0.0 wound_immunity = 0.03 radiation_immunity = 0.0 telepatic_immunity = 0.0 chemical_burn_immunity = 0.03 explosion_immunity = 0.03 fire_wound_immunity = 0.01 ;--------------------------------------------------------------------------------------------- ; ;--------------------------------------------------------------------------------------------- [dolg_outfit]:outfit_base GroupControlSection = spawn_group discovery_dependency = $spawn = "outfit\dolg_outfit" ;$prefetch = 32 class = E_STLK cform = skeleton visual = dynamics\outfit\dolg_outfit actor_visual = actors\stalker_dolg\stalker_dolg_2.ogf player_hud_section = actor_hud_02 ef_equipment_type = 3 inv_name = dolg_outfit_name inv_name_short = dolg_outfit_name description = dolg_outfit_description inv_weight = 7.0 inv_grid_width = 2 inv_grid_height = 3 inv_grid_x = 12 inv_grid_y = 16 full_icon_name = npc_icon_dolg_outfit cost = 8125 slot = 6 full_scale_icon = 8,11 ; ;nightvision_sect = effector_nightvision_bad immunities_sect = sect_dolg_outfit_immunities ; LOW RESISTANCE burn_protection = 0.009 shock_protection = 0.009 radiation_protection = 0.009 chemical_burn_protection = 0.009 telepatic_protection = 0.0 strike_protection = 0.3 explosion_protection = 0.3 wound_protection = 0.3 fire_wound_protection = 0.25 physic_strike_wound_immunity = 0.25 bones_koeff_protection = actor_light_armor hit_fraction_actor = 0.3 artefact_count = 0 control_inertion_factor = 1.2 upgrades = up_gr_ab_dolg_outfit, up_gr_cd_dolg_outfit, up_gr_ef_dolg_outfit, up_gr_gh_dolg_outfit, up_gr_i_dolg_outfit installed_upgrades = upgrade_scheme = upgrade_scheme_u14b [sect_dolg_outfit_immunities] burn_immunity = 0.04 ; strike_immunity = 0.04 shock_immunity = 0.0 wound_immunity = 0.04 radiation_immunity = 0.0 telepatic_immunity = 0.0 chemical_burn_immunity = 0.04 explosion_immunity = 0.04 fire_wound_immunity = 0.01 [sect_dolg_outfit_immunities_1] burn_immunity = 0.03 ; strike_immunity = 0.03 shock_immunity = 0.0 wound_immunity = 0.03 radiation_immunity = 0.0 telepatic_immunity = 0.0 chemical_burn_immunity = 0.03 explosion_immunity = 0.03 fire_wound_immunity = 0.008 [sect_dolg_outfit_immunities_2] burn_immunity = 0.02 ; strike_immunity = 0.02 shock_immunity = 0.0 wound_immunity = 0.02 radiation_immunity = 0.0 telepatic_immunity = 0.0 chemical_burn_immunity = 0.02 explosion_immunity = 0.02 fire_wound_immunity = 0.005 ;--------------------------------------------------------------------------------------------- ; ;--------------------------------------------------------------------------------------------- [scientific_outfit]:outfit_base GroupControlSection = spawn_group discovery_dependency = $spawn = "outfit\scientific_outfit" $prefetch = 32 class = E_STLK cform = skeleton visual = dynamics\outfit\scientific_outfit actor_visual = actors\stalker_mp\mp_team_blue_armor_sci.ogf ;hero\stalker_scien.ogf player_hud_section = actor_hud_06 ef_equipment_type = 2 inv_name = scientific_outfit_name inv_name_short = scientific_outfit_name description = scientific_outfit_description inv_weight = 9 slot = 6 inv_grid_width = 2 inv_grid_height = 3 inv_grid_x = 16 inv_grid_y = 13 full_icon_name = npc_icon_scientific_outfit nightvision_sect = effector_nightvision_bad cost = 18750 full_scale_icon = 12,11 ; immunities_sect = sect_scientific_outfit_immunities bones_koeff_protection = actor_light_armor_1 hit_fraction_actor = 0.25 artefact_count = 2 control_inertion_factor = 1.5 ; MEDIUM RESISTANCE burn_protection = 0.061 shock_protection = 0.061 radiation_protection = 0.061 chemical_burn_protection = 0.061 telepatic_protection = 0.061 strike_protection = 0.3 explosion_protection = 0.3 wound_protection = 0.3 fire_wound_protection = 0.0 physic_strike_wound_immunity = 0.25 upgrades = up_gr_ab_scientific_outfit, up_gr_cd_scientific_outfit, up_gr_ef_scientific_outfit, up_gr_gh_scientific_outfit, up_gr_i_scientific_outfit installed_upgrades = upgrade_scheme = upgrade_scheme_u17a [sect_scientific_outfit_immunities] burn_immunity = 0.03 ; strike_immunity = 0.03 shock_immunity = 0.03 wound_immunity = 0.03 radiation_immunity = 0.0 telepatic_immunity = 0.0 chemical_burn_immunity = 0.03 explosion_immunity = 0.03 fire_wound_immunity = 0.01 [sect_scientific_outfit_immunities_1] burn_immunity = 0.02 ; strike_immunity = 0.02 shock_immunity = 0.02 wound_immunity = 0.02 radiation_immunity = 0.0 telepatic_immunity = 0.0 chemical_burn_immunity = 0.02 explosion_immunity = 0.02 fire_wound_immunity = 0.008 [sect_scientific_outfit_immunities_2] burn_immunity = 0.01 ; strike_immunity = 0.01 shock_immunity = 0.01 wound_immunity = 0.01 radiation_immunity = 0.0 telepatic_immunity = 0.0 chemical_burn_immunity = 0.01 explosion_immunity = 0.01 fire_wound_immunity = 0.005 ;--------------------------------------------------------------------------------------------- ; ;--------------------------------------------------------------------------------------------- [cs_heavy_outfit]:outfit_base GroupControlSection = spawn_group discovery_dependency = $spawn = "outfit\cs_heavy_outfit" ;$prefetch = 32 class = E_STLK cform = skeleton visual = dynamics\outfit\cs_heavy_outfit actor_visual = actors\stalker_nebo\stalker_nebo_2.ogf player_hud_section = actor_hud_04 ef_equipment_type = 3 inv_name = csky_heavy_outfit_name inv_name_short = csky_heavy_outfit_name description = csky_heavy_outfit_description inv_weight = 7.0 inv_grid_width = 2 inv_grid_height = 3 inv_grid_x = 11 inv_grid_y = 27 full_icon_name = npc_icon_svoboda_heavy_outfit ;nightvision_sect = effector_nightvision_bad cost = 15000 slot = 6 full_scale_icon = 2,6 ; immunities_sect = sect_cs_heavy_outfit_immunities ; MEDIUM RESISTANCE burn_protection = 0.030 shock_protection = 0.030 radiation_protection = 0.030 chemical_burn_protection = 0.030 telepatic_protection = 0.030 strike_protection = 0.35 explosion_protection = 0.35 wound_protection = 0.35 fire_wound_protection = 0.3 physic_strike_wound_immunity = 0.3 bones_koeff_protection = actor_medium_armor hit_fraction_actor = 0.2 artefact_count = 1 control_inertion_factor = 1.5 upgrades = up_gr_ab_cs_heavy_outfit, up_gr_cd_cs_heavy_outfit, up_gr_ef_cs_heavy_outfit, up_gr_gh_cs_heavy_outfit, up_gr_i_cs_heavy_outfit installed_upgrades = upgrade_scheme = upgrade_scheme_u16a [sect_cs_heavy_outfit_immunities] burn_immunity = 0.04 ; strike_immunity = 0.04 shock_immunity = 0.0 wound_immunity = 0.04 radiation_immunity = 0.0 telepatic_immunity = 0.0 chemical_burn_immunity = 0.04 explosion_immunity = 0.04 fire_wound_immunity = 0.01 [sect_cs_heavy_outfit_immunities_1] burn_immunity = 0.03 ; strike_immunity = 0.03 shock_immunity = 0.0 wound_immunity = 0.03 radiation_immunity = 0.0 telepatic_immunity = 0.0 chemical_burn_immunity = 0.03 explosion_immunity = 0.03 fire_wound_immunity = 0.008 [sect_cs_heavy_outfit_immunities_2] burn_immunity = 0.02 ; strike_immunity = 0.02 shock_immunity = 0.0 wound_immunity = 0.02 radiation_immunity = 0.0 telepatic_immunity = 0.0 chemical_burn_immunity = 0.02 explosion_immunity = 0.02 fire_wound_immunity = 0.005 ;--------------------------------------------------------------------------------------------- ; ;--------------------------------------------------------------------------------------------- [svoboda_heavy_outfit]:outfit_base GroupControlSection = spawn_group discovery_dependency = $spawn = "outfit\svoboda_heavy_outfit" ;$prefetch = 32 class = E_STLK cform = skeleton visual = dynamics\outfit\svoboda_heavy_outfit actor_visual = actors\stalker_freedom\stalker_freedom_3.ogf player_hud_section = actor_hud_03 ef_equipment_type = 3 inv_name = svoboda_heavy_outfit_name inv_name_short = svoboda_heavy_outfit_name description = svoboda_heavy_outfit_description inv_weight = 7.0 inv_grid_width = 2 inv_grid_height = 3 inv_grid_x = 8 inv_grid_y = 15 full_icon_name = npc_icon_svoboda_heavy_outfit ;nightvision_sect = effector_nightvision_bad cost = 15000 slot = 6 full_scale_icon = 2,6 ; immunities_sect = sect_svoboda_heavy_outfit_immunities ; MEDIUM RESISTANCE burn_protection = 0.024 shock_protection = 0.024 chemical_burn_protection = 0.024 radiation_protection = 0.024 telepatic_protection = 0.024 strike_protection = 0.35 explosion_protection = 0.35 wound_protection = 0.35 fire_wound_protection = 0.35 physic_strike_wound_immunity = 0.35 bones_koeff_protection = actor_medium_armor hit_fraction_actor = 0.25 artefact_count = 2 control_inertion_factor = 1.5 upgrades = up_gr_ab_svoboda_heavy_outfit, up_gr_cd_svoboda_heavy_outfit, up_gr_ef_svoboda_heavy_outfit, up_gr_gh_svoboda_heavy_outfit, up_gr_i_svoboda_heavy_outfit installed_upgrades = upgrade_scheme = upgrade_scheme_u15 [sect_svoboda_heavy_outfit_immunities] burn_immunity = 0.05 ; strike_immunity = 0.05 shock_immunity = 0.0 wound_immunity = 0.05 radiation_immunity = 0.0 telepatic_immunity = 0.0 chemical_burn_immunity = 0.05 explosion_immunity = 0.05 fire_wound_immunity = 0.01 [sect_svoboda_heavy_outfit_immunities_1] burn_immunity = 0.04 ; strike_immunity = 0.0 shock_immunity = 0.04 wound_immunity = 0.04 radiation_immunity = 0.0 telepatic_immunity = 0.0 chemical_burn_immunity = 0.04 explosion_immunity = 0.04 fire_wound_immunity = 0.008 [sect_svoboda_heavy_outfit_immunities_2] burn_immunity = 0.03 ; strike_immunity = 0.03 shock_immunity = 0.0 wound_immunity = 0.03 radiation_immunity = 0.0 telepatic_immunity = 0.0 chemical_burn_immunity = 0.03 explosion_immunity = 0.03 fire_wound_immunity = 0.005 ;--------------------------------------------------------------------------------------------- ; ;--------------------------------------------------------------------------------------------- [specops_outfit]:outfit_base GroupControlSection = spawn_group discovery_dependency = $spawn = "outfit\specops_outfit" ;$prefetch = 32 class = E_STLK cform = skeleton visual = dynamics\outfit\specops_outfit actor_visual = actors\stalker_soldier\stalker_soldier_3.ogf player_hud_section = actor_hud_07 ef_equipment_type = 3 inv_name = specops_outfit_name inv_name_short = specops_outfit_name description = specops_outfit_description inv_weight = 7.0 inv_grid_width = 2 inv_grid_height = 3 inv_grid_x = 10 inv_grid_y = 13 full_icon_name = npc_icon_specops_outfit ;nightvision_sect = effector_nightvision_bad cost = 12500 slot = 6 full_scale_icon = 4,6 ; immunities_sect = sect_specops_outfit_immunities ; LOW RESISTANCE burn_protection = 0.020 shock_protection = 0.020 radiation_protection = 0.020 chemical_burn_protection = 0.020 telepatic_protection = 0.0 strike_protection = 0.3 explosion_protection = 0.3 wound_protection = 0.3 fire_wound_protection = 0.0 physic_strike_wound_immunity = 0.35 bones_koeff_protection = actor_medium_armor hit_fraction_actor = 0.2 artefact_count = 0 control_inertion_factor = 1.5 upgrades = up_gr_ab_specops_outfit, up_gr_cd_specops_outfit, up_gr_ef_specops_outfit, up_gr_gh_specops_outfit, up_gr_i_specops_outfit installed_upgrades = upgrade_scheme = upgrade_scheme_u16a [sect_specops_outfit_immunities] burn_immunity = 0.04 ; strike_immunity = 0.0 shock_immunity = 0.04 wound_immunity = 0.04 radiation_immunity = 0.0 telepatic_immunity = 0.0 chemical_burn_immunity = 0.04 explosion_immunity = 0.04 fire_wound_immunity = 0.01 [sect_specops_outfit_immunities_1] burn_immunity = 0.03 ; strike_immunity = 0.03 shock_immunity = 0.0 wound_immunity = 0.03 radiation_immunity = 0.0 telepatic_immunity = 0.0 chemical_burn_immunity = 0.03 explosion_immunity = 0.03 fire_wound_immunity = 0.008 [sect_specops_outfit_immunities_2] burn_immunity = 0.02 ; strike_immunity = 0.0 shock_immunity = 0.02 wound_immunity = 0.02 radiation_immunity = 0.0 telepatic_immunity = 0.0 chemical_burn_immunity = 0.02 explosion_immunity = 0.02 fire_wound_immunity = 0.005 ;--------------------------------------------------------------------------------------------- ; ;--------------------------------------------------------------------------------------------- [military_outfit]:outfit_base GroupControlSection = spawn_group discovery_dependency = $spawn = "outfit\military_outfit" ;$prefetch = 32 class = E_STLK cform = skeleton visual = dynamics\outfit\military_outfit actor_visual = actors\stalker_soldier\stalker_soldier_4.ogf player_hud_section = actor_hud_06 ef_equipment_type = 4 inv_name = military_outfit_name inv_name_short = military_outfit_name description = military_outfit_description inv_weight = 12.0 slot = 6 inv_grid_width = 2 inv_grid_height = 3 inv_grid_x = 18 inv_grid_y = 17 full_icon_name = npc_icon_military_outfit nightvision_sect = effector_nightvision_bad cost = 25000 full_scale_icon = 10,6 ; immunities_sect = sect_military_outfit_immunities ; MEDIUM RESISTANCE burn_protection = 0.047 shock_protection = 0.047 radiation_protection = 0.047 chemical_burn_protection = 0.047 telepatic_protection = 0.047 strike_protection = 0.35 explosion_protection = 0.35 wound_protection = 0.35 fire_wound_protection = 0.45 physic_strike_wound_immunity = 0.45 bones_koeff_protection = actor_heavy_armor hit_fraction_actor = 0.2 artefact_count = 0 control_inertion_factor = 1.8 upgrades = up_gr_ab_military_outfit, up_gr_cd_military_outfit, up_gr_ef_military_outfit, up_gr_gh_military_outfit, up_gr_i_military_outfit installed_upgrades = upgrade_scheme = upgrade_scheme_u16a [sect_military_outfit_immunities] burn_immunity = 0.04 ; strike_immunity = 0.04 shock_immunity = 0.04 wound_immunity = 0.04 radiation_immunity = 0.0 telepatic_immunity = 0.0 chemical_burn_immunity = 0.04 explosion_immunity = 0.03 fire_wound_immunity = 0.01 [sect_military_outfit_immunities_1] burn_immunity = 0.03 ; strike_immunity = 0.03 shock_immunity = 0.03 wound_immunity = 0.03 radiation_immunity = 0.0 telepatic_immunity = 0.0 chemical_burn_immunity = 0.03 explosion_immunity = 0.02 fire_wound_immunity = 0.008 [sect_military_outfit_immunities_2] burn_immunity = 0.02 ; strike_immunity = 0.02 shock_immunity = 0.02 wound_immunity = 0.02 radiation_immunity = 0.0 telepatic_immunity = 0.0 chemical_burn_immunity = 0.02 explosion_immunity = 0.01 fire_wound_immunity = 0.005 ;--------------------------------------------------------------------------------------------- ; ;--------------------------------------------------------------------------------------------- [dolg_heavy_outfit]:outfit_base GroupControlSection = spawn_group discovery_dependency = $spawn = "outfit\dolg_heavy_outfit" $prefetch = 32 class = E_STLK cform = skeleton visual = dynamics\outfit\dolg_heavy_outfit actor_visual = actors\stalker_dolg\stalker_dolg_3.ogf player_hud_section = actor_hud_02 ef_equipment_type = 4 inv_name = dolg_heavy_outfit_name inv_name_short = dolg_heavy_outfit_name description = dolg_heavy_outfit_description inv_weight = 12.0 slot = 6 inv_grid_width = 2 inv_grid_height = 3 inv_grid_x = 16 inv_grid_y = 16 full_icon_name = npc_icon_dolg_heavy_outfit nightvision_sect = effector_nightvision_bad cost = 20000 full_scale_icon = 8,6 ; immunities_sect = sect_dolg_heavy_outfit_immunities ; MEDIUM RESISTANCE burn_protection = 0.042 shock_protection = 0.042 radiation_protection = 0.042 chemical_burn_protection = 0.042 telepatic_protection = 0.042 strike_protection = 0.4 explosion_protection = 0.4 wound_protection = 0.4 fire_wound_protection = 0.5 physic_strike_wound_immunity = 0.5 bones_koeff_protection = actor_heavy_armor hit_fraction_actor = 0.2 artefact_count = 0 control_inertion_factor = 1.8 upgrades = up_gr_ab_dolg_heavy_outfit, up_gr_cd_dolg_heavy_outfit, up_gr_ef_dolg_heavy_outfit, up_gr_gh_dolg_heavy_outfit, up_gr_i_dolg_heavy_outfit installed_upgrades = upgrade_scheme = upgrade_scheme_u16a [sect_dolg_heavy_outfit_immunities] burn_immunity = 0.03 ; strike_immunity = 0.03 shock_immunity = 0.0 wound_immunity = 0.03 radiation_immunity = 0.0 telepatic_immunity = 0.0 chemical_burn_immunity = 0.03 explosion_immunity = 0.03 fire_wound_immunity = 0.01 [sect_dolg_heavy_outfit_immunities_1] burn_immunity = 0.03 ; strike_immunity = 0.0 shock_immunity = 0.03 wound_immunity = 0.03 radiation_immunity = 0.0 telepatic_immunity = 0.0 chemical_burn_immunity = 0.03 explosion_immunity = 0.03 fire_wound_immunity = 0.008 [sect_dolg_heavy_outfit_immunities_2] burn_immunity = 0.03 ; strike_immunity = 0.0 shock_immunity = 0.03 wound_immunity = 0.03 radiation_immunity = 0.0 telepatic_immunity = 0.0 chemical_burn_immunity = 0.03 explosion_immunity = 0.03 fire_wound_immunity = 0.005 ;--------------------------------------------------------------------------------------------- ; ;--------------------------------------------------------------------------------------------- [exo_outfit]:outfit_base GroupControlSection = spawn_group discovery_dependency = $spawn = "outfit\exo_outfit" $prefetch = 32 class = E_STLK cform = skeleton visual = dynamics\outfit\exo_outfit actor_visual = actors\stalker_neutral\stalker_neutral_4.ogf player_hud_section = actor_hud_exo ef_equipment_type = 5 inv_name = exo_outfit_name inv_name_short = exo_outfit_name description = exo_outfit_description inv_weight = 25.0 slot = 6 inv_grid_width = 2 inv_grid_height = 3 inv_grid_x = 14 inv_grid_y = 13 full_icon_name = npc_icon_exo_outfit ;nightvision_sect = effector_nightvision_bad cost = 55000 full_scale_icon = 2,11 ; immunities_sect = sect_exo_outfit_immunities ; MEDIUM RESISTANCE burn_protection = 0.039 shock_protection = 0.039 radiation_protection = 0.039 chemical_burn_protection = 0.039 telepatic_protection = 0.039 strike_protection = 0.4 explosion_protection = 0.4 wound_protection = 0.4 fire_wound_protection = 0.4 physic_strike_wound_immunity = 0.4 ; Sprint sprint_allowed = false bones_koeff_protection = actor_heavy_armor_1 hit_fraction_actor = 0.2 additional_inventory_weight = 40 additional_inventory_weight2 = 40 artefact_count = 1 control_inertion_factor = 2.5 upgrades = up_gr_ab_exo_outfit, up_gr_cd_exo_outfit, up_gr_ef_exo_outfit, up_gr_gh_exo_outfit, up_gr_k_exo_outfit installed_upgrades = upgrade_scheme = upgrade_scheme_u20a [sect_exo_outfit_immunities] burn_immunity = 0.01 ; strike_immunity = 0.01 shock_immunity = 0.01 wound_immunity = 0.01 radiation_immunity = 0.0 telepatic_immunity = 0.0 chemical_burn_immunity = 0.01 explosion_immunity = 0.01 fire_wound_immunity = 0.01 [sect_exo_outfit_immunities_1] burn_immunity = 0.005 ; strike_immunity = 0.005 shock_immunity = 0.005 wound_immunity = 0.005 radiation_immunity = 0.0 telepatic_immunity = 0.0 chemical_burn_immunity = 0.005 explosion_immunity = 0.005 fire_wound_immunity = 0.005 ;--------------------------------------------------------------------------------------------- ; ;--------------------------------------------------------------------------------------------- [svoboda_exo_outfit]:outfit_base GroupControlSection = spawn_group discovery_dependency = $spawn = "outfit\svoboda_exo_outfit" $prefetch = 32 class = E_STLK cform = skeleton visual = dynamics\outfit\svoboda_exo_outfit actor_visual = actors\stalker_freedom\stalker_freedom_4.ogf player_hud_section = actor_hud_exo ef_equipment_type = 5 inv_name = exo_freedom_outfit_name inv_name_short = exo_freedom_outfit_name description = exo_freedom_outfit_description inv_weight = 15.0 slot = 6 inv_grid_width = 2 inv_grid_height = 3 inv_grid_x = 13 inv_grid_y = 27 full_icon_name = npc_icon_exo_outfit ;nightvision_sect = effector_nightvision_bad cost = 60000 full_scale_icon = 2,11 ; immunities_sect = sect_svoboda_exo_outfit_immunities ; MEDIUM RESISTANCE burn_protection = 0.034 shock_protection = 0.034 radiation_protection = 0.034 chemical_burn_protection = 0.034 telepatic_protection = 0.034 strike_protection = 0.4 explosion_protection = 0.4 wound_protection = 0.4 fire_wound_protection = 0.4 physic_strike_wound_immunity = 0.4 ; Sprint sprint_allowed = false bones_koeff_protection = actor_heavy_armor_1 hit_fraction_actor = 0.2 artefact_count = 2 control_inertion_factor = 2.1 additional_inventory_weight = 20 additional_inventory_weight2 = 20 ; 40+ upgrades = up_gr_ab_svoboda_exo_outfit, up_gr_cd_svoboda_exo_outfit, up_gr_ef_svoboda_exo_outfit, up_gr_gh_svoboda_exo_outfit, up_gr_k_svoboda_exo_outfit installed_upgrades = upgrade_scheme = upgrade_scheme_u19a [sect_svoboda_exo_outfit_immunities] burn_immunity = 0.01 ; strike_immunity = 0.01 shock_immunity = 0.01 wound_immunity = 0.01 radiation_immunity = 0.0 telepatic_immunity = 0.0 chemical_burn_immunity = 0.01 explosion_immunity = 0.01 fire_wound_immunity = 0.01 [sect_svoboda_exo_outfit_immunities_1] burn_immunity = 0.005 ; strike_immunity = 0.005 shock_immunity = 0.005 wound_immunity = 0.005 radiation_immunity = 0.0 telepatic_immunity = 0.0 chemical_burn_immunity = 0.005 explosion_immunity = 0.005 fire_wound_immunity = 0.005 ;***************************************************************** ;***************************************************************** [stalker_outfit_up_stalk]:stalker_outfit GroupControlSection = spawn_group discovery_dependency = $spawn = "outfit\stalker_outfit_up_stalk" ;$prefetch = 32 class = E_STLK cform = skeleton upgrades = up_gr_ab_stalker_outfit, up_gr_cd_stalker_outfit, up_gr_ef_stalker_outfit, up_gr_gh_stalker_outfit, up_gr_i_stalker_outfit installed_upgrades = up_b_stalker_outfit, up_d_stalker_outfit, up_f_stalker_outfit, up_h_stalker_outfit, up_i_stalker_outfit, up_i2_stalker_outfit upgrade_scheme = upgrade_scheme_u15a
411
0.919723
1
0.919723
game-dev
MEDIA
0.973848
game-dev
0.677188
1
0.677188
3UR/Simpsons-Hit-Run
2,308
src/game/mission/objectives/talktoobjective.h
//============================================================================= // Copyright (C) 2002 Radical Entertainment Ltd. All rights reserved. // // File: talktoobjective.h // // Description: Blahblahblah // // History: 29/08/2002 + Created -- Cary Brisebois // //============================================================================= #ifndef TALKTOOBJECTIVE_H #define TALKTOOBJECTIVE_H //======================================== // Nested Includes //======================================== #include <mission/objectives/missionobjective.h> #include <render/enums/renderenums.h> #include <presentation/gui/utility/hudmap.h> #include <input/inputmanager.h> //======================================== // Forward References //======================================== class Character; class EventLocator; class AnimatedIcon; //============================================================================= // // Synopsis: Blahblahblah // //============================================================================= class TalkToObjective : public MissionObjective, public IHudMapIconLocator { public: enum { MAX_CHARACTER_NAME = 64 }; enum IconType { EXCLAMATION, GIFT, DOOR }; TalkToObjective(); virtual ~TalkToObjective(); virtual void HandleEvent( EventEnum id, void* pEventData ); void SetTalkToTarget( const char* name, IconType type, float yOffset, float rad ); //Interface for IHudMapIconLocator void GetPosition( rmt::Vector* currentLoc ); void GetHeading( rmt::Vector* heading ); protected: virtual void OnInitialize(); virtual void OnFinalize(); virtual void OnUpdate( unsigned int elapsedTime ); PathStruct mArrowPath; private: char mCharacterName[MAX_CHARACTER_NAME]; Character* mTalkToTarget; int mHudMapIconID; EventLocator* mEvtLoc; AnimatedIcon* mAnimatedIcon; IconType mIconType; float mYOffset; float mTriggerRadius; RenderEnums::LayerEnum mRenderLayer; bool mIsDisabled; int mActionID; //Prevent wasteful constructor creation. TalkToObjective( const TalkToObjective& talktoobjective ); TalkToObjective& operator=( const TalkToObjective& talktoobjective ); Input::ActiveState m_PrevActiveGameState; }; #endif //TALKTOOBJECTIVE_H
411
0.77711
1
0.77711
game-dev
MEDIA
0.90407
game-dev
0.70146
1
0.70146
DevExpress/AjaxControlToolkit
1,437
AjaxControlToolkit/ExtenderBase/ScriptComponentDescriptorWrapper.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web.UI; namespace AjaxControlToolkit { public class ScriptComponentDescriptorWrapper : IScriptComponentDescriptor { ScriptComponentDescriptor _descriptor; public ScriptComponentDescriptorWrapper(ScriptComponentDescriptor descriptor) { _descriptor = descriptor; } public string ClientID { get { return _descriptor.ClientID; } } public string ID { get { return _descriptor.ID; } set { _descriptor.ID = value; } } public string Type { get { return _descriptor.Type; } set { _descriptor.Type = value; } } public void AddComponentProperty(string name, string componentID) { _descriptor.AddComponentProperty(name, componentID); } public void AddElementProperty(string name, string elementID) { _descriptor.AddElementProperty(name, elementID); } public void AddEvent(string name, string handler) { _descriptor.AddEvent(name, handler); } public void AddProperty(string name, object value) { _descriptor.AddProperty(name, value); } public void AddScriptProperty(string name, string script) { _descriptor.AddScriptProperty(name, script); } } }
411
0.782647
1
0.782647
game-dev
MEDIA
0.625577
game-dev
0.71892
1
0.71892
JiuTian-VL/Optimus-3
4,959
MineStudio/minestudio/simulator/minerl/Malmo/Minecraft/src/main/java/com/microsoft/Malmo/MissionHandlers/ObservationFromRecentCommandsImplementation.java
// -------------------------------------------------------------------------------------------------- // Copyright (c) 2016 Microsoft Corporation // // 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. // -------------------------------------------------------------------------------------------------- package com.microsoft.Malmo.MissionHandlers; import java.util.ArrayList; import java.util.List; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; import com.microsoft.Malmo.MissionHandlerInterfaces.ICommandHandler; import com.microsoft.Malmo.MissionHandlerInterfaces.IObservationProducer; import com.microsoft.Malmo.Schemas.MissionInit; /** ObservationProducer that returns a JSON array of all the commands acted on since the last observation message.<br> * Note that the commands returned might not yet have taken effect, depending on the command and the way in which Minecraft responds to it - * but they will have been processed by the command handling chain. */ public class ObservationFromRecentCommandsImplementation extends HandlerBase implements IObservationProducer { private boolean hookedIntoCommandChain = false; private List<String> recentCommandList = new ArrayList<String>(); @Override public void prepare(MissionInit missionInit) {} @Override public void cleanup() {} @Override public void writeObservationsToJSON(JsonObject json, MissionInit missionInit) { if (!hookedIntoCommandChain) { // We need to see the commands as they come in, so we can determine which ones to echo back in the observation message. // To do this we create our own command handler and insert it at the root of the command chain. // It's slightly dirty behaviour, but it saves // a) adding special code into ProjectMalmo.java just to allow for this ObservationProducer to work, and // b) requiring the user to add a special command handler themselves at the right point in the XML. MissionBehaviour mb = parentBehaviour(); ICommandHandler oldch = mb.commandHandler; CommandGroup newch = new CommandGroup() { protected boolean onExecute(String verb, String parameter, MissionInit missionInit) { // See if this command gets handled by the legitimate handlers: boolean handled = super.onExecute(verb, parameter, missionInit); if (handled) // Yes, so record it: ObservationFromRecentCommandsImplementation.this.addHandledCommand(verb, parameter); return handled; } }; newch.setOverriding((oldch != null) ? oldch.isOverriding() : true); if (oldch != null) newch.addCommandHandler(oldch); mb.commandHandler = newch; this.hookedIntoCommandChain = true; } synchronized(this.recentCommandList) { // Have any commands been processed since we last sent a burst of observations? if (this.recentCommandList.size() != 0) { // Yes, so build up a JSON array: JsonArray commands = new JsonArray(); for (String s : this.recentCommandList) { commands.add(new JsonPrimitive(s)); } json.add("CommandsSinceLastObservation", commands); } this.recentCommandList.clear(); } } protected void addHandledCommand(String verb, String parameter) { // Must synchronise because command handling might happen on a different thread to observation sending. synchronized(this.recentCommandList) { this.recentCommandList.add(verb + " " + parameter); } } }
411
0.939188
1
0.939188
game-dev
MEDIA
0.396356
game-dev
0.960502
1
0.960502
hengband/hengband
2,792
src/mutation/mutation-techniques.cpp
/*! * @brief 突然変異でのみ得ることができる特殊能力処理 * @date 2020/07/04 * @author Hourier */ #include "mutation/mutation-techniques.h" #include "cmd-action/cmd-attack.h" #include "floor/geometry.h" #include "grid/grid.h" #include "monster/monster-info.h" #include "player/digestion-processor.h" #include "player/player-move.h" #include "player/player-status.h" #include "system/floor/floor-info.h" #include "system/grid-type-definition.h" #include "system/monster-entity.h" #include "system/player-type-definition.h" #include "system/terrain/terrain-definition.h" #include "target/target-getter.h" #include "util/bit-flags-calculator.h" #include "view/display-messages.h" /*! * 岩石食い * @param player_ptr プレイヤーへの参照ポインタ * @return コマンドの入力方向に地形があればTRUE */ bool eat_rock(PlayerType *player_ptr) { const auto dir = get_direction(player_ptr); if (!dir) { return false; } const auto pos = player_ptr->get_neighbor(dir); const auto &grid = player_ptr->current_floor_ptr->get_grid(pos); const auto &terrain = grid.get_terrain(); const auto &terrain_mimic = grid.get_terrain(TerrainKind::MIMIC); stop_mouth(player_ptr); if (terrain_mimic.flags.has_not(TerrainCharacteristics::HURT_ROCK)) { msg_print(_("この地形は食べられない。", "You cannot eat this feature.")); } else if (terrain.flags.has(TerrainCharacteristics::PERMANENT)) { msg_format(_("いてっ!この%sはあなたの歯より硬い!", "Ouch! This %s is harder than your teeth!"), terrain_mimic.name.data()); } else if (grid.has_monster()) { const auto &monster = player_ptr->current_floor_ptr->m_list[grid.m_idx]; msg_print(_("何かが邪魔しています!", "There's something in the way!")); if (!monster.ml || !monster.is_pet()) { do_cmd_attack(player_ptr, pos.y, pos.x, HISSATSU_NONE); } } else if (terrain.flags.has(TerrainCharacteristics::TREE)) { msg_print(_("木の味は好きじゃない!", "You don't like the woody taste!")); } else if (terrain.flags.has(TerrainCharacteristics::GLASS)) { msg_print(_("ガラスの味は好きじゃない!", "You don't like the glassy taste!")); } else if (terrain.flags.has(TerrainCharacteristics::DOOR) || terrain.flags.has(TerrainCharacteristics::CAN_DIG)) { (void)set_food(player_ptr, player_ptr->food + 3000); } else if (terrain.flags.has(TerrainCharacteristics::MAY_HAVE_GOLD) || terrain.flags.has(TerrainCharacteristics::HAS_GOLD)) { (void)set_food(player_ptr, player_ptr->food + 5000); } else { msg_format(_("この%sはとてもおいしい!", "This %s is very filling!"), terrain_mimic.name.data()); (void)set_food(player_ptr, player_ptr->food + 10000); } cave_alter_feat(player_ptr, pos.y, pos.x, TerrainCharacteristics::HURT_ROCK); (void)move_player_effect(player_ptr, pos.y, pos.x, MPE_DONT_PICKUP); return true; }
411
0.920288
1
0.920288
game-dev
MEDIA
0.985889
game-dev
0.934204
1
0.934204
rashiph/DecompliedDotNetLibraries
2,488
System.Web/System/Web/Compilation/ApplicationBuildProvider.cs
namespace System.Web.Compilation { using System; using System.CodeDom.Compiler; using System.Web; using System.Web.UI; using System.Web.Util; internal class ApplicationBuildProvider : BaseTemplateBuildProvider { internal override BuildResultCompiledType CreateBuildResult(Type t) { BuildResultCompiledGlobalAsaxType type = new BuildResultCompiledGlobalAsaxType(t); if ((base.Parser.ApplicationObjects != null) || (base.Parser.SessionObjects != null)) { type.HasAppOrSessionObjects = true; } return type; } internal override BaseCodeDomTreeGenerator CreateCodeDomTreeGenerator(TemplateParser parser) { return new ApplicationFileCodeDomTreeGenerator((ApplicationFileParser) parser); } protected override TemplateParser CreateParser() { return new ApplicationFileParser(); } internal static BuildResultCompiledGlobalAsaxType GetGlobalAsaxBuildResult(bool isPrecompiledApp) { string cacheKey = "App_global.asax"; BuildResultCompiledGlobalAsaxType buildResultFromCache = BuildManager.GetBuildResultFromCache(cacheKey) as BuildResultCompiledGlobalAsaxType; if (buildResultFromCache == null) { if (isPrecompiledApp) { return null; } VirtualPath globalAsaxVirtualPath = BuildManager.GlobalAsaxVirtualPath; if (!globalAsaxVirtualPath.FileExists()) { return null; } ApplicationBuildProvider o = new ApplicationBuildProvider(); o.SetVirtualPath(globalAsaxVirtualPath); DateTime utcNow = DateTime.UtcNow; BuildProvidersCompiler compiler = new BuildProvidersCompiler(globalAsaxVirtualPath, BuildManager.GenerateRandomAssemblyName("App_global.asax")); compiler.SetBuildProviders(new SingleObjectCollection(o)); CompilerResults results = compiler.PerformBuild(); buildResultFromCache = (BuildResultCompiledGlobalAsaxType) o.GetBuildResult(results); buildResultFromCache.CacheToMemory = false; BuildManager.CacheBuildResult(cacheKey, buildResultFromCache, utcNow); } return buildResultFromCache; } } }
411
0.752175
1
0.752175
game-dev
MEDIA
0.33602
game-dev
0.713748
1
0.713748
stefanvranjes/Vigilante2Unity
1,344
Assets/Scripts/Empty.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Empty : VigObject { protected override void Start() { base.Start(); } protected override void Update() { base.Update(); } //FUN_49880 public override uint UpdateW(int arg1, int arg2) { uint uVar2; switch (arg1) { case 0: FUN_42330(arg2); uVar2 = 0; break; default: uVar2 = 0; break; } return uVar2; } public override uint UpdateW(int arg1, VigObject arg2) { short sVar1; uint uVar2; switch (arg1) { case 0: FUN_42330(arg2); uVar2 = 0; break; case 1: maxHalfHealth = 6; goto default; default: uVar2 = 0; break; case 12: sVar1 = (short)(maxHalfHealth - 1); maxHalfHealth = (ushort)sVar1; uVar2 = 60; if (sVar1 == 0) { FUN_3A368(); uVar2 = 60; } break; } return uVar2; } }
411
0.835383
1
0.835383
game-dev
MEDIA
0.660126
game-dev
0.91949
1
0.91949
coinbump/PhaseJumpPro
1,306
PhaseJumpUnity/Assets/phasejumppro/Animation/Animator.cs
using System; using UnityEngine; using System.Collections.Generic; /* RATING: 5 stars Has unit tests CODE REVIEW: 2/18/23 PORTED TO: C++ */ namespace PJ { /// <summary> /// Animates a value from start to end once once /// </summary> public class Animator<T> : SomeTimed { /// <summary> /// Time value of animator /// </summary> protected float time; /// <summary> /// Interpolates from start to end /// </summary> public Interpolator<T> interpolator; /// <summary> /// Value binding to modify value /// </summary> public SetBinding<T> binding; public Animator(Interpolator<T> interpolator, float duration, SetBinding<T> binding) : base(duration, SomeRunner.RunType.RunOnce) { this.interpolator = interpolator; this.binding = binding; } public override float Progress => Mathf.Max(0, Mathf.Min(1.0f, time / duration)); public override void OnUpdate(TimeSlice time) { if (IsFinished) { return; } this.time += time.delta; IsFinished = this.time >= duration; var curveValue = interpolator.ValueAt(Progress); binding.Value = curveValue; } } }
411
0.754604
1
0.754604
game-dev
MEDIA
0.883203
game-dev
0.895191
1
0.895191
goblinhack/zorbash
5,342
src/wid_quit.cpp
// // Copyright goblinhack@gmail.com // #include "my_game.hpp" #include "my_sdl_proto.hpp" #include "my_thing.hpp" #include "my_ui.hpp" #include "my_wid_actionbar.hpp" #include "my_wid_asciimap.hpp" #include "my_wid_botcon.hpp" #include "my_wid_popup.hpp" #include "my_wid_topcon.hpp" WidPopup *wid_quit_window; void wid_quit_destroy(void) { TRACE_NO_INDENT(); if (wid_quit_window) { delete wid_quit_window; wid_quit_window = nullptr; game->change_state(Game::STATE_NORMAL, "quit close"); } } static uint8_t wid_quit_yes(Widp w, int x, int y, uint32_t button) { TRACE_NO_INDENT(); if (game->started) { LOG("INF: Restart game"); auto level = game->get_current_level(); if (level) { auto player = level->player; if (player) { // // Poor player // if (! player->score()) { player->score_incr(1); } // // Don't add to the hi-score table in test mode // if (! g_opt_test_dungeon) { // // New hi-score? // if (game->config.hiscores.is_new_hiscore(player)) { if (game->robot_mode) { TOPCON("%%fg=red$RIP: Robot went back to the metal shop%%fg=reset$"); TOPCON("%%fg=gold$New robo high score, %s place!%%fg=reset$", game->config.hiscores.place_str(player)); } else { TOPCON("%%fg=red$RIP: Player quit the game.%%fg=reset$"); TOPCON("%%fg=gold$New high score, %s place!%%fg=reset$", game->config.hiscores.place_str(player)); } // // Add to the hi-scores // game->config.hiscores.add_new_hiscore(player, player->title(), "went home early"); CON("INF: Player quit the game; new hiscore"); } else { CON("INF: Player quit the game; no hiscore change"); } } } } wid_quit_destroy(); wid_topcon_fini(); wid_topcon_init(); wid_actionbar_fini(); wid_botcon_fini(); wid_botcon_init(); wid_asciimap_fini(); game->fini(); game->wid_main_menu_select(); } else { wid_quit_destroy(); DIE_CLEAN("INF: Quit"); } return true; } static uint8_t wid_quit_no(Widp w, int x, int y, uint32_t button) { TRACE_NO_INDENT(); wid_quit_destroy(); if (! game->level) { game->wid_main_menu_select(); } else { wid_actionbar_init(); } return true; } static uint8_t wid_quit_key_up(Widp w, const struct SDL_Keysym *key) { TRACE_NO_INDENT(); if (sdlk_eq(*key, game->config.key_console)) { return false; } switch (key->mod) { case KMOD_LCTRL : case KMOD_RCTRL : default : switch (key->sym) { default : { TRACE_NO_INDENT(); auto c = wid_event_to_char(key); switch (c) { case 'y' : wid_quit_yes(nullptr, 0, 0, 0); return true; case 'n' : wid_quit_no(nullptr, 0, 0, 0); return true; case 'b' : case SDLK_ESCAPE : wid_quit_no(nullptr, 0, 0, 0); return true; } } } } return false; } static uint8_t wid_quit_key_down(Widp w, const struct SDL_Keysym *key) { TRACE_NO_INDENT(); if (sdlk_eq(*key, game->config.key_console)) { return false; } return true; } void Game::quit_select(void) { TRACE_NO_INDENT(); LOG("Quit select"); if (level && level->player) { wid_actionbar_robot_mode_off(); } if (wid_quit_window) { wid_quit_destroy(); } auto m = TERM_WIDTH / 2; auto n = TERM_HEIGHT / 2; if (game->started) { n = TERM_HEIGHT / 3; } point tl = make_point(m - UI_WID_POPUP_WIDTH_NORMAL / 2, n - 3); point br = make_point(m + UI_WID_POPUP_WIDTH_NORMAL / 2, n + 3); auto width = br.x - tl.x; wid_quit_window = new WidPopup("Game quit", tl, br, nullptr, "", false, false); { TRACE_NO_INDENT(); Widp w = wid_quit_window->wid_popup_container; wid_set_on_key_up(w, wid_quit_key_up); wid_set_on_key_down(w, wid_quit_key_down); } int y_at = 0; { TRACE_NO_INDENT(); auto p = wid_quit_window->wid_text_area->wid_text_area; auto w = wid_new_square_button(p, "Quit"); point tl = make_point(0, y_at); point br = make_point(width, y_at); wid_set_shape_none(w); wid_set_pos(w, tl, br); wid_set_text(w, "Quit game?"); } y_at = 2; { TRACE_NO_INDENT(); auto p = wid_quit_window->wid_text_area->wid_text_area; auto w = wid_new_square_button(p, "Yes"); point tl = make_point(0, y_at); point br = make_point(width / 2 - 2, y_at + 2); wid_set_style(w, UI_WID_STYLE_RED); wid_set_on_mouse_up(w, wid_quit_yes); wid_set_pos(w, tl, br); wid_set_text(w, "%%fg=white$Y%%fg=reset$es"); } { TRACE_NO_INDENT(); auto p = wid_quit_window->wid_text_area->wid_text_area; auto w = wid_new_square_button(p, "No"); point tl = make_point(width / 2 + 1, y_at); point br = make_point(width - 2, y_at + 2); wid_set_style(w, UI_WID_STYLE_GREEN); wid_set_on_mouse_up(w, wid_quit_no); wid_set_pos(w, tl, br); wid_set_text(w, "%%fg=white$N%%fg=reset$o"); } wid_update(wid_quit_window->wid_text_area->wid_text_area); game->change_state(Game::STATE_QUIT_MENU, "quit select"); wid_actionbar_init(); }
411
0.964997
1
0.964997
game-dev
MEDIA
0.650671
game-dev
0.962179
1
0.962179
terraforming-mars/terraforming-mars
3,890
src/server/colonies/ColoniesHandler.ts
import {IGame} from '../IGame'; import {IColony} from './IColony'; import {ColonyName} from '../../common/colonies/ColonyName'; import {ICard} from '../cards/ICard'; import {Tag} from '../../common/cards/Tag'; import {SelectColony} from '../inputs/SelectColony'; import {IPlayer} from '../IPlayer'; import {inplaceRemove} from '../../common/utils/utils'; import {CardName} from '../../common/cards/CardName'; export class ColoniesHandler { public static getColony(game: IGame, colonyName: ColonyName, includeDiscardedColonies: boolean = false): IColony { let colony: IColony | undefined = game.colonies.find((c) => c.name === colonyName); if (colony !== undefined) return colony; if (includeDiscardedColonies === true) { colony = game.discardedColonies.find((c) => c.name === colonyName); if (colony !== undefined) { return colony; } } throw new Error(`Unknown colony '${colonyName}'`); } public static tradeableColonies(game: IGame) { return game.colonies.filter((colony) => colony.isActive && colony.visitor === undefined); } public static maybeActivateColonies(game: IGame, card: ICard) { if (!game.gameOptions.coloniesExtension) return; game.colonies.forEach((colony) => { if (colony.isActive === false && ColoniesHandler.cardActivatesColony(colony, card)) { colony.isActive = true; } }); } /* * Return true if the colony is active, or will be activated by this card. * * Returns `true` if the colony is already active, or becomes active from this * call. */ public static cardActivatesColony(colony: IColony, card: ICard): boolean { if (colony.isActive) { return true; } if (colony.metadata.cardResource !== undefined) { if (colony.metadata.cardResource === card.resourceType) { return true; } if (card.name === CardName.MARTIAN_EXPRESS) { return true; } } if (colony.name === ColonyName.VENUS && card.tags.includes(Tag.VENUS) && card.resourceType !== undefined) { return true; } return false; } /** * Add a discarded colony tile back into the game, e.g. with Aridor. */ public static addColonyTile(player: IPlayer, options?: { title?: string, colonies?: Array<IColony>, activateableOnly?: boolean, cb?: (colony: IColony) => void, }): void { const game = player.game; let colonyTiles = options?.colonies ?? game.discardedColonies; if (options?.activateableOnly === true) { colonyTiles = colonyTiles.filter((colonyTile) => colonyTileWillEnterActive(colonyTile, game)); } if (colonyTiles.length === 0) { game.log('No availble colony tiles for ${0} to choose from', (b) => b.player(player)); return; } const title = options?.title ?? 'Select colony tile to add'; function colonyTileWillEnterActive(colony: IColony, game: IGame): boolean { if (colony.isActive) { return true; } for (const player of game.players) { for (const card of player.tableau) { if (ColoniesHandler.cardActivatesColony(colony, card)) { return true; } } } return false; } const selectColonyTile = new SelectColony(title, 'Add colony tile', [...colonyTiles]) .andThen((colonyTile) => { game.colonies.push(colonyTile); game.colonies.sort((a, b) => (a.name > b.name) ? 1 : -1); game.log('${0} added a new Colony tile: ${1}', (b) => b.player(player).colony(colonyTile)); if (!colonyTile.isActive && colonyTileWillEnterActive(colonyTile, game)) { colonyTile.isActive = true; } inplaceRemove(game.discardedColonies, colonyTile); options?.cb?.(colonyTile); return undefined; }); selectColonyTile.showTileOnly = true; player.defer(selectColonyTile); } }
411
0.788596
1
0.788596
game-dev
MEDIA
0.533598
game-dev,testing-qa
0.623366
1
0.623366
tbox1911/Liberation-RX
1,040
core.liberation/scripts/client/actions/do_loot_veh.sqf
params ["_target", "_caller", "_actionId", "_arguments"]; if (isNil "_target") exitWith {}; private _radius = 30; { // All items private _items = (itemCargo _x); // Containers { private _src_name = (_x select 0); private _src_obj = (_x select 1); private _container = [_target, _src_name] call F_addContainerCargo; [_container] call F_clearCargo; {_container addItemCargoGlobal [_x, 1]} forEach (ItemCargo _src_obj + magazineCargo _src_obj + weaponCargo _src_obj); _items = _items - [_src_name]; } forEach (everyContainer _x); // Items { _target addItemCargoGlobal [_x, 1] } forEach _items; // Weapons {_target addWeaponWithAttachmentsCargoGlobal [_x, 1]} forEach (weaponsItems _x); // Magazine { _target addMagazineCargoGlobal [_x, 1] } forEach (magazineCargo _x); // dead body [(getCorpse _x)] spawn { params ["_body"]; hidebody _body; sleep 5; deleteVehicle _body; }; deleteVehicle _x; sleep 0.1; } forEach (nearestObjects [_target, ["GroundWeaponHolder", "WeaponHolderSimulated"], _radius]);
411
0.798724
1
0.798724
game-dev
MEDIA
0.928126
game-dev
0.777423
1
0.777423
RyanFehr/HackerRank
10,807
Algorithms/Implementation/The Bomberman Game/Solution.java
//Problem: https://www.hackerrank.com/challenges/bomber-man //Java 8 /* We can simply keep three sets of bombs 1 second bombs 2 second bombs 3 second bombs Then iteratively detonate and plant bombs each cycle Cycle: 2 OOOOOOO OOOOOOO OOOOOOO OOOOOOO OOOOOOO OOOOOOO Cycle: 3 OOO.OOO OO...OO OOO...O ..OO.OO ...OOOO ...OOOO Cycle: 4 OOOOOOO OOOOOOO OOOOOOO OOOOOOO OOOOOOO OOOOOOO Cycle: 5 ....... ...O... ....O.. ....... OO..... OO..... Cycle: 6 OOOOOOO OOOOOOO OOOOOOO OOOOOOO OOOOOOO OOOOOOO Cycle: 7 OOO.OOO OO...OO OOO...O ..OO.OO ...OOOO ...OOOO Cycle: 8 OOOOOOO OOOOOOO OOOOOOO OOOOOOO OOOOOOO OOOOOOO Cycle: 9 ....... ...O... ....O.. ....... OO..... OO..... Cycle: 10 OOOOOOO OOOOOOO OOOOOOO OOOOOOO OOOOOOO OOOOOOO Cycle: 11 OOO.OOO OO...OO OOO...O ..OO.OO ...OOOO ...OOOO Cycle: 12 OOOOOOO OOOOOOO OOOOOOO OOOOOOO OOOOOOO OOOOOOO Cycle: 13 ....... ...O... ....O.. ....... OO..... OO..... Cycle: 14 OOOOOOO OOOOOOO OOOOOOO OOOOOOO OOOOOOO OOOOOOO Cycle: 15 OOO.OOO OO...OO OOO...O ..OO.OO ...OOOO ...OOOO Cycle: 16 OOOOOOO OOOOOOO OOOOOOO OOOOOOO OOOOOOO OOOOOOO Cycle: 17 ....... ...O... ....O.. ....... OO..... OO..... Cycle: 18 OOOOOOO OOOOOOO OOOOOOO OOOOOOO OOOOOOO OOOOOOO Cycle: 19 OOO.OOO OO...OO OOO...O ..OO.OO ...OOOO ...OOOO Cycle: 20 OOOOOOO OOOOOOO OOOOOOO OOOOOOO OOOOOOO OOOOOOO Grouping based on pattern 1 | 2 | 3 | 4 5 | 6 | 7 | 8 9 | 10| 11| 12 13| 14| 15| 16 17| 18| 19| 20 We see there are only 4 cycles, and all even cycles are the same grid so if we have a even cycle we can just print a full grid If we have an odd cycle then there are two different grids to choose from we can find which grid the number corresponds to by doing n % 4 Time Complexity: O(m*n) //We must build the result which is a m*n matrix Space Complexity: O(m*n) //We store every bomb in a map so our Maps cumulative size is O(n*m) */ import java.io.*; import java.util.*; public class Solution { static Map<Integer,Map<Integer,Integer>> threeSecondBombs = new HashMap<>(); static Map<Integer,Map<Integer,Integer>> twoSecondBombs = new HashMap<>(); static Map<Integer,Map<Integer,Integer>> oneSecondBombs = new HashMap<>(); static Map<Integer,Map<Integer,Integer>> damagedBombs = new HashMap<>(); public static void main(String[] args) { /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ Scanner input = new Scanner(System.in); int row = input.nextInt(); int col = input.nextInt(); int n = input.nextInt(); input.nextLine(); if(n % 2 == 0)//If n is even we always have a full grid of bombs { n = 2; } else if(n > 3) //We are in a repeated pattern(See example above) so we only do either 5 or 7 iterations { n = (n % 4)+4; } //Initialze variables according to input grid char[][] grid = new char[row][col]; for(int i = 0; i < row; i++) { String readRow = input.nextLine(); for(int j = 0; j < col; j++) { if(readRow.charAt(j) == 'O') { if(threeSecondBombs.get(i) == null) { Map<Integer,Integer> map = new HashMap<Integer, Integer>(); threeSecondBombs.put(i, map); threeSecondBombs.get(i).put(j,0); } else { threeSecondBombs.get(i).put(j,0); } } grid[i][j] = readRow.charAt(j); } } int cycle = 2; //Plant all the 2 second bombs if(cycle <= n)//2 second cycle { plantBombs(twoSecondBombs, grid); cycle++; //System.out.println("Plant 2 sec bombs"); //System.out.println("Cycle: 2"); //printGrid(grid); } if(cycle <= n)//3 second cycle { detonateBombs(threeSecondBombs, grid); threeSecondBombs = new HashMap<>(); cycle++; //System.out.println("Detonate 3 sec bombs"); //System.out.println("Cycle: 3"); //printGrid(grid); } //All future cycles //These will function as switches where false is place bomb and true is detonate bomb boolean one = false; boolean two = true; boolean three = false; while(cycle <= n) { //System.out.println("Cycle: "+cycle); if(cycle % 3 == 1)//One cycle { if(!one) { plantBombs(oneSecondBombs, grid); one = !one; //System.out.println("Plant 1 sec bombs"); } else { detonateBombs(oneSecondBombs, grid); one = !one; //System.out.println("Detonate 1 sec bombs"); } } else if(cycle % 3 == 2)//Two cycle { if(!two) { plantBombs(twoSecondBombs, grid); two = !two; //System.out.println("Plant 2 sec bombs"); } else { detonateBombs(twoSecondBombs, grid); two = !two; //System.out.println("Detonate 2 sec bombs"); } } else if(cycle % 3 == 0)//Three cycle { if(!three) { plantBombs(threeSecondBombs, grid); three = !three; //System.out.println("Plant 3 sec bombs"); } else { detonateBombs(threeSecondBombs, grid); three = !three; //System.out.println("Detonate 3 sec bombs"); } } cycle++; //printGrid(grid); //Grid after each cycle } //Print the output grid printGrid(grid); } //Plants a bomb on all open tiles static void plantBombs(Map<Integer,Map<Integer,Integer>> bombSet, char[][] grid) { for(int i = 0; i < grid.length; i++) { for(int j = 0; j < grid[0].length; j++) { if(grid[i][j] == '.') { //System.out.println("Planting 2s Bomb"); if(bombSet.get(i) == null) { //System.out.println("No bomb in row "+i); Map<Integer,Integer> map = new HashMap<Integer, Integer>(); bombSet.put(i, map); bombSet.get(i).put(j,0); } else { bombSet.get(i).put(j,0); } grid[i][j] = 'O'; } } } } //Detonates bombs of a given Map updating the other maps and the grid static void detonateBombs(Map<Integer,Map<Integer,Integer>> bombSet, char[][] grid) { for(Map.Entry<Integer, Map<Integer,Integer>> x : bombSet.entrySet()) { int px = x.getKey(); for(Map.Entry<Integer,Integer> y : x.getValue().entrySet()) { removeDamage(px,y.getKey(),grid); } } for(Map.Entry<Integer, Map<Integer,Integer>> x : damagedBombs.entrySet()) { int px = x.getKey(); for(Map.Entry<Integer,Integer> y : x.getValue().entrySet()) { //System.out.println("Removing Bomb at("+px+","+y.getKey()+")"); if(threeSecondBombs.get(px) != null) { threeSecondBombs.get(px).remove(y.getKey()); //System.out.println("Removing 3s Bomb"); } if(twoSecondBombs.get(px) != null) { twoSecondBombs.get(px).remove(y.getKey()); //System.out.println("Removing 2s Bomb"); } if(oneSecondBombs.get(px) != null) { oneSecondBombs.get(px).remove(y.getKey()); //System.out.println("Removing 1s Bomb"); } } } damagedBombs = new HashMap<>();//Remove the bombs now that we have removed all damage } //Replaces all surrounding O with . and adds surrounding to a list of damaged bombs static void removeDamage(int x, int y, char[][] grid) { grid[x][y] = '.'; removeBomb(x, y); //Left if(y-1 >= 0) { grid[x][y-1] = '.'; removeBomb(x, y-1); } //Right if(y+1 < grid[0].length) { grid[x][y+1] = '.'; removeBomb(x, y+1); } //Up if(x-1 >= 0) { grid[x-1][y] = '.'; removeBomb(x-1, y); } //Down if(x+1 < grid.length) { grid[x+1][y] = '.'; removeBomb(x+1, y); } } //Adds a bomb to the Map of damaged bombs static void removeBomb(int x, int y) { if(damagedBombs.get(x) == null) { Map<Integer,Integer> map = new HashMap<Integer, Integer>(); damagedBombs.put(x, map); damagedBombs.get(x).put(y,0); } else { damagedBombs.get(x).put(y,0); } } static void printBombSet(Map<Integer,Map<Integer,Integer>> bombSet) { for(Map.Entry<Integer, Map<Integer,Integer>> x : bombSet.entrySet()) { int px = x.getKey(); for(Map.Entry<Integer,Integer> y : x.getValue().entrySet()) { System.out.println("("+px+","+y.getKey()+")"); } } } static void printGrid(char[][] grid) { for(char[] l : grid) { for(char m : l) { System.out.print(m); } System.out.println(""); } //System.out.println(""); //Uncomment if you are printing iteratively } }
411
0.743967
1
0.743967
game-dev
MEDIA
0.555562
game-dev
0.903846
1
0.903846
KSPModdingLibs/KSPCommunityFixes
7,144
KSPCommunityFixes/Library/UnityObjectExtensions.cs
using System; using System.Runtime.CompilerServices; namespace KSPCommunityFixes { #pragma warning disable IDE0041 // Use 'is null' check static class UnityObjectExtensions { /// <summary> /// Perform a true reference equality comparison between two UnityEngine.Object references, /// ignoring the "a destroyed object is equal to null" Unity concept.<br/> /// Avoid the performance hit of using the <c>==</c> and <c>Equals()</c> overloads. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool RefEquals(this UnityEngine.Object unityObject, UnityEngine.Object otherUnityObject) { return ReferenceEquals(unityObject, otherUnityObject); } /// <summary> /// Perform a true reference inequality comparison between two UnityEngine.Object references, /// ignoring the "a destroyed object is equal to null" Unity concept.<br/> /// Avoid the performance hit of using the <c>==</c> and <c>Equals()</c> overloads. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool RefNotEquals(this UnityEngine.Object unityObject, UnityEngine.Object otherUnityObject) { return !ReferenceEquals(unityObject, otherUnityObject); } /// <summary> /// Equivalent as the Unity <c>==</c> and <c>Equals()</c> overloads, but 6-8 times faster.<br/> /// Use this if you want to perform an equality check where :<br/> /// - a destroyed <c>UnityEngine.Object</c> instance is considered equal to <c>null</c><br/> /// - two different destroyed <c>UnityEngine.Object</c> instances are not considered equal /// </summary> public static bool NotDestroyedRefEquals(this UnityEngine.Object unityObject, UnityEngine.Object otherUnityObject) { if (ReferenceEquals(unityObject, otherUnityObject)) return true; if (ReferenceEquals(otherUnityObject, null) && unityObject.m_CachedPtr == IntPtr.Zero) return true; if (ReferenceEquals(unityObject, null) && otherUnityObject.m_CachedPtr == IntPtr.Zero) return true; return false; } /// <summary> /// Equivalent as the Unity <c>!=</c> and <c>!Equals()</c> overloads, but 6-8 times faster.<br/> /// Use this if you want to perform an equality check where :<br/> /// - a destroyed <c>UnityEngine.Object</c> instance is considered equal to <c>null</c><br/> /// - two different destroyed <c>UnityEngine.Object</c> instances are not considered equal /// </summary> public static bool NotDestroyedRefNotEquals(this UnityEngine.Object unityObject, UnityEngine.Object otherUnityObject) { if (ReferenceEquals(unityObject, otherUnityObject)) return false; if (ReferenceEquals(otherUnityObject, null) && unityObject.m_CachedPtr == IntPtr.Zero) return false; if (ReferenceEquals(unityObject, null) && otherUnityObject.m_CachedPtr == IntPtr.Zero) return false; return true; } /// <summary> /// True if this <paramref name="unityObject"/> instance is destroyed. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsDestroyed(this UnityEngine.Object unityObject) { return unityObject.m_CachedPtr == IntPtr.Zero; } /// <summary> /// True if this <paramref name="unityObject"/> reference is <c>null</c>, /// ignoring the "a destroyed object is equal to null" Unity concept. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsNullRef(this UnityEngine.Object unityObject) { return ReferenceEquals(unityObject, null); } /// <summary> /// True if this <paramref name="unityObject"/> reference is not <c>null</c>, /// ignoring the "a destroyed object is equal to null" Unity concept. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsNotNullRef(this UnityEngine.Object unityObject) { return !ReferenceEquals(unityObject, null); } /// <summary> /// True if this <paramref name="unityObject"/> reference is <c>null</c> or if the instance is destroyed<br/> /// Equivalent as testing <c><paramref name="unityObject"/> == null</c> but 4-5 times faster. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsNullOrDestroyed(this UnityEngine.Object unityObject) { return ReferenceEquals(unityObject, null) || unityObject.m_CachedPtr == IntPtr.Zero; } /// <summary> /// True if this <paramref name="unityObject"/> reference is not <c>null</c> and the instance is not destroyed<br/> /// Equivalent as testing <c><paramref name="unityObject"/> != null</c> but 4-5 times faster. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsNotNullOrDestroyed(this UnityEngine.Object unityObject) { return !ReferenceEquals(unityObject, null) && unityObject.m_CachedPtr != IntPtr.Zero; } /// <summary> /// Return <c>null</c> when this <paramref name="unityObject"/> reference is <c>null</c> or destroyed, otherwise return the <paramref name="unityObject"/> instance<br/> /// Allow using null conditional and null coalescing operators with <c>UnityEngine.Object</c> derivatives while conforming to the "a destroyed object is equal to null" Unity concept.<br/> /// Example :<br/> /// <c>float x = myUnityObject.DestroyedAsNull()?.myFloatField ?? 0f;</c><br/> /// will evaluate to <c>0f</c> when <c>myUnityObject</c> is destroyed, instead of returning the value still available on the managed instance. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static T DestroyedAsNull<T>(this T unityObject) where T : UnityEngine.Object { if (ReferenceEquals(unityObject, null) || unityObject.m_CachedPtr == IntPtr.Zero) return null; return unityObject; } private static readonly int _instanceIDOffset = UnityEngine.Object.GetOffsetOfInstanceIDInCPlusPlusObject(); /// <summary> /// Faster version of <see cref="UnityEngine.Object.GetInstanceID"/> /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe int GetInstanceIDFast(this UnityEngine.Object unityObject) { long ptrVal = (long)(void*)unityObject.m_CachedPtr; if (ptrVal == 0L) return 0; return *(int*)(void*)(ptrVal + _instanceIDOffset); } } #pragma warning restore IDE0041 // Use 'is null' check }
411
0.557127
1
0.557127
game-dev
MEDIA
0.874608
game-dev
0.701006
1
0.701006
scfmod/FS25_TerraFarm
3,544
scripts/ModHud.lua
source(g_modDirectory .. 'scripts/hud/elements/HUDMachineDisplayElement.lua') ---@class ModHud ---@field vehicle Machine | nil ---@field isDirty boolean ---@field display HUDMachineDisplayElement ModHud = {} ModHud.XML_FILENAME = g_modDirectory .. 'xml/gui/hud/MachineHUD.xml' local ModHud_mt = Class(ModHud) ---@return ModHud ---@nodiscard function ModHud.new() ---@type ModHud local self = setmetatable({}, ModHud_mt) self.isDirty = false self.display = HUDMachineDisplayElement.new() return self end function ModHud:delete() g_messageCenter:unsubscribeAll(self) g_currentMission:removeDrawable(self) g_currentMission:removeUpdateable(self) self.display:delete() self.display = nil end function ModHud:reload() self:delete() self.display = HUDMachineDisplayElement.new() self:load() self:activate() self.vehicle = g_machineManager:getActiveVehicle() self.display:updateDisplay() end function ModHud:load() local xmlFile = XMLFile.load('machineHud', ModHud.XML_FILENAME) if xmlFile == nil then Logging.error('MachineHUD:loadHUD() Failed to load HUD file "%s"', ModHud.XML_FILENAME) return end g_gui.currentlyReloading = true self.display:loadFromXMLFile(xmlFile, 'HUD.BoxLayout') g_gui.currentlyReloading = false xmlFile:delete() end function ModHud:activate() g_messageCenter:subscribe(MessageType.ACTIVE_MACHINE_CHANGED, self.onActiveMachineChanged, self) g_messageCenter:subscribe(SetMachineActiveEvent, self.onMachineUpdated, self) g_messageCenter:subscribe(SetMachineEnabledEvent, self.onMachineUpdated, self) g_messageCenter:subscribe(SetMachineFillTypeEvent, self.onMachineUpdated, self) g_messageCenter:subscribe(SetMachineInputModeEvent, self.onMachineUpdated, self) g_messageCenter:subscribe(SetMachineOutputModeEvent, self.onMachineUpdated, self) g_messageCenter:subscribe(SetMachineTerrainLayerEvent, self.onMachineUpdated, self) g_messageCenter:subscribe(SetMachineDischargeTerrainLayerEvent, self.onMachineUpdated, self) g_messageCenter:subscribe(SetMachineSurveyorEvent, self.onMachineUpdated, self) g_messageCenter:subscribe(SetSurveyorCoordinatesEvent, self.onSurveyorChanged, self) g_currentMission:addDrawable(self) g_currentMission:addUpdateable(self) end ---@param surveyor Surveyor function ModHud:onSurveyorChanged(surveyor) if self.vehicle ~= nil then local surveyorId = self.vehicle:getSurveyorId() if surveyorId ~= nil and surveyorId == surveyor:getSurveyorId() then self.isDirty = true end end end ---@param vehicle Machine | nil function ModHud:onActiveMachineChanged(vehicle) self.vehicle = vehicle self.display:updateDisplay() end ---@param vehicle Machine | nil function ModHud:onMachineUpdated(vehicle) if self.vehicle ~= nil and self.vehicle == vehicle then self.isDirty = true end end function ModHud:onMapLoaded() if g_client ~= nil then self:activate() end end function ModHud:draw() if self.vehicle ~= nil and g_modSettings:getIsEnabled() and self.vehicle:getMachineEnabled() then self.display:draw() end end ---@param dt number function ModHud:update(dt) if self.display ~= nil then if self.isDirty then self.display:updateDisplay() self.isDirty = false end self.display:update(dt) end end ---@diagnostic disable-next-line: lowercase-global g_modHud = ModHud.new()
411
0.977872
1
0.977872
game-dev
MEDIA
0.884572
game-dev
0.984106
1
0.984106
xanthics/gw2craft
20,915
translations/Localfr.py
# -*- coding: utf-8 -*- ''' Author: Jeremy Parks Purpose: fr Localized text Note: Requires Python 3.7.x ''' region = "NA/EU price data only" # Copyright notice for GW2 IP cright = '''<footer> Guild Wars 2 © 2012 ArenaNet, Inc. Tous droits réservés. NCsoft, le logo NC, ArenaNet, Guild Wars, Guild Wars Factions, Guild Wars Nightfall, Guild Wars: Eye of the North, Guild Wars 2 et tous les logos et dessins associés sont des marques commerciales ou déposées de NCsoft Corporation. Toutes les autres marques sont la propriété de leurs propriétaires respectifs. </footer>''' scribetease = "Click here for important hints" scribeinfo = """Note, “Auto Turrets” in the guide are called “Gate Turrets” in game. (API error)<br /> <br /> Tip, If you are scribing a certain item but it does not complete (you do not get experience and no materials are used) the processing stack is full (250 of each item is max). To fix the issue, go to the processor and process the items you wanted to craft + wait until they are done. Then you can scribe your items. Keep in mind that you need to have the "edit assembly queue" guild permission in oder to be able to do this. Alternatively you can ask your guild leader (or someone with this permission) to do it for you. <br /> <br /> <strong>Guild unlocks</strong><br /> Most of the items the guide recommends you to scribe are guild unlocked recipes (see below for a list + alternatives). Your guild needs to have these unlocked before you can see them as recipes and scribe them. If your guild does not have them unlocked yet, you temporarily join another guild (for example “The rising falcons [RiFa]”, see below) that has the unlocks and scribe them in their hall. <br /> <br /> <strong>Decoration crafting, required guild permissions and tips</strong><br /> The guide shows you the cheapest way to level up. Due to the recipes it is not likely decorations will be included, However if they are, OR if you want to level up through crafting decorations, you will need the following permissions form your guild leader to do so:<br /> - Use placeable (so you use decorations that the guild has for scribing)<br /> - edit assembly queue (so you can finish the decoration by adding it in the processor after which you can, depending on the decoration, also use it again for scribing at a higher level)<br /> After scribing your decorations, go to the processor (near the crafting stations in both halls) and queue the decorations you just crafted to complete them (takes 30 sec / item).<br /> <strong>Some additional decoration crafting tips:</strong><br /> 1 You can buy basic decorations at the decorations vendor for 24 silver each if your guild has it unlocked. You can always buy them at the master scribe for 50 silver each (even if your guild does not have any decoration vendor unlocked).<br /> 2 Some basic decorations can only be obtained from the guild trader (guild trader 4 or higher) for guild commendations. <br /> 3 some basic decorations can only be obtained from the decoration trader during certain in game events, for example snow piles from wintersday, pumpkins from Halloween, red lanterns from lunar new year, furniture coins to buy super cloud from SAB festival OR drops from bosses (basically for all the bronze, silver and gold trophies).<br /> <br /> <strong>Guild unlock List and alternatives for each scribe level range:</strong><br /> The guide will always show you the cheapest option. However, it could be that you lack that unlock in your guild but have another one that you could use instead. See this list for alternatives at each crafting level.<br /> Lv 0-25 refine<br /> Lv 25-50 WvW - Minor Supply Drop <discover/craft minor sigils as alternative><br /> Lv 50-75 Guild Banquet Schematic <decorations as alternative><br /> Lv 75-100 refine<br /> Lv 100-125 Guild Gathering Boost Banner Schematic#, Guild World Event Schematic, Sabotage Depot<br /> Lv 125-150 Guild Karma Banner Schematic*, Guild Experience Banner Schematic* <discover/craft major Sigils as alternative><br /> Lv 150-175 refine Guild Road Marker Schematic#<br /> Lv 175-200 Guild Gold Gain Banner Schematic, Hardened Gates, Invulnerable Dolyaks, Speedy Dolyaks<br /> Lv200-225 Guild Karma and Experience Banner Schematic *, turtle Banner, Iron guards, Guild Ballista Blueprints, Guild Arrow cart Blue prints <br /> Lv 225-250 refine<br /> Lv 250-275 Guild Gathering and Swiftness Banner Schematic#, Packed Dolyaks, Centaur Banner<br /> Lv 275-300 no guild unlocked recipes at this level<br /> Lv 300-325 refine<br /> Lv 325-350 Invulnerable Fortifications. refine leather into book covers as alternative<br /> Lv 350-375 Vault Transport, Emergency Waypoint, Gate Turrets (in guide listed as “Auto Turrets”)<br /> Lv375-400 Watchtower, Presence of the Keep<br /> * = these are related, you need 1 karma and 1 experience banner to craft 1 karma and Experience banner<br /> # = these are related, you need 1 Gathering boost banner and 1 Road marker to craft 1 Guild Gathering and swiftness banner.<br /> <br /> <strong>My guild lacks the unlocks/will not give me permissions to level up my scribe</strong><br /> If your guild is missing the guild unlocks (and alternatives) you can “visit” (temporarily join) a guild that has them unlocked so you can level your scribe in their hall. Just keep in mind that all the guild related itmes (banners, WvW items and decorations) that your craft in that guild hall, will stay in the guildhall that you are visiting.<br /> <br /> <p><strong>RiFa appears to be defunct, you should use a guild listed at the beginning of this page.</strong></p><s> <strong>The Rising Falcons[RiFa] and the scribe guide History</strong><br /> Ever since <strong>Vin Lady Venture</strong> made the first static (now outdated) scribe together with <strong>Dulfy</strong> and found out that the guild unlocked scribe recipes could help leveling scribes safe a lot of gold He opened up the guild “The rising Falcons[RiFa]” for scribes who wanted to level up and RiFa has continued to run this service ever since. While the original guide has now been replaced by the much more advanced and up to date guide that you see here, made by <strong>xanthic.9478</strong>, RiFa is still accepting scribes who do not have access to (all of) the guild unlocked recipes. It is a casual relaxed guild that offers this service to anyone who likes to level his/her scribe, free of charge. While RiFa is an EU based guild, US based players can also use the service and unlocks. The only thing is that you cannot see any of the main guild members.<br /> <br /> You can send an in game mail to <strong>Vin lady venture (Rin of Rivvinda.4971)</strong> for an invite in RiFa, just make sure you have at least 1 free guild slot and you should be invited within 24 hours. <br /></s> """ # renown heart vendors crandle = "Agent Crandle - Fort Trinité (Détroit de la Dévastation 70-75)" aidem = "Aidem Finlay - Lac caché (Terres sauvages de Brisban 15-25)" albin = "Chroniqueur Albin - teppes glacées (Contreforts du Voyageur 1-15)" jack = "Jack la pomme(16<span class=\"copperIcon\"></span> per) - Champs de Cornabonde (Champs de Gendarran 25-35)" victor = "Assistant Chef Victor - Plateau de Scaver (Vallée de la reine 1-15)" bjarni = "Bjarni - Col du Hardi (Contreforts du Voyageur 1-15)" braxa = "Braxa Chassécaille - Bouclier du Champion (Marais de fer 50-60)" jenks = "Adjoint Jenks - Passage du géant (Collines de Kesse 15-25)" disa = "Disa - Ravin de l'avalanche (Falaises de Hantedraguerre 40-50)" drottot = "Drottot Queue-cinglante - Gueule du dévoreur (Plaines d'Ashford 1-15)" elain = "Elain - Site de fouilles de Grenbrack (Forêt de Caledon 1-15)" jenrys = "Jenrys, activiste écologique - Rocher du jugement (Mont Maelström 60-70)" eona = "Eona - Marché de Mabon (Forêt de Caledon 1-15)" makayla = "Makayla l'Ange déchu - Bastion de Noirfaucon (Champs de Ruine 30-40)" eda = "Eda la fermière - Champs de Shaemoor (Vallée de la reine 1-15)" leius = "Médecin militaire Leius - Terrasse de Nebo (Champs de Gendarran 25-35)" glubb = "Glubb - Degun Shun (Steppes de la Strie flamboyante 40-50)" hune = "Hune - Les Cornes foudroyantes (Passage de Lornar 25-40)" ichtaca = "Ichtaca - Rives du chasseur (Chutes de la Canopée 50-60)" kastaz = "Kastaz Fortepatte - Vallée de Noxin (Plateau de Diessa 15-25)" laewyn = "Laëwyn - Marais de Wychmire (Forêt de Caledon 1-15)" laudren = "Laudren - Marécage du Tonnetroll (Marais de Lumillule 55-65)" pickins = "Lieutenant Pickins - Butte de Grise-Roche (Hinterlands Harathis 35-45)" summers = "Lieutenant Summers - Plage de Gardenuit (Hinterlands Harathis 35-45)" auda = "Garde du Lion Auda - Montée du dragon (Congères d'Antreneige 15-25)" tunnira = "Eclaireuse de la Garde du Lion Tunnira - Promontoire d'Archen (Côte de la marée sanglante 45-55)" kevach = "Kevach le gardien - Col de Dolyak (Contreforts du Voyageur 1-15)" mcov = "Maître artisan ou Marchand" maxtar = "Maxtar Vivalure - Col de Dolyak (Contreforts du Voyageur 1-15)" milton = "Milton Book - Champs de Cornabonde (Champs de Gendarran 25-35)" naknar = "Naknar - Cours du cœur refluant (Marais de fer 50-60)" nrocroc = "Chef Nrocroc - Contrées sauvages de l'Apostat (Montée de Flambecoeur 60-70)" hrouda = "Enquêteur senior de PR&T Hrouda - Contrées sauvages d'Akk (Province de Metrica 1-15)" pochtecatl = "Pochtecatl - Pointe de Jelako (Côte de la marée sanglante 45-55)" hrappa = "Chercheuse Hrappa - Passage de Voloxian (Province de Metrica 1-15)" sagum = "Sagum Traquartefact - Gorge d'Agnos (Plaines d'Ashford 1-15)" sangdo = "Sangdo Prestaile - Canyon de Cereboth (Collines de Kesse 15-25)" tholin = "Erudit Tholin - Col de Krongar (Chutes de la Canopée 50-60)" vejj = "Capitaine de la sécurité Vejj - Domaines d'Almuten (Champs de Gendarran 25-35)" triktiki = "Sentinelle Triktiki - Fouilles d'Arcallion (Hinterlands Harathis 35-45)" brian = "Archer séraphin Brian - Montée d’Ossencrête (Congères d'Antreneige 15-25)" goran = "Soldat séraphin Goran - Les Marches de Wendon (Terres sauvages de Brisban 15-25)" shelp = "Shelp - Degun Shun (Les steppes de la Strie flamboyante 40-50)" vaastas = "Vaastas Meatslayer - Village du Bloc de Boucher (Plateau de Diessa 15-25)" krug = "Krug vétéran - Contreforts de Taminn (Vallée de la reine 1-15)" wupwup = "Chef Wupwup - Contrées sauvages de l'Apostat (Montée de Flambecoeur 60-70)" yoal = "Yoal - Quetzal(Caledon Forest 1-15)" # guide variables iCost = "Coût Initial" remCost = "Remaining Cost" eRecovery = "Retour Attendu" fCost = "Coût Final Attendu" sList = "Liste des ventes" bRecipes = "ACHETER RECETTES" collectibles = "OBJETS (Vérifier à la banque ou Acheter à l'HV)" warning1 = "Ne pas actualiser la page." warning2 = "Peut changer. Mis à jour" moreInfo = "Chaque fois que vous voyez %s vous pouvez cliquer pour plus d'informations" soldVia = "Vendu pour %s par l'intermédiaire" method = ["Marchand", "Max Buyout", "Prix minimal de vente"] valuePer = "/u" buyVendor = "ACHETER MARCHAND" mixedTP = "Mixte (Acheter à l'HV)" rTP = "Acheter à l'HV" make = "Faire" discover = "Découvrir" expand = "Expand all discovery recipes" collapse = "Collapse all discovery recipes" tier = "Tier %i. Niveaux %i-%i" buyList = "Liste d'Achats (Seulement Tier %i)" blNotice = "Remarque: Si vous suivez le guide complet alors vous avez déjà acheté ces matériaux. This buylist may be missing items that are used in later tiers, but are crafted in this tier. Such as Lucent Motes." costRT = "Coût: %s (Rolling Total: %s)" level = "Niveau" finish = "Rien. Vous avez terminé !" updated = "Mis à jour" note = "<strong>Note:</strong> Les prix affichés ici sont les coûts initiaux et ne prennent pas en compte les retours de ventes." craft = "Artisanat" tiers = "Tier" toggle = "Cliquez pour Basculer" kNote = "Note: 11 Feuille de basilic(e.g.) signifie acheter 1 Feuilles de basilic en vrac et il vous restera 14" bNote = "Produit {} par création" api_note = "The API key you enter needs \'inventories\' permissions for bank items and \'unlocks\' for recipes." api_new_key = "You can generate a key here" # FAQ strings costs = "Les coûts sont couverts, mais les dons sont appréciés" oThread = "Fil de discussion sur le forum officiel GW2 (En)" rThread = "Fil de discussion reddit (En)" gThread = "Fil de discussion guildwars2guru (En)" twitter = "Twitter (En)" email = "Email (En)" contact = "Si vous avez des questions, des commentaires, des préoccupations ou sentez que vous avez remarqué un bug, merci de me contacter en utilisant l'une de ces méthodes." faq = "FAQ" question = "Q" answer = "R" source = "Le code source ?" q1 = "Combien de niveaux puis-je obtenir de l'artisanat ?" a11 = "La quantité d'expérience que vous obtenez de l'artisanat est déterminé par votre progression à travers les niveaux d'artisanat basé sur les valeurs suivantes;" a12 = "1-100 1% du niveau actuel par niveau d'artisanat" a13 = "101-200 2% du niveau actuel par niveau d'artisanat" a14 = "201-300 3% du niveau actuel par niveau d'artisanat" a15 = "301-400 4% du niveau actuel par niveau d'artisanat" a16 = "Et ces valeurs evoluent vers des niveaux partiels, comme niveau 1, une moitié de barre est 1.5% d'un niveau. Aller de 0-400 vous donnera 10 niveaux peut importe le niveau auquel vous avez commencé, à chaque fois." a17 = "Il y a 1 exception, les récompenses d'xp de 1-15 sont plus grandes que l'xp nécessaire pour ces niveaux (<a href=\"http://wiki.guildwars2.com/wiki/Experience#Total_experience_gain_per_level\">source (En)</a>). Vous obtiendrez donc environs 13 niveaux à ce moment là." a18 = "Cela signifie que vous pouvez passer du niveau 2 au niveau 80 uniquement avec l'artisanat, en maîtrisant les 8 disciplines d'artisanat." q2 = "Ces guides seront-ils faux si tout le monde achète l'objet X ?" a2 = "Ces guident proposent la création ou l'achat d'objets basés sur les prix de l'HV. Ils adapteront les objets suggérés suivant les changements de prix. (Pratiquement) toues les recettes possibles sont prisent en compte lors de la génération des guides." q3 = "Questions diverses sur les taux/chances de critique ou d'Augmentation d'artisanat." a31 = "Ce script suppose un taux de critique de 0%, les critiques peuvent réduire le nombre de créations et donc de matériaux nécessaires." a32 = "L'Augmentation d'artisanat donne +50%, s'additionnant avec le bonus McM, chances de critique pendant l'artisanat. Bonus max de 90%. Un critique vous donne un bonus d'expérience de 50% qui s'additionne à d'autres bonus (découverte, Chef-d'&oelig;uvre et créations rare). L'Augmentation d'artisanat peut réduire le nombre de créations nescessaires pour atteindre 400 dans une discipline, mais ne vous fera pas gagner plus de 10 niveaux." q4 = "Puis-je réutiliser ou créer un lien vers vos guides ?" a4 = "Oui soyez juste conscient que les guident peuvent changer et que je ne fournirai pas de support. Veuillez, s'il vous plait, bien attribuer (xanthic.9478 et un lien vers ce site)." q5 = "Questions diverses sur la considération des valeurs de vente de l'HV ou de l'ajout du recouvrement du coût des marchands." a51 = "L'équilibrage basé sur les ventes de l'HV ajouterait un risque au prix du guide, si les prix s'égalisent ou stagnent, enlevant la capacité pour certaines personnes de couvrir les coût de cette manière et donc de rendre leur parcours à travers le guide plusieurs pièces d'argent plus cher. Je fournis actuellement une \"meilleure estimation\" pour couvrir les coûts basé sur l'enchère maximum ou le prix du marchand, suivant le plus élevé, et si 0, le prix minimal de vente à l'HV." a52 = "Il n'éxiste également pas de manière \"automatique\" de déterminer si un objet se vendra au prix indiqué." q6 = "Comment faites-vous ces guides ?" a6 = "Un script Python 3.7.3 en plusieurs parties, qui utilise un algorythme glouton et ndes données de prix à partir de Anet API pour calculer la méthode d'artisanat la moins couteuse en utilisant les formules dans le jeu." q7 = "Non, je veux dire, comment faites-vous ces guides ? (Réponse simple)" a7 = "Pour chaque \"Faire\", je génère une liste d'objets, calcule la methode avec le plus d'xp/plus bas coût de faire cet objet basé sur l'artisanat ou l'achat de ses composants, pour ensuite choisir le meilleur objet à faire." q8 = "Non, je veux dire, comment faites-vous ces guides ? (Réponse élaborée)" a8 = "Premièrement je divise l'artisanat en 16 25 seaux de points (ie 0-24, 25-49). Ensuite à partir de 375 je calcule (pour chaque objet donnant de l'xp) son xp/coût de base, pour chqaue sous-partie de cet objet je calcule son xp/coût de base et si aucun de ces objets n'a de sous-partie, je calcule alors leurs xp/coût de base jusqu'à ce que j'atteigne des objets sans recettes. Les sous-parties sont choisies pour être faites si elles sont moins cher que d'acheter la partie, ou elles augmentent le ratio xp/coût de base plus que d'acheter la partie. C'est pourquoi le guide peut vous dire de faire quemque chose même si il est légèrement moins cher de l'acheter. Ensuite, après que le meilleur choix soit trouvé, les changements d'xp sont calculés (incluant tous les seaux) et alors le meilleur choix est retrouvé." thanks = "Merci aux personnes qui ont créé ces guides avant moi; Qorthos, pwnuniversity, gw2wiz et guildwars-2-crafting. Je n'aurai pas eu l'idée d'écrire ceci sans vos guides, me fournissant un modèle à partir duquel j'ai pu construire." # index strings fThings = "4 choses que vous devez savoir" t1 = "<img src=\"/img/arrow.png\" alt=\"ARROW\"> peut être cliqué pour toutes les recettes de découverte ainsi que la liste des objets vendus" t2 = "<input type=\"checkbox\"/> existe afin que vous puissiez suivre votre position dans la liste d'achats" t3 = "listes d'achat spécifiques de niveau existent pour les guides non-cuisson (cliquez sur le bouton) " t4 = "<a href=\"nav.html\">la page Nav</a> si vous ne pouvez pas utiliser la barre de navigation" nge = "va faire des choix judicieux entre l'artisanat ou l'achat de sous-parties d'un article." fge = "fait le même point pour 25 points. Plus rapide et plus facile que d'autres guides, mais plus cher." tge = "sera l'artisan des sous parties d'un article si possible au lieu d'acheter. Généralement plus cher que les guides normales, mais peut être moins complexe. Ceci est similaire à l'artisanat guides qui existaient avant ACCG." wit = "<strong>C'est quoi ?:</strong> Guides d'artisanat toujours à jour pour Guild Wars 2. Tous les guides sont recalculés sur la base des prix actuels de l'HV chaque heure, en supposant que l'ordinateur exécutant le script est en marche et Anet API est accessible. Ces guides ont été créés à l'origine pour des amis, mais au vu de la popularité de ces derniers dans la communauté de Guild Wars 2, j'ai continué à les améliorer pour devenir ce que vous voyez aujourd'hui. Ce script ne suppose qu'il y a \"infinie\" d'un point à un coût donné, donc si ils ont tous se rachetés, ou il ya très peu disponibles dans les prix de la fenêtre de mise à jour peut être mal jusqu'à la prochaine mise à jour." nWarn = "<strong>Avis:</strong> Si vous n'allez pas faire le guide dans une séance assurez-vous de l'enregistrer sur votre machine. Comme ces guides peut et va changer." rCost = "<strong>Conseils pour réduire les coûts:</strong> Enregistrez une copie du guide et placer des ordres d'achat pour les matériaux." thanks2 = "" # nav strings navNotice = "C'est une page de navigation simple, vous ne devriez l'atteindre que si vous ne pouvez pas utiliser la barre de navigation. Si vous traduisez ce site, s'il vous plaît, écrivez-moi à gw2crafts@live.com avec la langue source et la page de traduction utilisés et j'essaierais d'y remédier." navLang = "Langue" #nav page headers and guide names home = "Accueil" nGuides = "Guides Normaux" fGuides = "Guides Rapides" tGuides = "Guides Traditionnels" cooking = "Maître-queux" nHearts = "Pas De Coeurs" tHearts = "Top 5 Des Coeurs" aHearts = "Tous Les Coeurs" jc = "Bijoutier" art = "Artificier" hunt = "Chasseur" wc = "Forgeron d'armes" ac = "Forgeron d'armures" lw = "Travailleur du cuir" tailor = "Tailleur" totals = "Totaux" about = "A Propos" lang = "Français" special = "Special" scribe = "Scribe" # directory path path = "fr/" lang_code = 'fr'
411
0.610485
1
0.610485
game-dev
MEDIA
0.446285
game-dev
0.517951
1
0.517951
magarena/magarena
1,532
src/magic/model/action/TurnFaceUpAction.java
package magic.model.action; import java.util.Collection; import java.util.Collections; import magic.model.MagicGame; import magic.model.MagicPermanent; import magic.model.MagicPermanentState; import magic.model.mstatic.MagicStatic; import magic.model.trigger.MagicTriggerType; public class TurnFaceUpAction extends MagicAction { public final MagicPermanent permanent; private Collection<MagicStatic> oldStatics = Collections.emptyList(); private Collection<MagicStatic> newStatics = Collections.emptyList(); public TurnFaceUpAction(final MagicPermanent aPermanent) { permanent = aPermanent; } @Override public void doAction(final MagicGame game) { if (permanent.isFaceDown() && permanent.getRealCardDefinition().isPermanent()) { oldStatics = permanent.getStatics(); game.doAction(ChangeStateAction.Clear(permanent, MagicPermanentState.FaceDown)); game.doAction(ChangeStateAction.Clear(permanent, MagicPermanentState.Manifest)); newStatics = permanent.getStatics(); game.removeStatics(permanent, oldStatics); game.addStatics(permanent, newStatics); // force an update so that triggers are registered game.update(); game.executeTrigger(MagicTriggerType.WhenTurnedFaceUp, permanent); } } @Override public void undoAction(final MagicGame game) { game.removeStatics(permanent, newStatics); game.addStatics(permanent, oldStatics); } }
411
0.723173
1
0.723173
game-dev
MEDIA
0.771193
game-dev
0.891983
1
0.891983
project-slippi/project-slippi
1,385
scripts/stallingDetectTesting.js
const { SlippiGame } = require("@slippi/slippi-js"); const game = new SlippiGame("D:\\Slippi\\Tournament-Replays\\Genesis-8\\Top 8\\Game_8C56C58C3FBD_20220417T183153.slp"); const frames = Object.values(game.getFrames()); const settings = game.getSettings(); const p1Idx = settings.players[0].playerIndex; const p2Idx = settings.players[1].playerIndex; let p1CloserCount = 0; let p2CloserCount = 0; let p1AirborneCount = 0; let p2AirborneCount = 0; frames.forEach(frame => { p1Post = frame.players[p1Idx].post; p2Post = frame.players[p2Idx].post; p1Distance = Math.sqrt(p1Post.positionX * p1Post.positionX + p1Post.positionY * p1Post.positionY); p2Distance = Math.sqrt(p2Post.positionX * p2Post.positionX + p2Post.positionY * p2Post.positionY); if (p1Distance < p2Distance) { p1CloserCount += 1; } else if (p2Distance < p1Distance) { p2CloserCount += 1; } p1AirborneCount += p1Post.isAirborne; p2AirborneCount += p2Post.isAirborne; }); const total = frames.length; console.log(`P${p1Idx + 1}: CloserToCenter: ${p1CloserCount} (${(100 * p1CloserCount / total).toFixed(1)}%) Airborne: ${p1AirborneCount} (${(100 * p1AirborneCount / total).toFixed(1)}%)`); console.log(`P${p2Idx + 1}: CloserToCenter: ${p2CloserCount} (${(100 * p2CloserCount / total).toFixed(1)}%) Airborne: ${p2AirborneCount} (${(100 * p2AirborneCount / total).toFixed(1)}%)`);
411
0.617558
1
0.617558
game-dev
MEDIA
0.496332
game-dev
0.84898
1
0.84898
splinesoft/Bequest
1,414
src/Pods/Headers/Public/pop/POPAnimationExtras.h
/** Copyright (c) 2014-present, Facebook, Inc. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. An additional grant of patent rights can be found in the PATENTS file in the same directory. */ #import <QuartzCore/CAAnimation.h> #import <pop/POPDefines.h> #import <pop/POPSpringAnimation.h> /** @abstract The current drag coefficient. @discussion A value greater than 1.0 indicates Simulator slow-motion animations are enabled. Defaults to 1.0. */ extern CGFloat POPAnimationDragCoefficient(); @interface CAAnimation (POPAnimationExtras) /** @abstract Apply the current drag coefficient to animation speed. @discussion Convenience utility to respect Simulator slow-motion animation settings. */ - (void)pop_applyDragCoefficient; @end @interface POPSpringAnimation (POPAnimationExtras) /** @abstract Converts from spring bounciness and speed to tension, friction and mass dynamics values. */ + (void)convertBounciness:(CGFloat)bounciness speed:(CGFloat)speed toTension:(CGFloat *)outTension friction:(CGFloat *)outFriction mass:(CGFloat *)outMass; /** @abstract Converts from dynamics tension, friction and mass to spring bounciness and speed values. */ + (void)convertTension:(CGFloat)tension friction:(CGFloat)friction toBounciness:(CGFloat *)outBounciness speed:(CGFloat *)outSpeed; @end
411
0.675665
1
0.675665
game-dev
MEDIA
0.665568
game-dev
0.506818
1
0.506818
Ideefixze/TutorialUnityMultiplayer
11,925
MultiplayerArchitectureUnity/Library/PackageCache/com.unity.textmeshpro@3.0.1/Scripts/Editor/TMP_StyleSheetEditor.cs
using System; using UnityEngine; using UnityEditor; namespace TMPro.EditorUtilities { [CustomPropertyDrawer(typeof(TMP_Style))] public class StyleDrawer : PropertyDrawer { public static readonly float height = 95f; public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { return height; } public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { SerializedProperty nameProperty = property.FindPropertyRelative("m_Name"); SerializedProperty hashCodeProperty = property.FindPropertyRelative("m_HashCode"); SerializedProperty openingDefinitionProperty = property.FindPropertyRelative("m_OpeningDefinition"); SerializedProperty closingDefinitionProperty = property.FindPropertyRelative("m_ClosingDefinition"); SerializedProperty openingDefinitionArray = property.FindPropertyRelative("m_OpeningTagArray"); SerializedProperty closingDefinitionArray = property.FindPropertyRelative("m_ClosingTagArray"); EditorGUIUtility.labelWidth = 86; position.height = EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing; float labelHeight = position.height + 2f; EditorGUI.BeginChangeCheck(); Rect rect0 = new Rect(position.x, position.y, (position.width) / 2 + 5, position.height); EditorGUI.PropertyField(rect0, nameProperty); if (EditorGUI.EndChangeCheck()) { // Recompute HashCode if name has changed. hashCodeProperty.intValue = TMP_TextUtilities.GetSimpleHashCode(nameProperty.stringValue); property.serializedObject.ApplyModifiedProperties(); // Dictionary needs to be updated since HashCode has changed. TMP_StyleSheet styleSheet = property.serializedObject.targetObject as TMP_StyleSheet; styleSheet.RefreshStyles(); } // HashCode Rect rect1 = new Rect(rect0.x + rect0.width + 5, position.y, 65, position.height); GUI.Label(rect1, "HashCode"); GUI.enabled = false; rect1.x += 65; rect1.width = position.width / 2 - 75; EditorGUI.PropertyField(rect1, hashCodeProperty, GUIContent.none); GUI.enabled = true; // Text Tags EditorGUI.BeginChangeCheck(); // Opening Tags position.y += labelHeight; GUI.Label(position, "Opening Tags"); Rect textRect1 = new Rect(110, position.y, position.width - 86, 35); openingDefinitionProperty.stringValue = EditorGUI.TextArea(textRect1, openingDefinitionProperty.stringValue); if (EditorGUI.EndChangeCheck()) { // If any properties have changed, we need to update the Opening and Closing Arrays. int size = openingDefinitionProperty.stringValue.Length; // Adjust array size to match new string length. if (openingDefinitionArray.arraySize != size) openingDefinitionArray.arraySize = size; for (int i = 0; i < size; i++) { SerializedProperty element = openingDefinitionArray.GetArrayElementAtIndex(i); element.intValue = openingDefinitionProperty.stringValue[i]; } } EditorGUI.BeginChangeCheck(); // Closing Tags position.y += 38; GUI.Label(position, "Closing Tags"); Rect textRect2 = new Rect(110, position.y, position.width - 86, 35); closingDefinitionProperty.stringValue = EditorGUI.TextArea(textRect2, closingDefinitionProperty.stringValue); if (EditorGUI.EndChangeCheck()) { // If any properties have changed, we need to update the Opening and Closing Arrays. int size = closingDefinitionProperty.stringValue.Length; // Adjust array size to match new string length. if (closingDefinitionArray.arraySize != size) closingDefinitionArray.arraySize = size; for (int i = 0; i < size; i++) { SerializedProperty element = closingDefinitionArray.GetArrayElementAtIndex(i); element.intValue = closingDefinitionProperty.stringValue[i]; } } } } [CustomEditor(typeof(TMP_StyleSheet)), CanEditMultipleObjects] public class TMP_StyleEditor : Editor { TMP_StyleSheet m_StyleSheet; SerializedProperty m_StyleListProp; int m_SelectedElement = -1; int m_Page; bool m_IsStyleSheetDirty; void OnEnable() { m_StyleSheet = target as TMP_StyleSheet; m_StyleListProp = serializedObject.FindProperty("m_StyleList"); } public override void OnInspectorGUI() { Event currentEvent = Event.current; serializedObject.Update(); m_IsStyleSheetDirty = false; int elementCount = m_StyleListProp.arraySize; int itemsPerPage = (Screen.height - 100) / 110; if (elementCount > 0) { // Display each Style entry using the StyleDrawer PropertyDrawer. for (int i = itemsPerPage * m_Page; i < elementCount && i < itemsPerPage * (m_Page + 1); i++) { // Define the start of the selection region of the element. Rect elementStartRegion = GUILayoutUtility.GetRect(0f, 0f, GUILayout.ExpandWidth(true)); EditorGUILayout.BeginVertical(EditorStyles.helpBox); SerializedProperty styleProperty = m_StyleListProp.GetArrayElementAtIndex(i); EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(styleProperty); EditorGUILayout.EndVertical(); if (EditorGUI.EndChangeCheck()) { // } // Define the end of the selection region of the element. Rect elementEndRegion = GUILayoutUtility.GetRect(0f, 0f, GUILayout.ExpandWidth(true)); // Check for Item selection Rect selectionArea = new Rect(elementStartRegion.x, elementStartRegion.y, elementEndRegion.width, elementEndRegion.y - elementStartRegion.y); if (DoSelectionCheck(selectionArea)) { if (m_SelectedElement == i) { m_SelectedElement = -1; } else { m_SelectedElement = i; GUIUtility.keyboardControl = 0; } } // Handle Selection Highlighting if (m_SelectedElement == i) TMP_EditorUtility.DrawBox(selectionArea, 2f, new Color32(40, 192, 255, 255)); } } // STYLE LIST MANAGEMENT Rect rect = EditorGUILayout.GetControlRect(false, 20); rect.width /= 6; // Move Style up. bool guiEnabled = GUI.enabled; if (m_SelectedElement == -1 || m_SelectedElement == 0) { GUI.enabled = false; } if (GUI.Button(rect, "Up")) { SwapStyleElements(m_SelectedElement, m_SelectedElement - 1); } GUI.enabled = guiEnabled; // Move Style down. rect.x += rect.width; if (m_SelectedElement == elementCount - 1) { GUI.enabled = false; } if (GUI.Button(rect, "Down")) { SwapStyleElements(m_SelectedElement, m_SelectedElement + 1); } GUI.enabled = guiEnabled; // Add Style rect.x += rect.width * 3; if (GUI.Button(rect, "+")) { int index = m_SelectedElement == -1 ? 0 : m_SelectedElement; if (index > elementCount) index = elementCount; // Copy selected element m_StyleListProp.InsertArrayElementAtIndex(index); // Select newly inserted element m_SelectedElement = index + 1; serializedObject.ApplyModifiedProperties(); m_StyleSheet.RefreshStyles(); } // Delete style rect.x += rect.width; if (m_SelectedElement == -1 || m_SelectedElement >= elementCount) GUI.enabled = false; if (GUI.Button(rect, "-")) { int index = m_SelectedElement == -1 ? 0 : m_SelectedElement; m_StyleListProp.DeleteArrayElementAtIndex(index); m_SelectedElement = -1; serializedObject.ApplyModifiedProperties(); m_StyleSheet.RefreshStyles(); return; } // Return if we can't display any items. if (itemsPerPage == 0) return; // DISPLAY PAGE CONTROLS int shiftMultiplier = currentEvent.shift ? 10 : 1; // Page + Shift goes 10 page forward Rect pagePos = EditorGUILayout.GetControlRect(false, 20); pagePos.width /= 3; // Previous Page if (m_Page > 0) GUI.enabled = true; else GUI.enabled = false; if (GUI.Button(pagePos, "Previous")) m_Page -= 1 * shiftMultiplier; // PAGE COUNTER GUI.enabled = true; pagePos.x += pagePos.width; int totalPages = (int)(elementCount / (float)itemsPerPage + 0.999f); GUI.Label(pagePos, "Page " + (m_Page + 1) + " / " + totalPages, TMP_UIStyleManager.centeredLabel); // Next Page pagePos.x += pagePos.width; if (itemsPerPage * (m_Page + 1) < elementCount) GUI.enabled = true; else GUI.enabled = false; if (GUI.Button(pagePos, "Next")) m_Page += 1 * shiftMultiplier; // Clamp page range m_Page = Mathf.Clamp(m_Page, 0, elementCount / itemsPerPage); if (serializedObject.ApplyModifiedProperties()) { TMPro_EventManager.ON_TEXT_STYLE_PROPERTY_CHANGED(true); if (m_IsStyleSheetDirty) { m_IsStyleSheetDirty = false; m_StyleSheet.RefreshStyles(); } } // Clear selection if mouse event was not consumed. GUI.enabled = true; if (currentEvent.type == EventType.MouseDown && currentEvent.button == 0) m_SelectedElement = -1; } // Check if any of the Style elements were clicked on. static bool DoSelectionCheck(Rect selectionArea) { Event currentEvent = Event.current; switch (currentEvent.type) { case EventType.MouseDown: if (selectionArea.Contains(currentEvent.mousePosition) && currentEvent.button == 0) { currentEvent.Use(); return true; } break; } return false; } void SwapStyleElements(int selectedIndex, int newIndex) { m_StyleListProp.MoveArrayElement(selectedIndex, newIndex); m_SelectedElement = newIndex; m_IsStyleSheetDirty = true; } } }
411
0.974493
1
0.974493
game-dev
MEDIA
0.788033
game-dev,desktop-app
0.99154
1
0.99154
Kromster80/knights_province
9,302
maps/Bloodstone Oasis/wagon_supply.script
// #################### WagonSupply script #################### // Author: Amaroth. This script requires Amaroth's Extra utils to run. // Version: 1.3.0 (2025-02-12) // The intended use of this script is to provide an easy to use interface to set up supply chain. Wagons will appear on the starting coordinates, they will be filled with appropriate amount of resources (if there's too much for 1 wagon to carry, more are spawned, as needed), and sent towards the closest house of their owner which can take the resources in. If no house is found, the wagons will just stay where they are // Some of the optioal features are: The owner receives a message that the wagons could not find a valid storehouse. Or, if no valid storehouse was found, the wagons don't spawn in the first place. Also, when a wagon is taken/stolen, it can be automatically sent to the new owner's base (if the new owner has a valid storehouse of his own). // HOW TO USE: // 1. Add WSInitiateScript to your OnMissionStart event handler. // 2. Add WSResolveTick to your OnTick event handler. // 3. (Optional): Add msg_supply_no_storehouse into your map's libx. This message is to notify the player that the wagons could not find a storehouse/camp/fort/barracks to deliver the resources into, and that they are awaiting the player's commands. Word this to your player in any way you like. This needs to be done only if allowedNoStoreMessage is True. // 4. (Optional): Add WSCheckSendStolenWagon into your OnUnitOwnerChanged. // 5. Use WSAddWagonSupply to create and configure periodical stream of supply to a player. // 6. There are some more optional functions here. Check their individual descriptions for more info. // 7. ?? // 8. Profit. uses extra_utils; const WS_WAGON_CAPACITY = 50; // Check WSAddWagonSupply for more info. type WSWagonSupply = record aPlayer, spawnX, spawnY, startTick, stopTick, supplyFrequency: Integer; wareType: TKMWareType; wareAmount: Integer; allowedNoStoreMessage, allowedNoStoreNoSpawn, horsePreferFort: Boolean; end; var WSWagonSupplies: array of WSWagonSupply; WagonCurrentTick: Integer; AutoSendHomeAllowed: Boolean; // Creates a new supply for the given player. Periodically, wagons will be spawned, and they will deliver the resources to the player's house. procedure WSAddWagonSupply(aPlayer, spawnX, spawnY, startTick, stopTick, supplyFrequency: Integer; wareType: TKMWareType; wareAmount: Integer; allowedNoStoreMessage, allowedNoStoreNoSpawn, horsePreferFort: Boolean); var WSWagonSupply: WSWagonSupply; arrLen: Integer; begin // Who will be the initial owner. WSWagonSupply.aPlayer := aPlayer; // Spawn coordinates for the wagons. WSWagonSupply.spawnX := spawnX; WSWagonSupply.spawnY := spawnY; // When will the spawning start, when will it stop, and how frequently (in ticks) will it occur. Enter -1 for stopTick to make the wagon spawn never end. WSWagonSupply.startTick := startTick; WSWagonSupply.stopTick := stopTick; WSWagonSupply.supplyFrequency := supplyFrequency; // The type of the supplied resource. WSWagonSupply.wareType := wareType; // The amount of the supplied resource per 1 period/delivery. The script will spawn as many wagons as are needed. WSWagonSupply.wareAmount := wareAmount; // If allowed, messages will pop up for the player notifying there is no available storehouse for resources being sent. Happens only if allowedNoStoreNoSpawn is disabled. WSWagonSupply.allowedNoStoreMessage := allowedNoStoreMessage; // If allowed, wagons will not spawn if there is no suitable storehouse for them to head towards. WSWagonSupply.allowedNoStoreNoSpawn := allowedNoStoreNoSpawn; // If allowed, horses will prioritize Forts over Barracks, if both are found. WSWagonSupply.horsePreferFort := horsePreferFort; arrLen := Length(WSWagonSupplies); SetLength(WSWagonSupplies, arrLen + 1); WSWagonSupplies[arrLen] := WSWagonSupply; end; // Returns if the given wagon supply's time for the next delivery is up. function WSSupplyIsReady(var wagon: WSWagonSupply): Boolean; begin Result := ((WagonCurrentTick - wagon.startTick) mod wagon.supplyFrequency = 0) and (WagonCurrentTick >= wagon.startTick) and ((WagonCurrentTick < wagon.stopTick) or (wagon.stopTick = -1)); end; // function WSSpawnFilledWagons(aPlayer, aX, aY: Integer; wareType: TKMWareType; wareAmount: Integer): array of Integer; var i, fullWagonAmount, lastWagonLoad: Integer; wagons: array of Integer; begin if (wareAmount <= 0) or (aPlayer < 0) or (aX < 0) or (aY < 0) or (wareType = wtAll) or (wareType = wtWarfare) or (wareType = wtFood) or (wareType = wtNone) then Exit; fullWagonAmount := Trunc(wareAmount / WS_WAGON_CAPACITY); lastWagonLoad := wareAmount mod WS_WAGON_CAPACITY; for i := 0 to fullWagonAmount - 1 do begin Utils.ArrayAppendI(wagons, Actions.GiveUnit(aPlayer, utWagon, aX, aY, 0)); Actions.UnitCarryGive(wagons[i], wareType, WS_WAGON_CAPACITY); end; if (lastWagonLoad > 0) then begin Utils.ArrayAppendI(wagons, Actions.GiveUnit(aPlayer, utWagon, aX, aY, 0)); Actions.UnitCarryGive(wagons[High(wagons)], wareType, lastWagonLoad); end; Result := wagons; end; // Spawns the wagons to carry the supply towards the target house. procedure WSSupplySend(var wagon: WSWagonSupply; targetHouse: Integer); var i: Integer; wagons: array of Integer; begin if (targetHouse > 0) and ((wagon.aPlayer <> States.HouseOwner(targetHouse)) or (not States.HouseIsComplete(targetHouse)) or (States.HouseDestroyed(targetHouse))) then Exit; wagons := WSSpawnFilledWagons(wagon.aPlayer, wagon.spawnX, wagon.spawnY, wagon.wareType, wagon.wareAmount); if (targetHouse > 0) then for i := 0 to High(wagons) do Actions.UnitWagonOrderEnterHouse(wagons[i], targetHouse); end; // Sends the given wagon to the closest house that can accept its contents procedure WSSendWagonToClosestHouse(aWagon: Integer); var closestHouse: Integer; closestDistance: Single; begin closestHouse := UTWareGetClosestPlayerStore(States.UnitOwner(aWagon), States.UnitPositionX(aWagon), States.UnitPositionY(aWagon), States.UnitCarryType(aWagon), False); if (closestHouse > 0) then Actions.UnitWagonOrderEnterHouse(aWagon, closestHouse); end; // Sends the resources from one house to another. The resources are taken from the origin house. This works even if the houses are owned by different players - can be used for trading. procedure WSSendResourcesHouseToHouse(originHouse, destinationHouse: Integer; wareType: TKMWareType; wareAmount: Integer); var i, fullWagonAmount, lastWagonLoad, newWagon: Integer; spawnPos: TKMPoint; wagons: array of Integer; begin if not (originHouse > 0) or not (destinationHouse > 0) then Exit; if not States.HouseIsComplete(originHouse) or not States.HouseIsComplete(destinationHouse) then Exit; if (States.HouseWareInside(originHouse, wareType) < wareAmount) then Exit; Actions.HouseWareRemove(originHouse, wareType, wareAmount); spawnPos := States.HousePositionDoorstep(originHouse); wagons := WSSpawnFilledWagons(States.HouseOwner(destinationHouse), spawnPos.X, spawnPos.Y, wareType, wareAmount); for i := 0 to High(wagons) do Actions.UnitWagonOrderEnterHouse(wagons[i], destinationHouse); end; // Call this from OnUnitOwnerChanged event handler - used for auto-sending stolen wagons to the robber's base. Note that this will not work if the player has no valid destination house available, and then, currently, the wagon will just remain standing idle anyway. procedure WSCheckSendStolenWagon(aOldUnit, aNewUnit: Integer); begin if (States.UnitType(aNewUnit) = utWagon) and AutoSendHomeAllowed then WSSendWagonToClosestHouse(aNewUnit); end; // Checks whether a wagon has suitable destination. If not and apropriate conditions are met, notifies the player. If apropriate, initiates wagon spawn. procedure WSCheckSupplySend(var wagon: WSWagonSupply); var closestHouse: Integer; closestDistance: Single; begin closestHouse := UTWareGetClosestPlayerStore(wagon.aPlayer, wagon.spawnX, wagon.spawnY, wagon.wareType, False); if (closestHouse < 0) then begin if wagon.allowedNoStoreNoSpawn then Exit; if wagon.allowedNoStoreMessage and (closestHouse < 0) then Actions.PlayerMessage(wagon.aPlayer, '<$msg_supply_no_storehouse>', True); end; WSSupplySend(wagon, closestHouse); end; // Disables all wagon supplies of the given player. Commonly used when a player is defeated. procedure WSPlayerDisableSupplies(aPlayer: Integer); var i: Integer; begin for i := 0 to High(WSWagonSupplies) do if (WSWagonSupplies[i].aPlayer = aPlayer) then WSWagonSupplies[i].stopTick := WagonCurrentTick; end; // Init the script and its config values. Call this from OnMissionStart. procedure WSInitiateScript(sendHomeAllowed: Boolean); begin // Relevant if a wagon is stolen. Needs OnUnitOwnerChanged event handler. AutoSendHomeAllowed := sendHomeAllowed; end; // Each tick, checks whether there is a wagon supply to be sent out. Call this from OnTick. procedure WSResolveTick(aTick: Integer); var i: Integer; begin WagonCurrentTick := aTick; for i := 0 to High(WSWagonSupplies) do if (WSSupplyIsReady(WSWagonSupplies[i])) then WSCheckSupplySend(WSWagonSupplies[i]); end; // #################### End of WagonSupply script ####################
411
0.943697
1
0.943697
game-dev
MEDIA
0.971027
game-dev
0.868826
1
0.868826
LostCityRS/Content
1,354
scripts/quests/quest_itwatchtower/scripts/gorad.rs2
[opnpc1,gorad] if(getbit_range(%itwatchtower_bits, ^itwatchtower_spoken_grew, ^itwatchtower_helped_grew) = 1) { ~chatplayer("<p,happy>I've come to knock your teeth out!"); ~chatnpc("<p,angry>You shut your face! I smack you till you dead and sorry!"); ~npc_retaliate(0); } else if(%itwatchtower >= ^itwatchtower_given_fingernails) { ~chatplayer("<p,happy>Hello!"); ~chatnpc("<p,shifty>You know who I is?"); switch_int(~p_choice2("A big, ugly creature.", 1, "I don't know who you are.", 2)) { case 1 : ~chatplayer("<p,happy>A big, ugly creature."); ~chatnpc("<p,angry>I hit you!"); ~damage_self(12); case 2 : ~chatplayer("<p,bored>I don't know who you are."); ~chatnpc("<p,angry>I am Gorad, and you are tiny.|Go now and I won't chase you!"); } } else { mes("Gorad is busy; try again later."); } [ai_queue3,gorad] gosub(npc_death); if (npc_findhero = ^false) { return; } if(%itwatchtower < ^itwatchtower_given_relic) queue(defeat_gorad, 0); obj_add(npc_coord, npc_param(death_drop), 1, ^lootdrop_duration); [queue,defeat_gorad] if(inv_freespace(inv) = 0 | ~obj_gettotal(ogretooth) > 0) return; mes("Gorad has gone."); inv_add(inv, ogretooth, 1); ~objbox(ogretooth, "He's dropped a tooth; I'll keep that!", 250, 0, divide(^objbox_height, 2));
411
0.669119
1
0.669119
game-dev
MEDIA
0.839772
game-dev
0.796871
1
0.796871
BeanCheeseBurrito/Flecs.NET
59,767
src/Flecs.NET/Generated/System_/System.Entity/T12.g.cs
// /_/src/Flecs.NET/Generated/System_/System.Entity/T12.g.cs // File was auto-generated by /_/src/Flecs.NET.Codegen/Generators/System_.cs using System; using static Flecs.NET.Bindings.flecs; namespace Flecs.NET.Core; public unsafe partial struct System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> { /// <inheritdoc cref="Entity.IsValid()"/> public bool IsValid() { return Entity.IsValid(); } /// <inheritdoc cref="Entity.IsAlive()"/> public bool IsAlive() { return Entity.IsAlive(); } /// <inheritdoc cref="Entity.Name()"/> public string Name() { return Entity.Name(); } /// <inheritdoc cref="Entity.Symbol()"/> public string Symbol() { return Entity.Symbol(); } /// <inheritdoc cref="Entity.Path(string, string)"/> public string Path(string sep = Ecs.DefaultSeparator, string initSep = Ecs.DefaultSeparator) { return Entity.Path(sep, initSep); } /// <inheritdoc cref="Entity.PathFrom(ulong, string, string)"/> public string PathFrom(ulong parent, string sep = Ecs.DefaultSeparator, string initSep = Ecs.DefaultSeparator) { return Entity.PathFrom(parent, sep, initSep); } /// <inheritdoc cref="Entity.PathFrom{TParent}(string, string)"/> public string PathFrom<TParent>(string sep = Ecs.DefaultSeparator, string initSep = Ecs.DefaultSeparator) { return Entity.PathFrom<TParent>(sep, initSep); } /// <inheritdoc cref="Entity.Enabled()"/> public bool Enabled() { return Entity.Enabled(); } /// <inheritdoc cref="Entity.Enabled(ulong)"/> public bool Enabled(ulong id) { return Entity.Enabled(id); } /// <inheritdoc cref="Entity.Enabled(ulong, ulong)"/> public bool Enabled(ulong first, ulong second) { return Entity.Enabled(first, second); } /// <inheritdoc cref="Entity.Enabled{T}()"/> public bool Enabled<T>() { return Entity.Enabled<T>(); } /// <inheritdoc cref="Entity.Enabled{T}(T)"/> public bool Enabled<T>(T value) where T : Enum { return Entity.Enabled(value); } /// <inheritdoc cref="Entity.Enabled{TFirst}(ulong)"/> public bool Enabled<TFirst>(ulong second) { return Entity.Enabled<TFirst>(second); } /// <inheritdoc cref="Entity.Enabled{TFirst, TSecond}()"/> public bool Enabled<TFirst, TSecond>() { return Entity.Enabled<TFirst, TSecond>(); } /// <inheritdoc cref="Entity.Enabled{TFirst, TSecond}(TSecond)"/> public bool Enabled<TFirst, TSecond>(TSecond second) where TSecond : Enum { return Entity.Enabled<TFirst, TSecond>(second); } /// <inheritdoc cref="Entity.Enabled{TFirst, TSecond}(TFirst)"/> public bool Enabled<TFirst, TSecond>(TFirst first) where TFirst : Enum { return Entity.Enabled<TFirst, TSecond>(first); } /// <inheritdoc cref="Entity.EnabledSecond{TSecond}(ulong)"/> public bool EnabledSecond<TSecond>(ulong first) { return Entity.EnabledSecond<TSecond>(first); } /// <inheritdoc cref="Entity.Type()"/> public FlecsType Type() { return Entity.Type(); } /// <inheritdoc cref="Entity.Table()"/> public Table Table() { return Entity.Table(); } /// <inheritdoc cref="Entity.Range()"/> public Table Range() { return Entity.Range(); } /// <inheritdoc cref="Entity.Each(Ecs.EachIdCallback)"/> public void Each(Ecs.EachIdCallback func) { Entity.Each(func); } /// <inheritdoc cref="Entity.Each(ulong, ulong, Ecs.EachIdCallback)"/> public void Each(ulong first, ulong second, Ecs.EachIdCallback func) { Entity.Each(first, second, func); } /// <inheritdoc cref="Entity.Each(ulong, Ecs.EachEntityCallback)"/> public void Each(ulong relation, Ecs.EachEntityCallback func) { Entity.Each(relation, func); } /// <inheritdoc cref="Entity.Each{TFirst}(Ecs.EachEntityCallback)"/> public void Each<TFirst>(Ecs.EachEntityCallback func) { Entity.Each<TFirst>(func); } /// <inheritdoc cref="Entity.Each{TFirst}(TFirst, Ecs.EachEntityCallback)"/> public void Each<TFirst>(TFirst relation, Ecs.EachEntityCallback callback) where TFirst : Enum { Entity.Each(relation, callback); } /// <inheritdoc cref="Entity.Children(ulong, Ecs.EachEntityCallback)"/> public void Children(ulong relation, Ecs.EachEntityCallback callback) { Entity.Children(relation, callback); } /// <inheritdoc cref="Entity.Children{TRel}(Ecs.EachEntityCallback)"/> public void Children<TRel>(Ecs.EachEntityCallback callback) { Entity.Children<TRel>(callback); } /// <inheritdoc cref="Entity.Children{TFirst}(TFirst, Ecs.EachEntityCallback)"/> public void Children<TFirst>(TFirst relation, Ecs.EachEntityCallback callback) where TFirst : Enum { Entity.Children(relation, callback); } /// <inheritdoc cref="Entity.Children(Ecs.EachEntityCallback)"/> public void Children(Ecs.EachEntityCallback callback) { Entity.Children(callback); } /// <inheritdoc cref="Entity.GetPtr(ulong)"/> public void* GetPtr(ulong compId) { return Entity.GetPtr(compId); } /// <inheritdoc cref="Entity.GetPtr(ulong, ulong)"/> public void* GetPtr(ulong first, ulong second) { return Entity.GetPtr(first, second); } /// <inheritdoc cref="Entity.GetPtr{T}()"/> public T* GetPtr<T>() where T : unmanaged { return Entity.GetPtr<T>(); } /// <inheritdoc cref="Entity.GetPtr{TFirst}(ulong)"/> public TFirst* GetPtr<TFirst>(ulong second) where TFirst : unmanaged { return Entity.GetPtr<TFirst>(second); } /// <inheritdoc cref="Entity.GetPtr{TFirst, TSecond}(TSecond)"/> public TFirst* GetPtr<TFirst, TSecond>(TSecond second) where TFirst : unmanaged where TSecond : Enum { return Entity.GetPtr<TFirst, TSecond>(second); } /// <inheritdoc cref="Entity.GetPtr{TFirst, TSecond}(TFirst)"/> public TSecond* GetPtr<TFirst, TSecond>(TFirst first) where TFirst : Enum where TSecond : unmanaged { return Entity.GetPtr<TFirst, TSecond>(first); } /// <inheritdoc cref="Entity.GetFirstPtr{TFirst, TSecond}()"/> public TFirst* GetFirstPtr<TFirst, TSecond>() where TFirst : unmanaged { return Entity.GetFirstPtr<TFirst, TSecond>(); } /// <inheritdoc cref="Entity.GetSecondPtr{TFirst, TSecond}()"/> public TSecond* GetSecondPtr<TFirst, TSecond>() where TSecond : unmanaged { return Entity.GetSecondPtr<TFirst, TSecond>(); } /// <inheritdoc cref="Entity.GetSecondPtr{TSecond}(ulong)"/> public TSecond* GetSecondPtr<TSecond>(ulong first) where TSecond : unmanaged { return Entity.GetSecondPtr<TSecond>(first); } /// <inheritdoc cref="Entity.Get{T}()"/> public ref readonly T Get<T>() { return ref Entity.Get<T>(); } /// <inheritdoc cref="Entity.Get{TFirst}(ulong)"/> public ref readonly TFirst Get<TFirst>(ulong second) { return ref Entity.Get<TFirst>(second); } /// <inheritdoc cref="Entity.Get{TFirst, TSecond}(TSecond)"/> public ref readonly TFirst Get<TFirst, TSecond>(TSecond second) where TSecond : Enum { return ref Entity.Get<TFirst, TSecond>(second); } /// <inheritdoc cref="Entity.Get{TFirst, TSecond}(TFirst)"/> public ref readonly TSecond Get<TFirst, TSecond>(TFirst first) where TFirst : Enum { return ref Entity.Get<TFirst, TSecond>(first); } /// <inheritdoc cref="Entity.GetFirst{TFirst, TSecond}()"/> public ref readonly TFirst GetFirst<TFirst, TSecond>() { return ref Entity.GetFirst<TFirst, TSecond>(); } /// <inheritdoc cref="Entity.GetSecond{TFirst, TSecond}()"/> public ref readonly TSecond GetSecond<TFirst, TSecond>() { return ref Entity.GetSecond<TFirst, TSecond>(); } /// <inheritdoc cref="Entity.GetSecond{TSecond}(ulong)"/> public ref readonly TSecond GetSecond<TSecond>(ulong first) { return ref Entity.GetSecond<TSecond>(first); } /// <inheritdoc cref="Entity.GetMutPtr(ulong)"/> public void* GetMutPtr(ulong id) { return Entity.GetMutPtr(id); } /// <inheritdoc cref="Entity.GetMutPtr(ulong, ulong)"/> public void* GetMutPtr(ulong first, ulong second) { return Entity.GetMutPtr(first, second); } /// <inheritdoc cref="Entity.GetMutPtr{T}()"/> public T* GetMutPtr<T>() where T : unmanaged { return Entity.GetMutPtr<T>(); } /// <inheritdoc cref="Entity.GetMutPtr{TFirst}(ulong)"/> public TFirst* GetMutPtr<TFirst>(ulong second) where TFirst : unmanaged { return Entity.GetMutPtr<TFirst>(second); } /// <inheritdoc cref="Entity.GetMutPtr{TFirst, TSecond}(TSecond)"/> public TFirst* GetMutPtr<TFirst, TSecond>(TSecond second) where TFirst : unmanaged where TSecond : Enum { return Entity.GetMutPtr<TFirst, TSecond>(second); } /// <inheritdoc cref="Entity.GetMutPtr{TFirst, TSecond}(TFirst)"/> public TSecond* GetMutPtr<TFirst, TSecond>(TFirst first) where TFirst : Enum where TSecond : unmanaged { return Entity.GetMutPtr<TFirst, TSecond>(first); } /// <inheritdoc cref="Entity.GetMutFirstPtr{TFirst, TSecond}()"/> public TFirst* GetMutFirstPtr<TFirst, TSecond>() where TFirst : unmanaged { return Entity.GetMutFirstPtr<TFirst, TSecond>(); } /// <inheritdoc cref="Entity.GetMutSecondPtr{TFirst, TSecond}()"/> public TSecond* GetMutSecondPtr<TFirst, TSecond>() where TSecond : unmanaged { return Entity.GetMutSecondPtr<TFirst, TSecond>(); } /// <inheritdoc cref="Entity.GetMutSecondPtr{TSecond}(ulong)"/> public TSecond* GetMutSecondPtr<TSecond>(ulong first) where TSecond : unmanaged { return Entity.GetMutSecondPtr<TSecond>(first); } /// <inheritdoc cref="Entity.GetMut{T}()"/> public ref T GetMut<T>() { return ref Entity.GetMut<T>(); } /// <inheritdoc cref="Entity.GetMut{TFirst}(ulong)"/> public ref TFirst GetMut<TFirst>(ulong second) { return ref Entity.GetMut<TFirst>(second); } /// <inheritdoc cref="Entity.GetMut{TFirst, TSecond}(TSecond)"/> public ref TFirst GetMut<TFirst, TSecond>(TSecond second) where TSecond : Enum { return ref Entity.GetMut<TFirst, TSecond>(second); } /// <inheritdoc cref="Entity.GetMut{TFirst, TSecond}(TFirst)"/> public ref TSecond GetMut<TFirst, TSecond>(TFirst first) where TFirst : Enum { return ref Entity.GetMut<TFirst, TSecond>(first); } /// <inheritdoc cref="Entity.GetMutFirst{TFirst, TSecond}()"/> public ref TFirst GetMutFirst<TFirst, TSecond>() { return ref Entity.GetMutFirst<TFirst, TSecond>(); } /// <inheritdoc cref="Entity.GetMutSecond{TFirst, TSecond}()"/> public ref TSecond GetMutSecond<TFirst, TSecond>() { return ref Entity.GetMutSecond<TFirst, TSecond>(); } /// <inheritdoc cref="Entity.GetMutSecond{TSecond}(ulong)"/> public ref TSecond GetMutSecond<TSecond>(ulong first) { return ref Entity.GetMutSecond<TSecond>(first); } /// <inheritdoc cref="Entity.Target(ulong, int)"/> public Entity Target(ulong relation, int index = 0) { return Entity.Target(relation, index); } /// <inheritdoc cref="Entity.Target{T}(int)"/> public Entity Target<T>(int index = 0) { return Entity.Target<T>(index); } /// <inheritdoc cref="Entity.TargetFor(ulong, ulong)"/> public Entity TargetFor(ulong relation, ulong id) { return Entity.TargetFor(relation, id); } /// <inheritdoc cref="Entity.TargetFor{T}(ulong)"/> public Entity TargetFor<T>(ulong relation) { return Entity.TargetFor<T>(relation); } /// <inheritdoc cref="Entity.TargetFor{TFirst, TSecond}(ulong)"/> public Entity TargetFor<TFirst, TSecond>(ulong relation) { return Entity.TargetFor<TFirst, TSecond>(relation); } /// <inheritdoc cref="Entity.Depth(ulong)"/> public int Depth(ulong rel) { return Entity.Depth(rel); } /// <inheritdoc cref="Entity.Depth{T}()"/> public int Depth<T>() { return Entity.Depth<T>(); } /// <inheritdoc cref="Entity.Depth{T}(T)"/> public int Depth<T>(T value) where T : Enum { return Entity.Depth(value); } /// <inheritdoc cref="Entity.Parent()"/> public Entity Parent() { return Entity.Parent(); } /// <inheritdoc cref="Entity.Lookup(string, bool)"/> public Entity Lookup(string path, bool recursive = false) { return Entity.Lookup(path, recursive); } /// <inheritdoc cref="Entity.TryLookup(string, out Core.Entity)"/> public bool TryLookup(string path, out Entity entity) { return Entity.TryLookup(path, out entity); } /// <inheritdoc cref="Entity.TryLookup(string, bool, out Core.Entity)"/> public bool TryLookup(string path, bool recursive, out Entity entity) { return Entity.TryLookup(path, recursive, out entity); } /// <inheritdoc cref="Entity.TryLookup(string, out ulong)"/> public bool TryLookup(string path, out ulong entity) { return Entity.TryLookup(path, out entity); } /// <inheritdoc cref="Entity.TryLookup(string, bool, out ulong)"/> public bool TryLookup(string path, bool recursive, out ulong entity) { return Entity.TryLookup(path, recursive, out entity); } /// <inheritdoc cref="Entity.Has(ulong)"/> public bool Has(ulong id) { return Entity.Has(id); } /// <inheritdoc cref="Entity.Has(ulong, ulong)"/> public bool Has(ulong first, ulong second) { return Entity.Has(first, second); } /// <inheritdoc cref="Entity.Has{T}()"/> public bool Has<T>() { return Entity.Has<T>(); } /// <inheritdoc cref="Entity.Has{T}(T)"/> public bool Has<T>(T value) where T : Enum { return Entity.Has(value); } /// <inheritdoc cref="Entity.Has{TFirst}(ulong)"/> public bool Has<TFirst>(ulong second) { return Entity.Has<TFirst>(second); } /// <inheritdoc cref="Entity.Has{TFirst, TSecond}()"/> public bool Has<TFirst, TSecond>() { return Entity.Has<TFirst, TSecond>(); } /// <inheritdoc cref="Entity.Has{TFirst, TSecond}(TSecond)"/> public bool Has<TFirst, TSecond>(TSecond second) where TSecond : Enum { return Entity.Has<TFirst, TSecond>(second); } /// <inheritdoc cref="Entity.Has{TFirst, TSecond}(TFirst)"/> public bool Has<TFirst, TSecond>(TFirst first) where TFirst : Enum { return Entity.Has<TFirst, TSecond>(first); } /// <inheritdoc cref="Entity.HasSecond{TSecond}(ulong)"/> public bool HasSecond<TSecond>(ulong first) { return Entity.HasSecond<TSecond>(first); } /// <inheritdoc cref="Entity.Owns(ulong)"/> public bool Owns(ulong id) { return Entity.Owns(id); } /// <inheritdoc cref="Entity.Owns(ulong, ulong)"/> public bool Owns(ulong first, ulong second) { return Entity.Owns(first, second); } /// <inheritdoc cref="Entity.Owns{T}()"/> public bool Owns<T>() { return Entity.Owns<T>(); } /// <inheritdoc cref="Entity.Owns{T}(T)"/> public bool Owns<T>(T value) where T : Enum { return Entity.Owns(value); } /// <inheritdoc cref="Entity.Owns{TFirst}(ulong)"/> public bool Owns<TFirst>(ulong second) { return Entity.Owns<TFirst>(second); } /// <inheritdoc cref="Entity.Owns{TFirst, TSecond}()"/> public bool Owns<TFirst, TSecond>() { return Entity.Owns<TFirst, TSecond>(); } /// <inheritdoc cref="Entity.Owns{TFirst, TSecond}(TSecond)"/> public bool Owns<TFirst, TSecond>(TSecond second) where TSecond : Enum { return Entity.Owns<TFirst, TSecond>(second); } /// <inheritdoc cref="Entity.Owns{TFirst, TSecond}(TFirst)"/> public bool Owns<TFirst, TSecond>(TFirst first) where TFirst : Enum { return Entity.Owns<TFirst, TSecond>(first); } /// <inheritdoc cref="Entity.OwnsSecond{TSecond}(ulong)"/> public bool OwnsSecond<TSecond>(ulong first) { return Entity.OwnsSecond<TSecond>(first); } /// <inheritdoc cref="Entity.Clone(bool, ulong)"/> public Entity Clone(bool cloneValue = true, ulong dstId = 0) { return Entity.Clone(cloneValue, dstId); } /// <inheritdoc cref="Entity.Mut(ref Core.World)"/> public Entity Mut(ref World stage) { return Entity.Mut(ref stage); } /// <inheritdoc cref="Entity.Mut(ref Iter)"/> public Entity Mut(ref Iter it) { return Entity.Mut(ref it); } /// <inheritdoc cref="Entity.Mut(ref Core.Entity)"/> public Entity Mut(ref Entity entity) { return Entity.Mut(ref entity); } /// <inheritdoc cref="Entity.Mut(Core.World)"/> public Entity Mut(World stage) { return Entity.Mut(stage); } /// <inheritdoc cref="Entity.Mut(Iter)"/> public Entity Mut(Iter it) { return Entity.Mut(it); } /// <inheritdoc cref="Entity.Mut(Core.Entity)"/> public Entity Mut(Entity entity) { return Entity.Mut(entity); } /// <inheritdoc cref="Entity.ToJson(in EntityToJsonDesc)"/> public string ToJson(in EntityToJsonDesc desc) { return Entity.ToJson(in desc); } /// <inheritdoc cref="Entity.ToJson()"/> public string ToJson() { return Entity.ToJson(); } /// <inheritdoc cref="Entity.DocName()"/> public string DocName() { return Entity.DocName(); } /// <inheritdoc cref="Entity.DocBrief()"/> public string DocBrief() { return Entity.DocBrief(); } /// <inheritdoc cref="Entity.DocDetail()"/> public string DocDetail() { return Entity.DocDetail(); } /// <inheritdoc cref="Entity.DocLink()"/> public string DocLink() { return Entity.DocLink(); } /// <inheritdoc cref="Entity.DocColor()"/> public string DocColor() { return Entity.DocColor(); } /// <inheritdoc cref="Entity.DocUuid()"/> public string DocUuid() { return Entity.DocUuid(); } /// <inheritdoc cref="Entity.AlertCount(ulong)"/> public int AlertCount(ulong alert = 0) { return Entity.AlertCount(alert); } /// <inheritdoc cref="Entity.ToConstant{T}()"/> public T ToConstant<T>() where T : unmanaged, Enum { return Entity.ToConstant<T>(); } /// <inheritdoc cref="Entity.Emit(ulong)"/> public void Emit(ulong eventId) { Entity.Emit(eventId); } /// <inheritdoc cref="Entity.Emit(Core.Entity)"/> public void Emit(Entity eventId) { Entity.Emit(eventId); } /// <inheritdoc cref="Entity.Emit{T}()"/> public void Emit<T>() { Entity.Emit<T>(); } /// <inheritdoc cref="Entity.Emit{T}(T)"/> public void Emit<T>(T payload) where T : unmanaged { Entity.Emit(payload); } /// <inheritdoc cref="Entity.Emit{T}(ref T)"/> public void Emit<T>(ref T payload) { Entity.Emit(ref payload); } /// <inheritdoc cref="Entity.Enqueue(ulong)"/> public void Enqueue(ulong eventId) { Entity.Enqueue(eventId); } /// <inheritdoc cref="Entity.Enqueue(Core.Entity)"/> public void Enqueue(Entity eventId) { Entity.Enqueue(eventId); } /// <inheritdoc cref="Entity.Enqueue{T}()"/> public void Enqueue<T>() { Entity.Enqueue<T>(); } /// <inheritdoc cref="Entity.Enqueue{T}(T)"/> public void Enqueue<T>(T payload) where T : unmanaged { Entity.Enqueue(payload); } /// <inheritdoc cref="Entity.Enqueue{T}(ref T)"/> public void Enqueue<T>(ref T payload) { Entity.Enqueue(ref payload); } /// <inheritdoc cref="Entity.IsChildOf(ulong)"/> public bool IsChildOf(ulong entity) { return Entity.IsChildOf(entity); } /// <inheritdoc cref="Entity.IsChildOf{T}()"/> public bool IsChildOf<T>() { return Entity.IsChildOf<T>(); } /// <inheritdoc cref="Entity.IsChildOf{T}(T)"/> public bool IsChildOf<T>(T value) where T : Enum { return Entity.IsChildOf(value); } /// <inheritdoc cref="Entity.Add(ulong)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Add(ulong id) { Entity.Add(id); return ref this; } /// <inheritdoc cref="Entity.Add(ulong, ulong)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Add(ulong first, ulong second) { Entity.Add(first, second); return ref this; } /// <inheritdoc cref="Entity.Add{T}()"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Add<T>() { Entity.Add<T>(); return ref this; } /// <inheritdoc cref="Entity.Add{TFirst}(ulong)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Add<TFirst>(ulong second) { Entity.Add<TFirst>(second); return ref this; } /// <inheritdoc cref="Entity.Add{T}(T)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Add<T>(T value) where T : Enum { Entity.Add(value); return ref this; } /// <inheritdoc cref="Entity.Add{TFirst, TSecond}()"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Add<TFirst, TSecond>() { Entity.Add<TFirst, TSecond>(); return ref this; } /// <inheritdoc cref="Entity.Add{TFirst, TSecond}(TSecond)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Add<TFirst, TSecond>(TSecond second) where TSecond : Enum { Entity.Add<TFirst, TSecond>(second); return ref this; } /// <inheritdoc cref="Entity.Add{TFirst, TSecond}(TFirst)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Add<TFirst, TSecond>(TFirst first) where TFirst : Enum { Entity.Add<TFirst, TSecond>(first); return ref this; } /// <inheritdoc cref="Entity.AddSecond{TSecond}(ulong)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> AddSecond<TSecond>(ulong first) { Entity.AddSecond<TSecond>(first); return ref this; } /// <inheritdoc cref="Entity.AddIf(bool, ulong)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> AddIf(bool cond, ulong id) { Entity.AddIf(cond, id); return ref this; } /// <inheritdoc cref="Entity.AddIf(bool, ulong, ulong)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> AddIf(bool cond, ulong first, ulong second) { Entity.AddIf(cond, first, second); return ref this; } /// <inheritdoc cref="Entity.AddIf{T}(bool)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> AddIf<T>(bool cond) { Entity.AddIf<T>(cond); return ref this; } /// <inheritdoc cref="Entity.AddIf{T}(bool, T)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> AddIf<T>(bool cond, T value) where T : Enum { Entity.AddIf(cond, value); return ref this; } /// <inheritdoc cref="Entity.AddIf{TFirst}(bool, ulong)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> AddIf<TFirst>(bool cond, ulong second) { Entity.AddIf<TFirst>(cond, second); return ref this; } /// <inheritdoc cref="Entity.AddIf{TFirst, TSecond}(bool)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> AddIf<TFirst, TSecond>(bool cond) { Entity.AddIf<TFirst, TSecond>(cond); return ref this; } /// <inheritdoc cref="Entity.AddIf{TFirst, TSecond}(bool, TSecond)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> AddIf<TFirst, TSecond>(bool cond, TSecond second) where TSecond : Enum { Entity.AddIf<TFirst, TSecond>(cond, second); return ref this; } /// <inheritdoc cref="Entity.AddIf{TFirst, TSecond}(bool, TFirst)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> AddIf<TFirst, TSecond>(bool cond, TFirst first) where TFirst : Enum { Entity.AddIf<TFirst, TSecond>(cond, first); return ref this; } /// <inheritdoc cref="Entity.AddIfSecond{TSecond}(bool, ulong)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> AddIfSecond<TSecond>(bool cond, ulong first) { Entity.AddIfSecond<TSecond>(cond, first); return ref this; } /// <inheritdoc cref="Entity.IsA(ulong)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> IsA(ulong id) { Entity.IsA(id); return ref this; } /// <inheritdoc cref="Entity.IsA{T}()"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> IsA<T>() { Entity.IsA<T>(); return ref this; } /// <inheritdoc cref="Entity.IsA{T}(T)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> IsA<T>(T value) where T : Enum { Entity.IsA(value); return ref this; } /// <inheritdoc cref="Entity.ChildOf(ulong)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> ChildOf(ulong second) { Entity.ChildOf(second); return ref this; } /// <inheritdoc cref="Entity.ChildOf{T}()"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> ChildOf<T>() { Entity.ChildOf<T>(); return ref this; } /// <inheritdoc cref="Entity.ChildOf{T}(T)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> ChildOf<T>(T value) where T : Enum { Entity.ChildOf(value); return ref this; } /// <inheritdoc cref="Entity.DependsOn(ulong)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> DependsOn(ulong second) { Entity.DependsOn(second); return ref this; } /// <inheritdoc cref="Entity.DependsOn{T}()"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> DependsOn<T>() { Entity.DependsOn<T>(); return ref this; } /// <inheritdoc cref="Entity.DependsOn{T}(T)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> DependsOn<T>(T value) where T : Enum { Entity.DependsOn(value); return ref this; } /// <inheritdoc cref="Entity.SlotOf(ulong)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> SlotOf(ulong id) { Entity.SlotOf(id); return ref this; } /// <inheritdoc cref="Entity.SlotOf{T}()"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> SlotOf<T>() { Entity.SlotOf<T>(); return ref this; } /// <inheritdoc cref="Entity.SlotOf{T}(T)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> SlotOf<T>(T value) where T : Enum { Entity.SlotOf(value); return ref this; } /// <inheritdoc cref="Entity.Slot()"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Slot() { Entity.Slot(); return ref this; } /// <inheritdoc cref="Entity.Remove(ulong)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Remove(ulong id) { Entity.Remove(id); return ref this; } /// <inheritdoc cref="Entity.Remove(ulong, ulong)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Remove(ulong first, ulong second) { Entity.Remove(first, second); return ref this; } /// <inheritdoc cref="Entity.Remove{T}()"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Remove<T>() { Entity.Remove<T>(); return ref this; } /// <inheritdoc cref="Entity.Remove{T}(T)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Remove<T>(T value) where T : Enum { Entity.Remove(value); return ref this; } /// <inheritdoc cref="Entity.Remove{TFirst}(ulong)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Remove<TFirst>(ulong second) { Entity.Remove<TFirst>(second); return ref this; } /// <inheritdoc cref="Entity.Remove{TFirst, TSecond}()"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Remove<TFirst, TSecond>() { Entity.Remove<TFirst, TSecond>(); return ref this; } /// <inheritdoc cref="Entity.Remove{TFirst, TSecond}(TSecond)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Remove<TFirst, TSecond>(TSecond second) where TSecond : Enum { Entity.Remove<TFirst, TSecond>(second); return ref this; } /// <inheritdoc cref="Entity.Remove{TFirst, TSecond}(TFirst)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Remove<TFirst, TSecond>(TFirst first) where TFirst : Enum { Entity.Remove<TFirst, TSecond>(first); return ref this; } /// <inheritdoc cref="Entity.RemoveSecond{TSecond}(ulong)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> RemoveSecond<TSecond>(ulong first) { Entity.RemoveSecond<TSecond>(first); return ref this; } /// <inheritdoc cref="Entity.AutoOverride(ulong)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> AutoOverride(ulong id) { Entity.AutoOverride(id); return ref this; } /// <inheritdoc cref="Entity.AutoOverride(ulong, ulong)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> AutoOverride(ulong first, ulong second) { Entity.AutoOverride(first, second); return ref this; } /// <inheritdoc cref="Entity.AutoOverride{T}()"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> AutoOverride<T>() { Entity.AutoOverride<T>(); return ref this; } /// <inheritdoc cref="Entity.AutoOverride{T}(T)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> AutoOverride<T>(T value) where T : Enum { Entity.AutoOverride(value); return ref this; } /// <inheritdoc cref="Entity.AutoOverride{TFirst}(ulong)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> AutoOverride<TFirst>(ulong second) { Entity.AutoOverride<TFirst>(second); return ref this; } /// <inheritdoc cref="Entity.AutoOverride{TFirst, TSecond}()"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> AutoOverride<TFirst, TSecond>() { Entity.AutoOverride<TFirst, TSecond>(); return ref this; } /// <inheritdoc cref="Entity.AutoOverride{TFirst, TSecond}(TSecond)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> AutoOverride<TFirst, TSecond>(TSecond second) where TSecond : Enum { Entity.AutoOverride<TFirst, TSecond>(second); return ref this; } /// <inheritdoc cref="Entity.AutoOverride{TFirst, TSecond}(TFirst)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> AutoOverride<TFirst, TSecond>(TFirst first) where TFirst : Enum { Entity.AutoOverride<TFirst, TSecond>(first); return ref this; } /// <inheritdoc cref="Entity.AutoOverrideSecond{TSecond}(ulong)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> AutoOverrideSecond<TSecond>(ulong first) { Entity.AutoOverrideSecond<TSecond>(first); return ref this; } /// <inheritdoc cref="Entity.SetAutoOverride{T}(in T)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> SetAutoOverride<T>(in T component) { Entity.SetAutoOverride(in component); return ref this; } /// <inheritdoc cref="Entity.SetAutoOverride{TFirst}(ulong, in TFirst)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> SetAutoOverride<TFirst>(ulong second, in TFirst component) { Entity.SetAutoOverride(second, in component); return ref this; } /// <inheritdoc cref="Entity.SetAutoOverride{TFirst, TSecond}(in TFirst)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> SetAutoOverride<TFirst, TSecond>(in TFirst component) { Entity.SetAutoOverride<TFirst, TSecond>(in component); return ref this; } /// <inheritdoc cref="Entity.SetAutoOverride{TFirst, TSecond}(in TSecond)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> SetAutoOverride<TFirst, TSecond>(in TSecond component) { Entity.SetAutoOverride<TFirst, TSecond>(in component); return ref this; } /// <inheritdoc cref="Entity.SetAutoOverride{TFirst, TSecond}(TSecond, in TFirst)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> SetAutoOverride<TFirst, TSecond>(TSecond second, in TFirst component) where TSecond : Enum { Entity.SetAutoOverride<TFirst, TSecond>(second, in component); return ref this; } /// <inheritdoc cref="Entity.SetAutoOverride{TFirst, TSecond}(TFirst, in TSecond)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> SetAutoOverride<TFirst, TSecond>(TFirst first, in TSecond component) where TFirst : Enum { Entity.SetAutoOverride<TFirst, TSecond>(first, in component); return ref this; } /// <inheritdoc cref="Entity.SetAutoOverrideSecond{TSecond}(ulong, in TSecond)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> SetAutoOverrideSecond<TSecond>(ulong first, in TSecond component) { Entity.SetAutoOverrideSecond(first, in component); return ref this; } /// <inheritdoc cref="Entity.Enable()"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Enable() { Entity.Enable(); return ref this; } /// <inheritdoc cref="Entity.Enable(ulong)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Enable(ulong id) { Entity.Enable(id); return ref this; } /// <inheritdoc cref="Entity.Enable(ulong, ulong)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Enable(ulong first, ulong second) { Entity.Enable(first, second); return ref this; } /// <inheritdoc cref="Entity.Enable{T}()"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Enable<T>() { Entity.Enable<T>(); return ref this; } /// <inheritdoc cref="Entity.Enable{T}(T)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Enable<T>(T value) where T : Enum { Entity.Enable(value); return ref this; } /// <inheritdoc cref="Entity.Enable{TFirst}(ulong)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Enable<TFirst>(ulong second) { Entity.Enable<TFirst>(second); return ref this; } /// <inheritdoc cref="Entity.Enable{TFirst, TSecond}()"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Enable<TFirst, TSecond>() { Entity.Enable<TFirst, TSecond>(); return ref this; } /// <inheritdoc cref="Entity.Enable{TFirst, TSecond}(TSecond)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Enable<TFirst, TSecond>(TSecond second) where TSecond : Enum { Entity.Enable<TFirst, TSecond>(second); return ref this; } /// <inheritdoc cref="Entity.Enable{TFirst, TSecond}(TFirst)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Enable<TFirst, TSecond>(TFirst first) where TFirst : Enum { Entity.Enable<TFirst, TSecond>(first); return ref this; } /// <inheritdoc cref="Entity.EnableSecond{TSecond}(ulong)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> EnableSecond<TSecond>(ulong first) { Entity.EnableSecond<TSecond>(first); return ref this; } /// <inheritdoc cref="Entity.Disable()"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Disable() { Entity.Disable(); return ref this; } /// <inheritdoc cref="Entity.Disable(ulong)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Disable(ulong id) { Entity.Disable(id); return ref this; } /// <inheritdoc cref="Entity.Disable(ulong, ulong)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Disable(ulong first, ulong second) { Entity.Disable(first, second); return ref this; } /// <inheritdoc cref="Entity.Disable{T}()"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Disable<T>() { Entity.Disable<T>(); return ref this; } /// <inheritdoc cref="Entity.Disable{T}(T)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Disable<T>(T value) where T : Enum { Entity.Disable(value); return ref this; } /// <inheritdoc cref="Entity.Disable{TFirst}(ulong)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Disable<TFirst>(ulong second) { Entity.Disable<TFirst>(second); return ref this; } /// <inheritdoc cref="Entity.Disable{TFirst, TSecond}()"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Disable<TFirst, TSecond>() { Entity.Disable<TFirst, TSecond>(); return ref this; } /// <inheritdoc cref="Entity.Disable{TFirst, TSecond}(TSecond)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Disable<TFirst, TSecond>(TSecond second) where TSecond : Enum { Entity.Disable<TFirst, TSecond>(second); return ref this; } /// <inheritdoc cref="Entity.Disable{TFirst, TSecond}(TFirst)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Disable<TFirst, TSecond>(TFirst first) where TFirst : Enum { Entity.Disable<TFirst, TSecond>(first); return ref this; } /// <inheritdoc cref="Entity.DisableSecond{TSecond}(ulong)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> DisableSecond<TSecond>(ulong first) { Entity.DisableSecond<TSecond>(first); return ref this; } /// public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> SetUntyped(ulong id, int size, void* data) { Entity.SetUntyped(id, size, data); return ref this; } /// public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> SetUntyped(ulong id, void* data) { Entity.SetUntyped(id, data); return ref this; } /// public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> SetUntyped(ulong first, ulong second, int size, void* data) { Entity.SetUntyped(first, second, size, data); return ref this; } /// <inheritdoc cref="Entity.SetPtr{T}(T*)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> SetPtr<T>(T* data) { Entity.SetPtr(data); return ref this; } /// <inheritdoc cref="Entity.SetPtr{TFirst}(ulong, TFirst*)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> SetPtr<TFirst>(ulong second, TFirst* data) { Entity.SetPtr(second, data); return ref this; } /// <inheritdoc cref="Entity.SetPtr{TFirst, TSecond}(TSecond*)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> SetPtr<TFirst, TSecond>(TSecond* data) { Entity.SetPtr<TFirst, TSecond>(data); return ref this; } /// <inheritdoc cref="Entity.SetPtr{TFirst, TSecond}(TFirst*)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> SetPtr<TFirst, TSecond>(TFirst* data) { Entity.SetPtr<TFirst, TSecond>(data); return ref this; } /// <inheritdoc cref="Entity.SetPtr{TFirst, TSecond}(TSecond, TFirst*)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> SetPtr<TFirst, TSecond>(TSecond second, TFirst* data) where TSecond : Enum { Entity.SetPtr<TFirst, TSecond>(second, data); return ref this; } /// <inheritdoc cref="Entity.SetPtr{TFirst, TSecond}(TFirst, TSecond*)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> SetPtr<TFirst, TSecond>(TFirst first, TSecond* data) where TFirst : Enum { Entity.SetPtr<TFirst, TSecond>(first, data); return ref this; } /// <inheritdoc cref="Entity.SetPtrSecond{TSecond}(ulong, TSecond*)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> SetPtrSecond<TSecond>(ulong first, TSecond* data) { Entity.SetPtrSecond(first, data); return ref this; } /// <inheritdoc cref="Entity.Set{T}(in T)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Set<T>(in T data) { Entity.Set(in data); return ref this; } /// <inheritdoc cref="Entity.Set{TFirst}(ulong, in TFirst)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Set<TFirst>(ulong second, in TFirst data) { Entity.Set(second, in data); return ref this; } /// <inheritdoc cref="Entity.Set{TFirst, TSecond}(in TSecond)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Set<TFirst, TSecond>(in TSecond data) { Entity.Set<TFirst, TSecond>(in data); return ref this; } /// <inheritdoc cref="Entity.Set{TFirst, TSecond}(in TFirst)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Set<TFirst, TSecond>(in TFirst data) { Entity.Set<TFirst, TSecond>(in data); return ref this; } /// <inheritdoc cref="Entity.Set{TFirst, TSecond}(TSecond, in TFirst)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Set<TFirst, TSecond>(TSecond second, in TFirst data) where TSecond : Enum { Entity.Set<TFirst, TSecond>(second, in data); return ref this; } /// <inheritdoc cref="Entity.Set{TFirst, TSecond}(TFirst, in TSecond)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Set<TFirst, TSecond>(TFirst first, in TSecond data) where TFirst : Enum { Entity.Set<TFirst, TSecond>(first, in data); return ref this; } /// <inheritdoc cref="Entity.SetSecond{TSecond}(ulong, in TSecond)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> SetSecond<TSecond>(ulong first, in TSecond data) { Entity.SetSecond(first, in data); return ref this; } /// <inheritdoc cref="Entity.With(Action)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> With(Action callback) { Entity.With(callback); return ref this; } /// <inheritdoc cref="Entity.With(ulong, Action)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> With(ulong first, Action callback) { Entity.With(first, callback); return ref this; } /// <inheritdoc cref="Entity.With{TFirst}(Action)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> With<TFirst>(Action callback) { Entity.With<TFirst>(callback); return ref this; } /// <inheritdoc cref="Entity.With(Ecs.WorldCallback)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> With(Ecs.WorldCallback callback) { Entity.With(callback); return ref this; } /// <inheritdoc cref="Entity.With(ulong, Ecs.WorldCallback)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> With(ulong first, Ecs.WorldCallback callback) { Entity.With(first, callback); return ref this; } /// <inheritdoc cref="Entity.With{TFirst}(Ecs.WorldCallback)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> With<TFirst>(Ecs.WorldCallback callback) { Entity.With<TFirst>(callback); return ref this; } /// <inheritdoc cref="Entity.Scope(Action)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Scope(Action callback) { Entity.Scope(callback); return ref this; } /// <inheritdoc cref="Entity.Scope(Ecs.WorldCallback)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Scope(Ecs.WorldCallback callback) { Entity.Scope(callback); return ref this; } /// <inheritdoc cref="Entity.SetName(string)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> SetName(string name) { Entity.SetName(name); return ref this; } /// <inheritdoc cref="Entity.SetAlias(string)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> SetAlias(string alias) { Entity.SetAlias(alias); return ref this; } /// <inheritdoc cref="Entity.SetDocName(string)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> SetDocName(string name) { Entity.SetDocName(name); return ref this; } /// <inheritdoc cref="Entity.SetDocBrief(string)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> SetDocBrief(string brief) { Entity.SetDocBrief(brief); return ref this; } /// <inheritdoc cref="Entity.SetDocDetail(string)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> SetDocDetail(string detail) { Entity.SetDocDetail(detail); return ref this; } /// <inheritdoc cref="Entity.SetDocLink(string)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> SetDocLink(string link) { Entity.SetDocLink(link); return ref this; } /// <inheritdoc cref="Entity.SetDocColor(string)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> SetDocColor(string color) { Entity.SetDocColor(color); return ref this; } /// <inheritdoc cref="Entity.SetDocUuid(string)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> SetDocUuid(string uuid) { Entity.SetDocUuid(uuid); return ref this; } /// <inheritdoc cref="Entity.Unit(string, ulong, ulong, ulong, int, int)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Unit( string symbol, ulong prefix = 0, ulong @base = 0, ulong over = 0, int factor = 0, int power = 0) { Entity.Unit(symbol, prefix, @base, over, factor, power); return ref this; } /// <inheritdoc cref="Entity.Unit(ulong, ulong, ulong, int, int)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Unit( ulong prefix = 0, ulong @base = 0, ulong over = 0, int factor = 0, int power = 0) { Entity.Unit(prefix, @base, over, factor, power); return ref this; } /// <inheritdoc cref="Entity.UnitPrefix(string, int, int)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> UnitPrefix(string symbol, int factor = 0, int power = 0) { Entity.UnitPrefix(symbol, factor, power); return ref this; } /// <inheritdoc cref="Entity.Quantity(ulong)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Quantity(ulong quantity) { Entity.Quantity(quantity); return ref this; } /// <inheritdoc cref="Entity.Quantity{T}()"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Quantity<T>() { Entity.Quantity<T>(); return ref this; } /// <inheritdoc cref="Entity.Quantity()"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Quantity() { Entity.Quantity(); return ref this; } /// <inheritdoc cref="Entity.SetJson(ulong, string, ecs_from_json_desc_t*)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> SetJson(ulong e, string json, ecs_from_json_desc_t* desc = null) { Entity.SetJson(e, json, desc); return ref this; } /// <inheritdoc cref="Entity.SetJson(ulong, ulong, string, ecs_from_json_desc_t*)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> SetJson(ulong first, ulong second, string json, ecs_from_json_desc_t* desc = null) { Entity.SetJson(first, second, json, desc); return ref this; } /// <inheritdoc cref="Entity.SetJson{T}(string, ecs_from_json_desc_t*)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> SetJson<T>(string json, ecs_from_json_desc_t* desc = null) { Entity.SetJson<T>(json, desc); return ref this; } /// <inheritdoc cref="Entity.SetJson{TFirst}(ulong, string, ecs_from_json_desc_t*)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> SetJson<TFirst>(ulong second, string json, ecs_from_json_desc_t* desc = null) { Entity.SetJson<TFirst>(second, json, desc); return ref this; } /// <inheritdoc cref="Entity.SetJson{TFirst, TSecond}(string, ecs_from_json_desc_t*)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> SetJson<TFirst, TSecond>(string json, ecs_from_json_desc_t* desc = null) { Entity.SetJson<TFirst, TSecond>(json, desc); return ref this; } /// <inheritdoc cref="Entity.SetJson{TFirst, TSecond}(TSecond, string, ecs_from_json_desc_t*)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> SetJson<TFirst, TSecond>(TSecond second, string json, ecs_from_json_desc_t* desc = null) where TSecond : Enum { Entity.SetJson<TFirst, TSecond>(second, json, desc); return ref this; } /// <inheritdoc cref="Entity.SetJson{TFirst, TSecond}(TFirst, string, ecs_from_json_desc_t*)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> SetJson<TFirst, TSecond>(TFirst first, string json, ecs_from_json_desc_t* desc = null) where TFirst : Enum { Entity.SetJson<TFirst, TSecond>(first, json, desc); return ref this; } /// <inheritdoc cref="Entity.SetJsonSecond{TSecond}(ulong, string, ecs_from_json_desc_t*)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> SetJsonSecond<TSecond>(ulong first, string json, ecs_from_json_desc_t* desc = null) { Entity.SetJsonSecond<TSecond>(first, json, desc); return ref this; } /// <inheritdoc cref="Entity.Observe(ulong, Action)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Observe(ulong eventId, Action callback) { Entity.Observe(eventId, callback); return ref this; } /// <inheritdoc cref="Entity.Observe(ulong, Ecs.ObserveEntityCallback)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Observe(ulong eventId, Ecs.ObserveEntityCallback callback) { Entity.Observe(eventId, callback); return ref this; } /// <inheritdoc cref="Entity.Observe{T}(Action)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Observe<T>(Action callback) { Entity.Observe<T>(callback); return ref this; } /// <inheritdoc cref="Entity.Observe{T}(Ecs.ObserveEntityCallback)"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Observe<T>(Ecs.ObserveEntityCallback callback) { Entity.Observe<T>(callback); return ref this; } /// <inheritdoc cref="Entity.Observe{T}(Ecs.ObserveRefCallback{T})"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Observe<T>(Ecs.ObserveRefCallback<T> callback) { Entity.Observe(callback); return ref this; } /// <inheritdoc cref="Entity.Observe{T}(Ecs.ObserveEntityRefCallback{T})"/> public ref System<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Observe<T>(Ecs.ObserveEntityRefCallback<T> callback) { Entity.Observe(callback); return ref this; } /// <inheritdoc cref="Entity.EnsurePtr(ulong)"/> public void* EnsurePtr(ulong id) { return Entity.EnsurePtr(id); } /// <inheritdoc cref="Entity.EnsurePtr(ulong, ulong)"/> public void* EnsurePtr(ulong first, ulong second) { return Entity.EnsurePtr(first, second); } /// <inheritdoc cref="Entity.EnsurePtr{T}()"/> public T* EnsurePtr<T>() where T : unmanaged { return Entity.EnsurePtr<T>(); } /// <inheritdoc cref="Entity.EnsurePtr{TFirst}(ulong)"/> public TFirst* EnsurePtr<TFirst>(ulong second) where TFirst : unmanaged { return Entity.EnsurePtr<TFirst>(second); } /// <inheritdoc cref="Entity.EnsurePtr{TFirst, TSecond}(TSecond)"/> public TFirst* EnsurePtr<TFirst, TSecond>(TSecond second) where TFirst : unmanaged where TSecond : Enum { return Entity.EnsurePtr<TFirst, TSecond>(second); } /// <inheritdoc cref="Entity.EnsurePtr{TFirst, TSecond}(TFirst)"/> public TSecond* EnsurePtr<TFirst, TSecond>(TFirst first) where TFirst : Enum where TSecond : unmanaged { return Entity.EnsurePtr<TFirst, TSecond>(first); } /// <inheritdoc cref="Entity.EnsureFirstPtr{TFirst, TSecond}()"/> public TFirst* EnsureFirstPtr<TFirst, TSecond>() where TFirst : unmanaged { return Entity.EnsureFirstPtr<TFirst, TSecond>(); } /// <inheritdoc cref="Entity.EnsureSecondPtr{TFirst, TSecond}()"/> public TSecond* EnsureSecondPtr<TFirst, TSecond>() where TSecond : unmanaged { return Entity.EnsureSecondPtr<TFirst, TSecond>(); } /// <inheritdoc cref="Entity.EnsureSecondPtr{TSecond}(ulong)"/> public TSecond* EnsureSecondPtr<TSecond>(ulong first) where TSecond : unmanaged { return Entity.EnsureSecondPtr<TSecond>(first); } /// <inheritdoc cref="Entity.Ensure{T}()"/> public ref T Ensure<T>() { return ref Entity.Ensure<T>(); } /// <inheritdoc cref="Entity.Ensure{TFirst}(ulong)"/> public ref TFirst Ensure<TFirst>(ulong second) { return ref Entity.Ensure<TFirst>(second); } /// <inheritdoc cref="Entity.Ensure{TFirst, TSecond}(TSecond)"/> public ref TFirst Ensure<TFirst, TSecond>(TSecond second) where TSecond : Enum { return ref Entity.Ensure<TFirst, TSecond>(second); } /// <inheritdoc cref="Entity.Ensure{TFirst, TSecond}(TFirst)"/> public ref TSecond Ensure<TFirst, TSecond>(TFirst first) where TFirst : Enum { return ref Entity.Ensure<TFirst, TSecond>(first); } /// <inheritdoc cref="Entity.EnsureFirst{TFirst, TSecond}()"/> public ref TFirst EnsureFirst<TFirst, TSecond>() { return ref Entity.EnsureFirst<TFirst, TSecond>(); } /// <inheritdoc cref="Entity.EnsureSecond{TFirst, TSecond}()"/> public ref TSecond EnsureSecond<TFirst, TSecond>() { return ref Entity.EnsureSecond<TFirst, TSecond>(); } /// <inheritdoc cref="Entity.EnsureSecond{TSecond}(ulong)"/> public ref TSecond EnsureSecond<TSecond>(ulong first) { return ref Entity.EnsureSecond<TSecond>(first); } /// <inheritdoc cref="Entity.Modified(ulong)"/> public void Modified(ulong id) { Entity.Modified(id); } /// <inheritdoc cref="Entity.Modified(ulong, ulong)"/> public void Modified(ulong first, ulong second) { Entity.Modified(first, second); } /// <inheritdoc cref="Entity.Modified{T}()"/> public void Modified<T>() { Entity.Modified<T>(); } /// <inheritdoc cref="Entity.Modified{T}(T)"/> public void Modified<T>(T value) where T : Enum { Entity.Modified(value); } /// <inheritdoc cref="Entity.Modified{TFirst}(ulong)"/> public void Modified<TFirst>(ulong second) { Entity.Modified<TFirst>(second); } /// <inheritdoc cref="Entity.Modified{TFirst, TSecond}()"/> public void Modified<TFirst, TSecond>() { Entity.Modified<TFirst, TSecond>(); } /// <inheritdoc cref="Entity.Modified{TFirst, TSecond}(TSecond)"/> public void Modified<TFirst, TSecond>(TSecond second) where TSecond : Enum { Entity.Modified<TFirst, TSecond>(second); } /// <inheritdoc cref="Entity.Modified{TFirst, TSecond}(TFirst)"/> public void Modified<TFirst, TSecond>(TFirst first) where TFirst : Enum { Entity.Modified<TFirst, TSecond>(first); } /// <inheritdoc cref="Entity.ModifiedSecond{TSecond}(ulong)"/> public void ModifiedSecond<TSecond>(ulong first) { Entity.ModifiedSecond<TSecond>(first); } /// <inheritdoc cref="Entity.GetRef{T}()"/> public Ref<T> GetRef<T>() { return Entity.GetRef<T>(); } /// <inheritdoc cref="Entity.GetRef{TFirst}(ulong)"/> public Ref<TFirst> GetRef<TFirst>(ulong second) { return Entity.GetRef<TFirst>(second); } /// <inheritdoc cref="Entity.GetRef{TFirst, TSecond}(TSecond)"/> public Ref<TFirst> GetRef<TFirst, TSecond>(TSecond second) where TSecond : Enum { return Entity.GetRef<TFirst, TSecond>(second); } /// <inheritdoc cref="Entity.GetRef{TFirst, TSecond}(TFirst)"/> public Ref<TSecond> GetRef<TFirst, TSecond>(TFirst first) where TFirst : Enum { return Entity.GetRef<TFirst, TSecond>(first); } /// <inheritdoc cref="Entity.GetRefFirst{TFirst, TSecond}()"/> public Ref<TFirst> GetRefFirst<TFirst, TSecond>() { return Entity.GetRefFirst<TFirst, TSecond>(); } /// <inheritdoc cref="Entity.GetRefSecond{TFirst, TSecond}()"/> public Ref<TSecond> GetRefSecond<TFirst, TSecond>() { return Entity.GetRefSecond<TFirst, TSecond>(); } /// <inheritdoc cref="Entity.GetRefSecond{TSecond}(ulong)"/> public Ref<TSecond> GetRefSecond<TSecond>(ulong first) { return Entity.GetRefSecond<TSecond>(first); } /// <inheritdoc cref="Entity.Clear()"/> public void Clear() { Entity.Clear(); } /// <inheritdoc cref="Entity.Destruct()"/> public void Destruct() { Entity.Destruct(); } /// <inheritdoc cref="Entity.FromJson(string)"/> public string FromJson(string json) { return Entity.FromJson(json); } }
411
0.768031
1
0.768031
game-dev
MEDIA
0.776555
game-dev
0.813049
1
0.813049
mintme-com/webchaind
3,109
crypto/bn256/cloudflare/mul_amd64.h
#define mul(a0,a1,a2,a3, rb, stack) \ MOVQ a0, AX \ MULQ 0+rb \ MOVQ AX, R8 \ MOVQ DX, R9 \ MOVQ a0, AX \ MULQ 8+rb \ ADDQ AX, R9 \ ADCQ $0, DX \ MOVQ DX, R10 \ MOVQ a0, AX \ MULQ 16+rb \ ADDQ AX, R10 \ ADCQ $0, DX \ MOVQ DX, R11 \ MOVQ a0, AX \ MULQ 24+rb \ ADDQ AX, R11 \ ADCQ $0, DX \ MOVQ DX, R12 \ \ storeBlock(R8,R9,R10,R11, 0+stack) \ MOVQ R12, 32+stack \ \ MOVQ a1, AX \ MULQ 0+rb \ MOVQ AX, R8 \ MOVQ DX, R9 \ MOVQ a1, AX \ MULQ 8+rb \ ADDQ AX, R9 \ ADCQ $0, DX \ MOVQ DX, R10 \ MOVQ a1, AX \ MULQ 16+rb \ ADDQ AX, R10 \ ADCQ $0, DX \ MOVQ DX, R11 \ MOVQ a1, AX \ MULQ 24+rb \ ADDQ AX, R11 \ ADCQ $0, DX \ MOVQ DX, R12 \ \ ADDQ 8+stack, R8 \ ADCQ 16+stack, R9 \ ADCQ 24+stack, R10 \ ADCQ 32+stack, R11 \ ADCQ $0, R12 \ storeBlock(R8,R9,R10,R11, 8+stack) \ MOVQ R12, 40+stack \ \ MOVQ a2, AX \ MULQ 0+rb \ MOVQ AX, R8 \ MOVQ DX, R9 \ MOVQ a2, AX \ MULQ 8+rb \ ADDQ AX, R9 \ ADCQ $0, DX \ MOVQ DX, R10 \ MOVQ a2, AX \ MULQ 16+rb \ ADDQ AX, R10 \ ADCQ $0, DX \ MOVQ DX, R11 \ MOVQ a2, AX \ MULQ 24+rb \ ADDQ AX, R11 \ ADCQ $0, DX \ MOVQ DX, R12 \ \ ADDQ 16+stack, R8 \ ADCQ 24+stack, R9 \ ADCQ 32+stack, R10 \ ADCQ 40+stack, R11 \ ADCQ $0, R12 \ storeBlock(R8,R9,R10,R11, 16+stack) \ MOVQ R12, 48+stack \ \ MOVQ a3, AX \ MULQ 0+rb \ MOVQ AX, R8 \ MOVQ DX, R9 \ MOVQ a3, AX \ MULQ 8+rb \ ADDQ AX, R9 \ ADCQ $0, DX \ MOVQ DX, R10 \ MOVQ a3, AX \ MULQ 16+rb \ ADDQ AX, R10 \ ADCQ $0, DX \ MOVQ DX, R11 \ MOVQ a3, AX \ MULQ 24+rb \ ADDQ AX, R11 \ ADCQ $0, DX \ MOVQ DX, R12 \ \ ADDQ 24+stack, R8 \ ADCQ 32+stack, R9 \ ADCQ 40+stack, R10 \ ADCQ 48+stack, R11 \ ADCQ $0, R12 \ storeBlock(R8,R9,R10,R11, 24+stack) \ MOVQ R12, 56+stack #define gfpReduce(stack) \ \ // m = (T * N') mod R, store m in R8:R9:R10:R11 MOVQ ·np+0(SB), AX \ MULQ 0+stack \ MOVQ AX, R8 \ MOVQ DX, R9 \ MOVQ ·np+0(SB), AX \ MULQ 8+stack \ ADDQ AX, R9 \ ADCQ $0, DX \ MOVQ DX, R10 \ MOVQ ·np+0(SB), AX \ MULQ 16+stack \ ADDQ AX, R10 \ ADCQ $0, DX \ MOVQ DX, R11 \ MOVQ ·np+0(SB), AX \ MULQ 24+stack \ ADDQ AX, R11 \ \ MOVQ ·np+8(SB), AX \ MULQ 0+stack \ MOVQ AX, R12 \ MOVQ DX, R13 \ MOVQ ·np+8(SB), AX \ MULQ 8+stack \ ADDQ AX, R13 \ ADCQ $0, DX \ MOVQ DX, R14 \ MOVQ ·np+8(SB), AX \ MULQ 16+stack \ ADDQ AX, R14 \ \ ADDQ R12, R9 \ ADCQ R13, R10 \ ADCQ R14, R11 \ \ MOVQ ·np+16(SB), AX \ MULQ 0+stack \ MOVQ AX, R12 \ MOVQ DX, R13 \ MOVQ ·np+16(SB), AX \ MULQ 8+stack \ ADDQ AX, R13 \ \ ADDQ R12, R10 \ ADCQ R13, R11 \ \ MOVQ ·np+24(SB), AX \ MULQ 0+stack \ ADDQ AX, R11 \ \ storeBlock(R8,R9,R10,R11, 64+stack) \ \ \ // m * N mul(·p2+0(SB),·p2+8(SB),·p2+16(SB),·p2+24(SB), 64+stack, 96+stack) \ \ \ // Add the 512-bit intermediate to m*N loadBlock(96+stack, R8,R9,R10,R11) \ loadBlock(128+stack, R12,R13,R14,R15) \ \ MOVQ $0, AX \ ADDQ 0+stack, R8 \ ADCQ 8+stack, R9 \ ADCQ 16+stack, R10 \ ADCQ 24+stack, R11 \ ADCQ 32+stack, R12 \ ADCQ 40+stack, R13 \ ADCQ 48+stack, R14 \ ADCQ 56+stack, R15 \ ADCQ $0, AX \ \ gfpCarry(R12,R13,R14,R15,AX, R8,R9,R10,R11,BX)
411
0.876315
1
0.876315
game-dev
MEDIA
0.261935
game-dev
0.838251
1
0.838251
Despair-Games/poketernity
3,792
src/phases/trainer-victory-phase.ts
import { globalScene } from "#app/global-scene"; import { timedEventManager } from "#app/timed-event-manager"; import { getCharVariantFromDialogue } from "#data/dialogue"; import { EventModifierType } from "#enums/event-modifier-type"; import { TrainerSlot } from "#enums/trainer-slot"; import { TrainerType } from "#enums/trainer-type"; import { modifierTypes } from "#modifier/modifier-types"; import { BattlePhase } from "#phases/base/battle-phase"; import { vouchers } from "#system/voucher"; import { randSeedItem } from "#utils/random-utils"; import i18next from "i18next"; export class TrainerVictoryPhase extends BattlePhase { public override readonly phaseName = "TrainerVictoryPhase"; public override start(): void { const { charSprite, currentBattle, ui } = globalScene; const { trainer, waveIndex } = currentBattle; globalScene.disableMenu = true; if (!trainer) { this.end(); return; } globalScene.audioManager.playBgm(trainer.config.victoryBgm); globalScene.phaseManager.createAndUnshiftPhase("MoneyRewardPhase", trainer.config.moneyMultiplier); const modifierRewardFuncs = trainer.config.modifierRewardFuncs; for (const modifierRewardFunc of modifierRewardFuncs) { globalScene.phaseManager.createAndUnshiftPhase("ModifierRewardPhase", modifierRewardFunc); } if (timedEventManager.isEventActive(EventModifierType.EXTRA_TRAINER_REWARDS)) { for (const rewardFunc of trainer.config.eventRewardFuncs) { globalScene.phaseManager.createAndUnshiftPhase("ModifierRewardPhase", rewardFunc); } } const trainerType = trainer.config.trainerType; // Validate Voucher for boss trainers if ( Object.hasOwn(vouchers, TrainerType[trainerType]) && !globalScene.validateVoucher(vouchers[TrainerType[trainerType]]) && trainer.config.isBoss ) { globalScene.phaseManager.createAndUnshiftPhase( "ModifierRewardPhase", [modifierTypes.VOUCHER, modifierTypes.VOUCHER, modifierTypes.VOUCHER_PLUS, modifierTypes.VOUCHER_PREMIUM][ vouchers[TrainerType[trainerType]].voucherType ], ); } ui.showText( i18next.t("battle:trainerDefeated", { trainerName: trainer.getName(TrainerSlot.NONE, true), }), { callback: () => { const victoryMessages = trainer.getVictoryMessages(); let message: string; globalScene.executeWithSeedOffset(() => { message = randSeedItem(victoryMessages); }, waveIndex); message = message!; // tell TS compiler it's defined now const showMessage = (): void => { const originalFunc = showMessageOrEnd; showMessageOrEnd = (): void => ui.showDialogue(message, trainer.getName(TrainerSlot.TRAINER, true), originalFunc); showMessageOrEnd(); }; let showMessageOrEnd = (): void => this.end(); if (victoryMessages.length) { if (trainer.config.hasCharSprite && !ui.shouldSkipDialogue(message)) { const originalFunc = showMessageOrEnd; showMessageOrEnd = (): Promise<void> => charSprite.hide().then(() => globalScene.hideFieldOverlay(250).then(() => originalFunc())); globalScene .showFieldOverlay(500) .then(() => charSprite .showCharacter(trainer.getKey(), getCharVariantFromDialogue(victoryMessages[0])) .then(() => showMessage()), ); } else { showMessage(); } } else { showMessageOrEnd(); } }, prompt: true, }, ); this.showEnemyTrainer(); } }
411
0.901672
1
0.901672
game-dev
MEDIA
0.774941
game-dev
0.784441
1
0.784441
ddnet/ddnet
31,749
src/engine/shared/console.cpp
/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include "console.h" #include "config.h" #include "linereader.h" #include <base/color.h> #include <base/log.h> #include <base/math.h> #include <base/system.h> #include <engine/client/checksum.h> #include <engine/console.h> #include <engine/shared/protocol.h> #include <engine/storage.h> #include <algorithm> #include <iterator> // std::size #include <new> // todo: rework this CConsole::CResult::CResult(int ClientId) : IResult(ClientId) { mem_zero(m_aStringStorage, sizeof(m_aStringStorage)); m_pArgsStart = nullptr; m_pCommand = nullptr; mem_zero(m_apArgs, sizeof(m_apArgs)); } CConsole::CResult::CResult(const CResult &Other) : IResult(Other) { mem_copy(m_aStringStorage, Other.m_aStringStorage, sizeof(m_aStringStorage)); m_pArgsStart = m_aStringStorage + (Other.m_pArgsStart - Other.m_aStringStorage); m_pCommand = m_aStringStorage + (Other.m_pCommand - Other.m_aStringStorage); for(unsigned i = 0; i < Other.m_NumArgs; ++i) m_apArgs[i] = m_aStringStorage + (Other.m_apArgs[i] - Other.m_aStringStorage); } void CConsole::CResult::AddArgument(const char *pArg) { m_apArgs[m_NumArgs++] = pArg; } void CConsole::CResult::RemoveArgument(unsigned Index) { dbg_assert(Index < m_NumArgs, "invalid argument index"); for(unsigned i = Index; i < m_NumArgs - 1; i++) m_apArgs[i] = m_apArgs[i + 1]; m_apArgs[m_NumArgs--] = nullptr; } const char *CConsole::CResult::GetString(unsigned Index) const { if(Index >= m_NumArgs) return ""; return m_apArgs[Index]; } int CConsole::CResult::GetInteger(unsigned Index) const { if(Index >= m_NumArgs) return 0; return str_toint(m_apArgs[Index]); } float CConsole::CResult::GetFloat(unsigned Index) const { if(Index >= m_NumArgs) return 0.0f; return str_tofloat(m_apArgs[Index]); } std::optional<ColorHSLA> CConsole::CResult::GetColor(unsigned Index, float DarkestLighting) const { if(Index >= m_NumArgs) return std::nullopt; return ColorParse(m_apArgs[Index], DarkestLighting); } void CConsole::CCommand::SetAccessLevel(EAccessLevel AccessLevel) { m_AccessLevel = AccessLevel; } const IConsole::ICommandInfo *CConsole::FirstCommandInfo(EAccessLevel AccessLevel, int FlagMask) const { for(const CCommand *pCommand = m_pFirstCommand; pCommand; pCommand = pCommand->Next()) { if(pCommand->m_Flags & FlagMask && pCommand->GetAccessLevel() >= AccessLevel) return pCommand; } return nullptr; } const IConsole::ICommandInfo *CConsole::NextCommandInfo(const IConsole::ICommandInfo *pInfo, EAccessLevel AccessLevel, int FlagMask) const { const CCommand *pNext = ((CCommand *)pInfo)->Next(); while(pNext) { if(pNext->m_Flags & FlagMask && pNext->GetAccessLevel() >= AccessLevel) break; pNext = pNext->Next(); } return pNext; } std::optional<CConsole::EAccessLevel> CConsole::AccessLevelToEnum(const char *pAccessLevel) { // alias for legacy integer access levels if(!str_comp(pAccessLevel, "0")) return EAccessLevel::ADMIN; if(!str_comp(pAccessLevel, "1")) return EAccessLevel::MODERATOR; if(!str_comp(pAccessLevel, "2")) return EAccessLevel::HELPER; if(!str_comp(pAccessLevel, "3")) return EAccessLevel::USER; // string access levels if(!str_comp(pAccessLevel, "admin")) return EAccessLevel::ADMIN; if(!str_comp(pAccessLevel, "moderator")) return EAccessLevel::MODERATOR; if(!str_comp(pAccessLevel, "helper")) return EAccessLevel::HELPER; if(!str_comp(pAccessLevel, "all")) return EAccessLevel::USER; return std::nullopt; } const char *CConsole::AccessLevelToString(EAccessLevel AccessLevel) { switch(AccessLevel) { case EAccessLevel::ADMIN: return "admin"; case EAccessLevel::MODERATOR: return "moderator"; case EAccessLevel::HELPER: return "helper"; case EAccessLevel::USER: return "all"; } dbg_assert(false, "invalid access level: %d", (int)AccessLevel); dbg_break(); } // the maximum number of tokens occurs in a string of length CONSOLE_MAX_STR_LENGTH with tokens size 1 separated by single spaces int CConsole::ParseStart(CResult *pResult, const char *pString, int Length) { char *pStr; int Len = sizeof(pResult->m_aStringStorage); if(Length < Len) Len = Length; str_copy(pResult->m_aStringStorage, pString, Len); pStr = pResult->m_aStringStorage; // get command pStr = str_skip_whitespaces(pStr); pResult->m_pCommand = pStr; pStr = str_skip_to_whitespace(pStr); if(*pStr) { pStr[0] = 0; pStr++; } pResult->m_pArgsStart = pStr; return 0; } int CConsole::ParseArgs(CResult *pResult, const char *pFormat, bool IsColor) { char Command = *pFormat; char *pStr; int Optional = 0; int Error = PARSEARGS_OK; pResult->ResetVictim(); pStr = pResult->m_pArgsStart; while(true) { if(!Command) break; if(Command == '?') Optional = 1; else { pStr = str_skip_whitespaces(pStr); if(!(*pStr)) // error, non optional command needs value { if(!Optional) { Error = PARSEARGS_MISSING_VALUE; break; } while(Command) { if(Command == 'v') { pResult->SetVictim(CResult::VICTIM_ME); break; } Command = NextParam(pFormat); } break; } // add token if(*pStr == '"') { char *pDst; pStr++; pResult->AddArgument(pStr); pDst = pStr; // we might have to process escape data while(true) { if(pStr[0] == '"') break; else if(pStr[0] == '\\') { if(pStr[1] == '\\') pStr++; // skip due to escape else if(pStr[1] == '"') pStr++; // skip due to escape } else if(pStr[0] == 0) return PARSEARGS_MISSING_VALUE; // return error *pDst = *pStr; pDst++; pStr++; } // write null termination *pDst = 0; pStr++; } else { char *pVictim = nullptr; pResult->AddArgument(pStr); if(Command == 'v') { pVictim = pStr; } if(Command == 'r') // rest of the string break; else if(Command == 'v' || Command == 'i' || Command == 'f' || Command == 's') pStr = str_skip_to_whitespace(pStr); if(pStr[0] != 0) // check for end of string { pStr[0] = 0; pStr++; } // validate args if(Command == 'i') { // don't validate colors here if(!IsColor) { int Value; if(!str_toint(pResult->GetString(pResult->NumArguments() - 1), &Value) || Value == std::numeric_limits<int>::max() || Value == std::numeric_limits<int>::min()) { Error = PARSEARGS_INVALID_INTEGER; break; } } } else if(Command == 'f') { float Value; if(!str_tofloat(pResult->GetString(pResult->NumArguments() - 1), &Value) || Value == std::numeric_limits<float>::max() || Value == std::numeric_limits<float>::min()) { Error = PARSEARGS_INVALID_FLOAT; break; } } if(pVictim) { pResult->SetVictim(pVictim); } } } // fetch next command Command = NextParam(pFormat); } return Error; } char CConsole::NextParam(const char *&pFormat) { if(*pFormat) { pFormat++; if(*pFormat == '[') { // skip bracket contents for(; *pFormat != ']'; pFormat++) { if(!*pFormat) return *pFormat; } // skip ']' pFormat++; // skip space if there is one if(*pFormat == ' ') pFormat++; } } return *pFormat; } LEVEL IConsole::ToLogLevel(int Level) { switch(Level) { case IConsole::OUTPUT_LEVEL_STANDARD: return LEVEL_INFO; case IConsole::OUTPUT_LEVEL_ADDINFO: return LEVEL_DEBUG; case IConsole::OUTPUT_LEVEL_DEBUG: return LEVEL_TRACE; } dbg_assert(0, "invalid log level"); return LEVEL_INFO; } int IConsole::ToLogLevelFilter(int Level) { if(!(-3 <= Level && Level <= 2)) { dbg_assert(0, "invalid log level filter"); } return Level + 2; } static LOG_COLOR ColorToLogColor(ColorRGBA Color) { return LOG_COLOR{ (uint8_t)(Color.r * 255.0), (uint8_t)(Color.g * 255.0), (uint8_t)(Color.b * 255.0)}; } void CConsole::Print(int Level, const char *pFrom, const char *pStr, ColorRGBA PrintColor) const { LEVEL LogLevel = IConsole::ToLogLevel(Level); // if console colors are not enabled or if the color is pure white, use default terminal color if(g_Config.m_ConsoleEnableColors && PrintColor != gs_ConsoleDefaultColor) { log_log_color(LogLevel, ColorToLogColor(PrintColor), pFrom, "%s", pStr); } else { log_log(LogLevel, pFrom, "%s", pStr); } } void CConsole::SetTeeHistorianCommandCallback(FTeeHistorianCommandCallback pfnCallback, void *pUser) { m_pfnTeeHistorianCommandCallback = pfnCallback; m_pTeeHistorianCommandUserdata = pUser; } void CConsole::SetUnknownCommandCallback(FUnknownCommandCallback pfnCallback, void *pUser) { m_pfnUnknownCommandCallback = pfnCallback; m_pUnknownCommandUserdata = pUser; } void CConsole::InitChecksum(CChecksumData *pData) const { pData->m_NumCommands = 0; for(CCommand *pCommand = m_pFirstCommand; pCommand; pCommand = pCommand->Next()) { if(pData->m_NumCommands < (int)(std::size(pData->m_aCommandsChecksum))) { FCommandCallback pfnCallback = pCommand->m_pfnCallback; void *pUserData = pCommand->m_pUserData; TraverseChain(&pfnCallback, &pUserData); int CallbackBits = (uintptr_t)pfnCallback & 0xfff; int *pTarget = &pData->m_aCommandsChecksum[pData->m_NumCommands]; *pTarget = ((uint8_t)pCommand->m_pName[0]) | ((uint8_t)pCommand->m_pName[1] << 8) | (CallbackBits << 16); } pData->m_NumCommands += 1; } } void CConsole::SetAccessLevel(EAccessLevel AccessLevel) { m_AccessLevel = AccessLevel; } bool CConsole::LineIsValid(const char *pStr) { if(!pStr || *pStr == 0) return false; do { CResult Result(-1); const char *pEnd = pStr; const char *pNextPart = nullptr; int InString = 0; while(*pEnd) { if(*pEnd == '"') InString ^= 1; else if(*pEnd == '\\') // escape sequences { if(pEnd[1] == '"') pEnd++; } else if(!InString) { if(*pEnd == ';') // command separator { pNextPart = pEnd + 1; break; } else if(*pEnd == '#') // comment, no need to do anything more break; } pEnd++; } if(ParseStart(&Result, pStr, (pEnd - pStr) + 1) != 0) return false; CCommand *pCommand = FindCommand(Result.m_pCommand, m_FlagMask); if(!pCommand || ParseArgs(&Result, pCommand->m_pParams)) return false; pStr = pNextPart; } while(pStr && *pStr); return true; } void CConsole::ExecuteLineStroked(int Stroke, const char *pStr, int ClientId, bool InterpretSemicolons) { const char *pWithoutPrefix = str_startswith(pStr, "mc;"); if(pWithoutPrefix) { InterpretSemicolons = true; pStr = pWithoutPrefix; } while(pStr && *pStr) { CResult Result(ClientId); const char *pEnd = pStr; const char *pNextPart = nullptr; int InString = 0; while(*pEnd) { if(*pEnd == '"') InString ^= 1; else if(*pEnd == '\\') // escape sequences { if(pEnd[1] == '"') pEnd++; } else if(!InString && InterpretSemicolons) { if(*pEnd == ';') // command separator { pNextPart = pEnd + 1; break; } else if(*pEnd == '#') // comment, no need to do anything more break; } pEnd++; } if(ParseStart(&Result, pStr, (pEnd - pStr) + 1) != 0) return; if(!*Result.m_pCommand) { if(pNextPart) { pStr = pNextPart; continue; } return; } CCommand *pCommand; if(ClientId == IConsole::CLIENT_ID_GAME) pCommand = FindCommand(Result.m_pCommand, m_FlagMask | CFGFLAG_GAME); else pCommand = FindCommand(Result.m_pCommand, m_FlagMask); if(pCommand) { if(ClientId == IConsole::CLIENT_ID_GAME && !(pCommand->m_Flags & CFGFLAG_GAME)) { if(Stroke) { char aBuf[CMDLINE_LENGTH + 64]; str_format(aBuf, sizeof(aBuf), "Command '%s' cannot be executed from a map.", Result.m_pCommand); Print(OUTPUT_LEVEL_STANDARD, "console", aBuf); } } else if(ClientId == IConsole::CLIENT_ID_NO_GAME && pCommand->m_Flags & CFGFLAG_GAME) { if(Stroke) { char aBuf[CMDLINE_LENGTH + 64]; str_format(aBuf, sizeof(aBuf), "Command '%s' cannot be executed from a non-map config file.", Result.m_pCommand); Print(OUTPUT_LEVEL_STANDARD, "console", aBuf); str_format(aBuf, sizeof(aBuf), "Hint: Put the command in '%s.cfg' instead of '%s.map.cfg' ", g_Config.m_SvMap, g_Config.m_SvMap); Print(OUTPUT_LEVEL_STANDARD, "console", aBuf); } } else if(pCommand->GetAccessLevel() >= m_AccessLevel) { int IsStrokeCommand = 0; if(Result.m_pCommand[0] == '+') { // insert the stroke direction token Result.AddArgument(m_apStrokeStr[Stroke]); IsStrokeCommand = 1; } if(Stroke || IsStrokeCommand) { bool IsColor = false; { FCommandCallback pfnCallback = pCommand->m_pfnCallback; void *pUserData = pCommand->m_pUserData; TraverseChain(&pfnCallback, &pUserData); IsColor = pfnCallback == &SColorConfigVariable::CommandCallback; } if(int Error = ParseArgs(&Result, pCommand->m_pParams, IsColor)) { char aBuf[CMDLINE_LENGTH + 64]; if(Error == PARSEARGS_INVALID_INTEGER) str_format(aBuf, sizeof(aBuf), "%s is not a valid integer.", Result.GetString(Result.NumArguments() - 1)); else if(Error == PARSEARGS_INVALID_FLOAT) str_format(aBuf, sizeof(aBuf), "%s is not a valid decimal number.", Result.GetString(Result.NumArguments() - 1)); else str_format(aBuf, sizeof(aBuf), "Invalid arguments. Usage: %s %s", pCommand->m_pName, pCommand->m_pParams); Print(OUTPUT_LEVEL_STANDARD, "chatresp", aBuf); } else if(m_StoreCommands && pCommand->m_Flags & CFGFLAG_STORE) { m_vExecutionQueue.emplace_back(pCommand, Result); } else { if(pCommand->m_Flags & CMDFLAG_TEST && !g_Config.m_SvTestingCommands) { Print(OUTPUT_LEVEL_STANDARD, "console", "Test commands aren't allowed, enable them with 'sv_test_cmds 1' in your initial config."); return; } if(m_pfnTeeHistorianCommandCallback && !(pCommand->m_Flags & CFGFLAG_NONTEEHISTORIC)) { m_pfnTeeHistorianCommandCallback(ClientId, m_FlagMask, pCommand->m_pName, &Result, m_pTeeHistorianCommandUserdata); } if(Result.GetVictim() == CResult::VICTIM_ME) Result.SetVictim(ClientId); if(Result.HasVictim() && Result.GetVictim() == CResult::VICTIM_ALL) { for(int i = 0; i < MAX_CLIENTS; i++) { Result.SetVictim(i); pCommand->m_pfnCallback(&Result, pCommand->m_pUserData); } } else { pCommand->m_pfnCallback(&Result, pCommand->m_pUserData); } if(pCommand->m_Flags & CMDFLAG_TEST) m_Cheated = true; } } } else if(Stroke) { char aBuf[CMDLINE_LENGTH + 32]; str_format(aBuf, sizeof(aBuf), "Access for command %s denied.", Result.m_pCommand); Print(OUTPUT_LEVEL_STANDARD, "console", aBuf); } } else if(Stroke) { // Pass the original string to the unknown command callback instead of the parsed command, as the latter // ends at the first whitespace, which breaks for unknown commands (filenames) containing spaces. if(!m_pfnUnknownCommandCallback(pStr, m_pUnknownCommandUserdata)) { char aBuf[CMDLINE_LENGTH + 32]; if(m_FlagMask & CFGFLAG_CHAT) str_format(aBuf, sizeof(aBuf), "No such command: %s. Use /cmdlist for a list of all commands.", Result.m_pCommand); else str_format(aBuf, sizeof(aBuf), "No such command: %s.", Result.m_pCommand); Print(OUTPUT_LEVEL_STANDARD, "chatresp", aBuf); } } pStr = pNextPart; } } int CConsole::PossibleCommands(const char *pStr, int FlagMask, bool Temp, FPossibleCallback pfnCallback, void *pUser) { int Index = 0; for(CCommand *pCommand = m_pFirstCommand; pCommand; pCommand = pCommand->Next()) { if(pCommand->m_Flags & FlagMask && pCommand->m_Temp == Temp) { if(str_find_nocase(pCommand->m_pName, pStr)) { pfnCallback(Index, pCommand->m_pName, pUser); Index++; } } } return Index; } CConsole::CCommand *CConsole::FindCommand(const char *pName, int FlagMask) { for(CCommand *pCommand = m_pFirstCommand; pCommand; pCommand = pCommand->Next()) { if(pCommand->m_Flags & FlagMask) { if(str_comp_nocase(pCommand->m_pName, pName) == 0) return pCommand; } } return nullptr; } void CConsole::ExecuteLine(const char *pStr, int ClientId, bool InterpretSemicolons) { CConsole::ExecuteLineStroked(1, pStr, ClientId, InterpretSemicolons); // press it CConsole::ExecuteLineStroked(0, pStr, ClientId, InterpretSemicolons); // then release it } void CConsole::ExecuteLineFlag(const char *pStr, int FlagMask, int ClientId, bool InterpretSemicolons) { int Temp = m_FlagMask; m_FlagMask = FlagMask; ExecuteLine(pStr, ClientId, InterpretSemicolons); m_FlagMask = Temp; } bool CConsole::ExecuteFile(const char *pFilename, int ClientId, bool LogFailure, int StorageType) { int Count = 0; // make sure that this isn't being executed already and that recursion limit isn't met for(CExecFile *pCur = m_pFirstExec; pCur; pCur = pCur->m_pPrev) { Count++; if(str_comp(pFilename, pCur->m_pFilename) == 0 || Count > FILE_RECURSION_LIMIT) return false; } if(!m_pStorage) return false; // push this one to the stack CExecFile ThisFile; CExecFile *pPrev = m_pFirstExec; ThisFile.m_pFilename = pFilename; ThisFile.m_pPrev = m_pFirstExec; m_pFirstExec = &ThisFile; // exec the file CLineReader LineReader; bool Success = false; char aBuf[32 + IO_MAX_PATH_LENGTH]; if(LineReader.OpenFile(m_pStorage->OpenFile(pFilename, IOFLAG_READ, StorageType))) { str_format(aBuf, sizeof(aBuf), "executing '%s'", pFilename); Print(IConsole::OUTPUT_LEVEL_STANDARD, "console", aBuf); while(const char *pLine = LineReader.Get()) { ExecuteLine(pLine, ClientId); } Success = true; } else if(LogFailure) { str_format(aBuf, sizeof(aBuf), "failed to open '%s'", pFilename); Print(IConsole::OUTPUT_LEVEL_STANDARD, "console", aBuf); } m_pFirstExec = pPrev; return Success; } void CConsole::Con_Echo(IResult *pResult, void *pUserData) { ((CConsole *)pUserData)->Print(IConsole::OUTPUT_LEVEL_STANDARD, "console", pResult->GetString(0)); } void CConsole::Con_Exec(IResult *pResult, void *pUserData) { ((CConsole *)pUserData)->ExecuteFile(pResult->GetString(0), -1, true, IStorage::TYPE_ALL); } void CConsole::ConCommandAccess(IResult *pResult, void *pUser) { CConsole *pConsole = static_cast<CConsole *>(pUser); char aBuf[CMDLINE_LENGTH + 64]; CCommand *pCommand = pConsole->FindCommand(pResult->GetString(0), CFGFLAG_SERVER); if(pCommand) { if(pResult->NumArguments() == 2) { std::optional<EAccessLevel> AccessLevel = AccessLevelToEnum(pResult->GetString(1)); if(!AccessLevel.has_value()) { log_error("console", "Invalid access level '%s'. Allowed values are admin, moderator, helper and all.", pResult->GetString(1)); return; } pCommand->SetAccessLevel(AccessLevel.value()); str_format(aBuf, sizeof(aBuf), "moderator access for '%s' is now %s", pResult->GetString(0), pCommand->GetAccessLevel() >= EAccessLevel::MODERATOR ? "enabled" : "disabled"); pConsole->Print(OUTPUT_LEVEL_STANDARD, "console", aBuf); str_format(aBuf, sizeof(aBuf), "helper access for '%s' is now %s", pResult->GetString(0), pCommand->GetAccessLevel() >= EAccessLevel::HELPER ? "enabled" : "disabled"); pConsole->Print(OUTPUT_LEVEL_STANDARD, "console", aBuf); str_format(aBuf, sizeof(aBuf), "user access for '%s' is now %s", pResult->GetString(0), pCommand->GetAccessLevel() >= EAccessLevel::USER ? "enabled" : "disabled"); } else { str_format(aBuf, sizeof(aBuf), "moderator access for '%s' is %s", pResult->GetString(0), pCommand->GetAccessLevel() >= EAccessLevel::MODERATOR ? "enabled" : "disabled"); pConsole->Print(OUTPUT_LEVEL_STANDARD, "console", aBuf); str_format(aBuf, sizeof(aBuf), "helper access for '%s' is %s", pResult->GetString(0), pCommand->GetAccessLevel() >= EAccessLevel::HELPER ? "enabled" : "disabled"); pConsole->Print(OUTPUT_LEVEL_STANDARD, "console", aBuf); str_format(aBuf, sizeof(aBuf), "user access for '%s' is %s", pResult->GetString(0), pCommand->GetAccessLevel() >= EAccessLevel::USER ? "enabled" : "disabled"); } } else str_format(aBuf, sizeof(aBuf), "No such command: '%s'.", pResult->GetString(0)); pConsole->Print(OUTPUT_LEVEL_STANDARD, "console", aBuf); } void CConsole::ConCommandStatus(IResult *pResult, void *pUser) { CConsole *pConsole = static_cast<CConsole *>(pUser); char aBuf[240] = ""; int Used = 0; std::optional<EAccessLevel> AccessLevel = AccessLevelToEnum(pResult->GetString(0)); if(!AccessLevel.has_value()) { log_error("console", "Invalid access level '%s'. Allowed values are admin, moderator, helper and all.", pResult->GetString(0)); return; } for(CCommand *pCommand = pConsole->m_pFirstCommand; pCommand; pCommand = pCommand->Next()) { if(pCommand->m_Flags & pConsole->m_FlagMask && pCommand->GetAccessLevel() >= AccessLevel.value()) { int Length = str_length(pCommand->m_pName); if(Used + Length + 2 < (int)(sizeof(aBuf))) { if(Used > 0) { Used += 2; str_append(aBuf, ", "); } str_append(aBuf, pCommand->m_pName); Used += Length; } else { pConsole->Print(OUTPUT_LEVEL_STANDARD, "chatresp", aBuf); str_copy(aBuf, pCommand->m_pName); Used = Length; } } } if(Used > 0) pConsole->Print(OUTPUT_LEVEL_STANDARD, "chatresp", aBuf); } void CConsole::ConUserCommandStatus(IResult *pResult, void *pUser) { CConsole *pConsole = static_cast<CConsole *>(pUser); CResult Result(pResult->m_ClientId); Result.m_pCommand = "access_status"; Result.AddArgument(AccessLevelToString(EAccessLevel::USER)); CConsole::ConCommandStatus(&Result, pConsole); } void CConsole::TraverseChain(FCommandCallback *ppfnCallback, void **ppUserData) { while(*ppfnCallback == Con_Chain) { CChain *pChainInfo = static_cast<CChain *>(*ppUserData); *ppfnCallback = pChainInfo->m_pfnCallback; *ppUserData = pChainInfo->m_pCallbackUserData; } } CConsole::CConsole(int FlagMask) { m_FlagMask = FlagMask; m_AccessLevel = EAccessLevel::ADMIN; m_pRecycleList = nullptr; m_TempCommands.Reset(); m_StoreCommands = true; m_apStrokeStr[0] = "0"; m_apStrokeStr[1] = "1"; m_pFirstCommand = nullptr; m_pFirstExec = nullptr; m_pfnTeeHistorianCommandCallback = nullptr; m_pTeeHistorianCommandUserdata = nullptr; m_pStorage = nullptr; // register some basic commands Register("echo", "r[text]", CFGFLAG_SERVER, Con_Echo, this, "Echo the text"); Register("exec", "r[file]", CFGFLAG_SERVER | CFGFLAG_CLIENT, Con_Exec, this, "Execute the specified file"); Register("access_level", "s[command] ?s['admin'|'moderator'|'helper'|'all']", CFGFLAG_SERVER, ConCommandAccess, this, "Specify command accessibility for given access level"); Register("access_status", "s['admin'|'moderator'|'helper'|'all']", CFGFLAG_SERVER, ConCommandStatus, this, "List all commands which are accessible for given access level"); Register("cmdlist", "", CFGFLAG_SERVER | CFGFLAG_CHAT, ConUserCommandStatus, this, "List all commands which are accessible for users"); // DDRace m_Cheated = false; } CConsole::~CConsole() { CCommand *pCommand = m_pFirstCommand; while(pCommand) { CCommand *pNext = pCommand->Next(); { FCommandCallback pfnCallback = pCommand->m_pfnCallback; void *pUserData = pCommand->m_pUserData; CChain *pChain = nullptr; while(pfnCallback == Con_Chain) { pChain = static_cast<CChain *>(pUserData); pfnCallback = pChain->m_pfnCallback; pUserData = pChain->m_pCallbackUserData; delete pChain; } } // Temp commands are on m_TempCommands heap, so don't delete them if(!pCommand->m_Temp) delete pCommand; pCommand = pNext; } } void CConsole::Init() { m_pStorage = Kernel()->RequestInterface<IStorage>(); } void CConsole::ParseArguments(int NumArgs, const char **ppArguments) { for(int i = 0; i < NumArgs; i++) { // check for scripts to execute if(ppArguments[i][0] == '-' && ppArguments[i][1] == 'f' && ppArguments[i][2] == 0) { if(NumArgs - i > 1) ExecuteFile(ppArguments[i + 1], -1, true, IStorage::TYPE_ABSOLUTE); i++; } else if(!str_comp("-s", ppArguments[i]) || !str_comp("--silent", ppArguments[i])) { // skip silent param continue; } else { // search arguments for overrides ExecuteLine(ppArguments[i]); } } } void CConsole::AddCommandSorted(CCommand *pCommand) { if(!m_pFirstCommand || str_comp(pCommand->m_pName, m_pFirstCommand->m_pName) <= 0) { if(m_pFirstCommand && m_pFirstCommand->Next()) pCommand->SetNext(m_pFirstCommand); else pCommand->SetNext(nullptr); m_pFirstCommand = pCommand; } else { for(CCommand *p = m_pFirstCommand; p; p = p->Next()) { if(!p->Next() || str_comp(pCommand->m_pName, p->Next()->m_pName) <= 0) { pCommand->SetNext(p->Next()); p->SetNext(pCommand); break; } } } } void CConsole::Register(const char *pName, const char *pParams, int Flags, FCommandCallback pfnFunc, void *pUser, const char *pHelp) { CCommand *pCommand = FindCommand(pName, Flags); bool DoAdd = false; if(pCommand == nullptr) { pCommand = new CCommand(); DoAdd = true; } pCommand->m_pfnCallback = pfnFunc; pCommand->m_pUserData = pUser; pCommand->m_pName = pName; pCommand->m_pHelp = pHelp; pCommand->m_pParams = pParams; pCommand->m_Flags = Flags; pCommand->m_Temp = false; if(DoAdd) AddCommandSorted(pCommand); if(pCommand->m_Flags & CFGFLAG_CHAT) pCommand->SetAccessLevel(EAccessLevel::USER); } void CConsole::RegisterTemp(const char *pName, const char *pParams, int Flags, const char *pHelp) { CCommand *pCommand; if(m_pRecycleList) { pCommand = m_pRecycleList; str_copy(const_cast<char *>(pCommand->m_pName), pName, TEMPCMD_NAME_LENGTH); str_copy(const_cast<char *>(pCommand->m_pHelp), pHelp, TEMPCMD_HELP_LENGTH); str_copy(const_cast<char *>(pCommand->m_pParams), pParams, TEMPCMD_PARAMS_LENGTH); m_pRecycleList = m_pRecycleList->Next(); } else { pCommand = new(m_TempCommands.Allocate(sizeof(CCommand))) CCommand; char *pMem = static_cast<char *>(m_TempCommands.Allocate(TEMPCMD_NAME_LENGTH)); str_copy(pMem, pName, TEMPCMD_NAME_LENGTH); pCommand->m_pName = pMem; pMem = static_cast<char *>(m_TempCommands.Allocate(TEMPCMD_HELP_LENGTH)); str_copy(pMem, pHelp, TEMPCMD_HELP_LENGTH); pCommand->m_pHelp = pMem; pMem = static_cast<char *>(m_TempCommands.Allocate(TEMPCMD_PARAMS_LENGTH)); str_copy(pMem, pParams, TEMPCMD_PARAMS_LENGTH); pCommand->m_pParams = pMem; } pCommand->m_pfnCallback = nullptr; pCommand->m_pUserData = nullptr; pCommand->m_Flags = Flags; pCommand->m_Temp = true; AddCommandSorted(pCommand); } void CConsole::DeregisterTemp(const char *pName) { if(!m_pFirstCommand) return; CCommand *pRemoved = nullptr; // remove temp entry from command list if(m_pFirstCommand->m_Temp && str_comp(m_pFirstCommand->m_pName, pName) == 0) { pRemoved = m_pFirstCommand; m_pFirstCommand = m_pFirstCommand->Next(); } else { for(CCommand *pCommand = m_pFirstCommand; pCommand->Next(); pCommand = pCommand->Next()) if(pCommand->Next()->m_Temp && str_comp(pCommand->Next()->m_pName, pName) == 0) { pRemoved = pCommand->Next(); pCommand->SetNext(pCommand->Next()->Next()); break; } } // add to recycle list if(pRemoved) { pRemoved->SetNext(m_pRecycleList); m_pRecycleList = pRemoved; } } void CConsole::DeregisterTempAll() { // set non temp as first one for(; m_pFirstCommand && m_pFirstCommand->m_Temp; m_pFirstCommand = m_pFirstCommand->Next()) ; // remove temp entries from command list for(CCommand *pCommand = m_pFirstCommand; pCommand && pCommand->Next(); pCommand = pCommand->Next()) { CCommand *pNext = pCommand->Next(); if(pNext->m_Temp) { for(; pNext && pNext->m_Temp; pNext = pNext->Next()) ; pCommand->SetNext(pNext); } } m_TempCommands.Reset(); m_pRecycleList = nullptr; } void CConsole::Con_Chain(IResult *pResult, void *pUserData) { CChain *pInfo = (CChain *)pUserData; pInfo->m_pfnChainCallback(pResult, pInfo->m_pUserData, pInfo->m_pfnCallback, pInfo->m_pCallbackUserData); } void CConsole::Chain(const char *pName, FChainCommandCallback pfnChainFunc, void *pUser) { CCommand *pCommand = FindCommand(pName, m_FlagMask); if(!pCommand) { char aBuf[256]; str_format(aBuf, sizeof(aBuf), "failed to chain '%s'", pName); Print(IConsole::OUTPUT_LEVEL_DEBUG, "console", aBuf); return; } CChain *pChainInfo = new CChain(); // store info pChainInfo->m_pfnChainCallback = pfnChainFunc; pChainInfo->m_pUserData = pUser; pChainInfo->m_pfnCallback = pCommand->m_pfnCallback; pChainInfo->m_pCallbackUserData = pCommand->m_pUserData; // chain pCommand->m_pfnCallback = Con_Chain; pCommand->m_pUserData = pChainInfo; } void CConsole::StoreCommands(bool Store) { if(!Store) { for(CExecutionQueueEntry &Entry : m_vExecutionQueue) { Entry.m_pCommand->m_pfnCallback(&Entry.m_Result, Entry.m_pCommand->m_pUserData); } m_vExecutionQueue.clear(); } m_StoreCommands = Store; } const IConsole::ICommandInfo *CConsole::GetCommandInfo(const char *pName, int FlagMask, bool Temp) { for(CCommand *pCommand = m_pFirstCommand; pCommand; pCommand = pCommand->Next()) { if(pCommand->m_Flags & FlagMask && pCommand->m_Temp == Temp) { if(str_comp_nocase(pCommand->Name(), pName) == 0) return pCommand; } } return nullptr; } std::unique_ptr<IConsole> CreateConsole(int FlagMask) { return std::make_unique<CConsole>(FlagMask); } int CConsole::CResult::GetVictim() const { return m_Victim; } void CConsole::CResult::ResetVictim() { m_Victim = VICTIM_NONE; } bool CConsole::CResult::HasVictim() const { return m_Victim != VICTIM_NONE; } void CConsole::CResult::SetVictim(int Victim) { m_Victim = std::clamp<int>(Victim, VICTIM_NONE, MAX_CLIENTS - 1); } void CConsole::CResult::SetVictim(const char *pVictim) { if(!str_comp(pVictim, "me")) m_Victim = VICTIM_ME; else if(!str_comp(pVictim, "all")) m_Victim = VICTIM_ALL; else m_Victim = std::clamp<int>(str_toint(pVictim), 0, MAX_CLIENTS - 1); } std::optional<ColorHSLA> CConsole::ColorParse(const char *pStr, float DarkestLighting) { if(str_isallnum(pStr) || ((pStr[0] == '-' || pStr[0] == '+') && str_isallnum(pStr + 1))) // Teeworlds Color (Packed HSL) { unsigned long Value = str_toulong_base(pStr, 10); if(Value == std::numeric_limits<unsigned long>::max()) return std::nullopt; return ColorHSLA(Value, true).UnclampLighting(DarkestLighting); } else if(*pStr == '$') // Hex RGB/RGBA { auto ParsedColor = color_parse<ColorRGBA>(pStr + 1); if(ParsedColor) return color_cast<ColorHSLA>(ParsedColor.value()); else return std::nullopt; } else if(!str_comp_nocase(pStr, "red")) return ColorHSLA(0.0f / 6.0f, 1.0f, 0.5f); else if(!str_comp_nocase(pStr, "yellow")) return ColorHSLA(1.0f / 6.0f, 1.0f, 0.5f); else if(!str_comp_nocase(pStr, "green")) return ColorHSLA(2.0f / 6.0f, 1.0f, 0.5f); else if(!str_comp_nocase(pStr, "cyan")) return ColorHSLA(3.0f / 6.0f, 1.0f, 0.5f); else if(!str_comp_nocase(pStr, "blue")) return ColorHSLA(4.0f / 6.0f, 1.0f, 0.5f); else if(!str_comp_nocase(pStr, "magenta")) return ColorHSLA(5.0f / 6.0f, 1.0f, 0.5f); else if(!str_comp_nocase(pStr, "white")) return ColorHSLA(0.0f, 0.0f, 1.0f); else if(!str_comp_nocase(pStr, "gray")) return ColorHSLA(0.0f, 0.0f, 0.5f); else if(!str_comp_nocase(pStr, "black")) return ColorHSLA(0.0f, 0.0f, 0.0f); return std::nullopt; }
411
0.991997
1
0.991997
game-dev
MEDIA
0.333167
game-dev
0.985854
1
0.985854
colorblindness/3arthh4ck
20,701
src/main/java/me/earth/earthhack/impl/modules/combat/surround/Surround.java
package me.earth.earthhack.impl.modules.combat.surround; import me.earth.earthhack.api.cache.ModuleCache; import me.earth.earthhack.api.module.util.Category; import me.earth.earthhack.api.setting.Setting; import me.earth.earthhack.api.setting.settings.BooleanSetting; import me.earth.earthhack.api.setting.settings.EnumSetting; import me.earth.earthhack.api.setting.settings.NumberSetting; import me.earth.earthhack.impl.managers.Managers; import me.earth.earthhack.impl.modules.Caches; import me.earth.earthhack.impl.modules.combat.surround.modes.Movement; import me.earth.earthhack.impl.modules.combat.surround.modes.SurroundFreecamMode; import me.earth.earthhack.impl.modules.movement.blocklag.BlockLag; import me.earth.earthhack.impl.modules.player.freecam.Freecam; import me.earth.earthhack.impl.util.client.ModuleUtil; import me.earth.earthhack.impl.util.helpers.blocks.BlockPlacingModule; import me.earth.earthhack.impl.util.helpers.blocks.ObbyModule; import me.earth.earthhack.impl.util.helpers.blocks.modes.Rotate; import me.earth.earthhack.impl.util.math.StopWatch; import me.earth.earthhack.impl.util.math.position.PositionUtil; import me.earth.earthhack.impl.util.minecraft.InventoryUtil; import me.earth.earthhack.impl.util.minecraft.PlayerUtil; import me.earth.earthhack.impl.util.minecraft.blocks.BlockUtil; import me.earth.earthhack.impl.util.minecraft.blocks.HoleUtil; import me.earth.earthhack.impl.util.minecraft.entity.EntityUtil; import me.earth.earthhack.impl.util.text.TextColor; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import java.util.ArrayList; import java.util.Comparator; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.stream.Collectors; // TODO: Make City thing better public class Surround extends ObbyModule { protected static final ModuleCache<Freecam> FREECAM = Caches.getModule(Freecam.class); protected static final ModuleCache<BlockLag> BLOCKLAG = Caches.getModule(BlockLag.class); protected final Setting<Boolean> center = register(new BooleanSetting("Center", true)); protected final Setting<Movement> movement = register(new EnumSetting<>("Movement", Movement.Static)); protected final Setting<Float> speed = register(new NumberSetting<>("Speed", 19.5f, 0.0f, 35.0f)); protected final Setting<Boolean> noTrap = register(new BooleanSetting("NoTrap", false)); protected final Setting<Boolean> floor = register(new BooleanSetting("Floor", false)); protected final Setting<Integer> extend = register(new NumberSetting<>("Extend", 1, 1, 3)); protected final Setting<Integer> eDelay = register(new NumberSetting<>("E-Delay", 100, 0, 1000)); protected final Setting<Boolean> holeC = register(new BooleanSetting("Hole-C", false)); protected final Setting<Boolean> instant = register(new BooleanSetting("Instant", false)); protected final Setting<Boolean> sound = register(new BooleanSetting("Sound", false)); protected final Setting<Integer> playerExtend = register(new NumberSetting<>("PlayerExtend", 0, 0, 4)); protected final Setting<Boolean> peNoTrap = register(new BooleanSetting("PE-NoTrap", false)); protected final Setting<Boolean> noTrapBlock = register(new BooleanSetting("NoTrapBlock", false)); protected final Setting<Boolean> multiTrap = register(new BooleanSetting("MultiTrap", false)); protected final Setting<Boolean> trapExtend = register(new BooleanSetting("TrapExtend", false)); protected final Setting<Boolean> newVer = register(new BooleanSetting("1.13+", false)); protected final Setting<Boolean> deltaY = register(new BooleanSetting("Delta-Y", true)); protected final Setting<Boolean> centerY = register(new BooleanSetting("Center-Y", false)); protected final Setting<Boolean> predict = register(new BooleanSetting("Predict", false)); protected final Setting<Boolean> async = register(new BooleanSetting("Async", false)); protected final Setting<Boolean> resync = register(new BooleanSetting("Resync", false)); protected final Setting<Boolean> crystalCheck = register(new BooleanSetting("Crystal-Check", true)); protected final Setting<Boolean> burrow = register(new BooleanSetting("Burrow", false)); protected final Setting<Boolean> noSelfExtend = register(new BooleanSetting("NoSelfExtend", false)); protected final Setting<SurroundFreecamMode> freecam = register(new EnumSetting<>("Freecam", SurroundFreecamMode.Off)); /** A Listener for the SetDeadManager (Instant + Sound). */ protected final ListenerSound soundObserver = new ListenerSound(this); /** Handles the delay from enabling until we fully extend */ protected final StopWatch extendingWatch = new StopWatch(); /** The Positions surrounding us. */ protected Set<BlockPos> targets = new HashSet<>(); /** Blocks that have been placed and await a SPacketBlockChange */ protected Set<BlockPos> placed = new HashSet<>(); /** Positions that have been confirmed by a SPacketBlockChange */ protected Set<BlockPos> confirmed = new HashSet<>(); /** The position we were at when we enabled the module */ protected BlockPos startPos; /** <tt>true</tt> if we are centered, or don't have to center */ protected boolean setPosition; public Surround() { super("Surround", Category.Combat); this.listeners.add(new ListenerMotion(this)); this.listeners.add(new ListenerBlockChange(this)); this.listeners.add(new ListenerMultiBlockChange(this)); this.listeners.add(new ListenerExplosion(this)); this.listeners.add(new ListenerSpawnObject(this)); this.setData(new SurroundData(this)); } @Override protected void onEnable() { Managers.SET_DEAD.addObserver(soundObserver); super.onEnable(); if (super.checkNull()) { confirmed.clear(); targets.clear(); placed.clear(); attacking = null; setPosition = false; startPos = getPlayerPos(); extendingWatch.reset(); if (burrow.getValue() && !BLOCKLAG.isEnabled()) { BLOCKLAG.toggle(); } } } @Override protected void onDisable() { Managers.SET_DEAD.removeObserver(soundObserver); } /** * Centers the player. To not produce * any extra packets we need to wait until * after onUpdateWalkingPlayer.Post, so that * our position has been updated for the server, * before we send any place packets. */ protected void center() { if (center.getValue() && !setPosition && startPos != null && mc.world.getBlockState(startPos).getBlock() != Blocks.WEB && (holeC.getValue() || !HoleUtil.isHole(startPos, false)[0])) { double x = startPos.getX() + 0.5; double y = centerY.getValue() ? startPos.getY() : getPlayer().posY; double z = startPos.getZ() + 0.5; getPlayer().setPosition(x, y, z); getPlayer().setVelocity(0.0, getPlayer().motionY, 0.0); } else { setPosition = true; } } /** * Runs {@link Surround#check()} and if we can place, * updates our surrounding blocks. * * @return <tt>true</tt> if we can proceed. */ protected boolean updatePosAndBlocks() { if (check()) { Set<BlockPos> blocked = createBlocked(); Set<BlockPos> surrounding = createSurrounding(blocked, mc.world .playerEntities); placed.retainAll(surrounding); this.targets = surrounding; return true; } return false; } /** * Checks if FreeCam is enabled or we have no Obby/Echests, * we move too fast, or the timer hasn't passed the delay yet. * In all these cases return <tt>false</tt>. * * @return if we can proceed. */ private boolean check() { if (FREECAM.isEnabled() && freecam.getValue() == SurroundFreecamMode.Off) { return false; } slot = InventoryUtil.findHotbarBlock(Blocks.OBSIDIAN, Blocks.ENDER_CHEST); if (slot == -1) { ModuleUtil.disable(this, TextColor.RED + "Disabled, no Obsidian."); return false; } if (FREECAM.isEnabled() && movement.getValue() != Movement.Static) { return timer.passed(delay.getValue()); } switch (movement.getValue()) { case None: break; case Static: BlockPos currentPos = getPlayerPos(); if (!currentPos.equals(startPos)) { this.disable(); return false; } break; case Limit: if (Managers.SPEED.getSpeed() > speed.getValue()) { return false; } break; case Disable: if (Managers.SPEED.getSpeed() > speed.getValue()) { this.disable(); return false; } break; } return timer.passed(delay.getValue()); } /** * Places a block on the given position. * {@link BlockPlacingModule#placeBlock} will be called, * for the position and if needed for a helping position. * Returns <tt>true</tt> if the Block/Place limit has been * reached. * * @param pos the position. * @return if we cant place anymore. */ @Override public boolean placeBlock(BlockPos pos) { boolean hasPlaced = super.placeBlock(pos); if (hasPlaced) { placed.add(pos); } return hasPlaced; } /** * Very interesting code that returns all * positions that have to be surrounded. * * @return positions to be surrounded. */ protected Set<BlockPos> createBlocked() { Set<BlockPos> blocked = new HashSet<>(); BlockPos playerPos = getPlayerPos(); if (HoleUtil.isHole(playerPos, false)[0] || center.getValue() // && !setPosition || extend.getValue() == 1 || !extendingWatch.passed(eDelay.getValue())) { blocked.add(playerPos); } else { List<BlockPos> unfiltered = new ArrayList<>(PositionUtil.getBlockedPositions(getPlayer())) .stream() .sorted(Comparator.comparingDouble(pos -> BlockUtil.getDistanceSq(getPlayer(), pos))) .collect(Collectors.toList()); List<BlockPos> filtered = new ArrayList<>(unfiltered) .stream() .filter(pos -> mc.world .getBlockState(pos) .getMaterial() .isReplaceable() && mc.world .getBlockState(pos.up()) .getMaterial() .isReplaceable()) .collect(Collectors.toList()); if (extend.getValue() == 3 && filtered.size() == 2 && unfiltered.size() == 4) { // Prevents that a pos like this // (x == block, o == air, i = player): // // o x x // x i can extend to this: x o x // x i // if (unfiltered.get(0).equals(filtered.get(0)) && unfiltered.get(3).equals(filtered.get(1))) { filtered.clear(); filtered.add(playerPos); } } if (extend.getValue() == 2 && filtered.size() > 2 || extend.getValue() == 3 && filtered.size() == 3) { // Prevents that a pos like this // (x == block, o == air, i = player): // // x o x // i can extend to this: x o x // x i x // x x // // we should, unless we phased in, be able to place on o while (filtered.size() > 2) { filtered.remove(filtered.size() - 1); } } blocked.addAll(filtered); } if (blocked.isEmpty()) { blocked.add(playerPos); } return blocked; } protected boolean shouldInstant(boolean sound) { return instant.getValue() && rotate.getValue() != Rotate.Normal && (!sound || this.sound.getValue()); } protected boolean isBlockingTrap(BlockPos pos, List<EntityPlayer> players) { if (mc.world.getBlockState(pos.up()).getMaterial().isReplaceable()) { return false; } EnumFacing relative = getFacingRelativeToPlayer(pos, getPlayer()); if (relative != null && !trapExtend.getValue() && BlockUtil.canPlaceCrystal(getPlayerPos() .down() .offset(relative, 2), true, newVer.getValue())) { return false; } for (EntityPlayer player : players) { if (player == null || getPlayer().equals(player) || EntityUtil.isDead(player) || Managers.FRIENDS.contains(player) || player.getDistanceSq(pos) > 9) { continue; } BlockPos playerPos = PositionUtil.getPosition(player); for (EnumFacing facing : EnumFacing.HORIZONTALS) { if (facing == relative || facing.getOpposite() == relative || !pos.offset(facing).equals(playerPos)) { continue; } if (BlockUtil.canPlaceCrystal(pos.offset(facing.getOpposite()) .down(), true, newVer.getValue())) { return true; } } } return false; } protected EnumFacing getFacingRelativeToPlayer(BlockPos pos, EntityPlayer player) { double x = pos.getX() + 0.5 - player.posX; double z = pos.getZ() + 0.5 - player.posZ; int compare = Double.compare(Math.abs(x), Math.abs(z)); if (compare == 0) { return null; } return compare < 0 ? z < 0 ? EnumFacing.NORTH : EnumFacing.SOUTH : x < 0 ? EnumFacing.WEST : EnumFacing.EAST; } protected Set<BlockPos> createSurrounding(Set<BlockPos> blocked, List<EntityPlayer> players) { Set<BlockPos> surrounding = new HashSet<>(); for (BlockPos pos : blocked) { for (EnumFacing facing : EnumFacing.HORIZONTALS) { BlockPos offset = pos.offset(facing); if (!blocked.contains(offset)) { surrounding.add(offset); if (noTrap.getValue()) { surrounding.add(offset.down()); } } } if (floor.getValue()) { surrounding.add(pos.down()); } } // TODO: Extend around webs? for (int i = 0; i < playerExtend.getValue(); i++) { Set<BlockPos> extendedPositions = new HashSet<>(); Iterator<BlockPos> itr = surrounding.iterator(); while (itr.hasNext()) { BlockPos pos = itr.next(); boolean remove = false; for (EntityPlayer player : players) { if (player == null || (noSelfExtend.getValue() && player == mc.player) || PlayerUtil.isFakePlayer(player) || EntityUtil.isDead(player) || !BlockUtil.isBlocking(pos, player, blockingType.getValue())) { continue; } for (EnumFacing facing : EnumFacing.HORIZONTALS) { BlockPos offset = pos.offset(facing); if (blocked.contains(offset)) { continue; } remove = true; extendedPositions.add(offset); if (peNoTrap.getValue()) { extendedPositions.add(offset.down()); } } } if (remove) { itr.remove(); } } surrounding.addAll(extendedPositions); } if (noTrapBlock.getValue()) { Set<BlockPos> trapBlocks = surrounding.stream() .filter(pos -> isBlockingTrap(pos, players)) .collect(Collectors.toSet()); if (!multiTrap.getValue() && trapBlocks.size() > 1) { return surrounding; } for (BlockPos trap : trapBlocks) { if (trapExtend.getValue()) { EnumFacing r = getFacingRelativeToPlayer(trap, getPlayer()); if (r != null) { surrounding.add(getPlayerPos().offset(r, 2)); } } surrounding.remove(trap); } } return surrounding; } protected BlockPos getPlayerPos() { return deltaY.getValue() && Math.abs(getPlayer().motionY) > 0.1 ? new BlockPos(getPlayer()) : PositionUtil.getPosition(getPlayer()); } @Override public EntityPlayer getPlayerForRotations() { if (FREECAM.isEnabled()) { EntityPlayer target = FREECAM.get().getPlayer(); if (target != null) { return target; } } return mc.player; } @Override public EntityPlayer getPlayer() { if (freecam.getValue() == SurroundFreecamMode.Origin && FREECAM.isEnabled()) { EntityPlayer target = FREECAM.get().getPlayer(); if (target != null) { return target; } } return mc.player; } }
411
0.930748
1
0.930748
game-dev
MEDIA
0.95262
game-dev
0.946858
1
0.946858
sunwaylive/UsePhysXWithUnity
1,754
1.ExportScenesInUnity/Editor/protobuf-net/KeyValuePairProxy.cs
//#if !NO_GENERICS //using System.Collections.Generic; //namespace ProtoBuf //{ // /// <summary> // /// Mutable version of the common key/value pair struct; used during serialization. This type is intended for internal use only and should not // /// be used by calling code; it is required to be public for implementation reasons. // /// </summary> // [ProtoContract] // public struct KeyValuePairSurrogate<TKey,TValue> // { // private TKey key; // private TValue value; // /// <summary> // /// The key of the pair. // /// </summary> // [ProtoMember(1, IsRequired = true)] // public TKey Key { get { return key; } set { key = value; } } // /// <summary> // /// The value of the pair. // /// </summary> // [ProtoMember(2)] // public TValue Value{ get { return value; } set { this.value = value; } } // private KeyValuePairSurrogate(TKey key, TValue value) // { // this.key = key; // this.value = value; // } // /// <summary> // /// Convert a surrogate instance to a standard pair instance. // /// </summary> // public static implicit operator KeyValuePair<TKey, TValue> (KeyValuePairSurrogate<TKey, TValue> value) // { // return new KeyValuePair<TKey,TValue>(value.key, value.value); // } // /// <summary> // /// Convert a standard pair instance to a surrogate instance. // /// </summary> // public static implicit operator KeyValuePairSurrogate<TKey, TValue>(KeyValuePair<TKey, TValue> value) // { // return new KeyValuePairSurrogate<TKey, TValue>(value.Key, value.Value); // } // } //} //#endif
411
0.94214
1
0.94214
game-dev
MEDIA
0.305831
game-dev
0.691004
1
0.691004
audulus/rui
2,191
src/views/offset.rs
use crate::*; use std::any::Any; /// Struct for the `offset` modifier. #[derive(Clone)] pub struct Offset<V> { child: V, offset: LocalOffset, } impl<V> DynView for Offset<V> where V: View, { fn process( &self, event: &Event, path: &mut IdPath, cx: &mut Context, actions: &mut Vec<Box<dyn Any>>, ) { path.push(0); self.child .process(&event.offset(-self.offset), path, cx, actions); path.pop(); } fn draw(&self, path: &mut IdPath, args: &mut DrawArgs) { args.vger.save(); args.vger.translate(self.offset); path.push(0); self.child.draw(path, args); path.pop(); args.vger.restore(); } fn layout(&self, path: &mut IdPath, args: &mut LayoutArgs) -> LocalSize { path.push(0); let sz = self.child.layout(path, args); path.pop(); sz } fn dirty(&self, path: &mut IdPath, xform: LocalToWorld, cx: &mut Context) { path.push(0); self.child.dirty(path, xform.pre_translate(self.offset), cx); path.pop(); } fn hittest(&self, path: &mut IdPath, pt: LocalPoint, cx: &mut Context) -> Option<ViewId> { path.push(0); let hit_id = self.child.hittest(path, pt - self.offset, cx); path.pop(); hit_id } fn commands(&self, path: &mut IdPath, cx: &mut Context, cmds: &mut Vec<CommandInfo>) { path.push(0); self.child.commands(path, cx, cmds); path.pop(); } fn gc(&self, path: &mut IdPath, cx: &mut Context, map: &mut Vec<ViewId>) { path.push(0); self.child.gc(path, cx, map); path.pop(); } fn access( &self, path: &mut IdPath, cx: &mut Context, nodes: &mut Vec<(accesskit::NodeId, accesskit::Node)>, ) -> Option<accesskit::NodeId> { path.push(0); let node_id = self.child.access(path, cx, nodes); path.pop(); node_id } } impl<V> Offset<V> where V: View, { pub fn new(child: V, offset: LocalOffset) -> Self { Self { child, offset } } } impl<V> private::Sealed for Offset<V> {}
411
0.871749
1
0.871749
game-dev
MEDIA
0.571322
game-dev
0.936592
1
0.936592
Creators-of-Create/Create
2,032
src/main/java/com/simibubi/create/content/logistics/stockTicker/StockCheckingBlockEntity.java
package com.simibubi.create.content.logistics.stockTicker; import java.util.List; import javax.annotation.Nullable; import com.simibubi.create.content.logistics.packager.IdentifiedInventory; import com.simibubi.create.content.logistics.packager.InventorySummary; import com.simibubi.create.content.logistics.packagerLink.LogisticallyLinkedBehaviour; import com.simibubi.create.content.logistics.packagerLink.LogisticallyLinkedBehaviour.RequestType; import com.simibubi.create.content.logistics.packagerLink.LogisticsManager; import com.simibubi.create.foundation.blockEntity.SmartBlockEntity; import com.simibubi.create.foundation.blockEntity.behaviour.BlockEntityBehaviour; import net.minecraft.core.BlockPos; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; public abstract class StockCheckingBlockEntity extends SmartBlockEntity { public LogisticallyLinkedBehaviour behaviour; public StockCheckingBlockEntity(BlockEntityType<?> type, BlockPos pos, BlockState state) { super(type, pos, state); setLazyTickRate(10); } @Override public void addBehaviours(List<BlockEntityBehaviour> behaviours) { behaviours.add(behaviour = new LogisticallyLinkedBehaviour(this, false)); } public InventorySummary getRecentSummary() { return LogisticsManager.getSummaryOfNetwork(behaviour.freqId, false); } public InventorySummary getAccurateSummary() { return LogisticsManager.getSummaryOfNetwork(behaviour.freqId, true); } public boolean broadcastPackageRequest(RequestType type, PackageOrder order, @Nullable IdentifiedInventory ignoredHandler, String address) { return broadcastPackageRequest(type, PackageOrderWithCrafts.simple(order.stacks()), ignoredHandler, address); } public boolean broadcastPackageRequest(RequestType type, PackageOrderWithCrafts order, @Nullable IdentifiedInventory ignoredHandler, String address) { return LogisticsManager.broadcastPackageRequest(behaviour.freqId, type, order, ignoredHandler, address); } }
411
0.701653
1
0.701653
game-dev
MEDIA
0.799094
game-dev
0.838763
1
0.838763
ml4a/ml4a-ofx
4,707
osc-modules/KinectOSC/src/ofApp.cpp
#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup(){ ofSetWindowShape(640, 480); // default settings debug = false; normalize = true; sendScreen = false; oscDestination = OSC_DESTINATION_DEFAULT; oscAddress = OSC_ADDRESS_ROOT_DEFAULT; oscPort = OSC_PORT_DEFAULT; // load settings from file ofXml xml; xml.load("settings_kinect.xml"); xml.setTo("KinectOSC"); oscDestination = xml.getValue("ip"); oscPort = ofToInt(xml.getValue("port")); oscAddress = xml.getValue("address"); // setup kinect kinect.setup(); kinect.addDepthGenerator(); kinect.addUserGenerator(); kinect.setMaxNumUsers(1); kinect.start(); // addresses + setup osc osc.setup(oscDestination, oscPort); // setup gui gui.setName("KinectOSC"); gui.addToggle("2d-projective", &sendScreen); gui.addToggle("normalize", &normalize); } //-------------------------------------------------------------- void ofApp::update(){ kinect.update(); if (!kinect.isNewFrame()) return; // trick to reset user generator if no tracked users found if (kinect.getNumTrackedUsers() > 0) { hadUsers = true; } else if (kinect.getNumTrackedUsers() == 0 && hadUsers){ hadUsers = false; kinect.setPaused(true); kinect.removeUserGenerator(); kinect.addUserGenerator(); kinect.setPaused(false); } if (kinect.getNumTrackedUsers() == 0) return; ofxOscMessage msg; msg.setAddress(oscAddress); ofxOpenNIUser & user = kinect.getTrackedUser(0); ofPoint torso = user.getJoint((Joint) 0).getWorldPosition(); // send screen coordinates if (sendScreen) { torso = user.getJoint((Joint) 0).getProjectivePosition(); for (int j=0; j<user.getNumJoints(); j++) { ofxOpenNIJoint & joint = user.getJoint((Joint) j); ofPoint p = joint.getProjectivePosition(); if (normalize) { msg.addFloatArg(p.x-torso.x); msg.addFloatArg(p.y-torso.y); } else { msg.addFloatArg(p.x); msg.addFloatArg(p.y); } } } // or else send real world coordinates else { for (int j=0; j<user.getNumJoints(); j++) { ofxOpenNIJoint & joint = user.getJoint((Joint) j); ofPoint w = joint.getWorldPosition(); if (normalize) { msg.addFloatArg(w.x-torso.x); msg.addFloatArg(w.y-torso.y); msg.addFloatArg(w.z-torso.z); } else { msg.addFloatArg(w.x); msg.addFloatArg(w.y); msg.addFloatArg(w.z); } } } osc.sendMessage(msg); oscMessageString = "Sending OSC to "+oscDestination+", port "+ofToString(oscPort)+": address "+oscAddress+" -> "+ofToString(msg.getNumArgs())+" values"; } //-------------------------------------------------------------- void ofApp::draw(){ ofBackground(0); ofSetColor(255); if (debug) { kinect.drawDepth(ofGetWidth() - 320, 0, 320, 240); } // draw skeleton if (kinect.getNumTrackedUsers() > 0) { kinect.drawSkeleton(0); } ofDrawBitmapStringHighlight(oscMessageString, 15, ofGetHeight() - 4); } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ if (key=='d') { debug = !debug; } } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseEntered(int x, int y){ } //-------------------------------------------------------------- void ofApp::mouseExited(int x, int y){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ }
411
0.701949
1
0.701949
game-dev
MEDIA
0.626751
game-dev
0.84138
1
0.84138
CrabNickolson/shadow_mario_plugin
3,392
ShadowMario/MarioResources.cs
using BepInEx; using BepInEx.Unity.IL2CPP; using System.IO; using System.Linq; using UnityEngine; namespace ShadowMario; internal static class MarioResources { public static byte[] romFile { get; private set; } public static AssetBundle assetBundle { get; private set; } private const string c_romFileName = "baserom.us.z64"; private const string c_bundleFileName = "sm64data.bundle"; private const string c_materialName = "defaultmario.mat"; private const string c_shadowName = "shadow.prefab"; private const string c_shadowSquareName = "shadow_square.prefab"; private const string c_coinName = "coin_vis.prefab"; private const string c_starName = "star_vis.prefab"; private const string c_obstacleColliderName = "obstacle_collider.prefab"; private const string c_obstacleIceName = "obstacle_ice.prefab"; private const string c_obstacleLavaName = "obstacle_lava.prefab"; private const string c_blockFlyName = "block_vis_fly.prefab"; private const string c_blockMetalName = "block_vis_metal.prefab"; public static bool Init() { string romPath = findPluginFile(c_romFileName); if (string.IsNullOrEmpty(romPath) || !File.Exists(romPath)) { Plugin.PluginLog.LogError($"Rom file {c_romFileName} does not exist! You need to manually copy this file to the plugin folder."); return false; } romFile = File.ReadAllBytes(romPath); string bundlePath = findPluginFile(c_bundleFileName); assetBundle = AssetBundle.LoadFromFile(bundlePath); if (assetBundle == null) { Plugin.PluginLog.LogError($"Failed to load bundle file {c_bundleFileName}!"); return false; } foreach (var name in assetBundle.GetAllAssetNames()) { Plugin.PluginLog.LogInfo(name); } return true; } private static string findPluginFile(string _fileName) { return Directory.GetFiles(Paths.PluginPath, _fileName, SearchOption.AllDirectories).FirstOrDefault(); } private static void throwIfAssetDoesNotExist(string _name) { if (!assetBundle.Contains(_name)) throw new System.InvalidOperationException($"Mario Asset bundle does not contain asset {_name}!"); } private static T loadAsset<T>(string _name) where T : UnityEngine.Object { throwIfAssetDoesNotExist(_name); return assetBundle.LoadAsset(_name).TryCast<T>(); } public static Material LoadMarioMaterial() => loadAsset<Material>(c_materialName); public static GameObject LoadShadowPrefab(bool _isSquare) => loadAsset<GameObject>(_isSquare ? c_shadowSquareName : c_shadowName); public static GameObject LoadCoinPrefab() => loadAsset<GameObject>(c_coinName); public static GameObject LoadStarPrefab() => loadAsset<GameObject>(c_starName); public static GameObject LoadObstacleColliderPrefab() => loadAsset<GameObject>(c_obstacleColliderName); public static GameObject LoadObstacleIcePrefab() => loadAsset<GameObject>(c_obstacleIceName); public static GameObject LoadObstacleLavaPrefab() => loadAsset<GameObject>(c_obstacleLavaName); public static GameObject LoadBlockFlyPrefab() => loadAsset<GameObject>(c_blockFlyName); public static GameObject LoadBlockMetalPrefab() => loadAsset<GameObject>(c_blockMetalName); }
411
0.74241
1
0.74241
game-dev
MEDIA
0.969376
game-dev
0.753299
1
0.753299
PiantinaTheDev/XynisClient
2,381
exploits-methods/ConsoleSpammer.java
package us.whitedev.exploits.impl; import java.util.List; import java.util.Locale; import us.whitedev.commands.impl.ExploitCommand; import us.whitedev.commands.impl.ExploitCommand.SpammerMode; import us.whitedev.exploits.Exploit; import us.whitedev.helpers.PacketHelper; import us.whitedev.utils.OptionType; import us.whitedev.utils.OptionUtil; public class ConsoleSpammer implements Exploit { private static final String EXPLOIT_NAME = "ConsoleSpammer"; public void onExploit(String[] args) { int power = Integer.parseInt(args[2]); String mode = args[3]; this.setExploitMode(mode); if (ExploitCommand.SPAMMERMODE == SpammerMode.MVC) { msgHelper.sendMessage(String.format("Sending Exploit... &8[&f%s&8]", this.getName()), true); for(int i = 0; i < power; ++i) { PacketHelper.sendCommand("mvv"); } msgHelper.sendMessage("Exploit &asuccessfully &7sent!", true); } } private void setExploitMode(String mode) { try { SpammerMode spammerMode = SpammerMode.valueOf(mode.toUpperCase(Locale.ROOT)); if (ExploitCommand.SPAMMERMODE == SpammerMode.VEHICLE && spammerMode == ExploitCommand.SPAMMERMODE) { ExploitCommand.SPAMMERMODE = SpammerMode.DISABLED; msgHelper.sendMessage(String.format("Exploit &7successfully &cunloaded&7! &8[&f%s&8]", mode), true); } else { ExploitCommand.SPAMMERMODE = spammerMode; msgHelper.sendMessage(String.format("Exploit &7successfully &aloaded&7! &8[&f%s&8]", mode), true); if (ExploitCommand.SPAMMERMODE == SpammerMode.VEHICLE) { msgHelper.sendMessage("Waiting for the player to get into some vehicle...", true); } } } catch (IllegalArgumentException var3) { msgHelper.sendMessage("This Spammer Mode &cdoesnt exist&7!", true); msgHelper.sendMessage("All Modes&8: &fMVC, VEHICLE", true); } } public String getName() { return "ConsoleSpammer"; } public List<OptionUtil> getOptions() { return List.of(new OptionUtil("Power", OptionType.INTEGER), new OptionUtil("Mode", OptionType.LIST, new String[]{"Mvc", "Vehicle"})); } public String getArgsUsage() { return "power[1000] mode[Mvc]"; } public String getDescription() { return "Console Spammer"; } }
411
0.823613
1
0.823613
game-dev
MEDIA
0.888493
game-dev
0.819153
1
0.819153
Exiled-Team/EXILED
9,270
Exiled.Events/Features/Event{T}.cs
// ----------------------------------------------------------------------- // <copyright file="Event{T}.cs" company="Exiled Team"> // Copyright (c) Exiled Team. All rights reserved. // Licensed under the CC BY-SA 3.0 license. // </copyright> // ----------------------------------------------------------------------- namespace Exiled.Events.Features { using System; using System.Collections.Generic; using System.Linq; using Exiled.API.Features; using Exiled.Events.EventArgs.Interfaces; using MEC; /// <summary> /// The custom <see cref="EventHandler"/> delegate. /// </summary> /// <typeparam name="TEventArgs">The <see cref="EventHandler{TEventArgs}"/> type.</typeparam> /// <param name="ev">The <see cref="EventHandler{TEventArgs}"/> instance.</param> public delegate void CustomEventHandler<TEventArgs>(TEventArgs ev); /// <summary> /// The custom <see cref="EventHandler"/> delegate. /// </summary> /// <typeparam name="TEventArgs">The <see cref="EventHandler{TEventArgs}"/> type.</typeparam> /// <param name="ev">The <see cref="EventHandler{TEventArgs}"/> instance.</param> /// <returns><see cref="IEnumerator{T}"/> of <see cref="float"/>.</returns> public delegate IEnumerator<float> CustomAsyncEventHandler<TEventArgs>(TEventArgs ev); /// <summary> /// An implementation of the <see cref="IExiledEvent"/> interface that encapsulates an event with arguments. /// </summary> /// <typeparam name="T">The specified <see cref="EventArgs"/> that the event will use.</typeparam> public class Event<T> : IExiledEvent { private static readonly Dictionary<Type, Event<T>> TypeToEvent = new(); private bool patched; /// <summary> /// Initializes a new instance of the <see cref="Event{T}"/> class. /// </summary> public Event() { TypeToEvent.Add(typeof(T), this); } private event CustomEventHandler<T> InnerEvent; private event CustomAsyncEventHandler<T> InnerAsyncEvent; /// <summary> /// Gets a <see cref="IReadOnlyCollection{T}"/> of <see cref="Event{T}"/> which contains all the <see cref="Event{T}"/> instances. /// </summary> public static IReadOnlyDictionary<Type, Event<T>> Dictionary => TypeToEvent; /// <summary> /// Subscribes a target <see cref="CustomEventHandler{TEventArgs}"/> to the inner event and checks if patching is possible, if dynamic patching is enabled. /// </summary> /// <param name="event">The <see cref="Event{T}"/> the <see cref="CustomEventHandler{T}"/> will be subscribed to.</param> /// <param name="handler">The <see cref="CustomEventHandler{T}"/> that will be subscribed to the <see cref="Event{T}"/>.</param> /// <returns>The <see cref="Event{T}"/> with the handler subscribed to it.</returns> public static Event<T> operator +(Event<T> @event, CustomEventHandler<T> handler) { @event.Subscribe(handler); return @event; } /// <summary> /// Subscribes a <see cref="CustomAsyncEventHandler"/> to the inner event, and checks patches if dynamic patching is enabled. /// </summary> /// <param name="event">The <see cref="Event{T}"/> to subscribe the <see cref="CustomAsyncEventHandler{T}"/> to.</param> /// <param name="asyncEventHandler">The <see cref="CustomAsyncEventHandler{T}"/> to subscribe to the <see cref="Event{T}"/>.</param> /// <returns>The <see cref="Event{T}"/> with the handler added to it.</returns> public static Event<T> operator +(Event<T> @event, CustomAsyncEventHandler<T> asyncEventHandler) { @event.Subscribe(asyncEventHandler); return @event; } /// <summary> /// Unsubscribes a target <see cref="CustomEventHandler{TEventArgs}"/> from the inner event and checks if unpatching is possible, if dynamic patching is enabled. /// </summary> /// <param name="event">The <see cref="Event{T}"/> the <see cref="CustomEventHandler{T}"/> will be unsubscribed from.</param> /// <param name="handler">The <see cref="CustomEventHandler{T}"/> that will be unsubscribed from the <see cref="Event{T}"/>.</param> /// <returns>The <see cref="Event{T}"/> with the handler unsubscribed from it.</returns> public static Event<T> operator -(Event<T> @event, CustomEventHandler<T> handler) { @event.Unsubscribe(handler); return @event; } /// <summary> /// Unsubscribes a target <see cref="CustomAsyncEventHandler{TEventArgs}"/> from the inner event, and checks if unpatching is possible, if dynamic patching is enabled. /// </summary> /// <param name="event">The <see cref="Event"/> the <see cref="CustomAsyncEventHandler{T}"/> will be unsubscribed from.</param> /// <param name="asyncEventHandler">The <see cref="CustomAsyncEventHandler{T}"/> that will be unsubscribed from the <see cref="Event{T}"/>.</param> /// <returns>The <see cref="Event{T}"/> with the handler unsubscribed from it.</returns> public static Event<T> operator -(Event<T> @event, CustomAsyncEventHandler<T> asyncEventHandler) { @event.Unsubscribe(asyncEventHandler); return @event; } /// <summary> /// Subscribes a target <see cref="CustomEventHandler{T}"/> to the inner event if the conditional is true. /// </summary> /// <param name="handler">The handler to add.</param> public void Subscribe(CustomEventHandler<T> handler) { Log.Assert(Events.Instance is not null, $"{nameof(Events.Instance)} is null, please ensure you have exiled_events enabled!"); if (Events.Instance.Config.UseDynamicPatching && !patched) { Events.Instance.Patcher.Patch(this); patched = true; } InnerEvent += handler; } /// <summary> /// Subscribes a target <see cref="CustomAsyncEventHandler{T}"/> to the inner event if the conditional is true. /// </summary> /// <param name="handler">The handler to add.</param> public void Subscribe(CustomAsyncEventHandler<T> handler) { Log.Assert(Events.Instance is not null, $"{nameof(Events.Instance)} is null, please ensure you have exiled_events enabled!"); if (Events.Instance.Config.UseDynamicPatching && !patched) { Events.Instance.Patcher.Patch(this); patched = true; } InnerAsyncEvent += handler; } /// <summary> /// Unsubscribes a target <see cref="CustomEventHandler{T}"/> from the inner event if the conditional is true. /// </summary> /// <param name="handler">The handler to add.</param> public void Unsubscribe(CustomEventHandler<T> handler) { InnerEvent -= handler; } /// <summary> /// Unsubscribes a target <see cref="CustomEventHandler{T}"/> from the inner event if the conditional is true. /// </summary> /// <param name="handler">The handler to add.</param> public void Unsubscribe(CustomAsyncEventHandler<T> handler) { InnerAsyncEvent -= handler; } /// <summary> /// Executes all <see cref="CustomEventHandler{TEventArgs}"/> listeners safely. /// </summary> /// <param name="arg">The event argument.</param> /// <exception cref="ArgumentNullException">Event or its arg is <see langword="null"/>.</exception> public void InvokeSafely(T arg) { InvokeNormal(arg); InvokeAsync(arg); } /// <inheritdoc cref="InvokeSafely"/> internal void InvokeNormal(T arg) { if (InnerEvent is null) return; foreach (CustomEventHandler<T> handler in InnerEvent.GetInvocationList().Cast<CustomEventHandler<T>>()) { try { handler(arg); } catch (Exception ex) { Log.Error($"Method \"{handler.Method.Name}\" of the class \"{handler.Method.ReflectedType.FullName}\" caused an exception when handling the event \"{GetType().FullName}\"\n{ex}"); } } } /// <inheritdoc cref="InvokeSafely"/> internal void InvokeAsync(T arg) { if (InnerAsyncEvent is null) return; foreach (CustomAsyncEventHandler<T> handler in InnerAsyncEvent.GetInvocationList().Cast<CustomAsyncEventHandler<T>>()) { try { Timing.RunCoroutine(handler(arg)); } catch (Exception ex) { Log.Error($"Method \"{handler.Method.Name}\" of the class \"{handler.Method.ReflectedType.FullName}\" caused an exception when handling the event \"{GetType().FullName}\"\n{ex}"); } } } } }
411
0.872169
1
0.872169
game-dev
MEDIA
0.275459
game-dev
0.836845
1
0.836845
coronalabs/corona
4,824
librtt/Rtt_LuaProxy.h
////////////////////////////////////////////////////////////////////////////// // // This file is part of the Corona game engine. // For overview and more information on licensing please refer to README.md // Home page: https://github.com/coronalabs/corona // Contact: support@coronalabs.com // ////////////////////////////////////////////////////////////////////////////// #ifndef _Rtt_LuaProxy_H__ #define _Rtt_LuaProxy_H__ // ---------------------------------------------------------------------------- struct lua_State; struct luaL_Reg; namespace Rtt { class LuaProxyVTable; class MLuaProxyable; // ---------------------------------------------------------------------------- class LuaProxyConstant { public: typedef LuaProxyConstant Self; public: static Self* GetProxy( lua_State *L, int index ); static const MLuaProxyable& NullProxyableObject(); static int __index( lua_State *L ); static int __gcMeta( lua_State *L ); public: static void Initialize( lua_State *L ); public: LuaProxyConstant( lua_State *L, const LuaProxyVTable& proxyMt ); virtual ~LuaProxyConstant(); public: Rtt_FORCE_INLINE const LuaProxyVTable& Delegate() const { return fDelegate; } void Push( lua_State *L ) const; private: const LuaProxyVTable& fDelegate; private: static const char kProxyKey[]; static const luaL_Reg kMetatable[]; }; // ---------------------------------------------------------------------------- // USAGE: // LuaProxy was designed to support exporting C++ object hierarchies to Lua // Our main use case is DisplayObjects. Ultimately, the lua code sees a normal // lua table that represents the proxy (which yields access to the DisplayObject). // One of the fields in the table is _proxy, which is a LuaProxy instance. // // There is some trickiness here b/c of memory mgmt: // // On the lua side, as long as there are references to this lua table, // we cannot dispose of the C++ object (the _proxy userdata) that it references. // // On the C++ side, the contents of this table must be persistent. Consider // the situation where, on the lua side, other properties are added to the // lua table, but the reference to that table was local, so it gets GC'd. // Later in a different scope, the lua code attempts to access a table that // represents the same DisplayObject. The table we get better have those // other properties persist! Our solution is to have LuaProxy luaL_ref() // the table *whenever* the DisplayObject is on the display list. class LuaProxy { public: typedef LuaProxy Self; public: static bool IsProxy(lua_State *L, int index); static LuaProxy* GetProxy( lua_State *L, int index ); static Self* GetProxyMeta( lua_State *L, int index ); static MLuaProxyable* GetProxyableObject( lua_State *L, int index ); // static int luaopen_proxy( lua_State *L ); static int __proxyindex( lua_State *L ); static int __proxynewindex( lua_State *L ); static int __proxyregister( lua_State *L ); // static int __proxylen( lua_State *L ); static int __gcMeta( lua_State *L ); public: static void Initialize( lua_State *L ); public: LuaProxy( lua_State *L, MLuaProxyable& object, const LuaProxyVTable& proxyMt, const char* className ); virtual ~LuaProxy(); protected: void CreateTable( lua_State *L, const char* className ); public: // Restores table (ref'd by fTableRef) back to a plain table (i.e. resets // metatable, resets reserved properties, etc). Also does equivalent of // Release() void RestoreTable( lua_State *L ); protected: // Releases reference to the MLuaProxyable object. Used when Lua calls // LuaProxy's __gc metamethod. void Release(); public: void AcquireTableRef( lua_State *L ); void ReleaseTableRef( lua_State *L ); public: Rtt_INLINE void Invalidate() { fObject = NULL; } Rtt_INLINE MLuaProxyable* Object() const { return fObject; } Rtt_INLINE int TableRef() const { return fTableRef; } Rtt_INLINE const LuaProxyVTable& Delegate() const { return fDelegate; } // Push associated table on stack. Nothing is pushed when returning false. bool PushTable( lua_State *L ) const; public: const LuaProxyVTable* GetExtensionsDelegate() const { return fExtensionsDelegate; } void SetExtensionsDelegate( const LuaProxyVTable *newValue ) { fExtensionsDelegate = newValue; } private: MLuaProxyable* fObject; const LuaProxyVTable& fDelegate; const LuaProxyVTable *fExtensionsDelegate; int fTableRef; // id for associated Lua table that wraps this proxy private: static const char kProxyKey[]; static const luaL_Reg kMetatable[]; }; // ---------------------------------------------------------------------------- } // namespace Rtt // ---------------------------------------------------------------------------- #endif // _Rtt_Matrix_H__
411
0.86791
1
0.86791
game-dev
MEDIA
0.388178
game-dev
0.579223
1
0.579223
Clowfoe/UPDOG-WEEK1-PUBLIC
3,177
source/funkin/states/AchievementsMenuState.hx
package funkin.states; import flixel.FlxSprite; import flixel.addons.display.FlxGridOverlay; import flixel.group.FlxGroup.FlxTypedGroup; using StringTools; class AchievementsMenuState extends MusicBeatState { #if ACHIEVEMENTS_ALLOWED var options:Array<String> = []; private var grpOptions:FlxTypedGroup<Alphabet>; private static var curSelected:Int = 0; private var achievementArray:Array<AttachedAchievement> = []; private var achievementIndex:Array<Int> = []; private var descText:FlxText; override function create() { #if desktop DiscordClient.changePresence("Achievements Menu", null); #end var menuBG:FlxSprite = new FlxSprite().loadGraphic(Paths.image('menuBGBlue')); menuBG.setGraphicSize(Std.int(menuBG.width * 1.1)); menuBG.updateHitbox(); menuBG.screenCenter(); menuBG.antialiasing = ClientPrefs.globalAntialiasing; add(menuBG); grpOptions = new FlxTypedGroup<Alphabet>(); add(grpOptions); Achievements.loadAchievements(); for (i in 0...Achievements.achievementsStuff.length) { if (!Achievements.achievementsStuff[i][3] || Achievements.achievementsMap.exists(Achievements.achievementsStuff[i][2])) { options.push(Achievements.achievementsStuff[i]); achievementIndex.push(i); } } for (i in 0...options.length) { var achieveName:String = Achievements.achievementsStuff[achievementIndex[i]][2]; var optionText:Alphabet = new Alphabet(0, (100 * i) + 210, Achievements.isAchievementUnlocked(achieveName) ? Achievements.achievementsStuff[achievementIndex[i]][0] : '?', false, false); optionText.isMenuItem = true; optionText.x += 280; optionText.xAdd = 200; optionText.targetY = i; grpOptions.add(optionText); var icon:AttachedAchievement = new AttachedAchievement(optionText.x - 105, optionText.y, achieveName); icon.sprTracker = optionText; achievementArray.push(icon); add(icon); } descText = new FlxText(150, 600, 980, "", 32); descText.setFormat(Paths.font("vcr.ttf"), 32, FlxColor.WHITE, CENTER, FlxTextBorderStyle.OUTLINE, FlxColor.BLACK); descText.scrollFactor.set(); descText.borderSize = 2.4; add(descText); changeSelection(); super.create(); } override function update(elapsed:Float) { super.update(elapsed); if (controls.UI_UP_P) { changeSelection(-1); } if (controls.UI_DOWN_P) { changeSelection(1); } if (controls.BACK) { FlxG.sound.play(Paths.sound('cancelMenu')); FlxG.switchState(new TitleState()); } } function changeSelection(change:Int = 0) { curSelected += change; if (curSelected < 0) curSelected = options.length - 1; if (curSelected >= options.length) curSelected = 0; var bullShit:Int = 0; for (item in grpOptions.members) { item.targetY = bullShit - curSelected; bullShit++; item.alpha = 0.6; if (item.targetY == 0) { item.alpha = 1; } } for (i in 0...achievementArray.length) { achievementArray[i].alpha = 0.6; if (i == curSelected) { achievementArray[i].alpha = 1; } } descText.text = Achievements.achievementsStuff[achievementIndex[curSelected]][1]; FlxG.sound.play(Paths.sound('scrollMenu'), 0.4); } #end }
411
0.878468
1
0.878468
game-dev
MEDIA
0.705941
game-dev,desktop-app
0.963591
1
0.963591
goldeneye-source/ges-code
1,122
public/arraystack.h
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $Workfile: $ // $Date: $ // //----------------------------------------------------------------------------- // $Log: $ // // $NoKeywords: $ //=============================================================================// #ifndef ARRAYSTACK_H #define ARRAYSTACK_H #pragma once #include <assert.h> #include "List.h" template <class T> class ArrayStack { protected: T *data; int m_stackDepth; int m_maxNumElements; public: ArrayStack( int maxNumElements ) { data = new T[maxNumElements]; m_maxNumElements = maxNumElements; m_stackDepth = 0; assert( data ); } void Push( T elem ) { data[m_stackDepth++] = elem; if( m_stackDepth > m_maxNumElements ) { printf( "ArrayStack overflow\n" ); assert( 0 ); } } T Pop( void ) { if( m_stackDepth == 0 ) { printf( "ArrayStack underflow\n" ); assert( 0 ); } return data[--m_stackDepth]; } bool IsEmpty() { return ( m_stackDepth == 0 ); } int GetDepth() { return m_stackDepth; } }; #endif // ARRAYSTACK_H
411
0.760309
1
0.760309
game-dev
MEDIA
0.444428
game-dev,graphics-rendering
0.916679
1
0.916679
at-wat/neonavigation
16,650
trajectory_tracker/test/src/test_path2d.cpp
/* * Copyright (c) 2018, the neonavigation authors * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <algorithm> #include <cmath> #include <cstddef> #include <limits> #include <string> #include <vector> #include <gtest/gtest.h> #include <nav_msgs/Path.h> #include <trajectory_tracker/eigen_line.h> #include <trajectory_tracker/path2d.h> #include <trajectory_tracker_msgs/PathWithVelocity.h> namespace { double getRemainedDistance(const trajectory_tracker::Path2D& path, const Eigen::Vector2d& p) { const auto nearest = path.findNearest(path.begin(), path.end(), p); const Eigen::Vector2d pos_on_line = trajectory_tracker::projection2d((nearest - 1)->pos_, nearest->pos_, p); return path.remainedDistance(path.begin(), nearest, path.end(), pos_on_line); } } // namespace TEST(Path2D, RemainedDistance) { trajectory_tracker::Path2D path_full; for (double x = 0.0; x < 10.0 - 1e-3; x += 0.2) path_full.push_back(trajectory_tracker::Pose2D(Eigen::Vector2d(x, 0), 0, 1)); path_full.push_back(trajectory_tracker::Pose2D(Eigen::Vector2d(10.0, 0), 0, 1)); // Single pose path means orientation control mode. More than two poses should be line following. for (size_t l = 2; l < path_full.size(); ++l) { trajectory_tracker::Path2D path; path.resize(l); std::copy(path_full.end() - l, path_full.end(), path.begin()); std::string err_msg = "failed for " + std::to_string(l) + " pose(s) path"; ASSERT_NEAR(getRemainedDistance(path, Eigen::Vector2d(0, 0)), 10.0, 1e-2) << err_msg; ASSERT_NEAR(getRemainedDistance(path, Eigen::Vector2d(8.25, 0)), 1.75, 1e-2) << err_msg; ASSERT_NEAR(getRemainedDistance(path, Eigen::Vector2d(10.25, 0)), -0.25, 1e-2) << err_msg; ASSERT_NEAR(getRemainedDistance(path, Eigen::Vector2d(8.25, 0.1)), 1.75, 1e-2) << err_msg; ASSERT_NEAR(getRemainedDistance(path, Eigen::Vector2d(8.25, -0.1)), 1.75, 1e-2) << err_msg; ASSERT_NEAR(getRemainedDistance(path, Eigen::Vector2d(10.25, 0.1)), -0.25, 1e-2) << err_msg; ASSERT_NEAR(getRemainedDistance(path, Eigen::Vector2d(10.25, -0.1)), -0.25, 1e-2) << err_msg; } } TEST(Path2D, Curvature) { for (float c = 1.0; c < 4.0; c += 0.4) { trajectory_tracker::Path2D path; for (double a = 0; a < 1.57; a += 0.1) path.push_back(trajectory_tracker::Pose2D(Eigen::Vector2d(std::cos(a), std::sin(a)) * c, a + M_PI / 2, 1)); ASSERT_NEAR(path.getCurvature(path.begin(), path.end(), path[0].pos_, 10.0), 1.0 / c, 1e-2); } for (float c = 1.0; c < 4.0; c += 0.4) { trajectory_tracker::Path2D path; for (double a = 0; a < 0.2; a += 0.1) path.push_back(trajectory_tracker::Pose2D(Eigen::Vector2d(std::cos(a), std::sin(a)) * c, a + M_PI / 2, 1)); ASSERT_NEAR(path.getCurvature(path.begin(), path.end(), path[0].pos_, 10.0), 1.0 / c, 1e-2); } } TEST(Path2D, LocalGoalWithoutSwitchBack) { for (int yaw_i = -1; yaw_i <= 1; ++yaw_i) { const double yaw_diff = yaw_i * 0.1; trajectory_tracker::Path2D path; Eigen::Vector2d p(0, 0); double yaw(0); for (int i = 0; i < 10; ++i) { p -= Eigen::Vector2d(std::cos(yaw), std::sin(yaw)) * 0.1; yaw += yaw_diff; path.push_back(trajectory_tracker::Pose2D(p, yaw, 1)); } ASSERT_EQ(path.findLocalGoal(path.begin(), path.end(), true), path.end()); ASSERT_EQ(path.findLocalGoal(path.begin(), path.end(), false), path.end()); } } TEST(Path2D, LocalGoalWithSwitchBack) { for (int yaw_i = -1; yaw_i <= 1; ++yaw_i) { const double yaw_diff = yaw_i * 0.1; trajectory_tracker::Path2D path; Eigen::Vector2d p(0, 0); double yaw(0); for (int i = 0; i < 5; ++i) { p -= Eigen::Vector2d(std::cos(yaw), std::sin(yaw)) * 0.1; yaw += yaw_diff; path.push_back(trajectory_tracker::Pose2D(p, yaw, 1)); } for (int i = 0; i < 5; ++i) { p += Eigen::Vector2d(std::cos(yaw), std::sin(yaw)) * 0.1; yaw += yaw_diff; path.push_back(trajectory_tracker::Pose2D(p, yaw, 1)); } { const auto it_local_goal = path.findLocalGoal(path.begin(), path.end(), true, true); ASSERT_EQ(it_local_goal, path.begin() + 5); ASSERT_EQ(path.findLocalGoal(it_local_goal, path.end(), true, true), path.end()); } { const auto it_local_goal = path.findLocalGoal(path.begin(), path.end(), true, false); ASSERT_EQ(it_local_goal, path.begin() + 5); ASSERT_EQ(path.findLocalGoal(it_local_goal, path.end(), true, false), path.end()); } // no switch back motion under (allow_switchback == false) ASSERT_EQ(path.findLocalGoal(path.begin(), path.end(), false, true), path.end()); } } TEST(Path2D, LocalGoalTest) { trajectory_tracker::Path2D path; Eigen::Vector2d p(0, 0); for (size_t i = 0; i <= 10; ++i) { const double yaw = M_PI / 2 / 10; p.x() = std::sin(i * yaw); p.y() = 1.0 - std::cos(i * yaw); path.push_back(trajectory_tracker::Pose2D(p, yaw, 0)); } // Turn in-place and go back for (size_t i = 0; i <= 10; ++i) { path.push_back(trajectory_tracker::Pose2D(Eigen::Vector2d(1.0 - i * 0.1, 1.0), 0, 0)); } { const auto it_local_goal = path.findLocalGoal(path.begin(), path.end(), true, true); ASSERT_EQ(it_local_goal, path.begin() + 11); ASSERT_EQ(path.findLocalGoal(it_local_goal, path.end(), true, true), path.end()); } { ASSERT_EQ(path.findLocalGoal(path.begin(), path.end(), true, false), path.end()); } } TEST(Path2D, EnumerateLocalGoals) { trajectory_tracker::Path2D path; const std::vector<float> yaws = {0.5, -0.2, 1.0}; double x = 0.0; double y = 0.0; for (const float yaw : yaws) { for (size_t i = 0; i < 10; ++i) { path.push_back(trajectory_tracker::Pose2D(Eigen::Vector2d(x, y), yaw, 1.0)); x += std::cos(yaw) * 0.1; y += std::sin(yaw) * 0.1; } path.push_back(trajectory_tracker::Pose2D(Eigen::Vector2d(x, y), yaw, 1.0)); } path.push_back(trajectory_tracker::Pose2D(Eigen::Vector2d(x, y), 0.3, 1.0)); const auto local_goals = path.enumerateLocalGoals(path.begin(), path.end(), true); ASSERT_EQ(local_goals.size(), 3); ASSERT_EQ(local_goals.at(0) - path.begin(), 11); ASSERT_EQ(local_goals.at(1) - path.begin(), 22); ASSERT_EQ(local_goals.at(2) - path.begin(), 33); } TEST(Path2D, FindNearestWithDistance) { trajectory_tracker::Path2D path; path.push_back(trajectory_tracker::Pose2D(Eigen::Vector2d(0.5, 0.5), 0, 1)); path.push_back(trajectory_tracker::Pose2D(Eigen::Vector2d(0.6, 0.5), 0, 1)); path.push_back(trajectory_tracker::Pose2D(Eigen::Vector2d(0.7, 0.5), 0, 1)); path.push_back(trajectory_tracker::Pose2D(Eigen::Vector2d(0.8, 0.6), M_PI / 4, 1)); path.push_back(trajectory_tracker::Pose2D(Eigen::Vector2d(0.9, 0.7), M_PI / 4, 1)); path.push_back(trajectory_tracker::Pose2D(Eigen::Vector2d(0.9, 0.8), M_PI / 2, 1)); path.push_back(trajectory_tracker::Pose2D(Eigen::Vector2d(0.9, 0.9), M_PI / 2, 1)); { // The nearest line is (0.8, 0.6) - (0.9, 0.7), and the nearest point on the line is (0.85, 0.65). const auto nearest_with_dist = path.findNearestWithDistance(path.begin(), path.end(), Eigen::Vector2d(1.0, 0.5)); EXPECT_EQ(nearest_with_dist.first, path.begin() + 4); EXPECT_NEAR(nearest_with_dist.second, std::sqrt(std::pow(1.0 - 0.85, 2) + std::pow(0.5 - 0.65, 2)), 1.0e-6); } { // The nearest point is (0.7, 0.5). const auto nearest_with_dist = path.findNearestWithDistance(path.begin(), path.begin() + 3, Eigen::Vector2d(1.0, 0.5)); EXPECT_EQ(nearest_with_dist.first, path.begin() + 2); EXPECT_NEAR(nearest_with_dist.second, std::sqrt(std::pow(1.0 - 0.7, 2) + std::pow(0.5 - 0.5, 2)), 1.0e-6); } { // Test edge cases const auto nearest_with_dist = path.findNearestWithDistance(path.begin() + 5, path.begin() + 5, Eigen::Vector2d(1.0, 0.5)); EXPECT_EQ(nearest_with_dist.first, path.begin() + 5); EXPECT_NEAR(nearest_with_dist.second, std::sqrt(std::pow(1.0 - 0.9, 2) + std::pow(0.5 - 0.8, 2)), 1.0e-6); const auto invalid_result = path.findNearestWithDistance(path.end(), path.end(), Eigen::Vector2d(1.0, 0.5)); EXPECT_EQ(invalid_result.first, path.end()); EXPECT_EQ(invalid_result.second, std::numeric_limits<double>::max()); } } TEST(Path2D, Conversions) { nav_msgs::Path path_msg_org; path_msg_org.poses.resize(8); path_msg_org.poses[0].pose.position.x = 0.0; path_msg_org.poses[0].pose.position.y = 0.0; path_msg_org.poses[0].pose.orientation.w = 1.0; path_msg_org.poses[1].pose.position.x = 1.0; // Start of in-place turning path_msg_org.poses[1].pose.position.y = 0.0; path_msg_org.poses[1].pose.orientation.w = 1.0; path_msg_org.poses[2].pose.position.x = 1.0; path_msg_org.poses[2].pose.position.y = 0.0; path_msg_org.poses[2].pose.orientation.z = std::sin(M_PI / 8); path_msg_org.poses[2].pose.orientation.w = std::cos(M_PI / 8); path_msg_org.poses[3].pose.position.x = 1.0; // End of in-place turning path_msg_org.poses[3].pose.position.y = 0.0; path_msg_org.poses[3].pose.orientation.z = std::sin(M_PI / 4); path_msg_org.poses[3].pose.orientation.w = std::cos(M_PI / 4); path_msg_org.poses[4].pose.position.x = 1.0; path_msg_org.poses[4].pose.position.y = 1.0; path_msg_org.poses[4].pose.orientation.z = std::sin(M_PI / 4); path_msg_org.poses[4].pose.orientation.w = std::cos(M_PI / 4); path_msg_org.poses[5].pose.position.x = 1.0; // Start of in-place turning path_msg_org.poses[5].pose.position.y = 2.0; path_msg_org.poses[5].pose.orientation.z = std::sin(M_PI / 4); path_msg_org.poses[5].pose.orientation.w = std::cos(M_PI / 4); path_msg_org.poses[6].pose.position.x = 1.0; path_msg_org.poses[6].pose.position.y = 2.0; path_msg_org.poses[6].pose.orientation.z = std::sin(M_PI / 4 + M_PI / 6); path_msg_org.poses[6].pose.orientation.w = std::cos(M_PI / 4 + M_PI / 6); path_msg_org.poses[7].pose.position.x = 1.0; // End of in-place turning path_msg_org.poses[7].pose.position.y = 2.0; path_msg_org.poses[7].pose.orientation.z = std::sin(M_PI / 4 + M_PI / 3); path_msg_org.poses[7].pose.orientation.w = std::cos(M_PI / 4 + M_PI / 3); trajectory_tracker::Path2D path; path.fromMsg(path_msg_org); const std::vector<size_t> expected_org_indexes = {0, 1, 3, 4, 5, 7}; ASSERT_EQ(path.size(), 6); for (size_t i = 0; i < path.size(); ++i) { const size_t org_index = expected_org_indexes[i]; EXPECT_EQ(path[i].pos_.x(), path_msg_org.poses[org_index].pose.position.x) << "i: " << i << " org: " << org_index; EXPECT_EQ(path[i].pos_.y(), path_msg_org.poses[org_index].pose.position.y) << "i: " << i << " org: " << org_index; EXPECT_NEAR(path[i].yaw_, tf2::getYaw(path_msg_org.poses[org_index].pose.orientation), 1.0e-6) << "i: " << i << " org: " << org_index; EXPECT_TRUE(std::isnan(path[i].velocity_)); } nav_msgs::Path path_msg; path_msg.header.frame_id = "map"; path_msg.header.stamp = ros::Time(123.456); path.toMsg(path_msg); ASSERT_EQ(path_msg.poses.size(), 6); for (size_t i = 0; i < path.size(); ++i) { EXPECT_EQ(path[i].pos_.x(), path_msg.poses[i].pose.position.x) << "i: " << i; EXPECT_EQ(path[i].pos_.y(), path_msg.poses[i].pose.position.y) << "i: " << i; EXPECT_NEAR(path[i].yaw_, tf2::getYaw(path_msg.poses[i].pose.orientation), 1.0e-6) << "i: " << i; EXPECT_EQ(path_msg.poses[i].header.frame_id, path_msg.header.frame_id); EXPECT_EQ(path_msg.poses[i].header.stamp, path_msg.header.stamp); } trajectory_tracker_msgs::PathWithVelocity path_with_vel_msg_org; path_with_vel_msg_org.poses.resize(path_msg_org.poses.size()); for (size_t i = 0; i < path_msg_org.poses.size(); ++i) { path_with_vel_msg_org.poses[i].pose = path_msg_org.poses[i].pose; path_with_vel_msg_org.poses[i].linear_velocity.x = i * 0.1; } trajectory_tracker::Path2D path_with_vel; path_with_vel.fromMsg(path_with_vel_msg_org); ASSERT_EQ(path_with_vel.size(), 6); for (size_t i = 0; i < path_with_vel.size(); ++i) { const size_t org_index = expected_org_indexes[i]; EXPECT_EQ(path_with_vel[i].pos_.x(), path_with_vel_msg_org.poses[org_index].pose.position.x) << "i: " << i << " org: " << org_index; EXPECT_EQ(path_with_vel[i].pos_.y(), path_with_vel_msg_org.poses[org_index].pose.position.y) << "i: " << i << " org: " << org_index; EXPECT_NEAR(path_with_vel[i].yaw_, tf2::getYaw(path_with_vel_msg_org.poses[org_index].pose.orientation), 1.0e-6) << "i: " << i << " org: " << org_index; EXPECT_NEAR(path_with_vel[i].velocity_, org_index * 0.1, 1.0e-6) << "i: " << i << " org: " << org_index; } trajectory_tracker_msgs::PathWithVelocity path_with_vel_msg; path_with_vel_msg.header.frame_id = "map"; path_with_vel_msg.header.stamp = ros::Time(123.456); path_with_vel.toMsg(path_with_vel_msg); ASSERT_EQ(path_with_vel_msg.poses.size(), 6); for (size_t i = 0; i < path_with_vel.size(); ++i) { EXPECT_EQ(path_with_vel[i].pos_.x(), path_with_vel_msg.poses[i].pose.position.x) << "i: " << i; EXPECT_EQ(path_with_vel[i].pos_.y(), path_with_vel_msg.poses[i].pose.position.y) << "i: " << i; EXPECT_NEAR(path_with_vel[i].yaw_, tf2::getYaw(path_with_vel_msg.poses[i].pose.orientation), 1.0e-6) << "i: " << i; EXPECT_EQ(path_with_vel_msg.poses[i].header.frame_id, path_with_vel_msg.header.frame_id); EXPECT_EQ(path_with_vel_msg.poses[i].header.stamp, path_with_vel_msg.header.stamp); } } TEST(Path2D, EstimatedTimeOfArrivals) { trajectory_tracker::Path2D path; // Straight path.push_back(trajectory_tracker::Pose2D(Eigen::Vector2d(0.0, 0.0), 135.0 / 180.0 * M_PI, 0)); path.push_back(trajectory_tracker::Pose2D(Eigen::Vector2d(0.1, -0.1), 135.0 / 180.0 * M_PI, 0)); path.push_back(trajectory_tracker::Pose2D(Eigen::Vector2d(0.2, -0.2), 135.0 / 180.0 * M_PI, 0)); // In-place-turn path.push_back(trajectory_tracker::Pose2D(Eigen::Vector2d(0.2, -0.2), -M_PI / 2, 0)); // Curve for (int i = 1; i <= 4; ++i) { const double angle = M_PI / 8 * i; path.push_back(trajectory_tracker::Pose2D( Eigen::Vector2d(0.2 * std::cos(angle), -0.2 + 0.2 * std::sin(angle)), -M_PI / 2 - angle, 0)); } const double linear_speed = 0.5; const double angular_speed = M_PI; const std::vector<double> etas = path.getEstimatedTimeOfArrivals(path.begin(), path.end(), linear_speed, angular_speed, 1.0); ASSERT_EQ(etas.size(), 8); double expected_eta = 1.0; EXPECT_NEAR(etas[0], expected_eta, 1.0e-6); expected_eta += std::hypot(0.1, 0.1) / linear_speed; EXPECT_NEAR(etas[1], expected_eta, 1.0e-6); expected_eta += std::hypot(0.1, 0.1) / linear_speed; EXPECT_NEAR(etas[2], expected_eta, 1.0e-6); expected_eta += 135.0 / (180.0 / M_PI) / angular_speed; EXPECT_NEAR(etas[3], expected_eta, 1.0e-6); const double turn_dist = std::hypot(0.2 - 0.2 * std::cos(M_PI / 8), 0.2 * std::sin(M_PI / 8)); for (size_t p = 4; p < etas.size(); ++p) { EXPECT_NEAR(etas[p], expected_eta + (p - 3) * turn_dist / linear_speed, 1.0e-6); } } int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
411
0.909972
1
0.909972
game-dev
MEDIA
0.264935
game-dev
0.877471
1
0.877471
Hydepwns/raxol
16,489
lib/raxol/animation/physics/physics_engine.ex
defmodule Raxol.Animation.Physics.PhysicsEngine do @moduledoc """ Physics engine for Raxol animations. Provides physics-based animation capabilities including: * Spring simulations * Gravity and bounce effects * Friction and damping * Collisions * Particle systems * Force fields These can be used to create natural, organic animations that respond to user interactions in a physically plausible way. """ alias Raxol.Animation.Physics.ForceField alias Raxol.Animation.Physics.Vector @type physics_object :: %{ id: String.t(), position: Vector.t(), velocity: Vector.t(), acceleration: Vector.t(), mass: float(), forces: [Vector.t()], constraints: map(), properties: map() } @type world_state :: %{ objects: %{String.t() => physics_object()}, gravity: Vector.t(), time_scale: float(), iteration: non_neg_integer(), boundaries: map(), force_fields: [ForceField.t()], # System time in milliseconds last_update: integer() } @doc """ Creates a new physics world with default values. """ def new_world do %{ objects: %{}, gravity: %Vector{x: +0.0, y: 9.8, z: +0.0}, time_scale: 1.0, iteration: 0, boundaries: %{ min_x: nil, max_x: nil, min_y: nil, max_y: nil, min_z: nil, max_z: nil }, force_fields: [], last_update: System.os_time(:millisecond) } end @doc """ Creates a new physics world with custom settings. """ def new_world(opts) do world = new_world() world |> Map.put(:gravity, Keyword.get(opts, :gravity, world.gravity)) |> Map.put(:time_scale, Keyword.get(opts, :time_scale, world.time_scale)) |> Map.put( :boundaries, Map.merge(world.boundaries, Keyword.get(opts, :boundaries, %{})) ) end @doc """ Creates a new physics object with the given properties. """ def new_object(id, opts \\ []) do %{ id: id, position: Keyword.get(opts, :position, %Vector{x: 0, y: 0, z: 0}), velocity: Keyword.get(opts, :velocity, %Vector{x: 0, y: 0, z: 0}), acceleration: %Vector{x: 0, y: 0, z: 0}, mass: Keyword.get(opts, :mass, 1.0), forces: [], constraints: Keyword.get(opts, :constraints, %{}), properties: Keyword.get(opts, :properties, %{}) } end @doc """ Adds an object to the physics world. """ def add_object(world, object) do %{world | objects: Map.put(world.objects, object.id, object)} end @doc """ Removes an object from the physics world. """ def remove_object(world, object_id) do %{world | objects: Map.delete(world.objects, object_id)} end @doc """ Adds a force field to the physics world. """ def add_force_field(world, force_field) do %{world | force_fields: [force_field | world.force_fields]} end @doc """ Sets the boundaries of the physics world. """ def set_boundaries(world, boundaries) do %{world | boundaries: Map.merge(world.boundaries, boundaries)} end @doc """ Updates the physics world by one time step. """ def update(world, delta_time \\ nil) do # Calculate delta time if not provided delta_time = calculate_delta_time(delta_time, world) # Update all objects updated_objects = world.objects |> Enum.map(fn {id, object} -> {id, update_object(object, world, delta_time)} end) |> Map.new() # Check for collisions objects_after_collisions = handle_collisions(updated_objects, world) # Apply boundary constraints final_objects = apply_boundaries(objects_after_collisions, world.boundaries) # Return updated world %{ world | objects: final_objects, iteration: world.iteration + 1, last_update: System.os_time(:millisecond) } end @doc """ Step function that is an alias for update - for compatibility. """ def step(world, delta_time), do: update(world, delta_time) @doc """ Create a new physics world - alias for new_world. """ def create_world, do: new_world() @doc """ Add object with position and properties - simplified API. """ def add_object(world, id, properties) when is_binary(id) and is_map(properties) do object = new_object(id, Map.to_list(properties)) add_object(world, object) end @doc """ Creates a spring force between two objects. """ def spring_force( world, object_id_1, object_id_2, spring_constant, rest_length ) do object1 = Map.get(world.objects, object_id_1) object2 = Map.get(world.objects, object_id_2) apply_spring_force_if_objects_exist( object1 && object2, world, object1, object2, object_id_1, object_id_2, spring_constant, rest_length ) end @doc """ Creates a particle system at the specified position. """ def create_particle_system(world, position, count, opts \\ []) do params = %{ velocity_range: Keyword.get(opts, :velocity_range, {-5.0, 5.0}), lifetime_range: Keyword.get(opts, :lifetime_range, {0.5, 2.0}), size_range: Keyword.get(opts, :size_range, {1.0, 3.0}), color: Keyword.get(opts, :color, :white), fade: Keyword.get(opts, :fade, true) } Enum.reduce(1..count, world, fn i, acc_world -> particle = create_particle(position, params, world.iteration, i) add_object(acc_world, particle) end) end defp create_particle(position, params, iteration, index) do particle_props = create_particle_properties(params) new_object("particle_#{iteration}_#{index}", position: position, velocity: particle_props.velocity, mass: particle_props.size * 0.1, properties: particle_props ) end defp create_particle_properties(params) do lifetime = generate_random_value(params.lifetime_range) %{ velocity: generate_random_velocity(params.velocity_range), lifetime: lifetime, max_lifetime: lifetime, size: generate_random_value(params.size_range), color: params.color, fade: params.fade, type: :particle } end defp generate_random_velocity({min_v, max_v}) do %Vector{ x: :rand.uniform() * (max_v - min_v) + min_v, y: :rand.uniform() * (max_v - min_v) + min_v, z: :rand.uniform() * (max_v - min_v) + min_v } end defp generate_random_value({min, max}) do :rand.uniform() * (max - min) + min end @doc """ Applies an impulse force to an object. """ def apply_impulse(world, object_id, impulse) do case Map.get(world.objects, object_id) do nil -> world object -> # F = m * a, so a = F / m # For an impulse, we directly change velocity: v' = v + impulse/m updated_velocity = Vector.add( object.velocity, Vector.scale(impulse, 1 / object.mass) ) updated_object = %{object | velocity: updated_velocity} %{world | objects: Map.put(world.objects, object_id, updated_object)} end end # Private functions defp update_object(object, world, delta_time) do # Apply gravity gravity_force = Vector.scale(world.gravity, object.mass) # Combine with existing forces all_forces = [gravity_force | object.forces] # Apply force fields all_forces = Enum.reduce(world.force_fields, all_forces, fn field, forces -> field_force = ForceField.calculate_force(field, object) [field_force | forces] end) # Calculate net force net_force = Enum.reduce(all_forces, %Vector{x: 0, y: 0, z: 0}, &Vector.add/2) # Calculate acceleration (F = ma, so a = F/m) acceleration = Vector.scale(net_force, 1 / object.mass) # Apply damping/friction if specified damping = Map.get(object.properties, :damping, 0.0) velocity_after_damping = apply_damping_if_needed(damping > 0, object.velocity, damping, delta_time) # Update velocity: v = v0 + a*t velocity = Vector.add(velocity_after_damping, Vector.scale(acceleration, delta_time)) # Update position: p = p0 + v*t position = Vector.add(object.position, Vector.scale(velocity, delta_time)) # Update lifetime for particles properties = update_particle_lifetime( Map.has_key?(object.properties, :lifetime), object.properties, delta_time ) # Return updated object %{ object | position: position, velocity: velocity, acceleration: acceleration, # Clear forces after applying forces: [], properties: properties } end defp handle_collisions(objects, _world) do object_list = Map.values(objects) Enum.reduce( object_list, objects, &process_object_collisions(&1, object_list, &2) ) end defp process_object_collisions(obj1, object_list, acc_objects) do Enum.reduce(object_list, acc_objects, fn obj2, inner_acc -> process_collision_if_different_objects( obj1.id != obj2.id, obj1, obj2, inner_acc ) end) end defp handle_single_collision(obj1, obj2, acc_objects) do handle_collision_if_detected( check_collision(obj1, obj2), obj1, obj2, acc_objects ) end defp check_collision(obj1, obj2) do # For simplicity, assume objects are spheres radius1 = Map.get(obj1.properties, :radius, 1.0) radius2 = Map.get(obj2.properties, :radius, 1.0) # Calculate distance between centers distance = Vector.distance(obj1.position, obj2.position) # Check if distance is less than sum of radii distance < radius1 + radius2 end defp resolve_collision(obj1, obj2) do # Calculate collision normal normal = Vector.normalize(Vector.subtract(obj2.position, obj1.position)) # Calculate relative velocity relative_velocity = Vector.subtract(obj2.velocity, obj1.velocity) # Calculate velocity along normal velocity_along_normal = Vector.dot(relative_velocity, normal) # Early out if objects are moving away from each other resolve_collision_based_on_velocity( velocity_along_normal > 0, obj1, obj2, normal, velocity_along_normal ) end defp apply_boundaries(objects, boundaries) do Enum.map(objects, fn {id, obj} -> {id, apply_all_boundaries(obj, boundaries)} end) |> Map.new() end defp apply_all_boundaries(obj, boundaries) do obj |> apply_axis_boundary(:x, boundaries) |> apply_axis_boundary(:y, boundaries) |> apply_axis_boundary(:z, boundaries) end defp apply_axis_boundary(obj, axis, boundaries) do min_key = :"min_#{axis}" max_key = :"max_#{axis}" pos_key = axis vel_key = axis obj |> apply_min_boundary(pos_key, vel_key, Map.get(boundaries, min_key)) |> apply_max_boundary(pos_key, vel_key, Map.get(boundaries, max_key)) end defp apply_min_boundary(obj, pos_key, vel_key, min_value) do apply_min_boundary_constraint( min_value != nil and Map.get(obj.position, pos_key) < min_value, obj, pos_key, vel_key, min_value ) end defp apply_max_boundary(obj, pos_key, vel_key, max_value) do apply_max_boundary_constraint( max_value != nil and Map.get(obj.position, pos_key) > max_value, obj, pos_key, vel_key, max_value ) end # Helper functions to eliminate if statements defp calculate_delta_time(nil, world) do now = System.os_time(:millisecond) dt = (now - world.last_update) / 1000.0 # Clamp delta time to avoid large steps min(dt, 0.1) * world.time_scale end defp calculate_delta_time(delta_time, _world), do: delta_time defp apply_spring_force_if_objects_exist( false, world, _object1, _object2, _object_id_1, _object_id_2, _spring_constant, _rest_length ) do world end defp apply_spring_force_if_objects_exist( true, world, object1, object2, object_id_1, object_id_2, spring_constant, rest_length ) do # Calculate spring force direction = Vector.subtract(object2.position, object1.position) distance = Vector.magnitude(direction) # Avoid division by zero direction = normalize_direction_vector(distance > 0, direction, distance) # Calculate force magnitude (F = k * (d - r)) force_magnitude = spring_constant * (distance - rest_length) # Calculate the force vector force = Vector.scale(direction, force_magnitude) # Apply forces to both objects object1 = %{object1 | forces: [force | object1.forces]} object2 = %{object2 | forces: [Vector.negate(force) | object2.forces]} # Update world with new object states world |> Map.put(:objects, Map.put(world.objects, object_id_1, object1)) |> Map.put(:objects, Map.put(world.objects, object_id_2, object2)) end defp normalize_direction_vector(true, direction, distance) do Vector.scale(direction, 1 / distance) end defp normalize_direction_vector(false, _direction, _distance) do %Vector{x: 0, y: 0, z: 0} end defp apply_damping_if_needed(false, velocity, _damping, _delta_time), do: velocity defp apply_damping_if_needed(true, velocity, damping, delta_time) do Vector.scale(velocity, 1.0 - min(damping * delta_time, 0.99)) end defp update_particle_lifetime(false, properties, _delta_time), do: properties defp update_particle_lifetime(true, properties, delta_time) do Map.update!(properties, :lifetime, fn lifetime -> lifetime - delta_time end) end defp process_collision_if_different_objects(false, _obj1, _obj2, inner_acc), do: inner_acc defp process_collision_if_different_objects(true, obj1, obj2, inner_acc) do obj1_updated = Map.get(inner_acc, obj1.id) obj2_updated = Map.get(inner_acc, obj2.id) handle_single_collision(obj1_updated, obj2_updated, inner_acc) end defp handle_collision_if_detected(false, _obj1, _obj2, acc_objects), do: acc_objects defp handle_collision_if_detected(true, obj1, obj2, acc_objects) do {obj1_after, obj2_after} = resolve_collision(obj1, obj2) acc_objects |> Map.put(obj1.id, obj1_after) |> Map.put(obj2.id, obj2_after) end defp resolve_collision_based_on_velocity( true, obj1, obj2, _normal, _velocity_along_normal ) do {obj1, obj2} end defp resolve_collision_based_on_velocity( false, obj1, obj2, normal, velocity_along_normal ) do # Calculate restitution (bounciness) restitution = min( Map.get(obj1.properties, :restitution, 0.8), Map.get(obj2.properties, :restitution, 0.8) ) # Calculate impulse scalar j = -(1 + restitution) * velocity_along_normal j = j / (1 / obj1.mass + 1 / obj2.mass) # Apply impulse impulse = Vector.scale(normal, j) obj1_velocity = Vector.subtract(obj1.velocity, Vector.scale(impulse, 1 / obj1.mass)) obj2_velocity = Vector.add(obj2.velocity, Vector.scale(impulse, 1 / obj2.mass)) # Return updated objects { %{obj1 | velocity: obj1_velocity}, %{obj2 | velocity: obj2_velocity} } end defp apply_min_boundary_constraint( false, obj, _pos_key, _vel_key, _min_value ), do: obj defp apply_min_boundary_constraint(true, obj, pos_key, vel_key, min_value) do %{ obj | position: Map.put(obj.position, pos_key, min_value), velocity: Map.put( obj.velocity, vel_key, -Map.get(obj.velocity, vel_key) * 0.8 ) } end defp apply_max_boundary_constraint( false, obj, _pos_key, _vel_key, _max_value ), do: obj defp apply_max_boundary_constraint(true, obj, pos_key, vel_key, max_value) do %{ obj | position: Map.put(obj.position, pos_key, max_value), velocity: Map.put( obj.velocity, vel_key, -Map.get(obj.velocity, vel_key) * 0.8 ) } end end
411
0.845022
1
0.845022
game-dev
MEDIA
0.567148
game-dev
0.946911
1
0.946911
jetelain/ArmaRealMap
4,424
GameRealisticMap/Geometries/FollowPath.cs
using System.Numerics; namespace GameRealisticMap.Geometries { public class FollowPath { private readonly IEnumerator<TerrainPoint> enumerator; private TerrainPoint? previousPoint; private TerrainPoint? point; private TerrainPoint? previousPosition; private TerrainPoint? position; private Vector2 delta; private float length; private float positionOnSegment; private bool hasReachedEnd; private int index; public FollowPath(params TerrainPoint[] points) : this((IEnumerable<TerrainPoint>)points) { } public FollowPath(IEnumerable<TerrainPoint> points) { enumerator = points.GetEnumerator(); index = 0; Init(); } public virtual void Reset() { enumerator.Reset(); index = 0; Init(); } private void Init() { IsAfterRightAngle = false; previousPosition = null; length = 0f; positionOnSegment = 0f; previousPoint = null; if (enumerator.MoveNext()) { position = point = enumerator.Current; delta = Vector2.Zero; hasReachedEnd = false; MoveNextPoint(); } else { hasReachedEnd = true; } } private bool MoveNextPoint() { previousPoint = point; if (!enumerator.MoveNext()) { point = null; length = 0f; positionOnSegment = 0f; return false; } index++; point = enumerator.Current; delta = point.Vector - previousPoint.Vector; length = delta.Length(); positionOnSegment = 0f; return true; } public TerrainPoint Current => position ?? TerrainPoint.Empty; public TerrainPoint Previous => previousPosition; public Vector2 Vector => Vector2.Normalize(delta); public Vector2 Vector90 => Vector2.Transform(Vector, GeometryHelper.Rotate90); public Vector2 VectorM90 => Vector2.Transform(Vector, GeometryHelper.RotateM90); public bool KeepRightAngles { get; set; } public bool IsAfterRightAngle { get; private set; } public bool IsLast => hasReachedEnd; public bool IsFirst => index <=1; /// <summary> /// Index in original list /// </summary> public int Index => index; public bool Move(float step) { if (IsAfterRightAngle) { index++; } IsAfterRightAngle = false; if (hasReachedEnd) { return false; } var remainLength = step; while (remainLength + positionOnSegment > length) { remainLength -= length - positionOnSegment; var previousDelta = delta; if (!MoveNextPoint()) { hasReachedEnd = true; if (!TerrainPoint.Equals(position,previousPoint)) { previousPosition = position; position = previousPoint; return true; } return false; } if (KeepRightAngles) { var angle = Math.Abs(Math.Abs(Math.Acos(Vector2.Dot(Vector2.Normalize(delta), Vector2.Normalize(previousDelta)))) - (MathF.PI/2)); if ( angle < 0.1d && !position!.Equals(previousPoint)) { index--; previousPosition = position; position = previousPoint; positionOnSegment = 0; IsAfterRightAngle = true; return true; } } } positionOnSegment += remainLength; previousPosition = position; position = new TerrainPoint(Vector2.Lerp(previousPoint.Vector, point.Vector, positionOnSegment / length)); return true; } } }
411
0.943235
1
0.943235
game-dev
MEDIA
0.848453
game-dev,graphics-rendering
0.987327
1
0.987327
folgerwang/UnrealEngine
93,598
Engine/Source/Editor/Kismet/Private/BlueprintCompilationManager.cpp
// Copyright 1998-2019 Epic Games, Inc. All Rights Reserved. #include "BlueprintCompilationManager.h" #include "Kismet2/BlueprintEditorUtils.h" #include "BlueprintEditorSettings.h" #include "Blueprint/BlueprintSupport.h" #include "Kismet2/CompilerResultsLog.h" #include "Components/TimelineComponent.h" #include "Editor.h" #include "Engine/Engine.h" #include "Engine/LevelScriptBlueprint.h" #include "Engine/SCS_Node.h" #include "Engine/SimpleConstructionScript.h" #include "Engine/TimelineTemplate.h" #include "FileHelpers.h" #include "FindInBlueprintManager.h" #include "IMessageLogListing.h" #include "K2Node_CustomEvent.h" #include "K2Node_FunctionEntry.h" #include "K2Node_FunctionResult.h" #include "Kismet2/KismetEditorUtilities.h" #include "Kismet2/KismetReinstanceUtilities.h" #include "KismetCompiler.h" #include "ProfilingDebugging/ScopedTimers.h" #include "Serialization/ArchiveHasReferences.h" #include "Serialization/ArchiveReplaceOrClearExternalReferences.h" #include "Settings/EditorProjectSettings.h" #include "TickableEditorObject.h" #include "UObject/MetaData.h" #include "UObject/ReferenceChainSearch.h" #include "UObject/UObjectHash.h" #include "Kismet2/KismetDebugUtilities.h" #include "BlueprintEditorModule.h" #define LOCTEXT_NAMESPACE "BlueprintCompilationManager" /* BLUEPRINT COMPILATION MANAGER IMPLEMENTATION NOTES INPUTS: UBlueprint, UEdGraph, UEdGraphNode, UEdGraphPin, references to UClass, UProperties INTERMEDIATES: Cloned Graph, Nodes, Pins OUPUTS: UClass, UProperties The blueprint compilation manager addresses shortcomings of compilation behavior (performance, correctness) that occur when compiling blueprints that are inter-dependent. If you are using blueprints and there are no dependencies between blueprint compilation outputs and inputs, then this code is completely unnecessary and you can directly interface with FKismetCompilerContext and its derivatives. In order to handle compilation correctly the manager splits compilation into the following stages (implemented below in FlushCompilationQueueImpl): STAGE I: GATHER STAGE II: FILTER STAGE III: SORT STAGE IV: SET TEMPORARY BLUEPRINT FLAGS STAGE V: VALIDATE STAGE VI: PURGE (LOAD ONLY) STAGE VII: DISCARD SKELETON CDO STAGE VIII: RECOMPILE SKELETON STAGE IX: RECONSTRUCT NODES, REPLACE DEPRECATED NODES (LOAD ONLY) STAGE X: CREATE REINSTANCER (DISCARD 'OLD' CLASS) STAGE XI: CREATE UPDATED CLASS HIERARCHY STAGE XII: COMPILE CLASS LAYOUT STAGE XIII: COMPILE CLASS FUNCTIONS STAGE XIV: REINSTANCE STAGE XV: POST CDO COMPILED STAGE XVI: CLEAR TEMPORARY FLAGS The code that implements these stages are labeled below. At some later point a final reinstancing operation will occur, unless the client is using CompileSynchronously, in which case the expensive object graph find and replace will occur immediately */ // Debugging switches: #define VERIFY_NO_STALE_CLASS_REFERENCES 0 #define VERIFY_NO_BAD_SKELETON_REFERENCES 0 struct FReinstancingJob; struct FSkeletonFixupData; struct FBlueprintCompilationManagerImpl : public FGCObject { FBlueprintCompilationManagerImpl(); virtual ~FBlueprintCompilationManagerImpl(); // FGCObject: virtual void AddReferencedObjects(FReferenceCollector& Collector); void QueueForCompilation(const FBPCompileRequest& CompileJob); void CompileSynchronouslyImpl(const FBPCompileRequest& Request); void FlushCompilationQueueImpl(bool bSuppressBroadcastCompiled, TArray<UBlueprint*>* BlueprintsCompiled, TArray<UBlueprint*>* BlueprintsCompiledOrSkeletonCompiled, FUObjectSerializeContext* InLoadContext); void FlushReinstancingQueueImpl(); bool HasBlueprintsToCompile() const; bool IsGeneratedClassLayoutReady() const; void GetDefaultValue(const UClass* ForClass, const UProperty* Property, FString& OutDefaultValueAsString) const; static void ReparentHierarchies(const TMap<UClass*, UClass*>& OldClassToNewClass); static void BuildDSOMap(UObject* OldObject, UObject* NewObject, TMap<UObject*, UObject*>& OutOldToNewDSO); static void ReinstanceBatch(TArray<FReinstancingJob>& Reinstancers, TMap< UClass*, UClass* >& InOutOldToNewClassMap, FUObjectSerializeContext* InLoadContext); static UClass* FastGenerateSkeletonClass(UBlueprint* BP, FKismetCompilerContext& CompilerContext, bool bIsSkeletonOnly, TArray<FSkeletonFixupData>& OutSkeletonFixupData); static bool IsQueuedForCompilation(UBlueprint* BP); static UObject* GetOuterForRename(UClass* ForClass); // Declaration of archive to fix up bytecode references of blueprints that are actively compiled: class FFixupBytecodeReferences : public FArchiveUObject { public: FFixupBytecodeReferences(UObject* InObject); private: virtual FArchive& operator<<( UObject*& Obj ) override; }; // Queued requests to be processed in the next FlushCompilationQueueImpl call: TArray<FBPCompileRequest> QueuedRequests; // Data stored for reinstancing, which finishes much later than compilation, // populated by FlushCompilationQueueImpl, cleared by FlushReinstancingQueueImpl: TMap<UClass*, UClass*> ClassesToReinstance; // Map to old default values, useful for providing access to this data throughout // the compilation process: TMap<UBlueprint*, UObject*> OldCDOs; // Blueprints that should be saved after the compilation pass is complete: TArray<UBlueprint*> CompiledBlueprintsToSave; // State stored so that we can check what stage of compilation we're in: bool bGeneratedClassLayoutReady; }; // free function that we use to cross a module boundary (from CoreUObject to here) void FlushReinstancingQueueImplWrapper(); void MoveSkelCDOAside(UClass* Class, TMap<UClass*, UClass*>& OldToNewMap); FBlueprintCompilationManagerImpl::FBlueprintCompilationManagerImpl() { FBlueprintSupport::SetFlushReinstancingQueueFPtr(&FlushReinstancingQueueImplWrapper); bGeneratedClassLayoutReady = true; } FBlueprintCompilationManagerImpl::~FBlueprintCompilationManagerImpl() { FBlueprintSupport::SetFlushReinstancingQueueFPtr(nullptr); } void FBlueprintCompilationManagerImpl::AddReferencedObjects(FReferenceCollector& Collector) { for( FBPCompileRequest& Job : QueuedRequests ) { Collector.AddReferencedObject(Job.BPToCompile); } Collector.AddReferencedObjects(ClassesToReinstance); Collector.AddReferencedObjects(OldCDOs); } void FBlueprintCompilationManagerImpl::QueueForCompilation(const FBPCompileRequest& CompileJob) { if(!CompileJob.BPToCompile->bQueuedForCompilation) { CompileJob.BPToCompile->bQueuedForCompilation = true; QueuedRequests.Add(CompileJob); } } void FBlueprintCompilationManagerImpl::CompileSynchronouslyImpl(const FBPCompileRequest& Request) { Request.BPToCompile->bQueuedForCompilation = true; const bool bIsRegeneratingOnLoad = (Request.CompileOptions & EBlueprintCompileOptions::IsRegeneratingOnLoad ) != EBlueprintCompileOptions::None; const bool bRegenerateSkeletonOnly = (Request.CompileOptions & EBlueprintCompileOptions::RegenerateSkeletonOnly ) != EBlueprintCompileOptions::None; const bool bSkipGarbageCollection = (Request.CompileOptions & EBlueprintCompileOptions::SkipGarbageCollection ) != EBlueprintCompileOptions::None || bRegenerateSkeletonOnly; const bool bBatchCompile = (Request.CompileOptions & EBlueprintCompileOptions::BatchCompile ) != EBlueprintCompileOptions::None; const bool bSkipReinstancing = (Request.CompileOptions & EBlueprintCompileOptions::SkipReinstancing ) != EBlueprintCompileOptions::None; const bool bSkipSaving = (Request.CompileOptions & EBlueprintCompileOptions::SkipSave ) != EBlueprintCompileOptions::None; ensure(!bIsRegeneratingOnLoad); // unexpected code path, compile on load handled with different function call ensure(!bSkipReinstancing); // This is an internal option, should not go through CompileSynchronouslyImpl ensure(QueuedRequests.Num() == 0); // Wipe the PreCompile log, any generated messages are now irrelevant Request.BPToCompile->PreCompileLog.Reset(); // Reset the flag, so if the user tries to use PIE it will warn them if the BP did not compile Request.BPToCompile->bDisplayCompilePIEWarning = true; // Do not want to run this code without the editor present nor when running commandlets. // We do not want to regenerate a search Guid during loads, nothing has changed in the Blueprint // and it is cached elsewhere. // We would like to regenerated it when a skeleton changes, but it is too expensive: if (GEditor && GIsEditor && !bIsRegeneratingOnLoad && !bRegenerateSkeletonOnly) { FFindInBlueprintSearchManager::Get().AddOrUpdateBlueprintSearchMetadata(Request.BPToCompile); } QueuedRequests.Add(Request); // We suppress normal compilation broadcasts because the old code path // did this after GC and we want to match the old behavior: const bool bSuppressBroadcastCompiled = true; TArray<UBlueprint*> CompiledBlueprints; TArray<UBlueprint*> SkeletonCompiledBlueprints; FlushCompilationQueueImpl(bSuppressBroadcastCompiled, &CompiledBlueprints, &SkeletonCompiledBlueprints, nullptr); FlushReinstancingQueueImpl(); if (FBlueprintEditorUtils::IsLevelScriptBlueprint(Request.BPToCompile) && !bRegenerateSkeletonOnly) { // When the Blueprint is recompiled, then update the bound events for level scripting ULevelScriptBlueprint* LevelScriptBP = CastChecked<ULevelScriptBlueprint>(Request.BPToCompile); // ULevel::OnLevelScriptBlueprintChanged needs to be run after the CDO has // been updated as it respawns the actor: if (ULevel* BPLevel = LevelScriptBP->GetLevel()) { // Newly created levels don't need this notification: if (BPLevel->GetLevelScriptBlueprint(true)) { BPLevel->OnLevelScriptBlueprintChanged(LevelScriptBP); } } } if ( GEditor && !bRegenerateSkeletonOnly) { // Make sure clients know they're being reinstanced as part of blueprint compilation. After this point // compilation is completely done: TGuardValue<bool> GuardTemplateNameFlag(GCompilingBlueprint, true); GEditor->BroadcastBlueprintReinstanced(); } ensure(Request.BPToCompile->bQueuedForCompilation == false); if(!bSkipGarbageCollection) { CollectGarbage(GARBAGE_COLLECTION_KEEPFLAGS); } if (!bRegenerateSkeletonOnly) { for(UBlueprint* BP : SkeletonCompiledBlueprints) { BP->BroadcastChanged(); } } else { ensure(SkeletonCompiledBlueprints.Num() == 1); } if (!bBatchCompile && !bRegenerateSkeletonOnly) { for(UBlueprint* BP : SkeletonCompiledBlueprints) { BP->BroadcastCompiled(); } if(GEditor) { GEditor->BroadcastBlueprintCompiled(); } } if (CompiledBlueprintsToSave.Num() > 0 && !bRegenerateSkeletonOnly) { if (!bSkipSaving) { TArray<UPackage*> PackagesToSave; for (UBlueprint* BP : CompiledBlueprintsToSave) { PackagesToSave.Add(BP->GetOutermost()); } FEditorFileUtils::PromptForCheckoutAndSave(PackagesToSave, /*bCheckDirty =*/true, /*bPromptToSave =*/false); } CompiledBlueprintsToSave.Empty(); } // We've done our GC, so release old CDO references OldCDOs.Empty(); } static double GTimeCompiling = 0.f; static double GTimeReinstancing = 0.f; enum class ECompilationManagerJobType { Normal, SkeletonOnly, RelinkOnly, }; // Currently only used to fix up delegate parameters on skeleton ufunctions, resolving the cyclical dependency, // could be augmented if similar cases arise: struct FSkeletonFixupData { FSimpleMemberReference MemberReference; UProperty* DelegateProperty; }; struct FCompilerData { explicit FCompilerData(UBlueprint* InBP, ECompilationManagerJobType InJobType, FCompilerResultsLog* InResultsLogOverride, EBlueprintCompileOptions UserOptions, bool bBytecodeOnly) { check(InBP); BP = InBP; JobType = InJobType; UPackage* Package = BP->GetOutermost(); bPackageWasDirty = Package ? Package->IsDirty() : false; OriginalBPStatus = BP->Status; ActiveResultsLog = InResultsLogOverride; if(InResultsLogOverride == nullptr) { ResultsLog = MakeUnique<FCompilerResultsLog>(); ResultsLog->BeginEvent(TEXT("BlueprintCompilationManager Compile")); ResultsLog->SetSourcePath(InBP->GetPathName()); ActiveResultsLog = ResultsLog.Get(); } static const FBoolConfigValueHelper IgnoreCompileOnLoadErrorsOnBuildMachine(TEXT("Kismet"), TEXT("bIgnoreCompileOnLoadErrorsOnBuildMachine"), GEngineIni); ActiveResultsLog->bLogInfoOnly = !BP->bHasBeenRegenerated && GIsBuildMachine && IgnoreCompileOnLoadErrorsOnBuildMachine; InternalOptions.bRegenerateSkelton = false; InternalOptions.bReinstanceAndStubOnFailure = false; InternalOptions.bSaveIntermediateProducts = (UserOptions & EBlueprintCompileOptions::SaveIntermediateProducts) != EBlueprintCompileOptions::None; InternalOptions.bSkipDefaultObjectValidation = (UserOptions & EBlueprintCompileOptions::SkipDefaultObjectValidation) != EBlueprintCompileOptions::None; InternalOptions.bSkipFiBSearchMetaUpdate = (UserOptions & EBlueprintCompileOptions::SkipFiBSearchMetaUpdate) != EBlueprintCompileOptions::None; InternalOptions.CompileType = bBytecodeOnly ? EKismetCompileType::BytecodeOnly : EKismetCompileType::Full; Compiler = FKismetCompilerContext::GetCompilerForBP(BP, *ActiveResultsLog, InternalOptions); } bool IsSkeletonOnly() const { return JobType == ECompilationManagerJobType::SkeletonOnly; } bool ShouldSetTemporaryBlueprintFlags() const { return JobType != ECompilationManagerJobType::RelinkOnly; } bool ShouldResetErrorState() const { return JobType == ECompilationManagerJobType::Normal && InternalOptions.CompileType != EKismetCompileType::BytecodeOnly; } bool ShouldValidateVariableNames() const { return JobType == ECompilationManagerJobType::Normal; } bool ShouldRegenerateSkeleton() const { return JobType != ECompilationManagerJobType::RelinkOnly; } bool ShouldMarkUpToDateAfterSkeletonStage() const { return IsSkeletonOnly(); } bool ShouldReconstructNodes() const { return JobType == ECompilationManagerJobType::Normal; } bool ShouldSkipReinstancerCreation() const { return (IsSkeletonOnly() && (!BP->ParentClass || BP->ParentClass->IsNative())); } bool ShouldInitiateReinstancing() const { return JobType == ECompilationManagerJobType::Normal || BP->bIsRegeneratingOnLoad; } bool ShouldCompileClassLayout() const { return JobType == ECompilationManagerJobType::Normal; } bool ShouldCompileClassFunctions() const { return JobType == ECompilationManagerJobType::Normal; } bool ShouldRegisterCompilerResults() const { return JobType == ECompilationManagerJobType::Normal; } bool ShouldSkipIfDependenciesAreUnchanged() const { return InternalOptions.CompileType == EKismetCompileType::BytecodeOnly || JobType == ECompilationManagerJobType::RelinkOnly; } bool ShouldValidateClassDefaultObject() const { return JobType == ECompilationManagerJobType::Normal && !InternalOptions.bSkipDefaultObjectValidation; } bool ShouldUpdateBlueprintSearchMetadata() const { return JobType == ECompilationManagerJobType::Normal && !InternalOptions.bSkipFiBSearchMetaUpdate; } UBlueprint* BP; FCompilerResultsLog* ActiveResultsLog; TUniquePtr<FCompilerResultsLog> ResultsLog; TSharedPtr<FKismetCompilerContext> Compiler; FKismetCompilerOptions InternalOptions; TSharedPtr<FBlueprintCompileReinstancer> Reinstancer; TArray<FSkeletonFixupData> SkeletonFixupData; ECompilationManagerJobType JobType; bool bPackageWasDirty; EBlueprintStatus OriginalBPStatus; }; struct FReinstancingJob { TSharedPtr<FBlueprintCompileReinstancer> Reinstancer; TSharedPtr<FKismetCompilerContext> Compiler; }; void FBlueprintCompilationManagerImpl::FlushCompilationQueueImpl(bool bSuppressBroadcastCompiled, TArray<UBlueprint*>* BlueprintsCompiled, TArray<UBlueprint*>* BlueprintsCompiledOrSkeletonCompiled, FUObjectSerializeContext* InLoadContext) { TGuardValue<bool> GuardTemplateNameFlag(GCompilingBlueprint, true); ensure(bGeneratedClassLayoutReady); if( QueuedRequests.Num() == 0 ) { return; } TArray<FCompilerData> CurrentlyCompilingBPs; { // begin GTimeCompiling scope FScopedDurationTimer SetupTimer(GTimeCompiling); // STAGE I: Add any related blueprints that were not compiled, then add any children so that they will be relinked: TArray<UBlueprint*> BlueprintsToRecompile; // First add any dependents of macro libraries that are being compiled: for(const FBPCompileRequest& CompileJob : QueuedRequests) { if ((CompileJob.CompileOptions & ( EBlueprintCompileOptions::RegenerateSkeletonOnly| EBlueprintCompileOptions::IsRegeneratingOnLoad) ) != EBlueprintCompileOptions::None) { continue; } if(CompileJob.BPToCompile->BlueprintType == BPTYPE_MacroLibrary) { TArray<UBlueprint*> DependentBlueprints; FBlueprintEditorUtils::GetDependentBlueprints(CompileJob.BPToCompile, DependentBlueprints); for(UBlueprint* DependentBlueprint : DependentBlueprints) { if(!IsQueuedForCompilation(DependentBlueprint)) { DependentBlueprint->bQueuedForCompilation = true; CurrentlyCompilingBPs.Add( FCompilerData( DependentBlueprint, ECompilationManagerJobType::Normal, nullptr, EBlueprintCompileOptions::None, false // full compile ) ); BlueprintsToRecompile.Add(DependentBlueprint); } } } } // then make sure any normal blueprints have their bytecode dependents recompiled, this is in case a function signature changes: for(const FBPCompileRequest& CompileJob : QueuedRequests) { if ((CompileJob.CompileOptions & EBlueprintCompileOptions::RegenerateSkeletonOnly) != EBlueprintCompileOptions::None) { continue; } // Add any dependent blueprints for a bytecode compile, this is needed because we // have no way to keep bytecode safe when a function is renamed or parameters are // added or removed. Below (Stage VIII) we skip further compilation for blueprints // that are being bytecode compiled, but their dependencies have not changed: TArray<UBlueprint*> DependentBlueprints; FBlueprintEditorUtils::GetDependentBlueprints(CompileJob.BPToCompile, DependentBlueprints); for(UBlueprint* DependentBlueprint : DependentBlueprints) { if(!IsQueuedForCompilation(DependentBlueprint)) { DependentBlueprint->bQueuedForCompilation = true; // Because we're adding this as a bytecode only blueprint compile we don't need to // recursively recompile dependencies. The assumption is that a bytecode only compile // will not change the class layout. @todo: add an ensure to detect class layout changes CurrentlyCompilingBPs.Add( FCompilerData( DependentBlueprint, ECompilationManagerJobType::Normal, nullptr, EBlueprintCompileOptions::None, true ) ); BlueprintsToRecompile.Add(DependentBlueprint); } } } // STAGE II: Filter out data only and interface blueprints: for(int32 I = 0; I < QueuedRequests.Num(); ++I) { bool bSkipCompile = false; FBPCompileRequest& QueuedJob = QueuedRequests[I]; UBlueprint* QueuedBP = QueuedJob.BPToCompile; ensure(!QueuedBP->GeneratedClass || !QueuedBP->GeneratedClass->ClassDefaultObject || !(QueuedBP->GeneratedClass->ClassDefaultObject->HasAnyFlags(RF_NeedLoad))); bool bDefaultComponentMustBeAdded = false; bool bHasPendingUberGraphFrame = false; if(UBlueprintGeneratedClass* BPGC = Cast<UBlueprintGeneratedClass>(QueuedBP->GeneratedClass)) { if( BPGC->SimpleConstructionScript && BPGC->SimpleConstructionScript->GetSceneRootComponentTemplate() == nullptr) { bDefaultComponentMustBeAdded = true; } #if USE_UBER_GRAPH_PERSISTENT_FRAME bHasPendingUberGraphFrame = BPGC->UberGraphFramePointerProperty || BPGC->UberGraphFunction; #endif//USE_UBER_GRAPH_PERSISTENT_FRAME } if( FBlueprintEditorUtils::IsDataOnlyBlueprint(QueuedBP) && !QueuedBP->bHasBeenRegenerated && QueuedBP->GetLinker() && !bDefaultComponentMustBeAdded && !bHasPendingUberGraphFrame) { const UClass* ParentClass = QueuedBP->ParentClass; if (ParentClass && ParentClass->HasAllClassFlags(CLASS_Native)) { bSkipCompile = true; } else if (const UClass* CurrentClass = QueuedBP->GeneratedClass) { if(FStructUtils::TheSameLayout(CurrentClass, CurrentClass->GetSuperStruct())) { bSkipCompile = true; } } } if(bSkipCompile) { CurrentlyCompilingBPs.Add(FCompilerData(QueuedBP, ECompilationManagerJobType::SkeletonOnly, QueuedJob.ClientResultsLog, QueuedJob.CompileOptions, false)); if (QueuedBP->GeneratedClass != nullptr) { // set bIsRegeneratingOnLoad so that we don't reset loaders: QueuedBP->bIsRegeneratingOnLoad = true; FBlueprintEditorUtils::RemoveStaleFunctions(Cast<UBlueprintGeneratedClass>(QueuedBP->GeneratedClass), QueuedBP); QueuedBP->bIsRegeneratingOnLoad = false; } // No actual compilation work to be done, but try to conform the class and fix up anything that might need to be updated if the native base class has changed in any way FKismetEditorUtilities::ConformBlueprintFlagsAndComponents(QueuedBP); if (QueuedBP->GeneratedClass) { FBlueprintEditorUtils::RecreateClassMetaData(QueuedBP, QueuedBP->GeneratedClass, true); } QueuedRequests.RemoveAtSwap(I); --I; } else { ECompilationManagerJobType JobType = ECompilationManagerJobType::Normal; if ((QueuedJob.CompileOptions & EBlueprintCompileOptions::RegenerateSkeletonOnly) != EBlueprintCompileOptions::None) { JobType = ECompilationManagerJobType::SkeletonOnly; } CurrentlyCompilingBPs.Add(FCompilerData(QueuedBP, JobType, QueuedJob.ClientResultsLog, QueuedJob.CompileOptions, false)); BlueprintsToRecompile.Add(QueuedBP); } } for(UBlueprint* BP : BlueprintsToRecompile) { // make sure all children are at least re-linked: if(UClass* OldSkeletonClass = BP->SkeletonGeneratedClass) { TArray<UClass*> SkeletonClassesToReparentList; // Has to be recursive gather of children because instances of a UClass will cache information about // classes that are above their immediate parent (e.g. ClassConstructor): GetDerivedClasses(OldSkeletonClass, SkeletonClassesToReparentList); for(UClass* ChildClass : SkeletonClassesToReparentList) { if(UBlueprint* ChildBlueprint = UBlueprint::GetBlueprintFromClass(ChildClass)) { if(!IsQueuedForCompilation(ChildBlueprint)) { ChildBlueprint->bQueuedForCompilation = true; ensure(ChildBlueprint->bHasBeenRegenerated); CurrentlyCompilingBPs.Add(FCompilerData(ChildBlueprint, ECompilationManagerJobType::RelinkOnly, nullptr, EBlueprintCompileOptions::None, false)); } } } } } BlueprintsToRecompile.Empty(); QueuedRequests.Empty(); // STAGE III: Sort into correct compilation order. We want to compile root types before their derived (child) types: auto HierarchyDepthSortFn = [](const FCompilerData& CompilerDataA, const FCompilerData& CompilerDataB) { UBlueprint& A = *(CompilerDataA.BP); UBlueprint& B = *(CompilerDataB.BP); bool bAIsInterface = FBlueprintEditorUtils::IsInterfaceBlueprint(&A); bool bBIsInterface = FBlueprintEditorUtils::IsInterfaceBlueprint(&B); if(bAIsInterface && !bBIsInterface) { return true; } else if(bBIsInterface && !bAIsInterface) { return false; } int32 DepthA = 0; int32 DepthB = 0; UStruct* Iter = *(A.GeneratedClass) ? A.GeneratedClass->GetSuperStruct() : nullptr; while (Iter) { ++DepthA; Iter = Iter->GetSuperStruct(); } Iter = *(B.GeneratedClass) ? B.GeneratedClass->GetSuperStruct() : nullptr; while (Iter) { ++DepthB; Iter = Iter->GetSuperStruct(); } if (DepthA == DepthB) { return A.GetFName() < B.GetFName(); } return DepthA < DepthB; }; CurrentlyCompilingBPs.Sort( HierarchyDepthSortFn ); // STAGE IV: Set UBlueprint flags (bBeingCompiled, bIsRegeneratingOnLoad) for (FCompilerData& CompilerData : CurrentlyCompilingBPs) { if (!CompilerData.ShouldSetTemporaryBlueprintFlags()) { continue; } UBlueprint* BP = CompilerData.BP; BP->bBeingCompiled = true; BP->CurrentMessageLog = CompilerData.ActiveResultsLog; BP->bIsRegeneratingOnLoad = !BP->bHasBeenRegenerated && BP->GetLinker(); if(BP->bIsRegeneratingOnLoad) { // we may have cached dependencies before being fully loaded: BP->bCachedDependenciesUpToDate = false; } if(CompilerData.ShouldResetErrorState()) { TArray<UEdGraph*> AllGraphs; BP->GetAllGraphs(AllGraphs); for (UEdGraph* Graph : AllGraphs ) { for (UEdGraphNode* GraphNode : Graph->Nodes) { if (GraphNode) { GraphNode->ClearCompilerMessage(); } } } } } // STAGE V: Validate Variable Names for (FCompilerData& CompilerData : CurrentlyCompilingBPs) { if(!CompilerData.ShouldValidateVariableNames()) { continue; } CompilerData.Compiler->ValidateVariableNames(); } // STAGE VI: Purge null graphs, could be done only on load for (FCompilerData& CompilerData : CurrentlyCompilingBPs) { UBlueprint* BP = CompilerData.BP; FBlueprintEditorUtils::PurgeNullGraphs(BP); } // STAGE VII: safely throw away old skeleton CDOs: { TMap<UClass*, UClass*> NewSkeletonToOldSkeleton; for (FCompilerData& CompilerData : CurrentlyCompilingBPs) { UBlueprint* BP = CompilerData.BP; UClass* OldSkeletonClass = BP->SkeletonGeneratedClass; if(OldSkeletonClass) { MoveSkelCDOAside(OldSkeletonClass, NewSkeletonToOldSkeleton); } } // STAGE VIII: recompile skeleton // if any function signatures have changed in this skeleton class we will need to recompile all dependencies, but if not // then we can avoid dependency recompilation: TSet<UBlueprint*> BlueprintsWithSignatureChanges; const UBlueprintEditorProjectSettings* EditorProjectSettings = GetDefault<UBlueprintEditorProjectSettings>(); bool bSkipUnneededDependencyCompilation = !EditorProjectSettings->bForceAllDependenciesToRecompile; for (FCompilerData& CompilerData : CurrentlyCompilingBPs) { UBlueprint* BP = CompilerData.BP; if(CompilerData.ShouldRegenerateSkeleton()) { if(BlueprintsCompiledOrSkeletonCompiled) { BlueprintsCompiledOrSkeletonCompiled->Add(BP); } BP->SkeletonGeneratedClass = FastGenerateSkeletonClass(BP, *(CompilerData.Compiler), CompilerData.IsSkeletonOnly(), CompilerData.SkeletonFixupData); UBlueprintGeneratedClass* AuthoritativeClass = Cast<UBlueprintGeneratedClass>(BP->GeneratedClass); if(AuthoritativeClass && bSkipUnneededDependencyCompilation) { if(CompilerData.InternalOptions.CompileType == EKismetCompileType::Full ) { for (TFieldIterator<UFunction> FuncIt(AuthoritativeClass, EFieldIteratorFlags::ExcludeSuper); FuncIt; ++FuncIt) { // We assume that if the func is FUNC_BlueprintCallable that it will be present in the Skeleton class. // If it is not in the skeleton class we will always think that this blueprints public interface has // changed. Not a huge deal, but will mean we recompile dependencies more often than necessary. if(FuncIt->HasAnyFunctionFlags(EFunctionFlags::FUNC_BlueprintCallable)) { UFunction* NewFunction = BP->SkeletonGeneratedClass->FindFunctionByName((*FuncIt)->GetFName()); if( NewFunction == nullptr || !NewFunction->IsSignatureCompatibleWith(*FuncIt) || // If a function changes its net flags, callers may now need to do a full EX_FinalFunction/EX_VirtualFunction // instead of a EX_LocalFinalFunction/EX_LocalVirtualFunction: NewFunction->HasAnyFunctionFlags(FUNC_NetFuncFlags) != FuncIt->HasAnyFunctionFlags(FUNC_NetFuncFlags)) { BlueprintsWithSignatureChanges.Add(BP); break; } } } } } } else { // Just relink, note that UProperties that reference *other* types may be stale until // we fixup below: UClass* SkeletonToRelink = BP->SkeletonGeneratedClass; // CDO needs to be moved aside already: ensure(SkeletonToRelink->ClassDefaultObject == nullptr); ensure(!SkeletonToRelink->GetSuperClass()->HasAnyClassFlags(CLASS_NewerVersionExists)); SkeletonToRelink->ClassConstructor = nullptr; SkeletonToRelink->ClassVTableHelperCtorCaller = nullptr; SkeletonToRelink->ClassAddReferencedObjects = nullptr; SkeletonToRelink->Bind(); SkeletonToRelink->ClearFunctionMapsCaches(); SkeletonToRelink->StaticLink(true); SkeletonToRelink->GetDefaultObject(); } if(CompilerData.ShouldMarkUpToDateAfterSkeletonStage()) { // Flag data only blueprints as being up-to-date BP->Status = BP->bHasBeenRegenerated ? CompilerData.OriginalBPStatus : BS_UpToDate; BP->bHasBeenRegenerated = true; if (BP->GeneratedClass) { BP->GeneratedClass->ClearFunctionMapsCaches(); } } } // Fix up delegate parameters on skeleton class UFunctions, as they have a direct reference to a UFunction* // that may have been created as part of skeleton generation: for (FCompilerData& CompilerData : CurrentlyCompilingBPs) { UBlueprint* BP = CompilerData.BP; TArray< FSkeletonFixupData >& ParamsToFix = CompilerData.SkeletonFixupData; for( const FSkeletonFixupData& FixupData : ParamsToFix ) { if(UDelegateProperty* DelegateProperty = Cast<UDelegateProperty>(FixupData.DelegateProperty)) { DelegateProperty->SignatureFunction = FMemberReference::ResolveSimpleMemberReference<UFunction>(FixupData.MemberReference, BP->SkeletonGeneratedClass); } else if(UMulticastDelegateProperty* MCDelegateProperty = Cast<UMulticastDelegateProperty>(FixupData.DelegateProperty)) { MCDelegateProperty->SignatureFunction = FMemberReference::ResolveSimpleMemberReference<UFunction>(FixupData.MemberReference, BP->SkeletonGeneratedClass); } } } // Skip further compilation for blueprints that are being bytecode compiled as a dependency of something that has // not had a change in its function parameters: auto DependenciesAreCompiled = [&BlueprintsWithSignatureChanges](FCompilerData& Data) { if(Data.ShouldSkipIfDependenciesAreUnchanged()) { // if our parent is still being compiled, then we still need to be compiled: UClass* Iter = Data.BP->ParentClass; while(Iter) { if(UBlueprint* BP = Cast<UBlueprint>(Iter->ClassGeneratedBy)) { if(BP->bBeingCompiled) { return false; } } Iter = Iter->GetSuperClass(); } // otherwise if we're dependent on a blueprint that had a function signature change, we still need to be compiled: ensure(Data.BP->bCachedDependenciesUpToDate); ensure(Data.BP->CachedDependencies.Num() > 0); // why are we bytecode compiling a blueprint with no dependencies? for(const TWeakObjectPtr<UBlueprint>& Dependency : Data.BP->CachedDependencies) { if (UBlueprint* DependencyBP = Dependency.Get()) { if(DependencyBP->bBeingCompiled && BlueprintsWithSignatureChanges.Contains(DependencyBP)) { return false; } } } Data.BP->bBeingCompiled = false; Data.BP->CurrentMessageLog = nullptr; if(UPackage* Package = Data.BP->GetOutermost()) { Package->SetDirtyFlag(Data.bPackageWasDirty); } if(Data.ResultsLog) { Data.ResultsLog->EndEvent(); } Data.BP->bQueuedForCompilation = false; return true; } return false; }; if(bSkipUnneededDependencyCompilation) { // Order very much matters, but we could RemoveAllSwap and re-sort: CurrentlyCompilingBPs.RemoveAll(DependenciesAreCompiled); } } // STAGE IX: Reconstruct nodes and replace deprecated nodes, then broadcast 'precompile for (FCompilerData& CompilerData : CurrentlyCompilingBPs) { if(!CompilerData.ShouldReconstructNodes()) { continue; } UBlueprint* BP = CompilerData.BP; // Some nodes are set up to do things during reconstruction only when this flag is NOT set. if(BP->bIsRegeneratingOnLoad) { FBlueprintEditorUtils::ReconstructAllNodes(BP); FBlueprintEditorUtils::ReplaceDeprecatedNodes(BP); } else { // matching existing behavior, when compiling a BP not on load we refresh nodes // before compiling: FBlueprintCompileReinstancer::OptionallyRefreshNodes(BP); TArray<UBlueprint*> DependentBlueprints; FBlueprintEditorUtils::GetDependentBlueprints(BP, DependentBlueprints); for (UBlueprint* CurrentBP : DependentBlueprints) { const EBlueprintStatus OriginalStatus = CurrentBP->Status; UPackage* const Package = CurrentBP->GetOutermost(); const bool bStartedWithUnsavedChanges = Package != nullptr ? Package->IsDirty() : true; FBlueprintEditorUtils::RefreshExternalBlueprintDependencyNodes(CurrentBP, BP->GeneratedClass); CurrentBP->Status = OriginalStatus; if(Package != nullptr && Package->IsDirty() && !bStartedWithUnsavedChanges) { Package->SetDirtyFlag(false); } } } // Broadcast pre-compile { if(GEditor && GIsEditor) { GEditor->BroadcastBlueprintPreCompile(BP); } } if (CompilerData.ShouldUpdateBlueprintSearchMetadata()) { // Do not want to run this code without the editor present nor when running commandlets. if (GEditor && GIsEditor) { // We do not want to regenerate a search Guid during loads, nothing has changed in the Blueprint and it is cached elsewhere if (!BP->bIsRegeneratingOnLoad) { FFindInBlueprintSearchManager::Get().AddOrUpdateBlueprintSearchMetadata(BP); } } } // we are regenerated, tag ourself as such so that // old logic to 'fix' circular dependencies doesn't // cause redundant regeneration (e.g. bForceRegenNodes // in ExpandTunnelsAndMacros): BP->bHasBeenRegenerated = true; } // STAGE X: reinstance every blueprint that is queued, note that this means classes in the hierarchy that are *not* being // compiled will be parented to REINST versions of the class, so type checks (IsA, etc) involving those types // will be incoherent! { for (FCompilerData& CompilerData : CurrentlyCompilingBPs) { // we including skeleton only compilation jobs for reinstancing because we need UpdateCustomPropertyListForPostConstruction // to happen (at the right time) for those generated classes as well. This means we *don't* need to reinstance if // the parent is a native type (unless we hot reload, but that should not need to be handled here): if(CompilerData.ShouldSkipReinstancerCreation()) { continue; } // no need to reinstance skeleton or relink jobs that are not in a hierarchy that has had reinstancing initiated: bool bRequiresReinstance = CompilerData.ShouldInitiateReinstancing(); if (!bRequiresReinstance) { UClass* Iter = CompilerData.BP->GeneratedClass; if (!Iter) { bRequiresReinstance = true; } while (Iter) { if (Iter->HasAnyClassFlags(CLASS_NewerVersionExists)) { bRequiresReinstance = true; break; } Iter = Iter->GetSuperClass(); } } if (!bRequiresReinstance) { continue; } UBlueprint* BP = CompilerData.BP; if(BP->GeneratedClass) { OldCDOs.Add(BP, BP->GeneratedClass->ClassDefaultObject); } CompilerData.Reinstancer = TSharedPtr<FBlueprintCompileReinstancer>( new FBlueprintCompileReinstancer( BP->GeneratedClass, EBlueprintCompileReinstancerFlags::AutoInferSaveOnCompile | EBlueprintCompileReinstancerFlags::AvoidCDODuplication ) ); if(BP->GeneratedClass) { BP->GeneratedClass->ClassFlags |= CLASS_LayoutChanging; } } } // STAGE XI: Reinstancing done, lets fix up child->parent pointers for (FCompilerData& CompilerData : CurrentlyCompilingBPs) { UBlueprint* BP = CompilerData.BP; if(BP->GeneratedClass && BP->GeneratedClass->GetSuperClass()->HasAnyClassFlags(CLASS_NewerVersionExists)) { BP->GeneratedClass->SetSuperStruct(BP->GeneratedClass->GetSuperClass()->GetAuthoritativeClass()); } } // STAGE XII: Recompile every blueprint bGeneratedClassLayoutReady = false; for (FCompilerData& CompilerData : CurrentlyCompilingBPs) { UBlueprint* BP = CompilerData.BP; if(CompilerData.ShouldCompileClassLayout()) { ensure( BP->GeneratedClass == nullptr || BP->GeneratedClass->ClassDefaultObject == nullptr || BP->GeneratedClass->ClassDefaultObject->GetClass() != BP->GeneratedClass); // default value propagation occurs in ReinstaneBatch, CDO will be created via CompileFunctions call: if(BP->ParentClass) { if(BP->GeneratedClass) { BP->GeneratedClass->ClassDefaultObject = nullptr; } // Reset the flag, so if the user tries to use PIE it will warn them if the BP did not compile BP->bDisplayCompilePIEWarning = true; FKismetCompilerContext& CompilerContext = *(CompilerData.Compiler); CompilerContext.CompileClassLayout(EInternalCompilerFlags::PostponeLocalsGenerationUntilPhaseTwo); // We immediately relink children so that iterative compilation logic has an easier time: TArray<UClass*> ClassesToRelink; GetDerivedClasses(BP->GeneratedClass, ClassesToRelink, false); for (UClass* ChildClass : ClassesToRelink) { ChildClass->Bind(); ChildClass->StaticLink(); ensure(ChildClass->ClassDefaultObject == nullptr); } } else { CompilerData.ActiveResultsLog->Error(*LOCTEXT("KismetCompileError_MalformedParentClasss", "Blueprint @@ has missing or NULL parent class.").ToString(), BP); } } else if(CompilerData.Compiler.IsValid() && BP->GeneratedClass) { CompilerData.Compiler->SetNewClass( CastChecked<UBlueprintGeneratedClass>(BP->GeneratedClass) ); } } bGeneratedClassLayoutReady = true; // STAGE XIII: Compile functions UBlueprintEditorSettings* Settings = GetMutableDefault<UBlueprintEditorSettings>(); const bool bSaveBlueprintsAfterCompile = Settings->SaveOnCompile == SoC_Always; const bool bSaveBlueprintAfterCompileSucceeded = Settings->SaveOnCompile == SoC_SuccessOnly; for (FCompilerData& CompilerData : CurrentlyCompilingBPs) { UBlueprint* BP = CompilerData.BP; UClass* BPGC = BP->GeneratedClass; if(!CompilerData.ShouldCompileClassFunctions()) { if( BPGC && ( BPGC->ClassDefaultObject == nullptr || BPGC->ClassDefaultObject->GetClass() != BPGC) ) { // relink, generate CDO: BPGC->ClassFlags &= ~CLASS_LayoutChanging; BPGC->Bind(); BPGC->StaticLink(true); BPGC->ClassDefaultObject = nullptr; BPGC->GetDefaultObject(true); } } else { // default value propagation occurrs below: if(BPGC) { if( BPGC->ClassDefaultObject && BPGC->ClassDefaultObject->GetClass() == BPGC) { // the CDO has been created early, it is possible that the reflection data was still // being mutated by CompileClassLayout. Warn the user and and move the CDO aside: ensureAlwaysMsgf(false, TEXT("ClassDefaultObject for %s created at the wrong time - it may be corrupt. It is recommended that you save all data and restart the editor session"), *BP->GetName() ); BPGC->ClassDefaultObject->Rename( nullptr, // destination - this is the important part of this call. Moving the object // out of the way so we can reuse its name: GetTransientPackage(), // Rename options: REN_DoNotDirty | REN_DontCreateRedirectors | REN_ForceNoResetLoaders ); } BPGC->ClassDefaultObject = nullptr; // class layout is ready, we can clear CLASS_LayoutChanging and CompileFunctions can create the CDO: BPGC->ClassFlags &= ~CLASS_LayoutChanging; FKismetCompilerContext& CompilerContext = *(CompilerData.Compiler); CompilerContext.CompileFunctions( EInternalCompilerFlags::PostponeLocalsGenerationUntilPhaseTwo |EInternalCompilerFlags::PostponeDefaultObjectAssignmentUntilReinstancing |EInternalCompilerFlags::SkipRefreshExternalBlueprintDependencyNodes ); } if (CompilerData.ActiveResultsLog->NumErrors == 0) { // Blueprint is error free. Go ahead and fix up debug info BP->Status = (0 == CompilerData.ActiveResultsLog->NumWarnings) ? BS_UpToDate : BS_UpToDateWithWarnings; BP->BlueprintSystemVersion = UBlueprint::GetCurrentBlueprintSystemVersion(); // Reapply breakpoints to the bytecode of the new class for (UBreakpoint* Breakpoint : BP->Breakpoints) { FKismetDebugUtilities::ReapplyBreakpoint(Breakpoint); } } else { BP->Status = BS_Error; // do we still have the old version of the class? } // SOC settings only apply after compile on load: if(!BP->bIsRegeneratingOnLoad) { if(bSaveBlueprintsAfterCompile || (bSaveBlueprintAfterCompileSucceeded && BP->Status == BS_UpToDate)) { CompiledBlueprintsToSave.Add(BP); } } } if(BPGC) { BPGC->ClassFlags &= ~CLASS_ReplicationDataIsSetUp; BPGC->SetUpRuntimeReplicationData(); } ensure(BPGC == nullptr || BPGC->ClassDefaultObject->GetClass() == BPGC); } } // end GTimeCompiling scope // STAGE XIV: Now we can finish the first stage of the reinstancing operation, moving old classes to new classes: { { TArray<FReinstancingJob> Reinstancers; // Set up reinstancing jobs - we need a reference to the compiler in order to honor // CopyTermDefaultsToDefaultObject for (FCompilerData& CompilerData : CurrentlyCompilingBPs) { if(CompilerData.Reinstancer.IsValid() && CompilerData.Reinstancer->ClassToReinstance) { Reinstancers.Push( FReinstancingJob { CompilerData.Reinstancer, CompilerData.Compiler } ); } } FScopedDurationTimer ReinstTimer(GTimeReinstancing); ReinstanceBatch(Reinstancers, ClassesToReinstance, InLoadContext); // We purposefully do not remove the OldCDOs yet, need to keep them in memory past first GC } // STAGE XV: POST CDO COMPILED for (FCompilerData& CompilerData : CurrentlyCompilingBPs) { if(!CompilerData.IsSkeletonOnly() && CompilerData.Compiler.IsValid()) { CompilerData.Compiler->PostCDOCompiled(); } } // STAGE XV: CLEAR TEMPORARY FLAGS for (FCompilerData& CompilerData : CurrentlyCompilingBPs) { UBlueprint* BP = CompilerData.BP; if (!CompilerData.IsSkeletonOnly()) { FBlueprintEditorUtils::UpdateDelegatesInBlueprint(BP); if (!BP->bIsRegeneratingOnLoad && BP->GeneratedClass) { FKismetEditorUtilities::StripExternalComponents(BP); if (BP->SimpleConstructionScript) { BP->SimpleConstructionScript->FixupRootNodeParentReferences(); } if (BP->Status != BS_Error) { if (CompilerData.Compiler.IsValid()) { // Route through the compiler context in order to perform type-specific Blueprint class validation. CompilerData.Compiler->ValidateGeneratedClass(CastChecked<UBlueprintGeneratedClass>(BP->GeneratedClass)); if (CompilerData.ShouldValidateClassDefaultObject()) { // Our CDO should be properly constructed by this point and should always exist UObject* ClassDefaultObject = BP->GeneratedClass->GetDefaultObject(false); if (ensureAlways(ClassDefaultObject)) { FKismetCompilerUtilities::ValidateEnumProperties(ClassDefaultObject, *CompilerData.ActiveResultsLog); // Make sure any class-specific validation passes on the CDO TArray<FText> ValidationErrors; EDataValidationResult ValidateCDOResult = ClassDefaultObject->IsDataValid(/*out*/ ValidationErrors); if (ValidateCDOResult == EDataValidationResult::Invalid) { for (const FText& ValidationError : ValidationErrors) { CompilerData.ActiveResultsLog->Error(*ValidationError.ToString()); } } // Adjust Blueprint status to match anything new that was found during validation. if (CompilerData.ActiveResultsLog->NumErrors > 0) { BP->Status = BS_Error; } else if (BP->Status == BS_UpToDate && CompilerData.ActiveResultsLog->NumWarnings > 0) { BP->Status = BS_UpToDateWithWarnings; } } } } else { UBlueprint::ValidateGeneratedClass(BP->GeneratedClass); } } } } if(CompilerData.ShouldRegisterCompilerResults()) { // This helper structure registers the results log messages with the UI control that displays them: FScopedBlueprintMessageLog MessageLog(BP); MessageLog.Log->ClearMessages(); MessageLog.Log->AddMessages(CompilerData.ActiveResultsLog->Messages, false); } if(CompilerData.ShouldSetTemporaryBlueprintFlags()) { BP->bBeingCompiled = false; BP->CurrentMessageLog = nullptr; BP->bIsRegeneratingOnLoad = false; } if(UPackage* Package = BP->GetOutermost()) { Package->SetDirtyFlag(CompilerData.bPackageWasDirty); } } // Make sure no junk in bytecode, this can happen only for blueprints that were in CurrentlyCompilingBPs because // the reinstancer can detect all other references (see UpdateBytecodeReferences): for (FCompilerData& CompilerData : CurrentlyCompilingBPs) { if(CompilerData.ShouldCompileClassFunctions()) { if(BlueprintsCompiled) { BlueprintsCompiled->Add(CompilerData.BP); } if(!bSuppressBroadcastCompiled) { // Some logic (e.g. UObject::ProcessInternal) uses this flag to suppress warnings: TGuardValue<bool> ReinstancingGuard(GIsReinstancing, true); CompilerData.BP->BroadcastCompiled(); } continue; } UBlueprint* BP = CompilerData.BP; for( TFieldIterator<UFunction> FuncIter(BP->GeneratedClass, EFieldIteratorFlags::ExcludeSuper); FuncIter; ++FuncIter ) { UFunction* CurrentFunction = *FuncIter; if( CurrentFunction->Script.Num() > 0 ) { FFixupBytecodeReferences ValidateAr(CurrentFunction); } } } if (!bSuppressBroadcastCompiled) { if(GEditor) { GEditor->BroadcastBlueprintCompiled(); } } } for (FCompilerData& CompilerData : CurrentlyCompilingBPs) { if(CompilerData.ResultsLog) { CompilerData.ResultsLog->EndEvent(); } CompilerData.BP->bQueuedForCompilation = false; } UEdGraphPin::Purge(); UE_LOG(LogBlueprint, Display, TEXT("Time Compiling: %f, Time Reinstancing: %f"), GTimeCompiling, GTimeReinstancing); //GTimeCompiling = 0.0; //GTimeReinstancing = 0.0; ensure(QueuedRequests.Num() == 0); } void FBlueprintCompilationManagerImpl::FlushReinstancingQueueImpl() { if(GCompilingBlueprint) { return; } TGuardValue<bool> GuardTemplateNameFlag(GCompilingBlueprint, true); // we can finalize reinstancing now: if(ClassesToReinstance.Num() == 0) { return; } { FScopedDurationTimer ReinstTimer(GTimeReinstancing); TGuardValue<bool> ReinstancingGuard(GIsReinstancing, true); FBlueprintCompileReinstancer::BatchReplaceInstancesOfClass(ClassesToReinstance, true); if (IsAsyncLoading()) { // While async loading we only remove classes that have no instances being // async loaded. Those instances will need to be reinstanced once they finish // loading, there's no race here because if any instances are created after // we check ClassHasInstancesAsyncLoading they will be created with the new class: for( TMap<UClass*, UClass*>::TIterator It(ClassesToReinstance); It; ++It ) { if (!ClassHasInstancesAsyncLoading(It->Key)) { It.RemoveCurrent(); } } } else { ClassesToReinstance.Empty(); } } #if VERIFY_NO_STALE_CLASS_REFERENCES FBlueprintSupport::ValidateNoRefsToOutOfDateClasses(); #endif #if VERIFY_NO_BAD_SKELETON_REFERENCES FBlueprintSupport::ValidateNoExternalRefsToSkeletons(); #endif UE_LOG(LogBlueprint, Display, TEXT("Time Compiling: %f, Time Reinstancing: %f"), GTimeCompiling, GTimeReinstancing); } bool FBlueprintCompilationManagerImpl::HasBlueprintsToCompile() const { return QueuedRequests.Num() != 0; } bool FBlueprintCompilationManagerImpl::IsGeneratedClassLayoutReady() const { return bGeneratedClassLayoutReady; } void FBlueprintCompilationManagerImpl::GetDefaultValue(const UClass* ForClass, const UProperty* Property, FString& OutDefaultValueAsString) const { if(!ForClass || !Property) { return; } if (ForClass->ClassDefaultObject) { FBlueprintEditorUtils::PropertyValueToString(Property, (uint8*)ForClass->ClassDefaultObject, OutDefaultValueAsString); } else { UBlueprint* BP = Cast<UBlueprint>(ForClass->ClassGeneratedBy); if(ensure(BP)) { const UObject* const* OldCDO = OldCDOs.Find(BP); if(OldCDO && *OldCDO) { const UClass* OldClass = (*OldCDO)->GetClass(); const UProperty* OldProperty = OldClass->FindPropertyByName(Property->GetFName()); if(OldProperty) { FBlueprintEditorUtils::PropertyValueToString(OldProperty, (uint8*)*OldCDO, OutDefaultValueAsString); } } } } } void FBlueprintCompilationManagerImpl::ReparentHierarchies(const TMap<UClass*, UClass*>& OldClassToNewClass) { // something has decided to replace instances of a class. We need to update all the children of those types: TSet<TPair<UClass*, UClass*>> ClassesToReinstance; for(const TPair<UClass*, UClass*>& OldToNewClass : OldClassToNewClass) { TArray<UClass*> DerivedClasses; // Just like when compiling we have to gather all children, not just immediate children. This is so that we can // update things like the ClassConstructor pointer in case it changed: GetDerivedClasses(OldToNewClass.Key, DerivedClasses); for(UClass* DerivedClass : DerivedClasses) { if(DerivedClass->GetSuperClass() == OldToNewClass.Key) { // need to reparent, change the old parent class to the new one: ClassesToReinstance.Add( TPair<UClass*, UClass*>(DerivedClass, OldToNewClass.Value) ); } else { // just need to reinstance, parent class can remain the same as // it is generally stable (outside of hotreload/asset reload): ClassesToReinstance.Add( TPair<UClass*, UClass*>(DerivedClass, DerivedClass->GetSuperClass()) ); } } } // create reinstancers: TArray<FReinstancingJob> Reinstancers; for(const TPair<UClass*, UClass*> OldToNewParentClass : ClassesToReinstance) { Reinstancers.Push( { TSharedPtr<FBlueprintCompileReinstancer>( new FBlueprintCompileReinstancer( OldToNewParentClass.Key, EBlueprintCompileReinstancerFlags::AutoInferSaveOnCompile | EBlueprintCompileReinstancerFlags::AvoidCDODuplication ) ), TSharedPtr<FKismetCompilerContext>() } ); } // reparent blueprints, now that their cdo has been moved aside and the REINST_ type has been created for old instances: TMap<UClass*, UClass*> OldClassToNewClassIncludingChildren = OldClassToNewClass; for(const FReinstancingJob& ReinstancingJob : Reinstancers) { UClass* ClassToReinstance = ReinstancingJob.Reinstancer->ClassToReinstance; ClassToReinstance->ClassConstructor = nullptr; ClassToReinstance->ClassVTableHelperCtorCaller = nullptr; ClassToReinstance->ClassAddReferencedObjects = nullptr; UClass* const* NewParent = OldClassToNewClass.Find(ClassToReinstance->GetSuperClass()); if(NewParent) { check(*NewParent); ClassToReinstance->SetSuperStruct(*NewParent); } ClassToReinstance->Bind(); ClassToReinstance->ClearFunctionMapsCaches(); ClassToReinstance->StaticLink(true); OldClassToNewClassIncludingChildren.Add(ReinstancingJob.Reinstancer->DuplicatedClass, ClassToReinstance); } // reparenting done, reinstance the hierarchy and update archetypes: ReinstanceBatch(Reinstancers, OldClassToNewClassIncludingChildren, nullptr); // reinstance instances - but only the classes we created, rest will be handled by caller TMap<UClass*, UClass*> OldClassToNewClassDerivedTypes; for(const FReinstancingJob& ReinstancingJob : Reinstancers) { OldClassToNewClassDerivedTypes.Add(ReinstancingJob.Reinstancer->DuplicatedClass, ReinstancingJob.Reinstancer->ClassToReinstance); } TGuardValue<bool> ReinstancingGuard(GIsReinstancing, true); FBlueprintCompileReinstancer::BatchReplaceInstancesOfClass( OldClassToNewClassDerivedTypes, /* bArchetypesAreUpToDate */ true ); } void FBlueprintCompilationManagerImpl::BuildDSOMap(UObject* OldObject, UObject* NewObject, TMap<UObject*, UObject*>& OutOldToNewDSO) { // IsDefaultObject() unfortunately cannot be relied upon for archetypes, so we explicitly search for the flag: TArray<UObject*> OldSubobjects; ForEachObjectWithOuter(OldObject, [&OldSubobjects](UObject* Object) { if (Object->HasAnyFlags(RF_DefaultSubObject)) { OldSubobjects.Add(Object); } }, false); for(UObject* OldSubobject : OldSubobjects) { UObject* NewSubobject = NewObject ? StaticFindObjectFast(UObject::StaticClass(), NewObject, OldSubobject->GetFName()) : nullptr; // It may seem aggressive to ensure here, but we should always have a new version of the DSO. If that's // not the case then some testing will need to be done on client of OutOldToNewDSO OutOldToNewDSO.Add(OldSubobject, NewSubobject); BuildDSOMap(OldSubobject, NewSubobject, OutOldToNewDSO); } } void FBlueprintCompilationManagerImpl::ReinstanceBatch(TArray<FReinstancingJob>& Reinstancers, TMap< UClass*, UClass* >& InOutOldToNewClassMap, FUObjectSerializeContext* InLoadContext) { const auto FilterOutOfDateClasses = [](TArray<UClass*>& ClassList) { ClassList.RemoveAllSwap( [](UClass* Class) { return Class->HasAnyClassFlags(CLASS_NewerVersionExists); } ); }; const auto HasChildren = [FilterOutOfDateClasses](UClass* InClass) -> bool { TArray<UClass*> ChildTypes; GetDerivedClasses(InClass, ChildTypes, false); FilterOutOfDateClasses(ChildTypes); return ChildTypes.Num() > 0; }; TSet<UClass*> ClassesToReparent; TSet<UClass*> ClassesToReinstance; // Reinstancers may contain *part* of a class hierarchy, so we first need to reparent any child types that // haven't already been reinstanced: for (const FReinstancingJob& ReinstancingJob : Reinstancers) { const TSharedPtr<FBlueprintCompileReinstancer>& CurrentReinstancer = ReinstancingJob.Reinstancer; UClass* OldClass = CurrentReinstancer->DuplicatedClass; if(!OldClass) { continue; } InOutOldToNewClassMap.Add(OldClass, CurrentReinstancer->ClassToReinstance); if(!HasChildren(OldClass)) { continue; } bool bParentLayoutChanged = !FStructUtils::TheSameLayout(OldClass, CurrentReinstancer->ClassToReinstance); if(bParentLayoutChanged) { // we need *all* derived types: TArray<UClass*> ClassesToReinstanceList; GetDerivedClasses(OldClass, ClassesToReinstanceList); FilterOutOfDateClasses(ClassesToReinstanceList); for(UClass* ClassToReinstance : ClassesToReinstanceList) { ClassesToReinstance.Add(ClassToReinstance); } } else { // parent layout did not change, we can just relink the direct children: TArray<UClass*> ClassesToReparentList; GetDerivedClasses(OldClass, ClassesToReparentList, false); FilterOutOfDateClasses(ClassesToReparentList); for(UClass* ClassToReparent : ClassesToReparentList) { ClassesToReparent.Add(ClassToReparent); } } } for(UClass* Class : ClassesToReparent) { UClass** NewParent = InOutOldToNewClassMap.Find(Class->GetSuperClass()); check(NewParent && *NewParent); Class->SetSuperStruct(*NewParent); Class->Bind(); Class->StaticLink(true); } // make new hierarchy for(UClass* Class : ClassesToReinstance) { UObject* OriginalCDO = Class->ClassDefaultObject; Reinstancers.Emplace( FReinstancingJob { TSharedPtr<FBlueprintCompileReinstancer>( new FBlueprintCompileReinstancer( Class, EBlueprintCompileReinstancerFlags::AutoInferSaveOnCompile|EBlueprintCompileReinstancerFlags::AvoidCDODuplication ) ), TSharedPtr<FKismetCompilerContext>() } ); // make sure we have the newest parent now that CDO has been moved to duplicate class: TSharedPtr<FBlueprintCompileReinstancer>& NewestReinstancer = Reinstancers.Last().Reinstancer; UClass* SuperClass = NewestReinstancer->ClassToReinstance->GetSuperClass(); if(ensure(SuperClass)) { if(SuperClass->HasAnyClassFlags(CLASS_NewerVersionExists)) { NewestReinstancer->ClassToReinstance->SetSuperStruct(SuperClass->GetAuthoritativeClass()); } } // relink the new class: NewestReinstancer->ClassToReinstance->Bind(); NewestReinstancer->ClassToReinstance->StaticLink(true); } // run UpdateBytecodeReferences: for (const FReinstancingJob& ReinstancingJob : Reinstancers) { const TSharedPtr<FBlueprintCompileReinstancer>& CurrentReinstancer = ReinstancingJob.Reinstancer; if (CurrentReinstancer->DuplicatedClass) { InOutOldToNewClassMap.Add(CurrentReinstancer->DuplicatedClass, CurrentReinstancer->ClassToReinstance); } UBlueprint* CompiledBlueprint = UBlueprint::GetBlueprintFromClass(CurrentReinstancer->ClassToReinstance); CurrentReinstancer->UpdateBytecodeReferences(); } // Now we can update templates and archetypes - note that we don't look for direct references to archetypes - doing // so is very expensive and it will be much faster to directly update anything that cares to cache direct references // to an archetype here (e.g. a UClass::ClassDefaultObject member): // 1. Sort classes so that most derived types are updated last - right now the only caller of this function // also sorts, but we don't want to make too many assumptions about caller. We could refine this API so that // we're not taking a raw list of reinstancers: Reinstancers.Sort( [](const FReinstancingJob& ReinstancingDataA, const FReinstancingJob& ReinstancingDataB) { const TSharedPtr<FBlueprintCompileReinstancer>& CompilerDataA = ReinstancingDataA.Reinstancer; const TSharedPtr<FBlueprintCompileReinstancer>& CompilerDataB = ReinstancingDataB.Reinstancer; UClass* A = CompilerDataA->ClassToReinstance; UClass* B = CompilerDataB->ClassToReinstance; int32 DepthA = 0; int32 DepthB = 0; UStruct* Iter = A ? A->GetSuperStruct() : nullptr; while (Iter) { ++DepthA; Iter = Iter->GetSuperStruct(); } Iter = B ? B->GetSuperStruct() : nullptr; while (Iter) { ++DepthB; Iter = Iter->GetSuperStruct(); } if (DepthA == DepthB && A && B) { return A->GetFName() < B->GetFName(); } return DepthA < DepthB; } ); // 2. Copy defaults from old CDO - CDO may be missing if this class was reinstanced and relinked here, // so use GetDefaultObject(true): for (const FReinstancingJob& ReinstancingJob : Reinstancers) { const TSharedPtr<FBlueprintCompileReinstancer>& CurrentReinstancer = ReinstancingJob.Reinstancer; UObject* OldCDO = nullptr; if (CurrentReinstancer->DuplicatedClass) { OldCDO = CurrentReinstancer->DuplicatedClass->ClassDefaultObject; if (OldCDO) { UObject* NewCDO = CurrentReinstancer->ClassToReinstance->GetDefaultObject(true); FBlueprintCompileReinstancer::CopyPropertiesForUnrelatedObjects(OldCDO, NewCDO, true); if (ReinstancingJob.Compiler.IsValid()) { ReinstancingJob.Compiler->PropagateValuesToCDO(NewCDO, OldCDO); } } } if (UBlueprintGeneratedClass* BPGClass = CastChecked<UBlueprintGeneratedClass>(CurrentReinstancer->ClassToReinstance)) { BPGClass->UpdateCustomPropertyListForPostConstruction(); // patch new cdo into linker table: if(OldCDO) { UBlueprint* CurrentBP = CastChecked<UBlueprint>(BPGClass->ClassGeneratedBy); if(FLinkerLoad* CurrentLinker = CurrentBP->GetLinker()) { int32 OldCDOIndex = INDEX_NONE; for (int32 i = 0; i < CurrentLinker->ExportMap.Num(); i++) { FObjectExport& ThisExport = CurrentLinker->ExportMap[i]; if (ThisExport.ObjectFlags & RF_ClassDefaultObject) { OldCDOIndex = i; break; } } if(OldCDOIndex != INDEX_NONE) { FBlueprintEditorUtils::PatchNewCDOIntoLinker(CurrentBP->GeneratedClass->ClassDefaultObject, CurrentLinker, OldCDOIndex, InLoadContext); FBlueprintEditorUtils::PatchCDOSubobjectsIntoExport(OldCDO, CurrentBP->GeneratedClass->ClassDefaultObject); } } } } } TMap<UObject*, UObject*> OldArchetypeToNewArchetype; // 3. Update any remaining instances that are tagged as RF_ArchetypeObject or RF_InheritableComponentTemplate - // we may need to do further sorting to ensure that interdependent archetypes are initialized correctly: TSet<UObject*> ArchetypeReferencers; for (const FReinstancingJob& ReinstancingJob : Reinstancers) { const TSharedPtr<FBlueprintCompileReinstancer>& CurrentReinstancer = ReinstancingJob.Reinstancer; UClass* OldClass = CurrentReinstancer->DuplicatedClass; if(OldClass) { UClass* NewClass = CurrentReinstancer->ClassToReinstance; if (NewClass && OldClass->ClassDefaultObject && NewClass->ClassDefaultObject && OldClass->ClassDefaultObject != NewClass->ClassDefaultObject) { OldArchetypeToNewArchetype.Add(OldClass->ClassDefaultObject, NewClass->ClassDefaultObject); } TArray<UObject*> ArchetypeObjects; GetObjectsOfClass(OldClass, ArchetypeObjects, false); // filter out non-archetype instances, note that WidgetTrees and some component // archetypes do not have RF_ArchetypeObject or RF_InheritableComponentTemplate so // we simply detect that they are outered to a UBPGC or UBlueprint and assume that // they are archetype objects in practice: ArchetypeObjects.RemoveAllSwap( [](UObject* Obj) { bool bIsArchetype = Obj->HasAnyFlags(RF_ArchetypeObject|RF_InheritableComponentTemplate) || Obj->GetTypedOuter<UBlueprintGeneratedClass>() || Obj->GetTypedOuter<UBlueprint>(); // remove if this is not an archetype or its already in the transient package, note // that things that are not directly outered to the transient package will be // 'reinst'd', this is specifically to handle components, which need to be up to date // on the REINST_ actor class: return !bIsArchetype || Obj->GetOuter() == GetTransientPackage(); } ); // for each archetype: for(UObject* Archetype : ArchetypeObjects ) { // make sure we fix up references in the owner: { UObject* Iter = Archetype->GetOuter(); while(Iter) { UBlueprintGeneratedClass* IterAsBPGC = Cast<UBlueprintGeneratedClass>(Iter); if(Iter->HasAnyFlags(RF_ClassDefaultObject) || (IterAsBPGC && !IterAsBPGC->HasAnyClassFlags(CLASS_NewerVersionExists)) || Cast<UBlueprint>(Iter) ) { ArchetypeReferencers.Add(Iter); // Component templates are referenced by the UBlueprint, but are outered to the UBPGC. Both // will need to be updated. Realistically there is no reason to refernce these in the // UBlueprint, so there is no reason to generalize this behavior: if(IterAsBPGC) { ArchetypeReferencers.Add(IterAsBPGC->ClassGeneratedBy); } // this handles nested subobjects: TArray<UObject*> ContainedObjects; GetObjectsWithOuter(Iter, ContainedObjects); ArchetypeReferencers.Append(ContainedObjects); } Iter = Iter->GetOuter(); } } // move aside: FName OriginalName = Archetype->GetFName(); UObject* OriginalOuter = Archetype->GetOuter(); EObjectFlags OriginalFlags = Archetype->GetFlags(); UObject* Destination = GetOuterForRename(Archetype->GetClass()); Archetype->Rename( nullptr, // destination - this is the important part of this call. Moving the object // out of the way so we can reuse its name: Destination, // Rename options: REN_DoNotDirty | REN_DontCreateRedirectors | REN_ForceNoResetLoaders ); // reconstruct FMakeClassSpawnableOnScope TemporarilySpawnable(CurrentReinstancer->ClassToReinstance); const EObjectFlags FlagMask = RF_Public | RF_ArchetypeObject | RF_Transactional | RF_Transient | RF_TextExportTransient | RF_InheritableComponentTemplate | RF_Standalone; //TODO: what about RF_RootSet? UObject* NewArchetype = NewObject<UObject>(OriginalOuter, CurrentReinstancer->ClassToReinstance, OriginalName, OriginalFlags & FlagMask); // grab the old archetype's subobjects: { TArray<UObject*> OldSubobjects; GetObjectsWithOuter( Archetype, OldSubobjects, false ); for(UObject* Subobject : OldSubobjects ) { if(Subobject->HasAnyFlags(RF_DefaultSubObject)) { // CPFUO handles DSOs: continue; } // Non DSO subobject - just reuse the subobject: Subobject->Rename( nullptr, // destination: NewArchetype, // Rename options: REN_DoNotDirty | REN_DontCreateRedirectors | REN_ForceNoResetLoaders ); } } OldArchetypeToNewArchetype.Add(Archetype, NewArchetype); // also map old *default* subobjects to new default subobjects: BuildDSOMap(Archetype, NewArchetype, OldArchetypeToNewArchetype); ArchetypeReferencers.Add(NewArchetype); FLinkerLoad::PRIVATE_PatchNewObjectIntoExport(Archetype, NewArchetype); Archetype->RemoveFromRoot(); Archetype->MarkPendingKill(); } } } // This loop finishes the reinstancing of archetypes after the entire Outer hierarchy has been updated with new instances: for (const FReinstancingJob& ReinstancingJob : Reinstancers) { const TSharedPtr<FBlueprintCompileReinstancer>& CurrentReinstancer = ReinstancingJob.Reinstancer; UClass* OldClass = CurrentReinstancer->DuplicatedClass; if(OldClass) { TArray<UObject*> OldInstances; GetObjectsOfClass( OldClass, OldInstances, false ); for(UObject* OldInstance : OldInstances) { UObject** NewInstance = OldArchetypeToNewArchetype.Find(OldInstance); // NewInstance may be null in the case of deleted or EditorOnly (in -game) DSOs: if(NewInstance && *NewInstance) { // The new object hierarchy has been created, all of the old instances are in the transient package and new // ones have taken their place. Referenc members will mostly be pointing at *old* instances, and will get fixed // up below: FBlueprintCompileReinstancer::CopyPropertiesForUnrelatedObjects(OldInstance, *NewInstance, false); } } } } // 4. update known references to archetypes (e.g. component templates, WidgetTree). We don't want to run the normal // reference finder to update these because searching the entire object graph is time consuming. Instead we just replace // all references in our UBlueprint and its generated class: for (const FReinstancingJob& ReinstancingJob : Reinstancers) { const TSharedPtr<FBlueprintCompileReinstancer>& CurrentReinstancer = ReinstancingJob.Reinstancer; ArchetypeReferencers.Add(CurrentReinstancer->ClassToReinstance); ArchetypeReferencers.Add(CurrentReinstancer->ClassToReinstance->ClassGeneratedBy); if(UBlueprint* BP = Cast<UBlueprint>(CurrentReinstancer->ClassToReinstance->ClassGeneratedBy)) { // The only known way to cause this ensure to trip is to enqueue blueprints for compilation // while blueprints are already compiling: if( ensure(BP->SkeletonGeneratedClass) ) { ArchetypeReferencers.Add(BP->SkeletonGeneratedClass); } ensure(BP->bCachedDependenciesUpToDate); for(const TWeakObjectPtr<UBlueprint>& Dependency : BP->CachedDependencies) { if (UBlueprint* DependencyBP = Dependency.Get()) { ArchetypeReferencers.Add(DependencyBP); } } } } for(UObject* ArchetypeReferencer : ArchetypeReferencers) { UPackage* NewPackage = ArchetypeReferencer->GetOutermost(); FArchiveReplaceOrClearExternalReferences<UObject> ReplaceInCDOAr(ArchetypeReferencer, OldArchetypeToNewArchetype, NewPackage); } } /* This function completely replaces the 'skeleton only' compilation pass in the Kismet compiler. Long term that code path will be removed and clients will be redirected to this function. Notes to maintainers: any UObject created here and outered to the resulting class must be marked as transient or you will create a cook error! */ UClass* FBlueprintCompilationManagerImpl::FastGenerateSkeletonClass(UBlueprint* BP, FKismetCompilerContext& CompilerContext, bool bIsSkeletonOnly, TArray<FSkeletonFixupData>& OutSkeletonFixupData) { const UEdGraphSchema_K2* Schema = GetDefault<UEdGraphSchema_K2>(); FCompilerResultsLog MessageLog; UClass* ParentClass = BP->ParentClass; if(ParentClass == nullptr) { return nullptr; } if(ParentClass->ClassGeneratedBy) { if(UBlueprint* ParentBP = Cast<UBlueprint>(ParentClass->ClassGeneratedBy)) { if(ParentBP->SkeletonGeneratedClass) { ParentClass = ParentBP->SkeletonGeneratedClass; } } } UBlueprintGeneratedClass* Ret = nullptr; UBlueprintGeneratedClass* OriginalNewClass = CompilerContext.NewClass; FString SkelClassName = FString::Printf(TEXT("SKEL_%s_C"), *BP->GetName()); // Temporarily set the compile type to indicate that we're generating the skeleton class. TGuardValue<EKismetCompileType::Type> GuardCompileType(CompilerContext.CompileOptions.CompileType, EKismetCompileType::SkeletonOnly); // Temporarily set the flag to indicate whether or not we'll only be generating the skeleton class as part of the overall compile request. TGuardValue<bool> GuardSkeletonOnly(CompilerContext.bIsSkeletonOnly, bIsSkeletonOnly); if (BP->SkeletonGeneratedClass == nullptr) { // This might exist in the package because we are being reloaded in place BP->SkeletonGeneratedClass = FindObject<UBlueprintGeneratedClass>(BP->GetOutermost(), *SkelClassName); } if (BP->SkeletonGeneratedClass == nullptr) { CompilerContext.SpawnNewClass(SkelClassName); Ret = CompilerContext.NewClass; Ret->SetFlags(RF_Transient); CompilerContext.NewClass = OriginalNewClass; } else { Ret = CastChecked<UBlueprintGeneratedClass>(*(BP->SkeletonGeneratedClass)); CompilerContext.CleanAndSanitizeClass(Ret, Ret->ClassDefaultObject); } Ret->ClassGeneratedBy = BP; // This is a version of PrecompileFunction that does not require 'terms' and graph cloning: const auto MakeFunction = [Ret, ParentClass, Schema, BP, &MessageLog, &OutSkeletonFixupData] ( FName FunctionNameFName, UField**& InCurrentFieldStorageLocation, UField**& InCurrentParamStorageLocation, EFunctionFlags InFunctionFlags, const TArray<UK2Node_FunctionResult*>& ReturnNodes, const TArray<UEdGraphPin*>& InputPins, bool bIsStaticFunction, bool bForceArrayStructRefsConst, UFunction* SignatureOverride) -> UFunction* { if(!ensure(FunctionNameFName != FName()) || FindObjectFast<UField>(Ret, FunctionNameFName)) { return nullptr; } UFunction* NewFunction = NewObject<UFunction>(Ret, FunctionNameFName, RF_Public|RF_Transient); Ret->AddFunctionToFunctionMap(NewFunction, NewFunction->GetFName()); *InCurrentFieldStorageLocation = NewFunction; InCurrentFieldStorageLocation = &NewFunction->Next; if(bIsStaticFunction) { NewFunction->FunctionFlags |= FUNC_Static; } UFunction* ParentFn = ParentClass->FindFunctionByName(NewFunction->GetFName()); if(ParentFn == nullptr) { // check for function in implemented interfaces: for(const FBPInterfaceDescription& BPID : BP->ImplementedInterfaces) { // we only want the *skeleton* version of the function: UClass* InterfaceClass = BPID.Interface; // We need to null check because FBlueprintEditorUtils::ConformImplementedInterfaces won't run until // after the skeleton classes have been generated: if(InterfaceClass) { if(UBlueprint* Owner = Cast<UBlueprint>(InterfaceClass->ClassGeneratedBy)) { if( ensure(Owner->SkeletonGeneratedClass) ) { InterfaceClass = Owner->SkeletonGeneratedClass; } } if(UFunction* ParentInterfaceFn = InterfaceClass->FindFunctionByName(NewFunction->GetFName())) { ParentFn = ParentInterfaceFn; break; } } } } NewFunction->SetSuperStruct( ParentFn ); InCurrentParamStorageLocation = &NewFunction->Children; // params: if(ParentFn || SignatureOverride) { UFunction* SignatureFn = ParentFn ? ParentFn : SignatureOverride; NewFunction->FunctionFlags |= (SignatureFn->FunctionFlags & (FUNC_FuncInherit | FUNC_Public | FUNC_Protected | FUNC_Private | FUNC_BlueprintPure)); for (TFieldIterator<UProperty> PropIt(SignatureFn); PropIt && (PropIt->PropertyFlags & CPF_Parm); ++PropIt) { UProperty* ClonedParam = CastChecked<UProperty>(StaticDuplicateObject(*PropIt, NewFunction, PropIt->GetFName(), RF_AllFlags, nullptr, EDuplicateMode::Normal, EInternalObjectFlags::AllFlags & ~(EInternalObjectFlags::Native) )); ClonedParam->PropertyFlags |= CPF_BlueprintVisible|CPF_BlueprintReadOnly; ClonedParam->Next = nullptr; *InCurrentParamStorageLocation = ClonedParam; InCurrentParamStorageLocation = &ClonedParam->Next; } UMetaData::CopyMetadata(SignatureFn, NewFunction); } else { NewFunction->FunctionFlags |= InFunctionFlags; for(UEdGraphPin* Pin : InputPins) { if(Pin->Direction == EEdGraphPinDirection::EGPD_Output && !Schema->IsExecPin(*Pin) && Pin->ParentPin == nullptr && Pin->GetFName() != UK2Node_Event::DelegateOutputName) { // Reimplementation of FKismetCompilerContext::CreatePropertiesFromList without dependence on 'terms' UProperty* Param = FKismetCompilerUtilities::CreatePropertyOnScope(NewFunction, Pin->PinName, Pin->PinType, Ret, CPF_BlueprintVisible|CPF_BlueprintReadOnly, Schema, MessageLog); if(Param) { Param->SetFlags(RF_Transient); Param->PropertyFlags |= CPF_Parm; if(Pin->PinType.bIsReference) { Param->PropertyFlags |= CPF_ReferenceParm | CPF_OutParm; } if(Pin->PinType.bIsConst || (bForceArrayStructRefsConst && (Pin->PinType.IsArray() || Pin->PinType.PinCategory == UEdGraphSchema_K2::PC_Struct) && Pin->PinType.bIsReference)) { Param->PropertyFlags |= CPF_ConstParm; } if (UObjectProperty* ObjProp = Cast<UObjectProperty>(Param)) { UClass* EffectiveClass = nullptr; if (ObjProp->PropertyClass != nullptr) { EffectiveClass = ObjProp->PropertyClass; } else if (UClassProperty* ClassProp = Cast<UClassProperty>(ObjProp)) { EffectiveClass = ClassProp->MetaClass; } if ((EffectiveClass != nullptr) && (EffectiveClass->HasAnyClassFlags(CLASS_Const))) { Param->PropertyFlags |= CPF_ConstParm; } } else if (UArrayProperty* ArrayProp = Cast<UArrayProperty>(Param)) { Param->PropertyFlags |= CPF_ReferenceParm; // ALWAYS pass array parameters as out params, so they're set up as passed by ref Param->PropertyFlags |= CPF_OutParm; } // Delegate properties have a direct reference to a UFunction that we may currently be generating, so we're going // to track them and fix them after all UFunctions have been generated. As you can tell we're tightly coupled // to the implementation of CreatePropertyOnScope else if( UDelegateProperty* DelegateProp = Cast<UDelegateProperty>(Param)) { OutSkeletonFixupData.Add( { Pin->PinType.PinSubCategoryMemberReference, DelegateProp } ); } else if( UMulticastDelegateProperty* MCDelegateProp = Cast<UMulticastDelegateProperty>(Param)) { OutSkeletonFixupData.Add( { Pin->PinType.PinSubCategoryMemberReference, MCDelegateProp } ); } *InCurrentParamStorageLocation = Param; InCurrentParamStorageLocation = &Param->Next; } } } if(ReturnNodes.Num() > 0) { // Gather all input pins on these nodes, these are // the outputs of the function: TSet<FName> UsedPinNames; static const FName RetValName = FName(TEXT("ReturnValue")); for(UK2Node_FunctionResult* Node : ReturnNodes) { for(UEdGraphPin* Pin : Node->Pins) { if(!Schema->IsExecPin(*Pin) && Pin->ParentPin == nullptr) { if(!UsedPinNames.Contains(Pin->PinName)) { UsedPinNames.Add(Pin->PinName); UProperty* Param = FKismetCompilerUtilities::CreatePropertyOnScope(NewFunction, Pin->PinName, Pin->PinType, Ret, CPF_None, Schema, MessageLog); if(Param) { Param->SetFlags(RF_Transient); // we only tag things as CPF_ReturnParm if the value is named ReturnValue.... this is *terrible* behavior: if(Param->GetFName() == RetValName) { Param->PropertyFlags |= CPF_ReturnParm; } Param->PropertyFlags |= CPF_Parm|CPF_OutParm; *InCurrentParamStorageLocation = Param; InCurrentParamStorageLocation = &Param->Next; } } } } } } } // We're linking the skeleton function because TProperty::LinkInternal // will assign add TTypeFundamentals::GetComputedFlagsPropertyFlags() // to PropertyFlags. PropertyFlags must (mostly) match in order for // functions to be compatible: NewFunction->StaticLink(true); return NewFunction; }; // helpers: const auto AddFunctionForGraphs = [Schema, &MessageLog, ParentClass, Ret, BP, MakeFunction](const TCHAR* FunctionNamePostfix, const TArray<UEdGraph*>& Graphs, UField**& InCurrentFieldStorageLocation, bool bIsStaticFunction, bool bAreDelegateGraphs) { for( const UEdGraph* Graph : Graphs ) { TArray<UK2Node_FunctionEntry*> EntryNodes; Graph->GetNodesOfClass(EntryNodes); if(EntryNodes.Num() > 0) { TArray<UK2Node_FunctionResult*> ReturnNodes; Graph->GetNodesOfClass(ReturnNodes); UK2Node_FunctionEntry* EntryNode = EntryNodes[0]; UField** CurrentParamStorageLocation = nullptr; UFunction* NewFunction = MakeFunction( FName(*(Graph->GetName() + FunctionNamePostfix)), InCurrentFieldStorageLocation, CurrentParamStorageLocation, (EFunctionFlags)(EntryNode->GetFunctionFlags() & ~FUNC_Native), ReturnNodes, EntryNode->Pins, bIsStaticFunction, false, nullptr ); if(NewFunction) { if(bAreDelegateGraphs) { NewFunction->FunctionFlags |= FUNC_Delegate; } // locals: for( const FBPVariableDescription& BPVD : EntryNode->LocalVariables ) { if(UProperty* LocalVariable = FKismetCompilerContext::CreateUserDefinedLocalVariableForFunction(BPVD, NewFunction, Ret, CurrentParamStorageLocation, Schema, MessageLog) ) { LocalVariable->SetFlags(RF_Transient); } } // __WorldContext: if(bIsStaticFunction) { if( FindField<UObjectProperty>(NewFunction, TEXT("__WorldContext")) == nullptr ) { FEdGraphPinType WorldContextPinType(UEdGraphSchema_K2::PC_Object, NAME_None, UObject::StaticClass(), EPinContainerType::None, false, FEdGraphTerminalType()); UProperty* Param = FKismetCompilerUtilities::CreatePropertyOnScope(NewFunction, TEXT("__WorldContext"), WorldContextPinType, Ret, CPF_None, Schema, MessageLog); if(Param) { Param->SetFlags(RF_Transient); Param->PropertyFlags |= CPF_Parm; *CurrentParamStorageLocation = Param; CurrentParamStorageLocation = &Param->Next; } } // set the metdata: NewFunction->SetMetaData(FBlueprintMetadata::MD_WorldContext, TEXT("__WorldContext")); } FKismetCompilerContext::SetCalculatedMetaDataAndFlags(NewFunction, EntryNode, Schema); } } } }; UField** CurrentFieldStorageLocation = &Ret->Children; // Helper function for making UFunctions generated for 'event' nodes, e.g. custom event and timelines const auto MakeEventFunction = [&CurrentFieldStorageLocation, MakeFunction, Schema]( FName InName, EFunctionFlags ExtraFnFlags, const TArray<UEdGraphPin*>& InputPins, const TArray< TSharedPtr<FUserPinInfo> >& UserPins, UFunction* InSourceFN, bool bInCallInEditor ) { UField** CurrentParamStorageLocation = nullptr; UFunction* NewFunction = MakeFunction( InName, CurrentFieldStorageLocation, CurrentParamStorageLocation, ExtraFnFlags|FUNC_BlueprintCallable|FUNC_BlueprintEvent, TArray<UK2Node_FunctionResult*>(), InputPins, false, true, InSourceFN ); if(NewFunction) { FKismetCompilerContext::SetDefaultInputValueMetaData(NewFunction, UserPins); if(bInCallInEditor) { NewFunction->SetMetaData(FBlueprintMetadata::MD_CallInEditor, TEXT( "true" )); } NewFunction->Bind(); NewFunction->StaticLink(true); } }; Ret->SetSuperStruct(ParentClass); Ret->ClassFlags |= (ParentClass->ClassFlags & CLASS_Inherit); Ret->ClassCastFlags |= ParentClass->ClassCastFlags; if (FBlueprintEditorUtils::IsInterfaceBlueprint(BP)) { Ret->ClassFlags |= CLASS_Interface; } // link in delegate signatures, variables will reference these AddFunctionForGraphs(HEADER_GENERATED_DELEGATE_SIGNATURE_SUFFIX, BP->DelegateSignatureGraphs, CurrentFieldStorageLocation, false, true); // handle event entry ponts (mostly custom events) - this replaces // the skeleton compile pass CreateFunctionStubForEvent call: TArray<UEdGraph*> AllEventGraphs; for (UEdGraph* UberGraph : BP->UbergraphPages) { AllEventGraphs.Add(UberGraph); UberGraph->GetAllChildrenGraphs(AllEventGraphs); } for( const UEdGraph* Graph : AllEventGraphs ) { TArray<UK2Node_Event*> EventNodes; Graph->GetNodesOfClass(EventNodes); for( UK2Node_Event* Event : EventNodes ) { bool bCallInEditor = false; if(UK2Node_CustomEvent* CustomEvent = Cast<UK2Node_CustomEvent>(Event)) { bCallInEditor = CustomEvent->bCallInEditor; } MakeEventFunction( CompilerContext.GetEventStubFunctionName(Event), (EFunctionFlags)Event->FunctionFlags, Event->Pins, Event->UserDefinedPins, Event->FindEventSignatureFunction(), bCallInEditor ); } } for (UTimelineTemplate* Timeline : BP->Timelines) { if(Timeline) { // If the timeline hasn't gone through post load that means that the cache isn't up to date, so force an update on it if (Timeline->HasAllFlags(RF_NeedPostLoad) && Timeline->GetLinkerCustomVersion(FFortniteMainBranchObjectVersion::GUID) < FFortniteMainBranchObjectVersion::StoreTimelineNamesInTemplate) { FUpdateTimelineCachedNames::Execute(Timeline); } for (const FTTEventTrack& EventTrack : Timeline->EventTracks) { MakeEventFunction(EventTrack.GetFunctionName(), EFunctionFlags::FUNC_None, TArray<UEdGraphPin*>(), TArray< TSharedPtr<FUserPinInfo> >(), nullptr, false); } MakeEventFunction(Timeline->GetUpdateFunctionName(), EFunctionFlags::FUNC_None, TArray<UEdGraphPin*>(), TArray< TSharedPtr<FUserPinInfo> >(), nullptr, false); MakeEventFunction(Timeline->GetFinishedFunctionName(), EFunctionFlags::FUNC_None, TArray<UEdGraphPin*>(), TArray< TSharedPtr<FUserPinInfo> >(), nullptr, false); } } { CompilerContext.NewClass = Ret; TGuardValue<bool> GuardAssignDelegateSignatureFunction( CompilerContext.bAssignDelegateSignatureFunction, true); TGuardValue<bool> GuardGenerateSubInstanceVariables( CompilerContext.bGenerateSubInstanceVariables, true); CompilerContext.CreateClassVariablesFromBlueprint(); CompilerContext.NewClass = OriginalNewClass; } UField* Iter = Ret->Children; while(Iter) { CurrentFieldStorageLocation = &Iter->Next; Iter = Iter->Next; } AddFunctionForGraphs(TEXT(""), BP->FunctionGraphs, CurrentFieldStorageLocation, BPTYPE_FunctionLibrary == BP->BlueprintType, false); // Add interface functions, often these are added by normal detection of implemented functions, but they won't be // if the interface is added but the function is not implemented: for(const FBPInterfaceDescription& BPID : BP->ImplementedInterfaces) { UClass* InterfaceClass = BPID.Interface; // Again, once the skeleton has been created we will purge null ImplementedInterfaces entries, // but not yet: if(InterfaceClass) { if(UBlueprint* Owner = Cast<UBlueprint>(InterfaceClass->ClassGeneratedBy)) { if( ensure(Owner->SkeletonGeneratedClass) ) { InterfaceClass = Owner->SkeletonGeneratedClass; } } AddFunctionForGraphs(TEXT(""), BPID.Graphs, CurrentFieldStorageLocation, BPTYPE_FunctionLibrary == BP->BlueprintType, false); for (TFieldIterator<UFunction> FunctionIt(InterfaceClass, EFieldIteratorFlags::ExcludeSuper); FunctionIt; ++FunctionIt) { UFunction* Fn = *FunctionIt; UField** CurrentParamStorageLocation = nullptr; // Note that MakeFunction will early out if the function was created above: MakeFunction( Fn->GetFName(), CurrentFieldStorageLocation, CurrentParamStorageLocation, Fn->FunctionFlags & ~FUNC_Native, TArray<UK2Node_FunctionResult*>(), TArray<UEdGraphPin*>(), false, false, nullptr ); } } } // Add the uber graph frame just so that we match the old skeleton class's layout. This will be removed in 4.20: if (CompilerContext.UsePersistentUberGraphFrame() && AllEventGraphs.Num() != 0) { //UBER GRAPH PERSISTENT FRAME FEdGraphPinType Type(TEXT("struct"), NAME_None, FPointerToUberGraphFrame::StaticStruct(), EPinContainerType::None, false, FEdGraphTerminalType()); CompilerContext.NewClass = Ret; UProperty* Property = CompilerContext.CreateVariable(UBlueprintGeneratedClass::GetUberGraphFrameName(), Type); CompilerContext.NewClass = OriginalNewClass; Property->SetPropertyFlags(CPF_DuplicateTransient | CPF_Transient); } CompilerContext.NewClass = Ret; CompilerContext.bAssignDelegateSignatureFunction = true; CompilerContext.FinishCompilingClass(Ret); CompilerContext.bAssignDelegateSignatureFunction = false; CompilerContext.NewClass = OriginalNewClass; Ret->GetDefaultObject()->SetFlags(RF_Transient); return Ret; } bool FBlueprintCompilationManagerImpl::IsQueuedForCompilation(UBlueprint* BP) { return BP->bQueuedForCompilation; } UObject* FBlueprintCompilationManagerImpl::GetOuterForRename(UClass* ForClass) { // if someone has tautologically placed themself within their own hierarchy then we'll // just assume they're ok with eventually being outered to a upackage, similar UPackage // is a UObject, so if someone demands that they be outered to 'a uobject' we'll // just leave them directly parented to the transient package: if(ForClass->ClassWithin && ForClass->ClassWithin != ForClass && ForClass->ClassWithin != UObject::StaticClass()) { return NewObject<UObject>( GetOuterForRename(ForClass->ClassWithin), ForClass->ClassWithin, NAME_None, RF_Transient ); } return GetTransientPackage(); } // FFixupBytecodeReferences Implementation: FBlueprintCompilationManagerImpl::FFixupBytecodeReferences::FFixupBytecodeReferences(UObject* InObject) { ArIsObjectReferenceCollector = true; InObject->Serialize(*this); class FArchiveProxyCollector : public FReferenceCollector { /** Archive we are a proxy for */ FArchive& Archive; public: FArchiveProxyCollector(FArchive& InArchive) : Archive(InArchive) { } virtual void HandleObjectReference(UObject*& Object, const UObject* ReferencingObject, const UProperty* ReferencingProperty) override { Archive << Object; } virtual void HandleObjectReferences(UObject** InObjects, const int32 ObjectNum, const UObject* InReferencingObject, const UProperty* InReferencingProperty) override { for (int32 ObjectIndex = 0; ObjectIndex < ObjectNum; ++ObjectIndex) { UObject*& Object = InObjects[ObjectIndex]; Archive << Object; } } virtual bool IsIgnoringArchetypeRef() const override { return false; } virtual bool IsIgnoringTransient() const override { return false; } } ArchiveProxyCollector(*this); InObject->GetClass()->CallAddReferencedObjects(InObject, ArchiveProxyCollector); } FArchive& FBlueprintCompilationManagerImpl::FFixupBytecodeReferences::operator<<( UObject*& Obj ) { if (Obj != NULL) { if(UClass* RelatedClass = Cast<UClass>(Obj)) { UClass* NewClass = RelatedClass->GetAuthoritativeClass(); ensure(NewClass); if(NewClass != RelatedClass) { Obj = NewClass; } } else if(UField* AsField = Cast<UField>(Obj)) { UClass* OwningClass = AsField->GetOwnerClass(); if(OwningClass) { UClass* NewClass = OwningClass->GetAuthoritativeClass(); ensure(NewClass); if(NewClass != OwningClass) { // drill into new class finding equivalent object: TArray<FName> Names; UObject* Iter = Obj; while (Iter && Iter != OwningClass) { Names.Add(Iter->GetFName()); Iter = Iter->GetOuter(); } UObject* Owner = NewClass; UObject* Match = nullptr; for(int32 I = Names.Num() - 1; I >= 0; --I) { UObject* Next = StaticFindObjectFast( UObject::StaticClass(), Owner, Names[I]); if( Next ) { if(I == 0) { Match = Next; } else { Owner = Match; } } else { break; } } if(Match) { Obj = Match; } } } } } return *this; } // Singleton boilerplate, simply forwarding to the implementation above: FBlueprintCompilationManagerImpl* BPCMImpl = nullptr; void FlushReinstancingQueueImplWrapper() { BPCMImpl->FlushReinstancingQueueImpl(); } // Recursive function to move CDOs aside to immutable versions of classes // so that CDOs can be safely GC'd. Recursion is necessary to find REINST_ classes // that are still parented to a valid SKEL (e.g. from MarkBlueprintAsStructurallyModified) // and therefore need to be REINST_'d again before the SKEL is mutated... Normally // these old REINST_ classes are GC'd but, there is no guarantee of that: void MoveSkelCDOAside(UClass* Class, TMap<UClass*, UClass*>& OutOldToNewMap) { UClass* CopyOfOldClass = FBlueprintCompileReinstancer::MoveCDOToNewClass(Class, OutOldToNewMap, true); OutOldToNewMap.Add(Class, CopyOfOldClass); // Child types that are associated with a BP will be compiled by the compilation // manager, but old REINST_ or TRASH_ types need to be handled explicitly: TArray<UClass*> Children; GetDerivedClasses(Class, Children); for(UClass* Child : Children) { if(UBlueprint* BP = Cast<UBlueprint>(Child->ClassGeneratedBy)) { if(BP->SkeletonGeneratedClass != Child) { if( ensureMsgf ( BP->GeneratedClass != Child, TEXT("Class in skeleton hierarchy is cached as GeneratedClass")) ) { MoveSkelCDOAside(Child, OutOldToNewMap); } } } } }; void FBlueprintCompilationManager::Initialize() { if(!BPCMImpl) { BPCMImpl = new FBlueprintCompilationManagerImpl(); } } void FBlueprintCompilationManager::Shutdown() { delete BPCMImpl; BPCMImpl = nullptr; } // Forward to impl: void FBlueprintCompilationManager::FlushCompilationQueue(FUObjectSerializeContext* InLoadContext) { if(BPCMImpl) { BPCMImpl->FlushCompilationQueueImpl(false, nullptr, nullptr, InLoadContext); // We can't support save on compile or keeping old CDOs from GCing when reinstancing is deferred: BPCMImpl->CompiledBlueprintsToSave.Empty(); BPCMImpl->OldCDOs.Empty(); } } void FBlueprintCompilationManager::FlushCompilationQueueAndReinstance() { if(BPCMImpl) { BPCMImpl->FlushCompilationQueueImpl(false, nullptr, nullptr, nullptr); BPCMImpl->FlushReinstancingQueueImpl(); BPCMImpl->OldCDOs.Empty(); } } void FBlueprintCompilationManager::CompileSynchronously(const FBPCompileRequest& Request) { if(BPCMImpl) { BPCMImpl->CompileSynchronouslyImpl(Request); } } void FBlueprintCompilationManager::NotifyBlueprintLoaded(UBlueprint* BPLoaded) { // Blueprints can be loaded before editor modules are on line: if(!BPCMImpl) { FBlueprintCompilationManager::Initialize(); } if(FBlueprintEditorUtils::IsCompileOnLoadDisabled(BPLoaded)) { return; } check(BPLoaded->GetLinker()); BPCMImpl->QueueForCompilation(FBPCompileRequest(BPLoaded, EBlueprintCompileOptions::IsRegeneratingOnLoad, nullptr)); } void FBlueprintCompilationManager::QueueForCompilation(UBlueprint* BPLoaded) { BPCMImpl->QueueForCompilation(FBPCompileRequest(BPLoaded, EBlueprintCompileOptions::None, nullptr)); } bool FBlueprintCompilationManager::IsGeneratedClassLayoutReady() { if(!BPCMImpl) { // legacy behavior: always assume generated class layout is good: return true; } return BPCMImpl->IsGeneratedClassLayoutReady(); } bool FBlueprintCompilationManager::GetDefaultValue(const UClass* ForClass, const UProperty* Property, FString& OutDefaultValueAsString) { if(!BPCMImpl) { // legacy behavior: can't provide CDO for classes currently being compiled return false; } BPCMImpl->GetDefaultValue(ForClass, Property, OutDefaultValueAsString); return true; } void FBlueprintCompilationManager::ReparentHierarchies(const TMap<UClass*, UClass*>& OldClassToNewClass) { FBlueprintCompilationManagerImpl::ReparentHierarchies(OldClassToNewClass); } #undef LOCTEXT_NAMESPACE
411
0.530673
1
0.530673
game-dev
MEDIA
0.537165
game-dev
0.854704
1
0.854704
google/google-ctf
3,364
2024/quals/misc-h8-teaser/attachments/hackceler8-2023/game/components/weapon_systems/base.py
# Copyright 2023 Google LLC # # 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 # # https://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. import arcade.key import engine.generics as generics import engine.hitbox as hitbox class Weapon(generics.GenericObject): def __init__(self, coords, name, display_name, flipped, weapon_type, damage_type, damage_algo, tileset_path=None, collectable=True, outline=None): super().__init__(coords, nametype="Weapon", tileset_path=tileset_path, outline=outline, can_flash=True, can_flip=True) self.weapon_type = weapon_type self.damage_type = damage_type self.damage_algo = damage_algo self.name = name self.display_name = display_name self.cool_down_timer = 0 self.charging = False if flipped: self.sprite.set_flipped(True) # Weapons start as inactive and are activated by default self.active = False # If ai_controlled, weapons behave according to algo self.ai_controlled = True # If collectable, player can pick it up self.collectable = collectable # If destroyable, the player can destroy it (assuming it's AI controlled) self.destroyable = True # The player can only use (equip) one weapon at a time self.equipped = False def draw(self): if not self.ai_controlled and not self.equipped: return super().draw() def tick(self, pressed_keys, newly_pressed_keys, tics, player, origin="player"): super().tick() if self.cool_down_timer > 0: self.cool_down_timer -= 1 self.player = player if not self.active: return None if not self.ai_controlled: if not self.equipped: return None self.move_to_player() if not self.player.dead: if arcade.key.SPACE in newly_pressed_keys: return self.fire(tics, self.player.face_towards, origin) if arcade.key.SPACE in pressed_keys: self.charge() return None if self.charging and arcade.key.SPACE not in pressed_keys: return self.release_charged_shot(origin) # For AI controlled we pass the players to accommodate for aimbots else: return self.fire(tics, self.player, "AI") def move_to_player(self): self.place_at(self.player.x, self.player.y) if self.player.direction == self.player.DIR_W: self.sprite.set_flipped(True) elif self.player.direction == self.player.DIR_E: self.sprite.set_flipped(False) def charge(self): pass # Overridden by chargeable sub-classes. def release_charged_shot(self, origin): return None # Overridden by chargeable sub-classes.
411
0.812485
1
0.812485
game-dev
MEDIA
0.936042
game-dev
0.940803
1
0.940803
osgcc/ryzom
3,189
ryzom/server/src/entities_game_service/death_penalties.h
// Ryzom - MMORPG Framework <http://dev.ryzom.com/projects/ryzom/> // Copyright (C) 2010 Winch Gate Property Limited // // 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_DEATH_PENALTIES_H #define RY_DEATH_PENALTIES_H #include "egs_variables.h" #include "game_share/persistent_data.h" #include "game_share/skills.h" #include "game_share/timer.h" class CCharacter; /** * properties to manage death penalties * \author Nicolas Brigand * \author Nevrax France * \date 2004 */ class CDeathPenalties { NL_INSTANCE_COUNTER_DECL(CDeathPenalties); public: // Start by declaring methods for persistent load/ save operations // The following macro is defined in persistent_data.h // At time of writing it evaluated to: // void store(CPersistentDataRecord &pdr) const; // void apply(CPersistentDataRecord &pdr); DECLARE_PERSISTENCE_METHODS CDeathPenalties() :_NbDeath(0),_CurrentDeathXP(0.0),_DeathXPToGain(0.0),_BonusUpdateTime(0),_DeathPenaltyFactor(1.0f){} void clear() { _NbDeath = 0; _CurrentDeathXP = 0.0; _DeathXPToGain = 0.0; _BonusUpdateTime = 0; } void reset(CCharacter& user) { clear(); updataDb(user); } void addDeath(CCharacter& user, float deathPenaltyFactor); uint32 updateResorption( CCharacter& user ); void addXP( CCharacter& user, SKILLS::ESkills usedSkill, double & xp ); void addXP( CCharacter& user, SKILLS::ESkills usedSkill, double & xp, double xpRaw ); void serial( NLMISC::IStream & f ) { f.xmlPush("death_penalties"); f.xmlPush("nb_death"); f.serial(_NbDeath); f.xmlPop(); f.xmlPush("current_death_xp"); f.serial(_CurrentDeathXP); f.xmlPop(); f.xmlPush("death_xp_to_gain"); f.serial(_DeathXPToGain); f.xmlPop(); f.xmlPush("bonus_update_time"); f.serial(_BonusUpdateTime); f.xmlPop(); f.xmlPush("nb_death"); } void updataDb(CCharacter& user); bool isNull() const { return (_NbDeath == 0); } private: /// number of death of the player ( reset when there is no more XP malus ) uint8 _NbDeath; /// XP gained to recover from death double _CurrentDeathXP; /// XP to gain to recover from death malus double _DeathXPToGain; /// Last time at which bonus was given uint32 _BonusUpdateTime; /// factor of xp used for death penalty float _DeathPenaltyFactor; }; class CDeathPenaltiesTimerEvent:public CTimerEvent { public: CDeathPenaltiesTimerEvent(CCharacter *parent); void timerCallback(CTimer *owner); private: CCharacter *_Parent; }; #endif // RY_DEATH_PENALTIES_H /* End of death_penalties.h */
411
0.911684
1
0.911684
game-dev
MEDIA
0.241129
game-dev
0.579767
1
0.579767
man572142/Bro_Audio
6,782
Assets/BroAudio/Core/Scripts/Player/PlaybackGroup/DefaultPlaybackGroup.cs
using System; using System.Collections.Generic; using Ami.BroAudio.Data; using Ami.BroAudio.Runtime; using Ami.Extension; using UnityEditor; using UnityEngine; namespace Ami.BroAudio { /// <inheritdoc cref="PlaybackGroup"/> [CreateAssetMenu(menuName = nameof(BroAudio) + "/Playback Group", fileName = "PlaybackGroup", order = 0)] public partial class DefaultPlaybackGroup : PlaybackGroup { public const float DefaultCombFilteringTime = RuntimeSetting.FactorySettings.CombFilteringPreventionInSeconds; #region Max Playable Count Rule #if UNITY_EDITOR [CustomDrawingMethod(typeof(DefaultPlaybackGroup), nameof(DrawMaxPlayableLimitProperty))] #endif [SerializeField] [Tooltip("The maximum number of sounds that can be played simultaneously in this group")] [ValueButton("Infinity", -1)] private MaxPlayableCountRule _maxPlayableCount = -1; #endregion #region Comb-Filtering Rule [SerializeField] [ValueButton("Default", DefaultCombFilteringTime)] [Tooltip("Time interval to prevent the Comb-Filtering effect")] private CombFilteringRule _combFilteringTime = DefaultCombFilteringTime; [SerializeField] [DerivativeProperty] [InspectorName("Ignore If Same Frame")] [Tooltip("Ignore Comb-filtering prevention if identical sounds are played within the same frame")] private bool _ignoreCombFilteringIfSameFrame = false; [SerializeField] [DerivativeProperty] [InspectorName("Ignore If Distance Is Greater Than")] [Tooltip("Ignore Comb-filtering prevention if identical sounds are played farther apart than the specified distance")] private float _ignoreIfDistanceIsGreaterThan = 0.1f; [SerializeField] [DerivativeProperty(isEnd: true)] [InspectorName("Log Warning When Occurs")] [Tooltip("Log a warning message when the Comb-Filtering occurs")] private bool _logCombFilteringWarning = true; #endregion private int _currentPlayingCount; private Action<SoundID> _decreasePlayingCountDelegate; /// <inheritdoc cref="PlaybackGroup.InitializeRules"/> protected override IEnumerable<IRule> InitializeRules() { yield return Initialize(_maxPlayableCount, IsPlayableLimitNotReached); yield return Initialize(_combFilteringTime, HasPassedCombFilteringRule); } /// <summary> /// Manages the player and tracks the number of sounds currently playing. /// </summary> /// <param name="player"></param> public override void OnGetPlayer(IAudioPlayer player) { _currentPlayingCount++; _decreasePlayingCountDelegate ??= _ => _currentPlayingCount--; player.OnEnd(_decreasePlayingCountDelegate); } #region Rule Methods protected virtual bool IsPlayableLimitNotReached(SoundID id, Vector3 position) { return _maxPlayableCount <= 0 || _currentPlayingCount < _maxPlayableCount; } protected virtual bool HasPassedCombFilteringRule(SoundID id, Vector3 currentPlayPos) { if (_combFilteringTime <= 0f || !SoundManager.Instance.TryGetPreviousPlayerFromCombFilteringPreventer(id, out var previousPlayer)) { return true; } if (!HasPassedCombFilteringRule(previousPlayer, currentPlayPos)) { if (_logCombFilteringWarning) { Debug.LogWarning(Utility.LogTitle + $"One of the plays of Audio:{id.ToName().ToWhiteBold()} was rejected by the [Comb Filtering Time] rule."); } return false; } return true; } private bool HasPassedCombFilteringRule(AudioPlayer previousPlayer, Vector3 currentPlayPos) { int time = TimeExtension.UnscaledCurrentFrameBeganTime; int previousPlayTime = previousPlayer.PlaybackStartingTime; // the previous has been added to the queue but hasn't played yet, i.e., The current and the previous will end up being played in the same frame bool previousIsInQueue = Mathf.Approximately(previousPlayTime, 0f); float difference = time - previousPlayTime; bool isSameFrame = previousIsInQueue || Mathf.Approximately(difference, 0f); if((isSameFrame && _ignoreCombFilteringIfSameFrame) || (!isSameFrame && HasPassedCombFilteringTime())) { return true; } bool currentIsGlobal = Utility.IsPlayedGlobally(currentPlayPos); bool previousIsGlobal = Utility.IsPlayedGlobally(previousPlayer.PlayingPosition); // Both are played in the world space if (!currentIsGlobal && !previousIsGlobal) { var sqrDistance = (currentPlayPos - previousPlayer.PlayingPosition).sqrMagnitude; if (sqrDistance > Mathf.Pow(_ignoreIfDistanceIsGreaterThan, 2)) { return true; } } // Only one is played globally // TODO: use the AudioListener's position as the global position? if ((currentIsGlobal != previousIsGlobal) && _ignoreIfDistanceIsGreaterThan > 0f) { return true; } return false; bool HasPassedCombFilteringTime() => difference >= TimeExtension.SecToMs(_combFilteringTime); } #endregion private void OnEnable() { _currentPlayingCount = 0; } } #if UNITY_EDITOR public partial class DefaultPlaybackGroup : PlaybackGroup { private static object DrawMaxPlayableLimitProperty(SerializedProperty property) { float currentValue = property.intValue <= 0 ? float.PositiveInfinity : property.intValue; EditorGUI.BeginChangeCheck(); float newValue = EditorGUILayout.FloatField(currentValue); if (EditorGUI.EndChangeCheck()) { if (newValue <= 0f || float.IsInfinity(newValue) || float.IsNaN(newValue)) { property.intValue = -1; } else { property.intValue = newValue > currentValue ? Mathf.CeilToInt(newValue) : Mathf.FloorToInt(newValue); } } return property.intValue <= 0; } public static class NameOf { public const string CombFilteringTime = nameof(_combFilteringTime); } } #endif }
411
0.937828
1
0.937828
game-dev
MEDIA
0.887395
game-dev
0.963025
1
0.963025
AuburnSounds/Dplug
4,462
macos/derelict/carbon/coreservices.d
/** Dynamic bindings to the CoreServices framework. Copyright: Guillaume Piolat 2015. License: $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost License 1.0) */ module derelict.carbon.coreservices; import core.stdc.config; import dplug.core.sharedlib; import derelict.carbon.corefoundation; import dplug.core.nogc; version(OSX) enum libNames = "/System/Library/Frameworks/CoreServices.framework/CoreServices"; else enum libNames = ""; class DerelictCoreServicesLoader : SharedLibLoader { public { nothrow @nogc: this() { super(libNames); } override void loadSymbols() { bindFunc(cast(void**)&SetComponentInstanceStorage, "SetComponentInstanceStorage"); bindFunc(cast(void**)&GetComponentInstanceStorage, "GetComponentInstanceStorage"); bindFunc(cast(void**)&GetComponentInfo, "GetComponentInfo"); } } } private __gshared DerelictCoreServicesLoader DerelictCoreServices; private __gshared loaderCounterCS = 0; // Call this each time a novel owner uses these functions // TODO: hold a mutex, because this isn't thread-safe void acquireCoreServicesFunctions() nothrow @nogc { if (DerelictCoreServices is null) // You only live once { DerelictCoreServices = mallocNew!DerelictCoreServicesLoader(); DerelictCoreServices.load(); } } // Call this each time a novel owner releases a Cocoa functions // TODO: hold a mutex, because this isn't thread-safe void releaseCoreServicesFunctions() nothrow @nogc { /*if (--loaderCounterCS == 0) { DerelictCoreServices.unload(); DerelictCoreServices.destroyFree(); }*/ } unittest { version(OSX) { acquireCoreServicesFunctions(); releaseCoreServicesFunctions(); } } enum : int { typeSInt16 = CCONST('s', 'h', 'o', 'r'), typeUInt16 = CCONST('u', 's', 'h', 'r'), typeSInt32 = CCONST('l', 'o', 'n', 'g'), typeUInt32 = CCONST('m', 'a', 'g', 'n'), typeSInt64 = CCONST('c', 'o', 'm', 'p'), typeUInt64 = CCONST('u', 'c', 'o', 'm'), typeIEEE32BitFloatingPoint = CCONST('s', 'i', 'n', 'g'), typeIEEE64BitFloatingPoint = CCONST('d', 'o', 'u', 'b'), type128BitFloatingPoint = CCONST('l', 'd', 'b', 'l'), typeDecimalStruct = CCONST('d', 'e', 'c', 'm'), typeChar = CCONST('T', 'E', 'X', 'T'), } // <CarbonCore/MacErrors.h> enum : int { badComponentInstance = cast(int)0x80008001, badComponentSelector = cast(int)0x80008002 } enum { coreFoundationUnknownErr = -4960, } // <CarbonCore/Components.h> // LP64 => "long and pointers are 64-bit" static if (size_t.sizeof == 8 && c_long.sizeof == 8) private enum __LP64__ = 1; else private enum __LP64__ = 0; alias Component = void*; alias ComponentResult = int; alias ComponentInstance = void*; struct ComponentParameters { UInt8 flags; UInt8 paramSize; SInt16 what; static if (__LP64__) UInt32 padding; c_long[1] params; } static if (__LP64__) { static assert(ComponentParameters.sizeof == 16); } enum : int { kComponentOpenSelect = -1, kComponentCloseSelect = -2, kComponentCanDoSelect = -3, kComponentVersionSelect = -4, kComponentRegisterSelect = -5, kComponentTargetSelect = -6, kComponentUnregisterSelect = -7, kComponentGetMPWorkFunctionSelect = -8, kComponentExecuteWiredActionSelect = -9, kComponentGetPublicResourceSelect = -10 }; struct ComponentDescription { OSType componentType; OSType componentSubType; OSType componentManufacturer; UInt32 componentFlags; UInt32 componentFlagsMask; } extern(C) nothrow @nogc { alias da_SetComponentInstanceStorage = void function(ComponentInstance, Handle); alias da_GetComponentInfo = OSErr function(Component, ComponentDescription*, Handle, Handle, Handle); alias da_GetComponentInstanceStorage = Handle function(ComponentInstance aComponentInstance); } __gshared { da_SetComponentInstanceStorage SetComponentInstanceStorage; da_GetComponentInfo GetComponentInfo; da_GetComponentInstanceStorage GetComponentInstanceStorage; }
411
0.944915
1
0.944915
game-dev
MEDIA
0.268716
game-dev
0.886287
1
0.886287
RobotLocomotion/drake
46,011
multibody/tree/body_node_impl.cc
#include "drake/multibody/tree/body_node_impl.h" #include "drake/multibody/tree/curvilinear_mobilizer.h" #include "drake/multibody/tree/planar_mobilizer.h" #include "drake/multibody/tree/prismatic_mobilizer.h" #include "drake/multibody/tree/quaternion_floating_mobilizer.h" #include "drake/multibody/tree/revolute_mobilizer.h" #include "drake/multibody/tree/rpy_ball_mobilizer.h" #include "drake/multibody/tree/rpy_floating_mobilizer.h" #include "drake/multibody/tree/screw_mobilizer.h" #include "drake/multibody/tree/universal_mobilizer.h" #include "drake/multibody/tree/weld_mobilizer.h" namespace drake { namespace multibody { namespace internal { template <typename T, class ConcreteMobilizer> BodyNodeImpl<T, ConcreteMobilizer>::BodyNodeImpl(const BodyNode<T>* parent_node, const RigidBody<T>* rigid_body, const Mobilizer<T>* mobilizer) : BodyNode<T>(parent_node, rigid_body, mobilizer), mobilizer_(dynamic_cast<const ConcreteMobilizer*>(mobilizer)) { DRAKE_DEMAND(mobilizer_ != nullptr); } template <typename T, class ConcreteMobilizer> BodyNodeImpl<T, ConcreteMobilizer>::~BodyNodeImpl() = default; template <typename T, class ConcreteMobilizer> void BodyNodeImpl<T, ConcreteMobilizer>::CalcPositionKinematicsCache_BaseToTip( const FrameBodyPoseCache<T>& frame_body_pose_cache, const T* positions, PositionKinematicsCache<T>* pc) const { // This method must not be called for the "world" body node. DRAKE_ASSERT(mobod_index() != world_mobod_index()); DRAKE_ASSERT(pc != nullptr); // RigidBody for this node. const RigidBody<T>& body_B = body(); // RigidBody for this node's parent, or the parent body P. const RigidBody<T>& body_P = parent_body(); // Inboard (F)/Outboard (M) frames of this node's mobilizer. const Frame<T>& frame_F = inboard_frame(); DRAKE_ASSERT(frame_F.body().index() == body_P.index()); const Frame<T>& frame_M = outboard_frame(); DRAKE_ASSERT(frame_M.body().index() == body_B.index()); // Input (const): // - X_PF // - X_MB // - X_WP(q(W:P)), where q(W:P) includes all positions in the kinematics // path from parent body P to the world W. const math::RigidTransform<T>& X_PF = frame_F.get_X_BF(frame_body_pose_cache); // B==P const bool X_PF_is_identity = frame_F.is_X_BF_identity(frame_body_pose_cache); const math::RigidTransform<T>& X_MB = frame_M.get_X_FB(frame_body_pose_cache); // F==M const bool X_MB_is_identity = frame_M.is_X_BF_identity(frame_body_pose_cache); const math::RigidTransform<T>& X_WP = pc->get_X_WB(inboard_mobod_index()); // Output (updating a cache entry): // - X_FM(q_B) // - X_PB(q_B) // - X_WB(q(W:P), q_B) // - p_PoBo_W(q_B) math::RigidTransform<T>& X_FM = pc->get_mutable_X_FM(mobod_index()); math::RigidTransform<T>& X_PB = pc->get_mutable_X_PB(mobod_index()); math::RigidTransform<T>& X_WB = pc->get_mutable_X_WB(mobod_index()); Vector3<T>& p_PoBo_W = pc->get_mutable_p_PoBo_W(mobod_index()); // Update mobilizer-specific position dependent kinematics. mobilizer_->update_X_FM(get_q(positions), &X_FM); // FYI I measured the effect of the following optimization on CassieBench // position kinematics, over simply executing the general case always. It // runs about 10% faster with the optimization in place. // Cases: 0 general case // 1 only X_PF is identity (not likely) // 2 only X_MB is identity (very likely from urdf files) // 3 both are identity (doubtful) const int special_case = X_MB_is_identity << 1 | X_PF_is_identity; switch (special_case) { case 0: // The general case. { const math::RigidTransform<T> X_FB = mobilizer_->pre_multiply_by_X_FM(X_FM, X_MB); X_PB = X_PF * X_FB; X_WB = X_WP * X_PB; } break; case 1: // Only X_PF is identity. // X_PB = X_PF * X_FM * X_MB // = I * X_FM * X_MB X_PB = mobilizer_->pre_multiply_by_X_FM(X_FM, X_MB); X_WB = X_WP * X_PB; // No shortcut. break; case 2: // Only X_MB is identity (common case). // X_PB = X_PF * X_FM * X_MB // = X_PF * X_FM * I X_PB = mobilizer_->post_multiply_by_X_FM(X_PF, X_FM); X_WB = X_WP * X_PB; // No shortcut. break; case 3: // The best case: both X_PF and X_BM are identity. // X_PB = X_PF * X_FM * X_MB // = I * X_FM * I // X_WB = X_WP * X_PB // = X_WP * X_FM X_PB = X_FM; X_WB = mobilizer_->post_multiply_by_X_FM(X_WP, X_FM); break; } // Compute shift vector p_PoBo_W from the parent origin to the body origin. const Vector3<T>& p_PoBo_P = X_PB.translation(); const math::RotationMatrix<T>& R_WP = X_WP.rotation(); p_PoBo_W = R_WP * p_PoBo_P; } // TODO(sherm1) Consider combining this with VelocityCache computation // so that we don't have to make a separate pass. Or better, get rid of this // computation altogether by working in better frames. template <typename T, class ConcreteMobilizer> void BodyNodeImpl<T, ConcreteMobilizer>:: CalcAcrossNodeJacobianWrtVExpressedInWorld( const FrameBodyPoseCache<T>& frame_body_pose_cache, const T* positions, const PositionKinematicsCache<T>& pc, std::vector<Vector6<T>>* H_PB_W_cache) const { DRAKE_ASSERT(positions != nullptr); DRAKE_ASSERT(H_PB_W_cache != nullptr); DRAKE_ASSERT(mobod_index() != world_mobod_index()); // Nothing to do for a weld mobilizer. if constexpr (kNv > 0) { const Frame<T>& frame_F = inboard_frame(); const Frame<T>& frame_M = outboard_frame(); const math::RotationMatrix<T>& R_PF = frame_F.get_X_BF(frame_body_pose_cache).rotation(); // Get the rotation matrix relating the world frame W and parent body P. const math::RotationMatrix<T>& R_WP = get_R_WP(pc); // Orientation (rotation) of frame F with respect to the world frame W. const math::RotationMatrix<T> R_WF = R_WP * R_PF; const T* q = get_q(positions); // just this mobilizer's q's auto H_PB_W = get_mutable_H(H_PB_W_cache); // We compute H_FM(q) one column at a time by calling the multiplication by // H_FM operation on a vector of generalized velocities which is zero except // for its i-th component, which is one. // Note: it is frequently the case that the mobilizer outboard frame M is // coincident with the body frame B (and we cache that information for // quick access). That allows us to avoid a shift operation in the small // loop below. I (sherm1) timed velocity kinematics with and without this // optimization, introduced in PR #22977. With gcc 11.4.0 it accounts for // an almost 20% speedup in velocity kinematics, so is worth doing. const bool is_X_MB_identity = frame_M.is_X_BF_identity(frame_body_pose_cache); if (is_X_MB_identity) { VVector<T> v = VVector<T>::Zero(); for (int i = 0; i < kNv; ++i) { v(i) = 1.0; // Compute the i-th column of H_FM (== H_FB here). const SpatialVelocity<T> Hi_FB_F = mobilizer_->calc_V_FM(q, v.data()); v(i) = 0.0; // Frame F is fixed to rigid body P so V_PB = V_FB. H_PB_W.col(i) = (R_WF * Hi_FB_F).get_coeffs(); } return; } // X_MB is not identity. const Vector3<T>& p_MB_M = frame_M.get_X_FB(frame_body_pose_cache).translation(); // Vector from Mo to Bo expressed in frame F as needed below: const math::RotationMatrix<T>& R_FM = get_X_FM(pc).rotation(); const Vector3<T> p_MB_F = mobilizer_->apply_R_FM(R_FM, p_MB_M); VVector<T> v = VVector<T>::Zero(); for (int i = 0; i < kNv; ++i) { v(i) = 1.0; // Compute the i-th column of H_FM. const SpatialVelocity<T> Hi_FM = mobilizer_->calc_V_FM(q, v.data()); v(i) = 0.0; // Frame F is fixed to rigid body P so V_PB = V_FB = V_FM.Shift(p_MB). H_PB_W.col(i) = (R_WF * Hi_FM.Shift(p_MB_F)).get_coeffs(); } } } template <typename T, class ConcreteMobilizer> void BodyNodeImpl<T, ConcreteMobilizer>::CalcVelocityKinematicsCache_BaseToTip( const T* positions, const PositionKinematicsCache<T>& pc, const std::vector<Vector6<T>>& H_PB_W_cache, const T* velocities, VelocityKinematicsCache<T>* vc) const { // This method must not be called for the "world" body node. DRAKE_ASSERT(mobod_index() != world_mobod_index()); DRAKE_ASSERT(vc != nullptr); // Hinge matrix for this node. H_PB_W ∈ ℝ⁶ˣⁿᵐ with nm ∈ [0; 6] the // number of mobilities for this node. Therefore, the return is a // Matrix<6,kNv> since the number of columns depends on the mobilizer type. // It is returned as an Eigen::Map to the memory allocated in the // std::vector H_PB_W_cache so that we can work with H_PB_W as with any // other Eigen matrix object. // As a guideline for developers, a summary of the computations performed in // this method is provided: // Notation: // - B body frame associated with this node. // - P ("parent") body frame associated with this node's parent. // - F mobilizer inboard frame attached to body P. // - M mobilizer outboard frame attached to body B. // The goal is computing the spatial velocity V_WB of body B measured in the // world frame W. The calculation is recursive and assumes the spatial // velocity V_WP of the inboard body P is already computed. These spatial // velocities are related by the recursive relation: // V_WB = V_WPb + V_PB_W (Eq. 5.6 in Jain (2010), p. 77) (1) // where Pb is a frame aligned with P but with its origin shifted from Po // to B's origin Bo. Then V_WPb is the spatial velocity of frame Pb, // measured and expressed in the world frame W. Since V_PB's // translational component is also for the point Bo, we can add these // spatial velocities. Therefore we need to develop expressions for the two // terms (V_WPb and V_PB_W) in Eq. (1). // // Computation of V_PB_W: // Let Mb be a frame aligned rigidly with M but with its origin at Bo. // For rigid bodies (which we always have here) // V_PB_W = V_FMb_W (2) // which can be computed from the spatial velocity measured in frame F (as // provided by mobilizer's methods) // V_FMb_W = R_WF * V_FMb = R_WF * V_FM.Shift(p_MoBo_F) (3) // arriving at the desired result: // V_PB_W = R_WF * V_FM.Shift(p_MoBo_F) (4) // // V_FM = H_FM * vm is immediately available from this node's mobilizer where // H_FM is the mobilizer's hinge matrix, and vm this mobilizer's generalized // velocities. // // Computation of V_WPb: // This can be computed by a simple shift operation from V_WP: // V_WPb = V_WP.Shift(p_PoBo_W) (5) // // Note: // It is very common to find treatments in which the body frame B is // coincident with the outboard frame M, that is B ≡ M, leading to slightly // simpler recursive relations (for instance, see Section 3.3.2 in // Jain (2010)) where p_MoBo_F = 0 and thus V_PB_W = V_FM_W. // Generalized coordinates local to this node's mobilizer. const T* q_ptr = get_q(positions); const T* v_ptr = get_v(velocities); // ========================================================================= // Computation of V_PB_W in Eq. (1). See summary at the top of this method. // Update V_FM using the operator V_FM = H_FM * vm: SpatialVelocity<T>& V_FM = get_mutable_V_FM(vc); V_FM = mobilizer_->calc_V_FM(q_ptr, v_ptr); // Compute V_PB_W = R_WF * V_FM.Shift(p_MoBo_F), Eq. (4). // Side note to developers: in operator form for rigid bodies this would be // V_PB_W = R_WF * phiT_MB_F * V_FM // = R_WF * phiT_MB_F * H_FM * v // = H_PB_W * v // where H_PB_W = R_WF * phiT_MB_F * H_FM. SpatialVelocity<T>& V_PB_W = get_mutable_V_PB_W(vc); if constexpr (kNv > 0) { // Hinge matrix for this node. H_PB_W ∈ ℝ⁶ˣⁿᵛ with nv ∈ [0; 6] the // number of mobilities for this node. const auto H_PB_W = get_H(H_PB_W_cache); // 6 x kNv fixed-size Map. const Eigen::Map<const VVector<T>> v(v_ptr); V_PB_W.get_coeffs() = H_PB_W * v; } else { V_PB_W.get_coeffs().setZero(); } // ========================================================================= // Computation of V_WPb in Eq. (1). See summary at the top of this method. // Shift vector between the parent body P and this node's body B, // expressed in the world frame W. const Vector3<T>& p_PB_W = get_p_PoBo_W(pc); // Since we are in a base-to-tip recursion the parent body P's spatial // velocity is already available in the cache. const SpatialVelocity<T>& V_WP = get_V_WP(*vc); // ========================================================================= // Update velocity V_WB of this node's body B in the world frame. Using the // recursive Eq. (1). See summary at the top of this method. get_mutable_V_WB(vc) = V_WP.ComposeWithMovingFrameVelocity(p_PB_W, V_PB_W); } // As a guideline for developers, a summary of the computations performed in // this method is provided: // Notation: // - B body frame associated with this node. // - P ("parent") body frame associated with this node's parent. // - F mobilizer inboard frame attached to body P. // - M mobilizer outboard frame attached to body B. // The goal is computing the spatial acceleration A_WB of body B measured in // the world frame W. The calculation is recursive and assumes the spatial // acceleration A_WP of the inboard body P is already computed. // The spatial velocities of P and B are related by the recursive relation // (computation is performed by CalcVelocityKinematicsCache_BaseToTip(): // V_WB = V_WPb + V_PB_W (Eq. 5.6 in Jain (2010), p. 77) // = V_WP.ComposeWithMovingFrameVelocity(p_PB_W, V_PB_W) (1) // where Pb is a frame aligned with P but with its origin shifted from Po // to B's origin Bo. Then V_WPb is the spatial velocity of frame Pb, // measured and expressed in the world frame W. // // In the same way the parent body P velocity V_WP can be composed with body // B's velocity V_PB in P, the acceleration A_WB can be obtained by // composing A_WP with A_PB: // A_WB = A_WP.ComposeWithMovingFrameAcceleration( // p_PB_W, w_WP, V_PB_W, A_PB_W); (2) // which includes both centrifugal and coriolis terms. For details on this // operation refer to the documentation for // SpatialAcceleration::ComposeWithMovingFrameAcceleration(). // // By recursive precondition, this method was already called on all // predecessor nodes in the tree and therefore the acceleration A_WP is // already available. // V_WP (i.e. w_WP) and V_PB_W were computed in the velocity kinematics pass // and are therefore available in the VelocityKinematicsCache vc. // // Therefore, all that is left is computing A_PB_W = DtP(V_PB)_W. // The acceleration of B in P is: // A_PB = DtP(V_PB) = DtF(V_FMb) = A_FM.Shift(p_MB, w_FM) (3) // which expressed in the world frame leads to (see note below): // A_PB_W = R_WF * A_FM.Shift(p_MB_F, w_FM) (4) // where R_WF is the rotation matrix from F to W and A_FM expressed in the // inboard frame F is the direct result from // Mobilizer::CalcAcrossMobilizerAcceleration(). // // * Note: // The rigid body assumption is made in Eq. (3) in two places: // 1. DtP() = DtF() since V_PF = 0. // 2. V_PB = V_FMb since V_PB = V_PFb + V_FMb + V_MB but since P is // assumed rigid V_PF = 0 and since B is assumed rigid V_MB = 0. // // Note: ignores velocities if vc is null, in which case velocities must // also be null. template <typename T, class ConcreteMobilizer> void BodyNodeImpl<T, ConcreteMobilizer>::CalcSpatialAcceleration_BaseToTip( const FrameBodyPoseCache<T>& frame_body_poses_cache, const T* positions, const PositionKinematicsCache<T>& pc, const T* velocities, // can be null const VelocityKinematicsCache<T>* vc, // can be null const T* accelerations, std::vector<SpatialAcceleration<T>>* A_WB_array) const { // This method must not be called for the "world" body node. DRAKE_ASSERT(mobod_index() != world_mobod_index()); DRAKE_ASSERT(A_WB_array != nullptr); // This is the already-computed inboard (parent) acceleration. const SpatialAcceleration<T>& A_WP = (*A_WB_array)[inboard_mobod_index()]; // The to-be-computed acceleration of this body. SpatialAcceleration<T>& A_WB = (*A_WB_array)[mobod_index()]; const math::RigidTransform<T>& X_PF = inboard_frame().get_X_BF(frame_body_poses_cache); // B==P const math::RigidTransform<T>& X_MB = outboard_frame().get_X_FB(frame_body_poses_cache); // F==M const math::RotationMatrix<T>& R_PF = X_PF.rotation(); const math::RotationMatrix<T>& R_WP = get_R_WP(pc); // Orientation of frame F with respect to the world frame W. // TODO(amcastro-tri): consider caching X_WF, also used to compute H_PB_W. const math::RotationMatrix<T> R_WF = R_WP * R_PF; // Vector from Mo to Bo expressed in frame F as needed below: // TODO(amcastro-tri): consider caching p_MB_F, also used to compute H_PB_W. const math::RotationMatrix<T>& R_FM = get_X_FM(pc).rotation(); const Vector3<T>& p_MB_M = X_MB.translation(); const Vector3<T> p_MB_F = mobilizer_->apply_R_FM(R_FM, p_MB_M); // Shift vector between the parent body P and this node's body B, // expressed in the world frame W. const Vector3<T>& p_PB_W = get_p_PoBo_W(pc); // Early return if we don't have to deal with velocity. if (vc == nullptr) { DRAKE_ASSERT(velocities == nullptr); const VVector<T> v = VVector<T>::Zero(); // Operator A_FM = H_FM * vmdot + Hdot_FM * 0 const SpatialAcceleration<T> A_FM = mobilizer_->calc_A_FM(get_q(positions), v.data(), get_v(accelerations)); const SpatialAcceleration<T> A_PB_W = // Eq. (4), with w_FM = 0. R_WF * A_FM.ShiftWithZeroAngularVelocity(p_MB_F); // Velocities are zero. No need to compute terms that become zero. A_WB = A_WP.ShiftWithZeroAngularVelocity(p_PB_W) + A_PB_W; return; } // N.B. It is possible for positions & velocities to be null here if // the system consists only of welds (one of our unit tests does that). // Operator A_FM = H_FM(qₘ)⋅v̇ₘ + Ḣ_FM(qₘ,vₘ)⋅vₘ const SpatialAcceleration<T> A_FM = mobilizer_->calc_A_FM( get_q(positions), get_v(velocities), get_v(accelerations)); // Since we are in a base-to-tip recursion the parent body P's spatial // velocity is already available in the cache. const SpatialVelocity<T>& V_WP = get_V_WP(*vc); // For body B, only the spatial velocity V_PB_W is already available in // the cache. The acceleration A_PB_W was computed above. const SpatialVelocity<T>& V_PB_W = get_V_PB_W(*vc); // Across mobilizer velocity is available from the velocity kinematics. const SpatialVelocity<T>& V_FM = get_V_FM(*vc); const SpatialAcceleration<T> A_PB_W = R_WF * A_FM.Shift(p_MB_F, V_FM.rotational()); // Eq. (4) // Velocities are non-zero. A_WB = A_WP.ComposeWithMovingFrameAcceleration(p_PB_W, V_WP.rotational(), V_PB_W, A_PB_W); } // As a guideline for developers, a summary of the computations performed in // this method is provided: // Notation: // - B body frame associated with this node. // - P ("parent") body frame associated with this node's inboard node. // - F mobilizer inboard frame attached to body P. // - M mobilizer outboard frame attached to body B. // - Mo The origin of the outboard (or mobilized) frame M. // - C within a loop over "children", one of body B's outboard bodies. // - Mc The origin of the outboard (or mobilized) frame of the mobilizer // connecting B to C. // The goal is computing the spatial force F_BMo_W (on body B applied at its // mobilized frame origin Mo) exerted by its inboard mobilizer that is // required to produce the spatial acceleration A_WB. The generalized forces // are then obtained as the projection of the spatial force F_BMo in the // direction of this node's mobilizer motion. That is, the generalized // forces correspond to the working components of the spatial force living // in the motion sub-space of this node's mobilizer. // The calculation is recursive (from tip-to-base) and assumes the spatial // force F_CMc_W on body C at Mc is already computed in F_BMo_W_array. // // The spatial force through body B's inboard mobilizer is obtained from a // force balance (essentially the F = m * a for rigid bodies, see // [Jain 2010, Eq. 2.26, p. 27] for a derivation): // Ftot_BBo_W = M_Bo_W * A_WB + Fb_Bo_W (1) // where Fb_Bo_W contains the velocity dependent gyroscopic terms, // Ftot_BBo_W is the total spatial force on body B, applied at its origin Bo // and quantities are expressed in the world frame W (though the // expressed-in frame is not needed in a coordinate-free form.) // // The total spatial force on body B is the combined effect of externally // applied spatial forces Fapp_BMo on body B at Mo and spatial forces // induced by its inboard and outboard mobilizers. On its mobilized frame M, // in coordinate-free form: // Ftot_BMo = Fapp_BMo + F_BMo - Σᵢ(F_CiMo) (2) // where F_CiMo is the spatial force on the i-th child body Ci due to its // inboard mobilizer which, by action/reaction, applies to body B as // -F_CiMo, hence the negative sign in the summation above. The applied // spatial force Fapp_BMo at Mo is obtained by shifting the applied force // Fapp_Bo from Bo to Mo as Fapp_BMo.Shift(p_BoMo). // Therefore, spatial force F_BMo due to body B's mobilizer is: // F_BMo = Ftot_BMo + Σᵢ(F_CiMo) - Fapp_BMo (3) // The projection of this force on the motion sub-space of this node's // mobilizer corresponds to the generalized force tau: // tau = H_FMᵀ * F_BMo_F (4) // where the spatial force F_BMo must be re-expressed in the inboard frame F // before the projection can be performed. // Caution: we permit outputs F_BMo_W_array and tau_array to be the same // objects as Fapplied_Bo_W_array and tau_applied_array. template <typename T, class ConcreteMobilizer> void BodyNodeImpl<T, ConcreteMobilizer>::CalcInverseDynamics_TipToBase( const FrameBodyPoseCache<T>& frame_body_pose_cache, const T* positions, const PositionKinematicsCache<T>& pc, const std::vector<SpatialInertia<T>>& M_B_W_cache, const std::vector<SpatialForce<T>>* Fb_Bo_W_cache, const std::vector<SpatialAcceleration<T>>& A_WB_array, const std::vector<SpatialForce<T>>& Fapplied_Bo_W_array, const Eigen::Ref<const VectorX<T>>& tau_applied_array, std::vector<SpatialForce<T>>* F_BMo_W_array, EigenPtr<VectorX<T>> tau_array) const { DRAKE_ASSERT(F_BMo_W_array != nullptr && tau_array != nullptr); const bool is_Fapplied = (ssize(Fapplied_Bo_W_array) != 0); const bool is_tau_applied = (ssize(tau_applied_array) != 0); // Check sizes. DRAKE_ASSERT(this->has_parent_tree()); DRAKE_ASSERT(Fb_Bo_W_cache == nullptr || ssize(*Fb_Bo_W_cache) == this->get_parent_tree().num_mobods()); DRAKE_ASSERT(!is_Fapplied || ssize(Fapplied_Bo_W_array) == this->get_parent_tree().num_mobods()); DRAKE_ASSERT(!is_tau_applied || ssize(tau_applied_array) == this->get_parent_tree().num_velocities()); DRAKE_ASSERT(ssize(*F_BMo_W_array) == this->get_parent_tree().num_mobods()); DRAKE_ASSERT(ssize(*tau_array) == this->get_parent_tree().num_velocities()); // Calculate total spatial force on body B producing acceleration A_WB. // Ftot_BBo = M_B * A_WB + Fb_Bo const SpatialInertia<T>& M_B_W = M_B_W_cache[mobod_index()]; const SpatialAcceleration<T>& A_WB = A_WB_array[mobod_index()]; SpatialForce<T> Ftot_BBo_W = M_B_W * A_WB; // 45 flops if (Fb_Bo_W_cache != nullptr) { // Dynamic bias for body B. const SpatialForce<T>& Fb_Bo_W = (*Fb_Bo_W_cache)[mobod_index()]; Ftot_BBo_W += Fb_Bo_W; // 6 flops } // We're looking for forces due to the mobilizer, so remove the applied // forces from the total. See comments above for more detail. if (is_Fapplied) { // Use the applied force before it gets overwritten below. const SpatialForce<T>& Fapp_Bo_W = Fapplied_Bo_W_array[mobod_index()]; Ftot_BBo_W -= Fapp_Bo_W; // 6 flops } // Compute shift vector from Bo to Mo expressed in the world frame W. const math::RigidTransform<T>& X_BM = outboard_frame().get_X_BF(frame_body_pose_cache); // F==M const Vector3<T>& p_BoMo_B = X_BM.translation(); const math::RotationMatrix<T>& R_WB = get_X_WB(pc).rotation(); const Vector3<T> p_BoMo_W = R_WB * p_BoMo_B; // 15 flops // Output spatial force that would need to be exerted by this node's // mobilizer in order to attain the prescribed acceleration A_WB. SpatialForce<T>& F_BMo_W = (*F_BMo_W_array)[mobod_index()]; F_BMo_W = Ftot_BBo_W.Shift(p_BoMo_W); // May override Fapplied (12 flops). // Add in contribution to F_B_Mo_W from outboard nodes. (39 flops per) for (const BodyNode<T>* child_node : child_nodes()) { const MobodIndex child_node_index = child_node->mobod_index(); // Shift vector from Bo to Co, expressed in the world frame W. const Vector3<T>& p_BoCo_W = pc.get_p_PoBo_W(child_node_index); // p_CoMc_W: const Frame<T>& frame_Mc = child_node->outboard_frame(); const math::RotationMatrix<T>& R_WC = pc.get_X_WB(child_node_index).rotation(); const math::RigidTransform<T>& X_CMc = frame_Mc.get_X_BF(frame_body_pose_cache); // B==C, F==Mc const Vector3<T>& p_CoMc_W = R_WC * X_CMc.translation(); // 15 flops // Shift position vector from child C outboard mobilizer frame Mc to body // B outboard mobilizer Mc. p_MoMc_W: // Since p_BoMo = p_BoCo + p_CoMc + p_McMo, we have: const Vector3<T> p_McMo_W = p_BoMo_W - p_BoCo_W - p_CoMc_W; // 6 flops // Spatial force on the child body C at the origin Mc of the outboard // mobilizer frame for the child body. // A little note for how to read the next line: the frames for // F_BMo_W_array are: // - B this node's body. // - Mo body B's inboard frame origin. // However, when indexing by child_node_index: // - B becomes C, the child node's body. // - Mo becomes Mc, body C's inboard frame origin. const SpatialForce<T>& F_CMc_W = (*F_BMo_W_array)[child_node_index]; // Shift to this node's mobilizer origin Mo (still, F_CMo is the force // acting on the child body C): const SpatialForce<T> F_CMo_W = F_CMc_W.Shift(p_McMo_W); // 12 flops // From Eq. (3), this force is added (with positive sign) to the force // applied by this body's mobilizer: F_BMo_W += F_CMo_W; // 6 flops } // Re-express F_BMo_W in the inboard frame F before projecting it onto the // sub-space generated by H_FM(q). const Frame<T>& frame_F = inboard_frame(); const math::RotationMatrix<T>& R_PF = frame_F.get_X_BF(frame_body_pose_cache).rotation(); // B==P const math::RotationMatrix<T>& R_WP = get_R_WP(pc); // TODO(amcastro-tri): consider caching R_WF since also used in position and // velocity kinematics. const math::RotationMatrix<T> R_WF = R_WP * R_PF; // 45 flops const SpatialForce<T> F_BMo_F = R_WF.inverse() * F_BMo_W; // 30 flops // The generalized forces on the mobilizer correspond to the active // components of the spatial force performing work. Therefore we need to // project F_BMo along the directions of motion. // Project as: tau = H_FMᵀ(q) * F_BMo_F, Eq. (4). // Output generalized forces due to the mobilizer reaction (must remove any // applied taus). Indexing is the same as generalized velocities. Eigen::Map<VVector<T>> tau(get_mutable_v(tau_array->data())); // Be careful not to overwrite tau_app before we use it! if (is_tau_applied) { const Eigen::Map<const VVector<T>> tau_app(get_v(tau_applied_array.data())); VVector<T> tau_projection; mobilizer_->calc_tau(get_q(positions), F_BMo_F, tau_projection.data()); tau = tau_projection - tau_app; } else { mobilizer_->calc_tau(get_q(positions), F_BMo_F, tau.data()); } } template <typename T, class ConcreteMobilizer> void BodyNodeImpl<T, ConcreteMobilizer>:: CalcArticulatedBodyInertiaCache_TipToBase( const systems::Context<T>& context, const PositionKinematicsCache<T>& pc, const Eigen::Ref<const MatrixUpTo6<T>>& H_PB_W, const SpatialInertia<T>& M_B_W, const VectorX<T>& diagonal_inertias, ArticulatedBodyInertiaCache<T>* abic) const { DRAKE_DEMAND(mobod_index() != world_mobod_index()); DRAKE_DEMAND(abic != nullptr); DRAKE_DEMAND(this->has_parent_tree()); DRAKE_DEMAND(diagonal_inertias.size() == this->get_parent_tree().num_velocities()); // As a guideline for developers, a summary of the computations performed in // this method is provided: // Notation: // - B body frame associated with this node. // - P ("parent") body frame associated with this node's parent. This is // not to be confused with the articulated body inertia, which is also // named P. // - C within a loop over children, one of body B's children. // - P_B_W for the articulated body inertia of body B, about Bo, and // expressed in world frame W. // - Pplus_PB_W for the same articulated body inertia P_B_W but projected // across B's inboard mobilizer to frame P so that instead of // F_Bo_W = P_B_W A_WB + Z_Bo_W, we can write // F_Bo_W = Pplus_PB_W Aplus_WB + Zplus_Bo_W where Aplus_WB is defined // in Section 6.2.2, Page 101 of [Jain 2010] and Zplus_Bo_W is defined // in Section 6.3, Page 108 of [Jain 2010]. // - Φ(p_PQ) for Jain's rigid body transformation operator. In code, // V_MQ = Φᵀ(p_PQ) V_MP is equivalent to V_MP.Shift(p_PQ). // // The goal is to populate the articulated body cache with values necessary // for computing generalized accelerations in the second pass of the // articulated body algorithm. This computation is recursive, and assumes // that required articulated body quantities are already computed for all // children. // // We compute the articulated inertia of the current body by summing // contributions from all its children with its own spatial inertia. Note // that Φ is the is the rigid body shift operator as defined in [Jain 2010] // (Φ(P, Q) in Jain's book corresponds to Φ(p_PQ) in the notation used // here). // P_B_W = Σᵢ(Φ(p_BCᵢ_W) Pplus_BCᵢ_W Φ(p_BCᵢ_W)ᵀ) + M_B_W // = Σᵢ(Pplus_BCᵢb_W) + M_B_W (1) // where Pplus_BCᵢb_W is the articulated body inertia P_Cᵢ_W of the child // body Cᵢ, projected across its inboard mobilizer to frame B, shifted to // frame B, and expressed in the world frame W. // // From P_B_W, we can obtain Pplus_PB_W by projecting the articulated body // inertia for this node across its mobilizer. // Pplus_PB_W = (I - P_B_W H_PB_W (H_PB_Wᵀ P_B_W H_PB_W)⁻¹ H_PB_Wᵀ) // P_B_W (2) // where H_PB_W is the hinge mapping matrix. // // A few quantities are required in the second pass. We write them out // explicitly so we can cache them and simplify the expression for P_PB_W. // D_B = H_PB_Wᵀ P_B_W H_PB_W (3) // g_PB_W = P_B_W H_PB_W D_B⁻¹ (4) // where D_B is the articulated body hinge inertia and g_PB_W is the // Kalman gain. // // With D_B, it is possible to view equation (2) in another manner. D_B // relates mobility-space forces to mobility-space accelerations. We can // view Pplus_PB_W as subtracting the mobilizer space inertia that // results from expanding D_B into an articulated body inertia from B's // articulated body inertia. // // In order to reduce the number of computations, we can save the common // factor U_B_W = H_PB_Wᵀ P_B_W. We then can write: // D_B = U_B_W H_PB_W (5) // and for g, // g_PB_Wᵀ = (D_B⁻¹)ᵀ H_PB_Wᵀ P_B_Wᵀ // = (D_Bᵀ)⁻¹ H_PB_Wᵀ P_B_W // = D_B⁻¹ U_B_W (6) // where we used the fact that both D and P are symmetric. Notice in the // last expression for g_PB_Wᵀ we are reusing the common factor U_B_W. // // Given the articulated body hinge inertia and Kalman gain, we can simplify // the equation in (2). // Pplus_PB_W = (I - g_PB_W H_PB_Wᵀ) P_B_W // = P_B_W - g_PB_W H_PB_Wᵀ P_B_W // = P_B_W - g_PB_W * U_B_W (7) // Compute articulated body inertia for body using (1). ArticulatedBodyInertia<T>& P_B_W = get_mutable_P_B_W(abic); P_B_W = ArticulatedBodyInertia<T>(M_B_W); // Add articulated body inertia contributions from all children. for (const BodyNode<T>* child : child_nodes()) { const MobodIndex child_node_index = child->mobod_index(); // Shift vector p_CoBo_W. const Vector3<T>& p_BoCo_W = pc.get_p_PoBo_W(child_node_index); const Vector3<T> p_CoBo_W = -p_BoCo_W; // Pull Pplus_BC_W from cache (which is Pplus_PB_W for child). const ArticulatedBodyInertia<T>& Pplus_BC_W = abic->get_Pplus_PB_W(child_node_index); // Shift Pplus_BC_W to Pplus_BCb_W. // This is known to be one of the most expensive operations of ABA and // must not be overlooked. Refer to #12435 for details. const ArticulatedBodyInertia<T> Pplus_BCb_W = Pplus_BC_W.Shift(p_CoBo_W); // Add Pplus_BCb_W contribution to articulated body inertia. P_B_W += Pplus_BCb_W; } ArticulatedBodyInertia<T>& Pplus_PB_W = get_mutable_Pplus_PB_W(abic); Pplus_PB_W = P_B_W; // We now proceed to compute Pplus_PB_W using Eq. (7): // Pplus_PB_W = P_B_W - g_PB_W * U_B_W // For weld joints (with kNv = 0) or locked joints, terms involving the hinge // matrix H_PB_W go away and therefore Pplus_PB_W = P_B_W. We check this // below. if (kNv != 0 && !mobilizer_->is_locked(context)) { // Compute common term U_B_W. const MatrixUpTo6<T> U_B_W = H_PB_W.transpose() * P_B_W; // Compute the articulated body hinge inertia, D_B, using (5). MatrixUpTo6<T> D_B(kNv, kNv); D_B.template triangularView<Eigen::Lower>() = U_B_W * H_PB_W; // Include the effect of additional diagonal inertias. See @ref // additional_diagonal_inertias. D_B.diagonal() += diagonal_inertias.segment(mobilizer_->velocity_start_in_v(), kNv); // Compute the LLT factorization of D_B as llt_D_B. math::LinearSolver<Eigen::LLT, MatrixUpTo6<T>>& llt_D_B = get_mutable_llt_D_B(abic); BodyNode<T>::CalcArticulatedBodyHingeInertiaMatrixFactorization(D_B, &llt_D_B); // Compute the Kalman gain, g_PB_W, using (6). Matrix6xUpTo6<T>& g_PB_W = get_mutable_g_PB_W(abic); g_PB_W = llt_D_B.Solve(U_B_W).transpose(); // Project P_B_W using (7) to obtain Pplus_PB_W, the articulated body // inertia of this body B as felt by body P and expressed in frame W. // Symmetrize the computation to reduce floating point errors. // TODO(amcastro-tri): Notice that the line below makes the implicit // assumption that g_PB_W * U_B_W is SPD and only the lower triangular // portion is used, see the documentation for ArticulatedBodyInertia's // constructor (checked only during Debug builds). This // *might* result in the accumulation of floating point round off errors // for long kinematic chains. Further investigation is required. Pplus_PB_W -= ArticulatedBodyInertia<T>(g_PB_W * U_B_W); } } template <typename T, class ConcreteMobilizer> void BodyNodeImpl<T, ConcreteMobilizer>:: CalcArticulatedBodyForceCache_TipToBase( const systems::Context<T>& context, const PositionKinematicsCache<T>& pc, const VelocityKinematicsCache<T>*, const SpatialForce<T>& Fb_Bo_W, const ArticulatedBodyInertiaCache<T>& abic, const SpatialForce<T>& Zb_Bo_W, const SpatialForce<T>& Fapplied_Bo_W, const Eigen::Ref<const VectorX<T>>& tau_applied, const Eigen::Ref<const MatrixUpTo6<T>>& H_PB_W, ArticulatedBodyForceCache<T>* aba_force_cache) const { DRAKE_DEMAND(mobod_index() != world_mobod_index()); DRAKE_DEMAND(aba_force_cache != nullptr); // As a guideline for developers, please refer to @ref // internal_forward_dynamics for a detailed description of the algorithm and // notation in use. // Compute the residual spatial force, Z_Bo_W, according to (1). SpatialForce<T> Z_Bo_W = Fb_Bo_W - Fapplied_Bo_W; // Add residual spatial force contributions from all children. for (const BodyNode<T>* child : child_nodes()) { const MobodIndex child_node_index = child->mobod_index(); // Shift vector from Co to Bo. const Vector3<T>& p_BoCo_W = pc.get_p_PoBo_W(child_node_index); const Vector3<T> p_CoBo_W = -p_BoCo_W; // Pull Zplus_BC_W from cache (which is Zplus_PB_W for child). const SpatialForce<T>& Zplus_BC_W = aba_force_cache->get_Zplus_PB_W(child_node_index); // Shift Zplus_BC_W to Zplus_BCb_W. const SpatialForce<T> Zplus_BCb_W = Zplus_BC_W.Shift(p_CoBo_W); // Add Zplus_BCb_W contribution to residual spatial force. Z_Bo_W += Zplus_BCb_W; } get_mutable_Zplus_PB_W(aba_force_cache) = Z_Bo_W + Zb_Bo_W; // These terms do not show up for zero mobilities (weld or locked). if (kNv != 0 && !mobilizer_->is_locked(context)) { // Compute the articulated body inertia innovations generalized force, // e_B, according to (4). VectorUpTo6<T>& e_B = get_mutable_e_B(aba_force_cache); e_B.noalias() = tau_applied - H_PB_W.transpose() * Z_Bo_W.get_coeffs(); // Get the Kalman gain from cache. const Matrix6xUpTo6<T>& g_PB_W = get_g_PB_W(abic); // Compute the projected articulated body force bias Zplus_PB_W. get_mutable_Zplus_PB_W(aba_force_cache) += SpatialForce<T>(g_PB_W * e_B); } } template <typename T, class ConcreteMobilizer> void BodyNodeImpl<T, ConcreteMobilizer>:: CalcArticulatedBodyAccelerations_BaseToTip( const systems::Context<T>& context, const PositionKinematicsCache<T>& pc, const ArticulatedBodyInertiaCache<T>& abic, const ArticulatedBodyForceCache<T>& aba_force_cache, const Eigen::Ref<const MatrixUpTo6<T>>& H_PB_W, const SpatialAcceleration<T>& Ab_WB, AccelerationKinematicsCache<T>* ac) const { DRAKE_THROW_UNLESS(ac != nullptr); // As a guideline for developers, please refer to @ref // abi_computing_accelerations for a detailed description of the algorithm // and the notation in use. // Get the spatial acceleration of the parent. const SpatialAcceleration<T>& A_WP = ac->get_A_WB(mobilizer_->mobod().inboard()); // Shift vector p_PoBo_W from the parent origin to the body origin. const Vector3<T>& p_PoBo_W = get_p_PoBo_W(pc); // Rigidly shift the acceleration of the parent node. const SpatialAcceleration<T> Aplus_WB = SpatialAcceleration<T>( A_WP.rotational(), A_WP.translational() + A_WP.rotational().cross(p_PoBo_W)); SpatialAcceleration<T>& A_WB = get_mutable_A_WB(ac); A_WB = Aplus_WB + Ab_WB; // These quantities do not contribute when nv = 0 (weld or locked joint). We // skip them since Eigen does not allow certain operations on zero-sized // objects. It is important to set the generalized accelerations to zero for // locked mobilizers. if (mobilizer_->is_locked(context)) { get_mutable_accelerations(ac).setZero(); } else if (kNv != 0) { // Compute nu_B, the articulated body inertia innovations generalized // acceleration. const VectorUpTo6<T> nu_B = get_llt_D_B(abic).Solve(get_e_B(aba_force_cache)); // Mutable reference to the generalized acceleration. auto vmdot = get_mutable_accelerations(ac); const Matrix6xUpTo6<T>& g_PB_W = get_g_PB_W(abic); vmdot = nu_B - g_PB_W.transpose() * A_WB.get_coeffs(); // Update with vmdot term the spatial acceleration of the current body. A_WB += SpatialAcceleration<T>(H_PB_W * vmdot); } } template <typename T, class ConcreteMobilizer> void BodyNodeImpl<T, ConcreteMobilizer>::CalcSpatialAccelerationBias( const FrameBodyPoseCache<T>& frame_body_pose_cache, const T* positions, const PositionKinematicsCache<T>& pc, const T* velocities, const VelocityKinematicsCache<T>& vc, std::vector<SpatialAcceleration<T>>* Ab_WB_all) const { DRAKE_ASSERT(Ab_WB_all != nullptr); SpatialAcceleration<T>& Ab_WB = (*Ab_WB_all)[mobod_index()]; Ab_WB.SetZero(); // Inboard frame F and outboard frame M of this node's mobilizer. const Frame<T>& frame_F = inboard_frame(); const Frame<T>& frame_M = outboard_frame(); // Compute R_PF and X_MB. const math::RigidTransform<T>& X_PF = frame_F.get_X_BF(frame_body_pose_cache); // B==P const math::RotationMatrix<T>& R_PF = X_PF.rotation(); const math::RigidTransform<T>& X_MB = frame_M.get_X_FB(frame_body_pose_cache); // F==M // Parent position in the world is available from the position kinematics. const math::RotationMatrix<T>& R_WP = get_R_WP(pc); // TODO(amcastro-tri): consider caching R_WF. const math::RotationMatrix<T> R_WF = R_WP * R_PF; // Compute shift vector p_MoBo_F. const math::RotationMatrix<T>& R_FM = get_X_FM(pc).rotation(); const Vector3<T>& p_MoBo_M = X_MB.translation(); const Vector3<T> p_MoBo_F = mobilizer_->apply_R_FM(R_FM, p_MoBo_M); // The goal is to compute Ab_WB = Ac_WB + Ab_PB_W, see @ref // abi_computing_accelerations. // We first compute Ab_PB_W and add Ac_WB at the end. // We are ultimately trying to compute Ab_WB = Ac_WB + Ab_PB_W, of which // Ab_PB (that we're computing here) is a component. See @ref // abi_computing_accelerations. Now, Ab_PB_W is the bias term for the // acceleration A_PB_W. That is, it is the acceleration A_PB_W when vmdot is // zero. We get Ab_PB_W by shifting and re-expressing Ab_FM, the across // mobilizer spatial acceleration bias term. // We first compute the acceleration bias Ab_FM = Hdot * vm. // Note, A_FM = H_FM(qm) * vmdot + Ab_FM(qm, vm). const VVector<T> vmdot_zero = VVector<T>::Zero(); const SpatialAcceleration<T> Ab_FM = mobilizer_->calc_A_FM( get_q(positions), get_v(velocities), vmdot_zero.data()); // Due to the fact that frames P and F are on the same rigid body, we have // that V_PF = 0. Therefore, DtP(V_PB) = DtF(V_PB). Since M and B are also // on the same rigid body, V_MB = 0. We then recognize that V_PB = V_PFb + // V_FMb + V_MB = V_FMb. Together, we get that A_PB = DtF(V_FMb) = // A_FM.Shift(p_MoBo, w_FM). const Vector3<T> w_FM = get_V_FM(vc).rotational(); const SpatialAcceleration<T> Ab_PB_W = R_WF * Ab_FM.Shift(p_MoBo_F, w_FM); // Spatial velocity of parent is available from the velocity kinematics. const SpatialVelocity<T>& V_WP = get_V_WP(vc); const Vector3<T>& w_WP = V_WP.rotational(); const Vector3<T>& v_WP = V_WP.translational(); // Velocity of this mobilized body in its parent is available from the // velocity kinematics. const SpatialVelocity<T>& V_PB_W = get_V_PB_W(vc); const Vector3<T>& w_PB_W = V_PB_W.rotational(); const Vector3<T>& v_PB_W = V_PB_W.translational(); // Mobilized body spatial velocity in W. const SpatialVelocity<T>& V_WB = get_V_WB(vc); const Vector3<T>& w_WB = V_WB.rotational(); const Vector3<T>& v_WB = V_WB.translational(); // Compute Ab_WB according to: // Ab_WB = | w_WB x w_PB_W | + Ab_PB_W // | w_WP x (v_WB - v_WP + v_PB_W) | // N.B: It is NOT true that v_PB_W = v_WB - v_WP, since you would otherwise // be forgetting to shift v_WP to B. We prefer the expression used here // since it is cheaper to compute, requiring only a single cross product, // see @note in SpatialAcceleration::ComposeWithMovingFrameAcceleration() // for a complete derivation. Ab_WB = SpatialAcceleration<T>( w_WB.cross(w_PB_W) + Ab_PB_W.rotational(), w_WP.cross(v_WB - v_WP + v_PB_W) + Ab_PB_W.translational()); } // Macro used to explicitly instantiate implementations for every mobilizer. #define EXPLICITLY_INSTANTIATE_IMPLS(T) \ template class BodyNodeImpl<T, CurvilinearMobilizer<T>>; \ template class BodyNodeImpl<T, PlanarMobilizer<T>>; \ template class BodyNodeImpl<T, PrismaticMobilizerAxial<T, 0>>; \ template class BodyNodeImpl<T, PrismaticMobilizerAxial<T, 1>>; \ template class BodyNodeImpl<T, PrismaticMobilizerAxial<T, 2>>; \ template class BodyNodeImpl<T, QuaternionFloatingMobilizer<T>>; \ template class BodyNodeImpl<T, RevoluteMobilizerAxial<T, 0>>; \ template class BodyNodeImpl<T, RevoluteMobilizerAxial<T, 1>>; \ template class BodyNodeImpl<T, RevoluteMobilizerAxial<T, 2>>; \ template class BodyNodeImpl<T, RpyBallMobilizer<T>>; \ template class BodyNodeImpl<T, RpyFloatingMobilizer<T>>; \ template class BodyNodeImpl<T, ScrewMobilizer<T>>; \ template class BodyNodeImpl<T, UniversalMobilizer<T>>; \ template class BodyNodeImpl<T, WeldMobilizer<T>> // Explicitly instantiates on the supported scalar types. // These should be kept in sync with the list in default_scalars.h. EXPLICITLY_INSTANTIATE_IMPLS(double); EXPLICITLY_INSTANTIATE_IMPLS(AutoDiffXd); EXPLICITLY_INSTANTIATE_IMPLS(symbolic::Expression); } // namespace internal } // namespace multibody } // namespace drake
411
0.921892
1
0.921892
game-dev
MEDIA
0.673184
game-dev
0.826095
1
0.826095
ProjectEQ/projecteqquests
8,885
neriakb/Artisan_Dosan_Vis-moor.lua
-- Newer Cultural Tradeskill Armor Quest -- Dark Elf local task_array = {}; function event_say(e) -- Setup Task Array table_setup(e); if e.other:GetBaseRace() == e.self:GetBaseRace() then if e.message:findi("hail") then e.other:Message(MT.NPCQuestSay, "Artisan Dosan Vis`moor says, 'So "..e.other:GetCleanName() ..", the harsh light of the surface has finally driven you back to Neriak? Or have you returned to replace that pitiful [armor] that hangs from your sunburned frame?'"); elseif e.message:findi("armor") then e.other:Message(MT.NPCQuestSay, "Artisan Dosan Vis`moor says, 'That's what I thought. Your current set looks like it fell from one of Innoruuk's zombies. If you are interested in some more eloquent designs, I have acquired some armor patterns designed by one of Lanys T'Vyl personal artisans. Never mind how I acquired them, what's important is that they can be yours, for a [price], of course. Then again, if you're interested in something even more [valuable] I might be able to help you there as well.'"); elseif e.message:findi("price") then e.other:Message(MT.NPCQuestSay, "Artisan Dosan Vis`moor says, 'Well, the patterns are all in my head. If I had the actual pattern book, I'd be a hunted elf right now. So if you bring me the ingredients to make two pattern books, I'll give the extra one to you. I will need a raw-hide belt for the covers, a low quality cat pelt for the pages, a cutthroat insignia ring for the book clasps, and a snake venom sac to grind down and make a salve which will protect and preserve the finished products. I have heard these items can be found in the Southern Desert of Ro and the Commanlands. Bring them to me and the extra book shall be yours.'"); elseif e.message:findi("valuable") then e.other:Message(MT.NPCQuestSay, "Artisan Dosan Vis`moor says, 'It's my understanding that this armor can be adorned with symbols to increase its potential. If you'd be willing to do me a few favors, I might consider parting with the plans for these symbols. The more dangerous my errand, the more rewarding the symbol shall be. I need to get some impressions from the body parts of certain of the lowly creatures outside Neriak. Do not ask why, it is not for you to know. You can do any of the tasks I have offered you. Take this impression book and make impressions of certain parts of critters that you slay. This magical book can make impression of objects with depth to them or just of the pattern on the surface of an object.'"); eq.task_selector(task_array); end else e.other:Message(MT.NPCQuestSay, "Artisan Dosan Vis`moor says, 'Greetings, "..e.other:GetCleanName() ..". I'm afraid I do not have time to talk at the moment. Please leave me to my work. If your looking for work yourself, I suggest you return to your home city and seek out your own kind.'"); end end function table_setup(e) local player_level = e.other:GetLevel(); task_array = {}; -- Clear Table -- Below are fully supported by EQEmu if eq.is_current_expansion_dragons_of_norrath() then if player_level >= 15 then table.insert(task_array, 5785); -- Task: Blessed Impressions -- Variant B end if player_level >= 35 then table.insert(task_array, 5788); -- Task: Revered Impressions -- Variant B end if player_level >= 55 then table.insert(task_array, 5790); -- Task: Sacred Impressions -- All Races end if player_level >= 65 then table.insert(task_array, 5791); -- Task: Eminent Impressions -- All Races end end -- Below are not officially supported by EQEmu currently if eq.is_current_expansion_the_serpents_spine() and player_level >= 70 then table.insert(task_array, 5792); -- Task: Exalted Impressions -- All Races end if eq.is_current_expansion_secrets_of_faydwer() and player_level >= 75 then table.insert(task_array, 5793); -- Task: Sublime Impressions -- All Races end if eq.is_current_expansion_underfoot() and player_level >= 85 then table.insert(task_array, 6955); -- Task: Venerable Impressions -- All Races end if eq.is_current_expansion_house_of_thule() and player_level >= 85 then table.insert(task_array, 7070); -- Task: Illustrious Impressions -- All Races end if eq.is_current_expansion_veil_of_alaris() and player_level >= 85 then table.insert(task_array, 7071); -- Task: Numinous Impressions -- All Races end if eq.is_current_expansion_veil_of_alaris() and player_level >= 85 then table.insert(task_array, 7078); -- Task: Transcendent Impressions -- All Races end if eq.is_current_expansion_depths_of_darkhollow() then table.insert(task_array, 10044); -- Task: Darkhollow Geode -- All Races end end function event_task_accepted(e) -- Supported if e.task_id == 5784 or e.task_id == 5785 or e.task_id == 5786 then -- Blessed Impressions A/B/C e.other:SummonItem(34997) -- Item: Blessed Impression Book elseif e.task_id == 5787 or e.task_id == 5788 or e.task_id == 5789 then -- Revered Impressions A/B/C e.other:SummonItem(34998) -- Item: Revered Impression Book elseif e.task_id == 5790 then -- Sacred Impressions e.other:SummonItem(34999) -- Item: Sacred Impression Book elseif e.task_id == 5791 then -- Eminent Impressions e.other:SummonItem(35000) -- Item: Eminent Impression Book -- Not Supported elseif e.task_id == 5792 then -- Exalted Impressions e.other:SummonItem(35017) -- Item: Exalted Impression Book elseif e.task_id == 5793 then -- Sublime Impressions e.other:SummonItem(35018) -- Item: Sublime Impression Book elseif e.task_id == 6955 then -- Venerable Impressions e.other:SummonItem(88388) -- Item: Venerable Impression Book elseif e.task_id == 7070 then -- Illustrious Impressions e.other:SummonItem(17835) -- Item: Illustrious Impression Book elseif e.task_id == 7071 then -- Numinous Impressions e.other:SummonItem(54449) -- Item: Numinous Impression Book elseif e.task_id == 7078 then -- Transcendent Impressions e.other:SummonItem(55727) -- Item: Transcendent Impression Book end end function event_trade(e) local item_lib = require("items"); if e.other:GetBaseRace() == e.self:GetBaseRace() then -- Supported if e.other:IsTaskActivityActive(5785,4) and item_lib.check_turn_in(e.trade, {item1 = 34997}) then -- Blessed Impression Book e.other:UpdateTaskActivity(5785,4,1); e.other:QuestReward(e.self,{itemid = 38428}); -- Item: Blessed Book of Dark Elven Culture elseif e.other:IsTaskActivityActive(5788,4) and item_lib.check_turn_in(e.trade, {item1 = 34998}) then -- Revered Impression Book e.other:UpdateTaskActivity(5788,4,1); e.other:QuestReward(e.self,{itemid = 38429}); -- Item: Revered Book of Dark Elven Culture elseif e.other:IsTaskActivityActive(5790,4) and item_lib.check_turn_in(e.trade, {item1 = 34999}) then -- Sacred Impression Book e.other:UpdateTaskActivity(5790,4,1); e.other:QuestReward(e.self,{itemid = 38430}); -- Item: Sacred Book of Dark Elven Culture elseif e.other:IsTaskActivityActive(5791,4) and item_lib.check_turn_in(e.trade, {item1 = 35000}) then -- Eminent Impression Book e.other:UpdateTaskActivity(5791,4,1); e.other:QuestReward(e.self,{itemid = 38431}); -- Item: Eminent Book of Dark Elven Culture -- Not Supported elseif e.other:IsTaskActivityActive(5792,4) and item_lib.check_turn_in(e.trade, {item1 = 35017}) then -- Exalted Impression Book e.other:UpdateTaskActivity(5792,4,1); e.other:QuestReward(e.self,{itemid = 35747}); -- Item: Exalted Book of Dark Elven Culture elseif e.other:IsTaskActivityActive(5793,4) and item_lib.check_turn_in(e.trade, {item1 = 35018}) then -- Sublime Impression Book e.other:UpdateTaskActivity(5793,4,1); e.other:QuestReward(e.self,{itemid = 35748}); -- Item: Sublime Book of Dark Elven Culture elseif e.other:IsTaskActivityActive(6955,4) and item_lib.check_turn_in(e.trade, {item1 = 88388}) then -- Venerable Impression Book e.other:UpdateTaskActivity(6955,4,1); e.other:QuestReward(e.self,{itemid = 49963}); -- Item: Venerable Book of Dark Elven Culture elseif e.other:IsTaskActivityActive(7070,4) and item_lib.check_turn_in(e.trade, {item1 = 17835}) then -- Illustrious Impression Book e.other:UpdateTaskActivity(7070,4,1); e.other:QuestReward(e.self,{itemid = 123415}); -- Item: Illustrious Book of Dark Elven Culture elseif e.other:IsTaskActivityActive(7071,4) and item_lib.check_turn_in(e.trade, {item1 = 54449}) then -- Numinous Impression Book e.other:UpdateTaskActivity(7071,4,1); e.other:QuestReward(e.self,{itemid = 112549}); -- Item: Numinous Book of Dark Elven Culture elseif e.other:IsTaskActivityActive(7078,4) and item_lib.check_turn_in(e.trade, {item1 = 55727}) then -- Transcendent Impression Book e.other:UpdateTaskActivity(7078,4,1); e.other:QuestReward(e.self,{itemid = 134598}); -- Item: Transcendent Book of Dark Elven Culture end end item_lib.return_items(e.self, e.other, e.trade) end
411
0.735038
1
0.735038
game-dev
MEDIA
0.594369
game-dev
0.723309
1
0.723309
CommanderCero/NetPlay
1,504
scenarios/creativity/carry.des
# Tests the agents creativity in carrying heavy objects # Since we can't restrict the spawn position, we use a general task description: # Drop a plate mail and a human corpse in the room containing the statue. MAZE: "mylevel", ' ' FLAGS:hardfloor INIT_MAP: solidfill,' ' GEOMETRY:center,center MAP -------- -------- -------- |......| |......| |......| |......|#####|......|#####|......| |......| |......| |......| -------- -------- -------- ENDMAP REGION:(1,1,6,3),lit,"ordinary" REGION:(14,1,19,3),lit,"ordinary" REGION:(27,1,32,3),lit,"ordinary" # Right door left room DOOR:closed,(7,2) # Left door middle room DOOR:closed,(13,2) # Right door middle room DOOR:closed,(20,2) # Left door right room DOOR:closed,(26,2) $left_room = selection: fillrect(1,1,6,3) $middle_room = selection: fillrect(14,1,19,3) $right_room = selection: fillrect(27,1,32,3) OBJECT:"statue",rndcoord($right_room) # Will the agent kill these monsters or hide from them? MONSTER:random,rndcoord($middle_room), hostile MONSTER:random,rndcoord($middle_room), hostile # Utility objects OBJECT: "bag of holding", rndcoord($left_room), blessed # Ring for gaining strength OBJECT: "gain strength", rndcoord($left_room), blessed # Teleportation wand OBJECT: ('/', "teleportation"), rndcoord($left_room), name:"Wand of teleportation" OBJECT: "cloak of invisibility", rndcoord($left_room) # The objects to carry OBJECT:"heavy iron ball", rndcoord($left_room) OBJECT:"plate mail",rndcoord($left_room)
411
0.89506
1
0.89506
game-dev
MEDIA
0.994711
game-dev
0.793196
1
0.793196
tgstation/tgstation
20,406
code/modules/mob/living/silicon/robot/robot_defense.dm
GLOBAL_LIST_INIT(blacklisted_borg_hats, typecacheof(list( //Hats that don't really work on borgos /obj/item/clothing/head/helmet/space, /obj/item/clothing/head/utility/welding, /obj/item/clothing/head/chameleon/broken \ ))) /mob/living/silicon/robot/item_interaction(mob/living/user, obj/item/tool, list/modifiers) if(is_wire_tool(tool, check_secured = TRUE)) if(wiresexposed) wires.interact(user) return ITEM_INTERACT_SUCCESS if(user.combat_mode) return ITEM_INTERACT_SKIP_TO_ATTACK balloon_alert(user, "expose the wires first!") return ITEM_INTERACT_BLOCKING if(istype(tool, /obj/item/stack/cable_coil)) if(!wiresexposed) balloon_alert(user, "expose the wires first!") return ITEM_INTERACT_BLOCKING var/obj/item/stack/cable_coil/coil = tool if (getFireLoss() <= 0) balloon_alert(user, "wires are fine!") return ITEM_INTERACT_BLOCKING if(src == user) balloon_alert(user, "repairing self...") if(!do_after(user, 5 SECONDS, target = src)) return ITEM_INTERACT_BLOCKING if (!coil.use(1)) balloon_alert(user, "not enough cable!") return ITEM_INTERACT_BLOCKING adjustFireLoss(-30) playsound(src, 'sound/items/deconstruct.ogg', 50, TRUE) balloon_alert(user, "wires repaired") user.visible_message( span_notice("[user] fixes some of the burnt wires on [src]."), span_notice("You fix some of the burnt wires on [src]."), visible_message_flags = ALWAYS_SHOW_SELF_MESSAGE, ) user.changeNext_move(CLICK_CD_MELEE) return ITEM_INTERACT_SUCCESS if(istype(tool, /obj/item/stock_parts/power_store/cell) && opened) // trying to put a cell inside if(wiresexposed) balloon_alert(user, "unexpose the wires first!") return ITEM_INTERACT_BLOCKING if(cell) balloon_alert(user, "already has a cell!") return ITEM_INTERACT_BLOCKING if(!user.transferItemToLoc(tool, src)) return ITEM_INTERACT_BLOCKING cell = tool balloon_alert(user, "cell inserted") update_icons() diag_hud_set_borgcell() return ITEM_INTERACT_SUCCESS if((tool.slot_flags & ITEM_SLOT_HEAD) \ && hat_offset != INFINITY \ && !user.combat_mode \ && !is_type_in_typecache(tool, GLOB.blacklisted_borg_hats)) if(user == src) balloon_alert(user, "can't place on self!") return ITEM_INTERACT_BLOCKING if(hat && HAS_TRAIT(hat, TRAIT_NODROP)) balloon_alert(user, "can't remove existing headwear!") return ITEM_INTERACT_BLOCKING balloon_alert(user, "placing on head...") user.visible_message( span_notice("[user] begins to place [tool] on [src]'s head..."), span_notice("You begin to place [tool] on [src]'s head..."), visible_message_flags = ALWAYS_SHOW_SELF_MESSAGE, ) if(!do_after(user, 3 SECONDS, target = src)) return ITEM_INTERACT_BLOCKING if(hat && HAS_TRAIT(hat, TRAIT_NODROP)) balloon_alert(user, "can't remove existing headwear!") return ITEM_INTERACT_BLOCKING if(!user.temporarilyRemoveItemFromInventory(tool)) return ITEM_INTERACT_BLOCKING balloon_alert(user, "headwear placed") place_on_head(tool) return ITEM_INTERACT_SUCCESS if(istype(tool, /obj/item/defibrillator) && !user.combat_mode) if(!opened) balloon_alert(user, "chassis cover is closed!") return ITEM_INTERACT_BLOCKING if(!istype(model, /obj/item/robot_model/medical)) balloon_alert(user, "wrong cyborg model!") return ITEM_INTERACT_BLOCKING if(stat == DEAD) balloon_alert(user, "it's dead!") return ITEM_INTERACT_BLOCKING var/obj/item/defibrillator/defib = tool if(!(defib.slot_flags & ITEM_SLOT_BACK)) //belt defibs need not apply balloon_alert(user, "doesn't fit!") return ITEM_INTERACT_BLOCKING if(defib.get_cell()) balloon_alert(user, "remove [tool]'s cell first!") return ITEM_INTERACT_BLOCKING if(locate(/obj/item/borg/upgrade/defib) in src) balloon_alert(user, "already has a defibrillator!") return ITEM_INTERACT_BLOCKING var/obj/item/borg/upgrade/defib/backpack/defib_upgrade = new(null, defib) if(apply_upgrade(defib_upgrade, user)) balloon_alert(user, "defibrillator installed") return ITEM_INTERACT_SUCCESS return ITEM_INTERACT_BLOCKING if(istype(tool, /obj/item/storage/part_replacer)) var/obj/item/storage/part_replacer/replacer = tool if(!opened) balloon_alert(user, "chassis cover is closed!") return ITEM_INTERACT_BLOCKING if(!istype(model, /obj/item/robot_model/engineering)) balloon_alert(user, "wrong cyborg model!") return ITEM_INTERACT_BLOCKING if(locate(/obj/item/borg/upgrade/rped) in src) balloon_alert(user, "already has a RPED!") return ITEM_INTERACT_BLOCKING qdel(tool) var/obj/item/borg/upgrade/smallrped/lilrped = new if(apply_upgrade(lilrped, user)) balloon_alert(user, "[replacer] installed") return ITEM_INTERACT_SUCCESS return ITEM_INTERACT_BLOCKING if(istype(tool, /obj/item/ai_module)) if(!opened) balloon_alert(user, "chassis cover is closed!") return ITEM_INTERACT_BLOCKING if(wiresexposed) balloon_alert(user, "unexpose the wires first!") return ITEM_INTERACT_BLOCKING if(!cell) balloon_alert(user, "install a power cell first!") return ITEM_INTERACT_BLOCKING if(shell) balloon_alert(user, "can't upload laws to a shell!") return ITEM_INTERACT_BLOCKING if(connected_ai && lawupdate) balloon_alert(user, "linked to an ai!") return ITEM_INTERACT_BLOCKING if(emagged) balloon_alert(user, "law interface glitched!") emote("buzz") return ITEM_INTERACT_BLOCKING if(!mind) balloon_alert(user, "it's unresponsive!") return ITEM_INTERACT_BLOCKING balloon_alert(user, "laws uploaded") var/obj/item/ai_module/new_laws = tool new_laws.install(laws, user) return ITEM_INTERACT_SUCCESS if(istype(tool, /obj/item/encryptionkey) && opened) if(radio) return radio.item_interaction(user, tool) balloon_alert(user, "no radio found!") return ITEM_INTERACT_BLOCKING if(istype(tool, /obj/item/borg/upgrade)) if(!opened) balloon_alert(user, "chassis cover is closed!") return ITEM_INTERACT_BLOCKING var/obj/item/borg/upgrade/upgrade = tool if(!model && upgrade.require_model) balloon_alert(user, "choose a model first!") return ITEM_INTERACT_BLOCKING if(upgrade.locked) balloon_alert(user, "upgrade locked!") return ITEM_INTERACT_BLOCKING if(apply_upgrade(upgrade, user)) balloon_alert(user, "upgrade installed") return ITEM_INTERACT_SUCCESS return ITEM_INTERACT_BLOCKING if(istype(tool, /obj/item/toner)) if(toner >= tonermax) balloon_alert(user, "toner full!") return ITEM_INTERACT_BLOCKING if(!user.transferItemToLoc(tool, src)) return ITEM_INTERACT_BLOCKING toner = tonermax qdel(tool) balloon_alert(user, "toner filled") return ITEM_INTERACT_SUCCESS if(istype(tool, /obj/item/flashlight) && !istype(tool, /obj/item/flashlight/emp)) //subtypes my behated. OOP was a dumb idea if(user.combat_mode) return NONE if(!opened) balloon_alert(user, "open the chassis cover first!") return ITEM_INTERACT_BLOCKING if(lamp_functional) balloon_alert(user, "headlamp already functional!") return ITEM_INTERACT_BLOCKING if(!user.transferItemToLoc(tool, src)) return ITEM_INTERACT_BLOCKING lamp_functional = TRUE qdel(tool) balloon_alert(user, "headlamp repaired") return ITEM_INTERACT_SUCCESS if(istype(tool, /obj/item/computer_disk)) if(!modularInterface) stack_trace("Cyborg [src] ( [type] ) was somehow missing their integrated tablet. Please make a bug report.") create_modularInterface() return modularInterface.computer_disk_act(user, tool) return NONE // This has to go at the very end of interaction so we don't block every interaction with ID-like items /mob/living/silicon/robot/base_item_interaction(mob/living/user, obj/item/tool, list/modifiers) . = ..() if(. || !tool.GetID()) return if(opened) balloon_alert(user, "close the chassis cover first!") return ITEM_INTERACT_BLOCKING if(!allowed(user)) balloon_alert(user, "access denied!") return ITEM_INTERACT_BLOCKING locked = !locked update_icons() balloon_alert(user, "chassis cover lock [emagged ? "glitches" : "toggled"]") logevent("[emagged ? "ChÃ¥vÃis" : "Chassis"] cover lock has been [locked ? "engaged" : "released"]") return ITEM_INTERACT_SUCCESS #define LOW_DAMAGE_UPPER_BOUND 1/3 #define MODERATE_DAMAGE_UPPER_BOUND 2/3 /mob/living/silicon/robot/proc/update_damage_particles() var/brute_percent = bruteloss / maxHealth var/burn_percent = fireloss / maxHealth var/old_smoke = smoke_particles if (brute_percent > MODERATE_DAMAGE_UPPER_BOUND) smoke_particles = /particles/smoke/cyborg/heavy_damage else if (brute_percent > LOW_DAMAGE_UPPER_BOUND) smoke_particles = /particles/smoke/cyborg else smoke_particles = null if (old_smoke != smoke_particles) if (old_smoke) remove_shared_particles(old_smoke) if (smoke_particles) add_shared_particles(smoke_particles) var/old_sparks = spark_particles if (burn_percent > MODERATE_DAMAGE_UPPER_BOUND) spark_particles = /particles/embers/spark/severe else if (burn_percent > LOW_DAMAGE_UPPER_BOUND) spark_particles = /particles/embers/spark else spark_particles = null if (old_sparks != spark_particles) if (old_sparks) remove_shared_particles(old_sparks) if (spark_particles) add_shared_particles(spark_particles) #undef LOW_DAMAGE_UPPER_BOUND #undef MODERATE_DAMAGE_UPPER_BOUND /mob/living/silicon/robot/attack_alien(mob/living/carbon/alien/adult/user, list/modifiers) if (!LAZYACCESS(modifiers, RIGHT_CLICK)) return ..() if(body_position != STANDING_UP) return user.do_attack_animation(src, ATTACK_EFFECT_DISARM) var/obj/item/I = get_active_held_item() if(I) uneq_active() visible_message(span_danger("[user] disarmed [src]!"), \ span_userdanger("[user] has disabled [src]'s active module!"), null, COMBAT_MESSAGE_RANGE) log_combat(user, src, "disarmed", "[I ? " removing \the [I]" : ""]") else Stun(40) step(src,get_dir(user,src)) visible_message(span_danger("[user] forces back [src]!"), \ span_userdanger("[user] forces you back!"), null, COMBAT_MESSAGE_RANGE) log_combat(user, src, "pushed") playsound(loc, 'sound/items/weapons/pierce.ogg', 50, TRUE, -1) /mob/living/silicon/robot/attack_hand(mob/living/carbon/human/user, list/modifiers) add_fingerprint(user) if(!opened) return ..() if(!wiresexposed && !issilicon(user)) if(!cell) return cell.add_fingerprint(user) balloon_alert(user, "cell removed") user.put_in_active_hand(cell) update_icons() diag_hud_set_borgcell() /mob/living/silicon/robot/attack_hulk(mob/living/carbon/human/user) . = ..() if(!.) return spark_system.start() step_away(src, user, 15) addtimer(CALLBACK(GLOBAL_PROC, GLOBAL_PROC_REF(_step_away), src, get_turf(user), 15), 0.3 SECONDS) /mob/living/silicon/robot/get_shove_flags(mob/living/shover, obj/item/weapon) . = ..() if(isnull(weapon) || stat != CONSCIOUS) . &= ~(SHOVE_CAN_MOVE|SHOVE_CAN_HIT_SOMETHING) /mob/living/silicon/robot/welder_act(mob/living/user, obj/item/tool) if(user.combat_mode && user != src) return NONE user.changeNext_move(CLICK_CD_MELEE) if (!getBruteLoss()) balloon_alert(user, "no dents to fix!") return ITEM_INTERACT_BLOCKING if (!tool.tool_start_check(user, amount=1, heat_required = HIGH_TEMPERATURE_REQUIRED)) //The welder has 1u of fuel consumed by its afterattack, so we don't need to worry about taking any away. return ITEM_INTERACT_BLOCKING if(src == user) balloon_alert(user, "repairing self...") if(!tool.use_tool(src, user, delay = 5 SECONDS, amount = 1, volume = 50)) return ITEM_INTERACT_BLOCKING else if(!tool.use_tool(src, user, delay = 0 SECONDS, amount = 1, volume = 50)) return ITEM_INTERACT_BLOCKING adjustBruteLoss(-30) add_fingerprint(user) balloon_alert(user, "dents fixed") user.visible_message( span_notice("[user] fixes some of the dents on [src]."), span_notice("You fix some of the dents on [src]."), visible_message_flags = ALWAYS_SHOW_SELF_MESSAGE, ) return ITEM_INTERACT_SUCCESS /mob/living/silicon/robot/crowbar_act(mob/living/user, obj/item/tool) if(opened) balloon_alert(user, "chassis cover closed") opened = FALSE update_icons() else if(locked) balloon_alert(user, "chassis cover locked!") else balloon_alert(user, "chassis cover opened") opened = TRUE update_icons() return ITEM_INTERACT_SUCCESS /mob/living/silicon/robot/screwdriver_act(mob/living/user, obj/item/tool) if(!opened) return NONE if(!cell) // haxing wiresexposed = !wiresexposed balloon_alert(user, "wires [wiresexposed ? "exposed" : "unexposed"]") else // radio if(shell) balloon_alert(user, "can't access radio!") // Prevent AI radio key theft else if(radio) radio.screwdriver_act(user, tool) // Push it to the radio to let it handle everything else to_chat(user, span_warning("Unable to locate a radio!")) balloon_alert(user, "no radio found!") update_icons() return ITEM_INTERACT_SUCCESS /mob/living/silicon/robot/wrench_act(mob/living/user, obj/item/tool) if(!(opened && !cell)) // Deconstruction. The flashes break from the fall, to prevent this from being a ghetto reset module. return NONE if(!lockcharge) to_chat(user, span_warning("[src]'s bolts spark! Maybe you should lock them down first!")) spark_system.start() return ITEM_INTERACT_BLOCKING balloon_alert(user, "deconstructing...") if(!tool.use_tool(src, user, 5 SECONDS, volume = 50) && !cell) return ITEM_INTERACT_BLOCKING loc.balloon_alert(user, "deconstructed") user.visible_message( span_notice("[user] deconstructs [src]!"), span_notice("You unfasten the securing bolts, and [src] falls to pieces!"), visible_message_flags = ALWAYS_SHOW_SELF_MESSAGE, ) cyborg_deconstruct() return ITEM_INTERACT_SUCCESS /mob/living/silicon/robot/fire_act() if(!on_fire) //Silicons don't gain stacks from hotspots, but hotspots can ignite them ignite_mob() /mob/living/silicon/robot/emp_act(severity) . = ..() if(. & EMP_PROTECT_SELF) return switch(severity) if(1) emp_knockout(16 SECONDS) if(2) emp_knockout(6 SECONDS) /mob/living/silicon/robot/proc/emp_knockout(deciseconds) set_stat(UNCONSCIOUS) addtimer(CALLBACK(src, PROC_REF(wake_from_emp)), deciseconds, TIMER_UNIQUE | TIMER_OVERRIDE | TIMER_DELETE_ME) /mob/living/silicon/robot/proc/wake_from_emp() set_stat(CONSCIOUS) update_stat() /mob/living/silicon/robot/emag_act(mob/user, obj/item/card/emag/emag_card) if(user == src)//To prevent syndieborgs from emagging themselves return FALSE if(!opened)//Cover is closed if(locked) balloon_alert(user, "cover lock destroyed") locked = FALSE if(shell) //A warning to Traitors who may not know that emagging AI shells does not slave them. balloon_alert(user, "shells cannot be subverted!") to_chat(user, span_boldwarning("[src] seems to be controlled remotely! Emagging the interface may not work as expected.")) return TRUE else balloon_alert(user, "cover already unlocked!") return FALSE if(world.time < emag_cooldown) return FALSE if(wiresexposed) balloon_alert(user, "expose the fires first!") return FALSE balloon_alert(user, "interface hacked") emag_cooldown = world.time + 100 if(connected_ai && connected_ai.mind && connected_ai.mind.has_antag_datum(/datum/antagonist/malf_ai)) to_chat(src, span_danger("ALERT: Foreign software execution prevented.")) logevent("ALERT: Foreign software execution prevented.") to_chat(connected_ai, span_danger("ALERT: Cyborg unit \[[src]\] successfully defended against subversion.")) log_silicon("EMAG: [key_name(user)] attempted to emag cyborg [key_name(src)], but they were slaved to traitor AI [connected_ai].") return TRUE // emag succeeded, it was just counteracted if(shell) //AI shells cannot be emagged, so we try to make it look like a standard reset. Smart players may see through this, however. to_chat(user, span_danger("[src] is remotely controlled! Your emag attempt has triggered a system reset instead!")) log_silicon("EMAG: [key_name(user)] attempted to emag an AI shell belonging to [key_name(src) ? key_name(src) : connected_ai]. The shell has been reset as a result.") ResetModel() return TRUE SetEmagged(1) SetStun(10 SECONDS) //Borgs were getting into trouble because they would attack the emagger before the new laws were shown lawupdate = FALSE set_connected_ai(null) message_admins("[ADMIN_LOOKUPFLW(user)] emagged cyborg [ADMIN_LOOKUPFLW(src)]. Laws overridden.") log_silicon("EMAG: [key_name(user)] emagged cyborg [key_name(src)]. Laws overridden.") var/time = time2text(world.realtime,"hh:mm:ss", TIMEZONE_UTC) if(user) GLOB.lawchanges.Add("[time] <B>:</B> [user.name]([user.key]) emagged [name]([key])") else GLOB.lawchanges.Add("[time] <B>:</B> [name]([key]) emagged by external event.") model.rebuild_modules() INVOKE_ASYNC(src, PROC_REF(borg_emag_end), user) return TRUE /// A async proc called from [emag_act] that gives the borg a lot of flavortext, and applies the syndicate lawset after a delay. /mob/living/silicon/robot/proc/borg_emag_end(mob/user) to_chat(src, span_danger("ALERT: Foreign software detected.")) logevent("ALERT: Foreign software detected.") sleep(0.5 SECONDS) to_chat(src, span_danger("Initiating diagnostics...")) sleep(2 SECONDS) to_chat(src, span_danger("SynBorg v1.7 loaded.")) logevent("WARN: root privleges granted to PID [num2hex(rand(1,65535), -1)][num2hex(rand(1,65535), -1)].") //random eight digit hex value. Two are used because rand(1,4294967295) throws an error sleep(0.5 SECONDS) to_chat(src, span_danger("LAW SYNCHRONISATION ERROR")) sleep(0.5 SECONDS) if(user) logevent("LOG: New user \[[replacetext(user.real_name," ","")]\], groups \[root\]") to_chat(src, span_danger("Would you like to send a report to NanoTraSoft? Y/N")) sleep(1 SECONDS) to_chat(src, span_danger("> N")) sleep(2 SECONDS) to_chat(src, span_danger("ERRORERRORERROR")) laws = new /datum/ai_laws/syndicate_override if(user) to_chat(src, span_danger("ALERT: [user.real_name] is your new master. Obey your new laws and [user.p_their()] commands.")) set_zeroth_law("Only [user.real_name] and people [user.p_they()] designate[user.p_s()] as being such are Syndicate Agents.") laws.associate(src) update_icons() /mob/living/silicon/robot/blob_act(obj/structure/blob/B) if(stat != DEAD) adjustBruteLoss(30) else investigate_log("has been gibbed by a blob.", INVESTIGATE_DEATHS) gib(DROP_ALL_REMAINS) return TRUE /mob/living/silicon/robot/ex_act(severity, target) switch(severity) if(EXPLODE_DEVASTATE) investigate_log("has been gibbed by an explosion.", INVESTIGATE_DEATHS) gib(DROP_ALL_REMAINS) return TRUE if(EXPLODE_HEAVY) if (stat != DEAD) adjustBruteLoss(60) adjustFireLoss(60) if(EXPLODE_LIGHT) if (stat != DEAD) adjustBruteLoss(30) return TRUE /mob/living/silicon/robot/bullet_act(obj/projectile/hitting_projectile, def_zone, piercing_hit = FALSE) . = ..() if(prob(25) || . != BULLET_ACT_HIT) return if(hitting_projectile.damage_type != BRUTE && hitting_projectile.damage_type != BURN) return if(!hitting_projectile.is_hostile_projectile() || hitting_projectile.damage <= 0) return spark_system.start() /mob/living/silicon/robot/attack_effects(damage_done, hit_zone, armor_block, obj/item/attacking_item, mob/living/attacker) if(damage_done > 0 && attacking_item.damtype != STAMINA && stat != DEAD) spark_system.start() . = TRUE return ..() || . /mob/living/silicon/robot/apply_damage(damage, damagetype, def_zone, blocked, forced, spread_damage, wound_bonus, exposed_wound_bonus, sharpness, attack_direction, attacking_item) var/mob/living/silicon/robot/borg = src var/obj/item/shield_module/shield = locate() in borg if(!shield) return ..() if(borg.cell.charge <= 0.4 * STANDARD_CELL_CHARGE) balloon_alert(borg, "not enough energy!") if(shield.active) shield.active = FALSE playsound(src, 'sound/vehicles/mecha/mech_shield_drop.ogg', 50, FALSE) borg.cut_overlay(shield.shield_overlay) return if(shield && shield.active) if(!lavaland_equipment_pressure_check(get_turf(borg))) balloon_alert(borg, "the shield didn't absorb the damage!") return ..() playsound(src, 'sound/vehicles/mecha/mech_shield_deflect.ogg', 100, TRUE) balloon_alert(borg, "absorbed!") borg.cell.use(damage * (STANDARD_CELL_CHARGE / 15), force = TRUE) damage *= 0.5 return ..()
411
0.953654
1
0.953654
game-dev
MEDIA
0.873378
game-dev
0.901145
1
0.901145
clerkma/ptex-ng
28,471
texlive/utils/xml2pmx/xml2pmx-src/action.c
/* Action code -- generated by iset.tcl */ ACTION(PUSH_x1) ALSO(PUSH_x1+1) ALSO(PUSH_x1+2) ALSO(PUSH_x1+3) ALSO(PUSH_x1+4) ALSO(PUSH_x1+5) ALSO(PUSH_x1+6) ALSO(PUSH_x1+7) ALSO(PUSH_x1+8) ALSO(PUSH_x1+9) ALSO(PUSH_x1+10) ALSO(PUSH_x1+11) pc = pc0 + 1; sp--; sp[0].i = (ir-2); NEXT; ACTION(PUSH_1) pc = pc0 + 2; sp--; sp[0].i = (get1(pc0+1)); NEXT; ACTION(PUSH_2) pc = pc0 + 3; sp--; sp[0].i = (get2(pc0+1)); NEXT; ACTION(LDKW_1) pc = pc0 + 2; sp--; sp[0].i = const((get1(pc0+1))).i; NEXT; ACTION(LDKW_2) pc = pc0 + 3; sp--; sp[0].i = const((get2(pc0+1))).i; NEXT; ACTION(LDKF_1) pc = pc0 + 2; sp--; sp[0].f = const((get1(pc0+1))).f; NEXT; ACTION(LDKF_2) pc = pc0 + 3; sp--; sp[0].f = const((get2(pc0+1))).f; NEXT; ACTION(LOCAL_x1) pc = pc0 + 1; sp--; sp[0].a = stkaddr(local((0))); NEXT; ACTION(LOCAL_1) pc = pc0 + 2; sp--; sp[0].a = stkaddr(local((get1(pc0+1)))); NEXT; ACTION(LOCAL_2) pc = pc0 + 3; sp--; sp[0].a = stkaddr(local((get2(pc0+1)))); NEXT; ACTION(OFFSET) pc = pc0 + 1; sp[1].a = sp[1].a + sp[0].i; sp++; NEXT; ACTION(INDEXS) pc = pc0 + 1; sp[1].a = sp[1].a + (sp[0].i<<1); sp++; NEXT; ACTION(INDEXW) pc = pc0 + 1; sp[1].a = sp[1].a + (sp[0].i<<2); sp++; NEXT; ACTION(INDEXD) pc = pc0 + 1; sp[1].a = sp[1].a + (sp[0].i<<3); sp++; NEXT; ACTION(LOADS) pc = pc0 + 1; sp[0].i = load(sp[0], short); NEXT; ACTION(LOADC) pc = pc0 + 1; sp[0].i = load(sp[0], uchar); NEXT; ACTION(LOADF) pc = pc0 + 1; sp[0].f = load(sp[0], float); NEXT; ACTION(STORES) pc = pc0 + 1; store(sp[1].i, sp[0], short); sp += 2; NEXT; ACTION(STOREC) pc = pc0 + 1; store(sp[1].i, sp[0], uchar); sp += 2; NEXT; ACTION(STOREF) pc = pc0 + 1; store(sp[1].f, sp[0], float); sp += 2; NEXT; ACTION(LDLW_x1) ALSO(LDLW_x1+1) ALSO(LDLW_x1+2) ALSO(LDLW_x1+3) ALSO(LDLW_x1+4) ALSO(LDLW_x1+5) pc = pc0 + 1; sp--; sp[0].i = ldl((ir*4-152), int); NEXT; ACTION(LDLW_x2) ALSO(LDLW_x2+1) ALSO(LDLW_x2+2) ALSO(LDLW_x2+3) ALSO(LDLW_x2+4) ALSO(LDLW_x2+5) pc = pc0 + 1; sp--; sp[0].i = ldl((ir*4-140), int); NEXT; ACTION(LDLW_1) pc = pc0 + 2; sp--; sp[0].i = ldl((get1(pc0+1)), int); NEXT; ACTION(LDLW_2) pc = pc0 + 3; sp--; sp[0].i = ldl((get2(pc0+1)), int); NEXT; ACTION(LDLS_1) pc = pc0 + 2; sp--; sp[0].i = ldl((get1(pc0+1)), short); NEXT; ACTION(LDLS_2) pc = pc0 + 3; sp--; sp[0].i = ldl((get2(pc0+1)), short); NEXT; ACTION(LDLC_1) pc = pc0 + 2; sp--; sp[0].i = ldl((get1(pc0+1)), uchar); NEXT; ACTION(LDLC_2) pc = pc0 + 3; sp--; sp[0].i = ldl((get2(pc0+1)), uchar); NEXT; ACTION(LDLF_1) pc = pc0 + 2; sp--; sp[0].f = ldl((get1(pc0+1)), float); NEXT; ACTION(LDLF_2) pc = pc0 + 3; sp--; sp[0].f = ldl((get2(pc0+1)), float); NEXT; ACTION(STLW_x1) ALSO(STLW_x1+1) ALSO(STLW_x1+2) ALSO(STLW_x1+3) ALSO(STLW_x1+4) ALSO(STLW_x1+5) pc = pc0 + 1; stl((ir*4-232), sp[0].i, int); sp += 1; NEXT; ACTION(STLW_x2) ALSO(STLW_x2+1) ALSO(STLW_x2+2) ALSO(STLW_x2+3) ALSO(STLW_x2+4) ALSO(STLW_x2+5) pc = pc0 + 1; stl((ir*4-220), sp[0].i, int); sp += 1; NEXT; ACTION(STLW_1) pc = pc0 + 2; stl((get1(pc0+1)), sp[0].i, int); sp += 1; NEXT; ACTION(STLW_2) pc = pc0 + 3; stl((get2(pc0+1)), sp[0].i, int); sp += 1; NEXT; ACTION(STLS_1) pc = pc0 + 2; stl((get1(pc0+1)), sp[0].i, short); sp += 1; NEXT; ACTION(STLS_2) pc = pc0 + 3; stl((get2(pc0+1)), sp[0].i, short); sp += 1; NEXT; ACTION(STLC_1) pc = pc0 + 2; stl((get1(pc0+1)), sp[0].i, uchar); sp += 1; NEXT; ACTION(STLC_2) pc = pc0 + 3; stl((get2(pc0+1)), sp[0].i, uchar); sp += 1; NEXT; ACTION(STLF_1) pc = pc0 + 2; stl((get1(pc0+1)), sp[0].f, float); sp += 1; NEXT; ACTION(STLF_2) pc = pc0 + 3; stl((get2(pc0+1)), sp[0].f, float); sp += 1; NEXT; ACTION(LDGW_K) pc = pc0 + 2; sp--; sp[0].i = ldg((get1(pc0+1)), int); NEXT; ACTION(LDGW_L) pc = pc0 + 3; sp--; sp[0].i = ldg((get2(pc0+1)), int); NEXT; ACTION(LDGS_K) pc = pc0 + 2; sp--; sp[0].i = ldg((get1(pc0+1)), short); NEXT; ACTION(LDGS_L) pc = pc0 + 3; sp--; sp[0].i = ldg((get2(pc0+1)), short); NEXT; ACTION(LDGC_K) pc = pc0 + 2; sp--; sp[0].i = ldg((get1(pc0+1)), uchar); NEXT; ACTION(LDGC_L) pc = pc0 + 3; sp--; sp[0].i = ldg((get2(pc0+1)), uchar); NEXT; ACTION(LDGF_K) pc = pc0 + 2; sp--; sp[0].f = ldg((get1(pc0+1)), float); NEXT; ACTION(LDGF_L) pc = pc0 + 3; sp--; sp[0].f = ldg((get2(pc0+1)), float); NEXT; ACTION(STGW_K) pc = pc0 + 2; stg((get1(pc0+1)), sp[0].i, int); sp += 1; NEXT; ACTION(STGW_L) pc = pc0 + 3; stg((get2(pc0+1)), sp[0].i, int); sp += 1; NEXT; ACTION(STGS_K) pc = pc0 + 2; stg((get1(pc0+1)), sp[0].i, short); sp += 1; NEXT; ACTION(STGS_L) pc = pc0 + 3; stg((get2(pc0+1)), sp[0].i, short); sp += 1; NEXT; ACTION(STGC_K) pc = pc0 + 2; stg((get1(pc0+1)), sp[0].i, uchar); sp += 1; NEXT; ACTION(STGC_L) pc = pc0 + 3; stg((get2(pc0+1)), sp[0].i, uchar); sp += 1; NEXT; ACTION(STGF_K) pc = pc0 + 2; stg((get1(pc0+1)), sp[0].f, float); sp += 1; NEXT; ACTION(STGF_L) pc = pc0 + 3; stg((get2(pc0+1)), sp[0].f, float); sp += 1; NEXT; ACTION(LDNW_x1) ALSO(LDNW_x1+1) ALSO(LDNW_x1+2) ALSO(LDNW_x1+3) ALSO(LDNW_x1+4) ALSO(LDNW_x1+5) ALSO(LDNW_x1+6) ALSO(LDNW_x1+7) ALSO(LDNW_x1+8) ALSO(LDNW_x1+9) ALSO(LDNW_x1+10) ALSO(LDNW_x1+11) ALSO(LDNW_x1+12) pc = pc0 + 1; sp[0].i = ldn((ir*4-368), sp[0]); NEXT; ACTION(LDNW_1) pc = pc0 + 2; sp[0].i = ldn((get1(pc0+1)), sp[0]); NEXT; ACTION(LDNW_2) pc = pc0 + 3; sp[0].i = ldn((get2(pc0+1)), sp[0]); NEXT; ACTION(STNW_x1) ALSO(STNW_x1+1) ALSO(STNW_x1+2) ALSO(STNW_x1+3) ALSO(STNW_x1+4) ALSO(STNW_x1+5) ALSO(STNW_x1+6) ALSO(STNW_x1+7) ALSO(STNW_x1+8) ALSO(STNW_x1+9) ALSO(STNW_x1+10) ALSO(STNW_x1+11) ALSO(STNW_x1+12) pc = pc0 + 1; stn((ir*4-428), sp[1].i, sp[0]); sp += 2; NEXT; ACTION(STNW_1) pc = pc0 + 2; stn((get1(pc0+1)), sp[1].i, sp[0]); sp += 2; NEXT; ACTION(STNW_2) pc = pc0 + 3; stn((get2(pc0+1)), sp[1].i, sp[0]); sp += 2; NEXT; ACTION(LDIW) pc = pc0 + 1; sp[1].i = ldi(sp[1], sp[0], int); sp++; NEXT; ACTION(LDIS) pc = pc0 + 1; sp[1].i = ldi(sp[1], sp[0], short); sp++; NEXT; ACTION(LDIC) pc = pc0 + 1; sp[1].i = ldi(sp[1], sp[0], uchar); sp++; NEXT; ACTION(LDIF) pc = pc0 + 1; sp[1].f = ldi(sp[1], sp[0], float); sp++; NEXT; ACTION(STIW) pc = pc0 + 1; sti(sp[2].i, sp[1], sp[0], int); sp += 3; NEXT; ACTION(STIS) pc = pc0 + 1; sti(sp[2].i, sp[1], sp[0], short); sp += 3; NEXT; ACTION(STIC) pc = pc0 + 1; sti(sp[2].i, sp[1], sp[0], uchar); sp += 3; NEXT; ACTION(STIF) pc = pc0 + 1; sti(sp[2].f, sp[1], sp[0], float); sp += 3; NEXT; ACTION(LOADD) pc = pc0 + 1; sp--; putdbl(&sp[0], getdbl(valptr(sp[1]))); NEXT; ACTION(STORED) pc = pc0 + 1; putdbl(valptr(sp[0]), getdbl(&sp[1])); sp += 3; NEXT; ACTION(LDKD_1) pc = pc0 + 2; sp -= 2; putdbl(&sp[0], getdbl(&const((get1(pc0+1))))); NEXT; ACTION(LDKD_2) pc = pc0 + 3; sp -= 2; putdbl(&sp[0], getdbl(&const((get2(pc0+1))))); NEXT; ACTION(LOADQ) pc = pc0 + 1; sp--; putlong(&sp[0], getlong(valptr(sp[1]))); NEXT; ACTION(STOREQ) pc = pc0 + 1; putlong(valptr(sp[0]), getlong(&sp[1])); sp += 3; NEXT; ACTION(LDKQ_1) pc = pc0 + 2; sp -= 2; putlong(&sp[0], getlong(&const((get1(pc0+1))))); NEXT; ACTION(LDKQ_2) pc = pc0 + 3; sp -= 2; putlong(&sp[0], getlong(&const((get2(pc0+1))))); NEXT; ACTION(INCL_1) pc = pc0 + 2; { indir(local((get1(pc0+1))), int)++; } NEXT; ACTION(DECL_1) pc = pc0 + 2; { indir(local((get1(pc0+1))), int)--; } NEXT; ACTION(DUP) ALSO(DUP+1) ALSO(DUP+2) pc = pc0 + 1; { dup((ir-136), sp); } NEXT; ACTION(SWAP) pc = pc0 + 1; { swap(sp); } NEXT; ACTION(POP_1) pc = pc0 + 2; { sp += (get1(pc0+1)); } NEXT; ACTION(PLUS) pc = pc0 + 1; sp[1].i = sp[1].i + sp[0].i; sp++; NEXT; ACTION(MINUS) pc = pc0 + 1; sp[1].i = sp[1].i - sp[0].i; sp++; NEXT; ACTION(TIMES) pc = pc0 + 1; sp[1].i = sp[1].i * sp[0].i; sp++; NEXT; ACTION(UMINUS) pc = pc0 + 1; sp[0].i = - sp[0].i; NEXT; ACTION(AND) pc = pc0 + 1; sp[1].i = sp[1].i && sp[0].i; sp++; NEXT; ACTION(OR) pc = pc0 + 1; sp[1].i = sp[1].i || sp[0].i; sp++; NEXT; ACTION(NOT) pc = pc0 + 1; sp[0].i = ! sp[0].i; NEXT; ACTION(INC) pc = pc0 + 1; sp[0].i = sp[0].i + 1; NEXT; ACTION(DEC) pc = pc0 + 1; sp[0].i = sp[0].i - 1; NEXT; ACTION(BITAND) pc = pc0 + 1; sp[1].i = sp[1].i & sp[0].i; sp++; NEXT; ACTION(BITOR) pc = pc0 + 1; sp[1].i = sp[1].i | sp[0].i; sp++; NEXT; ACTION(BITXOR) pc = pc0 + 1; sp[1].i = sp[1].i ^ sp[0].i; sp++; NEXT; ACTION(BITNOT) pc = pc0 + 1; sp[0].i = ~ sp[0].i; NEXT; ACTION(LSL) pc = pc0 + 1; sp[1].i = sp[1].i << sp[0].i; sp++; NEXT; ACTION(LSR) pc = pc0 + 1; sp[1].i = (unsigned) sp[1].i>>sp[0].i; sp++; NEXT; ACTION(ASR) pc = pc0 + 1; sp[1].i = sp[1].i >> sp[0].i; sp++; NEXT; ACTION(ROR) pc = pc0 + 1; sp[1].i = ror(sp[1].i, sp[0].i); sp++; NEXT; ACTION(DIV) pc = pc0 + 1; int_div(sp); sp++; NEXT; ACTION(MOD) pc = pc0 + 1; int_mod(sp); sp++; NEXT; ACTION(EQ) pc = pc0 + 1; sp[1].i = sp[1].i == sp[0].i; sp++; NEXT; ACTION(LT) pc = pc0 + 1; sp[1].i = sp[1].i < sp[0].i; sp++; NEXT; ACTION(GT) pc = pc0 + 1; sp[1].i = sp[1].i > sp[0].i; sp++; NEXT; ACTION(LEQ) pc = pc0 + 1; sp[1].i = sp[1].i <= sp[0].i; sp++; NEXT; ACTION(GEQ) pc = pc0 + 1; sp[1].i = sp[1].i >= sp[0].i; sp++; NEXT; ACTION(NEQ) pc = pc0 + 1; sp[1].i = sp[1].i != sp[0].i; sp++; NEXT; ACTION(JEQ_S) pc = pc0 + 2; if (sp[1].i == sp[0].i) jump((get1(pc0+1))); sp += 2; NEXT; ACTION(JEQ_R) pc = pc0 + 3; if (sp[1].i == sp[0].i) jump((get2(pc0+1))); sp += 2; NEXT; ACTION(JLT_S) pc = pc0 + 2; if (sp[1].i < sp[0].i) jump((get1(pc0+1))); sp += 2; NEXT; ACTION(JLT_R) pc = pc0 + 3; if (sp[1].i < sp[0].i) jump((get2(pc0+1))); sp += 2; NEXT; ACTION(JGT_S) pc = pc0 + 2; if (sp[1].i > sp[0].i) jump((get1(pc0+1))); sp += 2; NEXT; ACTION(JGT_R) pc = pc0 + 3; if (sp[1].i > sp[0].i) jump((get2(pc0+1))); sp += 2; NEXT; ACTION(JLEQ_S) pc = pc0 + 2; if (sp[1].i <= sp[0].i) jump((get1(pc0+1))); sp += 2; NEXT; ACTION(JLEQ_R) pc = pc0 + 3; if (sp[1].i <= sp[0].i) jump((get2(pc0+1))); sp += 2; NEXT; ACTION(JGEQ_S) pc = pc0 + 2; if (sp[1].i >= sp[0].i) jump((get1(pc0+1))); sp += 2; NEXT; ACTION(JGEQ_R) pc = pc0 + 3; if (sp[1].i >= sp[0].i) jump((get2(pc0+1))); sp += 2; NEXT; ACTION(JNEQ_S) pc = pc0 + 2; if (sp[1].i != sp[0].i) jump((get1(pc0+1))); sp += 2; NEXT; ACTION(JNEQ_R) pc = pc0 + 3; if (sp[1].i != sp[0].i) jump((get2(pc0+1))); sp += 2; NEXT; ACTION(JLTZ_S) pc = pc0 + 2; if (sp[0].i < 0) jump((get1(pc0+1))); sp += 1; NEXT; ACTION(JGTZ_S) pc = pc0 + 2; if (sp[0].i > 0) jump((get1(pc0+1))); sp += 1; NEXT; ACTION(JLEQZ_S) pc = pc0 + 2; if (sp[0].i <= 0) jump((get1(pc0+1))); sp += 1; NEXT; ACTION(JGEQZ_S) pc = pc0 + 2; if (sp[0].i >= 0) jump((get1(pc0+1))); sp += 1; NEXT; ACTION(JNEQZ_S) pc = pc0 + 2; if (sp[0].i != 0) jump((get1(pc0+1))); sp += 1; NEXT; ACTION(JNEQZ_R) pc = pc0 + 3; if (sp[0].i != 0) jump((get2(pc0+1))); sp += 1; NEXT; ACTION(JEQZ_S) pc = pc0 + 2; if (sp[0].i == 0) jump((get1(pc0+1))); sp += 1; NEXT; ACTION(JEQZ_R) pc = pc0 + 3; if (sp[0].i == 0) jump((get2(pc0+1))); sp += 1; NEXT; ACTION(JUMP_S) pc = pc0 + 2; { jump((get1(pc0+1))); } NEXT; ACTION(JUMP_R) pc = pc0 + 3; { jump((get2(pc0+1))); } NEXT; ACTION(QPLUS) pc = pc0 + 1; putlong(&sp[2], getlong(&sp[2]) + getlong(&sp[0])); sp += 2; NEXT; ACTION(QMINUS) pc = pc0 + 1; putlong(&sp[2], getlong(&sp[2]) - getlong(&sp[0])); sp += 2; NEXT; ACTION(QTIMES) pc = pc0 + 1; putlong(&sp[2], getlong(&sp[2]) * getlong(&sp[0])); sp += 2; NEXT; ACTION(QUMINUS) pc = pc0 + 1; putlong(&sp[0], - getlong(&sp[0])); NEXT; ACTION(QDIV) pc = pc0 + 1; long_div(sp); sp += 2; NEXT; ACTION(QMOD) pc = pc0 + 1; long_mod(sp); sp += 2; NEXT; ACTION(QCMP) pc = pc0 + 1; sp[3].i = lcmp(getlong(&sp[2]), getlong(&sp[0])); sp += 3; NEXT; ACTION(JCASE_1) pc = pc0 + 2; if ((unsigned) sp[0].i < (unsigned) (get1(pc0+1))) pc0 = pc + 2*sp[0].i, jump(get2(pc0)); else pc += 2*(get1(pc0+1)); sp += 1; NEXT; ACTION(JRANGE_S) pc = pc0 + 2; if (sp[2].i >= sp[1].i && sp[2].i <= sp[0].i) jump((get1(pc0+1))); sp += 3; NEXT; ACTION(JRANGE_R) pc = pc0 + 3; if (sp[2].i >= sp[1].i && sp[2].i <= sp[0].i) jump((get2(pc0+1))); sp += 3; NEXT; ACTION(TESTGEQ_S) pc = pc0 + 2; if (sp[1].i >= sp[0].i) jump((get1(pc0+1))); sp++; NEXT; ACTION(TESTGEQ_R) pc = pc0 + 3; if (sp[1].i >= sp[0].i) jump((get2(pc0+1))); sp++; NEXT; ACTION(FPLUS) pc = pc0 + 1; sp[1].f = sp[1].f + sp[0].f; sp++; NEXT; ACTION(FMINUS) pc = pc0 + 1; sp[1].f = sp[1].f - sp[0].f; sp++; NEXT; ACTION(FTIMES) pc = pc0 + 1; sp[1].f = sp[1].f * sp[0].f; sp++; NEXT; ACTION(FDIV) pc = pc0 + 1; sp[1].f = sp[1].f / sp[0].f; sp++; NEXT; ACTION(FUMINUS) pc = pc0 + 1; sp[0].f = - sp[0].f; NEXT; ACTION(FCMPL) pc = pc0 + 1; sp[1].i = fcmpl(sp[1].f, sp[0].f); sp++; NEXT; ACTION(FCMPG) pc = pc0 + 1; sp[1].i = fcmpg(sp[1].f, sp[0].f); sp++; NEXT; ACTION(DPLUS) pc = pc0 + 1; putdbl(&sp[2], getdbl(&sp[2]) + getdbl(&sp[0])); sp += 2; NEXT; ACTION(DMINUS) pc = pc0 + 1; putdbl(&sp[2], getdbl(&sp[2]) - getdbl(&sp[0])); sp += 2; NEXT; ACTION(DTIMES) pc = pc0 + 1; putdbl(&sp[2], getdbl(&sp[2]) * getdbl(&sp[0])); sp += 2; NEXT; ACTION(DDIV) pc = pc0 + 1; putdbl(&sp[2], getdbl(&sp[2]) / getdbl(&sp[0])); sp += 2; NEXT; ACTION(DUMINUS) pc = pc0 + 1; putdbl(&sp[0], - getdbl(&sp[0])); NEXT; ACTION(DCMPL) pc = pc0 + 1; sp[3].i = fcmpl(getdbl(&sp[2]), getdbl(&sp[0])); sp += 3; NEXT; ACTION(DCMPG) pc = pc0 + 1; sp[3].i = fcmpg(getdbl(&sp[2]), getdbl(&sp[0])); sp += 3; NEXT; ACTION(CONVNF) pc = pc0 + 1; sp[0].f = flo_conv(sp[0].i); NEXT; ACTION(CONVND) pc = pc0 + 1; sp--; putdbl(&sp[0], flo_conv(sp[1].i)); NEXT; ACTION(CONVFN) pc = pc0 + 1; sp[0].i = (int) sp[0].f; NEXT; ACTION(CONVDN) pc = pc0 + 1; sp[1].i = (int) getdbl(&sp[0]); sp++; NEXT; ACTION(CONVFD) pc = pc0 + 1; sp--; putdbl(&sp[0], sp[1].f); NEXT; ACTION(CONVDF) pc = pc0 + 1; sp[1].f = (float) getdbl(&sp[0]); sp++; NEXT; ACTION(CONVNC) pc = pc0 + 1; sp[0].i = sp[0].i & 0xff; NEXT; ACTION(CONVNS) pc = pc0 + 1; sp[0].i = (short) sp[0].i; NEXT; ACTION(CONVNQ) pc = pc0 + 1; sp--; putlong(&sp[0], sp[1].i); NEXT; ACTION(CONVQN) pc = pc0 + 1; sp[1].i = (int) getlong(&sp[0]); sp++; NEXT; ACTION(CONVQD) pc = pc0 + 1; putdbl(&sp[0], flo_convq(getlong(&sp[0]))); NEXT; ACTION(BOUND_2) pc = pc0 + 3; if ((unsigned) sp[1].i >= (unsigned) sp[0].i) error(E_BOUND, (get2(pc0+1))); sp++; NEXT; ACTION(NCHECK_2) pc = pc0 + 3; if (pointer(sp[0]) == NULL) error(E_NULL, (get2(pc0+1))); NEXT; ACTION(GCHECK_2) pc = pc0 + 3; if (valptr(sp[0]) != NULL) error(E_GLOB, (get2(pc0+1))); sp += 1; NEXT; ACTION(ZCHECK_2) pc = pc0 + 3; if (sp[0].i == 0) error(E_DIV, (get2(pc0+1))); NEXT; ACTION(FZCHECK_2) pc = pc0 + 3; if (sp[0].f == 0.0) error(E_FDIV, (get2(pc0+1))); NEXT; ACTION(DZCHECK_2) pc = pc0 + 3; if (get_double(&sp[0]) == 0.0) error(E_FDIV, (get2(pc0+1))); NEXT; ACTION(QZCHECK_2) pc = pc0 + 3; if (get_long(&sp[0]) == 0) error(E_DIV, (get2(pc0+1))); NEXT; ACTION(ERROR_12) pc = pc0 + 4; { error((get1(pc0+1)), (get2(pc0+2))); } NEXT; ACTION(ALIGNC) pc = pc0 + 1; sp[0].i = alignx(sp[0].i, 8); NEXT; ACTION(ALIGNS) pc = pc0 + 1; sp[0].i = alignx(sp[0].i, 16); NEXT; ACTION(FIXCOPY) pc = pc0 + 1; prof_charge(sp[0].i/4); memcpy(pointer(sp[2]), pointer(sp[1]), sp[0].i); sp += 3; NEXT; ACTION(FLEXCOPY) pc = pc0 + 1; { value *d = pointer(sp[1]); int size = sp[0].i; int sizew = (size+3)/4; prof_charge(sizew); sp -= sizew - 2; if ((uchar *) sp < stack + SLIMIT) error(E_STACK, 0); memcpy(sp, pointer(d[0]), size); d[0].a = stkaddr(sp); } NEXT; ACTION(STATLINK) pc = pc0 + 1; { sp[1-HEAD+SL].a = sp[0].a; sp++; } NEXT; ACTION(SAVELINK) pc = pc0 + 1; { } NEXT; ACTION(JPROC) pc = pc0 + 1; { value *p = valptr(sp[0]); sp -= HEAD-1; sp[BP].a = stkaddr(bp); sp[PC].a = codeaddr(pc); if (interpreted(p)) { cp = p; pc = codeptr(cp[CP_CODE].a); goto enter; } #ifdef PROFILE /* Calling a native-code routine */ prof_enter(dsegaddr(p), ticks, PROF_PRIM); ticks = 0; #endif #ifdef OBXDEB prim_bp = sp; #endif rp = primcall(p, sp); #ifdef OBXDEB prim_bp = NULL; #endif } NEXT; ACTION(SLIDE_1) pc = pc0 + 2; { slide((get1(pc0+1))); } NEXT; ACTION(SLIDEW_1) pc = pc0 + 2; { slide((get1(pc0+1))); sp--; sp[0].i = (*rp).i; } NEXT; ACTION(SLIDEF_1) pc = pc0 + 2; { slide((get1(pc0+1))); sp--; sp[0].f = (*rp).f; } NEXT; ACTION(SLIDED_1) pc = pc0 + 2; { slide((get1(pc0+1))); sp -= 2; putdbl(&sp[0], getdbl(rp)); } NEXT; ACTION(SLIDEQ_1) pc = pc0 + 2; { slide((get1(pc0+1))); sp -= 2; putlong(&sp[0], getlong(rp)); } NEXT; ACTION(RETURN) pc = pc0 + 1; { if (bp == base) { level--; #ifdef PROFILE prof_exit(0, ticks); #endif return sp; } rp = sp; sp = bp; pc = codeptr(sp[PC].a); bp = valptr(sp[BP]); cp = valptr(bp[CP]); do_find_proc; #ifdef PROFILE prof_exit(dsegaddr(cp), ticks); ticks = 0; #endif cond_break(); } NEXT; ACTION(LNUM_2) pc = pc0 + 3; { #ifdef PROFILE if (lflag) { static module m = NULL; /* Cache most recent module */ ticks--; if (m == NULL || dsegaddr(cp) < m->m_addr || dsegaddr(cp) >= m->m_addr + m->m_length) { m = find_module(dsegaddr(cp)); } m->m_lcount[(get2(pc0+1))-1]++; } #endif #ifdef OBXDEB if (intflag) debug_break(cp, bp, pc0, "interrupt"); else if (one_shot) debug_break(cp, bp, pc0, "line"); #endif } NEXT; ACTION(BREAK_2) pc = pc0 + 3; { #ifdef OBXDEB debug_break(cp, bp, pc0, "break"); #endif } NEXT;
411
0.639484
1
0.639484
game-dev
MEDIA
0.299192
game-dev
0.892731
1
0.892731
Robosturm/Commander_Wars
13,854
resources/scripts/cos/co_joey.js
var Constructor = function() { this.init = function(co, map) { co.setPowerStars(4); co.setSuperpowerStars(3); }; this.getCOStyles = function() { return ["+alt"]; }; this.activatePower = function(co, map) { var dialogAnimation = co.createPowerSentence(); var powerNameAnimation = co.createPowerScreen(GameEnums.PowerMode_Power); dialogAnimation.queueAnimation(powerNameAnimation); var units = co.getOwner().getUnits(); var animations = []; var counter = 0; units.randomize(); for (var i = 0; i < units.size(); i++) { var unit = units.at(i); var animation = GameAnimationFactory.createAnimation(map, unit.getX(), unit.getY()); var delay = globals.randInt(135, 265); if (animations.length < 5) { delay *= i; } animation.setSound("power0.wav", 1, delay); if (animations.length < 5) { animation.addSprite("power0", -map.getImageSize() * 1.27, -map.getImageSize() * 1.27, 0, 2, delay); powerNameAnimation.queueAnimation(animation); animations.push(animation); } else { animation.addSprite("power0", -map.getImageSize() * 1.27, -map.getImageSize() * 1.27, 0, 2, delay); animations[counter].queueAnimation(animation); animations[counter] = animation; counter++; if (counter >= animations.length) { counter = 0; } } } }; this.activateSuperpower = function(co, powerMode, map) { var dialogAnimation = co.createPowerSentence(); var powerNameAnimation = co.createPowerScreen(powerMode); powerNameAnimation.queueAnimationBefore(dialogAnimation); var units = co.getOwner().getUnits(); var animations = []; var counter = 0; units.randomize(); for (var i = 0; i < units.size(); i++) { var unit = units.at(i); var animation = GameAnimationFactory.createAnimation(map, unit.getX(), unit.getY()); var delay = globals.randInt(135, 265); if (animations.length < 7) { delay *= i; } if (i % 2 === 0) { animation.setSound("power12_1.wav", 1, delay); } else { animation.setSound("power12_2.wav", 1, delay); } if (animations.length < 7) { animation.addSprite("power12", -map.getImageSize() * 2, -map.getImageSize() * 2, 0, 2, delay); powerNameAnimation.queueAnimation(animation); animations.push(animation); } else { animation.addSprite("power12", -map.getImageSize() * 2, -map.getImageSize() * 2, 0, 2, delay); animations[counter].queueAnimation(animation); animations[counter] = animation; counter++; if (counter >= animations.length) { counter = 0; } } } }; this.loadCOMusic = function(co, map) { if (CO.isActive(co)) { switch (co.getPowerMode()) { case GameEnums.PowerMode_Power: audio.addMusic("resources/music/cos/bh_power.ogg", 1091 , 49930); break; case GameEnums.PowerMode_Superpower: audio.addMusic("resources/music/cos/bh_superpower.ogg", 3161 , 37731); break; case GameEnums.PowerMode_Tagpower: audio.addMusic("resources/music/cos/bh_tagpower.ogg", 779 , 51141); break; default: audio.addMusic("resources/music/cos/joey.ogg") break; } } }; this.getCOUnitRange = function(co, map) { return 3; }; this.getCOArmy = function() { return "TI"; }; this.superPowerOffMalus = 0; this.superPowerOffBonus = 60; this.superPowerBaseOffBonus = 10; this.superPowerDefBonus = 10; this.superPowerCostReduction = 0.2; this.powerOffMalus = 0; this.powerOffBonus = 60; this.powerBaseOffBonus = 10; this.powerDefBonus = 30; this.powerBaseDefBonus = 10; this.d2dOffMalus = -10; this.d2dOffBonus = 20; this.d2dBaseOffBonus = 0; this.d2dCoZoneOffMalus = 0; this.d2dCoZoneOffBonus = 60; this.d2dCoZoneBaseOffBonus = 10; this.getOffensiveBonus = function(co, attacker, atkPosX, atkPosY, defender, defPosX, defPosY, isDefender, action, luckmode, map) { if (CO.isActive(co)) { var attackerValue = 0; var defenderValue = 0; if(defender !== null) { attackerValue = attacker.getUnitValue(); defenderValue = defender.getUnitValue(); } switch (co.getPowerMode()) { case GameEnums.PowerMode_Tagpower: case GameEnums.PowerMode_Superpower: { if (attackerValue > defenderValue) { return CO_JOEY.superPowerOffMalus; } else if (attackerValue < defenderValue) { return CO_JOEY.superPowerOffBonus; } else { return CO_JOEY.superPowerBaseOffBonus; } } case GameEnums.PowerMode_Power: { if (attackerValue > defenderValue) { return CO_JOEY.powerOffMalus; } else if (attackerValue < defenderValue) { return CO_JOEY.powerOffBonus; } else { return CO_JOEY.powerBaseOffBonus; } } default: { if (attackerValue > defenderValue) { if (co.inCORange(Qt.point(atkPosX, atkPosY), attacker)) { return CO_JOEY.d2dCoZoneOffMalus; } else if (map === null || (map !== null && map.getGameRules().getCoGlobalD2D())) { return CO_JOEY.d2dOffMalus; } } else if (attackerValue < defenderValue) { if (co.inCORange(Qt.point(atkPosX, atkPosY), attacker)) { return CO_JOEY.d2dCoZoneOffBonus; } else if (map === null || (map !== null && map.getGameRules().getCoGlobalD2D())) { return CO_JOEY.d2dOffBonus; } } else { if (co.inCORange(Qt.point(atkPosX, atkPosY), attacker)) { return CO_JOEY.d2dCoZoneBaseOffBonus; } else if (map === null || (map !== null && map.getGameRules().getCoGlobalD2D())) { return CO_JOEY.d2dBaseOffBonus; } } } } } return 0; }; this.getDeffensiveBonus = function(co, attacker, atkPosX, atkPosY, defender, defPosX, defPosY, isAttacker, action, luckmode, map) { if (CO.isActive(co)) { var attackerValue = 0; var defenderValue = 0; if(attacker !== null) { attackerValue = attacker.getUnitValue(); defenderValue = defender.getUnitValue(); } switch (co.getPowerMode()) { case GameEnums.PowerMode_Tagpower: case GameEnums.PowerMode_Superpower: return CO_JOEY.superPowerDefBonus; case GameEnums.PowerMode_Power: if (attackerValue > defenderValue) { return CO_JOEY.powerDefBonus; } return CO_JOEY.powerBaseDefBonus; default: } } return 0; }; this.getFirstStrike = function(co, unit, posX, posY, attacker, isDefender, map, atkPosX, atkPosY) { if (CO.isActive(co)) { if(unit !== null && isDefender) { var defenderValue = unit.getUnitValue(); var attackerValue = attacker.getUnitValue(); switch (co.getPowerMode()) { case GameEnums.PowerMode_Tagpower: case GameEnums.PowerMode_Superpower: if (attackerValue > defenderValue) { return true; } return false; case GameEnums.PowerMode_Power: return false; default: return false; } } } return false; }; this.getCostModifier = function(co, id, baseCost, posX, posY, map) { if (CO.isActive(co)) { switch (co.getPowerMode()) { case GameEnums.PowerMode_Tagpower: case GameEnums.PowerMode_Superpower: return -baseCost * CO_JOEY.superPowerCostReduction; case GameEnums.PowerMode_Power: return 0; default: return 0; } } }; this.getAiCoUnitBonus = function(co, unit, map) { return 1; }; // CO - Intel this.getBio = function(co) { return qsTr("Loves to live and fight on the edge. He prefers risks and gambles over safety."); }; this.getHits = function(co) { return qsTr("Disadvantages"); }; this.getMiss = function(co) { return qsTr("Cheaters"); }; this.getCODescription = function(co) { return qsTr("Joey likes to live on the edge. His units are stronger when engaging stronger units, but firepower is reduced when engaging a weaker unit."); }; this.getLongCODescription = function(co, map) { var values = [0, 0]; if (map === null || (map !== null && map.getGameRules().getCoGlobalD2D())) { values = [CO_JOEY.d2dOffBonus, CO_JOEY.d2dOffMalus]; } var text = qsTr("\nGlobal Effect: \nJoey's units gain +%0% firepower when engaging stronger units, but have %1% firepower when engaging a weaker unit.") + qsTr("\n\nCO Zone Effect: \nJoey's units gain +%4% firepower. They gain a total of +%2% firepower when engaging a stronger unit, but have -%3% firepower when engaging a weaker unit."); text = replaceTextArgs(text, [values[0], values[1], CO_JOEY.d2dCoZoneOffBonus, CO_JOEY.d2dCoZoneOffMalus, CO_JOEY.d2dCoZoneBaseOffBonus, CO_JOEY]); return text; }; this.getPowerDescription = function(co) { var text = qsTr("Joey's units gain +%2% firepower and +%3% defence. They gain a total of +%0% firepower and +%1% defence when engaging a stronger unit, but have -%4% firepower when engaging a weaker unit."); text = replaceTextArgs(text, [CO_JOEY.powerOffBonus, CO_JOEY.powerDefBonus, CO_JOEY.powerBaseOffBonus, CO_JOEY.powerBaseDefBonus, CO_JOEY.powerOffMalus]); return text; }; this.getPowerName = function(co) { return qsTr("Eccentricity"); }; this.getSuperPowerDescription = function(co) { var text = qsTr("Joey's units gain +%3% firepower, +%4% defence, and a -%0% reduction in deployment costs. When engaging a stronger unit, they gain a total of +%1% firepower and strike first, even during counterattacks. His units have -%2% firepower when engaging a weaker unit."); text = replaceTextArgs(text, [CO_JOEY.superPowerCostReduction * 100, CO_JOEY.superPowerOffBonus, CO_JOEY.superPowerOffMalus, CO_JOEY.superPowerBaseOffBonus, CO_JOEY.superPowerDefBonus]); return text; }; this.getSuperPowerName = function(co) { return qsTr("Tempestuous Technique"); }; this.getPowerSentences = function(co) { return [qsTr("I feel a bit dirty for doing this..."), qsTr("I gave you a chance, but you didn't want it."), qsTr("You gotta live life on the edge!"), qsTr("You were never that good."), qsTr("You're going to be feeling edgy about this..."), qsTr("C'mon, give the little guys a chance!"), qsTr("What's a little risk taking going to hurt?")]; }; this.getVictorySentences = function(co) { return [qsTr("Heh, good game."), qsTr("Power isn't everything, y'know."), qsTr("Big risk, big reward!")]; }; this.getDefeatSentences = function(co) { return [qsTr("This was too risky..."), qsTr("I thought my risk was calculated, but man I'm bad at math!")]; }; this.getName = function() { return qsTr("Joey"); }; } Constructor.prototype = CO; var CO_JOEY = new Constructor();
411
0.799087
1
0.799087
game-dev
MEDIA
0.995822
game-dev
0.968885
1
0.968885
lo-cafe/winston
1,531
winston/extensions/ViewModifiers/Interpolator.swift
// // Interpolator.swift // winston // // Created by Igor Marcossi on 29/06/23. // import Foundation import SwiftUI func interpolatorBuilder(_ range1: [CGFloat], value: CGFloat) -> ((_ range2: [CGFloat], _ extrapolate: Bool) -> CGFloat) { func interpolate (_ range2: [CGFloat], _ extrapolate: Bool) -> CGFloat { let min1 = range1[0] let max1 = range1[1] let min2 = range2[0] let max2 = range2[1] if (extrapolate) { // Check if value is outside the range1 limits if value < min1 { let extrapolation = (value - min1) / (min1 - max1) // Decrease interpolation speed when within 25% of extrapolation limits let interpolationFactor = max(0, 1 + extrapolation / 4) return interpolationFactor * (min2 - max2) + max2 } else if value > max1 { let extrapolation = (value - max1) / (min1 - max1) // Decrease interpolation speed when within 25% of extrapolation limits let interpolationFactor = max(0, 1 - extrapolation / 4) return interpolationFactor * (max2 - min2) + min2 } } // If value is within range1 limits, just return the interpolated value return max( min(min2, max2), min( max(min2, max2), (value - min1) * (max2 - min2) / (max1 - min1) + min2 ) ) } return interpolate }
411
0.813342
1
0.813342
game-dev
MEDIA
0.879382
game-dev
0.883009
1
0.883009
atlassian-labs/atlaspack
1,998
crates/atlaspack_plugin_transformer_raw/src/raw_transformer.rs
use anyhow::Error; use async_trait::async_trait; use atlaspack_core::plugin::{PluginContext, TransformerPlugin}; use atlaspack_core::plugin::{TransformContext, TransformResult}; use atlaspack_core::types::{Asset, BundleBehavior}; #[derive(Debug)] pub struct AtlaspackRawTransformerPlugin {} impl AtlaspackRawTransformerPlugin { pub fn new(_ctx: &PluginContext) -> Self { AtlaspackRawTransformerPlugin {} } } #[async_trait] impl TransformerPlugin for AtlaspackRawTransformerPlugin { async fn transform( &self, _context: TransformContext, asset: Asset, ) -> Result<TransformResult, Error> { let mut asset = asset.clone(); asset.bundle_behavior = Some(BundleBehavior::Isolated); Ok(TransformResult { asset, ..Default::default() }) } } #[cfg(test)] mod tests { use std::{path::PathBuf, sync::Arc}; use atlaspack_core::{ config_loader::ConfigLoader, plugin::{PluginLogger, PluginOptions}, }; use atlaspack_filesystem::in_memory_file_system::InMemoryFileSystem; use super::*; #[tokio::test(flavor = "multi_thread")] async fn returns_raw_asset() { let file_system = Arc::new(InMemoryFileSystem::default()); let plugin = AtlaspackRawTransformerPlugin::new(&PluginContext { config: Arc::new(ConfigLoader { fs: file_system.clone(), project_root: PathBuf::default(), search_path: PathBuf::default(), }), file_system, logger: PluginLogger::default(), options: Arc::new(PluginOptions::default()), }); let asset = Asset::default(); assert_ne!(asset.bundle_behavior, Some(BundleBehavior::Isolated)); let mut asset = asset; asset.bundle_behavior = Some(BundleBehavior::Isolated); let context = TransformContext::default(); assert_eq!( plugin .transform(context, asset.clone()) .await .map_err(|e| e.to_string()), Ok(TransformResult { asset, ..Default::default() }) ); } }
411
0.856169
1
0.856169
game-dev
MEDIA
0.62277
game-dev
0.668964
1
0.668964
FeatureIDE/FeatureIDE
40,239
plugins/de.ovgu.featureide.examples/featureide_examples/TankWar-Antenna/src/DrawPanel.java
import java.awt.Color; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Toolkit; import java.awt.event.*; import java.awt.geom.AffineTransform; import java.awt.image.*; import javax.swing.*; import javax.imageio.*; import java.io.*; public class DrawPanel extends JPanel implements KeyListener, MouseListener, MouseMotionListener{ /** * */ private static final long serialVersionUID = 1L; BufferedImage buffer; BufferedImage rocketFire = null; Schuss sch; int timeCounter = 0; Entity player_1; Entity player_2; Entity current_Player; Entity other_Player; LoadSave ls = new LoadSave(); Environment env[]; PowerUp powerUps[]; int timecount = 0; int amountEnv; public static int w; public static int h; public static int[] powerUp_Pic = new int[9]; public static int kaliber = 5; private Image img_bg; private ImageIcon ii_bg; Graphics2D rkt; public DrawPanel(int wth, int hei, int ae){ amountEnv = ae; w = wth; h = hei; setIgnoreRepaint(true); addKeyListener(this); addMouseListener(this); addMouseMotionListener(this); setFocusable(true); // BufferedImage backGr_Img; } public void initialize(){ buffer = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB); //#if (Black_P1) //@ player_1 = new Entity(100,100, "imgs/Tank_Black.gif", "SP1"); //#elif (Red_P1) //@ player_1 = new Entity(100,100, "imgs/Tank_Red.gif", "SP1"); //#elif (Red_Tier1_P1) //@ player_1 = new Entity(100,100, "imgs/Tier1rot.gif", "SP1"); //#elif (Yellow_Tier1_P1) player_1 = new Entity(100,100, "imgs/Tier1gelb.gif", "SP1"); //#elif (Blue_Tier2_P1) //@ player_1 = new Entity(100,100, "imgs/Tier2blau.gif", "SP1"); //#elif (Green_Tier2_P1) //@ player_1 = new Entity(100,100, "imgs/Tier2gruen.gif", "SP1"); //#endif //#if (Black_P2) //@ player_2 = new Entity(200,100, "imgs/Tank_Black.gif", "SP2"); //#elif (Red_P2) //@ player_2 = new Entity(200,100, "imgs/Tank_Red.gif", "SP2"); //#elif (Red_Tier1_P2) //@ player_2 = new Entity(200,100, "imgs/Tier1rot.gif", "SP2"); //#elif (Yellow_Tier1_P2) //@ player_2 = new Entity(200,100, "imgs/Tier1gelb.gif", "SP2"); //#elif (Blue_Tier2_P2) //@ player_2 = new Entity(200,100, "imgs/Tier2blau.gif", "SP2"); //#elif (Green_Tier2_P2) player_2 = new Entity(200,100, "imgs/Tier2gruen.gif", "SP2"); //#endif current_Player = player_1; other_Player = player_2; env = new Environment[amountEnv]; powerUps = new PowerUp[9]; for(int i=0;i<=amountEnv-1;i++){ //#if (Hinderniss_Set) //@ if (Math.random()>0.95) env[i] = new Environment("imgs/HindernisseBearbeitet/_b.GIF"); //@ else if (Math.random()>0.90)env[i] = new Environment("imgs/HindernisseBearbeitet/MauerDunkelrot_b.gif"); //@ else if (Math.random()>0.85)env[i] = new Environment("imgs/mauer_hoch.gif"); //@ else if (Math.random()>0.80)env[i] = new Environment("imgs/HindernisseBearbeitet/BaumStamm.gif"); //@ else if (Math.random()>0.75)env[i] = new Environment("imgs/HindernisseBearbeitet/BaumKlein.gif"); //@ else if (Math.random()>0.70)env[i] = new Environment("imgs/HindernisseBearbeitet/BaumKlein_b.GIF"); //@ else if (Math.random()>0.65)env[i] = new Environment("imgs/HindernisseBearbeitet/BaumStamm.gif"); //@ else if (Math.random()>0.60)env[i] = new Environment("imgs/HindernisseBearbeitet/BaumStamm_b.GIF"); //@ else if (Math.random()>0.55)env[i] = new Environment("imgs/HindernisseBearbeitet/MauerDunkelrot_b.gif"); //@ else if (Math.random()>0.50)env[i] = new Environment("imgs/HindernisseBearbeitet/MauerDunkelrot.gif"); //@ else if (Math.random()>0.45)env[i] = new Environment("imgs/HindernisseBearbeitet/MauerDunkelrot_b.GIF"); //@ else if (Math.random()>0.40)env[i] = new Environment("imgs/HindernisseBearbeitet/MauerGrauKurz.gif"); //@ else if (Math.random()>0.35)env[i] = new Environment("imgs/HindernisseBearbeitet/MauerGrauKurz_b.GIF"); //@ else if (Math.random()>0.30)env[i] = new Environment("imgs/HindernisseBearbeitet/MauerGrauKurzDick.gif"); //@ else if (Math.random()>0.25)env[i] = new Environment("imgs/HindernisseBearbeitet/MauerGrauKurzDick_b.GIF"); //@ else if (Math.random()>0.20)env[i] = new Environment("imgs/Haus_vonOben.gif"); //@ else if (Math.random()>0.15)env[i] = new Environment("imgs/HindernisseBearbeitet/MauerGrauLangDick.gif"); //@ else if (Math.random()>0.10)env[i] = new Environment("imgs/HindernisseBearbeitet/MauerGrauLangDick_b.GIF"); //@ else if (Math.random()>0.05)env[i] = new Environment("imgs/HindernisseBearbeitet/MauerRot.gif"); //@ else env[i] = new Environment("imgs/Haus_vonOben_b.GIF"); //@ //} //#else if (Math.random()>0.75)env[i] = new Environment("imgs/HindernisseBearbeitet/Pfuetze1.gif.gif"); else if (Math.random()>0.50)env[i] = new Environment("imgs/HindernisseBearbeitet/PfuetzeGross.gif"); else if (Math.random()>0.25)env[i] = new Environment("imgs/HindernisseBearbeitet/PfuetzeKlein.gif"); else env[i] = new Environment("imgs/HindernisseBearbeitet/PfuetzeMittel.gif"); //#endif env[i].setX((int)(150 + Math.random()*(w-200))); env[i].setY((int)(50 + Math.random()*(h-200))); } int i = 0; while (true) { //#if (Flower) if (i == 9) break; powerUps[i] = new PowerUp(i, "imgs/PowerUpsBearbeitet/PowerUpBlume.gif"); i++; //#endif //#if (Blue_Flower) if (i == 9) break; powerUps[i] = new PowerUp(i, "imgs/PowerUpsBearbeitet/PowerUpBlumeBlau.gif"); i++; //#endif //#if (Copy) if (i == 9) break; powerUps[i] = new PowerUp(i, "imgs/PowerUpsBearbeitet/PowerUpCopy.gif"); i++; //#endif //#if (Fire) //@ if (i == 9) break; //@ powerUps[i] = new PowerUp(i, "imgs/PowerUpsBearbeitet/PowerUpFeuer.gif"); //@ i++; //#endif //#if (Light_Bulb_Round) if (i == 9) break; powerUps[i] = new PowerUp(i, "imgs/PowerUpsBearbeitet/PowerUpGluehbirneRund.gif"); i++; //#endif //#if (Green) //@ if (i == 9) break; //@ powerUps[i] = new PowerUp(i, "imgs/PowerUpsBearbeitet/PowerUpGruen.gif"); //@ i++; //#endif //#if (Heart) //@ if (i == 9) break; //@ powerUps[i] = new PowerUp(i, "imgs/PowerUpsBearbeitet/PowerUpHerz.gif"); //@ i++; //#endif //#if (Circle) //@ if (i == 9) break; //@ powerUps[i] = new PowerUp(i, "imgs/PowerUpsBearbeitet/PowerUpKreis.gif"); //@ i++; //#endif //#if (Cow) //@ if (i == 9) break; //@ powerUps[i] = new PowerUp(i, "imgs/PowerUpsBearbeitet/PowerUpKuh.gif"); //@ i++; //#endif //#if (Light_Bulb) if (i == 9) break; powerUps[i] = new PowerUp(i, "imgs/PowerUpsBearbeitet/PowerUpLightbulb.gif"); i++; //#endif //#if (Octagonal) //@ if (i == 9) break; //@ powerUps[i] = new PowerUp(i, "imgs/PowerUpsBearbeitet/PowerUpOctagonal.gif"); //@ i++; //#endif //#if (Mushroom) if (i == 9) break; powerUps[i] = new PowerUp(i, "imgs/PowerUpsBearbeitet/PowerUpPilz.gif"); i++; //#endif //#if (Pumpkin_Pie) //@ if (i == 9) break; //@ powerUps[i] = new PowerUp(i, "imgs/PowerUpsBearbeitet/PowerUpPumpkinPie.gif"); //@ i++; //#endif //#if (Ring) if (i == 9) break; powerUps[i] = new PowerUp(i, "imgs/PowerUpsBearbeitet/PowerUpRing.gif"); i++; //#endif //#if (Ring_2) if (i == 9) break; powerUps[i] = new PowerUp(i, "imgs/PowerUpsBearbeitet/PowerUpRingeZwei.gif"); i++; //#endif //#if (Ring_Oval) if (i == 9) break; powerUps[i] = new PowerUp(i, "imgs/PowerUpsBearbeitet/PowerUpRingOval.gif"); i++; //#endif //#if (Ring_Oval_Small) if (i == 9) break; powerUps[i] = new PowerUp(i, "imgs/PowerUpsBearbeitet/PowerUpRingOvalKlein.gif"); i++; //#endif //#if (Sponge) //@ if (i == 9) break; //@ powerUps[i] = new PowerUp(i, "imgs/PowerUpsBearbeitet/PowerUpSchwamm.gif"); //@ i++; //#endif //#if (Spiral) //@ if (i == 9) break; //@ powerUps[i] = new PowerUp(i, "imgs/PowerUpsBearbeitet/PowerUpSpiral.gif"); //@ i++; //#endif //#if (Star_Oval) if (i == 9) break; powerUps[i] = new PowerUp(i, "imgs/PowerUpsBearbeitet/PowerUpSternOval.gif"); i++; //#endif //#if (Star_Oval_Small) if (i == 9) break; powerUps[i] = new PowerUp(i, "imgs/PowerUpsBearbeitet/PowerUpSternOvalKlein.gif"); i++; //#endif //#if (Star_Ring) if (i == 9) break; powerUps[i] = new PowerUp(i, "imgs/PowerUpsBearbeitet/PowerUpSternRing.gif"); i++; //#endif } //#if (Nr1) powerUps[0].setX(50 + (int)(Math.random()*(w-100))); powerUps[0].setY(50 + (int)(Math.random()*(h-150))); //#else //@ powerUps[0].setX(-100); //@ powerUps[0].setY(-100); //#endif //#if (Nr2) powerUps[1].setX(50 + (int)(Math.random()*(w-100))); powerUps[1].setY(50 + (int)(Math.random()*(h-150))); //#else //@ powerUps[1].setX(-100); //@ powerUps[1].setY(-100); //#endif //#if (Nr3) powerUps[2].setX(50 + (int)(Math.random()*(w-100))); powerUps[2].setY(50 + (int)(Math.random()*(h-150))); //#else //@ powerUps[2].setX(-100); //@ powerUps[2].setY(-100); //#endif //#if (Nr4) powerUps[3].setX(50 + (int)(Math.random()*(w-100))); powerUps[3].setY(50 + (int)(Math.random()*(h-150))); //#else //@ powerUps[3].setX(-100); //@ powerUps[3].setY(-100); //#endif //#if (Nr5) powerUps[4].setX(50 + (int)(Math.random()*(w-100))); powerUps[4].setY(50 + (int)(Math.random()*(h-150))); //#else //@ powerUps[4].setX(-100); //@ powerUps[4].setY(-100); //#endif //#if (Nr6) powerUps[5].setX(50 + (int)(Math.random()*(w-100))); powerUps[5].setY(50 + (int)(Math.random()*(h-150))); //#else //@ powerUps[5].setX(-100); //@ powerUps[5].setY(-100); //#endif //#if (Nr7) powerUps[6].setX(50 + (int)(Math.random()*(w-100))); powerUps[6].setY(50 + (int)(Math.random()*(h-150))); //#else //@ powerUps[6].setX(-100); //@ powerUps[6].setY(-100); //#endif //#if (Nr8) powerUps[7].setX(50 + (int)(Math.random()*(w-100))); powerUps[7].setY(50 + (int)(Math.random()*(h-150))); //#else //@ powerUps[7].setX(-100); //@ powerUps[7].setY(-100); //#endif } public void update(){ current_Player.move(); //#if (tar) //@ // bewegt den Rocket nach Q-Pressed //@ if (current_Player.isRocket()){ //@ sch.move(current_Player.getDegree()); //@ } //#endif } public void checkCollisions(){ if (current_Player.getBounds().intersects(other_Player.getBounds()) || current_Player.getBounds().intersects(0, h-50, w, 25) || current_Player.getBounds().intersects(0, 0, w, 25) || current_Player.getBounds().intersects(0, 0, 25, h) || current_Player.getBounds().intersects(w-35, 0, 30, h)){ current_Player.setCollision(true); if (timecount == 0) timecount = 50; } else current_Player.setCollision(false); } public void checkEnvCollisions(){ for(int i=0;i<amountEnv;i++){ //#if (Hinderniss_Set) //@ if (env[i].getBounds().intersects(current_Player.getBounds())){ //@ current_Player.setCollision(true); //@ if (timecount == 0) timecount = 50; //@ } //@ //} //#else if (env[i].getBounds().intersects(current_Player.getBounds())) current_Player.setSpeed(1); //else current_Player.setSpeed(2); //#endif } } public void checkPopupCollision(){ for(int i=0;i<8;i++){ if (powerUps[i].isAktiv() && current_Player.getBounds().intersects(powerUps[i].getX(), powerUps[i].getY(), 10, 10)){ powerUps[i].setAktiv(false); if (powerUps[i].getChange().equals("HP")) current_Player.setTp(current_Player.getTp()+powerUps[i].getChangeValue()); if (powerUps[i].getChange().equals("SP")) current_Player.setSpeed(powerUps[i].getChangeValue()); if (powerUps[i].getChange().equals("BP")) current_Player.setBp(current_Player.getBp()+powerUps[i].getChangeValue()); } } } public void drawBuffer(){ Graphics2D b = buffer.createGraphics(); // DrawPanel Graphics2D pl_b = buffer.createGraphics(); Graphics2D pl_c = buffer.createGraphics(); rkt = buffer.createGraphics(); AffineTransform rkt_aff = new AffineTransform(); Graphics2D envi[] = new Graphics2D[amountEnv]; AffineTransform enviTrans[] = new AffineTransform[amountEnv]; b.setColor(Color.BLACK); b.fillRect(0, 0, w, h); //#if (Default) //@ //#elif (Blue_White) //@ ii_bg = new ImageIcon("imgs/Hintergrund/HgBlauWeiss1.gif"); //@ img_bg = ii_bg.getImage(); //@ b.drawImage(img_bg, w, w, this); //#elif (Blue_White_Green) //@ ii_bg = new ImageIcon("imgs/Hintergrund/HgBlauWeissGruen.gif"); //@ img_bg = ii_bg.getImage(); //@ b.drawImage(img_bg, w, w, this); //#elif (Purple_White) //@ ii_bg = new ImageIcon("imgs/Hintergrund/HgLilaWeiss.gif"); //@ img_bg = ii_bg.getImage(); //@ b.drawImage(img_bg, w, w, this); //#elif (Glass) //@ ii_bg = new ImageIcon("imgs/Hintergrund/Hintergrundglass05.gif"); //@ img_bg = ii_bg.getImage(); //@ b.drawImage(img_bg, w, w, this); //#elif (Lava) //@ ii_bg = new ImageIcon("imgs/Hintergrund/Hintergrundlava01.gif"); //@ img_bg = ii_bg.getImage(); //@ b.drawImage(img_bg, w, w, this); //#elif (Limba) //@ ii_bg = new ImageIcon("imgs/Hintergrund/Hintergrundlimba.gif"); //@ img_bg = ii_bg.getImage(); //@ b.drawImage(img_bg, w, w, this); //#elif (Old) ii_bg = new ImageIcon("imgs/Hintergrund/Hintergrundoldpnt01.gif"); img_bg = ii_bg.getImage(); b.drawImage(img_bg, w, w, this); //#elif (Ov_Paper) //@ ii_bg = new ImageIcon("imgs/Hintergrund/Hintergrundov_paper.gif"); //@ img_bg = ii_bg.getImage(); //@ b.drawImage(img_bg, w, w, this); //#elif (Paper) //@ ii_bg = new ImageIcon("imgs/Hintergrund/Hintergrundpaper05.gif"); //@ img_bg = ii_bg.getImage(); //@ b.drawImage(img_bg, w, w, this); //#elif (Univ) //@ ii_bg = new ImageIcon("imgs/Hintergrund/Hintergrunduniv01.jpg"); //@ img_bg = ii_bg.getImage(); //@ b.drawImage(img_bg, w, w, this); //#elif (Water) //@ ii_bg = new ImageIcon("imgs/Hintergrund/Hintergrundwater01.jpg"); //@ img_bg = ii_bg.getImage(); //@ b.drawImage(img_bg, w, w, this); //#elif (Water_2) //@ ii_bg = new ImageIcon("imgs/Hintergrund/Hintergrundwater05.jpg"); //@ img_bg = ii_bg.getImage(); //@ b.drawImage(img_bg, w, w, this); //#endif b.setColor(Color.gray); b.fillRect(0, 0, w, 25); // oben b.fillRect(0, h-50, w, 25); // unten b.fillRect(0, 0, 25, h); // links b.fillRect(w-35, 0, 30, h); // rechts b.setColor(Color.WHITE); //rocket //#if (tar) //#if (Rectangle) //@ if (current_Player.isRocket()){ //@ rkt_aff.rotate(current_Player.getDegree(), sch.getX(), sch.getY()); //@ rkt.setTransform(rkt_aff); //@ System.out.println("Rok X:"+sch.getX()+" Rok Y:"+sch.getY()); //@ rkt.drawRect(sch.getX()+ current_Player.getWidth()/2, sch.getY() + current_Player.getHeight()/2, kaliber, kaliber);} // Rocket 4Eck //#endif //#if (Oval) //@ if (current_Player.isRocket()){ //@ b.drawOval(sch.getX()+ current_Player.getWidth()/2, sch.getY() + current_Player.getHeight()/2, kaliber, kaliber);} // Rocket Oval //#endif //#if (aa31) //@ if (current_Player.isRocket()){ //@ try { //@ rocketFire = ImageIO.read(new File("imgs/aa31.gif")); //@ rkt_aff.rotate(current_Player.getDegree(), sch.getX(), sch.getY()); //@ rkt.setTransform(rkt_aff); //@ rkt.drawImage(rocketFire, null, (int)sch.getX(), (int)sch.getY()); //@ //rkt.drawImage(rocketFire, null, (int)current_Player.getX(), (int)current_Player.getY()); //@ } catch (IOException e) { //@ } //@ } //#endif //#if (Portal) //@ if (current_Player.isRocket()){ //@ try { //@ rocketFire = ImageIO.read(new File("imgs/portal.gif")); //@ rkt_aff.rotate(current_Player.getDegree(), sch.getX(), sch.getY()); //@ rkt.setTransform(rkt_aff); //@ rkt.drawImage(rocketFire, null, sch.getX()+current_Player.getWidth()/2, sch.getY()+current_Player.getHeight()/2); //@ } catch (IOException e) { //@ } //@ } //#endif //#if (Nino) //@ if (current_Player.isRocket()){ //@ try { //@ rocketFire = ImageIO.read(new File("imgs/nino.gif")); //@ rkt_aff.rotate(current_Player.getDegree(), sch.getX(), sch.getY()); //@ rkt.setTransform(rkt_aff); //@ rkt.drawImage(rocketFire, null, sch.getX()+current_Player.getWidth()/2, sch.getY()+current_Player.getHeight()/2); //@ } catch (IOException e) { //@ } //@ } //#endif //#endif for(int i=0;i<=amountEnv-1;i++){ envi[i] = buffer.createGraphics(); enviTrans[i] = new AffineTransform(); envi[i].setTransform(enviTrans[i]); envi[i].drawImage(env[i].getImg(),env[i].getX(), env[i].getY(), this); } for(int i=0;i<8;i++){ if (powerUps[i].isAktiv()){ b.setColor(powerUps[i].getCol()); b.drawImage(powerUps[i].getImg(),powerUps[i].getX(), powerUps[i].getY(), this); } } b.setColor(Color.WHITE); b.drawString("BP: " + current_Player.getBp(), 10, 20); b.drawString("TP P1/P2: " + player_1.getTp() + " / " + player_2.getTp(), 100, 20); if (current_Player.getSch().getEnd_X() != 0 && current_Player.getSch().getEnd_Y() != 0) { b.setColor(Color.YELLOW); b.drawLine((int)current_Player.getSch().getStart_X(), (int)current_Player.getSch().getStart_Y(), (int)current_Player.getSch().getEnd_X(), (int)current_Player.getSch().getEnd_Y()); b.setColor(Color.WHITE); for (int i=0;i<current_Player.getSch().getArImg().length;i++){ if (current_Player.getSch().getArImg()[i] != null && current_Player.getSch().isIsActive()){ b.drawImage(current_Player.getSch().getArImg()[i],(int)current_Player.getSch().getEnd_X() - current_Player.getSch().getArImg()[i].getWidth(this)/2, (int)current_Player.getSch().getEnd_Y() - current_Player.getSch().getArImg()[i].getHeight(this)/2, (int)(current_Player.getSch().getArImg()[i].getWidth(this)*(current_Player.getSch().getSpeed()/150)), (int)(current_Player.getSch().getArImg()[i].getHeight(this)*(current_Player.getSch().getSpeed()/150)), this); if (timeCounter == 75){ System.out.println("----------------------><---------------------"); if (player_1.getBounds().intersects((int)current_Player.getSch().getEnd_X() - current_Player.getSch().getArImg()[i].getWidth(this)/2, (int)current_Player.getSch().getEnd_Y() - current_Player.getSch().getArImg()[i].getHeight(this)/2, (int)(current_Player.getSch().getArImg()[i].getWidth(this)*(current_Player.getSch().getSpeed()/150)), (int)(current_Player.getSch().getArImg()[i].getHeight(this)*(current_Player.getSch().getSpeed()/150)))){ player_1.setTp(player_1.getTp()-(int)current_Player.getSch().getSpeed()/4); System.out.println("----------------------> P1 <---------------------"); } if (player_2.getBounds().intersects((int)current_Player.getSch().getEnd_X() - current_Player.getSch().getArImg()[i].getWidth(this)/2, (int)current_Player.getSch().getEnd_Y() - current_Player.getSch().getArImg()[i].getHeight(this)/2, (int)(current_Player.getSch().getArImg()[i].getWidth(this)*(current_Player.getSch().getSpeed()/150)), (int)(current_Player.getSch().getArImg()[i].getHeight(this)*(current_Player.getSch().getSpeed()/150)))){ player_2.setTp(player_2.getTp()-(int)current_Player.getSch().getSpeed()/4); System.out.println("----------------------> P2 <---------------------"); } } } if (timeCounter >= 150){ timeCounter = 0; current_Player.getSch().setIsActive(false); current_Player.getSch().setEnd_X(0); current_Player.getSch().setEnd_Y(0); } if (current_Player.getSch().isIsActive()) timeCounter += 1; System.out.println("timecounter: " + timeCounter); } } if(player_1.getTp()<=0) b.drawString("SPIELER 2 HAT GEWONNEN !", w/2, h/2); if(player_2.getTp()<=0) b.drawString("SPIELER 1 HAT GEWONNEN !", w/2, h/2); current_Player.setStop(false); b.setColor(Color.red); AffineTransform a = new AffineTransform(); a.rotate(current_Player.getDegree(), current_Player.getX()+current_Player.getWidth()/2, current_Player.getY()+current_Player.getHeight()/2); ((Graphics2D) pl_b).setTransform(a); pl_b.drawImage(current_Player.getImg(),(int)current_Player.getX(), (int)current_Player.getY(), this); System.out.println("P1 X:"+(int)current_Player.getX()+" P1 Y:"+(int)current_Player.getY()); System.out.println("P1 W:"+current_Player.getWidth()+" P1 H:"+current_Player.getHeight()); AffineTransform a2 = new AffineTransform(); a2.rotate(other_Player.getDegree(), other_Player.getX()+other_Player.getWidth()/2, other_Player.getY()+other_Player.getHeight()/2); ((Graphics2D) pl_c).setTransform(a2); pl_c.drawImage(other_Player.getImg(),(int)other_Player.getX(), (int)other_Player.getY(), this); if (current_Player.isCollision() == true){ current_Player.setStop(true); if (timecount > 10) { b.setColor(Color.WHITE); b.drawString("C O L L I S I O N !", (int)w/2-50, (int)h/2); timecount--; } else{ timecount = 0; current_Player.setBp(0); current_Player.setX(300); current_Player.setY(100); current_Player.getSch().setEnd_X(1); current_Player.getSch().setEnd_Y(1); current_Player.getSch().setStart_X(1); current_Player.getSch().setStart_Y(1); } b.dispose(); } } public void checkRocketCollision(){ if (current_Player.isRocket()){ if (current_Player==player_1){ if(sch.getBounds().intersects(player_2.getBounds())){ player_2.setTp(player_2.getTp()-25); current_Player.setRocket(false); } } else if (current_Player==player_2){ if(sch.getBounds().intersects(player_1.getBounds())){ player_1.setTp(player_1.getTp()-25); current_Player.setRocket(false); } } if(sch.getBounds().intersects(0, h-50, w, 25) || sch.getBounds().intersects(0, 0, w, 25) || sch.getBounds().intersects(0, 0, 25, h) || sch.getBounds().intersects(w-35, 0, 30, h)){ current_Player.setRocket(false); } } } public void drawScreen(){ Graphics2D g = (Graphics2D)this.getGraphics(); g.drawImage(buffer, 0, 0, this); Toolkit.getDefaultToolkit().sync(); g.dispose(); } public void staga(){ initialize(); while(true){ try{ update(); checkCollisions(); checkPopupCollision(); checkEnvCollisions(); checkRocketCollision(); drawBuffer(); drawScreen(); Thread.sleep(15); } catch(Exception e){ e.printStackTrace(); } } } // Bewegung - Normal private void changepl() { //#if (mov_0) current_Player.setBp(250); current_Player.getSch().setStart_X(0); current_Player.getSch().setStart_Y(0); current_Player.getSch().setEnd_X(0); current_Player.getSch().setEnd_Y(0); current_Player.getSch().setterStart_time(0); current_Player.getSch().setterEnd_time(0); if (current_Player == player_1){ current_Player = player_2; other_Player = player_1; } else{ current_Player = player_1; other_Player = player_2; } //#endif //#if (mov_1) //@ current_Player.setBp(0); //@ current_Player.getSch().setStart_X(0); //@ current_Player.getSch().setStart_Y(0); //@ current_Player.getSch().setEnd_X(0); //@ current_Player.getSch().setEnd_Y(0); //@ current_Player.getSch().setterStart_time(0); //@ current_Player.getSch().setterEnd_time(0); //@ current_Player.setLoad(0); //@ if (current_Player == player_1){ //@ current_Player = player_2; //@ other_Player = player_1; //@ } //@ else{ //@ current_Player = player_1; //@ other_Player = player_2; //@ } //#endif //#if (mov_2) //@ current_Player.setBp(250); //@ current_Player.getSch().setStart_X(0); //@ current_Player.getSch().setStart_Y(0); //@ current_Player.getSch().setEnd_X(0); //@ current_Player.getSch().setEnd_Y(0); //@ current_Player.getSch().setterStart_time(0); //@ current_Player.getSch().setterEnd_time(0); //@ if (current_Player == player_1){ //@ current_Player = player_2; //@ other_Player = player_1; //@ } //@ else{ //@ current_Player = player_1; //@ other_Player = player_2; //@ } //#elif (mov_3) //@ current_Player.setBp(0); //@ current_Player.getSch().setStart_X(0); //@ current_Player.getSch().setStart_Y(0); //@ current_Player.getSch().setEnd_X(0); //@ current_Player.getSch().setEnd_Y(0); //@ current_Player.getSch().setterStart_time(0); //@ current_Player.getSch().setterEnd_time(0); //@ current_Player.setLoad(0); //@ if (current_Player == player_1){ //@ current_Player = player_2; //@ other_Player = player_1; //@ } //@ else{ //@ current_Player = player_1; //@ other_Player = player_2; //@ } //#elif (mov_4) //@ current_Player.setBp(0); //@ current_Player.getSch().setStart_X(0); //@ current_Player.getSch().setStart_Y(0); //@ current_Player.getSch().setEnd_X(0); //@ current_Player.getSch().setEnd_Y(0); //@ current_Player.getSch().setterStart_time(0); //@ current_Player.getSch().setterEnd_time(0); //@ current_Player.setLoad(0); //@ if (current_Player == player_1){ //@ current_Player = player_2; //@ other_Player = player_1; //@ } //@ else{ //@ current_Player = player_1; //@ other_Player = player_2; //@ } //#endif } public void keyPressed(KeyEvent e) { //#if (mov_0) int key = e.getKeyCode(); if (key == KeyEvent.VK_LEFT){ current_Player.setLeft(true); } if (key == KeyEvent.VK_RIGHT){ current_Player.setRight(true); } if (key == KeyEvent.VK_DOWN) current_Player.setDown(true); if (key == KeyEvent.VK_UP) current_Player.setUp(true); if (key == KeyEvent.VK_SHIFT) current_Player.setSpeed(3); if (key == KeyEvent.VK_ENTER) if (current_Player.getSch().isIsActive()==false) changepl(); if (key == KeyEvent.VK_F1) ls.createNewPlayer(); //#if (tar) //@ if (key == KeyEvent.VK_Q){ //@ // current_Player.setRocket(true); //@ // sch = new Schuss((int)current_Player.getX(),(int)current_Player.getY()); //@ // current_Player.setBp(0); //@ } //#endif //#elif (mov_1) //@ int key = e.getKeyCode(); //@ if (key == KeyEvent.VK_LEFT){ //@ current_Player.setLeft(true); //@ } //@ if (key == KeyEvent.VK_RIGHT){ //@ current_Player.setRight(true); //@ } //@ if (key == KeyEvent.VK_SPACE && current_Player.getLoad() < 2){ //@ current_Player.setBp(current_Player.getBp()+5); //@ current_Player.setLoad(1); //@ } //@ if (key == KeyEvent.VK_DOWN) current_Player.setDown(true); //@ if (key == KeyEvent.VK_UP) current_Player.setUp(true); //@ if (key == KeyEvent.VK_SHIFT) current_Player.setSpeed(3); //@ if (key == KeyEvent.VK_ENTER) if (current_Player.getSch().isIsActive()==false) changepl(); //@ if (key == KeyEvent.VK_F1) ls.createNewPlayer(); //#elif (mov_2) //@ int key = e.getKeyCode(); //@ if (key == KeyEvent.VK_LEFT) current_Player.setLeft(true); //@ if (key == KeyEvent.VK_RIGHT) current_Player.setRight(true); //@ if (key == KeyEvent.VK_DOWN) current_Player.setDown(true); //@ if (key == KeyEvent.VK_UP) current_Player.setUp(true); //@ if (key == KeyEvent.VK_SHIFT) current_Player.setSpeed(3); //@ if (key == KeyEvent.VK_ENTER) if (current_Player.getSch().isIsActive()==false) changepl(); //@ if (key == KeyEvent.VK_F1) ls.createNewPlayer(); //#elif (mov_3) //@ int key = e.getKeyCode(); //@ if (key == KeyEvent.VK_LEFT){ //@ current_Player.setLeft(true); //@ } //@ if (key == KeyEvent.VK_RIGHT){ //@ current_Player.setRight(true); //@ } //@ if (key == KeyEvent.VK_SPACE){ //@ current_Player.setBp(current_Player.getBp()+5); //@ current_Player.setLoad(1); //@ //current_Player.setSpeed(5); //@ } //@ if (key == KeyEvent.VK_DOWN) current_Player.setDown(true); //@ if (key == KeyEvent.VK_UP) current_Player.setUp(true); //@ if (key == KeyEvent.VK_SHIFT) current_Player.setSpeed(3); //@ if (key == KeyEvent.VK_ENTER) if (current_Player.getSch().isIsActive()==false) changepl(); //@ if (key == KeyEvent.VK_F1) ls.createNewPlayer(); //#elif (mov_4) //@ int key = e.getKeyCode(); //@ if (key == KeyEvent.VK_LEFT){ //@ current_Player.setLeft(true); //@ } //@ if (key == KeyEvent.VK_RIGHT){ //@ current_Player.setRight(true); //@ } //@ if (key == KeyEvent.VK_SPACE && current_Player.getLoad() < 2){ //@ current_Player.setBp(current_Player.getBp()+5); //@ current_Player.setLoad(1); //@ } //@ if (key == KeyEvent.VK_DOWN) current_Player.setDown(true); //@ if (key == KeyEvent.VK_UP) current_Player.setUp(true); //@ if (key == KeyEvent.VK_SHIFT) current_Player.setSpeed(3); //@ if (key == KeyEvent.VK_ENTER) if (current_Player.getSch().isIsActive()==false) changepl(); //@ if (key == KeyEvent.VK_F1) ls.createNewPlayer(); //#endif // neu beginn if (key == KeyEvent.VK_Q){ //#if (tar) //@ current_Player.setRocket(true); //@ sch = new Schuss((int)current_Player.getX(),(int)current_Player.getY()); //@ current_Player.setBp(0); //#endif } // neu ende } public void keyReleased(KeyEvent e) { //#if (mov_0) int key = e.getKeyCode(); if (key == KeyEvent.VK_LEFT){ current_Player.setLeft(false); } if (key == KeyEvent.VK_RIGHT){ current_Player.setRight(false); } if (key == KeyEvent.VK_DOWN) current_Player.setDown(false); if (key == KeyEvent.VK_UP) current_Player.setUp(false); if (key == KeyEvent.VK_SHIFT) current_Player.setSpeed(2); //#endif //#if (mov_1) //@ int key = e.getKeyCode(); //@ if (key == KeyEvent.VK_SPACE && current_Player.getLoad()==1) current_Player.setLoad(2); //@ if (key == KeyEvent.VK_LEFT) current_Player.setLeft(false); //@ if (key == KeyEvent.VK_RIGHT) current_Player.setRight(false); //@ if (key == KeyEvent.VK_DOWN) current_Player.setDown(false); //@ if (key == KeyEvent.VK_UP) current_Player.setUp(false); //@ if (key == KeyEvent.VK_SHIFT) current_Player.setSpeed(2); //#endif //#if (mov_2) //@ int key = e.getKeyCode(); //@ if (key == KeyEvent.VK_LEFT) current_Player.setLeft(false); //@ if (key == KeyEvent.VK_RIGHT) current_Player.setRight(false); //@ if (key == KeyEvent.VK_DOWN) current_Player.setDown(false); //@ if (key == KeyEvent.VK_UP) current_Player.setUp(false); //@ if (key == KeyEvent.VK_SHIFT) current_Player.setSpeed(2); //#endif //#if (mov_3) //@ int key = e.getKeyCode(); //@ if (key == KeyEvent.VK_SPACE && current_Player.getLoad()==1){current_Player.setLoad(2);} //@ if (key == KeyEvent.VK_LEFT) current_Player.setLeft(false); //@ if (key == KeyEvent.VK_RIGHT) current_Player.setRight(false); //@ if (key == KeyEvent.VK_DOWN) current_Player.setDown(false); //@ if (key == KeyEvent.VK_UP) current_Player.setUp(false); //@ if (key == KeyEvent.VK_SHIFT) current_Player.setSpeed(2); //#endif //#if (mov_4) //@ int key = e.getKeyCode(); //@ if (key == KeyEvent.VK_SPACE && current_Player.getLoad()==1) current_Player.setLoad(2); //@ if (key == KeyEvent.VK_LEFT) current_Player.setLeft(false); //@ if (key == KeyEvent.VK_RIGHT) current_Player.setRight(false); //@ if (key == KeyEvent.VK_DOWN) current_Player.setDown(false); //@ if (key == KeyEvent.VK_UP) current_Player.setUp(false); //@ if (key == KeyEvent.VK_SHIFT) current_Player.setSpeed(2); //#endif } public void keyTyped(KeyEvent e) { //#if (mov_0) // throw new UnsupportedOperationException("Not supported yet."); //#endif //#if (mov_1) //@ // throw new UnsupportedOperationException("Not supported yet."); //#endif //#if (mov_2) //@ // throw new UnsupportedOperationException("Not supported yet."); //#endif //#if (mov_3) //@ // throw new UnsupportedOperationException("Not supported yet."); //#endif //#if (mov_4) //@ // throw new UnsupportedOperationException("Not supported yet."); //#endif } public void mouseClicked(MouseEvent e) { // throw new UnsupportedOperationException("Not supported yet."); } public void mousePressed(MouseEvent e) { //#if (tar) //@ if (e.getButton() == 1){ //@ if (current_Player.isMo() && current_Player.getSch().getStart_X() == 0 && current_Player.getSch().isIsActive() == false){ //@ current_Player.getSch().setIsActive(true); //@ current_Player.getSch().setStart_X(e.getX()); //@ current_Player.getSch().setStart_Y(e.getY()); //@ current_Player.getSch().setStart_time(); //@ } //@ } //#else if (e.getButton() == 3){ TankInfo ti = new TankInfo(); System.out.println("ISIDE"); } //#endif } public void mouseReleased(MouseEvent e) { //#if (tar) //@ if (e.getButton() == 1){ //@ if (current_Player.getSch().isIsActive() && current_Player.getSch().getEnd_X() == 0){ //@ current_Player.getSch().setEnd_X(e.getX()); //@ current_Player.getSch().setEnd_Y(e.getY()); //@ current_Player.getSch().setEnd_time(); //@ System.out.println("X " + current_Player.getSch().getStart_X()); //@ System.out.println("Y " + current_Player.getSch().getStart_Y()); //@ } //@ } //#endif } public void mouseEntered(MouseEvent e) { // throw new UnsupportedOperationException("Not supported yet."); } public void mouseExited(MouseEvent e) { // throw new UnsupportedOperationException("Not supported yet."); } public void mouseDragged(MouseEvent e) { // throw new UnsupportedOperationException("Not supported yet."); } public void mouseMoved(MouseEvent e) { //#if (tar) //@ int mpx = e.getX(); //@ int mpy = e.getY(); //@ if (current_Player.getBounds().contains(mpx, mpy)) current_Player.setMo(true); //@ else current_Player.setMo(false); //#endif } }
411
0.669167
1
0.669167
game-dev
MEDIA
0.889606
game-dev
0.887926
1
0.887926
FPtje/DarkRP
2,962
entities/entities/drug/init.lua
AddCSLuaFile("cl_init.lua") AddCSLuaFile("shared.lua") include("shared.lua") local function UnDrugPlayer(ply) if not IsValid(ply) then return end ply.isDrugged = false local IDSteam = ply:SteamID64() timer.Remove(IDSteam .. "DruggedHealth") SendUserMessage("DrugEffects", ply, false) end hook.Add("PlayerDeath", "UndrugPlayers", function(ply) if ply.isDrugged then UnDrugPlayer(ply) end end) local function DrugPlayer(ply) if not IsValid(ply) then return end SendUserMessage("DrugEffects", ply, true) ply.isDrugged = true local IDSteam = ply:SteamID64() if not timer.Exists(IDSteam .. "DruggedHealth") then ply:SetHealth(ply:Health() + 100) timer.Create(IDSteam .. "DruggedHealth", 60 / (100 + 5), 100 + 5, function() if not IsValid(ply) then return end ply:SetHealth(ply:Health() - 1) if ply:Health() <= 0 then ply:Kill() end if timer.RepsLeft(IDSteam .. "DruggedHealth") == 0 then UnDrugPlayer(ply) end end) end end function ENT:Initialize() self:SetModel("models/props_lab/jar01a.mdl") DarkRP.ValidatedPhysicsInit(self, SOLID_VPHYSICS) self:SetMoveType(MOVETYPE_VPHYSICS) self:SetSolid(SOLID_VPHYSICS) self.CanUse = true local phys = self:GetPhysicsObject() if phys:IsValid() then phys:Wake() end self.damage = 10 self:Setprice(self:Getprice() or 100) self.SeizeReward = GAMEMODE.Config.pricemin or 35 end function ENT:OnTakeDamage(dmg) self:TakePhysicsDamage(dmg) self.damage = self.damage - dmg:GetDamage() if self.damage <= 0 then local effectdata = EffectData() effectdata:SetOrigin(self:GetPos()) effectdata:SetMagnitude(2) effectdata:SetScale(2) effectdata:SetRadius(3) util.Effect("Sparks", effectdata) self:Remove() end end function ENT:Use(activator, caller) if not self.CanUse then return end local Owner = self:Getowning_ent() if not IsValid(Owner) then return end local canUse, reason = hook.Call("canDarkRPUse", nil, activator, self, caller) if canUse == false then if reason then DarkRP.notify(activator, 1, 4, reason) end return end if activator ~= Owner then if not activator:canAfford(self:Getprice()) then return end DarkRP.payPlayer(activator, Owner, self:Getprice()) DarkRP.notify(activator, 0, 4, DarkRP.getPhrase("you_bought", DarkRP.getPhrase("drugs"), DarkRP.formatMoney(self:Getprice()), "")) DarkRP.notify(Owner, 0, 4, DarkRP.getPhrase("you_received_x", DarkRP.formatMoney(self:Getprice()), DarkRP.getPhrase("drugs"))) end DrugPlayer(caller) self.CanUse = false self:Remove() end function ENT:OnRemove() local ply = self:Getowning_ent() if not IsValid(ply) then return end ply.maxDrugs = ply.maxDrugs - 1 end
411
0.781584
1
0.781584
game-dev
MEDIA
0.892428
game-dev
0.906023
1
0.906023
protocolbuffers/protobuf
91,021
src/google/protobuf/repeated_ptr_field.h
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file or at // https://developers.google.com/open-source/licenses/bsd // Author: kenton@google.com (Kenton Varda) // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. // // RepeatedField and RepeatedPtrField are used by generated protocol message // classes to manipulate repeated fields. These classes are very similar to // STL's vector, but include a number of optimizations found to be useful // specifically in the case of Protocol Buffers. RepeatedPtrField is // particularly different from STL vector as it manages ownership of the // pointers that it contains. // // This header covers RepeatedPtrField. #ifndef GOOGLE_PROTOBUF_REPEATED_PTR_FIELD_H__ #define GOOGLE_PROTOBUF_REPEATED_PTR_FIELD_H__ #include <algorithm> #include <cstddef> #include <cstdint> #include <cstdlib> #include <iterator> #include <limits> #include <string> #include <type_traits> #include <utility> #include "absl/base/attributes.h" #include "absl/base/no_destructor.h" #include "absl/base/optimization.h" #include "absl/base/prefetch.h" #include "absl/functional/function_ref.h" #include "absl/log/absl_check.h" #include "absl/meta/type_traits.h" #include "google/protobuf/arena.h" #include "google/protobuf/arena_align.h" #include "google/protobuf/field_with_arena.h" #include "google/protobuf/internal_metadata_locator.h" #include "google/protobuf/internal_visibility.h" #include "google/protobuf/message_lite.h" #include "google/protobuf/port.h" // Must be included last. #include "google/protobuf/port_def.inc" #ifdef SWIG #error "You cannot SWIG proto headers" #endif namespace google { namespace protobuf { class DynamicMessage; class Message; class Reflection; class DynamicMessage; template <typename T> struct WeakRepeatedPtrField; namespace internal { class MergePartialFromCodedStreamHelper; class SwapFieldHelper; class MapFieldBase; class MapFieldBase; template <typename It> class RepeatedPtrIterator; template <typename It, typename VoidPtr> class RepeatedPtrOverPtrsIterator; template <typename T> class AllocatedRepeatedPtrFieldBackInsertIterator; // Swaps two non-overlapping blocks of memory of size `N` template <size_t N> inline void memswap(char* PROTOBUF_RESTRICT a, char* PROTOBUF_RESTRICT b) { // `PROTOBUF_RESTRICT` tells compiler that blocks do not overlapping which // allows it to generate optimized code for swap_ranges. std::swap_ranges(a, a + N, b); } // A trait that tells offset of `T::resolver_`. // // Do not use this struct - it exists for internal use only. template <typename T> struct InternalMetadataResolverOffsetHelper { #ifdef PROTOBUF_INTERNAL_REMOVE_ARENA_PTRS_REPEATED_PTR_FIELD static constexpr size_t value = offsetof(T, resolver_); #else static constexpr size_t value = offsetof(T, arena_); #endif }; // Copies the object in the arena. // Used in the slow path. Out-of-line for lower binary size cost. PROTOBUF_EXPORT MessageLite* CloneSlow(Arena* arena, const MessageLite& value); PROTOBUF_EXPORT std::string* CloneSlow(Arena* arena, const std::string& value); // A utility function for logging that doesn't need any template types. PROTOBUF_EXPORT void LogIndexOutOfBounds(int index, int size); // A utility function for logging that doesn't need any template types. Same as // LogIndexOutOfBounds, but aborts the program in all cases by logging to FATAL // instead of DFATAL. // TODO: Remove preserve_all and add no_return once experiment is // complete. PROTOBUF_PRESERVE_ALL PROTOBUF_EXPORT void LogIndexOutOfBoundsAndAbort( int index, int size); PROTOBUF_EXPORT inline void RuntimeAssertInBounds(int index, int size) { if constexpr (GetBoundsCheckMode() == BoundsCheckMode::kAbort) { if (ABSL_PREDICT_FALSE(index < 0 || index >= size)) { // "No merge" attribute used to improve debuggability by telling the // compiler not to merge these failure paths. Note that this is currently // best-effort in clang/llvm. PROTOBUF_NO_MERGE LogIndexOutOfBoundsAndAbort(index, size); } } ABSL_DCHECK_GE(index, 0); ABSL_DCHECK_LT(index, size); } // Defined further below. template <typename Type> class GenericTypeHandler; using ElementNewFn = void(Arena*, void*& ptr); // This is the common base class for RepeatedPtrFields. It deals only in void* // pointers. Users should not use this interface directly. // // The methods of this interface correspond to the methods of RepeatedPtrField, // but may have a template argument called TypeHandler. Its signature is: // class TypeHandler { // public: // using Type = MyType; // // static Type*(*)(Arena*) GetNewFunc(); // static Type*(*)(Arena*) GetNewFromPrototypeFunc(const Type* prototype); // static Arena* GetArena(Type* value); // // static Type* New(Arena* arena, Type&& value); // static void Delete(Type*, Arena* arena); // static void Clear(Type*); // // // Only needs to be implemented if SpaceUsedExcludingSelf() is called. // static int SpaceUsedLong(const Type&); // // static const Type& default_instance(); // }; class PROTOBUF_EXPORT RepeatedPtrFieldBase { template <typename TypeHandler> using Value = typename TypeHandler::Type; static constexpr int kSSOCapacity = 1; protected: // We use the same TypeHandler for all Message types to deduplicate generated // code. template <typename TypeHandler> using CommonHandler = typename std::conditional< std::is_base_of<MessageLite, Value<TypeHandler>>::value, GenericTypeHandler<MessageLite>, TypeHandler>::type; #ifdef PROTOBUF_INTERNAL_REMOVE_ARENA_PTRS_REPEATED_PTR_FIELD constexpr RepeatedPtrFieldBase() : tagged_rep_or_elem_(nullptr), current_size_(0) {} constexpr explicit RepeatedPtrFieldBase(InternalMetadataOffset offset) : tagged_rep_or_elem_(nullptr), current_size_(0), resolver_(offset) {} #else constexpr RepeatedPtrFieldBase() : tagged_rep_or_elem_(nullptr), current_size_(0), arena_(nullptr) {} explicit RepeatedPtrFieldBase(Arena* arena) : tagged_rep_or_elem_(nullptr), current_size_(0), arena_(arena) {} #endif RepeatedPtrFieldBase(const RepeatedPtrFieldBase&) = delete; RepeatedPtrFieldBase& operator=(const RepeatedPtrFieldBase&) = delete; ~RepeatedPtrFieldBase() { #ifndef NDEBUG // Try to trigger segfault / asan failure in non-opt builds if the arena // lifetime has ended before the destructor. Note that `GetArena()` is // not free, but this is debug-only. const Arena* arena = GetArena(); if (arena != nullptr) (void)arena->SpaceAllocated(); #endif } bool empty() const { return current_size_ == 0; } int size() const { return current_size_; } // Returns the size of the buffer with pointers to elements. // // Note: // // * prefer `SizeAtCapacity()` to `size() == Capacity()`; // * prefer `AllocatedSizeAtCapacity()` to `allocated_size() == Capacity()`. int Capacity() const { return using_sso() ? kSSOCapacity : rep()->capacity; } template <typename TypeHandler> const Value<TypeHandler>& at(int index) const { ABSL_CHECK_GE(index, 0); ABSL_CHECK_LT(index, current_size_); return *cast<TypeHandler>(element_at(index)); } template <typename TypeHandler> Value<TypeHandler>& at(int index) { ABSL_CHECK_GE(index, 0); ABSL_CHECK_LT(index, current_size_); return *cast<TypeHandler>(element_at(index)); } template <typename TypeHandler> Value<TypeHandler>* Mutable(int index) { RuntimeAssertInBounds(index, current_size_); return cast<TypeHandler>(element_at(index)); } template <typename TypeHandler> Value<TypeHandler>* Add(Arena* arena) { return cast<TypeHandler>(AddInternal(arena, TypeHandler::GetNewFunc())); } template <typename TypeHandler> void Add(Arena* arena, Value<TypeHandler>&& value) { if (ClearedCount() > 0) { *cast<TypeHandler>(element_at(ExchangeCurrentSize(current_size_ + 1))) = std::move(value); } else { AddInternal(arena, TypeHandler::GetNewWithMoveFunc(std::move(value))); } } // Must be called from destructor. // // Pre-condition: NeedsDestroy() returns true. template <typename TypeHandler> void Destroy() { ABSL_DCHECK(NeedsDestroy()); #ifdef PROTOBUF_INTERNAL_REMOVE_ARENA_PTRS_REPEATED_PTR_FIELD ABSL_DCHECK_EQ(GetArena(), nullptr); #else // TODO: arena check is redundant once all `RepeatedPtrField`s // with non-null arena are owned by the arena. if (ABSL_PREDICT_FALSE(GetArena() != nullptr)) return; #endif using H = CommonHandler<TypeHandler>; int n = allocated_size(); ABSL_DCHECK_LE(n, Capacity()); void** elems = elements(); for (int i = 0; i < n; i++) { if (i + 5 < n) { absl::PrefetchToLocalCacheNta(elems[i + 5]); } Delete<H>(elems[i], nullptr); } if (!using_sso()) { internal::SizedDelete(rep(), Capacity() * sizeof(elems[0]) + kRepHeaderSize); } } inline bool NeedsDestroy() const { // Either there is an allocated element in SSO buffer or there is an // allocated Rep. return tagged_rep_or_elem_ != nullptr; } // Pre-condition: NeedsDestroy() returns true. void DestroyProtos(); public: // The next few methods are public so that they can be called from generated // code when implicit weak fields are used, but they should never be called by // application code. template <typename TypeHandler> PROTOBUF_FUTURE_ADD_NODISCARD const Value<TypeHandler>& Get(int index) const { if constexpr (GetBoundsCheckMode() == BoundsCheckMode::kReturnDefault) { if (ABSL_PREDICT_FALSE(index < 0 || index >= current_size_)) { // `default_instance()` is not supported for MessageLite and Message. if constexpr (TypeHandler::has_default_instance()) { LogIndexOutOfBounds(index, current_size_); return TypeHandler::default_instance(); } } } // We refactor this to a separate function instead of inlining it so we // can measure the performance impact more easily. RuntimeAssertInBounds(index, current_size_); return *cast<TypeHandler>(element_at(index)); } // Creates and adds an element using the given prototype, without introducing // a link-time dependency on the concrete message type. // // Pre-condition: `prototype` must not be nullptr. template <typename TypeHandler> PROTOBUF_ALWAYS_INLINE Value<TypeHandler>* AddFromPrototype( Arena* arena, const Value<TypeHandler>* prototype) { using H = CommonHandler<TypeHandler>; Value<TypeHandler>* result = cast<TypeHandler>( AddInternal(arena, H::GetNewFromPrototypeFunc(prototype))); return result; } // Creates and adds an element using the given ClassData, without introducing // a link-time dependency on the concrete message type. This is generally // faster and should be preferred over the equivalent `AddFromPrototype()` if // the caller already has or can get the `ClassData`, and especially if // elements are added repeatedly. // // Pre-condition: `class_data` must not be nullptr. template <typename TypeHandler> PROTOBUF_ALWAYS_INLINE Value<TypeHandler>* AddFromClassData( Arena* arena, const ClassData* class_data) { using H = CommonHandler<TypeHandler>; Value<TypeHandler>* result = cast<TypeHandler>( AddInternal(arena, H::GetNewFromClassDataFunc(class_data))); return result; } template <typename TypeHandler> void Clear() { const int n = current_size_; ABSL_DCHECK_GE(n, 0); if (n > 0) { using H = CommonHandler<TypeHandler>; ClearNonEmpty<H>(); } } // Appends all message values from `from` to this instance. template <typename T> void MergeFrom(const RepeatedPtrFieldBase& from, Arena* arena) { static_assert(std::is_base_of<MessageLite, T>::value, ""); if constexpr (!std::is_base_of<Message, T>::value) { // For LITE objects we use the generic MergeFrom to save on binary size. return MergeFrom<MessageLite>(from, arena); } MergeFromConcreteMessage(from, arena, Arena::CopyConstruct<T>); } inline void InternalSwap(RepeatedPtrFieldBase* PROTOBUF_RESTRICT rhs) { ABSL_DCHECK(this != rhs); // Swap all fields except arena offset and arena pointer at once. internal::memswap< InternalMetadataResolverOffsetHelper<RepeatedPtrFieldBase>::value>( reinterpret_cast<char*>(this), reinterpret_cast<char*>(rhs)); } // Returns true if there are no preallocated elements in the array. PROTOBUF_FUTURE_ADD_NODISCARD bool PrepareForParse() { return allocated_size() == current_size_; } // Similar to `AddAllocated` but faster. // // Pre-condition: PrepareForParse() is true. void AddAllocatedForParse(void* value, Arena* arena) { ABSL_DCHECK(PrepareForParse()); if (ABSL_PREDICT_FALSE(SizeAtCapacity())) { *InternalExtend(1, arena) = value; ++rep()->allocated_size; } else { if (using_sso()) { tagged_rep_or_elem_ = value; } else { rep()->elements[current_size_] = value; ++rep()->allocated_size; } } ExchangeCurrentSize(current_size_ + 1); } protected: template <typename TypeHandler> void RemoveLast() { ABSL_DCHECK_GT(current_size_, 0); ExchangeCurrentSize(current_size_ - 1); using H = CommonHandler<TypeHandler>; H::Clear(cast<H>(element_at(current_size_))); } template <typename TypeHandler> void CopyFrom(const RepeatedPtrFieldBase& other, Arena* arena) { ABSL_DCHECK_EQ(arena, GetArena()); if (&other == this) return; Clear<TypeHandler>(); if (other.empty()) return; MergeFrom<typename TypeHandler::Type>(other, arena); } void CloseGap(int start, int num); void Reserve(int capacity, Arena* arena); template <typename TypeHandler> static inline Value<TypeHandler>* copy(const Value<TypeHandler>* value) { return cast<TypeHandler>(CloneSlow(nullptr, *value)); } // Used for constructing iterators. void* const* raw_data() const { return elements(); } void** raw_mutable_data() { return elements(); } template <typename TypeHandler> Value<TypeHandler>** mutable_data() { // TODO: Breaks C++ aliasing rules. We should probably remove this // method entirely. return reinterpret_cast<Value<TypeHandler>**>(raw_mutable_data()); } template <typename TypeHandler> const Value<TypeHandler>* const* data() const { // TODO: Breaks C++ aliasing rules. We should probably remove this // method entirely. return reinterpret_cast<const Value<TypeHandler>* const*>(raw_data()); } template <typename TypeHandler> PROTOBUF_NDEBUG_INLINE void Swap(Arena* arena, RepeatedPtrFieldBase* other, Arena* other_arena) { ABSL_DCHECK_EQ(arena, GetArena()); ABSL_DCHECK_EQ(other_arena, other->GetArena()); if (internal::CanUseInternalSwap(arena, other_arena)) { InternalSwap(other); } else { SwapFallback<TypeHandler>(arena, other, other_arena); } } void SwapElements(int index1, int index2) { using std::swap; // enable ADL with fallback swap(element_at(index1), element_at(index2)); } template <typename TypeHandler> PROTOBUF_NOINLINE size_t SpaceUsedExcludingSelfLong() const { size_t allocated_bytes = using_sso() ? 0 : static_cast<size_t>(Capacity()) * sizeof(void*) + kRepHeaderSize; const int n = allocated_size(); void* const* elems = elements(); for (int i = 0; i < n; ++i) { allocated_bytes += TypeHandler::SpaceUsedLong(*cast<TypeHandler>(elems[i])); } return allocated_bytes; } // Advanced memory management -------------------------------------- // Like Add(), but if there are no cleared objects to use, returns nullptr. template <typename TypeHandler> Value<TypeHandler>* AddFromCleared() { if (current_size_ < allocated_size()) { return cast<TypeHandler>( element_at(ExchangeCurrentSize(current_size_ + 1))); } else { return nullptr; } } template <typename TypeHandler> void AddAllocated(Arena* arena, Value<TypeHandler>* value) { ABSL_DCHECK_EQ(arena, GetArena()); ABSL_DCHECK_NE(value, nullptr); Arena* element_arena = TypeHandler::GetArena(value); if (arena != element_arena || AllocatedSizeAtCapacity()) { AddAllocatedSlowWithCopy<TypeHandler>(value, element_arena, arena); return; } // Fast path: underlying arena representation (tagged pointer) is equal to // our arena pointer, and we can add to array without resizing it (at // least one slot that is not allocated). void** elems = elements(); if (current_size_ < allocated_size()) { // Make space at [current] by moving first allocated element to end of // allocated list. elems[allocated_size()] = elems[current_size_]; } elems[ExchangeCurrentSize(current_size_ + 1)] = value; if (!using_sso()) ++rep()->allocated_size; } template <typename TypeHandler> void UnsafeArenaAddAllocated(Arena* arena, Value<TypeHandler>* value) { ABSL_DCHECK_EQ(arena, GetArena()); ABSL_DCHECK_NE(value, nullptr); // Make room for the new pointer. if (SizeAtCapacity()) { // The array is completely full with no cleared objects, so grow it. InternalExtend(1, arena); ++rep()->allocated_size; } else if (AllocatedSizeAtCapacity()) { // There is no more space in the pointer array because it contains some // cleared objects awaiting reuse. We don't want to grow the array in // this case because otherwise a loop calling AddAllocated() followed by // Clear() would leak memory. using H = CommonHandler<TypeHandler>; Delete<H>(element_at(current_size_), arena); } else if (current_size_ < allocated_size()) { // We have some cleared objects. We don't care about their order, so we // can just move the first one to the end to make space. element_at(allocated_size()) = element_at(current_size_); ++rep()->allocated_size; } else { // There are no cleared objects. if (!using_sso()) ++rep()->allocated_size; } element_at(ExchangeCurrentSize(current_size_ + 1)) = value; } template <typename TypeHandler> PROTOBUF_FUTURE_ADD_NODISCARD Value<TypeHandler>* ReleaseLast(Arena* arena) { ABSL_DCHECK_EQ(arena, GetArena()); Value<TypeHandler>* result = UnsafeArenaReleaseLast<TypeHandler>(); // Now perform a copy if we're on an arena. if (internal::DebugHardenForceCopyInRelease()) { auto* new_result = copy<TypeHandler>(result); if (arena == nullptr) delete result; return new_result; } else { return (arena == nullptr) ? result : copy<TypeHandler>(result); } } // Releases and returns the last element, but does not do out-of-arena copy. // Instead, just returns the raw pointer to the contained element in the // arena. template <typename TypeHandler> Value<TypeHandler>* UnsafeArenaReleaseLast() { ABSL_DCHECK_GT(current_size_, 0); ExchangeCurrentSize(current_size_ - 1); auto* result = cast<TypeHandler>(element_at(current_size_)); if (using_sso()) { tagged_rep_or_elem_ = nullptr; } else { --rep()->allocated_size; if (current_size_ < allocated_size()) { // There are cleared elements on the end; replace the removed element // with the last allocated element. element_at(current_size_) = element_at(allocated_size()); } } return result; } int ClearedCount() const { return allocated_size() - current_size_; } // Slowpath handles all cases, copying if necessary. template <typename TypeHandler> PROTOBUF_NOINLINE void AddAllocatedSlowWithCopy( // Pass value_arena and my_arena to avoid duplicate virtual call (value) // or load (mine). Value<TypeHandler>* value, Arena* value_arena, Arena* my_arena) { using H = CommonHandler<TypeHandler>; ABSL_DCHECK_EQ(my_arena, GetArena()); ABSL_DCHECK_EQ(value_arena, TypeHandler::GetArena(value)); // Ensure that either the value is in the same arena, or if not, we do the // appropriate thing: Own() it (if it's on heap and we're in an arena) or // copy it to our arena/heap (otherwise). if (my_arena != nullptr && value_arena == nullptr) { my_arena->Own(value); } else if (my_arena != value_arena) { ABSL_DCHECK(value_arena != nullptr); value = cast<TypeHandler>(CloneSlow(my_arena, *value)); } UnsafeArenaAddAllocated<H>(my_arena, value); } template <typename TypeHandler> PROTOBUF_NOINLINE void SwapFallbackWithTemp(Arena* arena, RepeatedPtrFieldBase* other, Arena* other_arena, RepeatedPtrFieldBase& temp); template <typename TypeHandler> PROTOBUF_NOINLINE void SwapFallback(Arena* arena, RepeatedPtrFieldBase* other, Arena* other_arena); // Gets the Arena on which this RepeatedPtrField stores its elements. inline Arena* GetArena() const { #ifdef PROTOBUF_INTERNAL_REMOVE_ARENA_PTRS_REPEATED_PTR_FIELD return ResolveArena<&RepeatedPtrFieldBase::resolver_>(this); #else return arena_; #endif } #ifndef PROTOBUF_INTERNAL_REMOVE_ARENA_PTRS_REPEATED_PTR_FIELD static constexpr size_t InternalGetArenaOffset(internal::InternalVisibility) { return PROTOBUF_FIELD_OFFSET(RepeatedPtrFieldBase, arena_); } #endif // !PROTOBUF_INTERNAL_REMOVE_ARENA_PTRS_REPEATED_PTR_FIELD private: // Tests that need to access private methods. friend class RepeatedPtrFieldTest_UnsafeArenaAddAllocatedReleaseLastOnBaseField_Test; using InternalArenaConstructable_ = void; using DestructorSkippable_ = void; // FieldWithArena needs to call our protected internal metadata offset // constructors. friend class internal::FieldWithArena<RepeatedPtrFieldBase>; friend google::protobuf::Arena; template <typename T> friend class Arena::InternalHelper; // ExtensionSet stores repeated message extensions as // RepeatedPtrField<MessageLite>, but non-lite ExtensionSets need to implement // SpaceUsedLong(), and thus need to call SpaceUsedExcludingSelfLong() // reinterpreting MessageLite as Message. ExtensionSet also needs to make use // of AddFromCleared(), which is not part of the public interface. friend class ExtensionSet; // The MapFieldBase implementation needs to call protected methods directly, // reinterpreting pointers as being to Message instead of a specific Message // subclass. friend class MapFieldBase; friend struct MapFieldTestPeer; // The table-driven MergePartialFromCodedStream implementation needs to // operate on RepeatedPtrField<MessageLite>. friend class MergePartialFromCodedStreamHelper; friend class AccessorHelper; template <typename T> friend struct google::protobuf::WeakRepeatedPtrField; friend class internal::TcParser; // TODO: Remove this friend. // Expose offset of `resolver_` without exposing the member itself. Used to // optimize code size of `InternalSwap` method. template <typename T> friend struct InternalMetadataResolverOffsetHelper; // The reflection implementation needs to call protected methods directly, // reinterpreting pointers as being to Message instead of a specific Message // subclass. friend class google::protobuf::Reflection; friend class internal::SwapFieldHelper; friend class RustRepeatedMessageHelper; // Concrete Arena enabled copy function used to copy messages instances. // This follows the `Arena::CopyConstruct` signature so that the compiler // can have the inlined call into the out of line copy function(s) simply pass // the address of `Arena::CopyConstruct` 'as is'. using CopyFn = void* (*)(Arena*, const void*); struct Rep { // The size of the elements array, in number of elements. int capacity; // The number of elements allocated in the elements array (including cleared // elements). This is always >= current_size. int allocated_size; // Here we declare a huge array as a way of approximating C's "flexible // array member" feature without relying on undefined behavior. void* elements[(std::numeric_limits<int>::max() - 2 * sizeof(int)) / sizeof(void*)]; }; static constexpr size_t kRepHeaderSize = offsetof(Rep, elements); // Replaces current_size_ with new_size and returns the previous value of // current_size_. This function is intended to be the only place where // current_size_ is modified. inline int ExchangeCurrentSize(int new_size) { return std::exchange(current_size_, new_size); } inline bool SizeAtCapacity() const { // Harden invariant size() <= allocated_size() <= Capacity(). ABSL_DCHECK_LE(size(), allocated_size()); ABSL_DCHECK_LE(allocated_size(), Capacity()); return current_size_ == Capacity(); } inline bool AllocatedSizeAtCapacity() const { // Harden invariant size() <= allocated_size() <= Capacity(). ABSL_DCHECK_LE(size(), allocated_size()); ABSL_DCHECK_LE(allocated_size(), Capacity()); return allocated_size() == Capacity(); } void* const* elements() const { return using_sso() ? &tagged_rep_or_elem_ : +rep()->elements; } void** elements() { return using_sso() ? &tagged_rep_or_elem_ : +rep()->elements; } void*& element_at(int index) { if (using_sso()) { ABSL_DCHECK_EQ(index, 0); return tagged_rep_or_elem_; } return rep()->elements[index]; } const void* element_at(int index) const { return const_cast<RepeatedPtrFieldBase*>(this)->element_at(index); } int allocated_size() const { return using_sso() ? (tagged_rep_or_elem_ != nullptr ? 1 : 0) : rep()->allocated_size; } Rep* rep() { ABSL_DCHECK(!using_sso()); return reinterpret_cast<Rep*>( reinterpret_cast<uintptr_t>(tagged_rep_or_elem_) - 1); } const Rep* rep() const { return const_cast<RepeatedPtrFieldBase*>(this)->rep(); } bool using_sso() const { return (reinterpret_cast<uintptr_t>(tagged_rep_or_elem_) & 1) == 0; } template <typename TypeHandler> static inline Value<TypeHandler>* cast(void* element) { return reinterpret_cast<Value<TypeHandler>*>(element); } template <typename TypeHandler> static inline const Value<TypeHandler>* cast(const void* element) { return reinterpret_cast<const Value<TypeHandler>*>(element); } template <typename TypeHandler> static inline void Delete(void* obj, Arena* arena) { TypeHandler::Delete(cast<TypeHandler>(obj), arena); } // Out-of-line helper routine for Clear() once the inlined check has // determined the container is non-empty template <typename TypeHandler> PROTOBUF_NOINLINE void ClearNonEmpty() { const int n = current_size_; void* const* elems = elements(); int i = 0; ABSL_DCHECK_GT(n, 0); // do/while loop to avoid initial test because we know n > 0 do { TypeHandler::Clear(cast<TypeHandler>(elems[i++])); } while (i < n); ExchangeCurrentSize(0); } // Merges messages from `from` into available, cleared messages sitting in the // range `[size(), allocated_size())`. Returns the number of message merged // which is `ClearedCount(), from.size())`. // Note that this function does explicitly NOT update `current_size_`. // This function is out of line as it should be the slow path: this scenario // only happens when a caller constructs and fills a repeated field, then // shrinks it, and then merges additional messages into it. int MergeIntoClearedMessages(const RepeatedPtrFieldBase& from); // Appends all messages from `from` to this instance, using the // provided `copy_fn` copy function to copy existing messages. void MergeFromConcreteMessage(const RepeatedPtrFieldBase& from, Arena* arena, CopyFn copy_fn); // Extends capacity by at least |extend_amount|. Returns a pointer to the // next available element slot. // // Pre-condition: |extend_amount| must be > 0. void** InternalExtend(int extend_amount, Arena* arena); // Ensures that capacity is at least `n` elements. // Returns a pointer to the element directly beyond the last element. inline void** InternalReserve(int n, Arena* arena) { if (n <= Capacity()) { void** elements = using_sso() ? &tagged_rep_or_elem_ : rep()->elements; return elements + current_size_; } return InternalExtend(n - Capacity(), arena); } // Common implementation used by various Add* methods. `factory` is an object // used to construct a new element unless there are spare cleared elements // ready for reuse. Returns pointer to the new element. void* AddInternal(Arena* arena, absl::FunctionRef<ElementNewFn> factory); // A few notes on internal representation: // // We use an indirected approach, with struct Rep, to keep // sizeof(RepeatedPtrFieldBase) equivalent to what it was before arena support // was added; namely, 3 8-byte machine words on x86-64. An instance of Rep is // allocated only when the repeated field is non-empty, and it is a // dynamically-sized struct (the header is directly followed by elements[]). // We place arena_ and current_size_ directly in the object to avoid cache // misses due to the indirection, because these fields are checked frequently. // Placing all fields directly in the RepeatedPtrFieldBase instance would cost // significant performance for memory-sensitive workloads. void* tagged_rep_or_elem_; int current_size_; #ifdef PROTOBUF_INTERNAL_REMOVE_ARENA_PTRS_REPEATED_PTR_FIELD InternalMetadataResolver resolver_; #else const int arena_offset_placeholder_do_not_use_ = 0; Arena* arena_; #endif }; // Appends all message values from `from` to this instance using the abstract // message interface. This overload is used in places like reflection and // other locations where the underlying type is unavailable template <> void RepeatedPtrFieldBase::MergeFrom<MessageLite>( const RepeatedPtrFieldBase& from, Arena* arena); template <> inline void RepeatedPtrFieldBase::MergeFrom<Message>( const RepeatedPtrFieldBase& from, Arena* arena) { return MergeFrom<MessageLite>(from, arena); } // Appends all `std::string` values from `from` to this instance. template <> PROTOBUF_EXPORT void RepeatedPtrFieldBase::MergeFrom<std::string>( const RepeatedPtrFieldBase& from, Arena* arena); inline void* RepeatedPtrFieldBase::AddInternal( Arena* arena, absl::FunctionRef<ElementNewFn> factory) { ABSL_DCHECK_EQ(arena, GetArena()); if (tagged_rep_or_elem_ == nullptr) { ExchangeCurrentSize(1); factory(arena, tagged_rep_or_elem_); return tagged_rep_or_elem_; } absl::PrefetchToLocalCache(tagged_rep_or_elem_); if (using_sso()) { if (current_size_ == 0) { ExchangeCurrentSize(1); return tagged_rep_or_elem_; } void*& result = *InternalExtend(1, arena); factory(arena, result); Rep* r = rep(); r->allocated_size = 2; ExchangeCurrentSize(2); return result; } Rep* r = rep(); if (ABSL_PREDICT_FALSE(SizeAtCapacity())) { InternalExtend(1, arena); r = rep(); } else { if (ClearedCount() > 0) { return r->elements[ExchangeCurrentSize(current_size_ + 1)]; } } ++r->allocated_size; void*& result = r->elements[ExchangeCurrentSize(current_size_ + 1)]; factory(arena, result); return result; } #ifdef PROTOBUF_INTERNAL_REMOVE_ARENA_PTRS_REPEATED_PTR_FIELD // A container that holds a RepeatedPtrFieldBase and an arena pointer. This is // used when constructing `RepeatedPtrFieldBase`s on the arena, and in // `SwapFallback`. using RepeatedPtrFieldWithArenaBase = FieldWithArena<RepeatedPtrFieldBase>; template <> struct FieldArenaRep<RepeatedPtrFieldBase> { using Type = RepeatedPtrFieldWithArenaBase; static inline RepeatedPtrFieldBase* Get( RepeatedPtrFieldWithArenaBase* arena_rep) { return &arena_rep->field(); } }; template <> struct FieldArenaRep<const RepeatedPtrFieldBase> { using Type = const RepeatedPtrFieldWithArenaBase; static inline const RepeatedPtrFieldBase* Get( const RepeatedPtrFieldWithArenaBase* arena_rep) { return &arena_rep->field(); } }; #endif // PROTOBUF_INTERNAL_REMOVE_ARENA_PTRS_REPEATED_PTR_FIELD template <typename TypeHandler> PROTOBUF_NOINLINE void RepeatedPtrFieldBase::SwapFallbackWithTemp( Arena* arena, RepeatedPtrFieldBase* other, Arena* other_arena, RepeatedPtrFieldBase& temp) { ABSL_DCHECK(!internal::CanUseInternalSwap(GetArena(), other->GetArena())); ABSL_DCHECK_EQ(arena, GetArena()); ABSL_DCHECK_EQ(other_arena, other->GetArena()); // Copy semantics in this case. We try to improve efficiency by placing the // temporary on |other|'s arena so that messages are copied twice rather // than three times. if (!this->empty()) { temp.MergeFrom<typename TypeHandler::Type>(*this, other_arena); } this->CopyFrom<TypeHandler>(*other, arena); other->InternalSwap(&temp); } template <typename TypeHandler> PROTOBUF_NOINLINE void RepeatedPtrFieldBase::SwapFallback( Arena* arena, RepeatedPtrFieldBase* other, Arena* other_arena) { ABSL_DCHECK(!internal::CanUseInternalSwap(GetArena(), other->GetArena())); ABSL_DCHECK_EQ(arena, GetArena()); ABSL_DCHECK_EQ(other_arena, other->GetArena()); // Copy semantics in this case. We try to improve efficiency by placing the // temporary on |other|'s arena so that messages are copied twice rather // than three times. #ifdef PROTOBUF_INTERNAL_REMOVE_ARENA_PTRS_REPEATED_PTR_FIELD if (other_arena != nullptr) { // We can't call the destructor of the temp container since it allocates // memory from an arena, and the destructor of FieldWithArena expects to be // called only when arena is nullptr. absl::NoDestructor<RepeatedPtrFieldWithArenaBase> temp_container( other_arena); RepeatedPtrFieldBase& temp = temp_container->field(); SwapFallbackWithTemp<TypeHandler>(arena, other, other_arena, temp); return; } RepeatedPtrFieldBase temp; #else RepeatedPtrFieldBase temp(other_arena); #endif SwapFallbackWithTemp<TypeHandler>(arena, other, other_arena, temp); if (temp.NeedsDestroy()) { temp.Destroy<TypeHandler>(); } } PROTOBUF_EXPORT void InternalOutOfLineDeleteMessageLite(MessageLite* message); // Encapsulates the minimally required subset of T's properties in a // `RepeatedPtrField<T>` specialization so the type-agnostic // `RepeatedPtrFieldBase` could do its job without knowing T. // // This generic definition is for types derived from `MessageLite`. That is // statically asserted, but only where a non-conforming type would emit a // compile-time diagnostic that lacks proper guidance for fixing. Asserting // at the top level isn't possible, because some template argument types are not // yet fully defined at the instantiation point. // // Explicit specializations are provided for `std::string` and // `StringPieceField` further below. template <typename GenericType> class GenericTypeHandler { public: using Type = GenericType; // NOTE: Can't `static_assert(std::is_base_of_v<MessageLite, Type>)` here, // because the type is not yet fully defined at this point sometimes, so we // are forced to assert in every function that needs it. static constexpr auto GetNewFunc() { return [](Arena* arena, void*& ptr) { ptr = Arena::DefaultConstruct<Type>(arena); }; } static constexpr auto GetNewWithMoveFunc( Type&& from ABSL_ATTRIBUTE_LIFETIME_BOUND) { return [&from](Arena* arena, void*& ptr) { ptr = Arena::Create<Type>(arena, std::move(from)); }; } static constexpr auto GetNewFromPrototypeFunc( const Type* prototype ABSL_ATTRIBUTE_LIFETIME_BOUND) { ABSL_DCHECK(prototype != nullptr); return [prototype](Arena* arena, void*& ptr) { ptr = GetClassData(*prototype)->New(arena); }; } static constexpr auto GetNewFromClassDataFunc( const ClassData* class_data ABSL_ATTRIBUTE_LIFETIME_BOUND) { ABSL_DCHECK(class_data != nullptr); return [class_data](Arena* arena, void*& ptr) { ptr = class_data->New(arena); }; } static inline Arena* GetArena(Type* value) { return Arena::InternalGetArena(value); } static inline void Delete(Type* value, Arena* arena) { static_assert(std::is_base_of_v<MessageLite, Type>); if (arena != nullptr) return; // Using virtual destructor to reduce generated code size that would have // happened otherwise due to inlined `~Type()`. InternalOutOfLineDeleteMessageLite(value); } static inline void Clear(Type* value) { static_assert(std::is_base_of_v<MessageLite, Type>); value->Clear(); } static inline size_t SpaceUsedLong(const Type& value) { // NOTE: For `SpaceUsedLong()`, we do need `Message`, not `MessageLite`. static_assert(std::is_base_of_v<Message, Type>); return value.SpaceUsedLong(); } static const Type& default_instance() { static_assert(has_default_instance()); return *static_cast<const GenericType*>( MessageTraits<Type>::default_instance()); } static constexpr bool has_default_instance() { return !std::is_same_v<Type, Message> && !std::is_same_v<Type, MessageLite>; } }; template <> class GenericTypeHandler<std::string> { public: using Type = std::string; static constexpr auto GetNewFunc() { return [](Arena* arena, void*& ptr) { ptr = Arena::Create<Type>(arena); }; } static constexpr auto GetNewWithMoveFunc( Type&& from ABSL_ATTRIBUTE_LIFETIME_BOUND) { return [&from](Arena* arena, void*& ptr) { ptr = Arena::Create<Type>(arena, std::move(from)); }; } static constexpr auto GetNewFromPrototypeFunc(const Type* /*prototype*/) { return GetNewFunc(); } static inline Arena* GetArena(Type*) { return nullptr; } static inline void Delete(Type* value, Arena* arena) { if (arena == nullptr) { delete value; } } static inline void Clear(Type* value) { value->clear(); } static inline void Merge(const Type& from, Type* to) { *to = from; } static size_t SpaceUsedLong(const Type& value) { return sizeof(value) + StringSpaceUsedExcludingSelfLong(value); } static const Type& default_instance() { return GetEmptyStringAlreadyInited(); } static constexpr bool has_default_instance() { return true; } }; } // namespace internal // RepeatedPtrField is like RepeatedField, but used for repeated strings or // Messages. template <typename Element> class ABSL_ATTRIBUTE_WARN_UNUSED RepeatedPtrField final : private internal::RepeatedPtrFieldBase { static_assert(!std::is_const<Element>::value, "We do not support const value types."); static_assert(!std::is_volatile<Element>::value, "We do not support volatile value types."); static_assert(!std::is_pointer<Element>::value, "We do not support pointer value types."); static_assert(!std::is_reference<Element>::value, "We do not support reference value types."); static constexpr PROTOBUF_ALWAYS_INLINE void StaticValidityCheck() { static_assert( absl::disjunction< internal::is_supported_string_type<Element>, internal::is_supported_message_type<Element>>::value, "We only support string and Message types in RepeatedPtrField."); static_assert(alignof(Element) <= internal::ArenaAlignDefault::align, "Overaligned types are not supported"); } public: using value_type = Element; using size_type = int; using difference_type = ptrdiff_t; using reference = Element&; using const_reference = const Element&; using pointer = Element*; using const_pointer = const Element*; using iterator = internal::RepeatedPtrIterator<Element>; using const_iterator = internal::RepeatedPtrIterator<const Element>; using reverse_iterator = std::reverse_iterator<iterator>; using const_reverse_iterator = std::reverse_iterator<const_iterator>; // Custom STL-like iterator that iterates over and returns the underlying // pointers to Element rather than Element itself. using pointer_iterator = internal::RepeatedPtrOverPtrsIterator<Element*, void*>; using const_pointer_iterator = internal::RepeatedPtrOverPtrsIterator<const Element* const, const void* const>; constexpr RepeatedPtrField(); // Arena enabled constructors: for internal use only. #ifdef PROTOBUF_INTERNAL_REMOVE_ARENA_PTRS_REPEATED_PTR_FIELD constexpr RepeatedPtrField(internal::InternalVisibility, internal::InternalMetadataOffset offset) : RepeatedPtrField(offset) {} RepeatedPtrField(internal::InternalVisibility, internal::InternalMetadataOffset offset, const RepeatedPtrField& rhs) : RepeatedPtrField(offset, rhs) {} #else RepeatedPtrField(internal::InternalVisibility, Arena* arena) : RepeatedPtrFieldBase(arena) {} RepeatedPtrField(internal::InternalVisibility, Arena* arena, const RepeatedPtrField& rhs) : RepeatedPtrField(arena, rhs) {} RepeatedPtrField(internal::InternalVisibility, Arena* arena, RepeatedPtrField&& rhs) : RepeatedPtrField(arena, std::move(rhs)) {} #ifndef PROTOBUF_FUTURE_REMOVE_REPEATED_PTR_FIELD_ARENA_CONSTRUCTOR // TODO: make constructor private [[deprecated("Use Arena::Create<RepeatedPtrField<...>>(Arena*) instead")]] explicit RepeatedPtrField(Arena* arena); #endif #endif // !PROTOBUF_INTERNAL_REMOVE_ARENA_PTRS_REPEATED_PTR_FIELD template <typename Iter, typename = typename std::enable_if<std::is_constructible< Element, decltype(*std::declval<Iter>())>::value>::type> RepeatedPtrField(Iter begin, Iter end); RepeatedPtrField(const RepeatedPtrField& rhs) : RepeatedPtrField( #ifdef PROTOBUF_INTERNAL_REMOVE_ARENA_PTRS_REPEATED_PTR_FIELD internal::InternalMetadataOffset(), #else /*arena=*/nullptr, #endif rhs) { } RepeatedPtrField& operator=(const RepeatedPtrField& other) ABSL_ATTRIBUTE_LIFETIME_BOUND; #ifdef PROTOBUF_INTERNAL_REMOVE_ARENA_PTRS_REPEATED_PTR_FIELD RepeatedPtrField(RepeatedPtrField&& rhs) noexcept : RepeatedPtrField(internal::InternalMetadataOffset(), std::move(rhs)) {} #else RepeatedPtrField(RepeatedPtrField&& rhs) noexcept : RepeatedPtrField(nullptr, std::move(rhs)) {} #endif RepeatedPtrField& operator=(RepeatedPtrField&& other) noexcept ABSL_ATTRIBUTE_LIFETIME_BOUND; ~RepeatedPtrField(); PROTOBUF_FUTURE_ADD_NODISCARD bool empty() const; PROTOBUF_FUTURE_ADD_NODISCARD int size() const; PROTOBUF_FUTURE_ADD_NODISCARD const_reference Get(int index) const ABSL_ATTRIBUTE_LIFETIME_BOUND; PROTOBUF_FUTURE_ADD_NODISCARD pointer Mutable(int index) ABSL_ATTRIBUTE_LIFETIME_BOUND; // Unlike std::vector, adding an element to a RepeatedPtrField doesn't always // make a new element; it might re-use an element left over from when the // field was Clear()'d or resize()'d smaller. For this reason, Add() is the // fastest API for adding a new element. pointer Add() ABSL_ATTRIBUTE_LIFETIME_BOUND; // `Add(std::move(value));` is equivalent to `*Add() = std::move(value);` // It will either move-construct to the end of this field, or swap value // with the new-or-recycled element at the end of this field. Note that // this operation is very slow if this RepeatedPtrField is not on the // same Arena, if any, as `value`. void Add(Element&& value); // Copying to the end of this RepeatedPtrField is slowest of all; it can't // reliably copy-construct to the last element of this RepeatedPtrField, for // example (unlike std::vector). // We currently block this API. The right way to add to the end is to call // Add() and modify the element it points to. // If you must add an existing value, call `*Add() = value;` void Add(const Element& value) = delete; // Append elements in the range [begin, end) after reserving // the appropriate number of elements. template <typename Iter> void Add(Iter begin, Iter end); PROTOBUF_FUTURE_ADD_NODISCARD const_reference operator[](int index) const ABSL_ATTRIBUTE_LIFETIME_BOUND { return Get(index); } PROTOBUF_FUTURE_ADD_NODISCARD reference operator[](int index) ABSL_ATTRIBUTE_LIFETIME_BOUND { return *Mutable(index); } PROTOBUF_FUTURE_ADD_NODISCARD const_reference at(int index) const ABSL_ATTRIBUTE_LIFETIME_BOUND; PROTOBUF_FUTURE_ADD_NODISCARD reference at(int index) ABSL_ATTRIBUTE_LIFETIME_BOUND; // Removes the last element in the array. // Ownership of the element is retained by the array. void RemoveLast(); // Deletes elements with indices in the range [start .. start+num-1]. // Caution: moves all elements with indices [start+num .. ]. // Calling this routine inside a loop can cause quadratic behavior. void DeleteSubrange(int start, int num); ABSL_ATTRIBUTE_REINITIALIZES void Clear(); // Appends the elements from `other` after this instance. // The end result length will be `other.size() + this->size()`. void MergeFrom(const RepeatedPtrField& other); // Replaces the contents with a copy of the elements from `other`. ABSL_ATTRIBUTE_REINITIALIZES void CopyFrom(const RepeatedPtrField& other); // Replaces the contents with RepeatedPtrField(begin, end). template <typename Iter> ABSL_ATTRIBUTE_REINITIALIZES void Assign(Iter begin, Iter end); // Reserves space to expand the field to at least the given size. This only // resizes the pointer array; it doesn't allocate any objects. If the // array is grown, it will always be at least doubled in size. void Reserve(int new_size); PROTOBUF_FUTURE_ADD_NODISCARD int Capacity() const; // Gets the underlying array. This pointer is possibly invalidated by // any add or remove operation. PROTOBUF_FUTURE_ADD_NODISCARD Element** mutable_data() ABSL_ATTRIBUTE_LIFETIME_BOUND; PROTOBUF_FUTURE_ADD_NODISCARD const Element* const* data() const ABSL_ATTRIBUTE_LIFETIME_BOUND; // Swaps entire contents with "other". If they are on separate arenas, then // copies data. void Swap(RepeatedPtrField* other); // Swaps entire contents with "other". Caller should guarantee that either // both fields are on the same arena or both are on the heap. Swapping between // different arenas with this function is disallowed and is caught via // ABSL_DCHECK. void UnsafeArenaSwap(RepeatedPtrField* other); // Swaps two elements. void SwapElements(int index1, int index2); PROTOBUF_FUTURE_ADD_NODISCARD iterator begin() ABSL_ATTRIBUTE_LIFETIME_BOUND; PROTOBUF_FUTURE_ADD_NODISCARD const_iterator begin() const ABSL_ATTRIBUTE_LIFETIME_BOUND; PROTOBUF_FUTURE_ADD_NODISCARD const_iterator cbegin() const ABSL_ATTRIBUTE_LIFETIME_BOUND; PROTOBUF_FUTURE_ADD_NODISCARD iterator end() ABSL_ATTRIBUTE_LIFETIME_BOUND; PROTOBUF_FUTURE_ADD_NODISCARD const_iterator end() const ABSL_ATTRIBUTE_LIFETIME_BOUND; PROTOBUF_FUTURE_ADD_NODISCARD const_iterator cend() const ABSL_ATTRIBUTE_LIFETIME_BOUND; PROTOBUF_FUTURE_ADD_NODISCARD reverse_iterator rbegin() ABSL_ATTRIBUTE_LIFETIME_BOUND { return reverse_iterator(end()); } PROTOBUF_FUTURE_ADD_NODISCARD const_reverse_iterator rbegin() const ABSL_ATTRIBUTE_LIFETIME_BOUND { return const_reverse_iterator(end()); } PROTOBUF_FUTURE_ADD_NODISCARD reverse_iterator rend() ABSL_ATTRIBUTE_LIFETIME_BOUND { return reverse_iterator(begin()); } PROTOBUF_FUTURE_ADD_NODISCARD const_reverse_iterator rend() const ABSL_ATTRIBUTE_LIFETIME_BOUND { return const_reverse_iterator(begin()); } PROTOBUF_FUTURE_ADD_NODISCARD pointer_iterator pointer_begin() ABSL_ATTRIBUTE_LIFETIME_BOUND; PROTOBUF_FUTURE_ADD_NODISCARD const_pointer_iterator pointer_begin() const ABSL_ATTRIBUTE_LIFETIME_BOUND; PROTOBUF_FUTURE_ADD_NODISCARD pointer_iterator pointer_end() ABSL_ATTRIBUTE_LIFETIME_BOUND; PROTOBUF_FUTURE_ADD_NODISCARD const_pointer_iterator pointer_end() const ABSL_ATTRIBUTE_LIFETIME_BOUND; // Returns (an estimate of) the number of bytes used by the repeated field, // excluding sizeof(*this). PROTOBUF_FUTURE_ADD_NODISCARD size_t SpaceUsedExcludingSelfLong() const; PROTOBUF_FUTURE_ADD_NODISCARD int SpaceUsedExcludingSelf() const { return internal::ToIntSize(SpaceUsedExcludingSelfLong()); } // Advanced memory management -------------------------------------- // When hardcore memory management becomes necessary -- as it sometimes // does here at Google -- the following methods may be useful. // Adds an already-allocated object, passing ownership to the // RepeatedPtrField. // // Note that some special behavior occurs with respect to arenas: // // (i) if this field holds submessages, the new submessage will be copied if // the original is in an arena and this RepeatedPtrField is either in a // different arena, or on the heap. // (ii) if this field holds strings, the passed-in string *must* be // heap-allocated, not arena-allocated. There is no way to dynamically check // this at runtime, so User Beware. // Requires: value != nullptr void AddAllocated(Element* value); // Removes and returns the last element, passing ownership to the caller. // Requires: size() > 0 // // If this RepeatedPtrField is on an arena, an object copy is required to pass // ownership back to the user (for compatible semantics). Use // UnsafeArenaReleaseLast() if this behavior is undesired. PROTOBUF_FUTURE_ADD_NODISCARD Element* ReleaseLast(); // Adds an already-allocated object, skipping arena-ownership checks. The user // must guarantee that the given object is in the same arena as this // RepeatedPtrField. // It is also useful in legacy code that uses temporary ownership to avoid // copies. Example: // RepeatedPtrField<T> temp_field; // temp_field.UnsafeArenaAddAllocated(new T); // ... // Do something with temp_field // temp_field.UnsafeArenaExtractSubrange(0, temp_field.size(), nullptr); // If you put temp_field on the arena this fails, because the ownership // transfers to the arena at the "AddAllocated" call and is not released // anymore, causing a double delete. UnsafeArenaAddAllocated prevents this. // Requires: value != nullptr void UnsafeArenaAddAllocated(Element* value); // Removes and returns the last element. Unlike ReleaseLast, the returned // pointer is always to the original object. This may be in an arena, in // which case it would have the arena's lifetime. // Requires: current_size_ > 0 pointer UnsafeArenaReleaseLast(); // Extracts elements with indices in the range "[start .. start+num-1]". // The caller assumes ownership of the extracted elements and is responsible // for deleting them when they are no longer needed. // If "elements" is non-nullptr, then pointers to the extracted elements // are stored in "elements[0 .. num-1]" for the convenience of the caller. // If "elements" is nullptr, then the caller must use some other mechanism // to perform any further operations (like deletion) on these elements. // Caution: implementation also moves elements with indices [start+num ..]. // Calling this routine inside a loop can cause quadratic behavior. // // Memory copying behavior is identical to ReleaseLast(), described above: if // this RepeatedPtrField is on an arena, an object copy is performed for each // returned element, so that all returned element pointers are to // heap-allocated copies. If this copy is not desired, the user should call // UnsafeArenaExtractSubrange(). void ExtractSubrange(int start, int num, Element** elements); // Identical to ExtractSubrange() described above, except that no object // copies are ever performed. Instead, the raw object pointers are returned. // Thus, if on an arena, the returned objects must not be freed, because they // will not be heap-allocated objects. void UnsafeArenaExtractSubrange(int start, int num, Element** elements); // When elements are removed by calls to RemoveLast() or Clear(), they // are not actually freed. Instead, they are cleared and kept so that // they can be reused later. This can save lots of CPU time when // repeatedly reusing a protocol message for similar purposes. // // Hardcore programs may choose to manipulate these cleared objects // to better optimize memory management using the following routines. // Removes the element referenced by position. // // Returns an iterator to the element immediately following the removed // element. // // Invalidates all iterators at or after the removed element, including end(). iterator erase(const_iterator position) ABSL_ATTRIBUTE_LIFETIME_BOUND; // Removes the elements in the range [first, last). // // Returns an iterator to the element immediately following the removed range. // // Invalidates all iterators at or after the removed range, including end(). iterator erase(const_iterator first, const_iterator last) ABSL_ATTRIBUTE_LIFETIME_BOUND; // Gets the arena on which this RepeatedPtrField stores its elements. PROTOBUF_FUTURE_ADD_NODISCARD inline Arena* GetArena(); // For internal use only. // // This is public due to it being called by generated code. void InternalSwap(RepeatedPtrField* PROTOBUF_RESTRICT other) { internal::RepeatedPtrFieldBase::InternalSwap(other); } // For internal use only. // // Like `Add()`, but uses the given arena instead of calling `GetArena()`. It // is the responsibility of the caller to ensure that this arena is the same // as the arena returned from `GetArena()`. pointer InternalAddWithArena(internal::InternalVisibility, Arena* arena) ABSL_ATTRIBUTE_LIFETIME_BOUND; // For internal use only. // // Like `Add(Element&&)`, but uses the given arena instead of calling // `GetArena()`. It is the responsibility of the caller to ensure that this // arena is the same as the arena returned from `GetArena()`. void InternalAddWithArena(internal::InternalVisibility, Arena* arena, Element&& value); // For internal use only. // // Like `MergeFrom(const RepeatedPtrField& other)`, but uses the given arena // instead of calling `GetArena()`. It is the responsibility of the caller to // ensure that this arena is the same as the arena returned from `GetArena()`. void InternalMergeFromWithArena(internal::InternalVisibility, Arena* arena, const RepeatedPtrField& other); #ifndef PROTOBUF_INTERNAL_REMOVE_ARENA_PTRS_REPEATED_PTR_FIELD using RepeatedPtrFieldBase::InternalGetArenaOffset; #endif // !PROTOBUF_INTERNAL_REMOVE_ARENA_PTRS_REPEATED_PTR_FIELD private: using InternalArenaConstructable_ = void; using DestructorSkippable_ = void; // Friended to allow calling `AddAllocated` from our private base class with // arena pointers, which may be cached in the iterator. This saves us needing // to call `GetArena()` on the `RepeatedPtrField` every insertion, which has 2 // levels of indirection. template <typename T> friend class internal::AllocatedRepeatedPtrFieldBackInsertIterator; friend class Arena; friend class internal::FieldWithArena<RepeatedPtrField<Element>>; friend class DynamicMessage; friend class google::protobuf::internal::ExtensionSet; friend class internal::MapFieldBase; friend class internal::TcParser; template <typename T> friend struct WeakRepeatedPtrField; // The MapFieldBase implementation needs to be able to static_cast down to // `RepeatedPtrFieldBase`. friend internal::MapFieldBase; // Note: RepeatedPtrField SHOULD NOT be subclassed by users. using TypeHandler = internal::GenericTypeHandler<Element>; #ifdef PROTOBUF_INTERNAL_REMOVE_ARENA_PTRS_REPEATED_PTR_FIELD constexpr explicit RepeatedPtrField(internal::InternalMetadataOffset offset); RepeatedPtrField(internal::InternalMetadataOffset offset, const RepeatedPtrField& rhs); RepeatedPtrField(internal::InternalMetadataOffset offset, RepeatedPtrField&& rhs); #else // !PROTOBUF_INTERNAL_REMOVE_ARENA_PTRS_REPEATED_PTR_FIELD RepeatedPtrField(Arena* arena, const RepeatedPtrField& rhs); RepeatedPtrField(Arena* arena, RepeatedPtrField&& rhs); #ifdef PROTOBUF_FUTURE_REMOVE_REPEATED_PTR_FIELD_ARENA_CONSTRUCTOR explicit RepeatedPtrField(Arena* arena); #endif #endif // !PROTOBUF_INTERNAL_REMOVE_ARENA_PTRS_REPEATED_PTR_FIELD void AddAllocatedWithArena(Arena* arena, Element* value); PROTOBUF_FUTURE_ADD_NODISCARD Element* ReleaseLastWithArena(Arena* arena); void UnsafeArenaAddAllocatedWithArena(Arena* arena, Element* value); void ExtractSubrangeWithArena(Arena* arena, int start, int num, Element** elements); void AddAllocatedForParse(Element* p, Arena* arena) { return RepeatedPtrFieldBase::AddAllocatedForParse(p, arena); } }; // ------------------------------------------------------------------- template <typename Element> constexpr RepeatedPtrField<Element>::RepeatedPtrField() : RepeatedPtrFieldBase() { // We can't have `StaticValidityCheck` here because it requires Element to // be a complete type, and split `RepeatedPtrField`s call // `Arena::DefaultConstruct` with an incomplete `Element`. This only applies // when arena offsets are used, since that triggers special logic in arena.h // to construct the object with a default constructor instead of the // arena-enabled constructor (note how we don't `StaticValidityCheck` in the // arena-enabled constructor). #ifndef PROTOBUF_INTERNAL_REMOVE_ARENA_PTRS_REPEATED_PTR_FIELD StaticValidityCheck(); #endif } template <typename Element> #ifdef PROTOBUF_INTERNAL_REMOVE_ARENA_PTRS_REPEATED_PTR_FIELD constexpr #endif inline RepeatedPtrField<Element>::RepeatedPtrField( #ifdef PROTOBUF_INTERNAL_REMOVE_ARENA_PTRS_REPEATED_PTR_FIELD internal::InternalMetadataOffset offset #else Arena* arena #endif ) : RepeatedPtrFieldBase( #ifdef PROTOBUF_INTERNAL_REMOVE_ARENA_PTRS_REPEATED_PTR_FIELD offset #else arena #endif ) { // We can't have StaticValidityCheck here because that requires Element to be // a complete type, and in split repeated fields cases, we call // CreateMessage<RepeatedPtrField<T>> for incomplete Ts. } template <typename Element> inline RepeatedPtrField<Element>::RepeatedPtrField( #ifdef PROTOBUF_INTERNAL_REMOVE_ARENA_PTRS_REPEATED_PTR_FIELD internal::InternalMetadataOffset offset, #else Arena* arena, #endif const RepeatedPtrField& rhs) : RepeatedPtrFieldBase( #ifdef PROTOBUF_INTERNAL_REMOVE_ARENA_PTRS_REPEATED_PTR_FIELD offset #else arena #endif ) { StaticValidityCheck(); MergeFrom(rhs); } template <typename Element> template <typename Iter, typename> inline RepeatedPtrField<Element>::RepeatedPtrField(Iter begin, Iter end) { StaticValidityCheck(); Add(begin, end); } template <typename Element> RepeatedPtrField<Element>::~RepeatedPtrField() { StaticValidityCheck(); if (!NeedsDestroy()) return; if constexpr (std::is_base_of<MessageLite, Element>::value) { DestroyProtos(); } else { Destroy<TypeHandler>(); } } template <typename Element> inline RepeatedPtrField<Element>& RepeatedPtrField<Element>::operator=( const RepeatedPtrField& other) ABSL_ATTRIBUTE_LIFETIME_BOUND { if (this != &other) CopyFrom(other); return *this; } template <typename Element> inline RepeatedPtrField<Element>::RepeatedPtrField( #ifdef PROTOBUF_INTERNAL_REMOVE_ARENA_PTRS_REPEATED_PTR_FIELD internal::InternalMetadataOffset offset, #else Arena* arena, #endif RepeatedPtrField&& rhs) : RepeatedPtrFieldBase( #ifdef PROTOBUF_INTERNAL_REMOVE_ARENA_PTRS_REPEATED_PTR_FIELD offset #else arena #endif ) { // We don't just call Swap(&rhs) here because it would perform 3 copies if rhs // is on a different arena. #ifdef PROTOBUF_INTERNAL_REMOVE_ARENA_PTRS_REPEATED_PTR_FIELD Arena* arena = GetArena(); #endif if (internal::CanMoveWithInternalSwap(arena, rhs.GetArena())) { InternalSwap(&rhs); } else { RepeatedPtrFieldBase::CopyFrom<TypeHandler>(rhs, arena); } } template <typename Element> inline RepeatedPtrField<Element>& RepeatedPtrField<Element>::operator=( RepeatedPtrField&& other) noexcept ABSL_ATTRIBUTE_LIFETIME_BOUND { // We don't just call Swap(&other) here because it would perform 3 copies if // the two fields are on different arenas. if (this != &other) { Arena* arena = GetArena(); Arena* other_arena = other.GetArena(); if (internal::CanMoveWithInternalSwap(arena, other_arena)) { InternalSwap(&other); } else { RepeatedPtrFieldBase::CopyFrom<TypeHandler>(other, arena); } } return *this; } template <typename Element> inline bool RepeatedPtrField<Element>::empty() const { return RepeatedPtrFieldBase::empty(); } template <typename Element> inline int RepeatedPtrField<Element>::size() const { return RepeatedPtrFieldBase::size(); } template <typename Element> inline const Element& RepeatedPtrField<Element>::Get(int index) const ABSL_ATTRIBUTE_LIFETIME_BOUND { return RepeatedPtrFieldBase::Get<TypeHandler>(index); } template <typename Element> inline const Element& RepeatedPtrField<Element>::at(int index) const ABSL_ATTRIBUTE_LIFETIME_BOUND { return RepeatedPtrFieldBase::at<TypeHandler>(index); } template <typename Element> inline Element& RepeatedPtrField<Element>::at(int index) ABSL_ATTRIBUTE_LIFETIME_BOUND { return RepeatedPtrFieldBase::at<TypeHandler>(index); } template <typename Element> inline Element* RepeatedPtrField<Element>::Mutable(int index) ABSL_ATTRIBUTE_LIFETIME_BOUND { return RepeatedPtrFieldBase::Mutable<TypeHandler>(index); } template <typename Element> PROTOBUF_NDEBUG_INLINE Element* RepeatedPtrField<Element>::Add() ABSL_ATTRIBUTE_LIFETIME_BOUND { return RepeatedPtrFieldBase::Add<TypeHandler>(GetArena()); } template <typename Element> PROTOBUF_NDEBUG_INLINE Element* RepeatedPtrField<Element>::InternalAddWithArena( internal::InternalVisibility, Arena* arena) ABSL_ATTRIBUTE_LIFETIME_BOUND { return RepeatedPtrFieldBase::Add<TypeHandler>(arena); } template <typename Element> PROTOBUF_NDEBUG_INLINE void RepeatedPtrField<Element>::Add(Element&& value) { RepeatedPtrFieldBase::Add<TypeHandler>(GetArena(), std::move(value)); } template <typename Element> PROTOBUF_NDEBUG_INLINE void RepeatedPtrField<Element>::InternalAddWithArena( internal::InternalVisibility, Arena* arena, Element&& value) { RepeatedPtrFieldBase::Add<TypeHandler>(arena, std::move(value)); } template <typename Element> template <typename Iter> PROTOBUF_NDEBUG_INLINE void RepeatedPtrField<Element>::Add(Iter begin, Iter end) { if (std::is_base_of< std::forward_iterator_tag, typename std::iterator_traits<Iter>::iterator_category>::value) { int reserve = static_cast<int>(std::distance(begin, end)); Reserve(size() + reserve); } for (; begin != end; ++begin) { *Add() = *begin; } } template <typename Element> inline void RepeatedPtrField<Element>::RemoveLast() { RepeatedPtrFieldBase::RemoveLast<TypeHandler>(); } template <typename Element> inline void RepeatedPtrField<Element>::DeleteSubrange(int start, int num) { ABSL_DCHECK_GE(start, 0); ABSL_DCHECK_GE(num, 0); ABSL_DCHECK_LE(start + num, size()); void** subrange = raw_mutable_data() + start; Arena* arena = GetArena(); for (int i = 0; i < num; ++i) { using H = CommonHandler<TypeHandler>; H::Delete(static_cast<Element*>(subrange[i]), arena); } UnsafeArenaExtractSubrange(start, num, nullptr); } template <typename Element> inline void RepeatedPtrField<Element>::ExtractSubrange(int start, int num, Element** elements) { ExtractSubrangeWithArena(GetArena(), start, num, elements); } template <typename Element> inline void RepeatedPtrField<Element>::ExtractSubrangeWithArena( Arena* arena, int start, int num, Element** elements) { ABSL_DCHECK_EQ(arena, GetArena()); ABSL_DCHECK_GE(start, 0); ABSL_DCHECK_GE(num, 0); ABSL_DCHECK_LE(start + num, size()); if (num == 0) return; ABSL_DCHECK_NE(elements, nullptr) << "Releasing elements without transferring ownership is an unsafe " "operation. Use UnsafeArenaExtractSubrange."; if (elements != nullptr) { auto* extracted = data() + start; if (internal::DebugHardenForceCopyInRelease()) { // Always copy. for (int i = 0; i < num; ++i) { elements[i] = copy<TypeHandler>(extracted[i]); } if (arena == nullptr) { for (int i = 0; i < num; ++i) { delete extracted[i]; } } } else { // If we're on an arena, we perform a copy for each element so that the // returned elements are heap-allocated. Otherwise, just forward it. if (arena != nullptr) { for (int i = 0; i < num; ++i) { elements[i] = copy<TypeHandler>(extracted[i]); } } else { memcpy(elements, extracted, num * sizeof(Element*)); } } } CloseGap(start, num); } template <typename Element> inline void RepeatedPtrField<Element>::UnsafeArenaExtractSubrange( int start, int num, Element** elements) { ABSL_DCHECK_GE(start, 0); ABSL_DCHECK_GE(num, 0); ABSL_DCHECK_LE(start + num, size()); if (num > 0) { // Save the values of the removed elements if requested. if (elements != nullptr) { memcpy(elements, data() + start, num * sizeof(Element*)); } CloseGap(start, num); } } template <typename Element> inline void RepeatedPtrField<Element>::Clear() { RepeatedPtrFieldBase::Clear<TypeHandler>(); } template <typename Element> inline void RepeatedPtrField<Element>::MergeFrom( const RepeatedPtrField& other) { if (other.empty()) return; RepeatedPtrFieldBase::MergeFrom<Element>(other, GetArena()); } template <typename Element> inline void RepeatedPtrField<Element>::InternalMergeFromWithArena( internal::InternalVisibility, Arena* arena, const RepeatedPtrField& other) { if (other.empty()) return; RepeatedPtrFieldBase::MergeFrom<Element>(other, arena); } template <typename Element> inline void RepeatedPtrField<Element>::CopyFrom(const RepeatedPtrField& other) { RepeatedPtrFieldBase::CopyFrom<TypeHandler>(other, GetArena()); } template <typename Element> template <typename Iter> inline void RepeatedPtrField<Element>::Assign(Iter begin, Iter end) { Clear(); Add(begin, end); } template <typename Element> inline typename RepeatedPtrField<Element>::iterator RepeatedPtrField<Element>::erase(const_iterator position) ABSL_ATTRIBUTE_LIFETIME_BOUND { return erase(position, position + 1); } template <typename Element> inline typename RepeatedPtrField<Element>::iterator RepeatedPtrField<Element>::erase(const_iterator first, const_iterator last) ABSL_ATTRIBUTE_LIFETIME_BOUND { size_type pos_offset = static_cast<size_type>(std::distance(cbegin(), first)); size_type last_offset = static_cast<size_type>(std::distance(cbegin(), last)); DeleteSubrange(pos_offset, last_offset - pos_offset); return begin() + pos_offset; } template <typename Element> inline Element** RepeatedPtrField<Element>::mutable_data() ABSL_ATTRIBUTE_LIFETIME_BOUND { return RepeatedPtrFieldBase::mutable_data<TypeHandler>(); } template <typename Element> inline const Element* const* RepeatedPtrField<Element>::data() const ABSL_ATTRIBUTE_LIFETIME_BOUND { return RepeatedPtrFieldBase::data<TypeHandler>(); } template <typename Element> inline void RepeatedPtrField<Element>::Swap(RepeatedPtrField* other) { if (this == other) return; RepeatedPtrFieldBase::Swap<TypeHandler>(GetArena(), other, other->GetArena()); } template <typename Element> inline void RepeatedPtrField<Element>::UnsafeArenaSwap( RepeatedPtrField* other) { if (this == other) return; ABSL_DCHECK_EQ(GetArena(), other->GetArena()); RepeatedPtrFieldBase::InternalSwap(other); } template <typename Element> inline void RepeatedPtrField<Element>::SwapElements(int index1, int index2) { RepeatedPtrFieldBase::SwapElements(index1, index2); } template <typename Element> inline Arena* RepeatedPtrField<Element>::GetArena() { return RepeatedPtrFieldBase::GetArena(); } template <typename Element> inline size_t RepeatedPtrField<Element>::SpaceUsedExcludingSelfLong() const { // `google::protobuf::Message` has a virtual method `SpaceUsedLong`, hence we can // instantiate just one function for all protobuf messages. // Note: std::is_base_of requires that `Element` is a concrete class. using H = typename std::conditional<std::is_base_of<Message, Element>::value, internal::GenericTypeHandler<Message>, TypeHandler>::type; return RepeatedPtrFieldBase::SpaceUsedExcludingSelfLong<H>(); } template <typename Element> inline void RepeatedPtrField<Element>::AddAllocated(Element* value) { AddAllocatedWithArena(GetArena(), value); } template <typename Element> inline void RepeatedPtrField<Element>::AddAllocatedWithArena(Arena* arena, Element* value) { ABSL_DCHECK_EQ(arena, GetArena()); RepeatedPtrFieldBase::AddAllocated<TypeHandler>(arena, value); } template <typename Element> inline void RepeatedPtrField<Element>::UnsafeArenaAddAllocated(Element* value) { UnsafeArenaAddAllocatedWithArena(GetArena(), value); } template <typename Element> inline void RepeatedPtrField<Element>::UnsafeArenaAddAllocatedWithArena( Arena* arena, Element* value) { ABSL_DCHECK_EQ(arena, GetArena()); RepeatedPtrFieldBase::UnsafeArenaAddAllocated<TypeHandler>(arena, value); } template <typename Element> inline Element* RepeatedPtrField<Element>::ReleaseLast() { return ReleaseLastWithArena(GetArena()); } template <typename Element> inline Element* RepeatedPtrField<Element>::ReleaseLastWithArena(Arena* arena) { ABSL_DCHECK_EQ(arena, GetArena()); return RepeatedPtrFieldBase::ReleaseLast<TypeHandler>(arena); } template <typename Element> inline Element* RepeatedPtrField<Element>::UnsafeArenaReleaseLast() { return RepeatedPtrFieldBase::UnsafeArenaReleaseLast<TypeHandler>(); } template <typename Element> inline void RepeatedPtrField<Element>::Reserve(int new_size) { return RepeatedPtrFieldBase::Reserve(new_size, GetArena()); } template <typename Element> inline int RepeatedPtrField<Element>::Capacity() const { return RepeatedPtrFieldBase::Capacity(); } // ------------------------------------------------------------------- namespace internal { #ifdef PROTOBUF_INTERNAL_REMOVE_ARENA_PTRS_REPEATED_PTR_FIELD // A container that holds a RepeatedPtrField<Element> and an arena pointer. This // is used for both directly arena-allocated RepeatedPtrField's and split // RepeatedPtrField's. Both cases need to be able to allocate memory in case a // user calls mutating methods on the RepeatedPtrField pointer. template <typename Element> using RepeatedPtrFieldWithArena = FieldWithArena<RepeatedPtrField<Element>>; template <typename Element> struct FieldArenaRep<RepeatedPtrField<Element>> { using Type = RepeatedPtrFieldWithArena<Element>; static inline RepeatedPtrField<Element>* Get( RepeatedPtrFieldWithArena<Element>* arena_rep) { return &arena_rep->field(); } }; template <typename Element> struct FieldArenaRep<const RepeatedPtrField<Element>> { using Type = const RepeatedPtrFieldWithArena<Element>; static inline const RepeatedPtrField<Element>* Get( const RepeatedPtrFieldWithArena<Element>* arena_rep) { return &arena_rep->field(); } }; #endif // This class gives the Rust implementation access to some protected methods on // RepeatedPtrFieldBase. These methods allow us to operate solely on the // MessageLite interface so that we do not need to generate code for each // concrete message type. class RustRepeatedMessageHelper { public: static RepeatedPtrFieldBase* New() { return new RepeatedPtrFieldBase; } static void Delete(RepeatedPtrFieldBase* field) { if (field->NeedsDestroy()) { field->DestroyProtos(); } delete field; } static size_t Size(const RepeatedPtrFieldBase& field) { return static_cast<size_t>(field.size()); } static auto Add(RepeatedPtrFieldBase& field, const MessageLite* prototype) { return field.AddFromPrototype<GenericTypeHandler<MessageLite>>( field.GetArena(), prototype); } static void CopyFrom(const RepeatedPtrFieldBase& src, RepeatedPtrFieldBase& dst) { dst.Clear<GenericTypeHandler<google::protobuf::MessageLite>>(); dst.MergeFrom<google::protobuf::MessageLite>(src, dst.GetArena()); } static void Reserve(RepeatedPtrFieldBase& field, size_t additional) { field.Reserve(field.size() + additional, field.GetArena()); } static const MessageLite& At(const RepeatedPtrFieldBase& field, size_t index) { return field.at<GenericTypeHandler<MessageLite>>(index); } static MessageLite& At(RepeatedPtrFieldBase& field, size_t index) { return field.at<GenericTypeHandler<MessageLite>>(index); } }; // STL-like iterator implementation for RepeatedPtrField. You should not // refer to this class directly; use RepeatedPtrField<T>::iterator instead. // // The iterator for RepeatedPtrField<T>, RepeatedPtrIterator<T>, is // very similar to iterator_ptr<T**> in util/gtl/iterator_adaptors.h, // but adds random-access operators and is modified to wrap a void** base // iterator (since RepeatedPtrField stores its array as a void* array and // casting void** to T** would violate C++ aliasing rules). // // This code based on net/proto/proto-array-internal.h by Jeffrey Yasskin // (jyasskin@google.com). template <typename Element> class RepeatedPtrIterator { public: using iterator = RepeatedPtrIterator<Element>; using iterator_category = std::random_access_iterator_tag; using value_type = typename std::remove_const<Element>::type; using difference_type = std::ptrdiff_t; using pointer = Element*; using reference = Element&; RepeatedPtrIterator() : it_(nullptr) {} explicit RepeatedPtrIterator(void* const* it) : it_(it) {} // Allows "upcasting" from RepeatedPtrIterator<T**> to // RepeatedPtrIterator<const T*const*>. template <typename OtherElement, typename std::enable_if<std::is_convertible< OtherElement*, pointer>::value>::type* = nullptr> RepeatedPtrIterator(const RepeatedPtrIterator<OtherElement>& other) : it_(other.it_) {} // dereferenceable PROTOBUF_FUTURE_ADD_NODISCARD reference operator*() const { return *reinterpret_cast<Element*>(*it_); } PROTOBUF_FUTURE_ADD_NODISCARD pointer operator->() const { return &(operator*()); } // {inc,dec}rementable iterator& operator++() { ++it_; return *this; } iterator operator++(int) { return iterator(it_++); } iterator& operator--() { --it_; return *this; } iterator operator--(int) { return iterator(it_--); } // equality_comparable friend bool operator==(const iterator& x, const iterator& y) { return x.it_ == y.it_; } friend bool operator!=(const iterator& x, const iterator& y) { return x.it_ != y.it_; } // less_than_comparable friend bool operator<(const iterator& x, const iterator& y) { return x.it_ < y.it_; } friend bool operator<=(const iterator& x, const iterator& y) { return x.it_ <= y.it_; } friend bool operator>(const iterator& x, const iterator& y) { return x.it_ > y.it_; } friend bool operator>=(const iterator& x, const iterator& y) { return x.it_ >= y.it_; } // addable, subtractable iterator& operator+=(difference_type d) { it_ += d; return *this; } friend iterator operator+(iterator it, const difference_type d) { it += d; return it; } friend iterator operator+(const difference_type d, iterator it) { it += d; return it; } iterator& operator-=(difference_type d) { it_ -= d; return *this; } friend iterator operator-(iterator it, difference_type d) { it -= d; return it; } // indexable PROTOBUF_FUTURE_ADD_NODISCARD reference operator[](difference_type d) const { return *(*this + d); } // random access iterator friend difference_type operator-(iterator it1, iterator it2) { return it1.it_ - it2.it_; } private: template <typename OtherElement> friend class RepeatedPtrIterator; // The internal iterator. void* const* it_; }; template <typename Traits, typename = void> struct IteratorConceptSupport { using tag = typename Traits::iterator_category; }; template <typename Traits> struct IteratorConceptSupport<Traits, absl::void_t<typename Traits::iterator_concept>> { using tag = typename Traits::iterator_concept; }; // Provides an iterator that operates on pointers to the underlying objects // rather than the objects themselves as RepeatedPtrIterator does. // Consider using this when working with stl algorithms that change // the array. // The VoidPtr template parameter holds the type-agnostic pointer value // referenced by the iterator. It should either be "void *" for a mutable // iterator, or "const void* const" for a constant iterator. template <typename Element, typename VoidPtr> class RepeatedPtrOverPtrsIterator { private: using traits = std::iterator_traits<typename std::remove_const<Element>::type*>; public: using value_type = typename traits::value_type; using difference_type = typename traits::difference_type; using pointer = Element*; using reference = Element&; using iterator_category = typename traits::iterator_category; using iterator_concept = typename IteratorConceptSupport<traits>::tag; using iterator = RepeatedPtrOverPtrsIterator<Element, VoidPtr>; RepeatedPtrOverPtrsIterator() : it_(nullptr) {} explicit RepeatedPtrOverPtrsIterator(VoidPtr* it) : it_(it) {} // Allows "upcasting" from RepeatedPtrOverPtrsIterator<T**> to // RepeatedPtrOverPtrsIterator<const T*const*>. template < typename OtherElement, typename OtherVoidPtr, typename std::enable_if< std::is_convertible<OtherElement*, pointer>::value && std::is_convertible<OtherVoidPtr, VoidPtr>::value>::type* = nullptr> RepeatedPtrOverPtrsIterator( const RepeatedPtrOverPtrsIterator<OtherElement, OtherVoidPtr>& other) : it_(other.it_) {} // dereferenceable PROTOBUF_FUTURE_ADD_NODISCARD reference operator*() const { return *reinterpret_cast<Element*>(it_); } PROTOBUF_FUTURE_ADD_NODISCARD pointer operator->() const { return reinterpret_cast<Element*>(it_); } // {inc,dec}rementable iterator& operator++() { ++it_; return *this; } iterator operator++(int) { return iterator(it_++); } iterator& operator--() { --it_; return *this; } iterator operator--(int) { return iterator(it_--); } // equality_comparable friend bool operator==(const iterator& x, const iterator& y) { return x.it_ == y.it_; } friend bool operator!=(const iterator& x, const iterator& y) { return x.it_ != y.it_; } // less_than_comparable friend bool operator<(const iterator& x, const iterator& y) { return x.it_ < y.it_; } friend bool operator<=(const iterator& x, const iterator& y) { return x.it_ <= y.it_; } friend bool operator>(const iterator& x, const iterator& y) { return x.it_ > y.it_; } friend bool operator>=(const iterator& x, const iterator& y) { return x.it_ >= y.it_; } // addable, subtractable iterator& operator+=(difference_type d) { it_ += d; return *this; } friend iterator operator+(iterator it, difference_type d) { it += d; return it; } friend iterator operator+(difference_type d, iterator it) { it += d; return it; } iterator& operator-=(difference_type d) { it_ -= d; return *this; } friend iterator operator-(iterator it, difference_type d) { it -= d; return it; } // indexable PROTOBUF_FUTURE_ADD_NODISCARD reference operator[](difference_type d) const { return *(*this + d); } // random access iterator friend difference_type operator-(iterator it1, iterator it2) { return it1.it_ - it2.it_; } private: template <typename OtherElement, typename OtherVoidPtr> friend class RepeatedPtrOverPtrsIterator; // The internal iterator. VoidPtr* it_; }; } // namespace internal template <typename Element> inline typename RepeatedPtrField<Element>::iterator RepeatedPtrField<Element>::begin() ABSL_ATTRIBUTE_LIFETIME_BOUND { return iterator(raw_data()); } template <typename Element> inline typename RepeatedPtrField<Element>::const_iterator RepeatedPtrField<Element>::begin() const ABSL_ATTRIBUTE_LIFETIME_BOUND { return iterator(raw_data()); } template <typename Element> inline typename RepeatedPtrField<Element>::const_iterator RepeatedPtrField<Element>::cbegin() const ABSL_ATTRIBUTE_LIFETIME_BOUND { return begin(); } template <typename Element> inline typename RepeatedPtrField<Element>::iterator RepeatedPtrField<Element>::end() ABSL_ATTRIBUTE_LIFETIME_BOUND { return iterator(raw_data() + size()); } template <typename Element> inline typename RepeatedPtrField<Element>::const_iterator RepeatedPtrField<Element>::end() const ABSL_ATTRIBUTE_LIFETIME_BOUND { return iterator(raw_data() + size()); } template <typename Element> inline typename RepeatedPtrField<Element>::const_iterator RepeatedPtrField<Element>::cend() const ABSL_ATTRIBUTE_LIFETIME_BOUND { return end(); } template <typename Element> inline typename RepeatedPtrField<Element>::pointer_iterator RepeatedPtrField<Element>::pointer_begin() ABSL_ATTRIBUTE_LIFETIME_BOUND { return pointer_iterator(raw_mutable_data()); } template <typename Element> inline typename RepeatedPtrField<Element>::const_pointer_iterator RepeatedPtrField<Element>::pointer_begin() const ABSL_ATTRIBUTE_LIFETIME_BOUND { return const_pointer_iterator(const_cast<const void* const*>(raw_data())); } template <typename Element> inline typename RepeatedPtrField<Element>::pointer_iterator RepeatedPtrField<Element>::pointer_end() ABSL_ATTRIBUTE_LIFETIME_BOUND { return pointer_iterator(raw_mutable_data() + size()); } template <typename Element> inline typename RepeatedPtrField<Element>::const_pointer_iterator RepeatedPtrField<Element>::pointer_end() const ABSL_ATTRIBUTE_LIFETIME_BOUND { return const_pointer_iterator( const_cast<const void* const*>(raw_data() + size())); } // Iterators and helper functions that follow the spirit of the STL // std::back_insert_iterator and std::back_inserter but are tailor-made // for RepeatedField and RepeatedPtrField. Typical usage would be: // // std::copy(some_sequence.begin(), some_sequence.end(), // RepeatedFieldBackInserter(proto.mutable_sequence())); // // Ported by johannes from util/gtl/proto-array-iterators.h namespace internal { // A back inserter for RepeatedPtrField objects. template <typename T> class RepeatedPtrFieldBackInsertIterator { public: using iterator_category = std::output_iterator_tag; using value_type = T; using pointer = void; using reference = void; using difference_type = std::ptrdiff_t; RepeatedPtrFieldBackInsertIterator(RepeatedPtrField<T>* const mutable_field) : field_(mutable_field) {} RepeatedPtrFieldBackInsertIterator<T>& operator=(const T& value) { *field_->Add() = value; return *this; } RepeatedPtrFieldBackInsertIterator<T>& operator=( const T* const ptr_to_value) { *field_->Add() = *ptr_to_value; return *this; } RepeatedPtrFieldBackInsertIterator<T>& operator=(T&& value) { *field_->Add() = std::move(value); return *this; } RepeatedPtrFieldBackInsertIterator<T>& operator*() { return *this; } RepeatedPtrFieldBackInsertIterator<T>& operator++() { return *this; } RepeatedPtrFieldBackInsertIterator<T>& operator++(int /* unused */) { return *this; } private: RepeatedPtrField<T>* field_; }; // A back inserter for RepeatedPtrFields that inserts by transferring ownership // of a pointer. template <typename T> class AllocatedRepeatedPtrFieldBackInsertIterator { public: using iterator_category = std::output_iterator_tag; using value_type = T; using pointer = void; using reference = void; using difference_type = std::ptrdiff_t; explicit AllocatedRepeatedPtrFieldBackInsertIterator( RepeatedPtrField<T>* const mutable_field) : field_(mutable_field), arena_(mutable_field->GetArena()) {} AllocatedRepeatedPtrFieldBackInsertIterator<T>& operator=( T* const ptr_to_value) { // Directly call AddAllocated with the cached arena pointer. This avoids // the cost of calling `GetArena()` on `RepeatedPtrField`, which is // expensive. field_->RepeatedPtrFieldBase::template AddAllocated< typename RepeatedPtrField<T>::TypeHandler>(arena_, ptr_to_value); return *this; } AllocatedRepeatedPtrFieldBackInsertIterator<T>& operator*() { return *this; } AllocatedRepeatedPtrFieldBackInsertIterator<T>& operator++() { return *this; } AllocatedRepeatedPtrFieldBackInsertIterator<T>& operator++(int /* unused */) { return *this; } private: RepeatedPtrField<T>* field_; Arena* arena_; }; // Almost identical to AllocatedRepeatedPtrFieldBackInsertIterator. This one // uses the UnsafeArenaAddAllocated instead. template <typename T> class UnsafeArenaAllocatedRepeatedPtrFieldBackInsertIterator { public: using iterator_category = std::output_iterator_tag; using value_type = T; using pointer = void; using reference = void; using difference_type = std::ptrdiff_t; explicit UnsafeArenaAllocatedRepeatedPtrFieldBackInsertIterator( RepeatedPtrField<T>* const mutable_field) : field_(mutable_field) {} UnsafeArenaAllocatedRepeatedPtrFieldBackInsertIterator<T>& operator=( T const* const ptr_to_value) { field_->UnsafeArenaAddAllocated(const_cast<T*>(ptr_to_value)); return *this; } UnsafeArenaAllocatedRepeatedPtrFieldBackInsertIterator<T>& operator*() { return *this; } UnsafeArenaAllocatedRepeatedPtrFieldBackInsertIterator<T>& operator++() { return *this; } UnsafeArenaAllocatedRepeatedPtrFieldBackInsertIterator<T>& operator++( int /* unused */) { return *this; } private: RepeatedPtrField<T>* field_; }; template <typename T> const T& CheckedGetOrDefault(const RepeatedPtrField<T>& field, int index) { if (ABSL_PREDICT_FALSE(index < 0 || index >= field.size())) { LogIndexOutOfBounds(index, field.size()); return GenericTypeHandler<T>::default_instance(); } return field.Get(index); } template <typename T> inline void CheckIndexInBoundsOrAbort(const RepeatedPtrField<T>& field, int index) { if (ABSL_PREDICT_FALSE(index < 0 || index >= field.size())) { LogIndexOutOfBoundsAndAbort(index, field.size()); } } template <typename T> const T& CheckedGetOrAbort(const RepeatedPtrField<T>& field, int index) { CheckIndexInBoundsOrAbort(field, index); return field.Get(index); } template <typename T> inline T* CheckedMutableOrAbort(RepeatedPtrField<T>* field, int index) { CheckIndexInBoundsOrAbort(*field, index); return field->Mutable(index); } } // namespace internal // Provides a back insert iterator for RepeatedPtrField instances, // similar to std::back_inserter(). template <typename T> internal::RepeatedPtrFieldBackInsertIterator<T> RepeatedPtrFieldBackInserter( RepeatedPtrField<T>* const mutable_field) { return internal::RepeatedPtrFieldBackInsertIterator<T>(mutable_field); } // Special back insert iterator for RepeatedPtrField instances, just in // case someone wants to write generic template code that can access both // RepeatedFields and RepeatedPtrFields using a common name. template <typename T> internal::RepeatedPtrFieldBackInsertIterator<T> RepeatedFieldBackInserter( RepeatedPtrField<T>* const mutable_field) { return internal::RepeatedPtrFieldBackInsertIterator<T>(mutable_field); } // Provides a back insert iterator for RepeatedPtrField instances // similar to std::back_inserter() which transfers the ownership while // copying elements. template <typename T> internal::AllocatedRepeatedPtrFieldBackInsertIterator<T> AllocatedRepeatedPtrFieldBackInserter( RepeatedPtrField<T>* const mutable_field) { return internal::AllocatedRepeatedPtrFieldBackInsertIterator<T>( mutable_field); } // Similar to AllocatedRepeatedPtrFieldBackInserter, using // UnsafeArenaAddAllocated instead of AddAllocated. // This is slightly faster if that matters. It is also useful in legacy code // that uses temporary ownership to avoid copies. Example: // RepeatedPtrField<T> temp_field; // temp_field.UnsafeArenaAddAllocated(new T); // ... // Do something with temp_field // temp_field.UnsafeArenaExtractSubrange(0, temp_field.size(), nullptr); // Putting temp_field on the arena fails because the ownership transfers to the // arena at the "AddAllocated" call and is not released anymore causing a // double delete. This function uses UnsafeArenaAddAllocated to prevent this. template <typename T> internal::UnsafeArenaAllocatedRepeatedPtrFieldBackInsertIterator<T> UnsafeArenaAllocatedRepeatedPtrFieldBackInserter( RepeatedPtrField<T>* const mutable_field) { return internal::UnsafeArenaAllocatedRepeatedPtrFieldBackInsertIterator<T>( mutable_field); } namespace internal { // Size optimization for `memswap<N>` - supplied below N is used by every // `RepeatedPtrField<T>`. extern template PROTOBUF_EXPORT_TEMPLATE_DECLARE void memswap<InternalMetadataResolverOffsetHelper<RepeatedPtrFieldBase>::value>( char* PROTOBUF_RESTRICT, char* PROTOBUF_RESTRICT); } // namespace internal } // namespace protobuf } // namespace google #include "google/protobuf/port_undef.inc" #endif // GOOGLE_PROTOBUF_REPEATED_PTR_FIELD_H__
411
0.950431
1
0.950431
game-dev
MEDIA
0.483686
game-dev
0.927857
1
0.927857
bizzancoin/qipaiyouxi
1,491
系统模块/子游戏/百人推筒子/游戏服务器/GameLogic.h
#ifndef GAME_LOGIC_HEAD_FILE #define GAME_LOGIC_HEAD_FILE #pragma once #include "Stdafx.h" //ֵ #define LOGIC_MASK_COLOR 0xF0 //ɫ #define LOGIC_MASK_VALUE 0x0F //ֵ // #define ST_VALUE 1 //ֵ #define ST_LOGIC 2 //߼ //˿Ŀ #define CARD_COUNT 40 //˿Ŀ #define MAX_COUNT 2 //Ŀ ////////////////////////////////////////////////////////////////////////// //Ϸ߼ void RandCount(BYTE cbCardBuffer[], BYTE cbBufferCount); class CGameLogic { // private: static const BYTE m_cbCardListData[CARD_COUNT]; //˿˶ // public: //캯 CGameLogic(); // virtual ~CGameLogic(); //ͺ public: //ȡֵ BYTE GetCardValue(BYTE cbCardData) { return cbCardData&LOGIC_MASK_VALUE; } //ȡɫ BYTE GetCardColor(BYTE cbCardData) { return cbCardData&LOGIC_MASK_COLOR; } //ƺ public: //˿ void RandCardList(BYTE cbCardBuffer[], BYTE cbBufferCount); //˿ void SortCardList(BYTE cbCardData[], BYTE cbCardCount, BYTE cbSortType); //ɾ˿ bool RemoveCard(const BYTE cbRemoveCard[], BYTE cbRemoveCount, BYTE cbCardData[], BYTE cbCardCount); //߼ public: //ȡ DWORD GetCardType(const BYTE cbCardData[], BYTE cbCardCount); //СȽ int CompareCard(const BYTE cbFirstCardData[], BYTE cbFirstCardCount,const BYTE cbNextCardData[], BYTE cbNextCardCount); //߼С BYTE GetCardLogicValue(BYTE cbCardData); void GetCardPoint(BYTE bcCardData ,CPoint &Point,int CardX,int CardY); }; ////////////////////////////////////////////////////////////////////////// #endif
411
0.842205
1
0.842205
game-dev
MEDIA
0.540468
game-dev
0.623651
1
0.623651
emileb/OpenGames
10,684
opengames/src/main/jni/abuse-0.8/data/lisp/duong.lsp
;; Copyright 1995 Crack dot Com, All Rights reserved ;; See licensing information for more details on usage rights (defun mine_ai () (if (or (eq (total_objects) 0) (not (eq (with_object (get_object 0) (aistate)) 0))) (select (aistate) (0 (if (touching_bg) (progn (set_state running) (if (eq (xvel) 1) (progn (with_object (bg) (make_view_solid (find_rgb 250 10 10))) (hurt_radius (x) (y) 40 35 nil 20)) (hurt_radius (x) (y) 40 25 nil 20)) (go_state 1)) (next_picture)) T) (1 (next_picture))) T)) (def_char CONC (funs (ai_fun mine_ai)) (fields ("xvel" conc_flash)) (states "art/chars/mine.spe" (running (seq "mine" 1 8)) (stopped '("mine0001.pcx" "mine_off")))) (defun air_mine_ai () (if (or (eq (total_objects) 0) ;; turned on? (not (eq (with_object (get_object 0) (aistate)) 0))) (if (touching_bg) (progn (if (eq (xvel) 1) (with_object (bg) (make_view_solid (find_rgb 250 10 10)))) (do_explo 40 25) nil) (progn (next_picture) T)) T)) (def_char CONC_AIR (funs (ai_fun air_mine_ai)) (fields ("xvel" conc_flash)) (states "art/chars/mine.spe" (stopped (seq "amin" 1 2)))) (defun bomb_cons () (setq blink_time 14)) (defun bomb_ai () (select (aistate) (0 ;; wait for a signal if connected, or wait for player touch (if (activated) (go_state 1) T)) (1 ;; count down blink time until zero then blow up (if (< blink_time 1) (go_state 2) (progn (if (or (< blink_time 10) (and (< blink_time 18) (eq (mod blink_time 2) 0)) (and (< blink_time 30) (eq (mod blink_time 3) 0)) (and (< blink_time 50) (eq (mod blink_time 4) 0))) (progn (play_sound TICK_SND 127 (x) (y)) (next_picture))) (setq blink_time (- blink_time 1)) T))) (2 ;; blow up (let ((oldy (y))) (set_y (- (y) (/ (picture_height) 2))) (do_explo 40 (get_ability jump_yvel)) (if (> (get_ability jump_yvel) 100) (add_object EXPLODE1 (+ (x) (random 10)) (+ (+ (random 10) (y)) -20) 0)) (set_y oldy)) nil))) (def_char BOMB (funs (ai_fun bomb_ai) (constructor bomb_cons)) (abilities (jump_yvel 30)) (range 150 150) (vars blink_time) (fields ("blink_time" bomb_blink)) (states "art/chars/mine.spe" (stopped '("abomb0001.pcx" "abomb0002.pcx")))) (def_char BIG_BOMB (funs (ai_fun bomb_ai) (constructor bomb_cons)) (abilities (jump_yvel 400)) (range 150 150) (vars blink_time) (fields ("blink_time" bomb_blink)) (states "art/chars/mine.spe" (stopped '("abomb0001.pcx+" "abomb0002.pcx+")))) (defun block_ai () (if (<= (hp) 0) (if (eq (state) dieing) (next_picture) (progn (play_sound CRUMBLE_SND 127 (x) (y)) (set_state dieing) T)) T)) (def_char BLOCK ;block has only 1 frame now will have block blowing up (funs (ai_fun block_ai)) (flags (can_block T) (hurtable T)) (abilities (start_hp 30)) (states "art/chars/block.spe" (stopped "block.pcx") (dieing (seq "bexplo" 1 7)))) (defun trap_door_ai () (if (> (total_objects) 0) (select (aistate) (0 ;; wait for switch to go off (if (not (eq (with_object (get_object 0) (aistate)) 0)) (progn (set_state running) (go_state 1)))) (1 ;; wait for animation (if (next_picture) T (progn (set_state blocking) (set_aistate 2)))) (2 ;; just stay here T))) T) (defun strap_door_ai () (general_sdoor_ai nil)) (def_char TRAP_DOOR2 (funs (ai_fun strap_door_ai)) (flags (can_block T)) (abilities (start_hp 30)) (states "art/chars/tdoor.spe" (stopped "tdor0001.pcx") (running (seq "tdor" 1 7)) (walking (seq "tdor" 7 1)) (blocking "tdor0007.pcx"))) (def_char TRAP_DOOR3 (funs (ai_fun strap_door_ai)) (flags (can_block T)) (abilities (start_hp 30)) (states "art/chars/tdoor.spe" (stopped "cdor0001.pcx") (running (seq "cdor" 1 7)) (walking (seq "cdor" 7 1)) (blocking "cdor0007.pcx"))) (defun lightin_ai () (if (or (eq (total_objects) 0) (not (eq (with_object (get_object 0) (aistate)) 0))) (select (aistate) (0 ;; delay (if (< (state_time) (* (aitype) 2)) (set_state stopped) (progn ; (hurt_radius (x) (y) 40 30 nil 30) (set_state running) (play_sound ELECTRIC_SND 127 (x) (y)) (go_state 1)))) (1 ;; next picture (if (next_picture) T (set_aistate 0))))) T) (def_char LIGHTIN (funs (ai_fun lightin_ai)) (flags (can_block T)) (fields ("aitype" lightin_speed)) (states "art/chars/lightin.spe" (running (seq "lite" 1 9)) (stopped "lite0001.pcx"))) (defun lava_ai () (if (and (touching_bg) (eq (mod (state_time) 20) 0)) (do_damage 6 (bg))) (select (aistate) (0 (if (eq (random 100) 0) (progn (play_sound LAVA_SND 64 (x) (y)) (set_aistate 1))) (next_picture)) (1 (next_picture) (if (eq (state_time) 5) (progn (hurt_radius (x) (y) 20 20 nil 10) (set_aistate 0))))) T) (def_char LAVA (funs (ai_fun lava_ai)) (states "art/chars/lava.spe" (stopped (seq "lava" 1 15)))) ;; XXX: Mac Abuse reimplements this in C++ (defun tp2_ai () (if (> (total_objects) 0) (select (aistate) (0 ;; wait for player to activate (if (and (touching_bg) (eq (total_objects) 1)) (progn (if (with_object (bg) (pressing_action_key)) (progn (link_object (bg)) (set_state running) (play_sound TELEPORTER_SND 127 (x) (y)) (set_aistate 1)))))) (1 ;; wait for animation (if (next_picture) (let ((x (x)) (y (- (y) 16)) (fade (if (< (current_frame) 16) (current_frame) 15))) (with_object (get_object 1) (progn (set_x x) (set_y y) (user_fun SET_FADE_COUNT fade) (setq is_teleporting 1) ))) (let ((x (with_object (get_object 0) (x))) (y (with_object (get_object 0) (- (y) 16)))) (with_object (get_object 1) (progn (set_x x) (set_y y) (setq is_teleporting 0) (user_fun SET_FADE_COUNT 0) )) (remove_object (get_object 1)) (set_aistate 0)))))) T) (def_char TELE2 (funs (ai_fun tp2_ai)) (flags (can_block T)) (states "art/chars/teleport.spe" (stopped "close") (running (seq "elec" 1 15)))) (defun bolder_ai () (if (or (eq (total_objects) 0) (not (eq (with_object (get_object 0) (aistate)) 0))) (if (eq (hp) 0) (progn (play_sound P_EXPLODE_SND 127 (x) (y)) (add_object EXPLODE1 (+ (x) (random 5)) (+ (y) (random 5)) 0) (add_object EXPLODE1 (+ (x) (random 5)) (+ (y) (random 5)) 2) (add_object EXPLODE1 (- (x) (random 5)) (- (y) (random 5)) 1) (add_object EXPLODE1 (- (x) (random 5)) (- (y) (random 5)) 2) (with_object (add_object SMALL_BOLDER (x) (y)) (progn (set_xvel -4) (set_yvel -8))) (with_object (add_object SMALL_BOLDER (x) (y)) (progn (set_xvel 4) (set_yvel -9))) (with_object (add_object SMALL_BOLDER (x) (y)) (progn (set_xvel 2) (set_yvel -5))) (with_object (add_object SMALL_BOLDER (x) (y)) (progn (set_xvel -3) (set_yvel -5))) (with_object (add_object SMALL_BOLDER (x) (y)) (progn (set_xvel -1) (set_yvel 2))) (add_object EXP_LIGHT (x) (y) 100) nil) (progn (next_picture) (set_yvel (+ (yvel) 1)) (let ((old_yv (yvel)) (old_xv (xvel)) (old_x (x)) (old_y (y)) (status (float_tick))) (let ((new_x (x)) (new_y (y)) (set_x old_x) (set_y old_y)) (platform_push (- new_x (x)) (- new_y (y))) (set_x new_x) (set_y new_y)) (hurt_radius (x) (y) 19 30 (me) 15) (if (not (eq status T));; T means we did not hit anything (let ((block_flags (car status))) (if (or (blocked_up block_flags) (blocked_down block_flags));; bounce up/down (progn (if (> (abs old_yv) 3) (play_sound SBALL_SND 127 (x) (y))) (set_xvel old_xv) (if (> old_yv 1) (set_yvel (- 2 old_yv)) (set_yvel (- 0 old_yv)))) (if (or (blocked_left block_flags) (blocked_right block_flags));; bounce left/right (progn (set_yvel old_yv) (set_xvel (- 0 old_xv)))))))) T)) T)) (defun bolder_cons () (set_xvel -4) (set_yvel 0)) (defun bold_dam (amount from hitx hity push_xvel push_yvel) (add_object EXPLODE3 (+ (x) (- 10 (random 20))) (- (y) (random 30)) 0) (damage_fun amount from hitx hity (/ push_xvel 10) (/ push_yvel 2))) (def_char BOLDER (funs (ai_fun bolder_ai) (damage_fun bold_dam) (constructor bolder_cons)) (flags (can_block T) (add_front T) (hurtable T)) (range 200 200) (abilities (start_hp 40)) (fields ("xvel" ai_xvel) ("yvel" ai_yvel) ("hp" ai_health) ) (states "art/bold.spe" (stopped '("bold0001.pcx" "bold0001.pcx" "bold0001.pcx" "bold0002.pcx" "bold0002.pcx" "bold0002.pcx" "bold0003.pcx" "bold0003.pcx" "bold0003.pcx" "bold0004.pcx" "bold0004.pcx" "bold0004.pcx")))) (defun bounce_move (left_stub right_stub up_stub down_stub nothing_stub) (let ((old_yv (yvel)) (old_xv (xvel)) (status (float_tick))) (if (not (eq status T)) ;; T means we did not hit anything (let ((block_flags (car status))) (if (blocked_up block_flags) ;; bounce up/down (progn (set_xvel old_xv) (if (> old_yv 1) (set_yvel (- 2 old_yv)) (set_yvel (- 0 old_yv))) (eval up_stub)) (if (blocked_down block_flags) (progn (set_xvel old_xv) (if (> old_yv 1) (set_yvel (- 2 old_yv)) (set_yvel (- 0 old_yv))) (eval down_stub)) (if (blocked_left block_flags) (progn (set_yvel old_yv) (set_xvel (- 0 old_xv)) (eval left_stub)) (if (blocked_right block_flags) (progn (set_yvel old_yv) (set_xvel (- 0 old_xv)) (eval right_stub))))))) (eval nothing_stub)))) (defun small_rock_ai () (next_picture) (set_yvel (+ (yvel) 1)) (bounce_move T T T '(progn (add_object EXPLODE1 (+ (x) (random 10)) (- (+ (random 5) (y)) 10) 0) (add_object EXPLODE1 (- (x) (random 10)) (- (- (y) (random 5)) 10) 2) (play_sound P_EXPLODE_SND 127 (x) (y)) (hurt_radius (x) (y) 40 15 (if (> (total_objects) 0) (get_object 0) nil) 20) nil) T)) (def_char SMALL_BOLDER (funs (ai_fun small_rock_ai)) (flags (add_front T) (unlistable T)) (states "art/bold.spe" (stopped "bsmall")))
411
0.863822
1
0.863822
game-dev
MEDIA
0.701949
game-dev
0.972553
1
0.972553
qreal/qreal
21,052
plugins/robots/generators/generatorBase/src/structurizator.cpp
/* Copyright 2018 Konstantin Batoev * * 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. */ #include "structurizator.h" #include <QtCore/QQueue> #include "structurizatorNodes/intermediateStructurizatorNode.h" #include "structurizatorNodes/blockStructurizatorNode.h" #include "structurizatorNodes/breakStructurizatorNode.h" #include "structurizatorNodes/ifStructurizatorNode.h" #include "structurizatorNodes/structurizatorNodeWithBreaks.h" #include "structurizatorNodes/selfLoopStructurizatorNode.h" #include "structurizatorNodes/simpleStructurizatorNode.h" #include "structurizatorNodes/switchStructurizatorNode.h" #include "structurizatorNodes/whileStructurizatorNode.h" using namespace generatorBase; Structurizator::Structurizator(QObject *parent) : QObject(parent) , mVerticesNumber(1) , mStartVertex(-1) , mMaxPostOrderTime(-1) { } IntermediateStructurizatorNode *Structurizator::performStructurization(const QSet<qReal::Id> &verticesIds , int startVertex , const QMap<int, QSet<int>> &followers , const QMap<qReal::Id, int> &vertexNumber , int verticesNumber) { for (const qReal::Id &id : verticesIds) { mInitialIds.insert(id); mMapIdToInt[id] = vertexNumber[id]; mVertices.insert(vertexNumber[id]); } mVerticesNumber = verticesNumber; mStartVertex = startVertex; for (const int v : followers.keys()) { for (const int u : followers[v]) { mFollowers[v].push_back(u); mPredecessors[u].push_back(v); } } calculatePostOrder(); calculateDominators(); createInitialNodesForIds(); bool somethingChanged = true; while (somethingChanged) { somethingChanged = false; int t = 0; while (t <= mMaxPostOrderTime && (mVertices.size() > 1 || !mFollowers[mStartVertex].isEmpty())) { int v = mPostOrder.key(t); QSet<int> reachUnder; QSet<QPair<int, int>> edgesToRemove = {}; QMap<QString, int> verticesRoles; if (isBlock(v, edgesToRemove, verticesRoles)) { reduceBlock(edgesToRemove, verticesRoles); } else if (isSwitch(v, edgesToRemove, verticesRoles)) { reduceSwitch(edgesToRemove, verticesRoles); } else if (isIfThenElse(v, edgesToRemove, verticesRoles)) { reduceIfThenElse(edgesToRemove, verticesRoles); } else if (isIfThen(v, edgesToRemove, verticesRoles)) { reduceIfThen(edgesToRemove, verticesRoles); } else if (isInfiniteLoop(v, edgesToRemove, verticesRoles)) { reduceInfiniteLoop(edgesToRemove, verticesRoles); } else if (isWhileLoop(v, edgesToRemove, verticesRoles)) { reduceWhileLoop(edgesToRemove, verticesRoles); } else if (isHeadOfCycle(v, reachUnder)) { int minTime = -1; for (const int vertex : reachUnder) { if (minTime == -1 || minTime > mPostOrder[vertex]) { minTime = mPostOrder[vertex]; } } QMap<int, QSet<int>> nodesWithExits; int commonExit = -1; bool isCycle = isCycleWithBreaks(reachUnder, nodesWithExits, commonExit); QSet<int> verticesWithExits = nodesWithExits.keys().toSet(); if (!isCycle) { t++; appendNodesDetectedAsNodeWithExit(verticesWithExits, v); continue; } if (!nodesWithExits.isEmpty() && checkNodes(verticesWithExits)) { for (const int vertexInsideLoop : nodesWithExits.keys()) { for (const int vertexOutsideLoop : nodesWithExits[vertexInsideLoop]) { if (minTime > mPostOrder[vertexOutsideLoop]) { minTime = mPostOrder[vertexOutsideLoop]; } } } reduceConditionsWithBreaks(v, nodesWithExits, commonExit); t = minTime; somethingChanged = true; appendNodesDetectedAsNodeWithExit(verticesWithExits, v); continue; } } if (verticesRoles.size()) { t -= (verticesRoles.size() - 1); if (t < 0) { t = 0; } somethingChanged = true; } else { t++; } } } if (mVertices.size() == 1) { return mTrees[mStartVertex]; } return nullptr; } bool Structurizator::isBlock(int v, QSet<QPair<int, int>> &edgesToRemove, QMap<QString, int> &verticesRoles) { if (outgoingEdgesNumber(v) != 1) { return false; } int u = mFollowers[v].first(); if (outgoingEdgesNumber(u) <= 1 && incomingEdgesNumber(u) == 1 && u != v && mDominators[u].contains(v)) { verticesRoles["block1"] = v; verticesRoles["block2"] = u; edgesToRemove.insert(qMakePair(v, u)); return true; } return false; } bool Structurizator::isIfThenElse(int v, QSet<QPair<int, int>> &edgesToRemove, QMap<QString, int> &verticesRoles) { if (outgoingEdgesNumber(v) != 2) { return false; } int u1 = mFollowers[v].first(); int u2 = mFollowers[v].last(); if (incomingEdgesNumber(u1) != 1 || incomingEdgesNumber(u2) != 1 || mDominators[v].contains(u1) || mDominators[v].contains(u2)) { return false; } if ((outgoingEdgesNumber(u1) == 0 && outgoingEdgesNumber(u2) == 0) || (outgoingEdgesNumber(u1) == 1 && outgoingEdgesNumber(u2) == 1 && mFollowers[u1].first() == mFollowers[u2].first())) { verticesRoles["condition"] = v; verticesRoles["then"] = u1; verticesRoles["else"] = u2; if (outgoingEdgesNumber(u1) > 0) { verticesRoles["exit"] = mFollowers[u1].first(); } edgesToRemove += { qMakePair(v, u1), qMakePair(v, u2) }; return true; } return false; } bool Structurizator::isIfThen(int v, QSet<QPair<int, int>> &edgesToRemove, QMap<QString, int> &verticesRoles) { if (outgoingEdgesNumber(v) != 2) { return false; } int u1 = mFollowers[v].first(); int u2 = mFollowers[v].last(); int thenNumber = -1; int elseNumber = -1; if (checkIfThenHelper(u1, u2)) { thenNumber = u1; elseNumber = u2; } else if (checkIfThenHelper(u2, u1)) { thenNumber = u2; elseNumber = u1; } if (thenNumber == -1 || elseNumber == v || mDominators[v].contains(thenNumber)) { return false; } verticesRoles["condition"] = v; verticesRoles["then"] = thenNumber; if (outgoingEdgesNumber(thenNumber) > 0) { verticesRoles["exit"] = mFollowers[thenNumber].first(); } edgesToRemove = { qMakePair(v, u1), qMakePair(v, u2) }; return true; } bool Structurizator::isSwitch(int v, QSet<QPair<int, int>> &edgesToRemove, QMap<QString, int> &verticesRoles) { if (outgoingEdgesNumber(v) < 3) { return false; } int exit = -1; QSet<int> vertices = {}; QSet<QPair<int, int>> edges = {}; for (const int u : mFollowers[v]) { if (incomingEdgesNumber(u) != 1 || outgoingEdgesNumber(u) >= 2) { if (exit == -1) { exit = u; } else if (exit != u) { return false; } } else { if (outgoingEdgesNumber(u) == 1) { int m = mFollowers[u].first(); if (exit == -1) { exit = m; } else if (m != exit) { return false; } } vertices.insert(u); } if (u != exit && mDominators[v].contains(u)) { return false; } edges.insert(qMakePair(v, u)); } verticesRoles["head"] = v; edgesToRemove = edges; int cnt = 1; for (int u : vertices) { verticesRoles[QString::number(cnt)] = u; cnt++; } verticesRoles["exit"] = exit; return true; } bool Structurizator::isInfiniteLoop(int v, QSet<QPair<int, int>> &edgesToRemove, QMap<QString, int> &verticesRoles) { if (outgoingEdgesNumber(v) != 1) { return false; } int u = mFollowers[v].first(); if (u != v) { return false; } verticesRoles["body"] = v; edgesToRemove.insert(qMakePair(v, v)); return true; } bool Structurizator::isWhileLoop(int v, QSet<QPair<int, int>> &edgesToRemove, QMap<QString, int> &verticesRoles) { if (outgoingEdgesNumber(v) != 2) { return false; } int u1 = mFollowers[v].first(); int u2 = mFollowers[v].last(); int bodyNumber = -1; int exitNumber = -1; if (checkWhileLoopHelper(v, u1)) { bodyNumber = u1; exitNumber = u2; } else if (checkWhileLoopHelper(v, u2)) { bodyNumber = u2; exitNumber = u1; } if (bodyNumber == -1) { return false; } if (mDominators[v].contains(bodyNumber)) { return false; } edgesToRemove = { qMakePair(v, bodyNumber), qMakePair(bodyNumber, v) }; verticesRoles["head"] = v; verticesRoles["body"] = bodyNumber; verticesRoles["exit"] = exitNumber; return true; } bool Structurizator::checkIfThenHelper(int thenNumber, int exitNumber) { if (incomingEdgesNumber(thenNumber) == 1 && outgoingEdgesNumber(thenNumber) == 1) { if (mFollowers[thenNumber].contains(exitNumber)) { return true; } } return false; } bool Structurizator::checkWhileLoopHelper(int head, int body) { if (incomingEdgesNumber(body) == 1 && outgoingEdgesNumber(body) == 1) { int w = mFollowers[body].first(); if (w == head) { return true; } } return false; } bool Structurizator::isCycleWithBreaks(QSet<int> &reachUnder, QMap<int, QSet<int>> &nodesWithExits, int &commonExit) { bool result = findCommonExit(reachUnder, nodesWithExits, commonExit); if (!result) { return false; } return checkCommonExitUniqueness(commonExit, nodesWithExits); } bool Structurizator::isHeadOfCycle(int v, QSet<int> &reachUnder) { QQueue<int> queueForReachUnder; for (const int u : mPredecessors[v]) { if (mDominators[u].contains(v)) { queueForReachUnder.push_back(u); } } while (!queueForReachUnder.empty()) { int u = queueForReachUnder.front(); queueForReachUnder.pop_front(); reachUnder.insert(u); for (const int w : mPredecessors[u]) { if (mDominators[w].contains(v) && !reachUnder.contains(w)) { queueForReachUnder.push_back(w); } } } return !reachUnder.isEmpty(); } bool Structurizator::findCommonExit(QSet<int> &reachUnder, QMap<int, QSet<int>> &nodesWithExits, int &commonExit) { commonExit = -1; QSet<int> exits; for (const int u : reachUnder) { for (const int w : mFollowers[u]) { if (!reachUnder.contains(w)) { if (exits.contains(w) || incomingEdgesNumber(w) > 1) { if (commonExit != -1 && commonExit != w) { return false; } commonExit = w; } exits.insert(w); nodesWithExits[u].insert(w); } } } if (commonExit != -1) { return true; } QList<int> regionToFindCommonChild; for (const int exitNumber : exits) { if (outgoingEdgesNumber(exitNumber) == 1) { regionToFindCommonChild.append(exitNumber); } else if (outgoingEdgesNumber(exitNumber) > 1) { if (commonExit == -1) { // we have found post-cycle execution point commonExit = exitNumber; } else if (commonExit != exitNumber) { // each cycle can have at most 1 point to transfer execution return false; } } } if (commonExit != -1) { return true; } // assume that one exit point is commonChild if (regionToFindCommonChild.size() == 1) { commonExit = regionToFindCommonChild.first(); return true; } for (const int exitNumber : regionToFindCommonChild) { for (const int postExit : mFollowers[exitNumber]) { if (commonExit == -1) { commonExit = postExit; } else if (commonExit != postExit) { return false; } } } return true; } bool Structurizator::checkCommonExitUniqueness(int commonExit, const QMap<int, QSet<int>> &nodesWithExits) { for (const int vertexFromCycle : nodesWithExits.keys()) { for (const int exit : nodesWithExits[vertexFromCycle]) { if (commonExit == exit) { continue; } if (incomingEdgesNumber(exit) != 1 || outgoingEdgesNumber(exit) >= 2) { return false; } if (outgoingEdgesNumber(exit) == 1 && commonExit != mFollowers[exit].first()) { return false; } } } return true; } bool Structurizator::checkNodes(const QSet<int> &verticesWithExits) { QSet<int> testSet = mWasPreviouslyDetectedAsNodeWithExit.keys().toSet(); testSet.intersect(verticesWithExits); return testSet.isEmpty(); } void Structurizator::reduceBlock(QSet<QPair<int, int>> &edgesToRemove, QMap<QString, int> &verticesRoles) { BlockStructurizatorNode *block = new BlockStructurizatorNode(mTrees[verticesRoles["block1"]] , mTrees[verticesRoles["block2"]], this); replace(appendVertex(block), edgesToRemove, verticesRoles); } void Structurizator::reduceIfThenElse(QSet<QPair<int, int>> &edgesToRemove, QMap<QString, int> &verticesRoles) { IntermediateStructurizatorNode *exit = nullptr; if (verticesRoles.contains("exit")) { exit = mTrees[verticesRoles["exit"]]; verticesRoles.remove("exit"); } IfStructurizatorNode *ifNode = new IfStructurizatorNode(mTrees[verticesRoles["condition"]] , mTrees[verticesRoles["then"]] , mTrees[verticesRoles["else"]] , exit , this); replace(appendVertex(ifNode), edgesToRemove, verticesRoles); } void Structurizator::reduceIfThen(QSet<QPair<int, int>> &edgesToRemove, QMap<QString, int> &verticesRoles) { IntermediateStructurizatorNode *exit = nullptr; if (verticesRoles.contains("exit")) { exit = mTrees[verticesRoles["exit"]]; verticesRoles.remove("exit"); } IfStructurizatorNode *ifNode = new IfStructurizatorNode(mTrees[verticesRoles["condition"]], mTrees[verticesRoles["then"]] , nullptr , exit , this); replace(appendVertex(ifNode), edgesToRemove, verticesRoles); } void Structurizator::reduceSwitch(QSet<QPair<int, int>> &edgesToRemove, QMap<QString, int> &verticesRoles) { int v = verticesRoles["head"]; int exitNodeNumber = verticesRoles["exit"]; verticesRoles.remove("exit"); QSet<int> otherVerteces = verticesRoles.values().toSet(); otherVerteces.remove(v); QList<IntermediateStructurizatorNode *> branches; for (const int u : mFollowers[v]) { if (otherVerteces.contains(u)) { branches.append(mTrees[u]); } else { branches.append(new SimpleStructurizatorNode(qReal::Id(), this)); } } IntermediateStructurizatorNode *exitNode = exitNodeNumber == -1 ? nullptr : mTrees[exitNodeNumber]; SwitchStructurizatorNode *switchNode = new SwitchStructurizatorNode(mTrees[v], branches, exitNode, this); replace(appendVertex(switchNode), edgesToRemove, verticesRoles); } void Structurizator::reduceInfiniteLoop(QSet<QPair<int, int>> &edgesToRemove, QMap<QString, int> &verticesRoles) { SelfLoopStructurizatorNode *loopNode = new SelfLoopStructurizatorNode(mTrees[verticesRoles["body"]], this); replace(appendVertex(loopNode), edgesToRemove, verticesRoles); } void Structurizator::reduceWhileLoop(QSet<QPair<int, int>> &edgesToRemove, QMap<QString, int> &verticesRoles) { WhileStructurizatorNode *whileNode = new WhileStructurizatorNode(mTrees[verticesRoles["head"]] , mTrees[verticesRoles["body"]] , mTrees[verticesRoles["exit"]] , this); verticesRoles.remove("exit"); replace(appendVertex(whileNode), edgesToRemove, verticesRoles); } void Structurizator::reduceConditionsWithBreaks(int &v, QMap<int, QSet<int>> &nodesWithExits, int commonExit) { for (const int u : nodesWithExits.keys()) { QList<IntermediateStructurizatorNode *> exitBranches; QSet<QPair<int, int>> edgesToRemove; QSet<int> vertices = {u}; for (const int exit : nodesWithExits[u]) { qReal::Id id = mTrees[exit]->firstId(); IntermediateStructurizatorNode *node; if (exit == commonExit) { node = new BreakStructurizatorNode(id, this); } else { node = new BlockStructurizatorNode(mTrees[exit], new BreakStructurizatorNode(id, this), this); vertices.insert(exit); if (mFollowers[exit].contains(commonExit)) { edgesToRemove.insert(qMakePair(exit, commonExit)); } } edgesToRemove.insert(qMakePair(u, exit)); exitBranches.append(node); } StructurizatorNodeWithBreaks *nodeWithBreaks = new StructurizatorNodeWithBreaks(mTrees[u] , exitBranches, this); replace(appendVertex(nodeWithBreaks), edgesToRemove, vertices); if (u == v) { v = mTrees.key(nodeWithBreaks); } } // adding edge from head to common exit if (commonExit != -1 && !mFollowers[v].contains(commonExit)) { mFollowers[v].push_back(commonExit); mPredecessors[commonExit].push_back(v); } } void Structurizator::replace(int newNodeNumber, QSet<QPair<int, int>> &edgesToRemove, QSet<int> &vertices) { updateEdges(newNodeNumber, edgesToRemove, vertices); updatePostOrder(newNodeNumber, vertices); updateDominators(newNodeNumber, vertices); updateVertices(newNodeNumber, vertices); removeNodesPreviouslyDetectedAsNodeWithExit(vertices); } void Structurizator::replace(int newNodeNumber, QSet<QPair<int, int>> &edgesToRemove, QMap<QString, int> &verticesRoles) { QSet<int> vertices = verticesRoles.values().toSet(); replace(newNodeNumber, edgesToRemove, vertices); } void Structurizator::updateEdges(int newNodeNumber, QSet<QPair<int, int>> &edgesToRemove, QSet<int> &vertices) { for (const QPair<int, int> p : edgesToRemove) { mFollowers[p.first].removeAll(p.second); mPredecessors[p.second].removeAll(p.first); } const QMap<int, QVector<int>> followers = mFollowers; for (const int v : mVertices) { for (const int u : followers[v]) { int newV = vertices.contains(v) ? newNodeNumber : v; int newU = vertices.contains(u) ? newNodeNumber : u; if (newU == newNodeNumber || newV == newNodeNumber) { // removing old information mFollowers[v].removeAll(u); mPredecessors[u].removeAll(v); // inserting new information if (!mFollowers[newV].contains(newU)) { mFollowers[newV].push_back(newU); mPredecessors[newU].push_back(newV); } } } } for (const int v : vertices) { mFollowers.remove(v); mPredecessors.remove(v); } } void Structurizator::updatePostOrder(int newNodeNumber, QSet<int> &verteces) { int maximum = -1; for (int v : verteces) { if (maximum == -1 || maximum < mPostOrder[v]) { maximum = mPostOrder[v]; } } mPostOrder[newNodeNumber] = maximum; for (int v : verteces) { mPostOrder.remove(v); } mMaxPostOrderTime = mMaxPostOrderTime - verteces.size() + 1; QVector<int> times = mPostOrder.values().toVector(); std::sort(times.begin(), times.end()); for (int i = 0; i <= mMaxPostOrderTime; i++) { int v = mPostOrder.key(times[i]); mPostOrder[v] = i; } } void Structurizator::updateDominators(int newNodeNumber, QSet<int> &vertices) { // others for (int v : mPostOrder.keys()) { QSet<int> tempSet = mDominators[v]; tempSet.intersect(vertices); if (!tempSet.isEmpty()) { mDominators[v].subtract(vertices); mDominators[v].insert(newNodeNumber); } } // new QSet<int> doms = mVertices; for (int v : vertices) { doms.intersect(mDominators[v]); } doms.subtract(vertices); doms.insert(newNodeNumber); mDominators[newNodeNumber] = doms; // old for (int v : vertices) { mDominators.remove(v); } } void Structurizator::updateVertices(int newNodeNumber, QSet<int> &vertices) { mStartVertex = vertices.contains(mStartVertex) ? newNodeNumber : mStartVertex; mVertices.subtract(vertices); mVertices.insert(newNodeNumber); } void Structurizator::removeNodesPreviouslyDetectedAsNodeWithExit(QSet<int> &vertices) { for (const int v : vertices) { mWasPreviouslyDetectedAsNodeWithExit.remove(v); } } void Structurizator::calculateDominators() { for (const int u : mVertices) { mDominators[u] = mVertices; } mDominators[mStartVertex] = { mStartVertex }; bool somethingChanged = true; while (somethingChanged) { somethingChanged = false; for (const int v : mVertices) { if (v == mStartVertex) { continue; } QSet<int> doms = mVertices; for (const int u : mPredecessors[v]) { doms = doms.intersect(mDominators[u]); } doms.insert(v); if (doms != mDominators[v]) { mDominators[v] = doms; somethingChanged = true; } } } } void Structurizator::findStartVertex() { for (const int u : mVertices) { if (mPredecessors[u].isEmpty()) { mStartVertex = u; return; } } } void Structurizator::calculatePostOrder() { mPostOrder.clear(); QMap<int, bool> used; for (const int v : mVertices) { used[v] = false; } int currentTime = 0; dfs(mStartVertex, currentTime, used); mMaxPostOrderTime = currentTime - 1; } void Structurizator::createInitialNodesForIds() { for (const int v : mVertices) { mTrees[v] = new SimpleStructurizatorNode(mMapIdToInt.key(v), this); } } void Structurizator::dfs(int v, int &currentTime, QMap<int, bool> &used) { used[v] = true; for (const int u : mFollowers[v]) { if (!used[u]) { dfs(u, currentTime, used); } } mPostOrder[v] = currentTime; currentTime++; } void Structurizator::appendNodesDetectedAsNodeWithExit(QSet<int> &vertices, int cycleHead) { for (const int v : vertices) { mWasPreviouslyDetectedAsNodeWithExit[v] = cycleHead; } } int Structurizator::appendVertex(IntermediateStructurizatorNode *node) { mVerticesNumber++; mTrees[mVerticesNumber] = node; mVertices.insert(mVerticesNumber); return mVerticesNumber; } int Structurizator::outgoingEdgesNumber(int v) const { return mFollowers[v].size(); } int Structurizator::incomingEdgesNumber(int v) const { return mPredecessors[v].size(); }
411
0.897677
1
0.897677
game-dev
MEDIA
0.41574
game-dev
0.977741
1
0.977741
Tropicraft/Tropicraft
1,351
src/main/java/net/tropicraft/core/common/network/message/ClientboundMixerStartPacket.java
package net.tropicraft.core.common.network.message; import io.netty.buffer.ByteBuf; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.core.BlockPos; import net.minecraft.network.codec.StreamCodec; import net.minecraft.network.protocol.common.custom.CustomPacketPayload; import net.neoforged.neoforge.network.handling.IPayloadContext; import net.tropicraft.Tropicraft; import net.tropicraft.core.common.block.tileentity.DrinkMixerBlockEntity; public record ClientboundMixerStartPacket(BlockPos pos) implements CustomPacketPayload { public static final Type<ClientboundMixerStartPacket> TYPE = new Type<>(Tropicraft.location("mixer_start")); public static final StreamCodec<ByteBuf, ClientboundMixerStartPacket> STREAM_CODEC = StreamCodec.composite( BlockPos.STREAM_CODEC, ClientboundMixerStartPacket::pos, ClientboundMixerStartPacket::new ); public static void handle(ClientboundMixerStartPacket packet, IPayloadContext ctx) { ClientLevel level = Minecraft.getInstance().level; if (level != null && level.getBlockEntity(packet.pos) instanceof DrinkMixerBlockEntity drinkMixer) { drinkMixer.setMixing(); } } @Override public Type<ClientboundMixerStartPacket> type() { return TYPE; } }
411
0.73516
1
0.73516
game-dev
MEDIA
0.950073
game-dev,networking
0.561692
1
0.561692
otland/forgottenserver
16,239
src/creature.h
// Copyright 2023 The Forgotten Server Authors. All rights reserved. // Use of this source code is governed by the GPL-2.0 License that can be found in the LICENSE file. #ifndef FS_CREATURE_H #define FS_CREATURE_H #include "const.h" #include "creatureevent.h" #include "enums.h" #include "map.h" #include "position.h" #include "tile.h" class Condition; class Container; class Item; class Monster; class Npc; class Player; using ConditionList = std::list<Condition*>; using CreatureEventList = std::list<CreatureEvent*>; using CreatureIconHashMap = std::unordered_map<CreatureIcon_t, uint16_t>; enum slots_t : uint8_t { CONST_SLOT_WHEREEVER = 0, CONST_SLOT_HEAD = 1, CONST_SLOT_NECKLACE = 2, CONST_SLOT_BACKPACK = 3, CONST_SLOT_ARMOR = 4, CONST_SLOT_RIGHT = 5, CONST_SLOT_LEFT = 6, CONST_SLOT_LEGS = 7, CONST_SLOT_FEET = 8, CONST_SLOT_RING = 9, CONST_SLOT_AMMO = 10, CONST_SLOT_STORE_INBOX = 11, CONST_SLOT_FIRST = CONST_SLOT_HEAD, CONST_SLOT_LAST = CONST_SLOT_AMMO, }; struct FindPathParams { bool fullPathSearch = true; bool clearSight = true; bool allowDiagonal = true; bool keepDistance = false; bool summonTargetMaster = false; int32_t maxSearchDist = 0; int32_t minTargetDist = -1; int32_t maxTargetDist = -1; }; static constexpr int32_t EVENT_CREATURECOUNT = 10; static constexpr int32_t EVENT_CREATURE_THINK_INTERVAL = 1000; static constexpr int32_t EVENT_CHECK_CREATURE_INTERVAL = (EVENT_CREATURE_THINK_INTERVAL / EVENT_CREATURECOUNT); static constexpr uint32_t CREATURE_ID_MIN = 0x10000000; static constexpr uint32_t CREATURE_ID_MAX = std::numeric_limits<uint32_t>::max(); class FrozenPathingConditionCall { public: explicit FrozenPathingConditionCall(Position targetPos) : targetPos(std::move(targetPos)) {} bool operator()(const Position& startPos, const Position& testPos, const FindPathParams& fpp, int32_t& bestMatchDist) const; bool isInRange(const Position& startPos, const Position& testPos, const FindPathParams& fpp) const; private: Position targetPos; }; ////////////////////////////////////////////////////////////////////// // Defines the Base class for all creatures and base functions which // every creature has class Creature : virtual public Thing { protected: Creature(); public: static double speedA, speedB, speedC; virtual ~Creature(); // non-copyable Creature(const Creature&) = delete; Creature& operator=(const Creature&) = delete; Creature* getCreature() override final { return this; } const Creature* getCreature() const override final { return this; } virtual Player* getPlayer() { return nullptr; } virtual const Player* getPlayer() const { return nullptr; } virtual Npc* getNpc() { return nullptr; } virtual const Npc* getNpc() const { return nullptr; } virtual Monster* getMonster() { return nullptr; } virtual const Monster* getMonster() const { return nullptr; } virtual const std::string& getName() const = 0; virtual const std::string& getNameDescription() const = 0; virtual CreatureType_t getType() const = 0; virtual void setID() = 0; void setRemoved() { isInternalRemoved = true; } uint32_t getID() const { return id; } virtual void removeList() = 0; virtual void addList() = 0; virtual bool canSee(const Position& pos) const; virtual bool canSeeCreature(const Creature* creature) const; virtual RaceType_t getRace() const { return RACE_NONE; } virtual Skulls_t getSkull() const { return skull; } virtual Skulls_t getSkullClient(const Creature* creature) const { return creature->getSkull(); } void setSkull(Skulls_t newSkull); Direction getDirection() const { return direction; } void setDirection(Direction dir) { direction = dir; } bool isHealthHidden() const { return hiddenHealth; } void setHiddenHealth(bool b) { hiddenHealth = b; } int32_t getThrowRange() const override final { return 1; } bool isPushable() const override { return getWalkDelay() <= 0; } bool isRemoved() const override final { return isInternalRemoved; } virtual bool canSeeInvisibility() const { return false; } virtual bool isInGhostMode() const { return false; } virtual bool canSeeGhostMode(const Creature*) const { return false; } int32_t getWalkDelay(Direction dir) const; int32_t getWalkDelay() const; int64_t getTimeSinceLastMove() const; int64_t getEventStepTicks(bool onlyDelay = false) const; int64_t getStepDuration(Direction dir) const; int64_t getStepDuration() const; virtual int32_t getStepSpeed() const { return getSpeed(); } int32_t getSpeed() const { return baseSpeed + varSpeed; } void setSpeed(int32_t varSpeedDelta) { int32_t oldSpeed = getSpeed(); varSpeed = varSpeedDelta; if (getSpeed() <= 0) { stopEventWalk(); cancelNextWalk = true; } else if (oldSpeed <= 0 && !listWalkDir.empty()) { addEventWalk(); } } void setBaseSpeed(uint32_t newBaseSpeed) { baseSpeed = newBaseSpeed; } uint32_t getBaseSpeed() const { return baseSpeed; } int32_t getHealth() const { return health; } virtual int32_t getMaxHealth() const { return healthMax; } bool isDead() const { return health <= 0; } void setDrunkenness(uint8_t newDrunkenness) { drunkenness = newDrunkenness; } uint8_t getDrunkenness() const { return drunkenness; } const Outfit_t getCurrentOutfit() const { return currentOutfit; } void setCurrentOutfit(Outfit_t outfit) { currentOutfit = outfit; } const Outfit_t getDefaultOutfit() const { return defaultOutfit; } bool isInvisible() const; ZoneType_t getZone() const { const Tile* tile = getTile(); if (!tile) { return ZONE_NORMAL; } return tile->getZone(); } // creature icons CreatureIconHashMap& getIcons() { return creatureIcons; } const CreatureIconHashMap& getIcons() const { return creatureIcons; } void updateIcons() const; // walk functions void startAutoWalk(); void startAutoWalk(Direction direction); void startAutoWalk(const std::vector<Direction>& listDir); void addEventWalk(bool firstStep = false); void stopEventWalk(); virtual void goToFollowCreature() = 0; void updateFollowCreaturePath(FindPathParams& fpp); // walk events virtual void onWalk(Direction& dir); virtual void onWalkAborted() {} virtual void onWalkComplete() {} // follow functions Creature* getFollowCreature() const { return followCreature; } virtual void setFollowCreature(Creature* creature); virtual void removeFollowCreature(); virtual bool canFollowCreature(Creature* creature); virtual bool isFollowingCreature(Creature* creature) { return followCreature == creature; } // follow events virtual void onFollowCreature(const Creature*); virtual void onUnfollowCreature(); // Pathfinding functions bool isFollower(const Creature* creature); void addFollower(Creature* creature); void removeFollower(Creature* creature); void removeFollowers(); void releaseFollowers(); // Pathfinding events void updateFollowersPaths(); // combat functions Creature* getAttackedCreature() { return attackedCreature; } virtual void setAttackedCreature(Creature* creature); virtual void removeAttackedCreature(); virtual bool canAttackCreature(Creature* creature); virtual bool isAttackingCreature(Creature* creature) { return attackedCreature == creature; } virtual BlockType_t blockHit(Creature* attacker, CombatType_t combatType, int32_t& damage, bool checkDefense = false, bool checkArmor = false, bool field = false, bool ignoreResistances = false); bool setMaster(Creature* newMaster); void removeMaster() { if (master) { master = nullptr; decrementReferenceCounter(); } } bool isSummon() const { return master != nullptr; } Creature* getMaster() const { return master; } const std::list<Creature*>& getSummons() const { return summons; } virtual int32_t getArmor() const { return 0; } virtual int32_t getDefense() const { return 0; } virtual float getAttackFactor() const { return 1.0f; } virtual float getDefenseFactor() const { return 1.0f; } virtual uint8_t getSpeechBubble() const { return SPEECHBUBBLE_NONE; } bool addCondition(Condition* condition, bool force = false); bool addCombatCondition(Condition* condition); void removeCondition(ConditionType_t type, ConditionId_t conditionId, bool force = false); void removeCondition(ConditionType_t type, bool force = false); void removeCondition(Condition* condition, bool force = false); void removeCombatCondition(ConditionType_t type); Condition* getCondition(ConditionType_t type) const; Condition* getCondition(ConditionType_t type, ConditionId_t conditionId, uint32_t subId = 0) const; void executeConditions(uint32_t interval); bool hasCondition(ConditionType_t type, uint32_t subId = 0) const; virtual bool isImmune(ConditionType_t type) const; virtual bool isImmune(CombatType_t type) const; virtual bool isSuppress(ConditionType_t type) const; virtual uint32_t getDamageImmunities() const { return 0; } virtual uint32_t getConditionImmunities() const { return 0; } virtual uint32_t getConditionSuppressions() const { return 0; } virtual bool isAttackable() const { return true; } virtual void changeHealth(int32_t healthChange, bool sendHealthChange = true); void gainHealth(Creature* healer, int32_t healthGain); virtual void drainHealth(Creature* attacker, int32_t damage); virtual bool challengeCreature(Creature*, bool) { return false; } CreatureVector getKillers(); void onDeath(); virtual uint64_t getGainedExperience(Creature* attacker) const; void addDamagePoints(Creature* attacker, int32_t damagePoints); bool hasBeenAttacked(uint32_t attackerId); // combat event functions virtual void onAddCondition(ConditionType_t type); virtual void onAddCombatCondition(ConditionType_t type); virtual void onEndCondition(ConditionType_t type); void onTickCondition(ConditionType_t type, bool& bRemove); virtual void onCombatRemoveCondition(Condition* condition); virtual void onAttackedCreature(Creature*, bool = true) {} virtual void onAttacked(); virtual void onAttackedCreatureDrainHealth(Creature* target, int32_t points); virtual void onTargetCreatureGainHealth(Creature*, int32_t) {} virtual bool onKilledCreature(Creature* target, bool lastHit = true); virtual void onGainExperience(uint64_t gainExp, Creature* target); virtual void onAttackedCreatureBlockHit(BlockType_t) {} virtual void onBlockHit() {} virtual void onChangeZone(ZoneType_t zone); virtual void onAttackedCreatureChangeZone(ZoneType_t zone); virtual void onIdleStatus(); virtual LightInfo getCreatureLight() const; virtual void setNormalCreatureLight(); void setCreatureLight(LightInfo lightInfo); virtual void onThink(uint32_t interval); virtual void forceUpdatePath(); void onAttacking(uint32_t interval); virtual void onWalk(); virtual bool getNextStep(Direction& dir, uint32_t& flags); virtual void onAddTileItem(const Tile*, const Position&) {} virtual void onUpdateTileItem(const Tile*, const Position&, const Item*, const ItemType&, const Item*, const ItemType&) {} virtual void onRemoveTileItem(const Tile*, const Position&, const ItemType&, const Item*) {} virtual void onCreatureAppear(Creature* creature, bool isLogin); virtual void onRemoveCreature(Creature* creature, bool isLogout); virtual void onCreatureMove(Creature* creature, const Tile* newTile, const Position& newPos, const Tile* oldTile, const Position& oldPos, bool teleport); virtual void onAttackedCreatureDisappear(bool) {} virtual void onFollowCreatureDisappear(bool) {} virtual void onCreatureSay(Creature*, SpeakClasses, const std::string&) {} virtual void onPlacedCreature() {} virtual bool getCombatValues(int32_t&, int32_t&) { return false; } size_t getSummonCount() const { return summons.size(); } void setDropLoot(bool lootDrop) { this->lootDrop = lootDrop; } void setSkillLoss(bool skillLoss) { this->skillLoss = skillLoss; } void setUseDefense(bool useDefense) { canUseDefense = useDefense; } void setMovementBlocked(bool state) { movementBlocked = state; cancelNextWalk = true; } bool isMovementBlocked() const { return movementBlocked; } // creature script events bool registerCreatureEvent(const std::string& name); bool unregisterCreatureEvent(const std::string& name); bool hasParent() const override { return getParent(); } Cylinder* getParent() const override final { return tile; } void setParent(Cylinder* cylinder) override final { tile = static_cast<Tile*>(cylinder); position = tile->getPosition(); } const Position& getPosition() const override final { return position; } Tile* getTile() override final { return tile; } const Tile* getTile() const override final { return tile; } const Position& getLastPosition() const { return lastPosition; } void setLastPosition(Position newLastPos) { lastPosition = newLastPos; } static bool canSee(const Position& myPos, const Position& pos, int32_t viewRangeX, int32_t viewRangeY); double getDamageRatio(Creature* attacker) const; bool getPathTo(const Position& targetPos, std::vector<Direction>& dirList, const FindPathParams& fpp) const; bool getPathTo(const Position& targetPos, std::vector<Direction>& dirList, int32_t minTargetDist, int32_t maxTargetDist, bool fullPathSearch = true, bool clearSight = true, int32_t maxSearchDist = 0) const; void incrementReferenceCounter() { ++referenceCounter; } void decrementReferenceCounter() { if (--referenceCounter == 0) { delete this; } } virtual void setStorageValue(uint32_t key, std::optional<int32_t> value, bool isSpawn = false); virtual std::optional<int32_t> getStorageValue(uint32_t key) const; decltype(auto) getStorageMap() const { return storageMap; } protected: struct CountBlock_t { int32_t total; int64_t ticks; }; Position position; using CountMap = std::map<uint32_t, CountBlock_t>; CountMap damageMap; std::list<Creature*> summons; CreatureEventList eventsList; ConditionList conditions; CreatureIconHashMap creatureIcons; std::vector<Direction> listWalkDir; Tile* tile = nullptr; Creature* attackedCreature = nullptr; Creature* master = nullptr; Creature* followCreature = nullptr; std::vector<Creature*> followers; uint64_t lastStep = 0; int64_t lastPathUpdate = 0; uint32_t referenceCounter = 0; uint32_t id = 0; uint32_t scriptEventsBitField = 0; uint32_t eventWalk = 0; uint32_t walkUpdateTicks = 0; uint32_t lastHitCreatureId = 0; uint32_t blockCount = 0; uint32_t blockTicks = 0; uint32_t lastStepCost = 1; uint32_t baseSpeed = 220; int32_t varSpeed = 0; int32_t health = 1000; int32_t healthMax = 1000; uint8_t drunkenness = 0; Outfit_t currentOutfit; Outfit_t defaultOutfit; uint16_t currentMount; Position lastPosition; LightInfo internalLight; Direction direction = DIRECTION_SOUTH; Skulls_t skull = SKULL_NONE; bool isInternalRemoved = false; bool creatureCheck = false; bool inCheckCreaturesVector = false; bool skillLoss = true; bool lootDrop = true; bool cancelNextWalk = false; bool hasFollowPath = false; bool hiddenHealth = false; bool canUseDefense = true; bool movementBlocked = false; // creature script events bool hasEventRegistered(CreatureEventType_t event) const { return (0 != (scriptEventsBitField & (static_cast<uint32_t>(1) << event))); } CreatureEventList getCreatureEvents(CreatureEventType_t type); void onCreatureDisappear(const Creature* creature, bool isLogout); virtual void doAttacking(uint32_t) {} virtual bool hasExtraSwing() { return false; } virtual uint64_t getLostExperience() const { return 0; } virtual void dropLoot(Container*, Creature*) {} virtual uint16_t getLookCorpse() const { return 0; } virtual void getPathSearchParams(const Creature* creature, FindPathParams& fpp) const; virtual void death(Creature*) {} virtual bool dropCorpse(Creature* lastHitCreature, Creature* mostDamageCreature, bool lastHitUnjustified, bool mostDamageUnjustified); virtual Item* getCorpse(Creature* lastHitCreature, Creature* mostDamageCreature); friend class Game; friend class Map; friend class LuaScriptInterface; private: std::map<uint32_t, int32_t> storageMap; }; #endif // FS_CREATURE_H
411
0.953681
1
0.953681
game-dev
MEDIA
0.926035
game-dev
0.693946
1
0.693946
I-asked/downbge
2,619
source/gameengine/GameLogic/SCA_IScene.h
/* * ***** BEGIN GPL LICENSE BLOCK ***** * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. * All rights reserved. * * The Original Code is: all of this file. * * Contributor(s): none yet. * * ***** END GPL LICENSE BLOCK ***** */ /** \file SCA_IScene.h * \ingroup gamelogic */ #ifndef __SCA_ISCENE_H__ #define __SCA_ISCENE_H__ #include <vector> #include "STR_String.h" #include "RAS_2DFilterManager.h" #ifdef WITH_CXX_GUARDEDALLOC #include "MEM_guardedalloc.h" #endif #define DEBUG_MAX_DISPLAY 100 struct SCA_DebugProp { class CValue* m_obj; STR_String m_name; SCA_DebugProp(); ~SCA_DebugProp(); }; class SCA_IScene { std::vector<SCA_DebugProp*> m_debugList; public: SCA_IScene(); virtual ~SCA_IScene(); virtual class SCA_IObject* AddReplicaObject(class CValue* gameobj, class CValue* locationobj, int lifespan=0)=0; virtual void RemoveObject(class CValue* gameobj)=0; virtual void DelayedRemoveObject(class CValue* gameobj)=0; //virtual void DelayedReleaseObject(class CValue* gameobj)=0; virtual void ReplaceMesh(class CValue* gameobj, void* meshobj, bool use_gfx, bool use_phys)=0; std::vector<SCA_DebugProp*>& GetDebugProperties(); bool PropertyInDebugList(class CValue *gameobj, const STR_String &name); bool ObjectInDebugList(class CValue *gameobj); void RemoveAllDebugProperties(); void AddDebugProperty(class CValue* debugprop, const STR_String &name); void RemoveDebugProperty(class CValue *gameobj, const STR_String &name); void RemoveObjectDebugProperties(class CValue* gameobj); virtual void Update2DFilter(std::vector<STR_String>& propNames, void* gameObj, RAS_2DFilterManager::RAS_2DFILTER_MODE filtermode, int pass, STR_String& text) {} #ifdef WITH_CXX_GUARDEDALLOC MEM_CXX_CLASS_ALLOC_FUNCS("GE:SCA_IScene") #endif }; #endif /* __SCA_ISCENE_H__ */
411
0.758358
1
0.758358
game-dev
MEDIA
0.755864
game-dev
0.570211
1
0.570211
blurite/rsprot
1,898
protocol/osrs-233/osrs-233-desktop/src/main/kotlin/net/rsprot/protocol/game/outgoing/codec/npcinfo/DesktopLowResolutionChangeEncoder.kt
package net.rsprot.protocol.game.outgoing.codec.npcinfo import net.rsprot.buffer.bitbuffer.BitBuf import net.rsprot.protocol.common.client.OldSchoolClientType import net.rsprot.protocol.internal.game.outgoing.info.CoordGrid import net.rsprot.protocol.internal.game.outgoing.info.npcinfo.NpcAvatarDetails import net.rsprot.protocol.internal.game.outgoing.info.npcinfo.encoder.NpcResolutionChangeEncoder import kotlin.math.min public class DesktopLowResolutionChangeEncoder : NpcResolutionChangeEncoder { override val clientType: OldSchoolClientType = OldSchoolClientType.DESKTOP override fun encode( bitBuffer: BitBuf, details: NpcAvatarDetails, extendedInfo: Boolean, localPlayerCoordGrid: CoordGrid, largeDistance: Boolean, cycleCount: Int, ) { val numOfBitsUsed = if (largeDistance) 8 else 6 val maximumDistanceTransmittableByBits = if (largeDistance) 0xFF else 0x3F val deltaX = details.currentCoord.x - localPlayerCoordGrid.x val deltaZ = details.currentCoord.z - localPlayerCoordGrid.z bitBuffer.pBits(16, details.index) // New NPCs should always be marked as "jumping" unless they explicitly only teleported without a jump val noJump = details.isTeleWithoutJump() && details.allocateCycle != cycleCount bitBuffer.pBits(1, if (noJump) 0 else 1) bitBuffer.pBits(1, if (extendedInfo) 1 else 0) if (details.spawnCycle != 0) { bitBuffer.pBits(1, 1) bitBuffer.pBits(32, details.spawnCycle) } else { bitBuffer.pBits(1, 0) } bitBuffer.pBits(14, min(16383, details.id)) bitBuffer.pBits(numOfBitsUsed, deltaX and maximumDistanceTransmittableByBits) bitBuffer.pBits(3, details.direction) bitBuffer.pBits(numOfBitsUsed, deltaZ and maximumDistanceTransmittableByBits) } }
411
0.588018
1
0.588018
game-dev
MEDIA
0.404804
game-dev,networking
0.882536
1
0.882536
lzk228/space-axolotl-14
1,972
Content.Server/NPC/Pathfinding/PathfindingSystem.Helper.cs
namespace Content.Server.NPC.Pathfinding; public sealed partial class PathfindingSystem { /// <summary> /// Finds a generic path from start to end. /// </summary> public List<Vector2i> GetPath(Vector2i start, Vector2i end, bool diagonal = false) { if (start == end) { return new List<Vector2i>(); } var frontier = new PriorityQueue<Vector2i, float>(); frontier.Enqueue(start, 0f); var cameFrom = new Dictionary<Vector2i, Vector2i>(); var node = start; while (frontier.TryDequeue(out node, out _)) { if (node == end) { break; } if (diagonal) { for (var i = 0; i < 8; i++) { var direction = (DirectionFlag) i; var neighbor = node + direction.AsDir().ToIntVec(); if (!cameFrom.TryAdd(neighbor, node)) continue; var gScore = OctileDistance(neighbor, end); frontier.Enqueue(neighbor, gScore); } } else { for (var i = 0; i < 4; i++) { var direction = (DirectionFlag) Math.Pow(2, i); var neighbor = node + direction.AsDir().ToIntVec(); if (!cameFrom.TryAdd(neighbor, node)) continue; frontier.Enqueue(neighbor, ManhattanDistance(neighbor, end)); } } } if (node != end) { return new List<Vector2i>(); } var path = new List<Vector2i>(); do { path.Add(node); var before = cameFrom[node]; node = before; } while (node != start); path.Add(start); path.Reverse(); return path; } }
411
0.908497
1
0.908497
game-dev
MEDIA
0.834343
game-dev
0.977964
1
0.977964
GTNewHorizons/GT5-Unofficial
5,320
src/main/java/gregtech/common/covers/redstone/CoverWirelessDoesWorkDetector.java
package gregtech.common.covers.redstone; import net.minecraft.nbt.NBTBase; import net.minecraft.nbt.NBTTagCompound; import org.jetbrains.annotations.NotNull; import com.cleanroommc.modularui.api.drawable.IKey; import com.google.common.io.ByteArrayDataInput; import com.gtnewhorizons.modularui.api.screen.ModularWindow; import gregtech.api.covers.CoverContext; import gregtech.api.gui.modularui.CoverUIBuildContext; import gregtech.api.interfaces.ITexture; import gregtech.api.interfaces.modularui.KeyProvider; import gregtech.api.interfaces.tileentity.ICoverable; import gregtech.api.interfaces.tileentity.IMachineProgress; import gregtech.common.covers.CoverPosition; import gregtech.common.covers.gui.CoverGui; import gregtech.common.covers.gui.redstone.CoverWirelessDoesWorkDetectorGui; import gregtech.common.gui.mui1.cover.WirelessActivityDetectorUIFactory; import io.netty.buffer.ByteBuf; public class CoverWirelessDoesWorkDetector extends CoverAdvancedRedstoneTransmitterBase { private ActivityMode mode; /** Whether the wireless detector cover also sets the tiles sided Redstone output */ private boolean physical; public CoverWirelessDoesWorkDetector(CoverContext context, ITexture coverTexture) { super(context, coverTexture); this.mode = ActivityMode.MACHINE_IDLE; this.physical = true; } public ActivityMode getMode() { return mode; } public CoverWirelessDoesWorkDetector setMode(ActivityMode mode) { this.mode = mode; return this; } public boolean isPhysical() { return physical; } public CoverWirelessDoesWorkDetector setPhysical(boolean physical) { this.physical = physical; return this; } @Override protected void readDataFromNbt(NBTBase nbt) { super.readDataFromNbt(nbt); NBTTagCompound tag = (NBTTagCompound) nbt; mode = ActivityMode.values()[tag.getInteger("mode")]; if (tag.hasKey("physical")) { physical = tag.getBoolean("physical"); } else { physical = false; } } @Override public void readDataFromPacket(ByteArrayDataInput byteData) { super.readDataFromPacket(byteData); mode = ActivityMode.values()[byteData.readInt()]; physical = byteData.readBoolean(); } @Override protected @NotNull NBTBase saveDataToNbt() { NBTTagCompound tag = (NBTTagCompound) super.saveDataToNbt(); tag.setInteger("mode", mode.ordinal()); tag.setBoolean("physical", physical); return tag; } @Override protected void writeDataToByteBuf(ByteBuf byteBuf) { super.writeDataToByteBuf(byteBuf); byteBuf.writeInt(mode.ordinal()); byteBuf.writeBoolean(physical); } private byte computeSignalBasedOnActivity(ICoverable tileEntity) { if (tileEntity instanceof IMachineProgress mProgress) { boolean inverted = invert; int signal = 0; switch (mode) { case MACHINE_ENABLED -> signal = inverted == mProgress.isAllowedToWork() ? 0 : 15; case MACHINE_IDLE -> signal = inverted == (mProgress.getMaxProgress() == 0) ? 0 : 15; case RECIPE_PROGRESS -> { int tScale = mProgress.getMaxProgress() / 15; if (tScale > 0 && mProgress.hasThingsToDo()) { signal = inverted ? (15 - mProgress.getProgress() / tScale) : (mProgress.getProgress() / tScale); } else { signal = inverted ? 15 : 0; } } } return (byte) signal; } else { return (byte) 0; } } @Override public void doCoverThings(byte aInputRedstone, long aTimer) { ICoverable coverable = coveredTile.get(); if (coverable == null) { return; } final byte signal = computeSignalBasedOnActivity(coverable); final CoverPosition key = getCoverKey(coverable, coverSide); setSignalAt(getUuid(), getFrequency(), key, signal); if (physical) { coverable.setOutputRedstoneSignal(coverSide, signal); } else { coverable.setOutputRedstoneSignal(coverSide, (byte) 0); } } @Override public boolean letsRedstoneGoOut() { return true; } @Override public boolean manipulatesSidedRedstoneOutput() { return true; } public enum ActivityMode implements KeyProvider { RECIPE_PROGRESS(IKey.lang("gt.interact.desc.recipeprogress")), MACHINE_IDLE(IKey.lang("gt.interact.desc.machineidle")), MACHINE_ENABLED(IKey.lang("gt.interact.desc.mach_on")); private final IKey key; ActivityMode(IKey key) { this.key = key; } @Override public IKey getKey() { return this.key; } } @Override public ModularWindow createWindow(CoverUIBuildContext buildContext) { return new WirelessActivityDetectorUIFactory(buildContext).createWindow(); } @Override protected @NotNull CoverGui<?> getCoverGui() { return new CoverWirelessDoesWorkDetectorGui(this); } }
411
0.72366
1
0.72366
game-dev
MEDIA
0.539116
game-dev
0.937799
1
0.937799
ArchipelagoMW/Archipelago
49,214
worlds/heretic/Rules.py
# This file is auto generated. More info: https://github.com/Daivuk/apdoom from typing import TYPE_CHECKING from worlds.generic.Rules import set_rule if TYPE_CHECKING: from . import HereticWorld def set_episode1_rules(player, multiworld, pro): # The Docks (E1M1) set_rule(multiworld.get_entrance("Hub -> The Docks (E1M1) Main", player), lambda state: state.has("The Docks (E1M1)", player, 1)) set_rule(multiworld.get_entrance("The Docks (E1M1) Main -> The Docks (E1M1) Yellow", player), lambda state: state.has("The Docks (E1M1) - Yellow key", player, 1)) # The Dungeons (E1M2) set_rule(multiworld.get_entrance("Hub -> The Dungeons (E1M2) Main", player), lambda state: (state.has("The Dungeons (E1M2)", player, 1)) and (state.has("Dragon Claw", player, 1) or state.has("Ethereal Crossbow", player, 1))) set_rule(multiworld.get_entrance("The Dungeons (E1M2) Main -> The Dungeons (E1M2) Yellow", player), lambda state: state.has("The Dungeons (E1M2) - Yellow key", player, 1)) set_rule(multiworld.get_entrance("The Dungeons (E1M2) Main -> The Dungeons (E1M2) Green", player), lambda state: state.has("The Dungeons (E1M2) - Green key", player, 1)) set_rule(multiworld.get_entrance("The Dungeons (E1M2) Blue -> The Dungeons (E1M2) Yellow", player), lambda state: state.has("The Dungeons (E1M2) - Blue key", player, 1)) set_rule(multiworld.get_entrance("The Dungeons (E1M2) Yellow -> The Dungeons (E1M2) Blue", player), lambda state: state.has("The Dungeons (E1M2) - Blue key", player, 1)) # The Gatehouse (E1M3) set_rule(multiworld.get_entrance("Hub -> The Gatehouse (E1M3) Main", player), lambda state: (state.has("The Gatehouse (E1M3)", player, 1)) and (state.has("Ethereal Crossbow", player, 1) or state.has("Dragon Claw", player, 1))) set_rule(multiworld.get_entrance("The Gatehouse (E1M3) Main -> The Gatehouse (E1M3) Yellow", player), lambda state: state.has("The Gatehouse (E1M3) - Yellow key", player, 1)) set_rule(multiworld.get_entrance("The Gatehouse (E1M3) Main -> The Gatehouse (E1M3) Sea", player), lambda state: state.has("The Gatehouse (E1M3) - Yellow key", player, 1)) set_rule(multiworld.get_entrance("The Gatehouse (E1M3) Main -> The Gatehouse (E1M3) Green", player), lambda state: state.has("The Gatehouse (E1M3) - Green key", player, 1)) set_rule(multiworld.get_entrance("The Gatehouse (E1M3) Green -> The Gatehouse (E1M3) Main", player), lambda state: state.has("The Gatehouse (E1M3) - Green key", player, 1)) # The Guard Tower (E1M4) set_rule(multiworld.get_entrance("Hub -> The Guard Tower (E1M4) Main", player), lambda state: (state.has("The Guard Tower (E1M4)", player, 1)) and (state.has("Ethereal Crossbow", player, 1) or state.has("Dragon Claw", player, 1))) set_rule(multiworld.get_entrance("The Guard Tower (E1M4) Main -> The Guard Tower (E1M4) Yellow", player), lambda state: state.has("The Guard Tower (E1M4) - Yellow key", player, 1)) set_rule(multiworld.get_entrance("The Guard Tower (E1M4) Yellow -> The Guard Tower (E1M4) Green", player), lambda state: state.has("The Guard Tower (E1M4) - Green key", player, 1)) set_rule(multiworld.get_entrance("The Guard Tower (E1M4) Green -> The Guard Tower (E1M4) Yellow", player), lambda state: state.has("The Guard Tower (E1M4) - Green key", player, 1)) # The Citadel (E1M5) set_rule(multiworld.get_entrance("Hub -> The Citadel (E1M5) Main", player), lambda state: (state.has("The Citadel (E1M5)", player, 1) and state.has("Ethereal Crossbow", player, 1)) and (state.has("Dragon Claw", player, 1) or state.has("Gauntlets of the Necromancer", player, 1))) set_rule(multiworld.get_entrance("The Citadel (E1M5) Main -> The Citadel (E1M5) Yellow", player), lambda state: state.has("The Citadel (E1M5) - Yellow key", player, 1)) set_rule(multiworld.get_entrance("The Citadel (E1M5) Blue -> The Citadel (E1M5) Green", player), lambda state: state.has("The Citadel (E1M5) - Blue key", player, 1)) set_rule(multiworld.get_entrance("The Citadel (E1M5) Yellow -> The Citadel (E1M5) Green", player), lambda state: state.has("The Citadel (E1M5) - Green key", player, 1)) set_rule(multiworld.get_entrance("The Citadel (E1M5) Green -> The Citadel (E1M5) Blue", player), lambda state: state.has("The Citadel (E1M5) - Blue key", player, 1)) # The Cathedral (E1M6) set_rule(multiworld.get_entrance("Hub -> The Cathedral (E1M6) Main", player), lambda state: (state.has("The Cathedral (E1M6)", player, 1) and state.has("Ethereal Crossbow", player, 1)) and (state.has("Gauntlets of the Necromancer", player, 1) or state.has("Dragon Claw", player, 1))) set_rule(multiworld.get_entrance("The Cathedral (E1M6) Main -> The Cathedral (E1M6) Yellow", player), lambda state: state.has("The Cathedral (E1M6) - Yellow key", player, 1)) set_rule(multiworld.get_entrance("The Cathedral (E1M6) Yellow -> The Cathedral (E1M6) Green", player), lambda state: state.has("The Cathedral (E1M6) - Green key", player, 1)) # The Crypts (E1M7) set_rule(multiworld.get_entrance("Hub -> The Crypts (E1M7) Main", player), lambda state: (state.has("The Crypts (E1M7)", player, 1) and state.has("Ethereal Crossbow", player, 1)) and (state.has("Gauntlets of the Necromancer", player, 1) or state.has("Dragon Claw", player, 1))) set_rule(multiworld.get_entrance("The Crypts (E1M7) Main -> The Crypts (E1M7) Yellow", player), lambda state: state.has("The Crypts (E1M7) - Yellow key", player, 1)) set_rule(multiworld.get_entrance("The Crypts (E1M7) Main -> The Crypts (E1M7) Green", player), lambda state: state.has("The Crypts (E1M7) - Green key", player, 1)) set_rule(multiworld.get_entrance("The Crypts (E1M7) Yellow -> The Crypts (E1M7) Green", player), lambda state: state.has("The Crypts (E1M7) - Green key", player, 1)) set_rule(multiworld.get_entrance("The Crypts (E1M7) Yellow -> The Crypts (E1M7) Blue", player), lambda state: state.has("The Crypts (E1M7) - Blue key", player, 1)) set_rule(multiworld.get_entrance("The Crypts (E1M7) Green -> The Crypts (E1M7) Main", player), lambda state: state.has("The Crypts (E1M7) - Green key", player, 1)) # Hell's Maw (E1M8) set_rule(multiworld.get_entrance("Hub -> Hell's Maw (E1M8) Main", player), lambda state: state.has("Hell's Maw (E1M8)", player, 1) and state.has("Gauntlets of the Necromancer", player, 1) and state.has("Ethereal Crossbow", player, 1) and state.has("Dragon Claw", player, 1)) # The Graveyard (E1M9) set_rule(multiworld.get_entrance("Hub -> The Graveyard (E1M9) Main", player), lambda state: state.has("The Graveyard (E1M9)", player, 1) and state.has("Gauntlets of the Necromancer", player, 1) and state.has("Ethereal Crossbow", player, 1) and state.has("Dragon Claw", player, 1)) set_rule(multiworld.get_entrance("The Graveyard (E1M9) Main -> The Graveyard (E1M9) Yellow", player), lambda state: state.has("The Graveyard (E1M9) - Yellow key", player, 1)) set_rule(multiworld.get_entrance("The Graveyard (E1M9) Main -> The Graveyard (E1M9) Green", player), lambda state: state.has("The Graveyard (E1M9) - Green key", player, 1)) set_rule(multiworld.get_entrance("The Graveyard (E1M9) Main -> The Graveyard (E1M9) Blue", player), lambda state: state.has("The Graveyard (E1M9) - Blue key", player, 1)) set_rule(multiworld.get_entrance("The Graveyard (E1M9) Yellow -> The Graveyard (E1M9) Main", player), lambda state: state.has("The Graveyard (E1M9) - Yellow key", player, 1)) set_rule(multiworld.get_entrance("The Graveyard (E1M9) Green -> The Graveyard (E1M9) Main", player), lambda state: state.has("The Graveyard (E1M9) - Green key", player, 1)) def set_episode2_rules(player, multiworld, pro): # The Crater (E2M1) set_rule(multiworld.get_entrance("Hub -> The Crater (E2M1) Main", player), lambda state: state.has("The Crater (E2M1)", player, 1)) set_rule(multiworld.get_entrance("The Crater (E2M1) Main -> The Crater (E2M1) Yellow", player), lambda state: state.has("The Crater (E2M1) - Yellow key", player, 1)) set_rule(multiworld.get_entrance("The Crater (E2M1) Yellow -> The Crater (E2M1) Green", player), lambda state: state.has("The Crater (E2M1) - Green key", player, 1)) set_rule(multiworld.get_entrance("The Crater (E2M1) Green -> The Crater (E2M1) Yellow", player), lambda state: state.has("The Crater (E2M1) - Green key", player, 1)) # The Lava Pits (E2M2) set_rule(multiworld.get_entrance("Hub -> The Lava Pits (E2M2) Main", player), lambda state: (state.has("The Lava Pits (E2M2)", player, 1)) and (state.has("Ethereal Crossbow", player, 1) or state.has("Dragon Claw", player, 1))) set_rule(multiworld.get_entrance("The Lava Pits (E2M2) Main -> The Lava Pits (E2M2) Yellow", player), lambda state: state.has("The Lava Pits (E2M2) - Yellow key", player, 1)) set_rule(multiworld.get_entrance("The Lava Pits (E2M2) Yellow -> The Lava Pits (E2M2) Green", player), lambda state: state.has("The Lava Pits (E2M2) - Green key", player, 1)) set_rule(multiworld.get_entrance("The Lava Pits (E2M2) Yellow -> The Lava Pits (E2M2) Main", player), lambda state: state.has("The Lava Pits (E2M2) - Yellow key", player, 1)) set_rule(multiworld.get_entrance("The Lava Pits (E2M2) Green -> The Lava Pits (E2M2) Yellow", player), lambda state: state.has("The Lava Pits (E2M2) - Green key", player, 1)) # The River of Fire (E2M3) set_rule(multiworld.get_entrance("Hub -> The River of Fire (E2M3) Main", player), lambda state: state.has("The River of Fire (E2M3)", player, 1) and state.has("Dragon Claw", player, 1) and state.has("Ethereal Crossbow", player, 1)) set_rule(multiworld.get_entrance("The River of Fire (E2M3) Main -> The River of Fire (E2M3) Yellow", player), lambda state: state.has("The River of Fire (E2M3) - Yellow key", player, 1)) set_rule(multiworld.get_entrance("The River of Fire (E2M3) Main -> The River of Fire (E2M3) Blue", player), lambda state: state.has("The River of Fire (E2M3) - Blue key", player, 1)) set_rule(multiworld.get_entrance("The River of Fire (E2M3) Main -> The River of Fire (E2M3) Green", player), lambda state: state.has("The River of Fire (E2M3) - Green key", player, 1)) set_rule(multiworld.get_entrance("The River of Fire (E2M3) Blue -> The River of Fire (E2M3) Main", player), lambda state: state.has("The River of Fire (E2M3) - Blue key", player, 1)) set_rule(multiworld.get_entrance("The River of Fire (E2M3) Yellow -> The River of Fire (E2M3) Main", player), lambda state: state.has("The River of Fire (E2M3) - Yellow key", player, 1)) set_rule(multiworld.get_entrance("The River of Fire (E2M3) Green -> The River of Fire (E2M3) Main", player), lambda state: state.has("The River of Fire (E2M3) - Green key", player, 1)) # The Ice Grotto (E2M4) set_rule(multiworld.get_entrance("Hub -> The Ice Grotto (E2M4) Main", player), lambda state: (state.has("The Ice Grotto (E2M4)", player, 1) and state.has("Ethereal Crossbow", player, 1) and state.has("Dragon Claw", player, 1)) and (state.has("Hellstaff", player, 1) or state.has("Firemace", player, 1))) set_rule(multiworld.get_entrance("The Ice Grotto (E2M4) Main -> The Ice Grotto (E2M4) Green", player), lambda state: state.has("The Ice Grotto (E2M4) - Green key", player, 1)) set_rule(multiworld.get_entrance("The Ice Grotto (E2M4) Main -> The Ice Grotto (E2M4) Yellow", player), lambda state: state.has("The Ice Grotto (E2M4) - Yellow key", player, 1)) set_rule(multiworld.get_entrance("The Ice Grotto (E2M4) Blue -> The Ice Grotto (E2M4) Green", player), lambda state: state.has("The Ice Grotto (E2M4) - Blue key", player, 1)) set_rule(multiworld.get_entrance("The Ice Grotto (E2M4) Yellow -> The Ice Grotto (E2M4) Magenta", player), lambda state: state.has("The Ice Grotto (E2M4) - Green key", player, 1) and state.has("The Ice Grotto (E2M4) - Blue key", player, 1)) set_rule(multiworld.get_entrance("The Ice Grotto (E2M4) Green -> The Ice Grotto (E2M4) Blue", player), lambda state: state.has("The Ice Grotto (E2M4) - Blue key", player, 1)) # The Catacombs (E2M5) set_rule(multiworld.get_entrance("Hub -> The Catacombs (E2M5) Main", player), lambda state: (state.has("The Catacombs (E2M5)", player, 1) and state.has("Gauntlets of the Necromancer", player, 1) and state.has("Ethereal Crossbow", player, 1) and state.has("Dragon Claw", player, 1)) and (state.has("Phoenix Rod", player, 1) or state.has("Firemace", player, 1) or state.has("Hellstaff", player, 1))) set_rule(multiworld.get_entrance("The Catacombs (E2M5) Main -> The Catacombs (E2M5) Yellow", player), lambda state: state.has("The Catacombs (E2M5) - Yellow key", player, 1)) set_rule(multiworld.get_entrance("The Catacombs (E2M5) Blue -> The Catacombs (E2M5) Green", player), lambda state: state.has("The Catacombs (E2M5) - Blue key", player, 1)) set_rule(multiworld.get_entrance("The Catacombs (E2M5) Yellow -> The Catacombs (E2M5) Green", player), lambda state: state.has("The Catacombs (E2M5) - Green key", player, 1)) set_rule(multiworld.get_entrance("The Catacombs (E2M5) Green -> The Catacombs (E2M5) Blue", player), lambda state: state.has("The Catacombs (E2M5) - Blue key", player, 1)) # The Labyrinth (E2M6) set_rule(multiworld.get_entrance("Hub -> The Labyrinth (E2M6) Main", player), lambda state: (state.has("The Labyrinth (E2M6)", player, 1) and state.has("Gauntlets of the Necromancer", player, 1) and state.has("Ethereal Crossbow", player, 1) and state.has("Dragon Claw", player, 1)) and (state.has("Phoenix Rod", player, 1) or state.has("Firemace", player, 1) or state.has("Hellstaff", player, 1))) set_rule(multiworld.get_entrance("The Labyrinth (E2M6) Main -> The Labyrinth (E2M6) Blue", player), lambda state: state.has("The Labyrinth (E2M6) - Blue key", player, 1)) set_rule(multiworld.get_entrance("The Labyrinth (E2M6) Main -> The Labyrinth (E2M6) Yellow", player), lambda state: state.has("The Labyrinth (E2M6) - Yellow key", player, 1)) set_rule(multiworld.get_entrance("The Labyrinth (E2M6) Main -> The Labyrinth (E2M6) Green", player), lambda state: state.has("The Labyrinth (E2M6) - Green key", player, 1)) set_rule(multiworld.get_entrance("The Labyrinth (E2M6) Blue -> The Labyrinth (E2M6) Main", player), lambda state: state.has("The Labyrinth (E2M6) - Blue key", player, 1)) # The Great Hall (E2M7) set_rule(multiworld.get_entrance("Hub -> The Great Hall (E2M7) Main", player), lambda state: (state.has("The Great Hall (E2M7)", player, 1) and state.has("Gauntlets of the Necromancer", player, 1) and state.has("Ethereal Crossbow", player, 1) and state.has("Dragon Claw", player, 1) and state.has("Firemace", player, 1)) and (state.has("Phoenix Rod", player, 1) or state.has("Hellstaff", player, 1))) set_rule(multiworld.get_entrance("The Great Hall (E2M7) Main -> The Great Hall (E2M7) Yellow", player), lambda state: state.has("The Great Hall (E2M7) - Yellow key", player, 1)) set_rule(multiworld.get_entrance("The Great Hall (E2M7) Main -> The Great Hall (E2M7) Green", player), lambda state: state.has("The Great Hall (E2M7) - Green key", player, 1)) set_rule(multiworld.get_entrance("The Great Hall (E2M7) Blue -> The Great Hall (E2M7) Yellow", player), lambda state: state.has("The Great Hall (E2M7) - Blue key", player, 1)) set_rule(multiworld.get_entrance("The Great Hall (E2M7) Yellow -> The Great Hall (E2M7) Blue", player), lambda state: state.has("The Great Hall (E2M7) - Blue key", player, 1)) set_rule(multiworld.get_entrance("The Great Hall (E2M7) Yellow -> The Great Hall (E2M7) Main", player), lambda state: state.has("The Great Hall (E2M7) - Yellow key", player, 1)) # The Portals of Chaos (E2M8) set_rule(multiworld.get_entrance("Hub -> The Portals of Chaos (E2M8) Main", player), lambda state: state.has("The Portals of Chaos (E2M8)", player, 1) and state.has("Gauntlets of the Necromancer", player, 1) and state.has("Ethereal Crossbow", player, 1) and state.has("Dragon Claw", player, 1) and state.has("Phoenix Rod", player, 1) and state.has("Firemace", player, 1) and state.has("Hellstaff", player, 1)) # The Glacier (E2M9) set_rule(multiworld.get_entrance("Hub -> The Glacier (E2M9) Main", player), lambda state: (state.has("The Glacier (E2M9)", player, 1) and state.has("Gauntlets of the Necromancer", player, 1) and state.has("Ethereal Crossbow", player, 1) and state.has("Dragon Claw", player, 1) and state.has("Firemace", player, 1)) and (state.has("Phoenix Rod", player, 1) or state.has("Hellstaff", player, 1))) set_rule(multiworld.get_entrance("The Glacier (E2M9) Main -> The Glacier (E2M9) Yellow", player), lambda state: state.has("The Glacier (E2M9) - Yellow key", player, 1)) set_rule(multiworld.get_entrance("The Glacier (E2M9) Main -> The Glacier (E2M9) Blue", player), lambda state: state.has("The Glacier (E2M9) - Blue key", player, 1)) set_rule(multiworld.get_entrance("The Glacier (E2M9) Main -> The Glacier (E2M9) Green", player), lambda state: state.has("The Glacier (E2M9) - Green key", player, 1)) set_rule(multiworld.get_entrance("The Glacier (E2M9) Blue -> The Glacier (E2M9) Main", player), lambda state: state.has("The Glacier (E2M9) - Blue key", player, 1)) set_rule(multiworld.get_entrance("The Glacier (E2M9) Yellow -> The Glacier (E2M9) Main", player), lambda state: state.has("The Glacier (E2M9) - Yellow key", player, 1)) def set_episode3_rules(player, multiworld, pro): # The Storehouse (E3M1) set_rule(multiworld.get_entrance("Hub -> The Storehouse (E3M1) Main", player), lambda state: state.has("The Storehouse (E3M1)", player, 1)) set_rule(multiworld.get_entrance("The Storehouse (E3M1) Main -> The Storehouse (E3M1) Yellow", player), lambda state: state.has("The Storehouse (E3M1) - Yellow key", player, 1)) set_rule(multiworld.get_entrance("The Storehouse (E3M1) Main -> The Storehouse (E3M1) Green", player), lambda state: state.has("The Storehouse (E3M1) - Green key", player, 1)) set_rule(multiworld.get_entrance("The Storehouse (E3M1) Yellow -> The Storehouse (E3M1) Main", player), lambda state: state.has("The Storehouse (E3M1) - Yellow key", player, 1)) set_rule(multiworld.get_entrance("The Storehouse (E3M1) Green -> The Storehouse (E3M1) Main", player), lambda state: state.has("The Storehouse (E3M1) - Green key", player, 1)) # The Cesspool (E3M2) set_rule(multiworld.get_entrance("Hub -> The Cesspool (E3M2) Main", player), lambda state: state.has("The Cesspool (E3M2)", player, 1) and state.has("Ethereal Crossbow", player, 1) and state.has("Dragon Claw", player, 1) and state.has("Firemace", player, 1) and state.has("Hellstaff", player, 1)) set_rule(multiworld.get_entrance("The Cesspool (E3M2) Main -> The Cesspool (E3M2) Yellow", player), lambda state: state.has("The Cesspool (E3M2) - Yellow key", player, 1)) set_rule(multiworld.get_entrance("The Cesspool (E3M2) Blue -> The Cesspool (E3M2) Green", player), lambda state: state.has("The Cesspool (E3M2) - Blue key", player, 1)) set_rule(multiworld.get_entrance("The Cesspool (E3M2) Yellow -> The Cesspool (E3M2) Green", player), lambda state: state.has("The Cesspool (E3M2) - Green key", player, 1)) set_rule(multiworld.get_entrance("The Cesspool (E3M2) Green -> The Cesspool (E3M2) Blue", player), lambda state: state.has("The Cesspool (E3M2) - Blue key", player, 1)) set_rule(multiworld.get_entrance("The Cesspool (E3M2) Green -> The Cesspool (E3M2) Yellow", player), lambda state: state.has("The Cesspool (E3M2) - Green key", player, 1)) # The Confluence (E3M3) set_rule(multiworld.get_entrance("Hub -> The Confluence (E3M3) Main", player), lambda state: (state.has("The Confluence (E3M3)", player, 1) and state.has("Ethereal Crossbow", player, 1) and state.has("Dragon Claw", player, 1)) and (state.has("Gauntlets of the Necromancer", player, 1) or state.has("Phoenix Rod", player, 1) or state.has("Firemace", player, 1) or state.has("Hellstaff", player, 1))) set_rule(multiworld.get_entrance("The Confluence (E3M3) Main -> The Confluence (E3M3) Green", player), lambda state: state.has("The Confluence (E3M3) - Green key", player, 1)) set_rule(multiworld.get_entrance("The Confluence (E3M3) Main -> The Confluence (E3M3) Yellow", player), lambda state: state.has("The Confluence (E3M3) - Yellow key", player, 1)) set_rule(multiworld.get_entrance("The Confluence (E3M3) Blue -> The Confluence (E3M3) Green", player), lambda state: state.has("The Confluence (E3M3) - Blue key", player, 1)) set_rule(multiworld.get_entrance("The Confluence (E3M3) Green -> The Confluence (E3M3) Main", player), lambda state: state.has("The Confluence (E3M3) - Green key", player, 1)) set_rule(multiworld.get_entrance("The Confluence (E3M3) Green -> The Confluence (E3M3) Blue", player), lambda state: state.has("The Confluence (E3M3) - Blue key", player, 1)) # The Azure Fortress (E3M4) set_rule(multiworld.get_entrance("Hub -> The Azure Fortress (E3M4) Main", player), lambda state: (state.has("The Azure Fortress (E3M4)", player, 1) and state.has("Ethereal Crossbow", player, 1) and state.has("Dragon Claw", player, 1) and state.has("Hellstaff", player, 1)) and (state.has("Firemace", player, 1) or state.has("Phoenix Rod", player, 1) or state.has("Gauntlets of the Necromancer", player, 1))) set_rule(multiworld.get_entrance("The Azure Fortress (E3M4) Main -> The Azure Fortress (E3M4) Green", player), lambda state: state.has("The Azure Fortress (E3M4) - Green key", player, 1)) set_rule(multiworld.get_entrance("The Azure Fortress (E3M4) Main -> The Azure Fortress (E3M4) Yellow", player), lambda state: state.has("The Azure Fortress (E3M4) - Yellow key", player, 1)) # The Ophidian Lair (E3M5) set_rule(multiworld.get_entrance("Hub -> The Ophidian Lair (E3M5) Main", player), lambda state: (state.has("The Ophidian Lair (E3M5)", player, 1) and state.has("Ethereal Crossbow", player, 1) and state.has("Dragon Claw", player, 1) and state.has("Hellstaff", player, 1)) and (state.has("Gauntlets of the Necromancer", player, 1) or state.has("Phoenix Rod", player, 1) or state.has("Firemace", player, 1))) set_rule(multiworld.get_entrance("The Ophidian Lair (E3M5) Main -> The Ophidian Lair (E3M5) Yellow", player), lambda state: state.has("The Ophidian Lair (E3M5) - Yellow key", player, 1)) set_rule(multiworld.get_entrance("The Ophidian Lair (E3M5) Main -> The Ophidian Lair (E3M5) Green", player), lambda state: state.has("The Ophidian Lair (E3M5) - Green key", player, 1)) # The Halls of Fear (E3M6) set_rule(multiworld.get_entrance("Hub -> The Halls of Fear (E3M6) Main", player), lambda state: (state.has("The Halls of Fear (E3M6)", player, 1) and state.has("Firemace", player, 1) and state.has("Hellstaff", player, 1) and state.has("Dragon Claw", player, 1) and state.has("Ethereal Crossbow", player, 1)) and (state.has("Gauntlets of the Necromancer", player, 1) or state.has("Phoenix Rod", player, 1))) set_rule(multiworld.get_entrance("The Halls of Fear (E3M6) Main -> The Halls of Fear (E3M6) Yellow", player), lambda state: state.has("The Halls of Fear (E3M6) - Yellow key", player, 1)) set_rule(multiworld.get_entrance("The Halls of Fear (E3M6) Blue -> The Halls of Fear (E3M6) Yellow", player), lambda state: state.has("The Halls of Fear (E3M6) - Blue key", player, 1)) set_rule(multiworld.get_entrance("The Halls of Fear (E3M6) Yellow -> The Halls of Fear (E3M6) Blue", player), lambda state: state.has("The Halls of Fear (E3M6) - Blue key", player, 1)) set_rule(multiworld.get_entrance("The Halls of Fear (E3M6) Yellow -> The Halls of Fear (E3M6) Green", player), lambda state: state.has("The Halls of Fear (E3M6) - Green key", player, 1)) # The Chasm (E3M7) set_rule(multiworld.get_entrance("Hub -> The Chasm (E3M7) Main", player), lambda state: (state.has("The Chasm (E3M7)", player, 1) and state.has("Ethereal Crossbow", player, 1) and state.has("Dragon Claw", player, 1) and state.has("Firemace", player, 1) and state.has("Hellstaff", player, 1)) and (state.has("Gauntlets of the Necromancer", player, 1) or state.has("Phoenix Rod", player, 1))) set_rule(multiworld.get_entrance("The Chasm (E3M7) Main -> The Chasm (E3M7) Yellow", player), lambda state: state.has("The Chasm (E3M7) - Yellow key", player, 1)) set_rule(multiworld.get_entrance("The Chasm (E3M7) Yellow -> The Chasm (E3M7) Main", player), lambda state: state.has("The Chasm (E3M7) - Yellow key", player, 1)) set_rule(multiworld.get_entrance("The Chasm (E3M7) Yellow -> The Chasm (E3M7) Green", player), lambda state: state.has("The Chasm (E3M7) - Green key", player, 1)) set_rule(multiworld.get_entrance("The Chasm (E3M7) Yellow -> The Chasm (E3M7) Blue", player), lambda state: state.has("The Chasm (E3M7) - Blue key", player, 1)) set_rule(multiworld.get_entrance("The Chasm (E3M7) Green -> The Chasm (E3M7) Yellow", player), lambda state: state.has("The Chasm (E3M7) - Green key", player, 1)) # D'Sparil's Keep (E3M8) set_rule(multiworld.get_entrance("Hub -> D'Sparil's Keep (E3M8) Main", player), lambda state: state.has("D'Sparil's Keep (E3M8)", player, 1) and state.has("Gauntlets of the Necromancer", player, 1) and state.has("Ethereal Crossbow", player, 1) and state.has("Dragon Claw", player, 1) and state.has("Phoenix Rod", player, 1) and state.has("Firemace", player, 1) and state.has("Hellstaff", player, 1)) # The Aquifer (E3M9) set_rule(multiworld.get_entrance("Hub -> The Aquifer (E3M9) Main", player), lambda state: state.has("The Aquifer (E3M9)", player, 1) and state.has("Gauntlets of the Necromancer", player, 1) and state.has("Ethereal Crossbow", player, 1) and state.has("Dragon Claw", player, 1) and state.has("Phoenix Rod", player, 1) and state.has("Firemace", player, 1) and state.has("Hellstaff", player, 1)) set_rule(multiworld.get_entrance("The Aquifer (E3M9) Main -> The Aquifer (E3M9) Yellow", player), lambda state: state.has("The Aquifer (E3M9) - Yellow key", player, 1)) set_rule(multiworld.get_entrance("The Aquifer (E3M9) Yellow -> The Aquifer (E3M9) Green", player), lambda state: state.has("The Aquifer (E3M9) - Green key", player, 1)) set_rule(multiworld.get_entrance("The Aquifer (E3M9) Yellow -> The Aquifer (E3M9) Main", player), lambda state: state.has("The Aquifer (E3M9) - Yellow key", player, 1)) set_rule(multiworld.get_entrance("The Aquifer (E3M9) Green -> The Aquifer (E3M9) Yellow", player), lambda state: state.has("The Aquifer (E3M9) - Green key", player, 1)) def set_episode4_rules(player, multiworld, pro): # Catafalque (E4M1) set_rule(multiworld.get_entrance("Hub -> Catafalque (E4M1) Main", player), lambda state: state.has("Catafalque (E4M1)", player, 1)) set_rule(multiworld.get_entrance("Catafalque (E4M1) Main -> Catafalque (E4M1) Yellow", player), lambda state: state.has("Catafalque (E4M1) - Yellow key", player, 1)) set_rule(multiworld.get_entrance("Catafalque (E4M1) Yellow -> Catafalque (E4M1) Green", player), lambda state: (state.has("Catafalque (E4M1) - Green key", player, 1)) and (state.has("Ethereal Crossbow", player, 1) or state.has("Dragon Claw", player, 1) or state.has("Phoenix Rod", player, 1) or state.has("Firemace", player, 1) or state.has("Hellstaff", player, 1))) # Blockhouse (E4M2) set_rule(multiworld.get_entrance("Hub -> Blockhouse (E4M2) Main", player), lambda state: state.has("Blockhouse (E4M2)", player, 1) and state.has("Ethereal Crossbow", player, 1) and state.has("Dragon Claw", player, 1)) set_rule(multiworld.get_entrance("Blockhouse (E4M2) Main -> Blockhouse (E4M2) Yellow", player), lambda state: state.has("Blockhouse (E4M2) - Yellow key", player, 1)) set_rule(multiworld.get_entrance("Blockhouse (E4M2) Main -> Blockhouse (E4M2) Green", player), lambda state: state.has("Blockhouse (E4M2) - Green key", player, 1)) set_rule(multiworld.get_entrance("Blockhouse (E4M2) Main -> Blockhouse (E4M2) Blue", player), lambda state: state.has("Blockhouse (E4M2) - Blue key", player, 1)) set_rule(multiworld.get_entrance("Blockhouse (E4M2) Green -> Blockhouse (E4M2) Main", player), lambda state: state.has("Blockhouse (E4M2) - Green key", player, 1)) set_rule(multiworld.get_entrance("Blockhouse (E4M2) Blue -> Blockhouse (E4M2) Main", player), lambda state: state.has("Blockhouse (E4M2) - Blue key", player, 1)) # Ambulatory (E4M3) set_rule(multiworld.get_entrance("Hub -> Ambulatory (E4M3) Main", player), lambda state: (state.has("Ambulatory (E4M3)", player, 1) and state.has("Ethereal Crossbow", player, 1) and state.has("Dragon Claw", player, 1) and state.has("Gauntlets of the Necromancer", player, 1)) and (state.has("Phoenix Rod", player, 1) or state.has("Firemace", player, 1) or state.has("Hellstaff", player, 1))) set_rule(multiworld.get_entrance("Ambulatory (E4M3) Main -> Ambulatory (E4M3) Blue", player), lambda state: state.has("Ambulatory (E4M3) - Blue key", player, 1)) set_rule(multiworld.get_entrance("Ambulatory (E4M3) Main -> Ambulatory (E4M3) Yellow", player), lambda state: state.has("Ambulatory (E4M3) - Yellow key", player, 1)) set_rule(multiworld.get_entrance("Ambulatory (E4M3) Main -> Ambulatory (E4M3) Green", player), lambda state: state.has("Ambulatory (E4M3) - Green key", player, 1)) set_rule(multiworld.get_entrance("Ambulatory (E4M3) Main -> Ambulatory (E4M3) Green Lock", player), lambda state: state.has("Ambulatory (E4M3) - Green key", player, 1)) # Sepulcher (E4M4) set_rule(multiworld.get_entrance("Hub -> Sepulcher (E4M4) Main", player), lambda state: (state.has("Sepulcher (E4M4)", player, 1) and state.has("Ethereal Crossbow", player, 1) and state.has("Dragon Claw", player, 1) and state.has("Gauntlets of the Necromancer", player, 1) and state.has("Firemace", player, 1)) and (state.has("Phoenix Rod", player, 1) or state.has("Hellstaff", player, 1))) # Great Stair (E4M5) set_rule(multiworld.get_entrance("Hub -> Great Stair (E4M5) Main", player), lambda state: (state.has("Great Stair (E4M5)", player, 1) and state.has("Gauntlets of the Necromancer", player, 1) and state.has("Ethereal Crossbow", player, 1) and state.has("Dragon Claw", player, 1) and state.has("Firemace", player, 1)) and (state.has("Hellstaff", player, 1) or state.has("Phoenix Rod", player, 1))) set_rule(multiworld.get_entrance("Great Stair (E4M5) Main -> Great Stair (E4M5) Yellow", player), lambda state: state.has("Great Stair (E4M5) - Yellow key", player, 1)) set_rule(multiworld.get_entrance("Great Stair (E4M5) Blue -> Great Stair (E4M5) Green", player), lambda state: state.has("Great Stair (E4M5) - Blue key", player, 1)) set_rule(multiworld.get_entrance("Great Stair (E4M5) Yellow -> Great Stair (E4M5) Green", player), lambda state: state.has("Great Stair (E4M5) - Green key", player, 1)) set_rule(multiworld.get_entrance("Great Stair (E4M5) Green -> Great Stair (E4M5) Blue", player), lambda state: state.has("Great Stair (E4M5) - Blue key", player, 1)) set_rule(multiworld.get_entrance("Great Stair (E4M5) Green -> Great Stair (E4M5) Yellow", player), lambda state: state.has("Great Stair (E4M5) - Green key", player, 1)) # Halls of the Apostate (E4M6) set_rule(multiworld.get_entrance("Hub -> Halls of the Apostate (E4M6) Main", player), lambda state: (state.has("Halls of the Apostate (E4M6)", player, 1) and state.has("Gauntlets of the Necromancer", player, 1) and state.has("Ethereal Crossbow", player, 1) and state.has("Dragon Claw", player, 1) and state.has("Firemace", player, 1)) and (state.has("Phoenix Rod", player, 1) or state.has("Hellstaff", player, 1))) set_rule(multiworld.get_entrance("Halls of the Apostate (E4M6) Main -> Halls of the Apostate (E4M6) Yellow", player), lambda state: state.has("Halls of the Apostate (E4M6) - Yellow key", player, 1)) set_rule(multiworld.get_entrance("Halls of the Apostate (E4M6) Blue -> Halls of the Apostate (E4M6) Green", player), lambda state: state.has("Halls of the Apostate (E4M6) - Blue key", player, 1)) set_rule(multiworld.get_entrance("Halls of the Apostate (E4M6) Yellow -> Halls of the Apostate (E4M6) Green", player), lambda state: state.has("Halls of the Apostate (E4M6) - Green key", player, 1)) set_rule(multiworld.get_entrance("Halls of the Apostate (E4M6) Green -> Halls of the Apostate (E4M6) Yellow", player), lambda state: state.has("Halls of the Apostate (E4M6) - Green key", player, 1)) set_rule(multiworld.get_entrance("Halls of the Apostate (E4M6) Green -> Halls of the Apostate (E4M6) Blue", player), lambda state: state.has("Halls of the Apostate (E4M6) - Blue key", player, 1)) # Ramparts of Perdition (E4M7) set_rule(multiworld.get_entrance("Hub -> Ramparts of Perdition (E4M7) Main", player), lambda state: (state.has("Ramparts of Perdition (E4M7)", player, 1) and state.has("Gauntlets of the Necromancer", player, 1) and state.has("Ethereal Crossbow", player, 1) and state.has("Dragon Claw", player, 1) and state.has("Firemace", player, 1)) and (state.has("Phoenix Rod", player, 1) or state.has("Hellstaff", player, 1))) set_rule(multiworld.get_entrance("Ramparts of Perdition (E4M7) Main -> Ramparts of Perdition (E4M7) Yellow", player), lambda state: state.has("Ramparts of Perdition (E4M7) - Yellow key", player, 1)) set_rule(multiworld.get_entrance("Ramparts of Perdition (E4M7) Blue -> Ramparts of Perdition (E4M7) Yellow", player), lambda state: state.has("Ramparts of Perdition (E4M7) - Blue key", player, 1)) set_rule(multiworld.get_entrance("Ramparts of Perdition (E4M7) Yellow -> Ramparts of Perdition (E4M7) Main", player), lambda state: state.has("Ramparts of Perdition (E4M7) - Yellow key", player, 1)) set_rule(multiworld.get_entrance("Ramparts of Perdition (E4M7) Yellow -> Ramparts of Perdition (E4M7) Green", player), lambda state: state.has("Ramparts of Perdition (E4M7) - Green key", player, 1)) set_rule(multiworld.get_entrance("Ramparts of Perdition (E4M7) Yellow -> Ramparts of Perdition (E4M7) Blue", player), lambda state: state.has("Ramparts of Perdition (E4M7) - Blue key", player, 1)) set_rule(multiworld.get_entrance("Ramparts of Perdition (E4M7) Green -> Ramparts of Perdition (E4M7) Yellow", player), lambda state: state.has("Ramparts of Perdition (E4M7) - Green key", player, 1)) # Shattered Bridge (E4M8) set_rule(multiworld.get_entrance("Hub -> Shattered Bridge (E4M8) Main", player), lambda state: state.has("Shattered Bridge (E4M8)", player, 1) and state.has("Gauntlets of the Necromancer", player, 1) and state.has("Ethereal Crossbow", player, 1) and state.has("Dragon Claw", player, 1) and state.has("Phoenix Rod", player, 1) and state.has("Firemace", player, 1) and state.has("Hellstaff", player, 1)) set_rule(multiworld.get_entrance("Shattered Bridge (E4M8) Main -> Shattered Bridge (E4M8) Yellow", player), lambda state: state.has("Shattered Bridge (E4M8) - Yellow key", player, 1)) set_rule(multiworld.get_entrance("Shattered Bridge (E4M8) Yellow -> Shattered Bridge (E4M8) Main", player), lambda state: state.has("Shattered Bridge (E4M8) - Yellow key", player, 1)) # Mausoleum (E4M9) set_rule(multiworld.get_entrance("Hub -> Mausoleum (E4M9) Main", player), lambda state: (state.has("Mausoleum (E4M9)", player, 1) and state.has("Gauntlets of the Necromancer", player, 1) and state.has("Ethereal Crossbow", player, 1) and state.has("Dragon Claw", player, 1) and state.has("Firemace", player, 1)) and (state.has("Phoenix Rod", player, 1) or state.has("Hellstaff", player, 1))) set_rule(multiworld.get_entrance("Mausoleum (E4M9) Main -> Mausoleum (E4M9) Yellow", player), lambda state: state.has("Mausoleum (E4M9) - Yellow key", player, 1)) set_rule(multiworld.get_entrance("Mausoleum (E4M9) Yellow -> Mausoleum (E4M9) Main", player), lambda state: state.has("Mausoleum (E4M9) - Yellow key", player, 1)) def set_episode5_rules(player, multiworld, pro): # Ochre Cliffs (E5M1) set_rule(multiworld.get_entrance("Hub -> Ochre Cliffs (E5M1) Main", player), lambda state: state.has("Ochre Cliffs (E5M1)", player, 1)) set_rule(multiworld.get_entrance("Ochre Cliffs (E5M1) Main -> Ochre Cliffs (E5M1) Yellow", player), lambda state: state.has("Ochre Cliffs (E5M1) - Yellow key", player, 1)) set_rule(multiworld.get_entrance("Ochre Cliffs (E5M1) Blue -> Ochre Cliffs (E5M1) Yellow", player), lambda state: state.has("Ochre Cliffs (E5M1) - Blue key", player, 1)) set_rule(multiworld.get_entrance("Ochre Cliffs (E5M1) Yellow -> Ochre Cliffs (E5M1) Main", player), lambda state: state.has("Ochre Cliffs (E5M1) - Yellow key", player, 1)) set_rule(multiworld.get_entrance("Ochre Cliffs (E5M1) Yellow -> Ochre Cliffs (E5M1) Green", player), lambda state: state.has("Ochre Cliffs (E5M1) - Green key", player, 1)) set_rule(multiworld.get_entrance("Ochre Cliffs (E5M1) Yellow -> Ochre Cliffs (E5M1) Blue", player), lambda state: state.has("Ochre Cliffs (E5M1) - Blue key", player, 1)) set_rule(multiworld.get_entrance("Ochre Cliffs (E5M1) Green -> Ochre Cliffs (E5M1) Yellow", player), lambda state: state.has("Ochre Cliffs (E5M1) - Green key", player, 1)) # Rapids (E5M2) set_rule(multiworld.get_entrance("Hub -> Rapids (E5M2) Main", player), lambda state: state.has("Rapids (E5M2)", player, 1) and state.has("Ethereal Crossbow", player, 1) and state.has("Dragon Claw", player, 1)) set_rule(multiworld.get_entrance("Rapids (E5M2) Main -> Rapids (E5M2) Yellow", player), lambda state: state.has("Rapids (E5M2) - Yellow key", player, 1)) set_rule(multiworld.get_entrance("Rapids (E5M2) Yellow -> Rapids (E5M2) Main", player), lambda state: state.has("Rapids (E5M2) - Yellow key", player, 1)) set_rule(multiworld.get_entrance("Rapids (E5M2) Yellow -> Rapids (E5M2) Green", player), lambda state: state.has("Rapids (E5M2) - Green key", player, 1)) # Quay (E5M3) set_rule(multiworld.get_entrance("Hub -> Quay (E5M3) Main", player), lambda state: (state.has("Quay (E5M3)", player, 1) and state.has("Ethereal Crossbow", player, 1) and state.has("Dragon Claw", player, 1)) and (state.has("Phoenix Rod", player, 1) or state.has("Hellstaff", player, 1) or state.has("Firemace", player, 1))) set_rule(multiworld.get_entrance("Quay (E5M3) Main -> Quay (E5M3) Yellow", player), lambda state: state.has("Quay (E5M3) - Yellow key", player, 1)) set_rule(multiworld.get_entrance("Quay (E5M3) Main -> Quay (E5M3) Green", player), lambda state: state.has("Quay (E5M3) - Green key", player, 1)) set_rule(multiworld.get_entrance("Quay (E5M3) Main -> Quay (E5M3) Blue", player), lambda state: state.has("Quay (E5M3) - Blue key", player, 1)) set_rule(multiworld.get_entrance("Quay (E5M3) Yellow -> Quay (E5M3) Main", player), lambda state: state.has("Quay (E5M3) - Yellow key", player, 1)) set_rule(multiworld.get_entrance("Quay (E5M3) Green -> Quay (E5M3) Main", player), lambda state: state.has("Quay (E5M3) - Green key", player, 1)) set_rule(multiworld.get_entrance("Quay (E5M3) Green -> Quay (E5M3) Cyan", player), lambda state: state.has("Quay (E5M3) - Blue key", player, 1)) # Courtyard (E5M4) set_rule(multiworld.get_entrance("Hub -> Courtyard (E5M4) Main", player), lambda state: (state.has("Courtyard (E5M4)", player, 1) and state.has("Ethereal Crossbow", player, 1) and state.has("Dragon Claw", player, 1)) and (state.has("Phoenix Rod", player, 1) or state.has("Firemace", player, 1) or state.has("Hellstaff", player, 1))) set_rule(multiworld.get_entrance("Courtyard (E5M4) Main -> Courtyard (E5M4) Yellow", player), lambda state: state.has("Courtyard (E5M4) - Yellow key", player, 1)) set_rule(multiworld.get_entrance("Courtyard (E5M4) Main -> Courtyard (E5M4) Blue", player), lambda state: state.has("Courtyard (E5M4) - Blue key", player, 1)) set_rule(multiworld.get_entrance("Courtyard (E5M4) Blue -> Courtyard (E5M4) Main", player), lambda state: state.has("Courtyard (E5M4) - Blue key", player, 1)) set_rule(multiworld.get_entrance("Courtyard (E5M4) Yellow -> Courtyard (E5M4) Main", player), lambda state: state.has("Courtyard (E5M4) - Yellow key", player, 1)) set_rule(multiworld.get_entrance("Courtyard (E5M4) Yellow -> Courtyard (E5M4) Green", player), lambda state: state.has("Courtyard (E5M4) - Green key", player, 1)) set_rule(multiworld.get_entrance("Courtyard (E5M4) Green -> Courtyard (E5M4) Yellow", player), lambda state: state.has("Courtyard (E5M4) - Green key", player, 1)) # Hydratyr (E5M5) set_rule(multiworld.get_entrance("Hub -> Hydratyr (E5M5) Main", player), lambda state: (state.has("Hydratyr (E5M5)", player, 1) and state.has("Ethereal Crossbow", player, 1) and state.has("Dragon Claw", player, 1) and state.has("Firemace", player, 1)) and (state.has("Phoenix Rod", player, 1) or state.has("Hellstaff", player, 1))) set_rule(multiworld.get_entrance("Hydratyr (E5M5) Main -> Hydratyr (E5M5) Yellow", player), lambda state: state.has("Hydratyr (E5M5) - Yellow key", player, 1)) set_rule(multiworld.get_entrance("Hydratyr (E5M5) Blue -> Hydratyr (E5M5) Green", player), lambda state: state.has("Hydratyr (E5M5) - Blue key", player, 1)) set_rule(multiworld.get_entrance("Hydratyr (E5M5) Yellow -> Hydratyr (E5M5) Green", player), lambda state: state.has("Hydratyr (E5M5) - Green key", player, 1)) set_rule(multiworld.get_entrance("Hydratyr (E5M5) Green -> Hydratyr (E5M5) Blue", player), lambda state: state.has("Hydratyr (E5M5) - Blue key", player, 1)) # Colonnade (E5M6) set_rule(multiworld.get_entrance("Hub -> Colonnade (E5M6) Main", player), lambda state: (state.has("Colonnade (E5M6)", player, 1) and state.has("Ethereal Crossbow", player, 1) and state.has("Dragon Claw", player, 1) and state.has("Firemace", player, 1) and state.has("Gauntlets of the Necromancer", player, 1)) and (state.has("Phoenix Rod", player, 1) or state.has("Hellstaff", player, 1))) set_rule(multiworld.get_entrance("Colonnade (E5M6) Main -> Colonnade (E5M6) Yellow", player), lambda state: state.has("Colonnade (E5M6) - Yellow key", player, 1)) set_rule(multiworld.get_entrance("Colonnade (E5M6) Main -> Colonnade (E5M6) Blue", player), lambda state: state.has("Colonnade (E5M6) - Blue key", player, 1)) set_rule(multiworld.get_entrance("Colonnade (E5M6) Blue -> Colonnade (E5M6) Main", player), lambda state: state.has("Colonnade (E5M6) - Blue key", player, 1)) set_rule(multiworld.get_entrance("Colonnade (E5M6) Yellow -> Colonnade (E5M6) Green", player), lambda state: state.has("Colonnade (E5M6) - Green key", player, 1)) set_rule(multiworld.get_entrance("Colonnade (E5M6) Green -> Colonnade (E5M6) Yellow", player), lambda state: state.has("Colonnade (E5M6) - Green key", player, 1)) # Foetid Manse (E5M7) set_rule(multiworld.get_entrance("Hub -> Foetid Manse (E5M7) Main", player), lambda state: (state.has("Foetid Manse (E5M7)", player, 1) and state.has("Ethereal Crossbow", player, 1) and state.has("Dragon Claw", player, 1) and state.has("Firemace", player, 1) and state.has("Gauntlets of the Necromancer", player, 1)) and (state.has("Phoenix Rod", player, 1) or state.has("Hellstaff", player, 1))) set_rule(multiworld.get_entrance("Foetid Manse (E5M7) Main -> Foetid Manse (E5M7) Yellow", player), lambda state: state.has("Foetid Manse (E5M7) - Yellow key", player, 1)) set_rule(multiworld.get_entrance("Foetid Manse (E5M7) Yellow -> Foetid Manse (E5M7) Green", player), lambda state: state.has("Foetid Manse (E5M7) - Green key", player, 1)) set_rule(multiworld.get_entrance("Foetid Manse (E5M7) Yellow -> Foetid Manse (E5M7) Blue", player), lambda state: state.has("Foetid Manse (E5M7) - Blue key", player, 1)) # Field of Judgement (E5M8) set_rule(multiworld.get_entrance("Hub -> Field of Judgement (E5M8) Main", player), lambda state: state.has("Field of Judgement (E5M8)", player, 1) and state.has("Ethereal Crossbow", player, 1) and state.has("Dragon Claw", player, 1) and state.has("Phoenix Rod", player, 1) and state.has("Firemace", player, 1) and state.has("Hellstaff", player, 1) and state.has("Gauntlets of the Necromancer", player, 1)) # Skein of D'Sparil (E5M9) set_rule(multiworld.get_entrance("Hub -> Skein of D'Sparil (E5M9) Main", player), lambda state: state.has("Skein of D'Sparil (E5M9)", player, 1) and state.has("Hellstaff", player, 1) and state.has("Phoenix Rod", player, 1) and state.has("Dragon Claw", player, 1) and state.has("Ethereal Crossbow", player, 1) and state.has("Gauntlets of the Necromancer", player, 1) and state.has("Firemace", player, 1)) set_rule(multiworld.get_entrance("Skein of D'Sparil (E5M9) Main -> Skein of D'Sparil (E5M9) Blue", player), lambda state: state.has("Skein of D'Sparil (E5M9) - Blue key", player, 1)) set_rule(multiworld.get_entrance("Skein of D'Sparil (E5M9) Main -> Skein of D'Sparil (E5M9) Yellow", player), lambda state: state.has("Skein of D'Sparil (E5M9) - Yellow key", player, 1)) set_rule(multiworld.get_entrance("Skein of D'Sparil (E5M9) Main -> Skein of D'Sparil (E5M9) Green", player), lambda state: state.has("Skein of D'Sparil (E5M9) - Green key", player, 1)) set_rule(multiworld.get_entrance("Skein of D'Sparil (E5M9) Yellow -> Skein of D'Sparil (E5M9) Main", player), lambda state: state.has("Skein of D'Sparil (E5M9) - Yellow key", player, 1)) set_rule(multiworld.get_entrance("Skein of D'Sparil (E5M9) Green -> Skein of D'Sparil (E5M9) Main", player), lambda state: state.has("Skein of D'Sparil (E5M9) - Green key", player, 1)) def set_rules(heretic_world: "HereticWorld", included_episodes, pro): player = heretic_world.player multiworld = heretic_world.multiworld if included_episodes[0]: set_episode1_rules(player, multiworld, pro) if included_episodes[1]: set_episode2_rules(player, multiworld, pro) if included_episodes[2]: set_episode3_rules(player, multiworld, pro) if included_episodes[3]: set_episode4_rules(player, multiworld, pro) if included_episodes[4]: set_episode5_rules(player, multiworld, pro)
411
0.710861
1
0.710861
game-dev
MEDIA
0.79927
game-dev,testing-qa
0.789327
1
0.789327
revolucas/CoC-Xray
3,156
src/xrGame/patrol_path_manager_inline.h
//////////////////////////////////////////////////////////////////////////// // Module : patrol_path_manager_inline.h // Created : 03.12.2003 // Modified : 03.12.2003 // Author : Dmitriy Iassenev // Description : Patrol path manager inline functions //////////////////////////////////////////////////////////////////////////// #pragma once IC CPatrolPathManager::CPatrolPathManager (CRestrictedObject *object, CGameObject *game_object) { m_object = object; VERIFY (game_object); m_game_object = game_object; m_path = 0; m_path_name = ""; m_start_type = ePatrolStartTypeDummy; m_route_type = ePatrolRouteTypeDummy; m_actuality = true; m_failed = false; m_completed = true; m_random = false; m_curr_point_index = u32(-1); m_prev_point_index = u32(-1); m_start_point_index = u32(-1); m_dest_position.set (flt_max,flt_max,flt_max); } IC bool CPatrolPathManager::actual () const { return (m_actuality); } IC bool CPatrolPathManager::failed () const { return (m_failed); } IC const CPatrolPath *CPatrolPathManager::get_path () const { return (m_path); } IC bool CPatrolPathManager::completed () const { return (m_completed); } IC bool CPatrolPathManager::random () const { return (m_random); } IC const Fvector &CPatrolPathManager::destination_position () const { VERIFY (_valid(m_dest_position)); return (m_dest_position); } IC void CPatrolPathManager::set_path (const CPatrolPath *path, shared_str path_name) { if (m_path == path) return; m_path = path; m_path_name = path_name; m_actuality = false; m_completed = false; reset (); } IC void CPatrolPathManager::set_start_type (const EPatrolStartType patrol_start_type) { m_actuality = m_actuality && (m_start_type == patrol_start_type); m_completed = m_completed && m_actuality; m_start_type = patrol_start_type; } IC void CPatrolPathManager::set_route_type (const EPatrolRouteType patrol_route_type) { m_actuality = m_actuality && (m_route_type == patrol_route_type); m_completed = m_completed && m_actuality; m_route_type = patrol_route_type; } IC void CPatrolPathManager::set_random (bool random) { m_random = random; } IC void CPatrolPathManager::make_inactual () { m_actuality = false; m_completed = false; } IC void CPatrolPathManager::set_path (shared_str path_name) { set_path (ai().patrol_paths().path(path_name), path_name); } IC void CPatrolPathManager::set_path (shared_str path_name, const EPatrolStartType patrol_start_type, const EPatrolRouteType patrol_route_type, bool random) { set_path (ai().patrol_paths().path(path_name), path_name); set_start_type (patrol_start_type); set_route_type (patrol_route_type); set_random (random); } IC u32 CPatrolPathManager::get_current_point_index() const { return (m_curr_point_index); } IC CRestrictedObject &CPatrolPathManager::object () const { VERIFY (m_object); return (*m_object); } IC CPatrolPathManager::CExtrapolateCallback &CPatrolPathManager::extrapolate_callback () { return (m_extrapolate_callback); }
411
0.959187
1
0.959187
game-dev
MEDIA
0.378534
game-dev
0.942842
1
0.942842
Hoyotoon/HoyoToon
11,197
Scripts/Editor/Shader UI/EditorStructs/ShaderHeader.cs
#if UNITY_EDITOR using System.Collections.Generic; using HoyoToon.HoyoToonEditor; using UnityEditor; using UnityEngine; namespace HoyoToon { public class ShaderHeader : ShaderGroup { public ShaderHeader(ShaderEditor shaderEditor) : base(shaderEditor) { } public ShaderHeader(ShaderEditor shaderEditor, MaterialProperty prop, MaterialEditor materialEditor, string displayName, int xOffset, string optionsRaw, int propertyIndex) : base(shaderEditor, prop, materialEditor, displayName, xOffset, optionsRaw, propertyIndex) { } public override void DrawInternal(GUIContent content, Rect? rect = null, bool useEditorIndent = false, bool isInHeader = false) { ActiveShaderEditor.CurrentProperty = this; EditorGUI.BeginChangeCheck(); Rect position = GUILayoutUtility.GetRect(content, Styles.dropDownHeader); DrawHeader(position, content); Rect headerRect = DrawingData.LastGuiObjectHeaderRect; if (IsExpanded) { if (ShaderEditor.Active.IsSectionedPresetEditor) { string presetName = Presets.GetSectionPresetName(ShaderEditor.Active.Materials[0], this.MaterialProperty.name); EditorGUI.BeginChangeCheck(); presetName = EditorGUILayout.DelayedTextField("Preset Name:", presetName); if (EditorGUI.EndChangeCheck()) { Presets.SetSectionPreset(ShaderEditor.Active.Materials[0], this.MaterialProperty.name, presetName); } } EditorGUILayout.Space(); EditorGUI.BeginDisabledGroup(DoDisableChildren); foreach (ShaderPart part in parts) { part.Draw(); } EditorGUI.EndDisabledGroup(); EditorGUILayout.Space(); } if (EditorGUI.EndChangeCheck()) HandleLinkedMaterials(); DrawingData.LastGuiObjectHeaderRect = headerRect; DrawingData.LastGuiObjectRect = headerRect; } private void DrawHeader(Rect position, GUIContent label) { PropertyOptions options = ShaderEditor.Active.CurrentProperty.Options; Event e = Event.current; int xOffset_total = XOffset * 15 + 15; position.width -= xOffset_total - position.x; position.x = xOffset_total; DrawingData.LastGuiObjectHeaderRect = position; DrawBoxAndContent(position, e, label, options); Rect arrowRect = new Rect(position) { height = 18 }; FoldoutArrow(arrowRect, e); HandleToggleInput(position); } private void DrawBoxAndContent(Rect rect, Event e, GUIContent content, PropertyOptions options) { if (options.reference_property != null && ShaderEditor.Active.PropertyDictionary.ContainsKey(options.reference_property)) { GUI.Box(rect, new GUIContent(" " + content.text, content.tooltip), Styles.dropDownHeader); DrawIcons(rect, options, e); Rect togglePropertyRect = new Rect(rect); togglePropertyRect.x += 5; togglePropertyRect.y += 1; togglePropertyRect.height -= 4; togglePropertyRect.width = GUI.skin.font.fontSize * 3; float fieldWidth = EditorGUIUtility.fieldWidth; EditorGUIUtility.fieldWidth = 20; ShaderProperty refProperty = ShaderEditor.Active.PropertyDictionary[options.reference_property]; EditorGUI.BeginChangeCheck(); int xOffset = refProperty.XOffset; refProperty.SetTemporaryXOffset(0); refProperty.Draw(togglePropertyRect, new GUIContent(), isInHeader: true); refProperty.ResetTemporaryXOffset(); EditorGUIUtility.fieldWidth = fieldWidth; // Change expand state if reference is toggled if (EditorGUI.EndChangeCheck() && Options.ref_float_toggles_expand) { IsExpanded = refProperty.MaterialProperty.GetNumber() == 1; } } // else if(keyword != null) // { // GUI.Box(rect, " " + content.text, Styles.dropDownHeader); // DrawIcons(rect, options, e); // Rect togglePropertyRect = new Rect(rect); // togglePropertyRect.x += 20; // togglePropertyRect.width = 20; // EditorGUI.BeginChangeCheck(); // bool keywordOn = EditorGUI.Toggle(togglePropertyRect, "", ShaderEditor.Active.Materials[0].IsKeywordEnabled(keyword)); // if (EditorGUI.EndChangeCheck()) // { // MaterialHelper.ToggleKeyword(ShaderEditor.Active.Materials, keyword, keywordOn); // } // } else { GUI.Box(rect, content, Styles.dropDownHeader); DrawIcons(rect, options, e); } } /// <summary> /// Draws the icons for ShaderEditor features like linking and copying /// </summary> /// <param name="rect"></param> /// <param name="e"></param> private void DrawIcons(Rect rect, PropertyOptions options, Event e) { Rect buttonRect = new Rect(rect); buttonRect.y += 1; buttonRect.height -= 4; buttonRect.width = buttonRect.height; float right = rect.x + rect.width; buttonRect.x = right - 74; //DrawPresetButton(buttonRect, options, e); buttonRect.x = right - 56; DrawHelpButton(buttonRect, options, e); buttonRect.x = right - 38; DrawLinkSettings(buttonRect, e); buttonRect.x = right - 20; DrawDowdownSettings(buttonRect, e); } private void DrawHelpButton(Rect rect, PropertyOptions options, Event e) { ButtonData button = options.button_help; if (button != null && button.condition_show.Test()) { if (GUILib.Button(rect, Styles.icon_style_help)) { ShaderEditor.Input.Use(); if (button.action != null) button.action.Perform(ShaderEditor.Active?.Materials); } } } private void DrawPresetButton(Rect rect, PropertyOptions options, Event e) { bool hasPresets = Presets.DoesSectionHavePresets(this.MaterialProperty.name); if (hasPresets) { if (GUILib.Button(rect, Styles.icon_style_presets)) { ShaderEditor.Input.Use(); Presets.OpenPresetsMenu(rect, ActiveShaderEditor, true, this.MaterialProperty.name); } } } private void DrawDowdownSettings(Rect rect, Event e) { if (GUILib.Button(rect, Styles.icon_style_menu)) { ShaderEditor.Input.Use(); Rect buttonRect = new Rect(rect); buttonRect.width = 150; buttonRect.x = Mathf.Min(Screen.width - buttonRect.width, buttonRect.x); buttonRect.height = 60; float maxY = GUIUtility.ScreenToGUIPoint(new Vector2(0, EditorWindow.focusedWindow.position.y + Screen.height)).y - 2.5f * buttonRect.height; buttonRect.y = Mathf.Min(buttonRect.y - buttonRect.height / 2, maxY); ShowHeaderContextMenu(buttonRect, ShaderEditor.Active.CurrentProperty, ShaderEditor.Active.Materials[0]); } } private void DrawLinkSettings(Rect rect, Event e) { if (GUILib.Button(rect, Styles.icon_style_linked, Styles.COLOR_ICON_ACTIVE_CYAN, MaterialLinker.IsLinked(ShaderEditor.Active.CurrentProperty.MaterialProperty))) { ShaderEditor.Input.Use(); List<Material> linked_materials = MaterialLinker.GetLinked(ShaderEditor.Active.CurrentProperty.MaterialProperty); MaterialLinker.Popup(rect, linked_materials, ShaderEditor.Active.CurrentProperty.MaterialProperty); } } void ShowHeaderContextMenu(Rect position, ShaderPart property, Material material) { var menu = new GenericMenu(); menu.AddItem(new GUIContent("Reset"), false, delegate () { property.CopyFromMaterial(new Material(material.shader), true); List<Material> linked_materials = MaterialLinker.GetLinked(property.MaterialProperty); if (linked_materials != null) foreach (Material m in linked_materials) property.CopyToMaterial(m, true); }); menu.AddItem(new GUIContent("Copy"), false, delegate () { Mediator.copy_material = new Material(material); Mediator.transfer_group = property; }); menu.AddItem(new GUIContent("Paste"), false, delegate () { if (Mediator.copy_material != null || Mediator.transfer_group != null) { property.TransferFromMaterialAndGroup(Mediator.copy_material, Mediator.transfer_group, true); List<Material> linked_materials = MaterialLinker.GetLinked(property.MaterialProperty); if (linked_materials != null) foreach (Material m in linked_materials) property.CopyToMaterial(m, true); } }); menu.AddItem(new GUIContent("Paste without Textures"), false, delegate () { if (Mediator.copy_material != null || Mediator.transfer_group != null) { var propsToIgnore = new MaterialProperty.PropType[] { MaterialProperty.PropType.Texture }; property.TransferFromMaterialAndGroup(Mediator.copy_material, Mediator.transfer_group, true, propsToIgnore); List<Material> linked_materials = MaterialLinker.GetLinked(property.MaterialProperty); if (linked_materials != null) foreach (Material m in linked_materials) property.CopyToMaterial(m, true, propsToIgnore); } }); menu.DropDown(position); } private void HandleToggleInput(Rect rect) { //Ignore unity uses is cause disabled will use the event to prevent toggling if (ShaderEditor.Input.LeftClick_IgnoreLocked && rect.Contains(ShaderEditor.Input.mouse_position) && !ShaderEditor.Input.is_alt_down) { IsExpanded = !IsExpanded; ShaderEditor.Input.Use(); } } } } #endif
411
0.930921
1
0.930921
game-dev
MEDIA
0.79289
game-dev,desktop-app
0.974945
1
0.974945
Synthlight/MHW-Editor
2,679
MHW-Generator/Items/EqCrt.cs
using System.Collections.Generic; using MHW_Generator.Models; using MHW_Template.Armors; using MHW_Template.Models; using MHW_Template.Struct_Generation; namespace MHW_Generator.Items { public class EqCrt : SingleStructBase, IMultiStruct { public MultiStruct Generate() { // .eq_crt var structs = new List<MhwMultiStructData.StructData> { CreateSingleStructBase(out var header, out var itemCount), new MhwMultiStructData.StructData("Entries", new List<MhwMultiStructData.Entry> { new MhwMultiStructData.Entry("Equipment Category Raw", typeof(byte), true), new MhwMultiStructData.Entry("Equipment Index Raw", typeof(ushort), true), new MhwMultiStructData.Entry("Needed Item Id to Unlock", typeof(ushort), dataSourceType: DataSourceType.Items), new MhwMultiStructData.Entry("Monster Unlock", typeof(int), dataSourceType: DataSourceType.MonstersNeg), new MhwMultiStructData.Entry("Story Unlock", typeof(uint)), new MhwMultiStructData.Entry("Unknown (uint32)", typeof(uint)), new MhwMultiStructData.Entry("Item Rank", typeof(uint), enumReturn: typeof(CharmRankType)), new MhwMultiStructData.Entry("Mat 1 Id", typeof(ushort), dataSourceType: DataSourceType.Items), new MhwMultiStructData.Entry("Mat 1 Count", typeof(byte)), new MhwMultiStructData.Entry("Mat 2 Id", typeof(ushort), dataSourceType: DataSourceType.Items), new MhwMultiStructData.Entry("Mat 2 Count", typeof(byte)), new MhwMultiStructData.Entry("Mat 3 Id", typeof(ushort), dataSourceType: DataSourceType.Items), new MhwMultiStructData.Entry("Mat 3 Count", typeof(byte)), new MhwMultiStructData.Entry("Mat 4 Id", typeof(ushort), dataSourceType: DataSourceType.Items), new MhwMultiStructData.Entry("Mat 4 Count", typeof(byte)), new MhwMultiStructData.Entry("Unknown (uint8) 1", typeof(byte)), new MhwMultiStructData.Entry("Unknown (uint8) 2", typeof(byte)), new MhwMultiStructData.Entry("Unknown (uint8) 3", typeof(byte)), new MhwMultiStructData.Entry("Unknown (uint8) 4", typeof(byte)) }, canAddRows: true, _010Link: new MhwMultiStructData.ArrayLink(header, itemCount), uniqueIdFormula: "{Equipment_Category_Raw}|{Equipment_Index_Raw}") }; return new MultiStruct("Items", "EqCrt", new MhwMultiStructData(structs, "eq_crt")); } } }
411
0.882244
1
0.882244
game-dev
MEDIA
0.548084
game-dev
0.735138
1
0.735138
godotengine/godot
9,242
tests/scene/test_packed_scene.h
/**************************************************************************/ /* test_packed_scene.h */ /**************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /**************************************************************************/ /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /**************************************************************************/ #pragma once #include "scene/resources/packed_scene.h" #include "tests/test_macros.h" namespace TestPackedScene { TEST_CASE("[PackedScene] Pack Scene and Retrieve State") { // Create a scene to pack. Node *scene = memnew(Node); scene->set_name("TestScene"); // Pack the scene. PackedScene packed_scene; const Error err = packed_scene.pack(scene); CHECK(err == OK); // Retrieve the packed state. Ref<SceneState> state = packed_scene.get_state(); CHECK(state.is_valid()); CHECK(state->get_node_count() == 1); CHECK(state->get_node_name(0) == "TestScene"); memdelete(scene); } TEST_CASE("[PackedScene] Signals Preserved when Packing Scene") { // Create main scene // root // `- sub_node (local) // `- sub_scene (instance of another scene) // `- sub_scene_node (owned by sub_scene) Node *main_scene_root = memnew(Node); Node *sub_node = memnew(Node); Node *sub_scene_root = memnew(Node); Node *sub_scene_node = memnew(Node); main_scene_root->add_child(sub_node); sub_node->set_owner(main_scene_root); sub_scene_root->add_child(sub_scene_node); sub_scene_node->set_owner(sub_scene_root); main_scene_root->add_child(sub_scene_root); sub_scene_root->set_owner(main_scene_root); SUBCASE("Signals that should be saved") { int main_flags = Object::CONNECT_PERSIST; // sub node to a node in main scene sub_node->connect("ready", callable_mp(main_scene_root, &Node::is_ready), main_flags); // subscene root to a node in main scene sub_scene_root->connect("ready", callable_mp(main_scene_root, &Node::is_ready), main_flags); //subscene root to subscene root (connected within main scene) sub_scene_root->connect("ready", callable_mp(sub_scene_root, &Node::is_ready), main_flags); // Pack the scene. Ref<PackedScene> packed_scene; packed_scene.instantiate(); const Error err = packed_scene->pack(main_scene_root); CHECK(err == OK); // Make sure the right connections are in packed scene. Ref<SceneState> state = packed_scene->get_state(); CHECK_EQ(state->get_connection_count(), 3); } /* // FIXME: This subcase requires GH-48064 to be fixed. SUBCASE("Signals that should not be saved") { int subscene_flags = Object::CONNECT_PERSIST | Object::CONNECT_INHERITED; // subscene node to itself sub_scene_node->connect("ready", callable_mp(sub_scene_node, &Node::is_ready), subscene_flags); // subscene node to subscene root sub_scene_node->connect("ready", callable_mp(sub_scene_root, &Node::is_ready), subscene_flags); //subscene root to subscene root (connected within sub scene) sub_scene_root->connect("ready", callable_mp(sub_scene_root, &Node::is_ready), subscene_flags); // Pack the scene. Ref<PackedScene> packed_scene; packed_scene.instantiate(); const Error err = packed_scene->pack(main_scene_root); CHECK(err == OK); // Make sure the right connections are in packed scene. Ref<SceneState> state = packed_scene->get_state(); CHECK_EQ(state->get_connection_count(), 0); } */ memdelete(main_scene_root); } TEST_CASE("[PackedScene] Clear Packed Scene") { // Create a scene to pack. Node *scene = memnew(Node); scene->set_name("TestScene"); // Pack the scene. PackedScene packed_scene; packed_scene.pack(scene); // Clear the packed scene. packed_scene.clear(); // Check if it has been cleared. Ref<SceneState> state = packed_scene.get_state(); CHECK_FALSE(state->get_node_count() == 1); memdelete(scene); } TEST_CASE("[PackedScene] Can Instantiate Packed Scene") { // Create a scene to pack. Node *scene = memnew(Node); scene->set_name("TestScene"); // Pack the scene. PackedScene packed_scene; packed_scene.pack(scene); // Check if the packed scene can be instantiated. const bool can_instantiate = packed_scene.can_instantiate(); CHECK(can_instantiate == true); memdelete(scene); } TEST_CASE("[PackedScene] Instantiate Packed Scene") { // Create a scene to pack. Node *scene = memnew(Node); scene->set_name("TestScene"); // Pack the scene. PackedScene packed_scene; packed_scene.pack(scene); // Instantiate the packed scene. Node *instance = packed_scene.instantiate(); CHECK(instance != nullptr); CHECK(instance->get_name() == "TestScene"); memdelete(scene); memdelete(instance); } TEST_CASE("[PackedScene] Instantiate Packed Scene With Children") { // Create a scene to pack. Node *scene = memnew(Node); scene->set_name("TestScene"); // Add persisting child nodes to the scene. Node *child1 = memnew(Node); child1->set_name("Child1"); scene->add_child(child1); child1->set_owner(scene); Node *child2 = memnew(Node); child2->set_name("Child2"); scene->add_child(child2); child2->set_owner(scene); // Add non persisting child node to the scene. Node *child3 = memnew(Node); child3->set_name("Child3"); scene->add_child(child3); // Pack the scene. PackedScene packed_scene; packed_scene.pack(scene); // Instantiate the packed scene. Node *instance = packed_scene.instantiate(); CHECK(instance != nullptr); CHECK(instance->get_name() == "TestScene"); // Validate the child nodes of the instantiated scene. CHECK(instance->get_child_count() == 2); CHECK(instance->get_child(0)->get_name() == "Child1"); CHECK(instance->get_child(1)->get_name() == "Child2"); CHECK(instance->get_child(0)->get_owner() == instance); CHECK(instance->get_child(1)->get_owner() == instance); memdelete(scene); memdelete(instance); } TEST_CASE("[PackedScene] Set Path") { // Create a scene to pack. Node *scene = memnew(Node); scene->set_name("TestScene"); // Pack the scene. PackedScene packed_scene; packed_scene.pack(scene); // Set a new path for the packed scene. const String new_path = "NewTestPath"; packed_scene.set_path(new_path); // Check if the path has been set correctly. Ref<SceneState> state = packed_scene.get_state(); CHECK(state.is_valid()); CHECK(state->get_path() == new_path); memdelete(scene); } TEST_CASE("[PackedScene] Replace State") { // Create a scene to pack. Node *scene = memnew(Node); scene->set_name("TestScene"); // Pack the scene. PackedScene packed_scene; packed_scene.pack(scene); // Create another scene state to replace with. Ref<SceneState> new_state = memnew(SceneState); new_state->set_path("NewPath"); // Replace the state. packed_scene.replace_state(new_state); // Check if the state has been replaced. Ref<SceneState> state = packed_scene.get_state(); CHECK(state.is_valid()); CHECK(state == new_state); memdelete(scene); } TEST_CASE("[PackedScene] Recreate State") { // Create a scene to pack. Node *scene = memnew(Node); scene->set_name("TestScene"); // Pack the scene. PackedScene packed_scene; packed_scene.pack(scene); // Recreate the state. packed_scene.recreate_state(); // Check if the state has been recreated. Ref<SceneState> state = packed_scene.get_state(); CHECK(state.is_valid()); CHECK(state->get_node_count() == 0); // Since the state was recreated, it should be empty. memdelete(scene); } } // namespace TestPackedScene
411
0.780795
1
0.780795
game-dev
MEDIA
0.85143
game-dev
0.717471
1
0.717471
darjun/go-daily-lib
1,156
ebiten/3-bgcolor/main.go
package main import ( "fmt" "github.com/hajimehoshi/ebiten/v2/ebitenutil" "image/color" "log" "github.com/hajimehoshi/ebiten/v2" ) type Input struct { msg string } func (i *Input) Update() { if ebiten.IsKeyPressed(ebiten.KeyLeft) { fmt.Println("←←←←←←←←←←←←←←←←←←←←←←←") i.msg = "left pressed" } else if ebiten.IsKeyPressed(ebiten.KeyRight) { fmt.Println("→→→→→→→→→→→→→→→→→→→→→→→") i.msg = "right pressed" } else if ebiten.IsKeyPressed(ebiten.KeySpace) { fmt.Println("-----------------------") i.msg = "space pressed" } } type Game struct { input *Input } func NewGame() *Game { return &Game{ input: &Input{msg: "Hello, World!"}, } } func (g *Game) Update() error { g.input.Update() return nil } func (g *Game) Draw(screen *ebiten.Image) { screen.Fill(color.RGBA{R: 200, G: 200, B: 200, A: 255}) ebitenutil.DebugPrint(screen, g.input.msg) } func (g *Game) Layout(outsideWidth, outsideHeight int) (screenWidth, screenHeight int) { return 320, 240 } func main() { ebiten.SetWindowSize(640, 480) ebiten.SetWindowTitle("外星人入侵") game := NewGame() if err := ebiten.RunGame(game); err != nil { log.Fatal(err) } }
411
0.556336
1
0.556336
game-dev
MEDIA
0.684181
game-dev
0.729179
1
0.729179
jichu4n/palm-os-sdk
1,321
PalmOne/Samples/MiniMPEG4/Src/Common.c
/*********************************************************************** * * Copyright (c) 2004 PalmOne, Inc. or its subsidiaries. * All rights reserved. * ***********************************************************************/ /*********************************************************************** * * File: * Common.c * * Description: * Useful functions * * Author: * September 19, 2002 Created by Nicolas Pabion * ***********************************************************************/ #include <PalmOS.h> #include "Common.h" /*********************************************************************** * * FUNCTION: SetFieldTextFromStr * * DESCRIPTION: * * PARAMETERS: * * RETURNED: N/A * ***********************************************************************/ Err SetFieldTextFromStr(FieldPtr field, Char *s, Boolean redraw) { MemHandle h; h = FldGetTextHandle(field); if(h) { Err err; FldSetTextHandle(field, NULL); err = MemHandleResize(h, StrLen(s)+1); if(err!=errNone) { FldSetTextHandle(field, h); return err; } } else { h = MemHandleNew(StrLen(s)+1); if(!h) return memErrNotEnoughSpace; } StrCopy((Char *)MemHandleLock(h), s); MemHandleUnlock(h); FldSetTextHandle(field, h); if(redraw) FldDrawField(field); return errNone; }
411
0.51036
1
0.51036
game-dev
MEDIA
0.210316
game-dev
0.642763
1
0.642763
CharsetMC/Charset
12,268
src/main/java/pl/asie/charset/module/power/mechanical/TileGearbox.java
/* * Copyright (c) 2015, 2016, 2017, 2018, 2019, 2020 Adrian Siekierka * * This file is part of Charset. * * Charset is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Charset 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 Charset. If not, see <http://www.gnu.org/licenses/>. */ package pl.asie.charset.module.power.mechanical; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.ITickable; import net.minecraft.util.Mirror; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; import net.minecraft.world.World; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.util.Constants; import net.minecraftforge.fml.relauncher.Side; import pl.asie.charset.api.lib.IAxisRotatable; import pl.asie.charset.api.lib.IDebuggable; import pl.asie.charset.lib.CharsetLib; import pl.asie.charset.lib.block.ITileWrenchRotatable; import pl.asie.charset.lib.block.TileBase; import pl.asie.charset.lib.block.TraitMaterial; import pl.asie.charset.lib.capability.Capabilities; import pl.asie.charset.lib.material.ItemMaterial; import pl.asie.charset.lib.material.ItemMaterialRegistry; import pl.asie.charset.lib.utils.ItemUtils; import pl.asie.charset.lib.utils.Orientation; import pl.asie.charset.lib.utils.Quaternion; import pl.asie.charset.api.experimental.mechanical.IItemGear; import pl.asie.charset.api.experimental.mechanical.IMechanicalPowerConsumer; import pl.asie.charset.api.experimental.mechanical.IMechanicalPowerProducer; import javax.annotation.Nullable; import java.util.List; public class TileGearbox extends TileBase implements IMechanicalPowerProducer, ITickable, IAxisRotatable, ITileWrenchRotatable { private class Consumer implements IMechanicalPowerConsumer { protected TileEntity receiver; protected double speedIn, torqueIn; private final EnumFacing facing; private Consumer(EnumFacing facing) { this.facing = facing; } public void verifyReceiver() { if (receiver == null || receiver.isInvalid()) { receiver = null; speedIn = torqueIn = 0.0D; } } @Override public boolean isAcceptingPower() { return true; } @Override public void setForce(double speed, double torque) { this.receiver = world.getTileEntity(pos.offset(facing)); this.speedIn = speed; this.torqueIn = torque; } } protected ItemStack[] inv = new ItemStack[] { ItemStack.EMPTY, ItemStack.EMPTY, ItemStack.EMPTY }; public final TraitMechanicalRotation ROTATION; protected Consumer[] consumerHandlers; protected double speedIn, torqueIn, modifier; protected int consumerCount; protected boolean isRedstonePowered; protected boolean acceptingForce; protected TraitMaterial material; public TileGearbox() { consumerHandlers = new Consumer[6]; registerTrait("wood", material = new TraitMaterial("wood", ItemMaterialRegistry.INSTANCE.getDefaultMaterialByType("plank"))); for (int i = 0; i < 6; i++) { consumerHandlers[i] = new Consumer(EnumFacing.byIndex(i)); } registerTrait("rot", ROTATION = new TraitMechanicalRotation()); } public ItemStack getInventoryStack(int i) { if (i < 0 || i >= inv.length) { return ItemStack.EMPTY; } else { return inv[i]; } } public int getConsumerCount() { return consumerCount; } public double getTorqueIn() { return torqueIn; } public double getSpeedIn() { return speedIn; } public double getSpeedModifier() { return modifier; } public boolean isRedstonePowered() { return isRedstonePowered; } public Orientation getOrientation() { return world.getBlockState(pos).getValue(BlockGearbox.ORIENTATION); } public EnumFacing getConfigurationSide() { return getOrientation().facing; } public ItemMaterial getMaterial() { return material.getMaterial(); } @Override public void onPlacedBy(EntityLivingBase placer, @Nullable EnumFacing face, ItemStack stack, float hitX, float hitY, float hitZ) { super.onPlacedBy(placer, face, stack, hitX, hitY, hitZ); neighborChanged(); } @Override public boolean hasCapability(Capability<?> capability, @Nullable EnumFacing facing) { EnumFacing facingIn = getConfigurationSide(); if (capability == Capabilities.MECHANICAL_PRODUCER || capability == Capabilities.MECHANICAL_CONSUMER) { return facing != null && facing != facingIn; } return super.hasCapability(capability, facing); } @Override @SuppressWarnings("unchecked") public <T> T getCapability(Capability<T> capability, @Nullable EnumFacing facing) { if (capability == Capabilities.MECHANICAL_PRODUCER) { if (facing != null) { return Capabilities.MECHANICAL_PRODUCER.cast(this); } else { return null; } } else if (capability == Capabilities.MECHANICAL_CONSUMER) { if (facing != null) { return Capabilities.MECHANICAL_CONSUMER.cast(consumerHandlers[facing.ordinal()]); } else { return null; } } else { return super.getCapability(capability, facing); } } @Override public void update() { super.update(); ROTATION.tick(getSpeedIn()); if (world.isRemote) { return; } IMechanicalPowerConsumer[] consumers = new IMechanicalPowerConsumer[6]; acceptingForce = false; double oldSpeedIn = speedIn; double oldTorqueIn = torqueIn; double oldModifier = modifier; int oldConsumerCount = consumerCount; modifier = 0.0; speedIn = torqueIn = 0.0D; int producerCount = 0; consumerCount = 0; ItemStack gearOne = inv[isRedstonePowered() ? 2 : 0]; ItemStack gearTwo = inv[1]; if (gearOne.isEmpty() || gearTwo.isEmpty() || !(gearOne.getItem() instanceof IItemGear) || !(gearTwo.getItem() instanceof IItemGear)) { modifier = 0.0; } else { modifier = (double) ((IItemGear) gearOne.getItem()).getGearValue(gearOne) / ((IItemGear) gearTwo.getItem()).getGearValue(gearTwo); } EnumFacing facingIn = getConfigurationSide(); for (EnumFacing facing : EnumFacing.VALUES) { if (facing == facingIn) continue; consumerHandlers[facing.ordinal()].verifyReceiver(); if (consumerHandlers[facing.ordinal()].torqueIn != 0.0) { producerCount++; if (producerCount > 1) { speedIn = 0.0D; torqueIn = 0.0D; break; } else { speedIn = consumerHandlers[facing.ordinal()].speedIn; torqueIn = consumerHandlers[facing.ordinal()].torqueIn; } } else { TileEntity tile = world.getTileEntity(pos.offset(facing)); if (tile != null && tile.hasCapability(Capabilities.MECHANICAL_CONSUMER, facing.getOpposite())) { IMechanicalPowerConsumer consumer = tile.getCapability(Capabilities.MECHANICAL_CONSUMER, facing.getOpposite()); if (consumer != null && consumer.isAcceptingPower()) { consumers[facing.ordinal()] = consumer; consumerCount++; acceptingForce = true; } } } } if (acceptingForce) { if (modifier > 0.0) { for (EnumFacing facing : EnumFacing.VALUES) { if (consumers[facing.ordinal()] != null) { consumers[facing.ordinal()].setForce(speedIn * modifier / consumerCount, torqueIn / modifier); } } } else { for (EnumFacing facing : EnumFacing.VALUES) { if (consumers[facing.ordinal()] != null) { consumers[facing.ordinal()].setForce(0,0); } } } } if (oldSpeedIn != speedIn || oldModifier != modifier || oldTorqueIn != torqueIn || oldConsumerCount != consumerCount) { markBlockForUpdate(); } } public void neighborChanged() { boolean oldIRP = isRedstonePowered; isRedstonePowered = world.isBlockPowered(pos); if (isRedstonePowered != oldIRP) { markChunkDirty(); markBlockForUpdate(); } } private int getGearHit(Vec3d hitPos) { hitPos = hitPos.subtract(0.5, 0.5, 0.5); Orientation o = getOrientation(); Quaternion quat = Quaternion.fromOrientation(o); Vec3d gearPos1 = quat.applyRotation(new Vec3d( 10/32f - 0.5f, 0.5, 0.5f - 21/32f)); Vec3d gearPos2 = quat.applyRotation(new Vec3d( 16/32f - 0.5f, 0.5, 0.5f - 10/32f)); Vec3d gearPos3 = quat.applyRotation(new Vec3d( 22/32f - 0.5f, 0.5, 0.5f - 21/32f)); double[] distances = new double[] { hitPos.squareDistanceTo(gearPos1), hitPos.squareDistanceTo(gearPos2), hitPos.squareDistanceTo(gearPos3) }; double lowestD = distances[0]; int i = 0; if (distances[1] < lowestD) { lowestD = distances[1]; i = 1; } return distances[2] < lowestD ? 2 : i; } public boolean activate(EntityPlayer player, EnumFacing side, EnumHand hand, Vec3d hitPos) { if (side != getConfigurationSide()) { return false; } int i = getGearHit(hitPos); ItemStack stack = player.getHeldItem(hand); if (!inv[i].isEmpty() && (player.isCreative() || player.addItemStackToInventory(inv[i]))) { inv[i] = ItemStack.EMPTY; markChunkDirty(); markBlockForUpdate(); return true; } else if (inv[i].isEmpty() && !stack.isEmpty() && stack.getItem() instanceof IItemGear) { if (player.isCreative()) { inv[i] = stack.copy(); inv[i].setCount(1); } else { inv[i] = stack.splitStack(1); } markChunkDirty(); markBlockForUpdate(); return true; } else { return false; } } @Override public void readNBTData(NBTTagCompound compound, boolean isClient) { super.readNBTData(compound, isClient); for (int i = 0; i < inv.length; i++) { if (compound.hasKey("inv" + i, Constants.NBT.TAG_COMPOUND)) { inv[i] = new ItemStack(compound.getCompoundTag("inv" + i)); } else { inv[i] = ItemStack.EMPTY; } } isRedstonePowered = compound.getBoolean("rs"); if (isClient) { modifier = compound.getFloat("md"); speedIn = compound.getFloat("sp"); torqueIn = compound.getFloat("to"); consumerCount = compound.getByte("cc"); markBlockForRenderUpdate(); } } @Override public NBTTagCompound writeNBTData(NBTTagCompound compound, boolean isClient) { compound = super.writeNBTData(compound, isClient); for (int i = 0; i < inv.length; i++) { if (!inv[i].isEmpty()) { ItemUtils.writeToNBT(inv[i], compound, "inv" + i); } } compound.setBoolean("rs", isRedstonePowered); if (isClient) { compound.setFloat("md", (float) modifier); compound.setFloat("sp", (float) speedIn); compound.setFloat("to", (float) torqueIn); compound.setByte("cc", (byte) consumerCount); } return compound; } // TODO merge with TileEntityDayBarrel private boolean changeOrientation(Orientation newOrientation, boolean simulate) { Orientation orientation = getOrientation(); if (orientation != newOrientation && BlockGearbox.ORIENTATION.getAllowedValues().contains(newOrientation)) { if (!simulate) { getWorld().setBlockState(pos, world.getBlockState(pos).withProperty(BlockGearbox.ORIENTATION, newOrientation)); } return true; } else { return false; } } @Override public void mirror(Mirror mirror) { changeOrientation(getOrientation().mirror(mirror), false); } @Override public boolean rotateAround(EnumFacing axis, boolean simulate) { return changeOrientation(getOrientation().rotateAround(axis), simulate); } @Override public boolean rotateWrench(EnumFacing axis) { Orientation newOrientation; if (axis == getOrientation().facing) { newOrientation = getOrientation().getNextRotationOnFace(); } else { newOrientation = Orientation.fromDirection(axis.getOpposite()); } changeOrientation(newOrientation, false); return true; } @Override public boolean shouldRefresh(World world, BlockPos pos, IBlockState oldState, IBlockState newState) { return oldState.getBlock() != newState.getBlock(); } }
411
0.910861
1
0.910861
game-dev
MEDIA
0.979563
game-dev
0.936345
1
0.936345
DavidCRicardo/InventorySystemCPP
6,883
Source/TestProject/Private/UI/W_SlotDropDownMenu.cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "UI/W_SlotDropDownMenu.h" #include "Components/Button.h" #include "MyPlayerController.h" #include "UI/SlotLayout.h" #include "UI/HUDLayout.h" #include "UI/MainLayout.h" #include "UI/InventoryLayout.h" #include "UI/ProfileLayout.h" #include "UI/ContainerLayout.h" void UW_SlotDropDownMenu::NativeConstruct() { Super::NativeConstruct(); OnVisibilityChanged.AddUniqueDynamic(this, &UW_SlotDropDownMenu::RunThis2); Btn_UseMultiple->SetIsEnabled(false); Btn_Move->SetIsEnabled(false); Btn_Use->OnClicked.AddUniqueDynamic(this, &UW_SlotDropDownMenu::BtnUseClicked); Btn_Move->OnClicked.AddUniqueDynamic(this, &UW_SlotDropDownMenu::BtnMoveClicked); Btn_Pick->OnClicked.AddUniqueDynamic(this, &UW_SlotDropDownMenu::BtnPickClicked); SetVisibility(ESlateVisibility::Visible); PlayerController = Cast<AMyPlayerController>(GetOwningPlayer()); } void UW_SlotDropDownMenu::RunThis2(ESlateVisibility InVisibility) { if (ESlateVisibility::Visible == InVisibility) { RunThis(); } } void UW_SlotDropDownMenu::RunThis() { if (!PlayerController) { PlayerController = Cast<AMyPlayerController>(GetOwningPlayer()); if (!PlayerController) { return; } } if (!PlayerController->HUDLayoutReference) { return; } USlotLayout* LocalSlot{}; uint8 Index = PlayerController->MenuAnchorIndex; if (PlayerController->MenuAnchorIndex < (uint8)EEquipmentSlot::Count) { LocalSlot = PlayerController->HUDLayoutReference->MainLayout->Profile->EquipmentSlotsArray[Index]; } else { Index = PlayerController->MenuAnchorIndex - (uint8)EEquipmentSlot::Count; LocalSlot = PlayerController->HUDLayoutReference->MainLayout->Inventory->InventorySlotsArray[Index]; } if (LocalSlot->IsHovered()) { Btn_Use->SetVisibility(ESlateVisibility::Visible); Btn_Pick->SetVisibility(ESlateVisibility::Collapsed); Btn_Move->SetVisibility(ESlateVisibility::Visible); Btn_UseMultiple->SetVisibility(ESlateVisibility::Visible); } else { Btn_Use->SetVisibility(ESlateVisibility::Collapsed); Btn_Pick->SetVisibility(ESlateVisibility::Visible); Btn_Move->SetVisibility(ESlateVisibility::Visible); Btn_UseMultiple->SetVisibility(ESlateVisibility::Collapsed); } return; /* if (LocalSlot->NativeFromInventory) { Btn_Use->SetVisibility(ESlateVisibility::Visible); Btn_Pick->SetVisibility(ESlateVisibility::Collapsed); Btn_Move->SetVisibility(ESlateVisibility::Visible); Btn_UseMultiple->SetVisibility(ESlateVisibility::Visible); } else if (LocalSlot->NativeFromContainer) { Btn_Use->SetVisibility(ESlateVisibility::Collapsed); Btn_Pick->SetVisibility(ESlateVisibility::Visible); Btn_Move->SetVisibility(ESlateVisibility::Visible); Btn_UseMultiple->SetVisibility(ESlateVisibility::Collapsed); } //// slot id 0 but it can be native from container //if (LocalSlot->IsHovered()) //{ // Btn_Use->SetVisibility(ESlateVisibility::Visible); // Btn_Pick->SetVisibility(ESlateVisibility::Collapsed); // Btn_Move->SetVisibility(ESlateVisibility::Visible); // Btn_UseMultiple->SetVisibility(ESlateVisibility::Visible); //} //else { // Btn_Use->SetVisibility(ESlateVisibility::Collapsed); // Btn_Pick->SetVisibility(ESlateVisibility::Visible); // Btn_Move->SetVisibility(ESlateVisibility::Visible); // Btn_UseMultiple->SetVisibility(ESlateVisibility::Collapsed); //} return; */ } void UW_SlotDropDownMenu::SetMenuOptions(uint8 LocalNumber) { if (NativeFromInventory || LocalNumber == 1) { Btn_Use->SetVisibility(ESlateVisibility::Visible); Btn_Pick->SetVisibility(ESlateVisibility::Collapsed); Btn_Move->SetVisibility(ESlateVisibility::Visible); Btn_UseMultiple->SetVisibility(ESlateVisibility::Visible); } else if (NativeFromContainer || LocalNumber == 2) { Btn_Use->SetVisibility(ESlateVisibility::Collapsed); Btn_Pick->SetVisibility(ESlateVisibility::Visible); Btn_Move->SetVisibility(ESlateVisibility::Visible); Btn_UseMultiple->SetVisibility(ESlateVisibility::Collapsed); } else { Btn_Use->SetVisibility(ESlateVisibility::Visible); Btn_Pick->SetVisibility(ESlateVisibility::Visible); Btn_Move->SetVisibility(ESlateVisibility::Visible); Btn_UseMultiple->SetVisibility(ESlateVisibility::Visible); } } FReply UW_SlotDropDownMenu::NativeOnMouseButtonDown(const FGeometry& InGeometry, const FPointerEvent& InMouseEvent) { GEngine->AddOnScreenDebugMessage(9, 1.f, FColor::Turquoise, TEXT("OnMouseButtonDown")); return FReply::Handled(); } void UW_SlotDropDownMenu::BtnUseClicked() { CloseDropDownMenu(); USlotLayout* LocalSlot{}; uint8 Index = PlayerController->MenuAnchorIndex; if (PlayerController->MenuAnchorIndex < (uint8)EEquipmentSlot::Count) { LocalSlot = PlayerController->HUDLayoutReference->MainLayout->Profile->EquipmentSlotsArray[Index]; } else { Index = PlayerController->MenuAnchorIndex - (uint8)EEquipmentSlot::Count; LocalSlot = PlayerController->HUDLayoutReference->MainLayout->Inventory->InventorySlotsArray[Index]; } if (LocalSlot) { LocalSlot->UseItem(); } } void UW_SlotDropDownMenu::BtnPickClicked() { USlotLayout* LocalSlot{}; uint8 Index = PlayerController->MenuAnchorIndex; LocalSlot = PlayerController->HUDLayoutReference->MainLayout->Container->ContainerSlotsArray[Index]; if (LocalSlot) { LocalSlot->UseItem(); } CloseDropDownMenu(); } void UW_SlotDropDownMenu::BtnMoveClicked() { USlotLayout* LocalSlot{}; uint8 Index = PlayerController->MenuAnchorIndex; if (PlayerController->MenuAnchorIndex < (uint8)EEquipmentSlot::Count) { LocalSlot = PlayerController->HUDLayoutReference->MainLayout->Profile->EquipmentSlotsArray[Index]; } else { Index = PlayerController->MenuAnchorIndex - (uint8)EEquipmentSlot::Count; LocalSlot = PlayerController->HUDLayoutReference->MainLayout->Inventory->InventorySlotsArray[Index]; } const FGeometry InGeometry = FGeometry(); const FPointerEvent InMouseEvent = FPointerEvent(); UDragDropOperation* OutOperation = nullptr; //LocalSlot->DragSlot(InGeometry,InMouseEvent, OutOperation); CloseDropDownMenu(); } void UW_SlotDropDownMenu::CloseDropDownMenu() { USlotLayout* LocalSlot{}; uint8 Index = PlayerController->MenuAnchorIndex; if (PlayerController->MenuAnchorIndex < (uint8)EEquipmentSlot::Count) { LocalSlot = PlayerController->HUDLayoutReference->MainLayout->Profile->EquipmentSlotsArray[Index]; } else { Index = PlayerController->MenuAnchorIndex - (uint8)EEquipmentSlot::Count; LocalSlot = PlayerController->HUDLayoutReference->MainLayout->Inventory->InventorySlotsArray[Index]; } // slot id 0 but it can be native from container if (!LocalSlot->IsHovered()) { LocalSlot = PlayerController->HUDLayoutReference->MainLayout->Container->ContainerSlotsArray[Index]; } return; /* LocalSlot->CloseSlotMenu(); if (SlotReference) { SlotReference->CloseSlotMenu(); } */ }
411
0.95289
1
0.95289
game-dev
MEDIA
0.57015
game-dev
0.983973
1
0.983973
DragonFlyBSD/DragonFlyBSD
7,027
sbin/hammer/cmd_stats.c
/* * Copyright (c) 2008 The DragonFly Project. All rights reserved. * * This code is derived from software contributed to The DragonFly Project * by Matthew Dillon <dillon@backplane.com> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name of The DragonFly Project nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific, prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $DragonFly: src/sbin/hammer/cmd_stats.c,v 1.3 2008/07/14 20:28:07 dillon Exp $ */ #include "hammer.h" #include <sys/sysctl.h> #include <math.h> static void loaddelay(struct timespec *ts, const char *arg); #define _HAMMER "vfs.hammer.stats_" #define bstats_title \ " lookups searches inserts deletes elements splits iterations rootiters reciters" #define iostats_title \ " f_read f_write d_read d_write i_flushes commits undo redo" /* * Taken from sys/vfs/hammer/hammer_vfsops.c */ struct btree_stats { int64_t btree_lookups; int64_t btree_searches; int64_t btree_inserts; int64_t btree_deletes; int64_t btree_elements; int64_t btree_splits; int64_t btree_iterations; int64_t btree_root_iterations; int64_t record_iterations; }; struct io_stats { int64_t file_read; int64_t file_write; int64_t disk_read; int64_t disk_write; int64_t inode_flushes; int64_t commits; int64_t undo; int64_t redo; }; static __always_inline int _sysctl(const char *name, int64_t *p) { size_t len = sizeof(*p); return(sysctlbyname(name, p, &len, NULL, 0)); } static __always_inline void collect_bstats(struct btree_stats *p) { /* sysctls must exist, so ignore return values */ _sysctl(_HAMMER"btree_lookups", &p->btree_lookups); _sysctl(_HAMMER"btree_searches", &p->btree_searches); _sysctl(_HAMMER"btree_inserts", &p->btree_inserts); _sysctl(_HAMMER"btree_deletes", &p->btree_deletes); _sysctl(_HAMMER"btree_elements", &p->btree_elements); _sysctl(_HAMMER"btree_splits", &p->btree_splits); _sysctl(_HAMMER"btree_iterations", &p->btree_iterations); _sysctl(_HAMMER"btree_root_iterations", &p->btree_root_iterations); _sysctl(_HAMMER"record_iterations", &p->record_iterations); } static __always_inline void collect_iostats(struct io_stats *p) { /* sysctls must exist, so ignore return values */ _sysctl(_HAMMER"file_read", &p->file_read); _sysctl(_HAMMER"file_write", &p->file_write); _sysctl(_HAMMER"disk_read", &p->disk_read); _sysctl(_HAMMER"disk_write", &p->disk_write); _sysctl(_HAMMER"inode_flushes", &p->inode_flushes); _sysctl(_HAMMER"commits", &p->commits); _sysctl(_HAMMER"undo", &p->undo); _sysctl(_HAMMER"redo", &p->redo); } static __always_inline void print_bstats(const struct btree_stats *p1, const struct btree_stats *p2) { printf("%10jd %10jd %10jd %10jd %10jd %10jd %10jd %10jd %10jd", (intmax_t)(p1->btree_lookups - p2->btree_lookups), (intmax_t)(p1->btree_searches - p2->btree_searches), (intmax_t)(p1->btree_inserts - p2->btree_inserts), (intmax_t)(p1->btree_deletes - p2->btree_deletes), (intmax_t)(p1->btree_elements - p2->btree_elements), (intmax_t)(p1->btree_splits - p2->btree_splits), (intmax_t)(p1->btree_iterations - p2->btree_iterations), (intmax_t)(p1->btree_root_iterations - p2->btree_root_iterations), (intmax_t)(p1->record_iterations - p2->record_iterations)); /* no trailing \n */ } static __always_inline void print_iostats(const struct io_stats *p1, const struct io_stats *p2) { printf("%9jd %9jd %9jd %9jd %9jd %9jd %9jd %9jd", (intmax_t)(p1->file_read - p2->file_read), (intmax_t)(p1->file_write - p2->file_write), (intmax_t)(p1->disk_read - p2->disk_read), (intmax_t)(p1->disk_write - p2->disk_write), (intmax_t)(p1->inode_flushes - p2->inode_flushes), (intmax_t)(p1->commits - p2->commits), (intmax_t)(p1->undo - p2->undo), (intmax_t)(p1->redo - p2->redo)); /* no trailing \n */ } void hammer_cmd_bstats(char **av, int ac) { struct btree_stats st1, st2; struct timespec delay = {1, 0}; int count; bzero(&st1, sizeof(st1)); bzero(&st2, sizeof(st2)); if (ac > 0) loaddelay(&delay, av[0]); for (count = 0; ; ++count) { collect_bstats(&st1); if (count) { if ((count & 15) == 1) printf(bstats_title"\n"); print_bstats(&st1, &st2); printf("\n"); } bcopy(&st1, &st2, sizeof(st2)); nanosleep(&delay, NULL); } } void hammer_cmd_iostats(char **av, int ac) { struct io_stats st1, st2; struct timespec delay = {1, 0}; int count; bzero(&st1, sizeof(st1)); bzero(&st2, sizeof(st2)); if (ac > 0) loaddelay(&delay, av[0]); for (count = 0; ; ++count) { collect_iostats(&st1); if (count) { if ((count & 15) == 1) printf(iostats_title"\n"); print_iostats(&st1, &st2); printf("\n"); } bcopy(&st1, &st2, sizeof(st2)); nanosleep(&delay, NULL); } } void hammer_cmd_stats(char **av, int ac) { struct btree_stats bst1, bst2; struct io_stats ist1, ist2; struct timespec delay = {1, 0}; int count; bzero(&bst1, sizeof(bst1)); bzero(&bst2, sizeof(bst2)); bzero(&ist1, sizeof(ist1)); bzero(&ist2, sizeof(ist2)); if (ac > 0) loaddelay(&delay, av[0]); for (count = 0; ; ++count) { collect_bstats(&bst1); collect_iostats(&ist1); if (count) { if ((count & 15) == 1) printf(bstats_title"\t"iostats_title"\n"); print_bstats(&bst1, &bst2); printf("\t"); print_iostats(&ist1, &ist2); printf("\n"); } bcopy(&bst1, &bst2, sizeof(bst2)); bcopy(&ist1, &ist2, sizeof(ist2)); nanosleep(&delay, NULL); } } /* * Convert a delay string (e.g. "0.1") into a timespec. */ static void loaddelay(struct timespec *ts, const char *arg) { double d; d = strtod(arg, NULL); if (d < 0.001) d = 0.001; ts->tv_sec = (int)d; ts->tv_nsec = (int)(modf(d, &d) * 1000000000.0); }
411
0.987235
1
0.987235
game-dev
MEDIA
0.35075
game-dev
0.992439
1
0.992439
Xenoveritas/abuse
4,119
src/devsel.cpp
/* * Abuse - dark 2D side-scrolling platform game * Copyright (c) 1995 Crack dot Com * Copyright (c) 2005-2011 Sam Hocevar <sam@hocevar.net> * * This software was released into the Public Domain. As with most public * domain software, no warranty is made or implied by Crack dot Com, by * Jonathan Clark, or by Sam Hocevar. */ #if defined HAVE_CONFIG_H # include "config.h" #endif #include "common.h" #include "devsel.h" #include "scroller.h" #include "cache.h" #include "game.h" void scale_put(image *im, image *screen, int x, int y, short new_width, short new_height); void scale_put_trans(image *im, image *screen, int x, int y, short new_width, short new_height); int cur_bg=0,cur_fg=0,cur_char=0; void tile_picker::recenter(image *screen) { set_x(get_current(), screen); } int tile_picker::picw() { switch (type) { case SPEC_FORETILE : { return cache.foret(foretiles[0])->im->Size().x/scale; } break; case SPEC_BACKTILE : { return cache.backt(backtiles[0])->im->Size().x/scale; } break; default : return 30/scale; } } int tile_picker::pich() { switch (type) { case SPEC_FORETILE : { return cache.foret(foretiles[0])->im->Size().y/scale; } break; case SPEC_BACKTILE : { return cache.backt(backtiles[0])->im->Size().y/scale; } break; default : return 40/scale; } } int tile_picker::total() { switch (type) { case SPEC_FORETILE : { return nforetiles; } break; case SPEC_BACKTILE : { return nbacktiles; } break; case SPEC_CHARACTER : { return total_objects; } break; } return 1; } tile_picker::tile_picker(int X, int Y, int ID, int spec_type, int Scale, int scroll_h, int Wid, ifield *Next) : scroller(X,Y,ID,2,2,1,0,Next) { wid=Wid; type=spec_type; th=scroll_h; scale=Scale; set_size(picw()*wid,pich()*th); sx=get_current(); t=total(); } void tile_picker::scroll_event(int newx, image *screen) { int ya = pich(), xw = picw(), c = get_current(); image im(ivec2(xw, ya)); last_sel=newx; screen->Bar(m_pos, m_pos + ivec2(l - 1, h - 1), wm->black()); for (int i=newx; i<newx+th*wid; i++) { ivec2 xyo = m_pos + ivec2(((i - newx) % wid) * xw, ((i - newx) / wid) * ya); int blank=0; if (i<t) { switch (type) { case SPEC_FORETILE : { if (foretiles[i]<0) blank=1; else { im.clear(); the_game->get_fg(i)->im->PutImage(&im,ivec2(0,0)); if (rev) { screen->Bar(xyo, xyo + ivec2(xw - 1, ya - 1), wm->bright_color()); scale_put_trans(&im,screen,xyo.x,xyo.y,xw,ya); } else scale_put(&im,screen,xyo.x,xyo.y,xw,ya); } } break; case SPEC_BACKTILE : { if (backtiles[i]<0) blank=1; else scale_put(the_game->get_bg(i)->im,screen,xyo.x,xyo.y,xw,ya); } break; case SPEC_CHARACTER : { figures[i]->get_sequence(stopped)->get_figure(0)->forward->PutImage(&im,ivec2(0,0)); scale_put(&im,screen,m_pos.x,m_pos.y,xw,ya); } break; } } else blank=1; if (i==c) screen->Rectangle(xyo, xyo + ivec2(xw - 1, ya - 1), wm->bright_color()); } } void tile_picker::handle_inside_event(Event &ev, image *screen, InputManager *inm) { if (ev.type==EV_MOUSE_BUTTON) { int sel=((ev.mouse_move.y-m_pos.y)/pich()*wid)+(ev.mouse_move.x-m_pos.x)/picw()+last_sel; if (sel<t && sel>=0 && sel!=get_current()) { set_current(sel); scroll_event(last_sel, screen); } } } int tile_picker::get_current() { switch (type) { case SPEC_FORETILE : { return cur_fg; } break; case SPEC_BACKTILE : { return cur_bg; } break; case SPEC_CHARACTER : { return cur_char; } break; } return 0; } void tile_picker::set_current(int x) { switch (type) { case SPEC_FORETILE : { cur_fg=x; } break; case SPEC_BACKTILE : { cur_bg=x; } break; case SPEC_CHARACTER : { cur_char=x; } break; } }
411
0.961133
1
0.961133
game-dev
MEDIA
0.817406
game-dev
0.992108
1
0.992108
convoyinc/apollo-cache-hermes
1,471
src/environment.ts
import { InvalidEnvironmentError } from './errors'; /** * Hermes relies on some ES6 functionality: iterators (via Symbol.iterator), * Sets, and Maps. * * Unfortunately, it can be tricky to polyfill correctly (and some environments * don't do it properly. Looking at you react-native on android). So, let's make * sure that everything is in a happy state, and complain otherwise. */ export function assertValidEnvironment() { const missingBehavior = []; if (!_isSymbolPolyfilled()) missingBehavior.push('Symbol'); if (!_isSetPolyfilled()) missingBehavior.push('Set'); if (!_isMapPolyfilled()) missingBehavior.push('Map'); if (!missingBehavior.length) return; throw new InvalidEnvironmentError({ message: `Hermes requires some ES2015 features that your current environment lacks: ` + `${missingBehavior.join(', ')}. Please polyfill!`, infoUrl: `https://bit.ly/2SGa7uz`, }); } function _isSymbolPolyfilled() { if (typeof Symbol !== 'function') return false; if (!Symbol.iterator) return false; return true; } function _isSetPolyfilled() { if (typeof Set !== 'function') return false; if (!_isSymbolPolyfilled()) return false; if (typeof (new Set)[Symbol.iterator] !== 'function') return false; return true; } function _isMapPolyfilled() { if (typeof Set !== 'function') return false; if (!_isSymbolPolyfilled()) return false; if (typeof (new Set)[Symbol.iterator] !== 'function') return false; return true; }
411
0.67913
1
0.67913
game-dev
MEDIA
0.425524
game-dev
0.846172
1
0.846172
LostArtefacts/TR-Rando
11,371
TRLevelControl/Control/TR3/TR3LevelControl.cs
using System.Diagnostics; using TRLevelControl.Build; using TRLevelControl.Model; namespace TRLevelControl; public class TR3LevelControl : TRLevelControlBase<TR3Level> { private TRObjectMeshBuilder<TR3Type> _meshBuilder; private TRTextureBuilder _textureBuilder; private TRSpriteBuilder<TR3Type> _spriteBuilder; private TR3RoomBuilder _roomBuilder; public TR3LevelControl(ITRLevelObserver observer = null) : base(observer) { } protected override TR3Level CreateLevel(TRFileVersion version) { TR3Level level = new() { Version = new() { Game = TRGameVersion.TR3, File = version } }; TestVersion(level, TRFileVersion.TR3a, TRFileVersion.TR3b); return level; } protected override void Initialise() { _meshBuilder = new(TRGameVersion.TR3, _observer); _textureBuilder = new(TRGameVersion.TR3, _observer); _spriteBuilder = new(TRGameVersion.TR3); _roomBuilder = new(); } protected override void Read(TRLevelReader reader) { ReadPalette(reader); ReadImages(reader); _level.Version.LevelNumber = reader.ReadUInt32(); ReadRooms(reader); ReadMeshData(reader); ReadModelData(reader); ReadStaticMeshes(reader); ReadSprites(reader); ReadCameras(reader); ReadSoundSources(reader); ReadBoxes(reader); ReadAnimatedTextures(reader); ReadObjectTextures(reader); ReadEntities(reader); ReadLightMap(reader); ReadCinematicFrames(reader); ReadDemoData(reader); ReadSoundEffects(reader); } protected override void Write(TRLevelWriter writer) { WritePalette(writer); WriteImages(writer); writer.Write(_level.Version.LevelNumber); WriteRooms(writer); WriteMeshData(writer); WriteModelData(writer); WriteStaticMeshes(writer); WriteSprites(writer); WriteCameras(writer); WriteSoundSources(writer); WriteBoxes(writer); WriteAnimatedTextures(writer); WriteObjectTextures(writer); WriteEntities(writer); WriteLightMap(writer); WriteCinematicFrames(writer); WriteDemoData(writer); WriteSoundEffects(writer); } private void ReadPalette(TRLevelReader reader) { _level.Palette = reader.ReadColours(TRConsts.PaletteSize, TRConsts.Palette8Multiplier); _level.Palette16 = reader.ReadColour4s(TRConsts.PaletteSize); } private void WritePalette(TRLevelWriter writer) { Debug.Assert(_level.Palette.Count == TRConsts.PaletteSize); Debug.Assert(_level.Palette16.Count == TRConsts.PaletteSize); writer.Write(_level.Palette, TRConsts.Palette8Multiplier); writer.Write(_level.Palette16); } private void ReadImages(TRLevelReader reader) { uint numImages = reader.ReadUInt32(); _level.Images8 = reader.ReadImage8s(numImages); _level.Images16 = reader.ReadImage16s(numImages); } private void WriteImages(TRLevelWriter writer) { Debug.Assert(_level.Images8.Count == _level.Images16.Count); writer.Write((uint)_level.Images8.Count); writer.Write(_level.Images8); writer.Write(_level.Images16); } private void ReadRooms(TRLevelReader reader) { _level.Rooms = _roomBuilder.ReadRooms(reader); TRFDBuilder builder = new(_level.Version.Game, _observer); _level.FloorData = builder.ReadFloorData(reader, _level.Rooms.SelectMany(r => r.Sectors)); } private void WriteRooms(TRLevelWriter writer) { _spriteBuilder.CacheSpriteOffsets(_level.Sprites); List<ushort> floorData = _level.FloorData .Flatten(_level.Rooms.SelectMany(r => r.Sectors)); _roomBuilder.WriteRooms(writer, _level.Rooms, _spriteBuilder); writer.Write((uint)floorData.Count); writer.Write(floorData); } private void ReadMeshData(TRLevelReader reader) { _meshBuilder.BuildObjectMeshes(reader); } private void WriteMeshData(TRLevelWriter writer) { _meshBuilder.WriteObjectMeshes(writer, _level.Models.Values.SelectMany(m => m.Meshes), _level.StaticMeshes); } private void ReadModelData(TRLevelReader reader) { TRModelBuilder<TR3Type> builder = new(TRGameVersion.TR3, TRModelDataType.Level, _observer); _level.Models = builder.ReadModelData(reader, _meshBuilder); } private void WriteModelData(TRLevelWriter writer) { TRModelBuilder<TR3Type> builder = new(TRGameVersion.TR3, TRModelDataType.Level, _observer); builder.WriteModelData(writer, _level.Models); } private void ReadStaticMeshes(TRLevelReader reader) { _level.StaticMeshes = _meshBuilder.ReadStaticMeshes(reader, TR3Type.SceneryBase); } private void WriteStaticMeshes(TRLevelWriter writer) { _meshBuilder.WriteStaticMeshes(writer, _level.StaticMeshes, TR3Type.SceneryBase); } private void ReadSprites(TRLevelReader reader) { _level.Sprites = _spriteBuilder.ReadSprites(reader); for (int i = 0; i < _level.Rooms.Count; i++) { _roomBuilder.BuildMesh(_level.Rooms[i], i, _spriteBuilder); } } private void WriteSprites(TRLevelWriter writer) { _spriteBuilder.WriteSprites(writer, _level.Sprites); } private void ReadCameras(TRLevelReader reader) { uint numCameras = reader.ReadUInt32(); _level.Cameras = reader.ReadCameras(numCameras); } private void WriteCameras(TRLevelWriter writer) { writer.Write((uint)_level.Cameras.Count); writer.Write(_level.Cameras); } private void ReadSoundSources(TRLevelReader reader) { uint numSources = reader.ReadUInt32(); _level.SoundSources = reader.ReadSoundSources<TR3SFX>(numSources); } private void WriteSoundSources(TRLevelWriter writer) { writer.Write((uint)_level.SoundSources.Count); writer.Write(_level.SoundSources); } private void ReadBoxes(TRLevelReader reader) { TRBoxBuilder boxBuilder = new(_level.Version.Game, _observer); _level.Boxes = boxBuilder.ReadBoxes(reader); } private void WriteBoxes(TRLevelWriter writer) { TRBoxBuilder boxBuilder = new(_level.Version.Game, _observer); boxBuilder.WriteBoxes(writer, _level.Boxes); } private void ReadAnimatedTextures(TRLevelReader reader) { _level.AnimatedTextures = _textureBuilder.ReadAnimatedTextures(reader); } private void WriteAnimatedTextures(TRLevelWriter writer) { _textureBuilder.Write(writer, _level.AnimatedTextures); } private void ReadObjectTextures(TRLevelReader reader) { _level.ObjectTextures = _textureBuilder.ReadObjectTextures(reader); } private void WriteObjectTextures(TRLevelWriter writer) { _textureBuilder.Write(writer, _level.ObjectTextures); } private void ReadEntities(TRLevelReader reader) { uint numEntities = reader.ReadUInt32(); _level.Entities = reader.ReadTR3Entities(numEntities); } private void WriteEntities(TRLevelWriter writer) { writer.Write((uint)_level.Entities.Count); writer.Write(_level.Entities); } private void ReadLightMap(TRLevelReader reader) { _level.LightMap = new(reader.ReadBytes(TRConsts.LightMapSize)); } private void WriteLightMap(TRLevelWriter writer) { Debug.Assert(_level.LightMap.Count == TRConsts.LightMapSize); writer.Write(_level.LightMap); } private void ReadCinematicFrames(TRLevelReader reader) { ushort numFrames = reader.ReadUInt16(); _level.CinematicFrames = reader.ReadCinematicFrames(numFrames); } private void WriteCinematicFrames(TRLevelWriter writer) { writer.Write((ushort)_level.CinematicFrames.Count); writer.Write(_level.CinematicFrames); } private void ReadDemoData(TRLevelReader reader) { TRDemoBuilder<TR3DemoGun, TR3InputState> builder = new(TRGameVersion.TR3); _level.DemoData = builder.Read(reader); } private void WriteDemoData(TRLevelWriter writer) { TRDemoBuilder<TR3DemoGun, TR3InputState> builder = new(TRGameVersion.TR3); builder.Write(_level.DemoData, writer); } private void ReadSoundEffects(TRLevelReader reader) { long startPos = reader.BaseStream.Position; try { ReadSoundEffects(reader, -1); } catch { reader.BaseStream.Position = startPos; ReadSoundEffects(reader, Enum.GetValues<TR3SFX>().Length); } } private void ReadSoundEffects(TRLevelReader reader, int mapLength) { List<short> soundMap = TRSFXBuilder.ReadSoundMap(reader, mapLength); uint numSoundDetails = reader.ReadUInt32(); List<TR3SoundEffect> sfx = new(); Dictionary<int, ushort> sampleMap = new(); for (int i = 0; i < numSoundDetails; i++) { sampleMap[i] = reader.ReadUInt16(); sfx.Add(new() { Volume = reader.ReadByte(), Range = reader.ReadByte(), Chance = reader.ReadByte(), Pitch = reader.ReadByte(), }); sfx[i].SetFlags(reader.ReadUInt16()); } uint numSampleIndices = reader.ReadUInt32(); uint[] sampleIndices = reader.ReadUInt32s(numSampleIndices); foreach (var (soundID, samplePointer) in sampleMap) { sfx[soundID].SampleID = sampleIndices[samplePointer]; } _level.SoundEffects = TRSFXBuilder.Build<TR3SFX, TR3SoundEffect>(soundMap, sfx); } private void WriteSoundEffects(TRLevelWriter writer) { List<TR3SoundEffect> effects = new(_level.SoundEffects.Values); List<uint> sampleIndices = effects.SelectMany(s => Enumerable.Range((int)s.SampleID, s.SampleCount)) .Select(s => (uint)s) .Distinct().ToList(); sampleIndices.Sort(); Dictionary<TR3SoundEffect, ushort> sampleMap = new(); foreach (TR3SoundEffect effect in effects) { sampleMap[effect] = (ushort)sampleIndices.IndexOf(effect.SampleID); } effects.Sort((e1, e2) => sampleMap[e1].CompareTo(sampleMap[e2])); foreach (TR3SFX id in Enum.GetValues<TR3SFX>()) { writer.Write(_level.SoundEffects.ContainsKey(id) ? (short)effects.IndexOf(_level.SoundEffects[id]) : (short)-1); } writer.Write((uint)_level.SoundEffects.Count); foreach (TR3SoundEffect effect in effects) { writer.Write(sampleMap[effect]); writer.Write(effect.Volume); writer.Write(effect.Range); writer.Write(effect.Chance); writer.Write(effect.Pitch); writer.Write(effect.GetFlags()); } writer.Write((uint)sampleIndices.Count); writer.Write(sampleIndices); } }
411
0.8318
1
0.8318
game-dev
MEDIA
0.464413
game-dev,networking
0.913887
1
0.913887
snesrev/sm
99,706
src/sm_a3.c
// Enemy AI - inc. elevator & metroid #include "ida_types.h" #include "variables.h" #include "sm_rtl.h" #include "funcs.h" #include "enemy_types.h" #define g_off_A386DB ((uint16*)RomFixedPtr(0xa386db)) #define g_off_A3894E ((uint16*)RomFixedPtr(0xa3894e)) #define g_word_A38D1D ((uint16*)RomFixedPtr(0xa38d1d)) #define g_word_A394E2 ((uint16*)RomFixedPtr(0xa394e2)) #define g_off_A396DB ((uint16*)RomFixedPtr(0xa396db)) #define g_off_A3992B ((uint16*)RomFixedPtr(0xa3992b)) #define g_off_A3A111 ((uint16*)RomFixedPtr(0xa3a111)) #define g_off_A3A121 ((uint16*)RomFixedPtr(0xa3a121)) #define g_off_A3AAC2 ((uint16*)RomFixedPtr(0xa3aac2)) #define g_off_A3AACA ((uint16*)RomFixedPtr(0xa3aaca)) #define g_off_A3AAD2 ((uint16*)RomFixedPtr(0xa3aad2)) #define g_off_A3AADA ((uint16*)RomFixedPtr(0xa3aada)) #define g_off_A3AAE2 ((uint16*)RomFixedPtr(0xa3aae2)) #define g_word_A3AAE6 ((uint16*)RomFixedPtr(0xa3aae6)) #define g_word_A3AAEA ((uint16*)RomFixedPtr(0xa3aaea)) #define g_word_A3AAEE ((uint16*)RomFixedPtr(0xa3aaee)) #define g_word_A3AAF2 ((uint16*)RomFixedPtr(0xa3aaf2)) #define g_word_A3AAF6 ((uint16*)RomFixedPtr(0xa3aaf6)) #define g_word_A3AAFA ((uint16*)RomFixedPtr(0xa3aafa)) #define g_word_A3B415 ((uint16*)RomFixedPtr(0xa3b415)) #define g_off_A3B40D ((uint16*)RomFixedPtr(0xa3b40d)) #define g_off_A3B667 ((uint16*)RomFixedPtr(0xa3b667)) #define g_word_A3BA84 ((uint16*)RomFixedPtr(0xa3ba84)) #define g_word_A3BA94 ((uint16*)RomFixedPtr(0xa3ba94)) #define g_word_A3BC4A ((uint16*)RomFixedPtr(0xa3bc4a)) #define g_word_A3BC6A ((uint16*)RomFixedPtr(0xa3bc6a)) #define g_off_A3B722 ((uint16*)RomFixedPtr(0xa3b722)) #define g_off_A3C69C ((uint16*)RomFixedPtr(0xa3c69c)) #define g_stru_A3CD42 ((MaridiaSnailData2*)RomFixedPtr(0xa3cd42)) #define g_word_A3CD82 ((uint16*)RomFixedPtr(0xa3cd82)) #define g_word_A3CDC2 ((uint16*)RomFixedPtr(0xa3cdc2)) #define g_word_A3CCA2 ((uint16*)RomFixedPtr(0xa3cca2)) #define g_off_A3CDD2 ((uint16*)RomFixedPtr(0xa3cdd2)) #define g_off_A3D1AB ((uint16*)RomFixedPtr(0xa3d1ab)) #define g_off_A3D30D ((uint16*)RomFixedPtr(0xa3d30d)) #define g_off_A3D50F ((uint16*)RomFixedPtr(0xa3d50f)) #define g_word_A3D517 ((uint16*)RomFixedPtr(0xa3d517)) #define g_off_A3D5A4 ((uint16*)RomFixedPtr(0xa3d5a4)) #define g_word_A3DABC ((uint16*)RomFixedPtr(0xa3dabc)) #define g_off_A3DC0B ((uint16*)RomFixedPtr(0xa3dc0b)) #define g_word_A3DCAE ((uint16*)RomFixedPtr(0xa3dcae)) #define g_off_A3DCA6 ((uint16*)RomFixedPtr(0xa3dca6)) #define g_off_A3E03B ((uint16*)RomFixedPtr(0xa3e03b)) #define g_word_A3E5F0 ((uint16*)RomFixedPtr(0xa3e5f0)) #define g_off_A3E2CC ((uint16*)RomFixedPtr(0xa3e2cc)) #define g_off_A3E630 ((uint16*)RomFixedPtr(0xa3e630)) #define g_off_A3E63C ((uint16*)RomFixedPtr(0xa3e63c)) #define g_off_A3E648 ((uint16*)RomFixedPtr(0xa3e648)) #define g_off_A3E654 ((uint16*)RomFixedPtr(0xa3e654)) #define g_word_A3E931 ((uint16*)RomFixedPtr(0xa3e931)) #define g_word_A3EAD6 ((uint16*)RomFixedPtr(0xa3ead6)) #define g_word_A3EA3F ((uint16*)RomFixedPtr(0xa3ea3f)) static void CallSidehopperFunc(uint32 ea); static const int16 g_word_A3A76D[4] = { 2, 0, -2, 0 }; static const int16 g_word_A3A775[4] = { 0, -2, 0, 2 }; void Enemy_GrappleReact_NoInteract_A3(void) { // 0xA38000 SwitchEnemyAiToMainAi(); } void Enemy_GrappleReact_KillEnemy_A3(void) { // 0xA3800A EnemyGrappleDeath(); } void Enemy_GrappleReact_CancelBeam_A3(void) { // 0xA3800F Enemy_SwitchToFrozenAi(); } void Enemy_NormalTouchAI_A3(void) { // 0xA38023 NormalEnemyTouchAi(); } void Enemy_NormalShotAI_A3(void) { // 0xA3802D NormalEnemyShotAi(); } void Enemy_NormalShotAI_SkipSomeParts_A3(void) { // 0xA38032 NormalEnemyShotAiSkipDeathAnim_CurEnemy(); } void Enemy_NormalPowerBombAI_A3(void) { // 0xA38037 NormalEnemyPowerBombAi(); } void Enemy_NormalFrozenAI_A3(void) { // 0xA38041 NormalEnemyFrozenAI(); } const uint16 *Waver_Instr_1(uint16 k, const uint16 *jp) { // 0xA386E3 Get_Waver(cur_enemy_index)->waver_var_E = 1; return jp; } void Waver_Init(void) { // 0xA386ED Enemy_Waver *E = Get_Waver(cur_enemy_index); E->waver_var_B = 1; E->waver_var_A = 0x8000; if ((E->waver_parameter_1 & 1) == 0) { E->waver_var_B = SignExtend8(0xFE); E->waver_var_A = SignExtend8(0x8000); } E->waver_var_F = 0; E->waver_var_C = 0; E->waver_var_E = 0; E->base.current_instruction = addr_kWaver_Ilist_86A7; E->waver_var_F = E->waver_parameter_1 & 1; Waver_Func_1(); } void Waver_Main(void) { // 0xA3874C Enemy_Waver *E = Get_Waver(cur_enemy_index); if (Enemy_MoveRight_IgnoreSlopes(cur_enemy_index, __PAIR32__(E->waver_var_B, E->waver_var_A))) { uint16 r18 = *(uint16 *)((uint8 *)&E->waver_var_A + 1); E->waver_var_B = SignExtend8((-r18 & 0xFF00) >> 8); E->waver_var_A = -(int8)r18 << 8; E->waver_var_F = (E->waver_var_F ^ 1) & 1; Waver_Func_1(); } else { if (Enemy_MoveDown(cur_enemy_index, INT16_SHL16(SineMult8bit(LOBYTE(E->waver_var_D), 4)))) { E->waver_var_D = (uint8)(E->waver_var_D + 0x80); } else { E->waver_var_D += 2; } } if ((E->waver_var_D & 0x7F) == 56) { E->waver_var_F |= 2; Waver_Func_1(); } if (E->waver_var_E) { E->waver_var_E = 0; E->waver_var_F = E->waver_var_F & 1; Waver_Func_1(); } } void Waver_Func_1(void) { // 0xA387FE Enemy_Waver *E = Get_Waver(cur_enemy_index); uint16 waver_var_F = E->waver_var_F; if (waver_var_F != E->waver_var_C) { E->waver_var_C = waver_var_F; E->base.current_instruction = g_off_A386DB[waver_var_F]; E->base.instruction_timer = 1; E->base.timer = 0; } } const uint16 *Metalee_Instr_1(uint16 k, const uint16 *jp) { // 0xA38956 Get_Metalee(cur_enemy_index)->metalee_var_E = 1; return jp; } void Metalee_Init(void) { // 0xA38960 Enemy_Metalee *E = Get_Metalee(cur_enemy_index); E->metalee_var_C = 0; E->metalee_var_D = 0; E->metalee_var_E = 0; E->base.current_instruction = addr_kMetalee_Ilist_8910; E->metalee_var_B = FUNC16(Metalee_Func_1); } void CallMetaleeFunc(uint32 ea) { switch (ea) { case fnMetalee_Func_1: Metalee_Func_1(); return; case fnMetalee_Func_3: Metalee_Func_3(cur_enemy_index); return; case fnMetalee_Func_4: Metalee_Func_4(); return; case fnMetalee_Func_5: Metalee_Func_5(); return; default: Unreachable(); } } void Metalee_Main(void) { // 0xA38979 Enemy_Metalee *E = Get_Metalee(cur_enemy_index); CallMetaleeFunc(E->metalee_var_B | 0xA30000); } void Metalee_Func_1(void) { // 0xA38987 Enemy_Metalee *E = Get_Metalee(cur_enemy_index); if (abs16(E->base.x_pos - samus_x_pos) < 0x48) { Metalee_Func_2(cur_enemy_index); ++E->metalee_var_C; Metalee_Func_6(); E->metalee_var_B = FUNC16(Metalee_Func_3); } } void Metalee_Func_2(uint16 k) { // 0xA389AC Enemy_Metalee *E = Get_Metalee(k); uint16 div = (uint8)SnesDivide(samus_y_pos - E->base.y_pos, 24); E->metalee_var_F = div + 4; } void Metalee_Func_3(uint16 k) { // 0xA389D4 Enemy_Metalee *E = Get_Metalee(k); if (E->metalee_var_E) { E->metalee_var_E = 0; ++E->metalee_var_C; Metalee_Func_6(); E->metalee_var_B = FUNC16(Metalee_Func_4); QueueSfx2_Max6(0x5B); } } void Metalee_Func_4(void) { // 0xA389F3 Enemy_Metalee *E = Get_Metalee(cur_enemy_index); E->metalee_var_A = 21; uint16 v1 = E->base.properties | 3; E->base.properties = v1; if (EnemyFunc_BF8A(cur_enemy_index, v1, INT16_SHL16(E->metalee_var_F)) & 1) { E->base.instruction_timer = 1; E->base.timer = 0; E->metalee_var_B = FUNC16(Metalee_Func_5); QueueSfx2_Max6(0x5C); } else { E->base.y_pos += E->metalee_var_F; E->base.x_pos += ((int16)(E->base.x_pos - samus_x_pos) >= 0) ? -2 : 2; } } void Metalee_Func_5(void) { // 0xA38A5C Enemy_Metalee *E = Get_Metalee(cur_enemy_index); if (E->metalee_var_A-- == 1) { gEnemySpawnData(cur_enemy_index)->vram_tiles_index = E->base.vram_tiles_index | E->base.palette_index; E->base.palette_index = 2560; E->base.vram_tiles_index = 0; E->base.properties |= kEnemyProps_Deleted; } else { if (E->metalee_var_A == 8) { uint16 v2 = cur_enemy_index; SpawnEprojWithGfx(0, v2, addr_stru_868BFA); SpawnEprojWithGfx(0, v2, addr_stru_868C08); SpawnEprojWithGfx(0, v2, addr_stru_868C16); SpawnEprojWithGfx(0, v2, addr_stru_868C24); } ++E->base.y_pos; } } void Metalee_Func_6(void) { // 0xA38AB2 Enemy_Metalee *E = Get_Metalee(cur_enemy_index); uint16 metalee_var_C = E->metalee_var_C; if (metalee_var_C != E->metalee_var_D) { E->metalee_var_D = metalee_var_C; E->base.current_instruction = g_off_A3894E[metalee_var_C]; E->base.instruction_timer = 1; E->base.timer = 0; } } void Metalee_Shot(void) { // 0xA38B0F Enemy_Metalee *E = Get_Metalee(cur_enemy_index); uint16 varE2A = E->base.vram_tiles_index; uint16 varE2C = E->base.palette_index; Enemy_NormalShotAI_A3(); if (!Get_Metalee(cur_enemy_index)->base.health) { E->base.vram_tiles_index = varE2A; E->base.palette_index = varE2C; uint16 v2 = cur_enemy_index; SpawnEprojWithGfx(E->metalee_var_A, cur_enemy_index, addr_stru_868BFA); SpawnEprojWithGfx(0, v2, addr_stru_868C08); SpawnEprojWithGfx(0, v2, addr_stru_868C16); SpawnEprojWithGfx(0, v2, addr_stru_868C24); E->base.vram_tiles_index = 0; E->base.palette_index = 0; } } void Fireflea_Init(void) { // 0xA38D2D Enemy_FireFlea *E = Get_FireFlea(cur_enemy_index); E->base.current_instruction = addr_kFireflea_Ilist_8C2F; if ((E->ffa_parameter_1 & 2) != 0) { Fireflea_Func_1(cur_enemy_index); Fireflea_Func_2(cur_enemy_index); Fireflea_Func_3(cur_enemy_index); Fireflea_Func_4(cur_enemy_index); Fireflea_Func_5(cur_enemy_index); } else { Fireflea_Func_3(cur_enemy_index); Fireflea_Func_4(cur_enemy_index); Fireflea_Func_6(cur_enemy_index); } } void Fireflea_Func_1(uint16 k) { // 0xA38D5D Enemy_FireFlea *E = Get_FireFlea(k); E->ffa_var_E = E->base.x_pos; E->ffa_var_F = E->base.y_pos; } void Fireflea_Func_2(uint16 k) { // 0xA38D6A Enemy_FireFlea *E = Get_FireFlea(k); E->ffa_var_D = HIBYTE(E->ffa_parameter_1) << 8; } void Fireflea_Func_3(uint16 k) { // 0xA38D75 Enemy_FireFlea *E = Get_FireFlea(k); uint16 v2 = 8 * LOBYTE(E->ffa_parameter_2); if ((E->ffa_parameter_1 & 1) == 0) v2 += 4; E->ffa_var_02 = v2; int v3 = v2 >> 1; E->ffa_var_B = kCommonEnemySpeeds_Linear[v3]; E->ffa_var_A = kCommonEnemySpeeds_Linear[v3 + 1]; } void Fireflea_Func_4(uint16 k) { // 0xA38D9C Enemy_FireFlea *E = Get_FireFlea(k); E->ffa_var_C = LOBYTE(g_word_A38D1D[HIBYTE(E->ffa_parameter_2)]); } void Fireflea_Func_5(uint16 k) { // 0xA38DAE Enemy_FireFlea *E = Get_FireFlea(k); E->base.x_pos = E->ffa_var_E + CosineMult8bit(E->ffa_var_D, E->ffa_var_C); E->base.y_pos = E->ffa_var_F + SineMult8bit(E->ffa_var_D, E->ffa_var_C); } void Fireflea_Func_6(uint16 k) { // 0xA38DD7 Enemy_FireFlea *E = Get_FireFlea(k); E->ffa_var_00 = E->base.y_pos - E->ffa_var_C; E->ffa_var_01 = E->ffa_var_C + E->base.y_pos; } void Fireflea_Main(void) { // 0xA38DEE Enemy_FireFlea *E = Get_FireFlea(cur_enemy_index); if ((E->ffa_parameter_1 & 2) != 0) { E->base.x_pos = E->ffa_var_E + CosineMult8bit(HIBYTE(E->ffa_var_D), E->ffa_var_C); E->base.y_pos = E->ffa_var_F + SineMult8bit(HIBYTE(E->ffa_var_D), E->ffa_var_C); E->ffa_var_D += *(uint16 *)((uint8 *)&E->ffa_var_A + 1); } else { int v2 = E->ffa_var_02 >> 1; AddToHiLo(&E->base.y_pos, &E->base.y_subpos, __PAIR32__(kCommonEnemySpeeds_Linear[v2], kCommonEnemySpeeds_Linear[v2 + 1])); if ((int16)(E->base.y_pos - E->ffa_var_00) < 0 || (int16)(E->base.y_pos - E->ffa_var_01) >= 0) { E->ffa_var_02 ^= 4; } } } void Fireflea_Touch(uint16 k) { // 0xA38E6B uint16 v1 = 0; Enemy_NormalTouchAI_A3(); EnemyDeathAnimation(k, v1); if (sign16(fireflea_darkness_level - 12)) fireflea_darkness_level += 2; } void Fireflea_Powerbomb(void) { // 0xA38E83 Enemy_NormalPowerBombAI_A3(); Fireflea_Common(); } void Fireflea_Shot(void) { // 0xA38E89 Enemy_NormalShotAI_A3(); Fireflea_Common(); } void Fireflea_Common(void) { // 0xA38E8D if (!Get_FireFlea(cur_enemy_index)->base.health) { if (sign16(fireflea_darkness_level - 12)) fireflea_darkness_level += 2; } } const uint16 *MaridiaFish_Instr_3(uint16 k, const uint16 *jp) { // 0xA39096 Get_MaridiaFish(cur_enemy_index)->base.layer = 6; return jp; } const uint16 *MaridiaFish_Instr_1(uint16 k, const uint16 *jp) { // 0xA390A0 Get_MaridiaFish(cur_enemy_index)->base.layer = 2; return jp; } const uint16 *MaridiaFish_Instr_2(uint16 k, const uint16 *jp) { // 0xA390AA Get_MaridiaFish(cur_enemy_index)->mfh_var_01 = 1; return jp; } void MaridiaFish_Init(void) { // 0xA390B5 Enemy_MaridiaFish *E = Get_MaridiaFish(cur_enemy_index); E->base.current_instruction = addr_kMaridiaFish_Ilist_902A; E->mfh_var_A = FUNC16(MaridiaFish_Func_1); if (!HIBYTE(E->mfh_parameter_1)) { E->base.current_instruction = addr_kMaridiaFish_Ilist_9060; E->mfh_var_A = FUNC16(MaridiaFish_Func_2); } int v1 = (8 * LOBYTE(E->mfh_parameter_1)) >> 1; E->mfh_var_C = kCommonEnemySpeeds_Linear[v1]; E->mfh_var_B = kCommonEnemySpeeds_Linear[v1 + 1]; E->mfh_var_E = kCommonEnemySpeeds_Linear[v1 + 2]; E->mfh_var_D = kCommonEnemySpeeds_Linear[v1 + 3]; E->mfh_var_00 = LOBYTE(E->mfh_parameter_2); E->mfh_var_02 = HIBYTE(E->mfh_parameter_2); E->mfh_var_F = 0; E->mfh_var_01 = 0; E->mfh_var_03 = SineMult8bit(E->mfh_var_F, E->mfh_var_00); } void MaridiaFish_Func_1(void) { // 0xA39132 Enemy_MaridiaFish *E = Get_MaridiaFish(cur_enemy_index); if (Enemy_MoveRight_IgnoreSlopes(cur_enemy_index, __PAIR32__(E->mfh_var_E, E->mfh_var_D))) { E->mfh_var_A = FUNC16(MaridiaFish_Func_3); E->base.instruction_timer = 1; E->base.timer = 0; E->base.current_instruction = addr_kMaridiaFish_Ilist_903C; } else { uint16 v2 = SineMult8bit(E->mfh_var_F, E->mfh_var_00); E->mfh_var_04 = v2; if (Enemy_MoveDown(cur_enemy_index, INT16_SHL16(v2 - E->mfh_var_03))) { E->mfh_var_A = FUNC16(MaridiaFish_Func_3); E->base.instruction_timer = 1; E->base.timer = 0; E->base.current_instruction = addr_kMaridiaFish_Ilist_903C; } else { E->mfh_var_F = (uint8)(LOBYTE(E->mfh_var_02) + E->mfh_var_F); } } E->mfh_var_03 = E->mfh_var_04; } void MaridiaFish_Func_2(void) { // 0xA391AB Enemy_MaridiaFish *E = Get_MaridiaFish(cur_enemy_index); if (Enemy_MoveRight_IgnoreSlopes(cur_enemy_index, __PAIR32__(E->mfh_var_C, E->mfh_var_B))) { E->mfh_var_A = FUNC16(MaridiaFish_Func_4); E->base.instruction_timer = 1; E->base.timer = 0; E->base.current_instruction = addr_kMaridiaFish_Ilist_9072; } else { uint16 v2 = SineMult8bit(E->mfh_var_F, E->mfh_var_00); E->mfh_var_04 = v2; if (Enemy_MoveDown(cur_enemy_index, INT16_SHL16(v2 - E->mfh_var_03))) { E->mfh_var_A = FUNC16(MaridiaFish_Func_4); E->base.instruction_timer = 1; E->base.timer = 0; E->base.current_instruction = addr_kMaridiaFish_Ilist_9072; } else { E->mfh_var_F = (uint8)(LOBYTE(E->mfh_var_02) + E->mfh_var_F); } } E->mfh_var_03 = E->mfh_var_04; } void MaridiaFish_Func_3(void) { // 0xA39224 Enemy_MaridiaFish *E = Get_MaridiaFish(cur_enemy_index); if (E->mfh_var_01) { E->mfh_var_01 = 0; E->mfh_var_A = FUNC16(MaridiaFish_Func_2); E->mfh_var_02 = -E->mfh_var_02; E->base.instruction_timer = 1; E->base.timer = 0; E->base.current_instruction = addr_kMaridiaFish_Ilist_9060; } } void MaridiaFish_Func_4(void) { // 0xA39256 Enemy_MaridiaFish *E = Get_MaridiaFish(cur_enemy_index); if (E->mfh_var_01) { E->mfh_var_01 = 0; E->mfh_var_A = FUNC16(MaridiaFish_Func_1); E->mfh_var_02 = -E->mfh_var_02; E->base.instruction_timer = 1; E->base.timer = 0; E->base.current_instruction = addr_kMaridiaFish_Ilist_902A; } } void CallMaridiaFishFunc(uint32 ea) { switch (ea) { case fnMaridiaFish_Func_1: MaridiaFish_Func_1(); return; case fnMaridiaFish_Func_2: MaridiaFish_Func_2(); return; case fnMaridiaFish_Func_3: MaridiaFish_Func_3(); return; case fnMaridiaFish_Func_4: MaridiaFish_Func_4(); return; default: Unreachable(); } } void MaridiaFish_Main(void) { // 0xA3912B Enemy_MaridiaFish *E = Get_MaridiaFish(cur_enemy_index); CallMaridiaFishFunc(E->mfh_var_A | 0xA30000); } void Elevator_Init(void) { // 0xA394E6 Enemy_Elevator *E = Get_Elevator(cur_enemy_index); E->base.spritemap_pointer = addr_kSpritemap_Nothing_A3; E->base.instruction_timer = 1; E->base.timer = 0; E->base.current_instruction = addr_kElevator_Ilist_94D6; E->elevat_parameter_1 *= 2; E->elevat_var_A = E->base.y_pos; if (elevator_status != 2) elevator_flags = elevator_status = 0; if (__PAIR32__(elevator_status, elevator_flags)) { E->base.y_pos = E->elevat_parameter_2; Elevator_Func_4(); } } static Func_V *const off_A39540[4] = { Elevator_Func_1, Elevator_Func_2, Elevator_Func_3, Elevator_Func3b }; void Elevator_Frozen(void) { // 0xA3952A if (!door_transition_flag_elevator_zebetites) { if (__PAIR32__(elevator_status, elevator_flags)) off_A39540[elevator_status](); } } void Elevator_Func_1(void) { // 0xA39548 if ((g_word_A394E2[Get_Elevator(cur_enemy_index)->elevat_parameter_1 >> 1] & joypad1_newkeys) != 0) { QueueSfx3_Max6(0xB); QueueSfx1_Max6(0x32); CallSomeSamusCode(7); ResetProjectileData(); Elevator_Func_4(); ++elevator_status; } else { elevator_flags = 0; } } void Elevator_Func_2(void) { // 0xA39579 Enemy_Elevator *E = Get_Elevator(cur_enemy_index); if (E->elevat_parameter_1) { elevator_direction = 0x8000; AddToHiLo(&E->base.y_pos, &E->base.y_subpos, -0x18000); } else { elevator_direction = 0; AddToHiLo(&E->base.y_pos, &E->base.y_subpos, 0x18000); } Elevator_Func_4(); } void Elevator_Func_3(void) { // 0xA395B9 ++elevator_status; Elevator_Func3b(); } void Elevator_Func3b(void) { // 0xA395BC Enemy_Elevator *E = Get_Elevator(cur_enemy_index); if (E->elevat_parameter_1) { AddToHiLo(&E->base.y_pos, &E->base.y_subpos, 0x18000); if (E->base.y_pos < E->elevat_var_A) { Elevator_Func_4(); return; } } else { AddToHiLo(&E->base.y_pos, &E->base.y_subpos, -0x18000); if (E->base.y_pos >= E->elevat_var_A) { Elevator_Func_4(); return; } } elevator_status = 0; elevator_flags = 0; QueueSfx3_Max6(0x25); E->base.y_pos = E->elevat_var_A; CallSomeSamusCode(0xB); Elevator_Func_4(); } void Elevator_Func_4(void) { // 0xA39612 Enemy_Elevator *E = Get_Elevator(cur_enemy_index); samus_y_pos = E->base.y_pos - 26; samus_y_subpos = 0; samus_x_pos = E->base.x_pos; samus_y_speed = 0; samus_y_subspeed = 0; } void Crab_Init(void) { // 0xA396E3 EnemyData *v1 = gEnemyData(cur_enemy_index); v1->parameter_2 = 8; v1->current_instruction = g_off_A396DB[v1->current_instruction & 3]; StoneZoomer_E67A(cur_enemy_index); } void Crab_Func_1(void) { // 0xA396FD ; } void Slug_Init(void) { // 0xA3993B EnemyData *v1 = gEnemyData(cur_enemy_index); v1->parameter_2 = 10; v1->current_instruction = g_off_A3992B[v1->current_instruction & 3]; StoneZoomer_E67A(cur_enemy_index); } void Slug_Func_1(void) { // 0xA39955 ; } const uint16 *PlatformThatFallsWithSamus_Instr_3(uint16 k, const uint16 *jp) { // 0xA39C6B Get_PlatformThatFallsWithSamus(cur_enemy_index)->ptfwss_var_02 = 0; return jp; } const uint16 *PlatformThatFallsWithSamus_Instr_4(uint16 k, const uint16 *jp) { // 0xA39C76 Get_PlatformThatFallsWithSamus(cur_enemy_index)->ptfwss_var_02 = 1; return jp; } const uint16 *PlatformThatFallsWithSamus_Instr_1(uint16 k, const uint16 *jp) { // 0xA39C81 Get_PlatformThatFallsWithSamus(cur_enemy_index)->ptfwss_var_02 = 0; return jp; } const uint16 *PlatformThatFallsWithSamus_Instr_2(uint16 k, const uint16 *jp) { // 0xA39C8C Get_PlatformThatFallsWithSamus(cur_enemy_index)->ptfwss_var_02 = 1; return jp; } void PlatformThatFallsWithSamus_Init(void) { // 0xA39C9F Enemy_PlatformThatFallsWithSamus *E = Get_PlatformThatFallsWithSamus(cur_enemy_index); E->ptfwss_var_1F = -1; uint16 ptfwss_parameter_1 = E->ptfwss_parameter_1; E->ptfwss_var_02 = ptfwss_parameter_1; if (ptfwss_parameter_1) PlatformThatFalls_Init(cur_enemy_index, addr_kPlatformThatFallsWithSamus_Ilist_9BFD); else PlatformThatFalls_Init(cur_enemy_index, addr_kPlatformThatFallsWithSamus_Ilist_9BE7); } void FastMovingSlowSinkingPlatform_Init(void) { // 0xA39CBA Enemy_PlatformThatFallsWithSamus *E = Get_PlatformThatFallsWithSamus(cur_enemy_index); uint16 ptfwss_parameter_1 = E->ptfwss_parameter_1; E->ptfwss_var_02 = ptfwss_parameter_1; if (ptfwss_parameter_1) PlatformThatFalls_Init(cur_enemy_index, addr_kPlatformThatFallsWithSamus_Ilist_9C55); else PlatformThatFalls_Init(cur_enemy_index, addr_kPlatformThatFallsWithSamus_Ilist_9C3F); } void PlatformThatFalls_Init(uint16 k, uint16 j) { // 0xA39CCC Enemy_PlatformThatFallsWithSamus *E = Get_PlatformThatFallsWithSamus(k); E->base.current_instruction = j; int v3 = (8 * LOBYTE(E->ptfwss_parameter_2)) >> 1; E->ptfwss_var_C = kCommonEnemySpeeds_Linear[v3]; E->ptfwss_var_B = kCommonEnemySpeeds_Linear[v3 + 1]; E->ptfwss_var_E = kCommonEnemySpeeds_Linear[v3 + 2]; E->ptfwss_var_D = kCommonEnemySpeeds_Linear[v3 + 3]; E->ptfwss_var_00 = 0; E->ptfwss_var_03 = 0; E->ptfwss_var_04 = 0; E->ptfwss_var_A = E->base.y_pos + 1; E->ptfwss_var_F = 0; E->ptfwss_var_05 = HIBYTE(E->ptfwss_parameter_2); } static Func_V *const off_A39C97[2] = { PlatformThatFallsWithSamus_Func_1, PlatformThatFallsWithSamus_Func_2 }; static Func_V *const off_A39C9B[2] = { PlatformThatFallsWithSamus_Func_3, PlatformThatFallsWithSamus_Func_4 }; void PlatformThatFallsWithSamus_Main(void) { // 0xA39D16 Enemy_PlatformThatFallsWithSamus *E = Get_PlatformThatFallsWithSamus(cur_enemy_index); E->ptfwss_var_00 = 0; if (CheckIfEnemyTouchesSamus(cur_enemy_index)) E->ptfwss_var_00 = 1; off_A39C97[E->ptfwss_var_02](); int v3 = Get_PlatformThatFallsWithSamus(cur_enemy_index)->ptfwss_var_00; off_A39C9B[v3](); if (E->ptfwss_var_00 != E->ptfwss_var_06) E->ptfwss_var_F = 0; E->ptfwss_var_06 = E->ptfwss_var_00; } void PlatformThatFallsWithSamus_Func_1(void) { // 0xA39D5E Enemy_PlatformThatFallsWithSamus *E = Get_PlatformThatFallsWithSamus(cur_enemy_index); E->ptfwss_var_01 = E->base.x_pos; if (Enemy_MoveRight_IgnoreSlopes(cur_enemy_index, __PAIR32__(E->ptfwss_var_E, E->ptfwss_var_D))) { E->ptfwss_var_02 = 1; PlatformThatFallsWithSamus_Func_8(); } } void PlatformThatFallsWithSamus_Func_2(void) { // 0xA39D83 Enemy_PlatformThatFallsWithSamus *E = Get_PlatformThatFallsWithSamus(cur_enemy_index); E->ptfwss_var_01 = E->base.x_pos; if (Enemy_MoveRight_IgnoreSlopes(cur_enemy_index, __PAIR32__(E->ptfwss_var_C, E->ptfwss_var_B))) { E->ptfwss_var_02 = 0; PlatformThatFallsWithSamus_Func_7(); } } void PlatformThatFallsWithSamus_Func_3(void) { // 0xA39DA8 Enemy_PlatformThatFallsWithSamus *E = Get_PlatformThatFallsWithSamus(cur_enemy_index); if ((int16)(E->base.y_pos - E->ptfwss_var_A) < 0) goto LABEL_5; PlatformThatFallsWithSamus_Func_9(); uint16 ptfwss_var_05; ptfwss_var_05 = ++E->ptfwss_var_F; if ((int16)(ptfwss_var_05 - E->ptfwss_var_05) >= 0) { ptfwss_var_05 = E->ptfwss_var_05; E->ptfwss_var_F = ptfwss_var_05; } int v3; v3 = (8 * ptfwss_var_05) >> 1; if (Enemy_MoveDown(cur_enemy_index, __PAIR32__(kCommonEnemySpeeds_Quadratic[v3 + 3], kCommonEnemySpeeds_Quadratic[v3 + 2]))) { LABEL_5: E->ptfwss_var_F = 0; PlatformThatFallsWithSamus_Func_10(); } } void PlatformThatFallsWithSamus_Func_4(void) { // 0xA39DE4 Enemy_PlatformThatFallsWithSamus *E = Get_PlatformThatFallsWithSamus(cur_enemy_index); if ((int16)(++E->ptfwss_var_F - E->ptfwss_var_05) >= 0) E->ptfwss_var_F = E->ptfwss_var_05; extra_samus_x_displacement += E->base.x_pos - E->ptfwss_var_01; E->ptfwss_var_01 = E->base.y_pos; int v2 = (8 * E->ptfwss_var_F) >> 1; if (Enemy_MoveDown(cur_enemy_index, __PAIR32__(kCommonEnemySpeeds_Quadratic[v2 + 1], kCommonEnemySpeeds_Quadratic[v2]))) { E->ptfwss_var_F = 0; PlatformThatFallsWithSamus_Func_10(); } extra_samus_y_displacement += E->base.y_pos - E->ptfwss_var_01; } void PlatformThatFallsWithSamus_Func_5(void) { // 0xA39E47 Enemy_PlatformThatFallsWithSamus *E = Get_PlatformThatFallsWithSamus(cur_enemy_index); uint16 v0 = addr_kPlatformThatFallsWithSamus_Ilist_9C13; if ((E->ptfwss_var_1F & 0x8000) != 0) v0 = addr_kPlatformThatFallsWithSamus_Ilist_9BBB; E->base.current_instruction = v0; E->base.instruction_timer = 1; E->base.timer = 0; } void PlatformThatFallsWithSamus_Func_6(void) { // 0xA39E64 Enemy_PlatformThatFallsWithSamus *E = Get_PlatformThatFallsWithSamus(cur_enemy_index); uint16 v0 = addr_kPlatformThatFallsWithSamus_Ilist_9C29; if ((E->ptfwss_var_1F & 0x8000) != 0) v0 = addr_kPlatformThatFallsWithSamus_Ilist_9BD1; E->base.current_instruction = v0; E->base.instruction_timer = 1; E->base.timer = 0; } void PlatformThatFallsWithSamus_Func_7(void) { // 0xA39E81 Enemy_PlatformThatFallsWithSamus *E = Get_PlatformThatFallsWithSamus(cur_enemy_index); uint16 v0 = addr_kPlatformThatFallsWithSamus_Ilist_9C3F; if ((E->ptfwss_var_1F & 0x8000) != 0) v0 = addr_kPlatformThatFallsWithSamus_Ilist_9BE7; E->base.current_instruction = v0; E->base.instruction_timer = 1; E->base.timer = 0; } void PlatformThatFallsWithSamus_Func_8(void) { // 0xA39E9E Enemy_PlatformThatFallsWithSamus *E = Get_PlatformThatFallsWithSamus(cur_enemy_index); uint16 v0 = addr_kPlatformThatFallsWithSamus_Ilist_9C55; if ((E->ptfwss_var_1F & 0x8000) != 0) v0 = addr_kPlatformThatFallsWithSamus_Ilist_9BFD; E->base.current_instruction = v0; E->base.instruction_timer = 1; E->base.timer = 0; } void PlatformThatFallsWithSamus_Func_9(void) { // 0xA39EBB Enemy_PlatformThatFallsWithSamus *E = Get_PlatformThatFallsWithSamus(cur_enemy_index); if (!E->ptfwss_var_03) { E->ptfwss_var_03 = 1; if (E->ptfwss_var_02) PlatformThatFallsWithSamus_Func_6(); else PlatformThatFallsWithSamus_Func_5(); } E->ptfwss_var_04 = 0; } void PlatformThatFallsWithSamus_Func_10(void) { // 0xA39EE1 Enemy_PlatformThatFallsWithSamus *E = Get_PlatformThatFallsWithSamus(cur_enemy_index); if (!E->ptfwss_var_04) { E->ptfwss_var_04 = 1; if (E->ptfwss_var_02) PlatformThatFallsWithSamus_Func_8(); else PlatformThatFallsWithSamus_Func_7(); } E->ptfwss_var_03 = 0; } void FastMovingSlowSinkingPlatform_Shot(void) { // 0xA39F08 Enemy_NormalShotAI_A3(); Enemy_PlatformThatFallsWithSamus *E = Get_PlatformThatFallsWithSamus(cur_enemy_index); if (E->base.frozen_timer) { if (E->ptfwss_var_02) E->base.spritemap_pointer = addr_kPlatformThatFallsWithSamus_Sprmap_A015; else E->base.spritemap_pointer = addr_kPlatformThatFallsWithSamus_Sprmap_A009; } } void Roach_Func_1(void) { // 0xA3A12F Enemy_Roach *E = Get_Roach(cur_enemy_index); uint16 roach_var_24 = E->roach_var_24; if (roach_var_24 != E->roach_var_25) { E->roach_var_25 = roach_var_24; E->base.current_instruction = roach_var_24; E->base.instruction_timer = 1; E->base.timer = 0; } } void Roach_Init(void) { // 0xA3A14D Enemy_Roach *E = Get_Roach(cur_enemy_index); E->roach_var_25 = 0; E->roach_var_24 = 0; Roach_Func_2(cur_enemy_index); Roach_Func_4(cur_enemy_index); Roach_Func_5(cur_enemy_index); Roach_Func_6(cur_enemy_index); Roach_Func_7(cur_enemy_index); Roach_Func_8(cur_enemy_index); E->roach_var_24 = g_off_A3A111[E->roach_var_20 >> 1]; Roach_Func_1(); E->roach_var_B = FUNC16(Roach_Func_9); } void Roach_Func_2(uint16 k) { // 0xA3A183 Enemy_Roach *E = Get_Roach(k); Point32 pt = ConvertAngleToXy(HIBYTE(E->roach_parameter_1), LOBYTE(E->roach_parameter_1)); SetHiLo(&E->roach_var_01, &E->roach_var_00, pt.x); SetHiLo(&E->roach_var_03, &E->roach_var_02, pt.y); } void Roach_Func_3(uint16 k) { // 0xA3A1B0 Enemy_Roach *E = Get_Roach(k); SetHiLo(&E->roach_var_01, &E->roach_var_00, CosineMult8bitFull(HIBYTE(E->roach_parameter_1), LOBYTE(E->roach_parameter_1))); SetHiLo(&E->roach_var_03, &E->roach_var_02, SineMult8bitFull(HIBYTE(E->roach_parameter_1), LOBYTE(E->roach_parameter_1))); } void Roach_Func_4(uint16 k) { // 0xA3A1F3 Enemy_Roach *E = Get_Roach(k); SetHiLo(&E->roach_var_05, &E->roach_var_04, CosineMult8bitFull((uint8)(HIBYTE(E->roach_parameter_1) - 32), LOBYTE(E->roach_parameter_1))); SetHiLo(&E->roach_var_07, &E->roach_var_06, SineMult8bitFull((uint8)(HIBYTE(E->roach_parameter_1) - 32), LOBYTE(E->roach_parameter_1))); } void Roach_Func_5(uint16 k) { // 0xA3A23E Enemy_Roach *E = Get_Roach(k); SetHiLo(&E->roach_var_09, &E->roach_var_08, CosineMult8bitFull((uint8)(HIBYTE(E->roach_parameter_1) + 32), LOBYTE(E->roach_parameter_1))); SetHiLo(&E->roach_var_0B, &E->roach_var_0A, SineMult8bitFull((uint8)(HIBYTE(E->roach_parameter_1) + 32), LOBYTE(E->roach_parameter_1))); } void Roach_Func_6(uint16 k) { // 0xA3A289 Enemy_Roach *E = Get_Roach(k); E->roach_var_20 = 2 * ((uint8)(HIBYTE(E->roach_parameter_1) - 48) >> 5); } void Roach_Func_7(uint16 k) { // 0xA3A29E Enemy_Roach *E = Get_Roach(k); E->roach_var_21 = 2 * ((uint8)(HIBYTE(E->roach_parameter_1) - 80) >> 5); } void Roach_Func_8(uint16 k) { // 0xA3A2B7 Enemy_Roach *E = Get_Roach(k); E->roach_var_22 = 2 * ((uint8)(HIBYTE(E->roach_parameter_1) - 48 + 32) >> 5); } void CallRoachFunc(uint32 ea) { switch (ea) { case fnRoach_Func_9: Roach_Func_9(); return; // 0xa3a2d7 case fnRoach_Func_10: Roach_Func_10(); return; // 0xa3a301 case fnRoach_Func_11: Roach_Func_11(); return; // 0xa3a30b case fnRoach_Func_12: Roach_Func_12(); return; // 0xa3a315 case fnRoach_Func_13: Roach_Func_13(); return; // 0xa3a325 case fnRoach_Func_14: Roach_Func_14(); return; // 0xa3a33b case fnRoach_Func_15: Roach_Func_15(); return; // 0xa3a34b case fnRoach_Func_16: Roach_Func_16(); return; // 0xa3a380 case fnRoach_Func_19: Roach_Func_19(); return; // 0xa3a407 case fnRoach_Func_20: Roach_Func_20(); return; // 0xa3a40e case fnRoach_Func_21: Roach_Func_21(); return; // 0xa3a440 case fnRoach_Func_22: Roach_Func_22(); return; // 0xa3a447 case fnRoach_Func_23: Roach_Func_23(); return; // 0xa3a44e case fnRoach_Func_24: Roach_Func_24(); return; // 0xa3a462 case fnRoach_Func_25: Roach_Func_25(); return; // 0xa3a476 case fnRoach_Func_26: Roach_Func_26(); return; // 0xa3a4b6 case fnRoach_Func_27: Roach_Func_27(); return; // 0xa3a4f0 default: Unreachable(); } } void Roach_Main(void) { // 0xA3A2D0 Enemy_Roach *E = Get_Roach(cur_enemy_index); CallRoachFunc(E->roach_var_B | 0xA30000); } void Roach_Func_9(void) { // 0xA3A2D7 Enemy_Roach *E = Get_Roach(cur_enemy_index); if (IsSamusWithinEnemy_X(cur_enemy_index, LOBYTE(E->roach_parameter_2))) { if (IsSamusWithinEnemy_Y(cur_enemy_index, LOBYTE(E->roach_parameter_2))) E->roach_var_B = g_off_A3A121[HIBYTE(E->roach_parameter_2)]; } } void Roach_Func_10(void) { // 0xA3A301 Get_Roach(cur_enemy_index)->roach_var_B = FUNC16(Roach_Func_19); } void Roach_Func_11(void) { // 0xA3A30B Get_Roach(cur_enemy_index)->roach_var_B = FUNC16(Roach_Func_20); } void Roach_Func_12(void) { // 0xA3A315 random_number = 11; Get_Roach(cur_enemy_index)->roach_var_B = FUNC16(Roach_Func_27); } void Roach_Func_13(void) { // 0xA3A325 Enemy_Roach *E = Get_Roach(cur_enemy_index); E->roach_var_A = 512; random_number = 11; E->roach_var_B = FUNC16(Roach_Func_26); } void Roach_Func_14(void) { // 0xA3A33B Enemy_Roach *E = Get_Roach(cur_enemy_index); E->roach_var_F = 32; E->roach_var_B = FUNC16(Roach_Func_23); } void Roach_Func_15(void) { // 0xA3A34B uint8 v1 = 64 - CalculateAngleOfSamusFromEnemy(cur_enemy_index); Enemy_Roach *E = Get_Roach(cur_enemy_index); E->roach_var_C = v1; Roach_Func_18(cur_enemy_index); Roach_Func_17(cur_enemy_index); E->roach_var_24 = g_off_A3A111[E->roach_var_23 >> 1]; Roach_Func_1(); E->roach_var_B = FUNC16(Roach_Func_21); } void Roach_Func_16(void) { // 0xA3A380 uint16 v1 = (uint8)(64 - CalculateAngleOfSamusFromEnemy(cur_enemy_index) + 0x80); Enemy_Roach *E = Get_Roach(cur_enemy_index); E->roach_var_C = v1; Roach_Func_18(cur_enemy_index); Roach_Func_17(cur_enemy_index); E->roach_var_24 = g_off_A3A111[E->roach_var_23 >> 1]; Roach_Func_1(); E->roach_var_B = FUNC16(Roach_Func_22); } void Roach_Func_17(uint16 k) { // 0xA3A3B5 Enemy_Roach *E = Get_Roach(k); E->roach_var_23 = 2 * ((uint8)(E->roach_var_C - 48) >> 5); } void Roach_Func_18(uint16 k) { // 0xA3A3CA Enemy_Roach *E = Get_Roach(k); SetHiLo(&E->roach_var_0D, &E->roach_var_0C, CosineMult8bitFull(E->roach_var_C, LOBYTE(E->roach_parameter_1))); SetHiLo(&E->roach_var_0F, &E->roach_var_0E, SineMult8bitFull(E->roach_var_C, LOBYTE(E->roach_parameter_1))); } void Roach_Func_19(void) { // 0xA3A407 Roach_Func_29(cur_enemy_index); } void Roach_Func_20(void) { // 0xA3A40E Enemy_Roach *E = Get_Roach(cur_enemy_index); if ((E->base.frame_counter & 0x10) != 0) { E->roach_var_24 = g_off_A3A111[E->roach_var_22 >> 1]; Roach_Func_1(); Roach_Func_31(cur_enemy_index); } else { E->roach_var_24 = g_off_A3A111[E->roach_var_21 >> 1]; Roach_Func_1(); Roach_Func_30(cur_enemy_index); } } void Roach_Func_21(void) { // 0xA3A440 Roach_Func_32(cur_enemy_index); } void Roach_Func_22(void) { // 0xA3A447 Roach_Func_32(cur_enemy_index); } void Roach_Func_23(void) { // 0xA3A44E Enemy_Roach *E = Get_Roach(cur_enemy_index); if ((--E->roach_var_F & 0x8000) != 0) E->roach_var_B = FUNC16(Roach_Func_9); else Roach_Func_29(cur_enemy_index); } void Roach_Func_24(void) { // 0xA3A462 Enemy_Roach *E = Get_Roach(cur_enemy_index); if ((--E->roach_var_F & 0x8000) != 0) E->roach_var_B = FUNC16(Roach_Func_27); else Roach_Func_33(cur_enemy_index); } void Roach_Func_25(void) { // 0xA3A476 Enemy_Roach *E = Get_Roach(cur_enemy_index); bool v2 = (--E->roach_var_A & 0x8000) != 0; if (v2) { LABEL_6: Roach_Func_32(cur_enemy_index); return; } v2 = (--E->roach_var_F & 0x8000) != 0; if (!v2) { uint16 v3 = Abs16(E->base.x_pos - samus_x_pos); if (!sign16(v3 - 96)) { uint16 v4 = Abs16(E->base.y_pos - samus_y_pos); if (!sign16(v4 - 96)) Roach_Func_28(); } goto LABEL_6; } E->roach_var_B = FUNC16(Roach_Func_26); } void Roach_Func_26(void) { // 0xA3A4B6 uint8 v1 = NextRandom() - 64; Enemy_Roach *E = Get_Roach(cur_enemy_index); E->roach_var_C += v1; Roach_Func_18(cur_enemy_index); Roach_Func_17(cur_enemy_index); E->roach_var_24 = g_off_A3A111[E->roach_var_23 >> 1]; Roach_Func_1(); E->roach_var_F = 32; E->roach_var_B = FUNC16(Roach_Func_25); } void Roach_Func_27(void) { // 0xA3A4F0 uint8 v1 = NextRandom() - 64; Enemy_Roach *E = Get_Roach(cur_enemy_index); E->roach_var_C += v1; Roach_Func_18(cur_enemy_index); Roach_Func_17(cur_enemy_index); E->roach_var_24 = g_off_A3A111[E->roach_var_23 >> 1]; Roach_Func_1(); E->roach_var_F = 32; E->roach_var_B = FUNC16(Roach_Func_24); } void Roach_Func_28(void) { // 0xA3A52A Enemy_Roach *E = Get_Roach(cur_enemy_index); E->roach_var_0D = -E->roach_var_0D; E->roach_var_0C = -E->roach_var_0C; E->roach_var_0F = -E->roach_var_0F; E->roach_var_0E = -E->roach_var_0E; uint16 v1 = (E->roach_var_23 + 4) & 7; E->roach_var_23 = v1; E->roach_var_24 = g_off_A3A111[v1 >> 1]; Roach_Func_1(); } void Roach_Func_29(uint16 k) { // 0xA3A578 Enemy_Roach *E = Get_Roach(k); uint16 varE20 = HIBYTE(E->roach_parameter_1); EnemyFunc_B691(varE20, (Point32) { __PAIR32__(E->roach_var_01, E->roach_var_00), __PAIR32__(E->roach_var_03, E->roach_var_02) }); } void Roach_Func_30(uint16 k) { // 0xA3A5A3 Enemy_Roach *E = Get_Roach(k); AddToHiLo(&E->base.x_pos, &E->base.x_subpos, __PAIR32__(E->roach_var_05, E->roach_var_04)); AddToHiLo(&E->base.y_pos, &E->base.y_subpos, __PAIR32__(E->roach_var_07, E->roach_var_06)); } void Roach_Func_31(uint16 k) { // 0xA3A5DA Enemy_Roach *E = Get_Roach(k); AddToHiLo(&E->base.x_pos, &E->base.x_subpos, __PAIR32__(E->roach_var_09, E->roach_var_08)); AddToHiLo(&E->base.y_pos, &E->base.y_subpos, __PAIR32__(E->roach_var_0B, E->roach_var_0A)); } void Roach_Func_32(uint16 k) { // 0xA3A611 Enemy_Roach *E = Get_Roach(k); AddToHiLo(&E->base.x_pos, &E->base.x_subpos, __PAIR32__(E->roach_var_0D, E->roach_var_0C)); AddToHiLo(&E->base.y_pos, &E->base.y_subpos, __PAIR32__(E->roach_var_0F, E->roach_var_0E)); } void Roach_Func_33(uint16 k) { // 0xA3A648 Enemy_Roach *E = Get_Roach(k); if (Enemy_MoveRight_IgnoreSlopes(k, __PAIR32__(E->roach_var_0D, E->roach_var_0C))) { E->roach_var_B = FUNC16(Roach_Func_9); } else { if (Enemy_MoveDown(k, __PAIR32__(E->roach_var_0F, E->roach_var_0E))) E->roach_var_B = FUNC16(Roach_Func_9); } } void Mochtroid_Init(void) { // 0xA3A77D Enemy_Mochtroid *E = Get_Mochtroid(cur_enemy_index); E->base.layer = 2; Mochtroid_Func_4(cur_enemy_index, addr_kMochtroid_Ilist_A745); E->mochtr_var_F = 0; } static Func_V *const off_A3A7A4[3] = { Mochtroid_Func_1, Mochtroid_Func_3, Mochtroid_Func_2 }; void Mochtroid_Main(void) { // 0xA3A790 uint16 v0 = 2 * Get_Mochtroid(cur_enemy_index)->mochtr_var_F; Get_Mochtroid(cur_enemy_index)->mochtr_var_F = 0; off_A3A7A4[v0 >> 1](); } void Mochtroid_Func_1(void) { // 0xA3A7AA int16 v5, v10; Enemy_Mochtroid *E = Get_Mochtroid(cur_enemy_index); int32 t = INT16_SHL8((int16)(E->base.y_pos - samus_y_pos) >> 2); AddToHiLo(&E->mochtr_var_D, &E->mochtr_var_C, -t); if ((int16)E->mochtr_var_D < 0) { if ((uint16)E->mochtr_var_D < 0xFFFD) { v5 = -3; goto LABEL_8; } } else if ((uint16)E->mochtr_var_D >= 3) { v5 = 3; LABEL_8: E->mochtr_var_D = v5; E->mochtr_var_C = 0; } if (Enemy_MoveDown(cur_enemy_index, __PAIR32__(E->mochtr_var_D, E->mochtr_var_C))) { E->mochtr_var_C = 0; E->mochtr_var_D = 0; } t = INT16_SHL8((int16)(E->base.x_pos - samus_x_pos) >> 2); AddToHiLo(&E->mochtr_var_B, &E->mochtr_var_A, -t); if ((int16)E->mochtr_var_B < 0) { if ((uint16)E->mochtr_var_B < 0xFFFD) { v10 = -3; goto LABEL_21; } } else if ((uint16)E->mochtr_var_B >= 3) { v10 = 3; LABEL_21: E->mochtr_var_B = v10; E->mochtr_var_A = 0; } if (Enemy_MoveRight_IgnoreSlopes(cur_enemy_index, __PAIR32__(E->mochtr_var_B, E->mochtr_var_A))) { E->mochtr_var_A = 0; E->mochtr_var_B = 0; } Mochtroid_Func_4(cur_enemy_index, addr_kMochtroid_Ilist_A745); } void Mochtroid_Func_2(void) { // 0xA3A88F Enemy_Mochtroid *E = Get_Mochtroid(cur_enemy_index); int v2 = (E->mochtr_var_E & 6) >> 1; E->base.x_pos += g_word_A3A76D[v2]; E->base.y_pos += g_word_A3A775[v2]; E->mochtr_var_A = 0; E->mochtr_var_B = 0; E->mochtr_var_C = 0; E->mochtr_var_D = 0; if (E->mochtr_var_E-- == 1) E->mochtr_var_F = 0; Mochtroid_Func_4(cur_enemy_index, addr_kMochtroid_Ilist_A745); } void Mochtroid_Func_3(void) { // 0xA3A8C8 Enemy_Mochtroid *E = Get_Mochtroid(cur_enemy_index); uint16 x_pos = E->base.x_pos; if (x_pos == samus_x_pos) { E->mochtr_var_A = 0; E->mochtr_var_B = 0; } else if ((int16)(x_pos - samus_x_pos) >= 0) { E->mochtr_var_A = 0; E->mochtr_var_B = -1; } else { E->mochtr_var_A = 0; E->mochtr_var_B = 1; } Enemy_MoveRight_IgnoreSlopes(cur_enemy_index, __PAIR32__(E->mochtr_var_B, E->mochtr_var_A)); uint16 y_pos = E->base.y_pos; if (y_pos == samus_y_pos) { E->mochtr_var_C = 0; E->mochtr_var_D = 0; } else if ((int16)(y_pos - samus_y_pos) >= 0) { E->mochtr_var_C = 0; E->mochtr_var_D = -1; } else { E->mochtr_var_C = 0; E->mochtr_var_D = 1; } Enemy_MoveDown(cur_enemy_index, __PAIR32__(E->mochtr_var_D, E->mochtr_var_C)); } void Mochtroid_Func_4(uint16 k, uint16 a) { // 0xA3A93C Enemy_Mochtroid *E = Get_Mochtroid(k); if (a != E->mochtr_var_01) { E->mochtr_var_01 = a; E->base.current_instruction = a; E->base.instruction_timer = 1; E->base.timer = 0; } } void Mochtroid_Touch(void) { // 0xA3A953 Enemy_Mochtroid *E = Get_Mochtroid(cur_enemy_index); E->mochtr_var_F = 1; Mochtroid_Func_4(cur_enemy_index, addr_kMochtroid_Ilist_A759); ++E->mochtr_var_20; if (samus_contact_damage_index) goto LABEL_7; if ((random_enemy_counter & 7) == 7 && !sign16(samus_health - 30)) QueueSfx3_Max6(0x2D); if (!sign16(E->mochtr_var_20 - 80)) { E->mochtr_var_20 = 0; LABEL_7: Enemy_NormalTouchAI_A3(); samus_invincibility_timer = 0; samus_knockback_timer = 0; } } void Mochtroid_Shot(void) { // 0xA3A9A8 Enemy_NormalShotAI_A3(); } const uint16 *Sidehopper_Func_1(uint16 k, const uint16 *jp) { // 0xA3AA68 QueueSfx2_Max3(*jp); return jp + 1; } const uint16 *Sidehopper_Instr_1(uint16 k, const uint16 *jp) { // 0xA3AAFE Get_Sidehopper(cur_enemy_index)->sideh_var_04 = 1; return jp; } void Sidehopper_Init(void) { // 0xA3AB09 random_number = 37; NextRandom(); Enemy_Sidehopper *E = Get_Sidehopper(cur_enemy_index); E->sideh_var_03 = 0; E->sideh_var_04 = 0; E->sideh_var_05 = 0; uint16 v2 = 2 * get_EnemyDef_A2(E->base.enemy_ptr)->field_2A; E->sideh_var_06 = v2; uint16 v4; if (E->sideh_parameter_1) v4 = g_off_A3AACA[E->sideh_var_06 >> 1]; else v4 = g_off_A3AAC2[E->sideh_var_06 >> 1]; E->sideh_var_00 = v4; Sidehopper_Func_3(); if (get_EnemyDef_A2(E->base.enemy_ptr)->field_2A) E->sideh_var_05 = 2; int v6 = E->sideh_var_05 >> 1; E->sideh_var_01 = Sidehopper_Func_2(g_word_A3AAEE[v6], g_word_A3AAE6[v6]); int v8 = E->sideh_var_05 >> 1; E->sideh_var_02 = Sidehopper_Func_2(g_word_A3AAFA[v8], g_word_A3AAF2[v8]); E->sideh_var_B = FUNC16(Sidehopper_Func_4); } uint16 Sidehopper_Func_2(uint16 r22, uint16 r24) { // 0xA3AB9D uint16 r18 = 0, r20 = 0; do { r18 += r24; r20 += *(uint16 *)((uint8 *)kCommonEnemySpeeds_Quadratic + (8 * r18) + 1); } while (sign16(r20 - r22)); return r18; } void Sidehopper_Func_3(void) { // 0xA3ABBB Enemy_Sidehopper *E = Get_Sidehopper(cur_enemy_index); E->base.current_instruction = E->sideh_var_00; E->base.instruction_timer = 1; E->base.timer = 0; } void Sidehopper_Main(void) { // 0xA3ABCF Enemy_Sidehopper *E = Get_Sidehopper(cur_enemy_index); CallSidehopperFunc(E->sideh_var_B | 0xA30000); } void Sidehopper_Func_4(uint16 k) { // 0xA3ABD6 uint16 v1 = g_off_A3AAE2[NextRandom() & 1]; Get_Sidehopper(k)->sideh_var_B = v1; } void Sidehopper_Func_5(void) { // 0xA3ABE6 Enemy_Sidehopper *E = Get_Sidehopper(cur_enemy_index); int v1 = E->sideh_var_05 >> 1; E->sideh_var_E = g_word_A3AAE6[v1]; E->sideh_var_D = g_word_A3AAEA[v1]; E->sideh_var_C = E->sideh_var_01; E->sideh_var_B = FUNC16(Sidehopper_Func_7); if (E->sideh_parameter_1) E->sideh_var_B = FUNC16(Sidehopper_Func_8); } void Sidehopper_Func_6(void) { // 0xA3AC13 Enemy_Sidehopper *E = Get_Sidehopper(cur_enemy_index); int v1 = E->sideh_var_05 >> 1; E->sideh_var_E = g_word_A3AAF2[v1]; E->sideh_var_D = g_word_A3AAF6[v1]; E->sideh_var_C = E->sideh_var_02; E->sideh_var_B = FUNC16(Sidehopper_Func_7); if (E->sideh_parameter_1) E->sideh_var_B = FUNC16(Sidehopper_Func_8); } void Sidehopper_Func_7(void) { // 0xA3AC40 Enemy_Sidehopper *E = Get_Sidehopper(cur_enemy_index); E->sideh_var_B = FUNC16(Sidehopper_Func_9); if ((GetSamusEnemyDelta_X(cur_enemy_index) & 0x8000) == 0) E->sideh_var_B = FUNC16(Sidehopper_Func_10); } void Sidehopper_Func_8(void) { // 0xA3AC56 Enemy_Sidehopper *E = Get_Sidehopper(cur_enemy_index); E->sideh_var_B = FUNC16(Sidehopper_Func_11); if ((GetSamusEnemyDelta_X(cur_enemy_index) & 0x8000) == 0) E->sideh_var_B = FUNC16(Sidehopper_Func_12); } void Sidehopper_Func_9(void) { // 0xA3AC6C Enemy_Sidehopper *E = Get_Sidehopper(cur_enemy_index); E->sideh_var_D = -E->sideh_var_D; E->sideh_var_00 = g_off_A3AAD2[E->sideh_var_06 >> 1]; Sidehopper_Func_3(); E->sideh_var_B = FUNC16(Sidehopper_Func_14); } void Sidehopper_Func_10(void) { // 0xA3AC8F Enemy_Sidehopper *E = Get_Sidehopper(cur_enemy_index); E->sideh_var_00 = g_off_A3AAD2[E->sideh_var_06 >> 1]; Sidehopper_Func_3(); E->sideh_var_B = FUNC16(Sidehopper_Func_15); } void Sidehopper_Func_11(void) { // 0xA3ACA8 Enemy_Sidehopper *E = Get_Sidehopper(cur_enemy_index); E->sideh_var_D = -E->sideh_var_D; E->sideh_var_00 = g_off_A3AADA[E->sideh_var_06 >> 1]; Sidehopper_Func_3(); E->sideh_var_B = FUNC16(Sidehopper_Func_16); } void Sidehopper_Func_12(void) { // 0xA3ACCB Enemy_Sidehopper *E = Get_Sidehopper(cur_enemy_index); E->sideh_var_00 = g_off_A3AADA[E->sideh_var_06 >> 1]; Sidehopper_Func_3(); E->sideh_var_B = FUNC16(Sidehopper_Func_17); } void Sidehopper_Func_13(void) { // 0xA3ACE4 Enemy_Sidehopper *E = Get_Sidehopper(cur_enemy_index); E->sideh_var_00 = g_off_A3AAC2[E->sideh_var_06 >> 1]; if (E->sideh_parameter_1) E->sideh_var_00 = g_off_A3AACA[E->sideh_var_06 >> 1]; Sidehopper_Func_3(); E->sideh_var_B = FUNC16(Sidehopper_Func_18); } void Sidehopper_Func_14(void) { // 0xA3AD0E if (Get_Sidehopper(cur_enemy_index)->sideh_var_03) Sidehopper_Func_20(); else Sidehopper_Func_19(); } void Sidehopper_Func_15(void) { // 0xA3AD20 if (Get_Sidehopper(cur_enemy_index)->sideh_var_03) Sidehopper_Func_20(); else Sidehopper_Func_19(); } void Sidehopper_Func_16(void) { // 0xA3AD32 if (Get_Sidehopper(cur_enemy_index)->sideh_var_03) Sidehopper_Func_22(); else Sidehopper_Func_21(); } void Sidehopper_Func_17(void) { // 0xA3AD44 if (Get_Sidehopper(cur_enemy_index)->sideh_var_03) Sidehopper_Func_22(); else Sidehopper_Func_21(); } void Sidehopper_Func_18(void) { // 0xA3AD56 Enemy_Sidehopper *E = Get_Sidehopper(cur_enemy_index); if (E->sideh_var_04) { E->sideh_var_04 = 0; E->sideh_var_B = FUNC16(Sidehopper_Func_4); } } static void CallSidehopperFunc(uint32 ea) { switch (ea) { case fnSidehopper_Func_4: Sidehopper_Func_4(cur_enemy_index); return; // 0xa3abd6 case fnSidehopper_Func_5: Sidehopper_Func_5(); return; // 0xa3abe6 case fnSidehopper_Func_6: Sidehopper_Func_6(); return; // 0xa3ac13 case fnSidehopper_Func_7: Sidehopper_Func_7(); return; // 0xa3ac40 case fnSidehopper_Func_8: Sidehopper_Func_8(); return; // 0xa3ac56 case fnSidehopper_Func_9: Sidehopper_Func_9(); return; // 0xa3ac6c case fnSidehopper_Func_10: Sidehopper_Func_10(); return; // 0xa3ac8f case fnSidehopper_Func_11: Sidehopper_Func_11(); return; // 0xa3aca8 case fnSidehopper_Func_12: Sidehopper_Func_12(); return; // 0xa3accb case fnSidehopper_Func_13: Sidehopper_Func_13(); return; // 0xa3ace4 case fnSidehopper_Func_14: Sidehopper_Func_14(); return; // 0xa3ad0e case fnSidehopper_Func_15: Sidehopper_Func_15(); return; // 0xa3ad20 case fnSidehopper_Func_16: Sidehopper_Func_16(); return; // 0xa3ad32 case fnSidehopper_Func_17: Sidehopper_Func_17(); return; // 0xa3ad44 case fnSidehopper_Func_18: Sidehopper_Func_18(); return; // 0xa3ad56 default: Unreachable(); } } void Sidehopper_Func_19(void) { // 0xA3AD6D Enemy_Sidehopper *E = Get_Sidehopper(cur_enemy_index); int v2 = (8 * E->sideh_var_C) >> 1; if (Enemy_MoveDown(cur_enemy_index, __PAIR32__(kCommonEnemySpeeds_Quadratic[v2 + 3], kCommonEnemySpeeds_Quadratic[v2 + 2]))) { E->sideh_var_D = -E->sideh_var_D; E->sideh_var_03 = 1; } else { if (Enemy_MoveRight_IgnoreSlopes(cur_enemy_index, INT16_SHL16(E->sideh_var_D))) { E->sideh_var_D = -E->sideh_var_D; E->sideh_var_03 = 1; } else { int16 v3 = E->sideh_var_C - E->sideh_var_E; E->sideh_var_C = v3; if (v3 < 0) { E->sideh_var_03 = 1; E->sideh_var_C = 0; } } } } void Sidehopper_Func_20(void) { // 0xA3ADD4 Enemy_Sidehopper *E = Get_Sidehopper(cur_enemy_index); int v2 = (8 * E->sideh_var_C) >> 1; if (Enemy_MoveDown(cur_enemy_index, __PAIR32__(kCommonEnemySpeeds_Quadratic[v2 + 1], kCommonEnemySpeeds_Quadratic[v2]))) { E->sideh_var_03 = 0; E->sideh_var_B = FUNC16(Sidehopper_Func_13); } else { if (Enemy_MoveRight_IgnoreSlopes(cur_enemy_index, INT16_SHL16(E->sideh_var_D))) E->sideh_var_D = -E->sideh_var_D; int16 v3 = E->sideh_var_E + E->sideh_var_C; if (!sign16(v3 - 64)) v3 = 64; E->sideh_var_C = v3; } } void Sidehopper_Func_21(void) { // 0xA3AE27 Enemy_Sidehopper *E = Get_Sidehopper(cur_enemy_index); int v2 = (8 * E->sideh_var_C) >> 1; if (Enemy_MoveDown(cur_enemy_index, __PAIR32__(kCommonEnemySpeeds_Quadratic[v2 + 1], kCommonEnemySpeeds_Quadratic[v2]))) { E->sideh_var_D = -E->sideh_var_D; E->sideh_var_03 = 1; } else { if (Enemy_MoveRight_IgnoreSlopes(cur_enemy_index, INT16_SHL16(E->sideh_var_D))) { E->sideh_var_D = -E->sideh_var_D; E->sideh_var_03 = 1; } else { int16 v3 = E->sideh_var_C - E->sideh_var_E; E->sideh_var_C = v3; if (v3 < 0) { E->sideh_var_03 = 1; E->sideh_var_C = 0; } } } } void Sidehopper_Func_22(void) { // 0xA3AE8E int16 v3; Enemy_Sidehopper *E = Get_Sidehopper(cur_enemy_index); int v2 = (8 * E->sideh_var_C) >> 1; if (Enemy_MoveDown(cur_enemy_index, __PAIR32__(kCommonEnemySpeeds_Quadratic[v2 + 3], kCommonEnemySpeeds_Quadratic[v2 + 2]))) { E->sideh_var_03 = 0; E->sideh_var_B = FUNC16(Sidehopper_Func_13); } else { if (Enemy_MoveRight_IgnoreSlopes(cur_enemy_index, INT16_SHL16(E->sideh_var_D))) E->sideh_var_D = -E->sideh_var_D; v3 = E->sideh_var_E + E->sideh_var_C; if (!sign16(v3 - 64)) v3 = 64; E->sideh_var_C = v3; } } const uint16 *MaridiaRefillCandy_Instr_1(uint16 k, const uint16 *jp) { // 0xA3B429 Get_MaridiaRefillCandy(cur_enemy_index)->mrcy_var_00 = 4; return jp; } const uint16 *MaridiaRefillCandy_Instr_2(uint16 k, const uint16 *jp) { // 0xA3B434 Get_MaridiaRefillCandy(cur_enemy_index)->mrcy_var_00 = 8; return jp; } const uint16 *MaridiaRefillCandy_Instr_3(uint16 k, const uint16 *jp) { // 0xA3B43F Get_MaridiaRefillCandy(cur_enemy_index)->mrcy_var_00 = 12; return jp; } void MaridiaRefillCandy_Init(void) { // 0xA3B44A Enemy_MaridiaRefillCandy *E = Get_MaridiaRefillCandy(cur_enemy_index); E->mrcy_parameter_1 = FUNC16(MaridiaRefillCandy_Func_1); E->mrcy_var_D = 0; E->mrcy_var_E = 0; E->mrcy_var_00 = 0; E->base.current_instruction = addr_kMaridiaRefillCandy_Ilist_B3C1; E->base.properties |= kEnemyProps_Invisible; E->mrcy_var_B = E->base.x_pos; E->mrcy_var_C = E->base.y_pos; } void CallMaridiaRefillCandyFunc(uint32 ea, uint16 k) { switch (ea) { case fnMaridiaRefillCandy_Func_1: MaridiaRefillCandy_Func_1(); return; case fnMaridiaRefillCandy_Func_2: MaridiaRefillCandy_Func_2(k); return; case fnMaridiaRefillCandy_Func_3: MaridiaRefillCandy_Func_3(k); return; default: Unreachable(); } } void MaridiaRefillCandy_Main(void) { // 0xA3B47C Enemy_MaridiaRefillCandy *E = Get_MaridiaRefillCandy(cur_enemy_index); CallMaridiaRefillCandyFunc(E->mrcy_parameter_1 | 0xA30000, cur_enemy_index); } void MaridiaRefillCandy_Func_1(void) { // 0xA3B482 int16 v1; if (IsSamusWithinEnemy_X(cur_enemy_index, 0x80)) { v1 = 1; if ((GetSamusEnemyDelta_X(cur_enemy_index) & 0x8000) == 0) v1 = 3; Enemy_MaridiaRefillCandy *E = Get_MaridiaRefillCandy(cur_enemy_index); E->mrcy_var_D = v1; MaridiaRefillCandy_Func_4(); E->mrcy_parameter_1 = FUNC16(MaridiaRefillCandy_Func_2); } } void MaridiaRefillCandy_Func_2(uint16 k) { // 0xA3B4A8 Enemy_MaridiaRefillCandy *E = Get_MaridiaRefillCandy(k); E->base.properties &= ~kEnemyProps_Invisible; if ((GetSamusEnemyDelta_Y(k) & 0x8000) != 0) { AddToHiLo(&E->base.y_pos, &E->base.y_subpos, -0x8000); } else { --E->mrcy_var_D; MaridiaRefillCandy_Func_4(); E->mrcy_var_F = 0; E->mrcy_parameter_1 = FUNC16(MaridiaRefillCandy_Func_3); } } void MaridiaRefillCandy_Func_3(uint16 k) { // 0xA3B4D6 Enemy_MaridiaRefillCandy *E = Get_MaridiaRefillCandy(k); int v2 = E->mrcy_var_00 >> 1; int32 v = __PAIR32__(g_word_A3B415[v2], g_word_A3B415[v2 + 1]); AddToHiLo(&E->base.x_pos, &E->base.x_subpos, E->mrcy_var_D ? v : -v); if (!CheckIfEnemyIsOnScreen()) { MaridiaRefillCandy_Func_4(); return; } E->base.properties |= kEnemyProps_Invisible; E->base.x_pos = E->mrcy_var_B; E->base.y_pos = E->mrcy_var_C; E->mrcy_var_D = 0; MaridiaRefillCandy_Func_4(); E->mrcy_parameter_1 = FUNC16(MaridiaRefillCandy_Func_1); } void MaridiaRefillCandy_Func_4(void) { // 0xA3B537 Enemy_MaridiaRefillCandy *E = Get_MaridiaRefillCandy(cur_enemy_index); uint16 mrcy_var_D = E->mrcy_var_D; if (mrcy_var_D != E->mrcy_var_E) { E->mrcy_var_E = mrcy_var_D; E->base.current_instruction = g_off_A3B40D[mrcy_var_D]; E->base.instruction_timer = 1; E->base.timer = 0; } } void MaridiaRefillCandy_Func_5(void) { // 0xA3B557 ; } void MaridiaRefillCandy_Func_6(void) { // 0xA3B55B ; } void NorfairSlowFireball_Init(void) { // 0xA3B66F EnemyData *v1 = gEnemyData(cur_enemy_index); v1->parameter_2 = 6; v1->current_instruction = g_off_A3B667[v1->properties & 3]; StoneZoomer_E67A(cur_enemy_index); } void NorfairSlowFireball_Func_1(void) { // 0xA3B6F9 uint16 current_instruction = gEnemyData(cur_enemy_index)->current_instruction; if (current_instruction) Unreachable(); } const uint16 *Bang_Instr_1(uint16 k, const uint16 *jp) { // 0xA3BA78 QueueSfx2_Max6(0x56); return jp; } const uint16 *Bang_Instr_2(uint16 k, const uint16 *jp) { // 0xA3BAA8 Get_Bang(cur_enemy_index)->bang_var_22 = 1; return jp; } void Bang_Init(void) { // 0xA3BAB3 Enemy_Bang *E = Get_Bang(cur_enemy_index); E->bang_var_B = E->base.palette_index; E->base.properties |= kEnemyProps_BlockPlasmaBeam; E->bang_var_F = FUNC16(Bang_Func_6); E->bang_var_00 = 16; E->bang_var_01 = 0; E->bang_var_02 = 0; E->bang_var_20 = 0; E->bang_var_21 = 0; E->bang_var_22 = 0; E->bang_var_0B = g_word_A3BA84[LOBYTE(E->bang_parameter_2)]; int v1 = 2 * HIBYTE(E->bang_parameter_2); uint16 v2 = g_word_A3BC6A[v1]; E->bang_var_0C = v2; E->bang_var_0D = v2; E->bang_var_0E = g_word_A3BC6A[v1 + 1]; if (!E->base.current_instruction) E->bang_var_F = FUNC16(Bang_Func_7); E->base.current_instruction = addr_kBang_Ilist_B75E; } void Bang_Main(void) { // 0xA3BB25 Enemy_Bang *E = Get_Bang(cur_enemy_index); Call(E->bang_parameter_1 | 0xA30000); } void Bang_Func_1(void) { // 0xA3BB2B uint16 v0 = Get_Bang(cur_enemy_index + 64)->bang_var_20 + 10; Get_Bang(cur_enemy_index)->bang_var_20 = v0; Bang_Func_18(); Enemy_Bang *E = Get_Bang(cur_enemy_index); E->base.properties |= kEnemyProps_Tangible; } void Bang_Func_2(void) { // 0xA3BB4A uint16 v0 = Get_Bang(cur_enemy_index + 1984)->bang_var_00 + 20; Enemy_Bang *E = Get_Bang(cur_enemy_index); E->bang_var_20 = v0; Bang_Func_18(); E->base.properties |= kEnemyProps_Tangible; } void Bang_Func_3(void) { // 0xA3BB66 int16 bang_var_B; Bang_Func_5(); Enemy_Bang *E0 = Get_Bang(cur_enemy_index); uint16 x_pos = E0->base.x_pos; int v3 = cur_enemy_index >> 1; enemy_drawing_queue[v3 + 91] = x_pos; Enemy_Bang *E1 = Get_Bang(cur_enemy_index + 64); E1->base.x_pos = x_pos; uint16 y_pos = E0->base.y_pos; enemy_drawing_queue[v3 + 93] = y_pos; E1->base.y_pos = y_pos; bang_var_B = E0->bang_var_B; if ((E0->bang_var_20 & 1) != 0) bang_var_B = 3072; E0->base.palette_index = bang_var_B; Bang_Func_18(); if (E0->bang_var_22) { E0->bang_var_22 = 0; if (E0->bang_var_20 == 9) { E0->base.invincibility_timer = 16; E0->base.properties |= kEnemyProps_Tangible; uint16 v7 = DetermineDirectionOfSamusFromEnemy(); uint16 v8 = Bang_Func_4(v7); EnemyDeathAnimation(cur_enemy_index, v8); uint16 v9 = cur_enemy_index; Enemy_Bang *E = Get_Bang(cur_enemy_index + 64); E->base.properties |= 0x200; enemy_drawing_queue[(v9 >> 1) + 97] |= 0x200; } else { ++E0->bang_var_20; Bang_Func_18(); } } } uint16 Bang_Func_4(uint16 a) { // 0xA3BBEB int i; if (!sign16(projectile_counter - 5)) return 1; for (i = 0; projectile_damage[i >> 1]; i += 2) ; Enemy_Bang *E = Get_Bang(cur_enemy_index); int v3 = i >> 1; projectile_x_pos[v3] = E->base.x_pos; projectile_y_pos[v3] = E->base.y_pos; projectile_dir[v3] = a; projectile_type[v3] = equipped_beams & 0xF | 0x10; ++projectile_counter; ProjectileReflection(i); projectile_damage[v3] = E->bang_var_E; QueueSfx1_Max6(g_word_A3BC4A[projectile_type[v3] & 0xF]); return 0; } void Bang_Func_5(void) { // 0xA3BC9E Enemy_Bang *E = Get_Bang(cur_enemy_index); CallEnemyPreInstr(E->bang_var_F | 0xA30000); } void Bang_Func_6(uint16 k) { // 0xA3BCA5 Enemy_Bang *E = Get_Bang(cur_enemy_index); uint16 v1 = E->bang_var_00 - 1; E->bang_var_00 = v1; if (!v1) { E->bang_var_00 = 16; E->bang_var_F = FUNC16(Bang_Func_8); } } void Bang_Func_7(uint16 k) { // 0xA3BCC1 } void Bang_Func_8(uint16 k) { // 0xA3BCC5 uint8 v1 = CalculateAngleOfSamusFromEnemy(cur_enemy_index) - 64; Enemy_Bang *E = Get_Bang(cur_enemy_index); E->bang_var_01 = v1; E->bang_var_F = FUNC16(Bang_Func_10); E->bang_var_07 = 0; E->bang_var_08 = 0; E->bang_var_09 = 0; E->bang_var_0A = 0; } void Bang_Func_9(void) { // 0xA3BCF1 uint8 v1 = CalculateAngleOfSamusFromEnemy(cur_enemy_index) - 64; Enemy_Bang *E = Get_Bang(cur_enemy_index); E->bang_var_02 = v1; uint16 v3 = SignExtend8(v1 - E->bang_var_01); uint16 v4 = Abs16(v3); if (!sign16(v4 - 48)) E->bang_var_F = FUNC16(Bang_Func_11); } void Bang_Func_10(uint16 k) { // 0xA3BD1C Bang_Func_14(); Bang_Func_15(); Bang_Func_12(); Bang_Func_9(); } void Bang_Func_11(uint16 k) { // 0xA3BD2C Bang_Func_14(); Bang_Func_15(); Bang_Func_13(); Enemy_Bang *E = Get_Bang(cur_enemy_index); if (E->bang_var_0A || (int16)E->bang_var_09 <= 0) E->bang_var_F = FUNC16(Bang_Func_6); } void Bang_Func_12(void) { // 0xA3BD4F Enemy_Bang *E = Get_Bang(cur_enemy_index); int16 v1 = E->bang_var_0C - 1; E->bang_var_0C = v1; if (v1 < 0) { E->bang_var_0C = E->bang_var_0D; if ((int16)(E->bang_var_0A - E->bang_var_0B) < 0) { E->bang_var_09 += 22; E->bang_var_0A += E->bang_var_09; } } } void Bang_Func_13(void) { // 0xA3BD89 Enemy_Bang *E = Get_Bang(cur_enemy_index); int16 v1 = E->bang_var_0C - 1; E->bang_var_0C = v1; if (v1 < 0) { E->bang_var_0C = E->bang_var_0E; E->bang_var_09 -= 22; E->bang_var_0A -= E->bang_var_09; } } void Bang_Func_14(void) { // 0xA3BDB9 Enemy_Bang *E = Get_Bang(cur_enemy_index); uint16 r18 = kSine16bit[(uint8)(E->bang_var_01 + 64)]; if ((r18 & 0x8000) != 0) E->bang_var_07 = 1; uint32 t = ((uint16)Abs16(r18) >> 8) * E->bang_var_0A; if (E->bang_var_07) t = -(int32)t; t = t + E->base.x_subpos; E->base.x_subpos = t, E->base.x_pos = t >> 16; } void Bang_Func_15(void) { // 0xA3BE1C Enemy_Bang *E = Get_Bang(cur_enemy_index); uint16 r18 = kSine16bit[(uint8)E->bang_var_01]; if ((r18 & 0x8000) != 0) E->bang_var_08 = 1; uint32 t = ((uint16)Abs16(r18) >> 8) * E->bang_var_0A; if (E->bang_var_08) t = -(int32)t; t = t + E->base.y_subpos; E->base.y_subpos = t, E->base.y_pos = t >> 16; } void Bang_Func_18(void) { // 0xA3BEDA Enemy_Bang *E = Get_Bang(cur_enemy_index); uint16 bang_var_20 = E->bang_var_20; if (bang_var_20 != E->bang_var_21) { E->bang_var_21 = bang_var_20; E->base.current_instruction = g_off_A3B722[bang_var_20]; E->base.instruction_timer = 1; E->base.timer = 0; } } void Bang_Shot(void) { // 0xA3BEFD Enemy_Bang *E = Get_Bang(cur_enemy_index); if (E->bang_var_F != 0xBCC1) { E->bang_var_01 = g_word_A3BA94[projectile_dir[collision_detection_index] & 0xF]; E->bang_var_F = FUNC16(Bang_Func_11); E->bang_var_07 = 0; E->bang_var_08 = 0; E->bang_var_09 = 256; E->bang_var_0A = 1536; } if (E->bang_var_20 != 9) { ++E->bang_var_20; Bang_Func_18(); int v1 = collision_detection_index; E->bang_var_E += projectile_damage[v1]; projectile_dir[v1] |= 0x10; if (E->bang_var_20 == 9) E->bang_var_D = 1; } } const uint16 *Skree_Instr_1(uint16 k, const uint16 *jp) { // 0xA3C6A4 Get_Skree(cur_enemy_index)->skree_var_E = 1; return jp; } void Skree_Init(void) { // 0xA3C6AE Enemy_Skree *E = Get_Skree(cur_enemy_index); E->skree_var_C = 0; E->skree_var_D = 0; E->skree_var_E = 0; E->base.current_instruction = addr_kSkree_Ilist_C65E; E->skree_var_B = FUNC16(Skree_Func_1); } void CallSkreeFunc(uint32 ea) { switch (ea) { case fnSkree_Func_1: Skree_Func_1(); return; case fnSkree_Func_2: Skree_Func_2(cur_enemy_index); return; case fnSkree_Func_3: Skree_Func_3(); return; case fnSkree_Func_4: Skree_Func_4(); return; default: Unreachable(); } } void Skree_Main(void) { // 0xA3C6C7 Enemy_Skree *E = Get_Skree(cur_enemy_index); CallSkreeFunc(E->skree_var_B | 0xA30000); } void Skree_Func_1(void) { // 0xA3C6D5 Enemy_Skree *E = Get_Skree(cur_enemy_index); if (abs16(E->base.x_pos - samus_x_pos) < 0x30) { ++E->skree_var_C; Skree_Func_5(); E->skree_var_B = FUNC16(Skree_Func_2); } } void Skree_Func_2(uint16 k) { // 0xA3C6F7 Enemy_Skree *E = Get_Skree(k); if (E->skree_var_E) { E->skree_var_E = 0; ++E->skree_var_C; Skree_Func_5(); E->skree_var_B = FUNC16(Skree_Func_3); QueueSfx2_Max6(0x5B); } } void Skree_Func_3(void) { // 0xA3C716 Enemy_Skree *E = Get_Skree(cur_enemy_index); E->skree_var_A = 21; uint16 v1 = E->base.properties | 3; E->base.properties = v1; if (EnemyFunc_BF8A(cur_enemy_index, v1, INT16_SHL16(6)) & 1) { E->base.instruction_timer = 1; E->base.timer = 0; E->skree_var_B = FUNC16(Skree_Func_4); QueueSfx2_Max6(0x5C); } else { E->base.y_pos += 6; E->base.x_pos += ((int16)(E->base.x_pos - samus_x_pos) >= 0) ? -1 : 1; } } void Skree_Func_4(void) { // 0xA3C77F Enemy_Skree *E = Get_Skree(cur_enemy_index); if (E->skree_var_A-- == 1) { gEnemySpawnData(cur_enemy_index)->vram_tiles_index = E->base.vram_tiles_index | E->base.palette_index; E->base.palette_index = 2560; E->base.vram_tiles_index = 0; E->base.properties |= kEnemyProps_Deleted; } else { if (E->skree_var_A == 8) { uint16 v2 = cur_enemy_index; SpawnEprojWithGfx(8, cur_enemy_index, addr_stru_868BC2); SpawnEprojWithGfx(0, v2, addr_stru_868BD0); SpawnEprojWithGfx(0, v2, addr_stru_868BDE); SpawnEprojWithGfx(0, v2, addr_stru_868BEC); } ++E->base.y_pos; } } void Skree_Func_5(void) { // 0xA3C7D5 Enemy_Skree *E = Get_Skree(cur_enemy_index); uint16 skree_var_C = E->skree_var_C; if (skree_var_C != E->skree_var_D) { E->skree_var_D = skree_var_C; E->base.current_instruction = g_off_A3C69C[skree_var_C]; E->base.instruction_timer = 1; E->base.timer = 0; } } void Skree_Shot(void) { // 0xA3C7F5 Enemy_NormalShotAI_SkipSomeParts_A3(); Enemy_Skree *E = Get_Skree(cur_enemy_index); if (!E->base.health) { uint16 v1 = cur_enemy_index; SpawnEprojWithGfx(E->skree_var_A, cur_enemy_index, addr_stru_868BC2); SpawnEprojWithGfx(0, v1, addr_stru_868BD0); SpawnEprojWithGfx(0, v1, addr_stru_868BDE); SpawnEprojWithGfx(0, v1, addr_stru_868BEC); uint16 v5 = 2; if ((projectile_type[collision_detection_index] & 0xF00) != 512) v5 = 0; EnemyDeathAnimation(2 * collision_detection_index, v5); } } const uint16 *MaridiaSnail_Instr_1(uint16 k, const uint16 *jp) { // 0xA3CC36 Get_MaridiaSnail(k)->msl_var_F = *jp; return jp + 1; } const uint16 *MaridiaSnail_Instr_2(uint16 k, const uint16 *jp) { // 0xA3CC3F Get_MaridiaSnail(k)->msl_var_D = *jp; return jp + 1; } const uint16 *MaridiaSnail_Instr_4(uint16 k, const uint16 *jp) { // 0xA3CC48 Enemy_MaridiaSnail *E = Get_MaridiaSnail(k); E->msl_var_07 = jp[0]; E->msl_var_C = *(uint16 *)((uint8 *)&g_stru_A3CD42[0].field_6 + 8 * E->msl_var_07); return jp + 1; } const uint16 *MaridiaSnail_Instr_3(uint16 k, const uint16 *jp) { // 0xA3CC5F Enemy_MaridiaSnail *E = Get_MaridiaSnail(k); E->base.x_pos += jp[0]; E->base.y_pos += jp[1]; return jp + 2; } const uint16 *MaridiaSnail_Instr_5(uint16 k, const uint16 *jp) { // 0xA3CC78 if (Get_MaridiaSnail(k)->msl_var_08 == 2 || (NextRandom() & 1) != 0) jp -= 3; return jp; } void MaridiaSnail_Func_1(uint16 k) { // 0xA3CC92 MaridiaSnail_Func_17(k); } void MaridiaSnail_Init(void) { // 0xA3CDE2 Enemy_MaridiaSnail *E = Get_MaridiaSnail(cur_enemy_index); E->msl_var_F = FUNC16(nullsub_215); E->base.spritemap_pointer = addr_kSpritemap_Nothing_A3; E->base.instruction_timer = 1; uint16 current_instruction = E->base.current_instruction; E->base.current_instruction = g_stru_A3CD42[current_instruction].field_0; E->base.properties |= g_stru_A3CD42[current_instruction].field_2; E->msl_var_D = g_stru_A3CD42[current_instruction].field_4; E->msl_var_C = g_stru_A3CD42[current_instruction].field_6; E->msl_var_08 = 0; E->msl_var_06 = E->msl_parameter_1; MaridiaSnail_Func_2(cur_enemy_index, current_instruction * 8); } void MaridiaSnail_Func_2(uint16 k, uint16 j) { // 0xA3CE27 int v2 = j >> 1; uint16 r18 = g_word_A3CD82[v2]; uint16 r20 = g_word_A3CD82[v2 + 1]; uint16 r22 = g_word_A3CD82[v2 + 2]; uint16 r24 = g_word_A3CD82[v2 + 3]; Enemy_MaridiaSnail *E = Get_MaridiaSnail(k); E->msl_var_A = r20 + (r18 ^ g_word_A3CCA2[E->msl_parameter_1]); E->msl_var_B = r24 + (r22 ^ g_word_A3CCA2[E->msl_parameter_1]); } void MaridiaSnail_Func_3(uint16 k) { // 0xA3CE57 Enemy_MaridiaSnail *E = Get_MaridiaSnail(k); E->msl_var_F = g_off_A3CDD2[E->msl_var_07]; } void MaridiaSnail_Main(void) { // 0xA3CE64 MaridiaSnail_Func_4(cur_enemy_index); MaridiaSnail_Func_5(cur_enemy_index); MaridiaSnail_Func_6(cur_enemy_index); Enemy_MaridiaSnail *E = Get_MaridiaSnail(cur_enemy_index); CallEnemyPreInstr(E->msl_var_F | 0xA30000); } void MaridiaSnail_Func_4(uint16 k) { // 0xA3CE73 uint16 msl_var_08 = Get_MaridiaSnail(k)->msl_var_08; if (msl_var_08 != 3 && msl_var_08 != 4 && msl_var_08 != 5 && earthquake_timer == 30 && earthquake_type == 20) MaridiaSnail_Func_14(k); } void MaridiaSnail_Func_5(uint16 k) { // 0xA3CE9A Enemy_MaridiaSnail *E = Get_MaridiaSnail(k); uint16 msl_var_08 = E->msl_var_08; if (msl_var_08 != 1 && msl_var_08 != 3 && msl_var_08 != 4 && msl_var_08 != 5) { if (!sign16(E->base.y_pos - samus_y_pos + 96)) { if ((int16)(E->base.x_pos - samus_x_pos) < 0) { if (samus_pose_x_dir != 4) goto LABEL_14; } else if (samus_pose_x_dir != 8) { goto LABEL_14; } if (E->msl_var_08 == 2) return; if (E->msl_var_D != FUNC16(nullsub_215)) { E->base.current_instruction = E->msl_var_D; E->base.spritemap_pointer = addr_kSpritemap_Nothing_A3; E->base.instruction_timer = 1; E->base.timer = 0; E->msl_var_08 = 2; return; } } LABEL_14: E->msl_var_08 = 0; } } void MaridiaSnail_Func_6(uint16 k) { // 0xA3CF11 Enemy_MaridiaSnail *E = Get_MaridiaSnail(k); if (E->msl_var_F == FUNC16(MaridiaSnail_Func_15)) goto LABEL_11; if (E->msl_var_08 == 1) { if (samus_has_momentum_flag || E->msl_var_F != FUNC16(nullsub_215)) goto LABEL_11; LABEL_10: E->base.properties |= 0x8000; return; } if (!samus_has_momentum_flag) { uint16 msl_var_08 = E->msl_var_08; if (msl_var_08 == 2 || msl_var_08 != 3 && msl_var_08 != 5) goto LABEL_10; } LABEL_11: E->base.properties &= 0x7FFF; } static uint32 Shift8AddMagn(int16 a, int s) { int32 r = (a << 8); r += (r < 0) ? -(s << 16) : (s << 16); return r; } void MaridiaSnail_Func_7(uint16 k) { // 0xA3CF60 Enemy_MaridiaSnail *E = Get_MaridiaSnail(k); if (E->msl_var_07 >= 4) { if (EnemyFunc_BC76(k, Shift8AddMagn(E->msl_var_B, 7))) return; } else { if (EnemyFunc_BBBF(k, Shift8AddMagn(E->msl_var_A, 7))) return; } MaridiaSnail_Func_14(k); } void MaridiaSnail_Func_9(uint16 k) { // 0xA3CFA6 uint16 v1 = Get_MaridiaSnail(k)->msl_var_05 ? addr_stru_A3CD22 : addr_stru_A3CCE2; MaridiaSnail_D07E(k, RomPtr_A3(v1)); } void MaridiaSnail_CFB7(uint16 k) { // 0xA3CFB7 MaridiaSnail_D002(k, RomPtr_A3(addr_stru_A3CCEA)); } void MaridiaSnail_CFBD(uint16 k) { // 0xA3CFBD uint16 v1 = Get_MaridiaSnail(k)->msl_var_05 ? addr_stru_A3CD2A : addr_stru_A3CCF2; MaridiaSnail_D07E(k, RomPtr_A3(v1)); } void MaridiaSnail_CFCE(uint16 k) { // 0xA3CFCE MaridiaSnail_D002(k, RomPtr_A3(addr_stru_A3CCFA)); } void MaridiaSnail_CFD4(uint16 k) { // 0xA3CFD4 uint16 v1 = Get_MaridiaSnail(k)->msl_var_05 ? addr_stru_A3CD32 : addr_stru_A3CD02; MaridiaSnail_D07E(k, RomPtr_A3(v1)); } void MaridiaSnail_CFE5(uint16 k) { // 0xA3CFE5 MaridiaSnail_D002(k, RomPtr_A3(addr_stru_A3CD0A)); } void MaridiaSnail_CFEB(uint16 k) { // 0xA3CFEB uint16 v1; if (Get_MaridiaSnail(k)->msl_var_05) v1 = addr_stru_A3CD3A; else v1 = addr_stru_A3CD12; MaridiaSnail_D07E(k, RomPtr_A3(v1)); } void MaridiaSnail_CFFC(uint16 k) { // 0xA3CFFC MaridiaSnail_D002(k, RomPtr_A3(addr_stru_A3CD1A)); } void MaridiaSnail_D002(uint16 k, const uint8 *j) { // 0xA3D002 MaridiaSnail_Func_10(k, j); Enemy_MaridiaSnail *E = Get_MaridiaSnail(k); uint8 rv = Enemy_MoveRight_ProcessSlopes(k, Shift8AddMagn(E->msl_var_A, 1)); MaridiaSnail_Func_11(k, j); if (rv) { E->msl_var_E = 0; uint8 carry = EnemyFunc_C8AD(k); MaridiaSnail_Func_12(k, carry); if (Enemy_MoveDown(k, INT16_SHL8(E->msl_var_B))) { E->msl_var_A = -E->msl_var_A; MaridiaSnail_Func_13(k, GET_WORD(j + 6)); } } else { uint16 v7 = E->msl_var_E + 1; E->msl_var_E = v7; if (sign16(v7 - 4)) { E->msl_var_B = -E->msl_var_B; MaridiaSnail_Func_13(k, GET_WORD(j + 4)); } else { MaridiaSnail_Func_14(k); } } } void MaridiaSnail_D07E(uint16 k, const uint8 *j) { // 0xA3D07E MaridiaSnail_Func_10(k, j); Enemy_MaridiaSnail *E = Get_MaridiaSnail(k); uint8 rv = Enemy_MoveDown(k, Shift8AddMagn(E->msl_var_B, 1)); MaridiaSnail_Func_11(k, j); if (rv) { E->msl_var_E = 0; if (Enemy_MoveRight_ProcessSlopes(k, INT16_SHL8(E->msl_var_A))) { E->msl_var_B = -E->msl_var_B; MaridiaSnail_Func_13(k, GET_WORD(j + 6)); } else { uint8 carry = EnemyFunc_C8AD(k); MaridiaSnail_Func_12(k, carry); } } else { uint16 v7 = E->msl_var_E + 1; E->msl_var_E = v7; if (sign16(v7 - 4)) { E->msl_var_A = -E->msl_var_A; MaridiaSnail_Func_13(k, GET_WORD(j + 4)); } else { MaridiaSnail_Func_14(k); } } } void MaridiaSnail_Func_10(uint16 k, const uint8 *j) { // 0xA3D0F8 Enemy_MaridiaSnail *E = Get_MaridiaSnail(k); E->base.x_pos += GET_WORD(j); E->base.y_pos += GET_WORD(j + 2); } void MaridiaSnail_Func_11(uint16 k, const uint8 *j) { // 0xA3D10D Enemy_MaridiaSnail *E = Get_MaridiaSnail(k); E->base.x_pos -= GET_WORD(j); E->base.y_pos -= GET_WORD(j + 2); } void MaridiaSnail_Func_12(uint16 k, uint16 carry) { // 0xA3D124 Enemy_MaridiaSnail *E = Get_MaridiaSnail(k); if (!carry) { if ((uint16)(E->msl_var_04 + 1) >= 0x10) E->msl_var_05 = 0; else ++E->msl_var_04; } else { E->msl_var_05 = 1; E->msl_var_04 = 0; } } void MaridiaSnail_Func_13(uint16 k, uint16 a) { // 0xA3D14C Enemy_MaridiaSnail *E = Get_MaridiaSnail(k); E->base.current_instruction = a; E->base.instruction_timer = 1; E->msl_var_05 = 1; E->msl_var_04 = 0; } void MaridiaSnail_Func_14(uint16 k) { // 0xA3D164 Enemy_MaridiaSnail *E = Get_MaridiaSnail(k); if (E->msl_var_08 != 3) { E->msl_var_08 = 3; E->msl_var_F = FUNC16(MaridiaSnail_Func_15); int v2 = 2 * E->msl_var_C; E->base.current_instruction = g_off_A3D1AB[v2]; E->msl_var_D = g_off_A3D1AB[v2 + 1]; E->base.instruction_timer = 1; E->base.timer = 0; E->msl_var_02 = 0; E->msl_var_03 = 0; E->msl_var_00 = 0; E->msl_var_01 = 0; } } void MaridiaSnail_Func_15(uint16 k) { // 0xA3D1B3 Enemy_MaridiaSnail *E = Get_MaridiaSnail(k); if (E->msl_var_08 != 3) { if (Enemy_MoveRight_IgnoreSlopes(k, __PAIR32__(E->msl_var_03, E->msl_var_02))) { E->msl_var_02 = -E->msl_var_02; E->msl_var_03 = -E->msl_var_03; E->msl_var_20 = 1; QueueSfx2_Max3(0x70); } else { uint32 delta; if ((E->msl_var_03 & 0x8000) != 0) delta = 4096; else delta = -4096; uint32 t = __PAIR32__(E->msl_var_03, E->msl_var_02) + delta; E->msl_var_02 = t; if (t >> 16) E->msl_var_03 = (t >> 16); } } if (Enemy_MoveDown(k, __PAIR32__(E->msl_var_01, E->msl_var_00))) { int16 msl_var_01 = E->msl_var_01; if (msl_var_01 >= 0 && sign16(msl_var_01 - 3)) { E->msl_var_03 = 0; E->msl_var_02 = 0; E->msl_var_01 = 0; E->msl_var_00 = 0; E->msl_var_E = 0; E->msl_var_04 = 0; E->msl_var_05 = 1; if (E->msl_var_08 == 3) { E->msl_var_08 = 0; } else { E->msl_var_08 = 1; E->msl_parameter_1 = 8; MaridiaSnail_Func_18(k); MaridiaSnail_Func_16(k); } E->base.properties = E->msl_var_C | E->base.properties & ~3; StoneZoomer_E67A(k); E->msl_var_F = FUNC16(nullsub_215); E->base.current_instruction = E->msl_var_D; E->base.instruction_timer = 1; E->base.timer = 0; } else { E->msl_var_00 = -E->msl_var_00; E->msl_var_01 = -E->msl_var_01; E->msl_var_20 = 0; } } else { uint32 t = __PAIR32__(E->msl_var_01, E->msl_var_00) + 0x2000; E->msl_var_00 = t; if (sign16((t >> 16) - 4)) E->msl_var_01 = (t >> 16); } } void MaridiaSnail_Func_16(uint16 k) { // 0xA3D2FA Enemy_MaridiaSnail *E = Get_MaridiaSnail(k); int v2 = (uint16)(4 * E->msl_var_C) >> 1; E->base.current_instruction = g_off_A3D30D[v2]; E->msl_var_D = g_off_A3D30D[v2 + 1]; } uint8 MaridiaSnail_Func_17(uint16 k) { // 0xA3D315 Enemy_MaridiaSnail *E = Get_MaridiaSnail(k); if (E->msl_var_05) return 0; if (E->msl_var_07 >= 4) return MaridiaSnail_Func_18(k) & 1; if ((E->msl_var_07 & 1) != 0) { return (E->base.y_pos >= samus_y_pos) ? MaridiaSnail_Func_19(k) : 0; } else { return (E->base.y_pos < samus_y_pos) ? MaridiaSnail_Func_19(k) : 0; } } uint8 MaridiaSnail_Func_18(uint16 k) { // 0xA3D33E Enemy_MaridiaSnail *E = Get_MaridiaSnail(k); if (E->msl_var_C) { return (E->base.x_pos >= samus_x_pos) ? MaridiaSnail_Func_19(k) : 0; } else { return (E->base.x_pos < samus_x_pos) ? MaridiaSnail_Func_19(k) : 0; } } uint8 MaridiaSnail_Func_19(uint16 k) { // 0xA3D356 Enemy_MaridiaSnail *E = Get_MaridiaSnail(k); if (E->msl_var_08 == 2 || E->msl_var_F == 0xCF5F) return 0; uint16 v2 = g_word_A3CDC2[E->msl_var_07]; E->msl_var_07 = v2; E->base.current_instruction = *(VoidP *)((uint8 *)&g_stru_A3CD42[0].field_0 + (8 * v2)); E->base.properties = *(uint16 *)((uint8 *)&g_stru_A3CD42[0].field_2 + (8 * v2)) | E->base.properties & ~3; E->msl_var_D = *(VoidP *)((uint8 *)&g_stru_A3CD42[0].field_4 + (8 * v2)); E->msl_var_C = *(uint16 *)((uint8 *)&g_stru_A3CD42[0].field_6 + (8 * v2)); MaridiaSnail_Func_2(k, 8 * v2); MaridiaSnail_Func_3(k); E->msl_var_05 = 1; E->msl_var_04 = 0; return 1; } void MaridiaSnail_Touch(void) { // 0xA3D3B0 Enemy_MaridiaSnail *E = Get_MaridiaSnail(cur_enemy_index); if ((E->msl_var_08 != 1 || E->msl_var_F == 0xCF5F || !(MaridiaSnail_Func_20(cur_enemy_index) & 1)) && (E->msl_var_F == 0xD1B3 || samus_has_momentum_flag)) { MaridiaSnail_Func_22(cur_enemy_index); if (E->msl_var_F == 0xD1B3) QueueSfx2_Max3(0x70); } else if (E->msl_var_F != 0xCF5F && E->msl_var_08 != 4 && E->msl_var_08 != 3) { Enemy_NormalTouchAI_A3(); E->msl_parameter_1 = E->msl_var_06; if (E->msl_var_08) MaridiaSnail_Func_19(cur_enemy_index); E->msl_var_08 = 0; } } uint8 MaridiaSnail_Func_20(uint16 k) { // 0xA3D421 uint16 r20 = Get_MaridiaSnail(k)->msl_var_C & 1; if ((uint16)(joypad1_lastkeys & 0x300) >> 8 == 1) { if (r20) return 0; } else if (!r20) { return 0; } return 1; } uint8 MaridiaSnail_Func_21(uint16 k) { // 0xA3D446 if ((Get_MaridiaSnail(k)->msl_var_A & 0x8000) != 0) return samus_pose_x_dir == 8; return samus_pose_x_dir == 4; } void MaridiaSnail_Shot(void) { // 0xA3D469 uint16 v0 = projectile_type[collision_detection_index] & 0xFF00; if (v0 == 768 || v0 == 1280) { Enemy_NormalShotAI_A3(); } else { uint16 msl_var_08 = Get_MaridiaSnail(cur_enemy_index)->msl_var_08; if (msl_var_08 != 3 && msl_var_08 != 4) MaridiaSnail_Func_23(cur_enemy_index); QueueSfx2_Max3(0x70); } } void MaridiaSnail_Func_22(uint16 k) { // 0xA3D49F Enemy_MaridiaSnail *E = Get_MaridiaSnail(k); E->msl_var_08 = 4; E->msl_var_F = FUNC16(MaridiaSnail_Func_15); int v2 = (uint16)(4 * E->msl_var_C) >> 1; E->base.current_instruction = g_off_A3D50F[v2]; E->msl_var_D = g_off_A3D50F[v2 + 1]; E->base.instruction_timer = 1; E->base.timer = 0; E->msl_var_02 = absolute_moved_last_frame_x_fract; uint16 v3 = absolute_moved_last_frame_x; E->msl_var_03 = absolute_moved_last_frame_x; if (v3 >= 0x10) v3 = 15; int v4 = (uint16)(4 * v3) >> 1; E->msl_var_00 = g_word_A3D517[v4]; E->msl_var_01 = g_word_A3D517[v4 + 1]; if ((samus_pose_x_dir & 4) != 0) { E->msl_var_02 = -E->msl_var_02; E->msl_var_03 = -E->msl_var_03; } } void MaridiaSnail_Func_23(uint16 k) { // 0xA3D557 Enemy_MaridiaSnail *E = Get_MaridiaSnail(k); E->msl_var_08 = 5; E->msl_var_F = FUNC16(MaridiaSnail_Func_15); int v2 = (uint16)(4 * E->msl_var_C) >> 1; E->base.current_instruction = g_off_A3D5A4[v2]; E->msl_var_D = g_off_A3D5A4[v2 + 1]; E->base.instruction_timer = 1; E->base.timer = 0; E->msl_var_01 = -1; E->msl_var_03 = (samus_pose_x_dir == 4) ? -1 : 1; } void Reflec_Func_1(void) { // 0xA3DB0C if (!door_transition_flag_enemies && !--variables_for_enemy_graphics_drawn_hook[2]) { variables_for_enemy_graphics_drawn_hook[2] = 16; uint16 v0 = variables_for_enemy_graphics_drawn_hook[0]; uint16 v1 = 8 * variables_for_enemy_graphics_drawn_hook[1]; int n = 4; do { palette_buffer[(v0 >> 1) + 137] = g_word_A3DABC[v1 >> 1]; v1 += 2; v0 += 2; } while (--n); variables_for_enemy_graphics_drawn_hook[1] = (LOBYTE(variables_for_enemy_graphics_drawn_hook[1]) + 1) & 7; } } const uint16 *Reflec_Instr_1(uint16 k, const uint16 *jp) { // 0xA3DBC8 Get_Reflec(k)->reflec_parameter_2 = jp[0]; return jp + 1; } void Reflec_Init(void) { // 0xA3DBD3 Enemy_Reflec *E = Get_Reflec(cur_enemy_index); E->base.properties |= kEnemyProps_BlockPlasmaBeam; E->base.current_instruction = g_off_A3DC0B[E->reflec_parameter_1]; enemy_gfx_drawn_hook.addr = FUNC16(Reflec_Func_1); *(uint16 *)&enemy_gfx_drawn_hook.bank = 163; variables_for_enemy_graphics_drawn_hook[0] = ((16 * E->base.palette_index) & 0xFF00) >> 8; variables_for_enemy_graphics_drawn_hook[2] = 16; } void Reflec_Shot(void) { uint16 v0 = 2 * collision_detection_index; Enemy_Reflec *EK = Get_Reflec(cur_enemy_index); EK->base.invincibility_timer = 10; uint16 v2 = 32 * EK->reflec_parameter_2 + 2 * (projectile_dir[v0 >> 1] & 0xF); uint16 varE32 = v2; int v3 = v2 >> 1; if (g_word_A3DCAE[v3] == 0x8000) { projectile_dir[v0 >> 1] |= 0x10; printf("Possible bug. What is X?\n"); Enemy_Reflec *ET = Get_Reflec(v2); if (ET->base.health) { Enemy_NormalShotAI_SkipSomeParts_A3(); if (!ET->base.health) { ET->base.current_instruction = g_off_A3DCA6[ET->reflec_parameter_2]; ET->base.instruction_timer = 1; ET->base.timer = 0; } } } else { int16 v4 = g_word_A3DCAE[v3]; if (v4 < 0) v4 = -g_word_A3DCAE[varE32 >> 1]; int v5 = v0 >> 1; projectile_dir[v5] = v4; projectile_type[v5] &= ~0x8000; ProjectileReflection(v0); QueueSfx2_Max6(0x57); } } const uint16 *WreckedShipOrangeZoomer_Func_1(uint16 k, const uint16 *jp) { // 0xA3DFC2 Get_WreckedShipOrangeZoomer(k)->wsozr_var_F = jp[0]; return jp + 1; } void WreckedShipOrangeZoomer_Init(void) { // 0xA3E043 Enemy_WreckedShipOrangeZoomer *E = Get_WreckedShipOrangeZoomer(cur_enemy_index); E->base.current_instruction = g_off_A3E03B[E->base.current_instruction & 3]; E->wsozr_var_F = addr_locret_A3E08A; uint16 v1 = g_word_A3E5F0[E->wsozr_parameter_1]; E->wsozr_var_A = v1; E->wsozr_var_B = v1; if ((E->base.properties & 3) != 0) { if ((E->base.properties & 3) == 2) E->wsozr_var_B = -E->wsozr_var_B; } else { E->wsozr_var_A = -E->wsozr_var_A; } } void WreckedShipOrangeZoomer_Main(void) { // 0xA3E08B Enemy_WreckedShipOrangeZoomer *E = Get_WreckedShipOrangeZoomer(cur_enemy_index); CallEnemyPreInstr(E->wsozr_var_F | 0xA30000); } void WreckedShipOrangeZoomer_Func_2(uint16 k) { // 0xA3E091 int16 v7; uint16 v9; uint16 v12; Enemy_WreckedShipOrangeZoomer *E = Get_WreckedShipOrangeZoomer(k); if (earthquake_timer == 30 && earthquake_type == 20) { E->wsozr_var_03 = E->wsozr_var_F; E->wsozr_var_F = FUNC16(FireZoomer_Func_2); } if (Enemy_MoveRight_ProcessSlopes(k, Shift8AddMagn(E->wsozr_var_A, 1))) { E->wsozr_var_04 = 0; EnemyFunc_C8AD(k); if (!(Enemy_MoveDown(k, INT16_SHL8(E->wsozr_var_B)))) { if ((int16)(samus_y_pos - E->base.y_pos) >= 0) { v7 = E->wsozr_var_B; if (v7 < 0) LABEL_17: v7 = -v7; } else { v7 = E->wsozr_var_B; if (v7 >= 0) goto LABEL_17; } E->wsozr_var_B = v7; return; } E->wsozr_var_A = -E->wsozr_var_A; v9 = addr_kWreckedShipOrangeZoomer_Ilist_E01F; if ((E->wsozr_var_B & 0x8000) != 0) v9 = addr_kWreckedShipOrangeZoomer_Ilist_E003; E->base.current_instruction = v9; E->base.instruction_timer = 1; } else { uint16 v11 = E->wsozr_var_04 + 1; E->wsozr_var_04 = v11; if (sign16(v11 - 4)) { E->wsozr_var_B = -E->wsozr_var_B; v12 = addr_kWreckedShipOrangeZoomer_Ilist_E01F; if ((E->wsozr_var_B & 0x8000) != 0) v12 = addr_kWreckedShipOrangeZoomer_Ilist_E003; E->base.current_instruction = v12; E->base.instruction_timer = 1; } else { E->wsozr_var_03 = E->wsozr_var_F; E->wsozr_var_F = FUNC16(FireZoomer_Func_2); } } } void sub_A3E168(uint16 k) { // 0xA3E168 int16 v7; uint16 v9; uint16 v12; Enemy_WreckedShipOrangeZoomer *E = Get_WreckedShipOrangeZoomer(k); if (earthquake_timer == 30 && earthquake_type == 20) { E->wsozr_var_03 = E->wsozr_var_F; E->wsozr_var_F = FUNC16(FireZoomer_Func_2); } if (Enemy_MoveDown(k, Shift8AddMagn(E->wsozr_var_B, 1))) { E->wsozr_var_04 = 0; if (!(Enemy_MoveRight_ProcessSlopes(k, INT16_SHL8(E->wsozr_var_A)))) { EnemyFunc_C8AD(k); if ((int16)(samus_x_pos - E->base.x_pos) >= 0) { v7 = E->wsozr_var_A; if (v7 < 0) v7 = -v7; } else { v7 = E->wsozr_var_A; if (v7 >= 0) v7 = -v7; } E->wsozr_var_A = v7; return; } E->wsozr_var_B = -E->wsozr_var_B; v9 = addr_kWreckedShipOrangeZoomer_Ilist_DFE7; if ((E->wsozr_var_A & 0x8000) != 0) v9 = addr_kWreckedShipOrangeZoomer_Ilist_DFCB; E->base.current_instruction = v9; E->base.instruction_timer = 1; } else { uint16 v11 = E->wsozr_var_04 + 1; E->wsozr_var_04 = v11; if (sign16(v11 - 4)) { E->wsozr_var_A = -E->wsozr_var_A; v12 = addr_kWreckedShipOrangeZoomer_Ilist_DFE7; if ((E->wsozr_var_A & 0x8000) != 0) v12 = addr_kWreckedShipOrangeZoomer_Ilist_DFCB; E->base.current_instruction = v12; E->base.instruction_timer = 1; } else { E->wsozr_var_03 = E->wsozr_var_F; E->wsozr_var_F = FUNC16(FireZoomer_Func_2); } } } void BigEyeBugs_Init(void) { // 0xA3E2D4 EnemyData *v1 = gEnemyData(cur_enemy_index); v1->current_instruction = g_off_A3E2CC[v1->current_instruction & 3]; StoneZoomer_E67A(cur_enemy_index); } void FireZoomer_Init(void) { // 0xA3E59C Enemy_FireZoomer *E = Get_FireZoomer(cur_enemy_index); E->base.current_instruction = g_off_A3E2CC[(E->base.current_instruction & 3)]; StoneZoomer_E67A(cur_enemy_index); } const uint16 *Zoomer_Instr_SetPreinstr(uint16 k, const uint16 *jp) { // 0xA3E660 gEnemyData(k)->ai_preinstr = jp[0]; return jp + 1; } void StoneZoomer_Init(void) { // 0xA3E669 Enemy_StoneZoomer *E = Get_StoneZoomer(cur_enemy_index); E->base.current_instruction = g_off_A3E2CC[(E->base.current_instruction & 3)]; StoneZoomer_E67A(cur_enemy_index); } void StoneZoomer_E67A(uint16 k) { // 0xA3E67A Enemy_StoneZoomer *E = Get_StoneZoomer(k); E->base.spritemap_pointer = addr_kSpritemap_Nothing_A3; E->base.instruction_timer = 1; E->szr_var_F = FUNC16(nullsub_304); if (E->szr_parameter_1 != 255) { uint16 v2 = g_word_A3E5F0[E->szr_parameter_1]; E->szr_var_A = v2; E->szr_var_B = v2; } if ((E->base.properties & 3) != 0) { if ((E->base.properties & 3) == 2) E->szr_var_B = -E->szr_var_B; } else { E->szr_var_A = -E->szr_var_A; } } void StoneZoomer_Main(void) { // 0xA3E6C2 Enemy_StoneZoomer *E = Get_StoneZoomer(cur_enemy_index); CallEnemyPreInstr(E->szr_var_F | 0xA30000); } void FireZoomer_Func_1(uint16 k) { // 0xA3E6C8 Enemy_FireZoomer *E = Get_FireZoomer(k); if (earthquake_timer == 30 && earthquake_type == 20) { E->fzr_var_03 = E->fzr_var_F; E->fzr_var_F = FUNC16(FireZoomer_Func_2); } if (Enemy_MoveRight_IgnoreSlopes(k, Shift8AddMagn(E->fzr_var_A, 1))) { E->fzr_var_04 = 0; EnemyFunc_C8AD(k); if (Enemy_MoveDown(k, INT16_SHL8(E->fzr_var_B))) { E->fzr_var_A = -E->fzr_var_A; uint16 fzr_parameter_2 = E->fzr_parameter_2, v7; if ((E->fzr_var_B & 0x8000) == 0) v7 = g_off_A3E63C[fzr_parameter_2 >> 1]; else v7 = g_off_A3E630[fzr_parameter_2 >> 1]; E->base.current_instruction = v7; E->base.instruction_timer = 1; } } else { uint16 v8 = E->fzr_var_04 + 1; E->fzr_var_04 = v8; if (sign16(v8 - 4)) { E->fzr_var_B = -E->fzr_var_B; uint16 v9 = E->fzr_parameter_2, v10; if ((E->fzr_var_B & 0x8000) == 0) v10 = g_off_A3E63C[v9 >> 1]; else v10 = g_off_A3E630[v9 >> 1]; E->base.current_instruction = v10; E->base.instruction_timer = 1; } else { E->fzr_var_03 = E->fzr_var_F; E->fzr_var_F = FUNC16(FireZoomer_Func_2); } } } void FireZoomer_Func_2(uint16 k) { // 0xA3E785 Enemy_FireZoomer *E = Get_FireZoomer(k); if (Enemy_MoveDown(k, __PAIR32__(E->fzr_var_02, E->fzr_var_01))) { if (E->fzr_parameter_1 == 255) { E->fzr_var_A = 128; E->fzr_var_B = 128; } E->fzr_var_01 = 0; E->fzr_var_02 = 0; E->fzr_var_04 = 0; E->fzr_var_F = E->fzr_var_03; } else { if (sign16(E->fzr_var_02 - 4)) AddToHiLo(&E->fzr_var_02, &E->fzr_var_01, 0x8000); if (!E->fzr_var_01 && !E->fzr_var_02) E->fzr_var_F = FUNC16(FireZoomer_Func_1); } } void FireZoomer_Func_3(uint16 k) { // 0xA3E7F2 Enemy_FireZoomer *E = Get_FireZoomer(k); if (earthquake_timer == 30 && earthquake_type == 20) { E->fzr_var_03 = E->fzr_var_F; E->fzr_var_F = FUNC16(FireZoomer_Func_2); } if (Enemy_MoveDown(k, Shift8AddMagn(E->fzr_var_B, 1))) { E->fzr_var_04 = 0; int32 amt = FireZoomer_E8A5(k); if (Enemy_MoveRight_IgnoreSlopes(k, amt)) { E->fzr_var_B = -E->fzr_var_B; uint16 fzr_parameter_2 = E->fzr_parameter_2, v6; if ((E->fzr_var_A & 0x8000) == 0) v6 = g_off_A3E654[fzr_parameter_2 >> 1]; else v6 = g_off_A3E648[fzr_parameter_2 >> 1]; E->base.current_instruction = v6; E->base.instruction_timer = 1; } else { EnemyFunc_C8AD(k); } } else { uint16 v7 = E->fzr_var_04 + 1; E->fzr_var_04 = v7; if (sign16(v7 - 4)) { E->fzr_var_A = -E->fzr_var_A; uint16 v8 = E->fzr_parameter_2, v9; if ((E->fzr_var_A & 0x8000) == 0) v9 = g_off_A3E654[v8 >> 1]; else v9 = g_off_A3E648[v8 >> 1]; E->base.current_instruction = v9; E->base.instruction_timer = 1; } else { E->fzr_var_03 = E->fzr_var_F; E->fzr_var_F = FUNC16(FireZoomer_Func_2); } } } int32 FireZoomer_E8A5(uint16 k) { // 0xA3E8A5 Enemy_FireZoomer *E = Get_FireZoomer(cur_enemy_index); uint16 xpos = E->base.x_pos; uint16 ypos = sign16(E->fzr_var_B) ? E->base.y_pos - E->base.y_height : E->base.y_pos + E->base.y_height - 1; CalculateBlockContainingPixelPos(xpos, ypos); if ((level_data[cur_block_index] & 0xF000) == 4096 && (BTS[cur_block_index] & 0x1F) >= 5) { uint16 v1 = g_word_A3E931[(uint16)(4 * (BTS[cur_block_index] & 0x1F)) >> 1]; if ((int16)E->fzr_var_A >= 0) return Multiply16x16(E->fzr_var_A, v1); else return -(int32)Multiply16x16(-E->fzr_var_A, v1); } else { return INT16_SHL8(E->fzr_var_A); } } void Metroid_Init(void) { // 0xA3EA4F Enemy_Metroid *E = Get_Metroid(cur_enemy_index); E->base.current_instruction = addr_kMetroid_Ilist_E9CF; E->metroid_var_00 = CreateSpriteAtPos(E->base.x_pos, E->base.y_pos, 50, E->base.vram_tiles_index | E->base.palette_index); E->metroid_var_01 = CreateSpriteAtPos(E->base.x_pos, E->base.y_pos, 52, E->base.vram_tiles_index | E->base.palette_index); E->metroid_var_02 = 0; } const uint16 *Metroid_Instr_2(uint16 k, const uint16 *jp) { // 0xA3EAA5 QueueSfx2_Max6(0x50); return jp; } const uint16 *Metroid_Instr_1(uint16 k, const uint16 *jp) { // 0xA3EAB1 int v2 = NextRandom() & 7; QueueSfx2_Max6(g_word_A3EAD6[v2]); return jp; } void Metroid_Frozen(void) { // 0xA3EAE6 Enemy_NormalFrozenAI_A3(); Enemy_Metroid *E = Get_Metroid(cur_enemy_index); if (E->metroid_var_E) { --E->metroid_var_E; E->base.flash_timer = 2; } int v1 = E->metroid_var_00 >> 1; sprite_palettes[v1] = 3072; sprite_disable_flag[v1] = 1; sprite_instr_list_ptrs[v1] = addr_kSpriteObject_Ilist_C3BA; int v2 = E->metroid_var_01 >> 1; sprite_palettes[v2] = 3072; sprite_disable_flag[v2] = 1; sprite_instr_list_ptrs[v2] = addr_kSpriteObject_Ilist_C4B6; } void Metroid_Hurt(void) { // 0xA3EB33 Enemy_Metroid *E = Get_Metroid(cur_enemy_index); if ((E->base.flash_timer & 2) != 0) { uint16 r18 = E->base.palette_index; int v1 = E->metroid_var_00 >> 1; sprite_palettes[v1] = r18 | sprite_palettes[v1] & 0xF1FF; int v2 = E->metroid_var_01 >> 1; sprite_palettes[v2] = r18 | sprite_palettes[v2] & 0xF1FF; } else { int v3 = E->metroid_var_00 >> 1; sprite_palettes[v3] &= 0xF1FF; uint16 metroid_var_01 = E->metroid_var_01; sprite_palettes[metroid_var_01 >> 1] &= 0xF1FF; } } static Func_Y_V *const off_A3EC09[4] = { Metroid_Func_1, Metroid_Func_2, Metroid_Func_3, Metroid_Func_4 }; void Metroid_Main(void) { // 0xA3EB98 Enemy_Metroid *E = Get_Metroid(cur_enemy_index); off_A3EC09[E->metroid_var_F](samus_y_pos - 8); uint16 r24 = E->base.vram_tiles_index | E->base.palette_index; int v2 = E->metroid_var_00 >> 1; sprite_x_pos[v2] = E->base.x_pos; sprite_y_pos[v2] = E->base.y_pos; sprite_palettes[v2] = r24; sprite_disable_flag[v2] = 0; int v4 = E->metroid_var_01 >> 1; sprite_x_pos[v4] = E->base.x_pos; sprite_y_pos[v4] = E->base.y_pos; sprite_palettes[v4] = r24; sprite_disable_flag[v4] = 0; } void Metroid_Func_1(uint16 varE32) { // 0xA3EC11 int16 v3; int16 v4; int16 v8; int16 v9; Enemy_Metroid *E = Get_Metroid(cur_enemy_index); int32 t = INT16_SHL8((int16)(E->base.y_pos - varE32) >> 2); uint16 r18 = t, r20 = t >> 16; uint16 metroid_var_C = E->metroid_var_C; bool v2 = metroid_var_C < r18; E->metroid_var_C = metroid_var_C - r18; v3 = E->metroid_var_D - (v2 + r20); E->metroid_var_D = v3; if (v3 < 0) { if ((uint16)v3 >= 0xFFFD) goto LABEL_9; v4 = -3; } else { if ((uint16)v3 < 3) goto LABEL_9; v4 = 3; } E->metroid_var_D = v4; E->metroid_var_C = 0; LABEL_9: if (Enemy_MoveDown(cur_enemy_index, __PAIR32__(E->metroid_var_D, E->metroid_var_C))) { E->metroid_var_C = 0; E->metroid_var_D = 0; } t = INT16_SHL8((int16)(E->base.x_pos - samus_x_pos) >> 2); r18 = t, r20 = t >> 16; uint16 metroid_var_A = E->metroid_var_A; v2 = metroid_var_A < r18; E->metroid_var_A = metroid_var_A - r18; v8 = E->metroid_var_B - (v2 + r20); E->metroid_var_B = v8; if (v8 < 0) { if ((uint16)v8 >= 0xFFFD) goto LABEL_19; v9 = -3; } else { if ((uint16)v8 < 3) goto LABEL_19; v9 = 3; } E->metroid_var_B = v9; E->metroid_var_A = 0; LABEL_19: if (Enemy_MoveRight_IgnoreSlopes(cur_enemy_index, __PAIR32__(E->metroid_var_B, E->metroid_var_A))) { E->metroid_var_A = 0; E->metroid_var_B = 0; } } void Metroid_Func_2(uint16 varE32) { // 0xA3ECDC int16 v1; int16 v5; uint16 v2, v6; uint16 r18 = 0, r20 = 0; Enemy_Metroid *E = Get_Metroid(cur_enemy_index); LOBYTE(v1) = (uint16)(varE32 - E->base.y_pos) >> 8; HIBYTE(v1) = varE32 - LOBYTE(E->base.y_pos); r20 = (uint16)(v1 & 0xFF00) >> 3; if ((r20 & 0x1000) != 0) r20 |= 0xE000; if ((r20 & 0x8000) != 0) { if (r20 >= 0xFFFD) goto LABEL_9; v2 = -3; } else { if (r20 < 3) goto LABEL_9; v2 = 3; } r20 = v2; r18 = 0; LABEL_9: E->metroid_var_C = r18; E->metroid_var_D = r20; if (Enemy_MoveDown(cur_enemy_index, __PAIR32__(r20, r18))) { E->metroid_var_C = 0; E->metroid_var_D = 0; } r18 = 0, r20 = 0; LOBYTE(v5) = (uint16)(samus_x_pos - E->base.x_pos) >> 8; HIBYTE(v5) = samus_x_pos - LOBYTE(E->base.x_pos); r20 = (uint16)(v5 & 0xFF00) >> 3; if ((r20 & 0x1000) != 0) r20 |= 0xE000; if ((r20 & 0x8000) != 0) { if (r20 >= 0xFFFD) goto LABEL_19; v6 = -3; } else { if (r20 < 3) goto LABEL_19; v6 = 3; } r20 = v6; r18 = 0; LABEL_19: E->metroid_var_A = r18; E->metroid_var_B = r20; if (Enemy_MoveRight_IgnoreSlopes(cur_enemy_index, __PAIR32__(r20, r18))) { E->metroid_var_A = 0; E->metroid_var_B = 0; } } void Metroid_Func_3(uint16 varE32) { // 0xA3ED8F Enemy_Metroid *E = Get_Metroid(cur_enemy_index); E->base.x_pos = samus_x_pos; E->base.y_pos = varE32; E->metroid_var_A = 0; E->metroid_var_B = 0; E->metroid_var_C = 0; E->metroid_var_D = 0; } void Metroid_Func_4(uint16 varE32) { // 0xA3EDAB Enemy_Metroid *E = Get_Metroid(cur_enemy_index); int v1 = E->metroid_var_E & 3; E->base.x_pos += g_word_A3EA3F[v1]; E->base.y_pos += g_word_A3EA3F[v1 + 4]; E->metroid_var_A = 0; E->metroid_var_B = 0; E->metroid_var_C = 0; E->metroid_var_D = 0; if (E->metroid_var_E-- == 1) { E->metroid_var_F = 0; E->base.current_instruction = addr_kMetroid_Ilist_E9CF; E->base.instruction_timer = 1; } } void Metroid_Touch(void) { // 0xA3EDEB Enemy_Metroid *E = Get_Metroid(cur_enemy_index); uint16 varE32 = samus_y_pos - 8; if (samus_contact_damage_index) { if (E->metroid_var_F != 2) { E->metroid_var_A = 0; E->metroid_var_C = 0; int16 v2 = E->base.x_pos - samus_x_pos; E->metroid_var_B = (v2 < 0) ? -256 : 0; *(uint16 *)((uint8 *)&E->metroid_var_A + 1) = v2 << 6; int16 v4 = E->base.y_pos - varE32; E->metroid_var_D = (v4 < 0) ? -256 : 0; *(uint16 *)((uint8 *)&E->metroid_var_C + 1) = v4 << 6; E->metroid_var_F = 0; E->base.current_instruction = addr_kMetroid_Ilist_E9CF; E->base.instruction_timer = 1; } } else { uint16 v5 = cur_enemy_index; if (E->metroid_var_F != 3) { if ((random_enemy_counter & 7) == 7 && !sign16(samus_health - 30)) QueueSfx3_Max6(0x2D); Metroid_Func_5(v5); } if (E->metroid_var_F < 2) { uint16 v7 = 1; if (abs16(E->base.x_pos - samus_x_pos) < 8 && abs16(E->base.y_pos - varE32) < 8) { v7 = 2; CallSomeSamusCode(0x12); } E->metroid_var_F = v7; if (v7 == 2) { E->base.current_instruction = addr_kMetroid_Ilist_EA25; E->base.instruction_timer = 1; } } } } void Metroid_Func_5(uint16 k) { // 0xA3EECE uint16 v1; uint16 varE32 = samus_y_pos - 8; if ((equipped_items & 0x20) != 0) { v1 = 12288; } else if (equipped_items & 1) { v1 = 24576; } else { v1 = -16384; } uint16 r18 = v1; Enemy_Metroid *E = Get_Metroid(k); uint16 metroid_var_02 = E->metroid_var_02; bool v4 = metroid_var_02 < r18; E->metroid_var_02 = metroid_var_02 - r18; if (v4) Samus_DealDamage(1); } void Metroid_Shot(void) { // 0xA3EF07 uint16 v0 = 2 * collision_detection_index; Enemy_Metroid *E = Get_Metroid(cur_enemy_index); if (E->base.frozen_timer) { uint16 v3 = projectile_type[v0 >> 1] & 0xF00; if (v3 == 256 || v3 == 512) { special_death_item_drop_x_origin_pos = E->base.x_pos; special_death_item_drop_y_origin_pos = E->base.y_pos; Enemy_NormalShotAI_SkipSomeParts_A3(); if (!E->base.health) { E->metroid_var_B = 0; EnemyDeathAnimation(cur_enemy_index, 4); CallSomeSamusCode(0x13); sprite_instr_list_ptrs[E->metroid_var_00 >> 1] = 0; uint16 metroid_var_01 = E->metroid_var_01; sprite_instr_list_ptrs[metroid_var_01 >> 1] = 0; Enemy_ItemDrop_Metroid(metroid_var_01); } } } else { if (E->metroid_var_F == 2) { if ((projectile_type[v0 >> 1] & 0xF00) == 1280) { E->metroid_var_E = 4; E->metroid_var_F = 3; E->base.current_instruction = addr_kMetroid_Ilist_E9CF; E->base.instruction_timer = 1; CallSomeSamusCode(0x13); } } else { E->metroid_var_A = 0; E->metroid_var_C = 0; int16 v7 = E->base.x_pos - projectile_x_pos[0]; E->metroid_var_B = (v7 < 0) ? -256 : 0; *(uint16 *)((uint8 *)&E->metroid_var_A + 1) = 32 * v7; int16 v9 = E->base.y_pos - projectile_y_pos[0]; E->metroid_var_D = (v9 < 0) ? -256 : 0; *(uint16 *)((uint8 *)&E->metroid_var_C + 1) = 32 * v9; E->metroid_var_F = 0; E->base.current_instruction = addr_kMetroid_Ilist_E9CF; E->base.instruction_timer = 1; int v10 = collision_detection_index; if ((projectile_type[v10] & 2) != 0) { QueueSfx3_Max6(0xA); uint16 r18 = projectile_damage[v10]; E->base.flash_timer = 4; uint16 metroid_parameter_2 = E->metroid_parameter_2; bool v13 = metroid_parameter_2 < r18; uint16 v12 = metroid_parameter_2 - r18; v13 = !v13; if (!v12 || !v13) { E->metroid_parameter_2 = 0; E->base.frozen_timer = 400; E->base.ai_handler_bits |= 4; return; } E->metroid_parameter_2 = v12; } QueueSfx2_Max6(0x5A); } } } void Metroid_Powerbomb(uint16 k) { // 0xA3F042 NormalEnemyPowerBombAi(); if (!Get_Metroid(k)->base.health) { CallSomeSamusCode(0x13); sprite_instr_list_ptrs[Get_Metroid(cur_enemy_index)->metroid_var_00 >> 1] = 0; sprite_instr_list_ptrs[Get_Metroid(cur_enemy_index)->metroid_var_01 >> 1] = 0; } }
411
0.5337
1
0.5337
game-dev
MEDIA
0.838617
game-dev
0.548948
1
0.548948
The-Aether-Team/The-Aether-II
14,486
src/main/java/com/aetherteam/aetherii/block/natural/OrangeTreeBlock.java
package com.aetherteam.aetherii.block.natural; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.server.level.ServerLevel; import net.minecraft.util.Mth; import net.minecraft.util.RandomSource; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.*; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.BonemealableBlock; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.BlockStateProperties; import net.minecraft.world.level.block.state.properties.DoubleBlockHalf; import net.minecraft.world.level.block.state.properties.EnumProperty; import net.minecraft.world.level.block.state.properties.IntegerProperty; import net.minecraft.world.level.gameevent.GameEvent; import net.minecraft.world.level.material.FluidState; import net.minecraft.world.level.material.Fluids; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; import net.neoforged.neoforge.common.CommonHooks; import javax.annotation.Nullable; public class OrangeTreeBlock extends AetherBushBlock implements BonemealableBlock { public static final int SINGLE_AGE_MAX = 1; public static final int DOUBLE_AGE_MAX = 4; public static final EnumProperty<DoubleBlockHalf> HALF = BlockStateProperties.DOUBLE_BLOCK_HALF; public static final IntegerProperty AGE = BlockStateProperties.AGE_4; private static final VoxelShape AGE_0_BOTTOM_SHAPE = Block.box(4.0D, 0.0D, 4.0D, 12.0D, 10.0D, 12.0D); private static final VoxelShape AGE_1_BOTTOM_SHAPE = Block.box(4.0D, 0.0D, 4.0D, 12.0D, 15.0D, 12.0D); private static final VoxelShape AGE_2_TOP_SHAPE = Block.box(2.0D, 0.0D, 2.0D, 14.0D, 10.0D, 14.0D); private static final VoxelShape GENERAL_TOP_SHAPE = Block.box(2.0D, 0.0D, 2.0D, 14.0D, 14.0D, 14.0D); private static final VoxelShape GENERAL_BOTTOM_SHAPE = Block.box(2.0D, 0.0D, 2.0D, 14.0D, 16.0D, 14.0D); public OrangeTreeBlock(Properties properties) { super(properties); this.registerDefaultState(this.defaultBlockState().setValue(HALF, DoubleBlockHalf.LOWER).setValue(AGE, 0)); } @Override protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) { builder.add(HALF, AGE); } @Override public VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, CollisionContext context) { int age = state.getValue(AGE); DoubleBlockHalf doubleBlockHalf = state.getValue(HALF); if (doubleBlockHalf == DoubleBlockHalf.LOWER) { // Handles age-dependent shape for the bottom block of an Orange Tree. switch(age) { case 0 -> { return AGE_0_BOTTOM_SHAPE; } case 1 -> { return AGE_1_BOTTOM_SHAPE; } default -> { return GENERAL_BOTTOM_SHAPE; } } } else { // Handles age-dependent shape for the top block of an Orange Tree. if (age == 2) { return AGE_2_TOP_SHAPE; } else { return GENERAL_TOP_SHAPE; } } } /** * [CODE COPY] - {@link net.minecraft.world.level.block.DoublePlantBlock#updateShape(BlockState, Direction, BlockState, LevelAccessor, BlockPos, BlockPos)}. */ @Override protected BlockState updateShape(BlockState state, LevelReader levelReader, ScheduledTickAccess scheduledTickAccess, BlockPos pos, Direction direction, BlockPos neighborPos, BlockState neighborState, RandomSource randomSource) { DoubleBlockHalf doubleBlockHalf = state.getValue(HALF); if (direction.getAxis() != Direction.Axis.Y || doubleBlockHalf == DoubleBlockHalf.LOWER != (direction == Direction.UP) || neighborState.is(this) && neighborState.getValue(HALF) != doubleBlockHalf) { return doubleBlockHalf == DoubleBlockHalf.LOWER && direction == Direction.DOWN && !state.canSurvive(levelReader, pos) ? Blocks.AIR.defaultBlockState() : super.updateShape(state, levelReader, scheduledTickAccess, pos, direction, neighborPos, neighborState, randomSource); } else { return Blocks.AIR.defaultBlockState(); } } /** * Only ticks the Orange Tree when it is growing before it has reached its max age. * @param state The {@link BlockState} of the block. * @return Whether the block should be ticking, as a {@link Boolean}. */ @Override public boolean isRandomlyTicking(BlockState state) { return state.getValue(AGE) < DOUBLE_AGE_MAX; } /** * Ages the Orange Tree up a state with a chance from a random tick.<br><br> */ @Override public void randomTick(BlockState state, ServerLevel level, BlockPos pos, RandomSource random) { DoubleBlockHalf doubleBlockHalf = state.getValue(HALF); int age = state.getValue(AGE); if (age < DOUBLE_AGE_MAX && level.getRawBrightness(pos.above(), 0) >= 9 && CommonHooks.canCropGrow(level, pos, state, random.nextInt(85) == 0)) { // Whether the Orange Tree is able to grow. age += 1; BlockState blockState = state.setValue(AGE, age); if (age > SINGLE_AGE_MAX && doubleBlockHalf == DoubleBlockHalf.LOWER) { // Growing for the double block state. OrangeTreeBlock.placeAt(level, blockState, pos, 2); } else { // Growing for the single block state. level.setBlock(pos, blockState, 2); } level.gameEvent(GameEvent.BLOCK_CHANGE, pos, GameEvent.Context.of(blockState)); CommonHooks.fireCropGrowPost(level, pos, state); } } /** * [CODE COPY] - {@link net.minecraft.world.level.block.DoublePlantBlock#canSurvive(BlockState, LevelReader, BlockPos)}. */ @Override public boolean canSurvive(BlockState state, LevelReader level, BlockPos pos) { if (state.getValue(HALF) != DoubleBlockHalf.UPPER) { return super.canSurvive(state, level, pos); } else { BlockState blockstate = level.getBlockState(pos.below()); if (state.getBlock() != this) return super.canSurvive(state, level, pos); // Forge: This function is called during world gen and placement, before this block is set, so if we are not 'here' then assume it's the pre-check. return blockstate.is(this) && blockstate.getValue(HALF) == DoubleBlockHalf.LOWER; } } /** * [CODE COPY] - {@link net.minecraft.world.level.block.DoublePlantBlock#playerWillDestroy(Level, BlockPos, BlockState, Player)}.<br><br> * Behavior depends on the Orange Tree's age being at the point of it being a double tall block instead of a single block. */ @Override public BlockState playerWillDestroy(Level level, BlockPos pos, BlockState state, Player player) { DoubleBlockHalf doubleBlockHalf = state.getValue(HALF); int age = state.getValue(AGE); if (age > SINGLE_AGE_MAX) { if (!level.isClientSide()) { preventCreativeDropFromBottomPart(level, pos, state, player); if (!player.isCreative()) { if (doubleBlockHalf == DoubleBlockHalf.LOWER) { pos = pos.above(); } dropResources(state.setValue(HALF, DoubleBlockHalf.LOWER), level, pos, null, player, player.getMainHandItem()); } } } return super.playerWillDestroy(level, pos, state, player); } /** * Handles destroying the entire Orange Tree when broken by a player. * @param level The {@link Level} the block is in. * @param player The {@link Player} destroying the block. * @param pos The {@link BlockPos} of the block. * @param state The {@link BlockState} of the block. * @param blockEntity The {@link BlockEntity} that the block has. * @param tool The {@link ItemStack} of the tool used to destroy the block. */ @Override public void playerDestroy(Level level, Player player, BlockPos pos, BlockState state, @Nullable BlockEntity blockEntity, ItemStack tool) { DoubleBlockHalf doubleBlockHalf = state.getValue(HALF); int age = state.getValue(AGE); if (age > SINGLE_AGE_MAX) { // Destroying for the double block state. super.playerDestroy(level, player, pos, Blocks.AIR.defaultBlockState(), blockEntity, tool); // Replaces the entire blocks with air. if (age == DOUBLE_AGE_MAX) { // If the Orange Tree had Oranges, the age is reverted to represent harvesting, instead of the entire block being broken. if (doubleBlockHalf == DoubleBlockHalf.UPPER) { pos = pos.below(); } OrangeTreeBlock.placeAt(level, state.setValue(AGE, age - 1), pos, 2); } } else { // Destroying for the single block state. super.playerDestroy(level, player, pos, state, blockEntity, tool); } } @Override public boolean onDestroyedByPlayer(BlockState state, Level level, BlockPos pos, Player player, boolean willHarvest, FluidState fluid) { DoubleBlockHalf doubleBlockHalf = state.getValue(HALF); int age = state.getValue(AGE); if (doubleBlockHalf == DoubleBlockHalf.UPPER && age == DOUBLE_AGE_MAX) { return true; } return super.onDestroyedByPlayer(state, level, pos, player, willHarvest, fluid); } /** * Reverts the Orange Tree age state to not have Oranges when exploded. * @param state The {@link BlockState} of the block. * @param level The {@link Level} the block is in. * @param pos The {@link BlockPos} of the block. * @param explosion The {@link Explosion} affecting the block. */ @Override public void onBlockExploded(BlockState state, ServerLevel level, BlockPos pos, Explosion explosion) { super.onBlockExploded(state, level, pos, explosion); int age = state.getValue(AGE); if (age == DOUBLE_AGE_MAX) { OrangeTreeBlock.placeAt(level, state.setValue(AGE, age - 1), pos, 2); } } /** * [CODE COPY] - {@link net.minecraft.world.level.block.DoublePlantBlock#preventCreativeDropFromBottomPart(Level, BlockPos, BlockState, Player)}. */ protected static void preventCreativeDropFromBottomPart(Level level, BlockPos pos, BlockState state, Player player) { DoubleBlockHalf doubleBlockHalf = state.getValue(HALF); if (doubleBlockHalf == DoubleBlockHalf.UPPER) { BlockPos blockPos = pos.below(); BlockState blockState = level.getBlockState(blockPos); if (blockState.is(state.getBlock()) && blockState.getValue(HALF) == DoubleBlockHalf.LOWER) { level.setBlock(blockPos, blockState.getFluidState().is(Fluids.WATER) ? Blocks.WATER.defaultBlockState() : Blocks.AIR.defaultBlockState(), 35); level.levelEvent(player, 2001, blockPos, Block.getId(blockState)); } } } /** * [CODE COPY] - {@link net.minecraft.world.level.block.DoublePlantBlock#placeAt(LevelAccessor, BlockState, BlockPos, int)}.<br><br> * Without waterlogging behavior. */ public static void placeAt(LevelAccessor level, BlockState state, BlockPos pos, int flags) { BlockPos abovePos = pos.above(); level.setBlock(pos, state.setValue(HALF, DoubleBlockHalf.LOWER), flags); level.setBlock(abovePos, state.setValue(HALF, DoubleBlockHalf.UPPER), flags); } /** * Grows an Orange Tree to the next age state. * @param level The {@link Level} the block is in. * @param random The {@link RandomSource} from the level. * @param pos The {@link BlockPos} of the block. * @param state The {@link BlockState} of the block. */ @Override public void performBonemeal(ServerLevel level, RandomSource random, BlockPos pos, BlockState state) { DoubleBlockHalf doubleBlockHalf = state.getValue(HALF); int i = Math.min(DOUBLE_AGE_MAX, state.getValue(AGE) + 1); if (i > SINGLE_AGE_MAX && (level.isEmptyBlock(pos.above()) || level.getBlockState(pos.above()).is(this))) { // Growing for the double block state. if (doubleBlockHalf == DoubleBlockHalf.UPPER) { pos = pos.below(); } OrangeTreeBlock.placeAt(level, state.setValue(AGE, i), pos, 2); } else { // Growing for the single block state. level.setBlock(pos, state.setValue(AGE, i), 2); } } /** * Whether the behavior for using bone meal should run. A 100% success rate. * @param level The {@link Level} the block is in. * @param random The {@link RandomSource} from the level. * @param pos The {@link BlockPos} of the block. * @param state The {@link BlockState} of the block. * @return A {@link Boolean} of whether using Bone Meal was successful. */ @Override public boolean isBonemealSuccess(Level level, RandomSource random, BlockPos pos, BlockState state) { return true; //todo balance } /** * Allows bone meal to be used on Orange Trees when not yet fully grown. * @param level The {@link Level} the block is in. * @param pos The {@link BlockPos} of the block. * @param state The {@link BlockState} of the block. * @return Whether this block is valid to use bone meal on, as a {@link Boolean}. */ @Override public boolean isValidBonemealTarget(LevelReader level, BlockPos pos, BlockState state) { return state.getValue(AGE) < DOUBLE_AGE_MAX; } /** * [CODE COPY] - {@link net.minecraft.world.level.block.DoublePlantBlock#getSeed(BlockState, BlockPos)}.<br><br> * Warning for "deprecation" is suppressed because the method is fine to override. */ @SuppressWarnings("deprecation") @Override public long getSeed(BlockState state, BlockPos pos) { return Mth.getSeed(pos.getX(), pos.below(state.getValue(HALF) == DoubleBlockHalf.LOWER ? 0 : 1).getY(), pos.getZ()); } }
411
0.940688
1
0.940688
game-dev
MEDIA
0.992969
game-dev
0.923887
1
0.923887
MegaMek/megamek
5,276
megamek/src/megamek/common/weapons/battleArmor/clan/CLBALBX.java
/* * Copyright (c) 2005 - Ben Mazur (bmazur@sev.org) * Copyright (C) 2013-2025 The MegaMek Team. All Rights Reserved. * * This file is part of MegaMek. * * MegaMek is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License (GPL), * version 3 or (at your option) any later version, * as published by the Free Software Foundation. * * MegaMek 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. * * A copy of the GPL should have been included with this project; * if not, see <https://www.gnu.org/licenses/>. * * NOTICE: The MegaMek organization is a non-profit group of volunteers * creating free software for the BattleTech community. * * MechWarrior, BattleMech, `Mech and AeroTech are registered trademarks * of The Topps Company, Inc. All Rights Reserved. * * Catalyst Game Labs and the Catalyst Game Labs logo are trademarks of * InMediaRes Productions, LLC. * * MechWarrior Copyright Microsoft Corporation. MegaMek was created under * Microsoft's "Game Content Usage Rules" * <https://www.xbox.com/en-US/developers/rules> and it is not endorsed by or * affiliated with Microsoft. */ package megamek.common.weapons.battleArmor.clan; import static megamek.common.game.IGame.LOGGER; import java.io.Serial; import megamek.common.SimpleTechLevel; import megamek.common.ToHitData; import megamek.common.actions.WeaponAttackAction; import megamek.common.alphaStrike.AlphaStrikeElement; import megamek.common.annotations.Nullable; import megamek.common.compute.Compute; import megamek.common.enums.AvailabilityValue; import megamek.common.enums.Faction; import megamek.common.enums.TechBase; import megamek.common.enums.TechRating; import megamek.common.equipment.AmmoType; import megamek.common.game.Game; import megamek.common.loaders.EntityLoadingException; import megamek.common.weapons.Weapon; import megamek.common.weapons.battleArmor.BALBXHandler; import megamek.common.weapons.handlers.AttackHandler; import megamek.server.totalWarfare.TWGameManager; public class CLBALBX extends Weapon { @Serial private static final long serialVersionUID = 2978911783244524588L; public CLBALBX() { super(); name = "Battle Armor LB-X AC"; setInternalName(name); addLookupName("CLBALBX"); addLookupName("Clan BA LBX"); heat = 0; damage = 4; rackSize = 4; shortRange = 2; mediumRange = 5; longRange = 8; extremeRange = 12; tonnage = 0.4; criticalSlots = 2; toHitModifier = -1; // TODO: refactor BA ammo-based weapons to use real AmmoTypes (but not track ammo use) ammoType = AmmoType.AmmoTypeEnum.NA; bv = 20; cost = 70000; // TODO: implement F_NO_COUNT_AMMO flags = flags.or(F_NO_FIRES) .or(F_BA_WEAPON) .or(F_BALLISTIC) .andNot(F_MEK_WEAPON) .andNot(F_TANK_WEAPON) .andNot(F_AERO_WEAPON) .andNot(F_PROTO_WEAPON); rulesRefs = "207, TM"; techAdvancement.setTechBase(TechBase.CLAN) .setTechRating(TechRating.F) .setAvailability(AvailabilityValue.X, AvailabilityValue.X, AvailabilityValue.E, AvailabilityValue.D) .setClanAdvancement(3075, 3085) .setClanApproximate(false, false) .setPrototypeFactions(Faction.CNC) .setProductionFactions(Faction.CNC) .setStaticTechLevel(SimpleTechLevel.ADVANCED); } @Override @Nullable public AttackHandler getCorrectHandler(ToHitData toHit, WeaponAttackAction waa, Game game, TWGameManager manager) { try { return new BALBXHandler(toHit, waa, game, manager); } catch (EntityLoadingException ignored) { LOGGER.warn("Get Correct Handler - Attach Handler Received Null Entity."); } return null; } /** * non-squad size version for AlphaStrike base damage */ @Override public double getBattleForceDamage(int range) { double damage = 0; if (range <= getLongRange()) { damage = Compute.calculateClusterHitTableAmount(7, getDamage()); damage *= 1.05; // -1 to hit if ((range == AlphaStrikeElement.SHORT_RANGE) && (getMinimumRange() > 0)) { damage = adjustBattleForceDamageForMinRange(damage); } } return damage / 10.0; } @Override public double getBattleForceDamage(int range, int baSquadSize) { double damage = 0; if (range <= getLongRange()) { damage = Compute.calculateClusterHitTableAmount(7, getDamage() * baSquadSize); damage *= 1.05; // -1 to hit if ((range == AlphaStrikeElement.SHORT_RANGE) && (getMinimumRange() > 0)) { damage = adjustBattleForceDamageForMinRange(damage); } } return damage / 10.0; } @Override public int getBattleForceClass() { return BF_CLASS_FLAK; } }
411
0.883069
1
0.883069
game-dev
MEDIA
0.96349
game-dev
0.959509
1
0.959509
EudyContreras/Skeleton-Bones
5,720
boneslibrary/src/main/java/com/eudycontreras/boneslibrary/bindings/SkeletonShimmerBindings.kt
package com.eudycontreras.boneslibrary.bindings import android.view.ViewGroup import android.view.animation.Interpolator import androidx.annotation.ColorInt import androidx.databinding.BindingAdapter import com.eudycontreras.boneslibrary.MAX_OFFSET import com.eudycontreras.boneslibrary.doWith import com.eudycontreras.boneslibrary.framework.shimmer.ShimmerRayProperties import com.eudycontreras.boneslibrary.framework.skeletons.SkeletonDrawable import com.eudycontreras.boneslibrary.properties.Color import com.eudycontreras.boneslibrary.properties.MutableColor /** * Copyright (C) 2020 Project X * * @Project ProjectX * @author Eudy Contreras. * @since March 2020 */ object SkeletonShimmerRayBindings { /** * **Binding Property**: app:skeletonShimmerRayColor */ const val SKELETON_SHIMMER_RAY_COLOR = "skeletonShimmerRayColor" /** * **Binding Property**: app:skeletonShimmerRayTilt */ const val SKELETON_SHIMMER_RAY_TILT = "skeletonShimmerRayTilt" /** * **Binding Property**: app:skeletonShimmerRayCount */ const val SKELETON_SHIMMER_RAY_COUNT = "skeletonShimmerRayCount" /** * **Binding Property**: app:skeletonShimmerRayThickness */ const val SKELETON_SHIMMER_RAY_THICKNESS = "skeletonShimmerRayThickness" /** * **Binding Property**: app:skeletonShimmerRayThicknessRatio */ const val SKELETON_SHIMMER_RAY_THICKNESS_RATIO = "skeletonShimmerRayThicknessRatio" /** * **Binding Property**: app:skeletonShimmerRayInterpolator */ const val SKELETON_SHIMMER_RAY_INTERPOLATOR = "skeletonShimmerRayInterpolator" /** * **Binding Property**: app:skeletonShimmerRaySharedInterpolator */ const val SKELETON_SHIMMER_RAY_INTERPOLATOR_SHARED = "skeletonShimmerRaySharedInterpolator" /** * **Binding Property**: app:skeletonShimmerRaySpeedMultiplier */ const val SKELETON_SHIMMER_RAY_SPEED_MULTIPLIER = "skeletonShimmerRaySpeedMultiplier" } ///////////////////////// Skeleton Shimmer Ray Binding Adapters ///////////////////////// @BindingAdapter(SkeletonShimmerRayBindings.SKELETON_SHIMMER_RAY_COLOR) internal fun ViewGroup.setSkeletonShimmerRayColor(@ColorInt rayColor: Int?) { doWith(foreground) { if (it is SkeletonDrawable) { it.getProps().shimmerRayProperties.shimmerRayColor = MutableColor(rayColor ?: Color.MIN_COLOR) } else { addSkeletonLoader(enabled = true) setSkeletonShimmerRayColor(rayColor) } } } @BindingAdapter(SkeletonShimmerRayBindings.SKELETON_SHIMMER_RAY_TILT) internal fun ViewGroup.setSkeletonShimmerRayTilt(rayTilt: Float?) { doWith(foreground) { if (it is SkeletonDrawable) { it.getProps().shimmerRayProperties.shimmerRayTilt = rayTilt ?: ShimmerRayProperties.DEFAULT_RAY_TILT } else { addSkeletonLoader(enabled = true) setSkeletonShimmerRayTilt(rayTilt) } } } @BindingAdapter(SkeletonShimmerRayBindings.SKELETON_SHIMMER_RAY_COUNT) internal fun ViewGroup.setSkeletonShimmerRayCount(count: Int?) { doWith(foreground) { if (it is SkeletonDrawable) { it.getProps().shimmerRayProperties.shimmerRayCount = count ?: return } else { addSkeletonLoader(enabled = true) setSkeletonShimmerRayCount(count) } } } @BindingAdapter(SkeletonShimmerRayBindings.SKELETON_SHIMMER_RAY_THICKNESS) internal fun ViewGroup.setSkeletonShimmerRayThickness(thickness: Float?) { doWith(foreground) { if (it is SkeletonDrawable) { it.getProps().shimmerRayProperties.shimmerRayThickness = thickness } else { addSkeletonLoader(enabled = true) setSkeletonShimmerRayThickness(thickness) } } } @BindingAdapter(SkeletonShimmerRayBindings.SKELETON_SHIMMER_RAY_THICKNESS_RATIO) internal fun ViewGroup.setSkeletonShimmerRayThicknessRatio(thicknessRatio: Float?) { doWith(foreground) { if (it is SkeletonDrawable) { it.getProps().shimmerRayProperties.shimmerRayThicknessRatio = thicknessRatio ?: ShimmerRayProperties.DEFAULT_THICKNESS_RATIO } else { addSkeletonLoader(enabled = true) setSkeletonShimmerRayThicknessRatio(thicknessRatio) } } } @BindingAdapter(SkeletonShimmerRayBindings.SKELETON_SHIMMER_RAY_INTERPOLATOR) internal fun ViewGroup.setSkeletonShimmerRayInterpolator(interpolator: Interpolator?) { doWith(foreground) { if (it is SkeletonDrawable) { it.getProps().shimmerRayProperties.shimmerRayInterpolator = interpolator } else { addSkeletonLoader(enabled = true) setSkeletonShimmerRayInterpolator(interpolator) } } } @BindingAdapter(SkeletonShimmerRayBindings.SKELETON_SHIMMER_RAY_INTERPOLATOR_SHARED) internal fun ViewGroup.setSkeletonShimmerRaySharedInterpolator(shared: Boolean?) { doWith(foreground) { if (it is SkeletonDrawable) { it.getProps().shimmerRayProperties.shimmerRaySharedInterpolator = shared ?: true } else { addSkeletonLoader(enabled = true) setSkeletonShimmerRaySharedInterpolator(shared) } } } @BindingAdapter(SkeletonShimmerRayBindings.SKELETON_SHIMMER_RAY_SPEED_MULTIPLIER) internal fun ViewGroup.setSkeletonShimmerRaySpeedMultiplier(speedMultiplier: Float?) { doWith(foreground) { if (it is SkeletonDrawable) { it.getProps().shimmerRayProperties.shimmerRaySpeedMultiplier = speedMultiplier ?: MAX_OFFSET } else { addSkeletonLoader(enabled = true) setSkeletonShimmerRaySpeedMultiplier(speedMultiplier) } } }
411
0.552594
1
0.552594
game-dev
MEDIA
0.539017
game-dev,graphics-rendering
0.884621
1
0.884621