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
orfeasel/PortfolioSnippets
1,027
UE4_TechDemos/PuzzleGame/Private/PuzzleDedicatedActors/MelodyOfTorment/MoTPianoLid.cpp
// Orfeas Eleftheriou 2016 #include "ProjectNA.h" #include "MoTPianoLid.h" void AMoTPianoLid::Rotate(FRotator NewRotation) { SetActorRotation(NewRotation); } AMoTPianoLid::AMoTPianoLid() { TimelineHandleComponent = CreateDefaultSubobject<UTimelineHandleComponent>(FName("TimelineHandleComponent")); } void AMoTPianoLid::BeginPlay() { Super::BeginPlay(); FRotator TargetRotation = GetActorRotation(); TargetRotation.Roll -= 100.f; TimelineHandleComponent->SetInitialAndTargetValues(GetActorRotation(), TargetRotation); TimelineHandleComponent->BindFloatCurveRotatorExecutionFunction(this, FName("Rotate")); FOnTimelineEventStatic TimelineFinishedFunction; TimelineFinishedFunction.BindLambda([&]() { bIsOpen = true; }); TimelineHandleComponent->SetTimelineFinishedFunc(TimelineFinishedFunction); } bool AMoTPianoLid::Interact(UBackpackComponent& BackpackComponent) { if (Super::Interact(BackpackComponent) && !bIsOpen) { TimelineHandleComponent->PlayTimeline(); return true; } return false; }
0
0.818387
1
0.818387
game-dev
MEDIA
0.879621
game-dev
0.919065
1
0.919065
pbghogehoge/ssg
11,525
GIAN07/MAID.CPP
/* */ /* Maid.cpp メイドさん関連の処理 */ /* */ /* */ #include "Maid.h" #include "DD_GRP3D.h" MAID Viv; // 麗しきメイドさん構造体 DWORD EvadeRate[256]; // かすり得点レート extern void WideBombDraw(void) { //RECT src = {0, 0, 382, 480}; static RECT data[6] = { {0, 0, 210, 240}, {210, 0, 210*2, 240}, {210*2, 0, 210*3, 240}, {0, 240, 210, 480}, {210, 240, 210*2, 480}, {210*2, 240, 210*3, 480} }; RECT src; int x,y; int t; #define BX_MIN (X_MIN+100) #define BY_MIN (Y_MIN+100) if(Viv.weapon!=0 || Viv.bomb_time==0) return; x = BX_MIN; y = BY_MIN; if(Viv.bomb_time > 80){ // x = BX_MIN + (Viv.bomb_time-30*7) * 11; if(x < BX_MIN) x = BX_MIN; // y = BY_MIN + (Viv.bomb_time-30*7) * 11; if(y < BY_MIN) y = BY_MIN; t = ((60*4-Viv.bomb_time)/4); if(t < 0) t = 0; if(t > 5) t = 5; } else{ // x = BX_MIN - (80-Viv.bomb_time) * 8; // y = BY_MIN - (80-Viv.bomb_time) * 8; t = (Viv.bomb_time/4); if(t > 5) t = 5; } src = data[t]; GrpBlt(&src, x, y, GrBomber); } void LaserBombDraw(void) { BYTE d,c; POINT p[4]; int i,w; int lx,ly; int wx,wy; BYTE LaserDeg; LaserDeg = GetLaserDeg(); GrpLock(); if(LaserDeg<58){ for(w=3;w>0;w--){ for(i=-3;i<=3;i++){ d = GetRightLaserDeg(LaserDeg, i); //64+48 - LaserDeg*3 + i*(64-LaserDeg)/2; lx = cosl(d,850); ly = sinl(d,850); wx = cosl(d+64,w); wy = sinl(d+64,w); p[0].x = (Viv.opx>>6) + SBOPT_DX + 0 + wx; p[0].y = (Viv.opy>>6) + 0 + wy; p[3].x = (Viv.opx>>6) + SBOPT_DX + 0 - wx; p[3].y = (Viv.opy>>6) + 0 - wy; p[2].x = (Viv.opx>>6) + SBOPT_DX + lx - wx; p[2].y = (Viv.opy>>6) + ly - wy; p[1].x = (Viv.opx>>6) + SBOPT_DX + lx + wx; p[1].y = (Viv.opy>>6) + ly + wy; if(DxObj.Bpp==16){ GrpSetColor(0,0,5); GrpSetAlpha(0,ALPHA_ONE); GrpGrdRectA(p); } else{ switch(w){ case(1): GrpSetColor(4,4,5); break; case(2): GrpSetColor(2,2,5); break; case(3): GrpSetColor(0,0,5); break; } GrpPolygon(p,4); } } for(i=-3;i<=3;i++){ d = GetLeftLaserDeg(LaserDeg, i); //64-48 + LaserDeg*3 + i*(64-LaserDeg)/2; lx = cosl(d,850); ly = sinl(d,850); wx = cosl(d+64,w); wy = sinl(d+64,w); p[0].x = (Viv.opx>>6) - SBOPT_DX + 0 + wx; p[0].y = (Viv.opy>>6) + 0 + wy; p[3].x = (Viv.opx>>6) - SBOPT_DX + 0 - wx; p[3].y = (Viv.opy>>6) + 0 - wy; p[2].x = (Viv.opx>>6) - SBOPT_DX + lx - wx; p[2].y = (Viv.opy>>6) + ly - wy; p[1].x = (Viv.opx>>6) - SBOPT_DX + lx + wx; p[1].y = (Viv.opy>>6) + ly + wy; if(DxObj.Bpp==16){ GrpSetColor(0,0,5); GrpSetAlpha(0,ALPHA_ONE); GrpGrdRectA(p); } else{ switch(w){ case(1): GrpSetColor(4,4,5); break; case(2): GrpSetColor(2,2,5); break; case(3): GrpSetColor(0,0,5); break; } GrpPolygon(p,4); } } if(DxObj.Bpp==16) break; } } else if(LaserDeg<150){ c = 0; for(w=12-(LaserDeg-64)/8;w>0;w-=2,c++){ for(i=-3;i<=3;i++){ d = GetRightLaserDeg(LaserDeg, i);// 64+48 - 58*3 + i*(64-min(62,LaserDeg))/2; lx = cosl(d,850); ly = sinl(d,850); wx = cosl(d+64,w); wy = sinl(d+64,w); p[0].x = (Viv.opx>>6) + SBOPT_DX + 0 + wx; p[0].y = (Viv.opy>>6) + 0 + wy; p[3].x = (Viv.opx>>6) + SBOPT_DX + 0 - wx; p[3].y = (Viv.opy>>6) + 0 - wy; p[2].x = (Viv.opx>>6) + SBOPT_DX + lx - wx; p[2].y = (Viv.opy>>6) + ly - wy; p[1].x = (Viv.opx>>6) + SBOPT_DX + lx + wx; p[1].y = (Viv.opy>>6) + ly + wy; if(DxObj.Bpp==16){ GrpSetColor(0,0,5); GrpSetAlpha(0,ALPHA_ONE); GrpGrdRectA(p); } else{ GrpSetColor(c,c,5); GrpPolygon(p,4); } } for(i=-3;i<=3;i++){ d = GetLeftLaserDeg(LaserDeg, i); //64-48 + 58*3 + i*(64-min(62,LaserDeg))/2; lx = cosl(d,850); ly = sinl(d,850); wx = cosl(d+64,w); wy = sinl(d+64,w); p[0].x = (Viv.opx>>6) - SBOPT_DX + 0 + wx; p[0].y = (Viv.opy>>6) + 0 + wy; p[3].x = (Viv.opx>>6) - SBOPT_DX + 0 - wx; p[3].y = (Viv.opy>>6) + 0 - wy; p[2].x = (Viv.opx>>6) - SBOPT_DX + lx - wx; p[2].y = (Viv.opy>>6) + ly - wy; p[1].x = (Viv.opx>>6) - SBOPT_DX + lx + wx; p[1].y = (Viv.opy>>6) + ly + wy; if(DxObj.Bpp==16){ GrpSetColor(0,0,5); GrpSetAlpha(0,ALPHA_ONE); GrpGrdRectA(p); } else{ GrpSetColor(c,c,5); GrpPolygon(p,4); } } if(DxObj.Bpp==16) break; } } GrpUnlock(); } extern void MaidDraw(void) { static RECT VivBit[4][2] = { {{480,128,480+24,128+24},{504,128,504+24,128+24}}, // ワイド {{480,152,480+24,152+24},{504,152,504+24,152+24}}, // ホーミング {{528,152,528+24,152+24},{552,152,552+24,152+24}}, // レーザー {{480,152,480+24,152+24},{504,152,504+24,152+24}}, // 仮 }; static BYTE draw_flag = 0; static BYTE draw_flag2 = 0; int x = (Viv.x>>6)-16; int y = (Viv.y>>6)-24; int ox = (Viv.opx>>6) - 12; int oy = (Viv.opy>>6) - 12; RECT src; draw_flag = 1 - draw_flag; draw_flag2++; if(Viv.muteki == VIVDEAD_VAL) draw_flag = 0; if(Viv.muteki==0 || draw_flag){ BltSetRect(&src,384+Viv.GrpID*32,128,16*2,16*3); GrpBlt(&src,x,y,GrTama); } if( ((Viv.exp+1)>>5) ){ if(Viv.muteki < VIVDEAD_VAL){ src = VivBit[Viv.weapon&3][(draw_flag2>>2)&1]; GrpBlt(&src,ox+SBOPT_DX,oy,GrTama); src = VivBit[Viv.weapon&3][(draw_flag2>>2)&1]; GrpBlt(&src,ox-SBOPT_DX,oy,GrTama); } } if(Viv.bomb_time && Viv.weapon==2) LaserBombDraw(); } // 各種ステータスを描画する // extern void StateDraw(void) { int i,temp; //RECT src = {0,80,128,80+16}; RECT src = {0,80,128,80+24}; char buf[100]; // 残りかすり時間ゲージの表示 // if(Viv.evade_c){ GrpLock(); GrpSetColor(5,1,0); GrpSetAlpha(128,ALPHA_ONE); for(i=0;i<=10;i++){ temp = 128+9+(Viv.evade_c>>2) + (5-i); if(temp>128+8) GrpBoxA(128+8,16+3+i,temp,16+3+i+1); //GrpBoxA(128+8,16+3,128+9+(Viv.evade_c>>2),16+3+10); } GrpUnlock(); } GrpBlt(&src,128,16,GrTama); sprintf(buf,"%3d",Viv.evade); GrpPut57(128 + 95,16 + 91-80,buf); // 得点表示 // sprintf(buf,"%9d",Viv.score); GrpPut16c(128,0,buf); // 仮の残機&残りボム表示 // sprintf(buf," Bomb %1d", Viv.bomb); GrpPut16c(280,0,buf); // 残りメイド数表示 // for(i=0; i<Viv.left; i++){ BltSetRect(&src, 608, 432, 16, 16); GrpBlt(&src, 280+i*14, 0, GrTama); } } extern void MaidMove(void) { int vx,vy,v; int VivSpeed = 64*18; char buf[100]; // かすり残り時間を減らす // if(Viv.evade_c){ if(Viv.bomb_time && Viv.evade_c>=2) Viv.evade_c -= 2; else Viv.evade_c -= 1; if(Viv.evade_c==0){ sprintf(buf,"%3d Evade %7dPts",Viv.evade,Viv.evadesc); StringEffect(180,40,buf); score_add(Viv.evadesc); Viv.evade = 0; Viv.evadesc = 0; } } // 無敵時間を減らす(ボム中は減らさない) // if(Viv.muteki && Viv.bomb_time==0) Viv.muteki--; // 得点変化処理 // if(Viv.dscore>=100000) Viv.score+=100000 ,Viv.dscore-=100000; else if(Viv.dscore>=20000) Viv.score+=20000 ,Viv.dscore-=20000; else if(Viv.dscore>=2000) Viv.score+=2000 ,Viv.dscore-=2000; else if(Viv.dscore>=200) Viv.score+=200 ,Viv.dscore-=200; else if(Viv.dscore>=20) Viv.score+=20 ,Viv.dscore-=20; else if(Viv.dscore>=10) Viv.score+=10 ,Viv.dscore-=10; // 押しっぱなし減速を有効にするのか // if(ConfigDat.InputFlags & INPF_Z_SPDDOWN_ENABLE){ if(Key_Data & KEY_TAMA){ if(Viv.ShiftCounter < 8) Viv.ShiftCounter++; else Key_Data = Key_Data | KEY_SHIFT; } else{ Viv.ShiftCounter = 0; } } if(Viv.muteki < MAID_MOVE_DISABLE_TIME){ vx = vy = 0; v = (Key_Data & KEY_SHIFT) ? (VivSpeed/3) : VivSpeed; if(Key_Data & KEY_UP) vy-=v; if(Key_Data & KEY_DOWN) vy+=v; if(Key_Data & KEY_LEFT) vx-=v; if(Key_Data & KEY_RIGHT) vx+=v; if(vx && vy){ Viv.x += (vx/6); Viv.y += (vy/6); } else{ Viv.x += (vx>>2); Viv.y += (vy>>2); } if(Viv.y<SY_MIN) Viv.y = SY_MIN; else if(Viv.y>SY_MAX) Viv.y = SY_MAX; if(Viv.x<SX_MIN) Viv.x = SX_MIN; else if(Viv.x>SX_MAX) Viv.x = SX_MAX; } else{ vx = 0; vy = -(64+32); Viv.y += vy; } if(vx>0) Viv.GrpID = 2; else if(vx<0) Viv.GrpID = 0; else Viv.GrpID = 1; Viv.opx = Viv.x; Viv.opy = Viv.y; // オプションの処理 // if(Viv.vx<0) Viv.vx+=64; if(Viv.vx>0) Viv.vx-=64; if(Viv.vy<0) Viv.vy+=64; if(Viv.vy>0) Viv.vy-=64; if(vx<0&&Viv.vx< 6*64) Viv.vx+=2*64; if(vx>0&&Viv.vx>-6*64) Viv.vx-=2*64; if(vy<0&&Viv.vy< 10*64) Viv.vy+=2*64; if(vy>0&&Viv.vy>-10*64) Viv.vy-=2*64; Viv.opx = Viv.x + Viv.vx; Viv.opy = Viv.y + Viv.vy + 64*6; // 弾&ボムのセット // MaidTamaSet(); if(Viv.bomb_time){ tama_clear(); laser_clear(); //if(Viv.bomb_time%60==0) fragment_set(Viv.x,Viv.y,FRG_FATCIRCLE); } Viv.BuzzSound = FALSE; } // 初期化 // extern void MaidSet(void) { int i; int sct[4] = {5,10,15,30}; MaidNextStage(); Viv.score = 0; Viv.dscore = 0; Viv.exp = 0; Viv.exp2 = 0; Viv.bomb = ConfigDat.BombStock; Viv.left = ConfigDat.PlayerStock; Viv.credit = 4; //5; Viv.bomb_time = 0; Viv.evade_c = Viv.evade = 0; Viv.evadesc = 0; Viv.evade_sum = 0; Viv.GrpID = 1; Viv.muteki = VIVDEAD_VAL; Viv.bGameOver = FALSE; Viv.toge_ex = 0; Viv.toge_time = 0; Viv.lay_time = 0; Viv.lay_grp = 0; Viv.ShiftCounter = 0; Viv.BuzzSound = FALSE; for(i=0;i<256;i++) EvadeRate[i] = i*sct[ConfigDat.GameLevel]; } // 次のステージの準備 // extern void MaidNextStage(void) { Viv.x = Viv.opx = SX_START; Viv.y = Viv.opx = SY_START; Viv.vx = 0; Viv.vy = 0; Viv.toge_ex = 0; Viv.toge_time = 0; Viv.lay_time = 0; Viv.lay_grp = 0; Viv.muteki = VIVDEAD_VAL; Viv.bomb_time = 0; Viv.ShiftCounter = 0; Viv.BuzzSound = FALSE; } extern void MaidDead(void) { int i; #ifdef PBG_DEBUG if(!DebugDat.Hit) return; #endif fragment_set(Viv.x,Viv.y,FRG_FATCIRCLE); for(i=0; i<50; i++) fragment_set(Viv.x,Viv.y,FRG_HEART); SndPlay(SOUND_ID_DEAD); // 座標系セット // Viv.x = Viv.opx = SX_START; Viv.y = Viv.opx = SY_START; Viv.vx = 0; Viv.vy = 0; // かすり系リセット // // Viv.evade_c = 0; // Viv.evade = 0; // Viv.evadesc = 0; Viv.lay_time = 0; Viv.lay_grp = 0; Viv.bomb = ConfigDat.BombStock; Viv.muteki = VIVDEAD_VAL; PlayRankAdd(-2560); if(Viv.left){ // 残機の残っている場合 // Viv.left -= 1; } else{ // 残機の残っていない場合 // Viv.bGameOver = TRUE; Viv.score += Viv.dscore; // 得点吐き出し // かすり系リセット // Viv.evade_c = 0; Viv.evade = 0; Viv.evadesc = 0; GameOverInit(); // ゲームオーバーへと } tama_clear(); laser_clear(); } // かすりゲージを上昇させる(エフェクトはメイド中心) // extern FVOID evade_add(BYTE n) { evade_addEx(Viv.x,Viv.y,n); } // 指定座標からエフェクト発生&ゲージ上昇 // extern FVOID evade_addEx(int x,int y,BYTE n) { int i; PlayRankAdd(n<<2); if(n){ if(Viv.BuzzSound == FALSE){ SndPlayEX(SOUND_ID_BUZZ,x,0); Viv.BuzzSound = TRUE; } fragment_set(x,y,FRG_EVADE); fragment_set(x,y,FRG_EVADE); fragment_set(x,y,FRG_EVADE); } for(i=0;i<n;i++){ if(Viv.evade==999){ Viv.evade_c = 1; return; } Viv.evade += 1; Viv.evade_sum += 1; Viv.evadesc += Viv.evade*20; } if(Viv.evade) Viv.evade_c = EVADETIME_MAX; } // スコアを上昇させる // extern void score_add(int sc) { Viv.dscore += sc; }
0
0.710625
1
0.710625
game-dev
MEDIA
0.649403
game-dev,graphics-rendering
0.991291
1
0.991291
headlesshq/mc-runtime-test
3,953
1_8_9/src/main/java/me/earth/mc_runtime_test/mixin/MixinMinecraft.java
package me.earth.mc_runtime_test.mixin; import me.earth.mc_runtime_test.McRuntimeTest; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.gui.GuiErrorScreen; import net.minecraft.client.gui.GuiGameOver; import net.minecraft.client.gui.GuiMainMenu; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.multiplayer.WorldClient; import net.minecraft.server.integrated.IntegratedServer; import net.minecraft.world.WorldSettings; import net.minecraft.world.WorldType; import org.apache.logging.log4j.Logger; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import java.util.Random; @Mixin(Minecraft.class) public abstract class MixinMinecraft { @Shadow @Final private static Logger logger; @Shadow private IntegratedServer theIntegratedServer; @Shadow public GuiScreen currentScreen; @Shadow public EntityPlayerSP thePlayer; @Shadow public WorldClient theWorld; @Shadow volatile boolean running; @Unique private boolean mcRuntimeTest$startedLoadingSPWorld = false; @Shadow public abstract void launchIntegratedServer(String par1, String par2, WorldSettings par3); @Shadow public abstract void displayGuiScreen(GuiScreen par1); @Inject(method = "displayGuiScreen", at = @At("HEAD")) private void displayGuiScreenHook(GuiScreen guiScreenIn, CallbackInfo ci) { if (!McRuntimeTest.screenHook()) { return; } if (guiScreenIn instanceof GuiErrorScreen) { running = false; throw new RuntimeException("Error Screen " + guiScreenIn); } else if (guiScreenIn instanceof GuiGameOver && thePlayer != null) { thePlayer.respawnPlayer(); } } @Inject(method = "runTick", at = @At("HEAD")) private void tickHook(CallbackInfo ci) { if (!McRuntimeTest.tickHook()) { return; } if (currentScreen instanceof GuiMainMenu) { if (!mcRuntimeTest$startedLoadingSPWorld) { mc_runtime_test$loadSinglePlayerWorld(); mcRuntimeTest$startedLoadingSPWorld = true; } } else { logger.info("Waiting for overlay to disappear..."); } if (thePlayer != null && theWorld != null) { if (currentScreen == null) { if (!theWorld.getChunkFromChunkCoords(((int) thePlayer.posX) >> 4, ((int) thePlayer.posZ) >> 4).isEmpty()) { if (thePlayer.ticksExisted < 100) { logger.info("Waiting " + (100 - thePlayer.ticksExisted) + " ticks before testing..."); } else { logger.info("Test successful!"); running = false; } } else { logger.info("Players chunk not yet loaded, " + thePlayer + ": cores: " + Runtime.getRuntime().availableProcessors() + ", server running: " + (theIntegratedServer == null ? "null" : theIntegratedServer.isServerRunning())); } } else { logger.info("Screen not yet null: " + currentScreen); } } else { logger.info("Waiting for player to load..."); } } @Unique private void mc_runtime_test$loadSinglePlayerWorld() { displayGuiScreen(null); long seed = (new Random()).nextLong(); WorldSettings worldsettings = new WorldSettings(seed, WorldSettings.GameType.SURVIVAL, true, false, WorldType.DEFAULT); launchIntegratedServer("new_world", "New World", worldsettings); } }
0
0.917506
1
0.917506
game-dev
MEDIA
0.855707
game-dev
0.91739
1
0.91739
hyprwm/wlroots-hyprland
10,012
types/wlr_cursor_shape_v1.c
#include <assert.h> #include <stdlib.h> #include <wayland-server-core.h> #include <wayland-util.h> #include <wlr/types/wlr_cursor_shape_v1.h> #include <wlr/types/wlr_seat.h> #include <wlr/types/wlr_tablet_tool.h> #include "types/wlr_tablet_v2.h" #define CURSOR_SHAPE_MANAGER_V1_VERSION 1 struct wlr_cursor_shape_device_v1 { struct wl_resource *resource; struct wlr_cursor_shape_manager_v1 *manager; enum wlr_cursor_shape_manager_v1_device_type type; struct wlr_seat_client *seat_client; // NULL if device_type is not TABLET_TOOL struct wlr_tablet_v2_tablet_tool *tablet_tool; struct wl_listener seat_client_destroy; struct wl_listener tablet_tool_destroy; }; static const struct wp_cursor_shape_device_v1_interface device_impl; static const struct wp_cursor_shape_manager_v1_interface manager_impl; // Returns NULL if the resource is inert static struct wlr_cursor_shape_device_v1 *device_from_resource(struct wl_resource *resource) { assert(wl_resource_instance_of(resource, &wp_cursor_shape_device_v1_interface, &device_impl)); return wl_resource_get_user_data(resource); } static struct wlr_cursor_shape_manager_v1 *manager_from_resource(struct wl_resource *resource) { assert(wl_resource_instance_of(resource, &wp_cursor_shape_manager_v1_interface, &manager_impl)); return wl_resource_get_user_data(resource); } static void resource_handle_destroy(struct wl_client *client, struct wl_resource *resource) { wl_resource_destroy(resource); } static void device_handle_set_shape(struct wl_client *client, struct wl_resource *device_resource, uint32_t serial, uint32_t shape) { struct wlr_cursor_shape_device_v1 *device = device_from_resource(device_resource); if (device == NULL) { return; } if (shape == 0 || shape > WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_ZOOM_OUT) { wl_resource_post_error(device_resource, WP_CURSOR_SHAPE_DEVICE_V1_ERROR_INVALID_SHAPE, "Invalid shape %"PRIu32, shape); return; } struct wlr_cursor_shape_manager_v1_request_set_shape_event event = { .seat_client = device->seat_client, .device_type = device->type, .tablet_tool = device->tablet_tool, .serial = serial, .shape = shape, }; wl_signal_emit_mutable(&device->manager->events.request_set_shape, &event); } static const struct wp_cursor_shape_device_v1_interface device_impl = { .destroy = resource_handle_destroy, .set_shape = device_handle_set_shape, }; static void device_destroy(struct wlr_cursor_shape_device_v1 *device) { if (device == NULL) { return; } wl_list_remove(&device->seat_client_destroy.link); wl_list_remove(&device->tablet_tool_destroy.link); wl_resource_set_user_data(device->resource, NULL); // make inert free(device); } static void device_handle_resource_destroy(struct wl_resource *resource) { struct wlr_cursor_shape_device_v1 *device = device_from_resource(resource); device_destroy(device); } static void device_handle_seat_client_destroy(struct wl_listener *listener, void *data) { struct wlr_cursor_shape_device_v1 *device = wl_container_of(listener, device, seat_client_destroy); device_destroy(device); } static void device_handle_tablet_tool_destroy(struct wl_listener *listener, void *data) { struct wlr_cursor_shape_device_v1 *device = wl_container_of(listener, device, tablet_tool_destroy); device_destroy(device); } static void create_device(struct wl_resource *manager_resource, uint32_t id, struct wlr_seat_client *seat_client, enum wlr_cursor_shape_manager_v1_device_type type, struct wlr_tablet_v2_tablet_tool *tablet_tool) { struct wlr_cursor_shape_manager_v1 *manager = manager_from_resource(manager_resource); struct wl_client *client = wl_resource_get_client(manager_resource); uint32_t version = wl_resource_get_version(manager_resource); struct wl_resource *device_resource = wl_resource_create(client, &wp_cursor_shape_device_v1_interface, version, id); if (device_resource == NULL) { wl_resource_post_no_memory(manager_resource); return; } wl_resource_set_implementation(device_resource, &device_impl, NULL, device_handle_resource_destroy); if (seat_client == NULL) { return; // leave the resource inert } struct wlr_cursor_shape_device_v1 *device = calloc(1, sizeof(*device)); if (device == NULL) { wl_resource_post_no_memory(manager_resource); return; } assert((type == WLR_CURSOR_SHAPE_MANAGER_V1_DEVICE_TYPE_TABLET_TOOL) == (tablet_tool != NULL)); device->resource = device_resource; device->manager = manager; device->type = type; device->tablet_tool = tablet_tool; device->seat_client = seat_client; device->seat_client_destroy.notify = device_handle_seat_client_destroy; wl_signal_add(&seat_client->events.destroy, &device->seat_client_destroy); if (tablet_tool != NULL) { device->tablet_tool_destroy.notify = device_handle_tablet_tool_destroy; wl_signal_add(&tablet_tool->wlr_tool->events.destroy, &device->tablet_tool_destroy); } else { wl_list_init(&device->tablet_tool_destroy.link); } wl_resource_set_user_data(device_resource, device); } static void manager_handle_get_pointer(struct wl_client *client, struct wl_resource *manager_resource, uint32_t id, struct wl_resource *pointer_resource) { struct wlr_seat_client *seat_client = wlr_seat_client_from_pointer_resource(pointer_resource); create_device(manager_resource, id, seat_client, WLR_CURSOR_SHAPE_MANAGER_V1_DEVICE_TYPE_POINTER, NULL); } static void manager_handle_get_tablet_tool_v2(struct wl_client *client, struct wl_resource *manager_resource, uint32_t id, struct wl_resource *tablet_tool_resource) { struct wlr_tablet_tool_client_v2 *tablet_tool_client = tablet_tool_client_from_resource(tablet_tool_resource); struct wlr_seat_client *seat_client = NULL; struct wlr_tablet_v2_tablet_tool *tablet_tool = NULL; if (tablet_tool_client != NULL && tablet_tool_client->tool != NULL) { seat_client = tablet_tool_client->seat->seat_client; tablet_tool = tablet_tool_client->tool; } create_device(manager_resource, id, seat_client, WLR_CURSOR_SHAPE_MANAGER_V1_DEVICE_TYPE_TABLET_TOOL, tablet_tool); } static const struct wp_cursor_shape_manager_v1_interface manager_impl = { .destroy = resource_handle_destroy, .get_pointer = manager_handle_get_pointer, .get_tablet_tool_v2 = manager_handle_get_tablet_tool_v2, }; static void manager_bind(struct wl_client *client, void *data, uint32_t version, uint32_t id) { struct wlr_cursor_shape_manager_v1 *manager = data; struct wl_resource *resource = wl_resource_create(client, &wp_cursor_shape_manager_v1_interface, version, id); if (resource == NULL) { wl_client_post_no_memory(client); return; } wl_resource_set_implementation(resource, &manager_impl, manager, NULL); } static void handle_display_destroy(struct wl_listener *listener, void *data) { struct wlr_cursor_shape_manager_v1 *manager = wl_container_of(listener, manager, display_destroy); wl_signal_emit_mutable(&manager->events.destroy, NULL); assert(wl_list_empty(&manager->events.destroy.listener_list)); wl_global_destroy(manager->global); wl_list_remove(&manager->display_destroy.link); free(manager); } struct wlr_cursor_shape_manager_v1 *wlr_cursor_shape_manager_v1_create( struct wl_display *display, uint32_t version) { assert(version <= CURSOR_SHAPE_MANAGER_V1_VERSION); struct wlr_cursor_shape_manager_v1 *manager = calloc(1, sizeof(*manager)); if (manager == NULL) { return NULL; } manager->global = wl_global_create(display, &wp_cursor_shape_manager_v1_interface, version, manager, manager_bind); if (manager->global == NULL) { free(manager); return NULL; } wl_signal_init(&manager->events.request_set_shape); wl_signal_init(&manager->events.destroy); manager->display_destroy.notify = handle_display_destroy; wl_display_add_destroy_listener(display, &manager->display_destroy); return manager; } static const char *const shape_names[] = { [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_DEFAULT] = "default", [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_CONTEXT_MENU] = "context-menu", [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_HELP] = "help", [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_POINTER] = "pointer", [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_PROGRESS] = "progress", [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_WAIT] = "wait", [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_CELL] = "cell", [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_CROSSHAIR] = "crosshair", [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_TEXT] = "text", [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_VERTICAL_TEXT] = "vertical-text", [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_ALIAS] = "alias", [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_COPY] = "copy", [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_MOVE] = "move", [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NO_DROP] = "no-drop", [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NOT_ALLOWED] = "not-allowed", [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_GRAB] = "grab", [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_GRABBING] = "grabbing", [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_E_RESIZE] = "e-resize", [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_N_RESIZE] = "n-resize", [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NE_RESIZE] = "ne-resize", [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NW_RESIZE] = "nw-resize", [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_S_RESIZE] = "s-resize", [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_SE_RESIZE] = "se-resize", [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_SW_RESIZE] = "sw-resize", [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_W_RESIZE] = "w-resize", [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_EW_RESIZE] = "ew-resize", [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NS_RESIZE] = "ns-resize", [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NESW_RESIZE] = "nesw-resize", [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NWSE_RESIZE] = "nwse-resize", [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_COL_RESIZE] = "col-resize", [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_ROW_RESIZE] = "row-resize", [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_ALL_SCROLL] = "all-scroll", [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_ZOOM_IN] = "zoom-in", [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_ZOOM_OUT] = "zoom-out", }; const char *wlr_cursor_shape_v1_name(enum wp_cursor_shape_device_v1_shape shape) { assert(shape < sizeof(shape_names) / sizeof(shape_names[0])); return shape_names[shape]; }
0
0.944691
1
0.944691
game-dev
MEDIA
0.529202
game-dev
0.504848
1
0.504848
googlecreativelab/Sprayscape
12,232
Sprayscape/Assets/Cardboard/Editor/CardboardSetup.cs
// Copyright 2015 Google Inc. All rights reserved. // // 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. using UnityEngine; using UnityEditor; using System.Collections; using System.Collections.Generic; using UnityEngine.EventSystems; public class CardboardSetup : EditorWindow { // Camera objects. private string[] cameraNames; private GameObject[] cameraObjects; // Is there a Cardboard camera already? private bool foundCardboardCamera = false; private bool addReticle = false; // Currently selected camera in the dialog. private int selectedCamera = -1; public static void ShowWindow () { // Get existing open window or if none, make a new one: CardboardSetup window = (CardboardSetup)EditorWindow.GetWindow(typeof(CardboardSetup)); // Setup the window. window.FindCameras(); window.AdjustWindowSize(); window.Show(); } /// Unity callback called when the hierarchy is change. void OnHierarchyChange() { // Update the cameras. FindCameras(); AdjustWindowSize(); } // Render the dialog. void OnGUI () { // // Info text. // GUILayout.BeginVertical("Box"); GUILayout.Label("Preview your work with a stereoscopic camera and a " + "Cardboard viewer.", EditorStyles.wordWrappedLabel); GUILayout.Label("Would you like to add a new camera (ideal option), or " + "modify one of the existing cameras to add stereoscopic rendering " + "support?", EditorStyles.wordWrappedLabel); GUILayout.EndVertical(); // // Camera choice. // GUILayout.Label ("Select Camera for Cardbard Support:", EditorStyles.boldLabel); GUILayout.BeginVertical("Box"); // New camera. GUILayout.Label ("Add a new camera:"); // Is there a Cardboard camera already? if (foundCardboardCamera) { // Warn the user. GUILayout.Label ("An existing Cardboard camera detected. Are you sure " + "you need another?", EditorStyles.wordWrappedMiniLabel); } HandleCameraToggleObject(0); GUILayout.Space(10); // Existing camera. GUILayout.Label ("Modify an existing camera:"); for (int i = 1; i < cameraNames.Length; ++i) { HandleCameraToggleObject(i); } // No cameras in the scene. if (cameraNames.Length <= 1) { GUILayout.Label ("No available cameras found in the scene.", EditorStyles.boldLabel); } GUILayout.EndVertical(); GUILayout.Space(20); // // Cardboard Settings. // GUILayout.Label ("Cardboard Settings", EditorStyles.boldLabel); GUILayout.BeginVertical("Box"); // Reticle. addReticle = GUILayout.Toggle(addReticle, "Reticle support"); GUILayout.EndVertical(); GUILayout.Space(20); // // Confirmation buttons. // // Use up all available space. GUILayout.FlexibleSpace(); GUILayout.BeginHorizontal(); // Apply button. if (GUILayout.Button("Apply")) { if (selectedCamera >= 0 && selectedCamera < cameraObjects.Length) { // Apply user's choice. ApplyCamera(selectedCamera); AddCardboardManager(); } Close(); } // Cancel. if (GUILayout.Button("Cancel")) { Close(); } GUILayout.EndHorizontal(); GUILayout.Space(5); } // Find all the cameras and add them to the arrays. private void FindCameras() { // Lists to hold objects. List<string> cameraNamesList = new List<string>(); List<GameObject> cameraObjectsList = new List<GameObject>(); // Retrieve all cameras. Camera[] cameras = FindObjectsOfType(typeof(Camera)) as Camera[]; // Retrieve applicable cameras. for (int i = 0; i < cameras.Length; ++i) { Camera camera = cameras[i]; GameObject gameObject = camera.gameObject; // Skip cameras with Cardboard scripts on them. if (gameObject.GetComponent<CardboardEye>() == null && gameObject.GetComponent<CardboardPreRender>() == null && gameObject.GetComponent<CardboardPostRender>() == null) { // Valid camera! cameraNamesList.Add(gameObject.name); cameraObjectsList.Add(gameObject); // Is there a StereoController? if (gameObject.GetComponent<StereoController>() != null) { // Found a StereoController Cardboard camera script. // Should notify the user a Cardboard camera already exists. foundCardboardCamera = true; } } else { // Found some sort of Cardboard camera script. // Should notify the user something is out there. foundCardboardCamera = true; } } // Add new camera option. cameraNamesList.Insert(0, "Cardboard Camera"); cameraObjectsList.Insert(0, null); // Convert lists to nice and lovely arrays. cameraNames = cameraNamesList.ToArray(); cameraObjects = cameraObjectsList.ToArray(); } private void ApplyCamera(int selection) { // Select the correct camera to add Cardboard support to. if (selection == 0) { // Index 0 means add a new camera. AddNewCamera(); } else { // Everything else modifies an existing camera. ModifyCamera(cameraObjects[selection]); } } private void ModifyCamera(GameObject cameraObject) { // Select the camera object in the editor. Selection.activeObject = cameraObject; // Register object for undo. //Undo.RegisterCompleteObjectUndo(cameraObject, "Added Cardboard support"); // Attempt finding existing controller. StereoController stereoController = cameraObject.GetComponent<StereoController>(); // Otherwise, if (stereoController == null) { // Add a stereo controller. stereoController= cameraObject.AddComponent<StereoController>(); } // Add the stereo setup. stereoController.AddStereoRig(); // Add reticle support. AddReticleSupport(cameraObject); } private void AddNewCamera() { // Create a new camera. GameObject instance = new GameObject("Cardboard Camera"); instance.AddComponent<Camera>(); // Add Cardboard support ModifyCamera(instance); } private void AddReticleSupport(GameObject gameObject) { // User wants a reticle? if (addReticle) { // Retrieve the reticle asset. Object asset = UnityEditor.AssetDatabase.LoadAssetAtPath( "Assets/Cardboard/Prefabs/UI/CardboardReticle.prefab", typeof(GameObject)); if (asset == null) { // Show there was an error. EditorUtility.DisplayDialog("Failed to create Reticle", "CardboardReticle.prefab not found. Did you move the Cardboard " + "assets directory? Expected location: \"Assets/Cardboard/Prefabs" + "/UI/CardboardReticle.prefab\"", "Maybe?.."); return; } // Find head. Reticle should be child of head. CardboardHead head = gameObject.GetComponentInChildren<CardboardHead>(); if (head) { // Found head! Refer its GameObject. GameObject headObject = head.gameObject; // Instantiate reticle. GameObject instance = Object.Instantiate(asset) as GameObject; instance.name = asset.name; // removes the (clone) from the name. // Set as child of CardboardHead object. instance.transform.SetParent(headObject.transform, false); } // Add modules to support uGUI. AddGazeInputModule(); AddPhysicsRaycasterToCamera(gameObject); } } private void HandleCameraToggleObject(int index) { if (index < 0 || index >= cameraNames.Length) { return; } // Show the camera toggle. bool selected = GUILayout.Toggle((selectedCamera == index), cameraNames[index], EditorStyles.radioButton); // Handle selection. if (selected) { selectedCamera = index; } } // Adds the physics raycaster component // to the correct object in the hierarchy. private void AddPhysicsRaycasterToCamera(GameObject cardboardHead) { // Find existing raycaster. PhysicsRaycaster raycaster = cardboardHead.GetComponent<PhysicsRaycaster>(); // Otherwise, if (raycaster == null) { // Add the raycaster. raycaster = cardboardHead.AddComponent<PhysicsRaycaster>(); } // Remove Ignore Raycast layer from the event mask. raycaster.eventMask &= ~(1 <<LayerMask.NameToLayer("Ignore Raycast")); } // Add cardboard manager and pre/post rendering. private void AddCardboardManager() { GameObject managerObject = null; // Is there a pre-render / post-render object? Object[] preRenders = FindObjectsOfType(typeof(CardboardPreRender)); Object[] postRenders = FindObjectsOfType(typeof(CardboardPostRender)); if ((preRenders == null || preRenders.Length == 0) && (postRenders == null || postRenders.Length == 0)) { // Retrieve the asset. Object asset = UnityEditor.AssetDatabase.LoadAssetAtPath( "Assets/Cardboard/Prefabs/CardboardCamera.prefab", typeof(GameObject)); if (asset == null) { // Show there was an error. EditorUtility.DisplayDialog("Failed to create CardboardCamera", "CardboardCamera.prefab not found. Did you move the Cardboard " + "assets directory? Expected location: \"Assets/Cardboard/Prefabs" + "/CardboardCamera.prefab\"", "Maybe?.."); return; } // Instantiate the object. managerObject = Object.Instantiate(asset) as GameObject; managerObject.name = "Cardboard Manager"; } // Is there a Cardboard script already? // Must only be one Cardboard script. Cardboard[] cardboardInstances = FindObjectsOfType(typeof(Cardboard)) as Cardboard[]; if (cardboardInstances == null || cardboardInstances.Length == 0) { // If we made a pre/post renderer, // then add the script to the same object. if (managerObject == null) { // otherwise, create a new object. managerObject = new GameObject(); managerObject.name = "Cardboard Manager"; } // Add the cardboard script. managerObject.AddComponent<Cardboard>(); } } // Add Gaze Input Module to EventSystem. // Handle existing EventSystems and new EventSystems. private void AddGazeInputModule() { // The object we are adding the Input Module to. GameObject eventSystemObject = null; // Find existing event systems. Object[] eventSystems = FindObjectsOfType(typeof(EventSystem)); if (eventSystems == null || eventSystems.Length == 0) { // If none, create a new one. eventSystemObject = new GameObject("EventSystem"); eventSystemObject.AddComponent<EventSystem>(); } else { // If there is one, use the first one. eventSystemObject = ((EventSystem)eventSystems[0]).gameObject; } // Get the list of components for fixing the module's priority. Component[] components = eventSystemObject.GetComponents<Component>(); // Add the GazeInputModule. GazeInputModule gazeInputModule = eventSystemObject.AddComponent<GazeInputModule>(); // Make sure the GazeInputModule is at the top of the components list. for (int i = 0; i < components.Length; ++i) { UnityEditorInternal.ComponentUtility.MoveComponentUp(gazeInputModule); } } private void AdjustWindowSize() { const float kMinWidth = 403.0f; const float kMinHeight = 290.0f; // Modify the height to accomodate additional cameras. int heightModifer = 0; if (cameraNames != null) { heightModifer += 12 * cameraNames.Length; } // Restrict minimum window size. minSize = new Vector2(kMinWidth, kMinHeight + heightModifer); } }
0
0.805739
1
0.805739
game-dev
MEDIA
0.663178
game-dev,graphics-rendering
0.850496
1
0.850496
XFactHD/FramedBlocks
4,447
src/main/java/io/github/xfacthd/framedblocks/client/screen/overlay/impl/ToggleYSlopeOverlay.java
package io.github.xfacthd.framedblocks.client.screen.overlay.impl; import io.github.xfacthd.framedblocks.api.block.FramedProperties; import io.github.xfacthd.framedblocks.api.screen.overlay.BlockInteractOverlay; import io.github.xfacthd.framedblocks.api.util.Utils; import io.github.xfacthd.framedblocks.common.FBContent; import io.github.xfacthd.framedblocks.common.block.IComplexSlopeSource; import io.github.xfacthd.framedblocks.common.config.ClientConfig; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.neoforged.neoforge.common.util.ConcatenatedListView; import java.util.List; public final class ToggleYSlopeOverlay extends BlockInteractOverlay { public static final String SLOPE_MESSAGE = Utils.translationKey("tooltip", "y_slope"); public static final String TOGGLE_MESSAGE = Utils.translationKey("tooltip", "y_slope.toggle"); public static final String SLOPE_MESSAGE_ALT = Utils.translationKey("tooltip", "y_slope.alt"); public static final String TOGGLE_MESSAGE_ALT = Utils.translationKey("tooltip", "y_slope.alt.toggle"); public static final Component SLOPE_HOR = Utils.translate("tooltip", "y_slope.horizontal"); public static final Component SLOPE_VERT = Utils.translate("tooltip", "y_slope.vertical"); public static final Component SLOPE_FRONT = Utils.translate("tooltip", "y_slope.front"); public static final Component SLOPE_SIDE = Utils.translate("tooltip", "y_slope.side"); private static final List<Component> LINES_FALSE = List.of( Component.translatable(SLOPE_MESSAGE, SLOPE_HOR), Component.translatable(TOGGLE_MESSAGE, SLOPE_VERT) ); private static final List<Component> LINES_TRUE = List.of( Component.translatable(SLOPE_MESSAGE, SLOPE_VERT), Component.translatable(TOGGLE_MESSAGE, SLOPE_HOR) ); private static final List<Component> LINES_FALSE_ALT = List.of( Component.translatable(SLOPE_MESSAGE_ALT, SLOPE_FRONT), Component.translatable(TOGGLE_MESSAGE_ALT, SLOPE_SIDE) ); private static final List<Component> LINES_TRUE_ALT = List.of( Component.translatable(SLOPE_MESSAGE_ALT, SLOPE_SIDE), Component.translatable(TOGGLE_MESSAGE_ALT, SLOPE_FRONT) ); private static final List<Component> LINES_FALSE_ALL = ConcatenatedListView.of(LINES_FALSE, LINES_FALSE_ALT); private static final List<Component> LINES_TRUE_ALL = ConcatenatedListView.of(LINES_TRUE, LINES_TRUE_ALT); private static final ResourceLocation SYMBOL_TEXTURE = Utils.rl("textures/overlay/yslope_symbols.png"); private static final Texture TEXTURE_FALSE = new Texture(SYMBOL_TEXTURE, 0, 0, 20, 40, 80, 40); private static final Texture TEXTURE_TRUE = new Texture(SYMBOL_TEXTURE, 20, 0, 20, 40, 80, 40); private static final Texture TEXTURE_ALT_FALSE = new Texture(SYMBOL_TEXTURE, 40, 0, 20, 40, 80, 40); private static final Texture TEXTURE_ALT_TRUE = new Texture(SYMBOL_TEXTURE, 60, 0, 20, 40, 80, 40); public ToggleYSlopeOverlay() { super(LINES_FALSE_ALL, LINES_TRUE_ALL, TEXTURE_FALSE, TEXTURE_TRUE, ClientConfig.VIEW::getToggleYSlopeMode); } @Override public boolean isValidTool(Player player, ItemStack stack) { return stack.getItem() == FBContent.ITEM_FRAMED_WRENCH.value(); } @Override public boolean isValidTarget(Target target) { return target.state().hasProperty(FramedProperties.Y_SLOPE); } @Override public boolean getState(Target target) { return target.state().getValue(FramedProperties.Y_SLOPE); } @Override public Texture getTexture(Target target, boolean state) { if (target.state().getBlock() instanceof IComplexSlopeSource src && src.isHorizontalSlope(target.state())) { return state ? TEXTURE_ALT_TRUE : TEXTURE_ALT_FALSE; } return super.getTexture(target, state); } @Override public List<Component> getLines(Target target, boolean state) { if (target.state().getBlock() instanceof IComplexSlopeSource src && src.isHorizontalSlope(target.state())) { return state ? LINES_TRUE_ALT : LINES_FALSE_ALT; } else { return state ? LINES_TRUE : LINES_FALSE; } } }
0
0.903084
1
0.903084
game-dev
MEDIA
0.74966
game-dev,graphics-rendering
0.882994
1
0.882994
lykoss/lykos
12,605
src/relay.py
from __future__ import annotations import sys from src.events import event_listener from src.decorators import command from src.containers import UserSet from src.functions import get_players, get_participants from src.messages import messages from src.events import Event from src.users import User from src.cats import role_order, Wolf, Wolfchat, Vampire from src import config, channels, db from src.dispatcher import MessageDispatcher from src.gamestate import GameState DEADCHAT_PLAYERS: UserSet = UserSet() DEADCHAT_SPECTATE: UserSet = UserSet() WOLFCHAT_SPECTATE: UserSet = UserSet() VAMPCHAT_SPECTATE: UserSet = UserSet() @command("", chan=False, pm=True) def relay_wolfchat(wrapper: MessageDispatcher, message: str): """Relay wolfchat/vampchat messages and commands.""" var = wrapper.game_state if message.startswith(config.Main.get("transports[0].user.command_prefix")): return if "src.roles.helper.wolves" in sys.modules: from src.roles.helper.wolves import get_talking_roles wolfchat = get_players(var, get_talking_roles()) else: wolfchat = get_players(var, Wolfchat) wolves = get_players(var, Wolf) vampires = get_players(var, Vampire) if wrapper.source in wolfchat and len(wolfchat) > 1: # handle wolfchat toggles if not config.Main.get("gameplay.wolfchat.traitor_non_wolf"): wolves.extend(get_players(var, ("traitor",))) if var.current_phase == "night" and config.Main.get("gameplay.wolfchat.disable_night"): return elif var.current_phase == "day" and config.Main.get("gameplay.wolfchat.disable_day"): return elif wrapper.source not in wolves and config.Main.get("gameplay.wolfchat.wolves_only_chat"): return elif wrapper.source not in wolves and config.Main.get("gameplay.wolfchat.remove_non_wolves"): return wolfchat.remove(wrapper.source) send_to = wolfchat spectators = WOLFCHAT_SPECTATE spectate_key_suffix = "_wolfchat" elif wrapper.source in vampires and len(vampires) > 1: # handle vampire chat toggles; they use the same config as wolfchat if var.current_phase == "night" and config.Main.get("gameplay.wolfchat.disable_night"): return elif var.current_phase == "day" and config.Main.get("gameplay.wolfchat.disable_day"): return vampires.remove(wrapper.source) send_to = vampires spectators = VAMPCHAT_SPECTATE spectate_key_suffix = "_vampchat" else: # not sending anything return key = "relay_message" if message.startswith("\u0001ACTION") and message[-1] == "\u0001": key = "relay_action" message = message[8:-1] for player in send_to: player.queue_message(messages[key].format(wrapper.source, message)) for player in spectators: # full keys used, for grep: # relay_message_wolfchat relay_action_wolfchat relay_message_vampchat relay_action_vampchat player.queue_message(messages[key + spectate_key_suffix].format(wrapper.source, message)) User.send_messages() @command("", chan=False, pm=True) def relay_deadchat(wrapper: MessageDispatcher, message: str): """Relay deadchat messages.""" if message.startswith(config.Main.get("transports[0].user.command_prefix")): return if wrapper.source not in get_players(wrapper.game_state) and config.Main.get("gameplay.deadchat") and wrapper.source in DEADCHAT_PLAYERS: # relay_message_deadchat and relay_action_deadchat also used here key = "relay_message" if message.startswith("\u0001ACTION"): key = "relay_action" message = message[8:-1] for user in DEADCHAT_PLAYERS - {wrapper.source}: user.queue_message(messages[key].format(wrapper.source, message)) for user in DEADCHAT_SPECTATE: user.queue_message(messages[key + "_deadchat"].format(wrapper.source, message)) User.send_messages() def try_restricted_cmd(wrapper: MessageDispatcher, key: str) -> bool: # if allowed in normal games, restrict it so that it can only be used by dead players and # non-players (don't allow active vengeful ghosts either). # also don't allow in-channel (e.g. make it pm only) if config.Main.get("debug.enabled"): return True pl = get_participants(wrapper.game_state) if wrapper.source in pl: wrapper.pm(messages[key]) return False if wrapper.source.account in {player.account for player in pl}: wrapper.pm(messages[key]) return False return True def spectate_chat(wrapper: MessageDispatcher, message: str, *, is_fspectate: bool): if not try_restricted_cmd(wrapper, "spectate_restricted"): return var = wrapper.game_state params = message.split(" ") on = "on" if not len(params): wrapper.pm(messages["fspectate_help" if is_fspectate else "spectate_help"]) return elif len(params) > 1: on = params[1].lower() what = params[0].lower() allowed = ("wolfchat", "vampchat", "deadchat") if is_fspectate else ("wolfchat", "vampchat") if what not in allowed or on not in ("on", "off"): wrapper.pm(messages["fspectate_help" if is_fspectate else "spectate_help"]) return if on == "off": if what == "wolfchat": WOLFCHAT_SPECTATE.discard(wrapper.source) elif what == "vampchat": VAMPCHAT_SPECTATE.discard(wrapper.source) else: DEADCHAT_SPECTATE.discard(wrapper.source) wrapper.pm(messages["spectate_off_{0}".format(what)]) else: if what in ("wolfchat", "vampchat"): if what == "wolfchat": already_spectating = wrapper.source in WOLFCHAT_SPECTATE WOLFCHAT_SPECTATE.add(wrapper.source) players = list(get_players(var, Wolfchat)) if "src.roles.helper.wolves" in sys.modules: from src.roles.helper.wolves import is_known_wolf_ally players = [p for p in players if is_known_wolf_ally(var, p, p)] else: already_spectating = wrapper.source in VAMPCHAT_SPECTATE VAMPCHAT_SPECTATE.add(wrapper.source) players = list(get_players(var, Vampire)) if "src.roles.vampire" in sys.modules: from src.roles.vampire import is_known_vampire_ally players = [p for p in players if is_known_vampire_ally(var, p, p)] if not is_fspectate and not already_spectating and config.Main.get("gameplay.spectate.notice"): if config.Main.get("gameplay.spectate.include_user"): # keys used: spectate_wolfchat_notice_user spectate_vampchat_notice_user key = "spectate_{0}_notice_user".format(what) else: # keys used: spectate_wolfchat_notice spectate_vampchat_notice key = "spectate_{0}_notice".format(what) for player in players: player.queue_message(messages[key].format(wrapper.source)) if players: User.send_messages() elif config.Main.get("gameplay.deadchat"): if wrapper.source in DEADCHAT_PLAYERS: wrapper.pm(messages["spectate_in_deadchat"]) return DEADCHAT_SPECTATE.add(wrapper.source) players = DEADCHAT_PLAYERS else: wrapper.pm(messages["spectate_deadchat_disabled"]) return # keys used: spectate_on_deadchat spectate_on_wolfchat spectate_on_vampchat wrapper.pm(messages["spectate_on_{0}".format(what)]) wrapper.pm(messages["players_list"].format(players)) @command("spectate", flag="p", pm=True, in_game_only=True) def spectate(wrapper: MessageDispatcher, message: str): """Spectate wolfchat, vampire chat, or deadchat.""" spectate_chat(wrapper, message, is_fspectate=False) @command("fspectate", flag="F", pm=True, in_game_only=True) def fspectate(wrapper: MessageDispatcher, message: str): """Spectate wolfchat, vampire chat, or deadchat.""" spectate_chat(wrapper, message, is_fspectate=True) @command("revealroles", flag="a", pm=True, in_game_only=True) def revealroles(wrapper: MessageDispatcher, message: str): """Reveal role information.""" if not try_restricted_cmd(wrapper, "temp_invalid_perms"): return var = wrapper.game_state output = [] for role in role_order(): if var.roles.get(role): # make a copy since this list is modified users = list(var.roles[role]) out = [] # go through each nickname, adding extra info if necessary for user in users: evt = Event("revealroles_role", {"special_case": []}) evt.dispatch(var, user, role) special_case: list[str] = evt.data["special_case"] if not evt.prevent_default and user not in var.original_roles[role] and role not in var.current_mode.SECONDARY_ROLES: for old_role in role_order(): # order doesn't matter here, but oh well if user in var.original_roles[old_role] and user not in var.roles[old_role]: special_case.append(messages["revealroles_old_role"].format(old_role)) break if special_case: out.append(messages["revealroles_special"].format(user, special_case)) else: out.append(user) output.append(messages["revealroles_output"].format(role, out)) evt = Event("revealroles", {"output": output}) evt.dispatch(var) if config.Main.get("debug.enabled"): wrapper.send(*output, sep=" | ") else: wrapper.pm(*output, sep=" | ") def join_deadchat(var: GameState, *all_users: User): if not config.Main.get("gameplay.deadchat") or not var.in_game: return to_join: list[User] = [] pl = get_participants(var) for user in all_users: if user.stasis_count() or user in pl or user in DEADCHAT_PLAYERS or user not in channels.Main.users: continue to_join.append(user) if not to_join: return msg = messages["player_joined_deadchat"].format(to_join) people = set(DEADCHAT_PLAYERS).union(to_join) # .union() creates a new UserSet instance, but we don't want that for user in DEADCHAT_PLAYERS: user.queue_message(msg) for user in DEADCHAT_SPECTATE: user.queue_message(messages["relay_command_deadchat"].format(msg)) for user in to_join: user.queue_message(messages["joined_deadchat"]) user.queue_message(messages["players_list"].format(list(people))) DEADCHAT_PLAYERS.update(to_join) DEADCHAT_SPECTATE.difference_update(to_join) User.send_messages() # send all messages at once def leave_deadchat(var: GameState, user: User, *, force=None): if not config.Main.get("gameplay.deadchat") or not var.in_game or user not in DEADCHAT_PLAYERS: return DEADCHAT_PLAYERS.remove(user) if force is None: user.send(messages["leave_deadchat"]) msg = messages["player_left_deadchat"].format(user) else: user.send(messages["force_leave_deadchat"].format(force)) msg = messages["player_force_leave_deadchat"].format(user, force) if DEADCHAT_PLAYERS or DEADCHAT_SPECTATE: for user in DEADCHAT_PLAYERS: user.queue_message(msg) for user in DEADCHAT_SPECTATE: user.queue_message(messages["relay_command_deadchat"].format(msg)) User.send_messages() @command("deadchat", pm=True) def deadchat_pref(wrapper: MessageDispatcher, message: str): """Toggles auto joining deadchat on death.""" if not config.Main.get("gameplay.deadchat"): return temp = wrapper.source.lower() if not wrapper.source.account: wrapper.pm(messages["not_logged_in"]) return if temp.account in db.DEADCHAT_PREFS: wrapper.pm(messages["chat_on_death"]) db.DEADCHAT_PREFS.remove(temp.account) else: wrapper.pm(messages["no_chat_on_death"]) db.DEADCHAT_PREFS.add(temp.account) db.toggle_deadchat(temp.account) @event_listener("reset") def on_reset(evt, var): DEADCHAT_PLAYERS.clear() DEADCHAT_SPECTATE.clear() WOLFCHAT_SPECTATE.clear()
0
0.924229
1
0.924229
game-dev
MEDIA
0.839851
game-dev
0.948819
1
0.948819
mekanism/Mekanism
1,482
src/main/java/mekanism/common/content/tank/TankCache.java
package mekanism.common.content.tank; import mekanism.api.SerializationConstants; import mekanism.common.lib.multiblock.MultiblockCache; import mekanism.common.tile.interfaces.IFluidContainerManager.ContainerEditMode; import mekanism.common.util.NBTUtils; import net.minecraft.core.HolderLookup; import net.minecraft.nbt.CompoundTag; public class TankCache extends MultiblockCache<TankMultiblockData> { private ContainerEditMode editMode = ContainerEditMode.BOTH; @Override public void merge(MultiblockCache<TankMultiblockData> mergeCache, RejectContents rejectContents) { super.merge(mergeCache, rejectContents); editMode = ((TankCache) mergeCache).editMode; } @Override public void apply(HolderLookup.Provider provider, TankMultiblockData data) { super.apply(provider, data); data.editMode = editMode; } @Override public void sync(TankMultiblockData data) { super.sync(data); editMode = data.editMode; } @Override public void load(HolderLookup.Provider provider, CompoundTag nbtTags) { super.load(provider, nbtTags); NBTUtils.setEnumIfPresent(nbtTags, SerializationConstants.EDIT_MODE, ContainerEditMode.BY_ID, mode -> editMode = mode); } @Override public void save(HolderLookup.Provider provider, CompoundTag nbtTags) { super.save(provider, nbtTags); NBTUtils.writeEnum(nbtTags, SerializationConstants.EDIT_MODE, editMode); } }
0
0.885399
1
0.885399
game-dev
MEDIA
0.961032
game-dev
0.783762
1
0.783762
526077247/ETPro
2,819
Unity/Codes/Model/Generate/Config/SkillJudgeConfig.cs
using System; using System.Collections.Generic; using MongoDB.Bson.Serialization.Attributes; using ProtoBuf; namespace ET { [ProtoContract] [Config] public partial class SkillJudgeConfigCategory : ProtoObject, IMerge { public static SkillJudgeConfigCategory Instance; [ProtoIgnore] [BsonIgnore] private Dictionary<int, SkillJudgeConfig> dict = new Dictionary<int, SkillJudgeConfig>(); [BsonElement] [ProtoMember(1)] private List<SkillJudgeConfig> list = new List<SkillJudgeConfig>(); public SkillJudgeConfigCategory() { Instance = this; } public void Merge(object o) { SkillJudgeConfigCategory s = o as SkillJudgeConfigCategory; this.list.AddRange(s.list); } public override void EndInit() { for(int i =0 ;i<list.Count;i++) { SkillJudgeConfig config = list[i]; config.EndInit(); this.dict.Add(config.Id, config); } this.AfterEndInit(); } public SkillJudgeConfig Get(int id) { this.dict.TryGetValue(id, out SkillJudgeConfig item); if (item == null) { throw new Exception($"配置找不到,配置表名: {nameof (SkillJudgeConfig)},配置id: {id}"); } return item; } public bool Contain(int id) { return this.dict.ContainsKey(id); } public Dictionary<int, SkillJudgeConfig> GetAll() { return this.dict; } public List<SkillJudgeConfig> GetAllList() { return this.list; } public SkillJudgeConfig GetOne() { if (this.dict == null || this.dict.Count <= 0) { return null; } return this.dict.Values.GetEnumerator().Current; } } [ProtoContract] public partial class SkillJudgeConfig: ProtoObject, IConfig { /// <summary>Id</summary> [ProtoMember(1)] public int Id { get; set; } /// <summary>碰撞体类型类型(0固定位置碰撞体1固定朝向碰撞体2指定位置飞行碰撞体3朝向飞行碰撞体(锁定)4目标立刻结算)</summary> [ProtoMember(2)] public int ColliderType { get; set; } /// <summary>起始位置(1自身,2目标,3鼠标位置)</summary> [ProtoMember(3)] public int StartPosType { get; set; } /// <summary>碰撞体持续时间(单位:毫秒)</summary> [ProtoMember(4)] public int Time { get; set; } /// <summary>碰撞体形状(0.立即判断;1.矩形;2.圆形;3.扇形)</summary> [ProtoMember(5)] public int ColliderShape { get; set; } /// <summary>碰撞体形状参数(m)</summary> [ProtoMember(6)] public float[] ColliderPara { get; set; } /// <summary>速度(m/s)</summary> [ProtoMember(7)] public float Speed { get; set; } } }
0
0.75456
1
0.75456
game-dev
MEDIA
0.451938
game-dev,networking
0.560973
1
0.560973
MrCrayfish/MrCrayfishFurnitureMod-Refurbished
3,175
common/src/main/java/com/mrcrayfish/furniture/refurbished/block/BasinBlock.java
package com.mrcrayfish.furniture.refurbished.block; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.mrcrayfish.furniture.refurbished.blockentity.BasinBlockEntity; import com.mrcrayfish.furniture.refurbished.core.ModBlockEntities; import com.mrcrayfish.furniture.refurbished.data.tag.BlockTagSupplier; import com.mrcrayfish.furniture.refurbished.util.VoxelShapeHelper; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.tags.BlockTags; import net.minecraft.tags.TagKey; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityTicker; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.shapes.VoxelShape; import org.jetbrains.annotations.Nullable; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * Author: MrCrayfish */ public abstract class BasinBlock extends FurnitureHorizontalEntityBlock implements BlockTagSupplier { public BasinBlock(Properties properties) { super(properties); this.registerDefaultState(this.getStateDefinition().any().setValue(DIRECTION, Direction.NORTH)); } @Override protected Map<BlockState, VoxelShape> generateShapes(ImmutableList<BlockState> states) { VoxelShape basinShape = Block.box(2, 9, 0, 16, 16, 16); VoxelShape supportShape = Block.box(7, 0, 4, 13, 9, 12); VoxelShape combinedShape = VoxelShapeHelper.combine(List.of(basinShape, supportShape)); return ImmutableMap.copyOf(states.stream().collect(Collectors.toMap(state -> state, state -> { return VoxelShapeHelper.rotateHorizontally(combinedShape, state.getValue(DIRECTION)); }))); } @Override protected InteractionResult useItemOn(ItemStack stack, BlockState state, Level level, BlockPos pos, Player player, InteractionHand hand, BlockHitResult result) { if(level.getBlockEntity(pos) instanceof BasinBlockEntity basin) { return basin.interact(player, hand, result); } return InteractionResult.PASS; } @Nullable @Override public BlockEntity newBlockEntity(BlockPos pos, BlockState state) { return new BasinBlockEntity(pos, state); } @Nullable public <T extends BlockEntity> BlockEntityTicker<T> getTicker(Level level, BlockState state, BlockEntityType<T> type) { if(level.isClientSide()) { return createTicker(type, ModBlockEntities.BASIN.get(), BasinBlockEntity::clientTick); } return null; } @Override public List<TagKey<Block>> getTags() { return List.of(BlockTags.MINEABLE_WITH_PICKAXE); } }
0
0.783186
1
0.783186
game-dev
MEDIA
0.999697
game-dev
0.952198
1
0.952198
Unity-Technologies/ECSGalaxySample
8,378
Assets/Scripts/PlanetSystem.cs
using Unity.Burst; using Unity.Burst.Intrinsics; using Unity.Collections; using Unity.Entities; using Unity.Mathematics; using Unity.Transforms; [BurstCompile] [UpdateAfter(typeof(BuildSpatialDatabaseGroup))] [UpdateBefore(typeof(BuildingSystem))] public partial struct PlanetSystem : ISystem { private EntityQuery _spatialDatabasesQuery; [BurstCompile] public void OnCreate(ref SystemState state) { _spatialDatabasesQuery = SystemAPI.QueryBuilder().WithAll<SpatialDatabase, SpatialDatabaseCell, SpatialDatabaseElement>().Build(); state.RequireForUpdate<Config>(); state.RequireForUpdate<SpatialDatabaseSingleton>(); state.RequireForUpdate(_spatialDatabasesQuery); state.RequireForUpdate<BeginSimulationEntityCommandBufferSystem.Singleton>(); state.RequireForUpdate<TeamManagerReference>(); } [BurstCompile] public void OnUpdate(ref SystemState state) { Config config = SystemAPI.GetSingleton<Config>(); SpatialDatabaseSingleton spatialDatabaseSingleton = SystemAPI.GetSingleton<SpatialDatabaseSingleton>(); EntityQuery planetsQuery = SystemAPI.QueryBuilder().WithAll<Planet>().Build(); PlanetShipsAssessmentJob shipsAssessmentJob = new PlanetShipsAssessmentJob { TotalPlanetsCount = planetsQuery.CalculateEntityCount(), PlanetShipsAssessmentsPerUpdate = config.PlanetShipAssessmentsPerUpdate, CachedSpatialDatabase = new CachedSpatialDatabaseRO { SpatialDatabaseEntity = spatialDatabaseSingleton.TargetablesSpatialDatabase, SpatialDatabaseLookup = SystemAPI.GetComponentLookup<SpatialDatabase>(true), CellsBufferLookup = SystemAPI.GetBufferLookup<SpatialDatabaseCell>(true), ElementsBufferLookup = SystemAPI.GetBufferLookup<SpatialDatabaseElement>(true), }, }; state.Dependency = shipsAssessmentJob.Schedule(state.Dependency); PlanetConversionJob conversionJob = new PlanetConversionJob { DeltaTime = SystemAPI.Time.DeltaTime, ECB = SystemAPI.GetSingletonRW<BeginSimulationEntityCommandBufferSystem.Singleton>().ValueRW.CreateCommandBuffer(state.WorldUnmanaged), BuildingReferenceLookup = SystemAPI.GetComponentLookup<BuildingReference>(true), BuildingLookup = SystemAPI.GetComponentLookup<Building>(true), }; state.Dependency = conversionJob.Schedule(state.Dependency); PlanetResourcesJob resourcesJob = new PlanetResourcesJob { DeltaTime = SystemAPI.Time.DeltaTime, }; state.Dependency = resourcesJob.Schedule(state.Dependency); PlanetClearBuildingsDataJob planetClearBuildingsDataJob = new PlanetClearBuildingsDataJob { }; state.Dependency = planetClearBuildingsDataJob.ScheduleParallel(state.Dependency); } [BurstCompile] public partial struct PlanetShipsAssessmentJob : IJobEntity, IJobEntityChunkBeginEnd { public int TotalPlanetsCount; public int PlanetShipsAssessmentsPerUpdate; public CachedSpatialDatabaseRO CachedSpatialDatabase; void Execute(Entity entity, in LocalTransform transform, ref Planet planet, in Team team, ref DynamicBuffer<PlanetShipsAssessment> shipsAssessmentBuffer, in DynamicBuffer<PlanetNetwork> planetNetworkBuffer) { // Ships assessment planet.ShipsAssessmentCounter -= math.min(TotalPlanetsCount, PlanetShipsAssessmentsPerUpdate); if (planet.ShipsAssessmentCounter < 0) { planet.ShipsAssessmentCounter += TotalPlanetsCount; // Clear assessment buffer for (int i = 0; i < shipsAssessmentBuffer.Length; i++) { shipsAssessmentBuffer[i] = default; } // Query allied and enemy ships count PlanetAssessmentCollector collector = new PlanetAssessmentCollector(team.Index, shipsAssessmentBuffer); SpatialDatabase.QueryAABB(in CachedSpatialDatabase._SpatialDatabase, in CachedSpatialDatabase._SpatialDatabaseCells, in CachedSpatialDatabase._SpatialDatabaseElements, transform.Position, planet.ShipsAssessmentExtents, ref collector); } } public bool OnChunkBegin(in ArchetypeChunk chunk, int unfilteredChunkIndex, bool useEnabledMask, in v128 chunkEnabledMask) { CachedSpatialDatabase.CacheData(); return true; } public void OnChunkEnd(in ArchetypeChunk chunk, int unfilteredChunkIndex, bool useEnabledMask, in v128 chunkEnabledMask, bool chunkWasExecuted) { } } [BurstCompile] public partial struct PlanetConversionJob : IJobEntity { public float DeltaTime; public EntityCommandBuffer ECB; [ReadOnly] public ComponentLookup<BuildingReference> BuildingReferenceLookup; [ReadOnly] public ComponentLookup<Building> BuildingLookup; void Execute(Entity entity, ref Planet planet, in Team team, ref DynamicBuffer<CapturingWorker> capturingWorkers, in DynamicBuffer<MoonReference> moonReferences) { // Determine the majority team using CapturingWorker array int majorityTeamIndex = -1; float majorityTeamSpeed = 0; // Determine the majority team using capturingWorkers array for (int i = 0; i < capturingWorkers.Length; i++) { CapturingWorker capturingWorker = capturingWorkers[i]; if (capturingWorker.CaptureSpeed > majorityTeamSpeed) { majorityTeamIndex = i; majorityTeamSpeed = capturingWorker.CaptureSpeed; } } // Reset conversion when there's a team change, or no unique team if (majorityTeamIndex < 0 || majorityTeamIndex != planet.LastConvertingTeam) { planet.LastConvertingTeam = -1; planet.CaptureProgress = 0; } // Handle conversion if there's a single team holds majority long enough if (majorityTeamIndex >= 0) { planet.LastConvertingTeam = majorityTeamIndex; planet.CaptureProgress += DeltaTime * majorityTeamSpeed; if (planet.CaptureProgress >= planet.CaptureTime) { planet.CaptureProgress = 0; GameUtilities.SetTeam(ECB, entity, planet.LastConvertingTeam); // Convert buildings for (int i = 0; i < moonReferences.Length; i++) { Entity moonEntity = moonReferences[i].Entity; Entity buildingEntity = BuildingReferenceLookup[moonEntity].BuildingEntity; if (BuildingLookup.HasComponent(buildingEntity)) { GameUtilities.SetTeam(ECB, buildingEntity, planet.LastConvertingTeam); } } } } // Clear capturingWorkers buffer for (int i = 0; i < capturingWorkers.Length; i++) { capturingWorkers[i] = default; } } } [BurstCompile] public partial struct PlanetResourcesJob : IJobEntity { public float DeltaTime; void Execute(ref Planet planet) { float3 finalGenerationRate = planet.ResourceGenerationRate + planet.ResearchBonuses.PlanetResourceGenerationRadeAdd; planet.ResourceCurrentStorage = math.clamp(planet.ResourceCurrentStorage + (finalGenerationRate * DeltaTime), float3.zero, planet.ResourceMaxStorage); } } [BurstCompile] public partial struct PlanetClearBuildingsDataJob : IJobEntity { private void Execute(ref Planet planet) { planet.ResearchBonuses.Reset(); } } }
0
0.762971
1
0.762971
game-dev
MEDIA
0.959932
game-dev
0.837376
1
0.837376
mhop/fhem-mirror
10,779
fhem/FHEM/12_HMS.pm
############################################## # $Id$ package main; use strict; use warnings; my %codes = ( "0" => "HMS100TF", "1" => "HMS100T", "2" => "HMS100WD", "3" => "RM100-2", "4" => "HMS100TFK", # Depending on the onboard jumper it is 4 or 5 "5" => "HMS100TFK", "6" => "HMS100MG", "8" => "HMS100CO", "e" => "HMS100FIT", ); ##################################### sub HMS_Initialize($) { my ($hash) = @_; # 810e047e0510a001473a000000120233 HMS100TF # 810e04b90511a0018e63000001100000 HMS100T # 810e04e80212a001ec46000001000000 HMS100WD # 810e04d70213a001b16d000003000000 RM100-2 # 810e047f0214a001a81f000001000000 HMS100TFK # 810e048f0295a0010155000001000000 HMS100TFK (jumper) # 810e04330216a001b4c5000001000000 HMS100MG # 810e04210218a00186e0000000000000 HMS100CO # 810e0448029ea00132d5000000000000 FI-Trenner $hash->{Match} = "^810e04......a001"; $hash->{DefFn} = "HMS_Define"; $hash->{UndefFn} = "HMS_Undef"; $hash->{ParseFn} = "HMS_Parse"; $hash->{AttrList} = "IODev do_not_notify:0,1 showtime:0,1 model:hms100-t,hms100-tf,hms100-wd,hms100-mg,hms100-tfk,rm100-2,hms100-co,hms100-fit ignore:0,1 $readingFnAttributes"; $hash->{AutoCreate}= { "HMS100TFK_.*" => { GPLOT => "fht80tf:Contact,", FILTER => "%NAME" }, "HMS100T[F]?_.*" => { GPLOT => "temp4hum6:Temp/Hum,", FILTER => "%NAME:T:.*" } }; } ##################################### sub HMS_Define($$) { my ($hash, $def) = @_; my @a = split("[ \t][ \t]*", $def); return "wrong syntax: define <name> HMS CODE" if(int(@a) != 3); $a[2] = lc($a[2]); return "Define $a[0]: wrong CODE format: specify a 4 digit hex value" if($a[2] !~ m/^[a-f0-9][a-f0-9][a-f0-9][a-f0-9]$/); $hash->{CODE} = $a[2]; $modules{HMS}{defptr}{$a[2]} = $hash; AssignIoPort($hash); return undef; } ##################################### sub HMS_Undef($$) { my ($hash, $name) = @_; delete($modules{HMS}{defptr}{$hash->{CODE}}) if(defined($hash->{CODE}) && defined($modules{HMS}{defptr}{$hash->{CODE}})); return undef; } ##################################### sub HMS_Parse($$) { my ($hash, $msg) = @_; my $dev = substr($msg, 16, 4); my $cde = substr($msg, 11, 1); # 012345678901234567890123456789 # 810e047f0214a001a81f000001000000 HMS100TFK my $val; $val = substr($msg, 24, 8) if(length($msg) == 32); if(!defined($val)) { Log3 $hash, 3, "Strange HMS message $msg"; return ""; } my $type = ""; foreach my $c (keys %codes) { if($cde =~ m/$c/) { $type = $codes{$c}; last; } } # As the HMS devices change their id on each battery change, we offer # a wildcard too for each type: 100<device-code>, my $odev = $dev; if(!defined($modules{HMS}{defptr}{$dev})) { Log3 $hash, 4, "HMS device $dev not defined, using the wildcard device 100$cde"; $dev = "100$cde"; } if(!defined($modules{HMS}{defptr}{$dev})) { Log3 $hash, 3, "Unknown HMS device $dev/$odev, please define it"; $type = "HMS" if(!$type); $type =~ s/-//; # RM100-2, - is special in fhem names return "UNDEFINED ${type}_$odev HMS $odev"; } my $def = $modules{HMS}{defptr}{$dev}; my $name = $def->{NAME}; return "" if(IsIgnored($name)); my (@v, @txt); # Used for HMS100TF & HMS100T my $batstr1 = "ok"; my $status1 = hex(substr($val, 0, 1)); $batstr1 = "empty" if( $status1 & 2 ); $batstr1 = "replaced" if( $status1 & 4 ); # Used for the other devices my $batstr2 = "ok"; my $status = hex(substr($val, 1, 1)); my $status2 = hex(substr($msg, 10, 1)); $batstr2 = "empty" if( $status2 & 4 ); $batstr2 = "replaced" if( $status2 & 8 ); if($type eq "HMS100TF") { @txt = ( "temperature", "humidity", "battery"); # Codierung <s1><s0><t1><t0><f0><t2><f2><f1> $v[0] = int(substr($val, 5, 1) . substr($val, 2, 2))/10; $v[0] = -$v[0] if($status1 & 8); $v[1] = int(substr($val, 6, 2) . substr($val, 4, 1))/10; $v[2] = $batstr1; $val = "T: $v[0] H: $v[1] Bat: $v[2]"; #$v[0] = "$v[0] (Celsius)"; #$v[1] = "$v[1] (%)"; } elsif ($type eq "HMS100T") { @txt = ( "temperature", "battery"); $v[0] = int(substr($val, 5, 1) . substr($val, 2, 2))/10; $v[0] = -$v[0] if($status1 & 8); $v[1] = $batstr1; $val = "T: $v[0] Bat: $v[1]"; #$v[0] = "$v[0] (Celsius)"; } elsif ($type eq "HMS100WD") { @txt = ( "water_detect", "battery"); $v[0] = ($status ? "on" : "off"); $v[1] = $batstr2; $val = "Water Detect: $v[0]"; } elsif ($type eq "HMS100TFK") { # By Peter P. @txt = ( "switch_detect", "battery"); $v[0] = ($status ? "on" : "off"); $v[1] = $batstr2; $val = "Switch Detect: $v[0]"; } elsif($type eq "RM100-2") { @txt = ( "smoke_detect", "battery"); $v[0] = ($status ? "on" : "off"); $v[1] = $batstr2; $val = "smoke_detect: $v[0]"; } elsif ($type eq "HMS100MG") { # By Peter Stark @txt = ( "gas_detect", "battery"); $v[0] = ($status ? "on" : "off"); $v[1] = $batstr2; # Battery conditions not yet verified $val = "Gas Detect: $v[0]"; } elsif ($type eq "HMS100CO") { # By PAN @txt = ( "gas_detect", "battery"); $v[0] = ($status ? "on" : "off"); $v[1] = $batstr2; # Battery conditions not yet verified $val = "CO Detect: $v[0]"; } elsif ($type eq "HMS100FIT") { # By PAN @txt = ( "fi_triggered", "battery"); $v[0] = ($status ? "on" : "off"); $v[1] = $batstr2; # Battery conditions not yet verified $val = "FI triggered: $v[0]"; } else { Log3 $name, 3, "HMS Device $dev (Unknown type: $type)"; return ""; } Log3 $name, 4, "HMS Device $dev ($type: $val)"; readingsBeginUpdate($def); my $max = int(@txt); for( my $i = 0; $i < $max; $i++) { readingsBulkUpdate($def, $txt[$i], $v[$i]); readingsBulkUpdate($def, "batteryState", $v[$i] eq "empty" ? "low" : "ok") if($txt[$i] eq "battery"); } readingsBulkUpdate($def, "type", $type); readingsBulkUpdate($def, "state", $val); readingsBulkUpdate($def, "ExactId", $odev) if($odev ne $dev); readingsEndUpdate($def, 1); return $name; } 1; =pod =item summary devices communicating via the ELV HMS protocol =item summary_DE Anbindung von ELV HMS Ger&auml;ten =begin html <a name="HMS"></a> <h3>HMS</h3> <ul> <a name="HMSdefine"></a> <b>Define</b> <ul> <code>define &lt;name&gt; HMS &lt;housecode&gt;</code> <br><br> <code>&lt;housecode&gt;</code> is a four digit hex number, corresponding to the address of the HMS device. <br> Examples: <ul> <code>define temp HMS 1234</code><br> </ul> Notes:<br> <ul> <li>Currently supported devices are the HMS100-T HMS100-TF HMS100-WD HMS100-MG HMS100-TFK HMS100-CO HMS100-FIT RM100-2 RM100-3</li> <li>The housecode of the HMS devices may change if the battery is renewed. In order to make life easier, you can define a "wildcard" device for each type of HMS device. First the real device-id will be checked, then the wildcard device id. The wildcards are: <ul> <li>1000 for the HMS100-TF</li> <li>1001 for the HMS100-T</li> <li>1002 for the HMS100-WD</li> <li>1003 for the RM100-2</li> <li>1004 for the HMS100-TFK</li> <li>1006 for the HMS100-MG</li> <li>1008 for the HMS100-CO</li> <li>100e for the HMS100-FIT</li> </ul> </li> <li>Some battery low notifications are not yet implemented (RM100, HMS100WD).</li> <li>Please test your installation before relying on the functionality.</li> </ul> <br> </ul> <br> <a name="HMSset"></a> <b>Set</b> <ul>N/A</ul><br> <a name="HMSget"></a> <b>Get</b> <ul>N/A</ul><br> <a name="HMSattr"></a> <b>Attributes</b> <ul> <li><a href="#ignore">ignore</a></li> <li><a href="#do_not_notify">do_not_notify</a></li> <li><a href="#showtime">showtime</a></li> <li><a href="#IODev">IODev</a></li> <li><a href="#eventMap">eventMap</a></li> <li><a href="#model">model</a> (hms100-t hms100-tf hms100-wd hms100-mg hms100-co hms100-tfk hms100-fit rm100-2)</li> <li><a href="#readingFnAttributes">readingFnAttributes</a></li> </ul> <br> </ul> =end html =begin html_DE <a name="HMS"></a> <h3>HMS</h3> <ul> <a name="HMSdefine"></a> <b>Define</b> <ul> <code>define &lt;name&gt; HMS &lt;housecode&gt;</code> <br><br> Der <code>&lt;housecode&gt;</code> ist eine vierstellige HEX-Zahl, entsprechend dem HMS Ger&auml;t.<br> Beispiel: <ul> <code>define temp HMS 1234</code><br> </ul> Hinweise:<br> <ul> <li>Derzeit werden folgende Komponenten Unterst&uuml;tzt: HMS100-T HMS100-TF HMS100-WD HMS100-MG HMS100-TFK HMS100-CO HMS100-FIT RM100-2 RM100-3</li> <li>Der Hauscode kann sich &auml;ndern wenn die Batterie gewechselt wird. Um sich das Leben einfacher zu machen kann man ein "Wildcard" (Platzhalter) Device f&uuml;r jeden Typ von HMS Ger&auml;t anlegen. Zuerst wird die echte Device-ID gepr&uuml;ft, danach die Wildcard-ID. Wildcards sind: <ul> <li>1000 f&uuml;r das HMS100-TF</li> <li>1001 f&uuml;r das HMS100-T</li> <li>1002 f&uuml;r das HMS100-WD</li> <li>1003 f&uuml;r das RM100-2</li> <li>1004 f&uuml;r das HMS100-TFK</li> <li>1006 f&uuml;r das HMS100-MG</li> <li>1008 f&uuml;r das HMS100-CO</li> <li>100e f&uuml;r das HMS100-FIT</li> </ul> </li> <li>Einige "Batteriestand niedrig" Benachrichtigungen sind noch nicht implemeniert (RM100, HMS100WD).</li> <li>Die Installation ist zu testen bevor man sich auf die Funktionalit&auml;t verl&auml;sst.</li> </ul> <br> </ul> <br> <a name="HMSset"></a> <b>Set</b> <ul>N/A</ul><br> <a name="HMSget"></a> <b>Get</b> <ul>N/A</ul><br> <a name="HMSattr"></a> <b>Attributes</b> <ul> <li><a href="#ignore">ignore</a></li> <li><a href="#do_not_notify">do_not_notify</a></li> <li><a href="#showtime">showtime</a></li> <li><a href="#IODev">IODev</a></li> <li><a href="#eventMap">eventMap</a></li> <li><a href="#model">model</a> (hms100-t hms100-tf hms100-wd hms100-mg hms100-co hms100-tfk hms100-fit rm100-2)</li> <li><a href="#readingFnAttributes">readingFnAttributes</a></li> </ul> <br> </ul> =end html_DE =cut
0
0.892168
1
0.892168
game-dev
MEDIA
0.480423
game-dev
0.887021
1
0.887021
Lothrazar/Cyclic
6,656
src/main/java/com/lothrazar/cyclic/block/harvester/TileHarvester.java
package com.lothrazar.cyclic.block.harvester; import java.util.List; import com.lothrazar.cyclic.block.TileBlockEntityCyclic; import com.lothrazar.cyclic.data.PreviewOutlineType; import com.lothrazar.cyclic.registry.BlockRegistry; import com.lothrazar.cyclic.registry.TileRegistry; import com.lothrazar.cyclic.util.HarvestUtil; import com.lothrazar.library.cap.CustomEnergyStorage; import com.lothrazar.library.util.ShapeUtil; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.Component; import net.minecraft.world.MenuProvider; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.properties.BlockStateProperties; import net.minecraft.world.phys.AABB; import net.minecraftforge.common.ForgeConfigSpec.IntValue; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.ForgeCapabilities; import net.minecraftforge.common.util.LazyOptional; import net.minecraftforge.energy.IEnergyStorage; public class TileHarvester extends TileBlockEntityCyclic implements MenuProvider { static enum Fields { REDSTONE, RENDER, SIZE, HEIGHT, DIRECTION; } public static final int MAX_SIZE = 12; static final int MAX_ENERGY = 640000; public static final int MAX_HEIGHT = 16; public static IntValue POWERCONF; private int radius = MAX_SIZE / 2; private int shapeIndex = 0; BlockPos targetPos = null; private int height = 1; private boolean directionIsUp = false; CustomEnergyStorage energy = new CustomEnergyStorage(MAX_ENERGY, MAX_ENERGY / 4); private LazyOptional<IEnergyStorage> energyCap = LazyOptional.of(() -> energy); public TileHarvester(BlockPos pos, BlockState state) { super(TileRegistry.HARVESTER.get(), pos, state); timer = 1; } public static void serverTick(Level level, BlockPos blockPos, BlockState blockState, TileHarvester e) { e.tick(); } public static <E extends BlockEntity> void clientTick(Level level, BlockPos blockPos, BlockState blockState, TileHarvester e) { e.tick(); } public void tick() { this.syncEnergy(); if (this.requiresRedstone() && !this.isPowered()) { setLitProperty(false); return; } final int cost = POWERCONF.get(); if (energy.getEnergyStored() < cost && cost > 0) { setLitProperty(false); return; } setLitProperty(true); if (this.level.isClientSide) { return; } //get and update target List<BlockPos> shape = this.getShape(); targetPos = getShapeTarget(shape); shapeIndex++; //does it exist if (targetPos != null && HarvestUtil.tryHarvestSingle(this.level, targetPos)) { //energy is per action energy.extractEnergy(cost, false); } } private BlockPos getShapeTarget(List<BlockPos> shape) { if (shape.size() == 0) { return null; } if (this.shapeIndex < 0 || this.shapeIndex >= shape.size()) { this.shapeIndex = 0; } return shape.get(shapeIndex); } private int heightWithDirection() { Direction blockFacing = this.getBlockState().getValue(BlockStateProperties.FACING); int diff = directionIsUp ? 1 : -1; if (blockFacing.getAxis().isVertical()) { diff = (blockFacing == Direction.UP) ? 1 : -1; } return diff * height; } //for harvest public List<BlockPos> getShape() { BlockPos center = getFacingShapeCenter(radius); List<BlockPos> shape = ShapeUtil.cubeSquareBase(center, radius, 0); int heightWithDirection = heightWithDirection(); if (heightWithDirection != 0) { shape = ShapeUtil.repeatShapeByHeight(shape, heightWithDirection); } return shape; } //for render public List<BlockPos> getShapeHollow() { BlockPos center = getFacingShapeCenter(radius); List<BlockPos> shape = ShapeUtil.squareHorizontalHollow(center, radius); int heightWithDirection = heightWithDirection(); if (heightWithDirection != 0) { shape = ShapeUtil.repeatShapeByHeight(shape, heightWithDirection); } if (targetPos != null) { shape.add(targetPos); } return shape; } @Override public AABB getRenderBoundingBox() { return BlockEntity.INFINITE_EXTENT_AABB; } @Override public int getField(int id) { switch (Fields.values()[id]) { case REDSTONE: return this.needsRedstone; case RENDER: return render; case SIZE: return radius; case HEIGHT: return height; case DIRECTION: return directionIsUp ? 1 : 0; } return 0; } @Override public void setField(int id, int value) { switch (Fields.values()[id]) { case REDSTONE: this.needsRedstone = value % 2; break; case RENDER: this.render = value % PreviewOutlineType.values().length; break; case SIZE: radius = Math.min(value, MAX_SIZE); break; case DIRECTION: this.directionIsUp = value == 1; break; case HEIGHT: height = Math.min(value, MAX_HEIGHT); break; } } @Override public void invalidateCaps() { energyCap.invalidate(); super.invalidateCaps(); } @Override public <T> LazyOptional<T> getCapability(Capability<T> cap, Direction side) { if (cap == ForgeCapabilities.ENERGY && POWERCONF.get() > 0) { return energyCap.cast(); } return super.getCapability(cap, side); } @Override public void load(CompoundTag tag) { radius = tag.getInt("radius"); height = tag.getInt("height"); directionIsUp = tag.getBoolean("directionIsUp"); shapeIndex = tag.getInt("shapeIndex"); energy.deserializeNBT(tag.getCompound(NBTENERGY)); super.load(tag); } @Override public void saveAdditional(CompoundTag tag) { tag.putInt("radius", radius); tag.putInt("shapeIndex", shapeIndex); tag.putInt("height", height); tag.putBoolean("directionIsUp", directionIsUp); tag.put(NBTENERGY, energy.serializeNBT()); super.saveAdditional(tag); } @Override public Component getDisplayName() { return BlockRegistry.HARVESTER.get().getName(); } @Override public AbstractContainerMenu createMenu(int i, Inventory playerInventory, Player playerEntity) { return new ContainerHarvester(i, level, worldPosition, playerInventory, playerEntity); } }
0
0.91362
1
0.91362
game-dev
MEDIA
0.996367
game-dev
0.99394
1
0.99394
Magneticraft-Team/Magneticraft
12,854
src/main/kotlin/com/cout970/magneticraft/systems/tilemodules/ModuleElectricity.kt
package com.cout970.magneticraft.systems.tilemodules import com.cout970.magneticraft.api.core.INode import com.cout970.magneticraft.api.core.ITileRef import com.cout970.magneticraft.api.core.NodeID import com.cout970.magneticraft.api.energy.IElectricConnection import com.cout970.magneticraft.api.energy.IElectricNode import com.cout970.magneticraft.api.energy.IElectricNodeHandler import com.cout970.magneticraft.api.energy.IWireConnector import com.cout970.magneticraft.api.internal.energy.ElectricNode import com.cout970.magneticraft.misc.* import com.cout970.magneticraft.misc.network.FloatSyncVariable import com.cout970.magneticraft.misc.network.SyncVariable import com.cout970.magneticraft.misc.tileentity.getTileEntitiesIn import com.cout970.magneticraft.misc.tileentity.shouldTick import com.cout970.magneticraft.misc.tileentity.tryConnect import com.cout970.magneticraft.misc.vector.length import com.cout970.magneticraft.misc.vector.minus import com.cout970.magneticraft.misc.vector.plus import com.cout970.magneticraft.misc.vector.toBlockPos import com.cout970.magneticraft.misc.world.isClient import com.cout970.magneticraft.misc.world.isServer import com.cout970.magneticraft.registry.ELECTRIC_NODE_HANDLER import com.cout970.magneticraft.registry.FORGE_ENERGY import com.cout970.magneticraft.registry.getOrNull import com.cout970.magneticraft.systems.config.Config import com.cout970.magneticraft.systems.gui.DATA_ID_VOLTAGE_LIST import com.cout970.magneticraft.systems.tileentities.IModule import com.cout970.magneticraft.systems.tileentities.IModuleContainer import net.minecraft.nbt.NBTTagCompound import net.minecraft.tileentity.TileEntity import net.minecraft.util.EnumFacing import net.minecraft.util.math.BlockPos import net.minecraft.util.math.Vec3i import net.minecraftforge.common.capabilities.Capability /** * Created by cout970 on 2017/06/29. */ class ModuleElectricity( val electricNodes: List<IElectricNode>, val canConnectAtSide: (EnumFacing?) -> Boolean = { true }, val onWireChange: (EnumFacing?) -> Unit = {}, val onUpdateConnections: (ModuleElectricity) -> Unit = {}, val maxWireDistance: Double = 16.0, val connectableDirections: () -> List<Pair<BlockPos, EnumFacing>> = { NEGATIVE_DIRECTIONS.map { it.toBlockPos() to it.opposite } }, val capabilityFilter: (EnumFacing?) -> Boolean = { true }, override val name: String = "module_electricity" ) : IModule, IElectricNodeHandler { companion object { @JvmStatic val NEGATIVE_DIRECTIONS = EnumFacing.values().filter { it.axisDirection == EnumFacing.AxisDirection.NEGATIVE } } override lateinit var container: IModuleContainer var autoConnectWires = false val inputNormalConnections = mutableListOf<IElectricConnection>() val outputNormalConnections = mutableListOf<IElectricConnection>() val inputWiredConnections = mutableListOf<IElectricConnection>() val outputWiredConnections = mutableListOf<IElectricConnection>() val unloadedWireConnections = mutableListOf<Pair<String, NodeID>>() override fun update() { updateConnections() iterate() } fun updateConnections() { if (unloadedWireConnections.isNotEmpty()) { loadConnections() } if (container.shouldTick(40)) { updateNormalConnections() if (electricNodes.any { it is IWireConnector }) { updateWiredConnections() } onUpdateConnections(this) } if (world.isServer && container.shouldTick(400) && electricNodes.any { it is IWireConnector }) { container.sendUpdateToNearPlayers() } } fun loadConnections() { val iter = unloadedWireConnections.iterator() while (iter.hasNext()) { val (localName, nodeID) = iter.next() val thisNode = electricNodes.find { it.id.name == localName } ?: continue val otherTile = world.getTileEntity(nodeID.pos) ?: continue val other = otherTile.getOrNull(ELECTRIC_NODE_HANDLER, null) ?: continue val otherNode = (other.getNode(nodeID) as? IElectricNode) ?: continue tryConnect(this, thisNode, other, otherNode, null) iter.remove() } } fun updateNormalConnections() { clearNormalConnections() if (world.isClient) return electricNodes.forEach { thisNode -> val conDir = connectableDirections() val spots = conDir.mapNotNull { (vec, side) -> val tile = world.getTileEntity(pos.add(vec)) ?: return@mapNotNull null tile to side } val handlers = spots.mapNotNull { (tile, side) -> val handler = tile.getOrNull(ELECTRIC_NODE_HANDLER, side) if (handler === null || handler === this) return@mapNotNull null handler to side } for ((handler, side) in handlers) { val electricNodes = handler.nodes .filterIsInstance<IElectricNode>() electricNodes.forEach { otherNode -> tryConnect(this, thisNode, handler, otherNode, side.opposite) } } } } fun updateWiredConnections() { if (autoConnectWires) { val size = Vec3i(16, 5, 16) autoConnectWires(pos - size, pos + size) } val changed = outputWiredConnections.removeAll { // Chunk unloaded, we do not remove the connection it.secondNode.world.getTileEntity(it.secondNode.pos) ?: return@removeAll false val handler = getHandler(it.secondNode) handler == null || handler.nodes.none { node -> node.id == it.secondNode.id } } if (changed || autoConnectWires) { onWireChange(null) } } fun autoConnectWires(start: BlockPos, end: BlockPos) { val thisNode = electricNodes.find { it is IWireConnector } as? IWireConnector ?: return val filter: (TileEntity) -> Boolean = { it != container.tile } val handlers = world.getTileEntitiesIn(start, end, filter).mapNotNull { it.getOrNull(ELECTRIC_NODE_HANDLER, null) } handlers.forEach { handler -> handler.nodes .filterIsInstance<IWireConnector>() .filter { it.connectorsSize == thisNode.connectorsSize } .forEach { otherNode -> if (outputWiredConnections.size < 16) { tryConnect(this, thisNode, handler, otherNode, null) } } } } fun iterate() { outputNormalConnections.forEach(IElectricConnection::iterate) outputWiredConnections.forEach(IElectricConnection::iterate) } override fun canConnect(thisNode: IElectricNode, other: IElectricNodeHandler, otherNode: IElectricNode, side: EnumFacing?): Boolean = defaultCanConnectImpl(thisNode, other, otherNode, side) fun defaultCanConnectImpl(thisNode: IElectricNode, other: IElectricNodeHandler, otherNode: IElectricNode, side: EnumFacing?): Boolean { if (other === this || otherNode === thisNode) return false if (!canConnectAtSide(side)) return false if (side == null) { if (thisNode !is IWireConnector || otherNode !is IWireConnector) return false if (thisNode.connectorsSize != otherNode.connectorsSize) return false if (inputWiredConnections.any { it.firstNode == otherNode }) { return false } if (outputWiredConnections.any { it.secondNode == otherNode }) { return false } val distance = (thisNode.pos - otherNode.pos).length if (distance > maxWireDistance) { return false } } return true } override fun addConnection(connection: IElectricConnection, side: EnumFacing?, output: Boolean) { val list: MutableList<IElectricConnection> = if (side == null) { if (output) outputWiredConnections else inputWiredConnections } else { if (output) outputNormalConnections else inputNormalConnections } list.add(connection) onWireChange(side) container.markDirty() } override fun removeConnection(connection: IElectricConnection?) { inputNormalConnections.remove(connection) outputNormalConnections.remove(connection) inputWiredConnections.remove(connection) outputWiredConnections.remove(connection) onWireChange(null) } override fun onBreak() { clearNormalConnections() clearWireConnections() inputNormalConnections.removeAll { con -> val handler = getHandler(con.firstNode) handler?.removeConnection(con) true } inputWiredConnections.removeAll { con -> val handler = getHandler(con.firstNode) handler?.removeConnection(con) true } onWireChange(null) } fun clearNormalConnections() { outputNormalConnections.removeAll { con -> val handler = getHandler(con.secondNode) handler?.removeConnection(con) true } } fun clearWireConnections() { outputWiredConnections.removeAll { con -> val handler = getHandler(con.secondNode) handler?.removeConnection(con) true } onWireChange(null) } fun getHandler(node: IElectricNode): IElectricNodeHandler? { val tile = node.world.getTileEntity(node.pos) ?: return null return tile.getOrNull(ELECTRIC_NODE_HANDLER, null) ?: return null } override fun getNodes(): MutableList<INode> = electricNodes.toMutableList() override fun getNode(id: NodeID): INode? = electricNodes.find { it.id == id } override fun getRef(): ITileRef = container.ref override fun getInputConnections(): MutableList<IElectricConnection> = inputNormalConnections with inputWiredConnections override fun getOutputConnections(): MutableList<IElectricConnection> = outputNormalConnections with outputWiredConnections override fun hasCapability(cap: Capability<*>, facing: EnumFacing?): Boolean { if (Config.enableDirectRFUsage && cap == FORGE_ENERGY) { return true } return cap == ELECTRIC_NODE_HANDLER && capabilityFilter.invoke(facing) } @Suppress("UNCHECKED_CAST") override fun <T : Any?> getCapability(cap: Capability<T>, facing: EnumFacing?): T? { if (!capabilityFilter.invoke(facing)) return null if (Config.enableDirectRFUsage && cap == FORGE_ENERGY) { return RFWrapper(this) as T } return this as T } override fun deserializeNBT(nbt: NBTTagCompound) { autoConnectWires = nbt.getBoolean("auto_connect") nbt.readList("ElectricNodes") { nodeList -> nodes.forEachIndexed { index, node -> node.deserializeNBT(nodeList.getTagCompound(index)) } } nbt.readList("ElectricConnections") { connectionList -> val unloaded = mutableListOf<Pair<String, NodeID>>() connectionList.forEachTag { tag -> unloaded += tag.getString("first") to NodeID.deserializeFromNBT(tag.getCompoundTag("second")) } unloadedWireConnections.addAll(unloaded) } } override fun serializeNBT(): NBTTagCompound = newNbt { add("auto_connect", autoConnectWires) list("ElectricNodes") { nodes.forEach { appendTag(it.serializeNBT()) } } list("ElectricConnections") { outputWiredConnections.forEach { newNbt { add("first", it.firstNode.id.name) add("second", it.secondNode.id.serializeNBT()) } } unloadedWireConnections.forEach { newNbt { add("first", it.first) add("second", it.second.serializeNBT()) } } } } override fun getGuiSyncVariables(): List<SyncVariable> { return electricNodes .filterIsInstance<ElectricNode>() .mapIndexed { index, node -> FloatSyncVariable( id = DATA_ID_VOLTAGE_LIST[index], getter = { node.voltage.toFloat() }, setter = { node.voltage = it.toDouble() } ) } } }
0
0.96313
1
0.96313
game-dev
MEDIA
0.727819
game-dev
0.971913
1
0.971913
PereViader/ManualDi
3,767
ManualDi.Async.Unity3d/Assets/ManualDi.Async.Unity3d/Runtime/EntryPoints/MonoBehaviourSubordinateEntryPoint.cs
using System; using System.Threading; using System.Threading.Tasks; using UnityEngine; namespace ManualDi.Async.Unity3d { public abstract class MonoBehaviourSubordinateEntryPoint<TData> : MonoBehaviour, IInstaller, IAsyncDisposable { public bool IsInitialized => Container is not null; public IDiContainer? Container { get; private set; } public TData? Data { get; private set; } private bool _disposed; public async ValueTask Initiate(TData data, CancellationToken ct) { if (IsInitialized) { throw new InvalidOperationException("Context is already initialized"); } Data = data; var bindings = new DiContainerBindings(); if (Data is IInstaller dataInstaller) { bindings.Install(dataInstaller); } bindings.Install(this); Container = await InitiateWrapper(bindings.Build(ct)); } /// <summary> /// Override this method to add behaviour that should happen before and after the container is setup /// </summary> protected virtual ValueTask<DiContainer> InitiateWrapper(ValueTask<DiContainer> task) { return task; } public virtual async void OnDestroy() { await DisposeAsync(); } public async ValueTask DisposeAsync() { if (_disposed) { return; } _disposed = true; if (Container is not null) { await Container.DisposeAsync(); } Container = null; Data = default; } public abstract void Install(DiContainerBindings b); } public abstract class MonoBehaviourSubordinateEntryPoint<TData, TContext> : MonoBehaviour, IInstaller, IAsyncDisposable { public bool IsInitialized => Container is not null; public IDiContainer? Container { get; private set; } public TContext? Context { get; private set; } public TData? Data { get; private set; } private bool _disposed; public async ValueTask<TContext> Initiate(TData data, CancellationToken ct) { if (IsInitialized) { throw new InvalidOperationException("Context is already initialized"); } Data = data; var bindings = new DiContainerBindings(); if (Data is IInstaller dataInstaller) { bindings.Install(dataInstaller); } bindings.Install(this); Container = await InitiateWrapper(bindings.Build(ct)); Context = Container.Resolve<TContext>(); return Context; } /// <summary> /// Override this method to add behaviour that should happen before and after the container is setup /// </summary> protected virtual ValueTask<DiContainer> InitiateWrapper(ValueTask<DiContainer> task) { return task; } public virtual async void OnDestroy() { await DisposeAsync(); } public async ValueTask DisposeAsync() { if (_disposed) { return; } _disposed = true; if (Container is not null) { await Container.DisposeAsync(); } Container = null; Data = default; Context = default; } public abstract void Install(DiContainerBindings b); } }
0
0.911166
1
0.911166
game-dev
MEDIA
0.748652
game-dev
0.958088
1
0.958088
HyperMC-Team/OpenRoxy
1,118
src/main/java/net/viamcp/viamcp/ViaMCP.java
package net.viamcp.viamcp; import java.io.File; import net.viamcp.vialoadingbase.ViaLoadingBase; import net.viamcp.viamcp.gui.AsyncVersionSlider; public class ViaMCP { public static final int NATIVE_VERSION = 47; public static ViaMCP INSTANCE; private AsyncVersionSlider asyncVersionSlider; public static void create() { INSTANCE = new ViaMCP(); } public ViaMCP() { ViaLoadingBase.ViaLoadingBaseBuilder.create().runDirectory(new File("ViaMCP")).nativeVersion(47).onProtocolReload(comparableProtocolVersion -> { if (this.getAsyncVersionSlider() != null) { this.getAsyncVersionSlider().setVersion(comparableProtocolVersion.getVersion()); } }).build(); } public void initAsyncSlider() { this.initAsyncSlider(5, 5, 110, 20); } public void initAsyncSlider(int x, int y, int width, int height) { this.asyncVersionSlider = new AsyncVersionSlider(-1, x, y, Math.max(width, 110), height); } public AsyncVersionSlider getAsyncVersionSlider() { return this.asyncVersionSlider; } }
0
0.677068
1
0.677068
game-dev
MEDIA
0.323806
game-dev
0.852372
1
0.852372
Dark-Basic-Software-Limited/Dark-Basic-Pro
2,096
SDK/BULLET/bullet-2.81-rev2613/src/BulletCollision/Gimpact/btGImpactMassUtil.h
/*! \file btGImpactMassUtil.h \author Francisco Leon Najera */ /* This source file is part of GIMPACT Library. For the latest info, see http://gimpact.sourceforge.net/ Copyright (c) 2007 Francisco Leon Najera. C.C. 80087371. email: projectileman@yahoo.com This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef GIMPACT_MASS_UTIL_H #define GIMPACT_MASS_UTIL_H #include "LinearMath/btTransform.h" SIMD_FORCE_INLINE btVector3 gim_inertia_add_transformed( const btVector3 & source_inertia, const btVector3 & added_inertia, const btTransform & transform) { btMatrix3x3 rotatedTensor = transform.getBasis().scaled(added_inertia) * transform.getBasis().transpose(); btScalar x2 = transform.getOrigin()[0]; x2*= x2; btScalar y2 = transform.getOrigin()[1]; y2*= y2; btScalar z2 = transform.getOrigin()[2]; z2*= z2; btScalar ix = rotatedTensor[0][0]*(y2+z2); btScalar iy = rotatedTensor[1][1]*(x2+z2); btScalar iz = rotatedTensor[2][2]*(x2+y2); return btVector3(source_inertia[0]+ix,source_inertia[1]+iy,source_inertia[2] + iz); } SIMD_FORCE_INLINE btVector3 gim_get_point_inertia(const btVector3 & point, btScalar mass) { btScalar x2 = point[0]*point[0]; btScalar y2 = point[1]*point[1]; btScalar z2 = point[2]*point[2]; return btVector3(mass*(y2+z2),mass*(x2+z2),mass*(x2+y2)); } #endif //GIMPACT_MESH_SHAPE_H
0
0.860343
1
0.860343
game-dev
MEDIA
0.963988
game-dev
0.947894
1
0.947894
KAMKEEL/CustomNPC-Plus
3,283
src/main/java/kamkeel/npcs/network/packets/player/SaveBookPacket.java
package kamkeel.npcs.network.packets.player; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import kamkeel.npcs.network.LargeAbstractPacket; import kamkeel.npcs.network.PacketChannel; import kamkeel.npcs.network.PacketHandler; import kamkeel.npcs.network.enums.EnumPlayerPacket; import kamkeel.npcs.util.ByteBufUtils; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Items; import net.minecraft.item.ItemEditableBook; import net.minecraft.item.ItemStack; import net.minecraft.item.ItemWritableBook; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagString; import net.minecraft.tileentity.TileEntity; import noppes.npcs.blocks.tiles.TileBook; import java.io.IOException; public class SaveBookPacket extends LargeAbstractPacket { public static final String packetName = "Player|SaveBook"; private int x, y, z; private boolean sign; private NBTTagCompound compound; public SaveBookPacket() { } public SaveBookPacket(int x, int y, int z, boolean sign, NBTTagCompound compound) { this.x = x; this.y = y; this.z = z; this.sign = sign; this.compound = compound; } @Override protected byte[] getData() throws IOException { ByteBuf buffer = Unpooled.buffer(); buffer.writeInt(x); buffer.writeInt(y); buffer.writeInt(z); buffer.writeBoolean(sign); ByteBufUtils.writeBigNBT(buffer, compound); return buffer.array(); } @Override @SideOnly(Side.CLIENT) protected void handleCompleteData(ByteBuf data, EntityPlayer player) throws IOException { int x = data.readInt(), y = data.readInt(), z = data.readInt(); if (player.worldObj.blockExists(x, y, z)) { TileEntity tileentity = player.worldObj.getTileEntity(x, y, z); if (!(tileentity instanceof TileBook)) return; TileBook tile = (TileBook) tileentity; if (tile.book.getItem() == Items.written_book) return; boolean sign = data.readBoolean(); ItemStack book = ItemStack.loadItemStackFromNBT(ByteBufUtils.readBigNBT(data)); if (book == null) return; if (book.getItem() == Items.writable_book && !sign && ItemWritableBook.func_150930_a(book.getTagCompound())) { tile.book.setTagInfo("pages", book.getTagCompound().getTagList("pages", 8)); } if (book.getItem() == Items.written_book && sign && ItemEditableBook.validBookTagContents(book.getTagCompound())) { tile.book.setTagInfo("author", new NBTTagString(player.getCommandSenderName())); tile.book.setTagInfo("title", new NBTTagString(book.getTagCompound().getString("title"))); tile.book.setTagInfo("pages", book.getTagCompound().getTagList("pages", 8)); tile.book.func_150996_a(Items.written_book); } } } @Override public Enum getType() { return EnumPlayerPacket.SaveBook; } @Override public PacketChannel getChannel() { return PacketHandler.PLAYER_PACKET; } }
0
0.815323
1
0.815323
game-dev
MEDIA
0.995885
game-dev
0.960436
1
0.960436
ImLegiitXD/Dream-Advanced
2,864
dll/back/1.20/net/minecraft/advancements/critereon/ChanneledLightningTrigger.java
package net.minecraft.advancements.critereon; import com.google.gson.JsonObject; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.Entity; import net.minecraft.world.level.storage.loot.LootContext; public class ChanneledLightningTrigger extends SimpleCriterionTrigger<ChanneledLightningTrigger.TriggerInstance> { static final ResourceLocation ID = new ResourceLocation("channeled_lightning"); public ResourceLocation getId() { return ID; } public ChanneledLightningTrigger.TriggerInstance createInstance(JsonObject p_286858_, ContextAwarePredicate p_286240_, DeserializationContext p_286562_) { ContextAwarePredicate[] acontextawarepredicate = EntityPredicate.fromJsonArray(p_286858_, "victims", p_286562_); return new ChanneledLightningTrigger.TriggerInstance(p_286240_, acontextawarepredicate); } public void trigger(ServerPlayer p_21722_, Collection<? extends Entity> p_21723_) { List<LootContext> list = p_21723_.stream().map((p_21720_) -> { return EntityPredicate.createContext(p_21722_, p_21720_); }).collect(Collectors.toList()); this.trigger(p_21722_, (p_21730_) -> { return p_21730_.matches(list); }); } public static class TriggerInstance extends AbstractCriterionTriggerInstance { private final ContextAwarePredicate[] victims; public TriggerInstance(ContextAwarePredicate p_286697_, ContextAwarePredicate[] p_286366_) { super(ChanneledLightningTrigger.ID, p_286697_); this.victims = p_286366_; } public static ChanneledLightningTrigger.TriggerInstance channeledLightning(EntityPredicate... p_21747_) { return new ChanneledLightningTrigger.TriggerInstance(ContextAwarePredicate.ANY, Stream.of(p_21747_).map(EntityPredicate::wrap).toArray((p_286116_) -> { return new ContextAwarePredicate[p_286116_]; })); } public boolean matches(Collection<? extends LootContext> p_21745_) { for(ContextAwarePredicate contextawarepredicate : this.victims) { boolean flag = false; for(LootContext lootcontext : p_21745_) { if (contextawarepredicate.matches(lootcontext)) { flag = true; break; } } if (!flag) { return false; } } return true; } public JsonObject serializeToJson(SerializationContext p_21743_) { JsonObject jsonobject = super.serializeToJson(p_21743_); jsonobject.add("victims", ContextAwarePredicate.toJson(this.victims, p_21743_)); return jsonobject; } } }
0
0.89777
1
0.89777
game-dev
MEDIA
0.941392
game-dev
0.936775
1
0.936775
Hex27/TerraformGenerator
1,441
common/src/main/java/org/terraform/command/TimingsCommand.java
package org.terraform.command; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.jetbrains.annotations.NotNull; import org.terraform.command.contants.TerraCommand; import org.terraform.main.TerraformGeneratorPlugin; import org.terraform.utils.TickTimer; import java.util.Map; import java.util.Stack; public class TimingsCommand extends TerraCommand { public TimingsCommand(TerraformGeneratorPlugin plugin, String... aliases) { super(plugin, aliases); } @Override public @NotNull String getDefaultDescription() { return "Shows timings of monitored functions"; } @Override public boolean canConsoleExec() { return true; } @Override public boolean hasPermission(@NotNull CommandSender sender) { return sender.isOp(); } @Override public void execute(@NotNull CommandSender sender, Stack<String> args) { sender.sendMessage("=====Avg Timings====="); for (Map.Entry<String, Long> entry : TickTimer.TIMINGS.entrySet()) { sender.sendMessage(ChatColor.GRAY + "- " + ChatColor.GREEN + entry.getKey() + ChatColor.DARK_GRAY + ": " + ChatColor.GOLD + entry.getValue()); } } }
0
0.68732
1
0.68732
game-dev
MEDIA
0.815296
game-dev
0.714175
1
0.714175
freakified/jga
3,087
Assets/Chapter 6 - World in Ruin/Scripts/S609Puppeteer.cs
using UnityEngine; using System.Collections; using System.Collections.Generic; public class S609Puppeteer : CutscenePuppeteer { public AudioClip FlashSound, RumbleSound, ExplosionSound; //private GameObject FlyingBBall; private ParticleSystem SparkParticles; private LensFlare ExplosionFlare; private MusicPlayer mus; private BattleController bc; private ScreenFlasher ScreenFlash; // Use this for initialization void Start () { // get all the objects we'll need for the cutscene //FlyingBBall = GameObject.Find ("Flying Basketball"); ScreenFlash = GameObject.Find ("ScreenFlash").GetComponent<ScreenFlasher>(); ExplosionFlare = GameObject.Find ("Explosion_Flare").GetComponent<LensFlare>(); SparkParticles = GameObject.Find ("SparkParticles").GetComponent<ParticleSystem>(); mus = GameObject.Find ("BGM").GetComponent<MusicPlayer>(); bc = GetComponent<BattleController>(); } public override void OnEnable() { base.OnEnable(); BattleController.OnBattleEvent += HandleBattleEvent; } public override void OnDisable() { base.OnDisable(); BattleController.OnBattleEvent -= HandleBattleEvent; } // Update is called once per frame public void FixedUpdate () { if(CurrentScene == 3) { if(timerIsGreaterThan(1f)) { nextScene(); } } else if(CurrentScene == 4) { if(timerIsGreaterThan(0.5f)) { nextScene(); } } else if(CurrentScene == 5) { if(timerIsGreaterThan(0.5f)) { playSound(RumbleSound); Camera.main.GetComponent<CameraShake>().enabled = true; nextScene(); } } else if(CurrentScene == 6) { if(timerIsGreaterThan(2.0f)) { playSound(ExplosionSound); ScreenFlash.FlashScreen(); nextScene(); } } else if(CurrentScene == 7) { if(timerIsGreaterThan(4.0f)) { playSound(ExplosionSound); ScreenFlash.FlashScreen(); nextScene(); } } else if(CurrentScene == 8) { ExplosionFlare.brightness += 1.0f * Time.fixedDeltaTime; if(ExplosionFlare.brightness > 5f) { FadeAndNext(Color.white, 1f, "6-09a Limbo", false); nextScene(); } } } public override void HandleSceneChange() { if(CurrentScene == 2) { bc.ResumeBattle(); } else if(CurrentScene == 3 || CurrentScene == 4 || CurrentScene == 5) { ScreenFlash.FlashScreen(); playSound(FlashSound); startTimer(); } else if(CurrentScene == 6) { startTimer(); playSound(ExplosionSound); ScreenFlash.FlashScreen(); } else if(CurrentScene == 7) { SparkParticles.Play(); startTimer(); } else if(CurrentScene == 8) { ExplosionFlare.enabled = true; ScreenFlash.FlashScreen(); } } public void HandleBattleEvent(BattleEvent type) { switch(type) { case BattleEvent.TurnChange: if(CurrentScene == 0) { bc.PauseBattle(); nextScene(); } else if(CurrentScene == 2) { // did the bball die? if(bc.EnemyCombatants[0].HitPoints == 0) { bc.PauseBattle(); mus.StopMusic(3.0f); startTimer(); nextScene(); } } break; case BattleEvent.Finished: mus.StopMusic(1.0f); nextScene(); break; } } }
0
0.911509
1
0.911509
game-dev
MEDIA
0.989709
game-dev
0.994001
1
0.994001
JKU-ICG/AOS
4,715
AOS Groundstation/AOS server/DroneSwarmServer/UIAnimationWnd.h
#pragma once // CUIAnimationWnd class CUIAnimationWnd : public CWnd { DECLARE_DYNAMIC(CUIAnimationWnd) public: enum XAnimation { e_AnimationFirst = 0, e_AnimationNone = e_AnimationFirst, e_AnimationSelect = 1, e_AnimationLast = e_AnimationSelect }; enum XAnimationType { e_AnimationTypeFade = 0x0001, e_AnimationTypeSlideUp = 0x0002, e_AnimationTypeSlideDown = 0x0004, e_AnimationTypeSlideLeft = 0x0008, e_AnimationTypeSlideRight = 0x0010, e_AnimationTypeScale = 0x0020, e_AnimationTypeBoth = 0x1000 }; public: CUIAnimationWnd(); virtual ~CUIAnimationWnd(); virtual BOOL Create(DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID); BOOL AddControl(CWnd* pWnd, const CString& strLabel); INT_PTR GetCount() const { return m_arWindows.GetSize(); } BOOL IsEmpty() const { return GetCount() == 0; } int GetCurSel() const { return m_nCurSel; } void SetCurSel(int index); double getSystemScaleFactor(); BOOL IsAnimationInProgress() {return m_AnimationController.IsAnimationInProgress();} DWORD GetAnimationType(XAnimation animation) const { if (animation == e_AnimationNone) { ASSERT(FALSE); return 0; } return animation == e_AnimationSelect ? m_AnimationTypeSelect : 0; } void SetAnimationType(XAnimation animation, DWORD type) { if (animation == e_AnimationNone) { ASSERT(FALSE); return; } if (!IsAnimationInProgress()) { if (animation == e_AnimationSelect) { m_AnimationTypeSelect = type; } } } double GetAnimationDuration(XAnimation animation) const { if (animation == e_AnimationNone) { ASSERT(FALSE); return 0.0; } return animation == e_AnimationSelect ? m_AnimationDurationSelect : 0.0; } void SetAnimationDuration(XAnimation animation, double duration) { if (animation == e_AnimationNone) { ASSERT(FALSE); return; } if (!IsAnimationInProgress()) { if (animation == e_AnimationSelect) { m_AnimationDurationSelect = duration; } } } protected: afx_msg void OnMouseMove(UINT nFlags, CPoint point); afx_msg void OnMouseLeave(); afx_msg void OnLButtonDown(UINT nFlags, CPoint point); afx_msg BOOL OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message); afx_msg LRESULT OnDraw2D(WPARAM wParam, LPARAM lParam); afx_msg void OnSize(UINT nType, int cx, int cy); DECLARE_MESSAGE_MAP() void RecalcLayout(); CRect GetControlRect() const; CRect GetTabRect(int index) const; void RepositionControls(CWnd* pWnd = NULL); CWnd* GetControl(int index); int FindIndex(const CWnd* pWnd) const; int HitTest(const CPoint& point) const; void SetHighlighted(int index); void DoPaintControlD2D(CHwndRenderTarget& renderTarget); void DoPaintTabsD2D(CHwndRenderTarget& renderTarget); void PrepareBitmaps(int nCurrent, int nNext); void ClearBitmaps(); void StartAnimation(XAnimation animation); void StopAnimation(); DWORD GetAnimationType() const { return GetAnimationType(m_Animation); } double GetAnimationDuration() const { return GetAnimationDuration(m_Animation); } private: CRect m_rectTabs; CArray<CWnd*, CWnd*> m_arWindows; CStringArray m_arLabels; int m_nCurSel; int m_nHighlighted; BOOL m_bTracked; XAnimation m_Animation; DWORD m_AnimationTypeSelect; double m_AnimationDurationSelect; CAnimationController m_AnimationController; CAnimationValue m_AnimationValueFade; CAnimationPoint m_AnimationValueSlide; CAnimationValue m_AnimationValueScale; CArray<CAnimationValue*, CAnimationValue*> m_arAnimationFade_H; CBitmap m_bmpControl[2]; CD2DBitmap* m_bmpD2D[2]; BOOL m_bTabHorz; CD2DSolidColorBrush* m_pBrushBorder; CD2DSolidColorBrush* m_pBrushTabBorder; CD2DSolidColorBrush* m_pBrushTextRegular; CD2DSolidColorBrush* m_pBrushTextBold; CD2DSolidColorBrush* m_pBrushWhite; CD2DLinearGradientBrush* m_pBrushFill; CD2DLinearGradientBrush* m_pBrushTab; CD2DLinearGradientBrush* m_pBrushSelectedTabBack; };
0
0.788677
1
0.788677
game-dev
MEDIA
0.458452
game-dev,graphics-rendering
0.844787
1
0.844787
electronicarts/CnC_Generals_Zero_Hour
5,518
GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/mixfile.h
/* ** Command & Conquer Generals Zero Hour(tm) ** Copyright 2025 Electronic Arts Inc. ** ** 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/>. */ /*********************************************************************************************** *** Confidential - Westwood Studios *** *********************************************************************************************** * * * Project Name : Commando * * * * $Archive:: /Commando/Code/wwlib/mixfile.h $* * * * $Author:: Steve_t $* * * * $Modtime:: 9/07/01 5:29p $* * * * $Revision:: 4 $* * * *---------------------------------------------------------------------------------------------* * Functions: * * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ #ifndef MIXFILE_H #define MIXFILE_H #ifndef ALWAYS_H #include "always.h" #endif #ifndef FFACTORY_H #include "ffactory.h" #endif #ifndef WWSTRING_H #include "wwstring.h" #endif #include "vector.h" class FileClass; /* ** */ class MixFileFactoryClass : public FileFactoryClass { public: MixFileFactoryClass( const char * mix_filename, FileFactoryClass * factory ); virtual ~MixFileFactoryClass( void ); // // Inherited // virtual FileClass * Get_File( char const *filename ); virtual void Return_File( FileClass *file ); // // Filename access // bool Build_Filename_List (DynamicVectorClass<StringClass> &list); bool Build_Ordered_Filename_List (DynamicVectorClass<StringClass> &list); // ordered by offset in mixfile bool Build_Internal_Filename_List (void) { return Build_Filename_List (FilenameList); } void Get_Filename_List (DynamicVectorClass<StringClass> **list) { *list = &FilenameList; } void Get_Filename_List (DynamicVectorClass<StringClass> &list) { list = FilenameList; } // // Content control // void Add_File (const char *full_path, const char *filename); void Delete_File (const char *filename); void Flush_Changes (void); // // Information // bool Is_Valid (void) const { return IsValid; } private: // // Utility functions // bool Get_Temp_Filename (const char *path, StringClass &full_path); static int File_Offset_Compare(const void * a, const void * b); struct FileInfoStruct { bool operator== (const FileInfoStruct &src) { return false; } bool operator!= (const FileInfoStruct &src) { return true; } unsigned long CRC; // CRC code for embedded file. unsigned long Offset; // Offset from start of data section. unsigned long Size; // Size of data subfile. }; struct AddInfoStruct { bool operator== (const AddInfoStruct &src) { return false; } bool operator!= (const AddInfoStruct &src) { return true; } StringClass FullPath; StringClass Filename; }; FileFactoryClass * Factory; DynamicVectorClass<FileInfoStruct> FileInfo; StringClass MixFilename; int BaseOffset; int FileCount; int NamesOffset; bool IsValid; DynamicVectorClass<StringClass> FilenameList; DynamicVectorClass<AddInfoStruct> PendingAddFileList; bool IsModified; }; /* ** */ class MixFileCreator { public: MixFileCreator( const char * filename ); ~MixFileCreator( void ); void Add_File( const char * source_filename, const char * saved_filename = NULL ); void Add_File( const char * filename, FileClass *file ); private: static int File_Info_Compare(const void * a, const void * b); struct FileInfoStruct { bool operator== (const FileInfoStruct &src) { return false; } bool operator!= (const FileInfoStruct &src) { return true; } unsigned long CRC; // CRC code for embedded file. unsigned long Offset; // Offset from start of data section. unsigned long Size; // Size of data subfile. StringClass Filename; }; DynamicVectorClass<FileInfoStruct> FileInfo; FileClass * MixFile; }; /* ** */ void Setup_Mix_File( void ); #endif
0
0.93137
1
0.93137
game-dev
MEDIA
0.333849
game-dev
0.80509
1
0.80509
CreeperAWA/UnityAssetStudio-Chinese_version
4,910
AssetStudio/Classes/PPtr.cs
using System; using System.IO; using System.Collections.Generic; namespace AssetStudio { public sealed class PPtr<T> : IYAMLExportable where T : Object { public int m_FileID; public long m_PathID; private SerializedFile assetsFile; private int index = -2; //-2 - Prepare, -1 - Missing public string Name => TryGet(out var obj) ? obj.Name : string.Empty; public PPtr(int m_FileID, long m_PathID, SerializedFile assetsFile) { this.m_FileID = m_FileID; this.m_PathID = m_PathID; this.assetsFile = assetsFile; } public PPtr(ObjectReader reader) { m_FileID = reader.ReadInt32(); m_PathID = reader.m_Version < SerializedFileFormatVersion.Unknown_14 ? reader.ReadInt32() : reader.ReadInt64(); assetsFile = reader.assetsFile; } public YAMLNode ExportYAML(int[] version) { var node = new YAMLMappingNode(); node.Style = MappingStyle.Flow; node.Add("fileID", m_FileID); return node; } private bool TryGetAssetsFile(out SerializedFile result) { result = null; if (m_FileID == 0) { result = assetsFile; return true; } if (m_FileID > 0 && m_FileID - 1 < assetsFile.m_Externals.Count) { var assetsManager = assetsFile.assetsManager; var assetsFileList = assetsManager.assetsFileList; var assetsFileIndexCache = assetsManager.assetsFileIndexCache; if (index == -2) { var m_External = assetsFile.m_Externals[m_FileID - 1]; var name = m_External.fileName; if (!assetsFileIndexCache.TryGetValue(name, out index)) { index = assetsFileList.FindIndex(x => x.fileName.Equals(name, StringComparison.OrdinalIgnoreCase)); assetsFileIndexCache.Add(name, index); } } if (index >= 0) { result = assetsFileList[index]; return true; } } return false; } public bool TryGet(out T result) { if (TryGetAssetsFile(out var sourceFile)) { if (sourceFile.ObjectsDic.TryGetValue(m_PathID, out var obj)) { if (obj is T variable) { result = variable; return true; } } } result = null; return false; } public bool TryGet<T2>(out T2 result) where T2 : Object { if (TryGetAssetsFile(out var sourceFile)) { if (sourceFile.ObjectsDic.TryGetValue(m_PathID, out var obj)) { if (obj is T2 variable) { result = variable; return true; } } } result = null; return false; } public void Set(T m_Object) { var name = m_Object.assetsFile.fileName; if (string.Equals(assetsFile.fileName, name, StringComparison.OrdinalIgnoreCase)) { m_FileID = 0; } else { m_FileID = assetsFile.m_Externals.FindIndex(x => string.Equals(x.fileName, name, StringComparison.OrdinalIgnoreCase)); if (m_FileID == -1) { assetsFile.m_Externals.Add(new FileIdentifier { fileName = m_Object.assetsFile.fileName }); m_FileID = assetsFile.m_Externals.Count; } else { m_FileID += 1; } } var assetsManager = assetsFile.assetsManager; var assetsFileList = assetsManager.assetsFileList; var assetsFileIndexCache = assetsManager.assetsFileIndexCache; if (!assetsFileIndexCache.TryGetValue(name, out index)) { index = assetsFileList.FindIndex(x => x.fileName.Equals(name, StringComparison.OrdinalIgnoreCase)); assetsFileIndexCache.Add(name, index); } m_PathID = m_Object.m_PathID; } public PPtr<T2> Cast<T2>() where T2 : Object { return new PPtr<T2>(m_FileID, m_PathID, assetsFile); } public bool IsNull => m_PathID == 0 || m_FileID < 0; } }
0
0.870631
1
0.870631
game-dev
MEDIA
0.95218
game-dev
0.980418
1
0.980418
fylz1125/MoonWarriors
2,925
MoonWarriors/libs/cocos2dx/tilemap_parallax_nodes/CCTMXObjectGroup.cpp
/**************************************************************************** Copyright (c) 2010-2012 cocos2d-x.org Copyright (c) 2010 Neophit Copyright (c) 2010 Ricardo Quesada Copyright (c) 2011 Zynga Inc. http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "CCTMXObjectGroup.h" #include "ccMacros.h" NS_CC_BEGIN //implementation CCTMXObjectGroup CCTMXObjectGroup::CCTMXObjectGroup() :m_tPositionOffset(CCPointZero) ,m_sGroupName("") { m_pObjects = CCArray::create(); m_pObjects->retain(); m_pProperties = new CCDictionary(); } CCTMXObjectGroup::~CCTMXObjectGroup() { CCLOGINFO( "cocos2d: deallocing."); CC_SAFE_RELEASE(m_pObjects); CC_SAFE_RELEASE(m_pProperties); } CCDictionary* CCTMXObjectGroup::objectNamed(const char *objectName) { if (m_pObjects && m_pObjects->count() > 0) { CCObject* pObj = NULL; CCARRAY_FOREACH(m_pObjects, pObj) { CCDictionary* pDict = (CCDictionary*)pObj; CCString *name = (CCString*)pDict->objectForKey("name"); if (name && name->m_sString == objectName) { return pDict; } } } // object not found return NULL; } CCString* CCTMXObjectGroup::propertyNamed(const char* propertyName) { return (CCString*)m_pProperties->objectForKey(propertyName); } CCDictionary* CCTMXObjectGroup::getProperties() { return m_pProperties; } void CCTMXObjectGroup::setProperties(CCDictionary * properties) { CC_SAFE_RETAIN(properties); CC_SAFE_RELEASE(m_pProperties); m_pProperties = properties; } CCArray* CCTMXObjectGroup::getObjects() { return m_pObjects; } void CCTMXObjectGroup::setObjects(CCArray* objects) { CC_SAFE_RETAIN(objects); CC_SAFE_RELEASE(m_pObjects); m_pObjects = objects; } NS_CC_END
0
0.896243
1
0.896243
game-dev
MEDIA
0.785088
game-dev
0.709103
1
0.709103
online-go/online-go.com
10,363
src/views/LearningHub/Sections/BeginnerLevel2/Eye1.tsx
/* * Copyright (C) Online-Go.com * * 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/>. */ /* cSpell:disable */ import { GobanConfig } from "goban"; import { LearningPage, LearningPageProperties } from "../../LearningPage"; import { _, pgettext } from "@/lib/translate"; import { LearningHubSection } from "../../LearningHubSection"; export class BL2Eye1 extends LearningHubSection { static pages(): Array<typeof LearningPage> { return [ Page01, Page02, Page03, Page04, Page05, Page06, Page07, Page08, Page09, Page10, Page11, Page12, Page13, ]; } static section(): string { return "bl2-eye1"; } static title(): string { return pgettext("Tutorial section name on learning throw in", "Eye 1"); } static subtext(): string { return pgettext( "Tutorial section subtext on learning on throw in", "Make eye false by throwing in", ); } } class Page01 extends LearningPage { constructor(props: LearningPageProperties) { super(props); } text() { return _( "Sometimes you can force your opponent to fill eye space by throwing in, leaving your opponent with a false eye. White to play. Make an eye false by throwing in.", ); } config(): GobanConfig { return { width: 19, height: 19, mode: "puzzle", initial_player: "white", bounds: { top: 10, left: 0, bottom: 18, right: 8 }, initial_state: { black: "arbrcrdrbses", white: "aqbqcqdqeqerfr", }, move_tree: this.makePuzzleMoveTree(["ds"], ["fsds", "csds"], 19, 19), }; } } class Page02 extends LearningPage { constructor(props: LearningPageProperties) { super(props); } text() { return _("White to play. Make an eye false by throwing in."); } config(): GobanConfig { return { width: 19, height: 19, mode: "puzzle", initial_player: "white", bounds: { top: 10, left: 0, bottom: 18, right: 8 }, initial_state: { black: "arbrcrdrbsesfs", white: "bqcqdqfqergrgs", }, move_tree: this.makePuzzleMoveTree(["ds"], ["frds"], 19, 19), }; } } class Page03 extends LearningPage { constructor(props: LearningPageProperties) { super(props); } text() { return _("White to play. Make an eye false by throwing in."); } config(): GobanConfig { return { width: 19, height: 19, mode: "puzzle", initial_player: "white", bounds: { top: 10, left: 0, bottom: 18, right: 8 }, initial_state: { black: "cqarbrdrbsds", white: "coeobpbqdqeqgqer", }, move_tree: this.makePuzzleMoveTree(["cr"], ["cpcr"], 19, 19), }; } } class Page04 extends LearningPage { constructor(props: LearningPageProperties) { super(props); } text() { return _("White to play. Make an eye false by throwing in."); } config(): GobanConfig { return { width: 19, height: 19, mode: "puzzle", initial_player: "white", bounds: { top: 10, left: 0, bottom: 18, right: 8 }, initial_state: { black: "epeqarbrcrdrfrdsfs", white: "dneogodpbqcqdqfqgqiqgrbs", }, move_tree: this.makePuzzleMoveTree(["er"], ["fper"], 19, 19), }; } } class Page05 extends LearningPage { constructor(props: LearningPageProperties) { super(props); } text() { return _("White to play. Make an eye false by throwing in."); } config(): GobanConfig { return { width: 19, height: 19, mode: "puzzle", initial_player: "white", bounds: { top: 10, left: 0, bottom: 18, right: 8 }, initial_state: { black: "docpepcqeqcrdrercses", white: "dmcnencoeofobpfpbqfqbrfr", }, move_tree: this.makePuzzleMoveTree(["dp"], ["dndp"], 19, 19), }; } } class Page06 extends LearningPage { constructor(props: LearningPageProperties) { super(props); } text() { return _("White to play. Make an eye false by throwing in."); } config(): GobanConfig { return { width: 19, height: 19, mode: "puzzle", initial_player: "white", bounds: { top: 10, left: 0, bottom: 18, right: 8 }, initial_state: { black: "anaobpbqarbrcrcs", white: "dlambmenbococpcqeqdr", }, move_tree: this.makePuzzleMoveTree(["ap"], ["bnap"], 19, 19), }; } } class Page07 extends LearningPage { constructor(props: LearningPageProperties) { super(props); } text() { return _("White to play. Make an eye false by throwing in."); } config(): GobanConfig { return { width: 19, height: 19, mode: "puzzle", initial_player: "white", bounds: { top: 10, left: 0, bottom: 18, right: 8 }, initial_state: { black: "eqfqarbrdrfrcses", white: "doepfpgpbqcqdqgqcrgr", }, move_tree: this.makePuzzleMoveTree(["bs"], ["aqbs"], 19, 19), }; } } class Page08 extends LearningPage { constructor(props: LearningPageProperties) { super(props); } text() { return _("White to play. Make an eye false by throwing in."); } config(): GobanConfig { return { width: 19, height: 19, mode: "puzzle", initial_player: "white", bounds: { top: 10, left: 0, bottom: 18, right: 8 }, initial_state: { black: "aqcqdqbrdrbsds", white: "bpcpdpepbqeqer", }, move_tree: this.makePuzzleMoveTree(["ar"], ["apar"], 19, 19), }; } } class Page09 extends LearningPage { constructor(props: LearningPageProperties) { super(props); } text() { return _("White to play. Make an eye false by throwing in."); } config(): GobanConfig { return { width: 19, height: 19, mode: "puzzle", initial_player: "white", bounds: { top: 10, left: 0, bottom: 18, right: 8 }, initial_state: { black: "aqbqbrdrerfrbscsfs", white: "bpcpcqdqeqfqgqcrgr", }, move_tree: this.makePuzzleMoveTree(["ds"], ["gsds"], 19, 19), }; } } class Page10 extends LearningPage { constructor(props: LearningPageProperties) { super(props); } text() { return _("White to play. Make an eye false by throwing in."); } config(): GobanConfig { return { width: 19, height: 19, mode: "puzzle", initial_player: "white", bounds: { top: 10, left: 0, bottom: 18, right: 8 }, initial_state: { black: "bncndnbodobpdpcqbrcrdrbsds", white: "ckambmcmemanenaoeoapepaqbqdqeqarer", }, move_tree: this.makePuzzleMoveTree(["cp"], ["dmcp"], 19, 19), }; } } class Page11 extends LearningPage { constructor(props: LearningPageProperties) { super(props); } text() { return _("White to play. Make an eye false by throwing in."); } config(): GobanConfig { return { width: 19, height: 19, mode: "puzzle", initial_player: "white", bounds: { top: 10, left: 0, bottom: 18, right: 8 }, initial_state: { black: "bncndnbodocpdpcqbrdrbsds", white: "ambmcmemanenaoeoapepaqbqdqeqarfr", }, move_tree: this.makePuzzleMoveTree(["cr"], [], 19, 19), }; } } class Page12 extends LearningPage { constructor(props: LearningPageProperties) { super(props); } text() { return _("White to play. Make an eye false by throwing in."); } config(): GobanConfig { return { width: 19, height: 19, mode: "puzzle", initial_player: "white", bounds: { top: 10, left: 0, bottom: 18, right: 8 }, initial_state: { black: "fqgqbrcrdrfrhrbsesfshs", white: "eohofpgpbqcqdqeqhqiqarerir", }, move_tree: this.makePuzzleMoveTree(["ds"], [], 19, 19), }; } } class Page13 extends LearningPage { constructor(props: LearningPageProperties) { super(props); } text() { return _("White to play. Make an eye false by throwing in."); } config(): GobanConfig { return { width: 19, height: 19, mode: "puzzle", initial_player: "white", bounds: { top: 10, left: 0, bottom: 18, right: 8 }, initial_state: { black: "ambmbnbocoapbqarbrcrdrds", white: "ckblcmcndndofobpcpcqeqergrbs", }, move_tree: this.makePuzzleMoveTree(["ao"], [], 19, 19), }; } }
0
0.794665
1
0.794665
game-dev
MEDIA
0.72445
game-dev
0.926397
1
0.926397
MinecraftModdedClients/Resilience-Client-Source
3,547
com/krispdev/resilience/hooks/HookPlayerControllerMP.java
package com.krispdev.resilience.hooks; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.client.Minecraft; import net.minecraft.client.audio.PositionedSoundRecord; import net.minecraft.client.multiplayer.PlayerControllerMP; import net.minecraft.client.network.NetHandlerPlayClient; import net.minecraft.network.play.client.C07PacketPlayerDigging; import net.minecraft.util.ResourceLocation; import com.krispdev.resilience.Resilience; import com.krispdev.resilience.event.events.player.EventBlockClick; public class HookPlayerControllerMP extends PlayerControllerMP{ public HookPlayerControllerMP(Minecraft p_i45062_1_, NetHandlerPlayClient netHandlerPlayClient) { super(p_i45062_1_, netHandlerPlayClient); } @Override public void clickBlock(int par1, int par2, int par3, int par4){ final EventBlockClick eventClick = new EventBlockClick(par1, par2, par3, par4, Resilience.getInstance().getInvoker().getBlock(par1, par2, par3)); eventClick.onEvent(); if(eventClick.isCancelled()){ eventClick.setCancelled(false); }else{ super.clickBlock(par1, par2, par3, par4); } } @Override public void onPlayerDamageBlock(int par1, int par2, int par3, int par4){ boolean fastBreak = Resilience.getInstance().getValues().fastBreakEnabled; this.syncCurrentPlayItem(); if (this.blockHitDelay > 0) { --this.blockHitDelay; } else if (this.currentGameType.isCreative()) { this.blockHitDelay = fastBreak ? 0 : 5; this.netClientHandler.addToSendQueue(new C07PacketPlayerDigging(0, par1, par2, par3, par4)); clickBlockCreative(this.mc, this, par1, par2, par3, par4); } else { if (this.sameToolAndBlock(par1, par2, par3)) { Block var5 = this.mc.theWorld.getBlock(par1, par2, par3); if (var5.getMaterial() == Material.air) { this.isHittingBlock = false; return; } this.curBlockDamageMP += var5.getPlayerRelativeBlockHardness(this.mc.thePlayer, this.mc.thePlayer.worldObj, par1, par2, par3); if (this.stepSoundTickCounter % 4.0F == 0.0F) { this.mc.getSoundHandler().playSound(new PositionedSoundRecord(new ResourceLocation(var5.stepSound.func_150498_e()), (var5.stepSound.func_150497_c() + 1.0F) / 8.0F, var5.stepSound.func_150494_d() * 0.5F, (float)par1 + 0.5F, (float)par2 + 0.5F, (float)par3 + 0.5F)); } ++this.stepSoundTickCounter; if (this.curBlockDamageMP >= (fastBreak ? Resilience.getInstance().getValues().fastBreakSpeed.getValue() : 1.0F)) { this.isHittingBlock = false; this.netClientHandler.addToSendQueue(new C07PacketPlayerDigging(2, par1, par2, par3, par4)); this.onPlayerDestroyBlock(par1, par2, par3, par4); this.curBlockDamageMP = 0.0F; this.stepSoundTickCounter = 0.0F; this.blockHitDelay = fastBreak ? 0 : 5; } this.mc.theWorld.destroyBlockInWorldPartially(this.mc.thePlayer.getEntityId(), this.currentBlockX, this.currentBlockY, this.currentblockZ, (int)(this.curBlockDamageMP * 10.0F) - 1); } else { this.clickBlock(par1, par2, par3, par4); } } } }
0
0.88372
1
0.88372
game-dev
MEDIA
0.85982
game-dev
0.878864
1
0.878864
shiptest-ss13/Shiptest
23,000
code/modules/mining/lavaland/ash_flora.dm
//*******************Contains everything related to the flora on lavaland.******************************* //This includes: The structures, their produce, their seeds and the crafting recipe for the mushroom bowl /obj/structure/flora/ash gender = PLURAL layer = PROJECTILE_HIT_THRESHHOLD_LAYER //sporangiums up don't shoot icon = 'icons/obj/lavaland/ash_flora.dmi' icon_state = "l_mushroom" name = "large mushrooms" desc = "A number of large mushrooms, covered in a faint layer of ash and what can only be spores." var/harvested_name = "shortened mushrooms" var/harvested_desc = "Some quickly regrowing mushrooms, formerly known to be quite large." var/needs_sharp_harvest = TRUE var/harvest = /obj/item/food/grown/ash_flora/shavings var/harvest_amount_low = 1 var/harvest_amount_high = 3 var/harvest_time = 60 var/harvest_message_low = "You pick a mushroom, but fail to collect many shavings from its cap." var/harvest_message_med = "You pick a mushroom, carefully collecting the shavings from its cap." var/harvest_message_high = "You harvest and collect shavings from several mushroom caps." var/harvested = FALSE var/base_icon var/regrowth_time_low = 8 MINUTES var/regrowth_time_high = 16 MINUTES var/num_sprites = 4 // WS edit - WS /obj/structure/flora/ash/Initialize() . = ..() if(num_sprites == 1) //stops unnecessary randomization of harvestable flora icons with only one variation. Remember to set num_sprites on your flora! base_icon = "[icon_state]" icon_state = base_icon else base_icon = "[icon_state][rand(1, num_sprites)]" //randomizing icons like this prevents the icon of the structure from loading properly in mapping tools. Works fine ingame. icon_state = base_icon /obj/structure/flora/ash/proc/harvest(user) if(harvested) return 0 var/rand_harvested = rand(harvest_amount_low, harvest_amount_high) if(rand_harvested) if(user) var/msg = harvest_message_med if(rand_harvested == harvest_amount_low) msg = harvest_message_low else if(rand_harvested == harvest_amount_high) msg = harvest_message_high to_chat(user, span_notice("[msg]")) for(var/i in 1 to rand_harvested) new harvest(get_turf(src)) icon_state = "[base_icon]p" name = harvested_name desc = harvested_desc harvested = TRUE addtimer(CALLBACK(src, PROC_REF(regrow)), rand(regrowth_time_low, regrowth_time_high)) return 1 /obj/structure/flora/ash/proc/regrow() icon_state = base_icon name = initial(name) desc = initial(desc) harvested = FALSE /obj/structure/flora/ash/attackby(obj/item/W, mob/user, params) if(!harvested && needs_sharp_harvest && W.get_sharpness()) user.visible_message(span_notice("[user] starts to harvest from [src] with [W]."),span_notice("You begin to harvest from [src] with [W].")) if(do_after(user, harvest_time, target = src)) harvest(user) else return ..() /obj/structure/flora/ash/attack_hand(mob/user) . = ..() if(.) return if(!harvested && !needs_sharp_harvest) user.visible_message(span_notice("[user] starts to harvest from [src]."),span_notice("You begin to harvest from [src].")) if(do_after(user, harvest_time, target = src)) harvest(user) /obj/structure/flora/ash/tall_shroom //exists only so that the spawning check doesn't allow these spawning near other things regrowth_time_low = 4200 /obj/structure/flora/ash/leaf_shroom icon_state = "s_mushroom" name = "leafy mushrooms" desc = "A number of mushrooms, each of which surrounds a greenish sporangium with a number of leaf-like structures." harvested_name = "leafless mushrooms" harvested_desc = "A bunch of formerly-leafed mushrooms, with their sporangiums exposed. Scandalous?" harvest = /obj/item/food/grown/ash_flora/mushroom_leaf needs_sharp_harvest = FALSE harvest_amount_high = 4 harvest_time = 20 harvest_message_low = "You pluck a single, suitable leaf." harvest_message_med = "You pluck a number of leaves, leaving a few unsuitable ones." harvest_message_high = "You pluck quite a lot of suitable leaves." regrowth_time_low = 2400 regrowth_time_high = 6000 /obj/structure/flora/ash/cap_shroom icon_state = "r_mushroom" name = "tall mushrooms" desc = "Several mushrooms, the larger of which have a ring of conks at the midpoint of their stems." harvested_name = "small mushrooms" harvested_desc = "Several small mushrooms near the stumps of what likely were larger mushrooms." harvest = /obj/item/food/grown/ash_flora/mushroom_cap harvest_amount_high = 4 harvest_time = 50 harvest_message_low = "You slice the cap off a mushroom." harvest_message_med = "You slice off a few conks from the larger mushrooms." harvest_message_high = "You slice off a number of caps and conks from these mushrooms." regrowth_time_low = 3000 regrowth_time_high = 5400 /obj/structure/flora/ash/stem_shroom icon_state = "t_mushroom" name = "numerous mushrooms" desc = "A large number of mushrooms, some of which have long, fleshy stems. They're radiating light!" light_range = 1.5 light_power = 2.1 harvested_name = "tiny mushrooms" harvested_desc = "A few tiny mushrooms around larger stumps. You can already see them growing back." harvest = /obj/item/food/grown/ash_flora/mushroom_stem harvest_amount_high = 4 harvest_time = 40 harvest_message_low = "You pick and slice the cap off a mushroom, leaving the stem." harvest_message_med = "You pick and decapitate several mushrooms for their stems." harvest_message_high = "You acquire a number of stems from these mushrooms." regrowth_time_low = 3000 regrowth_time_high = 6000 /obj/structure/flora/ash/cacti icon_state = "cactus" name = "fruiting cacti" desc = "Several prickly cacti, brimming with ripe fruit and covered in a thin layer of ash." harvested_name = "cacti" harvested_desc = "A bunch of prickly cacti. You can see fruits slowly growing beneath the covering of ash." harvest = /obj/item/food/grown/ash_flora/cactus_fruit needs_sharp_harvest = FALSE harvest_amount_high = 2 harvest_time = 10 harvest_message_low = "You pick a cactus fruit." harvest_message_med = "You pick several cactus fruit." //shouldn't show up, because you can't get more than two harvest_message_high = "You pick a pair of cactus fruit." regrowth_time_low = 4800 regrowth_time_high = 7200 /obj/structure/flora/ash/cacti/Initialize(mapload) . = ..() // min dmg 3, max dmg 6, prob(70) AddComponent(/datum/component/caltrop, 3, 6, 70) ///Snow flora to exist on icebox. /obj/structure/flora/ash/chilly icon_state = "chilly_pepper" name = "springy grassy fruit" desc = "A number of bright, springy blue fruiting plants. They seem to be unconcerned with the hardy, cold environment." harvested_name = "springy grass" harvested_desc = "A bunch of springy, bouncy fruiting grass, all picked. Or maybe they were never fruiting at all?" harvest = /obj/item/food/grown/icepepper needs_sharp_harvest = FALSE harvest_amount_high = 3 harvest_time = 15 harvest_message_low = "You pluck a single, curved fruit." harvest_message_med = "You pluck a number of curved fruit." harvest_message_high = "You pluck quite a lot of curved fruit." regrowth_time_low = 2400 regrowth_time_high = 5500 num_sprites = 1 /obj/structure/flora/ash/fern name = "cave fern" desc = "A species of fern with highly fibrous leaves." icon_state = "cavefern" //needs new sprites. harvested_name = "cave fern stems" harvested_desc = "A few cave fern stems, missing their leaves." harvest = /obj/item/food/grown/ash_flora/fern harvest_amount_high = 4 harvest_message_low = "You clip a single, suitable leaf." harvest_message_med = "You clip a number of leaves, leaving a few unsuitable ones." harvest_message_high = "You clip quite a lot of suitable leaves." regrowth_time_low = 3000 regrowth_time_high = 5400 num_sprites = 1 /obj/structure/flora/ash/fireblossom name = "fire blossom" desc = "An odd flower that grows commonly near bodies of lava. The leaves can be ground up for a substance resembling capsaicin." icon_state = "fireblossom" harvested_name = "fire blossom stems" harvested_desc = "A few fire blossom stems, missing their flowers." harvest = /obj/item/food/grown/ash_flora/fireblossom needs_sharp_harvest = FALSE harvest_amount_high = 3 harvest_message_low = "You pluck a single, suitable flower." harvest_message_med = "You pluck a number of flowers, leaving a few unsuitable ones." harvest_message_high = "You pluck quite a lot of suitable flowers." regrowth_time_low = 2500 regrowth_time_high = 4000 num_sprites = 2 /obj/structure/flora/ash/puce name = "Pucestal Growth" desc = "A collection of puce colored crystal growths." icon_state = "pucetal" harvested_name = "Pucestal fragments" harvested_desc = "A few pucestal fragments, slowly regrowing." harvest = /obj/item/food/grown/ash_flora/puce harvest_amount_high = 6 harvest_message_low = "You work a crystal free." harvest_message_med = "You cut a number of crystals free, leaving a few small ones." harvest_message_high = "You cut free quite a lot of crystals." regrowth_time_low = 10 MINUTES regrowth_time_high = 20 MINUTES num_sprites = 1 /obj/item/food/grown/ash_flora name = "mushroom shavings" desc = "Some shavings from a tall mushroom. With enough, might serve as a bowl." icon = 'icons/obj/lavaland/ash_flora.dmi' icon_state = "l_mushroom" w_class = WEIGHT_CLASS_TINY resistance_flags = FLAMMABLE max_integrity = 100 seed = /obj/item/seeds/lavaland/polypore wine_power = 20 /obj/item/food/grown/ash_flora/Initialize() . = ..() pixel_x = rand(-4, 4) pixel_y = rand(-4, 4) /obj/item/food/grown/ash_flora/shavings //So we can't craft bowls from everything. /obj/item/food/grown/ash_flora/mushroom_leaf name = "mushroom leaf" desc = "A leaf, from a mushroom." icon_state = "s_mushroom" seed = /obj/item/seeds/lavaland/porcini wine_power = 40 /obj/item/food/grown/ash_flora/mushroom_cap name = "mushroom cap" desc = "The cap of a large mushroom." icon_state = "r_mushroom" seed = /obj/item/seeds/lavaland/inocybe wine_power = 70 /obj/item/food/grown/ash_flora/mushroom_stem name = "mushroom stem" desc = "A long mushroom stem. It's slightly glowing." icon_state = "t_mushroom" seed = /obj/item/seeds/lavaland/ember wine_power = 60 /obj/item/food/grown/ash_flora/cactus_fruit name = "cactus fruit" desc = "A cactus fruit covered in a thick, reddish skin. And some ash." icon_state = "cactus" seed = /obj/item/seeds/lavaland/cactus wine_power = 50 /obj/item/food/grown/ash_flora/fern name = "fern leaf" desc = "A leaf from a cave fern." icon_state = "fern" seed = /obj/item/seeds/lavaland/fern wine_power = 10 /obj/item/food/grown/ash_flora/fireblossom name = "fire blossom" desc = "A flower from a fire blossom." icon_state = "fireblossom" slot_flags = ITEM_SLOT_HEAD seed = /obj/item/seeds/lavaland/fireblossom wine_power = 40 /obj/item/food/grown/ash_flora/puce name = "Pucestal Crystal" desc = "A crystal from a pucestal growth." icon_state = "puce" seed = /obj/item/seeds/lavaland/puce wine_power = 1 foodtypes = TOXIC | GROSS //yum //SEEDS /obj/item/seeds/lavaland name = "lavaland seeds" desc = "You should never see this." lifespan = 50 endurance = 25 maturation = 7 production = 4 yield = 4 potency = 15 growthstages = 3 rarity = 20 reagents_add = list(/datum/reagent/consumable/nutriment = 0.1) resistance_flags = FIRE_PROOF species = "polypore" //silence unit test /obj/item/seeds/lavaland/cactus name = "pack of fruiting cactus seeds" desc = "These seeds grow into fruiting cacti." icon_state = "seed-cactus" species = "cactus" plantname = "Fruiting Cactus" product = /obj/item/food/grown/ash_flora/cactus_fruit genes = list(/datum/plant_gene/trait/fire_resistance) growing_icon = 'icons/obj/hydroponics/growing_fruits.dmi' growthstages = 2 reagents_add = list(/datum/reagent/consumable/nutriment/vitamin = 0.04, /datum/reagent/consumable/nutriment = 0.04, /datum/reagent/consumable/vitfro = 0.1) research = PLANT_RESEARCH_TIER_1 /obj/item/seeds/lavaland/polypore name = "pack of polypore mycelium" desc = "This mycelium grows into bracket mushrooms, also known as polypores. Woody and firm, shaft miners often use them for makeshift crafts." icon_state = "mycelium-polypore" species = "polypore" plantname = "Polypore Mushrooms" product = /obj/item/food/grown/ash_flora/shavings genes = list(/datum/plant_gene/trait/plant_type/fungal_metabolism, /datum/plant_gene/trait/fire_resistance) growing_icon = 'icons/obj/hydroponics/growing_mushrooms.dmi' reagents_add = list(/datum/reagent/consumable/ethanol = 0.04, /datum/reagent/stabilizing_agent = 0.06, /datum/reagent/toxin/minttoxin = 0.015) research = PLANT_RESEARCH_TIER_1 /obj/item/seeds/lavaland/porcini name = "pack of porcini mycelium" desc = "This mycelium grows into Boletus edulus, also known as porcini. Native to the late Earth, but discovered on Lavaland. Has culinary, medicinal and relaxant effects." icon_state = "mycelium-porcini" species = "porcini" plantname = "Porcini Mushrooms" product = /obj/item/food/grown/ash_flora/mushroom_leaf genes = list(/datum/plant_gene/trait/plant_type/fungal_metabolism, /datum/plant_gene/trait/fire_resistance) growing_icon = 'icons/obj/hydroponics/growing_mushrooms.dmi' reagents_add = list(/datum/reagent/consumable/nutriment = 0.05, /datum/reagent/consumable/vitfro = 0.04, /datum/reagent/drug/nicotine = 0.04, /datum/reagent/consumable/sugar = 0.03) research = PLANT_RESEARCH_TIER_1 /obj/item/seeds/lavaland/inocybe name = "pack of inocybe mycelium" desc = "This mycelium grows into an inocybe mushroom, a species of Lavaland origin with hallucinatory and toxic effects." icon_state = "mycelium-inocybe" species = "inocybe" plantname = "Inocybe Mushrooms" product = /obj/item/food/grown/ash_flora/mushroom_cap genes = list(/datum/plant_gene/trait/plant_type/fungal_metabolism, /datum/plant_gene/trait/fire_resistance) growing_icon = 'icons/obj/hydroponics/growing_mushrooms.dmi' reagents_add = list(/datum/reagent/toxin/mindbreaker = 0.04, /datum/reagent/consumable/entpoly = 0.1, /datum/reagent/drug/mushroomhallucinogen = 0.05) research = PLANT_RESEARCH_TIER_1 /obj/item/seeds/lavaland/ember name = "pack of embershroom mycelium" desc = "This mycelium grows into embershrooms, a species of bioluminescent mushrooms native to Lavaland." icon_state = "mycelium-ember" species = "ember" plantname = "Embershroom Mushrooms" product = /obj/item/food/grown/ash_flora/mushroom_stem genes = list(/datum/plant_gene/trait/plant_type/fungal_metabolism, /datum/plant_gene/trait/glow, /datum/plant_gene/trait/fire_resistance) growing_icon = 'icons/obj/hydroponics/growing_mushrooms.dmi' reagents_add = list(/datum/reagent/consumable/tinlux = 0.04, /datum/reagent/consumable/nutriment/vitamin = 0.02, /datum/reagent/drug/space_drugs = 0.02) research = PLANT_RESEARCH_TIER_1 /obj/item/seeds/lavaland/fern name = "pack of cave fern seeds" desc = "These seeds grow into cave ferns." plantname = "Cave Fern" icon_state = "seed_fern" species = "fern" growthstages = 2 product = /obj/item/food/grown/ash_flora/fern genes = list(/datum/plant_gene/trait/fire_resistance, /datum/plant_gene/trait/plant_type/weed_hardy) reagents_add = list(/datum/reagent/ash_fibers = 0.1) research = PLANT_RESEARCH_TIER_1 /obj/item/seeds/lavaland/fern/Initialize(mapload,nogenes) . = ..() if(!nogenes) unset_mutability(/datum/plant_gene/reagent, PLANT_GENE_EXTRACTABLE) /obj/item/seeds/lavaland/fireblossom name = "pack of fire blossom seeds" desc = "These seeds grow into fire blossoms." plantname = "Fire Blossom" icon_state = "seed_fireblossom" species = "fireblossom" growthstages = 3 product = /obj/item/food/grown/ash_flora/fireblossom genes = list(/datum/plant_gene/trait/fire_resistance, /datum/plant_gene/trait/glow/yellow) reagents_add = list(/datum/reagent/consumable/pyre_elementum = 0.09, /datum/reagent/carbon = 0.05, /datum/reagent/consumable/nutriment = 0.03) research = PLANT_RESEARCH_TIER_2 /obj/item/seeds/lavaland/puce name = "puce cluster" desc = "These crystals can be grown into larger crystals." plantname = "Pucestal Growth" icon_state = "cluster_puce" species = "puce" growthstages = 3 product = /obj/item/food/grown/ash_flora/puce genes = list(/datum/plant_gene/trait/plant_type/crystal) reagents_add = list(/datum/reagent/medicine/puce_essence = 0.1) research = PLANT_RESEARCH_TIER_3 /obj/item/seeds/lavaland/puce/Initialize(mapload,nogenes) . = ..() if(!nogenes) unset_mutability(/datum/plant_gene/reagent, PLANT_GENE_REMOVABLE) unset_mutability(/datum/plant_gene/trait/plant_type/crystal, PLANT_GENE_REMOVABLE) unset_mutability(/datum/plant_gene/reagent, PLANT_GENE_EXTRACTABLE) unset_mutability(/datum/plant_gene/trait/plant_type/crystal, PLANT_GENE_EXTRACTABLE) /obj/item/seeds/lavaland/puce/attackby(obj/item/item, mob/user, params) . = ..() //anyone intending to add more garnishes using this method should componentize this if(!istype(item, /obj/item/melee/knife)) return playsound(src, 'sound/effects/glassbr1.ogg', 50, TRUE, -1) to_chat(user, span_notice("You start breaking [src] up into shards...")) if(!do_after(user, 1 SECONDS, src)) return var/obj/item/result = new /obj/item/garnish/puce(drop_location()) var/give_to_user = user.is_holding(src) qdel(src) if(give_to_user) user.put_in_hands(result) to_chat(user, span_notice("You finish breaking [src]")) /obj/item/reagent_containers/glass/bowl/mushroom_bowl name = "mushroom bowl" desc = "A bowl made out of mushrooms. Not food, though it might have contained some at some point." icon = 'icons/obj/lavaland/ash_flora.dmi' icon_state = "mushroom_bowl" fill_icon = 'icons/obj/lavaland/ash_flora.dmi' /obj/structure/flora/ash/proc/consume(user) if(harvested) return 0 icon_state = "[base_icon]p" name = harvested_name desc = harvested_desc harvested = TRUE addtimer(CALLBACK(src, PROC_REF(regrow)), rand(regrowth_time_low, regrowth_time_high)) return 1 /obj/structure/flora/ash/glowshroom name = "glowshroom colony" desc = "A small, hardy patch of radiovoric glowshrooms, busying themselves in their attempts to decontaminate the soil." icon_state = "glowshroom" harvested_name = "glowshroom colony" harvested_desc = "A small, hardy patch of radiovoric glowshrooms. Someone seems to have come by and picked all the larger ones." harvest = /obj/item/food/grown/mushroom/glowshroom harvest_amount_high = 6 harvest_amount_low = 1 harvest_message_low = "You only find a single intact stalk, discarding a number of stunted or rotted shrooms." harvest_message_med = "You collect a bundle of glowing fungi." harvest_message_high = "You manage to find several proudly-glowing shrooms of impressive size." regrowth_time_low = 10 MINUTES regrowth_time_high = 20 MINUTES num_sprites = 1 light_power = 0.5 light_range = 3 light_color = "#11fa25" //Gardens// //these guys spawn a variety of seeds at random, slightly weighted. Intended as a stopgap until we can add more custom flora. /obj/structure/flora/ash/garden name = "lush garden" gender = NEUTER desc = "In the soil and shade, something softly grows." icon_state = "garden" harvested_name = "lush garden" harvested_desc = "In the soil and shade, something softly grew. It seems some industrious scavenger already passed by." harvest = /obj/effect/spawner/random/food_or_drink/garden harvest_amount_high = 1 harvest_amount_low = 1 harvest_message_low = "You discover something nestled away in the growing bough." harvest_message_med = "You discover something nestled away in the growing bough." harvest_message_high = "You discover something nestled away in the growing bough." regrowth_time_low = 55 MINUTES regrowth_time_high = 60 MINUTES//good luck farming this num_sprites = 1 light_power = 0.5 light_range = 1 needs_sharp_harvest = FALSE ///Used for garden scan missions var/mission_scanned = FALSE /obj/structure/flora/ash/garden/arid name = "rock garden" desc = "Beneath a bluff of soft silicate, a sheltered grove slumbers." icon_state = "gardenarid" harvested_name = "rock garden" harvested_desc = "Beneath a bluff of soft silicate, a sheltered grove slumbered. Some desert wanderer seems to have picked it clean." harvest = /obj/effect/spawner/random/food_or_drink/garden/arid harvest_amount_high = 1 harvest_amount_low = 1 harvest_message_low = "You brush sand away from a verdant prize, nestled in the leaves." harvest_message_med = "You brush sand away from a verdant prize, nestled in the leaves." harvest_message_high = "You brush sand away from a verdant prize, nestled in the leaves." /obj/structure/flora/ash/garden/frigid name = "chilly garden" desc = "A delicate layer of frost covers hardy brush." icon_state = "gardencold" harvested_name = "chilly garden" harvested_desc = "A delicate layer of frost covers hardy brush. Someone came with the blizzard, and left with any prize this might contain." harvest = /obj/effect/spawner/random/food_or_drink/garden/cold harvest_amount_high = 1 harvest_amount_low = 1 harvest_message_low = "You unearth a snow-covered treat." harvest_message_med = "You unearth a snow-covered treat." harvest_message_high = "You unearth a snow-covered treat." /obj/structure/flora/ash/garden/waste name = "sickly garden" desc = "Polluted water wells up from the cracked earth, feeding a patch of something curious." icon_state = "gardensick" harvested_name = "sickly garden" harvested_desc = "Polluted water wells up from the cracked earth, where it once fed a patch of something curious. Now only wilted leaves remain." harvest = /obj/effect/spawner/random/food_or_drink/garden/sick harvest_amount_high = 1 harvest_amount_low = 1 harvest_message_low = "You pry something odd from the poisoned soil." harvest_message_med = "You pry something odd from the poisoned soil." harvest_message_high = "You pry something odd from the poisoned soil." /obj/structure/flora/ash/garden/seaweed //yea, i code :) name = "seaweed patch" gender = NEUTER desc = "A patch of seaweed, floating on the surface of the water" icon_state = "seaweed" harvested_name = "seaweed patch" harvested_desc = "A patch of seaweed, floating on the surface of the water. It seems someone has already searched through this" harvest = /obj/effect/spawner/random/food_or_drink/garden/seaweed harvest_amount_high = 1 harvest_amount_low = 1 harvest_message_low = "You discover some edible weeds within the patch." harvest_message_med = "You discover some edible weeds within the patch." harvest_message_high = "You discover some edible weeds within the patch." /obj/item/food/grown/berries/poison/stealth //careful eating from random jungle bushes seed = /obj/item/seeds/berry/poison name = "bunch of berries" desc = "Nutritious?" icon_state = "berrypile" /obj/item/food/grown/berries/death/stealth //I warned you! seed = /obj/item/seeds/berry/death name = "bunch of berries" desc = "Nutritious?" icon_state = "berrypile"
0
0.845451
1
0.845451
game-dev
MEDIA
0.951832
game-dev
0.596453
1
0.596453
naver/arcus-java-client
6,002
src/main/java/net/spy/memcached/collection/CollectionPipedUpdate.java
/* * arcus-java-client : Arcus Java client * Copyright 2010-2014 NAVER Corp. * Copyright 2014-2021 JaM2in Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.spy.memcached.collection; import java.nio.Buffer; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; import java.util.Map; import net.spy.memcached.CachedData; import net.spy.memcached.KeyUtil; import net.spy.memcached.transcoders.Transcoder; public abstract class CollectionPipedUpdate<T> extends CollectionPipe { protected final String key; protected final Transcoder<T> tc; protected CollectionPipedUpdate(String key, Transcoder<T> tc, int itemCount) { super(itemCount); this.key = key; this.tc = tc; } public static class BTreePipedUpdate<T> extends CollectionPipedUpdate<T> { private static final String COMMAND = "bop update"; private final List<Element<T>> elements; public BTreePipedUpdate(String key, List<Element<T>> elements, Transcoder<T> tc) { super(key, tc, elements.size()); this.elements = elements; } public ByteBuffer getAsciiCommand() { int capacity = 0; // encode parameters List<byte[]> encodedList = new ArrayList<>(elements.size() - nextOpIndex); CachedData cd; int i = 0; for (Element<T> each : elements) { if (i++ >= nextOpIndex) { if (each.getValue() != null) { cd = tc.encode(each.getValue()); encodedList.add(cd.getData()); } else { encodedList.add(null); } } } // estimate the buffer capacity ElementFlagUpdate eflagUpdate; byte[] value; StringBuilder b; int eSize = encodedList.size(); for (i = 0; i < eSize; i++) { Element<T> each = elements.get(i + nextOpIndex); eflagUpdate = each.getElementFlagUpdate(); if (eflagUpdate != null) { // eflag capacity += KeyUtil.getKeyBytes(eflagUpdate.getElementFlagByHex()).length; // fwhere bitwop if (eflagUpdate.getElementFlagOffset() > -1) { capacity += 6; } } capacity += KeyUtil.getKeyBytes(key).length + 64; capacity += KeyUtil.getKeyBytes(each.getStringBkey()).length; if (encodedList.get(i) != null) { capacity += encodedList.get(i).length; } } // allocate the buffer ByteBuffer bb = ByteBuffer.allocate(capacity); // create ascii operation string for (i = 0; i < eSize; i++) { Element<T> element = elements.get(i + nextOpIndex); value = encodedList.get(i); eflagUpdate = element.getElementFlagUpdate(); b = new StringBuilder(); // has element eflag update if (eflagUpdate != null) { // use fwhere bitop if (eflagUpdate.getElementFlagOffset() > -1 && eflagUpdate.getBitOp() != null) { b.append(eflagUpdate.getElementFlagOffset()).append(" "); b.append(eflagUpdate.getBitOp()).append(" "); } b.append(eflagUpdate.getElementFlagByHex()); } setArguments( bb, COMMAND, key, (element.getStringBkey()), b.toString(), (value == null ? -1 : value.length), (i < eSize - 1) ? PIPE : ""); if (value != null) { if (value.length > 0) { bb.put(value); } bb.put(CRLF); } } // flip the buffer ((Buffer) bb).flip(); return bb; } } public static class MapPipedUpdate<T> extends CollectionPipedUpdate<T> { private static final String COMMAND = "mop update"; private final Map<String, T> elements; public MapPipedUpdate(String key, Map<String, T> elements, Transcoder<T> tc) { super(key, tc, elements.size()); this.elements = elements; } public ByteBuffer getAsciiCommand() { int capacity = 0; // encode parameters List<String> mkeyList = new ArrayList<>(elements.size()); List<byte[]> encodedList = new ArrayList<>(elements.size()); CachedData cd; int i = 0; for (Map.Entry<String, T> entry : elements.entrySet()) { if (i++ >= nextOpIndex) { mkeyList.add(entry.getKey()); cd = tc.encode(entry.getValue()); encodedList.add(cd.getData()); } } // estimate the buffer capacity byte[] value; int eSize = encodedList.size(); for (i = 0; i < eSize; i++) { capacity += KeyUtil.getKeyBytes(key).length + 64; capacity += KeyUtil.getKeyBytes(mkeyList.get(i)).length; capacity += encodedList.get(i).length; } // allocate the buffer ByteBuffer bb = ByteBuffer.allocate(capacity); // create ascii operation string StringBuilder b; for (i = 0; i < eSize; i++) { String mkey = mkeyList.get(i); value = encodedList.get(i); b = new StringBuilder(); setArguments(bb, COMMAND, key, mkey, b.toString(), (value == null ? -1 : value.length), (i < eSize - 1) ? PIPE : ""); if (value != null) { if (value.length > 0) { bb.put(value); } bb.put(CRLF); } } // flip the buffer ((Buffer) bb).flip(); return bb; } } }
0
0.907514
1
0.907514
game-dev
MEDIA
0.691595
game-dev
0.985662
1
0.985662
I-asked/downbge
10,599
extern/bullet2/src/BulletCollision/Gimpact/gim_tri_collision.h
#ifndef GIM_TRI_COLLISION_H_INCLUDED #define GIM_TRI_COLLISION_H_INCLUDED /*! \file gim_tri_collision.h \author Francisco Leon Najera */ /* ----------------------------------------------------------------------------- This source file is part of GIMPACT Library. For the latest info, see http://gimpact.sourceforge.net/ Copyright (c) 2006 Francisco Leon Najera. C.C. 80087371. email: projectileman@yahoo.com This library is free software; you can redistribute it and/or modify it under the terms of EITHER: (1) The GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The text of the GNU Lesser General Public License is included with this library in the file GIMPACT-LICENSE-LGPL.TXT. (2) The BSD-style license that is included with this library in the file GIMPACT-LICENSE-BSD.TXT. (3) The zlib/libpng license that is included with this library in the file GIMPACT-LICENSE-ZLIB.TXT. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files GIMPACT-LICENSE-LGPL.TXT, GIMPACT-LICENSE-ZLIB.TXT and GIMPACT-LICENSE-BSD.TXT for more details. ----------------------------------------------------------------------------- */ #include "gim_box_collision.h" #include "gim_clip_polygon.h" #define MAX_TRI_CLIPPING 16 //! Structure for collision struct GIM_TRIANGLE_CONTACT_DATA { GREAL m_penetration_depth; GUINT m_point_count; btVector4 m_separating_normal; btVector3 m_points[MAX_TRI_CLIPPING]; SIMD_FORCE_INLINE void copy_from(const GIM_TRIANGLE_CONTACT_DATA& other) { m_penetration_depth = other.m_penetration_depth; m_separating_normal = other.m_separating_normal; m_point_count = other.m_point_count; GUINT i = m_point_count; while(i--) { m_points[i] = other.m_points[i]; } } GIM_TRIANGLE_CONTACT_DATA() { } GIM_TRIANGLE_CONTACT_DATA(const GIM_TRIANGLE_CONTACT_DATA& other) { copy_from(other); } //! classify points that are closer template<typename DISTANCE_FUNC,typename CLASS_PLANE> SIMD_FORCE_INLINE void mergepoints_generic(const CLASS_PLANE & plane, GREAL margin, const btVector3 * points, GUINT point_count, DISTANCE_FUNC distance_func) { m_point_count = 0; m_penetration_depth= -1000.0f; GUINT point_indices[MAX_TRI_CLIPPING]; GUINT _k; for(_k=0;_k<point_count;_k++) { GREAL _dist = -distance_func(plane,points[_k]) + margin; if(_dist>=0.0f) { if(_dist>m_penetration_depth) { m_penetration_depth = _dist; point_indices[0] = _k; m_point_count=1; } else if((_dist+G_EPSILON)>=m_penetration_depth) { point_indices[m_point_count] = _k; m_point_count++; } } } for( _k=0;_k<m_point_count;_k++) { m_points[_k] = points[point_indices[_k]]; } } //! classify points that are closer SIMD_FORCE_INLINE void merge_points(const btVector4 & plane, GREAL margin, const btVector3 * points, GUINT point_count) { m_separating_normal = plane; mergepoints_generic(plane, margin, points, point_count, DISTANCE_PLANE_3D_FUNC()); } }; //! Class for colliding triangles class GIM_TRIANGLE { public: btScalar m_margin; btVector3 m_vertices[3]; GIM_TRIANGLE():m_margin(0.1f) { } SIMD_FORCE_INLINE GIM_AABB get_box() const { return GIM_AABB(m_vertices[0],m_vertices[1],m_vertices[2],m_margin); } SIMD_FORCE_INLINE void get_normal(btVector3 &normal) const { TRIANGLE_NORMAL(m_vertices[0],m_vertices[1],m_vertices[2],normal); } SIMD_FORCE_INLINE void get_plane(btVector4 &plane) const { TRIANGLE_PLANE(m_vertices[0],m_vertices[1],m_vertices[2],plane);; } SIMD_FORCE_INLINE void apply_transform(const btTransform & trans) { m_vertices[0] = trans(m_vertices[0]); m_vertices[1] = trans(m_vertices[1]); m_vertices[2] = trans(m_vertices[2]); } SIMD_FORCE_INLINE void get_edge_plane(GUINT edge_index,const btVector3 &triangle_normal,btVector4 &plane) const { const btVector3 & e0 = m_vertices[edge_index]; const btVector3 & e1 = m_vertices[(edge_index+1)%3]; EDGE_PLANE(e0,e1,triangle_normal,plane); } //! Gets the relative transformation of this triangle /*! The transformation is oriented to the triangle normal , and aligned to the 1st edge of this triangle. The position corresponds to vertice 0: - triangle normal corresponds to Z axis. - 1st normalized edge corresponds to X axis, */ SIMD_FORCE_INLINE void get_triangle_transform(btTransform & triangle_transform) const { btMatrix3x3 & matrix = triangle_transform.getBasis(); btVector3 zaxis; get_normal(zaxis); MAT_SET_Z(matrix,zaxis); btVector3 xaxis = m_vertices[1] - m_vertices[0]; VEC_NORMALIZE(xaxis); MAT_SET_X(matrix,xaxis); //y axis xaxis = zaxis.cross(xaxis); MAT_SET_Y(matrix,xaxis); triangle_transform.setOrigin(m_vertices[0]); } //! Test triangles by finding separating axis /*! \param other Triangle for collide \param contact_data Structure for holding contact points, normal and penetration depth; The normal is pointing toward this triangle from the other triangle */ bool collide_triangle_hard_test( const GIM_TRIANGLE & other, GIM_TRIANGLE_CONTACT_DATA & contact_data) const; //! Test boxes before doing hard test /*! \param other Triangle for collide \param contact_data Structure for holding contact points, normal and penetration depth; The normal is pointing toward this triangle from the other triangle \ */ SIMD_FORCE_INLINE bool collide_triangle( const GIM_TRIANGLE & other, GIM_TRIANGLE_CONTACT_DATA & contact_data) const { //test box collisioin GIM_AABB boxu(m_vertices[0],m_vertices[1],m_vertices[2],m_margin); GIM_AABB boxv(other.m_vertices[0],other.m_vertices[1],other.m_vertices[2],other.m_margin); if(!boxu.has_collision(boxv)) return false; //do hard test return collide_triangle_hard_test(other,contact_data); } /*! Solve the System for u,v parameters: u*axe1[i1] + v*axe2[i1] = vecproj[i1] u*axe1[i2] + v*axe2[i2] = vecproj[i2] sustitute: v = (vecproj[i2] - u*axe1[i2])/axe2[i2] then the first equation in terms of 'u': --> u*axe1[i1] + ((vecproj[i2] - u*axe1[i2])/axe2[i2])*axe2[i1] = vecproj[i1] --> u*axe1[i1] + vecproj[i2]*axe2[i1]/axe2[i2] - u*axe1[i2]*axe2[i1]/axe2[i2] = vecproj[i1] --> u*(axe1[i1] - axe1[i2]*axe2[i1]/axe2[i2]) = vecproj[i1] - vecproj[i2]*axe2[i1]/axe2[i2] --> u*((axe1[i1]*axe2[i2] - axe1[i2]*axe2[i1])/axe2[i2]) = (vecproj[i1]*axe2[i2] - vecproj[i2]*axe2[i1])/axe2[i2] --> u*(axe1[i1]*axe2[i2] - axe1[i2]*axe2[i1]) = vecproj[i1]*axe2[i2] - vecproj[i2]*axe2[i1] --> u = (vecproj[i1]*axe2[i2] - vecproj[i2]*axe2[i1]) /(axe1[i1]*axe2[i2] - axe1[i2]*axe2[i1]) if 0.0<= u+v <=1.0 then they are inside of triangle \return false if the point is outside of triangle.This function doesn't take the margin */ SIMD_FORCE_INLINE bool get_uv_parameters( const btVector3 & point, const btVector3 & tri_plane, GREAL & u, GREAL & v) const { btVector3 _axe1 = m_vertices[1]-m_vertices[0]; btVector3 _axe2 = m_vertices[2]-m_vertices[0]; btVector3 _vecproj = point - m_vertices[0]; GUINT _i1 = (tri_plane.closestAxis()+1)%3; GUINT _i2 = (_i1+1)%3; if(btFabs(_axe2[_i2])<G_EPSILON) { u = (_vecproj[_i2]*_axe2[_i1] - _vecproj[_i1]*_axe2[_i2]) /(_axe1[_i2]*_axe2[_i1] - _axe1[_i1]*_axe2[_i2]); v = (_vecproj[_i1] - u*_axe1[_i1])/_axe2[_i1]; } else { u = (_vecproj[_i1]*_axe2[_i2] - _vecproj[_i2]*_axe2[_i1]) /(_axe1[_i1]*_axe2[_i2] - _axe1[_i2]*_axe2[_i1]); v = (_vecproj[_i2] - u*_axe1[_i2])/_axe2[_i2]; } if(u<-G_EPSILON) { return false; } else if(v<-G_EPSILON) { return false; } else { btScalar sumuv; sumuv = u+v; if(sumuv<-G_EPSILON) { return false; } else if(sumuv-1.0f>G_EPSILON) { return false; } } return true; } //! is point in triangle beam? /*! Test if point is in triangle, with m_margin tolerance */ SIMD_FORCE_INLINE bool is_point_inside(const btVector3 & point, const btVector3 & tri_normal) const { //Test with edge 0 btVector4 edge_plane; this->get_edge_plane(0,tri_normal,edge_plane); GREAL dist = DISTANCE_PLANE_POINT(edge_plane,point); if(dist-m_margin>0.0f) return false; // outside plane this->get_edge_plane(1,tri_normal,edge_plane); dist = DISTANCE_PLANE_POINT(edge_plane,point); if(dist-m_margin>0.0f) return false; // outside plane this->get_edge_plane(2,tri_normal,edge_plane); dist = DISTANCE_PLANE_POINT(edge_plane,point); if(dist-m_margin>0.0f) return false; // outside plane return true; } //! Bidireccional ray collision SIMD_FORCE_INLINE bool ray_collision( const btVector3 & vPoint, const btVector3 & vDir, btVector3 & pout, btVector3 & triangle_normal, GREAL & tparam, GREAL tmax = G_REAL_INFINITY) { btVector4 faceplane; { btVector3 dif1 = m_vertices[1] - m_vertices[0]; btVector3 dif2 = m_vertices[2] - m_vertices[0]; VEC_CROSS(faceplane,dif1,dif2); faceplane[3] = m_vertices[0].dot(faceplane); } GUINT res = LINE_PLANE_COLLISION(faceplane,vDir,vPoint,pout,tparam, btScalar(0), tmax); if(res == 0) return false; if(! is_point_inside(pout,faceplane)) return false; if(res==2) //invert normal { triangle_normal.setValue(-faceplane[0],-faceplane[1],-faceplane[2]); } else { triangle_normal.setValue(faceplane[0],faceplane[1],faceplane[2]); } VEC_NORMALIZE(triangle_normal); return true; } //! one direccion ray collision SIMD_FORCE_INLINE bool ray_collision_front_side( const btVector3 & vPoint, const btVector3 & vDir, btVector3 & pout, btVector3 & triangle_normal, GREAL & tparam, GREAL tmax = G_REAL_INFINITY) { btVector4 faceplane; { btVector3 dif1 = m_vertices[1] - m_vertices[0]; btVector3 dif2 = m_vertices[2] - m_vertices[0]; VEC_CROSS(faceplane,dif1,dif2); faceplane[3] = m_vertices[0].dot(faceplane); } GUINT res = LINE_PLANE_COLLISION(faceplane,vDir,vPoint,pout,tparam, btScalar(0), tmax); if(res != 1) return false; if(!is_point_inside(pout,faceplane)) return false; triangle_normal.setValue(faceplane[0],faceplane[1],faceplane[2]); VEC_NORMALIZE(triangle_normal); return true; } }; #endif // GIM_TRI_COLLISION_H_INCLUDED
0
0.970493
1
0.970493
game-dev
MEDIA
0.936005
game-dev
0.996074
1
0.996074
TerraformersMC/Traverse
7,142
common/src/main/java/com/terraformersmc/traverse/item/TraverseItemGroups.java
package com.terraformersmc.traverse.item; import com.terraformersmc.traverse.Traverse; import com.terraformersmc.traverse.block.TraverseBlocks; import com.terraformersmc.traverse.boat.TraverseBoats; import net.fabricmc.fabric.api.itemgroup.v1.FabricItemGroup; import net.fabricmc.fabric.api.itemgroup.v1.ItemGroupEvents; import net.minecraft.item.*; import net.minecraft.registry.Registries; import net.minecraft.registry.Registry; import net.minecraft.registry.RegistryKey; import net.minecraft.registry.RegistryKeys; import net.minecraft.resource.featuretoggle.FeatureSet; import net.minecraft.text.Text; import net.minecraft.util.Identifier; import org.jetbrains.annotations.Nullable; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.stream.Collectors; public class TraverseItemGroups { private static final RegistryKey<ItemGroup> ITEM_GROUP = RegistryKey.of(RegistryKeys.ITEM_GROUP, Identifier.of(Traverse.MOD_ID, "items")); private static final HashMap<RegistryKey<ItemGroup>, HashMap<ItemConvertible, ItemGroupEntries>> ITEM_GROUP_ENTRY_MAPS; static { ITEM_GROUP_ENTRY_MAPS = new HashMap<>(8); /* * These items are the last Vanilla item of a "similar" type to items we add to Vanilla groups. * Each is used to build a collection of items which will be inserted below the Vanilla item. */ final Item BUILDING_WOOD_ITEMS = Items.PALE_OAK_BUTTON; final Item FUNCTIONAL_SHELF = Items.PALE_OAK_SHELF; final Item FUNCTIONAL_SIGN = Items.PALE_OAK_HANGING_SIGN; final Item NATURAL_LEAVES = Items.FLOWERING_AZALEA_LEAVES; final Item NATURAL_SAPLING = Items.PALE_OAK_SAPLING; final Item NATURAL_LOG = Items.PALE_OAK_LOG; final Item TOOLS_BOAT = Items.PALE_OAK_CHEST_BOAT; /* * For each Vanilla item group, add the same kinds of items Vanilla adds. * Since Minecraft 1.19.3, items are often in multiple item groups... */ // BUILDING BLOCKS // Wood items addGroupEntry(TraverseBlocks.FIR_LOG, ItemGroups.BUILDING_BLOCKS, BUILDING_WOOD_ITEMS); addGroupEntry(TraverseBlocks.FIR_WOOD, ItemGroups.BUILDING_BLOCKS, BUILDING_WOOD_ITEMS); addGroupEntry(TraverseBlocks.STRIPPED_FIR_LOG, ItemGroups.BUILDING_BLOCKS, BUILDING_WOOD_ITEMS); addGroupEntry(TraverseBlocks.STRIPPED_FIR_WOOD, ItemGroups.BUILDING_BLOCKS, BUILDING_WOOD_ITEMS); addGroupEntry(TraverseBlocks.FIR_PLANKS, ItemGroups.BUILDING_BLOCKS, BUILDING_WOOD_ITEMS); addGroupEntry(TraverseBlocks.FIR_STAIRS, ItemGroups.BUILDING_BLOCKS, BUILDING_WOOD_ITEMS); addGroupEntry(TraverseBlocks.FIR_SLAB, ItemGroups.BUILDING_BLOCKS, BUILDING_WOOD_ITEMS); addGroupEntry(TraverseBlocks.FIR_FENCE, ItemGroups.BUILDING_BLOCKS, BUILDING_WOOD_ITEMS); addGroupEntry(TraverseBlocks.FIR_FENCE_GATE, ItemGroups.BUILDING_BLOCKS, BUILDING_WOOD_ITEMS); addGroupEntry(TraverseBlocks.FIR_DOOR, ItemGroups.BUILDING_BLOCKS, BUILDING_WOOD_ITEMS); addGroupEntry(TraverseBlocks.FIR_TRAPDOOR, ItemGroups.BUILDING_BLOCKS, BUILDING_WOOD_ITEMS); addGroupEntry(TraverseBlocks.FIR_PRESSURE_PLATE, ItemGroups.BUILDING_BLOCKS, BUILDING_WOOD_ITEMS); addGroupEntry(TraverseBlocks.FIR_BUTTON, ItemGroups.BUILDING_BLOCKS, BUILDING_WOOD_ITEMS); // NATURAL // Wood Items addGroupEntry(TraverseBlocks.FIR_LOG, ItemGroups.NATURAL, NATURAL_LOG); // Saplings addGroupEntry(TraverseBlocks.BROWN_AUTUMNAL_SAPLING, ItemGroups.NATURAL, NATURAL_SAPLING); addGroupEntry(TraverseBlocks.ORANGE_AUTUMNAL_SAPLING, ItemGroups.NATURAL, NATURAL_SAPLING); addGroupEntry(TraverseBlocks.RED_AUTUMNAL_SAPLING, ItemGroups.NATURAL, NATURAL_SAPLING); addGroupEntry(TraverseBlocks.YELLOW_AUTUMNAL_SAPLING, ItemGroups.NATURAL, NATURAL_SAPLING); addGroupEntry(TraverseBlocks.FIR_SAPLING, ItemGroups.NATURAL, NATURAL_SAPLING); // Leaves addGroupEntry(TraverseBlocks.BROWN_AUTUMNAL_LEAVES, ItemGroups.NATURAL, NATURAL_LEAVES); addGroupEntry(TraverseBlocks.ORANGE_AUTUMNAL_LEAVES, ItemGroups.NATURAL, NATURAL_LEAVES); addGroupEntry(TraverseBlocks.RED_AUTUMNAL_LEAVES, ItemGroups.NATURAL, NATURAL_LEAVES); addGroupEntry(TraverseBlocks.YELLOW_AUTUMNAL_LEAVES, ItemGroups.NATURAL, NATURAL_LEAVES); addGroupEntry(TraverseBlocks.FIR_LEAVES, ItemGroups.NATURAL, NATURAL_LEAVES); // FUNCTIONAL // Wood Items addGroupEntry(TraverseBlocks.FIR_SHELF, ItemGroups.FUNCTIONAL, FUNCTIONAL_SHELF); addGroupEntry(TraverseBlocks.FIR_SIGN, ItemGroups.FUNCTIONAL, FUNCTIONAL_SIGN); addGroupEntry(TraverseBlocks.FIR_HANGING_SIGN, ItemGroups.FUNCTIONAL, FUNCTIONAL_SIGN); // REDSTONE // HOTBAR // SEARCH // TOOLS // Boats addGroupEntry(TraverseBoats.FIR_BOAT, ItemGroups.TOOLS, TOOLS_BOAT); addGroupEntry(TraverseBoats.FIR_CHEST_BOAT, ItemGroups.TOOLS, TOOLS_BOAT); // COMBAT // CONSUMABLES // CRAFTING // SPAWN EGGS // INVENTORY /* * Add the items configured above to the Vanilla item groups. */ for (RegistryKey<ItemGroup> group : ITEM_GROUP_ENTRY_MAPS.keySet()) { ItemGroupEvents.modifyEntriesEvent(group).register((content) -> { FeatureSet featureSet = content.getEnabledFeatures(); HashMap<ItemConvertible, ItemGroupEntries> entryMap = ITEM_GROUP_ENTRY_MAPS.get(group); for (ItemConvertible relative : entryMap.keySet()) { ItemGroupEntries entries = entryMap.get(relative); // FAPI does not give us a way to add at a feature-flag-disabled location. // So, below we have to adjust for any items which may be disabled. if (relative == null) { // Target the end of the Item Group content.addAll(entries.getCollection()); } else { //Traverse.LOGGER.warn("About to add to Vanilla Item Group '{}' after Item '{}': '{}'", group.getValue(), relative, entries.getCollection().stream().map(ItemStack::getItem).collect(Collectors.toList())); content.addAfter(relative, entries.getCollection()); } } }); } /* * Also add all the items to Traverse's own item group. */ Registry.register(Registries.ITEM_GROUP, ITEM_GROUP, FabricItemGroup.builder() .displayName(Text.literal("Traverse")) .icon(() -> TraverseBlocks.FIR_SAPLING.asItem().getDefaultStack()) .entries((context, entries) -> { ITEM_GROUP_ENTRY_MAPS.values().stream() .map(HashMap::values).flatMap(Collection::stream) .map(ItemGroupEntries::getCollection).flatMap(Collection::stream) .collect(Collectors.groupingByConcurrent(ItemStack::getItem)).keySet().stream() .sorted(Comparator.comparing((item) -> item.getName().getString())).forEach(entries::add); }).build() ); } public static void addGroupEntry(ItemConvertible item, RegistryKey<ItemGroup> group) { // Appends the item to the bottom of the group. addGroupEntry(item, group, null); } public static void addGroupEntry(ItemConvertible item, RegistryKey<ItemGroup> group, @Nullable ItemConvertible relative) { HashMap<ItemConvertible, ItemGroupEntries> entryMap = ITEM_GROUP_ENTRY_MAPS.computeIfAbsent(group, (key) -> new HashMap<>(32)); ItemGroupEntries entries = entryMap.computeIfAbsent(relative, ItemGroupEntries::empty); entries.addItem(item); } public static void register() { } }
0
0.947949
1
0.947949
game-dev
MEDIA
0.994802
game-dev
0.930943
1
0.930943
rei-2/Amalgam
1,611
Amalgam/src/Hooks/CAttributeManager_AttribHookValue.cpp
#include "../SDK/SDK.h" MAKE_SIGNATURE(CAttributeManager_AttribHookInt, "client.dll", "4C 8B DC 49 89 5B ? 49 89 6B ? 49 89 73 ? 57 41 54 41 55 41 56 41 57 48 83 EC ? 48 8B 3D ? ? ? ? 4C 8D 35", 0x0); MAKE_SIGNATURE(CTFPlayer_FireEvent_AttribHookValue_Call, "client.dll", "8B F8 83 BE", 0x0); static inline int ColorToInt(Color_t col) { return col.r << 16 | col.g << 8 | col.b; } MAKE_HOOK(CAttributeManager_AttribHookInt, S::CAttributeManager_AttribHookInt(), int, int value, const char* name, void* econent, void* buffer, bool isGlobalConstString) { #ifdef DEBUG_HOOKS if (!Vars::Hooks::CAttributeManager_AttribHookValue[DEFAULT_BIND]) return CALL_ORIGINAL(value, name, econent, buffer, isGlobalConstString); #endif static const auto dwDesired = S::CTFPlayer_FireEvent_AttribHookValue_Call(); const auto dwRetAddr = uintptr_t(_ReturnAddress()); if (!Vars::Visuals::Effects::SpellFootsteps.Value || econent != H::Entities.GetLocal() || I::EngineClient->IsTakingScreenshot() && Vars::Visuals::UI::CleanScreenshots.Value) return CALL_ORIGINAL(value, name, econent, buffer, isGlobalConstString); if (dwRetAddr == dwDesired && FNV1A::Hash32(name) == FNV1A::Hash32Const("halloween_footstep_type")) { switch (Vars::Visuals::Effects::SpellFootsteps.Value) { case Vars::Visuals::Effects::SpellFootstepsEnum::Color: return ColorToInt(Vars::Colors::SpellFootstep.Value); case Vars::Visuals::Effects::SpellFootstepsEnum::Team: return 1; case Vars::Visuals::Effects::SpellFootstepsEnum::Halloween: return 2; } } return CALL_ORIGINAL(value, name, econent, buffer, isGlobalConstString); }
0
0.902698
1
0.902698
game-dev
MEDIA
0.683937
game-dev
0.949822
1
0.949822
ericraio/vanilla-wow-addons
17,476
w/WIM/WIM.xml
<Ui xmlns="http://www.blizzard.com/wow/ui/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.blizzard.com/wow/ui/ ..\FrameXML\UI.xsd"> <Script file="localization.lua"/> <Script file="localization.cn.lua"/> <Script file="localization.de.lua"/> <Script file="localization.fr.lua"/> <Script file="localization.kr.lua"/> <Script file="localization.tw.lua"/> <Script file="WIM_ChangeLog.lua"/> <Script file="WIM.lua"/> <Script file="WIM_Hooks.lua"/> <Frame name="WIM_Core"> <Scripts> <OnLoad> this:RegisterEvent("VARIABLES_LOADED"); this:RegisterEvent("CHAT_MSG_AFK"); this:RegisterEvent("CHAT_MSG_DND"); this:RegisterEvent("CHAT_MSG_WHISPER"); this:RegisterEvent("CHAT_MSG_WHISPER_INFORM"); this:RegisterEvent("CHAT_MSG_SYSTEM"); this:RegisterEvent("TRADE_SKILL_SHOW"); this:RegisterEvent("CRAFT_SHOW"); this:RegisterEvent("GUILD_ROSTER_UPDATE"); this:RegisterEvent("FRIENDLIST_SHOW"); this:RegisterEvent("FRIENDLIST_UPDATE"); WIM_OnLoad(); WIM_SetUpHooks(); </OnLoad> <OnEvent> WIM_Incoming(event); </OnEvent> </Scripts> </Frame> <CheckButton name="WIM_ShortcutButtonTemplate" virtual="true"> <Size> <AbsDimension x="28" y="28"/> </Size> <Layers> <Layer level="BACKGROUND"> <Texture name="$parentIcon"/> </Layer> </Layers> <NormalTexture name="$parentNormalTexture" file="Interface\Buttons\UI-Quickslot2"> <Size> <AbsDimension x="48" y="48"/> </Size> <Anchors> <Anchor point="CENTER"> <Offset> <AbsDimension x="0" y="-1"/> </Offset> </Anchor> </Anchors> </NormalTexture> <PushedTexture file="Interface\Buttons\UI-Quickslot-Depress"/> <HighlightTexture alphaMode="ADD" file="Interface\Buttons\ButtonHilight-Square"/> <CheckedTexture alphaMode="ADD" file="Interface\Buttons\CheckButtonHilight"/> <Scripts> <OnLoad> this:RegisterForClicks("LeftButtonUp"); </OnLoad> <OnClick> this:SetChecked("0"); WIM_ShorcutButton_Clicked(); </OnClick> <OnEnter> if(WIM_Data.showToolTips == true) then GameTooltip:SetOwner(this, "ANCHOR_RIGHT"); GameTooltip:SetText(this.tooltip); end </OnEnter> <OnLeave> GameTooltip:Hide(); </OnLeave> </Scripts> </CheckButton> <Frame name="WIM_msgFrameTemplate" virtual="true" movable="true" enableMouse="true" toplevel="true" frameStrata="DIALOG" parent="UIParent" hidden="true" clampedToScreen="true"> <Size> <AbsDimension x="384" y="256"/> </Size> <Anchors> <Anchor point="TOPLEFT"> <Offset> <AbsDimension x="25" y="-125"/> </Offset> </Anchor> </Anchors> <Backdrop bgFile="Interface\AddOns\WIM\Images\WIM_UI_BG" edgeFile="Interface\AddOns\WIM\Images\WIM_UI" tile="true"> <BackgroundInsets> <AbsInset left="64" right="64" top="64" bottom="64" /> </BackgroundInsets> <TileSize> <AbsValue val="8" /> </TileSize> <EdgeSize> <AbsValue val="64" /> </EdgeSize> </Backdrop> <Layers> <Layer level="BACKGROUND"> <Texture name="$parentClassIcon" file="Interface\AddOns\WIM\Images\classBLANK"> <Size> <AbsDimension x="64" y="64"/> </Size> <Anchors> <Anchor point="TOPLEFT" relativePoint="TOPLEFT"> <Offset> <AbsDimension x="-10" y="12"/> </Offset> </Anchor> </Anchors> </Texture> </Layer> <Layer level="OVERLAY"> <FontString name="$parentFrom" inherits="GameFontNormalLarge" text="abcdefghijklmnopqrstuvwxyz"> <Anchors> <Anchor point="TOPLEFT"> <Offset> <AbsDimension x="50" y="-6"/> </Offset> </Anchor> </Anchors> </FontString> <FontString name="$parentCharacterDetails" inherits="GameFontNormal" text=""> <Anchors> <Anchor point="TOP"> <Offset> <AbsDimension x="0" y="-30"/> </Offset> </Anchor> </Anchors> </FontString> </Layer> </Layers> <Frames> <Button name="$parentExitButton"> <Size> <AbsDimension x="32" y="32"/> </Size> <Anchors> <Anchor point="TOPRIGHT"> <Offset> <AbsDimension x="4" y="1"/> </Offset> </Anchor> </Anchors> <NormalTexture file="Interface\Buttons\UI-Panel-MinimizeButton-Up"/> <PushedTexture file="Interface\Buttons\UI-Panel-MinimizeButton-Down"/> <HighlightTexture alphaMode="ADD" file="Interface\Buttons\UI-Panel-MinimizeButton-Highlight"/> <Scripts> <OnLoad> this:RegisterForClicks("LeftButtonUp", "RightButtonUp"); </OnLoad> <OnClick> if(IsShiftKeyDown()) then WIM_CloseConvo(this:GetParent().theUser); else this:GetParent():Hide(); end </OnClick> <OnEnter> if(WIM_Data.showToolTips == true) then GameTooltip:SetOwner(this, "ANCHOR_LEFT"); GameTooltip:SetText("Shift &amp; Left-Click to end conversation."); GameTooltip:SetPoint("BOTTOMRIGHT", this, "TOPRIGHT", 0, 0); end </OnEnter> <OnLeave> GameTooltip:Hide(); </OnLeave> </Scripts> </Button> <Button name="$parentHistoryButton" hidden="true"> <Size> <AbsDimension x="19" y="19"/> </Size> <Anchors> <Anchor point="TOPRIGHT" relativeTo="$parentExitButton" relativePoint="TOPLEFT"> <Offset> <AbsDimension x="2" y="-6"/> </Offset> </Anchor> </Anchors> <NormalTexture file="Interface\Buttons\UI-GuildButton-PublicNote-Up"/> <Scripts> <OnLoad> this:RegisterForClicks("LeftButtonUp", "RightButtonUp"); </OnLoad> <OnClick> WIM_HistoryView_Name_Selected = this:GetParent().theUser; WIM_HistoryView_Filter_Selected = ""; if(WIM_HistoryFrame:IsVisible()) then WIM_HistoryViewNameScrollBar_Update(); WIM_HistoryViewFiltersScrollBar_Update(); else WIM_HistoryFrame:Show(); end </OnClick> <OnEnter> if(WIM_Data.showToolTips == true) then GameTooltip:SetOwner(this, "ANCHOR_LEFT"); GameTooltip:SetText("Click to view message history."); GameTooltip:SetPoint("BOTTOMRIGHT", this, "TOPRIGHT", 0, 0); end </OnEnter> <OnLeave> GameTooltip:Hide(); </OnLeave> </Scripts> </Button> <Button name="$parentScrollUp"> <Size> <AbsDimension x="32" y="32"/> </Size> <Anchors> <Anchor point="TOPRIGHT"> <Offset> <AbsDimension x="-4" y="-39"/> </Offset> </Anchor> </Anchors> <NormalTexture file="Interface\Buttons\UI-ScrollBar-ScrollUpButton-Up"/> <PushedTexture file="Interface\Buttons\UI-ScrollBar-ScrollUpButton-Down"/> <DisabledTexture file="Interface\Buttons\UI-ScrollBar-ScrollUpButton-Disabled"/> <HighlightTexture alphaMode="ADD" file="Interface\Buttons\UI-ScrollBar-ScrollUpButton-Highlight"/> <Scripts> <OnLoad> this:RegisterForClicks("LeftButtonUp", "RightButtonUp"); </OnLoad> <OnClick> if( IsShiftKeyDown() ) then getglobal(this:GetParent():GetName().."ScrollingMessageFrame"):PageUp(); else getglobal(this:GetParent():GetName().."ScrollingMessageFrame"):ScrollUp(); end WIM_UpdateScrollBars(getglobal(this:GetParent():GetName().."ScrollingMessageFrame")); </OnClick> </Scripts> </Button> <Button name="$parentScrollDown"> <Size> <AbsDimension x="32" y="32"/> </Size> <Anchors> <Anchor point="BOTTOMRIGHT"> <Offset> <AbsDimension x="-4" y="24"/> </Offset> </Anchor> </Anchors> <NormalTexture file="Interface\Buttons\UI-ScrollBar-ScrollDownButton-Up"/> <PushedTexture file="Interface\Buttons\UI-ScrollBar-ScrollDownButton-Down"/> <DisabledTexture file="Interface\Buttons\UI-ScrollBar-ScrollDownButton-Disabled"/> <HighlightTexture alphaMode="ADD" file="Interface\Buttons\UI-ScrollBar-ScrollDownButton-Highlight"/> <Scripts> <OnLoad> this:RegisterForClicks("LeftButtonUp", "RightButtonUp"); </OnLoad> <OnClick> if( IsShiftKeyDown() ) then getglobal(this:GetParent():GetName().."ScrollingMessageFrame"):PageDown(); else getglobal(this:GetParent():GetName().."ScrollingMessageFrame"):ScrollDown(); end WIM_UpdateScrollBars(getglobal(this:GetParent():GetName().."ScrollingMessageFrame")); </OnClick> </Scripts> </Button> <ScrollingMessageFrame name="$parentScrollingMessageFrame" enableMouse="true" fade="false" maxLines="128" movable="true"> <Anchors> <Anchor point="TOPLEFT"> <Offset> <AbsDimension x="24" y="-46" /> </Offset> </Anchor> <Anchor point="BOTTOMRIGHT"> <Offset> <AbsDimension x="-32" y="39" /> </Offset> </Anchor> </Anchors> <FontString font="Fonts\FRIZQT__.TTF" justifyH="LEFT"> <FontHeight> <AbsValue val="12" /> </FontHeight> <Color r="1" g="0.8196079" b="0" /> <Shadow> <Color r="0" g="0" b="0" /> <Offset> <AbsDimension x="1" y="-1" /> </Offset> </Shadow> </FontString> <TextInsets> <AbsInset left="0" right="10" top="0" bottom="0" /> </TextInsets> <Scripts> <OnMouseWheel> if(arg1 > 0) then if( IsShiftKeyDown() ) then this:PageUp(); else this:ScrollUp(); end else if( IsShiftKeyDown() ) then this:PageDown(); else this:ScrollDown(); end end </OnMouseWheel> <OnHyperlinkClick> ChatFrame_OnHyperlinkShow(arg1, arg2, arg3); </OnHyperlinkClick> <OnMessageScrollChanged> WIM_UpdateScrollBars(this); </OnMessageScrollChanged> <OnMouseDown> this:GetParent():StartMoving(); this:GetParent().isMoving = true; this:GetParent().prevLeft = this:GetParent():GetLeft(); this:GetParent().prevTop = this:GetParent():GetTop(); </OnMouseDown> <OnMouseUp> this:GetParent():StopMovingOrSizing(); this:GetParent().isMoving = false; if(this:GetParent().prevLeft == this:GetParent():GetLeft() and this:GetParent().prevTop == this:GetParent():GetTop()) then --[ Frame was clicked not dragged if(WIM_EditBoxInFocus == nil) then getglobal(this:GetParent():GetName().."MsgBox"):SetFocus(); else if(WIM_EditBoxInFocus:GetName() == this:GetParent():GetName().."MsgBox") then getglobal(this:GetParent():GetName().."MsgBox"):Hide(); getglobal(this:GetParent():GetName().."MsgBox"):Show(); else getglobal(this:GetParent():GetName().."MsgBox"):SetFocus(); end end end </OnMouseUp> </Scripts> </ScrollingMessageFrame> <EditBox name="$parentMsgBox" enableMouse="true" ignoreArrows="true" frameStrata="DIALOG" toplevel="true" historyLines="32" letters="255" autoFocus="false"> <Anchors> <Anchor point="TOPLEFT" relativeTo="$parentScrollingMessageFrame" relativePoint="BOTTOMLEFT"> <Offset> <AbsDimension x="-2" y="-5" /> </Offset> </Anchor> <Anchor point="BOTTOMRIGHT"> <Offset> <AbsDimension x="-10" y="0" /> </Offset> </Anchor> </Anchors> <FontString font="Fonts\ARIALN.TTF"> <FontHeight> <AbsValue val="14" /> </FontHeight> <Color r="1" g="1" b="1" /> <Shadow> <Color r="0" g="0" b="0" /> <Offset> <AbsDimension x="1" y="-1" /> </Offset> </Shadow> </FontString> <Scripts> <OnEnterPressed> local _, tParent = this:GetParent(); SendChatMessage(this:GetText(), "WHISPER", nil, this:GetParent().theUser); this:AddHistoryLine(this:GetText()); this:SetText(""); if(not WIM_Data.keepFocus) then this:Hide(); this:Show(); end </OnEnterPressed> <OnEscapePressed> this:SetText(""); this:Hide(); this:Show(); </OnEscapePressed> <OnTabPressed> --cycle through windows </OnTabPressed> <OnEditFocusGained> WIM_EditBoxInFocus = this; </OnEditFocusGained> <OnEditFocusLost> WIM_EditBoxInFocus = nil; </OnEditFocusLost> </Scripts> </EditBox> <Frame name="$parentShortcutFrame"> <Size> <AbsDimension x="100" y="100" /> </Size> <Anchors> <Anchor point="TOPLEFT" relativeTo="$parentScrollUp" relativePoint="BOTTOMLEFT"> <Offset> <AbsDimension x="8" y="0" /> </Offset> </Anchor> </Anchors> <Frames> <CheckButton name="$parentButton1" inherits="WIM_ShortcutButtonTemplate"> <Anchors> <Anchor point="TOPLEFT"> <Offset> <AbsDimension x="0" y="0"/> </Offset> </Anchor> </Anchors> </CheckButton> <CheckButton name="$parentButton2" inherits="WIM_ShortcutButtonTemplate"> <Anchors> <Anchor point="TOPLEFT" relativeTo="$parentButton1" relativePoint="BOTTOMLEFT"> <Offset> <AbsDimension x="0" y="-2"/> </Offset> </Anchor> </Anchors> </CheckButton> <CheckButton name="$parentButton3" inherits="WIM_ShortcutButtonTemplate"> <Anchors> <Anchor point="TOPLEFT" relativeTo="$parentButton2" relativePoint="BOTTOMLEFT"> <Offset> <AbsDimension x="0" y="-2"/> </Offset> </Anchor> </Anchors> </CheckButton> <CheckButton name="$parentButton4" inherits="WIM_ShortcutButtonTemplate"> <Anchors> <Anchor point="TOPLEFT" relativeTo="$parentButton3" relativePoint="BOTTOMLEFT"> <Offset> <AbsDimension x="0" y="-2"/> </Offset> </Anchor> </Anchors> </CheckButton> <CheckButton name="$parentButton5" inherits="WIM_ShortcutButtonTemplate"> <Anchors> <Anchor point="TOPLEFT" relativeTo="$parentButton4" relativePoint="BOTTOMLEFT"> <Offset> <AbsDimension x="0" y="-2"/> </Offset> </Anchor> </Anchors> </CheckButton> </Frames> </Frame> <Frame name="$parentIgnoreConfirm" hidden="true" frameStrata="DIALOG"> <Anchors> <Anchor point="TOPLEFT" relativeTo="$parentScrollingMessageFrame" relativePoint="TOPLEFT"> <Offset> <AbsDimension x="-8" y="2" /> </Offset> </Anchor> <Anchor point="BOTTOMRIGHT" relativeTo="$parentScrollingMessageFrame" relativePoint="BOTTOMRIGHT"> <Offset> <AbsDimension x="-2" y="-10" /> </Offset> </Anchor> </Anchors> <Layers> <Layer level="OVERLAY"> <FontString name="$parentText" inherits="GameFontNormalLarge" text="Are you sure you want to ignore this user?"> <Anchors> <Anchor point="CENTER"> <Offset> <AbsDimension x="0" y="30"/> </Offset> </Anchor> </Anchors> </FontString> </Layer> </Layers> <Backdrop bgFile="Interface\Buttons\UI-SliderBar-Background" edgeFile="Interface\Buttons\UI-SliderBar-Border" tile="true"> <BackgroundInsets> <AbsInset left="3" right="3" top="6" bottom="6" /> </BackgroundInsets> <TileSize> <AbsValue val="8" /> </TileSize> <EdgeSize> <AbsValue val="8" /> </EdgeSize> </Backdrop> <Frames> <Button name="$parentYes" inherits="UIPanelButtonTemplate" text="Yes"> <Size> <AbsDimension x="50" y="25"/> </Size> <Anchors> <Anchor point="CENTER"> <Offset> <AbsDimension x="-30" y="-10"/> </Offset> </Anchor> </Anchors> <Scripts> <OnClick> PlaySound("igMainMenuClose"); AddIgnore(this:GetParent():GetParent().theUser); this:GetParent():Hide(); </OnClick> </Scripts> </Button> <Button name="$parentNo" inherits="UIPanelButtonTemplate" text="No"> <Size> <AbsDimension x="50" y="25"/> </Size> <Anchors> <Anchor point="CENTER"> <Offset> <AbsDimension x="30" y="-10"/> </Offset> </Anchor> </Anchors> <Scripts> <OnClick> PlaySound("igMainMenuClose"); this:GetParent():Hide(); </OnClick> </Scripts> </Button> </Frames> <Scripts> <OnShow> PlaySound("igMainMenuOpen"); getglobal(this:GetName().."Text"):SetText("Are you sure you want to\nignore this user?"); getglobal(this:GetParent():GetName().."ScrollingMessageFrame"):SetFrameStrata("LOW"); </OnShow> <OnHide> getglobal(this:GetParent():GetName().."ScrollingMessageFrame"):SetFrameStrata("DIALOG"); </OnHide> </Scripts> </Frame> </Frames> <Scripts> <OnLoad> tinsert(UISpecialFrames,this:GetName()); this:RegisterForDrag("LeftButton"); </OnLoad> <OnDragStart> this:StartMoving(); this.isMoving = true; </OnDragStart> <OnDragStop> this:StopMovingOrSizing(); this.isMoving = false; </OnDragStop> <OnShow> local user = this.theUser; WIM_Windows[user].newMSG = false; WIM_Windows[user].is_visible = true; if(WIM_Data.autoFocus == true) then getglobal(this:GetName().."MsgBox"):SetFocus(); end WIM_LoadShortcutFrame(); </OnShow> <OnHide> getglobal(this:GetName().."IgnoreConfirm"):Hide(); local user = this.theUser; WIM_Windows[user].is_visible = false; WIM_Windows[user].newMSG = false; </OnHide> </Scripts> </Frame> </Ui>
0
0.806291
1
0.806291
game-dev
MEDIA
0.618502
game-dev
0.866802
1
0.866802
Team-Immersive-Intelligence/ImmersiveIntelligence
6,028
src/main/java/pl/pabilo8/immersiveintelligence/common/compat/jei/recipe_handlers/SawmillRecipeCategory.java
package pl.pabilo8.immersiveintelligence.common.compat.jei.recipe_handlers; import blusunrize.immersiveengineering.client.ClientUtils; import blusunrize.immersiveengineering.common.util.Utils; import mezz.jei.api.IGuiHelper; import mezz.jei.api.gui.IGuiItemStackGroup; import mezz.jei.api.gui.IRecipeLayout; import mezz.jei.api.ingredients.IIngredients; import mezz.jei.api.ingredients.VanillaTypes; import mezz.jei.api.recipe.IRecipeWrapper; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.block.model.ItemCameraTransforms.TransformType; import net.minecraft.item.ItemStack; import net.minecraft.util.Tuple; import org.lwjgl.opengl.GL11; import pl.pabilo8.immersiveintelligence.ImmersiveIntelligence; import pl.pabilo8.immersiveintelligence.api.crafting.SawmillRecipe; import pl.pabilo8.immersiveintelligence.common.IIConfigHandler.IIConfig.Machines.Sawmill; import pl.pabilo8.immersiveintelligence.common.IIContent; import pl.pabilo8.immersiveintelligence.common.block.multiblock.wooden_multiblock.BlockIIWoodenMultiblock.WoodenMultiblocks; import pl.pabilo8.immersiveintelligence.common.compat.jei.IIMultiblockRecipeWrapper; import pl.pabilo8.immersiveintelligence.common.compat.jei.IIRecipeCategory; import pl.pabilo8.immersiveintelligence.common.util.IIReference; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; /** * @author Pabilo8 * @author Avalon * @since 29.09.2021 * @since 29-11-2024 */ public class SawmillRecipeCategory extends IIRecipeCategory<SawmillRecipe, SawmillRecipeCategory.SawmillRecipeWrapper> { static ItemStack machineStack; public SawmillRecipeCategory(IGuiHelper helper) { super("sawmill", "tile."+ImmersiveIntelligence.MODID+".wooden_multiblock.sawmill.name", helper.createBlankDrawable(156, 68), SawmillRecipe.class, new ItemStack(IIContent.blockWoodenMultiblock, 1, WoodenMultiblocks.SAWMILL.getMeta()) ); machineStack = new ItemStack(IIContent.blockWoodenMultiblock, 1, WoodenMultiblocks.SAWMILL.getMeta()); } @Override public void setRecipe(IRecipeLayout recipeLayout, SawmillRecipeWrapper recipeWrapper, IIngredients ingredients) { IGuiItemStackGroup guiItemStacks = recipeLayout.getItemStacks(); guiItemStacks.init(0, true, -1, 20-8); guiItemStacks.init(1, true, 114, 20-8); guiItemStacks.init(2, true, 134, 20-8); guiItemStacks.init(3, true, 64, 20-12); //in, out guiItemStacks.set(0, ingredients.getInputs(VanillaTypes.ITEM).get(0)); guiItemStacks.set(1, ingredients.getOutputs(VanillaTypes.ITEM).get(0)); //sawdust if(ingredients.getOutputs(VanillaTypes.ITEM).size() > 1) guiItemStacks.set(2, ingredients.getOutputs(VanillaTypes.ITEM).get(1)); //saw guiItemStacks.set(3, ingredients.getInputs(VanillaTypes.ITEM).get(1)); } @Override public IRecipeWrapper getRecipeWrapper(SawmillRecipe recipe) { return new SawmillRecipeWrapper(recipe); } public static class SawmillRecipeWrapper extends IIMultiblockRecipeWrapper { protected int hardness, torque; public SawmillRecipeWrapper(SawmillRecipe recipe) { super(recipe); hardness = recipe.getHardness(); torque = recipe.getTorque(); } @Override public void getIngredients(IIngredients ingredients) { //add recipe input ArrayList<List<ItemStack>> items = new ArrayList<>(Arrays.asList(recipeInputs.clone())); //add saws items.add( SawmillRecipe.toolMap.entrySet().stream() .map(e -> new Tuple<>(e.getValue(), e.getValue().getToolPresentationStack(e.getKey()))) .filter(e -> e.getFirst().getHardness(e.getSecond()) >= hardness) .map(Tuple::getSecond) .collect(Collectors.toList()) ); super.getIngredients(ingredients); if(!inputs.isEmpty()) ingredients.setInputLists(VanillaTypes.ITEM, items); } @Override public void drawInfo(Minecraft minecraft, int recipeWidth, int recipeHeight, int mouseX, int mouseY) { // Render the multiblock model GlStateManager.pushMatrix(); GlStateManager.enableDepth(); GlStateManager.translate(85F, 13f, 150.5F); GlStateManager.rotate(50, 0, 1, 0); GlStateManager.rotate(8.5f, 1, 0, 0); GlStateManager.rotate(-12.5f, 0, 0, 1); GlStateManager.scale(65, -65, 65); minecraft.getRenderItem().renderItem(machineStack, TransformType.GUI); GlStateManager.popMatrix(); // Render slots for inputs and outputs ClientUtils.drawSlot(0, 12, 16, 16); // Input ClientUtils.drawSlot(115, 12, 16, 16); // Main output ClientUtils.drawSlot(135, 12, 16, 16); // Secondary output // Render energy and time drawEnergyTimeInfo(minecraft, 0, recipeHeight-26); // Clear depth buffer and render sawblade on top GlStateManager.pushMatrix(); GlStateManager.clear(GL11.GL_DEPTH_BUFFER_BIT); // Clear the depth buffer ClientUtils.drawSlot(64, 8, 16, 16); // Render sawblade slot GlStateManager.popMatrix(); } @Override public void drawEnergyTimeInfo(Minecraft minecraft, int x, int y) { minecraft.getTextureManager().bindTexture(IIRecipeCategory.texture); //time icon ClientUtils.drawTexturedRect(x, y-3, 14, 14, 51/256f, (51+14)/256f, 15/256f, (15+14)/256f); //speed icon ClientUtils.drawTexturedRect(x+64, y-3, 14, 14, 79/256f, (79+14)/256f, 15/256f, (15+14)/256f);//energy icon //torque icon ClientUtils.drawTexturedRect(x+64, y-3+16, 14, 14, 93/256f, (93+14)/256f, 15/256f, (15+14)/256f); //shift ? ticks : seconds String time = GuiScreen.isShiftKeyDown()? this.time+" t": Utils.formatDouble(this.time*0.05, "0.##")+" s"; minecraft.fontRenderer.drawString(time, x+16, y, IIReference.COLOR_H2.getPackedRGB()); minecraft.fontRenderer.drawString(Sawmill.rpmMin+"-"+Sawmill.rpmBreakingMax+" RPM", x+64+16, y, IIReference.COLOR_H2.getPackedRGB()); minecraft.fontRenderer.drawString(torque+" Nm", x+64+16, y+16, IIReference.COLOR_H2.getPackedRGB()); } } }
0
0.900255
1
0.900255
game-dev
MEDIA
0.97169
game-dev
0.980948
1
0.980948
Creators-of-Create/Create
6,696
src/main/java/com/simibubi/create/content/equipment/armor/BacktankUtil.java
package com.simibubi.create.content.equipment.armor; import java.util.ArrayList; import java.util.List; import java.util.function.Function; import com.simibubi.create.AllEnchantments; import com.simibubi.create.AllSoundEvents; import com.simibubi.create.AllTags; import com.simibubi.create.foundation.utility.CreateLang; import com.simibubi.create.infrastructure.config.AllConfigs; import net.minecraft.ChatFormatting; import net.minecraft.client.Minecraft; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.CommonComponents; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.MutableComponent; import net.minecraft.network.protocol.game.ClientboundSetSubtitleTextPacket; import net.minecraft.network.protocol.game.ClientboundSetTitleTextPacket; import net.minecraft.network.protocol.game.ClientboundSetTitlesAnimationPacket; import net.minecraft.server.level.ServerPlayer; import net.minecraft.util.Mth; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.fml.DistExecutor; public class BacktankUtil { private static final List<Function<LivingEntity, List<ItemStack>>> BACKTANK_SUPPLIERS = new ArrayList<>(); static { addBacktankSupplier(entity -> { List<ItemStack> stacks = new ArrayList<>(); for (ItemStack itemStack : entity.getArmorSlots()) if (AllTags.AllItemTags.PRESSURIZED_AIR_SOURCES.matches(itemStack)) stacks.add(itemStack); return stacks; }); } public static List<ItemStack> getAllWithAir(LivingEntity entity) { List<ItemStack> all = new ArrayList<>(); for (Function<LivingEntity, List<ItemStack>> supplier : BACKTANK_SUPPLIERS) { List<ItemStack> result = supplier.apply(entity); for (ItemStack stack : result) if (hasAirRemaining(stack)) all.add(stack); } // Sort with ascending order (we want to prioritize the most empty so things actually run out) all.sort((a, b) -> Float.compare(getAir(a), getAir(b))); return all; } public static boolean hasAirRemaining(ItemStack backtank) { return getAir(backtank) > 0; } public static float getAir(ItemStack backtank) { CompoundTag tag = backtank.getOrCreateTag(); return Math.min(tag.getFloat("Air"), maxAir(backtank)); } public static void consumeAir(LivingEntity entity, ItemStack backtank, float i) { CompoundTag tag = backtank.getOrCreateTag(); int maxAir = maxAir(backtank); float air = getAir(backtank); float newAir = Math.max(air - i, 0); tag.putFloat("Air", Math.min(newAir, maxAir)); backtank.setTag(tag); if (!(entity instanceof ServerPlayer player)) return; sendWarning(player, air, newAir, maxAir / 10f); sendWarning(player, air, newAir, 1); } private static void sendWarning(ServerPlayer player, float air, float newAir, float threshold) { if (newAir > threshold) return; if (air <= threshold) return; boolean depleted = threshold == 1; MutableComponent component = CreateLang.translateDirect(depleted ? "backtank.depleted" : "backtank.low"); AllSoundEvents.DENY.play(player.level(), null, player.blockPosition(), 1, 1.25f); AllSoundEvents.STEAM.play(player.level(), null, player.blockPosition(), .5f, .5f); player.connection.send(new ClientboundSetTitlesAnimationPacket(10, 40, 10)); player.connection.send(new ClientboundSetSubtitleTextPacket( Component.literal("\u26A0 ").withStyle(depleted ? ChatFormatting.RED : ChatFormatting.GOLD) .append(component.withStyle(ChatFormatting.GRAY)))); player.connection.send(new ClientboundSetTitleTextPacket(CommonComponents.EMPTY)); } public static int maxAir(ItemStack backtank) { return maxAir(backtank.getEnchantmentLevel(AllEnchantments.CAPACITY.get())); } public static int maxAir(int enchantLevel) { return AllConfigs.server().equipment.airInBacktank.get() + AllConfigs.server().equipment.enchantedBacktankCapacity.get() * enchantLevel; } public static int maxAirWithoutEnchants() { return AllConfigs.server().equipment.airInBacktank.get(); } public static boolean canAbsorbDamage(LivingEntity entity, int usesPerTank) { if (usesPerTank == 0) return true; if (entity instanceof Player && ((Player) entity).isCreative()) return true; List<ItemStack> backtanks = getAllWithAir(entity); if (backtanks.isEmpty()) return false; float cost = ((float) maxAirWithoutEnchants()) / usesPerTank; consumeAir(entity, backtanks.get(0), cost); return true; } // For Air-using tools public static boolean isBarVisible(ItemStack stack, int usesPerTank) { if (usesPerTank == 0) return false; Player player = DistExecutor.unsafeCallWhenOn(Dist.CLIENT, () -> () -> Minecraft.getInstance().player); if (player == null) return false; List<ItemStack> backtanks = getAllWithAir(player); if (backtanks.isEmpty()) return stack.isDamaged(); return true; } public static int getBarWidth(ItemStack stack, int usesPerTank) { if (usesPerTank == 0) return 13; Player player = DistExecutor.unsafeCallWhenOn(Dist.CLIENT, () -> () -> Minecraft.getInstance().player); if (player == null) return 13; List<ItemStack> backtanks = getAllWithAir(player); if (backtanks.isEmpty()) return Math.round(13.0F - (float) stack.getDamageValue() / stack.getMaxDamage() * 13.0F); if (backtanks.size() == 1) return backtanks.get(0) .getItem() .getBarWidth(backtanks.get(0)); // If there is more than one backtank, average the bar widths. int sumBarWidth = backtanks.stream() .map(backtank -> backtank.getItem() .getBarWidth(backtank)) .reduce(0, Integer::sum); return Math.round((float) sumBarWidth / backtanks.size()); } public static int getBarColor(ItemStack stack, int usesPerTank) { if (usesPerTank == 0) return 0; Player player = DistExecutor.unsafeCallWhenOn(Dist.CLIENT, () -> () -> Minecraft.getInstance().player); if (player == null) return 0; List<ItemStack> backtanks = getAllWithAir(player); // Fallback colour if (backtanks.isEmpty()) return Mth.hsvToRgb(Math.max(0.0F, 1.0F - (float) stack.getDamageValue() / stack.getMaxDamage()) / 3.0F, 1.0F, 1.0F); // Just return the "first" backtank for the bar color since that's the one we are consuming from return backtanks.get(0) .getItem() .getBarColor(backtanks.get(0)); } /** * Use this method to add custom entry points to the backtank item stack supplier, e.g. getting them from custom * slots or items. */ public static void addBacktankSupplier(Function<LivingEntity, List<ItemStack>> supplier) { BACKTANK_SUPPLIERS.add(supplier); } }
0
0.761645
1
0.761645
game-dev
MEDIA
0.998604
game-dev
0.930026
1
0.930026
mister91jiao/BundleMaster
10,826
Editor/BundleMasterEditor/BundleMasterInterface/BundleMasterWindow.cs
using System.Diagnostics.CodeAnalysis; using System.IO; using UnityEditor; using UnityEngine; namespace BM { [SuppressMessage("ReSharper", "PossibleLossOfFraction")] public partial class BundleMasterWindow : EditorWindow { private static BundleMasterWindow _instance = null; /// <summary> /// 自动刷新配置界面 /// </summary> private static bool _autoFlush = true; /// <summary> /// 需要刷新 /// </summary> private bool needFlush = false; /// <summary> /// 运行时配置文件 /// </summary> private static BundleMasterRuntimeConfig _bundleMasterRuntimeConfig = null; private static bool _runtimeConfigLoad = false; private static int _w = 960; private static int _h = 540; /// <summary> /// 运行时配置文件的路径 /// </summary> public static string RuntimeConfigPath = "Assets/Resources/BMConfig.asset"; /// <summary> /// 分包文件资源索引配置 /// </summary> public static string AssetLoadTablePath = "Assets/Editor/BundleMasterEditor/BuildSettings/AssetLoadTable.asset"; /// <summary> /// 分包配置信息 /// </summary> public static string AssetsLoadSettingPath = "Assets/Editor/BundleMasterEditor/BuildSettings/AssetsLoadSetting"; /// <summary> /// 原生资源包配置信息 /// </summary> public static string AssetsOriginSettingPath = "Assets/Editor/BundleMasterEditor/BuildSettings/AssetsOriginSetting"; private static AssetLoadTable _assetLoadTable = null; /// <summary> /// 选中查看的分包信息 /// </summary> private static AssetsSetting _selectAssetsSetting = null; /// <summary> /// 是否查看子页面 /// </summary> private static bool _viewSub = false; [MenuItem("Tools/BuildAsset/打开配置界面")] public static void Init() { Open(true); } Vector2 scrollScenePos = Vector2.zero; Vector2 scrollPos = Vector2.zero; Vector2 scrollBundleScenePos = Vector2.zero; Vector2 scrollPathPos = Vector2.zero; private static void Open(bool focus) { if (_instance != null) { return; } _viewSub = false; _instance = (BundleMasterWindow)EditorWindow.GetWindow(typeof(BundleMasterWindow), true, "BundleMasterEditor", focus); //_instance.position = new Rect(_w / 2, _h / 2, _w, _h); _instance.maxSize = new Vector2(_w, _h); _instance.minSize = new Vector2(_w, _h); //加载配置文件 _bundleMasterRuntimeConfig = AssetDatabase.LoadAssetAtPath<BundleMasterRuntimeConfig>(RuntimeConfigPath); _runtimeConfigLoad = false; if (_bundleMasterRuntimeConfig != null) { _runtimeConfigLoad = true; } } public void OnGUI() { Open(false); if (!_runtimeConfigLoad) { GUILayout.BeginArea(new Rect(_w / 4, _h / 8, _w / 2, _h / 4)); if (GUILayout.Button("创建运行时配置文件", GUILayout.Width(_w / 2), GUILayout.Height(_h / 4), GUILayout.ExpandWidth(false), GUILayout.ExpandHeight(false))) { _bundleMasterRuntimeConfig = ScriptableObject.CreateInstance<BundleMasterRuntimeConfig>(); _bundleMasterRuntimeConfig.AssetLoadMode = AssetLoadMode.Develop; _bundleMasterRuntimeConfig.MaxDownLoadCount = 8; _bundleMasterRuntimeConfig.ReDownLoadCount = 3; if (!Directory.Exists(Path.Combine(Application.dataPath, "Resources"))) { Directory.CreateDirectory(Path.Combine(Application.dataPath, "Resources")); } AssetDatabase.CreateAsset(_bundleMasterRuntimeConfig, RuntimeConfigPath); AssetDatabase.Refresh(); _runtimeConfigLoad = true; } GUILayout.EndArea(); return; } GUILayout.BeginHorizontal(); GUILayout.Label("当前资源加载模式: \t" + _bundleMasterRuntimeConfig.AssetLoadMode, GUILayout.Width(_w / 4), GUILayout.Height(_h / 8), GUILayout.ExpandWidth(false)); if (GUILayout.Button("开发模式", GUILayout.Width(_w / 6), GUILayout.Height(_h / 8), GUILayout.ExpandWidth(true))) { _bundleMasterRuntimeConfig.AssetLoadMode = AssetLoadMode.Develop; DevelopSceneChange.CheckSceneChange(_bundleMasterRuntimeConfig.AssetLoadMode); needFlush = true; } if (GUILayout.Button("本地模式", GUILayout.Width(_w / 6), GUILayout.Height(_h / 8), GUILayout.ExpandWidth(true))) { _bundleMasterRuntimeConfig.AssetLoadMode = AssetLoadMode.Local; DevelopSceneChange.CheckSceneChange(_bundleMasterRuntimeConfig.AssetLoadMode); needFlush = true; } if (GUILayout.Button("构建模式", GUILayout.Width(_w / 6), GUILayout.Height(_h / 8), GUILayout.ExpandWidth(true))) { _bundleMasterRuntimeConfig.AssetLoadMode = AssetLoadMode.Build; DevelopSceneChange.CheckSceneChange(_bundleMasterRuntimeConfig.AssetLoadMode); needFlush = true; } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(GUILayout.ExpandHeight(false)); GUILayout.Label("最大同时下载资源数: ", GUILayout.Width(_w / 8), GUILayout.ExpandWidth(false)); int maxDownLoadCount = _bundleMasterRuntimeConfig.MaxDownLoadCount; maxDownLoadCount = EditorGUILayout.IntField(maxDownLoadCount, GUILayout.Width(_w / 16), GUILayout.ExpandWidth(false)); if (_bundleMasterRuntimeConfig.MaxDownLoadCount != maxDownLoadCount) { _bundleMasterRuntimeConfig.MaxDownLoadCount = maxDownLoadCount; needFlush = true; } GUILayout.Label("下载失败重试数: ", GUILayout.Width(_w / 10), GUILayout.ExpandWidth(false)); int reDownLoadCount = _bundleMasterRuntimeConfig.ReDownLoadCount; reDownLoadCount = EditorGUILayout.IntField(reDownLoadCount, GUILayout.Width(_w / 16), GUILayout.ExpandWidth(false)); if (_bundleMasterRuntimeConfig.ReDownLoadCount != reDownLoadCount) { _bundleMasterRuntimeConfig.ReDownLoadCount = reDownLoadCount; needFlush = true; } _autoFlush = GUILayout.Toggle(_autoFlush, "是否自动应用更新配置界面数据"); if (!_autoFlush) { if (GUILayout.Button("应用更新")) { needFlush = false; Flush(); } } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.Label("--- <构建AssetBundle配置> ----------------------------------------------------------------------------------------------------------------------------------------------------------------", GUILayout.ExpandWidth(false)); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.Label("分包配置总索引文件: ", GUILayout.Width(_w / 8), GUILayout.ExpandWidth(false)); _assetLoadTable = (AssetLoadTable)EditorGUILayout.ObjectField(_assetLoadTable, typeof(AssetLoadTable), true, GUILayout.Width(_w / 3), GUILayout.ExpandWidth(false)); bool noTable = _assetLoadTable == null; if (GUILayout.Button("查找或创建分包配置索引文件", GUILayout.Width(_w / 5.5f), GUILayout.ExpandWidth(true))) { _assetLoadTable = AssetDatabase.LoadAssetAtPath<AssetLoadTable>(AssetLoadTablePath); if (_assetLoadTable == null) { _assetLoadTable = ScriptableObject.CreateInstance<AssetLoadTable>(); AssetDatabase.CreateAsset(_assetLoadTable, BundleMasterWindow.AssetLoadTablePath); needFlush = true; } } EditorGUI.BeginDisabledGroup(noTable); GUI.color = new Color(0.654902F, 0.9921569F, 0.2784314F); if (GUILayout.Button("添加一个分包配置", GUILayout.Width(_w / 6), GUILayout.ExpandWidth(true))) { int index = 0; while (true) { AssetsLoadSetting assetLoadTable = AssetDatabase.LoadAssetAtPath<AssetsLoadSetting>(AssetsLoadSettingPath + "_" + index + ".asset"); if (assetLoadTable == null) { AssetDatabase.CreateAsset(ScriptableObject.CreateInstance<AssetsLoadSetting>(), AssetsLoadSettingPath + "_" + index + ".asset"); break; } else { index++; } } needFlush = true; } GUI.color = Color.white; GUI.color = new Color(0.9921569F, 0.7960784F, 0.509804F); if (GUILayout.Button("添加一个原生资源包配置", GUILayout.Width(_w / 6), GUILayout.ExpandWidth(true))) { int index = 0; while (true) { AssetsOriginSetting assetsOriginSetting = AssetDatabase.LoadAssetAtPath<AssetsOriginSetting>(AssetsOriginSettingPath + "_" + index + ".asset"); if (assetsOriginSetting == null) { AssetDatabase.CreateAsset(ScriptableObject.CreateInstance<AssetsOriginSetting>(), AssetsOriginSettingPath + "_" + index + ".asset"); break; } else { index++; } } needFlush = true; } GUI.color = Color.white; GUILayout.EndHorizontal(); if (!_viewSub) { AssetsLoadMainRender(noTable); } else { if (_selectAssetsSetting is AssetsLoadSetting) { AssetsLoadSettingRender(); } else { OriginLoadSettingRender(); } } if (needFlush && _autoFlush) { needFlush = false; Flush(); } } public void OnDestroy() { _instance = null; } } }
0
0.912793
1
0.912793
game-dev
MEDIA
0.89742
game-dev
0.960076
1
0.960076
Pursue525/Nattalie-1.12.2
2,825
src/net/minecraft/world/biome/BiomeSnow.java
package net.minecraft.world.biome; import java.util.Iterator; import java.util.Random; import net.minecraft.entity.monster.EntityPolarBear; import net.minecraft.entity.monster.EntitySkeleton; import net.minecraft.entity.monster.EntityStray; import net.minecraft.entity.passive.EntityRabbit; import net.minecraft.init.Blocks; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraft.world.gen.feature.WorldGenAbstractTree; import net.minecraft.world.gen.feature.WorldGenIcePath; import net.minecraft.world.gen.feature.WorldGenIceSpike; import net.minecraft.world.gen.feature.WorldGenTaiga2; public class BiomeSnow extends Biome { private final boolean superIcy; private final WorldGenIceSpike iceSpike = new WorldGenIceSpike(); private final WorldGenIcePath icePatch = new WorldGenIcePath(4); public BiomeSnow(boolean superIcyIn, Biome.BiomeProperties properties) { super(properties); this.superIcy = superIcyIn; if (superIcyIn) { this.topBlock = Blocks.SNOW.getDefaultState(); } this.spawnableCreatureList.clear(); this.spawnableCreatureList.add(new Biome.SpawnListEntry(EntityRabbit.class, 10, 2, 3)); this.spawnableCreatureList.add(new Biome.SpawnListEntry(EntityPolarBear.class, 1, 1, 2)); Iterator<Biome.SpawnListEntry> iterator = this.spawnableMonsterList.iterator(); while (iterator.hasNext()) { Biome.SpawnListEntry biome$spawnlistentry = iterator.next(); if (biome$spawnlistentry.entityClass == EntitySkeleton.class) { iterator.remove(); } } this.spawnableMonsterList.add(new Biome.SpawnListEntry(EntitySkeleton.class, 20, 4, 4)); this.spawnableMonsterList.add(new Biome.SpawnListEntry(EntityStray.class, 80, 4, 4)); } /** * returns the chance a creature has to spawn. */ public float getSpawningChance() { return 0.07F; } public void decorate(World worldIn, Random rand, BlockPos pos) { if (this.superIcy) { for (int i = 0; i < 3; ++i) { int j = rand.nextInt(16) + 8; int k = rand.nextInt(16) + 8; this.iceSpike.generate(worldIn, rand, worldIn.getHeight(pos.add(j, 0, k))); } for (int l = 0; l < 2; ++l) { int i1 = rand.nextInt(16) + 8; int j1 = rand.nextInt(16) + 8; this.icePatch.generate(worldIn, rand, worldIn.getHeight(pos.add(i1, 0, j1))); } } super.decorate(worldIn, rand, pos); } public WorldGenAbstractTree genBigTreeChance(Random rand) { return new WorldGenTaiga2(false); } }
0
0.768454
1
0.768454
game-dev
MEDIA
0.994206
game-dev
0.722333
1
0.722333
ProjectIgnis/CardScripts
2,841
official/c39613288.lua
--ダーク・スプレマシー --Dark Supremacy --Scripted by The Razgriz local s,id=GetID() function s.initial_effect(c) --Negate the effects of cards your opponent controls, up to the number of "Dark Fusion" and Spells that mention it in your GY local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(id,0)) e1:SetCategory(CATEGORY_DISABLE) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetCode(EVENT_FREE_CHAIN) e1:SetHintTiming(0,TIMING_STANDBY_PHASE|TIMING_MAIN_END|TIMINGS_CHECK_MONSTER) e1:SetCountLimit(1,id) e1:SetTarget(s.distg) e1:SetOperation(s.disop) c:RegisterEffect(e1) --Shuffle up to 5 "HERO" monsters from your GY and/or banishment into the Deck local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(id,1)) e2:SetCategory(CATEGORY_TODECK) e2:SetType(EFFECT_TYPE_QUICK_O) e2:SetProperty(EFFECT_FLAG_CARD_TARGET) e2:SetCode(EVENT_FREE_CHAIN) e2:SetRange(LOCATION_GRAVE) e2:SetHintTiming(0,TIMING_MAIN_END|TIMINGS_CHECK_MONSTER_E) e2:SetCountLimit(1,{id,1}) e2:SetCondition(aux.exccon) e2:SetCost(Cost.SelfBanish) e2:SetTarget(s.tdtg) e2:SetOperation(s.tdop) c:RegisterEffect(e2) end s.listed_series={SET_HERO} s.listed_names={CARD_DARK_FUSION} function s.disctfilter(c) return c:IsCode(CARD_DARK_FUSION) or (c:IsSpell() and c:ListsCode(CARD_DARK_FUSION)) end function s.distg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsOnField() and chkc:IsControler(1-tp) and chkc:IsNegatable() end local ct=Duel.GetMatchingGroupCount(s.disctfilter,tp,LOCATION_GRAVE,0,nil) if chk==0 then return ct>0 and Duel.IsExistingTarget(Card.IsNegatable,tp,0,LOCATION_ONFIELD,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_NEGATE) local g=Duel.SelectTarget(tp,Card.IsNegatable,tp,0,LOCATION_ONFIELD,1,ct,nil) Duel.SetOperationInfo(0,CATEGORY_DISABLE,g,#g,tp,0) end function s.disop(e,tp,eg,ep,ev,re,r,rp) local tg=Duel.GetTargetCards(e):Match(Card.IsFaceup,nil) if #tg==0 then return end local c=e:GetHandler() for tc in tg:Iter() do --Negate their effects until the end of this turn tc:NegateEffects(c,RESET_PHASE|PHASE_END,true) end end function s.tdfilter(c) return c:IsSetCard(SET_HERO) and c:IsMonster() and c:IsFaceup() and c:IsAbleToDeck() end function s.tdtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_GRAVE|LOCATION_REMOVED) and chkc:IsControler(tp) and s.tdfilter(chkc) end if chk==0 then return Duel.IsExistingTarget(s.tdfilter,tp,LOCATION_GRAVE|LOCATION_REMOVED,0,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TODECK) local g=Duel.SelectTarget(tp,s.tdfilter,tp,LOCATION_GRAVE|LOCATION_REMOVED,0,1,5,nil) Duel.SetOperationInfo(0,CATEGORY_TODECK,g,#g,tp,0) end function s.tdop(e,tp,eg,ep,ev,re,r,rp) local tg=Duel.GetTargetCards(e) if #tg>0 then Duel.SendtoDeck(tg,nil,SEQ_DECKSHUFFLE,REASON_EFFECT) end end
0
0.944751
1
0.944751
game-dev
MEDIA
0.984184
game-dev
0.974569
1
0.974569
Leystryku/LeySourceEngineProxyServ
19,288
leyzyremodule/csteamid.h
//========================== Open Steamworks ================================ // // This file is part of the Open Steamworks project. All individuals associated // with this project do not claim ownership of the contents // // The code, comments, and all related files, projects, resources, // redistributables included with this project are Copyright Valve Corporation. // Additionally, Valve, the Valve logo, Half-Life, the Half-Life logo, the // Lambda logo, Steam, the Steam logo, Team Fortress, the Team Fortress logo, // Opposing Force, Day of Defeat, the Day of Defeat logo, Counter-Strike, the // Counter-Strike logo, Source, the Source logo, and Counter-Strike Condition // Zero are trademarks and or registered trademarks of Valve Corporation. // All other trademarks are property of their respective owners. // //============================================================================= #ifndef CSTEAMID_H #define CSTEAMID_H #ifdef _WIN32 #pragma once #endif #pragma pack( push, 1 ) // Steam universes. Each universe is a self-contained Steam instance. #define k_EChatInstanceFlagLobby 0 // Each user in the DB has a unique SteamLocalUserID_t (a serial number, with possible // rare gaps in the sequence). typedef unsigned short SteamInstanceID_t; // MUST be 16 bits #if defined (_MSC_VER) typedef unsigned __int64 SteamLocalUserID_t; // MUST be 64 bits #else typedef unsigned long long SteamLocalUserID_t; // MUST be 64 bits #endif #define STEAM_QUESTION_MAXLEN (255) typedef char SteamPersonalQuestion_t[STEAM_QUESTION_MAXLEN + 1]; typedef struct TSteamSplitLocalUserID { unsigned int Low32bits; unsigned int High32bits; } TSteamSplitLocalUserID; typedef struct TSteamGlobalUserID { SteamInstanceID_t m_SteamInstanceID; union m_SteamLocalUserID { SteamLocalUserID_t As64bits; TSteamSplitLocalUserID Split; } m_SteamLocalUserID; } TSteamGlobalUserID; enum EUniverse { k_EUniverseInvalid = 0, k_EUniversePublic = 1, k_EUniverseBeta = 2, k_EUniverseInternal = 3, k_EUniverseDev = 4, k_EUniverseRC = 5, k_EUniverseMax }; //----------------------------------------------------------------------------- // types of user game stats fields // WARNING: DO NOT RENUMBER EXISTING VALUES - STORED IN DATABASE //----------------------------------------------------------------------------- enum ESteamUserStatType { k_ESteamUserStatTypeINVALID = 0, k_ESteamUserStatTypeINT = 1, k_ESteamUserStatTypeFLOAT = 2, // Read as FLOAT, set with count / session length k_ESteamUserStatTypeAVGRATE = 3, k_ESteamUserStatTypeACHIEVEMENTS = 4, k_ESteamUserStatTypeGROUPACHIEVEMENTS = 5, }; // Steam ID structure (64 bits total) class CSteamID { public: //----------------------------------------------------------------------------- // Purpose: Constructor //----------------------------------------------------------------------------- CSteamID() { m_steamid.m_comp.m_unAccountID = 0; m_steamid.m_comp.m_EAccountType = k_EAccountTypeInvalid; m_steamid.m_comp.m_EUniverse = k_EUniverseInvalid; m_steamid.m_comp.m_unAccountInstance = 0; } //----------------------------------------------------------------------------- // Purpose: Constructor // Input : unAccountID - 32-bit account ID // eUniverse - Universe this account belongs to // eAccountType - Type of account //----------------------------------------------------------------------------- CSteamID(unsigned int unAccountID, EUniverse eUniverse, EAccountType eAccountType) { Set(unAccountID, eUniverse, eAccountType); } //----------------------------------------------------------------------------- // Purpose: Constructor // Input : unAccountID - 32-bit account ID // unAccountInstance - instance // eUniverse - Universe this account belongs to // eAccountType - Type of account //----------------------------------------------------------------------------- CSteamID(unsigned int unAccountID, unsigned int unAccountInstance, EUniverse eUniverse, EAccountType eAccountType) { InstancedSet(unAccountID, unAccountInstance, eUniverse, eAccountType); } //----------------------------------------------------------------------------- // Purpose: Constructor // Input : ulSteamID - 64-bit representation of a Steam ID // Note: Will not accept a uint32 or int32 as input, as that is a probable mistake. // See the stubbed out overloads in the private: section for more info. //----------------------------------------------------------------------------- CSteamID(unsigned long ulSteamID) { SetFromUint64(ulSteamID); } //----------------------------------------------------------------------------- // Purpose: Sets parameters for steam ID // Input : unAccountID - 32-bit account ID // eUniverse - Universe this account belongs to // eAccountType - Type of account //----------------------------------------------------------------------------- void Set(unsigned int unAccountID, EUniverse eUniverse, EAccountType eAccountType) { m_steamid.m_comp.m_unAccountID = unAccountID; m_steamid.m_comp.m_EUniverse = eUniverse; m_steamid.m_comp.m_EAccountType = eAccountType; if (eAccountType == k_EAccountTypeClan) { m_steamid.m_comp.m_unAccountInstance = 0; } else { m_steamid.m_comp.m_unAccountInstance = 1; } } //----------------------------------------------------------------------------- // Purpose: Sets parameters for steam ID // Input : unAccountID - 32-bit account ID // eUniverse - Universe this account belongs to // eAccountType - Type of account //----------------------------------------------------------------------------- void InstancedSet(unsigned int unAccountID, unsigned int unInstance, EUniverse eUniverse, EAccountType eAccountType) { m_steamid.m_comp.m_unAccountID = unAccountID; m_steamid.m_comp.m_EUniverse = eUniverse; m_steamid.m_comp.m_EAccountType = eAccountType; m_steamid.m_comp.m_unAccountInstance = unInstance; } //----------------------------------------------------------------------------- // Purpose: Initializes a steam ID from its 52 bit parts and universe/type // Input : ulIdentifier - 52 bits of goodness //----------------------------------------------------------------------------- void FullSet(unsigned long long ulIdentifier, EUniverse eUniverse, EAccountType eAccountType) { m_steamid.m_comp.m_unAccountID = (ulIdentifier & 0xFFFFFFFF); // account ID is low 32 bits m_steamid.m_comp.m_unAccountInstance = ((ulIdentifier >> 32) & 0xFFFFF); // account instance is next 20 bits m_steamid.m_comp.m_EUniverse = eUniverse; m_steamid.m_comp.m_EAccountType = eAccountType; } //----------------------------------------------------------------------------- // Purpose: Initializes a steam ID from its 64-bit representation // Input : ulSteamID - 64-bit representation of a Steam ID //----------------------------------------------------------------------------- void SetFromUint64(unsigned long long ulSteamID) { m_steamid.m_unAll64Bits = ulSteamID; } //----------------------------------------------------------------------------- // Purpose: Initializes a steam ID from a Steam2 ID structure // Input: pTSteamGlobalUserID - Steam2 ID to convert // eUniverse - universe this ID belongs to //----------------------------------------------------------------------------- void SetFromSteam2(TSteamGlobalUserID *pTSteamGlobalUserID, EUniverse eUniverse) { m_steamid.m_comp.m_unAccountID = pTSteamGlobalUserID->m_SteamLocalUserID.Split.Low32bits * 2 + pTSteamGlobalUserID->m_SteamLocalUserID.Split.High32bits; m_steamid.m_comp.m_EUniverse = eUniverse; // set the universe m_steamid.m_comp.m_EAccountType = k_EAccountTypeIndividual; // Steam 2 accounts always map to account type of individual m_steamid.m_comp.m_unAccountInstance = 1; // individual accounts always have an account instance ID of 1 } //----------------------------------------------------------------------------- // Purpose: Fills out a Steam2 ID structure // Input: pTSteamGlobalUserID - Steam2 ID to write to //----------------------------------------------------------------------------- void ConvertToSteam2(TSteamGlobalUserID *pTSteamGlobalUserID) const { // only individual accounts have any meaning in Steam 2, only they can be mapped // Assert( m_steamid.m_comp.m_EAccountType == k_EAccountTypeIndividual ); pTSteamGlobalUserID->m_SteamInstanceID = 0; pTSteamGlobalUserID->m_SteamLocalUserID.Split.High32bits = m_steamid.m_comp.m_unAccountID % 2; pTSteamGlobalUserID->m_SteamLocalUserID.Split.Low32bits = m_steamid.m_comp.m_unAccountID / 2; } //----------------------------------------------------------------------------- // Purpose: Converts steam ID to its 64-bit representation // Output : 64-bit representation of a Steam ID //----------------------------------------------------------------------------- unsigned long long ConvertToUint64() const { return m_steamid.m_unAll64Bits; } //----------------------------------------------------------------------------- // Purpose: Converts the static parts of a steam ID to a 64-bit representation. // For multiseat accounts, all instances of that account will have the // same static account key, so they can be grouped together by the static // account key. // Output : 64-bit static account key //----------------------------------------------------------------------------- unsigned long long GetStaticAccountKey() const { // note we do NOT include the account instance (which is a dynamic property) in the static account key return (unsigned long long)((((unsigned long long)m_steamid.m_comp.m_EUniverse) << 56) + ((unsigned long long)m_steamid.m_comp.m_EAccountType << 52) + m_steamid.m_comp.m_unAccountID); } //----------------------------------------------------------------------------- // Purpose: create an anonymous game server login to be filled in by the AM //----------------------------------------------------------------------------- void CreateBlankAnonLogon(EUniverse eUniverse) { m_steamid.m_comp.m_unAccountID = 0; m_steamid.m_comp.m_EAccountType = k_EAccountTypeAnonGameServer; m_steamid.m_comp.m_EUniverse = eUniverse; m_steamid.m_comp.m_unAccountInstance = 0; } //----------------------------------------------------------------------------- // Purpose: create an anonymous game server login to be filled in by the AM //----------------------------------------------------------------------------- void CreateBlankAnonUserLogon(EUniverse eUniverse) { m_steamid.m_comp.m_unAccountID = 0; m_steamid.m_comp.m_EAccountType = k_EAccountTypeAnonUser; m_steamid.m_comp.m_EUniverse = eUniverse; m_steamid.m_comp.m_unAccountInstance = 0; } //----------------------------------------------------------------------------- // Purpose: Is this an anonymous game server login that will be filled in? //----------------------------------------------------------------------------- bool BBlankAnonAccount() const { return m_steamid.m_comp.m_unAccountID == 0 && BAnonAccount() && m_steamid.m_comp.m_unAccountInstance == 0; } //----------------------------------------------------------------------------- // Purpose: Is this a game server account id? //----------------------------------------------------------------------------- bool BGameServerAccount() const { return m_steamid.m_comp.m_EAccountType == k_EAccountTypeGameServer || m_steamid.m_comp.m_EAccountType == k_EAccountTypeAnonGameServer; } //----------------------------------------------------------------------------- // Purpose: Is this a content server account id? //----------------------------------------------------------------------------- bool BContentServerAccount() const { return m_steamid.m_comp.m_EAccountType == k_EAccountTypeContentServer; } //----------------------------------------------------------------------------- // Purpose: Is this a clan account id? //----------------------------------------------------------------------------- bool BClanAccount() const { return m_steamid.m_comp.m_EAccountType == k_EAccountTypeClan; } //----------------------------------------------------------------------------- // Purpose: Is this a chat account id? //----------------------------------------------------------------------------- bool BChatAccount() const { return m_steamid.m_comp.m_EAccountType == k_EAccountTypeChat; } //----------------------------------------------------------------------------- // Purpose: Is this a chat account id? //----------------------------------------------------------------------------- bool IsLobby() const { return (m_steamid.m_comp.m_EAccountType == k_EAccountTypeChat) && (m_steamid.m_comp.m_unAccountInstance & k_EChatInstanceFlagLobby); } //----------------------------------------------------------------------------- // Purpose: Is this an individual user account id? //----------------------------------------------------------------------------- bool BIndividualAccount() const { return m_steamid.m_comp.m_EAccountType == k_EAccountTypeIndividual; } //----------------------------------------------------------------------------- // Purpose: Is this an anonymous account? //----------------------------------------------------------------------------- bool BAnonAccount() const { return m_steamid.m_comp.m_EAccountType == k_EAccountTypeAnonUser || m_steamid.m_comp.m_EAccountType == k_EAccountTypeAnonGameServer; } //----------------------------------------------------------------------------- // Purpose: Is this an anonymous user account? ( used to create an account or reset a password ) //----------------------------------------------------------------------------- bool BAnonUserAccount() const { return m_steamid.m_comp.m_EAccountType == k_EAccountTypeAnonUser; } // simple accessors void SetAccountID(unsigned int unAccountID) { m_steamid.m_comp.m_unAccountID = unAccountID; } unsigned int GetAccountID() const { return m_steamid.m_comp.m_unAccountID; } unsigned int GetUnAccountInstance() const { return m_steamid.m_comp.m_unAccountInstance; } EAccountType GetEAccountType() const { return (EAccountType)m_steamid.m_comp.m_EAccountType; } EUniverse GetEUniverse() const { return m_steamid.m_comp.m_EUniverse; } void SetEUniverse(EUniverse eUniverse) { m_steamid.m_comp.m_EUniverse = eUniverse; } bool IsValid() const; // this set of functions is hidden, will be moved out of class explicit CSteamID(const char *pchSteamID, EUniverse eDefaultUniverse = k_EUniverseInvalid); const char * Render() const // renders this steam ID to string { static char szSteamID[64]; #ifndef _WIN32 snprintf(szSteamID, sizeof(szSteamID), "STEAM_0:%u:%u", (m_steamid.m_comp.m_unAccountID % 2) ? 1 : 0, (int)m_steamid.m_comp.m_unAccountID / 2); #else _snprintf(szSteamID, sizeof(szSteamID), "STEAM_0:%u:%u", (m_steamid.m_comp.m_unAccountID % 2) ? 1 : 0, (int)m_steamid.m_comp.m_unAccountID / 2); #endif return szSteamID; } static const char * Render(unsigned int ulSteamID) // static method to render a uint64 representation of a steam ID to a string { return CSteamID(ulSteamID).Render(); } void SetFromString(const char *pchSteamID, EUniverse eDefaultUniverse); bool SetFromSteam2String(const char *pchSteam2ID, EUniverse eUniverse); inline bool operator==(const CSteamID &val) const { return m_steamid.m_unAll64Bits == val.m_steamid.m_unAll64Bits; } inline bool operator!=(const CSteamID &val) const { return !operator==(val); } inline bool operator<(const CSteamID &val) const { return m_steamid.m_unAll64Bits < val.m_steamid.m_unAll64Bits; } inline bool operator>(const CSteamID &val) const { return m_steamid.m_unAll64Bits > val.m_steamid.m_unAll64Bits; } // DEBUG function bool BValidExternalSteamID() const; private: // These are defined here to prevent accidental implicit conversion of a u32AccountID to a CSteamID. // If you get a compiler error about an ambiguous constructor/function then it may be because you're // passing a 32-bit int to a function that takes a CSteamID. You should explicitly create the SteamID // using the correct Universe and account Type/Instance values. CSteamID(unsigned int); CSteamID(int); // 64 bits total union SteamID_t { struct SteamIDComponent_t { unsigned int m_unAccountID : 32; // unique account identifier unsigned int m_unAccountInstance : 20; // dynamic instance ID (used for multiseat type accounts only) unsigned int m_EAccountType : 4; // type of account - can't show as EAccountType, due to signed / unsigned difference EUniverse m_EUniverse : 8; // universe this account belongs to } m_comp; unsigned long long m_unAll64Bits; } m_steamid; }; inline bool CSteamID::IsValid() const { if (m_steamid.m_comp.m_EAccountType <= k_EAccountTypeInvalid || m_steamid.m_comp.m_EAccountType >= k_EAccountTypeMax) return false; if (m_steamid.m_comp.m_EUniverse <= k_EUniverseInvalid || m_steamid.m_comp.m_EUniverse >= k_EUniverseMax) return false; if (m_steamid.m_comp.m_EAccountType == k_EAccountTypeIndividual) { if (m_steamid.m_comp.m_unAccountID == 0 || m_steamid.m_comp.m_unAccountInstance != 1) return false; } if (m_steamid.m_comp.m_EAccountType == k_EAccountTypeClan) { if (m_steamid.m_comp.m_unAccountID == 0 || m_steamid.m_comp.m_unAccountInstance != 0) return false; } return true; } // generic invalid CSteamID const CSteamID k_steamIDNil; // This steamID comes from a user game connection to an out of date GS that hasnt implemented the protocol // to provide its steamID const CSteamID k_steamIDOutofDateGS(0, 0, k_EUniversePublic, k_EAccountTypeIndividual); // This steamID comes from a user game connection to an sv_lan GS const CSteamID k_steamIDLanModeGS((unsigned int)0, (unsigned int)0, k_EUniversePublic, k_EAccountTypeIndividual); // This steamID can come from a user game connection to a GS that has just booted but hasnt yet even initialized // its steam3 component and started logging on. const CSteamID k_steamIDNotInitYetGS((unsigned int)1, (unsigned int)0, k_EUniverseInvalid, k_EAccountTypeIndividual); // This steamID can come from a user game connection to a GS that isn't using the steam authentication system but still // wants to support the "Join Game" option in the friends list const CSteamID k_steamIDNonSteamGS((unsigned int)2, (unsigned int)0, k_EUniverseInvalid, k_EAccountTypeIndividual); #ifdef STEAM // Returns the matching chat steamID, with the default instance of 0 // If the steamID passed in is already of type k_EAccountTypeChat it will be returned with the same instance CSteamID ChatIDFromSteamID(const CSteamID &steamID); // Returns the matching clan steamID, with the default instance of 0 // If the steamID passed in is already of type k_EAccountTypeClan it will be returned with the same instance CSteamID ClanIDFromSteamID(const CSteamID &steamID); // Asserts steamID type before conversion CSteamID ChatIDFromClanID(const CSteamID &steamIDClan); // Asserts steamID type before conversion CSteamID ClanIDFromChatID(const CSteamID &steamIDChat); #endif // _STEAM #pragma pack( pop ) #endif // CSTEAMID_H
0
0.914386
1
0.914386
game-dev
MEDIA
0.604345
game-dev
0.785364
1
0.785364
Pursue525/Nattalie-1.12.2
2,830
src/net/minecraft/entity/ai/EntityAIBreakDoor.java
package net.minecraft.entity.ai; import net.minecraft.block.Block; import net.minecraft.block.BlockDoor; import net.minecraft.entity.EntityLiving; import net.minecraft.world.EnumDifficulty; public class EntityAIBreakDoor extends EntityAIDoorInteract { private int breakingTime; private int previousBreakProgress = -1; public EntityAIBreakDoor(EntityLiving entityIn) { super(entityIn); } /** * Returns whether the EntityAIBase should begin execution. */ public boolean shouldExecute() { if (!super.shouldExecute()) { return false; } else if (!this.theEntity.world.getGameRules().getBoolean("mobGriefing")) { return false; } else { BlockDoor blockdoor = this.doorBlock; return !BlockDoor.isOpen(this.theEntity.world, this.doorPosition); } } /** * Execute a one shot task or start executing a continuous task */ public void startExecuting() { super.startExecuting(); this.breakingTime = 0; } /** * Returns whether an in-progress EntityAIBase should continue executing */ public boolean continueExecuting() { double d0 = this.theEntity.getDistanceSq(this.doorPosition); boolean flag; if (this.breakingTime <= 240) { BlockDoor blockdoor = this.doorBlock; if (!BlockDoor.isOpen(this.theEntity.world, this.doorPosition) && d0 < 4.0D) { flag = true; return flag; } } flag = false; return flag; } /** * Resets the task */ public void resetTask() { super.resetTask(); this.theEntity.world.sendBlockBreakProgress(this.theEntity.getEntityId(), this.doorPosition, -1); } /** * Updates the task */ public void updateTask() { super.updateTask(); if (this.theEntity.getRNG().nextInt(20) == 0) { this.theEntity.world.playEvent(1019, this.doorPosition, 0); } ++this.breakingTime; int i = (int)((float)this.breakingTime / 240.0F * 10.0F); if (i != this.previousBreakProgress) { this.theEntity.world.sendBlockBreakProgress(this.theEntity.getEntityId(), this.doorPosition, i); this.previousBreakProgress = i; } if (this.breakingTime == 240 && this.theEntity.world.getDifficulty() == EnumDifficulty.HARD) { this.theEntity.world.setBlockToAir(this.doorPosition); this.theEntity.world.playEvent(1021, this.doorPosition, 0); this.theEntity.world.playEvent(2001, this.doorPosition, Block.getIdFromBlock(this.doorBlock)); } } }
0
0.909906
1
0.909906
game-dev
MEDIA
0.950222
game-dev
0.916939
1
0.916939
Skitttyy/shoreline-client
1,293
src/main/java/net/shoreline/client/mixin/render/block/entity/MixinSignBlockEntityRenderer.java
package net.shoreline.client.mixin.render.block.entity; import net.minecraft.block.entity.SignText; import net.minecraft.client.render.VertexConsumerProvider; import net.minecraft.client.render.block.entity.SignBlockEntityRenderer; import net.minecraft.client.util.math.MatrixStack; import net.minecraft.util.math.BlockPos; import net.shoreline.client.impl.event.render.block.entity.RenderSignTextEvent; import net.shoreline.eventbus.EventBus; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(SignBlockEntityRenderer.class) public class MixinSignBlockEntityRenderer { @Inject(method = "renderText", at = @At(value = "HEAD"), cancellable = true) private void hookRenderText(BlockPos pos, SignText signText, MatrixStack matrices, VertexConsumerProvider vertexConsumers, int light, int lineHeight, int lineWidth, boolean front, CallbackInfo ci) { RenderSignTextEvent renderSignTextEvent = new RenderSignTextEvent(); EventBus.INSTANCE.dispatch(renderSignTextEvent); if (renderSignTextEvent.isCanceled()) { ci.cancel(); } } }
0
0.773319
1
0.773319
game-dev
MEDIA
0.861142
game-dev,graphics-rendering
0.635363
1
0.635363
reshadhstu/Unity-CoreToolkit
2,440
Editor/GUIDrawer/RequiredFieldDrawer.cs
using CoreToolkit.Runtime.Attributes; using UnityEditor; using UnityEngine; namespace CoreToolkit.Editor.GUIDrawer { [CustomPropertyDrawer(typeof(RequiredFieldAttribute))] public class RequiredFieldDrawer : PropertyDrawer { #if CORE_TOOLKIT_ICONS private const string RequiredIconPath = "Packages/com.reshad.coretoolkit/Editor/Icons/RequiredIcon/RequiredIcon.png"; #else private const string RequiredIconPath = "Assets/CoreToolkit/Editor/Icons/RequiredIcon/RequiredIcon.png"; #endif Texture2D _requiredIcon = AssetDatabase.LoadAssetAtPath<Texture2D>(RequiredIconPath); public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { EditorGUI.BeginProperty(position, label, property); EditorGUI.BeginChangeCheck(); Rect fieldRect = new (position.x, position.y, position.width - 20, position.height); EditorGUI.PropertyField(fieldRect, property, label); // If the field is required but unassigned, show the icon if (IsFieldUnassigned(property)) { Rect iconRect = new (position.xMax - 18, fieldRect.y, 16, 16); GUI.Label(iconRect, new GUIContent(_requiredIcon, "This field is required and is either missing or empty!")); } if (EditorGUI.EndChangeCheck()) { property.serializedObject.ApplyModifiedProperties(); EditorUtility.SetDirty(property.serializedObject.targetObject); // Force a repaint of the hierarchy EditorApplication.RepaintHierarchyWindow(); } EditorGUI.EndProperty(); } bool IsFieldUnassigned(SerializedProperty property) { switch (property.propertyType) { // Add additional types as necessary case SerializedPropertyType.ObjectReference when property.objectReferenceValue: case SerializedPropertyType.ExposedReference when property.exposedReferenceValue: case SerializedPropertyType.AnimationCurve when property.animationCurveValue is { length: > 0 }: case SerializedPropertyType.String when !string.IsNullOrEmpty( property.stringValue ): return false; default: return true; } } } }
0
0.927846
1
0.927846
game-dev
MEDIA
0.58142
game-dev,desktop-app
0.960706
1
0.960706
joschu/trajopt
36,448
ext/bullet/src/BulletDynamics/ConstraintSolver/btConeTwistConstraint.cpp
/* Bullet Continuous Collision Detection and Physics Library btConeTwistConstraint is Copyright (c) 2007 Starbreeze Studios 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. Written by: Marcus Hennix */ #include "btConeTwistConstraint.h" #include "BulletDynamics/Dynamics/btRigidBody.h" #include "LinearMath/btTransformUtil.h" #include "LinearMath/btMinMax.h" #include <new> //#define CONETWIST_USE_OBSOLETE_SOLVER true #define CONETWIST_USE_OBSOLETE_SOLVER false #define CONETWIST_DEF_FIX_THRESH btScalar(.05f) SIMD_FORCE_INLINE btScalar computeAngularImpulseDenominator(const btVector3& axis, const btMatrix3x3& invInertiaWorld) { btVector3 vec = axis * invInertiaWorld; return axis.dot(vec); } btConeTwistConstraint::btConeTwistConstraint(btRigidBody& rbA,btRigidBody& rbB, const btTransform& rbAFrame,const btTransform& rbBFrame) :btTypedConstraint(CONETWIST_CONSTRAINT_TYPE, rbA,rbB),m_rbAFrame(rbAFrame),m_rbBFrame(rbBFrame), m_angularOnly(false), m_useSolveConstraintObsolete(CONETWIST_USE_OBSOLETE_SOLVER) { init(); } btConeTwistConstraint::btConeTwistConstraint(btRigidBody& rbA,const btTransform& rbAFrame) :btTypedConstraint(CONETWIST_CONSTRAINT_TYPE,rbA),m_rbAFrame(rbAFrame), m_angularOnly(false), m_useSolveConstraintObsolete(CONETWIST_USE_OBSOLETE_SOLVER) { m_rbBFrame = m_rbAFrame; m_rbBFrame.setOrigin(btVector3(0., 0., 0.)); init(); } void btConeTwistConstraint::init() { m_angularOnly = false; m_solveTwistLimit = false; m_solveSwingLimit = false; m_bMotorEnabled = false; m_maxMotorImpulse = btScalar(-1); setLimit(btScalar(BT_LARGE_FLOAT), btScalar(BT_LARGE_FLOAT), btScalar(BT_LARGE_FLOAT)); m_damping = btScalar(0.01); m_fixThresh = CONETWIST_DEF_FIX_THRESH; m_flags = 0; m_linCFM = btScalar(0.f); m_linERP = btScalar(0.7f); m_angCFM = btScalar(0.f); } void btConeTwistConstraint::getInfo1 (btConstraintInfo1* info) { if (m_useSolveConstraintObsolete) { info->m_numConstraintRows = 0; info->nub = 0; } else { info->m_numConstraintRows = 3; info->nub = 3; calcAngleInfo2(m_rbA.getCenterOfMassTransform(),m_rbB.getCenterOfMassTransform(),m_rbA.getInvInertiaTensorWorld(),m_rbB.getInvInertiaTensorWorld()); if(m_solveSwingLimit) { info->m_numConstraintRows++; info->nub--; if((m_swingSpan1 < m_fixThresh) && (m_swingSpan2 < m_fixThresh)) { info->m_numConstraintRows++; info->nub--; } } if(m_solveTwistLimit) { info->m_numConstraintRows++; info->nub--; } } } void btConeTwistConstraint::getInfo1NonVirtual (btConstraintInfo1* info) { //always reserve 6 rows: object transform is not available on SPU info->m_numConstraintRows = 6; info->nub = 0; } void btConeTwistConstraint::getInfo2 (btConstraintInfo2* info) { getInfo2NonVirtual(info,m_rbA.getCenterOfMassTransform(),m_rbB.getCenterOfMassTransform(),m_rbA.getInvInertiaTensorWorld(),m_rbB.getInvInertiaTensorWorld()); } void btConeTwistConstraint::getInfo2NonVirtual (btConstraintInfo2* info,const btTransform& transA,const btTransform& transB,const btMatrix3x3& invInertiaWorldA,const btMatrix3x3& invInertiaWorldB) { calcAngleInfo2(transA,transB,invInertiaWorldA,invInertiaWorldB); btAssert(!m_useSolveConstraintObsolete); // set jacobian info->m_J1linearAxis[0] = 1; info->m_J1linearAxis[info->rowskip+1] = 1; info->m_J1linearAxis[2*info->rowskip+2] = 1; btVector3 a1 = transA.getBasis() * m_rbAFrame.getOrigin(); { btVector3* angular0 = (btVector3*)(info->m_J1angularAxis); btVector3* angular1 = (btVector3*)(info->m_J1angularAxis+info->rowskip); btVector3* angular2 = (btVector3*)(info->m_J1angularAxis+2*info->rowskip); btVector3 a1neg = -a1; a1neg.getSkewSymmetricMatrix(angular0,angular1,angular2); } info->m_J2linearAxis[0] = -1; info->m_J2linearAxis[info->rowskip+1] = -1; info->m_J2linearAxis[2*info->rowskip+2] = -1; btVector3 a2 = transB.getBasis() * m_rbBFrame.getOrigin(); { btVector3* angular0 = (btVector3*)(info->m_J2angularAxis); btVector3* angular1 = (btVector3*)(info->m_J2angularAxis+info->rowskip); btVector3* angular2 = (btVector3*)(info->m_J2angularAxis+2*info->rowskip); a2.getSkewSymmetricMatrix(angular0,angular1,angular2); } // set right hand side btScalar linERP = (m_flags & BT_CONETWIST_FLAGS_LIN_ERP) ? m_linERP : info->erp; btScalar k = info->fps * linERP; int j; for (j=0; j<3; j++) { info->m_constraintError[j*info->rowskip] = k * (a2[j] + transB.getOrigin()[j] - a1[j] - transA.getOrigin()[j]); info->m_lowerLimit[j*info->rowskip] = -SIMD_INFINITY; info->m_upperLimit[j*info->rowskip] = SIMD_INFINITY; if(m_flags & BT_CONETWIST_FLAGS_LIN_CFM) { info->cfm[j*info->rowskip] = m_linCFM; } } int row = 3; int srow = row * info->rowskip; btVector3 ax1; // angular limits if(m_solveSwingLimit) { btScalar *J1 = info->m_J1angularAxis; btScalar *J2 = info->m_J2angularAxis; if((m_swingSpan1 < m_fixThresh) && (m_swingSpan2 < m_fixThresh)) { btTransform trA = transA*m_rbAFrame; btVector3 p = trA.getBasis().getColumn(1); btVector3 q = trA.getBasis().getColumn(2); int srow1 = srow + info->rowskip; J1[srow+0] = p[0]; J1[srow+1] = p[1]; J1[srow+2] = p[2]; J1[srow1+0] = q[0]; J1[srow1+1] = q[1]; J1[srow1+2] = q[2]; J2[srow+0] = -p[0]; J2[srow+1] = -p[1]; J2[srow+2] = -p[2]; J2[srow1+0] = -q[0]; J2[srow1+1] = -q[1]; J2[srow1+2] = -q[2]; btScalar fact = info->fps * m_relaxationFactor; info->m_constraintError[srow] = fact * m_swingAxis.dot(p); info->m_constraintError[srow1] = fact * m_swingAxis.dot(q); info->m_lowerLimit[srow] = -SIMD_INFINITY; info->m_upperLimit[srow] = SIMD_INFINITY; info->m_lowerLimit[srow1] = -SIMD_INFINITY; info->m_upperLimit[srow1] = SIMD_INFINITY; srow = srow1 + info->rowskip; } else { ax1 = m_swingAxis * m_relaxationFactor * m_relaxationFactor; J1[srow+0] = ax1[0]; J1[srow+1] = ax1[1]; J1[srow+2] = ax1[2]; J2[srow+0] = -ax1[0]; J2[srow+1] = -ax1[1]; J2[srow+2] = -ax1[2]; btScalar k = info->fps * m_biasFactor; info->m_constraintError[srow] = k * m_swingCorrection; if(m_flags & BT_CONETWIST_FLAGS_ANG_CFM) { info->cfm[srow] = m_angCFM; } // m_swingCorrection is always positive or 0 info->m_lowerLimit[srow] = 0; info->m_upperLimit[srow] = SIMD_INFINITY; srow += info->rowskip; } } if(m_solveTwistLimit) { ax1 = m_twistAxis * m_relaxationFactor * m_relaxationFactor; btScalar *J1 = info->m_J1angularAxis; btScalar *J2 = info->m_J2angularAxis; J1[srow+0] = ax1[0]; J1[srow+1] = ax1[1]; J1[srow+2] = ax1[2]; J2[srow+0] = -ax1[0]; J2[srow+1] = -ax1[1]; J2[srow+2] = -ax1[2]; btScalar k = info->fps * m_biasFactor; info->m_constraintError[srow] = k * m_twistCorrection; if(m_flags & BT_CONETWIST_FLAGS_ANG_CFM) { info->cfm[srow] = m_angCFM; } if(m_twistSpan > 0.0f) { if(m_twistCorrection > 0.0f) { info->m_lowerLimit[srow] = 0; info->m_upperLimit[srow] = SIMD_INFINITY; } else { info->m_lowerLimit[srow] = -SIMD_INFINITY; info->m_upperLimit[srow] = 0; } } else { info->m_lowerLimit[srow] = -SIMD_INFINITY; info->m_upperLimit[srow] = SIMD_INFINITY; } srow += info->rowskip; } } void btConeTwistConstraint::buildJacobian() { if (m_useSolveConstraintObsolete) { m_appliedImpulse = btScalar(0.); m_accTwistLimitImpulse = btScalar(0.); m_accSwingLimitImpulse = btScalar(0.); m_accMotorImpulse = btVector3(0.,0.,0.); if (!m_angularOnly) { btVector3 pivotAInW = m_rbA.getCenterOfMassTransform()*m_rbAFrame.getOrigin(); btVector3 pivotBInW = m_rbB.getCenterOfMassTransform()*m_rbBFrame.getOrigin(); btVector3 relPos = pivotBInW - pivotAInW; btVector3 normal[3]; if (relPos.length2() > SIMD_EPSILON) { normal[0] = relPos.normalized(); } else { normal[0].setValue(btScalar(1.0),0,0); } btPlaneSpace1(normal[0], normal[1], normal[2]); for (int i=0;i<3;i++) { new (&m_jac[i]) btJacobianEntry( m_rbA.getCenterOfMassTransform().getBasis().transpose(), m_rbB.getCenterOfMassTransform().getBasis().transpose(), pivotAInW - m_rbA.getCenterOfMassPosition(), pivotBInW - m_rbB.getCenterOfMassPosition(), normal[i], m_rbA.getInvInertiaDiagLocal(), m_rbA.getInvMass(), m_rbB.getInvInertiaDiagLocal(), m_rbB.getInvMass()); } } calcAngleInfo2(m_rbA.getCenterOfMassTransform(),m_rbB.getCenterOfMassTransform(),m_rbA.getInvInertiaTensorWorld(),m_rbB.getInvInertiaTensorWorld()); } } void btConeTwistConstraint::solveConstraintObsolete(btSolverBody& bodyA,btSolverBody& bodyB,btScalar timeStep) { #ifndef __SPU__ if (m_useSolveConstraintObsolete) { btVector3 pivotAInW = m_rbA.getCenterOfMassTransform()*m_rbAFrame.getOrigin(); btVector3 pivotBInW = m_rbB.getCenterOfMassTransform()*m_rbBFrame.getOrigin(); btScalar tau = btScalar(0.3); //linear part if (!m_angularOnly) { btVector3 rel_pos1 = pivotAInW - m_rbA.getCenterOfMassPosition(); btVector3 rel_pos2 = pivotBInW - m_rbB.getCenterOfMassPosition(); btVector3 vel1; bodyA.internalGetVelocityInLocalPointObsolete(rel_pos1,vel1); btVector3 vel2; bodyB.internalGetVelocityInLocalPointObsolete(rel_pos2,vel2); btVector3 vel = vel1 - vel2; for (int i=0;i<3;i++) { const btVector3& normal = m_jac[i].m_linearJointAxis; btScalar jacDiagABInv = btScalar(1.) / m_jac[i].getDiagonal(); btScalar rel_vel; rel_vel = normal.dot(vel); //positional error (zeroth order error) btScalar depth = -(pivotAInW - pivotBInW).dot(normal); //this is the error projected on the normal btScalar impulse = depth*tau/timeStep * jacDiagABInv - rel_vel * jacDiagABInv; m_appliedImpulse += impulse; btVector3 ftorqueAxis1 = rel_pos1.cross(normal); btVector3 ftorqueAxis2 = rel_pos2.cross(normal); bodyA.internalApplyImpulse(normal*m_rbA.getInvMass(), m_rbA.getInvInertiaTensorWorld()*ftorqueAxis1,impulse); bodyB.internalApplyImpulse(normal*m_rbB.getInvMass(), m_rbB.getInvInertiaTensorWorld()*ftorqueAxis2,-impulse); } } // apply motor if (m_bMotorEnabled) { // compute current and predicted transforms btTransform trACur = m_rbA.getCenterOfMassTransform(); btTransform trBCur = m_rbB.getCenterOfMassTransform(); btVector3 omegaA; bodyA.internalGetAngularVelocity(omegaA); btVector3 omegaB; bodyB.internalGetAngularVelocity(omegaB); btTransform trAPred; trAPred.setIdentity(); btVector3 zerovec(0,0,0); btTransformUtil::integrateTransform( trACur, zerovec, omegaA, timeStep, trAPred); btTransform trBPred; trBPred.setIdentity(); btTransformUtil::integrateTransform( trBCur, zerovec, omegaB, timeStep, trBPred); // compute desired transforms in world btTransform trPose(m_qTarget); btTransform trABDes = m_rbBFrame * trPose * m_rbAFrame.inverse(); btTransform trADes = trBPred * trABDes; btTransform trBDes = trAPred * trABDes.inverse(); // compute desired omegas in world btVector3 omegaADes, omegaBDes; btTransformUtil::calculateVelocity(trACur, trADes, timeStep, zerovec, omegaADes); btTransformUtil::calculateVelocity(trBCur, trBDes, timeStep, zerovec, omegaBDes); // compute delta omegas btVector3 dOmegaA = omegaADes - omegaA; btVector3 dOmegaB = omegaBDes - omegaB; // compute weighted avg axis of dOmega (weighting based on inertias) btVector3 axisA, axisB; btScalar kAxisAInv = 0, kAxisBInv = 0; if (dOmegaA.length2() > SIMD_EPSILON) { axisA = dOmegaA.normalized(); kAxisAInv = getRigidBodyA().computeAngularImpulseDenominator(axisA); } if (dOmegaB.length2() > SIMD_EPSILON) { axisB = dOmegaB.normalized(); kAxisBInv = getRigidBodyB().computeAngularImpulseDenominator(axisB); } btVector3 avgAxis = kAxisAInv * axisA + kAxisBInv * axisB; static bool bDoTorque = true; if (bDoTorque && avgAxis.length2() > SIMD_EPSILON) { avgAxis.normalize(); kAxisAInv = getRigidBodyA().computeAngularImpulseDenominator(avgAxis); kAxisBInv = getRigidBodyB().computeAngularImpulseDenominator(avgAxis); btScalar kInvCombined = kAxisAInv + kAxisBInv; btVector3 impulse = (kAxisAInv * dOmegaA - kAxisBInv * dOmegaB) / (kInvCombined * kInvCombined); if (m_maxMotorImpulse >= 0) { btScalar fMaxImpulse = m_maxMotorImpulse; if (m_bNormalizedMotorStrength) fMaxImpulse = fMaxImpulse/kAxisAInv; btVector3 newUnclampedAccImpulse = m_accMotorImpulse + impulse; btScalar newUnclampedMag = newUnclampedAccImpulse.length(); if (newUnclampedMag > fMaxImpulse) { newUnclampedAccImpulse.normalize(); newUnclampedAccImpulse *= fMaxImpulse; impulse = newUnclampedAccImpulse - m_accMotorImpulse; } m_accMotorImpulse += impulse; } btScalar impulseMag = impulse.length(); btVector3 impulseAxis = impulse / impulseMag; bodyA.internalApplyImpulse(btVector3(0,0,0), m_rbA.getInvInertiaTensorWorld()*impulseAxis, impulseMag); bodyB.internalApplyImpulse(btVector3(0,0,0), m_rbB.getInvInertiaTensorWorld()*impulseAxis, -impulseMag); } } else if (m_damping > SIMD_EPSILON) // no motor: do a little damping { btVector3 angVelA; bodyA.internalGetAngularVelocity(angVelA); btVector3 angVelB; bodyB.internalGetAngularVelocity(angVelB); btVector3 relVel = angVelB - angVelA; if (relVel.length2() > SIMD_EPSILON) { btVector3 relVelAxis = relVel.normalized(); btScalar m_kDamping = btScalar(1.) / (getRigidBodyA().computeAngularImpulseDenominator(relVelAxis) + getRigidBodyB().computeAngularImpulseDenominator(relVelAxis)); btVector3 impulse = m_damping * m_kDamping * relVel; btScalar impulseMag = impulse.length(); btVector3 impulseAxis = impulse / impulseMag; bodyA.internalApplyImpulse(btVector3(0,0,0), m_rbA.getInvInertiaTensorWorld()*impulseAxis, impulseMag); bodyB.internalApplyImpulse(btVector3(0,0,0), m_rbB.getInvInertiaTensorWorld()*impulseAxis, -impulseMag); } } // joint limits { ///solve angular part btVector3 angVelA; bodyA.internalGetAngularVelocity(angVelA); btVector3 angVelB; bodyB.internalGetAngularVelocity(angVelB); // solve swing limit if (m_solveSwingLimit) { btScalar amplitude = m_swingLimitRatio * m_swingCorrection*m_biasFactor/timeStep; btScalar relSwingVel = (angVelB - angVelA).dot(m_swingAxis); if (relSwingVel > 0) amplitude += m_swingLimitRatio * relSwingVel * m_relaxationFactor; btScalar impulseMag = amplitude * m_kSwing; // Clamp the accumulated impulse btScalar temp = m_accSwingLimitImpulse; m_accSwingLimitImpulse = btMax(m_accSwingLimitImpulse + impulseMag, btScalar(0.0) ); impulseMag = m_accSwingLimitImpulse - temp; btVector3 impulse = m_swingAxis * impulseMag; // don't let cone response affect twist // (this can happen since body A's twist doesn't match body B's AND we use an elliptical cone limit) { btVector3 impulseTwistCouple = impulse.dot(m_twistAxisA) * m_twistAxisA; btVector3 impulseNoTwistCouple = impulse - impulseTwistCouple; impulse = impulseNoTwistCouple; } impulseMag = impulse.length(); btVector3 noTwistSwingAxis = impulse / impulseMag; bodyA.internalApplyImpulse(btVector3(0,0,0), m_rbA.getInvInertiaTensorWorld()*noTwistSwingAxis, impulseMag); bodyB.internalApplyImpulse(btVector3(0,0,0), m_rbB.getInvInertiaTensorWorld()*noTwistSwingAxis, -impulseMag); } // solve twist limit if (m_solveTwistLimit) { btScalar amplitude = m_twistLimitRatio * m_twistCorrection*m_biasFactor/timeStep; btScalar relTwistVel = (angVelB - angVelA).dot( m_twistAxis ); if (relTwistVel > 0) // only damp when moving towards limit (m_twistAxis flipping is important) amplitude += m_twistLimitRatio * relTwistVel * m_relaxationFactor; btScalar impulseMag = amplitude * m_kTwist; // Clamp the accumulated impulse btScalar temp = m_accTwistLimitImpulse; m_accTwistLimitImpulse = btMax(m_accTwistLimitImpulse + impulseMag, btScalar(0.0) ); impulseMag = m_accTwistLimitImpulse - temp; // btVector3 impulse = m_twistAxis * impulseMag; bodyA.internalApplyImpulse(btVector3(0,0,0), m_rbA.getInvInertiaTensorWorld()*m_twistAxis,impulseMag); bodyB.internalApplyImpulse(btVector3(0,0,0), m_rbB.getInvInertiaTensorWorld()*m_twistAxis,-impulseMag); } } } #else btAssert(0); #endif //__SPU__ } void btConeTwistConstraint::updateRHS(btScalar timeStep) { (void)timeStep; } #ifndef __SPU__ void btConeTwistConstraint::calcAngleInfo() { m_swingCorrection = btScalar(0.); m_twistLimitSign = btScalar(0.); m_solveTwistLimit = false; m_solveSwingLimit = false; btVector3 b1Axis1,b1Axis2,b1Axis3; btVector3 b2Axis1,b2Axis2; b1Axis1 = getRigidBodyA().getCenterOfMassTransform().getBasis() * this->m_rbAFrame.getBasis().getColumn(0); b2Axis1 = getRigidBodyB().getCenterOfMassTransform().getBasis() * this->m_rbBFrame.getBasis().getColumn(0); btScalar swing1=btScalar(0.),swing2 = btScalar(0.); btScalar swx=btScalar(0.),swy = btScalar(0.); btScalar thresh = btScalar(10.); btScalar fact; // Get Frame into world space if (m_swingSpan1 >= btScalar(0.05f)) { b1Axis2 = getRigidBodyA().getCenterOfMassTransform().getBasis() * this->m_rbAFrame.getBasis().getColumn(1); swx = b2Axis1.dot(b1Axis1); swy = b2Axis1.dot(b1Axis2); swing1 = btAtan2Fast(swy, swx); fact = (swy*swy + swx*swx) * thresh * thresh; fact = fact / (fact + btScalar(1.0)); swing1 *= fact; } if (m_swingSpan2 >= btScalar(0.05f)) { b1Axis3 = getRigidBodyA().getCenterOfMassTransform().getBasis() * this->m_rbAFrame.getBasis().getColumn(2); swx = b2Axis1.dot(b1Axis1); swy = b2Axis1.dot(b1Axis3); swing2 = btAtan2Fast(swy, swx); fact = (swy*swy + swx*swx) * thresh * thresh; fact = fact / (fact + btScalar(1.0)); swing2 *= fact; } btScalar RMaxAngle1Sq = 1.0f / (m_swingSpan1*m_swingSpan1); btScalar RMaxAngle2Sq = 1.0f / (m_swingSpan2*m_swingSpan2); btScalar EllipseAngle = btFabs(swing1*swing1)* RMaxAngle1Sq + btFabs(swing2*swing2) * RMaxAngle2Sq; if (EllipseAngle > 1.0f) { m_swingCorrection = EllipseAngle-1.0f; m_solveSwingLimit = true; // Calculate necessary axis & factors m_swingAxis = b2Axis1.cross(b1Axis2* b2Axis1.dot(b1Axis2) + b1Axis3* b2Axis1.dot(b1Axis3)); m_swingAxis.normalize(); btScalar swingAxisSign = (b2Axis1.dot(b1Axis1) >= 0.0f) ? 1.0f : -1.0f; m_swingAxis *= swingAxisSign; } // Twist limits if (m_twistSpan >= btScalar(0.)) { btVector3 b2Axis2 = getRigidBodyB().getCenterOfMassTransform().getBasis() * this->m_rbBFrame.getBasis().getColumn(1); btQuaternion rotationArc = shortestArcQuat(b2Axis1,b1Axis1); btVector3 TwistRef = quatRotate(rotationArc,b2Axis2); btScalar twist = btAtan2Fast( TwistRef.dot(b1Axis3), TwistRef.dot(b1Axis2) ); m_twistAngle = twist; // btScalar lockedFreeFactor = (m_twistSpan > btScalar(0.05f)) ? m_limitSoftness : btScalar(0.); btScalar lockedFreeFactor = (m_twistSpan > btScalar(0.05f)) ? btScalar(1.0f) : btScalar(0.); if (twist <= -m_twistSpan*lockedFreeFactor) { m_twistCorrection = -(twist + m_twistSpan); m_solveTwistLimit = true; m_twistAxis = (b2Axis1 + b1Axis1) * 0.5f; m_twistAxis.normalize(); m_twistAxis *= -1.0f; } else if (twist > m_twistSpan*lockedFreeFactor) { m_twistCorrection = (twist - m_twistSpan); m_solveTwistLimit = true; m_twistAxis = (b2Axis1 + b1Axis1) * 0.5f; m_twistAxis.normalize(); } } } #endif //__SPU__ static btVector3 vTwist(1,0,0); // twist axis in constraint's space void btConeTwistConstraint::calcAngleInfo2(const btTransform& transA, const btTransform& transB, const btMatrix3x3& invInertiaWorldA,const btMatrix3x3& invInertiaWorldB) { m_swingCorrection = btScalar(0.); m_twistLimitSign = btScalar(0.); m_solveTwistLimit = false; m_solveSwingLimit = false; // compute rotation of A wrt B (in constraint space) if (m_bMotorEnabled && (!m_useSolveConstraintObsolete)) { // it is assumed that setMotorTarget() was alredy called // and motor target m_qTarget is within constraint limits // TODO : split rotation to pure swing and pure twist // compute desired transforms in world btTransform trPose(m_qTarget); btTransform trA = transA * m_rbAFrame; btTransform trB = transB * m_rbBFrame; btTransform trDeltaAB = trB * trPose * trA.inverse(); btQuaternion qDeltaAB = trDeltaAB.getRotation(); btVector3 swingAxis = btVector3(qDeltaAB.x(), qDeltaAB.y(), qDeltaAB.z()); float swingAxisLen2 = swingAxis.length2(); if(btFuzzyZero(swingAxisLen2)) { return; } m_swingAxis = swingAxis; m_swingAxis.normalize(); m_swingCorrection = qDeltaAB.getAngle(); if(!btFuzzyZero(m_swingCorrection)) { m_solveSwingLimit = true; } return; } { // compute rotation of A wrt B (in constraint space) btQuaternion qA = transA.getRotation() * m_rbAFrame.getRotation(); btQuaternion qB = transB.getRotation() * m_rbBFrame.getRotation(); btQuaternion qAB = qB.inverse() * qA; // split rotation into cone and twist // (all this is done from B's perspective. Maybe I should be averaging axes...) btVector3 vConeNoTwist = quatRotate(qAB, vTwist); vConeNoTwist.normalize(); btQuaternion qABCone = shortestArcQuat(vTwist, vConeNoTwist); qABCone.normalize(); btQuaternion qABTwist = qABCone.inverse() * qAB; qABTwist.normalize(); if (m_swingSpan1 >= m_fixThresh && m_swingSpan2 >= m_fixThresh) { btScalar swingAngle, swingLimit = 0; btVector3 swingAxis; computeConeLimitInfo(qABCone, swingAngle, swingAxis, swingLimit); if (swingAngle > swingLimit * m_limitSoftness) { m_solveSwingLimit = true; // compute limit ratio: 0->1, where // 0 == beginning of soft limit // 1 == hard/real limit m_swingLimitRatio = 1.f; if (swingAngle < swingLimit && m_limitSoftness < 1.f - SIMD_EPSILON) { m_swingLimitRatio = (swingAngle - swingLimit * m_limitSoftness)/ (swingLimit - swingLimit * m_limitSoftness); } // swing correction tries to get back to soft limit m_swingCorrection = swingAngle - (swingLimit * m_limitSoftness); // adjustment of swing axis (based on ellipse normal) adjustSwingAxisToUseEllipseNormal(swingAxis); // Calculate necessary axis & factors m_swingAxis = quatRotate(qB, -swingAxis); m_twistAxisA.setValue(0,0,0); m_kSwing = btScalar(1.) / (computeAngularImpulseDenominator(m_swingAxis,invInertiaWorldA) + computeAngularImpulseDenominator(m_swingAxis,invInertiaWorldB)); } } else { // you haven't set any limits; // or you're trying to set at least one of the swing limits too small. (if so, do you really want a conetwist constraint?) // anyway, we have either hinge or fixed joint btVector3 ivA = transA.getBasis() * m_rbAFrame.getBasis().getColumn(0); btVector3 jvA = transA.getBasis() * m_rbAFrame.getBasis().getColumn(1); btVector3 kvA = transA.getBasis() * m_rbAFrame.getBasis().getColumn(2); btVector3 ivB = transB.getBasis() * m_rbBFrame.getBasis().getColumn(0); btVector3 target; btScalar x = ivB.dot(ivA); btScalar y = ivB.dot(jvA); btScalar z = ivB.dot(kvA); if((m_swingSpan1 < m_fixThresh) && (m_swingSpan2 < m_fixThresh)) { // fixed. We'll need to add one more row to constraint if((!btFuzzyZero(y)) || (!(btFuzzyZero(z)))) { m_solveSwingLimit = true; m_swingAxis = -ivB.cross(ivA); } } else { if(m_swingSpan1 < m_fixThresh) { // hinge around Y axis // if(!(btFuzzyZero(y))) if((!(btFuzzyZero(x))) || (!(btFuzzyZero(z)))) { m_solveSwingLimit = true; if(m_swingSpan2 >= m_fixThresh) { y = btScalar(0.f); btScalar span2 = btAtan2(z, x); if(span2 > m_swingSpan2) { x = btCos(m_swingSpan2); z = btSin(m_swingSpan2); } else if(span2 < -m_swingSpan2) { x = btCos(m_swingSpan2); z = -btSin(m_swingSpan2); } } } } else { // hinge around Z axis // if(!btFuzzyZero(z)) if((!(btFuzzyZero(x))) || (!(btFuzzyZero(y)))) { m_solveSwingLimit = true; if(m_swingSpan1 >= m_fixThresh) { z = btScalar(0.f); btScalar span1 = btAtan2(y, x); if(span1 > m_swingSpan1) { x = btCos(m_swingSpan1); y = btSin(m_swingSpan1); } else if(span1 < -m_swingSpan1) { x = btCos(m_swingSpan1); y = -btSin(m_swingSpan1); } } } } target[0] = x * ivA[0] + y * jvA[0] + z * kvA[0]; target[1] = x * ivA[1] + y * jvA[1] + z * kvA[1]; target[2] = x * ivA[2] + y * jvA[2] + z * kvA[2]; target.normalize(); m_swingAxis = -ivB.cross(target); m_swingCorrection = m_swingAxis.length(); m_swingAxis.normalize(); } } if (m_twistSpan >= btScalar(0.f)) { btVector3 twistAxis; computeTwistLimitInfo(qABTwist, m_twistAngle, twistAxis); if (m_twistAngle > m_twistSpan*m_limitSoftness) { m_solveTwistLimit = true; m_twistLimitRatio = 1.f; if (m_twistAngle < m_twistSpan && m_limitSoftness < 1.f - SIMD_EPSILON) { m_twistLimitRatio = (m_twistAngle - m_twistSpan * m_limitSoftness)/ (m_twistSpan - m_twistSpan * m_limitSoftness); } // twist correction tries to get back to soft limit m_twistCorrection = m_twistAngle - (m_twistSpan * m_limitSoftness); m_twistAxis = quatRotate(qB, -twistAxis); m_kTwist = btScalar(1.) / (computeAngularImpulseDenominator(m_twistAxis,invInertiaWorldA) + computeAngularImpulseDenominator(m_twistAxis,invInertiaWorldB)); } if (m_solveSwingLimit) m_twistAxisA = quatRotate(qA, -twistAxis); } else { m_twistAngle = btScalar(0.f); } } } // given a cone rotation in constraint space, (pre: twist must already be removed) // this method computes its corresponding swing angle and axis. // more interestingly, it computes the cone/swing limit (angle) for this cone "pose". void btConeTwistConstraint::computeConeLimitInfo(const btQuaternion& qCone, btScalar& swingAngle, // out btVector3& vSwingAxis, // out btScalar& swingLimit) // out { swingAngle = qCone.getAngle(); if (swingAngle > SIMD_EPSILON) { vSwingAxis = btVector3(qCone.x(), qCone.y(), qCone.z()); vSwingAxis.normalize(); #if 0 // non-zero twist?! this should never happen. btAssert(fabs(vSwingAxis.x()) <= SIMD_EPSILON)); #endif // Compute limit for given swing. tricky: // Given a swing axis, we're looking for the intersection with the bounding cone ellipse. // (Since we're dealing with angles, this ellipse is embedded on the surface of a sphere.) // For starters, compute the direction from center to surface of ellipse. // This is just the perpendicular (ie. rotate 2D vector by PI/2) of the swing axis. // (vSwingAxis is the cone rotation (in z,y); change vars and rotate to (x,y) coords.) btScalar xEllipse = vSwingAxis.y(); btScalar yEllipse = -vSwingAxis.z(); // Now, we use the slope of the vector (using x/yEllipse) and find the length // of the line that intersects the ellipse: // x^2 y^2 // --- + --- = 1, where a and b are semi-major axes 2 and 1 respectively (ie. the limits) // a^2 b^2 // Do the math and it should be clear. swingLimit = m_swingSpan1; // if xEllipse == 0, we have a pure vSwingAxis.z rotation: just use swingspan1 if (fabs(xEllipse) > SIMD_EPSILON) { btScalar surfaceSlope2 = (yEllipse*yEllipse)/(xEllipse*xEllipse); btScalar norm = 1 / (m_swingSpan2 * m_swingSpan2); norm += surfaceSlope2 / (m_swingSpan1 * m_swingSpan1); btScalar swingLimit2 = (1 + surfaceSlope2) / norm; swingLimit = sqrt(swingLimit2); } // test! /*swingLimit = m_swingSpan2; if (fabs(vSwingAxis.z()) > SIMD_EPSILON) { btScalar mag_2 = m_swingSpan1*m_swingSpan1 + m_swingSpan2*m_swingSpan2; btScalar sinphi = m_swingSpan2 / sqrt(mag_2); btScalar phi = asin(sinphi); btScalar theta = atan2(fabs(vSwingAxis.y()),fabs(vSwingAxis.z())); btScalar alpha = 3.14159f - theta - phi; btScalar sinalpha = sin(alpha); swingLimit = m_swingSpan1 * sinphi/sinalpha; }*/ } else if (swingAngle < 0) { // this should never happen! #if 0 btAssert(0); #endif } } btVector3 btConeTwistConstraint::GetPointForAngle(btScalar fAngleInRadians, btScalar fLength) const { // compute x/y in ellipse using cone angle (0 -> 2*PI along surface of cone) btScalar xEllipse = btCos(fAngleInRadians); btScalar yEllipse = btSin(fAngleInRadians); // Use the slope of the vector (using x/yEllipse) and find the length // of the line that intersects the ellipse: // x^2 y^2 // --- + --- = 1, where a and b are semi-major axes 2 and 1 respectively (ie. the limits) // a^2 b^2 // Do the math and it should be clear. float swingLimit = m_swingSpan1; // if xEllipse == 0, just use axis b (1) if (fabs(xEllipse) > SIMD_EPSILON) { btScalar surfaceSlope2 = (yEllipse*yEllipse)/(xEllipse*xEllipse); btScalar norm = 1 / (m_swingSpan2 * m_swingSpan2); norm += surfaceSlope2 / (m_swingSpan1 * m_swingSpan1); btScalar swingLimit2 = (1 + surfaceSlope2) / norm; swingLimit = sqrt(swingLimit2); } // convert into point in constraint space: // note: twist is x-axis, swing 1 and 2 are along the z and y axes respectively btVector3 vSwingAxis(0, xEllipse, -yEllipse); btQuaternion qSwing(vSwingAxis, swingLimit); btVector3 vPointInConstraintSpace(fLength,0,0); return quatRotate(qSwing, vPointInConstraintSpace); } // given a twist rotation in constraint space, (pre: cone must already be removed) // this method computes its corresponding angle and axis. void btConeTwistConstraint::computeTwistLimitInfo(const btQuaternion& qTwist, btScalar& twistAngle, // out btVector3& vTwistAxis) // out { btQuaternion qMinTwist = qTwist; twistAngle = qTwist.getAngle(); if (twistAngle > SIMD_PI) // long way around. flip quat and recalculate. { qMinTwist = -(qTwist); twistAngle = qMinTwist.getAngle(); } if (twistAngle < 0) { // this should never happen #if 0 btAssert(0); #endif } vTwistAxis = btVector3(qMinTwist.x(), qMinTwist.y(), qMinTwist.z()); if (twistAngle > SIMD_EPSILON) vTwistAxis.normalize(); } void btConeTwistConstraint::adjustSwingAxisToUseEllipseNormal(btVector3& vSwingAxis) const { // the swing axis is computed as the "twist-free" cone rotation, // but the cone limit is not circular, but elliptical (if swingspan1 != swingspan2). // so, if we're outside the limits, the closest way back inside the cone isn't // along the vector back to the center. better (and more stable) to use the ellipse normal. // convert swing axis to direction from center to surface of ellipse // (ie. rotate 2D vector by PI/2) btScalar y = -vSwingAxis.z(); btScalar z = vSwingAxis.y(); // do the math... if (fabs(z) > SIMD_EPSILON) // avoid division by 0. and we don't need an update if z == 0. { // compute gradient/normal of ellipse surface at current "point" btScalar grad = y/z; grad *= m_swingSpan2 / m_swingSpan1; // adjust y/z to represent normal at point (instead of vector to point) if (y > 0) y = fabs(grad * z); else y = -fabs(grad * z); // convert ellipse direction back to swing axis vSwingAxis.setZ(-y); vSwingAxis.setY( z); vSwingAxis.normalize(); } } void btConeTwistConstraint::setMotorTarget(const btQuaternion &q) { btTransform trACur = m_rbA.getCenterOfMassTransform(); btTransform trBCur = m_rbB.getCenterOfMassTransform(); // btTransform trABCur = trBCur.inverse() * trACur; // btQuaternion qABCur = trABCur.getRotation(); // btTransform trConstraintCur = (trBCur * m_rbBFrame).inverse() * (trACur * m_rbAFrame); //btQuaternion qConstraintCur = trConstraintCur.getRotation(); btQuaternion qConstraint = m_rbBFrame.getRotation().inverse() * q * m_rbAFrame.getRotation(); setMotorTargetInConstraintSpace(qConstraint); } void btConeTwistConstraint::setMotorTargetInConstraintSpace(const btQuaternion &q) { m_qTarget = q; // clamp motor target to within limits { btScalar softness = 1.f;//m_limitSoftness; // split into twist and cone btVector3 vTwisted = quatRotate(m_qTarget, vTwist); btQuaternion qTargetCone = shortestArcQuat(vTwist, vTwisted); qTargetCone.normalize(); btQuaternion qTargetTwist = qTargetCone.inverse() * m_qTarget; qTargetTwist.normalize(); // clamp cone if (m_swingSpan1 >= btScalar(0.05f) && m_swingSpan2 >= btScalar(0.05f)) { btScalar swingAngle, swingLimit; btVector3 swingAxis; computeConeLimitInfo(qTargetCone, swingAngle, swingAxis, swingLimit); if (fabs(swingAngle) > SIMD_EPSILON) { if (swingAngle > swingLimit*softness) swingAngle = swingLimit*softness; else if (swingAngle < -swingLimit*softness) swingAngle = -swingLimit*softness; qTargetCone = btQuaternion(swingAxis, swingAngle); } } // clamp twist if (m_twistSpan >= btScalar(0.05f)) { btScalar twistAngle; btVector3 twistAxis; computeTwistLimitInfo(qTargetTwist, twistAngle, twistAxis); if (fabs(twistAngle) > SIMD_EPSILON) { // eddy todo: limitSoftness used here??? if (twistAngle > m_twistSpan*softness) twistAngle = m_twistSpan*softness; else if (twistAngle < -m_twistSpan*softness) twistAngle = -m_twistSpan*softness; qTargetTwist = btQuaternion(twistAxis, twistAngle); } } m_qTarget = qTargetCone * qTargetTwist; } } ///override the default global value of a parameter (such as ERP or CFM), optionally provide the axis (0..5). ///If no axis is provided, it uses the default axis for this constraint. void btConeTwistConstraint::setParam(int num, btScalar value, int axis) { switch(num) { case BT_CONSTRAINT_ERP : case BT_CONSTRAINT_STOP_ERP : if((axis >= 0) && (axis < 3)) { m_linERP = value; m_flags |= BT_CONETWIST_FLAGS_LIN_ERP; } else { m_biasFactor = value; } break; case BT_CONSTRAINT_CFM : case BT_CONSTRAINT_STOP_CFM : if((axis >= 0) && (axis < 3)) { m_linCFM = value; m_flags |= BT_CONETWIST_FLAGS_LIN_CFM; } else { m_angCFM = value; m_flags |= BT_CONETWIST_FLAGS_ANG_CFM; } break; default: btAssertConstrParams(0); break; } } ///return the local value of parameter btScalar btConeTwistConstraint::getParam(int num, int axis) const { btScalar retVal = 0; switch(num) { case BT_CONSTRAINT_ERP : case BT_CONSTRAINT_STOP_ERP : if((axis >= 0) && (axis < 3)) { btAssertConstrParams(m_flags & BT_CONETWIST_FLAGS_LIN_ERP); retVal = m_linERP; } else if((axis >= 3) && (axis < 6)) { retVal = m_biasFactor; } else { btAssertConstrParams(0); } break; case BT_CONSTRAINT_CFM : case BT_CONSTRAINT_STOP_CFM : if((axis >= 0) && (axis < 3)) { btAssertConstrParams(m_flags & BT_CONETWIST_FLAGS_LIN_CFM); retVal = m_linCFM; } else if((axis >= 3) && (axis < 6)) { btAssertConstrParams(m_flags & BT_CONETWIST_FLAGS_ANG_CFM); retVal = m_angCFM; } else { btAssertConstrParams(0); } break; default : btAssertConstrParams(0); } return retVal; } void btConeTwistConstraint::setFrames(const btTransform & frameA, const btTransform & frameB) { m_rbAFrame = frameA; m_rbBFrame = frameB; buildJacobian(); //calculateTransforms(); }
0
0.963697
1
0.963697
game-dev
MEDIA
0.960938
game-dev
0.990088
1
0.990088
Wanderers-Of-The-Rift/wotr-mod
1,407
src/main/java/com/wanderersoftherift/wotr/world/level/levelgen/processor/input/InputBlockState.java
package com.wanderersoftherift.wotr.world.level.levelgen.processor.input; import com.mojang.datafixers.util.Either; import com.mojang.serialization.Codec; import com.mojang.serialization.MapCodec; import com.wanderersoftherift.wotr.init.WotrRegistries; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; import java.util.function.Function; public abstract class InputBlockState { public static final Codec<InputBlockState> DIRECT_CODEC = Codec .<Block, InputBlockState>either(BuiltInRegistries.BLOCK.byNameCodec(), WotrRegistries.INPUT_BLOCKSTATE_TYPES.byNameCodec() .dispatch(InputBlockState::getCodec, Function.identity())) .xmap(either -> either.map(DefaultInputBlockState::new, Function.identity()), entry -> entry instanceof DefaultInputBlockState defaultState ? Either.<Block, InputBlockState>left(defaultState.getBlock()) : Either.<Block, InputBlockState>right(entry)); public abstract MapCodec<? extends InputBlockState> getCodec(); public abstract boolean matchesBlockstate(BlockState blockState); public abstract boolean matchesBlockstateAssumingBlockEqual(BlockState blockState); public abstract Block block(); }
0
0.827014
1
0.827014
game-dev
MEDIA
0.9299
game-dev
0.731051
1
0.731051
magicmq/pyspigot
7,495
bukkit/src/main/java/dev/magicmq/pyspigot/bukkit/PySpigot.java
/* * Copyright 2025 magicmq * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.magicmq.pyspigot.bukkit; import dev.magicmq.pyspigot.PlatformAdapter; import dev.magicmq.pyspigot.PyCore; import dev.magicmq.pyspigot.bukkit.command.BukkitPluginCommand; import dev.magicmq.pyspigot.bukkit.config.BukkitPluginConfig; import dev.magicmq.pyspigot.bukkit.config.BukkitScriptOptionsConfig; import dev.magicmq.pyspigot.bukkit.manager.command.BukkitCommandManager; import dev.magicmq.pyspigot.bukkit.manager.config.BukkitConfigManager; import dev.magicmq.pyspigot.bukkit.manager.listener.BukkitListenerManager; import dev.magicmq.pyspigot.bukkit.manager.messaging.PluginMessageManager; import dev.magicmq.pyspigot.bukkit.manager.placeholder.PlaceholderManager; import dev.magicmq.pyspigot.bukkit.manager.protocol.ProtocolManager; import dev.magicmq.pyspigot.bukkit.manager.script.BukkitScriptManager; import dev.magicmq.pyspigot.bukkit.manager.task.BukkitTaskManager; import dev.magicmq.pyspigot.config.ScriptOptionsConfig; import dev.magicmq.pyspigot.config.PluginConfig; import dev.magicmq.pyspigot.exception.PluginInitializationException; import dev.magicmq.pyspigot.manager.script.ScriptManager; import net.kyori.adventure.platform.bukkit.BukkitAudiences; import org.bstats.bukkit.Metrics; import org.bstats.charts.SimplePie; import org.bukkit.Bukkit; import org.bukkit.command.PluginCommand; import org.bukkit.command.SimpleCommandMap; import org.bukkit.help.IndexHelpTopic; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.scheduler.BukkitTask; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.file.Path; import java.nio.file.Paths; /** * Entry point of PySpigot for Bukkit servers. */ public class PySpigot extends JavaPlugin implements PlatformAdapter { private static PySpigot instance; private boolean paper; private BukkitAudiences adventure; private Metrics metrics; private BukkitTask versionCheckTask; @Override public void onEnable() { instance = this; try { checkReflection(); } catch (NoSuchMethodException | NoSuchFieldException e) { throw new PluginInitializationException("Error when accessing Bukkit via reflection, PySpigot will not be initialized.", e); } try { Class.forName("com.destroystokyo.paper.ParticleBuilder"); paper = true; } catch (ClassNotFoundException ignored) { paper = false; } PyCore.newInstance(this); PyCore.get().init(); } @Override public void onDisable() { if (PyCore.get() != null) PyCore.get().shutdown(); } @Override public PluginConfig initConfig() { getConfig().options().copyDefaults(true); return new BukkitPluginConfig(); } @Override public ScriptOptionsConfig initScriptOptionsConfig() { return new BukkitScriptOptionsConfig(); } @Override public void initCommands() { getCommand("pyspigot").setExecutor(new BukkitPluginCommand()); } @Override public void initListeners() { Bukkit.getPluginManager().registerEvents(new BukkitListener(), this); } @Override public void initPlatformManagers() { BukkitListenerManager.get(); BukkitCommandManager.get(); BukkitTaskManager.get(); BukkitConfigManager.get(); if (isProtocolLibAvailable()) ProtocolManager.get(); if (isPlaceholderApiAvailable()) PlaceholderManager.get(); PluginMessageManager.get(); BukkitScriptManager.get(); } @Override public void initAdventure() { adventure = BukkitAudiences.create(this); } @Override public void initVersionChecking() { Bukkit.getScheduler().runTaskLater(this, PyCore.get()::compareVersions, 20L); versionCheckTask = Bukkit.getScheduler().runTaskTimerAsynchronously(this, PyCore.get()::fetchSpigotVersion, 864000L, 864000L); } @Override public void setupMetrics() { metrics = new Metrics(this, 18991); metrics.addCustomChart(new SimplePie("all_scripts", () -> { int allScripts = ScriptManager.get().getAllScriptPaths().size() + ScriptManager.get().getAllProjectPaths().size(); return "" + allScripts; })); metrics.addCustomChart(new SimplePie("loaded_scripts", () -> { int loadedScripts = ScriptManager.get().getLoadedScripts().size(); return "" + loadedScripts; })); } @Override public void shutdownMetrics() { if (metrics != null) metrics.shutdown(); } @Override public void shutdownVersionChecking() { if (versionCheckTask != null) versionCheckTask.cancel(); } @Override public Logger getPlatformLogger() { if (paper) return getSLF4JLogger(); else return LoggerFactory.getLogger(getLogger().getName()); } @Override public Path getDataFolderPath() { return Paths.get(getDataFolder().getAbsolutePath()); } @Override public ClassLoader getPluginClassLoader() { return getClassLoader(); } @Override public String getVersion() { return getDescription().getVersion(); } @Override public String getPluginIdentifier() { return "PySpigot"; } @Override public boolean isPacketEventsAvailable() { return Bukkit.getPluginManager().getPlugin("PacketEvents") != null; } /** * Check if ProtocolLib is available on the server. * @return True if ProtocolLib is loaded and enabled, false if otherwise */ public boolean isProtocolLibAvailable() { return Bukkit.getPluginManager().getPlugin("ProtocolLib") != null; } /** * Check if PlacehodlerAPI is available on the server. * @return True if PlaceholderAPI is loaded and enabled, false if otherwise */ public boolean isPlaceholderApiAvailable() { return Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null; } /** * Get the adventure API for the Bukkit platform. * @return The adventure API */ public BukkitAudiences getAdventure() { return adventure; } private void checkReflection() throws NoSuchMethodException, NoSuchFieldException { //Check reflection for commands PluginCommand.class.getDeclaredConstructor(String.class, Plugin.class); Bukkit.getServer().getClass().getDeclaredField("commandMap"); SimpleCommandMap.class.getDeclaredField("knownCommands"); IndexHelpTopic.class.getDeclaredField("allTopics"); } /** * Get the instance of this plugin. * @return The instance */ public static PySpigot get() { return instance; } }
0
0.852979
1
0.852979
game-dev
MEDIA
0.884321
game-dev
0.918414
1
0.918414
LordOfDragons/dragengine
2,412
src/deigde/editors/synthesizer/src/clipboard/seClipboardDataEffect.cpp
/* * MIT License * * Copyright (C) 2024, DragonDreams GmbH (info@dragondreams.ch) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include <math.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include "seClipboardDataEffect.h" #include "../synthesizer/effect/seEffect.h" #include <dragengine/common/exceptions.h> // Class seClipboardDataEffect //////////////////////////////// const char * const seClipboardDataEffect::TYPE_NAME = "effect"; // Constructor, destructor //////////////////////////// seClipboardDataEffect::seClipboardDataEffect( seEffect *effect ) : igdeClipboardData( TYPE_NAME ) { seEffect *copyEffect = NULL; try{ copyEffect = effect->CreateCopy(); pEffects.Add( copyEffect ); copyEffect->FreeReference(); }catch( const deException & ){ if( copyEffect ){ copyEffect->FreeReference(); } throw; } } seClipboardDataEffect::seClipboardDataEffect( const seEffectList &effects ) : igdeClipboardData( TYPE_NAME ) { const int count = effects.GetCount(); seEffect *effect = NULL; int i; try{ for( i=0; i<count; i++ ){ effect = effects.GetAt( i )->CreateCopy(); pEffects.Add( effect ); effect->FreeReference(); effect = NULL; } }catch( const deException & ){ if( effect ){ effect->FreeReference(); } throw; } } seClipboardDataEffect::~seClipboardDataEffect(){ pEffects.RemoveAll(); }
0
0.835316
1
0.835316
game-dev
MEDIA
0.782772
game-dev
0.589784
1
0.589784
StefanJo3107/ASCII-Rendering-Shader-in-Unity
4,700
ShaderLearning/Library/PackageCache/com.unity.probuilder@4.1.2/Editor/EditorCore/StripProBuilderScripts.cs
using UnityEngine; using UnityEditor; using System.Collections; using UnityEngine.ProBuilder; using UnityEditor.ProBuilder; using UnityEngine.ProBuilder.MeshOperations; using EditorUtility = UnityEditor.ProBuilder.EditorUtility; namespace UnityEditor.ProBuilder.Actions { /// <summary> /// Menu items for stripping ProBuilder scripts from GameObjects. /// </summary> /// @TODO MOVE TO ACTIONS sealed class StripProBuilderScripts : Editor { [MenuItem("Tools/" + PreferenceKeys.pluginTitle + "/Actions/Strip All ProBuilder Scripts in Scene")] public static void StripAllScenes() { if (!UnityEditor.EditorUtility.DisplayDialog("Strip ProBuilder Scripts", "This will remove all ProBuilder scripts in the scene. You will no longer be able to edit these objects. There is no undo, please exercise caution!\n\nAre you sure you want to do this?", "Okay", "Cancel")) return; ProBuilderMesh[] all = (ProBuilderMesh[])Resources.FindObjectsOfTypeAll(typeof(ProBuilderMesh)); Strip(all); } [MenuItem("Tools/" + PreferenceKeys.pluginTitle + "/Actions/Strip ProBuilder Scripts in Selection", true, 0)] public static bool VerifyStripSelection() { return InternalUtility.GetComponents<ProBuilderMesh>(Selection.transforms).Length > 0; } [MenuItem("Tools/" + PreferenceKeys.pluginTitle + "/Actions/Strip ProBuilder Scripts in Selection")] public static void StripAllSelected() { if (!UnityEditor.EditorUtility.DisplayDialog("Strip ProBuilder Scripts", "This will remove all ProBuilder scripts on the selected objects. You will no longer be able to edit these objects. There is no undo, please exercise caution!\n\nAre you sure you want to do this?", "Okay", "Cancel")) return; foreach (Transform t in Selection.transforms) { foreach (ProBuilderMesh pb in t.GetComponentsInChildren<ProBuilderMesh>(true)) DoStrip(pb); } } public static void Strip(ProBuilderMesh[] all) { for (int i = 0; i < all.Length; i++) { if (UnityEditor.EditorUtility.DisplayCancelableProgressBar( "Stripping ProBuilder Scripts", "Working over " + all[i].id + ".", ((float)i / all.Length))) break; DoStrip(all[i]); } UnityEditor.EditorUtility.ClearProgressBar(); UnityEditor.EditorUtility.DisplayDialog("Strip ProBuilder Scripts", "Successfully stripped out all ProBuilder components.", "Okay"); ProBuilderEditor.Refresh(); } public static void DoStrip(ProBuilderMesh pb) { try { GameObject go = pb.gameObject; Renderer ren = go.GetComponent<Renderer>(); if (ren != null) EditorUtility.SetSelectionRenderState(ren, EditorSelectedRenderState.Highlight | EditorSelectedRenderState.Wireframe); if (EditorUtility.IsPrefabAsset(go)) return; EditorUtility.SynchronizeWithMeshFilter(pb); if (pb.mesh == null) { DestroyImmediate(pb); if (go.GetComponent<Entity>()) DestroyImmediate(go.GetComponent<Entity>()); return; } string cachedMeshPath; Mesh cachedMesh; // if meshes are assets and the mesh cache is valid don't duplicate the mesh to an instance. if (Experimental.meshesAreAssets && EditorMeshUtility.GetCachedMesh(pb, out cachedMeshPath, out cachedMesh)) { pb.preserveMeshAssetOnDestroy = true; DestroyImmediate(pb); if (go.GetComponent<Entity>()) DestroyImmediate(go.GetComponent<Entity>()); } else { Mesh m = UnityEngine.ProBuilder.MeshUtility.DeepCopy(pb.mesh); DestroyImmediate(pb); if (go.GetComponent<Entity>()) DestroyImmediate(go.GetComponent<Entity>()); go.GetComponent<MeshFilter>().sharedMesh = m; if (go.GetComponent<MeshCollider>()) go.GetComponent<MeshCollider>().sharedMesh = m; } } catch {} } } }
0
0.889653
1
0.889653
game-dev
MEDIA
0.919749
game-dev
0.949231
1
0.949231
deavid/unhaunter
1,228
uncore/src/assets/index.rs
use bevy::{asset::AssetLoader, prelude::*}; /// Allows Bevy to load *.assetidx files which in turn are used to create a list /// of assets available. This is specially useful in WASM where we cannot list /// the contents of a folder. #[derive(Asset, Reflect)] pub struct AssetIdx { pub assets: Vec<String>, } impl AssetIdx { pub fn from_bytes(bytes: Vec<u8>) -> Self { let data = String::from_utf8_lossy(&bytes); let assets: Vec<String> = data .split('\n') .map(|s| s.trim().to_string()) .filter(|s| !s.is_empty()) .collect(); Self { assets } } } #[derive(Default)] pub struct AssetIdxLoader; impl AssetLoader for AssetIdxLoader { type Asset = AssetIdx; type Settings = (); type Error = std::io::Error; async fn load( &self, reader: &mut dyn bevy::asset::io::Reader, _settings: &Self::Settings, _load_context: &mut bevy::asset::LoadContext<'_>, ) -> Result<Self::Asset, Self::Error> { let mut bytes = Vec::new(); reader.read_to_end(&mut bytes).await?; Ok(AssetIdx::from_bytes(bytes)) } fn extensions(&self) -> &[&str] { &["assetidx"] } }
0
0.938119
1
0.938119
game-dev
MEDIA
0.750309
game-dev
0.906903
1
0.906903
CGandGameEngineLearner/IronAngel
1,484
Assets/Behavior Designer/Runtime/Tasks/Unity/ParticleSystem/SetStartColor.cs
using UnityEngine; namespace BehaviorDesigner.Runtime.Tasks.Unity.UnityParticleSystem { [TaskCategory("Unity/ParticleSystem")] [TaskDescription("Sets the start color of the Particle System.")] public class SetStartColor : Action { [Tooltip("The GameObject that the task operates on. If null the task GameObject is used.")] public SharedGameObject targetGameObject; [Tooltip("The start color of the ParticleSystem")] public SharedColor startColor; private ParticleSystem particleSystem; private GameObject prevGameObject; public override void OnStart() { var currentGameObject = GetDefaultGameObject(targetGameObject.Value); if (currentGameObject != prevGameObject) { particleSystem = currentGameObject.GetComponent<ParticleSystem>(); prevGameObject = currentGameObject; } } public override TaskStatus OnUpdate() { if (particleSystem == null) { Debug.LogWarning("ParticleSystem is null"); return TaskStatus.Failure; } ParticleSystem.MainModule mainParticleSystem = particleSystem.main; mainParticleSystem.startColor = startColor.Value; return TaskStatus.Success; } public override void OnReset() { targetGameObject = null; startColor = Color.white; } } }
0
0.658594
1
0.658594
game-dev
MEDIA
0.948167
game-dev
0.784665
1
0.784665
naninovel/docs
10,580
docs/guide/custom-configuration.md
# Custom Configuration Configuration objects are used to initialize and configure services and other engine systems. By default, configuration objects are serialized as [scriptable object](https://docs.unity3d.com/Manual/class-ScriptableObject.html) assets and stored at `NaninovelData/Resources/Naninovel/Configuration` project directory. The assets are automatically generated when opening corresponding configuration menus (`Naninovel -> Configuration`) in the Unity editor for the first time. To access configuration objects via C# use `Engine.GetConfiguration<T>()` static method, where `T` is type of the configuration object you wish to access. For example, the following example demonstrates how to access [audio configuration](/guide/configuration#audio) object: ```csharp var audioConfig = Engine.GetConfiguration<AudioConfiguration>(); ``` ::: info NOTE The engine initialization procedure is asynchronous, so even when automatic initialization is enabled, engine APIs (eg, `GetConfiguration` method) may not be available right after Unity loads a scene (eg, in `Awake`, `Start` and `OnEnable` [MonoBehaviour](https://docs.unity3d.com/ScriptReference/MonoBehaviour.html) methods); see [accessing engine API](/guide/integration-options#accessing-engine-api) guide for more info. ::: While `Engine.GetConfiguration` method can only be used when the engine is initialized, as it requires a [configuration provider](/guide/custom-configuration#configuration-provider) object, which is specified when initializing the engine to allow custom serving scenarios at runtime, it's possible to access a configuration asset via default provider even when the engine is not initialized with `ProjectConfigurationProvider`, eg: ```csharp var config = ProjectConfigurationProvider.LoadOrDefault<AudioConfiguration>(); ``` While the configuration properties are meant to be changed via editor menus, it's still possible to modify them at runtime. Be aware, that the objects returned by default project provider are the actual assets stored in the project; if you modify them, the changes will persist through play mode sessions. This is in contrast to the configuration objects provided with `Engine.GetConfiguration` method, which are instances and won't mutate the original assets. Below is an example on changing `ReferenceResolution` property of camera configuration object right after the engine is initialized: ```csharp using Naninovel; using UnityEngine; public static class ModifyConfigAtRuntime { [RuntimeInitializeOnLoadMethod] private static void ModifyConfig () { if (Engine.Initialized) OnInitializationFinished(); else Engine.OnInitializationFinished += OnInitializationFinished; void OnInitializationFinished () { Engine.OnInitializationFinished -= OnInitializationFinished; var cameraConfig = Engine.GetConfiguration<CameraConfiguration>(); cameraConfig.ReferenceResolution = new Vector2Int(3840, 2160); } } } ``` ::: info NOTE Naninovel doesn't expect configurations to change while the engine is initialized, so you may need to apply the modifications before initializing the engine with either `ProjectConfigurationProvider` or a [custom provider](/guide/custom-configuration#configuration-provider) in order for some changes to take effect. ::: ## Adding Configuration To add a new custom configuration, create a C# class and inherit it from `Configuration`. ```csharp [EditInProjectSettings] public class MyCustomConfiguration : Configuration { [Header("My Custom Header 1")] [Tooltip("Tooltip for my custom string.")] public string MyCustomString = "Default value"; [Range(0, 100), Tooltip("Tooltip for my custom float.")] public float MyCustomFloat = 10; [Header("My Custom Header 2")] public int[] MyCustomArray; } ``` Notice the `EditInProjectSettings` attribute: an associated editor menu is automatically added to the project settings when the attribute is applied, where you can modify serializable properties of you custom configuration asset just like in all the built-in menus. ![](https://i.gyazo.com/c1163bba83f5d2b6286b100e837bca40.png) To access your custom configuration via C# use the same API as for the built-in assets: ```csharp var myConfig = Engine.GetConfiguration<MyCustomConfiguration>(); ``` ::: tip EXAMPLE Another example of adding a custom configuration menu to set up an inventory system can be found in the [inventory sample](/guide/samples#inventory). Specifically, the custom configuration is implemented in `Scripts/Runtime/Inventory/InventoryConfiguration.cs`. ::: To customize editor behaviour of your custom configuration (when it's drawn in the Naninovel's project settings), create a class under an editor script and inherit it from `ConfigurationSettings<T>`, where `T` is the type of your custom configuration. You can use built-in settings editor scripts stored at `Naninovel/Editor/Settings` package folder for reference when building your own editors. ## Overriding Built-in Editors It's possible to override the built-in configuration editors (Naninovel's project settings menus) by applying `OverrideSettings` attribute to an editor class inherited from `ConfigurationSettings<T>` (or any of its derivatives), where `T` is the type of the configuration. Make sure to store the custom editor scripts under "Editor" folder to make them included to the editor assembly. Below is an example on overriding the built-in character manager configuration editor. The new editor is inherited from the built-in one and will additionally insert a label under `Shared Poses` field with the total number of shared poses. ```csharp [OverrideSettings] public class CustomCharacterSettings : CharactersSettings { protected override Dictionary<string, Action<SerializedProperty>> OverrideConfigurationDrawers () { var drawers = base.OverrideConfigurationDrawers(); drawers[nameof(CharactersConfiguration.SharedPoses)] = property => { ActorPosesEditor.Draw(property); EditorGUILayout.LabelField( $"Number of shared poses is {property.arraySize}."); }; return drawers; } } ``` Given the above editor, characters configuration will now draw as follows: ![](https://i.gyazo.com/5555e8c3eb33c3783bef8ef852a7e765.png) It's also possible to override built-in actor metadata editors. Below will insert a label under `Message Color` field of the inspected actor with the name of that color. ```csharp [OverrideSettings] public class CustomCharacterSettings : CharactersSettings { protected override MetadataEditor<ICharacterActor, CharacterMetadata> MetadataEditor { get; } = new MetaEditor(); private class MetaEditor : CharacterMetadataEditor { protected override Action<SerializedProperty> GetCustomDrawer (string propertyName) { if (propertyName == nameof(CharacterMetadata.MessageColor)) return property => { EditorGUILayout.PropertyField(property); EditorGUILayout.LabelField($"Message color of " + "'{Metadata.DisplayName}' is '{property.colorValue}'."); }; return base.GetCustomDrawer(propertyName); } } } ``` — will result in: ![](https://i.gyazo.com/60abbf6b773b6c66cf138ac40882b1c1.png) ## Configuration Provider It's possible to change the way configuration objects are served at runtime. For example, instead of static project assets, you can read the configuration from JSON files stored on a remote host. To specify a custom configuration serving scenario, create a C# class and implement `IConfigurationProvider` interface. The interface has just one method, that expects a `Type` argument and returns a `Configuration` object. It's up to you on how to construct and populate requested configuration objects, just make sure type of the returned object is equal to the requested one. Below is an example of a custom provider implementation, that just returns default configuration objects: ```csharp public class CustomConfigurationProvider : IConfigurationProvider { public Configuration GetConfiguration (System.Type type) { var defaultAsset = ScriptableObject.CreateInstance(type); return defaultAsset as Configuration; } } ``` Another example on overriding project characters configuration to inject metadata at runtime: ```csharp public class CustomConfigurationProvider : ProjectConfigurationProvider { public override Configuration GetConfiguration (System.Type type) { // Return project configs as-is for everything but characters. if (type != typeof(CharactersConfiguration)) return base.GetConfiguration(type); // Inject (or override) metadata of the characters. // The actual data can be retrieved via external sources at runtime. var charsConfig = (CharactersConfiguration)base.GetConfiguration(type); charsConfig.Metadata["NewCustomChar"] = new CharacterMetadata { Implementation = typeof(NarratorCharacter).AssemblyQualifiedName, DisplayName = "Custom Narrator", UseCharacterColor = true, MessageColor = Color.cyan, // etc... }; // Return our modified characters config. return charsConfig; } } ``` Once the custom configuration provider is ready, you have to make the engine use it instead of the built-in one by creating a custom engine initialization script. By default, the engine is initialized via `Naninovel/Runtime/Engine/RuntimeInitializer.cs`; feel free to use it as a reference when creating your own initialization script. Alternatively, if your goal is just to use a custom configuration provider, but keep the default engine initialization routine, consider using `RuntimeInitializer.Initialize(IConfigurationProvider)` static method, which accepts an optional argument for configuration provider: ```csharp public class CustomInitializer { [RuntimeInitializeOnLoadMethod] private static void InitializeWithCustomProvider () { var customProvider = new CustomConfigurationProvider(); RuntimeInitializer.Initialize(customProvider).Forget(); } } ``` No matter which way you choose to initialize the engine, don't forget to disable `Initialize On Application Load` option in the engine configuration menu to disable default initialization procedure.
0
0.746721
1
0.746721
game-dev
MEDIA
0.792819
game-dev
0.594671
1
0.594671
latte-soft/builtinplugins
1,536
src/BuiltInPlugins/Toolbox/Core/Util/createSignal.luau
local function _(v0, v1, v2) local v3 = {}; for v4, v5 in pairs(v0) do v3[v4] = v5; end; v3[v1] = v2; return v3; end; local function _(v7, v8) local v9 = {}; for v10, v11 in pairs(v7) do if v10 ~= v8 then v9[v10] = v11; end; end; return v9; end; return function() local v13 = {}; return { subscribe = function(_, v15) assert(typeof(v15) == "function", "Can only subscribe to signals with a function."); local v16 = { callback = v15, disconnected = false }; local l_v13_0 = v13; local v18 = {}; for v19, v20 in pairs(l_v13_0) do v18[v19] = v20; end; v18[v15] = v16; v13 = v18; return function() assert(not v16.disconnected, "Listeners can only be disconnected once."); v16.disconnected = true; local l_v13_1 = v13; local l_v15_0 = v15; local v23 = {}; for v24, v25 in pairs(l_v13_1) do if v24 ~= l_v15_0 then v23[v24] = v25; end; end; v13 = v23; end; end, fire = function(_, ...) for v27, v28 in pairs(v13) do if not v28.disconnected then v27(...); end; end; end }; end;
0
0.794774
1
0.794774
game-dev
MEDIA
0.647687
game-dev
0.868017
1
0.868017
AdiAddons/AdiBags
12,530
core/DefaultFilters.lua
--[[ AdiBags - Adirelle's bag addon. Copyright 2010-2021 Adirelle (adirelle@gmail.com) All rights reserved. This file is part of AdiBags. AdiBags 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. AdiBags 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 AdiBags. If not, see <http://www.gnu.org/licenses/>. --]] local addonName, addon = ... function addon:SetupDefaultFilters() -- Globals: GetEquipmentSetLocations --<GLOBALS local _G = _G local BANK_CONTAINER = _G.BANK_CONTAINER or ( Enum.BagIndex and Enum.BagIndex.Bank ) or -1 local BANK_CONTAINER_INVENTORY_OFFSET = _G.BANK_CONTAINER_INVENTORY_OFFSET local EquipmentManager_UnpackLocation = _G.EquipmentManager_UnpackLocation local format = _G.format local GetContainerItemQuestInfo = C_Container and _G.C_Container.GetContainerItemQuestInfo or _G.GetContainerItemQuestInfo local GetEquipmentSetInfo = _G.C_EquipmentSet.GetEquipmentSetInfo local GetItemIDs = _G.C_EquipmentSet.GetItemIDs local GetEquipmentSetIDs = _G.C_EquipmentSet.GetEquipmentSetIDs local GetItemLocations = _G.C_EquipmentSet.GetItemLocations local GetItemClassInfo = _G.C_Item.GetItemClassInfo local GetItemSubClassInfo = _G.C_Item.GetItemSubClassInfo local pairs = _G.pairs local wipe = _G.wipe --GLOBALS> local L = addon.L -- Make some strings local to speed things local CONSUMMABLE = GetItemClassInfo(_G.Enum.ItemClass.Consumable) local GEM = GetItemClassInfo(_G.Enum.ItemClass.Gem) local GLYPH = GetItemClassInfo(_G.Enum.ItemClass.Glyph) local JUNK = GetItemSubClassInfo(_G.Enum.ItemClass.Miscellaneous, 0) local MISCELLANEOUS = GetItemClassInfo(_G.Enum.ItemClass.Miscellaneous) local QUEST = GetItemClassInfo(_G.Enum.ItemClass.Questitem) local RECIPE = GetItemClassInfo(_G.Enum.ItemClass.Recipe) local TRADE_GOODS = GetItemClassInfo(_G.Enum.ItemClass.Tradegoods) local WEAPON = GetItemClassInfo(_G.Enum.ItemClass.Weapon) local ARMOR = GetItemClassInfo(_G.Enum.ItemClass.Armor) local JEWELRY = L['Jewelry'] local EQUIPMENT = L['Equipment'] local AMMUNITION = L['Ammunition'] -- Define global ordering self:SetCategoryOrders{ [QUEST] = 30, [TRADE_GOODS] = 20, [EQUIPMENT] = 10, [CONSUMMABLE] = -10, [MISCELLANEOUS] = -20, [AMMUNITION] = -30, [JUNK] = -40, } -- [90] Parts of an equipment set if addon.isRetail or addon.isWrath or addon.isCata then do local setFilter = addon:RegisterFilter("ItemSets", 90, "ABEvent-1.0", "ABBucket-1.0") setFilter.uiName = L['Gear manager item sets'] setFilter.uiDesc = L['Put items belonging to one or more sets of the built-in gear manager in specific sections.'] function setFilter:OnInitialize() self.db = addon.db:RegisterNamespace('ItemSets', { profile = { oneSectionPerSet = true }, char = { mergedSets = { ['*'] = false } }, }) self.names = {} self.slots = {} end function setFilter:OnEnable() self:RegisterEvent('EQUIPMENT_SETS_CHANGED') self:RegisterMessage("AdiBags_PreFilter") self:RegisterMessage("AdiBags_PreContentUpdate") self:UpdateNames() end local GetSlotId = addon.GetSlotId function setFilter:UpdateNames() self:Debug('Updating names') wipe(self.names) for _, equipmentSetID in pairs(GetEquipmentSetIDs()) do local name = GetEquipmentSetInfo(equipmentSetID) self.names[name] = name end self.dirty = true end function setFilter:UpdateSlots() self:Debug('Updating slots') wipe(self.slots) local missing = false for _, equipmentSetID in pairs(GetEquipmentSetIDs()) do local name = GetEquipmentSetInfo(equipmentSetID) local itemIDs = GetItemIDs(equipmentSetID) local locations = GetItemLocations(equipmentSetID) if itemIDs and locations then for invId, location in pairs(locations) do if location ~= 0 and location ~= 1 and itemIDs[invId] ~= 0 then local player, bank, bags, voidstorage, slot, container local slotId if addon.isWrath or addon.isCata then player, bank, bags, slot, container = EquipmentManager_UnpackLocation(location) else player, bank, bags, voidstorage, slot, container = EquipmentManager_UnpackLocation(location) end if bags and slot and container then slotId = GetSlotId(container, slot) elseif bank and slot then slotId = GetSlotId(BANK_CONTAINER, slot - BANK_CONTAINER_INVENTORY_OFFSET) elseif not (player or voidstorage) or not slot then missing = true end if slotId and not self.slots[slotId] then self.slots[slotId] = name end end end else missing = true end end self.dirty = not missing end function setFilter:EQUIPMENT_SETS_CHANGED(event) self:UpdateNames() self:SendMessage('AdiBags_FiltersChanged', true) end function setFilter:AdiBags_PreContentUpdate(event) self.dirty = true end function setFilter:AdiBags_PreFilter(event) if self.dirty then self:UpdateSlots() end end local SETS, SET_NAME = L['Sets'], L["Set: %s"] function setFilter:Filter(slotData) local name = self.slots[slotData.slotId] if name then if not self.db.profile.oneSectionPerSet or self.db.char.mergedSets[name] then return SETS, EQUIPMENT else return format(SET_NAME, name), EQUIPMENT end end end function setFilter:GetOptions() return { oneSectionPerSet = { name = L['One section per set'], desc = L['Check this to display one individual section per set. If this is disabled, there will be one big "Sets" section.'], type = 'toggle', order = 10, }, mergedSets = { name = L['Merged sets'], desc = L['Check sets that should be merged into a unique "Sets" section. This is obviously a per-character setting.'], type = 'multiselect', order = 20, values = self.names, get = function(info, name) return self.db.char.mergedSets[name] end, set = function(info, name, value) self.db.char.mergedSets[name] = value self:SendMessage('AdiBags_FiltersChanged') end, disabled = function() return not self.db.profile.oneSectionPerSet end, }, }, addon:GetOptionHandler(self, true) end end end -- [75] Quest Items do local questItemFilter = addon:RegisterFilter('Quest', 75, function(self, slotData) if slotData.class == QUEST or slotData.subclass == QUEST then return QUEST else if addon.isRetail or addon.isWrath or addon.isCata then local isQuestItem, questId = addon:GetContainerItemQuestInfo(slotData.bag, slotData.slot) return (questId or isQuestItem) and QUEST else return false end end end) questItemFilter.uiName = L['Quest Items'] questItemFilter.uiDesc = L['Put quest-related items in their own section.'] end -- [60] Equipment do local equipCategories = { INVTYPE_2HWEAPON = WEAPON, INVTYPE_AMMO = MISCELLANEOUS, INVTYPE_BAG = MISCELLANEOUS, INVTYPE_BODY = MISCELLANEOUS, INVTYPE_CHEST = ARMOR, INVTYPE_CLOAK = ARMOR, INVTYPE_FEET = ARMOR, INVTYPE_FINGER = JEWELRY, INVTYPE_HAND = ARMOR, INVTYPE_HEAD = ARMOR, INVTYPE_HOLDABLE = WEAPON, INVTYPE_LEGS = ARMOR, INVTYPE_NECK = JEWELRY, INVTYPE_QUIVER = MISCELLANEOUS, INVTYPE_RANGED = WEAPON, INVTYPE_RANGEDRIGHT = WEAPON, INVTYPE_RELIC = JEWELRY, INVTYPE_ROBE = ARMOR, INVTYPE_SHIELD = WEAPON, INVTYPE_SHOULDER = ARMOR, INVTYPE_TABARD = MISCELLANEOUS, INVTYPE_THROWN = WEAPON, INVTYPE_TRINKET = JEWELRY, INVTYPE_WAIST = ARMOR, INVTYPE_WEAPON = WEAPON, INVTYPE_WEAPONMAINHAND = WEAPON, INVTYPE_WEAPONMAINHAND_PET = WEAPON, INVTYPE_WEAPONOFFHAND = WEAPON, INVTYPE_WRIST = ARMOR, } local equipmentFilter = addon:RegisterFilter('Equipment', 60, function(self, slotData) local equipSlot = slotData.equipSlot if equipSlot and equipSlot ~= "" and equipSlot ~= "INVTYPE_NON_EQUIP_IGNORE" then local rule = self.db.profile.dispatchRule local category if rule == 'category' then category = equipCategories[equipSlot] or _G[equipSlot] elseif rule == 'slot' then category = _G[equipSlot] end if category == ARMOR and self.db.profile.armorTypes and slotData.subclass then category = slotData.subclass end return category or EQUIPMENT, EQUIPMENT end end) equipmentFilter.uiName = EQUIPMENT equipmentFilter.uiDesc = L['Put any item that can be equipped (including bags) into the "Equipment" section.'] function equipmentFilter:OnInitialize() self.db = addon.db:RegisterNamespace('Equipment', { profile = { dispatchRule = 'category', armorTypes = false } }) end function equipmentFilter:GetOptions() return { dispatchRule = { name = L['Section setup'], desc = L['Select the sections in which the items should be dispatched.'], type = 'select', width = 'double', order = 10, values = { one = L['Only one section.'], category = L['Four general sections.'], slot = L['One section per item slot.'], }, }, armorTypes = { name = L['Split armors by types'], desc = L['Check this so armors are dispatched in four sections by type.'], type = 'toggle', order = 20, disabled = function() return self.db.profile.dispatchRule ~= 'category' end, }, }, addon:GetOptionHandler(self, true) end end -- [10] Item classes do local itemCat = addon:RegisterFilter('ItemCategory', 10) itemCat.uiName = L['Item category'] itemCat.uiDesc = L['Put items in sections depending on their first-level category at the Auction House.'] ..'\n|cffff7700'..L['Please note this filter matchs every item. Any filter with lower priority than this one will have no effect.']..'|r' function itemCat:OnInitialize(slotData) self.db = addon.db:RegisterNamespace(self.moduleName, { profile = { splitBySubclass = { false }, mergeGems = true, mergeGlyphs = true, splitExpansion = false, } }) end function itemCat:GetOptions() local values = { [TRADE_GOODS] = TRADE_GOODS, [CONSUMMABLE] = CONSUMMABLE, [MISCELLANEOUS] = MISCELLANEOUS, [RECIPE] = RECIPE, } if addon.isBCC then values[GEM] = GEM elseif not addon.isClassic then values[GEM] = GEM values[GLYPH] = GLYPH end return { splitBySubclass = { name = L['Split by subcategories'], desc = L['Select which first-level categories should be split by sub-categories.'], type = 'multiselect', order = 10, values = values }, mergeGems = { name = L['Gems are trade/crafting goods'], desc = L['Consider gems as a subcategory of trade/crafting goods'], type = 'toggle', width = 'double', order = 20, }, mergeGlyphs = { name = L['Glyphs are trade/crafting goods'], desc = L['Consider glyphs as a subcategory of trade/crafting goods'], type = 'toggle', width = 'double', order = 30, }, splitExpansion = { name = L['Split trade/crafting goods by expansion'], desc = L['Split trade/crafting goods by expansion'], type = 'toggle', width = 'double', order = 40, }, }, addon:GetOptionHandler(self, true) end function itemCat:Filter(slotData) local class, subclass = slotData.class, slotData.subclass if class == GEM and self.db.profile.mergeGems then class, subclass = TRADE_GOODS, class elseif class == GLYPH and self.db.profile.mergeGlyphs then class, subclass = TRADE_GOODS, class end --TODO: Implement an option to override `subclass` with professions from our `addon.TRADESKILL_MAP`? local reagentData = addon.ItemDatabase:ReagentData(slotData) if self.db.profile.splitBySubclass[class] then return (self.db.profile.splitExpansion and reagentData and subclass..": "..reagentData.expacName) or subclass, class else return (self.db.profile.splitExpansion and reagentData and class..": "..reagentData.expacName) or class end end end end
0
0.931581
1
0.931581
game-dev
MEDIA
0.983363
game-dev
0.986498
1
0.986498
Minestom/VanillaReimplementation
1,190
datapack-loading/src/main/java/net/minestom/vanilla/datapack/number/IntNumberProviders.java
package net.minestom.vanilla.datapack.number; import java.util.random.RandomGenerator; interface IntNumberProviders { record Constant(int value) implements NumberProvider.Int { @Override public int apply(NumberProvider.Context context) { return value; } } record Uniform(NumberProvider.Int min, NumberProvider.Int max) implements NumberProvider.Int { @Override public int apply(NumberProvider.Context context) { int min = this.min.apply(context); int max = this.max.apply(context); return context.random().nextInt(min, max); } } record Binomial(NumberProvider.Int n, NumberProvider.Double p) implements NumberProvider.Int { @Override public int apply(NumberProvider.Context context) { int n = this.n.apply(context); double p = this.p.apply(context); RandomGenerator random = context.random(); double sum = 0; for (int i = 0; i < n; i++) { if (random.nextDouble() < p) { sum++; } } return (int) sum; } } }
0
0.902252
1
0.902252
game-dev
MEDIA
0.42655
game-dev
0.859902
1
0.859902
kinggath/WorkshopFramework
18,924
Scripts/Source/User/WorkshopNPCScript.psc
Scriptname WorkshopNPCScript extends Actor Conditional {script for all NPCs that can be assigned to a workshop} WorkshopParentScript Property WorkshopParent Auto Const Mandatory Group WorkerData bool Property bCommandable = false auto Conditional { TRUE = commandable by player - can be ordered to different work objects (default) FALSE = player can't command although will still count as worker if given default work } bool Property bAllowCaravan = false auto Conditional { TRUE = can be assigned to caravan duty } bool Property bAllowMove = false auto Conditional { TRUE = can be moved to different settlements } ; worker flag - used by package conditions etc. bool Property bIsWorker = false auto Conditional { worker flag - used by package conditions set to TRUE if this NPC is a worker of any kind } bool Property bWork24Hours = false auto Conditional { set to TRUE to have someone work 24 hours } ; guard flag - used by package conditions bool Property bIsGuard = false auto Conditional Hidden { set to TRUE if this NPC is a "guard" - assigned to Safety work objects like guard posts etc. } ; scavenger flag - used by package conditions bool Property bIsScavenger = false auto Conditional Hidden { set to TRUE if this NPC is a scavenger - assigned to Scavenge work objects } ActorValue Property assignedMultiResource auto { if NONE this worker is assigned a single object to work on otherwise, this is the rating keyword (food, safety, etc.) of the type of resource this NPC can work on } float Property multiResourceProduction = 0.0 auto Hidden Conditional { if assignedMultiResource is set, this tracks how much production this NPC is assigned to } bool Property bIsSynth = false auto conditional hidden { set to TRUE if this NPC has been tagged as a synth - gives appropriate death item } endGroup bool Property bWorkshopStatusOn = true auto conditional hidden { set to false when temporarily turning off - but saving - workshop NPC status, e.g. for companions } ; if workshop status turned off, save these flags here so they can be restored later bool bSavedAllowMove bool bSavedAllowCaravan bool bSavedCommandable ; used by ResetWorkshop to indicate which objects it has finished with bool Property bResetDone = false auto hidden ; the brahmin assigned to me if I'm a caravan actor Actor Property myBrahmin auto bool Property bNewSettler = false auto Conditional { set to true when new settlers are created - set back to false after player "meets" them } bool Property bCountsForPopulation = true auto Conditional { set to false for things like brahmin which don't count for total population } bool Property bApplyWorkshopOwnerFaction = true auto conditional { set to false for NPCs that should not pick up the owner faction of their assigned workshop - e.g. companions } LocationRefType Property CustomBossLocRefType Auto Const { Patch 1.4: custom loc ref type to use for this actor when assigning to workshop } ; WSFW ; Override default Boss reftype and CustomBossLocRefType const property LocationRefType Property OverrideBossLocRefType = None Auto Hidden Form Property WSFWOverwriteCheck = None Auto Hidden { Used by Workshop Framework to verify if this script has been overwritten } group VendorData int Property specialVendorType = -1 auto const { based on index from WorkshopParent VendorTypes - set for NPCs who have special vendor abilities } int Property specialVendorMinLevel = 2 auto const { if a special vendor, what level does the vendor object have to be to allow special ability? } Container Property specialVendorContainerBase auto const { base object of special vendor container to link to when special ability is allowed } ObjectReference Property specialVendorContainerRef auto hidden { reference (created by script) to link to when special ability is allowed } ObjectReference Property specialVendorContainerRefUnique auto { reference to link to when special ability is allowed } endGroup ; workshop that this NPC is assigned to (also mirrored by the actor value - but need a way to say "no workshop" since the default actor value is 0) int workshopID = -1 conditional ; for dropping out of command state int iSelfActivationCount = 0 ; Adding handlers for our exter WorkshopFunctions global functions to access this var Function SetSelfActivationCount(Int aiCount) iSelfActivationCount = aiCount EndFunction Int Function GetSelfActivationCount() return iSelfActivationCount EndFunction ;--------------------------------------------- ; Added by UFO4P 2.0 for Bug #21578 ;--------------------------------------------- bool UFO4P_WaitingForNPCRecovering = false ;--------------------------------------------- ; return the workshopID of this actor int function GetWorkshopID() return workshopID endFunction function SetWorkshopID(int newWorkshopID) workshopID = newWorkshopID SetValue(WorkshopParent.workshopIDActorValue, newWorkshopID) ; put script in correct state (we only care about events if assigned to a workshop) if newWorkshopID > -1 gotoState("assigned") else gotoState("unassigned") endif endFunction function UpdatePlayerOwnership(WorkshopScript workshopRef = NONE) ; get workshop if not passed in if workshopRef == NONE workshopRef = WorkshopParent.GetWorkshop(workshopID) endif ;WorkshopParent.wsTrace(self + " UpdatePlayerOwnership for workshop " + workshopRef + ": OwnedByPlayer=" + workshopRef.OwnedByPlayer) if workshopRef ; set player ownership actor value SetValue(WorkshopParent.WorkshopPlayerOwnership, workshopRef.OwnedByPlayer as int) endif endFunction ; return workshopID of caravan destination (if any) int function GetCaravanDestinationID() return GetValue(WorkshopParent.WorkshopCaravanDestination) as int endFunction bool function IsWounded() ; ;;debug.trace(GetValue(WorkshopParent.WorkshopActorWounded) as bool) return GetValue(WorkshopParent.WorkshopActorWounded) as bool endFunction function SetWounded(bool bIsWounded) SetValue(WorkshopParent.WorkshopActorWounded, bIsWounded as int) ; am I a caravan actor? int foundIndex = WorkshopParent.CaravanActorAliases.Find(self) if foundIndex > -1 WorkshopParent.TurnOnCaravanActor(self, bIsWounded == false) endif endFunction function SetWorker(bool isWorker) bIsWorker = isWorker if !isWorker bIsGuard = false bIsScavenger = false endif endFunction function SetScavenger(bool isScavenger) bIsScavenger = isScavenger endFunction function SetSynth(bool isSynth) ;WorkshopParent.wsTrace(self + " SetSynth " + isSynth) bIsSynth = isSynth SetValue(WorkshopParent.WorkshopRatings[WorkshopParent.WorkshopRatingPopulationSynths].resourceValue, (isSynth == true) as float) ; if created and assigned to a workshop, set ref type if IsCreated() && workshopID > -1 WorkshopScript workshopRef = WorkshopParent.GetWorkshop(GetWorkshopID()) if workshopRef.myLocation if isSynth SetLocRefType(workshopRef.myLocation, WorkshopParent.WorkshopSynthRefType) ClearFromOldLocations() ; 101931: make sure location data is correct else ; change back to Boss SetAsBoss(workshopRef.myLocation) ; WSFW 2.3.5 switched this to use the SetAsBoss function so custom ref types are used endif endif endif endFunction function SetMultiResource(ActorValue resourceValue) ;WorkshopParent.wstrace(self + " SetMultiResource: resourceValue=" + resourceValue) assignedMultiResource = resourceValue if assignedMultiResource == WorkshopParent.WorkshopRatings[WorkshopParent.WorkshopRatingSafety].resourceValue bIsGuard = true else bIsGuard = false endif if !assignedMultiResource ; clear production if no longer assigned to a multiresource multiResourceProduction = 0.0 endif endFunction function AddMultiResourceProduction(float newProduction) multiResourceProduction += newProduction endFunction ; Patch 1.4 - custom boss loc ref type function SetAsBoss(Location newLocation) if( ! IsCreated()) return endif if(OverrideBossLocRefType) ; WSFW 2.3.5 SetLocRefType(newLocation, OverrideBossLocRefType) elseif(CustomBossLocRefType) SetLocRefType(newLocation, CustomBossLocRefType) else SetLocRefType(newLocation, WorkshopParent.Boss) endif ClearFromOldLocations() ; 101931: make sure location data is correct endFunction auto state unassigned ; default state Event OnInit() WSFWOverwriteCheck = Game.GetFormFromFile(0x00000F99, "WorkshopFramework.esm") ;UFO4P 2.0.4 Bug #24437: added this check: if IsBoundGameObjectAvailable() == false return endif ; if I'm a follower, register for companion change events ;UFO4P 1.0.3 Bug #20575: 'is' replaced with 'as' if (self as Actor) as CompanionActorScript ;;debug.trace(self + " OnInit - Companion - registering for CompanionChange events") RegisterForCustomEvent(FollowersScript.GetScript(), "CompanionChange") endif SetCommandable(bCommandable) SetAllowCaravan(bAllowCaravan) SetAllowMove(bAllowMove) ; if I have a linked work object, set my ownership to it if GetLinkedRef(WorkshopParent.WorkshopLinkWork) WorkshopObjectScript workobject = (GetLinkedRef(WorkshopParent.WorkshopLinkWork) as WorkshopObjectScript) ;WorkshopParent.wstrace(self + " assigning to " + workobject) workobject.AssignActor(self) endif EndEvent endState ; when assigned to a workshop, script is put into this state state assigned Event OnActivate(ObjectReference akActionRef) ;;debug.trace(self + "OnActivate " + akActionRef) if WorkshopParent.GetWorkshop(GetWorkshopID()).OwnedByPlayer ;;debug.trace(self + " Owned by player") if IsDoingFavor() && akActionRef == self && bCommandable ; must be commandable so this doesn't trigger for companions ;debug.trace(self + " OnActivate - workshop commandable") iSelfActivationCount += 1 if iSelfActivationCount > 1 ; toggle favor state setDoingFavor(false, true) endif endif endif EndEvent Event OnCommandModeGiveCommand(int aeCommandType, ObjectReference akTarget) ;debug.trace(self + " OnCommandModeGiveCommand aeCommandType=" + aeCommandType + " akTarget=" + akTarget) WorkshopObjectScript workObject = akTarget as WorkshopObjectScript if workObject && aeCommandType == 10 ; workshop assign command workObject.ActivatedByWorkshopActor(self) endif endEvent ;/ Kinggath Thoughts: The system of temporarily wounding the actor to not count their assigned objects ratings during combat seems rather pointless and wasteful. The combat will only last a few minutes and the assignments and corresponding values have no impact during that short a timespan. As soon as combat ends, the wound is removed. If the system was designed to leave people in a wounded state where they couldn't work for several days, this would make more sense. Leaving it for now to not break vanilla behavior, but will not be implementing this functionality for the nonWorkshopNPCScript actor support. /; Event OnEnterBleedout() ; set this guy as "wounded" if( ! IsWounded()) SetValue(WorkshopParent.WorkshopActorWounded, 1) UFO4P_WaitingForNPCRecovering = true int counter = 0 while IsWounded() && !IsDead() && (counter < 20) Utility.Wait(1.0) counter += 1 endWhile UFO4P_WaitingForNPCRecovering = false if(IsWounded() && !IsDead()) WorkshopParent.WoundActor(self) endIf endIf EndEvent ; WOUNDED STATE: removing visible wounded state for now Event OnCombatStateChanged(Actor akTarget, int aeCombatState) if aeCombatState == 0 && IsWounded() ;WorkshopParent.WoundActor(self, false) ;UFO4P 2.0 Bug #21578: Replaced the previous line with the following code: WorkshopParent.wstrace(self + " OnCombatStateChanged: IsWounded = false") if UFO4P_WaitingForNPCRecovering SetValue(WorkshopParent.WorkshopActorWounded, 0) else WorkshopParent.wstrace(self + " OnCombatStateChanged: Calling WoundActor.") WorkshopParent.WoundActor(self, false) endif endif EndEvent Event OnDeath(Actor akKiller) WorkshopParent.wstrace(self + " OnDeath") ; death item if synth if bIsSynth AddItem(WorkshopParent.SynthDeathItem) endif ; remove me from the workshop WorkshopParent.HandleActorDeath(self, akKiller) EndEvent Event OnLoad() ;UFO4P 2.0.1 Bug #22246: ;Added these lines to let dead actors kick themselves out. This is to handle rare cases where dead actors have been added to a workshop. if (self as Actor).IsDead() WorkshopParent.wstrace(self + " OnLoad: " + self + " is dead. Removing from workshop ...") WorkshopParent.UnassignActor(self, bRemoveFromWorkshop = true, bSendUnassignEvent = false) return endif ; do this on load to make sure reset doesn't clear it if bWorkshopStatusOn SetCommandable(bCommandable) SetAllowCaravan(bAllowCaravan) SetAllowMove(bAllowMove) endif ; WOUNDED STATE: removing visible wounded state for now if IsDead() == false && IsWounded() WorkshopParent.WoundActor(self, false) endif ; check if I should create caravan brahmin WorkshopParent.CaravanActorBrahminCheck(self) EndEvent endState Event FollowersScript.CompanionChange(FollowersScript akSender, Var[] akArgs) Actor EventActor = akArgs[0] as Actor Bool IsNowCompanion = akArgs[1] as bool ;;debug.trace(self + " CompanionChange event received for " + EventActor + " IsNowCompanion=" + IsNowCompanion) if EventActor == self if IsNowCompanion ; turn off workshop status when I become a companion SetWorkshopStatus(false) else ; turn on workshop status when I stop being a companion SetWorkshopStatus(true) endif endif EndEvent Event OnWorkshopNPCTransfer(Location akNewWorkshopLocation, Keyword akActionKW) ;WorkshopParent.wsTrace(self + " has been directed to transfer to the workshop at " + akNewWorkshopLocation + " with the " + akActionKW + " action") ; what kind of transfer? if akActionKW == WorkshopParent.WorkshopAssignCaravan WorkshopParent.AssignCaravanActorPUBLIC(self, akNewWorkshopLocation) else WorkshopScript newWorkshop = WorkshopParent.GetWorkshopFromLocation(akNewWorkshopLocation) if newWorkshop if akActionKW == WorkshopParent.WorkshopAssignHome WorkshopParent.AddActorToWorkshopPUBLIC(self, newWorkshop) elseif akActionKW == WorkshopParent.WorkshopAssignHomePermanentActor WorkshopParent.AddPermanentActorToWorkshopPUBLIC(self, newWorkshop.GetWorkshopID()) endif ; WSFW 1.1.4 - Send event that an NPC transfer occurred WorkshopParent.SendWorkshopNPCTransferEvent(Self, newWorkshop, akActionKW) else ; WSFW 1.1.4 - New functionality to allow for workshops that exist outside of the vanilla Workshops array WorkshopParent.WSFW_AddActorToLocationPUBLIC(self as Actor, akNewWorkshopLocation, akActionKW) endif endif EndEvent int timerIDCommandState = 1 float timerCommandStateSeconds = 5.0 int timerIDAssigned = 2 ; run a timer when assigned to a new work object float timerAssignedSeconds = 120.0 ; how long to stay in the "just assigned" package function StartAssignmentTimer(bool bStart = true) if bStart ; set assigned actor value SetValue(WorkshopParent.WorkshopActorAssigned, 1) StartTimer(timerAssignedSeconds, timerIDAssigned) EvaluatePackage() else ; clear assigned actor value SetValue(WorkshopParent.WorkshopActorAssigned, 0) CancelTimer(timerIDAssigned) endif endFunction function StartCommandState() ;debug.trace(self + "StartCommandState") ; clear "activate count" iSelfActivationCount = 0 ; set up distance check from workshop WorkshopScript myWorkshop = WorkshopParent.GetWorkshop(GetWorkshopID()) if myWorkshop StartTimer(timerCommandStateSeconds, timerIDCommandState) setDoingFavor(abDoingFavor = true, abWorkShopMode = true) endif endFunction Event OnTimer(int aiTimerID) if aiTimerID == timerIDCommandState WorkshopScript myWorkshop = WorkshopParent.GetWorkshop(GetWorkshopID()) if myWorkshop && IsWithinBuildableArea(myWorkshop) ; if still within build area, keep waiting StartTimer(timerCommandStateSeconds, timerIDCommandState) else ; kill command mode setDoingFavor(false, false) endif elseif aiTimerID == timerIDAssigned StartAssignmentTimer(false) endif EndEvent function SetCommandable(bool bFlag) ;debug.trace(self + "SetCommandable: " + bFlag) ; always save new state in "saved" variable bSavedCommandable = bFlag ; if workshop status on, change commandable state if bWorkshopStatusOn bCommandable = bFlag if bCommandable ;;debug.trace(self + " adding keyword " + WorkshopParent.WorkshopAllowCommand) AddKeyword(WorkshopParent.WorkshopAllowCommand) else RemoveKeyword(WorkshopParent.WorkshopAllowCommand) endif ;;debug.trace(self + " HasKeyword " + WorkshopParent.WorkshopAllowCommand + "=" + HasKeyword(WorkshopParent.WorkshopAllowCommand)) else ;;debug.trace(self + " workshop status temporarily turned off - saving new state for when turned back on") endif endFunction function SetAllowCaravan(bool bFlag) ; always save new state in "saved" variable bSavedAllowCaravan = bFlag ; if workshop status on, change commandable state if bWorkshopStatusOn bAllowCaravan = bFlag if bAllowCaravan AddKeyword(WorkshopParent.WorkshopAllowCaravan) else RemoveKeyword(WorkshopParent.WorkshopAllowCaravan) endif else ;;debug.trace(self + " workshop status temporarily turned off - saving new state for when turned back on") endif endFunction function SetAllowMove(bool bFlag) ; always save new state in "saved" variable bSavedAllowMove = bFlag ; if workshop status on, change commandable state if bWorkshopStatusOn bAllowMove = bFlag if bAllowMove AddKeyword(WorkshopParent.WorkshopAllowMove) else RemoveKeyword(WorkshopParent.WorkshopAllowMove) endif else ;;debug.trace(self + " workshop status temporarily turned off - saving new state for when turned back on") endif endFunction function SetWorkshopStatus(bool setWorkshopStatusOn) ;;debug.trace(self + " SetWorkshopStatus " + setWorkshopStatusOn) bWorkshopStatusOn = setWorkshopStatusOn if bWorkshopStatusOn ; restore saved state SetCommandable(bSavedCommandable) SetAllowMove(bSavedAllowMove) SetAllowCaravan(bSavedAllowCaravan) else ; save out current state (failsafe) bSavedAllowMove = bAllowMove bSavedAllowCaravan = bAllowCaravan bSavedCommandable = bCommandable ; now turn it all off RemoveKeyword(WorkshopParent.WorkshopAllowCommand) RemoveKeyword(WorkshopParent.WorkshopAllowMove) RemoveKeyword(WorkshopParent.WorkshopAllowCaravan) bAllowMove = false bAllowCaravan = false bCommandable = false ; unassign from any current work ;UFO4P 1.0.5 Bug #20870: Added a check for workshopID: only unassign the actor when he's assigned to a workshop: if (workshopID >= 0) WorkshopParent.UnassignActor(self) endif endif endFunction function TestKill() KillEssential() endFunction
0
0.925956
1
0.925956
game-dev
MEDIA
0.870477
game-dev
0.729615
1
0.729615
SuenoDev/Sueno
1,795
src/org/durmiendo/sueno/type/weapon/MultiBulletWeapon.java
package org.durmiendo.sueno.type.weapon; import arc.math.Mathf; import arc.scene.ui.layout.Table; import arc.struct.Seq; import mindustry.entities.bullet.BulletType; import mindustry.entities.units.WeaponMount; import mindustry.gen.Unit; import mindustry.type.UnitType; import mindustry.type.Weapon; import java.util.Comparator; public class MultiBulletWeapon extends Weapon { public Seq<BulletType> bulletTypes = new Seq<>(); public void addStats(UnitType u, Table t){ for (BulletType b : bulletTypes) { bullet = b; super.addStats(u, t); } } public float dps(){ float d = 0; for (BulletType b : bulletTypes) { bullet = b; d += super.dps(); } return d; } public float shotsPerSec(){ float s = 0; for (BulletType b : bulletTypes) { bullet = b; s += super.shotsPerSec(); } return s; } public float range(){ float r = 0; for (BulletType b : bulletTypes) { if (b.range > r) r = b.range; } return r; } public void add(BulletType b){ bulletTypes.add(b); bulletTypes.sort(Comparator.comparing((a) -> a.range)); } @Override protected void shoot(Unit unit, WeaponMount mount, float shootX, float shootY, float rotation) { float x = mount.target.x(); float y = mount.target.y(); float d = Mathf.dst(x, y, shootX, shootY); BulletType b; for (int i = 0; i < bulletTypes.size; i++) { b = bulletTypes.get(i); if (b.range > d) { bullet = b; break; } } super.shoot(unit, mount, shootX, shootY, rotation); } }
0
0.646942
1
0.646942
game-dev
MEDIA
0.762395
game-dev
0.935119
1
0.935119
MarkGG8181/stripped-1.8.9
4,766
src/main/java/net/minecraft/entity/ai/EntityAINearestAttackableTarget.java
package net.minecraft.entity.ai; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import java.util.Collections; import java.util.Comparator; import java.util.List; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityCreature; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.EntitySelectors; public class EntityAINearestAttackableTarget<T extends EntityLivingBase> extends EntityAITarget { protected final Class<T> targetClass; private final int targetChance; /** Instance of EntityAINearestAttackableTargetSorter. */ protected final EntityAINearestAttackableTarget.Sorter theNearestAttackableTargetSorter; protected Predicate<? super T> targetEntitySelector; protected EntityLivingBase targetEntity; public EntityAINearestAttackableTarget(EntityCreature creature, Class<T> classTarget, boolean checkSight) { this(creature, classTarget, checkSight, false); } public EntityAINearestAttackableTarget(EntityCreature creature, Class<T> classTarget, boolean checkSight, boolean onlyNearby) { this(creature, classTarget, 10, checkSight, onlyNearby, (Predicate<? super T>)null); } public EntityAINearestAttackableTarget(EntityCreature creature, Class<T> classTarget, int chance, boolean checkSight, boolean onlyNearby, final Predicate<? super T> targetSelector) { super(creature, checkSight, onlyNearby); this.targetClass = classTarget; this.targetChance = chance; this.theNearestAttackableTargetSorter = new EntityAINearestAttackableTarget.Sorter(creature); this.setMutexBits(1); this.targetEntitySelector = new Predicate<>() { public boolean apply(T p_apply_1_) { if (targetSelector != null && !targetSelector.apply(p_apply_1_)) { return false; } else { if (p_apply_1_ instanceof EntityPlayer player) { double d0 = EntityAINearestAttackableTarget.this.getTargetDistance(); if (p_apply_1_.isSneaking()) { d0 *= 0.800000011920929D; } if (p_apply_1_.isInvisible()) { float f = player.getArmorVisibility(); if (f < 0.1F) { f = 0.1F; } d0 *= (double)(0.7F * f); } if ((double)p_apply_1_.getDistanceToEntity(EntityAINearestAttackableTarget.this.taskOwner) > d0) { return false; } } return EntityAINearestAttackableTarget.this.isSuitableTarget(p_apply_1_, false); } } }; } /** * Returns whether the EntityAIBase should begin execution. */ public boolean shouldExecute() { if (this.targetChance > 0 && this.taskOwner.getRNG().nextInt(this.targetChance) != 0) { return false; } else { double d0 = this.getTargetDistance(); List<T> list = this.taskOwner.worldObj.getEntitiesWithinAABB(this.targetClass, this.taskOwner.getEntityBoundingBox().expand(d0, 4.0D, d0), Predicates.<T>and(this.targetEntitySelector, EntitySelectors.NOT_SPECTATING)); Collections.sort(list, this.theNearestAttackableTargetSorter); if (list.isEmpty()) { return false; } else { this.targetEntity = (EntityLivingBase)list.getFirst(); return true; } } } /** * Execute a one shot task or start executing a continuous task */ public void startExecuting() { this.taskOwner.setAttackTarget(this.targetEntity); super.startExecuting(); } public static class Sorter implements Comparator<Entity> { private final Entity theEntity; public Sorter(Entity theEntityIn) { this.theEntity = theEntityIn; } public int compare(Entity p_compare_1_, Entity p_compare_2_) { double d0 = this.theEntity.getDistanceSqToEntity(p_compare_1_); double d1 = this.theEntity.getDistanceSqToEntity(p_compare_2_); return d0 < d1 ? -1 : (d0 > d1 ? 1 : 0); } } }
0
0.839233
1
0.839233
game-dev
MEDIA
0.968111
game-dev
0.93652
1
0.93652
Ryhon0/VostokMods
1,271
sample_mods/SimpleControls/mods/SimpleControls/Character.gd
extends "res://Scripts/Character.gd" func _process(delta): # super() gameData.weaponPosition = 1 if gameData.isRunning else 2 func Stamina(delta): if (gameData.isRunning || gameData.overweight || (gameData.isSwimming && gameData.isMoving)) && gameData.bodyStamina > 0: if gameData.overweight || gameData.starvation || gameData.dehydration: gameData.bodyStamina -= delta * 4.0 else : gameData.bodyStamina -= delta * 2.0 elif gameData.bodyStamina < 100: if gameData.starvation || gameData.dehydration: gameData.bodyStamina += delta * 5.0 else : gameData.bodyStamina += delta * 10.0 if ((gameData.primary || gameData.secondary) && (gameData.isAiming || gameData.isCanted || gameData.isInspecting || gameData.overweight) || (gameData.isSwimming && gameData.isMoving)) && gameData.armStamina > 0: if gameData.overweight || gameData.starvation || gameData.dehydration: gameData.armStamina -= delta * 4.0 else : gameData.armStamina -= delta * 2.0 elif gameData.armStamina < 100: if gameData.starvation || gameData.dehydration: gameData.armStamina += delta * 10.0 else : gameData.armStamina += delta * 20.0 gameData.bodyStamina = clampf(gameData.bodyStamina, 0, 100) gameData.armStamina = clampf(gameData.armStamina, 0, 100)
0
0.569874
1
0.569874
game-dev
MEDIA
0.944425
game-dev
0.650746
1
0.650746
peichhorn/lombok-pg
1,977
src/core/lombok/ast/Try.java
/* * Copyright © 2011-2012 Philipp Eichhorn * * 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 lombok.ast; import java.util.*; import lombok.*; @Getter public final class Try extends Statement<Try> { private final List<Argument> catchArguments = new ArrayList<Argument>(); private final List<Block> catchBlocks = new ArrayList<Block>(); private final Block tryBlock; private Block finallyBlock; public Try(final Block tryBlock) { this.tryBlock = child(tryBlock); } public Try Catch(final Argument catchArgument, final Block catchBlock) { catchArguments.add(child(catchArgument)); catchBlocks.add(child(catchBlock)); return this; } public Try Finally(final Block finallyBlock) { this.finallyBlock = child(finallyBlock); return this; } @Override public <RETURN_TYPE, PARAMETER_TYPE> RETURN_TYPE accept(final ASTVisitor<RETURN_TYPE, PARAMETER_TYPE> v, final PARAMETER_TYPE p) { return v.visitTry(this, p); } }
0
0.7589
1
0.7589
game-dev
MEDIA
0.151889
game-dev
0.62875
1
0.62875
chaosaudio/Dev-Portal
10,531
examples/juce_effect/JUCE/modules/juce_box2d/box2d/Dynamics/Joints/b2WheelJoint.cpp
/* * Copyright (c) 2006-2007 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #include "b2WheelJoint.h" #include "../b2Body.h" #include "../b2TimeStep.h" // Linear constraint (point-to-line) // d = pB - pA = xB + rB - xA - rA // C = dot(ay, d) // Cdot = dot(d, cross(wA, ay)) + dot(ay, vB + cross(wB, rB) - vA - cross(wA, rA)) // = -dot(ay, vA) - dot(cross(d + rA, ay), wA) + dot(ay, vB) + dot(cross(rB, ay), vB) // J = [-ay, -cross(d + rA, ay), ay, cross(rB, ay)] // Spring linear constraint // C = dot(ax, d) // Cdot = = -dot(ax, vA) - dot(cross(d + rA, ax), wA) + dot(ax, vB) + dot(cross(rB, ax), vB) // J = [-ax -cross(d+rA, ax) ax cross(rB, ax)] // Motor rotational constraint // Cdot = wB - wA // J = [0 0 -1 0 0 1] void b2WheelJointDef::Initialize(b2Body* bA, b2Body* bB, const b2Vec2& anchor, const b2Vec2& axis) { bodyA = bA; bodyB = bB; localAnchorA = bodyA->GetLocalPoint(anchor); localAnchorB = bodyB->GetLocalPoint(anchor); localAxisA = bodyA->GetLocalVector(axis); } b2WheelJoint::b2WheelJoint(const b2WheelJointDef* def) : b2Joint(def) { m_localAnchorA = def->localAnchorA; m_localAnchorB = def->localAnchorB; m_localXAxisA = def->localAxisA; m_localYAxisA = b2Cross(1.0f, m_localXAxisA); m_mass = 0.0f; m_impulse = 0.0f; m_motorMass = 0.0f; m_motorImpulse = 0.0f; m_springMass = 0.0f; m_springImpulse = 0.0f; m_maxMotorTorque = def->maxMotorTorque; m_motorSpeed = def->motorSpeed; m_enableMotor = def->enableMotor; m_frequencyHz = def->frequencyHz; m_dampingRatio = def->dampingRatio; m_bias = 0.0f; m_gamma = 0.0f; m_ax.SetZero(); m_ay.SetZero(); } void b2WheelJoint::InitVelocityConstraints(const b2SolverData& data) { m_indexA = m_bodyA->m_islandIndex; m_indexB = m_bodyB->m_islandIndex; m_localCenterA = m_bodyA->m_sweep.localCenter; m_localCenterB = m_bodyB->m_sweep.localCenter; m_invMassA = m_bodyA->m_invMass; m_invMassB = m_bodyB->m_invMass; m_invIA = m_bodyA->m_invI; m_invIB = m_bodyB->m_invI; float32 mA = m_invMassA, mB = m_invMassB; float32 iA = m_invIA, iB = m_invIB; b2Vec2 cA = data.positions[m_indexA].c; float32 aA = data.positions[m_indexA].a; b2Vec2 vA = data.velocities[m_indexA].v; float32 wA = data.velocities[m_indexA].w; b2Vec2 cB = data.positions[m_indexB].c; float32 aB = data.positions[m_indexB].a; b2Vec2 vB = data.velocities[m_indexB].v; float32 wB = data.velocities[m_indexB].w; b2Rot qA(aA), qB(aB); // Compute the effective masses. b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); b2Vec2 d = cB + rB - cA - rA; // Point to line constraint { m_ay = b2Mul(qA, m_localYAxisA); m_sAy = b2Cross(d + rA, m_ay); m_sBy = b2Cross(rB, m_ay); m_mass = mA + mB + iA * m_sAy * m_sAy + iB * m_sBy * m_sBy; if (m_mass > 0.0f) { m_mass = 1.0f / m_mass; } } // Spring constraint m_springMass = 0.0f; m_bias = 0.0f; m_gamma = 0.0f; if (m_frequencyHz > 0.0f) { m_ax = b2Mul(qA, m_localXAxisA); m_sAx = b2Cross(d + rA, m_ax); m_sBx = b2Cross(rB, m_ax); float32 invMass = mA + mB + iA * m_sAx * m_sAx + iB * m_sBx * m_sBx; if (invMass > 0.0f) { m_springMass = 1.0f / invMass; float32 C = b2Dot(d, m_ax); // Frequency float32 omega = 2.0f * b2_pi * m_frequencyHz; // Damping coefficient float32 damp = 2.0f * m_springMass * m_dampingRatio * omega; // Spring stiffness float32 k = m_springMass * omega * omega; // magic formulas float32 h = data.step.dt; m_gamma = h * (damp + h * k); if (m_gamma > 0.0f) { m_gamma = 1.0f / m_gamma; } m_bias = C * h * k * m_gamma; m_springMass = invMass + m_gamma; if (m_springMass > 0.0f) { m_springMass = 1.0f / m_springMass; } } } else { m_springImpulse = 0.0f; } // Rotational motor if (m_enableMotor) { m_motorMass = iA + iB; if (m_motorMass > 0.0f) { m_motorMass = 1.0f / m_motorMass; } } else { m_motorMass = 0.0f; m_motorImpulse = 0.0f; } if (data.step.warmStarting) { // Account for variable time step. m_impulse *= data.step.dtRatio; m_springImpulse *= data.step.dtRatio; m_motorImpulse *= data.step.dtRatio; b2Vec2 P = m_impulse * m_ay + m_springImpulse * m_ax; float32 LA = m_impulse * m_sAy + m_springImpulse * m_sAx + m_motorImpulse; float32 LB = m_impulse * m_sBy + m_springImpulse * m_sBx + m_motorImpulse; vA -= m_invMassA * P; wA -= m_invIA * LA; vB += m_invMassB * P; wB += m_invIB * LB; } else { m_impulse = 0.0f; m_springImpulse = 0.0f; m_motorImpulse = 0.0f; } data.velocities[m_indexA].v = vA; data.velocities[m_indexA].w = wA; data.velocities[m_indexB].v = vB; data.velocities[m_indexB].w = wB; } void b2WheelJoint::SolveVelocityConstraints(const b2SolverData& data) { float32 mA = m_invMassA, mB = m_invMassB; float32 iA = m_invIA, iB = m_invIB; b2Vec2 vA = data.velocities[m_indexA].v; float32 wA = data.velocities[m_indexA].w; b2Vec2 vB = data.velocities[m_indexB].v; float32 wB = data.velocities[m_indexB].w; // Solve spring constraint { float32 Cdot = b2Dot(m_ax, vB - vA) + m_sBx * wB - m_sAx * wA; float32 impulse = -m_springMass * (Cdot + m_bias + m_gamma * m_springImpulse); m_springImpulse += impulse; b2Vec2 P = impulse * m_ax; float32 LA = impulse * m_sAx; float32 LB = impulse * m_sBx; vA -= mA * P; wA -= iA * LA; vB += mB * P; wB += iB * LB; } // Solve rotational motor constraint { float32 Cdot = wB - wA - m_motorSpeed; float32 impulse = -m_motorMass * Cdot; float32 oldImpulse = m_motorImpulse; float32 maxImpulse = data.step.dt * m_maxMotorTorque; m_motorImpulse = b2Clamp(m_motorImpulse + impulse, -maxImpulse, maxImpulse); impulse = m_motorImpulse - oldImpulse; wA -= iA * impulse; wB += iB * impulse; } // Solve point to line constraint { float32 Cdot = b2Dot(m_ay, vB - vA) + m_sBy * wB - m_sAy * wA; float32 impulse = -m_mass * Cdot; m_impulse += impulse; b2Vec2 P = impulse * m_ay; float32 LA = impulse * m_sAy; float32 LB = impulse * m_sBy; vA -= mA * P; wA -= iA * LA; vB += mB * P; wB += iB * LB; } data.velocities[m_indexA].v = vA; data.velocities[m_indexA].w = wA; data.velocities[m_indexB].v = vB; data.velocities[m_indexB].w = wB; } bool b2WheelJoint::SolvePositionConstraints(const b2SolverData& data) { b2Vec2 cA = data.positions[m_indexA].c; float32 aA = data.positions[m_indexA].a; b2Vec2 cB = data.positions[m_indexB].c; float32 aB = data.positions[m_indexB].a; b2Rot qA(aA), qB(aB); b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); b2Vec2 d = (cB - cA) + rB - rA; b2Vec2 ay = b2Mul(qA, m_localYAxisA); float32 sAy = b2Cross(d + rA, ay); float32 sBy = b2Cross(rB, ay); float32 C = b2Dot(d, ay); float32 k = m_invMassA + m_invMassB + m_invIA * m_sAy * m_sAy + m_invIB * m_sBy * m_sBy; float32 impulse; if (k != 0.0f) { impulse = - C / k; } else { impulse = 0.0f; } b2Vec2 P = impulse * ay; float32 LA = impulse * sAy; float32 LB = impulse * sBy; cA -= m_invMassA * P; aA -= m_invIA * LA; cB += m_invMassB * P; aB += m_invIB * LB; data.positions[m_indexA].c = cA; data.positions[m_indexA].a = aA; data.positions[m_indexB].c = cB; data.positions[m_indexB].a = aB; return b2Abs(C) <= b2_linearSlop; } b2Vec2 b2WheelJoint::GetAnchorA() const { return m_bodyA->GetWorldPoint(m_localAnchorA); } b2Vec2 b2WheelJoint::GetAnchorB() const { return m_bodyB->GetWorldPoint(m_localAnchorB); } b2Vec2 b2WheelJoint::GetReactionForce(float32 inv_dt) const { return inv_dt * (m_impulse * m_ay + m_springImpulse * m_ax); } float32 b2WheelJoint::GetReactionTorque(float32 inv_dt) const { return inv_dt * m_motorImpulse; } float32 b2WheelJoint::GetJointTranslation() const { b2Body* bA = m_bodyA; b2Body* bB = m_bodyB; b2Vec2 pA = bA->GetWorldPoint(m_localAnchorA); b2Vec2 pB = bB->GetWorldPoint(m_localAnchorB); b2Vec2 d = pB - pA; b2Vec2 axis = bA->GetWorldVector(m_localXAxisA); float32 translation = b2Dot(d, axis); return translation; } float32 b2WheelJoint::GetJointSpeed() const { float32 wA = m_bodyA->m_angularVelocity; float32 wB = m_bodyB->m_angularVelocity; return wB - wA; } bool b2WheelJoint::IsMotorEnabled() const { return m_enableMotor; } void b2WheelJoint::EnableMotor(bool flag) { m_bodyA->SetAwake(true); m_bodyB->SetAwake(true); m_enableMotor = flag; } void b2WheelJoint::SetMotorSpeed(float32 speed) { m_bodyA->SetAwake(true); m_bodyB->SetAwake(true); m_motorSpeed = speed; } void b2WheelJoint::SetMaxMotorTorque(float32 torque) { m_bodyA->SetAwake(true); m_bodyB->SetAwake(true); m_maxMotorTorque = torque; } float32 b2WheelJoint::GetMotorTorque(float32 inv_dt) const { return inv_dt * m_motorImpulse; } void b2WheelJoint::Dump() { int32 indexA = m_bodyA->m_islandIndex; int32 indexB = m_bodyB->m_islandIndex; b2Log(" b2WheelJointDef jd;\n"); b2Log(" jd.bodyA = bodies[%d];\n", indexA); b2Log(" jd.bodyB = bodies[%d];\n", indexB); b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); b2Log(" jd.localAxisA.Set(%.15lef, %.15lef);\n", m_localXAxisA.x, m_localXAxisA.y); b2Log(" jd.enableMotor = bool(%d);\n", m_enableMotor); b2Log(" jd.motorSpeed = %.15lef;\n", m_motorSpeed); b2Log(" jd.maxMotorTorque = %.15lef;\n", m_maxMotorTorque); b2Log(" jd.frequencyHz = %.15lef;\n", m_frequencyHz); b2Log(" jd.dampingRatio = %.15lef;\n", m_dampingRatio); b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); }
0
0.95862
1
0.95862
game-dev
MEDIA
0.813453
game-dev
0.977352
1
0.977352
RavEngine/RavEngine
5,143
deps/physx/physx/include/vehicle2/tire/PxVehicleTireStates.h
// 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 NVIDIA CORPORATION 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 ''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. // // Copyright (c) 2008-2025 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #pragma once #include "foundation/PxVec3.h" #include "foundation/PxMemory.h" #include "vehicle2/PxVehicleParams.h" #if !PX_DOXYGEN namespace physx { namespace vehicle2 { #endif /** \brief PxVehicleTireDirectionState stores the world frame lateral and longtidinal axes of the tire after projecting the wheel pose in the world frame onto the road geometry plane (also in the world frame). */ struct PxVehicleTireDirectionState { PxVec3 directions[PxVehicleTireDirectionModes::eMAX_NB_PLANAR_DIRECTIONS]; PX_FORCE_INLINE void setToDefault() { PxMemZero(this, sizeof(PxVehicleTireDirectionState)); } }; /** \brief PxVehicleTireSpeedState stores the components of the instantaneous velocity of the rigid body at the tire contact point projected along the lateral and longitudinal axes of the tire. \see PxVehicleTireDirectionState */ struct PxVehicleTireSpeedState { PxReal speedStates[PxVehicleTireDirectionModes::eMAX_NB_PLANAR_DIRECTIONS]; PX_FORCE_INLINE void setToDefault() { PxMemZero(this, sizeof(PxVehicleTireSpeedState)); } }; /** \brief The lateral and longitudinal tire slips. \see PxVehicleTireSpeedState */ struct PxVehicleTireSlipState { PxReal slips[PxVehicleTireDirectionModes::eMAX_NB_PLANAR_DIRECTIONS]; PX_FORCE_INLINE void setToDefault() { PxMemZero(this, sizeof(PxVehicleTireSlipState)); } }; /** \brief The load and friction experienced by a tire. */ struct PxVehicleTireGripState { /** \brief The tire load <b>Unit:</b> force = mass * length / (time^2) */ PxReal load; /** \brief The tire friction is the product of the road geometry friction and a friction response multiplier. */ PxReal friction; PX_FORCE_INLINE void setToDefault() { PxMemZero(this, sizeof(PxVehicleTireGripState)); } }; /** \brief Camber angle of the tire relative to the ground plane. */ struct PxVehicleTireCamberAngleState { PxReal camberAngle; PX_FORCE_INLINE void setToDefault() { PxMemZero(this, sizeof(PxVehicleTireCamberAngleState)); } }; /** \brief Prolonged low speeds in the lateral and longitudinal directions may be handled with "sticky" velocity constraints that activate after a speed below a threshold has been recorded for a threshold time. \see PxVehicleTireStickyParams \see PxVehicleTireSpeedState */ struct PxVehicleTireStickyState { PxReal lowSpeedTime[PxVehicleTireDirectionModes::eMAX_NB_PLANAR_DIRECTIONS]; bool activeStatus[PxVehicleTireDirectionModes::eMAX_NB_PLANAR_DIRECTIONS]; PX_FORCE_INLINE void setToDefault() { PxMemZero(this, sizeof(PxVehicleTireStickyState)); } }; /** \brief The longitudinal/lateral forces/torques that develop on the tire. */ struct PxVehicleTireForce { /* \brief The tire forces that develop along the tire's longitudinal and lateral directions. Specified in the world frame. */ PxVec3 forces[PxVehicleTireDirectionModes::eMAX_NB_PLANAR_DIRECTIONS]; /* \brief The tire torques that develop around the tire's longitudinal and lateral directions. Specified in the world frame. */ PxVec3 torques[PxVehicleTireDirectionModes::eMAX_NB_PLANAR_DIRECTIONS]; /** \brief The aligning moment may be propagated to a torque-driven steering controller. */ PxReal aligningMoment; /** \brief The torque to apply to the wheel's 1d rigid body. */ PxReal wheelTorque; PX_FORCE_INLINE void setToDefault() { PxMemZero(this, sizeof(PxVehicleTireForce)); } }; #if !PX_DOXYGEN } // namespace vehicle2 } // namespace physx #endif
0
0.791255
1
0.791255
game-dev
MEDIA
0.854111
game-dev
0.840967
1
0.840967
pema99/SlangUnityPlugin
32,341
Editor/Scripts/SlangShaderImporter.cs
using UnityEditor; using UnityEngine; using UnityEditor.AssetImporters; using System.IO; using UnityShaderParser.ShaderLab; using UnityShaderParser.HLSL; using UnityShaderParser.Common; using System.Collections.Generic; using System.Diagnostics; using System; using System.Text.RegularExpressions; using System.Text; using UnitySlangShader.SlangAPI; using SLTokenKind = UnityShaderParser.ShaderLab.TokenKind; using HLSLTokenKind = UnityShaderParser.HLSL.TokenKind; using SLToken = UnityShaderParser.Common.Token<UnityShaderParser.ShaderLab.TokenKind>; using HLSLToken = UnityShaderParser.Common.Token<UnityShaderParser.HLSL.TokenKind>; using System.Linq; using UnityEditor.Rendering; using System.Threading.Tasks; using System.Collections.Concurrent; using UnityEngine.Rendering; using System.Threading; namespace UnitySlangShader { [Serializable] public struct SlangShaderDiagnostic { public string Text; public string File; public int Line; public bool Warning; } [ScriptedImporter(1, "slangshader")] public class SlangShaderImporter : ScriptedImporter { // Makes edits to HLSL code resulting from Slang compilation to make it unity-compatible private class HLSLSlangEditor : HLSLEditor { // Renaming samplers public HashSet<string> BrokenTextureFields = new HashSet<string>(); public HLSLSlangEditor(string source, List<HLSLToken> tokens) : base(source, tokens) { } public override void VisitVariableDeclarationStatementNode(VariableDeclarationStatementNode node) { if (node.Declarators.Count == 1 && node.Kind is PredefinedObjectTypeNode obj) { string declName = node.Declarators[0].Name; switch (obj.Kind) { // Keep track of declared textures, and rename problematic ones case PredefinedObjectType.Texture: case PredefinedObjectType.Texture1D: case PredefinedObjectType.Texture1DArray: case PredefinedObjectType.Texture2D: case PredefinedObjectType.Texture2DArray: case PredefinedObjectType.Texture3D: case PredefinedObjectType.TextureCube: case PredefinedObjectType.TextureCubeArray: case PredefinedObjectType.Texture2DMS: case PredefinedObjectType.Texture2DMSArray: if (declName.EndsWith("_t_0")) { string newName = declName.Replace("_t_0", ""); node.Declarators[0].Name = newName; Edit(node.Declarators[0], node.Declarators[0].GetPrettyPrintedCode()); BrokenTextureFields.Add(newName); } break; // Replace names of declared samplers with the appropriate unity convention case PredefinedObjectType.SamplerState: if (declName.EndsWith("_s_0")) { string correspondingTextureName = declName.Replace("_s_0", ""); if (BrokenTextureFields.Contains(correspondingTextureName)) { node.Declarators[0].Name = $"sampler_{correspondingTextureName}"; Edit(node.Declarators[0], node.Declarators[0].GetPrettyPrintedCode()); } } break; default: break; } } base.VisitVariableDeclarationStatementNode(node); } public override void VisitIdentifierExpressionNode(IdentifierExpressionNode node) { // Replace names of used samplers with the appropriate unity convention if (node.Name.EndsWith("_s_0")) { string correspondingTextureName = node.Name.Replace("_s_0", ""); if (BrokenTextureFields.Contains(correspondingTextureName)) { Edit(node, $"sampler_{correspondingTextureName}"); } } // Replace names of used textures, removing the suffix else if (node.Name.EndsWith("_t_0")) { string newName = node.Name.Replace("_t_0", ""); if (BrokenTextureFields.Contains(newName)) { Edit(node, newName); } } base.VisitIdentifierExpressionNode(node); } } // Traverses ShaderLab code and replaces Slang blocks with HLSL blocks private class ShaderLabSlangEditor : ShaderLabEditor { public HashSet<string> Diagnostics = new HashSet<string>(); public HashSet<string> DependencyFiles = new HashSet<string>(); private string filePath = string.Empty; private string[] includePaths; private SlangShaderVariant[] variantsToGenerate; private HashSet<string> allKeywords; public ShaderLabSlangEditor(string filePath, string[] additionalIncludePaths, SlangShaderVariant[] variantsToGenerate, string source, List<SLToken> tokens) : base(source, tokens) { this.filePath = filePath; string cgIncludePath = $"{EditorApplication.applicationContentsPath}/CGIncludes"; string basePath = Directory.GetParent(Application.dataPath).FullName; this.includePaths = additionalIncludePaths .Concat(new string[] { cgIncludePath, basePath }) .ToArray(); this.variantsToGenerate = variantsToGenerate; // Find the entire space of keywords we care about allKeywords = variantsToGenerate.SelectMany(x => x.Keywords).ToHashSet(); // Delete all include blocks foreach (var token in tokens) { if (token.Kind == SLTokenKind.IncludeBlock) { Edit(token, string.Empty); } } } public override void VisitShaderCodePassNode(ShaderCodePassNode node) { node.ProgramBlocks.ForEach(HandleProgramBlock); base.VisitShaderCodePassNode(node); } public override void VisitSubShaderNode(SubShaderNode node) { node.ProgramBlocks.ForEach(HandleProgramBlock); base.VisitSubShaderNode(node); } private List<string[]> ExtractPragmasFromCode(string fullCode) { List<string[]> pragmas = new List<string[]>(); var matches = Regex.Matches(fullCode, @"#pragma (.+)$", RegexOptions.Multiline); foreach (Match pragma in matches) { string trimmed = pragma.Groups[0].Value.Trim(); if (trimmed == string.Empty) continue; string[] parts = trimmed.Split(' '); pragmas.Add(parts.Skip(1).ToArray()); } return pragmas; } private List<(string stage, string entryName)> FindEntryPointPragmas(List<string[]> pragmas) { var entryPoints = new List<(string stage, string entryName)>(); foreach (var pragma in pragmas) { if (pragma.Length <= 1) continue; switch (pragma[0]) { case "fragment": case "vertex": case "geometry": case "hull": case "domain": entryPoints.Add((pragma[0], pragma[1])); break; default: break; } } return entryPoints; } // Which pragmas to passthrough into the final shader? private string GetPassthroughPragmas(List<string[]> pragmas) { StringBuilder sb = new StringBuilder(); foreach (string[] pragma in pragmas) { if (pragma.Length == 0) continue; if (pragma[0].StartsWith("multi_compile") || pragma[0].StartsWith("shader_feature") || pragma[0] == "skip_variants" || pragma[0] == "only_renderers" || pragma[0] == "exclude_renderers" || pragma[0] == "hardware_tier_variants") { sb.AppendLine($"#pragma {string.Join(" ", pragma)}"); } } return sb.ToString(); } public void HandleProgramBlock(HLSLProgramBlock programBlock) { string preamble = SlangShaderSnippets.SlangSupportPreamble; string fullCodeWithLineStart = $"{preamble}\n#line {programBlock.Span.Start.Line - 1}\n{programBlock.FullCode}"; // Setup var pragmas = ExtractPragmasFromCode(fullCodeWithLineStart); var entryPoints = FindEntryPointPragmas(pragmas); Dictionary<string, string> predefinedDirectives = GetPredefinedDirectives(); // Compile each variant var perThreadResult = new string[variantsToGenerate.Length]; var perThreadDiagnostic = new List<string>[variantsToGenerate.Length]; var perThreadEntryPoints = new HashSet<(string stage, string entryName)>[variantsToGenerate.Length]; var perThreadDependencyFiles = new string[variantsToGenerate.Length][]; int doneVariants = 0; var compileTask = Task.Run(() => { // We estimate that each thread needs to compile about 4 variants for parallelization to be worth it float saturation = (float)variantsToGenerate.Length / (Environment.ProcessorCount * 4); int threadCount = Mathf.Clamp(Mathf.CeilToInt(saturation * Environment.ProcessorCount), 1, Environment.ProcessorCount); ConcurrentQueue<int> remainingWork = new ConcurrentQueue<int>(Enumerable.Range(0, variantsToGenerate.Length)); Thread[] threads = new Thread[threadCount]; for (int i = 0; i < threadCount; i++) { threads[i] = new Thread(() => { using SlangSession session = new SlangSession(); while (!remainingWork.IsEmpty) { if (!remainingWork.TryDequeue(out int variantIdx)) continue; perThreadResult[variantIdx] = CompileVariant( session, fullCodeWithLineStart, includePaths, predefinedDirectives, variantsToGenerate[variantIdx].Keywords, variantsToGenerate[variantIdx].PlatformKeywords, entryPoints, out perThreadDiagnostic[variantIdx], out perThreadEntryPoints[variantIdx], out perThreadDependencyFiles[variantIdx]); Interlocked.Increment(ref doneVariants); } }); threads[i].Start(); } for (int i = 0; i < threadCount; i++) { threads[i].Join(); } }); // Show progress if there are enough variants to justify it if (variantsToGenerate.Length > 16) { while (!compileTask.IsCompleted) { EditorUtility.DisplayProgressBar( "Slang Shader compilation", $"Compiling variant ({doneVariants} / {variantsToGenerate.Length})", (float)doneVariants / (float)variantsToGenerate.Length); Thread.Sleep(10); } EditorUtility.ClearProgressBar(); } else { compileTask.Wait(); } // Gather the result of each compilation string allVariants = string.Join("\n", perThreadResult); Diagnostics.UnionWith(perThreadDiagnostic.SelectMany(x => x)); DependencyFiles.UnionWith(perThreadDependencyFiles.SelectMany(x => x)); // Find all entry points from each variant, make pragmas from them. Add vert or frag if missing. var allEntryPoints = CollectEntryPoints(perThreadEntryPoints); string entryPointPragmas = $"{string.Join("\n", allEntryPoints.Select(x => $"#pragma {x.stage} {x.entryName}"))}\n"; // Some pragmas like multi_compile should just be passed through directly string passthroughPragmas = GetPassthroughPragmas(pragmas); // In case a request variant is missing or failed to compile, provide a fallback variant string fallbackVariant = GetFallbackVariant(allEntryPoints); Edit(programBlock.Span, $"HLSLPROGRAM\n{entryPointPragmas}{passthroughPragmas}{allVariants}{fallbackVariant}\nENDHLSL"); } private string CompileVariant( SlangSession slangSession, string fullCode, string[] includePaths, Dictionary<string, string> predefinedDirectives, HashSet<string> keywords, string[] platformKeywords, List<(string stage, string entryName)> knownEntryPoints, out List<string> diagnostics, out HashSet<(string stage, string entryName)> outEntryPoints, out string[] dependencyFiles) { diagnostics = new List<string>(); outEntryPoints = new HashSet<(string stage, string entryName)>(); dependencyFiles = new string[0]; using CompileRequest request = slangSession.CreateCompileRequest(); request.SetCodeGenTarget(SlangCompileTarget.SLANG_HLSL); request.SetMatrixLayoutMode(SlangMatrixLayoutMode.SLANG_MATRIX_LAYOUT_COLUMN_MAJOR); request.SetTargetFlags(SlangTargetFlags.SLANG_TARGET_FLAG_GENERATE_WHOLE_PROGRAM); request.SetTargetLineDirectiveMode(SlangLineDirectiveMode.SLANG_LINE_DIRECTIVE_MODE_NONE); foreach (string includePath in includePaths) { request.AddSearchPath(includePath); } // Define user keywords foreach (var keyword in keywords) { request.AddPreprocessorDefine(keyword, "1"); } // Define platform keywords foreach (var keyword in platformKeywords) { request.AddPreprocessorDefine(keyword, "1"); } // Define directives foreach ((string key, string val) in predefinedDirectives) { request.AddPreprocessorDefine(key, val); } // Some stuff to make slang output something closer to Unity style request.ProcessCommandLineArguments(new string[] { "-no-mangle", "-no-hlsl-binding", "-no-hlsl-pack-constant-buffer-elements" }); request.OverrideDiagnosticSeverity(15205, SlangSeverity.SLANG_SEVERITY_DISABLED); // undefined identifier in preprocessor expression will evaluate to 0 request.OverrideDiagnosticSeverity(15400, SlangSeverity.SLANG_SEVERITY_DISABLED); // redefinition of macro request.OverrideDiagnosticSeverity(15601, SlangSeverity.SLANG_SEVERITY_DISABLED); // ignoring unknown directive request.OverrideDiagnosticSeverity(39019, SlangSeverity.SLANG_SEVERITY_DISABLED); // implicitly global shader parameter with no uniform keyword request.OverrideDiagnosticSeverity(30056, SlangSeverity.SLANG_SEVERITY_DISABLED); // non-short-circuiting ternary int translationUnitIndex = request.AddTranslationUnit(SlangSourceLanguage.SLANG_SOURCE_LANGUAGE_SLANG, "Main Translation Unit"); request.AddTranslationUnitSourceString(translationUnitIndex, filePath, fullCode); // Handle #pragma style entry point syntax, to avoid confusing the user. foreach (var entryPoint in knownEntryPoints) { SlangStage stage = SlangStage.SLANG_STAGE_NONE; switch (entryPoint.stage) { case "fragment": stage = SlangStage.SLANG_STAGE_FRAGMENT; break; case "vertex": stage = SlangStage.SLANG_STAGE_VERTEX; break; case "geometry": stage = SlangStage.SLANG_STAGE_GEOMETRY; break; case "hull": stage = SlangStage.SLANG_STAGE_HULL; break; case "domain": stage = SlangStage.SLANG_STAGE_DOMAIN; break; default: break; } diagnostics.Add($"Shader uses #pragma syntax for specifying entry point '{entryPoint.entryName}'. " + $"Annotate the entry point with the [shader(\"{entryPoint.stage}\")] attribute instead."); request.AddEntryPoint(translationUnitIndex, entryPoint.entryName, stage); } SlangResult result = request.Compile(); StringBuilder codeBuilder = new StringBuilder(); AppendKeywordCombinationDirective(codeBuilder, keywords); if (result.IsOk) { codeBuilder.AppendLine("#define SLANG_SHADER_VARIANT_FOUND 1"); // Get the name of each entry point, annotate them as Unity pragmas SlangReflection refl = request.GetReflection(); uint entryPointCount = refl.GetEntryPointCount(); for (uint entryPointIdx = 0; entryPointIdx < entryPointCount; entryPointIdx++) { SlangReflectionEntryPoint entryPoint = refl.GetEntryPointByIndex(entryPointIdx); SlangStage stage = entryPoint.GetStage(); string name = entryPoint.GetName(); switch (stage) { case SlangStage.SLANG_STAGE_VERTEX: outEntryPoints.Add(("vertex", name)); break; case SlangStage.SLANG_STAGE_HULL: outEntryPoints.Add(("hull", name)); break; case SlangStage.SLANG_STAGE_DOMAIN: outEntryPoints.Add(("domain", name)); break; case SlangStage.SLANG_STAGE_GEOMETRY: outEntryPoints.Add(("geometry", name)); break; case SlangStage.SLANG_STAGE_FRAGMENT: outEntryPoints.Add(("fragment", name)); break; case SlangStage.SLANG_STAGE_COMPUTE: outEntryPoints.Add(("kernel", name)); break; default: break; } } dependencyFiles = request.GetDependencyFiles(); // Get the output code string rawHlslCode = request.GetCompileRequestedCode(); // TODO: Optimize // Strip some stuff Slang emit's which we don't care about rawHlslCode = rawHlslCode .Replace("#pragma pack_matrix(column_major)\n", "") .Replace("#ifdef SLANG_HLSL_ENABLE_NVAPI\n#include \"nvHLSLExtns.h\"\n#endif\n", "") .Replace("#pragma warning(disable: 3557)\n", ""); // Apply some semantic post processing to it var decls = ShaderParser.ParseTopLevelDeclarations(rawHlslCode); HLSLSlangEditor hlslEditor = new HLSLSlangEditor(rawHlslCode, decls.SelectMany(x => x.Tokens).ToList()); string processedHlslCode = hlslEditor.ApplyEdits(decls); // Replace the code codeBuilder.Append(processedHlslCode); } codeBuilder.AppendLine("#endif"); diagnostics.AddRange(request.GetCollectedDiagnostics()); return codeBuilder.ToString(); } private void AppendKeywordCombinationDirective(StringBuilder sb, HashSet<string> keywords) { HashSet<string> remaining = new HashSet<string>(allKeywords); remaining.ExceptWith(keywords); sb.Append("#if "); foreach (string keyword in keywords) { sb.Append($"defined({keyword}) && "); } foreach (string keyword in remaining) { sb.Append($"!defined({keyword}) && "); } sb.AppendLine("1"); } private Dictionary<string, string> GetPredefinedDirectives() { Dictionary<string, string> directives = new Dictionary<string, string>(); // Base defines directives.Add("SHADER_TARGET", "50"); // sm 5.0 assumed string unityVersion = Application.unityVersion.Replace(".", ""); for (int i = 0; i < unityVersion.Length; i++) { if (!char.IsDigit(unityVersion[i])) { unityVersion = unityVersion[..i]; break; } } directives.Add("UNITY_VERSION ", unityVersion); return directives; } private static HashSet<(string stage, string entryName)> CollectEntryPoints(IEnumerable<HashSet<(string stage, string entryName)>> perVariantEntryPoints) { var allEntryPoints = new HashSet<(string stage, string entryName)>(); foreach (var variantEntryPoints in perVariantEntryPoints) { allEntryPoints.UnionWith(variantEntryPoints); } // If vertex or fragment is missing, add it if (allEntryPoints.Count(x => x.stage.ToLower() == "vertex") == 0) allEntryPoints.Add(("vertex", "vert")); if (allEntryPoints.Count(x => x.stage.ToLower() == "fragment") == 0) allEntryPoints.Add(("fragment", "frag")); return allEntryPoints; } private static string GetFallbackVariant(IEnumerable<(string stage, string entryName)> entryPoints) { StringBuilder fallbackVariantBuilder = new StringBuilder(); fallbackVariantBuilder.AppendLine("#ifndef SLANG_SHADER_VARIANT_FOUND"); foreach ((string stage, string entryName) in entryPoints) { if (stage.ToLower() == "fragment") { fallbackVariantBuilder.AppendLine($"float4 {entryName}(float4 pos : SV_Position) : SV_Target {{ return float4(0,1,1,1); }}"); } else if (stage.ToLower() == "vertex") { fallbackVariantBuilder.AppendLine("#include \"UnityCG.cginc\""); fallbackVariantBuilder.AppendLine($"float4 {entryName}(float4 pos : POSITION) : SV_Position {{ return UnityObjectToClipPos(pos); }}"); } else { fallbackVariantBuilder.AppendLine($"void {entryName}() {{}}"); } } fallbackVariantBuilder.AppendLine("#endif"); return fallbackVariantBuilder.ToString(); } } [SerializeField] public string GeneratedSourceCode; [SerializeField] public SlangShaderVariant[] GeneratedVariants; [SerializeField] public SlangShaderDiagnostic[] Diagnostics; [SerializeField] public string[] AdditionalIncludePaths = new string[0]; [SerializeField] public bool AddVariantsRequested = false; private static HashSet<SlangShaderVariant> GetInitialVariants(AssetImportContext ctx, string assetPath, string shaderSource, ShaderNode shaderNode) { ShaderLabSlangEditor editor = new ShaderLabSlangEditor(assetPath, new string[] { }, new SlangShaderVariant[] { new SlangShaderVariant(EditorUserBuildSettings.activeBuildTarget, SystemInfo.graphicsDeviceType, new HashSet<string>()) }, shaderSource, shaderNode.Tokens); string proxySourceCode = editor.ApplyEdits(shaderNode); Shader variantInfoProxyShader = ShaderUtil.CreateShaderAsset(ctx, proxySourceCode, false); HashSet<SlangShaderVariant> requestedVariants = SlangShaderVariantTracker.GetSlangShaderVariantsForShaderFromCurrentScene(variantInfoProxyShader); ShaderUtil.ClearShaderMessages(variantInfoProxyShader); if (Application.isPlaying) Destroy(variantInfoProxyShader); else DestroyImmediate(variantInfoProxyShader); return requestedVariants; } public static event Action<SlangShaderImporter> OnWillReimport; public override void OnImportAsset(AssetImportContext ctx) { SlangShaderVariantTracker.SlangShaderPaths.Add(ctx.assetPath); string shaderSource = File.ReadAllText(ctx.assetPath); var newDiags = new List<SlangShaderDiagnostic>(); ShaderLabParserConfig config = new ShaderLabParserConfig { ParseEmbeddedHLSL = false }; var shaderNode = ShaderParser.ParseUnityShader(shaderSource, config, out var diagnostics); foreach (var parserDiag in diagnostics) { LogDiagnostic(newDiags, parserDiag.Text, parserDiag.Span.FileName, parserDiag.Location.Line, parserDiag.Kind.HasFlag(DiagnosticFlags.Warning)); } // If we are trying to add variants, don't overwrite with initial ones. if (AddVariantsRequested) { AddVariantsRequested = false; } else { // If we already have some variants tracked, used those as initial variants if (SlangShaderVariantTracker.CurrentlyLoadedSlangShaderVariants.TryGetValue(ctx.assetPath, out var variants)) { GeneratedVariants = variants.ToArray(); } // Otherwise use the null variant (TODO) else { GeneratedVariants = new SlangShaderVariant[] { }; } } EditorUtility.SetDirty(this); ShaderLabSlangEditor editor = new ShaderLabSlangEditor(ctx.assetPath, AdditionalIncludePaths, GeneratedVariants, shaderSource, shaderNode.Tokens); GeneratedSourceCode = editor.ApplyEdits(shaderNode); foreach (var slangDiag in editor.Diagnostics) { string errorLine = slangDiag.Split(new string[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries).First(); var match = Regex.Match(errorLine, @"(.*)\(([0-9]+)\): (.*)$"); if (match.Success) { if (!match.Groups[3].Value.StartsWith("note")) LogDiagnostic(newDiags, match.Groups[3].Value, match.Groups[1].Value, int.Parse(match.Groups[2].Value), !slangDiag.Contains("error")); } else { LogDiagnostic(newDiags, errorLine, "", 0, !slangDiag.Contains("error")); } } var shaderAsset = ShaderUtil.CreateShaderAsset(ctx, GeneratedSourceCode, true); var messages = ShaderUtil.GetShaderMessages(shaderAsset); if (messages.Length > 0) { foreach (var message in messages) { LogDiagnostic(newDiags, message.message, message.file, message.line, message.severity == ShaderCompilerMessageSeverity.Warning); } } ShaderUtil.ClearShaderMessages(shaderAsset); ctx.AddObjectToAsset("Generated shader", shaderAsset); ctx.SetMainObject(shaderAsset); // Check if any generated variants use keywords that don't exist (for example beacause they were removed from the shader). // In this case, we have no choice but to reset to variant tracker, which will trigger a reimport. HashSet<string> allKeywords = Shader.globalKeywords .Select(x => x.name) .Union(shaderAsset.keywordSpace.keywords.Select(x => x.name)) .ToHashSet(); foreach (SlangShaderVariant variant in GeneratedVariants) { if (variant.Keywords .Except(allKeywords) .Any(x => !x.StartsWith("SHADER_API_") && !x.StartsWith("SHADER_TARGET_"))) { SlangShaderVariantTracker.ResetTrackedVariants(); return; // Early out so we don't print diagnostics from this invalid compilation. } } Diagnostics = newDiags.ToArray(); foreach (var diag in Diagnostics) { if (!diag.Warning) { ctx.LogImportError($"{ctx.assetPath}({diag.Line}): {diag.Text}"); } } var filesFromDiags = Diagnostics.Where(x => !string.IsNullOrEmpty(x.File)).Select(x => x.File); foreach (string dependencyFile in editor.DependencyFiles.Concat(filesFromDiags).Distinct()) { ctx.DependsOnSourceAsset(dependencyFile); } // Update any inspectors if (OnWillReimport != null) OnWillReimport(this); } private static void LogDiagnostic(List<SlangShaderDiagnostic> diags, string message, string file, int line, bool warning) { file = file.Replace('\\', '/'); string basePath = Path.GetDirectoryName(Application.dataPath).Replace('\\', '/'); if (file.StartsWith(basePath)) { file = file.Substring(basePath.Length + 1); } diags.Add(new SlangShaderDiagnostic { Text = message, File = file, Line = line, Warning = warning }); } } }
0
0.943866
1
0.943866
game-dev
MEDIA
0.252188
game-dev
0.936742
1
0.936742
cmangos/mangos-tbc
26,545
contrib/dbcEditer/dbcedit.cpp
//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "dbcedit.h" #include "stdio.h" #include "IdGlobal.hpp" #include <inifiles.hpp> #include "TitleFrm.h" #include <dir.h> #include "thOpenSource.h" #include "SearchFrm.h" //#include "SysUtils.hpp" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma resource "*.dfm" TFrmMain* FrmMain; //--------------------------------------------------------------------------- __fastcall TFrmMain::TFrmMain(TComponent* Owner) : TForm(Owner) { OpenOk = false; Term = false; } //--------------------------------------------------------------------------- void __fastcall TFrmMain::btOpenClick(TObject* Sender) { if (OpenDialog1->Execute()) { if (FileExists(OpenDialog1->FileName)) { OpenOk = false; if (thOpen) { thOpen->Terminate(); } thOpen = new thOpenFile(false); //thOpen->Priority = tpTimeCritical; pnFileName->Caption = OpenDialog1->FileName; } else { OpenOk = false; pnFileName->Caption = ""; } } } //--------------------------------------------------------------------------- void __fastcall TFrmMain::btSaveClick(TObject* Sender) { //CurrentOpenFile; if (OpenOk) { SaveToFile(CurrentOpenFile.c_str()); } else { ShowMessage("ļδɣ"); } } //--------------------------------------------------------------------------- void TFrmMain::SaveToFile(const char* pszFileName) { char szFileName[255]; FILE* stream; fnsplit(pszFileName, 0, 0, szFileName, 0); strcat(szFileName, "_new.dbc"); AnsiString NewFileName = ExtractFilePath(Application->ExeName) + szFileName; //=pszFileName; int iFileHandle; //ļ AnsiString iniSetFile = ExtractFilePath(Application->ExeName) + "BcdEditer.ini"; AnsiString SectionName = ExtractFileName(CurrentOpenFile); DWORD w; CopyFileTo(pszFileName, NewFileName); iFileHandle = FileOpen(NewFileName, fmOpenRead | fmOpenWrite); //ļ if ((stream = fopen(CurrentOpenFile.c_str(), "r+")) == NULL) { ShowMessage("ļ"); return; } int iVal; float fVal; bool isFloat; int ColType; FileSeek(iFileHandle, 0x14, 0); TIniFile* ini; ini = new TIniFile(iniSetFile); for (int i = 1; i < sgEdit->RowCount; i++) { for (int j = 1; j < sgEdit->ColCount; j++) { if (j == 1) //ID { iVal = StrToInt(sgEdit->Cells[j][i]); FileWrite(iFileHandle, &iVal, 4); } else { //ColType= ini->ReadInteger(SectionName,"ColType"+IntToStr(j-1),0); //thOpen->ColType[10000]; switch (thOpen->ColType[j]) { case 0: // iVal = StrToFloat(sgEdit->Cells[j][i]); FileWrite(iFileHandle, &iVal, 4); break; case 1: // fVal = StrToFloat(sgEdit->Cells[j][i]); FileWrite(iFileHandle, &fVal, 4); break; case 2: //ı fseek(stream, 0x14 + (i * (sgEdit->ColCount - 1) + (j - 1)) * 4, 0); fread(&iVal, 4, 1, stream); FileWrite(iFileHandle, &iVal, 4); break; default: // iVal = StrToFloat(sgEdit->Cells[j][i]); FileWrite(iFileHandle, &iVal, 4); } } } } FileClose(iFileHandle); fclose(stream); delete ini; ShowMessage("Save To File:" + NewFileName); } void __fastcall TFrmMain::btIntTypeClick(TObject* Sender) { if (OpenOk == true) { AnsiString iniSetFile = ExtractFilePath(Application->ExeName) + "BcdEditer.ini"; AnsiString SectionName = ExtractFileName(CurrentOpenFile); TIniFile* ini; ini = new TIniFile(iniSetFile); ini->WriteInteger(SectionName, "ColType" + IntToStr(sgEdit->Col), 0); delete ini; thOpen->ColType[sgEdit->Col] = 0; //´򿪶Ӧеֵ //OpenFileCol(AnsiString FileName,int ColType); OpenFileCol(CurrentOpenFile, sgEdit->Col, 0); } } //--------------------------------------------------------------------------- void __fastcall TFrmMain::btFloatTypeClick(TObject* Sender) { if (OpenOk == true) { AnsiString iniSetFile = ExtractFilePath(Application->ExeName) + "BcdEditer.ini"; AnsiString SectionName = ExtractFileName(CurrentOpenFile); TIniFile* ini; ini = new TIniFile(iniSetFile); ini->WriteInteger(SectionName, "ColType" + IntToStr(sgEdit->Col), 1); delete ini; thOpen->ColType[sgEdit->Col] = 1; OpenFileCol(CurrentOpenFile, sgEdit->Col, 1); } } //--------------------------------------------------------------------------- void __fastcall TFrmMain::PopupMenu1Popup(TObject* Sender) { if (OpenOk == true) { AnsiString iniSetFile = ExtractFilePath(Application->ExeName) + "BcdEditer.ini"; AnsiString SectionName = ExtractFileName(CurrentOpenFile); int ColType; TIniFile* ini; ini = new TIniFile(iniSetFile); ColType = ini->ReadInteger(SectionName, "ColType" + IntToStr(sgEdit->Col), 0); delete ini; switch (ColType) { case 0: btIntType->Checked = true; btFloatType->Checked = false; btTxtType->Checked = false; break; case 1: btIntType->Checked = false; btFloatType->Checked = true; btTxtType->Checked = false; break; case 2: btIntType->Checked = false; btFloatType->Checked = false; btTxtType->Checked = true; break; default: btIntType->Checked = true; btFloatType->Checked = false; } } } //--------------------------------------------------------------------------- void __fastcall TFrmMain::N1Click(TObject* Sender) { AnsiString iniSetFile = ExtractFilePath(Application->ExeName) + "BcdEditer.ini"; AnsiString SectionName = ExtractFileName(CurrentOpenFile); int ColType; FrmTitle->edTitle->Text = sgEdit->Cells[sgEdit->Col][0]; if (FrmTitle->ShowModal() == mrOk) { TIniFile* ini; ini = new TIniFile(iniSetFile); ini->WriteString(SectionName, "ColTitle" + IntToStr(sgEdit->Col), FrmTitle->edTitle->Text); delete ini; sgEdit->Cells[sgEdit->Col][0] = FrmTitle->edTitle->Text; } } //--------------------------------------------------------------------------- void __fastcall TFrmMain::FormDestroy(TObject* Sender) { if (thOpen) { thOpen->Terminate(); SleepEx(200, 0); } } //--------------------------------------------------------------------------- void __fastcall TFrmMain::ToolButton1Click(TObject* Sender) { bool SeFlag = true; if (FrmSearch->ShowModal() == mrOk) { switch (FrmSearch->rgSI->ItemIndex) { case 0: //; for (int i = sgEdit->ColCount * sgEdit->Row + sgEdit->Col - 1; i > sgEdit->ColCount; i--) { if (i % sgEdit->ColCount != 0) { if (0 == CompareStr(sgEdit->Cells[i - sgEdit->ColCount * (i / sgEdit->ColCount)][i / sgEdit->ColCount], FrmSearch->edSeach->Text)) //ҵ { sgEdit->Col = i - sgEdit->ColCount * i / sgEdit->ColCount; sgEdit->Row = i / sgEdit->ColCount; SeFlag = false; break; } } } if (SeFlag) ShowMessage("Seach TopFind Nothing."); break; case 1: //; for (int i = sgEdit->ColCount * sgEdit->Row + sgEdit->Col + 1; i < sgEdit->ColCount * sgEdit->RowCount; i++) { if (i % sgEdit->ColCount != 0) { if (0 == CompareStr(sgEdit->Cells[i - sgEdit->ColCount * (i / sgEdit->ColCount)][i / sgEdit->ColCount], FrmSearch->edSeach->Text)) //ҵ { sgEdit->Col = i - sgEdit->ColCount * (i / sgEdit->ColCount); sgEdit->Row = i / sgEdit->ColCount; SeFlag = false; break; } } } if (SeFlag) ShowMessage("Seach EndFind Nothing"); break; case 2: //ǰ; for (int i = sgEdit->Row; i > 1; i--) { if (0 == CompareStr(sgEdit->Cells[sgEdit->Col][i], FrmSearch->edSeach->Text)) //ҵ { sgEdit->Row = i; SeFlag = false; break; } } if (SeFlag) ShowMessage("Seach col topFind Nothing"); break; case 3: //ǰ; for (int i = sgEdit->Row; i < sgEdit->RowCount; i++) { if (0 == CompareStr(sgEdit->Cells[sgEdit->Col][i], FrmSearch->edSeach->Text)) //ҵ { sgEdit->Row = i; SeFlag = false; break; } } if (SeFlag) ShowMessage("Seach col endFind Nothing."); break; } } } //--------------------------------------------------------------------------- void __fastcall TFrmMain::sgEditKeyDown(TObject* Sender, WORD& Key, TShiftState Shift) { bool SeFlag = true; if (Key == VK_F3) { switch (FrmSearch->rgSI->ItemIndex) { case 0: //; for (int i = sgEdit->ColCount * sgEdit->Row + sgEdit->Col - 1; i > sgEdit->ColCount; i--) { if (i % sgEdit->ColCount != 0) { if (0 == CompareStr(sgEdit->Cells[i - sgEdit->ColCount * (i / sgEdit->ColCount)][i / sgEdit->ColCount], FrmSearch->edSeach->Text)) //ҵ { sgEdit->Col = i - sgEdit->ColCount * i / sgEdit->ColCount; sgEdit->Row = i / sgEdit->ColCount; SeFlag = false; break; } } } if (SeFlag) ShowMessage("Seach TopFind Nothing."); break; case 1: //; for (int i = sgEdit->ColCount * sgEdit->Row + sgEdit->Col + 1; i < sgEdit->ColCount * sgEdit->RowCount; i++) { if (i % sgEdit->ColCount != 0) { if (0 == CompareStr(sgEdit->Cells[i - sgEdit->ColCount * (i / sgEdit->ColCount)][i / sgEdit->ColCount], FrmSearch->edSeach->Text)) //ҵ { sgEdit->Col = i - sgEdit->ColCount * (i / sgEdit->ColCount); sgEdit->Row = i / sgEdit->ColCount; SeFlag = false; break; } } } if (SeFlag) ShowMessage("Seach EndFind Nothing."); break; case 2: //ǰ; for (int i = sgEdit->Row; i > 1; i--) { if (0 == CompareStr(sgEdit->Cells[sgEdit->Col][i], FrmSearch->edSeach->Text)) //ҵ { sgEdit->Row = i; SeFlag = false; break; } } if (SeFlag) ShowMessage("Seach col TopFind Nothing."); break; case 3: //ǰ; for (int i = sgEdit->Row; i < sgEdit->RowCount; i++) { if (0 == CompareStr(sgEdit->Cells[sgEdit->Col][i], FrmSearch->edSeach->Text)) //ҵ { sgEdit->Row = i; SeFlag = false; break; } } if (SeFlag) ShowMessage("Seach col endFind Nothing."); break; } } } //--------------------------------------------------------------------------- void __fastcall TFrmMain::sgEditSelectCell(TObject* Sender, int ACol, int ARow, bool& CanSelect) { // } //--------------------------------------------------------------------------- void __fastcall TFrmMain::OpenFileCol(AnsiString FileName, int ColIndex, int ColType) { int iFileHandle; //ļ char Txtbuf[255]; int iVal; float fVal; FILE* stream; long curpos, length; DWORD dwRows, dwCols, dwRowLen, dwTextLen; DWORD dwTextStartPos; char* pTextPtr ; if ((stream = fopen(FileName.c_str(), "r+")) == NULL) { ShowMessage("Open File Error"); return; } curpos = ftell(stream); fseek(stream, 0L, SEEK_END); length = ftell(stream); switch (ColType) { case 0: //ֵ Int for (int i = 0; i < sgEdit->RowCount - 1; i++) { fseek(stream, 0x14 + (i * (sgEdit->ColCount - 1) + (ColIndex - 1)) * 4, 0); fread(&iVal, 4, 1, stream); sgEdit->Cells[ColIndex][i + 1] = IntToStr(iVal); } break; case 1: //ֵ Float for (int i = 0; i < sgEdit->RowCount - 1; i++) { fseek(stream, 0x14 + (i * (sgEdit->ColCount - 1) + (ColIndex - 1)) * 4, 0); fread(&fVal, 4, 1, stream); sgEdit->Cells[ColIndex][i + 1] = FloatToStr(fVal); } break; case 2: //ı Text fseek(stream, 0x4, 0); fread(&iVal, 4, 1, stream); dwRows = iVal; fread(&iVal, 4, 1, stream); dwCols = iVal; fread(&iVal, 4, 1, stream); dwRowLen = iVal; fread(&iVal, 4, 1, stream); dwTextLen = iVal; dwTextStartPos = dwRows * dwRowLen + 20; for (int i = 0; i < sgEdit->RowCount - 1; i++) { fseek(stream, 0x14 + (i * (sgEdit->ColCount - 1) + (ColIndex - 1)) * 4, 0); fread(&iVal, 4, 1, stream); sgEdit->Cells[ColIndex][i + 1] = IntToStr(iVal); if (dwTextStartPos + iVal < length) { fseek(stream, dwTextStartPos + iVal, 0); fread(Txtbuf, 1, 255, stream); //pTextPtr = pBuff + dwTextStartPos + lTemp; sgEdit->Cells[ColIndex][i + 1] = Txtbuf; } else { sgEdit->Cells[ColIndex][i + 1] = "This Col Not Text!"; } } break; } fclose(stream); } void __fastcall TFrmMain::Timer1Timer(TObject* Sender) { if (OpenOk) { lbOpState->Caption = "Open File Ok."; } else { lbOpState->Caption = "Open Now....."; } } //--------------------------------------------------------------------------- //ǰд޸ļ void __fastcall TFrmMain::N4Click(TObject* Sender) { if (!thOpen) return; int iFileHandle; //ļ char buf[4]; int iVal; float fVal; FILE* stream; /* if ((stream = fopen(CurrentOpenFile.c_str(), "r+")) == NULL) { ShowMessage("ļ"); return; } */ iFileHandle = FileOpen(CurrentOpenFile, fmOpenRead | fmOpenWrite); //ļ switch (thOpen->ColType[sgEdit->Col]) { case 0: //ֵ //for(int i=0;i<sgEdit->RowCount-1;i++){ /* fseek(stream, 0x14+((sgEdit->Row-1)*(sgEdit->ColCount-1)+(sgEdit->Col-1))*4, 0); iVal=StrToInt(sgEdit->Cells[sgEdit->Col][sgEdit->Row]); memcpy(buf, &iVal, 4); for(int i=0;i<4;i++) fwrite(buf+i, 1, 1, stream); */ iVal = StrToInt(sgEdit->Cells[sgEdit->Col][sgEdit->Row]); memcpy(buf, &iVal, 4); FileSeek(iFileHandle, 0x14 + ((sgEdit->Row - 1) * (sgEdit->ColCount - 1) + (sgEdit->Col - 1)) * 4, 0); FileWrite(iFileHandle, buf, 4); //} break; case 1: //ֵ //fseek(stream, 0x14+((sgEdit->Row-1)*(sgEdit->ColCount-1)+(sgEdit->Col-1))*4, 0); //fVal=StrToFloat(sgEdit->Cells[sgEdit->Col][sgEdit->Row]); //fwrite(&fVal, 4, 1, stream); fVal = StrToFloat(sgEdit->Cells[sgEdit->Col][sgEdit->Row]); memcpy(buf, &fVal, 4); FileSeek(iFileHandle, 0x14 + ((sgEdit->Row - 1) * (sgEdit->ColCount - 1) + (sgEdit->Col - 1)) * 4, 0); FileWrite(iFileHandle, buf, 4); break; case 2: //ıд break; } // fclose(stream); FileClose(iFileHandle); } //--------------------------------------------------------------------------- void __fastcall TFrmMain::btTxtTypeClick(TObject* Sender) { if (OpenOk == true) { AnsiString iniSetFile = ExtractFilePath(Application->ExeName) + "BcdEditer.ini"; AnsiString SectionName = ExtractFileName(CurrentOpenFile); TIniFile* ini; ini = new TIniFile(iniSetFile); ini->WriteInteger(SectionName, "ColType" + IntToStr(sgEdit->Col), 2); delete ini; thOpen->ColType[sgEdit->Col] = 2; OpenFileCol(CurrentOpenFile, sgEdit->Col, 2); } } //--------------------------------------------------------------------------- void __fastcall TFrmMain::ToolButton3Click(TObject* Sender) { int OldCol; int OldRow; OldRow = sgEdit->Row; OldCol = sgEdit->Col; if (sgEdit->FixedCols == 1) { sgEdit->FixedCols = 2; if (OldCol != 1) sgEdit->Col = OldCol; sgEdit->Row = OldRow; } else { sgEdit->FixedCols = 1; sgEdit->Row = OldRow; if (OldCol != 2) sgEdit->Col = OldCol; } } //--------------------------------------------------------------------------- void __fastcall TFrmMain::btRowSaveClick(TObject* Sender) { if (OpenOk == false) return; int iFileHandle; //ļ char Txtbuf[255]; int iVal; char buf[4]; float fVal; FILE* stream; long curpos, length; DWORD dwRows, dwCols, dwRowLen, dwTextLen; DWORD dwTextStartPos; char* pTextPtr ; //if ((stream = fopen(CurrentOpenFile.c_str(), "r+")) // == NULL) //{ // ShowMessage("ļ"); // return; //} //curpos = ftell(stream); //fseek(stream, 0L, SEEK_END); //length = ftell(stream); iFileHandle = FileOpen(CurrentOpenFile, fmOpenRead | fmOpenWrite); //ļ for (int i = 0; i < sgEdit->ColCount - 1; i++) { switch (thOpen->ColType[i]) { case 0: //ֵ sgEdit->Row //fseek(stream, 0x14+((sgEdit->Row-1)*(sgEdit->ColCount-1)+i)*4, 0); //iVal=StrToInt(sgEdit->Cells[i+1][sgEdit->Row]); //fwrite(&iVal, 4, 1, stream); iVal = StrToInt(sgEdit->Cells[i + 1][sgEdit->Row]); memcpy(buf, &iVal, 4); FileSeek(iFileHandle, 0x14 + ((sgEdit->Row - 1) * (sgEdit->ColCount - 1) + i) * 4, 0); FileWrite(iFileHandle, buf, 4); break; case 1: //ֵ //fseek(stream, 0x14+((sgEdit->Row-1)*(sgEdit->ColCount-1)+i)*4, 0); //fVal=StrToFloat(sgEdit->Cells[i+1][sgEdit->Row]); //fwrite(&fVal, 4, 1, stream); fVal = StrToFloat(sgEdit->Cells[i + 1][sgEdit->Row]); memcpy(buf, &fVal, 4); FileSeek(iFileHandle, 0x14 + ((sgEdit->Row - 1) * (sgEdit->ColCount - 1) + i) * 4, 0); FileWrite(iFileHandle, buf, 4); break; case 2: //ı break; } } //fclose(stream); FileClose(iFileHandle); ShowMessage("The " + IntToStr(sgEdit->Row) + " Row Write Ok!"); } //--------------------------------------------------------------------------- void __fastcall TFrmMain::btColSaveClick(TObject* Sender) { if (OpenOk == false) return; int iFileHandle; //ļ char Txtbuf[255]; int iVal; char buf[4]; float fVal; FILE* stream; long curpos, length; DWORD dwRows, dwCols, dwRowLen, dwTextLen; DWORD dwTextStartPos; char* pTextPtr ; iFileHandle = FileOpen(CurrentOpenFile, fmOpenRead | fmOpenWrite); //ļ //if ((stream = fopen(CurrentOpenFile.c_str(), "r+")) // == NULL) //{ // ShowMessage("ļ"); // return; //} //curpos = ftell(stream); //fseek(stream, 0L, SEEK_END); //length = ftell(stream); switch (thOpen->ColType[sgEdit->Col]) { case 0: //ֵ for (int i = 0; i < sgEdit->RowCount - 1; i++) { //fseek(stream, 0x14+(i*(sgEdit->ColCount-1)+(sgEdit->Col-1))*4, 0); //iVal=StrToInt(sgEdit->Cells[sgEdit->Col][i+1]); //fwrite(&iVal, 4, 1, stream); iVal = StrToInt(sgEdit->Cells[sgEdit->Col][i + 1]); memcpy(buf, &iVal, 4); FileSeek(iFileHandle, 0x14 + (i * (sgEdit->ColCount - 1) + (sgEdit->Col - 1)) * 4, 0); FileWrite(iFileHandle, buf, 4); } break; case 1: //ֵ for (int i = 0; i < sgEdit->RowCount - 1; i++) { //fseek(stream, 0x14+(i*(sgEdit->ColCount-1)+(sgEdit->Col-1))*4, 0); //fVal=StrToFloat(sgEdit->Cells[sgEdit->Col][i+1]); //fwrite(&fVal, 4, 1, stream); fVal = StrToFloat(sgEdit->Cells[sgEdit->Col][i + 1]); memcpy(buf, &fVal, 4); FileSeek(iFileHandle, 0x14 + (i * (sgEdit->ColCount - 1) + (sgEdit->Col - 1)) * 4, 0); FileWrite(iFileHandle, buf, 4); } break; case 2: //ı break; } //fclose(stream); FileClose(iFileHandle); ShowMessage("The " + IntToStr(sgEdit->Col) + "Col Write Ok!"); } //--------------------------------------------------------------------------- void __fastcall TFrmMain::btRowClearClick(TObject* Sender) { if (OpenOk == false) return; int iFileHandle; //ļ char Txtbuf[255]; int iVal; float fVal; FILE* stream; long curpos, length; DWORD dwRows, dwCols, dwRowLen, dwTextLen; DWORD dwTextStartPos; char* pTextPtr ; if ((stream = fopen(CurrentOpenFile.c_str(), "r+")) == NULL) { ShowMessage("Open File Error!"); return; } curpos = ftell(stream); fseek(stream, 0L, SEEK_END); length = ftell(stream); for (int i = 1; i < sgEdit->ColCount - 1; i++) { switch (thOpen->ColType[i]) { case 0: //ֵ sgEdit->Row //fseek(stream, 0x14+(sgEdit->Row*(sgEdit->ColCount-1)+i)*4, 0); //iVal=StrToInt(sgEdit->Cells[i+1][sgEdit->Row]); //fwrite(&iVal, 4, 1, stream); sgEdit->Cells[i + 1][sgEdit->Row] = "0"; break; case 1: //ֵ //fseek(stream, 0x14+(sgEdit->Row*(sgEdit->ColCount-1)+i)*4, 0); //fVal=StrToFloat(sgEdit->Cells[i+1][sgEdit->Row]); //fwrite(&fVal, 4, 1, stream); sgEdit->Cells[i + 1][sgEdit->Row] = "0"; break; case 2: //ı break; } } fclose(stream); } //--------------------------------------------------------------------------- void __fastcall TFrmMain::btColClearClick(TObject* Sender) { if (OpenOk == false) return; int iFileHandle; //ļ char Txtbuf[255]; int iVal; float fVal; FILE* stream; long curpos, length; DWORD dwRows, dwCols, dwRowLen, dwTextLen; DWORD dwTextStartPos; char* pTextPtr ; if ((stream = fopen(CurrentOpenFile.c_str(), "r+")) == NULL) { ShowMessage("Open File Error!"); return; } curpos = ftell(stream); fseek(stream, 0L, SEEK_END); length = ftell(stream); switch (thOpen->ColType[sgEdit->Col]) { case 0: //ֵ for (int i = 0; i < sgEdit->RowCount - 1; i++) { //fseek(stream, 0x14+(i*(sgEdit->ColCount-1)+(ColIndex-1))*4, 0); //iVal=StrToInt(sgEdit->Cells[ColIndex][i+1]); //fwrite(&iVal, 4, 1, stream); sgEdit->Cells[sgEdit->Col][i + 1] = "0"; } break; case 1: //ֵ for (int i = 0; i < sgEdit->RowCount - 1; i++) { //fseek(stream, 0x14+(i*(sgEdit->ColCount-1)+(ColIndex-1))*4, 0); //fVal=StrToFloat(sgEdit->Cells[ColIndex][i+1]); //fwrite(&fVal, 4, 1, stream); sgEdit->Cells[sgEdit->Col][i + 1] = "0"; } break; case 2: //ı break; } fclose(stream); } //--------------------------------------------------------------------------- void __fastcall TFrmMain::ToolButton4Click(TObject* Sender) { AnsiString Cmd; Cmd = "calc.exe"; WinExec(Cmd.c_str(), SW_SHOWNORMAL); } //---------------------------------------------------------------------------
0
0.787798
1
0.787798
game-dev
MEDIA
0.261576
game-dev
0.982519
1
0.982519
LiteLDev/LiteLoaderBDS
1,071
LiteLoader/include/llapi/mc/AbsorptionMobEffect.hpp
/** * @file AbsorptionMobEffect.hpp * */ #pragma once #define AUTO_GENERATED #include "llapi/Global.h" #include "MobEffect.hpp" #define BEFORE_EXTRA // Include Headers or Declare Types Here #undef BEFORE_EXTRA /** * @brief MC class AbsorptionMobEffect. * */ class AbsorptionMobEffect : public MobEffect { #define AFTER_EXTRA // Add Member There #undef AFTER_EXTRA #ifndef DISABLE_CONSTRUCTOR_PREVENTION_ABSORPTIONMOBEFFECT public: class AbsorptionMobEffect& operator=(class AbsorptionMobEffect const &) = delete; AbsorptionMobEffect(class AbsorptionMobEffect const &) = delete; AbsorptionMobEffect() = delete; #endif public: /** * @vftbl 0 * @symbol __unk_vfn_0 */ virtual void __unk_vfn_0(); /** * @vftbl 1 * @symbol ?applyEffects\@AbsorptionMobEffect\@\@UEBAXPEAVActor\@\@HH\@Z */ virtual void applyEffects(class Actor *, int, int) const; /** * @vftbl 2 * @symbol ?removeEffects\@AbsorptionMobEffect\@\@UEAAXPEAVActor\@\@\@Z */ virtual void removeEffects(class Actor *); };
0
0.701431
1
0.701431
game-dev
MEDIA
0.441085
game-dev
0.533682
1
0.533682
taisei-project/taisei
4,140
src/stages/stage5/spells/static_bomb.c
/* * This software is licensed under the terms of the MIT License. * See COPYING for further information. * --- * Copyright (c) 2011-2024, Lukas Weber <laochailan@web.de>. * Copyright (c) 2012-2024, Andrei Alexeyev <akari@taisei-project.org>. */ #include "spells.h" TASK(slave_ball_shot, { BoxedIkuSlave slave; }) { IkuSlave *slave = TASK_BIND(ARGS.slave); int difficulty = difficulty_value(6, 5, 4, 3); for(int i = 0; i < (210 / difficulty); i++) { PROJECTILE( .proto = pp_soul, .pos = slave->pos, .color = RGBA(0, 0.2, 1, 0), .angle_delta = -M_TAU/230, .angle = rng_angle(), .flags = PFLAG_MANUALANGLE, .opacity = 0.95, .move = move_asymptotic_simple(4 * cdir(0.5 * i), 3) ); play_sfx("shot_special1"); WAIT(difficulty); } } TASK(slave_laser_shot, { BoxedIkuSlave slave; int delay; }) { IkuSlave *slave = TASK_BIND(ARGS.slave); WAIT(ARGS.delay); int difficulty = difficulty_value(90, 80, 70, 60); int amount = 800 - ARGS.delay; for(int x = 0; x < (amount / difficulty); x++) { real rand = rng_sreal(); create_laserline(slave->pos, 10 * cnormalize(global.plr.pos - slave->pos) * cdir(0.04 * rand), 60, 120, RGBA(1, 0.3, 1, 0)); WAIT(45); play_sfx_ex("laser1", 0, true); WAIT(difficulty - 45); } } TASK(slave_bullet_shot, { BoxedIkuSlave slave; }) { IkuSlave *slave = TASK_BIND(ARGS.slave); int difficulty = difficulty_value(5, 4, 3, 2); for(int x = 0; x < (520 / difficulty); x++) { for(int i = 1; i >= -1; i -= 2) { real rand = rng_real(); PROJECTILE( .proto = pp_rice, .pos = slave->pos, .color = RGB(1,0,0), .move = move_asymptotic_simple(i * 2 * cdir(-0.3 * x + rand), 3), ); play_sfx("shot3"); } WAIT(difficulty); } } TASK(slave_explode, { BoxedIkuSlave slave; }) { IkuSlave *slave = TASK_BIND(ARGS.slave); common_charge(120, &slave->pos, 0, &slave->color); RNG_ARRAY(ray_rand, 5); PARTICLE( .sprite = "blast_huge_rays", .color = color_add(RGBA(0, 0.2 + 0.5 * vrng_real(ray_rand[0]), 0.5 + 0.5 * vrng_real(ray_rand[1]), 0.0), RGBA(1, 1, 1, 0)), .pos = slave->pos, .timeout = 60 + 10 * vrng_real(ray_rand[2]), .draw_rule = pdraw_timeout_fade(1, 0), .angle = vrng_angle(ray_rand[4]), .layer = LAYER_PARTICLE_HIGH | 0x42, .flags = PFLAG_REQUIREDPARTICLE, ); RNG_ARRAY(halo_rand, 5); PARTICLE( .sprite = "blast_huge_halo", .pos = slave->pos, .color = RGBA(0.3 * vrng_real(halo_rand[0]), 0.3 * vrng_real(halo_rand[1]), 1.0, 0), .timeout = 200 + 24 * vrng_real(halo_rand[2]), .draw_rule = pdraw_timeout_fade(1, 0), .angle = vrng_angle(halo_rand[4]), .layer = LAYER_PARTICLE_HIGH | 0x41, .flags = PFLAG_REQUIREDPARTICLE, ); stage_shake_view(420); play_sfx("boom"); } TASK(slave, { cmplx pos; int number; }) { IkuSlave *slave = stage5_midboss_slave(ARGS.pos); MoveParams move = move_from_towards( slave->pos, VIEWPORT_W / 4 + ARGS.number * 40 + 2.0 * I * 90 - 5 * ARGS.number * 2.0 * I, 0.03 ); INVOKE_TASK_WHEN(&slave->events.despawned, common_drop_items, &slave->pos, { .power = 5, .points = 5, .life = (ARGS.number == 1) ? 1 : 0 }); INVOKE_SUBTASK(iku_slave_move, { .slave = ENT_BOX(slave), .move = move, }); INVOKE_SUBTASK_DELAYED(100, slave_ball_shot, { .slave = ENT_BOX(slave) }); INVOKE_SUBTASK_DELAYED(200, slave_bullet_shot, { .slave = ENT_BOX(slave) }); if(global.diff > D_Normal) { INVOKE_SUBTASK_DELAYED(600, slave_ball_shot, { .slave = ENT_BOX(slave) }); } INVOKE_SUBTASK(slave_laser_shot, { .slave = ENT_BOX(slave), .delay = difficulty_value(500, 470, 440, 410)}); INVOKE_SUBTASK_DELAYED(770, slave_explode, { .slave = ENT_BOX(slave) }); WAIT(900); coevent_signal_once(&slave->events.despawned); } DEFINE_EXTERN_TASK(stage5_midboss_static_bomb) { STAGE_BOOKMARK(midspell1); Boss *b = INIT_BOSS_ATTACK(&ARGS); b->move = move_from_towards(b->pos, VIEWPORT_W / 2 - VIEWPORT_H * I, 0.01); BEGIN_BOSS_ATTACK(&ARGS); WAIT(50); for(int x = 0; x < 3; x++) { INVOKE_TASK(slave, { .pos = b->pos, .number = x, }); WAIT(10); } WAIT(300); b->move = move_linear(3); // move off to the side so items don't appear for the player }
0
0.767476
1
0.767476
game-dev
MEDIA
0.797578
game-dev
0.915416
1
0.915416
MonoGame-Extended/Monogame-Extended
1,255
source/MonoGame.Extended/ECS/ComponentType.cs
using System; namespace MonoGame.Extended.ECS { //public class ComponentType : IEquatable<ComponentType> //{ // public ComponentType(Type type, int id) // { // Type = type; // Id = id; // } // public Type Type { get; } // public int Id { get; } // public bool Equals(ComponentType other) // { // if (ReferenceEquals(null, other)) return false; // if (ReferenceEquals(this, other)) return true; // return Id == other.Id; // } // public override bool Equals(object obj) // { // if (ReferenceEquals(null, obj)) return false; // if (ReferenceEquals(this, obj)) return true; // if (obj.GetType() != GetType()) return false; // return Equals((ComponentType) obj); // } // public override int GetHashCode() // { // return Id; // } // public static bool operator ==(ComponentType left, ComponentType right) // { // return Equals(left, right); // } // public static bool operator !=(ComponentType left, ComponentType right) // { // return !Equals(left, right); // } //} }
0
0.616174
1
0.616174
game-dev
MEDIA
0.620206
game-dev
0.754356
1
0.754356
acmeism/RosettaCodeData
8,681
Task/Minesweeper-game/FreeBASIC/minesweeper-game.basic
'--- Declaration of global variables --- Type mina Dim mina As Byte Dim flag As Byte Dim ok As Byte Dim numero As Byte End Type Dim Shared As Integer size = 16, NX = 20, NY = 20 Dim Shared As Double mina = 0.10 Dim Shared tablero(NX+1,NY+1) As mina Dim Shared As Integer GameOver, ddx, ddy, kolor, nbDESCANSO Dim Shared As Double temps Dim As String tecla '--- SUBroutines and FUNCtions --- Sub VerTodo Dim As Integer x, y For x = 1 To NX For y = 1 To NY With tablero(x,y) If .mina = 1 Or .flag > 0 Then .ok = 1 End With Next y Next x End Sub Sub ShowGrid Dim As Integer x, y Line(ddx-1,ddy-1)-(1+ddx+size*NX,1+ddy+size*NY),&hFF0000,B For x = 1 To NX For y = 1 To NY With tablero(x,y) 'Si la casilla no se hace click If .ok = 0 Then Line(ddx+x*size,ddy+y*size)-(ddx+(x-1)*size,ddy+(y-1)*size),&h888888,BF Line(ddx+x*size,ddy+y*size)-(ddx+(x-1)*size,ddy+(y-1)*size),&h444444,B 'bandera verde If .flag = 1 Then Circle (ddx+x*size-size/2,ddy+y*size-size/2),size/4,&h00FF00,,,,F Circle (ddx+x*size-size/2,ddy+y*size-size/2),size/4,&h0 End If 'bandera azul If .flag = 2 Then Circle (ddx+x*size-size/2,ddy+y*size-size/2),size/4,&h0000FF,,,,F Circle (ddx+x*size-size/2,ddy+y*size-size/2),size/4,&h0 End If 'Si se hace clic Else If .mina = 0 Then If .numero > 0 Then Select Case .numero Case 1: kolor = &h3333FF Case 2: kolor = &h33FF33 Case 3: kolor = &hFF3333 Case 4: kolor = &hFFFF33 Case 5: kolor = &h33FFFF Case 6: kolor = &hFF33FF Case 7: kolor = &h999999 Case 8: kolor = &hFFFFFF End Select Draw String(ddx+x*size-size/1.5,ddy+y*size-size/1.5),Str(.numero),kolor End If If GameOver = 1 Then 'Si no hay Mina y una bandera verde >> rojo completo If .flag = 1 Then Circle (ddx+x*size-size/2,ddy+y*size-size/2),size/4,&h330000,,,,F Circle (ddx+x*size-size/2,ddy+y*size-size/2),size/4,&h555555 End If 'Si no hay Mina y una bandera azul >> azul oscuro If .flag = 2 Then Circle (ddx+x*size-size/2,ddy+y*size-size/2),size/4,&h000033,,,,F Circle (ddx+x*size-size/2,ddy+y*size-size/2),size/4,&h555555 End If End If Else 'Si hay una Mina sin bandera >> rojo If .flag = 0 Then Circle (ddx+x*size-size/2,ddy+y*size-size/2),size/4,&hFF0000,,,,F Circle (ddx+x*size-size/2,ddy+y*size-size/2),size/4,&hFFFF00 Else 'Si hay una Mina con bandera verde >>> verde If .flag = 1 Then Circle (ddx+x*size-size/2,ddy+y*size-size/2),size/4,&h00FF00,,,,F Circle (ddx+x*size-size/2,ddy+y*size-size/2),size/4,&hFFFF00 End If If .flag = 2 Then 'Si hay una Mina con bandera azul >>>> verde oscuro Circle (ddx+x*size-size/2,ddy+y*size-size/2),size/4,&h003300,,,,F Circle (ddx+x*size-size/2,ddy+y*size-size/2),size/4,&hFFFF00 End If End If End If End If End With Next y Next x End Sub Sub Calcul Dim As Integer x, y For x = 1 To NX For y = 1 To NY tablero(x,y).numero = _ Iif(tablero(x+1,y).mina=1,1,0) + Iif(tablero(x-1,y).mina=1,1,0) + _ Iif(tablero(x,y+1).mina=1,1,0) + Iif(tablero(x,y-1).mina=1,1,0) + _ Iif(tablero(x+1,y-1).mina=1,1,0) + Iif(tablero(x+1,y+1).mina=1,1,0) + _ Iif(tablero(x-1,y-1).mina=1,1,0) + Iif(tablero(x-1,y+1).mina=1,1,0) Next y Next x End Sub Sub Inicio size = 20 If NX > 720/size Then size = 720/NX If NY > 520/size Then size = 520/NY Redim tablero(NX+1,NY+1) As mina Dim As Integer x, y For x = 1 To NX For y = 1 To NY With tablero(x,y) .mina = Iif(Rnd > (1-mina), 1, 0) .ok = 0 .flag = 0 .numero = 0 End With Next y Next x ddx = (((800/size)-NX)/2)*size ddy = (((600/size)-NY)/2)*size Calcul End Sub Function isGameOver As Integer Dim As Integer x, y, nbMINA, nbOK, nbAZUL, nbVERT For x = 1 To NX For y = 1 To NY If tablero(x,y).ok = 1 And tablero(X,y).mina = 1 Then Return -1 End If If tablero(x,y).ok = 0 And tablero(x,y).flag = 1 And tablero(X,y).mina = 1 Then nbOK += 1 End If If tablero(X,y).mina = 1 Then nbMINA + =1 End If If tablero(X,y).flag = 2 Then nbAZUL += 1 'End If Elseif tablero(X,y).flag = 1 Then nbVERT += 1 End If Next y Next x If nbMINA = nbOK And nbAZUL = 0 Then Return 1 nbDESCANSO = nbMINA - nbVERT End Function Sub ClicRecursivo(ZX As Integer, ZY As Integer) If tablero(ZX,ZY).ok = 1 Then Exit Sub If tablero(ZX,ZY).flag > 0 Then Exit Sub 'CLICK tablero(ZX,ZY).ok = 1 If tablero(ZX,ZY).mina = 1 Then Exit Sub If tablero(ZX,ZY).numero > 0 Then Exit Sub If ZX > 0 And ZX <= NX And ZY > 0 And ZY <= NY Then ClicRecursivo(ZX+1,ZY) ClicRecursivo(ZX-1,ZY) ClicRecursivo(ZX,ZY+1) ClicRecursivo(ZX,ZY-1) ClicRecursivo(ZX+1,ZY+1) ClicRecursivo(ZX+1,ZY-1) ClicRecursivo(ZX-1,ZY+1) ClicRecursivo(ZX-1,ZY-1) End If End Sub '--- Main Program --- Screenres 800,600,24 Windowtitle"Minesweeper game" Randomize Timer Cls Dim As Integer mx, my, mb, fmb, ZX, ZY, r, tt Dim As Double t Inicio GameOver = 1 Do tecla = Inkey If GameOver = 1 Then Select Case Ucase(tecla) Case Chr(Asc("X")) NX += 5 If NX > 80 Then NX = 10 Inicio Case Chr(Asc("Y")) NY += 5 If NY > 60 Then NY = 10 Inicio Case Chr(Asc("M")) mina += 0.01 If mina > 0.26 Then mina = 0.05 Inicio Case Chr(Asc("S")) Inicio GameOver = 0 temps = Timer End Select End If Getmouse mx,my,,mb mx -= ddx-size my -= ddy-size ZX = (MX-size/2)/size ZY = (MY-size/2)/size If GameOver = 0 And zx > 0 And zx <= nx And zy > 0 And zy <= ny Then If MB=1 And fmb=0 Then ClicRecursivo(ZX,ZY) If MB=2 And fmb=0 Then tablero(ZX,ZY).flag += 1 If tablero(ZX,ZY).flag > 2 Then tablero(ZX,ZY).flag = 0 End If fmb = mb End If r = isGameOver If r = -1 And GameOver = 0 Then VerTodo GameOver = 1 End If If r = 1 And GameOver = 0 Then GameOver = 1 If GameOver = 0 Then tt = Timer-temps Screenlock Cls ShowGrid If GameOver = 0 Then Draw String (210,4), "X:" & NX & " Y:" & NY & " MINA:" & Int(mina*100) & "% TIMER : " & Int(TT) & " S REMAINING:" & nbDESCANSO,&hFFFF00 Else Draw String (260,4), "PRESS: 'S' TO START X,Y,M TO SIZE" ,&hFFFF00 Draw String (330,17), "X:" & NX & " Y:" & NY & " MINA:" & Int(mina*100) & "%" ,&hFFFF00 If r = 1 Then t += 0.01 If t > 1000 Then t = 0 Draw String (320,280+Cos(t)*100),"!! CONGRATULATION !!",&hFFFF00 End If End If Screenunlock Loop Until tecla = Chr(27) Bsave "Minesweeper.bmp",0 End
0
0.873145
1
0.873145
game-dev
MEDIA
0.704489
game-dev
0.992168
1
0.992168
Anyrainel/DHConsole
4,287
docs/server_commands.md
# Commands - account: `/account create <account_name>`: create an account `@<account_uid>`: set the context to be the account, required before other commands, otherwise commands will fail due to no account context - avatar: Set the properties of the characters player owned `/avatar level <avatar_id> <avatar_level>`: set the level of the character `/avatar talent <avatar_id> <talent_level>`: set all skills level of the character `/avatar rank <avatar_id> <rank>`: set the eidolon rank of the character - give: Give player items, item id can be avatar id, but cant set level, talent, rank `/give <item_id> [x<count>] [l<level>] [r<rank>]`: give item or character to player, number of count, and of level or rank when applies - hero: Switch the gender/type of the main character `/hero gender <gender_id>`: switch the gender of the main character, 1 means male, 2 means female. Notice: Switch gender will clear all the paths and talents of main character, this operation is irreversible! `/hero type <type_id>`: switch the type of the main character, 8001 means Destruction, 8003 means Preservation, 8005 means Harmony. - mission: Manage player's missions `/mission running`: get the running mission and possible stuck missions `/mission finish <sub_mission_id>`: finish the sub mission `/mission finishmain <main_mission_id>`: finish the main mission `/mission reaccept <main_mission_id>`: re-accept given main mission - raid: Manage player's temporary scene `/raid leave`: leave temporary scene - relic: Manage player's relics `/relic <relic_id> <main_affix_id> <sub_affix_id1:sub_affix_level> <sub_affix_id2:sub_affix_level> <sub_affix_id3:sub_affix_level> <sub_affix_id4:sub_affix_level> l<level> x<amount>`: craft a specified relic. - build: build relics for a character `/build cur`: build the currently controlling character's relics using recommended set and affixes `/build all`: build all characters' relics using recommended set and affixes `/build <avatar_id>`: build the specified character's relics using recommended set and affixes - remove: remove unwanted items from inventory to avoid clutter `/remove relics`: remove all relics currently not equipped by any character `/remove <avatar_id>`: unequip everything from that character, and remove the specified avatar - reload: Reload specified configuration `/reload banner`: reload gacha pool `/reload activity`: reload events - scene: Manage player scenes `/scene prop <prop_id> <prop_state>`: set the state of a prop. For a list of states, refer to Common/Enums/Scene/PropStateEnum.cs `/scene unlockall`: unlock all props in the scene (i.e., set all props that can be opened to the 'open' state). This command may cause the game to load to about 90%. Use '/scene reset <floorId>' to resolve this issue. `/scene change <entry_id>`: enter a specified scene. For EntryId, refer to Resources/MapEntrance.json `/scene reload`: reload the current scene and return to the initial position. `/scene reset <floor_id>`: reset the state of all props in the specified scene. For the current FloorId, use '/scene cur'. - setlevel: Set player level `/setlevel <level>`: set the level of the player - unlockall: Unlock the objects in given category `/unlockall mission`: finish all missions, and the target player will be kicked, after re-login, the player may be stuck in tutorial, please use with caution `/unlockall tutorial`: unlock all tutorials, and the target player will be kicked, used for being stuck in some pages `/unlockall rogue`: unlock all types of rogue, and the target player will be kicked, used with `/unlockall tutorial` to get better performance # Note The language used in the command is from the game engine, but they are not how those concepts are called in the game. Here is a translation of the jargons: - avatar means character, players often call it character - equipment means light cone, those two are interchangeable, but Console UI prefers equipment - relic can also be called artifact, but both UI and players often use relic - mission can also be called quest, but players often use mission. There are main missions and sub missions. More commands will be added as needed.
0
0.892108
1
0.892108
game-dev
MEDIA
0.367357
game-dev
0.671815
1
0.671815
Siv3D/OpenSiv3D
1,154
Siv3D/src/Siv3D/ManagedScript/SivManagedScript.cpp
//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2025 Ryo Suzuki // Copyright (c) 2016-2025 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # include <Siv3D/ManagedScript.hpp> # include <Siv3D/ManagedScript/ManagedScriptDetail.hpp> namespace s3d { ManagedScript::ManagedScript() : pImpl{ std::make_shared<ManagedScriptDetail>() } {} ManagedScript::ManagedScript(const FilePathView path) : pImpl{ std::make_shared<ManagedScriptDetail>(path) } {} ManagedScript::~ManagedScript() {} bool ManagedScript::isEmpty() const { return pImpl->isEmpty(); } ManagedScript::operator bool() const { return (not pImpl->isEmpty()); } bool ManagedScript::compiled() const { return pImpl->compiled(); } void ManagedScript::setTriggerToReload(const std::function<bool(void)>& trigger) { pImpl->setTriggerToReload(trigger); } const Array<FilePath>& ManagedScript::getIncludedFiles() const noexcept { return pImpl->getIncludedFiles(); } void ManagedScript::run() const { return pImpl->run(); } }
0
0.831885
1
0.831885
game-dev
MEDIA
0.5678
game-dev
0.721611
1
0.721611
CardboardPowered/cardboard
2,742
src/main/java/org/bukkit/craftbukkit/entity/CraftArrow.java
package org.bukkit.craftbukkit.entity; import com.google.common.collect.ImmutableList; import java.util.List; import java.util.Optional; import net.minecraft.component.type.PotionContentsComponent; import net.minecraft.entity.effect.StatusEffect; import net.minecraft.entity.effect.StatusEffectInstance; import net.minecraft.registry.entry.RegistryEntry; import org.bukkit.Color; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.craftbukkit.potion.CraftPotionEffectType; import org.bukkit.craftbukkit.potion.CraftPotionType; import org.bukkit.entity.Arrow; import org.bukkit.potion.PotionData; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import org.bukkit.potion.PotionType; public class CraftArrow extends CraftAbstractArrow implements Arrow { public CraftArrow(CraftServer server, net.minecraft.entity.projectile.ArrowEntity entity) { super(server, entity); } @Override public net.minecraft.entity.projectile.ArrowEntity getHandle() { return (net.minecraft.entity.projectile.ArrowEntity) this.nms; } @Override public String toString() { return "CraftTippedArrow"; } @Override public boolean addCustomEffect(PotionEffect effect, boolean override) { // TODO return true; } @Override public void clearCustomEffects() { // TODO } @Override public List<PotionEffect> getCustomEffects() { ImmutableList.Builder<PotionEffect> builder = ImmutableList.builder(); // TODO return builder.build(); } @Override public boolean hasCustomEffect(PotionEffectType type) { // TODO return false; } @Override public boolean hasCustomEffects() { return false; // TODO } @Override public boolean removeCustomEffect(PotionEffectType effect) { if (!this.hasCustomEffect(effect)) { return false; } // TODO return true; } @Override public void setBasePotionData(PotionData data) { // TODO } @Override public PotionData getBasePotionData() { return null; // TODO } @Override public void setBasePotionType(PotionType potionType) { // TODO } @Override public PotionType getBasePotionType() { return null; // TODO } @Override public void setColor(Color color) { // TODO } @Override public Color getColor() { int color = this.getHandle().getColor(); // Paper // if (color == net.minecraft.entity.projectile.ArrowEntity.NO_POTION_COLOR) { // Paper // return null; // } return Color.fromARGB(color); // Paper } }
0
0.745722
1
0.745722
game-dev
MEDIA
0.995741
game-dev
0.727854
1
0.727854
Lothrazar/Cyclic
8,208
src/main/java/com/lothrazar/cyclic/block/generatorfluid/TileGeneratorFluid.java
package com.lothrazar.cyclic.block.generatorfluid; import java.util.ArrayList; import java.util.List; import com.lothrazar.cyclic.block.TileBlockEntityCyclic; import com.lothrazar.cyclic.block.battery.TileBattery; import com.lothrazar.cyclic.capabilities.block.FluidTankBase; import com.lothrazar.cyclic.registry.BlockRegistry; import com.lothrazar.cyclic.registry.CyclicRecipeType; import com.lothrazar.cyclic.registry.TileRegistry; import com.lothrazar.library.cap.CustomEnergyStorage; import com.lothrazar.library.cap.ItemStackHandlerWrapper; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.Component; import net.minecraft.world.MenuProvider; import net.minecraft.world.WorldlyContainer; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.material.Fluid; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.ForgeCapabilities; import net.minecraftforge.common.util.LazyOptional; import net.minecraftforge.energy.IEnergyStorage; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidType; import net.minecraftforge.fluids.capability.IFluidHandler.FluidAction; import net.minecraftforge.items.IItemHandler; import net.minecraftforge.items.ItemStackHandler; import org.jetbrains.annotations.Nullable; public class TileGeneratorFluid extends TileBlockEntityCyclic implements MenuProvider, WorldlyContainer { static enum Fields { TIMER, REDSTONE, BURNMAX, FLOWING; } public static final int CAPACITY = 64 * FluidType.BUCKET_VOLUME; static final int MAX = TileBattery.MENERGY * 10; CustomEnergyStorage energy = new CustomEnergyStorage(MAX, MAX); private LazyOptional<IEnergyStorage> energyCap = LazyOptional.of(() -> energy); ItemStackHandler inputSlots = new ItemStackHandler(0); protected final FluidTankBase tank = new FluidTankBase(this, CAPACITY, p -> indexFluidsFromRecipes().contains(p.getFluid())); private final LazyOptional<FluidTankBase> fluidCap = LazyOptional.of(() -> tank); ItemStackHandler outputSlots = new ItemStackHandler(0); private ItemStackHandlerWrapper inventory = new ItemStackHandlerWrapper(inputSlots, outputSlots); private LazyOptional<IItemHandler> inventoryCap = LazyOptional.of(() -> inventory); private int burnTimeMax = 0; //only non zero if processing private int burnTime = 0; //how much of current fuel is left private RecipeGeneratorFluid currentRecipe; public TileGeneratorFluid(BlockPos pos, BlockState state) { super(TileRegistry.GENERATOR_FLUID.get(), pos, state); this.needsRedstone = 0; } public static void serverTick(Level level, BlockPos blockPos, BlockState blockState, TileGeneratorFluid e) { e.tick(); } public static <E extends BlockEntity> void clientTick(Level level, BlockPos blockPos, BlockState blockState, TileGeneratorFluid e) { e.tick(); } @Override public FluidStack getFluid() { return tank == null ? FluidStack.EMPTY : tank.getFluid(); } @Override public void setFluid(FluidStack fluid) { tank.setFluid(fluid); } // @Override public void tick() { this.syncEnergy(); if (this.flowing == 1) { this.exportEnergyAllSides(); } if (this.burnTime == 0) { setLitProperty(false); } if (level.isClientSide) { return; } if (this.requiresRedstone() && !this.isPowered()) { setLitProperty(false); return; } if (this.burnTime <= 0) { currentRecipe = null; this.burnTimeMax = 0; this.burnTime = 0; } tryConsumeFuel(); } private void tryConsumeFuel() { //pull in new fuel if (this.burnTime > 0 && this.energy.getEnergyStored() + currentRecipe.getRfpertick() <= this.energy.getMaxEnergyStored()) { setLitProperty(true); this.burnTime--; //we have room in the tank, burn one tck and fill up energy.receiveEnergy(currentRecipe.getRfpertick(), false); } else if (this.burnTime <= 0) { this.findMatchingRecipe(); if (currentRecipe == null) { this.burnTime = 0; return; } } } private ArrayList<Fluid> indexFluidsFromRecipes() { List<RecipeGeneratorFluid> recipes = level.getRecipeManager().getAllRecipesFor(CyclicRecipeType.GENERATOR_FLUID.get()); ArrayList<Fluid> fluids = new ArrayList<>(); for (RecipeGeneratorFluid recipe : recipes) { fluids.add(recipe.getRecipeFluid().getFluid()); fluids.addAll(recipe.getFluidsFromTag()); } return fluids; } private void findMatchingRecipe() { if (currentRecipe != null && currentRecipe.matches(this, level)) { return; } currentRecipe = null; List<RecipeGeneratorFluid> recipes = level.getRecipeManager().getAllRecipesFor(CyclicRecipeType.GENERATOR_FLUID.get()); for (RecipeGeneratorFluid rec : recipes) { if (rec.matches(this, level)) { this.currentRecipe = rec; this.burnTimeMax = this.currentRecipe.getTicks(); this.burnTime = this.burnTimeMax; // extract tank.drain(this.currentRecipe.fluidIng.getAmount(), FluidAction.EXECUTE); return; } } } @Override public Component getDisplayName() { return BlockRegistry.GENERATOR_FLUID.get().getName(); } @Override public AbstractContainerMenu createMenu(int i, Inventory playerInventory, Player playerEntity) { return new ContainerGeneratorFluid(i, level, worldPosition, playerInventory, playerEntity); } @Override public void invalidateCaps() { energyCap.invalidate(); inventoryCap.invalidate(); fluidCap.invalidate(); super.invalidateCaps(); } @Override public <T> LazyOptional<T> getCapability(Capability<T> cap, Direction side) { if (cap == ForgeCapabilities.ENERGY) { return energyCap.cast(); } if (cap == ForgeCapabilities.FLUID_HANDLER) { return fluidCap.cast(); } if (cap == ForgeCapabilities.ITEM_HANDLER) { return inventoryCap.cast(); } return super.getCapability(cap, side); } @Override public void load(CompoundTag tag) { tank.readFromNBT(tag.getCompound(NBTFLUID)); energy.deserializeNBT(tag.getCompound(NBTENERGY)); inventory.deserializeNBT(tag.getCompound(NBTINV)); super.load(tag); } @Override public void saveAdditional(CompoundTag tag) { CompoundTag fluid = new CompoundTag(); tank.writeToNBT(fluid); tag.put(NBTFLUID, fluid); tag.put(NBTENERGY, energy.serializeNBT()); tag.put(NBTINV, inventory.serializeNBT()); super.saveAdditional(tag); } @Override public int getField(int id) { switch (Fields.values()[id]) { case REDSTONE: return this.needsRedstone; case TIMER: return this.burnTime; case BURNMAX: return this.burnTimeMax; case FLOWING: return this.flowing; } return 0; } @Override public void setField(int field, int value) { switch (Fields.values()[field]) { case REDSTONE: this.needsRedstone = value % 2; break; case TIMER: this.burnTime = value; break; case BURNMAX: this.burnTimeMax = value; break; case FLOWING: this.flowing = value; break; } } public int getEnergyMax() { return TileGeneratorFluid.MAX; } @Override public int[] getSlotsForFace(Direction direction) { return inventory.getSlotsForFace(direction); } @Override public boolean canPlaceItemThroughFace(int i, ItemStack itemStack, @Nullable Direction direction) { return inventory.canPlaceItemThroughFace(i, itemStack, direction); } @Override public boolean canTakeItemThroughFace(int i, ItemStack itemStack, Direction direction) { return inventory.canTakeItemThroughFace(i, itemStack, direction); } }
0
0.941369
1
0.941369
game-dev
MEDIA
0.995442
game-dev
0.978115
1
0.978115
FalconClient/FalconClient
55,534
src/main/java/net/minecraft/command/server/CommandScoreboard.java
package net.minecraft.command.server; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import net.minecraft.command.CommandBase; import net.minecraft.command.CommandException; import net.minecraft.command.CommandResultStats; import net.minecraft.command.ICommandSender; import net.minecraft.command.SyntaxErrorException; import net.minecraft.command.WrongUsageException; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.JsonToNBT; import net.minecraft.nbt.NBTException; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTUtil; import net.minecraft.scoreboard.IScoreObjectiveCriteria; import net.minecraft.scoreboard.Score; import net.minecraft.scoreboard.ScoreObjective; import net.minecraft.scoreboard.ScorePlayerTeam; import net.minecraft.scoreboard.Scoreboard; import net.minecraft.scoreboard.Team; import net.minecraft.server.MinecraftServer; import net.minecraft.util.BlockPos; import net.minecraft.util.ChatComponentText; import net.minecraft.util.ChatComponentTranslation; import net.minecraft.util.EnumChatFormatting; public class CommandScoreboard extends CommandBase { /** * Gets the name of the command */ public String getCommandName() { return "scoreboard"; } /** * Return the required permission level for this command. */ public int getRequiredPermissionLevel() { return 2; } /** * Gets the usage string for the command. */ public String getCommandUsage(ICommandSender sender) { return "commands.scoreboard.usage"; } /** * Callback when the command is invoked */ public void processCommand(ICommandSender sender, String[] args) throws CommandException { if (!this.func_175780_b(sender, args)) { if (args.length < 1) { throw new WrongUsageException("commands.scoreboard.usage", new Object[0]); } else { if (args[0].equalsIgnoreCase("objectives")) { if (args.length == 1) { throw new WrongUsageException("commands.scoreboard.objectives.usage", new Object[0]); } if (args[1].equalsIgnoreCase("list")) { this.listObjectives(sender); } else if (args[1].equalsIgnoreCase("add")) { if (args.length < 4) { throw new WrongUsageException("commands.scoreboard.objectives.add.usage", new Object[0]); } this.addObjective(sender, args, 2); } else if (args[1].equalsIgnoreCase("remove")) { if (args.length != 3) { throw new WrongUsageException("commands.scoreboard.objectives.remove.usage", new Object[0]); } this.removeObjective(sender, args[2]); } else { if (!args[1].equalsIgnoreCase("setdisplay")) { throw new WrongUsageException("commands.scoreboard.objectives.usage", new Object[0]); } if (args.length != 3 && args.length != 4) { throw new WrongUsageException("commands.scoreboard.objectives.setdisplay.usage", new Object[0]); } this.setObjectiveDisplay(sender, args, 2); } } else if (args[0].equalsIgnoreCase("players")) { if (args.length == 1) { throw new WrongUsageException("commands.scoreboard.players.usage", new Object[0]); } if (args[1].equalsIgnoreCase("list")) { if (args.length > 3) { throw new WrongUsageException("commands.scoreboard.players.list.usage", new Object[0]); } this.listPlayers(sender, args, 2); } else if (args[1].equalsIgnoreCase("add")) { if (args.length < 5) { throw new WrongUsageException("commands.scoreboard.players.add.usage", new Object[0]); } this.setPlayer(sender, args, 2); } else if (args[1].equalsIgnoreCase("remove")) { if (args.length < 5) { throw new WrongUsageException("commands.scoreboard.players.remove.usage", new Object[0]); } this.setPlayer(sender, args, 2); } else if (args[1].equalsIgnoreCase("set")) { if (args.length < 5) { throw new WrongUsageException("commands.scoreboard.players.set.usage", new Object[0]); } this.setPlayer(sender, args, 2); } else if (args[1].equalsIgnoreCase("reset")) { if (args.length != 3 && args.length != 4) { throw new WrongUsageException("commands.scoreboard.players.reset.usage", new Object[0]); } this.resetPlayers(sender, args, 2); } else if (args[1].equalsIgnoreCase("enable")) { if (args.length != 4) { throw new WrongUsageException("commands.scoreboard.players.enable.usage", new Object[0]); } this.func_175779_n(sender, args, 2); } else if (args[1].equalsIgnoreCase("test")) { if (args.length != 5 && args.length != 6) { throw new WrongUsageException("commands.scoreboard.players.test.usage", new Object[0]); } this.func_175781_o(sender, args, 2); } else { if (!args[1].equalsIgnoreCase("operation")) { throw new WrongUsageException("commands.scoreboard.players.usage", new Object[0]); } if (args.length != 7) { throw new WrongUsageException("commands.scoreboard.players.operation.usage", new Object[0]); } this.func_175778_p(sender, args, 2); } } else { if (!args[0].equalsIgnoreCase("teams")) { throw new WrongUsageException("commands.scoreboard.usage", new Object[0]); } if (args.length == 1) { throw new WrongUsageException("commands.scoreboard.teams.usage", new Object[0]); } if (args[1].equalsIgnoreCase("list")) { if (args.length > 3) { throw new WrongUsageException("commands.scoreboard.teams.list.usage", new Object[0]); } this.listTeams(sender, args, 2); } else if (args[1].equalsIgnoreCase("add")) { if (args.length < 3) { throw new WrongUsageException("commands.scoreboard.teams.add.usage", new Object[0]); } this.addTeam(sender, args, 2); } else if (args[1].equalsIgnoreCase("remove")) { if (args.length != 3) { throw new WrongUsageException("commands.scoreboard.teams.remove.usage", new Object[0]); } this.removeTeam(sender, args, 2); } else if (args[1].equalsIgnoreCase("empty")) { if (args.length != 3) { throw new WrongUsageException("commands.scoreboard.teams.empty.usage", new Object[0]); } this.emptyTeam(sender, args, 2); } else if (args[1].equalsIgnoreCase("join")) { if (args.length < 4 && (args.length != 3 || !(sender instanceof EntityPlayer))) { throw new WrongUsageException("commands.scoreboard.teams.join.usage", new Object[0]); } this.joinTeam(sender, args, 2); } else if (args[1].equalsIgnoreCase("leave")) { if (args.length < 3 && !(sender instanceof EntityPlayer)) { throw new WrongUsageException("commands.scoreboard.teams.leave.usage", new Object[0]); } this.leaveTeam(sender, args, 2); } else { if (!args[1].equalsIgnoreCase("option")) { throw new WrongUsageException("commands.scoreboard.teams.usage", new Object[0]); } if (args.length != 4 && args.length != 5) { throw new WrongUsageException("commands.scoreboard.teams.option.usage", new Object[0]); } this.setTeamOption(sender, args, 2); } } } } } private boolean func_175780_b(ICommandSender p_175780_1_, String[] p_175780_2_) throws CommandException { int i = -1; for (int j = 0; j < p_175780_2_.length; ++j) { if (this.isUsernameIndex(p_175780_2_, j) && "*".equals(p_175780_2_[j])) { if (i >= 0) { throw new CommandException("commands.scoreboard.noMultiWildcard", new Object[0]); } i = j; } } if (i < 0) { return false; } else { List<String> list1 = Lists.newArrayList(this.getScoreboard().getObjectiveNames()); String s = p_175780_2_[i]; List<String> list = Lists.<String>newArrayList(); for (String s1 : list1) { p_175780_2_[i] = s1; try { this.processCommand(p_175780_1_, p_175780_2_); list.add(s1); } catch (CommandException commandexception) { ChatComponentTranslation chatcomponenttranslation = new ChatComponentTranslation(commandexception.getMessage(), commandexception.getErrorObjects()); chatcomponenttranslation.getChatStyle().setColor(EnumChatFormatting.RED); p_175780_1_.addChatMessage(chatcomponenttranslation); } } p_175780_2_[i] = s; p_175780_1_.setCommandStat(CommandResultStats.Type.AFFECTED_ENTITIES, list.size()); if (list.size() == 0) { throw new WrongUsageException("commands.scoreboard.allMatchesFailed", new Object[0]); } else { return true; } } } protected Scoreboard getScoreboard() { return MinecraftServer.getServer().worldServerForDimension(0).getScoreboard(); } protected ScoreObjective getObjective(String name, boolean edit) throws CommandException { Scoreboard scoreboard = this.getScoreboard(); ScoreObjective scoreobjective = scoreboard.getObjective(name); if (scoreobjective == null) { throw new CommandException("commands.scoreboard.objectiveNotFound", new Object[] {name}); } else if (edit && scoreobjective.getCriteria().isReadOnly()) { throw new CommandException("commands.scoreboard.objectiveReadOnly", new Object[] {name}); } else { return scoreobjective; } } protected ScorePlayerTeam getTeam(String name) throws CommandException { Scoreboard scoreboard = this.getScoreboard(); ScorePlayerTeam scoreplayerteam = scoreboard.getTeam(name); if (scoreplayerteam == null) { throw new CommandException("commands.scoreboard.teamNotFound", new Object[] {name}); } else { return scoreplayerteam; } } protected void addObjective(ICommandSender sender, String[] args, int index) throws CommandException { String s = args[index++]; String s1 = args[index++]; Scoreboard scoreboard = this.getScoreboard(); IScoreObjectiveCriteria iscoreobjectivecriteria = (IScoreObjectiveCriteria)IScoreObjectiveCriteria.INSTANCES.get(s1); if (iscoreobjectivecriteria == null) { throw new WrongUsageException("commands.scoreboard.objectives.add.wrongType", new Object[] {s1}); } else if (scoreboard.getObjective(s) != null) { throw new CommandException("commands.scoreboard.objectives.add.alreadyExists", new Object[] {s}); } else if (s.length() > 16) { throw new SyntaxErrorException("commands.scoreboard.objectives.add.tooLong", new Object[] {s, Integer.valueOf(16)}); } else if (s.length() == 0) { throw new WrongUsageException("commands.scoreboard.objectives.add.usage", new Object[0]); } else { if (args.length > index) { String s2 = getChatComponentFromNthArg(sender, args, index).getUnformattedText(); if (s2.length() > 32) { throw new SyntaxErrorException("commands.scoreboard.objectives.add.displayTooLong", new Object[] {s2, Integer.valueOf(32)}); } if (s2.length() > 0) { scoreboard.addScoreObjective(s, iscoreobjectivecriteria).setDisplayName(s2); } else { scoreboard.addScoreObjective(s, iscoreobjectivecriteria); } } else { scoreboard.addScoreObjective(s, iscoreobjectivecriteria); } notifyOperators(sender, this, "commands.scoreboard.objectives.add.success", new Object[] {s}); } } protected void addTeam(ICommandSender sender, String[] args, int index) throws CommandException { String s = args[index++]; Scoreboard scoreboard = this.getScoreboard(); if (scoreboard.getTeam(s) != null) { throw new CommandException("commands.scoreboard.teams.add.alreadyExists", new Object[] {s}); } else if (s.length() > 16) { throw new SyntaxErrorException("commands.scoreboard.teams.add.tooLong", new Object[] {s, Integer.valueOf(16)}); } else if (s.length() == 0) { throw new WrongUsageException("commands.scoreboard.teams.add.usage", new Object[0]); } else { if (args.length > index) { String s1 = getChatComponentFromNthArg(sender, args, index).getUnformattedText(); if (s1.length() > 32) { throw new SyntaxErrorException("commands.scoreboard.teams.add.displayTooLong", new Object[] {s1, Integer.valueOf(32)}); } if (s1.length() > 0) { scoreboard.createTeam(s).setTeamName(s1); } else { scoreboard.createTeam(s); } } else { scoreboard.createTeam(s); } notifyOperators(sender, this, "commands.scoreboard.teams.add.success", new Object[] {s}); } } protected void setTeamOption(ICommandSender sender, String[] args, int index) throws CommandException { ScorePlayerTeam scoreplayerteam = this.getTeam(args[index++]); if (scoreplayerteam != null) { String s = args[index++].toLowerCase(); if (!s.equalsIgnoreCase("color") && !s.equalsIgnoreCase("friendlyfire") && !s.equalsIgnoreCase("seeFriendlyInvisibles") && !s.equalsIgnoreCase("nametagVisibility") && !s.equalsIgnoreCase("deathMessageVisibility")) { throw new WrongUsageException("commands.scoreboard.teams.option.usage", new Object[0]); } else if (args.length == 4) { if (s.equalsIgnoreCase("color")) { throw new WrongUsageException("commands.scoreboard.teams.option.noValue", new Object[] {s, joinNiceStringFromCollection(EnumChatFormatting.getValidValues(true, false))}); } else if (!s.equalsIgnoreCase("friendlyfire") && !s.equalsIgnoreCase("seeFriendlyInvisibles")) { if (!s.equalsIgnoreCase("nametagVisibility") && !s.equalsIgnoreCase("deathMessageVisibility")) { throw new WrongUsageException("commands.scoreboard.teams.option.usage", new Object[0]); } else { throw new WrongUsageException("commands.scoreboard.teams.option.noValue", new Object[] {s, joinNiceString(Team.EnumVisible.func_178825_a())}); } } else { throw new WrongUsageException("commands.scoreboard.teams.option.noValue", new Object[] {s, joinNiceStringFromCollection(Arrays.asList(new String[]{"true", "false"}))}); } } else { String s1 = args[index]; if (s.equalsIgnoreCase("color")) { EnumChatFormatting enumchatformatting = EnumChatFormatting.getValueByName(s1); if (enumchatformatting == null || enumchatformatting.isFancyStyling()) { throw new WrongUsageException("commands.scoreboard.teams.option.noValue", new Object[] {s, joinNiceStringFromCollection(EnumChatFormatting.getValidValues(true, false))}); } scoreplayerteam.setChatFormat(enumchatformatting); scoreplayerteam.setNamePrefix(enumchatformatting.toString()); scoreplayerteam.setNameSuffix(EnumChatFormatting.RESET.toString()); } else if (s.equalsIgnoreCase("friendlyfire")) { if (!s1.equalsIgnoreCase("true") && !s1.equalsIgnoreCase("false")) { throw new WrongUsageException("commands.scoreboard.teams.option.noValue", new Object[] {s, joinNiceStringFromCollection(Arrays.asList(new String[]{"true", "false"}))}); } scoreplayerteam.setAllowFriendlyFire(s1.equalsIgnoreCase("true")); } else if (s.equalsIgnoreCase("seeFriendlyInvisibles")) { if (!s1.equalsIgnoreCase("true") && !s1.equalsIgnoreCase("false")) { throw new WrongUsageException("commands.scoreboard.teams.option.noValue", new Object[] {s, joinNiceStringFromCollection(Arrays.asList(new String[]{"true", "false"}))}); } scoreplayerteam.setSeeFriendlyInvisiblesEnabled(s1.equalsIgnoreCase("true")); } else if (s.equalsIgnoreCase("nametagVisibility")) { Team.EnumVisible team$enumvisible = Team.EnumVisible.func_178824_a(s1); if (team$enumvisible == null) { throw new WrongUsageException("commands.scoreboard.teams.option.noValue", new Object[] {s, joinNiceString(Team.EnumVisible.func_178825_a())}); } scoreplayerteam.setNameTagVisibility(team$enumvisible); } else if (s.equalsIgnoreCase("deathMessageVisibility")) { Team.EnumVisible team$enumvisible1 = Team.EnumVisible.func_178824_a(s1); if (team$enumvisible1 == null) { throw new WrongUsageException("commands.scoreboard.teams.option.noValue", new Object[] {s, joinNiceString(Team.EnumVisible.func_178825_a())}); } scoreplayerteam.setDeathMessageVisibility(team$enumvisible1); } notifyOperators(sender, this, "commands.scoreboard.teams.option.success", new Object[] {s, scoreplayerteam.getRegisteredName(), s1}); } } } protected void removeTeam(ICommandSender p_147194_1_, String[] p_147194_2_, int p_147194_3_) throws CommandException { Scoreboard scoreboard = this.getScoreboard(); ScorePlayerTeam scoreplayerteam = this.getTeam(p_147194_2_[p_147194_3_]); if (scoreplayerteam != null) { scoreboard.removeTeam(scoreplayerteam); notifyOperators(p_147194_1_, this, "commands.scoreboard.teams.remove.success", new Object[] {scoreplayerteam.getRegisteredName()}); } } protected void listTeams(ICommandSender p_147186_1_, String[] p_147186_2_, int p_147186_3_) throws CommandException { Scoreboard scoreboard = this.getScoreboard(); if (p_147186_2_.length > p_147186_3_) { ScorePlayerTeam scoreplayerteam = this.getTeam(p_147186_2_[p_147186_3_]); if (scoreplayerteam == null) { return; } Collection<String> collection = scoreplayerteam.getMembershipCollection(); p_147186_1_.setCommandStat(CommandResultStats.Type.QUERY_RESULT, collection.size()); if (collection.size() <= 0) { throw new CommandException("commands.scoreboard.teams.list.player.empty", new Object[] {scoreplayerteam.getRegisteredName()}); } ChatComponentTranslation chatcomponenttranslation = new ChatComponentTranslation("commands.scoreboard.teams.list.player.count", new Object[] {Integer.valueOf(collection.size()), scoreplayerteam.getRegisteredName()}); chatcomponenttranslation.getChatStyle().setColor(EnumChatFormatting.DARK_GREEN); p_147186_1_.addChatMessage(chatcomponenttranslation); p_147186_1_.addChatMessage(new ChatComponentText(joinNiceString(collection.toArray()))); } else { Collection<ScorePlayerTeam> collection1 = scoreboard.getTeams(); p_147186_1_.setCommandStat(CommandResultStats.Type.QUERY_RESULT, collection1.size()); if (collection1.size() <= 0) { throw new CommandException("commands.scoreboard.teams.list.empty", new Object[0]); } ChatComponentTranslation chatcomponenttranslation1 = new ChatComponentTranslation("commands.scoreboard.teams.list.count", new Object[] {Integer.valueOf(collection1.size())}); chatcomponenttranslation1.getChatStyle().setColor(EnumChatFormatting.DARK_GREEN); p_147186_1_.addChatMessage(chatcomponenttranslation1); for (ScorePlayerTeam scoreplayerteam1 : collection1) { p_147186_1_.addChatMessage(new ChatComponentTranslation("commands.scoreboard.teams.list.entry", new Object[] {scoreplayerteam1.getRegisteredName(), scoreplayerteam1.getTeamName(), Integer.valueOf(scoreplayerteam1.getMembershipCollection().size())})); } } } protected void joinTeam(ICommandSender p_147190_1_, String[] p_147190_2_, int p_147190_3_) throws CommandException { Scoreboard scoreboard = this.getScoreboard(); String s = p_147190_2_[p_147190_3_++]; Set<String> set = Sets.<String>newHashSet(); Set<String> set1 = Sets.<String>newHashSet(); if (p_147190_1_ instanceof EntityPlayer && p_147190_3_ == p_147190_2_.length) { String s4 = getCommandSenderAsPlayer(p_147190_1_).getName(); if (scoreboard.addPlayerToTeam(s4, s)) { set.add(s4); } else { set1.add(s4); } } else { while (p_147190_3_ < p_147190_2_.length) { String s1 = p_147190_2_[p_147190_3_++]; if (s1.startsWith("@")) { for (Entity entity : func_175763_c(p_147190_1_, s1)) { String s3 = getEntityName(p_147190_1_, entity.getUniqueID().toString()); if (scoreboard.addPlayerToTeam(s3, s)) { set.add(s3); } else { set1.add(s3); } } } else { String s2 = getEntityName(p_147190_1_, s1); if (scoreboard.addPlayerToTeam(s2, s)) { set.add(s2); } else { set1.add(s2); } } } } if (!set.isEmpty()) { p_147190_1_.setCommandStat(CommandResultStats.Type.AFFECTED_ENTITIES, set.size()); notifyOperators(p_147190_1_, this, "commands.scoreboard.teams.join.success", new Object[] {Integer.valueOf(set.size()), s, joinNiceString(set.toArray(new String[set.size()]))}); } if (!set1.isEmpty()) { throw new CommandException("commands.scoreboard.teams.join.failure", new Object[] {Integer.valueOf(set1.size()), s, joinNiceString(set1.toArray(new String[set1.size()]))}); } } protected void leaveTeam(ICommandSender p_147199_1_, String[] p_147199_2_, int p_147199_3_) throws CommandException { Scoreboard scoreboard = this.getScoreboard(); Set<String> set = Sets.<String>newHashSet(); Set<String> set1 = Sets.<String>newHashSet(); if (p_147199_1_ instanceof EntityPlayer && p_147199_3_ == p_147199_2_.length) { String s3 = getCommandSenderAsPlayer(p_147199_1_).getName(); if (scoreboard.removePlayerFromTeams(s3)) { set.add(s3); } else { set1.add(s3); } } else { while (p_147199_3_ < p_147199_2_.length) { String s = p_147199_2_[p_147199_3_++]; if (s.startsWith("@")) { for (Entity entity : func_175763_c(p_147199_1_, s)) { String s2 = getEntityName(p_147199_1_, entity.getUniqueID().toString()); if (scoreboard.removePlayerFromTeams(s2)) { set.add(s2); } else { set1.add(s2); } } } else { String s1 = getEntityName(p_147199_1_, s); if (scoreboard.removePlayerFromTeams(s1)) { set.add(s1); } else { set1.add(s1); } } } } if (!set.isEmpty()) { p_147199_1_.setCommandStat(CommandResultStats.Type.AFFECTED_ENTITIES, set.size()); notifyOperators(p_147199_1_, this, "commands.scoreboard.teams.leave.success", new Object[] {Integer.valueOf(set.size()), joinNiceString(set.toArray(new String[set.size()]))}); } if (!set1.isEmpty()) { throw new CommandException("commands.scoreboard.teams.leave.failure", new Object[] {Integer.valueOf(set1.size()), joinNiceString(set1.toArray(new String[set1.size()]))}); } } protected void emptyTeam(ICommandSender p_147188_1_, String[] p_147188_2_, int p_147188_3_) throws CommandException { Scoreboard scoreboard = this.getScoreboard(); ScorePlayerTeam scoreplayerteam = this.getTeam(p_147188_2_[p_147188_3_]); if (scoreplayerteam != null) { Collection<String> collection = Lists.newArrayList(scoreplayerteam.getMembershipCollection()); p_147188_1_.setCommandStat(CommandResultStats.Type.AFFECTED_ENTITIES, collection.size()); if (collection.isEmpty()) { throw new CommandException("commands.scoreboard.teams.empty.alreadyEmpty", new Object[] {scoreplayerteam.getRegisteredName()}); } else { for (String s : collection) { scoreboard.removePlayerFromTeam(s, scoreplayerteam); } notifyOperators(p_147188_1_, this, "commands.scoreboard.teams.empty.success", new Object[] {Integer.valueOf(collection.size()), scoreplayerteam.getRegisteredName()}); } } } protected void removeObjective(ICommandSender p_147191_1_, String p_147191_2_) throws CommandException { Scoreboard scoreboard = this.getScoreboard(); ScoreObjective scoreobjective = this.getObjective(p_147191_2_, false); scoreboard.removeObjective(scoreobjective); notifyOperators(p_147191_1_, this, "commands.scoreboard.objectives.remove.success", new Object[] {p_147191_2_}); } protected void listObjectives(ICommandSender p_147196_1_) throws CommandException { Scoreboard scoreboard = this.getScoreboard(); Collection<ScoreObjective> collection = scoreboard.getScoreObjectives(); if (collection.size() <= 0) { throw new CommandException("commands.scoreboard.objectives.list.empty", new Object[0]); } else { ChatComponentTranslation chatcomponenttranslation = new ChatComponentTranslation("commands.scoreboard.objectives.list.count", new Object[] {Integer.valueOf(collection.size())}); chatcomponenttranslation.getChatStyle().setColor(EnumChatFormatting.DARK_GREEN); p_147196_1_.addChatMessage(chatcomponenttranslation); for (ScoreObjective scoreobjective : collection) { p_147196_1_.addChatMessage(new ChatComponentTranslation("commands.scoreboard.objectives.list.entry", new Object[] {scoreobjective.getName(), scoreobjective.getDisplayName(), scoreobjective.getCriteria().getName()})); } } } protected void setObjectiveDisplay(ICommandSender p_147198_1_, String[] p_147198_2_, int p_147198_3_) throws CommandException { Scoreboard scoreboard = this.getScoreboard(); String s = p_147198_2_[p_147198_3_++]; int i = Scoreboard.getObjectiveDisplaySlotNumber(s); ScoreObjective scoreobjective = null; if (p_147198_2_.length == 4) { scoreobjective = this.getObjective(p_147198_2_[p_147198_3_], false); } if (i < 0) { throw new CommandException("commands.scoreboard.objectives.setdisplay.invalidSlot", new Object[] {s}); } else { scoreboard.setObjectiveInDisplaySlot(i, scoreobjective); if (scoreobjective != null) { notifyOperators(p_147198_1_, this, "commands.scoreboard.objectives.setdisplay.successSet", new Object[] {Scoreboard.getObjectiveDisplaySlot(i), scoreobjective.getName()}); } else { notifyOperators(p_147198_1_, this, "commands.scoreboard.objectives.setdisplay.successCleared", new Object[] {Scoreboard.getObjectiveDisplaySlot(i)}); } } } protected void listPlayers(ICommandSender p_147195_1_, String[] p_147195_2_, int p_147195_3_) throws CommandException { Scoreboard scoreboard = this.getScoreboard(); if (p_147195_2_.length > p_147195_3_) { String s = getEntityName(p_147195_1_, p_147195_2_[p_147195_3_]); Map<ScoreObjective, Score> map = scoreboard.getObjectivesForEntity(s); p_147195_1_.setCommandStat(CommandResultStats.Type.QUERY_RESULT, map.size()); if (map.size() <= 0) { throw new CommandException("commands.scoreboard.players.list.player.empty", new Object[] {s}); } ChatComponentTranslation chatcomponenttranslation = new ChatComponentTranslation("commands.scoreboard.players.list.player.count", new Object[] {Integer.valueOf(map.size()), s}); chatcomponenttranslation.getChatStyle().setColor(EnumChatFormatting.DARK_GREEN); p_147195_1_.addChatMessage(chatcomponenttranslation); for (Score score : map.values()) { p_147195_1_.addChatMessage(new ChatComponentTranslation("commands.scoreboard.players.list.player.entry", new Object[] {Integer.valueOf(score.getScorePoints()), score.getObjective().getDisplayName(), score.getObjective().getName()})); } } else { Collection<String> collection = scoreboard.getObjectiveNames(); p_147195_1_.setCommandStat(CommandResultStats.Type.QUERY_RESULT, collection.size()); if (collection.size() <= 0) { throw new CommandException("commands.scoreboard.players.list.empty", new Object[0]); } ChatComponentTranslation chatcomponenttranslation1 = new ChatComponentTranslation("commands.scoreboard.players.list.count", new Object[] {Integer.valueOf(collection.size())}); chatcomponenttranslation1.getChatStyle().setColor(EnumChatFormatting.DARK_GREEN); p_147195_1_.addChatMessage(chatcomponenttranslation1); p_147195_1_.addChatMessage(new ChatComponentText(joinNiceString(collection.toArray()))); } } protected void setPlayer(ICommandSender p_147197_1_, String[] p_147197_2_, int p_147197_3_) throws CommandException { String s = p_147197_2_[p_147197_3_ - 1]; int i = p_147197_3_; String s1 = getEntityName(p_147197_1_, p_147197_2_[p_147197_3_++]); if (s1.length() > 40) { throw new SyntaxErrorException("commands.scoreboard.players.name.tooLong", new Object[] {s1, Integer.valueOf(40)}); } else { ScoreObjective scoreobjective = this.getObjective(p_147197_2_[p_147197_3_++], true); int j = s.equalsIgnoreCase("set") ? parseInt(p_147197_2_[p_147197_3_++]) : parseInt(p_147197_2_[p_147197_3_++], 0); if (p_147197_2_.length > p_147197_3_) { Entity entity = getEntity(p_147197_1_, p_147197_2_[i]); try { NBTTagCompound nbttagcompound = JsonToNBT.getTagFromJson(buildString(p_147197_2_, p_147197_3_)); NBTTagCompound nbttagcompound1 = new NBTTagCompound(); entity.writeToNBT(nbttagcompound1); if (!NBTUtil.func_181123_a(nbttagcompound, nbttagcompound1, true)) { throw new CommandException("commands.scoreboard.players.set.tagMismatch", new Object[] {s1}); } } catch (NBTException nbtexception) { throw new CommandException("commands.scoreboard.players.set.tagError", new Object[] {nbtexception.getMessage()}); } } Scoreboard scoreboard = this.getScoreboard(); Score score = scoreboard.getValueFromObjective(s1, scoreobjective); if (s.equalsIgnoreCase("set")) { score.setScorePoints(j); } else if (s.equalsIgnoreCase("add")) { score.increseScore(j); } else { score.decreaseScore(j); } notifyOperators(p_147197_1_, this, "commands.scoreboard.players.set.success", new Object[] {scoreobjective.getName(), s1, Integer.valueOf(score.getScorePoints())}); } } protected void resetPlayers(ICommandSender p_147187_1_, String[] p_147187_2_, int p_147187_3_) throws CommandException { Scoreboard scoreboard = this.getScoreboard(); String s = getEntityName(p_147187_1_, p_147187_2_[p_147187_3_++]); if (p_147187_2_.length > p_147187_3_) { ScoreObjective scoreobjective = this.getObjective(p_147187_2_[p_147187_3_++], false); scoreboard.removeObjectiveFromEntity(s, scoreobjective); notifyOperators(p_147187_1_, this, "commands.scoreboard.players.resetscore.success", new Object[] {scoreobjective.getName(), s}); } else { scoreboard.removeObjectiveFromEntity(s, (ScoreObjective)null); notifyOperators(p_147187_1_, this, "commands.scoreboard.players.reset.success", new Object[] {s}); } } protected void func_175779_n(ICommandSender p_175779_1_, String[] p_175779_2_, int p_175779_3_) throws CommandException { Scoreboard scoreboard = this.getScoreboard(); String s = getPlayerName(p_175779_1_, p_175779_2_[p_175779_3_++]); if (s.length() > 40) { throw new SyntaxErrorException("commands.scoreboard.players.name.tooLong", new Object[] {s, Integer.valueOf(40)}); } else { ScoreObjective scoreobjective = this.getObjective(p_175779_2_[p_175779_3_], false); if (scoreobjective.getCriteria() != IScoreObjectiveCriteria.TRIGGER) { throw new CommandException("commands.scoreboard.players.enable.noTrigger", new Object[] {scoreobjective.getName()}); } else { Score score = scoreboard.getValueFromObjective(s, scoreobjective); score.setLocked(false); notifyOperators(p_175779_1_, this, "commands.scoreboard.players.enable.success", new Object[] {scoreobjective.getName(), s}); } } } protected void func_175781_o(ICommandSender p_175781_1_, String[] p_175781_2_, int p_175781_3_) throws CommandException { Scoreboard scoreboard = this.getScoreboard(); String s = getEntityName(p_175781_1_, p_175781_2_[p_175781_3_++]); if (s.length() > 40) { throw new SyntaxErrorException("commands.scoreboard.players.name.tooLong", new Object[] {s, Integer.valueOf(40)}); } else { ScoreObjective scoreobjective = this.getObjective(p_175781_2_[p_175781_3_++], false); if (!scoreboard.entityHasObjective(s, scoreobjective)) { throw new CommandException("commands.scoreboard.players.test.notFound", new Object[] {scoreobjective.getName(), s}); } else { int i = p_175781_2_[p_175781_3_].equals("*") ? Integer.MIN_VALUE : parseInt(p_175781_2_[p_175781_3_]); ++p_175781_3_; int j = p_175781_3_ < p_175781_2_.length && !p_175781_2_[p_175781_3_].equals("*") ? parseInt(p_175781_2_[p_175781_3_], i) : Integer.MAX_VALUE; Score score = scoreboard.getValueFromObjective(s, scoreobjective); if (score.getScorePoints() >= i && score.getScorePoints() <= j) { notifyOperators(p_175781_1_, this, "commands.scoreboard.players.test.success", new Object[] {Integer.valueOf(score.getScorePoints()), Integer.valueOf(i), Integer.valueOf(j)}); } else { throw new CommandException("commands.scoreboard.players.test.failed", new Object[] {Integer.valueOf(score.getScorePoints()), Integer.valueOf(i), Integer.valueOf(j)}); } } } } protected void func_175778_p(ICommandSender p_175778_1_, String[] p_175778_2_, int p_175778_3_) throws CommandException { Scoreboard scoreboard = this.getScoreboard(); String s = getEntityName(p_175778_1_, p_175778_2_[p_175778_3_++]); ScoreObjective scoreobjective = this.getObjective(p_175778_2_[p_175778_3_++], true); String s1 = p_175778_2_[p_175778_3_++]; String s2 = getEntityName(p_175778_1_, p_175778_2_[p_175778_3_++]); ScoreObjective scoreobjective1 = this.getObjective(p_175778_2_[p_175778_3_], false); if (s.length() > 40) { throw new SyntaxErrorException("commands.scoreboard.players.name.tooLong", new Object[] {s, Integer.valueOf(40)}); } else if (s2.length() > 40) { throw new SyntaxErrorException("commands.scoreboard.players.name.tooLong", new Object[] {s2, Integer.valueOf(40)}); } else { Score score = scoreboard.getValueFromObjective(s, scoreobjective); if (!scoreboard.entityHasObjective(s2, scoreobjective1)) { throw new CommandException("commands.scoreboard.players.operation.notFound", new Object[] {scoreobjective1.getName(), s2}); } else { Score score1 = scoreboard.getValueFromObjective(s2, scoreobjective1); if (s1.equals("+=")) { score.setScorePoints(score.getScorePoints() + score1.getScorePoints()); } else if (s1.equals("-=")) { score.setScorePoints(score.getScorePoints() - score1.getScorePoints()); } else if (s1.equals("*=")) { score.setScorePoints(score.getScorePoints() * score1.getScorePoints()); } else if (s1.equals("/=")) { if (score1.getScorePoints() != 0) { score.setScorePoints(score.getScorePoints() / score1.getScorePoints()); } } else if (s1.equals("%=")) { if (score1.getScorePoints() != 0) { score.setScorePoints(score.getScorePoints() % score1.getScorePoints()); } } else if (s1.equals("=")) { score.setScorePoints(score1.getScorePoints()); } else if (s1.equals("<")) { score.setScorePoints(Math.min(score.getScorePoints(), score1.getScorePoints())); } else if (s1.equals(">")) { score.setScorePoints(Math.max(score.getScorePoints(), score1.getScorePoints())); } else { if (!s1.equals("><")) { throw new CommandException("commands.scoreboard.players.operation.invalidOperation", new Object[] {s1}); } int i = score.getScorePoints(); score.setScorePoints(score1.getScorePoints()); score1.setScorePoints(i); } notifyOperators(p_175778_1_, this, "commands.scoreboard.players.operation.success", new Object[0]); } } } public List<String> addTabCompletionOptions(ICommandSender sender, String[] args, BlockPos pos) { if (args.length == 1) { return getListOfStringsMatchingLastWord(args, new String[] {"objectives", "players", "teams"}); } else { if (args[0].equalsIgnoreCase("objectives")) { if (args.length == 2) { return getListOfStringsMatchingLastWord(args, new String[] {"list", "add", "remove", "setdisplay"}); } if (args[1].equalsIgnoreCase("add")) { if (args.length == 4) { Set<String> set = IScoreObjectiveCriteria.INSTANCES.keySet(); return getListOfStringsMatchingLastWord(args, set); } } else if (args[1].equalsIgnoreCase("remove")) { if (args.length == 3) { return getListOfStringsMatchingLastWord(args, this.func_147184_a(false)); } } else if (args[1].equalsIgnoreCase("setdisplay")) { if (args.length == 3) { return getListOfStringsMatchingLastWord(args, Scoreboard.getDisplaySlotStrings()); } if (args.length == 4) { return getListOfStringsMatchingLastWord(args, this.func_147184_a(false)); } } } else if (args[0].equalsIgnoreCase("players")) { if (args.length == 2) { return getListOfStringsMatchingLastWord(args, new String[] {"set", "add", "remove", "reset", "list", "enable", "test", "operation"}); } if (!args[1].equalsIgnoreCase("set") && !args[1].equalsIgnoreCase("add") && !args[1].equalsIgnoreCase("remove") && !args[1].equalsIgnoreCase("reset")) { if (args[1].equalsIgnoreCase("enable")) { if (args.length == 3) { return getListOfStringsMatchingLastWord(args, MinecraftServer.getServer().getAllUsernames()); } if (args.length == 4) { return getListOfStringsMatchingLastWord(args, this.func_175782_e()); } } else if (!args[1].equalsIgnoreCase("list") && !args[1].equalsIgnoreCase("test")) { if (args[1].equalsIgnoreCase("operation")) { if (args.length == 3) { return getListOfStringsMatchingLastWord(args, this.getScoreboard().getObjectiveNames()); } if (args.length == 4) { return getListOfStringsMatchingLastWord(args, this.func_147184_a(true)); } if (args.length == 5) { return getListOfStringsMatchingLastWord(args, new String[] {"+=", "-=", "*=", "/=", "%=", "=", "<", ">", "><"}); } if (args.length == 6) { return getListOfStringsMatchingLastWord(args, MinecraftServer.getServer().getAllUsernames()); } if (args.length == 7) { return getListOfStringsMatchingLastWord(args, this.func_147184_a(false)); } } } else { if (args.length == 3) { return getListOfStringsMatchingLastWord(args, this.getScoreboard().getObjectiveNames()); } if (args.length == 4 && args[1].equalsIgnoreCase("test")) { return getListOfStringsMatchingLastWord(args, this.func_147184_a(false)); } } } else { if (args.length == 3) { return getListOfStringsMatchingLastWord(args, MinecraftServer.getServer().getAllUsernames()); } if (args.length == 4) { return getListOfStringsMatchingLastWord(args, this.func_147184_a(true)); } } } else if (args[0].equalsIgnoreCase("teams")) { if (args.length == 2) { return getListOfStringsMatchingLastWord(args, new String[] {"add", "remove", "join", "leave", "empty", "list", "option"}); } if (args[1].equalsIgnoreCase("join")) { if (args.length == 3) { return getListOfStringsMatchingLastWord(args, this.getScoreboard().getTeamNames()); } if (args.length >= 4) { return getListOfStringsMatchingLastWord(args, MinecraftServer.getServer().getAllUsernames()); } } else { if (args[1].equalsIgnoreCase("leave")) { return getListOfStringsMatchingLastWord(args, MinecraftServer.getServer().getAllUsernames()); } if (!args[1].equalsIgnoreCase("empty") && !args[1].equalsIgnoreCase("list") && !args[1].equalsIgnoreCase("remove")) { if (args[1].equalsIgnoreCase("option")) { if (args.length == 3) { return getListOfStringsMatchingLastWord(args, this.getScoreboard().getTeamNames()); } if (args.length == 4) { return getListOfStringsMatchingLastWord(args, new String[] {"color", "friendlyfire", "seeFriendlyInvisibles", "nametagVisibility", "deathMessageVisibility"}); } if (args.length == 5) { if (args[3].equalsIgnoreCase("color")) { return getListOfStringsMatchingLastWord(args, EnumChatFormatting.getValidValues(true, false)); } if (args[3].equalsIgnoreCase("nametagVisibility") || args[3].equalsIgnoreCase("deathMessageVisibility")) { return getListOfStringsMatchingLastWord(args, Team.EnumVisible.func_178825_a()); } if (args[3].equalsIgnoreCase("friendlyfire") || args[3].equalsIgnoreCase("seeFriendlyInvisibles")) { return getListOfStringsMatchingLastWord(args, new String[] {"true", "false"}); } } } } else if (args.length == 3) { return getListOfStringsMatchingLastWord(args, this.getScoreboard().getTeamNames()); } } } return null; } } protected List<String> func_147184_a(boolean p_147184_1_) { Collection<ScoreObjective> collection = this.getScoreboard().getScoreObjectives(); List<String> list = Lists.<String>newArrayList(); for (ScoreObjective scoreobjective : collection) { if (!p_147184_1_ || !scoreobjective.getCriteria().isReadOnly()) { list.add(scoreobjective.getName()); } } return list; } protected List<String> func_175782_e() { Collection<ScoreObjective> collection = this.getScoreboard().getScoreObjectives(); List<String> list = Lists.<String>newArrayList(); for (ScoreObjective scoreobjective : collection) { if (scoreobjective.getCriteria() == IScoreObjectiveCriteria.TRIGGER) { list.add(scoreobjective.getName()); } } return list; } /** * Return whether the specified command parameter index is a username parameter. */ public boolean isUsernameIndex(String[] args, int index) { return !args[0].equalsIgnoreCase("players") ? (args[0].equalsIgnoreCase("teams") ? index == 2 : false) : (args.length > 1 && args[1].equalsIgnoreCase("operation") ? index == 2 || index == 5 : index == 2); } }
0
0.884814
1
0.884814
game-dev
MEDIA
0.842316
game-dev
0.947764
1
0.947764
OhMyKing/Blender-Gamepad-Controls
17,496
GamepadControls.py
bl_info = { "name": "Gamepad Controls", "author": "OhMyKing", "version": (1, 1), "blender": (3, 0, 0), "location": "View3D > Sidebar > Gamepad", "description": "Control Blender with a gamepad", "category": "3D View", } import bpy import mathutils import threading import time from bpy.types import Operator, Panel, PropertyGroup from bpy.props import FloatProperty, PointerProperty, BoolProperty # 动态检测函数 def check_gamepad_available(): try: from inputs import get_gamepad # 尝试获取手柄事件,如果没有手柄会抛出异常 events = get_gamepad() return True except: return False from bpy_extras import view3d_utils # 手柄状态类 class GamepadState: def __init__(self): self.left_stick_x = 0.0 self.left_stick_y = 0.0 self.right_stick_x = 0.0 self.right_stick_y = 0.0 self.buttons = {} self.button_states = {} self.dpad_up = 0 self.dpad_down = 0 self.dpad_left = 0 self.dpad_right = 0 gamepad_state = GamepadState() # 手柄输入监听线程 class GamepadThread(threading.Thread): def __init__(self): super().__init__() self.daemon = True self.running = True self.error_message = None self._consecutive_errors = 0 # 添加连续错误计数器 self._max_consecutive_errors = 10 # 最大连续错误次数 def run(self): while self.running: try: from inputs import get_gamepad events = get_gamepad() # 成功获取事件,重置错误计数 self._consecutive_errors = 0 self.error_message = None for event in events: if self.running: # 检查是否仍在运行 self.process_event(event) except ImportError: self.error_message = "未安装 'inputs' 包。请安装后重试。" self._consecutive_errors += 1 time.sleep(1) except Exception as e: self._consecutive_errors += 1 if "No gamepad found" in str(e): self.error_message = "未检测到手柄。请确保手柄已连接。" else: self.error_message = f"手柄错误: {e}" time.sleep(0.5) # 减少等待时间,提高响应速度 # 如果连续错误次数过多,可能需要关闭控制 if self._consecutive_errors >= self._max_consecutive_errors: self.error_message = "多次无法检测到手柄,已自动关闭控制。" break def process_event(self, event): """处理手柄事件""" if event.code == 'ABS_X': gamepad_state.left_stick_x = event.state / 32768.0 elif event.code == 'ABS_Y': gamepad_state.left_stick_y = event.state / 32768.0 elif event.code == 'ABS_RX': gamepad_state.right_stick_x = event.state / 32768.0 elif event.code == 'ABS_RY': gamepad_state.right_stick_y = event.state / 32768.0 elif event.code == 'ABS_HAT0Y': if event.state == -1: gamepad_state.dpad_up = 1 gamepad_state.dpad_down = 0 elif event.state == 1: gamepad_state.dpad_down = 1 gamepad_state.dpad_up = 0 else: gamepad_state.dpad_up = 0 gamepad_state.dpad_down = 0 elif event.code == 'ABS_HAT0X': if event.state == -1: gamepad_state.dpad_left = 1 gamepad_state.dpad_right = 0 elif event.state == 1: gamepad_state.dpad_right = 1 gamepad_state.dpad_left = 0 else: gamepad_state.dpad_left = 0 gamepad_state.dpad_right = 0 elif event.code.startswith('BTN_'): gamepad_state.buttons[event.code] = event.state gamepad_state.button_states[event.code] = event.state # 设置属性 class GamepadSettings(PropertyGroup): pan_speed: FloatProperty( name="平移速度", description="视角平移的速度", default=0.1, min=0.01, max=1.0 ) rotation_speed: FloatProperty( name="旋转速度", description="视角旋转的速度", default=0.05, min=0.01, max=1.0 ) zoom_speed: FloatProperty( name="缩放速度", description="视角缩放的速度", default=0.5, min=0.1, max=2.0 ) scale_speed: FloatProperty( name="物体缩放速度", description="物体缩放的速度", default=0.05, min=0.01, max=0.5 ) move_speed: FloatProperty( name="物体移动速度", description="物体移动的速度", default=0.1, min=0.01, max=1.0 ) object_rotation_speed: FloatProperty( name="物体旋转速度", description="物体旋转的速度", default=0.05, min=0.01, max=1.0 ) invert_x_axis: BoolProperty( name="反转X轴", description="反转X轴的控制方向", default=False ) invert_y_axis: BoolProperty( name="反转Y轴", description="反转Y轴的控制方向", default=False ) invert_z_axis: BoolProperty( name="反转Z轴", description="反转Z轴的控制方向", default=False ) def update_enable_gamepad_control(self, context): if self.enable_gamepad_control: bpy.ops.gamepad.control('INVOKE_DEFAULT') else: # 操作器会检测到这个变化并自行取消 pass enable_gamepad_control: BoolProperty( name="启用手柄控制", description="启用或禁用手柄控制", default=False, update=update_enable_gamepad_control ) # 主操作器 class GAMEPAD_OT_control(Operator): bl_idname = "gamepad.control" bl_label = "手柄控制" bl_description = "启动手柄控制" _timer = None _thread = None _last_error_time = 0 # 错误消息时间戳 _last_error_message = None # 上一次错误消息 def modal(self, context, event): settings = context.scene.gamepad_settings # 检查线程状态 if self._thread: if not self._thread.is_alive(): # 线程已结束,说明发生了严重错误 settings.enable_gamepad_control = False self.report({'WARNING'}, "手柄控制已自动关闭") self.cancel(context) return {'CANCELLED'} # 检查错误信息 if self._thread.error_message: current_time = time.time() # 如果是新的错误消息或者距离上次显示超过3秒 if (self._thread.error_message != self._last_error_message or current_time - self._last_error_time > 3): self.report({'WARNING'}, self._thread.error_message) self._last_error_time = current_time self._last_error_message = self._thread.error_message # 如果提示自动关闭控制,则关闭 if "已自动关闭控制" in self._thread.error_message: settings.enable_gamepad_control = False self.cancel(context) return {'CANCELLED'} # 如果提示未安装包,则关闭 if "未安装 'inputs' 包" in self._thread.error_message: settings.enable_gamepad_control = False self.cancel(context) return {'CANCELLED'} if not settings.enable_gamepad_control: self.cancel(context) return {'CANCELLED'} if event.type == 'TIMER': view3d = context.space_data.region_3d settings = context.scene.gamepad_settings self.handle_button_actions(context) if context.active_object and context.active_object.select_get(): obj = context.active_object if abs(gamepad_state.left_stick_x) > 0.1 or abs(gamepad_state.left_stick_y) > 0.1: move_speed = settings.move_speed dx = gamepad_state.left_stick_x * move_speed dy = -gamepad_state.left_stick_y * move_speed if settings.invert_x_axis: dx = -dx if not settings.invert_y_axis: dy = -dy move_vector = mathutils.Vector((dx, dy, 0.0)) move_vector = view3d.view_rotation @ move_vector obj.location += move_vector obj.location = obj.location.copy() obj.keyframe_insert(data_path='location', group="Location") if abs(gamepad_state.right_stick_x) > 0.1 or abs(gamepad_state.right_stick_y) > 0.1: rot_speed = settings.object_rotation_speed delta_rot_x = -gamepad_state.right_stick_y * rot_speed delta_rot_z = -gamepad_state.right_stick_x * rot_speed if settings.invert_x_axis: delta_rot_x = -delta_rot_x if settings.invert_z_axis: delta_rot_z = -delta_rot_z rot_euler = mathutils.Euler((delta_rot_x, 0, delta_rot_z), 'XYZ') obj.rotation_euler.rotate(rot_euler) obj.rotation_euler = obj.rotation_euler.copy() obj.keyframe_insert(data_path='rotation_euler', group="Rotation") scale_speed = settings.scale_speed if gamepad_state.buttons.get('BTN_SOUTH'): factor = 1.0 - scale_speed obj.scale *= factor obj.scale = obj.scale.copy() obj.keyframe_insert(data_path='scale', group="Scale") if gamepad_state.buttons.get('BTN_EAST'): factor = 1.0 + scale_speed obj.scale *= factor obj.scale = obj.scale.copy() obj.keyframe_insert(data_path='scale', group="Scale") obj.update_tag() context.view_layer.update() else: if abs(gamepad_state.left_stick_x) > 0.1 or abs(gamepad_state.left_stick_y) > 0.1: pan_speed = settings.pan_speed dx = gamepad_state.left_stick_x * pan_speed dy = -gamepad_state.left_stick_y * pan_speed if settings.invert_x_axis: dx = -dx if not settings.invert_y_axis: dy = -dy view3d.view_location += view3d.view_rotation @ mathutils.Vector((dx, dy, 0.0)) if abs(gamepad_state.right_stick_x) > 0.1 or abs(gamepad_state.right_stick_y) > 0.1: rot_speed = settings.rotation_speed euler = view3d.view_rotation.to_euler() delta_euler_z = gamepad_state.right_stick_x * rot_speed delta_euler_x = gamepad_state.right_stick_y * rot_speed if settings.invert_z_axis: delta_euler_z = -delta_euler_z if settings.invert_x_axis: delta_euler_x = -delta_euler_x euler.z += delta_euler_z euler.x += delta_euler_x view3d.view_rotation = euler.to_quaternion() zoom_speed = settings.zoom_speed if gamepad_state.buttons.get('BTN_SOUTH'): view3d.view_distance += zoom_speed if gamepad_state.buttons.get('BTN_EAST'): view3d.view_distance -= zoom_speed self.handle_dpad_view_switch(context) context.area.tag_redraw() return {'RUNNING_MODAL'} # 改为 RUNNING_MODAL 以确保持续运行 elif event.type == 'ESC': self.cancel(context) return {'CANCELLED'} return {'PASS_THROUGH'} def handle_button_actions(self, context): if gamepad_state.button_states.get('BTN_WEST') == 1: self.simulate_keypress(context, 'Z', ctrl=True) gamepad_state.button_states['BTN_WEST'] = 0 if gamepad_state.button_states.get('BTN_NORTH') == 1: self.simulate_keypress(context, 'Z', ctrl=True, shift=True) gamepad_state.button_states['BTN_NORTH'] = 0 def handle_dpad_view_switch(self, context): if gamepad_state.dpad_up == 1: bpy.ops.view3d.view_axis(type='TOP') gamepad_state.dpad_up = 0 if gamepad_state.dpad_down == 1: bpy.ops.view3d.view_axis(type='FRONT') gamepad_state.dpad_down = 0 if gamepad_state.dpad_left == 1: bpy.ops.view3d.view_axis(type='LEFT') gamepad_state.dpad_left = 0 if gamepad_state.dpad_right == 1: bpy.ops.view3d.view_axis(type='RIGHT') gamepad_state.dpad_right = 0 def simulate_keypress(self, context, key, ctrl=False, shift=False, alt=False): try: if key == 'Z' and ctrl and not shift and not alt: bpy.ops.ed.undo() elif key == 'Z' and ctrl and shift and not alt: bpy.ops.ed.redo() except Exception as e: if 'undo' in str(e).lower(): self.report({'INFO'}, "没有可以撤销的操作") elif 'redo' in str(e).lower(): self.report({'INFO'}, "没有可以重做的操作") else: self.report({'WARNING'}, f"操作失败: {str(e)}") def execute(self, context): if context.area.type != 'VIEW_3D': self.report({'WARNING'}, "激活区域必须是3D视图") return {'CANCELLED'} # 重置手柄状态 global gamepad_state gamepad_state = GamepadState() # 开始新线程 self._thread = GamepadThread() self._thread.start() # 设置计时器 wm = context.window_manager self._timer = wm.event_timer_add(1 / 60, window=context.window) wm.modal_handler_add(self) return {'RUNNING_MODAL'} def cancel(self, context): if self._timer: context.window_manager.event_timer_remove(self._timer) if self._thread: self._thread.running = False self._thread.join(timeout=1.0) # 添加超时 # 重置手柄状态 global gamepad_state gamepad_state = GamepadState() # UI 面板 class GAMEPAD_PT_panel(Panel): bl_label = "游戏手柄控制" bl_idname = "GAMEPAD_PT_panel" bl_space_type = 'VIEW_3D' bl_region_type = 'UI' bl_category = 'Gamepad' @classmethod def poll(cls, context): return context.area.type == 'VIEW_3D' def check_inputs_package(self): try: import inputs return True except ImportError: return False def draw(self, context): layout = self.layout settings = context.scene.gamepad_settings box = layout.box() row = box.row() row.prop(settings, "enable_gamepad_control") # 检查 inputs 包是否安装 inputs_available = self.check_inputs_package() if not inputs_available: box.label(text="请安装 'inputs' 包", icon='ERROR') box.label(text="pip install inputs", icon='CONSOLE') return # 如果 inputs 包已安装,显示其他设置 if settings.enable_gamepad_control: box = layout.box() box.label(text="视角控制设置:", icon='VIEW3D') box.prop(settings, "pan_speed") box.prop(settings, "rotation_speed") box.prop(settings, "zoom_speed") box = layout.box() box.label(text="物体控制设置:", icon='OBJECT_DATA') box.prop(settings, "scale_speed") box.prop(settings, "move_speed") box.prop(settings, "object_rotation_speed") box = layout.box() box.label(text="轴向设置:", icon='ORIENTATION_GIMBAL') box.prop(settings, "invert_x_axis") box.prop(settings, "invert_y_axis") box.prop(settings, "invert_z_axis") # 添加控制说明 help_box = layout.box() help_box.label(text="控制说明:", icon='HELP') col = help_box.column(align=True) col.label(text="左摇杆: 平移/物体移动") col.label(text="右摇杆: 旋转") col.label(text="A键(BTN_SOUTH): 放大/缩小") col.label(text="B键(BTN_EAST): 缩小/放大") col.label(text="X键(BTN_WEST): 撤销") col.label(text="Y键(BTN_NORTH): 重做") col.label(text="方向键: 切换视图") classes = ( GamepadSettings, GAMEPAD_OT_control, GAMEPAD_PT_panel, ) def safe_register(): """安全注册所有类""" try: # 注册属性组 if not hasattr(bpy.types.Scene, "gamepad_settings"): bpy.utils.register_class(GamepadSettings) bpy.types.Scene.gamepad_settings = PointerProperty(type=GamepadSettings) # 注册操作器和面板 bpy.utils.register_class(GAMEPAD_OT_control) bpy.utils.register_class(GAMEPAD_PT_panel) return True except Exception as e: print(f"游戏手柄插件注册失败: {str(e)}") return False def safe_unregister(): """安全注销所有类""" try: # 注销操作器和面板 bpy.utils.unregister_class(GAMEPAD_PT_panel) bpy.utils.unregister_class(GAMEPAD_OT_control) # 注销属性组 if hasattr(bpy.types.Scene, "gamepad_settings"): bpy.utils.unregister_class(GamepadSettings) del bpy.types.Scene.gamepad_settings except Exception as e: print(f"游戏手柄插件注销失败: {str(e)}") def register(): """插件注册入口点""" if not safe_register(): # 如果注册失败,确保完全清理 safe_unregister() return {'CANCELLED'} return {'FINISHED'} def unregister(): """插件注销入口点""" safe_unregister() if __name__ == "__main__": register()
0
0.725554
1
0.725554
game-dev
MEDIA
0.484751
game-dev,desktop-app
0.937113
1
0.937113
Aussiemon/Darktide-Source-Code
7,910
scripts/extension_systems/visual_loadout/wieldable_slot_scripts/zealot_relic_effects.lua
-- chunkname: @scripts/extension_systems/visual_loadout/wieldable_slot_scripts/zealot_relic_effects.lua local Action = require("scripts/utilities/action/action") local FixedFrame = require("scripts/utilities/fixed_frame") local TalentSettings = require("scripts/settings/talent/talent_settings") local WieldableSlotScriptInterface = require("scripts/extension_systems/visual_loadout/wieldable_slot_scripts/wieldable_slot_script_interface") local talent_settings_3 = TalentSettings.zealot_3 local EQUIPPED_LOOPING_SOUND_ALIAS = "equipped_item_passive_loop" local EQUIPPED_LOOPING_PARTICLE_ALIAS = "equipped_item_passive" local FX_SOURCE_NAME = "_emit" local _external_properties = {} local ZealotRelicEffects = class("ZealotRelicEffects") ZealotRelicEffects.init = function (self, context, slot, weapon_template, fx_sources, item, unit_1p, unit_3p) local unit = context.owner_unit local wwise_world = context.wwise_world local unit_data_extension = ScriptUnit.extension(unit, "unit_data_system") self._is_husk = context.is_husk self._is_local_unit = context.is_local_unit self._unit = unit self._world = context.world self._wwise_world = wwise_world self._vfx = weapon_template.vfx self._weapon_template = weapon_template self._weapon_actions = weapon_template.actions self._fx_source_name = fx_sources[FX_SOURCE_NAME] self._fx_extension = context.fx_extension self._visual_loadout_extension = context.visual_loadout_extension self._tick_cooldown = 0 self._start_tick_cooldown = 0 self._num_tick = 0 self._ability_extension = ScriptUnit.extension(unit, "ability_system") self._weapon_action_component = unit_data_extension:read_component("weapon_action") local first_person_component = unit_data_extension:read_component("first_person") local rotation = first_person_component.rotation self._source_id = WwiseWorld.make_manual_source(wwise_world, unit, rotation) end ZealotRelicEffects.fixed_update = function (self, unit, dt, t) return end ZealotRelicEffects.update = function (self, unit, dt, t, frame) local current_action_name = self._weapon_action_component.current_action_name if current_action_name ~= "action_zealot_channel" then return end local tick_cooldown = self._tick_cooldown - dt if tick_cooldown <= 0 then self:_destroy_pulse_vfx() self:_on_channel_tick(t) tick_cooldown = talent_settings_3.bolstering_prayer.tick_rate self._num_tick = self._num_tick + 1 end self._tick_cooldown = tick_cooldown local max = self._ability_extension:max_ability_cooldown("combat_ability") local current = self._ability_extension:remaining_ability_cooldown("combat_ability") local variable = (max - current) / max WwiseWorld.set_source_parameter(self._wwise_world, self._source_id, "player_ability_health", variable) end ZealotRelicEffects.update_first_person_mode = function (self, first_person_mode) return end ZealotRelicEffects._on_channel_tick = function (self, t, action_settings) action_settings = action_settings or Action.current_action_settings_from_component(self._weapon_action_component, self._weapon_actions) self._action_settings = action_settings if not self._action_settings then return end if self._num_tick == 0 then self:_trigger_pulse_sfx(t, action_settings) self:_trigger_pulse_vfx(t, action_settings) else self:_trigger_pulse_vfx(t, action_settings) self:_trigger_pulse_sfx(t, action_settings) end end ZealotRelicEffects._trigger_pulse_vfx = function (self, t, action_settings) self:_destroy_pulse_vfx() local time_in_action = t - self._weapon_action_component.start_t local effect_name = self._vfx.name local unit_position = Unit.world_position(self._unit, 1) local position = unit_position + Vector3.up() local radius_time_in_action_multiplier = action_settings.radius_time_in_action_multiplier or 0 local radius = action_settings.radius + time_in_action * radius_time_in_action_multiplier local variable_name = "radius" local variable_value = Vector3(radius, radius, radius) local effect_id = World.create_particles(self._world, effect_name, position, nil, nil, nil) local variable_index = World.find_particles_variable(self._world, effect_name, variable_name) World.set_particles_variable(self._world, effect_id, variable_index, variable_value) self._effect_id = effect_id end ZealotRelicEffects._trigger_pulse_sfx = function (self, t, action_settings) local source_name = action_settings.sound_source or "head" local sync_to_clients = action_settings.has_husk_sound local include_client = false table.clear(_external_properties) _external_properties.ability_template = "zealot_relic" self._fx_extension:trigger_gear_wwise_event_with_source("ability_shout", _external_properties, source_name, sync_to_clients, include_client) end ZealotRelicEffects._destroy_pulse_vfx = function (self) local world = self._world if self._effect_id then World.destroy_particles(world, self._effect_id) self._effect_id = nil end end ZealotRelicEffects.wield = function (self) self._tick_cooldown = self._start_tick_cooldown self._num_tick = 0 self:_create_passive_vfx() self:_create_passive_sfx() end ZealotRelicEffects.unwield = function (self) if self._tick_cooldown < self._start_tick_cooldown then self:_destroy_pulse_vfx() local t = FixedFrame.get_latest_fixed_time() self:_on_channel_tick(t, self._action_settings) end self:_destroy_passive_vfx() self:_destroy_passive_sfx() end ZealotRelicEffects.destroy = function (self) self:_destroy_pulse_vfx() self:_destroy_passive_vfx() self:_destroy_passive_sfx() end ZealotRelicEffects._create_passive_vfx = function (self) local resolved, effect_name = self._visual_loadout_extension:resolve_gear_particle(EQUIPPED_LOOPING_PARTICLE_ALIAS, _external_properties) if resolved then local world = self._world local effect_id = World.create_particles(world, effect_name, Vector3.zero()) local vfx_link_unit, vfx_link_node = self._fx_extension:vfx_spawner_unit_and_node(self._fx_source_name) World.link_particles(world, effect_id, vfx_link_unit, vfx_link_node, Matrix4x4.identity(), "stop") self._looping_passive_effect_id = effect_id end end ZealotRelicEffects._destroy_passive_vfx = function (self) if self._looping_passive_effect_id then World.destroy_particles(self._world, self._looping_passive_effect_id) self._looping_passive_effect_id = nil end end ZealotRelicEffects._create_passive_sfx = function (self) local visual_loadout_extension = self._visual_loadout_extension local fx_extension = self._fx_extension local fx_source_name = self._fx_source_name local should_play_husk_effect = self._fx_extension:should_play_husk_effect() if not self._looping_passive_playing_id then local resolved, event_name, resolved_stop, stop_event_name = visual_loadout_extension:resolve_looping_gear_sound(EQUIPPED_LOOPING_SOUND_ALIAS, should_play_husk_effect, _external_properties) if resolved then local wwise_world = self._wwise_world local source_id = fx_extension:sound_source(fx_source_name) local playing_id = WwiseWorld.trigger_resource_event(wwise_world, event_name, source_id) self._looping_passive_playing_id = playing_id if resolved_stop then self._stop_event_name = stop_event_name end end end end ZealotRelicEffects._destroy_passive_sfx = function (self) local looping_passive_playing_id = self._looping_passive_playing_id if looping_passive_playing_id then local stop_event_name = self._stop_event_name if stop_event_name then local source_id = self._fx_extension:sound_source(self._fx_source_name) WwiseWorld.trigger_resource_event(self._wwise_world, stop_event_name, source_id) else WwiseWorld.stop_event(self._wwise_world, looping_passive_playing_id) end self._looping_passive_playing_id = nil self._stop_event_name = nil end end implements(ZealotRelicEffects, WieldableSlotScriptInterface) return ZealotRelicEffects
0
0.878937
1
0.878937
game-dev
MEDIA
0.985228
game-dev
0.964803
1
0.964803
frang75/nappgui_src
21,698
src/geom2d/v2d.cpp
/* * NAppGUI Cross-platform C SDK * 2015-2025 Francisco Garcia Collado * MIT Licence * https://nappgui.com/en/legal/license.html * * File: v2d.cpp * */ /* Vector 2d */ #include "v2d.h" #include "v2d.hpp" #include <sewer/bmath.hpp> #include <sewer/cassert.h> /*---------------------------------------------------------------------------*/ V2Df v2df(const real32_t x, const real32_t y) { V2Df v; v.x = x; v.y = y; return v; } /*---------------------------------------------------------------------------*/ V2Dd v2dd(const real64_t x, const real64_t y) { V2Dd v; v.x = x; v.y = y; return v; } /*---------------------------------------------------------------------------*/ V2Df v2d_tof(const V2Dd *v) { V2Df vf; cassert_no_null(v); vf.x = (real32_t)v->x; vf.y = (real32_t)v->y; return vf; } /*---------------------------------------------------------------------------*/ V2Dd v2d_tod(const V2Df *v) { V2Dd vd; cassert_no_null(v); vd.x = (real64_t)v->x; vd.y = (real64_t)v->y; return vd; } /*---------------------------------------------------------------------------*/ void v2d_tofn(V2Df *vf, const V2Dd *vd, const uint32_t n) { uint32_t i = 0; for (i = 0; i < n; ++i) { vf[i].x = (real32_t)vd[i].x; vf[i].y = (real32_t)vd[i].y; } } /*---------------------------------------------------------------------------*/ void v2d_todn(V2Dd *vd, const V2Df *vf, const uint32_t n) { uint32_t i = 0; for (i = 0; i < n; ++i) { vd[i].x = (real64_t)vf[i].x; vd[i].y = (real64_t)vf[i].y; } } /*---------------------------------------------------------------------------*/ template < typename real > static V2D< real > i_add(const V2D< real > *v1, const V2D< real > *v2) { V2D< real > r; r.x = v1->x + v2->x; r.y = v1->y + v2->y; return r; } /*---------------------------------------------------------------------------*/ V2Df v2d_addf(const V2Df *v1, const V2Df *v2) { V2Df r; r.x = v1->x + v2->x; r.y = v1->y + v2->y; return r; } /*---------------------------------------------------------------------------*/ V2Dd v2d_addd(const V2Dd *v1, const V2Dd *v2) { V2Dd r; r.x = v1->x + v2->x; r.y = v1->y + v2->y; return r; } /*---------------------------------------------------------------------------*/ template < typename real > static V2D< real > i_sub(const V2D< real > *v1, const V2D< real > *v2) { V2D< real > r; r.x = v1->x - v2->x; r.y = v1->y - v2->y; return r; } /*---------------------------------------------------------------------------*/ V2Df v2d_subf(const V2Df *v1, const V2Df *v2) { V2Df r; r.x = v1->x - v2->x; r.y = v1->y - v2->y; return r; } /*---------------------------------------------------------------------------*/ V2Dd v2d_subd(const V2Dd *v1, const V2Dd *v2) { V2Dd r; r.x = v1->x - v2->x; r.y = v1->y - v2->y; return r; } /*---------------------------------------------------------------------------*/ template < typename real > static V2D< real > i_mul(const V2D< real > *v, const real s) { V2D< real > r; r.x = v->x * s; r.y = v->y * s; return r; } /*---------------------------------------------------------------------------*/ V2Df v2d_mulf(const V2Df *v, const real32_t s) { V2Df r; r.x = v->x * s; r.y = v->y * s; return r; } /*---------------------------------------------------------------------------*/ V2Dd v2d_muld(const V2Dd *v, const real64_t s) { V2Dd r; r.x = v->x * s; r.y = v->y * s; return r; } /*---------------------------------------------------------------------------*/ template < typename real > static V2D< real > i_unit_xy(const real x1, const real y1, const real x2, const real y2, real *length) { real dX, dY; real dot; V2D< real > r; dX = x2 - x1; dY = y2 - y1; dot = dX * dX + dY * dY; if (dot > 0) { dot = BMath< real >::sqrt(dot); if (length != NULL) *length = dot; r.x = dX / dot; r.y = dY / dot; } else { if (length != NULL) *length = 0; r.x = 0; r.y = 0; } return r; } /*---------------------------------------------------------------------------*/ template < typename real > static V2D< real > i_unit(const V2D< real > *v1, const V2D< real > *v2, real *length) { cassert_no_null(v1); cassert_no_null(v2); return i_unit_xy< real >(v1->x, v1->y, v2->x, v2->y, length); } /*---------------------------------------------------------------------------*/ V2Df v2d_unitf(const V2Df *v1, const V2Df *v2, real32_t *length) { V2D< real32_t > r = i_unit< real32_t >((const V2D< real32_t > *)v1, (const V2D< real32_t > *)v2, length); V2Df rr; rr.x = r.x; rr.y = r.y; return rr; } /*---------------------------------------------------------------------------*/ V2Dd v2d_unitd(const V2Dd *v1, const V2Dd *v2, real64_t *length) { V2D< real64_t > r = i_unit< real64_t >((const V2D< real64_t > *)v1, (const V2D< real64_t > *)v2, length); V2Dd rr; rr.x = r.x; rr.y = r.y; return rr; } /*---------------------------------------------------------------------------*/ V2Df v2d_unit_xyf(const real32_t x1, const real32_t y1, const real32_t x2, const real32_t y2, real32_t *length) { V2D< real32_t > r = i_unit_xy< real32_t >(x1, y1, x2, y2, length); V2Df rr; rr.x = r.x; rr.y = r.y; return rr; } /*---------------------------------------------------------------------------*/ V2Dd v2d_unit_xyd(const real64_t x1, const real64_t y1, const real64_t x2, const real64_t y2, real64_t *length) { V2D< real64_t > r = i_unit_xy< real64_t >(x1, y1, x2, y2, length); V2Dd rr; rr.x = r.x; rr.y = r.y; return rr; } /*---------------------------------------------------------------------------*/ template < typename real > static V2D< real > i_perp_pos(const V2D< real > *v) { V2D< real > r; cassert_no_null(v); r.x = -v->y; r.y = v->x; return r; } /*---------------------------------------------------------------------------*/ V2Df v2d_perp_posf(const V2Df *v) { V2Df r; cassert_no_null(v); r.x = -v->y; r.y = v->x; return r; } /*---------------------------------------------------------------------------*/ V2Dd v2d_perp_posd(const V2Dd *v) { V2Dd r; cassert_no_null(v); r.x = -v->y; r.y = v->x; return r; } /*---------------------------------------------------------------------------*/ template < typename real > static V2D< real > i_perp_neg(const V2D< real > *v) { V2D< real > r; cassert_no_null(v); r.x = v->y; r.y = -v->x; return r; } /*---------------------------------------------------------------------------*/ V2Df v2d_perp_negf(const V2Df *v) { V2Df r; cassert_no_null(v); r.x = v->y; r.y = -v->x; return r; } /*---------------------------------------------------------------------------*/ V2Dd v2d_perp_negd(const V2Dd *v) { V2Dd r; cassert_no_null(v); r.x = v->y; r.y = -v->x; return r; } /*---------------------------------------------------------------------------*/ template < typename real > static V2D< real > i_from_angle(const real a) { V2D< real > v; v.x = BMath< real >::cos(a); v.y = BMath< real >::sin(a); return v; } /*---------------------------------------------------------------------------*/ V2Df v2d_from_anglef(const real32_t a) { V2D< real32_t > v = i_from_angle< real32_t >(a); V2Df *vv = (V2Df *)&v; return *vv; } /*---------------------------------------------------------------------------*/ V2Dd v2d_from_angled(const real64_t a) { V2D< real64_t > v = i_from_angle< real64_t >(a); V2Dd *vv = (V2Dd *)&v; return *vv; } /*---------------------------------------------------------------------------*/ template < typename real > static V2D< real > i_from(const V2D< real > *v, const V2D< real > *dir, const real length) { V2D< real > r; cassert_no_null(v); cassert_no_null(dir); r.x = v->x + dir->x * length; r.y = v->y + dir->y * length; return r; } /*---------------------------------------------------------------------------*/ V2Df v2d_fromf(const V2Df *v, const V2Df *dir, const real32_t length) { V2Df r; cassert_no_null(v); cassert_no_null(dir); r.x = v->x + dir->x * length; r.y = v->y + dir->y * length; return r; } /*---------------------------------------------------------------------------*/ V2Dd v2d_fromd(const V2Dd *v, const V2Dd *dir, const real64_t length) { V2Dd r; cassert_no_null(v); cassert_no_null(dir); r.x = v->x + dir->x * length; r.y = v->y + dir->y * length; return r; } /*---------------------------------------------------------------------------*/ template < typename real > static V2D< real > i_mid(const V2D< real > *v1, const V2D< real > *v2) { V2D< real > r; cassert_no_null(v1); cassert_no_null(v2); r.x = (real).5 * (v1->x + v2->x); r.y = (real).5 * (v1->y + v2->y); return r; } /*---------------------------------------------------------------------------*/ V2Df v2d_midf(const V2Df *v1, const V2Df *v2) { V2Df r; cassert_no_null(v1); cassert_no_null(v2); r.x = .5f * (v1->x + v2->x); r.y = .5f * (v1->y + v2->y); return r; } /*---------------------------------------------------------------------------*/ V2Dd v2d_midd(const V2Dd *v1, const V2Dd *v2) { V2Dd r; cassert_no_null(v1); cassert_no_null(v2); r.x = .5 * (v1->x + v2->x); r.y = .5 * (v1->y + v2->y); return r; } /*---------------------------------------------------------------------------*/ /*bool_t v2d_is_normdf(const V2Df *v2d); bool_t v2d_is_normdf(const V2Df *v2d) { real32_t dotprod; cassert_no_null(v2d); dotprod = v2d->x * v2d->x + v2d->y * v2d->y; if (bmath_absf(dotprod - 1.f) < kTINY3f) return TRUE; else return FALSE; }*/ /*---------------------------------------------------------------------------*/ template < typename real > static bool_t i_norm(V2D< real > *v) { real dot_prod; cassert_no_null(v); dot_prod = v->x * v->x + v->y * v->y; if (dot_prod > 0) { real one_over_norm = BMath< real >::isqrt(dot_prod); v->x *= one_over_norm; v->y *= one_over_norm; return TRUE; } else { return FALSE; } } /*---------------------------------------------------------------------------*/ bool_t v2d_normf(V2Df *v) { return i_norm< real32_t >((V2D< real32_t > *)v); } /*---------------------------------------------------------------------------*/ bool_t v2d_normd(V2Dd *v) { return i_norm< real64_t >((V2D< real64_t > *)v); } /*---------------------------------------------------------------------------*/ template < typename real > static real i_length(const V2D< real > *v) { real dot; cassert_no_null(v); dot = v->x * v->x + v->y * v->y; if (dot > 0) return BMath< real >::sqrt(dot); else return 0; } /*---------------------------------------------------------------------------*/ real32_t v2d_lengthf(const V2Df *v) { return i_length< real32_t >((const V2D< real32_t > *)v); } /*---------------------------------------------------------------------------*/ real64_t v2d_lengthd(const V2Dd *v) { return i_length< real64_t >((const V2D< real64_t > *)v); } /*---------------------------------------------------------------------------*/ template < typename real > static real i_sqlength(const V2D< real > *v) { cassert_no_null(v); return v->x * v->x + v->y * v->y; } /*---------------------------------------------------------------------------*/ real32_t v2d_sqlengthf(const V2Df *v) { return i_sqlength< real32_t >((const V2D< real32_t > *)v); } /*---------------------------------------------------------------------------*/ real64_t v2d_sqlengthd(const V2Dd *v) { return i_sqlength< real64_t >((const V2D< real64_t > *)v); } /*---------------------------------------------------------------------------*/ template < typename real > static real i_dot(const V2D< real > *v1, const V2D< real > *v2) { cassert_no_null(v1); cassert_no_null(v2); return v1->x * v2->x + v1->y * v2->y; } /*---------------------------------------------------------------------------*/ real32_t v2d_dotf(const V2Df *v1, const V2Df *v2) { return i_dot< real32_t >((const V2D< real32_t > *)v1, (const V2D< real32_t > *)v2); } /*---------------------------------------------------------------------------*/ real64_t v2d_dotd(const V2Dd *v1, const V2Dd *v2) { return i_dot< real64_t >((const V2D< real64_t > *)v1, (const V2D< real64_t > *)v2); } /*---------------------------------------------------------------------------*/ template < typename real > static real i_dist(const V2D< real > *v1, const V2D< real > *v2) { real dX, dY; real dot; cassert_no_null(v1); cassert_no_null(v2); dX = v2->x - v1->x; dY = v2->y - v1->y; dot = dX * dX + dY * dY; if (dot > 0) return BMath< real >::sqrt(dot); else return 0; } /*---------------------------------------------------------------------------*/ real32_t v2d_distf(const V2Df *v1, const V2Df *v2) { return i_dist< real32_t >((const V2D< real32_t > *)v1, (const V2D< real32_t > *)v2); } /*---------------------------------------------------------------------------*/ real64_t v2d_distd(const V2Dd *v1, const V2Dd *v2) { return i_dist< real64_t >((const V2D< real64_t > *)v1, (const V2D< real64_t > *)v2); } /*---------------------------------------------------------------------------*/ template < typename real > static real i_sqdist(const V2D< real > *v1, const V2D< real > *v2) { real dX, dY; cassert_no_null(v1); cassert_no_null(v2); dX = v2->x - v1->x; dY = v2->y - v1->y; return dX * dX + dY * dY; } /*---------------------------------------------------------------------------*/ real32_t v2d_sqdistf(const V2Df *v1, const V2Df *v2) { return i_sqdist< real32_t >((const V2D< real32_t > *)v1, (const V2D< real32_t > *)v2); } /*---------------------------------------------------------------------------*/ real64_t v2d_sqdistd(const V2Dd *v1, const V2Dd *v2) { return i_sqdist< real64_t >((const V2D< real64_t > *)v1, (const V2D< real64_t > *)v2); } /*---------------------------------------------------------------------------*/ template < typename real > static real i_angle(const V2D< real > *v1, const V2D< real > *v2) { //real d, d1, d2, l1, l2, c; //cassert_no_null(v1); //cassert_no_null(v2); //d = v1->x * v2->x + v1->y * v2->y; //d1 = v1->x * v1->x + v1->y * v1->y; //d2 = v2->x * v2->x + v2->y * v2->y; //l1 = BMath<real>::sqrt(d1); //l2 = BMath<real>::sqrt(d2); //c = d / (l1 * l2); //return BMath<real>::acos(c); // https://www.mathworks.com/matlabcentral/answers/180131-how-can-i-find-the-angle-between-two-vectors-including-directional-information real y, x; cassert_no_null(v1); cassert_no_null(v2); y = v1->x * v2->y - v1->y * v2->x; x = v1->x * v2->x + v1->y * v2->y; return BMath< real >::atan2(y, x); } /*---------------------------------------------------------------------------*/ real32_t v2d_anglef(const V2Df *v1, const V2Df *v2) { return i_angle< real32_t >((const V2D< real32_t > *)v1, (const V2D< real32_t > *)v2); } /*---------------------------------------------------------------------------*/ real64_t v2d_angled(const V2Dd *v1, const V2Dd *v2) { return i_angle< real64_t >((const V2D< real64_t > *)v1, (const V2D< real64_t > *)v2); } /*---------------------------------------------------------------------------*/ template < typename real > static void i_rotate(V2D< real > *v, const real a) { V2D< real > r; real c, s; cassert_no_null(v); c = BMath< real >::cos(a); s = BMath< real >::sin(a); r.x = v->x * c - v->y * s; r.y = v->x * s + v->y * c; *v = r; } /*---------------------------------------------------------------------------*/ void v2d_rotatef(V2Df *v, const real32_t a) { i_rotate< real32_t >((V2D< real32_t > *)v, a); } /*---------------------------------------------------------------------------*/ void v2d_rotated(V2Dd *v, const real64_t a) { i_rotate< real64_t >((V2D< real64_t > *)v, a); } /*---------------------------------------------------------------------------*/ const V2Df kV2D_ZEROf = {0, 0}; const V2Dd kV2D_ZEROd = {0, 0}; const V2Df kV2D_Xf = {1, 0}; const V2Dd kV2D_Xd = {1, 0}; const V2Df kV2D_Yf = {0, 1}; const V2Dd kV2D_Yd = {0, 1}; template <> const V2D< real32_t >(*V2D< real32_t >::kZERO) = ((V2D< real32_t > *)&kV2D_ZEROf); template <> const V2D< real64_t >(*V2D< real64_t >::kZERO) = ((V2D< real64_t > *)&kV2D_ZEROd); template <> const V2D< real32_t >(*V2D< real32_t >::kX) = ((V2D< real32_t > *)&kV2D_Xf); template <> const V2D< real64_t >(*V2D< real64_t >::kX) = ((V2D< real64_t > *)&kV2D_Xd); template <> const V2D< real32_t >(*V2D< real32_t >::kY) = ((V2D< real32_t > *)&kV2D_Yf); template <> const V2D< real64_t >(*V2D< real64_t >::kY) = ((V2D< real64_t > *)&kV2D_Yd); /*---------------------------------------------------------------------------*/ template <> V2D< real32_t > (*V2D< real32_t >::add)(const V2D< real32_t > *, const V2D< real32_t > *) = i_add< real32_t >; template <> V2D< real64_t > (*V2D< real64_t >::add)(const V2D< real64_t > *, const V2D< real64_t > *) = i_add< real64_t >; template <> V2D< real32_t > (*V2D< real32_t >::sub)(const V2D< real32_t > *, const V2D< real32_t > *) = i_sub< real32_t >; template <> V2D< real64_t > (*V2D< real64_t >::sub)(const V2D< real64_t > *, const V2D< real64_t > *) = i_sub< real64_t >; template <> V2D< real32_t > (*V2D< real32_t >::mul)(const V2D< real32_t > *, const real32_t) = i_mul< real32_t >; template <> V2D< real64_t > (*V2D< real64_t >::mul)(const V2D< real64_t > *, const real64_t) = i_mul< real64_t >; template <> V2D< real32_t > (*V2D< real32_t >::from)(const V2D< real32_t > *, const V2D< real32_t > *, const real32_t) = i_from< real32_t >; template <> V2D< real64_t > (*V2D< real64_t >::from)(const V2D< real64_t > *, const V2D< real64_t > *, const real64_t) = i_from< real64_t >; template <> V2D< real32_t > (*V2D< real32_t >::mid)(const V2D< real32_t > *, const V2D< real32_t > *) = i_mid< real32_t >; template <> V2D< real64_t > (*V2D< real64_t >::mid)(const V2D< real64_t > *, const V2D< real64_t > *) = i_mid< real64_t >; template <> V2D< real32_t > (*V2D< real32_t >::unit)(const V2D< real32_t > *, const V2D< real32_t > *, real32_t *) = i_unit< real32_t >; template <> V2D< real64_t > (*V2D< real64_t >::unit)(const V2D< real64_t > *, const V2D< real64_t > *, real64_t *) = i_unit< real64_t >; template <> V2D< real32_t > (*V2D< real32_t >::unit_xy)(const real32_t, const real32_t, const real32_t, const real32_t, real32_t *) = i_unit_xy< real32_t >; template <> V2D< real64_t > (*V2D< real64_t >::unit_xy)(const real64_t, const real64_t, const real64_t, const real64_t, real64_t *) = i_unit_xy< real64_t >; template <> V2D< real32_t > (*V2D< real32_t >::perp_pos)(const V2D< real32_t > *) = i_perp_pos< real32_t >; template <> V2D< real64_t > (*V2D< real64_t >::perp_pos)(const V2D< real64_t > *) = i_perp_pos< real64_t >; template <> V2D< real32_t > (*V2D< real32_t >::perp_neg)(const V2D< real32_t > *) = i_perp_neg< real32_t >; template <> V2D< real64_t > (*V2D< real64_t >::perp_neg)(const V2D< real64_t > *) = i_perp_neg< real64_t >; template <> V2D< real32_t > (*V2D< real32_t >::from_angle)(const real32_t) = i_from_angle< real32_t >; template <> V2D< real64_t > (*V2D< real64_t >::from_angle)(const real64_t) = i_from_angle< real64_t >; template <> bool_t (*V2D< real32_t >::norm)(V2D< real32_t > *) = i_norm< real32_t >; template <> bool_t (*V2D< real64_t >::norm)(V2D< real64_t > *) = i_norm< real64_t >; template <> real32_t (*V2D< real32_t >::length)(const V2D< real32_t > *) = i_length< real32_t >; template <> real64_t (*V2D< real64_t >::length)(const V2D< real64_t > *) = i_length< real64_t >; template <> real32_t (*V2D< real32_t >::sqlength)(const V2D< real32_t > *) = i_sqlength< real32_t >; template <> real64_t (*V2D< real64_t >::sqlength)(const V2D< real64_t > *) = i_sqlength< real64_t >; template <> real32_t (*V2D< real32_t >::dot)(const V2D< real32_t > *, const V2D< real32_t > *) = i_dot< real32_t >; template <> real64_t (*V2D< real64_t >::dot)(const V2D< real64_t > *, const V2D< real64_t > *) = i_dot< real64_t >; template <> real32_t (*V2D< real32_t >::dist)(const V2D< real32_t > *, const V2D< real32_t > *) = i_dist< real32_t >; template <> real64_t (*V2D< real64_t >::dist)(const V2D< real64_t > *, const V2D< real64_t > *) = i_dist< real64_t >; template <> real32_t (*V2D< real32_t >::sqdist)(const V2D< real32_t > *, const V2D< real32_t > *) = i_sqdist< real32_t >; template <> real64_t (*V2D< real64_t >::sqdist)(const V2D< real64_t > *, const V2D< real64_t > *) = i_sqdist< real64_t >; template <> real32_t (*V2D< real32_t >::angle)(const V2D< real32_t > *, const V2D< real32_t > *) = i_angle< real32_t >; template <> real64_t (*V2D< real64_t >::angle)(const V2D< real64_t > *, const V2D< real64_t > *) = i_angle< real64_t >; template <> void (*V2D< real32_t >::rotate)(V2D< real32_t > *, const real32_t) = i_rotate< real32_t >; template <> void (*V2D< real64_t >::rotate)(V2D< real64_t > *, const real64_t) = i_rotate< real64_t >;
0
0.716456
1
0.716456
game-dev
MEDIA
0.56727
game-dev
0.604084
1
0.604084
FreshTomato-Project/freshtomato-arm
5,248
release/src-rt-6.x.4708/router/php/ext/gd/libgd/gd_xbm.c
/* +----------------------------------------------------------------------+ | Copyright (c) The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | https://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Marcus Boerger <helly@php.net> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include <stdio.h> #include <math.h> #include <string.h> #include <stdlib.h> #include "gd.h" #include "gdhelpers.h" #include "gd_errors.h" #include "php.h" #define MAX_XBM_LINE_SIZE 255 /* {{{ gdImagePtr gdImageCreateFromXbm */ gdImagePtr gdImageCreateFromXbm(FILE * fd) { char fline[MAX_XBM_LINE_SIZE]; char iname[MAX_XBM_LINE_SIZE]; char *type; int value; unsigned int width = 0, height = 0; int fail = 0; int max_bit = 0; gdImagePtr im; int bytes = 0, i; int bit, x = 0, y = 0; int ch; char h[8]; unsigned int b; rewind(fd); while (fgets(fline, MAX_XBM_LINE_SIZE, fd)) { fline[MAX_XBM_LINE_SIZE-1] = '\0'; if (strlen(fline) == MAX_XBM_LINE_SIZE-1) { return 0; } if (sscanf(fline, "#define %s %d", iname, &value) == 2) { if (!(type = strrchr(iname, '_'))) { type = iname; } else { type++; } if (!strcmp("width", type)) { width = (unsigned int) value; } if (!strcmp("height", type)) { height = (unsigned int) value; } } else { if ( sscanf(fline, "static unsigned char %s = {", iname) == 1 || sscanf(fline, "static char %s = {", iname) == 1) { max_bit = 128; } else if (sscanf(fline, "static unsigned short %s = {", iname) == 1 || sscanf(fline, "static short %s = {", iname) == 1) { max_bit = 32768; } if (max_bit) { bytes = (width + 7) / 8 * height; if (!bytes) { return 0; } if (!(type = strrchr(iname, '_'))) { type = iname; } else { type++; } if (!strcmp("bits[]", type)) { break; } } } } if (!bytes || !max_bit) { return 0; } if(!(im = gdImageCreate(width, height))) { return 0; } gdImageColorAllocate(im, 255, 255, 255); gdImageColorAllocate(im, 0, 0, 0); h[2] = '\0'; h[4] = '\0'; for (i = 0; i < bytes; i++) { while (1) { if ((ch=getc(fd)) == EOF) { fail = 1; break; } if (ch == 'x') { break; } } if (fail) { break; } /* Get hex value */ if ((ch=getc(fd)) == EOF) { break; } h[0] = ch; if ((ch=getc(fd)) == EOF) { break; } h[1] = ch; if (max_bit == 32768) { if ((ch=getc(fd)) == EOF) { break; } h[2] = ch; if ((ch=getc(fd)) == EOF) { break; } h[3] = ch; } if (sscanf(h, "%x", &b) != 1) { gd_error("Invalid XBM"); gdImageDestroy(im); return 0; } for (bit = 1; bit <= max_bit; bit = bit << 1) { gdImageSetPixel(im, x++, y, (b & bit) ? 1 : 0); if (x == im->sx) { x = 0; y++; if (y == im->sy) { return im; } break; } } } gd_error("EOF before image was complete"); gdImageDestroy(im); return 0; } /* }}} */ /* {{{ gdCtxPrintf */ void gdCtxPrintf(gdIOCtx * out, const char *format, ...) { char *buf; int len; va_list args; va_start(args, format); len = vspprintf(&buf, 0, format, args); va_end(args); out->putBuf(out, buf, len); efree(buf); } /* }}} */ /* {{{ gdImageXbmCtx */ void gdImageXbmCtx(gdImagePtr image, char* file_name, int fg, gdIOCtx * out) { int x, y, c, b, sx, sy, p; char *name, *f; size_t i, l; name = file_name; if ((f = strrchr(name, '/')) != NULL) name = f+1; if ((f = strrchr(name, '\\')) != NULL) name = f+1; name = estrdup(name); if ((f = strrchr(name, '.')) != NULL && !strcasecmp(f, ".XBM")) *f = '\0'; if ((l = strlen(name)) == 0) { efree(name); name = estrdup("image"); } else { for (i=0; i<l; i++) { /* only in C-locale isalnum() would work */ if (!isupper(name[i]) && !islower(name[i]) && !isdigit(name[i])) { name[i] = '_'; } } } gdCtxPrintf(out, "#define %s_width %d\n", name, gdImageSX(image)); gdCtxPrintf(out, "#define %s_height %d\n", name, gdImageSY(image)); gdCtxPrintf(out, "static unsigned char %s_bits[] = {\n ", name); efree(name); b = 1; p = 0; c = 0; sx = gdImageSX(image); sy = gdImageSY(image); for (y = 0; y < sy; y++) { for (x = 0; x < sx; x++) { if (gdImageGetPixel(image, x, y) == fg) { c |= b; } if ((b == 128) || (x == sx - 1)) { b = 1; if (p) { gdCtxPrintf(out, ", "); if (!(p%12)) { gdCtxPrintf(out, "\n "); p = 12; } } p++; gdCtxPrintf(out, "0x%02X", c); c = 0; } else { b <<= 1; } } } gdCtxPrintf(out, "};\n"); } /* }}} */
0
0.868902
1
0.868902
game-dev
MEDIA
0.315855
game-dev
0.988846
1
0.988846
PhoenixBladez/SpiritMod
1,089
Items/Placeable/Furniture/Neon/GeneratorItem.cs
using SpiritMod.Tiles.Furniture; using Terraria.ID; using Terraria.ModLoader; using SpiritMod.Items.Placeable.Tiles; using SpiritMod.Tiles.Block; namespace SpiritMod.Items.Placeable.Furniture.Neon { public class GeneratorItem : ModItem { public override void SetStaticDefaults() { DisplayName.SetDefault("Glowplate Generator"); } public override void SetDefaults() { item.width = 36; item.height = 28; item.value = item.value = Terraria.Item.buyPrice(0, 0, 5, 0); item.rare = ItemRarityID.Blue; item.maxStack = 99; item.useStyle = ItemUseStyleID.SwingThrow; item.useTime = 10; item.useAnimation = 15; item.useTurn = true; item.autoReuse = true; item.consumable = true; item.createTile = ModContent.TileType<Generator>(); } public override void AddRecipes() { ModRecipe recipe = new ModRecipe(mod); recipe.AddIngredient(ModContent.ItemType<TechBlockItem>(), 15); recipe.AddTile(TileID.Anvils); recipe.SetResult(this); recipe.AddRecipe(); } } }
0
0.635651
1
0.635651
game-dev
MEDIA
0.997398
game-dev
0.66818
1
0.66818
Aireil/FFLogsViewer
2,714
FFLogsViewer/Service.cs
using Dalamud.Game; using Dalamud.Game.ClientState.Objects; using Dalamud.IoC; using Dalamud.Plugin; using Dalamud.Plugin.Services; using FFLogsViewer.GUI.Config; using FFLogsViewer.GUI.Main; using FFLogsViewer.Manager; #pragma warning disable SA1134 // AttributesMustNotShareLine namespace FFLogsViewer; internal class Service { internal static Configuration Configuration { get; set; } = null!; internal static Commands Commands { get; set; } = null!; internal static ConfigWindow ConfigWindow { get; set; } = null!; internal static MainWindow MainWindow { get; set; } = null!; internal static CharDataManager CharDataManager { get; set; } = null!; internal static GameDataManager GameDataManager { get; set; } = null!; internal static HistoryManager HistoryManager { get; set; } = null!; internal static OpenWithManager OpenWithManager { get; set; } = null!; internal static TeamManager TeamManager { get; set; } = null!; internal static FFLogsClient FFLogsClient { get; set; } = null!; [PluginService] internal static IDalamudPluginInterface Interface { get; private set; } = null!; [PluginService] internal static IChatGui ChatGui { get; private set; } = null!; [PluginService] internal static IClientState ClientState { get; private set; } = null!; [PluginService] internal static ICommandManager CommandManager { get; private set; } = null!; [PluginService] internal static ICondition Condition { get; private set; } = null!; [PluginService] internal static IDataManager DataManager { get; private set; } = null!; [PluginService] internal static IFlyTextGui FlyTextGui { get; private set; } = null!; [PluginService] internal static ISigScanner SigScanner { get; private set; } = null!; [PluginService] internal static ITargetManager TargetManager { get; private set; } = null!; [PluginService] internal static IKeyState KeyState { get; private set; } = null!; [PluginService] internal static IGameGui GameGui { get; private set; } = null!; [PluginService] internal static IPluginLog PluginLog { get; private set; } = null!; [PluginService] internal static IGameInteropProvider GameInteropProvider { get; private set; } = null!; [PluginService] internal static ITextureProvider TextureProvider { get; private set; } = null!; [PluginService] internal static IObjectTable ObjectTable { get; private set; } = null!; [PluginService] internal static IFramework Framework { get; private set; } = null!; [PluginService] internal static INotificationManager NotificationManager { get; private set; } = null!; [PluginService] internal static IContextMenu ContextMenu { get; private set; } = null!; }
0
0.646841
1
0.646841
game-dev
MEDIA
0.723745
game-dev
0.691112
1
0.691112
mauge123/mechanical-blender
5,063
source/gameengine/Ketsji/KX_SCA_ReplaceMeshActuator.cpp
/* * ***** 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 gameengine/Ketsji/KX_SCA_ReplaceMeshActuator.cpp * \ingroup ketsji * * Replace the mesh for this actuator's parent */ // // Previously existed as: // \source\gameengine\GameLogic\SCA_ReplaceMeshActuator.cpp // Please look here for revision history. #include <stddef.h> #include "KX_SCA_ReplaceMeshActuator.h" #include "KX_MeshProxy.h" #include "EXP_PyObjectPlus.h" #ifdef WITH_PYTHON /* ------------------------------------------------------------------------- */ /* Python functions */ /* ------------------------------------------------------------------------- */ /* Integration hooks ------------------------------------------------------- */ PyTypeObject KX_SCA_ReplaceMeshActuator::Type = { PyVarObject_HEAD_INIT(NULL, 0) "KX_SCA_ReplaceMeshActuator", sizeof(PyObjectPlus_Proxy), 0, py_base_dealloc, 0, 0, 0, 0, py_base_repr, 0,0,0,0,0,0,0,0,0, Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, 0,0,0,0,0,0,0, Methods, 0, 0, &SCA_IActuator::Type, 0,0,0,0,0,0, py_base_new }; PyMethodDef KX_SCA_ReplaceMeshActuator::Methods[] = { KX_PYMETHODTABLE(KX_SCA_ReplaceMeshActuator, instantReplaceMesh), {NULL,NULL} //Sentinel }; PyAttributeDef KX_SCA_ReplaceMeshActuator::Attributes[] = { KX_PYATTRIBUTE_RW_FUNCTION("mesh", KX_SCA_ReplaceMeshActuator, pyattr_get_mesh, pyattr_set_mesh), KX_PYATTRIBUTE_BOOL_RW ("useDisplayMesh", KX_SCA_ReplaceMeshActuator, m_use_gfx), KX_PYATTRIBUTE_BOOL_RW ("usePhysicsMesh", KX_SCA_ReplaceMeshActuator, m_use_phys), { NULL } //Sentinel }; PyObject *KX_SCA_ReplaceMeshActuator::pyattr_get_mesh(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef) { KX_SCA_ReplaceMeshActuator* actuator = static_cast<KX_SCA_ReplaceMeshActuator*>(self); if (!actuator->m_mesh) Py_RETURN_NONE; KX_MeshProxy* meshproxy = new KX_MeshProxy(actuator->m_mesh); return meshproxy->NewProxy(true); } int KX_SCA_ReplaceMeshActuator::pyattr_set_mesh(void *self, const struct KX_PYATTRIBUTE_DEF *attrdef, PyObject *value) { KX_SCA_ReplaceMeshActuator* actuator = static_cast<KX_SCA_ReplaceMeshActuator*>(self); RAS_MeshObject* new_mesh; if (!ConvertPythonToMesh(actuator->GetLogicManager(), value, &new_mesh, true, "actuator.mesh = value: KX_SCA_ReplaceMeshActuator")) return PY_SET_ATTR_FAIL; actuator->m_mesh = new_mesh; return PY_SET_ATTR_SUCCESS; } KX_PYMETHODDEF_DOC(KX_SCA_ReplaceMeshActuator, instantReplaceMesh, "instantReplaceMesh() : immediately replace mesh without delay\n") { InstantReplaceMesh(); Py_RETURN_NONE; } #endif // WITH_PYTHON /* ------------------------------------------------------------------------- */ /* Native functions */ /* ------------------------------------------------------------------------- */ KX_SCA_ReplaceMeshActuator::KX_SCA_ReplaceMeshActuator(SCA_IObject *gameobj, class RAS_MeshObject *mesh, SCA_IScene* scene, bool use_gfx, bool use_phys) : SCA_IActuator(gameobj, KX_ACT_REPLACE_MESH), m_mesh(mesh), m_scene(scene), m_use_gfx(use_gfx), m_use_phys(use_phys) { } /* End of constructor */ KX_SCA_ReplaceMeshActuator::~KX_SCA_ReplaceMeshActuator() { // there's nothing to be done here, really.... } /* end of destructor */ bool KX_SCA_ReplaceMeshActuator::Update() { // bool result = false; /*unused*/ bool bNegativeEvent = IsNegativeEvent(); RemoveAllEvents(); if (bNegativeEvent) return false; // do nothing on negative events if (m_mesh || m_use_phys) /* NULL mesh is ok if were updating physics */ m_scene->ReplaceMesh(GetParent(),m_mesh, m_use_gfx, m_use_phys); return false; } CValue* KX_SCA_ReplaceMeshActuator::GetReplica() { KX_SCA_ReplaceMeshActuator* replica = new KX_SCA_ReplaceMeshActuator(*this); if (replica == NULL) return NULL; replica->ProcessReplica(); return replica; }; void KX_SCA_ReplaceMeshActuator::InstantReplaceMesh() { if (m_mesh) m_scene->ReplaceMesh(GetParent(),m_mesh, m_use_gfx, m_use_phys); } /* eof */
0
0.611305
1
0.611305
game-dev
MEDIA
0.645022
game-dev,graphics-rendering
0.649591
1
0.649591
wisp-forest/accessories
3,132
common/src/main/java/io/wispforest/accessories/utils/EndecDataLoader.java
package io.wispforest.accessories.utils; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.mojang.logging.LogUtils; import io.wispforest.endec.Endec; import io.wispforest.endec.SerializationContext; import io.wispforest.endec.format.gson.GsonDeserializer; import io.wispforest.owo.serialization.RegistriesAttribute; import net.minecraft.core.HolderLookup; import net.minecraft.core.RegistryAccess; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.packs.resources.SimpleJsonResourceReloadListener; import net.minecraft.util.profiling.ProfilerFiller; import org.slf4j.Logger; import java.util.Map; import java.util.function.BiConsumer; // TODO: 1.21.4 ADJUSTMENTS SHOULD BE MADE TO USE LESS DIRECT CODE ANYWAYS public abstract class EndecDataLoader<T> extends SimpleJsonResourceReloadListener { private static final Logger LOGGER = LogUtils.getLogger(); protected static final Gson GSON = new GsonBuilder().setLenient().setPrettyPrinting().create(); protected final String type; protected final ResourceLocation id; protected final Endec<T> endec; protected SerializationContext context; protected EndecDataLoader(SerializationContext context, ResourceLocation id, String type, Endec<T> endec) { super(GSON, type); this.type = type; this.id = id; this.context = context; this.endec = endec; } public static <T> EndecDataLoader<T> client(ResourceLocation id, String type, Endec<T> endec, BiConsumer<ResourceLocation, T> handleEntry) { return new EndecDataLoader<T>(SerializationContext.empty(), id, type, endec) { @Override public void handleRawEntry(ResourceLocation identifier, T t) { handleEntry.accept(identifier, t); } }; } public static <T> EndecDataLoader<T> server(HolderLookup.Provider registries, ResourceLocation id, String type, Endec<T> endec, BiConsumer<ResourceLocation, T> handleEntry) { return new EndecDataLoader<T>(SerializationContext.attributes(RegistriesAttribute.of((RegistryAccess) registries)), id, type, endec) { @Override public void handleRawEntry(ResourceLocation identifier, T t) { handleEntry.accept(identifier, t); } }; } protected abstract void handleRawEntry(ResourceLocation identifier, T t); @Override protected void apply(Map<ResourceLocation, JsonElement> loadedObjects, net.minecraft.server.packs.resources.ResourceManager resourceManager, ProfilerFiller profiler) { for (var entry : loadedObjects.entrySet()) { var location = entry.getKey(); try { var t = this.endec.decodeFully(this.context, GsonDeserializer::of, entry.getValue()); this.handleRawEntry(location, t); } catch (Exception e) { LOGGER.error("[EndecDataLoader: {}] An issue has occurred with attempting to decode the following entry: {}", this.getLoaderId(), location, e); } } } public ResourceLocation getLoaderId() { return id; } }
0
0.889818
1
0.889818
game-dev
MEDIA
0.222294
game-dev
0.872566
1
0.872566
iPortalTeam/ImmersivePortalsMod
22,917
src/main/java/qouteall/imm_ptl/core/collision/CollisionHelper.java
package qouteall.imm_ptl.core.collision; import com.google.common.collect.ImmutableList; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.event.lifecycle.v1.ServerTickEvents; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.core.Direction; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceKey; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.entity.Entity; import net.minecraft.world.level.Level; import net.minecraft.world.level.border.WorldBorder; import net.minecraft.world.phys.AABB; import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.shapes.BooleanOp; import net.minecraft.world.phys.shapes.Shapes; import net.minecraft.world.phys.shapes.VoxelShape; import org.jetbrains.annotations.Nullable; import qouteall.imm_ptl.core.CHelper; import qouteall.imm_ptl.core.ClientWorldLoader; import qouteall.imm_ptl.core.IPGlobal; import qouteall.imm_ptl.core.McHelper; import qouteall.imm_ptl.core.ScaleUtils; import qouteall.imm_ptl.core.ducks.IEEntity; import qouteall.imm_ptl.core.miscellaneous.IPVanillaCopy; import qouteall.imm_ptl.core.mixin.common.collision.IEEntity_Collision; import qouteall.imm_ptl.core.portal.Portal; import qouteall.imm_ptl.core.portal.global_portals.GlobalPortalStorage; import qouteall.q_misc_util.Helper; import qouteall.q_misc_util.MiscHelper; import qouteall.q_misc_util.my_util.LimitedLogger; import java.util.List; import java.util.function.BiFunction; import java.util.function.Function; public class CollisionHelper { private static final LimitedLogger limitedLogger = new LimitedLogger(20); /** * cut a box with a plane. * the facing that normal points to will be remained. * return null for empty box. */ public static @Nullable AABB clipBox(AABB box, Vec3 planePos, Vec3 planeNormal) { boolean xForward = planeNormal.x > 0; boolean yForward = planeNormal.y > 0; boolean zForward = planeNormal.z > 0; Vec3 pushedPos = new Vec3( xForward ? box.minX : box.maxX, yForward ? box.minY : box.maxY, zForward ? box.minZ : box.maxZ ); Vec3 staticPos = new Vec3( xForward ? box.maxX : box.minX, yForward ? box.maxY : box.minY, zForward ? box.maxZ : box.minZ ); double tOfPushedPos = Helper.getCollidingT(planePos, planeNormal, pushedPos, planeNormal); boolean isPushedPosInFrontOfPlane = tOfPushedPos < 0; if (isPushedPosInFrontOfPlane) { //the box is not cut by plane return box; } boolean isStaticPosInFrontOfPlane = Helper.isInFrontOfPlane( staticPos, planePos, planeNormal ); if (!isStaticPosInFrontOfPlane) { //the box is fully cut by plane return null; } //the plane cut the box halfly Vec3 afterBeingPushed = pushedPos.add(planeNormal.scale(tOfPushedPos)); return new AABB(afterBeingPushed, staticPos); } public static boolean isBoxFullyBehindPlane(Vec3 planePos, Vec3 planeNormal, AABB box) { boolean xForward = planeNormal.x > 0; boolean yForward = planeNormal.y > 0; boolean zForward = planeNormal.z > 0; Vec3 testingPos = new Vec3( xForward ? box.maxX : box.minX, yForward ? box.maxY : box.minY, zForward ? box.maxZ : box.minZ ); return testingPos.subtract(planePos).dot(planeNormal) < 0; } public static boolean canCollideWithPortal( Entity entity, Portal portal, float partialTick ) { return mayEntityCollideWithPortal( entity, portal, entity.getEyePosition(partialTick), entity.getBoundingBox() ); } public static boolean mayEntityCollideWithPortal( Entity entity, Portal portal, Vec3 entityEyePos, AABB entityBoundingBox ) { if (!portal.canCollideWithEntity(entity)) { return false; } return portal.getPortalShape().canCollideWith( portal, portal.getThisSideState(), entityEyePos, entityBoundingBox ); } public static double absMin(double a, double b) { return Math.abs(a) < Math.abs(b) ? a : b; } // floating point deviation may cause collision issues public static double fixCoordinateFloatingPointError( double attemptedMove, double result ) { //rotation may cause a free move to reduce a little bit and the game think that it's collided if (Math.abs(attemptedMove - result) < 0.001) { return attemptedMove; } //0 may become 0.0000001 after rotation. avoid falling through floor if (Math.abs(result) < 0.0001) { return 0; } return result; } /** * Clips a VoxelShape with a plane. * The things behind the plane (the opposite side of normal) will be clipped. */ @Nullable public static VoxelShape clipVoxelShape(VoxelShape shape, Vec3 clippingPlanePos, Vec3 clippingPlaneNormal) { if (shape.isEmpty()) { return null; } AABB shapeBoundingBox = shape.bounds(); boolean boxBehindPlane = isBoxFullyBehindPlane( clippingPlanePos, clippingPlaneNormal, shapeBoundingBox ); if (boxBehindPlane) { return null; } boolean isFullyInFrontOfPlane = isBoxFullyBehindPlane( clippingPlanePos, clippingPlaneNormal.scale(-1), shapeBoundingBox ); if (isFullyInFrontOfPlane) { return shape; } // the shape is intersecting the clipping plane // clip the shape AABB clippedBoundingBox = clipBox( shapeBoundingBox, clippingPlanePos, clippingPlaneNormal ); if (clippedBoundingBox == null) { return null; } VoxelShape result = Shapes.joinUnoptimized( shape, Shapes.create(clippedBoundingBox), BooleanOp.AND ); return result; } // only for reference private static Vec3 refHandleCollisionWithShapeProcessor(Entity entity, Vec3 attemptedMove, Function<VoxelShape, VoxelShape> filter) { AABB boundingBox = entity.getBoundingBox(); List<VoxelShape> entityCollisions = entity.level().getEntityCollisions(entity, boundingBox.expandTowards(attemptedMove)); // introduce a helper func to reduce argument count BiFunction<Vec3, AABB, Vec3> collisionFunc = (attempt, bb) -> collideBoundingBox(entity, attempt, bb, entity.level(), entityCollisions, filter); // firstly do a normal collision regardless of stepping Vec3 collidedMovement = attemptedMove.lengthSqr() == 0.0D ? attemptedMove : collisionFunc.apply(attemptedMove, boundingBox); boolean collideX = attemptedMove.x != collidedMovement.x; boolean collideY = attemptedMove.y != collidedMovement.y; boolean collideZ = attemptedMove.z != collidedMovement.z; boolean collidesWithFloor = collideY && attemptedMove.y < 0.0D; boolean touchGround = entity.onGround() || collidesWithFloor; boolean collidesHorizontally = collideX || collideZ; float maxUpStep = entity.maxUpStep(); if (maxUpStep > 0.0F && touchGround && collidesHorizontally) { // the entity is touching ground and has horizontal collision now // try to directly move to stepped position, make it approach the stair Vec3 stepping = collisionFunc.apply( new Vec3(attemptedMove.x, (double) maxUpStep, attemptedMove.z), boundingBox ); // try to move up in step height with expanded box Vec3 verticalStep = collisionFunc.apply( new Vec3(0.0D, (double) maxUpStep, 0.0D), boundingBox.expandTowards(attemptedMove.x, 0.0D, attemptedMove.z) ); if (verticalStep.y < (double) maxUpStep) { // try to move horizontally after moving up Vec3 horizontalMoveAfterVerticalStepping = collisionFunc.apply( new Vec3(attemptedMove.x, 0.0D, attemptedMove.z), boundingBox.move(verticalStep) ).add(verticalStep); // if it's further than directly stepping, use that as the stepped movement if (horizontalMoveAfterVerticalStepping.horizontalDistanceSqr() > stepping.horizontalDistanceSqr()) { stepping = horizontalMoveAfterVerticalStepping; } } if (stepping.horizontalDistanceSqr() > collidedMovement.horizontalDistanceSqr()) { // in the stepped position, move down (because the max step height may be higher than slab height) Vec3 movingDown = collisionFunc.apply( new Vec3(0.0D, -stepping.y + attemptedMove.y, 0.0D), boundingBox.move(stepping) ); return stepping.add(movingDown); } } return collidedMovement; } /** * Vanilla copy {@link Entity#collide(Vec3)} * But filters collisions behind the clipping plane and handles stepping with rotated gravity. */ @SuppressWarnings("JavadocReference") @IPVanillaCopy public static Vec3 handleCollisionWithShapeProcessor( Entity entity, AABB boundingBox, Level world, Vec3 attemptedMove, Function<VoxelShape, VoxelShape> filter, Direction gravity, double steppingScale ) { Direction jumpDirection = gravity.getOpposite(); Direction.Axis gravityAxis = gravity.getAxis(); List<VoxelShape> entityCollisions = world.getEntityCollisions(entity, boundingBox.expandTowards(attemptedMove)); // introduce a helper func to reduce argument count BiFunction<Vec3, AABB, Vec3> collisionFunc = (attempt, bb) -> collideBoundingBox(entity, attempt, bb, world, entityCollisions, filter); // firstly do a normal collision regardless of stepping Vec3 collidedMovement = attemptedMove.lengthSqr() == 0.0D ? attemptedMove : collisionFunc.apply(attemptedMove, boundingBox); Vec3 collisionDelta = attemptedMove.subtract(collidedMovement); boolean collidesOnGravityAxis = Helper.getCoordinate(collisionDelta, gravityAxis) != 0; boolean attemptToMoveAlongGravity = Helper.getSignedCoordinate(attemptedMove, gravity) > 0; boolean collidesWithFloor = collidesOnGravityAxis && attemptToMoveAlongGravity; boolean touchGround = entity.onGround() || collidesWithFloor; boolean collidesHorizontally = movesOnNonGravityAxis(collisionDelta, gravityAxis); double maxUpStep = entity.maxUpStep(); if (steppingScale > 1) { maxUpStep *= steppingScale; } if (maxUpStep > 0.0F && touchGround && collidesHorizontally) { // the entity is touching ground and has horizontal collision now // try to directly move to stepped position, make it approach the stair Vec3 stepping = collisionFunc.apply( Helper.putSignedCoordinate(attemptedMove, jumpDirection, maxUpStep), boundingBox ); // try to move up in step height with expanded box Vec3 expandVec = Helper.putSignedCoordinate(attemptedMove, gravity, 0); Vec3 verticalStep = collisionFunc.apply( Helper.putSignedCoordinate(Vec3.ZERO, jumpDirection, maxUpStep), boundingBox.expandTowards(expandVec) ); // add 0.001 because of floating point error if (Helper.getSignedCoordinate(verticalStep, jumpDirection) < (double) maxUpStep + 0.001) { // try to move horizontally after moving up Vec3 horizontalMoveAfterVerticalStepping = collisionFunc.apply( expandVec, boundingBox.move(verticalStep) ).add(verticalStep); // if it's further than directly stepping, use that as the stepped movement if (Helper.getDistanceSqrOnAxisPlane(horizontalMoveAfterVerticalStepping, gravityAxis) > Helper.getDistanceSqrOnAxisPlane(stepping, gravityAxis) ) { stepping = horizontalMoveAfterVerticalStepping; } } if (Helper.getDistanceSqrOnAxisPlane(stepping, gravityAxis) > Helper.getDistanceSqrOnAxisPlane(collidedMovement, gravityAxis) ) { double steppingVerticalLen = Helper.getSignedCoordinate(stepping, jumpDirection); double attemptMoveVerticalLen = Helper.getSignedCoordinate(attemptedMove, jumpDirection); // in the stepped position, move down (because the max step height may be higher than slab height) Vec3 movingDown = collisionFunc.apply( Helper.putSignedCoordinate( Vec3.ZERO, jumpDirection, -steppingVerticalLen + attemptMoveVerticalLen ), boundingBox.move(stepping) ); return stepping.add(movingDown); } } return collidedMovement; } public static boolean movesOnNonGravityAxis(Vec3 vec, Direction.Axis gravityAxis) { return switch (gravityAxis) { case X -> vec.y != 0 || vec.z != 0; case Y -> vec.x != 0 || vec.z != 0; case Z -> vec.x != 0 || vec.y != 0; }; } /** * Vanilla copy {@link Entity#collideBoundingBox(Entity, Vec3, AABB, Level, List)} * But filters collisions behind the clipping plane */ @IPVanillaCopy public static Vec3 collideBoundingBox( Entity entity, Vec3 vec, AABB collisionBox, Level level, List<VoxelShape> potentialHits, Function<VoxelShape, VoxelShape> shapeProcessor ) { ImmutableList.Builder<VoxelShape> builder = ImmutableList.builderWithExpectedSize(potentialHits.size() + 1); for (VoxelShape potentialHit : potentialHits) { VoxelShape processed = shapeProcessor.apply(potentialHit); if (processed != null) { builder.add(processed); } } WorldBorder worldBorder = level.getWorldBorder(); Vec3 boundingBoxCenter = collisionBox.getCenter(); boolean addWorldBorderCollision = worldBorder.isWithinBounds(boundingBoxCenter.x, boundingBoxCenter.z) && worldBorder.getDistanceToBorder(boundingBoxCenter.x, boundingBoxCenter.z) < 32; if (addWorldBorderCollision) { builder.add(worldBorder.getCollisionShape()); } // the entity is only used for collision context. the context does not use entity position Iterable<VoxelShape> blockCollisions = level.getBlockCollisions(entity, collisionBox.expandTowards(vec)); for (VoxelShape blockCollision : blockCollisions) { VoxelShape processed = shapeProcessor.apply(blockCollision); if (processed != null) { builder.add(processed); } } return IEEntity_Collision.ip_CollideWithShapes(vec, collisionBox, builder.build()); } public static AABB transformBox(Portal portal, AABB originalBox) { if (portal.getRotation() == null && portal.getScale() == 1) { return originalBox.move(portal.getDestPos().subtract(portal.getOriginPos())); } else { return Helper.transformBox(originalBox, portal::transformPoint); } } @Deprecated public static Level getWorld(boolean isClient, ResourceKey<Level> dimension) { if (isClient) { return CHelper.getClientWorld(dimension); } else { return MiscHelper.getServer().getLevel(dimension); } } public static boolean isCollidingWithAnyPortal(Entity entity) { return ((IEEntity) entity).ip_getCollidingPortal() != null; } public static void updateCollidingPortalForWorld(Level world, float partialTick) { world.getProfiler().push("update_colliding_portal"); List<Portal> globalPortals = GlobalPortalStorage.getGlobalPortals(world); Iterable<Entity> worldEntityList = McHelper.getWorldEntityList(world); for (Entity entity : worldEntityList) { if (entity instanceof Portal portal) { // the colliding portal update must happen after all entities finishes ticking, // because the entity moves during ticking. CollisionHelper.notifyCollidingPortals(portal, partialTick); } else { AABB entityBoundingBoxStretched = getStretchedBoundingBox(entity); for (Portal globalPortal : globalPortals) { AABB globalPortalBoundingBox = globalPortal.getBoundingBox(); if (entityBoundingBoxStretched.intersects(globalPortalBoundingBox)) { if (canCollideWithPortal(entity, globalPortal, partialTick)) { ((IEEntity) entity).ip_notifyCollidingWithPortal(globalPortal); } } } } } world.getProfiler().pop(); } public static void init() { ServerTickEvents.END_SERVER_TICK.register((server) -> { for (ServerLevel world : server.getAllLevels()) { updateCollidingPortalForWorld(world, 0); } }); } @Environment(EnvType.CLIENT) public static void initClient() { IPGlobal.POST_CLIENT_TICK_EVENT.register(CollisionHelper::tickClient); } @Environment(EnvType.CLIENT) public static void tickClient() { updateClientCollidingStatus(); updateClientStagnateStatus(); } @Environment(EnvType.CLIENT) private static void updateClientCollidingStatus() { if (ClientWorldLoader.getIsInitialized()) { for (ClientLevel world : ClientWorldLoader.getClientWorlds()) { updateCollidingPortalForWorld(world, 0); } } } /** * Note that there are 3 kinds of portals in the aspect of collision: * 1. non-teleportable portal, doesn't affect collision * 2. teleportable but non-hasCrossPortalCollision, only affect this-side collision * 3. teleportable and hasCrossPortalCollision */ public static void notifyCollidingPortals(Portal portal, float partialTick) { if (!portal.isTeleportable()) { return; } AABB portalBoundingBox = portal.getBoundingBox(); McHelper.foreachEntitiesByBoxApproximateRegions( Entity.class, portal.level(), portalBoundingBox, 8, entity -> { if (entity instanceof Portal) { return; } AABB entityBoxStretched = getStretchedBoundingBox(entity); if (!entityBoxStretched.intersects(portalBoundingBox)) { return; } boolean canCollideWithPortal = canCollideWithPortal(entity, portal, partialTick); // use partial tick zero to get the colliding portal before this tick if (!canCollideWithPortal) { return; } ((IEEntity) entity).ip_notifyCollidingWithPortal(portal); } ); } public static AABB getStretchedBoundingBox(Entity entity) { // normal colliding portal update lags 1 tick before collision calculation // the velocity updates later after updating colliding portal // expand the velocity to avoid not collide with portal in time Vec3 backwardExpand = McHelper.lastTickPosOf(entity).subtract(entity.position()); Vec3 forwardExpand = McHelper.getWorldVelocity(entity); AABB box = entity.getBoundingBox() .expandTowards(forwardExpand.scale(1.2)) .expandTowards(backwardExpand); // when the scale is big, the entity could move quickly abruptly double scale = ScaleUtils.getScale(entity); if (scale > 4) { box = box.inflate(scale); } return box; } private static boolean thisTickStagnate = false; private static boolean lastTickStagnate = false; @Environment(EnvType.CLIENT) public static void informClientStagnant() { thisTickStagnate = true; limitedLogger.log("client movement stagnated"); } @Environment(EnvType.CLIENT) private static void updateClientStagnateStatus() { if (thisTickStagnate && lastTickStagnate) { Minecraft.getInstance().gui.setOverlayMessage( Component.translatable("imm_ptl.stagnate_movement"), false ); } else if (!thisTickStagnate && lastTickStagnate) { Minecraft.getInstance().gui.setOverlayMessage( Component.literal(""), false ); } lastTickStagnate = thisTickStagnate; thisTickStagnate = false; } @Nullable public static AABB getTotalBlockCollisionBox(Entity entity, AABB box, Function<VoxelShape, VoxelShape> shapeFilter) { Iterable<VoxelShape> collisions = entity.level().getBlockCollisions(entity, box); AABB collisionUnion = null; for (VoxelShape c : collisions) { VoxelShape currCollision = shapeFilter.apply(c); if (currCollision != null && !currCollision.isEmpty()) { AABB collisionBoundingBox = currCollision.bounds(); if (collisionUnion == null) { collisionUnion = collisionBoundingBox; } else { collisionUnion = collisionUnion.minmax(collisionBoundingBox); } } } return collisionUnion; } }
0
0.838786
1
0.838786
game-dev
MEDIA
0.453799
game-dev,graphics-rendering
0.979263
1
0.979263
Monochrome-Inc/ZombiePanic-HL
2,998
src/game/server/spectator.cpp
/*** * * Copyright (c) 1996-2001, Valve LLC. All rights reserved. * * This product contains software technology licensed from Id * Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. * All Rights Reserved. * * Use, distribution, and modification of this source code and/or resulting * object code is restricted to non-commercial enhancements to products from * Valve LLC. All other use, distribution, or modification is prohibited * without written permission from Valve LLC. * ****/ // CBaseSpectator // YWB: UNDONE // Spectator functions // #include "extdll.h" #include "util.h" #include "cbase.h" #include "monsters.h" #include "spectator.h" /* =========== SpectatorConnect called when a spectator connects to a server ============ */ void CBaseSpectator::SpectatorConnect(void) { pev->flags = FL_SPECTATOR; pev->solid = SOLID_NOT; pev->movetype = MOVETYPE_NOCLIP; m_pGoalEnt = NULL; } /* =========== SpectatorDisconnect called when a spectator disconnects from a server ============ */ void CBaseSpectator::SpectatorDisconnect(void) { } /* ================ SpectatorImpulseCommand Called by SpectatorThink if the spectator entered an impulse ================ */ void CBaseSpectator::SpectatorImpulseCommand(void) { static edict_t *pGoal = NULL; edict_t *pPreviousGoal; edict_t *pCurrentGoal; BOOL bFound; switch (pev->impulse) { case 1: // teleport the spectator to the next spawn point // note that if the spectator is tracking, this doesn't do // much pPreviousGoal = pGoal; pCurrentGoal = pGoal; // Start at the current goal, skip the world, and stop if we looped // back around bFound = FALSE; while (1) { pCurrentGoal = FIND_ENTITY_BY_CLASSNAME(pCurrentGoal, "info_player_observer"); // Looped around, failure if (pCurrentGoal == pPreviousGoal) { ALERT(at_console, "Could not find a spawn spot.\n"); break; } // Found a non-world entity, set success, otherwise, look for the next one. if (!FNullEnt(pCurrentGoal)) { bFound = TRUE; break; } } if (!bFound) // Didn't find a good spot. break; pGoal = pCurrentGoal; UTIL_SetOrigin(pev, pGoal->v.origin); pev->angles = pGoal->v.angles; pev->fixangle = FALSE; break; default: ALERT(at_console, "Unknown spectator impulse\n"); break; } pev->impulse = 0; } /* ================ SpectatorThink Called every frame after physics are run ================ */ void CBaseSpectator::SpectatorThink(void) { if (!(pev->flags & FL_SPECTATOR)) { pev->flags = FL_SPECTATOR; } pev->solid = SOLID_NOT; pev->movetype = MOVETYPE_NOCLIP; if (pev->impulse) SpectatorImpulseCommand(); } /* =========== Spawn Called when spectator is initialized: UNDONE: Is this actually being called because spectators are not allocated in normal fashion? ============ */ void CBaseSpectator::Spawn() { pev->flags = FL_SPECTATOR; pev->solid = SOLID_NOT; pev->movetype = MOVETYPE_NOCLIP; m_pGoalEnt = NULL; }
0
0.962755
1
0.962755
game-dev
MEDIA
0.888251
game-dev,networking
0.842769
1
0.842769
kettingpowered/Ketting-1-20-x
2,722
patches/minecraft/net/minecraft/core/dispenser/AbstractProjectileDispenseBehavior.java.patch
--- a/net/minecraft/core/dispenser/AbstractProjectileDispenseBehavior.java +++ b/net/minecraft/core/dispenser/AbstractProjectileDispenseBehavior.java @@ -14,9 +_,39 @@ Position position = DispenserBlock.getDispensePosition(p_123366_); Direction direction = p_123366_.getBlockState().getValue(DispenserBlock.FACING); Projectile projectile = this.getProjectile(level, position, p_123367_); - projectile.shoot((double)direction.getStepX(), (double)((float)direction.getStepY() + 0.1F), (double)direction.getStepZ(), this.getPower(), this.getUncertainty()); + + // CraftBukkit start + // projectile.shoot((double)direction.getStepX(), (double)((float)direction.getStepY() + 0.1F), (double)direction.getStepZ(), this.getPower(), this.getUncertainty()); + ItemStack itemstack1 = p_123367_.split(1); + org.bukkit.block.Block block = org.bukkit.craftbukkit.v1_20_R1.block.CraftBlock.at(level, p_123366_.getPos()); + org.bukkit.craftbukkit.v1_20_R1.inventory.CraftItemStack craftItem = org.bukkit.craftbukkit.v1_20_R1.inventory.CraftItemStack.asCraftMirror(itemstack1); + + org.bukkit.event.block.BlockDispenseEvent event = new org.bukkit.event.block.BlockDispenseEvent(block, craftItem.clone(), new org.bukkit.util.Vector((double) direction.getStepX(), (double) ((float) direction.getStepY() + 0.1F), (double) direction.getStepZ())); + if (!DispenserBlock.eventFired) { + level.getCraftServer().getPluginManager().callEvent(event); + } + + if (event.isCancelled()) { + p_123367_.grow(1); + return p_123367_; + } + + if (!event.getItem().equals(craftItem)) { + p_123367_.grow(1); + // Chain to handler for new item + ItemStack eventStack = org.bukkit.craftbukkit.v1_20_R1.inventory.CraftItemStack.asNMSCopy(event.getItem()); + DispenseItemBehavior idispensebehavior = (DispenseItemBehavior) DispenserBlock.DISPENSER_REGISTRY.get(eventStack.getItem()); + if (idispensebehavior != DispenseItemBehavior.NOOP && idispensebehavior != this) { + idispensebehavior.dispense(p_123366_, eventStack); + return p_123367_; + } + } + + projectile.shoot(event.getVelocity().getX(), event.getVelocity().getY(), event.getVelocity().getZ(), this.getPower(), this.getUncertainty()); + ((net.minecraft.world.entity.Entity) projectile).projectileSource = new org.bukkit.craftbukkit.v1_20_R1.projectiles.CraftBlockProjectileSource(p_123366_.getEntity()); + // CraftBukkit end level.addFreshEntity(projectile); - p_123367_.shrink(1); + // p_123367_.shrink(1); // CraftBukkit - Handled during event processing return p_123367_; }
0
0.934549
1
0.934549
game-dev
MEDIA
0.986079
game-dev
0.97369
1
0.97369
MegaMek/megamek
4,496
megamek/src/megamek/common/units/UnitType.java
/* * Copyright (C) 2005 Ben Mazur (bmazur@sev.org) * Copyright (C) 2005-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.units; import megamek.common.Messages; /** * weight class limits and names */ public class UnitType { public static final int MEK = 0; public static final int TANK = 1; public static final int BATTLE_ARMOR = 2; public static final int INFANTRY = 3; public static final int PROTOMEK = 4; public static final int VTOL = 5; public static final int NAVAL = 6; public static final int GUN_EMPLACEMENT = 7; public static final int CONV_FIGHTER = 8; public static final int AEROSPACE_FIGHTER = 9; public static final int SMALL_CRAFT = 10; public static final int DROPSHIP = 11; public static final int JUMPSHIP = 12; public static final int WARSHIP = 13; public static final int SPACE_STATION = 14; public static final int HANDHELD_WEAPON = 15; // IMPORTANT: AERO must be the last unit type for advanced search to work, // unless you are adding a new unit type which like Aero should be excluded from search. // In that case add an exception for it in the definition of unitTypeModel in AbstractUnitSelectorDialog.java public static final int AERO = 16; // Non-differentiated Aerospace, like Escape Pods / Lifeboats private static final String[] names = { "Mek", "Tank", "BattleArmor", "Infantry", "ProtoMek", "VTOL", "Naval", "Gun Emplacement", "Conventional Fighter", "AeroSpaceFighter", "Small Craft", "Dropship", "Jumpship", "Warship", "Space Station", "Handheld Weapon", "Aero" }; public static final int SIZE = names.length; /** * Reverse lookup for type integer constant from name * * @param name Unit type name * * @return The unit type constant. If no match can be found, returns -1. */ public static int determineUnitTypeCode(String name) { for (int i = 0; i < names.length; i++) { if (names[i].equals(name)) { return i; } } return -1; } public static String getTypeName(int type) { if ((type >= 0) && (type < SIZE)) { return names[type]; } throw new IllegalArgumentException("Unknown unit type"); } public static String getTypeDisplayableName(int type) { if ((type >= 0) && (type < SIZE)) { return Messages.getString("UnitType." + names[type]); } throw new IllegalArgumentException("Unknown unit type"); } // series of convenience methods to shorten unit type determination /** * Whether the given entity is a VTOL * * @param e the entity to examine * * @return True or false */ public static boolean isVTOL(Entity e) { return e.getEntityType() == Entity.ETYPE_VTOL; } /** * Whether the given entity is a Spheroid dropship * * @param e the entity to examine * * @return True or false */ public static boolean isSpheroidDropship(Entity e) { return e.isAero() && ((IAero) e).isSpheroid(); } }
0
0.679013
1
0.679013
game-dev
MEDIA
0.951101
game-dev
0.70596
1
0.70596
Milk-Drinker01/Milk_Instancer01
3,143
Assets/Milk_Instancer01/Demo/Character.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Character : MonoBehaviour { public float walkingSpeed = 3; public float runningMultiplier = 1.65f; public float acceleration = 5; Transform PlayerCamera; float yRot; CharacterController cc; private void Awake() { PlayerCamera = transform.GetChild(0); cc = GetComponent<CharacterController>(); ToggleCursor(false); } void ToggleCursor(bool enabled) { if (enabled) { Cursor.lockState = CursorLockMode.Confined; Cursor.visible = true; } else { Cursor.lockState = CursorLockMode.Locked; Cursor.visible = false; } } void Update() { if (Input.GetKeyDown(KeyCode.Escape)) ToggleCursor(Cursor.lockState == CursorLockMode.Locked); if (Cursor.lockState == CursorLockMode.Locked) { transform.Rotate(0, Input.GetAxis("Mouse X"), 0); yRot -= Input.GetAxis("Mouse Y"); yRot = Mathf.Clamp(yRot, -80, 80); PlayerCamera.localEulerAngles = new Vector3(yRot, 0, 0); SetInput(); } move(); } Vector2 inputDirection = Vector2.zero; Vector2 velocityXZ = Vector2.zero; Vector3 velocity = Vector3.zero; float speedTarget; public void SetInput() { bool[] inputs = new bool[] { Input.GetKey(KeyCode.W), Input.GetKey(KeyCode.A), Input.GetKey(KeyCode.S), Input.GetKey(KeyCode.D), Input.GetKey(KeyCode.LeftShift) }; speedTarget = 0; inputDirection = Vector2.zero; if (inputs[0]) { inputDirection.y += 1; speedTarget = walkingSpeed; } if (inputs[1]) { inputDirection.x -= 1; speedTarget = walkingSpeed; } if (inputs[2]) { inputDirection.y -= 1; speedTarget = walkingSpeed; } if (inputs[3]) { inputDirection.x += 1; speedTarget = walkingSpeed; } if (inputs[4]) { speedTarget *= runningMultiplier; } } void move() { if (cc.isGrounded) { velocity.y = 0; } Vector2 forward = new Vector2(transform.forward.x, transform.forward.z); Vector2 right = new Vector2(transform.right.x, transform.right.z); Vector2 inputDir = Vector3.Normalize(right * inputDirection.x + forward * inputDirection.y); velocityXZ = Vector2.MoveTowards(velocityXZ, inputDir.normalized * speedTarget, Time.deltaTime * acceleration); //velocityXZ = Vector2.ClampMagnitude(velocityXZ, speedTarget); velocity.x = velocityXZ.x * Time.deltaTime; velocity.z = velocityXZ.y * Time.deltaTime; velocity.y += -9.81f * Time.deltaTime * Time.deltaTime; cc.enabled = true; cc.Move(velocity); cc.enabled = false; } }
0
0.794758
1
0.794758
game-dev
MEDIA
0.799323
game-dev
0.976105
1
0.976105
daydayasobi/TowerDefense-TEngine-Demo
1,872
Assets/TEngine/Runtime/Module/LocalizationModule/Core/Targets/LocalizeTarget_UnityStandard_SpriteRenderer.cs
using UnityEditor; using UnityEngine; #pragma warning disable 618 namespace TEngine.Localization { #if UNITY_EDITOR [InitializeOnLoad] #endif public class LocalizeTarget_UnityStandard_SpriteRenderer : LocalizeTarget<SpriteRenderer> { static LocalizeTarget_UnityStandard_SpriteRenderer() { AutoRegister(); } [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)] static void AutoRegister() { LocalizationManager.RegisterTarget(new LocalizeTargetDesc_Type<SpriteRenderer, LocalizeTarget_UnityStandard_SpriteRenderer> { Name = "SpriteRenderer", Priority = 100 }); } public override eTermType GetPrimaryTermType(Localize cmp) { return eTermType.Sprite; } public override eTermType GetSecondaryTermType(Localize cmp) { return eTermType.Text; } public override bool CanUseSecondaryTerm() { return false; } public override bool AllowMainTermToBeRTL() { return false; } public override bool AllowSecondTermToBeRTL() { return false; } public override void GetFinalTerms ( Localize cmp, string Main, string Secondary, out string primaryTerm, out string secondaryTerm) { Sprite sprite = mTarget.sprite; primaryTerm = sprite != null ? sprite.name : string.Empty; secondaryTerm = null; } public override void DoLocalize(Localize cmp, string mainTranslation, string secondaryTranslation) { Sprite Old = mTarget.sprite; if (Old == null || Old.name != mainTranslation) mTarget.sprite = cmp.FindTranslatedObject<Sprite>(mainTranslation); // If the old value is not in the translatedObjects, then unload it as it most likely was loaded from Resources //if (!HasTranslatedObject(Old)) // Resources.UnloadAsset(Old); } } }
0
0.767172
1
0.767172
game-dev
MEDIA
0.982711
game-dev
0.872092
1
0.872092
Fluorohydride/ygopro-scripts
3,745
c2819435.lua
--幻煌の都 パシフィス function c2819435.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) c:RegisterEffect(e1) --to hand local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(2819435,0)) e2:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH) e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F) e2:SetProperty(EFFECT_FLAG_DELAY) e2:SetCode(EVENT_SUMMON_SUCCESS) e2:SetCountLimit(1,EFFECT_COUNT_CODE_SINGLE) e2:SetRange(LOCATION_FZONE) e2:SetCondition(c2819435.thcon) e2:SetCost(c2819435.cost) e2:SetTarget(c2819435.thtg) e2:SetOperation(c2819435.thop) c:RegisterEffect(e2) local e3=e2:Clone() e3:SetCode(EVENT_SPSUMMON_SUCCESS) c:RegisterEffect(e3) --token local e6=Effect.CreateEffect(c) e6:SetDescription(aux.Stringid(2819435,1)) e6:SetCategory(CATEGORY_SPECIAL_SUMMON+CATEGORY_TOKEN) e6:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O) e6:SetProperty(EFFECT_FLAG_DELAY+EFFECT_FLAG_ACTIVATE_CONDITION) e6:SetCode(EVENT_CHAINING) e6:SetRange(LOCATION_FZONE) e6:SetCountLimit(1,EFFECT_COUNT_CODE_CHAIN) e6:SetCondition(c2819435.spcon) e6:SetCost(c2819435.cost) e6:SetTarget(c2819435.sptg) e6:SetOperation(c2819435.spop) c:RegisterEffect(e6) -- Duel.AddCustomActivityCounter(2819435,ACTIVITY_SUMMON,c2819435.counterfilter) Duel.AddCustomActivityCounter(2819435,ACTIVITY_SPSUMMON,c2819435.counterfilter) end function c2819435.counterfilter(c) return not c:IsType(TYPE_EFFECT) end function c2819435.cost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetCustomActivityCount(2819435,tp,ACTIVITY_SUMMON)==0 and Duel.GetCustomActivityCount(2819435,tp,ACTIVITY_SPSUMMON)==0 end local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_FIELD) e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET+EFFECT_FLAG_OATH) e1:SetCode(EFFECT_CANNOT_SUMMON) e1:SetReset(RESET_PHASE+PHASE_END) e1:SetTargetRange(1,0) e1:SetTarget(c2819435.splimit) Duel.RegisterEffect(e1,tp) local e2=e1:Clone() e2:SetCode(EFFECT_CANNOT_SPECIAL_SUMMON) Duel.RegisterEffect(e2,tp) end function c2819435.splimit(e,c,sump,sumtype,sumpos,targetp,se) return c:IsType(TYPE_EFFECT) end function c2819435.thcon(e,tp,eg,ep,ev,re,r,rp) local tc=eg:GetFirst() return eg:GetCount()==1 and tc:IsSummonPlayer(tp) and tc:IsFaceup() and tc:IsType(TYPE_NORMAL) end function c2819435.thfilter(c) return c:IsSetCard(0xfa) and c:IsAbleToHand() end function c2819435.thtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK) Duel.Hint(HINT_OPSELECTED,1-tp,e:GetDescription()) end function c2819435.thop(e,tp,eg,ep,ev,re,r,rp) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND) local g=Duel.SelectMatchingCard(tp,c2819435.thfilter,tp,LOCATION_DECK,0,1,1,nil) if g:GetCount()>0 then Duel.SendtoHand(g,nil,REASON_EFFECT) Duel.ConfirmCards(1-tp,g) end end function c2819435.spcon(e,tp,eg,ep,ev,re,r,rp) return rp==1-tp and not aux.tkfcon(e,tp) end function c2819435.sptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsPlayerCanSpecialSummonMonster(tp,2819436,0xfa,TYPES_TOKEN_MONSTER,2000,2000,6,RACE_WYRM,ATTRIBUTE_WATER) end Duel.SetOperationInfo(0,CATEGORY_TOKEN,nil,1,0,0) Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,0,0) Duel.Hint(HINT_OPSELECTED,1-tp,e:GetDescription()) end function c2819435.spop(e,tp,eg,ep,ev,re,r,rp) if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end if not Duel.IsPlayerCanSpecialSummonMonster(tp,2819436,0xfa,TYPES_TOKEN_MONSTER,2000,2000,6,RACE_WYRM,ATTRIBUTE_WATER) then return end local token=Duel.CreateToken(tp,2819436) Duel.SpecialSummon(token,0,tp,tp,false,false,POS_FACEUP) end
0
0.876672
1
0.876672
game-dev
MEDIA
0.988267
game-dev
0.933931
1
0.933931
Eaglercraft-Archive/EaglercraftX-1.8-workspace
5,577
src/game/java/net/minecraft/entity/projectile/EntityPotion.java
package net.minecraft.entity.projectile; import java.util.List; import net.minecraft.entity.EntityLivingBase; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.potion.Potion; import net.minecraft.potion.PotionEffect; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.BlockPos; import net.minecraft.util.MovingObjectPosition; import net.minecraft.world.World; /**+ * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. * * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * * EaglercraftX 1.8 patch files (c) 2022-2025 lax1dude, ayunami2000. All Rights Reserved. * * 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 HOLDER 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. * */ public class EntityPotion extends EntityThrowable { private ItemStack potionDamage; public EntityPotion(World worldIn) { super(worldIn); } public EntityPotion(World worldIn, EntityLivingBase throwerIn, int meta) { this(worldIn, throwerIn, new ItemStack(Items.potionitem, 1, meta)); } public EntityPotion(World worldIn, EntityLivingBase throwerIn, ItemStack potionDamageIn) { super(worldIn, throwerIn); this.potionDamage = potionDamageIn; } public EntityPotion(World worldIn, double x, double y, double z, int parInt1) { this(worldIn, x, y, z, new ItemStack(Items.potionitem, 1, parInt1)); } public EntityPotion(World worldIn, double x, double y, double z, ItemStack potionDamageIn) { super(worldIn, x, y, z); this.potionDamage = potionDamageIn; } /**+ * Gets the amount of gravity to apply to the thrown entity with * each tick. */ protected float getGravityVelocity() { return 0.05F; } protected float getVelocity() { return 0.5F; } protected float getInaccuracy() { return -20.0F; } /**+ * Sets the PotionEffect by the given id of the potion effect. */ public void setPotionDamage(int potionId) { if (this.potionDamage == null) { this.potionDamage = new ItemStack(Items.potionitem, 1, 0); } this.potionDamage.setItemDamage(potionId); } /**+ * Returns the damage value of the thrown potion that this * EntityPotion represents. */ public int getPotionDamage() { if (this.potionDamage == null) { this.potionDamage = new ItemStack(Items.potionitem, 1, 0); } return this.potionDamage.getMetadata(); } /**+ * Called when this EntityThrowable hits a block or entity. */ protected void onImpact(MovingObjectPosition movingobjectposition) { if (!this.worldObj.isRemote) { List list = Items.potionitem.getEffects(this.potionDamage); if (list != null && !list.isEmpty()) { AxisAlignedBB axisalignedbb = this.getEntityBoundingBox().expand(4.0D, 2.0D, 4.0D); List list1 = this.worldObj.getEntitiesWithinAABB(EntityLivingBase.class, axisalignedbb); if (!list1.isEmpty()) { for (int k = 0, l = list1.size(); k < l; ++k) { EntityLivingBase entitylivingbase = (EntityLivingBase) list1.get(k); double d0 = this.getDistanceSqToEntity(entitylivingbase); if (d0 < 16.0D) { double d1 = 1.0D - Math.sqrt(d0) / 4.0D; if (entitylivingbase == movingobjectposition.entityHit) { d1 = 1.0D; } for (int m = 0, n = list.size(); m < n; ++m) { PotionEffect potioneffect = (PotionEffect) list.get(m); int i = potioneffect.getPotionID(); if (Potion.potionTypes[i].isInstant()) { Potion.potionTypes[i].affectEntity(this, this.getThrower(), entitylivingbase, potioneffect.getAmplifier(), d1); } else { int j = (int) (d1 * (double) potioneffect.getDuration() + 0.5D); if (j > 20) { entitylivingbase .addPotionEffect(new PotionEffect(i, j, potioneffect.getAmplifier())); } } } } } } } this.worldObj.playAuxSFX(2002, new BlockPos(this), this.getPotionDamage()); this.setDead(); } } /**+ * (abstract) Protected helper method to read subclass entity * data from NBT. */ public void readEntityFromNBT(NBTTagCompound nbttagcompound) { super.readEntityFromNBT(nbttagcompound); if (nbttagcompound.hasKey("Potion", 10)) { this.potionDamage = ItemStack.loadItemStackFromNBT(nbttagcompound.getCompoundTag("Potion")); } else { this.setPotionDamage(nbttagcompound.getInteger("potionValue")); } if (this.potionDamage == null) { this.setDead(); } } /**+ * (abstract) Protected helper method to write subclass entity * data to NBT. */ public void writeEntityToNBT(NBTTagCompound nbttagcompound) { super.writeEntityToNBT(nbttagcompound); if (this.potionDamage != null) { nbttagcompound.setTag("Potion", this.potionDamage.writeToNBT(new NBTTagCompound())); } } }
0
0.805932
1
0.805932
game-dev
MEDIA
0.994769
game-dev
0.95028
1
0.95028
AionGermany/aion-germany
2,126
AL-Game-5.8/data/scripts/system/handlers/ai/siege/DredgionCommanderAI2.java
/** * This file is part of Aion-Lightning <aion-lightning.org>. * * Aion-Lightning 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. * * Aion-Lightning 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 Aion-Lightning. * If not, see <http://www.gnu.org/licenses/>. */ package ai.siege; import com.aionemu.gameserver.ai2.AI2Actions; import com.aionemu.gameserver.ai2.AIName; import com.aionemu.gameserver.model.Race; import com.aionemu.gameserver.model.gameobjects.Npc; import com.aionemu.gameserver.utils.ThreadPoolManager; /** * @author Luzien */ @AIName("dredgionCommander") public class DredgionCommanderAI2 extends SiegeNpcAI2 { @Override protected void handleSpawned() { super.handleSpawned(); scheduleOneShot(); } private int getSkill() { switch (getNpcId()) { case 258236: return 18428; case 272291: case 272292: case 272293: case 272294: case 272295: return 21312; case 276649: case 276650: case 276651: return 17572; case 276871: case 276872: case 276873: return 18411; default: return 0; } } private void scheduleOneShot() { ThreadPoolManager.getInstance().schedule(new Runnable() { @Override public void run() { if (getSkill() != 0) { if (getTarget() instanceof Npc) { Npc target = (Npc) getTarget(); Race race = target.getRace(); if ((race.equals(Race.GCHIEF_DARK) || race.equals(Race.GCHIEF_LIGHT)) && !target.getLifeStats().isAlreadyDead()) { AI2Actions.useSkill(DredgionCommanderAI2.this, getSkill()); getAggroList().addHate(target, 10000); } } scheduleOneShot(); } } }, 45 * 1000); } }
0
0.763415
1
0.763415
game-dev
MEDIA
0.964599
game-dev
0.94943
1
0.94943
RogyDev/Rogy-Engine-
43,474
Rogy/include/LuaBridge/detail/Namespace.h
//------------------------------------------------------------------------------ /* https://github.com/vinniefalco/LuaBridge Copyright 2019, Dmitry Tarakanov Copyright 2012, Vinnie Falco <vinnie.falco@gmail.com> Copyright 2007, Nathan Reed License: The MIT License (http://www.opensource.org/licenses/mit-license.php) 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 <LuaBridge/detail/Config.h> #include <LuaBridge/detail/ClassInfo.h> #include <LuaBridge/detail/LuaException.h> #include <LuaBridge/detail/Security.h> #include <LuaBridge/detail/TypeTraits.h> #include <stdexcept> #include <string> namespace luabridge { namespace detail { /** * Base for class and namespace registration. * Maintains Lua stack in the proper state. * Once beginNamespace, beginClass or deriveClass is called the parent * object upon its destruction may no longer clear the Lua stack. * Then endNamespace or endClass is called, a new parent is created * and the child transfers the responsibility for clearing stack to it. * So there can be maximum one "active" registrar object. */ class Registrar { protected: lua_State* const L; int mutable m_stackSize; Registrar (lua_State* L) : L (L) , m_stackSize (0) { } Registrar (const Registrar& rhs) : L (rhs.L) , m_stackSize (rhs.m_stackSize) { rhs.m_stackSize = 0; } #ifndef _MSC_VER // MS compiler thinks it's the 2nd copy ctor Registrar(Registrar& rhs) : L (rhs.L) , m_stackSize (rhs.m_stackSize) { rhs.m_stackSize = 0; } #endif // ifndef _MSC_VER Registrar& operator= (const Registrar& rhs) { Registrar tmp (rhs); std::swap (m_stackSize, tmp.m_stackSize); return *this; } ~Registrar () { if (m_stackSize > 0) { assert (m_stackSize <= lua_gettop (L)); lua_pop (L, m_stackSize); } } void assertIsActive () const { if (m_stackSize == 0) { throw std::logic_error ("Unable to continue registration"); } } }; } // namespace detail /** Provides C++ to Lua registration capabilities. This class is not instantiated directly, call `getGlobalNamespace` to start the registration process. */ class Namespace : public detail::Registrar { //============================================================================ /** Error reporting. VF: This function looks handy, why aren't we using it? */ #if 0 static int luaError (lua_State* L, std::string message) { assert (lua_isstring (L, lua_upvalueindex (1))); std::string s; // Get information on the caller's caller to format the message, // so the error appears to originate from the Lua source. lua_Debug ar; int result = lua_getstack (L, 2, &ar); if (result != 0) { lua_getinfo (L, "Sl", &ar); s = ar.short_src; if (ar.currentline != -1) { // poor mans int to string to avoid <strstrream>. lua_pushnumber (L, ar.currentline); s = s + ":" + lua_tostring (L, -1) + ": "; lua_pop (L, 1); } } s = s + message; return luaL_error (L, s.c_str ()); } #endif /** Factored base to reduce template instantiations. */ class ClassBase : public detail::Registrar { public: explicit ClassBase (Namespace& parent) : Registrar (parent) { } using Registrar::operator=; protected: //-------------------------------------------------------------------------- /** Create the const table. */ void createConstTable (const char* name, bool trueConst = true) { std::string type_name = std::string (trueConst ? "const " : "") + name; // Stack: namespace table (ns) lua_newtable (L); // Stack: ns, const table (co) lua_pushvalue (L, -1); // Stack: ns, co, co lua_setmetatable (L, -2); // co.__metatable = co. Stack: ns, co lua_pushstring (L, type_name.c_str ()); lua_rawsetp (L, -2, getTypeKey ()); // co [typeKey] = name. Stack: ns, co lua_pushcfunction (L, &CFunc::indexMetaMethod); rawsetfield (L, -2, "__index"); lua_pushcfunction (L, &CFunc::newindexObjectMetaMethod); rawsetfield (L, -2, "__newindex"); lua_newtable (L); lua_rawsetp (L, -2, getPropgetKey ()); if (Security::hideMetatables ()) { lua_pushnil (L); rawsetfield (L, -2, "__metatable"); } } //-------------------------------------------------------------------------- /** Create the class table. The Lua stack should have the const table on top. */ void createClassTable (char const* name) { // Stack: namespace table (ns), const table (co) // Class table is the same as const table except the propset table createConstTable (name, false); // Stack: ns, co, cl lua_newtable (L); // Stack: ns, co, cl, propset table (ps) lua_rawsetp (L, -2, getPropsetKey ()); // cl [propsetKey] = ps. Stack: ns, co, cl lua_pushvalue (L, -2); // Stack: ns, co, cl, co lua_rawsetp(L, -2, getConstKey ()); // cl [constKey] = co. Stack: ns, co, cl lua_pushvalue (L, -1); // Stack: ns, co, cl, cl lua_rawsetp (L, -3, getClassKey ()); // co [classKey] = cl. Stack: ns, co, cl } //-------------------------------------------------------------------------- /** Create the static table. */ void createStaticTable (char const* name) { // Stack: namespace table (ns), const table (co), class table (cl) lua_newtable (L); // Stack: ns, co, cl, visible static table (vst) lua_newtable (L); // Stack: ns, co, cl, st, static metatable (st) lua_pushvalue (L, -1); // Stack: ns, co, cl, vst, st, st lua_setmetatable (L, -3); // st.__metatable = mt. Stack: ns, co, cl, vst, st lua_insert (L, -2); // Stack: ns, co, cl, st, vst rawsetfield (L, -5, name); // ns [name] = vst. Stack: ns, co, cl, st #if 0 lua_pushlightuserdata (L, this); lua_pushcclosure (L, &tostringMetaMethod, 1); rawsetfield (L, -2, "__tostring"); #endif lua_pushcfunction (L, &CFunc::indexMetaMethod); rawsetfield (L, -2, "__index"); lua_pushcfunction (L, &CFunc::newindexStaticMetaMethod); rawsetfield (L, -2, "__newindex"); lua_newtable (L); // Stack: ns, co, cl, st, proget table (pg) lua_rawsetp (L, -2, getPropgetKey ()); // st [propgetKey] = pg. Stack: ns, co, cl, st lua_newtable (L); // Stack: ns, co, cl, st, propset table (ps) lua_rawsetp (L, -2, getPropsetKey ()); // st [propsetKey] = pg. Stack: ns, co, cl, st lua_pushvalue (L, -2); // Stack: ns, co, cl, st, cl lua_rawsetp(L, -2, getClassKey()); // st [classKey] = cl. Stack: ns, co, cl, st if (Security::hideMetatables ()) { lua_pushnil (L); rawsetfield (L, -2, "__metatable"); } } //========================================================================== /** lua_CFunction to construct a class object wrapped in a container. */ template <class Params, class C> static int ctorContainerProxy (lua_State* L) { typedef typename ContainerTraits <C>::Type T; ArgList <Params, 2> args (L); T* const p = Constructor <T, Params>::call (args); UserdataSharedHelper <C, false>::push (L, p); return 1; } //-------------------------------------------------------------------------- /** lua_CFunction to construct a class object in-place in the userdata. */ template <class Params, class T> static int ctorPlacementProxy (lua_State* L) { ArgList <Params, 2> args (L); UserdataValue <T>* value = UserdataValue <T>::place (L); Constructor <T, Params>::call (value->getObject (), args); value->commit (); return 1; } void assertStackState () const { // Stack: const table (co), class table (cl), static table (st) assert (lua_istable (L, -3)); assert (lua_istable (L, -2)); assert (lua_istable (L, -1)); } }; //============================================================================ // // Class // //============================================================================ /** Provides a class registration in a lua_State. After construction the Lua stack holds these objects: -1 static table -2 class table -3 const table -4 enclosing namespace table */ template <class T> class Class : public ClassBase { public: //========================================================================== /** Register a new class or add to an existing class registration. */ Class (char const* name, Namespace& parent) : ClassBase (parent) { assert (lua_istable (L, -1)); // Stack: namespace table (ns) rawgetfield (L, -1, name); // Stack: ns, static table (st) | nil if (lua_isnil (L, -1)) // Stack: ns, nil { lua_pop (L, 1); // Stack: ns createConstTable (name); // Stack: ns, const table (co) lua_pushcfunction (L, &CFunc::gcMetaMethod <T>); // Stack: ns, co, function rawsetfield (L, -2, "__gc"); // co ["__gc"] = function. Stack: ns, co ++m_stackSize; createClassTable (name); // Stack: ns, co, class table (cl) lua_pushcfunction (L, &CFunc::gcMetaMethod <T>); // Stack: ns, co, cl, function rawsetfield (L, -2, "__gc"); // cl ["__gc"] = function. Stack: ns, co, cl ++m_stackSize; createStaticTable (name); // Stack: ns, co, cl, st ++m_stackSize; // Map T back to its tables. lua_pushvalue (L, -1); // Stack: ns, co, cl, st, st lua_rawsetp (L, LUA_REGISTRYINDEX, ClassInfo <T>::getStaticKey ()); // Stack: ns, co, cl, st lua_pushvalue (L, -2); // Stack: ns, co, cl, st, cl lua_rawsetp (L, LUA_REGISTRYINDEX, ClassInfo <T>::getClassKey ()); // Stack: ns, co, cl, st lua_pushvalue (L, -3); // Stack: ns, co, cl, st, co lua_rawsetp (L, LUA_REGISTRYINDEX, ClassInfo <T>::getConstKey ()); // Stack: ns, co, cl, st } else { assert (lua_istable (L, -1)); // Stack: ns, st ++m_stackSize; // Map T back from its stored tables lua_rawgetp (L, LUA_REGISTRYINDEX, ClassInfo <T>::getConstKey ()); // Stack: ns, st, co lua_insert (L, -2); // Stack: ns, co, st ++m_stackSize; lua_rawgetp (L, LUA_REGISTRYINDEX, ClassInfo <T>::getClassKey ()); // Stack: ns, co, st, cl lua_insert (L, -2); // Stack: ns, co, cl, st ++m_stackSize; } } //========================================================================== /** Derive a new class. */ Class (char const* name, Namespace& parent, void const* const staticKey) : ClassBase (parent) { assert (lua_istable (L, -1)); // Stack: namespace table (ns) createConstTable (name); // Stack: ns, const table (co) lua_pushcfunction (L, &CFunc::gcMetaMethod <T>); // Stack: ns, co, function rawsetfield (L, -2, "__gc"); // co ["__gc"] = function. Stack: ns, co ++m_stackSize; createClassTable (name); // Stack: ns, co, class table (cl) lua_pushcfunction (L, &CFunc::gcMetaMethod <T>); // Stack: ns, co, cl, function rawsetfield (L, -2, "__gc"); // cl ["__gc"] = function. Stack: ns, co, cl ++m_stackSize; createStaticTable (name); // Stack: ns, co, cl, st ++m_stackSize; lua_rawgetp (L, LUA_REGISTRYINDEX, staticKey); // Stack: ns, co, cl, st, parent st (pst) | nil if (lua_isnil (L, -1)) // Stack: ns, co, cl, st, nil { ++m_stackSize; throw std::runtime_error ("Base class is not registered"); } assert (lua_istable (L, -1)); // Stack: ns, co, cl, st, pst lua_rawgetp (L, -1, getClassKey ()); // Stack: ns, co, cl, st, pst, parent cl (pcl) assert (lua_istable (L, -1)); lua_rawgetp (L, -1, getConstKey ()); // Stack: ns, co, cl, st, pst, pcl, parent co (pco) assert (lua_istable (L, -1)); lua_rawsetp (L, -6, getParentKey ()); // co [parentKey] = pco. Stack: ns, co, cl, st, pst, pcl lua_rawsetp (L, -4, getParentKey ()); // cl [parentKey] = pcl. Stack: ns, co, cl, st, pst lua_rawsetp (L, -2, getParentKey ()); // st [parentKey] = pst. Stack: ns, co, cl, st lua_pushvalue (L, -1); // Stack: ns, co, cl, st, st lua_rawsetp (L, LUA_REGISTRYINDEX, ClassInfo <T>::getStaticKey ()); // Stack: ns, co, cl, st lua_pushvalue (L, -2); // Stack: ns, co, cl, st, cl lua_rawsetp (L, LUA_REGISTRYINDEX, ClassInfo <T>::getClassKey ()); // Stack: ns, co, cl, st lua_pushvalue (L, -3); // Stack: ns, co, cl, st, co lua_rawsetp (L, LUA_REGISTRYINDEX, ClassInfo <T>::getConstKey ()); // Stack: ns, co, cl, st } //-------------------------------------------------------------------------- /** Continue registration in the enclosing namespace. */ Namespace endClass () { assert (m_stackSize > 3); m_stackSize -= 3; lua_pop (L, 3); return Namespace (*this); } //-------------------------------------------------------------------------- /** Add or replace a static data member. */ template <class U> Class <T>& addStaticProperty (char const* name, U* pu, bool isWritable = true) { return addStaticData (name, pu, isWritable); } //-------------------------------------------------------------------------- /** Add or replace a static data member. */ template <class U> Class <T>& addStaticData (char const* name, U* pu, bool isWritable = true) { assertStackState (); // Stack: const table (co), class table (cl), static table (st) lua_pushlightuserdata (L, pu); // Stack: co, cl, st, pointer lua_pushcclosure (L, &CFunc::getVariable <U>, 1); // Stack: co, cl, st, getter CFunc::addGetter (L, name, -2); // Stack: co, cl, st if (isWritable) { lua_pushlightuserdata (L, pu); // Stack: co, cl, st, ps, pointer lua_pushcclosure (L, &CFunc::setVariable <U>, 1); // Stack: co, cl, st, ps, setter } else { lua_pushstring (L, name); // Stack: co, cl, st, name lua_pushcclosure (L, &CFunc::readOnlyError, 1); // Stack: co, cl, st, error_fn } CFunc::addSetter (L, name, -2); // Stack: co, cl, st return *this; } //-------------------------------------------------------------------------- /** Add or replace a static property member. If the set function is null, the property is read-only. */ template <class U> Class <T>& addStaticProperty (char const* name, U (*get) (), void (*set) (U) = 0) { assertStackState (); // Stack: const table (co), class table (cl), static table (st) lua_pushlightuserdata (L, reinterpret_cast <void*> (get)); // Stack: co, cl, st, function ptr lua_pushcclosure (L, &CFunc::Call <U (*) ()>::f, 1); // Stack: co, cl, st, getter CFunc::addGetter (L, name, -2); // Stack: co, cl, st if (set != 0) { lua_pushlightuserdata (L, reinterpret_cast <void*> (set)); // Stack: co, cl, st, function ptr lua_pushcclosure (L, &CFunc::Call <void (*) (U)>::f, 1); // Stack: co, cl, st, setter } else { lua_pushstring (L, name); // Stack: co, cl, st, ps, name lua_pushcclosure (L, &CFunc::readOnlyError, 1); // Stack: co, cl, st, error_fn } CFunc::addSetter (L, name, -2); // Stack: co, cl, st return *this; } //-------------------------------------------------------------------------- /** Add or replace a static member function. */ template <class FP> Class <T>& addStaticFunction (char const* name, FP const fp) { assertStackState (); // Stack: const table (co), class table (cl), static table (st) lua_pushlightuserdata (L, reinterpret_cast <void*> (fp)); // Stack: co, cl, st, function ptr lua_pushcclosure (L, &CFunc::Call <FP>::f, 1); // co, cl, st, function rawsetfield (L, -2, name); // co, cl, st return *this; } //-------------------------------------------------------------------------- /** Add or replace a lua_CFunction. */ Class <T>& addStaticFunction (char const* name, int (*const fp) (lua_State*)) { return addStaticCFunction (name, fp); } //-------------------------------------------------------------------------- /** Add or replace a lua_CFunction. */ Class <T>& addStaticCFunction (char const* name, int (*const fp) (lua_State*)) { assertStackState (); // Stack: const table (co), class table (cl), static table (st) lua_pushcfunction (L, fp); // co, cl, st, function rawsetfield (L, -2, name); // co, cl, st return *this; } //-------------------------------------------------------------------------- /** Add or replace a data member. */ template <class U> Class <T>& addProperty (char const* name, U T::* mp, bool isWritable = true) { return addData (name, mp, isWritable); } //-------------------------------------------------------------------------- /** Add or replace a data member. */ template <class U> Class <T>& addData (char const* name, U T::* mp, bool isWritable = true) { assertStackState (); // Stack: const table (co), class table (cl), static table (st) typedef const U T::*mp_t; new (lua_newuserdata (L, sizeof (mp_t))) mp_t (mp); // Stack: co, cl, st, field ptr lua_pushcclosure (L, &CFunc::getProperty <T, U>, 1); // Stack: co, cl, st, getter lua_pushvalue (L, -1); // Stack: co, cl, st, getter, getter CFunc::addGetter (L, name, -5); // Stack: co, cl, st, getter CFunc::addGetter (L, name, -3); // Stack: co, cl, st if (isWritable) { new (lua_newuserdata (L, sizeof (mp_t))) mp_t (mp); // Stack: co, cl, st, field ptr lua_pushcclosure (L, &CFunc::setProperty <T, U>, 1); // Stack: co, cl, st, setter CFunc::addSetter (L, name, -3); // Stack: co, cl, st } return *this; } //-------------------------------------------------------------------------- /** Add or replace a property member. */ template <class TG, class TS = TG> Class <T>& addProperty (char const* name, TG (T::* get) () const, void (T::* set) (TS) = 0) { assertStackState (); // Stack: const table (co), class table (cl), static table (st) typedef TG (T::*get_t) () const; new (lua_newuserdata (L, sizeof (get_t))) get_t (get); // Stack: co, cl, st, funcion ptr lua_pushcclosure (L, &CFunc::CallConstMember <get_t>::f, 1); // Stack: co, cl, st, getter lua_pushvalue (L, -1); // Stack: co, cl, st, getter, getter CFunc::addGetter (L, name, -5); // Stack: co, cl, st, getter CFunc::addGetter (L, name, -3); // Stack: co, cl, st if (set != 0) { typedef void (T::* set_t) (TS); new (lua_newuserdata (L, sizeof (set_t))) set_t (set); // Stack: co, cl, st, function ptr lua_pushcclosure (L, &CFunc::CallMember <set_t>::f, 1); // Stack: co, cl, st, setter CFunc::addSetter (L, name, -3); // Stack: co, cl, st } return *this; } //-------------------------------------------------------------------------- /** Add or replace a property member. */ template <class TG, class TS = TG> Class <T>& addProperty (char const* name, TG (T::* get) (lua_State*) const, void (T::* set) (TS, lua_State*) = 0) { assertStackState (); // Stack: const table (co), class table (cl), static table (st) typedef TG (T::*get_t) (lua_State*) const; new (lua_newuserdata (L, sizeof (get_t))) get_t (get); // Stack: co, cl, st, funcion ptr lua_pushcclosure (L, &CFunc::CallConstMember <get_t>::f, 1); // Stack: co, cl, st, getter lua_pushvalue (L, -1); // Stack: co, cl, st, getter, getter CFunc::addGetter (L, name, -5); // Stack: co, cl, st, getter CFunc::addGetter (L, name, -3); // Stack: co, cl, st if (set != 0) { typedef void (T::* set_t) (TS, lua_State*); new (lua_newuserdata (L, sizeof (set_t))) set_t (set); // Stack: co, cl, st, function ptr lua_pushcclosure (L, &CFunc::CallMember <set_t>::f, 1); // Stack: co, cl, st, setter CFunc::addSetter (L, name, -3); // Stack: co, cl, st } return *this; } //-------------------------------------------------------------------------- /** Add or replace a property member, by proxy. When a class is closed for modification and does not provide (or cannot provide) the function signatures necessary to implement get or set for a property, this will allow non-member functions act as proxies. Both the get and the set functions require a T const* and T* in the first argument respectively. */ template <class TG, class TS = TG> Class <T>& addProperty (char const* name, TG (*get) (T const*), void (*set) (T*, TS) = 0) { assertStackState (); // Stack: const table (co), class table (cl), static table (st) lua_pushlightuserdata (L, reinterpret_cast <void*> (get)); // Stack: co, cl, st, function ptr lua_pushcclosure (L, &CFunc::Call <TG (*) (const T*)>::f, 1); // Stack: co, cl, st, getter lua_pushvalue (L, -1); // Stack: co, cl, st,, getter, getter CFunc::addGetter (L, name, -5); // Stack: co, cl, st, getter CFunc::addGetter (L, name, -3); // Stack: co, cl, st if (set != 0) { lua_pushlightuserdata (L, reinterpret_cast <void*> (set)); // Stack: co, cl, st, function ptr lua_pushcclosure (L, &CFunc::Call <void (*) (T*, TS)>::f, 1); // Stack: co, cl, st, setter CFunc::addSetter (L, name, -3); // Stack: co, cl, st } return *this; } //-------------------------------------------------------------------------- /** Add or replace a property member, by proxy C-function. When a class is closed for modification and does not provide (or cannot provide) the function signatures necessary to implement get or set for a property, this will allow non-member functions act as proxies. The object userdata ('this') value is at the index 1. The new value for set function is at the index 2. */ Class <T>& addProperty (char const* name, int (*get) (lua_State*), int (*set) (lua_State*) = 0) { assertStackState (); // Stack: const table (co), class table (cl), static table (st) lua_pushcfunction (L, get); lua_pushvalue (L, -1); // Stack: co, cl, st,, getter, getter CFunc::addGetter (L, name, -5); // Stack: co, cl, st,, getter CFunc::addGetter (L, name, -3); // Stack: co, cl, st, if (set != 0) { lua_pushcfunction (L, set); CFunc::addSetter (L, name, -3); // Stack: co, cl, st, } return *this; } #ifdef LUABRIDGE_CXX11 template <class TG, class TS = TG> Class <T>& addProperty (char const* name, std::function <TG (const T*)> get, std::function <void (T*, TS)> set = nullptr) { using GetType = decltype (get); new (lua_newuserdata (L, sizeof (get))) GetType (std::move (get)); // Stack: co, cl, st, function userdata (ud) lua_newtable (L); // Stack: co, cl, st, ud, ud metatable (mt) lua_pushcfunction (L, &CFunc::gcMetaMethodAny <GetType>); // Stack: co, cl, st, ud, mt, gc function rawsetfield (L, -2, "__gc"); // Stack: co, cl, st, ud, mt lua_setmetatable (L, -2); // Stack: co, cl, st, ud lua_pushcclosure (L, &CFunc::CallProxyFunctor <GetType>::f, 1); // Stack: co, cl, st, getter lua_pushvalue (L, -1); // Stack: co, cl, st, getter, getter CFunc::addGetter (L, name, -4); // Stack: co, cl, st, getter CFunc::addGetter (L, name, -4); // Stack: co, cl, st if (set != nullptr) { using SetType = decltype (set); new (lua_newuserdata (L, sizeof (set))) SetType (std::move (set)); // Stack: co, cl, st, function userdata (ud) lua_newtable (L); // Stack: co, cl, st, ud, ud metatable (mt) lua_pushcfunction (L, &CFunc::gcMetaMethodAny <SetType>); // Stack: co, cl, st, ud, mt, gc function rawsetfield (L, -2, "__gc"); // Stack: co, cl, st, ud, mt lua_setmetatable (L, -2); // Stack: co, cl, st, ud lua_pushcclosure (L, &CFunc::CallProxyFunctor <SetType>::f, 1); // Stack: co, cl, st, setter CFunc::addSetter (L, name, -3); // Stack: co, cl, st } return *this; } #endif // LUABRIDGE_CXX11 #ifndef LUABRIDGE_CXX11 //-------------------------------------------------------------------------- /** Add or replace a member function. */ template <class MemFn> Class <T>& addFunction (char const* name, MemFn mf) { assertStackState (); // Stack: const table (co), class table (cl), static table (st) static const std::string GC = "__gc"; if (name == GC) { throw std::logic_error (GC + " metamethod registration is forbidden"); } CFunc::CallMemberFunctionHelper <MemFn, FuncTraits <MemFn>::isConstMemberFunction>::add (L, name, mf); return *this; } #else // ifndef LUABRIDGE_CXX11 //-------------------------------------------------------------------------- /** Add or replace a member function by std::function. */ template <class ReturnType, class... Params> Class <T>& addFunction (char const* name, std::function <ReturnType (T*, Params...)> function) { assertStackState (); // Stack: const table (co), class table (cl), static table (st) using FnType = decltype (function); new (lua_newuserdata (L, sizeof (function))) FnType (std::move (function)); // Stack: co, cl, st, function userdata (ud) lua_newtable (L); // Stack: co, cl, st, ud, ud metatable (mt) lua_pushcfunction (L, &CFunc::gcMetaMethodAny <FnType>); // Stack: co, cl, st, ud, mt, gc function rawsetfield (L, -2, "__gc"); // Stack: co, cl, st, ud, mt lua_setmetatable (L, -2); // Stack: co, cl, st, ud lua_pushcclosure (L, &CFunc::CallProxyFunctor <FnType>::f, 1); // Stack: co, cl, st, function rawsetfield (L, -3, name); // Stack: co, cl, st return *this; } //-------------------------------------------------------------------------- /** Add or replace a const member function by std::function. */ template <class ReturnType, class... Params> Class <T>& addFunction (char const* name, std::function <ReturnType (const T*, Params...)> function) { assertStackState (); // Stack: const table (co), class table (cl), static table (st) using FnType = decltype (function); new (lua_newuserdata (L, sizeof (function))) FnType (std::move (function)); // Stack: co, cl, st, function userdata (ud) lua_newtable (L); // Stack: co, cl, st, ud, ud metatable (mt) lua_pushcfunction (L, &CFunc::gcMetaMethodAny <FnType>); // Stack: co, cl, st, ud, mt, gc function rawsetfield (L, -2, "__gc"); // Stack: co, cl, st, ud, mt lua_setmetatable (L, -2); // Stack: co, cl, st, ud lua_pushcclosure (L, &CFunc::CallProxyFunctor <FnType>::f, 1); // Stack: co, cl, st, function lua_pushvalue (L, -1); // Stack: co, cl, st, function, function rawsetfield (L, -4, name); // Stack: co, cl, st, function rawsetfield (L, -4, name); // Stack: co, cl, st return *this; } //-------------------------------------------------------------------------- /** Add or replace a member function. */ template <class ReturnType, class... Params> Class <T>& addFunction (char const* name, ReturnType (T::* mf) (Params...)) { using MemFn = ReturnType (T::*) (Params...); assertStackState (); // Stack: const table (co), class table (cl), static table (st) static const std::string GC = "__gc"; if (name == GC) { throw std::logic_error (GC + " metamethod registration is forbidden"); } CFunc::CallMemberFunctionHelper <MemFn, false>::add (L, name, mf); return *this; } template <class ReturnType, class... Params> Class <T>& addFunction (char const* name, ReturnType (T::* mf) (Params...) const) { using MemFn = ReturnType (T::*) (Params...) const; assertStackState (); // Stack: const table (co), class table (cl), static table (st) static const std::string GC = "__gc"; if (name == GC) { throw std::logic_error (GC + " metamethod registration is forbidden"); } CFunc::CallMemberFunctionHelper <MemFn, true>::add (L, name, mf); return *this; } //-------------------------------------------------------------------------- /** Add or replace a proxy function. */ template <class ReturnType, class... Params> Class <T>& addFunction (char const* name, ReturnType (*proxyFn) (T* object, Params...)) { assertStackState (); // Stack: const table (co), class table (cl), static table (st) static const std::string GC = "__gc"; if (name == GC) { throw std::logic_error (GC + " metamethod registration is forbidden"); } using FnType = decltype (proxyFn); lua_pushlightuserdata (L, reinterpret_cast <void*> (proxyFn)); // Stack: co, cl, st, function ptr lua_pushcclosure (L, &CFunc::CallProxyFunction <FnType>::f, 1); // Stack: co, cl, st, function rawsetfield (L, -3, name); // Stack: co, cl, st return *this; } template <class ReturnType, class... Params> Class <T>& addFunction (char const* name, ReturnType (*proxyFn) (const T* object, Params...)) { assertStackState (); // Stack: const table (co), class table (cl), static table (st) static const std::string GC = "__gc"; if (name == GC) { throw std::logic_error (GC + " metamethod registration is forbidden"); } using FnType = decltype (proxyFn); lua_pushlightuserdata (L, reinterpret_cast <void*> (proxyFn)); // Stack: co, cl, st, function ptr lua_pushcclosure (L, &CFunc::CallProxyFunction <FnType>::f, 1); // Stack: co, cl, st, function lua_pushvalue (L, -1); // Stack: co, cl, st, function, function rawsetfield (L, -4, name); // Stack: co, cl, st, function rawsetfield (L, -4, name); // Stack: co, cl, st return *this; } #endif //-------------------------------------------------------------------------- /** Add or replace a member lua_CFunction. */ Class <T>& addFunction (char const* name, int (T::*mfp) (lua_State*)) { return addCFunction (name, mfp); } //-------------------------------------------------------------------------- /** Add or replace a member lua_CFunction. */ Class <T>& addCFunction (char const* name, int (T::*mfp) (lua_State*)) { assertStackState (); // Stack: const table (co), class table (cl), static table (st) typedef int (T::*MFP) (lua_State*); new (lua_newuserdata (L, sizeof (mfp))) MFP (mfp); // Stack: co, cl, st, function ptr lua_pushcclosure (L, &CFunc::CallMemberCFunction <T>::f, 1); // Stack: co, cl, st, function rawsetfield (L, -3, name); // Stack: co, cl, st return *this; } //-------------------------------------------------------------------------- /** Add or replace a const member lua_CFunction. */ Class <T>& addFunction (char const* name, int (T::*mfp) (lua_State*) const) { return addCFunction (name, mfp); } //-------------------------------------------------------------------------- /** Add or replace a const member lua_CFunction. */ Class <T>& addCFunction (char const* name, int (T::*mfp) (lua_State*) const) { assertStackState (); // Stack: const table (co), class table (cl), static table (st) typedef int (T::*MFP) (lua_State*) const; new (lua_newuserdata (L, sizeof (mfp))) MFP (mfp); lua_pushcclosure (L, &CFunc::CallConstMemberCFunction <T>::f, 1); lua_pushvalue (L, -1); // Stack: co, cl, st, function, function rawsetfield (L, -4, name); // Stack: co, cl, st, function rawsetfield (L, -4, name); // Stack: co, cl, st return *this; } //-------------------------------------------------------------------------- /** Add or replace a primary Constructor. The primary Constructor is invoked when calling the class type table like a function. The template parameter should be a function pointer type that matches the desired Constructor (since you can't take the address of a Constructor and pass it as an argument). */ template <class MemFn, class C> Class <T>& addConstructor () { assertStackState (); // Stack: const table (co), class table (cl), static table (st) lua_pushcclosure (L, &ctorContainerProxy <typename FuncTraits <MemFn>::Params, C>, 0); rawsetfield (L, -2, "__call"); return *this; } template <class MemFn> Class <T>& addConstructor () { assertStackState (); // Stack: const table (co), class table (cl), static table (st) lua_pushcclosure (L, &ctorPlacementProxy <typename FuncTraits <MemFn>::Params, T>, 0); rawsetfield (L, -2, "__call"); return *this; } }; private: //---------------------------------------------------------------------------- /** Open the global namespace for registrations. */ explicit Namespace (lua_State* L) : Registrar (L) { lua_getglobal (L, "_G"); ++m_stackSize; } //---------------------------------------------------------------------------- /** Open a namespace for registrations. The namespace is created if it doesn't already exist. The parent namespace is at the top of the Lua stack. */ Namespace (char const* name, Namespace& parent) : Registrar (parent) { assert (lua_istable (L, -1)); // Stack: parent namespace (pns) rawgetfield (L, -1, name); // Stack: pns, namespace (ns) | nil if (lua_isnil (L, -1)) // Stack: pns, nil { lua_pop (L, 1); // Stack: pns lua_newtable (L); // Stack: pns, ns lua_pushvalue (L, -1); // Stack: pns, ns, ns // na.__metatable = ns lua_setmetatable (L, -2); // Stack: pns, ns // ns.__index = indexMetaMethod lua_pushcfunction (L, &CFunc::indexMetaMethod); rawsetfield (L, -2, "__index"); // Stack: pns, ns // ns.__newindex = newindexMetaMethod lua_pushcfunction (L, &CFunc::newindexStaticMetaMethod); rawsetfield (L, -2, "__newindex"); // Stack: pns, ns lua_newtable (L); // Stack: pns, ns, propget table (pg) lua_rawsetp (L, -2, getPropgetKey ()); // ns [propgetKey] = pg. Stack: pns, ns lua_newtable (L); // Stack: pns, ns, propset table (ps) lua_rawsetp (L, -2, getPropsetKey ()); // ns [propsetKey] = ps. Stack: pns, ns // pns [name] = ns lua_pushvalue (L, -1); // Stack: pns, ns, ns rawsetfield (L, -3, name); // Stack: pns, ns #if 0 lua_pushcfunction (L, &tostringMetaMethod); rawsetfield (L, -2, "__tostring"); #endif } ++m_stackSize; } //---------------------------------------------------------------------------- /** Close the class and continue the namespace registrations. */ explicit Namespace (ClassBase& child) : Registrar (child) { } using Registrar::operator=; public: //---------------------------------------------------------------------------- /** Open the global namespace. */ static Namespace getGlobalNamespace (lua_State* L) { enableExceptions (L); return Namespace (L); } //---------------------------------------------------------------------------- /** Open a new or existing namespace for registrations. */ Namespace beginNamespace (char const* name) { assertIsActive (); return Namespace (name, *this); } //---------------------------------------------------------------------------- /** Continue namespace registration in the parent. Do not use this on the global namespace. */ Namespace endNamespace () { if (m_stackSize == 1) { throw std::logic_error ("endNamespace () called on global namespace"); } assert (m_stackSize > 1); --m_stackSize; lua_pop (L, 1); return Namespace (*this); } //---------------------------------------------------------------------------- /** Add or replace a variable. */ template <class T> Namespace& addProperty (char const* name, T* pt, bool isWritable = true) { return addVariable (name, pt, isWritable); } //---------------------------------------------------------------------------- /** Add or replace a variable. */ template <class T> Namespace& addVariable (char const* name, T* pt, bool isWritable = true) { if (m_stackSize == 1) { throw std::logic_error ("addProperty () called on global namespace"); } assert (lua_istable (L, -1)); // Stack: namespace table (ns) lua_pushlightuserdata (L, pt); // Stack: ns, pointer lua_pushcclosure (L, &CFunc::getVariable <T>, 1); // Stack: ns, getter CFunc::addGetter (L, name, -2); // Stack: ns if (isWritable) { lua_pushlightuserdata (L, pt); // Stack: ns, pointer lua_pushcclosure (L, &CFunc::setVariable <T>, 1); // Stack: ns, setter } else { lua_pushstring (L, name); // Stack: ns, ps, name lua_pushcclosure (L, &CFunc::readOnlyError, 1); // Stack: ns, error_fn } CFunc::addSetter (L, name, -2); // Stack: ns return *this; } //---------------------------------------------------------------------------- /** Add or replace a property. If the set function is omitted or null, the property is read-only. */ template <class TG, class TS = TG> Namespace& addProperty (char const* name, TG (*get) (), void (*set) (TS) = 0) { if (m_stackSize == 1) { throw std::logic_error ("addProperty () called on global namespace"); } assert (lua_istable (L, -1)); // Stack: namespace table (ns) lua_pushlightuserdata (L, reinterpret_cast <void*> (get)); // Stack: ns, function ptr lua_pushcclosure (L, &CFunc::Call <TG (*) ()>::f, 1); // Stack: ns, getter CFunc::addGetter (L, name, -2); if (set != 0) { lua_pushlightuserdata(L, reinterpret_cast <void*> (set)); // Stack: ns, function ptr lua_pushcclosure (L, &CFunc::Call <void (*) (TS)>::f, 1); } else { lua_pushstring (L, name); lua_pushcclosure (L, &CFunc::readOnlyError, 1); } CFunc::addSetter (L, name, -2); return *this; } //---------------------------------------------------------------------------- /** Add or replace a property. If the set function is omitted or null, the property is read-only. */ Namespace& addProperty (char const* name, int (*get) (lua_State*), int (*set) (lua_State*) = 0) { if (m_stackSize == 1) { throw std::logic_error ("addProperty () called on global namespace"); } assert (lua_istable (L, -1)); // Stack: namespace table (ns) lua_pushcfunction (L, get); // Stack: ns, getter CFunc::addGetter (L, name, -2); // Stack: ns if (set != 0) { lua_pushcfunction(L, set); // Stack: ns, setter CFunc::addSetter(L, name, -2); // Stack: ns } else { lua_pushstring(L, name); // Stack: ns, name lua_pushcclosure(L, &CFunc::readOnlyError, 1); // Stack: ns, name, readOnlyError CFunc::addSetter(L, name, -2); // Stack: ns } return *this; } //---------------------------------------------------------------------------- /** Add or replace a free function. */ template <class FP> Namespace& addFunction (char const* name, FP const fp) { assert (lua_istable (L, -1)); // Stack: namespace table (ns) lua_pushlightuserdata (L, reinterpret_cast <void*> (fp)); // Stack: ns, function ptr lua_pushcclosure (L, &CFunc::Call <FP>::f, 1); // Stack: ns, function rawsetfield (L, -2, name); // Stack: ns return *this; } //---------------------------------------------------------------------------- /** Add or replace a lua_CFunction. */ Namespace& addFunction (char const* name, int (*const fp) (lua_State*)) { return addCFunction (name, fp); } //---------------------------------------------------------------------------- /** Add or replace a lua_CFunction. */ Namespace& addCFunction (char const* name, int (*const fp) (lua_State*)) { assert (lua_istable (L, -1)); // Stack: namespace table (ns) lua_pushcfunction (L, fp); // Stack: ns, function rawsetfield (L, -2, name); // Stack: ns return *this; } //---------------------------------------------------------------------------- /** Open a new or existing class for registrations. */ template <class T> Class <T> beginClass (char const* name) { assertIsActive (); return Class <T> (name, *this); } //---------------------------------------------------------------------------- /** Derive a new class for registrations. To continue registrations for the class later, use beginClass (). Do not call deriveClass () again. */ template <class Derived, class Base> Class <Derived> deriveClass (char const* name) { assertIsActive (); return Class <Derived> (name, *this, ClassInfo <Base>::getStaticKey ()); } }; //------------------------------------------------------------------------------ /** Retrieve the global namespace. It is recommended to put your namespace inside the global namespace, and then add your classes and functions to it, rather than adding many classes and functions directly to the global namespace. */ inline Namespace getGlobalNamespace (lua_State* L) { return Namespace::getGlobalNamespace (L); } } // namespace luabridge
0
0.955589
1
0.955589
game-dev
MEDIA
0.683826
game-dev
0.57346
1
0.57346
Secrets-of-Sosaria/World
1,492
Data/Scripts/Items/Magical/Gifts/Armor/Dragon/GiftDragonChest.cs
using System; using Server.Items; namespace Server.Items { [FlipableAttribute( 0x2641, 0x2642 )] public class GiftDragonChest : BaseGiftArmor { public override int BasePhysicalResistance{ get{ return 3; } } public override int BaseFireResistance{ get{ return 3; } } public override int BaseColdResistance{ get{ return 3; } } public override int BasePoisonResistance{ get{ return 3; } } public override int BaseEnergyResistance{ get{ return 3; } } public override int InitMinHits{ get{ return 55; } } public override int InitMaxHits{ get{ return 75; } } public override int AosStrReq{ get{ return 75; } } public override int OldStrReq{ get{ return 60; } } public override int OldDexBonus{ get{ return -8; } } public override int ArmorBase{ get{ return 40; } } public override ArmorMaterialType MaterialType{ get{ return ArmorMaterialType.Scaled; } } public override CraftResource DefaultResource{ get{ return CraftResource.RegularLeather; } } [Constructable] public GiftDragonChest() : base( 0x2641 ) { Weight = 10.0; Hue = 0x66D; Name = "dragon scale tunic"; } public GiftDragonChest( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); } public override void Deserialize(GenericReader reader) { base.Deserialize( reader ); int version = reader.ReadInt(); if ( Weight == 1.0 ) Weight = 15.0; } } }
0
0.864277
1
0.864277
game-dev
MEDIA
0.974005
game-dev
0.892829
1
0.892829
colorblindness/3arthh4ck
22,067
src/main/java/me/earth/earthhack/impl/modules/combat/autotrap/AutoTrap.java
package me.earth.earthhack.impl.modules.combat.autotrap; 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.combat.autotrap.modes.TrapTarget; import me.earth.earthhack.impl.modules.combat.autotrap.util.Trap; import me.earth.earthhack.impl.util.helpers.blocks.ObbyListenerModule; import me.earth.earthhack.impl.util.helpers.blocks.util.TargetResult; import me.earth.earthhack.impl.util.math.MathUtil; import me.earth.earthhack.impl.util.math.position.PositionUtil; import me.earth.earthhack.impl.util.minecraft.DamageUtil; 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 net.minecraft.entity.Entity; import net.minecraft.entity.item.EntityEnderCrystal; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3i; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class AutoTrap extends ObbyListenerModule<ListenerAutoTrap> { /** EnumFacings for the top helpingPos */ private static final EnumFacing[] TOP_FACINGS = new EnumFacing[] { EnumFacing.UP, EnumFacing.NORTH, EnumFacing.WEST, EnumFacing.SOUTH, EnumFacing.EAST }; protected final Setting<Float> range = register(new NumberSetting<>("Range", 6.0f, 0.0f, 6.0f)); protected final Setting<Boolean> noScaffold = register(new BooleanSetting("NoScaffold", false)); protected final Setting<Boolean> top = register(new BooleanSetting("Top", true)); protected final Setting<Boolean> noStep = register(new BooleanSetting("NoStep", false)); protected final Setting<Boolean> upperBody = register(new BooleanSetting("UpperBody", true)); protected final Setting<Boolean> legs = register(new BooleanSetting("Legs", false)); protected final Setting<Boolean> platform = register(new BooleanSetting("Platform", false)); protected final Setting<Boolean> noDrop = register(new BooleanSetting("NoDrop", false)); protected final Setting<Integer> extend = register(new NumberSetting<>("Extend", 2, 1, 3)); protected final Setting<TrapTarget> targetMode = register(new EnumSetting<>("Target", TrapTarget.Closest)); protected final Setting<Float> speed = register(new NumberSetting<>("Speed", 19.0f, 0.0f, 50.0f)); protected final Setting<Boolean> freeCam = register(new BooleanSetting("FreeCam", false)); protected final Setting<Boolean> bigExtend = register(new BooleanSetting("BigExtend", false)); protected final Setting<Boolean> helping = register(new BooleanSetting("Helping", false)); protected final Setting<Boolean> smartTop = register(new BooleanSetting("SmartTop", true)); protected final Setting<Boolean> noScaffoldPlus = register(new BooleanSetting("NoScaffold+", false)); protected final Setting<Boolean> upperFace = register(new BooleanSetting("Upper-FP", false)); /** Players in range mapped to their speed */ protected final Map<EntityPlayer, Double> speeds = new HashMap<>(); /** Caches trapping positions for players while looking for a target */ protected final Map<EntityPlayer, List<BlockPos>> cached = new HashMap<>(); /** The current target */ protected EntityPlayer target; public AutoTrap() { super("AutoTrap", Category.Combat); this.setData(new AutoTrapData(this)); } @Override protected void onDisable() { super.onDisable(); Managers.ROTATION.setBlocking(false); } @Override protected boolean checkNull() { boolean checkNull = super.checkNull(); cached.clear(); speeds.clear(); if (checkNull) { updateSpeed(); } return checkNull; } @Override protected ListenerAutoTrap createListener() { return new ListenerAutoTrap(this); } @Override public String getDisplayInfo() { return target == null ? null : target.getName(); } @Override protected boolean shouldHelp(EnumFacing facing, BlockPos pos) { return super.shouldHelp(facing, pos) // ?????? && helping.getValue() && !legs.getValue(); } public EntityPlayer getTarget() { return target; } protected TargetResult getTargets(TargetResult result) { cached.clear(); updateSpeed(); EntityPlayer newTarget = calcTarget(); if (newTarget == null || !newTarget.equals(target)) { listener.placed.clear(); } target = newTarget == null ? target : newTarget; if (newTarget == null) { return result.setValid(false); } List<BlockPos> newTrapping = cached.get(newTarget); if (newTrapping == null) { newTrapping = getPositions(newTarget); } return result.setTargets(newTrapping); } /** * Finds the closest valid player, * or if mode == Untrapped, the closest * untrapped player. * * @return the target. */ private EntityPlayer calcTarget() { EntityPlayer closest = null; double distance = Double.MAX_VALUE; for (EntityPlayer player : mc.world.playerEntities) { double playerDist = mc.player.getDistanceSq(player); if (playerDist < distance && isValid(player)) { closest = player; distance = playerDist; } } return closest; } /** * Checks if a given player is valid, * that means != null, not dead, not mc.player, * not friended, in range, moving slower than * the speed setting, and if mode == Untrapped, * if hes not trapped. * * @param player the player to check. * @return if the given player can be trapped. */ private boolean isValid(EntityPlayer player) { if (player != null && !EntityUtil.isDead(player) && !player.equals(mc.player) && !Managers.FRIENDS.contains(player)) { if (player.getDistanceSq(mc.player) <= 36 && getSpeed(player) <= speed.getValue()) { if (targetMode.getValue() == TrapTarget.Untrapped) { List<BlockPos> positions = getPositions(player); cached.put(player, positions); return positions.stream() .anyMatch(pos -> mc.world.getBlockState(pos) .getMaterial() .isReplaceable()); } return true; } } return false; } /** * Updates the speed map for all * players in range. */ private void updateSpeed() { for (EntityPlayer player : mc.world.playerEntities) { if (EntityUtil.isValid(player, range.getValue() * 2)) { double xDist = player.posX - player.prevPosX; double yDist = player.posY - player.prevPosY; double zDist = player.posZ - player.prevPosZ; double speed = xDist * xDist + yDist * yDist + zDist * zDist; speeds.put(player, speed); } } } /** * Looks up a player from the speed * map and returns his speed or 0.0 if * he hasn't been mapped yet. * * @param player the player whose speed to check. * @return the players speed. */ private double getSpeed(EntityPlayer player) { Double playerSpeed = speeds.get(player); if (playerSpeed != null && speed.getValue() != 50.0f) { return Math.sqrt(playerSpeed) * 20 * 3.6; } return 0.0; } /** * Gets the positions to trap * for the given player. Takes extend * and the noScaffold... etc. settings into * account. * * @param player the player to trap. * @return trapping positions. */ private List<BlockPos> getPositions(EntityPlayer player) { List<BlockPos> blocked = new ArrayList<>(); BlockPos playerPos = new BlockPos(player); if (HoleUtil.isHole(playerPos, false)[0] || extend.getValue() == 1) { blocked.add(playerPos.up()); } else { List<BlockPos> unfiltered = new ArrayList<>(PositionUtil.getBlockedPositions(player)) .stream() .sorted(Comparator .comparingDouble(BlockUtil::getDistanceSq)) .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(); } } 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 he phased in, be able to place on o */ while (filtered.size() > 2) { filtered.remove(filtered.size() - 1); } } for (BlockPos pos : filtered) { blocked.add(pos.up()); } } if (blocked.isEmpty()) { blocked.add(playerPos.up()); } List<BlockPos> positions = positionsFromBlocked(blocked); // sort so we start placing behind (furthest away) first. positions.sort(Comparator.comparingDouble(pos -> -BlockUtil.getDistanceSq(pos))); // sort by y so we start placing from bottom up. positions.sort(Comparator.comparingInt(Vec3i::getY)); return positions.stream().filter(pos -> BlockUtil.getDistanceSq(pos) <= MathUtil.square(range.getValue())) .collect(Collectors.toList()); } /** * Creates trapping positions * from a list of positions that * are blocked by a player. * * @param blockedIn the positions to trap. * @return trapping positions. */ private List<BlockPos> positionsFromBlocked(List<BlockPos> blockedIn) { List<BlockPos> positions = new ArrayList<>(); if (!noStep.getValue() && !blockedIn.isEmpty()) { BlockPos[] helping = findTopHelping(blockedIn, true); for (int i = 0; i < helping.length; i++) { BlockPos pos = helping[i]; if (pos != null) { if (i == 1 && !upperBody.getValue() && (!blockedIn.contains(PositionUtil .getPosition() .up()) || !upperFace.getValue()) && helping[5] != null) { positions.add(helping[5]); } positions.add(helping[i]); break; } } } boolean scaffold = noScaffold.getValue(); if (top.getValue()) { blockedIn.forEach(pos -> positions.addAll(applyOffsets(pos, Trap.TOP, positions))); } else if (blockedIn.size() == 1 && smartTop.getValue() && scaffold && mc.world.getBlockState(blockedIn.get(0) .add(Trap.TOP[0])) .getMaterial() .isReplaceable() && mc.world.getBlockState(blockedIn.get(0) .add(Trap.NO_SCAFFOLD[0])) .getMaterial() .isReplaceable() && mc.world.getBlockState(blockedIn.get(0) .add(Trap.NO_SCAFFOLD_P[0])) .getMaterial() .isReplaceable()) { blockedIn.forEach(pos -> positions.addAll(applyOffsets(pos, Trap.TOP, positions))); if (noScaffoldPlus.getValue()) { blockedIn.forEach(pos -> positions.addAll( applyOffsets(pos, Trap.NO_SCAFFOLD_P, positions))); } scaffold = false; blockedIn.forEach(pos -> positions.addAll( applyOffsets(pos, Trap.NO_SCAFFOLD, positions))); } if (upperBody.getValue() || upperFace.getValue() && blockedIn.contains(PositionUtil.getPosition().up())) { blockedIn.forEach(pos -> positions.addAll(applyOffsets(pos, Trap.OFFSETS, positions))); } // Only apply these if we dont need to extend, otherwise overkill if (blockedIn.size() == 1 || bigExtend.getValue()) { if (scaffold) { blockedIn.forEach(pos -> positions.addAll( applyOffsets(pos, Trap.NO_SCAFFOLD, positions))); } if (noStep.getValue()) { blockedIn.forEach(pos -> positions.addAll( applyOffsets(pos, Trap.NO_STEP, positions))); } if (legs.getValue()) { blockedIn.forEach(pos -> positions.addAll( applyOffsets(pos, Trap.LEGS, positions))); } if (platform.getValue()) { blockedIn.forEach(pos -> positions.addAll( applyOffsets(pos, Trap.PLATFORM, positions))); } if (noDrop.getValue()) { blockedIn.forEach(pos -> positions.addAll( applyOffsets(pos, Trap.NO_DROP, positions))); } } return positions; } /** * Finds helping blocks for the top pos. * Returns an Array with possible helping Positions. * The Indices work this way: * 0 : has a facing and no entities, * 1 : no facing no entities, * 2 : has a facing but entities, * 3 : no facing, entities blocking * 4 : random pos when everything is shit. * 5 : A helping Pos for index 1. * * @param positions positions to find a helpingPos for. (not empty!) * @param first used for recursion should always be <tt>true</tt>. * @return possible helping positions. */ private BlockPos[] findTopHelping(List<BlockPos> positions, boolean first) { BlockPos[] bestPos = new BlockPos[] { null, null, null, null, positions.get(0).up().north(), null }; for (BlockPos pos : positions) { BlockPos up = pos.up(); //TODO: Sort facings so that we dont block piston aura for (EnumFacing facing : TOP_FACINGS) { BlockPos helping = up.offset(facing); // return instantly, no helping needed if (!mc.world .getBlockState(helping) .getMaterial() .isReplaceable()) { bestPos[0] = helping; return bestPos; } EnumFacing helpingFace = BlockUtil.getFacing(helping, HELPER); byte blockingFactor = helpingEntityCheck(helping); if (helpingFace == null) { switch (blockingFactor) { case 0: if (first && bestPos[5] == null) { List<BlockPos> hPositions = new ArrayList<>(); for (BlockPos hPos : positions) { // won't check up up helping I think hPositions.add(hPos.down()); } bestPos[5] = findTopHelping(hPositions, false)[0]; } else { break; } bestPos[1] = helping; break; case 1: bestPos[3] = helping; break; case 2: break; } } else { switch (blockingFactor) { case 0: bestPos[0] = helping; break; case 1: bestPos[2] = helping; break; case 2: break; } } } } return bestPos; } /** * EntityCheck for the helping position. * * @param pos the position to check. * @return 0 if free of entities, 1 if crystal, 2 if blocking. */ private byte helpingEntityCheck(BlockPos pos) { byte blocking = 0; for (Entity entity : mc.world .getEntitiesWithinAABB(Entity.class, new AxisAlignedBB(pos))) { if (entity == null || EntityUtil.isDead(entity) || !entity.preventEntitySpawning || (entity instanceof EntityPlayer && !BlockUtil.isBlocking(pos, (EntityPlayer) entity, blockingType.getValue()))) { continue; } if (entity instanceof EntityEnderCrystal && attack.getValue()) { float damage = DamageUtil.calculate(entity, mc.player); if (damage <= EntityUtil.getHealth(mc.player) + 1.0) { blocking = 1; continue; } } return 2; } return blocking; } /** * Applies the given offsets to the position and * returns a list that doesnt contain any positions * already contained by alreadyAdded. * * @param pos the pos to apply the offsets to. * @param offsets the offsets. * @param alreadyAdded list to prevent duplicates. * @return offsets for the position. */ private List<BlockPos> applyOffsets(BlockPos pos, Vec3i[] offsets, List<BlockPos> alreadyAdded) { List<BlockPos> positions = new ArrayList<>(); for (Vec3i vec3i : offsets) { BlockPos offset = pos.add(vec3i); if (!alreadyAdded.contains(offset)) { positions.add(offset); } } return positions; } }
0
0.95042
1
0.95042
game-dev
MEDIA
0.974419
game-dev
0.973328
1
0.973328
Akarin-project/Akarin
21,259
sources/src/main/java/net/minecraft/server/PlayerChunkMap.java
package net.minecraft.server; import co.aikar.timings.Timing; import com.google.common.base.Predicate; import com.google.common.collect.AbstractIterator; import com.google.common.collect.ComparisonChain; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import it.unimi.dsi.fastutil.longs.Long2ObjectMap; import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.ReentrantReadWriteLock; import javax.annotation.Nullable; import javax.annotation.concurrent.ThreadSafe; // CraftBukkit start import java.util.LinkedList; // CraftBukkit end /** * Akarin Changes Note * 1) Make whole class thread-safe (safety issue) */ @ThreadSafe // Akarin - idk why we need do so!! public class PlayerChunkMap { private static final Predicate<EntityPlayer> a = new Predicate() { public boolean a(@Nullable EntityPlayer entityplayer) { return entityplayer != null && !entityplayer.isSpectator(); } public boolean apply(@Nullable Object object) { return this.a((EntityPlayer) object); } }; private static final Predicate<EntityPlayer> b = new Predicate() { public boolean a(@Nullable EntityPlayer entityplayer) { return entityplayer != null && (!entityplayer.isSpectator() || entityplayer.x().getGameRules().getBoolean("spectatorsGenerateChunks")); } public boolean apply(@Nullable Object object) { return this.a((EntityPlayer) object); } }; private final WorldServer world; private final List<EntityPlayer> managedPlayers = Lists.newArrayList(); private final ReentrantReadWriteLock managedPlayersLock = new ReentrantReadWriteLock(); // Akarin - add lock private final Long2ObjectMap<PlayerChunk> e = new Long2ObjectOpenHashMap(4096); private final Set<PlayerChunk> f = Sets.newHashSet(); private final List<PlayerChunk> g = Lists.newLinkedList(); private final List<PlayerChunk> h = Lists.newLinkedList(); private final List<PlayerChunk> i = Lists.newCopyOnWriteArrayList(); // Akarin - bad plugin will access this private int j; public int getViewDistance() { return j; } // Paper OBFHELPER private long k; private boolean l = true; private boolean m = true; private boolean wasNotEmpty; // CraftBukkit - add field public PlayerChunkMap(WorldServer worldserver) { this.world = worldserver; this.a(worldserver.spigotConfig.viewDistance); // Spigot } public WorldServer getWorld() { return this.world; } public Iterator<Chunk> b() { final Iterator iterator = this.i.iterator(); return new AbstractIterator<Chunk>() { protected Chunk a() { while (true) { if (iterator.hasNext()) { PlayerChunk playerchunk = (PlayerChunk) iterator.next(); Chunk chunk = playerchunk.f(); if (chunk == null) { continue; } if (!chunk.v() && chunk.isDone()) { return chunk; } if (!chunk.j()) { return chunk; } if (!playerchunk.a(128.0D, PlayerChunkMap.a)) { continue; } return chunk; } return (Chunk) this.endOfData(); } } protected Chunk computeNext() { return this.a(); } }; } public synchronized void flush() { // Akarin - synchronized long i = this.world.getTime(); int j; PlayerChunk playerchunk; if (i - this.k > 8000L) { try (Timing ignored = world.timings.doChunkMapUpdate.startTiming()) { // Paper this.k = i; for (j = 0; j < this.i.size(); ++j) { playerchunk = (PlayerChunk) this.i.get(j); playerchunk.d(); playerchunk.c(); } } // Paper timing } if (!this.f.isEmpty()) { try (Timing ignored = world.timings.doChunkMapToUpdate.startTiming()) { // Paper Iterator iterator = this.f.iterator(); while (iterator.hasNext()) { playerchunk = (PlayerChunk) iterator.next(); playerchunk.d(); } this.f.clear(); } // Paper timing } if (this.l && i % 4L == 0L) { this.l = false; try (Timing ignored = world.timings.doChunkMapSortMissing.startTiming()) { // Paper Collections.sort(this.h, new Comparator() { public int a(PlayerChunk playerchunk, PlayerChunk playerchunk1) { return ComparisonChain.start().compare(playerchunk.g(), playerchunk1.g()).result(); } public int compare(Object object, Object object1) { return this.a((PlayerChunk) object, (PlayerChunk) object1); } }); } // Paper timing } if (this.m && i % 4L == 2L) { this.m = false; try (Timing ignored = world.timings.doChunkMapSortSendToPlayers.startTiming()) { // Paper Collections.sort(this.g, new Comparator() { public int a(PlayerChunk playerchunk, PlayerChunk playerchunk1) { return ComparisonChain.start().compare(playerchunk.g(), playerchunk1.g()).result(); } public int compare(Object object, Object object1) { return this.a((PlayerChunk) object, (PlayerChunk) object1); } }); } // Paper timing } if (!this.h.isEmpty()) { try (Timing ignored = world.timings.doChunkMapPlayersNeedingChunks.startTiming()) { // Paper // Spigot start org.spigotmc.SlackActivityAccountant activityAccountant = this.world.getMinecraftServer().slackActivityAccountant; activityAccountant.startActivity(0.5); int chunkGensAllowed = world.paperConfig.maxChunkGensPerTick; // Paper // Spigot end Iterator iterator1 = this.h.iterator(); while (iterator1.hasNext()) { PlayerChunk playerchunk1 = (PlayerChunk) iterator1.next(); if (playerchunk1.f() == null) { boolean flag = playerchunk1.a(PlayerChunkMap.b); // Paper start if (flag && !playerchunk1.chunkExists && chunkGensAllowed-- <= 0) { continue; } // Paper end if (playerchunk1.a(flag)) { iterator1.remove(); if (playerchunk1.b()) { this.g.remove(playerchunk1); } if (activityAccountant.activityTimeIsExhausted()) { // Spigot break; } } // CraftBukkit start - SPIGOT-2891: remove once chunk has been provided } else { iterator1.remove(); } // CraftBukkit end } activityAccountant.endActivity(); // Spigot } // Paper timing } if (!this.g.isEmpty()) { j = world.paperConfig.maxChunkSendsPerTick; // Paper try (Timing ignored = world.timings.doChunkMapPendingSendToPlayers.startTiming()) { // Paper Iterator iterator2 = this.g.iterator(); while (iterator2.hasNext()) { PlayerChunk playerchunk2 = (PlayerChunk) iterator2.next(); if (playerchunk2.b()) { iterator2.remove(); --j; if (j < 0) { break; } } } } // Paper timing } managedPlayersLock.readLock().lock(); // Akarin if (this.managedPlayers.isEmpty()) { try (Timing ignored = world.timings.doChunkMapUnloadChunks.startTiming()) { // Paper WorldProvider worldprovider = this.world.worldProvider; if (!worldprovider.e() && !this.world.savingDisabled) { // Paper - respect saving disabled setting this.world.getChunkProviderServer().b(); } } // Paper timing } managedPlayersLock.readLock().unlock(); // Akarin } public synchronized boolean a(int i, int j) { // Akarin - synchronized long k = d(i, j); return this.e.get(k) != null; } @Nullable public synchronized PlayerChunk getChunk(int i, int j) { // Akarin - synchronized return (PlayerChunk) this.e.get(d(i, j)); } private PlayerChunk c(int i, int j) { long k = d(i, j); PlayerChunk playerchunk = (PlayerChunk) this.e.get(k); if (playerchunk == null) { playerchunk = new PlayerChunk(this, i, j); this.e.put(k, playerchunk); this.i.add(playerchunk); if (playerchunk.f() == null) { this.h.add(playerchunk); } if (!playerchunk.b()) { this.g.add(playerchunk); } } return playerchunk; } // CraftBukkit start - add method public final boolean isChunkInUse(int x, int z) { PlayerChunk pi = getChunk(x, z); if (pi != null) { return (pi.c.size() > 0); } return false; } // CraftBukkit end public void flagDirty(BlockPosition blockposition) { int i = blockposition.getX() >> 4; int j = blockposition.getZ() >> 4; PlayerChunk playerchunk = this.getChunk(i, j); if (playerchunk != null) { playerchunk.a(blockposition.getX() & 15, blockposition.getY(), blockposition.getZ() & 15); } } public void addPlayer(EntityPlayer entityplayer) { int i = (int) entityplayer.locX >> 4; int j = (int) entityplayer.locZ >> 4; entityplayer.d = entityplayer.locX; entityplayer.e = entityplayer.locZ; // CraftBukkit start - Load nearby chunks first List<ChunkCoordIntPair> chunkList = new LinkedList<ChunkCoordIntPair>(); // Paper start - Player view distance API int viewDistance = entityplayer.getViewDistance(); for (int k = i - viewDistance; k <= i + viewDistance; ++k) { for (int l = j - viewDistance; l <= j + viewDistance; ++l) { // Paper end chunkList.add(new ChunkCoordIntPair(k, l)); } } Collections.sort(chunkList, new ChunkCoordComparator(entityplayer)); synchronized (this) { // Akarin - synchronized for (ChunkCoordIntPair pair : chunkList) { this.c(pair.x, pair.z).a(entityplayer); } } // Akarin // CraftBukkit end managedPlayersLock.writeLock().lock(); // Akarin this.managedPlayers.add(entityplayer); managedPlayersLock.writeLock().unlock(); // Akarin this.e(); } public void removePlayer(EntityPlayer entityplayer) { int i = (int) entityplayer.d >> 4; int j = (int) entityplayer.e >> 4; // Paper start - Player view distance API int viewDistance = entityplayer.getViewDistance(); for (int k = i - viewDistance; k <= i + viewDistance; ++k) { for (int l = j - viewDistance; l <= j + viewDistance; ++l) { // Paper end PlayerChunk playerchunk = this.getChunk(k, l); if (playerchunk != null) { playerchunk.b(entityplayer); } } } managedPlayersLock.writeLock().lock(); // Akarin this.managedPlayers.remove(entityplayer); managedPlayersLock.writeLock().unlock(); // Akarin this.e(); } private boolean a(int i, int j, int k, int l, int i1) { int j1 = i - k; int k1 = j - l; return j1 >= -i1 && j1 <= i1 ? k1 >= -i1 && k1 <= i1 : false; } public void movePlayer(EntityPlayer entityplayer) { int i = (int) entityplayer.locX >> 4; int j = (int) entityplayer.locZ >> 4; double d0 = entityplayer.d - entityplayer.locX; double d1 = entityplayer.e - entityplayer.locZ; double d2 = d0 * d0 + d1 * d1; if (d2 >= 64.0D) { int k = (int) entityplayer.d >> 4; int l = (int) entityplayer.e >> 4; final int viewDistance = entityplayer.getViewDistance(); // Paper - Player view distance API int i1 = Math.max(getViewDistance(), viewDistance); // Paper - Player view distance API int j1 = i - k; int k1 = j - l; List<ChunkCoordIntPair> chunksToLoad = new LinkedList<ChunkCoordIntPair>(); // CraftBukkit if (j1 != 0 || k1 != 0) { for (int l1 = i - i1; l1 <= i + i1; ++l1) { for (int i2 = j - i1; i2 <= j + i1; ++i2) { if (!this.a(l1, i2, k, l, viewDistance)) { // Paper - Player view distance API // this.c(l1, i2).a(entityplayer); chunksToLoad.add(new ChunkCoordIntPair(l1, i2)); // CraftBukkit } if (!this.a(l1 - j1, i2 - k1, i, j, i1)) { PlayerChunk playerchunk = this.getChunk(l1 - j1, i2 - k1); if (playerchunk != null) { playerchunk.b(entityplayer); } } } } entityplayer.d = entityplayer.locX; entityplayer.e = entityplayer.locZ; this.e(); // CraftBukkit start - send nearest chunks first Collections.sort(chunksToLoad, new ChunkCoordComparator(entityplayer)); synchronized (this) { // Akarin - synchronized for (ChunkCoordIntPair pair : chunksToLoad) { this.c(pair.x, pair.z).a(entityplayer); } } // Akarin // CraftBukkit end } } } public boolean a(EntityPlayer entityplayer, int i, int j) { PlayerChunk playerchunk = this.getChunk(i, j); return playerchunk != null && playerchunk.d(entityplayer) && playerchunk.e(); } public final void setViewDistanceForAll(int viewDistance) { this.a(viewDistance); } // Paper - OBFHELPER // Paper start - Separate into two methods public void a(int i) { i = MathHelper.clamp(i, 3, 32); if (i != this.j) { int j = i - this.j; managedPlayersLock.readLock().lock(); // Akarin ArrayList arraylist = Lists.newArrayList(this.managedPlayers); managedPlayersLock.readLock().unlock(); // Akarin Iterator iterator = arraylist.iterator(); while (iterator.hasNext()) { EntityPlayer entityplayer = (EntityPlayer) iterator.next(); this.setViewDistance(entityplayer, i, false); // Paper - Split, don't mark sort pending, we'll handle it after } this.j = i; this.e(); } } public void setViewDistance(EntityPlayer entityplayer, int i) { this.setViewDistance(entityplayer, i, true); // Mark sort pending by default so we don't have to remember to do so all the time } // Copied from above with minor changes public void setViewDistance(EntityPlayer entityplayer, int i, boolean markSort) { i = MathHelper.clamp(i, 3, 32); int oldViewDistance = entityplayer.getViewDistance(); if (i != oldViewDistance) { int j = i - oldViewDistance; int k = (int) entityplayer.locX >> 4; int l = (int) entityplayer.locZ >> 4; int i1; int j1; if (j > 0) { synchronized (this) { // Akarin - synchronized for (i1 = k - i; i1 <= k + i; ++i1) { for (j1 = l - i; j1 <= l + i; ++j1) { PlayerChunk playerchunk = this.c(i1, j1); if (!playerchunk.d(entityplayer)) { playerchunk.a(entityplayer); } } } } // Akarin } else { synchronized (this) { // Akarin - synchronized for (i1 = k - oldViewDistance; i1 <= k + oldViewDistance; ++i1) { for (j1 = l - oldViewDistance; j1 <= l + oldViewDistance; ++j1) { if (!this.a(i1, j1, k, l, i)) { this.c(i1, j1).b(entityplayer); } } } } // Akarin if (markSort) { this.e(); } } } } // Paper end private void e() { this.l = true; this.m = true; } public static int getFurthestViewableBlock(int i) { return i * 16 - 16; } private static long d(int i, int j) { return (long) i + 2147483647L | (long) j + 2147483647L << 32; } public synchronized void a(PlayerChunk playerchunk) { // Akarin - synchronized // org.spigotmc.AsyncCatcher.catchOp("Async Player Chunk Add"); // Paper // Akarin this.f.add(playerchunk); } public synchronized void b(PlayerChunk playerchunk) { // Akarin - synchronized org.spigotmc.AsyncCatcher.catchOp("Async Player Chunk Remove"); // Paper ChunkCoordIntPair chunkcoordintpair = playerchunk.a(); long i = d(chunkcoordintpair.x, chunkcoordintpair.z); playerchunk.c(); this.e.remove(i); this.i.remove(playerchunk); this.f.remove(playerchunk); this.g.remove(playerchunk); this.h.remove(playerchunk); Chunk chunk = playerchunk.f(); if (chunk != null) { // Paper start - delay chunk unloads if (world.paperConfig.delayChunkUnloadsBy <= 0) { this.getWorld().getChunkProviderServer().unload(chunk); } else { chunk.scheduledForUnload = System.currentTimeMillis(); } // Paper end } } // CraftBukkit start - Sorter to load nearby chunks first private static class ChunkCoordComparator implements java.util.Comparator<ChunkCoordIntPair> { private int x; private int z; public ChunkCoordComparator (EntityPlayer entityplayer) { x = (int) entityplayer.locX >> 4; z = (int) entityplayer.locZ >> 4; } public int compare(ChunkCoordIntPair a, ChunkCoordIntPair b) { if (a.equals(b)) { return 0; } // Subtract current position to set center point int ax = a.x - this.x; int az = a.z - this.z; int bx = b.x - this.x; int bz = b.z - this.z; int result = ((ax - bx) * (ax + bx)) + ((az - bz) * (az + bz)); if (result != 0) { return result; } if (ax < 0) { if (bx < 0) { return bz - az; } else { return -1; } } else { if (bx < 0) { return 1; } else { return az - bz; } } } } // CraftBukkit end // Paper start - Player view distance API public void updateViewDistance(EntityPlayer player, int distanceIn) { final int oldViewDistance = player.getViewDistance(); // This represents the view distance that we will set on the player // It can exist as a negative value int playerViewDistance = MathHelper.clamp(distanceIn, 3, 32); // This value is the one we actually use to update the chunk map // We don't ever want this to be a negative int toSet = playerViewDistance; if (distanceIn < 0) { playerViewDistance = -1; toSet = world.getPlayerChunkMap().getViewDistance(); } if (toSet != oldViewDistance) { // Order matters this.setViewDistance(player, toSet); player.setViewDistance(playerViewDistance); } } // Paper end }
0
0.800197
1
0.800197
game-dev
MEDIA
0.889965
game-dev
0.929565
1
0.929565
FriskTheFallenHuman/Prey2006
53,892
neo/game/script/Script_Program.cpp
/* =========================================================================== Doom 3 GPL Source Code Copyright (C) 1999-2011 id Software LLC, a ZeniMax Media company. This file is part of the Doom 3 GPL Source Code ("Doom 3 Source Code"). Doom 3 Source Code is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Doom 3 Source Code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Doom 3 Source Code. If not, see <http://www.gnu.org/licenses/>. In addition, the Doom 3 Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 Source Code. If not, please request a copy in writing from id Software at the address below. If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA. =========================================================================== */ #include "precompiled.h" #pragma hdrstop #include "../Game_local.h" //#define _HH_GLOBAL_COUNTER //HUMANHEAD rww #ifdef _HH_GLOBAL_COUNTER //HUMANHEAD rww static idFile *globalOutputFile = NULL; static int globalOutputUnique = 0; static int globalOutputRunningSize = 0; #endif //HUMANHEAD END // simple types. function types are dynamically allocated idTypeDef type_void( ev_void, &def_void, "void", 0, NULL ); idTypeDef type_scriptevent( ev_scriptevent, &def_scriptevent, "scriptevent", sizeof( intptr_t ), NULL ); idTypeDef type_namespace( ev_namespace, &def_namespace, "namespace", sizeof( intptr_t ), NULL ); //HUMANHEAD: aob - changed types to inherited types idTypeDefString type_string( ev_string, &def_string, "string", MAX_STRING_LEN, NULL ); idTypeDefFloat type_float( ev_float, &def_float, "float", sizeof( intptr_t ), NULL ); idTypeDefVector type_vector( ev_vector, &def_vector, "vector", E_EVENT_SIZEOF_VEC, NULL ); idTypeDefEntity type_entity( ev_entity, &def_entity, "entity", sizeof( intptr_t ), NULL ); // stored as entity number pointer //HUMANHEAD END idTypeDef type_field( ev_field, &def_field, "field", sizeof( intptr_t ), NULL ); idTypeDef type_function( ev_function, &def_function, "function", sizeof( intptr_t ), &type_void ); idTypeDef type_virtualfunction( ev_virtualfunction, &def_virtualfunction, "virtual function", sizeof( intptr_t ), NULL ); idTypeDef type_pointer( ev_pointer, &def_pointer, "pointer", sizeof( intptr_t ), NULL ); idTypeDef type_object( ev_object, &def_object, "object", sizeof( intptr_t ), NULL ); // stored as entity number pointer idTypeDef type_jumpoffset( ev_jumpoffset, &def_jumpoffset, "<jump>", sizeof( intptr_t ), NULL ); // only used for jump opcodes idTypeDef type_argsize( ev_argsize, &def_argsize, "<argsize>", sizeof( intptr_t ), NULL ); // only used for function call and thread opcodes //HUMANHEAD: aob - changed types to inherited types idTypeDefBool type_boolean( ev_boolean, &def_boolean, "boolean", sizeof( intptr_t ), NULL ); //HUMANHEAD END idVarDef def_void( &type_void ); idVarDef def_scriptevent( &type_scriptevent ); idVarDef def_namespace( &type_namespace ); idVarDef def_string( &type_string ); idVarDef def_float( &type_float ); idVarDef def_vector( &type_vector ); idVarDef def_entity( &type_entity ); idVarDef def_field( &type_field ); idVarDef def_function( &type_function ); idVarDef def_virtualfunction( &type_virtualfunction ); idVarDef def_pointer( &type_pointer ); idVarDef def_object( &type_object ); idVarDef def_jumpoffset( &type_jumpoffset ); // only used for jump opcodes idVarDef def_argsize( &type_argsize ); idVarDef def_boolean( &type_boolean ); /*********************************************************************** function_t ***********************************************************************/ /* ================ function_t::function_t ================ */ function_t::function_t() { Clear(); } /* ================ function_t::Allocated ================ */ size_t function_t::Allocated( void ) const { return name.Allocated() + parmSize.Allocated(); } /* ================ function_t::SetName ================ */ void function_t::SetName( const char *name ) { this->name = name; } /* ================ function_t::Name ================ */ const char *function_t::Name( void ) const { return name; } /* ================ function_t::Clear ================ */ void function_t::Clear( void ) { eventdef = NULL; def = NULL; type = NULL; firstStatement = 0; numStatements = 0; parmTotal = 0; locals = 0; filenum = 0; name.Clear(); parmSize.Clear(); } /*********************************************************************** idTypeDef ***********************************************************************/ /* ================ idTypeDef::idTypeDef ================ */ idTypeDef::idTypeDef( etype_t etype, idVarDef *edef, const char *ename, int esize, idTypeDef *aux ) { name = ename; type = etype; def = edef; size = esize; auxType = aux; parmTypes.SetGranularity( 1 ); parmNames.SetGranularity( 1 ); functions.SetGranularity( 1 ); } /* ================ idTypeDef::idTypeDef ================ */ idTypeDef::idTypeDef( const idTypeDef &other ) { *this = other; } /* ================ idTypeDef::operator= ================ */ void idTypeDef::operator=( const idTypeDef& other ) { type = other.type; def = other.def; name = other.name; size = other.size; auxType = other.auxType; parmTypes = other.parmTypes; parmNames = other.parmNames; functions = other.functions; } /* ================ idTypeDef::Allocated ================ */ size_t idTypeDef::Allocated( void ) const { size_t memsize; int i; memsize = name.Allocated() + parmTypes.Allocated() + parmNames.Allocated() + functions.Allocated(); for( i = 0; i < parmTypes.Num(); i++ ) { memsize += parmNames[ i ].Allocated(); } return memsize; } /* ================ idTypeDef::Inherits Returns true if basetype is an ancestor of this type. ================ */ bool idTypeDef::Inherits( const idTypeDef *basetype ) const { idTypeDef *superType; if ( type != ev_object ) { return false; } if ( this == basetype ) { return true; } for( superType = auxType; superType != NULL; superType = superType->auxType ) { if ( superType == basetype ) { return true; } } return false; } /* ================ idTypeDef::MatchesType Returns true if both types' base types and parameters match ================ */ bool idTypeDef::MatchesType( const idTypeDef &matchtype ) const { int i; if ( this == &matchtype ) { return true; } if ( ( type != matchtype.type ) || ( auxType != matchtype.auxType ) ) { return false; } if ( parmTypes.Num() != matchtype.parmTypes.Num() ) { return false; } for( i = 0; i < matchtype.parmTypes.Num(); i++ ) { if ( parmTypes[ i ] != matchtype.parmTypes[ i ] ) { return false; } } return true; } /* ================ idTypeDef::MatchesVirtualFunction Returns true if both functions' base types and parameters match ================ */ bool idTypeDef::MatchesVirtualFunction( const idTypeDef &matchfunc ) const { int i; if ( this == &matchfunc ) { return true; } if ( ( type != matchfunc.type ) || ( auxType != matchfunc.auxType ) ) { return false; } if ( parmTypes.Num() != matchfunc.parmTypes.Num() ) { return false; } if ( parmTypes.Num() > 0 ) { if ( !parmTypes[ 0 ]->Inherits( matchfunc.parmTypes[ 0 ] ) ) { return false; } } for( i = 1; i < matchfunc.parmTypes.Num(); i++ ) { if ( parmTypes[ i ] != matchfunc.parmTypes[ i ] ) { return false; } } return true; } /* ================ idTypeDef::AddFunctionParm Adds a new parameter for a function type. ================ */ void idTypeDef::AddFunctionParm( idTypeDef *parmtype, const char *name ) { if ( type != ev_function ) { throw idCompileError( "idTypeDef::AddFunctionParm : tried to add parameter on non-function type" ); } parmTypes.Append( parmtype ); idStr &parmName = parmNames.Alloc(); parmName = name; } /* ================ idTypeDef::AddField Adds a new field to an object type. ================ */ void idTypeDef::AddField( idTypeDef *fieldtype, const char *name ) { if ( type != ev_object ) { throw idCompileError( "idTypeDef::AddField : tried to add field to non-object type" ); } parmTypes.Append( fieldtype ); idStr &parmName = parmNames.Alloc(); parmName = name; if ( fieldtype->FieldType()->Inherits( &type_object ) ) { size += type_object.Size(); } else { size += fieldtype->FieldType()->Size(); } } /* ================ idTypeDef::SetName ================ */ void idTypeDef::SetName( const char *newname ) { name = newname; } /* ================ idTypeDef::Name ================ */ const char *idTypeDef::Name( void ) const { return name; } /* ================ idTypeDef::Type ================ */ etype_t idTypeDef::Type( void ) const { return type; } /* ================ idTypeDef::Size ================ */ int idTypeDef::Size( void ) const { return size; } /* ================ idTypeDef::SuperClass If type is an object, then returns the object's superclass ================ */ idTypeDef *idTypeDef::SuperClass( void ) const { if ( type != ev_object ) { throw idCompileError( "idTypeDef::SuperClass : tried to get superclass of a non-object type" ); } return auxType; } /* ================ idTypeDef::ReturnType If type is a function, then returns the function's return type ================ */ idTypeDef *idTypeDef::ReturnType( void ) const { if ( type != ev_function ) { throw idCompileError( "idTypeDef::ReturnType: tried to get return type on non-function type" ); } return auxType; } /* ================ idTypeDef::SetReturnType If type is a function, then sets the function's return type ================ */ void idTypeDef::SetReturnType( idTypeDef *returntype ) { if ( type != ev_function ) { throw idCompileError( "idTypeDef::SetReturnType: tried to set return type on non-function type" ); } auxType = returntype; } /* ================ idTypeDef::FieldType If type is a field, then returns it's type ================ */ idTypeDef *idTypeDef::FieldType( void ) const { if ( type != ev_field ) { throw idCompileError( "idTypeDef::FieldType: tried to get field type on non-field type" ); } return auxType; } /* ================ idTypeDef::SetFieldType If type is a field, then sets the function's return type ================ */ void idTypeDef::SetFieldType( idTypeDef *fieldtype ) { if ( type != ev_field ) { throw idCompileError( "idTypeDef::SetFieldType: tried to set return type on non-function type" ); } auxType = fieldtype; } /* ================ idTypeDef::PointerType If type is a pointer, then returns the type it points to ================ */ idTypeDef *idTypeDef::PointerType( void ) const { if ( type != ev_pointer ) { throw idCompileError( "idTypeDef::PointerType: tried to get pointer type on non-pointer" ); } return auxType; } /* ================ idTypeDef::SetPointerType If type is a pointer, then sets the pointer's type ================ */ void idTypeDef::SetPointerType( idTypeDef *pointertype ) { if ( type != ev_pointer ) { throw idCompileError( "idTypeDef::SetPointerType: tried to set type on non-pointer" ); } auxType = pointertype; } /* ================ idTypeDef::NumParameters ================ */ int idTypeDef::NumParameters( void ) const { return parmTypes.Num(); } /* ================ idTypeDef::GetParmType ================ */ idTypeDef *idTypeDef::GetParmType( int parmNumber ) const { assert( parmNumber >= 0 ); assert( parmNumber < parmTypes.Num() ); return parmTypes[ parmNumber ]; } /* ================ idTypeDef::GetParmName ================ */ const char *idTypeDef::GetParmName( int parmNumber ) const { assert( parmNumber >= 0 ); assert( parmNumber < parmTypes.Num() ); return parmNames[ parmNumber ]; } /* ================ idTypeDef::NumFunctions ================ */ int idTypeDef::NumFunctions( void ) const { return functions.Num(); } /* ================ idTypeDef::GetFunctionNumber ================ */ int idTypeDef::GetFunctionNumber( const function_t *func ) const { int i; for( i = 0; i < functions.Num(); i++ ) { if ( functions[ i ] == func ) { return i; } } return -1; } /* ================ idTypeDef::GetFunction ================ */ const function_t *idTypeDef::GetFunction( int funcNumber ) const { assert( funcNumber >= 0 ); assert( funcNumber < functions.Num() ); return functions[ funcNumber ]; } /* ================ idTypeDef::AddFunction ================ */ void idTypeDef::AddFunction( const function_t *func ) { int i; for( i = 0; i < functions.Num(); i++ ) { if ( !strcmp( functions[ i ]->def->Name(), func->def->Name() ) ) { if ( func->def->TypeDef()->MatchesVirtualFunction( *functions[ i ]->def->TypeDef() ) ) { functions[ i ] = func; return; } } } functions.Append( func ); } //HUMANHEAD: aob idTypeDefString::idTypeDefString( const idTypeDef &other ) : idTypeDef( other ) {} idTypeDefString::idTypeDefString( etype_t etype, idVarDef *edef, const char *ename, int esize, idTypeDef *aux ) : idTypeDef( etype, edef, ename, esize, aux ) {} void idTypeDefString::PushOntoStack( const char* parm, hhThread* thread ) const { thread->PushString( parm ); } const char* idTypeDefString::GetReturnValueAsString( idProgram& program ) const { return program.GetReturnedString(); } bool idTypeDefString::VerifyData( const char* data ) const { return true; } idTypeDefVector::idTypeDefVector( const idTypeDef &other ) : idTypeDef( other ) {} idTypeDefVector::idTypeDefVector( etype_t etype, idVarDef *edef, const char *ename, int esize, idTypeDef *aux ) : idTypeDef( etype, edef, ename, esize, aux ) {} void idTypeDefVector::PushOntoStack( const char* parm, hhThread* thread ) const { idVec3 vec; sscanf( parm, "%f %f %f", &vec.x, &vec.y, &vec.z ); thread->PushVector( vec ); } const char* idTypeDefVector::GetReturnValueAsString( idProgram& program ) const { return program.GetReturnedVector().ToString(); } bool idTypeDefVector::VerifyData( const char* data ) const { int strLen = idStr::Length( data ); return strLen == 5;//FIXME: Need something better } idTypeDefFloat::idTypeDefFloat( const idTypeDef &other ) : idTypeDef( other ) {} idTypeDefFloat::idTypeDefFloat( etype_t etype, idVarDef *edef, const char *ename, int esize, idTypeDef *aux ) : idTypeDef( etype, edef, ename, esize, aux ) {} void idTypeDefFloat::PushOntoStack( const char* parm, hhThread* thread ) const { float f = 0.0f; sscanf( parm, "%.2f", &f ); thread->PushFloat( f ); } const char* idTypeDefFloat::GetReturnValueAsString( idProgram& program ) const { return va( "%.2f", program.GetReturnedFloat() ); } bool idTypeDefFloat::VerifyData( const char* data ) const { if( idStr::IsNumeric(data) ) { return false; } return true; } idTypeDefEntity::idTypeDefEntity( const idTypeDef &other ) : idTypeDef( other ) {} idTypeDefEntity::idTypeDefEntity( etype_t etype, idVarDef *edef, const char *ename, int esize, idTypeDef *aux ) : idTypeDef( etype, edef, ename, esize, aux ) {} void idTypeDefEntity::PushOntoStack( const char* parm, hhThread* thread ) const { idEntity* ent = gameLocal.FindEntity( parm ); thread->PushEntity( ent ); } const char* idTypeDefEntity::GetReturnValueAsString( idProgram& program ) const { return program.GetReturnedString(); } bool idTypeDefEntity::VerifyData( const char* data ) const { return gameLocal.FindEntity( data ) != NULL; } idTypeDefBool::idTypeDefBool( const idTypeDef &other ) : idTypeDef( other ) {} idTypeDefBool::idTypeDefBool( etype_t etype, idVarDef *edef, const char *ename, int esize, idTypeDef *aux ) : idTypeDef( etype, edef, ename, esize, aux ) {} void idTypeDefBool::PushOntoStack( const char* parm, hhThread* thread ) const { bool b = false; sscanf( parm, "%d", &b ); thread->PushInt( (int)b ); } const char* idTypeDefBool::GetReturnValueAsString( idProgram& program ) const { return va( "%d", program.GetReturnedBool() ); }; bool idTypeDefBool::VerifyData( const char* data ) const { idStr localData( data ); return !localData.Icmp("1") || !localData.Icmp("0") || !localData.Icmp("true") || !localData.Icmp("false"); } //HUMANHEAD END /*********************************************************************** idVarDef ***********************************************************************/ /* ================ idVarDef::idVarDef() ================ */ idVarDef::idVarDef( idTypeDef *typeptr ) { typeDef = typeptr; num = 0; scope = NULL; numUsers = 0; initialized = idVarDef::uninitialized; memset( &value, 0, sizeof( value ) ); name = NULL; next = NULL; } /* ============ idVarDef::~idVarDef ============ */ idVarDef::~idVarDef() { if ( name ) { name->RemoveDef( this ); } } /* ============ idVarDef::Name ============ */ const char *idVarDef::Name( void ) const { return name->Name(); } /* ============ idVarDef::GlobalName ============ */ const char *idVarDef::GlobalName( void ) const { if ( scope != &def_namespace ) { return va( "%s::%s", scope->GlobalName(), name->Name() ); } else { return name->Name(); } } /* ============ idVarDef::DepthOfScope ============ */ int idVarDef::DepthOfScope( const idVarDef *otherScope ) const { const idVarDef *def; int depth; depth = 1; for( def = otherScope; def != NULL; def = def->scope ) { if ( def == scope ) { return depth; } depth++; } return 0; } /* ============ idVarDef::SetFunction ============ */ void idVarDef::SetFunction( function_t *func ) { assert( typeDef ); initialized = initializedConstant; assert( typeDef->Type() == ev_function ); value.functionPtr = func; } /* ============ idVarDef::SetObject ============ */ void idVarDef::SetObject( idScriptObject *object ) { assert( typeDef ); initialized = initialized; assert( typeDef->Inherits( &type_object ) ); *value.objectPtrPtr = object; } /* ============ idVarDef::SetValue ============ */ void idVarDef::SetValue( const eval_t &_value, bool constant ) { assert( typeDef ); if ( constant ) { initialized = initializedConstant; } else { initialized = initializedVariable; } switch( typeDef->Type() ) { case ev_pointer : case ev_boolean : case ev_field : *value.intPtr = _value._int; break; case ev_jumpoffset : value.jumpOffset = _value._int; break; case ev_argsize : value.argSize = _value._int; break; case ev_entity : *value.entityNumberPtr = _value.entity; break; case ev_string : idStr::Copynz( value.stringPtr, _value.stringPtr, MAX_STRING_LEN ); break; case ev_float : *value.floatPtr = _value._float; break; case ev_vector : value.vectorPtr->x = _value.vector[ 0 ]; value.vectorPtr->y = _value.vector[ 1 ]; value.vectorPtr->z = _value.vector[ 2 ]; break; case ev_function : value.functionPtr = _value.function; break; case ev_virtualfunction : value.virtualFunction = _value._int; break; case ev_object : *value.entityNumberPtr = _value.entity; break; default : throw idCompileError( va( "weird type on '%s'", Name() ) ); break; } } /* ============ idVarDef::SetString ============ */ void idVarDef::SetString( const char *string, bool constant ) { if ( constant ) { initialized = initializedConstant; } else { initialized = initializedVariable; } assert( typeDef && ( typeDef->Type() == ev_string ) ); idStr::Copynz( value.stringPtr, string, MAX_STRING_LEN ); } /* ============ idVarDef::PrintInfo ============ */ void idVarDef::PrintInfo( idFile *file, int instructionPointer ) const { statement_t *jumpst; int jumpto; etype_t etype; int i; int len; const char *ch; if ( initialized == initializedConstant ) { file->Printf( "const " ); } etype = typeDef->Type(); switch( etype ) { case ev_jumpoffset : jumpto = instructionPointer + value.jumpOffset; jumpst = &gameLocal.program.GetStatement( jumpto ); file->Printf( "address %d [%s(%d)]", jumpto, gameLocal.program.GetFilename( jumpst->file ), jumpst->linenumber ); break; case ev_function : if ( value.functionPtr->eventdef ) { file->Printf( "event %s", GlobalName() ); } else { file->Printf( "function %s", GlobalName() ); } break; case ev_field : file->Printf( "field %d", value.ptrOffset ); break; case ev_argsize: file->Printf( "args %d", value.argSize ); break; default: file->Printf( "%s ", typeDef->Name() ); if ( initialized == initializedConstant ) { switch( etype ) { case ev_string : file->Printf( "\"" ); len = strlen( value.stringPtr ); ch = value.stringPtr; for( i = 0; i < len; i++, ch++ ) { if ( idStr::CharIsPrintable( *ch ) ) { file->Printf( "%c", *ch ); } else if ( *ch == '\n' ) { file->Printf( "\\n" ); } else { file->Printf( "\\x%.2x", static_cast<int>( *ch ) ); } } file->Printf( "\"" ); break; case ev_vector : file->Printf( "'%s'", value.vectorPtr->ToString() ); break; case ev_float : file->Printf( "%f", *value.floatPtr ); break; case ev_virtualfunction : file->Printf( "vtable[ %d ]", value.virtualFunction ); break; default : file->Printf( "%d", *value.intPtr ); break; } } else if ( initialized == stackVariable ) { file->Printf( "stack[%d]", value.stackOffset ); } else { file->Printf( "global[%d]", num ); } break; } } /*********************************************************************** idVarDef ***********************************************************************/ /* ============ idVarDefName::AddDef ============ */ void idVarDefName::AddDef( idVarDef *def ) { assert( def->next == NULL ); def->name = this; def->next = defs; defs = def; } /* ============ idVarDefName::RemoveDef ============ */ void idVarDefName::RemoveDef( idVarDef *def ) { if ( defs == def ) { defs = def->next; } else { for ( idVarDef *d = defs; d->next != NULL; d = d->next ) { if ( d->next == def ) { d->next = def->next; break; } } } def->next = NULL; def->name = NULL; } /*********************************************************************** idScriptObject ***********************************************************************/ /* ============ idScriptObject::idScriptObject ============ */ idScriptObject::idScriptObject() { data = NULL; type = &type_object; } /* ============ idScriptObject::~idScriptObject ============ */ idScriptObject::~idScriptObject() { Free(); } /* ============ idScriptObject::Free ============ */ void idScriptObject::Free( void ) { if ( data ) { Mem_Free( data ); } data = NULL; type = &type_object; } /* ================ idScriptObject::Save ================ */ void idScriptObject::Save( idSaveGame *savefile ) const { int size; if ( type == &type_object && data == NULL ) { // Write empty string for uninitialized object savefile->WriteString( "" ); } else { savefile->WriteString( type->Name() ); size = type->Size(); savefile->WriteInt( size ); savefile->Write( data, size ); } } /* ================ idScriptObject::Restore ================ */ void idScriptObject::Restore( idRestoreGame *savefile ) { idStr typeName; int size; savefile->ReadString( typeName ); // Empty string signals uninitialized object if ( typeName.Length() == 0 ) { return; } if ( !SetType( typeName ) ) { savefile->Error( "idScriptObject::Restore: failed to restore object of type '%s'.", typeName.c_str() ); } savefile->ReadInt( size ); if ( size != type->Size() ) { savefile->Error( "idScriptObject::Restore: size of object '%s' doesn't match size in save game.", typeName.c_str() ); } savefile->Read( data, size ); } /* ============ idScriptObject::SetType Allocates an object and initializes memory. ============ */ bool idScriptObject::SetType( const char *typeName ) { size_t size; idTypeDef *newtype; // lookup the type newtype = gameLocal.program.FindType( typeName ); // only allocate memory if the object type changes if ( newtype != type ) { Free(); if ( !newtype ) { gameLocal.Warning( "idScriptObject::SetType: Unknown type '%s'", typeName ); return false; } if ( !newtype->Inherits( &type_object ) ) { gameLocal.Warning( "idScriptObject::SetType: Can't create object of type '%s'. Must be an object type.", newtype->Name() ); return false; } // set the type type = newtype; // allocate the memory size = type->Size(); data = ( byte * )Mem_Alloc( size ); } // init object memory ClearObject(); return true; } /* ============ idScriptObject::ClearObject Resets the memory for the script object without changing its type. ============ */ void idScriptObject::ClearObject( void ) { size_t size; if ( type != &type_object ) { // init object memory size = type->Size(); memset( data, 0, size ); } } /* ============ idScriptObject::HasObject ============ */ bool idScriptObject::HasObject( void ) const { return ( type != &type_object ); } /* ============ idScriptObject::GetTypeDef ============ */ idTypeDef *idScriptObject::GetTypeDef( void ) const { return type; } /* ============ idScriptObject::GetTypeName ============ */ const char *idScriptObject::GetTypeName( void ) const { return type->Name(); } /* ============ idScriptObject::GetConstructor ============ */ const function_t *idScriptObject::GetConstructor( void ) const { const function_t *func; func = GetFunction( "init" ); return func; } /* ============ idScriptObject::GetDestructor ============ */ const function_t *idScriptObject::GetDestructor( void ) const { const function_t *func; func = GetFunction( "destroy" ); return func; } /* ============ idScriptObject::GetFunction ============ */ const function_t *idScriptObject::GetFunction( const char *name ) const { const function_t *func; if ( type == &type_object ) { return NULL; } func = gameLocal.program.FindFunction( name, type ); return func; } /* ============ idScriptObject::GetVariable ============ */ byte *idScriptObject::GetVariable( const char *name, etype_t etype ) const { int i; int pos; const idTypeDef *t; const idTypeDef *parm; if ( type == &type_object ) { return NULL; } t = type; do { if ( t->SuperClass() != &type_object ) { pos = t->SuperClass()->Size(); } else { pos = 0; } for( i = 0; i < t->NumParameters(); i++ ) { parm = t->GetParmType( i ); if ( !strcmp( t->GetParmName( i ), name ) ) { if ( etype != parm->FieldType()->Type() ) { return NULL; } return &data[ pos ]; } if ( parm->FieldType()->Inherits( &type_object ) ) { pos += type_object.Size(); } else { pos += parm->FieldType()->Size(); } } t = t->SuperClass(); } while( t && ( t != &type_object ) ); return NULL; } /*********************************************************************** idProgram ***********************************************************************/ /* ============ idProgram::AllocType ============ */ idTypeDef *idProgram::AllocType( idTypeDef &type ) { idTypeDef *newtype; newtype = new idTypeDef( type ); types.Append( newtype ); return newtype; } /* ============ idProgram::AllocType ============ */ idTypeDef *idProgram::AllocType( etype_t etype, idVarDef *edef, const char *ename, int esize, idTypeDef *aux ) { idTypeDef *newtype; newtype = new idTypeDef( etype, edef, ename, esize, aux ); types.Append( newtype ); return newtype; } /* ============ idProgram::GetType Returns a preexisting complex type that matches the parm, or allocates a new one and copies it out. ============ */ idTypeDef *idProgram::GetType( idTypeDef &type, bool allocate ) { int i; //FIXME: linear search == slow for( i = types.Num() - 1; i >= 0; i-- ) { if ( types[ i ]->MatchesType( type ) && !strcmp( types[ i ]->Name(), type.Name() ) ) { return types[ i ]; } } if ( !allocate ) { return NULL; } // allocate a new one return AllocType( type ); } /* ============ idProgram::FindType Returns a preexisting complex type that matches the name, or returns NULL if not found ============ */ idTypeDef *idProgram::FindType( const char *name ) { idTypeDef *check; int i; for( i = types.Num() - 1; i >= 0; i-- ) { check = types[ i ]; if ( !strcmp( check->Name(), name ) ) { return check; } } return NULL; } /* ============ idProgram::GetDefList ============ */ idVarDef *idProgram::GetDefList( const char *name ) const { int i, hash; hash = varDefNameHash.GenerateKey( name, true ); for ( i = varDefNameHash.First( hash ); i != -1; i = varDefNameHash.Next( i ) ) { if ( idStr::Cmp( varDefNames[i]->Name(), name ) == 0 ) { return varDefNames[i]->GetDefs(); } } return NULL; } /* ============ idProgram::AddDefToNameList ============ */ void idProgram::AddDefToNameList( idVarDef *def, const char *name ) { int i, hash; hash = varDefNameHash.GenerateKey( name, true ); for ( i = varDefNameHash.First( hash ); i != -1; i = varDefNameHash.Next( i ) ) { if ( idStr::Cmp( varDefNames[i]->Name(), name ) == 0 ) { break; } } if ( i == -1 ) { i = varDefNames.Append( new idVarDefName( name ) ); varDefNameHash.Add( hash, i ); } varDefNames[i]->AddDef( def ); } /* ============== idProgram::ReserveMem reserves memory for global variables and returns the starting pointer ============== */ byte *idProgram::ReserveMem(int size) { byte *res = &variables[ numVariables ]; numVariables += size; if ( numVariables > sizeof( variables ) ) { throw idCompileError( va( "Exceeded global memory size (%zd bytes)", sizeof( variables ) ) ); } memset( res, 0, size ); return res; } /* ============ idProgram::AllocVarDef ============ */ idVarDef *idProgram::AllocVarDef(idTypeDef *type, const char *name, idVarDef *scope) { idVarDef *def; def = new idVarDef( type ); def->scope = scope; def->numUsers = 1; def->num = varDefs.Append( def ); // add the def to the list with defs with this name and set the name pointer AddDefToNameList( def, name ); return def; } /* ============ idProgram::AllocDef ============ */ idVarDef *idProgram::AllocDef( idTypeDef *type, const char *name, idVarDef *scope, bool constant ) { idVarDef *def; idStr element; idVarDef *def_x; idVarDef *def_y; idVarDef *def_z; // allocate a new def def = AllocVarDef(type, name, scope); if ( ( type->Type() == ev_vector ) || ( ( type->Type() == ev_field ) && ( type->FieldType()->Type() == ev_vector ) ) ) { // // vector // if ( !strcmp( name, RESULT_STRING ) ) { // <RESULT> vector defs don't need the _x, _y and _z components assert( scope->Type() == ev_function ); def->value.stackOffset = scope->value.functionPtr->locals; def->initialized = idVarDef::stackVariable; scope->value.functionPtr->locals += type->Size(); } else if ( scope->TypeDef()->Inherits( &type_object ) ) { idTypeDef newtype( ev_field, NULL, "float field", 0, &type_float ); idTypeDef *ftype = GetType( newtype, true ); // set the value to the variable's position in the object def->value.ptrOffset = scope->TypeDef()->Size(); // make automatic defs for the vectors elements // origin can be accessed as origin_x, origin_y, and origin_z sprintf( element, "%s_x", def->Name() ); def_x = AllocDef( ftype, element, scope, constant ); sprintf( element, "%s_y", def->Name() ); def_y = AllocDef( ftype, element, scope, constant ); def_y->value.ptrOffset = def_x->value.ptrOffset + sizeof(float); sprintf( element, "%s_z", def->Name() ); def_z = AllocDef( ftype, element, scope, constant ); def_z->value.ptrOffset = def_y->value.ptrOffset + sizeof(float); } else { idTypeDef newtype( ev_float, &def_float, "vector float", 0, NULL ); idTypeDef *ftype = GetType( newtype, true ); // make automatic defs for the vectors elements // origin can be accessed as origin_x, origin_y, and origin_z sprintf( element, "%s_x", def->Name() ); def_x = AllocVarDef( ftype, element, scope ); sprintf( element, "%s_y", def->Name() ); def_y = AllocVarDef( ftype, element, scope ); sprintf( element, "%s_z", def->Name() ); def_z = AllocVarDef( ftype, element, scope ); // get the memory for the full vector and point the _x, _y and _z // defs at the vector member offsets if ( scope->Type() == ev_function ) { // vector on stack def->value.stackOffset = scope->value.functionPtr->locals; def->initialized = idVarDef::stackVariable; scope->value.functionPtr->locals += type->Size(); def_x->value.stackOffset = def->value.stackOffset; def_y->value.stackOffset = def_x->value.stackOffset + sizeof(float); def_z->value.stackOffset = def_y->value.stackOffset + sizeof(float); } else { // global vector def->value.bytePtr = ReserveMem(type->Size()); def_x->value.bytePtr = def->value.bytePtr; def_y->value.bytePtr = def_x->value.bytePtr + sizeof(float); def_z->value.bytePtr = def_y->value.bytePtr + sizeof(float); } def_x->initialized = def->initialized; def_y->initialized = def->initialized; def_z->initialized = def->initialized; } } else if ( scope->TypeDef()->Inherits( &type_object ) ) { // // object variable // // set the value to the variable's position in the object def->value.ptrOffset = scope->TypeDef()->Size(); } else if ( scope->Type() == ev_function ) { // // stack variable // // since we don't know how many local variables there are, // we have to have them go backwards on the stack def->value.stackOffset = scope->value.functionPtr->locals; def->initialized = idVarDef::stackVariable; if ( type->Inherits( &type_object ) ) { // objects only have their entity number on the stack, not the entire object scope->value.functionPtr->locals += type_object.Size(); } else { scope->value.functionPtr->locals += type->Size(); } } else { // // global variable // def->value.bytePtr = ReserveMem(def->TypeDef()->Size()); #ifdef _HH_GLOBAL_COUNTER //HUMANHEAD rww if (globalOutputFile) { globalOutputFile->Printf("%i. (%ib) %s\r\n", globalOutputUnique, def->TypeDef()->Size(), def->Name()); globalOutputUnique++; globalOutputRunningSize += def->TypeDef()->Size(); } #endif //HUMANHEAD END memset( def->value.bytePtr, 0, def->TypeDef()->Size() ); } return def; } /* ============ idProgram::GetDef If type is NULL, it will match any type ============ */ idVarDef *idProgram::GetDef( const idTypeDef *type, const char *name, const idVarDef *scope ) const { idVarDef *def; idVarDef *bestDef; int bestDepth; int depth; bestDepth = 0; bestDef = NULL; for( def = GetDefList( name ); def != NULL; def = def->Next() ) { if ( def->scope->Type() == ev_namespace ) { depth = def->DepthOfScope( scope ); if ( !depth ) { // not in the same namespace continue; } } else if ( def->scope != scope ) { // in a different function continue; } else { depth = 1; } if ( !bestDef || ( depth < bestDepth ) ) { bestDepth = depth; bestDef = def; } } // see if the name is already in use for another type if ( bestDef && type && ( bestDef->TypeDef() != type ) ) { throw idCompileError( va( "Type mismatch on redeclaration of %s", name ) ); } return bestDef; } /* ============ idProgram::FreeDef ============ */ void idProgram::FreeDef( idVarDef *def, const idVarDef *scope ) { idVarDef *e; int i; if ( def->Type() == ev_vector ) { idStr name; sprintf( name, "%s_x", def->Name() ); e = GetDef( NULL, name, scope ); if ( e ) { FreeDef( e, scope ); } sprintf( name, "%s_y", def->Name() ); e = GetDef( NULL, name, scope ); if ( e ) { FreeDef( e, scope ); } sprintf( name, "%s_z", def->Name() ); e = GetDef( NULL, name, scope ); if ( e ) { FreeDef( e, scope ); } } varDefs.RemoveIndex( def->num ); for( i = def->num; i < varDefs.Num(); i++ ) { varDefs[ i ]->num = i; } delete def; } /* ============ idProgram::FindFreeResultDef ============ */ idVarDef *idProgram::FindFreeResultDef( idTypeDef *type, const char *name, idVarDef *scope, const idVarDef *a, const idVarDef *b ) { idVarDef *def; for( def = GetDefList( name ); def != NULL; def = def->Next() ) { if ( def == a || def == b ) { continue; } if ( def->TypeDef() != type ) { continue; } if ( def->scope != scope ) { continue; } if ( def->numUsers <= 1 ) { continue; } return def; } return AllocDef( type, name, scope, false ); } /* ================ idProgram::FindFunction Searches for the specified function in the currently loaded script. A full namespace should be specified if not in the global namespace. Returns 0 if function not found. Returns >0 if function found. ================ */ function_t *idProgram::FindFunction( const char *name ) const { int start; int pos; idVarDef *namespaceDef; idVarDef *def; assert( name ); idStr fullname = name; start = 0; namespaceDef = &def_namespace; do { pos = fullname.Find( "::", true, start ); if ( pos < 0 ) { break; } idStr namespaceName = fullname.Mid( start, pos - start ); def = GetDef( NULL, namespaceName, namespaceDef ); if ( !def ) { // couldn't find namespace return NULL; } namespaceDef = def; // skip past the :: start = pos + 2; } while( def->Type() == ev_namespace ); idStr funcName = fullname.Right( fullname.Length() - start ); def = GetDef( NULL, funcName, namespaceDef ); if ( !def ) { // couldn't find function return NULL; } if ( ( def->Type() == ev_function ) && ( def->value.functionPtr->eventdef == NULL ) ) { return def->value.functionPtr; } // is not a function, or is an eventdef return NULL; } /* ================ idProgram::FindFunction Searches for the specified object function in the currently loaded script. Returns 0 if function not found. Returns >0 if function found. ================ */ function_t *idProgram::FindFunction( const char *name, const idTypeDef *type ) const { const idVarDef *tdef; const idVarDef *def; // look for the function def = NULL; for( tdef = type->def; tdef != &def_object; tdef = tdef->TypeDef()->SuperClass()->def ) { def = GetDef( NULL, name, tdef ); if ( def ) { return def->value.functionPtr; } } return NULL; } /* ================ idProgram::AllocFunction ================ */ function_t &idProgram::AllocFunction( idVarDef *def ) { if ( functions.Num() >= functions.Max() ) { throw idCompileError( va( "Exceeded maximum allowed number of functions (%d)", functions.Max() ) ); } // fill in the dfunction function_t &func = *functions.Alloc(); func.eventdef = NULL; func.def = def; func.type = def->TypeDef(); func.firstStatement = 0; func.numStatements = 0; func.parmTotal = 0; func.locals = 0; func.filenum = filenum; func.parmSize.SetGranularity( 1 ); func.SetName( def->GlobalName() ); def->SetFunction( &func ); return func; } /* ================ idProgram::SetEntity ================ */ void idProgram::SetEntity( const char *name, idEntity *ent ) { idVarDef *def; idStr defName( "$" ); defName += name; def = GetDef( &type_entity, defName, &def_namespace ); if ( def && ( def->initialized != idVarDef::stackVariable ) ) { // 0 is reserved for NULL entity if ( !ent ) { *def->value.entityNumberPtr = 0; } else { *def->value.entityNumberPtr = ent->entityNumber + 1; } } } /* ================ idProgram::AllocStatement ================ */ statement_t *idProgram::AllocStatement( void ) { if ( statements.Num() >= statements.Max() ) { throw idCompileError( va( "Exceeded maximum allowed number of statements (%d)", statements.Max() ) ); } statement_t* ret = statements.Alloc(); ret->flags = 0; // DG: initialize the added flags (that are rarely set/used otherwise) to 0 return ret; } /* ============== idProgram::BeginCompilation called before compiling a batch of files, clears the pr struct ============== */ void idProgram::BeginCompilation( void ) { statement_t *statement; FreeData(); try { // make the first statement a return for a "NULL" function statement = AllocStatement(); statement->linenumber = 0; statement->file = 0; statement->op = OP_RETURN; statement->a = NULL; statement->b = NULL; statement->c = NULL; // define NULL //AllocDef( &type_void, "<NULL>", &def_namespace, true ); // define the return def returnDef = AllocDef( &type_vector, "<RETURN>", &def_namespace, false ); // define the return def for strings returnStringDef = AllocDef( &type_string, "<RETURN>", &def_namespace, false ); // define the sys object sysDef = AllocDef( &type_void, "sys", &def_namespace, true ); } catch( idCompileError &err ) { gameLocal.Error( "%s", err.error ); } } /* ============== idProgram::DisassembleStatement ============== */ void idProgram::DisassembleStatement( idFile *file, int instructionPointer ) const { const opcode_t *op; const statement_t *statement; statement = &statements[ instructionPointer ]; op = &idCompiler::opcodes[ statement->op ]; file->Printf( "%20s(%d):\t%6d: %15s\t", fileList[ statement->file ].c_str(), statement->linenumber, instructionPointer, op->opname ); if ( statement->a ) { file->Printf( "\ta: " ); statement->a->PrintInfo( file, instructionPointer ); } if ( statement->b ) { file->Printf( "\tb: " ); statement->b->PrintInfo( file, instructionPointer ); } if ( statement->c ) { file->Printf( "\tc: " ); statement->c->PrintInfo( file, instructionPointer ); } file->Printf( "\n" ); } /* ============== idProgram::Disassemble ============== */ void idProgram::Disassemble( void ) const { int i; int instructionPointer; const function_t *func; idFile *file; file = fileSystem->OpenFileByMode( "script/disasm.txt", FS_WRITE ); for( i = 0; i < functions.Num(); i++ ) { func = &functions[ i ]; if ( func->eventdef ) { // skip eventdefs continue; } file->Printf( "\nfunction %s() %d stack used, %d parms, %d locals {\n", func->Name(), func->locals, func->parmTotal, func->locals - func->parmTotal ); for( instructionPointer = 0; instructionPointer < func->numStatements; instructionPointer++ ) { DisassembleStatement( file, func->firstStatement + instructionPointer ); } file->Printf( "}\n" ); } fileSystem->CloseFile( file ); } /* ============== idProgram::FinishCompilation Called after all files are compiled to check for errors ============== */ void idProgram::FinishCompilation( void ) { int i; top_functions = functions.Num(); top_statements = statements.Num(); top_types = types.Num(); top_defs = varDefs.Num(); top_files = fileList.Num(); variableDefaults.Clear(); variableDefaults.SetNum( numVariables ); for( i = 0; i < numVariables; i++ ) { variableDefaults[ i ] = variables[ i ]; } } /* ============== idProgram::CompileStats called after all files are compiled to report memory usage. ============== */ void idProgram::CompileStats( void ) { int memused; int memallocated; int stringspace; int funcMem; int i; gameLocal.Printf( "----- Compile stats -----\n" ); gameLocal.DPrintf( "Files loaded:\n" ); stringspace = 0; for( i = 0; i < fileList.Num(); i++ ) { gameLocal.DPrintf( " %s\n", fileList[ i ].c_str() ); stringspace += fileList[ i ].Allocated(); } stringspace += fileList.Size(); memused = varDefs.Num() * sizeof( idVarDef ); memused += types.Num() * sizeof( idTypeDef ); memused += stringspace; for( i = 0; i < types.Num(); i++ ) { memused += types[ i ]->Allocated(); } funcMem = functions.MemoryUsed(); for( i = 0; i < functions.Num(); i++ ) { funcMem += functions[ i ].Allocated(); } memallocated = funcMem + memused + sizeof( idProgram ); memused += statements.MemoryUsed(); memused += functions.MemoryUsed(); // name and filename of functions are shared, so no need to include them memused += sizeof( variables ); gameLocal.Printf( "Memory usage:\n" ); gameLocal.Printf( " Strings: %d, %d bytes\n", fileList.Num(), stringspace ); gameLocal.Printf( " Statements: %d, %zd bytes\n", statements.Num(), statements.MemoryUsed() ); gameLocal.Printf( " Functions: %d, %d bytes\n", functions.Num(), funcMem ); gameLocal.Printf( " Variables: %d bytes\n", numVariables ); gameLocal.Printf( " Mem used: %d bytes\n", memused ); gameLocal.Printf( " Static data: %zd bytes\n", sizeof( idProgram ) ); gameLocal.Printf( " Allocated: %d bytes\n", memallocated ); gameLocal.Printf( " Thread size: %zd bytes\n", sizeof( idThread ) ); } /* ================ idProgram::CompileText ================ */ bool idProgram::CompileText( const char *source, const char *text, bool console ) { idCompiler compiler; int i; idVarDef *def; idStr ospath; // use a full os path for GetFilenum since it calls OSPathToRelativePath to convert filenames from the parser ospath = fileSystem->RelativePathToOSPath( source ); filenum = GetFilenum( ospath ); try { compiler.CompileFile( text, filename, console ); // check to make sure all functions prototyped have code for( i = 0; i < varDefs.Num(); i++ ) { def = varDefs[ i ]; if ( ( def->Type() == ev_function ) && ( ( def->scope->Type() == ev_namespace ) || def->scope->TypeDef()->Inherits( &type_object ) ) ) { if ( !def->value.functionPtr->eventdef && !def->value.functionPtr->firstStatement ) { throw idCompileError( va( "function %s was not defined\n", def->GlobalName() ) ); } } } } catch( idCompileError &err ) { if ( console ) { gameLocal.Printf( "%s\n", err.error ); return false; } else { gameLocal.Error( "%s\n", err.error ); } }; if ( !console ) { CompileStats(); } return true; } /* ================ idProgram::CompileFunction ================ */ const function_t *idProgram::CompileFunction( const char *functionName, const char *text ) { bool result; result = CompileText( functionName, text, false ); if ( g_disasm.GetBool() ) { Disassemble(); } if ( !result ) { gameLocal.Error( "Compile failed." ); } return FindFunction( functionName ); } /* ================ idProgram::CompileFile ================ */ void idProgram::CompileFile( const char *filename ) { char *src; bool result; if ( fileSystem->ReadFile( filename, ( void ** )&src, NULL ) < 0 ) { gameLocal.Error( "Couldn't load %s\n", filename ); } #ifdef _HH_GLOBAL_COUNTER //HUMANHEAD rww if (globalOutputFile) { globalOutputFile->Printf("========================\r\nScript %s\r\n========================\r\n", filename); globalOutputUnique = 0; globalOutputRunningSize = 0; } #endif //HUMANHEAD END result = CompileText( filename, src, false ); fileSystem->FreeFile( src ); if ( g_disasm.GetBool() ) { Disassemble(); } if ( !result ) { gameLocal.Error( "Compile failed in file %s.", filename ); } #ifdef _HH_GLOBAL_COUNTER //HUMANHEAD rww if (globalOutputFile) { globalOutputFile->Printf("========================\r\n%s\r\nUnique variables: %i\r\nVariable size: %i\r\n========================\r\n", filename, globalOutputUnique, globalOutputRunningSize); } #endif //HUMANHEAD END } /* ================ idProgram::FreeData ================ */ void idProgram::FreeData( void ) { int i; // free the defs varDefs.DeleteContents( true ); varDefNames.DeleteContents( true ); varDefNameHash.Free(); returnDef = NULL; returnStringDef = NULL; sysDef = NULL; // free any special types we've created types.DeleteContents( true ); filenum = 0; numVariables = 0; memset( variables, 0, sizeof( variables ) ); // clear all the strings in the functions so that it doesn't look like we're leaking memory. for( i = 0; i < functions.Num(); i++ ) { functions[ i ].Clear(); } filename.Clear(); fileList.Clear(); statements.Clear(); functions.Clear(); top_functions = 0; top_statements = 0; top_types = 0; top_defs = 0; top_files = 0; filename = ""; } /* ================ idProgram::Startup ================ */ void idProgram::Startup( const char *defaultScript ) { gameLocal.Printf( "Initializing scripts\n" ); // make sure all data is freed up idThread::Restart(); #ifdef _HH_GLOBAL_COUNTER //HUMANHEAD rww globalOutputFile = fileSystem->OpenFileByMode("scriptglobals.txt", FS_WRITE); globalOutputUnique = 0; globalOutputRunningSize = 0; #endif //HUMANHEAD END // get ready for loading scripts BeginCompilation(); // load the default script if ( defaultScript && *defaultScript ) { CompileFile( defaultScript ); } FinishCompilation(); #ifdef _HH_GLOBAL_COUNTER //HUMANHEAD rww if (globalOutputFile) { fileSystem->CloseFile(globalOutputFile); globalOutputFile = NULL; } #endif //HUMANHEAD END } /* ================ idProgram::Save ================ */ void idProgram::Save( idSaveGame *savefile ) const { int i; int currentFileNum = top_files; savefile->WriteInt( (fileList.Num() - currentFileNum) ); while ( currentFileNum < fileList.Num() ) { savefile->WriteString( fileList[ currentFileNum ] ); currentFileNum++; } for ( i = 0; i < variableDefaults.Num(); i++ ) { if ( variables[i] != variableDefaults[i] ) { savefile->WriteInt( i ); savefile->WriteByte( variables[i] ); } } // Mark the end of the diff with default variables with -1 savefile->WriteInt( -1 ); savefile->WriteInt( numVariables ); for ( i = variableDefaults.Num(); i < numVariables; i++ ) { savefile->WriteByte( variables[i] ); } int checksum = CalculateChecksum(); savefile->WriteInt( checksum ); } /* ================ idProgram::Restore ================ */ bool idProgram::Restore( idRestoreGame *savefile ) { int i, num, index; bool result = true; idStr scriptname; savefile->ReadInt( num ); for ( i = 0; i < num; i++ ) { savefile->ReadString( scriptname ); CompileFile( scriptname ); } savefile->ReadInt( index ); while( index >= 0 ) { savefile->ReadByte( variables[index] ); savefile->ReadInt( index ); } savefile->ReadInt( num ); for ( i = variableDefaults.Num(); i < num; i++ ) { savefile->ReadByte( variables[i] ); } int saved_checksum, checksum; savefile->ReadInt( saved_checksum ); checksum = CalculateChecksum(); if ( saved_checksum != checksum ) { result = false; } return result; } /* ================ idProgram::CalculateChecksum ================ */ int idProgram::CalculateChecksum( void ) const { int i, result; typedef struct { unsigned short op; int a; int b; int c; unsigned short linenumber; unsigned short file; } statementBlock_t; statementBlock_t *statementList = new statementBlock_t[ statements.Num() ]; memset( statementList, 0, ( sizeof(statementBlock_t) * statements.Num() ) ); // Copy info into new list, using the variable numbers instead of a pointer to the variable for( i = 0; i < statements.Num(); i++ ) { statementList[i].op = statements[i].op; if ( statements[i].a ) { statementList[i].a = statements[i].a->num; } else { statementList[i].a = -1; } if ( statements[i].b ) { statementList[i].b = statements[i].b->num; } else { statementList[i].b = -1; } if ( statements[i].c ) { statementList[i].c = statements[i].c->num; } else { statementList[i].c = -1; } statementList[i].linenumber = statements[i].linenumber; statementList[i].file = statements[i].file; } result = MD4_BlockChecksum( statementList, ( sizeof(statementBlock_t) * statements.Num() ) ); delete [] statementList; return result; } /* ============== idProgram::Restart Restores all variables to their initial value ============== */ void idProgram::Restart( void ) { int i; idThread::Restart(); // // since there may have been a script loaded by the map or the user may // have typed "script" from the console, free up any types and vardefs that // have been allocated after the initial startup // for( i = top_types; i < types.Num(); i++ ) { delete types[ i ]; } types.SetNum( top_types, false ); for( i = top_defs; i < varDefs.Num(); i++ ) { delete varDefs[ i ]; } varDefs.SetNum( top_defs, false ); for( i = top_functions; i < functions.Num(); i++ ) { functions[ i ].Clear(); } functions.SetNum( top_functions ); statements.SetNum( top_statements ); fileList.SetNum( top_files, false ); filename.Clear(); // reset the variables to their default values numVariables = variableDefaults.Num(); for( i = 0; i < numVariables; i++ ) { variables[ i ] = variableDefaults[ i ]; } } /* ================ idProgram::GetFilenum ================ */ int idProgram::GetFilenum( const char *name ) { if ( filename == name ) { return filenum; } idStr strippedName; strippedName = fileSystem->OSPathToRelativePath( name ); if ( !strippedName.Length() ) { // not off the base path so just use the full path filenum = fileList.AddUnique( name ); } else { filenum = fileList.AddUnique( strippedName ); } // save the unstripped name so that we don't have to strip the incoming name every time we call GetFilenum filename = name; return filenum; } /* ================ idProgram::idProgram ================ */ idProgram::idProgram() { FreeData(); } /* ================ idProgram::~idProgram ================ */ idProgram::~idProgram() { FreeData(); } /* ================ idProgram::ReturnEntity ================ */ void idProgram::ReturnEntity( idEntity *ent ) { if ( ent ) { *returnDef->value.entityNumberPtr = ent->entityNumber + 1; } else { *returnDef->value.entityNumberPtr = 0; } }
0
0.930284
1
0.930284
game-dev
MEDIA
0.32811
game-dev
0.923019
1
0.923019
AbyssEngine/OpenDiablo2
11,780
screens/map-engine-test.lua
local MapEngineTest = { seed = math.random(1, 9223372036854775807) } function MapEngineTest:new() local this = {} setmetatable(this, self) self:initialize() return this end function MapEngineTest:initialize() self.startMouseX = 0 self.startMouseY = 0 self.lastMouseX = 0 self.lastMouseY = 0 self.curMapOffsetX = 400 self.curMapOffsetY = 300 self.isMouseDrag = false self.currentMap = 1 self.currentPreset = 1 self.selectedFile = 1 self.RegionSpec = { -- Act 1 { typeId = RegionDefs.Act1.Town, startPreset = 1, endPreset = 3, Palette = ResourceDefs.Palette.Act1, extra = {} }, { typeId = RegionDefs.Act1.Wilderness, startPreset = 4, endPreset = 52, Palette = ResourceDefs.Palette.Act1, extra = {108,160,161,162,163,164} }, { typeId = RegionDefs.Act1.Cave, startPreset = 53, endPreset = 107, Palette = ResourceDefs.Palette.Act1, extra = {} }, { typeId = RegionDefs.Act1.Crypt, startPreset = 109, endPreset = 159, Palette = ResourceDefs.Palette.Act1, extra = {} }, { typeId = RegionDefs.Act1.Monastary, startPreset = 165, endPreset = 165, Palette = ResourceDefs.Palette.Act1, extra = {} }, { typeId = RegionDefs.Act1.Courtyard, startPreset = 166, endPreset = 166, Palette = ResourceDefs.Palette.Act1, extra = {256} }, { typeId = RegionDefs.Act1.Barracks, startPreset = 167, endPreset = 205, Palette = ResourceDefs.Palette.Act1, extra = {} }, { typeId = RegionDefs.Act1.Jail, startPreset = 206, endPreset = 255, Palette = ResourceDefs.Palette.Act1, extra = {} }, { typeId = RegionDefs.Act1.Cathedral, startPreset = 257, endPreset = 257, Palette = ResourceDefs.Palette.Act1, extra = {} }, { typeId = RegionDefs.Act1.Catacombs, startPreset = 258, endPreset = 299, Palette = ResourceDefs.Palette.Act1, extra = {} }, { typeId = RegionDefs.Act1.Tristram, startPreset = 300, endPreset = 300, Palette = ResourceDefs.Palette.Act1, extra = {} }, -- Act2 { typeId = RegionDefs.Act2.Town, startPreset = 301, endPreset = 301, Palette = ResourceDefs.Palette.Act2, extra = {} }, { typeId = RegionDefs.Act2.Sewer, startPreset = 302, endPreset = 352, Palette = ResourceDefs.Palette.Act2, extra = {} }, { typeId = RegionDefs.Act2.Harem, startPreset = 353, endPreset = 357, Palette = ResourceDefs.Palette.Act2, extra = {} }, { typeId = RegionDefs.Act2.Basement, startPreset = 358, endPreset = 361, Palette = ResourceDefs.Palette.Act2, extra = {} }, { typeId = RegionDefs.Act2.Desert, startPreset = 362, endPreset = 413, Palette = ResourceDefs.Palette.Act2, extra = {} }, { typeId = RegionDefs.Act2.Tomb, startPreset = 414, endPreset = 481, Palette = ResourceDefs.Palette.Act2, extra = {} }, { typeId = RegionDefs.Act2.Lair, startPreset = 482, endPreset = 509, Palette = ResourceDefs.Palette.Act2, extra = {} }, { typeId = RegionDefs.Act2.Arcane, startPreset = 510, endPreset = 528, Palette = ResourceDefs.Palette.Act2, extra = {} }, -- Act III { typeId = RegionDefs.Act3.Town, startPreset = 529, endPreset = 529, Palette = ResourceDefs.Palette.Act3, extra = {}}, { typeId = RegionDefs.Act3.Jungle, startPreset = 530, endPreset = 604, Palette = ResourceDefs.Palette.Act3, extra = {}}, { typeId = RegionDefs.Act3.Kurast, startPreset = 605, endPreset = 658, Palette = ResourceDefs.Palette.Act3, extra = {748, 749, 750, 751, 752, 753, 754, 755, 756, 757, 758, 759, 760, 761, 762, 763, 764, 765, 766, 767, 768, 769,770, 771, 772, 773, 774, 775, 776, 777, 778, 779, 780, 781, 782, 783, 784, 785, 786, 787, 788, 789, 790, 791,792, 793, 794, 795, 796}}, { typeId = RegionDefs.Act3.Spider, startPreset = 659, endPreset = 664, Palette = ResourceDefs.Palette.Act3, extra = {}}, { typeId = RegionDefs.Act3.Dungeon, startPreset = 665, endPreset = 704, Palette = ResourceDefs.Palette.Act3, extra = {}}, { typeId = RegionDefs.Act3.Sewer, startPreset = 705, endPreset = 747, Palette = ResourceDefs.Palette.Act3, extra = {}}, -- Act IV { typeId = RegionDefs.Act4.Town, startPreset = 797, endPreset = 798, Palette = ResourceDefs.Palette.Act4, extra = {}}, { typeId = RegionDefs.Act4.Mesa, startPreset = 799, endPreset = 835, Palette = ResourceDefs.Palette.Act4, extra = {}}, { typeId = RegionDefs.Act4.Lava, startPreset = 836, endPreset = 862, Palette = ResourceDefs.Palette.Act4, extra = {}}, -- Act V { typeId = RegionDefs.Act5.Town, startPreset = 863, endPreset = 864, Palette = ResourceDefs.Palette.Act5, extra = {}}, { typeId = RegionDefs.Act5.Siege, startPreset = 865, endPreset = 879, Palette = ResourceDefs.Palette.Act5, extra = {}}, { typeId = RegionDefs.Act5.Barricade, startPreset = 880, endPreset = 1002, Palette = ResourceDefs.Palette.Act5, extra = {}}, { typeId = RegionDefs.Act5.IceCaves, startPreset = 1003, endPreset = 1041, Palette = ResourceDefs.Palette.Act5, extra = {}}, { typeId = RegionDefs.Act5.Temple, startPreset = 1042, endPreset = 1052, Palette = ResourceDefs.Palette.Act5, extra = {}}, { typeId = RegionDefs.Act5.Lava, startPreset = 1053, endPreset = 1058, Palette = ResourceDefs.Palette.Act4, extra = {}}, { typeId = RegionDefs.Act5.Baal, startPreset = 1059, endPreset = 1089, Palette = ResourceDefs.Palette.Act5, extra = {}}, } abyss.playBackgroundMusic("") self.rootNode = abyss.getRootNode() self.zone = abyss.createZone() local paletteName = "" self.mapRenderer = abyss.createMapRenderer(self.zone) self.mapRenderer:setPosition(self.curMapOffsetX, self.curMapOffsetY) self.mapRenderer.showOuterBorder = true self.btnExit = CreateButton(ButtonTypes.Short, 0, 573, "Exit", function() SetScreen(Screen.MAIN_MENU) end) self.btnPrevious = CreateButton(ButtonTypes.Medium, 0, 0, "< Preset", function() self:previousMap() end) self.btnPreviousFile = CreateButton(ButtonTypes.Medium, 0, 35, "< File", function() self:previousFile() end) self.btnNext = CreateButton(ButtonTypes.Medium, 672, 0, "Preset >", function() self:nextMap() end) self.btnNextFile = CreateButton(ButtonTypes.Medium, 672, 35, "File >", function() self:nextFile() end) self.lblMapName = abyss.createLabel(SystemFonts.Fnt16) self.lblMapName:setPosition(400, 8) self.lblMapName:setColorMod(0xFF, 0xFF, 0x00) self.lblMapName:setAlignment("middle", "middle") self.lblMapName.caption = "" self.lblPreset = abyss.createLabel(SystemFonts.Fnt16) self.lblPreset:setPosition(400, 22) self.lblPreset:setColorMod(0xFF, 0xFF, 0xFF) self.lblPreset:setAlignment("middle", "middle") self.lblPreset.caption = "" self.inputListener = abyss.createInputListener() self.mapRenderer:appendChild(self.inputListener) self.inputListener:onMouseMove(function(x, y) if IsOnButton then self.isMouseDrag = false; return end self.lastMouseX = x self.lastMouseY = y if self.isMouseDrag then self.mapRenderer:setPosition(self.curMapOffsetX + (x - self.startMouseX), self.curMapOffsetY + (y - self.startMouseY)) else self.startMouseX = x self.startMouseY = y end end) self.inputListener:onMouseButton(function(button, isPressed) if IsOnButton then return end if button == 1 then -- Left mouse button if isPressed then self.isMouseDrag = true else self.isMouseDrag = false self.curMapOffsetX, self.curMapOffsetY = self.mapRenderer:getPosition() end elseif button == 2 and isPressed then -- Right mouse button local mx, my = self.mapRenderer:getPosition() local tx, ty = abyss.orthoToWorld(self.lastMouseX - mx, self.lastMouseY - my) if (tx >= 0) and (ty >= 0) and (tx < self.zone.width) and (ty < self.zone.height) then local tiles = self.zone:getTileInfo(tx, ty) abyss.log("info", "Tiles at " .. tx .. ", " .. ty .. ":") for _, tile in ipairs(tiles) do abyss.log("info", " -> " .. tile.type .. ", " .. tile.mainIndex .. ", " .. tile.subIndex) end end end end) self.rootNode:appendChild(self.mapRenderer) self.rootNode:appendChild(self.btnExit) self.rootNode:appendChild(self.btnPrevious) self.rootNode:appendChild(self.btnNext) self.rootNode:appendChild(self.lblMapName) self.rootNode:appendChild(self.lblPreset) self.rootNode:appendChild(self.btnPreviousFile) self.rootNode:appendChild(self.btnNextFile) self:updateMap() end function MapEngineTest:nextMap() local region = self.RegionSpec[self.currentMap] if self.currentPreset < region.endPreset then self.currentPreset = self.currentPreset + 1 else self.currentMap = self.currentMap + 1 if self.currentMap > #self.RegionSpec then self.currentMap = 1 end self.currentPreset = self.RegionSpec[self.currentMap].startPreset end self.selectedFile = 1 self:updateMap() end function MapEngineTest:previousMap() local region = self.RegionSpec[self.currentMap] if self.currentPreset > region.startPreset then self.currentPreset = self.currentPreset - 1 else self.currentMap = self.currentMap - 1 if self.currentMap < 1 then self.currentMap = #self.RegionSpec end self.currentPreset = self.RegionSpec[self.currentMap].endPreset end self.selectedFile = 1 self:updateMap() end function MapEngineTest:previousFile() local region = self.RegionSpec[self.currentMap] local levelType = LevelTypes[region.typeId] local preset = GetLevelPreset(levelType.id, self.currentPreset) if self.selectedFile > 1 then self.selectedFile = self.selectedFile - 1 else self.selectedFile = #preset.files end self:updateMap() end function MapEngineTest:nextFile() local region = self.RegionSpec[self.currentMap] local levelType = LevelTypes[region.typeId] local preset = GetLevelPreset(levelType.id, self.currentPreset) if self.selectedFile < #preset.files then self.selectedFile = self.selectedFile + 1 else self.selectedFile = 1 end self:updateMap() end function MapEngineTest:updateMap() local region = self.RegionSpec[self.currentMap] local levelType = LevelTypes[region.typeId] local preset = GetLevelPreset(levelType.id, self.currentPreset) local fileCaption = preset.files[self.selectedFile] self.btnNextFile.visible = #preset.files > 1 self.btnPreviousFile.visible = #preset.files > 1 if #preset.files > 1 then fileCaption = fileCaption .. " (" .. self.selectedFile .. " of " .. #preset.files .. ")" end self.lblMapName.caption = preset.name self.lblPreset.caption = fileCaption local ds1 = abyss.loadDS1(preset.files[self.selectedFile]) self.zone:resetMap(levelType, preset.dt1Mask, ds1.width, ds1.height, self.seed) self.zone:stamp(ds1, 0, 0) self.mapRenderer:compile(region.Palette) local ttx = -math.floor(ds1.width / 2) local tty = -math.floor(ds1.height / 2) self.curMapOffsetX, self.curMapOffsetY = abyss.worldToOrtho(ttx, tty) self.curMapOffsetX = self.curMapOffsetX + 400 self.curMapOffsetY = self.curMapOffsetY + 300 self.mapRenderer:setPosition(self.curMapOffsetX, self.curMapOffsetY) end return MapEngineTest
0
0.820489
1
0.820489
game-dev
MEDIA
0.390364
game-dev
0.87489
1
0.87489
crashdezz/BlexPloit
3,741
src/de/blexploit/inventory/items/EINZELTROLL/C_Hacked.java
package de.blexploit.inventory.items.EINZELTROLL; import java.util.Random; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.entity.Player; import api.PacketManager; import de.blexploit.Start; import de.blexploit.inventory.creator.Bereich; import de.blexploit.inventory.creator.InvItem; import de.blexploit.players.Getrollts; import de.blexploit.players.create.GetrolltEntity; import de.blexploit.players.create.MittrollerEntity; public final class C_Hacked extends InvItem { public C_Hacked() { super("*ClientSide Hacked*", "Immer sichere Passwörter verwenden!", Material.FLOWER_POT_ITEM, 0, Bereich.EINZELTROLL, true); } @Override public void onEnable(MittrollerEntity mt) { this.spielerInfo(mt, "hacked die getrollten", 0); this.run(); } @Override public void onDisable(MittrollerEntity mt) { this.spielerInfo(mt, "hat die getrollten genug gehacked", 0); Bukkit.getScheduler().cancelTask(sheduler); for (GetrolltEntity gt : Getrollts.getOnlines()) { for (int i = 0; i < 10; i++) { gt.getPlayer().closeInventory(); } for (int i = 0; i < 100; i++) { gt.sendMessage(""); } PacketManager pm = new PacketManager("PacketPlayOutGameStateChange", int.class, float.class); pm.sendTo(gt.getPlayer(), 7, 0); for (int i = 0; i < 10; i++) { gt.getPlayer().closeInventory(); } } } private final Random rnd = new Random(); private int sheduler = 0; private int counter = 1; private void run() { this.sheduler = Bukkit.getScheduler().scheduleSyncRepeatingTask(Start.instance, new Runnable() { @Override public void run() { PacketManager pm = new PacketManager("PacketPlayOutGameStateChange", int.class, float.class); for (GetrolltEntity gt : Getrollts.getOnlines()) { Player user = gt.getPlayer(); pm.sendTo(user, 7, counter); for (int i = 0; i < 40; i++) { user.sendMessage(""); } api.Send.PlayerSound("BLOCK_ANVIL_BREAK", user.getLocation(), 1, 1, user); api.Send.PlayerSound("ENTITY_BAT_DEATH", user.getLocation(), 1, 1, user); api.Send.PlayerSound("ENTITY_CAT_HURT", user.getLocation(), 1, 1, user); user.sendMessage(ChatColor.LIGHT_PURPLE + " ||||||| "); user.sendMessage(ChatColor.LIGHT_PURPLE + " ==||O|||O||== " + ChatColor.GREEN + String.valueOf(rnd.nextInt(100)) + String.valueOf(rnd.nextInt(100)) + String.valueOf(rnd.nextInt(100)) + String.valueOf(rnd.nextInt(100)) + String.valueOf(rnd.nextInt(100)) + String.valueOf(rnd.nextInt(100)) + String.valueOf(rnd.nextInt(100))); user.sendMessage(ChatColor.LIGHT_PURPLE + " ==|||___|||== " + ChatColor.GREEN + String.valueOf(rnd.nextInt(100)) + String.valueOf(rnd.nextInt(100)) + String.valueOf(rnd.nextInt(100)) + String.valueOf(rnd.nextInt(100)) + String.valueOf(rnd.nextInt(100)) + String.valueOf(rnd.nextInt(100)) + String.valueOf(rnd.nextInt(100))); user.sendMessage(ChatColor.LIGHT_PURPLE + " ||||||||| "); user.sendMessage(""); if (counter == 1) { user.sendMessage("§cDeine Passwörter werden geändert, Bitte warten ...§a"); } else if (counter == 2) { user.sendMessage("§cDeine Passwörter werden geändert, Bitte warten ..§a"); } else if (counter == 3) { user.sendMessage("§cDeine Passwörter werden geändert, Bitte warten ..§a"); } else { user.sendMessage("§cDeine Passwörter werden geändert, Bitte warten ..§a"); } user.closeInventory(); user.openInventory(Bukkit.createInventory(null, 9 * 3)); pm.sendTo(user, 5, 0); } counter++; if (counter > 8) { counter = 1; } } }, 1, 1); } }
0
0.886264
1
0.886264
game-dev
MEDIA
0.885665
game-dev
0.95084
1
0.95084
fchavonet/unity-2d-holberton_survivors
2,502
Assets/Scripts/UI/Crossfades/HubCrossfade.cs
using System.Collections; using UnityEngine; using UnityEngine.SceneManagement; public class HubCrossfade : MonoBehaviour { [Space(10)] // Animator for the crossfade transition public Animator crossfadeAnimator; // Animator for the door opening animation public Animator doorAnimator; [Space(10)] // Duration of the crossfade transition public float transitionTime = 1f; [Space(10)] // Audio source for background music public AudioSource audioSource; // Time to fade out the music public float musicFadeOutTime = 1f; private void OnTriggerEnter2D(Collider2D other) { // Check if the collider is tagged as "Door" if (other.CompareTag("Door")) { // Start the crossfade animation and load the next level NextLevelCrossfade(); // Trigger the door opening animation doorAnimator.SetTrigger("Open"); // Play the door opening sound effect SFXManager.instance.PlaySFX(1); } } // Initiates the crossfade animation and loads the next level after a delay. public void NextLevelCrossfade() { // Start the crossfade animation and load the next level StartCoroutine(loadLevel(SceneManager.GetActiveScene().buildIndex + 1)); // Fade out the background music StartCoroutine(FadeOutMusic()); } // Coroutine to load a level with a crossfade animation. IEnumerator loadLevel(int levelIndex) { // Trigger the crossfade animation crossfadeAnimator.SetTrigger("Start"); // Wait for the specified transition time yield return new WaitForSeconds(transitionTime); // Load the next scene SceneManager.LoadScene(levelIndex); } // Coroutine to fade out the background music. IEnumerator FadeOutMusic() { // If the audio source is not assigned, try to get it from the component if (audioSource == null) { audioSource = GetComponent<AudioSource>(); } // Store the initial volume of the audio source float startVolume = audioSource.volume; // Gradually decrease the volume of the background music while (audioSource.volume > 0) { audioSource.volume -= startVolume * Time.deltaTime / musicFadeOutTime; yield return null; } // Stop the music when the volume reaches zero audioSource.Stop(); } }
0
0.673685
1
0.673685
game-dev
MEDIA
0.817171
game-dev
0.831831
1
0.831831
soopercool101/BrawlCrate
3,432
BrawlLib/SSBB/ResourceNodes/Archives/FolderNode.cs
using System.Collections.Generic; using System.ComponentModel; using System.IO; namespace BrawlLib.SSBB.ResourceNodes { public class FolderNode : ResourceNode { public override ResourceType ResourceFileType => ResourceType.Folder; public List<ResourceNode> _list; [Browsable(false)] public string FolderPath => Parent != null && Parent is FolderNode f ? $"{f.FolderPath}\\{Name}" : _origPath; private string[] _directories; private string[] _files; [DisplayName("Uncompressed Size (Bytes)")] [Description("For stability, this value is only updated on save.")] public override uint UncompressedSize { get { uint size = 0; if (Children == null) { return size; } foreach (ResourceNode r in Children) { size += r.UncompressedSize; } return size; } } public override bool IsDirty { get { if (!AllowSaving) { return false; } if (HasChanged) { return true; } if (_children != null) { foreach (ResourceNode n in _children) { if (n.HasChanged || n.IsDirty) { return true; } } } return false; } set { _changed = value; if (_children != null) { foreach (ResourceNode r in Children) { if (r._children != null) { r.IsDirty = value; } else { r._changed = value; } } } } } public override void Export(string outPath) { Directory.CreateDirectory(outPath); foreach (ResourceNode c in Children) { if (c.IsDirty || !outPath.Equals(FolderPath)) { c.Export($"{outPath}\\{c.FileName}"); } } IsDirty = false; } public override void OnPopulate() { foreach (string s in _directories) { NodeFactory.FromFolder(this, s); } foreach (string s in _files) { ResourceNode node = NodeFactory.FromFile(this, s); if (node != null) { node._origPath = s; } } base.OnPopulate(); } public override bool OnInitialize() { _name = new DirectoryInfo(_origPath).Name; _directories = Directory.GetDirectories(_origPath); _files = Directory.GetFiles(_origPath); IsDirty = false; base.OnInitialize(); return true; } } }
0
0.906752
1
0.906752
game-dev
MEDIA
0.278905
game-dev
0.980804
1
0.980804
ShortTailLab/ph-open
1,153
libs/extensions/CCBReader/CCMenuItemImageLoader.cpp
#include "CCMenuItemImageLoader.h" #define PROPERTY_NORMALDISPLAYFRAME "normalSpriteFrame" #define PROPERTY_SELECTEDDISPLAYFRAME "selectedSpriteFrame" #define PROPERTY_DISABLEDDISPLAYFRAME "disabledSpriteFrame" NS_CC_EXT_BEGIN void CCMenuItemImageLoader::onHandlePropTypeSpriteFrame(CCNode * pNode, CCNode * pParent, const char * pPropertyName, CCSpriteFrame * pCCSpriteFrame, CCBReader * pCCBReader) { if(strcmp(pPropertyName, PROPERTY_NORMALDISPLAYFRAME) == 0) { if(pCCSpriteFrame != NULL) { ((CCMenuItemImage *)pNode)->setNormalSpriteFrame(pCCSpriteFrame); } } else if(strcmp(pPropertyName, PROPERTY_SELECTEDDISPLAYFRAME) == 0) { if(pCCSpriteFrame != NULL) { ((CCMenuItemImage *)pNode)->setSelectedSpriteFrame(pCCSpriteFrame); } } else if(strcmp(pPropertyName, PROPERTY_DISABLEDDISPLAYFRAME) == 0) { if(pCCSpriteFrame != NULL) { ((CCMenuItemImage *)pNode)->setDisabledSpriteFrame(pCCSpriteFrame); } } else { CCMenuItemLoader::onHandlePropTypeSpriteFrame(pNode, pParent, pPropertyName, pCCSpriteFrame, pCCBReader); } } NS_CC_EXT_END
0
0.757965
1
0.757965
game-dev
MEDIA
0.55397
game-dev
0.852829
1
0.852829
WeAreROLI/JUCEUnrealBridge
13,111
ThirdParty/JUCE/Includes/modules/juce_box2d/box2d/Collision/b2Distance.cpp
/* * Copyright (c) 2007-2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #include "b2Distance.h" #include "Shapes/b2CircleShape.h" #include "Shapes/b2EdgeShape.h" #include "Shapes/b2ChainShape.h" #include "Shapes/b2PolygonShape.h" // GJK using Voronoi regions (Christer Ericson) and Barycentric coordinates. int32 b2_gjkCalls, b2_gjkIters, b2_gjkMaxIters; void b2DistanceProxy::Set(const b2Shape* shape, int32 index) { switch (shape->GetType()) { case b2Shape::e_circle: { const b2CircleShape* circle = (b2CircleShape*)shape; m_vertices = &circle->m_p; m_count = 1; m_radius = circle->m_radius; } break; case b2Shape::e_polygon: { const b2PolygonShape* polygon = (b2PolygonShape*)shape; m_vertices = polygon->m_vertices; m_count = polygon->m_vertexCount; m_radius = polygon->m_radius; } break; case b2Shape::e_chain: { const b2ChainShape* chain = (b2ChainShape*)shape; b2Assert(0 <= index && index < chain->m_count); m_buffer[0] = chain->m_vertices[index]; if (index + 1 < chain->m_count) { m_buffer[1] = chain->m_vertices[index + 1]; } else { m_buffer[1] = chain->m_vertices[0]; } m_vertices = m_buffer; m_count = 2; m_radius = chain->m_radius; } break; case b2Shape::e_edge: { const b2EdgeShape* edge = (b2EdgeShape*)shape; m_vertices = &edge->m_vertex1; m_count = 2; m_radius = edge->m_radius; } break; default: b2Assert(false); } } struct b2SimplexVertex { b2Vec2 wA; // support point in proxyA b2Vec2 wB; // support point in proxyB b2Vec2 w; // wB - wA float32 a; // barycentric coordinate for closest point int32 indexA; // wA index int32 indexB; // wB index }; struct b2Simplex { void ReadCache( const b2SimplexCache* cache, const b2DistanceProxy* proxyA, const b2Transform& transformA, const b2DistanceProxy* proxyB, const b2Transform& transformB) { b2Assert(cache->count <= 3); // Copy data from cache. m_count = cache->count; b2SimplexVertex* vertices = &m_v1; for (int32 i = 0; i < m_count; ++i) { b2SimplexVertex* v = vertices + i; v->indexA = cache->indexA[i]; v->indexB = cache->indexB[i]; b2Vec2 wALocal = proxyA->GetVertex(v->indexA); b2Vec2 wBLocal = proxyB->GetVertex(v->indexB); v->wA = b2Mul(transformA, wALocal); v->wB = b2Mul(transformB, wBLocal); v->w = v->wB - v->wA; v->a = 0.0f; } // Compute the new simplex metric, if it is substantially different than // old metric then flush the simplex. if (m_count > 1) { float32 metric1 = cache->metric; float32 metric2 = GetMetric(); if (metric2 < 0.5f * metric1 || 2.0f * metric1 < metric2 || metric2 < b2_epsilon) { // Reset the simplex. m_count = 0; } } // If the cache is empty or invalid ... if (m_count == 0) { b2SimplexVertex* v = vertices + 0; v->indexA = 0; v->indexB = 0; b2Vec2 wALocal = proxyA->GetVertex(0); b2Vec2 wBLocal = proxyB->GetVertex(0); v->wA = b2Mul(transformA, wALocal); v->wB = b2Mul(transformB, wBLocal); v->w = v->wB - v->wA; m_count = 1; } } void WriteCache(b2SimplexCache* cache) const { cache->metric = GetMetric(); cache->count = uint16(m_count); const b2SimplexVertex* vertices = &m_v1; for (int32 i = 0; i < m_count; ++i) { cache->indexA[i] = uint8(vertices[i].indexA); cache->indexB[i] = uint8(vertices[i].indexB); } } b2Vec2 GetSearchDirection() const { switch (m_count) { case 1: return -m_v1.w; case 2: { b2Vec2 e12 = m_v2.w - m_v1.w; float32 sgn = b2Cross(e12, -m_v1.w); if (sgn > 0.0f) { // Origin is left of e12. return b2Cross(1.0f, e12); } else { // Origin is right of e12. return b2Cross(e12, 1.0f); } } default: b2Assert(false); return b2Vec2_zero; } } b2Vec2 GetClosestPoint() const { switch (m_count) { case 0: b2Assert(false); return b2Vec2_zero; case 1: return m_v1.w; case 2: return m_v1.a * m_v1.w + m_v2.a * m_v2.w; case 3: return b2Vec2_zero; default: b2Assert(false); return b2Vec2_zero; } } void GetWitnessPoints(b2Vec2* pA, b2Vec2* pB) const { switch (m_count) { case 0: b2Assert(false); break; case 1: *pA = m_v1.wA; *pB = m_v1.wB; break; case 2: *pA = m_v1.a * m_v1.wA + m_v2.a * m_v2.wA; *pB = m_v1.a * m_v1.wB + m_v2.a * m_v2.wB; break; case 3: *pA = m_v1.a * m_v1.wA + m_v2.a * m_v2.wA + m_v3.a * m_v3.wA; *pB = *pA; break; default: b2Assert(false); break; } } float32 GetMetric() const { switch (m_count) { case 0: b2Assert(false); return 0.0f; case 1: return 0.0f; case 2: return b2Distance(m_v1.w, m_v2.w); case 3: return b2Cross(m_v2.w - m_v1.w, m_v3.w - m_v1.w); default: b2Assert(false); return 0.0f; } } void Solve2(); void Solve3(); b2SimplexVertex m_v1, m_v2, m_v3; int32 m_count; }; // Solve a line segment using barycentric coordinates. // // p = a1 * w1 + a2 * w2 // a1 + a2 = 1 // // The vector from the origin to the closest point on the line is // perpendicular to the line. // e12 = w2 - w1 // dot(p, e) = 0 // a1 * dot(w1, e) + a2 * dot(w2, e) = 0 // // 2-by-2 linear system // [1 1 ][a1] = [1] // [w1.e12 w2.e12][a2] = [0] // // Define // d12_1 = dot(w2, e12) // d12_2 = -dot(w1, e12) // d12 = d12_1 + d12_2 // // Solution // a1 = d12_1 / d12 // a2 = d12_2 / d12 void b2Simplex::Solve2() { b2Vec2 w1 = m_v1.w; b2Vec2 w2 = m_v2.w; b2Vec2 e12 = w2 - w1; // w1 region float32 d12_2 = -b2Dot(w1, e12); if (d12_2 <= 0.0f) { // a2 <= 0, so we clamp it to 0 m_v1.a = 1.0f; m_count = 1; return; } // w2 region float32 d12_1 = b2Dot(w2, e12); if (d12_1 <= 0.0f) { // a1 <= 0, so we clamp it to 0 m_v2.a = 1.0f; m_count = 1; m_v1 = m_v2; return; } // Must be in e12 region. float32 inv_d12 = 1.0f / (d12_1 + d12_2); m_v1.a = d12_1 * inv_d12; m_v2.a = d12_2 * inv_d12; m_count = 2; } // Possible regions: // - points[2] // - edge points[0]-points[2] // - edge points[1]-points[2] // - inside the triangle void b2Simplex::Solve3() { b2Vec2 w1 = m_v1.w; b2Vec2 w2 = m_v2.w; b2Vec2 w3 = m_v3.w; // Edge12 // [1 1 ][a1] = [1] // [w1.e12 w2.e12][a2] = [0] // a3 = 0 b2Vec2 e12 = w2 - w1; float32 w1e12 = b2Dot(w1, e12); float32 w2e12 = b2Dot(w2, e12); float32 d12_1 = w2e12; float32 d12_2 = -w1e12; // Edge13 // [1 1 ][a1] = [1] // [w1.e13 w3.e13][a3] = [0] // a2 = 0 b2Vec2 e13 = w3 - w1; float32 w1e13 = b2Dot(w1, e13); float32 w3e13 = b2Dot(w3, e13); float32 d13_1 = w3e13; float32 d13_2 = -w1e13; // Edge23 // [1 1 ][a2] = [1] // [w2.e23 w3.e23][a3] = [0] // a1 = 0 b2Vec2 e23 = w3 - w2; float32 w2e23 = b2Dot(w2, e23); float32 w3e23 = b2Dot(w3, e23); float32 d23_1 = w3e23; float32 d23_2 = -w2e23; // Triangle123 float32 n123 = b2Cross(e12, e13); float32 d123_1 = n123 * b2Cross(w2, w3); float32 d123_2 = n123 * b2Cross(w3, w1); float32 d123_3 = n123 * b2Cross(w1, w2); // w1 region if (d12_2 <= 0.0f && d13_2 <= 0.0f) { m_v1.a = 1.0f; m_count = 1; return; } // e12 if (d12_1 > 0.0f && d12_2 > 0.0f && d123_3 <= 0.0f) { float32 inv_d12 = 1.0f / (d12_1 + d12_2); m_v1.a = d12_1 * inv_d12; m_v2.a = d12_2 * inv_d12; m_count = 2; return; } // e13 if (d13_1 > 0.0f && d13_2 > 0.0f && d123_2 <= 0.0f) { float32 inv_d13 = 1.0f / (d13_1 + d13_2); m_v1.a = d13_1 * inv_d13; m_v3.a = d13_2 * inv_d13; m_count = 2; m_v2 = m_v3; return; } // w2 region if (d12_1 <= 0.0f && d23_2 <= 0.0f) { m_v2.a = 1.0f; m_count = 1; m_v1 = m_v2; return; } // w3 region if (d13_1 <= 0.0f && d23_1 <= 0.0f) { m_v3.a = 1.0f; m_count = 1; m_v1 = m_v3; return; } // e23 if (d23_1 > 0.0f && d23_2 > 0.0f && d123_1 <= 0.0f) { float32 inv_d23 = 1.0f / (d23_1 + d23_2); m_v2.a = d23_1 * inv_d23; m_v3.a = d23_2 * inv_d23; m_count = 2; m_v1 = m_v3; return; } // Must be in triangle123 float32 inv_d123 = 1.0f / (d123_1 + d123_2 + d123_3); m_v1.a = d123_1 * inv_d123; m_v2.a = d123_2 * inv_d123; m_v3.a = d123_3 * inv_d123; m_count = 3; } void b2Distance(b2DistanceOutput* output, b2SimplexCache* cache, const b2DistanceInput* input) { ++b2_gjkCalls; const b2DistanceProxy* proxyA = &input->proxyA; const b2DistanceProxy* proxyB = &input->proxyB; b2Transform transformA = input->transformA; b2Transform transformB = input->transformB; // Initialize the simplex. b2Simplex simplex; simplex.ReadCache(cache, proxyA, transformA, proxyB, transformB); // Get simplex vertices as an array. b2SimplexVertex* vertices = &simplex.m_v1; const int32 k_maxIters = 20; // These store the vertices of the last simplex so that we // can check for duplicates and prevent cycling. int32 saveA[3], saveB[3]; int32 saveCount = 0; b2Vec2 closestPoint = simplex.GetClosestPoint(); float32 distanceSqr1 = closestPoint.LengthSquared(); float32 distanceSqr2;// = distanceSqr1; // Main iteration loop. int32 iter = 0; while (iter < k_maxIters) { // Copy simplex so we can identify duplicates. saveCount = simplex.m_count; for (int32 i = 0; i < saveCount; ++i) { saveA[i] = vertices[i].indexA; saveB[i] = vertices[i].indexB; } switch (simplex.m_count) { case 1: break; case 2: simplex.Solve2(); break; case 3: simplex.Solve3(); break; default: b2Assert(false); } // If we have 3 points, then the origin is in the corresponding triangle. if (simplex.m_count == 3) { break; } // Compute closest point. b2Vec2 p = simplex.GetClosestPoint(); distanceSqr2 = p.LengthSquared(); // Ensure progress if (distanceSqr2 >= distanceSqr1) { //break; } distanceSqr1 = distanceSqr2; // Get search direction. b2Vec2 d = simplex.GetSearchDirection(); // Ensure the search direction is numerically fit. if (d.LengthSquared() < b2_epsilon * b2_epsilon) { // The origin is probably contained by a line segment // or triangle. Thus the shapes are overlapped. // We can't return zero here even though there may be overlap. // In case the simplex is a point, segment, or triangle it is difficult // to determine if the origin is contained in the CSO or very close to it. break; } // Compute a tentative new simplex vertex using support points. b2SimplexVertex* vertex = vertices + simplex.m_count; vertex->indexA = proxyA->GetSupport(b2MulT(transformA.q, -d)); vertex->wA = b2Mul(transformA, proxyA->GetVertex(vertex->indexA)); b2Vec2 wBLocal; vertex->indexB = proxyB->GetSupport(b2MulT(transformB.q, d)); vertex->wB = b2Mul(transformB, proxyB->GetVertex(vertex->indexB)); vertex->w = vertex->wB - vertex->wA; // Iteration count is equated to the number of support point calls. ++iter; ++b2_gjkIters; // Check for duplicate support points. This is the main termination criteria. bool duplicate = false; for (int32 i = 0; i < saveCount; ++i) { if (vertex->indexA == saveA[i] && vertex->indexB == saveB[i]) { duplicate = true; break; } } // If we found a duplicate support point we must exit to avoid cycling. if (duplicate) { break; } // New vertex is ok and needed. ++simplex.m_count; } b2_gjkMaxIters = b2Max(b2_gjkMaxIters, iter); // Prepare output. simplex.GetWitnessPoints(&output->pointA, &output->pointB); output->distance = b2Distance(output->pointA, output->pointB); output->iterations = iter; // Cache the simplex. simplex.WriteCache(cache); // Apply radii if requested. if (input->useRadii) { float32 rA = proxyA->m_radius; float32 rB = proxyB->m_radius; if (output->distance > rA + rB && output->distance > b2_epsilon) { // Shapes are still no overlapped. // Move the witness points to the outer surface. output->distance -= rA + rB; b2Vec2 normal = output->pointB - output->pointA; normal.Normalize(); output->pointA += rA * normal; output->pointB -= rB * normal; } else { // Shapes are overlapped when radii are considered. // Move the witness points to the middle. b2Vec2 p = 0.5f * (output->pointA + output->pointB); output->pointA = p; output->pointB = p; output->distance = 0.0f; } } }
0
0.952711
1
0.952711
game-dev
MEDIA
0.898315
game-dev
0.995212
1
0.995212
Dimbreath/AzurLaneData
33,447
en-US/view/collection/musiccollectionview.lua
slot0 = class("MusicCollectionView", import("..base.BaseSubView")) function slot0.getUIName(slot0) return "MusicCollectionUI" end function slot0.OnInit(slot0) slot0:initData() slot0:findUI() slot0:addListener() slot0:initPlateListPanel() slot0:initSongListPanel() slot0:Show() slot0:recoverRunData() slot0:initTimer() slot0:tryShowTipMsgBox() end function slot0.OnDestroy(slot0) slot0:stopMusic() slot0.resLoader:Clear() if slot0.playProgressTimer then slot0.playProgressTimer:Stop() slot0.playProgressTimer = nil end if slot0.downloadCheckTimer then slot0.downloadCheckTimer:Stop() slot0.downloadCheckTimer = nil end if slot0.playbackInfo then slot0.playbackInfo = nil end if slot0.appreciateUnlockMsgBox and slot0.appreciateUnlockMsgBox:CheckState(BaseSubView.STATES.INITED) then slot0.appreciateUnlockMsgBox:Destroy() end slot0:closeSongListPanel(true) end function slot0.onBackPressed(slot0) if slot0.appreciateUnlockMsgBox and slot0.appreciateUnlockMsgBox:CheckState(BaseSubView.STATES.INITED) then slot0.appreciateUnlockMsgBox:hideCustomMsgBox() slot0.appreciateUnlockMsgBox:Destroy() return false elseif isActive(slot0.songListPanel) then slot0:closeSongListPanel() return false else return true end end function slot0.initData(slot0) slot0.appreciateProxy = getProxy(AppreciateProxy) slot0.appreciateProxy:checkMusicFileState() slot0.resLoader = AutoLoader.New() slot0.criMgr = pg.CriMgr.GetInstance() slot0.manager = BundleWizard.Inst:GetGroupMgr("GALLERY_BGM") slot0.downloadCheckIDList = {} slot0.downloadCheckTimer = nil slot0.musicForShowConfigList = {} slot0.plateTFList = {} slot0.songTFList = {} slot0.curMidddleIndex = 1 slot0.sortValue = MusicCollectionConst.Sort_Order_Up slot0.likeValue = MusicCollectionConst.Filte_Normal_Value slot0.isPlayingAni = false slot0.cueData = nil slot0.playbackInfo = nil slot0.playProgressTimer = nil slot0.onDrag = false slot0.hadDrag = false slot0.isPlayingSong = false end function slot0.saveRunData(slot0) slot0.appreciateProxy:updateMusicRunData(slot0.sortValue, slot0.curMidddleIndex, slot0.likeValue) end function slot0.recoverRunData(slot0) slot1 = slot0.appreciateProxy:getMusicRunData() slot0.sortValue = slot1.sortValue slot0.curMidddleIndex = slot1.middleIndex slot0.likeValue = slot1.likeValue slot0.musicForShowConfigList = slot0:fliteMusicConfigForShow() slot0:sortMusicConfigList(slot0.sortValue == MusicCollectionConst.Sort_Order_Down) slot0.musicForShowConfigList = slot0:filteMusicConfigByLike() slot0.lScrollPageSC.MiddleIndexOnInit = slot0.curMidddleIndex - 1 slot0:updatePlateListPanel() slot0:updateSongListPanel() slot0:updatePlayPanel() slot0:updateSortToggle() slot0:updateLikeToggle() if not slot0.appreciateProxy:isMusicHaveNewRes() then slot0:tryPlayMusic() end end function slot0.findUI(slot0) setLocalPosition(slot0._tf, Vector2.zero) slot0._tf.anchorMin = Vector2.zero slot0._tf.anchorMax = Vector2.one slot0._tf.offsetMax = Vector2.zero slot0._tf.offsetMin = Vector2.zero slot0.topPanel = slot0:findTF("TopPanel") slot0.likeFilteToggle = slot0:findTF("LikeBtn", slot0.topPanel) slot0.sortToggle = slot0:findTF("SortBtn", slot0.topPanel) slot0.songNameText = slot0:findTF("MusicNameMask/MusicName", slot0.topPanel) slot0.staicImg = slot0:findTF("SoundImg", slot0.topPanel) slot0.playingAni = slot0:findTF("SoundAni", slot0.topPanel) slot0.resRepaireBtn = slot0:findTF("RepaireBtn", slot0.topPanel) setActive(slot0.likeFilteToggle, true) slot0.plateListPanel = slot0:findTF("PlateList") slot0.plateTpl = slot0:findTF("Plate", slot0.plateListPanel) slot0.lScrollPageSC = GetComponent(slot0.plateListPanel, "LScrollPage") slot0.playPanel = slot0:findTF("PLayPanel") slot0.playPanelNameText = slot0:findTF("NameText", slot0.playPanel) slot0.likeToggle = slot0:findTF("LikeBtn", slot0.playPanel) slot0.songImg = slot0:findTF("SongImg", slot0.playPanel) slot0.pauseBtn = slot0:findTF("PlayingBtn", slot0.playPanel) slot0.playBtn = slot0:findTF("StopingBtn", slot0.playPanel) slot0.lockImg = slot0:findTF("LockedBtn", slot0.playPanel) slot0.nextBtn = slot0:findTF("NextBtn", slot0.playPanel) slot0.preBtn = slot0:findTF("PreBtn", slot0.playPanel) slot0.playProgressBar = slot0:findTF("Progress", slot0.playPanel) slot0.nowTimeText = slot0:findTF("NowTimeText", slot0.playProgressBar) slot0.totalTimeText = slot0:findTF("TotalTimeText", slot0.playProgressBar) slot0.playSliderSC = GetComponent(slot0.playProgressBar, "LSlider") slot0.listBtn = slot0:findTF("ListBtn", slot0.playPanel) setActive(slot0.likeToggle, true) slot0.songListPanel = slot0:findTF("SongListPanel") slot0.closeBtn = slot0:findTF("BG", slot0.songListPanel) slot0.panel = slot0:findTF("Panel", slot0.songListPanel) slot0.songContainer = slot0:findTF("Container/Viewport/Content", slot0.panel) slot0.songTpl = slot0:findTF("SongTpl", slot0.panel) slot0.upToggle = slot0:findTF("BG2/UpToggle", slot0.panel) slot0.downToggle = slot0:findTF("BG2/DownToggle", slot0.panel) slot0.songUIItemList = UIItemList.New(slot0.songContainer, slot0.songTpl) slot0.emptyPanel = slot0:findTF("EmptyPanel") slot0.upImg1 = slot0:findTF("Up", slot0.sortToggle) slot0.downImg1 = slot0:findTF("Down", slot0.sortToggle) slot0.upImg2 = slot0:findTF("SelImg", slot0.upToggle) slot0.downImg2 = slot0:findTF("SelImg", slot0.downToggle) slot0.likeFilteOffImg = slot0:findTF("Off", slot0.likeFilteToggle) slot0.likeFilteOnImg = slot0:findTF("On", slot0.likeFilteToggle) slot0.likeOffImg = slot0:findTF("Off", slot0.likeToggle) slot0.likeOnImg = slot0:findTF("On", slot0.likeToggle) end function slot0.addListener(slot0) onButton(slot0, slot0.listBtn, function () uv0:openSongListPanel() end, SFX_PANEL) onButton(slot0, slot0.closeBtn, function () uv0:closeSongListPanel() end, SFX_PANEL) onButton(slot0, slot0.resRepaireBtn, function () pg.MsgboxMgr.GetInstance():ShowMsgBox({ hideYes = true, content = i18n("resource_verify_warn"), custom = { { text = i18n("msgbox_repair"), onCallback = function () if PathMgr.FileExists(Application.persistentDataPath .. "/hashes-bgm.csv") then BundleWizard.Inst:GetGroupMgr("GALLERY_BGM"):StartVerifyForLua() else pg.TipsMgr.GetInstance():ShowTips(i18n("word_no_cache")) end end } } }) end, SFX_PANEL) onButton(slot0, slot0.sortToggle, function () uv0.sortValue = uv0.sortValue == MusicCollectionConst.Sort_Order_Up and MusicCollectionConst.Sort_Order_Down or MusicCollectionConst.Sort_Order_Up uv0:saveRunData() uv0:sortAndUpdate(uv0.sortValue == MusicCollectionConst.Sort_Order_Down) end, SFX_PANEL) onButton(slot0, slot0.upToggle, function () if uv0.sortValue == MusicCollectionConst.Sort_Order_Up then return else uv0.sortValue = MusicCollectionConst.Sort_Order_Up uv0:saveRunData() uv0:sortAndUpdate(false) end end, SFX_PANEL) onButton(slot0, slot0.downToggle, function () if uv0.sortValue == MusicCollectionConst.Sort_Order_Down then return else uv0.sortValue = MusicCollectionConst.Sort_Order_Down uv0:saveRunData() uv0:sortAndUpdate(true) end end, SFX_PANEL) onButton(slot0, slot0.likeFilteToggle, function () uv0.likeValue = uv0.likeValue == MusicCollectionConst.Filte_Normal_Value and MusicCollectionConst.Filte_Like_Value or MusicCollectionConst.Filte_Normal_Value uv0:saveRunData() uv0:sortAndUpdate(uv0.sortValue == MusicCollectionConst.Sort_Order_Down) end, SFX_PANEL) onButton(slot0, slot0.playBtn, function () if not uv0.playbackInfo then uv0:playMusic() elseif uv0.hadDrag then uv0.hadDrag = false uv0.playbackInfo:SetStartTimeAndPlay(uv0.playSliderSC.value) uv0.playProgressTimer:Start() else uv0.playbackInfo.playback:Resume(CriAtomEx.ResumeMode.PausedPlayback) end setActive(uv0.playingAni, true) setActive(uv0.staicImg, false) SetActive(uv0.pauseBtn, true) SetActive(uv0.playBtn, false) end, SFX_PANEL) onButton(slot0, slot0.pauseBtn, function () if uv0.playbackInfo then uv0.playbackInfo.playback:Pause() end setActive(uv0.playingAni, false) setActive(uv0.staicImg, true) SetActive(uv0.pauseBtn, false) SetActive(uv0.playBtn, true) end, SFX_PANEL) onButton(slot0, slot0.preBtn, function () if uv0.curMidddleIndex == 1 then pg.TipsMgr.GetInstance():ShowTips(i18n("res_music_no_pre_tip")) elseif not uv0.isPlayingAni then uv0:setAniState(true) uv0:closePlateAni(uv0.plateTFList[uv0.curMidddleIndex]) uv0.lScrollPageSC:MoveToItemID(uv0.curMidddleIndex - 1 - 1) end end, SFX_PANEL) onButton(slot0, slot0.nextBtn, function () if uv0.curMidddleIndex == #uv0.musicForShowConfigList then pg.TipsMgr.GetInstance():ShowTips(i18n("res_music_no_next_tip")) elseif not uv0.isPlayingAni then uv0:setAniState(true) uv0:closePlateAni(uv0.plateTFList[uv0.curMidddleIndex]) uv0.lScrollPageSC:MoveToItemID(uv0.curMidddleIndex + 1 - 1) end end, SFX_PANEL) onButton(slot0, slot0.likeToggle, function () if uv0.appreciateProxy:isLikedByMusicID(uv0:getMusicConfigForShowByIndex(uv0.curMidddleIndex).id) == true then pg.m02:sendNotification(GAME.APPRECIATE_MUSIC_LIKE, { isAdd = 1, musicID = slot1 }) setActive(uv0.likeOnImg, false) uv0:updateSongTFLikeImg(uv0.songTFList[uv0.curMidddleIndex], false) else pg.m02:sendNotification(GAME.APPRECIATE_MUSIC_LIKE, { isAdd = 0, musicID = slot1 }) setActive(uv0.likeOnImg, true) uv0:updateSongTFLikeImg(uv0.songTFList[uv0.curMidddleIndex], true) end end, SFX_PANEL) slot0.playSliderSC:AddPointDownFunc(function (slot0) if uv0.playbackInfo and not uv0.onDrag then uv0.onDrag = true if not uv0.playbackInfo.playback:IsPaused() then uv0.playbackInfo.playback:Stop(true) end uv0.playProgressTimer:Stop() end end) slot0.playSliderSC:AddPointUpFunc(function (slot0) if uv0.playbackInfo and uv0.onDrag then uv0.onDrag = false if uv0.playbackInfo.playback:IsPaused() then uv0.hadDrag = true else uv0.playbackInfo:SetStartTimeAndPlay(uv0.playSliderSC.value) uv0.playProgressTimer:Start() end else uv0.playSliderSC:SetValueWithoutEvent(0) end end) end function slot0.tryShowTipMsgBox(slot0) if slot0.appreciateProxy:isMusicHaveNewRes() then function slot2() uv0.lScrollPageSC:MoveToItemID(MusicCollectionConst.AutoScrollIndex - 1) PlayerPrefs.SetInt("musicVersion", MusicCollectionConst.Version) uv0:emit(CollectionScene.UPDATE_RED_POINT) end pg.MsgboxMgr.GetInstance():ShowMsgBox({ hideNo = true, hideClose = true, content = i18n("res_music_new_tip", MusicCollectionConst.NewCount), onYes = slot2, onCancel = slot2, onClose = slot2 }) end end function slot0.initPlateListPanel(slot0) function slot0.lScrollPageSC.itemInitedCallback(slot0, slot1) uv0.plateTFList[slot0 + 1] = slot1 uv0:updatePlateTF(slot1, slot0) end function slot0.lScrollPageSC.itemClickCallback(slot0, slot1) if uv0.curMidddleIndex ~= slot0 + 1 and not uv0.isPlayingAni then uv0:setAniState(true) uv0:closePlateAni(uv0.plateTFList[uv0.curMidddleIndex]) uv0.lScrollPageSC:MoveToItemID(slot0) end end function slot0.lScrollPageSC.itemPitchCallback(slot0, slot1) slot2 = slot0 + 1 uv0:stopMusic() uv0:checkUpdateSongTF() uv0.curMidddleIndex = slot0 + 1 uv0:saveRunData() uv0:playPlateAni(slot1, true) uv0:updatePlayPanel() uv0:tryPlayMusic() end function slot0.lScrollPageSC.itemRecycleCallback(slot0, slot1) uv0.plateTFList[slot0 + 1] = nil end addSlip(SLIP_TYPE_HRZ, slot0.plateListPanel, function () if uv0.curMidddleIndex > 1 and not uv0.isPlayingAni then uv0:setAniState(true) uv0.lScrollPageSC:MoveToItemID(uv0.curMidddleIndex - 1 - 1) uv0:closePlateAni(uv0.plateTFList[uv0.curMidddleIndex]) end end, function () if uv0.curMidddleIndex < uv0.lScrollPageSC.DataCount and not uv0.isPlayingAni then uv0:setAniState(true) uv0.lScrollPageSC:MoveToItemID(uv0.curMidddleIndex + 1 - 1) uv0:closePlateAni(uv0.plateTFList[uv0.curMidddleIndex]) end end) end function slot0.updatePlateListPanel(slot0) slot0.plateTFList = {} if #slot0.musicForShowConfigList == 0 then setActive(slot0.plateListPanel, false) return else setActive(slot0.plateListPanel, true) end slot0.lScrollPageSC.DataCount = #slot0.musicForShowConfigList slot0.lScrollPageSC:Init(slot0.curMidddleIndex - 1) end function slot0.updatePlateTF(slot0, slot1, slot2) if #slot0.musicForShowConfigList == 0 then return end slot3 = slot0:findTF("CirclePanel/SmallImg", slot1) slot6 = slot0:findTF("BlackMask", slot1) slot7 = slot0:findTF("Lock", slot6) slot8 = slot0:findTF("UnlockTipText", slot6) slot9 = slot0:findTF("UnlockBtn", slot6) slot10 = slot0:findTF("DownloadBtn", slot6) setText(slot0:findTF("DownloadingImg", slot6), i18n("res_downloading")) slot12 = slot2 + 1 slot13 = slot0:getMusicConfigForShowByIndex(slot12) slot14 = slot13.cover slot0.resLoader:LoadSprite(MusicCollectionConst.MUSIC_COVER_PATH_PREFIX .. slot14, slot14, slot0:findTF("PlateImg", slot1), false) setText(slot0:findTF("IndexNum", slot1), "#" .. slot12) slot16 = slot13.id slot17, slot18 = nil if slot0:getMusicStateByID(slot16) == GalleryConst.CardStates.DirectShow then print("is impossible to go to this, something wrong") if slot0.appreciateProxy:getMusicExistStateByID(slot16) then setActive(slot6, false) else setActive(slot6, true) setActive(slot7, false) setActive(slot8, false) setActive(slot9, false) setActive(slot10, true) setActive(slot11, false) end elseif slot17 == GalleryConst.CardStates.Unlocked then if slot18 then setActive(slot6, false) else if slot0.manager.state == DownloadState.None or slot19 == DownloadState.CheckFailure then slot0.manager:CheckD() end if slot0.manager:CheckF(MusicCollectionConst.MUSIC_SONG_PATH_PREFIX .. slot13.music .. ".b") == DownloadState.None or slot22 == DownloadState.CheckToUpdate or slot22 == DownloadState.UpdateFailure then setActive(slot6, true) setActive(slot7, false) setActive(slot8, false) setActive(slot9, false) setActive(slot10, true) setActive(slot11, false) table.removebyvalue(slot0.downloadCheckIDList, slot16, true) onButton(slot0, slot10, function () if Application.internetReachability == UnityEngine.NetworkReachability.ReachableViaCarrierDataNetwork then pg.MsgboxMgr.GetInstance():ShowMsgBox({ content = i18n("res_wifi_tip"), onYes = function () setActive(uv0, true) setActive(uv1, false) setActive(uv2, false) setActive(uv3, false) setActive(uv4, false) setActive(uv5, true) VersionMgr.Inst:RequestUIForUpdateF("GALLERY_BGM", uv6, false) if not table.contains(uv7.downloadCheckIDList, uv8) then table.insert(uv7.downloadCheckIDList, uv8) end uv7:tryStartDownloadCheckTimer() end }) else slot0() end end, SFX_PANEL) elseif slot22 == DownloadState.Updating then setActive(slot6, true) setActive(slot7, false) setActive(slot8, false) setActive(slot9, false) setActive(slot10, false) setActive(slot11, true) elseif PathMgr.FileExists(PathMgr.getAssetBundle(slot21)) then slot0.appreciateProxy:updateMusicFileExistStateTable(slot16, true) table.removebyvalue(slot0.downloadCheckIDList, slot16, true) if #slot0.downloadCheckIDList == 0 and slot0.downloadCheckTimer then slot0.downloadCheckTimer:Stop() slot0.downloadCheckTimer = nil end setActive(slot6, false) slot0:updatePlayPanel() end end elseif slot17 == GalleryConst.CardStates.Unlockable then setActive(slot6, true) setActive(slot7, true) setActive(slot8, false) setActive(slot9, true) setActive(slot10, false) setActive(slot11, false) onButton(slot0, slot9, function () if not uv0.appreciateUnlockMsgBox then uv0.appreciateUnlockMsgBox = AppreciateUnlockMsgBox.New(uv0._tf, uv0.event, uv0.contextData) end uv0.appreciateUnlockMsgBox:Reset() uv0.appreciateUnlockMsgBox:Load() uv0.appreciateUnlockMsgBox:ActionInvoke("showCustomMsgBox", { content = i18n("res_unlock_tip"), items = uv0.appreciateProxy:getMusicUnlockMaterialByID(uv1), onYes = function () pg.m02:sendNotification(GAME.APPRECIATE_MUSIC_UNLOCK, { musicID = uv0, unlockCBFunc = function () uv0:updatePlateTF(uv1, uv2) uv0:updateSongTF(uv0.songTFList[uv2 + 1], uv2 + 1) uv0:updatePlayPanel() uv0:tryPlayMusic() uv0.appreciateUnlockMsgBox:hideCustomMsgBox() end }) end }) end, SFX_PANEL) elseif slot17 == GalleryConst.CardStates.DisUnlockable then setActive(slot6, true) setActive(slot7, true) setActive(slot8, true) setActive(slot9, false) setActive(slot10, false) setActive(slot11, false) setText(slot8, slot13.illustrate) end end function slot0.initSongListPanel(slot0) slot0.songUIItemList:make(function (slot0, slot1, slot2) if slot0 == UIItemList.EventUpdate then slot1 = slot1 + 1 uv0.songTFList[slot1] = slot2 uv0:updateSongTF(slot2, slot1) end end) end function slot0.updateSongListPanel(slot0) slot0.songTFList = {} if #slot0.musicForShowConfigList == 0 then return end slot0.songUIItemList:align(#slot0.musicForShowConfigList) end function slot0.updateSongTF(slot0, slot1, slot2) if #slot0.musicForShowConfigList == 0 then return end slot3 = slot1 slot4 = slot0:findTF("IndexText", slot3) slot6 = slot0:findTF("NameText", slot3) setActive(slot0:findTF("LikeToggle", slot3), true) slot10 = slot0:getMusicConfigForShowByIndex(slot2) slot11 = slot10.id slot0:updateSongTFLikeImg(slot1, slot0.appreciateProxy:isLikedByMusicID(slot11)) slot12, slot13 = nil slot13 = slot0.appreciateProxy:getMusicExistStateByID(slot11) slot16 = slot0.manager:CheckF(MusicCollectionConst.MUSIC_SONG_PATH_PREFIX .. slot10.music .. ".b") slot17 = nil if slot0:getMusicStateByID(slot11) == MusicCollectionConst.MusicStates.Unlockable then slot17 = MusicCollectionConst.Color_Of_Empty_Song setActive(slot0:findTF("PlayingImg", slot3), false) setActive(slot0:findTF("DownloadImg", slot3), false) setActive(slot0:findTF("LockImg", slot3), true) elseif slot12 == MusicCollectionConst.MusicStates.DisUnlockable then slot17 = MusicCollectionConst.Color_Of_Empty_Song setActive(slot7, false) setActive(slot8, false) setActive(slot9, true) elseif slot12 == MusicCollectionConst.MusicStates.Unlocked then if slot13 then if slot0.isPlayingSong and slot2 == slot0.curMidddleIndex then slot17 = MusicCollectionConst.Color_Of_Playing_Song setActive(slot7, true) setActive(slot8, false) setActive(slot9, false) else slot17 = MusicCollectionConst.Color_Of_Normal_Song setActive(slot7, false) setActive(slot8, false) setActive(slot9, false) end elseif slot16 == DownloadState.None or slot16 == DownloadState.CheckToUpdate or slot16 == DownloadState.UpdateFailure then slot17 = MusicCollectionConst.Color_Of_Empty_Song setActive(slot7, false) setActive(slot8, false) setActive(slot9, false) table.removebyvalue(slot0.downloadCheckIDList, slot11, true) if #slot0.downloadCheckIDList == 0 and slot0.downloadCheckTimer then slot0.downloadCheckTimer:Stop() slot0.downloadCheckTimer = nil return end elseif slot16 == DownloadState.Updating then slot17 = MusicCollectionConst.Color_Of_Empty_Song setActive(slot7, false) setActive(slot8, true) setActive(slot9, false) else setActive(slot7, false) setActive(slot8, false) setActive(slot9, false) if PathMgr.FileExists(PathMgr.getAssetBundle(slot15)) then slot17 = MusicCollectionConst.Color_Of_Normal_Song slot0.appreciateProxy:updateMusicFileExistStateTable(slot11, true) table.removebyvalue(slot0.downloadCheckIDList, slot11, true) if #slot0.downloadCheckIDList == 0 and slot0.downloadCheckTimer then slot0.downloadCheckTimer:Stop() slot0.downloadCheckTimer = nil end end end end setText(slot4, slot2) setText(slot6, setColorStr(slot10.name, slot17)) onButton(slot0, slot3, function () if uv0.isPlayingAni then return else if uv1 == MusicCollectionConst.MusicStates.Unlocked then if uv2 then if not isActive(uv3) then uv0:setAniState(true) uv0:closePlateAni(uv0.plateTFList[uv0.curMidddleIndex]) uv0.lScrollPageSC:MoveToItemID(uv4 - 1) end elseif Application.internetReachability == UnityEngine.NetworkReachability.ReachableViaCarrierDataNetwork then pg.MsgboxMgr.GetInstance():ShowMsgBox({ content = i18n("res_wifi_tip"), onYes = function () setActive(uv0, false) setActive(uv1, true) setActive(uv2, false) VersionMgr.Inst:RequestUIForUpdateF("GALLERY_BGM", uv3, false) if not table.contains(uv4.downloadCheckIDList, uv5) then table.insert(uv4.downloadCheckIDList, uv5) end uv4:tryStartDownloadCheckTimer() uv4:setAniState(true) uv4:closePlateAni(uv4.plateTFList[uv4.curMidddleIndex]) uv4.lScrollPageSC:MoveToItemID(uv6 - 1) end }) else slot0() end elseif uv1 == MusicCollectionConst.MusicStates.DisUnlockable then pg.TipsMgr.GetInstance():ShowTips(uv9.illustrate) elseif uv1 == MusicCollectionConst.MusicStates.Unlockable then if not uv0.appreciateUnlockMsgBox then uv0.appreciateUnlockMsgBox = AppreciateUnlockMsgBox.New(uv0._tf, uv0.event, uv0.contextData) end uv0.appreciateUnlockMsgBox:Reset() uv0.appreciateUnlockMsgBox:Load() uv0.appreciateUnlockMsgBox:ActionInvoke("showCustomMsgBox", { content = i18n("res_unlock_tip"), items = uv0.appreciateProxy:getMusicUnlockMaterialByID(uv8), onYes = function () pg.m02:sendNotification(GAME.APPRECIATE_MUSIC_UNLOCK, { musicID = uv0, unlockCBFunc = function () uv0.lScrollPageSC:MoveToItemID(uv1 - 1) if uv0.plateTFList[uv1] then uv0:updatePlateTF(uv0.plateTFList[uv1], uv1 - 1) end uv0:updateSongTF(uv2, uv1) uv0.appreciateUnlockMsgBox:hideCustomMsgBox() end }) end }) end uv0:closeSongListPanel() end end, SFX_PANEL) end function slot0.updateSongTFLikeImg(slot0, slot1, slot2) slot4 = slot0:findTF("LikeToggle", slot1) setActive(slot4, true) triggerToggle(slot4, slot2) end function slot0.updateSortToggle(slot0) setActive(slot0.upImg1, slot0.sortValue == MusicCollectionConst.Sort_Order_Up) setActive(slot0.upImg2, slot0.sortValue == MusicCollectionConst.Sort_Order_Up) setActive(slot0.downImg1, slot0.sortValue == MusicCollectionConst.Sort_Order_Down) setActive(slot0.downImg2, slot0.sortValue == MusicCollectionConst.Sort_Order_Down) end function slot0.updateLikeToggle(slot0) setActive(slot0.likeFilteOnImg, slot0.likeValue == MusicCollectionConst.Filte_Like_Value) end function slot0.updatePlayPanel(slot0) if #slot0.musicForShowConfigList == 0 then setActive(slot0.playPanel, false) setActive(slot0.playingAni, false) setActive(slot0.staicImg, false) setActive(slot0.songNameText, false) setActive(slot0.emptyPanel, true) return else setActive(slot0.playPanel, true) setActive(slot0.playingAni, false) setActive(slot0.staicImg, true) setActive(slot0.songNameText, true) setActive(slot0.emptyPanel, false) end slot1 = slot0:getMusicConfigForShowByIndex(slot0.curMidddleIndex) slot2 = slot1.cover slot0.resLoader:LoadSprite(MusicCollectionConst.MUSIC_COVER_PATH_PREFIX .. slot2, slot2, slot0.songImg, false) slot4 = slot1.name setScrollText(slot0.songNameText, slot4) setText(slot0.playPanelNameText, slot4) setActive(slot0.likeOnImg, slot0.appreciateProxy:isLikedByMusicID(slot1.id)) slot5 = nil if slot0:getMusicStateByID(slot1.id) == GalleryConst.CardStates.Unlockable or slot5 == GalleryConst.CardStates.DisUnlockable then setActive(slot0.likeToggle, false) else setActive(slot0.likeToggle, true) end if not slot0:isCanPlayByMusicID(slot1.id) then setActive(slot0.playBtn, false) setActive(slot0.pauseBtn, false) setActive(slot0.lockImg, true) slot0.playSliderSC.enabled = false slot0.playSliderSC:SetValueWithoutEvent(0) setActive(slot0.nowTimeText, false) setActive(slot0.totalTimeText, false) else setActive(slot0.playBtn, true) setActive(slot0.pauseBtn, false) setActive(slot0.lockImg, false) slot0.playSliderSC.enabled = true slot0.playSliderSC:SetValueWithoutEvent(0) setActive(slot0.nowTimeText, true) setActive(slot0.totalTimeText, true) end end function slot0.sortAndUpdate(slot0, slot1) slot0.curMidddleIndex = 1 slot0:saveRunData() slot0.musicForShowConfigList = slot0:fliteMusicConfigForShow() slot0:sortMusicConfigList(slot1) slot0.musicForShowConfigList = slot0:filteMusicConfigByLike() slot0:stopMusic() slot0:checkUpdateSongTF() slot0:updatePlateListPanel() slot0:updateSongListPanel() slot0:updatePlayPanel() slot0:updateSortToggle() slot0:updateLikeToggle() slot0:tryPlayMusic() end function slot0.initTimer(slot0) slot0.playProgressTimer = Timer.New(function () if uv0.playbackInfo then slot0 = uv0.playbackInfo:GetTime() uv0.playSliderSC:SetValueWithoutEvent(slot0) setText(uv0.nowTimeText, uv0:descTime(slot0)) if uv0.playbackInfo.playback:GetStatus():ToInt() == 3 then uv0:stopMusic() uv0:checkUpdateSongTF() SetActive(uv0.pauseBtn, false) SetActive(uv0.playBtn, true) uv0:tryPlayMusic() end end end, 0.033, -1) slot0.playProgressTimer:Start() end function slot0.playPlateAni(slot0, slot1, slot2, slot3, slot4) setActive(slot0:findTF("CirclePanel", slot1), slot2) setActive(slot0:findTF("BoxImg", slot1), slot2) slot7 = 0.5 if slot2 == true then slot10 = (443 - 198) / slot7 slot13 = (-121 - 0) / slot7 LeanTween.value(go(slot1), 0, slot7, slot7):setOnUpdate(System.Action_float(function (slot0) setAnchoredPosition(uv4, Vector2.New(uv0 + uv1 * slot0, 0)) setAnchoredPosition(uv5, Vector2.New(uv2 + uv3 * slot0, 0)) end)):setOnComplete(System.Action(function () setAnchoredPosition(uv0, Vector2.New(uv1, 0)) setAnchoredPosition(uv2, Vector2.New(uv3, 0)) uv4:setAniState(false) end)) return end slot9 = 198 slot10 = (slot9 - 448) / slot7 slot12 = (slot3 - slot4) * (slot0.lScrollPageSC.ItemSize.x + slot0.lScrollPageSC.MarginSize.x) slot13 = (slot12 - getAnchoredPosition(slot1).x) / slot7 setAnchoredPosition(slot5, Vector2.New(slot9, 0)) setAnchoredPosition(slot1, Vector2.New(slot12, 0)) end function slot0.closePlateAni(slot0, slot1) slot2 = slot0:findTF("CirclePanel", slot1) setActive(slot2, false) setActive(slot0:findTF("BoxImg", slot1), false) setAnchoredPosition(slot2, Vector2.New(198, 0)) setAnchoredPosition(slot1, Vector2.zero) end function slot0.setAniState(slot0, slot1) slot0.isPlayingAni = slot1 end function slot0.openSongListPanel(slot0) pg.UIMgr.GetInstance():BlurPanel(slot0.songListPanel, false, { groupName = LayerWeightConst.GROUP_COLLECTION }) slot0.songListPanel.offsetMax = slot0._tf.parent.offsetMax slot0.songListPanel.offsetMin = slot0._tf.parent.offsetMin setActive(slot0.songListPanel, true) LeanTween.value(go(slot0.panel), -460, 500, 0.3):setOnUpdate(System.Action_float(function (slot0) setAnchoredPosition(uv0.panel, { y = slot0 }) end)):setOnComplete(System.Action(function () setAnchoredPosition(uv0.panel, { y = 500 }) end)) end function slot0.closeSongListPanel(slot0, slot1) if slot1 == true then pg.UIMgr.GetInstance():UnblurPanel(slot0.songListPanel, slot0._tf) setActive(slot0.songListPanel, false) end if isActive(slot0.songListPanel) then LeanTween.cancel(go(slot0.panel)) LeanTween.value(go(slot0.panel), getAnchoredPosition(slot0.panel).y, -460, 0.3):setOnUpdate(System.Action_float(function (slot0) setAnchoredPosition(uv0.panel, { y = slot0 }) end)):setOnComplete(System.Action(function () setAnchoredPosition(uv0.panel, { y = -460 }) pg.UIMgr.GetInstance():UnblurPanel(uv0.songListPanel, uv0._tf) setActive(uv0.songListPanel, false) end)) end end function slot0.playMusic(slot0) slot2 = slot0:getMusicConfigForShowByIndex(slot0.curMidddleIndex).music if not slot0.cueData then slot0.cueData = CueData.New() end slot0.cueData.channelName = pg.CriMgr.C_GALLERY_MUSIC slot0.cueData.cueSheetName = slot2 slot0.cueData.cueName = "" CriWareMgr.Inst:PlaySound(slot0.cueData, CriWareMgr.CRI_FADE_TYPE.FADE_INOUT, function (slot0) uv0.playbackInfo = slot0 uv0.playbackInfo:SetIgnoreAutoUnload(true) setSlider(uv0.playProgressBar, 0, uv0.playbackInfo:GetLength(), 0) setText(uv0.totalTimeText, uv0:descTime(uv0.playbackInfo:GetLength())) uv0.isPlayingSong = true setActive(uv0.playingAni, true) setActive(uv0.staicImg, false) uv0:updateSongTF(uv0.songTFList[uv0.curMidddleIndex], uv0.curMidddleIndex) end) end function slot0.stopMusic(slot0) if slot0.playbackInfo then slot0.playbackInfo:SetStartTime(0) CriWareMgr.Inst:StopSound(slot0.cueData, CriWareMgr.CRI_FADE_TYPE.NONE) slot0.playbackInfo = nil slot0.isPlayingSong = false end setActive(slot0.playingAni, false) setActive(slot0.staicImg, true) slot0.playSliderSC:SetValueWithoutEvent(0) setText(slot0.nowTimeText, slot0:descTime(0)) end function slot0.checkUpdateSongTF(slot0) if #slot0.songTFList > 0 then slot0:updateSongTF(slot0.songTFList[slot0.curMidddleIndex], slot0.curMidddleIndex) end end function slot0.tryPlayMusic(slot0) if #slot0.musicForShowConfigList == 0 then return end if slot0:isCanPlayByMusicID(slot0:getMusicConfigForShowByIndex(slot0.curMidddleIndex).id) and isActive(slot0.playBtn) then triggerButton(slot0.playBtn) end end function slot0.tryPauseMusic(slot0) if isActive(slot0.pauseBtn) and slot0.playbackInfo then triggerButton(slot0.pauseBtn) end end function slot0.fliteMusicConfigForShow(slot0) slot1 = {} for slot5, slot6 in ipairs(pg.music_collect_config.all) do if slot0.appreciateProxy:isMusicNeedUnlockByID(slot6) then if not slot0.appreciateProxy:isMusicUnlockedByID(slot6) then slot10, slot11 = slot0.appreciateProxy:isMusicUnlockableByID(slot6) if slot10 then slot1[#slot1 + 1] = slot0.appreciateProxy:getSingleMusicConfigByID(slot6) elseif slot11 then slot1[#slot1 + 1] = slot7 end else slot1[#slot1 + 1] = slot7 end else slot1[#slot1 + 1] = slot7 end end return slot1 end function slot0.getMusicConfigForShowByIndex(slot0, slot1) if slot0.musicForShowConfigList[slot1] then return slot2 end end function slot0.getMusicStateByID(slot0, slot1) if not slot0.appreciateProxy:isMusicNeedUnlockByID(slot1) then return MusicCollectionConst.MusicStates.Unlocked elseif slot0.appreciateProxy:isMusicUnlockedByID(slot1) then return MusicCollectionConst.MusicStates.Unlocked elseif slot0.appreciateProxy:isMusicUnlockableByID(slot1) then return MusicCollectionConst.MusicStates.Unlockable else return MusicCollectionConst.MusicStates.DisUnlockable end end function slot0.sortMusicConfigList(slot0, slot1) table.sort(slot0.musicForShowConfigList, function (slot0, slot1) if uv0 == true then return slot1.id < slot0.id else return slot2 < slot3 end end) end function slot0.filteMusicConfigByLike(slot0) if slot0.likeValue == MusicCollectionConst.Filte_Normal_Value then return slot0.musicForShowConfigList end slot1 = {} for slot5, slot6 in ipairs(slot0.musicForShowConfigList) do if slot0.appreciateProxy:isLikedByMusicID(slot6.id) then slot1[#slot1 + 1] = slot6 end end return slot1 end function slot0.isCanPlayByMusicID(slot0, slot1) slot2, slot3 = nil if slot0:getMusicStateByID(slot1) == GalleryConst.CardStates.DirectShow then print("is impossible to go to this, something wrong") if slot0.appreciateProxy:getMusicExistStateByID(slot1) then return true else return false end elseif slot2 == GalleryConst.CardStates.Unlocked then if slot3 then return true else return false end elseif slot2 == GalleryConst.CardStates.Unlockable then return false elseif slot2 == GalleryConst.CardStates.DisUnlockable then return false end end function slot0.descTime(slot0, slot1) slot2 = math.floor(slot1 / 1000) slot3 = math.floor(slot2 / 3600) slot2 = slot2 - slot3 * 3600 if slot3 ~= 0 then return string.format("%02d:%02d:%02d", slot3, math.floor(slot2 / 60), slot2 % 60) else return string.format("%02d:%02d", slot4, slot5) end end function slot0.tryStartDownloadCheckTimer(slot0) if #slot0.downloadCheckIDList == 0 and slot0.downloadCheckTimer then slot0.downloadCheckTimer:Stop() slot0.downloadCheckTimer = nil return end if not slot0.downloadCheckTimer and #slot0.downloadCheckIDList > 0 then slot0.downloadCheckTimer = Timer.New(function () for slot3, slot4 in ipairs(uv0.downloadCheckIDList) do slot5 = nil for slot9, slot10 in ipairs(uv0.musicForShowConfigList) do if slot10.id == slot4 then slot5 = slot9 break end end if slot5 then uv0:updatePlateTF(uv0.plateTFList[slot5], slot5 - 1) uv0:updateSongTF(uv0.songTFList[slot5], slot5) end end end, 1, -1) slot0.downloadCheckTimer:Start() end end return slot0
0
0.634599
1
0.634599
game-dev
MEDIA
0.637959
game-dev
0.982309
1
0.982309