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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
sealj553/VexV5Doom | 3,310 | include/okapi/api/util/abstractTimer.hpp | /**
* @author Ryan Benasutti, WPI
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#pragma once
#include "okapi/api/units/QFrequency.hpp"
#include "okapi/api/units/QTime.hpp"
namespace okapi {
class AbstractTimer {
public:
/**
* A Timer base class which implements its methods in terms of millis().
*
* @param ifirstCalled the current time
*/
explicit AbstractTimer(QTime ifirstCalled);
virtual ~AbstractTimer();
/**
* Returns the current time in units of QTime.
*
* @return the current time
*/
virtual QTime millis() const = 0;
/**
* Returns the time passed in ms since the previous call of this function.
*
* @return The time passed in ms since the previous call of this function
*/
virtual QTime getDt();
/**
* Returns the time passed in ms since the previous call of getDt(). Does not change the time
* recorded by getDt().
*
* @return The time passed in ms since the previous call of getDt()
*/
virtual QTime readDt() const;
/**
* Returns the time the timer was first constructed.
*
* @return The time the timer was first constructed
*/
virtual QTime getStartingTime() const;
/**
* Returns the time since the timer was first constructed.
*
* @return The time since the timer was first constructed
*/
virtual QTime getDtFromStart() const;
/**
* Place a time marker. Placing another marker will overwrite the previous one.
*/
virtual void placeMark();
/**
* Clears the marker.
*
* @return The old marker
*/
virtual QTime clearMark();
/**
* Place a hard time marker. Placing another hard marker will not overwrite the previous one;
* instead, call clearHardMark() and then place another.
*/
virtual void placeHardMark();
/**
* Clears the hard marker.
*
* @return The old hard marker
*/
virtual QTime clearHardMark();
/**
* Returns the time since the time marker. Returns 0_ms if there is no marker.
*
* @return The time since the time marker
*/
virtual QTime getDtFromMark() const;
/**
* Returns the time since the hard time marker. Returns 0_ms if there is no hard marker set.
*
* @return The time since the hard time marker
*/
virtual QTime getDtFromHardMark() const;
/**
* Returns true when the input time period has passed, then resets. Meant to be used in loops
* to run an action every time period without blocking.
*
* @param time time period
* @return true when the input time period has passed, false after reading true until the
* period has passed again
*/
virtual bool repeat(QTime time);
/**
* Returns true when the input time period has passed, then resets. Meant to be used in loops
* to run an action every time period without blocking.
*
* @param frequency the repeat frequency
* @return true when the input time period has passed, false after reading true until the
* period has passed again
*/
virtual bool repeat(QFrequency frequency);
protected:
QTime firstCalled;
QTime lastCalled;
QTime mark;
QTime hardMark;
QTime repeatMark;
};
} // namespace okapi
| 412 | 0.967547 | 1 | 0.967547 | game-dev | MEDIA | 0.162368 | game-dev | 0.932841 | 1 | 0.932841 |
azahar-emu/azahar | 1,048 | src/core/system_titles.h | // Copyright Citra Emulator Project / Azahar Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#pragma once
#include <optional>
#include <utility>
#include <vector>
#include "common/common_types.h"
namespace Core {
constexpr u32 NUM_SYSTEM_TITLE_REGIONS = 7;
enum SystemTitleSet : u32 { Minimal = 1 << 0, Old3ds = 1 << 1, New3ds = 1 << 2 };
/// Returns a list of firmware title IDs for a specific set and region.
std::vector<u64> GetSystemTitleIds(SystemTitleSet set, u32 region);
/// Gets the home menu title ID for a specific region.
u64 GetHomeMenuTitleId(u32 region);
/// Gets the home menu NCCH path for a specific region.
std::string GetHomeMenuNcchPath(u32 region);
/// Returns the region of a system title, if it can be determined.
std::optional<u32> GetSystemTitleRegion(u64 title_id);
/// Determines if all system titles are installed for o3ds and n3ds.
std::pair<bool, bool> AreSystemTitlesInstalled();
void UninstallSystemFiles(SystemTitleSet set);
} // namespace Core
| 412 | 0.754979 | 1 | 0.754979 | game-dev | MEDIA | 0.289073 | game-dev | 0.725624 | 1 | 0.725624 |
bumptech/glide | 2,377 | library/src/main/java/com/bumptech/glide/load/engine/LockedResource.java | package com.bumptech.glide.load.engine;
import androidx.annotation.NonNull;
import androidx.core.util.Pools;
import com.bumptech.glide.util.Preconditions;
import com.bumptech.glide.util.Synthetic;
import com.bumptech.glide.util.pool.FactoryPools;
import com.bumptech.glide.util.pool.StateVerifier;
/**
* A resource that defers any calls to {@link Resource#recycle()} until after {@link #unlock()} is
* called.
*
* <p>If the resource was recycled prior to {@link #unlock()}, then {@link #unlock()} will also
* recycle the resource.
*/
final class LockedResource<Z> implements Resource<Z>, FactoryPools.Poolable {
private static final Pools.Pool<LockedResource<?>> POOL =
FactoryPools.threadSafe(
20,
new FactoryPools.Factory<LockedResource<?>>() {
@Override
public LockedResource<?> create() {
return new LockedResource<Object>();
}
});
private final StateVerifier stateVerifier = StateVerifier.newInstance();
private Resource<Z> toWrap;
private boolean isLocked;
private boolean isRecycled;
@SuppressWarnings("unchecked")
@NonNull
static <Z> LockedResource<Z> obtain(Resource<Z> resource) {
LockedResource<Z> result = Preconditions.checkNotNull((LockedResource<Z>) POOL.acquire());
result.init(resource);
return result;
}
@SuppressWarnings("WeakerAccess")
@Synthetic
LockedResource() {}
private void init(Resource<Z> toWrap) {
isRecycled = false;
isLocked = true;
this.toWrap = toWrap;
}
private void release() {
toWrap = null;
POOL.release(this);
}
synchronized void unlock() {
stateVerifier.throwIfRecycled();
if (!isLocked) {
throw new IllegalStateException("Already unlocked");
}
this.isLocked = false;
if (isRecycled) {
recycle();
}
}
@NonNull
@Override
public Class<Z> getResourceClass() {
return toWrap.getResourceClass();
}
@NonNull
@Override
public Z get() {
return toWrap.get();
}
@Override
public int getSize() {
return toWrap.getSize();
}
@Override
public synchronized void recycle() {
stateVerifier.throwIfRecycled();
this.isRecycled = true;
if (!isLocked) {
toWrap.recycle();
release();
}
}
@NonNull
@Override
public StateVerifier getVerifier() {
return stateVerifier;
}
}
| 412 | 0.795379 | 1 | 0.795379 | game-dev | MEDIA | 0.760761 | game-dev | 0.907075 | 1 | 0.907075 |
jabuwu/shanty-quest | 3,219 | src/game/state.rs | use bevy::prelude::*;
use crate::game::prelude::*;
#[derive(Clone, Debug, Resource)]
pub struct GameState {
pub town: TownData,
pub band_members: [BandMember; 2],
pub band_unlocked_count: usize,
pub showed_example_text: bool,
pub quests: Quests,
pub dangerous_seas: bool,
pub attacks: Attacks,
pub checkpoint_notification: bool,
pub health: f32,
pub health_max: f32,
pub defense: u32,
pub experience: f32,
pub level: u32,
pub skill_points: u32,
pub checkpoint: Option<Box<GameState>>,
}
impl Default for GameState {
fn default() -> Self {
Self {
town: TownData::default(),
band_members: [BandMember::from_index(0), BandMember::from_index(1)],
band_unlocked_count: 3,
showed_example_text: false,
quests: Quests::default(),
dangerous_seas: false,
attacks: Attacks {
forward_cannons: 1,
shotgun_cannons: 0,
shockwave: 0,
bombs: 0,
kraken: 0,
},
health: 20.,
health_max: 20.,
defense: 1,
experience: 0.,
level: 1,
skill_points: 0,
checkpoint_notification: false,
checkpoint: None,
}
}
}
impl GameState {
pub fn checkpoint(&mut self) {
self.checkpoint_notification = true;
self.checkpoint = Some(Box::new(self.clone()));
}
pub fn restore_checkpoint(&mut self) -> bool {
if let Some(checkpoint) = self.checkpoint.take() {
let GameState {
experience,
level,
skill_points,
dangerous_seas,
..
} = *self;
*self = *checkpoint.clone();
self.checkpoint = Some(checkpoint);
self.checkpoint_notification = false;
self.experience = experience;
self.level = level;
self.skill_points = skill_points;
self.dangerous_seas = dangerous_seas;
true
} else {
false
}
}
pub fn member_in_band(&self, band_member: BandMember) -> bool {
for i in 0..2 {
if self.band_members[i] == band_member {
return true;
}
}
false
}
pub fn add_experience(&mut self, amt: f32) -> bool {
self.experience += amt;
if self.experience >= self.experience_max() {
self.experience -= self.experience_max();
self.level += 1;
true
} else {
false
}
}
pub fn experience_max(&self) -> f32 {
5. + (self.level - 1) as f32 * 10.
}
pub fn apply_defense_upgrade(&mut self) {
self.health *= 1.2;
self.health_max *= 1.2;
self.defense += 1;
}
pub fn has_all_unlocks(&self) -> bool {
self.attacks.forward_cannons == 5
&& self.attacks.shotgun_cannons == 5
&& self.attacks.shockwave == 5
&& self.attacks.bombs == 5
&& self.attacks.kraken == 5
&& self.defense == 5
}
}
| 412 | 0.915577 | 1 | 0.915577 | game-dev | MEDIA | 0.6231 | game-dev | 0.968931 | 1 | 0.968931 |
PaperMC/Paper-archive | 3,514 | patches/server/1024-API-to-allow-disallow-tick-sleeping.patch | From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Abel <abelvanhulst@gmail.com>
Date: Tue, 12 Nov 2024 22:25:20 +0100
Subject: [PATCH] API to allow/disallow tick sleeping
diff --git a/src/main/java/net/minecraft/server/MinecraftServer.java b/src/main/java/net/minecraft/server/MinecraftServer.java
index 1c5a439650146bee85a98d8072ee131300264eee..c3d02e4712a1543fc59d88e5d20adcb6c806be0f 100644
--- a/src/main/java/net/minecraft/server/MinecraftServer.java
+++ b/src/main/java/net/minecraft/server/MinecraftServer.java
@@ -328,6 +328,7 @@ public abstract class MinecraftServer extends ReentrantBlockableEventLoop<TickTa
// Spigot end
public final io.papermc.paper.configuration.PaperConfigurations paperConfigurations; // Paper - add paper configuration files
public boolean isIteratingOverLevels = false; // Paper - Throw exception on world create while being ticked
+ private final Set<String> pluginsBlockingSleep = new java.util.HashSet<>(); // Paper - API to allow/disallow tick sleeping
public static <S extends MinecraftServer> S spin(Function<Thread, S> serverFactory) {
AtomicReference<S> atomicreference = new AtomicReference();
@@ -1500,8 +1501,9 @@ public abstract class MinecraftServer extends ReentrantBlockableEventLoop<TickTa
long i = Util.getNanos();
int j = this.pauseWhileEmptySeconds() * 20;
+ this.removeDisabledPluginsBlockingSleep(); // Paper - API to allow/disallow tick sleeping
if (j > 0) {
- if (this.playerList.getPlayerCount() == 0 && !this.tickRateManager.isSprinting()) {
+ if (this.playerList.getPlayerCount() == 0 && !this.tickRateManager.isSprinting() && this.pluginsBlockingSleep.isEmpty()) { // Paper - API to allow/disallow tick sleeping
++this.emptyTicks;
} else {
this.emptyTicks = 0;
@@ -3031,5 +3033,22 @@ public abstract class MinecraftServer extends ReentrantBlockableEventLoop<TickTa
public boolean isTickPaused() {
return this.emptyTicks > 0 && this.emptyTicks >= this.pauseWhileEmptySeconds() * 20;
}
+
+ public void addPluginAllowingSleep(final String pluginName, final boolean value) {
+ if (!value) {
+ this.pluginsBlockingSleep.add(pluginName);
+ } else {
+ this.pluginsBlockingSleep.remove(pluginName);
+ }
+ }
+
+ private void removeDisabledPluginsBlockingSleep() {
+ if (this.pluginsBlockingSleep.isEmpty()) {
+ return;
+ }
+ this.pluginsBlockingSleep.removeIf(plugin -> (
+ !io.papermc.paper.plugin.manager.PaperPluginManagerImpl.getInstance().isPluginEnabled(plugin)
+ ));
+ }
// Paper end - API to check if the server is sleeping
}
diff --git a/src/main/java/org/bukkit/craftbukkit/CraftServer.java b/src/main/java/org/bukkit/craftbukkit/CraftServer.java
index df9cfdcc27d6f596d554d7271b1d6a30cd3fbc0e..6370b780af5043f32d07346ea4dd7f23c819f7a0 100644
--- a/src/main/java/org/bukkit/craftbukkit/CraftServer.java
+++ b/src/main/java/org/bukkit/craftbukkit/CraftServer.java
@@ -3264,5 +3264,10 @@ public final class CraftServer implements Server {
public boolean isPaused() {
return this.console.isTickPaused();
}
+
+ @Override
+ public void allowPausing(final Plugin plugin, final boolean value) {
+ this.console.addPluginAllowingSleep(plugin.getName(), value);
+ }
// Paper end - API to check if the server is sleeping
}
| 412 | 0.63924 | 1 | 0.63924 | game-dev | MEDIA | 0.963729 | game-dev | 0.624516 | 1 | 0.624516 |
MegaMek/megamek | 7,114 | megamek/src/megamek/client/ui/clientGUI/boardview/overlay/KeyBindingsOverlay.java | /*
* Copyright (C) 2020-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.clientGUI.boardview.overlay;
import java.awt.Font;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import megamek.client.ui.Messages;
import megamek.client.ui.clientGUI.GUIPreferences;
import megamek.client.ui.clientGUI.boardview.BoardView;
import megamek.client.ui.util.KeyCommandBind;
import megamek.common.preference.PreferenceChangeEvent;
/**
* An overlay for the BoardView that displays a selection of keybinds for the current game situation
*
* @author SJuliez
*/
public class KeyBindingsOverlay extends AbstractBoardViewOverlay {
/** The keybinds to be shown during the firing phases (incl. physical etc.) */
private static final List<KeyCommandBind> BINDS_FIRE = Arrays.asList(KeyCommandBind.NEXT_WEAPON,
KeyCommandBind.PREV_WEAPON,
KeyCommandBind.UNDO_LAST_STEP,
KeyCommandBind.NEXT_TARGET,
KeyCommandBind.NEXT_TARGET_VALID,
KeyCommandBind.NEXT_TARGET_NO_ALLIES,
KeyCommandBind.NEXT_TARGET_VALID_NO_ALLIES,
KeyCommandBind.PHYS_PUNCH,
KeyCommandBind.PHYS_KICK,
KeyCommandBind.PHYS_PUSH,
KeyCommandBind.DONE_NO_ACTION);
/** The keybinds to be shown during the movement phase */
private static final List<KeyCommandBind> BINDS_MOVE = Arrays.asList(KeyCommandBind.MOVE_STEP_FORWARD,
KeyCommandBind.MOVE_STEP_BACKWARD,
KeyCommandBind.TURN_LEFT,
KeyCommandBind.TURN_RIGHT,
KeyCommandBind.TOGGLE_MOVE_MODE,
KeyCommandBind.MOVE_BACKUP,
KeyCommandBind.MOVE_GO_PRONE,
KeyCommandBind.MOVE_GETUP,
KeyCommandBind.UNDO_LAST_STEP,
KeyCommandBind.TOGGLE_CONVERSION_MODE,
KeyCommandBind.DONE_NO_ACTION);
/** The keybinds to be shown in all phases during the local player's turn */
private static final List<KeyCommandBind> BINDS_MY_TURN = Arrays.asList(KeyCommandBind.CANCEL,
KeyCommandBind.DONE,
KeyCommandBind.NEXT_UNIT,
KeyCommandBind.PREV_UNIT,
KeyCommandBind.CENTER_ON_SELECTED);
/** The keybinds to be shown in all phases during any player's turn */
private static final List<KeyCommandBind> BINDS_ANY_TURN = Arrays.asList(KeyCommandBind.TOGGLE_CHAT,
KeyCommandBind.DRAW_LABELS,
KeyCommandBind.HEX_COORDS);
/** The keybinds to be shown in the Board Editor */
private static final List<KeyCommandBind> BINDS_BOARD_EDITOR = List.of(KeyCommandBind.HEX_COORDS);
private static final List<String> ADDITIONAL_BINDS = Arrays.asList(Messages.getString(
"KeyBindingsDisplay.fixedBinds")
.split("\n"));
private static final List<String> ADDITIONAL_BINDS_BOARD_EDITOR = Arrays.asList(Messages.getString(
"KeyBindingsDisplay.fixedBindsBoardEd").split("\n"));
/**
* An overlay for the BoardView that displays a selection of keybinds for the current game situation.
*/
public KeyBindingsOverlay(BoardView boardView) {
super(boardView, new Font("SansSerif", Font.PLAIN, 13));
}
@Override
protected String getHeaderText() {
return Messages.getString("KeyBindingsDisplay.heading", KeyCommandBind.getDesc(KeyCommandBind.KEY_BINDS));
}
/** @return an ArrayList of all text lines to be shown. */
@Override
protected List<String> assembleTextLines() {
List<String> result = new ArrayList<>();
addHeader(result);
if (clientGui != null) {
// In a game, not the Board Editor
// Most of the keybinds are only active during the local player's turn
if ((clientGui.getClient() != null) && (clientGui.getClient().isMyTurn())) {
List<KeyCommandBind> listForPhase = new ArrayList<>();
switch (currentPhase) {
case MOVEMENT:
listForPhase = BINDS_MOVE;
break;
case FIRING:
case OFFBOARD:
case PHYSICAL:
listForPhase = BINDS_FIRE;
break;
default:
break;
}
result.addAll(convertToStrings(listForPhase));
result.addAll(convertToStrings(BINDS_MY_TURN));
}
result.addAll(convertToStrings(BINDS_ANY_TURN));
result.addAll(ADDITIONAL_BINDS);
} else {
// Board Editor
result.addAll(convertToStrings(BINDS_BOARD_EDITOR));
result.addAll(ADDITIONAL_BINDS_BOARD_EDITOR);
}
return result;
}
/** Converts a list of KeyCommandBinds to a list of formatted strings. */
private List<String> convertToStrings(List<KeyCommandBind> keyCommandBinds) {
List<String> result = new ArrayList<>();
for (KeyCommandBind kcb : keyCommandBinds) {
String label = Messages.getString("KeyBinds.cmdNames." + kcb.cmd);
String d = KeyCommandBind.getDesc(kcb);
result.add(label + ": " + d);
}
return result;
}
@Override
protected boolean getVisibilityGUIPreference() {
return GUIP.getShowKeybindsOverlay();
}
@Override
protected int getDistTop(Rectangle clipBounds, int overlayHeight) {
return 30;
}
@Override
protected int getDistSide(Rectangle clipBounds, int overlayWidth) {
return 30;
}
@Override
public void preferenceChange(PreferenceChangeEvent e) {
if (e.getName().equals(GUIPreferences.SHOW_KEYBINDS_OVERLAY)) {
setVisible((boolean) e.getNewValue());
scheduleBoardViewRepaint();
}
super.preferenceChange(e);
}
}
| 412 | 0.916372 | 1 | 0.916372 | game-dev | MEDIA | 0.593295 | game-dev | 0.967695 | 1 | 0.967695 |
ritchieng/machine-learning-nanodegree | 8,676 | ml_project_resources/projects/smartcab/smartcab/simulator.py | import os
import time
import random
import importlib
class Simulator(object):
"""Simulates agents in a dynamic smartcab environment.
Uses PyGame to display GUI, if available.
"""
colors = {
'black' : ( 0, 0, 0),
'white' : (255, 255, 255),
'red' : (255, 0, 0),
'green' : ( 0, 255, 0),
'blue' : ( 0, 0, 255),
'cyan' : ( 0, 200, 200),
'magenta' : (200, 0, 200),
'yellow' : (255, 255, 0),
'orange' : (255, 128, 0)
}
def __init__(self, env, size=None, update_delay=1.0, display=True):
self.env = env
self.size = size if size is not None else ((self.env.grid_size[0] + 1) * self.env.block_size, (self.env.grid_size[1] + 1) * self.env.block_size)
self.width, self.height = self.size
self.bg_color = self.colors['white']
self.road_width = 5
self.road_color = self.colors['black']
self.quit = False
self.start_time = None
self.current_time = 0.0
self.last_updated = 0.0
self.update_delay = update_delay # duration between each step (in secs)
self.display = display
if self.display:
try:
self.pygame = importlib.import_module('pygame')
self.pygame.init()
self.screen = self.pygame.display.set_mode(self.size)
self.frame_delay = max(1, int(self.update_delay * 1000)) # delay between GUI frames in ms (min: 1)
self.agent_sprite_size = (32, 32)
self.agent_circle_radius = 10 # radius of circle, when using simple representation
for agent in self.env.agent_states:
agent._sprite = self.pygame.transform.smoothscale(self.pygame.image.load(os.path.join("images", "car-{}.png".format(agent.color))), self.agent_sprite_size)
agent._sprite_size = (agent._sprite.get_width(), agent._sprite.get_height())
self.font = self.pygame.font.Font(None, 28)
self.paused = False
except ImportError as e:
self.display = False
print "Simulator.__init__(): Unable to import pygame; display disabled.\n{}: {}".format(e.__class__.__name__, e)
except Exception as e:
self.display = False
print "Simulator.__init__(): Error initializing GUI objects; display disabled.\n{}: {}".format(e.__class__.__name__, e)
def run(self, n_trials=1):
self.quit = False
for trial in xrange(n_trials):
print "Simulator.run(): Trial {}".format(trial) # [debug]
self.env.reset()
self.current_time = 0.0
self.last_updated = 0.0
self.start_time = time.time()
while True:
try:
# Update current time
self.current_time = time.time() - self.start_time
#print "Simulator.run(): current_time = {:.3f}".format(self.current_time)
# Handle GUI events
if self.display:
for event in self.pygame.event.get():
if event.type == self.pygame.QUIT:
self.quit = True
elif event.type == self.pygame.KEYDOWN:
if event.key == 27: # Esc
self.quit = True
elif event.unicode == u' ':
self.paused = True
if self.paused:
self.pause()
# Update environment
if self.current_time - self.last_updated >= self.update_delay:
self.env.step()
self.last_updated = self.current_time
# Render GUI and sleep
if self.display:
self.render()
self.pygame.time.wait(self.frame_delay)
except KeyboardInterrupt:
self.quit = True
finally:
if self.quit or self.env.done:
break
if self.quit:
break
def render(self):
# Clear screen
self.screen.fill(self.bg_color)
# Draw elements
# * Static elements
for road in self.env.roads:
self.pygame.draw.line(self.screen, self.road_color, (road[0][0] * self.env.block_size, road[0][1] * self.env.block_size), (road[1][0] * self.env.block_size, road[1][1] * self.env.block_size), self.road_width)
for intersection, traffic_light in self.env.intersections.iteritems():
self.pygame.draw.circle(self.screen, self.road_color, (intersection[0] * self.env.block_size, intersection[1] * self.env.block_size), 10)
if traffic_light.state: # North-South is open
self.pygame.draw.line(self.screen, self.colors['green'],
(intersection[0] * self.env.block_size, intersection[1] * self.env.block_size - 15),
(intersection[0] * self.env.block_size, intersection[1] * self.env.block_size + 15), self.road_width)
else: # East-West is open
self.pygame.draw.line(self.screen, self.colors['green'],
(intersection[0] * self.env.block_size - 15, intersection[1] * self.env.block_size),
(intersection[0] * self.env.block_size + 15, intersection[1] * self.env.block_size), self.road_width)
# * Dynamic elements
for agent, state in self.env.agent_states.iteritems():
# Compute precise agent location here (back from the intersection some)
agent_offset = (2 * state['heading'][0] * self.agent_circle_radius, 2 * state['heading'][1] * self.agent_circle_radius)
agent_pos = (state['location'][0] * self.env.block_size - agent_offset[0], state['location'][1] * self.env.block_size - agent_offset[1])
agent_color = self.colors[agent.color]
if hasattr(agent, '_sprite') and agent._sprite is not None:
# Draw agent sprite (image), properly rotated
rotated_sprite = agent._sprite if state['heading'] == (1, 0) else self.pygame.transform.rotate(agent._sprite, 180 if state['heading'][0] == -1 else state['heading'][1] * -90)
self.screen.blit(rotated_sprite,
self.pygame.rect.Rect(agent_pos[0] - agent._sprite_size[0] / 2, agent_pos[1] - agent._sprite_size[1] / 2,
agent._sprite_size[0], agent._sprite_size[1]))
else:
# Draw simple agent (circle with a short line segment poking out to indicate heading)
self.pygame.draw.circle(self.screen, agent_color, agent_pos, self.agent_circle_radius)
self.pygame.draw.line(self.screen, agent_color, agent_pos, state['location'], self.road_width)
if agent.get_next_waypoint() is not None:
self.screen.blit(self.font.render(agent.get_next_waypoint(), True, agent_color, self.bg_color), (agent_pos[0] + 10, agent_pos[1] + 10))
if state['destination'] is not None:
self.pygame.draw.circle(self.screen, agent_color, (state['destination'][0] * self.env.block_size, state['destination'][1] * self.env.block_size), 6)
self.pygame.draw.circle(self.screen, agent_color, (state['destination'][0] * self.env.block_size, state['destination'][1] * self.env.block_size), 15, 2)
# * Overlays
text_y = 10
for text in self.env.status_text.split('\n'):
self.screen.blit(self.font.render(text, True, self.colors['red'], self.bg_color), (100, text_y))
text_y += 20
# Flip buffers
self.pygame.display.flip()
def pause(self):
abs_pause_time = time.time()
pause_text = "[PAUSED] Press any key to continue..."
self.screen.blit(self.font.render(pause_text, True, self.colors['cyan'], self.bg_color), (100, self.height - 40))
self.pygame.display.flip()
print pause_text # [debug]
while self.paused:
for event in self.pygame.event.get():
if event.type == self.pygame.KEYDOWN:
self.paused = False
self.pygame.time.wait(self.frame_delay)
self.screen.blit(self.font.render(pause_text, True, self.bg_color, self.bg_color), (100, self.height - 40))
self.start_time += (time.time() - abs_pause_time)
| 412 | 0.804866 | 1 | 0.804866 | game-dev | MEDIA | 0.608621 | game-dev | 0.924133 | 1 | 0.924133 |
lingjye/iOS-Learning | 1,738 | LottieDemo/Pods/lottie-ios/lottie-ios/Classes/PublicHeaders/LOTAnimatedSwitch.h | //
// LOTAnimatedSwitch.h
// Lottie
//
// Created by brandon_withrow on 8/25/17.
// Copyright © 2017 Airbnb. All rights reserved.
//
#import "LOTAnimatedControl.h"
NS_ASSUME_NONNULL_BEGIN
@interface LOTAnimatedSwitch : LOTAnimatedControl
/// Convenience method to initialize a control from the Main Bundle by name
+ (instancetype _Nonnull)switchNamed:(NSString * _Nonnull)toggleName;
/// Convenience method to initialize a control from the specified bundle by name
+ (instancetype _Nonnull)switchNamed:(NSString * _Nonnull)toggleName inBundle:(NSBundle * _Nonnull)bundle;
/// The ON/OFF state of the control. Setting will toggle without animation
@property (nonatomic, getter=isOn) BOOL on;
/// Enable interactive sliding gesture for toggle
@property (nonatomic) BOOL interactiveGesture;
/// Set the state of the control with animation
- (void)setOn:(BOOL)on animated:(BOOL)animated; // does not send action
/// Styling
/**
* Sets the animation play range for the ON state animation.
* fromProgress is the start of the animation
* toProgress is the end of the animation and also the ON static state
* Defaults 0-1
**/
- (void)setProgressRangeForOnState:(CGFloat)fromProgress
toProgress:(CGFloat)toProgress NS_SWIFT_NAME(setProgressRangeForOnState(fromProgress:toProgress:));
/**
* Sets the animation play range for the OFF state animation.
* fromProgress is the start of the animation
* toProgress is the end of the animation and also the OFF static state
* Defaults 1-0
**/
- (void)setProgressRangeForOffState:(CGFloat)fromProgress
toProgress:(CGFloat)toProgress NS_SWIFT_NAME(setProgressRangeForOffState(fromProgress:toProgress:));
@end
NS_ASSUME_NONNULL_END
| 412 | 0.507237 | 1 | 0.507237 | game-dev | MEDIA | 0.552538 | game-dev,desktop-app | 0.620661 | 1 | 0.620661 |
FunkinCrew/Funkin | 3,519 | source/funkin/input/TurboButtonHandler.hx | package funkin.input;
import flixel.input.gamepad.FlxGamepadInputID;
import flixel.input.gamepad.FlxGamepad;
import flixel.FlxBasic;
/**
* Handles repeating behavior when holding down a gamepad button or button combination.
*
* When the `inputs` are pressed, `activated` will be true for the first frame,
* then wait `delay` seconds before becoming true for one frame every `interval` seconds.
*
* Example: Pressing Ctrl+Z will undo, while holding Ctrl+Z will start to undo repeatedly.
*/
@:nullSafety
class TurboButtonHandler extends FlxBasic
{
/**
* Default delay before repeating.
*/
static inline final DEFAULT_DELAY:Float = 0.4;
/**
* Default interval between repeats.
*/
static inline final DEFAULT_INTERVAL:Float = 0.1;
/**
* Whether all of the keys for this handler are pressed.
*/
public var allPressed(get, never):Bool;
/**
* Whether all of the keys for this handler are activated,
* and the handler is ready to repeat.
*/
public var activated(default, null):Bool = false;
var inputs:Array<FlxGamepadInputID>;
var delay:Float;
var interval:Float;
var targetGamepad:FlxGamepad;
var allPressedTime:Float = 0;
function new(inputs:Array<FlxGamepadInputID>, delay:Float = DEFAULT_DELAY, interval:Float = DEFAULT_INTERVAL, ?targetGamepad:FlxGamepad)
{
super();
this.inputs = inputs;
this.delay = delay;
this.interval = interval;
this.targetGamepad = targetGamepad ?? FlxG.gamepads.firstActive;
}
function get_allPressed():Bool
{
if (targetGamepad == null) return false;
if (inputs == null || inputs.length == 0) return false;
if (inputs.length == 1) return targetGamepad.anyPressed(inputs);
// Check if ANY keys are unpressed
for (input in inputs)
{
if (!targetGamepad.anyPressed([input])) return false;
}
return true;
}
public override function update(elapsed:Float):Void
{
super.update(elapsed);
// Try to find a gamepad if we don't have one
if (targetGamepad == null)
{
targetGamepad = FlxG.gamepads.firstActive;
}
if (allPressed)
{
if (allPressedTime == 0)
{
activated = true;
}
else if (allPressedTime >= (delay + interval))
{
activated = true;
allPressedTime -= interval;
}
else
{
activated = false;
}
allPressedTime += elapsed;
}
else
{
allPressedTime = 0;
activated = false;
}
}
/**
* Builds a TurboButtonHandler that monitors from a single input.
* @param input The input to monitor.
* @param delay How long to wait before repeating.
* @param repeatDelay How long to wait between repeats.
* @return A TurboKeyHandler
*/
public static overload inline extern function build(input:FlxGamepadInputID, ?delay:Float = DEFAULT_DELAY,
?interval:Float = DEFAULT_INTERVAL):TurboButtonHandler
{
return new TurboButtonHandler([input], delay, interval);
}
/**
* Builds a TurboKeyHandler that monitors a key combination.
* @param inputs The combination of inputs to monitor.
* @param delay How long to wait before repeating.
* @param repeatDelay How long to wait between repeats.
* @return A TurboKeyHandler
*/
public static overload inline extern function build(inputs:Array<FlxGamepadInputID>, ?delay:Float = DEFAULT_DELAY,
?interval:Float = DEFAULT_INTERVAL):TurboButtonHandler
{
return new TurboButtonHandler(inputs, delay, interval);
}
}
| 412 | 0.781116 | 1 | 0.781116 | game-dev | MEDIA | 0.393752 | game-dev | 0.841199 | 1 | 0.841199 |
Auviotre/Enigmatic-Addons | 5,875 | src/main/java/auviotre/enigmatic/addon/contents/entities/CobwebBall.java | package auviotre.enigmatic.addon.contents.entities;
import auviotre.enigmatic.addon.registries.EnigmaticAddonEntities;
import net.minecraft.core.particles.ItemParticleOption;
import net.minecraft.core.particles.ParticleTypes;
import net.minecraft.network.protocol.game.ClientboundAddEntityPacket;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.sounds.SoundSource;
import net.minecraft.util.Mth;
import net.minecraft.world.effect.MobEffectInstance;
import net.minecraft.world.effect.MobEffects;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.monster.Monster;
import net.minecraft.world.entity.monster.Spider;
import net.minecraft.world.entity.projectile.Projectile;
import net.minecraft.world.entity.projectile.ProjectileUtil;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.state.BlockBehaviour;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.EntityHitResult;
import net.minecraft.world.phys.HitResult;
import net.minecraft.world.phys.Vec3;
import net.minecraftforge.event.ForgeEventFactory;
public class CobwebBall extends Projectile {
public CobwebBall(EntityType<? extends Projectile> type, Level world) {
super(type, world);
}
public CobwebBall(Level world, Monster spider) {
this(EnigmaticAddonEntities.COBWEB_BALL, world);
this.setOwner(spider);
this.setPos(spider.getX() - (double) (spider.getBbWidth() + 1.0F) * 0.5D * (double) Mth.sin(spider.yBodyRot * ((float) Math.PI / 180F)), spider.getEyeY() - (double) 0.1F, spider.getZ() + (double) (spider.getBbWidth() + 1.0F) * 0.5D * (double) Mth.cos(spider.yBodyRot * ((float) Math.PI / 180F)));
}
public void tick() {
super.tick();
for (int i = 0; i < 3; ++i) {
double theta = Math.random() * 2 * Math.PI;
double phi = (Math.random() - 0.5D) * Math.PI;
double deltaX = 0.02D * Math.sin(theta) * Math.cos(phi);
double deltaY = 0.02D * Math.sin(phi);
double deltaZ = 0.02D * Math.cos(theta) * Math.cos(phi);
double x = this.getX() + this.getDeltaMovement().x * i / 3;
double y = this.getY() + this.getDeltaMovement().y * i / 3;
double z = this.getZ() + this.getDeltaMovement().z * i / 3;
this.level().addParticle(this.getParticle(), x, y, z, deltaX, deltaY, deltaZ);
}
Vec3 vec3 = this.getDeltaMovement();
HitResult hitresult = ProjectileUtil.getHitResultOnMoveVector(this, this::canHitEntity);
if (hitresult.getType() != HitResult.Type.MISS && !ForgeEventFactory.onProjectileImpact(this, hitresult))
this.onHit(hitresult);
double d0 = this.getX() + vec3.x;
double d1 = this.getY() + vec3.y;
double d2 = this.getZ() + vec3.z;
this.updateRotation();
if (this.level().getBlockStates(this.getBoundingBox()).noneMatch(BlockBehaviour.BlockStateBase::isAir)) {
this.discard();
} else if (this.isInWaterOrBubble()) {
this.discard();
} else {
this.setDeltaMovement(vec3.scale(0.98F));
if (!this.isNoGravity()) {
this.setDeltaMovement(this.getDeltaMovement().add(0.0D, -0.06F, 0.0D));
}
this.setPos(d0, d1, d2);
}
}
private ItemParticleOption getParticle() {
return new ItemParticleOption(ParticleTypes.ITEM, new ItemStack(Blocks.COBWEB));
}
protected void onHitEntity(EntityHitResult hitResult) {
super.onHitEntity(hitResult);
Entity entity = this.getOwner();
if (entity instanceof Spider spider) {
Entity target = hitResult.getEntity();
if (target.hurt(this.damageSources().mobProjectile(this, spider), 0.1F)) {
if (target == spider.getTarget() && target instanceof LivingEntity living) {
entity.level().playSound(null, target.blockPosition(), SoundEvents.HONEY_BLOCK_PLACE, SoundSource.BLOCKS);
int difficulty = this.level().getDifficulty().getId();
if (this.random.nextInt(5) > difficulty || !entity.level().getBlockState(target.blockPosition()).isAir()) {
living.addEffect(new MobEffectInstance(MobEffects.MOVEMENT_SLOWDOWN, 75, 3), spider);
} else {
entity.level().setBlock(target.blockPosition(), Blocks.COBWEB.defaultBlockState(), Block.UPDATE_ALL);
}
}
}
}
}
protected void onHitBlock(BlockHitResult hitResult) {
super.onHitBlock(hitResult);
if (!this.level().isClientSide) {
this.discard();
}
}
protected void defineSynchedData() {
}
public void recreateFromPacket(ClientboundAddEntityPacket entityPacket) {
super.recreateFromPacket(entityPacket);
double xa = entityPacket.getXa();
double ya = entityPacket.getYa();
double za = entityPacket.getZa();
for (int i = 0; i < 7; ++i) {
double v = 0.4D + 0.1D * i;
double theta = Math.random() * 2 * Math.PI;
double phi = (Math.random() - 0.5D) * Math.PI;
double deltaX = 0.02D * Math.sin(theta) * Math.cos(phi) + xa * v;
double deltaY = 0.02D * Math.sin(phi) + ya;
double deltaZ = 0.02D * Math.cos(theta) * Math.cos(phi) + za * v;
this.level().addParticle(this.getParticle(), this.getX(), this.getY(), this.getZ(), deltaX, deltaY, deltaZ);
}
this.setDeltaMovement(xa, ya, za);
}
}
| 412 | 0.726062 | 1 | 0.726062 | game-dev | MEDIA | 0.981494 | game-dev | 0.974328 | 1 | 0.974328 |
jsdotlua/react-lua | 4,560 | modules/scheduler/src/SchedulerProfiling.luau | --!strict
-- ROBLOX upstream https://github.com/facebook/react/blob/8af27aeedbc6b00bc2ef49729fc84f116c70a27c/packages/scheduler/src/SchedulerProfiling.js
--[[*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
]]
-- ROBLOX NOTE: this file is synced against a post-17.0.1 version that doesn't use SharedArrayBuffer
-- ROBLOX: use patched console from shared
local console = require("@pkg/@jsdotlua/shared").console
local exports = {}
local SchedulerPriorities = require("./SchedulerPriorities")
type PriorityLevel = SchedulerPriorities.PriorityLevel
local ScheduleFeatureFlags = require("./SchedulerFeatureFlags")
local enableProfiling = ScheduleFeatureFlags.enableProfiling
local runIdCounter: number = 0
local mainThreadIdCounter: number = 0
-- Bytes per element is 4
local INITIAL_EVENT_LOG_SIZE = 131072
local MAX_EVENT_LOG_SIZE = 524288 -- Equivalent to 2 megabytes
-- Strictly speaking, only the first element of an EventLog can be a reference to another EventLog.
type EventLog = { EventLog | { number } }
local eventLogSize = 0
local eventLogBuffer = nil
local eventLog: EventLog? = nil
local eventLogIndex = 1
local TaskStartEvent = 1
local TaskCompleteEvent = 2
local TaskErrorEvent = 3
local TaskCancelEvent = 4
local TaskRunEvent = 5
local TaskYieldEvent = 6
local SchedulerSuspendEvent = 7
local SchedulerResumeEvent = 8
local function logEvent(entries)
if eventLog ~= nil then
-- ROBLOX deviation: upstream uses a packed array for performance. we do something simpler for now
eventLogIndex += #entries
if eventLogIndex + 1 > eventLogSize then
eventLogSize *= 2
if eventLogSize > MAX_EVENT_LOG_SIZE then
-- Using console['error'] to evade Babel and ESLint
console["error"](
"Scheduler Profiling: Event log exceeded maximum size. Don't "
.. "forget to call `stopLoggingProfilingEvents()`."
)
exports.stopLoggingProfilingEvents()
return
end
local newEventLog = {}
table.insert(newEventLog, eventLog)
eventLogBuffer = newEventLog
eventLog = newEventLog
end
table.insert(eventLog, entries)
end
end
exports.startLoggingProfilingEvents = function()
eventLogSize = INITIAL_EVENT_LOG_SIZE
eventLogBuffer = {}
eventLog = eventLogBuffer
eventLogIndex = 1
end
exports.stopLoggingProfilingEvents = function()
local buffer = eventLogBuffer
eventLogSize = 0
-- ROBLOX FIXME Luau: needs local inference? Type 'nil' could not be converted into '{| |}'
eventLogBuffer = nil :: any
eventLog = nil :: any
eventLogIndex = 1
return buffer
end
exports.markTaskStart = function(task, ms: number)
if enableProfiling then
if eventLog ~= nil then
-- performance.now returns a float, representing milliseconds. When the
-- event is logged, it's coerced to an int. Convert to microseconds to
-- maintain extra degrees of precision.
logEvent({ TaskStartEvent, ms * 1000, task.id, task.priorityLevel })
end
end
end
exports.markTaskCompleted = function(task, ms: number)
if enableProfiling then
if eventLog ~= nil then
-- performance.now returns a float, representing milliseconds. When the
-- event is logged, it's coerced to an int. Convert to microseconds to
-- maintain extra degrees of precision.
logEvent({ TaskCompleteEvent, ms * 1000, task.id })
end
end
end
exports.markTaskCanceled = function(task, ms: number)
if enableProfiling then
if eventLog ~= nil then
logEvent({ TaskCancelEvent, ms * 1000, task.id })
end
end
end
exports.markTaskErrored = function(task, ms: number)
if enableProfiling then
if eventLog ~= nil then
logEvent({ TaskErrorEvent, ms * 1000, task.id })
end
end
end
exports.markTaskRun = function(task, ms: number)
if enableProfiling then
runIdCounter += 1
if eventLog ~= nil then
logEvent({ TaskRunEvent, ms * 1000, task.id, runIdCounter })
end
end
end
exports.markTaskYield = function(task, ms: number)
if enableProfiling then
if eventLog ~= nil then
logEvent({ TaskYieldEvent, ms * 1000, task.id, runIdCounter })
end
end
end
exports.markSchedulerSuspended = function(ms: number)
if enableProfiling then
mainThreadIdCounter += 1
if eventLog ~= nil then
logEvent({ SchedulerSuspendEvent, ms * 1000, mainThreadIdCounter })
end
end
end
exports.markSchedulerUnsuspended = function(ms: number)
if enableProfiling then
if eventLog ~= nil then
logEvent({ SchedulerResumeEvent, ms * 1000, mainThreadIdCounter })
end
end
end
return exports
| 412 | 0.859622 | 1 | 0.859622 | game-dev | MEDIA | 0.423426 | game-dev | 0.88203 | 1 | 0.88203 |
fuyouawa/MMORPG | 1,318 | MMORPG/Assets/QFramework/Toolkits/_CoreKit/EventKit/EventTrigger/Physics/OnTriggerExitEventTrigger.cs | /****************************************************************************
* Copyright (c) 2016 - 2022 liangxiegame UNDER MIT License
*
* https://qframework.cn
* https://github.com/liangxiegame/QFramework
* https://gitee.com/liangxiegame/QFramework
****************************************************************************/
using System;
using UnityEngine;
namespace QFramework
{
public class OnTriggerExitEventTrigger : MonoBehaviour
{
public readonly EasyEvent<Collider> OnTriggerExitEvent = new EasyEvent<Collider>();
private void OnTriggerExit(Collider collider)
{
OnTriggerExitEvent.Trigger(collider);
}
}
public static class OnTriggerExitEventTriggerExtension
{
public static IUnRegister OnTriggerExitEvent<T>(this T self, Action<Collider> onTriggerExit)
where T : Component
{
return self.GetOrAddComponent<OnTriggerExitEventTrigger>().OnTriggerExitEvent
.Register(onTriggerExit);
}
public static IUnRegister OnTriggerExitEvent(this GameObject self, Action<Collider> onTriggerExit)
{
return self.GetOrAddComponent<OnTriggerExitEventTrigger>().OnTriggerExitEvent
.Register(onTriggerExit);
}
}
} | 412 | 0.595729 | 1 | 0.595729 | game-dev | MEDIA | 0.847804 | game-dev | 0.592085 | 1 | 0.592085 |
magefree/mage | 2,750 | Mage.Sets/src/mage/cards/l/LethalExploit.java | package mage.cards.l;
import java.util.UUID;
import mage.MageObject;
import mage.MageObjectReference;
import mage.abilities.Ability;
import mage.abilities.effects.ContinuousEffectImpl;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.*;
import mage.game.Game;
import mage.game.permanent.Permanent;
import mage.target.common.TargetCreaturePermanent;
import mage.watchers.common.ControlledModifiedCreatureAsSpellCastWatcher;
/**
*
* @author weirddan455
*/
public final class LethalExploit extends CardImpl {
public LethalExploit(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.INSTANT}, "{1}{B}");
// Target creature gets -2/-2 until end of turn. It gets an additional -1/-1 until end of turn for each modified creature you controlled as you cast this spell.
this.getSpellAbility().addEffect(new LethalExploitEffect());
this.getSpellAbility().addTarget(new TargetCreaturePermanent());
this.getSpellAbility().addWatcher(new ControlledModifiedCreatureAsSpellCastWatcher());
}
private LethalExploit(final LethalExploit card) {
super(card);
}
@Override
public LethalExploit copy() {
return new LethalExploit(this);
}
}
class LethalExploitEffect extends ContinuousEffectImpl {
private int boostValue = -2;
public LethalExploitEffect() {
super(Duration.EndOfTurn, Layer.PTChangingEffects_7, SubLayer.ModifyPT_7c, Outcome.UnboostCreature);
this.staticText = "Target creature gets -2/-2 until end of turn. It gets an additional -1/-1 until end of turn for each modified creature you controlled as you cast this spell";
}
private LethalExploitEffect(final LethalExploitEffect effect) {
super(effect);
this.boostValue = effect.boostValue;
}
@Override
public LethalExploitEffect copy() {
return new LethalExploitEffect(this);
}
@Override
public void init(Ability source, Game game) {
super.init(source, game);
ControlledModifiedCreatureAsSpellCastWatcher watcher = game.getState().getWatcher(ControlledModifiedCreatureAsSpellCastWatcher.class);
MageObject sourceObject = source.getSourceObject(game);
if (watcher != null && sourceObject != null) {
boostValue -= watcher.getModifiedCreatureCount(new MageObjectReference(sourceObject, game));
}
}
@Override
public boolean apply(Game game, Ability source) {
Permanent target = game.getPermanent(source.getFirstTarget());
if (target == null) {
return false;
}
target.addPower(boostValue);
target.addToughness(boostValue);
return true;
}
}
| 412 | 0.975244 | 1 | 0.975244 | game-dev | MEDIA | 0.990781 | game-dev | 0.98806 | 1 | 0.98806 |
JellyLabScripts/FarmHelper | 7,360 | src/main/java/com/jelly/farmhelperv2/util/KeyBindUtils.java | package com.jelly.farmhelperv2.util;
import com.google.common.collect.ImmutableMap;
import net.minecraft.client.Minecraft;
import net.minecraft.client.settings.KeyBinding;
import net.minecraft.util.MathHelper;
import net.minecraft.util.Vec3;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class KeyBindUtils {
private static final Minecraft mc = Minecraft.getMinecraft();
public static final KeyBinding[] allKeys = {
mc.gameSettings.keyBindAttack,
mc.gameSettings.keyBindUseItem,
mc.gameSettings.keyBindBack,
mc.gameSettings.keyBindForward,
mc.gameSettings.keyBindLeft,
mc.gameSettings.keyBindRight,
mc.gameSettings.keyBindJump,
mc.gameSettings.keyBindSneak,
mc.gameSettings.keyBindSprint,
};
public static final KeyBinding[] allKeys2 = {
mc.gameSettings.keyBindBack,
mc.gameSettings.keyBindForward,
mc.gameSettings.keyBindLeft,
mc.gameSettings.keyBindRight,
mc.gameSettings.keyBindJump,
};
public static void rightClick() {
if (!ReflectionUtils.invoke(mc, "func_147121_ag")) {
ReflectionUtils.invoke(mc, "rightClickMouse");
}
}
public static void leftClick() {
if (!ReflectionUtils.invoke(mc, "func_147116_af")) {
ReflectionUtils.invoke(mc, "clickMouse");
}
}
public static void middleClick() {
if (!ReflectionUtils.invoke(mc, "func_147112_ai")) {
ReflectionUtils.invoke(mc, "middleClickMouse");
}
}
public static void onTick(KeyBinding key) {
if (mc.currentScreen == null) {
KeyBinding.onTick(key.getKeyCode());
}
}
public static void setKeyBindState(KeyBinding key, boolean pressed) {
if (pressed) {
if (mc.currentScreen != null && key != null) {
realSetKeyBindState(key, false);
return;
}
}
realSetKeyBindState(key, pressed);
}
private static void realSetKeyBindState(KeyBinding key, boolean pressed) {
if (key == null) return;
if (pressed) {
if (!key.isKeyDown()) {
KeyBinding.onTick(key.getKeyCode());
KeyBinding.setKeyBindState(key.getKeyCode(), true);
}
} else {
if (key.isKeyDown()) {
KeyBinding.setKeyBindState(key.getKeyCode(), false);
}
}
}
public static void stopMovement() {
stopMovement(false);
}
public static void stopMovement(boolean ignoreAttack) {
realSetKeyBindState(mc.gameSettings.keyBindForward, false);
realSetKeyBindState(mc.gameSettings.keyBindBack, false);
realSetKeyBindState(mc.gameSettings.keyBindRight, false);
realSetKeyBindState(mc.gameSettings.keyBindLeft, false);
if (!ignoreAttack) {
realSetKeyBindState(mc.gameSettings.keyBindAttack, false);
realSetKeyBindState(mc.gameSettings.keyBindUseItem, false);
}
realSetKeyBindState(mc.gameSettings.keyBindSneak, false);
realSetKeyBindState(mc.gameSettings.keyBindJump, false);
realSetKeyBindState(mc.gameSettings.keyBindSprint, false);
}
public static void holdThese(boolean withAttack, KeyBinding... keyBinding) {
releaseAllExcept(keyBinding);
for (KeyBinding key : keyBinding) {
if (key != null)
realSetKeyBindState(key, true);
}
if (withAttack) {
realSetKeyBindState(mc.gameSettings.keyBindAttack, true);
}
}
public static void holdThese(KeyBinding... keyBinding) {
releaseAllExcept(keyBinding);
for (KeyBinding key : keyBinding) {
if (key != null)
realSetKeyBindState(key, true);
}
}
public static void releaseAllExcept(KeyBinding... keyBinding) {
for (KeyBinding key : allKeys) {
if (key != null && !contains(keyBinding, key) && key.isKeyDown()) {
realSetKeyBindState(key, false);
}
}
}
public static boolean contains(KeyBinding[] keyBinding, KeyBinding key) {
for (KeyBinding keyBind : keyBinding) {
if (keyBind != null && keyBind.getKeyCode() == key.getKeyCode())
return true;
}
return false;
}
public static boolean areAllKeybindsReleased() {
for (KeyBinding key : allKeys2) {
if (key != null && key.isKeyDown())
return false;
}
return true;
}
public static KeyBinding[] getHoldingKeybinds() {
KeyBinding[] keybinds = new KeyBinding[allKeys.length];
int i = 0;
for (KeyBinding key : allKeys) {
if (key != null && key.isKeyDown()) {
keybinds[i] = key;
i++;
}
}
return keybinds;
}
private static final Map<Integer, KeyBinding> keyBindMap = ImmutableMap.of(
0, mc.gameSettings.keyBindForward,
90, mc.gameSettings.keyBindLeft,
180, mc.gameSettings.keyBindBack,
-90, mc.gameSettings.keyBindRight
);
public static List<KeyBinding> getNeededKeyPresses(Vec3 orig, Vec3 dest) {
List<KeyBinding> keys = new ArrayList<>();
double[] delta = {orig.xCoord - dest.xCoord, orig.zCoord - dest.zCoord};
float requiredAngle = (float) (MathHelper.atan2(delta[0], -delta[1]) * (180.0 / Math.PI));
float angleDifference = AngleUtils.normalizeYaw(requiredAngle - mc.thePlayer.rotationYaw) * -1;
keyBindMap.forEach((yaw, key) -> {
if (Math.abs(yaw - angleDifference) < 67.5 || Math.abs(yaw - (angleDifference + 360.0)) < 67.5) {
keys.add(key);
}
});
return keys;
}
public static List<KeyBinding> getNeededKeyPresses(float neededYaw) {
List<KeyBinding> keys = new ArrayList<>();
neededYaw = AngleUtils.normalizeYaw(neededYaw - mc.thePlayer.rotationYaw) * -1;
float finalNeededYaw = neededYaw;
keyBindMap.forEach((yaw, key) -> {
if (Math.abs(yaw - finalNeededYaw) < 67.5 || Math.abs(yaw - (finalNeededYaw + 360.0)) < 67.5) {
keys.add(key);
}
});
return keys;
}
public static List<KeyBinding> getOppositeKeys(List<KeyBinding> kbs) {
List<KeyBinding> keys = new ArrayList<>();
kbs.forEach(key -> {
switch (key.getKeyCode()) {
case 17:
keys.add(mc.gameSettings.keyBindBack);
break;
case 30:
keys.add(mc.gameSettings.keyBindRight);
break;
case 31:
keys.add(mc.gameSettings.keyBindLeft);
break;
case 32:
keys.add(mc.gameSettings.keyBindForward);
break;
}
});
return keys;
}
public static List<KeyBinding> getKeyPressesToDecelerate(Vec3 orig, Vec3 dest) {
LogUtils.sendDebug("getKeyPressesToDecelerate");
return getOppositeKeys(getNeededKeyPresses(orig, dest));
}
} | 412 | 0.716645 | 1 | 0.716645 | game-dev | MEDIA | 0.898934 | game-dev | 0.938239 | 1 | 0.938239 |
aatxe/Orpheus | 3,537 | scripts/npc/world0/2040036.js | /*
This file is part of the OdinMS Maple Story Server
Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc>
Matthias Butz <matze@odinms.de>
Jan Christian Meyer <vimes@odinms.de>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation version 3 as published by
the Free Software Foundation. You may not use, modify or distribute
this program under any other version of the GNU Affero General Public
License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
@ Author : Raz
@
@ NPC = Red Balloon
@ Map = Hidden-Street <Stage 1>
@ NPC MapId = 922010100
@ Function = LPQ - 1st Stage
@
*/
var status = 0;
var party;
var preamble;
var gaveItems;
function start() {
status = -1;
action(1, 0, 0);
}
function action(mode, type, selection) {
if (mode == -1)
cm.dispose();//ExitChat
else if (mode == 0)
cm.dispose();//No
else{ //Regular Talk
if (mode == 1)
status++;
else
status--;
var eim = cm.getPlayer().getEventInstance();
var nthtext = "1st";
if (status == 0) {
party = eim.getPlayers();
preamble = eim.getProperty("leader" + nthtext + "preamble");
gaveItems = eim.getProperty("leader" + nthtext + "gaveItems");
if (preamble == null) {
cm.sendNext("Hi. Welcome to the " + nthtext + " stage.");
eim.setProperty("leader" + nthtext + "preamble","done");
cm.dispose();
}else{
if(!isLeader()){
if(gaveItems == null){
cm.sendOk("Please tell your #bParty-Leader#k to come talk to me");
cm.dispose();
}else{
cm.sendOk("Hurry, goto the next stage, the portal is open!");
cm.dispose();
}
}else{
if(gaveItems == null){
if(cm.itemQuantity(4001022) >= 25){
cm.sendOk("Good job! you have collected all 25 #b#t4001022#'s#k");
cm.removeAll(4001022);
}else{
cm.sendOk("Sorry you don't have all 25 #b#t4001022#'s#k");
cm.dispose();
}
}else{
cm.sendOk("Hurry, goto the next stage, the portal is open!");
cm.dispose();
}
}
}
}else if (status == 1){
cm.sendOk("You may continue to the next stage!");
cm.gate();
cm.clear();
cm.givePartyExp(3000, eim.getPlayers());
eim.setProperty("1stageclear","true");
eim.setProperty("leader" + nthtext + "gaveItems","done");
cm.dispose();
}
}
}
function isLeader(){
if(cm.getParty() == null){
return false;
}else{
return cm.isLeader();
}
}
| 412 | 0.582663 | 1 | 0.582663 | game-dev | MEDIA | 0.928553 | game-dev | 0.855319 | 1 | 0.855319 |
anegostudios/vssurvivalmod | 11,508 | Systems/WorldGen/Standard/ChunkGen/7.GenPonds/GenHotSprings.cs | using ProtoBuf;
using System;
using System.Collections.Generic;
using Vintagestory.API.Common;
using Vintagestory.API.MathTools;
using Vintagestory.API.Server;
using Vintagestory.API.Util;
#nullable disable
namespace Vintagestory.ServerMods
{
[ProtoContract]
public class HotSpringGenData
{
[ProtoMember(1)]
public double horRadius;
[ProtoMember(2)]
public double verRadiusSq;
}
public class GenHotSprings : ModStdWorldGen
{
Block[] decorBlocks;
Block blocksludgygravel;
int boilingWaterBlockId;
ICoreServerAPI api;
IWorldGenBlockAccessor wgenBlockAccessor;
public override void StartServerSide(ICoreServerAPI api)
{
base.StartServerSide(api);
this.api = api;
if (TerraGenConfig.DoDecorationPass)
{
api.Event.ChunkColumnGeneration(GenChunkColumn, EnumWorldGenPass.TerrainFeatures, "standard");
api.Event.GetWorldgenBlockAccessor(OnWorldGenBlockAccessor);
api.Event.InitWorldGenerator(initWorldGen, "standard");
}
}
private void OnWorldGenBlockAccessor(IChunkProviderThread chunkProvider)
{
wgenBlockAccessor = chunkProvider.GetBlockAccessor(false);
}
public void initWorldGen()
{
LoadGlobalConfig(api);
decorBlocks = new Block[] {
api.World.GetBlock(new AssetLocation("hotspringbacteria-87deg")),
api.World.GetBlock(new AssetLocation("hotspringbacteriasmooth-74deg")),
api.World.GetBlock(new AssetLocation("hotspringbacteriasmooth-65deg")),
api.World.GetBlock(new AssetLocation("hotspringbacteriasmooth-55deg"))
};
blocksludgygravel = api.World.GetBlock(new AssetLocation("sludgygravel"));
boilingWaterBlockId = api.World.GetBlock(new AssetLocation("boilingwater-still-7")).Id;
}
private void GenChunkColumn(IChunkColumnGenerateRequest request)
{
var data = request.Chunks[0].MapChunk.GetModdata<Dictionary<Vec3i, HotSpringGenData>>("hotspringlocations");
if (data == null) return;
if (GetIntersectingStructure(request.ChunkX * chunksize + chunksize / 2, request.ChunkZ * chunksize + chunksize / 2, SkipHotSpringsgHashCode) != null) return;
int baseX = request.ChunkX * chunksize;
int baseZ = request.ChunkZ * chunksize;
foreach (var keyval in data)
{
var centerPos = keyval.Key;
var gendata = keyval.Value;
genHotspring(baseX, baseZ, centerPos, gendata);
}
}
private void genHotspring(int baseX, int baseZ, Vec3i centerPos, HotSpringGenData gendata)
{
double radiusMul = 2;
double doubleRad = radiusMul * gendata.horRadius;
int mindx = (int)GameMath.Clamp(centerPos.X - doubleRad, -chunksize, 2 * chunksize - 1);
int maxdx = (int)GameMath.Clamp(centerPos.X + doubleRad + 1, -chunksize, 2 * chunksize - 1);
int mindz = (int)GameMath.Clamp(centerPos.Z - doubleRad, -chunksize, 2 * chunksize - 1);
int maxdz = (int)GameMath.Clamp(centerPos.Z + doubleRad + 1, -chunksize, 2 * chunksize - 1);
double xdistRel, zdistRel;
double hRadiusSq = doubleRad * doubleRad;
int minSurfaceY = 99999;
int maxSurfaceY = 0;
int checks = 0;
long sum = 0;
bool lakeHere = false;
for (int lx = mindx; lx <= maxdx; lx++)
{
xdistRel = (lx - centerPos.X) * (lx - centerPos.X) / hRadiusSq;
for (int lz = mindz; lz <= maxdz; lz++)
{
zdistRel = (lz - centerPos.Z) * (lz - centerPos.Z) / hRadiusSq;
var xzdist = xdistRel + zdistRel;
if (xzdist < 1)
{
var mc = wgenBlockAccessor.GetMapChunk((baseX + lx) / chunksize, (baseZ + lz) / chunksize);
if (mc == null) return;
int surfaceY = mc.WorldGenTerrainHeightMap[GameMath.Mod(lz, chunksize) * chunksize + GameMath.Mod(lx, chunksize)];
minSurfaceY = Math.Min(minSurfaceY, surfaceY);
maxSurfaceY = Math.Max(maxSurfaceY, surfaceY);
checks++;
sum += surfaceY;
Block fluidBlock = wgenBlockAccessor.GetBlockRaw(baseX + lx, surfaceY + 1, baseZ + lz, BlockLayersAccess.Fluid);
lakeHere |= (fluidBlock.Id != 0 && fluidBlock.LiquidCode != "boilingwater"); // Suppress hot springs also in lakeice, saltwater etc.
}
}
}
int avgSurfaceY = (int)Math.Round((double)sum / checks);
int surfaceRoughness = maxSurfaceY - minSurfaceY;
// Already a lake here
if (lakeHere)
{
return;
}
// Too steep, underwater or in mountains
if (surfaceRoughness >= 4 || minSurfaceY < api.World.SeaLevel + 1 || minSurfaceY > api.WorldManager.MapSizeY * 0.88f)
{
return;
}
gendata.horRadius = Math.Min(32, gendata.horRadius);
for (int lx = mindx; lx <= maxdx; lx++)
{
xdistRel = (lx - centerPos.X) * (lx - centerPos.X) / hRadiusSq;
for (int lz = mindz; lz <= maxdz; lz++)
{
zdistRel = (lz - centerPos.Z) * (lz - centerPos.Z) / hRadiusSq;
var xzdist = xdistRel + zdistRel;
if (xzdist < 1)
{
genhotSpringColumn(baseX + lx, avgSurfaceY, baseZ + lz, xzdist);
}
}
}
}
private void genhotSpringColumn(int posx, int posy, int posz, double xzdist)
{
var mapchunk = wgenBlockAccessor.GetChunkAtBlockPos(posx, posy, posz)?.MapChunk;
if (mapchunk == null) return;
int lx = posx % chunksize;
int lz = posz % chunksize; ushort[] terrainheightmap = mapchunk.WorldGenTerrainHeightMap;
int surfaceY = terrainheightmap[lz * chunksize + lx];
xzdist += (api.World.Rand.NextDouble() / 6 - 1/12.0) * 0.5;
BlockPos pos = new BlockPos(posx, posy, posz);
var hereFluid = wgenBlockAccessor.GetBlock(pos, BlockLayersAccess.Fluid);
var heredecorBlock = wgenBlockAccessor.GetDecor(pos, new DecorBits(BlockFacing.UP));
int decorBlockIndex = (int)Math.Max(1, xzdist * 10);
var decorBlock = decorBlockIndex < decorBlocks.Length ? decorBlocks[decorBlockIndex] : null;
for (int i = 0; i < Math.Min(decorBlocks.Length-1, decorBlockIndex); i++)
{
if (decorBlocks[i] == heredecorBlock)
{
// Already has a hotter temperature decor block here
decorBlock = decorBlocks[i];
break;
}
}
if (hereFluid.Id != 0)
{
// Already boiling water here
return;
}
bool gravelPlaced = false;
// 100% sludgy gravel for radius<60%, randomized for beyond
if (api.World.Rand.NextDouble() > xzdist - 0.4)
{
prepareHotSpringBase(posx, posy, posz, surfaceY, true, decorBlock);
wgenBlockAccessor.SetBlock(blocksludgygravel.Id, pos);
gravelPlaced = true;
}
// Boiling water for <= 20% radius
if (xzdist < 0.1)
{
prepareHotSpringBase(posx, posy, posz, surfaceY, false, null);
wgenBlockAccessor.SetBlock(0, pos, BlockLayersAccess.SolidBlocks);
wgenBlockAccessor.SetBlock(boilingWaterBlockId, pos);
wgenBlockAccessor.SetDecor(decorBlocks[0], pos.DownCopy(), BlockFacing.UP);
}
// Bacerial mat otherwise
else if (decorBlock != null)
{
prepareHotSpringBase(posx, posy, posz, surfaceY, true, decorBlock);
var upblock = wgenBlockAccessor.GetBlockAbove(pos, 1, BlockLayersAccess.Solid);
var upblock2 = wgenBlockAccessor.GetBlockAbove(pos, 2, BlockLayersAccess.Solid);
if (upblock2.SideSolid[BlockFacing.UP.Index]) pos.Y += 2;
else if (upblock.SideSolid[BlockFacing.UP.Index]) pos.Y++;
wgenBlockAccessor.SetDecor(decorBlock, pos, BlockFacing.UP);
} else
{
if (xzdist < 0.8 && !gravelPlaced)
{
prepareHotSpringBase(posx, posy, posz, surfaceY, true, decorBlock);
}
}
}
private void prepareHotSpringBase(int posx, int posy, int posz, int surfaceY, bool preventLiquidSpill = true, Block sideDecorBlock = null)
{
BlockPos pos = new BlockPos(posx, posy, posz);
// Dig free up
for (int y = posy + 1; y <= surfaceY + 1; y++)
{
pos.Y = y;
var block = wgenBlockAccessor.GetBlock(pos);
var lblock = wgenBlockAccessor.GetBlock(pos, BlockLayersAccess.Fluid);
if (preventLiquidSpill && (block == blocksludgygravel || lblock.Id == boilingWaterBlockId)) break;
wgenBlockAccessor.SetBlock(0, pos, BlockLayersAccess.SolidBlocks);
wgenBlockAccessor.SetBlock(0, pos, BlockLayersAccess.Fluid);
wgenBlockAccessor.SetDecor(api.World.Blocks[0], pos, BlockFacing.UP);
for (int i = 0; i < Cardinal.ALL.Length; i++)
{
var card = Cardinal.ALL[i];
var npos = new BlockPos(pos.X + card.Normali.X, pos.Y, pos.Z + card.Normali.Z);
var nlblock = wgenBlockAccessor.GetBlock(npos, BlockLayersAccess.Fluid);
if (nlblock.Id != 0)
{
wgenBlockAccessor.SetDecor(api.World.Blocks[0], npos.DownCopy(), BlockFacing.UP);
wgenBlockAccessor.SetBlock(blocksludgygravel.Id, npos, BlockLayersAccess.SolidBlocks);
if (sideDecorBlock != null)
{
wgenBlockAccessor.SetDecor(sideDecorBlock, npos, BlockFacing.UP);
}
}
}
}
int lx = posx % chunksize;
int lz = posz % chunksize;
var mc = wgenBlockAccessor.GetMapChunk(posx / chunksize, posz / chunksize);
mc.RainHeightMap[lz * chunksize + lx] = (ushort)posy;
mc.WorldGenTerrainHeightMap[lz * chunksize + lx] = (ushort)posy;
int blockRockid = mc.TopRockIdMap[lz * chunksize + lx];
// Build base down
for (int y = posy; y >= posy - 2; y--)
{
pos.Y = y;
wgenBlockAccessor.SetDecor(api.World.Blocks[0], pos, BlockFacing.UP);
wgenBlockAccessor.SetBlock(blocksludgygravel.Id, pos);
}
}
}
}
| 412 | 0.903565 | 1 | 0.903565 | game-dev | MEDIA | 0.888821 | game-dev | 0.931242 | 1 | 0.931242 |
PlayFab/UnrealMarketplacePlugin | 14,688 | 4.27/PlayFabPlugin/PlayFab/Source/PlayFab/Classes/PlayFabEventsModels.h | //////////////////////////////////////////////////////
// Copyright (C) Microsoft. 2018. All rights reserved.
//////////////////////////////////////////////////////
#pragma once
//////////////////////////////////////////////////////////////////////////////////////////////
// Automatically generated model file for the UE4 PlayFab plugin.
// This model file contains the request and response USTRUCTS
//
// API: Events
//////////////////////////////////////////////////////////////////////////////////////////////
#include "CoreMinimal.h"
#include "Kismet/BlueprintFunctionLibrary.h"
#include "PlayFabEnums.h"
#include "PlayFabRequestCommon.h"
#include "PlayFabLoginResultCommon.h"
#include "PlayFabEventsModels.generated.h"
class UPlayFabJsonObject;
//////////////////////////////////////////////////////////////////////////
// Generated PlayFab Events API Functions
//////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////
// PlayStream
//////////////////////////////////////////////////////
///////////////////////////////////////////////////////
// PlayStream Events
//////////////////////////////////////////////////////
USTRUCT(BlueprintType)
struct PLAYFAB_API FEventsCreateTelemetryKeyRequest : public FPlayFabRequestCommon
{
GENERATED_USTRUCT_BODY()
public:
/** The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.). */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "PlayFab | Events | PlayStream Events Models")
UPlayFabJsonObject* CustomTags = nullptr;
/** The optional entity to perform this action on. Defaults to the currently logged in entity. */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "PlayFab | Events | PlayStream Events Models")
UPlayFabJsonObject* Entity = nullptr;
/** The name of the new key. Telemetry key names must be unique within the scope of the title. */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "PlayFab | Events | PlayStream Events Models")
FString KeyName;
};
USTRUCT(BlueprintType)
struct PLAYFAB_API FEventsCreateTelemetryKeyResponse : public FPlayFabResultCommon
{
GENERATED_USTRUCT_BODY()
public:
/** Details about the newly created telemetry key. */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "PlayFab | Events | PlayStream Events Models")
UPlayFabJsonObject* NewKeyDetails = nullptr;
};
USTRUCT(BlueprintType)
struct PLAYFAB_API FEventsDeleteDataConnectionRequest : public FPlayFabRequestCommon
{
GENERATED_USTRUCT_BODY()
public:
/** The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.). */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "PlayFab | Events | PlayStream Events Models")
UPlayFabJsonObject* CustomTags = nullptr;
/** The name of the data connection to delete. */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "PlayFab | Events | PlayStream Events Models")
FString Name;
};
USTRUCT(BlueprintType)
struct PLAYFAB_API FEventsDeleteDataConnectionResponse : public FPlayFabResultCommon
{
GENERATED_USTRUCT_BODY()
public:
/** Indicates whether or not the connection was deleted as part of the request. */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "PlayFab | Events | PlayStream Events Models")
bool WasDeleted = false;
};
USTRUCT(BlueprintType)
struct PLAYFAB_API FEventsDeleteTelemetryKeyRequest : public FPlayFabRequestCommon
{
GENERATED_USTRUCT_BODY()
public:
/** The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.). */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "PlayFab | Events | PlayStream Events Models")
UPlayFabJsonObject* CustomTags = nullptr;
/** The optional entity to perform this action on. Defaults to the currently logged in entity. */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "PlayFab | Events | PlayStream Events Models")
UPlayFabJsonObject* Entity = nullptr;
/** The name of the key to delete. */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "PlayFab | Events | PlayStream Events Models")
FString KeyName;
};
USTRUCT(BlueprintType)
struct PLAYFAB_API FEventsDeleteTelemetryKeyResponse : public FPlayFabResultCommon
{
GENERATED_USTRUCT_BODY()
public:
/** Indicates whether or not the key was deleted. If false, no key with that name existed. */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "PlayFab | Events | PlayStream Events Models")
bool WasKeyDeleted = false;
};
USTRUCT(BlueprintType)
struct PLAYFAB_API FEventsGetDataConnectionRequest : public FPlayFabRequestCommon
{
GENERATED_USTRUCT_BODY()
public:
/** The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.). */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "PlayFab | Events | PlayStream Events Models")
UPlayFabJsonObject* CustomTags = nullptr;
/** The name of the data connection to retrieve. */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "PlayFab | Events | PlayStream Events Models")
FString Name;
};
USTRUCT(BlueprintType)
struct PLAYFAB_API FEventsGetDataConnectionResponse : public FPlayFabResultCommon
{
GENERATED_USTRUCT_BODY()
public:
/** The details of the queried Data Connection. */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "PlayFab | Events | PlayStream Events Models")
UPlayFabJsonObject* DataConnection = nullptr;
};
USTRUCT(BlueprintType)
struct PLAYFAB_API FEventsGetTelemetryKeyRequest : public FPlayFabRequestCommon
{
GENERATED_USTRUCT_BODY()
public:
/** The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.). */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "PlayFab | Events | PlayStream Events Models")
UPlayFabJsonObject* CustomTags = nullptr;
/** The optional entity to perform this action on. Defaults to the currently logged in entity. */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "PlayFab | Events | PlayStream Events Models")
UPlayFabJsonObject* Entity = nullptr;
/** The name of the key to retrieve. */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "PlayFab | Events | PlayStream Events Models")
FString KeyName;
};
USTRUCT(BlueprintType)
struct PLAYFAB_API FEventsGetTelemetryKeyResponse : public FPlayFabResultCommon
{
GENERATED_USTRUCT_BODY()
public:
/** Details about the requested telemetry key. */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "PlayFab | Events | PlayStream Events Models")
UPlayFabJsonObject* KeyDetails = nullptr;
};
USTRUCT(BlueprintType)
struct PLAYFAB_API FEventsListDataConnectionsRequest : public FPlayFabRequestCommon
{
GENERATED_USTRUCT_BODY()
public:
/** The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.). */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "PlayFab | Events | PlayStream Events Models")
UPlayFabJsonObject* CustomTags = nullptr;
};
USTRUCT(BlueprintType)
struct PLAYFAB_API FEventsListDataConnectionsResponse : public FPlayFabResultCommon
{
GENERATED_USTRUCT_BODY()
public:
/** The list of existing Data Connections. */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "PlayFab | Events | PlayStream Events Models")
TArray<UPlayFabJsonObject*> DataConnections;
};
USTRUCT(BlueprintType)
struct PLAYFAB_API FEventsListTelemetryKeysRequest : public FPlayFabRequestCommon
{
GENERATED_USTRUCT_BODY()
public:
/** The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.). */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "PlayFab | Events | PlayStream Events Models")
UPlayFabJsonObject* CustomTags = nullptr;
/** The optional entity to perform this action on. Defaults to the currently logged in entity. */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "PlayFab | Events | PlayStream Events Models")
UPlayFabJsonObject* Entity = nullptr;
};
USTRUCT(BlueprintType)
struct PLAYFAB_API FEventsListTelemetryKeysResponse : public FPlayFabResultCommon
{
GENERATED_USTRUCT_BODY()
public:
/** The telemetry keys configured for the title. */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "PlayFab | Events | PlayStream Events Models")
TArray<UPlayFabJsonObject*> KeyDetails;
};
USTRUCT(BlueprintType)
struct PLAYFAB_API FEventsSetDataConnectionRequest : public FPlayFabRequestCommon
{
GENERATED_USTRUCT_BODY()
public:
/** Settings of the data connection. */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "PlayFab | Events | PlayStream Events Models")
UPlayFabJsonObject* ConnectionSettings = nullptr;
/** The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.). */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "PlayFab | Events | PlayStream Events Models")
UPlayFabJsonObject* CustomTags = nullptr;
/** Whether or not the connection is currently active. */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "PlayFab | Events | PlayStream Events Models")
bool IsActive = false;
/** The name of the data connection to update or create. */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "PlayFab | Events | PlayStream Events Models")
FString Name;
/** The type of data connection. */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "PlayFab | Events | PlayStream Events Models")
EDataConnectionType Type = StaticCast<EDataConnectionType>(0);
};
USTRUCT(BlueprintType)
struct PLAYFAB_API FEventsSetDataConnectionResponse : public FPlayFabResultCommon
{
GENERATED_USTRUCT_BODY()
public:
/** The details of the Data Connection to be created or updated. */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "PlayFab | Events | PlayStream Events Models")
UPlayFabJsonObject* DataConnection = nullptr;
};
USTRUCT(BlueprintType)
struct PLAYFAB_API FEventsSetDataConnectionActiveRequest : public FPlayFabRequestCommon
{
GENERATED_USTRUCT_BODY()
public:
/** Whether to set the data connection to active (true) or deactivated (false). */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "PlayFab | Events | PlayStream Events Models")
bool Active = false;
/** The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.). */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "PlayFab | Events | PlayStream Events Models")
UPlayFabJsonObject* CustomTags = nullptr;
/** The name of the data connection to update. */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "PlayFab | Events | PlayStream Events Models")
FString Name;
};
USTRUCT(BlueprintType)
struct PLAYFAB_API FEventsSetDataConnectionActiveResponse : public FPlayFabResultCommon
{
GENERATED_USTRUCT_BODY()
public:
/** The most current details about the data connection that was to be updated. */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "PlayFab | Events | PlayStream Events Models")
UPlayFabJsonObject* DataConnection = nullptr;
/**
* Indicates whether or not the data connection was updated. If false, the data connection was already in the desired
* state.
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "PlayFab | Events | PlayStream Events Models")
bool WasUpdated = false;
};
USTRUCT(BlueprintType)
struct PLAYFAB_API FEventsSetTelemetryKeyActiveRequest : public FPlayFabRequestCommon
{
GENERATED_USTRUCT_BODY()
public:
/** Whether to set the key to active (true) or deactivated (false). */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "PlayFab | Events | PlayStream Events Models")
bool Active = false;
/** The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.). */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "PlayFab | Events | PlayStream Events Models")
UPlayFabJsonObject* CustomTags = nullptr;
/** The optional entity to perform this action on. Defaults to the currently logged in entity. */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "PlayFab | Events | PlayStream Events Models")
UPlayFabJsonObject* Entity = nullptr;
/** The name of the key to update. */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "PlayFab | Events | PlayStream Events Models")
FString KeyName;
};
USTRUCT(BlueprintType)
struct PLAYFAB_API FEventsSetTelemetryKeyActiveResponse : public FPlayFabResultCommon
{
GENERATED_USTRUCT_BODY()
public:
/** The most current details about the telemetry key that was to be updated. */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "PlayFab | Events | PlayStream Events Models")
UPlayFabJsonObject* KeyDetails = nullptr;
/** Indicates whether or not the key was updated. If false, the key was already in the desired state. */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "PlayFab | Events | PlayStream Events Models")
bool WasKeyUpdated = false;
};
USTRUCT(BlueprintType)
struct PLAYFAB_API FEventsWriteEventsRequest : public FPlayFabRequestCommon
{
GENERATED_USTRUCT_BODY()
public:
/** The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.). */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "PlayFab | Events | PlayStream Events Models")
UPlayFabJsonObject* CustomTags = nullptr;
/** The collection of events to write. Up to 200 events can be written per request. */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "PlayFab | Events | PlayStream Events Models")
TArray<UPlayFabJsonObject*> Events;
};
USTRUCT(BlueprintType)
struct PLAYFAB_API FEventsWriteEventsResponse : public FPlayFabResultCommon
{
GENERATED_USTRUCT_BODY()
public:
/**
* The unique identifiers assigned by the server to the events, in the same order as the events in the request. Only
* returned if FlushToPlayStream option is true.
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "PlayFab | Events | PlayStream Events Models")
FString AssignedEventIds;
};
| 412 | 0.83567 | 1 | 0.83567 | game-dev | MEDIA | 0.364351 | game-dev | 0.545744 | 1 | 0.545744 |
pascalabcnet/pascalabcnet | 3,022 | InstallerSamples/Algorithms/MazeGen.pas | // Программа генерации случайных лабиринтов
uses GraphABC;
const
szw = 70; // размер лабиринта
szh = 50;
cellsz = 10; // размер ячейки
type
point = record
x,y: integer;
end;
var
maze: array [0..szw-1] of array [0..szh-1] of integer;
todo: array [0..szw*szh-1] of point;
todonum: integer;
const
dx: array [0..3] of integer = (0, 0, -1, 1);
dy: array [0..3] of integer = (-1, 1, 0, 0);
procedure Init;
begin
for var x:=0 to szw-1 do
for var y:=0 to szh-1 do
if (x=0) or (x=szw-1) or (y=0) or (y=szh-1) then
maze[x][y]:=32
else maze[x][y]:=63;
var x := Random(szw-2)+1;
var y := Random(szh-2)+1;
// Пометить клетку как принадлежащую лабиринту
maze[x][y]:= maze[x][y] and not 48;
// Занести в список todo все ближайшие необработанные клетки
for var d:=0 to 3 do
if (maze[x + dx[d]][y + dy[d]] and 16) <> 0 then
begin
todo[todonum].x := x + dx[d];
todo[todonum].y := y + dy[d];
Inc(todonum);
maze[x + dx[d]][y + dy[d]] := maze[x + dx[d]][y + dy[d]] and not 16;
end;
// Пока не обработаны все клетки
while todonum > 0 do
begin
// Выбрать из списка todo произвольную клетку
var n := Random(todonum);
x := todo[n].x;
y := todo[n].y;
// Удалить из списка обработанную клетку
Dec(todonum);
todo[n]:= todo[todonum];
// Выбрать направление, которое ведет к лабиринту
var dd: integer;
repeat
dd:=Random (4);
until not ((maze[x + dx[dd]][y + dy[dd]] and 32) <> 0);
// Присоединить выбранную клетку к лабиринту
maze[x][y] := maze[x][y] and not ((1 shl dd) or 32);
maze[x + dx[dd]][y + dy[dd]] := maze[x + dx[dd]][y + dy[dd]] and not (1 shl (dd xor 1));
// Занести в список todo все ближайшие необработанные клетки
for var d:=0 to 3 do
if (maze[x + dx[d]][y + dy[d]] and 16) <> 0 then
begin
todo[todonum].x := x + dx[d];
todo[todonum].y := y + dy[d];
Inc(todonum);
maze[x + dx[d]][y + dy[d]] := maze[x + dx[d]][y + dy[d]] and not 16;
end;
end;
maze[1][1] := maze[1][1] and not 1; // начало лабиринта - в левом верхнем углу
maze[szw-2][szh-2] := maze[szw-2][szh-2] and not 2; // конец лабиринта - в правом нижнем углу
end;
procedure Draw;
begin
for var x:=1 to szw-2 do
for var y:=1 to szh-2 do
begin
if ((maze[x][y] and 1) <> 0) then // верхняя стена
Line(x * cellsz, y * cellsz, x * cellsz + cellsz , y * cellsz);
if ((maze[x][y] and 2) <> 0) then // нижняя стена
Line(x * cellsz, y * cellsz + cellsz, x * cellsz + cellsz , y * cellsz + cellsz);
if ((maze[x][y] and 4) <> 0) then // левая стена
Line(x * cellsz, y * cellsz, x * cellsz, y * cellsz + cellsz );
if ((maze[x][y] and 8) <> 0) then // правая стена
Line(x * cellsz + cellsz, y * cellsz, x * cellsz + cellsz, y * cellsz + cellsz);
end;
end;
begin
Window.Title := 'Генерация лабиринта';
SetWindowSize(szw*cellsz,szh*cellsz);
Init;
Draw;
end.
| 412 | 0.805512 | 1 | 0.805512 | game-dev | MEDIA | 0.855693 | game-dev | 0.855948 | 1 | 0.855948 |
sel-project/selery | 10,469 | source/selery/lang.d | /*
* Copyright (c) 2017-2019 sel-project
*
* 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.
*
*/
/**
* Copyright: Copyright (c) 2017-2019 sel-project
* License: MIT
* Authors: Kripth
* Source: $(HTTP github.com/sel-project/selery/source/selery/lang.d, selery/lang.d)
*/
module selery.lang;
import std.algorithm : canFind;
import std.array : Appender;
import std.conv : to, ConvException;
import std.file : exists, read;
import std.json : parseJSON;
import std.path : dirSeparator;
import std.string : toUpper, toLower, endsWith, split, indexOf, strip;
import selery.config : Files;
import selery.plugin : Plugin;
deprecated("Use LanguageManager instead") alias Lang = LanguageManager;
/**
* Stores translatable strings in various languages and provides
* methods to translate them with the provided arguments.
*/
class LanguageManager {
private const Files files;
public immutable string[] acceptedLanguages;
public immutable string language;
private string[string] defaults;
private TranslationManager[string][string] messages;
public string[string][string] raw; // used for web admin
public this(inout Files files, string language) {
this.files = files;
string[] accepted;
bool languageAccepted = false;
foreach(lang, countries; parseJSON(cast(string)files.readAsset("lang/languages.json")).object) {
foreach(i, country; countries.array) {
immutable code = lang ~ "_" ~ country.str.toUpper;
accepted ~= code;
if(i == 0) this.defaults[lang] = code;
}
}
this.acceptedLanguages = accepted.idup;
this.language = this.best(language);
}
public inout string best(string language) {
language = language.toLower;
// return full language matching full language (en_GB : en_GB)
foreach(lang ; this.acceptedLanguages) {
if(language == lang.toLower) return lang;
}
// return full language matching language only (en : en_GB)
if(language.length >= 2) {
auto d = language[0..2] in this.defaults;
if(d) return *d;
}
// return server's language
return this.language;
}
/**
* Loads languages in assets/lang/system and assets/lang/messages.
* Throws: RangeError if one of the given languages is not supported by the software.
*/
public inout void load() {
foreach(type ; ["system", "messages"]) {
foreach(lang ; acceptedLanguages) {
immutable file = "lang/" ~ type ~ "/" ~ lang ~ ".lang";
if(this.files.hasAsset(file)) this.add(lang, this.parseFile(cast(string)this.files.readAsset(file)));
}
}
}
/**
* Loads languages from plugin's assets files, located in plugins/$plugin/assets/lang.
*/
public inout string[string][string] loadPlugin(Plugin plugin) {
immutable folder = "lang" ~ dirSeparator;
string[string][string] ret;
bool loadImpl(string lang, string file) {
if(this.files.hasPluginAsset(plugin, file)) {
ret[lang] = this.parseFile(cast(string)this.files.readPluginAsset(plugin, file));
return true;
} else {
return false;
}
}
foreach(lang ; acceptedLanguages) {
if(!loadImpl(lang, folder ~ lang ~ ".lang")) loadImpl(lang, folder ~ lang[0..2] ~ ".lang");
}
return ret;
}
private inout string[string] parseFile(string data) {
string[string] ret;
foreach(string line ; split(data, "\n")) {
immutable equals = line.indexOf("=");
if(equals != -1) {
immutable message = line[0..equals].strip;
immutable text = line[equals+1..$].strip;
if(message.length && message[0] != '#') ret[message] = text;
}
}
return ret;
}
/**
* Adds messages using the given associative array of message:text.
*/
public void add(string language, string[string] messages) {
foreach(message, text; messages) {
this.raw[language][message] = text;
Element[] elements;
string next;
ptrdiff_t index = -1;
foreach(i, c; text) {
if(index >= 0) {
if(c == '}') {
try {
auto num = to!size_t(text[index+1..i]);
if(next.length) {
elements ~= Element(next);
next.length = 0;
}
elements ~= Element(num);
} catch(ConvException) {
next ~= text[index..i+1];
}
index = -1;
}
} else {
if(c == '{') {
index = i;
} else {
next ~= c;
}
}
}
if(index >= 0) next ~= text[index..$];
if(next.length) elements ~= Element(next);
if(elements.length) this.messages[language][message] = TranslationManager(elements);
}
}
/// ditto
public const void add(string language, string[string] messages) {
(cast()this).add(language, messages);
}
/**
* Translates a message in the given language with the given parameters.
* If the language is omitted the message is translated using the default
* language.
* Returns: the translated message if the language and the message exist or the message if not
*/
public inout string translate(inout string message, inout(string)[] params, string language) {
auto lang = language in this.messages;
if(lang) {
auto translatable = message in *lang;
if(translatable) {
return (*translatable).build(params);
}
}
return message;
}
/// ditto
public inout string translate(string message, string lang) {
return this.translate(message, [], language);
}
/// ditto
public inout string translate(string message, string[] params=[]) {
return this.translate(message, params, this.language);
}
/// ditto
public inout string translate(inout Translation translation, string language) {
return this.translate(translation.translatable.default_, translation.parameters, language);
}
/// ditto
public inout string translate(inout Translation translation) {
return this.translate(translation, this.language);
}
private void loadImpl(string language, void[] data) {
foreach(string line ; split(cast(string)data, "\n")) {
immutable equals = line.indexOf("=");
if(equals != -1) {
immutable message = line[0..equals].strip;
immutable text = line[equals+1..$].strip;
if(message.length) {
this.raw[language][message] = text;
immutable comment = text.indexOf("##");
Element[] elements;
string next;
ptrdiff_t index = -1;
foreach(i, c; text[0..comment==-1?$:comment]) {
if(index >= 0) {
if(c == '}') {
try {
auto num = to!size_t(text[index+1..i]);
if(next.length) {
elements ~= Element(next);
next.length = 0;
}
elements ~= Element(num);
} catch(ConvException) {
next ~= text[index..i+1];
}
index = -1;
}
} else {
if(c == '{') {
index = i;
} else {
next ~= c;
}
}
}
if(index >= 0) next ~= text[index..$];
if(next.length) elements ~= Element(next);
if(elements.length) this.messages[language][message] = TranslationManager(elements);
}
}
}
}
private static struct TranslationManager {
Element[] elements;
public inout string build(inout(string)[] args) {
Appender!string ret;
foreach(element ; this.elements) {
if(element.isString) {
ret.put(element.data);
} else if(element.index < args.length) {
ret.put(args[element.index]);
} else {
ret.put("{");
ret.put(to!string(element.index));
ret.put("}");
}
}
return ret.data;
}
}
private static struct Element {
union {
string data;
size_t index;
}
public bool isString;
public this(string data) {
this.data = data;
this.isString = true;
}
public this(size_t index) {
this.index = index;
this.isString = false;
}
}
}
struct Translation {
public Translatable translatable;
public string[] parameters;
public this(E...)(Translatable translatable, E parameters) {
this.translatable = translatable;
foreach(param ; parameters) {
static if(is(typeof(param) : string) || is(typeof(param) == string[])) this.parameters ~= param;
else this.parameters ~= param.to!string;
}
}
public this(E...)(string default_, E parameters) {
this(Translatable.all(default_), parameters);
}
public static Translation server(E...)(string default_, E parameters) {
return Translation(Translatable(default_), parameters);
}
}
/**
* Translation container for a multi-platform translation.
* The `default_` translation should never be empty and it should be a string that can be
* loaded from a language file.
* The `minecraft` and `bedrock` strings can either be a client-side translated message
* or empty. In that case the `default_` string is translated server-side and sent
* to the client.
* Example:
* ---
* // server-side string
* Translatable("example.test");
*
* // server-side for minecraft and client-side for bedrock
* Translatable("description.help", "", "commands.help.description");
* ---
*/
struct Translatable {
//TODO move somewhere else
enum MULTIPLAYER_JOINED = all("multiplayer.player.joined");
enum MULTIPLAYER_LEFT = all("multiplayer.player.left");
public static nothrow @safe @nogc Translatable all(inout string translation) {
return Translatable(translation, translation, translation);
}
public static nothrow @safe @nogc Translatable fromJava(inout string translation) {
return Translatable(translation, translation, "");
}
public static nothrow @safe @nogc Translatable fromBedrock(inout string translation) {
return Translatable(translation, "", translation);
}
/// Values.
public string default_, java, bedrock;
} | 412 | 0.882055 | 1 | 0.882055 | game-dev | MEDIA | 0.205769 | game-dev | 0.708118 | 1 | 0.708118 |
QianMo/X-PostProcessing-Library | 1,556 | Assets/X-PostProcessing/Effects/GlitchRGBSplitV5/Editor/GlitchRGBSplitV5Editor.cs |
//----------------------------------------------------------------------------------------------------------
// X-PostProcessing Library
// https://github.com/QianMo/X-PostProcessing-Library
// Copyright (C) 2020 QianMo. All rights reserved.
// Licensed under the MIT License
// You may not use this file except in compliance with the License.You may obtain a copy of the License at
// http://opensource.org/licenses/MIT
//----------------------------------------------------------------------------------------------------------
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using UnityEditor.Rendering.PostProcessing;
using UnityEngine.Rendering.PostProcessing;
namespace XPostProcessing
{
[PostProcessEditor(typeof(GlitchRGBSplitV5))]
public sealed class GlitchRGBSplitV5Editor : PostProcessEffectEditor<GlitchRGBSplitV5>
{
SerializedParameterOverride Amplitude;
SerializedParameterOverride Speed;
public override void OnEnable()
{
Amplitude = FindParameterOverride(x => x.Amplitude);
Speed = FindParameterOverride(x => x.Speed);
}
public override string GetDisplayTitle()
{
return XPostProcessingEditorUtility.DISPLAY_TITLE_PREFIX + base.GetDisplayTitle();
}
public override void OnInspectorGUI()
{
EditorUtilities.DrawHeaderLabel("Core Property");
PropertyField(Amplitude);
PropertyField(Speed);
}
}
}
| 412 | 0.730842 | 1 | 0.730842 | game-dev | MEDIA | 0.642195 | game-dev | 0.718456 | 1 | 0.718456 |
eli-b/mapf | 18,771 | Plan.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics;
using System.Text;
using ExtensionMethods;
namespace mapf;
/// <summary>
/// Represents a plan for a set of agents.
/// </summary>
public class Plan
{
private LinkedList<List<Move>> locationsAtTimes;
/// <summary>
/// Reconstructs the plan by goind backwards from the goal.
/// </summary>
/// <param name="goalState">The goal state from which to start going backwards</param>
public Plan(WorldState goalState)
{
WorldState currentNode = goalState;
this.locationsAtTimes = new LinkedList<List<Move>>(); // TODO: Initialize list with #agents
while (currentNode != null)
{
List<Move> agentMoves = currentNode.GetAgentsMoves();
this.locationsAtTimes.AddFirst(agentMoves);
currentNode = currentNode.prevStep;
}
}
/// <summary>
/// Reconstructs the plan by going backwards from the goal.
/// </summary>
/// <param name="goalState">The goal state from which to start going backwards</param>
public Plan(AgentState goalState)
{
AgentState currentNode = goalState;
this.locationsAtTimes = new LinkedList<List<Move>>(); // TODO: Initialize list with #agents
while (currentNode != null)
{
var l = new List<Move>();
l.Add(currentNode.GetMove());
this.locationsAtTimes.AddFirst(l);
currentNode = currentNode.prev;
}
}
/// <summary>
/// Assumes all routes are of the same length.
/// </summary>
/// <param name="routePerAgent"></param>
public Plan(LinkedList<Move>[] routePerAgent)
{
this.locationsAtTimes = new LinkedList<List<Move>>();
for (int i = 0; i < routePerAgent[0].Count; i++)
{
locationsAtTimes.AddLast(new List<Move>());
}
foreach (LinkedList<Move> agentRoute in routePerAgent)
{
LinkedListNode<List<Move>> locationsAtTime = this.locationsAtTimes.First;
foreach (Move agentLocation in agentRoute)
{
locationsAtTime.Value.Add(agentLocation);
locationsAtTime = locationsAtTime.Next;
}
}
}
/// <summary>
/// Generates a big plan from a collection of smaller plans.
/// </summary>
/// <param name="subplans"></param>
public Plan(IEnumerable<Plan> subplans)
{
int maxSize = subplans.Max(plan => plan.GetSize());
this.locationsAtTimes = new LinkedList<List<Move>>();
for (int time = 0; time < maxSize; time++)
{
var allMoves = new List<Move>();
foreach (Plan plan in subplans)
foreach (Move move in plan.GetLocationsAt(time))
allMoves.Add(move);
this.locationsAtTimes.AddLast(allMoves);
}
}
public Plan(IEnumerable<SinglePlan> subplans) // FIXME: Almost fully duplicates the previous method
{
int maxSize = subplans.Max(plan => plan.GetSize());
this.locationsAtTimes = new LinkedList<List<Move>>();
for (int time = 0; time < maxSize; time++)
{
var allMoves = new List<Move>();
foreach (SinglePlan plan in subplans)
{
allMoves.Add(plan.GetLocationAt(time));
}
this.locationsAtTimes.AddLast(allMoves);
}
}
/// <summary>
/// Medium-depth copy constructor - uses same Move objects.
/// </summary>
/// <param name="cpy"></param>
public Plan(Plan cpy)
{
this.locationsAtTimes = new LinkedList<List<Move>>();
foreach (List<Move> cpyStep in cpy.locationsAtTimes)
{
this.locationsAtTimes.AddLast(cpyStep.ToList<Move>());
}
}
/// <summary>
/// Add actions of other plan after actions of plan.
/// If this plan ends where the other starts,
/// the first timestep of the other plan is skipped.
/// </summary>
/// <param name="other"></param>
public void ContinueWith(Plan other)
{
bool first = true;
foreach (List<Move> newLocationsAtTime in other.locationsAtTimes)
{
if (first)
{
first = false;
if (newLocationsAtTime.SequenceEqual<Move>(this.locationsAtTimes.Last.Value))
continue;
else
Trace.Assert(false, "Continuing a plan doesn't start from the same state");
}
this.locationsAtTimes.AddLast(newLocationsAtTime);
}
}
public void Check(ProblemInstance problem)
{
SinglePlan[] singles = new SinglePlan[this.locationsAtTimes.First().Count];
for (int i = 0; i < singles.Length; i++)
{
singles[i] = new SinglePlan(this, i, problem.agents[i].agent.agentNum);
foreach ((int time, var move) in singles[i].locationAtTimes.Enumerate())
Trace.Assert(problem.IsValid(move), $"Plan of agent {i} uses an invalid location {move} at time {time}!");
}
// Check in every time step that the plans do not collide
for (int time = 1; time < this.locationsAtTimes.Count; time++) // Assuming no conflicts exist in time zero.
{
// Check all pairs of agents for a collision at the given time step
foreach ((int i1, var plan1) in singles.Enumerate())
{
foreach ((int i2, var plan2) in singles.Enumerate())
{
if (i1 < i2)
Trace.Assert(plan1.IsColliding(time, plan2) == false, $"Plans of agents {i1} and {i2} collide at time {time}!");
}
}
}
}
// TODO: Add GetCost and GetMakespan methods!
/// <summary>
/// Returns the location of the agents at a given time.
/// If the requested time is after the last step of the plan,
/// the agents are assumed to stay at their final location.
/// </summary>
/// <param name="time">The requested time</param>
/// <returns>A list of Moves that are the locations of the different agents at the requested time</returns>
public List<Move> GetLocationsAt(int time)
{
if (time < this.locationsAtTimes.Count)
return this.locationsAtTimes.ElementAt(time); // FIXME: Expensive!
else
{
var toCopy = this.locationsAtTimes.Last.Value;
var atRest = toCopy.ToList();
for (int i = 0; i < atRest.Count; i++)
{
atRest[i] = new Move(atRest[i].x, atRest[i].y, Move.Direction.Wait);
}
return atRest;
}
}
public LinkedList<List<Move>> GetLocations()
{
return this.locationsAtTimes;
}
/// <summary>
/// NOT the cost, which:
/// A) could depend on steps taken before solving started,
/// B) is 1 smaller than the size (a plan that starts at the goal costs zero)
/// C) under sum-of-costs, is the sum of the agent costs
/// Useful only for iteration over the relevant part of the plan.
/// </summary>
/// <returns>The size of the plan, assuming is doesn't end with steps where all agents WAIT at the goal (which should be discounted).</returns>
public int GetSize()
{
return this.locationsAtTimes.Count;
}
/// <summary>
/// Check if this plan collides with another plan at a given time
/// </summary>
/// <param name="time">The time at which to check if the collision occured</param>
/// <param name="otherPlan">The plan to check against</param>
public bool IsColliding(int time, Plan otherPlan)
{
List<Move> thisLocations = this.GetLocationsAt(time);
List<Move> otherLocations = otherPlan.GetLocationsAt(time);
// TODO: Think of a better implementation of this
foreach (Move aMove in thisLocations)
foreach (Move bMove in otherLocations)
if (aMove.IsColliding(bMove) == true)
return true;
return false;
}
/// <summary>
/// Print plan if it would fit nicely in the console, otherwise print why it wasn't printed
/// </summary>
public void PrintPlanIfShort()
{
var planSize = GetSize();
var numAgents = this.locationsAtTimes.First.Value.Count;
if (planSize < 200 && numAgents < 30)
PrintPlan();
else if (planSize >= 200)
Console.WriteLine($"Plan is too long to print ({planSize} steps).");
else
Console.WriteLine($"Plan is too wide to print ({numAgents} agents).");
}
/// <summary>
/// Prints the plan to the Console.
/// This is used for debugging purposes.
/// </summary>
public void PrintPlan()
{
foreach (List<Move> locationsAtTime in this.locationsAtTimes)
{
Console.Write("|");
foreach (Move aMove in locationsAtTime)
{
Console.Write(aMove.ToString() + "|");
}
Console.WriteLine("");
}
}
public override string ToString()
{
var s = new StringBuilder();
foreach (List<Move> locationsAtTime in this.locationsAtTimes)
{
s.Append($"|{String.Join("|", locationsAtTime)}|\n");
}
return s.ToString();
}
public HashSet<TimedMove> AddPlanToHashSet(HashSet<TimedMove> addTo, int until)
{
for (int i = 1; i < until; i++) // i = 1 because we assume start positions don't overlap
{
List<Move> step = this.GetLocationsAt(i);
foreach (Move move in step)
{
addTo.Add(new TimedMove(move,i));
}
}
return addTo;
}
}
public class SinglePlan
{
public List<Move> locationAtTimes { get; private set; }
public int agentNum;
/// <summary>
/// Not used
/// </summary>
/// <param name="goalState"></param>
/// <param name="agentIndex"></param>
public SinglePlan(WorldState goalState, int agentIndex)
{
this.agentNum = goalState.allAgentsState[agentIndex].agent.agentNum;
WorldState currentNode = goalState;
LinkedList<Move> locations = new LinkedList<Move>();
while (currentNode != null)
{
locations.AddFirst(currentNode.GetSingleAgentMove(agentIndex));
currentNode = currentNode.prevStep;
}
this.locationAtTimes = locations.ToList<Move>();
}
/// <summary>
/// Get a SinglePlan from a Plan
/// </summary>
/// <param name="plan"></param>
/// <param name="agentIndex">In this plan</param>
/// <param name="agentNum">To put in the returned SinglePlan</param>
public SinglePlan(Plan plan, int agentIndex, int agentNum)
{
this.agentNum = agentNum;
this.locationAtTimes = new List<Move>();
foreach (List<Move> movesAtTimestep in plan.GetLocations())
{
this.locationAtTimes.Add(movesAtTimestep[agentIndex]);
}
}
public SinglePlan(AgentState goalState)
{
this.agentNum = goalState.agent.agentNum;
AgentState currentNode = goalState;
LinkedList<Move> locations = new LinkedList<Move>();
while (currentNode != null)
{
locations.AddFirst(currentNode.GetMove());
currentNode = currentNode.prev;
}
this.locationAtTimes = locations.ToList<Move>();
}
public SinglePlan(LinkedList<Move> route, int agentNum)
{
this.agentNum = agentNum;
locationAtTimes = route.ToList<Move>();
}
public SinglePlan(SinglePlan cpy)
{
this.locationAtTimes = cpy.locationAtTimes.ToList<Move>(); // Behavior change: used to do a deep copy, with cloned moves.
this.agentNum = cpy.agentNum;
}
/// <summary>
/// TODO: Get rid of the else
/// </summary>
/// <param name="time"></param>
/// <returns></returns>
public Move GetLocationAt(int time)
{
if (time < this.locationAtTimes.Count)
return this.locationAtTimes[time];
else
{
var rest = new TimedMove(this.locationAtTimes[this.locationAtTimes.Count - 1], time);
rest.direction = Move.Direction.Wait;
return rest;
}
}
public override bool Equals(object obj)
{
if (obj == null)
return false;
SinglePlan other = (SinglePlan)obj;
return this.agentNum == other.agentNum && this.locationAtTimes.SequenceEqual<Move>(other.locationAtTimes);
}
public override int GetHashCode()
{
int ret;
unchecked // wrap-around is fine in hash functions
{
ret = Constants.PRIMES_FOR_HASHING[0] * this.agentNum.GetHashCode();
// Hash the contents and order of locationsAtTimes
int i = 0;
foreach (var move in this.locationAtTimes)
{
ret += Constants.PRIMES_FOR_HASHING[1] * i + Constants.PRIMES_FOR_HASHING[2] * move.GetHashCode();
i++;
}
}
return ret;
}
/// <summary>
/// Add actions of other plan after actions of plan.
/// If this plan ends where the other starts,
/// the first timestep of the other plan is skipped
/// </summary>
/// <param name="other"></param>
public void ContinueWith(SinglePlan other)
{
bool first = true;
foreach (Move newLocationAtTime in other.locationAtTimes)
{
if (first)
{
first = false;
if (this.locationAtTimes[this.locationAtTimes.Count - 1].Equals(newLocationAtTime))
continue;
else
Trace.Assert(false, "Continuing a plan doesn't start from the same state");
}
this.locationAtTimes.Add(newLocationAtTime);
}
}
/// <summary>
/// NOT the cost, which:
/// A) could depend on steps taken before solving started,
/// B) is 1 smaller than the size (a plan that starts at the goal costs zero)
/// Useful only for iteration over the relevant part of the plan.
/// </summary>
/// <returns>The size of the plan, excluding WAITs at the goal</returns>
public int GetSize()
{
int lastNonWaitIndex = this.locationAtTimes.Count - 1;
while (lastNonWaitIndex != 0 && locationAtTimes[lastNonWaitIndex].direction == Move.Direction.Wait)
lastNonWaitIndex--;
return lastNonWaitIndex + 1;
}
/// <summary>
/// TODO: Find all "GetSize() - 1" uses and replace them with this method
/// </summary>
/// <returns></returns>
public int GetCost()
{
if (Constants.costFunction == Constants.CostFunction.SUM_OF_COSTS)
{
if (Constants.sumOfCostsVariant == Constants.SumOfCostsVariant.ORIG)
{
return this.GetSize() - 1;
}
else if (Constants.sumOfCostsVariant == Constants.SumOfCostsVariant.WAITING_AT_GOAL_ALWAYS_FREE)
{
int cost = 0;
Move goal = this.locationAtTimes.Last<Move>(); // Assuming the plan ends at the goal
for (int i = 1; i < this.locationAtTimes.Count; i++) // The beginning position isn't a move
{
Move move = this.locationAtTimes[i];
if (move.x == goal.x &&
move.y == goal.y &&
move.direction == Move.Direction.Wait) // Waiting at the goal is free
continue;
cost += 1;
}
return cost;
}
}
else if (Constants.costFunction == Constants.CostFunction.MAKESPAN_THEN_SUM_OF_COSTS)
{
return this.GetSize() - 1;
}
return 0; // To quiet the compiler
}
/// <summary>
/// Check if this plan collides with another plan at a given time
/// </summary>
/// <param name="time">The time at which to check if the collision occured</param>
/// <param name="otherPlan">The plan to check against</param>
public bool IsColliding(int time, SinglePlan otherPlan)
{
Move thisLocation = this.GetLocationAt(time);
Move otherLocation = otherPlan.GetLocationAt(time);
if (thisLocation.IsColliding(otherLocation) == true) // IsColliding isn't virtual,
// so it doesn't matter whether the moves are actually TimedMoves
// with incorrect time
return true;
return false;
}
/// <summary>
/// Prints the plan to the Console.
/// This is used for debugging purposes.
/// </summary>
public void DebugPrint()
{
for (int time = 0; time < this.locationAtTimes.Count; time++)
{
Debug.WriteLine($"|{this.GetLocationAt(time)}|");
}
}
public override string ToString()
{
string s = "";
for (int time = 0; time < this.locationAtTimes.Count; time++)
{
s += $"|{this.GetLocationAt(time)}|\n";
}
return s;
}
public static SinglePlan[] GetSinglePlans(WorldState goalState) // FIXME: Duplication with other methods.
{
LinkedList<Move>[] allroutes = new LinkedList<Move>[goalState.allAgentsState.Length];
for (int i = 0; i < allroutes.Length; i++)
allroutes[i] = new LinkedList<Move>();
WorldState currentNode = goalState;
while (currentNode != null)
{
for (int i = 0; i < allroutes.Length; i++)
allroutes[i].AddFirst(currentNode.GetSingleAgentMove(i));
currentNode = currentNode.prevStep;
}
SinglePlan[] ans = new SinglePlan[goalState.allAgentsState.Length];
for (int i = 0; i < ans.Length; i++)
{
ans[i] = new SinglePlan(allroutes[i], goalState.allAgentsState[i].agent.agentNum);
}
return ans;
}
/// <summary>
/// Creates SinglePlans with agentIndex as agentNum. Not suitable for subproblems.
/// </summary>
/// <param name="allRoutes"></param>
/// <returns></returns>
public static SinglePlan[] GetSinglePlans(LinkedList<Move>[] allRoutes)
{
SinglePlan[] ans = new SinglePlan[allRoutes.Length];
for (int i = 0; i < ans.Length; i++)
{
ans[i] = new SinglePlan(allRoutes[i], i);
}
return ans;
}
}
| 412 | 0.834762 | 1 | 0.834762 | game-dev | MEDIA | 0.23517 | game-dev | 0.920821 | 1 | 0.920821 |
clipos/src_external_linux | 105,139 | drivers/staging/rtl8723bs/hal/HalBtc8723b1Ant.c | // SPDX-License-Identifier: GPL-2.0
/******************************************************************************
*
* Copyright(c) 2007 - 2012 Realtek Corporation. All rights reserved.
*
******************************************************************************/
#include "Mp_Precomp.h"
/* Global variables, these are static variables */
static COEX_DM_8723B_1ANT GLCoexDm8723b1Ant;
static PCOEX_DM_8723B_1ANT pCoexDm = &GLCoexDm8723b1Ant;
static COEX_STA_8723B_1ANT GLCoexSta8723b1Ant;
static PCOEX_STA_8723B_1ANT pCoexSta = &GLCoexSta8723b1Ant;
static const char *const GLBtInfoSrc8723b1Ant[] = {
"BT Info[wifi fw]",
"BT Info[bt rsp]",
"BT Info[bt auto report]",
};
static u32 GLCoexVerDate8723b1Ant = 20140507;
static u32 GLCoexVer8723b1Ant = 0x4e;
/* local function proto type if needed */
/* local function start with halbtc8723b1ant_ */
static u8 halbtc8723b1ant_BtRssiState(
u8 levelNum, u8 rssiThresh, u8 rssiThresh1
)
{
s32 btRssi = 0;
u8 btRssiState = pCoexSta->preBtRssiState;
btRssi = pCoexSta->btRssi;
if (levelNum == 2) {
if (
(pCoexSta->preBtRssiState == BTC_RSSI_STATE_LOW) ||
(pCoexSta->preBtRssiState == BTC_RSSI_STATE_STAY_LOW)
) {
if (btRssi >= (rssiThresh+BTC_RSSI_COEX_THRESH_TOL_8723B_1ANT)) {
btRssiState = BTC_RSSI_STATE_HIGH;
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_BT_RSSI_STATE,
("[BTCoex], BT Rssi state switch to High\n")
);
} else {
btRssiState = BTC_RSSI_STATE_STAY_LOW;
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_BT_RSSI_STATE,
("[BTCoex], BT Rssi state stay at Low\n")
);
}
} else {
if (btRssi < rssiThresh) {
btRssiState = BTC_RSSI_STATE_LOW;
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_BT_RSSI_STATE,
("[BTCoex], BT Rssi state switch to Low\n")
);
} else {
btRssiState = BTC_RSSI_STATE_STAY_HIGH;
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_BT_RSSI_STATE,
("[BTCoex], BT Rssi state stay at High\n")
);
}
}
} else if (levelNum == 3) {
if (rssiThresh > rssiThresh1) {
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_BT_RSSI_STATE,
("[BTCoex], BT Rssi thresh error!!\n")
);
return pCoexSta->preBtRssiState;
}
if (
(pCoexSta->preBtRssiState == BTC_RSSI_STATE_LOW) ||
(pCoexSta->preBtRssiState == BTC_RSSI_STATE_STAY_LOW)
) {
if (btRssi >= (rssiThresh+BTC_RSSI_COEX_THRESH_TOL_8723B_1ANT)) {
btRssiState = BTC_RSSI_STATE_MEDIUM;
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_BT_RSSI_STATE,
("[BTCoex], BT Rssi state switch to Medium\n")
);
} else {
btRssiState = BTC_RSSI_STATE_STAY_LOW;
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_BT_RSSI_STATE,
("[BTCoex], BT Rssi state stay at Low\n")
);
}
} else if (
(pCoexSta->preBtRssiState == BTC_RSSI_STATE_MEDIUM) ||
(pCoexSta->preBtRssiState == BTC_RSSI_STATE_STAY_MEDIUM)
) {
if (btRssi >= (rssiThresh1+BTC_RSSI_COEX_THRESH_TOL_8723B_1ANT)) {
btRssiState = BTC_RSSI_STATE_HIGH;
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_BT_RSSI_STATE,
("[BTCoex], BT Rssi state switch to High\n")
);
} else if (btRssi < rssiThresh) {
btRssiState = BTC_RSSI_STATE_LOW;
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_BT_RSSI_STATE,
("[BTCoex], BT Rssi state switch to Low\n")
);
} else {
btRssiState = BTC_RSSI_STATE_STAY_MEDIUM;
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_BT_RSSI_STATE,
("[BTCoex], BT Rssi state stay at Medium\n")
);
}
} else {
if (btRssi < rssiThresh1) {
btRssiState = BTC_RSSI_STATE_MEDIUM;
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_BT_RSSI_STATE,
("[BTCoex], BT Rssi state switch to Medium\n")
);
} else {
btRssiState = BTC_RSSI_STATE_STAY_HIGH;
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_BT_RSSI_STATE,
("[BTCoex], BT Rssi state stay at High\n")
);
}
}
}
pCoexSta->preBtRssiState = btRssiState;
return btRssiState;
}
static void halbtc8723b1ant_UpdateRaMask(
PBTC_COEXIST pBtCoexist, bool bForceExec, u32 disRateMask
)
{
pCoexDm->curRaMask = disRateMask;
if (bForceExec || (pCoexDm->preRaMask != pCoexDm->curRaMask))
pBtCoexist->fBtcSet(
pBtCoexist,
BTC_SET_ACT_UPDATE_RAMASK,
&pCoexDm->curRaMask
);
pCoexDm->preRaMask = pCoexDm->curRaMask;
}
static void halbtc8723b1ant_AutoRateFallbackRetry(
PBTC_COEXIST pBtCoexist, bool bForceExec, u8 type
)
{
bool bWifiUnderBMode = false;
pCoexDm->curArfrType = type;
if (bForceExec || (pCoexDm->preArfrType != pCoexDm->curArfrType)) {
switch (pCoexDm->curArfrType) {
case 0: /* normal mode */
pBtCoexist->fBtcWrite4Byte(
pBtCoexist, 0x430, pCoexDm->backupArfrCnt1
);
pBtCoexist->fBtcWrite4Byte(
pBtCoexist, 0x434, pCoexDm->backupArfrCnt2
);
break;
case 1:
pBtCoexist->fBtcGet(
pBtCoexist, BTC_GET_BL_WIFI_UNDER_B_MODE, &bWifiUnderBMode
);
if (bWifiUnderBMode) {
pBtCoexist->fBtcWrite4Byte(pBtCoexist, 0x430, 0x0);
pBtCoexist->fBtcWrite4Byte(pBtCoexist, 0x434, 0x01010101);
} else {
pBtCoexist->fBtcWrite4Byte(pBtCoexist, 0x430, 0x0);
pBtCoexist->fBtcWrite4Byte(pBtCoexist, 0x434, 0x04030201);
}
break;
default:
break;
}
}
pCoexDm->preArfrType = pCoexDm->curArfrType;
}
static void halbtc8723b1ant_RetryLimit(
PBTC_COEXIST pBtCoexist, bool bForceExec, u8 type
)
{
pCoexDm->curRetryLimitType = type;
if (
bForceExec ||
(pCoexDm->preRetryLimitType != pCoexDm->curRetryLimitType)
) {
switch (pCoexDm->curRetryLimitType) {
case 0: /* normal mode */
pBtCoexist->fBtcWrite2Byte(
pBtCoexist, 0x42a, pCoexDm->backupRetryLimit
);
break;
case 1: /* retry limit =8 */
pBtCoexist->fBtcWrite2Byte(pBtCoexist, 0x42a, 0x0808);
break;
default:
break;
}
}
pCoexDm->preRetryLimitType = pCoexDm->curRetryLimitType;
}
static void halbtc8723b1ant_AmpduMaxTime(
PBTC_COEXIST pBtCoexist, bool bForceExec, u8 type
)
{
pCoexDm->curAmpduTimeType = type;
if (
bForceExec || (pCoexDm->preAmpduTimeType != pCoexDm->curAmpduTimeType)
) {
switch (pCoexDm->curAmpduTimeType) {
case 0: /* normal mode */
pBtCoexist->fBtcWrite1Byte(
pBtCoexist, 0x456, pCoexDm->backupAmpduMaxTime
);
break;
case 1: /* AMPDU timw = 0x38 * 32us */
pBtCoexist->fBtcWrite1Byte(pBtCoexist, 0x456, 0x38);
break;
default:
break;
}
}
pCoexDm->preAmpduTimeType = pCoexDm->curAmpduTimeType;
}
static void halbtc8723b1ant_LimitedTx(
PBTC_COEXIST pBtCoexist,
bool bForceExec,
u8 raMaskType,
u8 arfrType,
u8 retryLimitType,
u8 ampduTimeType
)
{
switch (raMaskType) {
case 0: /* normal mode */
halbtc8723b1ant_UpdateRaMask(pBtCoexist, bForceExec, 0x0);
break;
case 1: /* disable cck 1/2 */
halbtc8723b1ant_UpdateRaMask(pBtCoexist, bForceExec, 0x00000003);
break;
case 2: /* disable cck 1/2/5.5, ofdm 6/9/12/18/24, mcs 0/1/2/3/4 */
halbtc8723b1ant_UpdateRaMask(pBtCoexist, bForceExec, 0x0001f1f7);
break;
default:
break;
}
halbtc8723b1ant_AutoRateFallbackRetry(pBtCoexist, bForceExec, arfrType);
halbtc8723b1ant_RetryLimit(pBtCoexist, bForceExec, retryLimitType);
halbtc8723b1ant_AmpduMaxTime(pBtCoexist, bForceExec, ampduTimeType);
}
static void halbtc8723b1ant_LimitedRx(
PBTC_COEXIST pBtCoexist,
bool bForceExec,
bool bRejApAggPkt,
bool bBtCtrlAggBufSize,
u8 aggBufSize
)
{
bool bRejectRxAgg = bRejApAggPkt;
bool bBtCtrlRxAggSize = bBtCtrlAggBufSize;
u8 rxAggSize = aggBufSize;
/* */
/* Rx Aggregation related setting */
/* */
pBtCoexist->fBtcSet(
pBtCoexist, BTC_SET_BL_TO_REJ_AP_AGG_PKT, &bRejectRxAgg
);
/* decide BT control aggregation buf size or not */
pBtCoexist->fBtcSet(
pBtCoexist, BTC_SET_BL_BT_CTRL_AGG_SIZE, &bBtCtrlRxAggSize
);
/* aggregation buf size, only work when BT control Rx aggregation size. */
pBtCoexist->fBtcSet(pBtCoexist, BTC_SET_U1_AGG_BUF_SIZE, &rxAggSize);
/* real update aggregation setting */
pBtCoexist->fBtcSet(pBtCoexist, BTC_SET_ACT_AGGREGATE_CTRL, NULL);
}
static void halbtc8723b1ant_QueryBtInfo(PBTC_COEXIST pBtCoexist)
{
u8 H2C_Parameter[1] = {0};
pCoexSta->bC2hBtInfoReqSent = true;
H2C_Parameter[0] |= BIT0; /* trigger */
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_TRACE_FW_EXEC,
("[BTCoex], Query Bt Info, FW write 0x61 = 0x%x\n", H2C_Parameter[0])
);
pBtCoexist->fBtcFillH2c(pBtCoexist, 0x61, 1, H2C_Parameter);
}
static void halbtc8723b1ant_MonitorBtCtr(PBTC_COEXIST pBtCoexist)
{
u32 regHPTxRx, regLPTxRx, u4Tmp;
u32 regHPTx = 0, regHPRx = 0, regLPTx = 0, regLPRx = 0;
static u8 NumOfBtCounterChk;
/* to avoid 0x76e[3] = 1 (WLAN_Act control by PTA) during IPS */
/* if (! (pBtCoexist->fBtcRead1Byte(pBtCoexist, 0x76e) & 0x8)) */
if (pCoexSta->bUnderIps) {
pCoexSta->highPriorityTx = 65535;
pCoexSta->highPriorityRx = 65535;
pCoexSta->lowPriorityTx = 65535;
pCoexSta->lowPriorityRx = 65535;
return;
}
regHPTxRx = 0x770;
regLPTxRx = 0x774;
u4Tmp = pBtCoexist->fBtcRead4Byte(pBtCoexist, regHPTxRx);
regHPTx = u4Tmp & bMaskLWord;
regHPRx = (u4Tmp & bMaskHWord)>>16;
u4Tmp = pBtCoexist->fBtcRead4Byte(pBtCoexist, regLPTxRx);
regLPTx = u4Tmp & bMaskLWord;
regLPRx = (u4Tmp & bMaskHWord)>>16;
pCoexSta->highPriorityTx = regHPTx;
pCoexSta->highPriorityRx = regHPRx;
pCoexSta->lowPriorityTx = regLPTx;
pCoexSta->lowPriorityRx = regLPRx;
if ((pCoexSta->lowPriorityTx >= 1050) && (!pCoexSta->bC2hBtInquiryPage))
pCoexSta->popEventCnt++;
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_TRACE,
(
"[BTCoex], Hi-Pri Rx/Tx: %d/%d, Lo-Pri Rx/Tx: %d/%d\n",
regHPRx,
regHPTx,
regLPRx,
regLPTx
)
);
/* reset counter */
pBtCoexist->fBtcWrite1Byte(pBtCoexist, 0x76e, 0xc);
if ((regHPTx == 0) && (regHPRx == 0) && (regLPTx == 0) && (regLPRx == 0)) {
NumOfBtCounterChk++;
if (NumOfBtCounterChk >= 3) {
halbtc8723b1ant_QueryBtInfo(pBtCoexist);
NumOfBtCounterChk = 0;
}
}
}
static void halbtc8723b1ant_MonitorWiFiCtr(PBTC_COEXIST pBtCoexist)
{
s32 wifiRssi = 0;
bool bWifiBusy = false, bWifiUnderBMode = false;
static u8 nCCKLockCounter;
pBtCoexist->fBtcGet(pBtCoexist, BTC_GET_BL_WIFI_BUSY, &bWifiBusy);
pBtCoexist->fBtcGet(pBtCoexist, BTC_GET_S4_WIFI_RSSI, &wifiRssi);
pBtCoexist->fBtcGet(
pBtCoexist, BTC_GET_BL_WIFI_UNDER_B_MODE, &bWifiUnderBMode
);
if (pCoexSta->bUnderIps) {
pCoexSta->nCRCOK_CCK = 0;
pCoexSta->nCRCOK_11g = 0;
pCoexSta->nCRCOK_11n = 0;
pCoexSta->nCRCOK_11nAgg = 0;
pCoexSta->nCRCErr_CCK = 0;
pCoexSta->nCRCErr_11g = 0;
pCoexSta->nCRCErr_11n = 0;
pCoexSta->nCRCErr_11nAgg = 0;
} else {
pCoexSta->nCRCOK_CCK = pBtCoexist->fBtcRead4Byte(pBtCoexist, 0xf88);
pCoexSta->nCRCOK_11g = pBtCoexist->fBtcRead2Byte(pBtCoexist, 0xf94);
pCoexSta->nCRCOK_11n = pBtCoexist->fBtcRead2Byte(pBtCoexist, 0xf90);
pCoexSta->nCRCOK_11nAgg = pBtCoexist->fBtcRead2Byte(pBtCoexist, 0xfb8);
pCoexSta->nCRCErr_CCK = pBtCoexist->fBtcRead4Byte(pBtCoexist, 0xf84);
pCoexSta->nCRCErr_11g = pBtCoexist->fBtcRead2Byte(pBtCoexist, 0xf96);
pCoexSta->nCRCErr_11n = pBtCoexist->fBtcRead2Byte(pBtCoexist, 0xf92);
pCoexSta->nCRCErr_11nAgg = pBtCoexist->fBtcRead2Byte(pBtCoexist, 0xfba);
}
/* reset counter */
pBtCoexist->fBtcWrite1ByteBitMask(pBtCoexist, 0xf16, 0x1, 0x1);
pBtCoexist->fBtcWrite1ByteBitMask(pBtCoexist, 0xf16, 0x1, 0x0);
if (bWifiBusy && (wifiRssi >= 30) && !bWifiUnderBMode) {
if (
(pCoexDm->btStatus == BT_8723B_1ANT_BT_STATUS_ACL_BUSY) ||
(pCoexDm->btStatus == BT_8723B_1ANT_BT_STATUS_ACL_SCO_BUSY) ||
(pCoexDm->btStatus == BT_8723B_1ANT_BT_STATUS_SCO_BUSY)
) {
if (
pCoexSta->nCRCOK_CCK > (
pCoexSta->nCRCOK_11g +
pCoexSta->nCRCOK_11n +
pCoexSta->nCRCOK_11nAgg
)
) {
if (nCCKLockCounter < 5)
nCCKLockCounter++;
} else {
if (nCCKLockCounter > 0)
nCCKLockCounter--;
}
} else {
if (nCCKLockCounter > 0)
nCCKLockCounter--;
}
} else {
if (nCCKLockCounter > 0)
nCCKLockCounter--;
}
if (!pCoexSta->bPreCCKLock) {
if (nCCKLockCounter >= 5)
pCoexSta->bCCKLock = true;
else
pCoexSta->bCCKLock = false;
} else {
if (nCCKLockCounter == 0)
pCoexSta->bCCKLock = false;
else
pCoexSta->bCCKLock = true;
}
pCoexSta->bPreCCKLock = pCoexSta->bCCKLock;
}
static bool halbtc8723b1ant_IsWifiStatusChanged(PBTC_COEXIST pBtCoexist)
{
static bool bPreWifiBusy, bPreUnder4way, bPreBtHsOn;
bool bWifiBusy = false, bUnder4way = false, bBtHsOn = false;
bool bWifiConnected = false;
pBtCoexist->fBtcGet(
pBtCoexist, BTC_GET_BL_WIFI_CONNECTED, &bWifiConnected
);
pBtCoexist->fBtcGet(pBtCoexist, BTC_GET_BL_WIFI_BUSY, &bWifiBusy);
pBtCoexist->fBtcGet(pBtCoexist, BTC_GET_BL_HS_OPERATION, &bBtHsOn);
pBtCoexist->fBtcGet(
pBtCoexist, BTC_GET_BL_WIFI_4_WAY_PROGRESS, &bUnder4way
);
if (bWifiConnected) {
if (bWifiBusy != bPreWifiBusy) {
bPreWifiBusy = bWifiBusy;
return true;
}
if (bUnder4way != bPreUnder4way) {
bPreUnder4way = bUnder4way;
return true;
}
if (bBtHsOn != bPreBtHsOn) {
bPreBtHsOn = bBtHsOn;
return true;
}
}
return false;
}
static void halbtc8723b1ant_UpdateBtLinkInfo(PBTC_COEXIST pBtCoexist)
{
PBTC_BT_LINK_INFO pBtLinkInfo = &pBtCoexist->btLinkInfo;
bool bBtHsOn = false;
pBtCoexist->fBtcGet(pBtCoexist, BTC_GET_BL_HS_OPERATION, &bBtHsOn);
pBtLinkInfo->bBtLinkExist = pCoexSta->bBtLinkExist;
pBtLinkInfo->bScoExist = pCoexSta->bScoExist;
pBtLinkInfo->bA2dpExist = pCoexSta->bA2dpExist;
pBtLinkInfo->bPanExist = pCoexSta->bPanExist;
pBtLinkInfo->bHidExist = pCoexSta->bHidExist;
/* work around for HS mode. */
if (bBtHsOn) {
pBtLinkInfo->bPanExist = true;
pBtLinkInfo->bBtLinkExist = true;
}
/* check if Sco only */
if (
pBtLinkInfo->bScoExist &&
!pBtLinkInfo->bA2dpExist &&
!pBtLinkInfo->bPanExist &&
!pBtLinkInfo->bHidExist
)
pBtLinkInfo->bScoOnly = true;
else
pBtLinkInfo->bScoOnly = false;
/* check if A2dp only */
if (
!pBtLinkInfo->bScoExist &&
pBtLinkInfo->bA2dpExist &&
!pBtLinkInfo->bPanExist &&
!pBtLinkInfo->bHidExist
)
pBtLinkInfo->bA2dpOnly = true;
else
pBtLinkInfo->bA2dpOnly = false;
/* check if Pan only */
if (
!pBtLinkInfo->bScoExist &&
!pBtLinkInfo->bA2dpExist &&
pBtLinkInfo->bPanExist &&
!pBtLinkInfo->bHidExist
)
pBtLinkInfo->bPanOnly = true;
else
pBtLinkInfo->bPanOnly = false;
/* check if Hid only */
if (
!pBtLinkInfo->bScoExist &&
!pBtLinkInfo->bA2dpExist &&
!pBtLinkInfo->bPanExist &&
pBtLinkInfo->bHidExist
)
pBtLinkInfo->bHidOnly = true;
else
pBtLinkInfo->bHidOnly = false;
}
static u8 halbtc8723b1ant_ActionAlgorithm(PBTC_COEXIST pBtCoexist)
{
PBTC_BT_LINK_INFO pBtLinkInfo = &pBtCoexist->btLinkInfo;
bool bBtHsOn = false;
u8 algorithm = BT_8723B_1ANT_COEX_ALGO_UNDEFINED;
u8 numOfDiffProfile = 0;
pBtCoexist->fBtcGet(pBtCoexist, BTC_GET_BL_HS_OPERATION, &bBtHsOn);
if (!pBtLinkInfo->bBtLinkExist) {
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_TRACE,
("[BTCoex], No BT link exists!!!\n")
);
return algorithm;
}
if (pBtLinkInfo->bScoExist)
numOfDiffProfile++;
if (pBtLinkInfo->bHidExist)
numOfDiffProfile++;
if (pBtLinkInfo->bPanExist)
numOfDiffProfile++;
if (pBtLinkInfo->bA2dpExist)
numOfDiffProfile++;
if (numOfDiffProfile == 1) {
if (pBtLinkInfo->bScoExist) {
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_TRACE,
("[BTCoex], BT Profile = SCO only\n")
);
algorithm = BT_8723B_1ANT_COEX_ALGO_SCO;
} else {
if (pBtLinkInfo->bHidExist) {
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_TRACE,
("[BTCoex], BT Profile = HID only\n")
);
algorithm = BT_8723B_1ANT_COEX_ALGO_HID;
} else if (pBtLinkInfo->bA2dpExist) {
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_TRACE,
("[BTCoex], BT Profile = A2DP only\n")
);
algorithm = BT_8723B_1ANT_COEX_ALGO_A2DP;
} else if (pBtLinkInfo->bPanExist) {
if (bBtHsOn) {
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_TRACE,
("[BTCoex], BT Profile = PAN(HS) only\n")
);
algorithm = BT_8723B_1ANT_COEX_ALGO_PANHS;
} else {
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_TRACE,
("[BTCoex], BT Profile = PAN(EDR) only\n")
);
algorithm = BT_8723B_1ANT_COEX_ALGO_PANEDR;
}
}
}
} else if (numOfDiffProfile == 2) {
if (pBtLinkInfo->bScoExist) {
if (pBtLinkInfo->bHidExist) {
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_TRACE,
("[BTCoex], BT Profile = SCO + HID\n")
);
algorithm = BT_8723B_1ANT_COEX_ALGO_HID;
} else if (pBtLinkInfo->bA2dpExist) {
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_TRACE,
("[BTCoex], BT Profile = SCO + A2DP ==> SCO\n")
);
algorithm = BT_8723B_1ANT_COEX_ALGO_SCO;
} else if (pBtLinkInfo->bPanExist) {
if (bBtHsOn) {
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_TRACE,
("[BTCoex], BT Profile = SCO + PAN(HS)\n")
);
algorithm = BT_8723B_1ANT_COEX_ALGO_SCO;
} else {
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_TRACE,
("[BTCoex], BT Profile = SCO + PAN(EDR)\n")
);
algorithm = BT_8723B_1ANT_COEX_ALGO_PANEDR_HID;
}
}
} else {
if (pBtLinkInfo->bHidExist && pBtLinkInfo->bA2dpExist) {
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_TRACE,
("[BTCoex], BT Profile = HID + A2DP\n")
);
algorithm = BT_8723B_1ANT_COEX_ALGO_HID_A2DP;
} else if (pBtLinkInfo->bHidExist && pBtLinkInfo->bPanExist) {
if (bBtHsOn) {
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_TRACE,
("[BTCoex], BT Profile = HID + PAN(HS)\n")
);
algorithm = BT_8723B_1ANT_COEX_ALGO_HID_A2DP;
} else {
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_TRACE,
("[BTCoex], BT Profile = HID + PAN(EDR)\n")
);
algorithm = BT_8723B_1ANT_COEX_ALGO_PANEDR_HID;
}
} else if (pBtLinkInfo->bPanExist && pBtLinkInfo->bA2dpExist) {
if (bBtHsOn) {
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_TRACE,
("[BTCoex], BT Profile = A2DP + PAN(HS)\n")
);
algorithm = BT_8723B_1ANT_COEX_ALGO_A2DP_PANHS;
} else {
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_TRACE,
("[BTCoex], BT Profile = A2DP + PAN(EDR)\n")
);
algorithm = BT_8723B_1ANT_COEX_ALGO_PANEDR_A2DP;
}
}
}
} else if (numOfDiffProfile == 3) {
if (pBtLinkInfo->bScoExist) {
if (pBtLinkInfo->bHidExist && pBtLinkInfo->bA2dpExist) {
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_TRACE,
("[BTCoex], BT Profile = SCO + HID + A2DP ==> HID\n")
);
algorithm = BT_8723B_1ANT_COEX_ALGO_HID;
} else if (
pBtLinkInfo->bHidExist && pBtLinkInfo->bPanExist
) {
if (bBtHsOn) {
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE, ("[BTCoex], BT Profile = SCO + HID + PAN(HS)\n"));
algorithm = BT_8723B_1ANT_COEX_ALGO_HID_A2DP;
} else {
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE, ("[BTCoex], BT Profile = SCO + HID + PAN(EDR)\n"));
algorithm = BT_8723B_1ANT_COEX_ALGO_PANEDR_HID;
}
} else if (pBtLinkInfo->bPanExist && pBtLinkInfo->bA2dpExist) {
if (bBtHsOn) {
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE, ("[BTCoex], BT Profile = SCO + A2DP + PAN(HS)\n"));
algorithm = BT_8723B_1ANT_COEX_ALGO_SCO;
} else {
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_TRACE,
("[BTCoex], BT Profile = SCO + A2DP + PAN(EDR) ==> HID\n")
);
algorithm = BT_8723B_1ANT_COEX_ALGO_PANEDR_HID;
}
}
} else {
if (
pBtLinkInfo->bHidExist &&
pBtLinkInfo->bPanExist &&
pBtLinkInfo->bA2dpExist
) {
if (bBtHsOn) {
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_TRACE,
("[BTCoex], BT Profile = HID + A2DP + PAN(HS)\n")
);
algorithm = BT_8723B_1ANT_COEX_ALGO_HID_A2DP;
} else {
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_TRACE,
("[BTCoex], BT Profile = HID + A2DP + PAN(EDR)\n")
);
algorithm = BT_8723B_1ANT_COEX_ALGO_HID_A2DP_PANEDR;
}
}
}
} else if (numOfDiffProfile >= 3) {
if (pBtLinkInfo->bScoExist) {
if (
pBtLinkInfo->bHidExist &&
pBtLinkInfo->bPanExist &&
pBtLinkInfo->bA2dpExist
) {
if (bBtHsOn) {
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_TRACE,
("[BTCoex], Error!!! BT Profile = SCO + HID + A2DP + PAN(HS)\n")
);
} else {
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_TRACE,
("[BTCoex], BT Profile = SCO + HID + A2DP + PAN(EDR) ==>PAN(EDR)+HID\n")
);
algorithm = BT_8723B_1ANT_COEX_ALGO_PANEDR_HID;
}
}
}
}
return algorithm;
}
static void halbtc8723b1ant_SetSwPenaltyTxRateAdaptive(
PBTC_COEXIST pBtCoexist, bool bLowPenaltyRa
)
{
u8 H2C_Parameter[6] = {0};
H2C_Parameter[0] = 0x6; /* opCode, 0x6 = Retry_Penalty */
if (bLowPenaltyRa) {
H2C_Parameter[1] |= BIT0;
H2C_Parameter[2] = 0x00; /* normal rate except MCS7/6/5, OFDM54/48/36 */
H2C_Parameter[3] = 0xf7; /* MCS7 or OFDM54 */
H2C_Parameter[4] = 0xf8; /* MCS6 or OFDM48 */
H2C_Parameter[5] = 0xf9; /* MCS5 or OFDM36 */
}
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_TRACE_FW_EXEC,
(
"[BTCoex], set WiFi Low-Penalty Retry: %s",
(bLowPenaltyRa ? "ON!!" : "OFF!!")
)
);
pBtCoexist->fBtcFillH2c(pBtCoexist, 0x69, 6, H2C_Parameter);
}
static void halbtc8723b1ant_LowPenaltyRa(
PBTC_COEXIST pBtCoexist, bool bForceExec, bool bLowPenaltyRa
)
{
pCoexDm->bCurLowPenaltyRa = bLowPenaltyRa;
if (!bForceExec) {
if (pCoexDm->bPreLowPenaltyRa == pCoexDm->bCurLowPenaltyRa)
return;
}
halbtc8723b1ant_SetSwPenaltyTxRateAdaptive(
pBtCoexist, pCoexDm->bCurLowPenaltyRa
);
pCoexDm->bPreLowPenaltyRa = pCoexDm->bCurLowPenaltyRa;
}
static void halbtc8723b1ant_SetCoexTable(
PBTC_COEXIST pBtCoexist,
u32 val0x6c0,
u32 val0x6c4,
u32 val0x6c8,
u8 val0x6cc
)
{
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_TRACE_SW_EXEC,
("[BTCoex], set coex table, set 0x6c0 = 0x%x\n", val0x6c0)
);
pBtCoexist->fBtcWrite4Byte(pBtCoexist, 0x6c0, val0x6c0);
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_TRACE_SW_EXEC,
("[BTCoex], set coex table, set 0x6c4 = 0x%x\n", val0x6c4)
);
pBtCoexist->fBtcWrite4Byte(pBtCoexist, 0x6c4, val0x6c4);
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_TRACE_SW_EXEC,
("[BTCoex], set coex table, set 0x6c8 = 0x%x\n", val0x6c8)
);
pBtCoexist->fBtcWrite4Byte(pBtCoexist, 0x6c8, val0x6c8);
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_TRACE_SW_EXEC,
("[BTCoex], set coex table, set 0x6cc = 0x%x\n", val0x6cc)
);
pBtCoexist->fBtcWrite1Byte(pBtCoexist, 0x6cc, val0x6cc);
}
static void halbtc8723b1ant_CoexTable(
PBTC_COEXIST pBtCoexist,
bool bForceExec,
u32 val0x6c0,
u32 val0x6c4,
u32 val0x6c8,
u8 val0x6cc
)
{
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_TRACE_SW,
(
"[BTCoex], %s write Coex Table 0x6c0 = 0x%x, 0x6c4 = 0x%x, 0x6cc = 0x%x\n",
(bForceExec ? "force to" : ""),
val0x6c0, val0x6c4, val0x6cc
)
);
pCoexDm->curVal0x6c0 = val0x6c0;
pCoexDm->curVal0x6c4 = val0x6c4;
pCoexDm->curVal0x6c8 = val0x6c8;
pCoexDm->curVal0x6cc = val0x6cc;
if (!bForceExec) {
if (
(pCoexDm->preVal0x6c0 == pCoexDm->curVal0x6c0) &&
(pCoexDm->preVal0x6c4 == pCoexDm->curVal0x6c4) &&
(pCoexDm->preVal0x6c8 == pCoexDm->curVal0x6c8) &&
(pCoexDm->preVal0x6cc == pCoexDm->curVal0x6cc)
)
return;
}
halbtc8723b1ant_SetCoexTable(
pBtCoexist, val0x6c0, val0x6c4, val0x6c8, val0x6cc
);
pCoexDm->preVal0x6c0 = pCoexDm->curVal0x6c0;
pCoexDm->preVal0x6c4 = pCoexDm->curVal0x6c4;
pCoexDm->preVal0x6c8 = pCoexDm->curVal0x6c8;
pCoexDm->preVal0x6cc = pCoexDm->curVal0x6cc;
}
static void halbtc8723b1ant_CoexTableWithType(
PBTC_COEXIST pBtCoexist, bool bForceExec, u8 type
)
{
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_TRACE,
("[BTCoex], ********** CoexTable(%d) **********\n", type)
);
pCoexSta->nCoexTableType = type;
switch (type) {
case 0:
halbtc8723b1ant_CoexTable(
pBtCoexist, bForceExec, 0x55555555, 0x55555555, 0xffffff, 0x3
);
break;
case 1:
halbtc8723b1ant_CoexTable(
pBtCoexist, bForceExec, 0x55555555, 0x5a5a5a5a, 0xffffff, 0x3
);
break;
case 2:
halbtc8723b1ant_CoexTable(
pBtCoexist, bForceExec, 0x5a5a5a5a, 0x5a5a5a5a, 0xffffff, 0x3
);
break;
case 3:
halbtc8723b1ant_CoexTable(
pBtCoexist, bForceExec, 0xaaaa5555, 0xaaaa5a5a, 0xffffff, 0x3
);
break;
case 4:
halbtc8723b1ant_CoexTable(
pBtCoexist, bForceExec, 0x55555555, 0xaaaa5a5a, 0xffffff, 0x3
);
break;
case 5:
halbtc8723b1ant_CoexTable(
pBtCoexist, bForceExec, 0x5a5a5a5a, 0xaaaa5a5a, 0xffffff, 0x3
);
break;
case 6:
halbtc8723b1ant_CoexTable(
pBtCoexist, bForceExec, 0x55555555, 0xaaaaaaaa, 0xffffff, 0x3
);
break;
case 7:
halbtc8723b1ant_CoexTable(
pBtCoexist, bForceExec, 0xaaaaaaaa, 0xaaaaaaaa, 0xffffff, 0x3
);
break;
default:
break;
}
}
static void halbtc8723b1ant_SetFwIgnoreWlanAct(
PBTC_COEXIST pBtCoexist, bool bEnable
)
{
u8 H2C_Parameter[1] = {0};
if (bEnable)
H2C_Parameter[0] |= BIT0; /* function enable */
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_TRACE_FW_EXEC,
(
"[BTCoex], set FW for BT Ignore Wlan_Act, FW write 0x63 = 0x%x\n",
H2C_Parameter[0]
)
);
pBtCoexist->fBtcFillH2c(pBtCoexist, 0x63, 1, H2C_Parameter);
}
static void halbtc8723b1ant_IgnoreWlanAct(
PBTC_COEXIST pBtCoexist, bool bForceExec, bool bEnable
)
{
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_TRACE_FW,
(
"[BTCoex], %s turn Ignore WlanAct %s\n",
(bForceExec ? "force to" : ""),
(bEnable ? "ON" : "OFF")
)
);
pCoexDm->bCurIgnoreWlanAct = bEnable;
if (!bForceExec) {
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_TRACE_FW_DETAIL,
(
"[BTCoex], bPreIgnoreWlanAct = %d, bCurIgnoreWlanAct = %d!!\n",
pCoexDm->bPreIgnoreWlanAct,
pCoexDm->bCurIgnoreWlanAct
)
);
if (pCoexDm->bPreIgnoreWlanAct == pCoexDm->bCurIgnoreWlanAct)
return;
}
halbtc8723b1ant_SetFwIgnoreWlanAct(pBtCoexist, bEnable);
pCoexDm->bPreIgnoreWlanAct = pCoexDm->bCurIgnoreWlanAct;
}
static void halbtc8723b1ant_SetLpsRpwm(
PBTC_COEXIST pBtCoexist, u8 lpsVal, u8 rpwmVal
)
{
u8 lps = lpsVal;
u8 rpwm = rpwmVal;
pBtCoexist->fBtcSet(pBtCoexist, BTC_SET_U1_LPS_VAL, &lps);
pBtCoexist->fBtcSet(pBtCoexist, BTC_SET_U1_RPWM_VAL, &rpwm);
}
static void halbtc8723b1ant_LpsRpwm(
PBTC_COEXIST pBtCoexist, bool bForceExec, u8 lpsVal, u8 rpwmVal
)
{
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_TRACE_FW,
(
"[BTCoex], %s set lps/rpwm = 0x%x/0x%x\n",
(bForceExec ? "force to" : ""),
lpsVal,
rpwmVal
)
);
pCoexDm->curLps = lpsVal;
pCoexDm->curRpwm = rpwmVal;
if (!bForceExec) {
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_TRACE_FW_DETAIL,
(
"[BTCoex], LPS-RxBeaconMode = 0x%x , LPS-RPWM = 0x%x!!\n",
pCoexDm->curLps,
pCoexDm->curRpwm
)
);
if (
(pCoexDm->preLps == pCoexDm->curLps) &&
(pCoexDm->preRpwm == pCoexDm->curRpwm)
) {
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_TRACE_FW_DETAIL,
(
"[BTCoex], LPS-RPWM_Last = 0x%x , LPS-RPWM_Now = 0x%x!!\n",
pCoexDm->preRpwm,
pCoexDm->curRpwm
)
);
return;
}
}
halbtc8723b1ant_SetLpsRpwm(pBtCoexist, lpsVal, rpwmVal);
pCoexDm->preLps = pCoexDm->curLps;
pCoexDm->preRpwm = pCoexDm->curRpwm;
}
static void halbtc8723b1ant_SwMechanism(
PBTC_COEXIST pBtCoexist, bool bLowPenaltyRA
)
{
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_BT_MONITOR,
("[BTCoex], SM[LpRA] = %d\n", bLowPenaltyRA)
);
halbtc8723b1ant_LowPenaltyRa(pBtCoexist, NORMAL_EXEC, bLowPenaltyRA);
}
static void halbtc8723b1ant_SetAntPath(
PBTC_COEXIST pBtCoexist, u8 antPosType, bool bInitHwCfg, bool bWifiOff
)
{
PBTC_BOARD_INFO pBoardInfo = &pBtCoexist->boardInfo;
u32 fwVer = 0, u4Tmp = 0, cntBtCalChk = 0;
bool bPgExtSwitch = false;
bool bUseExtSwitch = false;
bool bIsInMpMode = false;
u8 H2C_Parameter[2] = {0}, u1Tmp = 0;
pBtCoexist->fBtcGet(pBtCoexist, BTC_GET_BL_EXT_SWITCH, &bPgExtSwitch);
pBtCoexist->fBtcGet(pBtCoexist, BTC_GET_U4_WIFI_FW_VER, &fwVer); /* [31:16]=fw ver, [15:0]=fw sub ver */
if ((fwVer > 0 && fwVer < 0xc0000) || bPgExtSwitch)
bUseExtSwitch = true;
if (bInitHwCfg) {
pBtCoexist->fBtcSetRfReg(pBtCoexist, BTC_RF_A, 0x1, 0xfffff, 0x780); /* WiFi TRx Mask on */
pBtCoexist->fBtcSetBtReg(pBtCoexist, BTC_BT_REG_RF, 0x3c, 0x15); /* BT TRx Mask on */
if (fwVer >= 0x180000) {
/* Use H2C to set GNT_BT to HIGH */
H2C_Parameter[0] = 1;
pBtCoexist->fBtcFillH2c(pBtCoexist, 0x6E, 1, H2C_Parameter);
} else /* set grant_bt to high */
pBtCoexist->fBtcWrite1Byte(pBtCoexist, 0x765, 0x18);
/* set wlan_act control by PTA */
pBtCoexist->fBtcWrite1Byte(pBtCoexist, 0x76e, 0x4);
pBtCoexist->fBtcWrite1ByteBitMask(pBtCoexist, 0x67, 0x20, 0x1); /* BT select s0/s1 is controlled by WiFi */
pBtCoexist->fBtcWrite1ByteBitMask(pBtCoexist, 0x39, 0x8, 0x1);
pBtCoexist->fBtcWrite1Byte(pBtCoexist, 0x974, 0xff);
pBtCoexist->fBtcWrite1ByteBitMask(pBtCoexist, 0x944, 0x3, 0x3);
pBtCoexist->fBtcWrite1Byte(pBtCoexist, 0x930, 0x77);
} else if (bWifiOff) {
if (fwVer >= 0x180000) {
/* Use H2C to set GNT_BT to HIGH */
H2C_Parameter[0] = 1;
pBtCoexist->fBtcFillH2c(pBtCoexist, 0x6E, 1, H2C_Parameter);
} else /* set grant_bt to high */
pBtCoexist->fBtcWrite1Byte(pBtCoexist, 0x765, 0x18);
/* set wlan_act to always low */
pBtCoexist->fBtcWrite1Byte(pBtCoexist, 0x76e, 0x4);
pBtCoexist->fBtcGet(pBtCoexist, BTC_GET_BL_WIFI_IS_IN_MP_MODE, &bIsInMpMode);
if (!bIsInMpMode)
pBtCoexist->fBtcWrite1ByteBitMask(pBtCoexist, 0x67, 0x20, 0x0); /* BT select s0/s1 is controlled by BT */
else
pBtCoexist->fBtcWrite1ByteBitMask(pBtCoexist, 0x67, 0x20, 0x1); /* BT select s0/s1 is controlled by WiFi */
/* 0x4c[24:23]= 00, Set Antenna control by BT_RFE_CTRL BT Vendor 0xac = 0xf002 */
u4Tmp = pBtCoexist->fBtcRead4Byte(pBtCoexist, 0x4c);
u4Tmp &= ~BIT23;
u4Tmp &= ~BIT24;
pBtCoexist->fBtcWrite4Byte(pBtCoexist, 0x4c, u4Tmp);
} else {
/* Use H2C to set GNT_BT to LOW */
if (fwVer >= 0x180000) {
if (pBtCoexist->fBtcRead1Byte(pBtCoexist, 0x765) != 0) {
H2C_Parameter[0] = 0;
pBtCoexist->fBtcFillH2c(pBtCoexist, 0x6E, 1, H2C_Parameter);
}
} else {
/* BT calibration check */
while (cntBtCalChk <= 20) {
u1Tmp = pBtCoexist->fBtcRead1Byte(pBtCoexist, 0x49d);
cntBtCalChk++;
if (u1Tmp & BIT0) {
BTC_PRINT(BTC_MSG_INTERFACE, INTF_INIT, ("[BTCoex], ########### BT is calibrating (wait cnt =%d) ###########\n", cntBtCalChk));
mdelay(50);
} else {
BTC_PRINT(BTC_MSG_INTERFACE, INTF_INIT, ("[BTCoex], ********** BT is NOT calibrating (wait cnt =%d)**********\n", cntBtCalChk));
break;
}
}
/* set grant_bt to PTA */
pBtCoexist->fBtcWrite1Byte(pBtCoexist, 0x765, 0x0);
}
if (pBtCoexist->fBtcRead1Byte(pBtCoexist, 0x76e) != 0xc)
/* set wlan_act control by PTA */
pBtCoexist->fBtcWrite1Byte(pBtCoexist, 0x76e, 0xc);
}
if (bUseExtSwitch) {
if (bInitHwCfg) {
/* 0x4c[23]= 0, 0x4c[24]= 1 Antenna control by WL/BT */
u4Tmp = pBtCoexist->fBtcRead4Byte(pBtCoexist, 0x4c);
u4Tmp &= ~BIT23;
u4Tmp |= BIT24;
pBtCoexist->fBtcWrite4Byte(pBtCoexist, 0x4c, u4Tmp);
pBtCoexist->fBtcWrite4Byte(pBtCoexist, 0x948, 0x0); /* fixed internal switch S1->WiFi, S0->BT */
if (pBoardInfo->btdmAntPos == BTC_ANTENNA_AT_MAIN_PORT) {
/* tell firmware "no antenna inverse" */
H2C_Parameter[0] = 0;
H2C_Parameter[1] = 1; /* ext switch type */
pBtCoexist->fBtcFillH2c(pBtCoexist, 0x65, 2, H2C_Parameter);
} else {
/* tell firmware "antenna inverse" */
H2C_Parameter[0] = 1;
H2C_Parameter[1] = 1; /* ext switch type */
pBtCoexist->fBtcFillH2c(pBtCoexist, 0x65, 2, H2C_Parameter);
}
}
/* ext switch setting */
switch (antPosType) {
case BTC_ANT_PATH_WIFI:
if (pBoardInfo->btdmAntPos == BTC_ANTENNA_AT_MAIN_PORT)
pBtCoexist->fBtcWrite1ByteBitMask(pBtCoexist, 0x92c, 0x3, 0x1);
else
pBtCoexist->fBtcWrite1ByteBitMask(pBtCoexist, 0x92c, 0x3, 0x2);
break;
case BTC_ANT_PATH_BT:
if (pBoardInfo->btdmAntPos == BTC_ANTENNA_AT_MAIN_PORT)
pBtCoexist->fBtcWrite1ByteBitMask(pBtCoexist, 0x92c, 0x3, 0x2);
else
pBtCoexist->fBtcWrite1ByteBitMask(pBtCoexist, 0x92c, 0x3, 0x1);
break;
default:
case BTC_ANT_PATH_PTA:
if (pBoardInfo->btdmAntPos == BTC_ANTENNA_AT_MAIN_PORT)
pBtCoexist->fBtcWrite1ByteBitMask(pBtCoexist, 0x92c, 0x3, 0x1);
else
pBtCoexist->fBtcWrite1ByteBitMask(pBtCoexist, 0x92c, 0x3, 0x2);
break;
}
} else {
if (bInitHwCfg) {
/* 0x4c[23]= 1, 0x4c[24]= 0 Antenna control by 0x64 */
u4Tmp = pBtCoexist->fBtcRead4Byte(pBtCoexist, 0x4c);
u4Tmp |= BIT23;
u4Tmp &= ~BIT24;
pBtCoexist->fBtcWrite4Byte(pBtCoexist, 0x4c, u4Tmp);
/* Fix Ext switch Main->S1, Aux->S0 */
pBtCoexist->fBtcWrite1ByteBitMask(pBtCoexist, 0x64, 0x1, 0x0);
if (pBoardInfo->btdmAntPos == BTC_ANTENNA_AT_MAIN_PORT) {
/* tell firmware "no antenna inverse" */
H2C_Parameter[0] = 0;
H2C_Parameter[1] = 0; /* internal switch type */
pBtCoexist->fBtcFillH2c(pBtCoexist, 0x65, 2, H2C_Parameter);
} else {
/* tell firmware "antenna inverse" */
H2C_Parameter[0] = 1;
H2C_Parameter[1] = 0; /* internal switch type */
pBtCoexist->fBtcFillH2c(pBtCoexist, 0x65, 2, H2C_Parameter);
}
}
/* internal switch setting */
switch (antPosType) {
case BTC_ANT_PATH_WIFI:
if (pBoardInfo->btdmAntPos == BTC_ANTENNA_AT_MAIN_PORT)
pBtCoexist->fBtcWrite4Byte(pBtCoexist, 0x948, 0x0);
else
pBtCoexist->fBtcWrite4Byte(pBtCoexist, 0x948, 0x280);
break;
case BTC_ANT_PATH_BT:
if (pBoardInfo->btdmAntPos == BTC_ANTENNA_AT_MAIN_PORT)
pBtCoexist->fBtcWrite4Byte(pBtCoexist, 0x948, 0x280);
else
pBtCoexist->fBtcWrite4Byte(pBtCoexist, 0x948, 0x0);
break;
default:
case BTC_ANT_PATH_PTA:
if (pBoardInfo->btdmAntPos == BTC_ANTENNA_AT_MAIN_PORT)
pBtCoexist->fBtcWrite4Byte(pBtCoexist, 0x948, 0x200);
else
pBtCoexist->fBtcWrite4Byte(pBtCoexist, 0x948, 0x80);
break;
}
}
}
static void halbtc8723b1ant_SetFwPstdma(
PBTC_COEXIST pBtCoexist, u8 byte1, u8 byte2, u8 byte3, u8 byte4, u8 byte5
)
{
u8 H2C_Parameter[5] = {0};
u8 realByte1 = byte1, realByte5 = byte5;
bool bApEnable = false;
pBtCoexist->fBtcGet(pBtCoexist, BTC_GET_BL_WIFI_AP_MODE_ENABLE, &bApEnable);
if (bApEnable) {
if (byte1&BIT4 && !(byte1&BIT5)) {
BTC_PRINT(
BTC_MSG_INTERFACE,
INTF_NOTIFY,
("[BTCoex], FW for 1Ant AP mode\n")
);
realByte1 &= ~BIT4;
realByte1 |= BIT5;
realByte5 |= BIT5;
realByte5 &= ~BIT6;
}
}
H2C_Parameter[0] = realByte1;
H2C_Parameter[1] = byte2;
H2C_Parameter[2] = byte3;
H2C_Parameter[3] = byte4;
H2C_Parameter[4] = realByte5;
pCoexDm->psTdmaPara[0] = realByte1;
pCoexDm->psTdmaPara[1] = byte2;
pCoexDm->psTdmaPara[2] = byte3;
pCoexDm->psTdmaPara[3] = byte4;
pCoexDm->psTdmaPara[4] = realByte5;
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_TRACE_FW_EXEC,
(
"[BTCoex], PS-TDMA H2C cmd = 0x%x%08x\n",
H2C_Parameter[0],
H2C_Parameter[1]<<24|
H2C_Parameter[2]<<16|
H2C_Parameter[3]<<8|
H2C_Parameter[4]
)
);
pBtCoexist->fBtcFillH2c(pBtCoexist, 0x60, 5, H2C_Parameter);
}
static void halbtc8723b1ant_PsTdma(
PBTC_COEXIST pBtCoexist, bool bForceExec, bool bTurnOn, u8 type
)
{
PBTC_BT_LINK_INFO pBtLinkInfo = &pBtCoexist->btLinkInfo;
bool bWifiBusy = false;
u8 rssiAdjustVal = 0;
u8 psTdmaByte4Val = 0x50, psTdmaByte0Val = 0x51, psTdmaByte3Val = 0x10;
s8 nWiFiDurationAdjust = 0x0;
/* u32 fwVer = 0; */
/* BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE_FW, ("[BTCoex], %s turn %s PS TDMA, type =%d\n", */
/* (bForceExec? "force to":""), (bTurnOn? "ON":"OFF"), type)); */
pCoexDm->bCurPsTdmaOn = bTurnOn;
pCoexDm->curPsTdma = type;
pBtCoexist->fBtcGet(pBtCoexist, BTC_GET_BL_WIFI_BUSY, &bWifiBusy);
if (pCoexDm->bCurPsTdmaOn) {
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_TRACE,
(
"[BTCoex], ********** TDMA(on, %d) **********\n",
pCoexDm->curPsTdma
)
);
} else {
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_TRACE,
(
"[BTCoex], ********** TDMA(off, %d) **********\n",
pCoexDm->curPsTdma
)
);
}
if (!bForceExec) {
if (
(pCoexDm->bPrePsTdmaOn == pCoexDm->bCurPsTdmaOn) &&
(pCoexDm->prePsTdma == pCoexDm->curPsTdma)
)
return;
}
if (pCoexSta->nScanAPNum <= 5)
nWiFiDurationAdjust = 5;
else if (pCoexSta->nScanAPNum >= 40)
nWiFiDurationAdjust = -15;
else if (pCoexSta->nScanAPNum >= 20)
nWiFiDurationAdjust = -10;
if (!pCoexSta->bForceLpsOn) { /* only for A2DP-only case 1/2/9/11 */
psTdmaByte0Val = 0x61; /* no null-pkt */
psTdmaByte3Val = 0x11; /* no tx-pause at BT-slot */
psTdmaByte4Val = 0x10; /* 0x778 = d/1 toggle */
}
if (bTurnOn) {
if (pBtLinkInfo->bSlaveRole)
psTdmaByte4Val = psTdmaByte4Val | 0x1; /* 0x778 = 0x1 at wifi slot (no blocking BT Low-Pri pkts) */
switch (type) {
default:
halbtc8723b1ant_SetFwPstdma(
pBtCoexist, 0x51, 0x1a, 0x1a, 0x0, psTdmaByte4Val
);
break;
case 1:
halbtc8723b1ant_SetFwPstdma(
pBtCoexist,
psTdmaByte0Val,
0x3a+nWiFiDurationAdjust,
0x03,
psTdmaByte3Val,
psTdmaByte4Val
);
break;
case 2:
halbtc8723b1ant_SetFwPstdma(
pBtCoexist,
psTdmaByte0Val,
0x2d+nWiFiDurationAdjust,
0x03,
psTdmaByte3Val,
psTdmaByte4Val
);
break;
case 3:
halbtc8723b1ant_SetFwPstdma(
pBtCoexist, 0x51, 0x1d, 0x1d, 0x0, 0x10
);
break;
case 4:
halbtc8723b1ant_SetFwPstdma(
pBtCoexist, 0x93, 0x15, 0x3, 0x14, 0x0
);
break;
case 5:
halbtc8723b1ant_SetFwPstdma(
pBtCoexist, 0x61, 0x15, 0x3, 0x11, 0x10
);
break;
case 6:
halbtc8723b1ant_SetFwPstdma(
pBtCoexist, 0x61, 0x20, 0x3, 0x11, 0x11
);
break;
case 7:
halbtc8723b1ant_SetFwPstdma(pBtCoexist, 0x13, 0xc, 0x5, 0x0, 0x0);
break;
case 8:
halbtc8723b1ant_SetFwPstdma(
pBtCoexist, 0x93, 0x25, 0x3, 0x10, 0x0
);
break;
case 9:
halbtc8723b1ant_SetFwPstdma(
pBtCoexist,
psTdmaByte0Val,
0x21,
0x3,
psTdmaByte3Val,
psTdmaByte4Val
);
break;
case 10:
halbtc8723b1ant_SetFwPstdma(pBtCoexist, 0x13, 0xa, 0xa, 0x0, 0x40);
break;
case 11:
halbtc8723b1ant_SetFwPstdma(
pBtCoexist,
psTdmaByte0Val,
0x21,
0x03,
psTdmaByte3Val,
psTdmaByte4Val
);
break;
case 12:
halbtc8723b1ant_SetFwPstdma(
pBtCoexist, 0x51, 0x0a, 0x0a, 0x0, 0x50
);
break;
case 13:
halbtc8723b1ant_SetFwPstdma(
pBtCoexist, 0x51, 0x12, 0x12, 0x0, 0x10
);
break;
case 14:
halbtc8723b1ant_SetFwPstdma(
pBtCoexist, 0x51, 0x21, 0x3, 0x10, psTdmaByte4Val
);
break;
case 15:
halbtc8723b1ant_SetFwPstdma(
pBtCoexist, 0x13, 0xa, 0x3, 0x8, 0x0
);
break;
case 16:
halbtc8723b1ant_SetFwPstdma(
pBtCoexist, 0x93, 0x15, 0x3, 0x10, 0x0
);
break;
case 18:
halbtc8723b1ant_SetFwPstdma(
pBtCoexist, 0x93, 0x25, 0x3, 0x10, 0x0
);
break;
case 20:
halbtc8723b1ant_SetFwPstdma(
pBtCoexist, 0x61, 0x3f, 0x03, 0x11, 0x10
);
break;
case 21:
halbtc8723b1ant_SetFwPstdma(
pBtCoexist, 0x61, 0x25, 0x03, 0x11, 0x11
);
break;
case 22:
halbtc8723b1ant_SetFwPstdma(
pBtCoexist, 0x61, 0x25, 0x03, 0x11, 0x10
);
break;
case 23:
halbtc8723b1ant_SetFwPstdma(
pBtCoexist, 0xe3, 0x25, 0x3, 0x31, 0x18
);
break;
case 24:
halbtc8723b1ant_SetFwPstdma(
pBtCoexist, 0xe3, 0x15, 0x3, 0x31, 0x18
);
break;
case 25:
halbtc8723b1ant_SetFwPstdma(
pBtCoexist, 0xe3, 0xa, 0x3, 0x31, 0x18
);
break;
case 26:
halbtc8723b1ant_SetFwPstdma(
pBtCoexist, 0xe3, 0xa, 0x3, 0x31, 0x18
);
break;
case 27:
halbtc8723b1ant_SetFwPstdma(
pBtCoexist, 0xe3, 0x25, 0x3, 0x31, 0x98
);
break;
case 28:
halbtc8723b1ant_SetFwPstdma(
pBtCoexist, 0x69, 0x25, 0x3, 0x31, 0x0
);
break;
case 29:
halbtc8723b1ant_SetFwPstdma(
pBtCoexist, 0xab, 0x1a, 0x1a, 0x1, 0x10
);
break;
case 30:
halbtc8723b1ant_SetFwPstdma(
pBtCoexist, 0x51, 0x30, 0x3, 0x10, 0x10
);
break;
case 31:
halbtc8723b1ant_SetFwPstdma(
pBtCoexist, 0xd3, 0x1a, 0x1a, 0x0, 0x58
);
break;
case 32:
halbtc8723b1ant_SetFwPstdma(
pBtCoexist, 0x61, 0x35, 0x3, 0x11, 0x11
);
break;
case 33:
halbtc8723b1ant_SetFwPstdma(
pBtCoexist, 0xa3, 0x25, 0x3, 0x30, 0x90
);
break;
case 34:
halbtc8723b1ant_SetFwPstdma(
pBtCoexist, 0x53, 0x1a, 0x1a, 0x0, 0x10
);
break;
case 35:
halbtc8723b1ant_SetFwPstdma(
pBtCoexist, 0x63, 0x1a, 0x1a, 0x0, 0x10
);
break;
case 36:
halbtc8723b1ant_SetFwPstdma(
pBtCoexist, 0xd3, 0x12, 0x3, 0x14, 0x50
);
break;
case 40: /* SoftAP only with no sta associated, BT disable , TDMA mode for power saving */
/* here softap mode screen off will cost 70-80mA for phone */
halbtc8723b1ant_SetFwPstdma(
pBtCoexist, 0x23, 0x18, 0x00, 0x10, 0x24
);
break;
}
} else {
/* disable PS tdma */
switch (type) {
case 8: /* PTA Control */
halbtc8723b1ant_SetFwPstdma(pBtCoexist, 0x8, 0x0, 0x0, 0x0, 0x0);
halbtc8723b1ant_SetAntPath(
pBtCoexist, BTC_ANT_PATH_PTA, false, false
);
break;
case 0:
default: /* Software control, Antenna at BT side */
halbtc8723b1ant_SetFwPstdma(pBtCoexist, 0x0, 0x0, 0x0, 0x0, 0x0);
halbtc8723b1ant_SetAntPath(
pBtCoexist, BTC_ANT_PATH_BT, false, false
);
break;
case 9: /* Software control, Antenna at WiFi side */
halbtc8723b1ant_SetFwPstdma(pBtCoexist, 0x0, 0x0, 0x0, 0x0, 0x0);
halbtc8723b1ant_SetAntPath(
pBtCoexist, BTC_ANT_PATH_WIFI, false, false
);
break;
}
}
rssiAdjustVal = 0;
pBtCoexist->fBtcSet(
pBtCoexist, BTC_SET_U1_RSSI_ADJ_VAL_FOR_1ANT_COEX_TYPE, &rssiAdjustVal
);
/* update pre state */
pCoexDm->bPrePsTdmaOn = pCoexDm->bCurPsTdmaOn;
pCoexDm->prePsTdma = pCoexDm->curPsTdma;
}
static bool halbtc8723b1ant_IsCommonAction(PBTC_COEXIST pBtCoexist)
{
bool bCommon = false, bWifiConnected = false, bWifiBusy = false;
pBtCoexist->fBtcGet(pBtCoexist, BTC_GET_BL_WIFI_CONNECTED, &bWifiConnected);
pBtCoexist->fBtcGet(pBtCoexist, BTC_GET_BL_WIFI_BUSY, &bWifiBusy);
if (
!bWifiConnected &&
BT_8723B_1ANT_BT_STATUS_NON_CONNECTED_IDLE == pCoexDm->btStatus
) {
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_TRACE,
("[BTCoex], Wifi non connected-idle + BT non connected-idle!!\n")
);
/* halbtc8723b1ant_SwMechanism(pBtCoexist, false); */
bCommon = true;
} else if (
bWifiConnected &&
(BT_8723B_1ANT_BT_STATUS_NON_CONNECTED_IDLE == pCoexDm->btStatus)
) {
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_TRACE,
("[BTCoex], Wifi connected + BT non connected-idle!!\n")
);
/* halbtc8723b1ant_SwMechanism(pBtCoexist, false); */
bCommon = true;
} else if (
!bWifiConnected &&
(BT_8723B_1ANT_BT_STATUS_CONNECTED_IDLE == pCoexDm->btStatus)
) {
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_TRACE,
("[BTCoex], Wifi non connected-idle + BT connected-idle!!\n")
);
/* halbtc8723b1ant_SwMechanism(pBtCoexist, false); */
bCommon = true;
} else if (
bWifiConnected &&
(BT_8723B_1ANT_BT_STATUS_CONNECTED_IDLE == pCoexDm->btStatus)
) {
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE, ("[BTCoex], Wifi connected + BT connected-idle!!\n"));
/* halbtc8723b1ant_SwMechanism(pBtCoexist, false); */
bCommon = true;
} else if (
!bWifiConnected &&
(BT_8723B_1ANT_BT_STATUS_CONNECTED_IDLE != pCoexDm->btStatus)
) {
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_TRACE,
("[BTCoex], Wifi non connected-idle + BT Busy!!\n")
);
/* halbtc8723b1ant_SwMechanism(pBtCoexist, false); */
bCommon = true;
} else {
if (bWifiBusy) {
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_TRACE,
("[BTCoex], Wifi Connected-Busy + BT Busy!!\n")
);
} else {
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_TRACE,
("[BTCoex], Wifi Connected-Idle + BT Busy!!\n")
);
}
bCommon = false;
}
return bCommon;
}
static void halbtc8723b1ant_TdmaDurationAdjustForAcl(
PBTC_COEXIST pBtCoexist, u8 wifiStatus
)
{
static s32 up, dn, m, n, WaitCount;
s32 result; /* 0: no change, +1: increase WiFi duration, -1: decrease WiFi duration */
u8 retryCount = 0, btInfoExt;
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_TRACE_FW,
("[BTCoex], TdmaDurationAdjustForAcl()\n")
);
if (
(BT_8723B_1ANT_WIFI_STATUS_NON_CONNECTED_ASSO_AUTH_SCAN == wifiStatus) ||
(BT_8723B_1ANT_WIFI_STATUS_CONNECTED_SCAN == wifiStatus) ||
(BT_8723B_1ANT_WIFI_STATUS_CONNECTED_SPECIAL_PKT == wifiStatus)
) {
if (
pCoexDm->curPsTdma != 1 &&
pCoexDm->curPsTdma != 2 &&
pCoexDm->curPsTdma != 3 &&
pCoexDm->curPsTdma != 9
) {
halbtc8723b1ant_PsTdma(pBtCoexist, NORMAL_EXEC, true, 9);
pCoexDm->psTdmaDuAdjType = 9;
up = 0;
dn = 0;
m = 1;
n = 3;
result = 0;
WaitCount = 0;
}
return;
}
if (!pCoexDm->bAutoTdmaAdjust) {
pCoexDm->bAutoTdmaAdjust = true;
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_TRACE_FW_DETAIL,
("[BTCoex], first run TdmaDurationAdjust()!!\n")
);
halbtc8723b1ant_PsTdma(pBtCoexist, NORMAL_EXEC, true, 2);
pCoexDm->psTdmaDuAdjType = 2;
/* */
up = 0;
dn = 0;
m = 1;
n = 3;
result = 0;
WaitCount = 0;
} else {
/* acquire the BT TRx retry count from BT_Info byte2 */
retryCount = pCoexSta->btRetryCnt;
btInfoExt = pCoexSta->btInfoExt;
/* BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE_FW_DETAIL, ("[BTCoex], retryCount = %d\n", retryCount)); */
/* BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE_FW_DETAIL, ("[BTCoex], up =%d, dn =%d, m =%d, n =%d, WaitCount =%d\n", */
/* up, dn, m, n, WaitCount)); */
if (pCoexSta->lowPriorityTx > 1050 || pCoexSta->lowPriorityRx > 1250)
retryCount++;
result = 0;
WaitCount++;
if (retryCount == 0) { /* no retry in the last 2-second duration */
up++;
dn--;
if (dn <= 0)
dn = 0;
if (up >= n) { /* if 連續 n 個2秒 retry count為0, 則調寬WiFi duration */
WaitCount = 0;
n = 3;
up = 0;
dn = 0;
result = 1;
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_TRACE_FW_DETAIL,
("[BTCoex], Increase wifi duration!!\n")
);
}
} else if (retryCount <= 3) { /* <=3 retry in the last 2-second duration */
up--;
dn++;
if (up <= 0)
up = 0;
if (dn == 2) { /* if 連續 2 個2秒 retry count< 3, 則調窄WiFi duration */
if (WaitCount <= 2)
m++; /* 避免一直在兩個level中來回 */
else
m = 1;
if (m >= 20) /* m 最大值 = 20 ' 最大120秒 recheck是否調整 WiFi duration. */
m = 20;
n = 3*m;
up = 0;
dn = 0;
WaitCount = 0;
result = -1;
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE_FW_DETAIL, ("[BTCoex], Decrease wifi duration for retryCounter<3!!\n"));
}
} else { /* retry count > 3, 只要1次 retry count > 3, 則調窄WiFi duration */
if (WaitCount == 1)
m++; /* 避免一直在兩個level中來回 */
else
m = 1;
if (m >= 20) /* m 最大值 = 20 ' 最大120秒 recheck是否調整 WiFi duration. */
m = 20;
n = 3*m;
up = 0;
dn = 0;
WaitCount = 0;
result = -1;
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_TRACE_FW_DETAIL,
("[BTCoex], Decrease wifi duration for retryCounter>3!!\n")
);
}
if (result == -1) {
if (
BT_INFO_8723B_1ANT_A2DP_BASIC_RATE(btInfoExt) &&
((pCoexDm->curPsTdma == 1) || (pCoexDm->curPsTdma == 2))
) {
halbtc8723b1ant_PsTdma(pBtCoexist, NORMAL_EXEC, true, 9);
pCoexDm->psTdmaDuAdjType = 9;
} else if (pCoexDm->curPsTdma == 1) {
halbtc8723b1ant_PsTdma(pBtCoexist, NORMAL_EXEC, true, 2);
pCoexDm->psTdmaDuAdjType = 2;
} else if (pCoexDm->curPsTdma == 2) {
halbtc8723b1ant_PsTdma(pBtCoexist, NORMAL_EXEC, true, 9);
pCoexDm->psTdmaDuAdjType = 9;
} else if (pCoexDm->curPsTdma == 9) {
halbtc8723b1ant_PsTdma(pBtCoexist, NORMAL_EXEC, true, 11);
pCoexDm->psTdmaDuAdjType = 11;
}
} else if (result == 1) {
if (
BT_INFO_8723B_1ANT_A2DP_BASIC_RATE(btInfoExt) &&
((pCoexDm->curPsTdma == 1) || (pCoexDm->curPsTdma == 2))
) {
halbtc8723b1ant_PsTdma(pBtCoexist, NORMAL_EXEC, true, 9);
pCoexDm->psTdmaDuAdjType = 9;
} else if (pCoexDm->curPsTdma == 11) {
halbtc8723b1ant_PsTdma(pBtCoexist, NORMAL_EXEC, true, 9);
pCoexDm->psTdmaDuAdjType = 9;
} else if (pCoexDm->curPsTdma == 9) {
halbtc8723b1ant_PsTdma(pBtCoexist, NORMAL_EXEC, true, 2);
pCoexDm->psTdmaDuAdjType = 2;
} else if (pCoexDm->curPsTdma == 2) {
halbtc8723b1ant_PsTdma(pBtCoexist, NORMAL_EXEC, true, 1);
pCoexDm->psTdmaDuAdjType = 1;
}
} else { /* no change */
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_TRACE_FW_DETAIL,
(
"[BTCoex], ********** TDMA(on, %d) **********\n",
pCoexDm->curPsTdma
)
);
}
if (
pCoexDm->curPsTdma != 1 &&
pCoexDm->curPsTdma != 2 &&
pCoexDm->curPsTdma != 9 &&
pCoexDm->curPsTdma != 11
) /* recover to previous adjust type */
halbtc8723b1ant_PsTdma(
pBtCoexist, NORMAL_EXEC, true, pCoexDm->psTdmaDuAdjType
);
}
}
static void halbtc8723b1ant_PsTdmaCheckForPowerSaveState(
PBTC_COEXIST pBtCoexist, bool bNewPsState
)
{
u8 lpsMode = 0x0;
pBtCoexist->fBtcGet(pBtCoexist, BTC_GET_U1_LPS_MODE, &lpsMode);
if (lpsMode) { /* already under LPS state */
if (bNewPsState) {
/* keep state under LPS, do nothing. */
} else /* will leave LPS state, turn off psTdma first */
halbtc8723b1ant_PsTdma(pBtCoexist, NORMAL_EXEC, false, 0);
} else { /* NO PS state */
if (bNewPsState) /* will enter LPS state, turn off psTdma first */
halbtc8723b1ant_PsTdma(pBtCoexist, NORMAL_EXEC, false, 0);
else {
/* keep state under NO PS state, do nothing. */
}
}
}
static void halbtc8723b1ant_PowerSaveState(
PBTC_COEXIST pBtCoexist, u8 psType, u8 lpsVal, u8 rpwmVal
)
{
bool bLowPwrDisable = false;
switch (psType) {
case BTC_PS_WIFI_NATIVE:
/* recover to original 32k low power setting */
bLowPwrDisable = false;
pBtCoexist->fBtcSet(
pBtCoexist, BTC_SET_ACT_DISABLE_LOW_POWER, &bLowPwrDisable
);
pBtCoexist->fBtcSet(pBtCoexist, BTC_SET_ACT_NORMAL_LPS, NULL);
pCoexSta->bForceLpsOn = false;
break;
case BTC_PS_LPS_ON:
halbtc8723b1ant_PsTdmaCheckForPowerSaveState(pBtCoexist, true);
halbtc8723b1ant_LpsRpwm(pBtCoexist, NORMAL_EXEC, lpsVal, rpwmVal);
/* when coex force to enter LPS, do not enter 32k low power. */
bLowPwrDisable = true;
pBtCoexist->fBtcSet(
pBtCoexist, BTC_SET_ACT_DISABLE_LOW_POWER, &bLowPwrDisable
);
/* power save must executed before psTdma. */
pBtCoexist->fBtcSet(pBtCoexist, BTC_SET_ACT_ENTER_LPS, NULL);
pCoexSta->bForceLpsOn = true;
break;
case BTC_PS_LPS_OFF:
halbtc8723b1ant_PsTdmaCheckForPowerSaveState(pBtCoexist, false);
pBtCoexist->fBtcSet(pBtCoexist, BTC_SET_ACT_LEAVE_LPS, NULL);
pCoexSta->bForceLpsOn = false;
break;
default:
break;
}
}
/* */
/* */
/* Software Coex Mechanism start */
/* */
/* */
/* */
/* */
/* Non-Software Coex Mechanism start */
/* */
/* */
static void halbtc8723b1ant_ActionWifiMultiPort(PBTC_COEXIST pBtCoexist)
{
halbtc8723b1ant_PowerSaveState(pBtCoexist, BTC_PS_WIFI_NATIVE, 0x0, 0x0);
halbtc8723b1ant_PsTdma(pBtCoexist, NORMAL_EXEC, false, 8);
halbtc8723b1ant_CoexTableWithType(pBtCoexist, NORMAL_EXEC, 2);
}
static void halbtc8723b1ant_ActionHs(PBTC_COEXIST pBtCoexist)
{
halbtc8723b1ant_PsTdma(pBtCoexist, NORMAL_EXEC, true, 5);
halbtc8723b1ant_CoexTableWithType(pBtCoexist, NORMAL_EXEC, 2);
}
static void halbtc8723b1ant_ActionBtInquiry(PBTC_COEXIST pBtCoexist)
{
PBTC_BT_LINK_INFO pBtLinkInfo = &pBtCoexist->btLinkInfo;
bool bWifiConnected = false;
bool bApEnable = false;
bool bWifiBusy = false;
bool bBtBusy = false;
pBtCoexist->fBtcGet(pBtCoexist, BTC_GET_BL_WIFI_AP_MODE_ENABLE, &bApEnable);
pBtCoexist->fBtcGet(pBtCoexist, BTC_GET_BL_WIFI_CONNECTED, &bWifiConnected);
pBtCoexist->fBtcGet(pBtCoexist, BTC_GET_BL_WIFI_BUSY, &bWifiBusy);
pBtCoexist->fBtcSet(pBtCoexist, BTC_SET_BL_BT_TRAFFIC_BUSY, &bBtBusy);
if (!bWifiConnected && !pCoexSta->bWiFiIsHighPriTask) {
halbtc8723b1ant_PowerSaveState(pBtCoexist, BTC_PS_WIFI_NATIVE, 0x0, 0x0);
halbtc8723b1ant_PsTdma(pBtCoexist, NORMAL_EXEC, false, 8);
halbtc8723b1ant_CoexTableWithType(pBtCoexist, NORMAL_EXEC, 0);
} else if (
pBtLinkInfo->bScoExist ||
pBtLinkInfo->bHidExist ||
pBtLinkInfo->bA2dpExist
) {
/* SCO/HID/A2DP busy */
halbtc8723b1ant_PowerSaveState(pBtCoexist, BTC_PS_WIFI_NATIVE, 0x0, 0x0);
halbtc8723b1ant_PsTdma(pBtCoexist, NORMAL_EXEC, true, 32);
halbtc8723b1ant_CoexTableWithType(pBtCoexist, NORMAL_EXEC, 4);
} else if (pBtLinkInfo->bPanExist || bWifiBusy) {
halbtc8723b1ant_PowerSaveState(pBtCoexist, BTC_PS_WIFI_NATIVE, 0x0, 0x0);
halbtc8723b1ant_PsTdma(pBtCoexist, NORMAL_EXEC, true, 20);
halbtc8723b1ant_CoexTableWithType(pBtCoexist, NORMAL_EXEC, 4);
} else {
halbtc8723b1ant_PowerSaveState(pBtCoexist, BTC_PS_WIFI_NATIVE, 0x0, 0x0);
halbtc8723b1ant_PsTdma(pBtCoexist, NORMAL_EXEC, false, 8);
halbtc8723b1ant_CoexTableWithType(pBtCoexist, NORMAL_EXEC, 7);
}
}
static void halbtc8723b1ant_ActionBtScoHidOnlyBusy(
PBTC_COEXIST pBtCoexist, u8 wifiStatus
)
{
PBTC_BT_LINK_INFO pBtLinkInfo = &pBtCoexist->btLinkInfo;
bool bWifiConnected = false;
pBtCoexist->fBtcGet(pBtCoexist, BTC_GET_BL_WIFI_CONNECTED, &bWifiConnected);
/* tdma and coex table */
if (pBtLinkInfo->bScoExist) {
halbtc8723b1ant_PsTdma(pBtCoexist, NORMAL_EXEC, true, 5);
halbtc8723b1ant_CoexTableWithType(pBtCoexist, NORMAL_EXEC, 5);
} else { /* HID */
halbtc8723b1ant_PsTdma(pBtCoexist, NORMAL_EXEC, true, 6);
halbtc8723b1ant_CoexTableWithType(pBtCoexist, NORMAL_EXEC, 5);
}
}
static void halbtc8723b1ant_ActionWifiConnectedBtAclBusy(
PBTC_COEXIST pBtCoexist, u8 wifiStatus
)
{
u8 btRssiState;
PBTC_BT_LINK_INFO pBtLinkInfo = &pBtCoexist->btLinkInfo;
btRssiState = halbtc8723b1ant_BtRssiState(2, 28, 0);
if ((pCoexSta->lowPriorityRx >= 1000) && (pCoexSta->lowPriorityRx != 65535))
pBtLinkInfo->bSlaveRole = true;
else
pBtLinkInfo->bSlaveRole = false;
if (pBtLinkInfo->bHidOnly) { /* HID */
halbtc8723b1ant_ActionBtScoHidOnlyBusy(pBtCoexist, wifiStatus);
pCoexDm->bAutoTdmaAdjust = false;
return;
} else if (pBtLinkInfo->bA2dpOnly) { /* A2DP */
if (BT_8723B_1ANT_WIFI_STATUS_CONNECTED_IDLE == wifiStatus) {
halbtc8723b1ant_PsTdma(pBtCoexist, NORMAL_EXEC, true, 32);
halbtc8723b1ant_CoexTableWithType(pBtCoexist, NORMAL_EXEC, 4);
pCoexDm->bAutoTdmaAdjust = false;
} else {
halbtc8723b1ant_TdmaDurationAdjustForAcl(pBtCoexist, wifiStatus);
halbtc8723b1ant_CoexTableWithType(pBtCoexist, NORMAL_EXEC, 4);
pCoexDm->bAutoTdmaAdjust = true;
}
} else if (pBtLinkInfo->bHidExist && pBtLinkInfo->bA2dpExist) { /* HID+A2DP */
halbtc8723b1ant_PsTdma(pBtCoexist, NORMAL_EXEC, true, 14);
pCoexDm->bAutoTdmaAdjust = false;
halbtc8723b1ant_CoexTableWithType(pBtCoexist, NORMAL_EXEC, 4);
} else if (
pBtLinkInfo->bPanOnly ||
(pBtLinkInfo->bHidExist && pBtLinkInfo->bPanExist)
) { /* PAN(OPP, FTP), HID+PAN(OPP, FTP) */
halbtc8723b1ant_PsTdma(pBtCoexist, NORMAL_EXEC, true, 3);
halbtc8723b1ant_CoexTableWithType(pBtCoexist, NORMAL_EXEC, 4);
pCoexDm->bAutoTdmaAdjust = false;
} else if (
(pBtLinkInfo->bA2dpExist && pBtLinkInfo->bPanExist) ||
(pBtLinkInfo->bHidExist && pBtLinkInfo->bA2dpExist && pBtLinkInfo->bPanExist)
) { /* A2DP+PAN(OPP, FTP), HID+A2DP+PAN(OPP, FTP) */
halbtc8723b1ant_PsTdma(pBtCoexist, NORMAL_EXEC, true, 13);
halbtc8723b1ant_CoexTableWithType(pBtCoexist, NORMAL_EXEC, 4);
pCoexDm->bAutoTdmaAdjust = false;
} else {
/* BT no-profile busy (0x9) */
halbtc8723b1ant_PsTdma(pBtCoexist, NORMAL_EXEC, true, 32);
halbtc8723b1ant_CoexTableWithType(pBtCoexist, NORMAL_EXEC, 4);
pCoexDm->bAutoTdmaAdjust = false;
}
}
static void halbtc8723b1ant_ActionWifiNotConnected(PBTC_COEXIST pBtCoexist)
{
/* power save state */
halbtc8723b1ant_PowerSaveState(pBtCoexist, BTC_PS_WIFI_NATIVE, 0x0, 0x0);
/* tdma and coex table */
halbtc8723b1ant_PsTdma(pBtCoexist, FORCE_EXEC, false, 8);
halbtc8723b1ant_CoexTableWithType(pBtCoexist, NORMAL_EXEC, 0);
}
static void halbtc8723b1ant_ActionWifiNotConnectedScan(
PBTC_COEXIST pBtCoexist
)
{
PBTC_BT_LINK_INFO pBtLinkInfo = &pBtCoexist->btLinkInfo;
halbtc8723b1ant_PowerSaveState(pBtCoexist, BTC_PS_WIFI_NATIVE, 0x0, 0x0);
/* tdma and coex table */
if (BT_8723B_1ANT_BT_STATUS_ACL_BUSY == pCoexDm->btStatus) {
if (pBtLinkInfo->bA2dpExist) {
halbtc8723b1ant_PsTdma(pBtCoexist, NORMAL_EXEC, true, 32);
halbtc8723b1ant_CoexTableWithType(pBtCoexist, NORMAL_EXEC, 4);
} else if (pBtLinkInfo->bA2dpExist && pBtLinkInfo->bPanExist) {
halbtc8723b1ant_PsTdma(pBtCoexist, NORMAL_EXEC, true, 22);
halbtc8723b1ant_CoexTableWithType(pBtCoexist, NORMAL_EXEC, 4);
} else {
halbtc8723b1ant_PsTdma(pBtCoexist, NORMAL_EXEC, true, 20);
halbtc8723b1ant_CoexTableWithType(pBtCoexist, NORMAL_EXEC, 4);
}
} else if (
(BT_8723B_1ANT_BT_STATUS_SCO_BUSY == pCoexDm->btStatus) ||
(BT_8723B_1ANT_BT_STATUS_ACL_SCO_BUSY == pCoexDm->btStatus)
) {
halbtc8723b1ant_ActionBtScoHidOnlyBusy(
pBtCoexist, BT_8723B_1ANT_WIFI_STATUS_CONNECTED_SCAN
);
} else {
/* Bryant Add */
halbtc8723b1ant_PsTdma(pBtCoexist, NORMAL_EXEC, false, 8);
halbtc8723b1ant_CoexTableWithType(pBtCoexist, NORMAL_EXEC, 2);
}
}
static void halbtc8723b1ant_ActionWifiNotConnectedAssoAuth(
PBTC_COEXIST pBtCoexist
)
{
PBTC_BT_LINK_INFO pBtLinkInfo = &pBtCoexist->btLinkInfo;
halbtc8723b1ant_PowerSaveState(pBtCoexist, BTC_PS_WIFI_NATIVE, 0x0, 0x0);
/* tdma and coex table */
if (
(pBtLinkInfo->bScoExist) ||
(pBtLinkInfo->bHidExist) ||
(pBtLinkInfo->bA2dpExist)
) {
halbtc8723b1ant_PsTdma(pBtCoexist, NORMAL_EXEC, true, 32);
halbtc8723b1ant_CoexTableWithType(pBtCoexist, NORMAL_EXEC, 4);
} else if (pBtLinkInfo->bPanExist) {
halbtc8723b1ant_PsTdma(pBtCoexist, NORMAL_EXEC, true, 20);
halbtc8723b1ant_CoexTableWithType(pBtCoexist, NORMAL_EXEC, 4);
} else {
halbtc8723b1ant_PsTdma(pBtCoexist, NORMAL_EXEC, false, 8);
halbtc8723b1ant_CoexTableWithType(pBtCoexist, NORMAL_EXEC, 2);
}
}
static void halbtc8723b1ant_ActionWifiConnectedScan(PBTC_COEXIST pBtCoexist)
{
PBTC_BT_LINK_INFO pBtLinkInfo = &pBtCoexist->btLinkInfo;
halbtc8723b1ant_PowerSaveState(pBtCoexist, BTC_PS_WIFI_NATIVE, 0x0, 0x0);
/* tdma and coex table */
if (BT_8723B_1ANT_BT_STATUS_ACL_BUSY == pCoexDm->btStatus) {
if (pBtLinkInfo->bA2dpExist) {
halbtc8723b1ant_PsTdma(pBtCoexist, NORMAL_EXEC, true, 32);
halbtc8723b1ant_CoexTableWithType(pBtCoexist, NORMAL_EXEC, 4);
} else if (pBtLinkInfo->bA2dpExist && pBtLinkInfo->bPanExist) {
halbtc8723b1ant_PsTdma(pBtCoexist, NORMAL_EXEC, true, 22);
halbtc8723b1ant_CoexTableWithType(pBtCoexist, NORMAL_EXEC, 4);
} else {
halbtc8723b1ant_PsTdma(pBtCoexist, NORMAL_EXEC, true, 20);
halbtc8723b1ant_CoexTableWithType(pBtCoexist, NORMAL_EXEC, 4);
}
} else if (
(BT_8723B_1ANT_BT_STATUS_SCO_BUSY == pCoexDm->btStatus) ||
(BT_8723B_1ANT_BT_STATUS_ACL_SCO_BUSY == pCoexDm->btStatus)
) {
halbtc8723b1ant_ActionBtScoHidOnlyBusy(
pBtCoexist, BT_8723B_1ANT_WIFI_STATUS_CONNECTED_SCAN
);
} else {
/* Bryant Add */
halbtc8723b1ant_PsTdma(pBtCoexist, NORMAL_EXEC, false, 8);
halbtc8723b1ant_CoexTableWithType(pBtCoexist, NORMAL_EXEC, 2);
}
}
static void halbtc8723b1ant_ActionWifiConnectedSpecialPacket(
PBTC_COEXIST pBtCoexist
)
{
PBTC_BT_LINK_INFO pBtLinkInfo = &pBtCoexist->btLinkInfo;
halbtc8723b1ant_PowerSaveState(pBtCoexist, BTC_PS_WIFI_NATIVE, 0x0, 0x0);
/* tdma and coex table */
if (
(pBtLinkInfo->bScoExist) ||
(pBtLinkInfo->bHidExist) ||
(pBtLinkInfo->bA2dpExist)
) {
halbtc8723b1ant_PsTdma(pBtCoexist, NORMAL_EXEC, true, 32);
halbtc8723b1ant_CoexTableWithType(pBtCoexist, NORMAL_EXEC, 4);
} else if (pBtLinkInfo->bPanExist) {
halbtc8723b1ant_PsTdma(pBtCoexist, NORMAL_EXEC, true, 20);
halbtc8723b1ant_CoexTableWithType(pBtCoexist, NORMAL_EXEC, 4);
} else {
halbtc8723b1ant_PsTdma(pBtCoexist, NORMAL_EXEC, false, 8);
halbtc8723b1ant_CoexTableWithType(pBtCoexist, NORMAL_EXEC, 2);
}
}
static void halbtc8723b1ant_ActionWifiConnected(PBTC_COEXIST pBtCoexist)
{
bool bWifiBusy = false;
bool bScan = false, bLink = false, bRoam = false;
bool bUnder4way = false, bApEnable = false;
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_TRACE,
("[BTCoex], CoexForWifiConnect() ===>\n")
);
pBtCoexist->fBtcGet(pBtCoexist, BTC_GET_BL_WIFI_4_WAY_PROGRESS, &bUnder4way);
if (bUnder4way) {
halbtc8723b1ant_ActionWifiConnectedSpecialPacket(pBtCoexist);
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_TRACE,
("[BTCoex], CoexForWifiConnect(), return for wifi is under 4way<===\n")
);
return;
}
pBtCoexist->fBtcGet(pBtCoexist, BTC_GET_BL_WIFI_SCAN, &bScan);
pBtCoexist->fBtcGet(pBtCoexist, BTC_GET_BL_WIFI_LINK, &bLink);
pBtCoexist->fBtcGet(pBtCoexist, BTC_GET_BL_WIFI_ROAM, &bRoam);
if (bScan || bLink || bRoam) {
if (bScan)
halbtc8723b1ant_ActionWifiConnectedScan(pBtCoexist);
else
halbtc8723b1ant_ActionWifiConnectedSpecialPacket(pBtCoexist);
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_TRACE,
("[BTCoex], CoexForWifiConnect(), return for wifi is under scan<===\n")
);
return;
}
pBtCoexist->fBtcGet(pBtCoexist, BTC_GET_BL_WIFI_AP_MODE_ENABLE, &bApEnable);
pBtCoexist->fBtcGet(pBtCoexist, BTC_GET_BL_WIFI_BUSY, &bWifiBusy);
/* power save state */
if (
!bApEnable &&
BT_8723B_1ANT_BT_STATUS_ACL_BUSY == pCoexDm->btStatus &&
!pBtCoexist->btLinkInfo.bHidOnly
) {
if (pBtCoexist->btLinkInfo.bA2dpOnly) { /* A2DP */
if (!bWifiBusy)
halbtc8723b1ant_PowerSaveState(
pBtCoexist, BTC_PS_WIFI_NATIVE, 0x0, 0x0
);
else { /* busy */
if (pCoexSta->nScanAPNum >= BT_8723B_1ANT_WIFI_NOISY_THRESH) /* no force LPS, no PS-TDMA, use pure TDMA */
halbtc8723b1ant_PowerSaveState(
pBtCoexist, BTC_PS_WIFI_NATIVE, 0x0, 0x0
);
else
halbtc8723b1ant_PowerSaveState(
pBtCoexist, BTC_PS_LPS_ON, 0x50, 0x4
);
}
} else if (
(!pCoexSta->bPanExist) &&
(!pCoexSta->bA2dpExist) &&
(!pCoexSta->bHidExist)
)
halbtc8723b1ant_PowerSaveState(pBtCoexist, BTC_PS_WIFI_NATIVE, 0x0, 0x0);
else
halbtc8723b1ant_PowerSaveState(pBtCoexist, BTC_PS_LPS_ON, 0x50, 0x4);
} else
halbtc8723b1ant_PowerSaveState(pBtCoexist, BTC_PS_WIFI_NATIVE, 0x0, 0x0);
/* tdma and coex table */
if (!bWifiBusy) {
if (BT_8723B_1ANT_BT_STATUS_ACL_BUSY == pCoexDm->btStatus) {
halbtc8723b1ant_ActionWifiConnectedBtAclBusy(
pBtCoexist,
BT_8723B_1ANT_WIFI_STATUS_CONNECTED_IDLE
);
} else if (
(BT_8723B_1ANT_BT_STATUS_SCO_BUSY == pCoexDm->btStatus) ||
(BT_8723B_1ANT_BT_STATUS_ACL_SCO_BUSY == pCoexDm->btStatus)
) {
halbtc8723b1ant_ActionBtScoHidOnlyBusy(pBtCoexist,
BT_8723B_1ANT_WIFI_STATUS_CONNECTED_IDLE);
} else {
halbtc8723b1ant_PsTdma(pBtCoexist, NORMAL_EXEC, false, 8);
if ((pCoexSta->highPriorityTx) + (pCoexSta->highPriorityRx) <= 60)
halbtc8723b1ant_CoexTableWithType(pBtCoexist, NORMAL_EXEC, 2);
else
halbtc8723b1ant_CoexTableWithType(pBtCoexist, NORMAL_EXEC, 7);
}
} else {
if (BT_8723B_1ANT_BT_STATUS_ACL_BUSY == pCoexDm->btStatus) {
halbtc8723b1ant_ActionWifiConnectedBtAclBusy(
pBtCoexist,
BT_8723B_1ANT_WIFI_STATUS_CONNECTED_BUSY
);
} else if (
(BT_8723B_1ANT_BT_STATUS_SCO_BUSY == pCoexDm->btStatus) ||
(BT_8723B_1ANT_BT_STATUS_ACL_SCO_BUSY == pCoexDm->btStatus)
) {
halbtc8723b1ant_ActionBtScoHidOnlyBusy(
pBtCoexist,
BT_8723B_1ANT_WIFI_STATUS_CONNECTED_BUSY
);
} else {
halbtc8723b1ant_PsTdma(pBtCoexist, NORMAL_EXEC, false, 8);
if ((pCoexSta->highPriorityTx) + (pCoexSta->highPriorityRx) <= 60)
halbtc8723b1ant_CoexTableWithType(pBtCoexist, NORMAL_EXEC, 2);
else
halbtc8723b1ant_CoexTableWithType(pBtCoexist, NORMAL_EXEC, 7);
}
}
}
static void halbtc8723b1ant_RunSwCoexistMechanism(PBTC_COEXIST pBtCoexist)
{
u8 algorithm = 0;
algorithm = halbtc8723b1ant_ActionAlgorithm(pBtCoexist);
pCoexDm->curAlgorithm = algorithm;
if (halbtc8723b1ant_IsCommonAction(pBtCoexist)) {
} else {
switch (pCoexDm->curAlgorithm) {
case BT_8723B_1ANT_COEX_ALGO_SCO:
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE, ("[BTCoex], Action algorithm = SCO.\n"));
/* halbtc8723b1ant_ActionSco(pBtCoexist); */
break;
case BT_8723B_1ANT_COEX_ALGO_HID:
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE, ("[BTCoex], Action algorithm = HID.\n"));
/* halbtc8723b1ant_ActionHid(pBtCoexist); */
break;
case BT_8723B_1ANT_COEX_ALGO_A2DP:
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE, ("[BTCoex], Action algorithm = A2DP.\n"));
/* halbtc8723b1ant_ActionA2dp(pBtCoexist); */
break;
case BT_8723B_1ANT_COEX_ALGO_A2DP_PANHS:
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE, ("[BTCoex], Action algorithm = A2DP+PAN(HS).\n"));
/* halbtc8723b1ant_ActionA2dpPanHs(pBtCoexist); */
break;
case BT_8723B_1ANT_COEX_ALGO_PANEDR:
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE, ("[BTCoex], Action algorithm = PAN(EDR).\n"));
/* halbtc8723b1ant_ActionPanEdr(pBtCoexist); */
break;
case BT_8723B_1ANT_COEX_ALGO_PANHS:
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE, ("[BTCoex], Action algorithm = HS mode.\n"));
/* halbtc8723b1ant_ActionPanHs(pBtCoexist); */
break;
case BT_8723B_1ANT_COEX_ALGO_PANEDR_A2DP:
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE, ("[BTCoex], Action algorithm = PAN+A2DP.\n"));
/* halbtc8723b1ant_ActionPanEdrA2dp(pBtCoexist); */
break;
case BT_8723B_1ANT_COEX_ALGO_PANEDR_HID:
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE, ("[BTCoex], Action algorithm = PAN(EDR)+HID.\n"));
/* halbtc8723b1ant_ActionPanEdrHid(pBtCoexist); */
break;
case BT_8723B_1ANT_COEX_ALGO_HID_A2DP_PANEDR:
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE, ("[BTCoex], Action algorithm = HID+A2DP+PAN.\n"));
/* halbtc8723b1ant_ActionHidA2dpPanEdr(pBtCoexist); */
break;
case BT_8723B_1ANT_COEX_ALGO_HID_A2DP:
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE, ("[BTCoex], Action algorithm = HID+A2DP.\n"));
/* halbtc8723b1ant_ActionHidA2dp(pBtCoexist); */
break;
default:
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE, ("[BTCoex], Action algorithm = coexist All Off!!\n"));
break;
}
pCoexDm->preAlgorithm = pCoexDm->curAlgorithm;
}
}
static void halbtc8723b1ant_RunCoexistMechanism(PBTC_COEXIST pBtCoexist)
{
PBTC_BT_LINK_INFO pBtLinkInfo = &pBtCoexist->btLinkInfo;
bool bWifiConnected = false, bBtHsOn = false;
bool bIncreaseScanDevNum = false;
bool bBtCtrlAggBufSize = false;
u8 aggBufSize = 5;
u32 wifiLinkStatus = 0;
u32 numOfWifiLink = 0;
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE, ("[BTCoex], RunCoexistMechanism() ===>\n"));
if (pBtCoexist->bManualControl) {
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE, ("[BTCoex], RunCoexistMechanism(), return for Manual CTRL <===\n"));
return;
}
if (pBtCoexist->bStopCoexDm) {
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE, ("[BTCoex], RunCoexistMechanism(), return for Stop Coex DM <===\n"));
return;
}
if (pCoexSta->bUnderIps) {
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE, ("[BTCoex], wifi is under IPS !!!\n"));
return;
}
if (
(BT_8723B_1ANT_BT_STATUS_ACL_BUSY == pCoexDm->btStatus) ||
(BT_8723B_1ANT_BT_STATUS_SCO_BUSY == pCoexDm->btStatus) ||
(BT_8723B_1ANT_BT_STATUS_ACL_SCO_BUSY == pCoexDm->btStatus)
){
bIncreaseScanDevNum = true;
}
pBtCoexist->fBtcSet(
pBtCoexist,
BTC_SET_BL_INC_SCAN_DEV_NUM,
&bIncreaseScanDevNum
);
pBtCoexist->fBtcGet(
pBtCoexist,
BTC_GET_BL_WIFI_CONNECTED,
&bWifiConnected
);
pBtCoexist->fBtcGet(
pBtCoexist,
BTC_GET_U4_WIFI_LINK_STATUS,
&wifiLinkStatus
);
numOfWifiLink = wifiLinkStatus>>16;
if ((numOfWifiLink >= 2) || (wifiLinkStatus&WIFI_P2P_GO_CONNECTED)) {
BTC_PRINT(
BTC_MSG_INTERFACE,
INTF_NOTIFY,
(
"############# [BTCoex], Multi-Port numOfWifiLink = %d, wifiLinkStatus = 0x%x\n",
numOfWifiLink,
wifiLinkStatus
)
);
halbtc8723b1ant_LimitedTx(pBtCoexist, NORMAL_EXEC, 0, 0, 0, 0);
halbtc8723b1ant_LimitedRx(pBtCoexist, NORMAL_EXEC, false, bBtCtrlAggBufSize, aggBufSize);
if ((pBtLinkInfo->bA2dpExist) && (pCoexSta->bC2hBtInquiryPage)) {
BTC_PRINT(
BTC_MSG_INTERFACE,
INTF_NOTIFY,
("############# [BTCoex], BT Is Inquirying\n")
);
halbtc8723b1ant_ActionBtInquiry(pBtCoexist);
} else
halbtc8723b1ant_ActionWifiMultiPort(pBtCoexist);
return;
}
if ((pBtLinkInfo->bBtLinkExist) && (bWifiConnected)) {
halbtc8723b1ant_LimitedTx(pBtCoexist, NORMAL_EXEC, 1, 1, 0, 1);
if (pBtLinkInfo->bScoExist)
halbtc8723b1ant_LimitedRx(pBtCoexist, NORMAL_EXEC, false, true, 0x5);
else
halbtc8723b1ant_LimitedRx(pBtCoexist, NORMAL_EXEC, false, true, 0x8);
halbtc8723b1ant_SwMechanism(pBtCoexist, true);
halbtc8723b1ant_RunSwCoexistMechanism(pBtCoexist); /* just print debug message */
} else {
halbtc8723b1ant_LimitedTx(pBtCoexist, NORMAL_EXEC, 0, 0, 0, 0);
halbtc8723b1ant_LimitedRx(pBtCoexist, NORMAL_EXEC, false, false, 0x5);
halbtc8723b1ant_SwMechanism(pBtCoexist, false);
halbtc8723b1ant_RunSwCoexistMechanism(pBtCoexist); /* just print debug message */
}
pBtCoexist->fBtcGet(pBtCoexist, BTC_GET_BL_HS_OPERATION, &bBtHsOn);
if (pCoexSta->bC2hBtInquiryPage) {
BTC_PRINT(
BTC_MSG_INTERFACE,
INTF_NOTIFY,
("############# [BTCoex], BT Is Inquirying\n")
);
halbtc8723b1ant_ActionBtInquiry(pBtCoexist);
return;
} else if (bBtHsOn) {
halbtc8723b1ant_ActionHs(pBtCoexist);
return;
}
if (!bWifiConnected) {
bool bScan = false, bLink = false, bRoam = false;
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE, ("[BTCoex], wifi is non connected-idle !!!\n"));
pBtCoexist->fBtcGet(pBtCoexist, BTC_GET_BL_WIFI_SCAN, &bScan);
pBtCoexist->fBtcGet(pBtCoexist, BTC_GET_BL_WIFI_LINK, &bLink);
pBtCoexist->fBtcGet(pBtCoexist, BTC_GET_BL_WIFI_ROAM, &bRoam);
if (bScan || bLink || bRoam) {
if (bScan)
halbtc8723b1ant_ActionWifiNotConnectedScan(pBtCoexist);
else
halbtc8723b1ant_ActionWifiNotConnectedAssoAuth(pBtCoexist);
} else
halbtc8723b1ant_ActionWifiNotConnected(pBtCoexist);
} else /* wifi LPS/Busy */
halbtc8723b1ant_ActionWifiConnected(pBtCoexist);
}
static void halbtc8723b1ant_InitCoexDm(PBTC_COEXIST pBtCoexist)
{
/* force to reset coex mechanism */
/* sw all off */
halbtc8723b1ant_SwMechanism(pBtCoexist, false);
/* halbtc8723b1ant_PsTdma(pBtCoexist, FORCE_EXEC, false, 8); */
halbtc8723b1ant_CoexTableWithType(pBtCoexist, FORCE_EXEC, 0);
pCoexSta->popEventCnt = 0;
}
static void halbtc8723b1ant_InitHwConfig(
PBTC_COEXIST pBtCoexist,
bool bBackUp,
bool bWifiOnly
)
{
u32 u4Tmp = 0;/* fwVer; */
u8 u1Tmpa = 0, u1Tmpb = 0;
BTC_PRINT(
BTC_MSG_INTERFACE,
INTF_INIT,
("[BTCoex], 1Ant Init HW Config!!\n")
);
pBtCoexist->fBtcWrite1ByteBitMask(pBtCoexist, 0x550, 0x8, 0x1); /* enable TBTT nterrupt */
/* 0x790[5:0]= 0x5 */
pBtCoexist->fBtcWrite1Byte(pBtCoexist, 0x790, 0x5);
/* Enable counter statistics */
pBtCoexist->fBtcWrite1Byte(pBtCoexist, 0x778, 0x1);
pBtCoexist->fBtcWrite1ByteBitMask(pBtCoexist, 0x40, 0x20, 0x1);
/* Antenna config */
if (bWifiOnly) {
halbtc8723b1ant_SetAntPath(pBtCoexist, BTC_ANT_PATH_WIFI, true, false);
halbtc8723b1ant_PsTdma(pBtCoexist, FORCE_EXEC, false, 9);
} else
halbtc8723b1ant_SetAntPath(pBtCoexist, BTC_ANT_PATH_BT, true, false);
/* PTA parameter */
halbtc8723b1ant_CoexTableWithType(pBtCoexist, FORCE_EXEC, 0);
u4Tmp = pBtCoexist->fBtcRead4Byte(pBtCoexist, 0x948);
u1Tmpa = pBtCoexist->fBtcRead1Byte(pBtCoexist, 0x765);
u1Tmpb = pBtCoexist->fBtcRead1Byte(pBtCoexist, 0x67);
BTC_PRINT(
BTC_MSG_INTERFACE,
INTF_NOTIFY,
(
"############# [BTCoex], 0x948 = 0x%x, 0x765 = 0x%x, 0x67 = 0x%x\n",
u4Tmp,
u1Tmpa,
u1Tmpb
)
);
}
/* */
/* work around function start with wa_halbtc8723b1ant_ */
/* */
/* */
/* extern function start with EXhalbtc8723b1ant_ */
/* */
void EXhalbtc8723b1ant_PowerOnSetting(PBTC_COEXIST pBtCoexist)
{
PBTC_BOARD_INFO pBoardInfo = &pBtCoexist->boardInfo;
u8 u1Tmp = 0x0;
u16 u2Tmp = 0x0;
pBtCoexist->fBtcWrite1Byte(pBtCoexist, 0x67, 0x20);
/* enable BB, REG_SYS_FUNC_EN such that we can write 0x948 correctly. */
u2Tmp = pBtCoexist->fBtcRead2Byte(pBtCoexist, 0x2);
pBtCoexist->fBtcWrite2Byte(pBtCoexist, 0x2, u2Tmp|BIT0|BIT1);
/* set GRAN_BT = 1 */
pBtCoexist->fBtcWrite1Byte(pBtCoexist, 0x765, 0x18);
/* set WLAN_ACT = 0 */
pBtCoexist->fBtcWrite1Byte(pBtCoexist, 0x76e, 0x4);
/* */
/* S0 or S1 setting and Local register setting(By the setting fw can get ant number, S0/S1, ... info) */
/* Local setting bit define */
/* BIT0: "0" for no antenna inverse; "1" for antenna inverse */
/* BIT1: "0" for internal switch; "1" for external switch */
/* BIT2: "0" for one antenna; "1" for two antenna */
/* NOTE: here default all internal switch and 1-antenna ==> BIT1 = 0 and BIT2 = 0 */
if (pBtCoexist->chipInterface == BTC_INTF_USB) {
/* fixed at S0 for USB interface */
pBtCoexist->fBtcWrite4Byte(pBtCoexist, 0x948, 0x0);
u1Tmp |= 0x1; /* antenna inverse */
pBtCoexist->fBtcWriteLocalReg1Byte(pBtCoexist, 0xfe08, u1Tmp);
pBoardInfo->btdmAntPos = BTC_ANTENNA_AT_AUX_PORT;
} else {
/* for PCIE and SDIO interface, we check efuse 0xc3[6] */
if (pBoardInfo->singleAntPath == 0) {
/* set to S1 */
pBtCoexist->fBtcWrite4Byte(pBtCoexist, 0x948, 0x280);
pBoardInfo->btdmAntPos = BTC_ANTENNA_AT_MAIN_PORT;
} else if (pBoardInfo->singleAntPath == 1) {
/* set to S0 */
pBtCoexist->fBtcWrite4Byte(pBtCoexist, 0x948, 0x0);
u1Tmp |= 0x1; /* antenna inverse */
pBoardInfo->btdmAntPos = BTC_ANTENNA_AT_AUX_PORT;
}
if (pBtCoexist->chipInterface == BTC_INTF_PCI)
pBtCoexist->fBtcWriteLocalReg1Byte(pBtCoexist, 0x384, u1Tmp);
else if (pBtCoexist->chipInterface == BTC_INTF_SDIO)
pBtCoexist->fBtcWriteLocalReg1Byte(pBtCoexist, 0x60, u1Tmp);
}
}
void EXhalbtc8723b1ant_InitHwConfig(PBTC_COEXIST pBtCoexist, bool bWifiOnly)
{
halbtc8723b1ant_InitHwConfig(pBtCoexist, true, bWifiOnly);
}
void EXhalbtc8723b1ant_InitCoexDm(PBTC_COEXIST pBtCoexist)
{
BTC_PRINT(
BTC_MSG_INTERFACE,
INTF_INIT,
("[BTCoex], Coex Mechanism Init!!\n")
);
pBtCoexist->bStopCoexDm = false;
halbtc8723b1ant_InitCoexDm(pBtCoexist);
halbtc8723b1ant_QueryBtInfo(pBtCoexist);
}
void EXhalbtc8723b1ant_DisplayCoexInfo(PBTC_COEXIST pBtCoexist)
{
PBTC_BOARD_INFO pBoardInfo = &pBtCoexist->boardInfo;
PBTC_STACK_INFO pStackInfo = &pBtCoexist->stackInfo;
PBTC_BT_LINK_INFO pBtLinkInfo = &pBtCoexist->btLinkInfo;
u8 *cliBuf = pBtCoexist->cliBuf;
u8 u1Tmp[4], i, btInfoExt, psTdmaCase = 0;
u16 u2Tmp[4];
u32 u4Tmp[4];
bool bRoam = false;
bool bScan = false;
bool bLink = false;
bool bWifiUnder5G = false;
bool bWifiUnderBMode = false;
bool bBtHsOn = false;
bool bWifiBusy = false;
s32 wifiRssi = 0, btHsRssi = 0;
u32 wifiBw, wifiTrafficDir, faOfdm, faCck, wifiLinkStatus;
u8 wifiDot11Chnl, wifiHsChnl;
u32 fwVer = 0, btPatchVer = 0;
static u8 PopReportIn10s;
CL_SPRINTF(
cliBuf,
BT_TMP_BUF_SIZE,
"\r\n ============[BT Coexist info]============"
);
CL_PRINTF(cliBuf);
if (pBtCoexist->bManualControl) {
CL_SPRINTF(
cliBuf,
BT_TMP_BUF_SIZE,
"\r\n ============[Under Manual Control]============"
);
CL_PRINTF(cliBuf);
CL_SPRINTF(cliBuf,
BT_TMP_BUF_SIZE,
"\r\n =========================================="
);
CL_PRINTF(cliBuf);
}
if (pBtCoexist->bStopCoexDm) {
CL_SPRINTF(
cliBuf,
BT_TMP_BUF_SIZE,
"\r\n ============[Coex is STOPPED]============"
);
CL_PRINTF(cliBuf);
CL_SPRINTF(
cliBuf,
BT_TMP_BUF_SIZE,
"\r\n =========================================="
);
CL_PRINTF(cliBuf);
}
CL_SPRINTF(
cliBuf,
BT_TMP_BUF_SIZE,
"\r\n %-35s = %d/ %d/ %d", "Ant PG Num/ Ant Mech/ Ant Pos:", \
pBoardInfo->pgAntNum,
pBoardInfo->btdmAntNum,
pBoardInfo->btdmAntPos
);
CL_PRINTF(cliBuf);
CL_SPRINTF(
cliBuf,
BT_TMP_BUF_SIZE,
"\r\n %-35s = %s / %d", "BT stack/ hci ext ver", \
((pStackInfo->bProfileNotified) ? "Yes" : "No"),
pStackInfo->hciVersion
);
CL_PRINTF(cliBuf);
pBtCoexist->fBtcGet(pBtCoexist, BTC_GET_U4_BT_PATCH_VER, &btPatchVer);
pBtCoexist->fBtcGet(pBtCoexist, BTC_GET_U4_WIFI_FW_VER, &fwVer);
CL_SPRINTF(
cliBuf,
BT_TMP_BUF_SIZE,
"\r\n %-35s = %d_%x/ 0x%x/ 0x%x(%d)", "CoexVer/ FwVer/ PatchVer", \
GLCoexVerDate8723b1Ant,
GLCoexVer8723b1Ant,
fwVer,
btPatchVer,
btPatchVer
);
CL_PRINTF(cliBuf);
pBtCoexist->fBtcGet(pBtCoexist, BTC_GET_BL_HS_OPERATION, &bBtHsOn);
pBtCoexist->fBtcGet(pBtCoexist, BTC_GET_U1_WIFI_DOT11_CHNL, &wifiDot11Chnl);
pBtCoexist->fBtcGet(pBtCoexist, BTC_GET_U1_WIFI_HS_CHNL, &wifiHsChnl);
CL_SPRINTF(
cliBuf,
BT_TMP_BUF_SIZE,
"\r\n %-35s = %d / %d(%d)", "Dot11 channel / HsChnl(HsMode)", \
wifiDot11Chnl,
wifiHsChnl,
bBtHsOn
);
CL_PRINTF(cliBuf);
CL_SPRINTF(
cliBuf,
BT_TMP_BUF_SIZE,
"\r\n %-35s = %02x %02x %02x ", "H2C Wifi inform bt chnl Info", \
pCoexDm->wifiChnlInfo[0],
pCoexDm->wifiChnlInfo[1],
pCoexDm->wifiChnlInfo[2]
);
CL_PRINTF(cliBuf);
pBtCoexist->fBtcGet(pBtCoexist, BTC_GET_S4_WIFI_RSSI, &wifiRssi);
pBtCoexist->fBtcGet(pBtCoexist, BTC_GET_S4_HS_RSSI, &btHsRssi);
CL_SPRINTF(
cliBuf,
BT_TMP_BUF_SIZE,
"\r\n %-35s = %d/ %d", "Wifi rssi/ HS rssi", \
wifiRssi-100, btHsRssi-100
);
CL_PRINTF(cliBuf);
pBtCoexist->fBtcGet(pBtCoexist, BTC_GET_BL_WIFI_SCAN, &bScan);
pBtCoexist->fBtcGet(pBtCoexist, BTC_GET_BL_WIFI_LINK, &bLink);
pBtCoexist->fBtcGet(pBtCoexist, BTC_GET_BL_WIFI_ROAM, &bRoam);
CL_SPRINTF(
cliBuf,
BT_TMP_BUF_SIZE,
"\r\n %-35s = %d/ %d/ %d/ %s", "Wifi bLink/ bRoam/ bScan/ bHi-Pri", \
bLink, bRoam, bScan, ((pCoexSta->bWiFiIsHighPriTask) ? "1" : "0")
);
CL_PRINTF(cliBuf);
pBtCoexist->fBtcGet(pBtCoexist, BTC_GET_BL_WIFI_UNDER_5G, &bWifiUnder5G);
pBtCoexist->fBtcGet(pBtCoexist, BTC_GET_U4_WIFI_BW, &wifiBw);
pBtCoexist->fBtcGet(pBtCoexist, BTC_GET_BL_WIFI_BUSY, &bWifiBusy);
pBtCoexist->fBtcGet(
pBtCoexist, BTC_GET_U4_WIFI_TRAFFIC_DIRECTION, &wifiTrafficDir
);
pBtCoexist->fBtcGet(
pBtCoexist, BTC_GET_BL_WIFI_UNDER_B_MODE, &bWifiUnderBMode
);
CL_SPRINTF(
cliBuf,
BT_TMP_BUF_SIZE,
"\r\n %-35s = %s / %s/ %s/ AP =%d/ %s ", "Wifi status", \
(bWifiUnder5G ? "5G" : "2.4G"),
((bWifiUnderBMode) ? "11b" : ((BTC_WIFI_BW_LEGACY == wifiBw) ? "11bg" : (((BTC_WIFI_BW_HT40 == wifiBw) ? "HT40" : "HT20")))),
((!bWifiBusy) ? "idle" : ((BTC_WIFI_TRAFFIC_TX == wifiTrafficDir) ? "uplink" : "downlink")),
pCoexSta->nScanAPNum,
(pCoexSta->bCCKLock) ? "Lock" : "noLock"
);
CL_PRINTF(cliBuf);
pBtCoexist->fBtcGet(
pBtCoexist, BTC_GET_U4_WIFI_LINK_STATUS, &wifiLinkStatus
);
CL_SPRINTF(
cliBuf,
BT_TMP_BUF_SIZE,
"\r\n %-35s = %d/ %d/ %d/ %d/ %d", "sta/vwifi/hs/p2pGo/p2pGc", \
((wifiLinkStatus&WIFI_STA_CONNECTED) ? 1 : 0),
((wifiLinkStatus&WIFI_AP_CONNECTED) ? 1 : 0),
((wifiLinkStatus&WIFI_HS_CONNECTED) ? 1 : 0),
((wifiLinkStatus&WIFI_P2P_GO_CONNECTED) ? 1 : 0),
((wifiLinkStatus&WIFI_P2P_GC_CONNECTED) ? 1 : 0)
);
CL_PRINTF(cliBuf);
PopReportIn10s++;
CL_SPRINTF(
cliBuf,
BT_TMP_BUF_SIZE,
"\r\n %-35s = [%s/ %d/ %d/ %d] ", "BT [status/ rssi/ retryCnt/ popCnt]", \
((pBtCoexist->btInfo.bBtDisabled) ? ("disabled") : ((pCoexSta->bC2hBtInquiryPage) ? ("inquiry/page scan") : ((BT_8723B_1ANT_BT_STATUS_NON_CONNECTED_IDLE == pCoexDm->btStatus) ? "non-connected idle" :
((BT_8723B_1ANT_BT_STATUS_CONNECTED_IDLE == pCoexDm->btStatus) ? "connected-idle" : "busy")))),
pCoexSta->btRssi, pCoexSta->btRetryCnt, pCoexSta->popEventCnt
);
CL_PRINTF(cliBuf);
if (PopReportIn10s >= 5) {
pCoexSta->popEventCnt = 0;
PopReportIn10s = 0;
}
CL_SPRINTF(
cliBuf,
BT_TMP_BUF_SIZE,
"\r\n %-35s = %d / %d / %d / %d", "SCO/HID/PAN/A2DP", \
pBtLinkInfo->bScoExist,
pBtLinkInfo->bHidExist,
pBtLinkInfo->bPanExist,
pBtLinkInfo->bA2dpExist
);
CL_PRINTF(cliBuf);
if (pStackInfo->bProfileNotified) {
pBtCoexist->fBtcDispDbgMsg(pBtCoexist, BTC_DBG_DISP_BT_LINK_INFO);
} else {
CL_SPRINTF(cliBuf, BT_TMP_BUF_SIZE, "\r\n %-35s = %s", "BT Role", \
(pBtLinkInfo->bSlaveRole) ? "Slave" : "Master");
CL_PRINTF(cliBuf);
}
btInfoExt = pCoexSta->btInfoExt;
CL_SPRINTF(
cliBuf,
BT_TMP_BUF_SIZE,
"\r\n %-35s = %s", "BT Info A2DP rate", \
(btInfoExt&BIT0) ? "Basic rate" : "EDR rate"
);
CL_PRINTF(cliBuf);
for (i = 0; i < BT_INFO_SRC_8723B_1ANT_MAX; i++) {
if (pCoexSta->btInfoC2hCnt[i]) {
CL_SPRINTF(
cliBuf,
BT_TMP_BUF_SIZE,
"\r\n %-35s = %02x %02x %02x %02x %02x %02x %02x(%d)", GLBtInfoSrc8723b1Ant[i], \
pCoexSta->btInfoC2h[i][0], pCoexSta->btInfoC2h[i][1],
pCoexSta->btInfoC2h[i][2], pCoexSta->btInfoC2h[i][3],
pCoexSta->btInfoC2h[i][4], pCoexSta->btInfoC2h[i][5],
pCoexSta->btInfoC2h[i][6], pCoexSta->btInfoC2hCnt[i]
);
CL_PRINTF(cliBuf);
}
}
CL_SPRINTF(
cliBuf,
BT_TMP_BUF_SIZE,
"\r\n %-35s = %s/%s, (0x%x/0x%x)", "PS state, IPS/LPS, (lps/rpwm)", \
(pCoexSta->bUnderIps ? "IPS ON" : "IPS OFF"),
(pCoexSta->bUnderLps ? "LPS ON" : "LPS OFF"),
pBtCoexist->btInfo.lpsVal,
pBtCoexist->btInfo.rpwmVal
);
CL_PRINTF(cliBuf);
pBtCoexist->fBtcDispDbgMsg(pBtCoexist, BTC_DBG_DISP_FW_PWR_MODE_CMD);
if (!pBtCoexist->bManualControl) {
/* Sw mechanism */
CL_SPRINTF(
cliBuf,
BT_TMP_BUF_SIZE,
"\r\n %-35s", "============[Sw mechanism]============"
);
CL_PRINTF(cliBuf);
CL_SPRINTF(
cliBuf,
BT_TMP_BUF_SIZE,
"\r\n %-35s = %d", "SM[LowPenaltyRA]", \
pCoexDm->bCurLowPenaltyRa
);
CL_PRINTF(cliBuf);
CL_SPRINTF(
cliBuf,
BT_TMP_BUF_SIZE,
"\r\n %-35s = %s/ %s/ %d ", "DelBA/ BtCtrlAgg/ AggSize", \
(pBtCoexist->btInfo.bRejectAggPkt ? "Yes" : "No"),
(pBtCoexist->btInfo.bBtCtrlAggBufSize ? "Yes" : "No"),
pBtCoexist->btInfo.aggBufSize
);
CL_PRINTF(cliBuf);
CL_SPRINTF(
cliBuf,
BT_TMP_BUF_SIZE,
"\r\n %-35s = 0x%x ", "Rate Mask", \
pBtCoexist->btInfo.raMask
);
CL_PRINTF(cliBuf);
/* Fw mechanism */
CL_SPRINTF(cliBuf, BT_TMP_BUF_SIZE, "\r\n %-35s", "============[Fw mechanism]============");
CL_PRINTF(cliBuf);
psTdmaCase = pCoexDm->curPsTdma;
CL_SPRINTF(cliBuf, BT_TMP_BUF_SIZE, "\r\n %-35s = %02x %02x %02x %02x %02x case-%d (auto:%d)", "PS TDMA", \
pCoexDm->psTdmaPara[0], pCoexDm->psTdmaPara[1],
pCoexDm->psTdmaPara[2], pCoexDm->psTdmaPara[3],
pCoexDm->psTdmaPara[4], psTdmaCase, pCoexDm->bAutoTdmaAdjust);
CL_PRINTF(cliBuf);
CL_SPRINTF(cliBuf, BT_TMP_BUF_SIZE, "\r\n %-35s = %d", "Coex Table Type", \
pCoexSta->nCoexTableType);
CL_PRINTF(cliBuf);
CL_SPRINTF(cliBuf, BT_TMP_BUF_SIZE, "\r\n %-35s = %d", "IgnWlanAct", \
pCoexDm->bCurIgnoreWlanAct);
CL_PRINTF(cliBuf);
/*
CL_SPRINTF(cliBuf, BT_TMP_BUF_SIZE, "\r\n %-35s = 0x%x ", "Latest error condition(should be 0)", \
pCoexDm->errorCondition);
CL_PRINTF(cliBuf);
*/
}
/* Hw setting */
CL_SPRINTF(cliBuf, BT_TMP_BUF_SIZE, "\r\n %-35s", "============[Hw setting]============");
CL_PRINTF(cliBuf);
CL_SPRINTF(cliBuf, BT_TMP_BUF_SIZE, "\r\n %-35s = 0x%x/0x%x/0x%x/0x%x", "backup ARFR1/ARFR2/RL/AMaxTime", \
pCoexDm->backupArfrCnt1, pCoexDm->backupArfrCnt2, pCoexDm->backupRetryLimit, pCoexDm->backupAmpduMaxTime);
CL_PRINTF(cliBuf);
u4Tmp[0] = pBtCoexist->fBtcRead4Byte(pBtCoexist, 0x430);
u4Tmp[1] = pBtCoexist->fBtcRead4Byte(pBtCoexist, 0x434);
u2Tmp[0] = pBtCoexist->fBtcRead2Byte(pBtCoexist, 0x42a);
u1Tmp[0] = pBtCoexist->fBtcRead1Byte(pBtCoexist, 0x456);
CL_SPRINTF(cliBuf, BT_TMP_BUF_SIZE, "\r\n %-35s = 0x%x/0x%x/0x%x/0x%x", "0x430/0x434/0x42a/0x456", \
u4Tmp[0], u4Tmp[1], u2Tmp[0], u1Tmp[0]);
CL_PRINTF(cliBuf);
u1Tmp[0] = pBtCoexist->fBtcRead1Byte(pBtCoexist, 0x778);
u4Tmp[0] = pBtCoexist->fBtcRead4Byte(pBtCoexist, 0x6cc);
u4Tmp[1] = pBtCoexist->fBtcRead4Byte(pBtCoexist, 0x880);
CL_SPRINTF(
cliBuf, BT_TMP_BUF_SIZE,
"\r\n %-35s = 0x%x/ 0x%x/ 0x%x", "0x778/0x6cc/0x880[29:25]", \
u1Tmp[0], u4Tmp[0], (u4Tmp[1]&0x3e000000) >> 25
);
CL_PRINTF(cliBuf);
u4Tmp[0] = pBtCoexist->fBtcRead4Byte(pBtCoexist, 0x948);
u1Tmp[0] = pBtCoexist->fBtcRead1Byte(pBtCoexist, 0x67);
u4Tmp[1] = pBtCoexist->fBtcRead4Byte(pBtCoexist, 0x764);
u1Tmp[1] = pBtCoexist->fBtcRead1Byte(pBtCoexist, 0x76e);
CL_SPRINTF(
cliBuf,
BT_TMP_BUF_SIZE,
"\r\n %-35s = 0x%x/ 0x%x/ 0x%x/ 0x%x", "0x948/ 0x67[5] / 0x764 / 0x76e", \
u4Tmp[0], ((u1Tmp[0]&0x20) >> 5), (u4Tmp[1] & 0xffff), u1Tmp[1]
);
CL_PRINTF(cliBuf);
u4Tmp[0] = pBtCoexist->fBtcRead4Byte(pBtCoexist, 0x92c);
u4Tmp[1] = pBtCoexist->fBtcRead4Byte(pBtCoexist, 0x930);
u4Tmp[2] = pBtCoexist->fBtcRead4Byte(pBtCoexist, 0x944);
CL_SPRINTF(
cliBuf,
BT_TMP_BUF_SIZE,
"\r\n %-35s = 0x%x/ 0x%x/ 0x%x", "0x92c[1:0]/ 0x930[7:0]/0x944[1:0]", \
u4Tmp[0]&0x3, u4Tmp[1]&0xff, u4Tmp[2]&0x3
);
CL_PRINTF(cliBuf);
u1Tmp[0] = pBtCoexist->fBtcRead1Byte(pBtCoexist, 0x39);
u1Tmp[1] = pBtCoexist->fBtcRead1Byte(pBtCoexist, 0x40);
u4Tmp[0] = pBtCoexist->fBtcRead4Byte(pBtCoexist, 0x4c);
u1Tmp[2] = pBtCoexist->fBtcRead1Byte(pBtCoexist, 0x64);
CL_SPRINTF(
cliBuf,
BT_TMP_BUF_SIZE,
"\r\n %-35s = 0x%x/ 0x%x/ 0x%x/ 0x%x", "0x38[11]/0x40/0x4c[24:23]/0x64[0]", \
((u1Tmp[0] & 0x8)>>3),
u1Tmp[1],
((u4Tmp[0]&0x01800000)>>23),
u1Tmp[2]&0x1
);
CL_PRINTF(cliBuf);
u4Tmp[0] = pBtCoexist->fBtcRead4Byte(pBtCoexist, 0x550);
u1Tmp[0] = pBtCoexist->fBtcRead1Byte(pBtCoexist, 0x522);
CL_SPRINTF(
cliBuf,
BT_TMP_BUF_SIZE,
"\r\n %-35s = 0x%x/ 0x%x", "0x550(bcn ctrl)/0x522", \
u4Tmp[0], u1Tmp[0]
);
CL_PRINTF(cliBuf);
u4Tmp[0] = pBtCoexist->fBtcRead4Byte(pBtCoexist, 0xc50);
u1Tmp[0] = pBtCoexist->fBtcRead1Byte(pBtCoexist, 0x49c);
CL_SPRINTF(
cliBuf,
BT_TMP_BUF_SIZE,
"\r\n %-35s = 0x%x/ 0x%x", "0xc50(dig)/0x49c(null-drop)", \
u4Tmp[0]&0xff, u1Tmp[0]
);
CL_PRINTF(cliBuf);
u4Tmp[0] = pBtCoexist->fBtcRead4Byte(pBtCoexist, 0xda0);
u4Tmp[1] = pBtCoexist->fBtcRead4Byte(pBtCoexist, 0xda4);
u4Tmp[2] = pBtCoexist->fBtcRead4Byte(pBtCoexist, 0xda8);
u4Tmp[3] = pBtCoexist->fBtcRead4Byte(pBtCoexist, 0xcf0);
u1Tmp[0] = pBtCoexist->fBtcRead1Byte(pBtCoexist, 0xa5b);
u1Tmp[1] = pBtCoexist->fBtcRead1Byte(pBtCoexist, 0xa5c);
faOfdm =
((u4Tmp[0]&0xffff0000) >> 16) +
((u4Tmp[1]&0xffff0000) >> 16) +
(u4Tmp[1] & 0xffff) + (u4Tmp[2] & 0xffff) + \
((u4Tmp[3]&0xffff0000) >> 16) + (u4Tmp[3] & 0xffff);
faCck = (u1Tmp[0] << 8) + u1Tmp[1];
CL_SPRINTF(
cliBuf,
BT_TMP_BUF_SIZE,
"\r\n %-35s = 0x%x/ 0x%x/ 0x%x", "OFDM-CCA/OFDM-FA/CCK-FA", \
u4Tmp[0]&0xffff, faOfdm, faCck
);
CL_PRINTF(cliBuf);
CL_SPRINTF(
cliBuf,
BT_TMP_BUF_SIZE,
"\r\n %-35s = %d/ %d/ %d/ %d", "CRC_OK CCK/11g/11n/11n-Agg", \
pCoexSta->nCRCOK_CCK,
pCoexSta->nCRCOK_11g,
pCoexSta->nCRCOK_11n,
pCoexSta->nCRCOK_11nAgg
);
CL_PRINTF(cliBuf);
CL_SPRINTF(
cliBuf,
BT_TMP_BUF_SIZE,
"\r\n %-35s = %d/ %d/ %d/ %d", "CRC_Err CCK/11g/11n/11n-Agg", \
pCoexSta->nCRCErr_CCK,
pCoexSta->nCRCErr_11g,
pCoexSta->nCRCErr_11n,
pCoexSta->nCRCErr_11nAgg
);
CL_PRINTF(cliBuf);
u4Tmp[0] = pBtCoexist->fBtcRead4Byte(pBtCoexist, 0x6c0);
u4Tmp[1] = pBtCoexist->fBtcRead4Byte(pBtCoexist, 0x6c4);
u4Tmp[2] = pBtCoexist->fBtcRead4Byte(pBtCoexist, 0x6c8);
CL_SPRINTF(
cliBuf,
BT_TMP_BUF_SIZE,
"\r\n %-35s = 0x%x/ 0x%x/ 0x%x", "0x6c0/0x6c4/0x6c8(coexTable)", \
u4Tmp[0], u4Tmp[1], u4Tmp[2]);
CL_PRINTF(cliBuf);
CL_SPRINTF(
cliBuf,
BT_TMP_BUF_SIZE,
"\r\n %-35s = %d/ %d", "0x770(high-pri rx/tx)", \
pCoexSta->highPriorityRx, pCoexSta->highPriorityTx
);
CL_PRINTF(cliBuf);
CL_SPRINTF(
cliBuf,
BT_TMP_BUF_SIZE,
"\r\n %-35s = %d/ %d", "0x774(low-pri rx/tx)", \
pCoexSta->lowPriorityRx, pCoexSta->lowPriorityTx
);
CL_PRINTF(cliBuf);
pBtCoexist->fBtcDispDbgMsg(pBtCoexist, BTC_DBG_DISP_COEX_STATISTICS);
}
void EXhalbtc8723b1ant_IpsNotify(PBTC_COEXIST pBtCoexist, u8 type)
{
if (pBtCoexist->bManualControl || pBtCoexist->bStopCoexDm)
return;
if (BTC_IPS_ENTER == type) {
BTC_PRINT(
BTC_MSG_INTERFACE, INTF_NOTIFY, ("[BTCoex], IPS ENTER notify\n")
);
pCoexSta->bUnderIps = true;
halbtc8723b1ant_PsTdma(pBtCoexist, NORMAL_EXEC, false, 0);
halbtc8723b1ant_CoexTableWithType(pBtCoexist, NORMAL_EXEC, 0);
halbtc8723b1ant_SetAntPath(pBtCoexist, BTC_ANT_PATH_BT, false, true);
} else if (BTC_IPS_LEAVE == type) {
BTC_PRINT(
BTC_MSG_INTERFACE, INTF_NOTIFY, ("[BTCoex], IPS LEAVE notify\n")
);
pCoexSta->bUnderIps = false;
halbtc8723b1ant_InitHwConfig(pBtCoexist, false, false);
halbtc8723b1ant_InitCoexDm(pBtCoexist);
halbtc8723b1ant_QueryBtInfo(pBtCoexist);
}
}
void EXhalbtc8723b1ant_LpsNotify(PBTC_COEXIST pBtCoexist, u8 type)
{
if (pBtCoexist->bManualControl || pBtCoexist->bStopCoexDm)
return;
if (BTC_LPS_ENABLE == type) {
BTC_PRINT(
BTC_MSG_INTERFACE, INTF_NOTIFY, ("[BTCoex], LPS ENABLE notify\n")
);
pCoexSta->bUnderLps = true;
} else if (BTC_LPS_DISABLE == type) {
BTC_PRINT(
BTC_MSG_INTERFACE, INTF_NOTIFY, ("[BTCoex], LPS DISABLE notify\n")
);
pCoexSta->bUnderLps = false;
}
}
void EXhalbtc8723b1ant_ScanNotify(PBTC_COEXIST pBtCoexist, u8 type)
{
bool bWifiConnected = false, bBtHsOn = false;
u32 wifiLinkStatus = 0;
u32 numOfWifiLink = 0;
bool bBtCtrlAggBufSize = false;
u8 aggBufSize = 5;
u8 u1Tmpa, u1Tmpb;
u32 u4Tmp;
if (pBtCoexist->bManualControl || pBtCoexist->bStopCoexDm)
return;
if (BTC_SCAN_START == type) {
pCoexSta->bWiFiIsHighPriTask = true;
BTC_PRINT(
BTC_MSG_INTERFACE, INTF_NOTIFY, ("[BTCoex], SCAN START notify\n")
);
halbtc8723b1ant_PsTdma(pBtCoexist, FORCE_EXEC, false, 8); /* Force antenna setup for no scan result issue */
u4Tmp = pBtCoexist->fBtcRead4Byte(pBtCoexist, 0x948);
u1Tmpa = pBtCoexist->fBtcRead1Byte(pBtCoexist, 0x765);
u1Tmpb = pBtCoexist->fBtcRead1Byte(pBtCoexist, 0x67);
BTC_PRINT(
BTC_MSG_INTERFACE,
INTF_NOTIFY,
(
"[BTCoex], 0x948 = 0x%x, 0x765 = 0x%x, 0x67 = 0x%x\n",
u4Tmp,
u1Tmpa,
u1Tmpb
)
);
} else {
pCoexSta->bWiFiIsHighPriTask = false;
BTC_PRINT(
BTC_MSG_INTERFACE, INTF_NOTIFY, ("[BTCoex], SCAN FINISH notify\n")
);
pBtCoexist->fBtcGet(
pBtCoexist, BTC_GET_U1_AP_NUM, &pCoexSta->nScanAPNum
);
}
if (pBtCoexist->btInfo.bBtDisabled)
return;
pBtCoexist->fBtcGet(pBtCoexist, BTC_GET_BL_HS_OPERATION, &bBtHsOn);
pBtCoexist->fBtcGet(pBtCoexist, BTC_GET_BL_WIFI_CONNECTED, &bWifiConnected);
halbtc8723b1ant_QueryBtInfo(pBtCoexist);
pBtCoexist->fBtcGet(pBtCoexist, BTC_GET_U4_WIFI_LINK_STATUS, &wifiLinkStatus);
numOfWifiLink = wifiLinkStatus>>16;
if (numOfWifiLink >= 2) {
halbtc8723b1ant_LimitedTx(pBtCoexist, NORMAL_EXEC, 0, 0, 0, 0);
halbtc8723b1ant_LimitedRx(
pBtCoexist, NORMAL_EXEC, false, bBtCtrlAggBufSize, aggBufSize
);
halbtc8723b1ant_ActionWifiMultiPort(pBtCoexist);
return;
}
if (pCoexSta->bC2hBtInquiryPage) {
halbtc8723b1ant_ActionBtInquiry(pBtCoexist);
return;
} else if (bBtHsOn) {
halbtc8723b1ant_ActionHs(pBtCoexist);
return;
}
if (BTC_SCAN_START == type) {
/* BTC_PRINT(BTC_MSG_INTERFACE, INTF_NOTIFY, ("[BTCoex], SCAN START notify\n")); */
if (!bWifiConnected) /* non-connected scan */
halbtc8723b1ant_ActionWifiNotConnectedScan(pBtCoexist);
else /* wifi is connected */
halbtc8723b1ant_ActionWifiConnectedScan(pBtCoexist);
} else if (BTC_SCAN_FINISH == type) {
/* BTC_PRINT(BTC_MSG_INTERFACE, INTF_NOTIFY, ("[BTCoex], SCAN FINISH notify\n")); */
if (!bWifiConnected) /* non-connected scan */
halbtc8723b1ant_ActionWifiNotConnected(pBtCoexist);
else
halbtc8723b1ant_ActionWifiConnected(pBtCoexist);
}
}
void EXhalbtc8723b1ant_ConnectNotify(PBTC_COEXIST pBtCoexist, u8 type)
{
bool bWifiConnected = false, bBtHsOn = false;
u32 wifiLinkStatus = 0;
u32 numOfWifiLink = 0;
bool bBtCtrlAggBufSize = false;
u8 aggBufSize = 5;
if (
pBtCoexist->bManualControl ||
pBtCoexist->bStopCoexDm ||
pBtCoexist->btInfo.bBtDisabled
)
return;
if (BTC_ASSOCIATE_START == type) {
pCoexSta->bWiFiIsHighPriTask = true;
BTC_PRINT(BTC_MSG_INTERFACE, INTF_NOTIFY, ("[BTCoex], CONNECT START notify\n"));
pCoexDm->nArpCnt = 0;
} else {
pCoexSta->bWiFiIsHighPriTask = false;
BTC_PRINT(BTC_MSG_INTERFACE, INTF_NOTIFY, ("[BTCoex], CONNECT FINISH notify\n"));
/* pCoexDm->nArpCnt = 0; */
}
pBtCoexist->fBtcGet(pBtCoexist, BTC_GET_U4_WIFI_LINK_STATUS, &wifiLinkStatus);
numOfWifiLink = wifiLinkStatus>>16;
if (numOfWifiLink >= 2) {
halbtc8723b1ant_LimitedTx(pBtCoexist, NORMAL_EXEC, 0, 0, 0, 0);
halbtc8723b1ant_LimitedRx(pBtCoexist, NORMAL_EXEC, false, bBtCtrlAggBufSize, aggBufSize);
halbtc8723b1ant_ActionWifiMultiPort(pBtCoexist);
return;
}
pBtCoexist->fBtcGet(pBtCoexist, BTC_GET_BL_HS_OPERATION, &bBtHsOn);
if (pCoexSta->bC2hBtInquiryPage) {
halbtc8723b1ant_ActionBtInquiry(pBtCoexist);
return;
} else if (bBtHsOn) {
halbtc8723b1ant_ActionHs(pBtCoexist);
return;
}
if (BTC_ASSOCIATE_START == type) {
/* BTC_PRINT(BTC_MSG_INTERFACE, INTF_NOTIFY, ("[BTCoex], CONNECT START notify\n")); */
halbtc8723b1ant_ActionWifiNotConnectedAssoAuth(pBtCoexist);
} else if (BTC_ASSOCIATE_FINISH == type) {
/* BTC_PRINT(BTC_MSG_INTERFACE, INTF_NOTIFY, ("[BTCoex], CONNECT FINISH notify\n")); */
pBtCoexist->fBtcGet(pBtCoexist, BTC_GET_BL_WIFI_CONNECTED, &bWifiConnected);
if (!bWifiConnected) /* non-connected scan */
halbtc8723b1ant_ActionWifiNotConnected(pBtCoexist);
else
halbtc8723b1ant_ActionWifiConnected(pBtCoexist);
}
}
void EXhalbtc8723b1ant_MediaStatusNotify(PBTC_COEXIST pBtCoexist, u8 type)
{
u8 H2C_Parameter[3] = {0};
u32 wifiBw;
u8 wifiCentralChnl;
bool bWifiUnderBMode = false;
if (
pBtCoexist->bManualControl ||
pBtCoexist->bStopCoexDm ||
pBtCoexist->btInfo.bBtDisabled
)
return;
if (BTC_MEDIA_CONNECT == type) {
BTC_PRINT(BTC_MSG_INTERFACE, INTF_NOTIFY, ("[BTCoex], MEDIA connect notify\n"));
pBtCoexist->fBtcGet(pBtCoexist, BTC_GET_BL_WIFI_UNDER_B_MODE, &bWifiUnderBMode);
/* Set CCK Tx/Rx high Pri except 11b mode */
if (bWifiUnderBMode) {
pBtCoexist->fBtcWrite1Byte(pBtCoexist, 0x6cd, 0x00); /* CCK Tx */
pBtCoexist->fBtcWrite1Byte(pBtCoexist, 0x6cf, 0x00); /* CCK Rx */
} else {
pBtCoexist->fBtcWrite1Byte(pBtCoexist, 0x6cd, 0x10); /* CCK Tx */
pBtCoexist->fBtcWrite1Byte(pBtCoexist, 0x6cf, 0x10); /* CCK Rx */
}
pCoexDm->backupArfrCnt1 = pBtCoexist->fBtcRead4Byte(pBtCoexist, 0x430);
pCoexDm->backupArfrCnt2 = pBtCoexist->fBtcRead4Byte(pBtCoexist, 0x434);
pCoexDm->backupRetryLimit = pBtCoexist->fBtcRead2Byte(pBtCoexist, 0x42a);
pCoexDm->backupAmpduMaxTime = pBtCoexist->fBtcRead1Byte(pBtCoexist, 0x456);
} else {
BTC_PRINT(BTC_MSG_INTERFACE, INTF_NOTIFY, ("[BTCoex], MEDIA disconnect notify\n"));
pCoexDm->nArpCnt = 0;
pBtCoexist->fBtcWrite1Byte(pBtCoexist, 0x6cd, 0x0); /* CCK Tx */
pBtCoexist->fBtcWrite1Byte(pBtCoexist, 0x6cf, 0x0); /* CCK Rx */
}
/* only 2.4G we need to inform bt the chnl mask */
pBtCoexist->fBtcGet(pBtCoexist, BTC_GET_U1_WIFI_CENTRAL_CHNL, &wifiCentralChnl);
if ((BTC_MEDIA_CONNECT == type) && (wifiCentralChnl <= 14)) {
/* H2C_Parameter[0] = 0x1; */
H2C_Parameter[0] = 0x0;
H2C_Parameter[1] = wifiCentralChnl;
pBtCoexist->fBtcGet(pBtCoexist, BTC_GET_U4_WIFI_BW, &wifiBw);
if (BTC_WIFI_BW_HT40 == wifiBw)
H2C_Parameter[2] = 0x30;
else
H2C_Parameter[2] = 0x20;
}
pCoexDm->wifiChnlInfo[0] = H2C_Parameter[0];
pCoexDm->wifiChnlInfo[1] = H2C_Parameter[1];
pCoexDm->wifiChnlInfo[2] = H2C_Parameter[2];
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_TRACE_FW_EXEC,
(
"[BTCoex], FW write 0x66 = 0x%x\n",
H2C_Parameter[0]<<16 | H2C_Parameter[1]<<8 | H2C_Parameter[2]
)
);
pBtCoexist->fBtcFillH2c(pBtCoexist, 0x66, 3, H2C_Parameter);
}
void EXhalbtc8723b1ant_SpecialPacketNotify(PBTC_COEXIST pBtCoexist, u8 type)
{
bool bBtHsOn = false;
u32 wifiLinkStatus = 0;
u32 numOfWifiLink = 0;
bool bBtCtrlAggBufSize = false;
u8 aggBufSize = 5;
if (
pBtCoexist->bManualControl ||
pBtCoexist->bStopCoexDm ||
pBtCoexist->btInfo.bBtDisabled
)
return;
if (
BTC_PACKET_DHCP == type ||
BTC_PACKET_EAPOL == type ||
BTC_PACKET_ARP == type
) {
if (BTC_PACKET_ARP == type) {
BTC_PRINT(
BTC_MSG_INTERFACE,
INTF_NOTIFY,
("[BTCoex], special Packet ARP notify\n")
);
pCoexDm->nArpCnt++;
BTC_PRINT(
BTC_MSG_INTERFACE,
INTF_NOTIFY,
("[BTCoex], ARP Packet Count = %d\n", pCoexDm->nArpCnt)
);
if (pCoexDm->nArpCnt >= 10) /* if APR PKT > 10 after connect, do not go to ActionWifiConnectedSpecialPacket(pBtCoexist) */
pCoexSta->bWiFiIsHighPriTask = false;
else
pCoexSta->bWiFiIsHighPriTask = true;
} else {
pCoexSta->bWiFiIsHighPriTask = true;
BTC_PRINT(
BTC_MSG_INTERFACE,
INTF_NOTIFY,
("[BTCoex], special Packet DHCP or EAPOL notify\n")
);
}
} else {
pCoexSta->bWiFiIsHighPriTask = false;
BTC_PRINT(
BTC_MSG_INTERFACE,
INTF_NOTIFY,
("[BTCoex], special Packet [Type = %d] notify\n", type)
);
}
pCoexSta->specialPktPeriodCnt = 0;
pBtCoexist->fBtcGet(
pBtCoexist, BTC_GET_U4_WIFI_LINK_STATUS, &wifiLinkStatus
);
numOfWifiLink = wifiLinkStatus>>16;
if (numOfWifiLink >= 2) {
halbtc8723b1ant_LimitedTx(pBtCoexist, NORMAL_EXEC, 0, 0, 0, 0);
halbtc8723b1ant_LimitedRx(
pBtCoexist, NORMAL_EXEC, false, bBtCtrlAggBufSize, aggBufSize
);
halbtc8723b1ant_ActionWifiMultiPort(pBtCoexist);
return;
}
pBtCoexist->fBtcGet(pBtCoexist, BTC_GET_BL_HS_OPERATION, &bBtHsOn);
if (pCoexSta->bC2hBtInquiryPage) {
halbtc8723b1ant_ActionBtInquiry(pBtCoexist);
return;
} else if (bBtHsOn) {
halbtc8723b1ant_ActionHs(pBtCoexist);
return;
}
if (
BTC_PACKET_DHCP == type ||
BTC_PACKET_EAPOL == type ||
((BTC_PACKET_ARP == type) && (pCoexSta->bWiFiIsHighPriTask))
)
halbtc8723b1ant_ActionWifiConnectedSpecialPacket(pBtCoexist);
}
void EXhalbtc8723b1ant_BtInfoNotify(
PBTC_COEXIST pBtCoexist, u8 *tmpBuf, u8 length
)
{
u8 btInfo = 0;
u8 i, rspSource = 0;
bool bWifiConnected = false;
bool bBtBusy = false;
pCoexSta->bC2hBtInfoReqSent = false;
rspSource = tmpBuf[0]&0xf;
if (rspSource >= BT_INFO_SRC_8723B_1ANT_MAX)
rspSource = BT_INFO_SRC_8723B_1ANT_WIFI_FW;
pCoexSta->btInfoC2hCnt[rspSource]++;
BTC_PRINT(
BTC_MSG_INTERFACE,
INTF_NOTIFY,
("[BTCoex], Bt info[%d], length =%d, hex data =[",
rspSource,
length)
);
for (i = 0; i < length; i++) {
pCoexSta->btInfoC2h[rspSource][i] = tmpBuf[i];
if (i == 1)
btInfo = tmpBuf[i];
if (i == length-1)
BTC_PRINT(
BTC_MSG_INTERFACE, INTF_NOTIFY, ("0x%02x]\n", tmpBuf[i])
);
else
BTC_PRINT(BTC_MSG_INTERFACE, INTF_NOTIFY, ("0x%02x, ", tmpBuf[i]));
}
if (BT_INFO_SRC_8723B_1ANT_WIFI_FW != rspSource) {
pCoexSta->btRetryCnt = pCoexSta->btInfoC2h[rspSource][2]&0xf;
if (pCoexSta->btRetryCnt >= 1)
pCoexSta->popEventCnt++;
if (pCoexSta->btInfoC2h[rspSource][2]&0x20)
pCoexSta->bC2hBtPage = true;
else
pCoexSta->bC2hBtPage = false;
pCoexSta->btRssi = pCoexSta->btInfoC2h[rspSource][3]*2-90;
/* pCoexSta->btInfoC2h[rspSource][3]*2+10; */
pCoexSta->btInfoExt = pCoexSta->btInfoC2h[rspSource][4];
pCoexSta->bBtTxRxMask = (pCoexSta->btInfoC2h[rspSource][2]&0x40);
pBtCoexist->fBtcSet(pBtCoexist, BTC_SET_BL_BT_TX_RX_MASK, &pCoexSta->bBtTxRxMask);
if (!pCoexSta->bBtTxRxMask) {
/* BT into is responded by BT FW and BT RF REG 0x3C != 0x15 => Need to switch BT TRx Mask */
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE, ("[BTCoex], Switch BT TRx Mask since BT RF REG 0x3C != 0x15\n"));
pBtCoexist->fBtcSetBtReg(pBtCoexist, BTC_BT_REG_RF, 0x3c, 0x15);
}
/* Here we need to resend some wifi info to BT */
/* because bt is reset and loss of the info. */
if (pCoexSta->btInfoExt & BIT1) {
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_TRACE,
("[BTCoex], BT ext info bit1 check, send wifi BW&Chnl to BT!!\n")
);
pBtCoexist->fBtcGet(pBtCoexist, BTC_GET_BL_WIFI_CONNECTED, &bWifiConnected);
if (bWifiConnected)
EXhalbtc8723b1ant_MediaStatusNotify(pBtCoexist, BTC_MEDIA_CONNECT);
else
EXhalbtc8723b1ant_MediaStatusNotify(pBtCoexist, BTC_MEDIA_DISCONNECT);
}
if (pCoexSta->btInfoExt & BIT3) {
if (!pBtCoexist->bManualControl && !pBtCoexist->bStopCoexDm) {
BTC_PRINT(
BTC_MSG_ALGORITHM,
ALGO_TRACE,
("[BTCoex], BT ext info bit3 check, set BT NOT to ignore Wlan active!!\n")
);
halbtc8723b1ant_IgnoreWlanAct(pBtCoexist, FORCE_EXEC, false);
}
} else {
/* BT already NOT ignore Wlan active, do nothing here. */
}
}
/* check BIT2 first ==> check if bt is under inquiry or page scan */
if (btInfo & BT_INFO_8723B_1ANT_B_INQ_PAGE)
pCoexSta->bC2hBtInquiryPage = true;
else
pCoexSta->bC2hBtInquiryPage = false;
/* set link exist status */
if (!(btInfo&BT_INFO_8723B_1ANT_B_CONNECTION)) {
pCoexSta->bBtLinkExist = false;
pCoexSta->bPanExist = false;
pCoexSta->bA2dpExist = false;
pCoexSta->bHidExist = false;
pCoexSta->bScoExist = false;
} else { /* connection exists */
pCoexSta->bBtLinkExist = true;
if (btInfo & BT_INFO_8723B_1ANT_B_FTP)
pCoexSta->bPanExist = true;
else
pCoexSta->bPanExist = false;
if (btInfo & BT_INFO_8723B_1ANT_B_A2DP)
pCoexSta->bA2dpExist = true;
else
pCoexSta->bA2dpExist = false;
if (btInfo & BT_INFO_8723B_1ANT_B_HID)
pCoexSta->bHidExist = true;
else
pCoexSta->bHidExist = false;
if (btInfo & BT_INFO_8723B_1ANT_B_SCO_ESCO)
pCoexSta->bScoExist = true;
else
pCoexSta->bScoExist = false;
}
halbtc8723b1ant_UpdateBtLinkInfo(pBtCoexist);
btInfo = btInfo & 0x1f; /* mask profile bit for connect-ilde identification (for CSR case: A2DP idle --> 0x41) */
if (!(btInfo&BT_INFO_8723B_1ANT_B_CONNECTION)) {
pCoexDm->btStatus = BT_8723B_1ANT_BT_STATUS_NON_CONNECTED_IDLE;
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE, ("[BTCoex], BtInfoNotify(), BT Non-Connected idle!!!\n"));
} else if (btInfo == BT_INFO_8723B_1ANT_B_CONNECTION) {
/* connection exists but no busy */
pCoexDm->btStatus = BT_8723B_1ANT_BT_STATUS_CONNECTED_IDLE;
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE, ("[BTCoex], BtInfoNotify(), BT Connected-idle!!!\n"));
} else if (
(btInfo&BT_INFO_8723B_1ANT_B_SCO_ESCO) ||
(btInfo&BT_INFO_8723B_1ANT_B_SCO_BUSY)
) {
pCoexDm->btStatus = BT_8723B_1ANT_BT_STATUS_SCO_BUSY;
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE, ("[BTCoex], BtInfoNotify(), BT SCO busy!!!\n"));
} else if (btInfo&BT_INFO_8723B_1ANT_B_ACL_BUSY) {
if (BT_8723B_1ANT_BT_STATUS_ACL_BUSY != pCoexDm->btStatus)
pCoexDm->bAutoTdmaAdjust = false;
pCoexDm->btStatus = BT_8723B_1ANT_BT_STATUS_ACL_BUSY;
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE, ("[BTCoex], BtInfoNotify(), BT ACL busy!!!\n"));
} else {
pCoexDm->btStatus = BT_8723B_1ANT_BT_STATUS_MAX;
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE, ("[BTCoex], BtInfoNotify(), BT Non-Defined state!!!\n"));
}
if (
(BT_8723B_1ANT_BT_STATUS_ACL_BUSY == pCoexDm->btStatus) ||
(BT_8723B_1ANT_BT_STATUS_SCO_BUSY == pCoexDm->btStatus) ||
(BT_8723B_1ANT_BT_STATUS_ACL_SCO_BUSY == pCoexDm->btStatus)
)
bBtBusy = true;
else
bBtBusy = false;
pBtCoexist->fBtcSet(pBtCoexist, BTC_SET_BL_BT_TRAFFIC_BUSY, &bBtBusy);
halbtc8723b1ant_RunCoexistMechanism(pBtCoexist);
}
void EXhalbtc8723b1ant_HaltNotify(PBTC_COEXIST pBtCoexist)
{
BTC_PRINT(BTC_MSG_INTERFACE, INTF_NOTIFY, ("[BTCoex], Halt notify\n"));
halbtc8723b1ant_PowerSaveState(pBtCoexist, BTC_PS_WIFI_NATIVE, 0x0, 0x0);
halbtc8723b1ant_PsTdma(pBtCoexist, FORCE_EXEC, false, 0);
halbtc8723b1ant_SetAntPath(pBtCoexist, BTC_ANT_PATH_BT, false, true);
halbtc8723b1ant_IgnoreWlanAct(pBtCoexist, FORCE_EXEC, true);
EXhalbtc8723b1ant_MediaStatusNotify(pBtCoexist, BTC_MEDIA_DISCONNECT);
pBtCoexist->bStopCoexDm = true;
}
void EXhalbtc8723b1ant_PnpNotify(PBTC_COEXIST pBtCoexist, u8 pnpState)
{
BTC_PRINT(BTC_MSG_INTERFACE, INTF_NOTIFY, ("[BTCoex], Pnp notify\n"));
if (BTC_WIFI_PNP_SLEEP == pnpState) {
BTC_PRINT(BTC_MSG_INTERFACE, INTF_NOTIFY, ("[BTCoex], Pnp notify to SLEEP\n"));
halbtc8723b1ant_PowerSaveState(pBtCoexist, BTC_PS_WIFI_NATIVE, 0x0, 0x0);
halbtc8723b1ant_PsTdma(pBtCoexist, NORMAL_EXEC, false, 0);
halbtc8723b1ant_CoexTableWithType(pBtCoexist, NORMAL_EXEC, 2);
halbtc8723b1ant_SetAntPath(pBtCoexist, BTC_ANT_PATH_BT, false, true);
pBtCoexist->bStopCoexDm = true;
} else if (BTC_WIFI_PNP_WAKE_UP == pnpState) {
BTC_PRINT(BTC_MSG_INTERFACE, INTF_NOTIFY, ("[BTCoex], Pnp notify to WAKE UP\n"));
pBtCoexist->bStopCoexDm = false;
halbtc8723b1ant_InitHwConfig(pBtCoexist, false, false);
halbtc8723b1ant_InitCoexDm(pBtCoexist);
halbtc8723b1ant_QueryBtInfo(pBtCoexist);
}
}
void EXhalbtc8723b1ant_Periodical(PBTC_COEXIST pBtCoexist)
{
static u8 disVerInfoCnt;
u32 fwVer = 0, btPatchVer = 0;
BTC_PRINT(BTC_MSG_ALGORITHM, ALGO_TRACE, ("[BTCoex], ==========================Periodical ===========================\n"));
if (disVerInfoCnt <= 5) {
disVerInfoCnt += 1;
BTC_PRINT(BTC_MSG_INTERFACE, INTF_INIT, ("[BTCoex], ****************************************************************\n"));
pBtCoexist->fBtcGet(pBtCoexist, BTC_GET_U4_BT_PATCH_VER, &btPatchVer);
pBtCoexist->fBtcGet(pBtCoexist, BTC_GET_U4_WIFI_FW_VER, &fwVer);
BTC_PRINT(BTC_MSG_INTERFACE, INTF_INIT, ("[BTCoex], CoexVer/ FwVer/ PatchVer = %d_%x/ 0x%x/ 0x%x(%d)\n", \
GLCoexVerDate8723b1Ant, GLCoexVer8723b1Ant, fwVer, btPatchVer, btPatchVer));
BTC_PRINT(BTC_MSG_INTERFACE, INTF_INIT, ("[BTCoex], ****************************************************************\n"));
}
halbtc8723b1ant_MonitorBtCtr(pBtCoexist);
halbtc8723b1ant_MonitorWiFiCtr(pBtCoexist);
if (
halbtc8723b1ant_IsWifiStatusChanged(pBtCoexist) ||
pCoexDm->bAutoTdmaAdjust
)
halbtc8723b1ant_RunCoexistMechanism(pBtCoexist);
pCoexSta->specialPktPeriodCnt++;
}
| 412 | 0.90869 | 1 | 0.90869 | game-dev | MEDIA | 0.691425 | game-dev | 0.936132 | 1 | 0.936132 |
mamoniot/project-cybersyn | 11,702 | cybersyn/scripts/gui/manager.lua | local gui = require("__flib__.gui")
local constants = require("scripts.gui.constants")
--local actions = require("scripts.gui.actions")
local templates = require("scripts.gui.templates")
local stations_tab = require("scripts.gui.stations")
local trains_tab = require("scripts.gui.trains")
--local depots_tab = require("scripts.gui.depots")
local inventory_tab = require("scripts.gui.inventory")
--local history_tab = require("scripts.gui.history")
--local alerts_tab = require("scripts.gui.alerts")
local util = require("scripts.gui.util")
local manager = {}
--- @param player LuaPlayer
function manager.create(player)
local widths = constants.gui["en"]
---@type table<string, LuaGuiElement>
local refs = {}
gui.add(player.gui.screen, {
{
name = "manager_window",
type = "frame",
direction = "vertical",
visible = false,
--handler = manager.handle.manager_close,
children = {
{
name = "manager_titlebar",
type = "flow",
style = "flib_titlebar_flow",
handler = manager.handle.manager_titlebar_click,
children = {
{ type = "label", style = "frame_title", caption = { "mod-name.cybersyn" }, ignored_by_interaction = true },
{ type = "empty-widget", style = "flib_titlebar_drag_handle", ignored_by_interaction = true },
{
name = "manager_dispatcher_status_label",
type = "label",
style = "bold_label",
style_mods = { font_color = constants.colors.red.tbl, left_margin = -4, top_margin = 1 },
caption = { "cybersyn-gui.dispatcher-disabled" },
tooltip = { "cybersyn-gui.dispatcher-disabled-description" },
visible = not settings.global["cybersyn-enable-planner"].value,
},
--templates.frame_action_button("manager_pin_button", "ltnm_pin", { "cybersyn-gui.keep-open" }, manager.handle.manager_pin),--on_gui_clicked
--templates.frame_action_button("manager_refresh_button", "ltnm_refresh", { "cybersyn-gui.refresh-tooltip" }, manager.handle.manager_refresh_click),--on_gui_clicked
templates.frame_action_button(nil, "utility/close", { "gui.close-instruction" }, manager.handle
.manager_close), --on_gui_clicked
},
},
{
type = "frame",
style = "inside_deep_frame",
direction = "vertical",
children = {
{
type = "frame",
style = "ltnm_main_toolbar_frame",
children = {
{ type = "label", style = "subheader_caption_label", caption = { "cybersyn-gui.search-label" } },
{
name = "manager_text_search_field",
type = "textfield",
clear_and_focus_on_right_click = true,
handler = { [defines.events.on_gui_text_changed] = manager.handle.manager_update_text_search },
},
{ type = "label", style = "subheader_caption_label", caption = { "cybersyn-gui.search-item-label" } },
{
type = "choose-elem-button",
name = "manager_item_filter",
elem_type = "signal",
handler = manager.handle.manager_update_item_search
},
{ type = "empty-widget", style = "flib_horizontal_pusher" },
{ type = "label", style = "caption_label", caption = { "cybersyn-gui.network-name-label" } },
{
type = "choose-elem-button",
name = "network",
elem_type = "signal",
tooltip = { "cybersyn-gui.network-tooltip" },
handler = manager.handle.manager_update_network_name
},
{ type = "label", style = "caption_label", caption = { "cybersyn-gui.network-id-label" } },
{
name = "manager_network_mask_field",
type = "textfield",
style_mods = { width = 120 },
numeric = true,
allow_negative = true,
clear_and_focus_on_right_click = true,
text = "-1",
handler = { [defines.events.on_gui_text_changed] = manager.handle.manager_update_network_mask },
},
{ type = "label", style = "caption_label", caption = { "cybersyn-gui.surface-label" } },
{
name = "manager_surface_dropdown",
type = "drop-down",
handler = { [defines.events.on_gui_selection_state_changed] = manager.handle.manager_update_surface },
},
},
},
{
name = "manager_tabbed_pane",
type = "tabbed-pane",
style = "ltnm_tabbed_pane",
trains_tab.create(widths),
stations_tab.create(widths),
inventory_tab.create(),
selected_tab_index = 1,
},
},
},
},
},
}, refs)
refs.manager_titlebar.drag_target = refs.manager_window
refs.manager_window.force_auto_center()
return refs
end
--- @param player_data PlayerData
function manager.build(player_data)
local refs = player_data.refs
-- Surface dropdown
--- @type LuaGuiElement
local surface_dropdown = refs.manager_surface_dropdown
local surfaces = game.surfaces
local currently_selected_index = surface_dropdown.selected_index
local currently_selected_surface = nil
if currently_selected_index ~= (nil or 0) then
currently_selected_surface = surface_dropdown.get_item(currently_selected_index)
end
surface_dropdown.clear_items()
surface_dropdown.add_item("all", 1)
local i = 1
for name, _ in pairs(surfaces) do
i = i + 1
surface_dropdown.add_item(name, i)
--reselect same surface
if name == currently_selected_surface then
refs.manager_surface_dropdown.selected_index = i --[[@as uint]]
end
end
-- Validate that the selected index still exist
if player_data.search_surface_idx then
local selected_surface = game.get_surface(player_data.search_surface_idx)
-- If the surface was invalidated since last update, reset to all
if not selected_surface then
player_data.search_surface_idx = nil
end
end
-- sometimes manager_item_filter picked item is not saved for some reason
-- and then items are filtered but there is no indication in the GUI
-- restore the GUI elem from player_data here as a workaround
if player_data.search_item then
--- @type LuaGuiElement
local item_filter_elem = refs.manager_item_filter
item_filter_elem.elem_value = util.signalid_from_name(player_data.search_item)
end
-- same as above but for the network GUI elem
if player_data.search_network_name then
local network_filter_elem = refs.network
network_filter_elem.elem_value = util.signalid_from_name(player_data.search_network_name)
end
end
--- @param map_data MapData
--- @param player_data PlayerData
function manager.update(map_data, player_data, query_limit)
if player_data.selected_tab ~= nil then
manager.build(player_data)
end
if player_data.selected_tab == "stations_tab" then
stations_tab.build(map_data, player_data, query_limit)
elseif player_data.selected_tab == "inventory_tab" then
inventory_tab.build(map_data, player_data)
elseif player_data.selected_tab == "trains_tab" then
trains_tab.build(map_data, player_data, query_limit)
end
end
manager.handle = {}
--- @param e {player_index: uint}
function manager.wrapper(e, handler)
local player = game.get_player(e.player_index)
if not player then return end
local player_data = storage.manager.players[e.player_index]
handler(player, player_data, player_data.refs, e)
end
local function toggle_fab(elem, sprite, state)
if state then
elem.style = "flib_selected_frame_action_button"
elem.sprite = sprite .. ""
else
elem.style = "frame_action_button"
elem.sprite = sprite .. ""
end
end
--- @param player LuaPlayer
--- @param player_data PlayerData
--- @param refs table<string, LuaGuiElement>
function manager.handle.manager_open(player, player_data, refs)
refs.manager_window.bring_to_front()
refs.manager_window.visible = true
player_data.visible = true
if not player_data.pinning then
player.opened = refs.manager_window
end
player_data.is_manager_open = true
player.set_shortcut_toggled("cybersyn-toggle-gui", true)
end
--- @param player LuaPlayer
--- @param player_data PlayerData
--- @param refs table<string, LuaGuiElement>
function manager.handle.manager_close(player, player_data, refs)
util.close_manager_window(player, player_data, refs)
end
--- @param player LuaPlayer
--- @param player_data PlayerData
--- @param refs table<string, LuaGuiElement>
function manager.handle.manager_toggle(player, player_data, refs)
if player_data.is_manager_open then
manager.handle.manager_close(player, player_data, refs)
else
manager.handle.manager_open(player, player_data, refs)
end
end
--- @param player LuaPlayer
--- @param player_data PlayerData
--- @param refs table<string, LuaGuiElement>
function manager.handle.manager_recenter(player, player_data, refs)
refs.window.force_auto_center()
end
--- @param player LuaPlayer
--- @param player_data PlayerData
--- @param refs table<string, LuaGuiElement>
function manager.handle.manager_toggle_auto_refresh(player, player_data, refs)
player_data.auto_refresh = not player_data.auto_refresh
toggle_fab(refs.manager_refresh_button, "ltnm_refresh", player_data.auto_refresh)
end
--- @param player LuaPlayer
--- @param player_data PlayerData
--- @param refs table<string, LuaGuiElement>
function manager.handle.manager_toggle_pinned(player, player_data, refs)
player_data.pinned = not player_data.pinned
toggle_fab(refs.manager_pin_button, "ltnm_pin", player_data.pinned)
end
--- @param player LuaPlayer
--- @param player_data PlayerData
--- @param refs table<string, LuaGuiElement>
--- @param e GuiEventData
function manager.handle.manager_update_text_search(player, player_data, refs, e)
local query = e.text
if query then
-- Input sanitization
for pattern, replacement in pairs(constants.input_sanitizers) do
query = string.gsub(query, pattern, replacement)
end
end
player_data.search_query = query
end
--- @param player LuaPlayer
--- @param player_data PlayerData
--- @param refs table<string, LuaGuiElement>
--- @param e GuiEventData
function manager.handle.manager_update_item_search(player, player_data, refs, e)
local element = e.element
if not element then return end
local signal = e.element.elem_value
if signal then
player_data.search_item = signal.name
else
player_data.search_item = nil
end
end
--- @param player LuaPlayer
--- @param player_data PlayerData
--- @param refs table<string, LuaGuiElement>
--- @param e GuiEventData
function manager.handle.manager_update_network_name(player, player_data, refs, e)
local element = e.element
if not element then return end
local signal = element.elem_value
if signal then
player_data.search_network_name = signal.name
else
player_data.search_network_name = nil
end
end
--- @param player LuaPlayer
--- @param player_data PlayerData
--- @param refs table<string, LuaGuiElement>
--- @param e GuiEventData
function manager.handle.manager_update_network_mask(player, player_data, refs, e)
player_data.search_network_mask = tonumber(e.text) or -1
e.text = tostring(player_data.search_network_mask)
end
--- @param player LuaPlayer
--- @param player_data PlayerData
--- @param refs table<string, LuaGuiElement>
--- @param e GuiEventData
function manager.handle.manager_update_surface(player, player_data, refs, e)
local element = e.element
if not element then return end
local i = element.selected_index
---@type uint?
local surface_id = nil
--all surfaces should always be the first entry with an index of 1
if i > 1 then
local surface_name = refs.manager_surface_dropdown.get_item(i)
local surface = game.get_surface(surface_name)
if surface then
surface_id = surface.index
end
end
player_data.search_surface_idx = surface_id
end
gui.add_handlers(manager.handle, manager.wrapper)
return manager
| 412 | 0.951204 | 1 | 0.951204 | game-dev | MEDIA | 0.627398 | game-dev,desktop-app | 0.944301 | 1 | 0.944301 |
php-internal/dload | 3,478 | src/Module/Repository/Collection/AssetsCollection.php | <?php
declare(strict_types=1);
namespace Internal\DLoad\Module\Repository\Collection;
use Internal\DLoad\Module\Common\Architecture;
use Internal\DLoad\Module\Common\OperatingSystem;
use Internal\DLoad\Module\Repository\AssetInterface;
use Internal\DLoad\Module\Repository\Internal\Collection;
/**
* Collection of release assets with filtering capabilities.
*
* Provides methods to filter assets by architecture, operating system,
* file extension, and name patterns.
*
* ```php
* // Get Linux x86_64 assets with certain file extensions
* $assets = $release->getAssets()
* ->whereOperatingSystem(OperatingSystem::Linux)
* ->whereArchitecture(Architecture::X86_64)
* ->whereFileExtensions(['tar.gz', 'zip'])
* ->exceptDebPackages();
*
* // Find assets matching a pattern
* $assets = $release->getAssets()->whereNameMatches('/^app-v\d+/');
* ```
*
* @template-extends Collection<AssetInterface>
* @internal
* @psalm-internal Internal\DLoad\Module
*/
final class AssetsCollection extends Collection
{
/**
* Filters out Debian package assets.
*
* @return self New filtered collection
*/
public function exceptDebPackages(): self
{
return $this->except(
static fn(AssetInterface $asset): bool =>
\str_ends_with(\strtolower($asset->getName()), '.deb'),
);
}
/**
* Filters assets to include only those matching the specified architecture.
*
* @param Architecture $arch Required architecture
* @return self New filtered collection
*/
public function whereArchitecture(Architecture $arch): self
{
return $this->filter(
static fn(AssetInterface $asset): bool => $asset->getArchitecture() === $arch,
);
}
/**
* Filters assets to include only those matching the specified operating system.
*
* @param OperatingSystem $os Required operating system
* @return self New filtered collection
*/
public function whereOperatingSystem(OperatingSystem $os): self
{
return $this->filter(
static fn(AssetInterface $asset): bool => $asset->getOperatingSystem() === $os,
);
}
/**
* Filters assets to include only those with specified file extensions.
*
* @param list<non-empty-string> $extensions List of file extensions without leading dot
* @return self New filtered collection
*/
public function whereFileExtensions(array $extensions): self
{
return $this->filter(
static function (AssetInterface $asset) use ($extensions): bool {
$assetName = \strtolower($asset->getName());
foreach ($extensions as $extension) {
if (\str_ends_with($assetName, '.' . $extension)) {
return true;
}
}
return false;
},
);
}
/**
* Filters assets to include only those with names matching the given regex pattern.
*
* @param non-empty-string $pattern Regular expression pattern
* @return self New filtered collection
*/
public function whereNameMatches(string $pattern): self
{
return $this->filter(
static fn(AssetInterface $asset): bool => @\preg_match(
$pattern,
$asset->getName(),
flags: \PREG_NO_ERROR,
) === 1,
);
}
}
| 412 | 0.851863 | 1 | 0.851863 | game-dev | MEDIA | 0.33794 | game-dev | 0.828104 | 1 | 0.828104 |
eidosmontreal/unreal-vdb | 1,829 | Source/Runtime/Private/VdbToDynamicMeshActor.h | // Copyright 2022 Eidos-Montreal / Eidos-Sherbrooke
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http ://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include "CoreMinimal.h"
#include "DynamicMeshActor.h"
#include "VdbToDynamicMeshActor.generated.h"
// Actor that combines VdbToVolumeTexture component with a dynamic mesh.
// This class needs to be blueprinted, and the blueprint needs to implement UpdateDynamicMesh
// See BP_VdbToDynamicMesh for an example.
UCLASS(ClassGroup = Rendering, Meta = (ComponentWrapperClass))
class AVdbToDynamicMeshActor : public ADynamicMeshActor
{
GENERATED_UCLASS_BODY()
UFUNCTION(BlueprintImplementableEvent)
void UpdateDynamicMesh();
private:
#if WITH_EDITOR
virtual bool GetReferencedContentObjects(TArray<UObject*>& Objects) const override;
#endif
UPROPERTY(BlueprintReadOnly, VisibleAnywhere, Category = Volumetric, meta = (AllowPrivateAccess = "true"))
TObjectPtr<class UVdbAssetComponent> AssetComponent;
UPROPERTY(BlueprintReadOnly, VisibleAnywhere, Category = Volumetric, meta = (AllowPrivateAccess = "true"))
TObjectPtr<class UVdbToVolumeTextureComponent> VdbToTexComponent;
UPROPERTY(BlueprintReadOnly, VisibleAnywhere, Category = Volumetric, meta = (AllowPrivateAccess = "true"))
TObjectPtr<class UVdbSequenceComponent> SequenceComponent;
void UpdateDynamicMeshInternal(uint32 FrameIndex);
}; | 412 | 0.927419 | 1 | 0.927419 | game-dev | MEDIA | 0.594033 | game-dev,graphics-rendering | 0.713996 | 1 | 0.713996 |
DarkstarProject/darkstar | 2,262 | scripts/zones/Promyvion-Dem/Zone.lua | -----------------------------------
--
-- Zone: Promyvion-Dem (18)
--
-----------------------------------
local ID = require("scripts/zones/Promyvion-Dem/IDs")
require("scripts/globals/promyvion")
require("scripts/globals/keyitems")
require("scripts/globals/missions")
require("scripts/globals/settings")
require("scripts/globals/status")
-----------------------------------
function onInitialize(zone)
dsp.promyvion.initZone(zone)
end
function onZoneIn(player, prevZone)
local cs = -1
if player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0 then
player:setPos(185.891, 0, -52.331, 128)
end
if player:getCurrentMission(COP) == dsp.mission.id.cop.BELOW_THE_ARKS and player:getCharVar("PromathiaStatus") == 2 then
player:completeMission(COP, dsp.mission.id.cop.BELOW_THE_ARKS)
player:addMission(COP, dsp.mission.id.cop.THE_MOTHERCRYSTALS)
player:setCharVar("PromathiaStatus", 0)
elseif player:getCurrentMission(COP) == dsp.mission.id.cop.THE_MOTHERCRYSTALS then
if player:hasKeyItem(dsp.ki.LIGHT_OF_HOLLA) and player:hasKeyItem(dsp.ki.LIGHT_OF_MEA) then
if player:getCharVar("cslastpromy") == 1 then
player:setCharVar("cslastpromy", 0)
cs = 52
end
elseif player:hasKeyItem(dsp.ki.LIGHT_OF_HOLLA) or player:hasKeyItem(dsp.ki.LIGHT_OF_MEA) then
if player:getCharVar("cs2ndpromy") == 1 then
player:setCharVar("cs2ndpromy", 0)
cs = 51
end
end
end
if player:getCharVar("FirstPromyvionDem") == 1 then
cs = 50
end
return cs
end
function afterZoneIn(player)
if ENABLE_COP_ZONE_CAP == 1 then
player:addStatusEffect(dsp.effect.LEVEL_RESTRICTION, 30, 0, 0)
end
end
function onRegionEnter(player, region)
dsp.promyvion.onRegionEnter(player, region)
end
function onRegionLeave(player, region)
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
if csid == 46 and option == 1 then
player:setPos(-226.193, -46.459, -280.046, 127, 14) -- To Hall of Transference {R}
elseif csid == 50 then
player:setCharVar("FirstPromyvionDem", 0)
end
end | 412 | 0.909441 | 1 | 0.909441 | game-dev | MEDIA | 0.980607 | game-dev | 0.98977 | 1 | 0.98977 |
Baystation12/Baystation12 | 19,755 | code/modules/mechs/equipment/combat.dm | /obj/item/mech_equipment/mounted_system/taser
name = "mounted burst electrolaser carbine"
desc = "A dual fire mode burst electrolaser system connected to the exosuit's targetting system."
icon_state = "mech_taser"
holding_type = /obj/item/gun/energy/taser/carbine/mounted/mech
restricted_hardpoints = list(HARDPOINT_LEFT_HAND, HARDPOINT_RIGHT_HAND)
restricted_software = list(MECH_SOFTWARE_WEAPONS)
/obj/item/mech_equipment/mounted_system/taser/ion
name = "mounted ion rifle"
desc = "An exosuit-mounted ion rifle. Handle with care."
icon_state = "mech_ionrifle"
holding_type = /obj/item/gun/energy/ionrifle/mounted/mech
/obj/item/mech_equipment/mounted_system/taser/laser
name = "\improper CH-PS \"Immolator\" laser"
desc = "An exosuit-mounted laser rifle. Handle with care."
icon_state = "mech_lasercarbine"
holding_type = /obj/item/gun/energy/lasercannon/mounted/mech
/obj/item/gun/energy/taser/carbine/mounted/mech
use_external_power = TRUE
has_safety = FALSE
self_recharge = TRUE
burst = 3
burst_delay = 3
dispersion = list(-1.5,1,1.5)
/obj/item/gun/energy/ionrifle/mounted/mech
use_external_power = TRUE
has_safety = FALSE
self_recharge = TRUE
/obj/item/gun/energy/lasercannon/mounted/mech
name = "\improper CH-PS \"Immolator\" laser"
use_external_power = TRUE
has_safety = FALSE
self_recharge = TRUE
fire_delay = 15
accuracy = 2
/obj/item/gun/energy/get_hardpoint_maptext()
if (charge_cost <= 0)
return "INF"
return "[round(power_supply.charge / charge_cost)]/[max_shots]"
/obj/item/gun/energy/get_hardpoint_status_value()
var/obj/item/cell/C = get_cell()
if(istype(C))
return C.charge/C.maxcharge
return null
/obj/item/mech_equipment/shields
name = "exosuit shield droid"
desc = "The Hephaestus Armature system is a well liked energy deflector system designed to stop any projectile before it has a chance to become a threat."
icon_state = "shield_droid"
var/obj/aura/mechshield/aura = null
var/max_charge = 150
var/charge = 150
var/last_recharge = 0
var/charging_rate = 7500 * CELLRATE
var/cooldown = 3.5 SECONDS //Time until we can recharge again after a blocked impact
restricted_hardpoints = list(HARDPOINT_BACK)
restricted_software = list(MECH_SOFTWARE_WEAPONS)
/obj/item/mech_equipment/shields/installed(mob/living/exosuit/_owner)
. = ..()
aura = new(owner, src)
/obj/item/mech_equipment/shields/uninstalled()
QDEL_NULL(aura)
. = ..()
/obj/item/mech_equipment/shields/attack_self(mob/user)
. = ..()
if(.)
toggle()
/obj/item/mech_equipment/shields/proc/stop_damage(damage)
var/difference = damage - charge
charge = clamp(charge - damage, 0, max_charge)
last_recharge = world.time
if(difference > 0)
for(var/mob/pilot in owner.pilots)
to_chat(pilot, SPAN_DANGER("Warning: Deflector shield failure detect, shutting down"))
toggle()
playsound(owner.loc,'sound/mecha/internaldmgalarm.ogg',35,1)
return difference
else return 0
/obj/item/mech_equipment/shields/proc/toggle()
if(!aura)
return
aura.toggle()
playsound(owner,'sound/weapons/flash.ogg',35,1)
update_icon()
if(aura.active)
START_PROCESSING(SSobj, src)
else
STOP_PROCESSING(SSobj, src)
active = aura.active
passive_power_use = active ? 1 KILOWATTS : 0
owner.update_icon()
/obj/item/mech_equipment/shields/deactivate()
if(active)
toggle()
..()
/obj/item/mech_equipment/shields/on_update_icon()
if(!aura)
return
if(aura.active)
icon_state = "shield_droid_a"
else
icon_state = "shield_droid"
/obj/item/mech_equipment/shields/Process()
if(charge >= max_charge)
return
if((world.time - last_recharge) < cooldown)
return
var/obj/item/cell/cell = owner.get_cell()
var/actual_required_power = clamp(max_charge - charge, 0, charging_rate)
if(cell)
charge += cell.use(actual_required_power)
/obj/item/mech_equipment/shields/get_hardpoint_status_value()
return charge / max_charge
/obj/item/mech_equipment/shields/get_hardpoint_maptext()
return "[(aura && aura.active) ? "ONLINE" : "OFFLINE"]: [round((charge / max_charge) * 100)]%"
/obj/aura/mechshield
icon = 'icons/mecha/shield.dmi'
name = "mechshield"
var/obj/item/mech_equipment/shields/shields = null
var/active = 0
layer = ABOVE_HUMAN_LAYER
var/north_layer = MECH_UNDER_LAYER
plane = DEFAULT_PLANE
pixel_x = 8
pixel_y = 4
mouse_opacity = 0
/obj/aura/mechshield/Initialize(maploading, obj/item/mech_equipment/shields/holder)
. = ..()
shields = holder
/obj/aura/mechshield/added_to(mob/living/target)
. = ..()
target.add_vis_contents(src)
set_dir()
GLOB.dir_set_event.register(user, src, PROC_REF(update_dir))
/obj/aura/mechshield/proc/update_dir(user, old_dir, dir)
set_dir(dir)
/obj/aura/mechshield/set_dir(new_dir)
. = ..()
if(dir == NORTH)
layer = north_layer
else layer = initial(layer)
/obj/aura/mechshield/Destroy()
if(user)
GLOB.dir_set_event.unregister(user, src, PROC_REF(update_dir))
user.remove_vis_contents(src)
shields = null
. = ..()
/obj/aura/mechshield/proc/toggle()
active = !active
update_icon()
if(active)
flick("shield_raise", src)
else
flick("shield_drop", src)
/obj/aura/mechshield/on_update_icon()
if(active)
icon_state = "shield"
else
icon_state = "shield_null"
/obj/aura/mechshield/aura_check_bullet(obj/item/projectile/proj, def_zone)
if (active && shields?.charge)
proj.damage = shields.stop_damage(proj.damage)
user.visible_message(SPAN_WARNING("\The [shields.owner]'s shields flash and crackle."))
flick("shield_impact", src)
playsound(user,'sound/effects/basscannon.ogg',35,1)
new /obj/effect/smoke/illumination(user.loc, 5, 4, 1, "#ffffff")
if (proj.damage <= 0)
return AURA_FALSE|AURA_CANCEL
var/datum/effect/spark_spread/spark_system = new /datum/effect/spark_spread()
spark_system.set_up(5, 0, user)
spark_system.start()
playsound(loc, "sparks", 25, 1)
return FLAGS_OFF
/obj/aura/mechshield/aura_check_thrown(atom/movable/thrown_atom, datum/thrownthing/thrown_datum)
. = ..()
if (active && shields?.charge && thrown_datum.speed <= 5)
user.visible_message(SPAN_WARNING("\The [shields.owner]'s shields flash briefly as they deflect \the [thrown_atom]."))
flick("shield_impact", src)
playsound(user, 'sound/effects/basscannon.ogg', 10, TRUE)
return AURA_FALSE|AURA_CANCEL
//Melee! As a general rule I would recommend using regular objects and putting logic in them.
/obj/item/mech_equipment/mounted_system/melee
restricted_hardpoints = list(HARDPOINT_LEFT_HAND, HARDPOINT_RIGHT_HAND)
restricted_software = list(MECH_SOFTWARE_UTILITY)
/obj/item/material/hatchet/machete/mech
name = "mechete"
desc = "That thing was too big to be called a machete. Too big, too thick, too heavy, and too rough, it was more like a large hunk of iron."
w_class = ITEM_SIZE_GARGANTUAN
slot_flags = 0
default_material = MATERIAL_STEEL
base_parry_chance = 0 //Irrelevant for exosuits, revise if this changes
max_force = 35 // If we want to edit the force, use this number! The one below is prone to be changed when anything material gets modified.
force_multiplier = 0.75 // Equals 20 AP with 45 force with hardness 60 (Steel)
unbreakable = TRUE //Else we need a whole system for replacement blades
attack_cooldown_modifier = 10
/obj/item/material/hatchet/machete/mech/apply_hit_effect(mob/living/target, mob/living/user, hit_zone)
. = ..()
if (.)
do_attack_effect(target, "smash")
if (target.mob_size < user.mob_size) //Damaging attacks overwhelm smaller mobs
target.throw_at(get_edge_target_turf(target,get_dir(user, target)),1, 1)
/obj/item/material/hatchet/machete/mech/attack_self(mob/living/user)
. = ..()
if (user.a_intent != I_HURT)
return
var/obj/item/mech_equipment/mounted_system/melee/mechete/MC = loc
if (istype(MC))
//SPIN BLADE ATTACK GO!
var/mob/living/exosuit/E = MC.owner
if (E)
E.setClickCooldown(1.35 SECONDS)
E.visible_message(SPAN_DANGER("\The [E] swings \the [src] back, preparing for an attack!"), blind_message = SPAN_DANGER("You hear the loud hissing of hydraulics!"))
playsound(E, 'sound/mecha/mech_punch_fast.ogg', 35, 1)
if (do_after(E, 1.2 SECONDS, get_turf(user), DO_DEFAULT | DO_USER_UNIQUE_ACT | DO_PUBLIC_PROGRESS) && E && MC)
for (var/mob/living/M in orange(1, E))
M.use_weapon(src, E)
E.spin(0.65 SECONDS, 0.125 SECONDS)
playsound(E, 'sound/mecha/mechstep01.ogg', 40, 1)
/obj/item/mech_equipment/mounted_system/melee/mechete
icon_state = "mech_blade"
holding_type = /obj/item/material/hatchet/machete/mech
//Ballistic shield
/obj/item/mech_equipment/ballistic_shield
name = "exosuit ballistic shield"
desc = "The Hephaestus Bulwark is a formidable line of defense that sees widespread use in planetary peacekeeping operations and military formations alike."
icon_state = "mech_shield" //Rendering is handled by aura due to layering issues: TODO, figure out a better way to do this
var/obj/aura/mech_ballistic/aura = null
var/last_push = 0
var/chance = 60 //For attacks from the front, diminishing returns
var/last_max_block = 0 //Blocking during a perfect block window resets this, else there is an anti spam
var/max_block = 60 // Should block most things
var/blocking = FALSE
restricted_hardpoints = list(HARDPOINT_LEFT_HAND, HARDPOINT_RIGHT_HAND)
restricted_software = list(MECH_SOFTWARE_UTILITY)
/obj/item/mech_equipment/ballistic_shield/installed(mob/living/exosuit/_owner)
. = ..()
aura = new(owner, src)
/obj/item/mech_equipment/ballistic_shield/uninstalled()
QDEL_NULL(aura)
. = ..()
/obj/item/mech_equipment/ballistic_shield/afterattack(atom/target, mob/living/user, inrange, params)
. = ..()
if (.)
if (user.a_intent == I_HURT )
if (last_push + 1.6 SECONDS < world.time)
owner.visible_message(SPAN_WARNING("\The [owner] retracts \the [src], preparing to push with it!"), blind_message = SPAN_WARNING("You hear the whine of hydraulics and feel a rush of air!"))
owner.setClickCooldown(0.7 SECONDS)
last_push = world.time
if (do_after(owner, 0.5 SECONDS, get_turf(owner), DO_DEFAULT | DO_USER_UNIQUE_ACT | DO_PUBLIC_PROGRESS) && owner)
owner.visible_message(SPAN_WARNING("\The [owner] slams the area in front \the [src]!"), blind_message = SPAN_WARNING("You hear a loud hiss and feel a strong gust of wind!"))
playsound(src ,'sound/effects/bang.ogg',35,1)
var/list/turfs = list()
var/front = get_step(get_turf(owner), owner.dir)
turfs += front
turfs += get_step(front, turn(owner.dir, -90))
turfs += get_step(front, turn(owner.dir, 90))
for(var/turf/T in turfs)
for(var/mob/living/M in T)
if (!M.Adjacent(owner))
continue
M.attack_generic(owner, (owner.arms ? owner.arms.melee_damage * 0.2 : 0), "slammed")
M.throw_at(get_edge_target_turf(owner ,owner.dir),5, 2)
do_attack_effect(T, "smash")
/obj/item/mech_equipment/ballistic_shield/attack_self(mob/user)
. = ..()
if (.) //FORM A SHIELD WALL!
if (last_max_block + 2 SECONDS < world.time)
owner.visible_message(SPAN_WARNING("\The [owner] raises \the [src], locking it in place!"), blind_message = SPAN_WARNING("You hear the whir of motors and scratching metal!"))
playsound(src ,'sound/effects/bamf.ogg',35,1)
owner.setClickCooldown(0.8 SECONDS)
blocking = TRUE
last_max_block = world.time
do_after(owner, 0.75 SECONDS, get_turf(user), DO_DEFAULT | DO_USER_UNIQUE_ACT | DO_PUBLIC_PROGRESS)
blocking = FALSE
else
to_chat(user, SPAN_WARNING("You are not ready to block again!"))
/obj/item/mech_equipment/ballistic_shield/proc/block_chance(damage, pen, atom/source, mob/attacker)
if (damage > max_block || pen > max_block)
return 0
else
var/effective_block = blocking ? chance * 1.5 : chance
var/conscious_pilot_exists = FALSE
for (var/mob/living/pilot in owner.pilots)
if (!pilot.incapacitated())
conscious_pilot_exists = TRUE
break
if (!conscious_pilot_exists)
effective_block *= 0.5 //Who is going to block anything?
//Bit copypasta but I am doing something different from normal shields
var/attack_dir = 0
if (istype(source, /obj/item/projectile))
var/obj/item/projectile/P = source
attack_dir = get_dir(get_turf(src), P.starting)
else if (attacker)
attack_dir = get_dir(get_turf(src), get_turf(attacker))
else if (source)
attack_dir = get_dir(get_turf(src), get_turf(source))
if (attack_dir == turn(owner.dir, -90) || attack_dir == turn(owner.dir, 90))
effective_block *= 0.8
else if (attack_dir == turn(owner.dir, 180))
effective_block = 0
return effective_block
/obj/item/mech_equipment/ballistic_shield/proc/on_block_attack()
if (blocking)
//Reset timer for maximum chainblocks
last_max_block = 0
/obj/aura/mech_ballistic
icon = 'icons/mecha/ballistic_shield.dmi'
name = "mech_ballistic_shield"
var/obj/item/mech_equipment/ballistic_shield/shield = null
layer = MECH_UNDER_LAYER
plane = DEFAULT_PLANE
mouse_opacity = 0
/obj/aura/mech_ballistic/Initialize(maploading, obj/item/mech_equipment/ballistic_shield/holder)
. = ..()
shield = holder
//Get where we are attached so we know what icon to use
if (holder && holder.owner)
var/mob/living/exosuit/E = holder.owner
for (var/hardpoint in E.hardpoints)
var/obj/item/mech_equipment/hardpoint_object = E.hardpoints[hardpoint]
if (holder == hardpoint_object)
icon_state = "mech_shield_[hardpoint]"
var/image/I = image(icon, "[icon_state]_over")
I.layer = ABOVE_HUMAN_LAYER
AddOverlays(I)
/obj/aura/mech_ballistic/added_to(mob/living/target)
. = ..()
target.add_vis_contents(src)
set_dir()
GLOB.dir_set_event.register(user, src, PROC_REF(update_dir))
/obj/aura/mech_ballistic/proc/update_dir(user, old_dir, dir)
set_dir(dir)
/obj/aura/mech_ballistic/Destroy()
if (user)
GLOB.dir_set_event.unregister(user, src, PROC_REF(update_dir))
user.remove_vis_contents(src)
shield = null
. = ..()
/obj/aura/mech_ballistic/aura_check_bullet(obj/item/projectile/proj, def_zone)
. = ..()
if (shield && prob(shield.block_chance(proj.damage, proj.armor_penetration, source = proj)))
user.visible_message(SPAN_WARNING("\The [proj] is blocked by \the [user]'s [shield]."))
user.bullet_impact_visuals(proj, def_zone, 0)
return AURA_FALSE|AURA_CANCEL
/obj/aura/mech_ballistic/aura_check_thrown(atom/movable/thrown_atom, datum/thrownthing/thrown_datum)
. = ..()
if (shield)
var/throw_damage = 0
if (isobj(thrown_atom))
var/obj/object = thrown_atom
throw_damage = object.throwforce * (thrown_datum.speed / THROWFORCE_SPEED_DIVISOR)
if (prob(shield.block_chance(throw_damage, 0, source = thrown_atom, attacker = thrown_datum.thrower)))
user.visible_message(SPAN_WARNING("\The [thrown_atom] bounces off \the [user]'s [shield]."))
playsound(user.loc, 'sound/weapons/Genhit.ogg', 50, 1)
return AURA_FALSE|AURA_CANCEL
/obj/aura/mech_ballistic/aura_check_weapon(obj/item/weapon, mob/attacker, click_params)
. = ..()
if (shield && prob(shield.block_chance(weapon.force, weapon.armor_penetration, source = weapon, attacker = user)))
user.visible_message(SPAN_WARNING("\The [weapon] is blocked by \the [user]'s [shield]."))
playsound(user.loc, 'sound/weapons/Genhit.ogg', 50, TRUE)
return AURA_FALSE|AURA_CANCEL
/obj/item/mech_equipment/flash
name = "exosuit flash"
icon_state = "mech_flash"
var/flash_min = 7
var/flash_max = 9
var/flash_range = 3
restricted_hardpoints = list(HARDPOINT_LEFT_SHOULDER, HARDPOINT_RIGHT_SHOULDER)
restricted_software = list(MECH_SOFTWARE_WEAPONS)
active_power_use = 7 KILOWATTS
var/next_use = 0
origin_tech = list(TECH_MAGNET = 2, TECH_COMBAT = 2)
/obj/item/mech_equipment/flash/proc/area_flash()
playsound(src.loc, 'sound/weapons/flash.ogg', 100, 1)
var/flash_time = (rand(flash_min,flash_max) - 1)
var/obj/item/cell/C = owner.get_cell()
C.use(active_power_use * CELLRATE)
for (var/mob/living/O in oviewers(flash_range, owner))
if(istype(O))
var/protection = O.eyecheck()
if(protection >= FLASH_PROTECTION_MODERATE)
return
if(protection >= FLASH_PROTECTION_MINOR)
flash_time /= 2
if(ishuman(O))
var/mob/living/carbon/human/H = O
flash_time = round(H.getFlashMod() * flash_time)
if(flash_time <= 0)
return
if(!O.blinded)
O.flash_eyes(FLASH_PROTECTION_MODERATE - protection)
O.eye_blurry += flash_time
O.mod_confused(flash_time + 2)
/obj/item/mech_equipment/flash/attack_self(mob/user)
. = ..()
if(.)
if(world.time < next_use)
to_chat(user, SPAN_WARNING("\The [src] is recharging!"))
return
next_use = world.time + 20
area_flash()
owner.setClickCooldown(5)
/obj/item/mech_equipment/flash/afterattack(atom/target, mob/living/user, inrange, params)
. = ..()
if(.)
if(world.time < next_use)
to_chat(user, SPAN_WARNING("\The [src] is recharging!"))
return
var/mob/living/O = target
owner.setClickCooldown(5)
next_use = world.time + 15
if(istype(O))
playsound(src.loc, 'sound/weapons/flash.ogg', 100, 1)
var/flash_time = (rand(flash_min,flash_max))
var/obj/item/cell/C = owner.get_cell()
C.use(active_power_use * CELLRATE)
var/protection = O.eyecheck()
if(protection >= FLASH_PROTECTION_MAJOR)
return
if(protection >= FLASH_PROTECTION_MODERATE)
flash_time /= 2
if(ishuman(O))
var/mob/living/carbon/human/H = O
flash_time = round(H.getFlashMod() * flash_time)
if(flash_time <= 0)
return
if(!O.blinded)
O.flash_eyes(FLASH_PROTECTION_MAJOR - protection)
O.eye_blurry += flash_time
O.mod_confused(flash_time + 2)
if(isanimal(O)) //Hit animals a bit harder
O.Stun(flash_time)
else
O.Stun(flash_time / 2)
if(flash_time > 3)
O.drop_l_hand()
O.drop_r_hand()
if(flash_time > 5)
O.Weaken(3)
/obj/item/flamethrower/full/mech
max_beaker = ITEM_SIZE_NORMAL
range = 5
desc = "A Hephaestus brand 'Prometheus' flamethrower. Bigger and better."
/obj/item/flamethrower/full/mech/Initialize()
. = ..()
beaker = new /obj/item/reagent_containers/chem_disp_cartridge(src)
/obj/item/flamethrower/full/mech/get_hardpoint_maptext()
return beaker ? "[lit ? "ON" : "OFF"]-:-[beaker.reagents.total_volume]/[beaker.reagents.maximum_volume]" : "NO TANK"
/obj/item/flamethrower/full/mech/get_hardpoint_status_value()
return beaker ? beaker.reagents.total_volume/beaker.reagents.maximum_volume : 0
/obj/item/mech_equipment/mounted_system/flamethrower
icon_state = "mech_flamer"
holding_type = /obj/item/flamethrower/full/mech
restricted_hardpoints = list(HARDPOINT_LEFT_HAND, HARDPOINT_RIGHT_HAND)
restricted_software = list(MECH_SOFTWARE_WEAPONS)
/obj/item/mech_equipment/mounted_system/flamethrower/attack_self(mob/user)
. = ..()
if(owner && holding)
update_icon()
/obj/item/mech_equipment/mounted_system/flamethrower/use_tool(obj/item/W, mob/living/user, list/click_params)
if(!CanPhysicallyInteract(user)) return ..()
var/obj/item/flamethrower/full/mech/FM = holding
if(istype(FM))
if(isCrowbar(W) && FM.beaker)
if(FM.beaker)
user.visible_message(SPAN_NOTICE("\The [user] pries out \the [FM.beaker] using \the [W]."))
FM.beaker.dropInto(get_turf(user))
FM.beaker = null
return TRUE
if (istype(W, /obj/item/reagent_containers) && W.is_open_container() && (W.w_class <= FM.max_beaker))
if(FM.beaker)
to_chat(user, SPAN_NOTICE("There is already a tank inserted!"))
return TRUE
if(user.unEquip(W, FM))
user.visible_message(SPAN_NOTICE("\The [user] inserts \the [W] inside \the [src]."))
FM.beaker = W
return TRUE
return ..()
/obj/item/mech_equipment/mounted_system/flamethrower/on_update_icon()
if(owner && holding)
var/obj/item/flamethrower/full/mech/FM = holding
if(istype(FM))
if(FM.lit)
icon_state = "mech_flamer_lit"
else icon_state = "mech_flamer"
if(owner)
owner.update_icon()
| 412 | 0.982254 | 1 | 0.982254 | game-dev | MEDIA | 0.99083 | game-dev | 0.979768 | 1 | 0.979768 |
IPVP-MC/canvas | 9,891 | src/main/java/org/ipvp/canvas/Menu.java | /*
* Copyright (C) Matthew Steglinski (SainttX) <matt@ipvp.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.ipvp.canvas;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.inventory.InventoryAction;
import org.ipvp.canvas.mask.Mask;
import org.ipvp.canvas.slot.Slot;
/**
* A menu represents an interactive interface for Players backed by instances of
* Inventories.
* <p>
* Menu interaction will not function properly unless an instance of {@link MenuFunctionListener}
* is properly registered with the Bukkit event scheduler.
*/
public interface Menu extends Iterable<Slot> {
/**
* Drop handler that allows all cursor items to be dropped by default.
*
* <p>Apply to a menu using {@link #setCursorDropHandler(CursorDropHandler)}.
*/
CursorDropHandler ALLOW_CURSOR_DROPPING = (p, c) -> c.setResult(Event.Result.ALLOW);
/**
* Returns the fallback Menu for when this menu is closed
*
* @return The parent menu
*/
Optional<Menu> getParent();
/**
* Returns whether this menu will redraw.
*
* <p>If a player has an existing menu open and the
* dimensions of the open inventory are the same as
* this menu, then the contents of this menu will
* be applied to the current inventory to preserve
* cursor location.
*
* <p>Note: This feature cannot redraw the name of
* inventories, so when a new inventory is open
* and the contents are redrawn the name will not
* change.
*
* @return redraw status
*/
boolean isRedraw();
/**
* Returns all players that are currently viewing
* this menu.
*
* @return players viewing menu
*/
Collection<Player> getViewers();
/**
* Returns whether the player currently has this menu open.
*
* @param viewer Player
* @return true if the player has this menu open, false otherwise
*/
boolean isOpen(Player viewer);
/**
* Opens the Menu for a Player
*
* @param viewer The player to view the Menu
*/
void open(Player viewer);
/**
* Closes the menu for all viewers.
*
* @see #close(Player)
*/
void close();
/**
* Closes the Menu for a viewing Player
*
* @param viewer The player who currently is viewing this Menu
* @throws IllegalStateException If the Player is not viewing the Menu
*/
void close(Player viewer) throws IllegalStateException;
/**
* Re-renders the menu for all viewers.
*
* @see #update(Player)
*/
void update();
/**
* Re-renders the menu for the player.
*
* <p>If any items have changed in the inventory and a
* {@link Slot} has a non-null item then any changes
* for that slot will be overwritten.
*
* @param viewer player viewing inventory
* @throws IllegalStateException If player is not viewing the menu
*/
void update(Player viewer) throws IllegalStateException;
/**
* Returns all slots that belong to this menu.
*
* @return the menus slots
*/
List<Slot> getSlots();
/**
* Returns all slots in this menu that are affected by the
* mask.
*
* @param mask mask to get slots of
* @return menu slots affected by mask
*/
List<Slot> getSlots(Mask mask);
/**
* Returns the Slot found at the given index of the Menu.
*
* @param index The index of the Slot
* @return The Slot at the index
*/
Slot getSlot(int index);
/**
* Returns the Slot found at the given row and column of the Menu.
*
* <p>Rows and columns are not 0-indexed and both start at 1. For instance,
* the very first slot of an inventory (slot 0, top left corner) is
* the slot in the first row and first column. The last slot in
* a double chest is the slot in the sixth row and ninth column.
*
* @param row menu row
* @param column menu column
* @return slot at coordinates
*/
Slot getSlot(int row, int column);
/**
* Clears out the whole Menu
*/
void clear();
/**
* Clears out a particular Slot at the given index
*
* @param index The index number to clear
*/
void clear(int index);
/**
* Returns the dimensions of the Menu
*
* @return The menus row and column count
*/
Dimension getDimensions();
/**
* Returns a user-defined handler for when a Player closes the menu.
*
* @return The close handler
*/
Optional<CloseHandler> getCloseHandler();
/**
* Sets a new handler policy for when a Player closes the menu.
*
* @param handler The new close handler
*/
void setCloseHandler(CloseHandler handler);
/**
* Gets the cursor drop handler.
*
* @return drop handler
*/
Optional<CursorDropHandler> getCursorDropHandler();
/**
* Sets a new handler policy for when players drop items from their cursor
* outside the menu.
*
* @param handler drop handler
*/
void setCursorDropHandler(CursorDropHandler handler);
/**
* A Menu close handler is a user defined function or policy that occurs when a
* Player closes a menu.
*/
@FunctionalInterface
interface CloseHandler {
/**
* Called when a Player closes a menu, be it by navigating to a different
* inventory screen, or logging off.
*
* @param player The player that closed the menu
* @param menu Menu that was closed
*/
void close(Player player, Menu menu);
}
/**
* Interface for handling events where a player drops an item using their
* cursor outside the menu.
*
* <p>Since there is no slot clicked, this handler is triggered when an inventory
* action with type {@link InventoryAction#DROP_ONE_CURSOR} or {@link InventoryAction#DROP_ALL_CURSOR}
* is performed in an inventory.
*/
@FunctionalInterface
interface CursorDropHandler {
/**
* Called when a player drops an item with their cursor.
*
* @param player player dropping an item
* @param click information about the performed click
*/
void click(Player player, CursorDropInformation click);
}
/**
* A Builder for Menus
*/
interface Builder<T extends Builder<T>> {
/**
* Returns the dimensions of the Menu to be created.
*
* @return menu dimensions
*/
Dimension getDimensions();
/**
* Adds a title to this Menu
*
* @param title The title to display
* @return Fluent pattern
*/
T title(String title);
/**
* Adds a fallback parent to this Menu
*
* @param parent The fallback GUI
* @return Fluent pattern
*/
T parent(Menu parent);
/**
* Sets the redraw flag of this Menu.
*
* @param redraw redraw flag
* @return Fluent pattern
* @see #isRedraw()
*/
T redraw(boolean redraw);
/**
* Builds the Menu from the given data
*
* @return The instance of Menu, if successful
*/
Menu build();
}
/**
* Represents the dimensions of a Menu
*/
class Dimension {
private final int rows;
private final int columns;
public Dimension(int rows, int columns) {
this.rows = rows;
this.columns = columns;
}
/**
* Returns the number of rows in the Menu
*
* @return The row count
*/
public int getRows() {
return rows;
}
/**
* Returns the number of columns in the Menu
*
* @return The column count
*/
public int getColumns() {
return columns;
}
/**
* Returns the total area (slots) of the Menu
*
* @return The slot count
*/
public int getArea() {
return rows * columns;
}
@Override
public int hashCode() {
return rows * 31 + columns * 31;
}
@Override
public boolean equals(Object other) {
if (other == this) {
return true;
} else if (!(other instanceof Dimension)) {
return false;
}
Dimension o = (Dimension) other;
return o.rows == this.rows && o.columns == this.columns;
}
}
}
| 412 | 0.948177 | 1 | 0.948177 | game-dev | MEDIA | 0.369825 | game-dev | 0.946862 | 1 | 0.946862 |
folgerwang/UnrealEngine | 1,376 | Engine/Source/Editor/UMGEditor/Private/Designer/SZoomPan.cpp | // Copyright 1998-2019 Epic Games, Inc. All Rights Reserved.
#include "Designer/SZoomPan.h"
#include "Layout/LayoutUtils.h"
/////////////////////////////////////////////////////
// SZoomPan
void SZoomPan::Construct(const FArguments& InArgs)
{
ViewOffset = InArgs._ViewOffset;
ZoomAmount = InArgs._ZoomAmount;
ChildSlot
[
InArgs._Content.Widget
];
}
void SZoomPan::SetContent(const TSharedRef< SWidget >& InContent)
{
ChildSlot
[
InContent
];
}
void SZoomPan::OnArrangeChildren(const FGeometry& AllottedGeometry, FArrangedChildren& ArrangedChildren) const
{
const EVisibility ChildVisibility = ChildSlot.GetWidget()->GetVisibility();
if ( ArrangedChildren.Accepts(ChildVisibility) )
{
const FMargin SlotPadding(ChildSlot.SlotPadding.Get());
AlignmentArrangeResult XResult = AlignChild<Orient_Horizontal>(AllottedGeometry.Size.X, ChildSlot, SlotPadding, 1);
AlignmentArrangeResult YResult = AlignChild<Orient_Vertical>(AllottedGeometry.Size.Y, ChildSlot, SlotPadding, 1);
ArrangedChildren.AddWidget( ChildVisibility, AllottedGeometry.MakeChild(
ChildSlot.GetWidget(),
FVector2D(XResult.Offset, YResult.Offset) - ViewOffset.Get(),
ChildSlot.GetWidget()->GetDesiredSize(),
ZoomAmount.Get()
) );
}
}
float SZoomPan::GetRelativeLayoutScale(const FSlotBase& Child, float LayoutScaleMultiplier) const
{
return ZoomAmount.Get();
}
| 412 | 0.802167 | 1 | 0.802167 | game-dev | MEDIA | 0.331074 | game-dev | 0.984929 | 1 | 0.984929 |
mariumbacchus/Soulslike-Weaponry | 1,342 | src/main/java/net/soulsweaponry/blocks/ChungusMonolith.java | package net.soulsweaponry.blocks;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.block.FacingBlock;
import net.minecraft.item.ItemPlacementContext;
import net.minecraft.state.StateManager;
import net.minecraft.state.property.DirectionProperty;
import net.minecraft.util.BlockMirror;
import net.minecraft.util.BlockRotation;
import net.minecraft.util.math.Direction;
public class ChungusMonolith extends Block {
public static final DirectionProperty FACING = FacingBlock.FACING;
public ChungusMonolith(Settings settings) {
super(settings);
this.setDefaultState(this.stateManager.getDefaultState().with(FACING, Direction.NORTH));
}
@Override
public BlockState getPlacementState(ItemPlacementContext ctx) {
return this.getDefaultState().with(FACING, ctx.getPlayerLookDirection());
}
@Override
public BlockState rotate(BlockState state, BlockRotation rotation) {
return state.with(FACING, rotation.rotate(state.get(FACING)));
}
@Override
public BlockState mirror(BlockState state, BlockMirror mirror) {
return state.rotate(mirror.getRotation(state.get(FACING)));
}
@Override
protected void appendProperties(StateManager.Builder<Block, BlockState> builder) {
builder.add(FACING);
}
}
| 412 | 0.822666 | 1 | 0.822666 | game-dev | MEDIA | 0.981361 | game-dev | 0.854624 | 1 | 0.854624 |
emileb/OpenGames | 19,125 | opengames/src/main/jni/quake2/src/rsrc/g_cmds.c | #include "g_local.h"
#include "m_player.h"
char *ClientTeam (edict_t *ent)
{
char *p;
static char value[512];
value[0] = 0;
if (!ent->client)
return value;
strcpy(value, Info_ValueForKey (ent->client->pers.userinfo, "skin"));
p = strchr(value, '/');
if (!p)
return value;
if ((int)(dmflags->value) & DF_MODELTEAMS)
{
*p = 0;
return value;
}
// if ((int)(dmflags->value) & DF_SKINTEAMS)
return ++p;
}
qboolean OnSameTeam (edict_t *ent1, edict_t *ent2)
{
char ent1Team [512];
char ent2Team [512];
if (!((int)(dmflags->value) & (DF_MODELTEAMS | DF_SKINTEAMS)))
return false;
strcpy (ent1Team, ClientTeam (ent1));
strcpy (ent2Team, ClientTeam (ent2));
if (strcmp(ent1Team, ent2Team) == 0)
return true;
return false;
}
void SelectNextItem (edict_t *ent, int itflags)
{
gclient_t *cl;
int i, index;
gitem_t *it;
cl = ent->client;
if (cl->chase_target) {
ChaseNext(ent);
return;
}
// scan for the next valid one
for (i=1 ; i<=MAX_ITEMS ; i++)
{
index = (cl->pers.selected_item + i)%MAX_ITEMS;
if (!cl->pers.inventory[index])
continue;
it = &itemlist[index];
if (!it->use)
continue;
if (!(it->flags & itflags))
continue;
cl->pers.selected_item = index;
return;
}
cl->pers.selected_item = -1;
}
void SelectPrevItem (edict_t *ent, int itflags)
{
gclient_t *cl;
int i, index;
gitem_t *it;
cl = ent->client;
if (cl->chase_target) {
ChasePrev(ent);
return;
}
// scan for the next valid one
for (i=1 ; i<=MAX_ITEMS ; i++)
{
index = (cl->pers.selected_item + MAX_ITEMS - i)%MAX_ITEMS;
if (!cl->pers.inventory[index])
continue;
it = &itemlist[index];
if (!it->use)
continue;
if (!(it->flags & itflags))
continue;
cl->pers.selected_item = index;
return;
}
cl->pers.selected_item = -1;
}
void ValidateSelectedItem (edict_t *ent)
{
gclient_t *cl;
cl = ent->client;
if (cl->pers.inventory[cl->pers.selected_item])
return; // valid
SelectNextItem (ent, -1);
}
//=================================================================================
/*
==================
Cmd_Give_f
Give items to a client
==================
*/
void Cmd_Give_f (edict_t *ent)
{
char *name;
gitem_t *it;
int index;
int i;
qboolean give_all;
edict_t *it_ent;
if (deathmatch->value && !sv_cheats->value)
{
gi.cprintf (ent, PRINT_HIGH, "You must run the server with '+set cheats 1' to enable this command.\n");
return;
}
name = gi.args();
if (Q_stricmp(name, "all") == 0)
give_all = true;
else
give_all = false;
if (give_all || Q_stricmp(gi.argv(1), "health") == 0)
{
if (gi.argc() == 3)
ent->health = atoi(gi.argv(2));
else
ent->health = ent->max_health;
if (!give_all)
return;
}
if (give_all || Q_stricmp(name, "weapons") == 0)
{
for (i=0 ; i<game.num_items ; i++)
{
it = itemlist + i;
if (!it->pickup)
continue;
if (!(it->flags & IT_WEAPON))
continue;
ent->client->pers.inventory[i] += 1;
}
if (!give_all)
return;
}
if (give_all || Q_stricmp(name, "ammo") == 0)
{
for (i=0 ; i<game.num_items ; i++)
{
it = itemlist + i;
if (!it->pickup)
continue;
if (!(it->flags & IT_AMMO))
continue;
Add_Ammo (ent, it, 1000);
}
if (!give_all)
return;
}
if (give_all || Q_stricmp(name, "armor") == 0)
{
gitem_armor_t *info;
it = FindItem("Jacket Armor");
ent->client->pers.inventory[ITEM_INDEX(it)] = 0;
it = FindItem("Combat Armor");
ent->client->pers.inventory[ITEM_INDEX(it)] = 0;
it = FindItem("Body Armor");
info = (gitem_armor_t *)it->info;
ent->client->pers.inventory[ITEM_INDEX(it)] = info->max_count;
if (!give_all)
return;
}
if (give_all || Q_stricmp(name, "Power Shield") == 0)
{
it = FindItem("Power Shield");
it_ent = G_Spawn();
it_ent->classname = it->classname;
SpawnItem (it_ent, it);
Touch_Item (it_ent, ent, NULL, NULL);
if (it_ent->inuse)
G_FreeEdict(it_ent);
if (!give_all)
return;
}
if (give_all)
{
for (i=0 ; i<game.num_items ; i++)
{
it = itemlist + i;
if (!it->pickup)
continue;
if (it->flags & IT_NOT_GIVEABLE) // ROGUE
continue; // ROGUE
if (it->flags & (IT_ARMOR|IT_WEAPON|IT_AMMO))
continue;
ent->client->pers.inventory[i] = 1;
}
return;
}
it = FindItem (name);
if (!it)
{
name = gi.argv(1);
it = FindItem (name);
if (!it)
{
gi.cprintf (ent, PRINT_HIGH, "unknown item\n");
return;
}
}
if (!it->pickup)
{
gi.cprintf (ent, PRINT_HIGH, "non-pickup item\n");
return;
}
//ROGUE
if (it->flags & IT_NOT_GIVEABLE)
{
gi.dprintf ("item cannot be given\n");
return;
}
//ROGUE
index = ITEM_INDEX(it);
if (it->flags & IT_AMMO)
{
if (gi.argc() == 3)
ent->client->pers.inventory[index] = atoi(gi.argv(2));
else
ent->client->pers.inventory[index] += it->quantity;
}
else
{
it_ent = G_Spawn();
it_ent->classname = it->classname;
SpawnItem (it_ent, it);
// PMM - since some items don't actually spawn when you say to ..
if (!it_ent->inuse)
return;
// pmm
Touch_Item (it_ent, ent, NULL, NULL);
if (it_ent->inuse)
G_FreeEdict(it_ent);
}
}
/*
==================
Cmd_God_f
Sets client to godmode
argv(0) god
==================
*/
void Cmd_God_f (edict_t *ent)
{
char *msg;
if (deathmatch->value && !sv_cheats->value)
{
gi.cprintf (ent, PRINT_HIGH, "You must run the server with '+set cheats 1' to enable this command.\n");
return;
}
ent->flags ^= FL_GODMODE;
if (!(ent->flags & FL_GODMODE) )
msg = "godmode OFF\n";
else
msg = "godmode ON\n";
gi.cprintf (ent, PRINT_HIGH, msg);
}
/*
==================
Cmd_Notarget_f
Sets client to notarget
argv(0) notarget
==================
*/
void Cmd_Notarget_f (edict_t *ent)
{
char *msg;
if (deathmatch->value && !sv_cheats->value)
{
gi.cprintf (ent, PRINT_HIGH, "You must run the server with '+set cheats 1' to enable this command.\n");
return;
}
ent->flags ^= FL_NOTARGET;
if (!(ent->flags & FL_NOTARGET) )
msg = "notarget OFF\n";
else
msg = "notarget ON\n";
gi.cprintf (ent, PRINT_HIGH, msg);
}
/*
==================
Cmd_Noclip_f
argv(0) noclip
==================
*/
void Cmd_Noclip_f (edict_t *ent)
{
char *msg;
if (deathmatch->value && !sv_cheats->value)
{
gi.cprintf (ent, PRINT_HIGH, "You must run the server with '+set cheats 1' to enable this command.\n");
return;
}
if (ent->movetype == MOVETYPE_NOCLIP)
{
ent->movetype = MOVETYPE_WALK;
msg = "noclip OFF\n";
}
else
{
ent->movetype = MOVETYPE_NOCLIP;
msg = "noclip ON\n";
}
gi.cprintf (ent, PRINT_HIGH, msg);
}
/*
==================
Cmd_Use_f
Use an inventory item
==================
*/
void Cmd_Use_f (edict_t *ent)
{
int index;
gitem_t *it;
char *s;
s = gi.args();
it = FindItem (s);
if (!it)
{
gi.cprintf (ent, PRINT_HIGH, "unknown item: %s\n", s);
return;
}
if (!it->use)
{
gi.cprintf (ent, PRINT_HIGH, "Item is not usable.\n");
return;
}
index = ITEM_INDEX(it);
if (!ent->client->pers.inventory[index])
{
gi.cprintf (ent, PRINT_HIGH, "Out of item: %s\n", s);
return;
}
it->use (ent, it);
}
/*
==================
Cmd_Drop_f
Drop an inventory item
==================
*/
void Cmd_Drop_f (edict_t *ent)
{
int index;
gitem_t *it;
char *s;
s = gi.args();
it = FindItem (s);
if (!it)
{
gi.cprintf (ent, PRINT_HIGH, "unknown item: %s\n", s);
return;
}
if (!it->drop)
{
gi.cprintf (ent, PRINT_HIGH, "Item is not dropable.\n");
return;
}
index = ITEM_INDEX(it);
if (!ent->client->pers.inventory[index])
{
gi.cprintf (ent, PRINT_HIGH, "Out of item: %s\n", s);
return;
}
it->drop (ent, it);
}
/*
=================
Cmd_Inven_f
=================
*/
void Cmd_Inven_f (edict_t *ent)
{
int i;
gclient_t *cl;
cl = ent->client;
cl->showscores = false;
cl->showhelp = false;
if (cl->showinventory)
{
cl->showinventory = false;
return;
}
cl->showinventory = true;
gi.WriteByte (svc_inventory);
for (i=0 ; i<MAX_ITEMS ; i++)
{
gi.WriteShort (cl->pers.inventory[i]);
}
gi.unicast (ent, true);
}
/*
=================
Cmd_InvUse_f
=================
*/
void Cmd_InvUse_f (edict_t *ent)
{
gitem_t *it;
ValidateSelectedItem (ent);
if (ent->client->pers.selected_item == -1)
{
gi.cprintf (ent, PRINT_HIGH, "No item to use.\n");
return;
}
it = &itemlist[ent->client->pers.selected_item];
if (!it->use)
{
gi.cprintf (ent, PRINT_HIGH, "Item is not usable.\n");
return;
}
it->use (ent, it);
}
/*
=================
Cmd_WeapPrev_f
=================
*/
void Cmd_WeapPrev_f (edict_t *ent)
{
gclient_t *cl;
int i, index;
gitem_t *it;
int selected_weapon;
cl = ent->client;
if (!cl->pers.weapon)
return;
selected_weapon = ITEM_INDEX(cl->pers.weapon);
// scan for the next valid one
for (i=1 ; i<=MAX_ITEMS ; i++)
{
// PMM - prevent scrolling through ALL weapons
// index = (selected_weapon + i)%MAX_ITEMS;
index = (selected_weapon + MAX_ITEMS - i)%MAX_ITEMS;
if (!cl->pers.inventory[index])
continue;
it = &itemlist[index];
if (!it->use)
continue;
if (! (it->flags & IT_WEAPON) )
continue;
it->use (ent, it);
// PMM - prevent scrolling through ALL weapons
// if (cl->pers.weapon == it)
// return; // successful
if (cl->newweapon == it)
return;
}
}
/*
=================
Cmd_WeapNext_f
=================
*/
void Cmd_WeapNext_f (edict_t *ent)
{
gclient_t *cl;
int i, index;
gitem_t *it;
int selected_weapon;
cl = ent->client;
if (!cl->pers.weapon)
return;
selected_weapon = ITEM_INDEX(cl->pers.weapon);
// scan for the next valid one
for (i=1 ; i<=MAX_ITEMS ; i++)
{
// PMM - prevent scrolling through ALL weapons
// index = (selected_weapon + MAX_ITEMS - i)%MAX_ITEMS;
index = (selected_weapon + i)%MAX_ITEMS;
if (!cl->pers.inventory[index])
continue;
it = &itemlist[index];
if (!it->use)
continue;
if (! (it->flags & IT_WEAPON) )
continue;
it->use (ent, it);
// PMM - prevent scrolling through ALL weapons
// if (cl->pers.weapon == it)
// return; // successful
if (cl->newweapon == it)
return;
}
}
/*
=================
Cmd_WeapLast_f
=================
*/
void Cmd_WeapLast_f (edict_t *ent)
{
gclient_t *cl;
int index;
gitem_t *it;
cl = ent->client;
if (!cl->pers.weapon || !cl->pers.lastweapon)
return;
index = ITEM_INDEX(cl->pers.lastweapon);
if (!cl->pers.inventory[index])
return;
it = &itemlist[index];
if (!it->use)
return;
if (! (it->flags & IT_WEAPON) )
return;
it->use (ent, it);
}
/*
=================
Cmd_InvDrop_f
=================
*/
void Cmd_InvDrop_f (edict_t *ent)
{
gitem_t *it;
ValidateSelectedItem (ent);
if (ent->client->pers.selected_item == -1)
{
gi.cprintf (ent, PRINT_HIGH, "No item to drop.\n");
return;
}
it = &itemlist[ent->client->pers.selected_item];
if (!it->drop)
{
gi.cprintf (ent, PRINT_HIGH, "Item is not dropable.\n");
return;
}
it->drop (ent, it);
}
/*
=================
Cmd_Kill_f
=================
*/
void Cmd_Kill_f (edict_t *ent)
{
if((level.time - ent->client->respawn_time) < 5)
return;
ent->flags &= ~FL_GODMODE;
ent->health = 0;
meansOfDeath = MOD_SUICIDE;
//ROGUE
// make sure no trackers are still hurting us.
if(ent->client->tracker_pain_framenum)
RemoveAttackingPainDaemons (ent);
if (ent->client->owned_sphere)
{
G_FreeEdict(ent->client->owned_sphere);
ent->client->owned_sphere = NULL;
}
//ROGUE
player_die (ent, ent, ent, 100000, vec3_origin);
}
/*
=================
Cmd_PutAway_f
=================
*/
void Cmd_PutAway_f (edict_t *ent)
{
ent->client->showscores = false;
ent->client->showhelp = false;
ent->client->showinventory = false;
}
int PlayerSort (void const *a, void const *b)
{
int anum, bnum;
anum = *(int *)a;
bnum = *(int *)b;
anum = game.clients[anum].ps.stats[STAT_FRAGS];
bnum = game.clients[bnum].ps.stats[STAT_FRAGS];
if (anum < bnum)
return -1;
if (anum > bnum)
return 1;
return 0;
}
/*
=================
Cmd_Players_f
=================
*/
void Cmd_Players_f (edict_t *ent)
{
int i;
int count;
char small[64];
char large[1280];
int index[256];
count = 0;
for (i = 0 ; i < maxclients->value ; i++)
if (game.clients[i].pers.connected)
{
index[count] = i;
count++;
}
// sort by frags
qsort (index, count, sizeof(index[0]), PlayerSort);
// print information
large[0] = 0;
for (i = 0 ; i < count ; i++)
{
Com_sprintf (small, sizeof(small), "%3i %s\n",
game.clients[index[i]].ps.stats[STAT_FRAGS],
game.clients[index[i]].pers.netname);
if (strlen (small) + strlen(large) > sizeof(large) - 100 )
{ // can't print all of them in one packet
strcat (large, "...\n");
break;
}
strcat (large, small);
}
gi.cprintf (ent, PRINT_HIGH, "%s\n%i players\n", large, count);
}
/*
=================
Cmd_Wave_f
=================
*/
void Cmd_Wave_f (edict_t *ent)
{
int i;
i = atoi (gi.argv(1));
// can't wave when ducked
if (ent->client->ps.pmove.pm_flags & PMF_DUCKED)
return;
if (ent->client->anim_priority > ANIM_WAVE)
return;
ent->client->anim_priority = ANIM_WAVE;
switch (i)
{
case 0:
gi.cprintf (ent, PRINT_HIGH, "flipoff\n");
ent->s.frame = FRAME_flip01-1;
ent->client->anim_end = FRAME_flip12;
break;
case 1:
gi.cprintf (ent, PRINT_HIGH, "salute\n");
ent->s.frame = FRAME_salute01-1;
ent->client->anim_end = FRAME_salute11;
break;
case 2:
gi.cprintf (ent, PRINT_HIGH, "taunt\n");
ent->s.frame = FRAME_taunt01-1;
ent->client->anim_end = FRAME_taunt17;
break;
case 3:
gi.cprintf (ent, PRINT_HIGH, "wave\n");
ent->s.frame = FRAME_wave01-1;
ent->client->anim_end = FRAME_wave11;
break;
case 4:
default:
gi.cprintf (ent, PRINT_HIGH, "point\n");
ent->s.frame = FRAME_point01-1;
ent->client->anim_end = FRAME_point12;
break;
}
}
/*
==================
Cmd_Say_f
==================
*/
void Cmd_Say_f (edict_t *ent, qboolean team, qboolean arg0)
{
int i, j;
edict_t *other;
char *p;
char text[2048];
gclient_t *cl;
if (gi.argc () < 2 && !arg0)
return;
if (!((int)(dmflags->value) & (DF_MODELTEAMS | DF_SKINTEAMS)))
team = false;
if (team)
Com_sprintf (text, sizeof(text), "(%s): ", ent->client->pers.netname);
else
Com_sprintf (text, sizeof(text), "%s: ", ent->client->pers.netname);
if (arg0)
{
strcat (text, gi.argv(0));
strcat (text, " ");
strcat (text, gi.args());
}
else
{
p = gi.args();
if (*p == '"')
{
p++;
p[strlen(p)-1] = 0;
}
strcat(text, p);
}
// don't let text be too long for malicious reasons
if (strlen(text) > 150)
text[150] = 0;
strcat(text, "\n");
if (flood_msgs->value) {
cl = ent->client;
if (level.time < cl->flood_locktill) {
gi.cprintf(ent, PRINT_HIGH, "You can't talk for %d more seconds\n",
(int)(cl->flood_locktill - level.time));
return;
}
i = cl->flood_whenhead - flood_msgs->value + 1;
if (i < 0)
i = (sizeof(cl->flood_when)/sizeof(cl->flood_when[0])) + i;
if (cl->flood_when[i] &&
level.time - cl->flood_when[i] < flood_persecond->value) {
cl->flood_locktill = level.time + flood_waitdelay->value;
gi.cprintf(ent, PRINT_CHAT, "Flood protection: You can't talk for %d seconds.\n",
(int)flood_waitdelay->value);
return;
}
cl->flood_whenhead = (cl->flood_whenhead + 1) %
(sizeof(cl->flood_when)/sizeof(cl->flood_when[0]));
cl->flood_when[cl->flood_whenhead] = level.time;
}
if (dedicated->value)
gi.cprintf(NULL, PRINT_CHAT, "%s", text);
for (j = 1; j <= game.maxclients; j++)
{
other = &g_edicts[j];
if (!other->inuse)
continue;
if (!other->client)
continue;
if (team)
{
if (!OnSameTeam(ent, other))
continue;
}
gi.cprintf(other, PRINT_CHAT, "%s", text);
}
}
//======
//ROGUE
void Cmd_Ent_Count_f (edict_t *ent)
{
int x;
edict_t *e;
x=0;
for (e=g_edicts;e < &g_edicts[globals.num_edicts] ; e++)
{
if(e->inuse)
x++;
}
gi.dprintf("%d entites active\n", x);
}
//ROGUE
//======
void Cmd_PlayerList_f(edict_t *ent)
{
int i;
char st[80];
char text[1400];
edict_t *e2;
// connect time, ping, score, name
*text = 0;
for (i = 0, e2 = g_edicts + 1; i < maxclients->value; i++, e2++) {
if (!e2->inuse)
continue;
Com_sprintf(st, sizeof(st), "%02d:%02d %4d %3d %s%s\n",
(level.framenum - e2->client->resp.enterframe) / 600,
((level.framenum - e2->client->resp.enterframe) % 600)/10,
e2->client->ping,
e2->client->resp.score,
e2->client->pers.netname,
e2->client->resp.spectator ? " (spectator)" : "");
if (strlen(text) + strlen(st) > sizeof(text) - 50) {
sprintf(text+strlen(text), "And more...\n");
gi.cprintf(ent, PRINT_HIGH, "%s", text);
return;
}
strcat(text, st);
}
gi.cprintf(ent, PRINT_HIGH, "%s", text);
}
/*
=================
ClientCommand
=================
*/
void ClientCommand (edict_t *ent)
{
char *cmd;
if (!ent->client)
return; // not fully in game yet
cmd = gi.argv(0);
if (Q_stricmp (cmd, "players") == 0)
{
Cmd_Players_f (ent);
return;
}
if (Q_stricmp (cmd, "say") == 0)
{
Cmd_Say_f (ent, false, false);
return;
}
if (Q_stricmp (cmd, "say_team") == 0)
{
Cmd_Say_f (ent, true, false);
return;
}
if (Q_stricmp (cmd, "score") == 0)
{
Cmd_Score_f (ent);
return;
}
if (Q_stricmp (cmd, "help") == 0)
{
Cmd_Help_f (ent);
return;
}
if (level.intermissiontime)
return;
if (Q_stricmp (cmd, "use") == 0)
Cmd_Use_f (ent);
else if (Q_stricmp (cmd, "drop") == 0)
Cmd_Drop_f (ent);
else if (Q_stricmp (cmd, "give") == 0)
Cmd_Give_f (ent);
else if (Q_stricmp (cmd, "god") == 0)
Cmd_God_f (ent);
else if (Q_stricmp (cmd, "notarget") == 0)
Cmd_Notarget_f (ent);
else if (Q_stricmp (cmd, "noclip") == 0)
Cmd_Noclip_f (ent);
else if (Q_stricmp (cmd, "inven") == 0)
Cmd_Inven_f (ent);
else if (Q_stricmp (cmd, "invnext") == 0)
SelectNextItem (ent, -1);
else if (Q_stricmp (cmd, "invprev") == 0)
SelectPrevItem (ent, -1);
else if (Q_stricmp (cmd, "invnextw") == 0)
SelectNextItem (ent, IT_WEAPON);
else if (Q_stricmp (cmd, "invprevw") == 0)
SelectPrevItem (ent, IT_WEAPON);
else if (Q_stricmp (cmd, "invnextp") == 0)
SelectNextItem (ent, IT_POWERUP);
else if (Q_stricmp (cmd, "invprevp") == 0)
SelectPrevItem (ent, IT_POWERUP);
else if (Q_stricmp (cmd, "invuse") == 0)
Cmd_InvUse_f (ent);
else if (Q_stricmp (cmd, "invdrop") == 0)
Cmd_InvDrop_f (ent);
else if (Q_stricmp (cmd, "weapprev") == 0)
Cmd_WeapPrev_f (ent);
else if (Q_stricmp (cmd, "weapnext") == 0)
Cmd_WeapNext_f (ent);
else if (Q_stricmp (cmd, "weaplast") == 0)
Cmd_WeapLast_f (ent);
else if (Q_stricmp (cmd, "kill") == 0)
Cmd_Kill_f (ent);
else if (Q_stricmp (cmd, "putaway") == 0)
Cmd_PutAway_f (ent);
else if (Q_stricmp (cmd, "wave") == 0)
Cmd_Wave_f (ent);
else if (Q_stricmp(cmd, "playerlist") == 0)
Cmd_PlayerList_f(ent);
else if (Q_stricmp (cmd, "entcount") == 0) // PGM
Cmd_Ent_Count_f (ent); // PGM
else if (Q_stricmp (cmd, "disguise") == 0) // PGM
{
ent->flags |= FL_DISGUISED;
}
else // anything that doesn't match a command will be a chat
Cmd_Say_f (ent, false, true);
}
| 412 | 0.924855 | 1 | 0.924855 | game-dev | MEDIA | 0.870319 | game-dev | 0.965275 | 1 | 0.965275 |
indilo53/gtautil | 2,275 | gtautil/Program/Generic.cs |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using RageLib.Archives;
using RageLib.GTA5.Archives;
using RageLib.GTA5.Utilities;
using RageLib.Hash;
using RageLib.Resources.GTA5;
using RageLib.Resources.GTA5.PC.Drawables;
using RageLib.Resources.GTA5.PC.GameFiles;
namespace GTAUtil
{
partial class Program
{
static void HandleGenericOptions(string[] args)
{
CommandLine.Parse<GenericOptions>(args, (opts, gOpts) =>
{
int level = DLCList.Length - 1;
if(opts.DlcLevel != null)
{
level = Array.IndexOf(DLCList, opts.DlcLevel.ToLowerInvariant());
if (level == -1)
level = DLCList.Length - 1;
}
EnsureFiles(level);
// EnsureArchetypes(level);
if(opts.Mods != null)
{
Console.WriteLine("Loading mods");
var infos = Utils.Expand(opts.Mods);
int count = 0;
for(int i=0; i<infos.Length; i++)
{
var name = Path.GetFileNameWithoutExtension(infos[i].Name);
var ext = Path.GetExtension(infos[i].Name);
if (ext.Length > 0)
ext = ext.Substring(1);
var hash = Jenkins.Hash(name.ToLowerInvariant());
switch (ext)
{
case "ydr":
{
var ydr = new YdrFile();
ydr.Load(infos[i].FullName);
DrawableCache[hash] = ydr.Drawable;
count++;
break;
}
default: break;
}
}
Console.Error.WriteLine("Loaded " + count + " mods");
}
return;
});
}
}
}
| 412 | 0.548297 | 1 | 0.548297 | game-dev | MEDIA | 0.53506 | game-dev | 0.771158 | 1 | 0.771158 |
mattyx14/otxserver | 1,821 | data-otxserver/scripts/spells/monster/canopic_jar_heal.lua | local combat = Combat()
combat:setParameter(COMBAT_PARAM_EFFECT, CONST_ME_DRAWBLOOD)
combat:setParameter(COMBAT_PARAM_AGGRESSIVE, 0)
arr = {
{ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0 },
{ 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0 },
{ 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0 },
{ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0 },
{ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0 },
{ 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1 },
{ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0 },
{ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0 },
{ 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0 },
{ 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0 },
{ 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 },
}
local area = createCombatArea(arr)
combat:setArea(area)
function onTargetCreature(creature, target)
local hp = (creature:getHealth() / creature:getMaxHealth()) * 100
local min = 4000
local max = 5000
local master = target:getMaster()
if target:isPlayer() and not master or master and master:isPlayer() then
return true
end
if hp > 75 then
doTargetCombatHealth(0, target, COMBAT_HEALING, min, max, CONST_ME_NONE)
elseif hp < 75 and hp > 50 then
doTargetCombatHealth(0, target, COMBAT_HEALING, min * 0.5, max * 0.5, CONST_ME_NONE)
elseif hp < 50 and hp > 25 then
doTargetCombatHealth(0, target, COMBAT_HEALING, min * 0.25, max * 0.25, CONST_ME_NONE)
elseif hp < 25 then
doTargetCombatHealth(0, target, COMBAT_HEALING, min * 0.10, max * 0.10, CONST_ME_NONE)
end
return true
end
combat:setCallback(CALLBACK_PARAM_TARGETCREATURE, "onTargetCreature")
local spell = Spell("instant")
function spell.onCastSpell(creature, var)
return combat:execute(creature, var)
end
spell:name("canopic jar heal")
spell:words("###390")
spell:blockWalls(true)
spell:needLearn(true)
spell:register()
| 412 | 0.600896 | 1 | 0.600896 | game-dev | MEDIA | 0.690562 | game-dev | 0.619731 | 1 | 0.619731 |
worleydl/uwp-dep | 11,044 | x64/include/SDL2/SDL_keyboard.h | /*
Simple DirectMedia Layer
Copyright (C) 1997-2023 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/**
* \file SDL_keyboard.h
*
* Include file for SDL keyboard event handling
*/
#ifndef SDL_keyboard_h_
#define SDL_keyboard_h_
#include "SDL_stdinc.h"
#include "SDL_error.h"
#include "SDL_keycode.h"
#include "SDL_video.h"
#include "begin_code.h"
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
extern "C" {
#endif
/**
* \brief The SDL keysym structure, used in key events.
*
* \note If you are looking for translated character input, see the ::SDL_TEXTINPUT event.
*/
typedef struct SDL_Keysym
{
SDL_Scancode scancode; /**< SDL physical key code - see ::SDL_Scancode for details */
SDL_Keycode sym; /**< SDL virtual key code - see ::SDL_Keycode for details */
Uint16 mod; /**< current key modifiers */
Uint32 unused;
} SDL_Keysym;
/* Function prototypes */
/**
* Query the window which currently has keyboard focus.
*
* \returns the window with keyboard focus.
*
* \since This function is available since SDL 2.0.0.
*/
extern DECLSPEC SDL_Window * SDLCALL SDL_GetKeyboardFocus(void);
/**
* Get a snapshot of the current state of the keyboard.
*
* The pointer returned is a pointer to an internal SDL array. It will be
* valid for the whole lifetime of the application and should not be freed by
* the caller.
*
* A array element with a value of 1 means that the key is pressed and a value
* of 0 means that it is not. Indexes into this array are obtained by using
* SDL_Scancode values.
*
* Use SDL_PumpEvents() to update the state array.
*
* This function gives you the current state after all events have been
* processed, so if a key or button has been pressed and released before you
* process events, then the pressed state will never show up in the
* SDL_GetKeyboardState() calls.
*
* Note: This function doesn't take into account whether shift has been
* pressed or not.
*
* \param numkeys if non-NULL, receives the length of the returned array
* \returns a pointer to an array of key states.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_PumpEvents
* \sa SDL_ResetKeyboard
*/
extern DECLSPEC const Uint8 *SDLCALL SDL_GetKeyboardState(int *numkeys);
/**
* Clear the state of the keyboard
*
* This function will generate key up events for all pressed keys.
*
* \since This function is available since SDL 2.24.0.
*
* \sa SDL_GetKeyboardState
*/
extern DECLSPEC void SDLCALL SDL_ResetKeyboard(void);
/**
* Get the current key modifier state for the keyboard.
*
* \returns an OR'd combination of the modifier keys for the keyboard. See
* SDL_Keymod for details.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_GetKeyboardState
* \sa SDL_SetModState
*/
extern DECLSPEC SDL_Keymod SDLCALL SDL_GetModState(void);
/**
* Set the current key modifier state for the keyboard.
*
* The inverse of SDL_GetModState(), SDL_SetModState() allows you to impose
* modifier key states on your application. Simply pass your desired modifier
* states into `modstate`. This value may be a bitwise, OR'd combination of
* SDL_Keymod values.
*
* This does not change the keyboard state, only the key modifier flags that
* SDL reports.
*
* \param modstate the desired SDL_Keymod for the keyboard
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_GetModState
*/
extern DECLSPEC void SDLCALL SDL_SetModState(SDL_Keymod modstate);
/**
* Get the key code corresponding to the given scancode according to the
* current keyboard layout.
*
* See SDL_Keycode for details.
*
* \param scancode the desired SDL_Scancode to query
* \returns the SDL_Keycode that corresponds to the given SDL_Scancode.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_GetKeyName
* \sa SDL_GetScancodeFromKey
*/
extern DECLSPEC SDL_Keycode SDLCALL SDL_GetKeyFromScancode(SDL_Scancode scancode);
/**
* Get the scancode corresponding to the given key code according to the
* current keyboard layout.
*
* See SDL_Scancode for details.
*
* \param key the desired SDL_Keycode to query
* \returns the SDL_Scancode that corresponds to the given SDL_Keycode.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_GetKeyFromScancode
* \sa SDL_GetScancodeName
*/
extern DECLSPEC SDL_Scancode SDLCALL SDL_GetScancodeFromKey(SDL_Keycode key);
/**
* Get a human-readable name for a scancode.
*
* See SDL_Scancode for details.
*
* **Warning**: The returned name is by design not stable across platforms,
* e.g. the name for `SDL_SCANCODE_LGUI` is "Left GUI" under Linux but "Left
* Windows" under Microsoft Windows, and some scancodes like
* `SDL_SCANCODE_NONUSBACKSLASH` don't have any name at all. There are even
* scancodes that share names, e.g. `SDL_SCANCODE_RETURN` and
* `SDL_SCANCODE_RETURN2` (both called "Return"). This function is therefore
* unsuitable for creating a stable cross-platform two-way mapping between
* strings and scancodes.
*
* \param scancode the desired SDL_Scancode to query
* \returns a pointer to the name for the scancode. If the scancode doesn't
* have a name this function returns an empty string ("").
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_GetScancodeFromKey
* \sa SDL_GetScancodeFromName
*/
extern DECLSPEC const char *SDLCALL SDL_GetScancodeName(SDL_Scancode scancode);
/**
* Get a scancode from a human-readable name.
*
* \param name the human-readable scancode name
* \returns the SDL_Scancode, or `SDL_SCANCODE_UNKNOWN` if the name wasn't
* recognized; call SDL_GetError() for more information.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_GetKeyFromName
* \sa SDL_GetScancodeFromKey
* \sa SDL_GetScancodeName
*/
extern DECLSPEC SDL_Scancode SDLCALL SDL_GetScancodeFromName(const char *name);
/**
* Get a human-readable name for a key.
*
* See SDL_Scancode and SDL_Keycode for details.
*
* \param key the desired SDL_Keycode to query
* \returns a pointer to a UTF-8 string that stays valid at least until the
* next call to this function. If you need it around any longer, you
* must copy it. If the key doesn't have a name, this function
* returns an empty string ("").
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_GetKeyFromName
* \sa SDL_GetKeyFromScancode
* \sa SDL_GetScancodeFromKey
*/
extern DECLSPEC const char *SDLCALL SDL_GetKeyName(SDL_Keycode key);
/**
* Get a key code from a human-readable name.
*
* \param name the human-readable key name
* \returns key code, or `SDLK_UNKNOWN` if the name wasn't recognized; call
* SDL_GetError() for more information.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_GetKeyFromScancode
* \sa SDL_GetKeyName
* \sa SDL_GetScancodeFromName
*/
extern DECLSPEC SDL_Keycode SDLCALL SDL_GetKeyFromName(const char *name);
/**
* Start accepting Unicode text input events.
*
* This function will start accepting Unicode text input events in the focused
* SDL window, and start emitting SDL_TextInputEvent (SDL_TEXTINPUT) and
* SDL_TextEditingEvent (SDL_TEXTEDITING) events. Please use this function in
* pair with SDL_StopTextInput().
*
* On some platforms using this function activates the screen keyboard.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_SetTextInputRect
* \sa SDL_StopTextInput
*/
extern DECLSPEC void SDLCALL SDL_StartTextInput(void);
/**
* Check whether or not Unicode text input events are enabled.
*
* \returns SDL_TRUE if text input events are enabled else SDL_FALSE.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_StartTextInput
*/
extern DECLSPEC SDL_bool SDLCALL SDL_IsTextInputActive(void);
/**
* Stop receiving any text input events.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_StartTextInput
*/
extern DECLSPEC void SDLCALL SDL_StopTextInput(void);
/**
* Dismiss the composition window/IME without disabling the subsystem.
*
* \since This function is available since SDL 2.0.22.
*
* \sa SDL_StartTextInput
* \sa SDL_StopTextInput
*/
extern DECLSPEC void SDLCALL SDL_ClearComposition(void);
/**
* Returns if an IME Composite or Candidate window is currently shown.
*
* \since This function is available since SDL 2.0.22.
*/
extern DECLSPEC SDL_bool SDLCALL SDL_IsTextInputShown(void);
/**
* Set the rectangle used to type Unicode text inputs.
*
* To start text input in a given location, this function is intended to be
* called before SDL_StartTextInput, although some platforms support moving
* the rectangle even while text input (and a composition) is active.
*
* Note: If you want to use the system native IME window, try setting hint
* **SDL_HINT_IME_SHOW_UI** to **1**, otherwise this function won't give you
* any feedback.
*
* \param rect the SDL_Rect structure representing the rectangle to receive
* text (ignored if NULL)
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_StartTextInput
*/
extern DECLSPEC void SDLCALL SDL_SetTextInputRect(const SDL_Rect *rect);
/**
* Check whether the platform has screen keyboard support.
*
* \returns SDL_TRUE if the platform has some screen keyboard support or
* SDL_FALSE if not.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_StartTextInput
* \sa SDL_IsScreenKeyboardShown
*/
extern DECLSPEC SDL_bool SDLCALL SDL_HasScreenKeyboardSupport(void);
/**
* Check whether the screen keyboard is shown for given window.
*
* \param window the window for which screen keyboard should be queried
* \returns SDL_TRUE if screen keyboard is shown or SDL_FALSE if not.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_HasScreenKeyboardSupport
*/
extern DECLSPEC SDL_bool SDLCALL SDL_IsScreenKeyboardShown(SDL_Window *window);
/* Ends C function definitions when using C++ */
#ifdef __cplusplus
}
#endif
#include "close_code.h"
#endif /* SDL_keyboard_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| 412 | 0.849919 | 1 | 0.849919 | game-dev | MEDIA | 0.855838 | game-dev | 0.51882 | 1 | 0.51882 |
FTL13/FTL13 | 3,562 | code/modules/mob/living/simple_animal/hostile/mining_mobs/gutlunch.dm | //Gutlunches, passive mods that devour blood and gibs
/mob/living/simple_animal/hostile/asteroid/gutlunch
name = "gutlunch"
desc = "A scavenger that eats raw meat, often found alongside ash walkers. Produces a thick, nutritious milk."
icon = 'icons/mob/lavaland/lavaland_monsters.dmi'
icon_state = "gutlunch"
icon_living = "gutlunch"
icon_dead = "gutlunch"
speak_emote = list("warbles", "quavers")
emote_hear = list("trills.")
emote_see = list("sniffs.", "burps.")
weather_immunities = list("lava","ash")
faction = list("mining", "ashwalker")
density = FALSE
speak_chance = 1
turns_per_move = 8
obj_damage = 0
environment_smash = ENVIRONMENT_SMASH_NONE
move_to_delay = 15
response_help = "pets"
response_disarm = "gently pushes aside"
response_harm = "squishes"
friendly = "pinches"
a_intent = INTENT_HELP
ventcrawler = VENTCRAWLER_ALWAYS
gold_core_spawnable = 2
stat_attack = UNCONSCIOUS
gender = NEUTER
stop_automated_movement = FALSE
stop_automated_movement_when_pulled = TRUE
stat_exclusive = TRUE
robust_searching = TRUE
search_objects = TRUE
del_on_death = TRUE
loot = list(/obj/effect/decal/cleanable/blood/gibs)
deathmessage = "is pulped into bugmash."
animal_species = /mob/living/simple_animal/hostile/asteroid/gutlunch
childtype = list(/mob/living/simple_animal/hostile/asteroid/gutlunch/gubbuck = 45, /mob/living/simple_animal/hostile/asteroid/gutlunch/guthen = 55)
wanted_objects = list(/obj/effect/decal/cleanable/xenoblood/xgibs, /obj/effect/decal/cleanable/blood/gibs/)
var/obj/item/udder/gutlunch/udder = null
/mob/living/simple_animal/hostile/asteroid/gutlunch/Initialize()
udder = new()
. = ..()
/mob/living/simple_animal/hostile/asteroid/gutlunch/Destroy()
QDEL_NULL(udder)
return ..()
/mob/living/simple_animal/hostile/asteroid/gutlunch/regenerate_icons()
cut_overlays()
if(udder.reagents.total_volume == udder.reagents.maximum_volume)
add_overlay("gl_full")
..()
/mob/living/simple_animal/hostile/asteroid/gutlunch/attackby(obj/item/O, mob/user, params)
if(stat == CONSCIOUS && istype(O, /obj/item/weapon/reagent_containers/glass))
udder.milkAnimal(O, user)
regenerate_icons()
else
..()
/mob/living/simple_animal/hostile/asteroid/gutlunch/AttackingTarget()
if(is_type_in_typecache(target,wanted_objects)) //we eats
udder.generateMilk()
regenerate_icons()
visible_message("<span class='notice'>[src] slurps up [target].</span>")
qdel(target)
return ..()
//Male gutlunch. They're smaller and more colorful!
/mob/living/simple_animal/hostile/asteroid/gutlunch/gubbuck
name = "gubbuck"
gender = MALE
/mob/living/simple_animal/hostile/asteroid/gutlunch/gubbuck/Initialize()
..()
add_atom_colour(pick("#E39FBB", "#D97D64", "#CF8C4A"), FIXED_COLOUR_PRIORITY)
resize = 0.85
update_transform()
//Lady gutlunch. They make the babby.
/mob/living/simple_animal/hostile/asteroid/gutlunch/guthen
name = "guthen"
gender = FEMALE
/mob/living/simple_animal/hostile/asteroid/gutlunch/guthen/Life()
..()
if(udder.reagents.total_volume == udder.reagents.maximum_volume) //Only breed when we're full.
make_babies()
/mob/living/simple_animal/hostile/asteroid/gutlunch/guthen/make_babies()
. = ..()
if(.)
udder.reagents.clear_reagents()
regenerate_icons()
//Gutlunch udder
/obj/item/udder/gutlunch
name = "nutrient sac"
/obj/item/udder/gutlunch/New()
reagents = new(50)
reagents.my_atom = src
/obj/item/udder/gutlunch/generateMilk()
if(prob(60))
reagents.add_reagent("cream", rand(2, 5))
if(prob(45))
reagents.add_reagent("salglu_solution", rand(2,5))
| 412 | 0.890544 | 1 | 0.890544 | game-dev | MEDIA | 0.985965 | game-dev | 0.822901 | 1 | 0.822901 |
HbmMods/Hbm-s-Nuclear-Tech-GIT | 6,858 | src/main/java/com/hbm/wiaj/cannery/CanneryCentrifuge.java | package com.hbm.wiaj.cannery;
import org.lwjgl.opengl.GL11;
import com.hbm.blocks.ModBlocks;
import com.hbm.inventory.fluid.Fluids;
import com.hbm.items.ModItems;
import com.hbm.main.ResourceManager;
import com.hbm.tileentity.network.TileEntityPipeBaseNT;
import com.hbm.util.i18n.I18nUtil;
import com.hbm.wiaj.JarScene;
import com.hbm.wiaj.JarScript;
import com.hbm.wiaj.WorldInAJar;
import com.hbm.wiaj.actions.ActionCreateActor;
import com.hbm.wiaj.actions.ActionRemoveActor;
import com.hbm.wiaj.actions.ActionSetBlock;
import com.hbm.wiaj.actions.ActionSetTile;
import com.hbm.wiaj.actions.ActionSetZoom;
import com.hbm.wiaj.actions.ActionWait;
import com.hbm.wiaj.actors.ActorFancyPanel;
import com.hbm.wiaj.actors.ActorTileEntity;
import com.hbm.wiaj.actors.ITileActorRenderer;
import com.hbm.wiaj.actors.ActorFancyPanel.Orientation;
import net.minecraft.client.Minecraft;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
public class CanneryCentrifuge extends CanneryBase {
@Override
public ItemStack getIcon() {
return new ItemStack(ModBlocks.machine_gascent);
}
@Override
public String getName() {
return "cannery.centrifuge";
}
public JarScript createScript() {
WorldInAJar world = new WorldInAJar(9, 5, 5);
JarScript script = new JarScript(world);
JarScene scene0 = new JarScene(script);
scene0.add(new ActionSetZoom(2, 0));
for(int x = world.sizeX - 1; x >= 0 ; x--) {
for(int z = 0; z < world.sizeZ; z++) {
scene0.add(new ActionSetBlock(x, 0, z, Blocks.brick_block));
}
if(x == 7) {
scene0.add(new ActionSetTile(7, 1, 2, new Dummies.JarDummyConnector()));
scene0.add(new ActionSetBlock(7, 1, 2, ModBlocks.barrel_tcalloy));
}
if(x == 6) {
TileEntityPipeBaseNT duct = new TileEntityPipeBaseNT();
duct.setType(Fluids.UF6);
scene0.add(new ActionSetTile(6, 1, 2, duct));
scene0.add(new ActionSetBlock(6, 1, 2, ModBlocks.fluid_duct_neo, 0));
}
if(x == 5) {
scene0.add(new ActionSetTile(5, 1, 2, new Dummies.JarDummyConnector()));
NBTTagCompound cent = new NBTTagCompound();
cent.setDouble("x", 5);
cent.setDouble("y", 1);
cent.setDouble("z", 2);
cent.setInteger("rotation", 2);
scene0.add(new ActionCreateActor(0, new ActorTileEntity(new ActorGasCent(), cent)));
}
scene0.add(new ActionWait(2));
}
scene0.add(new ActionCreateActor(1, new ActorFancyPanel(Minecraft.getMinecraft().fontRenderer, -15, -50, new Object[][] {{I18nUtil.resolveKey("cannery.centrifuge.0")}}, 200)
.setColors(colorCopper).setOrientation(Orientation.BOTTOM)));
scene0.add(new ActionWait(60));
scene0.add(new ActionRemoveActor(1));
JarScene scene1 = new JarScene(script);
scene1.add(new ActionCreateActor(1, new ActorFancyPanel(Minecraft.getMinecraft().fontRenderer, -15, 10, new Object[][] {{I18nUtil.resolveKey("cannery.centrifuge.1")}}, 200)
.setColors(colorCopper).setOrientation(Orientation.CENTER)));
scene1.add(new ActionWait(60));
scene1.add(new ActionRemoveActor(1));
scene1.add(new ActionSetZoom(4, 20));
scene1.add(new ActionCreateActor(1, new ActorFancyPanel(Minecraft.getMinecraft().fontRenderer, 0, 40, new Object[][] {{I18nUtil.resolveKey("cannery.centrifuge.2")}}, 150)
.setColors(colorCopper).setOrientation(Orientation.LEFT)));
scene1.add(new ActionWait(60));
scene1.add(new ActionRemoveActor(1));
scene1.add(new ActionSetZoom(-2, 20));
scene1.add(new ActionWait(20));
NBTTagCompound c2 = new NBTTagCompound(); c2.setDouble("x", 4); c2.setDouble("y", 1); c2.setDouble("z", 2); c2.setInteger("rotation", 2);
scene1.add(new ActionCreateActor(1, new ActorTileEntity(new ActorGasCent(), c2)));
scene1.add(new ActionWait(10));
scene1.add(new ActionCreateActor(2, new ActorFancyPanel(Minecraft.getMinecraft().fontRenderer, 0, 0, new Object[][] {{I18nUtil.resolveKey("cannery.centrifuge.3")}}, 200)
.setColors(colorCopper).setOrientation(Orientation.CENTER)));
scene1.add(new ActionWait(100));
scene1.add(new ActionRemoveActor(2));
scene1.add(new ActionSetZoom(-2, 20));
scene1.add(new ActionCreateActor(2, new ActorFancyPanel(Minecraft.getMinecraft().fontRenderer, 0, 0, new Object[][] {{I18nUtil.resolveKey("cannery.centrifuge.4")}}, 200)
.setColors(colorCopper).setOrientation(Orientation.CENTER)));
scene1.add(new ActionWait(60));
scene1.add(new ActionRemoveActor(2));
NBTTagCompound c3 = new NBTTagCompound(); c3.setDouble("x", 3); c3.setDouble("y", 1); c3.setDouble("z", 2); c3.setInteger("rotation", 2);
scene1.add(new ActionCreateActor(2, new ActorTileEntity(new ActorGasCent(), c3)));
scene1.add(new ActionWait(10));
NBTTagCompound c4 = new NBTTagCompound(); c4.setDouble("x", 2); c4.setDouble("y", 1); c4.setDouble("z", 2); c4.setInteger("rotation", 2);
scene1.add(new ActionCreateActor(3, new ActorTileEntity(new ActorGasCent(), c4)));
scene1.add(new ActionWait(10));
scene1.add(new ActionCreateActor(4, new ActorFancyPanel(Minecraft.getMinecraft().fontRenderer, 0, 0, new Object[][] {{I18nUtil.resolveKey("cannery.centrifuge.5")}}, 200)
.setColors(colorCopper).setOrientation(Orientation.CENTER)));
scene1.add(new ActionWait(60));
scene1.add(new ActionRemoveActor(4));
scene1.add(new ActionCreateActor(4, new ActorFancyPanel(Minecraft.getMinecraft().fontRenderer, 28, -30, new Object[][] {{new ItemStack(ModItems.upgrade_gc_speed)}}, 0)
.setColors(colorCopper).setOrientation(Orientation.BOTTOM)));
scene1.add(new ActionCreateActor(5, new ActorFancyPanel(Minecraft.getMinecraft().fontRenderer, 45, 35, new Object[][] {{" = ", new ItemStack(ModItems.nugget_u238, 11), new ItemStack(ModItems.nugget_u235)}}, 0)
.setColors(colorCopper).setOrientation(Orientation.LEFT)));
script.addScene(scene0).addScene(scene1);
return script;
}
public static class ActorGasCent implements ITileActorRenderer {
@Override
public void renderActor(WorldInAJar world, int ticks, float interp, NBTTagCompound data) {
double x = data.getDouble("x");
double y = data.getDouble("y");
double z = data.getDouble("z");
int rotation = data.getInteger("rotation");
GL11.glTranslated(x + 0.5D, y, z + 0.5D);
GL11.glEnable(GL11.GL_LIGHTING);
GL11.glShadeModel(GL11.GL_SMOOTH);
switch(rotation) {
case 3: GL11.glRotatef(0, 0F, 1F, 0F); break;
case 5: GL11.glRotatef(90, 0F, 1F, 0F); break;
case 2: GL11.glRotatef(180, 0F, 1F, 0F); break;
case 4: GL11.glRotatef(270, 0F, 1F, 0F); break;
}
ITileActorRenderer.bindTexture(ResourceManager.gascent_tex);
ResourceManager.gascent.renderPart("Centrifuge");
ResourceManager.gascent.renderPart("Flag");
GL11.glShadeModel(GL11.GL_FLAT);
}
@Override
public void updateActor(int ticks, NBTTagCompound data) { }
}
}
| 412 | 0.857895 | 1 | 0.857895 | game-dev | MEDIA | 0.782338 | game-dev,graphics-rendering | 0.963239 | 1 | 0.963239 |
lunar-sway/minestuck | 2,047 | src/main/java/com/mraof/minestuck/jei/GristIngredientHelper.java | package com.mraof.minestuck.jei;
import com.mraof.minestuck.api.alchemy.GristAmount;
import com.mraof.minestuck.api.alchemy.GristType;
import com.mraof.minestuck.api.alchemy.GristTypes;
import mezz.jei.api.ingredients.IIngredientHelper;
import mezz.jei.api.ingredients.IIngredientType;
import mezz.jei.api.ingredients.subtypes.UidContext;
import net.minecraft.MethodsReturnNonnullByDefault;
import net.minecraft.resources.ResourceLocation;
import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@ParametersAreNonnullByDefault
@MethodsReturnNonnullByDefault
public class GristIngredientHelper implements IIngredientHelper<GristAmount>
{
public static List<GristAmount> createList()
{
List<GristAmount> list = new ArrayList<>();
for(GristType gristType : GristTypes.REGISTRY)
list.add(gristType.amount(1));
return list;
}
@Override
public IIngredientType<GristAmount> getIngredientType()
{
return MinestuckJeiPlugin.GRIST;
}
@Override
public String getDisplayName(GristAmount ingredient)
{
return ingredient.type().getDisplayName().getString();
}
@Override
public String getUniqueId(GristAmount ingredient, UidContext context)
{
return "grist:" + getResourceLocation(ingredient);
}
@Override
public Iterable<Integer> getColors(GristAmount ingredient)
{
return Collections.emptyList(); //Not dealing with this right now
}
@Override
public ResourceLocation getResourceLocation(GristAmount ingredient)
{
return ingredient.type().getIdOrThrow();
}
@Override
public GristAmount copyIngredient(GristAmount ingredient)
{
return new GristAmount(ingredient.type(), ingredient.amount());
}
@Override
public String getErrorInfo(@Nullable GristAmount ingredient)
{
if(ingredient == null)
return "grist:null";
else if(ingredient.type() == null)
return "grist:null:"+ingredient.amount();
else return "grist:"+getResourceLocation(ingredient)+":"+ingredient.amount();
}
} | 412 | 0.856406 | 1 | 0.856406 | game-dev | MEDIA | 0.816551 | game-dev | 0.906533 | 1 | 0.906533 |
passiony/xlua-framework-unity2018 | 2,567 | Assets/Editor/PackageBuild/CheckAssetBundles.cs | using System;
using UnityEngine;
using System.Collections;
using AssetBundles;
using UnityEditor;
/// <summary>
/// added by wsh @ 2018.01.03
/// 功能:打包前的AB检测工作
/// </summary>
public static class CheckAssetBundles
{
public static void SwitchChannel(string channelName)
{
var channelFolderPath = AssetBundleUtility.PackagePathToAssetsPath(AssetBundleConfig.ChannelFolderName);
var guids = AssetDatabase.FindAssets("t:textAsset", new string[] { channelFolderPath });
foreach (var guid in guids)
{
var path = AssetDatabase.GUIDToAssetPath(guid);
GameUtility.SafeWriteAllText(path, channelName);
}
AssetDatabase.Refresh();
}
public static void ClearAllAssetBundles()
{
var assebundleNames = AssetDatabase.GetAllAssetBundleNames();
var length = assebundleNames.Length;
var count = 0;
foreach (var assetbundleName in assebundleNames)
{
count++;
EditorUtility.DisplayProgressBar("Remove assetbundle name :", assetbundleName, (float)count / length);
AssetDatabase.RemoveAssetBundleName(assetbundleName, true);
}
AssetDatabase.Refresh();
EditorUtility.ClearProgressBar();
assebundleNames = AssetDatabase.GetAllAssetBundleNames();
if (assebundleNames.Length != 0)
{
Logger.LogError("Something wrong!!!");
}
}
public static void RunAllCheckers(bool checkChannel)
{
try
{
var guids = AssetDatabase.FindAssets("t:AssetBundleDispatcherConfig",
new string[] {AssetBundleInspectorUtils.DatabaseRoot});
var length = guids.Length;
var count = 0;
foreach (var guid in guids)
{
count++;
var assetPath = AssetDatabase.GUIDToAssetPath(guid);
var config = AssetDatabase.LoadAssetAtPath<AssetBundleDispatcherConfig>(assetPath);
config.Load();
EditorUtility.DisplayProgressBar("Run checker :", config.PackagePath, (float) count / length);
AssetBundleDispatcher.Run(config, checkChannel);
}
}
catch (Exception e)
{
Debug.LogError(e);
}
finally
{
AssetDatabase.Refresh();
EditorUtility.ClearProgressBar();
}
}
public static void Run(bool checkChannel)
{
ClearAllAssetBundles();
RunAllCheckers(checkChannel);
}
}
| 412 | 0.899586 | 1 | 0.899586 | game-dev | MEDIA | 0.915745 | game-dev | 0.978753 | 1 | 0.978753 |
LoganSMiller/AI-Refactored-Client | 4,012 | Pools/TempIntArrayPool.cs | // <auto-generated>
// AI-Refactored: TempIntArrayPool.cs (Ultimate Arbitration, Max-Realism, Zero-Alloc Edition – June 2025)
// Bulletproof, reusable int[] pooling for ultra-high-performance AI/world logic. Thread-safe, teardown/reload safe, diagnostics-ready.
// MIT License.
// </auto-generated>
namespace AIRefactored.Pools
{
using System;
using System.Collections.Generic;
/// <summary>
/// Pool for temporary <see cref="int"/> array reuse in AIRefactored and math-heavy logic paths.
/// Bulletproof: Thread-safe, teardown/reload safe, infinite reload, and diagnostics-ready.
/// </summary>
public static class TempIntArrayPool
{
private static readonly Dictionary<int, Stack<int[]>> PoolBySize = new Dictionary<int, Stack<int[]>>(32);
private static readonly object SyncRoot = new object();
private static int _totalRented, _totalReturned, _totalPooled;
static TempIntArrayPool()
{
try
{
AppDomain.CurrentDomain.DomainUnload += (_, __) => ClearAll();
}
catch { }
}
/// <summary>
/// Rents a pooled int array of at least the specified size (never null, always min length 1).
/// </summary>
public static int[] Rent(int size)
{
if (size <= 0)
size = 1;
lock (SyncRoot)
{
if (PoolBySize.TryGetValue(size, out var stack) && stack.Count > 0)
{
_totalRented++;
return stack.Pop();
}
}
_totalRented++;
return new int[size];
}
/// <summary>
/// Returns an int array to the pool (null and zero-length ignored).
/// </summary>
public static void Return(int[] array)
{
if (array == null || array.Length == 0)
return;
lock (SyncRoot)
{
if (!PoolBySize.TryGetValue(array.Length, out var stack))
{
stack = new Stack<int[]>(8);
PoolBySize[array.Length] = stack;
}
stack.Push(array);
_totalReturned++;
_totalPooled = stack.Count;
}
}
/// <summary>
/// Prewarms the pool with the specified number of int arrays of a given size.
/// </summary>
public static void Prewarm(int size, int count)
{
if (size <= 0 || count <= 0)
return;
lock (SyncRoot)
{
if (!PoolBySize.TryGetValue(size, out var stack))
{
stack = new Stack<int[]>(count);
PoolBySize[size] = stack;
}
for (int i = 0; i < count; i++)
stack.Push(new int[size]);
_totalPooled = stack.Count;
}
}
/// <summary>
/// Clears all pooled int arrays and resets pool state (teardown/reload safe).
/// </summary>
public static void ClearAll()
{
lock (SyncRoot)
{
foreach (var stack in PoolBySize.Values)
stack.Clear();
PoolBySize.Clear();
_totalPooled = 0;
_totalRented = 0;
_totalReturned = 0;
}
}
/// <summary>
/// Returns pooling stats for diagnostics/monitoring.
/// </summary>
public static (int arraySizes, int totalPooled, int totalRented, int totalReturned) GetStats()
{
lock (SyncRoot)
{
int pooled = 0;
foreach (var stack in PoolBySize.Values)
pooled += stack.Count;
return (PoolBySize.Count, pooled, _totalRented, _totalReturned);
}
}
}
}
| 412 | 0.889464 | 1 | 0.889464 | game-dev | MEDIA | 0.579784 | game-dev | 0.953456 | 1 | 0.953456 |
Aidymouse/Hexfriend | 1,434 | src/types/tilesets.ts | import { type Icon } from "./icon";
import type { HexOrientation } from "./terrain";
// Tiles get loaded by the loader. The symbol texture gets loaded under the id
export type Tile = {
display: string;
bgColor: number; // Some tiles won't *really* need a bg color, if they're all icon cos they're images, but, whatever
id: string; // Local to the tileset
symbol: Icon | null; // Picture to draw on the hex. This also implicitly sets the tile type as dynamic or bydimension
tileset_id: string; // Used to identify which tile to select when the tile is clicked on
preview_flatTop: string; // Preview for the tile panel
preview_pointyTop: string;
}
// export type TileSymbol = {
// color: number;
// texWidth: number;
// texHeight: number;
// pHex: number;
// base64: string;
// preview: string;
// rotation?: number; // Added in format v3
// }
// enum TilesetType {
// dynamic="dynamic",
// images="images",
// }
export type Tileset = {
name: string;
id: string;
author: string;
version: number;
collapsed: boolean; // This needs to go in a list of collapsed IDs in the save data somewhere, not in the tileset itself !
tiles: Tile[];
format_version: number; // Internal ID of tileset format.
supported_orientations: HexOrientation.FLATTOP | HexOrientation.POINTYTOP | 'both'
//tileset_type: TilesetType
}
export const LATEST_TILESET_FORMAT_VERSION = 4
export const LATEST_DEFAULT_TILESET_VERSION = 8
| 412 | 0.577867 | 1 | 0.577867 | game-dev | MEDIA | 0.505587 | game-dev | 0.5817 | 1 | 0.5817 |
ixray-team/ixray-1.6-stcop | 2,475 | src/xrGame/ai/monsters/states/monster_state_steal_inline.h | #pragma once
#define TEMPLATE_SPECIALIZATION template <\
typename _Object\
>
#define CStateMonsterStealAbstract CStateMonsterSteal<_Object>
#define STEAL_MIN_DISTANCE 4.f
#define STEAL_MAX_DISTANCE 15.f
#define STEAL_MAX_PATH_ANGLE PI_DIV_6
TEMPLATE_SPECIALIZATION
CStateMonsterStealAbstract::CStateMonsterSteal(_Object *obj) : inherited(obj)
{
}
TEMPLATE_SPECIALIZATION
void CStateMonsterStealAbstract::initialize()
{
inherited::initialize ();
this->object->path().prepare_builder ();
}
TEMPLATE_SPECIALIZATION
void CStateMonsterStealAbstract::execute()
{
this->object->set_action (ACT_STEAL);
this->object->anim().accel_activate (eAT_Calm);
this->object->anim().accel_set_braking (false);
this->object->path().set_target_point (this->object->EnemyMan.get_enemy_position(), this->object->EnemyMan.get_enemy_vertex());
this->object->path().set_generic_parameters ();
this->object->set_state_sound (MonsterSound::eMonsterSoundSteal);
}
TEMPLATE_SPECIALIZATION
bool CStateMonsterStealAbstract::check_completion()
{
return (!check_conditions());
}
TEMPLATE_SPECIALIZATION
bool CStateMonsterStealAbstract::check_start_conditions()
{
return (check_conditions());
}
TEMPLATE_SPECIALIZATION
bool CStateMonsterStealAbstract::check_conditions()
{
// if i see enemy
if (!this->object->EnemyMan.see_enemy_now()) return false;
// This is the only enemy
if (this->object->EnemyMan.get_enemies_count() > 1) return false;
// There is extended info about enemy?
if (!this->object->EnemyMan.get_flags().is(FLAG_ENEMY_STATS_NOT_READY)) {
// Enemy is not moving fast
if (this->object->EnemyMan.get_flags().is(FLAG_ENEMY_GO_FARTHER_FAST)) return false;
// Enemy doesn't know about me
if (!this->object->EnemyMan.get_flags().is(FLAG_ENEMY_DOESNT_KNOW_ABOUT_ME)) return false;
}
// Don't hear dangerous sounds
if (this->object->hear_dangerous_sound) return false;
// Don't get hitted
if (this->object->HitMemory.is_hit()) return false;
// Path with minimal deviation
//if (this->object->control().path_builder().detail().time_path_built() >= time_state_started) {
// if (this->object->path().get_path_angle() > STEAL_MAX_PATH_ANGLE) return false;
//}
// check distance to enemy
float dist = this->object->MeleeChecker.distance_to_enemy(this->object->EnemyMan.get_enemy());
if (dist < STEAL_MIN_DISTANCE) return false;
else if (dist > STEAL_MAX_DISTANCE) return false;
return true;
}
| 412 | 0.903415 | 1 | 0.903415 | game-dev | MEDIA | 0.931004 | game-dev | 0.7612 | 1 | 0.7612 |
FFXIV-CombatReborn/RotationSolverReborn | 1,529 | RotationSolver.Basic/Data/Countdown.cs | using FFXIVClientStructs.FFXIV.Client.System.Framework;
using FFXIVClientStructs.FFXIV.Client.UI.Agent;
using System.Runtime.InteropServices;
namespace RotationSolver.Basic.Data;
/// <summary>
/// Represents a countdown timer.
/// </summary>
[StructLayout(LayoutKind.Explicit)]
public unsafe struct Countdown
{
/// <summary>
/// The timer value.
/// </summary>
[FieldOffset(0x28)] public float Timer;
/// <summary>
/// Indicates whether the countdown is active.
/// </summary>
[FieldOffset(0x38)] public byte Active;
/// <summary>
/// The initiator of the countdown.
/// </summary>
[FieldOffset(0x3C)] public uint Initiator;
/// <summary>
/// Gets the instance of the countdown struct.
/// </summary>
public static unsafe Countdown* Instance
{
get
{
Countdown* instance = (Countdown*)Framework.Instance()->GetUIModule()->GetAgentModule()->GetAgentByInternalId(AgentId.CountDownSettingDialog);
return instance == null ? throw new InvalidOperationException("Countdown instance is null.") : instance;
}
}
/// <summary>
/// Gets the remaining time of the countdown.
/// </summary>
public static float TimeRemaining
{
get
{
Countdown* inst = Instance;
if (inst == null)
{
return 0;
}
float remainingTime = inst->Active != 0 ? inst->Timer : 0;
return remainingTime;
}
}
} | 412 | 0.81411 | 1 | 0.81411 | game-dev | MEDIA | 0.28139 | game-dev | 0.940378 | 1 | 0.940378 |
plasmicapp/plasmic | 4,885 | platform/wab/src/wab/shared/site-diffs/_tests_/merge-virtual-slots.spec.ts | import { ProjectFullDataResponse } from "@/wab/shared/ApiSchema";
import { flattenComponent } from "@/wab/shared/cached-selectors";
import { assert, ensure, hackyCast, intersectSets } from "@/wab/shared/common";
import { getParamByVarName } from "@/wab/shared/core/components";
import { flattenTpls, isTplNamable } from "@/wab/shared/core/tpls";
import {
isKnownTplComponent,
isKnownVirtualRenderExpr,
Site,
TplComponent,
TplNode,
} from "@/wab/shared/model/classes";
import defaultSlotChangeBundle from "@/wab/shared/site-diffs/_tests_/bundles/default-slot-change.json";
import {
fetchLastBundleVersion,
testMergeFromJsonBundle,
} from "@/wab/shared/site-diffs/_tests_/utils";
import { getSlotArg } from "@/wab/shared/SlotUtils";
beforeAll(async () => {
await fetchLastBundleVersion();
});
function getComponentInstance(site: Site) {
const homepage = ensure(
site.components.find((c) => c.name === "/"),
"Couldn't find Homepage"
);
const instance = ensure(
flattenComponent(homepage).find(
(tpl) => isTplNamable(tpl) && tpl.name === "wrappedInstance"
),
"Couldn't find wrappedInstance"
);
assert(isKnownTplComponent(instance), "Found instance is not of a component");
return instance;
}
function getSlotParamContent(
ancestorInstance: TplComponent,
mergedInstance: TplComponent,
slot: "target" | "content"
) {
const ancestorParam = ensure(
getParamByVarName(ancestorInstance.component, slot),
`Couldn't find ancestor ${slot} param`
);
const mergedParam = ensure(
getParamByVarName(mergedInstance.component, slot),
`Couldn't find merged ${slot} param`
);
expect(ancestorParam.uuid).toEqual(mergedParam.uuid);
const ancestorSlot = ensure(
getSlotArg(ancestorInstance, ancestorParam),
`Couldn't find ancestor ${slot} slot`
).expr;
const mergedSlot = ensure(
getSlotArg(mergedInstance, mergedParam),
`Couldn't find merged ${slot} slot`
).expr;
assert(
isKnownVirtualRenderExpr(ancestorSlot),
`Ancestor ${slot} content should be virtual render expr`
);
assert(
isKnownVirtualRenderExpr(mergedSlot),
`Merged ${slot} content should be virtual render expr`
);
return {
ancestorSlot,
mergedSlot,
};
}
function uuidsOfFlattenedTpls(tpls: TplNode[]) {
return tpls.flatMap((tpl) => flattenTpls(tpl).map(({ uuid }) => uuid));
}
describe("Merging virtual slots", () => {
it("shouldn't overwrite args for unchanged slots", () => {
/**
* defaultSlotChangeBundle contains the following components:
*
* BaseComp:
* - A component that exposes two slot targets: `target` and `content`
*
* WrappedComp:
* - A component that wraps BaseComp and forwards the slots of BaseComp
* - Both slots now contain a vertical stack with a single text node
*
* /:
* - A page that instantiates WrappedComp
*
*
* The difference between both branches is that the default value of the text node in the `content` slot is different.
* `Content` in main branch and `Content (changed)` in the broken branch.
*
* After merge we should expect that the `target` slot remains the same and the `content` slot should be different in the merged
* site instance in `WrappedComp`
*/
const result = testMergeFromJsonBundle(
hackyCast<ProjectFullDataResponse>(defaultSlotChangeBundle)
);
expect(result).toMatchObject({
status: "merged",
});
assert("ancestorSite" in result, "Expected ancestorSite to be returned");
const ancestor = result.ancestorSite;
const merged = result.mergedSite;
const ancestorInstance = getComponentInstance(ancestor);
const mergedInstance = getComponentInstance(merged);
const { ancestorSlot: ancestorSlotTarget, mergedSlot: mergedSlotTarget } =
getSlotParamContent(ancestorInstance, mergedInstance, "target");
// Since this slot wasn't changed, we should expect all the uuids to be the same
expect(uuidsOfFlattenedTpls(mergedSlotTarget.tpl)).toEqual(
uuidsOfFlattenedTpls(ancestorSlotTarget.tpl)
);
const { ancestorSlot: ancestorSlotContent, mergedSlot: mergedSlotContent } =
getSlotParamContent(ancestorInstance, mergedInstance, "content");
const uuidsAncestorSlotContent = uuidsOfFlattenedTpls(
ancestorSlotContent.tpl
);
const uuidsMergedSlotContent = uuidsOfFlattenedTpls(mergedSlotContent.tpl);
expect(uuidsAncestorSlotContent.length).toEqual(
uuidsMergedSlotContent.length
);
// All the uuids should be different because we changed the default value of the text node in the `content` slot
// which triggered the default content to be resynced
expect(
intersectSets(
new Set(uuidsAncestorSlotContent),
new Set(uuidsMergedSlotContent)
).size
).toEqual(0);
});
});
| 412 | 0.72565 | 1 | 0.72565 | game-dev | MEDIA | 0.524136 | game-dev | 0.831841 | 1 | 0.831841 |
OpenGamePanel/OGP-Website | 2,384 | lang/English/modules/config_games.php | <?php
/*
*
* OGP - Open Game Panel
* Copyright (C) 2008 - 2018 The OGP Development Team
*
* http://www.opengamepanel.org/
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
*/
define('OGP_LANG_resetting_configs', "Resetting all configs");
define('OGP_LANG_updating_configs', "Updating old configs");
define('OGP_LANG_configs_updated_ok', "Configurations reread successfully.");
define('OGP_LANG_reset_old_configs', "Reset old configs");
define('OGP_LANG_update_configs', "Update Configs");
define('OGP_LANG_game_config_setup', "Setup Game Configs");
define('OGP_LANG_config_reset_warning', "When you clear old configs there might be issues with the assigned game servers, because the identification numbers might not match with the new configurations.");
define('OGP_LANG_modify_configs_info', "If you want to modify the game configuration, you can modify the files located in %s.");
define('OGP_LANG_updating_config_from_file', "Updating config from %s file.");
define('OGP_LANG_error_when_handling_file', "Error occurred when handling file %s.");
define('OGP_LANG_error_while_adding_cfg_to_db', "Error occurred when adding data from %s to database.");
define('OGP_LANG_no_configs_found', "No configuration found from %s file.");
define('OGP_LANG_select_game', "Select Game");
define('OGP_LANG_create_xml_configs', "Create XML Configs");
define('OGP_LANG_failed_to_delete_config_from_db', "Failed to delete %s config from database");
define('OGP_LANG_failed_removing_file', "Falied removing the file %s.");
define('OGP_LANG_removed_game_cfg_from_disk_and_datbase', "Removed config for %s from storage and database.");
define('OGP_LANG_delete_game_config_for', "Delete game configuration for %s from disk and database.");
?> | 412 | 0.677375 | 1 | 0.677375 | game-dev | MEDIA | 0.678122 | game-dev | 0.665699 | 1 | 0.665699 |
madewokherd/xalia | 3,614 | xalia/UiDom/UiDomRadialDeadzone.cs | using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Xalia.Gudl;
using Xalia.Input;
namespace Xalia.UiDom
{
internal class UiDomRadialDeadzone : UiDomRoutine
{
public UiDomRadialDeadzone(UiDomRoutine routine, double deadzone) :
base("radial_deadzone", new UiDomValue[] { routine, new UiDomDouble(deadzone) })
{
Routine = routine;
Deadzone = deadzone;
}
public UiDomRoutine Routine { get; }
public double Deadzone { get; }
internal static UiDomValue ApplyFn(UiDomMethod method, UiDomValue context, GudlExpression[] arglist, UiDomRoot root, HashSet<(UiDomElement, GudlExpression)> depends_on)
{
if (arglist.Length < 2)
return UiDomUndefined.Instance;
var routine = context.Evaluate(arglist[0], root, depends_on) as UiDomRoutine;
if (routine is null)
return UiDomUndefined.Instance;
if (!context.Evaluate(arglist[1], root, depends_on).TryToDouble(out var deadzone))
return UiDomUndefined.Instance;
return new UiDomRadialDeadzone(routine, deadzone);
}
private static double ToEdgeDistance(short axis)
{
if (axis > 0)
return 1.0-(axis / 32767.0);
else
return -1.0-(axis / 32768.0);
}
private static short FromEdgeDistance(double axis)
{
if (axis > 0.0)
return (short)Math.Round((1.0 - axis) * 32767.0);
else
return (short)Math.Round((-1.0 - axis) * 32768.0);
}
public override async Task ProcessInputQueue(InputQueue queue)
{
var inner_queue = new InputQueue();
Utils.RunTask(Routine.ProcessInputQueue(inner_queue));
InputState state = default;
do
{
state = await queue.Dequeue();
if (state.Kind is InputStateKind.AnalogJoystick)
{
double xedge = ToEdgeDistance(state.XAxis);
double yedge = ToEdgeDistance(state.YAxis);
double edge_distance = Math.Min(Math.Abs(xedge), Math.Abs(yedge));
double intensity = 1.0 - edge_distance;
if (intensity <= Deadzone)
{
state.XAxis = 0;
state.YAxis = 0;
}
else
{
double new_edge_distance = edge_distance / (1.0 - Deadzone);
double multiplier = (1.0 - new_edge_distance) / (1.0 - edge_distance);
state.XAxis = (short)Math.Round(state.XAxis * multiplier);
state.YAxis = (short)Math.Round(state.YAxis * multiplier);
}
}
else if (state.Kind is InputStateKind.AnalogButton)
{
double edge_distance = ToEdgeDistance(state.Intensity);
double intensity = 1.0 - edge_distance;
if (intensity <= Deadzone)
{
state.XAxis = 0;
}
else
{
state.XAxis = FromEdgeDistance(edge_distance / (1.0 - Deadzone));
}
}
inner_queue.Enqueue(state);
} while (!(state.Kind is InputStateKind.Disconnected));
}
}
}
| 412 | 0.907711 | 1 | 0.907711 | game-dev | MEDIA | 0.33965 | game-dev | 0.94862 | 1 | 0.94862 |
PhoenixBladez/SpiritMod | 1,359 | Items/Weapon/Summon/GloomgusStaff.cs | using Microsoft.Xna.Framework;
using SpiritMod.Projectiles.Summon;
using Terraria;
using Terraria.ID;
using Terraria.ModLoader;
namespace SpiritMod.Items.Weapon.Summon
{
public class GloomgusStaff : ModItem
{
public override void SetStaticDefaults()
{
DisplayName.SetDefault("Glumshroom Staff");
Tooltip.SetDefault("Summons explosive mushrooms");
}
public override void SetDefaults()
{
item.CloneDefaults(ItemID.QueenSpiderStaff); //only here for values we haven't defined ourselves yet
item.damage = 51; //placeholder damage :3
item.mana = 10; //somehow I think this might be too much...? -thegamemaster1234
item.width = 40;
item.height = 40;
item.value = Terraria.Item.sellPrice(0, 2, 0, 0);
item.rare = ItemRarityID.Pink;
item.useTime = 30;
item.useAnimation = 30;
item.autoReuse = true;
item.knockBack = 2.5f;
item.UseSound = SoundID.Item25;
item.shoot = ModContent.ProjectileType<GloomgusShroom>();
item.shootSpeed = 0f;
}
public override bool Shoot(Player player, ref Microsoft.Xna.Framework.Vector2 position, ref float speedX, ref float speedY, ref int type, ref int damage, ref float knockBack)
{
//projectile spawns at mouse cursor
Vector2 value18 = Main.screenPosition + new Vector2((float)Main.mouseX, (float)Main.mouseY);
position = value18;
return true;
}
}
} | 412 | 0.827987 | 1 | 0.827987 | game-dev | MEDIA | 0.990193 | game-dev | 0.636712 | 1 | 0.636712 |
xBimTeam/XbimEssentials | 3,221 | Xbim.Ifc4x3/BuildingControlsDomain/IfcAlarm.cs | // ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool Xbim.CodeGeneration
//
// Changes to this file may cause incorrect behaviour and will be lost if
// the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
using Xbim.Ifc4x3.SharedBldgServiceElements;
using System;
using System.Collections.Generic;
using System.Linq;
using Xbim.Common;
using Xbim.Common.Exceptions;
using Xbim.Ifc4x3.BuildingControlsDomain;
//## Custom using statements
//##
namespace Xbim.Ifc4x3.BuildingControlsDomain
{
[ExpressType("IfcAlarm", 1098)]
// ReSharper disable once PartialTypeWithSinglePart
public partial class @IfcAlarm : IfcDistributionControlElement, IInstantiableEntity, IContainsEntityReferences, IContainsIndexedReferences, IEquatable<@IfcAlarm>
{
//internal constructor makes sure that objects are not created outside of the model/ assembly controlled area
internal IfcAlarm(IModel model, int label, bool activated) : base(model, label, activated)
{
}
#region Explicit attribute fields
private IfcAlarmTypeEnum? _predefinedType;
#endregion
#region Explicit attribute properties
[EntityAttribute(9, EntityAttributeState.Optional, EntityAttributeType.Enum, EntityAttributeType.None, null, null, 37)]
public IfcAlarmTypeEnum? @PredefinedType
{
get
{
if(_activated) return _predefinedType;
Activate();
return _predefinedType;
}
set
{
SetValue( v => _predefinedType = v, _predefinedType, value, "PredefinedType", 9);
}
}
#endregion
#region IPersist implementation
public override void Parse(int propIndex, IPropertyValue value, int[] nestedIndex)
{
switch (propIndex)
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
base.Parse(propIndex, value, nestedIndex);
return;
case 8:
_predefinedType = (IfcAlarmTypeEnum) System.Enum.Parse(typeof (IfcAlarmTypeEnum), value.EnumVal, true);
return;
default:
throw new XbimParserException(string.Format("Attribute index {0} is out of range for {1}", propIndex + 1, GetType().Name.ToUpper()));
}
}
#endregion
#region Equality comparers and operators
public bool Equals(@IfcAlarm other)
{
return this == other;
}
#endregion
#region IContainsEntityReferences
IEnumerable<IPersistEntity> IContainsEntityReferences.References
{
get
{
if (@OwnerHistory != null)
yield return @OwnerHistory;
if (@ObjectPlacement != null)
yield return @ObjectPlacement;
if (@Representation != null)
yield return @Representation;
}
}
#endregion
#region IContainsIndexedReferences
IEnumerable<IPersistEntity> IContainsIndexedReferences.IndexedReferences
{
get
{
if (@ObjectPlacement != null)
yield return @ObjectPlacement;
if (@Representation != null)
yield return @Representation;
}
}
#endregion
#region Custom code (will survive code regeneration)
//## Custom code
//##
#endregion
}
} | 412 | 0.91886 | 1 | 0.91886 | game-dev | MEDIA | 0.168622 | game-dev | 0.968571 | 1 | 0.968571 |
magefree/mage | 1,931 | Mage.Sets/src/mage/cards/e/ElvishGuidance.java | package mage.cards.e;
import mage.Mana;
import mage.abilities.Ability;
import mage.abilities.dynamicvalue.DynamicValue;
import mage.abilities.dynamicvalue.common.PermanentsOnBattlefieldCount;
import mage.abilities.effects.common.AttachEffect;
import mage.abilities.effects.mana.DynamicManaEffect;
import mage.abilities.keyword.EnchantAbility;
import mage.abilities.mana.EnchantedTappedTriggeredManaAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.Outcome;
import mage.constants.SubType;
import mage.filter.FilterPermanent;
import mage.target.TargetPermanent;
import mage.target.common.TargetLandPermanent;
import java.util.UUID;
/**
* @author Eirkei
*/
public final class ElvishGuidance extends CardImpl {
private static final FilterPermanent filter = new FilterPermanent(SubType.ELF, "Elf on the battlefield");
private static final DynamicValue xValue = new PermanentsOnBattlefieldCount(filter);
public ElvishGuidance(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.ENCHANTMENT}, "{2}{G}");
this.subtype.add(SubType.AURA);
// Enchant land
TargetPermanent auraTarget = new TargetLandPermanent();
this.getSpellAbility().addTarget(auraTarget);
this.getSpellAbility().addEffect(new AttachEffect(Outcome.PutManaInPool));
Ability ability = new EnchantAbility(auraTarget);
this.addAbility(ability);
// Whenever enchanted land is tapped for mana, its controller adds {G} for each Elf on the battlefield.
this.addAbility(new EnchantedTappedTriggeredManaAbility(new DynamicManaEffect(
Mana.GreenMana(1), xValue
)));
}
private ElvishGuidance(final ElvishGuidance card) {
super(card);
}
@Override
public ElvishGuidance copy() {
return new ElvishGuidance(this);
}
}
| 412 | 0.943622 | 1 | 0.943622 | game-dev | MEDIA | 0.927938 | game-dev | 0.994112 | 1 | 0.994112 |
Kholid060/inspect-css | 1,156 | src/lib/codemirror/lang-css/highlight.js | import { styleTags, tags as t } from '@lezer/highlight';
export const cssHighlighting = styleTags({
'AtKeyword import charset namespace keyframes media supports':
t.definitionKeyword,
'from to selector': t.keyword,
NamespaceName: t.namespace,
KeyframeName: t.labelName,
KeyframeRangeName: t.operatorKeyword,
TagName: t.tagName,
ClassName: t.className,
PseudoClassName: t.constant(t.className),
IdName: t.labelName,
'FeatureName PropertyName': t.propertyName,
AttributeName: t.attributeName,
NumberLiteral: t.number,
KeywordQuery: t.keyword,
UnaryQueryOp: t.operatorKeyword,
'CallTag ValueName': t.atom,
VariableName: t.variableName,
Callee: t.operatorKeyword,
Unit: t.unit,
'UniversalSelector NestingSelector': t.definitionOperator,
MatchOp: t.compareOperator,
'ChildOp SiblingOp, LogicOp': t.logicOperator,
BinOp: t.arithmeticOperator,
Important: t.modifier,
Comment: t.blockComment,
ColorLiteral: t.color,
'ParenthesizedContent StringLiteral': t.string,
':': t.punctuation,
'PseudoOp #': t.derefOperator,
'; ,': t.separator,
'( )': t.paren,
'[ ]': t.squareBracket,
'{ }': t.brace,
});
| 412 | 0.760773 | 1 | 0.760773 | game-dev | MEDIA | 0.332306 | game-dev | 0.92672 | 1 | 0.92672 |
beyond-aion/aion-server | 5,615 | game-server/data/handlers/quest/cygnea/_10501ResearchtheRuins.java | package quest.cygnea;
import static com.aionemu.gameserver.model.DialogAction.*;
import com.aionemu.gameserver.model.gameobjects.Item;
import com.aionemu.gameserver.model.gameobjects.player.Player;
import com.aionemu.gameserver.network.aion.serverpackets.SM_ITEM_USAGE_ANIMATION;
import com.aionemu.gameserver.questEngine.handlers.AbstractQuestHandler;
import com.aionemu.gameserver.questEngine.handlers.HandlerResult;
import com.aionemu.gameserver.questEngine.model.QuestEnv;
import com.aionemu.gameserver.questEngine.model.QuestState;
import com.aionemu.gameserver.questEngine.model.QuestStatus;
import com.aionemu.gameserver.utils.PacketSendUtility;
import com.aionemu.gameserver.utils.ThreadPoolManager;
/**
* @Author Majka
* @Description:
* Talk with Mosphera at the Aequis First Hold.
* Use the Ruins Location Map to find the first location.
* Examine the Collapsed Ruins.
* Use the Ruins Location Map to find the second location.
* Examine the Ancient Balaur Corpse.
* Use the Ruins Location Map to find the third location.
* Obtain the Token of Balaur and take it to Mosphera.
* Help Mosphera investigate the secret of the suspicious ruins.
*/
public class _10501ResearchtheRuins extends AbstractQuestHandler {
private final static int workItemId = 182215598; // Ruins Location Map
public _10501ResearchtheRuins() {
super(10501);
}
@Override
public void register() {
// Mosphera 804700
// Ancient Balaur Corpse 731535
// Collapsed Ruins 731536
int[] npcs = { 804700, 731535, 731536 };
for (int npc : npcs) {
qe.registerQuestNpc(npc).addOnTalkEvent(questId);
}
qe.registerQuestItem(workItemId, questId);
qe.registerOnQuestCompleted(questId);
qe.registerOnLevelChanged(questId);
}
@Override
public boolean onDialogEvent(QuestEnv env) {
final Player player = env.getPlayer();
final QuestState qs = player.getQuestStateList().getQuestState(questId);
if (qs == null)
return false;
int var = qs.getQuestVarById(0);
int targetId = env.getTargetId();
int dialogActionId = env.getDialogActionId();
switch (targetId) {
case 804700: // Mosphera
if (qs.getStatus() == QuestStatus.START) {
if (var == 0) { // Step 0: Talk with Mosphera at the Aequis First Hold.
if (dialogActionId == QUEST_SELECT)
return sendQuestDialog(env, 1011);
if (dialogActionId == SETPRO1)
return defaultCloseDialog(env, var, var + 1, workItemId, 1); // Gives item Ruins Location Map [ID: 182215598]
}
if (var == 6) { // Step 6: Obtain the Token of Balaur and take it to Mosphera.
if (dialogActionId == QUEST_SELECT)
return sendQuestDialog(env, 3057);
// @ToCheck: is Cygnea Aetheric Field Stone [ID: 702760] related with mission?
if (dialogActionId == CHECK_USER_HAS_QUEST_ITEM) {
long itemCount = player.getInventory().getItemCountByItemId(182215599);
if (itemCount > 0) {
removeQuestItem(env, 182215599, itemCount);
qs.setStatus(QuestStatus.REWARD);
updateQuestStatus(env);
return sendQuestDialog(env, 10000);
} else {
return sendQuestDialog(env, 10001);
}
}
}
}
if (qs.getStatus() == QuestStatus.REWARD) {
if (dialogActionId == USE_OBJECT) {
return sendQuestDialog(env, 10002);
}
return sendQuestEndDialog(env);
}
break;
case 731535: // Ancient Balaur Corpse
if (var == 4) { // Step 4: Examine the Ancient Balaur Corpse.
if (dialogActionId == QUEST_SELECT)
return sendQuestDialog(env, 2375);
if (dialogActionId == SETPRO5) {
// Spawn Beritra Raider for 10 minutes
spawnTemporarily(236250, player.getWorldMapInstance(), 2067.6863f, 386.52222f, 565.7099f, (byte) 70, 10);
return defaultCloseDialog(env, var, var + 1);
}
}
break;
case 731536: // Collapsed Ruins
if (var == 2) { // Step 2: Examine the Collapsed Ruins
if (dialogActionId == QUEST_SELECT)
return sendQuestDialog(env, 1693);
if (dialogActionId == SETPRO3)
return defaultCloseDialog(env, var, var + 1);
}
break;
}
return false;
}
@Override
public HandlerResult onItemUseEvent(final QuestEnv env, Item item) {
final Player player = env.getPlayer();
final QuestState qs = player.getQuestStateList().getQuestState(questId);
if (qs == null)
return HandlerResult.UNKNOWN;
final int id = item.getItemTemplate().getTemplateId();
if (id != workItemId)
return HandlerResult.UNKNOWN;
final int itemObjId = item.getObjectId();
PacketSendUtility.broadcastPacket(player, new SM_ITEM_USAGE_ANIMATION(player.getObjectId(), itemObjId, id, 1000, 0, 0), true);
ThreadPoolManager.getInstance().schedule(new Runnable() {
@Override
public void run() {
PacketSendUtility.broadcastPacket(player, new SM_ITEM_USAGE_ANIMATION(player.getObjectId(), itemObjId, id, 0, 1, 0), true);
int var = qs.getQuestVarById(0);
// Step 1: Use the Ruins Location Map to find the first location
// Step 3: Use the Ruins Location Map to find the second location
// Step 5: Use the Ruins Location Map to find the third location
if (var == 1 || var == 3 || var == 5) {
qs.setQuestVar(var + 1);
updateQuestStatus(env);
}
}
}, 1000);
return HandlerResult.SUCCESS;
}
@Override
public void onQuestCompletedEvent(QuestEnv env) {
defaultOnQuestCompletedEvent(env, 10500);
}
@Override
public void onLevelChangedEvent(Player player) {
defaultOnLevelChangedEvent(player, 10500);
}
}
| 412 | 0.981707 | 1 | 0.981707 | game-dev | MEDIA | 0.965381 | game-dev | 0.987516 | 1 | 0.987516 |
DoubangoTelecom/webrtc-audioproc | 1,706 | system_wrappers/source/map_no_stl.h | /*
* Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef WEBRTC_SYSTEM_WRAPPERS_SOURCE_MAP_NO_STL_H_
#define WEBRTC_SYSTEM_WRAPPERS_SOURCE_MAP_NO_STL_H_
#include "constructor_magic.h"
namespace webrtc {
class CriticalSectionWrapper;
class MapNoStlItem
{
friend class Map;
public:
MapNoStlItem(int id, void* ptr);
virtual ~MapNoStlItem();
void* GetItem();
int GetId();
unsigned int GetUnsignedId();
void SetItem(void* ptr);
protected:
MapNoStlItem* next_;
MapNoStlItem* prev_;
private:
int item_id_;
void* item_ptr_;
DISALLOW_COPY_AND_ASSIGN(MapNoStlItem);
};
class MapNoStl
{
public:
MapNoStl();
virtual ~MapNoStl();
// MapWrapper functions.
int Insert(int id, void* ptr);
int Erase(MapNoStlItem* item);
int Erase(int id);
int Size() const;
MapNoStlItem* First() const;
MapNoStlItem* Last() const;
MapNoStlItem* Next(MapNoStlItem* item) const;
MapNoStlItem* Previous(MapNoStlItem* item) const;
MapNoStlItem* Find(int id) const;
private:
MapNoStlItem* Locate(int id) const;
int Remove(MapNoStlItem* item);
CriticalSection* critical_section_;
MapNoStlItem* first_;
MapNoStlItem* last_;
int size_;
DISALLOW_COPY_AND_ASSIGN(MapNoStl);
};
} // namespace webrtc
#endif // WEBRTC_SYSTEM_WRAPPERS_SOURCE_MAP_NO_STL_H_
| 412 | 0.941433 | 1 | 0.941433 | game-dev | MEDIA | 0.312674 | game-dev | 0.682544 | 1 | 0.682544 |
devzspy/GameSpy-Openspy-Core | 2,934 | openspy/files/legacystatsprocessor/lua/thps5pc/process.lua | -- Load_NJ Load_NY Load_FL Load_SD Load_HI Load_VC Load_SJ Load_RU Load_SE Load_VN Load_HN Load_SC2
local int_map_crcs = { -154656044, 1920361226, -680391191, -300129329, 966513896, 219087401, 161763016, -1648921988, -1726262439, 1941864084, -1476443829, -1935473659 }
-- nettrickattack netgraffiti netscorechallenge netcombomambo netslap netking netgoalattack netctf netfirefight
local gametype_crcs = { 818085795, 1580115212, 345515018, -989134896, -103425741, 1861811616, -333443414, 1818227302, -1074579968 }
local gameid = 1005
function ProcessResults(profileid, snapshotdata, done)
local map = find_paramint(snapshotdata, "mapcrc")
local gametype = find_paramint(snapshotdata,"gametypecrc")
local mapindex = -1
for i,v in ipairs(int_map_crcs) do
if v == map then
mapindex = i --index 0 is for ranking, etc
end
end
if mapindex == -1 then
return 0
end
if gametype == -333443414 then
return 0
end
--used to detect if people were cheating
local cheating = find_paramint(snapshotdata,"highscore")
if cheating > 0 then
return 0
end
local max_players = find_paramint(snapshotdata, "maxplayers")
max_players = max_players - 1
local total_players = 0
for x=0,max_players do
local tscore = find_paramint(snapshotdata,"score_"..x)
if tscore > 0 then
total_players = total_players + 1
end
end
for i=0,max_players do
local playerscore = find_paramint(snapshotdata,"score_"..i)
local playercombo = find_paramint(snapshotdata,"combo_"..i)
local pid = find_paramint(snapshotdata,"pid_"..i)
local currentName = find_param(snapshotdata,"player_"..i)
local updateRank = 0
local pct = 100
if pid > 0 then
local currentRating = GetPlayerIntValue(gameid, 2, 0, pid, "Rating")
local curHighScore = GetPlayerIntValue(gameid, 2, mapindex, pid, "HighScore")
local curHighCombo = GetPlayerIntValue(gameid, 2, mapindex, pid, "HighCombo")
local totalMapIncreases = GetPlayerIntValue(gameid, 0, mapindex, pid, "TotalHSIncs")
local totalMapIncreases_Combo = GetPlayerIntValue(gameid, 0, mapindex, pid, "TotalCIncs")
if total_players > 0 then
if totalMapIncreases > 0 then
pct = pct * (totalMapIncreases/total_players)
end
end
if playerscore > curHighScore then
SetPlayerIntValue(gameid, 2, mapindex, pid, "HighScore", playerscore)
SetPlayerIntValue(gameid, 0, mapindex, pid, "TotalHSIncs", totalMapIncreases+1)
updateRank = 1
end
if playercombo > curHighCombo then
SetPlayerIntValue(gameid, 2, mapindex, pid, "HighCombo", playercombo)
SetPlayerIntValue(gameid, 0, mapindex, pid, "TotalCIncs", totalMapIncreases_Combo+1)
-- updateRank = 1
end
if updateRank == 1 then
currentRating = currentRating + pct
if currentRating > 3000 then
currentRating = 3000
end
SetPlayerIntValue(gameid, 2, 0, pid, "Rating", currentRating)
end
SetPlayerStringValue(gameid, 2, 0, pid, "PlayerName", currentName)
end
end
end
| 412 | 0.584437 | 1 | 0.584437 | game-dev | MEDIA | 0.868221 | game-dev,networking | 0.899553 | 1 | 0.899553 |
Armourers-Workshop/Armourers-Workshop | 4,234 | common/src/main/java/moe/plushie/armourers_workshop/library/client/gui/globalskinlibrary/panels/InfoLibraryPanel.java | package moe.plushie.armourers_workshop.library.client.gui.globalskinlibrary.panels;
import com.apple.library.coregraphics.CGRect;
import com.apple.library.foundation.NSMutableString;
import com.apple.library.foundation.NSTextAlignment;
import com.apple.library.uikit.UIColor;
import com.apple.library.uikit.UILabel;
import com.apple.library.uikit.UILabelDelegate;
import moe.plushie.armourers_workshop.library.client.gui.globalskinlibrary.GlobalSkinLibraryWindow;
import moe.plushie.armourers_workshop.library.data.GlobalSkinLibrary;
import moe.plushie.armourers_workshop.library.data.impl.ServerStatus;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import java.util.Map;
@Environment(EnvType.CLIENT)
public class InfoLibraryPanel extends AbstractLibraryPanel implements UILabelDelegate {
private static final String URL_DISCORD = "https://discord.gg/5Z3KKvU";
private static final String URL_GITHUB = "https://github.com/Armourers-Workshop/Armourers-Workshop";
private static final String URL_REDDIT = "https://www.reddit.com/r/ArmourersWorkshop/";
private static final String URL_DONATION = "https://ko-fi.com/riskyken";
private final UILabel label = new UILabel(CGRect.ZERO);
private ServerStatus stats = null;
private String failMessage = null;
public InfoLibraryPanel() {
super("skin-library-global.panel.info", GlobalSkinLibraryWindow.Page.LIBRARY_INFO::equals);
this.setup();
}
private void setup() {
label.setFrame(bounds().insetBy(5, 5, 5, 5));
label.setAutoresizingMask(AutoresizingMask.flexibleWidth | AutoresizingMask.flexibleHeight);
label.setTextVerticalAlignment(NSTextAlignment.Vertical.TOP);
label.setNumberOfLines(0);
label.setTextColor(UIColor.WHITE);
label.setUserInteractionEnabled(true);
label.setDelegate(this);
addSubview(label);
}
@Override
public void refresh() {
super.refresh();
stats = null;
failMessage = null;
reloadUI();
GlobalSkinLibrary.getInstance().getServerStatus((results, exception) -> {
if (exception != null) {
failMessage = exception.getMessage();
} else {
stats = results;
}
reloadUI();
});
}
public void reloadUI() {
var message = new NSMutableString("\n\n\n");
if (stats != null) {
message.append(getDisplayText("total_skins", stats.totalSkin()));
message.append("\n\n");
message.append(getDisplayText("download_count", stats.downloadsLastHour(), stats.downloadsLastDay(), stats.downloadsLastWeek()));
message.append("\n\n");
} else {
if (failMessage != null) {
message.append(getDisplayText("error_getting_stats"));
message.append("\n\n");
message.append(failMessage);
message.append("\n\n");
} else {
message.append(getDisplayText("loading"));
message.append("\n\n");
message.append("\n\n");
}
}
message.append("\n");
message.append(getDisplayText("links"));
message.append("\n\n");
message.append(getDisplayText("link.discord"));
message.append(" ");
message.append(getURLText(URL_DISCORD));
message.append("\n\n");
message.append(getDisplayText("link.github"));
message.append(" ");
message.append(getURLText(URL_GITHUB));
message.append("\n\n");
message.append(getDisplayText("link.reddit"));
message.append(" ");
message.append(getURLText(URL_REDDIT));
message.append("\n\n");
message.append("\n");
message.append(getDisplayText("link.donation"));
message.append(" ");
message.append(getURLText(URL_DONATION));
message.append("\n\n");
label.setText(message);
}
@Override
public void labelWillClickAttributes(UILabel label, Map<String, ?> attributes) {
if (router != null) {
router.labelWillClickAttributes(label, attributes);
}
}
}
| 412 | 0.606085 | 1 | 0.606085 | game-dev | MEDIA | 0.460783 | game-dev | 0.870386 | 1 | 0.870386 |
semickolon/GodotRx | 2,915 | addons/godotrx/Internal/NodeTracker.cs | using Godot;
using System;
using System.Reactive.Linq;
using System.Reactive.Subjects;
namespace GodotRx.Internal
{
internal class NodeTracker : Node
{
public static readonly string DefaultName = "__NodeTracker__";
private Subject<float>? _onProcess;
private Subject<float>? _onPhysicsProcess;
private Subject<InputEvent>? _onInput;
private Subject<InputEvent>? _onUnhandledInput;
private Subject<InputEventKey>? _onUnhandledKeyInput;
public IObservable<float> OnProcess
{
get
{
if (_onProcess == null)
{
_onProcess = new Subject<float>();
SetProcess(true);
}
return _onProcess.AsObservable();
}
}
public IObservable<float> OnPhysicsProcess
{
get
{
if (_onPhysicsProcess == null)
{
_onPhysicsProcess = new Subject<float>();
SetPhysicsProcess(true);
}
return _onPhysicsProcess.AsObservable();
}
}
public IObservable<InputEvent> OnInput
{
get
{
if (_onInput == null)
{
_onInput = new Subject<InputEvent>();
SetProcessInput(true);
}
return _onInput.AsObservable();
}
}
public IObservable<InputEvent> OnUnhandledInput
{
get
{
if (_onUnhandledInput == null)
{
_onUnhandledInput = new Subject<InputEvent>();
SetProcessUnhandledInput(true);
}
return _onUnhandledInput.AsObservable();
}
}
public IObservable<InputEventKey> OnUnhandledKeyInput
{
get
{
if (_onUnhandledKeyInput == null)
{
_onUnhandledKeyInput = new Subject<InputEventKey>();
SetProcessUnhandledKeyInput(true);
}
return _onUnhandledKeyInput.AsObservable();
}
}
public override void _Ready()
{
SetProcess(false);
SetPhysicsProcess(false);
SetProcessInput(false);
SetProcessUnhandledInput(false);
SetProcessUnhandledKeyInput(false);
}
public override void _Process(float delta)
{
_onProcess?.OnNext(delta);
}
public override void _PhysicsProcess(float delta)
{
_onPhysicsProcess?.OnNext(delta);
}
public override void _Input(InputEvent ev)
{
_onInput?.OnNext(ev);
}
public override void _UnhandledInput(InputEvent ev)
{
_onUnhandledInput?.OnNext(ev);
}
public override void _UnhandledKeyInput(InputEventKey ev)
{
_onUnhandledKeyInput?.OnNext(ev);
}
protected override void Dispose(bool disposing)
{
_onProcess?.CompleteAndDispose();
_onPhysicsProcess?.CompleteAndDispose();
_onInput?.CompleteAndDispose();
_onUnhandledInput?.CompleteAndDispose();
_onUnhandledKeyInput?.CompleteAndDispose();
base.Dispose(disposing);
}
}
} | 412 | 0.629562 | 1 | 0.629562 | game-dev | MEDIA | 0.438239 | game-dev | 0.657124 | 1 | 0.657124 |
faib920/fireasy2 | 6,965 | src/Fireasy.Common/Extensions/EnumerableExtension.cs | // -----------------------------------------------------------------------
// <copyright company="Fireasy"
// email="faib920@126.com"
// qq="55570729">
// (c) Copyright Fireasy. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
namespace Fireasy.Common.Extensions
{
/// <summary>
/// 枚举器扩展方法。
/// </summary>
public static class EnumerableExtension
{
/// <summary>
/// 将一个序列转换为 <see cref="T:System.Collections.ObjectModel.ReadOnlyCollection`1"/>。
/// </summary>
/// <typeparam name="T">元素类型。</typeparam>
/// <param name="source"></param>
/// <returns></returns>
public static ReadOnlyCollection<T> ToReadOnly<T>(this IEnumerable<T> source)
{
var list = source == null ? new List<T>() : new List<T>(source);
return list.AsReadOnly();
}
/// <summary>
/// 判断序列中是否有元素。
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
public static bool IsNullOrEmpty(this IEnumerable source)
{
if (source == null)
{
return true;
}
if (source is ICollection collection)
{
return collection.Count == 0;
}
var enu = source.GetEnumerator();
var hasElement = enu.MoveNext();
enu.TryDispose();
return !hasElement;
}
/// <summary>
/// 枚举序列中的所有元素,并执行指定的方法。
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <param name="action"></param>
public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
Guard.ArgumentNull(source, nameof(source));
Guard.ArgumentNull(action, nameof(action));
foreach (var item in source)
{
action(item);
}
}
/// <summary>
/// 枚举序列中的所有元素,并执行指定的方法(方法中带索引参数)。
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <param name="action"></param>
public static void ForEach<T>(this IEnumerable<T> source, Action<T, int> action)
{
Guard.ArgumentNull(source, nameof(source));
Guard.ArgumentNull(action, nameof(action));
var index = 0;
foreach (var item in source)
{
action(item, index++);
}
}
/// <summary>
/// 并行的方式枚举序列中的所有元素,并执行指定的方法。
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <param name="action"></param>
public static void ForEachParallel<T>(this IEnumerable<T> source, Action<T> action)
{
Guard.ArgumentNull(source, nameof(source));
Guard.ArgumentNull(action, nameof(action));
source.AsParallel().ForAll(action);
}
/// <summary>
/// 返回一个序列的切片。
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <param name="start"></param>
/// <param name="stop"></param>
/// <param name="step"></param>
/// <returns></returns>
public static IEnumerable<T> Slice<T>(this IEnumerable<T> source, int? start = null, int? stop = null, int? step = null)
{
Guard.ArgumentNull(source, nameof(source));
Guard.Argument(step != 0, nameof(step));
var sourceCollection = source as IList<T> ?? new List<T>(source);
if (sourceCollection.Count == 0)
{
yield break;
}
var stepCount = step ?? 1;
var startIndex = start ?? ((stepCount > 0) ? 0 : sourceCollection.Count - 1);
var stopIndex = stop ?? ((stepCount > 0) ? sourceCollection.Count : -1);
if (start < 0)
{
startIndex = sourceCollection.Count + startIndex;
}
if (stop < 0)
{
stopIndex = sourceCollection.Count + stopIndex;
}
startIndex = Math.Max(startIndex, (stepCount > 0) ? 0 : int.MinValue);
startIndex = Math.Min(startIndex, (stepCount > 0) ? sourceCollection.Count : sourceCollection.Count - 1);
stopIndex = Math.Max(stopIndex, -1);
stopIndex = Math.Min(stopIndex, sourceCollection.Count);
for (var i = startIndex; (stepCount > 0) ? i < stopIndex : i > stopIndex; i += stepCount)
{
yield return sourceCollection[i];
}
yield break;
}
/// <summary>
/// 构造一个不可变的序列。
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <returns></returns>
public static IEnumerable<T> MakeImmutable<T>(this IEnumerable<T> source)
{
var isReadOnlyCollection = source is ReadOnlyCollection<T>;
var isMutable = source is T[] || source is IList || source is ICollection<T>;
if (isReadOnlyCollection || !isMutable)
{
return source;
}
else
{
return CreateImmutableCollection(source);
}
}
/// <summary>
/// 将一个 <see cref="IEnumerable"/> 枚举成泛型 <typeparamref name="T"/> 的枚举。
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="enumerable"></param>
/// <returns></returns>
public static IEnumerable<T> Enumerable<T>(this IEnumerable enumerable)
{
foreach (var item in enumerable)
{
yield return (T)item;
}
}
public static void Cycle<T>(this IList<T> list, int start, Action<T> action)
{
var count = list.Count;
Guard.OutOfRange(count, start);
var i = start;
var reback = false;
list.ElementAt(1);
while (true)
{
if (i >= count)
{
i = 0;
reback = true;
}
if (reback && i >= start)
{
break;
}
action?.Invoke(list[i]);
i++;
}
}
private static IEnumerable<T> CreateImmutableCollection<T>(this IEnumerable<T> collection)
{
foreach (var item in collection)
{
yield return item;
}
}
}
}
| 412 | 0.872878 | 1 | 0.872878 | game-dev | MEDIA | 0.183627 | game-dev | 0.978113 | 1 | 0.978113 |
anantshri/Android_Security | 4,392 | Fuzzing/hacking-team/sms_fuzzer_injectors/peach/FilePublisherPdu.cs |
//
// Copyright (c) Michael Eddington
//
// 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.
//
// Authors:
// Michael Eddington (mike@dejavusecurity.com)
using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using Peach.Core.Dom;
using Peach.Core.IO;
using NLog;
namespace Peach.Core.Publishers
{
[Publisher("FilePdu", true)]
[Publisher("FileStream")]
[Publisher("file.FileWriter")]
[Publisher("file.FileReader")]
[Parameter("FileName", typeof(string), "Name of file to open for reading/writing")]
[Parameter("Overwrite", typeof(bool), "Replace existing file? [true/false, default true]", "true")]
[Parameter("Append", typeof(bool), "Append to end of file [true/false, default flase]", "false")]
public class FilePublisherPdu : StreamPublisher
{
private static NLog.Logger logger = LogManager.GetCurrentClassLogger();
protected override NLog.Logger Logger { get { return logger; } }
public string FileName { get; set; }
public string fileTemplate { get; set; }
public bool Overwrite { get; set; }
public bool Append { get; set; }
public uint Counter = 10000;
private static int maxOpenAttempts = 10;
private FileMode fileMode = FileMode.OpenOrCreate;
public FilePublisherPdu(Dictionary<string, Variant> args)
: base(args)
{
fileTemplate = FileName;
setFileName(0);
if (Overwrite && Append)
throw new PeachException("File publisher does not support Overwrite and Append being enabled at once.");
else if (Overwrite)
fileMode = FileMode.Create;
else if (Append)
fileMode = FileMode.Append | FileMode.OpenOrCreate;
else
fileMode = FileMode.OpenOrCreate;
}
protected void setFileName(uint iteration)
{
FileName = fileTemplate + iteration.ToString();
if (IsControlIteration)
FileName += ".Control";
}
protected override void OnOpen()
{
System.Diagnostics.Debug.Assert(stream == null);
int i = 0;
while (true)
{
try
{
stream = System.IO.File.Open(FileName, fileMode);
return;
}
catch (Exception ex)
{
if (++i < maxOpenAttempts)
{
Thread.Sleep(200);
}
else
{
Logger.Error("Could not open file '{0}' after {1} attempts. {2}", FileName, maxOpenAttempts, ex.Message);
throw new SoftException(ex);
}
}
}
}
protected override void OnClose()
{
System.Diagnostics.Debug.Assert(stream != null);
try
{
stream.Close();
}
catch (Exception ex)
{
logger.Error(ex.Message);
}
stream = null;
}
protected override void OnOutput(BitwiseStream data)
{
int byteRead;
System.Text.ASCIIEncoding encoding= new System.Text.ASCIIEncoding();
Byte[] bytes;
long data_length = data.Length;
if((this.Iteration % Counter) == 0)
{
this.OnClose();
this.setFileName(this.Iteration / Counter);
this.OnOpen();
}
if(data_length == 0) return;
while((byteRead = data.ReadByte()) != -1)
{
bytes = encoding.GetBytes(byteRead.ToString("X2"));
stream.WriteByte(bytes[0]);
stream.WriteByte(bytes[1]);
}
bytes = encoding.GetBytes("\n");
stream.WriteByte(bytes[0]);
}
}
}
// END
| 412 | 0.896263 | 1 | 0.896263 | game-dev | MEDIA | 0.330225 | game-dev | 0.983232 | 1 | 0.983232 |
Questie/Questie | 7,509 | Modules/QuestieAnnounce.lua | local Questie = _G.Questie
---@class QuestieAnnounce
local QuestieAnnounce = QuestieLoader:CreateModule("QuestieAnnounce")
local _QuestieAnnounce = {}
---@type QuestieDB
local QuestieDB = QuestieLoader:ImportModule("QuestieDB")
---@type QuestieLink
local QuestieLink = QuestieLoader:ImportModule("QuestieLink")
---@type l10n
local l10n = QuestieLoader:ImportModule("l10n")
local GetItemInfo = C_Item.GetItemInfo or GetItemInfo
local itemCache = {} -- cache data since this happens on item looted it could happen a lot with auto loot
local alreadySentBandaid = {} -- TODO: rewrite the entire thing its a lost cause
local _GetAnnounceMarker
---@return string
_GetAnnounceMarker = function()
local locale = l10n:GetUILocale()
if IsInRaid() or IsInGroup() then
if locale == "ruRU" then
return "{звезда} Questie: ";
elseif locale == "frFR" then
return "{rt1} Questie : ";
else
return "{rt1} Questie: "
end
else
return ""
end
end
function QuestieAnnounce:AnnounceObjectiveToChannel(questId, itemId, objectiveText, objectiveProgress)
if _QuestieAnnounce:AnnounceEnabledAndPlayerInChannel() and Questie.db.profile.questAnnounceObjectives then
-- no hyperlink required here
local questLink = QuestieLink:GetQuestLinkStringById(questId);
local objective
if itemId then
local itemLink = select(2, GetItemInfo(itemId))
objective = objectiveProgress.." "..itemLink
else
objective = objectiveProgress.." "..objectiveText
end
local message = _GetAnnounceMarker() .. l10n("%s for %s!", objective, questLink)
_QuestieAnnounce:AnnounceToChannel(message)
end
end
local _has_seen_incomplete = {}
local _has_sent_announce = {}
function QuestieAnnounce:ObjectiveChanged(questId, text, numFulfilled, numRequired)
-- Announce completed objective
if (numRequired ~= numFulfilled) then
_has_seen_incomplete[text] = true
elseif _has_seen_incomplete[text] and not _has_sent_announce[text] then
_has_seen_incomplete[text] = nil
_has_sent_announce[text] = true
QuestieAnnounce:AnnounceObjectiveToChannel(questId, nil, text, tostring(numFulfilled) .. "/" .. tostring(numRequired))
end
end
function QuestieAnnounce:AnnounceQuestItemLootedToChannel(questId, itemId)
if _QuestieAnnounce:AnnounceEnabledAndPlayerInChannel() and Questie.db.profile.questAnnounceItems then
local questHyperLink = QuestieLink:GetQuestLinkStringById(questId);
local itemLink = select(2, GetItemInfo(itemId))
local message = _GetAnnounceMarker() .. l10n("Picked up %s which starts %s!", itemLink, questHyperLink)
_QuestieAnnounce:AnnounceToChannel(message)
return true
else
return false
end
end
function _QuestieAnnounce:AnnounceSelf(questId, itemId)
local questHyperLink = QuestieLink:GetQuestHyperLink(questId);
local itemLink = select(2, GetItemInfo(itemId));
Questie:Print(l10n("You picked up %s which starts %s!", itemLink, questHyperLink));
end
---@return boolean
function _QuestieAnnounce:AnnounceEnabledAndPlayerInChannel()
if Questie.db.profile.questAnnounceLocally == true then
return true -- we always want to print if this option is enabled
elseif Questie.db.profile.questAnnounceChannel == "both" then
return IsInRaid() or IsInGroup()
elseif Questie.db.profile.questAnnounceChannel == "raid" then
return IsInRaid()
elseif Questie.db.profile.questAnnounceChannel == "party" then
return IsInGroup() and not IsInRaid()
else
return false
end
end
function _QuestieAnnounce.GetChatMessageChannel()
if IsInRaid() then
return "RAID"
elseif IsInGroup(LE_PARTY_CATEGORY_INSTANCE) then
return "INSTANCE_CHAT"
else
return "PARTY"
end
end
function _QuestieAnnounce:AnnounceToChannel(message)
Questie:Debug(Questie.DEBUG_DEVELOP, "[QuestieAnnounce] raw msg: ", message)
if (not message) or alreadySentBandaid[message] or Questie.db.profile.questieShutUp then
return
end
alreadySentBandaid[message] = true
if IsInRaid() or IsInGroup() then
SendChatMessage(message, _QuestieAnnounce.GetChatMessageChannel())
elseif Questie.db.profile.questAnnounceLocally == true then
Questie:Print(message)
end
end
local playerNameCache
---@return string
local function _GetPlayerName()
playerNameCache = UnitName("player")
return playerNameCache
end
function QuestieAnnounce:ItemLooted(text, notPlayerName, _, _, playerName)
if (playerNameCache or _GetPlayerName()) == playerName or (string.len(playerName) == 0 and playerNameCache == notPlayerName) then
local itemId = tonumber(string.match(text, "item:(%d+)"))
if not itemId then return end
local startQuestId = itemCache[itemId]
-- startQuestId can have boolean false as value, need to compare to nil
-- check QueryItemSingle because this event can fire before db init is complete
if (startQuestId == nil) and QuestieDB.QueryItemSingle then
startQuestId = QuestieDB.QueryItemSingle(itemId, "startQuest")
-- filter 0 values away so itemCache value is a valid questId if it evaluates to true
-- we do "or false" here because nil would mean not cached
startQuestId = (startQuestId and startQuestId > 0) and startQuestId or false
itemCache[itemId] = startQuestId
end
if startQuestId then
if not QuestieAnnounce:AnnounceQuestItemLootedToChannel(startQuestId, itemId) then
_QuestieAnnounce:AnnounceSelf(startQuestId, itemId)
end
end
end
end
function QuestieAnnounce:AcceptedQuest(questId)
if (_QuestieAnnounce:AnnounceEnabledAndPlayerInChannel()) and Questie.db.profile.questAnnounceAccepted then
local questLink = QuestieLink:GetQuestLinkStringById(questId)
local message = _GetAnnounceMarker() .. l10n("Quest %s: %s", l10n('Accepted'), questLink or "no quest name")
_QuestieAnnounce:AnnounceToChannel(message)
end
end
function QuestieAnnounce:AbandonedQuest(questId)
if (_QuestieAnnounce:AnnounceEnabledAndPlayerInChannel()) and Questie.db.profile.questAnnounceAbandoned then
local questLink = QuestieLink:GetQuestLinkStringById(questId)
local message = _GetAnnounceMarker() .. l10n("Quest %s: %s", l10n('Abandoned'), questLink or "no quest name")
_QuestieAnnounce:AnnounceToChannel(message)
end
end
function QuestieAnnounce:CompletedQuest(questId)
if (_QuestieAnnounce:AnnounceEnabledAndPlayerInChannel()) and Questie.db.profile.questAnnounceCompleted then
local questLink = QuestieLink:GetQuestLinkStringById(questId)
local message = _GetAnnounceMarker() .. l10n("Quest %s: %s", l10n('Completed'), questLink or "no quest name")
_QuestieAnnounce:AnnounceToChannel(message)
end
end
---@param questId QuestId
---@param breadcrumbQuestId QuestId
function QuestieAnnounce.IncompleteBreadcrumbQuest(questId, breadcrumbQuestId)
local questLink = QuestieLink:GetQuestHyperLink(questId)
local breadcrumbQuestLink = QuestieLink:GetQuestHyperLink(breadcrumbQuestId)
local message = l10n("You have accepted %s without completing its breadcrumb quest %s.", questLink, breadcrumbQuestLink)
Questie:Print(message)
end
return QuestieAnnounce
| 412 | 0.844343 | 1 | 0.844343 | game-dev | MEDIA | 0.828663 | game-dev | 0.891443 | 1 | 0.891443 |
LangYa466/MCPLite-all-source | 6,645 | src/main/java/net/minecraft/entity/ai/EntityAIControlledByPlayer.java | /*
* Decompiled with CFR 0.151.
*/
package net.minecraft.entity.ai;
import net.minecraft.block.Block;
import net.minecraft.block.BlockSlab;
import net.minecraft.block.BlockStairs;
import net.minecraft.block.material.Material;
import net.minecraft.entity.EntityCreature;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.ai.EntityAIBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.util.BlockPos;
import net.minecraft.util.MathHelper;
import net.minecraft.world.pathfinder.WalkNodeProcessor;
public class EntityAIControlledByPlayer
extends EntityAIBase {
private final EntityLiving thisEntity;
private final float maxSpeed;
private float currentSpeed;
private boolean speedBoosted;
private int speedBoostTime;
private int maxSpeedBoostTime;
public EntityAIControlledByPlayer(EntityLiving entitylivingIn, float maxspeed) {
this.thisEntity = entitylivingIn;
this.maxSpeed = maxspeed;
this.setMutexBits(7);
}
@Override
public void startExecuting() {
this.currentSpeed = 0.0f;
}
@Override
public void resetTask() {
this.speedBoosted = false;
this.currentSpeed = 0.0f;
}
@Override
public boolean shouldExecute() {
return this.thisEntity.isEntityAlive() && this.thisEntity.riddenByEntity != null && this.thisEntity.riddenByEntity instanceof EntityPlayer && (this.speedBoosted || this.thisEntity.canBeSteered());
}
@Override
public void updateTask() {
ItemStack itemstack;
EntityPlayer entityplayer = (EntityPlayer)this.thisEntity.riddenByEntity;
EntityCreature entitycreature = (EntityCreature)this.thisEntity;
float f = MathHelper.wrapAngleTo180_float(entityplayer.rotationYaw - this.thisEntity.rotationYaw) * 0.5f;
if (f > 5.0f) {
f = 5.0f;
}
if (f < -5.0f) {
f = -5.0f;
}
this.thisEntity.rotationYaw = MathHelper.wrapAngleTo180_float(this.thisEntity.rotationYaw + f);
if (this.currentSpeed < this.maxSpeed) {
this.currentSpeed += (this.maxSpeed - this.currentSpeed) * 0.01f;
}
if (this.currentSpeed > this.maxSpeed) {
this.currentSpeed = this.maxSpeed;
}
int i = MathHelper.floor_double(this.thisEntity.posX);
int j = MathHelper.floor_double(this.thisEntity.posY);
int k = MathHelper.floor_double(this.thisEntity.posZ);
float f1 = this.currentSpeed;
if (this.speedBoosted) {
if (this.speedBoostTime++ > this.maxSpeedBoostTime) {
this.speedBoosted = false;
}
f1 += f1 * 1.15f * MathHelper.sin((float)this.speedBoostTime / (float)this.maxSpeedBoostTime * (float)Math.PI);
}
float f2 = 0.91f;
if (this.thisEntity.onGround) {
f2 = this.thisEntity.worldObj.getBlockState((BlockPos)new BlockPos((int)MathHelper.floor_float((float)((float)i)), (int)(MathHelper.floor_float((float)((float)j)) - 1), (int)MathHelper.floor_float((float)((float)k)))).getBlock().slipperiness * 0.91f;
}
float f3 = 0.16277136f / (f2 * f2 * f2);
float f4 = MathHelper.sin(entitycreature.rotationYaw * (float)Math.PI / 180.0f);
float f5 = MathHelper.cos(entitycreature.rotationYaw * (float)Math.PI / 180.0f);
float f6 = entitycreature.getAIMoveSpeed() * f3;
float f7 = Math.max(f1, 1.0f);
f7 = f6 / f7;
float f8 = f1 * f7;
float f9 = -(f8 * f4);
float f10 = f8 * f5;
if (MathHelper.abs(f9) > MathHelper.abs(f10)) {
if (f9 < 0.0f) {
f9 -= this.thisEntity.width / 2.0f;
}
if (f9 > 0.0f) {
f9 += this.thisEntity.width / 2.0f;
}
f10 = 0.0f;
} else {
f9 = 0.0f;
if (f10 < 0.0f) {
f10 -= this.thisEntity.width / 2.0f;
}
if (f10 > 0.0f) {
f10 += this.thisEntity.width / 2.0f;
}
}
int l = MathHelper.floor_double(this.thisEntity.posX + (double)f9);
int i1 = MathHelper.floor_double(this.thisEntity.posZ + (double)f10);
int j1 = MathHelper.floor_float(this.thisEntity.width + 1.0f);
int k1 = MathHelper.floor_float(this.thisEntity.height + entityplayer.height + 1.0f);
int l1 = MathHelper.floor_float(this.thisEntity.width + 1.0f);
if (i != l || k != i1) {
boolean flag;
Block block = this.thisEntity.worldObj.getBlockState(new BlockPos(i, j, k)).getBlock();
boolean bl = flag = !this.isStairOrSlab(block) && (block.getMaterial() != Material.air || !this.isStairOrSlab(this.thisEntity.worldObj.getBlockState(new BlockPos(i, j - 1, k)).getBlock()));
if (flag && 0 == WalkNodeProcessor.func_176170_a(this.thisEntity.worldObj, this.thisEntity, l, j, i1, j1, k1, l1, false, false, true) && 1 == WalkNodeProcessor.func_176170_a(this.thisEntity.worldObj, this.thisEntity, i, j + 1, k, j1, k1, l1, false, false, true) && 1 == WalkNodeProcessor.func_176170_a(this.thisEntity.worldObj, this.thisEntity, l, j + 1, i1, j1, k1, l1, false, false, true)) {
entitycreature.getJumpHelper().setJumping();
}
}
if (!entityplayer.capabilities.isCreativeMode && this.currentSpeed >= this.maxSpeed * 0.5f && this.thisEntity.getRNG().nextFloat() < 0.006f && !this.speedBoosted && (itemstack = entityplayer.getHeldItem()) != null && itemstack.getItem() == Items.carrot_on_a_stick) {
itemstack.damageItem(1, entityplayer);
if (itemstack.stackSize == 0) {
ItemStack itemstack1 = new ItemStack(Items.fishing_rod);
itemstack1.setTagCompound(itemstack.getTagCompound());
entityplayer.inventory.mainInventory[entityplayer.inventory.currentItem] = itemstack1;
}
}
this.thisEntity.moveEntityWithHeading(0.0f, f1);
}
private boolean isStairOrSlab(Block blockIn) {
return blockIn instanceof BlockStairs || blockIn instanceof BlockSlab;
}
public boolean isSpeedBoosted() {
return this.speedBoosted;
}
public void boostSpeed() {
this.speedBoosted = true;
this.speedBoostTime = 0;
this.maxSpeedBoostTime = this.thisEntity.getRNG().nextInt(841) + 140;
}
public boolean isControlledByPlayer() {
return !this.isSpeedBoosted() && this.currentSpeed > this.maxSpeed * 0.3f;
}
}
| 412 | 0.849837 | 1 | 0.849837 | game-dev | MEDIA | 0.955778 | game-dev | 0.983655 | 1 | 0.983655 |
TelepathicGrunt/RepurposedStructures-Quilt | 4,298 | src/main/java/com/telepathicgrunt/repurposedstructures/world/features/StructureVineAndLeaves.java | package com.telepathicgrunt.repurposedstructures.world.features;
import com.mojang.serialization.Codec;
import com.telepathicgrunt.repurposedstructures.world.features.configs.StructureTargetAndLengthConfig;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.VineBlock;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.levelgen.feature.Feature;
import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext;
public class StructureVineAndLeaves extends Feature<StructureTargetAndLengthConfig> {
public StructureVineAndLeaves(Codec<StructureTargetAndLengthConfig> config) {
super(config);
}
@Override
public boolean place(FeaturePlaceContext<StructureTargetAndLengthConfig> context) {
BlockPos.MutableBlockPos mutable = new BlockPos.MutableBlockPos();
for(int i = 0; i < context.config().attempts; i++) {
mutable.set(context.origin()).move(
context.random().nextInt(7) - 3,
context.random().nextInt(4) - 1,
context.random().nextInt(7) - 3
);
if(!context.level().isEmptyBlock(mutable)) {
continue;
}
// generates vines from given position down length number of blocks if path is clear and the given position is valid
int length = 0;
BlockPos.MutableBlockPos vineMutablePos = new BlockPos.MutableBlockPos().set(mutable);
ChunkPos currentChunkPos = new ChunkPos(vineMutablePos);
BlockState currentBlockstate;
BlockState aboveBlockstate;
// Biased towards max length
int maxLength = context.config().length - context.random().nextInt(context.random().nextInt(context.config().length) + 1);
int targetY = vineMutablePos.getY() - maxLength;
for (; vineMutablePos.getY() >= targetY; vineMutablePos.move(Direction.DOWN)) {
if (context.level().isEmptyBlock(vineMutablePos)) {
for (Direction direction : Direction.Plane.HORIZONTAL) {
mutable.set(vineMutablePos).move(direction);
ChunkPos newChunkPos = new ChunkPos(mutable);
// Prevent floating vines at chunk borders
if(newChunkPos.x != currentChunkPos.x || newChunkPos.z != currentChunkPos.z) continue;
if(length == 0 &&
context.level().getBlockState(vineMutablePos.above()).canOcclude() &&
context.level().getBlockState(mutable).isAir() &&
context.level().getBlockState(mutable.above()).canOcclude())
{
context.level().setBlock(mutable, Blocks.JUNGLE_LEAVES.defaultBlockState(), 3);
}
currentBlockstate = Blocks.VINE.defaultBlockState().setValue(VineBlock.getPropertyForFace(direction), Boolean.TRUE);
aboveBlockstate = context.level().getBlockState(vineMutablePos.above());
if (currentBlockstate.canSurvive(context.level(), vineMutablePos) && context.level().getBlockState(vineMutablePos.relative(direction)).getBlock() != Blocks.MOSS_CARPET) {
//places topmost vine that can face upward
context.level().setBlock(vineMutablePos, currentBlockstate.setValue(VineBlock.UP, aboveBlockstate.canOcclude()), 2);
length++;
break;
}
else if (aboveBlockstate.is(Blocks.VINE)) {
//places rest of the vine as long as vine is above
context.level().setBlock(vineMutablePos, aboveBlockstate.setValue(VineBlock.UP, false), 2);
length++;
break;
}
}
} else {
break;
}
}
}
return true;
}
} | 412 | 0.92064 | 1 | 0.92064 | game-dev | MEDIA | 0.966733 | game-dev | 0.944955 | 1 | 0.944955 |
openmultiplayer/open.mp | 15,962 | Server/Components/Pawn/Scripting/Vehicle/Natives.cpp | /*
* This Source Code Form is subject to the terms of the Mozilla Public License,
* v. 2.0. If a copy of the MPL was not distributed with this file, You can
* obtain one at http://mozilla.org/MPL/2.0/.
*
* The original code is copyright (c) 2022, open.mp team and contributors.
*/
#include "../Types.hpp"
#include <Server/Components/Vehicles/vehicle_components.hpp>
#include <Server/Components/Vehicles/vehicle_models.hpp>
#include <Server/Components/Vehicles/vehicle_colours.hpp>
#include <Server/Components/Vehicles/vehicle_seats.hpp>
#include <sdk.hpp>
SCRIPT_API(CreateVehicle, int(int modelid, Vector3 pos, float rotation, int colour1, int colour2, int respawnDelay))
{
bool addSiren = false;
auto params = GetParams();
if ((params[0] / sizeof(cell)) >= 9)
{
addSiren = params[9];
}
IVehiclesComponent* vehicles = PawnManager().Get()->vehicles;
if (vehicles)
{
IVehicle* vehicle = vehicles->create(false, modelid, pos, rotation, colour1, colour2, Seconds(respawnDelay), addSiren);
if (vehicle)
{
return vehicle->getID();
}
}
return INVALID_VEHICLE_ID;
}
SCRIPT_API(GetVehicleSeats, int(int modelid))
{
return Impl::getVehiclePassengerSeats(modelid);
}
SCRIPT_API(DestroyVehicle, bool(IVehicle& vehicle))
{
PawnManager().Get()->vehicles->release(vehicle.getID());
return true;
}
SCRIPT_API(IsVehicleStreamedIn, bool(IVehicle& vehicle, IPlayer& player))
{
return vehicle.isStreamedInForPlayer(player);
}
SCRIPT_API(GetVehiclePos, bool(IVehicle& vehicle, Vector3& pos))
{
pos = vehicle.getPosition();
return true;
}
SCRIPT_API(SetVehiclePos, bool(IVehicle& vehicle, Vector3 pos))
{
vehicle.setPosition(pos);
return true;
}
SCRIPT_API(GetVehicleZAngle, bool(IVehicle& vehicle, float& angle))
{
angle = vehicle.getZAngle();
return true;
}
SCRIPT_API(GetVehicleRotationQuat, bool(IVehicle& vehicle, GTAQuat& quat))
{
quat = vehicle.getRotation();
return true;
}
SCRIPT_API(GetVehicleDistanceFromPoint, float(IVehicle& vehicle, Vector3 pos))
{
return glm::distance(vehicle.getPosition(), pos);
}
SCRIPT_API(SetVehicleZAngle, bool(IVehicle& vehicle, float angle))
{
vehicle.setZAngle(angle);
return true;
}
SCRIPT_API(SetVehicleParamsForPlayer, bool(IVehicle& vehicle, IPlayer& player, int objective, int doors))
{
VehicleParams params = vehicle.getParams();
params.objective = objective;
params.doors = doors;
vehicle.setParamsForPlayer(player, params);
return true;
}
SCRIPT_API(ManualVehicleEngineAndLights, bool())
{
if (PawnManager().Get()->config)
{
*PawnManager().Get()->config->getBool("game.use_manual_engine_and_lights") = true;
}
return true;
}
SCRIPT_API(SetVehicleParamsEx, bool(IVehicle& vehicle, int engine, int lights, int alarm, int doors, int bonnet, int boot, int objective))
{
VehicleParams params = vehicle.getParams();
params.engine = engine;
params.lights = lights;
params.alarm = alarm;
params.doors = doors;
params.bonnet = bonnet;
params.boot = boot;
params.objective = objective;
vehicle.setParams(params);
return true;
}
SCRIPT_API(GetVehicleParamsEx, bool(IVehicle& vehicle, int& engine, int& lights, int& alarm, int& doors, int& bonnet, int& boot, int& objective))
{
const VehicleParams& params = vehicle.getParams();
engine = params.engine;
lights = params.lights;
alarm = params.alarm;
doors = params.doors;
bonnet = params.bonnet;
boot = params.boot;
objective = params.objective;
return true;
}
SCRIPT_API(GetVehicleParamsSirenState, int(IVehicle& vehicle))
{
return vehicle.getParams().siren;
}
SCRIPT_API(SetVehicleParamsCarDoors, bool(IVehicle& vehicle, int frontLeft, int frontRight, int rearLeft, int rearRight))
{
VehicleParams params = vehicle.getParams();
params.doorDriver = frontLeft;
params.doorPassenger = frontRight;
params.doorBackLeft = rearLeft;
params.doorBackRight = rearRight;
vehicle.setParams(params);
return true;
}
SCRIPT_API(GetVehicleParamsCarDoors, bool(IVehicle& vehicle, int& frontLeft, int& frontRight, int& rearLeft, int& rearRight))
{
const VehicleParams& params = vehicle.getParams();
frontLeft = params.doorDriver;
frontRight = params.doorPassenger;
rearLeft = params.doorBackLeft;
rearRight = params.doorBackRight;
return true;
}
SCRIPT_API(SetVehicleParamsCarWindows, bool(IVehicle& vehicle, int frontLeft, int frontRight, int rearLeft, int rearRight))
{
VehicleParams params = vehicle.getParams();
params.windowDriver = frontLeft;
params.windowPassenger = frontRight;
params.windowBackLeft = rearLeft;
params.windowBackRight = rearRight;
vehicle.setParams(params);
return true;
}
SCRIPT_API(GetVehicleParamsCarWindows, bool(IVehicle& vehicle, int& frontLeft, int& frontRight, int& rearLeft, int& rearRight))
{
const VehicleParams& params = vehicle.getParams();
frontLeft = params.windowDriver;
frontRight = params.windowPassenger;
rearLeft = params.windowBackLeft;
rearRight = params.windowBackRight;
return true;
}
SCRIPT_API(SetVehicleToRespawn, bool(IVehicle& vehicle))
{
vehicle.respawn();
return true;
}
SCRIPT_API(LinkVehicleToInterior, bool(IVehicle& vehicle, int interiorid))
{
vehicle.setInterior(interiorid);
return true;
}
SCRIPT_API(AddVehicleComponent, bool(IVehicle& vehicle, int componentid))
{
vehicle.addComponent(componentid);
return true;
}
SCRIPT_API(RemoveVehicleComponent, bool(IVehicle& vehicle, int componentid))
{
vehicle.removeComponent(componentid);
return true;
}
SCRIPT_API(ChangeVehicleColor, bool(IVehicle& vehicle, int colour1, int colour2))
{
vehicle.setColour(colour1, colour2);
return true;
}
SCRIPT_API(ChangeVehiclePaintjob, bool(IVehicle& vehicle, int paintjobid))
{
vehicle.setPaintJob(paintjobid);
return true;
}
SCRIPT_API(SetVehicleHealth, bool(IVehicle& vehicle, float health))
{
vehicle.setHealth(health);
return true;
}
SCRIPT_API(GetVehicleHealth, bool(IVehicle& vehicle, float& health))
{
health = vehicle.getHealth();
return true;
}
SCRIPT_API(AttachTrailerToVehicle, bool(IVehicle& trailer, IVehicle& vehicle))
{
vehicle.attachTrailer(trailer);
return true;
}
SCRIPT_API(DetachTrailerFromVehicle, bool(IVehicle& vehicle))
{
vehicle.detachTrailer();
return true;
}
SCRIPT_API(IsTrailerAttachedToVehicle, bool(IVehicle& vehicle))
{
return vehicle.getTrailer() != nullptr;
}
SCRIPT_API(GetVehicleTrailer, int(IVehicle& vehicle))
{
IVehicle* trailer = vehicle.getTrailer();
if (trailer)
{
return trailer->getID();
}
else
{
return 0; // why isnt this INVALID_VEHICLE_ID mr keyman
}
}
SCRIPT_API(SetVehicleNumberPlate, bool(IVehicle& vehicle, std::string const& numberPlate))
{
vehicle.setPlate(numberPlate);
return true;
}
SCRIPT_API(GetVehicleModel, int(IVehicle& vehicle))
{
return vehicle.getModel();
}
SCRIPT_API(GetVehicleComponentInSlot, int(IVehicle& vehicle, int slot))
{
return vehicle.getComponentInSlot(slot);
}
SCRIPT_API(GetVehicleComponentType, int(int componentid))
{
return getVehicleComponentSlot(componentid);
}
SCRIPT_API(VehicleCanHaveComponent, bool(int modelid, int componentid))
{
return Impl::isValidComponentForVehicleModel(modelid, componentid);
}
SCRIPT_API(GetRandomCarColPair, bool(int modelid, int& colour1, int& colour2, int& colour3, int& colour4))
{
getRandomVehicleColour(modelid, colour1, colour2, colour3, colour4);
return true;
}
SCRIPT_API(CarColIndexToColour, int(int colourIndex, int alpha))
{
return carColourIndexToColour(colourIndex, alpha);
}
SCRIPT_API(RepairVehicle, bool(IVehicle& vehicle))
{
vehicle.repair();
return true;
}
SCRIPT_API(GetVehicleVelocity, bool(IVehicle& vehicle, Vector3& velocity))
{
velocity = vehicle.getVelocity();
return true;
}
SCRIPT_API(SetVehicleVelocity, bool(IVehicle& vehicle, Vector3 velocity))
{
vehicle.setVelocity(velocity);
return true;
}
SCRIPT_API(SetVehicleAngularVelocity, bool(IVehicle& vehicle, Vector3 velocity))
{
vehicle.setAngularVelocity(velocity);
return true;
}
SCRIPT_API(GetVehicleDamageStatus, bool(IVehicle& vehicle, int& panels, int& doors, int& lights, int& tires))
{
vehicle.getDamageStatus(panels, doors, lights, tires);
return true;
}
SCRIPT_API(UpdateVehicleDamageStatus, bool(IVehicle& vehicle, int panels, int doors, int lights, int tires))
{
vehicle.setDamageStatus(panels, doors, lights, tires);
return true;
}
SCRIPT_API(GetVehicleModelInfo, bool(int vehiclemodel, int infotype, Vector3& pos))
{
return getVehicleModelInfo(vehiclemodel, VehicleModelInfoType(infotype), pos);
}
SCRIPT_API(SetVehicleVirtualWorld, bool(IVehicle& vehicle, int virtualWorld))
{
vehicle.setVirtualWorld(virtualWorld);
return true;
}
SCRIPT_API(GetVehicleVirtualWorld, int(IVehicle& vehicle))
{
return vehicle.getVirtualWorld();
}
SCRIPT_API(GetVehicleLandingGearState, int(IVehicle& vehicle))
{
return vehicle.getLandingGearState();
}
SCRIPT_API(IsValidVehicle, bool(IVehicle* vehicle))
{
return vehicle != nullptr;
}
SCRIPT_API(AddStaticVehicle, int(int modelid, Vector3 spawn, float angle, int colour1, int colour2))
{
IVehiclesComponent* vehicles = PawnManager().Get()->vehicles;
if (vehicles)
{
IVehicle* vehicle = vehicles->create(true, modelid, spawn, angle, colour1, colour2, Seconds(120), false);
if (vehicle)
{
return vehicle->getID();
}
}
return INVALID_VEHICLE_ID;
}
SCRIPT_API(AddStaticVehicleEx, int(int modelid, Vector3 spawn, float angle, int colour1, int colour2, int respawnDelay))
{
bool addSiren = false;
auto params = GetParams();
if ((params[0] / sizeof(cell)) >= 9)
{
addSiren = params[9];
}
IVehiclesComponent* vehicles = PawnManager().Get()->vehicles;
if (vehicles)
{
IVehicle* vehicle = vehicles->create(true, modelid, spawn, angle, colour1, colour2, Seconds(respawnDelay), addSiren);
if (vehicle)
{
return vehicle->getID();
}
}
return INVALID_VEHICLE_ID;
}
SCRIPT_API(EnableVehicleFriendlyFire, bool())
{
*PawnManager::Get()->config->getBool("game.use_vehicle_friendly_fire") = true;
return true;
}
SCRIPT_API(GetVehicleSpawnInfo, bool(IVehicle& vehicle, Vector3& position, float& rotation, int& colour1, int& colour2))
{
const VehicleSpawnData& data = vehicle.getSpawnData();
position = data.position;
rotation = data.zRotation;
colour1 = data.colour1;
colour2 = data.colour2;
return true;
}
SCRIPT_API(SetVehicleSpawnInfo, bool(IVehicle& vehicle, int modelid, Vector3 position, float rotation, int colour1, int colour2, int respawn_time, int interior))
{
const VehicleSpawnData& data = vehicle.getSpawnData();
vehicle.setSpawnData({ respawn_time >= -1 ? Seconds(respawn_time) : data.respawnDelay, modelid, position, rotation, colour1, colour2, data.siren, interior != -2 ? interior : data.interior });
return true;
}
SCRIPT_API(GetVehicleModelCount, int(int modelid))
{
if (modelid < 400 || modelid > 611)
return 0;
auto& models = PawnManager::Get()->vehicles->models();
return models[modelid - 400];
}
SCRIPT_API(GetVehicleModelsUsed, int())
{
auto& vehicle_models = PawnManager::Get()->vehicles->models();
return std::count_if(vehicle_models.begin(), vehicle_models.end(), [](uint8_t model_instances)
{
return model_instances > 0;
});
}
SCRIPT_API(GetVehiclePaintjob, int(IVehicle& vehicle))
{
return vehicle.getPaintJob();
}
SCRIPT_API(GetVehicleColor, bool(IVehicle& vehicle, int& colour1, int& colour2))
{
Pair<int, int> colors = vehicle.getColour();
colour1 = colors.first;
colour2 = colors.second;
return true;
}
SCRIPT_API(GetVehicleInterior, int(IVehicle& vehicle))
{
return vehicle.getInterior();
}
SCRIPT_API(GetVehicleNumberPlate, bool(IVehicle& vehicle, OutputOnlyString& number_plate))
{
number_plate = vehicle.getPlate();
return true;
}
SCRIPT_API(SetVehicleRespawnDelay, bool(IVehicle& vehicle, int respawn_delay))
{
if (respawn_delay < -1)
return false;
vehicle.setRespawnDelay(Seconds(respawn_delay));
return true;
}
SCRIPT_API(GetVehicleRespawnDelay, int(IVehicle& vehicle))
{
return vehicle.getRespawnDelay().count();
}
SCRIPT_API_FAILRET(GetVehicleCab, INVALID_VEHICLE_ID, int(IVehicle& vehicle))
{
IVehicle* cab = vehicle.getCab();
if (cab == nullptr)
{
return FailRet;
}
return cab->getID();
}
SCRIPT_API_FAILRET(GetVehicleTower, INVALID_VEHICLE_ID, int(IVehicle& vehicle))
{
IVehicle* cab = vehicle.getCab();
if (cab == nullptr)
{
return FailRet;
}
return cab->getID();
}
SCRIPT_API(GetVehicleOccupiedTick, int(IVehicle& vehicle))
{
return std::chrono::duration_cast<Milliseconds>(Time::now() - vehicle.getLastOccupiedTime()).count();
}
SCRIPT_API(GetVehicleRespawnTick, int(IVehicle& vehicle))
{
return std::chrono::duration_cast<Milliseconds>(Time::now() - vehicle.getLastSpawnTime()).count();
}
SCRIPT_API(HasVehicleBeenOccupied, bool(IVehicle& vehicle))
{
return vehicle.hasBeenOccupied();
}
SCRIPT_API(IsVehicleOccupied, bool(IVehicle& vehicle))
{
return vehicle.isOccupied();
}
SCRIPT_API(IsVehicleDead, bool(IVehicle& vehicle))
{
return vehicle.isDead();
}
SCRIPT_API(SetVehicleParamsSirenState, bool(IVehicle& vehicle, bool siren_state))
{
VehicleParams params = vehicle.getParams();
params.siren = siren_state;
vehicle.setParams(params);
return true;
}
SCRIPT_API(ToggleVehicleSirenEnabled, bool(IVehicle& vehicle, bool status))
{
vehicle.setSiren(status);
return true;
}
SCRIPT_API(IsVehicleSirenEnabled, bool(IVehicle& vehicle))
{
return vehicle.getSpawnData().siren;
}
SCRIPT_API_FAILRET(GetVehicleLastDriver, INVALID_PLAYER_ID, int(IVehicle& vehicle))
{
return vehicle.getLastDriverPoolID();
}
SCRIPT_API_FAILRET(GetVehicleDriver, INVALID_PLAYER_ID, int(IVehicle& vehicle))
{
IPlayer* driver = vehicle.getDriver();
if (!driver)
{
return FailRet;
}
return driver->getID();
}
SCRIPT_API(IsPlayerInModShop, bool(IPlayerVehicleData& data))
{
return data.isInModShop();
}
SCRIPT_API(GetPlayerSirenState, int(IPlayerVehicleData& data))
{
IVehicle* vehicle = data.getVehicle();
if (vehicle)
{
return vehicle->getSirenState();
}
return 0;
}
SCRIPT_API(GetPlayerLandingGearState, int(IPlayerVehicleData& data))
{
IVehicle* vehicle = data.getVehicle();
if (vehicle)
{
return vehicle->getLandingGearState();
}
return 0;
}
SCRIPT_API(GetPlayerHydraReactorAngle, int(IPlayerVehicleData& data))
{
IVehicle* vehicle = data.getVehicle();
if (vehicle)
{
return vehicle->getHydraThrustAngle();
}
return 0;
}
SCRIPT_API(GetPlayerTrainSpeed, float(IPlayerVehicleData& data))
{
IVehicle* vehicle = data.getVehicle();
if (vehicle)
{
return vehicle->getTrainSpeed();
}
return 0.0f;
}
SCRIPT_API(GetVehicleSirenState, int(IVehicle& vehicle))
{
return vehicle.getSirenState();
}
SCRIPT_API(GetVehicleHydraReactorAngle, int(IVehicle& vehicle))
{
return vehicle.getHydraThrustAngle();
}
SCRIPT_API(GetVehicleTrainSpeed, float(IVehicle& vehicle))
{
return vehicle.getTrainSpeed();
}
SCRIPT_API(GetVehicleMatrix, bool(IVehicle& vehicle, Vector3& right, Vector3& up, Vector3& at))
{
glm::mat3 mat = glm::transpose(glm::mat3_cast(vehicle.getRotation().q));
right = mat[0];
up = mat[1];
at = mat[2];
return true;
}
SCRIPT_API_FAILRET(GetVehicleOccupant, INVALID_PLAYER_ID, int(IVehicle& vehicle, int seat))
{
IPlayer* driver = vehicle.getDriver();
// Looking for driver
if (seat == 0)
{
return driver == nullptr ? INVALID_PLAYER_ID : driver->getID();
}
// Looking for a passenger
else
{
const FlatHashSet<IPlayer*>& passengers = vehicle.getPassengers();
for (auto& passenger : passengers)
{
if (passenger)
{
IPlayerVehicleData* data = queryExtension<IPlayerVehicleData>(passenger);
if (data && data->getSeat() == seat)
{
return passenger->getID();
}
}
}
}
return INVALID_PLAYER_ID;
}
SCRIPT_API(GetVehicleMaxPassengers, int(int model))
{
return Impl::getVehiclePassengerSeats(model);
}
SCRIPT_API(CountVehicleOccupants, int(IVehicle& vehicle))
{
IPlayer* driver = vehicle.getDriver();
const FlatHashSet<IPlayer*>& passengers = vehicle.getPassengers();
int occupants = 0;
if (driver)
{
occupants++;
}
occupants += passengers.size();
return occupants;
}
| 412 | 0.791998 | 1 | 0.791998 | game-dev | MEDIA | 0.870552 | game-dev | 0.621893 | 1 | 0.621893 |
lokinmodar/Echoglossian | 1,425 | NativeUI/AddonHandlers/Character/CharacterReputeSubWindowHandler.cs | // <copyright file="CharacterReputeSubWindowHandler.cs" company="lokinmodar">
// Copyright (c) lokinmodar. All rights reserved.
// Licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International Public License license.
// </copyright>
namespace Echoglossian.NativeUI.AddonHandlers.Character;
/// <summary>
/// Handles translation for the "CharacterClass" addon using AtkValues and
/// StringArrayData.
/// Lifecycle-safe: extracts and applies values within valid memory scope per
/// frame.
/// </summary>
public class CharacterReputeSubWindowHandler : GenericAddonHandler<GameWindow>
{
/// <summary>
/// Initializes a new instance of the
/// <see cref="CharacterReputeSubWindowHandler" /> class.
/// </summary>
/// <param name="config">The configuration settings for the plugin.</param>
/// <param name="translationService">The service used for translating text.</param>
public CharacterReputeSubWindowHandler(
Config config,
TranslationService translationService)
: base(
"CharacterRepute",
config,
translationService,
true,
true,
StringArrayType.Character)
{
this.RegisterHandler(AddonEvent.PreSetup, this.OnPreSetup);
this.RegisterHandler(AddonEvent.PreRefresh, this.OnPreRefresh);
this.RegisterHandler(
AddonEvent.PreRequestedUpdate,
this.OnPreRequestedUpdate);
}
} | 412 | 0.890522 | 1 | 0.890522 | game-dev | MEDIA | 0.869596 | game-dev | 0.901154 | 1 | 0.901154 |
SammySemicolon/Malum-Mod | 2,668 | src/main/java/com/sammy/malum/common/item/curiosities/curios/sets/soulward/CurioMagebaneBelt.java | package com.sammy.malum.common.item.curiosities.curios.sets.soulward;
import com.google.common.collect.Multimap;
import com.sammy.malum.MalumMod;
import com.sammy.malum.common.item.IMalumEventResponder;
import com.sammy.malum.common.item.curiosities.curios.MalumCurioItem;
import com.sammy.malum.core.helpers.*;
import com.sammy.malum.core.systems.events.*;
import com.sammy.malum.registry.common.MalumAttributes;
import net.minecraft.core.Holder;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.*;
import net.minecraft.world.entity.*;
import net.minecraft.world.entity.ai.attributes.Attribute;
import net.minecraft.world.entity.ai.attributes.AttributeModifier;
import net.minecraft.world.item.ItemStack;
import team.lodestar.lodestone.registry.common.tag.LodestoneDamageTypeTags;
import top.theillusivec4.curios.api.SlotContext;
import java.util.function.Consumer;
public class CurioMagebaneBelt extends MalumCurioItem implements IMalumEventResponder {
public CurioMagebaneBelt(Properties builder) {
super(builder, MalumTrinketType.ORNATE);
}
@Override
public void addExtraTooltipLines(Consumer<Component> consumer) {
consumer.accept(ComponentHelper.positiveCurioEffect("soul_ward_magic_resilience"));
consumer.accept(ComponentHelper.negativeCurioEffect("soul_ward_long_shatter_cooldown"));
}
@Override
public void modifySoulWardPropertiesEvent(ModifySoulWardPropertiesEvent event, LivingEntity wardedEntity, ItemStack stack) {
if (event.getSource().is(LodestoneDamageTypeTags.IS_MAGIC)) {
event.setNewIntegrity(event.getOriginalIntegrity()*1.5f);
}
}
@Override
public void soulWardDamageEvent(SoulWardDamageEvent event, LivingEntity wardedEntity, ItemStack stack) {
var handler = event.getSoulWardHandler();
if (handler.isDepleted()) {
handler.addCooldown(wardedEntity, 8f);
return;
}
if (event.getSource().is(LodestoneDamageTypeTags.IS_MAGIC)) {
handler.recoverSoulWard(wardedEntity, 1.5f);
}
}
@Override
public void addAttributeModifiers(Multimap<Holder<Attribute>, AttributeModifier> map, SlotContext slotContext, ItemStack stack) {
final ResourceLocation id = MalumMod.malumPath("magebane_belt");
addAttributeModifier(map, MalumAttributes.SOUL_WARD_RECOVERY_RATE,
new AttributeModifier(id, 0.4f, AttributeModifier.Operation.ADD_MULTIPLIED_BASE));
addAttributeModifier(map, MalumAttributes.SOUL_WARD_CAPACITY,
new AttributeModifier(id, 6f, AttributeModifier.Operation.ADD_VALUE));
}
}
| 412 | 0.859065 | 1 | 0.859065 | game-dev | MEDIA | 0.975379 | game-dev | 0.963665 | 1 | 0.963665 |
SuperAnt30/Mvk | 4,527 | Mvk/MvkServer/World/Block/List/BlockTallGrass.cs | using MvkServer.Glm;
using MvkServer.Item;
using MvkServer.Item.List;
using MvkServer.Util;
namespace MvkServer.World.Block.List
{
/// <summary>
/// Блок длинной травы
/// </summary>
public class BlockTallGrass : BlockAbPlants
{
/***
* Met
* 0 - низ
* 1 - вверх
*/
/// <summary>
/// Блок длинной травы
/// </summary>
public BlockTallGrass() : base(209) { }
/// <summary>
/// Блок который замедляет сущность в перемещении на ~30%
/// </summary>
public override bool IsSlow(BlockState state) => state.met == 0;
/// <summary>
/// Стороны целого блока для рендера 0 - 5 стороны
/// </summary>
public override QuadSide[] GetQuads(int met, int xc, int zc, int xb, int zb)
=> quads[((xc + zc + xb + zb) & 4) + met * 5];
/// <summary>
/// Передать список ограничительных рамок блока
/// </summary>
public override AxisAlignedBB[] GetCollisionBoxesToList(BlockPos pos, int met)
{
return new AxisAlignedBB[] { new AxisAlignedBB(
new vec3(pos.X + .0625f, pos.Y, pos.Z + .0625f),
new vec3(pos.X + .9375f, pos.Y + (met == 0 ? 1 : .75f), pos.Z + .9375f)) };
}
/// <summary>
/// Инициализация коробок
/// </summary>
protected override void InitQuads()
{
vec3[] offsetMet = new vec3[]
{
new vec3(0),
new vec3(.1875f, 0, .1875f),
new vec3(-.1875f, 0, .1875f),
new vec3(.1875f, 0, -.1875f),
new vec3(-.1875f, 0, -.1875f)
};
quads = new QuadSide[10][];
for (int i = 0; i < 5; i++)
{
quads[i] = new QuadSide[] {
new QuadSide(1).SetTexture(Particle).SetSide(Pole.North, true, -2, 0, 8, 18, 16, 8).SetRotate(glm.pi45).SetTranslate(offsetMet[i]),
new QuadSide(1).SetTexture(Particle).SetSide(Pole.West, true, 8, 0, -2, 8, 16, 18).SetRotate(glm.pi45).SetTranslate(offsetMet[i])
};
quads[i + 5] = new QuadSide[] {
new QuadSide(1).SetTexture(Particle + 1).SetSide(Pole.North, true, -2, 0, 8, 18, 16, 8).SetRotate(glm.pi45).SetTranslate(offsetMet[i]).Wind(),
new QuadSide(1).SetTexture(Particle + 1).SetSide(Pole.West, true, 8, 0, -2, 8, 16, 18).SetRotate(glm.pi45).SetTranslate(offsetMet[i]).Wind()
};
}
}
/// <summary>
/// Действие перед размещеннием блока, для определения метданных
/// </summary>
public override BlockState OnBlockPlaced(WorldBase worldIn, BlockPos blockPos, BlockState state, Pole side, vec3 facing)
=> state.NewMet(1);
/// <summary>
/// Проверка установи блока, можно ли его установить тут
/// </summary>
public override bool CanBlockStay(WorldBase worldIn, BlockPos blockPos, int met = 0)
{
EnumBlock enumBlock = worldIn.GetBlockState(blockPos.OffsetDown()).GetEBlock();
return enumBlock == EnumBlock.TallGrass || enumBlock == EnumBlock.Turf;
}
/// <summary>
/// Смена соседнего блока
/// </summary>
public override void NeighborBlockChange(WorldBase worldIn, BlockPos blockPos, BlockState neighborState, BlockBase neighborBlock)
{
if (!CanBlockStay(worldIn, blockPos))
{
// DropBlockAsItem(worldIn, blockPos, state, 0);
worldIn.SetBlockToAir(blockPos, 15);
}
else if (worldIn.GetBlockState(blockPos.OffsetUp()).IsAir())
{
worldIn.SetBlockStateMet(blockPos, 1);
}
}
#region Drop
/// <summary>
/// Получите количество выпавших на основе данного уровня удачи
/// </summary>
protected override int QuantityDroppedWithBonus(ItemAbTool itemTool, Rand random)
=> (itemTool != null && itemTool.EItem == EnumItem.AxeSteel) || random.Next(10) == 0 ? 1 : 0;
/// <summary>
/// Получите предмет, который должен выпасть из этого блока при сборе.
/// </summary>
protected override ItemBase GetItemDropped(BlockState state, Rand rand, ItemAbTool itemTool)
=> Items.GetItemCache(EnumItem.DryGrass);
#endregion
}
}
| 412 | 0.903963 | 1 | 0.903963 | game-dev | MEDIA | 0.910568 | game-dev | 0.953843 | 1 | 0.953843 |
prime31/ZestKit | 2,864 | Assets/ZestKit/Collections/TweenChain.cs | using UnityEngine;
using System;
using System.Collections.Generic;
using System.Collections;
namespace Prime31.ZestKit
{
/// <summary>
/// provides a container that allows you to chain together 2 or more ITweenables. They will run one after the other until
/// all of them are complete.
/// </summary>
public class TweenChain : AbstractTweenable
{
List<ITweenable> _tweenList = new List<ITweenable>();
int _currentTween = 0;
Action<TweenChain> _completionHandler;
public int totalTweens { get { return _tweenList.Count; } }
public override void start()
{
// prep our first tween
if( _tweenList.Count > 0 )
_tweenList[0].start();
base.start();
}
#region ITweenable
public override bool tick()
{
if( _isPaused )
return false;
// if currentTween is greater than we've got in the tweenList end this chain
if( _currentTween >= _tweenList.Count )
return true;
var tween = _tweenList[_currentTween];
if( tween.tick() )
{
_currentTween++;
if( _currentTween == _tweenList.Count )
{
if( _completionHandler != null )
_completionHandler( this );
_isCurrentlyManagedByZestKit = false;
return true;
}
else
{
// we have a new tween so start it
_tweenList[_currentTween].start();
}
}
return false;
}
public override void recycleSelf()
{
for( var i = 0; i < _tweenList.Count; i++ )
_tweenList[i].recycleSelf();
_tweenList.Clear();
}
/// <summary>
/// bringToCompletion is ignored for chains due to it not having a solid, specific meaning for a chain
/// </summary>
/// <param name="bringToCompletion">If set to <c>true</c> bring to completion.</param>
public override void stop( bool bringToCompletion = false, bool bringToCompletionImmediately = false )
{
_currentTween = _tweenList.Count;
}
#endregion
#region ITweenControl
/// <summary>
/// when called via StartCoroutine this will continue until the TweenChain completes
/// </summary>
/// <returns>The for completion.</returns>
public IEnumerator waitForCompletion()
{
while( _currentTween < _tweenList.Count )
yield return null;
}
#endregion
#region TweenChain management
public TweenChain appendTween( ITweenable tween )
{
// make sure we have a legit ITweenable
if( tween is ITweenable )
{
tween.resume();
_tweenList.Add( tween as ITweenable );
}
else
{
Debug.LogError( "attempted to add a tween that does not implement ITweenable to a TweenChain!" );
}
return this;
}
/// <summary>
/// chainable. sets the action that should be called when the tween is complete.
/// </summary>
public TweenChain setCompletionHandler( Action<TweenChain> completionHandler )
{
_completionHandler = completionHandler;
return this;
}
#endregion
}
} | 412 | 0.880635 | 1 | 0.880635 | game-dev | MEDIA | 0.317924 | game-dev | 0.90202 | 1 | 0.90202 |
jimdroberts/FishMMO | 6,134 | FishMMO-Unity/Assets/Scripts/Client/UI/Controls/World/HotkeyBar/UIHotkeyButton.cs | using FishMMO.Shared;
using FishNet.Transporting;
using UnityEngine.UI;
namespace FishMMO.Client
{
/// <summary>
/// UI button for a hotkey slot, supporting cooldown display and hotkey assignment.
/// </summary>
public class UIHotkeyButton : UIReferenceButton
{
/// <summary>
/// The hotkey slot index this button represents.
/// </summary>
public int HotkeySlot;
/// <summary>
/// The slider used to visually represent cooldown progress for this hotkey.
/// </summary>
public Slider CooldownMask;
/// <summary>
/// The key mapping string for this hotkey (e.g., "1", "Q").
/// </summary>
public string KeyMap = "";
/// <summary>
/// Unity Awake callback. Subscribes to cooldown events.
/// </summary>
protected override void Awake()
{
ICooldownController.OnAddCooldown += CooldownController_OnAddCooldown;
ICooldownController.OnUpdateCooldown += CooldownController_OnUpdateCooldown;
ICooldownController.OnRemoveCooldown += CooldownController_OnRemoveCooldown;
}
/// <summary>
/// Unity OnDestroy callback. Unsubscribes from cooldown events.
/// </summary>
protected override void OnDestroy()
{
ICooldownController.OnAddCooldown -= CooldownController_OnAddCooldown;
ICooldownController.OnUpdateCooldown -= CooldownController_OnUpdateCooldown;
ICooldownController.OnRemoveCooldown -= CooldownController_OnRemoveCooldown;
}
/// <summary>
/// Handles the event when a cooldown is added for a reference ID.
/// Updates the cooldown mask value if relevant.
/// </summary>
/// <param name="referenceID">The reference ID for the cooldown.</param>
/// <param name="cooldown">The cooldown instance.</param>
private void CooldownController_OnAddCooldown(long referenceID, CooldownInstance cooldown)
{
if (referenceID != ReferenceID ||
CooldownMask == null)
{
return;
}
// Only update if cooldown times are valid
if (cooldown.RemainingTime > 0 &&
cooldown.TotalTime > 0)
{
CooldownMask.value = cooldown.RemainingTime / cooldown.TotalTime;
}
}
/// <summary>
/// Handles the event when a cooldown is updated for a reference ID.
/// Updates the cooldown mask value if relevant.
/// </summary>
/// <param name="referenceID">The reference ID for the cooldown.</param>
/// <param name="cooldown">The cooldown instance.</param>
private void CooldownController_OnUpdateCooldown(long referenceID, CooldownInstance cooldown)
{
if (referenceID != ReferenceID ||
CooldownMask == null)
{
return;
}
// Only update if cooldown times are valid
if (cooldown.RemainingTime > 0 &&
cooldown.TotalTime > 0)
{
CooldownMask.value = cooldown.RemainingTime / cooldown.TotalTime;
}
}
/// <summary>
/// Handles the event when a cooldown is removed for a reference ID.
/// Resets the cooldown mask value if relevant.
/// </summary>
/// <param name="referenceID">The reference ID for the cooldown.</param>
private void CooldownController_OnRemoveCooldown(long referenceID)
{
if (referenceID != ReferenceID ||
CooldownMask == null)
{
return;
}
CooldownMask.value = 0.0f;
}
/// <summary>
/// Handles left mouse click events for the hotkey button.
/// Assigns a hotkey if dragging, otherwise activates the hotkey.
/// </summary>
public override void OnLeftClick()
{
if (UIManager.TryGet("UIDragObject", out UIDragObject dragObject) &&
dragObject.Visible)
{
// Only allow assignment for non-bank types
if (dragObject.Type != ReferenceButtonType.Bank)
{
Type = dragObject.Type;
ReferenceID = dragObject.ReferenceID;
if (Icon != null)
{
Icon.sprite = dragObject.Icon.sprite;
}
// Tell the server to assign this hotkey
Client.Broadcast(new HotkeySetBroadcast()
{
HotkeyData = new HotkeyData()
{
Type = (byte)Type,
Slot = HotkeySlot,
ReferenceID = ReferenceID,
}
}, Channel.Reliable);
}
// Clear the drag object no matter what
dragObject.Clear();
}
else
{
Activate();
}
}
/// <summary>
/// Handles right mouse click events for the hotkey button.
/// Removes the hotkey assignment and clears the button.
/// </summary>
public override void OnRightClick()
{
if (UIManager.TryGet("UIDragObject", out UIDragObject dragObject) && ReferenceID != NULL_REFERENCE_ID)
{
dragObject.SetReference(Icon.sprite, ReferenceID, Type);
Clear();
// Tell server to clear this hotkey
Client.Broadcast(new HotkeySetBroadcast()
{
HotkeyData = new HotkeyData()
{
Type = 0,
Slot = HotkeySlot,
ReferenceID = UIReferenceButton.NULL_REFERENCE_ID,
}
}, Channel.Reliable);
}
}
/// <summary>
/// Activates the hotkey action based on its type and key mapping.
/// </summary>
public void Activate()
{
if (Character != null && !string.IsNullOrWhiteSpace(KeyMap))
{
switch (Type)
{
case ReferenceButtonType.None:
break;
case ReferenceButtonType.Inventory:
// Activate inventory item
if (Character.TryGet(out IInventoryController inventoryController))
{
inventoryController.Activate((int)ReferenceID);
}
break;
case ReferenceButtonType.Equipment:
// Activate equipment item
if (Character.TryGet(out IEquipmentController equipmentController))
{
equipmentController.Activate((int)ReferenceID);
}
break;
case ReferenceButtonType.Bank:
break;
case ReferenceButtonType.Ability:
// Activate ability if UI does not have focus
if (!UIManager.ControlHasFocus() &&
Character.TryGet(out IAbilityController abilityController))
{
abilityController.Activate(ReferenceID, InputManager.GetKeyCode(KeyMap));
}
break;
default:
return;
}
}
}
/// <summary>
/// Clears the hotkey button UI and resets the cooldown mask.
/// </summary>
public override void Clear()
{
base.Clear();
if (CooldownMask != null)
{
CooldownMask.value = 0;
}
}
}
} | 412 | 0.627559 | 1 | 0.627559 | game-dev | MEDIA | 0.90444 | game-dev | 0.67089 | 1 | 0.67089 |
Fluorohydride/ygopro-scripts | 2,492 | c71870152.lua | --フォーチュンレディ・ファイリー
function c71870152.initial_effect(c)
--atk,def
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e1:SetRange(LOCATION_MZONE)
e1:SetCode(EFFECT_SET_ATTACK)
e1:SetValue(c71870152.value)
c:RegisterEffect(e1)
local e2=e1:Clone()
e2:SetCode(EFFECT_SET_DEFENSE)
c:RegisterEffect(e2)
--level up
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(71870152,0))
e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F)
e3:SetRange(LOCATION_MZONE)
e3:SetCountLimit(1)
e3:SetCode(EVENT_PHASE+PHASE_STANDBY)
e3:SetCondition(c71870152.lvcon)
e3:SetOperation(c71870152.lvop)
c:RegisterEffect(e3)
--destroy
local e4=Effect.CreateEffect(c)
e4:SetDescription(aux.Stringid(71870152,1))
e4:SetCategory(CATEGORY_DESTROY+CATEGORY_DAMAGE)
e4:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e4:SetProperty(EFFECT_FLAG_CARD_TARGET)
e4:SetCode(EVENT_SPSUMMON_SUCCESS)
e4:SetCondition(c71870152.descon)
e4:SetTarget(c71870152.destg)
e4:SetOperation(c71870152.desop)
c:RegisterEffect(e4)
end
function c71870152.value(e,c)
return c:GetLevel()*200
end
function c71870152.lvcon(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetTurnPlayer()==tp
end
function c71870152.lvop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsFacedown() or not c:IsRelateToEffect(e) or c:IsLevelAbove(12) then return end
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_LEVEL)
e1:SetValue(1)
e1:SetReset(RESET_EVENT+RESETS_STANDARD+RESET_DISABLE)
c:RegisterEffect(e1)
end
function c71870152.descon(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
return c:IsFaceup() and c:IsAttackPos() and c:IsSpecialSummonSetCard(0x31)
end
function c71870152.filter(c)
return c:IsFaceup()
end
function c71870152.destg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(1-tp) and c71870152.filter(chkc) end
if chk==0 then return true end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY)
local g=Duel.SelectTarget(tp,c71870152.filter,tp,0,LOCATION_MZONE,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,g:GetCount(),0,0)
Duel.SetOperationInfo(0,CATEGORY_DAMAGE,nil,0,1-tp,0)
end
function c71870152.desop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if not tc then return end
local atk=tc:GetAttack()
if tc:IsFaceup() and tc:IsRelateToEffect(e) and Duel.Destroy(tc,REASON_EFFECT)~=0 then
Duel.Damage(1-tp,atk,REASON_EFFECT)
end
end
| 412 | 0.891971 | 1 | 0.891971 | game-dev | MEDIA | 0.981012 | game-dev | 0.949312 | 1 | 0.949312 |
Aussiemon/Darktide-Source-Code | 5,778 | dialogues/generated/adamant_a_psyker_female_b.lua | -- chunkname: @dialogues/generated/adamant_a_psyker_female_b.lua
local adamant_a_psyker_female_b = {
combat_pause_limited_adamant_a_02_b = {
randomize_indexes_n = 0,
sound_events_n = 1,
sound_events = {
[1] = "loc_psyker_female_b__combat_pause_limited_adamant_a_02_b_01",
},
sound_events_duration = {
[1] = 4.111688,
},
randomize_indexes = {},
},
combat_pause_limited_adamant_a_05_b = {
randomize_indexes_n = 0,
sound_events_n = 1,
sound_events = {
[1] = "loc_psyker_female_b__combat_pause_limited_adamant_a_05_b_01",
},
sound_events_duration = {
[1] = 4.193896,
},
randomize_indexes = {},
},
combat_pause_limited_adamant_a_11_b = {
randomize_indexes_n = 0,
sound_events_n = 1,
sound_events = {
[1] = "loc_psyker_female_b__combat_pause_limited_adamant_a_11_b_01",
},
sound_events_duration = {
[1] = 3.131583,
},
randomize_indexes = {},
},
combat_pause_limited_adamant_a_15_b = {
randomize_indexes_n = 0,
sound_events_n = 1,
sound_events = {
[1] = "loc_psyker_female_b__combat_pause_limited_adamant_a_15_b_01",
},
sound_events_duration = {
[1] = 4.514688,
},
randomize_indexes = {},
},
combat_pause_limited_adamant_a_18_b = {
randomize_indexes_n = 0,
sound_events_n = 1,
sound_events = {
[1] = "loc_psyker_female_b__combat_pause_limited_adamant_a_18_b_01",
},
sound_events_duration = {
[1] = 4.308292,
},
randomize_indexes = {},
},
combat_pause_limited_adamant_a_20_b = {
randomize_indexes_n = 0,
sound_events_n = 1,
sound_events = {
[1] = "loc_psyker_female_b__combat_pause_limited_adamant_a_20_b_01",
},
sound_events_duration = {
[1] = 4.356521,
},
randomize_indexes = {},
},
combat_pause_limited_bolt_on_a_adamant_a_01_b = {
randomize_indexes_n = 0,
sound_events_n = 1,
sound_events = {
[1] = "loc_psyker_female_b__combat_pause_limited_bolt_on_a_adamant_a_01_b_01",
},
sound_events_duration = {
[1] = 4.349854,
},
randomize_indexes = {},
},
combat_pause_quirk_adamant_a_trait_01_b = {
randomize_indexes_n = 0,
sound_events_n = 2,
sound_events = {
[1] = "loc_psyker_female_b__combat_pause_quirk_adamant_a_trait_01_b_01",
[2] = "loc_psyker_female_b__combat_pause_quirk_adamant_a_trait_01_b_02",
},
sound_events_duration = {
[1] = 3.177563,
[2] = 4.898063,
},
randomize_indexes = {},
},
combat_pause_quirk_adamant_a_trait_02_b = {
randomize_indexes_n = 0,
sound_events_n = 2,
sound_events = {
[1] = "loc_psyker_female_b__combat_pause_quirk_adamant_a_trait_02_b_01",
[2] = "loc_psyker_female_b__combat_pause_quirk_adamant_a_trait_02_b_02",
},
sound_events_duration = {
[1] = 3.432292,
[2] = 4.470292,
},
randomize_indexes = {},
},
combat_pause_quirk_adamant_a_trait_03_b = {
randomize_indexes_n = 0,
sound_events_n = 2,
sound_events = {
[1] = "loc_psyker_female_b__combat_pause_quirk_adamant_a_trait_03_b_01",
[2] = "loc_psyker_female_b__combat_pause_quirk_adamant_a_trait_03_b_02",
},
sound_events_duration = {
[1] = 3.110979,
[2] = 2.925688,
},
randomize_indexes = {},
},
combat_pause_quirk_adamant_a_trait_04_b = {
randomize_indexes_n = 0,
sound_events_n = 2,
sound_events = {
[1] = "loc_psyker_female_b__combat_pause_quirk_adamant_a_trait_04_b_01",
[2] = "loc_psyker_female_b__combat_pause_quirk_adamant_a_trait_04_b_02",
},
sound_events_duration = {
[1] = 3.381667,
[2] = 5.666063,
},
randomize_indexes = {},
},
combat_pause_quirk_adamant_a_trait_05_b = {
randomize_indexes_n = 0,
sound_events_n = 2,
sound_events = {
[1] = "loc_psyker_female_b__combat_pause_quirk_adamant_a_trait_05_b_01",
[2] = "loc_psyker_female_b__combat_pause_quirk_adamant_a_trait_05_b_02",
},
sound_events_duration = {
[1] = 2.259438,
[2] = 2.935813,
},
randomize_indexes = {},
},
combat_pause_quirk_adamant_a_trait_06_b = {
randomize_indexes_n = 0,
sound_events_n = 2,
sound_events = {
[1] = "loc_psyker_female_b__combat_pause_quirk_adamant_a_trait_06_b_01",
[2] = "loc_psyker_female_b__combat_pause_quirk_adamant_a_trait_06_b_02",
},
sound_events_duration = {
[1] = 5.551771,
[2] = 3.566604,
},
randomize_indexes = {},
},
combat_pause_quirk_adamant_a_trait_07_b = {
randomize_indexes_n = 0,
sound_events_n = 2,
sound_events = {
[1] = "loc_psyker_female_b__combat_pause_quirk_adamant_a_trait_07_b_01",
[2] = "loc_psyker_female_b__combat_pause_quirk_adamant_a_trait_07_b_02",
},
sound_events_duration = {
[1] = 2.906917,
[2] = 4.440729,
},
randomize_indexes = {},
},
combat_pause_quirk_adamant_a_trait_08_b = {
randomize_indexes_n = 0,
sound_events_n = 2,
sound_events = {
[1] = "loc_psyker_female_b__combat_pause_quirk_adamant_a_trait_08_b_01",
[2] = "loc_psyker_female_b__combat_pause_quirk_adamant_a_trait_08_b_02",
},
sound_events_duration = {
[1] = 5.044521,
[2] = 3.642979,
},
randomize_indexes = {},
},
combat_pause_quirk_adamant_a_trait_09_b = {
randomize_indexes_n = 0,
sound_events_n = 2,
sound_events = {
[1] = "loc_psyker_female_b__combat_pause_quirk_adamant_a_trait_09_b_01",
[2] = "loc_psyker_female_b__combat_pause_quirk_adamant_a_trait_09_b_02",
},
sound_events_duration = {
[1] = 1.820104,
[2] = 3.080313,
},
randomize_indexes = {},
},
combat_pause_quirk_adamant_a_trait_10_b = {
randomize_indexes_n = 0,
sound_events_n = 2,
sound_events = {
[1] = "loc_psyker_female_b__combat_pause_quirk_adamant_a_trait_10_b_01",
[2] = "loc_psyker_female_b__combat_pause_quirk_adamant_a_trait_10_b_02",
},
sound_events_duration = {
[1] = 4.72,
[2] = 3.9425,
},
randomize_indexes = {},
},
}
return settings("adamant_a_psyker_female_b", adamant_a_psyker_female_b)
| 412 | 0.786078 | 1 | 0.786078 | game-dev | MEDIA | 0.799728 | game-dev | 0.562091 | 1 | 0.562091 |
LuxiaSL/hephia | 12,589 | internal/modules/behaviors/behavior_manager.py | # modules/behaviors/behavior_manager.py
from typing import Optional
from .behavior import Behavior
from .idle import IdleBehavior
from .walk import WalkBehavior
from .chase import ChaseBehavior
from .sleep import SleepBehavior
from .relax import RelaxBehavior
from ..needs.needs_manager import NeedsManager
from ...internal_context import InternalContext
from event_dispatcher import global_event_dispatcher, Event
import time
import random
class BehaviorManager:
"""
Manages behaviors through a probabilistic state transition system.
The behavior system models natural activity patterns by:
{immediate reactions} -> {needs drive behavior changes}
{energy management} -> {alternates between active and restful states}
{mood influence} -> {emotional state affects behavior choices}
{fuzzy determinism} -> {behaviors emerge naturally but not predictably}
Behaviors affect needs directly through rate modification,
creating a natural feedback loop between activity and internal state.
Future integrations with cognitive systems will allow for more
deliberate behavior control and learning.
"""
BEHAVIOR_PATTERNS = {
'idle': {
'base_weight': 0.3,
'transitions': {
'walk': {
'trigger': 'boredom',
'probability': lambda needs: 1 - needs['boredom']['satisfaction'], # Inverse of satisfaction
'min_threshold': 0.3 # 30% satisfaction or below to start walk
},
'relax': {
'trigger': 'stamina',
'probability': lambda needs: 1 - needs['stamina']['satisfaction'],
'min_threshold': 0.6 # Relax triggers if stamina is less than 60% satisfied
}
}
},
'walk': {
'base_weight': 0.2,
'transitions': {
'chase': {
'trigger': 'boredom',
'probability': lambda needs: 1 - needs['boredom']['satisfaction'],
'min_threshold': 0.5,
'condition': lambda needs: needs['stamina']['satisfaction'] > 0.4 # Only chase if stamina is above 40%
},
'relax': {
'trigger': 'stamina',
'probability': lambda needs: 1 - needs['stamina']['satisfaction'],
'min_threshold': 0.3
},
'idle': {
'trigger': 'boredom',
'probability': lambda needs: needs['boredom']['satisfaction'],
'min_threshold': 0.3
}
}
},
'relax': {
'base_weight': 0.2,
'transitions': {
'sleep': {
'trigger': 'stamina',
'probability': lambda needs: 1 - needs['stamina']['satisfaction'],
'min_threshold': 0.2
},
'idle': {
'trigger': 'stamina',
'probability': lambda needs: needs['stamina']['satisfaction'],
'min_threshold': 0.6
}
}
},
'sleep': {
'base_weight': 0.1,
'force_threshold': {
'trigger': 'stamina',
'value': 0.1 # Trigger sleep when stamina satisfaction drops below 10%
},
'transitions': {
'idle': {
'trigger': 'stamina',
'probability': lambda needs: needs['stamina']['satisfaction'],
'min_threshold': 0.8 # Wake up if stamina is above 80% satisfied
}
}
}
}
def __init__(self, internal_context: InternalContext, needs_manager: NeedsManager):
"""
Initializes the BehaviorManager.
Args:
internal_context (InternalContext): methods to retrieve current internal state
needs_manager (NeedsManager): The NeedsManager instance (used by behaviors to manage rates)
"""
self.internal_context = internal_context
self.needs_manager = needs_manager
self.current_behavior: Optional[Behavior] = None
self.locked_until = 0
self.locked_by = None
self.behaviors = {
'idle': IdleBehavior(self),
'walk': WalkBehavior(self),
'chase': ChaseBehavior(self),
'sleep': SleepBehavior(self),
'relax': RelaxBehavior(self)
}
self.change_behavior('idle')
self.setup_event_listeners()
def setup_event_listeners(self):
global_event_dispatcher.add_listener("need:changed", self.determine_behavior)
global_event_dispatcher.add_listener("action:completed", self.determine_behavior)
global_event_dispatcher.add_listener("mood:changed", self.determine_behavior)
global_event_dispatcher.add_listener("emotion:new", self.determine_behavior)
global_event_dispatcher.add_listener("memory:echo", self._handle_memory_echo)
async def _handle_memory_echo(self, event):
"""
Handle memory echo effects on behavior by creating a light behavioral resonance
based on remembered states.
"""
echo_data = event.data
if not echo_data or 'metadata' not in echo_data:
return
# Extract remembered behavior state if present
remembered_behavior = echo_data['metadata'].get('behavior', {})
if not remembered_behavior:
return
# Calculate echo intensity factoring system-wide echo intensity
behavior_intensity = echo_data.get('intensity', 0.3) * 0.4 # Reduced impact vs direct needs/emotions
# If behavior matches current, temporarily lock it
if remembered_behavior.get('name') == self.current_behavior.name:
# Brief lock to reinforce behavior
lock_duration = 1.5 * behavior_intensity
self.locked_until = time.time() + lock_duration
self.locked_by = 'memory_echo'
else:
# Force behavior recheck with current context
await self.determine_behavior(event)
def update(self):
"""
Updates the current behavior.
"""
if self.current_behavior:
self.current_behavior.update()
def change_behavior(self, new_behavior_name):
"""
Changes the current behavior.
Args:
new_behavior_name (str): selected behavior to activate
"""
old_behavior = None # Ensure old_behavior is always defined
if self.current_behavior:
old_behavior = self.current_behavior
self.current_behavior.stop()
self.current_behavior = self.behaviors[new_behavior_name]
self.current_behavior.start()
global_event_dispatcher.dispatch_event_sync(Event("behavior:changed", {
"old_name": old_behavior.name if old_behavior else None,
"new_name": new_behavior_name
}))
def is_locked(self):
"""
Checks if the behavior is currently locked.
Returns:
bool: True if the behavior is locked, False otherwise.
"""
return time.time() < self.locked_until
def force_behavior(self, behavior_name, duration=None):
"""
Forces a specific behavior for a given duration.
Args:
behavior_name (str): The name of the behavior to force.
duration (float, optional): The duration in seconds to lock the behavior. If not provided, the behavior will be locked indefinitely.
"""
if behavior_name in self.behaviors:
self.change_behavior(behavior_name)
if duration:
self.locked_until = time.time() + duration
self.locked_by = 'forced'
else:
self.locked_until = float('inf')
self.locked_by = 'forced'
async def determine_behavior(self, event):
"""
Determines the appropriate behavior based on the current state and event.
Args:
event (Event): The event that triggered the behavior determination.
"""
event_type = event.event_type
event_data = event.data
current_needs = self.internal_context.get_current_needs()
current_mood = self.internal_context.get_current_mood()
recent_emotions = await self.internal_context.get_recent_emotions()
new_behavior = self._calculate_behavior(event_type, event_data, current_needs, current_mood, recent_emotions)
if new_behavior != self.current_behavior.name:
self.change_behavior(new_behavior)
def _calculate_behavior(self, event_type, event_data, current_needs, current_mood, recent_emotions):
"""
Calculates the appropriate behavior based on the current state and event using a probabilistic transition system.
Args:
event_type (str): The type of event that triggered the behavior calculation.
event_data (dict): Additional data associated with the event.
current_needs (dict): The current state of the internal's needs.
current_mood (dict): The current mood info of the internal.
recent_emotions (list): A list of recent EmotionalVector objects.
Returns:
str: The name of the selected behavior.
"""
if self.is_locked():
print("Behavior is locked; returning current behavior.")
return self.current_behavior.name
current = self.current_behavior.name
pattern = self.BEHAVIOR_PATTERNS[current]
# Step 1: Check force_threshold conditions
for behavior, data in self.BEHAVIOR_PATTERNS.items():
if 'force_threshold' in data:
threshold = data['force_threshold']
current_value = current_needs[threshold['trigger']]['satisfaction']
if current_value <= threshold['value']:
return behavior
# Step 2: Calculate transition weights
transition_weights = {}
for next_behavior, rules in pattern['transitions'].items():
current_value = current_needs[rules['trigger']]['satisfaction']
probability = rules['probability'](current_needs)
if current_value <= rules['min_threshold']:
if 'condition' in rules and not rules['condition'](current_needs):
continue
transition_weights[next_behavior] = probability * random.random()
if not transition_weights:
# Default to current behavior or choose a safe fallback
return current
# Step 3: Add weight for staying in current behavior
transition_weights[current] = pattern['base_weight'] * random.random()
# Step 4: Determine the highest-weighted behavior
try:
selected_behavior = max(transition_weights.items(), key=lambda x: x[1])[0]
return selected_behavior
except Exception as e:
print(f"Error selecting behavior from weights: {e}")
raise e
def get_current_behavior(self):
"""
Returns the current behavior.
Returns:
Behavior: The current behavior instance.
"""
return self.current_behavior
def get_behavior_state(self):
"""
Gets the persistent state of the behavior system.
"""
return {
"current_behavior": self.current_behavior.name if self.current_behavior else None,
**({"locked_until": self.locked_until, "locked_by": self.locked_by}
if self.is_locked() else {})
}
def set_behavior_state(self, state):
"""
Sets the state of the behavior system.
"""
if not state:
return
# Set lock state first if present
if "locked_until" in state and "locked_by" in state:
self.locked_until = state["locked_until"]
self.locked_by = state["locked_by"]
else:
self.locked_until = 0
self.locked_by = None
# Change to specified behavior if provided
if "current_behavior" in state and state["current_behavior"] in self.behaviors:
self.change_behavior(state["current_behavior"])
else:
self.change_behavior("idle") | 412 | 0.978478 | 1 | 0.978478 | game-dev | MEDIA | 0.499301 | game-dev,ml-ai | 0.956852 | 1 | 0.956852 |
RTS-SYSU/Timing-Analysis-Multicores | 4,617 | RTSS_EXPERIMENT/Fig45_46_papa/papa_Our/7/sw/airborne/autopilot/pid.c | /*
$Id: pid.c,v 1.2 2011-01-21 11:52:44 moellmer Exp $
Copyright (C) 2003 Pascal Brisset, Antoine Drouin
This file is part of paparazzi.
paparazzi 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, or (at your option)
any later version.
paparazzi 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 paparazzi; see the file COPYING. If not, write to
the Free Software Foundation, 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
/** \file pid.c
\brief PID controllers (roll, pitch, climb, altitude, course).
*/
//#include <stdlib.h>
#include <math.h>
#include "pid.h"
#include "autopilot.h"
#include "infrared.h"
#include "estimator.h"
#include "nav.h"
float desired_roll = 0.;
float desired_pitch = 0.;
int16_t desired_gaz, desired_aileron, desired_elevator;
float roll_pgain = ROLL_PGAIN;
float pitch_pgain = PITCH_PGAIN;
float pitch_of_roll = PITCH_OF_ROLL;
float pitch_of_vz_pgain = CLIMB_PITCH_OF_VZ_PGAIN;
float pitch_of_vz = 0.;
/** \brief Computes ::desired_aileron and ::desired_elevator from attitude estimation and expected attitude. */
void roll_pitch_pid_run( void )
{
for(int i=0;i<1;i++){
float err = estimator_phi - desired_roll;
desired_aileron = TRIM_PPRZ( roll_pgain * err );
if ( pitch_of_roll < 0. )
pitch_of_roll = 0.;
err = -( estimator_theta - desired_pitch - pitch_of_roll * fabs(
estimator_phi ) );
desired_elevator = TRIM_PPRZ( pitch_pgain * err );
}
}
float course_pgain = COURSE_PGAIN;
float desired_course = 0.;
float max_roll = MAX_ROLL;
void course_pid_run( void )
{
float err = estimator_hspeed_dir - desired_course;
//NORM_RAD_ANGLE(err);
_Pragma( "loopbound min 0 max 1" )
while ( err > M_PI ) err -= 2 * M_PI;
_Pragma( "loopbound min 0 max 1" )
while ( err < -M_PI ) err += 2 * M_PI;
nav_desired_roll = course_pgain * err; // * fspeed / AIR_SPEED;
if ( nav_desired_roll > max_roll )
nav_desired_roll = max_roll;
else
if ( nav_desired_roll < -max_roll )
nav_desired_roll = -max_roll;
}
const float climb_pgain = CLIMB_PGAIN;
const float climb_igain = CLIMB_IGAIN;
float desired_climb = 0., pre_climb = 0.;
static const float level_gaz = CLIMB_LEVEL_GAZ;
float climb_sum_err = 0;
float climb_pitch_pgain = CLIMB_PITCH_PGAIN;
float climb_pitch_igain = CLIMB_PITCH_IGAIN;
float climb_pitch_sum_err = 0.;
float max_pitch = MAX_PITCH;
float min_pitch = MIN_PITCH;
#define MAX_CLIMB_SUM_ERR 100
#define MAX_PITCH_CLIMB_SUM_ERR 100
/** \brief Computes desired_gaz and desired_pitch from desired_climb */
void climb_pid_run ( void )
{
for(int i=0;i<1;i++){
float err = estimator_z_dot - desired_climb;
float fgaz;
if ( auto_pitch ) { /* gaz constant */
desired_gaz = nav_desired_gaz;
desired_pitch = climb_pitch_pgain * ( err + climb_pitch_igain *
climb_pitch_sum_err );
if ( desired_pitch > max_pitch )
desired_pitch = max_pitch;
if ( desired_pitch < min_pitch )
desired_pitch = min_pitch;
climb_pitch_sum_err += err;
if ( climb_pitch_sum_err > MAX_PITCH_CLIMB_SUM_ERR )
climb_pitch_sum_err = MAX_PITCH_CLIMB_SUM_ERR;
if ( climb_pitch_sum_err < - MAX_PITCH_CLIMB_SUM_ERR )
climb_pitch_sum_err = - MAX_PITCH_CLIMB_SUM_ERR;
} else { /* pitch almost constant */
/* pitch offset for climb */
pitch_of_vz = ( desired_climb > 0 ) ? desired_climb * pitch_of_vz_pgain : 0.;
fgaz = climb_pgain * ( err + climb_igain * climb_sum_err ) + CLIMB_LEVEL_GAZ +
CLIMB_GAZ_OF_CLIMB * desired_climb;
climb_sum_err += err;
if ( climb_sum_err > MAX_CLIMB_SUM_ERR ) climb_sum_err = MAX_CLIMB_SUM_ERR;
if ( climb_sum_err < - MAX_CLIMB_SUM_ERR ) climb_sum_err = - MAX_CLIMB_SUM_ERR;
desired_gaz = TRIM_UPPRZ( fgaz * MAX_PPRZ );
desired_pitch = nav_pitch + pitch_of_vz;
}
}
}
float altitude_pgain = ALTITUDE_PGAIN;
void altitude_pid_run( void )
{
float err = estimator_z - desired_altitude;
desired_climb = pre_climb + altitude_pgain * err;
if ( desired_climb < -CLIMB_MAX ) desired_climb = -CLIMB_MAX;
if ( desired_climb > CLIMB_MAX ) desired_climb = CLIMB_MAX;
}
| 412 | 0.561246 | 1 | 0.561246 | game-dev | MEDIA | 0.628944 | game-dev | 0.903963 | 1 | 0.903963 |
doyubkim/fluid-engine-dev | 3,011 | src/jet/fdm_mgpcg_solver3.cpp | // Copyright (c) 2018 Doyub Kim
//
// I am making my contributions/submissions to this project solely in my
// personal capacity and am not conveying any rights to any intellectual
// property of any third parties.
#include <pch.h>
#include <jet/cg.h>
#include <jet/fdm_mgpcg_solver3.h>
#include <jet/mg.h>
using namespace jet;
void FdmMgpcgSolver3::Preconditioner::build(FdmMgLinearSystem3* system_,
MgParameters<FdmBlas3> mgParams_) {
system = system_;
mgParams = mgParams_;
}
void FdmMgpcgSolver3::Preconditioner::solve(const FdmVector3& b,
FdmVector3* x) {
// Copy dimension
FdmMgVector3 mgX = system->x;
FdmMgVector3 mgB = system->x;
FdmMgVector3 mgBuffer = system->x;
// Copy input to the top
mgX.levels.front().set(*x);
mgB.levels.front().set(b);
mgVCycle(system->A, mgParams, &mgX, &mgB, &mgBuffer);
// Copy result to the output
x->set(mgX.levels.front());
}
//
FdmMgpcgSolver3::FdmMgpcgSolver3(
unsigned int numberOfCgIter, size_t maxNumberOfLevels,
unsigned int numberOfRestrictionIter, unsigned int numberOfCorrectionIter,
unsigned int numberOfCoarsestIter, unsigned int numberOfFinalIter,
double maxTolerance, double sorFactor, bool useRedBlackOrdering)
: FdmMgSolver3(maxNumberOfLevels, numberOfRestrictionIter,
numberOfCorrectionIter, numberOfCoarsestIter,
numberOfFinalIter, maxTolerance, sorFactor,
useRedBlackOrdering),
_maxNumberOfIterations(numberOfCgIter),
_lastNumberOfIterations(0),
_tolerance(maxTolerance),
_lastResidualNorm(kMaxD) {}
bool FdmMgpcgSolver3::solve(FdmMgLinearSystem3* system) {
Size3 size = system->A.levels.front().size();
_r.resize(size);
_d.resize(size);
_q.resize(size);
_s.resize(size);
system->x.levels.front().set(0.0);
_r.set(0.0);
_d.set(0.0);
_q.set(0.0);
_s.set(0.0);
_precond.build(system, params());
pcg<FdmBlas3, Preconditioner>(system->A.levels.front(),
system->b.levels.front(),
_maxNumberOfIterations, _tolerance, &_precond,
&system->x.levels.front(), &_r, &_d, &_q, &_s,
&_lastNumberOfIterations, &_lastResidualNorm);
JET_INFO << "Residual after solving MGPCG: " << _lastResidualNorm
<< " Number of MGPCG iterations: " << _lastNumberOfIterations;
return _lastResidualNorm <= _tolerance ||
_lastNumberOfIterations < _maxNumberOfIterations;
}
unsigned int FdmMgpcgSolver3::maxNumberOfIterations() const {
return _maxNumberOfIterations;
}
unsigned int FdmMgpcgSolver3::lastNumberOfIterations() const {
return _lastNumberOfIterations;
}
double FdmMgpcgSolver3::tolerance() const { return _tolerance; }
double FdmMgpcgSolver3::lastResidual() const { return _lastResidualNorm; }
| 412 | 0.85896 | 1 | 0.85896 | game-dev | MEDIA | 0.40252 | game-dev | 0.8746 | 1 | 0.8746 |
japsuu/KorpiEngine | 2,057 | src/Core/UI/DearImGui/EntityEditor.cs | #if KORPI_TOOLS
using ImGuiNET;
using KorpiEngine.Entities;
using KorpiEngine.InputManagement;
using KorpiEngine.Mathematics;
using KorpiEngine.Rendering;
namespace KorpiEngine.UI.DearImGui;
public class EntityEditor() : ImGuiWindow(true)
{
private Entity? _target;
public override string Title => "Entity Editor";
protected override void PreUpdate()
{
if (!Input.GetMouseButtonDown(MouseButton.Left) || GUI.WantCaptureMouse)
return;
Vector2 mousePos = Input.MousePosition;
Vector2 mouseUV = new Vector2(mousePos.X / Graphics.ViewportResolution.X, mousePos.Y / Graphics.ViewportResolution.Y);
GBuffer? gBuffer = Camera.LastRenderedCamera?.GBuffer;
if (gBuffer == null)
return;
int instanceID = gBuffer.GetObjectIDAt(mouseUV);
if (instanceID == 0)
{
SetTarget(null);
return;
}
Entity? e = EngineObject.FindObjectByID<Entity>(instanceID);
SetTarget(e);
}
public void SetTarget(Entity? entity)
{
_target = entity;
}
protected override void DrawContent()
{
if (_target == null || _target.IsDestroyed)
{
ImGui.Text("No entity selected.");
return;
}
ImGui.Text($"Entity: {_target.Name}");
ImGui.Separator();
DrawEntityHierarchy(_target);
}
private static void DrawEntityHierarchy(Entity entity)
{
// Inline destroy button
if (ImGui.Button("Destroy"))
{
entity.Destroy();
return;
}
ImGui.SameLine();
// Transform hierarchy
if (entity.HasChildren)
{
if (!ImGui.TreeNode(entity.Name))
return;
foreach (Entity child in entity.Children)
DrawEntityHierarchy(child);
ImGui.TreePop();
}
else
{
ImGui.Text(entity.Name);
}
}
}
#endif | 412 | 0.823548 | 1 | 0.823548 | game-dev | MEDIA | 0.775568 | game-dev | 0.953295 | 1 | 0.953295 |
ImLegiitXD/Ambient | 1,435 | src/main/java/net/minecraft/block/BlockBreakable.java | package net.minecraft.block;
import net.minecraft.block.material.MapColor;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Blocks;
import net.minecraft.util.BlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraft.world.IBlockAccess;
public class BlockBreakable extends Block {
private final boolean ignoreSimilarity;
protected BlockBreakable(Material materialIn, boolean ignoreSimilarityIn) {
this(materialIn, ignoreSimilarityIn, materialIn.getMaterialMapColor());
}
protected BlockBreakable(Material p_i46393_1_, boolean p_i46393_2_, MapColor p_i46393_3_) {
super(p_i46393_1_, p_i46393_3_);
this.ignoreSimilarity = p_i46393_2_;
}
public boolean isOpaqueCube() {
return false;
}
public boolean shouldSideBeRendered(IBlockAccess worldIn, BlockPos pos, EnumFacing side) {
IBlockState iblockstate = worldIn.getBlockState(pos);
Block block = iblockstate.getBlock();
if (this == Blocks.glass || this == Blocks.stained_glass) {
if (worldIn.getBlockState(pos.offset(side.getOpposite())) != iblockstate) {
return true;
}
if (block == this) {
return false;
}
}
return (this.ignoreSimilarity || block != this) && super.shouldSideBeRendered(worldIn, pos, side);
}
}
| 412 | 0.665341 | 1 | 0.665341 | game-dev | MEDIA | 0.988143 | game-dev | 0.813824 | 1 | 0.813824 |
sjtug/sjtulib-latex-talk | 1,394 | support/figures/mindmap.tex | \documentclass[tikz]{standalone}
\usetikzlibrary{mindmap}
% !TIKZEDT BOUNDINGBOX = -3 -3 8 5
\begin{document}
\begin{tikzpicture}[mindmap,concept color=cprimary,scale=0.6,every node/.style={scale=0.6},text=white]
\definecolor{cprimary}{RGB}{0,64,152} %problue
\definecolor{csecondary}{RGB}{51,141,39} %lightgreen
\definecolor{ctertiary}{RGB}{0,81,78} %lightgray
\node [concept] {Stage-Based Strategy for Scheduling Jobs Problem with Max-Min Fairness}
child[concept color=ctertiary,grow=150] {
node[concept] {Algorithm Design}
child[concept,grow=140,concept color=csecondary] {node[concept] {Simple Example}}
child[concept,grow=180,concept color=csecondary] {node[concept] {Stage Based}}
child[concept,grow=220,concept color=csecondary] {node[concept] {Max-Min Fairness}}
}
child[concept color=ctertiary,grow=210] {
node[concept] {NP-Completeness}
child[concept,grow=160,concept color=csecondary] {node[concept] {3-SAT}}
child[concept,grow=200,concept color=csecondary] {node[concept] {Reduction}}
}
child[concept color=ctertiary,grow=0] {
node[concept] {Algorithm \& Test}
child[concept,grow=40,concept color=csecondary] {node[concept] {Floyd-Warshall}}
child[concept,grow=0,concept color=csecondary] {node[concept] {Without Max-min}}
child[concept,grow=-40,concept color=csecondary] {node[concept] {Max-min Iteration}}
};
\end{tikzpicture}
\end{document} | 412 | 0.750974 | 1 | 0.750974 | game-dev | MEDIA | 0.197131 | game-dev | 0.559013 | 1 | 0.559013 |
fulpstation/fulpstation | 12,730 | code/modules/religion/sparring/sparring_datum.dm | /datum/sparring_match
///the chaplain. it isn't actually a chaplain all the time, but in the cases where the chaplain is needed this will always be them.
var/mob/living/carbon/human/chaplain
///the other fighter
var/mob/living/carbon/human/opponent
///what weapons will be allowed during the sparring match
var/weapons_condition
///area instance the participants must stay in
var/area/arena_condition
///what stakes the fight will have
var/stakes_condition
///cheats from the chaplain
var/chaplain_violations_allowed = 2
///cheats from the non-chaplain
var/opponent_violations_allowed = 2
///outside interventions that ruin the match
var/flubs = 2
/datum/sparring_match/New(weapons_condition, arena_condition, stakes_condition, mob/living/carbon/human/chaplain, mob/living/carbon/human/opponent)
. = ..()
src.weapons_condition = weapons_condition
src.arena_condition = arena_condition
src.stakes_condition = stakes_condition
src.chaplain = chaplain
src.opponent = opponent
ADD_TRAIT(chaplain, TRAIT_SPARRING, TRAIT_GENERIC)
ADD_TRAIT(opponent, TRAIT_SPARRING, TRAIT_GENERIC)
hook_signals(chaplain)
hook_signals(opponent)
chaplain.add_filter("sparring_outline", 9, list("type" = "outline", "color" = "#e02200"))
opponent.add_filter("sparring_outline", 9, list("type" = "outline", "color" = "#004ee0"))
/datum/sparring_match/proc/hook_signals(mob/living/carbon/human/sparring)
//weapon conditions
if(weapons_condition < CONDITION_ANY_WEAPON)
RegisterSignal(sparring, COMSIG_MOB_FIRED_GUN, PROC_REF(gun_violation))
RegisterSignal(sparring, COMSIG_MOB_GRENADE_ARMED, PROC_REF(grenade_violation))
if(weapons_condition <= CONDITION_CEREMONIAL_ONLY)
RegisterSignal(sparring, COMSIG_ATOM_ATTACKBY, PROC_REF(melee_violation))
//arena conditions
RegisterSignal(sparring, COMSIG_MOVABLE_MOVED, PROC_REF(arena_violation))
//severe violations (insta violation win for other party) conditions
RegisterSignal(sparring, COMSIG_MOVABLE_POST_TELEPORT, PROC_REF(teleport_violation))
//win conditions
RegisterSignal(sparring, COMSIG_MOB_STATCHANGE, PROC_REF(check_for_victory))
//flub conditions
RegisterSignal(sparring, COMSIG_ATOM_ATTACKBY, PROC_REF(outsider_interference), override = TRUE)
RegisterSignal(sparring, COMSIG_ATOM_HULK_ATTACK, PROC_REF(hulk_interference), override = TRUE)
RegisterSignal(sparring, COMSIG_ATOM_ATTACK_HAND, PROC_REF(hand_interference), override = TRUE)
RegisterSignal(sparring, COMSIG_ATOM_ATTACK_PAW, PROC_REF(paw_interference), override = TRUE)
RegisterSignal(sparring, COMSIG_ATOM_HITBY, PROC_REF(thrown_interference), override = TRUE)
RegisterSignal(sparring, COMSIG_ATOM_BULLET_ACT, PROC_REF(projectile_interference), override = TRUE)
//severe flubs (insta match ender, no winners) conditions
RegisterSignal(sparring, COMSIG_LIVING_DEATH, PROC_REF(death_flub))
RegisterSignal(sparring, COMSIG_QDELETING, PROC_REF(deletion_flub))
/datum/sparring_match/proc/unhook_signals(mob/living/carbon/human/sparring)
if(!sparring)
return
UnregisterSignal(sparring, list(
COMSIG_MOB_FIRED_GUN,
COMSIG_MOB_GRENADE_ARMED,
COMSIG_MOVABLE_MOVED,
COMSIG_MOVABLE_POST_TELEPORT,
COMSIG_MOB_STATCHANGE,
COMSIG_ATOM_ATTACKBY,
COMSIG_ATOM_HULK_ATTACK,
COMSIG_ATOM_ATTACK_HAND,
COMSIG_ATOM_ATTACK_PAW,
COMSIG_ATOM_HITBY,
COMSIG_ATOM_BULLET_ACT,
COMSIG_LIVING_DEATH,
COMSIG_QDELETING,
))
///someone is changing health state, end the fight in crit
/datum/sparring_match/proc/check_for_victory(datum/participant, new_stat)
SIGNAL_HANDLER
//death needs to be a flub, conscious means they haven't won
if(new_stat == CONSCIOUS || new_stat == DEAD)
return
if(participant == chaplain)
end_match(opponent, chaplain)
else
end_match(chaplain, opponent)
// SIGNALS THAT ARE FOR BEING ATTACKED FIRST (GUILTY)
/datum/sparring_match/proc/outsider_interference(datum/source, obj/item/I, mob/attacker)
SIGNAL_HANDLER
if(attacker == chaplain || attacker == opponent)
return
INVOKE_ASYNC(src, PROC_REF(flub), attacker)
/datum/sparring_match/proc/hulk_interference(datum/source, mob/attacker)
SIGNAL_HANDLER
if((attacker == chaplain || attacker == opponent))
// fist fighting a hulk is so dumb. i can't fathom why you would do this.
return
INVOKE_ASYNC(src, PROC_REF(flub), attacker)
/datum/sparring_match/proc/hand_interference(datum/source, mob/living/attacker)
SIGNAL_HANDLER
if(attacker == chaplain || attacker == opponent)
//you can pretty much always use fists as a participant
return
INVOKE_ASYNC(src, PROC_REF(flub), attacker)
/datum/sparring_match/proc/paw_interference(datum/source, mob/living/attacker)
SIGNAL_HANDLER
if(attacker == chaplain || attacker == opponent)
//you can pretty much always use paws as a participant
return
INVOKE_ASYNC(src, PROC_REF(flub), attacker)
/datum/sparring_match/proc/thrown_interference(datum/source, atom/movable/thrown_movable, skipcatch = FALSE, hitpush = TRUE, blocked = FALSE, datum/thrownthing/throwingdatum)
SIGNAL_HANDLER
if(isitem(thrown_movable))
var/mob/living/honorbound = source
var/obj/item/thrown_item = thrown_movable
var/mob/thrown_by = thrown_item.thrownby?.resolve()
if(thrown_item.throwforce < honorbound.health && ishuman(thrown_by))
INVOKE_ASYNC(src, PROC_REF(flub), thrown_by)
/datum/sparring_match/proc/projectile_interference(datum/participant, obj/projectile/proj)
SIGNAL_HANDLER
if(proj.firer == chaplain || proj.firer == opponent)
//oh, well that's allowed. or maybe it isn't. doesn't matter because firing the gun will trigger a violation, so no additional violation needed
return
var/mob/living/interfering
if(isliving(proj.firer))
interfering = proj.firer
INVOKE_ASYNC(src, PROC_REF(flub), interfering)
///someone randomly fucking died
/datum/sparring_match/proc/death_flub(datum/deceased)
SIGNAL_HANDLER
flubbed_match()
///someone randomly fucking deleted
/datum/sparring_match/proc/deletion_flub(datum/qdeleting)
SIGNAL_HANDLER
flubbed_match()
///someone used a gun
/datum/sparring_match/proc/gun_violation(mob/offender, obj/item/gun/gun_fired, target, params, zone_override, list/bonus_spread_values)
SIGNAL_HANDLER
violation(offender, "using guns")
///someone used a grenade
/datum/sparring_match/proc/grenade_violation(datum/offender)
SIGNAL_HANDLER
violation(offender, "using grenades")
///someone used melee weapons
/datum/sparring_match/proc/melee_violation(datum/offender, obj/item/thing, mob/user, params)
SIGNAL_HANDLER
if(weapons_condition != CONDITION_CEREMONIAL_ONLY)
violation(offender, "using melee weapons")
if(istype(thing, /obj/item/ceremonial_blade))
return
violation(offender, "using non ceremonial weapons")
/datum/sparring_match/proc/teleport_violation(datum/offender)
SIGNAL_HANDLER
if(offender == chaplain)
end_match(opponent, chaplain, violation_victory = TRUE)
else
end_match(chaplain, opponent, violation_victory = TRUE)
///someone tried to leave
/datum/sparring_match/proc/arena_violation(atom/movable/mover, atom/oldloc, direction)
SIGNAL_HANDLER
var/area/inhabited_area = get_area(mover)
if(inhabited_area == arena_condition)
return //still in the ring!! :)
violation(mover, "leaving the arena")
var/atom/throw_target = get_edge_target_turf(mover, REVERSE_DIR(direction))
mover.throw_at(throw_target, 6, 4)
/datum/sparring_match/proc/violation(mob/living/carbon/human/offender, reason)
SIGNAL_HANDLER
to_chat(offender, span_userdanger("Violation! No [reason]!"))
if(offender == chaplain)
chaplain_violations_allowed--
if(!chaplain_violations_allowed)
end_match(opponent, chaplain, violation_victory = TRUE)
else
opponent_violations_allowed--
if(!opponent_violations_allowed)
end_match(chaplain, opponent, violation_victory = TRUE)
/datum/sparring_match/proc/flub(mob/living/interfering)
if(interfering)
var/list/possible_punishments = list(PUNISHMENT_OMEN, PUNISHMENT_LIGHTNING)
if(ishuman(interfering))
possible_punishments += PUNISHMENT_BRAND
switch(pick(possible_punishments))
if(PUNISHMENT_OMEN)
to_chat(interfering, span_warning("You get a bad feeling... for interfering with [chaplain]'s sparring match..."))
interfering.AddComponent(/datum/component/omen)
if(PUNISHMENT_LIGHTNING)
to_chat(interfering, span_warning("[GLOB.deity] has punished you for interfering with [chaplain]'s sparring match!"))
lightningbolt(interfering)
if(PUNISHMENT_BRAND)
var/mob/living/carbon/human/branded = interfering
to_chat(interfering, span_warning("[GLOB.deity] brands your flesh for interfering with [chaplain]'s sparring match!!"))
var/obj/item/bodypart/branded_limb = pick(branded.bodyparts)
branded_limb.force_wound_upwards(/datum/wound/burn/flesh/severe/brand, wound_source = "divine intervention")
branded.emote("scream")
flubs--
if(!flubs) //too many interferences
flubbed_match()
///this match was interfered on, nobody wins or loses anything, just end
/datum/sparring_match/proc/flubbed_match()
cleanup_sparring_match()
if(chaplain) //flubing means we don't know who is still standing
to_chat(chaplain, span_bolddanger("The match was flub'd! No winners, no losers. You may restart the match with another contract."))
if(opponent)
to_chat(opponent, span_bolddanger("The match was flub'd! No winners, no losers."))
qdel(src)
///helper to remove all the effects after a match ends
/datum/sparring_match/proc/cleanup_sparring_match()
REMOVE_TRAIT(chaplain, TRAIT_SPARRING, TRAIT_GENERIC)
REMOVE_TRAIT(opponent, TRAIT_SPARRING, TRAIT_GENERIC)
unhook_signals(chaplain)
unhook_signals(opponent)
chaplain.remove_filter("sparring_outline")
opponent.remove_filter("sparring_outline")
/datum/sparring_match/proc/end_match(mob/living/carbon/human/winner, mob/living/carbon/human/loser, violation_victory = FALSE)
cleanup_sparring_match()
to_chat(chaplain, span_bolddanger("[violation_victory ? "[loser] DISQUALIFIED!" : ""] [winner] HAS WON!"))
to_chat(opponent, span_bolddanger("[violation_victory ? "[loser] DISQUALIFIED!" : ""] [winner] HAS WON!"))
win(winner, loser, violation_victory)
lose(loser, winner)
if(stakes_condition != STAKES_YOUR_SOUL)
var/healing_message = "You may want to heal up the loser now."
if(winner == chaplain)
healing_message += " Your bible will heal the loser for awhile."
to_chat(winner, span_notice(healing_message))
qdel(src)
///most of the effects are handled on `lose()` instead.
/datum/sparring_match/proc/win(mob/living/carbon/human/winner, mob/living/carbon/human/loser, violation_victory)
switch(stakes_condition)
if(STAKES_HOLY_MATCH)
if(winner == chaplain)
if(violation_victory)
to_chat(winner, span_warning("[GLOB.deity] is not entertained from a matched decided by violations. No favor awarded..."))
else
to_chat(winner, span_nicegreen("You've won favor with [GLOB.deity]!"))
var/datum/religion_sect/spar/sect = GLOB.religious_sect
sect.adjust_favor(1, winner)
sect.past_opponents += WEAKREF(loser)
if(STAKES_MONEY_MATCH)
to_chat(winner, span_nicegreen("You've won all of [loser]'s money!"))
if(STAKES_YOUR_SOUL)
to_chat(winner, span_nicegreen("You've won [loser]'s SOUL!"))
/datum/sparring_match/proc/lose(mob/living/carbon/human/loser, mob/living/carbon/human/winner)
if(!loser) //shit happened?
return
switch(stakes_condition)
if(STAKES_HOLY_MATCH)
if(loser == chaplain)
var/datum/religion_sect/spar/sect = GLOB.religious_sect
sect.matches_lost++
if(sect.matches_lost < 3)
to_chat(loser, span_userdanger("[GLOB.deity] is angry you lost in their name!"))
return
to_chat(loser, span_userdanger("[GLOB.deity] is enraged by your lackluster sparring record!"))
lightningbolt(loser)
loser.add_mood_event("sparring", /datum/mood_event/banished)
loser.mind.holy_role = NONE
to_chat(loser, span_userdanger("You have been excommunicated! You are no longer holy!"))
if(STAKES_MONEY_MATCH)
to_chat(loser, span_userdanger("You've lost all your money to [winner]!"))
var/datum/bank_account/loser_account = loser.get_bank_account()
var/datum/bank_account/winner_account = winner.get_bank_account()
if(!loser_account || !winner_account)//the winner is pretty owned in this case but whatever shoulda read the fine print of the contract
return
winner_account.transfer_money(loser_account, loser_account.account_balance, "Bet: Sparring")
if(STAKES_YOUR_SOUL)
var/turf/shard_turf = get_turf(loser)
if(!shard_turf)
return
to_chat(loser, span_userdanger("You've lost ownership over your soul to [winner]!"))
var/obj/item/soulstone/anybody/chaplain/sparring/shard = new(shard_turf)
INVOKE_ASYNC(shard, TYPE_PROC_REF(/obj/item/soulstone, capture_soul), loser, winner, forced = TRUE)
| 412 | 0.795382 | 1 | 0.795382 | game-dev | MEDIA | 0.96365 | game-dev | 0.890454 | 1 | 0.890454 |
ACGaming/UniversalTweaks | 3,038 | src/main/java/mod/acgaming/universaltweaks/tweaks/entities/trading/UTVillagerProfessionRestriction.java | package mod.acgaming.universaltweaks.tweaks.entities.trading;
import java.util.HashMap;
import java.util.Map;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.common.registry.ForgeRegistries;
import mod.acgaming.universaltweaks.UniversalTweaks;
import mod.acgaming.universaltweaks.config.UTConfigTweaks;
public class UTVillagerProfessionRestriction
{
public static final Map<String, Entry> VILLAGER_PROFESSION_MAP = new HashMap<>();
public static void initBiomeRestrictions()
{
VILLAGER_PROFESSION_MAP.clear();
for (String entry : UTConfigTweaks.ENTITIES.utVillagerProfessionBiomeRestriction)
{
try
{
String[] parts = entry.split(";");
if (parts.length != 2)
{
UniversalTweaks.LOGGER.warn("Invalid villager profession blacklist entry: {}", entry);
continue;
}
String mode = parts[0].trim().toLowerCase();
if (!mode.equals("whitelist") && !mode.equals("blacklist"))
{
UniversalTweaks.LOGGER.warn("Invalid mode in villager profession blacklist entry (must be 'whitelist' or 'blacklist'): {}", entry);
continue;
}
String[] biomeProfParts = parts[1].split("=");
if (biomeProfParts.length != 2)
{
UniversalTweaks.LOGGER.warn("Invalid format in villager profession blacklist entry: {}", entry);
continue;
}
String biome = biomeProfParts[0].trim();
String[] professions = biomeProfParts[1].split(",");
// Validate biome
if (ForgeRegistries.BIOMES.getValue(new ResourceLocation(biome)) == null)
{
UniversalTweaks.LOGGER.warn("Invalid biome in villager profession blacklist entry: {}", biome);
continue;
}
// Validate professions
for (String prof : professions)
{
prof = prof.trim();
if (ForgeRegistries.VILLAGER_PROFESSIONS.getValue(new ResourceLocation(prof)) == null)
{
UniversalTweaks.LOGGER.warn("Invalid profession in villager profession blacklist entry: {}", prof);
}
}
VILLAGER_PROFESSION_MAP.put(biome, new Entry(mode, professions));
}
catch (Exception e)
{
UniversalTweaks.LOGGER.error("Error parsing villager profession blacklist entry: {}", entry, e);
}
}
}
public static class Entry
{
public final String mode;
public final String[] professions;
public Entry(String mode, String[] professions)
{
this.mode = mode;
this.professions = professions;
}
}
}
| 412 | 0.564703 | 1 | 0.564703 | game-dev | MEDIA | 0.940709 | game-dev | 0.700798 | 1 | 0.700798 |
freeminer/freeminer | 9,294 | src/server/serveractiveobject.h | // Luanti
// SPDX-License-Identifier: LGPL-2.1-or-later
// Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
#pragma once
#include <cassert>
#include <unordered_set>
#include <optional>
#include "irrlichttypes_bloated.h"
#include "activeobject.h"
#include "itemgroup.h"
#include "util/container.h"
#include "threading/lock.h"
/*
Some planning
-------------
* Server environment adds an active object, which gets the id 1
* The active object list is scanned for each client once in a while,
and it finds out what objects have been added that are not known
by the client yet. This scan is initiated by the Server class and
the result ends up directly to the server.
* A network packet is created with the info and sent to the client.
* Environment converts objects to static data and static data to
objects, based on how close players are to them.
*/
class ServerEnvironment;
struct ItemStack;
struct ToolCapabilities;
struct ObjectProperties;
struct PlayerHPChangeReason;
class Inventory;
struct InventoryLocation;
class ServerActiveObject : public ActiveObject
, public shared_locker
{
// fm:
public:
float m_uptime_last = 0;
Queue<ActiveObjectMessage> & m_messages_out;
// ===
public:
/*
NOTE: m_env can be NULL, but step() isn't called if it is.
Prototypes are used that way.
*/
ServerActiveObject(ServerEnvironment *env, v3f pos);
virtual ~ServerActiveObject() = default;
virtual ActiveObjectType getSendType() const
{ return getType(); }
// Called after id has been set and has been inserted in environment
virtual void addedToEnvironment(u32 dtime_s){};
// Called before removing from environment
virtual void removingFromEnvironment(){};
// Safely mark the object for removal or deactivation
void markForRemoval();
void markForDeactivation();
/*
Some simple getters/setters
*/
v3f getBasePosition() const {
std::lock_guard<std::mutex> lock(m_base_position_mutex);
return m_base_position; }
void setBasePosition(v3f pos);
ServerEnvironment* getEnv(){ return m_env; }
/*
Some more dynamic interface
*/
virtual void setPos(const v3f &pos)
{ setBasePosition(pos); }
virtual void addPos(const v3f &added_pos)
{ setBasePosition(m_base_position + added_pos); }
// continuous: if true, object does not stop immediately at pos
virtual void moveTo(v3f pos, bool continuous)
{ setBasePosition(pos); }
// If object has moved less than this and data has not changed,
// saving to disk may be omitted
virtual float getMinimumSavedMovement();
virtual std::string getDescription(){return "SAO";}
/*
Step object in time.
Messages added to messages are sent to client over network.
send_recommended:
True at around 5-10 times a second, same for all objects.
This is used to let objects send most of the data at the
same time so that the data can be combined in a single
packet.
*/
virtual void step(float dtime, bool send_recommended){}
/*
The return value of this is passed to the client-side object
when it is created
*/
virtual std::string getClientInitializationData(u16 protocol_version) {return "";}
/*
The return value of this is passed to the server-side object
when it is created (converted from static to active - actually
the data is the static form)
*/
virtual void getStaticData(std::string *result) const
{
assert(isStaticAllowed());
*result = "";
}
/*
Return false in here to never save and instead remove object
on unload. getStaticData() will not be called in that case.
*/
virtual bool isStaticAllowed() const
{return true;}
/*
Return false here to never unload the object.
isStaticAllowed && shouldUnload -> unload when out of active block range
!isStaticAllowed && shouldUnload -> unload when block is unloaded
*/
virtual bool shouldUnload() const
{ return true; }
// Returns added tool wear
virtual u32 punch(v3f dir,
const ToolCapabilities *toolcap = nullptr,
ServerActiveObject *puncher = nullptr,
float time_from_last_punch = 1000000.0f,
u16 initial_wear = 0)
{ return 0; }
virtual void rightClick(ServerActiveObject *clicker)
{}
virtual void setHP(s32 hp, const PlayerHPChangeReason &reason)
{}
virtual u16 getHP() const
{ return 0; }
/// @brief Returns an unique ID for this object (persistent across unload, server restarts).
/// @note Because these strings are very short, copying them is not expensive.
virtual std::string getGUID() const = 0;
virtual void setArmorGroups(const ItemGroupList &armor_groups)
{}
virtual const ItemGroupList &getArmorGroups() const
{ static ItemGroupList rv; return rv; }
virtual void setAnimation(v2f frames, float frame_speed, float frame_blend, bool frame_loop)
{}
virtual void getAnimation(v2f *frames, float *frame_speed, float *frame_blend, bool *frame_loop)
{}
virtual void setAnimationSpeed(float frame_speed)
{}
virtual void setBoneOverride(const std::string &bone, const BoneOverride &props)
{}
virtual BoneOverride getBoneOverride(const std::string &bone)
{ BoneOverride props; return props; }
virtual const BoneOverrideMap &getBoneOverrides() const
{ static BoneOverrideMap rv; return rv; }
virtual const std::unordered_set<object_t> &getAttachmentChildIds() const
{ static std::unordered_set<object_t> rv; return rv; }
virtual ServerActiveObject *getParent() const { return nullptr; }
virtual ObjectProperties *accessObjectProperties()
{ return NULL; }
virtual void notifyObjectPropertiesModified()
{}
// Inventory and wielded item
virtual Inventory *getInventory() const
{ return NULL; }
virtual InventoryLocation getInventoryLocation() const;
virtual void setInventoryModified()
{}
virtual std::string getWieldList() const
{ return ""; }
virtual u16 getWieldIndex() const
{ return 0; }
virtual ItemStack getWieldedItem(ItemStack *selected,
ItemStack *hand = nullptr) const;
virtual bool setWieldedItem(const ItemStack &item);
inline void attachParticleSpawner(u32 id)
{
m_attached_particle_spawners.insert(id);
}
inline void detachParticleSpawner(u32 id)
{
m_attached_particle_spawners.erase(id);
}
std::string generateUpdateInfantCommand(u16 infant_id, u16 protocol_version);
void dumpAOMessagesToQueue(std::queue<ActiveObjectMessage> &queue);
/*
Number of players which know about this object. Object won't be
deleted until this is 0 to keep the id preserved for the right
object.
*/
std::atomic_ushort m_known_by_count {0};
/*
A getter that unifies the above to answer the question:
"Can the environment still interact with this object?"
*/
inline bool isGone() const
{ return m_pending_removal || m_pending_deactivation; }
inline bool isPendingRemoval() const
{ return m_pending_removal; }
/*
Whether the object's static data has been stored to a block
Note that `!isStaticAllowed() && m_static_exists` is a valid state
(though it usually doesn't persist long) and you need to be careful
about handling it.
*/
bool m_static_exists = false;
/*
The block from which the object was loaded from, and in which
a copy of the static data resides.
*/
v3s16 m_static_block = v3s16(1337,1337,1337);
// Names of players to whom the object is to be sent, not considering parents.
using Observers = std::optional<std::unordered_set<std::string>>;
Observers m_observers;
/// Invalidate final observer cache. This needs to be done whenever
/// the observers of this object or any of its ancestors may have changed.
void invalidateEffectiveObservers();
/// Cache `m_effective_observers` with the names of all observers,
/// also indirect observers (object attachment chain).
const Observers &getEffectiveObservers();
/// Force a recalculation of final observers (including all parents).
const Observers &recalculateEffectiveObservers();
/// Whether the object is sent to `player_name`
bool isEffectivelyObservedBy(const std::string &player_name);
protected:
// Cached intersection of m_observers of this object and all its parents.
std::optional<Observers> m_effective_observers;
virtual void onMarkedForDeactivation() {}
virtual void onMarkedForRemoval() {}
ServerEnvironment *m_env;
std::unordered_set<u32> m_attached_particle_spawners;
/*
Same purpose as m_pending_removal but for deactivation.
deactvation = save static data in block, remove active object
If this is set alongside with m_pending_removal, removal takes
priority.
Note: Do not assign this directly, use markForDeactivation() instead.
*/
std::atomic_bool m_pending_deactivation = false;
/*
- Whether this object is to be removed when nobody knows about
it anymore.
- Removal is delayed to preserve the id for the time during which
it could be confused to some other object by some client.
- This is usually set to true by the step() method when the object wants
to be deleted but can be set by anything else too.
Note: Do not assign this directly, use markForRemoval() instead.
*/
std::atomic_bool m_pending_removal = false;
/*
Queue of messages to be sent to the client
*/
//std::queue<ActiveObjectMessage> m_messages_out;
private:
v3f m_base_position; // setBasePosition updates index and MUST be called
mutable std::mutex m_base_position_mutex;
};
using ServerActiveObjectPtr = std::shared_ptr<ServerActiveObject>;
| 412 | 0.92495 | 1 | 0.92495 | game-dev | MEDIA | 0.665352 | game-dev | 0.744182 | 1 | 0.744182 |
gitclonparis/ninpai | 3,660 | BidAskLowHigh.cs | #region Using declarations
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Xml.Serialization;
using NinjaTrader.Cbi;
using NinjaTrader.Gui;
using NinjaTrader.Gui.Chart;
using NinjaTrader.Gui.SuperDom;
using NinjaTrader.Gui.Tools;
using NinjaTrader.Data;
using NinjaTrader.NinjaScript;
using NinjaTrader.Core.FloatingPoint;
using NinjaTrader.NinjaScript.DrawingTools;
#endregion
namespace NinjaTrader.NinjaScript.Indicators.ninpai
{
public class BidAskLowHigh : Indicator
{
private NinjaTrader.NinjaScript.BarsTypes.VolumetricBarsType barsType;
protected override void OnStateChange()
{
if (State == State.SetDefaults)
{
Description = @"Indicator based on Order Flow Volumetric Bars";
Name = "BidAskLowHigh";
Calculate = Calculate.OnBarClose;
IsOverlay = true;
DisplayInDataBox = true;
DrawOnPricePanel = true;
DrawHorizontalGridLines = true;
DrawVerticalGridLines = true;
PaintPriceMarkers = true;
ScaleJustification = NinjaTrader.Gui.Chart.ScaleJustification.Right;
}
else if (State == State.DataLoaded)
{
barsType = Bars.BarsSeries.BarsType as NinjaTrader.NinjaScript.BarsTypes.VolumetricBarsType;
if (barsType == null)
throw new Exception("This indicator requires Volumetric Bars.");
}
}
protected override void OnBarUpdate()
{
if (CurrentBar < 3) return;
// Check for UP condition
if (Close[0] > Open[0]) // Green bar
{
double lowPrice = Low[0];
double level1 = barsType.Volumes[0].GetAskVolumeForPrice(lowPrice);
double level2 = barsType.Volumes[0].GetAskVolumeForPrice(lowPrice + (1 * TickSize));
double level3 = barsType.Volumes[0].GetAskVolumeForPrice(lowPrice + (2 * TickSize));
if (level1 < level2 && level2 < level3)
{
Draw.ArrowUp(this, "UpArrow" + CurrentBar, true, 0, Low[0] - (2 * TickSize), Brushes.LimeGreen);
}
}
// TODO: Implement DOWN condition
}
}
}
#region NinjaScript generated code. Neither change nor remove.
namespace NinjaTrader.NinjaScript.Indicators
{
public partial class Indicator : NinjaTrader.Gui.NinjaScript.IndicatorRenderBase
{
private ninpai.BidAskLowHigh[] cacheBidAskLowHigh;
public ninpai.BidAskLowHigh BidAskLowHigh()
{
return BidAskLowHigh(Input);
}
public ninpai.BidAskLowHigh BidAskLowHigh(ISeries<double> input)
{
if (cacheBidAskLowHigh != null)
for (int idx = 0; idx < cacheBidAskLowHigh.Length; idx++)
if (cacheBidAskLowHigh[idx] != null && cacheBidAskLowHigh[idx].EqualsInput(input))
return cacheBidAskLowHigh[idx];
return CacheIndicator<ninpai.BidAskLowHigh>(new ninpai.BidAskLowHigh(), input, ref cacheBidAskLowHigh);
}
}
}
namespace NinjaTrader.NinjaScript.MarketAnalyzerColumns
{
public partial class MarketAnalyzerColumn : MarketAnalyzerColumnBase
{
public Indicators.ninpai.BidAskLowHigh BidAskLowHigh()
{
return indicator.BidAskLowHigh(Input);
}
public Indicators.ninpai.BidAskLowHigh BidAskLowHigh(ISeries<double> input )
{
return indicator.BidAskLowHigh(input);
}
}
}
namespace NinjaTrader.NinjaScript.Strategies
{
public partial class Strategy : NinjaTrader.Gui.NinjaScript.StrategyRenderBase
{
public Indicators.ninpai.BidAskLowHigh BidAskLowHigh()
{
return indicator.BidAskLowHigh(Input);
}
public Indicators.ninpai.BidAskLowHigh BidAskLowHigh(ISeries<double> input )
{
return indicator.BidAskLowHigh(input);
}
}
}
#endregion
| 412 | 0.568914 | 1 | 0.568914 | game-dev | MEDIA | 0.304735 | game-dev | 0.858073 | 1 | 0.858073 |
CreativeDesigner3D/BlenderSource | 102,649 | source/blender/bmesh/intern/bmesh_mesh.c | /*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/** \file
* \ingroup bmesh
*
* BM mesh level functions.
*/
#include "MEM_guardedalloc.h"
#include "DNA_listBase.h"
#include "DNA_scene_types.h"
#include "BLI_bitmap.h"
#include "BLI_linklist_stack.h"
#include "BLI_listbase.h"
#include "BLI_math.h"
#include "BLI_stack.h"
#include "BLI_task.h"
#include "BLI_utildefines.h"
#include "BKE_editmesh.h"
#include "BKE_global.h"
#include "BKE_mesh.h"
#include "BKE_multires.h"
#include "atomic_ops.h"
#include "intern/bmesh_private.h"
/* used as an extern, defined in bmesh.h */
const BMAllocTemplate bm_mesh_allocsize_default = {512, 1024, 2048, 512};
const BMAllocTemplate bm_mesh_chunksize_default = {512, 1024, 2048, 512};
static void bm_mempool_init_ex(const BMAllocTemplate *allocsize,
const bool use_toolflags,
BLI_mempool **r_vpool,
BLI_mempool **r_epool,
BLI_mempool **r_lpool,
BLI_mempool **r_fpool)
{
size_t vert_size, edge_size, loop_size, face_size;
if (use_toolflags == true) {
vert_size = sizeof(BMVert_OFlag);
edge_size = sizeof(BMEdge_OFlag);
loop_size = sizeof(BMLoop);
face_size = sizeof(BMFace_OFlag);
}
else {
vert_size = sizeof(BMVert);
edge_size = sizeof(BMEdge);
loop_size = sizeof(BMLoop);
face_size = sizeof(BMFace);
}
if (r_vpool) {
*r_vpool = BLI_mempool_create(
vert_size, allocsize->totvert, bm_mesh_chunksize_default.totvert, BLI_MEMPOOL_ALLOW_ITER);
}
if (r_epool) {
*r_epool = BLI_mempool_create(
edge_size, allocsize->totedge, bm_mesh_chunksize_default.totedge, BLI_MEMPOOL_ALLOW_ITER);
}
if (r_lpool) {
*r_lpool = BLI_mempool_create(
loop_size, allocsize->totloop, bm_mesh_chunksize_default.totloop, BLI_MEMPOOL_NOP);
}
if (r_fpool) {
*r_fpool = BLI_mempool_create(
face_size, allocsize->totface, bm_mesh_chunksize_default.totface, BLI_MEMPOOL_ALLOW_ITER);
}
}
static void bm_mempool_init(BMesh *bm, const BMAllocTemplate *allocsize, const bool use_toolflags)
{
bm_mempool_init_ex(allocsize, use_toolflags, &bm->vpool, &bm->epool, &bm->lpool, &bm->fpool);
#ifdef USE_BMESH_HOLES
bm->looplistpool = BLI_mempool_create(sizeof(BMLoopList), 512, 512, BLI_MEMPOOL_NOP);
#endif
}
void BM_mesh_elem_toolflags_ensure(BMesh *bm)
{
BLI_assert(bm->use_toolflags);
if (bm->vtoolflagpool && bm->etoolflagpool && bm->ftoolflagpool) {
return;
}
bm->vtoolflagpool = BLI_mempool_create(sizeof(BMFlagLayer), bm->totvert, 512, BLI_MEMPOOL_NOP);
bm->etoolflagpool = BLI_mempool_create(sizeof(BMFlagLayer), bm->totedge, 512, BLI_MEMPOOL_NOP);
bm->ftoolflagpool = BLI_mempool_create(sizeof(BMFlagLayer), bm->totface, 512, BLI_MEMPOOL_NOP);
BMIter iter;
BMVert_OFlag *v_olfag;
BLI_mempool *toolflagpool = bm->vtoolflagpool;
BM_ITER_MESH (v_olfag, &iter, bm, BM_VERTS_OF_MESH) {
v_olfag->oflags = BLI_mempool_calloc(toolflagpool);
}
BMEdge_OFlag *e_olfag;
toolflagpool = bm->etoolflagpool;
BM_ITER_MESH (e_olfag, &iter, bm, BM_EDGES_OF_MESH) {
e_olfag->oflags = BLI_mempool_calloc(toolflagpool);
}
BMFace_OFlag *f_olfag;
toolflagpool = bm->ftoolflagpool;
BM_ITER_MESH (f_olfag, &iter, bm, BM_FACES_OF_MESH) {
f_olfag->oflags = BLI_mempool_calloc(toolflagpool);
}
bm->totflags = 1;
}
void BM_mesh_elem_toolflags_clear(BMesh *bm)
{
if (bm->vtoolflagpool) {
BLI_mempool_destroy(bm->vtoolflagpool);
bm->vtoolflagpool = NULL;
}
if (bm->etoolflagpool) {
BLI_mempool_destroy(bm->etoolflagpool);
bm->etoolflagpool = NULL;
}
if (bm->ftoolflagpool) {
BLI_mempool_destroy(bm->ftoolflagpool);
bm->ftoolflagpool = NULL;
}
}
/**
* \brief BMesh Make Mesh
*
* Allocates a new BMesh structure.
*
* \return The New bmesh
*
* \note ob is needed by multires
*/
BMesh *BM_mesh_create(const BMAllocTemplate *allocsize, const struct BMeshCreateParams *params)
{
/* allocate the structure */
BMesh *bm = MEM_callocN(sizeof(BMesh), __func__);
/* allocate the memory pools for the mesh elements */
bm_mempool_init(bm, allocsize, params->use_toolflags);
/* allocate one flag pool that we don't get rid of. */
bm->use_toolflags = params->use_toolflags;
bm->toolflag_index = 0;
bm->totflags = 0;
CustomData_reset(&bm->vdata);
CustomData_reset(&bm->edata);
CustomData_reset(&bm->ldata);
CustomData_reset(&bm->pdata);
return bm;
}
/**
* \brief BMesh Free Mesh Data
*
* Frees a BMesh structure.
*
* \note frees mesh, but not actual BMesh struct
*/
void BM_mesh_data_free(BMesh *bm)
{
BMVert *v;
BMEdge *e;
BMLoop *l;
BMFace *f;
BMIter iter;
BMIter itersub;
const bool is_ldata_free = CustomData_bmesh_has_free(&bm->ldata);
const bool is_pdata_free = CustomData_bmesh_has_free(&bm->pdata);
/* Check if we have to call free, if not we can avoid a lot of looping */
if (CustomData_bmesh_has_free(&(bm->vdata))) {
BM_ITER_MESH (v, &iter, bm, BM_VERTS_OF_MESH) {
CustomData_bmesh_free_block(&(bm->vdata), &(v->head.data));
}
}
if (CustomData_bmesh_has_free(&(bm->edata))) {
BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) {
CustomData_bmesh_free_block(&(bm->edata), &(e->head.data));
}
}
if (is_ldata_free || is_pdata_free) {
BM_ITER_MESH (f, &iter, bm, BM_FACES_OF_MESH) {
if (is_pdata_free) {
CustomData_bmesh_free_block(&(bm->pdata), &(f->head.data));
}
if (is_ldata_free) {
BM_ITER_ELEM (l, &itersub, f, BM_LOOPS_OF_FACE) {
CustomData_bmesh_free_block(&(bm->ldata), &(l->head.data));
}
}
}
}
/* Free custom data pools, This should probably go in CustomData_free? */
if (bm->vdata.totlayer) {
BLI_mempool_destroy(bm->vdata.pool);
}
if (bm->edata.totlayer) {
BLI_mempool_destroy(bm->edata.pool);
}
if (bm->ldata.totlayer) {
BLI_mempool_destroy(bm->ldata.pool);
}
if (bm->pdata.totlayer) {
BLI_mempool_destroy(bm->pdata.pool);
}
/* free custom data */
CustomData_free(&bm->vdata, 0);
CustomData_free(&bm->edata, 0);
CustomData_free(&bm->ldata, 0);
CustomData_free(&bm->pdata, 0);
/* destroy element pools */
BLI_mempool_destroy(bm->vpool);
BLI_mempool_destroy(bm->epool);
BLI_mempool_destroy(bm->lpool);
BLI_mempool_destroy(bm->fpool);
if (bm->vtable) {
MEM_freeN(bm->vtable);
}
if (bm->etable) {
MEM_freeN(bm->etable);
}
if (bm->ftable) {
MEM_freeN(bm->ftable);
}
/* destroy flag pool */
BM_mesh_elem_toolflags_clear(bm);
#ifdef USE_BMESH_HOLES
BLI_mempool_destroy(bm->looplistpool);
#endif
BLI_freelistN(&bm->selected);
if (bm->lnor_spacearr) {
BKE_lnor_spacearr_free(bm->lnor_spacearr);
MEM_freeN(bm->lnor_spacearr);
}
BMO_error_clear(bm);
}
/**
* \brief BMesh Clear Mesh
*
* Clear all data in bm
*/
void BM_mesh_clear(BMesh *bm)
{
const bool use_toolflags = bm->use_toolflags;
/* free old mesh */
BM_mesh_data_free(bm);
memset(bm, 0, sizeof(BMesh));
/* allocate the memory pools for the mesh elements */
bm_mempool_init(bm, &bm_mesh_allocsize_default, use_toolflags);
bm->use_toolflags = use_toolflags;
bm->toolflag_index = 0;
bm->totflags = 0;
CustomData_reset(&bm->vdata);
CustomData_reset(&bm->edata);
CustomData_reset(&bm->ldata);
CustomData_reset(&bm->pdata);
}
/**
* \brief BMesh Free Mesh
*
* Frees a BMesh data and its structure.
*/
void BM_mesh_free(BMesh *bm)
{
BM_mesh_data_free(bm);
if (bm->py_handle) {
/* keep this out of 'BM_mesh_data_free' because we want python
* to be able to clear the mesh and maintain access. */
bpy_bm_generic_invalidate(bm->py_handle);
bm->py_handle = NULL;
}
MEM_freeN(bm);
}
/**
* Helpers for #BM_mesh_normals_update and #BM_verts_calc_normal_vcos
*/
/* We use that existing internal API flag,
* assuming no other tool using it would run concurrently to clnors editing. */
#define BM_LNORSPACE_UPDATE _FLAG_MF
typedef struct BMEdgesCalcVectorsData {
/* Read-only data. */
const float (*vcos)[3];
/* Read-write data, but no need to protect it, no concurrency to fear here. */
float (*edgevec)[3];
} BMEdgesCalcVectorsData;
static void mesh_edges_calc_vectors_cb(void *userdata, MempoolIterData *mp_e)
{
BMEdgesCalcVectorsData *data = userdata;
BMEdge *e = (BMEdge *)mp_e;
if (e->l) {
const float *v1_co = data->vcos ? data->vcos[BM_elem_index_get(e->v1)] : e->v1->co;
const float *v2_co = data->vcos ? data->vcos[BM_elem_index_get(e->v2)] : e->v2->co;
sub_v3_v3v3(data->edgevec[BM_elem_index_get(e)], v2_co, v1_co);
normalize_v3(data->edgevec[BM_elem_index_get(e)]);
}
else {
/* the edge vector will not be needed when the edge has no radial */
}
}
static void bm_mesh_edges_calc_vectors(BMesh *bm, float (*edgevec)[3], const float (*vcos)[3])
{
BM_mesh_elem_index_ensure(bm, BM_EDGE | (vcos ? BM_VERT : 0));
BMEdgesCalcVectorsData data = {
.vcos = vcos,
.edgevec = edgevec,
};
BM_iter_parallel(
bm, BM_EDGES_OF_MESH, mesh_edges_calc_vectors_cb, &data, bm->totedge >= BM_OMP_LIMIT);
}
typedef struct BMVertsCalcNormalsData {
/* Read-only data. */
const float (*fnos)[3];
const float (*edgevec)[3];
const float (*vcos)[3];
/* Read-write data, protected by an atomic-based fake spin-lock like system. */
float (*vnos)[3];
} BMVertsCalcNormalsData;
static void mesh_verts_calc_normals_accum_cb(void *userdata, MempoolIterData *mp_f)
{
#define FLT_EQ_NONAN(_fa, _fb) (*((const uint32_t *)&_fa) == *((const uint32_t *)&_fb))
BMVertsCalcNormalsData *data = userdata;
BMFace *f = (BMFace *)mp_f;
const float *f_no = data->fnos ? data->fnos[BM_elem_index_get(f)] : f->no;
BMLoop *l_first, *l_iter;
l_iter = l_first = BM_FACE_FIRST_LOOP(f);
do {
const float *e1diff, *e2diff;
float dotprod;
float fac;
/* calculate the dot product of the two edges that
* meet at the loop's vertex */
e1diff = data->edgevec[BM_elem_index_get(l_iter->prev->e)];
e2diff = data->edgevec[BM_elem_index_get(l_iter->e)];
dotprod = dot_v3v3(e1diff, e2diff);
/* edge vectors are calculated from e->v1 to e->v2, so
* adjust the dot product if one but not both loops
* actually runs from from e->v2 to e->v1 */
if ((l_iter->prev->e->v1 == l_iter->prev->v) ^ (l_iter->e->v1 == l_iter->v)) {
dotprod = -dotprod;
}
fac = saacos(-dotprod);
if (fac != fac) { /* NAN detection. */
/* Degenerated case, nothing to do here, just ignore that vertex. */
continue;
}
/* accumulate weighted face normal into the vertex's normal */
float *v_no = data->vnos ? data->vnos[BM_elem_index_get(l_iter->v)] : l_iter->v->no;
/* This block is a lockless threadsafe madd_v3_v3fl.
* It uses the first float of the vector as a sort of cheap spin-lock,
* assuming FLT_MAX is a safe 'illegal' value that cannot be set here otherwise.
* It also assumes that collisions between threads are highly unlikely,
* else performances would be quite bad here. */
float virtual_lock = v_no[0];
while (true) {
/* This loops until following conditions are met:
* - v_no[0] has same value as virtual_lock (i.e. it did not change since last try).
* - v_no[0] was not FLT_MAX, i.e. it was not locked by another thread.
*/
const float vl = atomic_cas_float(&v_no[0], virtual_lock, FLT_MAX);
if (FLT_EQ_NONAN(vl, virtual_lock) && vl != FLT_MAX) {
break;
}
virtual_lock = vl;
}
BLI_assert(v_no[0] == FLT_MAX);
/* Now we own that normal value, and can change it.
* But first scalar of the vector must not be changed yet, it's our lock! */
virtual_lock += f_no[0] * fac;
v_no[1] += f_no[1] * fac;
v_no[2] += f_no[2] * fac;
/* Second atomic operation to 'release'
* our lock on that vector and set its first scalar value. */
/* Note that we do not need to loop here, since we 'locked' v_no[0],
* nobody should have changed it in the mean time. */
virtual_lock = atomic_cas_float(&v_no[0], FLT_MAX, virtual_lock);
BLI_assert(virtual_lock == FLT_MAX);
} while ((l_iter = l_iter->next) != l_first);
#undef FLT_EQ_NONAN
}
static void mesh_verts_calc_normals_normalize_cb(void *userdata, MempoolIterData *mp_v)
{
BMVertsCalcNormalsData *data = userdata;
BMVert *v = (BMVert *)mp_v;
float *v_no = data->vnos ? data->vnos[BM_elem_index_get(v)] : v->no;
if (UNLIKELY(normalize_v3(v_no) == 0.0f)) {
const float *v_co = data->vcos ? data->vcos[BM_elem_index_get(v)] : v->co;
normalize_v3_v3(v_no, v_co);
}
}
static void bm_mesh_verts_calc_normals(BMesh *bm,
const float (*edgevec)[3],
const float (*fnos)[3],
const float (*vcos)[3],
float (*vnos)[3])
{
BM_mesh_elem_index_ensure(bm, (BM_EDGE | BM_FACE) | ((vnos || vcos) ? BM_VERT : 0));
BMVertsCalcNormalsData data = {
.fnos = fnos,
.edgevec = edgevec,
.vcos = vcos,
.vnos = vnos,
};
BM_iter_parallel(
bm, BM_FACES_OF_MESH, mesh_verts_calc_normals_accum_cb, &data, bm->totface >= BM_OMP_LIMIT);
/* normalize the accumulated vertex normals */
BM_iter_parallel(bm,
BM_VERTS_OF_MESH,
mesh_verts_calc_normals_normalize_cb,
&data,
bm->totvert >= BM_OMP_LIMIT);
}
static void mesh_faces_calc_normals_cb(void *UNUSED(userdata), MempoolIterData *mp_f)
{
BMFace *f = (BMFace *)mp_f;
BM_face_normal_update(f);
}
/**
* \brief BMesh Compute Normals
*
* Updates the normals of a mesh.
*/
void BM_mesh_normals_update(BMesh *bm)
{
float(*edgevec)[3] = MEM_mallocN(sizeof(*edgevec) * bm->totedge, __func__);
/* Parallel mempool iteration does not allow generating indices inline anymore... */
BM_mesh_elem_index_ensure(bm, (BM_EDGE | BM_FACE));
/* calculate all face normals */
BM_iter_parallel(
bm, BM_FACES_OF_MESH, mesh_faces_calc_normals_cb, NULL, bm->totface >= BM_OMP_LIMIT);
/* Zero out vertex normals */
BMIter viter;
BMVert *v;
int i;
BM_ITER_MESH_INDEX (v, &viter, bm, BM_VERTS_OF_MESH, i) {
BM_elem_index_set(v, i); /* set_inline */
zero_v3(v->no);
}
bm->elem_index_dirty &= ~BM_VERT;
/* Compute normalized direction vectors for each edge.
* Directions will be used for calculating the weights of the face normals on the vertex normals.
*/
bm_mesh_edges_calc_vectors(bm, edgevec, NULL);
/* Add weighted face normals to vertices, and normalize vert normals. */
bm_mesh_verts_calc_normals(bm, (const float(*)[3])edgevec, NULL, NULL, NULL);
MEM_freeN(edgevec);
}
/**
* \brief BMesh Compute Normals from/to external data.
*
* Computes the vertex normals of a mesh into vnos,
* using given vertex coordinates (vcos) and polygon normals (fnos).
*/
void BM_verts_calc_normal_vcos(BMesh *bm,
const float (*fnos)[3],
const float (*vcos)[3],
float (*vnos)[3])
{
float(*edgevec)[3] = MEM_mallocN(sizeof(*edgevec) * bm->totedge, __func__);
/* Compute normalized direction vectors for each edge.
* Directions will be used for calculating the weights of the face normals on the vertex normals.
*/
bm_mesh_edges_calc_vectors(bm, edgevec, vcos);
/* Add weighted face normals to vertices, and normalize vert normals. */
bm_mesh_verts_calc_normals(bm, (const float(*)[3])edgevec, fnos, vcos, vnos);
MEM_freeN(edgevec);
}
/**
* Helpers for #BM_mesh_loop_normals_update and #BM_loops_calc_normal_vcos
*/
static void bm_mesh_edges_sharp_tag(BMesh *bm,
const float (*vnos)[3],
const float (*fnos)[3],
float (*r_lnos)[3],
const float split_angle,
const bool do_sharp_edges_tag)
{
BMIter eiter;
BMEdge *e;
int i;
const bool check_angle = (split_angle < (float)M_PI);
const float split_angle_cos = check_angle ? cosf(split_angle) : -1.0f;
{
char htype = BM_VERT | BM_LOOP;
if (fnos) {
htype |= BM_FACE;
}
BM_mesh_elem_index_ensure(bm, htype);
}
/* This first loop checks which edges are actually smooth,
* and pre-populate lnos with vnos (as if they were all smooth). */
BM_ITER_MESH_INDEX (e, &eiter, bm, BM_EDGES_OF_MESH, i) {
BMLoop *l_a, *l_b;
BM_elem_index_set(e, i); /* set_inline */
BM_elem_flag_disable(e, BM_ELEM_TAG); /* Clear tag (means edge is sharp). */
/* An edge with only two loops, might be smooth... */
if (BM_edge_loop_pair(e, &l_a, &l_b)) {
bool is_angle_smooth = true;
if (check_angle) {
const float *no_a = fnos ? fnos[BM_elem_index_get(l_a->f)] : l_a->f->no;
const float *no_b = fnos ? fnos[BM_elem_index_get(l_b->f)] : l_b->f->no;
is_angle_smooth = (dot_v3v3(no_a, no_b) >= split_angle_cos);
}
/* We only tag edges that are *really* smooth:
* If the angle between both its polys' normals is below split_angle value,
* and it is tagged as such,
* and both its faces are smooth,
* and both its faces have compatible (non-flipped) normals,
* i.e. both loops on the same edge do not share the same vertex.
*/
if (BM_elem_flag_test(e, BM_ELEM_SMOOTH) && BM_elem_flag_test(l_a->f, BM_ELEM_SMOOTH) &&
BM_elem_flag_test(l_b->f, BM_ELEM_SMOOTH) && l_a->v != l_b->v) {
if (is_angle_smooth) {
const float *no;
BM_elem_flag_enable(e, BM_ELEM_TAG);
/* linked vertices might be fully smooth, copy their normals to loop ones. */
if (r_lnos) {
no = vnos ? vnos[BM_elem_index_get(l_a->v)] : l_a->v->no;
copy_v3_v3(r_lnos[BM_elem_index_get(l_a)], no);
no = vnos ? vnos[BM_elem_index_get(l_b->v)] : l_b->v->no;
copy_v3_v3(r_lnos[BM_elem_index_get(l_b)], no);
}
}
else if (do_sharp_edges_tag) {
/* Note that we do not care about the other sharp-edge cases
* (sharp poly, non-manifold edge, etc.),
* only tag edge as sharp when it is due to angle threshold. */
BM_elem_flag_disable(e, BM_ELEM_SMOOTH);
}
}
}
}
bm->elem_index_dirty &= ~BM_EDGE;
}
/**
* Check whether given loop is part of an unknown-so-far cyclic smooth fan, or not.
* Needed because cyclic smooth fans have no obvious 'entry point',
* and yet we need to walk them once, and only once.
*/
bool BM_loop_check_cyclic_smooth_fan(BMLoop *l_curr)
{
BMLoop *lfan_pivot_next = l_curr;
BMEdge *e_next = l_curr->e;
BLI_assert(!BM_elem_flag_test(lfan_pivot_next, BM_ELEM_TAG));
BM_elem_flag_enable(lfan_pivot_next, BM_ELEM_TAG);
while (true) {
/* Much simpler than in sibling code with basic Mesh data! */
lfan_pivot_next = BM_vert_step_fan_loop(lfan_pivot_next, &e_next);
if (!lfan_pivot_next || !BM_elem_flag_test(e_next, BM_ELEM_TAG)) {
/* Sharp loop/edge, so not a cyclic smooth fan... */
return false;
}
/* Smooth loop/edge... */
if (BM_elem_flag_test(lfan_pivot_next, BM_ELEM_TAG)) {
if (lfan_pivot_next == l_curr) {
/* We walked around a whole cyclic smooth fan
* without finding any already-processed loop,
* means we can use initial l_curr/l_prev edge as start for this smooth fan. */
return true;
}
/* ... already checked in some previous looping, we can abort. */
return false;
}
/* ... we can skip it in future, and keep checking the smooth fan. */
BM_elem_flag_enable(lfan_pivot_next, BM_ELEM_TAG);
}
}
/**
* BMesh version of BKE_mesh_normals_loop_split() in mesh_evaluate.c
* Will use first clnors_data array, and fallback to cd_loop_clnors_offset
* (use NULL and -1 to not use clnors).
*
* \note This sets #BM_ELEM_TAG which is used in tool code (e.g. T84426).
* we could add a low-level API flag for this, see #BM_ELEM_API_FLAG_ENABLE and friends.
*/
static void bm_mesh_loops_calc_normals(BMesh *bm,
const float (*vcos)[3],
const float (*fnos)[3],
float (*r_lnos)[3],
MLoopNorSpaceArray *r_lnors_spacearr,
const short (*clnors_data)[2],
const int cd_loop_clnors_offset,
const bool do_rebuild)
{
BMIter fiter;
BMFace *f_curr;
const bool has_clnors = clnors_data || (cd_loop_clnors_offset != -1);
MLoopNorSpaceArray _lnors_spacearr = {NULL};
/* Temp normal stack. */
BLI_SMALLSTACK_DECLARE(normal, float *);
/* Temp clnors stack. */
BLI_SMALLSTACK_DECLARE(clnors, short *);
/* Temp edge vectors stack, only used when computing lnor spacearr. */
BLI_Stack *edge_vectors = NULL;
{
char htype = 0;
if (vcos) {
htype |= BM_VERT;
}
/* Face/Loop indices are set inline below. */
BM_mesh_elem_index_ensure(bm, htype);
}
if (!r_lnors_spacearr && has_clnors) {
/* We need to compute lnor spacearr if some custom lnor data are given to us! */
r_lnors_spacearr = &_lnors_spacearr;
}
if (r_lnors_spacearr) {
BKE_lnor_spacearr_init(r_lnors_spacearr, bm->totloop, MLNOR_SPACEARR_BMLOOP_PTR);
edge_vectors = BLI_stack_new(sizeof(float[3]), __func__);
}
/* Clear all loops' tags (means none are to be skipped for now). */
int index_face, index_loop = 0;
BM_ITER_MESH_INDEX (f_curr, &fiter, bm, BM_FACES_OF_MESH, index_face) {
BMLoop *l_curr, *l_first;
BM_elem_index_set(f_curr, index_face); /* set_inline */
l_curr = l_first = BM_FACE_FIRST_LOOP(f_curr);
do {
BM_elem_index_set(l_curr, index_loop++); /* set_inline */
BM_elem_flag_disable(l_curr, BM_ELEM_TAG);
} while ((l_curr = l_curr->next) != l_first);
}
bm->elem_index_dirty &= ~(BM_FACE | BM_LOOP);
/* We now know edges that can be smoothed (they are tagged),
* and edges that will be hard (they aren't).
* Now, time to generate the normals.
*/
BM_ITER_MESH (f_curr, &fiter, bm, BM_FACES_OF_MESH) {
BMLoop *l_curr, *l_first;
l_curr = l_first = BM_FACE_FIRST_LOOP(f_curr);
do {
if (do_rebuild && !BM_ELEM_API_FLAG_TEST(l_curr, BM_LNORSPACE_UPDATE) &&
!(bm->spacearr_dirty & BM_SPACEARR_DIRTY_ALL)) {
continue;
}
/* A smooth edge, we have to check for cyclic smooth fan case.
* If we find a new, never-processed cyclic smooth fan, we can do it now using that loop/edge
* as 'entry point', otherwise we can skip it. */
/* Note: In theory, we could make bm_mesh_loop_check_cyclic_smooth_fan() store
* mlfan_pivot's in a stack, to avoid having to fan again around
* the vert during actual computation of clnor & clnorspace. However, this would complicate
* the code, add more memory usage, and
* BM_vert_step_fan_loop() is quite cheap in term of CPU cycles,
* so really think it's not worth it. */
if (BM_elem_flag_test(l_curr->e, BM_ELEM_TAG) &&
(BM_elem_flag_test(l_curr, BM_ELEM_TAG) || !BM_loop_check_cyclic_smooth_fan(l_curr))) {
}
else if (!BM_elem_flag_test(l_curr->e, BM_ELEM_TAG) &&
!BM_elem_flag_test(l_curr->prev->e, BM_ELEM_TAG)) {
/* Simple case (both edges around that vertex are sharp in related polygon),
* this vertex just takes its poly normal.
*/
const int l_curr_index = BM_elem_index_get(l_curr);
const float *no = fnos ? fnos[BM_elem_index_get(f_curr)] : f_curr->no;
copy_v3_v3(r_lnos[l_curr_index], no);
/* If needed, generate this (simple!) lnor space. */
if (r_lnors_spacearr) {
float vec_curr[3], vec_prev[3];
MLoopNorSpace *lnor_space = BKE_lnor_space_create(r_lnors_spacearr);
{
const BMVert *v_pivot = l_curr->v;
const float *co_pivot = vcos ? vcos[BM_elem_index_get(v_pivot)] : v_pivot->co;
const BMVert *v_1 = BM_edge_other_vert(l_curr->e, v_pivot);
const float *co_1 = vcos ? vcos[BM_elem_index_get(v_1)] : v_1->co;
const BMVert *v_2 = BM_edge_other_vert(l_curr->prev->e, v_pivot);
const float *co_2 = vcos ? vcos[BM_elem_index_get(v_2)] : v_2->co;
sub_v3_v3v3(vec_curr, co_1, co_pivot);
normalize_v3(vec_curr);
sub_v3_v3v3(vec_prev, co_2, co_pivot);
normalize_v3(vec_prev);
}
BKE_lnor_space_define(lnor_space, r_lnos[l_curr_index], vec_curr, vec_prev, NULL);
/* We know there is only one loop in this space,
* no need to create a linklist in this case... */
BKE_lnor_space_add_loop(r_lnors_spacearr, lnor_space, l_curr_index, l_curr, true);
if (has_clnors) {
const short(*clnor)[2] = clnors_data ? &clnors_data[l_curr_index] :
(const void *)BM_ELEM_CD_GET_VOID_P(
l_curr, cd_loop_clnors_offset);
BKE_lnor_space_custom_data_to_normal(lnor_space, *clnor, r_lnos[l_curr_index]);
}
}
}
/* We *do not need* to check/tag loops as already computed!
* Due to the fact a loop only links to one of its two edges,
* a same fan *will never be walked more than once!*
* Since we consider edges having neighbor faces with inverted (flipped) normals as sharp,
* we are sure that no fan will be skipped, even only considering the case
* (sharp curr_edge, smooth prev_edge), and not the alternative
* (smooth curr_edge, sharp prev_edge).
* All this due/thanks to link between normals and loop ordering.
*/
else {
/* We have to fan around current vertex, until we find the other non-smooth edge,
* and accumulate face normals into the vertex!
* Note in case this vertex has only one sharp edge,
* this is a waste because the normal is the same as the vertex normal,
* but I do not see any easy way to detect that (would need to count number of sharp edges
* per vertex, I doubt the additional memory usage would be worth it, especially as it
* should not be a common case in real-life meshes anyway).
*/
BMVert *v_pivot = l_curr->v;
BMEdge *e_next;
const BMEdge *e_org = l_curr->e;
BMLoop *lfan_pivot, *lfan_pivot_next;
int lfan_pivot_index;
float lnor[3] = {0.0f, 0.0f, 0.0f};
float vec_curr[3], vec_next[3], vec_org[3];
/* We validate clnors data on the fly - cheapest way to do! */
int clnors_avg[2] = {0, 0};
const short(*clnor_ref)[2] = NULL;
int clnors_nbr = 0;
bool clnors_invalid = false;
const float *co_pivot = vcos ? vcos[BM_elem_index_get(v_pivot)] : v_pivot->co;
MLoopNorSpace *lnor_space = r_lnors_spacearr ? BKE_lnor_space_create(r_lnors_spacearr) :
NULL;
BLI_assert((edge_vectors == NULL) || BLI_stack_is_empty(edge_vectors));
lfan_pivot = l_curr;
lfan_pivot_index = BM_elem_index_get(lfan_pivot);
e_next = lfan_pivot->e; /* Current edge here, actually! */
/* Only need to compute previous edge's vector once,
* then we can just reuse old current one! */
{
const BMVert *v_2 = BM_edge_other_vert(e_next, v_pivot);
const float *co_2 = vcos ? vcos[BM_elem_index_get(v_2)] : v_2->co;
sub_v3_v3v3(vec_org, co_2, co_pivot);
normalize_v3(vec_org);
copy_v3_v3(vec_curr, vec_org);
if (r_lnors_spacearr) {
BLI_stack_push(edge_vectors, vec_org);
}
}
while (true) {
/* Much simpler than in sibling code with basic Mesh data! */
lfan_pivot_next = BM_vert_step_fan_loop(lfan_pivot, &e_next);
if (lfan_pivot_next) {
BLI_assert(lfan_pivot_next->v == v_pivot);
}
else {
/* next edge is non-manifold, we have to find it ourselves! */
e_next = (lfan_pivot->e == e_next) ? lfan_pivot->prev->e : lfan_pivot->e;
}
/* Compute edge vector.
* NOTE: We could pre-compute those into an array, in the first iteration,
* instead of computing them twice (or more) here.
* However, time gained is not worth memory and time lost,
* given the fact that this code should not be called that much in real-life meshes.
*/
{
const BMVert *v_2 = BM_edge_other_vert(e_next, v_pivot);
const float *co_2 = vcos ? vcos[BM_elem_index_get(v_2)] : v_2->co;
sub_v3_v3v3(vec_next, co_2, co_pivot);
normalize_v3(vec_next);
}
{
/* Code similar to accumulate_vertex_normals_poly_v3. */
/* Calculate angle between the two poly edges incident on this vertex. */
const BMFace *f = lfan_pivot->f;
const float fac = saacos(dot_v3v3(vec_next, vec_curr));
const float *no = fnos ? fnos[BM_elem_index_get(f)] : f->no;
/* Accumulate */
madd_v3_v3fl(lnor, no, fac);
if (has_clnors) {
/* Accumulate all clnors, if they are not all equal we have to fix that! */
const short(*clnor)[2] = clnors_data ? &clnors_data[lfan_pivot_index] :
(const void *)BM_ELEM_CD_GET_VOID_P(
lfan_pivot, cd_loop_clnors_offset);
if (clnors_nbr) {
clnors_invalid |= ((*clnor_ref)[0] != (*clnor)[0] ||
(*clnor_ref)[1] != (*clnor)[1]);
}
else {
clnor_ref = clnor;
}
clnors_avg[0] += (*clnor)[0];
clnors_avg[1] += (*clnor)[1];
clnors_nbr++;
/* We store here a pointer to all custom lnors processed. */
BLI_SMALLSTACK_PUSH(clnors, (short *)*clnor);
}
}
/* We store here a pointer to all loop-normals processed. */
BLI_SMALLSTACK_PUSH(normal, (float *)r_lnos[lfan_pivot_index]);
if (r_lnors_spacearr) {
/* Assign current lnor space to current 'vertex' loop. */
BKE_lnor_space_add_loop(
r_lnors_spacearr, lnor_space, lfan_pivot_index, lfan_pivot, false);
if (e_next != e_org) {
/* We store here all edges-normalized vectors processed. */
BLI_stack_push(edge_vectors, vec_next);
}
}
if (!BM_elem_flag_test(e_next, BM_ELEM_TAG) || (e_next == e_org)) {
/* Next edge is sharp, we have finished with this fan of faces around this vert! */
break;
}
/* Copy next edge vector to current one. */
copy_v3_v3(vec_curr, vec_next);
/* Next pivot loop to current one. */
lfan_pivot = lfan_pivot_next;
lfan_pivot_index = BM_elem_index_get(lfan_pivot);
}
{
float lnor_len = normalize_v3(lnor);
/* If we are generating lnor spacearr, we can now define the one for this fan. */
if (r_lnors_spacearr) {
if (UNLIKELY(lnor_len == 0.0f)) {
/* Use vertex normal as fallback! */
copy_v3_v3(lnor, r_lnos[lfan_pivot_index]);
lnor_len = 1.0f;
}
BKE_lnor_space_define(lnor_space, lnor, vec_org, vec_next, edge_vectors);
if (has_clnors) {
if (clnors_invalid) {
short *clnor;
clnors_avg[0] /= clnors_nbr;
clnors_avg[1] /= clnors_nbr;
/* Fix/update all clnors of this fan with computed average value. */
/* Prints continuously when merge custom normals, so commenting. */
/* printf("Invalid clnors in this fan!\n"); */
while ((clnor = BLI_SMALLSTACK_POP(clnors))) {
// print_v2("org clnor", clnor);
clnor[0] = (short)clnors_avg[0];
clnor[1] = (short)clnors_avg[1];
}
// print_v2("new clnors", clnors_avg);
}
else {
/* We still have to consume the stack! */
while (BLI_SMALLSTACK_POP(clnors)) {
/* pass */
}
}
BKE_lnor_space_custom_data_to_normal(lnor_space, *clnor_ref, lnor);
}
}
/* In case we get a zero normal here, just use vertex normal already set! */
if (LIKELY(lnor_len != 0.0f)) {
/* Copy back the final computed normal into all related loop-normals. */
float *nor;
while ((nor = BLI_SMALLSTACK_POP(normal))) {
copy_v3_v3(nor, lnor);
}
}
else {
/* We still have to consume the stack! */
while (BLI_SMALLSTACK_POP(normal)) {
/* pass */
}
}
}
/* Tag related vertex as sharp, to avoid fanning around it again
* (in case it was a smooth one). */
if (r_lnors_spacearr) {
BM_elem_flag_enable(l_curr->v, BM_ELEM_TAG);
}
}
} while ((l_curr = l_curr->next) != l_first);
}
if (r_lnors_spacearr) {
BLI_stack_free(edge_vectors);
if (r_lnors_spacearr == &_lnors_spacearr) {
BKE_lnor_spacearr_free(r_lnors_spacearr);
}
}
}
/* This threshold is a bit touchy (usual float precision issue), this value seems OK. */
#define LNOR_SPACE_TRIGO_THRESHOLD (1.0f - 1e-4f)
/**
* Check each current smooth fan (one lnor space per smooth fan!), and if all its
* matching custom lnors are not (enough) equal, add sharp edges as needed.
*/
static bool bm_mesh_loops_split_lnor_fans(BMesh *bm,
MLoopNorSpaceArray *lnors_spacearr,
const float (*new_lnors)[3])
{
BLI_bitmap *done_loops = BLI_BITMAP_NEW((size_t)bm->totloop, __func__);
bool changed = false;
BLI_assert(lnors_spacearr->data_type == MLNOR_SPACEARR_BMLOOP_PTR);
for (int i = 0; i < bm->totloop; i++) {
if (!lnors_spacearr->lspacearr[i]) {
/* This should not happen in theory, but in some rare case (probably ugly geometry)
* we can get some NULL loopspacearr at this point. :/
* Maybe we should set those loops' edges as sharp?
*/
BLI_BITMAP_ENABLE(done_loops, i);
if (G.debug & G_DEBUG) {
printf("WARNING! Getting invalid NULL loop space for loop %d!\n", i);
}
continue;
}
if (!BLI_BITMAP_TEST(done_loops, i)) {
/* Notes:
* * In case of mono-loop smooth fan, we have nothing to do.
* * Loops in this linklist are ordered (in reversed order compared to how they were
* discovered by BKE_mesh_normals_loop_split(), but this is not a problem).
* Which means if we find a mismatching clnor,
* we know all remaining loops will have to be in a new, different smooth fan/lnor space.
* * In smooth fan case, we compare each clnor against a ref one,
* to avoid small differences adding up into a real big one in the end!
*/
if (lnors_spacearr->lspacearr[i]->flags & MLNOR_SPACE_IS_SINGLE) {
BLI_BITMAP_ENABLE(done_loops, i);
continue;
}
LinkNode *loops = lnors_spacearr->lspacearr[i]->loops;
BMLoop *prev_ml = NULL;
const float *org_nor = NULL;
while (loops) {
BMLoop *ml = loops->link;
const int lidx = BM_elem_index_get(ml);
const float *nor = new_lnors[lidx];
if (!org_nor) {
org_nor = nor;
}
else if (dot_v3v3(org_nor, nor) < LNOR_SPACE_TRIGO_THRESHOLD) {
/* Current normal differs too much from org one, we have to tag the edge between
* previous loop's face and current's one as sharp.
* We know those two loops do not point to the same edge,
* since we do not allow reversed winding in a same smooth fan.
*/
BMEdge *e = (prev_ml->e == ml->prev->e) ? prev_ml->e : ml->e;
BM_elem_flag_disable(e, BM_ELEM_TAG | BM_ELEM_SMOOTH);
changed = true;
org_nor = nor;
}
prev_ml = ml;
loops = loops->next;
BLI_BITMAP_ENABLE(done_loops, lidx);
}
/* We also have to check between last and first loops,
* otherwise we may miss some sharp edges here!
* This is just a simplified version of above while loop.
* See T45984. */
loops = lnors_spacearr->lspacearr[i]->loops;
if (loops && org_nor) {
BMLoop *ml = loops->link;
const int lidx = BM_elem_index_get(ml);
const float *nor = new_lnors[lidx];
if (dot_v3v3(org_nor, nor) < LNOR_SPACE_TRIGO_THRESHOLD) {
BMEdge *e = (prev_ml->e == ml->prev->e) ? prev_ml->e : ml->e;
BM_elem_flag_disable(e, BM_ELEM_TAG | BM_ELEM_SMOOTH);
changed = true;
}
}
}
}
MEM_freeN(done_loops);
return changed;
}
/**
* Assign custom normal data from given normal vectors, averaging normals
* from one smooth fan as necessary.
*/
static void bm_mesh_loops_assign_normal_data(BMesh *bm,
MLoopNorSpaceArray *lnors_spacearr,
short (*r_clnors_data)[2],
const int cd_loop_clnors_offset,
const float (*new_lnors)[3])
{
BLI_bitmap *done_loops = BLI_BITMAP_NEW((size_t)bm->totloop, __func__);
BLI_SMALLSTACK_DECLARE(clnors_data, short *);
BLI_assert(lnors_spacearr->data_type == MLNOR_SPACEARR_BMLOOP_PTR);
for (int i = 0; i < bm->totloop; i++) {
if (!lnors_spacearr->lspacearr[i]) {
BLI_BITMAP_ENABLE(done_loops, i);
if (G.debug & G_DEBUG) {
printf("WARNING! Still getting invalid NULL loop space in second loop for loop %d!\n", i);
}
continue;
}
if (!BLI_BITMAP_TEST(done_loops, i)) {
/* Note we accumulate and average all custom normals in current smooth fan,
* to avoid getting different clnors data (tiny differences in plain custom normals can
* give rather huge differences in computed 2D factors).
*/
LinkNode *loops = lnors_spacearr->lspacearr[i]->loops;
if (lnors_spacearr->lspacearr[i]->flags & MLNOR_SPACE_IS_SINGLE) {
BMLoop *ml = (BMLoop *)loops;
const int lidx = BM_elem_index_get(ml);
BLI_assert(lidx == i);
const float *nor = new_lnors[lidx];
short *clnor = r_clnors_data ? &r_clnors_data[lidx] :
BM_ELEM_CD_GET_VOID_P(ml, cd_loop_clnors_offset);
BKE_lnor_space_custom_normal_to_data(lnors_spacearr->lspacearr[i], nor, clnor);
BLI_BITMAP_ENABLE(done_loops, i);
}
else {
int nbr_nors = 0;
float avg_nor[3];
short clnor_data_tmp[2], *clnor_data;
zero_v3(avg_nor);
while (loops) {
BMLoop *ml = loops->link;
const int lidx = BM_elem_index_get(ml);
const float *nor = new_lnors[lidx];
short *clnor = r_clnors_data ? &r_clnors_data[lidx] :
BM_ELEM_CD_GET_VOID_P(ml, cd_loop_clnors_offset);
nbr_nors++;
add_v3_v3(avg_nor, nor);
BLI_SMALLSTACK_PUSH(clnors_data, clnor);
loops = loops->next;
BLI_BITMAP_ENABLE(done_loops, lidx);
}
mul_v3_fl(avg_nor, 1.0f / (float)nbr_nors);
BKE_lnor_space_custom_normal_to_data(
lnors_spacearr->lspacearr[i], avg_nor, clnor_data_tmp);
while ((clnor_data = BLI_SMALLSTACK_POP(clnors_data))) {
clnor_data[0] = clnor_data_tmp[0];
clnor_data[1] = clnor_data_tmp[1];
}
}
}
}
MEM_freeN(done_loops);
}
/**
* Compute internal representation of given custom normals (as an array of float[2] or data layer).
*
* It also makes sure the mesh matches those custom normals, by marking new sharp edges to split
* the smooth fans when loop normals for the same vertex are different, or averaging the normals
* instead, depending on the do_split_fans parameter.
*/
static void bm_mesh_loops_custom_normals_set(BMesh *bm,
const float (*vcos)[3],
const float (*vnos)[3],
const float (*fnos)[3],
MLoopNorSpaceArray *r_lnors_spacearr,
short (*r_clnors_data)[2],
const int cd_loop_clnors_offset,
float (*new_lnors)[3],
const int cd_new_lnors_offset,
bool do_split_fans)
{
BMFace *f;
BMLoop *l;
BMIter liter, fiter;
float(*cur_lnors)[3] = MEM_mallocN(sizeof(*cur_lnors) * bm->totloop, __func__);
BKE_lnor_spacearr_clear(r_lnors_spacearr);
/* Tag smooth edges and set lnos from vnos when they might be completely smooth...
* When using custom loop normals, disable the angle feature! */
bm_mesh_edges_sharp_tag(bm, vnos, fnos, cur_lnors, (float)M_PI, false);
/* Finish computing lnos by accumulating face normals
* in each fan of faces defined by sharp edges. */
bm_mesh_loops_calc_normals(
bm, vcos, fnos, cur_lnors, r_lnors_spacearr, r_clnors_data, cd_loop_clnors_offset, false);
/* Extract new normals from the data layer if necessary. */
float(*custom_lnors)[3] = new_lnors;
if (new_lnors == NULL) {
custom_lnors = MEM_mallocN(sizeof(*new_lnors) * bm->totloop, __func__);
BM_ITER_MESH (f, &fiter, bm, BM_FACES_OF_MESH) {
BM_ITER_ELEM (l, &liter, f, BM_LOOPS_OF_FACE) {
const float *normal = BM_ELEM_CD_GET_VOID_P(l, cd_new_lnors_offset);
copy_v3_v3(custom_lnors[BM_elem_index_get(l)], normal);
}
}
}
/* Validate the new normals. */
for (int i = 0; i < bm->totloop; i++) {
if (is_zero_v3(custom_lnors[i])) {
copy_v3_v3(custom_lnors[i], cur_lnors[i]);
}
else {
normalize_v3(custom_lnors[i]);
}
}
/* Now, check each current smooth fan (one lnor space per smooth fan!),
* and if all its matching custom lnors are not equal, add sharp edges as needed. */
if (do_split_fans && bm_mesh_loops_split_lnor_fans(bm, r_lnors_spacearr, custom_lnors)) {
/* If any sharp edges were added, run bm_mesh_loops_calc_normals() again to get lnor
* spacearr/smooth fans matching the given custom lnors. */
BKE_lnor_spacearr_clear(r_lnors_spacearr);
bm_mesh_loops_calc_normals(
bm, vcos, fnos, cur_lnors, r_lnors_spacearr, r_clnors_data, cd_loop_clnors_offset, false);
}
/* And we just have to convert plain object-space custom normals to our
* lnor space-encoded ones. */
bm_mesh_loops_assign_normal_data(
bm, r_lnors_spacearr, r_clnors_data, cd_loop_clnors_offset, custom_lnors);
MEM_freeN(cur_lnors);
if (custom_lnors != new_lnors) {
MEM_freeN(custom_lnors);
}
}
static void bm_mesh_loops_calc_normals_no_autosmooth(BMesh *bm,
const float (*vnos)[3],
const float (*fnos)[3],
float (*r_lnos)[3])
{
BMIter fiter;
BMFace *f_curr;
{
char htype = BM_LOOP;
if (vnos) {
htype |= BM_VERT;
}
if (fnos) {
htype |= BM_FACE;
}
BM_mesh_elem_index_ensure(bm, htype);
}
BM_ITER_MESH (f_curr, &fiter, bm, BM_FACES_OF_MESH) {
BMLoop *l_curr, *l_first;
const bool is_face_flat = !BM_elem_flag_test(f_curr, BM_ELEM_SMOOTH);
l_curr = l_first = BM_FACE_FIRST_LOOP(f_curr);
do {
const float *no = is_face_flat ? (fnos ? fnos[BM_elem_index_get(f_curr)] : f_curr->no) :
(vnos ? vnos[BM_elem_index_get(l_curr->v)] : l_curr->v->no);
copy_v3_v3(r_lnos[BM_elem_index_get(l_curr)], no);
} while ((l_curr = l_curr->next) != l_first);
}
}
#if 0 /* Unused currently */
/**
* \brief BMesh Compute Loop Normals
*
* Updates the loop normals of a mesh.
* Assumes vertex and face normals are valid (else call BM_mesh_normals_update() first)!
*/
void BM_mesh_loop_normals_update(BMesh *bm,
const bool use_split_normals,
const float split_angle,
float (*r_lnos)[3],
MLoopNorSpaceArray *r_lnors_spacearr,
const short (*clnors_data)[2],
const int cd_loop_clnors_offset)
{
const bool has_clnors = clnors_data || (cd_loop_clnors_offset != -1);
if (use_split_normals) {
/* Tag smooth edges and set lnos from vnos when they might be completely smooth...
* When using custom loop normals, disable the angle feature! */
bm_mesh_edges_sharp_tag(bm, NULL, NULL, has_clnors ? (float)M_PI : split_angle, r_lnos);
/* Finish computing lnos by accumulating face normals
* in each fan of faces defined by sharp edges. */
bm_mesh_loops_calc_normals(
bm, NULL, NULL, r_lnos, r_lnors_spacearr, clnors_data, cd_loop_clnors_offset);
}
else {
BLI_assert(!r_lnors_spacearr);
bm_mesh_loops_calc_normals_no_autosmooth(bm, NULL, NULL, r_lnos);
}
}
#endif
/**
* \brief BMesh Compute Loop Normals from/to external data.
*
* Compute split normals, i.e. vertex normals associated with each poly (hence 'loop normals').
* Useful to materialize sharp edges (or non-smooth faces) without actually modifying the geometry
* (splitting edges).
*/
void BM_loops_calc_normal_vcos(BMesh *bm,
const float (*vcos)[3],
const float (*vnos)[3],
const float (*fnos)[3],
const bool use_split_normals,
const float split_angle,
float (*r_lnos)[3],
MLoopNorSpaceArray *r_lnors_spacearr,
short (*clnors_data)[2],
const int cd_loop_clnors_offset,
const bool do_rebuild)
{
const bool has_clnors = clnors_data || (cd_loop_clnors_offset != -1);
if (use_split_normals) {
/* Tag smooth edges and set lnos from vnos when they might be completely smooth...
* When using custom loop normals, disable the angle feature! */
bm_mesh_edges_sharp_tag(bm, vnos, fnos, r_lnos, has_clnors ? (float)M_PI : split_angle, false);
/* Finish computing lnos by accumulating face normals
* in each fan of faces defined by sharp edges. */
bm_mesh_loops_calc_normals(
bm, vcos, fnos, r_lnos, r_lnors_spacearr, clnors_data, cd_loop_clnors_offset, do_rebuild);
}
else {
BLI_assert(!r_lnors_spacearr);
bm_mesh_loops_calc_normals_no_autosmooth(bm, vnos, fnos, r_lnos);
}
}
/**
* Define sharp edges as needed to mimic 'autosmooth' from angle threshold.
*
* Used when defining an empty custom loop normals data layer,
* to keep same shading as with autosmooth!
*/
void BM_edges_sharp_from_angle_set(BMesh *bm, const float split_angle)
{
if (split_angle >= (float)M_PI) {
/* Nothing to do! */
return;
}
bm_mesh_edges_sharp_tag(bm, NULL, NULL, NULL, split_angle, true);
}
void BM_lnorspacearr_store(BMesh *bm, float (*r_lnors)[3])
{
BLI_assert(bm->lnor_spacearr != NULL);
if (!CustomData_has_layer(&bm->ldata, CD_CUSTOMLOOPNORMAL)) {
BM_data_layer_add(bm, &bm->ldata, CD_CUSTOMLOOPNORMAL);
}
int cd_loop_clnors_offset = CustomData_get_offset(&bm->ldata, CD_CUSTOMLOOPNORMAL);
BM_loops_calc_normal_vcos(bm,
NULL,
NULL,
NULL,
true,
M_PI,
r_lnors,
bm->lnor_spacearr,
NULL,
cd_loop_clnors_offset,
false);
bm->spacearr_dirty &= ~(BM_SPACEARR_DIRTY | BM_SPACEARR_DIRTY_ALL);
}
#define CLEAR_SPACEARRAY_THRESHOLD(x) ((x) / 2)
void BM_lnorspace_invalidate(BMesh *bm, const bool do_invalidate_all)
{
if (bm->spacearr_dirty & BM_SPACEARR_DIRTY_ALL) {
return;
}
if (do_invalidate_all || bm->totvertsel > CLEAR_SPACEARRAY_THRESHOLD(bm->totvert)) {
bm->spacearr_dirty |= BM_SPACEARR_DIRTY_ALL;
return;
}
if (bm->lnor_spacearr == NULL) {
bm->spacearr_dirty |= BM_SPACEARR_DIRTY_ALL;
return;
}
BMVert *v;
BMLoop *l;
BMIter viter, liter;
/* Note: we could use temp tag of BMItem for that,
* but probably better not use it in such a low-level func?
* --mont29 */
BLI_bitmap *done_verts = BLI_BITMAP_NEW(bm->totvert, __func__);
BM_mesh_elem_index_ensure(bm, BM_VERT);
/* When we affect a given vertex, we may affect following smooth fans:
* - all smooth fans of said vertex;
* - all smooth fans of all immediate loop-neighbors vertices;
* This can be simplified as 'all loops of selected vertices and their immediate neighbors'
* need to be tagged for update.
*/
BM_ITER_MESH (v, &viter, bm, BM_VERTS_OF_MESH) {
if (BM_elem_flag_test(v, BM_ELEM_SELECT)) {
BM_ITER_ELEM (l, &liter, v, BM_LOOPS_OF_VERT) {
BM_ELEM_API_FLAG_ENABLE(l, BM_LNORSPACE_UPDATE);
/* Note that we only handle unselected neighbor vertices here, main loop will take care of
* selected ones. */
if ((!BM_elem_flag_test(l->prev->v, BM_ELEM_SELECT)) &&
!BLI_BITMAP_TEST(done_verts, BM_elem_index_get(l->prev->v))) {
BMLoop *l_prev;
BMIter liter_prev;
BM_ITER_ELEM (l_prev, &liter_prev, l->prev->v, BM_LOOPS_OF_VERT) {
BM_ELEM_API_FLAG_ENABLE(l_prev, BM_LNORSPACE_UPDATE);
}
BLI_BITMAP_ENABLE(done_verts, BM_elem_index_get(l_prev->v));
}
if ((!BM_elem_flag_test(l->next->v, BM_ELEM_SELECT)) &&
!BLI_BITMAP_TEST(done_verts, BM_elem_index_get(l->next->v))) {
BMLoop *l_next;
BMIter liter_next;
BM_ITER_ELEM (l_next, &liter_next, l->next->v, BM_LOOPS_OF_VERT) {
BM_ELEM_API_FLAG_ENABLE(l_next, BM_LNORSPACE_UPDATE);
}
BLI_BITMAP_ENABLE(done_verts, BM_elem_index_get(l_next->v));
}
}
BLI_BITMAP_ENABLE(done_verts, BM_elem_index_get(v));
}
}
MEM_freeN(done_verts);
bm->spacearr_dirty |= BM_SPACEARR_DIRTY;
}
void BM_lnorspace_rebuild(BMesh *bm, bool preserve_clnor)
{
BLI_assert(bm->lnor_spacearr != NULL);
if (!(bm->spacearr_dirty & (BM_SPACEARR_DIRTY | BM_SPACEARR_DIRTY_ALL))) {
return;
}
BMFace *f;
BMLoop *l;
BMIter fiter, liter;
float(*r_lnors)[3] = MEM_callocN(sizeof(*r_lnors) * bm->totloop, __func__);
float(*oldnors)[3] = preserve_clnor ? MEM_mallocN(sizeof(*oldnors) * bm->totloop, __func__) :
NULL;
int cd_loop_clnors_offset = CustomData_get_offset(&bm->ldata, CD_CUSTOMLOOPNORMAL);
BM_mesh_elem_index_ensure(bm, BM_LOOP);
if (preserve_clnor) {
BLI_assert(bm->lnor_spacearr->lspacearr != NULL);
BM_ITER_MESH (f, &fiter, bm, BM_FACES_OF_MESH) {
BM_ITER_ELEM (l, &liter, f, BM_LOOPS_OF_FACE) {
if (BM_ELEM_API_FLAG_TEST(l, BM_LNORSPACE_UPDATE) ||
bm->spacearr_dirty & BM_SPACEARR_DIRTY_ALL) {
short(*clnor)[2] = BM_ELEM_CD_GET_VOID_P(l, cd_loop_clnors_offset);
int l_index = BM_elem_index_get(l);
BKE_lnor_space_custom_data_to_normal(
bm->lnor_spacearr->lspacearr[l_index], *clnor, oldnors[l_index]);
}
}
}
}
if (bm->spacearr_dirty & BM_SPACEARR_DIRTY_ALL) {
BKE_lnor_spacearr_clear(bm->lnor_spacearr);
}
BM_loops_calc_normal_vcos(bm,
NULL,
NULL,
NULL,
true,
M_PI,
r_lnors,
bm->lnor_spacearr,
NULL,
cd_loop_clnors_offset,
true);
MEM_freeN(r_lnors);
BM_ITER_MESH (f, &fiter, bm, BM_FACES_OF_MESH) {
BM_ITER_ELEM (l, &liter, f, BM_LOOPS_OF_FACE) {
if (BM_ELEM_API_FLAG_TEST(l, BM_LNORSPACE_UPDATE) ||
bm->spacearr_dirty & BM_SPACEARR_DIRTY_ALL) {
if (preserve_clnor) {
short(*clnor)[2] = BM_ELEM_CD_GET_VOID_P(l, cd_loop_clnors_offset);
int l_index = BM_elem_index_get(l);
BKE_lnor_space_custom_normal_to_data(
bm->lnor_spacearr->lspacearr[l_index], oldnors[l_index], *clnor);
}
BM_ELEM_API_FLAG_DISABLE(l, BM_LNORSPACE_UPDATE);
}
}
}
MEM_SAFE_FREE(oldnors);
bm->spacearr_dirty &= ~(BM_SPACEARR_DIRTY | BM_SPACEARR_DIRTY_ALL);
#ifndef NDEBUG
BM_lnorspace_err(bm);
#endif
}
/**
* \warning This function sets #BM_ELEM_TAG on loops & edges via #bm_mesh_loops_calc_normals,
* take care to run this before setting up tags.
*/
void BM_lnorspace_update(BMesh *bm)
{
if (bm->lnor_spacearr == NULL) {
bm->lnor_spacearr = MEM_callocN(sizeof(*bm->lnor_spacearr), __func__);
}
if (bm->lnor_spacearr->lspacearr == NULL) {
float(*lnors)[3] = MEM_callocN(sizeof(*lnors) * bm->totloop, __func__);
BM_lnorspacearr_store(bm, lnors);
MEM_freeN(lnors);
}
else if (bm->spacearr_dirty & (BM_SPACEARR_DIRTY | BM_SPACEARR_DIRTY_ALL)) {
BM_lnorspace_rebuild(bm, false);
}
}
void BM_normals_loops_edges_tag(BMesh *bm, const bool do_edges)
{
BMFace *f;
BMEdge *e;
BMIter fiter, eiter;
BMLoop *l_curr, *l_first;
if (do_edges) {
int index_edge;
BM_ITER_MESH_INDEX (e, &eiter, bm, BM_EDGES_OF_MESH, index_edge) {
BMLoop *l_a, *l_b;
BM_elem_index_set(e, index_edge); /* set_inline */
BM_elem_flag_disable(e, BM_ELEM_TAG);
if (BM_edge_loop_pair(e, &l_a, &l_b)) {
if (BM_elem_flag_test(e, BM_ELEM_SMOOTH) && l_a->v != l_b->v) {
BM_elem_flag_enable(e, BM_ELEM_TAG);
}
}
}
bm->elem_index_dirty &= ~BM_EDGE;
}
int index_face, index_loop = 0;
BM_ITER_MESH_INDEX (f, &fiter, bm, BM_FACES_OF_MESH, index_face) {
BM_elem_index_set(f, index_face); /* set_inline */
l_curr = l_first = BM_FACE_FIRST_LOOP(f);
do {
BM_elem_index_set(l_curr, index_loop++); /* set_inline */
BM_elem_flag_disable(l_curr, BM_ELEM_TAG);
} while ((l_curr = l_curr->next) != l_first);
}
bm->elem_index_dirty &= ~(BM_FACE | BM_LOOP);
}
/**
* Auxiliary function only used by rebuild to detect if any spaces were not marked as invalid.
* Reports error if any of the lnor spaces change after rebuilding, meaning that all the possible
* lnor spaces to be rebuilt were not correctly marked.
*/
#ifndef NDEBUG
void BM_lnorspace_err(BMesh *bm)
{
bm->spacearr_dirty |= BM_SPACEARR_DIRTY_ALL;
bool clear = true;
MLoopNorSpaceArray *temp = MEM_callocN(sizeof(*temp), __func__);
temp->lspacearr = NULL;
BKE_lnor_spacearr_init(temp, bm->totloop, MLNOR_SPACEARR_BMLOOP_PTR);
int cd_loop_clnors_offset = CustomData_get_offset(&bm->ldata, CD_CUSTOMLOOPNORMAL);
float(*lnors)[3] = MEM_callocN(sizeof(*lnors) * bm->totloop, __func__);
BM_loops_calc_normal_vcos(
bm, NULL, NULL, NULL, true, M_PI, lnors, temp, NULL, cd_loop_clnors_offset, true);
for (int i = 0; i < bm->totloop; i++) {
int j = 0;
j += compare_ff(
temp->lspacearr[i]->ref_alpha, bm->lnor_spacearr->lspacearr[i]->ref_alpha, 1e-4f);
j += compare_ff(
temp->lspacearr[i]->ref_beta, bm->lnor_spacearr->lspacearr[i]->ref_beta, 1e-4f);
j += compare_v3v3(
temp->lspacearr[i]->vec_lnor, bm->lnor_spacearr->lspacearr[i]->vec_lnor, 1e-4f);
j += compare_v3v3(
temp->lspacearr[i]->vec_ortho, bm->lnor_spacearr->lspacearr[i]->vec_ortho, 1e-4f);
j += compare_v3v3(
temp->lspacearr[i]->vec_ref, bm->lnor_spacearr->lspacearr[i]->vec_ref, 1e-4f);
if (j != 5) {
clear = false;
break;
}
}
BKE_lnor_spacearr_free(temp);
MEM_freeN(temp);
MEM_freeN(lnors);
BLI_assert(clear);
bm->spacearr_dirty &= ~BM_SPACEARR_DIRTY_ALL;
}
#endif
static void bm_loop_normal_mark_indiv_do_loop(BMLoop *l,
BLI_bitmap *loops,
MLoopNorSpaceArray *lnor_spacearr,
int *totloopsel,
const bool do_all_loops_of_vert)
{
if (l != NULL) {
const int l_idx = BM_elem_index_get(l);
if (!BLI_BITMAP_TEST(loops, l_idx)) {
/* If vert and face selected share a loop, mark it for editing. */
BLI_BITMAP_ENABLE(loops, l_idx);
(*totloopsel)++;
if (do_all_loops_of_vert) {
/* If required, also mark all loops shared by that vertex.
* This is needed when loop spaces may change
* (i.e. when some faces or edges might change of smooth/sharp status). */
BMIter liter;
BMLoop *lfan;
BM_ITER_ELEM (lfan, &liter, l->v, BM_LOOPS_OF_VERT) {
const int lfan_idx = BM_elem_index_get(lfan);
if (!BLI_BITMAP_TEST(loops, lfan_idx)) {
BLI_BITMAP_ENABLE(loops, lfan_idx);
(*totloopsel)++;
}
}
}
else {
/* Mark all loops in same loop normal space (aka smooth fan). */
if ((lnor_spacearr->lspacearr[l_idx]->flags & MLNOR_SPACE_IS_SINGLE) == 0) {
for (LinkNode *node = lnor_spacearr->lspacearr[l_idx]->loops; node; node = node->next) {
const int lfan_idx = BM_elem_index_get((BMLoop *)node->link);
if (!BLI_BITMAP_TEST(loops, lfan_idx)) {
BLI_BITMAP_ENABLE(loops, lfan_idx);
(*totloopsel)++;
}
}
}
}
}
}
}
/* Mark the individual clnors to be edited, if multiple selection methods are used. */
static int bm_loop_normal_mark_indiv(BMesh *bm, BLI_bitmap *loops, const bool do_all_loops_of_vert)
{
BMEditSelection *ese, *ese_prev;
int totloopsel = 0;
const bool sel_verts = (bm->selectmode & SCE_SELECT_VERTEX) != 0;
const bool sel_edges = (bm->selectmode & SCE_SELECT_EDGE) != 0;
const bool sel_faces = (bm->selectmode & SCE_SELECT_FACE) != 0;
const bool use_sel_face_history = sel_faces && (sel_edges || sel_verts);
BM_mesh_elem_index_ensure(bm, BM_LOOP);
BLI_assert(bm->lnor_spacearr != NULL);
BLI_assert(bm->lnor_spacearr->data_type == MLNOR_SPACEARR_BMLOOP_PTR);
if (use_sel_face_history) {
/* Using face history allows to select a single loop from a single face...
* Note that this is On² piece of code,
* but it is not designed to be used with huge selection sets,
* rather with only a few items selected at most.*/
/* Goes from last selected to the first selected element. */
for (ese = bm->selected.last; ese; ese = ese->prev) {
if (ese->htype == BM_FACE) {
/* If current face is selected,
* then any verts to be edited must have been selected before it. */
for (ese_prev = ese->prev; ese_prev; ese_prev = ese_prev->prev) {
if (ese_prev->htype == BM_VERT) {
bm_loop_normal_mark_indiv_do_loop(
BM_face_vert_share_loop((BMFace *)ese->ele, (BMVert *)ese_prev->ele),
loops,
bm->lnor_spacearr,
&totloopsel,
do_all_loops_of_vert);
}
else if (ese_prev->htype == BM_EDGE) {
BMEdge *e = (BMEdge *)ese_prev->ele;
bm_loop_normal_mark_indiv_do_loop(BM_face_vert_share_loop((BMFace *)ese->ele, e->v1),
loops,
bm->lnor_spacearr,
&totloopsel,
do_all_loops_of_vert);
bm_loop_normal_mark_indiv_do_loop(BM_face_vert_share_loop((BMFace *)ese->ele, e->v2),
loops,
bm->lnor_spacearr,
&totloopsel,
do_all_loops_of_vert);
}
}
}
}
}
else {
if (sel_faces) {
/* Only select all loops of selected faces. */
BMLoop *l;
BMFace *f;
BMIter liter, fiter;
BM_ITER_MESH (f, &fiter, bm, BM_FACES_OF_MESH) {
if (BM_elem_flag_test(f, BM_ELEM_SELECT)) {
BM_ITER_ELEM (l, &liter, f, BM_LOOPS_OF_FACE) {
bm_loop_normal_mark_indiv_do_loop(
l, loops, bm->lnor_spacearr, &totloopsel, do_all_loops_of_vert);
}
}
}
}
if (sel_edges) {
/* Only select all loops of selected edges. */
BMLoop *l;
BMEdge *e;
BMIter liter, eiter;
BM_ITER_MESH (e, &eiter, bm, BM_EDGES_OF_MESH) {
if (BM_elem_flag_test(e, BM_ELEM_SELECT)) {
BM_ITER_ELEM (l, &liter, e, BM_LOOPS_OF_EDGE) {
bm_loop_normal_mark_indiv_do_loop(
l, loops, bm->lnor_spacearr, &totloopsel, do_all_loops_of_vert);
/* Loops actually 'have' two edges, or said otherwise, a selected edge actually selects
* *two* loops in each of its faces. We have to find the other one too. */
if (BM_vert_in_edge(e, l->next->v)) {
bm_loop_normal_mark_indiv_do_loop(
l->next, loops, bm->lnor_spacearr, &totloopsel, do_all_loops_of_vert);
}
else {
BLI_assert(BM_vert_in_edge(e, l->prev->v));
bm_loop_normal_mark_indiv_do_loop(
l->prev, loops, bm->lnor_spacearr, &totloopsel, do_all_loops_of_vert);
}
}
}
}
}
if (sel_verts) {
/* Select all loops of selected verts. */
BMLoop *l;
BMVert *v;
BMIter liter, viter;
BM_ITER_MESH (v, &viter, bm, BM_VERTS_OF_MESH) {
if (BM_elem_flag_test(v, BM_ELEM_SELECT)) {
BM_ITER_ELEM (l, &liter, v, BM_LOOPS_OF_VERT) {
bm_loop_normal_mark_indiv_do_loop(
l, loops, bm->lnor_spacearr, &totloopsel, do_all_loops_of_vert);
}
}
}
}
}
return totloopsel;
}
static void loop_normal_editdata_init(
BMesh *bm, BMLoopNorEditData *lnor_ed, BMVert *v, BMLoop *l, const int offset)
{
BLI_assert(bm->lnor_spacearr != NULL);
BLI_assert(bm->lnor_spacearr->lspacearr != NULL);
const int l_index = BM_elem_index_get(l);
short *clnors_data = BM_ELEM_CD_GET_VOID_P(l, offset);
lnor_ed->loop_index = l_index;
lnor_ed->loop = l;
float custom_normal[3];
BKE_lnor_space_custom_data_to_normal(
bm->lnor_spacearr->lspacearr[l_index], clnors_data, custom_normal);
lnor_ed->clnors_data = clnors_data;
copy_v3_v3(lnor_ed->nloc, custom_normal);
copy_v3_v3(lnor_ed->niloc, custom_normal);
lnor_ed->loc = v->co;
}
BMLoopNorEditDataArray *BM_loop_normal_editdata_array_init(BMesh *bm,
const bool do_all_loops_of_vert)
{
BMLoop *l;
BMVert *v;
BMIter liter, viter;
int totloopsel = 0;
BLI_assert(bm->spacearr_dirty == 0);
BMLoopNorEditDataArray *lnors_ed_arr = MEM_callocN(sizeof(*lnors_ed_arr), __func__);
lnors_ed_arr->lidx_to_lnor_editdata = MEM_callocN(
sizeof(*lnors_ed_arr->lidx_to_lnor_editdata) * bm->totloop, __func__);
if (!CustomData_has_layer(&bm->ldata, CD_CUSTOMLOOPNORMAL)) {
BM_data_layer_add(bm, &bm->ldata, CD_CUSTOMLOOPNORMAL);
}
const int cd_custom_normal_offset = CustomData_get_offset(&bm->ldata, CD_CUSTOMLOOPNORMAL);
BM_mesh_elem_index_ensure(bm, BM_LOOP);
BLI_bitmap *loops = BLI_BITMAP_NEW(bm->totloop, __func__);
/* This function define loop normals to edit, based on selection modes and history. */
totloopsel = bm_loop_normal_mark_indiv(bm, loops, do_all_loops_of_vert);
if (totloopsel) {
BMLoopNorEditData *lnor_ed = lnors_ed_arr->lnor_editdata = MEM_mallocN(
sizeof(*lnor_ed) * totloopsel, __func__);
BM_ITER_MESH (v, &viter, bm, BM_VERTS_OF_MESH) {
BM_ITER_ELEM (l, &liter, v, BM_LOOPS_OF_VERT) {
if (BLI_BITMAP_TEST(loops, BM_elem_index_get(l))) {
loop_normal_editdata_init(bm, lnor_ed, v, l, cd_custom_normal_offset);
lnors_ed_arr->lidx_to_lnor_editdata[BM_elem_index_get(l)] = lnor_ed;
lnor_ed++;
}
}
}
lnors_ed_arr->totloop = totloopsel;
}
MEM_freeN(loops);
lnors_ed_arr->cd_custom_normal_offset = cd_custom_normal_offset;
return lnors_ed_arr;
}
void BM_loop_normal_editdata_array_free(BMLoopNorEditDataArray *lnors_ed_arr)
{
MEM_SAFE_FREE(lnors_ed_arr->lnor_editdata);
MEM_SAFE_FREE(lnors_ed_arr->lidx_to_lnor_editdata);
MEM_freeN(lnors_ed_arr);
}
/**
* \warning This function sets #BM_ELEM_TAG on loops & edges via #bm_mesh_loops_calc_normals,
* take care to run this before setting up tags.
*/
bool BM_custom_loop_normals_to_vector_layer(BMesh *bm)
{
BMFace *f;
BMLoop *l;
BMIter liter, fiter;
if (!CustomData_has_layer(&bm->ldata, CD_CUSTOMLOOPNORMAL)) {
return false;
}
BM_lnorspace_update(bm);
BM_mesh_elem_index_ensure(bm, BM_LOOP);
/* Create a loop normal layer. */
if (!CustomData_has_layer(&bm->ldata, CD_NORMAL)) {
BM_data_layer_add(bm, &bm->ldata, CD_NORMAL);
CustomData_set_layer_flag(&bm->ldata, CD_NORMAL, CD_FLAG_TEMPORARY);
}
const int cd_custom_normal_offset = CustomData_get_offset(&bm->ldata, CD_CUSTOMLOOPNORMAL);
const int cd_normal_offset = CustomData_get_offset(&bm->ldata, CD_NORMAL);
BM_ITER_MESH (f, &fiter, bm, BM_FACES_OF_MESH) {
BM_ITER_ELEM (l, &liter, f, BM_LOOPS_OF_FACE) {
const int l_index = BM_elem_index_get(l);
const short *clnors_data = BM_ELEM_CD_GET_VOID_P(l, cd_custom_normal_offset);
float *normal = BM_ELEM_CD_GET_VOID_P(l, cd_normal_offset);
BKE_lnor_space_custom_data_to_normal(
bm->lnor_spacearr->lspacearr[l_index], clnors_data, normal);
}
}
return true;
}
void BM_custom_loop_normals_from_vector_layer(BMesh *bm, bool add_sharp_edges)
{
if (!CustomData_has_layer(&bm->ldata, CD_CUSTOMLOOPNORMAL) ||
!CustomData_has_layer(&bm->ldata, CD_NORMAL)) {
return;
}
const int cd_custom_normal_offset = CustomData_get_offset(&bm->ldata, CD_CUSTOMLOOPNORMAL);
const int cd_normal_offset = CustomData_get_offset(&bm->ldata, CD_NORMAL);
if (bm->lnor_spacearr == NULL) {
bm->lnor_spacearr = MEM_callocN(sizeof(*bm->lnor_spacearr), __func__);
}
bm_mesh_loops_custom_normals_set(bm,
NULL,
NULL,
NULL,
bm->lnor_spacearr,
NULL,
cd_custom_normal_offset,
NULL,
cd_normal_offset,
add_sharp_edges);
bm->spacearr_dirty &= ~(BM_SPACEARR_DIRTY | BM_SPACEARR_DIRTY_ALL);
}
/**
* \brief BMesh Begin Edit
*
* Functions for setting up a mesh for editing and cleaning up after
* the editing operations are done. These are called by the tools/operator
* API for each time a tool is executed.
*/
void bmesh_edit_begin(BMesh *UNUSED(bm), BMOpTypeFlag UNUSED(type_flag))
{
/* Most operators seem to be using BMO_OPTYPE_FLAG_UNTAN_MULTIRES to change the MDisps to
* absolute space during mesh edits. With this enabled, changes to the topology
* (loop cuts, edge subdivides, etc) are not reflected in the higher levels of
* the mesh at all, which doesn't seem right. Turning off completely for now,
* until this is shown to be better for certain types of mesh edits. */
#ifdef BMOP_UNTAN_MULTIRES_ENABLED
/* switch multires data out of tangent space */
if ((type_flag & BMO_OPTYPE_FLAG_UNTAN_MULTIRES) &&
CustomData_has_layer(&bm->ldata, CD_MDISPS)) {
bmesh_mdisps_space_set(bm, MULTIRES_SPACE_TANGENT, MULTIRES_SPACE_ABSOLUTE);
/* ensure correct normals, if possible */
bmesh_rationalize_normals(bm, 0);
BM_mesh_normals_update(bm);
}
#endif
}
/**
* \brief BMesh End Edit
*/
void bmesh_edit_end(BMesh *bm, BMOpTypeFlag type_flag)
{
ListBase select_history;
/* BMO_OPTYPE_FLAG_UNTAN_MULTIRES disabled for now, see comment above in bmesh_edit_begin. */
#ifdef BMOP_UNTAN_MULTIRES_ENABLED
/* switch multires data into tangent space */
if ((flag & BMO_OPTYPE_FLAG_UNTAN_MULTIRES) && CustomData_has_layer(&bm->ldata, CD_MDISPS)) {
/* set normals to their previous winding */
bmesh_rationalize_normals(bm, 1);
bmesh_mdisps_space_set(bm, MULTIRES_SPACE_ABSOLUTE, MULTIRES_SPACE_TANGENT);
}
else if (flag & BMO_OP_FLAG_RATIONALIZE_NORMALS) {
bmesh_rationalize_normals(bm, 1);
}
#endif
/* compute normals, clear temp flags and flush selections */
if (type_flag & BMO_OPTYPE_FLAG_NORMALS_CALC) {
bm->spacearr_dirty |= BM_SPACEARR_DIRTY_ALL;
BM_mesh_normals_update(bm);
}
if ((type_flag & BMO_OPTYPE_FLAG_SELECT_VALIDATE) == 0) {
select_history = bm->selected;
BLI_listbase_clear(&bm->selected);
}
if (type_flag & BMO_OPTYPE_FLAG_SELECT_FLUSH) {
BM_mesh_select_mode_flush(bm);
}
if ((type_flag & BMO_OPTYPE_FLAG_SELECT_VALIDATE) == 0) {
bm->selected = select_history;
}
if (type_flag & BMO_OPTYPE_FLAG_INVALIDATE_CLNOR_ALL) {
bm->spacearr_dirty |= BM_SPACEARR_DIRTY_ALL;
}
}
void BM_mesh_elem_index_ensure_ex(BMesh *bm, const char htype, int elem_offset[4])
{
#ifdef DEBUG
BM_ELEM_INDEX_VALIDATE(bm, "Should Never Fail!", __func__);
#endif
if (elem_offset == NULL) {
/* Simple case. */
const char htype_needed = bm->elem_index_dirty & htype;
if (htype_needed == 0) {
goto finally;
}
}
if (htype & BM_VERT) {
if ((bm->elem_index_dirty & BM_VERT) || (elem_offset && elem_offset[0])) {
BMIter iter;
BMElem *ele;
int index = elem_offset ? elem_offset[0] : 0;
BM_ITER_MESH (ele, &iter, bm, BM_VERTS_OF_MESH) {
BM_elem_index_set(ele, index++); /* set_ok */
}
BLI_assert(elem_offset || index == bm->totvert);
}
else {
// printf("%s: skipping vert index calc!\n", __func__);
}
}
if (htype & BM_EDGE) {
if ((bm->elem_index_dirty & BM_EDGE) || (elem_offset && elem_offset[1])) {
BMIter iter;
BMElem *ele;
int index = elem_offset ? elem_offset[1] : 0;
BM_ITER_MESH (ele, &iter, bm, BM_EDGES_OF_MESH) {
BM_elem_index_set(ele, index++); /* set_ok */
}
BLI_assert(elem_offset || index == bm->totedge);
}
else {
// printf("%s: skipping edge index calc!\n", __func__);
}
}
if (htype & (BM_FACE | BM_LOOP)) {
if ((bm->elem_index_dirty & (BM_FACE | BM_LOOP)) ||
(elem_offset && (elem_offset[2] || elem_offset[3]))) {
BMIter iter;
BMElem *ele;
const bool update_face = (htype & BM_FACE) && (bm->elem_index_dirty & BM_FACE);
const bool update_loop = (htype & BM_LOOP) && (bm->elem_index_dirty & BM_LOOP);
int index_loop = elem_offset ? elem_offset[2] : 0;
int index = elem_offset ? elem_offset[3] : 0;
BM_ITER_MESH (ele, &iter, bm, BM_FACES_OF_MESH) {
if (update_face) {
BM_elem_index_set(ele, index++); /* set_ok */
}
if (update_loop) {
BMLoop *l_iter, *l_first;
l_iter = l_first = BM_FACE_FIRST_LOOP((BMFace *)ele);
do {
BM_elem_index_set(l_iter, index_loop++); /* set_ok */
} while ((l_iter = l_iter->next) != l_first);
}
}
BLI_assert(elem_offset || !update_face || index == bm->totface);
if (update_loop) {
BLI_assert(elem_offset || !update_loop || index_loop == bm->totloop);
}
}
else {
// printf("%s: skipping face/loop index calc!\n", __func__);
}
}
finally:
bm->elem_index_dirty &= ~htype;
if (elem_offset) {
if (htype & BM_VERT) {
elem_offset[0] += bm->totvert;
if (elem_offset[0] != bm->totvert) {
bm->elem_index_dirty |= BM_VERT;
}
}
if (htype & BM_EDGE) {
elem_offset[1] += bm->totedge;
if (elem_offset[1] != bm->totedge) {
bm->elem_index_dirty |= BM_EDGE;
}
}
if (htype & BM_LOOP) {
elem_offset[2] += bm->totloop;
if (elem_offset[2] != bm->totloop) {
bm->elem_index_dirty |= BM_LOOP;
}
}
if (htype & BM_FACE) {
elem_offset[3] += bm->totface;
if (elem_offset[3] != bm->totface) {
bm->elem_index_dirty |= BM_FACE;
}
}
}
}
void BM_mesh_elem_index_ensure(BMesh *bm, const char htype)
{
BM_mesh_elem_index_ensure_ex(bm, htype, NULL);
}
/**
* Array checking/setting macros
*
* Currently vert/edge/loop/face index data is being abused, in a few areas of the code.
*
* To avoid correcting them afterwards, set 'bm->elem_index_dirty' however its possible
* this flag is set incorrectly which could crash blender.
*
* Code that calls this functions may depend on dirty indices on being set.
* Keep this function read-only.
*/
void BM_mesh_elem_index_validate(
BMesh *bm, const char *location, const char *func, const char *msg_a, const char *msg_b)
{
const char iter_types[3] = {BM_VERTS_OF_MESH, BM_EDGES_OF_MESH, BM_FACES_OF_MESH};
const char flag_types[3] = {BM_VERT, BM_EDGE, BM_FACE};
const char *type_names[3] = {"vert", "edge", "face"};
BMIter iter;
BMElem *ele;
int i;
bool is_any_error = 0;
for (i = 0; i < 3; i++) {
const bool is_dirty = (flag_types[i] & bm->elem_index_dirty) != 0;
int index = 0;
bool is_error = false;
int err_val = 0;
int err_idx = 0;
BM_ITER_MESH (ele, &iter, bm, iter_types[i]) {
if (!is_dirty) {
if (BM_elem_index_get(ele) != index) {
err_val = BM_elem_index_get(ele);
err_idx = index;
is_error = true;
break;
}
}
index++;
}
if ((is_error == true) && (is_dirty == false)) {
is_any_error = true;
fprintf(stderr,
"Invalid Index: at %s, %s, %s[%d] invalid index %d, '%s', '%s'\n",
location,
func,
type_names[i],
err_idx,
err_val,
msg_a,
msg_b);
}
else if ((is_error == false) && (is_dirty == true)) {
#if 0 /* mostly annoying */
/* dirty may have been incorrectly set */
fprintf(stderr,
"Invalid Dirty: at %s, %s (%s), dirty flag was set but all index values are "
"correct, '%s', '%s'\n",
location,
func,
type_names[i],
msg_a,
msg_b);
#endif
}
}
#if 0 /* mostly annoying, even in debug mode */
# ifdef DEBUG
if (is_any_error == 0) {
fprintf(stderr, "Valid Index Success: at %s, %s, '%s', '%s'\n", location, func, msg_a, msg_b);
}
# endif
#endif
(void)is_any_error; /* shut up the compiler */
}
/* debug check only - no need to optimize */
#ifndef NDEBUG
bool BM_mesh_elem_table_check(BMesh *bm)
{
BMIter iter;
BMElem *ele;
int i;
if (bm->vtable && ((bm->elem_table_dirty & BM_VERT) == 0)) {
BM_ITER_MESH_INDEX (ele, &iter, bm, BM_VERTS_OF_MESH, i) {
if (ele != (BMElem *)bm->vtable[i]) {
return false;
}
}
}
if (bm->etable && ((bm->elem_table_dirty & BM_EDGE) == 0)) {
BM_ITER_MESH_INDEX (ele, &iter, bm, BM_EDGES_OF_MESH, i) {
if (ele != (BMElem *)bm->etable[i]) {
return false;
}
}
}
if (bm->ftable && ((bm->elem_table_dirty & BM_FACE) == 0)) {
BM_ITER_MESH_INDEX (ele, &iter, bm, BM_FACES_OF_MESH, i) {
if (ele != (BMElem *)bm->ftable[i]) {
return false;
}
}
}
return true;
}
#endif
void BM_mesh_elem_table_ensure(BMesh *bm, const char htype)
{
/* assume if the array is non-null then its valid and no need to recalc */
const char htype_needed =
(((bm->vtable && ((bm->elem_table_dirty & BM_VERT) == 0)) ? 0 : BM_VERT) |
((bm->etable && ((bm->elem_table_dirty & BM_EDGE) == 0)) ? 0 : BM_EDGE) |
((bm->ftable && ((bm->elem_table_dirty & BM_FACE) == 0)) ? 0 : BM_FACE)) &
htype;
BLI_assert((htype & ~BM_ALL_NOLOOP) == 0);
/* in debug mode double check we didn't need to recalculate */
BLI_assert(BM_mesh_elem_table_check(bm) == true);
if (htype_needed == 0) {
goto finally;
}
if (htype_needed & BM_VERT) {
if (bm->vtable && bm->totvert <= bm->vtable_tot && bm->totvert * 2 >= bm->vtable_tot) {
/* pass (re-use the array) */
}
else {
if (bm->vtable) {
MEM_freeN(bm->vtable);
}
bm->vtable = MEM_mallocN(sizeof(void **) * bm->totvert, "bm->vtable");
bm->vtable_tot = bm->totvert;
}
}
if (htype_needed & BM_EDGE) {
if (bm->etable && bm->totedge <= bm->etable_tot && bm->totedge * 2 >= bm->etable_tot) {
/* pass (re-use the array) */
}
else {
if (bm->etable) {
MEM_freeN(bm->etable);
}
bm->etable = MEM_mallocN(sizeof(void **) * bm->totedge, "bm->etable");
bm->etable_tot = bm->totedge;
}
}
if (htype_needed & BM_FACE) {
if (bm->ftable && bm->totface <= bm->ftable_tot && bm->totface * 2 >= bm->ftable_tot) {
/* pass (re-use the array) */
}
else {
if (bm->ftable) {
MEM_freeN(bm->ftable);
}
bm->ftable = MEM_mallocN(sizeof(void **) * bm->totface, "bm->ftable");
bm->ftable_tot = bm->totface;
}
}
if (htype_needed & BM_VERT) {
BM_iter_as_array(bm, BM_VERTS_OF_MESH, NULL, (void **)bm->vtable, bm->totvert);
}
if (htype_needed & BM_EDGE) {
BM_iter_as_array(bm, BM_EDGES_OF_MESH, NULL, (void **)bm->etable, bm->totedge);
}
if (htype_needed & BM_FACE) {
BM_iter_as_array(bm, BM_FACES_OF_MESH, NULL, (void **)bm->ftable, bm->totface);
}
finally:
/* Only clear dirty flags when all the pointers and data are actually valid.
* This prevents possible threading issues when dirty flag check failed but
* data wasn't ready still.
*/
bm->elem_table_dirty &= ~htype_needed;
}
/* use BM_mesh_elem_table_ensure where possible to avoid full rebuild */
void BM_mesh_elem_table_init(BMesh *bm, const char htype)
{
BLI_assert((htype & ~BM_ALL_NOLOOP) == 0);
/* force recalc */
BM_mesh_elem_table_free(bm, BM_ALL_NOLOOP);
BM_mesh_elem_table_ensure(bm, htype);
}
void BM_mesh_elem_table_free(BMesh *bm, const char htype)
{
if (htype & BM_VERT) {
MEM_SAFE_FREE(bm->vtable);
}
if (htype & BM_EDGE) {
MEM_SAFE_FREE(bm->etable);
}
if (htype & BM_FACE) {
MEM_SAFE_FREE(bm->ftable);
}
}
BMVert *BM_vert_at_index_find(BMesh *bm, const int index)
{
return BLI_mempool_findelem(bm->vpool, index);
}
BMEdge *BM_edge_at_index_find(BMesh *bm, const int index)
{
return BLI_mempool_findelem(bm->epool, index);
}
BMFace *BM_face_at_index_find(BMesh *bm, const int index)
{
return BLI_mempool_findelem(bm->fpool, index);
}
BMLoop *BM_loop_at_index_find(BMesh *bm, const int index)
{
BMIter iter;
BMFace *f;
int i = index;
BM_ITER_MESH (f, &iter, bm, BM_FACES_OF_MESH) {
if (i < f->len) {
BMLoop *l_first, *l_iter;
l_iter = l_first = BM_FACE_FIRST_LOOP(f);
do {
if (i == 0) {
return l_iter;
}
i -= 1;
} while ((l_iter = l_iter->next) != l_first);
}
i -= f->len;
}
return NULL;
}
/**
* Use lookup table when available, else use slower find functions.
*
* \note Try to use #BM_mesh_elem_table_ensure instead.
*/
BMVert *BM_vert_at_index_find_or_table(BMesh *bm, const int index)
{
if ((bm->elem_table_dirty & BM_VERT) == 0) {
return (index < bm->totvert) ? bm->vtable[index] : NULL;
}
return BM_vert_at_index_find(bm, index);
}
BMEdge *BM_edge_at_index_find_or_table(BMesh *bm, const int index)
{
if ((bm->elem_table_dirty & BM_EDGE) == 0) {
return (index < bm->totedge) ? bm->etable[index] : NULL;
}
return BM_edge_at_index_find(bm, index);
}
BMFace *BM_face_at_index_find_or_table(BMesh *bm, const int index)
{
if ((bm->elem_table_dirty & BM_FACE) == 0) {
return (index < bm->totface) ? bm->ftable[index] : NULL;
}
return BM_face_at_index_find(bm, index);
}
/**
* Return the amount of element of type 'type' in a given bmesh.
*/
int BM_mesh_elem_count(BMesh *bm, const char htype)
{
BLI_assert((htype & ~BM_ALL_NOLOOP) == 0);
switch (htype) {
case BM_VERT:
return bm->totvert;
case BM_EDGE:
return bm->totedge;
case BM_FACE:
return bm->totface;
default: {
BLI_assert(0);
return 0;
}
}
}
/**
* Remaps the vertices, edges and/or faces of the bmesh as indicated by vert/edge/face_idx arrays
* (xxx_idx[org_index] = new_index).
*
* A NULL array means no changes.
*
* \note
* - Does not mess with indices, just sets elem_index_dirty flag.
* - For verts/edges/faces only (as loops must remain "ordered" and "aligned"
* on a per-face basis...).
*
* \warning Be careful if you keep pointers to affected BM elements,
* or arrays, when using this func!
*/
void BM_mesh_remap(BMesh *bm, const uint *vert_idx, const uint *edge_idx, const uint *face_idx)
{
/* Mapping old to new pointers. */
GHash *vptr_map = NULL, *eptr_map = NULL, *fptr_map = NULL;
BMIter iter, iterl;
BMVert *ve;
BMEdge *ed;
BMFace *fa;
BMLoop *lo;
if (!(vert_idx || edge_idx || face_idx)) {
return;
}
BM_mesh_elem_table_ensure(
bm, (vert_idx ? BM_VERT : 0) | (edge_idx ? BM_EDGE : 0) | (face_idx ? BM_FACE : 0));
/* Remap Verts */
if (vert_idx) {
BMVert **verts_pool, *verts_copy, **vep;
int i, totvert = bm->totvert;
const uint *new_idx;
/* Special case: Python uses custom - data layers to hold PyObject references.
* These have to be kept in - place, else the PyObject's we point to, wont point back to us. */
const int cd_vert_pyptr = CustomData_get_offset(&bm->vdata, CD_BM_ELEM_PYPTR);
/* Init the old-to-new vert pointers mapping */
vptr_map = BLI_ghash_ptr_new_ex("BM_mesh_remap vert pointers mapping", bm->totvert);
/* Make a copy of all vertices. */
verts_pool = bm->vtable;
verts_copy = MEM_mallocN(sizeof(BMVert) * totvert, "BM_mesh_remap verts copy");
void **pyptrs = (cd_vert_pyptr != -1) ? MEM_mallocN(sizeof(void *) * totvert, __func__) : NULL;
for (i = totvert, ve = verts_copy + totvert - 1, vep = verts_pool + totvert - 1; i--;
ve--, vep--) {
*ve = **vep;
/* printf("*vep: %p, verts_pool[%d]: %p\n", *vep, i, verts_pool[i]);*/
if (cd_vert_pyptr != -1) {
void **pyptr = BM_ELEM_CD_GET_VOID_P(((BMElem *)ve), cd_vert_pyptr);
pyptrs[i] = *pyptr;
}
}
/* Copy back verts to their new place, and update old2new pointers mapping. */
new_idx = vert_idx + totvert - 1;
ve = verts_copy + totvert - 1;
vep = verts_pool + totvert - 1; /* old, org pointer */
for (i = totvert; i--; new_idx--, ve--, vep--) {
BMVert *new_vep = verts_pool[*new_idx];
*new_vep = *ve;
#if 0
printf(
"mapping vert from %d to %d (%p/%p to %p)\n", i, *new_idx, *vep, verts_pool[i], new_vep);
#endif
BLI_ghash_insert(vptr_map, *vep, new_vep);
if (cd_vert_pyptr != -1) {
void **pyptr = BM_ELEM_CD_GET_VOID_P(((BMElem *)new_vep), cd_vert_pyptr);
*pyptr = pyptrs[*new_idx];
}
}
bm->elem_index_dirty |= BM_VERT;
bm->elem_table_dirty |= BM_VERT;
MEM_freeN(verts_copy);
if (pyptrs) {
MEM_freeN(pyptrs);
}
}
/* Remap Edges */
if (edge_idx) {
BMEdge **edges_pool, *edges_copy, **edp;
int i, totedge = bm->totedge;
const uint *new_idx;
/* Special case: Python uses custom - data layers to hold PyObject references.
* These have to be kept in - place, else the PyObject's we point to, wont point back to us. */
const int cd_edge_pyptr = CustomData_get_offset(&bm->edata, CD_BM_ELEM_PYPTR);
/* Init the old-to-new vert pointers mapping */
eptr_map = BLI_ghash_ptr_new_ex("BM_mesh_remap edge pointers mapping", bm->totedge);
/* Make a copy of all vertices. */
edges_pool = bm->etable;
edges_copy = MEM_mallocN(sizeof(BMEdge) * totedge, "BM_mesh_remap edges copy");
void **pyptrs = (cd_edge_pyptr != -1) ? MEM_mallocN(sizeof(void *) * totedge, __func__) : NULL;
for (i = totedge, ed = edges_copy + totedge - 1, edp = edges_pool + totedge - 1; i--;
ed--, edp--) {
*ed = **edp;
if (cd_edge_pyptr != -1) {
void **pyptr = BM_ELEM_CD_GET_VOID_P(((BMElem *)ed), cd_edge_pyptr);
pyptrs[i] = *pyptr;
}
}
/* Copy back verts to their new place, and update old2new pointers mapping. */
new_idx = edge_idx + totedge - 1;
ed = edges_copy + totedge - 1;
edp = edges_pool + totedge - 1; /* old, org pointer */
for (i = totedge; i--; new_idx--, ed--, edp--) {
BMEdge *new_edp = edges_pool[*new_idx];
*new_edp = *ed;
BLI_ghash_insert(eptr_map, *edp, new_edp);
#if 0
printf(
"mapping edge from %d to %d (%p/%p to %p)\n", i, *new_idx, *edp, edges_pool[i], new_edp);
#endif
if (cd_edge_pyptr != -1) {
void **pyptr = BM_ELEM_CD_GET_VOID_P(((BMElem *)new_edp), cd_edge_pyptr);
*pyptr = pyptrs[*new_idx];
}
}
bm->elem_index_dirty |= BM_EDGE;
bm->elem_table_dirty |= BM_EDGE;
MEM_freeN(edges_copy);
if (pyptrs) {
MEM_freeN(pyptrs);
}
}
/* Remap Faces */
if (face_idx) {
BMFace **faces_pool, *faces_copy, **fap;
int i, totface = bm->totface;
const uint *new_idx;
/* Special case: Python uses custom - data layers to hold PyObject references.
* These have to be kept in - place, else the PyObject's we point to, wont point back to us. */
const int cd_poly_pyptr = CustomData_get_offset(&bm->pdata, CD_BM_ELEM_PYPTR);
/* Init the old-to-new vert pointers mapping */
fptr_map = BLI_ghash_ptr_new_ex("BM_mesh_remap face pointers mapping", bm->totface);
/* Make a copy of all vertices. */
faces_pool = bm->ftable;
faces_copy = MEM_mallocN(sizeof(BMFace) * totface, "BM_mesh_remap faces copy");
void **pyptrs = (cd_poly_pyptr != -1) ? MEM_mallocN(sizeof(void *) * totface, __func__) : NULL;
for (i = totface, fa = faces_copy + totface - 1, fap = faces_pool + totface - 1; i--;
fa--, fap--) {
*fa = **fap;
if (cd_poly_pyptr != -1) {
void **pyptr = BM_ELEM_CD_GET_VOID_P(((BMElem *)fa), cd_poly_pyptr);
pyptrs[i] = *pyptr;
}
}
/* Copy back verts to their new place, and update old2new pointers mapping. */
new_idx = face_idx + totface - 1;
fa = faces_copy + totface - 1;
fap = faces_pool + totface - 1; /* old, org pointer */
for (i = totface; i--; new_idx--, fa--, fap--) {
BMFace *new_fap = faces_pool[*new_idx];
*new_fap = *fa;
BLI_ghash_insert(fptr_map, *fap, new_fap);
if (cd_poly_pyptr != -1) {
void **pyptr = BM_ELEM_CD_GET_VOID_P(((BMElem *)new_fap), cd_poly_pyptr);
*pyptr = pyptrs[*new_idx];
}
}
bm->elem_index_dirty |= BM_FACE | BM_LOOP;
bm->elem_table_dirty |= BM_FACE;
MEM_freeN(faces_copy);
if (pyptrs) {
MEM_freeN(pyptrs);
}
}
/* And now, fix all vertices/edges/faces/loops pointers! */
/* Verts' pointers, only edge pointers... */
if (eptr_map) {
BM_ITER_MESH (ve, &iter, bm, BM_VERTS_OF_MESH) {
/* printf("Vert e: %p -> %p\n", ve->e, BLI_ghash_lookup(eptr_map, ve->e));*/
if (ve->e) {
ve->e = BLI_ghash_lookup(eptr_map, ve->e);
BLI_assert(ve->e);
}
}
}
/* Edges' pointers, only vert pointers (as we don't mess with loops!),
* and - ack! - edge pointers,
* as we have to handle disklinks... */
if (vptr_map || eptr_map) {
BM_ITER_MESH (ed, &iter, bm, BM_EDGES_OF_MESH) {
if (vptr_map) {
/* printf("Edge v1: %p -> %p\n", ed->v1, BLI_ghash_lookup(vptr_map, ed->v1));*/
/* printf("Edge v2: %p -> %p\n", ed->v2, BLI_ghash_lookup(vptr_map, ed->v2));*/
ed->v1 = BLI_ghash_lookup(vptr_map, ed->v1);
ed->v2 = BLI_ghash_lookup(vptr_map, ed->v2);
BLI_assert(ed->v1);
BLI_assert(ed->v2);
}
if (eptr_map) {
/* printf("Edge v1_disk_link prev: %p -> %p\n", ed->v1_disk_link.prev,*/
/* BLI_ghash_lookup(eptr_map, ed->v1_disk_link.prev));*/
/* printf("Edge v1_disk_link next: %p -> %p\n", ed->v1_disk_link.next,*/
/* BLI_ghash_lookup(eptr_map, ed->v1_disk_link.next));*/
/* printf("Edge v2_disk_link prev: %p -> %p\n", ed->v2_disk_link.prev,*/
/* BLI_ghash_lookup(eptr_map, ed->v2_disk_link.prev));*/
/* printf("Edge v2_disk_link next: %p -> %p\n", ed->v2_disk_link.next,*/
/* BLI_ghash_lookup(eptr_map, ed->v2_disk_link.next));*/
ed->v1_disk_link.prev = BLI_ghash_lookup(eptr_map, ed->v1_disk_link.prev);
ed->v1_disk_link.next = BLI_ghash_lookup(eptr_map, ed->v1_disk_link.next);
ed->v2_disk_link.prev = BLI_ghash_lookup(eptr_map, ed->v2_disk_link.prev);
ed->v2_disk_link.next = BLI_ghash_lookup(eptr_map, ed->v2_disk_link.next);
BLI_assert(ed->v1_disk_link.prev);
BLI_assert(ed->v1_disk_link.next);
BLI_assert(ed->v2_disk_link.prev);
BLI_assert(ed->v2_disk_link.next);
}
}
}
/* Faces' pointers (loops, in fact), always needed... */
BM_ITER_MESH (fa, &iter, bm, BM_FACES_OF_MESH) {
BM_ITER_ELEM (lo, &iterl, fa, BM_LOOPS_OF_FACE) {
if (vptr_map) {
/* printf("Loop v: %p -> %p\n", lo->v, BLI_ghash_lookup(vptr_map, lo->v));*/
lo->v = BLI_ghash_lookup(vptr_map, lo->v);
BLI_assert(lo->v);
}
if (eptr_map) {
/* printf("Loop e: %p -> %p\n", lo->e, BLI_ghash_lookup(eptr_map, lo->e));*/
lo->e = BLI_ghash_lookup(eptr_map, lo->e);
BLI_assert(lo->e);
}
if (fptr_map) {
/* printf("Loop f: %p -> %p\n", lo->f, BLI_ghash_lookup(fptr_map, lo->f));*/
lo->f = BLI_ghash_lookup(fptr_map, lo->f);
BLI_assert(lo->f);
}
}
}
/* Selection history */
{
BMEditSelection *ese;
for (ese = bm->selected.first; ese; ese = ese->next) {
switch (ese->htype) {
case BM_VERT:
if (vptr_map) {
ese->ele = BLI_ghash_lookup(vptr_map, ese->ele);
BLI_assert(ese->ele);
}
break;
case BM_EDGE:
if (eptr_map) {
ese->ele = BLI_ghash_lookup(eptr_map, ese->ele);
BLI_assert(ese->ele);
}
break;
case BM_FACE:
if (fptr_map) {
ese->ele = BLI_ghash_lookup(fptr_map, ese->ele);
BLI_assert(ese->ele);
}
break;
}
}
}
if (fptr_map) {
if (bm->act_face) {
bm->act_face = BLI_ghash_lookup(fptr_map, bm->act_face);
BLI_assert(bm->act_face);
}
}
if (vptr_map) {
BLI_ghash_free(vptr_map, NULL, NULL);
}
if (eptr_map) {
BLI_ghash_free(eptr_map, NULL, NULL);
}
if (fptr_map) {
BLI_ghash_free(fptr_map, NULL, NULL);
}
}
/**
* Use new memory pools for this mesh.
*
* \note needed for re-sizing elements (adding/removing tool flags)
* but could also be used for packing fragmented bmeshes.
*/
void BM_mesh_rebuild(BMesh *bm,
const struct BMeshCreateParams *params,
BLI_mempool *vpool_dst,
BLI_mempool *epool_dst,
BLI_mempool *lpool_dst,
BLI_mempool *fpool_dst)
{
const char remap = (vpool_dst ? BM_VERT : 0) | (epool_dst ? BM_EDGE : 0) |
(lpool_dst ? BM_LOOP : 0) | (fpool_dst ? BM_FACE : 0);
BMVert **vtable_dst = (remap & BM_VERT) ? MEM_mallocN(bm->totvert * sizeof(BMVert *), __func__) :
NULL;
BMEdge **etable_dst = (remap & BM_EDGE) ? MEM_mallocN(bm->totedge * sizeof(BMEdge *), __func__) :
NULL;
BMLoop **ltable_dst = (remap & BM_LOOP) ? MEM_mallocN(bm->totloop * sizeof(BMLoop *), __func__) :
NULL;
BMFace **ftable_dst = (remap & BM_FACE) ? MEM_mallocN(bm->totface * sizeof(BMFace *), __func__) :
NULL;
const bool use_toolflags = params->use_toolflags;
if (remap & BM_VERT) {
BMIter iter;
int index;
BMVert *v_src;
BM_ITER_MESH_INDEX (v_src, &iter, bm, BM_VERTS_OF_MESH, index) {
BMVert *v_dst = BLI_mempool_alloc(vpool_dst);
memcpy(v_dst, v_src, sizeof(BMVert));
if (use_toolflags) {
((BMVert_OFlag *)v_dst)->oflags = bm->vtoolflagpool ?
BLI_mempool_calloc(bm->vtoolflagpool) :
NULL;
}
vtable_dst[index] = v_dst;
BM_elem_index_set(v_src, index); /* set_ok */
}
}
if (remap & BM_EDGE) {
BMIter iter;
int index;
BMEdge *e_src;
BM_ITER_MESH_INDEX (e_src, &iter, bm, BM_EDGES_OF_MESH, index) {
BMEdge *e_dst = BLI_mempool_alloc(epool_dst);
memcpy(e_dst, e_src, sizeof(BMEdge));
if (use_toolflags) {
((BMEdge_OFlag *)e_dst)->oflags = bm->etoolflagpool ?
BLI_mempool_calloc(bm->etoolflagpool) :
NULL;
}
etable_dst[index] = e_dst;
BM_elem_index_set(e_src, index); /* set_ok */
}
}
if (remap & (BM_LOOP | BM_FACE)) {
BMIter iter;
int index, index_loop = 0;
BMFace *f_src;
BM_ITER_MESH_INDEX (f_src, &iter, bm, BM_FACES_OF_MESH, index) {
if (remap & BM_FACE) {
BMFace *f_dst = BLI_mempool_alloc(fpool_dst);
memcpy(f_dst, f_src, sizeof(BMFace));
if (use_toolflags) {
((BMFace_OFlag *)f_dst)->oflags = bm->ftoolflagpool ?
BLI_mempool_calloc(bm->ftoolflagpool) :
NULL;
}
ftable_dst[index] = f_dst;
BM_elem_index_set(f_src, index); /* set_ok */
}
/* handle loops */
if (remap & BM_LOOP) {
BMLoop *l_iter_src, *l_first_src;
l_iter_src = l_first_src = BM_FACE_FIRST_LOOP((BMFace *)f_src);
do {
BMLoop *l_dst = BLI_mempool_alloc(lpool_dst);
memcpy(l_dst, l_iter_src, sizeof(BMLoop));
ltable_dst[index_loop] = l_dst;
BM_elem_index_set(l_iter_src, index_loop++); /* set_ok */
} while ((l_iter_src = l_iter_src->next) != l_first_src);
}
}
}
#define MAP_VERT(ele) vtable_dst[BM_elem_index_get(ele)]
#define MAP_EDGE(ele) etable_dst[BM_elem_index_get(ele)]
#define MAP_LOOP(ele) ltable_dst[BM_elem_index_get(ele)]
#define MAP_FACE(ele) ftable_dst[BM_elem_index_get(ele)]
#define REMAP_VERT(ele) \
{ \
if (remap & BM_VERT) { \
ele = MAP_VERT(ele); \
} \
} \
((void)0)
#define REMAP_EDGE(ele) \
{ \
if (remap & BM_EDGE) { \
ele = MAP_EDGE(ele); \
} \
} \
((void)0)
#define REMAP_LOOP(ele) \
{ \
if (remap & BM_LOOP) { \
ele = MAP_LOOP(ele); \
} \
} \
((void)0)
#define REMAP_FACE(ele) \
{ \
if (remap & BM_FACE) { \
ele = MAP_FACE(ele); \
} \
} \
((void)0)
/* verts */
{
for (int i = 0; i < bm->totvert; i++) {
BMVert *v = vtable_dst[i];
if (v->e) {
REMAP_EDGE(v->e);
}
}
}
/* edges */
{
for (int i = 0; i < bm->totedge; i++) {
BMEdge *e = etable_dst[i];
REMAP_VERT(e->v1);
REMAP_VERT(e->v2);
REMAP_EDGE(e->v1_disk_link.next);
REMAP_EDGE(e->v1_disk_link.prev);
REMAP_EDGE(e->v2_disk_link.next);
REMAP_EDGE(e->v2_disk_link.prev);
if (e->l) {
REMAP_LOOP(e->l);
}
}
}
/* faces */
{
for (int i = 0; i < bm->totface; i++) {
BMFace *f = ftable_dst[i];
REMAP_LOOP(f->l_first);
{
BMLoop *l_iter, *l_first;
l_iter = l_first = BM_FACE_FIRST_LOOP((BMFace *)f);
do {
REMAP_VERT(l_iter->v);
REMAP_EDGE(l_iter->e);
REMAP_FACE(l_iter->f);
REMAP_LOOP(l_iter->radial_next);
REMAP_LOOP(l_iter->radial_prev);
REMAP_LOOP(l_iter->next);
REMAP_LOOP(l_iter->prev);
} while ((l_iter = l_iter->next) != l_first);
}
}
}
LISTBASE_FOREACH (BMEditSelection *, ese, &bm->selected) {
switch (ese->htype) {
case BM_VERT:
if (remap & BM_VERT) {
ese->ele = (BMElem *)MAP_VERT(ese->ele);
}
break;
case BM_EDGE:
if (remap & BM_EDGE) {
ese->ele = (BMElem *)MAP_EDGE(ese->ele);
}
break;
case BM_FACE:
if (remap & BM_FACE) {
ese->ele = (BMElem *)MAP_FACE(ese->ele);
}
break;
}
}
if (bm->act_face) {
REMAP_FACE(bm->act_face);
}
#undef MAP_VERT
#undef MAP_EDGE
#undef MAP_LOOP
#undef MAP_EDGE
#undef REMAP_VERT
#undef REMAP_EDGE
#undef REMAP_LOOP
#undef REMAP_EDGE
/* Cleanup, re-use local tables if the current mesh had tables allocated.
* could use irrespective but it may use more memory than the caller wants
* (and not be needed). */
if (remap & BM_VERT) {
if (bm->vtable) {
SWAP(BMVert **, vtable_dst, bm->vtable);
bm->vtable_tot = bm->totvert;
bm->elem_table_dirty &= ~BM_VERT;
}
MEM_freeN(vtable_dst);
BLI_mempool_destroy(bm->vpool);
bm->vpool = vpool_dst;
}
if (remap & BM_EDGE) {
if (bm->etable) {
SWAP(BMEdge **, etable_dst, bm->etable);
bm->etable_tot = bm->totedge;
bm->elem_table_dirty &= ~BM_EDGE;
}
MEM_freeN(etable_dst);
BLI_mempool_destroy(bm->epool);
bm->epool = epool_dst;
}
if (remap & BM_LOOP) {
/* no loop table */
MEM_freeN(ltable_dst);
BLI_mempool_destroy(bm->lpool);
bm->lpool = lpool_dst;
}
if (remap & BM_FACE) {
if (bm->ftable) {
SWAP(BMFace **, ftable_dst, bm->ftable);
bm->ftable_tot = bm->totface;
bm->elem_table_dirty &= ~BM_FACE;
}
MEM_freeN(ftable_dst);
BLI_mempool_destroy(bm->fpool);
bm->fpool = fpool_dst;
}
}
/**
* Re-allocates mesh data with/without toolflags.
*/
void BM_mesh_toolflags_set(BMesh *bm, bool use_toolflags)
{
if (bm->use_toolflags == use_toolflags) {
return;
}
const BMAllocTemplate allocsize = BMALLOC_TEMPLATE_FROM_BM(bm);
BLI_mempool *vpool_dst = NULL;
BLI_mempool *epool_dst = NULL;
BLI_mempool *fpool_dst = NULL;
bm_mempool_init_ex(&allocsize, use_toolflags, &vpool_dst, &epool_dst, NULL, &fpool_dst);
if (use_toolflags == false) {
BLI_mempool_destroy(bm->vtoolflagpool);
BLI_mempool_destroy(bm->etoolflagpool);
BLI_mempool_destroy(bm->ftoolflagpool);
bm->vtoolflagpool = NULL;
bm->etoolflagpool = NULL;
bm->ftoolflagpool = NULL;
}
BM_mesh_rebuild(bm,
&((struct BMeshCreateParams){
.use_toolflags = use_toolflags,
}),
vpool_dst,
epool_dst,
NULL,
fpool_dst);
bm->use_toolflags = use_toolflags;
}
/* -------------------------------------------------------------------- */
/** \name BMesh Coordinate Access
* \{ */
void BM_mesh_vert_coords_get(BMesh *bm, float (*vert_coords)[3])
{
BMIter iter;
BMVert *v;
int i;
BM_ITER_MESH_INDEX (v, &iter, bm, BM_VERTS_OF_MESH, i) {
copy_v3_v3(vert_coords[i], v->co);
}
}
float (*BM_mesh_vert_coords_alloc(BMesh *bm, int *r_vert_len))[3]
{
float(*vert_coords)[3] = MEM_mallocN(bm->totvert * sizeof(*vert_coords), __func__);
BM_mesh_vert_coords_get(bm, vert_coords);
*r_vert_len = bm->totvert;
return vert_coords;
}
void BM_mesh_vert_coords_apply(BMesh *bm, const float (*vert_coords)[3])
{
BMIter iter;
BMVert *v;
int i;
BM_ITER_MESH_INDEX (v, &iter, bm, BM_VERTS_OF_MESH, i) {
copy_v3_v3(v->co, vert_coords[i]);
}
}
void BM_mesh_vert_coords_apply_with_mat4(BMesh *bm,
const float (*vert_coords)[3],
const float mat[4][4])
{
BMIter iter;
BMVert *v;
int i;
BM_ITER_MESH_INDEX (v, &iter, bm, BM_VERTS_OF_MESH, i) {
mul_v3_m4v3(v->co, mat, vert_coords[i]);
}
}
/** \} */
| 412 | 0.986699 | 1 | 0.986699 | game-dev | MEDIA | 0.498845 | game-dev,graphics-rendering | 0.915484 | 1 | 0.915484 |
cmangos/playerbots | 4,041 | playerbot/strategy/actions/AcceptInvitationAction.h | #pragma once
#include "playerbot/strategy/Action.h"
namespace ai
{
class AcceptInvitationAction : public Action
{
public:
AcceptInvitationAction(PlayerbotAI* ai) : Action(ai, "accept invitation") {}
virtual bool Execute(Event& event)
{
Group* grp = bot->GetGroupInvite();
if (!grp)
return false;
Player* inviter = sObjectMgr.GetPlayer(grp->GetLeaderGuid());
if (!inviter)
return false;
if (!ai->GetSecurity()->CheckLevelFor(PlayerbotSecurityLevel::PLAYERBOT_SECURITY_INVITE, false, inviter))
{
WorldPacket data(SMSG_GROUP_DECLINE, 10);
data << bot->GetName();
sServerFacade.SendPacket(inviter, data);
bot->UninviteFromGroup();
return false;
}
if (bot->isAFK())
bot->ToggleAFK();
WorldPacket p;
uint32 roles_mask = 0;
p << roles_mask;
bot->GetSession()->HandleGroupAcceptOpcode(p);
if (!bot->GetGroup() || !bot->GetGroup()->IsMember(inviter->GetObjectGuid()))
return false;
if (sRandomPlayerbotMgr.IsFreeBot(bot))
{
ai->SetMaster(inviter);
ai->ChangeStrategy("+follow", BotState::BOT_STATE_NON_COMBAT);
}
ai->ResetStrategies();
ai->ChangeStrategy("-lfg,-bg", BotState::BOT_STATE_NON_COMBAT);
ai->Reset();
sPlayerbotAIConfig.logEvent(ai, "AcceptInvitationAction", grp->GetLeaderName(), std::to_string(grp->GetMembersCount()));
Player* master = inviter;
if (master->GetPlayerbotAI()) //Copy formation from bot master.
{
if (sPlayerbotAIConfig.inviteChat && (sRandomPlayerbotMgr.IsFreeBot(bot) || !ai->HasActivePlayerMaster()))
{
std::map<std::string, std::string> placeholders;
placeholders["%name"] = master->GetName();
std::string reply;
if (urand(0, 3))
reply = BOT_TEXT2("Send me an invite %name!", placeholders);
else
reply = BOT_TEXT2("Sure I will join you.", placeholders);
Guild* guild = sGuildMgr.GetGuildById(bot->GetGuildId());
if (guild && master->IsInGuild(bot))
guild->BroadcastToGuild(bot->GetSession(), reply, LANG_UNIVERSAL);
else if (sServerFacade.GetDistance2d(bot, master) < sPlayerbotAIConfig.spellDistance * 1.5)
bot->Say(reply, (bot->GetTeam() == ALLIANCE ? LANG_COMMON : LANG_ORCISH));
}
Formation* masterFormation = MAI_VALUE(Formation*, "formation");
FormationValue* value = (FormationValue*)context->GetValue<Formation*>("formation");
value->Load(masterFormation->getName());
}
ai->TellPlayer(inviter, BOT_TEXT("hello"), PlayerbotSecurityLevel::PLAYERBOT_SECURITY_ALLOW_ALL, false);
ai->DoSpecificAction("reset raids", event, true);
ai->DoSpecificAction("update gear", event, true);
return true;
}
virtual bool isUsefulWhenStunned() override { return true; }
#ifdef GenerateBotHelp
virtual std::string GetHelpName() { return "accept invitation"; }
virtual std::string GetHelpDescription()
{
return "This action makes the bot accept group invitations.\n"
"It will automatically handle AFK status and update strategies.\n"
"For free bots, the inviter becomes the bot's master.";
}
virtual std::vector<std::string> GetUsedActions() { return {"reset raids", "update gear"}; }
virtual std::vector<std::string> GetUsedValues() { return {"formation"}; }
#endif
};
}
| 412 | 0.867676 | 1 | 0.867676 | game-dev | MEDIA | 0.589317 | game-dev | 0.917098 | 1 | 0.917098 |
ReikaKalseki/ChromatiCraft | 7,977 | World/Dimension/Generators/WorldGenTerrainCrystal.java | /*******************************************************************************
* @author Reika Kalseki
*
* Copyright 2017
*
* All rights reserved.
* Distribution of the software in any form is only allowed with
* explicit, prior permission from the owner.
******************************************************************************/
package Reika.ChromatiCraft.World.Dimension.Generators;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Random;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
import net.minecraft.util.MathHelper;
import net.minecraft.world.World;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidRegistry;
import Reika.ChromatiCraft.Base.ChromaDimensionBiome;
import Reika.ChromatiCraft.Base.ChromaWorldGenerator;
import Reika.ChromatiCraft.Block.Dimension.BlockDimensionDeco.DimDecoTypes;
import Reika.ChromatiCraft.Block.Worldgen.BlockLootChest.TileEntityLootChest;
import Reika.ChromatiCraft.Block.Worldgen.BlockStructureShield.BlockType;
import Reika.ChromatiCraft.Magic.ElementTagCompound;
import Reika.ChromatiCraft.Registry.ChromaBlocks;
import Reika.ChromatiCraft.Registry.ItemMagicRegistry;
import Reika.ChromatiCraft.World.Dimension.DimensionGenerators;
import Reika.DragonAPI.Instantiable.Data.BlockStruct.FilledBlockArray;
import Reika.DragonAPI.Instantiable.Data.Immutable.BlockKey;
import Reika.DragonAPI.Instantiable.Data.Immutable.Coordinate;
import Reika.DragonAPI.Libraries.Java.ReikaRandomHelper;
import Reika.DragonAPI.Libraries.Registry.ReikaItemHelper;
public class WorldGenTerrainCrystal extends ChromaWorldGenerator {
public WorldGenTerrainCrystal(DimensionGenerators g, Random rand, long seed) {
super(g, rand, seed);
}
@Override
public boolean generate(World world, Random rand, int x, int y, int z) {
int h = y+64+rand.nextInt(64);
if (h > 250)
return false;
int n = 4+rand.nextInt(9);
for (int i = 0; i < n; i++) {
int dx = ReikaRandomHelper.getRandomPlusMinus(x, 24);
int dz = ReikaRandomHelper.getRandomPlusMinus(z, 24);
int dy = ReikaRandomHelper.getRandomPlusMinus(h, 12);
int s = 3+rand.nextInt(6);
float f = (float)ReikaRandomHelper.getRandomPlusMinus(1.5D, 0.5D);
TerrainCrystal t = new TerrainCrystal(s, f);
t.hasTreasure = rand.nextInt(18) == 0;
t.hasCore = rand.nextInt(6) == 0;
t.hasPool = rand.nextInt(3) == 0;
t.hasResource = !t.hasTreasure && !t.hasCore && !t.hasPool && rand.nextInt(3) == 0;
if (rand.nextInt(4) == 0)
t.heightExponent = ReikaRandomHelper.getRandomBetween(0.25, rand.nextBoolean() ? 1.5 : 2D); //0.5 is a hemispherical bottom; 2 is pointed
if (rand.nextInt(8) == 0) {
t.stone = new BlockKey(ChromaBlocks.STRUCTSHIELD.getBlockInstance(), BlockType.STONE.ordinal());
t.top = new BlockKey(ChromaBlocks.STRUCTSHIELD.getBlockInstance(), BlockType.MOSS.ordinal());
}
switch(rand.nextInt(12)) {
case 0:
t.core = new BlockKey(Blocks.diamond_ore);
break;
case 1:
t.core = new BlockKey(Blocks.emerald_ore);
break;
case 2:
case 3:
t.core = new BlockKey(Blocks.obsidian);
break;
}
switch(rand.nextInt(12)) {
case 0:
case 1:
t.pool = new BlockKey(ChromaBlocks.CHROMA.getBlockInstance());
break;
case 2:
case 3:
t.pool = new BlockKey(FluidRegistry.getFluid("ender").getBlock());
break;
case 4: {
Fluid fs = FluidRegistry.getFluid("ic2uumatter");
if (fs != null && fs.canBePlacedInWorld())
t.core = new BlockKey(fs.getBlock());
break;
}
/*
case 5: {
Fluid fs = FluidRegistry.getFluid("springwater");
if (fs != null && fs.canBePlacedInWorld())
t.core = new BlockKey(fs.getBlock());
break;
}
*/
case 6: {
Fluid fs = FluidRegistry.getFluid("fluidpure");
if (fs != null && fs.canBePlacedInWorld())
t.core = new BlockKey(fs.getBlock());
break;
}
}
FilledBlockArray b = t.generate(world, dx, dy, dz);
int tries = 0;
while (tries < 100 && !b.isAtLeastXPercent(world, 90, Blocks.air)) {
dx = ReikaRandomHelper.getRandomPlusMinus(x, 16);
dz = ReikaRandomHelper.getRandomPlusMinus(z, 16);
dy = ReikaRandomHelper.getRandomPlusMinus(h, 6);
b = t.generate(world, dx, dy, dz);
}
if (b.isAtLeastXPercent(world, 90, Blocks.air)) {
b.place();
if (t.hasTreasure) {
TileEntityLootChest te = (TileEntityLootChest)world.getTileEntity(dx, dy-t.size/2, dz);
this.generateLoot(te, rand);
}
}
}
//ChromatiCraft.logger.log("Generated @ "+x+", "+z);
return true;
}
private void generateLoot(TileEntityLootChest te, Random rand) {
int n = 16+rand.nextInt(24);
ArrayList<ItemStack> li = ItemMagicRegistry.instance.getAllRegisteredItems();
for (int i = 0; i < n; i++) {
int idx = rand.nextInt(li.size());
ItemStack in = li.get(idx);
ElementTagCompound value = ItemMagicRegistry.instance.getItemValue(in);
int max = Math.min(16, 24/value.getMaximumValue());
int num = Math.min(1+rand.nextInt(max), in.getMaxStackSize());
ItemStack is = ReikaItemHelper.getSizedItemStack(in, num);
int slot = rand.nextInt(te.getSizeInventory());
while (te.getStackInSlot(slot) != null) {
slot = rand.nextInt(te.getSizeInventory());
}
te.setInventorySlotContents(slot, is);
}
}
@Override
public float getGenerationChance(World world, int cx, int cz, ChromaDimensionBiome biome) {
return 0.005F;
}
private static class TerrainCrystal {
private final int size;
private final float heightFactor;
private double heightExponent = 1;
private boolean hasCore = false;
private boolean hasPool = false;
private boolean hasTreasure = false;
private boolean hasResource = false;
private BlockKey top = new BlockKey(Blocks.grass);
private BlockKey stone = new BlockKey(Blocks.stone);
private BlockKey core = new BlockKey(Blocks.lava);
private BlockKey pool = new BlockKey(Blocks.water);
private TerrainCrystal(int s, float h) {
size = s;
heightFactor = h;
}
public FilledBlockArray generate(World world, int x, int y, int z) {
FilledBlockArray arr = new FilledBlockArray(world);
int dy = y;
double r = size;
double mh = size*heightFactor;
int h = 0;
while (r > 0) {
int dr = MathHelper.ceiling_double_int(r);
for (int i = -dr; i <= dr; i++) {
for (int k = -dr; k <= dr; k++) {
int d = Math.abs(i)+Math.abs(k);
if (d <= dr) {
int dx = x+i;
int dz = z+k;
BlockKey b = dy == y ? top : stone;
if (hasCore && d < dr-1 && dy < y)
b = core;
if (hasPool && d < dr-1 && dy == y)
b = pool;
arr.setBlock(dx, dy, dz, b);
}
}
}
h++;
r = size*Math.pow(1-h/mh, heightExponent);
dy--;
}
if (hasTreasure) {
arr.setBlock(x, y-size/2, z, ChromaBlocks.LOOTCHEST.getBlockInstance());
}
if (hasResource) {
int y2 = y-size/2;
arr.setBlock(x, y2, z, ChromaBlocks.DIMGEN.getBlockInstance(), DimDecoTypes.LATTICE.ordinal());
arr.setBlock(x, y2+1, z, ChromaBlocks.DIMGEN.getBlockInstance(), DimDecoTypes.LATTICE.ordinal());
arr.setBlock(x, y2-1, z, ChromaBlocks.DIMGEN.getBlockInstance(), DimDecoTypes.LATTICE.ordinal());
arr.setBlock(x+1, y2, z, ChromaBlocks.DIMGEN.getBlockInstance(), DimDecoTypes.LATTICE.ordinal());
arr.setBlock(x-1, y2, z, ChromaBlocks.DIMGEN.getBlockInstance(), DimDecoTypes.LATTICE.ordinal());
arr.setBlock(x, y2, z+1, ChromaBlocks.DIMGEN.getBlockInstance(), DimDecoTypes.LATTICE.ordinal());
arr.setBlock(x, y2, z-1, ChromaBlocks.DIMGEN.getBlockInstance(), DimDecoTypes.LATTICE.ordinal());
}
if (hasCore) {
HashSet<Coordinate> set = new HashSet();
for (Coordinate c : arr.keySet()) {
if (c.yCoord == arr.getMinY())
set.add(c);
}
for (Coordinate c : set) {
arr.setBlock(c.xCoord, c.yCoord, c.zCoord, stone);
}
}
return arr;
}
}
}
| 412 | 0.88275 | 1 | 0.88275 | game-dev | MEDIA | 0.851652 | game-dev | 0.97875 | 1 | 0.97875 |
gwtproject/gwt | 6,381 | user/super/com/google/gwt/emul/java/util/Vector.java | /*
* Copyright 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package java.util;
import static javaemul.internal.InternalPreconditions.checkElement;
import java.io.Serializable;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.UnaryOperator;
import jsinterop.annotations.JsNonNull;
/**
* To keep performance characteristics in line with Java community expectations,
* <code>Vector</code> is a wrapper around <code>ArrayList</code>.
* See <a href="https://docs.oracle.com/javase/8/docs/api/java/util/Vector.html">
* the official Java API doc</a> for details.
*
* @param <E> element type.
*/
public class Vector<E> extends AbstractList<E> implements List<E>,
RandomAccess, Cloneable, Serializable {
private transient ArrayList<E> arrayList;
/**
* Ensures that RPC will consider type parameter E to be exposed. It will be
* pruned by dead code elimination.
*/
@SuppressWarnings("unused")
private E exposeElement;
public Vector() {
arrayList = new ArrayList<E>();
}
public Vector(Collection<? extends E> c) {
arrayList = new ArrayList<E>();
addAll(c);
}
public Vector(int initialCapacity) {
arrayList = new ArrayList<E>(initialCapacity);
}
/**
* Capacity increment is ignored.
*/
@SuppressWarnings("unused")
public Vector(int initialCapacity, int ignoredCapacityIncrement) {
this(initialCapacity);
}
@Override
public boolean add(E o) {
return arrayList.add(o);
}
@Override
public void add(int index, E o) {
checkArrayElementIndex(index, size() + 1);
arrayList.add(index, o);
}
@Override
public boolean addAll(Collection<? extends E> c) {
return arrayList.addAll(c);
}
@Override
public boolean addAll(int index, Collection<? extends E> c) {
checkArrayElementIndex(index, size() + 1);
return arrayList.addAll(index, c);
}
public void addElement(E o) {
add(o);
}
public int capacity() {
return arrayList.size();
}
@Override
public void clear() {
arrayList.clear();
}
public Object clone() {
return new Vector<E>(this);
}
@Override
public boolean contains(Object elem) {
return arrayList.contains(elem);
}
@Override
public boolean containsAll(Collection<?> c) {
return arrayList.containsAll(c);
}
public void copyInto(Object[] objs) {
int i = -1;
int n = size();
while (++i < n) {
objs[i] = get(i);
}
}
public E elementAt(int index) {
return get(index);
}
public Enumeration<E> elements() {
return Collections.enumeration(arrayList);
}
public void ensureCapacity(int capacity) {
arrayList.ensureCapacity(capacity);
}
public E firstElement() {
checkElement(!isEmpty());
return get(0);
}
@Override
public void forEach(Consumer<? super E> consumer) {
arrayList.forEach(consumer);
}
@Override
public E get(int index) {
checkArrayElementIndex(index, size());
return arrayList.get(index);
}
@Override
public int indexOf(Object elem) {
return arrayList.indexOf(elem);
}
public int indexOf(Object elem, int index) {
checkArrayIndexOutOfBounds(index >= 0, index);
return arrayList.indexOf(elem, index);
}
public void insertElementAt(E o, int index) {
add(index, o);
}
@Override
public boolean isEmpty() {
return (arrayList.size() == 0);
}
@Override
public Iterator<E> iterator() {
return arrayList.iterator();
}
public E lastElement() {
checkElement(!isEmpty());
return get(size() - 1);
}
@Override
public int lastIndexOf(Object o) {
return arrayList.lastIndexOf(o);
}
public int lastIndexOf(Object o, int index) {
checkArrayIndexOutOfBounds(index < size(), index);
return arrayList.lastIndexOf(o, index);
}
@Override
public E remove(int index) {
checkArrayElementIndex(index, size());
return arrayList.remove(index);
}
@Override
public boolean removeAll(Collection<?> c) {
return arrayList.removeAll(c);
}
public void removeAllElements() {
clear();
}
public boolean removeElement(Object o) {
return remove(o);
}
public void removeElementAt(int index) {
remove(index);
}
@Override
public boolean removeIf(Predicate<? super E> filter) {
return arrayList.removeIf(filter);
}
@Override
public void replaceAll(UnaryOperator<E> operator) {
arrayList.replaceAll(operator);
}
@Override
public E set(int index, E elem) {
checkArrayElementIndex(index, size());
return arrayList.set(index, elem);
}
public void setElementAt(E o, int index) {
set(index, o);
}
public void setSize(int size) {
checkArrayIndexOutOfBounds(size >= 0, size);
arrayList.setSize(size);
}
@Override
public int size() {
return arrayList.size();
}
@Override
public void sort(Comparator<? super E> c) {
arrayList.sort(c);
}
@Override
@JsNonNull
public List<E> subList(int fromIndex, int toIndex) {
return arrayList.subList(fromIndex, toIndex);
}
@Override
public Object[] toArray() {
return arrayList.toArray();
}
@Override
public <T> T[] toArray(T[] a) {
return arrayList.toArray(a);
}
@Override
public String toString() {
return arrayList.toString();
}
public void trimToSize() {
arrayList.trimToSize();
}
@Override
protected void removeRange(int fromIndex, int endIndex) {
arrayList.removeRange(fromIndex, endIndex);
}
private static void checkArrayElementIndex(int index, int size) {
if (index < 0 || index >= size) {
throw new ArrayIndexOutOfBoundsException();
}
}
private static void checkArrayIndexOutOfBounds(boolean expression, int index) {
if (!expression) {
throw new ArrayIndexOutOfBoundsException(String.valueOf(index));
}
}
}
| 412 | 0.922119 | 1 | 0.922119 | game-dev | MEDIA | 0.290911 | game-dev | 0.921762 | 1 | 0.921762 |
masterfeizz/EDuke3D | 81,179 | source/lunatic/defs.ilua | -- INTERNAL
-- definitions of BUILD and game types for the Lunatic Interpreter
local require = require
local ffi = require("ffi")
local ffiC = ffi.C
-- Lua C API functions.
local CF = CF
local bit = bit
local coroutine = coroutine
local string = string
local table = table
local math = math
local assert = assert
local error = error
local getfenv = getfenv
local getmetatable = getmetatable
local ipairs = ipairs
local loadstring = loadstring
local pairs = pairs
local pcall = pcall
local rawget = rawget
local rawset = rawset
local select = select
local setmetatable = setmetatable
local setfenv = setfenv
local tonumber = tonumber
local tostring = tostring
local type = type
-- Create a new module for passing stuff to other modules.
local lprivate = {}
require("package").loaded.lprivate = lprivate
require("jit.opt").start("maxmcode=10240") -- in KiB
-- The "gv" global will provide access to C global *scalars* and safe functions.
-- NOTE: This exposes C library functions from e.g. the global C namespace, but
-- without their declarations, they will be sitting there like a stone.
local gv_ = {}
-- [key]=<boolean> forbids, [key]=<non-boolean (e.g. table, function)> overrides
local gv_access = {}
-- This is for declarations of arrays or pointers which should not be
-- accessible through the "gv" global. The "defs_common" module will
-- use this function.
--
-- Notes: do not declare multiple scalars on one line (this is bad:
-- "int32_t a, b"). Do not name array arguments (or add a space
-- between the identifier and the '[' instead).
function decl(str, ...)
-- NOTE that the regexp also catches non-array/non-function identifiers
-- like "user_defs ud;"
for varname in string.gmatch(str, "([%a_][%w_]*)[[(;]") do
if (ffiC._DEBUG_LUNATIC ~= 0) then
print("FORBID "..varname)
end
gv_access[varname] = true
end
ffi.cdef(str, ...)
end
lprivate.decl = decl
ffi.cdef[[
enum {
LUNATIC_CLIENT_MAPSTER32 = 0,
LUNATIC_CLIENT_EDUKE32 = 1,
LUNATIC_CLIENT = LUNATIC_CLIENT_EDUKE32
}
]]
-- Load the definitions common to the game's and editor's Lua interface.
local defs_c = require("defs_common")
local cansee = defs_c.cansee
local strip_const = defs_c.strip_const
local setmtonce = defs_c.setmtonce
-- Must be after loading "defs_common" which redefines "print" to use
-- OSD_Printf()
local print, printf = print, defs_c.printf
---=== EDuke32 game definitions ===---
local INV_NAMES = {
"STEROIDS",
"SHIELD",
"SCUBA",
"HOLODUKE",
"JETPACK",
"DUMMY1",
"ACCESS",
"HEATS",
"DUMMY2",
"FIRSTAID",
"BOOTS",
}
local WEAPON_NAMES = {
"KNEE",
"PISTOL",
"SHOTGUN",
"CHAINGUN",
"RPG",
"HANDBOMB",
"SHRINKER",
"DEVISTATOR",
"TRIPBOMB",
"FREEZE",
"HANDREMOTE",
"GROW",
}
---- game structs ----
lprivate.GET = defs_c.conststruct(INV_NAMES)
lprivate.WEAPON = defs_c.conststruct(WEAPON_NAMES)
ffi.cdef([[
enum {
GET_MAX = 11,
MAX_WEAPONS = 12,
MAXPLAYERS = 16,
GTICSPERSEC = 30, // The real number of movement updates per second
};
]])
ffi.cdef[[
struct action {
int16_t startframe, numframes;
int16_t viewtype, incval, delay;
};
struct move {
int16_t hvel, vvel;
};
#pragma pack(push,1)
typedef struct { int32_t id; struct move mv; } con_move_t;
typedef struct { int32_t id; struct action ac; } con_action_t;
#pragma pack(pop)
typedef struct {
int32_t id;
con_action_t act;
con_move_t mov;
int32_t movflags;
} con_ai_t;
]]
defs_c.bitint_new_struct_type("int16_t", "SBit16")
defs_c.bitint_new_struct_type("int32_t", "SBit32")
defs_c.bitint_new_struct_type("uint32_t", "UBit32")
-- Struct template for actor_t. It already has 'const' fields (TODO: might need
-- to make more 'const'), but still has array members exposed, so is unsuited
-- for external exposure.
local ACTOR_STRUCT = [[
struct {
const int32_t t_data[10];
const struct move mv;
const struct action ac;
const uint16_t actiontics;
]]..defs_c.bitint_member("SBit32", "flags")..[[
vec3_t bpos; //12b
int32_t floorz,ceilingz,lastvx,lastvy; //16b
int32_t lasttransport; //4b
const int16_t picnum;
int16_t ang, extra;
const int16_t owner;
// NOTE: not to be confused with .movflags:
]]..defs_c.bitint_member("SBit16", "_movflag")..[[
int16_t tempang, timetosleep;
int16_t stayputsect;
const int16_t dispicnum;
// Movement flags, sprite[i].hitag in C-CON.
// XXX: more research where it was used in EDuke32's C code? (also .lotag <-> actiontics)
// XXX: what if CON code knew of the above implementation detail?
]]..defs_c.bitint_member("UBit16", "movflags")..[[
int16_t cgg;
const int16_t lightId, lightcount, lightmaxrange;
// NOTE: on 32-bit, C's lightptr+filler <=> this dummy:
const union { intptr_t ptr; uint64_t dummy; } _light;
}
]]
local bcarray = require("bcarray")
local bcheck = require("bcheck")
local check_sector_idx, check_tile_idx = bcheck.sector_idx, bcheck.tile_idx
local check_sprite_idx = bcheck.sprite_idx
local check_weapon_idx, check_inventory_idx = bcheck.weapon_idx, bcheck.inventory_idx
local check_sound_idx = bcheck.sound_idx
local check_number = bcheck.number
local check_type = bcheck.type
bcarray.new("int16_t", 64, "loogie", "int16_x_64") -- TODO: randomize member names
bcarray.new("int16_t", ffiC.MAX_WEAPONS, "weapon", "int16_x_MAX_WEAPONS", WEAPON_NAMES)
bcarray.new("int16_t", ffiC.GET_MAX, "inventory", "int16_x_GET_MAX", INV_NAMES)
-- NOTE: writing e.g. "ps.jetpack_on" in Lua when "ps.jetpack_on~=0" was meant
-- is probably one of the most commonly committed errors, so we make it a bool
-- type instead of uint8_t. The only issue is that if CON coders used these
-- fields to store more than just one bit, we're in trouble.
-- This will need to be documented and frozen for release.
local DUKEPLAYER_STRUCT = [[
__attribute__((packed)) struct {
vec3_t pos, opos, vel, npos;
vec2_t bobpos, fric;
int32_t truefz, truecz, player_par;
int32_t randomflamex, exitx, exity;
int32_t runspeed, max_player_health, max_shield_amount;
int32_t autostep, autostep_sbw;
uint32_t interface_toggle_flag;
int32_t pipebombControl, pipebombLifetime, pipebombLifetimeVar;
int32_t tripbombControl, tripbombLifetime, tripbombLifetimeVar;
int32_t zrange;
int16_t angrange, autoaimang;
uint16_t max_actors_killed, actors_killed;
]]..defs_c.bitint_member("UBit16", "gotweapon")..[[
uint16_t zoom;
int16_x_64 loogiex;
int16_x_64 loogiey;
int16_t sbs, sound_pitch;
int16_t ang, oang, angvel;
const<S> int16_t cursectnum;
int16_t look_ang, last_extra, subweapon;
int16_x_MAX_WEAPONS max_ammo_amount;
int16_x_MAX_WEAPONS ammo_amount;
int16_x_GET_MAX inv_amount;
const<I-> int16_t wackedbyactor;
int16_t pyoff, opyoff;
int16_t horiz, horizoff, ohoriz, ohorizoff;
const<I-> int16_t newowner;
int16_t jumping_counter, airleft;
int16_t fta;
const<Q> int16_t ftq;
const int16_t access_wallnum, access_spritenum;
int16_t got_access, weapon_ang, visibility;
int16_t somethingonplayer, on_crane;
const int16_t i;
const int16_t one_parallax_sectnum;
int16_t random_club_frame, one_eighty_count;
const<I-> int16_t dummyplayersprite;
int16_t extra_extra8;
int16_t actorsqu, timebeforeexit;
const<X-> int16_t customexitsound;
int16_t last_pissed_time;
int16_x_MAX_WEAPONS weaprecs;
int16_t weapon_sway, crack_time, bobcounter;
int16_t orotscrnang, rotscrnang, dead_flag; // JBF 20031220: added orotscrnang
int16_t holoduke_on, pycount;
int16_t transporter_hold;
uint8_t max_secret_rooms, secret_rooms;
uint8_t frag, fraggedself, quick_kick, last_quick_kick;
uint8_t return_to_center;
bool reloading;
const uint8_t weapreccnt;
uint8_t aim_mode, auto_aim, weaponswitch, movement_lock, team;
uint8_t tipincs, hbomb_hold_delay;
const<P> uint8_t frag_ps;
uint8_t kickback_pic;
uint8_t gm;
bool on_warping_sector;
uint8_t footprintcount, hurt_delay;
bool hbomb_on, jumping_toggle, rapid_fire_hold, on_ground;
// NOTE: there's array indexing with inven_icon, but always after a
// bound check:
uint8_t inven_icon, buttonpalette;
bool over_shoulder_on;
uint8_t show_empty_weapon;
bool jetpack_on, spritebridge;
uint8_t lastrandomspot; // unused
bool scuba_on;
uint8_t footprintpal;
bool heat_on;
uint8_t invdisptime;
bool holster_weapon;
uint8_t falling_counter, footprintshade;
uint8_t refresh_inventory;
const<W> uint8_t last_full_weapon;
const uint8_t toggle_key_flag;
uint8_t knuckle_incs, knee_incs, access_incs;
uint8_t walking_snd_toggle, palookup, hard_landing, fist_incs;
int8_t numloogs, loogcnt;
const int8_t scream_voice;
const<W-> int8_t last_weapon;
const int8_t cheat_phase;
int8_t weapon_pos;
const<W-> int8_t wantweaponfire;
const<W> int8_t curr_weapon;
const uint8_t palette;
palette_t _pals;
int8_t _palsfadespeed, _palsfadenext, _palsfadeprio, _padding2;
// NOTE: In C, the struct type has no name. We only have it here to define
// a metatype later.
const weaponaccess_t weapon;
const int8_t _padding;
}
]]
local PROJECTILE_STRUCT = [[
struct {
int32_t workslike, cstat;
int32_t hitradius, range, flashcolor;
const int16_t spawns;
const int16_t sound, isound;
int16_t vel;
const int16_t decal, trail;
int16_t tnum, drop;
int16_t offset, bounces;
const int16_t bsound;
int16_t toffset;
int16_t extra, extra_rand;
int8_t sxrepeat, syrepeat, txrepeat, tyrepeat;
int8_t shade, xrepeat, yrepeat, pal;
int8_t movecnt;
uint8_t clipdist;
int8_t filler[2];
int32_t userdata;
}
]]
-- KEEPINSYNC weapondata_mt below.
local WEAPONDATA_STRUCT = "struct {"..table.concat(con_lang.wdata_members, ';').."; }"
local randgen = require("randgen")
local ma_rand = randgen.new(true) -- initialize to "random" (time-based) seed
local ma_count = nil
local function ma_replace_array(typestr, neltstr)
local nelts = tonumber(neltstr)
if (nelts==nil) then
nelts = ffiC[neltstr]
assert(type(nelts)=="number")
end
local strtab = { "const ", typestr.." " }
for i=1,nelts do
local ch1 = 97 + (ma_rand:getu32() % 25) -- 'a'..'z'
strtab[i+2] = string.format("_%c%x%s", ch1, ma_count, (i<nelts) and "," or ";")
ma_count = ma_count+1
end
return table.concat(strtab)
end
---=== Protection of scalars in (currently only) DukePlayer_t struct. ===---
-- This is more convenient than writing dozens of set-member methods.
local prot_scalar_chkfunc = {
S = check_sector_idx,
I = check_sprite_idx,
P = bcheck.player_idx,
W = check_weapon_idx,
X = check_sound_idx,
Q = bcheck.quote_idx,
}
local DukePlayer_prot_allowneg = {} -- [<member name>] = true if setting <0 allowed
local DukePlayer_prot_chkfunc = {} -- [<member name>] = <checking function>
local function ma_replace_scalar(what, typestr, membname)
DukePlayer_prot_chkfunc[membname] = assert(prot_scalar_chkfunc[what:sub(1,1)])
DukePlayer_prot_allowneg[membname] = (what:sub(2)=="-")
return ma_replace_array(typestr, 1)
end
-- Converts a template struct definition to an external one, in which arrays
-- have been substituted by randomly named scalar fields.
-- <also_scalars>: also handle protected scalars like "const<W-> ..." etc.
local function mangle_arrays(structstr, also_scalars)
ma_count = 0
-- NOTE: regexp only works for non-nested arrays and for one array per line.
structstr = structstr:gsub("const%s+([%w_]+)[^\n]+%[([%w_]+)%];", ma_replace_array)
if (also_scalars) then
-- One protected scalar per line, too.
structstr = structstr:gsub("const<(.-)>%s+([%w_]-)%s+([%w_]-);", ma_replace_scalar)
end
return structstr
end
--print(mangle_arrays(DUKEPLAYER_STRUCT, true))
--- default defines etc.
local con_lang = require("con_lang")
local xmath = require("xmath")
ffi.cdef([[
typedef struct { int32_t _p; } weaponaccess_t;
typedef struct {
]]..defs_c.bitint_member("UBit32", "bits")..[[
int16_t fvel, svel, avel;
int8_t horz, extbits;
} input_t;
typedef
]].. mangle_arrays(ACTOR_STRUCT) ..[[
actor_t;
typedef
]].. mangle_arrays(DUKEPLAYER_STRUCT, true) ..[[
DukePlayer_t;
typedef __attribute__((packed)) struct {
DukePlayer_t *ps;
input_t *sync;
int32_t netsynctime;
int16_t ping, filler;
int32_t pcolor, pteam;
uint8_t frags[MAXPLAYERS], wchoice[MAX_WEAPONS];
char vote, gotvote, pingcnt, playerquitflag, ready;
char user_name[32];
uint32_t revision;
} playerdata_t;
typedef struct {
int32_t cur, count;
int32_t gunposx, lookhalfang;
int32_t gunposy, lookhoriz;
int32_t shade;
} hudweapon_t;
typedef
]].. WEAPONDATA_STRUCT ..[[
weapondata_t;
typedef
]].. PROJECTILE_STRUCT ..[[
projectile_t;
typedef struct {
uint32_t _flags; // XXX: do we want to have this accessible at game time?
int32_t _cacherange;
projectile_t *_proj;
const projectile_t *_defproj;
} tiledata_t;
typedef struct {
vec3_t pos;
int32_t dist, clock;
int16_t ang, horiz;
int16_t sect; // NOTE: protected in camera_mt's __newindex
} camera_t;
enum
{
MAXMOUSEBUTTONS = 10,
MAXMOUSEAXES = 2,
MAXJOYBUTTONS = 32,
MAXJOYBUTTONSANDHATS = (32+4),
MAXJOYAXES = 9,
NUMGAMEFUNCTIONS = 56,
// game.h
MAXRIDECULE = 10,
MAXRIDECULELENGTH = 40,
MAXSAVEGAMES = 10,
MAXSAVEGAMENAME = 22,
MAXPWLOCKOUT = 128,
MAXRTSNAME = 128,
};
typedef struct {
int32_t const_visibility,uw_framerate;
int32_t camera_time,folfvel,folavel,folx,foly,fola;
int32_t reccnt,crosshairscale;
int32_t runkey_mode,statusbarscale,mouseaiming,weaponswitch,drawweapon; // JBF 20031125
int32_t democams,color,msgdisptime,statusbarmode;
int32_t m_noexits,noexits,autovote,automsg,idplayers;
int32_t team, viewbob, weaponsway, althud, weaponscale, textscale;
int32_t entered_name,screen_tilting,shadows,fta_on,executions,auto_run;
int32_t coords,tickrate,levelstats,m_coop,coop,screen_size,lockout,crosshair;
int32_t playerai,angleinterpolation,obituaries;
int32_t respawn_monsters,respawn_items,respawn_inventory,recstat,monsters_off,brightness;
int32_t m_respawn_items,m_respawn_monsters,m_respawn_inventory,m_recstat,m_monsters_off,detail;
int32_t m_ffire,ffire,m_player_skill,m_level_number,m_volume_number,multimode;
int32_t player_skill,level_number,volume_number,m_marker,marker,mouseflip;
vec2_t m_origin;
int32_t playerbest;
int32_t configversion;
int16_t pause_on,from_bonus;
int16_t camerasprite,last_camsprite;
int16_t last_level,secretlevel, bgstretch;
struct {
int32_t UseJoystick;
int32_t UseMouse;
int32_t AutoAim;
int32_t ShowOpponentWeapons;
int32_t MouseDeadZone,MouseBias;
int32_t SmoothInput;
// JBF 20031211: Store the input settings because
// (currently) jmact can't regurgitate them
int32_t MouseFunctions[MAXMOUSEBUTTONS][2];
int32_t MouseDigitalFunctions[MAXMOUSEAXES][2];
int32_t MouseAnalogueAxes[MAXMOUSEAXES];
int32_t MouseAnalogueScale[MAXMOUSEAXES];
int32_t JoystickFunctions[MAXJOYBUTTONSANDHATS][2];
int32_t JoystickDigitalFunctions[MAXJOYAXES][2];
int32_t JoystickAnalogueAxes[MAXJOYAXES];
int32_t JoystickAnalogueScale[MAXJOYAXES];
int32_t JoystickAnalogueDead[MAXJOYAXES];
int32_t JoystickAnalogueSaturate[MAXJOYAXES];
uint8_t KeyboardKeys[NUMGAMEFUNCTIONS][2];
//
// Sound variables
//
int32_t MasterVolume;
int32_t FXVolume;
int32_t MusicVolume;
int32_t SoundToggle;
int32_t MusicToggle;
int32_t VoiceToggle;
int32_t AmbienceToggle;
int32_t NumVoices;
int32_t NumChannels;
int32_t NumBits;
int32_t MixRate;
int32_t ReverseStereo;
//
// Screen variables
//
int32_t ScreenMode;
int32_t ScreenWidth;
int32_t ScreenHeight;
int32_t ScreenBPP;
int32_t ForceSetup;
int32_t NoAutoLoad;
const int32_t scripthandle;
int32_t setupread;
int32_t CheckForUpdates;
int32_t LastUpdateCheck;
int32_t useprecache;
} config;
char overhead_on,last_overhead,showweapons;
char god,warp_on,cashman,eog,showallmap;
char show_help,scrollmode,noclip;
char ridecule[MAXRIDECULE][MAXRIDECULELENGTH];
char savegame[MAXSAVEGAMES][MAXSAVEGAMENAME];
char pwlockout[MAXPWLOCKOUT],rtsname[MAXRTSNAME];
char display_bonus_screen;
char show_level_text;
char wchoice[MAX_WEAPONS];
} user_defs;
typedef struct {
int32_t partime, designertime;
char *name, *filename, *musicfn;
void *savedstate;
} map_t;
]])
bcarray.new("weapondata_t", ffiC.MAX_WEAPONS, "weapon", "weapondata_x_MAX_WEAPONS", WEAPON_NAMES)
bcarray.new("int32_t", con_lang.MAXSESSIONVARS, "sessionvar", "int32_x_MAXSESSIONVARS")
-- EXTERNALLY EXPOSED GAME VARIABLES
ffi.cdef[[
const int32_t screenpeek;
hudweapon_t hudweap;
int32_t g_logoFlags;
]]
-- INTERNAL VARIABLES/FUNCTIONS
decl("map_t MapInfo[$*$];", con_lang.MAXVOLUMES+1, con_lang.MAXLEVELS)
decl("char EpisodeNames[$][33];", con_lang.MAXVOLUMES)
decl[[
const int32_t myconnectindex;
int32_t g_RETURN;
int32_t g_elCONSize;
char *g_elCON;
void El_SetCON(const char *conluacode);
void El_OnError(const char *str);
char *g_elSavecode;
void El_FreeSaveCode(void);
const char *(*El_SerializeGamevars)(int32_t *slenptr, int32_t levelnum);
int32_t (*El_RestoreGamevars)(const char *savecode);
int32_t (*El_GetLabelValue)(const char *label);
const char *s_buildRev;
const char *g_sizes_of_what[];
int32_t g_sizes_of[];
int32_t g_elFirstTime;
int32_t g_elCallDepth;
int32_t block_deletesprite;
const char **g_elModules;
char g_modDir[];
int32_x_MAXSESSIONVARS g_elSessionVar;
actor_t actor[MAXSPRITES];
camera_t g_camera;
user_defs ud;
playerdata_t *const g_player;
DukePlayer_t *g_player_ps[MAXPLAYERS];
weapondata_x_MAX_WEAPONS g_playerWeapon[MAXPLAYERS];
weapondata_t g_weaponOverridden[MAX_WEAPONS];
int16_t WeaponPickupSprites[MAX_WEAPONS];
tiledata_t g_tile[MAXTILES];
projectile_t SpriteProjectile[MAXSPRITES];
int32_t g_noResetVars;
void (*A_ResetVars)(int32_t iActor);
// Used from lunacon.lua for dynamic {tile,sound} remapping:
struct
{
const char *str;
int32_t *dynvalptr;
const int16_t staticval;
} g_dynTileList[], g_dynSoundList[];
char *ScriptQuotes[];
const int32_t playerswhenstarted;
int16_t g_spriteDeleteQueueSize;
int16_t BlimpSpawnSprites[15];
int32_t g_scriptVersion;
const int32_t g_currentFrameRate;
const int32_t g_currentMenu;
uint16_t g_earthquakeTime;
uint32_t g_moveThingsCount;
char CheatKeys[2];
// Must not have functions here that may call events directly or
// indirectly. See lunatic_game.c.
int32_t A_IncurDamage(int32_t sn); // not bound-checked!
int32_t G_CheckActivatorMotion(int32_t lotag);
int32_t A_Dodge(spritetype *s);
int32_t A_MoveSpriteClipdist(int32_t spritenum, const vec3_t *change, uint32_t cliptype, int32_t clipdist);
void P_DoQuote(int32_t q, DukePlayer_t *p);
void P_SetGamePalette(DukePlayer_t *player, uint32_t palid, int32_t set);
void G_AddUserQuote(const char *daquote);
void G_ClearCameraView(DukePlayer_t *ps);
void G_DrawTileGeneric(int32_t x, int32_t y, int32_t zoom, int32_t tilenum,
int32_t shade, int32_t orientation, int32_t p);
void G_InitTimer(int32_t ticspersec);
void G_GetTimeDate(int32_t *vals);
int32_t G_ToggleWallInterpolation(int32_t w, int32_t doset);
int32_t G_StartTrack(int32_t level);
int32_t VM_CheckSquished2(int32_t i, int32_t snum);
void M_ChangeMenu(int32_t cm);
const char *KB_ScanCodeToString(uint8_t scancode);
int32_t A_CheckAnySoundPlaying(int32_t i);
int32_t S_CheckSoundPlaying(int32_t i, int32_t num);
void S_StopEnvSound(int32_t num, int32_t i);
int32_t FX_StopAllSounds(void);
void S_ChangeSoundPitch(int32_t num, int32_t i, int32_t pitchoffset);
int32_t S_GetMusicPosition(void);
void S_SetMusicPosition(int32_t position);
int32_t minitext_(int32_t x,int32_t y,const char *t,int32_t s,int32_t p,int32_t sb);
void G_DrawTXDigiNumZ(int32_t starttile, int32_t x,int32_t y,int32_t n,int32_t s,int32_t pal,
int32_t cs,int32_t x1, int32_t y1, int32_t x2, int32_t y2, int32_t z);
int32_t G_PrintGameText(int32_t f, int32_t tile, int32_t x, int32_t y, const char *t,
int32_t s, int32_t p, int32_t o,
int32_t x1, int32_t y1, int32_t x2, int32_t y2, int32_t z);
vec2_t G_ScreenText(const int32_t font,
int32_t x, int32_t y, const int32_t z, const int32_t blockangle, const int32_t charangle,
const char *str, const int32_t shade, int32_t pal, int32_t o, int32_t alpha,
int32_t xspace, int32_t yline, int32_t xbetween, int32_t ybetween, const int32_t f,
const int32_t x1, const int32_t y1, const int32_t x2, const int32_t y2);
vec2_t G_ScreenTextSize(const int32_t font,
int32_t x, int32_t y, const int32_t z, const int32_t blockangle,
const char *str, const int32_t o,
int32_t xspace, int32_t yline, int32_t xbetween, int32_t ybetween,
const int32_t f,
int32_t x1, int32_t y1, int32_t x2, int32_t y2);
const char* G_PrintYourTime(void);
const char* G_PrintParTime(void);
const char* G_PrintDesignerTime(void);
const char* G_PrintBestTime(void);
void G_UpdateScreenArea(void);
void G_SaveMapState(void);
void G_RestoreMapState(void);
void G_FreeMapState(int32_t mapnum);
]]
decl[[
int32_t kopen4loadfrommod(const char *filename, char searchfirst);
char **g_scriptModules;
int32_t g_scriptModulesNum;
const char *G_ConFile(void);
void G_DoGameStartup(const int32_t *params);
int32_t C_DefineSound(int32_t sndidx, const char *fn, int32_t args [5]);
void C_DefineMusic(int32_t vol, int32_t lev, const char *fn);
void C_DefineQuote(int32_t qnum, const char *qstr);
void C_DefineVolumeName(int32_t vol, const char *name);
void C_DefineVolumeFlags(int32_t vol, int32_t flags);
void C_UndefineVolume(int32_t vol);
void C_DefineSkillName(int32_t skill, const char *name);
void C_UndefineSkill(int32_t skill);
void C_DefineLevelName(int32_t vol, int32_t lev, const char *fn,
int32_t partime, int32_t designertime,
const char *levelname);
void C_UndefineLevel(int32_t vol, int32_t lev);
void C_DefineProjectile(int32_t j, int32_t what, int32_t val);
void C_DefineGameFuncName(int32_t idx, const char *name);
void C_DefineGameType(int32_t idx, int32_t flags, const char *name);
int32_t C_SetDefName(const char *name);
void C_SetCfgName(const char *cfgname);
int32_t SCRIPT_GetNumber(int32_t scripthandle, const char *sectionname, const char *entryname, int32_t *number);
void SCRIPT_PutNumber(int32_t scripthandle, const char *sectionname, const char *entryname, int32_t number,
int32_t hexadecimal, int32_t defaultvalue);
]]
-- http://lua-users.org/wiki/SandBoxes says "potentially unsafe"
-- as it allows to see implementations of functions.
--local string_dump = string.dump
string.dump = nil
-- sanity-check struct type sizes
local good = true
for i=0,10 do
local what = ffi.string(ffiC.g_sizes_of_what[i])
local fsz = ffi.sizeof(what)
local csz = ffiC.g_sizes_of[i]
if (ffiC._DEBUG_LUNATIC ~= 0) then
print(i..": "..what..": C sizeof = "..tostring(csz)..", FFI sizeof = "..tostring(fsz))
end
if (fsz ~= csz) then
good = false;
end
end
if (not good) then
error("Some sizes don't match between C and LuaJIT/FFI.")
end
--== "player" global, needed by the "control" module ==--
local player_static_members = defs_c.static_members_tab()
--[[
player_static_members._INPUT_BITS = defs_c.conststruct
{
JUMP = 1,
CROUCH = 2,
FIRE = 4,
AIM_UP = 8,
AIM_DOWN = 16,
RUNNING = 32,
LOOK_LEFT = 64,
LOOK_RIGHT = 128,
-- weapons...
STEROIDS = 4096,
LOOK_UP = 8192,
LOOK_DOWN = 16384,
NIGHTVISION = 32768,
MEDKIT = 65536,
RESERVED = 131072,
CENTER_VIEW = 262144,
HOLSTER_WEAPON = 524288,
INVENTORY_LEFT = 1048576,
PAUSE = 2097152,
QUICK_KICK = 4194304,
AIM_MODE = 8388608,
HOLODUKE = 16777216,
JETPACK = 33554432,
QUIT = 67108864,
INVENTORY_RIGHT = 134217728,
TURN_AROUND = 268435456,
OPEN = 536870912,
INVENTORY = 1073741824,
ESC = 2147483648,
}
player_static_members._INPUT_EXT_BITS = defs_c.conststruct
{
MOVE_FORWARD = 1,
MOVE_BACKWARD = 2,
STRAFE_LEFT = 4,
STRAFE_RIGHT = 8,
TURN_LEFT = 16,
TURN_RIGHT = 32,
}
--]]
local band = bit.band
local lsh = bit.lshift
local ivec3 = xmath.ivec3
do
-- player.all() iterator
local function iter_allplayers(_nil, pli)
if (pli+1 < ffiC.playerswhenstarted) then
return pli+1
end
end
function player_static_members.all()
return iter_allplayers, nil, -1
end
-- player.holdskey(pli, keyname)
local KEYS = { -- SK_CROUCH etc. -- "sync keys"
CROUCH = lsh(1,1),
RUN = lsh(1,5),
OPEN = lsh(1,29),
}
function player_static_members.holdskey(pli, keyname)
bcheck.player_idx(pli)
if (KEYS[keyname] == nil) then
error("invalid key name: "..tostring(keyname), 2)
end
return ffiC.g_player[pli].sync.bitsbits:test(KEYS[keyname])
end
end
local player_holdskey = player_static_members.holdskey
-- Actor flags
local actor_static_members = defs_c.static_members_tab()
do
local our_SFLAG = {}
local ext_SFLAG = con_lang.labels[4] -- external actor flags only
local USER_MASK = 0
for name, flag in pairs(ext_SFLAG) do
our_SFLAG[name:sub(7)] = flag -- strip "SFLAG_"
USER_MASK = bit.bor(USER_MASK, flag)
end
-- Add a couple of convenience defines.
our_SFLAG.enemy = con_lang.SFLAG.SFLAG_BADGUY
our_SFLAG.enemystayput = con_lang.SFLAG.SFLAG_BADGUY + con_lang.SFLAG.SFLAG_BADGUYSTAYPUT
our_SFLAG.rotfixed = con_lang.SFLAG.SFLAG_ROTFIXED
-- Callback function chaining control flags.
our_SFLAG.replace = 0x08000000
our_SFLAG.replace_soft = 0x08000000 -- compat
our_SFLAG.replace_hard = 0x08000000 -- compat, deprecated
our_SFLAG.chain_beg = 0x20000000
our_SFLAG.chain_end = 0x40000000
our_SFLAG._CHAIN_MASK_ACTOR = 0x78000000
our_SFLAG._CHAIN_MASK_EVENT = 0x68000000
-- XXX: CON doesn't export BADGUYSTAYPUT or ROTFIXED SFLAGs, but they are considered
-- external for Lunatic.
our_SFLAG.USER_MASK = bit.bor(USER_MASK, our_SFLAG.enemystayput, our_SFLAG.rotfixed)
actor_static_members.FLAGS = defs_c.conststruct(our_SFLAG)
-- Sprite status numbers. Kept in 'actor', because it's more of a game-side
-- concept (event though status lists are implemented in the engine), and
-- to prevent confusion with sprite.CSTAT.
local our_STAT = {}
for name, statnum in pairs(con_lang.STAT) do
-- Strip 'STAT_'.
our_STAT[name:sub(6)] = statnum
end
actor_static_members.STAT = defs_c.conststruct(our_STAT)
actor_static_members.MOVFLAGS = defs_c.conststruct
{
-- NOTE: no underscores, like in DEFS.CON.
faceplayer = 1,
geth = 2,
getv = 4,
randomangle = 8,
faceplayerslow = 16,
spin = 32,
faceplayersmart = 64,
fleeenemy = 128,
jumptoplayer_only = 256,
jumptoplayer_bits = 257, -- NOTE: two bits set!
jumptoplayer = 257,
seekplayer = 512,
furthestdir = 1024,
dodgebullet = 4096,
}
end
function actor_static_members.fall(i)
check_sprite_idx(i)
CF.VM_FallSprite(i)
end
-- actor.move(i, vec, cliptype [, clipdist])
function actor_static_members.move(i, vec, cliptype, clipdist)
check_sprite_idx(i)
local vel = ivec3(vec.x, vec.y, vec.z)
return ffiC.A_MoveSpriteClipdist(i, vel, cliptype, clipdist or -1)
end
-- Delete sprite with index <i>.
function actor_static_members.delete(i)
check_sprite_idx(i)
if (ffiC.sprite[i].statnum == ffiC.MAXSTATUS) then
error("Attempt to delete a sprite already not in the game world", 2)
end
if (ffiC.block_deletesprite ~= 0) then
error("Attempt to delete sprite in EVENT_EGS", 2)
end
-- TODO_MP
if (ffiC.g_player_ps[0].i == i) then
error("Attempt to delete player 0's APLAYER sprite", 2)
end
CF.A_DeleteSprite(i)
end
local tile_static_members = defs_c.static_members_tab()
do
tile_static_members.sizx = defs_c.creategtab_membidx(ffiC.tilesiz, "x", ffiC.MAXTILES, "tilesizx[]")
tile_static_members.sizy = defs_c.creategtab_membidx(ffiC.tilesiz, "y", ffiC.MAXTILES, "tilesizy[]")
end
-- XXX: error message will say "g_player_ps"
player = setmtonce({}, defs_c.GenStructMetatable("g_player_ps", "playerswhenstarted", player_static_members))
-- needed by "control"
actor = setmtonce({}, defs_c.GenStructMetatable("actor", "MAXSPRITES", actor_static_members))
-- Some bitwise NOTs of various actor flag masks.
local BNOT = {
USER_MASK = bit.bnot(actor.FLAGS.USER_MASK),
CHAIN_MASK_ACTOR = bit.bnot(actor.FLAGS._CHAIN_MASK_ACTOR),
CHAIN_MASK_EVENT = bit.bnot(actor.FLAGS._CHAIN_MASK_EVENT),
}
local projectile = defs_c.creategtab_membidx_ptr(ffiC.g_tile, "_proj", ffiC.MAXTILES, "projectile")
local g_tile = setmtonce({}, defs_c.GenStructMetatable("g_tile", "MAXTILES", tile_static_members))
--== Custom operations for BUILD data structures ==--
-- Among other things, declares struct action and struct move, and their
-- ID-wrapped types con_action_t and con_move_t
local con = require("control")
do
local isenemytile = con.isenemytile
-- Add game-side metamethods to "spritetype" and register it with "metatype"
local spr_mt_index_add = {
isenemy = function(s)
return isenemytile(s.picnum)
end,
}
defs_c.finish_spritetype(spr_mt_index_add)
end
-- Check a literal numeric action or move value.
local function check_literal_am(am, typename)
if (type(am) ~= "number") then
error("bad argument: expected number or "..typename, 3)
end
-- Negative values are generated as con.action/con.move IDs.
if (not (am >= 0 and am <= 32767)) then
error("bad argument: expected number in [0 .. 32767]", 3)
end
end
-- An unrestricted actor_t pointer, for internal use:
local actor_ptr_ct = ffi.typeof("$ *", ffi.typeof(strip_const(ACTOR_STRUCT)))
local player_ptr_ct = ffi.typeof("$ *", ffi.typeof(strip_const(DUKEPLAYER_STRUCT)))
local projectile_ptr_ct = ffi.typeof("$ *", ffi.typeof(strip_const(PROJECTILE_STRUCT)))
-- An unrestricted weapondata_t pointer, but with the member names stripped of
-- the leading underscore, too:
local weapondata_ptr_ct = ffi.typeof("$ *", ffi.typeof((strip_const(WEAPONDATA_STRUCT):gsub(" _"," "))))
local con_action_ct = ffi.typeof("const con_action_t")
local con_move_ct = ffi.typeof("const con_move_t")
local con_ai_ct = ffi.typeof("const con_ai_t")
-- All-zero bare action and move.
local nullac, nullmv = ffi.new("const struct action"), ffi.new("const struct move")
-- All-zero action and move with IDs. Mostly for CON support.
local literal_act = { [0]=con_action_ct(0), [1]=con_action_ct(1) }
local literal_mov = { [0]=con_move_ct(0), [1]=con_move_ct(1) }
local function get_actor_idx(a)
local i = ffi.cast(actor_ptr_ct, a)-ffi.cast(actor_ptr_ct, ffiC.actor)
-- assert(not (i >= ffiC.MAXSPRITES+0ULL))
return i
end
local actor_methods = {
-- action
set_action = function(a, act)
a = ffi.cast(actor_ptr_ct, a)
if (ffi.istype(con_action_ct, act)) then
a.t_data[4] = act.id
a.ac = act.ac
else
check_literal_am(act, "action")
a.t_data[4] = act
a.ac = nullac
end
a.t_data[2] = 0
a.t_data[3] = 0
end,
has_action = function(a, act)
a = ffi.cast(actor_ptr_ct, a)
if (ffi.istype(con_action_ct, act)) then
return (a.t_data[4]==act.id)
else
check_literal_am(act, "action")
return (a.t_data[4]==act)
end
end,
-- count
set_count = function(a, count)
ffi.cast(actor_ptr_ct, a).t_data[0] = count
end,
get_count = function(a)
return ffi.cast(actor_ptr_ct, a).t_data[0]
end,
-- action count
reset_acount = function(a)
ffi.cast(actor_ptr_ct, a).t_data[2] = 0
end,
get_acount = function(a)
return ffi.cast(actor_ptr_ct, a).t_data[2]
end,
-- Override action delay. The action ID is kept.
set_action_delay = function(a, delay)
ffi.cast(actor_ptr_ct, a).ac.delay = delay
end,
-- move
set_move = function(a, mov, movflags)
a = ffi.cast(actor_ptr_ct, a)
if (ffi.istype(con_move_ct, mov)) then
a.t_data[1] = mov.id
a.mv = mov.mv
else
check_literal_am(mov, "move")
a.t_data[1] = mov
a.mv = nullmv
end
a.t_data[0] = 0
a.movflags = movflags or 0
local spr = ffiC.sprite[get_actor_idx(a)]
if (not spr:isenemy() or spr.extra > 0) then
if (bit.band(a.movflags, 8) ~= 0) then -- random_angle
spr.ang = bit.band(ffiC.krand(), 2047)
end
end
end,
has_move = function(a, mov)
a = ffi.cast(actor_ptr_ct, a)
if (ffi.istype(con_move_ct, mov)) then
return (a.t_data[1]==mov.id)
else
check_literal_am(mov, "move")
return (a.t_data[1]==mov)
end
end,
-- Override velocity, keeping move ID.
set_hvel = function(a, hvel)
ffi.cast(actor_ptr_ct, a).mv.hvel = hvel
end,
set_vvel = function(a, vvel)
ffi.cast(actor_ptr_ct, a).mv.vvel = vvel
end,
-- ai
set_ai = function(a, ai)
local oa = a
a = ffi.cast(actor_ptr_ct, a)
-- TODO: literal number AIs?
if (not ffi.istype(con_ai_ct, ai)) then
error("bad argument: expected ai", 2)
end
-- NOTE: compare with gameexec.c, "CON_AI:"
a.t_data[5] = ai.id
oa:set_action(ai.act)
oa:set_move(ai.mov, ai.movflags)
-- Already reset with set_move():
-- a.t_data[0] = 0
end,
has_ai = function(a, ai)
a = ffi.cast(actor_ptr_ct, a)
if (ffi.istype(con_ai_ct, ai)) then
return (a.t_data[5]==ai.id)
else
check_literal_am(ai, "ai")
return (a.t_data[5]==ai)
end
end,
-- Getters/setters.
_get_t_data = function(a, idx)
if (not (idx >= 0 and idx < 10)) then
error("invalid t_data index "..idx, 2)
end
return ffi.cast(actor_ptr_ct, a).t_data[idx]
end,
_set_t_data = function(a, idx, val)
if (not (idx >= 0 and idx < 10)) then
error("invalid t_data index "..idx, 2)
end
ffi.cast(actor_ptr_ct, a).t_data[idx] = val
end,
set_picnum = function(a, picnum)
if (not (picnum < 0)) then
check_tile_idx(picnum)
end
ffi.cast(actor_ptr_ct, a).picnum = picnum
end,
set_owner = function(a, owner)
-- XXX: is it permissible to set to -1?
check_sprite_idx(owner)
ffi.cast(actor_ptr_ct, a).owner = owner
end,
--- Custom methods ---
-- Checkers for whether the movement update made the actor hit
-- something.
checkhit = function(a)
-- Check whether we hit *anything*, including ceiling/floor.
return a._movflagbits:test(49152)
end,
checkbump = function(a)
-- Check whether we bumped into a wall or sprite.
return (a._movflagbits:mask(49152) >= 32768)
end,
hitwall = function(a)
if (a._movflagbits:mask(49152) == 32768) then
return a._movflagbits:mask(32767)
end
end,
hitsprite = function(a)
if (a._movflagbits:mask(49152) == 49152) then
return a._movflagbits:mask(32767)
end
end,
-- NOTE: no 'hitsector' or 'hitceiling' / 'hitfloor' for now because
-- more research is needed as to what the best way of checking c/f is.
}
local actor_mt = {
__index = function(a, key)
if (actor_methods[key] ~= nil) then
return actor_methods[key]
elseif (key == "proj") then
return ffiC.SpriteProjectile[get_actor_idx(a)]
else
error("invalid indexing key to actor object", 2)
end
end,
}
ffi.metatype("actor_t", actor_mt)
--- PER-PLAYER WEAPON SETTINGS
local wd_sound_member = {}
for _, declstr in pairs(con_lang.wdata_members) do
local member = declstr:match("const int32_t _(.*sound)$")
if (member) then
wd_sound_member[member] = true
if (ffiC._DEBUG_LUNATIC ~= 0) then
printf("weapondata_t member %s denotes a sound", member)
end
end
end
local weapondata_mt = {
__index = function(wd, member)
-- Handle protected members that are renamed (e.g. shoots/_shoots).
return ffi.cast(weapondata_ptr_ct, wd)[0][member]
end,
__newindex = function(wd, member, val)
-- Set to 'true' if we set a tile or sound member.
local didit = false
check_type(member, "string") -- MEMBER_IS_STRING
check_number(val)
if (wd_sound_member[member]) then -- XXX: sound2time is a time, not a sound
if (val < 0) then
val = 0 -- Set to 0 if negative (e.g. CrackDown).
else
check_sound_idx(val)
end
didit = true
elseif (member=="workslike") then
check_weapon_idx(val)
elseif (member=="spawn" or member=="shoots") then
if (val < 0) then
-- Set to 0 if oob (e.g. CrackDown). This is a bit problematic
-- for .shoots because it's used unconditionally except in one
-- case (see player.c).
val = 0
else
check_tile_idx(val)
end
didit = true
end
-- DEBUG:
-- printf("assigning %s to weapon's %s", tostring(val), member)
-- NOTE: we're indexing a *pointer* with the user-supplied 'member',
-- which could be dangerouns if it could be a number. However, we have
-- assured that is is not in MEMBER_IS_STRING above.
ffi.cast(weapondata_ptr_ct, wd)[member] = val
if (didit and ffiC.g_elCallDepth==0) then
-- Signal that we overrode this member at CON translation time.
-- Get weapon index as pointer difference first. PLAYER_0.
local wi = ffi.cast(weapondata_ptr_ct, wd)
- ffi.cast(weapondata_ptr_ct, ffiC.g_playerWeapon)
assert(wi >= 0 and wi < ffiC.MAX_WEAPONS)
-- Set g_weaponOverridden[wi][member], but without invoking
-- weapondata_t's __newindex metamethod (i.e. us)!
ffi.cast(weapondata_ptr_ct, ffiC.g_weaponOverridden[wi])[member] = 1
end
end,
}
ffi.metatype("weapondata_t", weapondata_mt)
local weaponaccess_mt = {
-- Syntax like "player[0].weapon.KNEE.shoots" possible because
-- g_playerWeapon[] is declared as an array of corresponding bcarray types
-- for us.
__index = function(wa, key)
if (type(key)~="number" and type(key)~="string") then
error("must access weapon either by number or by name")
end
return ffiC.g_playerWeapon[wa._p][key]
end,
}
ffi.metatype("weaponaccess_t", weaponaccess_mt)
local function clamp(num, min, max)
return num < min and min
or num > max and max
or num
end
local function clamp0to1(num)
check_number(num, 4)
return clamp(num, 0, 1)
end
local player_methods = {
-- CON-like addammo/addweapon, but without the non-local control flow
-- (returns true if weapon's ammo was at the max. instead).
addammo = con._addammo,
addweapon = con._addweapon,
stomp = con._pstomp,
holdskey = function(p, keyname)
-- XXX: on invalid <keyname>, error will point to this next line:
return player_holdskey(p.weapon._p, keyname)
end,
has_weapon = function(p, weap)
return p.gotweaponbits:test(lsh(1,weap))
end,
give_weapon = function(p, weap)
p.gotweaponbits:set(lsh(1,weap))
end,
take_weapon = function(p, weap)
p.gotweaponbits:clear(lsh(1,weap))
end,
-- Give or take weapon, for implementation of CON's .gotweapon access.
_gt_weapon = function(p, weap, give_p)
if (give_p ~= 0) then
p:give_weapon(weap)
else
p:take_weapon(weap)
end
end,
whack = function(p, no_return_to_center)
p.horiz = p.horiz + 64
if (not no_return_to_center) then
p.return_to_center = 9
end
local n = bit.arshift(128-band(ffiC.krand(),255), 1)
p.rotscrnang = n
p.look_ang = n
end,
-- External, improved 'palfrom'.
-- <speed>: possibly fractional speed of tint fading, in pals.f decrements per gametic.
-- XXX: exposes internals.
-- <prio>: a value from -128 to 127, higher ones trump lower or equal ones
fadecol = function(p, fadefrac, r, g, b, speed, prio)
-- Validate inargs: clamp f,r,g,b to [0 .. 1] first and multiply by
-- 63 for the internal handling.
fadefrac = clamp0to1(fadefrac)*63
-- NOTE: a fadefrac of now <1 is allowed, e.g. for clearing the tint.
r = clamp0to1(r)*63
g = clamp0to1(g)*63
b = clamp0to1(b)*63
if (speed ~= nil) then
check_number(speed)
-- Clamp to sensible values; the speed is stored in an int8_t
-- (see below).
speed = clamp(speed, 1/128, 127)
else
speed = 1
end
if (prio ~= nil) then
check_number(prio)
if (not (prio >= -128 and prio < 127)) then
error("invalid argument #6 (priority): must be in [-128 .. 127]", 2)
end
else
prio = 0
end
-- Check if a currently active tint has higher priority.
if (p._pals.f > 0 and p._palsfadeprio > prio) then
return
end
-- The passed tint can be applied now.
p:_palfrom(fadefrac, r, g, b)
p._palsfadeprio = prio
-- Calculate .palsfade{speed,next}
if (speed >= 1) then
-- Will round to the nearest integer ("banker's
-- rounding"). NOTE: This is not correct for all numbers, see
-- http://blog.frama-c.com/index.php?post/2013/05/02/nearbyintf1
p._palsfadespeed = speed + 0.5
p._palsfadenext = 0
else
-- NOTE: Values that round to 0 have are equivalent behavior to
-- passing a <speed> of 1.
local negspeedrecip = -((1/speed) + 0.5) -- [-128.5 .. 1/127+0.5]
p._palsfadespeed = negspeedrecip
p._palsfadenext = negspeedrecip
end
end,
-- INTERNAL and CON-only.
_palfrom = function(p, f, r,g,b)
local pals = p._pals
-- Assume that CON's palfrom starts with prio 0 and speed 0.
if (pals.f == 0 or p._palsfadeprio <= 0) then
pals.f = f
pals.r, pals.g, pals.b = r, g, b
p._palsfadespeed, p._palsfadenext = 0, 0
end
end,
}
local player_mt = {
__index = function(p, key)
if (player_methods[key] ~= nil) then
return player_methods[key]
elseif (key == "_input") then
return ffiC.g_player[p.weapon._p].sync[0]
else
-- Read access to protected player members.
return ffi.cast(player_ptr_ct, p)[0][key]
end
end,
__newindex = function(p, key, val)
-- Write access to protected player members.
local allowneg = DukePlayer_prot_allowneg[key]
assert(type(allowneg)=="boolean")
if (allowneg==false or not (val == -1)) then
DukePlayer_prot_chkfunc[key](val)
end
ffi.cast(player_ptr_ct, p)[key] = val
end,
}
ffi.metatype("DukePlayer_t", player_mt)
local function GenProjectileSetFunc(Member, checkfunc)
return function(self, idx)
if (not (idx == -1)) then
checkfunc(idx)
end
ffi.cast(projectile_ptr_ct, self)[Member] = idx
end
end
local projectile_mt = {
__index = {
set_spawns = GenProjectileSetFunc("spawns", check_tile_idx),
set_decal = GenProjectileSetFunc("decal", check_tile_idx),
set_trail = GenProjectileSetFunc("trail", check_tile_idx),
set_sound = GenProjectileSetFunc("sound", check_sound_idx),
set_isound = GenProjectileSetFunc("isound", check_sound_idx),
set_bsound = GenProjectileSetFunc("bsound", check_sound_idx),
},
}
ffi.metatype("projectile_t", projectile_mt)
local user_defs_mt = {
__index = {
set_screen_size = function(ud, screen_size)
if (ud.screen_size ~= screen_size) then
ud.screen_size = screen_size
ffiC.G_UpdateScreenArea()
end
end,
set_volume_number = function(ud, volume_number)
-- NOTE: allow volume_number==MAXVOLUMES.
if (not (volume_number==con_lang.MAXVOLUMES)) then
bcheck.volume_idx(volume_number)
end
ud.volume_number = volume_number
end,
set_m_volume_number = function(ud, volume_number)
-- NOTE: allow volume_number==MAXVOLUMES.
if (not (volume_number==con_lang.MAXVOLUMES)) then
bcheck.volume_idx(volume_number)
end
ud.m_volume_number = volume_number
end,
set_level_number = function(ud, level_number)
bcheck.level_idx(level_number)
ud.level_number = level_number
end,
},
}
ffi.metatype("user_defs", user_defs_mt)
--- CUSTOM "gv" VARIABLES
local camera_mt = {
-- TODO: "set position" method, which also updates the sectnum
__index = ffiC.g_camera,
__newindex = function(_, key, val)
if (key=="sect") then
check_sector_idx(val)
end
ffiC.g_camera[key] = val
end,
}
gv_access.cam = setmtonce({}, camera_mt)
gv_access._ud = ffiC.ud
-- Support for some CON global system gamevars. RETURN handled separately.
gv_access._csv = ffi.new "struct { int32_t LOTAG, HITAG, TEXTURE; }"
gv_access.REND = defs_c.conststruct
{
CLASSIC = 0,
POLYMOST = 3,
POLYMER = 4,
}
gv_access.WEAPON = lprivate.WEAPON
gv_access.GET = lprivate.GET
function gv_access._get_yxaspect()
return ffiC.yxaspect
end
function gv_access._get_viewingrange()
return ffiC.viewingrange
end
function gv_access._currentFramerate()
return ffiC.g_currentFrameRate
end
function gv_access._currentMenu()
return ffiC.g_currentMenu
end
function gv_access._changeMenu(cm)
ffiC.M_ChangeMenu(cm)
end
function gv_access._set_guniqhudid(id)
local MAXUNIQHUDID = 256 -- KEEPINSYNC build.h
if (not (id >= 0 and id < MAXUNIQHUDID)) then
error("invalid unique HUD ID "..id)
end
ffiC.guniqhudid = id
end
function gv_access.currentEpisode()
return ffiC.ud.volume_number + 1
end
function gv_access.currentLevel()
return ffiC.ud.level_number + 1
end
function gv_access.doQuake(gametics, snd)
ffiC.g_earthquakeTime = gametics
if (snd ~= nil) then
con._globalsound(ffiC.screenpeek, snd)
end
end
-- Declare all con_lang.labels constants in the global FFI namespace.
for i=1,#con_lang.labels do
if (getmetatable(con_lang.labels[i]) ~= "noffiC") then
local strbuf = {"enum {"}
for label, val in pairs(con_lang.labels[i]) do
strbuf[#strbuf+1] = string.format("%s = %d,", label, val)
end
strbuf[#strbuf+1] = "};"
ffi.cdef(table.concat(strbuf))
end
end
---=== Set up restricted global environment ===---
local allowed_modules = {
coroutine=coroutine, bit=bit, table=table, math=math, string=string,
os = {
clock = function() return gv_.gethiticks()*0.001 end,
},
randgen = randgen,
engine = require("engine"),
stat = require("stat"),
bitar = require("bitar"),
xmath = xmath,
fs = require("fs"),
con = con,
}
do
local ctype_cansave = {}
-- Register as "serializeable" the type of cdata object <v>.
local function reg_serializable_cv(v)
assert(type(v)=="cdata")
assert(type(v._serialize)=="function")
-- NOTE: tonumber() on a ctype cdata object gets its LuaJIT-internal
-- ID, the one that would be shown with tostring(), e.g.
-- ctype<struct 95>
ctype_cansave[tonumber(ffi.typeof(v))] = true
end
function lprivate.cansave_cdata(v)
return type(v)=="cdata" and ctype_cansave[tonumber(ffi.typeof(v))]
end
reg_serializable_cv(xmath.vec3())
reg_serializable_cv(ivec3())
end
-- Protect base modules.
local function basemod_newidx()
error("modifying base module table forbidden", 2)
end
for modname, themodule in pairs(allowed_modules) do
local mt = {
__index = themodule,
__newindex = basemod_newidx,
}
allowed_modules[modname] = setmtonce({}, mt)
end
---=== Module stuff ===---
local package_loaded = {} -- [<modname>] = false/true/table
local modname_stack = {} -- [<depth>]=string
local module_gamevars = {} -- [<modname>] = { <gvname1>, <gvname2>, ... }
local module_gvlocali = {} -- [<modname>] = { <localidx_beg>, <localidx_end> }
local module_thread = {} -- [<modname>] = <module_thread>
local function getcurmodname(thisfuncname)
if (#modname_stack == 0) then
error("'"..thisfuncname.."' must be called at the top level of a require'd file", 3)
-- ... as opposed to "at runtime".
end
return modname_stack[#modname_stack]
end
local function errorf(level, fmt, ...)
local errmsg = string.format(fmt, ...)
error(errmsg, level+1)
end
local function readintostr_mod(fn)
-- TODO: g_loadFromGroupOnly?
local fd = ffiC.kopen4loadfrommod(fn, 0)
if (fd < 0) then
return nil
end
return defs_c.readintostr(fd)
end
local debug = require("debug")
-- Get the number of active locals in the function that calls the function
-- calling this one.
local function getnumlocals(l)
-- 200 is the max. number of locals at one level
for i=1,200 do
-- level:
-- 0 is debug.getlocal() itself.
-- 1 is this function (getnumlocals).
-- 2 is the function calling getnumlocals()
-- 3 is the function calling that one.
if (debug.getlocal(3, i) == nil) then
return i-1
end
end
end
local function error_on_nil_read(_, varname)
error("attempt to read nil variable '"..varname.."'", 2)
end
local required_module_mt = {
__index = error_on_nil_read,
__newindex = function()
error("modifying module table forbidden", 2)
end,
__metatable = true,
}
-- Will contain a function to restore gamevars when running from savegame
-- restoration. See SAVEFUNC_ARGS for its arguments.
local g_restorefunc = nil
-- Local gamevar restoration function run from
-- our_require('end_gamevars') <- [user module].
local function restore_local(li, lval)
-- level:
-- 0 is getlocal() itself.
-- 1 is this function (restore_local).
-- 2 is the function calling restore_local(), the savecode.
-- 3 is the function calling the savecode, our_require.
-- 4 is the function calling our_require, the module function.
if (ffiC._DEBUG_LUNATIC ~= 0) then
printf("Restoring index #%d (%s) with value %s",
li, debug.getlocal(4, li), tostring(lval))
end
assert(debug.setlocal(4, li, lval))
end
-- The "require" function accessible to Lunatic code.
-- Base modules in allowed_modules are wrapped so that they cannot be
-- modified, user modules are searched in the EDuke32 search
-- path. Also, our require
-- * never messes with the global environment, it only returns the module.
-- * allows passing varargs beyond the name to the module.
local function our_require(modname, ...)
local ERRLEV = 5
-- Check module name is valid first.
-- TODO: restrict valid names?
if (type(modname) ~= "string" or #modname==0) then
error("module name must be a nonempty string", 2)
end
-- For _LUNATIC_DBG
if (modname:match("^_LUNATIC") and ffiC._DEBUG_LUNATIC == 0) then
return nil
end
-- Handle the section between module() and require("end_gamevars").
if (modname == "end_gamevars") then
local thismodname = getcurmodname("require")
if (module_gamevars[thismodname] ~= nil) then
error("\"require 'end_gamevars'\" must be called at most once per require'd file", 2)
end
local gvnames = {}
for name in pairs(getfenv(2)) do
gvnames[#gvnames+1] = name
if (ffiC._DEBUG_LUNATIC ~= 0) then
printf("MODULE %s GAMEVAR %s", thismodname, name)
end
end
module_gamevars[thismodname] = gvnames
local gvmodi = module_gvlocali[thismodname]
gvmodi[2] = getnumlocals()
if (ffiC._DEBUG_LUNATIC ~= 0) then
local numlocals = gvmodi[2]-gvmodi[1]+1
if (numlocals > 0) then
printf("Module '%s' has %d locals, index %d to %d",
thismodname, numlocals, gvmodi[1], gvmodi[2])
end
end
-- Potentially restore gamevars.
if (g_restorefunc) then
local modtab = package_loaded[thismodname]
assert(type(modtab)=="table")
-- SAVEFUNC_ARGS.
g_restorefunc(thismodname, modtab, restore_local)
end
-- Return whether we're NOT running from a savegame restore in the
-- second outarg. (Lunatic-private!)
return nil, (g_restorefunc==nil)
end
-- See whether it's a base module name.
if (allowed_modules[modname] ~= nil) then
return allowed_modules[modname]
end
--- Search user modules...
if (modname:find("[/\\]")) then
error("Module name must not contain directory separators", ERRLEV-1)
end
-- Instead, dots are translated to directory separators. For EDuke32's
-- virtual file system, this is always a forward slash. Keep the original
-- module name for passing to the module function.
local omodname = modname
modname = modname:gsub("%.", "/")
local omod = package_loaded[modname]
if (omod ~= nil) then
if (omod==false) then
error("Loop while loading modules", ERRLEV-1)
end
-- already loaded
assert(omod==true or type(omod)=="table")
return omod
end
local modfn = modname .. ".lua"
local str = readintostr_mod(modfn)
if (str == nil) then
errorf(ERRLEV-1, "Couldn't open file \"%s\"", modfn)
end
-- Implant code that yields the module thread just before it would return
-- otherwise.
str = str.."\nrequire('coroutine').yield()"
local modfunc, errmsg = loadstring(str, modfn)
if (modfunc == nil) then
errorf(ERRLEV-1, "Couldn't load \"%s\": %s", modname, errmsg)
end
package_loaded[modname] = false -- 'not yet loaded'
table.insert(modname_stack, modname)
-- Run the module code in a separate Lua thread!
local modthread = coroutine.create(modfunc)
local ok, retval = coroutine.resume(modthread, omodname, ...)
if (not ok) then
errorf(ERRLEV-1, "Failed running \"%s\": %s\n%s", modname,
retval, debug.traceback(modthread))
end
table.remove(modname_stack)
local modtab = package_loaded[modname]
if (type(modtab) ~= "table") then
-- The module didn't call our 'module'. Check if it returned a table.
-- In that case, the coroutine has finished its main function and has
-- not reached our implanted 'yield'.
if (coroutine.status(modthread)=="dead" and type(retval)=="table") then
modtab = retval
package_loaded[modname] = modtab
else
package_loaded[modname] = true
end
end
if (type(modtab) == "table") then
-- Protect module table in any case (i.e. either if the module used our
-- 'module' or if it returned a table).
setmetatable(modtab, required_module_mt)
end
local gvmodi = module_gvlocali[modname]
if (gvmodi and gvmodi[2] and gvmodi[2]>=gvmodi[1]) then
if (coroutine.status(modthread)=="suspended") then
-- Save off the suspended thread so that we may get its locals later on.
-- It is never resumed, but only ever used for debug.getlocal().
module_thread[modname] = modthread
if (ffiC._DEBUG_LUNATIC ~= 0) then
printf("Keeping coroutine for module \"%s\"", modname)
end
end
end
return modtab
end
local module_mt = {
__index = error_on_nil_read,
}
-- Our 'module' replacement doesn't get the module name from the function args
-- since a malicious user could remove other loaded modules this way.
-- Also, our 'module' takes no varargs ("option functions" in Lua).
-- TODO: make transactional?
local function our_module()
if (#modname_stack == 0) then
error("'module' must be called at the top level of a require'd file", 2)
-- ... as opposed to "at runtime".
end
local modname = getcurmodname("module")
if (package_loaded[modname]) then
error("'module' must be called at most once per require'd file", 2)
end
local M = setmetatable({}, module_mt)
package_loaded[modname] = M
-- change the environment of the function which called us:
setfenv(2, M)
module_gvlocali[modname] = { getnumlocals()+1 }
end
-- overridden 'error' that always passes a string to the base 'error'
local function our_error(errmsg, level)
if (type(errmsg) ~= "string") then
error("error using 'error': error message must be a string", 2)
end
if (level) then
if (type(level) ~= "number") then
error("error using 'error': error level must be a number", 2)
end
error(errmsg, level==0 and 0 or level+1)
end
error(errmsg, 2)
end
-- _G tweaks -- pull in only 'safe' stuff
local G_ = {} -- our soon-to-be global environment
G_.assert = assert
G_.error = our_error
G_.ipairs = ipairs
G_.pairs = pairs
G_.pcall = pcall
G_.print = print
G_.module = our_module
G_.next = next
G_.require = our_require
G_.select = select
G_.tostring = tostring
G_.tonumber = tonumber
G_.type = type
G_.unpack = unpack
G_.xpcall = xpcall
G_._VERSION = _VERSION
-- Available through our 'require':
-- bit, coroutine, math, string, table
-- Not available:
-- collectgarbage, debug, dofile, gcinfo (DEPRECATED), getfenv, getmetatable,
-- jit, load, loadfile, loadstring, newproxy (NOT STD?), package, rawequal,
-- rawget, rawset, setfenv, setmetatable
G_._G = G_
-- Chain together two functions taking 3 input args.
local function chain_func3(func1, func2)
if (func1==nil or func2==nil) then
return assert(func1 or func2)
end
-- Return a function that runs <func1> first and then tail-calls <func2>.
return function(aci, pli, dist)
func1(aci, pli, dist)
return func2(aci, pli, dist)
end
end
-- Determines the last numeric index of a table using *pairs*, so that in
-- arg-lists with "holes" (e.g. {1, 2, nil, function() end}) are handled
-- properly.
local function ourmaxn(tab)
local maxi = 0
for i in pairs(tab) do
if (type(i)=="number") then
maxi = math.max(i, maxi)
end
end
assert(tab[maxi] ~= nil)
return maxi
end
-- Running for the very first time?
local g_firstRun = (ffiC.g_elCONSize == 0)
-- Actor functions, saved for actor chaining
local actor_funcs = {}
-- Event functions, saved for event chaining
local event_funcs = {}
-- Per-actor sprite animation callbacks
local animsprite_funcs = {}
local gameactor_internal = gameactor_internal -- included in lunatic.c
local gameevent_internal = gameevent_internal -- included in lunatic.c
local function animate_all_sprites()
for i=0,ffiC.spritesortcnt-1 do
local tspr = ffiC.tsprite[i]
if (tspr.owner < ffiC.MAXSPRITES+0ULL) then
local spr = tspr:getspr()
local animfunc = animsprite_funcs[spr.picnum]
if (animfunc) then
animfunc(tspr)
end
end
end
end
local function check_arg_number(name, argpos, val)
if (type(val) ~= "number") then
errorf(3, "invalid '%s' argument (#%d) to gameactor: must be a number", name, argpos)
end
end
-- gameactor{tilenum [, flags [, strength [, action [, move [, movflags]]]]], func}
-- Every arg may be positional OR key=val (with the name indicated above as key),
-- but not both.
local function our_gameactor(args)
bcheck.top_level("gameactor")
if (type(args)~="table") then
error("invalid gameactor call: must be passed a table")
end
local tilenum = args[1]
if (type(tilenum) ~= "number") then
error("invalid argument #1 to gameactor: must be a number", 2)
end
if (not (tilenum >= 0 and tilenum < ffiC.MAXTILES)) then
error("invalid argument #1 to gameactor: must be a tile number [0..gv.MAXTILES-1]", 2)
end
local lastargi = ourmaxn(args)
local func = args[lastargi]
if (type(func) ~= "function") then
func = args.func
lastargi = 1/0
end
if (type(func) ~= "function") then
error("invalid gameactor call: must provide a function with last numeric arg or .func", 2)
end
local flags = (lastargi > 2 and args[2]) or args.flags or 0
check_arg_number("flags", 2, flags)
local AF = actor.FLAGS
local chainflags = band(flags, AF._CHAIN_MASK_ACTOR)
flags = band(flags, BNOT.CHAIN_MASK_ACTOR)
if (chainflags == 0) then
-- Default chaining behavior: don't, replace the old actor instead.
chainflags = AF.replace
elseif (band(chainflags, chainflags-1) ~= 0) then
error("invalid chaining control flags to gameactor", 2)
end
local replacep = (chainflags==AF.replace)
if (not replacep and not actor_funcs[tilenum]) then
error("attempt to chain code to nonexistent actor tile "..tilenum, 2)
end
local flags_rbits = band(flags, BNOT.USER_MASK)
if (flags_rbits ~= 0) then
error("invalid 'flags' argument (#2) to gameactor: must not set reserved bits (0x"
..(bit.tohex(flags_rbits))..")", 2)
end
local strength = ((lastargi > 3 and args[3]) or args.strength) or (replacep and 0 or nil)
if (replacep or strength~=nil) then
check_arg_number("strength", 3, strength)
end
local act = ((lastargi > 4 and args[4]) or args.action) or (replacep and literal_act[0] or nil)
if (replacep or act ~= nil) then
if (type(act)=="number" and (act==0 or act==1)) then
act = literal_act[act]
elseif (not ffi.istype(con_action_ct, act)) then
error("invalid 'action' argument (#4) to gameactor: must be an action", 2)
end
end
local mov = ((lastargi > 5 and args[5]) or args.move) or (replacep and literal_mov[0] or nil)
if (replacep or mov ~= nil) then
if (type(mov)=="number" and (mov==0 or mov==1)) then
mov = literal_mov[mov]
elseif (not ffi.istype(con_move_ct, mov)) then
error("invalid 'move' argument (#5) to gameactor: must be a move", 2)
end
end
local movflags = ((lastargi > 6 and args[6]) or args.movflags) or (replacep and 0 or nil)
if (replacep or movflags ~= nil) then
check_arg_number("movflags", 6, movflags)
end
-- Register a potentially passed drawn sprite animation callback function.
-- TODO: allow registering without main actor execution callback.
local animfunc = args.animate
if (animfunc ~= nil) then
if (type(animfunc) ~= "function") then
error("invalid 'animate' argument to gameactor: must be a function", 2)
end
animsprite_funcs[tilenum] = replacep and func
or (chainflags==AF.chain_beg) and chain_func3(animfunc, animsprite_funcs[tilenum])
or (chainflags==AF.chain_end) and chain_func3(animsprite_funcs[tilenum], animfunc)
or assert(false)
-- Register our EVENT_ANIMATEALLSPRITES only now so that it is not
-- called if there are no 'animate' definitions.
gameevent_internal(97, animate_all_sprites) -- EVENT_ANIMATEALLSPRITES
end
-- All good, bitwise-OR the tile bits and register the actor!
ffiC.g_tile[tilenum]._flags = bit.bor(ffiC.g_tile[tilenum]._flags, flags)
local newfunc = replacep and func
or (chainflags==AF.chain_beg) and chain_func3(func, actor_funcs[tilenum])
or (chainflags==AF.chain_end) and chain_func3(actor_funcs[tilenum], func)
or assert(false)
gameactor_internal(tilenum, strength, act, mov, movflags, newfunc)
actor_funcs[tilenum] = newfunc
end
-- gameevent{<event idx or string> [, flags], <event function>}
local function our_gameevent(args)
bcheck.top_level("gameevent")
if (type(args)~="table") then
error("invalid gameevent call: must be passed a table")
end
local event = args[1]
if (type(event) == "string") then
if (event:sub(1,6) ~= "EVENT_") then
event = "EVENT_"..event
end
local eventidx = con_lang.EVENT[event]
if (eventidx == nil) then
errorf(2, "gameevent: invalid event label %q", event)
end
event = eventidx
end
if (type(event) ~= "number") then
error("invalid argument #1 to gameevent: must be a number or event label", 2)
end
if (not (event >= 0 and event < con_lang.MAXEVENTS)) then
error("invalid argument #1 to gameevent: must be an event number (0 .. MAXEVENTS-1)", 2)
end
local AF = actor.FLAGS
-- Kind of CODEDUP from our_gameactor.
local lastargi = ourmaxn(args)
local func = args[lastargi]
if (type(func) ~= "function") then
func = args.func
lastargi = 1/0
end
if (type(func) ~= "function") then
error("invalid gameevent call: must provide a function with last numeric arg or .func", 2)
end
-- Event chaining: in Lunatic, chaining at the *end* is the default.
local flags = (lastargi > 2 and args[2]) or args.flags or AF.chain_end
if (type(flags) ~= "number") then
error("invalid 'flags' argument (#2) to gameevent: must be a number", 2)
end
if (band(flags, BNOT.CHAIN_MASK_EVENT) ~= 0) then
error("invalid 'flags' argument to gameevent: must not set reserved bits", 2)
end
local newfunc = (flags==AF.replace) and func
or (flags==AF.chain_beg) and chain_func3(func, event_funcs[event])
or (flags==AF.chain_end) and chain_func3(event_funcs[event], func)
or assert(false)
gameevent_internal(event, newfunc)
event_funcs[event] = newfunc
end
--- non-default data and functions
G_.gameevent = our_gameevent
G_.gameactor = our_gameactor
-- These come from above:
G_.player = player
G_.actor = actor
G_.projectile = projectile
G_.g_tile = g_tile
G_.LUNATIC_FIRST_TIME = (ffiC.g_elFirstTime ~= 0)
-- A table that can be used for temporary data when debugging from the OSD.
G_.d = {}
---=== Lunatic translator setup ===---
read_into_string = readintostr_mod -- for lunacon
local lunacon = require("lunacon")
local concode, lineinfo
--- Get Lua code for CON (+ mutator) code.
if (g_firstRun) then
-- Compiling CON for the first time.
local confn = { ffi.string(ffiC.G_ConFile()) }
local nummods = ffiC.g_scriptModulesNum
if (nummods > 0) then
assert(ffiC.g_scriptModules ~= nil)
for i=1,nummods do
confn[i+1] = ffi.string(ffiC.g_scriptModules[i-1])
end
end
concode, lineinfo = lunacon.compile(confn)
if (concode == nil) then
error("Failure compiling CON code, exiting.", 0)
end
assert(lineinfo)
-- Back up the translated code on the C side.
assert(type(concode)=="string")
ffiC.El_SetCON(concode)
else
-- CON was already compiled.
concode = ffi.string(ffiC.g_elCON, ffiC.g_elCONSize)
lineinfo = lunacon.get_lineinfo(concode)
end
if (ffiC._DEBUG_LUNATIC ~= 0) then
-- XXX: lineinfo of 2nd up time has one line less.
printf("CON line info has %d Lua lines", #lineinfo.llines)
end
do
-- Translate one Lua line number to a CON file name + line number
local function transline(lnum)
return string.format("%s:%d", lineinfo:getfline(tonumber(lnum)))
end
-- Register the function that tweaks an error message, looking out for
-- errors from CON and translating the line numbers.
local function tweak_traceback_msg(errmsg)
return errmsg:gsub('%[string "CON"%]:([0-9]+)', transline)
end
lprivate.tweak_traceback_msg = tweak_traceback_msg
set_tweak_traceback_internal(tweak_traceback_msg)
end
-- XXX: May still be require'd from user code, we don't want that (at least not
-- under this name).
local CON_MODULE_NAME = "_CON\0"
-- Set up Lunatic gamevar serialization.
do
local savegame = require("savegame")
-- Callback for: const char *(int32_t *slenptr, int32_t levelnum);
ffiC.El_SerializeGamevars = function(slenptr, levelnum)
local sb = savegame.savebuffer()
-- Module name, module table, restore_local. See SAVEFUNC_ARGS.
sb:addraw("local N,M,F=...")
-- A local to temporarily hold module locals.
sb:addraw("local L")
-- XXX: System gamevars? Most of them ought to be saved with C data.
for modname, modvars in pairs(module_gamevars) do
local isCON = (modname==CON_MODULE_NAME)
sb:startmod(modname)
-- Handle global gamevars first.
for i=1,#modvars do
local varname = modvars[i]
local excludedVars = isCON and varname=="_V" and
package_loaded[CON_MODULE_NAME]._V._IS_NORESET_GAMEVAR or nil
-- Serialize gamevar named 'varname' from module named 'modname'.
-- XXX: May error. This will terminate EDuke32 since this callback
-- is run unprotected.
if (sb:add("M."..varname, package_loaded[modname][varname], excludedVars)) then
-- We couldn't serialize that gamevar.
slenptr[0] = -1
-- Signal which gamevar that was.
return (isCON and "<CON>" or modname).."."..varname
end
end
local modthread = module_thread[modname]
if (modthread) then
-- Handle local gamevars.
local gvmodi = module_gvlocali[modname]
for li=gvmodi[1],gvmodi[2] do
-- Serialize local with index <li>. Get its value first.
local lname, lval = debug.getlocal(modthread, 1, li)
if (sb:add("L", lval)) then
-- We couldn't serialize that gamevar.
slenptr[0] = -1
return "local "..modname.."."..lname
end
-- Emit code to call restore_local.
sb:addrawf("F(%d,L)", li)
end
end
sb:endmod()
end
-- Get the whole code as a string.
local savecode = sb:getcode()
if (ffiC._DEBUG_LUNATIC ~= 0) then
-- Dump the code if Lunatic debugging is enabled (-Lopts=diag) and
-- there is a LUNATIC_SAVECODE_FN variable in the environment.
local os = require("os")
local fn = os.getenv("LUNATIC_SAVECODE_FN")
if (fn ~= nil) then
if (levelnum >= 0) then
fn = fn .. levelnum
end
local io = require("io")
local f = io.open(fn, "w")
if (f ~= nil) then
f:write(savecode)
f:close()
printf("Wrote Lunatic gamevar restoration code to \"%s\".", fn)
end
end
end
-- Set the size of the code and return the code to C.
slenptr[0] = #savecode
return savecode
end
end
-- change the environment of this chunk to the table G_
-- NOTE: all references to global variables from this point on
-- (also in functions created after this point) refer to G_ !
setfenv(1, G_)
-- Print keys and values of a table.
local function printkv(label, table)
print("========== Keys and values of "..label.." ("..tostring(table)..")")
for k,v in pairs(table) do
print(k .. ": " .. tostring(v))
end
print("----------")
end
--printkv('_G AFTER SETFENV', _G)
---=== Restricted access to C variables from Lunatic ===---
-- error(..., 2) is to blame the caller and get its line numbers
-- Map of 'gv' variable names to C ones.
local varnameMap = {
gametic = "g_moveThingsCount",
RETURN = "g_RETURN",
_sessionVar = "g_elSessionVar",
}
gv_access.gametic = true
gv_access.RETURN = true
gv_access._sessionVar = true
local tmpmt = {
__index = function(_, key)
if (gv_access[key] == nil) then
-- Read access allowed.
return ffiC[key]
elseif (type(gv_access[key])~="boolean") then
-- Overridden 'gv' pseudo-member...
return gv_access[key]
elseif (varnameMap[key]) then
-- Variable known under a different name on the C side.
return ffiC[varnameMap[key]]
end
error("access forbidden", 2)
end,
__newindex = function(_, key, val)
if (gv_access[key] == nil) then
-- Variables declared 'const' are handled by LuaJIT.
ffiC[key] = val
elseif (varnameMap[key]) then
ffiC[varnameMap[key]] = val
else
error("write access forbidden", 2)
end
end,
}
gv = setmtonce(gv_, tmpmt)
-- This will create 'sprite', 'wall', etc. HERE, i.e. in the environment of this chunk
defs_c.create_globals(_G)
-- REMOVE this for release
if (ffiC._DEBUG_LUNATIC ~= 0) then
local DBG_ = {}
DBG_.debug = require("debug")
DBG_.printkv = printkv
DBG_.loadstring = loadstring
DBG_.oom = function()
local s = "1"
for i=1,math.huge do
s = s..s
end
end
-- Test reading from all struct members
DBG_.testmembread = function()
for _1, sac in pairs { con_lang.StructAccessCode, con_lang.StructAccessCode2 } do
for what, labels in pairs(sac) do
if (what~="tspr") then
for _3, membaccode in pairs(labels) do
if (type(membaccode)=="table") then
membaccode = membaccode[1]
end
if (membaccode) then
local codestr = [[
do
local _bit,_math=require'bit',require'math'
local _con=require'con'
local _band,_gv=_bit.band,gv
local tmp=]]..
membaccode:gsub("^_gud%(_pli%)", "_con._get_userdef(0)"):gsub("%%s","0").." end"
local code = assert(loadstring(codestr))
code()
end
end
end
end
end
end
allowed_modules._LUNATIC_DBG = DBG_
end
---=== Finishing environment setup ===---
--printkv('_G AFTER DECLS', _G)
local index_error_mt = {
__index = function(_, key)
error("attempt to read undeclared variable '"..key.."'", 2)
end,
__metatable = true,
}
-- PiL 14.2 continued
-- We need this at the end because we were previously doing just that!
setmetatable(G_, index_error_mt)
local global_mt = {
__index = G_,
__newindex = function()
error("attempt to write into the global environment")
end,
__metatable = true,
}
-- Change the environment of the running Lua thread so that everything
-- what we've set up will be available when this chunk is left.
-- In particular, we need the globals defined after setting this chunk's
-- environment earlier.
setfenv(0, setmetatable({}, global_mt))
do
-- If we're running from a savegame restoration, create the restoration
-- function. Must be here, after the above setfenv(), because it must be
-- created in this protected ('user') context!
local cstr = ffiC.g_elSavecode
if (cstr~=nil) then
local restorecode = ffi.string(cstr)
ffiC.El_FreeSaveCode()
g_restorefunc = assert(loadstring(restorecode))
end
end
-- Restore CON gamevars from loadmapstate.
-- TODO: non-user-defined gamevars.
-- TODO: savegames.
-- int32_t El_RestoreGamevars(const char *)
ffiC.El_RestoreGamevars = function(savecode)
savecode = ffi.string(savecode)
local restorefunc = assert(loadstring(savecode))
restorefunc(CON_MODULE_NAME, package_loaded[CON_MODULE_NAME], nil)
return 0
end
-- Run the CON code translated into Lua.
if (assert(concode ~= nil)) then
local confunc, conerrmsg = loadstring(concode, "CON")
if (confunc == nil) then
error("Failure loading translated CON code: "..conerrmsg, 0)
end
-- Emulate our 'require' for the CON module when running it, for
-- our_module() which is called from the generated Lua code.
table.insert(modname_stack, CON_MODULE_NAME)
local conlabels, conaction, conmove, conai = confunc()
table.remove(modname_stack)
local function protect_con_table(tab)
-- NOTE: Some of our code specifically excepts the name tables to be
-- indexable with nonexistent keys. See e.g. control.lua: _A_SpawnGlass()
if (ffiC._LUNATIC_STRICT ~= 0) then
tab = setmetatable(tab, index_error_mt)
end
return setmtonce({}, { __index=tab, __newindex=basemod_newidx })
end
-- Set up CON.* modules, providing access to diffenrent kinds of labels
-- defined in CON from Lua. See CONCODE_RETURN in lunacon.lua.
allowed_modules["CON.DEFS"] = protect_con_table(conlabels)
allowed_modules["CON.ACTION"] = protect_con_table(conaction)
allowed_modules["CON.MOVE"] = protect_con_table(conmove)
allowed_modules["CON.AI"] = protect_con_table(conai)
-- Propagate potentially remapped defines to the control module.
con._setuplabels(conlabels)
local function getLabelValue(str, doupper)
return conlabels[doupper and string.upper(str) or str]
end
ffiC.El_GetLabelValue = function(label)
local str = ffi.string(label)
local ok, val = pcall(getLabelValue, str, false)
if (not ok or type(val)~="number") then
ok, val = pcall(getLabelValue, str, true)
end
return (ok and type(val)=="number") and val or bit.tobit(0x80000000)
end
end
-- When starting a map, load Lua modules given on the command line.
if (not g_firstRun) then
local i=0
while (ffiC.g_elModules[i] ~= nil) do
-- Get the module name and strip the trailing extension.
local modname = ffi.string(ffiC.g_elModules[i]):gsub("%.lua$","")
if (modname:find("%.")) then
-- Because they will be replaced by dirseps in our_require().
error("Dots are not permitted in module names", 0)
end
-- Allow forward slashes in module names from the cmdline.
our_require((modname:gsub("%.lua$",""):gsub("/",".")))
i = i+1
end
ffiC.g_elFirstTime = 0
end
if (g_restorefunc) then
-- Clear it so that it may be garbage-collected.
g_restorefunc = nil
end
| 412 | 0.897681 | 1 | 0.897681 | game-dev | MEDIA | 0.401368 | game-dev | 0.666946 | 1 | 0.666946 |
oot-pc-port/oot-pc-port | 2,485 | asm/non_matchings/overlays/actors/ovl_En_Horse/func_80A5DDB0.s | glabel func_80A5DDB0
/* 02AC0 80A5DDB0 27BDFFE8 */ addiu $sp, $sp, 0xFFE8 ## $sp = FFFFFFE8
/* 02AC4 80A5DDB4 AFBF0014 */ sw $ra, 0x0014($sp)
/* 02AC8 80A5DDB8 AFA5001C */ sw $a1, 0x001C($sp)
/* 02ACC 80A5DDBC 240E000A */ addiu $t6, $zero, 0x000A ## $t6 = 0000000A
/* 02AD0 80A5DDC0 240F0006 */ addiu $t7, $zero, 0x0006 ## $t7 = 00000006
/* 02AD4 80A5DDC4 00803025 */ or $a2, $a0, $zero ## $a2 = 00000000
/* 02AD8 80A5DDC8 AC8E014C */ sw $t6, 0x014C($a0) ## 0000014C
/* 02ADC 80A5DDCC AC8F0210 */ sw $t7, 0x0210($a0) ## 00000210
/* 02AE0 80A5DDD0 8CD80158 */ lw $t8, 0x0158($a2) ## 00000158
/* 02AE4 80A5DDD4 3C0880A6 */ lui $t0, %hi(D_80A65E58) ## $t0 = 80A60000
/* 02AE8 80A5DDD8 248401AC */ addiu $a0, $a0, 0x01AC ## $a0 = 000001AC
/* 02AEC 80A5DDDC 0018C880 */ sll $t9, $t8, 2
/* 02AF0 80A5DDE0 01194021 */ addu $t0, $t0, $t9
/* 02AF4 80A5DDE4 8D085E58 */ lw $t0, %lo(D_80A65E58)($t0)
/* 02AF8 80A5DDE8 8D050018 */ lw $a1, 0x0018($t0) ## 80A60018
/* 02AFC 80A5DDEC 0C02947A */ jal func_800A51E8
/* 02B00 80A5DDF0 AFA60018 */ sw $a2, 0x0018($sp)
/* 02B04 80A5DDF4 8FA60018 */ lw $a2, 0x0018($sp)
/* 02B08 80A5DDF8 3C0180A6 */ lui $at, %hi(D_80A668C0) ## $at = 80A60000
/* 02B0C 80A5DDFC C42868C0 */ lwc1 $f8, %lo(D_80A668C0)($at)
/* 02B10 80A5DE00 8CC201CC */ lw $v0, 0x01CC($a2) ## 000001CC
/* 02B14 80A5DE04 C4C6025C */ lwc1 $f6, 0x025C($a2) ## 0000025C
/* 02B18 80A5DE08 84490002 */ lh $t1, 0x0002($v0) ## 00000002
/* 02B1C 80A5DE0C ACC00244 */ sw $zero, 0x0244($a2) ## 00000244
/* 02B20 80A5DE10 44892000 */ mtc1 $t1, $f4 ## $f4 = 0.00
/* 02B24 80A5DE14 00000000 */ nop
/* 02B28 80A5DE18 46802020 */ cvt.s.w $f0, $f4
/* 02B2C 80A5DE1C 46080282 */ mul.s $f10, $f0, $f8
/* 02B30 80A5DE20 460A3400 */ add.s $f16, $f6, $f10
/* 02B34 80A5DE24 E4D0025C */ swc1 $f16, 0x025C($a2) ## 0000025C
/* 02B38 80A5DE28 8FBF0014 */ lw $ra, 0x0014($sp)
/* 02B3C 80A5DE2C 27BD0018 */ addiu $sp, $sp, 0x0018 ## $sp = 00000000
/* 02B40 80A5DE30 03E00008 */ jr $ra
/* 02B44 80A5DE34 00000000 */ nop
| 412 | 0.870901 | 1 | 0.870901 | game-dev | MEDIA | 0.92704 | game-dev | 0.73943 | 1 | 0.73943 |
GarageGames/Qt | 15,821 | qt-5/qtwebengine/src/3rdparty/chromium/third_party/WebKit/Source/core/inspector/InspectorDebuggerAgent.h | /*
* Copyright (C) 2010 Apple Inc. All rights reserved.
* Copyright (C) 2010-2011 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS 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 APPLE OR ITS 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.
*/
#ifndef InspectorDebuggerAgent_h
#define InspectorDebuggerAgent_h
#include "bindings/core/v8/ScriptState.h"
#include "core/InspectorFrontend.h"
#include "core/frame/ConsoleTypes.h"
#include "core/inspector/AsyncCallStackTracker.h"
#include "core/inspector/ConsoleAPITypes.h"
#include "core/inspector/InjectedScript.h"
#include "core/inspector/InspectorBaseAgent.h"
#include "core/inspector/PromiseTracker.h"
#include "core/inspector/ScriptBreakpoint.h"
#include "core/inspector/ScriptDebugListener.h"
#include "wtf/Forward.h"
#include "wtf/HashMap.h"
#include "wtf/PassRefPtr.h"
#include "wtf/Vector.h"
#include "wtf/text/StringHash.h"
namespace blink {
class ConsoleMessage;
class Document;
class Event;
class EventListener;
class EventTarget;
class ExecutionContextTask;
class FormData;
class HTTPHeaderMap;
class InjectedScriptManager;
class InspectorFrontend;
class JavaScriptCallFrame;
class JSONObject;
class KURL;
class MutationObserver;
class ScriptAsyncCallStack;
class ScriptDebugServer;
class ScriptRegexp;
class ScriptSourceCode;
class ScriptValue;
class ThreadableLoaderClient;
class XMLHttpRequest;
typedef String ErrorString;
class InspectorDebuggerAgent : public InspectorBaseAgent<InspectorDebuggerAgent>, public ScriptDebugListener, public InspectorBackendDispatcher::DebuggerCommandHandler {
WTF_MAKE_NONCOPYABLE(InspectorDebuggerAgent);
WTF_MAKE_FAST_ALLOCATED_WILL_BE_REMOVED;
public:
enum BreakpointSource {
UserBreakpointSource,
DebugCommandBreakpointSource,
MonitorCommandBreakpointSource
};
static const char backtraceObjectGroup[];
virtual ~InspectorDebuggerAgent();
virtual void trace(Visitor*);
virtual void canSetScriptSource(ErrorString*, bool* result) override final { *result = true; }
virtual void init() override final;
virtual void setFrontend(InspectorFrontend*) override final;
virtual void clearFrontend() override final;
virtual void restore() override final;
bool isPaused();
bool runningNestedMessageLoop();
void addMessageToConsole(ConsoleMessage*);
String preprocessEventListener(LocalFrame*, const String& source, const String& url, const String& functionName);
PassOwnPtr<ScriptSourceCode> preprocess(LocalFrame*, const ScriptSourceCode&);
// Part of the protocol.
virtual void enable(ErrorString*) override final;
virtual void disable(ErrorString*) override final;
virtual void setBreakpointsActive(ErrorString*, bool active) override final;
virtual void setSkipAllPauses(ErrorString*, bool skipped, const bool* untilReload) override final;
virtual void setBreakpointByUrl(ErrorString*, int lineNumber, const String* optionalURL, const String* optionalURLRegex, const int* optionalColumnNumber, const String* optionalCondition, const bool* isAntiBreakpoint, TypeBuilder::Debugger::BreakpointId*, RefPtr<TypeBuilder::Array<TypeBuilder::Debugger::Location> >& locations) override final;
virtual void setBreakpoint(ErrorString*, const RefPtr<JSONObject>& location, const String* optionalCondition, TypeBuilder::Debugger::BreakpointId*, RefPtr<TypeBuilder::Debugger::Location>& actualLocation) override final;
virtual void removeBreakpoint(ErrorString*, const String& breakpointId) override final;
virtual void continueToLocation(ErrorString*, const RefPtr<JSONObject>& location, const bool* interstateLocationOpt) override final;
virtual void getStepInPositions(ErrorString*, const String& callFrameId, RefPtr<TypeBuilder::Array<TypeBuilder::Debugger::Location> >& positions) override final;
virtual void getBacktrace(ErrorString*, RefPtr<TypeBuilder::Array<TypeBuilder::Debugger::CallFrame> >&, RefPtr<TypeBuilder::Debugger::StackTrace>&) override final;
virtual void searchInContent(ErrorString*, const String& scriptId, const String& query, const bool* optionalCaseSensitive, const bool* optionalIsRegex, RefPtr<TypeBuilder::Array<TypeBuilder::Page::SearchMatch> >&) override final;
virtual void setScriptSource(ErrorString*, RefPtr<TypeBuilder::Debugger::SetScriptSourceError>&, const String& scriptId, const String& newContent, const bool* preview, RefPtr<TypeBuilder::Array<TypeBuilder::Debugger::CallFrame> >& newCallFrames, RefPtr<JSONObject>& result, RefPtr<TypeBuilder::Debugger::StackTrace>& asyncStackTrace) override final;
virtual void restartFrame(ErrorString*, const String& callFrameId, RefPtr<TypeBuilder::Array<TypeBuilder::Debugger::CallFrame> >& newCallFrames, RefPtr<JSONObject>& result, RefPtr<TypeBuilder::Debugger::StackTrace>& asyncStackTrace) override final;
virtual void getScriptSource(ErrorString*, const String& scriptId, String* scriptSource) override final;
virtual void getFunctionDetails(ErrorString*, const String& functionId, RefPtr<TypeBuilder::Debugger::FunctionDetails>&) override final;
virtual void getCollectionEntries(ErrorString*, const String& objectId, RefPtr<TypeBuilder::Array<TypeBuilder::Debugger::CollectionEntry> >&) override final;
virtual void pause(ErrorString*) override final;
virtual void resume(ErrorString*) override final;
virtual void stepOver(ErrorString*) override final;
virtual void stepInto(ErrorString*) override final;
virtual void stepOut(ErrorString*) override final;
virtual void setPauseOnExceptions(ErrorString*, const String& pauseState) override final;
virtual void evaluateOnCallFrame(ErrorString*,
const String& callFrameId,
const String& expression,
const String* objectGroup,
const bool* includeCommandLineAPI,
const bool* doNotPauseOnExceptionsAndMuteConsole,
const bool* returnByValue,
const bool* generatePreview,
RefPtr<TypeBuilder::Runtime::RemoteObject>& result,
TypeBuilder::OptOutput<bool>* wasThrown,
RefPtr<TypeBuilder::Debugger::ExceptionDetails>&) override final;
virtual void compileScript(ErrorString*, const String& expression, const String& sourceURL, const int* executionContextId, TypeBuilder::OptOutput<TypeBuilder::Debugger::ScriptId>*, RefPtr<TypeBuilder::Debugger::ExceptionDetails>&) override;
virtual void runScript(ErrorString*, const TypeBuilder::Debugger::ScriptId&, const int* executionContextId, const String* objectGroup, const bool* doNotPauseOnExceptionsAndMuteConsole, RefPtr<TypeBuilder::Runtime::RemoteObject>& result, RefPtr<TypeBuilder::Debugger::ExceptionDetails>&) override;
virtual void setOverlayMessage(ErrorString*, const String*) override;
virtual void setVariableValue(ErrorString*, int in_scopeNumber, const String& in_variableName, const RefPtr<JSONObject>& in_newValue, const String* in_callFrame, const String* in_functionObjectId) override final;
virtual void skipStackFrames(ErrorString*, const String* pattern, const bool* skipContentScripts) override final;
virtual void setAsyncCallStackDepth(ErrorString*, int depth) override final;
virtual void enablePromiseTracker(ErrorString*) override final;
virtual void disablePromiseTracker(ErrorString*) override final;
virtual void getPromises(ErrorString*, RefPtr<TypeBuilder::Array<TypeBuilder::Debugger::PromiseDetails> >& promises) override final;
virtual void getPromiseById(ErrorString*, int promiseId, const String* objectGroup, RefPtr<TypeBuilder::Runtime::RemoteObject>& promise) override final;
void schedulePauseOnNextStatement(InspectorFrontend::Debugger::Reason::Enum breakReason, PassRefPtr<JSONObject> data);
void didInstallTimer(ExecutionContext*, int timerId, int timeout, bool singleShot);
void didRemoveTimer(ExecutionContext*, int timerId);
bool willFireTimer(ExecutionContext*, int timerId);
void didFireTimer();
void didRequestAnimationFrame(Document*, int callbackId);
void didCancelAnimationFrame(Document*, int callbackId);
bool willFireAnimationFrame(Document*, int callbackId);
void didFireAnimationFrame();
void didEnqueueEvent(EventTarget*, Event*);
void didRemoveEvent(EventTarget*, Event*);
void willHandleEvent(EventTarget*, Event*, EventListener*, bool useCapture);
void didHandleEvent();
void willLoadXHR(XMLHttpRequest*, ThreadableLoaderClient*, const AtomicString& method, const KURL&, bool async, PassRefPtr<FormData> body, const HTTPHeaderMap& headers, bool includeCrendentials);
void didDispatchXHRLoadendEvent(XMLHttpRequest*);
void didEnqueueMutationRecord(ExecutionContext*, MutationObserver*);
void didClearAllMutationRecords(ExecutionContext*, MutationObserver*);
void willDeliverMutationRecords(ExecutionContext*, MutationObserver*);
void didDeliverMutationRecords();
void didPostExecutionContextTask(ExecutionContext*, ExecutionContextTask*);
void didKillAllExecutionContextTasks(ExecutionContext*);
void willPerformExecutionContextTask(ExecutionContext*, ExecutionContextTask*);
void didPerformExecutionContextTask();
int traceAsyncOperationStarting(ExecutionContext*, const String& operationName, int prevOperationId = 0);
void traceAsyncOperationCompleted(ExecutionContext*, int operationId);
void traceAsyncOperationCompletedCallbackStarting(ExecutionContext*, int operationId);
void traceAsyncCallbackStarting(ExecutionContext*, int operationId);
void traceAsyncCallbackCompleted();
bool canBreakProgram();
void breakProgram(InspectorFrontend::Debugger::Reason::Enum breakReason, PassRefPtr<JSONObject> data);
void scriptExecutionBlockedByCSP(const String& directiveText);
class Listener : public WillBeGarbageCollectedMixin {
public:
virtual ~Listener() { }
virtual void debuggerWasEnabled() = 0;
virtual void debuggerWasDisabled() = 0;
virtual void stepInto() = 0;
virtual void didPause() = 0;
virtual bool canPauseOnPromiseEvent() = 0;
virtual void didCreatePromise() = 0;
virtual void didResolvePromise() = 0;
virtual void didRejectPromise() = 0;
};
void setListener(Listener* listener) { m_listener = listener; }
bool enabled();
virtual ScriptDebugServer& scriptDebugServer() = 0;
void setBreakpoint(const String& scriptId, int lineNumber, int columnNumber, BreakpointSource, const String& condition = String());
void removeBreakpoint(const String& scriptId, int lineNumber, int columnNumber, BreakpointSource);
PassRefPtrWillBeRawPtr<ScriptAsyncCallStack> currentAsyncStackTraceForConsole();
protected:
explicit InspectorDebuggerAgent(InjectedScriptManager*);
virtual void startListeningScriptDebugServer() = 0;
virtual void stopListeningScriptDebugServer() = 0;
virtual void muteConsole() = 0;
virtual void unmuteConsole() = 0;
InjectedScriptManager* injectedScriptManager() { return m_injectedScriptManager; }
virtual InjectedScript injectedScriptForEval(ErrorString*, const int* executionContextId) = 0;
virtual void enable();
virtual void disable();
virtual SkipPauseRequest didPause(ScriptState*, const ScriptValue& callFrames, const ScriptValue& exception, const Vector<String>& hitBreakpoints, bool isPromiseRejection) override final;
virtual void didContinue() override final;
void reset();
void pageDidCommitLoad();
private:
SkipPauseRequest shouldSkipExceptionPause();
SkipPauseRequest shouldSkipStepPause();
bool isTopCallFrameInFramework();
void cancelPauseOnNextStatement();
void addMessageToConsole(MessageSource, MessageType);
PassRefPtr<TypeBuilder::Array<TypeBuilder::Debugger::CallFrame> > currentCallFrames();
PassRefPtr<TypeBuilder::Debugger::StackTrace> currentAsyncStackTrace();
virtual void didParseSource(const String& scriptId, const Script&, CompileResult) override final;
virtual bool v8AsyncTaskEventsEnabled() const override final;
virtual void didReceiveV8AsyncTaskEvent(ExecutionContext*, const String& eventType, const String& eventName, int id) override final;
virtual bool v8PromiseEventsEnabled() const override final;
virtual void didReceiveV8PromiseEvent(ScriptState*, v8::Handle<v8::Object> promise, v8::Handle<v8::Value> parentPromise, int status) override final;
void setPauseOnExceptionsImpl(ErrorString*, int);
PassRefPtr<TypeBuilder::Debugger::Location> resolveBreakpoint(const String& breakpointId, const String& scriptId, const ScriptBreakpoint&, BreakpointSource);
void removeBreakpoint(const String& breakpointId);
void clear();
bool assertPaused(ErrorString*);
void clearBreakDetails();
String sourceMapURLForScript(const Script&, CompileResult);
PassRefPtrWillBeRawPtr<JavaScriptCallFrame> topCallFrameSkipUnknownSources(String* scriptURL, bool* isBlackboxed);
AsyncCallStackTracker& asyncCallStackTracker() const { return *m_asyncCallStackTracker; };
PromiseTracker& promiseTracker() const { return *m_promiseTracker; }
typedef HashMap<String, Script> ScriptsMap;
typedef HashMap<String, Vector<String> > BreakpointIdToDebugServerBreakpointIdsMap;
typedef HashMap<String, std::pair<String, BreakpointSource> > DebugServerBreakpointToBreakpointIdAndSourceMap;
RawPtrWillBeMember<InjectedScriptManager> m_injectedScriptManager;
InspectorFrontend::Debugger* m_frontend;
RefPtr<ScriptState> m_pausedScriptState;
ScriptValue m_currentCallStack;
ScriptsMap m_scripts;
BreakpointIdToDebugServerBreakpointIdsMap m_breakpointIdToDebugServerBreakpointIds;
DebugServerBreakpointToBreakpointIdAndSourceMap m_serverBreakpoints;
String m_continueToLocationBreakpointId;
InspectorFrontend::Debugger::Reason::Enum m_breakReason;
RefPtr<JSONObject> m_breakAuxData;
bool m_javaScriptPauseScheduled;
bool m_debuggerStepScheduled;
bool m_steppingFromFramework;
bool m_pausingOnNativeEvent;
RawPtrWillBeMember<Listener> m_listener;
int m_skippedStepInCount;
int m_minFrameCountForSkip;
bool m_skipAllPauses;
bool m_skipContentScripts;
OwnPtr<ScriptRegexp> m_cachedSkipStackRegExp;
OwnPtrWillBeMember<AsyncCallStackTracker> m_asyncCallStackTracker;
OwnPtrWillBeMember<PromiseTracker> m_promiseTracker;
};
} // namespace blink
#endif // !defined(InspectorDebuggerAgent_h)
| 412 | 0.825756 | 1 | 0.825756 | game-dev | MEDIA | 0.42989 | game-dev | 0.740096 | 1 | 0.740096 |
Unity-Technologies/ProjectTinySamples | 3,829 | BlendShapeDemo/Assets/Scripts/Systems/BlendShapeSystem.cs | using Unity.Entities;
using Unity.Collections;
using Unity.Transforms;
using Unity.Tiny;
using Unity.Tiny.Input;
using Unity.Tiny.Rendering;
namespace BlendShapeDemo
{
/// <summary>
/// Translate the cursor pressed according to the mouse position in the X axis
/// Remap the value of the sliders to fit with the BlendShape weight
/// Modify the character mesh according to the sliders
/// </summary>
public class BlendShapeSystem : SystemBase
{
private InputSystem inputsystem;
protected override void OnCreate()
{
inputsystem = World.GetExistingSystem<InputSystem>();
}
protected override void OnUpdate()
{
var game = GetSingleton<Game>();
var input = World.GetExistingSystem<InputSystem>();
var inputPos = inputsystem.GetInputPosition();
var mousePos = ScreenToWorldSystem.ScreenPointToWorldPoint(World, inputPos.x);
if (game.gameState == GameState.Billy || game.gameState == GameState.Emily)
{
Entities.ForEach((ref Entity entity, ref Cursor cursor, ref Tappable tappable, ref Translation translation) =>
{
if (tappable.IsPressed)
{
// Check if the current cursor is between the right range
if (translation.Value.x >= cursor.minRange && translation.Value.x <= cursor.maxRange)
{
translation.Value.x = mousePos.x;
SetBlendShape(cursor.blendShapeOrder.ToString(), RemapSlider(cursor.minRange, cursor.maxRange, 0, 100, translation.Value.x));
}
// Clamp min slider
if(translation.Value.x <= cursor.minRange)
translation.Value.x = cursor.minRange;
// Clamp max slider
if (translation.Value.x >= cursor.maxRange)
translation.Value.x = cursor.maxRange;
}
}).WithStructuralChanges().Run();
}
}
// Remap slider value to fit with the BlendShape weight (0, 100)
public float RemapSlider(float rawMin, float rawMax, float newMin, float newMax, float rawValue)
{
float rawRange = (rawMax - rawMin);
float newRange = (newMax - newMin);
float newCurrentValue = (((rawValue - rawMin) * newRange) / rawRange) + newMin;
return newCurrentValue;
}
// Select the BlendShape we want and modify his weight according to the slider value
public void SetBlendShape(string blendShapeName, float blendShapeWeight)
{
#if UNITY_DOTSRUNTIME
EntityCommandBuffer ecb = new EntityCommandBuffer(Allocator.Temp);
Entities.ForEach((Entity entity, DynamicBuffer<BlendShapeWeight> smrBlendShapeWeightBuffer, ref SkinnedMeshRenderer smr, ref Character character) =>
{
SetBlendShapeWeight setWeight = new SetBlendShapeWeight();
setWeight.NameHash = BlendShapeChannel.GetNameHash(blendShapeName);
setWeight.ModifiedWeight = blendShapeWeight;
DynamicBuffer<SetBlendShapeWeight> setWeightsBuffer = ecb.AddBuffer<SetBlendShapeWeight>(entity);
setWeightsBuffer.Add(setWeight);
}).WithoutBurst().Run();
ecb.Playback(EntityManager);
ecb.Dispose();
#endif
}
}
}
| 412 | 0.933069 | 1 | 0.933069 | game-dev | MEDIA | 0.957615 | game-dev | 0.975309 | 1 | 0.975309 |
ggnkua/Atari_ST_Sources | 1,363 | C/Christian Grunenberg/EGEM_220/EXAMPLE/DIALDEMO/DIAMOUSE.C |
/* DialogMouse (PRG): Demonstriert von der Mausposition abhngige Mausform/Infozeile */
#include <e_gem.h>
#include <string.h>
#include "diamouse.h"
DIAINFO *di;
OBJECT *tr;
char *dm="DiaMouse",
path[][MAX_PATH]={"\\ST-GUIDE.AC?","\\DOCUMENTS\\","\\SETTINGS\\","\\MODULES\\"},
*info[]={"","Hilfesystem","Pfad fr Dokumente...","Pfad fr Einstellungen...","Pfad fr Module...","Abbruch","","Besttigen",""};
int ObInfo(DIAINFO *di,OBJECT *t,int ob,int l,int x,int y,GRECT *r)
{
window_info(di->di_win,info[ob]);
if (ob>=PATH1 && ob<=PATH4)
{
MouseCursor();
return(DIALOG_MOUSE);
}
return(DIALOG_OBJECT);
}
void main()
{
if (open_rsc("diamouse.rsc",NULL,dm,dm,"DIAMOUSE",0,0,0)==TRUE)
{
rsrc_gaddr(R_TREE,0,&tr);
fix_objects(tr,NO_SCALING,8,16);
if ((di=open_dialog(tr,dm,NULL,NULL,DIA_MOUSEPOS,FALSE,WIN_DIAL|WD_INFO,0,NULL,NULL))!=NULL)
{
char file[MAX_PATH],buf[MAX_PATH],*pa,ex;
for (ex=0;ex<4;ex++)
ob_set_text(tr,ex+PATH1,path[ex]);
dialog_mouse(di,ObInfo);
while ((ex=XFormObject(NULL,NULL))>=PATH1 && ex<=PATH4)
{
strcpy(file,GetFilename(strcpy(buf,pa=path[ex-PATH1])));
GetPath(buf);
if (FileSelect(info[ex],buf,file,NULL,FALSE,0,NULL)>0)
{
MakeFullpath(pa,buf,ex==PATH1 ? file : "");
ob_draw(di,ex);
}
ob_select(di,tr,ex,FALSE,TRUE);
}
}
close_rsc(TRUE,0);
}
exit(-1);
}
| 412 | 0.870591 | 1 | 0.870591 | game-dev | MEDIA | 0.256593 | game-dev | 0.963963 | 1 | 0.963963 |
space-wizards/space-station-14 | 1,294 | Content.Server/Doors/WireActions/DoorBoltLightWireAction.cs | using Content.Server.Doors.Systems;
using Content.Server.Wires;
using Content.Shared.Doors;
using Content.Shared.Doors.Components;
using Content.Shared.Wires;
namespace Content.Server.Doors;
public sealed partial class DoorBoltLightWireAction : ComponentWireAction<DoorBoltComponent>
{
public override Color Color { get; set; } = Color.Lime;
public override string Name { get; set; } = "wire-name-bolt-light";
public override StatusLightState? GetLightState(Wire wire, DoorBoltComponent comp)
=> comp.BoltLightsEnabled ? StatusLightState.On : StatusLightState.Off;
public override object StatusKey { get; } = AirlockWireStatus.BoltLightIndicator;
public override bool Cut(EntityUid user, Wire wire, DoorBoltComponent door)
{
EntityManager.System<DoorSystem>().SetBoltLightsEnabled((wire.Owner, door), false);
return true;
}
public override bool Mend(EntityUid user, Wire wire, DoorBoltComponent door)
{
EntityManager.System<DoorSystem>().SetBoltLightsEnabled((wire.Owner, door), true);
return true;
}
public override void Pulse(EntityUid user, Wire wire, DoorBoltComponent door)
{
EntityManager.System<DoorSystem>().SetBoltLightsEnabled((wire.Owner, door), !door.BoltLightsEnabled);
}
}
| 412 | 0.696283 | 1 | 0.696283 | game-dev | MEDIA | 0.302382 | game-dev | 0.74286 | 1 | 0.74286 |
SilentChaos512/Silent-Gear | 1,181 | src/main/java/net/silentchaos512/gear/item/BlueprintPackageItem.java | package net.silentchaos512.gear.item;
import net.minecraft.ChatFormatting;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.TooltipFlag;
import net.minecraft.world.level.storage.loot.LootTable;
import net.silentchaos512.lib.item.LootContainerItem;
import java.util.List;
public class BlueprintPackageItem extends LootContainerItem {
public BlueprintPackageItem(ResourceLocation defaultLootTable) {
super(defaultLootTable, new Properties());
}
public ResourceKey<LootTable> getDefaultLootTable() {
return getLootTable(getStack());
}
@Override
public void appendHoverText(ItemStack stack, TooltipContext context, List<Component> tooltip, TooltipFlag flagIn) {
tooltip.add(Component.translatable("item.silentgear.blueprint_package.desc1").withStyle(ChatFormatting.ITALIC));
tooltip.add(Component.translatable("item.silentgear.blueprint_package.desc2").withStyle(ChatFormatting.ITALIC));
super.appendHoverText(stack, context, tooltip, flagIn);
}
}
| 412 | 0.760267 | 1 | 0.760267 | game-dev | MEDIA | 0.997777 | game-dev | 0.919762 | 1 | 0.919762 |
Destuur/ModForge | 1,680 | ModForge.Test/Program.cs | using ModForge.Shared;
using ModForge.Shared.Factories;
using ModForge.Shared.Models.Data;
using ModForge.Shared.Models.STORM;
using ModForge.Shared.Services;
using System.IO.Compression;
using System.Reflection.PortableExecutable;
using System.Text;
using System.Xml.Linq;
using System.Xml.Serialization;
namespace ModForge.Test
{
class Program
{
static void Main(string[] args)
{
//var pakPath = @"G:\SteamLibrary\steamapps\common\KingdomComeDeliverance2\Data\IPL_GameData.pak";
//var storm = ReadStormFile(pakPath, "storm.xml");
//List<Storm> stormFiles = new();
//foreach (var task in storm.Tasks)
//{
// // Ich gehe davon aus, dass du in Task eine Sources-Liste hast (sonst anpassen)
// foreach (var source in task.Sources)
// {
// stormFiles.Add(ReadStormFile(pakPath, source.Path));
// }
//}
//var selectors = SelectorParser.SelectorAttributes;
//var operations = OperationParser.OperationAttributes;
}
//private static Storm ReadStormFile(string pakPath, string stormFile)
//{
// using FileStream zipToOpen = new(pakPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
// using ZipArchive archive = new(zipToOpen, ZipArchiveMode.Read);
// var normalizedStormFile = stormFile.Replace('\\', '/');
// foreach (var entry in archive.Entries)
// {
// if (!entry.FullName.Contains(normalizedStormFile))
// continue;
// using var stream = entry.Open();
// string xml = new StreamReader(entry.Open()).ReadToEnd();
// var parser = new StormParser();
// var storm = parser.Parse(xml);
// return storm;
// }
// return null; // Datei nicht gefunden
//}
}
} | 412 | 0.841256 | 1 | 0.841256 | game-dev | MEDIA | 0.68804 | game-dev | 0.866835 | 1 | 0.866835 |
antlr/antlr4 | 3,630 | runtime/Swift/Sources/Antlr4/atn/LexerAction.swift | ///
/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
/// Use of this file is governed by the BSD 3-clause license that
/// can be found in the LICENSE.txt file in the project root.
///
///
/// Represents a single action which can be executed following the successful
/// match of a lexer rule. Lexer actions are used for both embedded action syntax
/// and ANTLR 4's new lexer command syntax.
///
/// - Sam Harwell
/// - 4.2
///
public class LexerAction: Hashable {
///
/// Gets the serialization type of the lexer action.
///
/// - returns: The serialization type of the lexer action.
///
public func getActionType() -> LexerActionType {
fatalError(#function + " must be overridden")
}
///
/// Gets whether the lexer action is position-dependent. Position-dependent
/// actions may have different semantics depending on the _org.antlr.v4.runtime.CharStream_
/// index at the time the action is executed.
///
/// Many lexer commands, including `type`, `skip`, and
/// `more`, do not check the input index during their execution.
/// Actions like this are position-independent, and may be stored more
/// efficiently as part of the _org.antlr.v4.runtime.atn.LexerATNConfig#lexerActionExecutor_.
///
/// - returns: `true` if the lexer action semantics can be affected by the
/// position of the input _org.antlr.v4.runtime.CharStream_ at the time it is executed;
/// otherwise, `false`.
///
public func isPositionDependent() -> Bool {
fatalError(#function + " must be overridden")
}
///
/// Execute the lexer action in the context of the specified _org.antlr.v4.runtime.Lexer_.
///
/// For position-dependent actions, the input stream must already be
/// positioned correctly prior to calling this method.
///
/// - parameter lexer: The lexer instance.
///
public func execute(_ lexer: Lexer) throws {
fatalError(#function + " must be overridden")
}
public func hash(into hasher: inout Hasher) {
fatalError(#function + " must be overridden")
}
}
public func ==(lhs: LexerAction, rhs: LexerAction) -> Bool {
if lhs === rhs {
return true
}
if (lhs is LexerChannelAction) && (rhs is LexerChannelAction) {
return (lhs as! LexerChannelAction) == (rhs as! LexerChannelAction)
} else if (lhs is LexerCustomAction) && (rhs is LexerCustomAction) {
return (lhs as! LexerCustomAction) == (rhs as! LexerCustomAction)
} else if (lhs is LexerIndexedCustomAction) && (rhs is LexerIndexedCustomAction) {
return (lhs as! LexerIndexedCustomAction) == (rhs as! LexerIndexedCustomAction)
} else if (lhs is LexerModeAction) && (rhs is LexerModeAction) {
return (lhs as! LexerModeAction) == (rhs as! LexerModeAction)
} else if (lhs is LexerMoreAction) && (rhs is LexerMoreAction) {
return (lhs as! LexerMoreAction) == (rhs as! LexerMoreAction)
} else if (lhs is LexerPopModeAction) && (rhs is LexerPopModeAction) {
return (lhs as! LexerPopModeAction) == (rhs as! LexerPopModeAction)
} else if (lhs is LexerPushModeAction) && (rhs is LexerPushModeAction) {
return (lhs as! LexerPushModeAction) == (rhs as! LexerPushModeAction)
} else if (lhs is LexerSkipAction) && (rhs is LexerSkipAction) {
return (lhs as! LexerSkipAction) == (rhs as! LexerSkipAction)
} else if (lhs is LexerTypeAction) && (rhs is LexerTypeAction) {
return (lhs as! LexerTypeAction) == (rhs as! LexerTypeAction)
}
return false
}
| 412 | 0.732804 | 1 | 0.732804 | game-dev | MEDIA | 0.475519 | game-dev | 0.934041 | 1 | 0.934041 |
PolarisSS13/Polaris | 5,964 | code/modules/power/antimatter/shielding.dm | //like orange but only checks north/south/east/west for one step
/proc/cardinalrange(var/center)
var/list/things = list()
for(var/direction in cardinal)
var/turf/T = get_step(center, direction)
if(!T) continue
things += T.contents
return things
/obj/machinery/am_shielding
name = "antimatter reactor section"
desc = "This device was built using a phoron life-form that seems to increase phoron's natural ability to react with neutrinos while reducing the combustibility."
icon = 'icons/obj/machines/antimatter.dmi'
icon_state = "shield"
anchored = 1
density = 1
dir = 1
use_power = USE_POWER_OFF //Living things generally dont use power
idle_power_usage = 0
active_power_usage = 0
var/obj/machinery/power/am_control_unit/control_unit = null
var/processing = 0//To track if we are in the update list or not, we need to be when we are damaged and if we ever
var/stability = 100//If this gets low bad things tend to happen
var/efficiency = 1//How many cores this core counts for when doing power processing, phoron in the air and stability could affect this
/obj/machinery/am_shielding/Initialize()
. = ..()
addtimer(CALLBACK(src, .proc/controllerscan), 1 SECOND)
/obj/machinery/am_shielding/proc/controllerscan(var/priorscan = 0)
//Make sure we are the only one here
if(!istype(src.loc, /turf))
qdel(src)
return
for(var/obj/machinery/am_shielding/AMS in loc.contents)
if(AMS == src) continue
spawn(0)
qdel(src)
return
//Search for shielding first
for(var/obj/machinery/am_shielding/AMS in cardinalrange(src))
if(AMS && AMS.control_unit && link_control(AMS.control_unit))
break
if(!control_unit)//No other guys nearby look for a control unit
for(var/direction in cardinal)
for(var/obj/machinery/power/am_control_unit/AMC in cardinalrange(src))
if(AMC.add_shielding(src))
break
if(!control_unit)
if(!priorscan)
spawn(20)
controllerscan(1)//Last chance
return
spawn(0)
qdel(src)
return
/obj/machinery/am_shielding/Destroy()
if(control_unit) control_unit.remove_shielding(src)
if(processing) shutdown_core()
visible_message("<font color='red'>The [src.name] melts!</font>")
//Might want to have it leave a mess on the floor but no sprites for now
..()
return
/obj/machinery/am_shielding/CanPass(atom/movable/mover, turf/target)
return FALSE
/obj/machinery/am_shielding/process()
if(!processing) . = PROCESS_KILL
//TODO: core functions and stability
//TODO: think about checking the airmix for phoron and increasing power output
return
/obj/machinery/am_shielding/emp_act()//Immune due to not really much in the way of electronics.
return 0
/obj/machinery/am_shielding/ex_act(severity)
switch(severity)
if(1.0)
stability -= 80
if(2.0)
stability -= 40
if(3.0)
stability -= 20
check_stability()
return
/obj/machinery/am_shielding/bullet_act(var/obj/item/projectile/Proj)
if(Proj.check_armour != "bullet")
stability -= Proj.force/2
return 0
/obj/machinery/am_shielding/update_icon()
cut_overlays()
for(var/direction in alldirs)
var/machine = locate(/obj/machinery, get_step(loc, direction))
if((istype(machine, /obj/machinery/am_shielding) && machine:control_unit == control_unit)||(istype(machine, /obj/machinery/power/am_control_unit) && machine == control_unit))
add_overlay("shield_[direction]")
if(core_check())
add_overlay("core")
if(!processing) setup_core()
else if(processing) shutdown_core()
/obj/machinery/am_shielding/attackby(obj/item/W, mob/user)
if(!istype(W) || !user) return
if(W.force > 10)
stability -= W.force/2
check_stability()
..()
return
//Call this to link a detected shilding unit to the controller
/obj/machinery/am_shielding/proc/link_control(var/obj/machinery/power/am_control_unit/AMC)
if(!istype(AMC)) return 0
if(control_unit && control_unit != AMC) return 0//Already have one
control_unit = AMC
control_unit.add_shielding(src,1)
return 1
//Scans cards for shields or the control unit and if all there it
/obj/machinery/am_shielding/proc/core_check()
for(var/direction in alldirs)
var/machine = locate(/obj/machinery, get_step(loc, direction))
if(!machine) return 0//Need all for a core
if(!istype(machine, /obj/machinery/am_shielding) && !istype(machine, /obj/machinery/power/am_control_unit)) return 0
return 1
/obj/machinery/am_shielding/proc/setup_core()
processing = 1
START_MACHINE_PROCESSING(src)
if(!control_unit) return
control_unit.linked_cores.Add(src)
control_unit.reported_core_efficiency += efficiency
return
/obj/machinery/am_shielding/proc/shutdown_core()
processing = 0
if(!control_unit) return
control_unit.linked_cores.Remove(src)
control_unit.reported_core_efficiency -= efficiency
return
/obj/machinery/am_shielding/proc/check_stability(var/injecting_fuel = 0)
if(stability > 0) return
if(injecting_fuel && control_unit)
control_unit.exploding = 1
if(src)
qdel(src)
return
/obj/machinery/am_shielding/proc/recalc_efficiency(var/new_efficiency)//tbh still not 100% sure how I want to deal with efficiency so this is likely temp
if(!control_unit || !processing) return
if(stability < 50)
new_efficiency /= 2
control_unit.reported_core_efficiency += (new_efficiency - efficiency)
efficiency = new_efficiency
return
/obj/item/am_shielding_container
name = "packaged antimatter reactor section"
desc = "A small storage unit containing an antimatter reactor section. To use place near an antimatter control unit or deployed antimatter reactor section and use a multitool to activate this package."
icon = 'icons/obj/machines/antimatter.dmi'
icon_state = "box"
item_state = "electronic"
w_class = ITEMSIZE_LARGE
throwforce = 5
throw_speed = 1
throw_range = 2
matter = list(MAT_STEEL = 100)
/obj/item/am_shielding_container/attackby(var/obj/item/I, var/mob/user)
if(istype(I, /obj/item/multitool) && istype(src.loc,/turf))
new/obj/machinery/am_shielding(src.loc)
qdel(src)
return
..()
return | 412 | 0.941971 | 1 | 0.941971 | game-dev | MEDIA | 0.218985 | game-dev | 0.888944 | 1 | 0.888944 |
Sin365/AxibugEmuOnline | 5,429 | AxibugEmuOnline.Client.PSVita/Assets/Script/AppMain/UI/MainMenuController.cs | using DG.Tweening;
using DG.Tweening.Core;
using DG.Tweening.Plugins.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;
namespace AxibugEmuOnline.Client.UI
{
public class MainMenuController : MenuItemController<MenuData>
{
[SerializeField]
HorizontalLayoutGroup GroupRoot;
[SerializeField]
MenuItem Template;
[SerializeField]
List<MenuData> MenuSetting;
[SerializeField]
float HoriRollSpd = 1f;
[SerializeField]
int InitSelect = -1;
private RectTransform groupRootRect => m_menuItemRoot as RectTransform;
private TweenerCore<Vector2, Vector2, VectorOptions> rollTween;
private List<CanvasGroup> m_runtimeMenuUICanvas;
private Sequence seq;
protected override void Start()
{
base.Start();
m_runtimeMenuUICanvas = m_runtimeMenuUI.Select(menu => menu.gameObject.AddComponent<CanvasGroup>()).ToList();
m_runtimeMenuUICanvas.ForEach(canv => canv.gameObject.AddComponent<AutoRaycastCanvasGroup>());
if (InitSelect != -1)
{
m_selectIndex = InitSelect;
PlaySelectItemAnim(false);
}
}
public override void Init(List<MenuData> menuDataList) { }
public void EnterDetailState()
{
if (seq != null)
{
seq.Kill();
seq = null;
}
var selectItem = m_runtimeMenuUICanvas[SelectIndex];
var hideItem = m_runtimeMenuUICanvas.Where(i => i != selectItem).ToList();
seq = DOTween.Sequence();
seq.Append(
DOTween.To(() => selectItem.alpha, (x) => selectItem.alpha = x, 1, 0.2f)
)
.Join(
DOTween.To(() => hideItem[0].alpha, (x) => hideItem.ForEach(i => i.alpha = x), 0, 0.2f)
);
seq.Play();
}
public void ExitDetailState()
{
if (seq != null)
{
seq.Kill();
seq = null;
}
var selectItem = m_runtimeMenuUICanvas[SelectIndex];
var hideItem = m_runtimeMenuUICanvas.Where(i => i != selectItem).ToList();
seq = DOTween.Sequence();
seq.Append(
DOTween.To(() => selectItem.alpha, (x) => selectItem.alpha = x, 1, 0.2f)
)
.Join(
DOTween.To(() => hideItem[0].alpha, (x) => hideItem.ForEach(i => i.alpha = x), 1, 0.2f)
);
seq.Play();
}
protected override void OnSelectMenuChanged()
{
PlaySelectItemAnim(true);
}
private void PlaySelectItemAnim(bool useAnim)
{
var step = GroupRoot.spacing;
var needSelectItem = m_runtimeMenuUI[SelectIndex];
var offset = needSelectItem.Rect.anchoredPosition.x;
var targetPosition = groupRootRect.anchoredPosition;
targetPosition.x = -offset;
if (rollTween != null) { rollTween.Kill(); rollTween = null; }
for (var i = 0; i < m_runtimeMenuUI.Count; i++)
{
var item = m_runtimeMenuUI[i];
item.SetSelectState(i == SelectIndex);
}
if (useAnim)
{
rollTween = DOTween.To(
() => groupRootRect.anchoredPosition,
(x) => groupRootRect.anchoredPosition = x,
targetPosition,
HoriRollSpd)
.SetSpeedBased();
}
else
{
groupRootRect.anchoredPosition = targetPosition;
}
}
protected override void OnCmdSelectItemLeft()
{
SelectIndex--;
}
protected override void OnCmdSelectItemRight()
{
SelectIndex++;
}
#if UNITY_EDITOR
[ContextMenu("UpdateMenuUI")]
public void UpdateMenuUI()
{
while (GroupRoot.transform.childCount > 0)
{
DestroyImmediate(GroupRoot.transform.GetChild(GroupRoot.transform.childCount - 1).gameObject);
}
for (int i = 0; i < MenuSetting.Count; i++)
{
var settingData = MenuSetting[i];
var templatePrefab = settingData.OverrideTemplate != null ? settingData.OverrideTemplate.gameObject : Template.gameObject;
MenuItem itemScript = null;
var prefabClone = UnityEditor.PrefabUtility.InstantiatePrefab(templatePrefab) as GameObject;
itemScript = prefabClone.GetComponent<MenuItem>();
itemScript.gameObject.SetActive(true);
itemScript.transform.SetParent(GroupRoot.transform);
itemScript.SetData(settingData);
itemScript.transform.localScale = Vector3.one;
}
UnityEditor.EditorUtility.SetDirty(this);
}
#endif
}
[Serializable]
public class MenuData
{
public Sprite Icon;
public string Name;
public string SubTitle;
public string Description;
public MenuItem OverrideTemplate;
public List<MenuData> SubMenus;
}
}
| 412 | 0.886812 | 1 | 0.886812 | game-dev | MEDIA | 0.912505 | game-dev | 0.985278 | 1 | 0.985278 |
libMesh/libmesh | 4,926 | contrib/exodusii/v8.11/exodus/src/ex_get_partial_num_map.c | /*
* Copyright(C) 1999-2020 National Technology & Engineering Solutions
* of Sandia, LLC (NTESS). Under the terms of Contract DE-NA0003525 with
* NTESS, the U.S. Government retains certain rights in this software.
*
* See packages/seacas/LICENSE for details
*/
/*****************************************************************************
*
* exgpem - ex_get_partial_elem_map
*
* entry conditions -
* input parameters:
* int exoid exodus file id
* int map_id element map id
* int ent_start first entry in map
* int ent_count number of entries in map
*
* exit conditions -
* int* elem_map element map
*
* revision history -
*
*
*****************************************************************************/
#include "exodusII.h" // for ex_err, etc
#include "exodusII_int.h" // for EX_FATAL, EX_NOERR, etc
/*
* reads the element map with specified ID
*/
int ex_get_partial_num_map(int exoid, ex_entity_type map_type, ex_entity_id map_id,
int64_t ent_start, int64_t ent_count, void_int *map)
{
int dimid, var_id, id_ndx, status;
size_t num_mobj, start[1], count[1];
char errmsg[MAX_ERR_LENGTH];
const char *dim_map_size;
const char *dim_num_maps;
EX_FUNC_ENTER();
if (ex__check_valid_file_id(exoid, __func__) == EX_FATAL) {
EX_FUNC_LEAVE(EX_FATAL);
}
switch (map_type) {
case EX_NODE_MAP:
dim_map_size = DIM_NUM_NODES;
dim_num_maps = DIM_NUM_NM;
break;
case EX_EDGE_MAP:
dim_map_size = DIM_NUM_EDGE;
dim_num_maps = DIM_NUM_EDM;
break;
case EX_FACE_MAP:
dim_map_size = DIM_NUM_FACE;
dim_num_maps = DIM_NUM_FAM;
break;
case EX_ELEM_MAP:
dim_map_size = DIM_NUM_ELEM;
dim_num_maps = DIM_NUM_EM;
break;
default:
snprintf(errmsg, MAX_ERR_LENGTH, "Bad map type (%d) specified", map_type);
ex_err_fn(exoid, __func__, errmsg, EX_BADPARAM);
EX_FUNC_LEAVE(EX_FATAL);
}
/* See if file contains any elements...*/
if (nc_inq_dimid(exoid, dim_map_size, &dimid) != NC_NOERR) {
EX_FUNC_LEAVE(EX_NOERR);
}
if ((status = nc_inq_dimlen(exoid, dimid, &num_mobj)) != NC_NOERR) {
snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to get number of mesh objects in file id %d",
exoid);
ex_err_fn(exoid, __func__, errmsg, status);
EX_FUNC_LEAVE(EX_FATAL);
}
/* Check input parameters for a valid range of numbers */
if (ent_start <= 0 || ent_start > num_mobj) {
snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: start count is invalid in file id %d", exoid);
ex_err_fn(exoid, __func__, errmsg, EX_BADPARAM);
EX_FUNC_LEAVE(EX_FATAL);
}
if (ent_count < 0) {
snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: Invalid count value in file id %d", exoid);
ex_err_fn(exoid, __func__, errmsg, EX_BADPARAM);
EX_FUNC_LEAVE(EX_FATAL);
}
if (ent_start + ent_count - 1 > num_mobj) {
snprintf(errmsg, MAX_ERR_LENGTH,
"ERROR: start+count-1 is larger than element count in file id %d", exoid);
ex_err_fn(exoid, __func__, errmsg, EX_BADPARAM);
EX_FUNC_LEAVE(EX_FATAL);
}
/* first check if any maps have been defined */
if ((status = nc_inq_dimid(exoid, dim_num_maps, &dimid)) != NC_NOERR) {
snprintf(errmsg, MAX_ERR_LENGTH, "Warning: no %ss defined in file id %d",
ex_name_of_object(map_type), exoid);
ex_err_fn(exoid, __func__, errmsg, status);
EX_FUNC_LEAVE(EX_WARN);
}
/* Lookup index of element map id property array */
id_ndx = ex__id_lkup(exoid, map_type, map_id);
if (id_ndx <= 0) {
snprintf(errmsg, MAX_ERR_LENGTH,
"ERROR: failed to locate %s id %" PRId64 " in id variable in file id %d",
ex_name_of_object(map_type), map_id, exoid);
ex_err_fn(exoid, __func__, errmsg, EX_LASTERR);
EX_FUNC_LEAVE(EX_FATAL);
}
/* inquire id's of previously defined dimensions and variables */
if ((status = nc_inq_varid(exoid, ex__name_of_map(map_type, id_ndx), &var_id)) != NC_NOERR) {
snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to locate %s %" PRId64 " in file id %d",
ex_name_of_object(map_type), map_id, exoid);
ex_err_fn(exoid, __func__, errmsg, status);
EX_FUNC_LEAVE(EX_FATAL);
}
/* read in the map */
start[0] = ent_start - 1;
count[0] = ent_count;
if (count[0] == 0) {
start[0] = 0;
}
if (ex_int64_status(exoid) & EX_MAPS_INT64_API) {
status = nc_get_vara_longlong(exoid, var_id, start, count, map);
}
else {
status = nc_get_vara_int(exoid, var_id, start, count, map);
}
if (status == -1) {
snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to get %s in file id %d",
ex_name_of_object(map_type), exoid);
ex_err_fn(exoid, __func__, errmsg, status);
EX_FUNC_LEAVE(EX_FATAL);
}
EX_FUNC_LEAVE(EX_NOERR);
}
| 412 | 0.950122 | 1 | 0.950122 | game-dev | MEDIA | 0.590639 | game-dev | 0.961817 | 1 | 0.961817 |
illarionov/wasi-emscripten-host | 1,594 | bindings-graalvm241-emscripten/src/jvmMain/kotlin/host/module/emscripten/function/SyscallFchown32.kt | /*
* Copyright 2024, the wasi-emscripten-host project authors and contributors. Please see the AUTHORS file
* for details. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
* SPDX-License-Identifier: Apache-2.0
*/
package at.released.weh.bindings.graalvm241.host.module.emscripten.function
import at.released.weh.bindings.graalvm241.ext.getArgAsInt
import at.released.weh.bindings.graalvm241.host.module.emscripten.BaseEmscriptenWasmNode
import at.released.weh.emcripten.runtime.function.SyscallFchown32FunctionHandle
import at.released.weh.host.EmbedderHost
import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary
import com.oracle.truffle.api.frame.VirtualFrame
import org.graalvm.wasm.WasmContext
import org.graalvm.wasm.WasmInstance
import org.graalvm.wasm.WasmLanguage
import org.graalvm.wasm.WasmModule
internal class SyscallFchown32(
language: WasmLanguage,
module: WasmModule,
host: EmbedderHost,
) : BaseEmscriptenWasmNode<SyscallFchown32FunctionHandle>(language, module, SyscallFchown32FunctionHandle(host)) {
override fun executeWithContext(frame: VirtualFrame, context: WasmContext, instance: WasmInstance): Int {
val args = frame.arguments
return syscallFchown32(
args.getArgAsInt(0),
args.getArgAsInt(1),
args.getArgAsInt(2),
)
}
@TruffleBoundary
@Suppress("MemberNameEqualsClassName")
private fun syscallFchown32(
fd: Int,
owner: Int,
group: Int,
): Int = handle.execute(fd, owner, group)
}
| 412 | 0.69441 | 1 | 0.69441 | game-dev | MEDIA | 0.483201 | game-dev | 0.702448 | 1 | 0.702448 |
dviglo/dviglo | 1,747 | source/third-party/slikenet/Source/include/slikenet/FileListNodeContext.h | /*
* Original work: Copyright (c) 2014, Oculus VR, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* RakNet License.txt file in the licenses directory of this source tree. An additional grant
* of patent rights can be found in the RakNet Patents.txt file in the same directory.
*
*
* Modified work: Copyright (c) 2017, SLikeSoft UG (haftungsbeschränkt)
*
* This source code was modified by SLikeSoft. Modifications are licensed under the MIT-style
* license found in the license.txt file in the root directory of this source tree.
*/
/// \file FileListNodeContext.h
///
#ifndef __FILE_LIST_NODE_CONTEXT_H
#define __FILE_LIST_NODE_CONTEXT_H
#include "BitStream.h"
struct FileListNodeContext
{
FileListNodeContext() {dataPtr=0; dataLength=0;}
FileListNodeContext(unsigned char o, uint32_t f1, uint32_t f2, uint32_t f3) : op(o), flnc_extraData1(f1), flnc_extraData2(f2), flnc_extraData3(f3) {dataPtr=0; dataLength=0;}
~FileListNodeContext() {}
unsigned char op;
uint32_t flnc_extraData1;
uint32_t flnc_extraData2;
uint32_t flnc_extraData3;
void *dataPtr;
unsigned int dataLength;
};
inline SLNet::BitStream& operator<<(SLNet::BitStream& out, FileListNodeContext& in)
{
out.Write(in.op);
out.Write(in.flnc_extraData1);
out.Write(in.flnc_extraData2);
out.Write(in.flnc_extraData3);
return out;
}
inline SLNet::BitStream& operator>>(SLNet::BitStream& in, FileListNodeContext& out)
{
in.Read(out.op);
bool success = in.Read(out.flnc_extraData1);
(void) success;
assert(success);
success = in.Read(out.flnc_extraData2);
(void) success;
assert(success);
success = in.Read(out.flnc_extraData3);
(void) success;
assert(success);
return in;
}
#endif
| 412 | 0.936739 | 1 | 0.936739 | game-dev | MEDIA | 0.267382 | game-dev | 0.851112 | 1 | 0.851112 |
EmpireBDev/PBEvo-Server-V3.68 | 5,289 | Server.Game/Network/ServerPacket/PROTOCOL_BATTLE_START_GAME_ACK.cs | using Plugin.Core.Enums;
using Plugin.Core.Models;
using Plugin.Core.Network;
using Server.Game.Data.Models;
namespace Server.Game.Network.ServerPacket
{
public class PROTOCOL_BATTLE_START_GAME_ACK : GameServerPacket
{
private readonly RoomModel Room;
public PROTOCOL_BATTLE_START_GAME_ACK(RoomModel Room)
{
this.Room = Room;
}
public override void Write()
{
WriteH(4103);
WriteH(0);
WriteB(PlayerIdData(Room));
WriteB(RoomSlotData(Room));
WriteB(SlotInfoData(Room));
WriteC((byte)Room.MapId);
WriteC((byte)Room.Rule);
WriteC((byte)Room.Stage);
WriteC((byte)Room.RoomType);
}
private byte[] PlayerIdData(RoomModel Room)
{
using (SyncServerPacket S = new SyncServerPacket())
{
S.WriteC((byte)Room.GetReadyPlayers());
for (int i = 0; i < Room.Slots.Length; i++)
{
SlotModel Slot = Room.Slots[i];
if (Slot.State >= SlotState.READY && Slot.Equipment != null)
{
Account Player = Room.GetPlayerBySlot(Slot);
if (Player != null && Player.SlotId == i)
{
S.WriteD((uint)Player.PlayerId);
}
}
}
return S.ToArray();
}
}
private byte[] RoomSlotData(RoomModel Room)
{
using (SyncServerPacket S = new SyncServerPacket())
{
S.WriteC((byte)Room.Slots.Length);
for (int i = 0; i < Room.Slots.Length; i++)
{
S.WriteC((byte)(i % 2));
}
return S.ToArray();
}
}
private byte[] SlotInfoData(RoomModel Room)
{
using (SyncServerPacket S = new SyncServerPacket())
{
S.WriteC((byte)Room.GetReadyPlayers());
for (int i = 0; i < Room.Slots.Length; i++)
{
SlotModel Slot = Room.Slots[i];
if (Slot.State >= SlotState.READY && Slot.Equipment != null)
{
Account Player = Room.GetPlayerBySlot(Slot);
if (Player != null && Player.SlotId == i)
{
S.WriteC((byte)Slot.Id);
S.WriteD(Slot.Id % 2 == 0 ? Slot.Equipment.CharaRedId : Slot.Equipment.CharaBlueId);
S.WriteD(Slot.Equipment.WeaponPrimary);
S.WriteD(Slot.Equipment.WeaponSecondary);
S.WriteD(Slot.Equipment.WeaponMelee);
S.WriteD(Slot.Equipment.WeaponExplosive);
S.WriteD(Slot.Equipment.WeaponSpecial);
if (Room.IsDinoMode())
{
if (!Room.SwapRound)
{
S.WriteD(Slot.Id % 2 == 0 ? Slot.Equipment.DinoItem : Slot.Equipment.CharaBlueId);
}
else
{
S.WriteD(Slot.Id % 2 == 0 ? Slot.Equipment.CharaRedId : Slot.Equipment.DinoItem);
}
}
else
{
S.WriteD(Slot.Id % 2 == 0 ? Slot.Equipment.CharaRedId : Slot.Equipment.CharaBlueId);
}
S.WriteD(Slot.Equipment.PartHead);
S.WriteD(Slot.Equipment.PartFace);
S.WriteD(Slot.Equipment.PartJacket);
S.WriteD(Slot.Equipment.PartPocket);
S.WriteD(Slot.Equipment.PartGlove);
S.WriteD(Slot.Equipment.PartBelt);
S.WriteD(Slot.Equipment.PartHolster);
S.WriteD(Slot.Equipment.PartSkin);
S.WriteD(Slot.Equipment.BeretItem);
S.WriteB(new byte[5] { 0x64, 0x64, 0x64, 0x64, 0x64 });
if (Player != null)
{
S.WriteC((byte)Player.Title.Equiped1);
S.WriteC((byte)Player.Title.Equiped2);
S.WriteC((byte)Player.Title.Equiped3);
}
else
{
S.WriteB(new byte[3] { 0xFF, 0xFF, 0xFF });
}
S.WriteD(Slot.Equipment.AccessoryId);
S.WriteD(Slot.Equipment.SprayId);
S.WriteD(Slot.Equipment.NameCardId);
}
}
}
return S.ToArray();
}
}
}
} | 412 | 0.779596 | 1 | 0.779596 | game-dev | MEDIA | 0.686953 | game-dev | 0.70641 | 1 | 0.70641 |
ErLinErYi/PlantsVsZombies | 4,575 | PlantsVsZombies/cocos2d/cocos/2d/CCActionTween.h | /****************************************************************************
Copyright (c) 2009 lhunath (Maarten Billemont)
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2013-2017 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#ifndef __CCACTIONTWEEN_H__
#define __CCACTIONTWEEN_H__
#include "2d/CCActionInterval.h"
NS_CC_BEGIN
/**
* @addtogroup actions
* @{
*/
/**
@brief The delegate class for ActionTween.
@details If you want to use ActionTween on a node.
You should implement the node follow these steps:
1. The node should be inherit from ActionTweenDelegate.
2. Override the virtual method updateTweenAction in the node.
Then once you running ActionTween on the node, the method updateTweenAction will be invoked.
*/
class CC_DLL ActionTweenDelegate
{
public:
/**
* @js NA
* @lua NA
*/
virtual ~ActionTweenDelegate() {}
/**
@brief The callback function when ActionTween is running.
@param value The new value of the specified key.
@param key The key of property which should be updated.
*/
virtual void updateTweenAction(float value, const std::string& key) = 0;
};
/** ActionTween
ActionTween is an action that lets you update any property of an object.
For example, if you want to modify the "width" property of a target from 200 to 300 in 2 seconds, then:
@code
auto modifyWidth = ActionTween::create(2, "width", 200, 300);
target->runAction(modifyWidth);
@endcode
Another example: ScaleTo action could be rewritten using PropertyAction:
@code
// scaleA and scaleB are equivalents
auto scaleA = ScaleTo::create(2, 3); // (duration, to)
auto scaleB = ActionTween::create(2, "scale", 1, 3); // (duration, key, from, to)
@endcode
@since v0.99.2
*/
class CC_DLL ActionTween : public ActionInterval
{
public:
/**
* @brief Create and initializes the action with the property name (key), and the from and to parameters.
* @param duration The duration of the ActionTween. It's a value in seconds.
* @param key The key of property which should be updated.
* @param from The value of the specified property when the action begin.
* @param to The value of the specified property when the action end.
* @return If the creation success, return a pointer of ActionTween; otherwise, return nil.
*/
static ActionTween* create(float duration, const std::string& key, float from, float to);
// Overrides
void startWithTarget(Node *target) override;
void update(float dt) override;
ActionTween* reverse() const override;
ActionTween *clone() const override;
CC_CONSTRUCTOR_ACCESS:
/**
* @brief Initializes the action with the property name (key), and the from and to parameters.
* @param duration The duration of the ActionTween. It's a value in seconds.
* @param key The key of property which should be updated.
* @param from The value of the specified property when the action begin.
* @param to The value of the specified property when the action end.
* @return If the initialization success, return true; otherwise, return false.
*/
bool initWithDuration(float duration, const std::string& key, float from, float to);
protected:
std::string _key;
float _from, _to;
float _delta;
};
// end of actions group
/// @}
NS_CC_END
#endif /* __CCACTIONTWEEN_H__ */
| 412 | 0.913364 | 1 | 0.913364 | game-dev | MEDIA | 0.874073 | game-dev | 0.660746 | 1 | 0.660746 |
Angry-Pixel/The-Betweenlands | 3,400 | src/main/java/thebetweenlands/common/world/gen/feature/WorldGenCaveThorns.java | package thebetweenlands.common.world.gen.feature;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Stack;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import thebetweenlands.common.block.plant.BlockThorns;
import thebetweenlands.common.registries.BlockRegistry;
public class WorldGenCaveThorns extends WorldGenCave {
private BlockThorns thorns = (BlockThorns) BlockRegistry.THORNS;
private static final int MIN_RADIUS = 2;
private static final int MAX_RADIUS = 3;
private static final int LENGTH_RANGE = 5;
private static final int MIN_LENGTH = 2;
private static final int MAX_HEIGHT = 8;
public WorldGenCaveThorns() {
this(false);
}
public WorldGenCaveThorns(boolean doBlockNotify) {
super(doBlockNotify);
}
@Override
public boolean generate(World world, Random random, BlockPos origin) {
if (!isGoodStart(world, origin)) {
return false;
}
int radius = random.nextInt(MAX_RADIUS - MIN_RADIUS + 1) + MIN_RADIUS;
int radiusSq = radius * radius;
Stack<BlockPos> searching = new Stack<BlockPos>();
List<BlockPos> checked = new ArrayList<BlockPos>();
List<PlantLocation> locations = new ArrayList<PlantLocation>();
BlockPos start = origin.add(0, -1, 0);
searching.push(start);
checked.add(start);
while (!searching.isEmpty()) {
BlockPos pos = searching.pop();
double distSq = origin.distanceSq(pos.getX(), pos.getY(), pos.getZ());
if (random.nextFloat() > distSq / radiusSq) {
locations.add(new PlantLocation(world, pos));
}
for (EnumFacing dir : directions) {
BlockPos offsetPos = pos.offset(dir);
if (offsetPos.distanceSq(origin.getX(), origin.getY(), origin.getZ()) > radiusSq) {
continue;
}
if (supports(world, offsetPos.add(0, 1, 0))) {
if (!checked.contains(offsetPos)) {
searching.push(offsetPos);
checked.add(offsetPos);
}
} else if (supports(world, offsetPos)) {
BlockPos below = offsetPos.add(0, -1, 0);
if (!checked.contains(below)) {
searching.push(below);
checked.add(below);
}
}
}
}
if (locations.size() < 5) {
return false;
}
int maximumHeight = 0;
for (PlantLocation location : locations) {
if (location.getHeight() > maximumHeight) {
maximumHeight = location.getHeight();
}
}
if (maximumHeight < 3) {
return false;
}
int[] facesWithThorns = new int[4];
for (PlantLocation location : locations) {
BlockPos pos = location.getPos();
int sideCount = 0;
int metadata = 0;
for (int n = 0; n < directions.length; n++) {
EnumFacing face = directions[n];
BlockPos neighbourPos = pos.offset(face);
if (isValidBlock(world, neighbourPos) && world.isSideSolid(neighbourPos, face)) {
int side = 1 << n;
facesWithThorns[sideCount++] = side;
metadata |= side;
}
}
this.setBlockAndNotifyAdequately(world, pos, thorns.getStateFromMeta(metadata));
if (metadata > 0 && location.getHeight() > 1) {
int hangingMetadata = facesWithThorns[random.nextInt(sideCount)];
int length = random.nextInt(location.getHeight() > MAX_HEIGHT ? MAX_HEIGHT : location.getHeight() - 1) + 1;
for (int n = 1; n < length; n++) {
setBlockAndNotifyAdequately(world, pos.add(0, -n, 0), thorns.getStateFromMeta(hangingMetadata));
}
}
}
return true;
}
}
| 412 | 0.931833 | 1 | 0.931833 | game-dev | MEDIA | 0.911246 | game-dev | 0.96112 | 1 | 0.96112 |
jleclanche/fireplace | 2,735 | fireplace/cards/uldum/priest.py | from ..utils import *
##
# Minions
class ULD_262:
"""High Priest Amet"""
# [x]Whenever you summon a minion, set its Health equal to this minion's.
events = Summon(CONTROLLER, MINION).on(SetStateBuff(Summon.CARD, "ULD_262e"))
class ULD_262e:
max_health = lambda self, _: self._xhealth
class ULD_266:
"""Grandmummy"""
# [x]<b>Reborn</b> <b>Deathrattle:</b> Give a random friendly minion +1/+1.
deathrattle = Buff(RANDOM_OTHER_FRIENDLY_MINION, "ULD_266e")
ULD_266e = buff(+1, +1)
class ULD_268:
"""Psychopomp"""
# [x]<b>Battlecry:</b> Summon a random friendly minion that died this game. Give it
# <b>Reborn</b>.
play = Summon(CONTROLLER, Copy(RANDOM(FRIENDLY + KILLED + MINION))).then(
GiveReborn(Summon.CARD)
)
class ULD_269:
"""Wretched Reclaimer"""
# [x]<b>Battlecry:</b> Destroy a friendly minion, then return it to life with full
# Health.
requirements = {
PlayReq.REQ_MINION_TARGET: 0,
PlayReq.REQ_FRIENDLY_TARGET: 0,
PlayReq.REQ_TARGET_IF_AVAILABLE: 0,
}
play = Destroy(TARGET), Summon(CONTROLLER, Copy(TARGET))
class ULD_270:
"""Sandhoof Waterbearer"""
# At the end of your turn, restore #5 Health to a damaged friendly character.
events = OWN_TURN_END.on(Heal(RANDOM(FRIENDLY + DAMAGED_CHARACTERS), 5))
##
# Spells
class ULD_265:
"""Embalming Ritual"""
# Give a minion <b>Reborn</b>.
requirements = {
PlayReq.REQ_TARGET_TO_PLAY: 0,
PlayReq.REQ_MINION_TARGET: 0,
}
play = GiveReborn(TARGET)
class ULD_272:
"""Holy Ripple"""
# Deal $1 damage to all enemies. Restore #1_Health to all friendly characters.
play = Hit(ENEMY_CHARACTERS, 1), Heal(FRIENDLY_CHARACTERS, 1)
class ULD_714:
"""Penance"""
# <b>Lifesteal</b> Deal $3 damage to a_minion.
requirements = {
PlayReq.REQ_TARGET_TO_PLAY: 0,
PlayReq.REQ_MINION_TARGET: 0,
}
play = Hit(TARGET, 3)
class ULD_718:
"""Plague of Death"""
# <b>Silence</b> and destroy all_minions.
play = Silence(ALL_MINIONS), Destroy(ALL_MINIONS)
class ULD_724:
"""Activate the Obelisk"""
# <b>Quest:</b> Restore 15_Health. <b>Reward:</b> Obelisk's Eye.
progress_total = 15
quest = Heal(source=FRIENDLY).after(AddProgress(SELF, Heal.TARGET, Heal.AMOUNT))
reward = Summon(CONTROLLER, "ULD_724p")
class ULD_724p:
"""Obelisk's Eye"""
# <b>Hero Power</b> Restore #3 Health. If you target a minion, also give it +3/+3.
requirements = {
PlayReq.REQ_TARGET_TO_PLAY: 0,
}
activate = Find(TARGET + MINION) & (Heal(TARGET, 3), Buff(TARGET, "ULD_724e")) | (
Heal(TARGET, 3)
)
ULD_724e = buff(+3, +3)
| 412 | 0.935894 | 1 | 0.935894 | game-dev | MEDIA | 0.975305 | game-dev | 0.828465 | 1 | 0.828465 |
llr104/LiFrame | 1,531 | server/gameslg/data/citymgr.go | package data
import (
"github.com/llr104/LiFrame/core/orm"
"github.com/llr104/LiFrame/server/gameslg/slgdb"
"github.com/llr104/LiFrame/server/gameslg/xlsx"
"github.com/llr104/LiFrame/utils"
"sync"
)
type cityManager struct {
cityMap map[int16] *slgdb.City
mutex sync.RWMutex
}
var CityMgr cityManager
func (s* cityManager) load() {
s.mutex.Lock()
defer s.mutex.Unlock()
count, err := orm.NewOrm().QueryTable(slgdb.City{}).Count()
if err != nil{
utils.Log.Error("WorldMap db error:%s", err.Error())
}else{
if count == 0 {
/*
还没有城市数据,创建城市数据
先简单点一个10个城市,魏蜀吴开始每个国家各有三个城池,魏蜀吴中间有一个空白城连接,只有占领了空白城才能攻击其他国家
*/
t := utils.XlsxMgr.Get(xlsx.XlsxCity, xlsx.SheetWorldCity)
n := t.GetCnt()
for i:=0; i<n; i++ {
cId, _ := t.GetInt("cId", i)
name, _ := t.GetString("name", i)
nation, _ := t.GetInt("nation", i)
capital, _ := t.GetInt("capital", i)
adjacent, _ := t.GetString("adjacent", i)
c := slgdb.City{CId:int16(cId), Name:name, Nation:int8(nation), Capital:capital==1, Adjacent:adjacent}
slgdb.InsertCityToDB(&c)
s.cityMap[c.CId] = &c
}
}else {
var citys []*slgdb.City
orm.NewOrm().QueryTable(slgdb.City{}).All(&citys)
for _,v := range citys{
s.cityMap[v.CId] = v
}
}
utils.Log.Info("读取城市数据成功:%v", s.cityMap)
}
}
func (s* cityManager) Count() int{
s.mutex.Lock()
defer s.mutex.Unlock()
return len(s.cityMap)
}
func (s* cityManager) CityMap() map[int16] *slgdb.City {
s.mutex.Lock()
defer s.mutex.Unlock()
return s.cityMap
}
| 412 | 0.749056 | 1 | 0.749056 | game-dev | MEDIA | 0.188364 | game-dev | 0.892546 | 1 | 0.892546 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.