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
Haleth/Aurora
25,951
Skin/Retail/AddOns/Blizzard_AchievementUI.lua
local _, private = ... if not private.isRetail then return end --[[ Lua Globals ]] -- luacheck: globals select next -- [[ Core ]] local Aurora = private.Aurora local Base, Hook, Skin = Aurora.Base, Aurora.Hook, Aurora.Skin local Color, Util = Aurora.Color, Aurora.Util local function SkinSearchButton(button) button:SetNormalTexture("") button:SetPushedTexture("") local r, g, b = Color.highlight:GetRGB() local highlight = button.selectedTexture or button:GetHighlightTexture() highlight:SetColorTexture(r, g, b, 0.2) end do --[[ AddOns\Blizzard_AchievementUI.lua ]] local IN_GUILD_VIEW = false local red, green, blue = Color.red:Hue(0.03), Color.green:Lightness(-0.4), Color.blue:Hue(-0.05) local redDesat, greenDesat, blueDesat = red:Saturation(-0.4), green:Saturation(-0.4), blue:Saturation(-0.4) function Hook.AchievementFrame_UpdateTabs(clickedTab) for i = 1, 3 do _G["AchievementFrameTab"..i].text:SetPoint("CENTER") end end function Hook.AchievementFrame_ToggleView() IN_GUILD_VIEW = not (_G.AchievementFrameHeaderTitle:GetText() == _G.ACHIEVEMENT_TITLE) if IN_GUILD_VIEW then _G.AchievementFrameGuildEmblemLeft:SetVertexColor(1, 1, 1, 0.25) _G.AchievementFrameGuildEmblemRight:SetVertexColor(1, 1, 1, 0.25) end end function Hook.AchievementButton_UpdatePlusMinusTexture(button) if button:IsForbidden() then return end -- twitter achievement share is protected if button.plusMinus:IsShown() then button._auroraPlusMinus:Show() if button.collapsed then button._auroraPlusMinus.plus:Show() else button._auroraPlusMinus.plus:Hide() end elseif button._auroraPlusMinus then button._auroraPlusMinus:Hide() end end function Hook.AchievementButton_Saturate(self) Base.SetBackdropColor(self, Color.button, 1) if IN_GUILD_VIEW then self.titleBar:SetColorTexture(green:GetRGB()) else if self.accountWide then self.titleBar:SetColorTexture(blue:GetRGB()) else self.titleBar:SetColorTexture(red:GetRGB()) end end if self.description then self.description:SetTextColor(.9, .9, .9) self.description:SetShadowOffset(1, -1) end end function Hook.AchievementButton_Desaturate(self) Base.SetBackdropColor(self, Color.button, 1) if IN_GUILD_VIEW then self.titleBar:SetColorTexture(greenDesat:GetRGB()) else if self.accountWide then self.titleBar:SetColorTexture(blueDesat:GetRGB()) else self.titleBar:SetColorTexture(redDesat:GetRGB()) end end end local numMini = 0 function Hook.AchievementButton_GetMiniAchievement(index) if index > numMini then Skin.MiniAchievementTemplate(_G["AchievementFrameMiniAchievement" .. index]) numMini = numMini + 1 end end local numProgress = 0 function Hook.AchievementButton_GetProgressBar(index, renderOffScreen) if index > numProgress then local offscreenName = "" if renderOffScreen then offscreenName = "OffScreen" end Skin.AchievementProgressBarTemplate(_G["AchievementFrameProgressBar" .. offscreenName .. index]) numProgress = numProgress + 1 end end local numMeta = 0 function Hook.AchievementButton_GetMeta(index, renderOffScreen) if index > numMeta then local offscreenName = "" if renderOffScreen then offscreenName = "OffScreen" end Skin.MetaCriteriaTemplate(_G["AchievementFrameMeta" .. offscreenName .. index]) numMeta = numMeta + 1 end end function Hook.AchievementFrameStats_SetStat(button, category, index, colorIndex, isSummary) if not button.id then return end if not colorIndex then colorIndex = index end if (colorIndex % 2) == 1 then button.background:Hide() else button.background:SetColorTexture(1, 1, 1, 0.25) end end function Hook.AchievementFrameStats_SetHeader(button, id) button.background:Show() button.background:SetAlpha(1.0) button.background:SetBlendMode("DISABLE") button.background:SetColorTexture(Color.button:GetRGB()) end local numAchievements = 0 function Hook.AchievementFrameSummary_UpdateAchievements(...) for i = numAchievements + 1, _G.ACHIEVEMENTUI_MAX_SUMMARY_ACHIEVEMENTS do local button = _G["AchievementFrameSummaryAchievement"..i] if button then if i > 1 then local anchorTo = _G["AchievementFrameSummaryAchievement"..i-1] button:SetPoint("TOPLEFT", anchorTo, "BOTTOMLEFT", 0, -1 ) button:SetPoint("TOPRIGHT", anchorTo, "BOTTOMRIGHT", 0, -1 ) end numAchievements = numAchievements + 1 end end end Hook.AchievementFrameComparisonStats_SetStat = Hook.AchievementFrameStats_SetStat Hook.AchievementFrameComparisonStats_SetHeader = Hook.AchievementFrameStats_SetHeader local SearchPreviewButtonHieght = 27 function Hook.AchievementFrame_ShowSearchPreviewResults() local numResults = _G.GetNumFilteredAchievements() if numResults > 5 then numResults = 6 end _G.AchievementFrame.searchPreviewContainer:SetPoint("BOTTOM", _G.AchievementFrame.searchBox, 0, -(numResults * SearchPreviewButtonHieght)) end end do --[[ AddOns\Blizzard_AchievementUI.xml ]] function Skin.AchievementSearchPreviewButton(Button) SkinSearchButton(Button) Button.selectedTexture:SetPoint("TOPLEFT", 1, -1) Button.selectedTexture:SetPoint("BOTTOMRIGHT", -1, 1) Button.iconFrame:SetAlpha(0) Base.CropIcon(Button.icon, Button) end function Skin.AchievementFullSearchResultsButton(Button) SkinSearchButton(Button) Button.iconFrame:SetAlpha(0) Base.CropIcon(Button.icon, Button) Button.path:SetTextColor(Color.grayLight:GetRGB()) Button.resultType:SetTextColor(Color.grayLight:GetRGB()) end function Skin.AchievementFrameSummaryCategoryTemplate(StatusBar) Skin.FrameTypeStatusBar(StatusBar) local name = StatusBar:GetName() StatusBar.label:SetPoint("LEFT", 6, 0) StatusBar.text:SetPoint("RIGHT", -6, 0) _G[name.."Left"]:Hide() _G[name.."Right"]:Hide() _G[name.."Middle"]:Hide() _G[name.."FillBar"]:Hide() local r, g, b = Color.highlight:GetRGB() _G[name.."ButtonHighlightLeft"]:Hide() _G[name.."ButtonHighlightRight"]:Hide() local highlight = _G[name.."ButtonHighlightMiddle"] highlight:SetAllPoints() highlight:SetColorTexture(r, g, b, 0.2) end function Skin.AchievementCheckButtonTemplate(CheckButton) Skin.FrameTypeCheckButton(CheckButton) CheckButton:SetBackdropOption("offsets", { left = 2, right = 2, top = 2, bottom = 2, }) _G[CheckButton:GetName().."Text"]:SetPoint("LEFT", CheckButton, "RIGHT", 2, 0) local bg = CheckButton:GetBackdropTexture("bg") local check = CheckButton:GetCheckedTexture() check:ClearAllPoints() check:SetPoint("TOPLEFT", bg, -6, 6) check:SetPoint("BOTTOMRIGHT", bg, 6, -6) check:SetDesaturated(true) check:SetVertexColor(Color.highlight:GetRGB()) end function Skin.AchievementFrameTabButtonTemplate(Button) local name = Button:GetName() Button:SetHeight(28) _G[name.."LeftDisabled"]:SetTexture("") _G[name.."MiddleDisabled"]:SetTexture("") _G[name.."RightDisabled"]:SetTexture("") _G[name.."Left"]:SetTexture("") _G[name.."Middle"]:SetTexture("") _G[name.."Right"]:SetTexture("") _G[name.."LeftHighlight"]:SetTexture("") _G[name.."MiddleHighlight"]:SetTexture("") _G[name.."RightHighlight"]:SetTexture("") Skin.FrameTypeFrame(Button) Base.SetHighlight(Button) Button._auroraTabResize = true end function Skin.MiniAchievementTemplate(Frame) Base.CropIcon(Frame.icon, Frame) Frame.border:Hide() end function Skin.MetaCriteriaTemplate(Button) Base.CropIcon(Button.icon, Button) Button.border:Hide() end function Skin.AchievementProgressBarTemplate(StatusBar) Skin.FrameTypeStatusBar(StatusBar) local name = StatusBar:GetName() _G[name.."BG"]:Hide() _G[name.."BorderLeft"]:Hide() _G[name.."BorderRight"]:Hide() _G[name.."BorderCenter"]:Hide() end function Skin.AchievementHeaderStatusBarTemplate(StatusBar) Skin.FrameTypeStatusBar(StatusBar) local name = StatusBar:GetName() _G[name.."Left"]:Hide() _G[name.."Right"]:Hide() _G[name.."Middle"]:Hide() _G[name.."FillBar"]:Hide() end function Skin.AchievementCategoryTemplate(Button) Base.SetBackdrop(Button, Color.button) Button.background:Hide() Button.label:SetPoint("BOTTOMLEFT", 6, 0) Button.label:SetPoint("TOPRIGHT") Button.label:SetJustifyV("MIDDLE") local r, g, b = Color.highlight:GetRGB() local highlight = Button:GetHighlightTexture() highlight:SetColorTexture(r, g, b, 0.5) highlight:SetPoint("BOTTOMRIGHT") end function Skin.AchievementIconFrameTemplate(Frame) Frame.bling:Hide() Base.CropIcon(Frame.texture, Frame) Frame.frame:Hide() end function Skin.AchievementTemplate(Button) _G.hooksecurefunc(Button, "Saturate", Hook.AchievementButton_Saturate) _G.hooksecurefunc(Button, "Desaturate", Hook.AchievementButton_Desaturate) Base.SetBackdrop(Button, Color.button, 1) Button.background:Hide() local name = Button:GetName() _G[name.."BottomLeftTsunami"]:Hide() _G[name.."BottomRightTsunami"]:Hide() _G[name.."TopLeftTsunami"]:Hide() _G[name.."TopRightTsunami"]:Hide() _G[name.."BottomTsunami1"]:Hide() _G[name.."TopTsunami1"]:Hide() local titleMask = Button:CreateMaskTexture() titleMask:SetTexture([[Interface\FriendsFrame\PendingFriendNameBG-New]], "CLAMPTOBLACKADDITIVE", "CLAMPTOBLACKADDITIVE") titleMask:SetAllPoints(Button.titleBar) Button.titleBar:AddMaskTexture(titleMask) Button.titleBar:SetHeight(68) Button.titleBar:SetPoint("TOPLEFT", 10, 8) Button.titleBar:SetPoint("TOPRIGHT", -10, 8) Button.glow:Hide() Button.rewardBackground:SetAlpha(0) Button.guildCornerL:Hide() Button.guildCornerR:Hide() Button.label:SetPoint("TOP", 0, -4) Button.plusMinus:SetAlpha(0) local plusMinus = _G.CreateFrame("Frame", nil, Button) Base.SetBackdrop(plusMinus, Color.button) plusMinus:SetAllPoints(Button.plusMinus) plusMinus.plus = plusMinus:CreateTexture(nil, "ARTWORK") plusMinus.plus:SetSize(1, 7) plusMinus.plus:SetPoint("CENTER") plusMinus.plus:SetColorTexture(1, 1, 1) plusMinus.minus = plusMinus:CreateTexture(nil, "ARTWORK") plusMinus.minus:SetSize(7, 1) plusMinus.minus:SetPoint("CENTER") plusMinus.minus:SetColorTexture(1, 1, 1) Button._auroraPlusMinus = plusMinus Base.SetBackdrop(Button.highlight, Color.highlight, Color.frame.a) Button.highlight:DisableDrawLayer("OVERLAY") Button.highlight:ClearAllPoints() Button.highlight:SetPoint("TOPLEFT", 1, -1) Button.highlight:SetPoint("BOTTOMRIGHT", -1, 1) Skin.AchievementIconFrameTemplate(Button.icon) Skin.AchievementCheckButtonTemplate(Button.tracked) end function Skin.ComparisonPlayerTemplate(Frame) _G.hooksecurefunc(Frame, "Saturate", Hook.AchievementButton_Saturate) _G.hooksecurefunc(Frame, "Desaturate", Hook.AchievementButton_Desaturate) Base.SetBackdrop(Frame, Color.frame) Frame.background:Hide() local titleMask = Frame:CreateMaskTexture() titleMask:SetTexture([[Interface\FriendsFrame\PendingFriendNameBG-New]], "CLAMPTOBLACKADDITIVE", "CLAMPTOBLACKADDITIVE") titleMask:SetPoint("TOPLEFT", Frame.titleBar, 0, 8) titleMask:SetPoint("BOTTOMRIGHT", Frame.titleBar, 0, -15) Frame.titleBar:AddMaskTexture(titleMask) Frame.titleBar:ClearAllPoints() Frame.titleBar:SetPoint("TOPLEFT", 10, -1) Frame.titleBar:SetPoint("BOTTOMRIGHT", -10, 1) Frame.glow:Hide() Frame.label:SetPoint("TOP", 0, -4) Skin.AchievementIconFrameTemplate(Frame.icon) end function Skin.SummaryAchievementTemplate(Frame) Frame:SetHeight(44) Frame.icon:SetPoint("TOPLEFT", -1, -1) Frame.shield:SetPoint("TOPRIGHT", -5, -2) Skin.ComparisonPlayerTemplate(Frame) Base.SetBackdrop(Frame.highlight, Color.highlight, Color.frame.a) Frame.highlight:DisableDrawLayer("OVERLAY") Frame.highlight:ClearAllPoints() Frame.highlight:SetPoint("TOPLEFT", 1, -1) Frame.highlight:SetPoint("BOTTOMRIGHT", -1, 1) end function Skin.ComparisonTemplate(Frame) Skin.ComparisonPlayerTemplate(Frame.player) _G.hooksecurefunc(Frame.friend, "Saturate", Hook.AchievementButton_Saturate) _G.hooksecurefunc(Frame.friend, "Desaturate", Hook.AchievementButton_Desaturate) Base.SetBackdrop(Frame.friend, Color.frame) Frame.friend.background:Hide() Frame.friend.titleBar:Hide() Frame.friend.glow:Hide() Skin.AchievementIconFrameTemplate(Frame.friend.icon) end function Skin.StatTemplate(Button) Button.left:SetAlpha(0) Button.middle:SetAlpha(0) Button.right:SetAlpha(0) local r, g, b = Color.highlight:GetRGB() Button:GetHighlightTexture():SetColorTexture(r, g, b, 0.2) end function Skin.ComparisonStatTemplate(Frame) Frame.left:SetAlpha(0) Frame.middle:SetAlpha(0) Frame.right:SetAlpha(0) Frame.left2:SetAlpha(0) Frame.middle2:SetAlpha(0) Frame.right2:SetAlpha(0) end end function private.AddOns.Blizzard_AchievementUI() _G.hooksecurefunc("AchievementFrame_UpdateTabs", Hook.AchievementFrame_UpdateTabs) _G.hooksecurefunc("AchievementFrame_ToggleView", Hook.AchievementFrame_ToggleView) _G.hooksecurefunc("AchievementButton_UpdatePlusMinusTexture", Hook.AchievementButton_UpdatePlusMinusTexture) _G.hooksecurefunc("AchievementButton_GetMiniAchievement", Hook.AchievementButton_GetMiniAchievement) _G.hooksecurefunc("AchievementButton_GetProgressBar", Hook.AchievementButton_GetProgressBar) _G.hooksecurefunc("AchievementButton_GetMeta", Hook.AchievementButton_GetMeta) _G.hooksecurefunc("AchievementFrameSummary_UpdateAchievements", Hook.AchievementFrameSummary_UpdateAchievements) _G.hooksecurefunc("AchievementFrameStats_SetStat", Hook.AchievementFrameStats_SetStat) _G.hooksecurefunc("AchievementFrameStats_SetHeader", Hook.AchievementFrameStats_SetHeader) _G.hooksecurefunc("AchievementFrameComparisonStats_SetStat", Hook.AchievementFrameComparisonStats_SetStat) _G.hooksecurefunc("AchievementFrameComparisonStats_SetHeader", Hook.AchievementFrameComparisonStats_SetHeader) _G.hooksecurefunc("AchievementFrame_ShowSearchPreviewResults", Hook.AchievementFrame_ShowSearchPreviewResults) _G.hooksecurefunc("AchievementComparisonPlayerButton_Saturate", function(self) if not self._auroraSkinned then Skin.SummaryAchievementTemplate(self) self._auroraSkinned = true end Hook.AchievementButton_Saturate(self) end) _G.hooksecurefunc("AchievementComparisonPlayerButton_Desaturate", function(self) if not self._auroraSkinned then Skin.SummaryAchievementTemplate(self) self._auroraSkinned = true end Hook.AchievementButton_Desaturate(self) end) ---------------------- -- AchievementFrame -- ---------------------- local AchievementFrame = _G.AchievementFrame Skin.FrameTypeFrame(AchievementFrame) local bg = AchievementFrame:GetBackdropTexture("bg") AchievementFrame:SetBackdropOption("offsets", { left = 0, right = 0, top = -10, bottom = 0, }) _G.AchievementFrameBackground:Hide() _G.AchievementFrameMetalBorderLeft:Hide() _G.AchievementFrameMetalBorderRight:Hide() _G.AchievementFrameMetalBorderBottom:Hide() _G.AchievementFrameMetalBorderTop:Hide() _G.AchievementFrameCategoriesBG:Hide() _G.AchievementFrameWaterMark:SetDesaturated(true) _G.AchievementFrameWaterMark:SetAlpha(0.5) _G.AchievementFrameGuildEmblemLeft:SetAlpha(0.5) _G.AchievementFrameGuildEmblemRight:SetAlpha(0.5) _G.AchievementFrameMetalBorderTopLeft:Hide() _G.AchievementFrameMetalBorderTopRight:Hide() _G.AchievementFrameMetalBorderBottomLeft:Hide() _G.AchievementFrameMetalBorderBottomRight:Hide() _G.AchievementFrameWoodBorderTopLeft:Hide() _G.AchievementFrameWoodBorderTopRight:Hide() _G.AchievementFrameWoodBorderBottomLeft:Hide() _G.AchievementFrameWoodBorderBottomRight:Hide() ------------ -- Header -- ------------ _G.AchievementFrameHeader:Hide() _G.AchievementFrameHeaderLeft:Hide() _G.AchievementFrameHeaderRight:Hide() _G.AchievementFrameHeaderPointBorder:Hide() _G.AchievementFrameHeaderTitle:Hide() _G.AchievementFrameHeaderLeftDDLInset:SetAlpha(0) _G.AchievementFrameHeaderRightDDLInset:SetAlpha(0) _G.AchievementFrameHeaderPoints:SetParent(AchievementFrame) _G.AchievementFrameHeaderPoints:SetPoint("TOP", bg) _G.AchievementFrameHeaderPoints:SetPoint("BOTTOM", bg, "TOP", 0, -private.FRAME_TITLE_HEIGHT) _G.AchievementFrameHeaderShield:SetParent(AchievementFrame) ---------------- -- Categories -- ---------------- _G.AchievementFrameCategories:SetBackdrop(nil) Skin.HybridScrollBarTemplate(_G.AchievementFrameCategoriesContainerScrollBar) ------------------ -- Achievements -- ------------------ _G.AchievementFrameAchievementsBackground:Hide() select(3, _G.AchievementFrameAchievements:GetRegions()):Hide() Skin.HybridScrollBarTemplate(_G.AchievementFrameAchievementsContainerScrollBar) select(2, _G.AchievementFrameAchievements:GetChildren()):Hide() ----------- -- Stats -- ----------- _G.AchievementFrameStatsBG:Hide() Skin.HybridScrollBarTemplate(_G.AchievementFrameStatsContainerScrollBar) _G.AchievementFrameStatsContainerScrollBar:SetPoint("TOPLEFT", _G.AchievementFrameStatsContainer, "TOPRIGHT", 0, -12) _G.AchievementFrameStatsContainerScrollBar:SetPoint("BOTTOMLEFT", _G.AchievementFrameStatsContainer, "BOTTOMRIGHT", 0, 12) select(3, _G.AchievementFrameStats:GetChildren()):Hide() ------------- -- Summary -- ------------- _G.AchievementFrameSummaryBackground:Hide() _G.AchievementFrameSummary:GetChildren():Hide() _G.AchievementFrameSummaryAchievementsHeaderHeader:Hide() _G.AchievementFrameSummaryCategoriesHeaderTexture:Hide() Skin.FrameTypeStatusBar(_G.AchievementFrameSummaryCategoriesStatusBar) _G.AchievementFrameSummaryCategoriesStatusBarTitle:SetPoint("LEFT", 6, 0) _G.AchievementFrameSummaryCategoriesStatusBarText:SetPoint("RIGHT", -6, 0) _G.AchievementFrameSummaryCategoriesStatusBarLeft:Hide() _G.AchievementFrameSummaryCategoriesStatusBarRight:Hide() _G.AchievementFrameSummaryCategoriesStatusBarMiddle:Hide() _G.AchievementFrameSummaryCategoriesStatusBarFillBar:Hide() for i = 1, 12 do Skin.AchievementFrameSummaryCategoryTemplate(_G["AchievementFrameSummaryCategoriesCategory"..i]) end ---------------- -- Comparison -- ---------------- _G.AchievementFrameComparisonHeader:SetPoint("BOTTOMLEFT", _G.AchievementFrameComparisonSummaryFriend, "TOPLEFT") _G.AchievementFrameComparisonHeader:SetPoint("BOTTOMRIGHT", _G.AchievementFrameComparisonSummaryFriend, "TOPRIGHT") _G.AchievementFrameComparisonHeader:SetHeight(private.FRAME_TITLE_HEIGHT * 2) _G.AchievementFrameComparisonHeaderBG:Hide() _G.AchievementFrameComparisonHeaderPortrait:Hide() _G.AchievementFrameComparisonHeaderPortraitBg:Hide() _G.AchievementFrameComparisonHeaderName:ClearAllPoints() _G.AchievementFrameComparisonHeaderName:SetPoint("TOP") _G.AchievementFrameComparisonHeaderName:SetHeight(private.FRAME_TITLE_HEIGHT) _G.AchievementFrameComparisonHeaderPoints:ClearAllPoints() _G.AchievementFrameComparisonHeaderPoints:SetPoint("TOP", "$parentName", "BOTTOM", 0, 0) _G.AchievementFrameComparisonHeaderPoints:SetHeight(private.FRAME_TITLE_HEIGHT) _G.AchievementFrameComparisonSummary:SetHeight(24) for _, unit in next, {"Player", "Friend"} do local summery = _G["AchievementFrameComparisonSummary"..unit] summery:SetHeight(24) summery:SetBackdrop(nil) _G["AchievementFrameComparisonSummary"..unit.."Background"]:Hide() Skin.AchievementHeaderStatusBarTemplate(summery.statusBar) summery.statusBar:ClearAllPoints() summery.statusBar:SetPoint("TOPLEFT") summery.statusBar:SetPoint("BOTTOMRIGHT") end Skin.HybridScrollBarTemplate(_G.AchievementFrameComparisonContainerScrollBar) _G.AchievementFrameComparisonContainerScrollBar:SetPoint("TOPLEFT", _G.AchievementFrameComparisonContainer, "TOPRIGHT", 0, -12) _G.AchievementFrameComparisonContainerScrollBar:SetPoint("BOTTOMLEFT", _G.AchievementFrameComparisonContainer, "BOTTOMRIGHT", 0, 12) Skin.HybridScrollBarTemplate(_G.AchievementFrameComparisonStatsContainerScrollBar) _G.AchievementFrameComparisonStatsContainerScrollBar:SetPoint("TOPLEFT", _G.AchievementFrameComparisonStatsContainer, "TOPRIGHT", 0, -12) _G.AchievementFrameComparisonStatsContainerScrollBar:SetPoint("BOTTOMLEFT", _G.AchievementFrameComparisonStatsContainer, "BOTTOMRIGHT", 0, 12) select(5, _G.AchievementFrameComparison:GetChildren()):Hide() _G.AchievementFrameComparisonBackground:Hide() _G.AchievementFrameComparisonDark:SetAlpha(0) _G.AchievementFrameComparisonWatermark:SetAlpha(0) Skin.UIPanelCloseButton(_G.AchievementFrameCloseButton) _G.AchievementFrameCloseButton:SetPoint("TOPRIGHT", bg, 5.6, 5) Skin.AchievementFrameTabButtonTemplate(_G.AchievementFrameTab1) Skin.AchievementFrameTabButtonTemplate(_G.AchievementFrameTab2) Skin.AchievementFrameTabButtonTemplate(_G.AchievementFrameTab3) Util.PositionRelative("TOPLEFT", AchievementFrame, "BOTTOMLEFT", 20, -1, 1, "Right", { _G.AchievementFrameTab1, _G.AchievementFrameTab2, _G.AchievementFrameTab3, }) Base.SetBackdrop(_G.AchievementFrameFilterDropDown, Color.button) local filterBG = _G.AchievementFrameFilterDropDown:GetBackdropTexture("bg") _G.AchievementFrameFilterDropDown:SetPoint("TOPLEFT", bg, 148, -6) _G.AchievementFrameFilterDropDown:SetHeight(16) _G.AchievementFrameFilterDropDownText:SetPoint("LEFT", filterBG, 5, 0) Skin.FrameTypeButton(_G.AchievementFrameFilterDropDownButton) _G.AchievementFrameFilterDropDownButton:SetSize(16, 16) local filterArrow = _G.AchievementFrameFilterDropDownButton:CreateTexture(nil, "ARTWORK") filterArrow:SetPoint("TOPLEFT", 4, -6) filterArrow:SetPoint("BOTTOMRIGHT", -4, 6) Base.SetTexture(filterArrow, "arrowDown") local searchBox = AchievementFrame.searchBox Skin.SearchBoxTemplate(searchBox) searchBox:ClearAllPoints() searchBox:SetPoint("TOPRIGHT", bg, -148, 0) local searchPreview = AchievementFrame.searchPreviewContainer searchPreview.background:Hide() searchPreview.borderAnchor:Hide() searchPreview.botRightCorner:Hide() searchPreview.bottomBorder:Hide() searchPreview.leftBorder:Hide() searchPreview.rightBorder:Hide() searchPreview.topBorder:Hide() Skin.FrameTypeFrame(searchPreview) for i = 1, #searchPreview.searchPreviews do Skin.AchievementSearchPreviewButton(searchPreview.searchPreviews[i]) end SkinSearchButton(searchPreview.showAllSearchResults) local searchResults = AchievementFrame.searchResults Skin.FrameTypeFrame(searchResults) searchResults:GetRegions():Hide() -- background local titleText = searchResults.titleText titleText:ClearAllPoints() titleText:SetPoint("TOPLEFT") titleText:SetPoint("BOTTOMRIGHT", searchResults, "TOPRIGHT", 0, -private.FRAME_TITLE_HEIGHT) searchResults.topLeftCorner:Hide() searchResults.topRightCorner:Hide() searchResults.topBorder:Hide() searchResults.bottomLeftCorner:Hide() searchResults.bottomRightCorner:Hide() searchResults.bottomBorder:Hide() searchResults.leftBorder:Hide() searchResults.rightBorder:Hide() searchResults.topTileStreaks:Hide() searchResults.topLeftCorner2:Hide() searchResults.topRightCorner2:Hide() searchResults.topBorder2:Hide() searchResults.scrollFrame:ClearAllPoints() searchResults.scrollFrame:SetPoint("TOPLEFT", 3, -(private.FRAME_TITLE_HEIGHT + 3)) searchResults.scrollFrame:SetPoint("BOTTOMRIGHT", -23, 3) Skin.UIPanelCloseButton(searchResults.closeButton) Skin.HybridScrollBarTrimTemplate(searchResults.scrollFrame.scrollBar) end
0
0.880512
1
0.880512
game-dev
MEDIA
0.761932
game-dev,desktop-app
0.985135
1
0.985135
ParadoxGameConverters/EU4ToVic3
1,025
EU4ToVic3/Source/Mappers/AISecretGoalMapper/AISecretGoalMapping.h
#ifndef AI_SECRET_GOAL_MAPPING_H #define AI_SECRET_GOAL_MAPPING_H #include "Parser.h" namespace V3 { class ClayManager; class Country; } // namespace V3 namespace mappers { class AISecretGoalMapping: commonItems::parser { public: AISecretGoalMapping() = default; explicit AISecretGoalMapping(std::istream& theStream); [[nodiscard]] bool matchGoal(const V3::Country& country, const V3::Country& target, const V3::ClayManager& clayManager) const; private: void registerKeys(); std::optional<std::string> capital; std::optional<std::string> targetCapital; std::optional<bool> targetCapitalDiffRegion; std::optional<int> targetRankLEQ; std::optional<int> targetRankGEQ; std::optional<bool> targetSubject; std::optional<bool> targetOverlord; std::optional<bool> targetRival; std::optional<bool> targetGP; std::optional<bool> gp; std::optional<bool> targetIsClaimed; std::optional<bool> targetIsClaimedByRival; std::optional<bool> govFormDiff; }; } // namespace mappers #endif // AI_SECRET_GOAL_MAPPING_H
0
0.86433
1
0.86433
game-dev
MEDIA
0.528737
game-dev
0.543144
1
0.543144
experiment-games/gmod-experiment-redux
3,869
plugins/tactical_goggles/cl_plugin.lua
local PLUGIN = PLUGIN PLUGIN.tacticalOverlay = Material("effects/combine_binocoverlay") PLUGIN.randomDisplayLines = { "Transmitting physical transition vector...", "Parsing view ports and data arrays...", "Updating biosignal co-ordinates...", "Pinging connection to network...", "Synchronizing locational data...", "Translating radio messages...", "Emptying outgoing pipes...", "Sensoring proximity...", "Pinging loopback...", "Idle connection..." } -- Table to store scanned inventory data PLUGIN.scannedInventories = PLUGIN.scannedInventories or {} net.Receive("expDisplayLine", function() local text = net.ReadString() local color = net.ReadColor() PLUGIN:AddDisplayLine(text, color) end) function PLUGIN:AddDisplayLine(text, color, ...) if (not IsValid(ix.gui.tacticalDisplay)) then return end ix.gui.tacticalDisplay:AddLine(text, color, nil, ...) end net.Receive("expInventorySearch", function() local target = net.ReadEntity() local itemCount = net.ReadUInt(8) local items = {} for i = 1, itemCount do items[#items + 1] = net.ReadString() end if (IsValid(target)) then PLUGIN.scannedInventories[target] = { items = items, expireTime = CurTime() + PLUGIN.inventoryExpireSeconds } end end) function PLUGIN:DrawInventoryInfo(target, items) if (not items or #items == 0) then return end local client = LocalPlayer() local targetPos = target:GetPos() -- Try find the head, chest bone in that order or default to GetPos() local lookups = { "ValveBiped.Bip01_Head1", "ValveBiped.Bip01_Spine2" } for _, bone in ipairs(lookups) do local bonePos = target:GetBonePosition(target:LookupBone(bone)) if (bonePos) then targetPos = bonePos break end end local screenPos = targetPos:ToScreen() -- Don't draw if target is not on screen if (not screenPos.visible) then return end -- Calculate distance fade local distance = client:GetPos():DistToSqr(target:GetPos()) local maxDistance = 90 ^ 2 local alpha = math.Clamp(255 - (distance / maxDistance * 255), 25, 255) -- Starting position (line tracing up and right from player) local startX = screenPos.x + 50 local startY = screenPos.y - 100 -- Draw background local itemCount = #items local lineHeight = 16 local totalHeight = itemCount * lineHeight + 10 local maxWidth = 0 -- Calculate max width needed surface.SetFont("BudgetLabel") for _, item in ipairs(items) do local w, _ = surface.GetTextSize(item) if (w > maxWidth) then maxWidth = w end end maxWidth = maxWidth + 20 -- Draw background box surface.SetDrawColor(101, 174, 124, alpha * 0.05) surface.DrawRect(startX - 5, startY - 5, maxWidth, totalHeight) -- Draw border surface.SetDrawColor(101, 174, 124, alpha) surface.DrawOutlinedRect(startX - 5, startY - 5, maxWidth, totalHeight) -- Draw header line from player to info box surface.SetDrawColor(101, 174, 124, alpha * 0.5) surface.DrawLine(screenPos.x, screenPos.y - 10, startX - 5, startY + totalHeight / 2) -- Draw items surface.SetFont("BudgetLabel") local y = startY for i, item in ipairs(items) do local color = Color(255, 255, 255, alpha) -- Color code certain items if (item:find("Currency:")) then color = Color(255, 215, 0, alpha) -- Gold for currency elseif (item:find("weapon") or item:find("Weapon")) then color = Color(255, 100, 100, alpha) -- Red for weapons elseif (item:find("armor") or item:find("Armor")) then color = Color(100, 100, 255, alpha) -- Blue for armor end surface.SetTextColor(color) surface.SetTextPos(startX, y) surface.DrawText("• " .. item) y = y + lineHeight end -- Draw scan indicator local scanText = "SCANNED" local scanW, scanH = surface.GetTextSize(scanText) surface.SetTextColor(101, 174, 124, alpha * 0.8) surface.SetTextPos(startX + maxWidth - scanW - 5, startY - scanH - 5) surface.DrawText(scanText) end
0
0.910943
1
0.910943
game-dev
MEDIA
0.881548
game-dev
0.992631
1
0.992631
Ellypse/IntelliJ-IDEA-Lua-IDE-WoW-API
4,127
APIs/ChallengeModeInfo.lua
---@class C_ChallengeMode @ChallengeModeInfo C_ChallengeMode = {} ---@param itemLocation ItemLocation ---@return boolean canUse function C_ChallengeMode.CanUseKeystoneInCurrentMap(itemLocation) end function C_ChallengeMode.ClearKeystone() end function C_ChallengeMode.CloseKeystoneFrame() end ---@return number|nil mapChallengeModeID function C_ChallengeMode.GetActiveChallengeMapID() end ---@return number, number, boolean activeKeystoneLevel, activeAffixIDs, wasActiveKeystoneCharged function C_ChallengeMode.GetActiveKeystoneInfo() end ---@param affixID number ---@return cstring, cstring, number name, description, filedataid function C_ChallengeMode.GetAffixInfo(affixID) end ---@return number, number, number, boolean, number, boolean, number|nil, number|nil, boolean, boolean, number, boolean, ChallengeModeCompletionMemberInfo mapChallengeModeID, level, time, onTime, keystoneUpgradeLevels, practiceRun, oldOverallDungeonScore, newOverallDungeonScore, IsMapRecord, IsAffixRecord, PrimaryAffix, isEligibleForScore, members function C_ChallengeMode.GetCompletionInfo() end ---@return number, number numDeaths, timeLost function C_ChallengeMode.GetDeathCount() end --- Returns a color value from the passed in overall season M+ rating. ---@param dungeonScore number ---@return colorRGB scoreColor function C_ChallengeMode.GetDungeonScoreRarityColor(dungeonScore) end ---@return ChallengeModeGuildTopAttempt topAttempt function C_ChallengeMode.GetGuildLeaders() end --- Returns a color value from the passed in keystone level. ---@param level number ---@return colorRGB levelScore function C_ChallengeMode.GetKeystoneLevelRarityColor(level) end ---@return MythicPlusRatingLinkInfo displayScores function C_ChallengeMode.GetMapScoreInfo() end ---@return number mapChallengeModeIDs function C_ChallengeMode.GetMapTable() end ---@param mapChallengeModeID number ---@return cstring, number, number, number|nil, number name, id, timeLimit, texture, backgroundTexture function C_ChallengeMode.GetMapUIInfo(mapChallengeModeID) end --- Gets the overall season mythic+ rating for the player. ---@return number overallDungeonScore function C_ChallengeMode.GetOverallDungeonScore() end ---@param powerLevel number ---@return number, number damageMod, healthMod function C_ChallengeMode.GetPowerLevelDamageHealthMod(powerLevel) end ---@return number, number, number mapChallengeModeID, affixIDs, keystoneLevel function C_ChallengeMode.GetSlottedKeystoneInfo() end --- Returns a color value from the passed in mythic+ rating from the combined affix scores for a specific dungeon ---@param specificDungeonOverallScore number ---@return colorRGB specificDungeonOverallScoreColor function C_ChallengeMode.GetSpecificDungeonOverallScoreRarityColor(specificDungeonOverallScore) end --- Returns a color value from the passed in mythic+ rating for a specific dungeon. ---@param specificDungeonScore number ---@return colorRGB specificDungeonScoreColor function C_ChallengeMode.GetSpecificDungeonScoreRarityColor(specificDungeonScore) end ---@return boolean hasSlottedKeystone function C_ChallengeMode.HasSlottedKeystone() end ---@return boolean challengeModeActive function C_ChallengeMode.IsChallengeModeActive() end ---@return boolean removalSuccessful function C_ChallengeMode.RemoveKeystone() end ---@param mapChallengeModeID number function C_ChallengeMode.RequestLeaders(mapChallengeModeID) end function C_ChallengeMode.Reset() end function C_ChallengeMode.SlotKeystone() end ---@return boolean success function C_ChallengeMode.StartChallengeMode() end ---@class ChallengeModeCompletionMemberInfo ---@field memberGUID WOWGUID ---@field name string ChallengeModeCompletionMemberInfo = {} ---@class ChallengeModeGuildAttemptMember ---@field name string ---@field classFileName cstring ChallengeModeGuildAttemptMember = {} ---@class ChallengeModeGuildTopAttempt ---@field name string ---@field classFileName cstring ---@field keystoneLevel number ---@field mapChallengeModeID number ---@field isYou boolean ---@field members ChallengeModeGuildAttemptMember ChallengeModeGuildTopAttempt = {}
0
0.766203
1
0.766203
game-dev
MEDIA
0.923226
game-dev
0.762291
1
0.762291
wangtaoking1/texaspoker
16,586
branches/mlearning/run_area/works/source/AdvancedAI/AdvancedAI.java
package AdvancedAI; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import utils.BetState; import utils.CardGroup; import utils.Color; import utils.Constants; import utils.MaxCardComputer; import utils.Poker; import utils.SuperAI; public class AdvancedAI extends SuperAI { private int foldCounter = 0; // 用来计算fold的局数 public AdvancedAI(String playerID) { super(playerID); } private int getIndex(Color color) { switch (color) { case SPADES: return 0; case HEARTS: return 1; case CLUBS: return 2; case DIAMONDS: return 3; default: break; } return 0; } private String fold(ArrayList<BetState> betStates) { // String colors[] = { "SPADES", // 黑桃 // "HEARTS", // 红桃 // "CLUBS", // 梅花 // "DIAMONDS" // 方片 // }; // String logName = "/home/wenzhu/area/fold_log.txt"; // try { // FileWriter writer = new FileWriter(logName, true); // foldCounter ++; // writer.write("fold " + Integer.toString(foldCounter) + "\n"); // writer.write("Current Hand Number: " + Integer.toString(this.getHandNum()) + "\n"); // writer.write("Hold pokers:\n"); // ArrayList<Poker> hp = this.getHoldPokers(); // for (int i = 0; i < hp.size(); i++) // writer.write(colors[getIndex(hp.get(i).getColor())] + " " // + hp.get(i).getValue() + "\n"); // // writer.write("Public pokers:\n"); // ArrayList<Poker> pp = this.getPublicPokers(); // for (int i = 0; i < pp.size(); i++) // writer.write(colors[getIndex(pp.get(i).getColor())] + " " // + pp.get(i).getValue() + "\n"); // // int maxBet = this.getMaxBet(betStates); // int selfBet = this.getSelfBet(betStates); // int diff = maxBet - selfBet; // writer.write("MaxBet: " + Integer.toString(maxBet) + "\n"); // writer.write("SelfBet " + Integer.toString(selfBet) + "\n"); // writer.write("Diff: " + Integer.toString(diff) + "\n"); // writer.write("Rest Jetton: " // + Integer.toString(this.getTotalJetton()) + "\n"); // writer.write("Rest Money: " // + Integer.toString(this.getTotalMoney()) + "\n"); // writer.write("Money and Jetton: " // + Integer.toString(this.getTotalMoneyAndJetton()) + "\n"); // writer.close(); // } catch (IOException e) { // e.printStackTrace(); // } finally { // } return "fold"; } @Override public String thinkAfterHold(ArrayList<BetState> betStates) { ArrayList<Poker> hp = this.getHoldPokers(); // 计算自己与最大押注的差距,得出需要押注的大小 int maxBet = this.getMaxBet(betStates); int selfBet = this.getSelfBet(betStates); int diff = (maxBet - selfBet); int maxBlindBet = Constants.HIGH_BET_MULTIPLE * this.getBlind(); // 可接受(跟注)最大下注筹码 int midBlindBet = Constants.MIDDLE_BET_MULTIPLE * this.getBlind(); // 可接受(跟注)中等下注筹码 // 如果手牌是大对:AA, KK, QQ, JJ, 1010等 if (this.isHoldBigPair(hp)) { int raise_bet = Constants.LOW_RAISE_MULTIPLE * this.getBlind(); // 如果需要加注的筹码小于"BLIND_RAISE_MULTIPLE * 盲注金额", 则自己加注至 // "BLIND_RAISE_MULTIPLE * 盲注金额" if (diff < raise_bet) { if (raise_bet - diff > this.getTotalJetton()) return "all_in"; else return "raise " + Integer.toString(raise_bet - diff); } // 如果需要加注的筹码大于"BLIND_RAISE_MULTIPLE * 盲注金额"时,不加注,但跟注 else return callByDiff(diff); } // 其它牌的情况,如果需要下注超过可打接受最大下注金额,弃牌 else if (diff >= maxBlindBet) return fold(betStates); // 需要跟注的筹码大于剩余总金币与筹码的一个比例时则弃牌(相对于剩余的金币与筹码来说,下注太多了,比较保守的做法的就是弃牌) // else if (diff * Constants.MAX_TOTAL_MULTIPLE > this // .getTotalMoneyAndJetton()) // return fold(betStates); // 手牌是小对:2~9中的一对 else if (this.isHoldSmallPair(hp)) { // 如果需要下注小于可接受最大下注金额,则跟注 if (diff <= maxBlindBet) return callByDiff(diff); } // 手牌不相等且都大于GAP_VALUE else if (this.isHoldBig(hp)) { // 如果需要下注小于可接受中等下注金额,则跟注 if (diff <= midBlindBet) return callByDiff(diff); else return fold(betStates); } // 手牌其中有一个大于GAP_VALUE else if (hp.get(0).getValue() >= Constants.GAP_VALUE || hp.get(0).getValue() >= Constants.GAP_VALUE) { // 如果需要下注小于可接受中等下注金额且(手牌同花色(有可能组成同花)或者相差小于4(有可能组成顺子)) if (diff <= midBlindBet) { if (this.isHoldSameColor(hp) || this.isHoldLessThanFour(hp) || (hp.get(0).getValue() >= 11 || hp.get(1).getValue() >= 11)) return callByDiff(diff); } else return fold(betStates); } return fold(betStates); } /** * 判断手牌是否相差小于等于4(有可能组成顺子) * * @param hp * @return */ private boolean isHoldLessThanFour(ArrayList<Poker> hp) { // 其中有一张为A if (hp.get(0).getValue() == 14 || hp.get(1).getValue() == 14) return Math.abs(hp.get(0).getValue() - hp.get(1).getValue()) % 13 <= 4 ? true : false; else if (Math.abs(hp.get(0).getValue() - hp.get(1).getValue()) <= 4) return true; return false; } /** * 手牌都大于或等于10 * * @param hp * @return */ private boolean isHoldBig(ArrayList<Poker> hp) { if (hp.get(0).getValue() >= Constants.GAP_VALUE && hp.get(1).getValue() >= Constants.GAP_VALUE) return true; return false; } private boolean isHoldSmall(ArrayList<Poker> hp) { if (hp.get(0).getValue() < Constants.GAP_VALUE && hp.get(1).getValue() < Constants.GAP_VALUE) return true; return false; } /** * 判断手牌是否同花色 * * @param hp * @return */ private boolean isHoldSameColor(ArrayList<Poker> hp) { if (hp.get(0).getColor() == hp.get(1).getColor()) return true; return false; } /** * 跟注 * * @param diff * @return */ private String callByDiff(int diff) { // 不需要跟注的时候,则让牌(check) if (diff == 0) return "check"; // 剩余筹码足够,则跟注 else if (diff < this.getTotalJetton()) return "call"; // 剩余筹码不够,则全押 else return "all_in"; } /** * 获取本手牌已下注的玩家下的最大注 * * @param betStates * @return */ private int getMaxBet(ArrayList<BetState> betStates) { int maxBet = 0; for (int i = 0; i < betStates.size(); i++) { if (betStates.get(i).getBet() > maxBet) maxBet = betStates.get(i).getBet(); } return maxBet; } /** * 获取本手牌自己已下注的筹码 * * @param betStates * @return */ private int getSelfBet(ArrayList<BetState> betStates) { for (int i = 0; i < betStates.size(); i++) { if (betStates.get(i).getPlayerID() == this.getPlayerID()) return betStates.get(i).getBet(); } return 0; } /** * 发出三张公共牌之后思考策略 * * @param betStates * 各玩家的当前押注状态 * @return 押注策略 "check|call|raise num|all_in|fold" */ @Override public String thinkAfterFlop(ArrayList<BetState> betStates) { ArrayList<Poker> hp = this.getHoldPokers(); ArrayList<Poker> pp = this.getPublicPokers(); CardGroup maxGroup = (new MaxCardComputer(hp, pp)).getMaxCardGroup(); int maxBet = this.getMaxBet(betStates); int selfBet = this.getSelfBet(betStates); int diff = (maxBet - selfBet); long power = maxGroup.getPower(); // 一对 if (power > (long) 2 * Math.pow(10, 10) && power < (long) 3 * Math.pow(10, 10)) { // 手牌是大对 if (isHoldBigPair(hp)) return callByDiff(diff); // 手牌是小对 else if (isHoldSmallPair(hp)) { if (diff <= Constants.HIGH_BET_MULTIPLE * this.getBlind()) return callByDiff(diff); else return fold(betStates); } // 手牌不是对,说明公共牌有一对 else { if (hp.get(0).getValue() >= Constants.GAP_VALUE || hp.get(1).getValue() >= Constants.GAP_VALUE) { if (diff < Constants.MIDDLE_BET_MULTIPLE * this.getBlind()) return callByDiff(diff); else return fold(betStates); } // 两张牌都是小牌 else if (diff <= Constants.LOW_BET_MULTIPLE) return callByDiff(diff); else return fold(betStates); } } // 两对 else if (power > (long) 3 * Math.pow(10, 10) && power < (long) 4 * Math.pow(10, 10)) { // 手牌是大对,说明另一对是公共牌中出现的,这种情况相当于只有一对 if (this.isHoldBigPair(hp)) { if (diff >= Constants.HIGH_BET_MULTIPLE * this.getBlind()) { // 剩余金币与筹码还比较多,使用比较积极的打法 if (diff * Constants.MAX_TOTAL_MULTIPLE < this .getTotalMoneyAndJetton()) return callByDiff(diff); else return fold(betStates); } return callByDiff(diff); } // 手牌是小对 else if (this.isHoldSmallPair(hp)) { if (diff <= Constants.MIDDLE_BET_MULTIPLE * this.getBlind()) return callByDiff(diff); else return fold(betStates); } // 手牌不相等,说明此时是与公共牌中的两张牌组成两对 else { // 两对都是大对 if (this.isHoldBig(hp)) { return this .raiseByDiff(diff, Constants.HIGH_RAISE_MULTIPLE); } // 其中一个是大对 else if (hp.get(0).getValue() >= Constants.GAP_VALUE || hp.get(1).getValue() >= Constants.GAP_VALUE) { return this.raiseByDiff(diff, Constants.MIDDLE_RAISE_MULTIPLE); } // 两对都是小对 else { if (diff <= Constants.HIGH_BET_MULTIPLE * this.getBlind()) return callByDiff(diff); else return fold(betStates); } } } // 三条 else if (power > (long) 4 * Math.pow(10, 10) && power < (long) 5 * Math.pow(10, 10)) { // 手牌相等 if (hp.get(0).getValue() == hp.get(1).getValue()) { return raiseByDiff(diff, Constants.HIGH_RAISE_MULTIPLE); // 加高倍注 } // 手牌不相等,说明三条中的两个是在公共牌里的 else { return raiseByDiff(diff, Constants.MIDDLE_RAISE_MULTIPLE); // 加中倍注 } } // 顺子及以上 else if (power > (long) 5 * Math.pow(10, 10)) { return raiseByDiff(diff, Constants.HIGH_RAISE_MULTIPLE); // 加高倍注 } // 在当前剩余金币与筹码总和下,下注太多,弃牌 if (diff * Constants.MAX_TOTAL_MULTIPLE > this.getTotalMoneyAndJetton()) return fold(betStates); // 同花或顺子差一张 else if (this.computeFlush(hp, pp) <= 1 || this.computeStraight(hp, pp) <= 1) { if (diff <= Constants.MIDDLE_BET_MULTIPLE * this.getBlind()) return callByDiff(diff); else return fold(betStates); } // 高牌 else if (this.isHoldBig(hp)) { if (diff <= Constants.LOW_BET_MULTIPLE * this.getBlind()) return callByDiff(diff); else return fold(betStates); } else if (diff == 0) return "check"; return fold(betStates); } /** * 加注:加注金额为mutiple * blind * * @param diff * 根据前面玩家下注,需要跟注的最小数量 * @param multiple * @return */ private String raiseByDiff(int diff, int multiple) { if (diff < multiple * this.getBlind()) return "raise " + Integer.toString(multiple * this.getBlind() - diff); else return "call"; } /** * 发出一张转牌之后思考策略 * * @param betStates * 各玩家的当前押注状态 * @return 押注策略 "check|call|raise num|all_in|fold" */ @Override public String thinkAfterTurn(ArrayList<BetState> betStates) { return thinkAfterFlop(betStates); // ArrayList<Poker> hp = this.getHoldPokers(); // ArrayList<Poker> pp = this.getPublicPokers(); // CardGroup maxGroup = (new MaxCardComputer(hp, pp)).getMaxCardGroup(); // // int diff = this.computeDifference(betStates); // int bet = 0; // if (maxGroup.getPower() > (long) 3 * Math.pow(10, 10)) { // // 两对及两对以上 // if (diff >= this.getTotalJetton()) // return "all_in"; // else if (diff == 0) // return "raise " + 3 * this.getBlind(); // else // return "call"; // } else if (this.computeFlush(hp, pp) <= 1 // || this.computeStraight(hp, pp) <= 1) { // // 同花或顺子差一张 // if (diff >= 5 * this.getBlind()) // return fold(betStates); // else if (diff == 0) // return "check"; // else if (diff > this.getTotalJetton()) // return "all_in"; // else // return "call"; // } else if (this.isOneMaxPair(maxGroup, hp)) { // // 最大对子 // if (diff >= 3 * this.getBlind()) // return fold(betStates); // else if (diff == 0) // return "check"; // else if (diff > this.getTotalJetton()) // return "all_in"; // else // return "call"; // } else { // if (diff == 0) // return "check"; // else // return fold(betStates); // } } /** * 发出一张河牌之后思考策略 * * @param betStates * 各玩家的当前押注状态 * @return 押注策略 "check|call|raise num|all_in|fold" */ @Override public String thinkAfterRiver(ArrayList<BetState> betStates) { return thinkAfterFlop(betStates); // ArrayList<Poker> hp = this.getHoldPokers(); // ArrayList<Poker> pp = this.getPublicPokers(); // CardGroup maxGroup = (new MaxCardComputer(hp, pp)).getMaxCardGroup(); // // int diff = this.computeDifference(betStates); // int bet = 0; // if (maxGroup.getPower() > (long) 3 * Math.pow(10, 10)) { // // 两对及两对以上 // if (diff >= this.getTotalJetton()) // return "all_in"; // else if (diff == 0) // return "raise " + 3 * this.getBlind(); // else // return "call"; // } else if (this.computeFlush(hp, pp) <= 1 // || this.computeStraight(hp, pp) <= 1) { // // 同花或顺子差一张 // if (diff >= 5 * this.getBlind()) // return fold(betStates); // else if (diff == 0) // return "check"; // else if (diff > this.getTotalJetton()) // return "all_in"; // else // return "call"; // } else if (this.isOneMaxPair(maxGroup, hp)) { // // 最大对子 // if (diff >= 3 * this.getBlind()) // return fold(betStates); // else if (diff == 0) // return "check"; // else if (diff > this.getTotalJetton()) // return "all_in"; // else // return "call"; // } else { // if (diff == 0) // return "check"; // else // return fold(betStates); // } } /** * 计算自己与其他押最大注玩家的差距,用于决定自己押注的多少 * * @param betStates * @return */ private int computeDifference(ArrayList<BetState> betStates) { int maxBet = 0, selfBet = 0; for (int i = 0; i < betStates.size(); i++) { if (betStates.get(i).getBet() > maxBet) maxBet = betStates.get(i).getBet(); if (betStates.get(i).getPlayerID() == this.getPlayerID()) selfBet = betStates.get(i).getBet(); } return (maxBet - selfBet); } /** * 判断手牌是否是大对:AA, KK, QQ, JJ, 1010等 * * @param hp * 手牌 * @return 大对返回true, 否则返回false */ private boolean isHoldBigPair(ArrayList<Poker> hp) { // 避免出错 if (hp == null || hp.size() < 2) return false; // 手牌是大对:AA, KK, QQ, JJ, 1010等 else if (hp.get(0).getValue() == hp.get(1).getValue() && hp.get(0).getValue() >= 10) return true; return false; } /** * 判断手牌是否是小对:2~9中的一对 * * @param hp * 手牌 * @return 小对返回true,否则返回false */ private boolean isHoldSmallPair(ArrayList<Poker> hp) { // 避免出错 if (hp == null || hp.size() < 2) return false; // 手牌是大对:AA, KK, QQ, JJ, 1010等 else if (hp.get(0).getValue() == hp.get(1).getValue() && hp.get(0).getValue() < 10) return true; return false; } /** * 根据两张底牌判断是否应该弃牌 * * @param holdPokers * @return */ private boolean shouldFold(ArrayList<Poker> hp) { int v1 = hp.get(0).getValue(); int v2 = hp.get(1).getValue(); // 两张牌都小于10且不可能组成顺子,弃牌 if ((v1 < 10 && v2 < 10) && Math.abs(v1 - v2) > 4) return true; return false; } /** * 计算当前牌组成同花最少还差多少张 * * @param backPokers * @param publicPokers * @return */ private int computeFlush(ArrayList<Poker> holdPokers, ArrayList<Poker> publicPokers) { int count[] = new int[4]; for (Poker p : holdPokers) { switch (p.getColor()) { case SPADES: count[0]++; break; case HEARTS: count[1]++; break; case CLUBS: count[2]++; break; case DIAMONDS: count[3]++; break; } } for (Poker p : publicPokers) { switch (p.getColor()) { case SPADES: count[0]++; break; case HEARTS: count[1]++; break; case CLUBS: count[2]++; break; case DIAMONDS: count[3]++; break; } } int maxCount = 0; for (int i = 0; i < count.length; i++) if (count[i] > maxCount) maxCount = count[i]; return 5 - maxCount; } /** * 计算当前牌组成顺子最少需要多少张牌 * * @param holdPokers * @param publicPokers * @return */ private int computeStraight(ArrayList<Poker> holdPokers, ArrayList<Poker> publicPokers) { boolean visited[] = new boolean[15]; for (int i = 0; i < visited.length; i++) visited[i] = false; // 将所有出现的牌值标记 for (Poker poker : holdPokers) { if (poker.getValue() == 14) { visited[1] = visited[14] = true; } else { visited[poker.getValue()] = true; } } for (Poker poker : publicPokers) { if (poker.getValue() == 14) { visited[1] = visited[14] = true; } else { visited[poker.getValue()] = true; } } int maxCount = 0; for (int i = 1; i <= 10; i++) { int count = 0; for (int j = 0; j < 5; j++) { if (visited[i + j]) { count++; } } if (count > maxCount) { maxCount = count; } } return 5 - maxCount; } /** * 如果为一对,判断是否为最大对 * * @param group * @return */ private boolean isOneMaxPair(CardGroup group, ArrayList<Poker> hp) { if ((group.getPower() / (long) Math.pow(10, 10)) != 2) { return false; } boolean flag = false; for (Poker poker : hp) { if (poker.getValue() == group.getPokers().get(0).getValue()) { flag = true; break; } } return flag; } }
0
0.840434
1
0.840434
game-dev
MEDIA
0.83812
game-dev
0.911078
1
0.911078
LordOfDragons/dragengine
6,651
src/modules/scripting/dragonscript/scripts/behaviortree/BTConditionParameterTableInt.ds
/* * 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. */ namespace Dragengine.BehaviorTreeSystem pin Dragengine.Scenery pin Dragengine.Utils /** * \brief Behavior tree condition evaluating an integer parameter table entry. * * Compares the value of a parameter table entry against a static value or another parameter * table entry. */ class BTConditionParameterTableInt implements BTCondition /** \brief Compare operator. */ public enum Operator /** \brief Entry is equal to value. */ equal /** \brief Entry is not equal to value. */ notEqual /** \brief Entry is less than value. */ lessThan /** \brief Entry is less than or equal to value. */ lessThanOrEqual /** \brief Entry is greater than value. */ greaterThan /** \brief Entry is greater than or equal to value. */ greaterThanOrEqual end var ParameterTableEntry pEntry var int pDefaultValue var Operator pOperator var ParameterTableEntry pEntryCompareValue var int pCompareValue var String pParameterNameCompareValue /** \brief Create condition. */ func new(ParameterTableEntry entry, int defaultValue, Operator operator, int compareValue) \ this(entry, defaultValue, operator, null, compareValue, null) end /** \brief Create condition. */ func new(ParameterTableEntry entry, int defaultValue, Operator operator, \ int compareValue, String parameterNameCompareValue) \ this(entry, defaultValue, operator, null, compareValue, parameterNameCompareValue) end /** \brief Create condition. */ func new(ParameterTableEntry entry, int defaultValue, Operator operator, \ ParameterTableEntry entryCompareValue, int compareValue, String parameterNameCompareValue) if entry == null throw EInvalidParam.new() end pEntry = entry pDefaultValue = defaultValue pOperator = operator pEntryCompareValue = entryCompareValue pCompareValue = compareValue pParameterNameCompareValue = parameterNameCompareValue end /** \brief Parameter table entry to compare. */ func ParameterTableEntry getEntry() return pEntry end /** \brief Set parameter table entry to compare. */ func void setEntry(ParameterTableEntry entry) if entry == null throw EInvalidParam.new() end pEntry = entry end /** \brief Default value if entry to compare is not null. */ func int getDefaultValue() return pDefaultValue end /** \brief Set default value if entry to compare is not null. */ func void setDefaultValue(int defaultValue) pDefaultValue = defaultValue end /** \brief Compare operator from eOperators. */ func Operator getOperator() return pOperator end /** \brief Set compare operator from eOperators. */ func void setOperator(Operator operator) pOperator = operator end /** \brief Parameter table entry to compare against. */ func ParameterTableEntry getEntryCompareValue() return pEntryCompareValue end /** \brief Set parameter table entry to compare against. */ func void setEntryCompareValue(ParameterTableEntry entry) pEntryCompareValue = entry end /** \brief Default compare against value. */ func int getCompareValue() return pCompareValue end /** \brief Set default compare against value. */ func void setCompareValue(int compareValue) pCompareValue = compareValue end /** \brief Use named parameter as source of compare value if not null. */ func String getParameterNameCompareValue() return pParameterNameCompareValue end /** \brief Use named parameter as source of compare value if not null. */ func void setParameterNameCompareValue(String name) pParameterNameCompareValue = name end /** \brief Create condition testing the exact opposite. */ func BTConditionParameterTableInt negated() var Operator operator = pOperator select operator case Operator.equal operator = Operator.notEqual case Operator.notEqual operator = Operator.equal case Operator.lessThan operator = Operator.greaterThanOrEqual case Operator.lessThanOrEqual operator = Operator.greaterThan case Operator.greaterThan operator = Operator.lessThanOrEqual case Operator.greaterThanOrEqual operator = Operator.lessThan end return BTConditionParameterTableInt.new(pEntry, pDefaultValue, \ operator, pEntryCompareValue, pCompareValue, \ pParameterNameCompareValue) end /** * \brief Evaluate condition. * \param parameters Dictionary with parameters of type String key and String value. * Do not change the content of the dictionary as it is shared. */ func bool evaluateCondition(BTContext context, Dictionary parameters) var int compareValue = pCompareValue if pEntryCompareValue != null compareValue = pEntryCompareValue.getValue(compareValue) end if pParameterNameCompareValue != null var String value = parameters.getAt(pParameterNameCompareValue, null) cast String if value != null compareValue = value.toInt() end end select pOperator case Operator.equal return pEntry.getValue(pDefaultValue) == compareValue case Operator.notEqual return pEntry.getValue(pDefaultValue) != compareValue case Operator.lessThan return pEntry.getValue(pDefaultValue) < compareValue case Operator.lessThanOrEqual return pEntry.getValue(pDefaultValue) <= compareValue case Operator.greaterThan return pEntry.getValue(pDefaultValue) > compareValue case Operator.greaterThanOrEqual return pEntry.getValue(pDefaultValue) >= compareValue else return false end end end
0
0.900578
1
0.900578
game-dev
MEDIA
0.190779
game-dev
0.894377
1
0.894377
abagames/crisp-game-lib
4,430
docs/scrambird/main.js
title = "SCRAMBIRD"; description = ` [Tap] Fly & Shoot `; characters = [ ` rr rr yrry yrry y y y y `, ` bbbb bbbbbb bbbb r r r r `, ` pp l ll rlrrl rllll lr `, ` l ll rlrrl rllll l lr pp `, ` l l `, ]; options = { theme: "pixel", isPlayingBgm: true, isReplayEnabled: true, seed: 3000, }; /** @type {{x: number, height: number}[]} */ let walls; let wallHeight; let wallHeightVel; /** @type {{pos: Vector, launchTicks: number}[]} */ let missiles; /** @type {Vector[]} */ let tanks; let nextTankDist; /** @type {{pos: Vector, vy: number}} */ let ship; /** @type {Vector[]} */ let shots; /** @type {{pos: Vector, vel: Vector}[]} */ let bombs; let fuel; let multiplier; function update() { if (!ticks) { walls = times(11, (i) => { return { x: i * 10, height: 10 }; }); wallHeight = 10; wallHeightVel = 0; missiles = []; tanks = []; nextTankDist = 10; ship = { pos: vec(10, 50), vy: 0 }; shots = []; bombs = []; fuel = 50; multiplier = 1; } const scr = difficulty * 0.3; /** @type {Color} */ // @ts-ignore const wallColor = ["purple", "blue", "green", "red"][floor(ticks / 420) % 4]; color(wallColor); walls.forEach((w) => { w.x -= scr; if (w.x < -10) { w.x += 110; wallHeight += wallHeightVel; if ( (wallHeight < 10 && wallHeightVel < 0) || (wallHeight > 50 && wallHeightVel > 0) ) { wallHeightVel *= -1; wallHeight += wallHeightVel; } else if (rnd() < 0.2) { wallHeightVel = 0; } else if (rnd() < 0.3) { wallHeightVel = rnd() < 0.5 ? -10 : 10; } w.height = wallHeight; nextTankDist--; if (nextTankDist < 0) { tanks.push(vec(w.x + 5, 90 - w.height - 3)); nextTankDist = rnd(1, 16); } else if (rnd() < 0.5) { missiles.push({ pos: vec(w.x + 5, 90 - w.height - 3), launchTicks: rnd() < 0.5 / sqrt(difficulty) ? 9999 : rnd(200, 300) / difficulty, }); } } rect(w.x, 90 - w.height, 9, w.height); rect(w.x, 0, 9, 5); }); color("black"); if (input.isJustPressed) { play(fuel > 0 ? "laser" : "hit"); ship.vy -= difficulty * (fuel > 0 ? 0.5 : 0.1); shots.push(vec(ship.pos)); bombs.push({ pos: vec(ship.pos), vel: vec(2 * sqrt(difficulty), 0) }); } ship.vy += 0.015 * difficulty; ship.vy *= 0.98; ship.pos.y += ship.vy; if ( char(addWithCharCode("c", ship.vy < 0 ? 0 : 1), ship.pos).isColliding.rect[ wallColor ] ) { play("explosion"); end(); } color("red"); particle(ship.pos.x - 2, ship.pos.y, 0.5, 0.5, PI, PI / 5); remove(shots, (s) => { s.x += 2 * sqrt(difficulty); if (char("e", s).isColliding.rect[wallColor]) { return true; } return s.x > 103; }); color("cyan"); remove(bombs, (b) => { b.vel.y += 0.1 * difficulty; b.vel.mul(0.9); b.pos.add(b.vel); if (bar(b.pos, 2, 2, b.vel.angle).isColliding.rect[wallColor]) { return true; } }); remove(missiles, (m) => { m.pos.x -= scr; m.launchTicks--; if (m.launchTicks < 0) { m.pos.y -= difficulty * 0.5; } color("black"); const c = char("a", m.pos).isColliding; if (c.char.e || c.rect.cyan) { play("hit"); color("red"); particle(m.pos); addScore(multiplier, m.pos); multiplier++; return true; } if (c.char.c || c.char.d) { play("explosion"); end(); } if (m.pos.x < -3 || m.pos.y < -3) { if (multiplier > 1) { multiplier--; } return true; } }); color("black"); remove(tanks, (t) => { t.x -= scr; const c = char("b", t).isColliding; if (c.char.e || c.rect.cyan) { play("powerUp"); color("blue"); particle(t); fuel = clamp(fuel + 10, 0, 50); return true; } if (c.char.c || c.char.d) { play("explosion"); end(); } return t.x < -3; }); color("transparent"); remove(shots, (s) => { const c = char("e", s).isColliding.char; return c.a || c.b; }); remove(bombs, (b) => { const c = bar(b.pos, 2, 2, b.vel.angle).isColliding.char; return c.a || c.b; }); fuel = clamp(fuel - difficulty * 0.025, 0, 50); color("yellow"); text("FUEL", 10, 93); rect(40, 90, fuel, 6); color("blue"); rect(40 + fuel, 90, 50 - fuel, 6); }
0
0.892763
1
0.892763
game-dev
MEDIA
0.91732
game-dev
0.705865
1
0.705865
taraniselsu/TacLifeSupport
4,565
Source/GameSettings.cs
/** * Thunder Aerospace Corporation's Life Support for Kerbal Space Program. * Written by Taranis Elsu. * * (C) Copyright 2013, Taranis Elsu * * Kerbal Space Program is Copyright (C) 2013 Squad. See http://kerbalspaceprogram.com/. This * project is in no way associated with nor endorsed by Squad. * * This code is licensed under the Attribution-NonCommercial-ShareAlike 3.0 (CC BY-NC-SA 3.0) * creative commons license. See <http://creativecommons.org/licenses/by-nc-sa/3.0/legalcode> * for full details. * * Attribution — You are free to modify this code, so long as you mention that the resulting * work is based upon or adapted from this code. * * Non-commercial - You may not use this work for commercial purposes. * * Share Alike — If you alter, transform, or build upon this work, you may distribute the * resulting work only under the same or similar license to the CC BY-NC-SA 3.0 license. * * Note that Thunder Aerospace Corporation is a ficticious entity created for entertainment * purposes. It is in no way meant to represent a real entity. Any similarity to a real entity * is purely coincidental. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Tac { public class TacGameSettings { private const string configNodeName = "SavedGameSettings"; public bool IsNewSave { get; set; } public bool Enabled { get; set; } public bool HibernateInsteadOfKill { get; set; } public double RespawnDelay { get; set; } public Dictionary<string, CrewMemberInfo> knownCrew { get; private set; } public Dictionary<Guid, VesselInfo> knownVessels { get; private set; } public TacGameSettings() { IsNewSave = true; Enabled = true; HibernateInsteadOfKill = false; RespawnDelay = 9203545.0; // 1 Kerbin year (the game's default is too short at only 36 minutes) knownCrew = new Dictionary<string, CrewMemberInfo>(); knownVessels = new Dictionary<Guid, VesselInfo>(); } public void Load(ConfigNode node) { if (node.HasNode(configNodeName)) { ConfigNode settingsNode = node.GetNode(configNodeName); IsNewSave = Utilities.GetValue(settingsNode, "IsNewSave", IsNewSave); Enabled = Utilities.GetValue(settingsNode, "Enabled", Enabled); HibernateInsteadOfKill = Utilities.GetValue(settingsNode, "HibernateInsteadOfKill", HibernateInsteadOfKill); RespawnDelay = Utilities.GetValue(settingsNode, "RespawnDelay", RespawnDelay); knownCrew.Clear(); var crewNodes = settingsNode.GetNodes(CrewMemberInfo.ConfigNodeName); foreach (ConfigNode crewNode in crewNodes) { CrewMemberInfo crewMemberInfo = CrewMemberInfo.Load(crewNode); knownCrew[crewMemberInfo.name] = crewMemberInfo; } knownVessels.Clear(); var vesselNodes = settingsNode.GetNodes(VesselInfo.ConfigNodeName); foreach (ConfigNode vesselNode in vesselNodes) { if (vesselNode.HasValue("Guid")) { Guid id = new Guid(vesselNode.GetValue("Guid")); VesselInfo vesselInfo = VesselInfo.Load(vesselNode); knownVessels[id] = vesselInfo; } } } } public void Save(ConfigNode node) { ConfigNode settingsNode; if (node.HasNode(configNodeName)) { settingsNode = node.GetNode(configNodeName); } else { settingsNode = node.AddNode(configNodeName); } settingsNode.AddValue("IsNewSave", IsNewSave); settingsNode.AddValue("Enabled", Enabled); settingsNode.AddValue("HibernateInsteadOfKill", HibernateInsteadOfKill); settingsNode.AddValue("RespawnDelay", RespawnDelay); foreach (CrewMemberInfo crewMemberInfo in knownCrew.Values) { crewMemberInfo.Save(settingsNode); } foreach (var entry in knownVessels) { ConfigNode vesselNode = entry.Value.Save(settingsNode); vesselNode.AddValue("Guid", entry.Key); } } } }
0
0.876822
1
0.876822
game-dev
MEDIA
0.594599
game-dev
0.767547
1
0.767547
facebookresearch/off-belief-learning
2,510
searchcc/sparta.h
// Copyright (c) Facebook, Inc. and its affiliates. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // #pragma once #include "searchcc/game_sim.h" #include "searchcc/hand_dist.h" #include "searchcc/hybrid_model.h" namespace search { class SpartaActor { public: SpartaActor(int index, std::shared_ptr<rela::BatchRunner> bpRunner, int seed) : index(index) , rng_(seed) , prevModel_(index) , model_(index) { assert(bpRunner != nullptr); model_.setBpModel(bpRunner, getH0(*bpRunner, 1)); } void setPartners(std::vector<std::shared_ptr<SpartaActor>> partners) { partners_ = std::move(partners); } void updateBelief(const GameSimulator& env, int numThread) { assert(callOrder_ == 0); ++callOrder_; const auto& state = env.state(); int curPlayer = state.CurPlayer(); int numPlayer = env.game().NumPlayers(); assert((int)partners_.size() == numPlayer); int prevPlayer = (curPlayer - 1 + numPlayer) % numPlayer; std::cout << "prev player: " << prevPlayer << std::endl; auto [obs, lastMove, cardCount, myHand] = observeForSearch(env.state(), index, hideAction, false); search::updateBelief( prevState_, env.game(), lastMove, cardCount, myHand, partners_[prevPlayer]->prevModel_, index, handDist_, numThread); } void observe(const GameSimulator& env) { // assert(callOrder_ == 1); ++callOrder_; const auto& state = env.state(); model_.observeBeforeAct(env, 0); if (prevState_ == nullptr) { prevState_ = std::make_unique<hle::HanabiState>(state); } else { *prevState_ = state; } } int decideAction(const GameSimulator& env) { // assert(callOrder_ == 2); callOrder_ = 0; prevModel_ = model_; // this line can only be in decide action return model_.decideAction(env, false); } // should be called after decideAction hle::HanabiMove spartaSearch( const GameSimulator& env, hle::HanabiMove bpMove, int numSearch, float threshold); const int index; const bool hideAction = false; private: mutable std::mt19937 rng_; HybridModel prevModel_; HybridModel model_; HandDistribution handDist_; std::vector<std::shared_ptr<SpartaActor>> partners_; std::unique_ptr<hle::HanabiState> prevState_ = nullptr; int callOrder_ = 0; }; } // namespace search
0
0.892986
1
0.892986
game-dev
MEDIA
0.566515
game-dev
0.800783
1
0.800783
LanternPowered/Lantern
2,709
src/main/java/org/lanternpowered/server/item/recipe/crafting/SimpleCraftingMatrix.java
/* * This file is part of LanternServer, licensed under the MIT License (MIT). * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * 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 org.lanternpowered.server.item.recipe.crafting; import org.spongepowered.api.item.inventory.ItemStack; import org.spongepowered.api.item.inventory.crafting.CraftingGridInventory; import javax.annotation.Nullable; final class SimpleCraftingMatrix implements ICraftingMatrix { @Nullable private ItemStack[][] matrix; private final CraftingGridInventory grid; SimpleCraftingMatrix(CraftingGridInventory grid) { this.grid = grid; } @Override public void set(int x, int y, ItemStack itemStack) { if (this.matrix == null) { this.matrix = new ItemStack[this.grid.getColumns()][this.grid.getRows()]; } this.matrix[x][y] = itemStack; } @Override public ItemStack get(int x, int y) { if (this.matrix == null) { this.matrix = new ItemStack[this.grid.getColumns()][this.grid.getRows()]; } ItemStack itemStack = this.matrix[x][y]; if (itemStack == null) { itemStack = this.matrix[x][y] = this.grid.peek(x, y).orElse(ItemStack.empty()); } return itemStack; } @Override public int width() { return this.grid.getColumns(); } @Override public int height() { return this.grid.getRows(); } @Override public CraftingMatrix copy() { return new SimpleCraftingMatrix(this.grid); } }
0
0.726337
1
0.726337
game-dev
MEDIA
0.954594
game-dev
0.774141
1
0.774141
williewillus/Botania
2,793
src/main/java/vazkii/botania/common/item/lens/LensRedirect.java
/** * This class was created by <Vazkii>. It's distributed as * part of the Botania Mod. Get the Source Code in github: * https://github.com/Vazkii/Botania * * Botania is Open Source and distributed under the * Botania License: http://botaniamod.net/license.php * * File Created @ [15/11/2015, 19:13:03 (GMT)] */ package vazkii.botania.common.item.lens; import net.minecraft.entity.projectile.EntityThrowable; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; import vazkii.botania.api.internal.IManaBurst; import vazkii.botania.api.mana.IDirectioned; import vazkii.botania.api.mana.IThrottledPacket; import vazkii.botania.common.core.helper.Vector3; public class LensRedirect extends Lens { @Override public boolean collideBurst(IManaBurst burst, EntityThrowable entity, RayTraceResult pos, boolean isManaBlock, boolean dead, ItemStack stack) { BlockPos coords = burst.getBurstSourceBlockPos(); if(!entity.worldObj.isRemote && pos.entityHit == null && coords.getY() != -1 && (pos.getBlockPos() == null || !pos.getBlockPos().equals(coords))) { TileEntity tile = entity.worldObj.getTileEntity(pos.getBlockPos()); if(tile != null && tile instanceof IDirectioned) { if(!burst.isFake()) { IDirectioned redir = (IDirectioned) tile; Vector3 tileVec = Vector3.fromTileEntityCenter(tile); Vector3 sourceVec = new Vector3(coords.getX() + 0.5, coords.getY() + 0.5, coords.getZ() + 0.5); AxisAlignedBB axis = entity.worldObj.getBlockState(coords).getCollisionBoundingBox(entity.worldObj, coords).offset(coords); if(axis == null) axis = new AxisAlignedBB(coords, coords.add(1, 1, 1)); if(!sourceVec.isInside(axis)) sourceVec = new Vector3(axis.minX + (axis.maxX - axis.minX) / 2, axis.minY + (axis.maxY - axis.minY) / 2, axis.minZ + (axis.maxZ - axis.minZ) / 2); Vector3 diffVec = sourceVec.subtract(tileVec); Vector3 diffVec2D = new Vector3(diffVec.x, diffVec.z, 0); Vector3 rotVec = new Vector3(0, 1, 0); double angle = rotVec.angle(diffVec2D) / Math.PI * 180.0; if(sourceVec.x < tileVec.x) angle = -angle; redir.setRotationX((float) angle + 90F); rotVec = new Vector3(diffVec.x, 0, diffVec.z); angle = diffVec.angle(rotVec) * 180F / Math.PI; if(sourceVec.y < tileVec.y) angle = -angle; redir.setRotationY((float) angle); redir.commitRedirection(); if(redir instanceof IThrottledPacket) ((IThrottledPacket) redir).markDispatchable(); } } } if(!isManaBlock) { dead = false; burst.setMinManaLoss(Math.max(0, burst.getMinManaLoss() - 4)); } return dead; } }
0
0.785392
1
0.785392
game-dev
MEDIA
0.904337
game-dev
0.850012
1
0.850012
discordia-space/CEV-Eris
22,237
code/modules/clothing/head/armor.dm
/obj/item/clothing/head/armor item_state_slots = list( slot_l_hand_str = "helmet", slot_r_hand_str = "helmet", ) body_parts_covered = HEAD | EARS item_flags = THICKMATERIAL flags_inv = HIDEEARS cold_protection = HEAD min_cold_protection_temperature = HELMET_MIN_COLD_PROTECTION_TEMPERATURE heat_protection = HEAD max_heat_protection_temperature = HELMET_MAX_HEAT_PROTECTION_TEMPERATURE siemens_coefficient = 0.6 w_class = ITEM_SIZE_NORMAL price_tag = 100 spawn_tags = SPAWN_TAG_CLOTHING_HEAD_HELMET bad_type = /obj/item/clothing/head/armor style = STYLE_NEG_HIGH style_coverage = COVERS_HAIR /* * Helmets */ /obj/item/clothing/head/armor/helmet name = "helmet" desc = "Standard Security gear. Protects the head from impacts." icon_state = "helmet" armor = list( melee = 7, bullet = 10, energy = 10, bomb = 50, bio = 0, rad = 0 ) matter = list( MATERIAL_STEEL = 5, MATERIAL_PLASTEEL = 1 //a lil bit of plasteel since it's better than handmade shit ) /obj/item/clothing/head/armor/helmet/visor desc = "Standard Security gear. Protects the head from impacts. Has a permanently affixed visor to protect the eyes." icon_state = "helmet_visor" body_parts_covered = HEAD | EARS | EYES matter = list( MATERIAL_STEEL = 5, MATERIAL_PLASTEEL = 1, MATERIAL_GLASS = 2 // costs some glass cause of the visor and the included eye protection ) /obj/item/clothing/head/armor/helmet/merchelm name = "Mercenary Armour Helmet" desc = "A high-quality helmet in a fetching tan. Very durable" icon_state = "merchelm" body_parts_covered = HEAD | EARS | EYES | FACE armor = list( melee = 12, bullet = 12, energy = 12, bomb = 75, bio = 0, rad = 0 ) flash_protection = FLASH_PROTECTION_MODERATE price_tag = 500 style_coverage = COVERS_WHOLE_HEAD /obj/item/clothing/head/armor/helmet/dermal name = "Dermal Armour Patch" desc = "You're not quite sure how you manage to take it on and off, but it implants nicely in your head." icon_state = "dermal" body_parts_covered = HEAD flags_inv = NONE /obj/item/clothing/head/armor/helmet/ironhammer name = "operator helmet" desc = "Ironhammer Security gear. Protects the head from impacts, and the lack of a visor ensures an unhindered aim." icon_state = "helmet_ironhammer" flags_inv = BLOCKHEADHAIR|HIDEEARS /obj/item/clothing/head/armor/helmet/technomancer name = "insulated technomancer helmet" desc = "A piece of armor used in hostile work conditions to protect the head. Comes with a built-in flashlight." description_info = "The appearance of the visor can be changed with a wrench." body_parts_covered = HEAD|EARS|EYES|FACE item_flags = THICKMATERIAL flags_inv = BLOCKHEADHAIR|HIDEEARS|HIDEEYES|HIDEFACE action_button_name = "Toggle Headlamp" light_overlay = "technohelmet_light" brightness_on = 4 armor = list( melee = 7, bullet = 7, energy = 3, bomb = 100, bio = 0, rad = 80 )//Mix between hardhat.dm armor values, helmet armor values in armor.dm, and armor values for TM void helmet in station.dm. flash_protection = FLASH_PROTECTION_MAJOR price_tag = 500 style_coverage = COVERS_WHOLE_HEAD style = STYLE_NONE /obj/item/clothing/head/armor/helmet/technomancer/New() . = ..() icon_state = pick(list("technohelmet_visor", "technohelmet_googles")) /obj/item/clothing/head/armor/helmet/technomancer/attackby(obj/item/W, mob/user) if(QUALITY_BOLT_TURNING in W.tool_qualities) if(icon_state == "technohelmet_visor") icon_state = "technohelmet_googles" to_chat(usr, "You reconfigure the [src]'s visor to look like a pair of goggles.") return else icon_state = "technohelmet_visor" to_chat(usr, "You reconfigure the [src]'s goggles to look like a visor.") return . = ..() /obj/item/clothing/head/armor/helmet/technomancer_old name = "reinforced technomancer helmet" desc = "Technomancer League's ballistic helmet. Comes with a built-in flashlight. The welder-proof visor hinders aim." icon_state = "technohelmet_old" body_parts_covered = HEAD|EARS|EYES|FACE item_flags = THICKMATERIAL flags_inv = BLOCKHEADHAIR|HIDEEARS|HIDEEYES|HIDEFACE action_button_name = "Toggle Headlamp" brightness_on = 4 armor = list( melee = 9, bullet = 9, energy = 9, bomb = 100, bio = 0, rad = 0 ) flash_protection = FLASH_PROTECTION_MAJOR price_tag = 500 /obj/item/clothing/head/armor/helmet/handmade name = "handmade combat helmet" desc = "It looks like it was made from a bucket and some steel. Uncomfortable and heavy but better than nothing." icon_state = "helmet_handmade" armor = list( melee = 7, bullet = 7, energy = 7, bomb = 35, bio = 0, rad = 0 ) price_tag = 75 /obj/item/clothing/head/armor/helmet/scavengerhelmet name = "scavenger helmet" desc = "A sturdy, handcrafted helmet. It's well balanced and sits low on your head, with padding on the inside." icon_state = "scav_helmet" armor = list( melee = 10, bullet = 9, energy = 7, bomb = 35, bio = 0, rad = 0 ) price_tag = 200 /obj/item/clothing/head/armor/helmet/thunderdome name = "\improper Thunderdome helmet" desc = "<i>'Let the battle commence!'</i>" icon_state = "thunderdome" min_cold_protection_temperature = SPACE_HELMET_MIN_COLD_PROTECTION_TEMPERATURE siemens_coefficient = 1 spawn_blacklisted = TRUE /obj/item/clothing/head/armor/bulletproof name = "bulletproof helmet" desc = "A bulletproof helmet that excels in protecting the wearer against traditional projectile weaponry and explosives to a minor extent." icon_state = "bulletproof" body_parts_covered = HEAD | EARS | EYES | FACE armor = list( melee = 7, bullet = 15, energy = 7, bomb = 30, bio = 0, rad = 0 ) price_tag = 400 flags_inv = BLOCKHEADHAIR|HIDEEARS|HIDEEYES|HIDEFACE flash_protection = FLASH_PROTECTION_MINOR matter = list( MATERIAL_STEEL = 8, MATERIAL_PLASTEEL = 2, //Higher plasteel cost since it's booletproof MATERIAL_GLASS = 3 //For the visor parts ) style_coverage = COVERS_WHOLE_HEAD /obj/item/clothing/head/armor/bulletproof/ironhammer_nvg //currently junk-only name = "tactical ballistic helmet" desc = "A bulletproof security helmet that excels in protecting the wearer against traditional projectile weaponry and explosives to a minor extent. \ Comes with inbuilt nightvision HUD." icon_state = "bulletproof_ironhammer" body_parts_covered = HEAD | EARS flags_inv = NONE action_button_name = "Toggle Night Vision" var/obj/item/clothing/glasses/powered/bullet_proof_ironhammer/hud var/last_toggle = 0 var/toggle_delay = 2 SECONDS price_tag = 600 /obj/item/clothing/head/armor/bulletproof/ironhammer_nvg/New() ..() hud = new(src) hud.canremove = FALSE /obj/item/clothing/head/armor/bulletproof/ironhammer_nvg/ui_action_click() if(..()) return TRUE toggle() /obj/item/clothing/head/armor/bulletproof/ironhammer_nvg/verb/toggle() set name = "Toggle Night Vision HUD" set desc = "Allows you to see in the dark." set category = "Object" var/mob/user = loc if(usr.stat || user.restrained()) return if(user.get_equipped_item(slot_head) != src) return if(hud in src) if(user.equip_to_slot_if_possible(hud, slot_glasses) && world.time > last_toggle) to_chat(user, "You flip down [src] night vision goggles with a high-pitched whine.") last_toggle = world.time + toggle_delay hud.toggle(user, TRUE) update_icon() else to_chat(user, "You are wearing something which is in the way or trying to flip the googles too fast!") else if(ismob(hud.loc) && world.time > last_toggle) last_toggle = world.time + toggle_delay var/mob/hud_loc = hud.loc hud_loc.drop_from_inventory(hud, src) hud.toggle(user, TRUE) to_chat(user, "You flip up [src] night vision goggles, turning them off.") hud.forceMove(src) else to_chat(user, "You can't pull off the goggles so fast!") update_icon() usr.update_action_buttons() /obj/item/clothing/head/armor/bulletproof/ironhammer_nvg/dropped(usr) ..() if(hud.loc != src) if(ismob(hud.loc)) var/mob/hud_loc = hud.loc hud_loc.drop_from_inventory(hud, src) to_chat(hud_loc, "[hud] automaticly retract in [src].") hud.forceMove(src) update_icon() /obj/item/clothing/head/armor/bulletproof/ironhammer_nvg/update_icon() if(hud in src) icon_state = "bulletproof_ironhammer" set_light(0, 0) else icon_state = "bulletproof_ironhammer_on" set_light(1, 1, COLOR_LIGHTING_GREEN_MACHINERY) update_wear_icon() ..() /obj/item/clothing/head/armor/bulletproof/ironhammer_full name = "full ballistic helmet" desc = "Standard-issue Ironhammer ballistic helmet with a basic HUD included, covers the operator's entire face." icon_state = "ironhammer_full" item_flags = THICKMATERIAL | COVER_PREVENT_MANIPULATION price_tag = 500 matter = list( MATERIAL_STEEL = 10, // also comes with a hud with it's own prices MATERIAL_PLASTEEL = 2, MATERIAL_GLASS = 2 ) /obj/item/clothing/head/armor/laserproof //TODO: Give it reflection capabilities after refactor name = "ablative helmet" desc = "A ablative security helmet that excels in protecting the wearer against energy and laser projectiles." icon_state = "ablative" body_parts_covered = HEAD | EARS | EYES flags_inv = HIDEEARS | HIDEEYES armor = list( melee = 7, bullet = 7, energy = 16, bomb = 20, bio = 0, rad = 0 ) siemens_coefficient = 0 price_tag = 325 matter = list( MATERIAL_STEEL = 4, // slightly less steel cost MATERIAL_PLASTEEL = 1, MATERIAL_GLASS = 10 // glass is reflective yo, make it cost a lot of it - also, visor ) style_coverage = COVERS_WHOLE_HEAD // toggleable face guard /obj/item/clothing/head/armor/faceshield //We cant just use the armor var to store the original since initial(armor) will return a null pointer var/list/armor_up = list(melee = 0, bullet = 0, energy = 0, bomb = 0, bio = 0, rad = 0) var/list/armor_down = list(melee = 0, bullet = 0, energy = 0, bomb = 0, bio = 0, rad = 0) var/tint_down = TINT_LOW flags_inv = HIDEEARS var/flags_inv_down = HIDEMASK|HIDEEARS|HIDEEYES|HIDEFACE|BLOCKHEADHAIR body_parts_covered = HEAD|EARS var/body_parts_covered_down = HEAD|EARS|EYES|FACE flash_protection = FLASH_PROTECTION_NONE var/flash_protection_down = FLASH_PROTECTION_MINOR action_button_name = "Flip Face Shield" var/up = FALSE bad_type = /obj/item/clothing/head/armor/faceshield style_coverage = COVERS_HAIR|COVERS_EARS /obj/item/clothing/head/armor/faceshield/riot name = "riot helmet" desc = "A helmet specifically designed to protect against close range attacks." icon_state = "riot" armor_up = list(melee = 7, bullet = 5, energy = 5, bomb = 35, bio = 0, rad = 0) armor_down = list(melee = 10, bullet = 8, energy = 7, bomb = 50, bio = 0, rad = 0) item_flags = THICKMATERIAL | COVER_PREVENT_MANIPULATION price_tag = 150 matter = list( MATERIAL_STEEL = 6, // more covered by helmet MATERIAL_PLASTEEL = 2, MATERIAL_GLASS = 6, ) flash_protection_down = FLASH_PROTECTION_MODERATE // used against flash mobs /obj/item/clothing/head/armor/faceshield/Initialize() . = ..() set_is_up(up) /obj/item/clothing/head/armor/faceshield/attack_self() toggle() /obj/item/clothing/head/armor/faceshield/update_icon() icon_state = up ? "[initial(icon_state)]_up" : initial(icon_state) //I wanted to name it set_up() but some how I thought that would be misleading /obj/item/clothing/head/armor/faceshield/proc/set_is_up(is_up) up = is_up if(up) armor = getArmor(arglist(armor_up)) flash_protection = initial(flash_protection) tint = initial(tint) flags_inv = initial(flags_inv) body_parts_covered = initial(body_parts_covered) style_coverage = initial(style_coverage) else armor = getArmor(arglist(armor_down)) flash_protection = flash_protection_down tint = tint_down flags_inv = flags_inv_down body_parts_covered = body_parts_covered_down style_coverage = COVERS_WHOLE_HEAD update_icon() update_wear_icon() //update our mob overlays /obj/item/clothing/head/armor/faceshield/verb/toggle() set category = "Object" set name = "Adjust face shield" set src in usr if(!usr.incapacitated()) src.set_is_up(!src.up) if(src.up) to_chat(usr, "You push the [src] up out of your face.") else to_chat(usr, "You flip the [src] down to protect your face.") usr.update_action_buttons() if(ishuman(usr)) var/mob/living/carbon/human/beingofeyes = usr beingofeyes.update_equipment_vision() /* * Ironhammer riot helmet with HUD */ /obj/item/clothing/head/armor/riot_hud name = "heavy operator helmet" desc = "Standard-issue Ironhammer helmet with a basic HUD and targeting system included." icon_state = "light_riot" tint = TINT_NONE body_parts_covered = HEAD|FACE|EARS armor = list( melee = 16, bullet = 13, energy = 10, bomb = 75, bio = 0, rad = 0 ) item_flags = THICKMATERIAL | COVER_PREVENT_MANIPULATION flags_inv = BLOCKHEADHAIR|HIDEEARS|HIDEEYES|HIDEFACE flash_protection = FLASH_PROTECTION_MINOR action_button_name = "Toggle Security Hud" var/obj/item/clothing/glasses/hud/security/hud price_tag = 500 style_coverage = COVERS_WHOLE_HEAD /obj/item/clothing/head/armor/riot_hud/New() ..() hud = new(src) hud.canremove = FALSE /obj/item/clothing/head/armor/riot_hud/ui_action_click() if(..()) return TRUE toggle() /obj/item/clothing/head/armor/riot_hud/verb/toggle() set name = "Toggle Security Hud" set desc = "Shows you jobs and criminal statuses" set category = "Object" var/mob/user = loc if(usr.stat || user.restrained()) return if(user.get_equipped_item(slot_head) != src) return if(hud in src) if(user.equip_to_slot_if_possible(hud, slot_glasses)) to_chat(user, "You enable security hud on [src].") update_icon() else if(ismob(hud.loc)) var/mob/hud_loc = hud.loc hud_loc.drop_from_inventory(hud, src) to_chat(user, "You disable security hud on [src].") hud.forceMove(src) update_icon() usr.update_action_buttons() /obj/item/clothing/head/armor/riot_hud/dropped(usr) ..() if(hud.loc != src) if(ismob(hud.loc)) var/mob/hud_loc = hud.loc hud_loc.drop_from_inventory(hud, src) to_chat(hud_loc, "[hud] automaticly retract in [src].") hud.forceMove(src) update_icon() /obj/item/clothing/head/armor/riot_hud/update_icon() if(hud in src) icon_state = "light_riot" set_light(0, 0) else icon_state = "light_riot_on" set_light(2, 2, COLOR_LIGHTING_ORANGE_MACHINERY) update_wear_icon() ..() // S E R B I A // /obj/item/clothing/head/armor/steelpot name = "steelpot helmet" desc = "A titanium helmet of serbian origin. Still widely used despite being discontinued." icon_state = "steelpot" armor = list( melee = 10, bullet = 10, energy = 7, bomb = 50, bio = 0, rad = 0 ) // slightly buffed IHS helmet minus energy resistance flags_inv = BLOCKHEADHAIR body_parts_covered = HEAD|EARS siemens_coefficient = 1 /obj/item/clothing/head/armor/faceshield/altyn name = "altyn helmet" desc = "A titanium helmet of serbian origin. Still widely used despite being discontinued." icon_state = "altyn" armor_up = list(melee = 5, bullet = 5, energy = 2, bomb = 30, bio = 0, rad = 0) armor_down = list(melee = 10, bullet = 13, energy = 7, bomb = 50, bio = 0, rad = 0) siemens_coefficient = 1 up = TRUE /obj/item/clothing/head/armor/faceshield/altyn/brown icon_state = "altyn_brown" /obj/item/clothing/head/armor/faceshield/altyn/black icon_state = "altyn_black" /obj/item/clothing/head/armor/faceshield/altyn/maska name = "maska helmet" desc = "\"I do not know who I am, I don\'t know why I\'m here. All I know is that I must kill.\"" icon_state = "maska" armor_down = list( melee = 14, bullet = 15, energy = 7, bomb = 50, bio = 0, rad = 0 ) // superior ballistic protection, mediocre laser protection. /obj/item/clothing/head/armor/faceshield/altyn/maska/tripoloski name = "striped maska helmet" desc = "Someone has painted a Maska in the Gopnik style." icon_state = "altyn_tripoloski" /obj/item/clothing/head/armor/helmet/visor/cyberpunkgoggle name = "\improper Type-34C Semi-Enclosed Headwear" desc = "Civilian model of a popular helmet used by certain law enforcement agencies. It does not have any armor plating, but has a neo-laminated fabric lining." icon_state = "cyberpunkgoggle" flags_inv = HIDEEARS|HIDEEYES|BLOCKHAIR siemens_coefficient = 0.9 //More conductive than most helmets armor = list( melee = 1, bullet = 4, energy = 2, bomb = 0, bio = 0, rad = 0 ) style_coverage = COVERS_FACE|COVERS_HAIR /obj/item/clothing/head/armor/helmet/visor/cyberpunkgoggle/armored name = "\improper Type-34 Semi-Enclosed Headwear" desc = "Armored helmet used by certain law enforcement agencies. It's hard to believe there's a human somewhere behind that." armor = list( melee = 7, bullet = 10, energy = 10, bomb = 30, bio = 0, rad = 0 ) /obj/item/clothing/head/armor/helmet/crusader name = "crusader helmet" desc = "May God guide you." icon_state = "crusader_hemet" item_state = "crusader_hemet" body_parts_covered = HEAD|FACE|EYES|EARS flags_inv = HIDEMASK|HIDEEARS|HIDEEYES|HIDEFACE|BLOCKHAIR matter = list(MATERIAL_BIOMATTER = 15, MATERIAL_PLASTEEL = 5, MATERIAL_STEEL = 5, MATERIAL_GOLD = 1) armor = list( melee = 13, bullet = 13, energy = 13, bomb = 75, bio = 0, rad = 0 ) unacidable = TRUE spawn_blacklisted = TRUE style_coverage = COVERS_WHOLE_HEAD /obj/item/clothing/head/armor/helmet/tanker name = "black tanker helmet" desc = "Protects the head from damage while you are in the exoskeleton." icon_state = "tanker_helmet" item_flags = THICKMATERIAL flags_inv = HIDEEARS|BLOCKHEADHAIR siemens_coefficient = 1 armor = list( melee = 4, bullet = 3, energy = 0, bomb = 0, bio = 0, rad = 0 ) /obj/item/clothing/head/armor/helmet/tanker/green name = "green tanker helmet" icon_state = "tanker_helmet_green" /obj/item/clothing/head/armor/helmet/tanker/brown name = "brown tanker helmet" icon_state = "tanker_helmet_brown" /obj/item/clothing/head/armor/helmet/tanker/gray name = "gray tanker helmet" icon_state = "tanker_helmet_gray" /obj/item/clothing/head/armor/excel_beret name = "Excelsior beret" desc = "An armored white and orange beret, issued out to Haven's many conscripts" icon_state = "excel_beret" item_state = "excel_beret" armor = list( melee = 5, bullet = 4, energy = 5, bomb = 5, bio = 0, rad = 0 ) matter = list( MATERIAL_BIOMATTER = 2, MATERIAL_PLASTIC = 1, MATERIAL_STEEL = 1 ) /obj/item/clothing/head/armor/excel_sfera name = "Excelsior sfera-9 helmet" desc = "The most common Excelsior combat helmet, offers decent enough protection for relative ease of production." icon_state = "spherer_helm" item_state = "spherer_helm" armor = list( melee = 8, bullet = 12, energy = 10, bomb = 25, bio = 0, rad = 0 ) matter = list( MATERIAL_PLASTIC = 2, MATERIAL_GLASS = 2, MATERIAL_STEEL = 3, MATERIAL_PLASTEEL = 2 ) siemens_coefficient = 1 species_restricted = list(SPECIES_HUMAN) price_tag = 150 /obj/item/clothing/head/armor/korund_helm name = "Excelsior sfera-45 helmet" desc = "The most durable and heavy Excelsior helmet to date, for Haven's hardest battles." icon_state = "korund_helm" item_state = "korund_helm" armor = list( melee = 16, bullet = 14, energy = 16, bomb = 95, bio = 0, rad = 0 ) matter = list( MATERIAL_PLASTIC = 40, MATERIAL_GLASS = 10, MATERIAL_STEEL = 25, MATERIAL_PLASTEEL = 10 ) siemens_coefficient = 1 species_restricted = list(SPECIES_HUMAN) price_tag = 150 spawn_blacklisted = TRUE /obj/item/clothing/head/armor/faceshield/paramedic name = "Moebius paramedic helmet" desc = "Seven minutes or a refund." icon_state = "trauma_team" item_state = "trauma_team" flags_inv = HIDEEARS|BLOCKHAIR item_flags = BLOCK_GAS_SMOKE_EFFECT|AIRTIGHT matter = list( MATERIAL_PLASTEEL = 10, MATERIAL_GLASS = 5, MATERIAL_PLASTIC = 5, MATERIAL_PLATINUM = 2 ) armor_up = list( melee = 5, bullet = 5, energy = 5, bomb = 20, bio = 100, rad = 50 ) armor_down = list( melee = 7, bullet = 10, energy = 10, bomb = 50, bio = 100, rad = 50) up = TRUE spawn_blacklisted = TRUE style = STYLE_HIGH tint_down = TINT_NONE var/speaker_enabled = TRUE var/scan_scheduled = FALSE var/scan_interval = 15 SECONDS var/repeat_report_after = 60 SECONDS var/list/crewmembers_recently_reported = list() /obj/item/clothing/head/armor/faceshield/paramedic/equipped(mob/M) . = ..() schedule_scan() /obj/item/clothing/head/armor/faceshield/paramedic/proc/schedule_scan() if(scan_scheduled) return if(!speaker_enabled) return scan_scheduled = TRUE spawn(scan_interval) if(QDELETED(src)) return scan_scheduled = FALSE report_health_alerts() /obj/item/clothing/head/armor/faceshield/paramedic/proc/schedule_memory_cleanup(entry) spawn(repeat_report_after) if(QDELETED(src)) return crewmembers_recently_reported.Remove(entry) /obj/item/clothing/head/armor/faceshield/paramedic/proc/report_health_alerts() if(!speaker_enabled) return if(!ishuman(loc)) return var/mob/living/carbon/human/user = loc var/list/crewmembers = list() var/list/z_levels_to_scan = list(1, 2, 3, 4, 5) for(var/z_level in z_levels_to_scan) crewmembers += crew_repository.health_data(z_level) if(crewmembers.len) for(var/i = 1, i <= crewmembers.len, i++) var/list/entry = crewmembers[i] if(entry["alert"] && !entry["muted"]) if(entry["name"] in crewmembers_recently_reported) continue crewmembers_recently_reported += entry["name"] schedule_memory_cleanup(entry["name"]) to_chat(user, SPAN_WARNING("[src] beeps: '[entry["name"]]'s on-suit sensors broadcast an emergency signal. Access monitoring software for details.'")) schedule_scan() /obj/item/clothing/head/armor/faceshield/paramedic/AltClick() toogle_speaker() /obj/item/clothing/head/armor/faceshield/paramedic/verb/toogle_speaker() set name = "Toogle helmet's speaker" set category = "Object" set src in usr if(speaker_enabled) to_chat(usr, SPAN_WARNING("[src] beeps: 'Notifications disabled.'")) speaker_enabled = FALSE else to_chat(usr, SPAN_WARNING("[src] beeps: 'Notifications enabled.'")) speaker_enabled = TRUE report_health_alerts() schedule_scan()
0
0.966121
1
0.966121
game-dev
MEDIA
0.999668
game-dev
0.665062
1
0.665062
ReciHub/FunnyAlgorithms
2,259
Rat Maze Problem/RatMaze.cpp
/* C/C++ program to solve Rat in a Maze problem using backtracking */ #include <stdio.h> // Maze size #define N 4 bool solveMazeUtil(int maze[N][N], int x, int y, int sol[N][N]); /* A utility function to print solution matrix sol[N][N] */ void printSolution(int sol[N][N]) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) printf(" %d ", sol[i][j]); printf("\n"); } } /* A utility function to check if x, y is valid index for N*N maze */ bool isSafe(int maze[N][N], int x, int y) { // if (x, y outside maze) return false if (x >= 0 && x < N && y >= 0 && y < N && maze[x][y] == 1) return true; return false; } /* This function solves the Maze problem using Backtracking. It mainly uses solveMazeUtil() to solve the problem. It returns false if no path is possible, otherwise return true and prints the path in the form of 1s. Please note that there may be more than one solutions, this function prints one of the feasible solutions.*/ bool solveMaze(int maze[N][N]) { int sol[N][N] = { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }; if (solveMazeUtil(maze, 0, 0, sol) == false) { printf("Solution doesn't exist"); return false; } printSolution(sol); return true; } /* A recursive utility function to solve Maze problem */ bool solveMazeUtil(int maze[N][N], int x, int y, int sol[N][N]) { // if (x, y is goal) return true if (x == N - 1 && y == N - 1) { sol[x][y] = 1; return true; } // Check if maze[x][y] is valid if (isSafe(maze, x, y) == true) { // mark x, y as part of solution path sol[x][y] = 1; /* Move forward in x direction */ if (solveMazeUtil(maze, x + 1, y, sol) == true) return true; /* If moving in x direction doesn't give solution then Move down in y direction */ if (solveMazeUtil(maze, x, y + 1, sol) == true) return true; /* If none of the above movements work then BACKTRACK: unmark x, y as part of solution path */ sol[x][y] = 0; return false; } return false; } // driver program to test above function int main() { int maze[N][N] = { { 1, 0, 0, 0 }, { 1, 1, 0, 1 }, { 0, 1, 0, 0 }, { 1, 1, 1, 1 } }; solveMaze(maze); return 0; }
0
0.697746
1
0.697746
game-dev
MEDIA
0.817248
game-dev
0.934188
1
0.934188
MicrosoftDocs/mslearn-mr-adt-in-unity
1,519
Unity-Project/Assets/NonRelease/AutomatedBuilds/Editor/AutoBuild.cs
using System; using System.Collections.Generic; using System.Linq; using UnityEditor; /// <summary> /// Class used by the automated build process, to execute the build through the command line. /// </summary> public class AutoBuild { /// <summary> /// Build method to create a build for the HoloLens 2. /// </summary> public static void BuildHoloLens2() { string[] autobuildSettingsAssetGuids = AssetDatabase.FindAssets($"t:{nameof(AutoBuildSettings)}"); string path = AssetDatabase.GUIDToAssetPath(autobuildSettingsAssetGuids[0]); AutoBuildSettings settings = AssetDatabase.LoadAssetAtPath(path,typeof(AutoBuildSettings)) as AutoBuildSettings; List<EditorBuildSettingsScene> scenesForBuild = new List<EditorBuildSettingsScene>(); int i = 0; foreach (var scenePath in settings.ScenePathsForBuild) { if (i == settings.StartSceneZeroBasedIndex) scenesForBuild = scenesForBuild.Prepend(new EditorBuildSettingsScene(scenePath, true)).ToList(); //add the start scene at the beginning else scenesForBuild = scenesForBuild.Append(new EditorBuildSettingsScene(scenePath, true)).ToList(); //add all the other scenes at the end i++; } var sceneArray = scenesForBuild.ToArray(); EditorBuildSettings.scenes = sceneArray; BuildPipeline.BuildPlayer(sceneArray, Environment.GetCommandLineArgs().Last(), BuildTarget.WSAPlayer, BuildOptions.None); } }
0
0.715303
1
0.715303
game-dev
MEDIA
0.576999
game-dev
0.801285
1
0.801285
MegaMek/megamek
6,517
megamek/src/megamek/client/ui/dialogs/customMek/APWeaponChoicePanel.java
/* * Copyright (C) 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.client.ui.dialogs.customMek; import java.awt.GridBagLayout; import java.io.Serial; import java.util.ArrayList; import java.util.Iterator; import java.util.Objects; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; import megamek.client.ui.GBC; import megamek.common.CriticalSlot; import megamek.common.battleArmor.BattleArmor; import megamek.common.equipment.EquipmentType; import megamek.common.equipment.Mounted; import megamek.common.equipment.WeaponMounted; import megamek.common.equipment.WeaponType; import megamek.common.exceptions.LocationFullException; import megamek.common.units.Entity; import megamek.logging.MMLogger; /** * A panel that houses a label and a combo box that allows for selecting which anti-personnel weapon is mounted in an AP * mount. * * @author arlith */ public class APWeaponChoicePanel extends JPanel { @Serial private static final long serialVersionUID = 6189888202192403704L; private static final MMLogger LOGGER = MMLogger.create(APWeaponChoicePanel.class); private final Entity entity; private final ArrayList<WeaponType> weaponTypes; private final JComboBox<String> comboChoices; private final Mounted<?> apMounted; public APWeaponChoicePanel(Entity entity, Mounted<?> mounted, ArrayList<WeaponType> weapons) { this.entity = entity; weaponTypes = weapons; apMounted = mounted; EquipmentType equipmentType = null; if ((mounted != null) && (mounted.getLinked() != null)) { equipmentType = mounted.getLinked().getType(); } comboChoices = new JComboBox<>(); comboChoices.addItem("None"); comboChoices.setSelectedIndex(0); Iterator<WeaponType> it = weaponTypes.iterator(); for (int x = 1; it.hasNext(); x++) { WeaponType weaponType = it.next(); comboChoices.addItem(weaponType.getName()); if ((equipmentType != null) && Objects.equals(weaponType.getInternalName(), equipmentType.getInternalName())) { comboChoices.setSelectedIndex(x); } } String labelDescription = ""; if ((mounted != null) && (mounted.getBaMountLoc() != BattleArmor.MOUNT_LOC_NONE)) { labelDescription += " (" + BattleArmor.MOUNT_LOC_NAMES[mounted.getBaMountLoc()] + ')'; } else { labelDescription = "None"; } JLabel labelLocation = new JLabel(labelDescription); GridBagLayout gridBagLayout = new GridBagLayout(); setLayout(gridBagLayout); add(labelLocation, GBC.std()); add(comboChoices, GBC.std()); } public void applyChoice() { int selectedIndex = comboChoices.getSelectedIndex(); // If there's no selection, there's nothing we can do if (selectedIndex == -1) { return; } WeaponType weaponType = null; if ((selectedIndex > 0) && (selectedIndex <= weaponTypes.size())) { // Need to account for the "None" selection weaponType = weaponTypes.get(selectedIndex - 1); } // Remove any currently mounted AP weapon if (apMounted.getLinked() != null && apMounted.getLinked().getType() != weaponType) { Mounted<?> mAPMountedLinked = apMounted.getLinked(); entity.getEquipment().remove(mAPMountedLinked); if (mAPMountedLinked instanceof WeaponMounted weaponMounted) { entity.getWeaponList().remove(weaponMounted); entity.getTotalWeaponList().remove(weaponMounted); } // We need to make sure that the weapon has been removed from the critical slots, otherwise it can cause // issues for (int location = 0; location < entity.locations(); location++) { for (int locationCritical = 0; locationCritical < entity.getNumberOfCriticalSlots(location); locationCritical++) { CriticalSlot criticalSlot = entity.getCritical(location, locationCritical); if (criticalSlot != null && criticalSlot.getMount() != null && criticalSlot.getMount().equals(mAPMountedLinked)) { entity.setCritical(location, locationCritical, null); } } } } // Did the selection not change, or no weapon was selected if ((apMounted.getLinked() != null && apMounted.getLinked().getType() == weaponType) || selectedIndex == 0) { return; } // Add the newly mounted weapon try { Mounted<?> newWeapon = entity.addEquipment(weaponType, apMounted.getLocation()); apMounted.setLinked(newWeapon); newWeapon.setLinked(apMounted); newWeapon.setAPMMounted(true); } catch (LocationFullException ex) { // This shouldn't happen for BA... LOGGER.error(ex, "Location Full"); } } @Override public void setEnabled(boolean enabled) { comboChoices.setEnabled(enabled); } }
0
0.95718
1
0.95718
game-dev
MEDIA
0.908575
game-dev
0.970419
1
0.970419
desertkun/brainout
1,039
server/src/com/desertkun/brainout/content/components/ServerCampFireComponent.java
package com.desertkun.brainout.content.components; import com.badlogic.gdx.utils.Json; import com.badlogic.gdx.utils.JsonValue; import com.desertkun.brainout.content.components.base.ContentComponent; import com.desertkun.brainout.data.components.ServerCampFireComponentData; import com.desertkun.brainout.data.components.base.ComponentObject; import com.desertkun.brainout.reflection.Reflect; import com.desertkun.brainout.reflection.ReflectAlias; @Reflect("content.components.ServerCampFireComponent") public class ServerCampFireComponent extends ContentComponent { private String addFuel; @Override public ServerCampFireComponentData getComponent(ComponentObject componentObject) { return new ServerCampFireComponentData(componentObject, this); } @Override public void write(Json json) { } public String getAddFuel() { return addFuel; } @Override public void read(Json json, JsonValue jsonData) { addFuel = jsonData.getString("addFuel"); } }
0
0.858208
1
0.858208
game-dev
MEDIA
0.949018
game-dev
0.665852
1
0.665852
dune3d/dune3d
1,841
src/document/entity/entity_circle3d.cpp
#include "entity_circle3d.hpp" #include "nlohmann/json.hpp" #include "util/glm_util.hpp" #include "util/json_util.hpp" #include "document/document.hpp" #include "entity_workplane.hpp" #include "entityt_impl.hpp" namespace dune3d { EntityCircle3D::EntityCircle3D(const UUID &uu) : Base(uu) { } EntityCircle3D::EntityCircle3D(const UUID &uu, const json &j) : Base(uu, j), m_center(j.at("center").get<glm::dvec3>()), m_radius(j.at("radius").get<double>()), m_normal(j.at("normal").get<glm::dquat>()) { } json EntityCircle3D::serialize() const { json j = Entity::serialize(); j["center"] = m_center; j["radius"] = m_radius; j["normal"] = m_normal; return j; } double EntityCircle3D::get_param(unsigned int point, unsigned int axis) const { if (point == 0) return m_radius; else if (point == 1) return m_center[axis]; else if (point == 2) return m_normal[axis]; return NAN; } void EntityCircle3D::set_param(unsigned int point, unsigned int axis, double value) { if (point == 0) m_radius = value; else if (point == 1) m_center[axis] = value; else if (point == 2) m_normal[axis] = value; } std::string EntityCircle3D::get_point_name(unsigned int point) const { switch (point) { case 1: return "center"; default: return ""; } } glm::dvec3 EntityCircle3D::get_point(unsigned int point, const Document &doc) const { if (point == 1) return m_center; return {NAN, NAN, NAN}; } bool EntityCircle3D::is_valid_point(unsigned int point) const { return point == 1; } void EntityCircle3D::move(const Entity &last, const glm::dvec3 &delta, unsigned int point) { auto &en_last = dynamic_cast<const EntityCircle3D &>(last); m_center = en_last.m_center + delta; } } // namespace dune3d
0
0.910442
1
0.910442
game-dev
MEDIA
0.501597
game-dev
0.887891
1
0.887891
retro-esp32/RetroESP32
10,751
Components/odroid-go-spectrum-emulator/components/spectrum/vgakey.c
/* * Copyright (C) 1996-1998 Szeredi Miklos * Email: mszeredi@inf.bme.hu * * 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. See the file COPYING. * * 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., 675 Mass Ave, Cambridge, MA 02139, USA. * */ #include "config.h" #include "spkey.h" #include "spkey_p.h" #include "spperif.h" #include "vgascr.h" #include "akey.h" #include <stdlib.h> #include "../odroid/odroid_input.h" #include "../odroid/odroid_audio.h" #include "../odroid/odroid_display.h" #include "../odroid/odroid_ui.h" extern void keyboard_init(); extern void keyboard_close(); extern void keyboard_translatekeys(); extern int keyboard; extern int menu(); extern void kb_blank(); extern void kb_set(); extern int b_up,b_down,b_left,b_right,b_a,b_b,b_start,b_select; int pressed=0; // used for de-bouncing buttons int kbpos=0; // virtual keyboard position const int need_switch_mode = 1; volatile int spvk_after_switch = 0; const int map[40]={ 2,3,4,5,6,7,8,9,10,11, 16,17,18,19,20,21,22,23,24,25, 30,31,32,33,34,35,36,37,38,28, 42,44,45,46,47,48,49,50,54,57 }; #define LASTKEYCODE 111 #define KC_F1 59 #define KC_L_SHIFT 42 #define KC_R_SHIFT 54 #define KC_L_CTRL 29 #define KC_R_CTRL 97 #define KC_L_ALT 56 #define KC_R_ALT 100 static char kbstate[LASTKEYCODE]; extern void DoMenuHome(bool save); extern void draw_keyboard(); extern void setup_buttons(); extern bool use_goemu; extern int my_lastborder; extern int sp_nosync; bool menu_restart = false; int menuButtonFrameCount = -10; void menu_keyboard_update(odroid_ui_entry *entry) { sprintf(entry->text, "%-9s: %s", "keyboard", keyboard?"on":"off"); } odroid_ui_func_toggle_rc menu_keyboard_toggle(odroid_ui_entry *entry, odroid_gamepad_state *joystick) { keyboard=!keyboard; return ODROID_UI_FUNC_TOGGLE_RC_MENU_CLOSE; } void menu_keyboard_configure_update(odroid_ui_entry *entry) { sprintf(entry->text, "%-9s", "keyboard mapping"); } odroid_ui_func_toggle_rc menu_keyboard_configure_toggle(odroid_ui_entry *entry, odroid_gamepad_state *joystick) { if (!joystick->values[ODROID_INPUT_A]) return ODROID_UI_FUNC_TOGGLE_RC_NOTHING; odroid_display_unlock(); odroid_ui_wait_for_key(ODROID_INPUT_A, false); setup_buttons(); odroid_display_lock(); return ODROID_UI_FUNC_TOGGLE_RC_MENU_CLOSE; } void menu_spectrum_init(odroid_ui_window *window) { odroid_ui_create_entry(window, &menu_keyboard_update, &menu_keyboard_toggle); odroid_ui_create_entry(window, &menu_keyboard_configure_update, &menu_keyboard_configure_toggle); } void keyboard_update() { odroid_gamepad_state joystick; int i; for (i=0; i<LASTKEYCODE; i++) kbstate[i]=0; odroid_input_gamepad_read(&joystick); // first, process volume button... //djk //--------------------------------------- if (!pressed && joystick.values[ODROID_INPUT_VOLUME]) { pressed=1; int keyboard_old = keyboard; bool config_speedup_old = config_speedup; menu_restart = odroid_ui_menu_ext(menu_restart, &menu_spectrum_init); my_lastborder=100; if (config_speedup_old != config_speedup) sp_nosync = config_speedup; if (keyboard != keyboard_old) draw_keyboard(); } //--------------------------------------- #ifdef CONFIG_IN_GAME_MENU_YES if(joystick.values[ODROID_INPUT_MENU] && menuButtonFrameCount!=0) { menuButtonFrameCount = 0; printf("\n\n-----------\nYou Pressed MENU\n-----------\n"); DoMenuHome(false); } if(!joystick.values[ODROID_INPUT_MENU]) { menuButtonFrameCount = 1; } #else // 2 different approaches depending if virtual keyboard is actice... if (!keyboard) { if (joystick.values[ODROID_INPUT_UP]) kbstate[map[b_up]]=1; if (joystick.values[ODROID_INPUT_DOWN]) kbstate[map[b_down]]=1; if (joystick.values[ODROID_INPUT_LEFT]) kbstate[map[b_left]]=1; if (joystick.values[ODROID_INPUT_RIGHT]) kbstate[map[b_right]]=1; if (joystick.values[ODROID_INPUT_A]) kbstate[map[b_a]]=1; if (joystick.values[ODROID_INPUT_B]) kbstate[map[b_b]]=1; if (joystick.values[ODROID_INPUT_SELECT]) kbstate[map[b_select]]=1; if (joystick.values[ODROID_INPUT_START]) kbstate[map[b_start]]=1; if (!use_goemu) { if (joystick.values[ODROID_INPUT_MENU]) menu(); } else if (!joystick.values[ODROID_INPUT_MENU] && menuButtonFrameCount!=0) { if (menuButtonFrameCount>1) { DoMenuHome(false); } menuButtonFrameCount = 0; } else if (joystick.values[ODROID_INPUT_MENU]) { menuButtonFrameCount++; if (menuButtonFrameCount > (60 * 1) / 2) { DoMenuHome(true); } } } #endif else { if (!pressed && joystick.values[ODROID_INPUT_UP]) { kb_blank(); kbpos-=10; if (kbpos<0) kbpos+=40; kb_set(); pressed=1; } if (!pressed && joystick.values[ODROID_INPUT_DOWN]) { kb_blank(); kbpos+=10; if (kbpos>39) kbpos-=40; kb_set(); pressed=1; } if (!pressed && joystick.values[ODROID_INPUT_LEFT]) { kb_blank(); kbpos--; if (kbpos%10==9 || kbpos==-1) kbpos+=10; kb_set(); pressed=1; } if (!pressed && joystick.values[ODROID_INPUT_RIGHT]) { kb_blank(); kbpos++; if (kbpos%10==0) kbpos-=10; kb_set(); pressed=1; } if (joystick.values[ODROID_INPUT_A]) kbstate[map[kbpos]]=1; if (joystick.values[ODROID_INPUT_SELECT]) kbstate[map[30]]=1; // CAPS-shift if (joystick.values[ODROID_INPUT_START]) kbstate[map[38]]=1; // sym-shift if (joystick.values[ODROID_INPUT_B] || joystick.values[ODROID_INPUT_MENU]) {keyboard=0; my_lastborder=100;} } if (pressed && !joystick.values[ODROID_INPUT_UP] && !joystick.values[ODROID_INPUT_DOWN] && !joystick.values[ODROID_INPUT_LEFT] && !joystick.values[ODROID_INPUT_RIGHT] && !joystick.values[ODROID_INPUT_VOLUME] ) pressed=0; } static void spkb_init(void) { keyboard_init(); keyboard_translatekeys(); // kbstate = keyboard_getstate(); // bjs not needed now } #define spkb_close() keyboard_close() #define spkb_raw() keyboard_init() #define spkb_normal() keyboard_close() #define spkb_update() keyboard_update() #define kbst(i) kbstate[i] #define SDEMPTY {0, 0} #define SDSPEC(x) {x, x} struct spscan_keydef { unsigned norm; unsigned shifted; }; static struct spscan_keydef sp_cp_keycode[] = { SDEMPTY, SDSPEC(SK_Escape), {'1', '!'}, {'2', '@'}, {'3', '#'}, {'4', '$'}, {'5', '%'}, {'6', '^'}, {'7', '&'}, {'8', '*'}, {'9', '('}, {'0', ')'}, {'-', '_'}, {'=', '+'}, SDSPEC(SK_BackSpace), SDSPEC(SK_Tab), {'q', 'Q'}, {'w', 'W'}, {'e', 'E'}, {'r', 'R'}, {'t', 'T'}, {'y', 'Y'}, {'u', 'U'}, {'i', 'I'}, {'o', 'O'}, {'p', 'P'}, {'[', '{'}, {']', '}'}, SDSPEC(SK_Return), SDSPEC(SK_Control_L), {'a', 'A'}, {'s', 'S'}, {'d', 'D'}, {'f', 'F'}, {'g', 'G'}, {'h', 'H'}, {'j', 'J'}, {'k', 'K'}, {'l', 'L'}, {';', ':'}, {'\'', '"'}, {'`', '~'}, SDSPEC(SK_Shift_L), {'\\', '|'}, {'z', 'Z'}, {'x', 'X'}, {'c', 'C'}, {'v', 'V'}, {'b', 'B'}, {'n', 'N'}, {'m', 'M'}, {',', '<'}, {'.', '>'}, {'/', '?'}, SDSPEC(SK_Shift_R), SDSPEC(SK_KP_Multiply), SDSPEC(SK_Alt_L), {' ', ' '}, SDSPEC(SK_Caps_Lock), SDSPEC(SK_F1), SDSPEC(SK_F2), SDSPEC(SK_F3), SDSPEC(SK_F4), SDSPEC(SK_F5), SDSPEC(SK_F6), SDSPEC(SK_F7), SDSPEC(SK_F8), SDSPEC(SK_F9), SDSPEC(SK_F10), SDSPEC(SK_Num_Lock), SDSPEC(SK_Scroll_Lock), SDSPEC(SK_KP_Home), SDSPEC(SK_KP_Up), SDSPEC(SK_KP_Page_Up), SDSPEC(SK_KP_Subtract), SDSPEC(SK_KP_Left), SDSPEC(SK_KP_5), SDSPEC(SK_KP_Right), SDSPEC(SK_KP_Add), SDSPEC(SK_KP_End), SDSPEC(SK_KP_Down), SDSPEC(SK_KP_Page_Down), SDSPEC(SK_KP_Insert), SDSPEC(SK_KP_Delete), SDEMPTY, SDEMPTY, {'<', '>'}, SDSPEC(SK_F11), SDSPEC(SK_F12), SDEMPTY, SDEMPTY, SDEMPTY, SDEMPTY, SDEMPTY, SDEMPTY, SDEMPTY, SDSPEC(SK_KP_Enter), SDSPEC(SK_Control_R), SDSPEC(SK_KP_Divide), SDSPEC(SK_Print), SDSPEC(SK_Alt_R), SDEMPTY, SDSPEC(SK_Home), SDSPEC(SK_Up), SDSPEC(SK_Page_Up), SDSPEC(SK_Left), SDSPEC(SK_Right), SDSPEC(SK_End), SDSPEC(SK_Down), SDSPEC(SK_Page_Down), SDSPEC(SK_Insert), SDSPEC(SK_Delete), }; spkeyboard kb_mkey; void spkey_textmode(void) { spkb_normal(); restore_sptextmode(); } void spkey_screenmode(void) { set_vga_spmode(); spkb_raw(); sp_init_screen_mark(); } //------------------------------------------------ void spkb_process_events(int evenframe) { int i; int changed; if(evenframe) { spkb_update(); changed = 0; for(i = 0; i <= LASTKEYCODE; i++) { int ki; int sh; int ks; ks = sp_cp_keycode[i].norm; ki = KS_TO_KEY(ks); if( kbst(i) && !spkb_kbstate[ki].press ) { // press changed = 1; spkb_kbstate[ki].press = 1; sh = sp_cp_keycode[i].shifted; spkb_last.modif = 0; if(kbst(KC_L_SHIFT) || kbst(KC_R_SHIFT)) spkb_last.modif |= SKShiftMask; if(kbst(KC_L_CTRL) || kbst(KC_R_CTRL)) spkb_last.modif |= SKControlMask; if(kbst(KC_L_ALT) || kbst(KC_R_ALT)) spkb_last.modif |= SKMod1Mask; spkb_last.index = ki; spkb_last.shifted = sh; spkb_last.keysym = (spkb_last.modif & SKShiftMask) ? sh : ks; if((!ISFKEY(ks) || !spvk_after_switch) && accept_keys && !spkey_keyfuncs()) { spkb_kbstate[ki].state = 1; spkb_kbstate[i].frame = sp_int_ctr; } else spkb_kbstate[ki].state = 0; spvk_after_switch = 0; } if( !kbst(i) && spkb_kbstate[ki].press ) { // release changed = 1; spkb_kbstate[ki].press = 0; spkb_kbstate[ki].state = 0; } } if(changed) spkb_state_changed = 1; } process_keys(); } //--------------------------------------------------- void init_spect_key(void) { int i; for(i = 0; i < NR_SPKEYS; i++) spkb_kbstate[i].press = 0; clear_keystates(); init_basekeys(); spkb_init(); // atexit(close_spect_key); // bjs unnecessary! } int display_keyboard(void) { return 0; }
0
0.890984
1
0.890984
game-dev
MEDIA
0.555384
game-dev,embedded-firmware
0.979455
1
0.979455
OpenAngelArena/oaa
3,511
content/particles/hero/sohei/arcana/dbz/sohei_knockback_dbz.vpcf
<!-- kv3 encoding:text:version{e21c7f3c-8a33-41c5-9977-a76d3a32aa0d} format:vpcf59:version{6cf97bfa-52a0-441a-87f0-856fb7aaa129} --> { _class = "CParticleSystemDefinition" m_bShouldHitboxesFallbackToRenderBounds = false m_nMaxParticles = 40 m_ConstantColor = [ 89, 111, 133, 255 ] m_bShouldSort = false m_nBehaviorVersion = 12 m_nFirstMultipleOverride_BackwardCompat = 6 m_controlPointConfigurations = [ { m_name = "preview" m_drivers = [ { m_iAttachType = "PATTACH_WORLDORIGIN" m_entityName = "self" }, ] }, ] m_Emitters = [ { _class = "C_OP_ContinuousEmitter" m_flEmitRate = { m_nType = "PF_TYPE_LITERAL" m_flLiteralValue = 40.0 } }, ] m_Initializers = [ { _class = "C_INIT_InitFloat" m_InputValue = { m_nType = "PF_TYPE_RANDOM_UNIFORM" m_flRandomMin = 0.5 m_flRandomMax = 1.0 m_nRandomMode = "PF_RANDOM_MODE_CONSTANT" } m_nOutputField = 1 }, { _class = "C_INIT_InitFloat" m_InputValue = { m_nType = "PF_TYPE_RANDOM_UNIFORM" m_flRandomMin = 120.0 m_flRandomMax = 160.0 m_nRandomMode = "PF_RANDOM_MODE_CONSTANT" } }, { _class = "C_INIT_InitFloat" m_InputValue = { m_nType = "PF_TYPE_RANDOM_UNIFORM" m_flRandomMin = 0.313726 m_flRandomMax = 0.392157 m_nRandomMode = "PF_RANDOM_MODE_CONSTANT" } m_nOutputField = 7 }, { _class = "C_INIT_CreateWithinSphereTransform" m_LocalCoordinateSystemSpeedMax = [ 110.0, 0.0, 60.0 ] m_LocalCoordinateSystemSpeedMin = [ 110.0, 0.0, 60.0 ] m_fRadiusMax = 32.0 m_fSpeedMax = 32.0 }, { _class = "C_INIT_InitFloat" m_InputValue = { m_nType = "PF_TYPE_RANDOM_UNIFORM" m_flRandomMin = 0.0 m_flRandomMax = 360.0 m_nRandomMode = "PF_RANDOM_MODE_CONSTANT" m_bHasRandomSignFlip = true } m_nOutputField = 4 }, { _class = "C_INIT_RandomColor" m_ColorMax = [ 255, 255, 0, 255 ] m_ColorMin = [ 192, 105, 0, 255 ] }, { _class = "C_INIT_PositionOffset" m_OffsetMin = [ 0.0, 0.0, 70.0 ] m_OffsetMax = [ 0.0, 0.0, 70.0 ] }, ] m_Operators = [ { _class = "C_OP_Decay" }, { _class = "C_OP_FadeInSimple" }, { _class = "C_OP_FadeOutSimple" m_flFadeOutTime = 0.75 }, { _class = "C_OP_ColorInterpolate" m_ColorFade = [ 44, 53, 62, 255 ] }, { _class = "C_OP_BasicMovement" }, ] m_Renderers = [ { _class = "C_OP_RenderSprites" m_flStartFadeSize = 0.2 m_flEndFadeSize = 0.25 m_flMaxSize = 0.25 m_flAnimationRate = 1.0 m_vecTexturesInput = [ { m_hTexture = resource:"materials/particle/smoke/maya_wispy/wispy_v2.vtex" }, ] }, ] m_Children = [ { m_ChildRef = resource:"particles/hero/sohei/arcana/dbz/econ/events/ti6/force_staff_ti6_ground_trail.vpcf" }, { m_ChildRef = resource:"particles/hero/sohei/arcana/dbz/econ/events/ti6/force_staff_ti6_glow_trail.vpcf" }, { m_ChildRef = resource:"particles/hero/sohei/arcana/dbz/econ/events/ti6/force_staff_ti6_glow.vpcf" }, { m_ChildRef = resource:"particles/hero/sohei/arcana/dbz/econ/events/ti6/force_staff_ti6_trail.vpcf" }, { m_ChildRef = resource:"particles/hero/sohei/arcana/dbz/econ/events/ti6/force_staff_ti6_snow.vpcf" }, { m_ChildRef = resource:"particles/hero/sohei/arcana/dbz/econ/events/ti6/force_staff_ti6_mod_trail.vpcf" }, { m_ChildRef = resource:"particles/hero/sohei/arcana/dbz/econ/events/ti6/force_staff_ti6_snow_glow.vpcf" }, ] }
0
0.797973
1
0.797973
game-dev
MEDIA
0.819303
game-dev
0.615
1
0.615
ReactiveDrop/reactivedrop_public_src
19,398
src/game/client/swarm/vgui/asw_hud_squad_hotbar.cpp
#include "cbase.h" #include "asw_hud_squad_hotbar.h" #include "hud_macros.h" #include "squad_inventory_panel.h" #include <vgui_controls/ImagePanel.h> #include <vgui_controls/Label.h> #include "c_asw_marine.h" #include "asw_shareddefs.h" #include "c_asw_game_resource.h" #include "c_asw_marine_resource.h" #include "c_asw_weapon.h" #include "asw_marine_profile.h" #include "asw_weapon_parse.h" #include "clientmode_asw.h" #include "briefingtooltip.h" #include "iclientmode.h" #include "asw_input.h" #include <vgui_controls/AnimationController.h> #include "hud_locator_target.h" #include "asw_equipment_list.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" extern ConVar asw_draw_hud; ConVar asw_hotbar_simple( "asw_hotbar_simple", "1", FCVAR_NONE, "Show only 1 item per AI marine on the squad hotbar" ); ConVar asw_hotbar_self( "asw_hotbar_self", "1", FCVAR_NONE, "Show your own items on the hotbar" ); /* DECLARE_HUDELEMENT( CASW_Hud_Squad_Hotbar ); DECLARE_HUD_MESSAGE( CASW_Hud_Squad_Hotbar, ASWOrderUseItemFX ); DECLARE_HUD_MESSAGE( CASW_Hud_Squad_Hotbar, ASWOrderStopItemFX ); #define NUM_USE_ITEM_ORDER_CLASSES 19 const char *pszUseItemOrderClasses[NUM_USE_ITEM_ORDER_CLASSES] = { "cancel", "asw_weapon_bait", "asw_weapon_buff_grenade", "asw_weapon_freeze_grenades", "asw_weapon_grenades", "asw_weapon_laser_mines", "asw_weapon_mines", "asw_weapon_t75", "asw_weapon_tesla_trap", "asw_weapon_heal_grenade", "asw_weapon_sentry", "asw_weapon_sentry_cannon", "asw_weapon_sentry_flamer", "asw_weapon_sentry_freeze", "asw_weapon_hornet_barrage", "asw_weapon_electrified_armor", "asw_weapon_flares", "asw_weapon_welder", "asw_weapon_stim", }; */ CASW_Hud_Squad_Hotbar::CASW_Hud_Squad_Hotbar( const char *pElementName ) : CASW_HudElement( pElementName ), vgui::Panel( GetClientMode()->GetViewport(), "ASW_Hud_Squad_Hotbar" ) { SetHiddenBits( HIDEHUD_PLAYERDEAD | HIDEHUD_REMOTE_TURRET ); SetScheme( vgui::scheme()->LoadSchemeFromFile("resource/SwarmSchemeNew.res", "SwarmSchemeNew" ) ); m_iNumMarines = 0; } CASW_Hud_Squad_Hotbar::~CASW_Hud_Squad_Hotbar() { BriefingTooltip::Free(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CASW_Hud_Squad_Hotbar::Init( void ) { //HOOK_HUD_MESSAGE( CASW_Hud_Squad_Hotbar, ASWOrderUseItemFX ); //HOOK_HUD_MESSAGE( CASW_Hud_Squad_Hotbar, ASWOrderStopItemFX ); } bool CASW_Hud_Squad_Hotbar::ShouldDraw( void ) { if ( !ASWGameResource() ) return false; C_ASW_Player *pPlayer = C_ASW_Player::GetLocalASWPlayer(); if ( !pPlayer ) return false; if ( asw_hotbar_self.GetBool() ) { return asw_draw_hud.GetBool() && CASW_HudElement::ShouldDraw(); } m_iNumMarines = 0; for ( int i = 0; i < ASWGameResource()->GetMaxMarineResources(); i++ ) { C_ASW_Marine_Resource* pMR = ASWGameResource()->GetMarineResource( i ); if ( !pMR ) continue; if ( pMR->GetCommander() != pPlayer ) continue; C_ASW_Marine *pMarine = pMR->GetMarineEntity(); if ( !pMarine ) continue; m_iNumMarines++; } return m_iNumMarines > 1 && asw_draw_hud.GetBool() && CASW_HudElement::ShouldDraw(); } void CASW_Hud_Squad_Hotbar::ApplySchemeSettings( vgui::IScheme *pScheme ) { BaseClass::ApplySchemeSettings( pScheme ); SetBgColor( Color( 0, 0, 0, 100 ) ); } void CASW_Hud_Squad_Hotbar::PerformLayout() { BaseClass::PerformLayout(); // position our child entries in a horizontal list and expand to fit them int border = YRES( 2 ); int gap = YRES( 4 ); int tw = border, th = 0; for ( int i = 0; i < m_pEntries.Count(); i++ ) { m_pEntries[i]->InvalidateLayout( true ); m_pEntries[i]->SetPos( tw, border ); int w, h; m_pEntries[i]->GetSize( w, h ); th = MAX( h, th ); tw += w + gap; } th = border + th + border; tw = tw - gap + border; SetSize( tw, th ); SetPos( ScreenWidth() * 0.5f - tw * 0.5f, ScreenHeight() * 0.3f - th ); // position in lower center of screen } void CASW_Hud_Squad_Hotbar::OnThink() { BaseClass::OnThink(); UpdateList(); for ( int i = 0; i < m_pEntries.Count(); i++ ) { if ( m_pEntries[ i ]->IsCursorOver() ) { // make sure tooltip is created and parented correctly BriefingTooltip::EnsureParent( GetParent() ); m_pEntries[ i ]->ShowTooltip(); break; } } /* // loops through to see if we have effects that are flagged to die after a certain time for ( HotbarOrderEffectsList_t::IndexLocalType_t i = m_hHotbarOrderEffects.Head() ; m_hHotbarOrderEffects.IsValidIndex(i) ; i = m_hHotbarOrderEffects.Next(i) ) { if ( m_hHotbarOrderEffects[i].flRemoveAtTime > 0 && m_hHotbarOrderEffects[i].flRemoveAtTime < gpGlobals->curtime ) { int iMarine = m_hHotbarOrderEffects[i].iEffectID; C_ASW_Marine *pMarine = dynamic_cast<C_ASW_Marine*>(ClientEntityList().GetEnt(iMarine)); // turn iMarine ent index into the marine if ( !pMarine ) return; StopItemFX( pMarine, -1 ); } } */ } void CASW_Hud_Squad_Hotbar::UpdateList() { if ( !ASWGameResource() ) return; C_ASW_Player *pPlayer = C_ASW_Player::GetLocalASWPlayer(); int iEntry = 0; bool bHasItem = false; if ( asw_hotbar_self.GetBool() ) { if ( iEntry >= m_pEntries.Count() ) { CASW_Hotbar_Entry *pPanel = new CASW_Hotbar_Entry( this, "SquadInventoryPanelEntry" ); m_pEntries.AddToTail( pPanel ); InvalidateLayout(); } // add your offhand item to the hotbar first C_ASW_Marine *pPlayerMarine = C_ASW_Marine::AsMarine( pPlayer->GetViewNPC() ); if ( pPlayerMarine ) { C_ASW_Weapon *pWeapon = pPlayerMarine->GetASWWeapon( ASW_INVENTORY_SLOT_EXTRA ); if ( pWeapon ) { m_pEntries[ iEntry ]->m_iHotKeyIndex = -1; m_pEntries[ iEntry ]->SetVisible( true ); m_pEntries[ iEntry ]->SetDetails( pPlayerMarine, ASW_INVENTORY_SLOT_EXTRA ); bHasItem = true; } } if ( !bHasItem ) // blank it out if there's no item in that slot { m_pEntries[ iEntry ]->m_iHotKeyIndex = iEntry; m_pEntries[ iEntry ]->SetDetails( NULL, -1 ); m_pEntries[ iEntry ]->SetVisible( false ); } iEntry++; } for ( int i = 0; i < ASWGameResource()->GetMaxMarineResources(); i++ ) { C_ASW_Marine_Resource* pMR = ASWGameResource()->GetMarineResource( i ); if ( !pMR ) continue; if ( pMR->GetCommander() != pPlayer ) continue; C_ASW_Marine *pMarine = pMR->GetMarineEntity(); if ( !pMarine ) continue; if ( pMarine->IsInhabited() ) continue; if ( iEntry >= m_pEntries.Count() ) { CASW_Hotbar_Entry *pPanel = new CASW_Hotbar_Entry( this, "SquadInventoryPanelEntry" ); m_pEntries.AddToTail( pPanel ); InvalidateLayout(); } bHasItem = false; for ( int k = 0; k < ASW_NUM_INVENTORY_SLOTS; k++ ) { C_ASW_Weapon *pWeapon = pMarine->GetASWWeapon( k ); if ( !pWeapon ) continue; const CASW_WeaponInfo* pInfo = pWeapon->GetWeaponInfo(); if ( !pInfo || !pInfo->m_bOffhandActivate ) // TODO: Fix for sentry guns continue; m_pEntries[ iEntry ]->m_iHotKeyIndex = iEntry; m_pEntries[ iEntry ]->SetVisible( true ); m_pEntries[ iEntry ]->SetDetails( pMarine, k ); bHasItem = true; if ( asw_hotbar_simple.GetBool() ) // only 1 item per marine break; } if ( !bHasItem ) // blank it out if there's no item in that slot { m_pEntries[ iEntry ]->m_iHotKeyIndex = iEntry; m_pEntries[ iEntry ]->SetDetails( NULL, -1 ); m_pEntries[ iEntry ]->SetVisible( false ); } iEntry++; } for ( int i = iEntry; i < m_pEntries.Count(); i++ ) { m_pEntries[ i ]->SetVisible( false ); } } void CASW_Hud_Squad_Hotbar::ActivateHotbarItem( int i ) { if ( i < 0 || i >= m_pEntries.Count() ) return; m_pEntries[ i ]->ActivateItem(); } int CASW_Hud_Squad_Hotbar::GetHotBarSlot( const char *szWeaponName ) { for ( int i = 0; i < m_pEntries.Count(); i++ ) { CASW_Hotbar_Entry *pEntry = m_pEntries[ i ]; if ( pEntry && pEntry->m_hMarine.Get() ) { C_ASW_Weapon *pWeapon = pEntry->m_hMarine->GetASWWeapon( pEntry->m_iInventoryIndex ); if ( pWeapon ) { if ( FClassnameIs( pWeapon, szWeaponName ) ) { return i; } } } } return -1; } #if 0 void CASW_Hud_Squad_Hotbar::StopItemFX( C_ASW_Marine *pMarine, float flDeleteTime, bool bFailed ) { if ( !pMarine ) return; // loops through to see if we already have an order effect for this marine for ( HotbarOrderEffectsList_t::IndexLocalType_t i = m_hHotbarOrderEffects.Head() ; m_hHotbarOrderEffects.IsValidIndex(i) ; i = m_hHotbarOrderEffects.Next(i) ) { if ( m_hHotbarOrderEffects[i].iEffectID == pMarine->entindex() && m_hHotbarOrderEffects[i].pEffect ) { if ( bFailed ) { m_hHotbarOrderEffects[i].flRemoveAtTime = MAX( flDeleteTime, 0.5f ); m_hHotbarOrderEffects[i].pEffect->SetControlPoint( 2, Vector( 0, 1, 0 ) ); break; } if ( flDeleteTime > 0 ) { m_hHotbarOrderEffects[i].flRemoveAtTime = flDeleteTime; break; } pMarine->ParticleProp()->StopEmission( m_hHotbarOrderEffects[i].pEffect ); m_hHotbarOrderEffects[i].pEffect = NULL; m_hHotbarOrderEffects.Remove(i); break; } } } //----------------------------------------------------------------------------- // Purpose: Message handler for ASWOrderUseItemFX message //----------------------------------------------------------------------------- void CASW_Hud_Squad_Hotbar::MsgFunc_ASWOrderUseItemFX( bf_read &msg ) { int iMarine = msg.ReadShort(); C_ASW_Marine *pMarine = dynamic_cast<C_ASW_Marine*>(ClientEntityList().GetEnt(iMarine)); // turn iMarine ent index into the marine if ( !pMarine ) return; int iOrderType = msg.ReadShort(); int iInventorySlot = msg.ReadShort(); Vector vecPosition; vecPosition.x = msg.ReadFloat(); vecPosition.y = msg.ReadFloat(); vecPosition.z = msg.ReadFloat(); // loops through to see if we already have an order effect for this marine StopItemFX( pMarine ); const char *pszClassName = NULL; switch( iOrderType ) { case ASW_USE_ORDER_WITH_ITEM: { // check we have an item in that slot CASW_Weapon* pWeapon = pMarine->GetASWWeapon( iInventorySlot ); if ( !pWeapon || !pWeapon->GetWeaponInfo() || !pWeapon->GetWeaponInfo()->m_bOffhandActivate ) return; pszClassName = pWeapon->GetClassname(); } break; case ASW_USE_ORDER_HACK: { pszClassName = "asw_weapon_t75"; // for now, we're using the t75 icon for hacking } break; default: { Assert( false ); // unspecified order type return; } break; } //CNewParticleEffect *pEffect = pMarine->ParticleProp()->Create( "order_use_item", PATTACH_CUSTOMORIGIN, -1, vecPosition - pMarine->GetAbsOrigin() ); CNewParticleEffect *pEffect = pMarine->ParticleProp()->Create( "order_use_item", PATTACH_ABSORIGIN ); if ( pEffect ) { pMarine->ParticleProp()->AddControlPoint( pEffect, 1, pMarine, PATTACH_CUSTOMORIGIN ); pEffect->SetControlPoint( 1, vecPosition );//vecPosition - pMarine->GetAbsOrigin() for ( int i = 0; i < NUM_USE_ITEM_ORDER_CLASSES; i++ ) { if ( pszUseItemOrderClasses[i] && !Q_strcmp ( pszUseItemOrderClasses[i] , pszClassName ) ) { pEffect->SetControlPoint( 2, Vector( i, 0, 0 ) ); break; } } HotbarOrderEffectsList_t::IndexLocalType_t iIndex = m_hHotbarOrderEffects.AddToTail(); m_hHotbarOrderEffects[iIndex].iEffectID = iMarine; m_hHotbarOrderEffects[iIndex].pEffect = pEffect; } } void CASW_Hud_Squad_Hotbar::MsgFunc_ASWOrderStopItemFX( bf_read &msg ) { int iMarine = msg.ReadShort(); C_ASW_Marine *pMarine = dynamic_cast<C_ASW_Marine*>(ClientEntityList().GetEnt(iMarine)); // turn iMarine ent index into the marine if ( !pMarine ) return; bool bShouldDelay = msg.ReadOneBit() ? true : false; bool bFailed = msg.ReadOneBit() ? true : false; // loops through to see if we already have an order effect for this marine if ( bFailed ) StopItemFX( pMarine, gpGlobals->curtime + 2.0f, true ); else if ( bShouldDelay ) StopItemFX( pMarine, gpGlobals->curtime + 2.0f ); else StopItemFX( pMarine ); } #endif /// ========================================= CASW_Hotbar_Entry::CASW_Hotbar_Entry( vgui::Panel *pParent, const char *pElementName ) : BaseClass( pParent, pElementName ) { m_pWeaponImage = new vgui::ImagePanel( this, "Image" ); m_pWeaponImage->SetShouldScaleImage( true ); m_pMarineNameLabel = new vgui::Label( this, "MarineNameLabel", "" ); m_pKeybindLabel = new vgui::Label( this, "KeybindLabel", "" ); m_pQuantityLabel = new vgui::Label( this, "pQuantityLabel", "" ); m_bMouseOver = false; m_iHotKeyIndex = 0; } CASW_Hotbar_Entry::~CASW_Hotbar_Entry() { } void CASW_Hotbar_Entry::SetDetails( C_ASW_Marine *pMarine, int iInventoryIndex ) { m_hMarine = pMarine; m_iInventoryIndex = iInventoryIndex; UpdateImage(); } void CASW_Hotbar_Entry::ClearImage() { m_pWeaponImage->SetVisible( false ); m_pMarineNameLabel->SetVisible( false ); m_pKeybindLabel->SetVisible( false ); m_pQuantityLabel->SetVisible( false ); } void CASW_Hotbar_Entry::UpdateImage() { if ( !m_hMarine.Get() ) { ClearImage(); return; } C_ASW_Weapon *pWeapon = m_hMarine->GetASWWeapon( m_iInventoryIndex ); if ( !pWeapon ) { ClearImage(); return; } const CASW_WeaponInfo *pInfo = pWeapon->GetWeaponInfo(); const CASW_EquipItem *pItem = pWeapon->GetEquipItem(); if ( !pInfo || !pItem ) { return; } if ( !pInfo->m_bOffhandActivate && ( !asw_hotbar_self.GetBool() || m_iHotKeyIndex != -1 ) ) // TODO: Fix for sentry guns { // allow your own third item to show even if it's not usable ClearImage(); return; } m_pWeaponImage->SetVisible( true ); m_pMarineNameLabel->SetVisible( true ); m_pKeybindLabel->SetVisible( true ); m_pQuantityLabel->SetVisible( true ); m_pWeaponImage->SetImage( pItem->m_szEquipIcon ); CASW_Marine_Profile *pProfile = m_hMarine->GetMarineProfile(); if ( pProfile ) { m_pMarineNameLabel->SetText( pProfile->GetShortName() ); } const char *pszKey = ""; if ( m_iHotKeyIndex != -1 ) { char szBinding[ 128 ]; Q_snprintf( szBinding, sizeof( szBinding ), "asw_squad_hotbar %d", m_iHotKeyIndex ); pszKey = ASW_FindKeyBoundTo( szBinding ); } else { pszKey = ASW_FindKeyBoundTo( "+grenade1" ); } char szKey[ 12 ]; Q_snprintf( szKey, sizeof(szKey), "%s", pszKey ); Q_strupr( szKey ); m_pKeybindLabel->SetText( szKey ); // TODO: Eventually make this into instructor key style? or a version of that which fits the HUD char szQuantity[ 32 ]; Q_snprintf( szQuantity, sizeof( szQuantity ), "x%d", pWeapon->DisplayClip1() ); m_pQuantityLabel->SetText( szQuantity ); } void CASW_Hotbar_Entry::ShowTooltip() { if ( !m_hMarine.Get() ) return; C_ASW_Weapon *pWeapon = m_hMarine->GetASWWeapon( m_iInventoryIndex ); if ( !pWeapon ) return; const CASW_WeaponInfo *pInfo = pWeapon->GetWeaponInfo(); const CASW_EquipItem *pItem = pWeapon->GetEquipItem(); if ( !pInfo || !pItem || !pInfo->m_bOffhandActivate ) // TODO: Fix for sentry guns return; int x = GetWide() * 0.8f; int y = GetTall() * 0.02f; LocalToScreen( x, y ); g_hBriefingTooltip->SetTooltip( this, pItem->m_szShortName, " ", x, y, vgui::Label::a_northwest ); } void CASW_Hotbar_Entry::ActivateItem() { if ( !m_hMarine.Get() ) return; if ( m_hMarine->IsInhabited() ) return; C_ASW_Weapon *pWeapon = m_hMarine->GetASWWeapon( m_iInventoryIndex ); if ( !pWeapon ) return; const CASW_WeaponInfo* pInfo = pWeapon->GetWeaponInfo(); if ( !pInfo || !pInfo->m_bOffhandActivate ) // TODO: Fix for sentry guns return; // make it flash new CASWSelectOverlayPulse( this ); char buffer[ 64 ]; Q_snprintf(buffer, sizeof(buffer), "cl_ai_offhand %d %d", m_iInventoryIndex, m_hMarine->entindex() ); engine->ClientCmd( buffer ); CLocalPlayerFilter filter; C_BaseEntity::EmitSound( filter, -1 /*SOUND_FROM_LOCAL_PLAYER*/, "ASWInterface.Button3" ); } void CASW_Hotbar_Entry::ApplySchemeSettings( vgui::IScheme *pScheme ) { BaseClass::ApplySchemeSettings( pScheme ); m_pMarineNameLabel->SetFgColor( Color( 168, 168, 192, 255 ) ); m_pMarineNameLabel->SetFont( pScheme->GetFont( "VerdanaVerySmall", IsProportional() ) ); m_pKeybindLabel->SetFgColor( Color( 255, 255, 255, 255 ) ); m_pKeybindLabel->SetFont( pScheme->GetFont( "Default", IsProportional() ) ); m_pQuantityLabel->SetFgColor( Color( 66, 142, 192, 255 ) ); m_pQuantityLabel->SetFont( pScheme->GetFont( "DefaultSmall", IsProportional() ) ); m_pWeaponImage->SetDrawColor( Color( 66, 142, 192, 255 ) ); SetBgColor( Color( 32, 32, 64, 128 ) ); UpdateImage(); } void CASW_Hotbar_Entry::PerformLayout() { BaseClass::PerformLayout(); int w = YRES( 38); // halfwide, presuming 'extra' sized items int h = YRES( 38 ); SetSize( w, h ); int border = YRES( 2 ); m_pMarineNameLabel->SetContentAlignment( vgui::Label::a_northeast ); m_pMarineNameLabel->SetBounds( border, border, w - border * 2, YRES( 12 ) ); m_pKeybindLabel->SetContentAlignment( vgui::Label::a_northwest ); m_pKeybindLabel->SetBounds( border, border, w - border * 2, YRES( 12 ) ); m_pQuantityLabel->SetContentAlignment( vgui::Label::a_southeast ); m_pQuantityLabel->SetBounds( border, border, w - border * 2, h - border * 2 ); border = YRES( 3 ); m_pWeaponImage->SetBounds( border, border, w - border * 2, h - border * 2 ); } // ============================================================ //----------------------------------------------------------------------------- // CASWSelectOverlayPulse // // creates a highlight pulse over the panel of an offhand item that has just been used // //----------------------------------------------------------------------------- CASWSelectOverlayPulse::CASWSelectOverlayPulse( vgui::Panel* pParent ) { SetPaintBackgroundEnabled( false ); m_pParent = NULL; m_bStarted = false; m_fScale = 1.1; if ( pParent ) { m_pParent = pParent; SetParent( pParent->GetParent() ); Initialize(); } else { MarkForDeletion(); SetVisible( false ); } } CASWSelectOverlayPulse::~CASWSelectOverlayPulse() { } void CASWSelectOverlayPulse::Initialize() { vgui::HScheme scheme = vgui::scheme()->LoadSchemeFromFile("resource/swarm/SwarmSchemeNew.res", "SwarmSchemeNew"); SetScheme(scheme); m_pOverlayLabel = new vgui::ImagePanel( this, "SelectOverlayImage" ); m_fStartTime = gpGlobals->curtime; int x, y; m_pParent->GetPos( x, y ); int w, h; m_pParent->GetSize( w, h ); SetSize( w * m_fScale, h * m_fScale ); SetPos( x - ( GetWide() - w ) / 2, y - ( GetTall() - h ) / 2 ); SetZPos( 100 ); if ( m_pOverlayLabel ) { m_pOverlayLabel->SetImage( "inventory/item_select_glow" ); m_pOverlayLabel->SetShouldScaleImage( true ); m_pOverlayLabel->SetAlpha( 255 ); m_pOverlayLabel->SetPos( 0, 0 ); m_pOverlayLabel->SetSize( w * m_fScale, h * m_fScale ); m_bStarted = true; } } //----------------------------------------------------------------------------- // Purpose: Delete panel when highlight has faded out //----------------------------------------------------------------------------- void CASWSelectOverlayPulse::OnThink() { if ( m_pOverlayLabel && gpGlobals->curtime > m_fStartTime ) { if ( m_bStarted ) { m_bStarted = false; vgui::GetAnimationController()->RunAnimationCommand( m_pOverlayLabel, "alpha", 0, 0.21, 1.0f, vgui::AnimationController::INTERPOLATOR_DEACCEL ); } else if ( m_pOverlayLabel->GetAlpha() <= 0 ) { MarkForDeletion(); SetVisible( false ); } } }
0
0.973847
1
0.973847
game-dev
MEDIA
0.776392
game-dev
0.634697
1
0.634697
glKarin/com.n0n3m4.diii4a
19,723
Q3E/src/main/jni/jk/codeJK2/game/AI_Mark1.cpp
/* =========================================================================== Copyright (C) 2000 - 2013, Raven Software, Inc. Copyright (C) 2001 - 2013, Activision, Inc. Copyright (C) 2013 - 2015, OpenJK contributors This file is part of the OpenJK source code. OpenJK is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. =========================================================================== */ #include "g_headers.h" #include "b_local.h" #include "g_nav.h" #define MIN_MELEE_RANGE 320 #define MIN_MELEE_RANGE_SQR ( MIN_MELEE_RANGE * MIN_MELEE_RANGE ) #define MIN_DISTANCE 128 #define MIN_DISTANCE_SQR ( MIN_DISTANCE * MIN_DISTANCE ) #define TURN_OFF 0x00000100 #define LEFT_ARM_HEALTH 40 #define RIGHT_ARM_HEALTH 40 #define AMMO_POD_HEALTH 40 #define BOWCASTER_VELOCITY 1300 #define BOWCASTER_NPC_DAMAGE_EASY 12 #define BOWCASTER_NPC_DAMAGE_NORMAL 24 #define BOWCASTER_NPC_DAMAGE_HARD 36 #define BOWCASTER_SIZE 2 #define BOWCASTER_SPLASH_DAMAGE 0 #define BOWCASTER_SPLASH_RADIUS 0 //Local state enums enum { LSTATE_NONE = 0, LSTATE_ASLEEP, LSTATE_WAKEUP, LSTATE_FIRED0, LSTATE_FIRED1, LSTATE_FIRED2, LSTATE_FIRED3, LSTATE_FIRED4, }; qboolean NPC_CheckPlayerTeamStealth( void ); gentity_t *CreateMissile( vec3_t org, vec3_t dir, float vel, int life, gentity_t *owner, qboolean altFire = qfalse ); void Mark1_BlasterAttack(qboolean advance); void DeathFX( gentity_t *ent ); extern gitem_t *FindItemForAmmo( ammo_t ammo ); /* ------------------------- NPC_Mark1_Precache ------------------------- */ void NPC_Mark1_Precache(void) { G_SoundIndex( "sound/chars/mark1/misc/mark1_wakeup"); G_SoundIndex( "sound/chars/mark1/misc/shutdown"); G_SoundIndex( "sound/chars/mark1/misc/walk"); G_SoundIndex( "sound/chars/mark1/misc/run"); G_SoundIndex( "sound/chars/mark1/misc/death1"); G_SoundIndex( "sound/chars/mark1/misc/death2"); G_SoundIndex( "sound/chars/mark1/misc/anger"); G_SoundIndex( "sound/chars/mark1/misc/mark1_fire"); G_SoundIndex( "sound/chars/mark1/misc/mark1_pain"); G_SoundIndex( "sound/chars/mark1/misc/mark1_explo"); // G_EffectIndex( "small_chunks"); G_EffectIndex( "env/med_explode2"); G_EffectIndex( "probeexplosion1"); G_EffectIndex( "blaster/smoke_bolton"); G_EffectIndex( "bryar/muzzle_flash"); G_EffectIndex( "droidexplosion1" ); RegisterItem( FindItemForAmmo( AMMO_METAL_BOLTS)); RegisterItem( FindItemForAmmo( AMMO_BLASTER )); RegisterItem( FindItemForWeapon( WP_BOWCASTER )); RegisterItem( FindItemForWeapon( WP_BRYAR_PISTOL )); } /* ------------------------- NPC_Mark1_Part_Explode ------------------------- */ void NPC_Mark1_Part_Explode( gentity_t *self, int bolt ) { if ( bolt >=0 ) { mdxaBone_t boltMatrix; vec3_t org, dir; gi.G2API_GetBoltMatrix( self->ghoul2, self->playerModel, bolt, &boltMatrix, self->currentAngles, self->currentOrigin, (cg.time?cg.time:level.time), NULL, self->s.modelScale ); gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, org ); gi.G2API_GiveMeVectorFromMatrix( boltMatrix, NEGATIVE_Y, dir ); G_PlayEffect( "env/med_explode2", org, dir ); } G_PlayEffect( "blaster/smoke_bolton", self->playerModel, bolt, self->s.number ); } /* ------------------------- Mark1_Idle ------------------------- */ void Mark1_Idle( void ) { NPC_BSIdle(); NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_SLEEP1, SETANIM_FLAG_NORMAL ); } /* ------------------------- Mark1Dead_FireRocket - Shoot the left weapon, the multi-blaster ------------------------- */ void Mark1Dead_FireRocket (void) { mdxaBone_t boltMatrix; vec3_t muzzle1,muzzle_dir; int damage = 50; gi.G2API_GetBoltMatrix( NPC->ghoul2, NPC->playerModel, NPC->genericBolt5, &boltMatrix, NPC->currentAngles, NPC->currentOrigin, (cg.time?cg.time:level.time), NULL, NPC->s.modelScale ); gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, muzzle1 ); gi.G2API_GiveMeVectorFromMatrix( boltMatrix, NEGATIVE_Y, muzzle_dir ); G_PlayEffect( "bryar/muzzle_flash", muzzle1, muzzle_dir ); G_Sound( NPC, G_SoundIndex("sound/chars/mark1/misc/mark1_fire")); gentity_t *missile = CreateMissile( muzzle1, muzzle_dir, BOWCASTER_VELOCITY, 10000, NPC ); missile->classname = "bowcaster_proj"; missile->s.weapon = WP_BOWCASTER; VectorSet( missile->maxs, BOWCASTER_SIZE, BOWCASTER_SIZE, BOWCASTER_SIZE ); VectorScale( missile->maxs, -1, missile->mins ); missile->damage = damage; missile->dflags = DAMAGE_DEATH_KNOCKBACK; missile->methodOfDeath = MOD_ENERGY; missile->clipmask = MASK_SHOT | CONTENTS_LIGHTSABER; missile->splashDamage = BOWCASTER_SPLASH_DAMAGE; missile->splashRadius = BOWCASTER_SPLASH_RADIUS; // we don't want it to bounce missile->bounceCount = 0; } /* ------------------------- Mark1Dead_FireBlaster - Shoot the left weapon, the multi-blaster ------------------------- */ void Mark1Dead_FireBlaster (void) { vec3_t muzzle1,muzzle_dir; gentity_t *missile; mdxaBone_t boltMatrix; int bolt; bolt = NPC->genericBolt1; gi.G2API_GetBoltMatrix( NPC->ghoul2, NPC->playerModel, bolt, &boltMatrix, NPC->currentAngles, NPC->currentOrigin, (cg.time?cg.time:level.time), NULL, NPC->s.modelScale ); gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, muzzle1 ); gi.G2API_GiveMeVectorFromMatrix( boltMatrix, NEGATIVE_Y, muzzle_dir ); G_PlayEffect( "bryar/muzzle_flash", muzzle1, muzzle_dir ); missile = CreateMissile( muzzle1, muzzle_dir, 1600, 10000, NPC ); G_Sound( NPC, G_SoundIndex("sound/chars/mark1/misc/mark1_fire")); missile->classname = "bryar_proj"; missile->s.weapon = WP_BRYAR_PISTOL; missile->damage = 1; missile->dflags = DAMAGE_DEATH_KNOCKBACK; missile->methodOfDeath = MOD_ENERGY; missile->clipmask = MASK_SHOT | CONTENTS_LIGHTSABER; } /* ------------------------- Mark1_die ------------------------- */ void Mark1_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod,int dFlags,int hitLoc ) { /* int anim; // Is he dead already? anim = self->client->ps.legsAnim; if (((anim==BOTH_DEATH1) || (anim==BOTH_DEATH2)) && (self->client->ps.torsoAnimTimer==0)) { // This is because self->health keeps getting zeroed out. HL_NONE acts as health in this case. self->locationDamage[HL_NONE] += damage; if (self->locationDamage[HL_NONE] > 50) { DeathFX(self); self->client->ps.eFlags |= EF_NODRAW; self->contents = CONTENTS_CORPSE; // G_FreeEntity( self ); // Is this safe? I can't see why we'd mark it nodraw and then just leave it around?? self->e_ThinkFunc = thinkF_G_FreeEntity; self->nextthink = level.time + FRAMETIME; } return; } */ G_Sound( self, G_SoundIndex(va("sound/chars/mark1/misc/death%d.wav",Q_irand( 1, 2)))); // Choose a death anim if (Q_irand( 1, 10) > 5) { NPC_SetAnim( self, SETANIM_BOTH, BOTH_DEATH2, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); } else { NPC_SetAnim( self, SETANIM_BOTH, BOTH_DEATH1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); } } /* ------------------------- Mark1_dying ------------------------- */ void Mark1_dying( gentity_t *self ) { int num,newBolt; if (self->client->ps.torsoAnimTimer>0) { if (TIMER_Done(self,"dyingExplosion")) { num = Q_irand( 1, 3); // Find place to generate explosion if (num == 1) { num = Q_irand( 8, 10); newBolt = gi.G2API_AddBolt( &self->ghoul2[self->playerModel], va("*flash%d",num) ); NPC_Mark1_Part_Explode(self,newBolt); } else { num = Q_irand( 1, 6); newBolt = gi.G2API_AddBolt( &self->ghoul2[self->playerModel], va("*torso_tube%d",num) ); NPC_Mark1_Part_Explode(self,newBolt); gi.G2API_SetSurfaceOnOff( &self->ghoul2[self->playerModel], va("torso_tube%d",num), TURN_OFF ); } TIMER_Set( self, "dyingExplosion", Q_irand( 300, 1000 ) ); } // int dir; // vec3_t right; // Shove to the side // AngleVectors( self->client->renderInfo.eyeAngles, NULL, right, NULL ); // VectorMA( self->client->ps.velocity, -80, right, self->client->ps.velocity ); // See which weapons are there // Randomly fire blaster if (!gi.G2API_GetSurfaceRenderStatus( &self->ghoul2[self->playerModel], "l_arm" )) // Is the blaster still on the model? { if (Q_irand( 1, 5) == 1) { SaveNPCGlobals(); SetNPCGlobals( self ); Mark1Dead_FireBlaster(); RestoreNPCGlobals(); } } // Randomly fire rocket if (!gi.G2API_GetSurfaceRenderStatus( &self->ghoul2[self->playerModel], "r_arm" )) // Is the rocket still on the model? { if (Q_irand( 1, 10) == 1) { SaveNPCGlobals(); SetNPCGlobals( self ); Mark1Dead_FireRocket(); RestoreNPCGlobals(); } } } } /* ------------------------- NPC_Mark1_Pain - look at what was hit and see if it should be removed from the model. ------------------------- */ void NPC_Mark1_Pain( gentity_t *self, gentity_t *inflictor, gentity_t *other, vec3_t point, int damage, int mod,int hitLoc ) { int newBolt,i,chance; NPC_Pain( self, inflictor, other, point, damage, mod ); G_Sound( self, G_SoundIndex("sound/chars/mark1/misc/mark1_pain")); // Hit in the CHEST??? if (hitLoc==HL_CHEST) { chance = Q_irand( 1, 4); if ((chance == 1) && (damage > 5)) { NPC_SetAnim( self, SETANIM_BOTH, BOTH_PAIN1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); } } // Hit in the left arm? else if ((hitLoc==HL_ARM_LT) && (self->locationDamage[HL_ARM_LT] > LEFT_ARM_HEALTH)) { if (self->locationDamage[hitLoc] >= LEFT_ARM_HEALTH) // Blow it up? { newBolt = gi.G2API_AddBolt( &self->ghoul2[self->playerModel], "*flash3" ); if ( newBolt != -1 ) { NPC_Mark1_Part_Explode(self,newBolt); } gi.G2API_SetSurfaceOnOff( &self->ghoul2[self->playerModel], "l_arm", TURN_OFF ); } } // Hit in the right arm? else if ((hitLoc==HL_ARM_RT) && (self->locationDamage[HL_ARM_RT] > RIGHT_ARM_HEALTH)) // Blow it up? { if (self->locationDamage[hitLoc] >= RIGHT_ARM_HEALTH) { newBolt = gi.G2API_AddBolt( &self->ghoul2[self->playerModel], "*flash4" ); if ( newBolt != -1 ) { // G_PlayEffect( "small_chunks", self->playerModel, self->genericBolt2, self->s.number); NPC_Mark1_Part_Explode( self, newBolt ); } gi.G2API_SetSurfaceOnOff( &self->ghoul2[self->playerModel], "r_arm", TURN_OFF ); } } // Check ammo pods else { for (i=0;i<6;i++) { if ((hitLoc==HL_GENERIC1+i) && (self->locationDamage[HL_GENERIC1+i] > AMMO_POD_HEALTH)) // Blow it up? { if (self->locationDamage[hitLoc] >= AMMO_POD_HEALTH) { newBolt = gi.G2API_AddBolt( &self->ghoul2[self->playerModel], va("*torso_tube%d",(i+1)) ); if ( newBolt != -1 ) { NPC_Mark1_Part_Explode(self,newBolt); } gi.G2API_SetSurfaceOnOff( &self->ghoul2[self->playerModel], va("torso_tube%d",(i+1)), TURN_OFF ); NPC_SetAnim( self, SETANIM_BOTH, BOTH_PAIN1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); break; } } } } // Are both guns shot off? if ((gi.G2API_GetSurfaceRenderStatus( &self->ghoul2[self->playerModel], "l_arm" )) && (gi.G2API_GetSurfaceRenderStatus( &self->ghoul2[self->playerModel], "r_arm" ))) { G_Damage(self,NULL,NULL,NULL,NULL,self->health,0,MOD_UNKNOWN); } } /* ------------------------- Mark1_Hunt - look for enemy. -------------------------` */ void Mark1_Hunt(void) { if ( NPCInfo->goalEntity == NULL ) { NPCInfo->goalEntity = NPC->enemy; } NPC_FaceEnemy( qtrue ); NPCInfo->combatMove = qtrue; NPC_MoveToGoal( qtrue ); } /* ------------------------- Mark1_FireBlaster - Shoot the left weapon, the multi-blaster ------------------------- */ void Mark1_FireBlaster(void) { vec3_t muzzle1,enemy_org1,delta1,angleToEnemy1; static vec3_t forward, vright, up; gentity_t *missile; mdxaBone_t boltMatrix; int bolt; // Which muzzle to fire from? if ((NPCInfo->localState <= LSTATE_FIRED0) || (NPCInfo->localState == LSTATE_FIRED4)) { NPCInfo->localState = LSTATE_FIRED1; bolt = NPC->genericBolt1; } else if (NPCInfo->localState == LSTATE_FIRED1) { NPCInfo->localState = LSTATE_FIRED2; bolt = NPC->genericBolt2; } else if (NPCInfo->localState == LSTATE_FIRED2) { NPCInfo->localState = LSTATE_FIRED3; bolt = NPC->genericBolt3; } else { NPCInfo->localState = LSTATE_FIRED4; bolt = NPC->genericBolt4; } gi.G2API_GetBoltMatrix( NPC->ghoul2, NPC->playerModel, bolt, &boltMatrix, NPC->currentAngles, NPC->currentOrigin, (cg.time?cg.time:level.time), NULL, NPC->s.modelScale ); gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, muzzle1 ); if (NPC->health) { CalcEntitySpot( NPC->enemy, SPOT_HEAD, enemy_org1 ); VectorSubtract (enemy_org1, muzzle1, delta1); vectoangles ( delta1, angleToEnemy1 ); AngleVectors (angleToEnemy1, forward, vright, up); } else { AngleVectors (NPC->currentAngles, forward, vright, up); } G_PlayEffect( "bryar/muzzle_flash", muzzle1, forward ); G_Sound( NPC, G_SoundIndex("sound/chars/mark1/misc/mark1_fire")); missile = CreateMissile( muzzle1, forward, 1600, 10000, NPC ); missile->classname = "bryar_proj"; missile->s.weapon = WP_BRYAR_PISTOL; missile->damage = 1; missile->dflags = DAMAGE_DEATH_KNOCKBACK; missile->methodOfDeath = MOD_ENERGY; missile->clipmask = MASK_SHOT | CONTENTS_LIGHTSABER; } /* ------------------------- Mark1_BlasterAttack ------------------------- */ void Mark1_BlasterAttack(qboolean advance ) { int chance; if ( TIMER_Done( NPC, "attackDelay" ) ) // Attack? { chance = Q_irand( 1, 5); NPCInfo->burstCount++; if (NPCInfo->burstCount<3) // Too few shots this burst? { chance = 2; // Force it to keep firing. } else if (NPCInfo->burstCount>12) // Too many shots fired this burst? { NPCInfo->burstCount = 0; chance = 1; // Force it to stop firing. } // Stop firing. if (chance == 1) { NPCInfo->burstCount = 0; TIMER_Set( NPC, "attackDelay", Q_irand( 1000, 3000) ); NPC->client->ps.torsoAnimTimer=0; // Just in case the firing anim is running. } else { if (TIMER_Done( NPC, "attackDelay2" )) // Can't be shooting every frame. { TIMER_Set( NPC, "attackDelay2", Q_irand( 50, 50) ); Mark1_FireBlaster(); NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_ATTACK1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); } return; } } else if (advance) { if ( NPC->client->ps.torsoAnim == BOTH_ATTACK1 ) { NPC->client->ps.torsoAnimTimer=0; // Just in case the firing anim is running. } Mark1_Hunt(); } else // Make sure he's not firing. { if ( NPC->client->ps.torsoAnim == BOTH_ATTACK1 ) { NPC->client->ps.torsoAnimTimer=0; // Just in case the firing anim is running. } } } /* ------------------------- Mark1_FireRocket ------------------------- */ void Mark1_FireRocket(void) { mdxaBone_t boltMatrix; vec3_t muzzle1,enemy_org1,delta1,angleToEnemy1; static vec3_t forward, vright, up; int damage = 50; gi.G2API_GetBoltMatrix( NPC->ghoul2, NPC->playerModel, NPC->genericBolt5, &boltMatrix, NPC->currentAngles, NPC->currentOrigin, (cg.time?cg.time:level.time), NULL, NPC->s.modelScale ); gi.G2API_GiveMeVectorFromMatrix( boltMatrix, ORIGIN, muzzle1 ); // G_PlayEffect( "blaster/muzzle_flash", muzzle1 ); CalcEntitySpot( NPC->enemy, SPOT_HEAD, enemy_org1 ); VectorSubtract (enemy_org1, muzzle1, delta1); vectoangles ( delta1, angleToEnemy1 ); AngleVectors (angleToEnemy1, forward, vright, up); G_Sound( NPC, G_SoundIndex("sound/chars/mark1/misc/mark1_fire" )); gentity_t *missile = CreateMissile( muzzle1, forward, BOWCASTER_VELOCITY, 10000, NPC ); missile->classname = "bowcaster_proj"; missile->s.weapon = WP_BOWCASTER; VectorSet( missile->maxs, BOWCASTER_SIZE, BOWCASTER_SIZE, BOWCASTER_SIZE ); VectorScale( missile->maxs, -1, missile->mins ); missile->damage = damage; missile->dflags = DAMAGE_DEATH_KNOCKBACK; missile->methodOfDeath = MOD_ENERGY; missile->clipmask = MASK_SHOT | CONTENTS_LIGHTSABER; missile->splashDamage = BOWCASTER_SPLASH_DAMAGE; missile->splashRadius = BOWCASTER_SPLASH_RADIUS; // we don't want it to bounce missile->bounceCount = 0; } /* ------------------------- Mark1_RocketAttack ------------------------- */ void Mark1_RocketAttack( qboolean advance ) { if ( TIMER_Done( NPC, "attackDelay" ) ) // Attack? { TIMER_Set( NPC, "attackDelay", Q_irand( 1000, 3000) ); NPC_SetAnim( NPC, SETANIM_TORSO, BOTH_ATTACK2, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); Mark1_FireRocket(); } else if (advance) { Mark1_Hunt(); } } /* ------------------------- Mark1_AttackDecision ------------------------- */ void Mark1_AttackDecision( void ) { int blasterTest,rocketTest; //randomly talk if ( TIMER_Done(NPC,"patrolNoise") ) { if (TIMER_Done(NPC,"angerNoise")) { // G_Sound( NPC, G_SoundIndex(va("sound/chars/mark1/misc/talk%d.wav", Q_irand(1, 4)))); TIMER_Set( NPC, "patrolNoise", Q_irand( 4000, 10000 ) ); } } // Enemy is dead or he has no enemy. if ((NPC->enemy->health<1) || ( NPC_CheckEnemyExt() == qfalse )) { NPC->enemy = NULL; return; } // Rate our distance to the target and visibility float distance = (int) DistanceHorizontalSquared( NPC->currentOrigin, NPC->enemy->currentOrigin ); distance_e distRate = ( distance > MIN_MELEE_RANGE_SQR ) ? DIST_LONG : DIST_MELEE; qboolean visible = NPC_ClearLOS( NPC->enemy ); qboolean advance = (qboolean)(distance > MIN_DISTANCE_SQR); // If we cannot see our target, move to see it if ((!visible) || (!NPC_FaceEnemy(qtrue))) { Mark1_Hunt(); return; } // See if the side weapons are there blasterTest = gi.G2API_GetSurfaceRenderStatus( &NPC->ghoul2[NPC->playerModel], "l_arm" ); rocketTest = gi.G2API_GetSurfaceRenderStatus( &NPC->ghoul2[NPC->playerModel], "r_arm" ); // It has both side weapons if (!blasterTest && !rocketTest) { ; // So do nothing. } else if (blasterTest) { distRate = DIST_LONG; } else if (rocketTest) { distRate = DIST_MELEE; } else // It should never get here, but just in case { NPC->health = 0; NPC->client->ps.stats[STAT_HEALTH] = 0; GEntity_DieFunc(NPC, NPC, NPC, 100, MOD_UNKNOWN); } // We can see enemy so shoot him if timers let you. NPC_FaceEnemy( qtrue ); if (distRate == DIST_MELEE) { Mark1_BlasterAttack(advance); } else if (distRate == DIST_LONG) { Mark1_RocketAttack(advance); } } /* ------------------------- Mark1_Patrol ------------------------- */ void Mark1_Patrol( void ) { if ( NPC_CheckPlayerTeamStealth() ) { G_Sound( NPC, G_SoundIndex("sound/chars/mark1/misc/mark1_wakeup")); NPC_UpdateAngles( qtrue, qtrue ); return; } //If we have somewhere to go, then do that if (!NPC->enemy) { if ( UpdateGoal() ) { ucmd.buttons |= BUTTON_WALKING; NPC_MoveToGoal( qtrue ); NPC_UpdateAngles( qtrue, qtrue ); } //randomly talk // if (TIMER_Done(NPC,"patrolNoise")) // { // G_Sound( NPC, G_SoundIndex(va("sound/chars/mark1/misc/talk%d.wav", Q_irand(1, 4)))); // // TIMER_Set( NPC, "patrolNoise", Q_irand( 2000, 4000 ) ); // } } } /* ------------------------- NPC_BSMark1_Default ------------------------- */ void NPC_BSMark1_Default( void ) { //NPC->e_DieFunc = dieF_Mark1_die; if ( NPC->enemy ) { NPCInfo->goalEntity = NPC->enemy; Mark1_AttackDecision(); } else if ( NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES ) { Mark1_Patrol(); } else { Mark1_Idle(); } }
0
0.962383
1
0.962383
game-dev
MEDIA
0.992416
game-dev
0.797728
1
0.797728
PaperMC/Paper
4,222
paper-api/src/generated/java/io/papermc/paper/registry/keys/tags/BannerPatternTagKeys.java
package io.papermc.paper.registry.keys.tags; import static net.kyori.adventure.key.Key.key; import io.papermc.paper.annotation.GeneratedClass; import io.papermc.paper.registry.RegistryKey; import io.papermc.paper.registry.tag.TagKey; import net.kyori.adventure.key.Key; import org.bukkit.block.banner.PatternType; import org.jspecify.annotations.NullMarked; /** * Vanilla tag keys for {@link RegistryKey#BANNER_PATTERN}. * * @apiNote The fields provided here are a direct representation of * what is available from the vanilla game source. They may be * changed (including removals) on any Minecraft version * bump, so cross-version compatibility is not provided on the * same level as it is on most of the other API. */ @SuppressWarnings({ "unused", "SpellCheckingInspection" }) @NullMarked @GeneratedClass public final class BannerPatternTagKeys { /** * {@code #minecraft:no_item_required} * * @apiNote This field is version-dependant and may be removed in future Minecraft versions */ public static final TagKey<PatternType> NO_ITEM_REQUIRED = create(key("no_item_required")); /** * {@code #minecraft:pattern_item/bordure_indented} * * @apiNote This field is version-dependant and may be removed in future Minecraft versions */ public static final TagKey<PatternType> PATTERN_ITEM_BORDURE_INDENTED = create(key("pattern_item/bordure_indented")); /** * {@code #minecraft:pattern_item/creeper} * * @apiNote This field is version-dependant and may be removed in future Minecraft versions */ public static final TagKey<PatternType> PATTERN_ITEM_CREEPER = create(key("pattern_item/creeper")); /** * {@code #minecraft:pattern_item/field_masoned} * * @apiNote This field is version-dependant and may be removed in future Minecraft versions */ public static final TagKey<PatternType> PATTERN_ITEM_FIELD_MASONED = create(key("pattern_item/field_masoned")); /** * {@code #minecraft:pattern_item/flow} * * @apiNote This field is version-dependant and may be removed in future Minecraft versions */ public static final TagKey<PatternType> PATTERN_ITEM_FLOW = create(key("pattern_item/flow")); /** * {@code #minecraft:pattern_item/flower} * * @apiNote This field is version-dependant and may be removed in future Minecraft versions */ public static final TagKey<PatternType> PATTERN_ITEM_FLOWER = create(key("pattern_item/flower")); /** * {@code #minecraft:pattern_item/globe} * * @apiNote This field is version-dependant and may be removed in future Minecraft versions */ public static final TagKey<PatternType> PATTERN_ITEM_GLOBE = create(key("pattern_item/globe")); /** * {@code #minecraft:pattern_item/guster} * * @apiNote This field is version-dependant and may be removed in future Minecraft versions */ public static final TagKey<PatternType> PATTERN_ITEM_GUSTER = create(key("pattern_item/guster")); /** * {@code #minecraft:pattern_item/mojang} * * @apiNote This field is version-dependant and may be removed in future Minecraft versions */ public static final TagKey<PatternType> PATTERN_ITEM_MOJANG = create(key("pattern_item/mojang")); /** * {@code #minecraft:pattern_item/piglin} * * @apiNote This field is version-dependant and may be removed in future Minecraft versions */ public static final TagKey<PatternType> PATTERN_ITEM_PIGLIN = create(key("pattern_item/piglin")); /** * {@code #minecraft:pattern_item/skull} * * @apiNote This field is version-dependant and may be removed in future Minecraft versions */ public static final TagKey<PatternType> PATTERN_ITEM_SKULL = create(key("pattern_item/skull")); private BannerPatternTagKeys() { } /** * Creates a tag key for {@link PatternType} in the registry {@code minecraft:banner_pattern}. * * @param key the tag key's key * @return a new tag key */ public static TagKey<PatternType> create(final Key key) { return TagKey.create(RegistryKey.BANNER_PATTERN, key); } }
0
0.647198
1
0.647198
game-dev
MEDIA
0.955684
game-dev
0.797982
1
0.797982
jedis/jediacademy
19,044
codemp/game/NPC_AI_Mark1.c
#include "b_local.h" #include "g_nav.h" #define MIN_MELEE_RANGE 320 #define MIN_MELEE_RANGE_SQR ( MIN_MELEE_RANGE * MIN_MELEE_RANGE ) #define MIN_DISTANCE 128 #define MIN_DISTANCE_SQR ( MIN_DISTANCE * MIN_DISTANCE ) #define TURN_OFF 0x00000100 #define LEFT_ARM_HEALTH 40 #define RIGHT_ARM_HEALTH 40 #define AMMO_POD_HEALTH 40 #define BOWCASTER_VELOCITY 1300 #define BOWCASTER_NPC_DAMAGE_EASY 12 #define BOWCASTER_NPC_DAMAGE_NORMAL 24 #define BOWCASTER_NPC_DAMAGE_HARD 36 #define BOWCASTER_SIZE 2 #define BOWCASTER_SPLASH_DAMAGE 0 #define BOWCASTER_SPLASH_RADIUS 0 //Local state enums enum { LSTATE_NONE = 0, LSTATE_ASLEEP, LSTATE_WAKEUP, LSTATE_FIRED0, LSTATE_FIRED1, LSTATE_FIRED2, LSTATE_FIRED3, LSTATE_FIRED4, }; qboolean NPC_CheckPlayerTeamStealth( void ); void Mark1_BlasterAttack(qboolean advance); void DeathFX( gentity_t *ent ); #include "../namespace_begin.h" extern gitem_t *BG_FindItemForAmmo( ammo_t ammo ); #include "../namespace_end.h" /* ------------------------- NPC_Mark1_Precache ------------------------- */ void NPC_Mark1_Precache(void) { G_SoundIndex( "sound/chars/mark1/misc/mark1_wakeup"); G_SoundIndex( "sound/chars/mark1/misc/shutdown"); G_SoundIndex( "sound/chars/mark1/misc/walk"); G_SoundIndex( "sound/chars/mark1/misc/run"); G_SoundIndex( "sound/chars/mark1/misc/death1"); G_SoundIndex( "sound/chars/mark1/misc/death2"); G_SoundIndex( "sound/chars/mark1/misc/anger"); G_SoundIndex( "sound/chars/mark1/misc/mark1_fire"); G_SoundIndex( "sound/chars/mark1/misc/mark1_pain"); G_SoundIndex( "sound/chars/mark1/misc/mark1_explo"); // G_EffectIndex( "small_chunks"); G_EffectIndex( "env/med_explode2"); G_EffectIndex( "explosions/probeexplosion1"); G_EffectIndex( "blaster/smoke_bolton"); G_EffectIndex( "bryar/muzzle_flash"); G_EffectIndex( "explosions/droidexplosion1" ); RegisterItem( BG_FindItemForAmmo( AMMO_METAL_BOLTS)); RegisterItem( BG_FindItemForAmmo( AMMO_BLASTER )); RegisterItem( BG_FindItemForWeapon( WP_BOWCASTER )); RegisterItem( BG_FindItemForWeapon( WP_BRYAR_PISTOL )); } /* ------------------------- NPC_Mark1_Part_Explode ------------------------- */ void NPC_Mark1_Part_Explode( gentity_t *self, int bolt ) { if ( bolt >=0 ) { mdxaBone_t boltMatrix; vec3_t org, dir; trap_G2API_GetBoltMatrix( self->ghoul2, 0, bolt, &boltMatrix, self->r.currentAngles, self->r.currentOrigin, level.time, NULL, self->modelScale ); BG_GiveMeVectorFromMatrix( &boltMatrix, ORIGIN, org ); BG_GiveMeVectorFromMatrix( &boltMatrix, NEGATIVE_Y, dir ); G_PlayEffectID( G_EffectIndex("env/med_explode2"), org, dir ); G_PlayEffectID( G_EffectIndex("blaster/smoke_bolton"), org, dir ); } //G_PlayEffectID( G_EffectIndex("blaster/smoke_bolton"), self->playerModel, bolt, self->s.number ); } /* ------------------------- Mark1_Idle ------------------------- */ void Mark1_Idle( void ) { NPC_BSIdle(); NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_SLEEP1, SETANIM_FLAG_NORMAL ); } /* ------------------------- Mark1Dead_FireRocket - Shoot the left weapon, the multi-blaster ------------------------- */ void Mark1Dead_FireRocket (void) { mdxaBone_t boltMatrix; vec3_t muzzle1,muzzle_dir; gentity_t *missile; int damage = 50; int bolt = trap_G2API_AddBolt(NPC->ghoul2, 0, "*flash5"); trap_G2API_GetBoltMatrix( NPC->ghoul2, 0, bolt, &boltMatrix, NPC->r.currentAngles, NPC->r.currentOrigin, level.time, NULL, NPC->modelScale ); BG_GiveMeVectorFromMatrix( &boltMatrix, ORIGIN, muzzle1 ); BG_GiveMeVectorFromMatrix( &boltMatrix, NEGATIVE_Y, muzzle_dir ); G_PlayEffectID( G_EffectIndex("bryar/muzzle_flash"), muzzle1, muzzle_dir ); G_Sound( NPC, CHAN_AUTO, G_SoundIndex("sound/chars/mark1/misc/mark1_fire")); missile = CreateMissile( muzzle1, muzzle_dir, BOWCASTER_VELOCITY, 10000, NPC, qfalse ); missile->classname = "bowcaster_proj"; missile->s.weapon = WP_BOWCASTER; VectorSet( missile->r.maxs, BOWCASTER_SIZE, BOWCASTER_SIZE, BOWCASTER_SIZE ); VectorScale( missile->r.maxs, -1, missile->r.mins ); missile->damage = damage; missile->dflags = DAMAGE_DEATH_KNOCKBACK; //missile->methodOfDeath = MOD_ENERGY; missile->methodOfDeath = MOD_ROCKET; missile->clipmask = MASK_SHOT | CONTENTS_LIGHTSABER; missile->splashDamage = BOWCASTER_SPLASH_DAMAGE; missile->splashRadius = BOWCASTER_SPLASH_RADIUS; // we don't want it to bounce missile->bounceCount = 0; } /* ------------------------- Mark1Dead_FireBlaster - Shoot the left weapon, the multi-blaster ------------------------- */ void Mark1Dead_FireBlaster (void) { vec3_t muzzle1,muzzle_dir; gentity_t *missile; mdxaBone_t boltMatrix; int bolt; bolt = trap_G2API_AddBolt(NPC->ghoul2, 0, "*flash1"); trap_G2API_GetBoltMatrix( NPC->ghoul2, 0, bolt, &boltMatrix, NPC->r.currentAngles, NPC->r.currentOrigin, level.time, NULL, NPC->modelScale ); BG_GiveMeVectorFromMatrix( &boltMatrix, ORIGIN, muzzle1 ); BG_GiveMeVectorFromMatrix( &boltMatrix, NEGATIVE_Y, muzzle_dir ); G_PlayEffectID( G_EffectIndex("bryar/muzzle_flash"), muzzle1, muzzle_dir ); missile = CreateMissile( muzzle1, muzzle_dir, 1600, 10000, NPC, qfalse ); G_Sound( NPC, CHAN_AUTO, G_SoundIndex("sound/chars/mark1/misc/mark1_fire")); missile->classname = "bryar_proj"; missile->s.weapon = WP_BRYAR_PISTOL; missile->damage = 1; missile->dflags = DAMAGE_DEATH_KNOCKBACK; missile->methodOfDeath = MOD_BRYAR_PISTOL; missile->clipmask = MASK_SHOT | CONTENTS_LIGHTSABER; } /* ------------------------- Mark1_die ------------------------- */ void Mark1_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int damage, int mod,int dFlags,int hitLoc ) { /* int anim; // Is he dead already? anim = self->client->ps.legsAnim; if (((anim==BOTH_DEATH1) || (anim==BOTH_DEATH2)) && (self->client->ps.torsoTimer<=0)) { // This is because self->health keeps getting zeroed out. HL_NONE acts as health in this case. self->locationDamage[HL_NONE] += damage; if (self->locationDamage[HL_NONE] > 50) { DeathFX(self); self->client->ps.eFlags |= EF_NODRAW; self->contents = CONTENTS_CORPSE; // G_FreeEntity( self ); // Is this safe? I can't see why we'd mark it nodraw and then just leave it around?? self->e_ThinkFunc = thinkF_G_FreeEntity; self->nextthink = level.time + FRAMETIME; } return; } */ G_Sound( self, CHAN_AUTO, G_SoundIndex(va("sound/chars/mark1/misc/death%d.wav",Q_irand( 1, 2)))); // Choose a death anim if (Q_irand( 1, 10) > 5) { NPC_SetAnim( self, SETANIM_BOTH, BOTH_DEATH2, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); } else { NPC_SetAnim( self, SETANIM_BOTH, BOTH_DEATH1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); } } /* ------------------------- Mark1_dying ------------------------- */ void Mark1_dying( gentity_t *self ) { int num,newBolt; if (self->client->ps.torsoTimer>0) { if (TIMER_Done(self,"dyingExplosion")) { num = Q_irand( 1, 3); // Find place to generate explosion if (num == 1) { num = Q_irand( 8, 10); newBolt = trap_G2API_AddBolt( self->ghoul2, 0, va("*flash%d",num) ); NPC_Mark1_Part_Explode(self,newBolt); } else { num = Q_irand( 1, 6); newBolt = trap_G2API_AddBolt( self->ghoul2, 0, va("*torso_tube%d",num) ); NPC_Mark1_Part_Explode(self,newBolt); NPC_SetSurfaceOnOff( self, va("torso_tube%d",num), TURN_OFF ); } TIMER_Set( self, "dyingExplosion", Q_irand( 300, 1000 ) ); } // int dir; // vec3_t right; // Shove to the side // AngleVectors( self->client->renderInfo.eyeAngles, NULL, right, NULL ); // VectorMA( self->client->ps.velocity, -80, right, self->client->ps.velocity ); // See which weapons are there // Randomly fire blaster if (!trap_G2API_GetSurfaceRenderStatus( self->ghoul2, 0, "l_arm" )) // Is the blaster still on the model? { if (Q_irand( 1, 5) == 1) { SaveNPCGlobals(); SetNPCGlobals( self ); Mark1Dead_FireBlaster(); RestoreNPCGlobals(); } } // Randomly fire rocket if (!trap_G2API_GetSurfaceRenderStatus( self->ghoul2, 0, "r_arm" )) // Is the rocket still on the model? { if (Q_irand( 1, 10) == 1) { SaveNPCGlobals(); SetNPCGlobals( self ); Mark1Dead_FireRocket(); RestoreNPCGlobals(); } } } } /* ------------------------- NPC_Mark1_Pain - look at what was hit and see if it should be removed from the model. ------------------------- */ void NPC_Mark1_Pain(gentity_t *self, gentity_t *attacker, int damage) { int newBolt,i,chance; int hitLoc = gPainHitLoc; NPC_Pain( self, attacker, damage ); G_Sound( self, CHAN_AUTO, G_SoundIndex("sound/chars/mark1/misc/mark1_pain")); // Hit in the CHEST??? if (hitLoc==HL_CHEST) { chance = Q_irand( 1, 4); if ((chance == 1) && (damage > 5)) { NPC_SetAnim( self, SETANIM_BOTH, BOTH_PAIN1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); } } // Hit in the left arm? else if ((hitLoc==HL_ARM_LT) && (self->locationDamage[HL_ARM_LT] > LEFT_ARM_HEALTH)) { if (self->locationDamage[hitLoc] >= LEFT_ARM_HEALTH) // Blow it up? { newBolt = trap_G2API_AddBolt( self->ghoul2, 0, "*flash3" ); if ( newBolt != -1 ) { NPC_Mark1_Part_Explode(self,newBolt); } NPC_SetSurfaceOnOff( self, "l_arm", TURN_OFF ); } } // Hit in the right arm? else if ((hitLoc==HL_ARM_RT) && (self->locationDamage[HL_ARM_RT] > RIGHT_ARM_HEALTH)) // Blow it up? { if (self->locationDamage[hitLoc] >= RIGHT_ARM_HEALTH) { newBolt = trap_G2API_AddBolt( self->ghoul2, 0, "*flash4" ); if ( newBolt != -1 ) { // G_PlayEffect( "small_chunks", self->playerModel, self->genericBolt2, self->s.number); NPC_Mark1_Part_Explode( self, newBolt ); } NPC_SetSurfaceOnOff( self, "r_arm", TURN_OFF ); } } // Check ammo pods else { for (i=0;i<6;i++) { if ((hitLoc==HL_GENERIC1+i) && (self->locationDamage[HL_GENERIC1+i] > AMMO_POD_HEALTH)) // Blow it up? { if (self->locationDamage[hitLoc] >= AMMO_POD_HEALTH) { newBolt = trap_G2API_AddBolt( self->ghoul2, 0, va("*torso_tube%d",(i+1)) ); if ( newBolt != -1 ) { NPC_Mark1_Part_Explode(self,newBolt); } NPC_SetSurfaceOnOff( self, va("torso_tube%d",(i+1)), TURN_OFF ); NPC_SetAnim( self, SETANIM_BOTH, BOTH_PAIN1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); break; } } } } // Are both guns shot off? if ((trap_G2API_GetSurfaceRenderStatus( self->ghoul2, 0, "l_arm" )>0) && (trap_G2API_GetSurfaceRenderStatus( self->ghoul2, 0, "r_arm" )>0)) { G_Damage(self,NULL,NULL,NULL,NULL,self->health,0,MOD_UNKNOWN); } } /* ------------------------- Mark1_Hunt - look for enemy. -------------------------` */ void Mark1_Hunt(void) { if ( NPCInfo->goalEntity == NULL ) { NPCInfo->goalEntity = NPC->enemy; } NPC_FaceEnemy( qtrue ); NPCInfo->combatMove = qtrue; NPC_MoveToGoal( qtrue ); } /* ------------------------- Mark1_FireBlaster - Shoot the left weapon, the multi-blaster ------------------------- */ void Mark1_FireBlaster(void) { vec3_t muzzle1,enemy_org1,delta1,angleToEnemy1; static vec3_t forward, vright, up; static vec3_t muzzle; gentity_t *missile; mdxaBone_t boltMatrix; int bolt; // Which muzzle to fire from? if ((NPCInfo->localState <= LSTATE_FIRED0) || (NPCInfo->localState == LSTATE_FIRED4)) { NPCInfo->localState = LSTATE_FIRED1; bolt = trap_G2API_AddBolt(NPC->ghoul2, 0, "*flash1"); } else if (NPCInfo->localState == LSTATE_FIRED1) { NPCInfo->localState = LSTATE_FIRED2; bolt = trap_G2API_AddBolt(NPC->ghoul2, 0, "*flash2"); } else if (NPCInfo->localState == LSTATE_FIRED2) { NPCInfo->localState = LSTATE_FIRED3; bolt = trap_G2API_AddBolt(NPC->ghoul2, 0, "*flash3"); } else { NPCInfo->localState = LSTATE_FIRED4; bolt = trap_G2API_AddBolt(NPC->ghoul2, 0, "*flash4"); } trap_G2API_GetBoltMatrix( NPC->ghoul2, 0, bolt, &boltMatrix, NPC->r.currentAngles, NPC->r.currentOrigin, level.time, NULL, NPC->modelScale ); BG_GiveMeVectorFromMatrix( &boltMatrix, ORIGIN, muzzle1 ); if (NPC->health) { CalcEntitySpot( NPC->enemy, SPOT_HEAD, enemy_org1 ); VectorSubtract (enemy_org1, muzzle1, delta1); vectoangles ( delta1, angleToEnemy1 ); AngleVectors (angleToEnemy1, forward, vright, up); } else { AngleVectors (NPC->r.currentAngles, forward, vright, up); } G_PlayEffectID( G_EffectIndex("bryar/muzzle_flash"), muzzle1, forward ); G_Sound( NPC, CHAN_AUTO, G_SoundIndex("sound/chars/mark1/misc/mark1_fire")); missile = CreateMissile( muzzle1, forward, 1600, 10000, NPC, qfalse ); missile->classname = "bryar_proj"; missile->s.weapon = WP_BRYAR_PISTOL; missile->damage = 1; missile->dflags = DAMAGE_DEATH_KNOCKBACK; missile->methodOfDeath = MOD_BRYAR_PISTOL; missile->clipmask = MASK_SHOT | CONTENTS_LIGHTSABER; } /* ------------------------- Mark1_BlasterAttack ------------------------- */ void Mark1_BlasterAttack(qboolean advance ) { int chance; if ( TIMER_Done( NPC, "attackDelay" ) ) // Attack? { chance = Q_irand( 1, 5); NPCInfo->burstCount++; if (NPCInfo->burstCount<3) // Too few shots this burst? { chance = 2; // Force it to keep firing. } else if (NPCInfo->burstCount>12) // Too many shots fired this burst? { NPCInfo->burstCount = 0; chance = 1; // Force it to stop firing. } // Stop firing. if (chance == 1) { NPCInfo->burstCount = 0; TIMER_Set( NPC, "attackDelay", Q_irand( 1000, 3000) ); NPC->client->ps.torsoTimer=0; // Just in case the firing anim is running. } else { if (TIMER_Done( NPC, "attackDelay2" )) // Can't be shooting every frame. { TIMER_Set( NPC, "attackDelay2", Q_irand( 50, 50) ); Mark1_FireBlaster(); NPC_SetAnim( NPC, SETANIM_BOTH, BOTH_ATTACK1, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); } return; } } else if (advance) { if ( NPC->client->ps.torsoAnim == BOTH_ATTACK1 ) { NPC->client->ps.torsoTimer=0; // Just in case the firing anim is running. } Mark1_Hunt(); } else // Make sure he's not firing. { if ( NPC->client->ps.torsoAnim == BOTH_ATTACK1 ) { NPC->client->ps.torsoTimer=0; // Just in case the firing anim is running. } } } /* ------------------------- Mark1_FireRocket ------------------------- */ void Mark1_FireRocket(void) { mdxaBone_t boltMatrix; vec3_t muzzle1,enemy_org1,delta1,angleToEnemy1; static vec3_t forward, vright, up; int bolt = trap_G2API_AddBolt(NPC->ghoul2, 0, "*flash5"); gentity_t *missile; int damage = 50; trap_G2API_GetBoltMatrix( NPC->ghoul2, 0, bolt, &boltMatrix, NPC->r.currentAngles, NPC->r.currentOrigin, level.time, NULL, NPC->modelScale ); BG_GiveMeVectorFromMatrix( &boltMatrix, ORIGIN, muzzle1 ); // G_PlayEffect( "blaster/muzzle_flash", muzzle1 ); CalcEntitySpot( NPC->enemy, SPOT_HEAD, enemy_org1 ); VectorSubtract (enemy_org1, muzzle1, delta1); vectoangles ( delta1, angleToEnemy1 ); AngleVectors (angleToEnemy1, forward, vright, up); G_Sound( NPC, CHAN_AUTO, G_SoundIndex("sound/chars/mark1/misc/mark1_fire" )); missile = CreateMissile( muzzle1, forward, BOWCASTER_VELOCITY, 10000, NPC, qfalse ); missile->classname = "bowcaster_proj"; missile->s.weapon = WP_BOWCASTER; VectorSet( missile->r.maxs, BOWCASTER_SIZE, BOWCASTER_SIZE, BOWCASTER_SIZE ); VectorScale( missile->r.maxs, -1, missile->r.mins ); missile->damage = damage; missile->dflags = DAMAGE_DEATH_KNOCKBACK; missile->methodOfDeath = MOD_ROCKET; missile->clipmask = MASK_SHOT | CONTENTS_LIGHTSABER; missile->splashDamage = BOWCASTER_SPLASH_DAMAGE; missile->splashRadius = BOWCASTER_SPLASH_RADIUS; // we don't want it to bounce missile->bounceCount = 0; } /* ------------------------- Mark1_RocketAttack ------------------------- */ void Mark1_RocketAttack( qboolean advance ) { if ( TIMER_Done( NPC, "attackDelay" ) ) // Attack? { TIMER_Set( NPC, "attackDelay", Q_irand( 1000, 3000) ); NPC_SetAnim( NPC, SETANIM_TORSO, BOTH_ATTACK2, SETANIM_FLAG_OVERRIDE|SETANIM_FLAG_HOLD ); Mark1_FireRocket(); } else if (advance) { Mark1_Hunt(); } } /* ------------------------- Mark1_AttackDecision ------------------------- */ void Mark1_AttackDecision( void ) { int blasterTest,rocketTest; float distance; distance_e distRate; qboolean visible; qboolean advance; //randomly talk if ( TIMER_Done(NPC,"patrolNoise") ) { if (TIMER_Done(NPC,"angerNoise")) { // G_Sound( NPC, G_SoundIndex(va("sound/chars/mark1/misc/talk%d.wav", Q_irand(1, 4)))); TIMER_Set( NPC, "patrolNoise", Q_irand( 4000, 10000 ) ); } } // Enemy is dead or he has no enemy. if ((NPC->enemy->health<1) || ( NPC_CheckEnemyExt(qfalse) == qfalse )) { NPC->enemy = NULL; return; } // Rate our distance to the target and visibility distance = (int) DistanceHorizontalSquared( NPC->r.currentOrigin, NPC->enemy->r.currentOrigin ); distRate = ( distance > MIN_MELEE_RANGE_SQR ) ? DIST_LONG : DIST_MELEE; visible = NPC_ClearLOS4( NPC->enemy ); advance = (qboolean)(distance > MIN_DISTANCE_SQR); // If we cannot see our target, move to see it if ((!visible) || (!NPC_FaceEnemy(qtrue))) { Mark1_Hunt(); return; } // See if the side weapons are there blasterTest = trap_G2API_GetSurfaceRenderStatus( NPC->ghoul2, 0, "l_arm" ); rocketTest = trap_G2API_GetSurfaceRenderStatus( NPC->ghoul2, 0, "r_arm" ); // It has both side weapons if (!blasterTest && !rocketTest) { ; // So do nothing. } else if (blasterTest!=-1 &&blasterTest) { distRate = DIST_LONG; } else if (rocketTest!=-1 &&rocketTest) { distRate = DIST_MELEE; } else // It should never get here, but just in case { NPC->health = 0; NPC->client->ps.stats[STAT_HEALTH] = 0; //GEntity_DieFunc(NPC, NPC, NPC, 100, MOD_UNKNOWN); if (NPC->die) { NPC->die(NPC, NPC, NPC, 100, MOD_UNKNOWN); } } // We can see enemy so shoot him if timers let you. NPC_FaceEnemy( qtrue ); if (distRate == DIST_MELEE) { Mark1_BlasterAttack(advance); } else if (distRate == DIST_LONG) { Mark1_RocketAttack(advance); } } /* ------------------------- Mark1_Patrol ------------------------- */ void Mark1_Patrol( void ) { if ( NPC_CheckPlayerTeamStealth() ) { G_Sound( NPC, CHAN_AUTO, G_SoundIndex("sound/chars/mark1/misc/mark1_wakeup")); NPC_UpdateAngles( qtrue, qtrue ); return; } //If we have somewhere to go, then do that if (!NPC->enemy) { if ( UpdateGoal() ) { ucmd.buttons |= BUTTON_WALKING; NPC_MoveToGoal( qtrue ); NPC_UpdateAngles( qtrue, qtrue ); } //randomly talk // if (TIMER_Done(NPC,"patrolNoise")) // { // G_Sound( NPC, G_SoundIndex(va("sound/chars/mark1/misc/talk%d.wav", Q_irand(1, 4)))); // // TIMER_Set( NPC, "patrolNoise", Q_irand( 2000, 4000 ) ); // } } } /* ------------------------- NPC_BSMark1_Default ------------------------- */ void NPC_BSMark1_Default( void ) { //NPC->e_DieFunc = dieF_Mark1_die; if ( NPC->enemy ) { NPCInfo->goalEntity = NPC->enemy; Mark1_AttackDecision(); } else if ( NPCInfo->scriptFlags & SCF_LOOK_FOR_ENEMIES ) { Mark1_Patrol(); } else { Mark1_Idle(); } }
0
0.968761
1
0.968761
game-dev
MEDIA
0.993131
game-dev
0.72881
1
0.72881
mastercomfig/tf2-patches-old
1,386
src/game/server/ai_speechfilter.h
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // //=============================================================================// #ifndef AI_SPEECHFILTER_H #define AI_SPEECHFILTER_H #ifdef _WIN32 #pragma once #endif //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- class CAI_SpeechFilter : public CBaseEntity, public IEntityListener { DECLARE_CLASS( CAI_SpeechFilter, CBaseEntity ); public: DECLARE_DATADESC(); void Spawn( void ); void Activate( void ); void UpdateOnRemove( void ); void Enable( bool bEnable ); void InputEnable( inputdata_t &inputdata ); void InputDisable( inputdata_t &inputdata ); void InputSetIdleModifier( inputdata_t &inputdata ); void PopulateSubjectList( bool purge = false ); // Accessors for our NPC float GetIdleModifier( void ) { return m_flIdleModifier; } bool NeverSayHello( void ) { return m_bNeverSayHello; } void OnEntityCreated( CBaseEntity *pEntity ); void OnEntityDeleted( CBaseEntity *pEntity ); protected: string_t m_iszSubject; float m_flIdleModifier; // Multiplier to the percentage chance that our NPC will idle speak bool m_bNeverSayHello; // If set, the NPC never says hello to the player bool m_bDisabled; }; #endif // AI_SPEECHFILTER_H
0
0.904847
1
0.904847
game-dev
MEDIA
0.779024
game-dev,audio-video-media
0.589437
1
0.589437
unresolved3169/Turanic
1,595
src/pocketmine/command/defaults/SeedCommand.php
<?php /* * * * _______ _ * |__ __| (_) * | |_ _ _ __ __ _ _ __ _ ___ * | | | | | '__/ _` | '_ \| |/ __| * | | |_| | | | (_| | | | | | (__ * |_|\__,_|_| \__,_|_| |_|_|\___| * * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * @author TuranicTeam * @link https://github.com/TuranicTeam/Turanic * * */ namespace pocketmine\command\defaults; use pocketmine\command\CommandSender; use pocketmine\event\TranslationContainer; use pocketmine\Player; class SeedCommand extends VanillaCommand { /** * SeedCommand constructor. * * @param string $name */ public function __construct($name){ parent::__construct( $name, "%pocketmine.command.seed.description", "%pocketmine.command.seed.usage" ); $this->setPermission("pocketmine.command.seed"); } /** * @param CommandSender $sender * @param string $currentAlias * @param array $args * * @return bool */ public function execute(CommandSender $sender, string $currentAlias, array $args){ if(!$this->canExecute($sender)){ return true; } if($sender instanceof Player){ $seed = $sender->getLevel()->getSeed(); }else{ $seed = $sender->getServer()->getDefaultLevel()->getSeed(); } $sender->sendMessage(new TranslationContainer("commands.seed.success", [$seed])); return true; } }
0
0.818501
1
0.818501
game-dev
MEDIA
0.911065
game-dev
0.641072
1
0.641072
KZGlobalTeam/cs2kz-metamod
2,094
src/sdk/cinbuttonstate.h
#pragma once #include "common.h" #include "utils/schema.h" enum EInButtonState : uint64_t { IN_BUTTON_UP = 0x0, IN_BUTTON_DOWN = 0x1, IN_BUTTON_DOWN_UP = 0x2, IN_BUTTON_UP_DOWN = 0x3, IN_BUTTON_UP_DOWN_UP = 0x4, IN_BUTTON_DOWN_UP_DOWN = 0x5, IN_BUTTON_DOWN_UP_DOWN_UP = 0x6, IN_BUTTON_UP_DOWN_UP_DOWN = 0x7, IN_BUTTON_STATE_COUNT = 0x8, }; class CInButtonState { DECLARE_SCHEMA_CLASS(CInButtonState); public: SCHEMA_FIELD_POINTER(uint64, m_pButtonStates); void GetButtons(uint64 buttons[3]) { for (int i = 0; i < 3; i++) { buttons[i] = this->m_pButtonStates[i]; } } EInButtonState GetButtonState(uint64 button) { return (EInButtonState)(!!(this->m_pButtonStates[0] & button) + !!(this->m_pButtonStates[1] & button) * 2 + !!(this->m_pButtonStates[2] & button) * 4); }; bool IsButtonNewlyPressed(uint64 button) { return this->GetButtonState(button) >= 3; } static bool IsButtonPressed(uint64 buttons[3], uint64 button, bool onlyDown = false) { if (onlyDown) { return buttons[0] & button; } else { bool multipleKeys = (button & (button - 1)); if (multipleKeys) { u64 currentButton = button; u64 key = 0; if (button) { while (true) { if (currentButton & 1) { u64 keyMask = 1ull << key; EInButtonState keyState = (EInButtonState)(keyMask && buttons[0] + (keyMask && buttons[1]) * 2 + (keyMask && buttons[2]) * 4); if (keyState > IN_BUTTON_DOWN_UP) { return true; } } key++; currentButton >>= 1; if (!currentButton) { return !!(buttons[0] & button); } } } return false; } else { EInButtonState keyState = (EInButtonState)(!!(button & buttons[0]) + !!(button & buttons[1]) * 2 + !!(button & buttons[2]) * 4); if (keyState > IN_BUTTON_DOWN_UP) { return true; } return !!(buttons[0] & button); } } } bool IsButtonPressed(uint64 button, bool onlyDown) { return CInButtonState::IsButtonPressed(this->m_pButtonStates, button, onlyDown); } };
0
0.899824
1
0.899824
game-dev
MEDIA
0.431758
game-dev
0.514915
1
0.514915
ixray-team/ixray-1.6-stcop
1,886
src/3rd-party/MagicSoftware/FreeMagic/Source/ImageAnalysis/MgcTImage.h
// Magic Software, Inc. // http://www.magic-software.com // Copyright (c) 2000-2002. All Rights Reserved // // Source code from Magic Software is supplied under the terms of a license // agreement and may not be copied or disclosed except in accordance with the // terms of that agreement. The various license agreements may be found at // the Magic Software web site. This file is subject to the license // // FREE SOURCE CODE // http://www.magic-software.com/License/free.pdf #ifndef MGCTIMAGE_H #define MGCTIMAGE_H #include "MgcImageConvert.h" #include "MgcLattice.h" #include <fstream> namespace Mgc { // The class T is intended to be a wrapper of native data (int, float, char, // etc.). The code uses memcpy, memcmp, and memset on the array of T values. // Class T must have the following member functions: // T::T () // T& T::operator= (T) // static const char* GetRTTI () // The static member function returns a string that is used for streaming. template <class T> class TImage : public Lattice { public: // Construction and destruction. TImage accepts responsibility for // deleting the input arrays. TImage (int iDimensions, int* aiBound, T* atData = NULL); TImage (const TImage& rkImage); TImage (const char* acFilename); virtual ~TImage (); // data access T* GetData () const; T& operator[] (int i) const; // assignment TImage& operator= (const TImage& rkImage); TImage& operator= (T tValue); // comparison bool operator== (const TImage& rkImage) const; bool operator!= (const TImage& rkImage) const; // streaming bool Load (const char* acFilename); bool Save (const char* acFilename) const; protected: // for deferred creation of bounds TImage (int iDimensions); void SetData (T* atData); T* m_atData; }; #include "MgcTImage.inl" } // namespace Mgc #endif
0
0.780608
1
0.780608
game-dev
MEDIA
0.407293
game-dev
0.558953
1
0.558953
Goob-Station/Goob-Station
2,257
Content.Client/_Shitcode/Heretic/GhoulSystem.cs
// SPDX-FileCopyrightText: 2025 Aiden <28298836+Aidenkrz@users.noreply.github.com> // SPDX-FileCopyrightText: 2025 Aiden <aiden@djkraz.com> // SPDX-FileCopyrightText: 2025 GoobBot <uristmchands@proton.me> // SPDX-FileCopyrightText: 2025 JohnOakman <sremy2012@hotmail.fr> // SPDX-FileCopyrightText: 2025 Misandry <mary@thughunt.ing> // SPDX-FileCopyrightText: 2025 SolsticeOfTheWinter <solsticeofthewinter@gmail.com> // SPDX-FileCopyrightText: 2025 TheBorzoiMustConsume <197824988+TheBorzoiMustConsume@users.noreply.github.com> // SPDX-FileCopyrightText: 2025 github-actions <github-actions@github.com> // SPDX-FileCopyrightText: 2025 gus <august.eymann@gmail.com> // // SPDX-License-Identifier: AGPL-3.0-or-later using Content.Shared.Heretic; using Content.Shared.StatusIcon.Components; using Robust.Client.Player; using Robust.Shared.Prototypes; namespace Content.Client._Shitcode.Heretic; public sealed partial class GhoulSystem : EntitySystem { [Dependency] private readonly IPrototypeManager _prototype = default!; [Dependency] private readonly IPlayerManager _player = default!; public override void Initialize() { base.Initialize(); SubscribeLocalEvent<HereticComponent, GetStatusIconsEvent>(OnHereticMasterIcons); SubscribeLocalEvent<GhoulComponent, GetStatusIconsEvent>(OnGhoulIcons); } /// <summary> /// Show to ghouls who their master is /// </summary> private void OnHereticMasterIcons(Entity<HereticComponent> ent, ref GetStatusIconsEvent args) { var player = _player.LocalEntity; if (!TryComp<GhoulComponent>(player, out var playerGhoul)) return; if (GetNetEntity(ent.Owner) != playerGhoul.BoundHeretic) return; if (_prototype.TryIndex(playerGhoul.MasterIcon, out var iconPrototype)) args.StatusIcons.Add(iconPrototype); } /// <summary> /// Show an icon for all ghouls to all ghouls and all heretics. /// </summary> private void OnGhoulIcons(Entity<GhoulComponent> ent, ref GetStatusIconsEvent args) { var player = _player.LocalEntity; if (_prototype.TryIndex(ent.Comp.GhoulIcon, out var iconPrototype)) args.StatusIcons.Add(iconPrototype); } }
0
0.804183
1
0.804183
game-dev
MEDIA
0.630192
game-dev
0.754855
1
0.754855
ggnkua/Atari_ST_Sources
44,974
ASM/Mcoder/3D/VINCENT/3D3.S
; ------------------------------------------- ; ; The maxi-optimyzed 3D Z-rout ; ; (C) 1989-90 Vincent PENNE (Ziggy STARDUST). ; ; ------------------------------------------- ; output 3d2.tos opt o+,ow-,m+ ; opt P=68030 ; #[ Constantes et macros: TRUE = -1 FALSE = 0 ; Parametre systeme NECR = 8 DEBUG = TRUE BOMB = TRUE ; Variable pour les calculs 3D TSINUS = 1024 DISTEC = 32 ; Organisation de la palette (Pour l'instant 1 plan par couleur) COLFOND = $000 TAILPAL = 16 ; (Jusqu'a 512!!) MINCOL = 0 MAXCOL = 3 ; Parametre pour le tracage des lignes horizontales, configuration de l'ecran NBLIG = 200 LECRAN = 320 DEPASSE = 512 MINX = 0 MAXX = 320 Vsync MACRO move #$25,-(a7) trap #14 addq #2,a7 ENDM Vsync_no_interrupt MACRO .waitvbl\@: move.b $ffff8205.w,d0 cmp.b $ffff8201.w,d0 bne.s .waitvbl\@ move.b $ffff8207.w,d0 cmp.b $ffff8203.w,d0 bne.s .waitvbl\@ tst.b $ffff8209.w bne.s .waitvbl\@ ENDM Tstcol MACRO IFNE DEBUG tst.b tcol beq.s .nc\@ move #\1,$ffff8240.w .nc\@: ENDC ENDM Print MACRO pea \1 move #9,-(a7) trap #1 addq #6,a7 ENDM Flab MACRO a\@: ENDM ; #] Constantes et macros: ; #[ Debut: debut: clr -(a7) move #$20,-(a7) trap #1 addq.l #4,a7 bsr init move.l #obj1,curobj lea init_val(pc),a1 lea current_val(pc),a2 moveq #(init_val-current_val)/2-1,d0 .loop: move (a1)+,(a2)+ dbra d0,.loop move #-200,mainx mainloop: bsr anime3d bra mainloop coordx: dc.w 0 coordy: dc.w 0 mainx: dc.w 0 ; #] Debut: ; #[ Init: ; #[ Init_system: init: move.b #2,$484.w bsr relocation bsr init_hline bsr genere_circle move.l $44e.w,oldec move.l #ecran,d0 ; andi.l #$ffff00,d0 clr.b d0 ;MCODER lea ec,a0 moveq #NECR-1,d7 .loop: move.l d0,NECR*4(a0) move.l d0,(a0)+ addi.l #32000,d0 dbra d7,.loop move.l ec,ec1 move.b $ffff8260.w,oldrez movem.l $ffff8240.w,d0-d7 movem.l d0-d7,oldpal move #$2700,sr IFNE BOMB movem.l $8.w,d0-d7 movem.l d0-d7,oldbomb lea $8.w,a0 ; Redirection des bombes move.l #fin,d0 REPT 8 move.l d0,(a0)+ ENDR ENDC move.l #trap3,$80+3*4.w move #$2700,sr andi.b #%11,oldrez cmpi.b #2,oldrez bne.s .okmoni not $ffff8240.w .waitmoni: btst #7,$fffffa01.w beq.s .waitmoni Vsync_no_interrupt clr.b $ffff8260.w .waitsp: cmpi.b #$39,$fffffc02.w bne.s .waitsp .waitsp2: cmpi.b #$39,$fffffc02.w beq.s .waitsp2 .okmoni: Vsync_no_interrupt clr.b $ffff8260.w bsr initmfp bsr init_mouse move #$2300,sr bsr error_clavier btst #1,$ffff820a.w bne.s .no move #60,qfreq move #190,qtimer .no: move.l $10.w,-(a7) move.l #jump68000,$10.w sub.l a0,a0 putnop: ; movec a0,vbr illegal tst.b q68000 bne.s .no68030 move.l #line68030,qline move.l #line68030t,qlinet .no68030: move.l (a7)+,$10.w move.b ec1+3*4-4+1,$ffff8201.w move.b ec1+3*4-4+2,$ffff8203.w rts section bss q68000 ds.w 1 section text jump68000: st q68000 move.l #$4e714e71,putnop rte ; #] Init_system: ; #[ Uninit: uninit: move #$2700,sr IFNE BOMB movem.l oldbomb,d0-d7 movem.l d0-d7,$8.w ENDC move.l #$08000000,$ffff8800.w move.l #$09000000,$ffff8800.w move.l #$0a000000,$ffff8800.w jsr finmfp cmpi.b #2,oldrez bne.s .no_change_moni .waitmoni: btst #7,$fffffa01.w bne.s .waitmoni moveq #50-1,d0 bsr wait .no_change_moni: Vsync_no_interrupt move.b oldrez,$ffff8260.w bsr error_clavier move #$2300,sr move #-1,-(a7) move.l oldec,-(a7) move.l oldec,-(a7) move #5,-(a7) trap #14 adda.l #12,a7 move #$25,-(a7) trap #14 addq.l #2,a7 movem.l oldpal,d0-d7 movem.l d0-d7,$ffff8240.w bsr waitc move.b #$8,$fffffc02.w rts ; #] Uninit: ; #] Init: ; #[ Init/reinstall interupt: initmfp: move sr,-(a7) move #$2700,sr move.b $ffff820a.w,oldfreq lea $fffffa01.w,a0 lea oldmfp,a1 move #16,d0 savemfp: move.b (a0),(a1)+ addq.l #2,a0 dbra d0,savemfp movem.l $100.w,d0-d7 ; On sauvegarde les vecteur MFP movem.l d0-d7,oldvec movem.l $120.w,d0-d7 movem.l d0-d7,oldvec+$20 movem.l $58.w,d0-d7 ; Et 68000... movem.l d0-d7,oldvec+$40 bsr.s finmfp bclr #3,$fffffa17.w move.b #%00000000,$fffffa07.w move.b #%00000000,$fffffa13.w move.b #%01000000,$fffffa09.w move.b #%01000000,$fffffa15.w move.l #vbl,$70.w move.l #clavier,$118.w move (a7)+,sr rts oldfreq dc.w 0 finmfp: move sr,-(a7) move #$2700,sr moveq #0,d1 ; Ecran noir lea $ffff8240.w,a0 moveq #16/2-1,d0 .noir: move.l d1,(a0)+ dbra d0,.noir bsr waitc move.b #$22,(a0) bsr waitc move.b #$f0,(a0) bsr waitc move.b #$00,(a0) lea oldmfp,a0 lea $fffffa01.w,a1 move #16,d0 restmfp: move.b (a0)+,(a1) addq.l #2,a1 dbra d0,restmfp movem.l oldvec,d0-d7 movem.l d0-d7,$100.w movem.l oldvec+$20,d0-d7 movem.l d0-d7,$120.w movem.l oldvec+$40,d0-d7 movem.l d0-d7,$58.w move (a7)+,sr rts section bss oldvec ds.l 24 oldmfp ds.b 24 section text ; #] Init/reinstall interupt: ; #[ Wait: wait: move #13333,d1 .wait: dbra d1,.wait dbra d0,wait rts ; #] Wait: ; #[ Clavier interupt: ; #[ Interuption: clavier: tst $fffffc00.w bpl.s noclav move d0,-(a7) clr d0 move.b $fffffc02.w,d0 move.l a0,-(a7) bclr #7,d0 lea clav(pc),a0 seq (a0,d0) move.l (a7)+,a0 move (a7)+,d0 noclav: rte ; #] Interuption: ; #[ Init mouse: clav ds.b 128 even init_mouse: lea $fffffc02.w,a0 bsr.s waitc move.b #$12,(a0) bsr.s error_clavier rts waitc: btst #1,$fffffc00.w beq.s waitc rts error_clavier: btst #5,$fffffc00.w beq.s .noerror tst.b $fffffc02.w bra.s error_clavier .noerror: btst #0,$fffffc00.w beq.s .vidbuff tst.b $fffffc02.w bra.s error_clavier .vidbuff: rts ; #] Init mouse: ; #[ Test touche: Touche_objet MACRO tst.b \1(a0) beq.s .\@ move.l \2,curobj .\@ ENDM VITEZOOM = 2 test_touche: lea clav(pc),a0 Flab tst.b $4e(a0) ; '+'? beq.s .no addi #VITEZOOM,oz .no: Flab tst.b $4a(a0) ; '-'? beq.s .no subi #VITEZOOM,oz .no: Flab tst.b $72(a0) ; <Enter>? beq.s .no addi #VITEZOOM*10,oz .no: Flab tst.b $66(a0) ; '*'? beq.s .no subi #VITEZOOM*10,oz .no: Flab tst.b $1(a0) ; <Esc>? beq.s .no illegal .no: Flab tst.b $39(a0) ; <Espace>? beq.s .no jmp fin .no: Flab tst.b 59(a0) ; <F1>? beq.s .no st $f(a0) .no: Flab tst.b 60(a0) ; <F2>? beq.s .no st qaffn .no: Flab tst.b 61(a0) ; <F3>? beq.s .no sf qaffn move #NECR,neffecr .no: Flab tst.b 62(a0) ; <F4>? beq.s .no move #1,nvbl .no: Flab tst.b 63(a0) ; <F5>? beq.s .no move #2,nvbl .no: Flab sf tcol tst.b $f(a0) ; <Tab>? beq.s .no st tcol .no: Flab tst.b $68(a0) ; "8"? beq.s .no addq #1,va .no: Flab tst.b $6E(a0) ; "2"? beq.s .no subq #1,va .no: Flab tst.b $6C(a0) ; "6"? beq.s .no addq #1,vb .no: Flab tst.b $6A(a0) ; "4"? beq.s .no subq #1,vb .no: Flab tst.b $69(a0) ; "9"? beq.s .no addq #1,vg .no: Flab tst.b $6D(a0) ; "1"? beq.s .no subq #1,vg .no: Flab tst.b $0E(a0) ; <Backspace>? beq.s .no clr va clr vb clr vg .no: Flab tst.b $61(a0) ; <Undo>? beq.s .no ;#[ Reinit: move #$2700,sr moveq #128/4-1,d0 move.l a0,a1 .cl_clav: clr.l (a1)+ dbra d0,.cl_clav bsr init_mouse move #$2300,sr lea init_val(pc),a1 lea current_val(pc),a2 moveq #(init_val-current_val)/2-1,d0 .loop: move (a1)+,(a2)+ dbra d0,.loop ;#] Reinit: .no: Touche_objet 2,#obj1 Touche_objet 3,#obj2 Touche_objet 4,#obj3 Touche_objet 5,#obj4 Touche_objet 6,#obj5 Touche_objet 7,#obj6 Touche_objet 8,#obj7 Touche_objet 9,#obj8 Touche_objet 10,#obj9 Touche_objet 11,#obj10 Touche_objet 12,#obj11 Touche_objet 13,#obj12 Touche_objet 14,#obj13 Touche_objet 15,#obj14 Touche_objet 16,#obj15 Touche_objet 17,#obj16 Touche_objet 18,#obj17 Touche_objet 19,#obj18 Touche_objet 20,#obj19 Touche_objet 21,#obj20 Touche_objet 22,#obj21 Touche_objet 23,#obj22 Touche_objet 24,#obj23 Touche_objet 25,#obj24 Touche_objet 26,#obj25 Touche_objet 27,#obj26 rts ; #] Test touche: ; #] Clavier interupt: ; #[ Supervisor/User mode: trap3: ; Pour passer en superviseur rapidement move #$2300,(a7) rte retour: move.l oldpile(pc),a7 trap #3 rts oldpile dc.l 0 ; #] Supervisor/User mode: ; #[ Forme relocation: ;------------------------------ ; Liste des routine: ; ;------------------------------ ; 'Defp' : def_plot ; ; 'Anim' : anime_plot ; ; 'Inic' : init_color ; ; 'Setc' : set_color ; ; 'Affp' : call_poly ; ; 'F1p ' : face1p ; ; 'F1pt' : face1pt ; ; '1pti' : faceipti ; ; 'Vert' : vertices ; ; 'Hide' : hide ; ; 'Goto' : goto ; ; 'Enab' : enable ; ; 'Disa' : disable ; ; 'Fin ' : fin_afforme ; ;------------------------------ relocation: lea debut_objets_def-16,a0 lea debut_objets,a1 move.l a1,d1 .reloc_def: lea 16(a0),a0 move.l (a0),d0 blt.s .fin_reloc_def bgt.s .reloc_def move.l (a1)+,d0 add.l d1,d0 move.l d0,(a0) bra.s .reloc_def .fin_reloc_def: lea debut_objets,a0 lea .fin_routine_list,a3 .reloc: lea .routine_list,a2 move.l (a0),d1 cmpi.l #'Finr',d1 beq.s .fin_relocate .reloc2: cmp.l (a2)+,d1 beq.s .ident addq #4,a2 cmpa.l a3,a2 blt.s .reloc2 bra.s .noident .ident: cmpi.l #'Anim',d1 beq.s .defp cmpi.l #'Defp',d1 bne.s .nodefp .defp: move.l a0,d0 addq.l #4,d0 ;MCODER add.l d0,4(a0) .nodefp: move.l (a2)+,(a0) .noident: addq #2,a0 bra.s .reloc .fin_relocate: rts .routine_list: dc.b 'Defp' dc.l def_plot dc.b 'Anim' dc.l anime_plot dc.b 'Inic' dc.l init_color dc.b 'Setc' dc.l set_color dc.b 'Affp' dc.l call_poly dc.b 'F1p ' dc.l face1p dc.b 'F1pt' dc.l face1pt dc.b '1pti' dc.l face1pti dc.b 'Vert' dc.l vertices dc.b 'Shpr' dc.l sphere dc.b 'Hide' dc.l hide dc.b 'Goto' dc.l goto dc.b 'Enab' dc.l enable dc.b 'Disa' dc.l disable dc.b 'Fin ' dc.l fin_afforme .fin_routine_list: ; #] Forme relocation: ; #[ Afforme: ; #[ Datas: * Position de l'observateur ---> oa dc.w 0 * Angle Alpha ob dc.w 0 * Beta og dc.w 0 * et Gamma... oba dc.w 0 obb dc.w 0 obg dc.w 0 current_val: ox dc.w 0 oy dc.w 0 oz dc.w 0 cz dc.w 0 va dc.w 0 vb dc.w 0 vg dc.w 0 init_val: dc.w 0 dc.w 0 ;0 dc.w -310 dc.w 0 dc.w 0 ;-3 dc.w 0 ;6 dc.w 0 ;-9 m1 ds.w 1 ; Doivent etre consecutifs! m2 ds.w 1 m3 ds.w 1 n2 ds.w 1 n1 ds.w 1 n3 ds.w 1 o3 ds.w 1 o1 ds.w 1 o2 ds.w 1 obx ds.w 1 oby ds.w 1 obz ds.w 1 limx1 ds.w 1 limx2 ds.w 1 limy1 ds.w 1 limy2 ds.w 1 table: ; Table de sinus incbin table2 even ; Fenetre de clipping --> mix dc.w MINX miy dc.w 0 max dc.w MAXX-1 may dc.w NBLIG ty1 dc.w 32000 ty2 dc.w 0 colorpoly ds.w 1 ; couleur du polygone maxy ds.w 1 miny ds.w 1 ; Centre de l'cran ---> cx dc.w 160 cy dc.w 100-4 curcol dc.w 0 curpal dc.l pal2 ;palette: ; incbin palette.pal pal2: dc.w 0,$333,$444,$555,$666,$330,$550,$770,$700,$500,$007,$005,$500,$700,$770,$777 ; 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 dispal ds.b TAILPAL even affpal dc.l pal ; #] Datas: ; #[ Quelques MACROs...: Tstx MACRO cmpi #-DEPASSE+1,\1 bgt.s .dep1\@ move #-DEPASSE+1,\1 .dep1\@: cmpi #DEPASSE-1+LECRAN,\1 blt.s .dep2\@ move #DEPASSE-1+LECRAN,\1 .dep2\@: cmp limx1(pc),\1 bge.s .l1\@ move \1,limx1 .l1\@: cmp limx2(pc),\1 ble.s .l2\@ move \1,limx2 .l2\@: ENDM Tsty MACRO cmp limy1(pc),\1 bge.s .l1\@ move \1,limy1 .l1\@: cmp limy2(pc),\1 ble.s .l2\@ move \1,limy2 .l2\@: ENDM Next MACRO move.l (a1)+,a3 jmp (a3) ENDM ; #] Quelques MACROs...: ; #[ Afforme: even afforme: Tstcol $770 movem.l d0-d7/a0-a6,-(a7) move.l -16(a6),a1 Next fin_afforme: ;#[ Set limit and used plane: move.l curlim,a0 move limx1,d0 cmp mix(pc),d0 bge.s .1 move mix(pc),d0 .1: move d0,(a0)+ move limx2,d0 cmp max(pc),d0 ble.s .2 move max(pc),d0 .2: move d0,(a0)+ move limy1,d0 cmp miy(pc),d0 bge.s .3 move miy(pc),d0 .3: move d0,(a0)+ move limy2,d0 cmp may(pc),d0 ble.s .4 move may(pc),d0 .4: move d0,(a0)+ move.b used_plane,(a0)+ ;#] Set limit and used plane: movem.l (a7)+,d0-d7/a0-a6 rts ; #] Afforme: ; #[ Def_plot: def_plot: move.l (a1)+,a5 ; #] Def_plot: ; #[ Calcul plot: calcul_plot: ;#[ Init matrice: move -12(a6),obx move -10(a6),oby move -8(a6),obz move ox(pc),d0 sub d0,obx move oy(pc),d0 sub d0,oby move oz(pc),d0 sub d0,obz lea table+TSINUS/2(pc),a0 ; Table des sinus... lea table(pc),a2 ; et des cosinus sab equr d2 cab equr d3 sbb equr d4 cbb equr d5 sgb equr d6 cgb equr d7 move -6(a6),d0 add d0,d0 move (a0,d0),sab move (a2,d0),cab move -4(a6),d0 add d0,d0 move (a0,d0),sbb move (a2,d0),cbb move -2(a6),d0 add d0,d0 move (a0,d0),sgb move (a2,d0),cgb ; Preparation matrice lea m1(pc),a6 move sab,d0 muls cgb,d0 move cab,d1 muls sbb,d1 add.l d1,d1 swap d1 muls sgb,d1 add.l d1,d0 add.l d0,d0 swap d0 move d0,(a6)+ ; m1 move cab,d0 muls cbb,d0 add.l d0,d0 swap d0 move d0,(a6)+ ; m2 move sab,d0 muls sgb,d0 move cab,d1 muls sbb,d1 add.l d1,d1 swap d1 muls cgb,d1 sub.l d1,d0 add.l d0,d0 swap d0 move d0,(a6)+ ; m3 move sbb,(a6)+ ; n2 move cbb,d0 muls sgb,d0 add.l d0,d0 swap d0 neg d0 move d0,(a6)+ ; n1 move cbb,d0 muls cgb,d0 add.l d0,d0 swap d0 move d0,(a6)+ ; n3 move cab,d0 muls sgb,d0 move sab,d1 muls sbb,d1 add.l d1,d1 swap d1 muls cgb,d1 add.l d1,d0 add.l d0,d0 swap d0 move d0,(a6)+ ; o3 move cab,d0 muls cgb,d0 move sab,d1 muls sbb,d1 add.l d1,d1 swap d1 muls sgb,d1 sub.l d1,d0 add.l d0,d0 swap d0 move d0,(a6)+ ; o1 move sab,d0 muls cbb,d0 add.l d0,d0 swap d0 neg d0 move d0,(a6)+ ; o2 ;#] Init matrice: ;#[ Calcul points 3d: Tstcol $707 move max(pc),limx1 move mix(pc),limx2 move may(pc),limy1 move miy(pc),limy2 lea plot2d,a0 lea plot3d,a3 move (a5)+,d2 lea m1(pc),a6 loop_plot: move (a5)+,d3 move (a5)+,d4 ; Rotation autour du centre de l'objet move.l a6,a2 ; Rotation X move d2,d6 muls (a2)+,d6 move d3,d5 muls (a2)+,d5 add.l d5,d6 move d4,d5 muls (a2)+,d5 add.l d5,d6 add.l d6,d6 swap d6 ; Rotation Y move d3,d7 muls (a2)+,d7 move d2,d5 muls (a2)+,d5 add.l d5,d7 move d4,d5 muls (a2)+,d5 add.l d5,d7 add.l d7,d7 swap d7 ; Rotation Z muls (a2)+,d4 muls (a2)+,d2 add.l d2,d4 muls (a2)+,d3 add.l d3,d4 add.l d4,d4 swap d4 ; On ramene aux coordone de l'obs add (a2)+,d6 add (a2)+,d7 add (a2)+,d4 neg d7 move d6,(a3)+ move d7,(a3)+ move d4,(a3)+ cmpi #DISTEC,d4 ; Z infrieur DISTEC? ble .clipz ; Oui --> clipz ; Avec ZOOM = 256 ; (X * ZOOM) / Z + CX ext.l d6 asl.l #8,d6 divs d4,d6 add cx(pc),d6 Tstx d6 move d6,(a0)+ ; (Y * ZOOM) / Z + CY ext.l d7 asl.l #8,d7 divs d4,d7 add cy(pc),d7 move d7,(a0)+ cmp ty1(pc),d7 bgt.s .okty1 move d7,ty1 .okty1: cmp ty2(pc),d7 blt.s .okty2 move d7,ty2 .okty2: Tsty d7 move (a5)+,d2 cmpi #$8000,d2 bne loop_plot .fin_plot: Tstcol $000 Next .clipz: addq.l #4,a0 move (a5)+,d2 cmpi #$8000,d2 bne loop_plot Tstcol $000 Next ;#] Calcul points 3d: ; #] Calcul plot: ; #[ Anime plot: anime_plot: move.l (a1)+,a5 move (a1),d0 adda d0,a5 move.l a5,a4 .search_last: cmpi #$8000,(a4) beq.s .fin_search addq #6,a4 addq #6,d0 bra.s .search_last .fin_search: cmpi #$8000,2(a4) bne.s .no_last_anime moveq #-2,d0 .no_last_anime: addq #2,d0 move d0,(a1)+ bra calcul_plot ; #] Anime plot: ; #[ Init color: init_color: moveq #MINCOL,d6 lea dispal(pc),a6 REPT TAILPAL move.b #-1,(a6)+ ENDR move (a1)+,d1 lea dispal(pc),a6 clr.b (a6,d1) move.l affpal(pc),a6 move #COLFOND,(a6)+ ; Couleur 0 = couleur de fond move.l curpal,a4 add d1,d1 move (a4,d1),(a6)+ Next ; #] Init color: ; #[ Set color: set_color: move (a1)+,d0 ; Couleur de la face N lea dispal(pc),a2 tst.b (a2,d0) bge.s .okcol cmpi #MAXCOL,d6 blt.s .nomaxcol move.b #MAXCOL,(a2,d0) bra.s .okcol .nomaxcol: addq #1,d6 move.b d6,(a2,d0) move d6,d2 cmpi.b #4-1,d6 bne.s .col1 move #8-1,d2 .col1: cmpi.b #3-1,d6 bne.s .col2 move #4-1,d2 .col2: move.l curpal,a2 move d0,d3 add d3,d3 move (a2,d3),d3 .copal: move d3,(a6)+ dbra d2,.copal lea dispal(pc),a2 .okcol: move.b (a2,d0),d2 ext d2 move d2,colorpoly bset d2,used_plane Next ; #] Set color: ; #[ Hide: hide: Tstcol $070 lea plot2d,a0 lea plot3d,a4 movem (a1)+,d0-d2 move d0,d3 add d0,d3 move d3,d4 add d0,d3 add d3,d3 cmpi #DISTEC,4(a4,d3) ; Point derriere ecran? ble.s .ok ; Oui --> On ne peut pas tester la visibilite move d1,d3 add d1,d3 move d3,d5 add d1,d3 add d3,d3 cmpi #DISTEC,4(a4,d3) ble.s .ok move d2,d3 add d2,d3 move d3,d7 add d2,d3 add d3,d3 cmpi #DISTEC,4(a4,d3) ble.s .ok add d4,d4 add d5,d5 add d7,d7 move (a0,d4),d3 move (a0,d7),d1 sub (a0,d5),d3 sub (a0,d5),d1 move 2(a0,d7),d2 sub 2(a0,d5),d2 muls d2,d3 move 2(a0,d4),d2 sub 2(a0,d5),d2 muls d2,d1 cmp.l d3,d1 ; Face visible? bgt.s .ok ; Oui --> Ok add (a1),a1 Next .ok: addq #2,a1 Next ; #] Hide: ; #[ Goto face: goto: add (a1),a1 Next ; #] Goto face: ; #[ Enable: enable: move.l a1,a3 adda (a1)+,a3 move.l #enabled,(a3) Next ; #] Enable: ; #[ Disable: disable: move.l a1,a3 adda (a1)+,a3 move.l #disabled,(a3) Next ; #] Disable: ; #[ Enabled: enabled: move.l #hide,-4(a1) addq #8,a1 Next ; #] Enabled: ; #[ Disabled: disabled: move.l #hide,-4(a1) addq #6,a1 adda (a1),a1 Next ; #] Disabled: ; #[ Init 1 plane face: face1p: move.l #hline_one_plane,curline Next ; #] Init 1 plane face: ; #[ Init 1 plane tramed face: face1pt: move.l #hline_one_plane_tramed,curline Next ; #] Init 1 plane tramed face: ; #[ Init inversed 1 plane tramed face: face1pti: move.l #hline_inversed_one_plane_tramed,curline Next ; #] Init inversed 1 plane tramed face: ; #[ Vertices: vertices: Tstcol $700 lea 2(a1),a5 move.l a2,a4 lea plot2d,a0 lea plot3d,a3 lea pxy,a2 move #32767,d1 .loop_plot: move (a1)+,d0 ; --> No points blt .fin_plot add d0,d0 move d0,d3 add d0,d0 ; No point * 4 dans D0 add d0,d3 ; No point * 6 dans D3 IFNE TRUE cmpi #DISTEC,4(a3,d3) ; Point derriere ecran? bgt .okscreen ; Non ; Oui --> calcul intersection ;#[ Calcul screen intersection: move -4(a1),d4 cmpa.l a5,a1 ; Premier point? bgt.s .nofirstp ; Non move.l a1,a3 .find_end: tst (a3)+ bge.s .find_end move -4(a3),d4 lea plot3d,a3 .nofirstp: move d4,d2 add d4,d2 add d4,d2 add d2,d2 ; * 6 cmpi #DISTEC,4(a3,d2) ble .badp1 ; cx + zoom * ((x + (xx - x) * (DISTEC - z)) / (zz - z)) / DISTEC move (a3,d3),d4 sub (a3,d2),d4 move #DISTEC,d5 sub 4(a3,d2),d5 muls d5,d4 move 4(a3,d3),d5 sub 4(a3,d2),d5 divs d5,d4 add (a3,d2),d4 ; ext.l d4 ; asl.l #8,d4 ; divs #DISTEC,d4 asl #8-5,d4 ; Pour ZOOM = 256 et DISTEC = 32 add cx,d4 Tstx d4 move d4,(a2)+ ; cy + zoom * ((y + (yy - y) * (DISTEC - z)) / (zz - z)) / DISTEC move 2(a3,d3),d4 sub 2(a3,d2),d4 move #DISTEC,d5 sub 4(a3,d2),d5 muls d5,d4 move 4(a3,d3),d5 sub 4(a3,d2),d5 divs d5,d4 add 2(a3,d2),d4 ; ext.l d4 ; asl.l #8,d4 ; divs #DISTEC,d4 asl #8-5,d4 ; Pour ZOOM = 256 et DISTEC = 32 add cy,d4 Tsty d4 move d4,(a2)+ .badp1: move (a1),d4 bge.s .nolastp ; Si dernier point move -2(a5),d4 .nolastp: move d4,d2 add d4,d2 add d4,d2 add d2,d2 cmpi #DISTEC,4(a3,d2) ble .badp2 ; cx + zoom * ((x + (xx - x) * (DISTEC - z)) / (zz - z)) / DISTEC move (a3,d3),d4 sub (a3,d2),d4 move #DISTEC,d5 sub 4(a3,d2),d5 muls d5,d4 move 4(a3,d3),d5 sub 4(a3,d2),d5 divs d5,d4 add (a3,d2),d4 ; ext.l d4 ; asl.l #8,d4 ; divs #DISTEC,d4 asl #8-5,d4 ; Pour ZOOM = 256 et DISTEC = 32 add cx,d4 Tstx d4 move d4,(a2)+ ; cy + zoom * ((y + (yy - y) * (DISTEC - z)) / (zz - z)) / DISTEC move 2(a3,d3),d4 sub 2(a3,d2),d4 move #DISTEC,d5 sub 4(a3,d2),d5 muls d5,d4 move 4(a3,d3),d5 sub 4(a3,d2),d5 divs d5,d4 add 2(a3,d2),d4 ; ext.l d4 ; asl.l #8,d4 ; divs #DISTEC,d4 asl #8-5,d4 ; Pour ZOOM = 256 et DISTEC = 32 add cy,d4 Tsty d4 move d4,(a2)+ .badp2: bra .loop_plot ;#] Calcul screen intersection: .okscreen: ENDC move.l (a0,d0),d5 cmp d1,d5 bge.s .highter move.l a2,a4 move d5,d1 .highter: move.l d5,(a2)+ bra .loop_plot .fin_plot: move.l a2,a5 Next ; #] Vertices: ; #[ Sphere: sphere: move (a1)+,d0 move (a1)+,d1 lea plot2d,a2 lea plot3d,a3 add d0,d0 move d0,d2 add d0,d0 move d0,d3 add d2,d0 move 4(a3,d0),d0 cmpi #DISTEC,d0 blt .nosphere ext.l d1 ; Calcul du rayon asl #8,d1 divs d0,d1 move 2(a2,d3),d2 move (a2,d3),d3 movem.l d6/a6/a1,-(a7) move d2,d4 move d2,d5 add d1,d4 sub d1,d5 Tsty d4 Tsty d5 move d3,d4 move d3,d5 add d1,d4 sub d1,d5 Tstx d4 Tstx d5 move d1,-(a7) move d2,-(a7) bsr circle move (a7)+,d0 move (a7)+,d1 sub d1,d0 add d1,d1 move.l curline,a0 move.l ec1,a6 move colorpoly,d7 add d7,d7 adda d7,a6 bsr call_line movem.l (a7)+,d6/a6/a1 .nosphere: Next ; #] Sphere: ; #[ Call poly: call_poly: move.l a5,d7 sub.l #pxy,d7 ; Y'a-t-il moins de trois segments? cmpi #3*2,d7 ble .nopoly Tstcol $007 movem.l d6/a1/a6,-(a7) lea pxy,a6 bsr.s affpoly movem.l (a7)+,d6/a1/a6 .nopoly: Next ; #] Call poly: ; #] Afforme: ; #[ Affpoly: ; ------------------------------------------------------------------------ ; ; Filled polygone, ; ; (C) Copyright 1989-90 Vincent PENNE (Ziggy STARDUST) ; ; ------------------------------------------------------------------------ ; ; A4: Adresse du point le plus haut dans la liste ; A5: Adresse du dernier point de la liste ; A6: Adresse du premier point de la liste nopoly: rts affpoly: lea 4(a4),a0 move 2(a4),d0 move may(pc),d7 cmp miy(pc),d0 ; Miny plus petit que miy? bge.s cnegaplot ; Non move miy(pc),d0 cnegaplot: move d0,d5 lea points_droite,a2 move.l a4,a3 ;#[ Calcul right plot: ; D0 : Position Y courante ; D7 : May ; A2 : Table points droites ; A4 : Adresse points le plus haut ; A5 : Adresse du dernier point ; A6 : Adresse du premier point new_plotr: movem (a4),d1-d4 ; X1 Y1 X2 Y2 addq #4,a4 cmp.l a5,a4 blt.s .ok move.l a6,a4 move (a4),d3 move 2(a4),d4 .ok: cmp.l a3,a4 beq fin_plotr cmp d0,d4 ble.s new_plotr move d4,d6 cmp d7,d6 ; Point plus bas que may? blt.s .oklow ; Non move d7,d6 cmp d2,d7 ; Y2 superieur a Y1 courant? ble fin_plotr .oklow: add d1,d1 add d1,d1 add d3,d3 add d3,d3 sub d1,d3 sub d2,d4 cmp miy(pc),d2 bge.s .noclip sub d0,d2 ; On cherche X de dpart par rapport D0 neg d2 muls d3,d2 divs d4,d2 add d2,d1 .noclip: ext.l d3 lsl.l #5,d3 divs d4,d3 ext.l d3 lsl.l #8,d3 lsl.l #3,d3 sub d6,d0 bge .nobord addi #NBLIG,d0 swap d1 move d3,d1 beq fast_plotr addi #$8000,d1 swap d1 swap d3 add d0,d0 add d0,d0 jmp .calc_plot(pc,d0) .calc_plot: dcb.l NBLIG-1,$34c1d383 ; REPT NBLIG-1 ; move d1,(a2)+ ; addx.l d3,d1 ; ENDR move d1,(a2)+ IFNE DEBUG*0 cmp (a0),d1 bne.s .nobord not $ffff8240 ENDC .nobord: move d6,d0 bra new_plotr fin_plotr: ;#] Calcul right plot: lea points_gauche,a2 move.l a0,a3 move d5,d0 ;#[ Calcul left plot: ; D0 : Position Y courante ; D7 : May ; A2 : Table points gauches ; A0 : Adresse points le plus haut ; A5 : Adresse du dernier point ; A6 : Adresse du premier point new_plotl: move -(a0),d2 ; Y1 move -(a0),d1 ; X1 cmp.l a6,a0 bgt.s .ok move.l a5,a0 .ok: move -2(a0),d4 ; Y2 move -4(a0),d3 ; X2 cmp.l a3,a0 beq fin_plotl cmp d5,d4 ble.s new_plotl move d4,d6 cmp d7,d6 ; Point plus bas que may? blt.s .oklow ; Non move d7,d6 cmp d2,d7 ; Y2 superieur a Y1 courant? ble fin_plotl .oklow: add d1,d1 add d1,d1 add d3,d3 add d3,d3 sub d1,d3 sub d2,d4 cmp miy(pc),d2 bge.s .noclip sub d5,d2 ; On cherche X de dpart par rapport d5 neg d2 muls d3,d2 divs d4,d2 add d2,d1 .noclip: ext.l d3 lsl.l #5,d3 divs d4,d3 ext.l d3 lsl.l #8,d3 lsl.l #3,d3 sub d6,d5 bge .nobord addi #NBLIG,d5 swap d1 move d3,d1 beq fast_plotl addi #$8000,d1 swap d1 swap d3 add d5,d5 add d5,d5 jmp .calc_plot(pc,d5) .calc_plot: dcb.l NBLIG-1,$34c1d383 ; REPT NBLIG-1 ; move d1,(a2)+ ; addx.l d3,d1 ; ENDR move d1,(a2)+ IFNE DEBUG*0 cmp (a0),d1 bne.s .nobord not $ffff8240 ENDC .nobord: move d6,d5 bra new_plotl fin_plotl: ;#] Calcul left plot: move d5,d1 sub d0,d1 move colorpoly(pc),d2 move.l ec1,a6 add d2,d2 adda d2,a6 Tstcol $077 move.l curline,a0 bsr call_line rts ;#[ Fast calcul: fast_plotl: swap d1 swap d3 beq very_fast_plotl add d5,d5 add d5,d5 jmp .calc_fplot(pc,d5) .calc_fplot: dcb.l NBLIG,$34c1d243 ; REPT NBLIG ; move d1,(a2)+ ; add d3,d1 ; ENDR move d6,d5 bra new_plotl very_fast_plotl: bclr #0,d5 bne.s .no move d1,(a2)+ .no: move d1,d2 swap d1 move d2,d1 jmp .calc_fplot(pc,d5) .calc_fplot: dcb.w NBLIG/2,$24c1 ; REPT NBLIG/2 ; move.l d1,(a2)+ ; ENDR move d6,d5 bra new_plotl fast_plotr: swap d1 swap d3 beq very_fast_plotr add d0,d0 add d0,d0 jmp .calc_fplot(pc,d0) .calc_fplot: dcb.l NBLIG,$34c1d243 ; REPT NBLIG ; move d1,(a2)+ ; add d3,d1 ; ENDR move d6,d0 bra new_plotr very_fast_plotr: bclr #0,d0 bne.s .no move d1,(a2)+ .no: move d1,d2 swap d1 move d2,d1 jmp .calc_fplot(pc,d0) .calc_fplot: dcb.w NBLIG/2,$24c1 ; REPT NBLIG/2 ; move d1,(a2)+ ; ENDR move d6,d0 bra new_plotr ;#] Fast calcul: ; #] Affpoly: ; #[ Very fast horizontal line: ; ------------------------------------------------------------------------ ; ; Appel routine de tracage horizontal ; ; (Gere le clipping en Y) ; ; ------------------------------------------------------------------------ ; ; #[ Calling rout: ; Routine d'appele ; A0 : Routine a appele ; A6 : Adresse ecran ; D0 : Position Y ; D1 : Nbr de ligne a afficher curline dc.l hline_one_plane call_line: tst d1 blt.s .noaff lea points_gauche,a4 lea points_droite,a5 cmp miy(pc),d0 bge.s .ok sub miy(pc),d0 add d0,d1 blt.s .noaff add d0,d0 suba d0,a4 suba d0,a5 move miy(pc),d0 .ok: move d0,d2 add d1,d2 cmpi #NBLIG,d2 blt.s .ok2 move #NBLIG,d1 sub d0,d1 blt .noaff .ok2: move d0,d3 lsl #5,d3 move d3,d2 add d3,d3 add d3,d3 add d2,d3 adda d3,a6 move d1,d7 ; * 160 jmp (a0) .noaff: rts ; ------------------------------------------------------------------------ ; ; Tracage de ligne horizontal 1 plan. ; ; ------------------------------------------------------------------------ ; ; A4: Table des points gauches ; A5: " " " droits ; A6: Adresse ecran ; D7: Nombre le ligne en hauteur ; ************ ; ; Non trames: ; ; ************ ; hline_one_plane: moveq #$ffffffff,d5 lea ldecal,a1 lea rdecal,a2 qline = *+2 jmp line68000 line68000: lsl #7,d7 ; La routine fait 128 octets neg d7 lea phline2,a3 jmp (a3,d7) line68030: subq #1,d7 ; #[ One plane: (128 octets) hline2: moveq #-4,d0 and (a4)+,d0 moveq #-4,d1 and (a5)+,d1 move.l (a1,d0),d0 move.l (a2,d1),d1 sub d1,d0 bge.s .little_line move.l a6,a0 adda d1,a0 swap d1 or d1,(a0) adda d0,a0 asr #1,d0 jmp .loopline+4(pc,d0) .little_line: bne.s .nohline and.l d1,d0 swap d0 or d0,(a6,d1) bra.s .nohline N set (LECRAN-32)/2 REPT (LECRAN-32)/16 move d5,N(a0) N set N-8 ENDR .loopline: swap d0 or d0,(a0) .nohline: lea 160(a6),a6 hline1: ; #] One plane: dbra d7,hline2 rts ; ******** ; ; trames: ; ; ******** ; hline_one_plane_tramed: move.l #$5555aaaa,d5 btst #0,d0 beq.s .ok swap d5 ;MCODER .ok: jmp_one_plane_tramed: lea ldecal,a1 lea rdecal,a2 qlinet = *+2 jmp line68000t line68000t: lsl #3,d7 move d7,d0 lsl #4,d7 add d0,d7 ; La routine fait 136 octets neg d7 lea phlinet2,a3 jmp (a3,d7) line68030t: subq #1,d7 ; #[ One plane tramed: (136 octets) hline_tramed2: moveq #-4,d0 and (a4)+,d0 moveq #-4,d1 and (a5)+,d1 move.l (a1,d0),d0 move.l (a2,d1),d1 sub d1,d0 bge.s .little_line move.l a6,a0 adda d1,a0 swap d1 and d5,d1 or d1,(a0) adda d0,a0 asr #1,d0 jmp .loopline+4(pc,d0) .little_line: bne.s .nohline and.l d1,d0 swap d0 and d5,d0 or d0,(a6,d1) bra.s .nohline N set (LECRAN-32)/2 REPT (LECRAN-32)/16 move d5,N(a0) N set N-8 ENDR .loopline: swap d0 and d5,d0 or d0,(a0) .nohline: swap d5 ;MCODER lea 160(a6),a6 hline_tramed1: ; #] One plane tramed: dbra d7,hline_tramed2 rts ; ****************** ; ; trames inverses: ; ; ****************** ; hline_inversed_one_plane_tramed: move.l #$5555aaaa,d5 btst #0,d0 bne.s .ok swap d5 ;MCODER .ok: bra jmp_one_plane_tramed ; #] Calling rout: ; #[ Genere hline: bord: dc %111111111111111,%11111111111111,%1111111111111,%111111111111,%11111111111,%1111111111,%111111111,%11111111,%1111111,%111111,%11111,%1111,%111,%11,%1,0 init_hline: lea phline,a1 ; Pregenere les lignes 1 plan move #NBLIG-1,d0 .lphline: lea hline2,a0 move #(hline1-hline2)/2-1,d1 .lphline2: move (a0)+,(a1)+ dbra d1,.lphline2 dbra d0,.lphline move #$4e75,(a1)+ Flab lea phlinet,a1 ; Pregenere les lignes 1 plan trames move #NBLIG-1,d0 .lphline: lea hline_tramed2,a0 move #(hline_tramed1-hline_tramed2)/2-1,d1 .lphline2: move (a0)+,(a1)+ dbra d1,.lphline2 dbra d0,.lphline move #$4e75,(a1)+ lea ldecal,a0 ; Precalcul le bord des lignes H lea rdecal,a2 move #0,d2 move #0,d3 move #LECRAN/16-1,d0 decal1: lea bord,a1 move #15,d1 decal2: move (a1)+,d7 move d7,(a0)+ move d2,(a0)+ not d7 bne.s .pazero move #-1,(a2)+ subq #8,d3 move d3,(a2)+ addq #8,d3 bra.s .zero .pazero move d7,(a2)+ move d3,(a2)+ .zero dbra d1,decal2 addq #8,d2 addq #8,d3 dbra d0,decal1 lea ldecal-DEPASSE*4,a0 ; Precalcul pour le cliping en X lea rdecal-DEPASSE*4,a1 move #DEPASSE+MINX-1,d0 .ld: move.l #$7fff0000+MINX/2,(a0)+ move.l #$7fff0000+MINX/2-8,(a1)+ dbra d0,.ld lea rdecal+MAXX*4,a0 lea ldecal+MAXX*4,a1 move #DEPASSE+(LECRAN-MAXX)-1,d0 .rd: move.l #$ffff0000+MAXX/2-8,(a0)+ move.l #$ffff0000+MAXX/2,(a1)+ dbra d0,.rd rts section bss phline: ds.b (hline1-hline2)*NBLIG phline2: ds 1 ; Pour RTS even phlinet: ds.b (hline_tramed1-hline_tramed2)*NBLIG phlinet2: ds 1 ; Pour RTS even ds.l DEPASSE ldecal ds.l LECRAN ds.l DEPASSE ds.l DEPASSE rdecal ds.l LECRAN ds.l DEPASSE section text ; #] Genere hline: ; #] Very fast horizontal line: ; #[ Circle rout: ; ---------------------------------------------------------------------------- ; ; Routine de cercle. (C) Copyright 1990 Ziggy STARDUST. ; ; ---------------------------------------------------------------------------- ; ; #[ Calling rout: ; D1 = Rayon du cercle ; D2 = Position Y de centre du cercle ; D3 = Position X du centre du cercle circle: move #$0300,sr move.l a7,oldpile move d1,d7 move d1,d2 add d1,d2 lea points_droite,a0 move.l a0,a4 move.l a0,a5 adda d2,a5 adda d2,a5 adda d2,a0 move.l a0,a1 lea points_gauche,a2 move.l a2,a6 move.l a2,a7 adda d2,a7 adda d2,a7 adda d2,a2 move.l a2,a3 cmpi #1,d7 ble.s .nocircle add d3,d3 add d3,d3 move d1,d4 add d4,d4 add d4,d4 move d3,d5 sub d4,d5 add d3,d4 move d1,d2 asr #1,d2 neg d7 muls #23170/2,d7 ; asr.l #6,d7 ; asr.l #8,d7 ; add d7,d7 ; add d7,d7 asr.l #8,d7 asr.l #4,d7 and #-4,d7 ;MCODER move d7,d0 asl #3,d7 add d0,d7 ; * 36 octets clr d0 ext.l d7 move.l #circle_rout,jmpcircle add.l d7,jmpcircle move d3,d6 move d3,d7 jmpcircle: = *+2 jmp $0.l .nocircle: moveq #0,d0 move d0,-(a0) move d0,(a1)+ move d0,-(a2) move d0,(a3)+ move.l oldpile(pc),a7 trap #3 rts ; #] Calling rout: ; #[ Initiale routine: (36 octets...) ; D0 = Y ; D1 = X ; D2 = X2 circle1: add d0,d2 blt.s .ok .tst: subq #1,d1 subq #4,d4 addq #4,d5 move d6,(a4)+ move d6,-(a5) move d7,(a6)+ move d7,-(a7) sub d1,d2 bge.s .tst .ok: addq #1,d0 addq #4,d6 subq #4,d7 move d4,-(a0) move d4,(a1)+ move d5,-(a2) move d5,(a3)+ circle2: ; #] Initiale routine: ; #[ Genere cercle: genere_circle: lea debut_circle_rout,a1 move #NBLIG*2-1,d0 .g_circle: lea circle1(pc),a0 move #(circle2-circle1)/2-1,d1 .g_circle2: move (a0)+,(a1)+ dbra d1,.g_circle2 dbra d0,.g_circle move #$4ef9,(a1)+ move.l #retour,(a1)+ ; --> Jmp retour rts section bss debut_circle_rout: ds.b (circle2-circle1)*NBLIG*2 circle_rout: ds.w 3 section text ; #] Genere cercle: ; #] Circle rout: ; #[ Anime: curobj dc.l obj1 ; #[ Vbl synchro, clearing screen, calling Afforme: anime3d: movem.l d0-a6,-(a7) bsr anime tst.b clav+67 ; <F9>? bne.s .norot move oba,d0 add va,d0 andi #TSINUS-1,d0 move d0,oba move obb,d0 add vb,d0 andi #TSINUS-1,d0 move d0,obb move obg,d0 add vg,d0 andi #TSINUS-1,d0 move d0,obg .norot: bsr gere movem.l (a7)+,d0-a6 rts gere: move mainx,coordx move.l #obj1,curobj bsr affobj sub #50,coordx move.l #obj2,curobj bsr affobj addq #2,mainx cmp #200,mainx ble.s .ok move #-200,mainx .ok rts affobj: move coordx,ox move coordy,oy clr va clr vb clr vg move.l curobj,a0 move oba,10(a0) move obb,12(a0) move obg,14(a0) lea 16(a0),a6 bra afforme neffecr: dc.w 0 anime: Tstcol $000 IFNE DEBUG tst.b qaffn beq.s .no move oz,d0 move.l ec1,a0 lea 2*8*160(a0),a0 bsr affnr .no: ENDC .waitvbl: move.l curec,a0 sub.l affec,a0 cmpa.l #NECR*4-1*4,a0 bge.s .waitvbl move.l curec,a0 addq.l #4,a0 cmpa.l #ec+NECR*4*2,a0 blt.s okswap suba #NECR*4,a0 sub.l #NECR*4,affec okswap: move.l (a0),ec1 move.l NECR*2*4*1(a0),curlim move.l NECR*2*4*2(a0),affpal move.l a0,curec move.l ec1,a0 move.l curlim,a1 movem (a1),d0-d3 move.b 8(a1),used_plane move.l #.ret,retcls bra cls .ret: clr.b used_plane Flab tst neffecr beq.s .no subq #1,neffecr move.l ec1,a0 bsr cls1plan .no: Tstcol $700 rts ; #] Vbl synchro, clearing screen, calling Afforme: ; #] Anime: ; #[ Fin: fin: jsr uninit clr -(a7) trap #1 ; #] Fin: ; #[ Cls one plane: cls1plan: moveq #0,d0 move #NBLIG-1,d1 .loop: N set 0 REPT 20 move d0,N(a0) N set N+8 ENDR lea 160(a0),a0 dbra d1,.loop rts ; #] Cls one plane: ; #[ Cls a variable area and number of plane: ; #[ Calling rout: ; Routine d'effacement ; D0: Min X ; D1: Max X ; D2: Min Y ; D3: Max Y ; A0: Adresse ecran ; retcls: Adresse retour du CLS section bss oa7 ds.l 1 used_plane ds.b 1 even section text cls: tst.b clav+68 ; <F10>? beq.s .no move.b #$0f,used_plane .no: move #$0300,sr move.l a7,oa7 move.l a0,a7 andi #$fff0,d0 addi #16,d1 andi #$fff0,d1 ; Multiple de 16 pixel move d1,d5 lsr #1,d5 sub d0,d1 ; Largeur lsr #2,d1 sub d2,d3 subq #1,d3 ble cls0 asl #5,d2 ; * 32 move d2,d4 add d2,d2 add d2,d2 ; * 128 add d4,d2 ; --> * 160 add d2,d5 adda d5,a7 move d3,d0 moveq #0,d7 move.b used_plane,d7 add d7,d7 add d7,d7 jmp .jmp_plane(pc,d7) .jmp_plane: bra.w fcls bra.w plan0001 bra.w plan0010 bra.w plan0011 bra.w plan0100 bra.w plan0101 bra.w plan0110 bra.w plan0111 bra.w plan1000 bra.w plan1001 bra.w plan1010 bra.w plan1011 bra.w plan1100 bra.w plan1101 bra.w plan1110 bra.w plan1111 ; #] Calling rout: ; #[ Four plane: plan1111: plan1010: plan0101: plan1110: plan1101: plan1011: plan0111: addq #2,d1 ble cls0 move d1,.ajmp+2 moveq #0,d1 move.l d1,d2 move.l d1,d3 move.l d1,d4 move.l d1,d5 move.l d1,d6 move.l d1,d7 move.l d1,a0 move.l d1,a1 move.l d1,a2 move.l d1,a3 move.l d1,a4 move.l d1,a5 move.l d1,a6 .ajmp: bra.w tcls tcls: bra.w cls0 bra.w cls1 bra.w cls2 bra.w cls3 bra.w cls4 bra.w cls5 bra.w cls6 bra.w cls7 bra.w cls8 bra.w cls9 bra.w cls10 bra.w cls11 bra.w cls12 bra.w cls13 bra.w cls14 bra.w cls15 bra.w cls16 bra.w cls17 bra.w cls18 bra.w cls19 bra.w cls20 cls1: move.l d1,-(a7) move.l d1,-(a7) lea 160+8(a7),a7 dbra d0,cls1 bra fcls cls2: movem.l d1-d4,-(a7) lea 160+16(a7),a7 dbra d0,cls2 bra fcls cls3: movem.l d1-d6,-(a7) lea 160+24(a7),a7 dbra d0,cls3 bra fcls cls4: movem.l d1-a0,-(a7) lea 160+32(a7),a7 dbra d0,cls4 bra fcls cls5: movem.l d1-a2,-(a7) lea 160+40(a7),a7 dbra d0,cls5 bra fcls cls6: movem.l d1-a4,-(a7) lea 160+48(a7),a7 dbra d0,cls6 bra fcls cls7: movem.l d1-a6,-(a7) lea 160+56(a7),a7 dbra d0,cls7 bra fcls cls8: movem.l d1-a6,-(a7) move.l d1,-(a7) move.l d1,-(a7) lea 160+64(a7),a7 dbra d0,cls8 bra fcls cls9: movem.l d1-a6,-(a7) movem.l d1-d4,-(a7) lea 160+72(a7),a7 dbra d0,cls9 bra.s fcls cls10: movem.l d1-a6,-(a7) movem.l d1-d6,-(a7) lea 160+80(a7),a7 dbra d0,cls10 bra.s fcls cls11: movem.l d1-a6,-(a7) movem.l d1-a0,-(a7) lea 160+88(a7),a7 dbra d0,cls11 bra.s fcls cls12: movem.l d1-a6,-(a7) movem.l d1-a2,-(a7) lea 160+96(a7),a7 dbra d0,cls12 bra.s fcls cls13: movem.l d1-a6,-(a7) movem.l d1-a4,-(a7) lea 160+104(a7),a7 dbra d0,cls13 bra.s fcls cls14: movem.l d1-a6,-(a7) movem.l d1-a6,-(a7) lea 160+112(a7),a7 dbra d0,cls14 bra.s fcls cls15: movem.l d1-a6,-(a7) movem.l d1-a6,-(a7) move.l d1,-(a7) move.l d1,-(a7) lea 160+120(a7),a7 dbra d0,cls15 ; bra.s fcls two_plane_cls0: one_plane_cls0: cls0: fcls: move.l oa7,a7 trap #3 clr.b used_plane dc $4ef9 ; --> Jmp retcls dc.l 0 cls16: movem.l d1-a6,-(a7) movem.l d1-a6,-(a7) movem.l d1-d4,-(a7) lea 160+128(a7),a7 dbra d0,cls16 bra.s fcls cls17: movem.l d1-a6,-(a7) movem.l d1-a6,-(a7) movem.l d1-d6,-(a7) lea 160+136(a7),a7 dbra d0,cls17 bra.s fcls cls18: movem.l d1-a6,-(a7) movem.l d1-a6,-(a7) movem.l d1-a0,-(a7) lea 160+144(a7),a7 dbra d0,cls18 bra.s fcls cls19: movem.l d1-a6,-(a7) movem.l d1-a6,-(a7) movem.l d1-a2,-(a7) lea 160+152(a7),a7 dbra d0,cls19 bra.s fcls cls20: movem.l d1-a6,-(a7) movem.l d1-a6,-(a7) movem.l d1-a4,-(a7) lea 160+160(a7),a7 dbra d0,cls20 bra fcls ; #] Four plane: ; #[ Two plane: plan1001: addq #2,a7 plan1100: addq #2,a7 plan0110: addq #2,a7 plan0011: addq #2,d1 ble fcls move d1,.ajmp+2 moveq #0,d1 .ajmp: bra.w two_plane_cls two_plane_cls: bra.w two_plane_cls0 bra.w two_plane_cls1 bra.w two_plane_cls2 bra.w two_plane_cls3 bra.w two_plane_cls4 bra.w two_plane_cls5 bra.w two_plane_cls6 bra.w two_plane_cls7 bra.w two_plane_cls8 bra.w two_plane_cls9 bra.w two_plane_cls10 bra.w two_plane_cls11 bra.w two_plane_cls12 bra.w two_plane_cls13 bra.w two_plane_cls14 bra.w two_plane_cls15 bra.w two_plane_cls16 bra.w two_plane_cls17 bra.w two_plane_cls18 bra.w two_plane_cls19 bra.w two_plane_cls20 Tpcls MACRO two_plane_loop\@: IFGE \1-1 move.l d1,-8(a7) ENDC IFGE \1-2 move.l d1,-16(a7) ENDC IFGE \1-3 move.l d1,-24(a7) ENDC IFGE \1-4 move.l d1,-32(a7) ENDC IFGE \1-5 move.l d1,-40(a7) ENDC IFGE \1-6 move.l d1,-48(a7) ENDC IFGE \1-7 move.l d1,-56(a7) ENDC IFGE \1-8 move.l d1,-64(a7) ENDC IFGE \1-9 move.l d1,-72(a7) ENDC IFGE \1-10 move.l d1,-80(a7) ENDC IFGE \1-11 move.l d1,-88(a7) ENDC IFGE \1-12 move.l d1,-96(a7) ENDC IFGE \1-13 move.l d1,-104(a7) ENDC IFGE \1-14 move.l d1,-112(a7) ENDC IFGE \1-15 move.l d1,-120(a7) ENDC IFGE \1-16 move.l d1,-128(a7) ENDC IFGE \1-17 move.l d1,-136(a7) ENDC IFGE \1-18 move.l d1,-144(a7) ENDC IFGE \1-19 move.l d1,-152(a7) ENDC IFGE \1-20 move.l d1,-160(a7) ENDC lea 160(a7),a7 dbra d0,two_plane_loop\@ bra fcls ENDM two_plane_cls1 Tpcls 1 two_plane_cls2 Tpcls 2 two_plane_cls3 Tpcls 3 two_plane_cls4 Tpcls 4 two_plane_cls5 Tpcls 5 two_plane_cls6 Tpcls 6 two_plane_cls7 Tpcls 7 two_plane_cls8 Tpcls 8 two_plane_cls9 Tpcls 9 two_plane_cls10 Tpcls 10 two_plane_cls11 Tpcls 11 two_plane_cls12 Tpcls 12 two_plane_cls13 Tpcls 13 two_plane_cls14 Tpcls 14 two_plane_cls15 Tpcls 15 two_plane_cls16 Tpcls 16 two_plane_cls17 Tpcls 17 two_plane_cls18 Tpcls 18 two_plane_cls19 Tpcls 19 two_plane_cls20 Tpcls 20 ; #] Two plane: ; #[ One plane: plan1000: addq #2,a7 plan0100: addq #2,a7 plan0010: addq #2,a7 plan0001: addq #2,d1 ble fcls move d1,.ajmp+2 moveq #0,d1 .ajmp: bra.w one_plane_cls one_plane_cls: bra.w one_plane_cls0 bra.w one_plane_cls1 bra.w one_plane_cls2 bra.w one_plane_cls3 bra.w one_plane_cls4 bra.w one_plane_cls5 bra.w one_plane_cls6 bra.w one_plane_cls7 bra.w one_plane_cls8 bra.w one_plane_cls9 bra.w one_plane_cls10 bra.w one_plane_cls11 bra.w one_plane_cls12 bra.w one_plane_cls13 bra.w one_plane_cls14 bra.w one_plane_cls15 bra.w one_plane_cls16 bra.w one_plane_cls17 bra.w one_plane_cls18 bra.w one_plane_cls19 bra.w one_plane_cls20 Opcls MACRO one_plane_loop\@: IFGE \1-1 move d1,-8(a7) ENDC IFGE \1-2 move d1,-16(a7) ENDC IFGE \1-3 move d1,-24(a7) ENDC IFGE \1-4 move d1,-32(a7) ENDC IFGE \1-5 move d1,-40(a7) ENDC IFGE \1-6 move d1,-48(a7) ENDC IFGE \1-7 move d1,-56(a7) ENDC IFGE \1-8 move d1,-64(a7) ENDC IFGE \1-9 move d1,-72(a7) ENDC IFGE \1-10 move d1,-80(a7) ENDC IFGE \1-11 move d1,-88(a7) ENDC IFGE \1-12 move d1,-96(a7) ENDC IFGE \1-13 move d1,-104(a7) ENDC IFGE \1-14 move d1,-112(a7) ENDC IFGE \1-15 move d1,-120(a7) ENDC IFGE \1-16 move d1,-128(a7) ENDC IFGE \1-17 move d1,-136(a7) ENDC IFGE \1-18 move d1,-144(a7) ENDC IFGE \1-19 move d1,-152(a7) ENDC IFGE \1-20 move d1,-160(a7) ENDC lea 160(a7),a7 dbra d0,one_plane_loop\@ bra fcls ENDM one_plane_cls1 Opcls 1 one_plane_cls2 Opcls 2 one_plane_cls3 Opcls 3 one_plane_cls4 Opcls 4 one_plane_cls5 Opcls 5 one_plane_cls6 Opcls 6 one_plane_cls7 Opcls 7 one_plane_cls8 Opcls 8 one_plane_cls9 Opcls 9 one_plane_cls10 Opcls 10 one_plane_cls11 Opcls 11 one_plane_cls12 Opcls 12 one_plane_cls13 Opcls 13 one_plane_cls14 Opcls 14 one_plane_cls15 Opcls 15 one_plane_cls16 Opcls 16 one_plane_cls17 Opcls 17 one_plane_cls18 Opcls 18 one_plane_cls19 Opcls 19 one_plane_cls20 Opcls 20 ; #] One plane: ; #] Cls a variable area and number of plane: ; #[ Vbl: ; #[ Datas: qaffn dc.b 0 even curec dc.l ec+3*4 affec dc.l ec cvbl dc.w 0 cvbl1 dc.w 0 cvbl2 dc.w 0 cvbl3 dc.w 0 tcol dc.w 0 ec1 ds.l 1 curlim ds.l 1 ec: ds.l NECR*2 tlim: N set 0 REPT NECR dc.l lim+N N set N+10 ENDR N set 0 REPT NECR dc.l lim+N N set N+10 ENDR tpal: N set 0 REPT NECR dc.l pal+N N set N+32 ENDR N set 0 REPT NECR dc.l pal+N N set N+32 ENDR lim: REPT NECR*2 dc 10,30,20,30,0 ENDR pal: REPT NECR dc.w 0 dc.w $777 ds.w 14 ENDR section text ; #] Datas: ; #[ Real_VBL: att_vbl dc.w 0 vbl: move.l #vbl2,$134.w clr.b $fffffa19.w subq #1,att_vbl bgt.s novbl nvbl = *+2 move #1,att_vbl bset #5,$fffffa07.w bset #5,$fffffa13.w qtimer = *+2 move.b #220,$fffffa1f.w move.b #7,$fffffa19.w novbl: rte ; #] Real_VBL: ; #[ Timer_VBL: FREQUENCE = 50 vbl2: ; move #$005,$ffff8240 movem.l d0-a6,-(a7) addq #1,cvbl addq #1,cvbl1 qfreq = *+2 cmpi #FREQUENCE,cvbl1 blt.s okcvbl move cvbl2,cvbl3 clr cvbl1 clr cvbl2 okcvbl: IFNE DEBUG tst.b qaffn beq.s .no sub.l a1,a1 move cvbl3,a1 add a1,a1 add a1,a1 adda.l #nombre,a1 move.l ec1,a0 jsr (a1) .no: ENDC move.l curec,a1 sub.l affec,a1 cmpa.l #2*4,a1 blt.s noswap addq #1,cvbl2 move.l affec(pc),a0 addq #4,a0 move.l a0,affec move.b 1(a0),$ffff8201.w move.b 2(a0),$ffff8203.w move.l NECR*2*4*2(a0),a0 movem.l (a0),d0-d7 ; movem.l palette(pc),d0-d7 movem.l d0-d7,$ffff8240.w noswap: IFNE DEBUG tst.b qaffn beq.s .no adda.l #nombre,a1 move.l ec1,a0 lea 8*160(a0),a0 jsr (a1) .no: ENDC bsr test_touche movem.l (a7)+,d0-a6 clr.b $fffffa19.w ; move #$500,$ffff8240.w rte ; #] Timer_VBL: ; #] Vbl: ; #[ Affn: affnr: tst d0 bge.s .ok neg d0 .ok: ext.l d0 divs #100,d0 cmpi #100,d0 bge.s .noaffn add d0,d0 add d0,d0 jsr nombre(pc,d0) swap d0 add d0,d0 add d0,d0 addq #8,a0 jmp nombre(pc,d0) .noaffn: rts nombre: incbin zeroa99.bin even rts affn: lea num,a6 affn1: divs #10,d7 move d7,-(a7) swap d7 addi #'0',d7 move.b d7,-(a6) move (a7)+,d7 ext.l d7 bne.s affn1 Print (a6) rts ; #] Affn: ; #[ 3D Objects: debut_objets = *+$1c incbin objets3.prg ; #] 3D Objects: ; #[ Objects defs: ; #[ Macros: OBJET MACRO dc.l \1 dc.w \2,\3,\4,\5,\6,\7 ; X Y Z A B G ENDM OBJETR MACRO dc.l 0 dc.w \1,\2,\3,\4,\5,\6 ; X Y Z A B G ENDM ; #] Macros: debut_objets_def: obj1 OBJETR 0,0,0,0,0,0 ;a obj2 OBJETR 0,0,0,0,0,0 ;b obj3 OBJETR 0,0,0,0,0,0 ;c obj4 OBJETR 0,0,0,0,0,0 ;d obj5 OBJETR 0,0,0,0,0,0 ;e obj6 OBJETR 0,0,0,0,0,0 ;f obj7 OBJETR 0,0,0,0,0,0 ;g obj8 OBJETR 0,0,0,0,0,0 ;h obj9 OBJETR 0,0,0,0,0,0 ;i obj10 OBJETR 0,0,0,0,0,0 ;j obj11 OBJETR 0,0,0,0,0,0 ;k obj12 OBJETR 0,0,0,0,0,0 ;l obj13 OBJETR 0,0,0,0,0,0 ;m obj14 OBJETR 0,0,0,0,0,0 ;n obj15 OBJETR 0,0,0,0,0,0 ;o obj16 OBJETR 0,0,0,0,0,0 ;p obj17 OBJETR 0,0,0,0,0,0 ;q obj18 OBJETR 0,0,0,0,0,0 ;r obj19 OBJETR 0,0,0,0,0,0 ;s obj20 OBJETR 0,0,0,0,0,0 ;t obj21 OBJETR 0,0,0,0,0,0 ;u obj22 OBJETR 0,0,0,0,0,0 ;v obj23 OBJETR 0,0,0,0,0,0 ;w obj24 OBJETR 0,0,0,0,0,0 ;x obj25 OBJETR 0,0,0,0,0,0 ;y obj26 OBJETR 0,0,0,0,0,0 ;z dc.l -1 ; #] Objects defs: ; #[ Variables: section bss ; #[ Variables_systemes: oldpal ds.w 16 oldbomb ds.l 8 oldrez ds.b 1 oldrez_tt ds.b 1 even oldec ds.l 1 ; #] Variables_systemes: plot3d ds.w 128*3 * Table des points apres calcul 3D plot2d ds.w 128*2 * 128 points max dans une forme 3D pxy ds.l 16 * Tableau du polygone points_gauche ds.w NBLIG ds.w DEPASSE*2 points_droite ds.w NBLIG ds.w DEPASSE*2 num ds.b 20 ds.b 256 ecran ds.b 32000*NECR even ; #] Variables:
0
0.948697
1
0.948697
game-dev
MEDIA
0.31069
game-dev
0.993568
1
0.993568
fulpstation/fulpstation
3,161
code/modules/antagonists/blob/blobstrains/debris_devourer.dm
#define DEBRIS_DENSITY (length(core.contents) / (length(overmind.blobs_legit) * 0.25)) // items per blob // Accumulates junk liberally /datum/blobstrain/debris_devourer name = "Debris Devourer" description = "will launch accumulated debris into targets. Does very low brute damage without debris-launching." analyzerdescdamage = "Does very low brute damage and may grab onto melee weapons." analyzerdesceffect = "Devours loose items left on the station, and releases them when attacking or attacked." color = "#8B1000" complementary_color = "#00558B" blobbernaut_message = "blasts" message = "The blob blasts you" /datum/blobstrain/debris_devourer/attack_living(mob/living/L, list/nearby_blobs) send_message(L) for (var/obj/structure/blob/blob in nearby_blobs) debris_attack(L, blob) /datum/blobstrain/debris_devourer/on_sporedeath(mob/living/spore) var/obj/structure/blob/special/core/core = overmind.blob_core for(var/i in 1 to 3) var/obj/item/I = pick(core.contents) if (I && !QDELETED(I)) I.forceMove(get_turf(spore)) I.throw_at(get_edge_target_turf(spore,pick(GLOB.alldirs)), 6, 5, spore, TRUE, FALSE, null, 3) /datum/blobstrain/debris_devourer/expand_reaction(obj/structure/blob/B, obj/structure/blob/newB, turf/T, mob/eye/blob/O, coefficient = 1) //when the blob expands, do this for (var/obj/item/I in T) I.forceMove(overmind.blob_core) /datum/blobstrain/debris_devourer/proc/debris_attack(atom/attacking, atom/source) var/obj/structure/blob/special/core/core = overmind.blob_core if (prob(40 * DEBRIS_DENSITY)) // Pretend the items are spread through the blob and its mobs and not in the core. var/obj/item/I = length(core.contents) ? pick(core.contents) : null if (!QDELETED(I)) I.forceMove(get_turf(source)) I.throw_at(attacking, 6, 5, overmind, TRUE, FALSE, null, 3) /datum/blobstrain/debris_devourer/blobbernaut_attack(atom/attacking, mob/living/basic/blobbernaut) debris_attack(attacking, blobbernaut) /datum/blobstrain/debris_devourer/damage_reaction(obj/structure/blob/B, damage, damage_type, damage_flag, coefficient = 1) //when the blob takes damage, do this var/obj/structure/blob/special/core/core = overmind.blob_core return round(max((coefficient*damage)-min(coefficient*DEBRIS_DENSITY, 10), 0)) // reduce damage taken by items per blob, up to 10 /datum/blobstrain/debris_devourer/examine(mob/user) . = ..() var/obj/structure/blob/special/core/core = overmind.blob_core if (isobserver(user)) . += span_notice("Absorbed debris is currently reducing incoming damage by [round(max(min(DEBRIS_DENSITY, 10),0))]") else switch (round(max(min(DEBRIS_DENSITY, 10),0))) if (0) . += span_notice("There is not currently enough absorbed debris to reduce damage.") if (1 to 3) . += span_notice("Absorbed debris is currently reducing incoming damage by a very low amount.") // these roughly correspond with force description strings if (4 to 7) . += span_notice("Absorbed debris is currently reducing incoming damage by a low amount.") if (8 to 10) . += span_notice("Absorbed debris is currently reducing incoming damage by a medium amount.") #undef DEBRIS_DENSITY
0
0.857356
1
0.857356
game-dev
MEDIA
0.966638
game-dev
0.963988
1
0.963988
ViveSoftware/ViveInputUtility-Unity
3,229
Assets/HTC.UnityPlugin/ViveInputUtility/Scripts/VivePose/ViveRigidPoseTracker.cs
//========= Copyright 2016-2024, HTC Corporation. All rights reserved. =========== using UnityEngine; using HTC.UnityPlugin.Utility; namespace HTC.UnityPlugin.Vive { [AddComponentMenu("VIU/Device Tracker/Vive Rigid Pose Tracker (Rigidbody)", 8)] [RequireComponent(typeof(Rigidbody))] public class ViveRigidPoseTracker : VivePoseTracker { public const float MIN_FOLLOWING_DURATION = 0.02f; public const float DEFAULT_FOLLOWING_DURATION = 0.04f; public const float MAX_FOLLOWING_DURATION = 0.5f; private Rigidbody rigid; private RigidPose targetPose; private bool m_snap; [SerializeField] private bool m_snapOnEnable = true; [Range(MIN_FOLLOWING_DURATION, MAX_FOLLOWING_DURATION)] public float followingDuration = DEFAULT_FOLLOWING_DURATION; public bool snapOnEnable { get { return m_snapOnEnable; } set { m_snapOnEnable = value; } } protected override void Start() { base.Start(); rigid = GetComponent<Rigidbody>(); rigid.useGravity = false; } protected override void OnEnable() { base.OnEnable(); if (m_snapOnEnable) { m_snap = true; } } protected virtual void FixedUpdate() { if (isPoseValid) { RigidPose.SetRigidbodyVelocity(rigid, rigid.position, targetPose.pos, followingDuration); RigidPose.SetRigidbodyAngularVelocity(rigid, rigid.rotation, targetPose.rot, followingDuration); } else { #if UNITY_6000_0_OR_NEWER rigid.linearVelocity = Vector3.zero; #else rigid.velocity = Vector3.zero; #endif rigid.angularVelocity = Vector3.zero; } } protected override void OnDisable() { #if UNITY_6000_0_OR_NEWER rigid.linearVelocity = Vector3.zero; #else rigid.velocity = Vector3.zero; #endif rigid.angularVelocity = Vector3.zero; base.OnDisable(); } public override void OnNewPoses() { var deviceIndex = viveRole.GetDeviceIndex(); // set targetPose to device pose targetPose = VivePose.GetPose(deviceIndex) * new RigidPose(posOffset, Quaternion.Euler(rotOffset)); if (origin != null && origin != transform.parent) { targetPose = new RigidPose(origin.transform) * targetPose; ModifyPose(ref targetPose, false); } else { ModifyPose(ref targetPose, true); } // transform to world space var o = origin != null ? origin : transform.parent; if (o != null) { targetPose = new RigidPose(o) * targetPose; targetPose.pos.Scale(o.localScale); } if (m_snap) { m_snap = false; transform.position = targetPose.pos; transform.rotation = targetPose.rot; } SetIsValid(VivePose.IsValid(deviceIndex)); } } }
0
0.812735
1
0.812735
game-dev
MEDIA
0.923042
game-dev
0.954379
1
0.954379
SamB440/ForcePack
4,722
api/src/main/java/com/convallyria/forcepack/api/ForcePackPlatform.java
package com.convallyria.forcepack.api; import com.convallyria.forcepack.api.resourcepack.PackFormatResolver; import com.convallyria.forcepack.api.resourcepack.ResourcePack; import com.convallyria.forcepack.api.resourcepack.ResourcePackVersion; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; public interface ForcePackPlatform extends ForcePackAPI { /** * Gets whether the specified URL is a default hosted one. * @param url the url to check * @return true if site is a default host */ default boolean isDefaultHost(String url) { List<String> warnForHost = List.of("convallyria.com"); for (String host : warnForHost) { if (url.contains(host)) { return true; } } return false; } /** * Gets, if there is one, the blacklisted site within a URL * @param url the url to check * @return an {@link Optional<String>} possibly containing the URL of the blacklisted site found */ default Optional<String> getBlacklistedSite(String url) { List<String> blacklisted = List.of("mediafire.com"); for (String blacklistedSite : blacklisted) { if (url.contains(blacklistedSite)) { return Optional.of(url); } } return Optional.empty(); } /** * Gets whether the specified URL has a valid ending * @param url the url to check * @return true if URL ends with a valid extension */ default boolean isValidEnding(String url) { List<String> validUrlEndings = Arrays.asList(".zip", "dl=1"); boolean hasEnding = false; for (String validUrlEnding : validUrlEndings) { if (url.endsWith(validUrlEnding)) { hasEnding = true; break; } } return hasEnding; } default ResourcePackVersion getVersionFromId(String versionId) { if (versionId.equals("all")) { return null; } try { // One version? final double fixedVersion = Double.parseDouble(versionId); return ResourcePackVersion.of(fixedVersion, fixedVersion); } catch (NumberFormatException ignored) { try { // Version range? final String[] ranged = versionId.split("-"); final double min = Double.parseDouble(ranged[0]); final double max = Double.parseDouble(ranged[1]); return ResourcePackVersion.of(min, max); } catch (NumberFormatException | IndexOutOfBoundsException ignored2) {} } throw new IllegalArgumentException("Invalid version id: " + versionId); } default Set<ResourcePack> getPacksForVersion(int protocolVersion) { final double packFormat = PackFormatResolver.getPackFormat(protocolVersion); log("Searching for a resource pack with pack version " + packFormat); Set<ResourcePack> validPacks = new HashSet<>(); boolean hasVersionOverride = false; for (ResourcePack resourcePack : getResourcePacks()) { final Optional<ResourcePackVersion> version = resourcePack.getVersion(); log("Trying resource pack " + resourcePack.getURL() + " (" + (version.isEmpty() ? version.toString() : version.get().toString()) + ")"); final boolean inVersion = version.isEmpty() || version.get().inVersion(packFormat); if (!inVersion) continue; if (version.isPresent()) { hasVersionOverride = true; } validPacks.add(resourcePack); log("Added resource pack " + resourcePack.getURL()); if (protocolVersion < 765) { // If < 1.20.3, only one pack can be applied. break; } } if (!validPacks.isEmpty()) { log("Found valid resource packs (" + validPacks.size() + ")"); // If we found version-specific resource packs, use those instead of the fallback if (hasVersionOverride) { validPacks = validPacks.stream().filter(pack -> pack.getVersion().isPresent()).collect(Collectors.toSet()); } log("Found valid resource packs (filtered to: " + validPacks.size() + ")"); for (ResourcePack validPack : validPacks) { log("Chosen resource pack " + validPack.getURL()); } return validPacks; } log("No valid resource packs found"); return null; } void log(String info, Object... format); }
0
0.948725
1
0.948725
game-dev
MEDIA
0.847615
game-dev
0.936788
1
0.936788
ChuckHearthstone/SilverFish
3,751
DefaultRoutine/Chuck.SilverFish/ai/Handmanager.cs
using SilverFish.Helpers; namespace Chuck.SilverFish { using System.Collections.Generic; public class Handmanager { public class Handcard { public int position = 0; public int entity = -1; public int manacost = 1000; public int addattack = 0; public int addHp = 0; public CardDB.Card card; public Minion target; public int elemPoweredUp = 0; public int extraParam2 = 0; public bool extraParam3 = false; public Handcard() { card = CardDB.Instance.unknownCard; } public Handcard(Handcard hc) { this.position = hc.position; this.entity = hc.entity; this.manacost = hc.manacost; this.card = hc.card; this.addattack = hc.addattack; this.addHp = hc.addHp; this.elemPoweredUp = hc.elemPoweredUp; } public Handcard(CardDB.Card c) { this.position = 0; this.entity = -1; this.card = c; this.addattack = 0; this.addHp = 0; } public void setHCtoHC(Handcard hc) { this.manacost = hc.manacost; this.addattack = hc.addattack; this.addHp = hc.addHp; this.card = hc.card; this.elemPoweredUp = hc.elemPoweredUp; } public int getManaCost(Playfield p) { return this.card.getManaCost(p, this.manacost); } public bool canplayCard(Playfield p, bool own) { return this.card.canplayCard(p, this.manacost, own); } } public List<Handcard> handCards = new List<Handcard>(); public int anzcards = 0; public int enemyAnzCards = 0; private int ownPlayerController = 0; Helpfunctions help; CardDB cdb = CardDB.Instance; private static Handmanager instance; public static Handmanager Instance { get { return instance ?? (instance = new Handmanager()); } } private Handmanager() { this.help = Helpfunctions.Instance; } public void clearAllRecalc() { this.handCards.Clear(); this.anzcards = 0; this.enemyAnzCards = 0; this.ownPlayerController = 0; } public void setOwnPlayer(int player) { this.ownPlayerController = player; } public void setHandcards(List<Handcard> hc, int anzown, int anzenemy) { this.handCards.Clear(); foreach (Handcard h in hc) { this.handCards.Add(new Handcard(h)); } //this.handCards.AddRange(hc); this.handCards.Sort((a, b) => a.position.CompareTo(b.position)); this.anzcards = anzown; this.enemyAnzCards = anzenemy; } public void printcards() { LogHelper.WriteCombatLog("Own Handcards: "); foreach (Handmanager.Handcard hc in this.handCards) { LogHelper.WriteCombatLog("pos " + hc.position + " " + hc.card.name + " " + hc.manacost + " entity " + hc.entity + " " + hc.card.cardIDenum + " " + hc.addattack + " " + hc.addHp + " " + hc.elemPoweredUp); } LogHelper.WriteCombatLog("Enemy cards: " + this.enemyAnzCards); } } }
0
0.781575
1
0.781575
game-dev
MEDIA
0.97413
game-dev
0.862472
1
0.862472
mayuki/Cocona
1,287
src/Cocona.Core/Help/TransformHelpAttribute.cs
using Cocona.Application; using Cocona.Command; using Cocona.Filters; using Cocona.Help.DocumentModel; using Cocona.Internal; namespace Cocona.Help; [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = true, Inherited = false)] public abstract class TransformHelpAttribute : Attribute, ICoconaHelpTransformer { public abstract void TransformHelp(HelpMessage helpMessage, CommandDescriptor command); } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = true, Inherited = false)] public class TransformHelpFactoryAttribute : Attribute, IFilterFactory { public Type Transformer { get; } public TransformHelpFactoryAttribute(Type transformer) { Transformer = transformer ?? throw new ArgumentNullException(nameof(transformer)); if (!typeof(ICoconaHelpTransformer).IsAssignableFrom(transformer)) { throw new ArgumentException($"Transformer Type '{transformer.FullName}' doesn't implement ICoconaHelpTransformer"); } } public IFilterMetadata CreateInstance(IServiceProvider serviceProvider) { return (IFilterMetadata)(serviceProvider.GetRequiredService<ICoconaInstanceActivator>()).GetServiceOrCreateInstance(serviceProvider, Transformer)!; } }
0
0.692263
1
0.692263
game-dev
MEDIA
0.201226
game-dev
0.831681
1
0.831681
redot-rex/rex-engine
9,907
scene/3d/physics/joints/slider_joint_3d.cpp
/**************************************************************************/ /* slider_joint_3d.cpp */ /**************************************************************************/ /* This file is part of: */ /* REDOT ENGINE */ /* https://redotengine.org */ /**************************************************************************/ /* Copyright (c) 2024-present Redot Engine contributors */ /* (see REDOT_AUTHORS.md) */ /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /**************************************************************************/ #include "slider_joint_3d.h" void SliderJoint3D::_bind_methods() { ClassDB::bind_method(D_METHOD("set_param", "param", "value"), &SliderJoint3D::set_param); ClassDB::bind_method(D_METHOD("get_param", "param"), &SliderJoint3D::get_param); ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "linear_limit/upper_distance", PropertyHint::HINT_RANGE, "-1024,1024,0.01,suffix:m"), "set_param", "get_param", PARAM_LINEAR_LIMIT_UPPER); ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "linear_limit/lower_distance", PropertyHint::HINT_RANGE, "-1024,1024,0.01,suffix:m"), "set_param", "get_param", PARAM_LINEAR_LIMIT_LOWER); ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "linear_limit/softness", PropertyHint::HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_LINEAR_LIMIT_SOFTNESS); ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "linear_limit/restitution", PropertyHint::HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_LINEAR_LIMIT_RESTITUTION); ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "linear_limit/damping", PropertyHint::HINT_RANGE, "0,16.0,0.01"), "set_param", "get_param", PARAM_LINEAR_LIMIT_DAMPING); ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "linear_motion/softness", PropertyHint::HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_LINEAR_MOTION_SOFTNESS); ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "linear_motion/restitution", PropertyHint::HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_LINEAR_MOTION_RESTITUTION); ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "linear_motion/damping", PropertyHint::HINT_RANGE, "0,16.0,0.01"), "set_param", "get_param", PARAM_LINEAR_MOTION_DAMPING); ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "linear_ortho/softness", PropertyHint::HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_LINEAR_ORTHOGONAL_SOFTNESS); ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "linear_ortho/restitution", PropertyHint::HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_LINEAR_ORTHOGONAL_RESTITUTION); ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "linear_ortho/damping", PropertyHint::HINT_RANGE, "0,16.0,0.01"), "set_param", "get_param", PARAM_LINEAR_ORTHOGONAL_DAMPING); ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "angular_limit/upper_angle", PropertyHint::HINT_RANGE, "-180,180,0.1,radians_as_degrees"), "set_param", "get_param", PARAM_ANGULAR_LIMIT_UPPER); ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "angular_limit/lower_angle", PropertyHint::HINT_RANGE, "-180,180,0.1,radians_as_degrees"), "set_param", "get_param", PARAM_ANGULAR_LIMIT_LOWER); ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "angular_limit/softness", PropertyHint::HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_ANGULAR_LIMIT_SOFTNESS); ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "angular_limit/restitution", PropertyHint::HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_ANGULAR_LIMIT_RESTITUTION); ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "angular_limit/damping", PropertyHint::HINT_RANGE, "0,16.0,0.01"), "set_param", "get_param", PARAM_ANGULAR_LIMIT_DAMPING); ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "angular_motion/softness", PropertyHint::HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_ANGULAR_MOTION_SOFTNESS); ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "angular_motion/restitution", PropertyHint::HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_ANGULAR_MOTION_RESTITUTION); ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "angular_motion/damping", PropertyHint::HINT_RANGE, "0,16.0,0.01"), "set_param", "get_param", PARAM_ANGULAR_MOTION_DAMPING); ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "angular_ortho/softness", PropertyHint::HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_ANGULAR_ORTHOGONAL_SOFTNESS); ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "angular_ortho/restitution", PropertyHint::HINT_RANGE, "0.01,16.0,0.01"), "set_param", "get_param", PARAM_ANGULAR_ORTHOGONAL_RESTITUTION); ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, "angular_ortho/damping", PropertyHint::HINT_RANGE, "0,16.0,0.01"), "set_param", "get_param", PARAM_ANGULAR_ORTHOGONAL_DAMPING); BIND_ENUM_CONSTANT(PARAM_LINEAR_LIMIT_UPPER); BIND_ENUM_CONSTANT(PARAM_LINEAR_LIMIT_LOWER); BIND_ENUM_CONSTANT(PARAM_LINEAR_LIMIT_SOFTNESS); BIND_ENUM_CONSTANT(PARAM_LINEAR_LIMIT_RESTITUTION); BIND_ENUM_CONSTANT(PARAM_LINEAR_LIMIT_DAMPING); BIND_ENUM_CONSTANT(PARAM_LINEAR_MOTION_SOFTNESS); BIND_ENUM_CONSTANT(PARAM_LINEAR_MOTION_RESTITUTION); BIND_ENUM_CONSTANT(PARAM_LINEAR_MOTION_DAMPING); BIND_ENUM_CONSTANT(PARAM_LINEAR_ORTHOGONAL_SOFTNESS); BIND_ENUM_CONSTANT(PARAM_LINEAR_ORTHOGONAL_RESTITUTION); BIND_ENUM_CONSTANT(PARAM_LINEAR_ORTHOGONAL_DAMPING); BIND_ENUM_CONSTANT(PARAM_ANGULAR_LIMIT_UPPER); BIND_ENUM_CONSTANT(PARAM_ANGULAR_LIMIT_LOWER); BIND_ENUM_CONSTANT(PARAM_ANGULAR_LIMIT_SOFTNESS); BIND_ENUM_CONSTANT(PARAM_ANGULAR_LIMIT_RESTITUTION); BIND_ENUM_CONSTANT(PARAM_ANGULAR_LIMIT_DAMPING); BIND_ENUM_CONSTANT(PARAM_ANGULAR_MOTION_SOFTNESS); BIND_ENUM_CONSTANT(PARAM_ANGULAR_MOTION_RESTITUTION); BIND_ENUM_CONSTANT(PARAM_ANGULAR_MOTION_DAMPING); BIND_ENUM_CONSTANT(PARAM_ANGULAR_ORTHOGONAL_SOFTNESS); BIND_ENUM_CONSTANT(PARAM_ANGULAR_ORTHOGONAL_RESTITUTION); BIND_ENUM_CONSTANT(PARAM_ANGULAR_ORTHOGONAL_DAMPING); BIND_ENUM_CONSTANT(PARAM_MAX); } void SliderJoint3D::set_param(Param p_param, real_t p_value) { ERR_FAIL_INDEX(p_param, PARAM_MAX); params[p_param] = p_value; if (is_configured()) { PhysicsServer3D::get_singleton()->slider_joint_set_param(get_rid(), PhysicsServer3D::SliderJointParam(p_param), p_value); } update_gizmos(); } real_t SliderJoint3D::get_param(Param p_param) const { ERR_FAIL_INDEX_V(p_param, PARAM_MAX, 0); return params[p_param]; } void SliderJoint3D::_configure_joint(RID p_joint, PhysicsBody3D *body_a, PhysicsBody3D *body_b) { Transform3D gt = get_global_transform(); Transform3D ainv = body_a->get_global_transform().affine_inverse(); Transform3D local_a = ainv * gt; local_a.orthonormalize(); Transform3D local_b = gt; if (body_b) { Transform3D binv = body_b->get_global_transform().affine_inverse(); local_b = binv * gt; } local_b.orthonormalize(); PhysicsServer3D::get_singleton()->joint_make_slider(p_joint, body_a->get_rid(), local_a, body_b ? body_b->get_rid() : RID(), local_b); for (int i = 0; i < PARAM_MAX; i++) { PhysicsServer3D::get_singleton()->slider_joint_set_param(p_joint, PhysicsServer3D::SliderJointParam(i), params[i]); } } SliderJoint3D::SliderJoint3D() { params[PARAM_LINEAR_LIMIT_UPPER] = 1.0; params[PARAM_LINEAR_LIMIT_LOWER] = -1.0; params[PARAM_LINEAR_LIMIT_SOFTNESS] = 1.0; params[PARAM_LINEAR_LIMIT_RESTITUTION] = 0.7; params[PARAM_LINEAR_LIMIT_DAMPING] = 1.0; params[PARAM_LINEAR_MOTION_SOFTNESS] = 1.0; params[PARAM_LINEAR_MOTION_RESTITUTION] = 0.7; params[PARAM_LINEAR_MOTION_DAMPING] = 0; //1.0; params[PARAM_LINEAR_ORTHOGONAL_SOFTNESS] = 1.0; params[PARAM_LINEAR_ORTHOGONAL_RESTITUTION] = 0.7; params[PARAM_LINEAR_ORTHOGONAL_DAMPING] = 1.0; params[PARAM_ANGULAR_LIMIT_UPPER] = 0; params[PARAM_ANGULAR_LIMIT_LOWER] = 0; params[PARAM_ANGULAR_LIMIT_SOFTNESS] = 1.0; params[PARAM_ANGULAR_LIMIT_RESTITUTION] = 0.7; params[PARAM_ANGULAR_LIMIT_DAMPING] = 0; //1.0; params[PARAM_ANGULAR_MOTION_SOFTNESS] = 1.0; params[PARAM_ANGULAR_MOTION_RESTITUTION] = 0.7; params[PARAM_ANGULAR_MOTION_DAMPING] = 1.0; params[PARAM_ANGULAR_ORTHOGONAL_SOFTNESS] = 1.0; params[PARAM_ANGULAR_ORTHOGONAL_RESTITUTION] = 0.7; params[PARAM_ANGULAR_ORTHOGONAL_DAMPING] = 1.0; }
0
0.927442
1
0.927442
game-dev
MEDIA
0.479697
game-dev
0.614258
1
0.614258
JiuTian-VL/Optimus-3
5,149
MineStudio/minestudio/simulator/minerl/Malmo/Minecraft/src/main/java/com/microsoft/Malmo/Utils/PositionHelper.java
// -------------------------------------------------------------------------------------------------- // Copyright (c) 2016 Microsoft Corporation // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and // associated documentation files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, publish, distribute, // sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT // NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // -------------------------------------------------------------------------------------------------- package com.microsoft.Malmo.Utils; import java.util.ArrayList; import java.util.List; import net.minecraft.block.state.IBlockState; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; import com.microsoft.Malmo.Schemas.Pos; /** Helper functions for position-related doings. */ public class PositionHelper { /** Calculate the Euclidean distance between the player and the target position. * @param player the player whose distance from target we want to know * @param targetPos the target position, specified as a Schema pos object * @return a float containing the Euclidean distance 'twixt player and target */ public static float calcDistanceFromPlayerToPosition(EntityPlayerSP player, Pos targetPos) { double x = player.posX - targetPos.getX().doubleValue(); double y = player.posY - targetPos.getY().doubleValue(); double z = player.posZ - targetPos.getZ().doubleValue(); return (float)Math.sqrt(x*x + y*y + z*z); } public static List<BlockPos> getTouchingBlocks(EntityPlayerSP player) { // Determine which blocks we are touching. // This code is adapted from Entity, where it is used to fire the Block.onEntityCollidedWithBlock methods. BlockPos blockposmin = new BlockPos(player.getEntityBoundingBox().minX - 0.001D, player.getEntityBoundingBox().minY - 0.001D, player.getEntityBoundingBox().minZ - 0.001D); BlockPos blockposmax = new BlockPos(player.getEntityBoundingBox().maxX + 0.001D, player.getEntityBoundingBox().maxY + 0.001D, player.getEntityBoundingBox().maxZ + 0.001D); List<BlockPos> blocks = new ArrayList<BlockPos>(); if (player.world.isAreaLoaded(blockposmin, blockposmax)) { for (int i = blockposmin.getX(); i <= blockposmax.getX(); ++i) { for (int j = blockposmin.getY(); j <= blockposmax.getY(); ++j) { for (int k = blockposmin.getZ(); k <= blockposmax.getZ(); ++k) { blocks.add(new BlockPos(i, j, k)); } } } } return blocks; } /** * Finds the highest block on the x and z coordinate that is solid or liquid, and returns its y coord. */ public static BlockPos getTopSolidOrLiquidBlock(World world, BlockPos pos) { Chunk chunk = world.getChunkFromBlockCoords(pos); BlockPos blockpos; BlockPos blockpos1; for (blockpos = new BlockPos(pos.getX(), chunk.getTopFilledSegment() + 16, pos.getZ()); blockpos.getY() >= 0; blockpos = blockpos1) { blockpos1 = blockpos.down(); IBlockState state = chunk.getBlockState(blockpos1); if ((state.getMaterial().blocksMovement() || state.getMaterial().isLiquid()) && !state.getBlock().isLeaves(state, world, blockpos1) && !state.getBlock().isFoliage(world, blockpos1)) { break; } } return blockpos; } /** * Finds the highest block on the x and z coordinate that we can teleport an agent to, and returns its y coord. */ public static BlockPos getTopTeleportableBlock(World world, BlockPos pos) { Chunk chunk = world.getChunkFromBlockCoords(pos); BlockPos blockpos; BlockPos blockpos1; for (blockpos = new BlockPos(pos.getX(), chunk.getTopFilledSegment() + 16, pos.getZ()); blockpos.getY() >= 0; blockpos = blockpos1) { blockpos1 = blockpos.down(); IBlockState state = chunk.getBlockState(blockpos1); if (state.getMaterial().blocksMovement() || state.getMaterial().isLiquid()) { break; } } return blockpos; } }
0
0.938735
1
0.938735
game-dev
MEDIA
0.979498
game-dev
0.951227
1
0.951227
Dysoch/DyTech
7,054
MAIN-DyTech-World/scripts/xp.lua
module("XP", package.seeall) require "config" require "scripts.functions" require "scripts.gui" function Building_Level(event) if not global.XP then fs.Startup() end global.XP.Building.Total = global.XP.Building.Total + (1/fs.Amount_Players()) global.XP.Building.Set = global.XP.Building.Set + (1/fs.Amount_Players()) if global.XP.Building.Set == global.XP.Building.Needed or global.XP.Building.Set > global.XP.Building.Needed then global.XP.Building.Set = global.XP.Building.Set - global.XP.Building.Needed global.XP.Building.Level = global.XP.Building.Level + 1 global.XP.Level = global.XP.Level + 1 debug("XP: Building reached "..global.XP.Building.Needed.." items") global.XP.Building.Needed = global.XP.Building.Needed + math.random(global.XP.Building.Total) PlayerPrint({"xp-2", {"building"}}) end end function Explore_Level(event) if not global.XP then fs.Startup() end global.XP.Explore.Total = global.XP.Explore.Total + (1/fs.Amount_Players()) global.XP.Explore.Set = global.XP.Explore.Set + (1/fs.Amount_Players()) if global.XP.Explore.Set == global.XP.Explore.Needed or global.XP.Explore.Set > global.XP.Explore.Needed then global.XP.Explore.Set = global.XP.Explore.Set - global.XP.Explore.Needed global.XP.Explore.Level = global.XP.Explore.Level + 1 global.XP.Level = global.XP.Level + 1 debug("XP: Explore reached "..global.XP.Explore.Needed.." chunks") global.XP.Explore.Needed = global.XP.Explore.Needed + math.random(math.floor(global.XP.Explore.Total/5)) PlayerPrint({"xp-2", {"explore"}}) end end function Crafting_Speed_Bonus(event) if not global.XP then fs.Startup() end global.XP.Crafting.Total = global.XP.Crafting.Total + (event.item_stack.count/fs.Amount_Players()) global.XP.Crafting.Set = global.XP.Crafting.Set + (event.item_stack.count/fs.Amount_Players()) if global.XP.Crafting.Set == global.XP.Crafting.Needed or global.XP.Crafting.Set > global.XP.Crafting.Needed then global.XP.Crafting.Set = global.XP.Crafting.Set - global.XP.Crafting.Needed global.XP.Crafting.Level = global.XP.Crafting.Level + 1 global.XP.Level = global.XP.Level + 1 Bonus1 = (math.random()/2) global.XP.Crafting.Bonus = (global.XP.Crafting.Bonus + Bonus1) debug("XP: Crafting reached "..global.XP.Crafting.Needed.." items, increased crafting speed. (speed: "..global.XP.Crafting.Bonus..")") global.XP.Crafting.Needed = global.XP.Crafting.Needed + math.random(global.XP.Crafting.Total) game.forces.player.manual_crafting_speed_modifier = global.XP.Crafting.Bonus PlayerPrint({"xp", {"crafting"}, string.sub(Bonus1,1,4)}) end end function Mining_Speed_Bonus(event) if not global.XP then fs.Startup() end global.XP.Mining.Total = global.XP.Mining.Total + (event.item_stack.count/fs.Amount_Players()) global.XP.Mining.Set = global.XP.Mining.Set + (event.item_stack.count/fs.Amount_Players()) if global.XP.Mining.Set == global.XP.Mining.Needed or global.XP.Mining.Set > global.XP.Mining.Needed then global.XP.Mining.Set = global.XP.Mining.Set - global.XP.Mining.Needed global.XP.Mining.Level = global.XP.Mining.Level + 1 global.XP.Level = global.XP.Level + 1 Bonus1 = (math.random()/2) global.XP.Mining.Bonus = global.XP.Mining.Bonus + Bonus1 debug("XP: Mining reached "..global.XP.Mining.Needed.." items, increased Mining speed. (speed: "..global.XP.Mining.Bonus..")") global.XP.Mining.Needed = global.XP.Mining.Needed + math.random(global.XP.Mining.Total) game.forces.player.manual_mining_speed_modifier = global.XP.Mining.Bonus PlayerPrint({"xp", {"mining"}, string.sub(Bonus1,1,4)}) end end function Fighting_Bonus(event) if not global.XP then fs.Startup() end if event.entity.type == "unit" then global.XP.Fighting.Killed_Total = global.XP.Fighting.Killed_Total + (1/fs.Amount_Players()) global.XP.Fighting.Killed_Set = global.XP.Fighting.Killed_Set + (1/fs.Amount_Players()) GUI_checker() elseif event.entity.type == "unit-spawner" then global.XP.Fighting.Killed_Total = global.XP.Fighting.Killed_Total + (10/fs.Amount_Players()) global.XP.Fighting.Killed_Set = global.XP.Fighting.Killed_Set + (10/fs.Amount_Players()) GUI_checker() end if global.XP.Fighting.Killed_Set == global.XP.Fighting.Needed or global.XP.Fighting.Killed_Set > global.XP.Fighting.Needed then global.XP.Fighting.Killed_Set = global.XP.Fighting.Killed_Set - global.XP.Fighting.Needed global.XP.Fighting.Level = global.XP.Fighting.Level + 1 global.XP.Level = global.XP.Level + 1 Extinction() debug("XP: Fighting reached "..global.XP.Fighting.Needed.." kills, increased Fighting stats by "..(global.XP.Fighting.Level/50)) global.XP.Fighting.Needed = global.XP.Fighting.Needed + math.random(global.XP.Fighting.Killed_Total) global.XP.Fighting.Bonus = global.XP.Fighting.Bonus + (global.XP.Fighting.Level/50) if not global.XP.Fighting.Category then global.XP.Fighting.Category = {"bullet","rocket","flame-thrower","shotgun-shell","railgun","cannon-shell","combat-robot-laser","laser-turret","electric","capsule","combat-robot-beam"} end for number,name in pairs(global.XP.Fighting.Category) do game.forces.player.set_ammo_damage_modifier(name, (game.forces.player.get_ammo_damage_modifier(name)+(global.XP.Fighting.Level/50))) end for number,name in pairs(global.XP.Fighting.Category) do game.forces.player.set_gun_speed_modifier(name, (game.forces.player.get_gun_speed_modifier(name)+(global.XP.Fighting.Level/50))) end PlayerPrint({"xp", {"fighting"}, string.sub((global.XP.Fighting.Level/50),1,4)}) end end function GUI_checker() if global.XP.GUI then for number in pairs(game.players) do GUI.closeGUI("XP", number) GUI.showDyTechWorldXPGUI(number) game.players[number].gui.left["mainDyTechWorldXPFlow"]["mainDyTechWorldXPFrame"]["Crafting-XP"].value = (global.XP.Crafting.Set/global.XP.Crafting.Needed) game.players[number].gui.left["mainDyTechWorldXPFlow"]["mainDyTechWorldXPFrame"]["Mining-XP"].value = (global.XP.Mining.Set/global.XP.Mining.Needed) game.players[number].gui.left["mainDyTechWorldXPFlow"]["mainDyTechWorldXPFrame"]["Building-XP"].value = (global.XP.Building.Set/global.XP.Building.Needed) game.players[number].gui.left["mainDyTechWorldXPFlow"]["mainDyTechWorldXPFrame"]["Explore-XP"].value = (global.XP.Explore.Set/global.XP.Explore.Needed) game.players[number].gui.left["mainDyTechWorldXPFlow"]["mainDyTechWorldXPFrame"]["Fighting-XP"].value = (global.XP.Fighting.Killed_Set/global.XP.Fighting.Needed) end else for number in pairs(game.players) do GUI.closeGUI("XP", number) end end end function Extinction() if not global.XP.Fighting.Extinction then global.XP.Fighting.Extinction = 0 end if global.XP.Fighting.Level==3 or global.XP.Fighting.Level==5 or global.XP.Fighting.Level==7 or global.XP.Fighting.Level==9 or global.XP.Fighting.Level==11 or global.XP.Fighting.Level==13 or global.XP.Fighting.Level==15 or global.XP.Fighting.Level==17 or global.XP.Fighting.Level==19 or global.XP.Fighting.Level==21 then global.XP.Fighting.Extinction = global.XP.Fighting.Extinction + 1 end end
0
0.750026
1
0.750026
game-dev
MEDIA
0.980216
game-dev
0.791846
1
0.791846
logisim-evolution/logisim-evolution
6,254
src/main/java/com/cburch/draw/actions/ModelReorderAction.java
/* * Logisim-evolution - digital logic design tool and simulator * Copyright by the Logisim-evolution developers * * https://github.com/logisim-evolution/ * * This is free software released under GNU GPLv3 license */ package com.cburch.draw.actions; import static com.cburch.draw.Strings.S; import com.cburch.draw.model.CanvasModel; import com.cburch.draw.model.CanvasObject; import com.cburch.draw.model.ReorderRequest; import com.cburch.draw.util.ZOrder; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; public class ModelReorderAction extends ModelAction { private final List<ReorderRequest> requests; private final List<CanvasObject> objects; private final int type; public ModelReorderAction(CanvasModel model, List<ReorderRequest> requests) { super(model); this.requests = new ArrayList<>(requests); this.objects = new ArrayList<>(requests.size()); for (final var req : requests) { objects.add(req.getObject()); } var typeIndex = 0; // 0 = mixed/unknown, -1 = to greater index, 1 = to // smaller index for (final var req : requests) { final var from = req.getFromIndex(); final var to = req.getToIndex(); final var thisType = Integer.compare(to, from); if (typeIndex == 2) { typeIndex = thisType; } else if (typeIndex != thisType) { typeIndex = 0; break; } } this.type = typeIndex; } public static ModelReorderAction createLower( CanvasModel model, Collection<? extends CanvasObject> objects) { final var reqs = new ArrayList<ReorderRequest>(); final var zmap = ZOrder.getZIndex(objects, model); for (final var entry : zmap.entrySet()) { final var obj = entry.getKey(); final var from = entry.getValue(); final var above = ZOrder.getObjectBelow(obj, model, objects); if (above != null) { var to = ZOrder.getZIndex(above, model); if (objects.contains(above)) { to++; } reqs.add(new ReorderRequest(obj, from, to)); } } if (reqs.isEmpty()) return null; reqs.sort(ReorderRequest.ASCENDING_FROM); repairRequests(reqs); return new ModelReorderAction(model, reqs); } public static ModelReorderAction createLowerBottom( CanvasModel model, Collection<? extends CanvasObject> objects) { final var reqs = new ArrayList<ReorderRequest>(); final var zmap = ZOrder.getZIndex(objects, model); var to = 0; for (final var entry : zmap.entrySet()) { final var obj = entry.getKey(); final var from = entry.getValue(); reqs.add(new ReorderRequest(obj, from, to)); } if (reqs.isEmpty()) return null; reqs.sort(ReorderRequest.ASCENDING_FROM); repairRequests(reqs); return new ModelReorderAction(model, reqs); } public static ModelReorderAction createRaise( CanvasModel model, Collection<? extends CanvasObject> objects) { final var reqs = new ArrayList<ReorderRequest>(); final var zmap = ZOrder.getZIndex(objects, model); for (final var entry : zmap.entrySet()) { final var obj = entry.getKey(); final var from = entry.getValue(); final var above = ZOrder.getObjectAbove(obj, model, objects); if (above != null) { var to = ZOrder.getZIndex(above, model); if (objects.contains(above)) { to--; } reqs.add(new ReorderRequest(obj, from, to)); } } if (reqs.isEmpty()) return null; reqs.sort(ReorderRequest.DESCENDING_FROM); repairRequests(reqs); return new ModelReorderAction(model, reqs); } public static ModelReorderAction createRaiseTop( CanvasModel model, Collection<? extends CanvasObject> objects) { final var reqs = new ArrayList<ReorderRequest>(); final var zmap = ZOrder.getZIndex(objects, model); final var to = model.getObjectsFromBottom().size() - 1; for (final var entry : zmap.entrySet()) { final var obj = entry.getKey(); final var from = entry.getValue(); reqs.add(new ReorderRequest(obj, from, to)); } if (reqs.isEmpty()) return null; reqs.sort(ReorderRequest.ASCENDING_FROM); repairRequests(reqs); return new ModelReorderAction(model, reqs); } private static void repairRequests(List<ReorderRequest> reqs) { for (int i = 0, n = reqs.size(); i < n; i++) { final var req = reqs.get(i); var from = req.getFromIndex(); var to = req.getToIndex(); for (var j = 0; j < i; j++) { final var prev = reqs.get(j); final var prevFrom = prev.getFromIndex(); final var prevTo = prev.getToIndex(); if (prevFrom <= from && from < prevTo) { from--; } else if (prevTo <= from && from < prevFrom) { from++; } if (prevFrom <= to && to < prevTo) { to--; } else if (prevTo <= to && to < prevFrom) { to++; } } if (from != req.getFromIndex() || to != req.getToIndex()) { reqs.set(i, new ReorderRequest(req.getObject(), from, to)); } } for (var i = reqs.size() - 1; i >= 0; i--) { final var req = reqs.get(i); if (req.getFromIndex() == req.getToIndex()) { reqs.remove(i); } } } @Override void doSub(CanvasModel model) { model.reorderObjects(requests); } @Override public String getName() { if (type < 0) { return S.get("actionRaise", getShapesName(objects)); } else if (type > 0) { return S.get("actionLower", getShapesName(objects)); } else { return S.get("actionReorder", getShapesName(objects)); } } @Override public Collection<CanvasObject> getObjects() { return objects; } public List<ReorderRequest> getReorderRequests() { return Collections.unmodifiableList(requests); } @Override void undoSub(CanvasModel model) { final var inv = new ArrayList<ReorderRequest>(requests.size()); for (var i = requests.size() - 1; i >= 0; i--) { final var request = requests.get(i); inv.add( new ReorderRequest(request.getObject(), request.getToIndex(), request.getFromIndex())); } model.reorderObjects(inv); } }
0
0.906452
1
0.906452
game-dev
MEDIA
0.322499
game-dev
0.951333
1
0.951333
rsocket/rsocket-cpp
1,836
rsocket/statemachine/StreamFragmentAccumulator.cpp
// Copyright (c) Facebook, Inc. and its affiliates. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "rsocket/statemachine/StreamFragmentAccumulator.h" namespace rsocket { StreamFragmentAccumulator::StreamFragmentAccumulator() : flagsComplete(false), flagsNext(false) {} void StreamFragmentAccumulator::addPayloadIgnoreFlags(Payload p) { if (p.metadata) { if (!fragments.metadata) { fragments.metadata = std::move(p.metadata); } else { fragments.metadata->prev()->appendChain(std::move(p.metadata)); } } if (p.data) { if (!fragments.data) { fragments.data = std::move(p.data); } else { fragments.data->prev()->appendChain(std::move(p.data)); } } } void StreamFragmentAccumulator::addPayload( Payload p, bool next, bool complete) { flagsNext |= next; flagsComplete |= complete; addPayloadIgnoreFlags(std::move(p)); } Payload StreamFragmentAccumulator::consumePayloadIgnoreFlags() { flagsComplete = false; flagsNext = false; return std::move(fragments); } std::tuple<Payload, bool, bool> StreamFragmentAccumulator::consumePayloadAndFlags() { auto ret = std::make_tuple( std::move(fragments), bool(flagsNext), bool(flagsComplete)); flagsComplete = false; flagsNext = false; return ret; } } /* namespace rsocket */
0
0.950675
1
0.950675
game-dev
MEDIA
0.65535
game-dev
0.914544
1
0.914544
AntKarlov/Anthill-Framework
3,116
ru/antkarlov/anthill/ants/AntFamily.as
package ru.antkarlov.anthill.ants { import flash.utils.Dictionary; import flash.utils.describeType; import flash.utils.getDefinitionByName; public class AntFamily extends Object implements IFamily { private var _nodes:AntNodeList; private var _nodeClass:Class; private var _objects:Dictionary; private var _components:Dictionary; private var _pool:AntNodePool; private var _core:AntCore; /** * @constructor */ public function AntFamily(aNodeClass:Class, aCore:AntCore) { super(); _nodeClass = aNodeClass; _core = aCore; init(); } /** * @private */ private function init():void { _nodes = new AntNodeList(); _objects = new Dictionary(); _components = new Dictionary(); _pool = new AntNodePool(_nodeClass, _components); _pool.set(_pool.get()); var variables:XMLList = describeType(_nodeClass).factory.variable; for each (var atom:XML in variables) { if (atom.@name != "object") { var componentClass:Class = getDefinitionByName(atom.@type) as Class; _components[componentClass] = atom.@name.toString(); } } } /** * @private */ public function add(aObject:AntObject):void { if (!_objects[aObject]) { var componentClass:*; for (componentClass in _components) { if (!aObject.has(componentClass)) { return; } } var node:AntNode = _pool.get(); node.object = aObject; for (componentClass in _components) { node[_components[componentClass]] = aObject.get(componentClass); } _objects[aObject] = node; _nodes.add(node); } } /** * @private */ public function remove(aObject:AntObject):void { if (_objects[aObject]) { var node:AntNode = _objects[aObject]; delete _objects[aObject]; _nodes.remove(node); if (_core.isLocked) { _pool.setToCache(node); _core.eventUpdateComplete.add(onCoreUpdateCompleted); } else { _pool.set(node); } } } /** * @private */ private function onCoreUpdateCompleted():void { _core.eventUpdateComplete.remove(onCoreUpdateCompleted); _pool.releaseCache(); } //--------------------------------------- // IFamily Implementation //--------------------------------------- //import ru.antkarlov.anthill.ants.IFamily; public function get nodes():AntNodeList { return _nodes; } public function addObject(aObject:AntObject):void { add(aObject); } public function removeObject(aObject:AntObject):void { remove(aObject); } public function componentAdded(aObject:AntObject, aComponentClass:Class):void { add(aObject); } public function componentRemoved(aObject:AntObject, aComponentClass:Class):void { if (_components[aComponentClass]) { remove(aObject); } } public function clear():void { var i:int = 0; var node:AntNode; while (i < _nodes.numNodes) { node = _nodes.get(i++); delete _objects[node.object]; } _nodes.removeAll(); _nodes = null; } } }
0
0.792323
1
0.792323
game-dev
MEDIA
0.789996
game-dev
0.800672
1
0.800672
jswigart/omni-bot
1,756
Omnibot/Common/EngineFuncs.h
//////////////////////////////////////////////////////////////////////////////// // // $LastChangedBy$ // $LastChangedDate$ // $LastChangedRevision$ // //////////////////////////////////////////////////////////////////////////////// #pragma once #ifndef __ENGINEFUNCS_H__ #define __ENGINEFUNCS_H__ #include "common.h" #include "IEngineInterface.h" namespace EngineFuncs { bool TraceLine( obTraceResult &_tr, const Vector3f &_start, const Vector3f &_end, const AABB *_aabb, int _mask, int _user, bool _usepvs ); std::string EntityName( const GameEntity _ent, const char* defaultName = "" ); GameEntity EntityOwner( const GameEntity _ent ); bool EntityPosition( const GameEntity _ent, Vector3f &_pos ); bool EntityEyePosition( const GameEntity _ent, Vector3f &_pos ); bool EntityBonePosition( const GameEntity _ent, int _boneid, Vector3f &_pos ); bool EntityOrientation( const GameEntity _ent, float _fwd[ 3 ], float _right[ 3 ], float _up[ 3 ] ); bool EntityOrientation( const GameEntity _ent, Matrix3f & mat ); bool EntityVelocity( const GameEntity _ent, Vector3f &_vel ); bool EntityLocalAABB( const GameEntity _ent, AABB &_bounds ); bool EntityWorldOBB( const GameEntity _ent, Box3f &_bounds ); bool EntityGroundEntity( const GameEntity _ent, GameEntity &moveent ); bool IsInPvs( const Vector3f &_source, const Vector3f &_target ); bool GroundPosition( const Vector3f &_pos, Vector3f &_outPosition, Vector3f &_outNormal, float _offset = 0.f ); ////////////////////////////////////////////////////////////////////////// void FlushAsyncMessages(); void ConsoleMessage( const char* _msg ); void ConsoleError( const char* _msg ); }; namespace Constants { enum Internal { MAX_PLAYERS = 64, MAX_ENTITIES = 4096 }; } #endif
0
0.730813
1
0.730813
game-dev
MEDIA
0.955709
game-dev
0.637578
1
0.637578
CraftTweaker/CraftTweaker
2,845
fabric/src/main/java/com/blamejared/crafttweaker/api/event/type/FabricItemTooltipEvent.java
//TODO this is left as an example of a fabric event, unfortunately the ItemTooltipCallback class is fully client side, so it cannot be used on a server //package com.blamejared.crafttweaker.api.event.type; // //import com.blamejared.crafttweaker.api.annotation.ZenRegister; //import com.blamejared.crafttweaker.api.event.ZenEvent; //import com.blamejared.crafttweaker.api.event.bus.CommonAdaptingEventBusWire; //import com.blamejared.crafttweaker.api.event.bus.FabricEventBusWire; //import com.blamejared.crafttweaker.api.event.bus.FabricWiredWrap; //import com.blamejared.crafttweaker.api.event.bus.IEventBus; //import com.blamejared.crafttweaker.api.item.IItemStack; //import com.blamejared.crafttweaker_annotations.annotations.Document; //import net.fabricmc.fabric.api.client.item.v1.ItemTooltipCallback; //import net.minecraft.network.chat.Component; //import net.minecraft.world.item.ItemStack; //import net.minecraft.world.item.TooltipFlag; //import org.openzen.zencode.java.ZenCodeType; // //import java.util.List; // //@ZenRegister //@ZenEvent //@Document("fabric/api/event/item/ItemTooltipEvent") //@ZenCodeType.Name("crafttweaker.forge.api.event.item.ItemTooltipEvent") //public final class FabricItemTooltipEvent { // // @ZenEvent.Bus // public static final IEventBus<FabricItemTooltipEvent> BUS = IEventBus.direct( // FabricItemTooltipEvent.class, // CommonAdaptingEventBusWire.of( // FabricEventBusWire.of(ItemTooltipCallback.EVENT, ItemTooltipCallback.class, FabricItemTooltipEvent.class), // ItemTooltipEvent.BUS, // FabricItemTooltipEvent::toCommon // ) // ); // // private final IItemStack stack; // private final TooltipFlag tooltipFlag; // private final List<Component> lines; // // private FabricItemTooltipEvent(final IItemStack stack, final TooltipFlag tooltipFlag, final List<Component> lines) { // this.stack = stack; // this.tooltipFlag = tooltipFlag; // this.lines = lines; // } // // @FabricWiredWrap // public static FabricItemTooltipEvent of(final ItemStack stack, final TooltipFlag tooltipFlag, final List<Component> lines) { // return new FabricItemTooltipEvent(IItemStack.of(stack), tooltipFlag, lines); // } // // private static ItemTooltipEvent toCommon(final FabricItemTooltipEvent platform) { // return ItemTooltipEvent.of(platform.stack(), platform.tooltipFlag(), platform.lines()); // } // // @ZenCodeType.Getter("stack") // public IItemStack stack() { // return this.stack; // } // // @ZenCodeType.Getter("tooltipFlag") // public TooltipFlag tooltipFlag() { // return this.tooltipFlag; // } // // @ZenCodeType.Getter("lines") // public List<Component> lines() { // return this.lines; // } //}
0
0.855805
1
0.855805
game-dev
MEDIA
0.941889
game-dev
0.687818
1
0.687818
botstylee/botstylee
2,032
lib/tictactoe.cjs
class TicTacToe { constructor(playerX = 'x', playerO = 'o') { this.playerX = playerX this.playerO = playerO this._currentTurn = false this._x = 0 this._o = 0 this.turns = 0 } get board() { return this._x | this._o } get currentTurn() { return this._currentTurn ? this.playerO : this.playerX } get enemyTurn() { return this._currentTurn ? this.playerX : this.playerO } static check(state) { for (var combo of [7, 56, 73, 84, 146, 273, 292, 448]) if ((state & combo) === combo) return !0 return !1 } /** * ```js * TicTacToe.toBinary(1, 2) // 0b010000000 * ``` */ static toBinary(x = 0, y = 0) { if (x < 0 || x > 2 || y < 0 || y > 2) throw new Error('invalid position') return 1 << x + (3 * y) } /** * @param player `0` is `X`, `1` is `O` * * - `-3` `Game Ended` * - `-2` `Invalid` * - `-1` `Invalid Position` * - ` 0` `Position Occupied` * - ` 1` `Sucess` * @returns {-3|-2|-1|0|1} */ turn(player = 0, x = 0, y) { if (this.board === 511) return -3 var pos = 0 if (y == null) { if (x < 0 || x > 8) return -1 pos = 1 << x } else { if (x < 0 || x > 2 || y < 0 || y > 2) return -1 pos = TicTacToe.toBinary(x, y) } if (this._currentTurn ^ player) return -2 if (this.board & pos) return 0 this[this._currentTurn ? '_o' : '_x'] |= pos this._currentTurn = !this._currentTurn this.turns++ return 1 } /** * @returns {('X'|'O'|1|2|3|4|5|6|7|8|9)[]} */ static render(boardX = 0, boardO = 0) { var x = parseInt(boardX.toString(2), 4) var y = parseInt(boardO.toString(2), 4) * 2 return [...(x + y).toString(4).padStart(9, '0')].reverse().map((value, index) => value == 1 ? 'X' : value == 2 ? 'O' : ++index) } /** * @returns {('X'|'O'|1|2|3|4|5|6|7|8|9)[]} */ render() { return TicTacToe.render(this._x, this._o) } get winner() { var x = TicTacToe.check(this._x) var o = TicTacToe.check(this._o) return x ? this.playerX : o ? this.playerO : false } } new TicTacToe().turn module.exports = TicTacToe
0
0.545597
1
0.545597
game-dev
MEDIA
0.682463
game-dev
0.812539
1
0.812539
FalconClient/FalconClient
16,367
src/main/java/net/minecraft/entity/item/EntityItem.java
package net.minecraft.entity.item; import net.minecraft.block.material.Material; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.stats.AchievementList; import net.minecraft.util.BlockPos; import net.minecraft.util.DamageSource; import net.minecraft.util.MathHelper; import net.minecraft.util.StatCollector; import net.minecraft.world.World; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class EntityItem extends Entity { private static final Logger logger = LogManager.getLogger(); /** * The age of this EntityItem (used to animate it up and down as well as expire it) */ private int age; private int delayBeforeCanPickup; /** The health of this EntityItem. (For example, damage for tools) */ private int health; private String thrower; private String owner; /** The EntityItem's random initial float height. */ public float hoverStart; public EntityItem(World worldIn, double x, double y, double z) { super(worldIn); this.health = 5; this.hoverStart = (float)(Math.random() * Math.PI * 2.0D); this.setSize(0.25F, 0.25F); this.setPosition(x, y, z); this.rotationYaw = (float)(Math.random() * 360.0D); this.motionX = (double)((float)(Math.random() * 0.20000000298023224D - 0.10000000149011612D)); this.motionY = 0.20000000298023224D; this.motionZ = (double)((float)(Math.random() * 0.20000000298023224D - 0.10000000149011612D)); } public EntityItem(World worldIn, double x, double y, double z, ItemStack stack) { this(worldIn, x, y, z); this.setEntityItemStack(stack); } /** * returns if this entity triggers Block.onEntityWalking on the blocks they walk on. used for spiders and wolves to * prevent them from trampling crops */ protected boolean canTriggerWalking() { return false; } public EntityItem(World worldIn) { super(worldIn); this.health = 5; this.hoverStart = (float)(Math.random() * Math.PI * 2.0D); this.setSize(0.25F, 0.25F); this.setEntityItemStack(new ItemStack(Blocks.air, 0)); } protected void entityInit() { this.getDataWatcher().addObjectByDataType(10, 5); } /** * Called to update the entity's position/logic. */ public void onUpdate() { if (this.getEntityItem() == null) { this.setDead(); } else { super.onUpdate(); if (this.delayBeforeCanPickup > 0 && this.delayBeforeCanPickup != 32767) { --this.delayBeforeCanPickup; } this.prevPosX = this.posX; this.prevPosY = this.posY; this.prevPosZ = this.posZ; this.motionY -= 0.03999999910593033D; this.noClip = this.pushOutOfBlocks(this.posX, (this.getEntityBoundingBox().minY + this.getEntityBoundingBox().maxY) / 2.0D, this.posZ); this.moveEntity(this.motionX, this.motionY, this.motionZ); boolean flag = (int)this.prevPosX != (int)this.posX || (int)this.prevPosY != (int)this.posY || (int)this.prevPosZ != (int)this.posZ; if (flag || this.ticksExisted % 25 == 0) { if (this.worldObj.getBlockState(new BlockPos(this)).getBlock().getMaterial() == Material.lava) { this.motionY = 0.20000000298023224D; this.motionX = (double)((this.rand.nextFloat() - this.rand.nextFloat()) * 0.2F); this.motionZ = (double)((this.rand.nextFloat() - this.rand.nextFloat()) * 0.2F); this.playSound("random.fizz", 0.4F, 2.0F + this.rand.nextFloat() * 0.4F); } if (!this.worldObj.isRemote) { this.searchForOtherItemsNearby(); } } float f = 0.98F; if (this.onGround) { f = this.worldObj.getBlockState(new BlockPos(MathHelper.floor_double(this.posX), MathHelper.floor_double(this.getEntityBoundingBox().minY) - 1, MathHelper.floor_double(this.posZ))).getBlock().slipperiness * 0.98F; } this.motionX *= (double)f; this.motionY *= 0.9800000190734863D; this.motionZ *= (double)f; if (this.onGround) { this.motionY *= -0.5D; } if (this.age != -32768) { ++this.age; } this.handleWaterMovement(); if (!this.worldObj.isRemote && this.age >= 6000) { this.setDead(); } } } /** * Looks for other itemstacks nearby and tries to stack them together */ private void searchForOtherItemsNearby() { for (EntityItem entityitem : this.worldObj.getEntitiesWithinAABB(EntityItem.class, this.getEntityBoundingBox().expand(0.5D, 0.0D, 0.5D))) { this.combineItems(entityitem); } } /** * Tries to merge this item with the item passed as the parameter. Returns true if successful. Either this item or * the other item will be removed from the world. */ private boolean combineItems(EntityItem other) { if (other == this) { return false; } else if (other.isEntityAlive() && this.isEntityAlive()) { ItemStack itemstack = this.getEntityItem(); ItemStack itemstack1 = other.getEntityItem(); if (this.delayBeforeCanPickup != 32767 && other.delayBeforeCanPickup != 32767) { if (this.age != -32768 && other.age != -32768) { if (itemstack1.getItem() != itemstack.getItem()) { return false; } else if (itemstack1.hasTagCompound() ^ itemstack.hasTagCompound()) { return false; } else if (itemstack1.hasTagCompound() && !itemstack1.getTagCompound().equals(itemstack.getTagCompound())) { return false; } else if (itemstack1.getItem() == null) { return false; } else if (itemstack1.getItem().getHasSubtypes() && itemstack1.getMetadata() != itemstack.getMetadata()) { return false; } else if (itemstack1.stackSize < itemstack.stackSize) { return other.combineItems(this); } else if (itemstack1.stackSize + itemstack.stackSize > itemstack1.getMaxStackSize()) { return false; } else { itemstack1.stackSize += itemstack.stackSize; other.delayBeforeCanPickup = Math.max(other.delayBeforeCanPickup, this.delayBeforeCanPickup); other.age = Math.min(other.age, this.age); other.setEntityItemStack(itemstack1); this.setDead(); return true; } } else { return false; } } else { return false; } } else { return false; } } /** * sets the age of the item so that it'll despawn one minute after it has been dropped (instead of five). Used when * items are dropped from players in creative mode */ public void setAgeToCreativeDespawnTime() { this.age = 4800; } /** * Returns if this entity is in water and will end up adding the waters velocity to the entity */ public boolean handleWaterMovement() { if (this.worldObj.handleMaterialAcceleration(this.getEntityBoundingBox(), Material.water, this)) { if (!this.inWater && !this.firstUpdate) { this.resetHeight(); } this.inWater = true; } else { this.inWater = false; } return this.inWater; } /** * Will deal the specified amount of damage to the entity if the entity isn't immune to fire damage. Args: * amountDamage */ protected void dealFireDamage(int amount) { this.attackEntityFrom(DamageSource.inFire, (float)amount); } /** * Called when the entity is attacked. */ public boolean attackEntityFrom(DamageSource source, float amount) { if (this.isEntityInvulnerable(source)) { return false; } else if (this.getEntityItem() != null && this.getEntityItem().getItem() == Items.nether_star && source.isExplosion()) { return false; } else { this.setBeenAttacked(); this.health = (int)((float)this.health - amount); if (this.health <= 0) { this.setDead(); } return false; } } /** * (abstract) Protected helper method to write subclass entity data to NBT. */ public void writeEntityToNBT(NBTTagCompound tagCompound) { tagCompound.setShort("Health", (short)((byte)this.health)); tagCompound.setShort("Age", (short)this.age); tagCompound.setShort("PickupDelay", (short)this.delayBeforeCanPickup); if (this.getThrower() != null) { tagCompound.setString("Thrower", this.thrower); } if (this.getOwner() != null) { tagCompound.setString("Owner", this.owner); } if (this.getEntityItem() != null) { tagCompound.setTag("Item", this.getEntityItem().writeToNBT(new NBTTagCompound())); } } /** * (abstract) Protected helper method to read subclass entity data from NBT. */ public void readEntityFromNBT(NBTTagCompound tagCompund) { this.health = tagCompund.getShort("Health") & 255; this.age = tagCompund.getShort("Age"); if (tagCompund.hasKey("PickupDelay")) { this.delayBeforeCanPickup = tagCompund.getShort("PickupDelay"); } if (tagCompund.hasKey("Owner")) { this.owner = tagCompund.getString("Owner"); } if (tagCompund.hasKey("Thrower")) { this.thrower = tagCompund.getString("Thrower"); } NBTTagCompound nbttagcompound = tagCompund.getCompoundTag("Item"); this.setEntityItemStack(ItemStack.loadItemStackFromNBT(nbttagcompound)); if (this.getEntityItem() == null) { this.setDead(); } } /** * Called by a player entity when they collide with an entity */ public void onCollideWithPlayer(EntityPlayer entityIn) { if (!this.worldObj.isRemote) { ItemStack itemstack = this.getEntityItem(); int i = itemstack.stackSize; if (this.delayBeforeCanPickup == 0 && (this.owner == null || 6000 - this.age <= 200 || this.owner.equals(entityIn.getName())) && entityIn.inventory.addItemStackToInventory(itemstack)) { if (itemstack.getItem() == Item.getItemFromBlock(Blocks.log)) { entityIn.triggerAchievement(AchievementList.mineWood); } if (itemstack.getItem() == Item.getItemFromBlock(Blocks.log2)) { entityIn.triggerAchievement(AchievementList.mineWood); } if (itemstack.getItem() == Items.leather) { entityIn.triggerAchievement(AchievementList.killCow); } if (itemstack.getItem() == Items.diamond) { entityIn.triggerAchievement(AchievementList.diamonds); } if (itemstack.getItem() == Items.blaze_rod) { entityIn.triggerAchievement(AchievementList.blazeRod); } if (itemstack.getItem() == Items.diamond && this.getThrower() != null) { EntityPlayer entityplayer = this.worldObj.getPlayerEntityByName(this.getThrower()); if (entityplayer != null && entityplayer != entityIn) { entityplayer.triggerAchievement(AchievementList.diamondsToYou); } } if (!this.isSilent()) { this.worldObj.playSoundAtEntity(entityIn, "random.pop", 0.2F, ((this.rand.nextFloat() - this.rand.nextFloat()) * 0.7F + 1.0F) * 2.0F); } entityIn.onItemPickup(this, i); if (itemstack.stackSize <= 0) { this.setDead(); } } } } /** * Get the name of this object. For players this returns their username */ public String getName() { return this.hasCustomName() ? this.getCustomNameTag() : StatCollector.translateToLocal("item." + this.getEntityItem().getUnlocalizedName()); } /** * If returns false, the item will not inflict any damage against entities. */ public boolean canAttackWithItem() { return false; } /** * Teleports the entity to another dimension. Params: Dimension number to teleport to */ public void travelToDimension(int dimensionId) { super.travelToDimension(dimensionId); if (!this.worldObj.isRemote) { this.searchForOtherItemsNearby(); } } /** * Returns the ItemStack corresponding to the Entity (Note: if no item exists, will log an error but still return an * ItemStack containing Block.stone) */ public ItemStack getEntityItem() { ItemStack itemstack = this.getDataWatcher().getWatchableObjectItemStack(10); if (itemstack == null) { if (this.worldObj != null) { logger.error("Item entity " + this.getEntityId() + " has no item?!"); } return new ItemStack(Blocks.stone); } else { return itemstack; } } /** * Sets the ItemStack for this entity */ public void setEntityItemStack(ItemStack stack) { this.getDataWatcher().updateObject(10, stack); this.getDataWatcher().setObjectWatched(10); } public String getOwner() { return this.owner; } public void setOwner(String owner) { this.owner = owner; } public String getThrower() { return this.thrower; } public void setThrower(String thrower) { this.thrower = thrower; } public int getAge() { return this.age; } public void setDefaultPickupDelay() { this.delayBeforeCanPickup = 10; } public void setNoPickupDelay() { this.delayBeforeCanPickup = 0; } public void setInfinitePickupDelay() { this.delayBeforeCanPickup = 32767; } public void setPickupDelay(int ticks) { this.delayBeforeCanPickup = ticks; } public boolean cannotPickup() { return this.delayBeforeCanPickup > 0; } public void setNoDespawn() { this.age = -6000; } public void func_174870_v() { this.setInfinitePickupDelay(); this.age = 5999; } }
0
0.92354
1
0.92354
game-dev
MEDIA
0.994777
game-dev
0.974768
1
0.974768
Secrets-of-Sosaria/World
1,388
Data/Scripts/Mobiles/Animals/Misc/Goat.cs
using System; using Server.Mobiles; namespace Server.Mobiles { [CorpseName( "a goat corpse" )] public class Goat : BaseCreature { [Constructable] public Goat() : base( AIType.AI_Animal, FightMode.Aggressor, 10, 1, 0.2, 0.4 ) { Name = "a goat"; Body = 209; BaseSoundID = 0x99; SetStr( 19 ); SetDex( 15 ); SetInt( 5 ); SetHits( 12 ); SetMana( 0 ); SetDamage( 3, 4 ); SetDamageType( ResistanceType.Physical, 100 ); SetResistance( ResistanceType.Physical, 5, 15 ); SetSkill( SkillName.MagicResist, 5.0 ); SetSkill( SkillName.Tactics, 5.0 ); SetSkill( SkillName.FistFighting, 5.0 ); Fame = 150; Karma = 0; VirtualArmor = 10; Tamable = true; ControlSlots = 1; MinTameSkill = 11.1; } public override int Meat{ get{ return 2; } } public override int Hides{ get{ return 8; } } public override int Cloths{ get{ return 4; } } public override ClothType ClothType{ get{ return ClothType.Wooly; } } public override FoodType FavoriteFood{ get{ return FoodType.GrainsAndHay | FoodType.FruitsAndVegies; } } public Goat(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(); } } }
0
0.734468
1
0.734468
game-dev
MEDIA
0.956583
game-dev
0.757635
1
0.757635
ppy/osu
9,028
osu.Game/Overlays/Toolbar/TransientUserStatisticsUpdateDisplay.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Sprites; using osu.Framework.Localisation; using osu.Framework.Threading; using osu.Game.Graphics; using osu.Game.Graphics.Sprites; using osu.Game.Graphics.UserInterface; using osu.Game.Online; using osu.Game.Resources.Localisation.Web; using osuTK; namespace osu.Game.Overlays.Toolbar { public partial class TransientUserStatisticsUpdateDisplay : CompositeDrawable { public Bindable<ScoreBasedUserStatisticsUpdate?> LatestUpdate { get; } = new Bindable<ScoreBasedUserStatisticsUpdate?>(); private Statistic<int> globalRank = null!; private Statistic<int> pp = null!; [BackgroundDependencyLoader] private void load(UserStatisticsWatcher? userStatisticsWatcher) { RelativeSizeAxes = Axes.Y; AutoSizeAxes = Axes.X; Alpha = 0; InternalChild = new FillFlowContainer { RelativeSizeAxes = Axes.Y, AutoSizeAxes = Axes.X, Padding = new MarginPadding { Horizontal = 10 }, Spacing = new Vector2(10), Direction = FillDirection.Horizontal, Children = new Drawable[] { globalRank = new Statistic<int>(UsersStrings.ShowRankGlobalSimple, @"#", Comparer<int>.Create((before, after) => before - after)), pp = new Statistic<int>(RankingsStrings.StatPerformance, string.Empty, Comparer<int>.Create((before, after) => Math.Sign(after - before))), } }; if (userStatisticsWatcher != null) ((IBindable<ScoreBasedUserStatisticsUpdate?>)LatestUpdate).BindTo(userStatisticsWatcher.LatestUpdate); } protected override void LoadComplete() { base.LoadComplete(); LatestUpdate.BindValueChanged(val => { if (val.NewValue == null) return; var update = val.NewValue; // null handling here is best effort because it is annoying. globalRank.Alpha = update.After.GlobalRank == null ? 0 : 1; pp.Alpha = update.After.PP == null ? 0 : 1; if (globalRank.Alpha == 0 && pp.Alpha == 0) return; FinishTransforms(true); this.FadeIn(500, Easing.OutQuint); if (update.After.GlobalRank != null) { globalRank.Display( update.Before.GlobalRank ?? update.After.GlobalRank.Value, Math.Abs((update.After.GlobalRank.Value - update.Before.GlobalRank) ?? 0), update.After.GlobalRank.Value); } if (update.After.PP != null) { int before = (int)Math.Round(update.Before.PP ?? update.After.PP.Value); int after = (int)Math.Round(update.After.PP.Value); int delta = Math.Abs(after - before); pp.Display(before, delta, after); } this.Delay(5000).FadeOut(500, Easing.OutQuint); }); } private partial class Statistic<T> : CompositeDrawable where T : struct, IEquatable<T>, IFormattable { private readonly LocalisableString title; private readonly string mainValuePrefix; private readonly IComparer<T> valueComparer; private Counter<T> mainValue = null!; private Counter<T> deltaValue = null!; private OsuSpriteText titleText = null!; private ScheduledDelegate? valueUpdateSchedule; [Resolved] private OsuColour colours { get; set; } = null!; public Statistic(LocalisableString title, string mainValuePrefix, IComparer<T> valueComparer) { this.title = title; this.mainValuePrefix = mainValuePrefix; this.valueComparer = valueComparer; } [BackgroundDependencyLoader] private void load() { RelativeSizeAxes = Axes.Y; AutoSizeAxes = Axes.X; InternalChild = new FillFlowContainer { AutoSizeAxes = Axes.Both, Anchor = Anchor.CentreRight, Origin = Anchor.CentreRight, Direction = FillDirection.Vertical, Children = new Drawable[] { mainValue = new Counter<T> { ValuePrefix = mainValuePrefix, Anchor = Anchor.CentreRight, Origin = Anchor.CentreRight, }, new Container { AutoSizeAxes = Axes.Both, Anchor = Anchor.CentreRight, Origin = Anchor.CentreRight, Children = new Drawable[] { deltaValue = new Counter<T> { Anchor = Anchor.CentreRight, Origin = Anchor.CentreRight, Font = OsuFont.Default.With(size: 12, fixedWidth: true, weight: FontWeight.SemiBold), AlwaysPresent = true, }, titleText = new OsuSpriteText { Anchor = Anchor.CentreRight, Origin = Anchor.CentreRight, Font = OsuFont.Default.With(size: 12, weight: FontWeight.SemiBold), Text = title, AlwaysPresent = true, } } } } }; } public void Display(T before, T delta, T after) { valueUpdateSchedule?.Cancel(); valueUpdateSchedule = null; int comparison = valueComparer.Compare(before, after); if (comparison > 0) { deltaValue.Colour = colours.Lime1; deltaValue.ValuePrefix = "+"; } else if (comparison < 0) { deltaValue.Colour = colours.Red1; deltaValue.ValuePrefix = "-"; } else { deltaValue.Colour = Colour4.White; deltaValue.ValuePrefix = string.Empty; } mainValue.SetCountWithoutRolling(before); deltaValue.SetCountWithoutRolling(delta); titleText.Alpha = 1; deltaValue.Alpha = 0; using (BeginDelayedSequence(1200)) { titleText.FadeOut(250, Easing.OutQuad); deltaValue.FadeIn(250, Easing.OutQuad); using (BeginDelayedSequence(1250)) { valueUpdateSchedule = Schedule(() => { mainValue.Current.Value = after; deltaValue.Current.SetDefault(); }); } } } } private partial class Counter<T> : RollingCounter<T> where T : struct, IEquatable<T>, IFormattable { public FontUsage Font { get; init; } = OsuFont.Default.With(fixedWidth: true); public string ValuePrefix { get => valuePrefix; set { valuePrefix = value; UpdateDisplay(); } } private string valuePrefix = string.Empty; protected override LocalisableString FormatCount(T count) => LocalisableString.Format(@"{0}{1:N0}", ValuePrefix, count); protected override OsuSpriteText CreateSpriteText() => base.CreateSpriteText().With(t => { t.Font = Font; t.Spacing = new Vector2(-1.5f, 0); }); protected override double RollingDuration => 1500; } } }
0
0.886561
1
0.886561
game-dev
MEDIA
0.618283
game-dev
0.949031
1
0.949031
feifeid47/Unity-UI-Adapter
1,836
Assets/Plugins/UIAdapter/SafeAreaAdapter.cs
using UnityEngine; using UnityEngine.UI; namespace Feif.UI { public class SafeAreaAdapter : AdapterBase { [Header("是否每一帧都计算")] public bool CalculateEveryFrame = false; private RectTransform rect; private static CanvasScaler scaler; public static void Init(CanvasScaler scaler) { SafeAreaAdapter.scaler = scaler; } private void Awake() { SafeAreaAdapter.Init(GameObject.FindObjectOfType<CanvasScaler>()); rect = GetComponent<RectTransform>(); Adapt(); } private void Update() { if (CalculateEveryFrame) { Adapt(); } } public override void Adapt() { if (scaler == null) return; var safeArea = Screen.safeArea; int width = (int)(scaler.referenceResolution.x * (1 - scaler.matchWidthOrHeight) + scaler.referenceResolution.y * Screen.width / Screen.height * scaler.matchWidthOrHeight); int height = (int)(scaler.referenceResolution.y * scaler.matchWidthOrHeight - scaler.referenceResolution.x * Screen.height / Screen.width * (scaler.matchWidthOrHeight - 1)); float ratio = scaler.referenceResolution.y * scaler.matchWidthOrHeight / Screen.height - scaler.referenceResolution.x * (scaler.matchWidthOrHeight - 1) / Screen.width; rect.anchorMin = Vector2.zero; rect.anchorMax = Vector2.one; rect.offsetMin = new Vector2(safeArea.position.x * ratio, safeArea.position.y * ratio); rect.offsetMax = new Vector2(safeArea.position.x * ratio + safeArea.width * ratio - width, -(height - safeArea.position.y * ratio - safeArea.height * ratio)); } } }
0
0.820651
1
0.820651
game-dev
MEDIA
0.481567
game-dev
0.916989
1
0.916989
space-wizards/RobustToolbox
15,768
Robust.Shared/Physics/Systems/SharedPhysicsSystem.cs
using System; using Prometheus; using Robust.Shared.Configuration; using Robust.Shared.Containers; using Robust.Shared.GameObjects; using Robust.Shared.GameStates; using Robust.Shared.Map; using Robust.Shared.Map.Components; using Robust.Shared.Physics.Collision; using Robust.Shared.Physics.Components; using Robust.Shared.Physics.Events; using Robust.Shared.Threading; using Robust.Shared.Timing; using Robust.Shared.Utility; using DependencyAttribute = Robust.Shared.IoC.DependencyAttribute; namespace Robust.Shared.Physics.Systems { public abstract partial class SharedPhysicsSystem : EntitySystem { /* * TODO: * TOI Solver (continuous collision detection) * Poly cutting */ public static readonly Histogram TickUsageControllerBeforeSolveHistogram = Metrics.CreateHistogram("robust_entity_physics_controller_before_solve", "Amount of time spent running a controller's UpdateBeforeSolve", new HistogramConfiguration { LabelNames = new[] {"controller"}, Buckets = Histogram.ExponentialBuckets(0.000_001, 1.5, 25) }); public static readonly Histogram TickUsageControllerAfterSolveHistogram = Metrics.CreateHistogram("robust_entity_physics_controller_after_solve", "Amount of time spent running a controller's UpdateAfterSolve", new HistogramConfiguration { LabelNames = new[] {"controller"}, Buckets = Histogram.ExponentialBuckets(0.000_001, 1.5, 25) }); [Dependency] private readonly IConfigurationManager _cfg = default!; [Dependency] private readonly IManifoldManager _manifoldManager = default!; [Dependency] private readonly IParallelManager _parallel = default!; [Dependency] private readonly EntityLookupSystem _lookup = default!; [Dependency] private readonly SharedBroadphaseSystem _broadphase = default!; [Dependency] private readonly SharedContainerSystem _containerSystem = default!; [Dependency] private readonly SharedDebugPhysicsSystem _debugPhysics = default!; [Dependency] private readonly SharedJointSystem _joints = default!; [Dependency] private readonly SharedTransformSystem _transform = default!; [Dependency] private readonly CollisionWakeSystem _wakeSystem = default!; private int _substeps; /// <summary> /// A variation of <see cref="IGameTiming.CurTime"/> that takes into account the current physics sub-step. /// Useful for some entities that need to interpolate their positions during sub-steps. /// </summary> public TimeSpan? EffectiveCurTime; public bool MetricsEnabled { get; protected set; } private EntityQuery<CollideOnAnchorComponent> _anchorQuery; private EntityQuery<FixturesComponent> _fixturesQuery; private EntityQuery<JointComponent> JointQuery; private EntityQuery<JointRelayTargetComponent> RelayTargetQuery; private EntityQuery<MapGridComponent> _gridQuery; protected EntityQuery<MapComponent> MapQuery; protected EntityQuery<PhysicsComponent> PhysicsQuery; protected EntityQuery<TransformComponent> XformQuery; private ComponentRegistration _physicsReg = default!; private byte _angularVelocityIndex; public override void Initialize() { base.Initialize(); _physicsReg = EntityManager.ComponentFactory.GetRegistration(CompIdx.Index<PhysicsComponent>()); // TODO PHYSICS STATE // Consider condensing the possible fields into just Linear velocity, angular velocity, and "Other" // Or maybe even just "velocity" & "other" // Then get-state doesn't have to iterate over a 10-element array. // And it simplifies the DirtyField calls. // Though I guess combining fixtures & physics will complicate it a bit more again. // If you update this then update the delta state + GetState + HandleState! EntityManager.ComponentFactory.RegisterNetworkedFields(_physicsReg, nameof(PhysicsComponent.CanCollide), nameof(PhysicsComponent.BodyStatus), nameof(PhysicsComponent.BodyType), nameof(PhysicsComponent.SleepingAllowed), nameof(PhysicsComponent.FixedRotation), nameof(PhysicsComponent.Friction), nameof(PhysicsComponent.Force), nameof(PhysicsComponent.Torque), nameof(PhysicsComponent.LinearDamping), nameof(PhysicsComponent.AngularDamping), nameof(PhysicsComponent.AngularVelocity), nameof(PhysicsComponent.LinearVelocity)); _angularVelocityIndex = 10; _anchorQuery = GetEntityQuery<CollideOnAnchorComponent>(); _fixturesQuery = GetEntityQuery<FixturesComponent>(); JointQuery = GetEntityQuery<JointComponent>(); RelayTargetQuery = GetEntityQuery<JointRelayTargetComponent>(); MapQuery = GetEntityQuery<MapComponent>(); _gridQuery = GetEntityQuery<MapGridComponent>(); PhysicsQuery = GetEntityQuery<PhysicsComponent>(); XformQuery = GetEntityQuery<TransformComponent>(); SubscribeLocalEvent<GridAddEvent>(OnGridAdd); SubscribeLocalEvent<CollisionChangeEvent>(OnCollisionChange); SubscribeLocalEvent<PhysicsComponent, EntGotRemovedFromContainerMessage>(HandleContainerRemoved); SubscribeLocalEvent<PhysicsComponent, ComponentInit>(OnPhysicsInit); SubscribeLocalEvent<PhysicsComponent, ComponentShutdown>(OnPhysicsShutdown); SubscribeLocalEvent<PhysicsComponent, ComponentGetState>(OnPhysicsGetState); SubscribeLocalEvent<PhysicsComponent, ComponentHandleState>(OnPhysicsHandleState); InitializeIsland(); InitializeContacts(); Subs.CVar(_cfg, CVars.AutoClearForces, OnAutoClearChange, true); Subs.CVar(_cfg, CVars.NetTickrate, UpdateSubsteps, true); Subs.CVar(_cfg, CVars.TargetMinimumTickrate, UpdateSubsteps, true); } private void OnPhysicsShutdown(EntityUid uid, PhysicsComponent component, ComponentShutdown args) { SetCanCollide(uid, false, false, body: component); DebugTools.Assert(!component.Awake); if (LifeStage(uid) <= EntityLifeStage.MapInitialized) RemComp<FixturesComponent>(uid); } private void OnCollisionChange(ref CollisionChangeEvent ev) { var uid = ev.BodyUid; var mapId = Transform(uid).MapID; if (mapId == MapId.Nullspace) return; if (!ev.CanCollide) { DestroyContacts(ev.Body); } } private void OnAutoClearChange(bool value) { _autoClearForces = value; } private void UpdateSubsteps(int obj) { var targetMinTickrate = (float) _cfg.GetCVar(CVars.TargetMinimumTickrate); var serverTickrate = (float) _cfg.GetCVar(CVars.NetTickrate); _substeps = (int)Math.Ceiling(targetMinTickrate / serverTickrate); } internal void OnParentChange(Entity<TransformComponent, MetaDataComponent> ent, EntityUid oldParent, EntityUid? oldMap) { // We do not have a directed/body subscription, because the entity changing parents may not have a physics component, but one of its children might. var (uid, xform, meta) = ent; // If this entity has yet to be initialized, then we can skip this as equivalent code will get run during // init anyways. HOWEVER: it is possible that one of the children of this entity are already post-init, in // which case they still need to handle map changes. This frequently happens when clients receives a server // state where a known/old entity gets attached to a new, previously unknown, entity. The new entity will be // uninitialized but have an initialized child. if (xform.ChildCount == 0 && meta.EntityLifeStage < EntityLifeStage.Initialized) return; // Is this entity getting recursively detached after it's parent was already detached to null? if (oldMap == null && xform.MapUid == null) return; var body = PhysicsQuery.CompOrNull(uid); // Handle map changes if (oldMap != xform.MapUid) { // This will also handle broadphase updating & joint clearing. HandleMapChange(uid, xform, body); return; } if (body != null) HandleParentChangeVelocity(uid, body, oldParent, xform); } /// <summary> /// Recursively add/remove from awake bodies, clear joints, remove from move buffer, and update broadphase. /// </summary> private void HandleMapChange(EntityUid uid, TransformComponent xform, PhysicsComponent? body) { RecursiveMapUpdate(uid, xform, body); } /// <summary> /// Recursively add/remove from awake bodies, clear joints, remove from move buffer, and update broadphase. /// </summary> private void RecursiveMapUpdate( EntityUid uid, TransformComponent xform, PhysicsComponent? body) { DebugTools.Assert(!Deleted(uid)); _joints.ClearJoints(uid); foreach (var child in xform._children) { if (XformQuery.TryGetComponent(child, out var childXform)) { PhysicsQuery.TryGetComponent(child, out var childBody); RecursiveMapUpdate(child, childXform, childBody); } } } private void OnGridAdd(GridAddEvent ev) { var guid = ev.EntityUid; // If it's mapgrid then no physics. if (HasComp<MapComponent>(guid)) return; var body = EnsureComp<PhysicsComponent>(guid); var manager = EnsureComp<FixturesComponent>(guid); SetCanCollide(guid, true, manager: manager, body: body); SetBodyType(guid, BodyType.Static, manager: manager, body: body); } public override void Shutdown() { base.Shutdown(); ShutdownContacts(); } private void HandleContainerRemoved(EntityUid uid, PhysicsComponent physics, EntGotRemovedFromContainerMessage message) { // If entity being deleted then the parent change will already be handled elsewhere and we don't want to re-add it to the map. if (MetaData(uid).EntityLifeStage >= EntityLifeStage.Terminating) return; // If this entity is only meant to collide when anchored, return early. if (_anchorQuery.TryGetComponent(uid, out var collideComp) && collideComp.Enable) return; WakeBody(uid, body: physics); } /// <summary> /// Simulates the physical world for a given amount of time. /// </summary> /// <param name="deltaTime">Delta Time in seconds of how long to simulate the world.</param> /// <param name="prediction">Should only predicted entities be considered in this simulation step?</param> protected void SimulateWorld(float deltaTime, bool prediction) { var frameTime = deltaTime / _substeps; EffectiveCurTime = _gameTiming.CurTime; for (int i = 0; i < _substeps; i++) { var updateBeforeSolve = new PhysicsUpdateBeforeSolveEvent(prediction, frameTime); RaiseLocalEvent(ref updateBeforeSolve); // Find new contacts and (TODO: temporary) update any per-map virtual controllers // Box2D does this at the end of a step and also here when there's a fixture update. // Given external stuff can move bodies we'll just do this here. _broadphase.FindNewContacts(); // TODO PHYSICS Fix Collision Mispredicts // If a physics update induces a position update that brings fixtures into contact, the collision starts in the NEXT tick, // as positions are updated after CollideContacts() gets called. // // If a player input induces a position update that brings fixtures into contact, the collision happens on the SAME tick, // as inputs are handled before system updates. // // When applying a server's game state with new positions, the client won't know what caused the positions to update, // and thus can't know whether the collision already occurred (i.e., whether its effects are already contained within the // game state currently being applied), or whether it should start on the next tick and needs to predict the start of // the collision. // // Currently the client assumes that any position updates happened due to physics steps. I.e., positions are reset, then // contacts are reset via ResetContacts(), then positions are updated using the new game state. Alternatively, we could // call ResetContacts() AFTER applying the server state, which would correspond to assuming that the collisions have // already "started" in the state, and we don't want to re-raise the events. // // Currently there is no way to avoid mispredicts from happening. E.g., a simple collision-counter component will always // either mispredict on physics induced position changes, or on player/input induced updates. The easiest way I can think // of to fix this would be to always call `CollideContacts` again at the very end of a physics update. // But that might be unnecessarily expensive for what are hopefully only infrequent mispredicts. CollideContacts(); Step(frameTime, prediction); var updateAfterSolve = new PhysicsUpdateAfterSolveEvent(prediction, frameTime); RaiseLocalEvent(ref updateAfterSolve); // On last substep (or main step where no substeps occured) we'll update all of the lerp data. if (i == _substeps - 1) { FinalStep(); } EffectiveCurTime = EffectiveCurTime.Value + TimeSpan.FromSeconds(frameTime); } EffectiveCurTime = null; } protected virtual void FinalStep() { } } [ByRefEvent] public readonly struct PhysicsUpdateAfterSolveEvent { public readonly bool Prediction; public readonly float DeltaTime; public PhysicsUpdateAfterSolveEvent(bool prediction, float deltaTime) { Prediction = prediction; DeltaTime = deltaTime; } } [ByRefEvent] public readonly struct PhysicsUpdateBeforeSolveEvent { public readonly bool Prediction; public readonly float DeltaTime; public PhysicsUpdateBeforeSolveEvent(bool prediction, float deltaTime) { Prediction = prediction; DeltaTime = deltaTime; } } }
0
0.865311
1
0.865311
game-dev
MEDIA
0.97026
game-dev
0.954317
1
0.954317
kej715/DtCyber
5,995
deadstart.c
/*-------------------------------------------------------------------------- ** ** Copyright (c) 2003-2011, Tom Hunter ** ** Name: deadstart.c ** ** Description: ** Perform emulation of CDC 6600 deadstart. ** ** This program is free software: you can redistribute it and/or modify ** it under the terms of the GNU General Public License version 3 as ** published by the Free Software Foundation. ** ** 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 version 3 for more details. ** ** You should have received a copy of the GNU General Public License ** version 3 along with this program in file "license-gpl-3.0.txt". ** If not, see <http://www.gnu.org/licenses/gpl-3.0.txt>. ** **-------------------------------------------------------------------------- */ /* ** ------------- ** Include Files ** ------------- */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "const.h" #include "types.h" #include "proto.h" /* ** ----------------- ** Private Constants ** ----------------- */ /* ** ----------------------- ** Private Macro Functions ** ----------------------- */ /* ** ----------------------------------------- ** Private Typedef and Structure Definitions ** ----------------------------------------- */ /* ** --------------------------- ** Private Function Prototypes ** --------------------------- */ static FcStatus deadFunc(PpWord funcCode); static void deadIo(void); static void deadActivate(void); static void deadDisconnect(void); /* ** ---------------- ** Public Variables ** ---------------- */ u16 deadstartPanel[MaxDeadStart]; u8 deadstartCount; /* ** ----------------- ** Private Variables ** ----------------- */ static u8 dsSequence; /* deadstart sequencer */ /* **-------------------------------------------------------------------------- ** ** Public Functions ** **-------------------------------------------------------------------------- */ /*-------------------------------------------------------------------------- ** Purpose: Execute deadstart function. ** ** Parameters: Name Description. ** ** Returns: Nothing. ** **------------------------------------------------------------------------*/ void deadStart(void) { DevSlot *dp; u8 pp; u8 ch; dp = channelAttach(0, 0, DtDeadStartPanel); dp->activate = deadActivate; dp->disconnect = deadDisconnect; dp->func = deadFunc; dp->io = deadIo; dp->selectedUnit = 0; /* ** Set all normal channels to active and empty. */ for (ch = 0; ch < channelCount; ch++) { if ((ch <= 013) || ((ch >= 020) && (ch <= 033))) { channel[ch].active = TRUE; } } /* ** Set special channels appropriately. */ channel[ChInterlock].active = (features & HasInterlockReg) != 0; channel[ChMaintenance].active = FALSE; /* ** Reset deadstart sequencer. */ dsSequence = 0; for (pp = 0; pp < ppuCount; pp++) { /* ** Assign PPs to the corresponding channels. */ if (pp < 012) { ppu[pp].opD = pp; channel[pp].active = TRUE; } else { ppu[pp].opD = pp - 012 + 020; channel[pp - 012 + 020].active = TRUE; } /* ** Set all PPs to INPUT (71) instruction. */ ppu[pp].opF = 071; ppu[pp].busy = TRUE; /* ** Clear P registers and location zero of each PP. */ ppu[pp].regP = 0; ppu[pp].mem[0] = 0; /* ** Set all A registers to an input word count of 10000. */ ppu[pp].regA = 010000; } /* ** Start load of PPU0. */ channel[0].ioDevice = dp; channel[0].active = TRUE; channel[0].full = TRUE; channel[0].data = 0; } /*-------------------------------------------------------------------------- ** Purpose: Execute function code on deadstart pseudo device. ** ** Parameters: Name Description. ** funcCode function code ** ** Returns: FcStatus ** **------------------------------------------------------------------------*/ static FcStatus deadFunc(PpWord funcCode) { (void)funcCode; return (FcDeclined); } /*-------------------------------------------------------------------------- ** Purpose: Perform I/O on deadstart panel. ** ** Parameters: Name Description. ** ** Returns: Nothing. ** **------------------------------------------------------------------------*/ static void deadIo(void) { if (!activeChannel->full) { if (dsSequence == deadstartCount) { activeChannel->active = FALSE; } else { activeChannel->data = deadstartPanel[dsSequence++] & Mask12; activeChannel->full = TRUE; } } } /*-------------------------------------------------------------------------- ** Purpose: Handle channel activation. ** ** Parameters: Name Description. ** ** Returns: Nothing. ** **------------------------------------------------------------------------*/ static void deadActivate(void) { } /*-------------------------------------------------------------------------- ** Purpose: Handle disconnecting of channel. ** ** Parameters: Name Description. ** ** Returns: Nothing. ** **------------------------------------------------------------------------*/ static void deadDisconnect(void) { } /*--------------------------- End Of File ------------------------------*/
0
0.699256
1
0.699256
game-dev
MEDIA
0.252556
game-dev
0.508185
1
0.508185
gamekit-developers/gamekit
9,196
Samples/OgreDemo/SDK/OSX/Xcode Templates/Xcode4/Project Templates/Ogre/iOS Application.xctemplate/OgreFramework.cpp
#include "OgreFramework.h" #include "macUtils.h" using namespace Ogre; namespace Ogre { template<> OgreFramework* Ogre::Singleton<OgreFramework>::msSingleton = 0; }; OgreFramework::OgreFramework() { m_MoveSpeed = 0.1f; m_RotateSpeed = 0.3f; m_bShutDownOgre = false; m_iNumScreenShots = 0; m_pRoot = 0; m_pSceneMgr = 0; m_pRenderWnd = 0; m_pCamera = 0; m_pViewport = 0; m_pLog = 0; m_pTimer = 0; m_pInputMgr = 0; m_pKeyboard = 0; m_pMouse = 0; #if OGRE_PLATFORM == OGRE_PLATFORM_APPLE m_ResourcePath = macBundlePath() + "/Contents/Resources/"; #elif defined(OGRE_IS_IOS) m_ResourcePath = macBundlePath() + "/"; #else m_ResourcePath = ""; #endif m_pTrayMgr = 0; m_FrameEvent = Ogre::FrameEvent(); } //||||||||||||||||||||||||||||||||||||||||||||||| #if defined(OGRE_IS_IOS) bool OgreFramework::initOgre(Ogre::String wndTitle, OIS::KeyListener *pKeyListener, OIS::MultiTouchListener *pMouseListener) #else bool OgreFramework::initOgre(Ogre::String wndTitle, OIS::KeyListener *pKeyListener, OIS::MouseListener *pMouseListener) #endif { new Ogre::LogManager(); m_pLog = Ogre::LogManager::getSingleton().createLog("OgreLogfile.log", true, true, false); m_pLog->setDebugOutputEnabled(true); String pluginsPath; // only use plugins.cfg if not static #ifndef OGRE_STATIC_LIB pluginsPath = m_ResourcePath + "plugins.cfg"; #endif m_pRoot = new Ogre::Root(pluginsPath, Ogre::macBundlePath() + "/ogre.cfg"); #ifdef OGRE_STATIC_LIB m_StaticPluginLoader.load(); #endif if(!m_pRoot->showConfigDialog()) return false; m_pRenderWnd = m_pRoot->initialise(true, wndTitle); m_pSceneMgr = m_pRoot->createSceneManager(ST_GENERIC, "SceneManager"); m_pSceneMgr->setAmbientLight(Ogre::ColourValue(0.7f, 0.7f, 0.7f)); m_pCamera = m_pSceneMgr->createCamera("Camera"); m_pCamera->setPosition(Vector3(0, 60, 60)); m_pCamera->lookAt(Vector3(0, 0, 0)); m_pCamera->setNearClipDistance(1); m_pViewport = m_pRenderWnd->addViewport(m_pCamera); m_pViewport->setBackgroundColour(ColourValue(0.8f, 0.7f, 0.6f, 1.0f)); m_pCamera->setAspectRatio(Real(m_pViewport->getActualWidth()) / Real(m_pViewport->getActualHeight())); m_pViewport->setCamera(m_pCamera); unsigned long hWnd = 0; OIS::ParamList paramList; m_pRenderWnd->getCustomAttribute("WINDOW", &hWnd); paramList.insert(OIS::ParamList::value_type("WINDOW", Ogre::StringConverter::toString(hWnd))); m_pInputMgr = OIS::InputManager::createInputSystem(paramList); #if !defined(OGRE_IS_IOS) m_pKeyboard = static_cast<OIS::Keyboard*>(m_pInputMgr->createInputObject(OIS::OISKeyboard, true)); m_pMouse = static_cast<OIS::Mouse*>(m_pInputMgr->createInputObject(OIS::OISMouse, true)); m_pMouse->getMouseState().height = m_pRenderWnd->getHeight(); m_pMouse->getMouseState().width = m_pRenderWnd->getWidth(); #else m_pMouse = static_cast<OIS::MultiTouch*>(m_pInputMgr->createInputObject(OIS::OISMultiTouch, true)); #endif #if !defined(OGRE_IS_IOS) if(pKeyListener == 0) m_pKeyboard->setEventCallback(this); else m_pKeyboard->setEventCallback(pKeyListener); #endif if(pMouseListener == 0) m_pMouse->setEventCallback(this); else m_pMouse->setEventCallback(pMouseListener); Ogre::String secName, typeName, archName; Ogre::ConfigFile cf; cf.load(m_ResourcePath + "resources.cfg"); Ogre::ConfigFile::SectionIterator seci = cf.getSectionIterator(); while (seci.hasMoreElements()) { secName = seci.peekNextKey(); Ogre::ConfigFile::SettingsMultiMap *settings = seci.getNext(); Ogre::ConfigFile::SettingsMultiMap::iterator i; for (i = settings->begin(); i != settings->end(); ++i) { typeName = i->first; archName = i->second; #if OGRE_PLATFORM == OGRE_PLATFORM_APPLE || defined(OGRE_IS_IOS) // OS X does not set the working directory relative to the app, // In order to make things portable on OS X we need to provide // the loading with it's own bundle path location if (!Ogre::StringUtil::startsWith(archName, "/", false)) // only adjust relative dirs archName = Ogre::String(m_ResourcePath + archName); #endif Ogre::ResourceGroupManager::getSingleton().addResourceLocation(archName, typeName, secName); } } Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(5); Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups(); m_pTimer = OGRE_NEW Ogre::Timer(); m_pTimer->reset(); m_pTrayMgr = new OgreBites::SdkTrayManager("TrayMgr", m_pRenderWnd, m_pMouse, this); m_pTrayMgr->showFrameStats(OgreBites::TL_BOTTOMLEFT); m_pTrayMgr->showLogo(OgreBites::TL_BOTTOMRIGHT); m_pTrayMgr->hideCursor(); m_pRenderWnd->setActive(true); return true; } OgreFramework::~OgreFramework() { if(m_pInputMgr) OIS::InputManager::destroyInputSystem(m_pInputMgr); if(m_pTrayMgr) delete m_pTrayMgr; #ifdef OGRE_STATIC_LIB m_StaticPluginLoader.unload(); #endif if(m_pRoot) delete m_pRoot; } bool OgreFramework::keyPressed(const OIS::KeyEvent &keyEventRef) { #if !defined(OGRE_IS_IOS) if(m_pKeyboard->isKeyDown(OIS::KC_ESCAPE)) { m_bShutDownOgre = true; return true; } if(m_pKeyboard->isKeyDown(OIS::KC_SYSRQ)) { m_pRenderWnd->writeContentsToTimestampedFile("BOF_Screenshot_", ".png"); return true; } if(m_pKeyboard->isKeyDown(OIS::KC_M)) { static int mode = 0; if(mode == 2) { m_pCamera->setPolygonMode(PM_SOLID); mode = 0; } else if(mode == 0) { m_pCamera->setPolygonMode(PM_WIREFRAME); mode = 1; } else if(mode == 1) { m_pCamera->setPolygonMode(PM_POINTS); mode = 2; } } if(m_pKeyboard->isKeyDown(OIS::KC_O)) { if(m_pTrayMgr->isLogoVisible()) { m_pTrayMgr->hideLogo(); m_pTrayMgr->hideFrameStats(); } else { m_pTrayMgr->showLogo(OgreBites::TL_BOTTOMRIGHT); m_pTrayMgr->showFrameStats(OgreBites::TL_BOTTOMLEFT); } } #endif return true; } bool OgreFramework::keyReleased(const OIS::KeyEvent &keyEventRef) { return true; } //||||||||||||||||||||||||||||||||||||||||||||||| #if defined(OGRE_IS_IOS) bool OgreFramework::touchMoved(const OIS::MultiTouchEvent &evt) { OIS::MultiTouchState state = evt.state; int origTransX = 0, origTransY = 0; #if !OGRE_NO_VIEWPORT_ORIENTATIONMODE switch(m_pCamera->getViewport()->getOrientationMode()) { case Ogre::OR_LANDSCAPELEFT: origTransX = state.X.rel; origTransY = state.Y.rel; state.X.rel = -origTransY; state.Y.rel = origTransX; break; case Ogre::OR_LANDSCAPERIGHT: origTransX = state.X.rel; origTransY = state.Y.rel; state.X.rel = origTransY; state.Y.rel = origTransX; break; // Portrait doesn't need any change case Ogre::OR_PORTRAIT: default: break; } #endif m_pCamera->yaw(Degree(state.X.rel * -0.1)); m_pCamera->pitch(Degree(state.Y.rel * -0.1)); return true; } //||||||||||||||||||||||||||||||||||||||||||||||| bool OgreFramework::touchPressed(const OIS:: MultiTouchEvent &evt) { #pragma unused(evt) return true; } //||||||||||||||||||||||||||||||||||||||||||||||| bool OgreFramework::touchReleased(const OIS:: MultiTouchEvent &evt) { #pragma unused(evt) return true; } bool OgreFramework::touchCancelled(const OIS:: MultiTouchEvent &evt) { #pragma unused(evt) return true; } #else bool OgreFramework::mouseMoved(const OIS::MouseEvent &evt) { m_pCamera->yaw(Degree(evt.state.X.rel * -0.1f)); m_pCamera->pitch(Degree(evt.state.Y.rel * -0.1f)); return true; } bool OgreFramework::mousePressed(const OIS::MouseEvent &evt, OIS::MouseButtonID id) { return true; } bool OgreFramework::mouseReleased(const OIS::MouseEvent &evt, OIS::MouseButtonID id) { return true; } #endif void OgreFramework::updateOgre(double timeSinceLastFrame) { m_MoveScale = m_MoveSpeed * (float)timeSinceLastFrame; m_RotScale = m_RotateSpeed * (float)timeSinceLastFrame; #if OGRE_VERSION >= 0x10800 m_pSceneMgr->setSkyBoxEnabled(true); #endif m_TranslateVector = Vector3::ZERO; getInput(); moveCamera(); m_FrameEvent.timeSinceLastFrame = timeSinceLastFrame; m_pTrayMgr->frameRenderingQueued(m_FrameEvent); } void OgreFramework::moveCamera() { #if !defined(OGRE_IS_IOS) if(m_pKeyboard->isKeyDown(OIS::KC_LSHIFT)) m_pCamera->moveRelative(m_TranslateVector); else #endif m_pCamera->moveRelative(m_TranslateVector / 10); } void OgreFramework::getInput() { #if !defined(OGRE_IS_IOS) if(m_pKeyboard->isKeyDown(OIS::KC_A)) m_TranslateVector.x = -m_MoveScale; if(m_pKeyboard->isKeyDown(OIS::KC_D)) m_TranslateVector.x = m_MoveScale; if(m_pKeyboard->isKeyDown(OIS::KC_W)) m_TranslateVector.z = -m_MoveScale; if(m_pKeyboard->isKeyDown(OIS::KC_S)) m_TranslateVector.z = m_MoveScale; #endif }
0
0.919389
1
0.919389
game-dev
MEDIA
0.555622
game-dev,desktop-app
0.964205
1
0.964205
reedlaw/ruby-mmo
1,027
engine.rb
#!/usr/bin/env ruby def require_dir(dir) Dir["#{dir}/*.rb"].each do |file| require File.join(File.dirname(__FILE__), file ) end end require_dir("engine") modules = [] ObjectSpace.each_object(Module) {|m| modules << m.name } require_dir("players") player_modules = [] ObjectSpace.each_object(Module) do |m| next unless m.class == Module player_modules << m.name unless modules.include?(m.name) end require_dir("monsters") game = Game.new player_modules.each do |m| constant = Object player = Player.new game.players << player p = PlayerProxy.new(player) p.extend constant.const_get(m) player.proxy = p game.proxies << p end # Spawn 2 rats for each player (game.players.count * 2).times do monster = Monster.new game.players << monster r = PlayerProxy.new(monster) r.extend Rat monster.proxy = r game.proxies << r end if ARGV.size > 1 and ARGV[0] == "-r" and ARGV[1] =~ /^[1-9]\d*$/ ARGV.shift rount_count = ARGV.shift.to_i else rount_count = 100 end game.round(rount_count)
0
0.699084
1
0.699084
game-dev
MEDIA
0.844147
game-dev
0.80254
1
0.80254
LoganSMiller/AI-Refactored-Client
9,670
AI/Optimization/BotOwnerGroupOptimization.cs
// <auto-generated> // AI-Refactored: BotOwnerGroupOptimization.cs (Ultimate Beyond Diamond – Ultra-Realism Squad Pass, June 2025) // All squad optimization is bulletproof, squad-personality blended, multiplayer/headless safe, fully humanized. // Maximum psychology, casualty/contagion, squad trust, confidence/jitter, suppression, and vision blending. // Zero alloc in hot path. No dev/debug log calls, ever. MIT License. // </auto-generated> namespace AIRefactored.AI.Optimization { using System; using System.Collections.Generic; using AIRefactored.AI.Core; using AIRefactored.Core; using AIRefactored.Runtime; using BepInEx.Logging; using EFT; using UnityEngine; /// <summary> /// Applies squad-wide, personality-synchronized optimization to AIRefactored bots. /// Deep squad/group psychology, dynamic confidence/casualty/contagion, vision/trust blending, /// and full panic/suppression integration. Multiplayer/headless safe, bulletproof, zero-alloc. /// </summary> public sealed class BotOwnerGroupOptimization { #region Static Fields private static readonly ManualLogSource Logger = Plugin.LoggerInstance; #endregion #region Public Methods /// <summary> /// Optimizes squad AI for all valid bots in the group. /// Blends group/individual traits, adapts to squad size/casualty, panic/suppression state, /// and never breaks immersion. Zero alloc in hot path; bulletproof error isolation. /// </summary> /// <param name="botOwners">Pooled squad list (TempListPool enforced externally).</param> public void OptimizeGroupAI(List<BotOwner> botOwners) { if (botOwners == null || botOwners.Count == 0) return; int aliveCount = 0; float sumCohesion = 0f, sumAggression = 0f, sumAwareness = 0f; float sumSuppression = 0f, sumPanic = 0f; // Phase 1: Gather full group averages (personality, cohesion, aggression, suppression/panic) for (int i = 0, count = botOwners.Count; i < count; i++) { BotOwner bot = null; try { bot = botOwners[i]; if (bot == null || bot.IsDead) continue; var profile = bot.Profile; if (profile == null || string.IsNullOrEmpty(profile.Id)) continue; var personality = BotRegistry.Get(profile.Id); if (personality == null) continue; sumCohesion += Mathf.Clamp01(personality.Cohesion); sumAggression += Mathf.Clamp01(personality.AggressionLevel); sumAwareness += Mathf.Clamp01(personality.Awareness); // Suppression and panic integration (via BotComponentCache) var cache = BotComponentCacheRegistry.TryGetExisting(bot); if (cache?.Suppression != null && cache.Suppression.IsSuppressed()) sumSuppression += 1f; if (cache?.PanicHandler != null && cache.PanicHandler.IsPanicking) sumPanic += 1f; aliveCount++; } catch { } } if (aliveCount == 0) return; float groupCohesion = sumCohesion / aliveCount; float groupAggression = sumAggression / aliveCount; float groupAwareness = sumAwareness / aliveCount; float suppressionRatio = sumSuppression / aliveCount; float panicRatio = sumPanic / aliveCount; int groupTotal = botOwners.Count; // Phase 2: Blend squad traits, apply deep psychology and panic/suppression modifiers (zero-alloc, bulletproof) for (int i = 0; i < groupTotal; i++) { BotOwner bot = null; try { bot = botOwners[i]; if (bot == null || bot.IsDead) continue; var player = bot.GetPlayer; if (player == null || !player.IsAI || player.IsYourPlayer) continue; var profile = bot.Profile; if (profile == null || string.IsNullOrEmpty(profile.Id)) continue; BotSettingsComponents settings = null; try { settings = bot.Settings != null ? bot.Settings.FileSettings : null; } catch { } if (settings == null || settings.Mind == null) continue; var mind = settings.Mind; var personality = BotRegistry.Get(profile.Id); if (personality == null) continue; var cache = BotComponentCacheRegistry.TryGetExisting(bot); ApplyModifiers( bot, personality, mind, groupCohesion, groupAggression, groupAwareness, suppressionRatio, panicRatio, aliveCount, groupTotal, cache ); } catch (Exception ex) { // Never spam logs, only critical error. Logger.LogWarning("[GroupOpt] OptimizeGroupAI: Exception at bot index " + i + ": " + ex.Message); } } } #endregion #region Private Methods /// <summary> /// Applies squad/individual blending and deep group psychology. All output is error-guarded and zero-alloc. /// </summary> private static void ApplyModifiers( BotOwner bot, BotPersonalityProfile personality, BotGlobalsMindSettings mind, float groupCohesion, float groupAggression, float groupAwareness, float suppressionRatio, float panicRatio, int groupAlive, int groupTotal, BotComponentCache cache ) { try { // Blend individual toward group mean (EFT-like: 40% group, 60% self) float blendedCohesion = Mathf.Lerp(personality.Cohesion, groupCohesion, 0.40f); float blendedAggression = Mathf.Lerp(personality.AggressionLevel, groupAggression, 0.40f); float blendedAwareness = Mathf.Lerp(personality.Awareness, groupAwareness, 0.35f); // Squad size: larger squads cautious, aggression/casualty spike for losses float squadScale = Mathf.Clamp01(groupTotal / 4f); float cohesionMod = 1f - blendedCohesion * 0.6f * squadScale; float aggressionMod = blendedAggression * 0.21f + groupAggression * 0.16f; float awarenessMod = Mathf.Clamp01(blendedAwareness); // Trust: high cohesion shrinks vision range, increases group callout confidence mind.DIST_TO_FOUND_SQRT = Mathf.Lerp(420f, 720f, cohesionMod); // Casualty/contagion: squad panic, aggression spikes as team dies or panics float casualtyPenalty = groupTotal > 1 ? (1f - (float)groupAlive / groupTotal) : 0f; float panicBonus = Mathf.Clamp(panicRatio * 0.43f + suppressionRatio * 0.29f, 0f, 0.8f); mind.FRIEND_AGR_KILL = Mathf.Clamp(mind.FRIEND_AGR_KILL + aggressionMod + casualtyPenalty * 0.51f + panicBonus, 0f, 1f); // Vision cone: narrows for cohesive squads, widens if scattered/panicked/suppressed float baseLook = 28f - (blendedCohesion * 11.5f) + (1f - groupCohesion) * 8f; if (panicRatio > 0.2f || suppressionRatio > 0.18f) baseLook += 5.5f * (panicRatio + suppressionRatio); mind.ENEMY_LOOK_AT_ME_ANG = Mathf.Clamp(baseLook, 5f, 43f); // Alertness/jitter: more twitchy if group scattered or most bots are dead/panicked float alertMod = (1f - groupCohesion) + (groupAlive <= 2 ? 0.38f : 0f) + panicBonus; mind.MIN_DAMAGE_SCARE = Mathf.Lerp(19f, 6f, alertMod); // Confidence/fear: aggressive group can shrink enemy vision range (mirrors EFT AI confidence code) if (blendedAggression > 0.66f && groupCohesion > 0.55f) mind.DIST_TO_FOUND_SQRT *= 0.96f; // Suppression/panic can cut vision and widen error window if (panicRatio > 0.33f || suppressionRatio > 0.28f) mind.DIST_TO_FOUND_SQRT *= 0.95f; // Final bulletproof clamp (EFT-like) mind.DIST_TO_FOUND_SQRT = Mathf.Clamp(mind.DIST_TO_FOUND_SQRT, 110f, 900f); mind.ENEMY_LOOK_AT_ME_ANG = Mathf.Clamp(mind.ENEMY_LOOK_AT_ME_ANG, 3.0f, 50f); mind.MIN_DAMAGE_SCARE = Mathf.Clamp(mind.MIN_DAMAGE_SCARE, 2.2f, 32f); // No disables, never throws } catch (Exception ex) { Logger.LogWarning("[GroupOpt] ApplyModifiers: Exception for bot " + (bot?.Profile?.Info?.Nickname ?? "Unknown") + ": " + ex.Message); } } #endregion } }
0
0.892852
1
0.892852
game-dev
MEDIA
0.970172
game-dev
0.679707
1
0.679707
away3d/awayphysics-core-fp11
7,381
Bullet/BulletCollision/NarrowPhaseCollision/btContinuousConvexCollision.cpp
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "btContinuousConvexCollision.h" #include "BulletCollision/CollisionShapes/btConvexShape.h" #include "BulletCollision/NarrowPhaseCollision/btSimplexSolverInterface.h" #include "LinearMath/btTransformUtil.h" #include "BulletCollision/CollisionShapes/btSphereShape.h" #include "btGjkPairDetector.h" #include "btPointCollector.h" #include "BulletCollision/CollisionShapes/btStaticPlaneShape.h" btContinuousConvexCollision::btContinuousConvexCollision ( const btConvexShape* convexA,const btConvexShape* convexB,btSimplexSolverInterface* simplexSolver, btConvexPenetrationDepthSolver* penetrationDepthSolver) :m_simplexSolver(simplexSolver), m_penetrationDepthSolver(penetrationDepthSolver), m_convexA(convexA),m_convexB1(convexB),m_planeShape(0) { } btContinuousConvexCollision::btContinuousConvexCollision( const btConvexShape* convexA,const btStaticPlaneShape* plane) :m_simplexSolver(0), m_penetrationDepthSolver(0), m_convexA(convexA),m_convexB1(0),m_planeShape(plane) { } /// This maximum should not be necessary. It allows for untested/degenerate cases in production code. /// You don't want your game ever to lock-up. #define MAX_ITERATIONS 64 void btContinuousConvexCollision::computeClosestPoints( const btTransform& transA, const btTransform& transB,btPointCollector& pointCollector) { if (m_convexB1) { m_simplexSolver->reset(); btGjkPairDetector gjk(m_convexA,m_convexB1,m_convexA->getShapeType(),m_convexB1->getShapeType(),m_convexA->getMargin(),m_convexB1->getMargin(),m_simplexSolver,m_penetrationDepthSolver); btGjkPairDetector::ClosestPointInput input; input.m_transformA = transA; input.m_transformB = transB; gjk.getClosestPoints(input,pointCollector,0); } else { //convex versus plane const btConvexShape* convexShape = m_convexA; const btStaticPlaneShape* planeShape = m_planeShape; const btVector3& planeNormal = planeShape->getPlaneNormal(); const btScalar& planeConstant = planeShape->getPlaneConstant(); btTransform convexWorldTransform = transA; btTransform convexInPlaneTrans; convexInPlaneTrans= transB.inverse() * convexWorldTransform; btTransform planeInConvex; planeInConvex= convexWorldTransform.inverse() * transB; btVector3 vtx = convexShape->localGetSupportingVertex(planeInConvex.getBasis()*-planeNormal); btVector3 vtxInPlane = convexInPlaneTrans(vtx); btScalar distance = (planeNormal.dot(vtxInPlane) - planeConstant); btVector3 vtxInPlaneProjected = vtxInPlane - distance*planeNormal; btVector3 vtxInPlaneWorld = transB * vtxInPlaneProjected; btVector3 normalOnSurfaceB = transB.getBasis() * planeNormal; pointCollector.addContactPoint( normalOnSurfaceB, vtxInPlaneWorld, distance); } } bool btContinuousConvexCollision::calcTimeOfImpact( const btTransform& fromA, const btTransform& toA, const btTransform& fromB, const btTransform& toB, CastResult& result) { /// compute linear and angular velocity for this interval, to interpolate btVector3 linVelA,angVelA,linVelB,angVelB; btTransformUtil::calculateVelocity(fromA,toA,btScalar(1.),linVelA,angVelA); btTransformUtil::calculateVelocity(fromB,toB,btScalar(1.),linVelB,angVelB); btScalar boundingRadiusA = m_convexA->getAngularMotionDisc(); btScalar boundingRadiusB = m_convexB1?m_convexB1->getAngularMotionDisc():0.f; btScalar maxAngularProjectedVelocity = angVelA.length() * boundingRadiusA + angVelB.length() * boundingRadiusB; btVector3 relLinVel = (linVelB-linVelA); btScalar relLinVelocLength = (linVelB-linVelA).length(); if ((relLinVelocLength+maxAngularProjectedVelocity) == 0.f) return false; btScalar lambda = btScalar(0.); btVector3 v(1,0,0); int maxIter = MAX_ITERATIONS; btVector3 n; n.setValue(btScalar(0.),btScalar(0.),btScalar(0.)); bool hasResult = false; btVector3 c; btScalar lastLambda = lambda; //btScalar epsilon = btScalar(0.001); int numIter = 0; //first solution, using GJK btScalar radius = 0.001f; // result.drawCoordSystem(sphereTr); btPointCollector pointCollector1; { computeClosestPoints(fromA,fromB,pointCollector1); hasResult = pointCollector1.m_hasResult; c = pointCollector1.m_pointInWorld; } if (hasResult) { btScalar dist; dist = pointCollector1.m_distance + result.m_allowedPenetration; n = pointCollector1.m_normalOnBInWorld; btScalar projectedLinearVelocity = relLinVel.dot(n); if ((projectedLinearVelocity+ maxAngularProjectedVelocity)<=SIMD_EPSILON) return false; //not close enough while (dist > radius) { if (result.m_debugDrawer) { result.m_debugDrawer->drawSphere(c,0.2f,btVector3(1,1,1)); } btScalar dLambda = btScalar(0.); projectedLinearVelocity = relLinVel.dot(n); //don't report time of impact for motion away from the contact normal (or causes minor penetration) if ((projectedLinearVelocity+ maxAngularProjectedVelocity)<=SIMD_EPSILON) return false; dLambda = dist / (projectedLinearVelocity+ maxAngularProjectedVelocity); lambda = lambda + dLambda; if (lambda > btScalar(1.)) return false; if (lambda < btScalar(0.)) return false; //todo: next check with relative epsilon if (lambda <= lastLambda) { return false; //n.setValue(0,0,0); break; } lastLambda = lambda; //interpolate to next lambda btTransform interpolatedTransA,interpolatedTransB,relativeTrans; btTransformUtil::integrateTransform(fromA,linVelA,angVelA,lambda,interpolatedTransA); btTransformUtil::integrateTransform(fromB,linVelB,angVelB,lambda,interpolatedTransB); relativeTrans = interpolatedTransB.inverseTimes(interpolatedTransA); if (result.m_debugDrawer) { result.m_debugDrawer->drawSphere(interpolatedTransA.getOrigin(),0.2f,btVector3(1,0,0)); } result.DebugDraw( lambda ); btPointCollector pointCollector; computeClosestPoints(interpolatedTransA,interpolatedTransB,pointCollector); if (pointCollector.m_hasResult) { dist = pointCollector.m_distance+result.m_allowedPenetration; c = pointCollector.m_pointInWorld; n = pointCollector.m_normalOnBInWorld; } else { result.reportFailure(-1, numIter); return false; } numIter++; if (numIter > maxIter) { result.reportFailure(-2, numIter); return false; } } result.m_fraction = lambda; result.m_normal = n; result.m_hitPoint = c; return true; } return false; }
0
0.92986
1
0.92986
game-dev
MEDIA
0.993225
game-dev
0.992053
1
0.992053
stuartcaunt/isgl3d
4,172
isgl3dbullet/Isgl3dPhysicsWorld.mm
/* * iSGL3D: http://isgl3d.com * * Copyright (c) 2010-2012 Stuart Caunt * * 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. * */ #import "Isgl3dPhysicsWorld.h" #import "Isgl3dPhysicsObject3D.h" #import "Isgl3dMotionState.h" #import "btBulletDynamicsCommon.h" @implementation Isgl3dPhysicsWorld + (id)physicsWorld { return [[[self alloc] init] autorelease]; } - (id)init { if ((self = [super init])) { _lastStepTime = [[NSDate alloc] init]; _physicsObjects = [[NSMutableArray alloc] init]; } return self; } - (void)dealloc { [_lastStepTime release]; [_physicsObjects release]; [super dealloc]; } - (void)setDiscreteDynamicsWorld:(btDiscreteDynamicsWorld *)discreteDynamicsWorld { _discreteDynamicsWorld = discreteDynamicsWorld; } - (void)addPhysicsObject:(Isgl3dPhysicsObject3D *)physicsObject { // Add collision object to dynamics world _discreteDynamicsWorld->addRigidBody(physicsObject.rigidBody); // Add to physics list [_physicsObjects addObject:physicsObject]; } - (void)removePhysicsObject:(Isgl3dPhysicsObject3D *)physicsObject { // Remove from render list [physicsObject.node removeFromParent]; // Remove collision object from dynamics world _discreteDynamicsWorld->removeRigidBody(physicsObject.rigidBody); // Remove from physics list [_physicsObjects removeObject:physicsObject]; } - (void)clearAll { [super clearAll]; for (Isgl3dPhysicsObject3D * physicsObject in _physicsObjects) { _discreteDynamicsWorld->removeRigidBody(physicsObject.rigidBody); } [_physicsObjects removeAllObjects]; } - (void)updateWorldTransformation:(Isgl3dMatrix4 *)parentTransformation { // Get time since last step NSDate * currentTime = [[NSDate alloc] init]; NSTimeInterval timeInterval = [currentTime timeIntervalSinceDate:_lastStepTime]; // float optimalInterval = 1. / 60.; // if (timeInterval > optimalInterval) { // timeInterval = optimalInterval; // } // Update the simulation _discreteDynamicsWorld->stepSimulation(timeInterval, 2); [_lastStepTime release]; _lastStepTime = currentTime; //NSLog(@"N objects = %i", [_physicsObjects count]); // Update all global matrices [super updateWorldTransformation:parentTransformation]; } - (void)setGravity:(float)x y:(float)y z:(float)z { _discreteDynamicsWorld->setGravity(btVector3(x, y, z)); } - (Isgl3dPhysicsObject3D *) createPhysicsObject:(Isgl3dNode *)node shape:(btCollisionShape *)shape mass:(float)mass restitution:(float)restitution { // Create a motion state for the object Isgl3dMotionState * motionState = new Isgl3dMotionState(node); // Create a rigid body btVector3 localInertia(0, 0, 0); shape->calculateLocalInertia(mass, localInertia); btRigidBody * rigidBody = new btRigidBody(mass, motionState, shape, localInertia); rigidBody->setRestitution(restitution); rigidBody->setActivationState(DISABLE_DEACTIVATION); // Create a physics object and add it to the physics world Isgl3dPhysicsObject3D * physicsObject = [[Isgl3dPhysicsObject3D alloc] initWithNode:node andRigidBody:rigidBody]; [self addPhysicsObject:physicsObject]; return [physicsObject autorelease]; } @end
0
0.617844
1
0.617844
game-dev
MEDIA
0.833907
game-dev
0.752025
1
0.752025
ComfyFactory/ComfyFactorio
4,690
modules/mineable_wreckage_yields_ores.lua
local Event = require 'utils.event' local max_spill = 40 local math_random = math.random local math_floor = math.floor local math_sqrt = math.sqrt local insert = table.insert local scrap_yeild = { ['mineable-wreckage'] = 1 } local weights = { { 'iron-ore', 25 }, { 'copper-ore', 17 }, { 'coal', 13 }, { 'stone', 10 }, { 'uranium-ore', 2 } } local particles = { ['iron-ore'] = 'iron-ore-particle', ['copper-ore'] = 'copper-ore-particle', ['uranium-ore'] = 'coal-particle', ['coal'] = 'coal-particle', ['stone'] = 'stone-particle' } local ore_raffle = {} for _, t in pairs(weights) do for _ = 1, t[2], 1 do insert(ore_raffle, t[1]) end end local function create_particles(surface, name, position, amount, cause_position) local direction_mod = (-100 + math_random(0, 200)) * 0.0004 local direction_mod_2 = (-100 + math_random(0, 200)) * 0.0004 if cause_position then direction_mod = (cause_position.x - position.x) * 0.025 direction_mod_2 = (cause_position.y - position.y) * 0.025 end for i = 1, amount, 1 do local m = math_random(4, 10) local m2 = m * 0.005 surface.create_entity( { name = name, position = position, frame_speed = 1, vertical_speed = 0.130, height = 0, movement = { (m2 - (math_random(0, m) * 0.01)) + direction_mod, (m2 - (math_random(0, m) * 0.01)) + direction_mod_2 } } ) end end local function get_amount(entity) local distance_to_center = math_floor(math_sqrt(entity.position.x ^ 2 + entity.position.y ^ 2)) local distance_modifier = 0.25 local base_amount = 35 local maximum_amount = 100 if storage.rocks_yield_ore_distance_modifier then distance_modifier = storage.rocks_yield_ore_distance_modifier end if storage.rocks_yield_ore_base_amount then base_amount = storage.rocks_yield_ore_base_amount end if storage.rocks_yield_ore_maximum_amount then maximum_amount = storage.rocks_yield_ore_maximum_amount end local amount = base_amount + (distance_to_center * distance_modifier) if amount > maximum_amount then amount = maximum_amount end local m = (70 + math_random(0, 60)) * 0.01 amount = math_floor(amount * scrap_yeild[entity.name] * m) if amount < 1 then amount = 1 end return amount end local function on_player_mined_entity(event) local entity = event.entity if not entity.valid then return end if not scrap_yeild[entity.name] then return end event.buffer.clear() local ore = ore_raffle[math_random(1, #ore_raffle)] local player = game.players[event.player_index] local count = get_amount(entity) local position = { x = entity.position.x, y = entity.position.y } player.surface.create_entity({ name = 'flying-text', position = position, text = '+' .. count .. ' [img=item/' .. ore .. ']', color = { r = 200, g = 160, b = 30 } }) create_particles(player.surface, particles[ore], position, 64, { x = player.position.x, y = player.position.y }) --entity.destroy() if count > max_spill then player.surface.spill_item_stack(position, { name = ore, count = max_spill }, true) count = count - max_spill local inserted_count = player.insert({ name = ore, count = count }) count = count - inserted_count if count > 0 then player.surface.spill_item_stack(position, { name = ore, count = count }, true) end else player.surface.spill_item_stack(position, { name = ore, count = count }, true) end end local function on_entity_died(event) local entity = event.entity if not entity.valid then return end if not scrap_yeild[entity.name] then return end local surface = entity.surface local ore = ore_raffle[math_random(1, #ore_raffle)] local pos = { entity.position.x, entity.position.y } create_particles(surface, particles[ore], pos, 16, false) if event.cause then if event.cause.valid then if event.cause.force.index == 2 or event.cause.force.index == 3 then entity.destroy() return end end end entity.destroy() surface.spill_item_stack(pos, { name = ore, count = math_random(8, 12) }, true) end Event.add(defines.events.on_entity_died, on_entity_died) Event.add(defines.events.on_player_mined_entity, on_player_mined_entity)
0
0.857493
1
0.857493
game-dev
MEDIA
0.997202
game-dev
0.920493
1
0.920493
Nextpeer/Nextpeer-UFORUN
6,779
cocos2d-x-2.2/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UISliderTest/UISliderTest.cpp
#include "UISliderTest.h" // UISliderTest UISliderTest::UISliderTest() : m_pDisplayValueLabel(NULL) { } UISliderTest::~UISliderTest() { } /*===*/ bool UISliderTest::init() { if (UIScene::init()) { CCSize widgetSize = m_pWidget->getSize(); // Add a label in which the slider alert will be displayed m_pDisplayValueLabel = UILabel::create(); m_pDisplayValueLabel->setText("Move the slider thumb"); m_pDisplayValueLabel->setFontName("Marker Felt"); m_pDisplayValueLabel->setFontSize(32); m_pDisplayValueLabel->setAnchorPoint(ccp(0.5f, -1)); m_pDisplayValueLabel->setPosition(ccp(widgetSize.width / 2.0f, widgetSize.height / 2.0f)); m_pUiLayer->addWidget(m_pDisplayValueLabel); // Add the alert UILabel *alert = UILabel::create(); alert->setText("Slider"); alert->setFontName("Marker Felt"); alert->setFontSize(30); alert->setColor(ccc3(159, 168, 176)); alert->setPosition(ccp(widgetSize.width / 2.0f, widgetSize.height / 2.0f - alert->getSize().height * 1.75)); m_pUiLayer->addWidget(alert); // Create the slider UISlider* slider = UISlider::create(); slider->setTouchEnabled(true); slider->loadBarTexture("cocosui/sliderTrack.png"); slider->loadSlidBallTextures("cocosui/sliderThumb.png", "cocosui/sliderThumb.png", ""); slider->loadProgressBarTexture("cocosui/sliderProgress.png"); slider->setPosition(ccp(widgetSize.width / 2.0f, widgetSize.height / 2.0f)); // slider->setPosition(ccp(widgetSize.width / 2.0f, widgetSize.height / 2.0f + slider->getSize().height * 2)); slider->addEventListenerSlider(this, sliderpercentchangedselector(UISliderTest::sliderEvent)); m_pUiLayer->addWidget(slider); /* // Create the slider that set allow min progress and allow max progress UISlider* sliderAllow = UISlider::create(); //===// // sliderAllow->setMinAllowPercent(20); // sliderAllow->setMaxAllowPercent(80); // sliderAllow->setTouchEnabled(true); sliderAllow->loadBarTexture("cocosui/sliderTrack.png"); sliderAllow->loadSlidBallTextures("cocosui/sliderThumb.png", "cocosui/sliderThumb.png", ""); sliderAllow->loadProgressBarTexture("cocosui/sliderProgress.png"); sliderAllow->setPosition(ccp(widgetSize.width / 2.0f, widgetSize.height / 2.0f - sliderAllow->getSize().height * 2)); sliderAllow->addEventListenerSlider(this, sliderpercentchangedselector(UISliderTest::sliderEvent)); m_pUiLayer->addWidget(sliderAllow); */ return true; } return false; } /*=*/ void UISliderTest::sliderEvent(CCObject *pSender, SliderEventType type) { switch (type) { case SLIDER_PERCENTCHANGED: { UISlider* slider = dynamic_cast<UISlider*>(pSender); int percent = slider->getPercent(); m_pDisplayValueLabel->setText(CCString::createWithFormat("Percent %d", percent)->getCString()); } break; default: break; } } // UISliderTest_Scale9 UISliderTest_Scale9::UISliderTest_Scale9() : m_pDisplayValueLabel(NULL) { } UISliderTest_Scale9::~UISliderTest_Scale9() { } /*===*/ bool UISliderTest_Scale9::init() { if (UIScene::init()) { CCSize widgetSize = m_pWidget->getSize(); // Add a label in which the slider alert will be displayed m_pDisplayValueLabel = UILabel::create(); m_pDisplayValueLabel->setText("Move the slider thumb"); m_pDisplayValueLabel->setFontName("Marker Felt"); m_pDisplayValueLabel->setFontSize(32); m_pDisplayValueLabel->setAnchorPoint(ccp(0.5f, -1)); m_pDisplayValueLabel->setPosition(ccp(widgetSize.width / 2.0f, widgetSize.height / 2.0f)); m_pUiLayer->addWidget(m_pDisplayValueLabel); // Add the alert UILabel *alert = UILabel::create(); alert->setText("Slider scale9 render"); alert->setFontName("Marker Felt"); alert->setFontSize(30); alert->setColor(ccc3(159, 168, 176)); alert->setPosition(ccp(widgetSize.width / 2.0f, widgetSize.height / 2.0f - alert->getSize().height * 1.75)); m_pUiLayer->addWidget(alert); // Create the slider UISlider* slider = UISlider::create(); slider->setTouchEnabled(true); slider->loadBarTexture("cocosui/sliderTrack2.png"); slider->loadSlidBallTextures("cocosui/sliderThumb.png", "cocosui/sliderThumb.png", ""); slider->loadProgressBarTexture("cocosui/slider_bar_active_9patch.png"); slider->setScale9Enabled(true); slider->setCapInsets(CCRectMake(0, 0, 0, 0)); slider->setSize(CCSizeMake(250, 19)); slider->setPosition(ccp(widgetSize.width / 2.0f, widgetSize.height / 2.0f)); // slider->setPosition(ccp(widgetSize.width / 2.0f, widgetSize.height / 2.0f + slider->getSize().height * 2)); slider->addEventListenerSlider(this, sliderpercentchangedselector(UISliderTest_Scale9::sliderEvent)); m_pUiLayer->addWidget(slider); /* // Create the slider that set allow min progress and allow max progress UISlider* sliderAllow = UISlider::create(); //===// // sliderAllow->setMinAllowPercent(20); // sliderAllow->setMaxAllowPercent(80); // sliderAllow->setTouchEnabled(true); sliderAllow->loadBarTexture("cocosui/sliderTrack2.png"); sliderAllow->loadSlidBallTextures("cocosui/sliderThumb.png", "cocosui/sliderThumb.png", ""); sliderAllow->loadProgressBarTexture("cocosui/slider_bar_active_9patch.png"); sliderAllow->setScale9Enabled(true); sliderAllow->setCapInsets(CCRectMake(0, 0, 0, 0)); sliderAllow->setSize(CCSizeMake(250, 10)); sliderAllow->setPosition(ccp(widgetSize.width / 2.0f, widgetSize.height / 2.0f - slider->getSize().height * 2)); sliderAllow->addEventListenerSlider(this, sliderpercentchangedselector(UISliderTest_Scale9::sliderEvent)); m_pUiLayer->addWidget(sliderAllow); */ return true; } return false; } /*=*/ void UISliderTest_Scale9::sliderEvent(CCObject *pSender, SliderEventType type) { switch (type) { case SLIDER_PERCENTCHANGED: { UISlider* slider = dynamic_cast<UISlider*>(pSender); int percent = slider->getPercent(); m_pDisplayValueLabel->setText(CCString::createWithFormat("Percent %d", percent)->getCString()); } break; default: break; } }
0
0.820256
1
0.820256
game-dev
MEDIA
0.571899
game-dev
0.831956
1
0.831956
icza/screp
3,029
rep/mapdata.go
// This file contains the types describing the map data. package rep import "github.com/icza/screp/rep/repcore" // MapData describes the map and objects on it. type MapData struct { // Version of the map. // 0x2f: StarCraft beta // 0x3b: 1.00-1.03 StarCraft and above ("hybrid") // 0x3f: 1.04 StarCraft and above ("hybrid") // 0x40: StarCraft Remastered // 0xcd: Brood War // 0xce: Brood War Remastered Version uint16 // TileSet defines the tile set used on the map. TileSet *repcore.TileSet TileSetMissing bool `json:"tileSetMissing,omitempty"` // Scenario name Name string // Scenario description Description string // PlayerOwners defines the player types (player owners). PlayerOwners []*repcore.PlayerOwner // PlayerSides defines the player sides (player races). PlayerSides []*repcore.PlayerSide // Tiles is the tile data of the map (within the tile set): width x height elements. // 1 Tile is 32 units (pixel) Tiles []uint16 `json:",omitempty"` // Mineral field locations on the map MineralFields []Resource `json:",omitempty"` // Geyser locations on the map Geysers []Resource `json:",omitempty"` // StartLocations on the map StartLocations []StartLocation // MapGraphics holds data for map image rendering. MapGraphics *MapGraphics `json:",omitempty"` // Debug holds optional debug info. Debug *MapDataDebug `json:"-"` } // MaxHumanPlayers returns the max number of human players on the map. func (md *MapData) MaxHumanPlayers() (count int) { for _, owner := range md.PlayerOwners { if owner == repcore.PlayerOwnerHumanOpenSlot { count++ } } return } // Resource describes a resource (mineral field of vespene geyser). type Resource struct { // Location of the resource repcore.Point // Amount of the resource Amount uint32 } // StartLocation describes a player start location on the map type StartLocation struct { repcore.Point // SlotID of the owner of this start location; // Belongs to the Player with matching Player.SlotID SlotID byte } // MapDataDebug holds debug info for the map data section. type MapDataDebug struct { // Data is the raw, uncompressed data of the section. Data []byte } // MapGraphics holds info usually required only for map image rendering. type MapGraphics struct { // PlacedUnits contains all placed units on the map. // This includes mineral fields, geysers and startlocations too. // This also includes unit sprites. PlacedUnits []*PlacedUnit // Sprites contains additional visual sprites on the map. Sprites []*Sprite } type PlacedUnit struct { repcore.Point // UnitID is the unit id. This value is used in repcmd.Unit.UnitID. UnitID uint16 // SlotID of the owner of this unit. // Belongs to the Player with matching Player.SlotID SlotID byte // ResourceAmount of if it's a resource ResourceAmount uint32 `json:",omitempty"` // Sprite tells if this unit is a sprite. Sprite bool `json:",omitempty"` } type Sprite struct { repcore.Point // SpriteID is the sprite id. SpriteID uint16 }
0
0.727732
1
0.727732
game-dev
MEDIA
0.97133
game-dev
0.637378
1
0.637378
gwaredd/unium
2,777
Assets/Unium/Core/UniumSocketRepeater.cs
// Copyright (c) 2017 Gwaredd Mountain, https://opensource.org/licenses/MIT #if !UNIUM_DISABLE && ( DEVELOPMENT_BUILD || UNITY_EDITOR || UNIUM_ENABLE ) using UnityEngine; namespace gw.unium { public partial class UniumSocket { //////////////////////////////////////////////////////////////////////////////////////////////////// // periodically repeats a request - this is useful for watching variables over time class Repeater { public string ID { get { return mRequest.ID; } } public bool IsFinished { get; private set; } //---------------------------------------------------------------------------------------------------- Route mRoute; RequestAdapterSocket mRequest; int mCount = 0; float mTimer = 0.0f; int mFrom = 0; int mTo = 0; float mFreq = 1.0f; public Repeater( Route route, RequestAdapterSocket req ) { mRoute = route; mRequest = req; var repeat = req.Message.repeat; mFrom = repeat.skip; mTo = repeat.samples != int.MaxValue ? mFrom + repeat.samples : int.MaxValue; mFreq = repeat.freq; mRequest.Info( "repeating" ); } //---------------------------------------------------------------------------------------------------- public void Cancel() { mRequest.Info( "stopped" ); IsFinished = true; } //---------------------------------------------------------------------------------------------------- public void Tick() { if( IsFinished ) { return; } // update timer mTimer += Time.deltaTime; if( mTimer < mFreq ) { return; } mTimer = 0.0f; // skip start? if( mCount++ < mFrom ) { return; } // dispatch route mRoute.Dispatch( mRequest ); if( mRequest.Rejected ) { mRequest.Info( "cancelled" ); IsFinished = true; } // finished? else if( mCount == mTo ) { IsFinished = true; mRequest.Info( "finished" ); } } } } } #endif
0
0.709091
1
0.709091
game-dev
MEDIA
0.817033
game-dev
0.781988
1
0.781988
ckosmic/g64
1,423
lua/entities/g64_wingcap.lua
AddCSLuaFile() ENT.Type = "anim" ENT.Base = "base_entity" ENT.Category = "G64" ENT.PrintName = "Wing Cap" ENT.Author = "ckosmic" ENT.Spawnable = false ENT.AdminSpawnable = true ENT.AdminOnly = false RegisterG64Entity(ENT, "g64_wingcap") function ENT:SpawnFunction(ply, tr, ClassName) if not tr.Hit then return end local SpawnPos = tr.HitPos + tr.HitNormal * 16 local ent = ents.Create(ClassName) ent:SetPos(SpawnPos) ent:Spawn() ent:Activate() return ent end function ENT:Initialize() self:SetModel( "models/player/items/humans/top_hat.mdl" ) self:SetColor( Color( 255, 255, 255 ) ) self:SetModelScale(2, 0) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid( SOLID_VPHYSICS ) self.Collected = false if SERVER then self:PhysicsInit( SOLID_VPHYSICS ) end self:PhysWake() end function ENT:Draw() self:DrawModel() end function ENT:Think() if CLIENT then local ply = LocalPlayer() local marioEnt = ply.MarioEnt if g64utils.WithinBounds(self:GetPos(), ply:GetNetworkOrigin(), 40) and self.Collected == false then if IsValid(ply.MarioEnt) and ply.IsMario == true and ply.MarioEnt.hasWingCap == false then ply.MarioEnt.EnableWingCap = true end g64utils.RemoveFromClient(self) self.Collected = true end end end list.Set("g64_entities", "g64_wingcap", { Category = "Caps", Name = "Wing Cap", Material = "materials/vgui/entities/g64_wingcap.png" })
0
0.775145
1
0.775145
game-dev
MEDIA
0.903698
game-dev
0.949044
1
0.949044
friflo/Friflo.Json.Fliox
2,325
Engine/src/Tests/ECS/GenericComponents.cs
using Friflo.Engine.ECS; // ReSharper disable ClassNeverInstantiated.Global namespace Tests.ECS { // --------------------- component field types ignored by serializer public struct GenericStruct<T> { public T value; } public class GenericClass<T> { public T value; } public interface IGenericInterface<T> { public T Value { get; set; } } // ------------------------------------------------------------------------------------------------------ // [Generic structs in components is not supported] https://github.com/friflo/Friflo.Json.Fliox/issues/45 // Fixed by commit: [Mapper - Ignore unsupported fields/properties in custom classes, structs and interfaces.] // https://github.com/friflo/Friflo.Json.Fliox/commit/12c4f88f26d86cffd014f00f823d152eede29d36 // Remarks: Unsupported fields/properties in custom classes, structs and interfaces are now ignored by mapper/serialization. // Fix published in: https://www.nuget.org/packages/Friflo.Json.Fliox/1.0.2 public struct ComponentWithGenerics : IComponent { public GenericStruct<int> genericStruct; public GenericClass<int> genericClass; public IGenericInterface<int> genericInterface; } // ------------------------------------------------------------------------------------------------------ // [Generic components and tags types are not supported and throw exception on usage. · Issue #53] // https://github.com/friflo/Friflo.Json.Fliox/issues/53 [GenericInstanceType("comp-int", typeof(int))] [GenericInstanceType("comp-string", typeof(string))] public struct GenericComponent<T> : IComponent { public T value; } [GenericInstanceType("comp-3", typeof(int), typeof(int), typeof(int))] public struct GenericComponent3<T1,T2,T3> : IComponent { public T1 value1; public T2 value2; public T3 value3; } // ReSharper disable UnusedTypeParameter [GenericInstanceType("tag-int", typeof(int))] [GenericInstanceType("tag-string", typeof(string))] public struct GenericTag<T> : ITag { } [GenericInstanceType("generic-tag2", typeof(int), typeof(bool))] public struct GenericTag2<T1, T2> : ITag { } [CodeCoverageTest] [GenericInstanceType("generic-tag3", typeof(int), typeof(int), typeof(int))] public struct GenericTag3<T1, T2, T3> : ITag { } }
0
0.82731
1
0.82731
game-dev
MEDIA
0.74472
game-dev
0.823461
1
0.823461
manisha-v/Number-Cruncher
8,079
Codes/Minor2d/Library/PackageCache/com.unity.2d.animation@3.2.11/Editor/SpriteLib/SpriteLibraryAssetInspector.cs
using UnityEditor.U2D.Animation; using UnityEditorInternal; using UnityEngine; using UnityEngine.Experimental.U2D.Animation; namespace UnityEditor.Experimental.U2D.Animation { [CustomEditor(typeof(SpriteLibraryAsset))] internal class SpriteLibraryAssetInspector : Editor { static class Style { public static GUIContent duplicateWarningText = EditorGUIUtility.TrTextContent("Duplicate name found or name hash clashes. Please use a different name"); public static GUIContent duplicateWarning = EditorGUIUtility.TrIconContent("console.warnicon.sml", duplicateWarningText.text); public static GUIContent nameLabel = new GUIContent(TextContent.label); public static int lineSpacing = 3; } private SerializedProperty m_Labels; private ReorderableList m_LabelReorderableList; private bool m_UpdateHash = false; private readonly float kElementHeight = EditorGUIUtility.singleLineHeight * 3; public void OnEnable() { m_Labels = serializedObject.FindProperty("m_Labels"); m_LabelReorderableList = new ReorderableList(serializedObject, m_Labels, true, false, true, true); SetupOrderList(); } public void OnDisable() { var sla = target as SpriteLibraryAsset; if (sla != null) sla.UpdateHashes(); } float GetElementHeight(int index) { var property = m_Labels.GetArrayElementAtIndex(index); var spriteListProp = property.FindPropertyRelative("m_CategoryList"); if (spriteListProp.isExpanded) return (spriteListProp.arraySize + 1) * (EditorGUIUtility.singleLineHeight + Style.lineSpacing) + kElementHeight; return kElementHeight; } void DrawElement(Rect rect, int index, bool selected, bool focused) { var property = m_Labels.GetArrayElementAtIndex(index); var catRect = new Rect(rect.x, rect.y, rect.width - kElementHeight, EditorGUIUtility.singleLineHeight); var vaRect = new Rect(rect.x, rect.y + EditorGUIUtility.singleLineHeight, rect.width - kElementHeight, EditorGUIUtility.singleLineHeight); var categoryProp = property.FindPropertyRelative("m_Name"); var spriteListProp = property.FindPropertyRelative("m_CategoryList"); EditorGUI.BeginChangeCheck(); var newCatName = EditorGUI.DelayedTextField(catRect, categoryProp.stringValue); if (EditorGUI.EndChangeCheck()) { newCatName = newCatName.Trim(); m_UpdateHash = true; if (categoryProp.stringValue != newCatName) { // Check if this nameLabel is already taken if (!IsNameInUsed(newCatName, m_Labels, "m_Name", 0)) categoryProp.stringValue = newCatName; else Debug.LogWarning(Style.duplicateWarningText.text); } } EditorGUI.PropertyField(vaRect, spriteListProp); if (spriteListProp.isExpanded) { EditorGUI.indentLevel++; var indentedRect = EditorGUI.IndentedRect(vaRect); var labelWidth = EditorGUIUtility.labelWidth; EditorGUIUtility.labelWidth = 40 + indentedRect.x - vaRect.x; indentedRect.y += EditorGUIUtility.singleLineHeight + Style.lineSpacing; var sizeRect = indentedRect; int size = EditorGUI.IntField(sizeRect, TextContent.size, spriteListProp.arraySize); if (size != spriteListProp.arraySize && size >= 0) spriteListProp.arraySize = size; indentedRect.y += EditorGUIUtility.singleLineHeight + Style.lineSpacing; DrawSpriteListProperty(indentedRect, spriteListProp); EditorGUIUtility.labelWidth = labelWidth; EditorGUI.indentLevel--; } } void DrawSpriteListProperty(Rect rect, SerializedProperty spriteListProp) { for (int i = 0; i < spriteListProp.arraySize; ++i) { var element = spriteListProp.GetArrayElementAtIndex(i); EditorGUI.BeginChangeCheck(); var oldName = element.FindPropertyRelative("m_Name").stringValue; var nameRect = new Rect(rect.x, rect.y, rect.width / 2, EditorGUIUtility.singleLineHeight); bool nameDuplicate = IsNameInUsed(oldName, spriteListProp, "m_Name", 1); if (nameDuplicate) { nameRect.width -= 20; } var newName = EditorGUI.DelayedTextField( nameRect, Style.nameLabel, oldName); if (nameDuplicate) { nameRect.x += nameRect.width; nameRect.width = 20; GUI.Label(nameRect, Style.duplicateWarning); } if (EditorGUI.EndChangeCheck()) { newName = newName.Trim(); element.FindPropertyRelative("m_Name").stringValue = newName; } EditorGUI.PropertyField(new Rect(rect.x + rect.width / 2 + 5, rect.y, rect.width / 2, EditorGUIUtility.singleLineHeight), element.FindPropertyRelative("m_Sprite")); rect.y += EditorGUIUtility.singleLineHeight + Style.lineSpacing; } } public override void OnInspectorGUI() { serializedObject.Update(); EditorGUI.BeginChangeCheck(); if (EditorGUI.EndChangeCheck()) SetupOrderList(); m_UpdateHash = false; m_LabelReorderableList.DoLayoutList(); serializedObject.ApplyModifiedProperties(); if (m_UpdateHash) (target as SpriteLibraryAsset).UpdateHashes(); } bool IsNameInUsed(string name, SerializedProperty property, string propertyField, int threshold) { int count = 0; var nameHash = SpriteLibraryAsset.GetStringHash(name); for (int i = 0; i < property.arraySize; ++i) { var sp = property.GetArrayElementAtIndex(i); var otherName = sp.FindPropertyRelative(propertyField).stringValue; var otherNameHash = SpriteLibraryAsset.GetStringHash(otherName); if (otherName == name || nameHash == otherNameHash) { count++; if (count > threshold) return true; } } return false; } void OnAddCallback(ReorderableList list) { var oldSize = m_Labels.arraySize; m_Labels.arraySize += 1; const string kNewCatName = "New Category"; string newCatName = kNewCatName; int catNameIncrement = 1; while (true) { if (IsNameInUsed(newCatName, m_Labels, "m_Name", 0)) newCatName = string.Format("{0} {1}", kNewCatName, catNameIncrement++); else break; } var sp = m_Labels.GetArrayElementAtIndex(oldSize); sp.FindPropertyRelative("m_Name").stringValue = newCatName; sp.FindPropertyRelative("m_Hash").intValue = SpriteLibraryAsset.GetStringHash(newCatName); } private void SetupOrderList() { m_LabelReorderableList.drawElementCallback = DrawElement; m_LabelReorderableList.elementHeight = kElementHeight; m_LabelReorderableList.elementHeightCallback = GetElementHeight; m_LabelReorderableList.onAddCallback = OnAddCallback; } } }
0
0.857867
1
0.857867
game-dev
MEDIA
0.927511
game-dev
0.988531
1
0.988531
tzaeschke/ode4j
1,510
core/src/main/java/org/ode4j/ode/internal/CollideConvexTrimesh.java
package org.ode4j.ode.internal; import java.util.Arrays; import org.ode4j.ode.DAABBC; import org.ode4j.ode.DColliderFn; import org.ode4j.ode.DContactGeomBuffer; import org.ode4j.ode.DGeom; import org.ode4j.ode.internal.CollisionLibccd.CollideConvexTrimeshTrianglesCCD; import org.ode4j.ode.internal.gimpact.GimDynArrayInt; import org.ode4j.ode.internal.gimpact.GimGeometry.aabb3f; import org.ode4j.ode.internal.gimpact.GimTrimesh; class CollideConvexTrimesh implements DColliderFn { @Override public int dColliderFn(DGeom o1, DGeom o2, int flags, DContactGeomBuffer contacts) { DxGimpact trimesh = (DxGimpact) o2; GimTrimesh ptrimesh = trimesh.m_collision_trimesh(); aabb3f test_aabb = new aabb3f(); DAABBC aabb = o1.getAABB(); test_aabb.set(aabb.getMin0(), aabb.getMax0(), aabb.getMin1(), aabb.getMax1(), aabb.getMin2(), aabb.getMax2()); GimDynArrayInt collision_result = GimDynArrayInt.GIM_CREATE_BOXQUERY_LIST(); ptrimesh.getAabbSet().gim_aabbset_box_collision(test_aabb, collision_result); int contactcount = 0; if (collision_result.size() != 0) { int[] boxesresult = Arrays.copyOf(collision_result.GIM_DYNARRAY_POINTER(), collision_result.size()); ptrimesh.gim_trimesh_locks_work_data(); CollideConvexTrimeshTrianglesCCD collideFn = new CollideConvexTrimeshTrianglesCCD(); contactcount = collideFn.collide(o1, o2, boxesresult, flags, contacts); ptrimesh.gim_trimesh_unlocks_work_data(); } collision_result.GIM_DYNARRAY_DESTROY(); return contactcount; } }
0
0.76657
1
0.76657
game-dev
MEDIA
0.408679
game-dev
0.716304
1
0.716304
UCRBrainGameCenter/BGC_Tools
1,373
DataStructures/Generic/Node.cs
using System.Collections.Generic; namespace BGC.DataStructures.Generic { /// <summary> /// Generic Node for generating tree structure /// /// @todo: adding some functions to make this easier to use would be ideal /// </summary> public struct Node<T> { public T Value; public List<Node<T>> Children; /// <summary>Return whether the node is a leaf</summary> public bool IsLeaf => Children.Count == 0; /// <summary>Returns whether the node is an internal node</summary> public bool IsInternalNode => !IsLeaf; /// <summary> /// Construct a node with no children /// </summary> public Node(T value) { Value = value; Children = new List<Node<T>>(); } /// <summary> /// Construct a node with a list of children /// @todo: Do we really want the node taking ownership of the passed-in list? /// </summary> public Node(T value, List<Node<T>> children) { Value = value; Children = children; } /// <summary> /// Construct a node with an array of children /// </summary> public Node(T value, Node<T>[] children) { Value = value; Children = new List<Node<T>>(children); } } }
0
0.784241
1
0.784241
game-dev
MEDIA
0.789675
game-dev
0.553578
1
0.553578
grpc/grpc
3,120
src/core/util/no_destruct.h
// Copyright 2022 gRPC authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GRPC_SRC_CORE_UTIL_NO_DESTRUCT_H #define GRPC_SRC_CORE_UTIL_NO_DESTRUCT_H #include <grpc/support/port_platform.h> #include <type_traits> #include <utility> #include "src/core/util/construct_destruct.h" namespace grpc_core { // NoDestruct<T> is a wrapper around an object of type T that: // - stores the value inline - no heap allocation // - is non-copyable // - is eagerly constructed (i.e. the constructor is called when NoDestruct is // constructed) // - *NEVER* calls ~T() // It's useful in cases where no ordering can be assumed between destructors of // objects that need to refer to each other - such as at program destruction // time. // Examples: // // globally available object: // static NoDestruct<Foo> g_foo(1, "foo", 2.0); // // used as: // g_foo->DoSomething(); // // singleton function: // Bar* BarSingleton() { // static NoDestruct<Bar> bar(1, "bar", 2.0); // return &*bar; // } // The globally available version is constructed at program startup, and the // singleton version is constructed at the first call to BarSingleton(). // Neither Foo nor Bar instance will be destructed. template <typename T> class NoDestruct { public: template <typename... Args> explicit NoDestruct(Args&&... args) { static_assert(std::is_trivially_destructible<NoDestruct<T>>::value, "NoDestruct must be trivially destructible"); Construct(reinterpret_cast<T*>(&space_), std::forward<Args>(args)...); } NoDestruct(const NoDestruct&) = delete; NoDestruct& operator=(const NoDestruct&) = delete; ~NoDestruct() = default; T* operator->() { return get(); } const T* operator->() const { return get(); } T& operator*() { return *get(); } const T& operator*() const { return *get(); } T* get() { return reinterpret_cast<T*>(&space_); } const T* get() const { return reinterpret_cast<const T*>(&space_); } private: alignas(T) char space_[sizeof(T)]; }; // Helper for when a program desires a single *process wide* instance of a // default constructed T to be always available. // The instance is constructed eagerly at program startup, so it's essentially // free to load the pointer to the instance. template <typename T> class NoDestructSingleton { public: static T* Get() { return &*value_; } private: NoDestructSingleton() = delete; ~NoDestructSingleton() = delete; static NoDestruct<T> value_; }; template <typename T> NoDestruct<T> NoDestructSingleton<T>::value_; } // namespace grpc_core #endif // GRPC_SRC_CORE_UTIL_NO_DESTRUCT_H
0
0.962258
1
0.962258
game-dev
MEDIA
0.160899
game-dev
0.838598
1
0.838598
CarbonMC-CN/Graphene
2,299
src/main/java/net/carbonmc/graphene/command/KillMobsCommand.java
package net.carbonmc.graphene.command; import com.mojang.brigadier.CommandDispatcher; import net.minecraft.commands.CommandSourceStack; import net.minecraft.commands.Commands; import net.minecraft.commands.arguments.EntityArgument; import net.minecraft.network.chat.Component; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.monster.Monster; import net.minecraft.world.entity.player.Player; import java.util.Collection; import java.util.function.Predicate; public class KillMobsCommand { public static void register(CommandDispatcher<CommandSourceStack> dispatcher) { dispatcher.register( Commands.literal("killmobs") .requires(source -> source.hasPermission(4)) // OP 4级权限 .executes(context -> killMobs(context.getSource(), context.getSource().getPlayerOrException())) .then(Commands.argument("targets", EntityArgument.players()) .executes(context -> killMobs(context.getSource(), EntityArgument.getPlayers(context, "targets"))) ) ); } private static int killMobs(CommandSourceStack source, Player player) { return killMobs(source, java.util.Collections.singleton(player)); } private static int killMobs(CommandSourceStack source, Collection<? extends Player> players) { int totalKilled = 0; for (Player player : players) { double range = 50.0; Predicate<Entity> isMonster = entity -> entity instanceof Monster && !entity.getType().equals(EntityType.ENDER_DRAGON); Collection<Entity> monsters = player.level().getEntities(player, player.getBoundingBox().inflate(range), isMonster); int killed = 0; for (Entity mob : monsters) { mob.discard(); killed++; } totalKilled += killed; if (killed > 0) { player.sendSystemMessage(Component.literal("清除了 " + killed + " 个怪物")); } else { player.sendSystemMessage(Component.literal("附近没有怪物")); } } return totalKilled; } }
0
0.881773
1
0.881773
game-dev
MEDIA
0.98152
game-dev
0.88107
1
0.88107
RobertSkalko/Age-of-Exile
1,955
src/main/java/com/robertx22/age_of_exile/uncommon/utilityclasses/ClientOnly.java
package com.robertx22.age_of_exile.uncommon.utilityclasses; import com.robertx22.age_of_exile.gui.screens.dungeon.DungeonInfoScreen; import com.robertx22.age_of_exile.uncommon.datasaving.Load; import net.minecraft.client.Minecraft; import net.minecraft.client.world.ClientWorld; import net.minecraft.entity.Entity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.ItemStack; import net.minecraft.util.SoundEvents; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import java.util.UUID; public class ClientOnly { public static int ticksSinceChatWasOpened = 0; public static void totemAnimWithItem(ItemStack stack) { Minecraft.getInstance().player.playSound(SoundEvents.TOTEM_USE, 1, 1); Minecraft.getInstance().gameRenderer.displayItemActivation(stack); } public static Entity getEntityByUUID(World world, UUID id) { if (world instanceof ClientWorld) { for (Entity entity : ((ClientWorld) world).entitiesForRendering()) { if (entity.getUUID() .equals(id)) { return entity; } } } return null; } public static PlayerEntity getPlayerById(UUID id) { try { return Minecraft.getInstance().level.getPlayerByUUID(id); } catch (Exception e) { } return null; } public static PlayerEntity getPlayer() { return Minecraft.getInstance().player; } public static void pressUseKey() { Minecraft.getInstance().options.keyUse.setDown(true); } public static void openMapsScreen(BlockPos pos) { Minecraft.getInstance() .setScreen(new DungeonInfoScreen(pos, Load.playerRPGData(Minecraft.getInstance().player).maps.dungeonData)); } public static void stopUseKey() { Minecraft.getInstance().options.keyUse.setDown(false); } }
0
0.714814
1
0.714814
game-dev
MEDIA
0.993042
game-dev
0.701996
1
0.701996
WayofTime/BloodMagic
2,725
src/main/java/wayoftime/bloodmagic/recipe/RecipeARCPotion.java
package wayoftime.bloodmagic.recipe; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Random; import net.minecraft.util.RandomSource; import org.apache.commons.lang3.tuple.Pair; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.effect.MobEffectInstance; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.alchemy.PotionUtils; import net.minecraft.world.item.crafting.Ingredient; import net.minecraft.world.item.crafting.RecipeSerializer; import net.minecraftforge.fluids.FluidStack; import wayoftime.bloodmagic.common.registries.BloodMagicRecipeSerializers; import wayoftime.bloodmagic.recipe.helper.FluidStackIngredient; public class RecipeARCPotion extends RecipeARC { public RecipeARCPotion(ResourceLocation id, Ingredient input, int inputSize, Ingredient arc_tool, FluidStackIngredient inputFluid, ItemStack output, List<Pair<ItemStack, Pair<Double, Double>>> addedItems, FluidStack outputFluid, boolean consumeIngredient) { super(id, input, inputSize, arc_tool, inputFluid, output, addedItems, outputFluid, consumeIngredient); } public List<ItemStack> getAllListedOutputs(ItemStack inputStack, ItemStack toolStack) { if (toolStack.isEmpty()) { return super.getAllListedOutputs(inputStack, toolStack); } List<ItemStack> list = new ArrayList<ItemStack>(); Collection<MobEffectInstance> collection = PotionUtils.getCustomEffects(toolStack); ItemStack outputCopyStack = output.copy(); PotionUtils.setCustomEffects(outputCopyStack, collection); list.add(outputCopyStack); for (Pair<ItemStack, Pair<Double, Double>> pair : addedItems) { list.add(pair.getLeft().copy()); } return list; } public List<ItemStack> getAllOutputs(RandomSource rand, ItemStack inputStack, ItemStack toolStack, double secondaryBonus) { if (toolStack.isEmpty()) { return super.getAllOutputs(rand, inputStack, toolStack, secondaryBonus); } List<ItemStack> list = new ArrayList<ItemStack>(); Collection<MobEffectInstance> collection = PotionUtils.getCustomEffects(toolStack); ItemStack outputCopyStack = output.copy(); PotionUtils.setCustomEffects(outputCopyStack, collection); list.add(outputCopyStack); for (Pair<ItemStack, Pair<Double, Double>> pair : addedItems) { Pair<Double, Double> bonus = pair.getRight(); if (rand.nextDouble() < (bonus.getLeft() + secondaryBonus * bonus.getRight())) list.add(pair.getLeft().copy()); } return list; } @Override public boolean breakTool() { return false; } @Override public RecipeSerializer<? extends RecipeARCPotion> getSerializer() { return BloodMagicRecipeSerializers.ARC_POTION.getRecipeSerializer(); } }
0
0.819052
1
0.819052
game-dev
MEDIA
0.988257
game-dev
0.965119
1
0.965119
samolego/Taterzens
3,261
src/main/java/org/samo_lego/taterzens/common/commands/edit/commands/CooldownCommand.java
package org.samo_lego.taterzens.common.commands.edit.commands; import com.mojang.brigadier.arguments.LongArgumentType; import com.mojang.brigadier.context.CommandContext; import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.brigadier.tree.LiteralCommandNode; import net.minecraft.commands.CommandSourceStack; import net.minecraft.commands.arguments.MessageArgument; import net.minecraft.world.entity.Entity; import org.samo_lego.taterzens.common.Taterzens; import org.samo_lego.taterzens.common.commands.NpcCommand; import static net.minecraft.commands.Commands.argument; import static net.minecraft.commands.Commands.literal; import static org.samo_lego.taterzens.common.Taterzens.config; import static org.samo_lego.taterzens.common.util.TextUtil.successText; public class CooldownCommand { public static void registerNode(LiteralCommandNode<CommandSourceStack> commandsNode) { LiteralCommandNode<CommandSourceStack> cooldown = literal("cooldown") .requires(cs -> Taterzens.getInstance().getPlatform().checkPermission(cs, "taterzens.edit.commands.cooldown", config.perms.npcCommandPermissionLevel)) .then(literal("set") .requires(cs -> Taterzens.getInstance().getPlatform().checkPermission(cs, "taterzens.edit.commands.cooldown.set", config.perms.npcCommandPermissionLevel)) .then(argument("cooldown", LongArgumentType.longArg(0)) .executes(CooldownCommand::setCooldown) ) ) .then(literal("editMessage") .requires(cs -> Taterzens.getInstance().getPlatform().checkPermission(cs, "taterzens.edit.commands.cooldown.edit_message", config.perms.npcCommandPermissionLevel)) .then(argument("new cooldown message", MessageArgument.message()) .executes(CooldownCommand::setMessage) ) ) .build(); commandsNode.addChild(cooldown); } private static int setMessage(CommandContext<CommandSourceStack> context) throws CommandSyntaxException { Entity entity = context.getSource().getEntityOrException(); String msg = MessageArgument.getMessage(context, "new cooldown message").getString(); return NpcCommand.selectedTaterzenExecutor(entity, taterzen -> { taterzen.setCooldownMessage(msg); context.getSource().sendSystemMessage( successText("taterzens.command.commands.cooldown.edit_message", msg, taterzen.getName().getString())); }); } private static int setCooldown(CommandContext<CommandSourceStack> context) throws CommandSyntaxException { Entity entity = context.getSource().getEntityOrException(); long cooldown = LongArgumentType.getLong(context, "cooldown"); return NpcCommand.selectedTaterzenExecutor(entity, taterzen -> { taterzen.setMinCommandInteractionTime(cooldown); context.getSource().sendSystemMessage( successText("taterzens.command.commands.cooldown.set", String.valueOf(cooldown), taterzen.getName().getString())); }); } }
0
0.726232
1
0.726232
game-dev
MEDIA
0.963638
game-dev
0.780196
1
0.780196
mcclure/bitbucket-backup
2,499
repos/template/contents/Modules/Dependencies/include/Box2D/Dynamics/b2Island.h
/* * Copyright (c) 2006-2009 Erin Catto http://www.gphysics.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 B2_ISLAND_H #define B2_ISLAND_H #include <Box2D/Common/b2Math.h> #include <Box2D/Dynamics/b2Body.h> #include <Box2D/Dynamics/b2TimeStep.h> class b2Contact; class b2Joint; class b2StackAllocator; class b2ContactListener; struct b2ContactConstraint; /// This is an internal structure. struct b2Position { b2Vec2 x; float32 a; }; /// This is an internal structure. struct b2Velocity { b2Vec2 v; float32 w; }; /// This is an internal class. class b2Island { public: b2Island(int32 bodyCapacity, int32 contactCapacity, int32 jointCapacity, b2StackAllocator* allocator, b2ContactListener* listener); ~b2Island(); void Clear() { m_bodyCount = 0; m_contactCount = 0; m_jointCount = 0; } void Solve(const b2TimeStep& step, const b2Vec2& gravity, bool allowSleep); void Add(b2Body* body) { b2Assert(m_bodyCount < m_bodyCapacity); body->m_islandIndex = m_bodyCount; m_bodies[m_bodyCount++] = body; } void Add(b2Contact* contact) { b2Assert(m_contactCount < m_contactCapacity); m_contacts[m_contactCount++] = contact; } void Add(b2Joint* joint) { b2Assert(m_jointCount < m_jointCapacity); m_joints[m_jointCount++] = joint; } void Report(const b2ContactConstraint* constraints); b2StackAllocator* m_allocator; b2ContactListener* m_listener; b2Body** m_bodies; b2Contact** m_contacts; b2Joint** m_joints; b2Position* m_positions; b2Velocity* m_velocities; int32 m_bodyCount; int32 m_jointCount; int32 m_contactCount; int32 m_bodyCapacity; int32 m_contactCapacity; int32 m_jointCapacity; int32 m_positionIterationCount; }; #endif
0
0.751463
1
0.751463
game-dev
MEDIA
0.816981
game-dev
0.629475
1
0.629475
ServUO/ServUO
2,538
Scripts/Items/Equipment/Weapons/MagicWand.cs
using System; using Server.Engines.Craft; namespace Server.Items { public class MagicWand : BaseBashing, IRepairable { public CraftSystem RepairSystem { get { return DefCarpentry.CraftSystem; } } [Constructable] public MagicWand() : base(0xDF2) { this.Weight = 1.0; } public MagicWand(Serial serial) : base(serial) { } public override WeaponAbility PrimaryAbility { get { return WeaponAbility.Dismount; } } public override WeaponAbility SecondaryAbility { get { return WeaponAbility.Disarm; } } public override int AosStrengthReq { get { return 5; } } public override int AosMinDamage { get { return 9; } } public override int AosMaxDamage { get { return 11; } } public override int AosSpeed { get { return 40; } } public override float MlSpeed { get { return 2.75f; } } public override int OldStrengthReq { get { return 0; } } public override int OldMinDamage { get { return 2; } } public override int OldMaxDamage { get { return 6; } } public override int OldSpeed { get { return 35; } } public override int InitMinHits { get { return 31; } } public override int InitMaxHits { get { return 110; } } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write((int)0); // version } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadInt(); } } }
0
0.79306
1
0.79306
game-dev
MEDIA
0.909269
game-dev
0.84873
1
0.84873
TelepathicGrunt/RepurposedStructures
2,953
common/src/main/java/com/telepathicgrunt/repurposedstructures/world/structures/pieces/LegacyOceanBottomSinglePoolElement.java
package com.telepathicgrunt.repurposedstructures.world.structures.pieces; import com.mojang.datafixers.util.Either; import com.mojang.serialization.MapCodec; import com.mojang.serialization.codecs.RecordCodecBuilder; import com.telepathicgrunt.repurposedstructures.modinit.RSStructurePieces; import net.minecraft.core.Holder; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.level.block.Rotation; import net.minecraft.world.level.levelgen.structure.BoundingBox; import net.minecraft.world.level.levelgen.structure.pools.SinglePoolElement; import net.minecraft.world.level.levelgen.structure.pools.StructurePoolElementType; import net.minecraft.world.level.levelgen.structure.pools.StructureTemplatePool; import net.minecraft.world.level.levelgen.structure.templatesystem.BlockIgnoreProcessor; import net.minecraft.world.level.levelgen.structure.templatesystem.LiquidSettings; import net.minecraft.world.level.levelgen.structure.templatesystem.StructurePlaceSettings; import net.minecraft.world.level.levelgen.structure.templatesystem.StructureProcessorList; import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate; import java.util.Optional; public class LegacyOceanBottomSinglePoolElement extends SinglePoolElement { public static final MapCodec<LegacyOceanBottomSinglePoolElement> CODEC = RecordCodecBuilder.mapCodec( (legacyOceanBottomSinglePoolElementInstance) -> legacyOceanBottomSinglePoolElementInstance .group(templateCodec(), processorsCodec(), projectionCodec(), overrideLiquidSettingsCodec()) .apply(legacyOceanBottomSinglePoolElementInstance, LegacyOceanBottomSinglePoolElement::new)); protected LegacyOceanBottomSinglePoolElement(Either<ResourceLocation, StructureTemplate> resourceLocationStructureTemplateEither, Holder<StructureProcessorList> structureProcessorListHolder, StructureTemplatePool.Projection projection, Optional<LiquidSettings> liquidSettings) { super(resourceLocationStructureTemplateEither, structureProcessorListHolder, projection, liquidSettings); } @Override protected StructurePlaceSettings getSettings(Rotation rotation, BoundingBox mutableBoundingBox, LiquidSettings liquidSettings, boolean doNotReplaceJigsaw) { StructurePlaceSettings structureplacesettings = super.getSettings(rotation, mutableBoundingBox, liquidSettings, doNotReplaceJigsaw); structureplacesettings.popProcessor(BlockIgnoreProcessor.STRUCTURE_BLOCK); structureplacesettings.addProcessor(BlockIgnoreProcessor.STRUCTURE_AND_AIR); return structureplacesettings; } public StructurePoolElementType<?> getType() { return RSStructurePieces.LEGACY_OCEAN_BOTTOM.get(); } public String toString() { return "LegacyOceanBottomSingle[" + this.template + "]"; } }
0
0.63922
1
0.63922
game-dev
MEDIA
0.981223
game-dev
0.895528
1
0.895528
folgerwang/UnrealEngine
11,017
Engine/Source/Runtime/Experimental/Chaos/Private/Chaos/SpatialHash.cpp
// Copyright 1998-2019 Epic Games, Inc. All Rights Reserved. #include "Chaos/SpatialHash.h" #include "ProfilingDebugging/ScopedTimers.h" namespace Chaos { DEFINE_LOG_CATEGORY_STATIC(LogChaosSpatialHash, Verbose, All); template<class T> void TSpatialHash<T>::Init(const T Radius) { double Time = 0.0; FDurationTimer Timer(Time); MCellSize = 2.0 * Radius; MBoundingBox = TBox<T, 3>(TVector<T, 3>(0.0), Chaos::TVector<T, 3>(0.0)); for (int32 Idx = 0; Idx < MParticles.Num(); ++Idx) { MBoundingBox.GrowToInclude(MParticles[Idx]); } TVector<T, 3> Extents = MBoundingBox.Extents(); // ensure(MCellSize < Extents[0] && MCellSize < Extents[1] && MCellSize < Extents[2]); T PrincipalAxisLength = Extents[MBoundingBox.LargestAxis()]; int32 NumberOfCellsOnPrincipalAxis = FMath::CeilToInt(PrincipalAxisLength / MCellSize); MCellSize = PrincipalAxisLength / (T)NumberOfCellsOnPrincipalAxis; T CellSizeInv = 1.0 / MCellSize; MNumberOfCellsX = FMath::CeilToInt(Extents[0] * CellSizeInv) + 1; MNumberOfCellsY = FMath::CeilToInt(Extents[1] * CellSizeInv) + 1; MNumberOfCellsZ = FMath::CeilToInt(Extents[2] * CellSizeInv) + 1; for (int32 IdxParticle = 0; IdxParticle < MParticles.Num(); ++IdxParticle) { int32 HashTableIdx = HashFunction(MParticles[IdxParticle]); ensure(HashTableIdx < MNumberOfCellsX * MNumberOfCellsY * MNumberOfCellsZ); if (MHashTable.Contains(HashTableIdx)) { MHashTable[HashTableIdx].Add(IdxParticle); } else { MHashTable.Add(HashTableIdx); MHashTable[HashTableIdx].Add(IdxParticle); } } Timer.Stop(); UE_LOG(LogChaosSpatialHash, Log, TEXT("TSpatialHash<T>::Init() Time is %f"), Time); } template<class T> void TSpatialHash<T>::Init() { double Time = 0.0; FDurationTimer Timer(Time); MBoundingBox = TBox<T, 3>(TVector<T, 3>(0.0), Chaos::TVector<T, 3>(0.0)); for (int32 Idx = 0; Idx < MParticles.Num(); ++Idx) { MBoundingBox.GrowToInclude(MParticles[Idx]); } TVector<T, 3> Extents = MBoundingBox.Extents(); T PrincipalAxisLength = Extents[MBoundingBox.LargestAxis()]; MCellSize = PrincipalAxisLength / 20.0; // ensure(MCellSize < Extents[0] && MCellSize < Extents[1] && MCellSize < Extents[2]); int32 NumberOfCellsOnPrincipalAxis = FMath::CeilToInt(PrincipalAxisLength / MCellSize); MCellSize = PrincipalAxisLength / (T)NumberOfCellsOnPrincipalAxis; T CellSizeInv = 1.0 / MCellSize; MNumberOfCellsX = FMath::CeilToInt(Extents[0] * CellSizeInv) + 1; MNumberOfCellsY = FMath::CeilToInt(Extents[1] * CellSizeInv) + 1; MNumberOfCellsZ = FMath::CeilToInt(Extents[2] * CellSizeInv) + 1; for (int32 IdxParticle = 0; IdxParticle < MParticles.Num(); ++IdxParticle) { int32 HashTableIdx = HashFunction(MParticles[IdxParticle]); ensure(HashTableIdx < MNumberOfCellsX * MNumberOfCellsY * MNumberOfCellsZ); if (MHashTable.Contains(HashTableIdx)) { MHashTable[HashTableIdx].Add(IdxParticle); } else { MHashTable.Add(HashTableIdx); MHashTable[HashTableIdx].Add(IdxParticle); } } Timer.Stop(); UE_LOG(LogChaosSpatialHash, Log, TEXT("TSpatialHash<T>::Init() Time is %f"), Time); } template<class T> void TSpatialHash<T>::Update(const TArray<TVector<T, 3>>& Particles, const T Radius) { MParticles = Particles; MHashTable.Empty(); Init(Radius); } template<class T> void TSpatialHash<T>::Update(const TArray<TVector<T, 3>>& Particles) { MParticles = Particles; MHashTable.Empty(); Init(); } template<class T> void TSpatialHash<T>::Update(const T Radius) { MHashTable.Empty(); Init(Radius); } template <class T> TArray<int32> TSpatialHash<T>::GetClosestPoints(const TVector<T, 3>& Particle, const T MaxRadius) { double Time = 0.0; FDurationTimer Timer(Time); TSet<int32> ClosestPoints; int32 MaxN = ComputeMaxN(Particle, MaxRadius); for (int32 IdxRing = 0; IdxRing < MaxN; ++IdxRing) { TSet<int32> CellIndices = GetNRing(Particle, IdxRing); for (auto& CellIdx : CellIndices) { if (MHashTable.Contains(CellIdx)) { ClosestPoints.Append(MHashTable[CellIdx]); } } } // Need to delete points which are out of MaxRadius range TSet<int32> PointsToRemove; T MaxRadiusSquared = MaxRadius * MaxRadius; for (auto& Elem : ClosestPoints) { FVector Diff = Particle - MParticles[Elem]; if (Diff.SizeSquared() > MaxRadiusSquared) { PointsToRemove.Add(Elem); } } if (PointsToRemove.Num() > 0) { ClosestPoints = ClosestPoints.Difference(ClosestPoints.Intersect(PointsToRemove)); } Timer.Stop(); UE_LOG(LogChaosSpatialHash, Log, TEXT("TSpatialHash<T>::GetClosestPoints() Time is %f"), Time); return ClosestPoints.Array(); } template<class T> TArray<int32> TSpatialHash<T>::GetClosestPoints(const TVector<T, 3>& Particle, const T MaxRadius, const int32 MaxPoints) { double Time = 0.0; FDurationTimer Timer(Time); TSet<int32> ClosestPoints; int32 MaxN = ComputeMaxN(Particle, MaxRadius); for (int32 IdxRing = 0; IdxRing < MaxN; ++IdxRing) { TSet<int32> CellIndices = GetNRing(Particle, IdxRing); for (auto& CellIdx : CellIndices) { if (MHashTable.Contains(CellIdx)) { ClosestPoints.Append(MHashTable[CellIdx]); } } } // Need to delete points which are out of MaxRadius range TSet<int32> PointsToRemove; T MaxRadiusSquared = MaxRadius * MaxRadius; for (auto& Elem : ClosestPoints) { FVector Diff = Particle - MParticles[Elem]; if (Diff.SizeSquared() > MaxRadiusSquared) { PointsToRemove.Add(Elem); } } if (PointsToRemove.Num() > 0) { ClosestPoints = ClosestPoints.Difference(ClosestPoints.Intersect(PointsToRemove)); } // Sort ClosestPoints TMap<int32, T> ParticleIdxDistanceMap; for (auto& Elem : ClosestPoints) { TVector<T, 3> Diff = Particle - MParticles[Elem]; ParticleIdxDistanceMap.Add(Elem, Diff.SizeSquared()); } ParticleIdxDistanceMap.ValueSort([](const T& Distance1, const T& Distance2) { return Distance1 < Distance2; }); TArray<int32> ClosestPointsArray; ParticleIdxDistanceMap.GetKeys(ClosestPointsArray); // Delete points after MaxPoints if (ClosestPointsArray.Num() > MaxPoints) { ClosestPointsArray.SetNum(MaxPoints); } Timer.Stop(); UE_LOG(LogChaosSpatialHash, Log, TEXT("TSpatialHash<T>::GetClosestPoints() Time is %f"), Time); return ClosestPointsArray; } template<class T> int32 TSpatialHash<T>::GetClosestPoint(const TVector<T, 3>& Particle) { double Time = 0.0; FDurationTimer Timer(Time); TVector<T, 3> Extents = MBoundingBox.Extents(); T PrincipalAxisLength = Extents[MBoundingBox.LargestAxis()]; const T MaxRadius = PrincipalAxisLength / 2.0; TSet<int32> ClosestPoints; int32 MaxN = 2; for (int32 IdxRing = 0; IdxRing < MaxN; ++IdxRing) { TSet<int32> CellIndices = GetNRing(Particle, IdxRing); for (auto& CellIdx : CellIndices) { if (MHashTable.Contains(CellIdx)) { ClosestPoints.Append(MHashTable[CellIdx]); } } } // Find closest point int32 ClosestPointIdx = ClosestPoints.Array()[0]; if (ClosestPoints.Num() > 1) { float DistanceSquared = FLT_MAX; for (auto& Elem : ClosestPoints) { FVector Diff = Particle - MParticles[Elem]; T DiffSquared = Diff.SizeSquared(); if (DiffSquared < DistanceSquared) { DistanceSquared = DiffSquared; ClosestPointIdx = Elem; } } } Timer.Stop(); UE_LOG(LogChaosSpatialHash, Log, TEXT("TSpatialHash<T>::GetClosestPoint() Time is %f"), Time); return ClosestPointIdx; } template<class T> int32 TSpatialHash<T>::ComputeMaxN(const TVector<T, 3>& Particle, const T Radius) { int32 MaxN = INT_MIN; TArray<int32> IndexParticleArray; IndexParticleArray.SetNum(3); ComputeGridXYZ(Particle, IndexParticleArray[0], IndexParticleArray[1], IndexParticleArray[2]); TArray<TVector<T, 3>> Points; Points.Add(Particle - TVector<T, 3>(Radius, 0.0, 0.0)); Points.Add(Particle + TVector<T, 3>(Radius, 0.0, 0.0)); Points.Add(Particle - TVector<T, 3>(0.0, Radius, 0.0)); Points.Add(Particle + TVector<T, 3>(0.0, Radius, 0.0)); Points.Add(Particle - TVector<T, 3>(0.0, 0.0, Radius)); Points.Add(Particle + TVector<T, 3>(0.0, 0.0, Radius)); TArray<int32> IndexPointArray; IndexPointArray.SetNum(3); for (int32 IdxPoint = 0; IdxPoint < Points.Num(); ++IdxPoint) { ComputeGridXYZ(Points[IdxPoint], IndexPointArray[0], IndexPointArray[1], IndexPointArray[2]); IndexPointArray[0] = FMath::Clamp(IndexPointArray[0], 0, MNumberOfCellsX - 1); IndexPointArray[1] = FMath::Clamp(IndexPointArray[1], 0, MNumberOfCellsY - 1); IndexPointArray[2] = FMath::Clamp(IndexPointArray[2], 0, MNumberOfCellsZ - 1); for (int32 Idx = 0; Idx < 3; ++Idx) { int32 Diff = FMath::Abs(IndexParticleArray[Idx] - IndexPointArray[Idx]) + 1; if (Diff > MaxN) { MaxN = Diff; } } } return MaxN; } template<class T> TSet<int32> TSpatialHash<T>::GetNRing(const TVector<T, 3>& Particle, const int32 N) { TSet<int32> RingCells; int32 ParticleXIndex, ParticleYIndex, ParticleZIndex; ComputeGridXYZ(Particle, ParticleXIndex, ParticleYIndex, ParticleZIndex); int32 XIndex, YIndex, ZIndex; if (N == 0) { RingCells.Add(HashFunction(ParticleXIndex, ParticleYIndex, ParticleZIndex)); } else { for (int32 XIdx = -N; XIdx <= N; ++XIdx) { for (int32 YIdx = -N; YIdx <= N; ++YIdx) { for (int32 ZIdx = -N; ZIdx <= N; ++ZIdx) { if (XIdx == N || XIdx == -N || YIdx == N || YIdx == -N || ZIdx == N || ZIdx == -N) { XIndex = ParticleXIndex + XIdx; YIndex = ParticleYIndex + YIdx; ZIndex = ParticleZIndex + ZIdx; if (XIndex >= 0 && XIndex < MNumberOfCellsX && YIndex >= 0 && YIndex < MNumberOfCellsY && ZIndex >= 0 && ZIndex < MNumberOfCellsZ) { RingCells.Add(HashFunction(XIndex, YIndex, ZIndex)); } } } } } } return RingCells; } template<class T> void TSpatialHash<T>::ComputeGridXYZ(const TVector<T, 3>& Particle, int32& XIndex, int32& YIndex, int32& ZIndex) { T CellSizeInv = 1.0 / MCellSize; FVector Location = Particle - MBoundingBox.Min() + TVector<T, 3>(0.5 * MCellSize); XIndex = (int32)(Location.X * CellSizeInv); YIndex = (int32)(Location.Y * CellSizeInv); ZIndex = (int32)(Location.Z * CellSizeInv); } template<class T> int32 TSpatialHash<T>::HashFunction(int32& XIndex, int32& YIndex, int32& ZIndex) { return XIndex + YIndex * MNumberOfCellsX + ZIndex * MNumberOfCellsX * MNumberOfCellsY; } template<class T> int32 TSpatialHash<T>::HashFunction(const TVector<T, 3>& Particle) { T CellSizeInv = 1.0 / MCellSize; FVector Location = Particle - MBoundingBox.Min() + TVector<T, 3>(0.5 * MCellSize); int32 XIndex, YIndex, ZIndex; ComputeGridXYZ(Particle, XIndex, YIndex, ZIndex); return XIndex + YIndex * MNumberOfCellsX + ZIndex * MNumberOfCellsX * MNumberOfCellsY; } template class TSpatialHash<float>; }
0
0.96521
1
0.96521
game-dev
MEDIA
0.554308
game-dev
0.984759
1
0.984759
miw-upm/IWVG
1,349
doo/src/main/java/ticTacToe/v370/controllers/local/LocalController.java
package ticTacToe.v370.controllers.local; import ticTacToe.v370.models.Color; import ticTacToe.v370.models.Coordinate; import ticTacToe.v370.models.Game; import ticTacToe.v370.models.State; public abstract class LocalController { private Game game; protected LocalController(Game game) { assert game != null; this.game = game; } protected int numPlayers() { return game.getNumPlayers(); } protected State getState(){ return game.getState(); } public void setState(State state){ assert state != null; game.setState(state); } public Color take() { return game.take(); } public void put(Coordinate target) { assert target != null; game.put(target); if (game.existTicTacToe()) { game.setState(State.FINAL); } else { game.change(); } } public void remove(Coordinate origin) { assert origin != null; game.remove(origin); } public void clear() { game.clear(); } public boolean empty(Coordinate coordinate) { assert coordinate != null; return game.empty(coordinate); } public boolean full(Coordinate coordinate) { assert coordinate != null; return game.full(coordinate); } public boolean existTicTacToe() { return game.existTicTacToe(); } public Color getColor(Coordinate coordinate){ assert coordinate != null; return game.getColor(coordinate); } }
0
0.838157
1
0.838157
game-dev
MEDIA
0.746072
game-dev
0.7859
1
0.7859
OGSR/OGSR-Engine
3,663
ogsr_engine/xrGame/movement_manager_patrol.cpp
//////////////////////////////////////////////////////////////////////////// // Module : movement_manager_patrol.cpp // Created : 03.12.2003 // Modified : 03.12.2003 // Author : Dmitriy Iassenev // Description : Movement manager for patrol paths //////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "movement_manager.h" #include "patrol_path_manager.h" #include "level_path_manager.h" #include "detail_path_manager.h" #include "ai_object_location.h" #include "custommonster.h" #include "level_path_builder.h" #include "detail_path_builder.h" #include "mt_config.h" void CMovementManager::process_patrol_path() { if (!level_path().actual() && (m_path_state > ePathStateBuildLevelPath)) m_path_state = ePathStateBuildLevelPath; if (!patrol().actual() && (m_path_state > ePathStateSelectPatrolPoint)) m_path_state = ePathStateSelectPatrolPoint; switch (m_path_state) { case ePathStateSelectPatrolPoint: { patrol().select_point(object().Position(), level_path().m_dest_vertex_id); if (patrol().failed()) break; if (patrol().completed()) { m_path_state = ePathStatePathCompleted; break; } m_path_state = ePathStateBuildLevelPath; } case ePathStateBuildLevelPath: { if (can_use_distributed_computations(mtLevelPath)) { level_path_builder().setup(object().ai_location().level_vertex_id(), level_dest_vertex_id()); break; } level_path().build_path(object().ai_location().level_vertex_id(), level_dest_vertex_id()); if (level_path().failed()) break; m_path_state = ePathStateContinueLevelPath; break; } case ePathStateContinueLevelPath: { level_path().select_intermediate_vertex(); m_path_state = ePathStateBuildDetailPath; } case ePathStateBuildDetailPath: { detail().set_state_patrol_path(patrol().extrapolate_path()); detail().set_start_position(object().Position()); detail().set_start_direction(Fvector().setHP(-m_body.current.yaw, 0)); detail().set_dest_position(patrol().destination_position()); if (can_use_distributed_computations(mtDetailPath)) { detail_path_builder().setup(level_path().path(), level_path().intermediate_index()); break; } detail().build_path(level_path().path(), level_path().intermediate_index()); on_build_path(); if (detail().failed()) { m_path_state = ePathStateBuildLevelPath; break; } m_path_state = ePathStatePathVerification; break; } case ePathStatePathVerification: { if (!patrol().actual()) m_path_state = ePathStateSelectPatrolPoint; else if (!level_path().actual()) m_path_state = ePathStateBuildLevelPath; else if (!detail().actual()) m_path_state = ePathStateBuildLevelPath; else if (detail().completed(object().Position(), !detail().state_patrol_path())) { m_path_state = ePathStateContinueLevelPath; if (level_path().completed()) { m_path_state = ePathStateSelectPatrolPoint; if (patrol().completed()) m_path_state = ePathStatePathCompleted; } } break; } case ePathStatePathCompleted: { if (!patrol().actual()) m_path_state = ePathStateSelectPatrolPoint; break; } default: NODEFAULT; } }
0
0.921993
1
0.921993
game-dev
MEDIA
0.899623
game-dev
0.937664
1
0.937664
jm33-m0/emp3r0r
4,388
core/internal/cc/modules/mod.go
package modules import ( "fmt" "strconv" "strings" "github.com/jm33-m0/emp3r0r/core/internal/def" "github.com/jm33-m0/emp3r0r/core/internal/live" "github.com/jm33-m0/emp3r0r/core/lib/logging" "github.com/lithammer/fuzzysearch/fuzzy" "github.com/spf13/cobra" ) var ( // ShellHelpInfo provide utilities like ps, kill, etc // deprecated ShellHelpInfo = map[string]string{ "#ps": "List processes: `ps`", "#kill": "Kill process: `kill <PID>`", "#net": "Show network info", "put": "Put a file from CC to agent: `put <local file> <remote path>`", "get": "Get a file from agent: `get <remote file>`", } // ModuleRunners a map of module helpers ModuleRunners = map[string]func(){ def.ModCMD_EXEC: moduleCmd, def.ModSHELL: moduleShell, def.ModPROXY: moduleProxy, def.ModPORT_FWD: modulePortFwd, def.ModLPE_SUGGEST: moduleLPE, def.ModCLEAN_LOG: moduleLogCleaner, // def.ModPERSISTENCE: modulePersistence, // DISABLED: buggy module def.ModVACCINE: moduleVaccine, def.ModINJECTOR: moduleInjector, def.ModBring2CC: moduleBring2CC, def.ModListener: modListener, def.ModSSHHarvester: module_ssh_harvester, def.ModDownloader: moduleDownloader, def.ModFileServer: moduleFileServer, def.ModMemDump: moduleMemDump, def.ModELF_PATCH: moduleElfPatch, } ) // UpdateOptions reads options from modules config, and set default values func UpdateOptions(modName string) (exist bool) { if live.ActiveModule == nil { logging.Errorf("No active module") return } // filter user supplied option for mod := range ModuleRunners { if mod == modName { exist = true break } } if !exist { logging.Errorf("UpdateOptions: no such module: %s", modName) return } // help us add new options addIfNotFound := func(modOpt *def.ModOption) { if _, exist := live.ActiveModule.Options[modOpt.Name]; !exist { logging.Debugf("UpdateOptions: adding %s", modOpt.Name) live.ActiveModule.Options[modOpt.Name] = modOpt } } modconfig := def.Modules[modName] if strings.ToLower(modconfig.AgentConfig.Exec) != "built-in" && !modconfig.IsLocal { logging.Debugf("UpdateOptions: module %s is not built-in, adding download_addr", modName) download_addr := &def.ModOption{ Name: "download_addr", Desc: "Download URL for this module, useful when you want to use an agent as caching server", Val: "", Vals: []string{}, } addIfNotFound(download_addr) } return } // ModuleRun run current module func ModuleRun() { if live.ActiveModule == nil { logging.Errorf("No active module") return } if live.ActiveAgent != nil { target_os := live.ActiveAgent.GOOS mod_os := strings.ToLower(live.ActiveModule.Platform) if mod_os != "generic" && target_os != mod_os { logging.Errorf("ModuleRun: module %s does not support %s", strconv.Quote(live.ActiveModule.Name), target_os) return } } // is a target needed? if live.ActiveAgent == nil && !live.ActiveModule.IsLocal { logging.Errorf("Target not specified") return } // run module mod := ModuleRunners[live.ActiveModule.Name] if mod != nil { go mod() } else { logging.Errorf("Module %s has no runner", strconv.Quote(live.ActiveModule.Name)) } } func CmdModuleSearch(cmd *cobra.Command, args []string) { ModuleSearch(args[0]) } // search modules, powered by fuzzysearch func ModuleSearch(keyword string) []*def.ModuleConfig { search_targets := new([]string) for name, mod_config := range def.Modules { *search_targets = append(*search_targets, fmt.Sprintf("%s: %s", name, mod_config.Comment)) } result := fuzzy.Find(keyword, *search_targets) // render results search_results := make([]*def.ModuleConfig, 0) for _, r := range result { mod_name := strings.Split(r, ":")[0] mod, ok := def.Modules[mod_name] if ok { search_results = append(search_results, mod) } } return search_results } // SetActiveModule set the active module to use: `use` command func SetActiveModule(modName string) { for mod := range ModuleRunners { if mod == modName { live.ActiveModule = def.Modules[modName] UpdateOptions(modName) logging.Infof("Using module %s", strconv.Quote(modName)) mod, exists := def.Modules[modName] if exists { logging.Successf("%s: %s", modName, mod.Comment) } return } } logging.Errorf("No such module: %s", strconv.Quote(modName)) }
0
0.877554
1
0.877554
game-dev
MEDIA
0.234712
game-dev
0.878702
1
0.878702
Mithion/ArsMagica2
7,677
src/api/java/thaumcraft/api/crafting/ShapedArcaneRecipe.java
package thaumcraft.api.crafting; import java.util.ArrayList; import java.util.HashMap; import net.minecraft.block.Block; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.world.World; import net.minecraftforge.oredict.OreDictionary; import thaumcraft.api.ThaumcraftApiHelper; import thaumcraft.api.aspects.AspectList; public class ShapedArcaneRecipe implements IArcaneRecipe { //Added in for future ease of change, but hard coded for now. private static final int MAX_CRAFT_GRID_WIDTH = 3; private static final int MAX_CRAFT_GRID_HEIGHT = 3; public ItemStack output = null; public Object[] input = null; public AspectList aspects = null; public String research; public int width = 0; public int height = 0; private boolean mirrored = true; public ShapedArcaneRecipe(String research, Block result, AspectList aspects, Object... recipe){ this(research, new ItemStack(result), aspects, recipe); } public ShapedArcaneRecipe(String research, Item result, AspectList aspects, Object... recipe){ this(research, new ItemStack(result), aspects, recipe); } public ShapedArcaneRecipe(String research, ItemStack result, AspectList aspects, Object... recipe) { output = result.copy(); this.research = research; this.aspects = aspects; String shape = ""; int idx = 0; if (recipe[idx] instanceof Boolean) { mirrored = (Boolean)recipe[idx]; if (recipe[idx+1] instanceof Object[]) { recipe = (Object[])recipe[idx+1]; } else { idx = 1; } } if (recipe[idx] instanceof String[]) { String[] parts = ((String[])recipe[idx++]); for (String s : parts) { width = s.length(); shape += s; } height = parts.length; } else { while (recipe[idx] instanceof String) { String s = (String)recipe[idx++]; shape += s; width = s.length(); height++; } } if (width * height != shape.length()) { String ret = "Invalid shaped ore recipe: "; for (Object tmp : recipe) { ret += tmp + ", "; } ret += output; throw new RuntimeException(ret); } HashMap<Character, Object> itemMap = new HashMap<Character, Object>(); for (; idx < recipe.length; idx += 2) { Character chr = (Character)recipe[idx]; Object in = recipe[idx + 1]; if (in instanceof ItemStack) { itemMap.put(chr, ((ItemStack)in).copy()); } else if (in instanceof Item) { itemMap.put(chr, new ItemStack((Item)in)); } else if (in instanceof Block) { itemMap.put(chr, new ItemStack((Block)in, 1, OreDictionary.WILDCARD_VALUE)); } else if (in instanceof String) { itemMap.put(chr, OreDictionary.getOres((String)in)); } else { String ret = "Invalid shaped ore recipe: "; for (Object tmp : recipe) { ret += tmp + ", "; } ret += output; throw new RuntimeException(ret); } } input = new Object[width * height]; int x = 0; for (char chr : shape.toCharArray()) { input[x++] = itemMap.get(chr); } } @Override public ItemStack getCraftingResult(IInventory var1){ return output.copy(); } @Override public int getRecipeSize(){ return input.length; } @Override public ItemStack getRecipeOutput(){ return output; } @Override public boolean matches(IInventory inv, World world, EntityPlayer player) { if (research.length()>0 && !ThaumcraftApiHelper.isResearchComplete(player.getCommandSenderName(), research)) { return false; } for (int x = 0; x <= MAX_CRAFT_GRID_WIDTH - width; x++) { for (int y = 0; y <= MAX_CRAFT_GRID_HEIGHT - height; ++y) { if (checkMatch(inv, x, y, false)) { return true; } if (mirrored && checkMatch(inv, x, y, true)) { return true; } } } return false; } private boolean checkMatch(IInventory inv, int startX, int startY, boolean mirror) { for (int x = 0; x < MAX_CRAFT_GRID_WIDTH; x++) { for (int y = 0; y < MAX_CRAFT_GRID_HEIGHT; y++) { int subX = x - startX; int subY = y - startY; Object target = null; if (subX >= 0 && subY >= 0 && subX < width && subY < height) { if (mirror) { target = input[width - subX - 1 + subY * width]; } else { target = input[subX + subY * width]; } } ItemStack slot = ThaumcraftApiHelper.getStackInRowAndColumn(inv, x, y); if (target instanceof ItemStack) { if (!checkItemEquals((ItemStack)target, slot)) { return false; } } else if (target instanceof ArrayList) { boolean matched = false; for (ItemStack item : (ArrayList<ItemStack>)target) { matched = matched || checkItemEquals(item, slot); } if (!matched) { return false; } } else if (target == null && slot != null) { return false; } } } return true; } private boolean checkItemEquals(ItemStack target, ItemStack input) { if (input == null && target != null || input != null && target == null) { return false; } return (target.getItem() == input.getItem() && (!target.hasTagCompound() || ItemStack.areItemStackTagsEqual(target, input)) && (target.getItemDamage() == OreDictionary.WILDCARD_VALUE|| target.getItemDamage() == input.getItemDamage())); } public ShapedArcaneRecipe setMirrored(boolean mirror) { mirrored = mirror; return this; } /** * Returns the input for this recipe, any mod accessing this value should never * manipulate the values in this array as it will effect the recipe itself. * @return The recipes input vales. */ public Object[] getInput() { return this.input; } @Override public AspectList getAspects() { return aspects; } @Override public AspectList getAspects(IInventory inv) { return aspects; } @Override public String getResearch() { return research; } }
0
0.937933
1
0.937933
game-dev
MEDIA
0.970412
game-dev
0.963177
1
0.963177
bevy-cheatbook/bevy-cheatbook
1,194
src/code/examples/manual-event-clear.rs
#![allow(unused_variables)] use bevy::prelude::*; struct MySpecialEvent; struct MyRegularEvent; // ANCHOR: main use bevy::ecs::event::Events; fn main() { App::new() .add_plugins(DefaultPlugins) // add the `Events<T>` resource manually // these events will not have automatic cleanup .init_resource::<Events<MySpecialEvent>>() // this is a regular event type with automatic cleanup .add_event::<MyRegularEvent>() // add the cleanup systems .add_system(my_event_manager::<MySpecialEvent>) .run(); } /// Custom cleanup strategy for events /// /// Generic to allow using for any custom event type fn my_event_manager<T: 'static + Send + Sync>( mut events: ResMut<Events<T>>, ) { // TODO: implement your custom logic // for deciding when to clear the events // clear all events like this: events.clear(); // or with double-buffering // (this is what Bevy's default strategy does) events.update(); // or drain them, if you want to iterate, // to access the values: for event in events.drain() { // TODO: do something with each event } } // ANCHOR_END: main
0
0.701782
1
0.701782
game-dev
MEDIA
0.621463
game-dev
0.817881
1
0.817881
smogon/pokemon-showdown
4,311
data/mods/gen9ssb/items.ts
export const Items: import('../../../sim/dex-items').ModdedItemDataTable = { // Archas lilligantiumz: { name: "Lilligantium Z", spritenum: 633, onTakeItem: false, zMove: "Aura Rain", zMoveFrom: "Quiver Dance", itemUser: ["Lilligant"], desc: "If held by a Lilligant with Quiver Dance, it can use Aura Rain.", }, // Arya flygonite: { name: "Flygonite", spritenum: 111, itemUser: ["Flygon"], megaEvolves: "Flygon", megaStone: "Trapinch", onTakeItem(item, source) { if (item.megaEvolves === source.baseSpecies.baseSpecies) return false; return true; }, desc: "If held by a Flygon, this item allows it to Mega Evolve in battle.", }, // Irpachuza irpatuziniumz: { name: "Irpatuzinium Z", spritenum: 648, onTakeItem: false, zMove: "Bibbidi-Bobbidi-Rands", zMoveFrom: "Fleur Cannon", itemUser: ["Mr. Mime"], desc: "If held by a Mr. Mime with Fleur Cannon, it can use Bibbidi-Bobbidi-Rands.", }, // Loethalion gardevoirite: { inherit: true, itemUser: ["Ralts"], megaEvolves: "Ralts", desc: "If held by a Ralts, this item allows it to Mega Evolve in battle.", }, // Peary pearyumz: { name: "Pearyum Z", spritenum: 647, onTakeItem: false, zMove: "1000 Gears", zMoveFrom: "Gear Grind", itemUser: ["Klinklang"], desc: "If held by a Klinklang with Gear Grind, it can use 1000 Gears.", }, // Rainshaft rainiumz: { name: "Rainium Z", spritenum: 652, onTakeItem: false, zMove: "Hatsune Miku's Lucky Orb", zMoveFrom: "Sparkling Aria", itemUser: ["Xerneas"], desc: "If held by a Xerneas with Sparkling Aria, it can use Hatsune Miku's Lucky Orb.", }, // Modified for other effects eviolite: { inherit: true, onModifyDef(def, pokemon) { // Added Pichu-Spiky-eared for Hydrostatics to use Eviolite if (pokemon.baseSpecies.nfe || pokemon.species.id === 'pichuspikyeared') { return this.chainModify(1.5); } }, onModifySpD(spd, pokemon) { // Added Pichu-Spiky-eared for Hydrostatics to use Eviolite if (pokemon.baseSpecies.nfe || pokemon.species.id === 'pichuspikyeared') { return this.chainModify(1.5); } }, }, // modified for nya's ability focusband: { inherit: true, onDamage(damage, target, source, effect) { const chance = target.hasAbility('adorablegrace') ? 2 : 1; if (this.randomChance(chance, 10) && damage >= target.hp && effect && effect.effectType === 'Move') { this.add("-activate", target, "item: Focus Band"); return target.hp - 1; } }, }, quickclaw: { inherit: true, onFractionalPriority(priority, pokemon) { const chance = pokemon.hasAbility('adorablegrace') ? 2 : 1; if (priority <= 0 && this.randomChance(chance, 5)) { this.add('-activate', pokemon, 'item: Quick Claw'); return 0.1; } }, }, // modified for SexyMalasada's ability lifeorb: { inherit: true, onAfterMoveSecondarySelf(source, target, move) { if (source && source !== target && move && move.category !== 'Status' && !source.forceSwitchFlag) { if (source.hasAbility('Ancestry Ritual')) { this.heal(source.baseMaxhp / 10, source, source, this.dex.items.get('lifeorb')); } else { this.damage(source.baseMaxhp / 10, source, source, this.dex.items.get('lifeorb')); } } }, }, safetygoggles: { inherit: true, onImmunity(type, pokemon) { if (type === 'sandstorm' || type === 'deserteddunes' || type === 'hail' || type === 'powder') return false; }, }, utilityumbrella: { inherit: true, onStart(pokemon) { if (!pokemon.ignoringItem()) return; if (['sunnyday', 'raindance', 'desolateland', 'primordialsea', 'stormsurge'].includes(this.field.effectiveWeather())) { this.runEvent('WeatherChange', pokemon, pokemon, this.effect); } }, onUpdate(pokemon) { if (!this.effectState.inactive) return; this.effectState.inactive = false; if (['sunnyday', 'raindance', 'desolateland', 'primordialsea', 'stormsurge'].includes(this.field.effectiveWeather())) { this.runEvent('WeatherChange', pokemon, pokemon, this.effect); } }, onEnd(pokemon) { if (['sunnyday', 'raindance', 'desolateland', 'primordialsea', 'stormsurge'].includes(this.field.effectiveWeather())) { this.runEvent('WeatherChange', pokemon, pokemon, this.effect); } this.effectState.inactive = true; }, }, };
0
0.914717
1
0.914717
game-dev
MEDIA
0.944401
game-dev
0.989542
1
0.989542
rav3dev/vrtwix
16,371
Assets/_VRtwix/Scripts/CustomHand.cs
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using Valve.VR; using Valve.VR.InteractionSystem; public class CustomHand : MonoBehaviour { [Header("Hand Interaction Settings")] public float gripRadius; public float indexRadius; public float pinchRadius; public Vector3 gripPoint = new Vector3(0, 0, -.1f); // local interaction point positions public Vector3 indexPoint = new Vector3(-0.04f, -0.055f, -0.005f); public Vector3 pinchPoint = new Vector3(0, 0, -.05f); public LayerMask layerColliderChecker;//Layer to interact & grab with [Header("Inputs And Actions")] public SteamVR_Action_Boolean grabButton;//grab inputs public SteamVR_Action_Boolean pinchButton; public SteamVR_Action_Vibration hapticSignal = SteamVR_Input.GetAction<SteamVR_Action_Vibration>("Haptic");//Output of haptic ramble public SteamVR_Action_Single squeezeButton;//squeeze input he he public SteamVR_Input_Sources handType;//hand type, is it right or left public GrabType grabType;// current grab type public enum GrabType { None, Select, Grip, Pinch, } public SteamVR_renderModel renderModel;// controller model [Header("Blend speed settings")] [Range(0.001f, 1f)] public float blend = .1f; // hand blend state transition speed [Range(0.001f, 1f)] public float blendPosition = .1f; // hand blend position transition speed //SYSTEM VARIABLES [HideInInspector] public bool smoothBlendPhysicsObject;// smooth pickup of physical object [HideInInspector] public Collider[] selectedGripColliders, selectedIndexColliders, selectedPinchColliders;//colliders in a grab radius public CustomInteractible selectedIndexInteractible, selectedPinchInteractible, selectedGripInteractible, grabInteractible;// nearest interaction objects and object is currently interacting with [HideInInspector] public SteamVR_Behaviour_Skeleton skeleton;// current hand's skeleton [HideInInspector] public SteamVR_Skeleton_Poser grabPoser;// poser of object currently interacting with [HideInInspector] public Vector3 posSavePoser, rotSavePoser, inverceLocalPosition;//magic variables, which are need to calculate something ( need to know ) [HideInInspector] public Transform pivotPoser, toolTransform;//Pivot from hands poser, hidden instrument to simplify some calculations [HideInInspector] public bool hideController, alwayshideController;//hide controller [HideInInspector] public float squeeze;//squeeze strength bool setHandTransform;//Assing position, to pass of the 1st frame, used to be a bug ( maybe remove, need to check if this bug still here ) float blendToAnimation = 1, blendToPose = 1, blendToPoseMoveObject = 1;//smooth transition for animation and pose //STORAGE Vector3 endFramePos, oldInterpolatePos; Quaternion endFrameRot, oldInterpolateRot; void Start() { if (!pivotPoser) pivotPoser = new GameObject().transform; pivotPoser.hideFlags = HideFlags.HideInHierarchy; if (!toolTransform) toolTransform = new GameObject().transform; toolTransform.hideFlags = HideFlags.HideInHierarchy; if (GetComponent<SteamVR_Behaviour_Pose>()) { handType = GetComponent<SteamVR_Behaviour_Pose>().inputSource; } else { Debug.LogError("no SteamVR_Behaviour_Pose on this object"); } if (GetComponentInChildren<SteamVR_Behaviour_Skeleton>()) { skeleton = GetComponentInChildren<SteamVR_Behaviour_Skeleton>(); } if (GetComponentInChildren<SteamVR_renderModel>()) { renderModel = GetComponentInChildren<SteamVR_renderModel>(); StartCoroutine(hideControllerCoroutine()); } skeleton.BlendToSkeleton(); } void FixedUpdate() { SelectObject(PointByPoint(indexPoint), GrabType.Select, selectedIndexColliders, ref selectedIndexInteractible); squeeze = squeezeButton.GetAxis(handType); PivotUpdate(); GrabCheck(); if (grabPoser && grabInteractible) { GrabUpdate(); return; } SelectObject(PointByPoint(pinchPoint), GrabType.Pinch, selectedPinchColliders, ref selectedPinchInteractible); SelectObject(PointByPoint(gripPoint), GrabType.Grip, selectedGripColliders, ref selectedGripInteractible); } IEnumerator hideControllerCoroutine() { while (true) { if (renderModel.transform.childCount > 0) { renderModelVisible(hideController); break; } yield return 0; } } void GrabCheck() { if (grabType != GrabType.None && grabInteractible) { if (grabType == GrabType.Pinch && pinchButton.GetStateUp(handType)) { grabInteractible.SendMessage("GrabEnd", this, SendMessageOptions.DontRequireReceiver); GrabEnd(); } if (grabType == GrabType.Grip && grabButton.GetStateUp(handType)) { grabInteractible.SendMessage("GrabEnd", this, SendMessageOptions.DontRequireReceiver); GrabEnd(); } } if (!grabPoser) { BlendControll(true); CustomInteractible oldgrabInteractible = grabInteractible; if (selectedIndexInteractible) { grabInteractible = selectedIndexInteractible; InteractionProcessor(oldgrabInteractible, grabInteractible, GrabType.Select); } else if (selectedPinchInteractible && pinchButton.GetStateDown(handType)) { grabInteractible = selectedPinchInteractible; InteractionProcessor(oldgrabInteractible, grabInteractible, GrabType.Pinch); } else if (selectedGripInteractible && grabButton.GetStateDown(handType)) { grabInteractible = selectedGripInteractible; InteractionProcessor(oldgrabInteractible, grabInteractible, GrabType.Grip); } } } private void InteractionProcessor(CustomInteractible oldgrabInteractible, CustomInteractible grabInteractible, GrabType procGrabType) { if (grabInteractible != oldgrabInteractible) { if (oldgrabInteractible) oldgrabInteractible.SendMessage("GrabEnd", this, SendMessageOptions.DontRequireReceiver); if (grabInteractible) { grabInteractible.SendMessage("GrabStart", this, SendMessageOptions.DontRequireReceiver); setHandTransform = false; grabType = procGrabType; renderModelVisible(!grabInteractible.hideController); SkeletonUpdate(); blendToPose = 1; blendToPoseMoveObject = 1; endFramePos = transform.parent.InverseTransformPoint(skeleton.transform.position); endFrameRot = skeleton.transform.rotation; } } } public void GrabUpdateCustom() { if (grabPoser) { skeleton.BlendToPoser(grabPoser, 0); posSavePoser = grabPoser.transform.localPosition; rotSavePoser = grabPoser.transform.localEulerAngles; grabPoser.transform.rotation = transform.rotation * grabPoser.GetBlendedPose(skeleton).rotation; grabPoser.transform.position = transform.TransformPoint(grabPoser.GetBlendedPose(skeleton).position); PivotUpdate(); inverceLocalPosition = grabPoser.transform.InverseTransformPoint(transform.position); grabPoser.transform.localPosition = posSavePoser; grabPoser.transform.localEulerAngles = rotSavePoser; skeleton.transform.position = grabPoser.transform.TransformPoint(inverceLocalPosition); skeleton.transform.rotation = grabPoser.transform.rotation * Quaternion.Inverse(grabPoser.GetBlendedPose(skeleton).rotation); BlendControll(false); skeleton.skeletonBlend = blendToAnimation; } } void BlendControll(bool positive) { if (positive) { if (blend > 0) { blendToAnimation += 1f / blend * Time.deltaTime; blendToAnimation = Mathf.Clamp01(blendToAnimation); blendToPose += 1f / blendPosition * Time.deltaTime; blendToPose = Mathf.Clamp01(blendToPose); blendToPoseMoveObject += 1f / blendPosition * Time.deltaTime; blendToPoseMoveObject = Mathf.Clamp01(blendToPoseMoveObject); } else { blendToAnimation = 1; } } else { if (blend > 0) { blendToAnimation -= 1f / blend * Time.deltaTime; blendToAnimation = Mathf.Clamp01(blendToAnimation); blendToPose -= 1f / blendPosition * Time.deltaTime; blendToPose = Mathf.Clamp01(blendToPose); blendToPoseMoveObject -= 1f / blendPosition * Time.deltaTime; blendToPoseMoveObject = Mathf.Clamp01(blendToPoseMoveObject); } else { blendToAnimation = 0; } } } void GrabUpdate() { if (grabPoser) { skeleton.BlendToPoser(grabPoser, 0); posSavePoser = grabPoser.transform.localPosition; rotSavePoser = grabPoser.transform.localEulerAngles; grabPoser.transform.rotation = transform.rotation * grabPoser.GetBlendedPose(skeleton).rotation; grabPoser.transform.position = transform.TransformPoint(grabPoser.GetBlendedPose(skeleton).position); PivotUpdate(); inverceLocalPosition = grabPoser.transform.InverseTransformPoint(transform.position); grabPoser.transform.localPosition = posSavePoser; grabPoser.transform.localEulerAngles = rotSavePoser; grabInteractible.SendMessage("GrabUpdate", this, SendMessageOptions.DontRequireReceiver); BlendControll(false); skeleton.skeletonBlend = blendToAnimation; } } public void HapticResponse(float hlength, float hfreq, float hpower) { hapticSignal.Execute(0, hlength, hfreq, hpower, handType); } void LateUpdate() { if (grabPoser) { if (setHandTransform) { skeleton.transform.position = grabPoser.transform.TransformPoint(inverceLocalPosition); skeleton.transform.rotation = grabPoser.transform.rotation * Quaternion.Inverse(grabPoser.GetBlendedPose(skeleton).rotation); skeleton.transform.position = Vector3.Lerp(skeleton.transform.position, transform.parent.TransformPoint(endFramePos), blendToPose); skeleton.transform.rotation = Quaternion.Lerp(skeleton.transform.rotation, endFrameRot, blendToPose); oldInterpolatePos = skeleton.transform.position; oldInterpolateRot = skeleton.transform.rotation; } else { setHandTransform = true; } } else { skeleton.transform.position = Vector3.Lerp(transform.parent.TransformPoint(endFramePos), skeleton.transform.parent.position, blendToPose); skeleton.transform.rotation = Quaternion.Lerp(endFrameRot, skeleton.transform.parent.rotation, blendToPose); } } public void renderModelVisible(bool visible) { if (renderModel) { if (alwayshideController) renderModel.SetMeshRendererState(false); else renderModel.SetMeshRendererState(visible); } } void GrabEnd() { endFramePos = transform.parent.InverseTransformPoint(oldInterpolatePos); endFrameRot = oldInterpolateRot; skeleton.transform.localPosition = Vector3.zero; skeleton.transform.localEulerAngles = Vector3.zero; ///save coord skeleton.BlendToSkeleton(blend); renderModelVisible(!hideController); blendToPose = 0; blendToPoseMoveObject = 0; grabPoser = null; grabInteractible = null; grabType = GrabType.None; } public void DetachHand() { GrabEnd(); } void SelectObject(Vector3 selectPoint, GrabType grabType, Collider[] colliders, ref CustomInteractible interactible) { if (!grabPoser) { colliders = Physics.OverlapSphere(selectPoint, gripRadius, layerColliderChecker); interactible = null; float tempCloseDistance = float.MaxValue; for (int i = 0; i < colliders.Length; i++) { CustomInteractible tempCustomInteractible = colliders[i].GetComponentInParent<CustomInteractible>(); if (tempCustomInteractible != null && tempCustomInteractible.isInteractible && tempCustomInteractible.grabType == grabType) { if (Vector3.Distance(tempCustomInteractible.transform.position, selectPoint) < tempCloseDistance) { tempCloseDistance = Vector3.Distance(tempCustomInteractible.transform.position, selectPoint); interactible = tempCustomInteractible; } } } } else if(grabType == GrabType.Select) // HANDLE SELECT TYPE { if (interactible) { colliders = Physics.OverlapSphere(selectPoint, indexRadius * 2f, layerColliderChecker); if (colliders == null || colliders.Length == 0) { interactible.SendMessage("GrabEnd", this, SendMessageOptions.DontRequireReceiver); GrabEnd(); interactible = null; return; } for (int i = 0; i < colliders.Length; i++) { CustomInteractible tempCustomInteractible = colliders[i].GetComponentInParent<CustomInteractible>(); if (tempCustomInteractible && tempCustomInteractible == interactible) { return; } } interactible.SendMessage("GrabEnd", this, SendMessageOptions.DontRequireReceiver); GrabEnd(); interactible = null; } } } public void SkeletonUpdate() { if (skeleton) { if (grabPoser) { skeleton.BlendToPoser(grabPoser); PivotUpdate(); } } } public void PivotUpdate() { if (grabPoser) { pivotPoser.rotation = transform.rotation * grabPoser.GetBlendedPose(skeleton).rotation; pivotPoser.position = transform.TransformPoint(grabPoser.GetBlendedPose(skeleton).position); } } public Vector3 PointByPoint(Vector3 point) { if (handType == SteamVR_Input_Sources.RightHand) return transform.TransformPoint(Vector3.Scale(new Vector3(-1, 1, 1), point)); if (handType == SteamVR_Input_Sources.LeftHand) return transform.TransformPoint(point); return Vector3.zero; } public void SetEndFramePos() { endFramePos = transform.parent.InverseTransformPoint(skeleton.transform.position); } public void SetBlendPose(float setBlend) { blendToPoseMoveObject = setBlend; } public float GetBlendPose() { if (smoothBlendPhysicsObject) return 1 - blendToPoseMoveObject; else return 1; } void OnDrawGizmosSelected() { Gizmos.DrawWireSphere(PointByPoint(pinchPoint), gripRadius); Gizmos.DrawWireSphere(PointByPoint(gripPoint), pinchRadius); Gizmos.DrawWireSphere(PointByPoint(indexPoint), indexRadius); } }
0
0.835192
1
0.835192
game-dev
MEDIA
0.811678
game-dev
0.924371
1
0.924371
Tencent/behaviac
2,339
test/btunittest/BehaviacData/exported/node_test/fsm/action_ut_1_2.xml
<?xml version="1.0" encoding="utf-8"?> <!--EXPORTED BY TOOL, DON'T MODIFY IT!--> <!--Source File: node_test\fsm\action_ut_1_2.xml--> <behavior name="node_test/fsm/action_ut_1_2" agenttype="AgentNodeTest" version="5"> <pars> <par name="par_go" type="UnityEngine::GameObject*" value="null" /> <par name="par_float_type_0" type="float" value="0" /> <par name="par_float_type_1" type="float" value="0" /> <par name="par_float_type_2" type="float" value="2.7" /> </pars> <node class="DecoratorLoop" id="8"> <property Count="const int -1" /> <property DecorateWhenChildEnds="true" /> <property DoneWithinFrame="false" /> <node class="Sequence" id="0"> <node class="Compute" id="3"> <property Operator="Add" /> <property Opl="float Self.AgentNodeTest::par_float_type_0" /> <property Opr1="const float 0.5" /> <property Opr2="const float 1.3" /> </node> <node class="Action" id="2"> <property Method="Self.AgentNodeTest::setTestVar_2(float Self.AgentNodeTest::par_float_type_0)" /> <property ResultOption="BT_SUCCESS" /> </node> <node class="Assignment" id="1"> <property CastRight="false" /> <property Opl="float Self.AgentNodeTest::par_float_type_1" /> <property Opr="float Self.AgentNodeTest::testVar_2" /> </node> <node class="Compute" id="4"> <property Operator="Add" /> <property Opl="float Self.AgentNodeTest::par_float_type_0" /> <property Opr1="float Self.AgentNodeTest::par_float_type_1" /> <property Opr2="float Self.AgentNodeTest::par_float_type_2" /> </node> <node class="Action" id="5"> <property Method="Self.AgentNodeTest::setTestVar_3(float Self.AgentNodeTest::par_float_type_0)" /> <property ResultOption="BT_SUCCESS" /> </node> <node class="Assignment" id="7"> <property CastRight="false" /> <property Opl="UnityEngine::GameObject Self.AgentNodeTest::par_go" /> <property Opr="Self.AgentNodeTest::createGameObject()" /> </node> <node class="Action" id="6"> <property Method="Self.AgentNodeTest::testGameObject(UnityEngine::GameObject Self.AgentNodeTest::par_go)" /> <property ResultOption="BT_SUCCESS" /> </node> </node> </node> </behavior>
0
0.807102
1
0.807102
game-dev
MEDIA
0.894756
game-dev
0.902678
1
0.902678
ReactiveDrop/reactivedrop_public_src
17,963
src/game/shared/swarm/asw_remote_turret_shared.cpp
#include "cbase.h" #ifdef CLIENT_DLL #define CBaseAnimating C_BaseAnimating #include "c_asw_player.h" #include "c_asw_marine.h" #include "fx.h" #include "soundenvelope.h" #include "c_te_effect_dispatch.h" #include "c_user_message_register.h" #include "c_asw_fx.h" #define CASW_Marine C_ASW_Marine #else #include "EntityFlame.h" #include "asw_player.h" #include "asw_marine.h" #include "ai_network.h" #include "ndebugoverlay.h" #endif #include "asw_gamerules.h" #include "asw_util_shared.h" #include "igamemovement.h" #include "in_buttons.h" #include "asw_remote_turret_shared.h" #include "ammodef.h" #include "fmtstr.h" #include "effect_dispatch_data.h" #include "particle_parse.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" IMPLEMENT_NETWORKCLASS_ALIASED( ASW_Remote_Turret, DT_ASW_Remote_Turret ); BEGIN_NETWORK_TABLE( CASW_Remote_Turret, DT_ASW_Remote_Turret ) #ifdef CLIENT_DLL RecvPropEHandle( RECVINFO( m_hUser ) ), RecvPropFloat( RECVINFO( m_angEyeAngles[0] ) ), RecvPropFloat( RECVINFO( m_angEyeAngles[1] ) ), RecvPropBool( RECVINFO( m_bUpsideDown ) ), RecvPropQAngles( RECVINFO( m_angDefault ) ), RecvPropQAngles( RECVINFO( m_angViewLimit ) ), #else SendPropEHandle( SENDINFO( m_hUser ) ), SendPropAngle( SENDINFO_VECTORELEM( m_angEyeAngles, 0 ), 11, SPROP_CHANGES_OFTEN ), SendPropAngle( SENDINFO_VECTORELEM( m_angEyeAngles, 1 ), 11, SPROP_CHANGES_OFTEN ), SendPropBool( SENDINFO( m_bUpsideDown ) ), SendPropQAngles( SENDINFO( m_angDefault ), 10 ), SendPropQAngles( SENDINFO( m_angViewLimit ), 10 ), #endif END_NETWORK_TABLE() LINK_ENTITY_TO_CLASS( asw_remote_turret, CASW_Remote_Turret ); PRECACHE_WEAPON_REGISTER( asw_remote_turret ); #define ASW_REMOTE_TURRET_MODEL "models/swarm/SentryGun/remoteturret.mdl" ConVar asw_turret_fire_rate( "asw_turret_fire_rate", "0.1", FCVAR_CHEAT | FCVAR_REPLICATED, "Firing rate of remote controlled turrets" ); ConVar asw_turret_turn_rate( "asw_turret_turn_rate", "50.0", FCVAR_CHEAT | FCVAR_REPLICATED, "Turning rate of remote controlled turrets" ); ConVar asw_turret_dmg_override( "asw_turret_dmg_override", "0", FCVAR_CHEAT | FCVAR_REPLICATED, "Overrides remote turret's damage. 0 means no override is done" ); extern ConVar asw_weapon_max_shooting_distance; #ifndef CLIENT_DLL BEGIN_DATADESC( CASW_Remote_Turret ) DEFINE_KEYFIELD( m_bUpsideDown, FIELD_BOOLEAN, "UpsideDown" ), DEFINE_KEYFIELD( m_angViewLimit, FIELD_VECTOR, "viewlimits" ), DEFINE_OUTPUT( m_OnStartedUsing, "OnStartedUsing" ), DEFINE_OUTPUT( m_OnStoppedUsing, "OnStoppedUsing" ), END_DATADESC() #else ConVar asw_turret_debug_limits( "asw_turret_debug_limits", "0", FCVAR_CHEAT, "Prints debug info about turret turning limits" ); #endif // not client CASW_Remote_Turret::CASW_Remote_Turret() #ifdef CLIENT_DLL : m_iv_angEyeAngles( "C_ASW_Remote_Turret::m_iv_angEyeAngles" ) #endif { m_angEyeAngles.Init(); m_iAmmoType = GetAmmoDef()->Index( "ASW_AG" ); m_fNextFireTime = 0; #ifdef CLIENT_DLL m_flNextTurnSound = 0.0f; m_bLastUser = false; m_iFireSequence = -1; m_iIdleSequence = -1; m_iIdleOffSequence = -1; m_iTurnOnSequence = -1; m_iTurnOffSequence = -1; AddVar( &m_angEyeAngles, &m_iv_angEyeAngles, LATCH_SIMULATION_VAR ); #else m_hUser = NULL; #endif } CASW_Remote_Turret::~CASW_Remote_Turret() { } #ifndef CLIENT_DLL void CASW_Remote_Turret::Spawn() { if ( GetModelName() == NULL_STRING ) { SetModelName( AllocPooledStringConstant( ASW_REMOTE_TURRET_MODEL ) ); } BaseClass::Spawn(); Precache(); SetModel( STRING( GetModelName() ) ); SetMoveType( MOVETYPE_NONE ); SetSolid( SOLID_BBOX ); SetCollisionGroup( COLLISION_GROUP_NONE ); m_takedamage = DAMAGE_NO; m_iHealth = 100; m_iMaxHealth = m_iHealth; m_angDefault = GetLocalAngles(); if ( m_angViewLimit.GetX() <= 0 ) m_angViewLimit.SetX( 60 ); if ( m_angViewLimit.GetY() <= 0 ) m_angViewLimit.SetY( 60 ); } void CASW_Remote_Turret::Precache() { PrecacheModel( ASW_REMOTE_TURRET_MODEL ); PrecacheScriptSound( "ASW_Sentry.Fire" ); PrecacheScriptSound( "ASW_Sentry.Turn" ); BaseClass::Precache(); } #endif // not client void CASW_Remote_Turret::SetupMove( CBasePlayer *player, CUserCmd *ucmd, IMoveHelper *pHelper, CMoveData *move ) { // only care about facing and firing move->m_vecViewAngles = ucmd->viewangles; // todo: clamp facing angle here? move->m_nButtons = ucmd->buttons; } void CASW_Remote_Turret::SmoothTurretAngle( QAngle &ang ) { float dt = MIN( 0.2, gpGlobals->frametime ); ang[YAW] = ASW_ClampYaw( asw_turret_turn_rate.GetFloat(), m_angEyeAngles[YAW], ang[YAW], dt ); ang[PITCH] = ASW_ClampYaw( asw_turret_turn_rate.GetFloat() * 0.8f, m_angEyeAngles[PITCH], ang[PITCH], dt ); m_angEyeAngles = ang;//GetMarine()->EyeAngles()[YAW]; } void CASW_Remote_Turret::ProcessMovement( CBasePlayer *pPlayer, CMoveData *pMoveData ) { QAngle angTemp = RealEyeAngles(); m_angEyeAngles = angTemp; SetAbsAngles( m_angEyeAngles ); // check for firing bool bAttack1, bAttack2, bReload; GetButtons( bAttack1, bAttack2, bReload ); if ( bAttack1 && gpGlobals->curtime >= m_fNextFireTime ) { FireTurret( pPlayer ); } } #ifdef CLIENT_DLL const QAngle &CASW_Remote_Turret::RealEyeAngles() { C_ASW_Marine *pMarine = m_hUser.Get(); if ( pMarine && pMarine->IsInhabited() && pMarine->GetCommander() == C_ASW_Player::GetLocalASWPlayer() ) { return C_ASW_Player::GetLocalASWPlayer()->EyeAngles(); } return m_angEyeAngles; } const QAngle &CASW_Remote_Turret::EyeAngles() { return m_angEyeAngles; } int CASW_Remote_Turret::GetMuzzleAttachment( void ) { return LookupAttachment( "muzzle" ); } float CASW_Remote_Turret::GetMuzzleFlashScale( void ) { return 1.5f; } void CASW_Remote_Turret::ProcessMuzzleFlashEvent() { // attach muzzle flash particle system effect int iAttachment = GetMuzzleAttachment(); if ( iAttachment > 0 ) { float flScale = GetMuzzleFlashScale(); FX_MuzzleEffectAttached( flScale, GetRefEHandle(), iAttachment, NULL, false ); } BaseClass::ProcessMuzzleFlashEvent(); } void CASW_Remote_Turret::OnDataChanged( DataUpdateType_t updateType ) { if ( updateType == DATA_UPDATE_CREATED ) { // force an update m_bLastUser = !m_hUser; // assume m_bUpsideDown never changes! m_iFireSequence = LookupSequence( "fire" ); m_iIdleSequence = LookupSequence( "idle" ); m_iIdleOffSequence = LookupSequence( m_bUpsideDown ? "idle_off_reversed" : "idle_off" ); m_iTurnOnSequence = LookupSequence( m_bUpsideDown ? "turn_on_reversed" : "turn_on" ); m_iTurnOffSequence = LookupSequence( m_bUpsideDown ? "turn_off_reversed" : "turn_off" ); SetNextClientThink( gpGlobals->curtime ); } BaseClass::OnDataChanged( updateType ); } void CASW_Remote_Turret::ClientThink( void ) { float yawdiff = abs( AngleDiff( m_LastAngle[YAW], m_angEyeAngles[YAW] ) ); float pitchdiff = abs( AngleDiff( m_LastAngle[PITCH], m_angEyeAngles[PITCH] ) ); bool bPlaySound = yawdiff > 1 || pitchdiff > 1; if ( bPlaySound && gpGlobals->curtime >= m_flNextTurnSound ) { EmitSound( "ASW_Sentry.Turn" ); m_flNextTurnSound = gpGlobals->curtime + 0.5f; m_LastAngle = m_angEyeAngles; } bool bHasUser = !!m_hUser; if ( bHasUser != m_bLastUser ) { m_bLastUser = bHasUser; ResetSequence( bHasUser ? m_iTurnOnSequence : m_iTurnOffSequence ); } if ( m_hUser.Get() ) { SetNextClientThink( gpGlobals->curtime + 0.1f ); } else { SetNextClientThink( gpGlobals->curtime + 1.0f ); } } void CASW_Remote_Turret::ReachedEndOfSequence() { bool bHasUser = !!m_hUser; ResetSequence( bHasUser ? m_iIdleSequence : m_iIdleOffSequence ); } #else const QAngle &CASW_Remote_Turret::RealEyeAngles() { CASW_Marine *pMarine = m_hUser.Get(); if ( pMarine && pMarine->IsInhabited() && pMarine->GetCommander() ) { return pMarine->GetCommander()->EyeAngles(); } return m_angEyeAngles; } const QAngle &CASW_Remote_Turret::EyeAngles() { return m_angEyeAngles; } #endif Vector CASW_Remote_Turret::GetTurretCamPosition() { int iAttachment = LookupAttachment( "camera" ); if ( iAttachment > 0 ) { Vector camOrigin; QAngle camAngles; if ( GetAttachment( iAttachment, camOrigin, camAngles ) ) { return camOrigin; } } return GetAbsOrigin(); } Vector CASW_Remote_Turret::GetTurretMuzzlePosition() { Vector vecMuzzleOffset( 41.92, 0, 8.0 ); Vector vecMuzzleOffsetTransformed( 0, 0, 0 ); matrix3x4_t matrix; QAngle angFacing = EyeAngles(); if ( m_bUpsideDown ) angFacing[ROLL] += 180; AngleMatrix( angFacing, matrix ); VectorTransform( vecMuzzleOffset, matrix, vecMuzzleOffsetTransformed ); return vecMuzzleOffsetTransformed + GetAbsOrigin(); } void CASW_Remote_Turret::GetButtons( bool &bAttack1, bool &bAttack2, bool &bReload ) { CASW_Marine *pMarine = m_hUser.Get(); if ( pMarine && pMarine->IsInhabited() && pMarine->GetCommander() ) { bAttack1 = !!( pMarine->GetCommander()->m_nButtons & IN_ATTACK ); bAttack2 = !!( pMarine->GetCommander()->m_nButtons & IN_ATTACK2 ); bReload = !!( pMarine->GetCommander()->m_nButtons & IN_RELOAD ); return; } bAttack1 = false; bAttack2 = false; bReload = false; } void CASW_Remote_Turret::FireTurret( CBasePlayer *pPlayer ) { if ( !pPlayer ) return; Vector vecShootOrigin, vecShootDir; vecShootOrigin = GetTurretMuzzlePosition(); #ifdef CLIENT_DLL QAngle angFacing = EyeAngles(); #else autoaim_params_t params; params.m_fScale = 2.0f; params.m_fMaxDist = asw_weapon_max_shooting_distance.GetFloat(); QAngle angFacing = EyeAngles() + AutoaimDeflection( vecShootOrigin, EyeAngles(), params ); #endif AngleVectors( angFacing, &vecShootDir ); FireBulletsInfo_t info( 1, vecShootOrigin, vecShootDir, GetBulletSpread(), asw_weapon_max_shooting_distance.GetFloat(), m_iAmmoType ); info.m_flDamage = GetSentryDamage(); info.m_pAttacker = this; info.m_iTracerFreq = 1; FireBullets( info ); EmitSound( "ASW_Sentry.Fire" ); CEffectData data; data.m_vOrigin = GetAbsOrigin(); CPASFilter filter( data.m_vOrigin ); DispatchParticleEffect( "muzzle_sentrygun", PATTACH_POINT_FOLLOW, this, "muzzle", false, -1, &filter ); m_fNextFireTime = gpGlobals->curtime + asw_turret_fire_rate.GetFloat(); } CASW_Marine *CASW_Remote_Turret::GetUser() { return m_hUser.Get(); } #ifndef CLIENT_DLL QAngle CASW_Remote_Turret::AutoaimDeflection( Vector &vecSrc, const QAngle &eyeAngles, autoaim_params_t &params ) { float bestscore; float score; Vector bestdir; CBaseEntity *bestent; trace_t tr; Vector v_forward, v_right, v_up; AngleVectors( eyeAngles, &v_forward, &v_right, &v_up ); // try all possible entities bestdir = v_forward; bestscore = 0.0f; bestent = NULL; // Reset this data params.m_bOnTargetNatural = false; CBaseEntity *pIgnore = NULL; CTraceFilterSkipTwoEntities traceFilter( this, pIgnore, COLLISION_GROUP_NONE ); UTIL_TraceLine( vecSrc, vecSrc + bestdir * MAX_COORD_FLOAT, MASK_SHOT, &traceFilter, &tr ); CBaseEntity *pEntHit = tr.m_pEnt; if ( pEntHit && pEntHit->m_takedamage != DAMAGE_NO && pEntHit->GetHealth() > 0 ) { // don't look through water if ( !( ( GetWaterLevel() != 3 && pEntHit->GetWaterLevel() == 3 ) || ( GetWaterLevel() == 3 && pEntHit->GetWaterLevel() == 0 ) ) ) { if ( pEntHit->GetFlags() & FL_AIMTARGET ) { // Player is already on target naturally, don't autoaim. // Fill out the autoaim_params_t struct, though. params.m_hAutoAimEntity.Set( pEntHit ); params.m_vecAutoAimDir = bestdir; params.m_vecAutoAimPoint = tr.endpos; params.m_bAutoAimAssisting = false; params.m_bOnTargetNatural = true; } return vec3_angle; } } int count = AimTarget_ListCount(); if ( count ) { CBaseEntity **pList = ( CBaseEntity ** )stackalloc( sizeof( CBaseEntity * ) * count ); AimTarget_ListCopy( pList, count ); for ( int i = 0; i < count; i++ ) { Vector center; Vector dir; CBaseEntity *pEntity = pList[i]; // Don't shoot yourself if ( pEntity == this ) continue; if ( !pEntity->IsAlive() || !pEntity->edict() ) continue; // don't look through water if ( ( GetWaterLevel() != 3 && pEntity->GetWaterLevel() == 3 ) || ( GetWaterLevel() == 3 && pEntity->GetWaterLevel() == 0 ) ) continue; // don't autoaim at marines if ( m_hUser && m_hUser->IRelationType( pEntity ) == D_LI ) continue; // Don't autoaim at the noisy bodytarget, this makes the autoaim crosshair wobble. center = pEntity->WorldSpaceCenter(); dir = ( center - vecSrc ); float dist = dir.Length2D(); VectorNormalize( dir ); // Skip if out of range. if ( dist > params.m_fMaxDist ) continue; float dot = DotProduct( dir, v_forward ); // make sure it's in front of the player if ( dot < 0 ) continue; score = GetAutoaimScore( vecSrc, v_forward, pEntity->GetAutoAimCenter(), pEntity, params.m_fScale ); if ( score <= bestscore ) { continue; } UTIL_TraceLine( vecSrc, center, MASK_SHOT, &traceFilter, &tr ); if ( tr.fraction != 1.0 && tr.m_pEnt != pEntity ) { // Msg( "hit %s, can't see %s\n", STRING( tr.u.ent->classname ), STRING( pEdict->classname ) ); continue; } // This is the best candidate so far. bestscore = score; bestent = pEntity; bestdir = dir; } if ( bestent ) { QAngle bestang; VectorAngles( bestdir, bestang ); bestang -= eyeAngles; // Autoaim detected a target for us. Aim automatically at its bodytarget. params.m_hAutoAimEntity.Set( bestent ); params.m_vecAutoAimDir = bestdir; params.m_vecAutoAimPoint = bestent->BodyTarget( vecSrc, false ); params.m_bAutoAimAssisting = true; return bestang; } } return QAngle( 0, 0, 0 ); } float CASW_Remote_Turret::GetAutoaimScore( const Vector &eyePosition, const Vector &viewDir, const Vector &vecTarget, CBaseEntity *pTarget, float fScale ) { float radiusSqr; float targetRadiusSqr = Square( ( pTarget->GetAutoAimRadius() * fScale ) ); Vector vecNearestPoint = PointOnLineNearestPoint( eyePosition, eyePosition + viewDir * 8192, vecTarget ); Vector vecDiff = vecTarget - vecNearestPoint; radiusSqr = vecDiff.LengthSqr(); if ( radiusSqr <= targetRadiusSqr ) { float score; score = 1.0f - ( radiusSqr / targetRadiusSqr ); Assert( score >= 0.0f && score <= 1.0f ); return score; } // 0 means no score- doesn't qualify for autoaim. return 0.0f; } int CASW_Remote_Turret::UpdateTransmitState() { return SetTransmitState( FL_EDICT_ALWAYS ); } // always send this entity to players (for now...) int CASW_Remote_Turret::ShouldTransmit( const CCheckTransmitInfo *pInfo ) { return FL_EDICT_ALWAYS; } void CASW_Remote_Turret::StopUsingTurret() { m_OnStoppedUsing.FireOutput( m_hUser, m_hComputerArea ); m_hUser = NULL; m_hComputerArea = NULL; DispatchUpdateTransmitState(); } void CASW_Remote_Turret::StartedUsingTurret( CASW_Marine *pUser, CBaseEntity *pComputerArea ) { m_OnStartedUsing.FireOutput( pUser, pComputerArea ); m_hUser = pUser; m_hComputerArea = pComputerArea; DispatchUpdateTransmitState(); } #else // client // clamp view angles void CASW_Remote_Turret::CreateMove( float flInputSampleTime, CUserCmd *pCmd ) { QAngle angDefault = m_angDefault; if ( GetMoveParent() ) { angDefault += GetMoveParent()->GetAbsAngles(); } QAngle angMax = angDefault + m_angViewLimit; QAngle angMin = angDefault - m_angViewLimit; // limit all 3 axes of rotation if ( asw_turret_debug_limits.GetBool() ) Msg( "Limiting turret:" ); for ( int i = 0; i < 3; i++ ) { float fDiff = UTIL_AngleDiff( pCmd->viewangles[i], angDefault[i] ); float fMinDiff = UTIL_AngleDiff( angMin[i], angDefault[i] ); float fMaxDiff = UTIL_AngleDiff( angMax[i], angDefault[i] ); if ( asw_turret_debug_limits.GetBool() ) Msg( "%d: fdiff=%f mindiff=%f maxdiff=%f min=%f max=%f ang=%f def=%f", i, fDiff, fMinDiff, fMaxDiff, angMin[i], angMax[i], pCmd->viewangles[i], angDefault[i] ); if ( fMinDiff <= -180 || fMinDiff >= 180 ) // if 360 rotation is allowed, skip any clamping for this axis continue; if ( fDiff < fMinDiff ) pCmd->viewangles[i] = angMin[i]; else if ( fDiff > fMaxDiff ) pCmd->viewangles[i] = angMax[i]; } if ( asw_turret_debug_limits.GetBool() ) Msg( "\n" ); } #endif int CASW_Remote_Turret::GetSentryDamage() { if ( asw_turret_dmg_override.GetFloat() > 0 ) return asw_turret_dmg_override.GetFloat(); if ( !ASWGameRules() ) return 10; return MAX( 25 - ( ( ASWGameRules()->GetMissionDifficulty() - 5 ) * 0.75f ), 10 ); } void CASW_Remote_Turret::MakeTracer( const Vector &vecTracerSrc, const trace_t &tr, int iTracerType ) { #ifdef GAME_DLL CBroadcastRecipientFilter filter; if ( gpGlobals->maxClients <= 1 ) { filter.SetIgnorePredictionCull( true ); } const char *szTracer = "ASWRemoteTurretTracer"; UserMessageBegin( filter, szTracer ); WRITE_SHORT( entindex() ); WRITE_FLOAT( tr.endpos.x ); WRITE_FLOAT( tr.endpos.y ); WRITE_FLOAT( tr.endpos.z ); MessageEnd(); #else ASWRemoteTurretTracer( tr.endpos ); #endif } #ifdef CLIENT_DLL void __MsgFunc_ASWRemoteTurretTracer( bf_read &msg ) { int iSentry = msg.ReadShort(); C_BaseEntity *pEnt = ClientEntityList().GetEnt( iSentry ); Vector vecEnd; vecEnd.x = msg.ReadFloat(); vecEnd.y = msg.ReadFloat(); vecEnd.z = msg.ReadFloat(); if ( pEnt && pEnt->Classify() == CLASS_ASW_REMOTE_TURRET ) { CASW_Remote_Turret *pSentry = assert_cast< CASW_Remote_Turret * >( pEnt ); pSentry->ASWRemoteTurretTracer( vecEnd ); } } USER_MESSAGE_REGISTER( ASWRemoteTurretTracer ); void CASW_Remote_Turret::ASWRemoteTurretTracer( const Vector &vecEnd ) { MDLCACHE_CRITICAL_SECTION(); Vector vecStart; QAngle vecAngles; if ( IsDormant() ) return; ResetSequence( m_iFireSequence ); C_BaseAnimating::PushAllowBoneAccess( true, false, "remoteturret" ); // Get the muzzle origin if ( !GetAttachment( GetMuzzleAttachment(), vecStart, vecAngles ) ) { return; } ASWDoParticleTracer( "tracer_autogun", vecStart, vecEnd ); C_BaseAnimating::PopBoneAccess( "remoteturret" ); } #endif
0
0.932661
1
0.932661
game-dev
MEDIA
0.968171
game-dev
0.83812
1
0.83812
LogicalError/realtime-CSG-for-unity
37,140
Plugins/Editor/Scripts/Data/SceneQuery/SceneQueryUtility.cs
using System; using System.Collections.Generic; using UnityEngine; using System.Linq; using UnityEngine.SceneManagement; using UnityEditor; using RealtimeCSG; using RealtimeCSG.Legacy; using RealtimeCSG.Components; using Object = UnityEngine.Object; using RealtimeCSG.Foundation; namespace InternalRealtimeCSG { internal sealed class PointSelection { public PointSelection(int brushNodeID, int pointIndex) { BrushNodeID = brushNodeID; PointIndex = pointIndex; } public readonly int BrushNodeID; public readonly int PointIndex; } internal static class SceneQueryUtility { #region GetAllComponentsInScene public static List<T> GetAllComponentsInScene<T>(Scene scene) where T : Component { var items = new List<T>(); var rootItems = GetRootGameObjectsInScene(scene); for (int i = 0; i < rootItems.Length; i++) { var root = rootItems[i]; if (!root) continue; items.AddRange(root.GetComponentsInChildren<T>(true)); } return items; } public static GameObject[] GetRootGameObjectsInScene(Scene scene) { if (scene.isLoaded) return scene.GetRootGameObjects(); var rootLookup = new HashSet<Transform>(); var transforms = Object.FindObjectsOfType<Transform>(); for (int i = 0; i < transforms.Length;i++) rootLookup.Add(transforms[i].root); var rootArray = rootLookup.ToArray(); var gameObjectArray = new GameObject[rootArray.Length]; for (int i = 0; i < rootArray.Length; i++) gameObjectArray[i] = rootArray[i].gameObject; return gameObjectArray; } #endregion #region GetFirstGameObjectInSceneWithName public static GameObject GetFirstGameObjectInSceneWithName(Scene scene, string name) { foreach (var root in scene.GetRootGameObjects()) { if (!root) continue; if (root.name == name) return root; foreach (var transform in root.GetComponentsInChildren<Transform>(true)) { if (transform.name == name) return transform.gameObject; } } return null; } #endregion #region GetUniqueHiddenGameObjectInSceneWithName internal static GameObject GetUniqueHiddenGameObjectInSceneWithName(Scene scene, string name) { if (!scene.IsValid() || !scene.isLoaded) return null; var rootGameObjects = scene.GetRootGameObjects(); GameObject foundRoot = null; for (int i = 0; i < rootGameObjects.Length; i++) { var root = rootGameObjects[i]; if (!root) continue; if (root.hideFlags != HideFlags.None && root.name == name) { if (foundRoot) { Object.DestroyImmediate(root); continue; } foundRoot = root; } var rootChildren = root.GetComponentsInChildren<Transform>(true); for (int j = 0; j < rootChildren.Length; j++) { var child = rootChildren[j]; if (child == root) continue; if (!child) continue; if (child.hideFlags == HideFlags.None || child.name != name) continue; if (foundRoot) { Object.DestroyImmediate(child.gameObject); continue; } foundRoot = child.gameObject; } } return foundRoot; } #endregion #region GetGroupObjectIfObjectIsPartOfGroup public static GameObject GetGroupGameObjectIfObjectIsPartOfGroup(GameObject gameObject) { if (gameObject == null) return null; var node = gameObject.GetComponentInChildren<CSGNode>(); if (!node) return gameObject; var operation = GetGroupOperationForNode(node); return operation == null ? gameObject : operation.gameObject; } #endregion internal static bool GameObjectContainsAttribute<T>(GameObject go) where T : Attribute { var behaviours = go.GetComponents(typeof(Component)); for (var index = 0; index < behaviours.Length; index++) { var behaviour = behaviours[index]; if (behaviour == null) continue; var behaviourType = behaviour.GetType(); if (behaviourType.GetCustomAttributes(typeof(T), true).Length > 0) return true; } return false; } internal static GameObject FindSelectionBase(GameObject go) { if (go == null) return null; #if UNITY_2018_3_OR_NEWER Transform prefabBase = null; if (PrefabUtility.IsPartOfNonAssetPrefabInstance(go)) { prefabBase = PrefabUtility.GetOutermostPrefabInstanceRoot(go).transform; } #endif GameObject group = null; Transform groupTransform = null; var node = go.GetComponentInChildren<CSGNode>(); if (node) { var operation = GetGroupOperationForNode(node); group = (operation == null) ? null : operation.gameObject; groupTransform = (operation == null) ? null : operation.transform; } Transform tr = go.transform; while (tr != null) { #if UNITY_2018_3_OR_NEWER if (tr == prefabBase) return tr.gameObject; #endif if (tr == groupTransform) return group; if (GameObjectContainsAttribute<SelectionBaseAttribute>(tr.gameObject)) return tr.gameObject; tr = tr.parent; } return go; } #region GetGroupOperationForNode (private) private static CSGOperation GetGroupOperationForNode(CSGNode node) { if (!node) return null; var parent = node.transform.parent; while (parent) { var model = parent.GetComponent<CSGModel>(); if (model) return null; var parentOp = parent.GetComponent<CSGOperation>(); if (parentOp && //!parentOp.PassThrough && parentOp.HandleAsOne) return parentOp; parent = parent.transform.parent; } return null; } #endregion #region GetTopMostGroupForNode public static CSGNode GetTopMostGroupForNode(CSGNode node) { if (!node) return null; var topSelected = node; var parent = node.transform.parent; while (parent) { var model = parent.GetComponent<CSGModel>(); if (model) break; var parentOp = parent.GetComponent<CSGOperation>(); if (parentOp && parentOp.HandleAsOne && !parentOp.PassThrough) topSelected = parentOp; parent = parent.transform.parent; } return topSelected; } #endregion #region DeselectAllChildBrushes (private) private static void DeselectAllChildBrushes(Transform transform, HashSet<GameObject> objectsInFrustum) { var visibleLayers = Tools.visibleLayers; for (int i = 0, childCount = transform.childCount; i < childCount; i++) { var childTransform = transform.GetChild(i); var childNode = childTransform.GetComponent<CSGNode>(); if (!childNode || (childNode is CSGModel) || ((1 << childNode.gameObject.layer) & visibleLayers) == 0) continue; var childGameObject = childTransform.gameObject; objectsInFrustum.Remove(childGameObject); DeselectAllChildBrushes(childTransform.transform, objectsInFrustum); } } #endregion #region AreAllBrushesSelected (private) private static bool AreAllBrushesSelected(Transform transform, HashSet<GameObject> objectsInFrustum) { var visibleLayers = Tools.visibleLayers; var allChildrenSelected = true; var i = 0; var childCount = transform.childCount; for (; i < childCount; i++) { var childTransform = transform.GetChild(i); var childNode = childTransform.GetComponent<CSGNode>(); if (!childNode || (childNode is CSGModel) || ((1 << childNode.gameObject.layer) & visibleLayers) == 0) { continue; } var childGameObject = childTransform.gameObject; if (!childTransform.gameObject.activeInHierarchy) { objectsInFrustum.Remove(childGameObject); continue; } if (objectsInFrustum.Contains(childGameObject)) { objectsInFrustum.Remove(childGameObject); continue; } var childOperation = childNode as CSGOperation; if (childOperation == null || !childOperation.PassThrough) { objectsInFrustum.Remove(childGameObject); allChildrenSelected = false; break; } var result = AreAllBrushesSelected(childTransform, objectsInFrustum); objectsInFrustum.Remove(childGameObject); if (result) continue; objectsInFrustum.Remove(childGameObject); allChildrenSelected = false; break; } if (allChildrenSelected) return true; for (; i < childCount; i++) { var childTransform = transform.GetChild(i); var childNode = childTransform.GetComponent<CSGNode>(); if (!childNode || (childNode is CSGModel)) continue; var childGameObject = childTransform.gameObject; objectsInFrustum.Remove(childGameObject); DeselectAllChildBrushes(childTransform.transform, objectsInFrustum); } return false; } #endregion #region GetItemsInFrustum public static bool GetItemsInFrustum(Plane[] planes, HashSet<GameObject> objectsInFrustum) { if (objectsInFrustum == null) return false; objectsInFrustum.Clear(); var found = false; foreach (var model in InternalCSGModelManager.Models) { if (!ModelTraits.WillModelRender(model)) continue; found = InternalCSGModelManager.External.GetItemsInFrustum(model, planes, objectsInFrustum) || found; } var visibleLayers = Tools.visibleLayers; var items = objectsInFrustum.ToArray(); for (var i = items.Length - 1; i >= 0; i--) { var child = items[i]; var node = child.GetComponent<CSGNode>(); if (!node || ((1 << node.gameObject.layer) & visibleLayers) == 0) continue; if (!objectsInFrustum.Contains(child)) continue; while (true) { var parent = GetGroupOperationForNode(node); if (!parent || !AreAllBrushesSelected(parent.transform, objectsInFrustum)) break; objectsInFrustum.Add(parent.gameObject); node = parent; } } return found; } #endregion #region GetPointsInFrustum internal static PointSelection[] GetPointsInFrustum(Camera camera, Plane[] planes, CSGBrush[] brushes, ControlMeshState[] controlMeshStates, bool ignoreHiddenPoints) { var pointSelection = new List<PointSelection>(); for (var t = 0; t < brushes.Length; t++) { var targetMeshState = controlMeshStates[t]; if (targetMeshState == null) continue; var cameraState = targetMeshState.GetCameraState(camera, false); for (var p = 0; p < targetMeshState.WorldPoints.Length; p++) { if (ignoreHiddenPoints && cameraState.WorldPointBackfaced[p]) continue; var point = targetMeshState.WorldPoints[p]; var found = true; for (var i = 0; i < 6; i++) { if (!(planes[i].GetDistanceToPoint(point) > MathConstants.DistanceEpsilon)) continue; found = false; break; } if (found) { pointSelection.Add(new PointSelection(t, p)); } } } return pointSelection.ToArray(); } #endregion #region DeepSelection (private) private static List<GameObject> deepClickIgnoreGameObjectList = new List<GameObject>(); private static List<CSGBrush> deepClickIgnoreBrushList = new List<CSGBrush>(); private static Vector2 _prevSceenPos = new Vector2(float.PositiveInfinity, float.PositiveInfinity); private static Camera _prevCamera; private static void ResetDeepClick(bool resetPosition = true) { deepClickIgnoreGameObjectList.Clear(); deepClickIgnoreBrushList.Clear(); if (resetPosition) { _prevSceenPos = new Vector2(float.PositiveInfinity, float.PositiveInfinity); _prevCamera = null; } } #endregion #region Find..xx..Intersection #region FindClickWorldIntersection public class HideFlagsState { public Dictionary<UnityEngine.GameObject, CSGModel> generatedComponents; public Dictionary<UnityEngine.GameObject, HideFlags> hideFlags; } public static HideFlagsState BeginPicking(GameObject[] ignoreGameObjects) { var state = new HideFlagsState() { generatedComponents = new Dictionary<UnityEngine.GameObject, CSGModel>(), hideFlags = new Dictionary<UnityEngine.GameObject, HideFlags>() }; foreach(var model in CSGModelManager.GetAllModels()) { if (!model.generatedMeshes) continue; var renderers = model.generatedMeshes.GetComponentsInChildren<Renderer>(); if (renderers != null) { foreach (var renderer in renderers) state.generatedComponents[renderer.gameObject] = model; } var colliders = model.generatedMeshes.GetComponentsInChildren<Collider>(); if (colliders != null) { foreach (var collider in colliders) state.generatedComponents[collider.gameObject] = model; } } if (state.generatedComponents != null) { foreach(var pair in state.generatedComponents) { var gameObject = pair.Key; var model = pair.Value; state.hideFlags[gameObject] = gameObject.hideFlags; if (ignoreGameObjects != null && ArrayUtility.Contains(ignoreGameObjects, model.gameObject)) { gameObject.hideFlags = HideFlags.HideInInspector | HideFlags.HideInHierarchy; } else { gameObject.hideFlags = HideFlags.None; } } } return state; } public static CSGModel EndPicking(HideFlagsState state, UnityEngine.GameObject pickedObject) { if (state == null || state.hideFlags == null) return null; foreach (var pair in state.hideFlags) pair.Key.hideFlags = pair.Value; if (object.Equals(pickedObject, null)) return null; if (state.generatedComponents == null) return null; CSGModel model; if (state.generatedComponents.TryGetValue(pickedObject, out model)) return model; return null; } static GameObject FindFirstWorldIntersection(Camera camera, Vector2 screenPos, Vector3 worldRayStart, Vector3 worldRayEnd, out MeshRenderer meshRenderer, out int materialIndex, List<GameObject> ignoreGameObjects = null, List<CSGBrush> ignoreBrushes = null, bool ignoreInvisibleSurfaces = true) { meshRenderer = null; materialIndex = 0; var wireframeShown = CSGSettings.IsWireframeShown(camera); TryAgain: CSGModel model; GameObject gameObject = null; var ignoreGameObjectArray = (ignoreGameObjects == null || ignoreGameObjects.Count == 0) ? null : ignoreGameObjects.ToArray(); { var flagState = BeginPicking(ignoreGameObjectArray); try { gameObject = HandleUtility.PickGameObject(screenPos, ignoreGameObjectArray, out materialIndex); } finally { model = EndPicking(flagState, gameObject); } } if (!object.Equals(gameObject, null) && model) { if (ignoreGameObjects != null && ignoreGameObjects.Contains(model.gameObject)) { Debug.Assert(false); } else { LegacyBrushIntersection[] _deepClickIntersections; var ignoreBrushesArray = (ignoreGameObjects == null || ignoreGameObjects.Count == 0) ? null : ignoreBrushes.ToArray(); if (FindWorldIntersection(model, worldRayStart, worldRayEnd, out _deepClickIntersections, ignoreInvisibleSurfaces: ignoreInvisibleSurfaces && !wireframeShown, ignoreUnrenderables: !wireframeShown, ignoreBrushes: ignoreBrushesArray)) { var visibleLayers = Tools.visibleLayers; for (int i = 0; i < _deepClickIntersections.Length; i++) { gameObject = _deepClickIntersections[i].gameObject; if (((1 << gameObject.layer) & visibleLayers) == 0) continue; return gameObject; } } if (ignoreGameObjects != null) { ignoreGameObjects.Add(model.gameObject); foreach (var component in model.generatedMeshes.GetComponentsInChildren<GeneratedMeshInstance>()) ignoreGameObjects.Add(component.gameObject); goto TryAgain; } } // Try finding a regular unity object instead gameObject = HandleUtility.PickGameObject(screenPos, false, ignoreGameObjectArray); } // If we really didn't find anything, just return null if (ReferenceEquals(gameObject, null) || !gameObject) return null; // Make sure our found gameobject isn't sneakily a CSG related object (should not happen at this point) if (!gameObject.GetComponent<CSGModel>() && !gameObject.GetComponent<CSGBrush>() && !gameObject.GetComponent<CSGOperation>() && !gameObject.GetComponent<GeneratedMeshInstance>() && !gameObject.GetComponent<GeneratedMeshes>()) { meshRenderer = gameObject.GetComponent<MeshRenderer>(); return gameObject; } // If we're not ignoring something, just return null after all if (ignoreGameObjects == null) return null; // Ignore this object and try again (might've been blocking a model) ignoreGameObjects.Add(gameObject); goto TryAgain; } public static bool FindClickWorldIntersection(Camera camera, Vector2 screenPos, out GameObject foundObject, bool ignoreInvisibleSurfaces = true, bool ignoreDeepClick = false) { MeshRenderer meshRenderer = null; int materialIndex= 0; return FindClickWorldIntersection(camera, screenPos, out foundObject, out meshRenderer, out materialIndex, ignoreInvisibleSurfaces, ignoreDeepClick); } public static void ClearDeepClick() { clearDeepClick = true; } static bool clearDeepClick = false; public static bool FindClickWorldIntersection(Camera camera, Vector2 screenPos, out GameObject foundObject, out MeshRenderer meshRenderer, out int materialIndex, bool ignoreInvisibleSurfaces = true, bool ignoreDeepClick = false) { meshRenderer = null; materialIndex = 0; foundObject = null; if (!camera) return false; var worldRay = HandleUtility.GUIPointToWorldRay(screenPos); var worldRayStart = worldRay.origin; var worldRayVector = (worldRay.direction * (camera.farClipPlane - camera.nearClipPlane)); var worldRayEnd = worldRayStart + worldRayVector; // If we moved our mouse, reset our ignore list if (_prevSceenPos != screenPos || _prevCamera != camera || ignoreDeepClick || clearDeepClick) { ResetDeepClick(); clearDeepClick = false; } _prevSceenPos = screenPos; _prevCamera = camera; // Get the first click that is not in our ignore list foundObject = FindFirstWorldIntersection(camera, screenPos, worldRayStart, worldRayEnd, out meshRenderer, out materialIndex, deepClickIgnoreGameObjectList, deepClickIgnoreBrushList, ignoreInvisibleSurfaces); // If we haven't found anything, try getting the first item in our list that's either a brush or a regular gameobject (loop around) if (object.Equals(foundObject, null)) { bool found = false; for (int i = 0; i < deepClickIgnoreGameObjectList.Count; i++) { foundObject = deepClickIgnoreGameObjectList[i]; // We don't want models or mesh containers since they're in this list to skip, and should never be selected if (!foundObject || foundObject.GetComponent<CSGModel>() || foundObject.GetComponent<GeneratedMeshInstance>() || foundObject.GetComponent<GeneratedMeshes>()) continue; found = true; break; } if (!found) { // We really didn't find anything foundObject = null; ResetDeepClick(); return false; } else { // Reset our list so we only skip our current selection on the next click ResetDeepClick( resetPosition: false // But make sure we remember our current mouse position ); } } // Remember our gameobject/brush so we don't select it on the next click var brush = foundObject.GetComponent<CSGBrush>(); if (brush) deepClickIgnoreBrushList.Add(brush); deepClickIgnoreGameObjectList.Add(foundObject); return true; } #endregion #region FindMeshIntersection public static LegacyBrushIntersection FindMeshIntersection(Camera camera, Vector2 screenPos, CSGBrush[] ignoreBrushes = null, HashSet<Transform> ignoreTransforms = null) { var worldRay = HandleUtility.GUIPointToWorldRay(screenPos); var hit = HandleUtility.RaySnap(worldRay); while (hit != null) { var rh = (RaycastHit)hit; if (ignoreTransforms != null && ignoreTransforms.Contains(rh.transform)) { worldRay.origin = rh.point + (worldRay.direction * 0.00001f); hit = HandleUtility.RaySnap(worldRay); continue; } // Check if it's a mesh ... if (rh.transform.GetComponent<MeshRenderer>() && // .. but not one we generated !rh.transform.GetComponent<CSGNode>() && !rh.transform.GetComponent<GeneratedMeshInstance>()) { return new LegacyBrushIntersection { brushNodeID = CSGNode.InvalidNodeID, surfaceIndex = -1, worldIntersection = rh.point, worldPlane = new CSGPlane(-rh.normal, rh.point) }; } break; } LegacyBrushIntersection intersection; if (FindWorldIntersection(camera, worldRay, out intersection, ignoreBrushes: ignoreBrushes)) return intersection; var gridPlane = RealtimeCSG.CSGGrid.CurrentGridPlane; var intersectionPoint = gridPlane.RayIntersection(worldRay); if (float.IsNaN(intersectionPoint.x) || float.IsNaN(intersectionPoint.y) || float.IsNaN(intersectionPoint.z) || float.IsInfinity(intersectionPoint.x) || float.IsInfinity(intersectionPoint.y) || float.IsInfinity(intersectionPoint.z)) { intersectionPoint = worldRay.GetPoint(10); return new LegacyBrushIntersection { brushNodeID = CSGNode.InvalidNodeID, surfaceIndex = -1, worldIntersection = MathConstants.zeroVector3, worldPlane = new CSGPlane(gridPlane.normal, intersectionPoint) }; } return new LegacyBrushIntersection { brushNodeID = CSGNode.InvalidNodeID, surfaceIndex = -1, worldIntersection = intersectionPoint, worldPlane = gridPlane }; } #endregion #region FindUnityWorldIntersection public static bool FindUnityWorldIntersection(Camera camera, Vector2 screenPos, out GameObject foundObject, bool ignoreInvisibleSurfaces = true) { foundObject = null; if (!camera) return false; var wireframeShown = CSGSettings.IsWireframeShown(camera); var worldRay = HandleUtility.GUIPointToWorldRay(screenPos); var worldRayStart = worldRay.origin; var worldRayVector = (worldRay.direction * (camera.farClipPlane - camera.nearClipPlane)); var worldRayEnd = worldRayStart + worldRayVector; CSGModel intersectionModel = null; LegacyBrushIntersection[] intersections; if (FindMultiWorldIntersection(worldRayStart, worldRayEnd, out intersections, ignoreInvisibleSurfaces: ignoreInvisibleSurfaces && !wireframeShown)) { var visibleLayers = Tools.visibleLayers; for (int i = 0; i < intersections.Length; i++) { if (((1 << intersections[i].gameObject.layer) & visibleLayers) == 0) continue; intersectionModel = intersections[i].model; break; } } /* GameObject[] modelMeshes = null; HideFlags[] hideFlags = null; if (intersectionModel != null) { modelMeshes = CSGModelManager.GetModelMeshes(intersectionModel); if (modelMeshes != null) { hideFlags = new HideFlags[modelMeshes.Length]; for (var i = 0; i < modelMeshes.Length; i++) { hideFlags[i] = modelMeshes[i].hideFlags; modelMeshes[i].hideFlags = HideFlags.None; } } } */ CSGModel foundModel; GameObject gameObject = null; var flagState = BeginPicking(null); try { gameObject = HandleUtility.PickGameObject(screenPos, false, null); } finally { foundModel = EndPicking(flagState, gameObject); } if (foundModel == intersectionModel && intersectionModel) return false; /* var gameObject = HandleUtility.PickGameObject(screenPos, false); if (modelMeshes != null) { for (var i = 0; i < modelMeshes.Length; i++) { var modelMesh = modelMeshes[i]; if (!modelMesh) continue; if (gameObject == modelMesh) gameObject = null; modelMesh.hideFlags = hideFlags[i]; } } */ if (!gameObject || gameObject.GetComponent<Canvas>() || gameObject.GetComponent<CSGModel>() || gameObject.GetComponent<CSGBrush>() || gameObject.GetComponent<CSGOperation>() || gameObject.GetComponent<GeneratedMeshInstance>() || gameObject.GetComponent<GeneratedMeshes>()) return false; foundObject = gameObject; return true; } #endregion #region FindWorldIntersection public static bool FindWorldIntersection(Camera camera, Vector2 screenPos, out LegacyBrushIntersection intersection, bool ignoreInvisibleSurfaces = true, bool ignoreUnrenderables = true, CSGBrush[] ignoreBrushes = null) { var worldRay = HandleUtility.GUIPointToWorldRay(screenPos); return FindWorldIntersection(camera, worldRay, out intersection, ignoreInvisibleSurfaces, ignoreUnrenderables, ignoreBrushes); } public static bool FindWorldIntersection(Camera camera, Ray worldRay, out LegacyBrushIntersection intersection, bool ignoreInvisibleSurfaces = true, bool ignoreUnrenderables = true, CSGBrush[] ignoreBrushes = null) { var rayStart = worldRay.origin; var rayVector = (worldRay.direction * (camera.farClipPlane - camera.nearClipPlane)); var rayEnd = rayStart + rayVector; return FindWorldIntersection(rayStart, rayEnd, out intersection, ignoreInvisibleSurfaces, ignoreUnrenderables, ignoreBrushes); } static CSGModel[] __foundModels = new CSGModel[0]; public static bool FindWorldIntersection(Vector3 rayStart, Vector3 rayEnd, out LegacyBrushIntersection intersection, bool ignoreInvisibleSurfaces = true, bool ignoreUnrenderables = true, CSGBrush[] ignoreBrushes = null) { intersection = null; if (InternalCSGModelManager.External == null || InternalCSGModelManager.External.RayCastMulti == null) return false; var forceIgnoreInvisibleSurfaces = ignoreInvisibleSurfaces && !CSGSettings.ShowCulledSurfaces; var visibleLayers = Tools.visibleLayers; int foundModelCount = 0; if (__foundModels.Length < InternalCSGModelManager.Models.Length) __foundModels = new CSGModel[InternalCSGModelManager.Models.Length]; for (var g = 0; g < InternalCSGModelManager.Models.Length; g++) { var model = InternalCSGModelManager.Models[g]; if (!model.isActiveAndEnabled || !ModelTraits.IsModelSelectable(model)) continue; if (ignoreUnrenderables && !ModelTraits.WillModelRender(model) && !Selection.Contains(model.gameObject.GetInstanceID())) continue; __foundModels[foundModelCount] = model; foundModelCount++; } if (foundModelCount == 0) return false; LegacyBrushIntersection[] modelIntersections; if (!InternalCSGModelManager.External.RayCastMulti( foundModelCount, __foundModels, rayStart, rayEnd, forceIgnoreInvisibleSurfaces, out modelIntersections, ignoreBrushes: ignoreBrushes)) return false; for (var i = 0; i < modelIntersections.Length; i++) { var modelIntersection = modelIntersections[i]; if (intersection != null && modelIntersection.distance > intersection.distance) continue; var brush = modelIntersection.gameObject.GetComponent<CSGBrush>(); if (BrushTraits.IsSurfaceUnselectable(brush, modelIntersection.surfaceIndex, brush.ChildData.Model.IsTrigger, ignoreInvisibleSurfaces)) continue; modelIntersection.brush = brush; intersection = modelIntersection; } if (intersection == null) return false; return true; } #endregion #region FindWorldIntersection static bool FindWorldIntersection(CSGModel model, Vector3 worldRayStart, Vector3 worldRayEnd, out LegacyBrushIntersection[] intersections, bool ignoreInvisibleSurfaces = true, bool ignoreUnrenderables = true, CSGBrush[] ignoreBrushes = null) { intersections = null; if (InternalCSGModelManager.External == null || InternalCSGModelManager.External.RayCastIntoModelMulti == null) return false; var foundIntersections = new Dictionary<CSGNode, LegacyBrushIntersection>(); var visibleLayers = Tools.visibleLayers; ignoreInvisibleSurfaces = ignoreInvisibleSurfaces && !CSGSettings.ShowCulledSurfaces; if (!ModelTraits.IsModelSelectable(model)) return false; if (ignoreUnrenderables && !ModelTraits.WillModelRender(model) && !Selection.Contains(model.gameObject.GetInstanceID())) return false; LegacyBrushIntersection[] modelIntersections; if (!InternalCSGModelManager.External.RayCastIntoModelMulti(model, worldRayStart, worldRayEnd, ignoreInvisibleSurfaces, out modelIntersections, ignoreBrushes: ignoreBrushes)) return false; for (var i = 0; i < modelIntersections.Length; i++) { var intersection = modelIntersections[i]; var brush = intersection.gameObject.GetComponent<CSGBrush>(); if (BrushTraits.IsSurfaceUnselectable(brush, intersection.surfaceIndex, brush.ChildData.Model.IsTrigger, ignoreSurfaceFlags: ignoreInvisibleSurfaces)) continue; var currentNode = GetTopMostGroupForNode(brush); LegacyBrushIntersection other; if (foundIntersections.TryGetValue(currentNode, out other) && other.distance <= intersection.distance) continue; intersection.brush = brush; intersection.model = model; foundIntersections[currentNode] = modelIntersections[i]; } if (foundIntersections.Count == 0) return false; var sortedIntersections = foundIntersections.Values.ToArray(); Array.Sort(sortedIntersections, (x, y) => (int)Mathf.Sign(x.distance - y.distance)); intersections = sortedIntersections; return true; } #endregion #region FindMultiWorldIntersection public static bool FindMultiWorldIntersection(Vector3 worldRayStart, Vector3 worldRayEnd, out LegacyBrushIntersection[] intersections, bool ignoreInvisibleSurfaces = true, bool ignoreUnrenderables = true, CSGBrush[] ignoreBrushes = null) { intersections = null; if (InternalCSGModelManager.External == null || InternalCSGModelManager.External.RayCastIntoModelMulti == null) return false; var foundIntersections = new Dictionary<CSGNode, LegacyBrushIntersection>(); var visibleLayers = Tools.visibleLayers; ignoreInvisibleSurfaces = ignoreInvisibleSurfaces && !CSGSettings.ShowCulledSurfaces; for (var g = 0; g < InternalCSGModelManager.Models.Length; g++) { var model = InternalCSGModelManager.Models[g]; if (!ModelTraits.IsModelSelectable(model)) continue; if (ignoreUnrenderables && !ModelTraits.WillModelRender(model) && !Selection.Contains(model.gameObject.GetInstanceID())) continue; LegacyBrushIntersection[] modelIntersections; if (!InternalCSGModelManager.External.RayCastIntoModelMulti(model, worldRayStart, worldRayEnd, ignoreInvisibleSurfaces, out modelIntersections, ignoreBrushes: ignoreBrushes)) continue; for (var i = 0; i < modelIntersections.Length; i++) { var intersection = modelIntersections[i]; var brush = intersection.gameObject.GetComponent<CSGBrush>(); if (BrushTraits.IsSurfaceUnselectable(brush, intersection.surfaceIndex, brush.ChildData.Model.IsTrigger, ignoreSurfaceFlags: ignoreInvisibleSurfaces)) continue; var currentNode = GetTopMostGroupForNode(brush); LegacyBrushIntersection other; if (foundIntersections.TryGetValue(currentNode, out other) && other.distance <= intersection.distance) continue; intersection.brush = brush; intersection.model = model; foundIntersections[currentNode] = modelIntersections[i]; } } if (foundIntersections.Count == 0) return false; var sortedIntersections = foundIntersections.Values.ToArray(); Array.Sort(sortedIntersections, (x, y) => (int)Mathf.Sign(x.distance - y.distance)); intersections = sortedIntersections; return true; } #endregion #region FindBrushIntersection public static bool FindBrushIntersection(CSGBrush brush, Matrix4x4 modelTransformation, Vector3 rayStart, Vector3 rayEnd, out LegacyBrushIntersection intersection) { intersection = null; if (!brush || InternalCSGModelManager.External.RayCastIntoBrush == null) return false; if (!InternalCSGModelManager.External.RayCastIntoBrush(brush.brushNodeID, rayStart, rayEnd, modelTransformation, out intersection, false)) return false; if (BrushTraits.IsSurfaceUnselectable(brush, intersection.surfaceIndex, brush.ChildData.Model.IsTrigger)) return false; return true; } #endregion #region FindSurfaceIntersection public static bool FindSurfaceIntersection(Camera camera, CSGBrush brush, Matrix4x4 modelTransformation, Int32 surfaceIndex, Vector2 screenPos, out LegacySurfaceIntersection intersection) { var worldRay = HandleUtility.GUIPointToWorldRay(screenPos); var rayStart = worldRay.origin; var rayVector = (worldRay.direction * (camera.farClipPlane - camera.nearClipPlane)); var rayEnd = rayStart + rayVector; intersection = null; if (!brush || InternalCSGModelManager.External.RayCastIntoBrushSurface == null) return false; if (!InternalCSGModelManager.External.RayCastIntoBrushSurface(brush.brushNodeID, surfaceIndex, rayStart, rayEnd, modelTransformation, out intersection)) { return false; } if (BrushTraits.IsSurfaceUnselectable(brush, surfaceIndex, brush.ChildData.Model.IsTrigger)) { return false; } return true; } #endregion #endregion } }
0
0.94447
1
0.94447
game-dev
MEDIA
0.891766
game-dev
0.948164
1
0.948164
Esteemed-Innovation/Esteemed-Innovation
13,436
src/main/java/eiteam/esteemedinnovation/commons/handler/GenericTickHandler.java
package eiteam.esteemedinnovation.commons.handler; import eiteam.esteemedinnovation.api.block.DisguisableBlock; import eiteam.esteemedinnovation.api.enhancement.UtilEnhancements; import eiteam.esteemedinnovation.api.tool.SteamTool; import eiteam.esteemedinnovation.api.util.ItemStackUtility; import eiteam.esteemedinnovation.armor.ArmorModule; import eiteam.esteemedinnovation.armor.exosuit.steam.ItemSteamExosuitArmor; import eiteam.esteemedinnovation.commons.EsteemedInnovation; import eiteam.esteemedinnovation.commons.network.CamoPacket; import eiteam.esteemedinnovation.commons.util.ReflectionHelper; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiMerchant; import net.minecraft.client.renderer.ItemRenderer; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.EntityEquipmentSlot; import net.minecraft.item.Item; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; import net.minecraftforge.fml.common.FMLCommonHandler; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.TickEvent; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import java.lang.reflect.Field; import static eiteam.esteemedinnovation.firearms.FirearmModule.MUSKET; import static eiteam.esteemedinnovation.firearms.FirearmModule.SPYGLASS; import static eiteam.esteemedinnovation.transport.TransportationModule.BRASS_PIPE; public class GenericTickHandler { private static float zoom = 0.0F; ResourceLocation spyglassfiller = new ResourceLocation(EsteemedInnovation.MOD_ID + ":textures/gui/spyglassfiller.png"); ResourceLocation spyglass = new ResourceLocation(EsteemedInnovation.MOD_ID + ":textures/gui/spyglassfiller.png"); private boolean inUse = false; private boolean wasInUse = false; private float fov = 0; private float sensitivity = 0; private int zoomSettingOn = 0; private boolean lastPressingKey = false; private static Field itemInMainHandField; private static Field itemInOffHandField; static { if (FMLCommonHandler.instance().getSide() == Side.CLIENT) { EsteemedInnovation.logger.info("Getting some fields from reflection for Tick Handling."); itemInMainHandField = ReflectionHelper.getField("itemStackMainHand", "field_187467_d", ItemRenderer.class); itemInOffHandField = ReflectionHelper.getField("itemStackOffHand", "field_187468_e", ItemRenderer.class); if (itemInMainHandField != null) { itemInMainHandField.setAccessible(true); } if (itemInOffHandField != null) { itemInOffHandField.setAccessible(true); } } } @SubscribeEvent @SideOnly(Side.CLIENT) public void tickStart(TickEvent.ClientTickEvent event) { wasInUse = inUse; Minecraft mc = Minecraft.getMinecraft(); inUse = false; if (event.side == Side.CLIENT && mc.player != null) { /* Prevents caching of SteamTool ItemStacks in the ItemRenderer, so that the ItemOverrideList has access to the new NBT added in ItemSteamTool#onUpdate. */ ItemStack mainHandStack = mc.player.getHeldItemMainhand(); ItemStack offHandStack = mc.player.getHeldItemOffhand(); if (mainHandStack != null && mainHandStack.getItem() instanceof SteamTool) { try { itemInMainHandField.set(mc.getItemRenderer(), mainHandStack); } catch (IllegalAccessException e) { e.printStackTrace(); } } if (offHandStack != null && offHandStack.getItem() instanceof SteamTool) { try { itemInOffHandField.set(mc.getItemRenderer(), offHandStack); } catch (IllegalAccessException e) { e.printStackTrace(); } } if (mc.currentScreen == null || !(mc.currentScreen instanceof GuiMerchant)) { GenericEventHandler.lastViewVillagerGui = false; } EntityPlayer player = mc.player; ItemStack held = ItemStackUtility.getHeldItemStack(player); if (mc.gameSettings.keyBindUseItem.isKeyDown() && player.isSneaking() && held != null && held.getItem() instanceof ItemBlock) { RayTraceResult pos = mc.objectMouseOver; if (pos != null) { BlockPos blockPos = pos.getBlockPos(); // blockPos is null when objectMouseOver is not over a block (on an entity). //noinspection ConstantConditions if (blockPos != null) { TileEntity te = mc.world.getTileEntity(blockPos); if (mc.world.getBlockState(blockPos).getBlock() == BRASS_PIPE || (te instanceof DisguisableBlock)) { EsteemedInnovation.channel.sendToServer(new CamoPacket(blockPos)); } } } } ItemStack hat = player.getItemStackFromSlot(EntityEquipmentSlot.HEAD); Item monacle = ArmorModule.MONOCLE; Item goggles = ArmorModule.GOGGLES; boolean hasHat = hat != null && (hat.getItem() == monacle || hat.getItem() == goggles || (hat.getItem() == ArmorModule.STEAM_EXO_HEAD && (((ItemSteamExosuitArmor) hat.getItem()).hasUpgrade(hat, goggles) || ((ItemSteamExosuitArmor) hat.getItem()).hasUpgrade(hat, monacle)))); if (hasHat) { if (mc.gameSettings.thirdPersonView == 0) { if (ArmorModule.MONOCLE_KEY.isKeyDown() && !lastPressingKey) { zoomSettingOn++; zoomSettingOn = zoomSettingOn % 4; switch (zoomSettingOn) { case 0: mc.gameSettings.fovSetting = fov; mc.gameSettings.mouseSensitivity = sensitivity; break; case 1: mc.gameSettings.fovSetting = fov; mc.gameSettings.mouseSensitivity = sensitivity; int i = 0; while (Math.abs((mc.gameSettings.fovSetting - ((fov + 5F)) / 2.0F)) > 2.5F && i < 200) { zoom += 1.0F; mc.gameSettings.fovSetting -= 2.5F; mc.gameSettings.mouseSensitivity -= 0.01F; i++; } break; case 2: mc.gameSettings.fovSetting = fov; mc.gameSettings.mouseSensitivity = sensitivity; i = 0; while (Math.abs((mc.gameSettings.fovSetting - ((fov + 5F)) / 5.0F)) > 2.5F && i < 200) { zoom += 1.0F; mc.gameSettings.fovSetting -= 2.5F; mc.gameSettings.mouseSensitivity -= 0.01F; i++; } break; case 3: mc.gameSettings.fovSetting = fov; mc.gameSettings.mouseSensitivity = sensitivity; i = 0; while (Math.abs((mc.gameSettings.fovSetting - ((fov + 5F)) / 12.0F)) > 2.5F && i < 200) { zoom += 1.0F; mc.gameSettings.fovSetting -= 2.5F; mc.gameSettings.mouseSensitivity -= 0.01F; i++; } break; } lastPressingKey = true; } else if (!ArmorModule.MONOCLE_KEY.isKeyDown()) { lastPressingKey = false; } inUse = zoomSettingOn != 0; } } ItemStack item = player.inventory.getStackInSlot(player.inventory.currentItem); if (item != null && item.getItem() == SPYGLASS) { if (mc.gameSettings.thirdPersonView == 0) { inUse = true; this.renderTelescopeOverlay(); } } if (!wasInUse && item != null && player.isHandActive() && item.getItem() == MUSKET && UtilEnhancements.getEnhancementFromItem(item) == SPYGLASS) { boolean isShooting = false; if (item.getTagCompound() != null) { NBTTagCompound nbt = item.getTagCompound(); if (nbt.getInteger("loaded") > 0) { isShooting = true; } } if (isShooting && mc.gameSettings.thirdPersonView == 0) { inUse = true; mc.gameSettings.fovSetting -= 30F; mc.gameSettings.mouseSensitivity -= 0.3F; this.renderTelescopeOverlay(); } } if (!inUse && !wasInUse) { fov = mc.gameSettings.fovSetting; sensitivity = mc.gameSettings.mouseSensitivity; } if (!inUse && wasInUse) { mc.gameSettings.fovSetting = fov; mc.gameSettings.mouseSensitivity = sensitivity; } if (inUse && !wasInUse) { zoom = 0.0F; } if (inUse && mc.gameSettings.keyBindAttack.isKeyDown() && zoom > 0F && item != null && item.getItem() == SPYGLASS) { zoom -= 1.0F; mc.gameSettings.fovSetting += 2.5F; mc.gameSettings.mouseSensitivity += 0.01F; } if (inUse && mc.gameSettings.keyBindUseItem.isKeyDown() && mc.gameSettings.fovSetting > 5F && item != null && item.getItem() == SPYGLASS) { zoom += 1.0F; mc.gameSettings.fovSetting -= 2.5F; mc.gameSettings.mouseSensitivity -= 0.01F; } } } private void renderTelescopeOverlay() { // GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS); // ScaledResolution var5 = new ScaledResolution(mc.gameSettings, mc.displayWidth, mc.displayHeight); // int par1 = var5.getScaledWidth(); // int par2 = var5.getScaledHeight(); // int par3 = par1-par2; // GL11.glDisable(GL11.GL_DEPTH_TEST); // GL11.glDepthMask(false); // GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); // GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); // // GL11.glDisable(GL11.GL_ALPHA_TEST); // ITextureObject test = mc.renderEngine.getTexture(spyglass); // try { // IResourceManager resourceManager = ObfuscationReflectionHelper.getPrivateValue(TextureManager.class, mc.renderEngine, "theResourceManager"); // test.loadTexture(resourceManager); // } catch (IOException e) { // e.printStackTrace(); // } // GL11.glBindTexture(GL11.GL_TEXTURE_2D, test.getGlTextureId()); // //mc.renderEngine.bindTexture(spyglass,test.getGlTextureId()); // Tessellator var3 = Tessellator.instance; // var3.startDrawingQuads(); // var3.addVertexWithUV(par3/2, par2, -90.0D, 0.0D, 1.0D); // var3.addVertexWithUV((par3/2)+par2, par2, -90.0D, 1.0D, 1.0D); // var3.addVertexWithUV((par3/2)+par2, 0.0D, -90.0D, 1.0D, 0.0D); // var3.addVertexWithUV(par3/2, 0.0D, -90.0D, 0.0D, 0.0D); // var3.draw(); // // mc.renderEngine.bindTexture(spyglassfiller); // var3 = Tessellator.instance; // var3.startDrawingQuads(); // var3.addVertexWithUV(0, par2, -90.0D, 0.0D, 1.0D); // var3.addVertexWithUV(par3/2, par2, -90.0D, 1.0D, 1.0D); // var3.addVertexWithUV(par3/2, 0.0D, -90.0D, 1.0D, 0.0D); // var3.addVertexWithUV(0, 0.0D, -90.0D, 0.0D, 0.0D); // var3.draw(); // // // mc.renderEngine.bindTexture(spyglassfiller); // var3 = Tessellator.instance; // var3.startDrawingQuads(); // var3.addVertexWithUV((par3/2)+par2, par2, -90.0D, 0.0D, 1.0D); // var3.addVertexWithUV(par1, par2, -90.0D, 1.0D, 1.0D); // var3.addVertexWithUV(par1, 0.0D, -90.0D, 1.0D, 0.0D); // var3.addVertexWithUV((par3/2)+par2, 0.0D, -90.0D, 0.0D, 0.0D); // var3.draw(); // // GL11.glDepthMask(true); // GL11.glEnable(GL11.GL_DEPTH_TEST); // GL11.glEnable(GL11.GL_ALPHA_TEST); // GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); // GL11.glPopAttrib(); } }
0
0.915798
1
0.915798
game-dev
MEDIA
0.972498
game-dev
0.927847
1
0.927847
project-topaz/topaz
1,442
scripts/globals/abilities/pets/lightning_breath.lua
--------------------------------------------------- -- Lightning Breath --------------------------------------------------- require("scripts/globals/settings") require("scripts/globals/status") require("scripts/globals/monstertpmoves") require("scripts/globals/ability") --------------------------------------------------- function onAbilityCheck(player, target, ability) return 0, 0 end function onUseAbility(pet, target, skill, action) local master = pet:getMaster() ---------- Deep Breathing ---------- -- 0 for none -- 1 for first merit -- 0.25 for each merit after the first -- TODO: 0.1 per merit for augmented AF2 (10663 *w/ augment*) local deep = 1 if (pet:hasStatusEffect(tpz.effect.MAGIC_ATK_BOOST) == true) then deep = deep + 1 + (master:getMerit(tpz.merit.DEEP_BREATHING) - 1) * 0.25 pet:delStatusEffect(tpz.effect.MAGIC_ATK_BOOST) end local gear = master:getMod(tpz.mod.WYVERN_BREATH) / 256 -- Master gear that enhances breath local dmgmod = MobBreathMove(pet, target, 0.185, pet:getMainLvl() * 15, tpz.magic.ele.LIGHTNING) -- Works out to (hp/6) + 15, as desired dmgmod = (dmgmod * (1 + gear)) * deep pet:setTP(0) local dmg = AbilityFinalAdjustments(dmgmod, pet, skill, target, tpz.attackType.BREATH, tpz.damageType.LIGHTNING, MOBPARAM_IGNORE_SHADOWS) target:takeDamage(dmg, pet, tpz.attackType.BREATH, tpz.damageType.FIRE) return dmg end
0
0.904435
1
0.904435
game-dev
MEDIA
0.966395
game-dev
0.915121
1
0.915121
bozimmerman/CoffeeMud
13,933
com/planet_ink/coffee_mud/Abilities/Properties/Prop_LangTranslator.java
package com.planet_ink.coffee_mud.Abilities.Properties; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.core.collections.*; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Libraries.interfaces.*; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import java.util.*; /* Copyright 2004-2025 Bo Zimmerman Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ public class Prop_LangTranslator extends Property implements Language { @Override public String ID() { return "Prop_LangTranslator"; } @Override public String name() { return "Language Translator"; } @Override public String writtenName() { return "Language Translator"; } @Override public int abstractQuality() { return Ability.QUALITY_BENEFICIAL_SELF; } @Override protected int canAffectCode() { return CAN_MOBS | CAN_ITEMS | CAN_ROOMS; } protected Map<String, Pair<Integer,List<String>>> langs = new Hashtable<String, Pair<Integer,List<String>>>(); protected final Set<String> trusted = new HashSet<String>(); protected Set<String> ints = new XHashSet<String>("Common"); protected boolean passive = false; protected final String[] lastLang = new String[] { "" }; @Override public String accountForYourself() { return "Translates spoken language"; } @Override public boolean isANaturalLanguage() { return true; } protected void logError(final String msg) { final String aname = (affected!=null)?affected.Name():"null"; final String rname = CMLib.map().getApproximateExtendedRoomID(CMLib.map().roomLocation(affected)); Log.errOut("Prop_LangTranslator: "+msg+": "+aname+": "+rname); } @Override public void setMiscText(final String text) { super.setMiscText(text); final Vector<String> V=CMParms.parse(text); langs.clear(); ints.clear(); trusted.clear(); int lastpct=100; List<String> words=new ArrayList<String>(1); for(int v=0;v<V.size();v++) { String s=V.elementAt(v); if(s.endsWith("%")) s=s.substring(0,s.length()-1); if(CMath.isNumber(s)) lastpct=CMath.s_int(s); else if(s.startsWith("'")||s.startsWith("`")) { final String wds=s.substring(1).trim().toUpperCase(); if(wds.length()>0) words.add(wds); } else if(s.startsWith("#")) { final String nm=s.substring(1).trim().toUpperCase(); if(nm.length()>0) trusted.add(nm); } else if(s.equalsIgnoreCase("notranslate")) passive=true; else { final Ability A=CMClass.getAbility(s); if(A!=null) { langs.put(A.ID().toUpperCase(),new Pair<Integer,List<String>>(Integer.valueOf(lastpct),words)); ints.add(A.ID()); words=new ArrayList<String>(1); } else logError("Bad parm: '"+s+"'"); } } } @Override public Set<String> languagesSupported() { return ints; } @Override public String getVerb() { return ""; } @Override public String getTranslationVerb() { return ""; } protected boolean wordMatch(String words, final List<String> allMatchWords) { if((allMatchWords == null)||(allMatchWords.size()==0)||(allMatchWords.contains("*"))) return true; if(words==null) return false; words=words.trim().toUpperCase(); if(words.length()==0) return false; words=" "+words+" "; for(final String s : allMatchWords) { if(s.startsWith("*")) { if(s.endsWith("*")) { if(words.indexOf(s.substring(1,s.length()-1))>=0) return true; } else if(words.indexOf(s.substring(1)+" ")>=0) return true; } else if(s.endsWith("*")) { if(words.indexOf(" "+s.substring(0,s.length()-1))>=0) return true; } else if(s.startsWith("^")) { if(words.startsWith(" "+s.substring(1))) return true; } else if(words.indexOf(" "+s+" ")>=0) return true; } return false; } @Override public boolean translatesLanguage(final String language, final String words) { final Pair<Integer,List<String>> p = langs.get(language.toUpperCase()); if(p==null) return false; if(wordMatch(words, p.second)) { synchronized(lastLang) { lastLang[0] = language; } return true; } return false; } @Override public int getProficiency(String language) { if(language.equalsIgnoreCase(ID())) { synchronized(lastLang) { language=lastLang[0]; } } final Pair<Integer,List<String>> p = langs.get(language.toUpperCase()); if(p==null) return 0; return p.first.intValue(); } @Override public boolean beingSpoken(final String language) { return !passive; } @Override public void setBeingSpoken(final String language, final boolean beingSpoken) { } @Override public Map<String, String> translationHash(final String language) { return new Hashtable<String, String>(); } @Override public List<String[]> translationLists(final String language) { return new Vector<String[]>(); } @Override public String translate(final String language, final String word) { return word; } @Override public void executeMsg(final Environmental myHost, final CMMsg msg) { super.executeMsg(myHost,msg); if(passive) { if((msg.sourceMinor()==CMMsg.TYP_SPEAK) &&(msg.target()==affected) &&(affected instanceof MOB) &&((trusted.contains(msg.source().Name().toUpperCase().trim())) ||(trusted.contains("*"))) &&(msg.sourceMessage()!=null)) { Language langL; if(msg.tool() instanceof Language) langL=(Language)msg.tool(); else { langL=CMLib.utensils().getLanguageSpoken(msg.source()); if(langL == null) langL=(Language)CMClass.getAbility("Common"); } if(langs.containsKey(langL.ID().toUpperCase())) { final String spokenMsg = CMStrings.getSayFromMessage(msg.sourceMessage()); final Pair<Integer,List<String>> p = langs.get(langL.ID().toUpperCase()); if(wordMatch(spokenMsg, p.second)) { final MOB M=(MOB)affected; final List<String> parsedInput=CMParms.parse(spokenMsg); int metaFlags = MUDCmdProcessor.METAFLAG_INORDER; if((!M.isPlayer())&&(M.session()!=null)) metaFlags|=MUDCmdProcessor.METAFLAG_POSSESSED; final List<List<String>> MORE_CMDS=CMLib.lang().preCommandParser(parsedInput); for(int m=0;m<MORE_CMDS.size();m++) ((MOB)affected).enqueCommand(MORE_CMDS.get(m),metaFlags,0); } } } } else if((msg.tool() instanceof Ability) &&(msg.sourceMinor()!=CMMsg.TYP_TEACH)) { if(text().length()>0) { final Pair<Integer,List<String>> p = langs.get(msg.tool().ID().toUpperCase()); if(p==null) return; if(CMLib.dice().rollPercentage()>p.first.intValue()) return; } if((msg.tool().ID().equals("Fighter_SmokeSignals")) &&(msg.sourceMinor()==CMMsg.NO_EFFECT) &&(msg.targetMinor()==CMMsg.NO_EFFECT) &&(msg.othersMessage()!=null)) CMLib.commands().postSay(msg.source(),null,L("The smoke signals seem to say '@x1'.",msg.othersMessage()),false,false); else if(((msg.sourceMinor()==CMMsg.TYP_SPEAK) ||(msg.sourceMinor()==CMMsg.TYP_TELL) ||(msg.sourceMinor()==CMMsg.TYP_ORDER) ||(CMath.bset(msg.sourceMajor(),CMMsg.MASK_CHANNEL))) &&(msg.sourceMessage()!=null) &&((((Ability)msg.tool()).classificationCode()&Ability.ALL_ACODES)==Ability.ACODE_LANGUAGE)) { final String str=CMStrings.getSayFromMessage(msg.sourceMessage()); if(str!=null) { Environmental target=null; final String sourceName = affected.name(); if(msg.target() instanceof MOB) target=msg.target(); if(CMath.bset(msg.sourceMajor(),CMMsg.MASK_CHANNEL)) { msg.addTrailerMsg(CMClass.getMsg(msg.source(),null,null,CMMsg.MSG_NOISE|CMMsg.MASK_ALWAYS, L("@x1 say(s) '@x2 said \"@x3\" in @x4'",sourceName,msg.source().name(),str,msg.tool().name()))); } else if((target==null)&&(msg.targetMessage()!=null)) { msg.addTrailerMsg(CMClass.getMsg(msg.source(),null,null,CMMsg.MSG_NOISE|CMMsg.MASK_ALWAYS, L("@x1 say(s) '@x2 said \"@x3\" in @x4'",sourceName,msg.source().name(),str,msg.tool().name()))); } else if(msg.othersMessage()!=null) { msg.addTrailerMsg(CMClass.getMsg(msg.source(),target,null,CMMsg.MSG_NOISE|CMMsg.MASK_ALWAYS, L("@x1 say(s) '@x2 said \"@x3\" in @x4'",sourceName,msg.source().name(),str,msg.tool().name()))); } } } } } protected String[] parseParms(final String code,final String val) { if(code.startsWith("+")||code.startsWith("-")) { final String lang=code.substring(1); String parms=""; if((val != null)&&(val.length()>0)) parms=val; return new String[] {lang, parms}; } return null; } public Pair<Integer,List<String>> parseEquate(final Integer defI, final String arg) { Integer amt = (defI == null) ? Integer.valueOf(100) : defI; final List<String> words=new ArrayList<String>(); for(String s : CMParms.parse(arg)) { if(s.endsWith("%")) s=s.substring(0,s.length()-1); if(CMath.isNumber(s)) amt=Integer.valueOf(CMath.s_int(s)); else if(s.startsWith("'")||s.startsWith("`")) { final String wds=s.substring(1).trim().toUpperCase(); if(wds.length()>0) words.add(wds); } } return new Pair<Integer,List<String>>(amt,words); } public void rebuildMiscText() { final StringBuilder str=new StringBuilder(""); if(passive) str.append("NOTRANSLATE "); for(final String t : trusted) str.append("#"+t).append(" "); for(final String ID : ints) { final Pair<Integer,List<String>> p = langs.get(ID.toUpperCase().trim()); if(p!=null) { str.append(p.first.intValue()).append(" "); for(final String s : p.second) { if(s.indexOf(" ")>0) str.append("\"`").append(s).append("\" "); else str.append("`").append(s).append(" "); } } str.append(ID).append(" "); } super.miscText = str.toString().trim(); } @Override public String getStat(final String code) { int x=code.indexOf(':'); if((x>0) &&(code.substring(0, x).toUpperCase().equals("EXISTS"))) { final String allParms=code.substring(x+1).trim(); x=allParms.indexOf(' '); final String lang = (x<0)?allParms:allParms.substring(0, x).trim(); if(lang.startsWith("#")) return trusted.contains(lang.toUpperCase().trim())?"true":"false"; final Pair<Integer,List<String>> p=(x<0)?null:parseEquate(Integer.valueOf(100),allParms.substring(x+1).trim()); final Pair<Integer,List<String>> dat=langs.get(lang.toUpperCase().trim()); if(dat == null) return "false"; if(p==null) return "true"; for(final String s : p.second) { if(!dat.second.contains(s.toUpperCase())) return "false"; } return "true"; } else return super.getStat(code); } @Override public void setStat(final String code, final String val) { if(code.startsWith("+")) { final String[] args = parseParms(code,val); if(args[0].equalsIgnoreCase("PASSIVE")||args[0].equalsIgnoreCase("NOTRANSLATE")) { if (!passive) { passive=true; rebuildMiscText(); } } else if(args[0].equalsIgnoreCase("TRUSTED")) { if(!trusted.contains(val.toUpperCase())) { trusted.add(val.toUpperCase()); rebuildMiscText(); } } else { final Ability A=CMClass.findAbility(args[0]); if(A==null) return; if(!langs.containsKey(A.ID().toUpperCase())) { langs.put(A.ID().toUpperCase(), parseEquate(null,args[1])); ints.add(A.ID()); rebuildMiscText(); } else { final List<String> old=langs.get(A.ID().toUpperCase()).second; final Integer I=langs.get(A.ID().toUpperCase()).first; langs.put(A.ID().toUpperCase(), parseEquate(I,args[1])); langs.get(A.ID().toUpperCase()).second.addAll(old); rebuildMiscText(); } } } else if(code.startsWith("-")) { final String[] args = parseParms(code,val); if(args[0].equalsIgnoreCase("PASSIVE")||args[0].equalsIgnoreCase("NOTRANSLATE")) { if (passive) { passive=false; rebuildMiscText(); } } else if(args[0].equalsIgnoreCase("TRUSTED")) { if(trusted.contains(val.toUpperCase())) { trusted.remove(val.toUpperCase()); rebuildMiscText(); } } else { final Ability A=CMClass.findAbility(args[0]); if(A==null) return; if(args[1].length()==0) { if(langs.containsKey(A.ID().toUpperCase())) { langs.remove(A.ID().toUpperCase()); ints.remove(A.ID()); rebuildMiscText(); } } else if(langs.containsKey(A.ID().toUpperCase())) { final Pair<Integer,List<String>> p = langs.get(A.ID().toUpperCase()); if((p!=null)&&(p.second.size()>0)) { p.second.removeAll(parseEquate(null,args[1]).second); rebuildMiscText(); } } } } else super.setStat(code, val); } }
0
0.946334
1
0.946334
game-dev
MEDIA
0.495212
game-dev
0.912989
1
0.912989
MedeaMelana/Magic
3,073
Magic/src/Magic/Layers.hs
{-# LANGUAGE GADTs #-} module Magic.Layers ( -- * Layered effects -- | Layered effects are a type of continuous effects that modify -- objects, players, or the game rules. Their interaction is managed by a -- layer system, which is why this library calls them layered effects. LayeredEffect(..), ModifyObject(..), Layer(..), layer, -- * Temporary layered effects TemporaryLayeredEffect(..), Duration(..), -- * Creating layered effects affectSelf, affectBattlefield, affectRestOfBattlefield, affectAttached, affectingSelf ) where import Magic.Some (Some(..)) import Magic.Core (object, objectPart) import qualified Magic.IdList as IdList import Magic.Types import Control.Applicative ((<$>)) import Data.Label (get) import Data.Label.Monadic (asks) import Data.Maybe (mapMaybe, maybeToList) -- | Compute the layer in which a 'ModifyObject' applies. Object -- modifications are applied in order of increasing corresponding layers -- (among other things). layer :: ModifyObject -> Layer layer m = case m of ChangeController _ -> Layer2 ChangeTypes _ -> Layer4 ChangeColors _ -> Layer5 AddStaticKeywordAbility _ -> Layer6 RemoveStaticKeywordAbility _ -> Layer6 AddActivatedAbility _ -> Layer6 AddTriggeredAbilities _ -> Layer6 RemoveAllAbilities -> Layer6 DefinePT _ -> Layer7a SetPT _ -> Layer7b ModifyPT _ -> Layer7c SwitchPT -> Layer7e RestrictAllowAttacks _ -> LayerRules RestrictAllowBlocks _ -> LayerRules -- | Affect only the object that carries the layered effect itself. affectSelf :: Contextual (View [SomeObjectRef]) affectSelf r _you = return [r] -- | Affect objects on the battlefield, from a layered effect of an object -- on the battlefield. affectBattlefield :: (PlayerRef -> Object -> Bool) -> Contextual (View [SomeObjectRef]) affectBattlefield ok (Some Battlefield, _) you = mapMaybe (\(i, perm@Permanent {}) -> if ok you (get objectPart perm) then Just (Some Battlefield, i) else Nothing) . IdList.toList <$> asks battlefield affectBattlefield _ _ _ = return [] -- | Affect all other objects on the battlefield, from a layered effect of an -- object on the battlefield. affectRestOfBattlefield :: (PlayerRef -> Object -> Bool) -> Contextual (View [SomeObjectRef]) affectRestOfBattlefield ok (Some Battlefield, iSelf) you = mapMaybe (\(i, perm@Permanent {}) -> if iSelf /= i && ok you (get objectPart perm) then Just (Some Battlefield, i) else Nothing) . IdList.toList <$> asks battlefield affectRestOfBattlefield _ _ _ = return [] -- | Affect whatever object this object is attached to. affectAttached :: Contextual (View [SomeObjectRef]) affectAttached (Some Battlefield, i) _you = do perm <- asks (object (Battlefield, i)) return (maybeToList (get attachedTo perm)) affectAttached _ _ = return [] affectingSelf :: [ModifyObject] -> LayeredEffect affectingSelf = LayeredObjectEffect affectSelf
0
0.874498
1
0.874498
game-dev
MEDIA
0.203875
game-dev
0.933823
1
0.933823
AlmasB/Zephyria
1,410
src/main/kotlin/com/almasb/zeph/character/components/RandomWanderComponent.kt
package com.almasb.zeph.character.components import com.almasb.fxgl.dsl.random import com.almasb.fxgl.entity.component.Component import com.almasb.fxgl.pathfinding.astar.AStarCell import com.almasb.fxgl.pathfinding.astar.AStarMoveComponent import com.almasb.zeph.Config import com.almasb.zeph.character.CharacterEntity /** * * * @author Almas Baimagambetov (almaslvl@gmail.com) */ class RandomWanderComponent : Component() { private lateinit var astar: AStarMoveComponent<AStarCell> private lateinit var action: CharacterActionComponent private var time = 0.0 private var nextMoveTime = random(Config.CHAR_IDLE_TIME, Config.CHAR_IDLE_TIME + 2.5) override fun onUpdate(tpf: Double) { if (astar.isAtDestination) { time += tpf if (time >= nextMoveTime) { // TODO: check logic for identifying where a char is val cellX = (entity as CharacterEntity).cellX val cellY = (entity as CharacterEntity).cellY astar.grid .getRandomCell { it.isWalkable && it.distance(astar.grid.get(cellX, cellY)) < 5 } .ifPresent { action.orderMove(it.x, it.y) } time = 0.0 nextMoveTime = random(Config.CHAR_IDLE_TIME, Config.CHAR_IDLE_TIME + 2.5) } } } }
0
0.864096
1
0.864096
game-dev
MEDIA
0.869713
game-dev
0.942828
1
0.942828
P3pp3rF1y/Reliquary
2,601
src/main/java/reliquary/client/gui/hud/HandgunPane.java
package reliquary.client.gui.hud; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.world.InteractionHand; import net.minecraft.world.item.ItemStack; import reliquary.client.gui.components.Box; import reliquary.client.gui.components.Component; import reliquary.client.gui.components.ItemStackPane; import reliquary.init.ModItems; public class HandgunPane extends Component { private final Box mainPane; private final ItemStackPane[] bulletPanes = new ItemStackPane[8]; private final ItemStackPane magazinePane; private final InteractionHand hand; public HandgunPane(InteractionHand hand) { this.hand = hand; magazinePane = new ItemStackPane(ModItems.EMPTY_MAGAZINE.get()); for (int i = 0; i < 8; i++) { bulletPanes[i] = new ItemStackPane(ItemStack.EMPTY) { @Override public int getPadding() { return -3; //hack to let bullets overlap a bit } }; } Box bulletsPane = new Box(Box.Layout.HORIZONTAL, Box.Alignment.MIDDLE, bulletPanes) { @Override public int getPadding() { return 3; //hack to counter the minus padding of bullets } }; if (hand == InteractionHand.OFF_HAND) { mainPane = Box.createHorizontal(Box.Alignment.MIDDLE, new ItemStackPane(ModItems.HANDGUN.get()), magazinePane, bulletsPane); } else { mainPane = Box.createHorizontal(Box.Alignment.MIDDLE, bulletsPane, magazinePane, new ItemStackPane(ModItems.HANDGUN.get())); } } @Override public int getHeightInternal() { return mainPane.getHeight(); } @Override public int getWidthInternal() { return mainPane.getWidth(); } @Override public int getHeight() { return holdsHandgun() ? super.getHeight() : 0; } @Override public boolean shouldRender() { return holdsHandgun(); } private boolean holdsHandgun() { return Minecraft.getInstance().player.getItemInHand(hand).getItem() == ModItems.HANDGUN.get(); } @Override public void renderInternal(GuiGraphics guiGraphics, int x, int y) { ItemStack handgun = Minecraft.getInstance().player.getItemInHand(hand); if (handgun.isEmpty()) { return; } ItemStack bullets = ModItems.HANDGUN.get().getBulletStack(handgun); for (int i = 0; i < 8; i++) { if (i < bullets.getCount()) { bulletPanes[i].setItemStack(bullets); } else { bulletPanes[i].setItemStack(ItemStack.EMPTY); } } if (bullets.isEmpty() && (System.currentTimeMillis() / 500) % 2 == 0) { magazinePane.setItem(ModItems.EMPTY_MAGAZINE.get()); } else { magazinePane.setItemStack(ItemStack.EMPTY); } mainPane.render(guiGraphics, x, y); } }
0
0.82988
1
0.82988
game-dev
MEDIA
0.97708
game-dev
0.740589
1
0.740589
hakobast/flowzard
5,547
flowzard/src/main/java/hakobastvatsatryan/flowzard/router/SupportFragmentNavigator.kt
package hakobastvatsatryan.flowzard.router import android.app.Activity import android.content.Intent import android.support.v4.app.Fragment import android.support.v4.app.FragmentManager import android.support.v4.app.FragmentTransaction import android.support.v7.app.AppCompatActivity import hakobastvatsatryan.flowzard.Result import hakobastvatsatryan.flowzard.data.BundleDataBunch import java.util.* abstract class SupportFragmentNavigator(val activity: AppCompatActivity, private val containerId: Int ) : Navigator { protected abstract fun getActivityIntent(id: String, data: Any?): Intent protected abstract fun createFragment(screenKey: String, data: Any?): Fragment? protected abstract fun onExit() protected val stack: LinkedList<String?> = LinkedList() private val fragmentManager: FragmentManager get() { return activity.supportFragmentManager } override fun applyCommands(commands: Array<Command>) { this.fragmentManager.executePendingTransactions() this.copyStackFromFragmentManager() commands.forEach { applyCommand(it) } } protected open fun applyCommand(command: Command) { when (command) { is Command.StartFlow -> processStartFlowCommand(command) is Command.EndFlow -> processEndFlowCommand(command) is Command.Forward -> processForwardCommand(command) is Command.Replace -> processReplaceCommand(command) is Command.BackTo -> processBackToCommand(command) is Command.Back -> processBackCommand(command) is Command.Add -> processAddCommand(command) } } private fun processStartFlowCommand(command: Command.StartFlow) { val intent = getActivityIntent(command.id, command.data) intent.putExtra("flow-id", command.id) intent.putExtra("flow-instance-id", command.instanceId) if (command.requestCode != null) { activity.startActivityForResult(intent, command.requestCode) } else { activity.startActivity(intent) } } private fun processEndFlowCommand(command: Command.EndFlow) { if (command.result != null) { activity.setResult(resultToCode(command.result), resultToData(command.result)) } activity.finish() } protected open fun processForwardCommand(command: Command.Forward) { val fragment = this.createFragment(command.screenKey, command.data) if (fragment == null) { this.unknownScreen(command) } else { val transaction = this.fragmentManager.beginTransaction() this.processTransaction( command, this.fragmentManager.findFragmentById(this.containerId), fragment, transaction ) transaction.replace(this.containerId, fragment) .addToBackStack(command.screenKey) .commit() this.stack.add(command.screenKey) } } protected open fun processReplaceCommand(command: Command.Replace) { val fragment = this.createFragment(command.screenKey, command.data) if (fragment == null) { this.unknownScreen(command) } else { if (this.stack.size > 0) { this.fragmentManager.popBackStack() this.stack.pop() } val transaction = this.fragmentManager.beginTransaction() this.processTransaction( command, this.fragmentManager.findFragmentById(this.containerId), fragment, transaction ) transaction.replace(this.containerId, fragment) .addToBackStack(command.screenKey) .commit() this.stack.add(command.screenKey) } } protected open fun processAddCommand(command: Command.Add) { val fragment = this.createFragment(command.screenKey, command.data) if (fragment == null) { this.unknownScreen(command) } else { val transaction = this.fragmentManager.beginTransaction() this.processTransaction( command, this.fragmentManager.findFragmentById(this.containerId), fragment, transaction ) transaction.add(this.containerId, fragment) .addToBackStack(command.screenKey) .commit() this.stack.add(command.screenKey) } } protected open fun processBackToCommand(command: Command.BackTo) { val key = command.screenKey if (key == null) { this.backToRoot() } else { val index = this.stack.indexOf(key) val size = this.stack.size if (index != -1) { for (i in 1 until size - index) { this.stack.pop() } this.fragmentManager.popBackStack(key, 0) } else { this.backToUnexisting(command.screenKey) } } } protected open fun processBackCommand(command: Command.Back) { if (this.stack.size > 0) { this.fragmentManager.popBackStack() this.stack.pop() } else { this.onExit() } } private fun backToRoot() { this.fragmentManager.popBackStack(null, 1) this.stack.clear() } protected open fun processTransaction(command: Command, currentFragment: Fragment?, nextFragment: Fragment, fragmentTransaction: FragmentTransaction ) { } protected open fun unknownScreen(command: Command) { throw RuntimeException("Can't create a screen for passed screenKey.") } protected open fun backToUnexisting(screenKey: String) { this.backToRoot() } private fun copyStackFromFragmentManager() { val stackSize = this.fragmentManager.backStackEntryCount for (i in 0 until stackSize) { this.stack.add(this.fragmentManager.getBackStackEntryAt(i).name) } } private fun resultToCode(result: Result): Int { return when (result) { Result.CANCEL -> Activity.RESULT_CANCELED is Result.SUCCESS -> Activity.RESULT_OK } } private fun resultToData(result: Result): Intent? { return ((result as? Result.SUCCESS)?.data as? BundleDataBunch)?.let { Intent().putExtras(it.bundle) } } }
0
0.897381
1
0.897381
game-dev
MEDIA
0.287741
game-dev
0.956022
1
0.956022
Coloryr/AllMusic_Server
1,428
fabric_1_19_3/src/main/java/com/coloryr/allmusic/server/AllMusicFabric.java
package com.coloryr.allmusic.server; import com.coloryr.allmusic.server.core.AllMusic; import net.fabricmc.api.ModInitializer; import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback; import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents; import net.minecraft.server.MinecraftServer; import net.minecraft.util.Identifier; import okio.Buffer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; public class AllMusicFabric implements ModInitializer { public static MinecraftServer server; public static final Logger LOGGER = LoggerFactory.getLogger("AllMusic Server"); public static final Identifier ID = new Identifier("allmusic", "channel"); public static final String dir = "allmusic_server/"; @Override public void onInitialize() { AllMusic.log = new LogFabric(); AllMusic.side = new SideFabric(); new AllMusic().init(new File(dir)); CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess, environment) -> CommandFabric.instance.register(dispatcher)); Buffer buffer = new Buffer(); buffer.close(); ServerLifecycleEvents.SERVER_STARTED.register((a) -> { server = a; AllMusic.start(); Tasks.init(); }); ServerLifecycleEvents.SERVER_STOPPING.register((a) -> { AllMusic.stop(); }); } }
0
0.647646
1
0.647646
game-dev
MEDIA
0.928459
game-dev
0.815748
1
0.815748
PaperMC/Paper
2,072
paper-api/src/main/java/io/papermc/paper/event/entity/EntityEffectTickEvent.java
package io.papermc.paper.event.entity; import org.bukkit.entity.LivingEntity; import org.bukkit.event.Cancellable; import org.bukkit.event.HandlerList; import org.bukkit.event.entity.EntityEvent; import org.bukkit.potion.PotionEffectType; import org.jetbrains.annotations.ApiStatus; import org.jspecify.annotations.NullMarked; /** * An event that is triggered when an entity receives a potion effect instantly * or when the potion effect is applied on each tick (e.g. every 25 ticks for Poison level 1). * <p> * For example, this event may be called when an entity regenerates health * or takes poison damage as a result of a potion effect. */ @NullMarked public class EntityEffectTickEvent extends EntityEvent implements Cancellable { private static final HandlerList HANDLER_LIST = new HandlerList(); private final PotionEffectType type; private final int amplifier; private boolean cancelled; @ApiStatus.Internal public EntityEffectTickEvent(final LivingEntity entity, final PotionEffectType type, final int amplifier) { super(entity); this.type = type; this.amplifier = amplifier; } @Override public LivingEntity getEntity() { return (LivingEntity) super.getEntity(); } /** * Gets the type of the potion effect associated with this event. * * @return the {@link PotionEffectType} of the effect */ public PotionEffectType getType() { return type; } /** * Gets the amplifier level of the potion effect associated with this event. * * @return the amplifier level of the potion effect */ public int getAmplifier() { return amplifier; } @Override public boolean isCancelled() { return this.cancelled; } @Override public void setCancelled(final boolean cancel) { this.cancelled = cancel; } @Override public HandlerList getHandlers() { return HANDLER_LIST; } public static HandlerList getHandlerList() { return HANDLER_LIST; } }
0
0.846747
1
0.846747
game-dev
MEDIA
0.876048
game-dev
0.952266
1
0.952266
antonpup/CounterStrike2GSI
2,328
CounterStrike2GSI/Nodes/Provider.cs
using Newtonsoft.Json.Linq; namespace CounterStrike2GSI.Nodes { /// <summary> /// Information about the provider of this GameState. /// </summary> public class Provider : Node { /// <summary> /// Game name. /// </summary> public readonly string Name; /// <summary> /// Game Steam AppID. /// </summary> public readonly int AppID; /// <summary> /// Game version. /// </summary> public readonly int Version; /// <summary> /// Local player's Steam ID. /// </summary> public readonly string SteamID; /// <summary> /// Timestamp of the GameState data. /// </summary> public readonly int Timestamp; internal Provider(JObject parsed_data = null) : base(parsed_data) { Name = GetString("name"); AppID = GetInt("appid"); Version = GetInt("version"); SteamID = GetString("steamid"); Timestamp = GetInt("timestamp"); } /// <inheritdoc/> public override string ToString() { return $"[" + $"Name: {Name}, " + $"AppID: {AppID}, " + $"Version: {Version}, " + $"SteamID: {SteamID}" + $"Timestamp: {Timestamp}" + $"]"; } /// <inheritdoc/> public override bool Equals(object obj) { if (null == obj) { return false; } return obj is Provider other && Name.Equals(other.Name) && AppID == other.AppID && Version == other.Version && SteamID.Equals(other.SteamID); } /// <inheritdoc/> public override int GetHashCode() { int hashCode = 854512546; hashCode = hashCode * -845579214 + Name.GetHashCode(); hashCode = hashCode * -845579214 + AppID.GetHashCode(); hashCode = hashCode * -845579214 + Version.GetHashCode(); hashCode = hashCode * -845579214 + SteamID.GetHashCode(); hashCode = hashCode * -845579214 + Timestamp.GetHashCode(); return hashCode; } } }
0
0.602414
1
0.602414
game-dev
MEDIA
0.829424
game-dev
0.558428
1
0.558428
gama-platform/gama
9,987
gama.extension.physics/src/org/jbox2d/dynamics/contacts/Contact.java
/******************************************************************************* * Copyright (c) 2013, Daniel Murphy * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 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. ******************************************************************************/ package org.jbox2d.dynamics.contacts; import org.jbox2d.callbacks.ContactListener; import org.jbox2d.collision.ContactID; import org.jbox2d.collision.Manifold; import org.jbox2d.collision.ManifoldPoint; import org.jbox2d.collision.WorldManifold; import org.jbox2d.collision.shapes.Shape; import org.jbox2d.common.MathUtils; import org.jbox2d.common.Transform; import org.jbox2d.dynamics.Body; import org.jbox2d.dynamics.Fixture; import org.jbox2d.pooling.IWorldPool; /** * The class manages contact between two shapes. A contact exists for each overlapping AABB in the * broad-phase (except if filtered). Therefore a contact object may exist that has no contact * points. * * @author daniel */ public abstract class Contact { // Flags stored in m_flags // Used when crawling contact graph when forming islands. public static final int ISLAND_FLAG = 0x0001; // Set when the shapes are touching. public static final int TOUCHING_FLAG = 0x0002; // This contact can be disabled (by user) public static final int ENABLED_FLAG = 0x0004; // This contact needs filtering because a fixture filter was changed. public static final int FILTER_FLAG = 0x0008; // This bullet contact had a TOI event public static final int BULLET_HIT_FLAG = 0x0010; public static final int TOI_FLAG = 0x0020; public int m_flags; // World pool and list pointers. public Contact m_prev; public Contact m_next; // Nodes for connecting bodies. public ContactEdge m_nodeA = null; public ContactEdge m_nodeB = null; public Fixture m_fixtureA; public Fixture m_fixtureB; public int m_indexA; public int m_indexB; public final Manifold m_manifold; public float m_toiCount; public float m_toi; public float m_friction; public float m_restitution; public float m_tangentSpeed; protected final IWorldPool pool; protected Contact(IWorldPool argPool) { m_fixtureA = null; m_fixtureB = null; m_nodeA = new ContactEdge(); m_nodeB = new ContactEdge(); m_manifold = new Manifold(); pool = argPool; } /** initialization for pooling */ public void init(Fixture fA, int indexA, Fixture fB, int indexB) { m_flags = ENABLED_FLAG; m_fixtureA = fA; m_fixtureB = fB; m_indexA = indexA; m_indexB = indexB; m_manifold.pointCount = 0; m_prev = null; m_next = null; m_nodeA.contact = null; m_nodeA.prev = null; m_nodeA.next = null; m_nodeA.other = null; m_nodeB.contact = null; m_nodeB.prev = null; m_nodeB.next = null; m_nodeB.other = null; m_toiCount = 0; m_friction = Contact.mixFriction(fA.m_friction, fB.m_friction); m_restitution = Contact.mixRestitution(fA.m_restitution, fB.m_restitution); m_tangentSpeed = 0; } /** * Get the contact manifold. Do not set the point count to zero. Instead call Disable. */ public Manifold getManifold() { return m_manifold; } /** * Get the world manifold. */ public void getWorldManifold(WorldManifold worldManifold) { final Body bodyA = m_fixtureA.getBody(); final Body bodyB = m_fixtureB.getBody(); final Shape shapeA = m_fixtureA.getShape(); final Shape shapeB = m_fixtureB.getShape(); worldManifold.initialize(m_manifold, bodyA.getTransform(), shapeA.m_radius, bodyB.getTransform(), shapeB.m_radius); } /** * Is this contact touching * * @return */ public boolean isTouching() { return (m_flags & TOUCHING_FLAG) == TOUCHING_FLAG; } /** * Enable/disable this contact. This can be used inside the pre-solve contact listener. The * contact is only disabled for the current time step (or sub-step in continuous collisions). * * @param flag */ public void setEnabled(boolean flag) { if (flag) { m_flags |= ENABLED_FLAG; } else { m_flags &= ~ENABLED_FLAG; } } /** * Has this contact been disabled? * * @return */ public boolean isEnabled() { return (m_flags & ENABLED_FLAG) == ENABLED_FLAG; } /** * Get the next contact in the world's contact list. * * @return */ public Contact getNext() { return m_next; } /** * Get the first fixture in this contact. * * @return */ public Fixture getFixtureA() { return m_fixtureA; } public int getChildIndexA() { return m_indexA; } /** * Get the second fixture in this contact. * * @return */ public Fixture getFixtureB() { return m_fixtureB; } public int getChildIndexB() { return m_indexB; } public void setFriction(float friction) { m_friction = friction; } public float getFriction() { return m_friction; } public void resetFriction() { m_friction = Contact.mixFriction(m_fixtureA.m_friction, m_fixtureB.m_friction); } public void setRestitution(float restitution) { m_restitution = restitution; } public float getRestitution() { return m_restitution; } public void resetRestitution() { m_restitution = Contact.mixRestitution(m_fixtureA.m_restitution, m_fixtureB.m_restitution); } public void setTangentSpeed(float speed) { m_tangentSpeed = speed; } public float getTangentSpeed() { return m_tangentSpeed; } public abstract void evaluate(Manifold manifold, Transform xfA, Transform xfB); /** * Flag this contact for filtering. Filtering will occur the next time step. */ public void flagForFiltering() { m_flags |= FILTER_FLAG; } // djm pooling private final Manifold oldManifold = new Manifold(); public void update(ContactListener listener) { oldManifold.set(m_manifold); // Re-enable this contact. m_flags |= ENABLED_FLAG; boolean touching = false; boolean wasTouching = (m_flags & TOUCHING_FLAG) == TOUCHING_FLAG; boolean sensorA = m_fixtureA.isSensor(); boolean sensorB = m_fixtureB.isSensor(); boolean sensor = sensorA || sensorB; Body bodyA = m_fixtureA.getBody(); Body bodyB = m_fixtureB.getBody(); Transform xfA = bodyA.getTransform(); Transform xfB = bodyB.getTransform(); // log.debug("TransformA: "+xfA); // log.debug("TransformB: "+xfB); if (sensor) { Shape shapeA = m_fixtureA.getShape(); Shape shapeB = m_fixtureB.getShape(); touching = pool.getCollision().testOverlap(shapeA, m_indexA, shapeB, m_indexB, xfA, xfB); // Sensors don't generate manifolds. m_manifold.pointCount = 0; } else { evaluate(m_manifold, xfA, xfB); touching = m_manifold.pointCount > 0; // Match old contact ids to new contact ids and copy the // stored impulses to warm start the solver. for (int i = 0; i < m_manifold.pointCount; ++i) { ManifoldPoint mp2 = m_manifold.points[i]; mp2.normalImpulse = 0.0f; mp2.tangentImpulse = 0.0f; ContactID id2 = mp2.id; for (int j = 0; j < oldManifold.pointCount; ++j) { ManifoldPoint mp1 = oldManifold.points[j]; if (mp1.id.isEqual(id2)) { mp2.normalImpulse = mp1.normalImpulse; mp2.tangentImpulse = mp1.tangentImpulse; break; } } } if (touching != wasTouching) { bodyA.setAwake(true); bodyB.setAwake(true); } } if (touching) { m_flags |= TOUCHING_FLAG; } else { m_flags &= ~TOUCHING_FLAG; } if (listener == null) { return; } if (wasTouching == false && touching == true) { listener.beginContact(this); } if (wasTouching == true && touching == false) { listener.endContact(this); } if (sensor == false && touching) { listener.preSolve(this, oldManifold); } } /** * Friction mixing law. The idea is to allow either fixture to drive the restitution to zero. For * example, anything slides on ice. * * @param friction1 * @param friction2 * @return */ public static final float mixFriction(float friction1, float friction2) { return MathUtils.sqrt(friction1 * friction2); } /** * Restitution mixing law. The idea is allow for anything to bounce off an inelastic surface. For * example, a superball bounces on anything. * * @param restitution1 * @param restitution2 * @return */ public static final float mixRestitution(float restitution1, float restitution2) { return restitution1 > restitution2 ? restitution1 : restitution2; } }
0
0.958121
1
0.958121
game-dev
MEDIA
0.526764
game-dev
0.972391
1
0.972391
hackclub/sprig
8,003
games/Treasure Maze (Correct Version).js
/* @title: Treasure Maze @description: Treasure Maze is a maze game where you have to avoid guards to reach the treasure at the end of the maze. @author: AiyuuHacks @tags: [] @addedOn: 2024-09-03 */ const player = "p" const obstacle1 = "1" const obstacle2 = "2" const obstacle3 = "3" const obstacle4 = "4" const obstacle5 = "5" const obstacle6 = "6" const obstacle7 = "7" const wall = "w" const chest = "c" const o1Path = [1,1,1,1,1,1,1,1,1,-1,-1,-1,-1,-1,-1,-1,-1,-1] const o2Path = [1,1,1,1,1,-1,-1,-1,-1,-1] const o3Path = [1,1,1,1,1,1,1,-1,-1,-1,-1,-1,-1,-1] const o4Path = [1,1,1,1,1,1,1,1,1,1,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1] const o5Path = [1,1,1,1,1,1,1,1,-1,-1,-1,-1,-1,-1,-1,-1] const o6Path = [1,1,1,1,1,1,-1,-1,-1,-1,-1,-1] const o7Path = [1,1,1,1,1,1,1,1,1,-1,-1,-1,-1,-1,-1,-1,-1,-1] setLegend( [player, bitmap` .......0000..... ......0LLLL00... .....033333330.. ....030000000... .....0L252520... ....0LLLLLLL0... ...030LLLLLL0... ....0.0000000... .....0LLLLL0.... ....0LL0LLL01... ....0110LLL11... ....011LLLL0.... .....00000000... ....0660..0990.. ....0000..0000.. ................`], [obstacle1, bitmap` ................ ......000000.... ....00055550.... ...0055566500... ...0555666650... ...00000000000.. ...0222222220... ...0223222320... ...0222CCC220... ...000C222C00... .....0000000.... .....0555550.006 ...0005555500066 ..00.0777550.006 .....0777770.... .....0777770....`], [obstacle2, bitmap` ................ ......000000.... ....00055550.... ...0055566500... ...0555666650... ...00000000000.. ...0222222220... ...0223222320... ...0222CCC220... ...000C222C00... .....0000000.... .....0555550.006 ...0005555500066 ..00.0777550.006 .....0777770.... .....0777770....`], [obstacle3, bitmap` ................ ......000000.... ....00055550.... ...0055566500... ...0555666650... ...00000000000.. ...0222222220... ...0223222320... ...0222CCC220... ...000C222C00... .....0000000.... .....0555550.006 ...0005555500066 ..00.0777550.006 .....0777770.... .....0777770....`], [obstacle4, bitmap` ................ ......000000.... ....00055550.... ...0055566500... ...0555666650... ...00000000000.. ...0222222220... ...0223222320... ...0222CCC220... ...000C222C00... .....0000000.... .....0555550.006 ...0005555500066 ..00.0777550.006 .....0777770.... .....0777770....`], [obstacle5, bitmap` ................ ......000000.... ....00055550.... ...0055566500... ...0555666650... ...00000000000.. ...0222222220... ...0223222320... ...0222CCC220... ...000C222C00... .....0000000.... .....0555550.006 ...0005555500066 ..00.0777550.006 .....0777770.... .....0777770....`], [obstacle6, bitmap` ................ ......000000.... ....00055550.... ...0055566500... ...0555666650... ...00000000000.. ...0222222220... ...0223222320... ...0222CCC220... ...000C222C00... .....0000000.... .....0555550.006 ...0005555500066 ..00.0777550.006 .....0777770.... .....0777770....`], [obstacle7, bitmap` ................ ......000000.... ....00055550.... ...0055566500... ...0555666650... ...00000000000.. ...0222222220... ...0223222320... ...0222CCC220... ...000C222C00... .....0000000.... .....0555550.006 ...0005555500066 ..00.0777550.006 .....0777770.... .....0777770....`], [wall, bitmap` 0003000030000033 0000300030000030 0000300330000030 0003300033000330 0003000003003300 0003000033003000 0000000000033000 0000000000030000 0000333000000000 0003300000000000 3330000000033000 0000033000003300 0000003000000300 0030000330003300 0330000030000330 3300000030000030`], [chest, bitmap` ................ ................ ................ ................ ................ ....00000000.... ...00CCCCCC00... ..00CCCCCCCC00.. .00CCCCCCCCCC00. .0CCCC6666CCCC0. .00000600600000. .0CCCC6666CCCC0. .0CCCCCCCCCCCC0. .00000000000000. ................ ................`], ) setSolids([wall, player]) setMap(map` c....w7......... wwww.w.www.w..w. 4...........ww6. .ww.www.w.w....w .w...w5.w..www.w ww.w.w..ww.w.w.w 3w...w.......w.w ...www.w.ww..w.. .ww....w..w..w.. .w..ww.w2.....w. ..w.w..wwww.www. .w..ww....w..... .ww.........ww.. .....www..w..w.. wwww.w.w.w.www.. p....w1.........`) onInput("d", () => { var p = getFirst(player) p.x += 1 }) onInput("a", () => { var p = getFirst(player) p.x -= 1 }) onInput("w", () => { var p = getFirst(player) p.y -= 1 }) onInput("s", () => { var p = getFirst(player) p.y += 1 }) function playerWin(){ var chests = getAll(chest) var p = getFirst(player) for (var i = 0; i<chests.length; i++){ var c = chests [i] if (c.x == p.x && c.y == p.y){ return true } } return false } function playerHit1(){ var obstacles1 = getAll(obstacle1) var p = getFirst(player) for (var i = 0; i<obstacles1.length; i++){ var o = obstacles1 [i] if (o.x == p.x && o.y == p.y){ return true } } return false } function playerHit2(){ var obstacles2 = getAll(obstacle2) var p = getFirst(player) for (var i = 0; i<obstacles2.length; i++){ var o = obstacles2 [i] if (o.x == p.x && o.y == p.y){ return true } } return false } function playerHit3(){ var obstacles3 = getAll(obstacle3) var p = getFirst(player) for (var i = 0; i<obstacles3.length; i++){ var o = obstacles3 [i] if (o.x == p.x && o.y == p.y){ return true } } return false } function playerHit4(){ var obstacles4 = getAll(obstacle4) var p = getFirst(player) for (var i = 0; i<obstacles4.length; i++){ var o = obstacles4 [i] if (o.x == p.x && o.y == p.y){ return true } } return false } function playerHit5(){ var obstacles5 = getAll(obstacle5) var p = getFirst(player) for (var i = 0; i<obstacles5.length; i++){ var o = obstacles5 [i] if (o.x == p.x && o.y == p.y){ return true } } return false } function playerHit6(){ var obstacles6 = getAll(obstacle6) var p = getFirst(player) for (var i = 0; i<obstacles6.length; i++){ var o = obstacles6 [i] if (o.x == p.x && o.y == p.y){ return true } } return false } function playerHit7(){ var obstacles7 = getAll(obstacle7) var p = getFirst(player) for (var i = 0; i<obstacles7.length; i++){ var o = obstacles7 [i] if (o.x == p.x && o.y == p.y){ return true } } return false } var cnt = 0 var cnt2 = 0 var cnt3 = 0 var cnt4 = 0 var cnt5 = 0 var cnt6 = 0 var cnt7 = 0 var gameLoop = setInterval(() => { var o1 = getFirst(obstacle1) o1.x += o1Path[cnt] cnt++ if(cnt>18){cnt=0} var o2 = getFirst(obstacle2) o2.x += o2Path[cnt2] cnt2++ if(cnt2>9){cnt2=0} var o3 = getFirst(obstacle3) o3.y += o3Path[cnt3] cnt3++ if(cnt3>13){cnt3=0} var o4 = getFirst(obstacle4) o4.x += o4Path[cnt4] cnt4++ if(cnt4>21){cnt4=0} var o5 = getFirst(obstacle5) o5.y += o5Path[cnt5] cnt5++ if(cnt5>15){cnt5=0} var o6 = getFirst(obstacle6) o6.y += o6Path[cnt6] cnt6++ if(cnt6>11){cnt6=0} var o7 = getFirst(obstacle7) o7.x += o7Path[cnt7] cnt7++ if(cnt7>17){cnt7=0} if (playerWin() == true){ clearInterval(gameLoop) addText("You Win!",{ color: color`3` }) } if (playerHit1() == true){ clearInterval(gameLoop) addText("You Lose!",{ color: color`3` }) } if (playerHit2() == true){ clearInterval(gameLoop) addText("You Lose!",{ color: color`3` }) } if (playerHit3() == true){ clearInterval(gameLoop) addText("You Lose!",{ color: color`3` }) } if (playerHit4() == true){ clearInterval(gameLoop) addText("You Lose!",{ color: color`3` }) } if (playerHit5() == true){ clearInterval(gameLoop) addText("You Lose!",{ color: color`3` }) } if (playerHit6() == true){ clearInterval(gameLoop) addText("You Lose!",{ color: color`3` }) } if (playerHit7() == true){ clearInterval(gameLoop) addText("You Lose!",{ color: color`3` }) } }, 150)
0
0.534541
1
0.534541
game-dev
MEDIA
0.86655
game-dev
0.68787
1
0.68787
pret/pokediamond
2,508
arm9/src/scrcmd_items.c
#include "global.h" #include "bag.h" #include "scrcmd.h" extern BOOL sub_02054CB0(u16 item_id); BOOL ScrCmd_GiveItem(struct ScriptContext *ctx) // 007B { struct FieldSystem *fieldSystem = ctx->fieldSystem; u16 item_id = ScriptGetVar(ctx); u16 quantity = ScriptGetVar(ctx); u16 *item_was_added = ScriptGetVarPointer(ctx); struct Bag *bag = Save_Bag_Get(fieldSystem->saveData); *item_was_added = (u16)Bag_AddItem(bag, item_id, quantity, HEAP_ID_4); return FALSE; } BOOL ScrCmd_TakeItem(struct ScriptContext *ctx) // 007C { struct FieldSystem *fieldSystem = ctx->fieldSystem; u16 item_id = ScriptGetVar(ctx); u16 quantity = ScriptGetVar(ctx); u16 *item_was_taken = ScriptGetVarPointer(ctx); struct Bag *bag = Save_Bag_Get(fieldSystem->saveData); *item_was_taken = (u16)Bag_TakeItem(bag, item_id, quantity, HEAP_ID_4); return FALSE; } BOOL ScrCmd_HasSpaceForItem(struct ScriptContext *ctx) // 007D { struct FieldSystem *fieldSystem = ctx->fieldSystem; u16 item_id = ScriptGetVar(ctx); u16 quantity = ScriptGetVar(ctx); u16 *has_space = ScriptGetVarPointer(ctx); struct Bag *bag = Save_Bag_Get(fieldSystem->saveData); *has_space = (u16)Bag_HasSpaceForItem(bag, item_id, quantity, HEAP_ID_4); return FALSE; } BOOL ScrCmd_HasItem(struct ScriptContext *ctx) // 007E { struct FieldSystem *fieldSystem = ctx->fieldSystem; u16 item_id = ScriptGetVar(ctx); u16 quantity = ScriptGetVar(ctx); u16 *has_item = ScriptGetVarPointer(ctx); struct Bag *bag = Save_Bag_Get(fieldSystem->saveData); *has_item = (u16)Bag_HasItem(bag, item_id, quantity, HEAP_ID_FIELD); return FALSE; } BOOL ScrCmd_ItemIdIsTMOrHM(struct ScriptContext *ctx) // 007F { struct FieldSystem *fieldSystem = ctx->fieldSystem; u16 item_id = ScriptGetVar(ctx); u16 *is_tm_or_hm = ScriptGetVarPointer(ctx); *is_tm_or_hm = (u16)sub_02054CB0(item_id); return FALSE; } BOOL ScrCmd_GetItemPocketId(struct ScriptContext *ctx) // 0080 { struct FieldSystem *fieldSystem = ctx->fieldSystem; u16 item_id = ScriptGetVar(ctx); u16 *pocket = ScriptGetVarPointer(ctx); *pocket = (u16)GetItemAttr(item_id, ITEMATTR_POCKET, HEAP_ID_FIELD); return FALSE; } BOOL ScrCmd_Unk0081(struct ScriptContext *ctx) // 0081 - todo: DummyGiveItem? { #pragma unused(ctx) return FALSE; } BOOL ScrCmd_Unk0082(struct ScriptContext *ctx) // 0082 - todo: DummyHasItem? { #pragma unused(ctx) return FALSE; }
0
0.914634
1
0.914634
game-dev
MEDIA
0.671004
game-dev
0.851669
1
0.851669
Sandrem/FlyCasual
3,764
Assets/Scripts/Model/SquadBuilder/SquadBuilder.cs
using Editions; using Players; using System; using Upgrade; namespace SquadBuilderNS { public class SquadBuilder { //TODO: Hide public ContentDatabase Database; public SquadLists SquadLists; public SquadBuilderView View { get; set; } public PlayerNo CurrentPlayer; public SquadList CurrentSquad => SquadLists[CurrentPlayer]; // TEMP??? public SquadListShip CurrentShip { get; set; } public UpgradeSlot CurrentUpgradeSlot { get; set; } public string CurrentShipName { get; set; } //TEMP public static SquadBuilder Instance; public SquadBuilder() { Instance = this; GenerateDatabase(); SquadLists = new SquadLists(); CurrentPlayer = PlayerNo.Player1; } public void GenerateDatabase() { Database = new ContentDatabase(Edition.Current); } public void SetPlayers(string modeName) { SetPlayerTypesByMode(modeName); SetDefaultPlayerNames(); } private void SetPlayerTypesByMode(string modeName) { switch (modeName) { case "vsAI": SetPlayerTypes(typeof(HumanPlayer), typeof(AggressorAiPlayer)); break; case "Internet": SetPlayerTypes(typeof(HumanPlayer), typeof(NetworkOpponentPlayer)); break; case "HotSeat": SetPlayerTypes(typeof(HumanPlayer), typeof(HumanPlayer)); break; case "AIvsAI": SetPlayerTypes(typeof(AggressorAiPlayer), typeof(AggressorAiPlayer)); break; case "Replay": SetPlayerTypes(typeof(ReplayPlayer), typeof(ReplayPlayer)); break; default: break; } } private void SetPlayerTypes(Type playerOneType, Type playerTwoType) { SquadLists[PlayerNo.Player1].PlayerType = playerOneType; SquadLists[PlayerNo.Player2].PlayerType = playerTwoType; } public void SetDefaultPlayerNames() { SquadLists[PlayerNo.Player1].GenerateDefaultNameForSquad(); SquadLists[PlayerNo.Player2].GenerateDefaultNameForSquad(); } public void SaveAutosaveSquadConfigurations() { if (!DebugManager.DebugNetworkSingleDevice) { for (int i = 0; i < 2; i++) { try { SquadLists[Tools.IntToPlayer(i + 1)].SaveSquadronToFile("Autosave (Player " + (i + 1) + ")"); } catch (Exception) { DebugManager.DebugNetworkSingleDevice = true; } } } } public void GenerateSavedConfigurationsLocal() { // TODO: Change to Enumerator foreach (SquadList squad in SquadLists.Squads.Values) { squad.SavedConfiguration = squad.GetSquadInJson(); JSONObject playerInfoJson = new JSONObject(); playerInfoJson.AddField("NickName", Options.NickName); playerInfoJson.AddField("Title", Options.Title); playerInfoJson.AddField("Avatar", Options.Avatar); squad.SavedConfiguration.AddField("PlayerInfo", playerInfoJson); } } public void ReGenerateSquads() { SquadLists.ReGenerateSquads(); } } }
0
0.831119
1
0.831119
game-dev
MEDIA
0.855238
game-dev
0.903704
1
0.903704
MrStahlfelge/lightblocks
5,546
core/src/de/golfgl/lightblocks/state/TotalScore.java
package de.golfgl.lightblocks.state; import com.badlogic.gdx.utils.Json; import com.badlogic.gdx.utils.JsonValue; import de.golfgl.gdxgamesvcs.IGameServiceClient; import de.golfgl.lightblocks.backend.PlayerDetails; import de.golfgl.lightblocks.gpgs.GpgsHelper; /** * Der Total Score nimmt die gesamten Punktzahlen für den Spieler auf * <p> * Created by Benjamin Schulte on 07.02.2017. */ public class TotalScore implements Json.Serializable { private static final String KEY_MAX_COMBO_COUNT = "maxComboCount"; // der aktuelle Punktestand private long score; // die abgebauten Reihen private long clearedLines; // Anzahl gezogene Blöcke private long drawnTetrominos; private long fourLineCount; private long tSpins; private long doubles; private long multiPlayerMatchesWon; private long multiPlayerMatchesStarted; private int maxComboCount; public void addScore(long score) { this.score += score; } public long getScore() { return score; } public long getClearedLines() { return clearedLines; } public void addClearedLines(long clearedLines) { this.clearedLines += clearedLines; } public long getDrawnTetrominos() { return drawnTetrominos; } public void incDrawnTetrominos() { this.drawnTetrominos += 1; } public long getFourLineCount() { return fourLineCount; } public void incFourLineCount() { this.fourLineCount += 1; } public long getTSpins() { return tSpins; } public void incTSpins() { this.tSpins += 1; } public long getDoubles() { return doubles; } public void incDoubles() { this.doubles += 1; } public long getMultiPlayerMatchesWon() { return multiPlayerMatchesWon; } public void incMultiPlayerMatchesWon() { this.multiPlayerMatchesWon += 1; } public long getMultiPlayerMatchesStarted() { return multiPlayerMatchesStarted; } public void incMultiPlayerMatchesStarted() { this.multiPlayerMatchesStarted += 1; } public int getMaxComboCount() { return maxComboCount; } public boolean setMaxComboCount(int maxComboCount) { if (maxComboCount > this.maxComboCount) { this.maxComboCount = maxComboCount; return true; } return false; } protected void mergeWithOther(TotalScore totalScore) { if (totalScore.getScore() > score) score = totalScore.getScore(); if (totalScore.getClearedLines() > clearedLines) clearedLines = totalScore.getClearedLines(); if (totalScore.drawnTetrominos > drawnTetrominos) drawnTetrominos = totalScore.drawnTetrominos; if (totalScore.getFourLineCount() > fourLineCount) fourLineCount = totalScore.getFourLineCount(); if (totalScore.getTSpins() > tSpins) tSpins = totalScore.getTSpins(); if (totalScore.getDoubles() > doubles) doubles = totalScore.getDoubles(); if (totalScore.getMultiPlayerMatchesStarted() > multiPlayerMatchesStarted) multiPlayerMatchesStarted = totalScore.getMultiPlayerMatchesStarted(); if (multiPlayerMatchesWon < totalScore.getMultiPlayerMatchesWon()) multiPlayerMatchesWon = totalScore.getMultiPlayerMatchesWon(); setMaxComboCount(totalScore.getMaxComboCount()); } public void mergeWithPlayerDetails(PlayerDetails playerDetails) { if (playerDetails.countTotalBlocks > drawnTetrominos) drawnTetrominos = playerDetails.countTotalBlocks; } public void checkAchievements(IGameServiceClient gpgsClient) { // Warum werden die Achievements nicht immer kontrolliert? Ganz einfach: Falls dieses Objekt // gar nicht der tatsächliche Spielstand ist, sondern nur ein geladener o.ä. // reduziert außerdem die Anzahl der Meldungen an GPGS if (gpgsClient == null || !gpgsClient.isSessionActive()) return; if (score >= 1000000) gpgsClient.unlockAchievement(GpgsHelper.ACH_SCORE_MILLIONAIRE); if (maxComboCount >= 7) gpgsClient.unlockAchievement(GpgsHelper.ACH_COMBINATOR); } @Override public void write(Json json) { json.writeValue("score", score); json.writeValue("clearedLines", clearedLines); json.writeValue("drawnTetrominos", drawnTetrominos); json.writeValue("fourLineCount", fourLineCount); json.writeValue("tSpins", tSpins); json.writeValue("doubles", doubles); json.writeValue("multiPlayerMatchesWon", multiPlayerMatchesWon); json.writeValue("multiPlayerMatchesStarted", multiPlayerMatchesStarted); json.writeValue(KEY_MAX_COMBO_COUNT, maxComboCount); } @Override public void read(Json json, JsonValue jsonData) { score = jsonData.getLong("score", 0); clearedLines = jsonData.getLong("clearedLines", 0); drawnTetrominos = jsonData.getLong("drawnTetrominos", 0); fourLineCount = jsonData.getLong("fourLineCount", 0); tSpins = jsonData.getLong("tSpins", 0); doubles = jsonData.getLong("doubles", 0); multiPlayerMatchesWon = jsonData.getLong("multiPlayerMatchesWon", 0); multiPlayerMatchesStarted = jsonData.getLong("multiPlayerMatchesStarted", 0); maxComboCount = jsonData.getInt(KEY_MAX_COMBO_COUNT, 0); } }
0
0.804398
1
0.804398
game-dev
MEDIA
0.747031
game-dev
0.820729
1
0.820729
CCBlueX/LiquidBounce
2,836
src/main/java/net/ccbluex/liquidbounce/injection/mixins/minecraft/client/MixinKeyboard.java
/* * This file is part of LiquidBounce (https://github.com/CCBlueX/LiquidBounce) * * Copyright (c) 2015 - 2025 CCBlueX * * LiquidBounce 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. * * LiquidBounce 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 LiquidBounce. If not, see <https://www.gnu.org/licenses/>. */ package net.ccbluex.liquidbounce.injection.mixins.minecraft.client; import net.ccbluex.liquidbounce.event.EventManager; import net.ccbluex.liquidbounce.event.events.KeyEvent; import net.ccbluex.liquidbounce.event.events.KeyboardCharEvent; import net.ccbluex.liquidbounce.event.events.KeyboardKeyEvent; import net.minecraft.client.Keyboard; import net.minecraft.client.MinecraftClient; import net.minecraft.client.util.InputUtil; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(Keyboard.class) public class MixinKeyboard { @Shadow @Final private MinecraftClient client; /** * Hook key event */ @Inject(method = "onKey", at = @At(value = "FIELD", target = "Lnet/minecraft/client/MinecraftClient;currentScreen:Lnet/minecraft/client/gui/screen/Screen;", shift = At.Shift.BEFORE, ordinal = 0)) private void hookKeyboardKey(long window, int key, int scancode, int i, int j, CallbackInfo callback) { // does if (window == this.client.getWindow().getHandle()) var inputKey = InputUtil.fromKeyCode(key, scancode); EventManager.INSTANCE.callEvent(new KeyboardKeyEvent(inputKey, key, scancode, i, j, this.client.currentScreen)); if (client.currentScreen == null) { EventManager.INSTANCE.callEvent(new KeyEvent(inputKey, i)); } } /** * Hook char event */ @Inject(method = "onChar", at = @At(value = "FIELD", target = "Lnet/minecraft/client/MinecraftClient;currentScreen:Lnet/minecraft/client/gui/screen/Screen;", shift = At.Shift.BEFORE)) private void hookKeyboardChar(long window, int codePoint, int modifiers, CallbackInfo callback) { // does if (window == this.client.getWindow().getHandle()) EventManager.INSTANCE.callEvent(new KeyboardCharEvent(codePoint, modifiers)); } }
0
0.591407
1
0.591407
game-dev
MEDIA
0.784451
game-dev
0.562761
1
0.562761
mariopartyrd/marioparty4
55,684
src/REL/ztardll/main.c
#include "ext_math.h" #include "game/chrman.h" #include "game/gamework.h" #include "game/gamework_data.h" #include "game/hsfdraw.h" #include "game/hsfman.h" #include "game/hsfmotion.h" #include "game/objsub.h" #include "game/pad.h" #include "game/sprite.h" #include "game/window.h" #include "game/wipe.h" #include "REL/ztardll.h" extern s32 charVoiceGroupStat[8]; void fn_1_1774(void); void fn_1_1CF0(void); void fn_1_1DA0(void); void fn_1_2350(void); void fn_1_33B0(void); void fn_1_40E4(void); void fn_1_424(void); void fn_1_4374(void); void fn_1_4948(void); void fn_1_51BC(s16 arg0); s32 fn_1_524C(s32 arg0); void fn_1_66F8(void); void fn_1_7414(ModelData *model, Mtx matrix); omObjData *lbl_1_bss_6C; Process *lbl_1_bss_68; s32 lbl_1_bss_64; s32 lbl_1_bss_60; s16 lbl_1_bss_5E; s16 lbl_1_bss_5C; s16 lbl_1_bss_5A; s16 lbl_1_bss_58; s32 lbl_1_bss_54; s16 lbl_1_bss_52; s16 lbl_1_bss_50; s16 lbl_1_bss_4C[2]; s16 lbl_1_bss_4A; s16 lbl_1_bss_48; s16 lbl_1_bss_46; s16 lbl_1_bss_44; s16 lbl_1_bss_42; s16 lbl_1_bss_3E[2]; s16 lbl_1_bss_36[4]; s16 lbl_1_bss_E[4][5]; s16 lbl_1_bss_C; Process *lbl_1_bss_8; s16 lbl_1_bss_4; s32 lbl_1_bss_0; void ObjectSetup(void) { s32 var_r31; s32 var_r30; OSReport("******* ZP ObjectSetup *********\n"); lbl_1_bss_68 = omInitObjMan(0x32, 0x2000); lbl_1_bss_60 = 0; lbl_1_bss_58 = omovlevtno; _ClearFlag(0x10000); _ClearFlag(0x10008); GWSystem.mg_type = -1; GWSystem.player_curr = 0; lbl_1_bss_5E = -1; mgBoardHostEnableF = 1; var_r30 = omMgIndexGet(0x29); lbl_1_bss_54 = GWMGAvailGet(var_r30 + 0x191); Hu3DCameraCreate(1); Hu3DCameraPerspectiveSet(1, 30.0f, 20.0f, 15000.0f, 1.2f); Hu3DCameraViewportSet(1, 0.0f, 0.0f, 640.0f, 480.0f, 0.0f, 1.0f); CRot.x = 0.0f; CRot.y = 0.0f; CRot.z = 0.0f; Center.x = 0.0f; Center.y = 90.0f; Center.z = 30.0f; CZoom = 1220.0f; var_r31 = Hu3DGLightCreate(0.0f, 100.0f, 1000.0f, 0.0f, -0.5f, -1.0f, 0xFF, 0xFF, 0xFF); Hu3DGLightInfinitytSet(var_r31); HuPrcChildCreate(fn_1_424, 0x64, 0x3000, 0, lbl_1_bss_68); HuPrcChildCreate(fn_1_66F8, 0xC8, 0x1000, 0, lbl_1_bss_68); lbl_1_bss_6C = omAddObjEx(lbl_1_bss_68, 0x7FDA, 0, 0, -1, omOutView); Hu3DBGColorSet(0, 0, 0); HuWinInit(1); if (lbl_1_bss_58 == 1) { HuAudVoiceInit(-1); } if (lbl_1_bss_58 != 0) { HuAudSndGrpSetSet(4); HuAudSeqPlay(0x2E); } GWSystem.mg_type = -1; mgPracticeEnableF = 1; } s16 lbl_1_data_22[4] = { 0x3A, 0xC8, 0x166, 0xC8 }; void fn_1_424(void) { Vec sp2C; Vec sp20; Vec sp14; Vec sp8; float var_f31; float var_f30; s16 var_r31; s16 var_r30; s16 var_r29; s16 var_r28; s16 var_r27; s16 var_r26; var_r26 = 0; var_r27 = 0; fn_1_7D6C(lbl_1_bss_68); HuPrcVSleep(); HuDataDirClose(DATADIR_MPEX); lbl_1_bss_5A = 0; if (mgQuitExtraF != 0) { mgQuitExtraF = 0; var_r26 = 1; lbl_1_bss_58 = 0; } else { if (lbl_1_bss_58 == 1) { lbl_1_bss_5A = 0; goto block_92; } if (lbl_1_bss_58 == 2) { lbl_1_bss_5A = 1; goto block_93; } GWPlayerCfg[0].group = GWPlayerCfg[1].group = 0; GWPlayerCfg[2].group = GWPlayerCfg[3].group = 1; } block_7: fn_1_1774(); if (lbl_1_bss_54 == 0) { HuSprTPLvlSet(lbl_1_bss_4C[1], 0, 0.5f); HuSprTPLvlSet(lbl_1_bss_4C[1], 2, 0.5f); } if (var_r26 == 0) { WipeCreate(WIPE_MODE_IN, WIPE_TYPE_NORMAL, 30); HuPrcSleep(0xA); sp2C.x = 510.0f; sp2C.y = 80.0f; sp2C.z = 1500.0f; Hu3D2Dto3D(&sp2C, 1, &sp8); sp2C.x = 200.0f; sp2C.y = 400.0f; sp2C.z = 100.0f; Hu3D2Dto3D(&sp2C, 1, &sp20); VECSubtract(&sp8, &sp20, &sp14); for (var_r31 = 0; var_r31 <= 0x1E; var_r31++) { if (var_r31 <= 0x14) { var_f31 = var_r31 / 20.0; HuSprGrpPosSet(lbl_1_bss_52, 288.0f, 80.0 - (180.0 * (1.0 - sind((90.0f * var_f31))))); HuSprGrpPosSet(lbl_1_bss_50, 288.0f, 80.0 - (180.0 * (1.0 - sind((90.0f * var_f31))))); HuSprGrpPosSet(lbl_1_bss_4C[0], 138.0 - (300.0 * (1.0 - sind((90.0f * var_f31)))), 240.0f); HuSprGrpPosSet(lbl_1_bss_4C[1], 438.0 + (300.0 * (1.0 - sind((90.0f * var_f31)))), 240.0f); } var_f31 = var_r31 / 30.0; VECScale(&sp14, &sp2C, var_f31); VECAdd(&sp2C, &sp20, &sp2C); Hu3DModelRotSet(lbl_1_bss_42, 0.0f, -10.0f, -15.0f); Hu3DModelPosSetV(lbl_1_bss_42, &sp2C); HuPrcVSleep(); } } else { sp2C.x = 510.0f; sp2C.y = 80.0f; sp2C.z = 1500.0f; Hu3D2Dto3D(&sp2C, 1, &sp20); Hu3DModelRotSet(lbl_1_bss_42, 0.0f, -10.0f, -15.0f); Hu3DModelPosSetV(lbl_1_bss_42, &sp20); var_f31 = var_r31 / 20.0; HuSprGrpPosSet(lbl_1_bss_52, 288.0f, 80.0f); HuSprGrpPosSet(lbl_1_bss_50, 288.0f, 80.0f); HuSprGrpPosSet(lbl_1_bss_4C[0], 138.0f, 240.0f); HuSprGrpPosSet(lbl_1_bss_4C[1], 438.0f, 240.0f); WipeCreate(WIPE_MODE_IN, WIPE_TYPE_NORMAL, 20); while (WipeStatGet() != 0) { HuPrcVSleep(); } } loop_19: fn_1_11020(); fn_1_11264(MAKE_MESSID(0x33, 0x24), 0, 0); if (lbl_1_bss_5A == 0) { fn_1_11264(MAKE_MESSID(0x33, 0x25), 0, 1); } else { fn_1_11264(MAKE_MESSID(0x33, 0x2A), 0, 1); } fn_1_11708(MAKE_MESSID(0x33, 0x8D)); for (var_r31 = 0; var_r31 <= 0x0A; var_r31++) { var_f31 = var_r31 / 10.0; HuSprTPLvlSet(lbl_1_bss_4A, 0, var_f31); HuSprGrpPosSet(lbl_1_bss_4A, lbl_1_data_22[lbl_1_bss_5A * 2], lbl_1_data_22[(lbl_1_bss_5A * 2) + 1]); HuPrcVSleep(); } while (TRUE) { HuPrcVSleep(); if ((HuPadStkX[0] / 10) != 0) { var_r29 = lbl_1_bss_5A; if (HuPadStkX[0] < 0 && lbl_1_bss_5A > 0) { lbl_1_bss_5A--; } if (HuPadStkX[0] > 0 && lbl_1_bss_5A < 1) { lbl_1_bss_5A++; } if (lbl_1_bss_5A != var_r29) { HuAudFXPlay(0); for (var_r31 = 0; var_r31 <= 0xA; var_r31++) { var_f31 = sind((90.0 * (var_r31 / 10.0))); var_f30 = lbl_1_data_22[var_r29 * 2] + (var_f31 * (lbl_1_data_22[lbl_1_bss_5A * 2] - lbl_1_data_22[var_r29 * 2])); HuSprGrpPosSet(lbl_1_bss_4A, var_f30, lbl_1_data_22[(lbl_1_bss_5A * 2) + 1]); HuPrcVSleep(); } if (lbl_1_bss_5A == 0) { fn_1_11264(MAKE_MESSID(0x33, 0x25), 0, 1); } else { fn_1_11264(MAKE_MESSID(0x33, 0x2A), 0, 1); } } } if (HuPadBtnDown[0] & PAD_BUTTON_B) { HuAudFXPlay(3); fn_1_111E0(); fn_1_1190C(); lbl_1_bss_60 = 1; while (TRUE) { HuPrcVSleep(); } } if (HuPadBtnDown[0] & PAD_BUTTON_A) { if (lbl_1_bss_5A != 1 || lbl_1_bss_54 != 0) { break; } HuAudFXPlay(4); } } HuAudFXPlay(2); fn_1_111E0(); fn_1_1190C(); lbl_1_bss_5E = -1; var_r29 = lbl_1_bss_5A ^ 1; for (var_r31 = 0; var_r31 <= 0x14; var_r31++) { if (var_r31 <= 0xA) { var_f31 = var_r31 / 10.0; HuSprTPLvlSet(lbl_1_bss_4A, 0, 1.0 - var_f31); } var_f31 = 1.0 - (var_r31 / 20.0); HuSprGrpScaleSet(lbl_1_bss_4C[var_r29], var_f31, var_f31); if (lbl_1_bss_5A == 0) { var_f31 = -var_f31; } HuSprGrpPosSet(lbl_1_bss_4C[lbl_1_bss_5A], 288.0f + (150.0f * var_f31), 240.0f); HuPrcVSleep(); } for (var_r27 = 0;;) { if (lbl_1_bss_5A == 0) { var_r30 = fn_1_97D0(2, var_r27); } else { var_r30 = fn_1_97D0(3, var_r27); if (var_r30 != 0) { mgTypeCurr = 2; var_r30 = fn_1_524C(1); if (var_r30 == 0) { var_r27 = 1; continue; } } } if (var_r30 == 0) { for (var_r31 = 0; var_r31 <= 0x14; var_r31++) { var_f31 = var_r31 / 20.0; HuSprGrpScaleSet(lbl_1_bss_4C[var_r29], var_f31, var_f31); if (lbl_1_bss_5A != 0) { var_f31 = -var_f31; } HuSprGrpPosSet(lbl_1_bss_4C[lbl_1_bss_5A], 288.0f - (150.0f * var_f31), 240.0f); var_f31 = var_r31 / 20.0; if (lbl_1_bss_5A == 0) { var_r28 = -1; } else { var_r28 = 1; } HuSprGrpPosSet(lbl_1_bss_46, 288.0 + (var_r28 * (400.0 * (1.0 - cosd((90.0f * var_f31))))), 340.0f); HuPrcVSleep(); } goto loop_19; } var_r27 = 1; fn_1_1DA0(); for (var_r31 = 0; var_r31 <= 0x14; var_r31++) { var_f31 = var_r31 / 20.0; if (lbl_1_bss_5A == 0) { var_r28 = -1; } else { var_r28 = 1; } HuSprGrpPosSet(lbl_1_bss_46, 288.0 + (var_r28 * (400.0 * (1.0 - sind((90.0f * var_f31))))), 340.0f); HuPrcVSleep(); } if (lbl_1_bss_5A == 0) { fn_1_40E4(); } if (lbl_1_bss_4 == 0) { lbl_1_bss_4 = 1; HuPrcChildCreate(fn_1_7C00, 0x64, 0x2000, 0, lbl_1_bss_68); } fn_1_11020(); fn_1_11264(MAKE_MESSID(0x33, 0x2C), 0, 0); var_r30 = fn_1_11390(0); if (var_r30 != -1) { if (var_r30 != 1) { break; } } fn_1_111E0(); for (var_r31 = 0; var_r31 <= 0xA; var_r31++) { var_f31 = cosd((90.0 * (var_r31 / 10.0))); HuSprGrpScaleSet(lbl_1_bss_46, 1.0f, var_f31); HuPrcVSleep(); } HuSprGrpKill(lbl_1_bss_46); } fn_1_111E0(); fn_1_1190C(); WipeCreate(WIPE_MODE_OUT, WIPE_TYPE_NORMAL, 20); while (WipeStatGet() != 0) { HuPrcVSleep(); } mgBattleStarMax = 0; HuSprGrpKill(lbl_1_bss_48); HuSprGrpKill(lbl_1_bss_52); HuSprGrpKill(lbl_1_bss_50); HuSprGrpKill(lbl_1_bss_4C[0]); HuSprGrpKill(lbl_1_bss_4C[1]); HuSprGrpKill(lbl_1_bss_4A); HuSprGrpKill(lbl_1_bss_46); Hu3DModelKill(lbl_1_bss_42); HuPrcKill(lbl_1_bss_8); while (lbl_1_bss_4 != 0) { HuPrcVSleep(); } if (lbl_1_bss_5A == 0) { block_92: fn_1_2350(); } else { block_93: fn_1_4374(); } var_r26 = 1; goto block_7; } void fn_1_1774(void) { SeqWork work; s16 var_r31; s16 var_r30; char *var_r29; s16 var_r28; AnimData *var_r27; char *var_r26; AnimData *var_r25; AnimData *var_r24; AnimData *var_r23; var_r27 = HuSprAnimReadFile(DATA_MAKE_NUM(DATADIR_ZTAR, 3)); lbl_1_bss_48 = HuSprGrpCreate(1); var_r31 = HuSprCreate(var_r27, 0xC8, 0); HuSprGrpMemberSet(lbl_1_bss_48, 0, var_r31); HuSprGrpDrawNoSet(lbl_1_bss_48, 0x7F); HuSprGrpPosSet(lbl_1_bss_48, 288.0f, 240.0f); for (var_r30 = 0; var_r30 < 0x10; var_r30++) { work.sprite[var_r30] = work.spr_grp[var_r30] = -1; } var_r29 = MessData_MesPtrGet(messDataPtr, MAKE_MESSID(0x17, 0x21)); for (var_r26 = var_r29; *var_r29 != 0; var_r29++) { if (*var_r29 == 0xA) { *var_r29 = 0x10; } } lbl_1_bss_52 = work.spr_grp[fn_1_7754(&work, var_r26)]; HuSprGrpPosSet(lbl_1_bss_52, 288.0f, -300.0f); HuSprGrpDrawNoSet(lbl_1_bss_52, 0x7F); var_r27 = HuSprAnimReadFile(DATA_MAKE_NUM(DATADIR_ZTAR, 4)); lbl_1_bss_50 = HuSprGrpCreate(1); var_r31 = HuSprCreate(var_r27, 0x64, 0); HuSprGrpMemberSet(lbl_1_bss_50, 0, var_r31); HuSprGrpPosSet(lbl_1_bss_50, 288.0f, -300.0f); HuSprGrpDrawNoSet(lbl_1_bss_50, 0x7F); var_r27 = HuSprAnimReadFile(DATA_MAKE_NUM(DATADIR_ZTAR, 5)); var_r25 = HuSprAnimReadFile(DATA_MAKE_NUM(DATADIR_ZTAR, 14)); var_r24 = HuSprAnimReadFile(DATA_MAKE_NUM(DATADIR_ZTAR, 64)); var_r23 = HuSprAnimReadFile(DATA_MAKE_NUM(DATADIR_ZTAR, 15)); for (var_r30 = 0; var_r30 < 2; var_r30++) { var_r28 = HuSprGrpCreate(4); lbl_1_bss_4C[var_r30] = var_r28; var_r31 = HuSprCreate(var_r27, 0x64, var_r30); HuSprGrpMemberSet(var_r28, 0, var_r31); var_r31 = HuSprCreate(var_r25, 0x6E, 0); HuSprGrpMemberSet(var_r28, 1, var_r31); var_r31 = HuSprCreate(var_r24, 0x78, 0); HuSprGrpMemberSet(var_r28, 2, var_r31); HuSprScaleSet(var_r28, 2, 0.5f, 0.5f); var_r31 = HuSprCreate(var_r23, 0x82, 0); HuSprGrpMemberSet(var_r28, 3, var_r31); HuSprGrpPosSet(var_r28, 288.0f, -300.0f); HuSprGrpDrawNoSet(var_r28, 0x7F); } var_r27 = HuSprAnimReadFile(DATA_MAKE_NUM(DATADIR_ZTAR, 6)); lbl_1_bss_4A = HuSprGrpCreate(1); var_r31 = HuSprCreate(var_r27, 0x32, 0); HuSprGrpMemberSet(lbl_1_bss_4A, 0, var_r31); HuSprGrpPosSet(lbl_1_bss_4A, 288.0f, -300.0f); lbl_1_bss_42 = Hu3DModelCreateFile(DATA_MAKE_NUM(DATADIR_ZTAR, 0)); lbl_1_bss_3E[0] = Hu3DJointMotionFile(lbl_1_bss_42, DATA_MAKE_NUM(DATADIR_ZTAR, 1)); lbl_1_bss_3E[1] = Hu3DJointMotionFile(lbl_1_bss_42, DATA_MAKE_NUM(DATADIR_ZTAR, 2)); Hu3DMotionSet(lbl_1_bss_42, lbl_1_bss_3E[0]); Hu3DModelAttrSet(lbl_1_bss_42, HU3D_MOTATTR_LOOP); Hu3DModelPosSet(lbl_1_bss_42, 0.0f, 1000.0f, 0.0f); lbl_1_bss_8 = HuPrcChildCreate(fn_1_1CF0, 0x64, 0x2000, 0, lbl_1_bss_68); } void fn_1_1CF0(void) { float var_f31 = 0.0f; ModelData *var_r31 = &Hu3DData[lbl_1_bss_42]; while (TRUE) { var_r31->pos.y += sind(var_f31); var_f31 += 3.0f; if (var_f31 > 360.0f) { var_f31 -= 360.0f; } HuPrcVSleep(); } } void fn_1_1DA0(void) { s16 spC[4]; s16 sp8[2]; s16 var_r31; AnimData *var_r30; s16 var_r29; s16 var_r28; s16 var_r27; sp8[0] = 0; sp8[1] = 2; for (var_r31 = 0; var_r31 < 4; var_r31++) { spC[sp8[GWPlayerCfg[var_r31].group]++] = var_r31; } if (lbl_1_bss_5A == 0) { var_r28 = HuSprGrpCreate(5); lbl_1_bss_46 = var_r28; var_r30 = HuSprAnimReadFile(DATA_MAKE_NUM(DATADIR_ZTAR, 17)); var_r29 = HuSprCreate(var_r30, 0x78, 0); HuSprGrpMemberSet(var_r28, 0, var_r29); for (var_r31 = 0; var_r31 < 2; var_r31++) { var_r30 = HuSprAnimReadFile(GWPlayerCfg[spC[var_r31]].character + DATA_MAKE_NUM(DATADIR_ZTAR, 18)); var_r29 = HuSprCreate(var_r30, 0x6E, 0); HuSprGrpMemberSet(var_r28, (var_r31 * 2) + 1, var_r29); HuSprPosSet(var_r28, (var_r31 * 2) + 1, (var_r31 * 0x30) - 0x18, -4.0f); if (GWPlayerCfg[spC[var_r31]].iscom == 0) { var_r30 = HuSprAnimReadFile(DATA_MAKE_NUM(DATADIR_ZTAR, 32)); var_r29 = HuSprCreate(var_r30, 0x64, spC[var_r31]); } else { var_r30 = HuSprAnimReadFile(DATA_MAKE_NUM(DATADIR_ZTAR, 33)); var_r29 = HuSprCreate(var_r30, 0x64, GWPlayerCfg[spC[var_r31]].diff); } HuSprGrpMemberSet(var_r28, (var_r31 * 2) + 2, var_r29); HuSprPosSet(var_r28, (var_r31 * 2) + 2, (var_r31 * 0x30) - 0x18, 20.0f); } } else { var_r28 = HuSprGrpCreate(0xA); lbl_1_bss_46 = var_r28; var_r30 = HuSprAnimReadFile(DATA_MAKE_NUM(DATADIR_ZTAR, 16)); var_r29 = HuSprCreate(var_r30, 0x78, 0); HuSprGrpMemberSet(var_r28, 0, var_r29); var_r27 = -0x4B; for (var_r31 = 0; var_r31 < 4; var_r31++) { var_r30 = HuSprAnimReadFile(GWPlayerCfg[spC[var_r31]].character + DATA_MAKE_NUM(DATADIR_ZTAR, 18)); var_r29 = HuSprCreate(var_r30, 0x6E, 0); HuSprGrpMemberSet(var_r28, (var_r31 * 2) + 1, var_r29); HuSprPosSet(var_r28, (var_r31 * 2) + 1, var_r27, 0.0f); if (GWPlayerCfg[spC[var_r31]].iscom == 0) { var_r30 = HuSprAnimReadFile(DATA_MAKE_NUM(DATADIR_ZTAR, 32)); var_r29 = HuSprCreate(var_r30, 0x64, spC[var_r31]); } else { var_r30 = HuSprAnimReadFile(DATA_MAKE_NUM(DATADIR_ZTAR, 33)); var_r29 = HuSprCreate(var_r30, 0x64, GWPlayerCfg[spC[var_r31]].diff); } HuSprGrpMemberSet(var_r28, (var_r31 * 2) + 2, var_r29); HuSprPosSet(var_r28, (var_r31 * 2) + 2, var_r27, 22.0f); var_r27 += 0x2A; if (var_r31 == 1) { var_r27 += 0x18; } } var_r30 = HuSprAnimReadFile(DATA_MAKE_NUM(DATADIR_ZTAR, 10)); var_r29 = HuSprCreate(var_r30, 0x5A, 0); HuSprGrpMemberSet(var_r28, 9, var_r29); } HuSprGrpPosSet(var_r28, 0.0f, -100.0f); } void fn_1_2350(void) { s16 spC[4]; s16 sp8[2]; float var_f31; s16 var_r31; sp8[0] = 0; sp8[1] = 2; for (var_r31 = 0; var_r31 < 4; var_r31++) { spC[sp8[GWPlayerCfg[var_r31].group]++] = var_r31; } if (lbl_1_bss_58 != 0) { if (GWPlayerCoinWinGet(spC[0]) > 0) { mgBattleStarMax++; } } fn_1_33B0(); Hu3DModelPosSet(lbl_1_bss_36[2], 500.0f, 0.0f, 0.0f); Hu3DModelPosSet(lbl_1_bss_36[3], 500.0f, 0.0f, 0.0f); HuSprScaleSet(lbl_1_bss_50, 2, 0.0f, 0.0f); if (lbl_1_bss_58 != 0) { if (GWPlayerCoinWinGet(spC[0]) == 0) { mgBattleStarMax++; } HuSprBankSet(lbl_1_bss_50, 1, mgBattleStarMax); HuSprScaleSet(lbl_1_bss_50, 1, 1.0f, 1.0f); WipeCreate(WIPE_MODE_IN, WIPE_TYPE_NORMAL, 20); while (WipeStatGet() != 0) { HuPrcVSleep(); } HuPrcSleep(0x1E); if (GWPlayerCoinWinGet(spC[0]) > 0) { HuSprAttrReset(lbl_1_bss_44, 6, 4); HuSprPosSet(lbl_1_bss_44, 6, ((mgBattleStarMax - 1) << 5) + 0x46, 340.0f); for (var_r31 = 0; var_r31 <= 0x3C; var_r31++) { var_f31 = var_r31 / 60.0; HuSprTPLvlSet(lbl_1_bss_44, 6, var_f31); var_f31 = 1.0 + (5.0 * cosd((90.0f * var_f31))); HuSprScaleSet(lbl_1_bss_44, 6, var_f31, var_f31); if (var_r31 == 0x14) { HuAudFXPlay(0x9A); if (mgBattleStarMax < 6) { Hu3DMotionShiftSet(lbl_1_bss_36[0], lbl_1_bss_E[0][2], 0.0f, 10.0f, HU3D_MOTATTR_NONE); Hu3DMotionShiftSet(lbl_1_bss_36[1], lbl_1_bss_E[1][2], 0.0f, 10.0f, HU3D_MOTATTR_NONE); } else { Hu3DMotionShiftSet(lbl_1_bss_36[0], lbl_1_bss_E[0][3], 0.0f, 10.0f, HU3D_MOTATTR_NONE); Hu3DMotionShiftSet(lbl_1_bss_36[1], lbl_1_bss_E[1][3], 0.0f, 10.0f, HU3D_MOTATTR_NONE); } } HuPrcVSleep(); } HuAudFXPlay(8); if (mgBattleStarMax >= 6) { HuPrcSleep(0x3C); var_r31 = omMgIndexGet(0x29); lbl_1_bss_54 = 1; fn_1_11020(); fn_1_11338(GWPlayerCfg[spC[0]].character, 0); fn_1_11338(GWPlayerCfg[spC[1]].character, 1); fn_1_11264(MAKE_MESSID(0x33, 0xA0), 0, 0); if (GWMGAvailGet(var_r31 + 0x191) == 0) { GWMGAvailSet(var_r31 + 0x191); GWGameStat.present[0x37] = 1; fn_1_11264(MAKE_MESSID(0x33, 0x29), 0, 0); } fn_1_111E0(); WipeCreate(WIPE_MODE_OUT, WIPE_TYPE_NORMAL, 30); while (WipeStatGet() != 0) { HuPrcVSleep(); } } else { Hu3DMotionShiftSet(lbl_1_bss_36[0], lbl_1_bss_E[0][0], 0.0f, 10.0f, HU3D_MOTATTR_LOOP); Hu3DMotionShiftSet(lbl_1_bss_36[1], lbl_1_bss_E[1][0], 0.0f, 10.0f, HU3D_MOTATTR_LOOP); for (var_r31 = 0; var_r31 <= 0xA; var_r31++) { var_f31 = 1.0 - (var_r31 / 10.0); HuSprScaleSet(lbl_1_bss_50, 1, var_f31, var_f31); HuPrcVSleep(); } HuPrcSleep(0x3C); goto block_39; } } else { Hu3DMotionShiftSet(lbl_1_bss_36[0], lbl_1_bss_E[0][4], 0.0f, 10.0f, HU3D_MOTATTR_NONE); Hu3DMotionShiftSet(lbl_1_bss_36[1], lbl_1_bss_E[1][4], 0.0f, 10.0f, HU3D_MOTATTR_NONE); HuPrcSleep(0xB4); WipeColorSet(0, 0, 0); WipeCreate(WIPE_MODE_OUT, WIPE_TYPE_NORMAL, 30); while (WipeStatGet() != 0) { HuPrcVSleep(); } } } else { WipeCreate(WIPE_MODE_IN, WIPE_TYPE_NORMAL, 20); while (WipeStatGet() != 0) { HuPrcVSleep(); } HuPrcSleep(0x1E); block_39: Hu3DMotionSet(lbl_1_bss_36[2], lbl_1_bss_E[2][1]); Hu3DMotionSet(lbl_1_bss_36[3], lbl_1_bss_E[3][1]); Hu3DModelRotSet(lbl_1_bss_36[2], 0.0f, -90.0f, 0.0f); Hu3DModelRotSet(lbl_1_bss_36[3], 0.0f, -90.0f, 0.0f); HuSprBankSet(lbl_1_bss_50, 1, mgBattleStarMax + 1); for (var_r31 = 0; var_r31 <= 0x1E; var_r31++) { var_f31 = 1.0 - sind((90.0 * (var_r31 / 30.0))); Hu3DModelPosSet(lbl_1_bss_36[2], 125.0f + (400.0f * var_f31), 0.0f, 0.0f); Hu3DModelPosSet(lbl_1_bss_36[3], 275.0f + (400.0f * var_f31), 0.0f, 0.0f); if (var_r31 == 0x19) { Hu3DMotionShiftSet(lbl_1_bss_36[2], lbl_1_bss_E[2][0], 0.0f, 10.0f, HU3D_MOTATTR_LOOP); Hu3DMotionShiftSet(lbl_1_bss_36[3], lbl_1_bss_E[3][0], 0.0f, 10.0f, HU3D_MOTATTR_LOOP); } if ((GWPlayerCfg[2].character < 8) && ((var_r31 % 5) == 0)) { HuAudFXPlay(GWPlayerCfg[2].character + 0xD5); } if ((GWPlayerCfg[3].character < 8) && (((var_r31 + 3) % 5) == 0)) { HuAudFXPlay(GWPlayerCfg[3].character + 0xD5); } if (var_r31 > 0x14) { var_f31 = 1.0 - ((var_r31 - 0x14) / 10.0); Hu3DModelRotSet(lbl_1_bss_36[2], 0.0f, 90.0f * -var_f31, 0.0f); Hu3DModelRotSet(lbl_1_bss_36[3], 0.0f, 90.0f * -var_f31, 0.0f); } if (var_r31 <= 0x14) { var_f31 = 1.2 * sind((90.0 * (var_r31 / 20.0))); HuSprScaleSet(lbl_1_bss_50, 1, var_f31, var_f31); } else if (var_r31 > 0x14) { var_f31 = 1.0 + (0.2 * cosd((90.0 * ((var_r31 - 0x14) / 10.0)))); HuSprScaleSet(lbl_1_bss_50, 1, var_f31, var_f31); } HuPrcVSleep(); } HuAudFXPlay(0x355); for (var_r31 = 0; var_r31 <= 0x14; var_r31++) { var_f31 = 1.0 + (5.0 * cosd((90.0 * (var_r31 / 20.0)))); HuSprScaleSet(lbl_1_bss_50, 2, var_f31, var_f31); HuSprTPLvlSet(lbl_1_bss_50, 2, var_r31 / 20.0); HuPrcVSleep(); } fn_1_114EC(MAKE_MESSID(0x33, 0x4F), 1); while (TRUE) { if ((*HuPadBtnDown & 0x100) != 0) { HuAudFXPlay(2); if (mgBattleStarMax >= 5) { GWSystem.mg_type = 0; } fn_1_51BC(1); } if ((*HuPadBtnDown & 0x200) != 0) { break; } HuPrcVSleep(); } HuAudFXPlay(3); fn_1_1190C(); WipeColorSet(0, 0, 0); WipeCreate(WIPE_MODE_OUT, WIPE_TYPE_NORMAL, 20); while (WipeStatGet() != 0) { HuPrcVSleep(); } } HuSprGrpKill(lbl_1_bss_48); HuSprGrpKill(lbl_1_bss_50); HuSprGrpKill(lbl_1_bss_44); Hu3DModelKill(lbl_1_bss_42); HuPrcKill(lbl_1_bss_8); Hu3DModelKill(lbl_1_bss_C); CharModelKill(-1); for (var_r31 = 0; var_r31 < 4; var_r31++) { if (GWPlayerCfg[spC[var_r31]].character >= 8) { Hu3DModelKill(lbl_1_bss_36[var_r31]); Hu3DMotionKill(lbl_1_bss_E[var_r31][0]); Hu3DMotionKill(lbl_1_bss_E[var_r31][1]); } } lbl_1_bss_58 = 0; lbl_1_bss_5A = 0; } s32 lbl_1_data_2C[6] = { DATA_MAKE_NUM(DATADIR_ZTAR, 59), DATA_MAKE_NUM(DATADIR_ZTAR, 34), DATA_MAKE_NUM(DATADIR_ZTAR, 39), DATA_MAKE_NUM(DATADIR_ZTAR, 44), DATA_MAKE_NUM(DATADIR_ZTAR, 49), DATA_MAKE_NUM(DATADIR_ZTAR, 54), }; u8 lbl_1_data_44[6] = { 0, 1, 1, 2, 2, 3 }; void fn_1_33B0(void) { Vec sp38; Vec sp2C; Vec sp20; Vec sp14; s16 spC[4]; s16 sp8[2]; s16 var_r31; s16 var_r30; AnimData *var_r29; s16 var_r28; s16 var_r27; s16 var_r26; s16 var_r25; s16 var_r24; AnimData *var_r23; sp8[0] = 0; sp8[1] = 2; for (var_r31 = 0; var_r31 < 4; var_r31++) { spC[sp8[GWPlayerCfg[var_r31].group]++] = var_r31; } var_r29 = HuSprAnimReadFile(DATA_MAKE_NUM(DATADIR_ZTAR, 3)); lbl_1_bss_48 = HuSprGrpCreate(1); var_r30 = HuSprCreate(var_r29, 0xC8, 0); HuSprGrpMemberSet(lbl_1_bss_48, 0, var_r30); HuSprGrpDrawNoSet(lbl_1_bss_48, 0x7F); HuSprGrpPosSet(lbl_1_bss_48, 288.0f, 240.0f); lbl_1_bss_50 = HuSprGrpCreate(3); var_r29 = HuSprAnimReadFile(DATA_MAKE_NUM(DATADIR_ZTAR, 12)); var_r30 = HuSprCreate(var_r29, 0x78, 0); HuSprGrpMemberSet(lbl_1_bss_50, 0, var_r30); HuSprPosSet(lbl_1_bss_50, 0, 288.0f, 80.0f); var_r29 = HuSprAnimReadFile(DATA_MAKE_NUM(DATADIR_ZTAR, 11)); if ((mgBattleStarMax + 1) >= 7) { var_r30 = HuSprCreate(var_r29, 0x64, 6); } else { var_r30 = HuSprCreate(var_r29, 0x64, mgBattleStarMax + 1); } HuSprGrpMemberSet(lbl_1_bss_50, 1, var_r30); HuSprPosSet(lbl_1_bss_50, 1, VERSION_JP ? 234.0f : 342.0f, 80.0f); HuSprScaleSet(lbl_1_bss_50, 1, 0.0f, 0.0f); HuSprGrpDrawNoSet(lbl_1_bss_50, 0x7F); var_r29 = HuSprAnimReadFile(DATA_MAKE_NUM(DATADIR_ZTAR, 9)); var_r30 = HuSprCreate(var_r29, 0x64, 0); HuSprGrpMemberSet(lbl_1_bss_50, 2, var_r30); HuSprPosSet(lbl_1_bss_50, 2, 288.0f, 240.0f); HuSprDrawNoSet(lbl_1_bss_50, 2, 0); HuSprGrpPosSet(lbl_1_bss_50, 0.0f, 0.0f); var_r27 = HuSprGrpCreate(7); lbl_1_bss_44 = var_r27; var_r29 = HuSprAnimReadFile(DATA_MAKE_NUM(DATADIR_ZTAR, 8)); var_r23 = HuSprAnimReadFile(DATA_MAKE_NUM(DATADIR_ZTAR, 7)); var_r24 = mgBattleStarMax; if (GWPlayerCoinWinGet(spC[0]) > 0) { var_r24--; } for (var_r31 = 0; var_r31 < 6; var_r31++) { if (var_r31 >= var_r24) { var_r30 = HuSprCreate(var_r23, 0x64, 0); } else { var_r30 = HuSprCreate(var_r29, 0x64, 0); } HuSprGrpMemberSet(var_r27, var_r31, var_r30); HuSprPosSet(var_r27, var_r31, (var_r31 << 5) + 0x46, 340.0f); } var_r30 = HuSprCreate(var_r29, 0x5A, 0); HuSprGrpMemberSet(var_r27, 6, var_r30); HuSprAttrSet(var_r27, 6, 4); HuSprGrpPosSet(var_r27, 0.0f, 0.0f); sp38.x = 510.0f; sp38.y = 80.0f; sp38.z = 1500.0f; Hu3D2Dto3D(&sp38, 1, &sp2C); lbl_1_bss_42 = Hu3DModelCreateFile(DATA_MAKE_NUM(DATADIR_ZTAR, 0)); lbl_1_bss_3E[0] = Hu3DJointMotionFile(lbl_1_bss_42, DATA_MAKE_NUM(DATADIR_ZTAR, 1)); lbl_1_bss_3E[1] = Hu3DJointMotionFile(lbl_1_bss_42, DATA_MAKE_NUM(DATADIR_ZTAR, 2)); Hu3DModelAttrSet(lbl_1_bss_42, HU3D_MOTATTR_LOOP); Hu3DModelPosSetV(lbl_1_bss_42, &sp2C); Hu3DModelRotSet(lbl_1_bss_42, 0.0f, -10.0f, -15.0f); Hu3DMotionSet(lbl_1_bss_42, lbl_1_bss_3E[0]); lbl_1_bss_8 = HuPrcChildCreate(fn_1_1CF0, 0x64, 0x2000, 0, lbl_1_bss_68); GWPlayerCfg[spC[2]].character = mgIndexList[mgBattleStarMax * 2]; GWPlayerCfg[spC[3]].character = mgIndexList[mgBattleStarMax * 2 + 1]; GWPlayerCfg[spC[0]].group = GWPlayerCfg[spC[1]].group = 0; GWPlayerCfg[spC[2]].group = GWPlayerCfg[spC[3]].group = 1; GWPlayerCfg[spC[2]].iscom = GWPlayerCfg[spC[3]].iscom = 1; GWPlayerCfg[spC[2]].diff = GWPlayerCfg[spC[3]].diff = lbl_1_data_44[mgBattleStarMax]; var_r26 = -0x113; if (lbl_1_bss_58 != 0) { CharKill(-1); for (var_r31 = 0; var_r31 < 4; var_r31++) { if (GWPlayerCfg[spC[var_r31]].character < 8) { CharARAMOpen(GWPlayerCfg[spC[var_r31]].character); } } } for (var_r31 = 0; var_r31 < 4; var_r31++) { var_r28 = GWPlayerCfg[spC[var_r31]].character; if (var_r28 != 0xFF) { if (var_r28 < 8) { lbl_1_bss_36[var_r31] = CharModelCreate(var_r28, 2); lbl_1_bss_E[var_r31][0] = CharModelMotionCreate(var_r28, DATA_MAKE_NUM(DATADIR_MARIOMOT, 0x00)); lbl_1_bss_E[var_r31][1] = CharModelMotionCreate(var_r28, DATA_MAKE_NUM(DATADIR_MARIOMOT, 0x03)); if (var_r31 < 2) { lbl_1_bss_E[var_r31][2] = CharModelMotionCreate(var_r28, DATA_MAKE_NUM(DATADIR_MARIOMOT, 0x48)); lbl_1_bss_E[var_r31][3] = CharModelMotionCreate(var_r28, DATA_MAKE_NUM(DATADIR_MARIOMOT, 0x17)); lbl_1_bss_E[var_r31][4] = CharModelMotionCreate(var_r28, DATA_MAKE_NUM(DATADIR_MARIOMOT, 0x18)); } CharModelVoiceEnableSet(GWPlayerCfg[spC[var_r31]].character, lbl_1_bss_E[var_r31][1], 0); Hu3DModelScaleSet(lbl_1_bss_36[var_r31], 0.8f, 0.8f, 0.8f); } else { var_r25 = var_r28 - 8; lbl_1_bss_36[var_r31] = Hu3DModelCreateFile(lbl_1_data_2C[var_r25]); lbl_1_bss_E[var_r31][0] = Hu3DJointMotionFile(lbl_1_bss_36[var_r31], lbl_1_data_2C[var_r25] + 1); lbl_1_bss_E[var_r31][1] = Hu3DJointMotionFile(lbl_1_bss_36[var_r31], lbl_1_data_2C[var_r25] + 2); Hu3DModelScaleSet(lbl_1_bss_36[var_r31], 0.8f, 0.8f, 0.8f); } Hu3DMotionSet(lbl_1_bss_36[var_r31], lbl_1_bss_E[var_r31][0]); Hu3DModelAttrSet(lbl_1_bss_36[var_r31], HU3D_MOTATTR_LOOP); Hu3DModelPosSet(lbl_1_bss_36[var_r31], var_r26, 0.0f, 0.0f); Hu3DModelShadowSet(lbl_1_bss_36[var_r31]); var_r26 += 0x96; if (var_r31 == 1) { var_r26 += 0x64; } } } CharModelDataClose(-1); Hu3DShadowCreate(20.0f, 500.0f, 8000.0f); Hu3DShadowTPLvlSet(0.5f); Hu3DShadowSizeSet(0xC0); sp20.x = sp20.y = sp20.z = 0.0f; sp38.x = sp38.z = 100.0f; sp38.y = 2000.0f; sp14.x = sp14.y = 0.0f; sp14.z = 1.0f; Hu3DShadowPosSet(&sp38, &sp14, &sp20); lbl_1_bss_C = Hu3DHookFuncCreate(fn_1_7414); Hu3DModelLayerSet(lbl_1_bss_C, 1); } void fn_1_40E4(void) { s16 sp14[4]; s16 spC[4]; s16 sp8[2]; s16 var_r31; s16 var_r30; s16 var_r29; s16 var_r28; sp8[0] = 0; sp8[1] = 2; for (var_r31 = 0; var_r31 < 4; var_r31++) { spC[sp8[GWPlayerCfg[var_r31].group]++] = var_r31; } var_r30 = 0; for (var_r31 = var_r30; var_r31 < 8; var_r31++) { if ((var_r31 != GWPlayerCfg[spC[0]].character) && (var_r31 != GWPlayerCfg[spC[1]].character)) { sp14[var_r30++] = var_r31; } } for (var_r31 = 0; var_r31 < 0x1E; var_r31++) { var_r30 = frandmod(6); var_r29 = frandmod(6); var_r28 = sp14[var_r30]; sp14[var_r30] = sp14[var_r29]; sp14[var_r29] = var_r28; } for (var_r31 = 0; var_r31 < 6; var_r31++) { mgIndexList[var_r31] = sp14[var_r31]; } mgIndexList[6] = 0xC; mgIndexList[7] = 9; mgIndexList[8] = 0xB; mgIndexList[9] = 0xA; mgIndexList[0xA] = 8; mgIndexList[0xB] = 0xD; mgIndexList[0xC] = mgIndexList[0xD] = 0xFF; GWPlayerCfg[spC[2]].character = mgIndexList[0]; GWPlayerCfg[spC[3]].character = mgIndexList[1]; } s16 lbl_1_data_4A[6] = { 0x3A, 0x36, 0x40, 0x4B, 0x46, 0x3E }; s16 lbl_1_data_56[7] = { 0x3B, 0x38, 0x42, 0x4D, 0x48, 0x3F, 0 }; void fn_1_4374(void) { s16 spC[4]; s16 sp8[2]; float var_f31; s16 var_r31; s16 var_r30; sp8[0] = 0; sp8[1] = 2; for (var_r31 = 0; var_r31 < 4; var_r31++) { spC[sp8[GWPlayerCfg[var_r31].group]++] = var_r31; } fn_1_4948(); WipeCreate(WIPE_MODE_IN, WIPE_TYPE_NORMAL, 20); while (WipeStatGet() != 0) { HuPrcVSleep(); } HuPrcSleep(0x1E); if (lbl_1_bss_58 != 0) { var_r30 = 0; for (var_r31 = var_r30; var_r31 < 4; var_r31++) { if (GWPlayerCoinWinGet(spC[var_r31]) > 0) { if (var_r30 == 0) { HuAudFXPlay(0x9A); } if (GWPlayerCfg[spC[var_r31]].character >= 8) { HuAudFXPlay(lbl_1_data_4A[GWPlayerCfg[spC[var_r31]].character - 8]); } Hu3DMotionShiftSet(lbl_1_bss_36[var_r31], lbl_1_bss_E[var_r31][3], 0.0f, 10.0f, HU3D_MOTATTR_NONE); var_r30++; } else { if (GWPlayerCfg[spC[var_r31]].character >= 8) { HuAudFXPlay(lbl_1_data_56[GWPlayerCfg[spC[var_r31]].character - 8]); } Hu3DMotionShiftSet(lbl_1_bss_36[var_r31], lbl_1_bss_E[var_r31][4], 0.0f, 10.0f, HU3D_MOTATTR_NONE); } } HuSprAttrReset(lbl_1_bss_50, 1, 4); HuPrcSleep(0x78); } else { HuAudFXPlay(0x355); HuSprAttrReset(lbl_1_bss_50, 1, 4); for (var_r31 = 0; var_r31 <= 0x14; var_r31++) { var_f31 = 1.0 + (5.0 * cosd((90.0 * (var_r31 / 20.0)))); HuSprScaleSet(lbl_1_bss_50, 1, var_f31, var_f31); HuSprTPLvlSet(lbl_1_bss_50, 1, var_r31 / 20.0); HuPrcVSleep(); } } fn_1_114EC(MAKE_MESSID(0x33, 0x4F), 1); while (TRUE) { if (HuPadBtnDown[0] & PAD_BUTTON_A) { HuAudFXPlay(2); fn_1_51BC(2); } if (HuPadBtnDown[0] & PAD_BUTTON_B) { break; } HuPrcVSleep(); } HuAudFXPlay(3); fn_1_1190C(); WipeColorSet(0, 0, 0); WipeCreate(WIPE_MODE_OUT, WIPE_TYPE_NORMAL, 20); while (WipeStatGet() != 0) { HuPrcVSleep(); } HuSprGrpKill(lbl_1_bss_48); HuSprGrpKill(lbl_1_bss_50); Hu3DModelKill(lbl_1_bss_42); HuPrcKill(lbl_1_bss_8); Hu3DModelKill(lbl_1_bss_C); CharModelKill(-1); for (var_r31 = 0; var_r31 < 4; var_r31++) { if (GWPlayerCfg[spC[var_r31]].character >= 8) { Hu3DModelKill(lbl_1_bss_36[var_r31]); Hu3DMotionKill(lbl_1_bss_E[var_r31][0]); Hu3DMotionKill(lbl_1_bss_E[var_r31][1]); } } lbl_1_bss_58 = 0; lbl_1_bss_5A = 0; } void fn_1_4948(void) { Vec sp38; Vec sp2C; Vec sp20; Vec sp14; s16 spC[4]; s16 sp8[2]; s16 var_r31; s16 var_r30; s16 var_r29; s16 var_r28; AnimData *var_r27; s16 var_r26; s16 var_r25; sp8[0] = 0; sp8[1] = 2; for (var_r31 = 0; var_r31 < 4; var_r31++) { spC[sp8[GWPlayerCfg[var_r31].group]++] = var_r31; } var_r27 = HuSprAnimReadFile(DATA_MAKE_NUM(DATADIR_ZTAR, 3)); lbl_1_bss_48 = HuSprGrpCreate(1); var_r29 = HuSprCreate(var_r27, 0xC8, 0); HuSprGrpMemberSet(lbl_1_bss_48, 0, var_r29); HuSprGrpDrawNoSet(lbl_1_bss_48, 0x7F); HuSprGrpPosSet(lbl_1_bss_48, 288.0f, 240.0f); lbl_1_bss_50 = HuSprGrpCreate(2); var_r27 = HuSprAnimReadFile(DATA_MAKE_NUM(DATADIR_ZTAR, 13)); var_r29 = HuSprCreate(var_r27, 0x78, 0); HuSprGrpMemberSet(lbl_1_bss_50, 0, var_r29); HuSprPosSet(lbl_1_bss_50, 0, 288.0f, 80.0f); HuSprGrpPosSet(lbl_1_bss_50, 0.0f, 0.0f); HuSprGrpDrawNoSet(lbl_1_bss_50, 0x7F); var_r27 = HuSprAnimReadFile(DATA_MAKE_NUM(DATADIR_ZTAR, 9)); var_r29 = HuSprCreate(var_r27, 0x64, 0); HuSprGrpMemberSet(lbl_1_bss_50, 1, var_r29); HuSprPosSet(lbl_1_bss_50, 1, 288.0f, 240.0f); HuSprAttrSet(lbl_1_bss_50, 1, 4); HuSprDrawNoSet(lbl_1_bss_50, 1, 0); sp38.x = 510.0f; sp38.y = 80.0f; sp38.z = 1500.0f; Hu3D2Dto3D(&sp38, 1, &sp2C); lbl_1_bss_42 = Hu3DModelCreateFile(DATA_MAKE_NUM(DATADIR_ZTAR, 0)); lbl_1_bss_3E[0] = Hu3DJointMotionFile(lbl_1_bss_42, DATA_MAKE_NUM(DATADIR_ZTAR, 1)); lbl_1_bss_3E[1] = Hu3DJointMotionFile(lbl_1_bss_42, DATA_MAKE_NUM(DATADIR_ZTAR, 2)); Hu3DModelAttrSet(lbl_1_bss_42, HU3D_MOTATTR_LOOP); Hu3DModelPosSetV(lbl_1_bss_42, &sp2C); Hu3DModelRotSet(lbl_1_bss_42, 0.0f, -10.0f, -15.0f); Hu3DMotionSet(lbl_1_bss_42, lbl_1_bss_3E[0]); lbl_1_bss_8 = HuPrcChildCreate(fn_1_1CF0, 0x64, 0x2000, 0, lbl_1_bss_68); var_r28 = -0x113; for (var_r31 = 0; var_r31 < 4; var_r31++) { var_r30 = GWPlayerCfg[spC[var_r31]].character; if (var_r30 < 8) { lbl_1_bss_36[var_r31] = CharModelCreate(var_r30, 2); lbl_1_bss_E[var_r31][0] = CharModelMotionCreate(var_r30, DATA_MAKE_NUM(DATADIR_MARIOMOT, 0x00)); lbl_1_bss_E[var_r31][3] = CharModelMotionCreate(var_r30, DATA_MAKE_NUM(DATADIR_MARIOMOT, 0x17)); lbl_1_bss_E[var_r31][4] = CharModelMotionCreate(var_r30, DATA_MAKE_NUM(DATADIR_MARIOMOT, 0x18)); Hu3DModelScaleSet(lbl_1_bss_36[var_r31], 0.8f, 0.8f, 0.8f); } else { var_r26 = var_r30 - 8; var_r25 = Hu3DModelCreateFile(lbl_1_data_2C[var_r26]); lbl_1_bss_36[var_r31] = var_r25; lbl_1_bss_E[var_r31][0] = Hu3DJointMotionFile(var_r25, lbl_1_data_2C[var_r26] + 1); lbl_1_bss_E[var_r31][3] = Hu3DJointMotionFile(var_r25, lbl_1_data_2C[var_r26] + 3); lbl_1_bss_E[var_r31][4] = Hu3DJointMotionFile(var_r25, lbl_1_data_2C[var_r26] + 4); Hu3DModelScaleSet(lbl_1_bss_36[var_r31], 0.8f, 0.8f, 0.8f); } Hu3DMotionSet(lbl_1_bss_36[var_r31], lbl_1_bss_E[var_r31][0]); Hu3DModelAttrSet(lbl_1_bss_36[var_r31], HU3D_MOTATTR_LOOP); Hu3DModelPosSet(lbl_1_bss_36[var_r31], var_r28, 0.0f, 0.0f); Hu3DModelShadowSet(lbl_1_bss_36[var_r31]); var_r28 += 0x96; if (var_r31 == 1) { var_r28 += 0x64; } } CharModelDataClose(-1); Hu3DShadowCreate(20.0f, 500.0f, 8000.0f); Hu3DShadowTPLvlSet(0.5f); Hu3DShadowSizeSet(0xC0); sp20.x = sp20.y = sp20.z = 0.0f; sp38.x = sp38.z = 100.0f; sp38.y = 2000.0f; sp14.x = sp14.y = 0.0f; sp14.z = 1.0f; Hu3DShadowPosSet(&sp38, &sp14, &sp20); lbl_1_bss_C = Hu3DHookFuncCreate(fn_1_7414); Hu3DModelLayerSet(lbl_1_bss_C, 1); } void fn_1_51BC(s16 arg0) { s16 var_r31; omOvlHisData *var_r30; u32 var_r29; WipeColorSet(0xFF, 0xFF, 0xFF); WipeCreate(WIPE_MODE_OUT, WIPE_TYPE_NORMAL, 0x3C); HuAudSeqAllFadeOut(0x3E8); while (WipeStatGet() != 0) { HuPrcVSleep(); } #if !VERSION_ENG if ((GWPlayerCfg->character >= 8) && (GWPlayerCfg->character >= 8) && (GWPlayerCfg->character >= 8) && (GWPlayerCfg->character >= 8)) { msmMusStopAll(1, 0); msmSeStopAll(1, 0); var_r29 = OSGetTick(); while (TRUE) { if ((msmMusGetNumPlay(1) != 0) || (msmSeGetNumPlay(1) != 0)) { if (((OSGetTick() - var_r29) / (*((u32 *)0x800000F8) / 4 / 1000)) >= 0x1F4) { break; } } else { break; } } msmSysDelGroupBase(0); #if VERSION_PAL for (var_r31 = 0; var_r31 < 8; var_r31++) { charVoiceGroupStat[var_r31] = 0; } #endif } #endif var_r30 = omOvlHisGet(0); omOvlHisChg(0, OVL_ZTAR, arg0, var_r30->stat); omOvlCallEx(OVL_M433, 1, 0, 0); while (TRUE) { HuPrcVSleep(); } } float lbl_1_data_64[8] = { -132.0f, -12.0f, 60.0f, 132.0f, -132.0f, -60.0f, 60.0f, 132.0f, }; u8 lbl_1_data_84[16] = { 0, 1, 2, 3, 1, 0, 2, 3, 2, 0, 1, 3, 3, 0, 1, 2 }; u8 lbl_1_data_94[12] = { 0, 1, 2, 3, 0, 2, 1, 3, 0, 3, 1, 2 }; s32 fn_1_524C(s32 arg0) { s16 spC; float var_f31; float var_f30; float var_f29; s16 var_r31; s16 var_r30; float *var_r29; s16 var_r28; s16 var_r27; AnimData *var_r26; s16 var_r25; s16 var_r24; s16 var_r23; WindowData *var_r22; if (mgTypeCurr == 1) { var_r29 = lbl_1_data_64; var_f29 = 216.0f; } else { var_r29 = &lbl_1_data_64[4]; var_f29 = 288.0f; } var_r28 = HuSprGrpCreate(0x10); for (var_r31 = 0; var_r31 < 4; var_r31++) { var_r26 = HuSprAnimReadFile(GWPlayerCfg[var_r31].character + DATA_MAKE_NUM(DATADIR_ZTAR, 69)); var_r25 = HuSprCreate(var_r26, 4, 0); HuSprGrpMemberSet(var_r28, var_r31 * 4, var_r25); HuSprPosSet(var_r28, var_r31 * 4, var_r29[var_r31], 0.0f); if (mgTypeCurr == 1) { if (var_r31 == 0) { var_r26 = HuSprAnimReadFile(DATA_MAKE_NUM(DATADIR_ZTAR, 89)); } else { var_r26 = HuSprAnimReadFile(DATA_MAKE_NUM(DATADIR_ZTAR, 90)); } } else if (var_r31 < 2) { var_r26 = HuSprAnimReadFile(DATA_MAKE_NUM(DATADIR_ZTAR, 89)); } else { var_r26 = HuSprAnimReadFile(DATA_MAKE_NUM(DATADIR_ZTAR, 90)); } var_r25 = HuSprCreate(var_r26, 3, 0); HuSprGrpMemberSet(var_r28, (var_r31 * 4) + 1, var_r25); HuSprPosSet(var_r28, (var_r31 * 4) + 1, var_r29[var_r31], 0.0f); if (GWPlayerCfg[var_r31].iscom != 0) { var_r26 = HuSprAnimReadFile(DATA_MAKE_NUM(DATADIR_ZTAR, 87)); } else { var_r26 = HuSprAnimReadFile(GWPlayerCfg[var_r31].pad_idx + DATA_MAKE_NUM(DATADIR_ZTAR, 83)); } var_r25 = HuSprCreate(var_r26, 2, 1); HuSprGrpMemberSet(var_r28, (var_r31 * 4) + 2, var_r25); HuSprPosSet(var_r28, (var_r31 * 4) + 2, var_r29[var_r31], 0.0f); var_r26 = HuSprAnimReadFile(DATA_MAKE_NUM(DATADIR_ZTAR, 88)); var_r25 = HuSprCreate(var_r26, 2, GWPlayerCfg[var_r31].diff); HuSprGrpMemberSet(var_r28, (var_r31 * 4) + 3, var_r25); HuSprPosSet(var_r28, (var_r31 * 4) + 3, var_r29[var_r31], 38.0f); if (GWPlayerCfg[var_r31].iscom == 0) { HuSprAttrSet(var_r28, (var_r31 * 4) + 3, 4); } } var_r27 = HuSprGrpCreate(5); var_r26 = HuSprAnimRead(HuDataReadNum(DATA_MAKE_NUM(DATADIR_ZTAR, 67), MEMORY_DEFAULT_NUM)); var_r25 = HuSprCreate(var_r26, 0x32, 0); HuSprGrpMemberSet(var_r27, 0, var_r25); HuSprTPLvlSet(var_r27, 0, 0.9f); HuSprPosSet(var_r27, 0, 0.0f, 0.0f); HuSprScaleSet(var_r27, 0, 1.1f, 1.0f); var_r26 = HuSprAnimRead(HuDataReadNum(DATA_MAKE_NUM(DATADIR_ZTAR, 65), MEMORY_DEFAULT_NUM)); var_r25 = HuSprCreate(var_r26, 0x28, 0); HuSprGrpMemberSet(var_r27, 1, var_r25); HuSprPosSet(var_r27, 1, 0.0f, -90.0f); var_r26 = HuSprAnimRead(HuDataReadNum(DATA_MAKE_NUM(DATADIR_ZTAR, 66), MEMORY_DEFAULT_NUM)); var_r25 = HuSprCreate(var_r26, 0x28, 0); HuSprGrpMemberSet(var_r27, 2, var_r25); HuSprPosSet(var_r27, 2, 0.0f, 0.0f); var_r26 = HuSprAnimRead(HuDataReadNum(DATA_MAKE_NUM(DATADIR_ZTAR, 68), MEMORY_DEFAULT_NUM)); var_r25 = HuSprCreate(var_r26, 0x28, 1); HuSprGrpMemberSet(var_r27, 3, var_r25); HuSprPosSet(var_r27, 3, 180.0f, 0.0f); var_r26 = HuSprAnimRead(HuDataReadNum(DATA_MAKE_NUM(DATADIR_ZTAR, 68), MEMORY_DEFAULT_NUM)); var_r25 = HuSprCreate(var_r26, 0x28, 0); HuSprGrpMemberSet(var_r27, 4, var_r25); HuSprPosSet(var_r27, 4, -180.0f, 0.0f); HuSprGrpPosSet(var_r27, 288.0f, 240.0f); for (var_r31 = 0; var_r31 <= 0x3C; var_r31++) { if (var_r31 <= 0x32) { var_f31 = var_r31 / 50.0; var_f30 = -300.0 + (560.0 * sind((90.0f * var_f31))); HuSprGrpPosSet(var_r27, 288.0f, var_f30); HuSprGrpPosSet(var_r28, 288.0f, var_f30); } else { var_f31 = (var_r31 - 0x32) / 10.0; var_f30 = 240.0 + (20.0 * cosd((90.0f * var_f31))); var_f30 = var_f30; HuSprGrpPosSet(var_r27, 288.0f, var_f30); HuSprGrpPosSet(var_r28, 288.0f, var_f30); } HuPrcVSleep(); } var_r24 = HuWinCreate(0.0f, 0.0f, 0x1E0, 0x28, 0); HuWinMesSpeedSet(var_r24, 0); HuWinBGTPLvlSet(var_r24, 0.0f); HuWinMesSet(var_r24, MAKE_MESSID(0x1A, 0x20)); var_r22 = &winData[var_r24]; HuWinPriSet(var_r24, 5); HuWinPosSet(var_r24, (576.0f - var_r22->w) / 2, 300.0f); #if VERSION_PAL HuWinScaleSet(var_r24, 0.95f, 1.0f); #endif HuWinAttrSet(var_r24, 0x800); var_r30 = 0; var_r23 = 0; while (TRUE) { HuPrcVSleep(); if (HuPadBtnDown[0] & PAD_BUTTON_B) { HuAudFXPlay(3); goto block_89; } spC = 0; if (HuPadDStkRep[0] & PAD_BUTTON_LEFT) { HuAudFXPlay(0x304); for (var_r31 = 0; var_r31 <= 5; var_r31++) { var_f31 = var_r31 / 5.0; HuSprPosSet(var_r27, 4, -180.0 - (10.0 * sind((90.0f * var_f31))), 0.0f); HuPrcVSleep(); } var_r30--; if (mgTypeCurr == 1) { if (var_r30 < 0) { var_r30 = 3; } if (var_r30 >= 4) { var_r30 = 0; } for (var_r31 = 0; var_r31 < 4; var_r31++) { HuSprPosSet(var_r28, lbl_1_data_84[var_r30 * 4 + var_r31] * 4, var_r29[var_r31], 0.0f); HuSprPosSet(var_r28, lbl_1_data_84[var_r30 * 4 + var_r31] * 4 + 2, var_r29[var_r31], 0.0f); HuSprPosSet(var_r28, lbl_1_data_84[var_r30 * 4 + var_r31] * 4 + 3, var_r29[var_r31], 38.0f); } } else { if (var_r30 < 0) { var_r30 = 2; } if (var_r30 >= 3) { var_r30 = 0; } for (var_r31 = 0; var_r31 < 4; var_r31++) { HuSprPosSet(var_r28, lbl_1_data_94[var_r30 * 4 + var_r31] * 4, var_r29[var_r31], 0.0f); HuSprPosSet(var_r28, lbl_1_data_94[var_r30 * 4 + var_r31] * 4 + 2, var_r29[var_r31], 0.0f); HuSprPosSet(var_r28, lbl_1_data_94[var_r30 * 4 + var_r31] * 4 + 3, var_r29[var_r31], 38.0f); } } for (var_r31 = 0; var_r31 <= 5; var_r31++) { var_f31 = var_r31 / 5.0; HuSprPosSet(var_r27, 4, -180.0 - (10.0 * cosd((90.0f * var_f31))), 0.0f); HuPrcVSleep(); } } else { if (HuPadDStkRep[0] & PAD_BUTTON_RIGHT) { HuAudFXPlay(0x304); for (var_r31 = 0; var_r31 <= 5; var_r31++) { var_f31 = var_r31 / 5.0; HuSprPosSet(var_r27, 3, 180.0 - (10.0 * sind((90.0f * var_f31))), 0.0f); HuPrcVSleep(); } var_r30++; if (mgTypeCurr == 1) { if (var_r30 < 0) { var_r30 = 3; } if (var_r30 >= 4) { var_r30 = 0; } for (var_r31 = 0; var_r31 < 4; var_r31++) { HuSprPosSet(var_r28, lbl_1_data_84[var_r30 * 4 + var_r31] * 4, var_r29[var_r31], 0.0f); HuSprPosSet(var_r28, (lbl_1_data_84[var_r30 * 4 + var_r31] * 4) + 2, var_r29[var_r31], 0.0f); HuSprPosSet(var_r28, (lbl_1_data_84[var_r30 * 4 + var_r31] * 4) + 3, var_r29[var_r31], 38.0f); } } else { if (var_r30 < 0) { var_r30 = 2; } if (var_r30 >= 3) { var_r30 = 0; } for (var_r31 = 0; var_r31 < 4; var_r31++) { HuSprPosSet(var_r28, lbl_1_data_94[var_r30 * 4 + var_r31] * 4, var_r29[var_r31], 0.0f); HuSprPosSet(var_r28, (lbl_1_data_94[var_r30 * 4 + var_r31] * 4) + 2, var_r29[var_r31], 0.0f); HuSprPosSet(var_r28, (lbl_1_data_94[var_r30 * 4 + var_r31] * 4) + 3, var_r29[var_r31], 38.0f); } } for (var_r31 = 0; var_r31 <= 5; var_r31++) { var_f31 = var_r31 / 5.0; HuSprPosSet(var_r27, 3, 180.0 + (10.0 * cosd((90.0f * var_f31))), 0.0f); HuPrcVSleep(); } } } if (HuPadBtnDown[0] & (PAD_BUTTON_START | PAD_BUTTON_A)) { HuAudFXPlay(0x305); if (mgTypeCurr == 1) { GWPlayerCfg[lbl_1_data_84[var_r30 * 4]].group = 0; for (var_r31 = 1; var_r31 < 4; var_r31++) { GWPlayerCfg[lbl_1_data_84[var_r30 * 4 + var_r31]].group = 1; } } else { for (var_r31 = 0; var_r31 < 2; var_r31++) { GWPlayerCfg[lbl_1_data_94[var_r30 * 4 + var_r31]].group = 0; } for (var_r31 = 2; var_r31 < 4; var_r31++) { GWPlayerCfg[lbl_1_data_94[var_r30 * 4 + var_r31]].group = 1; } } if (arg0 != 0) { var_r23 = 1; } else { return 1; } block_89: HuWinKill(var_r24); for (var_r31 = 0; var_r31 <= 0x3C; var_r31++) { if (var_r31 <= 0xA) { var_f31 = var_r31 / 10.0; var_f30 = 240.0 + (20.0 * sind((90.0f * var_f31))); HuSprGrpPosSet(var_r27, 288.0f, var_f30); HuSprGrpPosSet(var_r28, 288.0f, var_f30); } else { var_f31 = (var_r31 - 0xA) / 50.0; var_f30 = -300.0 + (560.0 * cosd(90.0f * var_f31)); HuSprGrpPosSet(var_r27, 288.0f, var_f30); HuSprGrpPosSet(var_r28, 288.0f, var_f30); } HuPrcVSleep(); } HuSprGrpKill(var_r28); HuSprGrpKill(var_r27); return var_r23; } } } void fn_1_66F8(void) { s16 var_r31; while (TRUE) { if (lbl_1_bss_60 != 0 || omSysExitReq) { break; } HuPrcVSleep(); } WipeColorSet(0xFF, 0xFF, 0xFF); WipeCreate(WIPE_MODE_OUT, WIPE_TYPE_NORMAL, 60); while (WipeStatGet() != 0) { HuPrcVSleep(); } HuDataDirClose(DATADIR_INSTPIC); while (lbl_1_bss_4 != 0) { HuPrcVSleep(); } CharModelDataClose(-1); for (var_r31 = 0; var_r31 < 4; var_r31++) { GWPlayerCfg[var_r31].character = -1; } #if VERSION_PAL for (var_r31 = 0; var_r31 < 8; var_r31++) { charVoiceGroupStat[var_r31] = 0; } #endif mgPracticeEnableF = 0; omOvlReturnEx(1, 1); HuPrcEnd(); } void fn_1_6804(void) { Vec sp2C; Vec sp20; Vec sp14; Vec sp8; float var_f31; float var_f30; float var_f29; s8 var_r31; CRot.y += 0.1f * HuPadStkX[0]; CRot.x += 0.1f * HuPadStkY[0]; CZoom += HuPadTrigL[0] / 2; CZoom -= HuPadTrigR[0] / 2; if (HuPadBtnDown[0] & PAD_BUTTON_B) { OSReport("%f,%f,%f\n", CRot.x, CRot.y, CRot.z); OSReport("%f,%f,%f\n", Center.x, Center.y, Center.z); OSReport("%f\n", CZoom); } if (CZoom < 100.0f) { CZoom = 100.0f; } sp2C.x = Center.x + (CZoom * (sind(CRot.y) * cosd(CRot.x))); sp2C.y = Center.y + (CZoom * -sind(CRot.x)); sp2C.z = Center.z + (CZoom * (cosd(CRot.y) * cosd(CRot.x))); sp20.x = Center.x - sp2C.x; sp20.y = Center.y - sp2C.y; sp20.z = Center.z - sp2C.z; sp14.x = sind(CRot.y) * sind(CRot.x); sp14.y = cosd(CRot.x); sp14.z = cosd(CRot.y) * sind(CRot.x); var_f31 = CRot.z; sp8.x = sp14.x * ((sp20.x * sp20.x) + ((1.0f - (sp20.x * sp20.x)) * cosd(var_f31))) + sp14.y * (((sp20.x * sp20.y) * (1.0 - cosd(var_f31))) - sp20.z * sind(var_f31)) + sp14.z * (((sp20.x * sp20.z) * (1.0 - cosd(var_f31))) + sp20.y * sind(var_f31)); sp8.y = sp14.y * ((sp20.y * sp20.y) + ((1.0f - (sp20.y * sp20.y)) * cosd(var_f31))) + sp14.x * (((sp20.x * sp20.y) * (1.0 - cosd(var_f31))) + sp20.z * sind(var_f31)) + sp14.z * (((sp20.y * sp20.z) * (1.0 - cosd(var_f31))) - sp20.x * sind(var_f31)); sp8.z = sp14.z * ((sp20.z * sp20.z) + ((1.0f - (sp20.z * sp20.z)) * cosd(var_f31))) + (sp14.x * (((sp20.x * sp20.z) * (1.0 - cosd(var_f31))) - sp20.y * sind(var_f31)) + sp14.y * (((sp20.y * sp20.z) * (1.0 - cosd(var_f31))) + sp20.x * sind(var_f31))); VECCrossProduct(&sp14, &sp20, &sp20); VECNormalize(&sp20, &sp20); var_r31 = HuPadSubStkX[0] & 0xF8; if (var_r31 != 0) { Center.x += 0.05f * (sp20.x * var_r31); Center.y += 0.05f * (sp20.y * var_r31); Center.z += 0.05f * (sp20.z * var_r31); } VECNormalize(&sp8, &sp20); var_r31 = -(HuPadSubStkY[0] & 0xF8); if (var_r31 != 0) { Center.x += 0.05f * (sp20.x * var_r31); Center.y += 0.05f * (sp20.y * var_r31); Center.z += 0.05f * (sp20.z * var_r31); } } void fn_1_7414(ModelData *model, Mtx matrix) { Mtx sp8C; Mtx sp5C; Mtx sp2C; GXTexObj spC; s32 sp8; sp8 = 0; GXClearVtxDesc(); GXSetVtxDesc(GX_VA_POS, GX_DIRECT); GXSetVtxAttrFmt(GX_VTXFMT0, GX_VA_POS, GX_POS_XYZ, GX_F32, 0); GXInitTexObj(&spC, Hu3DShadowData.unk_04, Hu3DShadowData.unk_02, Hu3DShadowData.unk_02, 1, GX_CLAMP, GX_CLAMP, GX_FALSE); GXInitTexObjLOD(&spC, GX_LINEAR, GX_LINEAR, 0.0f, 0.0f, 0.0f, GX_FALSE, GX_FALSE, GX_ANISO_1); GXLoadTexObj(&spC, GX_TEXMAP0); MTXInverse(Hu3DCameraMtx, sp5C); MTXConcat(sp5C, matrix, sp8C); MTXConcat(Hu3DShadowData.unk_68, Hu3DShadowData.unk_38, sp2C); MTXConcat(sp2C, sp8C, sp8C); GXLoadTexMtxImm(sp8C, 0x39, GX_MTX3x4); GXSetTexCoordGen2(GX_TEXCOORD0, GX_TG_MTX3x4, GX_TG_POS, 0x39, GX_FALSE, 0x7D); GXSetTevOrder(GX_TEVSTAGE0, GX_TEXCOORD0, GX_TEXMAP0, GX_COLOR0A0); GXSetTevColorIn(GX_TEVSTAGE0, GX_CC_TEXC, GX_CC_ZERO, GX_CC_ZERO, GX_CC_ZERO); GXSetTevColorOp(GX_TEVSTAGE0, GX_TEV_ADD, GX_TB_ZERO, GX_CS_SCALE_1, GX_TRUE, GX_TEVPREV); GXSetTevAlphaIn(GX_TEVSTAGE0, GX_CA_KONST, GX_CA_ZERO, GX_CA_ZERO, GX_CA_ZERO); GXSetTevAlphaOp(GX_TEVSTAGE0, GX_TEV_ADD, GX_TB_ZERO, GX_CS_SCALE_1, GX_FALSE, GX_TEVPREV); GXSetNumTexGens(1); GXSetNumTevStages(1); GXSetNumChans(1); GXSetChanCtrl(GX_COLOR0, GX_TRUE, GX_SRC_REG, GX_SRC_VTX, 1, GX_DF_CLAMP, GX_AF_NONE); GXSetBlendMode(GX_BM_BLEND, GX_BL_ZERO, GX_BL_INVDSTCLR, GX_LO_NOOP); GXSetZMode(1, GX_LEQUAL, GX_FALSE); GXLoadPosMtxImm(matrix, 0); GXBegin(GX_QUADS, GX_VTXFMT0, 4); GXPosition3f32(-500.0f, 0.0f, -500.0f); GXPosition3f32(500.0f, 0.0f, -500.0f); GXPosition3f32(500.0f, 0.0f, 500.0f); GXPosition3f32(-500.0f, 0.0f, 500.0f); }
0
0.816925
1
0.816925
game-dev
MEDIA
0.429802
game-dev
0.923321
1
0.923321
savatkinv/VoxelGame
7,529
VoxelGame_UnityProject/Assets/Custom/NaughtyAttributes/Scripts/Editor/PropertyDrawers/AnimatorParamPropertyDrawer.cs
using System.Collections.Generic; using System.Reflection; using UnityEditor; using UnityEditor.Animations; using UnityEngine; namespace NaughtyAttributes.Editor { [CustomPropertyDrawer(typeof(AnimatorParamAttribute))] public class AnimatorParamPropertyDrawer : PropertyDrawerBase { private const string InvalidAnimatorControllerWarningMessage = "Target animator controller is null"; private const string InvalidTypeWarningMessage = "{0} must be an int or a string"; protected override float GetPropertyHeight_Internal(SerializedProperty property, GUIContent label) { AnimatorParamAttribute animatorParamAttribute = PropertyUtility.GetAttribute<AnimatorParamAttribute>(property); bool validAnimatorController = GetAnimatorController(property, animatorParamAttribute.AnimatorName) != null; bool validPropertyType = property.propertyType == SerializedPropertyType.Integer || property.propertyType == SerializedPropertyType.String; return (validAnimatorController && validPropertyType) ? GetPropertyHeight(property) : GetPropertyHeight(property) + GetHelpBoxHeight(); } protected override void OnGUI_Internal(Rect rect, SerializedProperty property, GUIContent label) { EditorGUI.BeginProperty(rect, label, property); AnimatorParamAttribute animatorParamAttribute = PropertyUtility.GetAttribute<AnimatorParamAttribute>(property); AnimatorController animatorController = GetAnimatorController(property, animatorParamAttribute.AnimatorName); if (animatorController == null) { DrawDefaultPropertyAndHelpBox(rect, property, InvalidAnimatorControllerWarningMessage, MessageType.Warning); return; } int parametersCount = animatorController.parameters.Length; List<AnimatorControllerParameter> animatorParameters = new List<AnimatorControllerParameter>(parametersCount); for (int i = 0; i < parametersCount; i++) { AnimatorControllerParameter parameter = animatorController.parameters[i]; if (animatorParamAttribute.AnimatorParamType == null || parameter.type == animatorParamAttribute.AnimatorParamType) { animatorParameters.Add(parameter); } } switch (property.propertyType) { case SerializedPropertyType.Integer: DrawPropertyForInt(rect, property, label, animatorParameters); break; case SerializedPropertyType.String: DrawPropertyForString(rect, property, label, animatorParameters); break; default: DrawDefaultPropertyAndHelpBox(rect, property, string.Format(InvalidTypeWarningMessage, property.name), MessageType.Warning); break; } EditorGUI.EndProperty(); } private static void DrawPropertyForInt(Rect rect, SerializedProperty property, GUIContent label, List<AnimatorControllerParameter> animatorParameters) { int paramNameHash = property.intValue; int index = 0; for (int i = 0; i < animatorParameters.Count; i++) { if (paramNameHash == animatorParameters[i].nameHash) { index = i + 1; // +1 because the first option is reserved for (None) break; } } string[] displayOptions = GetDisplayOptions(animatorParameters); int newIndex = EditorGUI.Popup(rect, label.text, index, displayOptions); int newValue = newIndex == 0 ? 0 : animatorParameters[newIndex - 1].nameHash; if (property.intValue != newValue) { property.intValue = newValue; } } private static void DrawPropertyForString(Rect rect, SerializedProperty property, GUIContent label, List<AnimatorControllerParameter> animatorParameters) { string paramName = property.stringValue; int index = 0; for (int i = 0; i < animatorParameters.Count; i++) { if (paramName.Equals(animatorParameters[i].name, System.StringComparison.Ordinal)) { index = i + 1; // +1 because the first option is reserved for (None) break; } } string[] displayOptions = GetDisplayOptions(animatorParameters); int newIndex = EditorGUI.Popup(rect, label.text, index, displayOptions); string newValue = newIndex == 0 ? null : animatorParameters[newIndex - 1].name; if (!property.stringValue.Equals(newValue, System.StringComparison.Ordinal)) { property.stringValue = newValue; } } private static string[] GetDisplayOptions(List<AnimatorControllerParameter> animatorParams) { string[] displayOptions = new string[animatorParams.Count + 1]; displayOptions[0] = "(None)"; for (int i = 0; i < animatorParams.Count; i++) { displayOptions[i + 1] = animatorParams[i].name; } return displayOptions; } private static AnimatorController GetAnimatorController(SerializedProperty property, string animatorName) { object target = PropertyUtility.GetTargetObjectWithProperty(property); FieldInfo animatorFieldInfo = ReflectionUtility.GetField(target, animatorName); if (animatorFieldInfo != null && animatorFieldInfo.FieldType == typeof(Animator)) { Animator animator = animatorFieldInfo.GetValue(target) as Animator; if (animator != null) { AnimatorController animatorController = animator.runtimeAnimatorController as AnimatorController; return animatorController; } } PropertyInfo animatorPropertyInfo = ReflectionUtility.GetProperty(target, animatorName); if (animatorPropertyInfo != null && animatorPropertyInfo.PropertyType == typeof(Animator)) { Animator animator = animatorPropertyInfo.GetValue(target) as Animator; if (animator != null) { AnimatorController animatorController = animator.runtimeAnimatorController as AnimatorController; return animatorController; } } MethodInfo animatorGetterMethodInfo = ReflectionUtility.GetMethod(target, animatorName); if (animatorGetterMethodInfo != null && animatorGetterMethodInfo.ReturnType == typeof(Animator) && animatorGetterMethodInfo.GetParameters().Length == 0) { Animator animator = animatorGetterMethodInfo.Invoke(target, null) as Animator; if (animator != null) { AnimatorController animatorController = animator.runtimeAnimatorController as AnimatorController; return animatorController; } } return null; } } }
0
0.610474
1
0.610474
game-dev
MEDIA
0.864736
game-dev
0.652314
1
0.652314