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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
paper-plane-developers/paper-plane | 15,365 | src/ui/session/content/message_row/mod.rs | mod base;
mod bubble;
mod document;
mod indicators;
mod label;
mod location;
mod media_picture;
mod photo;
mod reply;
mod sticker;
mod text;
mod venue;
mod video;
use std::cell::RefCell;
use std::sync::OnceLock;
use adw::prelude::*;
use gettextrs::gettext;
use glib::clone;
use gtk::gio;
use gtk::glib;
use gtk::subclass::prelude::*;
use gtk::CompositeTemplate;
pub(crate) use self::base::MessageBase;
pub(crate) use self::base::MessageBaseExt;
pub(crate) use self::base::MessageBaseImpl;
pub(crate) use self::bubble::MessageBubble;
pub(crate) use self::document::MessageDocument;
pub(crate) use self::document::StatusIndicator as MessageDocumentStatusIndicator;
pub(crate) use self::indicators::MessageIndicators;
pub(crate) use self::label::MessageLabel;
pub(crate) use self::location::MessageLocation;
pub(crate) use self::media_picture::MediaPicture;
pub(crate) use self::photo::MessagePhoto;
pub(crate) use self::reply::MessageReply;
pub(crate) use self::sticker::MessageSticker;
pub(crate) use self::text::MessageText;
pub(crate) use self::venue::MessageVenue;
pub(crate) use self::video::MessageVideo;
use crate::model;
use crate::ui;
use crate::utils;
const AVATAR_SIZE: i32 = 32;
const SPACING: i32 = 6;
mod imp {
use super::*;
#[derive(Debug, Default, CompositeTemplate)]
#[template(resource = "/app/drey/paper-plane/ui/session/content/message_row/mod.ui")]
pub(crate) struct Row {
/// A `model::Message` or `SponsoredMessage`
pub(super) message: RefCell<Option<glib::Object>>,
pub(super) content: RefCell<Option<gtk::Widget>>,
pub(super) avatar: RefCell<Option<ui::Avatar>>,
}
#[glib::object_subclass]
impl ObjectSubclass for Row {
const NAME: &'static str = "PaplMessageRow";
type Type = super::Row;
type ParentType = gtk::Widget;
fn class_init(klass: &mut Self::Class) {
klass.bind_template();
klass.bind_template_instance_callbacks();
klass.install_action("message-row.reply", None, move |widget, _, _| {
widget.reply()
});
klass.install_action("message-row.edit", None, move |widget, _, _| widget.edit());
klass.install_action("message-row.revoke-delete", None, move |widget, _, _| {
widget.show_delete_dialog(true)
});
klass.install_action("message-row.delete", None, move |widget, _, _| {
widget.show_delete_dialog(false)
});
}
fn instance_init(obj: &glib::subclass::InitializingObject<Self>) {
obj.init_template();
}
}
impl ObjectImpl for Row {
fn properties() -> &'static [glib::ParamSpec] {
static PROPERTIES: OnceLock<Vec<glib::ParamSpec>> = OnceLock::new();
PROPERTIES.get_or_init(|| {
vec![glib::ParamSpecObject::builder::<glib::Object>("message")
.explicit_notify()
.build()]
})
}
fn set_property(&self, _id: usize, value: &glib::Value, pspec: &glib::ParamSpec) {
let obj = self.obj();
match pspec.name() {
"message" => obj.set_message(value.get().unwrap()),
_ => unimplemented!(),
}
}
fn property(&self, _id: usize, pspec: &glib::ParamSpec) -> glib::Value {
let obj = self.obj();
match pspec.name() {
"message" => obj.message().to_value(),
_ => unimplemented!(),
}
}
fn dispose(&self) {
if let Some(avatar) = self.avatar.borrow().as_ref() {
avatar.unparent();
}
if let Some(content) = self.content.borrow().as_ref() {
content.unparent();
}
}
}
impl WidgetImpl for Row {}
}
glib::wrapper! {
pub(crate) struct Row(ObjectSubclass<imp::Row>)
@extends gtk::Widget;
}
#[gtk::template_callbacks]
impl Row {
pub(crate) fn new(message: &glib::Object) -> Self {
let layout_manager = gtk::BoxLayout::builder().spacing(SPACING).build();
glib::Object::builder()
.property("layout-manager", layout_manager)
.property("message", message)
.build()
}
#[template_callback]
fn on_released(&self, n_press: i32, _x: f64, _y: f64) {
if n_press == 2 && self.can_reply_to_message() {
self.reply();
}
}
fn reply(&self) {
if let Ok(message) = self.message().downcast::<model::Message>() {
self.activate_action("chat-history.reply", Some(&message.id().to_variant()))
.unwrap();
}
}
fn edit(&self) {
if let Ok(message) = self.message().downcast::<model::Message>() {
self.activate_action("chat-history.edit", Some(&message.id().to_variant()))
.unwrap();
}
}
fn show_delete_dialog(&self, revoke: bool) {
let window: gtk::Window = self.root().and_then(|root| root.downcast().ok()).unwrap();
let message = if revoke {
gettext("Do you want to delete this message for <b>everyone</b>?")
} else {
gettext("Do you want to delete this message?")
};
let dialog = adw::MessageDialog::builder()
.heading(gettext("Confirm Message Deletion"))
.body_use_markup(true)
.body(message)
.transient_for(&window)
.build();
dialog.add_responses(&[("no", &gettext("_No")), ("yes", &gettext("_Yes"))]);
dialog.set_default_response(Some("no"));
dialog.set_response_appearance("yes", adw::ResponseAppearance::Destructive);
dialog.choose(
gio::Cancellable::NONE,
clone!(@weak self as obj => move |response| {
if response == "yes" {
if let Ok(message) = obj.message().downcast::<model::Message>() {
utils::spawn(async move {
if let Err(e) = message.delete(revoke).await {
log::warn!("Error deleting a message (revoke = {}): {:?}", revoke, e);
}
});
}
}
}));
}
pub(crate) fn message(&self) -> glib::Object {
self.imp().message.borrow().clone().unwrap()
}
pub(crate) fn set_message(&self, message: glib::Object) {
let imp = self.imp();
if imp.message.borrow().as_ref() == Some(&message) {
return;
}
if let Some(message) = message.downcast_ref::<model::Message>() {
let show_avatar = if message.is_outgoing() {
false
} else if message.chat_().is_own_chat() {
message.forward_info().is_some()
} else {
match message.chat_().chat_type() {
model::ChatType::BasicGroup(_) => true,
model::ChatType::Supergroup(supergroup) => !supergroup.is_channel(),
_ => false,
}
};
if show_avatar {
let avatar = {
let mut avatar_borrow = imp.avatar.borrow_mut();
if let Some(avatar) = avatar_borrow.clone() {
avatar
} else {
let avatar = ui::Avatar::new();
avatar.set_size(AVATAR_SIZE);
avatar.set_valign(gtk::Align::End);
// Insert at the beginning
avatar.insert_after(self, gtk::Widget::NONE);
*avatar_borrow = Some(avatar.clone());
avatar
}
};
if message.chat_().is_own_chat() {
match message.forward_info().unwrap().origin() {
model::MessageForwardOrigin::User(user) => {
avatar.set_custom_text(None);
avatar.set_item(Some(user.upcast()));
}
model::MessageForwardOrigin::Chat { chat, .. }
| model::MessageForwardOrigin::Channel { chat, .. } => {
avatar.set_custom_text(None);
avatar.set_item(Some(chat.upcast()));
}
model::MessageForwardOrigin::HiddenUser { sender_name }
| model::MessageForwardOrigin::MessageImport { sender_name } => {
avatar.set_item(None);
avatar.set_custom_text(Some(&sender_name));
}
}
} else {
let avatar_item = match message.sender() {
model::MessageSender::User(user) => user.upcast(),
model::MessageSender::Chat(chat) => chat.upcast(),
};
avatar.set_custom_text(None);
avatar.set_item(Some(avatar_item));
}
} else {
if let Some(avatar) = imp.avatar.borrow().as_ref() {
avatar.unparent();
}
imp.avatar.replace(None);
}
}
self.update_content(message.clone());
imp.message.replace(Some(message));
// TODO: Update actions when needed (e.g. chat permissions change)
self.update_actions();
self.notify("message");
}
fn can_reply_to_message(&self) -> bool {
if let Some(message) = self.message().downcast_ref::<model::Message>() {
can_send_messages_in_chat(&message.chat_())
} else {
false
}
}
fn can_edit_message(&self) -> bool {
if let Some(message) = self.message().downcast_ref::<model::Message>() {
let is_text_message = matches!(
message.content().0,
tdlib::enums::MessageContent::MessageText(_)
);
// TODO: Support more message types in the future
is_text_message
&& message.can_be_edited()
&& can_send_messages_in_chat(&message.chat_())
} else {
false
}
}
fn update_actions(&self) {
self.action_set_enabled("message-row.reply", self.can_reply_to_message());
self.action_set_enabled("message-row.edit", self.can_edit_message());
if let Some(message) = self.message().downcast_ref::<model::Message>() {
self.action_set_enabled("message-row.delete", message.can_be_deleted_only_for_self());
self.action_set_enabled(
"message-row.revoke-delete",
message.can_be_deleted_for_all_users(),
);
} else {
self.action_set_enabled("message-row.delete", false);
self.action_set_enabled("message-row.revoke-delete", false);
}
}
fn update_content(&self, message: glib::Object) {
use tdlib::enums::MessageContent::*;
let is_outgoing = if let Some(message_) = message.downcast_ref::<model::Message>() {
// Do not mark channel messages as outgoing
let is_outgoing = match message_.chat_().chat_type() {
model::ChatType::Supergroup(data) if data.is_channel() => false,
_ => message_.is_outgoing(),
};
match message_.content().0 {
// FIXME: Re-enable MessageVideo when
// https://github.com/paper-plane-developers/paper-plane/issues/410 is fixed
MessageAnimation(_) /*| MessageContent::MessageVideo(_)*/ => {
self.update_specific_content::<_, ui::MessageVideo>(message_);
}
MessageAnimatedEmoji(data)
if data.animated_emoji.sticker.clone().map(
|s| matches!(s.format, tdlib::enums::StickerFormat::Webp | tdlib::enums::StickerFormat::Tgs)
).unwrap_or_default() => {
self.update_specific_content::<_, ui::MessageSticker>(message_);
}
MessageLocation(_) => {
self.update_specific_content::<_, ui::MessageLocation>(message_);
}
MessagePhoto(_) => {
self.update_specific_content::<_, ui::MessagePhoto>(message_);
}
MessageSticker(data)
if matches!(data.sticker.format, tdlib::enums::StickerFormat::Webp | tdlib::enums::StickerFormat::Tgs) =>
{
self.update_specific_content::<_, ui::MessageSticker>(message_);
}
MessageDocument(_) => {
self.update_specific_content::<_, ui::MessageDocument>(message_);
}
MessageVenue(_) => {
self.update_specific_content::<_, ui::MessageVenue>(message_);
}
_ => {
self.update_specific_content::<_, ui::MessageText>(&message);
}
}
is_outgoing
} else {
self.update_specific_content::<_, ui::MessageText>(&message);
false
};
let content_ref = self.imp().content.borrow();
let content = content_ref.as_ref().unwrap();
if is_outgoing {
content.set_halign(gtk::Align::End);
} else {
content.set_halign(gtk::Align::Start);
}
}
fn update_specific_content<M, B>(&self, message: &M)
where
B: MessageBaseExt<Message = M>,
{
let mut content_ref = self.imp().content.borrow_mut();
match content_ref.as_ref().and_then(|c| c.downcast_ref::<B>()) {
Some(content) => {
content.set_message(message);
}
None => {
if let Some(old_content) = &*content_ref {
old_content.unparent();
}
let content = B::new(message);
content.set_hexpand(true);
content.set_valign(gtk::Align::Start);
// Insert at the end
content.insert_before(self, gtk::Widget::NONE);
*content_ref = Some(content.upcast());
}
}
}
}
fn can_send_messages_in_chat(chat: &model::Chat) -> bool {
use tdlib::enums::ChatMemberStatus::*;
let member_status = match chat.chat_type() {
model::ChatType::Supergroup(supergroup) => Some(supergroup.status()),
model::ChatType::BasicGroup(supergroup) => Some(supergroup.status()),
_ => None,
};
member_status
.map(|s| match s.0 {
Creator(_) => true,
Administrator(_) => true,
Member => chat.permissions().0.can_send_basic_messages,
Restricted(data) => {
chat.permissions().0.can_send_basic_messages
&& data.permissions.can_send_basic_messages
}
Left => false,
Banned(_) => false,
})
.unwrap_or(true)
}
| 412 | 0.878956 | 1 | 0.878956 | game-dev | MEDIA | 0.519284 | game-dev | 0.924545 | 1 | 0.924545 |
OpenMITM/MuCuteClient | 4,647 | app/src/main/java/com/mucheng/mucute/client/game/module/combat/KillauraModule.kt | package com.mucheng.mucute.client.game.module.combat
import com.mucheng.mucute.client.game.InterceptablePacket
import com.mucheng.mucute.client.game.Module
import com.mucheng.mucute.client.game.ModuleCategory
import com.mucheng.mucute.client.game.entity.*
import org.cloudburstmc.math.vector.Vector3f
import org.cloudburstmc.protocol.bedrock.packet.MovePlayerPacket
import org.cloudburstmc.protocol.bedrock.packet.PlayerAuthInputPacket
class KillauraModule : Module("killaura", ModuleCategory.Combat) {
private var playersOnly by boolValue("players_only", true)
private var mobsOnly by boolValue("mobs_only", false)
private var tpAuraEnabled by boolValue("tp_aura", false)
private var rangeValue by floatValue("range", 3.7f, 2f..7f)
private var attackInterval by intValue("delay", 5, 1..20)
private var cpsValue by intValue("cps", 10, 1..20)
private var boost by intValue("packets", 1, 1..10)
private var tpspeed by intValue("tp_speed", 1000, 100..2000)
private var distanceToKeep by floatValue("keep_distance", 2.0f, 1f..5f)
private var lastAttackTime = 0L
private var tpCooldown = 0L
override fun beforePacketBound(interceptablePacket: InterceptablePacket) {
if (!isEnabled) return
val packet = interceptablePacket.packet
if (packet is PlayerAuthInputPacket) {
val currentTime = System.currentTimeMillis()
val minAttackDelay = 1000L / cpsValue
if (packet.tick % attackInterval == 0L && (currentTime - lastAttackTime) >= minAttackDelay) {
val closestEntities = searchForClosestEntities()
if (closestEntities.isEmpty()) return
closestEntities.forEach { entity ->
// Handle teleportation once when TP Aura is enabled
if (tpAuraEnabled && (currentTime - tpCooldown) >= tpspeed) {
teleportTo(entity, distanceToKeep)
tpCooldown = currentTime
}
repeat(boost) {
session.localPlayer.attack(entity)
}
lastAttackTime = currentTime
}
}
}
}
private fun teleportTo(entity: Entity, distance: Float) {
val targetPosition = entity.vec3Position
val playerPosition = session.localPlayer.vec3Position
val direction = Vector3f.from(
targetPosition.x - playerPosition.x,
0f, // No modification to Y-axis
targetPosition.z - playerPosition.z
)
val length = direction.length()
val normalizedDirection = if (length != 0f) {
Vector3f.from(direction.x / length, 0f, direction.z / length)
} else {
direction
}
val newPosition = Vector3f.from(
targetPosition.x - normalizedDirection.x * distance,
playerPosition.y,
targetPosition.z - normalizedDirection.z * distance
)
val movePlayerPacket = MovePlayerPacket().apply {
runtimeEntityId = session.localPlayer.runtimeEntityId
position = newPosition
rotation = entity.vec3Rotation
mode = MovePlayerPacket.Mode.NORMAL
isOnGround = false
ridingRuntimeEntityId = 0
tick = session.localPlayer.tickExists
}
session.clientBound(movePlayerPacket)
}
private fun Entity.isTarget(): Boolean {
return when (this) {
is LocalPlayer -> false
is Player -> {
if (mobsOnly) {
false
} else if (playersOnly) {
!this.isBot()
} else {
!this.isBot()
}
}
is EntityUnknown -> {
if (mobsOnly) {
isMob()
} else if (playersOnly) {
false
} else {
true
}
}
else -> false
}
}
private fun EntityUnknown.isMob(): Boolean {
return this.identifier in MobList.mobTypes
}
private fun Player.isBot(): Boolean {
if (this is LocalPlayer) return false
val playerList = session.level.playerMap[this.uuid] ?: return true
return playerList.name.isBlank()
}
private fun searchForClosestEntities(): List<Entity> {
return session.level.entityMap.values
.filter { entity -> entity.distance(session.localPlayer) < rangeValue && entity.isTarget() }
}
} | 412 | 0.905073 | 1 | 0.905073 | game-dev | MEDIA | 0.949642 | game-dev | 0.937733 | 1 | 0.937733 |
bitzhuwei/SharpFileDB | 5,384 | SharpFileDB/Blocks/IndexBlock.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//using System.Threading.Tasks;
namespace SharpFileDB.Blocks
{
/// <summary>
/// 存储索引的块。此块在内存中充当skip list。
/// </summary>
[Serializable]
public class IndexBlock : AllocBlock, ILinkedNode<IndexBlock>
{
/// <summary>
/// 此Index代表的Skip List的头结点列的最上方的结点(this.SkipListHeadNodes.Last())的位置。
/// </summary>
public long SkipListHeadNodePos { get; set; }
/// <summary>
/// 此索引的第一列skip list结点。是skip list的头结点。
/// <para>SkipListHeadNodes[0]是最下方的结点。</para>
/// <para>/*SkipListNodes[maxLevel - 1]↓*/</para>
/// <para>/*SkipListNodes[.]↓*/</para>
/// <para>/*SkipListNodes[.]↓*/</para>
/// <para>/*SkipListNodes[2]↓*/</para>
/// <para>/*SkipListNodes[1]↓*/</para>
/// <para>/*SkipListNodes[0] */</para>
/// </summary>
public SkipListNodeBlock[] SkipListHeadNodes { get; set; }
/// <summary>
/// 此Index代表的Skip List的尾结点(this.SkipListHeadNode)的位置。
/// </summary>
public long SkipListTailNodePos { get; set; }
/// <summary>
/// 此索引的最后一个skip list结点。是skip list的尾结点。
/// </summary>
public SkipListNodeBlock SkipListTailNode { get; set; }
/// <summary>
/// 安排所有文件指针。如果全部安排完毕,返回true,否则返回false。
/// </summary>
/// <returns></returns>
public override bool ArrangePos()
{
bool allArranged = true;
if (this.SkipListHeadNodes != null)// 如果这里的SkipListHeadNodes == null,则说明此索引块是索引链表里的头结点。头结点是不需要SkipListHeadNodes有数据的。
{
int length = this.SkipListHeadNodes.Length;
if (length == 0)
{ throw new Exception("SKip List's head nodes has 0 element!"); }
long pos = this.SkipListHeadNodes[length - 1].ThisPos;
if (pos != 0)
{ this.SkipListHeadNodePos = pos; }
else
{ allArranged = false; }
}
if (this.SkipListTailNode != null)// 如果这里的SkipListTailNodes == null,则说明此索引块是索引链表里的头结点。头结点是不需要SkipListTailNodes有数据的。
{
long pos = this.SkipListTailNode.ThisPos;
if (pos != 0)
{ this.SkipListTailNodePos = pos; }
else
{ allArranged = false; }
}
if (this.NextObj != null)
{
if (this.NextObj.ThisPos != 0)
{ this.NextPos = this.NextObj.ThisPos; }
else
{ allArranged = false; }
}
return allArranged;
}
/// <summary>
/// 用于加速skip list的增删。
/// </summary>
public int CurrentLevel { get; set; }
/// <summary>
/// 此Index代表的表的成员(字段/属性)名。
/// </summary>
public string BindMember { get; set; }
/// <summary>
/// 存储索引的块。
/// </summary>
public IndexBlock() { }
const string strSkipListHeadNodePos = "A";
const string strSkipListTailNodePos = "B";
const string strCurrentLevel = "C";
const string strBindMember = "D";
const string strNext = "E";
/// <summary>
/// 序列化时系统会调用此方法。
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
{
base.GetObjectData(info, context);
info.AddValue(strSkipListHeadNodePos, this.SkipListHeadNodePos);
info.AddValue(strSkipListTailNodePos, this.SkipListTailNodePos);
info.AddValue(strCurrentLevel, this.CurrentLevel);
info.AddValue(strBindMember, this.BindMember);
info.AddValue(strNext, this.NextPos);
}
/// <summary>
/// BinaryFormatter会通过调用此方法来反序列化此块。
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
protected IndexBlock(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{
this.SkipListHeadNodePos = info.GetInt64(strSkipListHeadNodePos);
this.SkipListTailNodePos = info.GetInt64(strSkipListTailNodePos);
this.CurrentLevel = info.GetInt32(strCurrentLevel);
this.BindMember = info.GetString(strBindMember);
this.NextPos = info.GetInt64(strNext);
}
#region IDoubleLinkedNode 成员
/// <summary>
/// 数据库中保存此值。
/// </summary>
public long NextPos { get; set; }
/// <summary>
/// 数据库中不保存此值。
/// </summary>
public IndexBlock NextObj { get; set; }
#endregion
/// <summary>
/// 显示此块的信息,便于调试。
/// </summary>
/// <returns></returns>
public override string ToString()
{
return string.Format("{0}, SkipListHeadNodePos: {1}, BindMember: {2}, NextPos: {3}",
base.ToString(),
this.SkipListHeadNodePos,
this.BindMember,
this.NextPos);
}
}
}
| 412 | 0.777771 | 1 | 0.777771 | game-dev | MEDIA | 0.400346 | game-dev | 0.601365 | 1 | 0.601365 |
EOS-team/EOS | 12,834 | src/embodied-intelligence/src/3D_human_pose_recognition/ios_sdk/UnityDEBUG/ForDebug/Library/PackageCache/com.unity.timeline@1.6.4/Editor/Utilities/ClipModifier.cs | using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine.Timeline;
using UnityEngine.Playables;
namespace UnityEditor.Timeline
{
static class ClipModifier
{
public static bool Delete(TimelineAsset timeline, TimelineClip clip)
{
return timeline.DeleteClip(clip);
}
public static bool Tile(IEnumerable<TimelineClip> clips)
{
if (clips.Count() < 2)
return false;
var clipsByTracks = clips.GroupBy(x => x.GetParentTrack())
.Select(track => new { track.Key, Items = track.OrderBy(c => c.start) });
foreach (var track in clipsByTracks)
{
UndoExtensions.RegisterTrack(track.Key, L10n.Tr("Tile"));
}
foreach (var track in clipsByTracks)
{
double newStart = track.Items.First().start;
foreach (var c in track.Items)
{
c.start = newStart;
newStart += c.duration;
}
}
return true;
}
public static bool TrimStart(IEnumerable<TimelineClip> clips, double trimTime)
{
var result = false;
foreach (var clip in clips)
result |= TrimStart(clip, trimTime);
return result;
}
public static bool TrimStart(TimelineClip clip, double trimTime)
{
if (clip.asset == null)
return false;
if (clip.start > trimTime)
return false;
if (clip.end < trimTime)
return false;
UndoExtensions.RegisterClip(clip, L10n.Tr("Trim Clip Start"));
// Note: We are NOT using edit modes in this case because we want the same result
// regardless of the selected EditMode: split at cursor and delete left part
SetStart(clip, trimTime, false);
clip.ConformEaseValues();
return true;
}
public static bool TrimEnd(IEnumerable<TimelineClip> clips, double trimTime)
{
var result = false;
foreach (var clip in clips)
result |= TrimEnd(clip, trimTime);
return result;
}
public static bool TrimEnd(TimelineClip clip, double trimTime)
{
if (clip.asset == null)
return false;
if (clip.start > trimTime)
return false;
if (clip.end < trimTime)
return false;
UndoExtensions.RegisterClip(clip, L10n.Tr("Trim Clip End"));
TrimClipWithEditMode(clip, TrimEdge.End, trimTime);
return true;
}
public static bool MatchDuration(IEnumerable<TimelineClip> clips)
{
double referenceDuration = clips.First().duration;
UndoExtensions.RegisterClips(clips, L10n.Tr("Match Clip Duration"));
foreach (var clip in clips)
{
var newEnd = clip.start + referenceDuration;
TrimClipWithEditMode(clip, TrimEdge.End, newEnd);
}
return true;
}
public static bool Split(IEnumerable<TimelineClip> clips, double splitTime, PlayableDirector director)
{
var result = false;
foreach (var clip in clips)
{
if (clip.start >= splitTime)
continue;
if (clip.end <= splitTime)
continue;
UndoExtensions.RegisterClip(clip, L10n.Tr("Split Clip"));
TimelineClip newClip = TimelineHelpers.Clone(clip, director, director, clip.start);
clip.easeInDuration = 0;
newClip.easeOutDuration = 0;
SetStart(clip, splitTime, false);
SetEnd(newClip, splitTime, false);
// Sort produced by cloning clips on top of each other is unpredictable (it varies between mono runtimes)
clip.GetParentTrack().SortClips();
result = true;
}
return result;
}
public static void SetStart(TimelineClip clip, double time, bool affectTimeScale)
{
var supportsClipIn = clip.SupportsClipIn();
var supportsPadding = TimelineUtility.IsRecordableAnimationClip(clip);
bool calculateTimeScale = (affectTimeScale && clip.SupportsSpeedMultiplier());
// treat empty recordable clips as not supporting clip in (there are no keys to modify)
if (supportsPadding && (clip.animationClip == null || clip.animationClip.empty))
{
supportsClipIn = false;
}
if (supportsClipIn && !supportsPadding && !calculateTimeScale)
{
var minStart = clip.FromLocalTimeUnbound(0.0);
if (time < minStart)
time = minStart;
}
var maxStart = clip.end - TimelineClip.kMinDuration;
if (time > maxStart)
time = maxStart;
var timeOffset = time - clip.start;
var duration = clip.duration - timeOffset;
if (calculateTimeScale)
{
var f = clip.duration / duration;
clip.timeScale *= f;
}
if (supportsClipIn && !calculateTimeScale)
{
if (supportsPadding)
{
double clipInGlobal = clip.clipIn / clip.timeScale;
double keyShift = -timeOffset;
if (timeOffset < 0) // left drag, eliminate clipIn before shifting
{
double clipInDelta = Math.Max(-clipInGlobal, timeOffset);
keyShift = -Math.Min(0, timeOffset - clipInDelta);
clip.clipIn += clipInDelta * clip.timeScale;
}
else if (timeOffset > 0) // right drag, elimate padding in animation clip before adding clip in
{
var clipInfo = AnimationClipCurveCache.Instance.GetCurveInfo(clip.animationClip);
double keyDelta = clip.FromLocalTimeUnbound(clipInfo.keyTimes.Min()) - clip.start;
keyShift = -Math.Max(0, Math.Min(timeOffset, keyDelta));
clip.clipIn += Math.Max(timeOffset + keyShift, 0) * clip.timeScale;
}
if (keyShift != 0)
{
AnimationTrackRecorder.ShiftAnimationClip(clip.animationClip, (float)(keyShift * clip.timeScale));
}
}
else
{
clip.clipIn += timeOffset * clip.timeScale;
}
}
clip.start = time;
clip.duration = duration;
}
public static void SetEnd(TimelineClip clip, double time, bool affectTimeScale)
{
var duration = Math.Max(time - clip.start, TimelineClip.kMinDuration);
if (affectTimeScale && clip.SupportsSpeedMultiplier())
{
var f = clip.duration / duration;
clip.timeScale *= f;
}
clip.duration = duration;
}
public static bool ResetEditing(IEnumerable<TimelineClip> clips)
{
var result = false;
foreach (var clip in clips)
result = result || ResetEditing(clip);
return result;
}
public static bool ResetEditing(TimelineClip clip)
{
if (clip.asset == null)
return false;
UndoExtensions.RegisterClip(clip, L10n.Tr("Reset Clip Editing"));
clip.clipIn = 0.0;
if (clip.clipAssetDuration < double.MaxValue)
{
var duration = clip.clipAssetDuration / clip.timeScale;
TrimClipWithEditMode(clip, TrimEdge.End, clip.start + duration);
}
return true;
}
public static bool MatchContent(IEnumerable<TimelineClip> clips)
{
var result = false;
foreach (var clip in clips)
result |= MatchContent(clip);
return result;
}
public static bool MatchContent(TimelineClip clip)
{
if (clip.asset == null)
return false;
UndoExtensions.RegisterClip(clip, L10n.Tr("Match Clip Content"));
var newStartCandidate = clip.start - clip.clipIn / clip.timeScale;
var newStart = newStartCandidate < 0.0 ? 0.0 : newStartCandidate;
TrimClipWithEditMode(clip, TrimEdge.Start, newStart);
// In case resetting the start was blocked by edit mode or timeline start, we do the best we can
clip.clipIn = (clip.start - newStartCandidate) * clip.timeScale;
if (clip.clipAssetDuration > 0 && TimelineHelpers.HasUsableAssetDuration(clip))
{
var duration = TimelineHelpers.GetLoopDuration(clip);
var offset = (clip.clipIn / clip.timeScale) % duration;
TrimClipWithEditMode(clip, TrimEdge.End, clip.start - offset + duration);
}
return true;
}
public static void TrimClipWithEditMode(TimelineClip clip, TrimEdge edge, double time)
{
var clipItem = ItemsUtils.ToItem(clip);
EditMode.BeginTrim(clipItem, edge);
if (edge == TrimEdge.Start)
EditMode.TrimStart(clipItem, time, false);
else
EditMode.TrimEnd(clipItem, time, false);
EditMode.FinishTrim();
}
public static bool CompleteLastLoop(IEnumerable<TimelineClip> clips)
{
foreach (var clip in clips)
{
CompleteLastLoop(clip);
}
return true;
}
public static void CompleteLastLoop(TimelineClip clip)
{
FixLoops(clip, true);
}
public static bool TrimLastLoop(IEnumerable<TimelineClip> clips)
{
foreach (var clip in clips)
{
TrimLastLoop(clip);
}
return true;
}
public static void TrimLastLoop(TimelineClip clip)
{
FixLoops(clip, false);
}
static void FixLoops(TimelineClip clip, bool completeLastLoop)
{
if (!TimelineHelpers.HasUsableAssetDuration(clip))
return;
var loopDuration = TimelineHelpers.GetLoopDuration(clip);
var firstLoopDuration = loopDuration - clip.clipIn * (1.0 / clip.timeScale);
// Making sure we don't trim to zero
if (!completeLastLoop && firstLoopDuration > clip.duration)
return;
var numLoops = (clip.duration - firstLoopDuration) / loopDuration;
var numCompletedLoops = Math.Floor(numLoops);
if (!(numCompletedLoops < numLoops))
return;
if (completeLastLoop)
numCompletedLoops += 1;
var newEnd = clip.start + firstLoopDuration + loopDuration * numCompletedLoops;
UndoExtensions.RegisterClip(clip, L10n.Tr("Trim Clip Last Loop"));
TrimClipWithEditMode(clip, TrimEdge.End, newEnd);
}
public static bool DoubleSpeed(IEnumerable<TimelineClip> clips)
{
foreach (var clip in clips)
{
if (clip.SupportsSpeedMultiplier())
{
UndoExtensions.RegisterClip(clip, L10n.Tr("Double Clip Speed"));
clip.timeScale = clip.timeScale * 2.0f;
}
}
return true;
}
public static bool HalfSpeed(IEnumerable<TimelineClip> clips)
{
foreach (var clip in clips)
{
if (clip.SupportsSpeedMultiplier())
{
UndoExtensions.RegisterClip(clip, L10n.Tr("Half Clip Speed"));
clip.timeScale = clip.timeScale * 0.5f;
}
}
return true;
}
public static bool ResetSpeed(IEnumerable<TimelineClip> clips)
{
foreach (var clip in clips)
{
if (clip.timeScale != 1.0)
{
UndoExtensions.RegisterClip(clip, L10n.Tr("Reset Clip Speed"));
clip.timeScale = 1.0;
}
}
return true;
}
}
}
| 412 | 0.705973 | 1 | 0.705973 | game-dev | MEDIA | 0.510451 | game-dev | 0.935883 | 1 | 0.935883 |
Team-Immersive-Intelligence/ImmersiveIntelligence | 4,296 | src/main/java/pl/pabilo8/immersiveintelligence/common/entity/ammo/component/EntityWhitePhosphorus.java | package pl.pabilo8.immersiveintelligence.common.entity.ammo.component;
import blusunrize.immersiveengineering.common.entities.EntityIEProjectile;
import blusunrize.immersiveengineering.common.util.IEPotions;
import blusunrize.immersiveengineering.common.util.Utils;
import com.elytradev.mirage.event.GatherLightsEvent;
import com.elytradev.mirage.lighting.ILightEventConsumer;
import com.elytradev.mirage.lighting.Light;
import net.minecraft.entity.EntityAreaEffectCloud;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.SoundEvents;
import net.minecraft.potion.PotionEffect;
import net.minecraft.util.EnumParticleTypes;
import net.minecraft.util.SoundCategory;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.math.RayTraceResult.Type;
import net.minecraft.world.Explosion;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.Optional;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import pl.pabilo8.immersiveintelligence.client.fx.utils.ParticleRegistry;
import pl.pabilo8.immersiveintelligence.common.IIPotions;
import pl.pabilo8.immersiveintelligence.common.util.IIColor;
import pl.pabilo8.immersiveintelligence.common.util.entity.IIEntityUtils;
/**
* @author Pabilo8 (pabilo@iiteam.net)
* @since 26.10.2019
*/
@net.minecraftforge.fml.common.Optional.Interface(iface = "com.elytradev.mirage.lighting.ILightEventConsumer", modid = "mirage")
public class EntityWhitePhosphorus extends EntityIEProjectile implements ILightEventConsumer
{
public EntityWhitePhosphorus(World world)
{
super(world);
}
public EntityWhitePhosphorus(World world, double x, double y, double z, double ax, double ay, double az)
{
super(world, x, y, z, ax, ay, az);
}
@Override
protected void entityInit()
{
super.entityInit();
}
@Override
public double getGravity()
{
return 0.07F;
}
/**
* Gets called every tick from main Entity class
*/
@Override
public void onEntityUpdate()
{
super.onEntityUpdate();
if(getEntityWorld().isRemote)
spawnTracerParticles();
}
@SideOnly(Side.CLIENT)
private void spawnTracerParticles()
{
ParticleRegistry.spawnTracerFX(getPositionVector(), IIEntityUtils.getEntityMotion(this), 0.2f, IIColor.WHITE);
}
/**
* Sets entity to burn for x scatter of seconds, cannot lower scatter of existing fire.
*/
@Override
public void setFire(int seconds)
{
super.setFire(seconds);
}
@Override
public void onImpact(RayTraceResult mop)
{
if(!this.world.isRemote&&mop.typeOfHit!=Type.MISS&&world!=null&&mop.getBlockPos()!=null)
{
Explosion explosion = new Explosion(world, this, posX, posY, posZ, 1, true, false);
explosion.doExplosionA();
explosion.doExplosionB(false);
world.playSound(null, mop.getBlockPos(), SoundEvents.BLOCK_LAVA_EXTINGUISH, SoundCategory.BLOCKS, 0.125f, 1f);
EntityAreaEffectCloud cloud = new EntityAreaEffectCloud(world, mop.getBlockPos().getX(), mop.getBlockPos().getY()+1f, mop.getBlockPos().getZ());
cloud.addEffect(new PotionEffect(IIPotions.brokenArmor, Math.round(180), 1));
cloud.addEffect(new PotionEffect(IEPotions.flammable, Math.round(180), 2));
cloud.addEffect(new PotionEffect(IEPotions.stunned, Math.round(80), 1));
cloud.addEffect(new PotionEffect(IEPotions.flashed, Math.round(120), 1));
cloud.setRadius(6f);
cloud.setDuration(Math.round(30f+(10f*Utils.RAND.nextFloat())));
cloud.setParticle(EnumParticleTypes.CLOUD);
world.spawnEntity(cloud);
world.getEntitiesWithinAABB(EntityLivingBase.class, new AxisAlignedBB(getPosition()).grow(0.5f)).forEach(entityLivingBase -> entityLivingBase.setFire(40));
setDead();
}
}
@Override
protected boolean allowFriendlyFire(EntityPlayer target)
{
return false;
}
@Override
@SideOnly(Side.CLIENT)
public int getBrightnessForRender()
{
return 15;
}
/**
* Gets how bright this entity is.
*/
@Override
public float getBrightness()
{
return 15;
}
@Override
@SideOnly(Side.CLIENT)
@Optional.Method(modid = "mirage")
public void gatherLights(GatherLightsEvent evt)
{
evt.add(Light.builder()
.pos(this)
.color(1, 1, 1)
.radius(.05f)
.build());
}
} | 412 | 0.881031 | 1 | 0.881031 | game-dev | MEDIA | 0.98748 | game-dev | 0.904771 | 1 | 0.904771 |
BartoszMilewski/CodeCoop | 1,341 | co-op/UniqueName.cpp | //-----------------------------------------
// (c) Reliable Software 1998 -- 2001
//-----------------------------------------
#include "precompiled.h"
#include "UniqueName.h"
#include <File/Path.h>
#include <StringOp.h>
//
// UniqueName
//
void UniqueName::Serialize (Serializer& out) const
{
out.PutLong (_gidParent);
_name.Serialize (out);
}
void UniqueName::Deserialize (Deserializer& in, int version)
{
_gidParent = in.GetLong ();
_name.Deserialize (in, version);
}
bool UniqueName::IsEqual (UniqueName const & uname) const
{
if (GetParentId () == uname.GetParentId ())
{
std::string const & thisName = GetName ();
return IsFileNameEqual (thisName, uname.GetName ());
}
return false;
}
bool UniqueName::IsStrictlyEqual (UniqueName const & uname) const
{
if (GetParentId () == uname.GetParentId ())
{
std::string const & thisName = GetName ();
return IsCaseEqual (thisName, uname.GetName ());
}
return false;
}
bool UniqueName::IsNormalized () const
{
return FilePath::IsFileNameOnly (_name);
}
bool UniqueName::operator < (UniqueName const & uname) const
{
if (GetParentId () < uname.GetParentId ())
return true;
if (uname.GetParentId () < GetParentId ())
return false;
std::string const & thisName = GetName ();
return IsFileNameLess (thisName, uname.GetName ());
}
| 412 | 0.775478 | 1 | 0.775478 | game-dev | MEDIA | 0.353308 | game-dev | 0.841424 | 1 | 0.841424 |
PowerNukkitX/PowerNukkitX | 1,672 | src/main/java/cn/nukkit/block/BlockBoneBlock.java | package cn.nukkit.block;
import cn.nukkit.Player;
import cn.nukkit.block.property.CommonBlockProperties;
import cn.nukkit.item.Item;
import cn.nukkit.item.ItemTool;
import cn.nukkit.math.BlockFace;
import org.jetbrains.annotations.NotNull;
public class BlockBoneBlock extends BlockSolid{
public static final BlockProperties PROPERTIES = new BlockProperties(BONE_BLOCK, CommonBlockProperties.DEPRECATED, CommonBlockProperties.PILLAR_AXIS);
@Override
@NotNull public BlockProperties getProperties() {
return PROPERTIES;
}
public BlockBoneBlock() {
this(PROPERTIES.getDefaultState());
}
public BlockBoneBlock(BlockState blockstate) {
super(blockstate);
}
@Override
public double getHardness() {
return 2;
}
@Override
public double getResistance() {
return 10;
}
@Override
public int getToolType() {
return ItemTool.TYPE_PICKAXE;
}
@Override
public int getToolTier() {
return ItemTool.TIER_WOODEN;
}
@Override
public String getName() {
return "Bone Block";
}
@Override
public boolean place(@NotNull Item item, @NotNull Block block, @NotNull Block target, @NotNull BlockFace face, double fx, double fy, double fz, Player player) {
this.setPillarAxis(face.getAxis());
this.getLevel().setBlock(block, this, true);
return true;
}
public BlockFace.Axis getPillarAxis() {
return getPropertyValue(CommonBlockProperties.PILLAR_AXIS);
}
public void setPillarAxis(BlockFace.Axis axis) {
setPropertyValue(CommonBlockProperties.PILLAR_AXIS, axis);
}
} | 412 | 0.820533 | 1 | 0.820533 | game-dev | MEDIA | 0.97454 | game-dev | 0.762395 | 1 | 0.762395 |
naver/tamgu | 10,369 | lispe/include/jagrgx.h | /*
* LispE
*
* Copyright 2020-present NAVER Corp.
* The 3-Clause BSD License
*/
// jagrgx.h
//
//
#ifndef rgx_h
#define rgx_h
#include "vecter.h"
typedef enum{ an_epsilon=0, an_end=1, an_remove=2, an_negation=4, an_mandatory=8, an_error=12, an_rule=16, an_final=32, an_beginning=64, an_ending=128} an_flag;
typedef enum{aut_reg=1,aut_reg_plus,aut_reg_star,
aut_meta, aut_meta_plus, aut_meta_star,
aut_any,aut_any_plus,aut_any_star,
aut_ocrl_brk, aut_ccrl_brk, aut_ccrl_brk_plus, aut_ccrl_brk_star,
aut_obrk, aut_cbrk, aut_cbrk_plus, aut_cbrk_star,
aut_opar, aut_cpar, aut_negation
}
aut_actions;
//------------------------character automatons---------------------------------------------------
class Au_theautomaton;
class Au_theautomatons;
class Au_automate;
//-----------------------------------------------------------------------------------------------
class Au_state;
class Au_any {
public:
bool vero;
an_flag type;
Au_any(unsigned char t) {
type=(an_flag)t;
vero = true;
}
virtual bool same(Au_any* a) {
if (a->Type()==type && a->vero == vero)
return true;
return false;
}
an_flag Type() {
return type;
}
virtual char compare(wchar_t c) {
return vero;
}
void setvero(bool neg) {
vero = !neg;
}
};
class Au_char : public Au_any {
public:
wchar_t action;
Au_char(wchar_t a, unsigned char t) : Au_any(t) {
action=a;
}
bool same(Au_any* a) {
if (a->Type()==type && a->vero == vero && ((Au_char*)a)->action==action)
return true;
return false;
}
char compare(wchar_t c) {
if (action==c)
return vero;
return !vero;
}
};
class Au_epsilon : public Au_any {
public:
Au_epsilon() : Au_any(an_epsilon) {}
bool same(Au_any* a) {
if (a->Type()==an_epsilon && a->vero == vero)
return true;
return false;
}
char compare(wchar_t c) {
return 2;
}
};
class Au_meta : public Au_any {
public:
static utf8_handler* met;
wchar_t action;
Au_meta(uchar a, unsigned char t) : Au_any(t) {
action=a;
}
bool same(Au_any* a) {
if (a->Type()==type && a->vero == vero && ((Au_meta*)a)->action==action)
return true;
return false;
}
//CHSacdnprsx
char compare(wchar_t car) {
switch(action) {
case 'C':
if (met->c_is_upper(car))
return vero;
return !vero;
case 'S':
if (car <= 32 || car == 160)
return vero;
return !vero;
case 'a':
if (car=='_' || met->c_is_alpha(car))
return vero;
return !vero;
case 'c':
if (met->c_is_lower(car))
return vero;
return !vero;
case 'd':
if (c_is_digit(car))
return vero;
return !vero;
case 'e':
if (met->c_is_emoji(car))
return vero;
return !vero;
case 'E':
if (met->c_is_emojicomp(car))
return vero;
return !vero;
case 'n':
if (car == 160)
return vero;
return !vero;
case 'p':
if (met->c_is_punctuation(car))
return vero;
return !vero;
case 'r':
if (car == 10 || car == 13)
return vero;
return !vero;
case 's':
if (car == 9 || car == 32 || car == 160)
return vero;
return !vero;
case 'x': //hexadecimal character
if ((car>='A' && car <= 'F') || (car>='a' && car <= 'f') || (car >= '0' && car <= '9'))
return vero;
return !vero;
default:
if (action == car)
return vero;
return !vero;
}
}
};
class Au_arc {
public:
Au_any* action;
Au_state* state;
unsigned char mark;
Au_arc(Au_any* a) {
action=a;
state=NULL;
mark=false;
}
~Au_arc() {
delete action;
}
an_flag Type() {
return action->Type();
}
bool same(Au_arc* a) {
return action->same(a->action);
}
bool checkfinalepsilon();
bool find(wstring& w, wstring& sep, long i, vector<long>& res);
};
class Au_state {
public:
vecter<Au_arc*> arcs;
uchar status;
unsigned char mark;
Au_state() {
status=0;
mark=false;
}
void storerulearcs(unordered_map<long,bool>& rules);
virtual long idx() {return -1;}
bool isend() {
if ((status&an_end)==an_end)
return true;
return false;
}
void removeend() {
status &= ~an_end;
}
bool isfinal() {
if (arcs.last == 0)
return true;
if ((status&an_final)==an_final)
return true;
return false;
}
bool isrule() {
if ((status&an_rule)==an_rule)
return true;
return false;
}
bool match(wstring& w, long i);
bool find(wstring& w, wstring& sep, long i, vector<long>& res);
long loop(wstring& w, long i);
void removeepsilon();
void addrule(Au_arc*);
void merge(Au_state*);
Au_arc* build(Au_theautomatons* g, wstring& token, uchar type, Au_state* common, bool nega);
Au_state* build(Au_theautomatons* g, long i,vector<wstring>& tokens, vector<aut_actions>& types, Au_state* common);
};
class Au_state_final : public Au_state {
public:
long rule;
Au_state_final(long r) {
rule=r;
status=an_rule;
}
long idx() {return rule;}
};
class Au_theautomaton {
public:
Au_state* first;
Au_theautomaton() {
first=NULL;
}
Au_theautomaton(wstring rgx);
bool match(wstring& w);
bool search(wstring& w);
long find(wstring& w);
long find(wstring& w, long i);
bool search(wstring& w, long& first, long& last, long init = 0);
bool searchlast(wstring& w, long& first, long& last, long init = 0);
bool bytesearch(wstring& w, long& first, long& last);
void bytesearchall(wstring& w, vector<long>& res);
void searchall(wstring& w, vector<long>& res, long init = 0);
void find(wstring& w, wstring& sep, vector<long>& res);
virtual bool parse(wstring& rgx, Au_theautomatons* automatons=NULL);
};
class Au_theautomatons {
public:
vecter<Au_state*> states;
vecter<Au_arc*> arcs;
Au_state* state() {
Au_state* s=new Au_state;
states.push_back(s);
return s;
}
Au_state* statefinal(long r) {
Au_state_final* s=new Au_state_final(r);
states.push_back(s);
return s;
}
Au_arc* arc(Au_any* a, Au_state* s=NULL) {
Au_arc* ac=new Au_arc(a);
arcs.push_back(ac);
if (s==NULL)
ac->state=state();
else
ac->state=s;
return ac;
}
void clean() {
states.wipe();
arcs.wipe();
}
void clean(long s, long a) {
long i,ii;
//We delete the states marked for destruction...
for (i=s;i<states.size();i++) {
if (states.vecteur[i] != NULL && states.vecteur[i]->mark == an_remove) {
delete states.vecteur[i];
states.vecteur[i]=NULL;
}
}
//Compacting
//We remove the NULL...
for (i=s;i<states.size();i++) {
if (states.vecteur[i]==NULL) {
ii=i;
while (ii<states.last && states.vecteur[ii]==NULL) ii++;
if (ii==states.last) {
states.last=i;
break;
}
states.vecteur[i]=states.vecteur[ii];
states.vecteur[ii]=NULL;
}
}
//We delete the arcs marked for destruction...
for (i=a;i<arcs.size();i++) {
if (arcs.vecteur[i] != NULL && arcs.vecteur[i]->mark == an_remove) {
delete arcs.vecteur[i];
arcs.vecteur[i]=NULL;
}
}
//Compacting
//We remove the NULL...
for (i=a;i<arcs.size();i++) {
if (arcs.vecteur[i]==NULL) {
ii=i;
while (ii<arcs.last && arcs.vecteur[ii]==NULL) ii++;
if (ii==arcs.last) {
arcs.last=i;
break;
}
arcs.vecteur[i]=arcs.vecteur[ii];
arcs.vecteur[ii]=NULL;
}
}
}
void clearmarks() {
long i;
for (i=0;i<states.last;i++) {
if (states.vecteur[i]!=NULL)
states.vecteur[i]->mark=false;
}
for (i=0;i<arcs.last;i++) {
if (arcs.vecteur[i] != NULL)
arcs.vecteur[i]->mark=false;
}
}
void clear(long s, long a) {
long i;
for (i=s;i<states.last;i++) {
if (states.vecteur[i]!=NULL)
states.vecteur[i]->mark=false;
}
for (i=a;i<arcs.last;i++) {
if (arcs.vecteur[i] != NULL)
arcs.vecteur[i]->mark=false;
}
}
void boundaries(long& s, long& a) {
s=states.size();
a=arcs.size();
}
~Au_theautomatons() {
states.wipe();
arcs.wipe();
}
};
class Au_automate : public Au_theautomaton {
public:
Au_theautomatons garbage;
Au_automate() {
first=NULL;
}
Au_automate(wstring& rgx);
bool compile(wstring& rgx) {
return parse(rgx, &garbage);
}
bool compiling(wstring& rgx,long feature);
};
class Jag_theautomaton : public Au_automate {
public:
wstring regularexpression;
Jag_theautomaton(wstring& rgx) : Au_automate(rgx) {
regularexpression = rgx;
}
};
#endif
| 412 | 0.819697 | 1 | 0.819697 | game-dev | MEDIA | 0.317951 | game-dev | 0.959739 | 1 | 0.959739 |
liyunfan1223/mod-playerbots | 2,009 | src/strategy/values/SnareTargetValue.cpp | /*
* Copyright (C) 2016+ AzerothCore <www.azerothcore.org>, released under GNU AGPL v3 license, you may redistribute it
* and/or modify it under version 3 of the License, or (at your option), any later version.
*/
#include "SnareTargetValue.h"
#include "Playerbots.h"
#include "ServerFacade.h"
Unit* SnareTargetValue::Calculate()
{
std::string const spell = qualifier;
GuidVector attackers = botAI->GetAiObjectContext()->GetValue<GuidVector>("attackers")->Get();
Unit* target = botAI->GetAiObjectContext()->GetValue<Unit*>("current target")->Get();
for (ObjectGuid const guid : attackers)
{
Unit* unit = botAI->GetUnit(guid);
if (!unit)
continue;
if (bot->GetDistance(unit) > botAI->GetRange("spell"))
continue;
Unit* chaseTarget;
switch (unit->GetMotionMaster()->GetCurrentMovementGeneratorType())
{
case FLEEING_MOTION_TYPE:
return unit;
case CHASE_MOTION_TYPE:
{
chaseTarget = sServerFacade->GetChaseTarget(unit);
if (!chaseTarget)
continue;
Player* chaseTargetPlayer = ObjectAccessor::FindPlayer(chaseTarget->GetGUID());
// check if need to snare
bool shouldSnare = true;
// do not slow down if bot is melee and mob/bot attack each other
if (chaseTargetPlayer && !botAI->IsRanged(bot) && chaseTargetPlayer == bot)
shouldSnare = false;
if (!unit->isMoving())
shouldSnare = false;
if (unit->HasAuraType(SPELL_AURA_MOD_ROOT))
shouldSnare = false;
if (chaseTargetPlayer && shouldSnare && !botAI->IsTank(chaseTargetPlayer))
{
return unit;
}
break;
}
default:
break;
}
}
return nullptr;
}
| 412 | 0.954859 | 1 | 0.954859 | game-dev | MEDIA | 0.973052 | game-dev | 0.989307 | 1 | 0.989307 |
PaperMC/Paper | 8,575 | paper-api/src/main/java/org/bukkit/entity/AbstractArrow.java | package org.bukkit.entity;
import java.util.List;
import org.bukkit.block.Block;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.Unmodifiable;
/**
* Represents an arrow.
*/
public interface AbstractArrow extends Projectile {
/**
* Gets the knockback strength for an arrow, which is the
* {@link org.bukkit.enchantments.Enchantment#KNOCKBACK KnockBack} level
* of the bow that shot it.
*
* @return the knockback strength value
* @see #getWeapon()
* @deprecated moved to being a function of the firing weapon, always returns 0 here
*/
@Deprecated(since = "1.21", forRemoval = true)
public int getKnockbackStrength();
/**
* Sets the knockback strength for an arrow.
*
* @param knockbackStrength the knockback strength value
* @see #setWeapon(org.bukkit.inventory.ItemStack)
* @deprecated moved to being a function of the firing weapon, does nothing here
*/
@Deprecated(since = "1.21", forRemoval = true)
public void setKnockbackStrength(int knockbackStrength);
/**
* Gets the base amount of damage this arrow will do.
*
* Defaults to 2.0 for a normal arrow with
* <code>0.5 * (1 + power level)</code> added for arrows fired from
* enchanted bows.
*
* @return base damage amount
*/
public double getDamage();
/**
* Sets the base amount of damage this arrow will do.
*
* @param damage new damage amount
*/
public void setDamage(double damage);
/**
* Gets the number of times this arrow can pierce through an entity.
*
* @return pierce level
*/
public int getPierceLevel();
/**
* Sets the number of times this arrow can pierce through an entity.
*
* Must be between 0 and 127 times.
*
* @param pierceLevel new pierce level
*/
public void setPierceLevel(int pierceLevel);
/**
* Gets whether this arrow is critical.
* <p>
* Critical arrows have increased damage and cause particle effects.
* <p>
* Critical arrows generally occur when a player fully draws a bow before
* firing.
*
* @return true if it is critical
*/
public boolean isCritical();
/**
* Sets whether or not this arrow should be critical.
*
* @param critical whether or not it should be critical
*/
public void setCritical(boolean critical);
/**
* Gets whether this arrow is in a block or not.
* <p>
* Arrows in a block are motionless and may be picked up by players.
*
* @return true if in a block
*/
public boolean isInBlock();
/**
* Gets the block to which this arrow is attached.
*
* @return the attached block or null if not attached
* @deprecated can be attached to multiple blocks use {@link AbstractArrow#getAttachedBlocks()} instead
*/
@Nullable
@Deprecated(since = "1.21.4")
public Block getAttachedBlock();
/**
* Gets the block(s) which this arrow is attached to.
* All the returned blocks are responsible for preventing
* the arrow from falling.
*
* @return the attached block(s) or an empty list if not attached
*/
@NotNull
@Unmodifiable
List<Block> getAttachedBlocks();
/**
* Gets the current pickup status of this arrow.
*
* @return the pickup status of this arrow.
*/
@NotNull
public PickupStatus getPickupStatus();
/**
* Sets the current pickup status of this arrow.
*
* @param status new pickup status of this arrow.
*/
public void setPickupStatus(@NotNull PickupStatus status);
/**
* Gets if this arrow was shot from a crossbow.
*
* @return if shot from a crossbow
*/
public boolean isShotFromCrossbow();
/**
* Sets if this arrow was shot from a crossbow.
*
* @param shotFromCrossbow if shot from a crossbow
* @see #setWeapon(org.bukkit.inventory.ItemStack)
* @deprecated a function of the firing weapon instead, this method does nothing
*/
@Deprecated(since = "1.21", forRemoval = true)
public void setShotFromCrossbow(boolean shotFromCrossbow);
/**
* Gets the ItemStack which will be picked up from this arrow.
*
* @return The picked up ItemStack
* @deprecated use {@link #getItemStack()}
*/
@NotNull
@Deprecated(forRemoval = true, since = "1.20.4") // Paper
public ItemStack getItem();
/**
* Sets the ItemStack which will be picked up from this arrow.
*
* @param item ItemStack set to be picked up
* @deprecated use {@link #setItemStack(ItemStack)}
*/
@Deprecated(forRemoval = true, since = "1.20.4") // Paper
public void setItem(@NotNull ItemStack item);
/**
* Gets the ItemStack which fired this arrow.
*
* @return The firing ItemStack
*/
@Nullable // Paper
public ItemStack getWeapon();
/**
* Sets the ItemStack which fired this arrow.
*
* @param item The firing ItemStack
*/
public void setWeapon(@NotNull ItemStack item);
/**
* Represents the pickup status of this arrow.
*/
public enum PickupStatus {
/**
* The arrow cannot be picked up.
*/
DISALLOWED,
/**
* The arrow can be picked up.
*/
ALLOWED,
/**
* The arrow can only be picked up by players in creative mode.
*/
CREATIVE_ONLY
}
// Paper start
/**
* Gets the {@link PickupRule} for this arrow.
*
* <p>This is generally {@link PickupRule#ALLOWED} only if the arrow was
* <b>not</b> fired from a bow with the infinity enchantment.</p>
*
* @return The pickup rule
* @deprecated Use {@link Arrow#getPickupStatus()} as an upstream compatible replacement for this function
*/
@Deprecated
default PickupRule getPickupRule() {
return PickupRule.valueOf(this.getPickupStatus().name());
}
/**
* Set the rule for which players can pickup this arrow as an item.
*
* @param rule The pickup rule
* @deprecated Use {@link Arrow#setPickupStatus(PickupStatus)} with {@link PickupStatus} as an upstream compatible replacement for this function
*/
@Deprecated
default void setPickupRule(PickupRule rule) {
this.setPickupStatus(PickupStatus.valueOf(rule.name()));
}
@Deprecated
enum PickupRule {
DISALLOWED,
ALLOWED,
CREATIVE_ONLY;
}
// Paper end
// Paper start - more projectile API
/**
* Gets the {@link ItemStack} for this arrow. This stack is used
* for both visuals on the arrow and the stack that could be picked up.
*
* @return The ItemStack, as if a player picked up the arrow
*/
@NotNull ItemStack getItemStack();
/**
* Sets the {@link ItemStack} for this arrow. This stack is used for both
* visuals on the arrow and the stack that could be picked up.
*
* @param stack the arrow stack
*/
void setItemStack(@NotNull ItemStack stack);
/**
* Sets the amount of ticks this arrow has been alive in the world
* This is used to determine when the arrow should be automatically despawned.
*
* @param ticks lifetime ticks
*/
void setLifetimeTicks(int ticks);
/**
* Gets how many ticks this arrow has been in the world for.
*
* @return ticks this arrow has been in the world
*/
int getLifetimeTicks();
/**
* Gets the sound that is played when this arrow hits an entity.
*
* @return sound that plays
*/
@NotNull
org.bukkit.Sound getHitSound();
/**
* Sets the sound that is played when this arrow hits an entity.
*
* @param sound sound that is played
*/
void setHitSound(@NotNull org.bukkit.Sound sound);
// Paper end - more projectile API
// Paper start - Fix PickupStatus getting reset
/**
* Set the shooter of this projectile.
*
* @param source the {@link org.bukkit.projectiles.ProjectileSource} that shot this projectile
* @param resetPickupStatus whether the {@link org.bukkit.entity.AbstractArrow.PickupStatus} should be reset
*/
void setShooter(@Nullable org.bukkit.projectiles.ProjectileSource source, boolean resetPickupStatus);
// Paper end - Fix PickupStatus getting reset
}
| 412 | 0.890297 | 1 | 0.890297 | game-dev | MEDIA | 0.840844 | game-dev | 0.980605 | 1 | 0.980605 |
GalaxyCr8r/solarance-beginnings | 7,935 | server/src/types/sectors.rs | use spacetimedb::{table, ReducerContext, SpacetimeType};
use spacetimedsl::{dsl, Wrapper};
use crate::types::{common, factions::*, jumpgates::reducers::*};
pub mod definitions; // Definitions for initial ingested data.
pub mod impls; // Impls for this file's structs
pub mod reducers; // SpacetimeDB Reducers for this file's structs.
//pub mod rls; // Row-level-security rules for this file's structs.
pub mod timers; // Timers related to this file's structs.
pub mod utility; // Utility functions (NOT reducers) for this file's structs.
#[derive(SpacetimeType, Debug, Clone, PartialEq, Eq)]
pub enum SpectralKind {
/// Hottest, brightest, and bluest stars.
O,
/// Blue-white Stars
B,
/// White Stars
A,
/// Yellow-white Stars
F,
/// Yellow Stars (Sol)
G,
/// Orange Stars
K,
/// Coolest, dimmest, and reddest stars.
M,
}
#[derive(SpacetimeType, Debug, Clone, PartialEq, Eq)]
pub enum StarSystemObjectKind {
Star,
Planet,
Moon,
AsteroidBelt,
NebulaBelt,
}
#[dsl(plural_name = star_systems)]
#[table(name = star_system, public)]
pub struct StarSystem {
#[primary_key]
#[auto_inc]
#[create_wrapper]
#[referenced_by(path = crate::types::sectors, table = star_system_object)]
#[referenced_by(path = crate::types::sectors, table = sector)]
id: u32,
#[unique]
pub name: String, // e.g., "Sol", "Alpha Centauri"
pub map_coordinates: common::Vec2, // Coordinates on the galactic map
pub spectral: SpectralKind,
/// 0, Hypergiants ... 5, Main sequence (Sol) ... 7, White dwarfs
pub luminosity: u8,
#[index(btree)]
#[use_wrapper(path = FactionId)]
#[foreign_key(path = crate::types::factions, table = faction, column = id, on_delete = Error)]
/// FK to Faction, can change
pub controlling_faction_id: u32,
//pub discovered_by_faction_id: Option<u32>, // First faction to chart it
}
#[dsl(plural_name = star_system_objects)]
#[table(name = star_system_object, public)]
pub struct StarSystemObject {
#[primary_key]
#[auto_inc]
#[create_wrapper]
id: u32,
#[index(btree)]
#[use_wrapper(path = StarSystemId)]
#[foreign_key(path = crate::types::sectors, table = star_system, column = id, on_delete = Delete)]
/// FK to StarSystem
pub system_id: u32,
pub kind: StarSystemObjectKind,
/// Object's star system position
pub orbit_au: f32,
/// Either the rotation in the orbit in radians, or the kilometers wide for asteroid/nebula belts.
pub rotation_or_width_km: f32,
pub gfx_key: Option<String>, // Key for client to look up image
}
#[dsl(plural_name = sectors)]
#[table(name = sector, public)]
pub struct Sector {
#[primary_key] // NOT Auto-inc so it can be reloaded as-is
#[create_wrapper]
#[referenced_by(path = crate::types::sectors, table = asteroid_sector)]
#[referenced_by(path = crate::types::stellarobjects, table = stellar_object)]
#[referenced_by(path = crate::types::asteroids, table = asteroid)]
#[referenced_by(path = crate::types::ships, table = ship)]
#[referenced_by(path = crate::types::stations, table = station)]
#[referenced_by(path = crate::types::jumpgates, table = jump_gate)]
#[referenced_by(path = crate::types::chats, table = sector_chat_message)]
#[referenced_by(path = crate::types::items, table = cargo_crate)]
id: u64,
#[index(btree)]
#[use_wrapper(path = StarSystemId)]
#[foreign_key(path = crate::types::sectors, table = star_system, column = id, on_delete = Error)]
/// FK to StarSystem
pub system_id: u32,
pub name: String,
pub description: Option<String>,
#[index(btree)]
#[use_wrapper(path = FactionId)]
#[foreign_key(path = crate::types::factions, table = faction, column = id, on_delete = Error)]
/// FK to Faction, can change
pub controlling_faction_id: u32,
/// 0 (lawless) to 10 (heavily policed)
/// Depends on the adjecency a faction Garrison station
pub security_level: u8,
// Sector Potentials
/// How much sunlight the current sector has.
/// From 1.0 being in orbit around the sun, to 0.0 being outside a solar system.
/// Most sectors will have 0.9 - 0.5 depending on how far from the center of the solar system it is.
/// Solar power plants want to be in sectors of 0.5+
pub sunlight: f32,
/// How much weird stuff the current sector has going on.
/// From 1.0 being inside the middle of eye of chaos, to 0.0 being a normal solar system.
/// Most sectors will have 0.0 - 0.1, research stations want to be in sectors of 0.5+
pub anomalous: f32,
/// How much gas/dust the current sector has.
/// From 1.0 being so thick you can't use your sensors, to 0.0 being a clear space.
/// Most sectors will have 0.0 - 0.1, pirate stations want to be in sectors of 0.5+
pub nebula: f32,
/// How likely rare ore is to appear in the current sector.
/// From 1.0 being ONLY rare ore, to 0.0 being only iron.
/// Most sectors will have 0.0 - 0.1, refinery stations want to be in sectors of 0.5+
pub rare_ore: f32,
// Sector's star system position
pub x: f32,
pub y: f32,
pub background_gfx_key: Option<String>, // Key for client to look up background image
}
#[dsl(plural_name = asteroid_sectors)]
#[table(name = asteroid_sector)]
pub struct AsteroidSector {
#[primary_key] // NOT Auto-inc so it can be reloaded as-is
#[use_wrapper(path = SectorId)]
#[foreign_key(path = crate::types::sectors, table = sector, column = id, on_delete = Delete)]
id: u64,
pub sparseness: u8, // Relative amount of asteroids to spawn
pub rarity: u8, // Skews the amount of spawned asteroids with high rarity ores
pub cluster_extent: f32, // How far from 0,0 can asteroids spawn
pub cluster_inner: Option<f32>, // How far from 0,0 can asteroids NOT spawn
}
//////////////////////////////////////////////////////////////
// Impls
//////////////////////////////////////////////////////////////
impl Sector {
pub fn get(ctx: &ReducerContext, id: &SectorId) -> Result<Sector, String> {
Ok(dsl(ctx).get_sector_by_id(id)?)
}
}
//////////////////////////////////////////////////////////////
// Init
//////////////////////////////////////////////////////////////
pub fn init(ctx: &ReducerContext) -> Result<(), String> {
timers::init(ctx)?;
definitions::init(ctx)?;
Ok(())
}
//////////////////////////////////////////////////////////////
// Utilities
//////////////////////////////////////////////////////////////
/// Creates a jumpgate in each sector, using the direction of the each other sector's position
fn connect_sectors_with_warpgates(
ctx: &ReducerContext,
a: &Sector,
b: &Sector,
) -> Result<(), String> {
let a_pos = glam::Vec2::new(a.x, a.y);
let b_pos = glam::Vec2::new(b.x, b.y);
//info!("Sector Positions: A{} B{}", a_pos, b_pos);
let a_angle = (b_pos - a_pos).to_angle();
let b_angle = (a_pos - b_pos).to_angle();
//info!("Sector Angles: A{} B{}", a_angle, b_angle);
let a_wp_pos = glam::Vec2::from_angle(a_angle) * 5000.0;
let b_wp_pos = glam::Vec2::from_angle(b_angle) * 5000.0;
//info!("Sector WP Pos: A{} B{}", a_wp_pos, b_wp_pos);
create_jumpgate_in_sector(
ctx, a.id, a_wp_pos.x, a_wp_pos.y, b.id, b_wp_pos.x, b_wp_pos.y,
)?;
create_jumpgate_in_sector(
ctx, b.id, b_wp_pos.x, b_wp_pos.y, a.id, a_wp_pos.x, a_wp_pos.y,
)?;
Ok(())
}
/// For jumpdrive-enabled ships, calculates the incoming vector the ship should be entering from.
pub fn get_entrance_angle(departing: &Sector, destination: &Sector) -> f32 {
let a_pos = glam::Vec2::new(departing.x, departing.y);
let b_pos = glam::Vec2::new(destination.x, destination.y);
// Destination entrance angle
(a_pos - b_pos).to_angle()
}
| 412 | 0.706544 | 1 | 0.706544 | game-dev | MEDIA | 0.252449 | game-dev | 0.59827 | 1 | 0.59827 |
rheit/zdoom | 174,070 | src/p_actionfunctions.cpp | /*
** thingdef_codeptr.cpp
**
** Code pointers for Actor definitions
**
**---------------------------------------------------------------------------
** Copyright 2002-2006 Christoph Oelckers
** Copyright 2004-2006 Randy Heit
** 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. The name of the author may not be used to endorse or promote products
** derived from this software without specific prior written permission.
** 4. When not used as part of ZDoom or a ZDoom derivative, this code will be
** covered by 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 SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
** IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
** OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
** IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
** INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
** NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
** THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**---------------------------------------------------------------------------
**
*/
#include "gi.h"
#include "g_level.h"
#include "actor.h"
#include "info.h"
#include "sc_man.h"
#include "tarray.h"
#include "w_wad.h"
#include "templates.h"
#include "r_defs.h"
#include "a_pickups.h"
#include "s_sound.h"
#include "cmdlib.h"
#include "p_lnspec.h"
#include "p_effect.h"
#include "p_enemy.h"
#include "decallib.h"
#include "m_random.h"
#include "i_system.h"
#include "p_local.h"
#include "c_console.h"
#include "doomerrors.h"
#include "a_sharedglobal.h"
#include "v_video.h"
#include "v_font.h"
#include "doomstat.h"
#include "v_palette.h"
#include "g_shared/a_specialspot.h"
#include "actorptrselect.h"
#include "m_bbox.h"
#include "r_data/r_translate.h"
#include "p_trace.h"
#include "p_setup.h"
#include "gstrings.h"
#include "d_player.h"
#include "p_maputl.h"
#include "p_spec.h"
#include "templates.h"
#include "v_text.h"
#include "thingdef.h"
#include "math/cmath.h"
#include "a_armor.h"
#include "a_health.h"
AActor *SingleActorFromTID(int tid, AActor *defactor);
static FRandom pr_camissile ("CustomActorfire");
static FRandom pr_camelee ("CustomMelee");
static FRandom pr_cabullet ("CustomBullet");
static FRandom pr_cajump ("CustomJump");
static FRandom pr_cwbullet ("CustomWpBullet");
static FRandom pr_cwjump ("CustomWpJump");
static FRandom pr_cwpunch ("CustomWpPunch");
static FRandom pr_grenade ("ThrowGrenade");
static FRandom pr_crailgun ("CustomRailgun");
static FRandom pr_spawndebris ("SpawnDebris");
static FRandom pr_spawnitemex ("SpawnItemEx");
static FRandom pr_burst ("Burst");
static FRandom pr_monsterrefire ("MonsterRefire");
static FRandom pr_teleport("A_Teleport");
static FRandom pr_bfgselfdamage("BFGSelfDamage");
//==========================================================================
//
// ACustomInventory :: CallStateChain
//
// Executes the code pointers in a chain of states
// until there is no next state
//
//==========================================================================
bool ACustomInventory::CallStateChain (AActor *actor, FState *state)
{
INTBOOL result = false;
int counter = 0;
VMValue params[3] = { actor, this, 0 };
// We accept return types of `state`, `(int|bool)` or `state, (int|bool)`.
// The last one is for the benefit of A_Warp and A_Teleport.
int retval, numret;
FState *nextstate;
VMReturn ret[2];
ret[0].PointerAt((void **)&nextstate);
ret[1].IntAt(&retval);
FState *savedstate = this->state;
while (state != NULL)
{
if (!(state->UseFlags & SUF_ITEM))
{
auto so = FState::StaticFindStateOwner(state);
Printf(TEXTCOLOR_RED "State %s.%d not flagged for use in CustomInventory state chains.\n", so->TypeName.GetChars(), int(state - so->OwnedStates));
return false;
}
this->state = state;
nextstate = NULL; // assume no jump
if (state->ActionFunc != NULL)
{
if (state->ActionFunc->Unsafe)
{
// If an unsafe function (i.e. one that accesses user variables) is being detected, print a warning once and remove the bogus function. We may not call it because that would inevitably crash.
auto owner = FState::StaticFindStateOwner(state);
Printf(TEXTCOLOR_RED "Unsafe state call in state %s.%d to %s which accesses user variables. The action function has been removed from this state\n",
owner->TypeName.GetChars(), int(state - owner->OwnedStates), state->ActionFunc->PrintableName.GetChars());
state->ActionFunc = nullptr;
}
PPrototype *proto = state->ActionFunc->Proto;
VMReturn *wantret;
FStateParamInfo stp = { state, STATE_StateChain, PSP_WEAPON };
params[2] = VMValue(&stp, ATAG_GENERIC);
retval = true; // assume success
wantret = NULL; // assume no return value wanted
numret = 0;
// For functions that return nothing (or return some type
// we don't care about), we pretend they return true,
// thanks to the values set just above.
if (proto->ReturnTypes.Size() == 1)
{
if (proto->ReturnTypes[0] == TypeState)
{ // Function returns a state
wantret = &ret[0];
retval = false; // this is a jump function which never affects the success state.
}
else if (proto->ReturnTypes[0] == TypeSInt32 || proto->ReturnTypes[0] == TypeBool)
{ // Function returns an int or bool
wantret = &ret[1];
}
numret = 1;
}
else if (proto->ReturnTypes.Size() == 2)
{
if (proto->ReturnTypes[0] == TypeState &&
(proto->ReturnTypes[1] == TypeSInt32 || proto->ReturnTypes[1] == TypeBool))
{ // Function returns a state and an int or bool
wantret = &ret[0];
numret = 2;
}
}
try
{
GlobalVMStack.Call(state->ActionFunc, params, state->ActionFunc->ImplicitArgs, wantret, numret);
}
catch (CVMAbortException &err)
{
err.MaybePrintMessage();
auto owner = FState::StaticFindStateOwner(state);
int offs = int(state - owner->OwnedStates);
err.stacktrace.AppendFormat("Called from state %s.%d in inventory state chain in %s\n", owner->TypeName.GetChars(), offs, GetClass()->TypeName.GetChars());
throw;
}
// As long as even one state succeeds, the whole chain succeeds unless aborted below.
// A state that wants to jump does not count as "succeeded".
if (nextstate == NULL)
{
result |= retval;
}
}
// Since there are no delays it is a good idea to check for infinite loops here!
counter++;
if (counter >= 10000) break;
if (nextstate == NULL)
{
nextstate = state->GetNextState();
if (state == nextstate)
{ // Abort immediately if the state jumps to itself!
result = false;
break;
}
}
state = nextstate;
}
this->state = savedstate;
return !!result;
}
//==========================================================================
//
// GetPointer
//
// resolve AAPTR_*
//
//==========================================================================
DEFINE_ACTION_FUNCTION(AActor, GetPointer)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_INT(ptr);
ACTION_RETURN_OBJECT(COPY_AAPTR(self, ptr));
}
//==========================================================================
//
// CheckClass
//
// NON-ACTION function to check a pointer's class.
//
//==========================================================================
DEFINE_ACTION_FUNCTION(AActor, CheckClass)
{
if (numret > 0)
{
assert(ret != NULL);
PARAM_SELF_PROLOGUE(AActor);
PARAM_CLASS (checktype, AActor);
PARAM_INT_DEF (pick_pointer);
PARAM_BOOL_DEF (match_superclass);
self = COPY_AAPTR(self, pick_pointer);
if (self == nullptr || checktype == nullptr)
{
ret->SetInt(false);
}
else if (match_superclass)
{
ret->SetInt(self->IsKindOf(checktype));
}
else
{
ret->SetInt(self->GetClass() == checktype);
}
return 1;
}
return 0;
}
//==========================================================================
//
// CheckClass
//
// NON-ACTION function to calculate missile damage for the given actor
//
//==========================================================================
DEFINE_ACTION_FUNCTION(AActor, GetMissileDamage)
{
if (numret > 0)
{
assert(ret != NULL);
PARAM_SELF_PROLOGUE(AActor);
PARAM_INT(mask);
PARAM_INT(add);
PARAM_INT_DEF(pick_pointer);
self = COPY_AAPTR(self, pick_pointer);
if (self == NULL)
{
ret->SetInt(0);
}
else
{
ret->SetInt(self->GetMissileDamage(mask, add));
}
return 1;
}
return 0;
}
//==========================================================================
//
// CountInv
//
// NON-ACTION function to return the inventory count of an item.
//
//==========================================================================
DEFINE_ACTION_FUNCTION(AActor, CountInv)
{
if (numret > 0)
{
assert(ret != NULL);
PARAM_SELF_PROLOGUE(AActor);
PARAM_CLASS(itemtype, AInventory);
PARAM_INT_DEF(pick_pointer);
self = COPY_AAPTR(self, pick_pointer);
if (self == NULL || itemtype == NULL)
{
ret->SetInt(0);
}
else
{
AInventory *item = self->FindInventory(itemtype);
ret->SetInt(item ? item->Amount : 0);
}
return 1;
}
return 0;
}
//==========================================================================
//
// GetDistance
//
// NON-ACTION function to get the distance in double.
//
//==========================================================================
DEFINE_ACTION_FUNCTION(AActor, GetDistance)
{
if (numret > 0)
{
assert(ret != NULL);
PARAM_SELF_PROLOGUE(AActor);
PARAM_BOOL(checkz);
PARAM_INT_DEF(ptr);
AActor *target = COPY_AAPTR(self, ptr);
if (!target || target == self)
{
ret->SetFloat(0);
}
else
{
DVector3 diff = self->Vec3To(target);
if (checkz)
diff.Z += (target->Height - self->Height) / 2;
else
diff.Z = 0.;
ret->SetFloat(diff.Length());
}
return 1;
}
return 0;
}
//==========================================================================
//
// GetAngle
//
// NON-ACTION function to get the angle in degrees (normalized to -180..180)
//
//==========================================================================
enum GAFlags
{
GAF_RELATIVE = 1,
GAF_SWITCH = 1 << 1,
};
DEFINE_ACTION_FUNCTION(AActor, GetAngle)
{
if (numret > 0)
{
assert(ret != NULL);
PARAM_SELF_PROLOGUE(AActor);
PARAM_INT(flags);
PARAM_INT_DEF(ptr)
AActor *target = COPY_AAPTR(self, ptr);
if (!target || target == self)
{
ret->SetFloat(0);
}
else
{
DVector3 diff = (flags & GAF_SWITCH) ? target->Vec3To(self) : self->Vec3To(target);
DAngle angto = diff.Angle();
DAngle yaw = (flags & GAF_SWITCH) ? target->Angles.Yaw : self->Angles.Yaw;
if (flags & GAF_RELATIVE) angto = deltaangle(yaw, angto);
ret->SetFloat(angto.Degrees);
}
return 1;
}
return 0;
}
//==========================================================================
//
// GetSpawnHealth
//
//==========================================================================
DEFINE_ACTION_FUNCTION(AActor, GetSpawnHealth)
{
if (numret > 0)
{
PARAM_SELF_PROLOGUE(AActor);
ret->SetInt(self->SpawnHealth());
return 1;
}
return 0;
}
//==========================================================================
//
// GetGibHealth
//
//==========================================================================
DEFINE_ACTION_FUNCTION(AActor, GetGibHealth)
{
if (numret > 0)
{
PARAM_SELF_PROLOGUE(AActor);
ret->SetInt(self->GetGibHealth());
return 1;
}
return 0;
}
//==========================================================================
//
// GetSpriteAngle
//
// NON-ACTION function returns the sprite angle of a pointer.
//==========================================================================
DEFINE_ACTION_FUNCTION(AActor, GetSpriteAngle)
{
if (numret > 0)
{
assert(ret != NULL);
PARAM_SELF_PROLOGUE(AActor);
PARAM_INT_DEF(ptr);
AActor *target = COPY_AAPTR(self, ptr);
if (target == nullptr)
{
ret->SetFloat(0.0);
}
else
{
const double ang = target->SpriteAngle.Degrees;
ret->SetFloat(ang);
}
return 1;
}
return 0;
}
//==========================================================================
//
// GetSpriteRotation
//
// NON-ACTION function returns the sprite rotation of a pointer.
//==========================================================================
DEFINE_ACTION_FUNCTION(AActor, GetSpriteRotation)
{
if (numret > 0)
{
assert(ret != NULL);
PARAM_SELF_PROLOGUE(AActor);
PARAM_INT_DEF(ptr);
AActor *target = COPY_AAPTR(self, ptr);
if (target == nullptr)
{
ret->SetFloat(0.0);
}
else
{
const double ang = target->SpriteRotation.Degrees;
ret->SetFloat(ang);
}
return 1;
}
return 0;
}
//==========================================================================
//
// GetZAt
//
// NON-ACTION function to get the floor or ceiling z at (x, y) with
// relativity being an option.
//==========================================================================
enum GZFlags
{
GZF_ABSOLUTEPOS = 1, // Use the absolute position instead of an offsetted one.
GZF_ABSOLUTEANG = 1 << 1, // Don't add the actor's angle to the parameter.
GZF_CEILING = 1 << 2, // Check the ceiling instead of the floor.
GZF_3DRESTRICT = 1 << 3, // Ignore midtextures and 3D floors above the pointer's z.
GZF_NOPORTALS = 1 << 4, // Don't pass through any portals.
GZF_NO3DFLOOR = 1 << 5, // Pass all 3D floors.
};
DEFINE_ACTION_FUNCTION(AActor, GetZAt)
{
if (numret > 0)
{
assert(ret != NULL);
PARAM_SELF_PROLOGUE(AActor);
PARAM_FLOAT_DEF(px);
PARAM_FLOAT_DEF(py);
PARAM_ANGLE_DEF(angle);
PARAM_INT_DEF(flags);
PARAM_INT_DEF(pick_pointer);
AActor *mobj = COPY_AAPTR(self, pick_pointer);
if (mobj == nullptr)
{
ret->SetFloat(0);
}
else
{
// [MC] At any time, the NextLowest/Highest functions could be changed to include
// more FFC flags to check. Don't risk it by just passing flags straight to it.
DVector2 pos = { px, py };
double z = 0.;
int pflags = (flags & GZF_3DRESTRICT) ? FFCF_3DRESTRICT : 0;
if (flags & GZF_NOPORTALS) pflags |= FFCF_NOPORTALS;
if (!(flags & GZF_ABSOLUTEPOS))
{
if (!(flags & GZF_ABSOLUTEANG))
{
angle += mobj->Angles.Yaw;
}
double s = angle.Sin();
double c = angle.Cos();
pos = mobj->Vec2Offset(pos.X * c + pos.Y * s, pos.X * s - pos.Y * c);
}
sector_t *sec = P_PointInSector(pos);
if (sec)
{
if (flags & GZF_CEILING)
{
if ((flags & GZF_NO3DFLOOR) && (flags & GZF_NOPORTALS))
{
z = sec->ceilingplane.ZatPoint(pos);
}
else if (flags & GZF_NO3DFLOOR)
{
z = sec->HighestCeilingAt(pos);
}
else
{ // [MC] Handle strict 3D floors and portal toggling via the flags passed to it.
z = sec->NextHighestCeilingAt(pos.X, pos.Y, mobj->Z(), mobj->Top(), pflags);
}
}
else
{
if ((flags & GZF_NO3DFLOOR) && (flags & GZF_NOPORTALS))
{
z = sec->floorplane.ZatPoint(pos);
}
else if (flags & GZF_NO3DFLOOR)
{
z = sec->LowestFloorAt(pos);
}
else
{
z = sec->NextLowestFloorAt(pos.X, pos.Y, mobj->Z(), pflags, mobj->MaxStepHeight);
}
}
}
ret->SetFloat(z);
return 1;
}
}
return 0;
}
//==========================================================================
//
// GetCrouchFactor
//
// NON-ACTION function to retrieve a player's crouching factor.
//
//==========================================================================
DEFINE_ACTION_FUNCTION(AActor, GetCrouchFactor)
{
if (numret > 0)
{
assert(ret != NULL);
PARAM_SELF_PROLOGUE(AActor);
PARAM_INT_DEF(ptr);
AActor *mobj = COPY_AAPTR(self, ptr);
if (!mobj || !mobj->player)
{
ret->SetFloat(1);
}
else
{
ret->SetFloat(mobj->player->crouchfactor);
}
return 1;
}
return 0;
}
//==========================================================================
//
// GetCVar
//
// NON-ACTION function that works like ACS's GetCVar.
//
//==========================================================================
DEFINE_ACTION_FUNCTION(AActor, GetCVar)
{
if (numret > 0)
{
assert(ret != nullptr);
PARAM_SELF_PROLOGUE(AActor);
PARAM_STRING(cvarname);
FBaseCVar *cvar = GetCVar(self, cvarname);
if (cvar == nullptr)
{
ret->SetFloat(0);
}
else
{
ret->SetFloat(cvar->GetGenericRep(CVAR_Float).Float);
}
return 1;
}
return 0;
}
//==========================================================================
//
// GetPlayerInput
//
// NON-ACTION function that works like ACS's GetPlayerInput.
// Takes a pointer as anyone may or may not be a player.
//==========================================================================
DEFINE_ACTION_FUNCTION(AActor, GetPlayerInput)
{
if (numret > 0)
{
assert(ret != nullptr);
PARAM_SELF_PROLOGUE(AActor);
PARAM_INT (inputnum);
PARAM_INT_DEF(ptr);
AActor *mobj = COPY_AAPTR(self, ptr);
//Need a player.
if (!mobj || !mobj->player)
{
ret->SetInt(0);
}
else
{
ret->SetInt(P_Thing_CheckInputNum(mobj->player, inputnum));
}
return 1;
}
return 0;
}
//==========================================================================
//
// CountProximity
//
// NON-ACTION function of A_CheckProximity that returns how much it counts.
// Takes a pointer as anyone may or may not be a player.
//==========================================================================
DEFINE_ACTION_FUNCTION(AActor, CountProximity)
{
if (numret > 0)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_CLASS(classname, AActor);
PARAM_FLOAT(distance);
PARAM_INT_DEF(flags);
PARAM_INT_DEF(ptr);
AActor *mobj = COPY_AAPTR(self, ptr);
if (mobj == nullptr)
{
ret->SetInt(0);
}
else
{
ret->SetInt(P_Thing_CheckProximity(self, classname, distance, 0, flags, ptr, true));
}
return 1;
}
return 0;
}
//===========================================================================
//
// __decorate_internal_int__
// __decorate_internal_bool__
// __decorate_internal_float__
//
// Placeholders for forcing DECORATE to cast numbers. If actually called,
// returns whatever was passed.
//
//===========================================================================
DEFINE_ACTION_FUNCTION(AActor, __decorate_internal_int__)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_INT(returnme);
ACTION_RETURN_INT(returnme);
}
DEFINE_ACTION_FUNCTION(AActor, __decorate_internal_bool__)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_BOOL(returnme);
ACTION_RETURN_BOOL(returnme);
}
DEFINE_ACTION_FUNCTION(AActor, __decorate_internal_float__)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_FLOAT(returnme);
if (numret > 0)
{
ret->SetFloat(returnme);
return 1;
}
return 0;
}
//==========================================================================
//
// A_RearrangePointers
//
// Allow an actor to change its relationship to other actors by
// copying pointers freely between TARGET MASTER and TRACER.
// Can also assign null value, but does not duplicate A_ClearTarget.
//
//==========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_RearrangePointers)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_INT (ptr_target);
PARAM_INT_DEF (ptr_master);
PARAM_INT_DEF (ptr_tracer);
PARAM_INT_DEF (flags);
// Rearrange pointers internally
// Fetch all values before modification, so that all fields can get original values
AActor
*gettarget = self->target,
*getmaster = self->master,
*gettracer = self->tracer;
switch (ptr_target) // pick the new target
{
case AAPTR_MASTER:
self->target = getmaster;
if (!(PTROP_UNSAFETARGET & flags)) VerifyTargetChain(self);
break;
case AAPTR_TRACER:
self->target = gettracer;
if (!(PTROP_UNSAFETARGET & flags)) VerifyTargetChain(self);
break;
case AAPTR_NULL:
self->target = NULL;
// THIS IS NOT "A_ClearTarget", so no other targeting info is removed
break;
}
// presently permitting non-monsters to set master
switch (ptr_master) // pick the new master
{
case AAPTR_TARGET:
self->master = gettarget;
if (!(PTROP_UNSAFEMASTER & flags)) VerifyMasterChain(self);
break;
case AAPTR_TRACER:
self->master = gettracer;
if (!(PTROP_UNSAFEMASTER & flags)) VerifyMasterChain(self);
break;
case AAPTR_NULL:
self->master = NULL;
break;
}
switch (ptr_tracer) // pick the new tracer
{
case AAPTR_TARGET:
self->tracer = gettarget;
break; // no verification deemed necessary; the engine never follows a tracer chain(?)
case AAPTR_MASTER:
self->tracer = getmaster;
break; // no verification deemed necessary; the engine never follows a tracer chain(?)
case AAPTR_NULL:
self->tracer = NULL;
break;
}
return 0;
}
//==========================================================================
//
// A_TransferPointer
//
// Copy one pointer (MASTER, TARGET or TRACER) from this actor (SELF),
// or from this actor's MASTER, TARGET or TRACER.
//
// You can copy any one of that actor's pointers
//
// Assign the copied pointer to any one pointer in SELF,
// MASTER, TARGET or TRACER.
//
// Any attempt to make an actor point to itself will replace the pointer
// with a null value.
//
//==========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_TransferPointer)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_INT (ptr_source);
PARAM_INT (ptr_recipient);
PARAM_INT (ptr_sourcefield);
PARAM_INT_DEF (ptr_recipientfield);
PARAM_INT_DEF (flags);
AActor *source, *recipient;
// Exchange pointers with actors to whom you have pointers (or with yourself, if you must)
source = COPY_AAPTR(self, ptr_source);
recipient = COPY_AAPTR(self, ptr_recipient); // pick an actor to store the provided pointer value
if (recipient == NULL)
{
return 0;
}
// convert source from dataprovider to data
source = COPY_AAPTR(source, ptr_sourcefield);
if (source == recipient)
{ // The recepient should not acquire a pointer to itself; will write NULL}
source = NULL;
}
if (ptr_recipientfield == AAPTR_DEFAULT)
{ // If default: Write to same field as data was read from
ptr_recipientfield = ptr_sourcefield;
}
ASSIGN_AAPTR(recipient, ptr_recipientfield, source, flags);
return 0;
}
//==========================================================================
//
// A_CopyFriendliness
//
// Join forces with one of the actors you are pointing to (MASTER by default)
//
// Normal CopyFriendliness reassigns health. This function will not.
//
//==========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_CopyFriendliness)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_INT_DEF (ptr_source);
if (self->player != NULL)
{
return 0;
}
AActor *source = COPY_AAPTR(self, ptr_source);
if (source != NULL)
{ // No change in current target or health
self->CopyFriendliness(source, false, false);
}
return 0;
}
//==========================================================================
//
// Customizable attack functions which use actor parameters.
//
//==========================================================================
static void DoAttack (AActor *self, bool domelee, bool domissile,
int MeleeDamage, FSoundID MeleeSound, PClassActor *MissileType,double MissileHeight)
{
if (self->target == NULL) return;
A_FaceTarget (self);
if (domelee && MeleeDamage>0 && self->CheckMeleeRange ())
{
int damage = pr_camelee.HitDice(MeleeDamage);
if (MeleeSound) S_Sound (self, CHAN_WEAPON, MeleeSound, 1, ATTN_NORM);
int newdam = P_DamageMobj (self->target, self, self, damage, NAME_Melee);
P_TraceBleed (newdam > 0 ? newdam : damage, self->target, self);
}
else if (domissile && MissileType != NULL)
{
// This seemingly senseless code is needed for proper aiming.
double add = MissileHeight + self->GetBobOffset() - 32;
self->AddZ(add);
AActor *missile = P_SpawnMissileXYZ (self->PosPlusZ(32.), self, self->target, MissileType, false);
self->AddZ(-add);
if (missile)
{
// automatic handling of seeker missiles
if (missile->flags2&MF2_SEEKERMISSILE)
{
missile->tracer=self->target;
}
P_CheckMissileSpawn(missile, self->radius);
}
}
}
DEFINE_ACTION_FUNCTION(AActor, A_MeleeAttack)
{
PARAM_SELF_PROLOGUE(AActor);
int MeleeDamage = self->GetClass()->MeleeDamage;
FSoundID MeleeSound = self->GetClass()->MeleeSound;
DoAttack(self, true, false, MeleeDamage, MeleeSound, NULL, 0);
return 0;
}
DEFINE_ACTION_FUNCTION(AActor, A_MissileAttack)
{
PARAM_SELF_PROLOGUE(AActor);
PClassActor *MissileType = PClass::FindActor(self->GetClass()->MissileName);
DoAttack(self, false, true, 0, 0, MissileType, self->GetClass()->MissileHeight);
return 0;
}
DEFINE_ACTION_FUNCTION(AActor, A_ComboAttack)
{
PARAM_SELF_PROLOGUE(AActor);
int MeleeDamage = self->GetClass()->MeleeDamage;
FSoundID MeleeSound = self->GetClass()->MeleeSound;
PClassActor *MissileType = PClass::FindActor(self->GetClass()->MissileName);
DoAttack(self, true, true, MeleeDamage, MeleeSound, MissileType, self->GetClass()->MissileHeight);
return 0;
}
DEFINE_ACTION_FUNCTION(AActor, A_BasicAttack)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_INT (melee_damage);
PARAM_SOUND (melee_sound);
PARAM_CLASS (missile_type, AActor);
PARAM_FLOAT (missile_height);
if (missile_type != NULL)
{
DoAttack(self, true, true, melee_damage, melee_sound, missile_type, missile_height);
}
return 0;
}
//==========================================================================
//
// Custom sound functions.
//
//==========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_PlaySound)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_SOUND_DEF (soundid);
PARAM_INT_DEF (channel);
PARAM_FLOAT_DEF (volume);
PARAM_BOOL_DEF (looping);
PARAM_FLOAT_DEF (attenuation);
PARAM_BOOL_DEF (local);
if (!looping)
{
S_PlaySound(self, channel, soundid, (float)volume, (float)attenuation, local);
}
else
{
if (!S_IsActorPlayingSomething (self, channel&7, soundid))
{
S_PlaySound(self, channel | CHAN_LOOP, soundid, (float)volume, (float)attenuation, local);
}
}
return 0;
}
DEFINE_ACTION_FUNCTION(AActor, A_StopSound)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_INT_DEF(slot);
S_StopSound(self, slot);
return 0;
}
//==========================================================================
//
// These come from a time when DECORATE constants did not exist yet and
// the sound interface was less flexible. As a result the parameters are
// not optimal and these functions have been deprecated in favor of extending
// A_PlaySound and A_StopSound.
//
//==========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_PlaySoundEx)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_SOUND (soundid);
PARAM_NAME (channel);
PARAM_BOOL_DEF (looping);
PARAM_INT_DEF (attenuation_raw);
float attenuation;
switch (attenuation_raw)
{
case -1: attenuation = ATTN_STATIC; break; // drop off rapidly
default:
case 0: attenuation = ATTN_NORM; break; // normal
case 1:
case 2: attenuation = ATTN_NONE; break; // full volume
}
if (channel < NAME_Auto || channel > NAME_SoundSlot7)
{
channel = NAME_Auto;
}
if (!looping)
{
S_Sound (self, int(channel) - NAME_Auto, soundid, 1, attenuation);
}
else
{
if (!S_IsActorPlayingSomething (self, int(channel) - NAME_Auto, soundid))
{
S_Sound (self, (int(channel) - NAME_Auto) | CHAN_LOOP, soundid, 1, attenuation);
}
}
return 0;
}
DEFINE_ACTION_FUNCTION(AActor, A_StopSoundEx)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_NAME(channel);
if (channel > NAME_Auto && channel <= NAME_SoundSlot7)
{
S_StopSound (self, int(channel) - NAME_Auto);
}
return 0;
}
//==========================================================================
//
// Generic seeker missile function
//
//==========================================================================
static FRandom pr_seekermissile ("SeekerMissile");
enum
{
SMF_LOOK = 1,
SMF_PRECISE = 2,
SMF_CURSPEED = 4,
};
DEFINE_ACTION_FUNCTION(AActor, A_SeekerMissile)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_INT(ang1);
PARAM_INT(ang2);
PARAM_INT_DEF(flags);
PARAM_INT_DEF(chance);
PARAM_INT_DEF(distance);
if ((flags & SMF_LOOK) && (self->tracer == 0) && (pr_seekermissile()<chance))
{
self->tracer = P_RoughMonsterSearch (self, distance, true);
}
if (!P_SeekerMissile(self, clamp<int>(ang1, 0, 90), clamp<int>(ang2, 0, 90), !!(flags & SMF_PRECISE), !!(flags & SMF_CURSPEED)))
{
if (flags & SMF_LOOK)
{ // This monster is no longer seekable, so let us look for another one next time.
self->tracer = NULL;
}
}
return 0;
}
//==========================================================================
//
// Hitscan attack with a customizable amount of bullets (specified in damage)
//
//==========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_BulletAttack)
{
PARAM_SELF_PROLOGUE(AActor);
int i;
if (!self->target) return 0;
A_FaceTarget (self);
DAngle slope = P_AimLineAttack (self, self->Angles.Yaw, MISSILERANGE);
S_Sound (self, CHAN_WEAPON, self->AttackSound, 1, ATTN_NORM);
for (i = self->GetMissileDamage (0, 1); i > 0; --i)
{
DAngle angle = self->Angles.Yaw + pr_cabullet.Random2() * (5.625 / 256.);
int damage = ((pr_cabullet()%5)+1)*3;
P_LineAttack(self, angle, MISSILERANGE, slope, damage,
NAME_Hitscan, NAME_BulletPuff);
}
return 0;
}
//==========================================================================
//
// State jump function
//
//==========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_Jump)
{
PARAM_ACTION_PROLOGUE(AActor);
PARAM_INT(maxchance);
paramnum++; // Increment paramnum to point at the first jump target
int count = numparam - paramnum;
if (count > 0 && (maxchance >= 256 || pr_cajump() < maxchance))
{
int jumpnum = (count == 1 ? 0 : (pr_cajump() % count));
PARAM_STATE_ACTION_AT(paramnum + jumpnum, jumpto);
ACTION_RETURN_STATE(jumpto);
}
ACTION_RETURN_STATE(NULL);
}
//==========================================================================
//
// State jump function
//
//==========================================================================
DEFINE_ACTION_FUNCTION(AActor, CheckInventory)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_CLASS (itemtype, AInventory);
PARAM_INT (itemamount);
PARAM_INT_DEF (setowner);
if (itemtype == nullptr)
{
ACTION_RETURN_BOOL(false);
}
AActor *owner = COPY_AAPTR(self, setowner);
if (owner == nullptr)
{
ACTION_RETURN_BOOL(false);
}
AInventory *item = owner->FindInventory(itemtype);
if (item)
{
if (itemamount > 0)
{
if (item->Amount >= itemamount)
{
ACTION_RETURN_BOOL(true);
}
}
else if (item->Amount >= item->MaxAmount)
{
ACTION_RETURN_BOOL(true);
}
}
ACTION_RETURN_BOOL(false);
}
//==========================================================================
//
// State jump function
//
//==========================================================================
DEFINE_ACTION_FUNCTION(AActor, CheckArmorType)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_NAME (type);
PARAM_INT_DEF(amount);
ABasicArmor *armor = (ABasicArmor *)self->FindInventory(NAME_BasicArmor);
ACTION_RETURN_BOOL(armor && armor->ArmorType == type && armor->Amount >= amount);
}
//==========================================================================
//
// Parameterized version of A_Explode
//
//==========================================================================
enum
{
XF_HURTSOURCE = 1,
XF_NOTMISSILE = 4,
XF_NOACTORTYPE = 1 << 3,
XF_NOSPLASH = 16,
};
DEFINE_ACTION_FUNCTION(AActor, A_Explode)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_INT_DEF (damage);
PARAM_INT_DEF (distance);
PARAM_INT_DEF (flags);
PARAM_BOOL_DEF (alert);
PARAM_INT_DEF (fulldmgdistance);
PARAM_INT_DEF (nails);
PARAM_INT_DEF (naildamage);
PARAM_CLASS_DEF (pufftype, AActor);
PARAM_NAME_DEF (damagetype);
if (damage < 0) // get parameters from metadata
{
damage = self->GetClass()->ExplosionDamage;
distance = self->GetClass()->ExplosionRadius;
flags = !self->GetClass()->DontHurtShooter;
alert = false;
}
if (distance <= 0) distance = damage;
// NailBomb effect, from SMMU but not from its source code: instead it was implemented and
// generalized from the documentation at http://www.doomworld.com/eternity/engine/codeptrs.html
if (nails)
{
DAngle ang;
for (int i = 0; i < nails; i++)
{
ang = i*360./nails;
// Comparing the results of a test wad with Eternity, it seems A_NailBomb does not aim
P_LineAttack (self, ang, MISSILERANGE, 0.,
//P_AimLineAttack (self, ang, MISSILERANGE),
naildamage, NAME_Hitscan, pufftype);
}
}
if (!(flags & XF_NOACTORTYPE) && damagetype == NAME_None)
{
damagetype = self->DamageType;
}
int pflags = 0;
if (flags & XF_HURTSOURCE) pflags |= RADF_HURTSOURCE;
if (flags & XF_NOTMISSILE) pflags |= RADF_SOURCEISSPOT;
int count = P_RadiusAttack (self, self->target, damage, distance, damagetype, pflags, fulldmgdistance);
if (!(flags & XF_NOSPLASH)) P_CheckSplash(self, distance);
if (alert && self->target != NULL && self->target->player != NULL)
{
P_NoiseAlert(self->target, self);
}
ACTION_RETURN_INT(count);
}
//==========================================================================
//
// A_RadiusThrust
//
//==========================================================================
enum
{
RTF_AFFECTSOURCE = 1,
RTF_NOIMPACTDAMAGE = 2,
RTF_NOTMISSILE = 4,
};
DEFINE_ACTION_FUNCTION(AActor, A_RadiusThrust)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_INT_DEF (force);
PARAM_INT_DEF (distance);
PARAM_INT_DEF (flags);
PARAM_INT_DEF (fullthrustdistance);
bool sourcenothrust = false;
if (force == 0) force = 128;
if (distance <= 0) distance = abs(force);
// Temporarily negate MF2_NODMGTHRUST on the shooter, since it renders this function useless.
if (!(flags & RTF_NOTMISSILE) && self->target != NULL && self->target->flags2 & MF2_NODMGTHRUST)
{
sourcenothrust = true;
self->target->flags2 &= ~MF2_NODMGTHRUST;
}
P_RadiusAttack (self, self->target, force, distance, self->DamageType, flags | RADF_NODAMAGE, fullthrustdistance);
P_CheckSplash(self, distance);
if (sourcenothrust)
{
self->target->flags2 |= MF2_NODMGTHRUST;
}
return 0;
}
//==========================================================================
//
// A_RadiusDamageSelf
//
//==========================================================================
enum
{
RDSF_BFGDAMAGE = 1,
};
DEFINE_ACTION_FUNCTION(AActor, A_RadiusDamageSelf)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_INT_DEF(damage);
PARAM_FLOAT_DEF(distance);
PARAM_INT_DEF(flags);
PARAM_CLASS_DEF(flashtype, AActor);
int i;
int damageSteps;
int actualDamage;
double actualDistance;
actualDistance = self->Distance3D(self->target);
if (actualDistance < distance)
{
// [XA] Decrease damage with distance. Use the BFG damage
// calculation formula if the flag is set (essentially
// a generalization of SMMU's BFG11K behavior, used
// with fraggle's blessing.)
damageSteps = damage - int(damage * actualDistance / distance);
if (flags & RDSF_BFGDAMAGE)
{
actualDamage = 0;
for (i = 0; i < damageSteps; ++i)
actualDamage += (pr_bfgselfdamage() & 7) + 1;
}
else
{
actualDamage = damageSteps;
}
// optional "flash" effect -- spawn an actor on
// the player to indicate bad things happened.
AActor *flash = NULL;
if(flashtype != NULL)
flash = Spawn(flashtype, self->target->PosPlusZ(self->target->Height / 4), ALLOW_REPLACE);
int dmgFlags = 0;
FName dmgType = NAME_BFGSplash;
if (flash != NULL)
{
if (flash->flags5 & MF5_PUFFGETSOWNER) flash->target = self->target;
if (flash->flags3 & MF3_FOILINVUL) dmgFlags |= DMG_FOILINVUL;
if (flash->flags7 & MF7_FOILBUDDHA) dmgFlags |= DMG_FOILBUDDHA;
dmgType = flash->DamageType;
}
int newdam = P_DamageMobj(self->target, self, self->target, actualDamage, dmgType, dmgFlags);
P_TraceBleed(newdam > 0 ? newdam : actualDamage, self->target, self);
}
return 0;
}
//==========================================================================
//
// Execute a line special / script
//
//==========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_CallSpecial)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_INT (special);
PARAM_INT_DEF (arg1);
PARAM_INT_DEF (arg2);
PARAM_INT_DEF (arg3);
PARAM_INT_DEF (arg4);
PARAM_INT_DEF (arg5);
bool res = !!P_ExecuteSpecial(special, NULL, self, false, arg1, arg2, arg3, arg4, arg5);
ACTION_RETURN_BOOL(res);
}
//==========================================================================
//
// The ultimate code pointer: Fully customizable missiles!
//
//==========================================================================
enum CM_Flags
{
CMF_AIMMODE = 3,
CMF_TRACKOWNER = 4,
CMF_CHECKTARGETDEAD = 8,
CMF_ABSOLUTEPITCH = 16,
CMF_OFFSETPITCH = 32,
CMF_SAVEPITCH = 64,
CMF_ABSOLUTEANGLE = 128,
CMF_BADPITCH = 256
};
DEFINE_ACTION_FUNCTION(AActor, A_SpawnProjectile)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_CLASS (ti, AActor);
PARAM_FLOAT_DEF (Spawnheight);
PARAM_FLOAT_DEF (Spawnofs_xy);
PARAM_ANGLE_DEF (Angle);
PARAM_INT_DEF (flags);
PARAM_ANGLE_DEF (Pitch);
PARAM_INT_DEF (ptr);
AActor *ref = COPY_AAPTR(self, ptr);
int aimmode = flags & CMF_AIMMODE;
AActor * targ;
AActor * missile;
if (ref != NULL || aimmode == 2)
{
if (ti)
{
DAngle angle = self->Angles.Yaw - 90;
double x = Spawnofs_xy * angle.Cos();
double y = Spawnofs_xy * angle.Sin();
double z = Spawnheight + self->GetBobOffset() - 32 + (self->player? self->player->crouchoffset : 0.);
DVector3 pos = self->Pos();
switch (aimmode)
{
case 0:
default:
// same adjustment as above (in all 3 directions this time) - for better aiming!
self->SetXYZ(self->Vec3Offset(x, y, z));
missile = P_SpawnMissileXYZ(self->PosPlusZ(32.), self, ref, ti, false);
self->SetXYZ(pos);
break;
case 1:
missile = P_SpawnMissileXYZ(self->Vec3Offset(x, y, self->GetBobOffset() + Spawnheight), self, ref, ti, false);
break;
case 2:
self->SetXYZ(self->Vec3Offset(x, y, 0.));
missile = P_SpawnMissileAngleZSpeed(self, self->Z() + self->GetBobOffset() + Spawnheight, ti, self->Angles.Yaw, 0, GetDefaultByType(ti)->Speed, self, false);
self->SetXYZ(pos);
flags |= CMF_ABSOLUTEPITCH;
break;
}
if (missile != NULL)
{
// Use the actual velocity instead of the missile's Speed property
// so that this can handle missiles with a high vertical velocity
// component properly.
double missilespeed;
if ( (CMF_ABSOLUTEPITCH|CMF_OFFSETPITCH) & flags)
{
if (CMF_OFFSETPITCH & flags)
{
Pitch += missile->Vel.Pitch();
}
missilespeed = fabs(Pitch.Cos() * missile->Speed);
missile->Vel.Z = Pitch.Sin() * missile->Speed;
if (!(flags & CMF_BADPITCH)) missile->Vel.Z *= -1;
}
else
{
missilespeed = missile->VelXYToSpeed();
}
if (CMF_SAVEPITCH & flags)
{
missile->Angles.Pitch = Pitch;
// In aimmode 0 and 1 without absolutepitch or offsetpitch, the pitch parameter
// contains the unapplied parameter. In that case, it is set as pitch without
// otherwise affecting the spawned actor.
}
missile->Angles.Yaw = (CMF_ABSOLUTEANGLE & flags) ? Angle : missile->Angles.Yaw + Angle;
missile->VelFromAngle(missilespeed);
// handle projectile shooting projectiles - track the
// links back to a real owner
if (self->isMissile(!!(flags & CMF_TRACKOWNER)))
{
AActor *owner = self ;//->target;
while (owner->isMissile(!!(flags & CMF_TRACKOWNER)) && owner->target)
owner = owner->target;
targ = owner;
missile->target = owner;
// automatic handling of seeker missiles
if (self->flags2 & missile->flags2 & MF2_SEEKERMISSILE)
{
missile->tracer = self->tracer;
}
}
else if (missile->flags2 & MF2_SEEKERMISSILE)
{
// automatic handling of seeker missiles
missile->tracer = self->target;
}
// we must redo the spectral check here because the owner is set after spawning so the FriendPlayer value may be wrong
if (missile->flags4 & MF4_SPECTRAL)
{
if (missile->target != NULL)
{
missile->SetFriendPlayer(missile->target->player);
}
else
{
missile->FriendPlayer = 0;
}
}
P_CheckMissileSpawn(missile, self->radius);
}
}
}
else if (flags & CMF_CHECKTARGETDEAD)
{
// Target is dead and the attack shall be aborted.
if (self->SeeState != NULL && (self->health > 0 || !(self->flags3 & MF3_ISMONSTER)))
self->SetState(self->SeeState);
}
return 0;
}
//==========================================================================
//
// An even more customizable hitscan attack
//
//==========================================================================
enum CBA_Flags
{
CBAF_AIMFACING = 1,
CBAF_NORANDOM = 2,
CBAF_EXPLICITANGLE = 4,
CBAF_NOPITCH = 8,
CBAF_NORANDOMPUFFZ = 16,
CBAF_PUFFTARGET = 32,
CBAF_PUFFMASTER = 64,
CBAF_PUFFTRACER = 128,
};
static void AimBulletMissile(AActor *proj, AActor *puff, int flags, bool temp, bool cba);
DEFINE_ACTION_FUNCTION(AActor, A_CustomBulletAttack)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_ANGLE (spread_xy);
PARAM_ANGLE (spread_z);
PARAM_INT (numbullets);
PARAM_INT (damageperbullet);
PARAM_CLASS_DEF (pufftype, AActor);
PARAM_FLOAT_DEF (range);
PARAM_INT_DEF (flags);
PARAM_INT_DEF (ptr);
PARAM_CLASS_DEF (missile, AActor);
PARAM_FLOAT_DEF (Spawnheight);
PARAM_FLOAT_DEF (Spawnofs_xy);
AActor *ref = COPY_AAPTR(self, ptr);
if (range == 0)
range = MISSILERANGE;
int i;
DAngle bangle;
DAngle bslope = 0.;
int laflags = (flags & CBAF_NORANDOMPUFFZ)? LAF_NORANDOMPUFFZ : 0;
if (ref != NULL || (flags & CBAF_AIMFACING))
{
if (!(flags & CBAF_AIMFACING))
{
A_Face(self, ref);
}
bangle = self->Angles.Yaw;
if (!(flags & CBAF_NOPITCH)) bslope = P_AimLineAttack (self, bangle, MISSILERANGE);
if (pufftype == nullptr) pufftype = PClass::FindActor(NAME_BulletPuff);
S_Sound (self, CHAN_WEAPON, self->AttackSound, 1, ATTN_NORM);
for (i = 0; i < numbullets; i++)
{
DAngle angle = bangle;
DAngle slope = bslope;
if (flags & CBAF_EXPLICITANGLE)
{
angle += spread_xy;
slope += spread_z;
}
else
{
angle += spread_xy * (pr_cwbullet.Random2() / 255.);
slope += spread_z * (pr_cwbullet.Random2() / 255.);
}
int damage = damageperbullet;
if (!(flags & CBAF_NORANDOM))
damage *= ((pr_cabullet()%3)+1);
AActor *puff = P_LineAttack(self, angle, range, slope, damage, NAME_Hitscan, pufftype, laflags);
if (missile != nullptr && pufftype != nullptr)
{
double x = Spawnofs_xy * angle.Cos();
double y = Spawnofs_xy * angle.Sin();
DVector3 pos = self->Pos();
self->SetXYZ(self->Vec3Offset(x, y, 0.));
AActor *proj = P_SpawnMissileAngleZSpeed(self, self->Z() + self->GetBobOffset() + Spawnheight, missile, self->Angles.Yaw, 0, GetDefaultByType(missile)->Speed, self, false);
self->SetXYZ(pos);
if (proj)
{
bool temp = (puff == nullptr);
if (!puff)
{
puff = P_LineAttack(self, angle, range, slope, 0, NAME_Hitscan, pufftype, laflags | LAF_NOINTERACT);
}
if (puff)
{
AimBulletMissile(proj, puff, flags, temp, true);
}
}
}
}
}
return 0;
}
//==========================================================================
//
// A fully customizable melee attack
//
//==========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_CustomMeleeAttack)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_INT_DEF (damage);
PARAM_SOUND_DEF (meleesound);
PARAM_SOUND_DEF (misssound);
PARAM_NAME_DEF (damagetype);
PARAM_BOOL_DEF (bleed);
if (damagetype == NAME_None)
damagetype = NAME_Melee; // Melee is the default type
if (!self->target)
return 0;
A_FaceTarget (self);
if (self->CheckMeleeRange ())
{
if (meleesound)
S_Sound (self, CHAN_WEAPON, meleesound, 1, ATTN_NORM);
int newdam = P_DamageMobj (self->target, self, self, damage, damagetype);
if (bleed)
P_TraceBleed (newdam > 0 ? newdam : damage, self->target, self);
}
else
{
if (misssound)
S_Sound (self, CHAN_WEAPON, misssound, 1, ATTN_NORM);
}
return 0;
}
//==========================================================================
//
// A fully customizable combo attack
//
//==========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_CustomComboAttack)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_CLASS (ti, AActor);
PARAM_FLOAT (spawnheight);
PARAM_INT (damage);
PARAM_SOUND_DEF (meleesound);
PARAM_NAME_DEF (damagetype);
PARAM_BOOL_DEF (bleed);
if (!self->target)
return 0;
A_FaceTarget (self);
if (self->CheckMeleeRange())
{
if (damagetype == NAME_None)
damagetype = NAME_Melee; // Melee is the default type
if (meleesound)
S_Sound (self, CHAN_WEAPON, meleesound, 1, ATTN_NORM);
int newdam = P_DamageMobj (self->target, self, self, damage, damagetype);
if (bleed)
P_TraceBleed (newdam > 0 ? newdam : damage, self->target, self);
}
else if (ti)
{
// This seemingly senseless code is needed for proper aiming.
double add = spawnheight + self->GetBobOffset() - 32;
self->AddZ(add);
AActor *missile = P_SpawnMissileXYZ (self->PosPlusZ(32.), self, self->target, ti, false);
self->AddZ(-add);
if (missile)
{
// automatic handling of seeker missiles
if (missile->flags2 & MF2_SEEKERMISSILE)
{
missile->tracer = self->target;
}
P_CheckMissileSpawn(missile, self->radius);
}
}
return 0;
}
//==========================================================================
//
// State jump function
//
//==========================================================================
DEFINE_ACTION_FUNCTION(AStateProvider, A_JumpIfNoAmmo)
{
PARAM_ACTION_PROLOGUE(AStateProvider);
PARAM_STATE_ACTION(jump);
if (!ACTION_CALL_FROM_PSPRITE() || self->player->ReadyWeapon == nullptr)
{
ACTION_RETURN_STATE(NULL);
}
if (!self->player->ReadyWeapon->CheckAmmo(self->player->ReadyWeapon->bAltFire, false, true))
{
ACTION_RETURN_STATE(jump);
}
ACTION_RETURN_STATE(NULL);
}
//==========================================================================
//
// An even more customizable hitscan attack
//
//==========================================================================
enum FB_Flags
{
FBF_USEAMMO = 1,
FBF_NORANDOM = 2,
FBF_EXPLICITANGLE = 4,
FBF_NOPITCH = 8,
FBF_NOFLASH = 16,
FBF_NORANDOMPUFFZ = 32,
FBF_PUFFTARGET = 64,
FBF_PUFFMASTER = 128,
FBF_PUFFTRACER = 256,
};
static void AimBulletMissile(AActor *proj, AActor *puff, int flags, bool temp, bool cba)
{
if (proj && puff)
{
if (proj)
{
// FAF_BOTTOM = 1
// Aim for the base of the puff as that's where blood puffs will spawn... roughly.
A_Face(proj, puff, 0., 0., 0., 0., 1);
proj->Vel3DFromAngle(proj->Angles.Pitch, proj->Speed);
if (!temp)
{
if (cba)
{
if (flags & CBAF_PUFFTARGET) proj->target = puff;
if (flags & CBAF_PUFFMASTER) proj->master = puff;
if (flags & CBAF_PUFFTRACER) proj->tracer = puff;
}
else
{
if (flags & FBF_PUFFTARGET) proj->target = puff;
if (flags & FBF_PUFFMASTER) proj->master = puff;
if (flags & FBF_PUFFTRACER) proj->tracer = puff;
}
}
}
}
if (puff && temp)
{
puff->Destroy();
}
}
DEFINE_ACTION_FUNCTION(AStateProvider, A_FireBullets)
{
PARAM_ACTION_PROLOGUE(AStateProvider);
PARAM_ANGLE (spread_xy);
PARAM_ANGLE (spread_z);
PARAM_INT (numbullets);
PARAM_INT (damageperbullet);
PARAM_CLASS_DEF (pufftype, AActor);
PARAM_INT_DEF (flags);
PARAM_FLOAT_DEF (range);
PARAM_CLASS_DEF (missile, AActor);
PARAM_FLOAT_DEF (Spawnheight);
PARAM_FLOAT_DEF (Spawnofs_xy);
if (!self->player) return 0;
player_t *player = self->player;
AWeapon *weapon = player->ReadyWeapon;
int i;
DAngle bangle;
DAngle bslope = 0.;
int laflags = (flags & FBF_NORANDOMPUFFZ)? LAF_NORANDOMPUFFZ : 0;
if ((flags & FBF_USEAMMO) && weapon && ACTION_CALL_FROM_PSPRITE())
{
if (!weapon->DepleteAmmo(weapon->bAltFire, true))
return 0; // out of ammo
}
if (range == 0) range = PLAYERMISSILERANGE;
if (!(flags & FBF_NOFLASH)) static_cast<APlayerPawn *>(self)->PlayAttacking2 ();
if (!(flags & FBF_NOPITCH)) bslope = P_BulletSlope(self);
bangle = self->Angles.Yaw;
if (pufftype == NULL) pufftype = PClass::FindActor(NAME_BulletPuff);
if (weapon != NULL)
{
S_Sound(self, CHAN_WEAPON, weapon->AttackSound, 1, ATTN_NORM);
}
if ((numbullets == 1 && !player->refire) || numbullets == 0)
{
int damage = damageperbullet;
if (!(flags & FBF_NORANDOM))
damage *= ((pr_cwbullet()%3)+1);
AActor *puff = P_LineAttack(self, bangle, range, bslope, damage, NAME_Hitscan, pufftype, laflags);
if (missile != nullptr)
{
bool temp = false;
DAngle ang = self->Angles.Yaw - 90;
DVector2 ofs = ang.ToVector(Spawnofs_xy);
AActor *proj = P_SpawnPlayerMissile(self, ofs.X, ofs.Y, Spawnheight, missile, bangle, nullptr, nullptr, false, true);
if (proj)
{
if (!puff)
{
temp = true;
puff = P_LineAttack(self, bangle, range, bslope, 0, NAME_Hitscan, pufftype, laflags | LAF_NOINTERACT);
}
AimBulletMissile(proj, puff, flags, temp, false);
}
}
}
else
{
if (numbullets < 0)
numbullets = 1;
for (i = 0; i < numbullets; i++)
{
DAngle angle = bangle;
DAngle slope = bslope;
if (flags & FBF_EXPLICITANGLE)
{
angle += spread_xy;
slope += spread_z;
}
else
{
angle += spread_xy * (pr_cwbullet.Random2() / 255.);
slope += spread_z * (pr_cwbullet.Random2() / 255.);
}
int damage = damageperbullet;
if (!(flags & FBF_NORANDOM))
damage *= ((pr_cwbullet()%3)+1);
AActor *puff = P_LineAttack(self, angle, range, slope, damage, NAME_Hitscan, pufftype, laflags);
if (missile != nullptr)
{
bool temp = false;
DAngle ang = self->Angles.Yaw - 90;
DVector2 ofs = ang.ToVector(Spawnofs_xy);
AActor *proj = P_SpawnPlayerMissile(self, ofs.X, ofs.Y, Spawnheight, missile, angle, nullptr, nullptr, false, true);
if (proj)
{
if (!puff)
{
temp = true;
puff = P_LineAttack(self, angle, range, slope, 0, NAME_Hitscan, pufftype, laflags | LAF_NOINTERACT);
}
AimBulletMissile(proj, puff, flags, temp, false);
}
}
}
}
return 0;
}
//==========================================================================
//
// A_FireProjectile
//
//==========================================================================
enum FP_Flags
{
FPF_AIMATANGLE = 1,
FPF_TRANSFERTRANSLATION = 2,
FPF_NOAUTOAIM = 4,
};
DEFINE_ACTION_FUNCTION(AStateProvider, A_FireProjectile)
{
PARAM_ACTION_PROLOGUE(AStateProvider);
PARAM_CLASS (ti, AActor);
PARAM_ANGLE_DEF (angle);
PARAM_BOOL_DEF (useammo);
PARAM_FLOAT_DEF (spawnofs_xy);
PARAM_FLOAT_DEF (spawnheight);
PARAM_INT_DEF (flags);
PARAM_ANGLE_DEF (pitch);
if (!self->player)
return 0;
player_t *player = self->player;
AWeapon *weapon = player->ReadyWeapon;
FTranslatedLineTarget t;
// Only use ammo if called from a weapon
if (useammo && ACTION_CALL_FROM_PSPRITE() && weapon)
{
if (!weapon->DepleteAmmo(weapon->bAltFire, true))
return 0; // out of ammo
}
if (ti)
{
DAngle ang = self->Angles.Yaw - 90;
DVector2 ofs = ang.ToVector(spawnofs_xy);
DAngle shootangle = self->Angles.Yaw;
if (flags & FPF_AIMATANGLE) shootangle += angle;
// Temporarily adjusts the pitch
DAngle saved_player_pitch = self->Angles.Pitch;
self->Angles.Pitch -= pitch;
AActor * misl=P_SpawnPlayerMissile (self, ofs.X, ofs.Y, spawnheight, ti, shootangle, &t, NULL, false, (flags & FPF_NOAUTOAIM) != 0);
self->Angles.Pitch = saved_player_pitch;
// automatic handling of seeker missiles
if (misl)
{
if (flags & FPF_TRANSFERTRANSLATION)
misl->Translation = self->Translation;
if (t.linetarget && !t.unlinked && (misl->flags2 & MF2_SEEKERMISSILE))
misl->tracer = t.linetarget;
if (!(flags & FPF_AIMATANGLE))
{
// This original implementation is to aim straight ahead and then offset
// the angle from the resulting direction.
misl->Angles.Yaw += angle;
misl->VelFromAngle(misl->VelXYToSpeed());
}
}
}
return 0;
}
//==========================================================================
//
// A_CustomPunch
//
// Berserk is not handled here. That can be done with A_CheckIfInventory
//
//==========================================================================
enum
{
CPF_USEAMMO = 1,
CPF_DAGGER = 2,
CPF_PULLIN = 4,
CPF_NORANDOMPUFFZ = 8,
CPF_NOTURN = 16,
CPF_STEALARMOR = 32,
};
DEFINE_ACTION_FUNCTION(AStateProvider, A_CustomPunch)
{
PARAM_ACTION_PROLOGUE(AStateProvider);
PARAM_INT (damage);
PARAM_BOOL_DEF (norandom);
PARAM_INT_DEF (flags);
PARAM_CLASS_DEF (pufftype, AActor);
PARAM_FLOAT_DEF (range);
PARAM_FLOAT_DEF (lifesteal);
PARAM_INT_DEF (lifestealmax);
PARAM_CLASS_DEF (armorbonustype, ABasicArmorBonus);
PARAM_SOUND_DEF (MeleeSound);
PARAM_SOUND_DEF (MissSound);
if (!self->player)
return 0;
player_t *player = self->player;
AWeapon *weapon = player->ReadyWeapon;
DAngle angle;
DAngle pitch;
FTranslatedLineTarget t;
int actualdamage;
if (!norandom)
damage *= pr_cwpunch() % 8 + 1;
angle = self->Angles.Yaw + pr_cwpunch.Random2() * (5.625 / 256);
if (range == 0) range = DEFMELEERANGE;
pitch = P_AimLineAttack (self, angle, range, &t);
// only use ammo when actually hitting something!
if ((flags & CPF_USEAMMO) && t.linetarget && weapon && ACTION_CALL_FROM_PSPRITE())
{
if (!weapon->DepleteAmmo(weapon->bAltFire, true))
return 0; // out of ammo
}
if (pufftype == NULL)
pufftype = PClass::FindActor(NAME_BulletPuff);
int puffFlags = LAF_ISMELEEATTACK | ((flags & CPF_NORANDOMPUFFZ) ? LAF_NORANDOMPUFFZ : 0);
P_LineAttack (self, angle, range, pitch, damage, NAME_Melee, pufftype, puffFlags, &t, &actualdamage);
if (!t.linetarget)
{
if (MissSound) S_Sound(self, CHAN_WEAPON, MissSound, 1, ATTN_NORM);
}
else
{
if (lifesteal > 0 && !(t.linetarget->flags5 & MF5_DONTDRAIN))
{
if (flags & CPF_STEALARMOR)
{
if (armorbonustype == NULL)
{
armorbonustype = dyn_cast<ABasicArmorBonus::MetaClass>(PClass::FindClass("ArmorBonus"));
}
if (armorbonustype != NULL)
{
assert(armorbonustype->IsDescendantOf(RUNTIME_CLASS(ABasicArmorBonus)));
ABasicArmorBonus *armorbonus = static_cast<ABasicArmorBonus *>(Spawn(armorbonustype));
armorbonus->SaveAmount *= int(actualdamage * lifesteal);
armorbonus->MaxSaveAmount = lifestealmax <= 0 ? armorbonus->MaxSaveAmount : lifestealmax;
armorbonus->flags |= MF_DROPPED;
armorbonus->ClearCounters();
if (!armorbonus->CallTryPickup(self))
{
armorbonus->Destroy ();
}
}
}
else
{
P_GiveBody (self, int(actualdamage * lifesteal), lifestealmax);
}
}
if (weapon != NULL)
{
if (MeleeSound) S_Sound(self, CHAN_WEAPON, MeleeSound, 1, ATTN_NORM);
else S_Sound (self, CHAN_WEAPON, weapon->AttackSound, 1, ATTN_NORM);
}
if (!(flags & CPF_NOTURN))
{
// turn to face target
self->Angles.Yaw = t.angleFromSource;
}
if (flags & CPF_PULLIN) self->flags |= MF_JUSTATTACKED;
if (flags & CPF_DAGGER) P_DaggerAlert (self, t.linetarget);
}
return 0;
}
//==========================================================================
//
// customizable railgun attack function
//
//==========================================================================
DEFINE_ACTION_FUNCTION(AStateProvider, A_RailAttack)
{
PARAM_ACTION_PROLOGUE(AStateProvider);
PARAM_INT (damage);
PARAM_INT_DEF (spawnofs_xy);
PARAM_BOOL_DEF (useammo);
PARAM_COLOR_DEF (color1);
PARAM_COLOR_DEF (color2);
PARAM_INT_DEF (flags);
PARAM_FLOAT_DEF (maxdiff);
PARAM_CLASS_DEF (pufftype, AActor);
PARAM_ANGLE_DEF (spread_xy);
PARAM_ANGLE_DEF (spread_z);
PARAM_FLOAT_DEF (range) ;
PARAM_INT_DEF (duration);
PARAM_FLOAT_DEF (sparsity);
PARAM_FLOAT_DEF (driftspeed);
PARAM_CLASS_DEF (spawnclass, AActor);
PARAM_FLOAT_DEF (spawnofs_z);
PARAM_INT_DEF (SpiralOffset);
PARAM_INT_DEF (limit);
if (range == 0) range = 8192;
if (sparsity == 0) sparsity=1.0;
if (self->player == NULL)
return 0;
AWeapon *weapon = self->player->ReadyWeapon;
// only use ammo when actually hitting something!
if (useammo && weapon != NULL && ACTION_CALL_FROM_PSPRITE())
{
if (!weapon->DepleteAmmo(weapon->bAltFire, true))
return 0; // out of ammo
}
if (!(flags & RAF_EXPLICITANGLE))
{
spread_xy = spread_xy * pr_crailgun.Random2() / 255;
spread_z = spread_z * pr_crailgun.Random2() / 255;
}
FRailParams p;
p.source = self;
p.damage = damage;
p.offset_xy = spawnofs_xy;
p.offset_z = spawnofs_z;
p.color1 = color1;
p.color2 = color2;
p.maxdiff = maxdiff;
p.flags = flags;
p.puff = pufftype;
p.angleoffset = spread_xy;
p.pitchoffset = spread_z;
p.distance = range;
p.duration = duration;
p.sparsity = sparsity;
p.drift = driftspeed;
p.spawnclass = spawnclass;
p.SpiralOffset = SpiralOffset;
p.limit = limit;
P_RailAttack(&p);
return 0;
}
//==========================================================================
//
// also for monsters
//
//==========================================================================
enum
{
CRF_DONTAIM = 0,
CRF_AIMPARALLEL = 1,
CRF_AIMDIRECT = 2,
CRF_EXPLICITANGLE = 4,
};
DEFINE_ACTION_FUNCTION(AActor, A_CustomRailgun)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_INT (damage);
PARAM_INT_DEF (spawnofs_xy)
PARAM_COLOR_DEF (color1)
PARAM_COLOR_DEF (color2)
PARAM_INT_DEF (flags)
PARAM_INT_DEF (aim)
PARAM_FLOAT_DEF (maxdiff)
PARAM_CLASS_DEF (pufftype, AActor)
PARAM_ANGLE_DEF (spread_xy)
PARAM_ANGLE_DEF (spread_z)
PARAM_FLOAT_DEF (range)
PARAM_INT_DEF (duration)
PARAM_FLOAT_DEF (sparsity)
PARAM_FLOAT_DEF (driftspeed)
PARAM_CLASS_DEF (spawnclass, AActor)
PARAM_FLOAT_DEF (spawnofs_z)
PARAM_INT_DEF (SpiralOffset)
PARAM_INT_DEF (limit)
if (range == 0) range = 8192.;
if (sparsity == 0) sparsity = 1;
FTranslatedLineTarget t;
DVector3 savedpos = self->Pos();
DAngle saved_angle = self->Angles.Yaw;
DAngle saved_pitch = self->Angles.Pitch;
if (aim && self->target == NULL)
{
return 0;
}
// [RH] Andy Baker's stealth monsters
if (self->flags & MF_STEALTH)
{
self->visdir = 1;
}
self->flags &= ~MF_AMBUSH;
if (aim)
{
self->Angles.Yaw = self->AngleTo(self->target);
}
self->Angles.Pitch = P_AimLineAttack (self, self->Angles.Yaw, MISSILERANGE, &t, 60., 0, aim ? self->target : NULL);
if (t.linetarget == NULL && aim)
{
// We probably won't hit the target, but aim at it anyway so we don't look stupid.
DVector2 xydiff = self->Vec2To(self->target);
double zdiff = self->target->Center() - self->Center() - self->Floorclip;
self->Angles.Pitch = -VecToAngle(xydiff.Length(), zdiff);
}
// Let the aim trail behind the player
if (aim)
{
saved_angle = self->Angles.Yaw = self->AngleTo(self->target, -self->target->Vel.X * 3, -self->target->Vel.Y * 3);
if (aim == CRF_AIMDIRECT)
{
// Tricky: We must offset to the angle of the current position
// but then change the angle again to ensure proper aim.
self->SetXY(self->Vec2Offset(
spawnofs_xy * self->Angles.Yaw.Cos(),
spawnofs_xy * self->Angles.Yaw.Sin()));
spawnofs_xy = 0;
self->Angles.Yaw = self->AngleTo(self->target,- self->target->Vel.X * 3, -self->target->Vel.Y * 3);
}
if (self->target->flags & MF_SHADOW)
{
DAngle rnd = pr_crailgun.Random2() * (45. / 256.);
self->Angles.Yaw += rnd;
}
}
if (!(flags & CRF_EXPLICITANGLE))
{
spread_xy = spread_xy * pr_crailgun.Random2() / 255;
spread_z = spread_z * pr_crailgun.Random2() / 255;
}
FRailParams p;
p.source = self;
p.damage = damage;
p.offset_xy = spawnofs_xy;
p.offset_z = spawnofs_z;
p.color1 = color1;
p.color2 = color2;
p.maxdiff = maxdiff;
p.flags = flags;
p.puff = pufftype;
p.angleoffset = spread_xy;
p.pitchoffset = spread_z;
p.distance = range;
p.duration = duration;
p.sparsity = sparsity;
p.drift = driftspeed;
p.spawnclass = spawnclass;
p.SpiralOffset = SpiralOffset;
p.limit = 0;
P_RailAttack(&p);
self->SetXYZ(savedpos);
self->Angles.Yaw = saved_angle;
self->Angles.Pitch = saved_pitch;
return 0;
}
//===========================================================================
//
// DoGiveInventory
//
//===========================================================================
static bool DoGiveInventory(AActor *receiver, bool orresult, VM_ARGS)
{
int paramnum = 0;
PARAM_CLASS (mi, AInventory);
PARAM_INT_DEF (amount)
if (!orresult)
{
PARAM_INT_DEF(setreceiver)
receiver = COPY_AAPTR(receiver, setreceiver);
}
if (receiver == NULL)
{ // If there's nothing to receive it, it's obviously a fail, right?
return false;
}
// Owned inventory items cannot own anything because their Inventory pointer is repurposed for the owner's linked list.
if (receiver->IsKindOf(RUNTIME_CLASS(AInventory)) && static_cast<AInventory*>(receiver)->Owner != nullptr)
{
return false;
}
if (amount <= 0)
{
amount = 1;
}
if (mi)
{
AInventory *item = static_cast<AInventory *>(Spawn(mi));
if (item == NULL)
{
return false;
}
if (item->IsKindOf(RUNTIME_CLASS(AHealth)))
{
item->Amount *= amount;
}
else
{
item->Amount = amount;
}
item->flags |= MF_DROPPED;
item->ClearCounters();
if (!item->CallTryPickup(receiver))
{
item->Destroy();
return false;
}
else
{
return true;
}
}
return false;
}
DEFINE_ACTION_FUNCTION(AActor, A_GiveInventory)
{
PARAM_SELF_PROLOGUE(AActor);
ACTION_RETURN_BOOL(DoGiveInventory(self, false, VM_ARGS_NAMES));
}
DEFINE_ACTION_FUNCTION(AActor, A_GiveToTarget)
{
PARAM_SELF_PROLOGUE(AActor);
ACTION_RETURN_BOOL(DoGiveInventory(self->target, false, VM_ARGS_NAMES));
}
DEFINE_ACTION_FUNCTION(AActor, A_GiveToChildren)
{
PARAM_SELF_PROLOGUE(AActor);
TThinkerIterator<AActor> it;
AActor *mo;
int count = 0;
while ((mo = it.Next()))
{
if (mo->master == self)
{
count += DoGiveInventory(mo, true, VM_ARGS_NAMES);
}
}
ACTION_RETURN_INT(count);
}
DEFINE_ACTION_FUNCTION(AActor, A_GiveToSiblings)
{
PARAM_SELF_PROLOGUE(AActor);
TThinkerIterator<AActor> it;
AActor *mo;
int count = 0;
if (self->master != NULL)
{
while ((mo = it.Next()))
{
if (mo->master == self->master && mo != self)
{
count += DoGiveInventory(mo, true, VM_ARGS_NAMES);
}
}
}
ACTION_RETURN_INT(count);
}
//===========================================================================
//
// A_SetInventory
//
//===========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_SetInventory)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_CLASS(itemtype, AInventory);
PARAM_INT(amount);
PARAM_INT_DEF(ptr);
PARAM_BOOL_DEF(beyondMax);
bool res = false;
if (itemtype == nullptr)
{
ACTION_RETURN_BOOL(false);
}
AActor *mobj = COPY_AAPTR(self, ptr);
if (mobj == nullptr)
{
ACTION_RETURN_BOOL(false);
}
AInventory *item = mobj->FindInventory(itemtype);
if (item != nullptr)
{
// A_SetInventory sets the absolute amount.
// Subtract or set the appropriate amount as necessary.
if (amount == item->Amount)
{
// Nothing was changed.
ACTION_RETURN_BOOL(false);
}
else if (amount <= 0)
{
//Remove it all.
res = (mobj->TakeInventory(itemtype, item->Amount, true, false));
ACTION_RETURN_BOOL(res);
}
else if (amount < item->Amount)
{
int amt = abs(item->Amount - amount);
res = (mobj->TakeInventory(itemtype, amt, true, false));
ACTION_RETURN_BOOL(res);
}
else
{
item->Amount = (beyondMax ? amount : clamp(amount, 0, item->MaxAmount));
ACTION_RETURN_BOOL(true);
}
}
else
{
if (amount <= 0)
{
ACTION_RETURN_BOOL(false);
}
item = static_cast<AInventory *>(Spawn(itemtype));
if (item == nullptr)
{
ACTION_RETURN_BOOL(false);
}
else
{
item->Amount = amount;
item->flags |= MF_DROPPED;
item->ItemFlags |= IF_IGNORESKILL;
item->ClearCounters();
if (!item->CallTryPickup(mobj))
{
item->Destroy();
ACTION_RETURN_BOOL(false);
}
ACTION_RETURN_BOOL(true);
}
}
ACTION_RETURN_BOOL(false);
}
//===========================================================================
//
// A_TakeInventory
//
//===========================================================================
enum
{
TIF_NOTAKEINFINITE = 1,
};
bool DoTakeInventory(AActor *receiver, bool orresult, VM_ARGS)
{
int paramnum = 0;
PARAM_CLASS (itemtype, AInventory);
PARAM_INT_DEF (amount);
PARAM_INT_DEF (flags);
if (itemtype == NULL)
{
return false;
}
if (!orresult)
{
PARAM_INT_DEF(setreceiver);
receiver = COPY_AAPTR(receiver, setreceiver);
}
if (receiver == NULL)
{
return false;
}
return receiver->TakeInventory(itemtype, amount, true, (flags & TIF_NOTAKEINFINITE) != 0);
}
DEFINE_ACTION_FUNCTION(AActor, A_TakeInventory)
{
PARAM_SELF_PROLOGUE(AActor);
ACTION_RETURN_BOOL(DoTakeInventory(self, false, VM_ARGS_NAMES));
}
DEFINE_ACTION_FUNCTION(AActor, A_TakeFromTarget)
{
PARAM_SELF_PROLOGUE(AActor);
ACTION_RETURN_BOOL(DoTakeInventory(self->target, false, VM_ARGS_NAMES));
}
DEFINE_ACTION_FUNCTION(AActor, A_TakeFromChildren)
{
PARAM_SELF_PROLOGUE(AActor);
TThinkerIterator<AActor> it;
AActor *mo;
int count = 0;
while ((mo = it.Next()))
{
if (mo->master == self)
{
count += DoTakeInventory(mo, true, VM_ARGS_NAMES);
}
}
ACTION_RETURN_INT(count);
}
DEFINE_ACTION_FUNCTION(AActor, A_TakeFromSiblings)
{
PARAM_SELF_PROLOGUE(AActor);
TThinkerIterator<AActor> it;
AActor *mo;
int count = 0;
if (self->master != NULL)
{
while ((mo = it.Next()))
{
if (mo->master == self->master && mo != self)
{
count += DoTakeInventory(mo, true, VM_ARGS_NAMES);
}
}
}
ACTION_RETURN_INT(count);
}
//===========================================================================
//
// Common code for A_SpawnItem and A_SpawnItemEx
//
//===========================================================================
enum SIX_Flags
{
SIXF_TRANSFERTRANSLATION = 0x00000001,
SIXF_ABSOLUTEPOSITION = 0x00000002,
SIXF_ABSOLUTEANGLE = 0x00000004,
SIXF_ABSOLUTEVELOCITY = 0x00000008,
SIXF_SETMASTER = 0x00000010,
SIXF_NOCHECKPOSITION = 0x00000020,
SIXF_TELEFRAG = 0x00000040,
SIXF_CLIENTSIDE = 0x00000080, // only used by Skulldronum
SIXF_TRANSFERAMBUSHFLAG = 0x00000100,
SIXF_TRANSFERPITCH = 0x00000200,
SIXF_TRANSFERPOINTERS = 0x00000400,
SIXF_USEBLOODCOLOR = 0x00000800,
SIXF_CLEARCALLERTID = 0x00001000,
SIXF_MULTIPLYSPEED = 0x00002000,
SIXF_TRANSFERSCALE = 0x00004000,
SIXF_TRANSFERSPECIAL = 0x00008000,
SIXF_CLEARCALLERSPECIAL = 0x00010000,
SIXF_TRANSFERSTENCILCOL = 0x00020000,
SIXF_TRANSFERALPHA = 0x00040000,
SIXF_TRANSFERRENDERSTYLE = 0x00080000,
SIXF_SETTARGET = 0x00100000,
SIXF_SETTRACER = 0x00200000,
SIXF_NOPOINTERS = 0x00400000,
SIXF_ORIGINATOR = 0x00800000,
SIXF_TRANSFERSPRITEFRAME = 0x01000000,
SIXF_TRANSFERROLL = 0x02000000,
SIXF_ISTARGET = 0x04000000,
SIXF_ISMASTER = 0x08000000,
SIXF_ISTRACER = 0x10000000,
};
static bool InitSpawnedItem(AActor *self, AActor *mo, int flags)
{
if (mo == NULL)
{
return false;
}
AActor *originator = self;
if (!(mo->flags2 & MF2_DONTTRANSLATE))
{
if (flags & SIXF_TRANSFERTRANSLATION)
{
mo->Translation = self->Translation;
}
else if (flags & SIXF_USEBLOODCOLOR)
{
// [XA] Use the spawning actor's BloodColor to translate the newly-spawned object.
PalEntry bloodcolor = self->GetBloodColor();
mo->Translation = TRANSLATION(TRANSLATION_Blood, bloodcolor.a);
}
}
if (flags & SIXF_TRANSFERPOINTERS)
{
mo->target = self->target;
mo->master = self->master; // This will be overridden later if SIXF_SETMASTER is set
mo->tracer = self->tracer;
}
mo->Angles.Yaw = self->Angles.Yaw;
if (flags & SIXF_TRANSFERPITCH)
{
mo->Angles.Pitch = self->Angles.Pitch;
}
if (!(flags & SIXF_ORIGINATOR))
{
while (originator && originator->isMissile())
{
originator = originator->target;
}
}
if (flags & SIXF_TELEFRAG)
{
P_TeleportMove(mo, mo->Pos(), true);
// This is needed to ensure consistent behavior.
// Otherwise it will only spawn if nothing gets telefragged
flags |= SIXF_NOCHECKPOSITION;
}
if (mo->flags3 & MF3_ISMONSTER)
{
if (!(flags & SIXF_NOCHECKPOSITION) && !P_TestMobjLocation(mo))
{
// The monster is blocked so don't spawn it at all!
mo->ClearCounters();
mo->Destroy();
return false;
}
else if (originator && !(flags & SIXF_NOPOINTERS))
{
if (originator->flags3 & MF3_ISMONSTER)
{
// If this is a monster transfer all friendliness information
mo->CopyFriendliness(originator, true);
}
else if (originator->player)
{
// A player always spawns a monster friendly to him
mo->flags |= MF_FRIENDLY;
mo->SetFriendPlayer(originator->player);
AActor * attacker=originator->player->attacker;
if (attacker)
{
if (!(attacker->flags&MF_FRIENDLY) ||
(deathmatch && attacker->FriendPlayer!=0 && attacker->FriendPlayer!=mo->FriendPlayer))
{
// Target the monster which last attacked the player
mo->LastHeard = mo->target = attacker;
}
}
}
}
}
else if (!(flags & SIXF_TRANSFERPOINTERS))
{
// If this is a missile or something else set the target to the originator
mo->target = originator ? originator : self;
}
if (flags & SIXF_NOPOINTERS)
{
//[MC]Intentionally eliminate pointers. Overrides TRANSFERPOINTERS, but is overridden by SETMASTER/TARGET/TRACER.
mo->LastHeard = NULL; //Sanity check.
mo->target = NULL;
mo->master = NULL;
mo->tracer = NULL;
}
if (flags & SIXF_SETMASTER)
{ // don't let it attack you (optional)!
mo->master = originator;
}
if (flags & SIXF_SETTARGET)
{
mo->target = originator;
}
if (flags & SIXF_SETTRACER)
{
mo->tracer = originator;
}
if (flags & SIXF_TRANSFERSCALE)
{
mo->Scale = self->Scale;
}
if (flags & SIXF_TRANSFERAMBUSHFLAG)
{
mo->flags = (mo->flags & ~MF_AMBUSH) | (self->flags & MF_AMBUSH);
}
if (flags & SIXF_CLEARCALLERTID)
{
self->RemoveFromHash();
self->tid = 0;
}
if (flags & SIXF_TRANSFERSPECIAL)
{
mo->special = self->special;
memcpy(mo->args, self->args, sizeof(self->args));
}
if (flags & SIXF_CLEARCALLERSPECIAL)
{
self->special = 0;
memset(self->args, 0, sizeof(self->args));
}
if (flags & SIXF_TRANSFERSTENCILCOL)
{
mo->fillcolor = self->fillcolor;
}
if (flags & SIXF_TRANSFERALPHA)
{
mo->Alpha = self->Alpha;
}
if (flags & SIXF_TRANSFERRENDERSTYLE)
{
mo->RenderStyle = self->RenderStyle;
}
if (flags & SIXF_TRANSFERSPRITEFRAME)
{
mo->sprite = self->sprite;
mo->frame = self->frame;
}
if (flags & SIXF_TRANSFERROLL)
{
mo->Angles.Roll = self->Angles.Roll;
}
if (flags & SIXF_ISTARGET)
{
self->target = mo;
}
if (flags & SIXF_ISMASTER)
{
self->master = mo;
}
if (flags & SIXF_ISTRACER)
{
self->tracer = mo;
}
return true;
}
//===========================================================================
//
// A_SpawnItem
//
// Spawns an item in front of the caller like Heretic's time bomb
//
//===========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_SpawnItem)
{
PARAM_ACTION_PROLOGUE(AActor);
PARAM_CLASS_DEF (missile, AActor)
PARAM_FLOAT_DEF (distance)
PARAM_FLOAT_DEF (zheight)
PARAM_BOOL_DEF (useammo)
PARAM_BOOL_DEF (transfer_translation)
if (missile == NULL)
{
ACTION_RETURN_BOOL(false);
}
// Don't spawn monsters if this actor has been massacred
if (self->DamageType == NAME_Massacre && (GetDefaultByType(missile)->flags3 & MF3_ISMONSTER))
{
ACTION_RETURN_BOOL(true);
}
if (ACTION_CALL_FROM_PSPRITE())
{
// Used from a weapon, so use some ammo
AWeapon *weapon = self->player->ReadyWeapon;
if (weapon == NULL)
{
ACTION_RETURN_BOOL(true);
}
if (useammo && !weapon->DepleteAmmo(weapon->bAltFire))
{
ACTION_RETURN_BOOL(true);
}
}
AActor *mo = Spawn( missile, self->Vec3Angle(distance, self->Angles.Yaw, -self->Floorclip + self->GetBobOffset() + zheight), ALLOW_REPLACE);
int flags = (transfer_translation ? SIXF_TRANSFERTRANSLATION : 0) + (useammo ? SIXF_SETMASTER : 0);
ACTION_RETURN_BOOL(InitSpawnedItem(self, mo, flags)); // for an inventory item's use state
}
//===========================================================================
//
// A_SpawnItemEx
//
// Enhanced spawning function
//
//===========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_SpawnItemEx)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_CLASS (missile, AActor);
PARAM_FLOAT_DEF (xofs)
PARAM_FLOAT_DEF (yofs)
PARAM_FLOAT_DEF (zofs)
PARAM_FLOAT_DEF (xvel)
PARAM_FLOAT_DEF (yvel)
PARAM_FLOAT_DEF (zvel)
PARAM_ANGLE_DEF (angle)
PARAM_INT_DEF (flags)
PARAM_INT_DEF (chance)
PARAM_INT_DEF (tid)
if (missile == NULL)
{
ACTION_RETURN_BOOL(false);
}
if (chance > 0 && pr_spawnitemex() < chance)
{
ACTION_RETURN_BOOL(true);
}
// Don't spawn monsters if this actor has been massacred
if (self->DamageType == NAME_Massacre && (GetDefaultByType(missile)->flags3 & MF3_ISMONSTER))
{
ACTION_RETURN_BOOL(true);
}
DVector2 pos;
if (!(flags & SIXF_ABSOLUTEANGLE))
{
angle += self->Angles.Yaw;
}
double s = angle.Sin();
double c = angle.Cos();
if (flags & SIXF_ABSOLUTEPOSITION)
{
pos = self->Vec2Offset(xofs, yofs);
}
else
{
// in relative mode negative y values mean 'left' and positive ones mean 'right'
// This is the inverse orientation of the absolute mode!
pos = self->Vec2Offset(xofs * c + yofs * s, xofs * s - yofs*c);
}
if (!(flags & SIXF_ABSOLUTEVELOCITY))
{
// Same orientation issue here!
double newxvel = xvel * c + yvel * s;
yvel = xvel * s - yvel * c;
xvel = newxvel;
}
AActor *mo = Spawn(missile, DVector3(pos, self->Z() - self->Floorclip + self->GetBobOffset() + zofs), ALLOW_REPLACE);
bool res = InitSpawnedItem(self, mo, flags);
if (res)
{
if (tid != 0)
{
assert(mo->tid == 0);
mo->tid = tid;
mo->AddToHash();
}
mo->Vel = {xvel, yvel, zvel};
if (flags & SIXF_MULTIPLYSPEED)
{
mo->Vel *= mo->Speed;
}
mo->Angles.Yaw = angle;
}
ACTION_RETURN_BOOL(res); // for an inventory item's use state
}
//===========================================================================
//
// A_ThrowGrenade
//
// Throws a grenade (like Hexen's fighter flechette)
//
//===========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_ThrowGrenade)
{
PARAM_ACTION_PROLOGUE(AActor);
PARAM_CLASS (missile, AActor);
PARAM_FLOAT_DEF (zheight)
PARAM_FLOAT_DEF (xyvel)
PARAM_FLOAT_DEF (zvel)
PARAM_BOOL_DEF (useammo)
if (missile == NULL)
{
ACTION_RETURN_BOOL(true);
}
if (ACTION_CALL_FROM_PSPRITE())
{
// Used from a weapon, so use some ammo
AWeapon *weapon = self->player->ReadyWeapon;
if (weapon == NULL)
{
ACTION_RETURN_BOOL(true);
}
if (useammo && !weapon->DepleteAmmo(weapon->bAltFire))
{
ACTION_RETURN_BOOL(true);
}
}
AActor *bo;
bo = Spawn(missile,
self->PosPlusZ(-self->Floorclip + self->GetBobOffset() + zheight + 35 + (self->player? self->player->crouchoffset : 0.)),
ALLOW_REPLACE);
if (bo)
{
P_PlaySpawnSound(bo, self);
if (xyvel != 0)
bo->Speed = xyvel;
bo->Angles.Yaw = self->Angles.Yaw + (((pr_grenade()&7) - 4) * (360./256.));
DAngle pitch = -self->Angles.Pitch;
DAngle angle = bo->Angles.Yaw;
// There are two vectors we are concerned about here: xy and z. We rotate
// them separately according to the shooter's pitch and then sum them to
// get the final velocity vector to shoot with.
double xy_xyscale = bo->Speed * pitch.Cos();
double xy_velz = bo->Speed * pitch.Sin();
double xy_velx = xy_xyscale * angle.Cos();
double xy_vely = xy_xyscale * angle.Sin();
pitch = self->Angles.Pitch;
double z_xyscale = zvel * pitch.Sin();
double z_velz = zvel * pitch.Cos();
double z_velx = z_xyscale * angle.Cos();
double z_vely = z_xyscale * angle.Sin();
bo->Vel.X = xy_velx + z_velx + self->Vel.X / 2;
bo->Vel.Y = xy_vely + z_vely + self->Vel.Y / 2;
bo->Vel.Z = xy_velz + z_velz;
bo->target = self;
P_CheckMissileSpawn (bo, self->radius);
}
else
{
ACTION_RETURN_BOOL(false);
}
ACTION_RETURN_BOOL(true);
}
//===========================================================================
//
// A_Recoil
//
//===========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_Recoil)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_FLOAT(xyvel);
self->Thrust(self->Angles.Yaw + 180., xyvel);
return 0;
}
//===========================================================================
//
// A_SelectWeapon
//
//===========================================================================
enum SW_Flags
{
SWF_SELECTPRIORITY = 1,
};
DEFINE_ACTION_FUNCTION(AActor, A_SelectWeapon)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_CLASS(cls, AWeapon);
PARAM_INT_DEF(flags);
bool selectPriority = !!(flags & SWF_SELECTPRIORITY);
if ((!selectPriority && cls == NULL) || self->player == NULL)
{
ACTION_RETURN_BOOL(false);
}
AWeapon *weaponitem = static_cast<AWeapon*>(self->FindInventory(cls));
if (weaponitem != NULL && weaponitem->IsKindOf(RUNTIME_CLASS(AWeapon)))
{
if (self->player->ReadyWeapon != weaponitem)
{
self->player->PendingWeapon = weaponitem;
}
ACTION_RETURN_BOOL(true);
}
else if (selectPriority)
{
// [XA] if the named weapon cannot be found (or is a dummy like 'None'),
// select the next highest priority weapon. This is basically
// the same as A_CheckReload minus the ammo check. Handy.
self->player->mo->PickNewWeapon(NULL);
ACTION_RETURN_BOOL(true);
}
else
{
ACTION_RETURN_BOOL(false);
}
}
//===========================================================================
//
// A_Print
//
//===========================================================================
EXTERN_CVAR(Float, con_midtime)
DEFINE_ACTION_FUNCTION(AActor, A_Print)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_STRING (text);
PARAM_FLOAT_DEF (time);
PARAM_NAME_DEF (fontname);
if (text[0] == '$') text = GStrings(&text[1]);
if (self->CheckLocalView (consoleplayer) ||
(self->target != NULL && self->target->CheckLocalView (consoleplayer)))
{
float saved = con_midtime;
FFont *font = NULL;
if (fontname != NAME_None)
{
font = V_GetFont(fontname);
}
if (time > 0)
{
con_midtime = float(time);
}
FString formatted = strbin1(text);
C_MidPrint(font != NULL ? font : SmallFont, formatted.GetChars());
con_midtime = saved;
}
return 0;
}
//===========================================================================
//
// A_PrintBold
//
//===========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_PrintBold)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_STRING (text);
PARAM_FLOAT_DEF (time);
PARAM_NAME_DEF (fontname);
float saved = con_midtime;
FFont *font = NULL;
if (text[0] == '$') text = GStrings(&text[1]);
if (fontname != NAME_None)
{
font = V_GetFont(fontname);
}
if (time > 0)
{
con_midtime = float(time);
}
FString formatted = strbin1(text);
C_MidPrintBold(font != NULL ? font : SmallFont, formatted.GetChars());
con_midtime = saved;
return 0;
}
//===========================================================================
//
// A_Log
//
//===========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_Log)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_STRING(text);
if (text[0] == '$') text = GStrings(&text[1]);
FString formatted = strbin1(text);
Printf("%s\n", formatted.GetChars());
return 0;
}
//=========================================================================
//
// A_LogInt
//
//===========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_LogInt)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_INT(num);
Printf("%d\n", num);
return 0;
}
//=========================================================================
//
// A_LogFloat
//
//===========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_LogFloat)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_FLOAT(num);
IGNORE_FORMAT_PRE
Printf("%H\n", num);
IGNORE_FORMAT_POST
return 0;
}
//===========================================================================
//
// A_SetTranslucent
//
//===========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_SetTranslucent)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_FLOAT (alpha);
PARAM_INT_DEF (mode);
mode = mode == 0 ? STYLE_Translucent : mode == 2 ? STYLE_Fuzzy : STYLE_Add;
self->RenderStyle.Flags &= ~STYLEF_Alpha1;
self->Alpha = clamp(alpha, 0., 1.);
self->RenderStyle = ERenderStyle(mode);
return 0;
}
//===========================================================================
//
// A_SetRenderStyle
//
//===========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_SetRenderStyle)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_FLOAT(alpha);
PARAM_INT_DEF(mode);
self->Alpha = clamp(alpha, 0., 1.);
self->RenderStyle = ERenderStyle(mode);
return 0;
}
//===========================================================================
//
// A_FadeIn
//
// Fades the actor in
//
//===========================================================================
enum FadeFlags
{
FTF_REMOVE = 1 << 0,
FTF_CLAMP = 1 << 1,
};
DEFINE_ACTION_FUNCTION(AActor, A_FadeIn)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_FLOAT_DEF(reduce);
PARAM_INT_DEF(flags);
if (reduce == 0)
{
reduce = 0.1;
}
self->RenderStyle.Flags &= ~STYLEF_Alpha1;
self->Alpha += reduce;
if (self->Alpha >= 1.)
{
if (flags & FTF_CLAMP)
{
self->Alpha = 1.;
}
if (flags & FTF_REMOVE)
{
P_RemoveThing(self);
}
}
return 0;
}
//===========================================================================
//
// A_FadeOut
//
// fades the actor out and destroys it when done
//
//===========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_FadeOut)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_FLOAT_DEF(reduce);
PARAM_INT_DEF(flags);
if (reduce == 0)
{
reduce = 0.1;
}
self->RenderStyle.Flags &= ~STYLEF_Alpha1;
self->Alpha -= reduce;
if (self->Alpha <= 0)
{
if (flags & FTF_CLAMP)
{
self->Alpha = 0;
}
if (flags & FTF_REMOVE)
{
P_RemoveThing(self);
}
}
return 0;
}
//===========================================================================
//
// A_FadeTo
//
// fades the actor to a specified transparency by a specified amount and
// destroys it if so desired
//
//===========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_FadeTo)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_FLOAT (target);
PARAM_FLOAT_DEF (amount);
PARAM_INT_DEF (flags);
self->RenderStyle.Flags &= ~STYLEF_Alpha1;
if (self->Alpha > target)
{
self->Alpha -= amount;
if (self->Alpha < target)
{
self->Alpha = target;
}
}
else if (self->Alpha < target)
{
self->Alpha += amount;
if (self->Alpha > target)
{
self->Alpha = target;
}
}
if (flags & FTF_CLAMP)
{
self->Alpha = clamp(self->Alpha, 0., 1.);
}
if (self->Alpha == target && (flags & FTF_REMOVE))
{
P_RemoveThing(self);
}
return 0;
}
//===========================================================================
//
// A_SpawnDebris
//
//===========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_SpawnDebris)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_CLASS (debris, AActor);
PARAM_BOOL_DEF (transfer_translation)
PARAM_FLOAT_DEF (mult_h)
PARAM_FLOAT_DEF (mult_v)
int i;
AActor *mo;
if (debris == NULL)
return 0;
// only positive values make sense here
if (mult_v <= 0) mult_v = 1;
if (mult_h <= 0) mult_h = 1;
for (i = 0; i < GetDefaultByType(debris)->health; i++)
{
double xo = (pr_spawndebris() - 128) / 16.;
double yo = (pr_spawndebris() - 128) / 16.;
double zo = pr_spawndebris()*self->Height / 256 + self->GetBobOffset();
mo = Spawn(debris, self->Vec3Offset(xo, yo, zo), ALLOW_REPLACE);
if (mo)
{
if (transfer_translation)
{
mo->Translation = self->Translation;
}
if (i < mo->GetClass()->NumOwnedStates)
{
mo->SetState (mo->GetClass()->OwnedStates + i);
}
mo->Vel.X = mult_h * pr_spawndebris.Random2() / 64.;
mo->Vel.Y = mult_h * pr_spawndebris.Random2() / 64.;
mo->Vel.Z = mult_v * ((pr_spawndebris() & 7) + 5);
}
}
return 0;
}
//===========================================================================
//
// A_SpawnParticle
//
//===========================================================================
enum SPFflag
{
SPF_FULLBRIGHT = 1,
SPF_RELPOS = 1 << 1,
SPF_RELVEL = 1 << 2,
SPF_RELACCEL = 1 << 3,
SPF_RELANG = 1 << 4,
SPF_NOTIMEFREEZE = 1 << 5,
};
DEFINE_ACTION_FUNCTION(AActor, A_SpawnParticle)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_COLOR (color);
PARAM_INT_DEF (flags)
PARAM_INT_DEF (lifetime)
PARAM_FLOAT_DEF (size)
PARAM_ANGLE_DEF (angle)
PARAM_FLOAT_DEF (xoff)
PARAM_FLOAT_DEF (yoff)
PARAM_FLOAT_DEF (zoff)
PARAM_FLOAT_DEF (xvel)
PARAM_FLOAT_DEF (yvel)
PARAM_FLOAT_DEF (zvel)
PARAM_FLOAT_DEF (accelx)
PARAM_FLOAT_DEF (accely)
PARAM_FLOAT_DEF (accelz)
PARAM_FLOAT_DEF (startalpha)
PARAM_FLOAT_DEF (fadestep)
PARAM_FLOAT_DEF (sizestep)
startalpha = clamp(startalpha, 0., 1.);
if (fadestep > 0) fadestep = clamp(fadestep, 0., 1.);
size = fabs(size);
if (lifetime != 0)
{
if (flags & SPF_RELANG) angle += self->Angles.Yaw;
double s = angle.Sin();
double c = angle.Cos();
DVector3 pos(xoff, yoff, zoff);
DVector3 vel(xvel, yvel, zvel);
DVector3 acc(accelx, accely, accelz);
//[MC] Code ripped right out of A_SpawnItemEx.
if (flags & SPF_RELPOS)
{
// in relative mode negative y values mean 'left' and positive ones mean 'right'
// This is the inverse orientation of the absolute mode!
pos.X = xoff * c + yoff * s;
pos.Y = xoff * s - yoff * c;
}
if (flags & SPF_RELVEL)
{
vel.X = xvel * c + yvel * s;
vel.Y = xvel * s - yvel * c;
}
if (flags & SPF_RELACCEL)
{
acc.X = accelx * c + accely * s;
acc.Y = accelx * s - accely * c;
}
P_SpawnParticle(self->Vec3Offset(pos), vel, acc, color, startalpha, lifetime, size, fadestep, sizestep, flags);
}
return 0;
}
//===========================================================================
//
// A_CheckSight
// jumps if no player can see this actor
//
//===========================================================================
DEFINE_ACTION_FUNCTION(AActor, CheckIfSeen)
{
PARAM_SELF_PROLOGUE(AActor);
for (int i = 0; i < MAXPLAYERS; i++)
{
if (playeringame[i])
{
// Always check sight from each player.
if (P_CheckSight(players[i].mo, self, SF_IGNOREVISIBILITY))
{
ACTION_RETURN_BOOL(false);
}
// If a player is viewing from a non-player, then check that too.
if (players[i].camera != NULL && players[i].camera->player == NULL &&
P_CheckSight(players[i].camera, self, SF_IGNOREVISIBILITY))
{
ACTION_RETURN_BOOL(false);
}
}
}
ACTION_RETURN_BOOL(true);
}
//===========================================================================
//
// A_CheckSightOrRange
// Jumps if this actor is out of range of all players *and* out of sight.
// Useful for maps with many multi-actor special effects.
//
//===========================================================================
static bool DoCheckSightOrRange(AActor *self, AActor *camera, double range, bool twodi, bool checksight)
{
if (camera == NULL)
{
return false;
}
// Check distance first, since it's cheaper than checking sight.
DVector2 pos = camera->Vec2To(self);
double dz;
double eyez = camera->Center();
if (eyez > self->Top())
{
dz = self->Top() - eyez;
}
else if (eyez < self->Z())
{
dz = self->Z() - eyez;
}
else
{
dz = 0;
}
double distance = DVector3(pos, twodi? 0. : dz).LengthSquared();
if (distance <= range)
{
// Within range
return true;
}
// Now check LOS.
if (checksight && P_CheckSight(camera, self, SF_IGNOREVISIBILITY))
{ // Visible
return true;
}
return false;
}
DEFINE_ACTION_FUNCTION(AActor, CheckSightOrRange)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_FLOAT(range);
PARAM_BOOL_DEF(twodi);
range *= range;
for (int i = 0; i < MAXPLAYERS; ++i)
{
if (playeringame[i])
{
// Always check from each player.
if (DoCheckSightOrRange(self, players[i].mo, range, twodi, true))
{
ACTION_RETURN_BOOL(false);
}
// If a player is viewing from a non-player, check that too.
if (players[i].camera != NULL && players[i].camera->player == NULL &&
DoCheckSightOrRange(self, players[i].camera, range, twodi, true))
{
ACTION_RETURN_BOOL(false);
}
}
}
ACTION_RETURN_BOOL(true);
}
DEFINE_ACTION_FUNCTION(AActor, CheckRange)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_FLOAT(range);
PARAM_BOOL_DEF(twodi);
range *= range;
for (int i = 0; i < MAXPLAYERS; ++i)
{
if (playeringame[i])
{
// Always check from each player.
if (DoCheckSightOrRange(self, players[i].mo, range, twodi, false))
{
ACTION_RETURN_BOOL(false);
}
// If a player is viewing from a non-player, check that too.
if (players[i].camera != NULL && players[i].camera->player == NULL &&
DoCheckSightOrRange(self, players[i].camera, range, twodi, false))
{
ACTION_RETURN_BOOL(false);
}
}
}
ACTION_RETURN_BOOL(true);
}
//===========================================================================
//
// Inventory drop
//
//===========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_DropInventory)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_CLASS(drop, AInventory);
if (drop)
{
AInventory *inv = self->FindInventory(drop);
if (inv)
{
self->DropInventory(inv);
}
}
return 0;
}
//===========================================================================
//
// A_SetBlend
//
//===========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_SetBlend)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_COLOR (color);
PARAM_FLOAT (alpha);
PARAM_INT (tics);
PARAM_COLOR_DEF (color2);
if (color == MAKEARGB(255,255,255,255))
color = 0;
if (color2 == MAKEARGB(255,255,255,255))
color2 = 0;
if (color2.a == 0)
color2 = color;
new DFlashFader(color.r/255.f, color.g/255.f, color.b/255.f, float(alpha),
color2.r/255.f, color2.g/255.f, color2.b/255.f, 0,
float(tics)/TICRATE, self);
return 0;
}
//===========================================================================
//
// A_CountdownArg
//
//===========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_CountdownArg)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_INT(cnt);
PARAM_STATE_DEF(state)
if (cnt<0 || cnt >= 5) return 0;
if (!self->args[cnt]--)
{
if (self->flags&MF_MISSILE)
{
P_ExplodeMissile(self, NULL, NULL);
}
else if (self->flags&MF_SHOOTABLE)
{
P_DamageMobj(self, NULL, NULL, self->health, NAME_None, DMG_FORCED);
}
else
{
if (state == nullptr) state = self->FindState(NAME_Death);
self->SetState(state);
}
}
return 0;
}
//============================================================================
//
// A_Burst
//
//============================================================================
DEFINE_ACTION_FUNCTION(AActor, A_Burst)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_CLASS(chunk, AActor);
int i, numChunks;
AActor * mo;
if (chunk == NULL)
{
return 0;
}
self->Vel.Zero();
self->Height = self->GetDefault()->Height;
// [RH] In Hexen, this creates a random number of shards (range [24,56])
// with no relation to the size of the self shattering. I think it should
// base the number of shards on the size of the dead thing, so bigger
// things break up into more shards than smaller things.
// An self with radius 20 and height 64 creates ~40 chunks.
numChunks = MAX<int> (4, int(self->radius * self->Height)/32);
i = (pr_burst.Random2()) % (numChunks/4);
for (i = MAX (24, numChunks + i); i >= 0; i--)
{
double xo = (pr_burst() - 128) * self->radius / 128;
double yo = (pr_burst() - 128) * self->radius / 128;
double zo = (pr_burst() * self->Height / 255);
mo = Spawn(chunk, self->Vec3Offset(xo, yo, zo), ALLOW_REPLACE);
if (mo)
{
mo->Vel.Z = 4 * (mo->Z() - self->Z()) / self->Height;
mo->Vel.X = pr_burst.Random2() / 128.;
mo->Vel.Y = pr_burst.Random2() / 128.;
mo->RenderStyle = self->RenderStyle;
mo->Alpha = self->Alpha;
mo->CopyFriendliness(self, true);
}
}
// [RH] Do some stuff to make this more useful outside Hexen
if (self->flags4 & MF4_BOSSDEATH)
{
A_BossDeath(self);
}
A_Unblock(self, true);
self->Destroy ();
return 0;
}
//===========================================================================
//
// A_Stop
// resets all velocity of the actor to 0
//
//===========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_Stop)
{
PARAM_SELF_PROLOGUE(AActor);
self->Vel.Zero();
if (self->player && self->player->mo == self && !(self->player->cheats & CF_PREDICTING))
{
self->player->mo->PlayIdle();
self->player->Vel.Zero();
}
return 0;
}
static void CheckStopped(AActor *self)
{
if (self->player != NULL &&
self->player->mo == self &&
!(self->player->cheats & CF_PREDICTING) && !self->Vel.isZero())
{
self->player->mo->PlayIdle();
self->player->Vel.Zero();
}
}
//===========================================================================
//
// A_Respawn
//
//===========================================================================
enum RS_Flags
{
RSF_FOG=1,
RSF_KEEPTARGET=2,
RSF_TELEFRAG=4,
};
DEFINE_ACTION_FUNCTION(AActor, A_Respawn)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_INT_DEF(flags);
bool oktorespawn = false;
DVector3 pos = self->Pos();
self->flags |= MF_SOLID;
self->Height = self->GetDefault()->Height;
self->radius = self->GetDefault()->radius;
self->RestoreSpecialPosition();
if (flags & RSF_TELEFRAG)
{
// [KS] DIE DIE DIE DIE erm *ahem* =)
oktorespawn = P_TeleportMove(self, self->Pos(), true, false);
}
else
{
oktorespawn = P_CheckPosition(self, self->Pos(), true);
}
if (oktorespawn)
{
AActor *defs = self->GetDefault();
self->health = defs->health;
// [KS] Don't keep target, because it could be self if the monster committed suicide
// ...Actually it's better off an option, so you have better control over monster behavior.
if (!(flags & RSF_KEEPTARGET))
{
self->target = NULL;
self->LastHeard = NULL;
self->lastenemy = NULL;
}
else
{
// Don't attack yourself (Re: "Marine targets itself after suicide")
if (self->target == self)
self->target = NULL;
if (self->lastenemy == self)
self->lastenemy = NULL;
}
self->flags = (defs->flags & ~MF_FRIENDLY) | (self->flags & MF_FRIENDLY);
self->flags2 = defs->flags2;
self->flags3 = (defs->flags3 & ~(MF3_NOSIGHTCHECK | MF3_HUNTPLAYERS)) | (self->flags3 & (MF3_NOSIGHTCHECK | MF3_HUNTPLAYERS));
self->flags4 = (defs->flags4 & ~MF4_NOHATEPLAYERS) | (self->flags4 & MF4_NOHATEPLAYERS);
self->flags5 = defs->flags5;
self->flags6 = defs->flags6;
self->flags7 = defs->flags7;
self->SetState (self->SpawnState);
self->renderflags &= ~RF_INVISIBLE;
if (flags & RSF_FOG)
{
P_SpawnTeleportFog(self, pos, true, true);
P_SpawnTeleportFog(self, self->Pos(), false, true);
}
if (self->CountsAsKill())
{
level.total_monsters++;
}
}
else
{
self->flags &= ~MF_SOLID;
}
return 0;
}
//==========================================================================
//
// A_PlayerSkinCheck
//
//==========================================================================
DEFINE_ACTION_FUNCTION(AActor, PlayerSkinCheck)
{
PARAM_SELF_PROLOGUE(AActor);
ACTION_RETURN_BOOL(self->player != NULL &&
skins[self->player->userinfo.GetSkin()].othergame);
}
// [KS] *** Start of my modifications ***
//==========================================================================
//
// A_CheckLOF (state jump, int flags = CRF_AIM_VERT|CRF_AIM_HOR,
// fixed range = 0, angle angle = 0, angle pitch = 0,
// fixed offsetheight = 32, fixed offsetwidth = 0,
// int ptr_target = AAPTR_DEFAULT (target) )
//
//==========================================================================
enum CLOF_flags
{
CLOFF_NOAIM_VERT = 0x00000001,
CLOFF_NOAIM_HORZ = 0x00000002,
CLOFF_JUMPENEMY = 0x00000004,
CLOFF_JUMPFRIEND = 0x00000008,
CLOFF_JUMPOBJECT = 0x00000010,
CLOFF_JUMPNONHOSTILE = 0x00000020,
CLOFF_SKIPENEMY = 0x00000040,
CLOFF_SKIPFRIEND = 0x00000080,
CLOFF_SKIPOBJECT = 0x00000100,
CLOFF_SKIPNONHOSTILE = 0x00000200,
CLOFF_MUSTBESHOOTABLE = 0x00000400,
CLOFF_SKIPTARGET = 0x00000800,
CLOFF_ALLOWNULL = 0x00001000,
CLOFF_CHECKPARTIAL = 0x00002000,
CLOFF_MUSTBEGHOST = 0x00004000,
CLOFF_IGNOREGHOST = 0x00008000,
CLOFF_MUSTBESOLID = 0x00010000,
CLOFF_BEYONDTARGET = 0x00020000,
CLOFF_FROMBASE = 0x00040000,
CLOFF_MUL_HEIGHT = 0x00080000,
CLOFF_MUL_WIDTH = 0x00100000,
CLOFF_JUMP_ON_MISS = 0x00200000,
CLOFF_AIM_VERT_NOOFFSET = 0x00400000,
CLOFF_SETTARGET = 0x00800000,
CLOFF_SETMASTER = 0x01000000,
CLOFF_SETTRACER = 0x02000000,
};
struct LOFData
{
AActor *Self;
AActor *Target;
int Flags;
bool BadActor;
};
ETraceStatus CheckLOFTraceFunc(FTraceResults &trace, void *userdata)
{
LOFData *data = (LOFData *)userdata;
int flags = data->Flags;
if (trace.HitType != TRACE_HitActor)
{
return TRACE_Stop;
}
if (trace.Actor == data->Target)
{
if (flags & CLOFF_SKIPTARGET)
{
if (flags & CLOFF_BEYONDTARGET)
{
return TRACE_Skip;
}
return TRACE_Abort;
}
return TRACE_Stop;
}
if (flags & CLOFF_MUSTBESHOOTABLE)
{ // all shootability checks go here
if (!(trace.Actor->flags & MF_SHOOTABLE))
{
return TRACE_Skip;
}
if (trace.Actor->flags2 & MF2_NONSHOOTABLE)
{
return TRACE_Skip;
}
}
if ((flags & CLOFF_MUSTBESOLID) && !(trace.Actor->flags & MF_SOLID))
{
return TRACE_Skip;
}
if (flags & CLOFF_MUSTBEGHOST)
{
if (!(trace.Actor->flags3 & MF3_GHOST))
{
return TRACE_Skip;
}
}
else if (flags & CLOFF_IGNOREGHOST)
{
if (trace.Actor->flags3 & MF3_GHOST)
{
return TRACE_Skip;
}
}
if (
((flags & CLOFF_JUMPENEMY) && data->Self->IsHostile(trace.Actor)) ||
((flags & CLOFF_JUMPFRIEND) && data->Self->IsFriend(trace.Actor)) ||
((flags & CLOFF_JUMPOBJECT) && !(trace.Actor->flags3 & MF3_ISMONSTER)) ||
((flags & CLOFF_JUMPNONHOSTILE) && (trace.Actor->flags3 & MF3_ISMONSTER) && !data->Self->IsHostile(trace.Actor))
)
{
return TRACE_Stop;
}
if (
((flags & CLOFF_SKIPENEMY) && data->Self->IsHostile(trace.Actor)) ||
((flags & CLOFF_SKIPFRIEND) && data->Self->IsFriend(trace.Actor)) ||
((flags & CLOFF_SKIPOBJECT) && !(trace.Actor->flags3 & MF3_ISMONSTER)) ||
((flags & CLOFF_SKIPNONHOSTILE) && (trace.Actor->flags3 & MF3_ISMONSTER) && !data->Self->IsHostile(trace.Actor))
)
{
return TRACE_Skip;
}
data->BadActor = true;
return TRACE_Abort;
}
DEFINE_ACTION_FUNCTION(AActor, CheckLOF)
{
// Check line of fire
/*
Not accounted for / I don't know how it works: FLOORCLIP
*/
AActor *target;
DVector3 pos;
DVector3 vel;
PARAM_SELF_PROLOGUE(AActor);
PARAM_INT_DEF (flags)
PARAM_FLOAT_DEF (range)
PARAM_FLOAT_DEF (minrange)
PARAM_ANGLE_DEF (angle)
PARAM_ANGLE_DEF (pitch)
PARAM_FLOAT_DEF (offsetheight)
PARAM_FLOAT_DEF (offsetwidth)
PARAM_INT_DEF (ptr_target)
PARAM_FLOAT_DEF (offsetforward)
DAngle ang;
target = COPY_AAPTR(self, ptr_target == AAPTR_DEFAULT ? AAPTR_TARGET|AAPTR_PLAYER_GETTARGET|AAPTR_NULL : ptr_target); // no player-support by default
if (flags & CLOFF_MUL_HEIGHT)
{
if (self->player != NULL)
{
// Synced with hitscan: self->player->mo->height is strangely conscientious about getting the right actor for player
offsetheight *= self->player->mo->Height * self->player->crouchfactor;
}
else
{
offsetheight *= self->Height;
}
}
if (flags & CLOFF_MUL_WIDTH)
{
offsetforward *= self->radius;
offsetwidth *= self->radius;
}
pos = self->PosPlusZ(offsetheight - self->Floorclip);
if (!(flags & CLOFF_FROMBASE))
{ // default to hitscan origin
// Synced with hitscan: self->Height is strangely NON-conscientious about getting the right actor for player
pos.Z += self->Height *0.5;
if (self->player != NULL)
{
pos.Z += self->player->mo->AttackZOffset * self->player->crouchfactor;
}
else
{
pos.Z += 8;
}
}
if (target)
{
if (range > 0 && !(flags & CLOFF_CHECKPARTIAL))
{
double distance = self->Distance3D(target);
if (distance > range)
{
ACTION_RETURN_BOOL(false);
}
}
if (flags & CLOFF_NOAIM_HORZ)
{
ang = self->Angles.Yaw;
}
else ang = self->AngleTo (target);
angle += ang;
double s = ang.Sin();
double c = ang.Cos();
DVector2 xy = self->Vec2Offset(offsetforward * c + offsetwidth * s, offsetforward * s - offsetwidth * c);
pos.X = xy.X;
pos.Y = xy.Y;
double xydist = self->Distance2D(target);
if (flags & CLOFF_NOAIM_VERT)
{
pitch += self->Angles.Pitch;
}
else if (flags & CLOFF_AIM_VERT_NOOFFSET)
{
pitch -= VecToAngle(xydist, target->Center() - pos.Z + offsetheight);
}
else
{
pitch -= VecToAngle(xydist, target->Center() - pos.Z);
}
}
else if (flags & CLOFF_ALLOWNULL)
{
angle += self->Angles.Yaw;
pitch += self->Angles.Pitch;
double s = angle.Sin();
double c = angle.Cos();
DVector2 xy = self->Vec2Offset(offsetforward * c + offsetwidth * s, offsetforward * s - offsetwidth * c);
pos.X = xy.X;
pos.Y = xy.Y;
}
else
{
ACTION_RETURN_BOOL(false);
}
double cp = pitch.Cos();
vel = { cp * angle.Cos(), cp * angle.Sin(), -pitch.Sin() };
/* Variable set:
jump, flags, target
pos (trace point of origin)
vel (trace unit vector)
range
*/
sector_t *sec = P_PointInSector(pos);
if (range == 0)
{
range = (self->player != NULL) ? PLAYERMISSILERANGE : MISSILERANGE;
}
FTraceResults trace;
LOFData lof_data;
lof_data.Self = self;
lof_data.Target = target;
lof_data.Flags = flags;
lof_data.BadActor = false;
Trace(pos, sec, vel, range, ActorFlags::FromInt(0xFFFFFFFF), ML_BLOCKEVERYTHING, self, trace, TRACE_PortalRestrict,
CheckLOFTraceFunc, &lof_data);
if (trace.HitType == TRACE_HitActor ||
((flags & CLOFF_JUMP_ON_MISS) && !lof_data.BadActor && trace.HitType != TRACE_HitNone))
{
if (minrange > 0 && trace.Distance < minrange)
{
ACTION_RETURN_BOOL(false);
}
if ((trace.HitType == TRACE_HitActor) && (trace.Actor != NULL) && !(lof_data.BadActor))
{
if (flags & (CLOFF_SETTARGET)) self->target = trace.Actor;
if (flags & (CLOFF_SETMASTER)) self->master = trace.Actor;
if (flags & (CLOFF_SETTRACER)) self->tracer = trace.Actor;
}
ACTION_RETURN_BOOL(true);
}
ACTION_RETURN_BOOL(false);
}
//==========================================================================
//
// A_JumpIfTargetInLOS (state label, optional fixed fov, optional int flags,
// optional fixed dist_max, optional fixed dist_close)
//
// Jumps if the actor can see its target, or if the player has a linetarget.
// ProjectileTarget affects how projectiles are treated. If set, it will use
// the target of the projectile for seekers, and ignore the target for
// normal projectiles. If not set, it will use the missile's owner instead
// (the default). ProjectileTarget is now flag JLOSF_PROJECTILE. dist_max
// sets the maximum distance that actor can see, 0 means forever. dist_close
// uses special behavior if certain flags are set, 0 means no checks.
//
//==========================================================================
enum JLOS_flags
{
JLOSF_PROJECTILE = 1 << 0,
JLOSF_NOSIGHT = 1 << 1,
JLOSF_CLOSENOFOV = 1 << 2,
JLOSF_CLOSENOSIGHT = 1 << 3,
JLOSF_CLOSENOJUMP = 1 << 4,
JLOSF_DEADNOJUMP = 1 << 5,
JLOSF_CHECKMASTER = 1 << 6,
JLOSF_TARGETLOS = 1 << 7,
JLOSF_FLIPFOV = 1 << 8,
JLOSF_ALLYNOJUMP = 1 << 9,
JLOSF_COMBATANTONLY = 1 << 10,
JLOSF_NOAUTOAIM = 1 << 11,
JLOSF_CHECKTRACER = 1 << 12,
};
DEFINE_ACTION_FUNCTION(AActor, CheckIfTargetInLOS)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_ANGLE_DEF (fov)
PARAM_INT_DEF (flags)
PARAM_FLOAT_DEF (dist_max)
PARAM_FLOAT_DEF (dist_close)
AActor *target, *viewport;
FTranslatedLineTarget t;
bool doCheckSight;
if (!self->player)
{
if (flags & JLOSF_CHECKMASTER)
{
target = self->master;
}
else if ((self->flags & MF_MISSILE && (flags & JLOSF_PROJECTILE)) || (flags & JLOSF_CHECKTRACER))
{
if ((self->flags2 & MF2_SEEKERMISSILE) || (flags & JLOSF_CHECKTRACER))
target = self->tracer;
else
target = NULL;
}
else
{
target = self->target;
}
if (target == NULL)
{ // [KS] Let's not call P_CheckSight unnecessarily in this case.
ACTION_RETURN_BOOL(false);
}
if ((flags & JLOSF_DEADNOJUMP) && (target->health <= 0))
{
ACTION_RETURN_BOOL(false);
}
doCheckSight = !(flags & JLOSF_NOSIGHT);
}
else
{
// Does the player aim at something that can be shot?
P_AimLineAttack(self, self->Angles.Yaw, MISSILERANGE, &t, (flags & JLOSF_NOAUTOAIM) ? 0.5 : 0., ALF_PORTALRESTRICT);
if (!t.linetarget)
{
ACTION_RETURN_BOOL(false);
}
target = t.linetarget;
switch (flags & (JLOSF_TARGETLOS|JLOSF_FLIPFOV))
{
case JLOSF_TARGETLOS|JLOSF_FLIPFOV:
// target makes sight check, player makes fov check; player has verified fov
fov = 0.;
// fall-through
case JLOSF_TARGETLOS:
doCheckSight = !(flags & JLOSF_NOSIGHT); // The target is responsible for sight check and fov
break;
default:
// player has verified sight and fov
fov = 0.;
// fall-through
case JLOSF_FLIPFOV: // Player has verified sight, but target must verify fov
doCheckSight = false;
break;
}
}
// [FDARI] If target is not a combatant, don't jump
if ( (flags & JLOSF_COMBATANTONLY) && (!target->player) && !(target->flags3 & MF3_ISMONSTER))
{
ACTION_RETURN_BOOL(false);
}
// [FDARI] If actors share team, don't jump
if ((flags & JLOSF_ALLYNOJUMP) && self->IsFriend(target))
{
ACTION_RETURN_BOOL(false);
}
double distance = self->Distance3D(target);
if (dist_max && (distance > dist_max))
{
ACTION_RETURN_BOOL(false);
}
if (dist_close && (distance < dist_close))
{
if (flags & JLOSF_CLOSENOJUMP)
{
ACTION_RETURN_BOOL(false);
}
if (flags & JLOSF_CLOSENOFOV)
fov = 0.;
if (flags & JLOSF_CLOSENOSIGHT)
doCheckSight = false;
}
if (flags & JLOSF_TARGETLOS) { viewport = target; target = self; }
else { viewport = self; }
if (doCheckSight && !P_CheckSight (viewport, target, SF_IGNOREVISIBILITY))
{
ACTION_RETURN_BOOL(false);
}
if (flags & JLOSF_FLIPFOV)
{
if (viewport == self) { viewport = target; target = self; }
else { target = viewport; viewport = self; }
}
fov = MIN<DAngle>(fov, 360.);
if (fov > 0)
{
DAngle an = absangle(viewport->AngleTo(target), viewport->Angles.Yaw);
if (an > (fov / 2))
{
ACTION_RETURN_BOOL(false); // [KS] Outside of FOV - return
}
}
ACTION_RETURN_BOOL(true);
}
//==========================================================================
//
// A_JumpIfInTargetLOS (state label, optional fixed fov, optional int flags
// optional fixed dist_max, optional fixed dist_close)
//
//==========================================================================
DEFINE_ACTION_FUNCTION(AActor, CheckIfInTargetLOS)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_ANGLE_DEF (fov)
PARAM_INT_DEF (flags)
PARAM_FLOAT_DEF (dist_max)
PARAM_FLOAT_DEF (dist_close)
AActor *target;
if (flags & JLOSF_CHECKMASTER)
{
target = self->master;
}
else if (self->flags & MF_MISSILE && (flags & JLOSF_PROJECTILE))
{
if (self->flags2 & MF2_SEEKERMISSILE)
target = self->tracer;
else
target = NULL;
}
else
{
target = self->target;
}
if (target == NULL)
{ // [KS] Let's not call P_CheckSight unnecessarily in this case.
ACTION_RETURN_BOOL(false);
}
if ((flags & JLOSF_DEADNOJUMP) && (target->health <= 0))
{
ACTION_RETURN_BOOL(false);
}
double distance = self->Distance3D(target);
if (dist_max && (distance > dist_max))
{
ACTION_RETURN_BOOL(false);
}
bool doCheckSight = !(flags & JLOSF_NOSIGHT);
if (dist_close && (distance < dist_close))
{
if (flags & JLOSF_CLOSENOJUMP)
{
ACTION_RETURN_BOOL(false);
}
if (flags & JLOSF_CLOSENOFOV)
fov = 0.;
if (flags & JLOSF_CLOSENOSIGHT)
doCheckSight = false;
}
if (fov > 0 && (fov < 360.))
{
DAngle an = absangle(target->AngleTo(self), target->Angles.Yaw);
if (an > (fov / 2))
{
ACTION_RETURN_BOOL(false); // [KS] Outside of FOV - return
}
}
if (doCheckSight && !P_CheckSight (target, self, SF_IGNOREVISIBILITY))
{
ACTION_RETURN_BOOL(false);
}
ACTION_RETURN_BOOL(true);
}
//===========================================================================
//
// Modified code pointer from Skulltag
//
//===========================================================================
DEFINE_ACTION_FUNCTION(AStateProvider, A_CheckForReload)
{
PARAM_ACTION_PROLOGUE(AStateProvider);
if ( self->player == NULL || self->player->ReadyWeapon == NULL )
{
ACTION_RETURN_STATE(NULL);
}
PARAM_INT (count);
PARAM_STATE_ACTION (jump);
PARAM_BOOL_DEF (dontincrement);
if (numret > 0)
{
ret->SetPointer(NULL, ATAG_STATE);
numret = 1;
}
AWeapon *weapon = self->player->ReadyWeapon;
int ReloadCounter = weapon->ReloadCounter;
if (!dontincrement || ReloadCounter != 0)
ReloadCounter = (weapon->ReloadCounter+1) % count;
else // 0 % 1 = 1? So how do we check if the weapon was never fired? We should only do this when we're not incrementing the counter though.
ReloadCounter = 1;
// If we have not made our last shot...
if (ReloadCounter != 0)
{
// Go back to the refire frames, instead of continuing on to the reload frames.
if (numret != 0)
{
ret->SetPointer(jump, ATAG_STATE);
}
}
else
{
// We need to reload. However, don't reload if we're out of ammo.
weapon->CheckAmmo(false, false);
}
if (!dontincrement)
{
weapon->ReloadCounter = ReloadCounter;
}
return numret;
}
//===========================================================================
//
// Resets the counter for the above function
//
//===========================================================================
DEFINE_ACTION_FUNCTION(AStateProvider, A_ResetReloadCounter)
{
PARAM_ACTION_PROLOGUE(AStateProvider);
if (self->player == NULL || self->player->ReadyWeapon == NULL)
return 0;
AWeapon *weapon = self->player->ReadyWeapon;
weapon->ReloadCounter = 0;
return 0;
}
//===========================================================================
//
// A_ChangeFlag
//
//===========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_ChangeFlag)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_STRING (flagname);
PARAM_BOOL (value);
ModActorFlag(self, flagname, value);
return 0;
}
//===========================================================================
//
// A_CheckFlag
//
//===========================================================================
DEFINE_ACTION_FUNCTION(AActor, CheckFlag)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_STRING (flagname);
PARAM_INT_DEF (checkpointer);
AActor *owner = COPY_AAPTR(self, checkpointer);
ACTION_RETURN_BOOL(owner != nullptr && CheckActorFlag(owner, flagname));
}
DEFINE_ACTION_FUNCTION(AActor, A_ChangeCountFlags)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_INT_DEF(kill);
PARAM_INT_DEF(item);
PARAM_INT_DEF(secret);
if (self->CountsAsKill() && self->health > 0) --level.total_monsters;
if (self->flags & MF_COUNTITEM) --level.total_items;
if (self->flags5 & MF5_COUNTSECRET) --level.total_secrets;
if (kill != -1)
{
if (kill == 0) self->flags &= ~MF_COUNTKILL;
else self->flags |= MF_COUNTKILL;
}
if (item != -1)
{
if (item == 0) self->flags &= ~MF_COUNTITEM;
else self->flags |= MF_COUNTITEM;
}
if (secret != -1)
{
if (secret == 0) self->flags5 &= ~MF5_COUNTSECRET;
else self->flags5 |= MF5_COUNTSECRET;
}
if (self->CountsAsKill() && self->health > 0) ++level.total_monsters;
if (self->flags & MF_COUNTITEM) ++level.total_items;
if (self->flags5 & MF5_COUNTSECRET) ++level.total_secrets;
return 0;
}
//===========================================================================
//
// A_RaiseMaster
//
//===========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_RaiseMaster)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_BOOL_DEF(copy);
if (self->master != NULL)
{
P_Thing_Raise(self->master, copy ? self : NULL);
}
return 0;
}
//===========================================================================
//
// A_RaiseChildren
//
//===========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_RaiseChildren)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_BOOL_DEF(copy);
TThinkerIterator<AActor> it;
AActor *mo;
while ((mo = it.Next()) != NULL)
{
if (mo->master == self)
{
P_Thing_Raise(mo, copy ? self : NULL);
}
}
return 0;
}
//===========================================================================
//
// A_RaiseSiblings
//
//===========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_RaiseSiblings)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_BOOL_DEF(copy);
TThinkerIterator<AActor> it;
AActor *mo;
if (self->master != NULL)
{
while ((mo = it.Next()) != NULL)
{
if (mo->master == self->master && mo != self)
{
P_Thing_Raise(mo, copy ? self : NULL);
}
}
}
return 0;
}
//===========================================================================
//
// A_MonsterRefire
//
// Keep firing unless target got out of sight
//
//===========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_MonsterRefire)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_INT (prob);
PARAM_STATE (jump);
A_FaceTarget(self);
if (pr_monsterrefire() < prob)
{
ACTION_RETURN_STATE(NULL);
}
if (self->target == NULL
|| P_HitFriend (self)
|| self->target->health <= 0
|| !P_CheckSight (self, self->target, SF_SEEPASTBLOCKEVERYTHING|SF_SEEPASTSHOOTABLELINES) )
{
ACTION_RETURN_STATE(jump);
}
ACTION_RETURN_STATE(NULL);
}
//===========================================================================
//
// A_SetAngle
//
// Set actor's angle (in degrees).
//
//===========================================================================
enum
{
SPF_FORCECLAMP = 1, // players always clamp
SPF_INTERPOLATE = 2,
};
DEFINE_ACTION_FUNCTION(AActor, A_SetAngle)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_FLOAT_DEF(angle);
PARAM_INT_DEF(flags);
PARAM_INT_DEF(ptr);
AActor *ref = COPY_AAPTR(self, ptr);
if (ref != NULL)
{
ref->SetAngle(angle, !!(flags & SPF_INTERPOLATE));
}
return 0;
}
//===========================================================================
//
// A_SetPitch
//
// Set actor's pitch (in degrees).
//
//===========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_SetPitch)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_FLOAT(pitch);
PARAM_INT_DEF(flags);
PARAM_INT_DEF(ptr);
AActor *ref = COPY_AAPTR(self, ptr);
if (ref != NULL)
{
ref->SetPitch(pitch, !!(flags & SPF_INTERPOLATE), !!(flags & SPF_FORCECLAMP));
}
return 0;
}
//===========================================================================
//
// [Nash] A_SetRoll
//
// Set actor's roll (in degrees).
//
//===========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_SetRoll)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_FLOAT (roll);
PARAM_INT_DEF (flags);
PARAM_INT_DEF (ptr) ;
AActor *ref = COPY_AAPTR(self, ptr);
if (ref != NULL)
{
ref->SetRoll(roll, !!(flags & SPF_INTERPOLATE));
}
return 0;
}
//===========================================================================
//
// A_ScaleVelocity
//
// Scale actor's velocity.
//
//===========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_ScaleVelocity)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_FLOAT(scale);
PARAM_INT_DEF(ptr);
AActor *ref = COPY_AAPTR(self, ptr);
if (ref == NULL)
{
return 0;
}
bool was_moving = !ref->Vel.isZero();
ref->Vel *= scale;
// If the actor was previously moving but now is not, and is a player,
// update its player variables. (See A_Stop.)
if (was_moving)
{
CheckStopped(ref);
}
return 0;
}
//===========================================================================
//
// A_ChangeVelocity
//
//===========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_ChangeVelocity)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_FLOAT_DEF (x)
PARAM_FLOAT_DEF (y)
PARAM_FLOAT_DEF (z)
PARAM_INT_DEF (flags)
PARAM_INT_DEF (ptr)
AActor *ref = COPY_AAPTR(self, ptr);
if (ref == NULL)
{
return 0;
}
INTBOOL was_moving = !ref->Vel.isZero();
DVector3 vel(x, y, z);
double sina = ref->Angles.Yaw.Sin();
double cosa = ref->Angles.Yaw.Cos();
if (flags & 1) // relative axes - make x, y relative to actor's current angle
{
vel.X = x*cosa - y*sina;
vel.Y = x*sina + y*cosa;
}
if (flags & 2) // discard old velocity - replace old velocity with new velocity
{
ref->Vel = vel;
}
else // add new velocity to old velocity
{
ref->Vel += vel;
}
if (was_moving)
{
CheckStopped(ref);
}
return 0;
}
//===========================================================================
//
// A_SetUserVar
//
//===========================================================================
static PField *GetVar(DObject *self, FName varname)
{
PField *var = dyn_cast<PField>(self->GetClass()->Symbols.FindSymbol(varname, true));
if (var == NULL || (var->Flags & (VARF_Native | VARF_Private | VARF_Protected | VARF_Static)) || !var->Type->IsKindOf(RUNTIME_CLASS(PBasicType)))
{
Printf("%s is not a user variable in class %s\n", varname.GetChars(),
self->GetClass()->TypeName.GetChars());
return nullptr;
}
return var;
}
DEFINE_ACTION_FUNCTION(AActor, A_SetUserVar)
{
PARAM_SELF_PROLOGUE(DObject);
PARAM_NAME (varname);
PARAM_INT (value);
// Set the value of the specified user variable.
PField *var = GetVar(self, varname);
if (var != nullptr)
{
var->Type->SetValue(reinterpret_cast<BYTE *>(self) + var->Offset, value);
}
return 0;
}
DEFINE_ACTION_FUNCTION(AActor, A_SetUserVarFloat)
{
PARAM_SELF_PROLOGUE(DObject);
PARAM_NAME (varname);
PARAM_FLOAT (value);
// Set the value of the specified user variable.
PField *var = GetVar(self, varname);
if (var != nullptr)
{
var->Type->SetValue(reinterpret_cast<BYTE *>(self) + var->Offset, value);
}
return 0;
}
//===========================================================================
//
// A_SetUserArray
//
//===========================================================================
static PField *GetArrayVar(DObject *self, FName varname, int pos)
{
PField *var = dyn_cast<PField>(self->GetClass()->Symbols.FindSymbol(varname, true));
if (var == NULL || (var->Flags & (VARF_Native | VARF_Private | VARF_Protected | VARF_Static)) ||
!var->Type->IsKindOf(RUNTIME_CLASS(PArray)) ||
!static_cast<PArray *>(var->Type)->ElementType->IsKindOf(RUNTIME_CLASS(PBasicType)))
{
Printf("%s is not a user array in class %s\n", varname.GetChars(),
self->GetClass()->TypeName.GetChars());
return nullptr;
}
if ((unsigned)pos >= static_cast<PArray *>(var->Type)->ElementCount)
{
Printf("%d is out of bounds in array %s in class %s\n", pos, varname.GetChars(),
self->GetClass()->TypeName.GetChars());
return nullptr;
}
return var;
}
DEFINE_ACTION_FUNCTION(AActor, A_SetUserArray)
{
PARAM_SELF_PROLOGUE(DObject);
PARAM_NAME (varname);
PARAM_INT (pos);
PARAM_INT (value);
// Set the value of the specified user array at index pos.
PField *var = GetArrayVar(self, varname, pos);
if (var != nullptr)
{
PArray *arraytype = static_cast<PArray *>(var->Type);
arraytype->ElementType->SetValue(reinterpret_cast<BYTE *>(self) + var->Offset + arraytype->ElementSize * pos, value);
}
return 0;
}
DEFINE_ACTION_FUNCTION(AActor, A_SetUserArrayFloat)
{
PARAM_SELF_PROLOGUE(DObject);
PARAM_NAME (varname);
PARAM_INT (pos);
PARAM_FLOAT (value);
// Set the value of the specified user array at index pos.
PField *var = GetArrayVar(self, varname, pos);
if (var != nullptr)
{
PArray *arraytype = static_cast<PArray *>(var->Type);
arraytype->ElementType->SetValue(reinterpret_cast<BYTE *>(self) + var->Offset + arraytype->ElementSize * pos, value);
}
return 0;
}
//===========================================================================
//
// A_Teleport([state teleportstate, [class targettype,
// [class fogtype, [int flags, [fixed mindist,
// [fixed maxdist]]]]]])
//
// Attempts to teleport to a targettype at least mindist away and at most
// maxdist away (0 means unlimited). If successful, spawn a fogtype at old
// location and place calling actor in teleportstate.
//
//===========================================================================
enum T_Flags
{
TF_TELEFRAG = 0x00000001, // Allow telefrag in order to teleport.
TF_RANDOMDECIDE = 0x00000002, // Randomly fail based on health. (A_Srcr2Decide)
TF_FORCED = 0x00000004, // Forget what's in the way. TF_Telefrag takes precedence though.
TF_KEEPVELOCITY = 0x00000008, // Preserve velocity.
TF_KEEPANGLE = 0x00000010, // Keep angle.
TF_USESPOTZ = 0x00000020, // Set the z to the spot's z, instead of the floor.
TF_NOSRCFOG = 0x00000040, // Don't leave any fog behind when teleporting.
TF_NODESTFOG = 0x00000080, // Don't spawn any fog at the arrival position.
TF_USEACTORFOG = 0x00000100, // Use the actor's TeleFogSourceType and TeleFogDestType fogs.
TF_NOJUMP = 0x00000200, // Don't jump after teleporting.
TF_OVERRIDE = 0x00000400, // Ignore NOTELEPORT.
TF_SENSITIVEZ = 0x00000800, // Fail if the actor wouldn't fit in the position (for Z).
};
DEFINE_ACTION_FUNCTION(AActor, A_Teleport)
{
PARAM_ACTION_PROLOGUE(AActor);
PARAM_STATE_DEF (teleport_state)
PARAM_CLASS_DEF (target_type, ASpecialSpot)
PARAM_CLASS_DEF (fog_type, AActor)
PARAM_INT_DEF (flags)
PARAM_FLOAT_DEF (mindist)
PARAM_FLOAT_DEF (maxdist)
PARAM_INT_DEF (ptr)
AActor *ref = COPY_AAPTR(self, ptr);
// A_Teleport and A_Warp were the only codepointers that can state jump
// *AND* have a meaningful inventory state chain result. Grrr.
if (numret > 1)
{
ret[1].SetInt(false);
numret = 2;
}
if (numret > 0)
{
ret[0].SetPointer(NULL, ATAG_STATE);
}
if (!ref)
{
return numret;
}
if ((ref->flags2 & MF2_NOTELEPORT) && !(flags & TF_OVERRIDE))
{
return numret;
}
// Randomly choose not to teleport like A_Srcr2Decide.
if (flags & TF_RANDOMDECIDE)
{
static const int chance[] =
{
192, 120, 120, 120, 64, 64, 32, 16, 0
};
unsigned int chanceindex = ref->health / ((ref->SpawnHealth()/8 == 0) ? 1 : ref->SpawnHealth()/8);
if (chanceindex >= countof(chance))
{
chanceindex = countof(chance) - 1;
}
if (pr_teleport() >= chance[chanceindex])
{
return numret;
}
}
DSpotState *state = DSpotState::GetSpotState();
if (state == NULL)
{
return numret;
}
if (target_type == NULL)
{
target_type = PClass::FindActor("BossSpot");
}
AActor *spot = state->GetSpotWithMinMaxDistance(target_type, ref->X(), ref->Y(), mindist, maxdist);
if (spot == NULL)
{
return numret;
}
// [MC] By default, the function adjusts the actor's Z if it's below the floor or above the ceiling.
// This can be an issue as actors designed to maintain specific z positions wind up teleporting
// anyway when they should not, such as a floor rising above or ceiling lowering below the position
// of the spot.
if (flags & TF_SENSITIVEZ)
{
double posz = (flags & TF_USESPOTZ) ? spot->Z() : spot->floorz;
if ((posz + ref->Height > spot->ceilingz) || (posz < spot->floorz))
{
return numret;
}
}
DVector3 prev = ref->Pos();
double aboveFloor = spot->Z() - spot->floorz;
double finalz = spot->floorz + aboveFloor;
if (spot->Top() > spot->ceilingz)
finalz = spot->ceilingz - ref->Height;
else if (spot->Z() < spot->floorz)
finalz = spot->floorz;
DVector3 tpos = spot->PosAtZ(finalz);
//Take precedence and cooperate with telefragging first.
bool tele_result = P_TeleportMove(ref, tpos, !!(flags & TF_TELEFRAG));
if (!tele_result && (flags & TF_FORCED))
{
//If for some reason the original move didn't work, regardless of telefrag, force it to move.
ref->SetOrigin(tpos, false);
tele_result = true;
}
AActor *fog1 = NULL, *fog2 = NULL;
if (tele_result)
{
//If a fog type is defined in the parameter, or the user wants to use the actor's predefined fogs,
//and if there's no desire to be fogless, spawn a fog based upon settings.
if (fog_type || (flags & TF_USEACTORFOG))
{
if (!(flags & TF_NOSRCFOG))
{
if (flags & TF_USEACTORFOG)
P_SpawnTeleportFog(ref, prev, true, true);
else
{
fog1 = Spawn(fog_type, prev, ALLOW_REPLACE);
if (fog1 != NULL)
fog1->target = ref;
}
}
if (!(flags & TF_NODESTFOG))
{
if (flags & TF_USEACTORFOG)
P_SpawnTeleportFog(ref, ref->Pos(), false, true);
else
{
fog2 = Spawn(fog_type, ref->Pos(), ALLOW_REPLACE);
if (fog2 != NULL)
fog2->target = ref;
}
}
}
ref->SetZ((flags & TF_USESPOTZ) ? spot->Z() : ref->floorz, false);
if (!(flags & TF_KEEPANGLE))
ref->Angles.Yaw = spot->Angles.Yaw;
if (!(flags & TF_KEEPVELOCITY)) ref->Vel.Zero();
if (!(flags & TF_NOJUMP)) //The state jump should only happen with the calling actor.
{
if (teleport_state == NULL)
{
// Default to Teleport.
teleport_state = self->FindState("Teleport");
// If still nothing, then return.
if (teleport_state == NULL)
{
return numret;
}
}
if (numret > 0)
{
ret[0].SetPointer(teleport_state, ATAG_STATE);
}
return numret;
}
}
if (numret > 1)
{
ret[1].SetInt(tele_result);
}
return numret;
}
//===========================================================================
//
// A_Quake
//
//===========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_Quake)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_INT (intensity);
PARAM_INT (duration);
PARAM_INT (damrad);
PARAM_INT (tremrad);
PARAM_SOUND_DEF (sound);
P_StartQuake(self, 0, intensity, duration, damrad, tremrad, sound);
return 0;
}
//===========================================================================
//
// A_QuakeEx
//
// Extended version of A_Quake. Takes individual axis into account and can
// take flags.
//===========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_QuakeEx)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_INT(intensityX);
PARAM_INT(intensityY);
PARAM_INT(intensityZ);
PARAM_INT(duration);
PARAM_INT(damrad);
PARAM_INT(tremrad);
PARAM_SOUND_DEF(sound);
PARAM_INT_DEF(flags);
PARAM_FLOAT_DEF(mulWaveX);
PARAM_FLOAT_DEF(mulWaveY);
PARAM_FLOAT_DEF(mulWaveZ);
PARAM_INT_DEF(falloff);
PARAM_INT_DEF(highpoint);
PARAM_FLOAT_DEF(rollIntensity);
PARAM_FLOAT_DEF(rollWave);
P_StartQuakeXYZ(self, 0, intensityX, intensityY, intensityZ, duration, damrad, tremrad, sound, flags, mulWaveX, mulWaveY, mulWaveZ, falloff, highpoint,
rollIntensity, rollWave);
return 0;
}
//===========================================================================
//
// A_Weave
//
//===========================================================================
void A_Weave(AActor *self, int xyspeed, int zspeed, double xydist, double zdist)
{
DVector2 newpos;
int weaveXY, weaveZ;
DAngle angle;
double dist;
weaveXY = self->WeaveIndexXY & 63;
weaveZ = self->WeaveIndexZ & 63;
angle = self->Angles.Yaw + 90;
if (xydist != 0 && xyspeed != 0)
{
dist = BobSin(weaveXY) * xydist;
newpos = self->Pos().XY() - angle.ToVector(dist);
weaveXY = (weaveXY + xyspeed) & 63;
dist = BobSin(weaveXY) * xydist;
newpos += angle.ToVector(dist);
if (!(self->flags5 & MF5_NOINTERACTION))
{
P_TryMove (self, newpos, true);
}
else
{
FLinkContext ctx;
self->UnlinkFromWorld (&ctx);
self->flags |= MF_NOBLOCKMAP;
// We need to do portal offsetting here explicitly, because SetXY cannot do that.
newpos -= self->Pos().XY();
self->SetXY(self->Vec2Offset(newpos.X, newpos.Y));
self->LinkToWorld (&ctx);
}
self->WeaveIndexXY = weaveXY;
}
if (zdist != 0 && zspeed != 0)
{
self->AddZ(-BobSin(weaveZ) * zdist);
weaveZ = (weaveZ + zspeed) & 63;
self->AddZ(BobSin(weaveZ) * zdist);
self->WeaveIndexZ = weaveZ;
}
}
DEFINE_ACTION_FUNCTION(AActor, A_Weave)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_INT (xspeed);
PARAM_INT (yspeed);
PARAM_FLOAT (xdist);
PARAM_FLOAT (ydist);
A_Weave(self, xspeed, yspeed, xdist, ydist);
return 0;
}
//===========================================================================
//
// A_LineEffect
//
// This allows linedef effects to be activated inside deh frames.
//
//===========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_LineEffect)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_INT_DEF(special);
PARAM_INT_DEF(tag);
line_t junk;
maplinedef_t oldjunk;
bool res = false;
if (!(self->flags6 & MF6_LINEDONE)) // Unless already used up
{
if ((oldjunk.special = special)) // Linedef type
{
oldjunk.tag = tag; // Sector tag for linedef
P_TranslateLineDef(&junk, &oldjunk); // Turn into native type
res = !!P_ExecuteSpecial(junk.special, NULL, self, false, junk.args[0],
junk.args[1], junk.args[2], junk.args[3], junk.args[4]);
if (res && !(junk.flags & ML_REPEAT_SPECIAL)) // If only once,
self->flags6 |= MF6_LINEDONE; // no more for this thing
}
}
ACTION_RETURN_BOOL(res);
}
//==========================================================================
//
// A Wolf3D-style attack codepointer
//
//==========================================================================
enum WolfAttackFlags
{
WAF_NORANDOM = 1,
WAF_USEPUFF = 2,
};
DEFINE_ACTION_FUNCTION(AActor, A_WolfAttack)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_INT_DEF (flags)
PARAM_SOUND_DEF (sound)
PARAM_FLOAT_DEF (snipe)
PARAM_INT_DEF (maxdamage)
PARAM_INT_DEF (blocksize)
PARAM_INT_DEF (pointblank)
PARAM_INT_DEF (longrange)
PARAM_FLOAT_DEF (runspeed)
PARAM_CLASS_DEF (pufftype, AActor)
if (!self->target)
return 0;
// Enemy can't see target
if (!P_CheckSight(self, self->target))
return 0;
A_FaceTarget (self);
// Target can dodge if it can see enemy
DAngle angle = absangle(self->target->Angles.Yaw, self->target->AngleTo(self));
bool dodge = (P_CheckSight(self->target, self) && angle < 30. * 256. / 360.); // 30 byteangles ~ 21
// Distance check is simplistic
DVector2 vec = self->Vec2To(self->target);
double dx = fabs (vec.X);
double dy = fabs (vec.Y);
double dist = dx > dy ? dx : dy;
// Some enemies are more precise
dist *= snipe;
// Convert distance into integer number of blocks
int idist = int(dist / blocksize);
// Now for the speed accuracy thingie
double speed = self->target->Vel.LengthSquared();
int hitchance = speed < runspeed ? 256 : 160;
// Distance accuracy (factoring dodge)
hitchance -= idist * (dodge ? 16 : 8);
// While we're here, we may as well do something for this:
if (self->target->flags & MF_SHADOW)
{
hitchance >>= 2;
}
// The attack itself
if (pr_cabullet() < hitchance)
{
// Compute position for spawning blood/puff
DAngle angle = self->target->AngleTo(self);
DVector3 BloodPos = self->target->Vec3Angle(self->target->radius, angle, self->target->Height/2);
int damage = flags & WAF_NORANDOM ? maxdamage : (1 + (pr_cabullet() % maxdamage));
if (dist >= pointblank)
damage >>= 1;
if (dist >= longrange)
damage >>= 1;
FName mod = NAME_None;
bool spawnblood = !((self->target->flags & MF_NOBLOOD)
|| (self->target->flags2 & (MF2_INVULNERABLE|MF2_DORMANT)));
if (flags & WAF_USEPUFF && pufftype)
{
AActor *dpuff = GetDefaultByType(pufftype->GetReplacement());
mod = dpuff->DamageType;
if (dpuff->flags2 & MF2_THRUGHOST && self->target->flags3 & MF3_GHOST)
damage = 0;
if ((0 && dpuff->flags3 & MF3_PUFFONACTORS) || !spawnblood)
{
spawnblood = false;
P_SpawnPuff(self, pufftype, BloodPos, angle, angle, 0);
}
}
else if (self->target->flags3 & MF3_GHOST)
damage >>= 2;
if (damage)
{
int newdam = P_DamageMobj(self->target, self, self, damage, mod, DMG_THRUSTLESS);
if (spawnblood)
{
P_SpawnBlood(BloodPos, angle, newdam > 0 ? newdam : damage, self->target);
P_TraceBleed(newdam > 0 ? newdam : damage, self->target, self);
}
}
}
// And finally, let's play the sound
S_Sound (self, CHAN_WEAPON, sound, 1, ATTN_NORM);
return 0;
}
//==========================================================================
//
// A_Warp
//
//==========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_Warp)
{
PARAM_ACTION_PROLOGUE(AActor);
PARAM_INT(destination_selector);
PARAM_FLOAT_DEF(xofs)
PARAM_FLOAT_DEF(yofs)
PARAM_FLOAT_DEF(zofs)
PARAM_ANGLE_DEF(angle)
PARAM_INT_DEF(flags)
PARAM_STATE_DEF(success_state)
PARAM_FLOAT_DEF(heightoffset)
PARAM_FLOAT_DEF(radiusoffset)
PARAM_ANGLE_DEF(pitch)
AActor *reference;
// A_Teleport and A_Warp were the only codepointers that can state jump
// *AND* have a meaningful inventory state chain result. Grrr.
if (numret > 1)
{
ret[1].SetInt(false);
numret = 2;
}
if (numret > 0)
{
ret[0].SetPointer(NULL, ATAG_STATE);
}
if ((flags & WARPF_USETID))
{
reference = SingleActorFromTID(destination_selector, self);
}
else
{
reference = COPY_AAPTR(self, destination_selector);
}
//If there is no actor to warp to, fail.
if (!reference)
{
return numret;
}
if (P_Thing_Warp(self, reference, xofs, yofs, zofs, angle, flags, heightoffset, radiusoffset, pitch))
{
if (success_state)
{
// Jumps should never set the result for inventory state chains!
// in this case, you have the statejump to help you handle all the success anyway.
if (numret > 0)
{
ret[0].SetPointer(success_state, ATAG_STATE);
}
}
else if (numret > 1)
{
ret[1].SetInt(true);
}
}
return numret;
}
static bool DoCheckSpecies(AActor *mo, FName filterSpecies, bool exclude)
{
FName actorSpecies = mo->GetSpecies();
if (filterSpecies == NAME_None) return true;
return exclude ? (actorSpecies != filterSpecies) : (actorSpecies == filterSpecies);
}
static bool DoCheckClass(AActor *mo, PClassActor *filterClass, bool exclude)
{
const PClass *actorClass = mo->GetClass();
if (filterClass == NULL) return true;
return exclude ? (actorClass != filterClass) : (actorClass == filterClass);
}
//==========================================================================
//
// A_RadiusGive(item, distance, flags, amount, filter, species)
//
// Uses code roughly similar to A_Explode (but without all the compatibility
// baggage and damage computation code) to give an item to all eligible mobjs
// in range.
//
//==========================================================================
enum RadiusGiveFlags
{
RGF_GIVESELF = 1 << 0,
RGF_PLAYERS = 1 << 1,
RGF_MONSTERS = 1 << 2,
RGF_OBJECTS = 1 << 3,
RGF_VOODOO = 1 << 4,
RGF_CORPSES = 1 << 5,
RGF_NOTARGET = 1 << 6,
RGF_NOTRACER = 1 << 7,
RGF_NOMASTER = 1 << 8,
RGF_CUBE = 1 << 9,
RGF_NOSIGHT = 1 << 10,
RGF_MISSILES = 1 << 11,
RGF_INCLUSIVE = 1 << 12,
RGF_ITEMS = 1 << 13,
RGF_KILLED = 1 << 14,
RGF_EXFILTER = 1 << 15,
RGF_EXSPECIES = 1 << 16,
RGF_EITHER = 1 << 17,
RGF_MASK = /*2111*/
RGF_GIVESELF |
RGF_PLAYERS |
RGF_MONSTERS |
RGF_OBJECTS |
RGF_VOODOO |
RGF_CORPSES |
RGF_KILLED |
RGF_MISSILES |
RGF_ITEMS,
};
static bool DoRadiusGive(AActor *self, AActor *thing, PClassActor *item, int amount, double distance, int flags, PClassActor *filter, FName species, double mindist)
{
bool doPass = false;
// Always allow self to give, no matter what other flags are specified. Otherwise, not at all.
if (thing == self)
{
if (!(flags & RGF_GIVESELF))
return false;
doPass = true;
}
else if (thing->flags & MF_MISSILE)
{
if (!(flags & RGF_MISSILES))
return false;
doPass = true;
}
else if (((flags & RGF_ITEMS) && thing->IsKindOf(RUNTIME_CLASS(AInventory))) ||
((flags & RGF_CORPSES) && thing->flags & MF_CORPSE) ||
((flags & RGF_KILLED) && thing->flags6 & MF6_KILLED))
{
doPass = true;
}
else if ((flags & (RGF_MONSTERS | RGF_OBJECTS | RGF_PLAYERS | RGF_VOODOO)))
{
// Make sure it's alive as we're not looking for corpses or killed here.
if (!doPass && thing->health > 0)
{
if (thing->player != nullptr)
{
if (((flags & RGF_PLAYERS) && (thing->player->mo == thing)) ||
((flags & RGF_VOODOO) && (thing->player->mo != thing)))
{
doPass = true;
}
}
else
{
if (((flags & RGF_MONSTERS) && (thing->flags3 & MF3_ISMONSTER)) ||
((flags & RGF_OBJECTS) && (!(thing->flags3 & MF3_ISMONSTER)) &&
(thing->flags & MF_SHOOTABLE || thing->flags6 & MF6_VULNERABLE)))
{
doPass = true;
}
}
}
}
// Nothing matched up so don't bother with the rest.
if (!doPass)
return false;
//[MC] Check for a filter, species, and the related exfilter/expecies/either flag(s).
bool filterpass = DoCheckClass(thing, filter, !!(flags & RGF_EXFILTER)),
speciespass = DoCheckSpecies(thing, species, !!(flags & RGF_EXSPECIES));
if ((flags & RGF_EITHER) ? (!(filterpass || speciespass)) : (!(filterpass && speciespass)))
{
if (thing != self) //Don't let filter and species obstruct RGF_GIVESELF.
return false;
}
if ((thing != self) && (flags & (RGF_NOTARGET | RGF_NOMASTER | RGF_NOTRACER)))
{
//Check for target, master, and tracer flagging.
bool targetPass = true;
bool masterPass = true;
bool tracerPass = true;
bool ptrPass = false;
if ((thing == self->target) && (flags & RGF_NOTARGET))
targetPass = false;
if ((thing == self->master) && (flags & RGF_NOMASTER))
masterPass = false;
if ((thing == self->tracer) && (flags & RGF_NOTRACER))
tracerPass = false;
ptrPass = (flags & RGF_INCLUSIVE) ? (targetPass || masterPass || tracerPass) : (targetPass && masterPass && tracerPass);
//We should not care about what the actor is here. It's safe to abort this actor.
if (!ptrPass)
return false;
}
if (doPass)
{
DVector3 diff = self->Vec3To(thing);
diff.Z += thing->Height *0.5;
if (flags & RGF_CUBE)
{ // check if inside a cube
double dx = fabs(diff.X);
double dy = fabs(diff.Y);
double dz = fabs(diff.Z);
if ((dx > distance || dy > distance || dz > distance) || (mindist && (dx < mindist && dy < mindist && dz < mindist)))
{
return false;
}
}
else
{ // check if inside a sphere
double lengthsquared = diff.LengthSquared();
if (lengthsquared > distance*distance || (mindist && (lengthsquared < mindist*mindist)))
{
return false;
}
}
if ((flags & RGF_NOSIGHT) || P_CheckSight(thing, self, SF_IGNOREVISIBILITY | SF_IGNOREWATERBOUNDARY))
{ // OK to give; target is in direct path, or the monster doesn't care about it being in line of sight.
AInventory *gift = static_cast<AInventory *>(Spawn(item));
if (gift->IsKindOf(RUNTIME_CLASS(AHealth)))
{
gift->Amount *= amount;
}
else
{
gift->Amount = amount;
}
gift->flags |= MF_DROPPED;
gift->ClearCounters();
if (!gift->CallTryPickup(thing))
{
gift->Destroy();
return false;
}
else
{
return true;
}
}
}
return false;
}
DEFINE_ACTION_FUNCTION(AActor, A_RadiusGive)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_CLASS (item, AInventory);
PARAM_FLOAT (distance);
PARAM_INT (flags);
PARAM_INT_DEF (amount);
PARAM_CLASS_DEF (filter, AActor);
PARAM_NAME_DEF (species);
PARAM_FLOAT_DEF (mindist);
PARAM_INT_DEF (limit);
// We need a valid item, valid targets, and a valid range
if (item == nullptr || (flags & RGF_MASK) == 0 || !flags || distance <= 0 || mindist >= distance)
{
ACTION_RETURN_INT(0);
}
bool unlimited = (limit <= 0);
if (amount == 0)
{
amount = 1;
}
AActor *thing;
int given = 0;
if (flags & RGF_MISSILES)
{
TThinkerIterator<AActor> it;
while ((thing = it.Next()) && ((unlimited) || (given < limit)))
{
given += DoRadiusGive(self, thing, item, amount, distance, flags, filter, species, mindist);
}
}
else
{
FPortalGroupArray check(FPortalGroupArray::PGA_Full3d);
double mid = self->Center();
FMultiBlockThingsIterator it(check, self->X(), self->Y(), mid-distance, mid+distance, distance, false, self->Sector);
FMultiBlockThingsIterator::CheckResult cres;
while ((it.Next(&cres)) && ((unlimited) || (given < limit)))
{
given += DoRadiusGive(self, cres.thing, item, amount, distance, flags, filter, species, mindist);
}
}
ACTION_RETURN_INT(given);
}
//==========================================================================
//
// A_SetTics
//
//==========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_SetTics)
{
PARAM_ACTION_PROLOGUE(AActor);
PARAM_INT(tics_to_set);
if (ACTION_CALL_FROM_PSPRITE())
{
DPSprite *pspr = self->player->FindPSprite(stateinfo->mPSPIndex);
if (pspr != nullptr)
{
pspr->Tics = tics_to_set;
return 0;
}
}
else if (ACTION_CALL_FROM_ACTOR())
{
// Just set tics for self.
self->tics = tics_to_set;
}
// for inventory state chains this needs to be ignored.
return 0;
}
//==========================================================================
//
// A_DropItem
//
//==========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_DropItem)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_CLASS (spawntype, AActor);
PARAM_INT_DEF(amount);
PARAM_INT_DEF(chance);
P_DropItem(self, spawntype, amount, chance);
return 0;
}
//===========================================================================
//
// Common A_Damage handler
//
// A_Damage* (int amount, str damagetype, int flags, str filter, str species)
// Damages the specified actor by the specified amount. Negative values heal.
// Flags: See below.
// Filter: Specified actor is the only type allowed to be affected.
// Species: Specified species is the only type allowed to be affected.
//
// Examples:
// A_Damage(20,"Normal",DMSS_FOILINVUL,0,"DemonicSpecies") <--Only actors
// with a species "DemonicSpecies" will be affected. Use 0 to not filter by actor.
//
//===========================================================================
enum DMSS
{
DMSS_FOILINVUL = 1, //Foil invulnerability
DMSS_AFFECTARMOR = 2, //Make it affect armor
DMSS_KILL = 4, //Damages them for their current health
DMSS_NOFACTOR = 8, //Ignore DamageFactors
DMSS_FOILBUDDHA = 16, //Can kill actors with Buddha flag, except the player.
DMSS_NOPROTECT = 32, //Ignores PowerProtection entirely
DMSS_EXFILTER = 64, //Changes filter into a blacklisted class instead of whitelisted.
DMSS_EXSPECIES = 128, // ^ but with species instead.
DMSS_EITHER = 256, //Allow either type or species to be affected.
DMSS_INFLICTORDMGTYPE = 512, //Ignore the passed damagetype and use the inflictor's instead.
};
static void DoDamage(AActor *dmgtarget, AActor *inflictor, AActor *source, int amount, FName DamageType, int flags, PClassActor *filter, FName species)
{
bool filterpass = DoCheckClass(dmgtarget, filter, !!(flags & DMSS_EXFILTER)),
speciespass = DoCheckSpecies(dmgtarget, species, !!(flags & DMSS_EXSPECIES));
if ((flags & DMSS_EITHER) ? (filterpass || speciespass) : (filterpass && speciespass))
{
int dmgFlags = 0;
if (flags & DMSS_FOILINVUL)
dmgFlags |= DMG_FOILINVUL;
if (flags & DMSS_FOILBUDDHA)
dmgFlags |= DMG_FOILBUDDHA;
if (flags & (DMSS_KILL | DMSS_NOFACTOR)) //Kill implies NoFactor
dmgFlags |= DMG_NO_FACTOR;
if (!(flags & DMSS_AFFECTARMOR) || (flags & DMSS_KILL)) //Kill overrides AffectArmor
dmgFlags |= DMG_NO_ARMOR;
if (flags & DMSS_KILL) //Kill adds the value of the damage done to it. Allows for more controlled extreme death types.
amount += dmgtarget->health;
if (flags & DMSS_NOPROTECT) //Ignore PowerProtection.
dmgFlags |= DMG_NO_PROTECT;
if (amount > 0)
{ //Should wind up passing them through just fine.
if (flags & DMSS_INFLICTORDMGTYPE)
DamageType = inflictor->DamageType;
P_DamageMobj(dmgtarget, inflictor, source, amount, DamageType, dmgFlags);
}
else if (amount < 0)
{
amount = -amount;
P_GiveBody(dmgtarget, amount);
}
}
}
//===========================================================================
//
//
//
//===========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_DamageSelf)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_INT (amount);
PARAM_NAME_DEF (damagetype)
PARAM_INT_DEF (flags)
PARAM_CLASS_DEF (filter, AActor)
PARAM_NAME_DEF (species)
PARAM_INT_DEF (src)
PARAM_INT_DEF (inflict)
AActor *source = COPY_AAPTR(self, src);
AActor *inflictor = COPY_AAPTR(self, inflict);
DoDamage(self, inflictor, source, amount, damagetype, flags, filter, species);
return 0;
}
//===========================================================================
//
//
//
//===========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_DamageTarget)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_INT (amount);
PARAM_NAME_DEF (damagetype)
PARAM_INT_DEF (flags)
PARAM_CLASS_DEF (filter, AActor)
PARAM_NAME_DEF (species)
PARAM_INT_DEF (src)
PARAM_INT_DEF (inflict)
AActor *source = COPY_AAPTR(self, src);
AActor *inflictor = COPY_AAPTR(self, inflict);
if (self->target != NULL)
DoDamage(self->target, inflictor, source, amount, damagetype, flags, filter, species);
return 0;
}
//===========================================================================
//
//
//
//===========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_DamageTracer)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_INT (amount);
PARAM_NAME_DEF (damagetype)
PARAM_INT_DEF (flags)
PARAM_CLASS_DEF (filter, AActor)
PARAM_NAME_DEF (species)
PARAM_INT_DEF (src)
PARAM_INT_DEF (inflict)
AActor *source = COPY_AAPTR(self, src);
AActor *inflictor = COPY_AAPTR(self, inflict);
if (self->tracer != NULL)
DoDamage(self->tracer, inflictor, source, amount, damagetype, flags, filter, species);
return 0;
}
//===========================================================================
//
//
//
//===========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_DamageMaster)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_INT (amount);
PARAM_NAME_DEF (damagetype)
PARAM_INT_DEF (flags)
PARAM_CLASS_DEF (filter, AActor)
PARAM_NAME_DEF (species)
PARAM_INT_DEF (src)
PARAM_INT_DEF (inflict)
AActor *source = COPY_AAPTR(self, src);
AActor *inflictor = COPY_AAPTR(self, inflict);
if (self->master != NULL)
DoDamage(self->master, inflictor, source, amount, damagetype, flags, filter, species);
return 0;
}
//===========================================================================
//
//
//
//===========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_DamageChildren)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_INT (amount);
PARAM_NAME_DEF (damagetype)
PARAM_INT_DEF (flags)
PARAM_CLASS_DEF (filter, AActor)
PARAM_NAME_DEF (species)
PARAM_INT_DEF (src)
PARAM_INT_DEF (inflict)
AActor *source = COPY_AAPTR(self, src);
AActor *inflictor = COPY_AAPTR(self, inflict);
TThinkerIterator<AActor> it;
AActor *mo;
while ( (mo = it.Next()) )
{
if (mo->master == self)
DoDamage(mo, inflictor, source, amount, damagetype, flags, filter, species);
}
return 0;
}
//===========================================================================
//
//
//
//===========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_DamageSiblings)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_INT (amount);
PARAM_NAME_DEF (damagetype)
PARAM_INT_DEF (flags)
PARAM_CLASS_DEF (filter, AActor)
PARAM_NAME_DEF (species)
PARAM_INT_DEF (src)
PARAM_INT_DEF (inflict)
AActor *source = COPY_AAPTR(self, src);
AActor *inflictor = COPY_AAPTR(self, inflict);
TThinkerIterator<AActor> it;
AActor *mo;
if (self->master != NULL)
{
while ((mo = it.Next()))
{
if (mo->master == self->master && mo != self)
DoDamage(mo, inflictor, source, amount, damagetype, flags, filter, species);
}
}
return 0;
}
//===========================================================================
//
// A_Kill*(damagetype, int flags)
//
//===========================================================================
enum KILS
{
KILS_FOILINVUL = 1 << 0,
KILS_KILLMISSILES = 1 << 1,
KILS_NOMONSTERS = 1 << 2,
KILS_FOILBUDDHA = 1 << 3,
KILS_EXFILTER = 1 << 4,
KILS_EXSPECIES = 1 << 5,
KILS_EITHER = 1 << 6,
};
static void DoKill(AActor *killtarget, AActor *inflictor, AActor *source, FName damagetype, int flags, PClassActor *filter, FName species)
{
bool filterpass = DoCheckClass(killtarget, filter, !!(flags & KILS_EXFILTER)),
speciespass = DoCheckSpecies(killtarget, species, !!(flags & KILS_EXSPECIES));
if ((flags & KILS_EITHER) ? (filterpass || speciespass) : (filterpass && speciespass)) //Check this first. I think it'll save the engine a lot more time this way.
{
int dmgFlags = DMG_NO_ARMOR | DMG_NO_FACTOR;
if (KILS_FOILINVUL)
dmgFlags |= DMG_FOILINVUL;
if (KILS_FOILBUDDHA)
dmgFlags |= DMG_FOILBUDDHA;
if ((killtarget->flags & MF_MISSILE) && (flags & KILS_KILLMISSILES))
{
//[MC] Now that missiles can set masters, lets put in a check to properly destroy projectiles. BUT FIRST! New feature~!
//Check to see if it's invulnerable. Disregarded if foilinvul is on, but never works on a missile with NODAMAGE
//since that's the whole point of it.
if ((!(killtarget->flags2 & MF2_INVULNERABLE) || (flags & KILS_FOILINVUL)) &&
(!(killtarget->flags7 & MF7_BUDDHA) || (flags & KILS_FOILBUDDHA)) &&
!(killtarget->flags5 & MF5_NODAMAGE))
{
P_ExplodeMissile(killtarget, NULL, NULL);
}
}
if (!(flags & KILS_NOMONSTERS))
{
P_DamageMobj(killtarget, inflictor, source, killtarget->health, damagetype, dmgFlags);
}
}
}
//===========================================================================
//
// A_KillTarget(damagetype, int flags)
//
//===========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_KillTarget)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_NAME_DEF (damagetype)
PARAM_INT_DEF (flags)
PARAM_CLASS_DEF (filter, AActor)
PARAM_NAME_DEF (species)
PARAM_INT_DEF (src)
PARAM_INT_DEF (inflict)
AActor *source = COPY_AAPTR(self, src);
AActor *inflictor = COPY_AAPTR(self, inflict);
if (self->target != NULL)
DoKill(self->target, inflictor, source, damagetype, flags, filter, species);
return 0;
}
//===========================================================================
//
// A_KillTracer(damagetype, int flags)
//
//===========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_KillTracer)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_NAME_DEF (damagetype)
PARAM_INT_DEF (flags)
PARAM_CLASS_DEF (filter, AActor)
PARAM_NAME_DEF (species)
PARAM_INT_DEF (src)
PARAM_INT_DEF (inflict)
AActor *source = COPY_AAPTR(self, src);
AActor *inflictor = COPY_AAPTR(self, inflict);
if (self->tracer != NULL)
DoKill(self->tracer, inflictor, source, damagetype, flags, filter, species);
return 0;
}
//===========================================================================
//
// A_KillMaster(damagetype, int flags)
//
//===========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_KillMaster)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_NAME_DEF (damagetype)
PARAM_INT_DEF (flags)
PARAM_CLASS_DEF (filter, AActor)
PARAM_NAME_DEF (species)
PARAM_INT_DEF (src)
PARAM_INT_DEF (inflict)
AActor *source = COPY_AAPTR(self, src);
AActor *inflictor = COPY_AAPTR(self, inflict);
if (self->master != NULL)
DoKill(self->master, inflictor, source, damagetype, flags, filter, species);
return 0;
}
//===========================================================================
//
// A_KillChildren(damagetype, int flags)
//
//===========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_KillChildren)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_NAME_DEF (damagetype)
PARAM_INT_DEF (flags)
PARAM_CLASS_DEF (filter, AActor)
PARAM_NAME_DEF (species)
PARAM_INT_DEF (src)
PARAM_INT_DEF (inflict)
AActor *source = COPY_AAPTR(self, src);
AActor *inflictor = COPY_AAPTR(self, inflict);
TThinkerIterator<AActor> it;
AActor *mo;
while ( (mo = it.Next()) )
{
if (mo->master == self)
{
DoKill(mo, inflictor, source, damagetype, flags, filter, species);
}
}
return 0;
}
//===========================================================================
//
// A_KillSiblings(damagetype, int flags)
//
//===========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_KillSiblings)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_NAME_DEF (damagetype)
PARAM_INT_DEF (flags)
PARAM_CLASS_DEF (filter, AActor)
PARAM_NAME_DEF (species)
PARAM_INT_DEF (src)
PARAM_INT_DEF (inflict)
AActor *source = COPY_AAPTR(self, src);
AActor *inflictor = COPY_AAPTR(self, inflict);
TThinkerIterator<AActor> it;
AActor *mo;
if (self->master != NULL)
{
while ( (mo = it.Next()) )
{
if (mo->master == self->master && mo != self)
{
DoKill(mo, inflictor, source, damagetype, flags, filter, species);
}
}
}
return 0;
}
//===========================================================================
//
// DoRemove
//
//===========================================================================
enum RMVF_flags
{
RMVF_MISSILES = 1 << 0,
RMVF_NOMONSTERS = 1 << 1,
RMVF_MISC = 1 << 2,
RMVF_EVERYTHING = 1 << 3,
RMVF_EXFILTER = 1 << 4,
RMVF_EXSPECIES = 1 << 5,
RMVF_EITHER = 1 << 6,
};
static void DoRemove(AActor *removetarget, int flags, PClassActor *filter, FName species)
{
bool filterpass = DoCheckClass(removetarget, filter, !!(flags & RMVF_EXFILTER)),
speciespass = DoCheckSpecies(removetarget, species, !!(flags & RMVF_EXSPECIES));
if ((flags & RMVF_EITHER) ? (filterpass || speciespass) : (filterpass && speciespass))
{
if ((flags & RMVF_EVERYTHING))
{
P_RemoveThing(removetarget);
}
if ((flags & RMVF_MISC) && !((removetarget->flags3 & MF3_ISMONSTER) && (removetarget->flags & MF_MISSILE)))
{
P_RemoveThing(removetarget);
}
if ((removetarget->flags3 & MF3_ISMONSTER) && !(flags & RMVF_NOMONSTERS))
{
P_RemoveThing(removetarget);
}
if ((removetarget->flags & MF_MISSILE) && (flags & RMVF_MISSILES))
{
P_RemoveThing(removetarget);
}
}
}
//===========================================================================
//
// A_RemoveTarget
//
//===========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_RemoveTarget)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_INT_DEF(flags);
PARAM_CLASS_DEF(filter, AActor);
PARAM_NAME_DEF(species);
if (self->target != NULL)
{
DoRemove(self->target, flags, filter, species);
}
return 0;
}
//===========================================================================
//
// A_RemoveTracer
//
//===========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_RemoveTracer)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_INT_DEF(flags);
PARAM_CLASS_DEF(filter, AActor);
PARAM_NAME_DEF(species);
if (self->tracer != NULL)
{
DoRemove(self->tracer, flags, filter, species);
}
return 0;
}
//===========================================================================
//
// A_RemoveMaster
//
//===========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_RemoveMaster)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_INT_DEF(flags);
PARAM_CLASS_DEF(filter, AActor);
PARAM_NAME_DEF(species);
if (self->master != NULL)
{
DoRemove(self->master, flags, filter, species);
}
return 0;
}
//===========================================================================
//
// A_RemoveChildren
//
//===========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_RemoveChildren)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_BOOL_DEF(removeall);
PARAM_INT_DEF(flags);
PARAM_CLASS_DEF(filter, AActor);
PARAM_NAME_DEF(species);
TThinkerIterator<AActor> it;
AActor *mo;
while ((mo = it.Next()) != NULL)
{
if (mo->master == self && (mo->health <= 0 || removeall))
{
DoRemove(mo, flags, filter, species);
}
}
return 0;
}
//===========================================================================
//
// A_RemoveSiblings
//
//===========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_RemoveSiblings)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_BOOL_DEF(removeall);
PARAM_INT_DEF(flags);
PARAM_CLASS_DEF(filter, AActor);
PARAM_NAME_DEF(species);
TThinkerIterator<AActor> it;
AActor *mo;
if (self->master != NULL)
{
while ((mo = it.Next()) != NULL)
{
if (mo->master == self->master && mo != self && (mo->health <= 0 || removeall))
{
DoRemove(mo, flags, filter, species);
}
}
}
return 0;
}
//===========================================================================
//
// A_Remove
//
//===========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_Remove)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_INT(removee);
PARAM_INT_DEF(flags);
PARAM_CLASS_DEF(filter, AActor);
PARAM_NAME_DEF(species);
AActor *reference = COPY_AAPTR(self, removee);
if (reference != NULL)
{
DoRemove(reference, flags, filter, species);
}
return 0;
}
//===========================================================================
//
// A_SetTeleFog
//
// Sets the teleport fog(s) for the calling actor.
// Takes a name of the classes for the source and destination.
//===========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_SetTeleFog)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_CLASS(oldpos, AActor);
PARAM_CLASS(newpos, AActor);
self->TeleFogSourceType = oldpos;
self->TeleFogDestType = newpos;
return 0;
}
//===========================================================================
//
// A_SwapTeleFog
//
// Switches the source and dest telefogs around.
//===========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_SwapTeleFog)
{
PARAM_SELF_PROLOGUE(AActor);
if ((self->TeleFogSourceType != self->TeleFogDestType)) //Does nothing if they're the same.
{
PClassActor *temp = self->TeleFogSourceType;
self->TeleFogSourceType = self->TeleFogDestType;
self->TeleFogDestType = temp;
}
return 0;
}
//===========================================================================
//
// A_SetFloatBobPhase
//
// Changes the FloatBobPhase of the actor.
//===========================================================================
//===========================================================================
// A_SetHealth
//
// Changes the health of the actor.
// Takes a pointer as well.
//===========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_SetHealth)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_INT (health);
PARAM_INT_DEF (ptr);
AActor *mobj = COPY_AAPTR(self, ptr);
if (!mobj)
{
return 0;
}
player_t *player = mobj->player;
if (player)
{
if (health <= 0)
player->mo->health = mobj->health = player->health = 1; //Copied from the buddha cheat.
else
player->mo->health = mobj->health = player->health = health;
}
else if (mobj)
{
if (health <= 0)
mobj->health = 1;
else
mobj->health = health;
}
return 0;
}
//===========================================================================
// A_ResetHealth
//
// Resets the health of the actor to default, except if their dead.
// Takes a pointer.
//===========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_ResetHealth)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_INT_DEF(ptr);
AActor *mobj = COPY_AAPTR(self, ptr);
if (!mobj)
{
return 0;
}
player_t *player = mobj->player;
if (player && (player->mo->health > 0))
{
player->health = player->mo->health = player->mo->GetDefault()->health; //Copied from the resurrect cheat.
}
else if (mobj && (mobj->health > 0))
{
mobj->health = mobj->SpawnHealth();
}
return 0;
}
//===========================================================================
// A_SetSpecies(str species, ptr)
//
// Sets the species of the calling actor('s pointer).
//===========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_SetSpecies)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_NAME(species);
PARAM_INT_DEF(ptr);
AActor *mobj = COPY_AAPTR(self, ptr);
if (!mobj)
{
return 0;
}
mobj->Species = species;
return 0;
}
//===========================================================================
//
// A_SetChaseThreshold(int threshold, bool def, int ptr)
//
// Sets the current chase threshold of the actor (pointer). If def is true,
// changes the default threshold which the actor resets to once it switches
// targets and doesn't have the +QUICKTORETALIATE flag.
//===========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_SetChaseThreshold)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_INT(threshold);
PARAM_BOOL_DEF(def);
PARAM_INT_DEF(ptr);
AActor *mobj = COPY_AAPTR(self, ptr);
if (!mobj)
{
return 0;
}
if (def)
mobj->DefThreshold = (threshold >= 0) ? threshold : 0;
else
mobj->threshold = (threshold >= 0) ? threshold : 0;
return 0;
}
//==========================================================================
//
// A_CheckProximity(jump, classname, distance, count, flags, ptr)
//
// Checks to see if a certain actor class is close to the
// actor/pointer within distance, in numbers.
//==========================================================================
DEFINE_ACTION_FUNCTION(AActor, CheckProximity)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_CLASS(classname, AActor);
PARAM_FLOAT(distance);
PARAM_INT_DEF(count);
PARAM_INT_DEF(flags);
PARAM_INT_DEF(ptr);
ACTION_RETURN_BOOL(!!P_Thing_CheckProximity(self, classname, distance, count, flags, ptr));
}
/*===========================================================================
A_CheckBlock
(state block, int flags, int ptr)
Checks if something is blocking the actor('s pointer) 'ptr'.
The SET pointer flags only affect the caller, not the pointer.
===========================================================================*/
enum CBF
{
CBF_NOLINES = 1 << 0, //Don't check lines.
CBF_SETTARGET = 1 << 1, //Sets the caller/pointer's target to the actor blocking it. Actors only.
CBF_SETMASTER = 1 << 2, //^ but with master.
CBF_SETTRACER = 1 << 3, //^ but with tracer.
CBF_SETONPTR = 1 << 4, //Sets the pointer change on the actor doing the checking instead of self.
CBF_DROPOFF = 1 << 5, //Check for dropoffs.
CBF_NOACTORS = 1 << 6, //Don't check actors.
CBF_ABSOLUTEPOS = 1 << 7, //Absolute position for offsets.
CBF_ABSOLUTEANGLE = 1 << 8, //Absolute angle for offsets.
};
DEFINE_ACTION_FUNCTION(AActor, CheckBlock)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_INT_DEF(flags)
PARAM_INT_DEF(ptr)
PARAM_FLOAT_DEF(xofs)
PARAM_FLOAT_DEF(yofs)
PARAM_FLOAT_DEF(zofs)
PARAM_ANGLE_DEF(angle)
AActor *mobj = COPY_AAPTR(self, ptr);
//Needs at least one state jump to work.
if (!mobj)
{
ACTION_RETURN_BOOL(false);
}
if (!(flags & CBF_ABSOLUTEANGLE))
{
angle += self->Angles.Yaw;
}
DVector3 oldpos = mobj->Pos();
DVector3 pos;
if (flags & CBF_ABSOLUTEPOS)
{
pos = { xofs, yofs, zofs };
}
else
{
double s = angle.Sin();
double c = angle.Cos();
pos = mobj->Vec3Offset(xofs * c + yofs * s, xofs * s - yofs * c, zofs);
}
// Next, try checking the position based on the sensitivity desired.
// If checking for dropoffs, set the z so we can have maximum flexibility.
// Otherwise, set origin and set it back after testing.
bool checker = false;
if (flags & CBF_DROPOFF)
{
// Unfortunately, whenever P_CheckMove returned false, that means it could
// ignore a variety of flags mainly because of P_CheckPosition. This
// results in picking up false positives due to actors or lines being in the way
// when they clearly should not be.
int fpass = PCM_DROPOFF;
if (flags & CBF_NOACTORS) fpass |= PCM_NOACTORS;
if (flags & CBF_NOLINES) fpass |= PCM_NOLINES;
mobj->SetZ(pos.Z);
checker = P_CheckMove(mobj, pos, fpass);
mobj->SetZ(oldpos.Z);
}
else
{
mobj->SetOrigin(pos, true);
checker = P_TestMobjLocation(mobj);
mobj->SetOrigin(oldpos, true);
}
if (checker)
{
ACTION_RETURN_BOOL(false);
}
if (mobj->BlockingMobj)
{
AActor *setter = (flags & CBF_SETONPTR) ? mobj : self;
if (setter)
{
if (flags & CBF_SETTARGET) setter->target = mobj->BlockingMobj;
if (flags & CBF_SETMASTER) setter->master = mobj->BlockingMobj;
if (flags & CBF_SETTRACER) setter->tracer = mobj->BlockingMobj;
}
}
//[MC] I don't know why I let myself be persuaded not to include a flag.
//If an actor is loaded with pointers, they don't really have any options to spare.
//Also, fail if a dropoff or a step is too great to pass over when checking for dropoffs.
ACTION_RETURN_BOOL((!(flags & CBF_NOACTORS) && (mobj->BlockingMobj)) || (!(flags & CBF_NOLINES) && mobj->BlockingLine != NULL) ||
((flags & CBF_DROPOFF) && !checker));
}
//===========================================================================
//
// A_FaceMovementDirection(angle offset, bool pitch, ptr)
//
// Sets the actor('s pointer) to face the direction of travel.
//===========================================================================
enum FMDFlags
{
FMDF_NOPITCH = 1 << 0,
FMDF_INTERPOLATE = 1 << 1,
FMDF_NOANGLE = 1 << 2,
};
DEFINE_ACTION_FUNCTION(AActor, A_FaceMovementDirection)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_ANGLE_DEF(offset)
PARAM_ANGLE_DEF(anglelimit)
PARAM_ANGLE_DEF(pitchlimit)
PARAM_INT_DEF(flags)
PARAM_INT_DEF(ptr)
AActor *mobj = COPY_AAPTR(self, ptr);
//Need an actor.
if (!mobj || ((flags & FMDF_NOPITCH) && (flags & FMDF_NOANGLE)))
{
ACTION_RETURN_BOOL(false);
}
//Don't bother calculating this if we don't have any horizontal movement.
if (!(flags & FMDF_NOANGLE) && (mobj->Vel.X != 0 || mobj->Vel.Y != 0))
{
DAngle current = mobj->Angles.Yaw;
DAngle angle = mobj->Vel.Angle();
//Done because using anglelimit directly causes a signed/unsigned mismatch.
//Code borrowed from A_Face*.
if (anglelimit > 0)
{
DAngle delta = -deltaangle(current, angle);
if (fabs(delta) > anglelimit)
{
if (delta < 0)
{
current += anglelimit + offset;
}
else if (delta > 0)
{
current -= anglelimit + offset;
}
mobj->SetAngle(current, !!(flags & FMDF_INTERPOLATE));
}
else
mobj->SetAngle(angle + offset, !!(flags & FMDF_INTERPOLATE));
}
else
mobj->SetAngle(angle + offset, !!(flags & FMDF_INTERPOLATE));
}
if (!(flags & FMDF_NOPITCH))
{
DAngle current = mobj->Angles.Pitch;
const DVector2 velocity = mobj->Vel.XY();
DAngle pitch = -VecToAngle(velocity.Length(), mobj->Vel.Z);
if (pitchlimit > 0)
{
DAngle pdelta = deltaangle(current, pitch);
if (fabs(pdelta) > pitchlimit)
{
if (pdelta > 0)
{
current -= MIN(pitchlimit, pdelta);
}
else //if (pdelta < 0)
{
current += MIN(pitchlimit, -pdelta);
}
mobj->SetPitch(current, !!(flags & FMDF_INTERPOLATE));
}
else
{
mobj->SetPitch(pitch, !!(flags & FMDF_INTERPOLATE));
}
}
else
{
mobj->SetPitch(pitch, !!(flags & FMDF_INTERPOLATE));
}
}
ACTION_RETURN_BOOL(true);
}
//==========================================================================
//
// A_CopySpriteFrame(from, to, flags)
//
// Copies the sprite and/or frame from one pointer to another.
//==========================================================================
enum CPSFFlags
{
CPSF_NOSPRITE = 1,
CPSF_NOFRAME = 1 << 1,
};
DEFINE_ACTION_FUNCTION(AActor, A_CopySpriteFrame)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_INT(from);
PARAM_INT(to);
PARAM_INT_DEF(flags);
AActor *copyfrom = COPY_AAPTR(self, from);
AActor *copyto = COPY_AAPTR(self, to);
if (copyfrom == copyto || copyfrom == nullptr || copyto == nullptr || ((flags & CPSF_NOSPRITE) && (flags & CPSF_NOFRAME)))
{
ACTION_RETURN_BOOL(false);
}
if (!(flags & CPSF_NOSPRITE)) copyto->sprite = copyfrom->sprite;
if (!(flags & CPSF_NOFRAME)) copyto->frame = copyfrom->frame;
ACTION_RETURN_BOOL(true);
}
//==========================================================================
//
// A_SetMaskRotation(anglestart, angleend, pitchstart, pitchend, flags, ptr)
//
// Specifies how much to fake a sprite rotation.
//==========================================================================
enum VRFFlags
{
VRF_NOANGLESTART = 1,
VRF_NOANGLEEND = 1 << 1,
VRF_NOPITCHSTART = 1 << 2,
VRF_NOPITCHEND = 1 << 3,
};
DEFINE_ACTION_FUNCTION(AActor, A_SetVisibleRotation)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_ANGLE_DEF(anglestart)
PARAM_ANGLE_DEF(angleend)
PARAM_ANGLE_DEF(pitchstart)
PARAM_ANGLE_DEF(pitchend)
PARAM_INT_DEF(flags)
PARAM_INT_DEF(ptr)
AActor *mobj = COPY_AAPTR(self, ptr);
if (mobj == nullptr)
{
ACTION_RETURN_BOOL(false);
}
if (!(flags & VRF_NOANGLESTART))
{
mobj->VisibleStartAngle = anglestart;
}
if (!(flags & VRF_NOANGLEEND))
{
mobj->VisibleEndAngle = angleend;
}
if (!(flags & VRF_NOPITCHSTART))
{
mobj->VisibleStartPitch = pitchstart;
}
if (!(flags & VRF_NOPITCHEND))
{
mobj->VisibleEndPitch = pitchend;
}
ACTION_RETURN_BOOL(true);
}
//==========================================================================
//
//
//
//==========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_SetTranslation)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_NAME(trname);
self->SetTranslation(trname);
return 0;
}
//==========================================================================
//
//
//
//==========================================================================
DEFINE_ACTION_FUNCTION(AActor, A_CheckTerrain)
{
PARAM_SELF_PROLOGUE(AActor);
sector_t *sec = self->Sector;
if (self->Z() == sec->floorplane.ZatPoint(self) && sec->PortalBlocksMovement(sector_t::floor))
{
if (sec->special == Damage_InstantDeath)
{
P_DamageMobj(self, NULL, NULL, 999, NAME_InstantDeath);
}
else if (sec->special == Scroll_StrifeCurrent)
{
int anglespeed = tagManager.GetFirstSectorTag(sec) - 100;
double speed = (anglespeed % 10) / 16.;
DAngle an = (anglespeed / 10) * (360 / 8.);
self->Thrust(an, speed);
}
}
return 0;
}
DEFINE_ACTION_FUNCTION(AActor, A_SetSize)
{
PARAM_SELF_PROLOGUE(AActor);
PARAM_FLOAT(newradius);
PARAM_FLOAT_DEF(newheight);
PARAM_BOOL_DEF(testpos);
if (newradius < 0.) newradius = self->radius;
if (newheight < 0.) newheight = self->Height;
double oldradius = self->radius;
double oldheight = self->Height;
FLinkContext ctx;
self->UnlinkFromWorld(&ctx);
self->radius = newradius;
self->Height = newheight;
self->LinkToWorld(&ctx);
if (testpos && !P_TestMobjLocation(self))
{
self->UnlinkFromWorld(&ctx);
self->radius = oldradius;
self->Height = oldheight;
self->LinkToWorld(&ctx);
ACTION_RETURN_BOOL(false);
}
ACTION_RETURN_BOOL(true);
}
| 412 | 0.939977 | 1 | 0.939977 | game-dev | MEDIA | 0.861668 | game-dev | 0.981837 | 1 | 0.981837 |
webbukkit/dynmap | 1,455 | DynmapCore/src/main/java/org/dynmap/hdmap/HDPerspective.java | package org.dynmap.hdmap;
import java.util.List;
import org.dynmap.DynmapChunk;
import org.dynmap.DynmapWorld;
import org.dynmap.MapTile;
import org.dynmap.utils.MapChunkCache;
import org.dynmap.utils.TileFlags;
import org.dynmap.utils.Vector3D;
import org.json.simple.JSONObject;
public interface HDPerspective {
/* Get name of perspective */
String getName();
/* Get tiles invalidated by change at given location */
List<TileFlags.TileCoord> getTileCoords(DynmapWorld w, int x, int y, int z, int tilescale);
/* Get tiles invalidated by change at given volume, defined by 2 opposite corner locations */
List<TileFlags.TileCoord> getTileCoords(DynmapWorld w, int minx, int miny, int minz, int maxx, int maxy, int maxz, int tilescale);
/* Get tiles adjacent to given tile */
MapTile[] getAdjecentTiles(MapTile tile);
/* Get chunks needed for given tile */
List<DynmapChunk> getRequiredChunks(MapTile tile);
/* Render given tile */
boolean render(MapChunkCache cache, HDMapTile tile, String mapname);
public boolean isBiomeDataNeeded();
public boolean isHightestBlockYDataNeeded();
public boolean isRawBiomeDataNeeded();
public boolean isBlockTypeDataNeeded();
double getScale();
int getModelScale();
public void addClientConfiguration(JSONObject mapObject);
public void transformWorldToMapCoord(Vector3D input, Vector3D rslt);
public int hashCode();
}
| 412 | 0.775258 | 1 | 0.775258 | game-dev | MEDIA | 0.579083 | game-dev | 0.82168 | 1 | 0.82168 |
oskardudycz/Ogooreck | 2,430 | src/Ogooreck/BusinessLogic/Decider.cs | using Ogooreck.Factories;
#pragma warning disable CS1591
namespace Ogooreck.BusinessLogic;
public record Decider<TCommand, TEvent, TState>(
Func<TCommand, TState, DecideResult<TEvent, TState>> Decide,
Func<TState, TEvent, TState> Evolve,
Func<TState> GetInitialState
);
public static class Decider
{
public static Decider<TCommand, TEvent, TState> For<TCommand, TEvent, TState>(
Func<TCommand, TState, DecideResult<TEvent, TState>> decide,
Func<TState, TEvent, TState>? evolve = null,
Func<TState>? getInitialState = null
) =>
new(
decide,
(state, @event) => evolve != null ? evolve(state, @event) : state,
getInitialState ?? ObjectFactory<TState>.GetDefaultOrUninitialized
);
public static Decider<TCommand, TEvent, TState> For<TCommand, TEvent, TState>(
Func<TCommand, TState, TEvent> decide,
Func<TState, TEvent, TState>? evolve = null,
Func<TState>? getInitialState = null
) =>
For<TCommand, TEvent, TState>(
(command, currentState) => new[] { decide(command, currentState) },
evolve,
getInitialState
);
public static Decider<TCommand, TEvent, TState> For<TCommand, TEvent, TState>(
Func<TCommand, TState, TEvent[]> decide,
Func<TState, TEvent, TState>? evolve = null,
Func<TState>? getInitialState = null
) =>
For<TCommand, TEvent, TState>(
(command, currentState) => DecideResult.For<TEvent, TState>(decide(command, currentState)),
evolve,
getInitialState
);
}
public record DecideResult<TEvent, TState>(
TEvent[] NewEvents,
TState? NewState = default
);
public static class DecideResult
{
public static DecideResult<TEvent, TState> For<TEvent, TState>(params TEvent[] newEvents) => new(newEvents);
public static DecideResult<TEvent, TState> For<TEvent, TState>(TState currentState) =>
new(Array.Empty<TEvent>(), currentState);
public static DecideResult<TEvent, TState> For<TEvent, TState>(TState currentState, params TEvent[] newEvents) =>
new(newEvents, currentState);
public static DecideResult<object, TState> For<TState>(params object[] newEvents) => new(newEvents);
public static DecideResult<object, TState> For<TState>(TState currentState) =>
new(Array.Empty<object>(), currentState);
}
| 412 | 0.844985 | 1 | 0.844985 | game-dev | MEDIA | 0.814952 | game-dev | 0.675428 | 1 | 0.675428 |
jzyong/game-server | 1,360 | game-bydr/src/main/java/com/jzy/game/bydr/server/BydrHttpServer.java | package com.jzy.game.bydr.server;
import java.lang.management.ThreadInfo;
import com.jzy.game.engine.mina.config.MinaServerConfig;
import com.jzy.game.engine.mina.service.GameHttpSevice;
import com.jzy.game.engine.script.ScriptManager;
import com.jzy.game.model.handler.http.favicon.GetFaviconHandler;
import com.jzy.game.model.handler.http.server.ExitServerHandler;
import com.jzy.game.model.handler.http.server.JvmInfoHandler;
import com.jzy.game.model.handler.http.server.ReloadConfigHandler;
import com.jzy.game.model.handler.http.server.ReloadScriptHandler;
import com.jzy.game.model.handler.http.server.ThreadInfoHandler;
/**
* http服务器
*
* @author JiangZhiYong
* @QQ 359135103 2017年7月24日 下午1:46:00
*/
public class BydrHttpServer extends GameHttpSevice {
public BydrHttpServer(MinaServerConfig minaServerConfig) {
super(minaServerConfig);
}
@Override
protected void running() {
super.running();
// 添加关服、脚本加载 等公用 handler
ScriptManager.getInstance().addIHandler(ReloadScriptHandler.class);
ScriptManager.getInstance().addIHandler(ExitServerHandler.class);
ScriptManager.getInstance().addIHandler(ReloadConfigHandler.class);
ScriptManager.getInstance().addIHandler(JvmInfoHandler.class);
ScriptManager.getInstance().addIHandler(GetFaviconHandler.class);
ScriptManager.getInstance().addIHandler(ThreadInfoHandler.class);
}
}
| 412 | 0.57802 | 1 | 0.57802 | game-dev | MEDIA | 0.629997 | game-dev | 0.744791 | 1 | 0.744791 |
Fluorohydride/ygopro-scripts | 1,125 | c33725271.lua | --ヴォルカニック・チャージ
function c33725271.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_TODECK)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetTarget(c33725271.target)
e1:SetOperation(c33725271.activate)
c:RegisterEffect(e1)
end
function c33725271.filter(c)
return c:IsSetCard(0x32) and c:IsType(TYPE_MONSTER) and c:IsAbleToDeck()
end
function c33725271.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsControler(tp) and chkc:IsLocation(LOCATION_GRAVE) and c33725271.filter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c33725271.filter,tp,LOCATION_GRAVE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TODECK)
local g=Duel.SelectTarget(tp,c33725271.filter,tp,LOCATION_GRAVE,0,1,3,nil)
Duel.SetOperationInfo(0,CATEGORY_TODECK,g,g:GetCount(),0,0)
end
function c33725271.activate(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS)
local sg=g:Filter(Card.IsRelateToEffect,nil,e)
if sg:GetCount()>0 then
Duel.SendtoDeck(sg,nil,SEQ_DECKSHUFFLE,REASON_EFFECT)
end
end
| 412 | 0.894398 | 1 | 0.894398 | game-dev | MEDIA | 0.982538 | game-dev | 0.938028 | 1 | 0.938028 |
PhoenixBladez/SpiritMod | 3,996 | NPCs/Boss/ExplodingFeather.cs | using Microsoft.Xna.Framework;
using Terraria;
using Terraria.ID;
using Terraria.ModLoader;
namespace SpiritMod.NPCs.Boss
{
public class ExplodingFeather : ModProjectile
{
public override void SetStaticDefaults()
{
DisplayName.SetDefault("Exploding Feather");
Main.projFrames[projectile.type] = 4;
}
public override void SetDefaults()
{
projectile.width = projectile.height = 34;
projectile.hostile = true;
projectile.friendly = false;
projectile.penetrate = -1;
}
public override bool PreAI()
{
projectile.spriteDirection = projectile.direction;
projectile.frameCounter++;
if (projectile.frameCounter >= 3) {
projectile.frame++;
projectile.frameCounter = 0;
if (projectile.frame >= 4)
projectile.frame = 0;
}
projectile.rotation = projectile.velocity.ToRotation() + 1.57F;
return true;
}
public override void AI()
{
int num = 5;
for (int k = 0; k < 3; k++) {
int index2 = Dust.NewDust(projectile.position, 1, 1, DustID.RedTorch, 0.0f, 0.0f, 0, new Color(), 1f);
Main.dust[index2].position = projectile.Center - projectile.velocity / num * (float)k;
Main.dust[index2].scale = .5f;
Main.dust[index2].velocity *= 0f;
Main.dust[index2].noGravity = true;
Main.dust[index2].noLight = false;
}
}
public override void Kill(int timeLeft)
{
Main.PlaySound(SoundID.Item, (int)projectile.position.X, (int)projectile.position.Y, 14);
projectile.position.X = projectile.position.X + (float)(projectile.width / 4);
projectile.position.Y = projectile.position.Y + (float)(projectile.height / 4);
projectile.width = 20;
projectile.height = 20;
projectile.position.X = projectile.position.X - (float)(projectile.width / 4);
projectile.position.Y = projectile.position.Y - (float)(projectile.height / 4);
for (int num625 = 0; num625 < 2; num625++) {
float scaleFactor10 = 0.2f;
if (num625 == 1) {
scaleFactor10 = 0.5f;
}
if (num625 == 2) {
scaleFactor10 = 1f;
}
int num626 = Gore.NewGore(new Vector2(projectile.position.X + (float)(projectile.width / 2) - 24f, projectile.position.Y + (float)(projectile.height / 2) - 24f), default, Main.rand.Next(61, 64), 1f);
Main.gore[num626].velocity *= scaleFactor10;
Gore expr_13AB6_cp_0 = Main.gore[num626];
expr_13AB6_cp_0.velocity.X = expr_13AB6_cp_0.velocity.X + 1f;
Gore expr_13AD6_cp_0 = Main.gore[num626];
expr_13AD6_cp_0.velocity.Y = expr_13AD6_cp_0.velocity.Y + 1f;
num626 = Gore.NewGore(new Vector2(projectile.position.X + (float)(projectile.width / 2) - 24f, projectile.position.Y + (float)(projectile.height / 2) - 24f), default, Main.rand.Next(61, 64), 1f);
Main.gore[num626].velocity *= scaleFactor10;
Gore expr_13B79_cp_0 = Main.gore[num626];
expr_13B79_cp_0.velocity.X = expr_13B79_cp_0.velocity.X - 1f;
Gore expr_13B99_cp_0 = Main.gore[num626];
expr_13B99_cp_0.velocity.Y = expr_13B99_cp_0.velocity.Y + 1f;
}
projectile.position.X = projectile.position.X + (float)(projectile.width / 4);
projectile.position.Y = projectile.position.Y + (float)(projectile.height / 4);
projectile.width = 10;
projectile.height = 10;
projectile.position.X = projectile.position.X - (float)(projectile.width / 4);
projectile.position.Y = projectile.position.Y - (float)(projectile.height / 4);
for (int num273 = 0; num273 < 3; num273++) {
int num274 = Dust.NewDust(new Vector2(projectile.position.X, projectile.position.Y), projectile.width, projectile.height, DustID.Flare_Blue, 0f, 0f, 0, default, 1f);
Main.dust[num274].noGravity = true;
Main.dust[num274].noLight = true;
Main.dust[num274].scale = 0.7f;
int num278 = Dust.NewDust(new Vector2(projectile.position.X, projectile.position.Y), projectile.width, projectile.height, DustID.DemonTorch, 0f, 0f, 0, default, 1f);
Main.dust[num278].noGravity = true;
Main.dust[num278].noLight = true;
Main.dust[num278].scale = 0.7f;
}
}
}
}
| 412 | 0.611991 | 1 | 0.611991 | game-dev | MEDIA | 0.993325 | game-dev | 0.909456 | 1 | 0.909456 |
saitoha/SDL1.2-SIXEL | 11,869 | src/video/bwindow/SDL_sysevents.cc | /*
SDL - Simple DirectMedia Layer
Copyright (C) 1997-2012 Sam Lantinga
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Sam Lantinga
slouken@libsdl.org
*/
#include "SDL_config.h"
#include <support/UTF8.h>
#include <stdio.h>
#include <string.h>
#include "SDL_error.h"
#include "SDL_events.h"
#include "SDL_BWin.h"
#include "SDL_lowvideo.h"
static SDLKey keymap[128];
int mouse_relative = 0;
extern "C" {
#include "../../events/SDL_sysevents.h"
#include "../../events/SDL_events_c.h"
#include "SDL_sysevents_c.h"
#include "../SDL_cursor_c.h"
void BE_PumpEvents(_THIS)
{
}
void BE_InitOSKeymap(_THIS)
{
for ( uint i=0; i<SDL_TABLESIZE(keymap); ++i )
keymap[i] = SDLK_UNKNOWN;
keymap[0x01] = SDLK_ESCAPE;
keymap[B_F1_KEY] = SDLK_F1;
keymap[B_F2_KEY] = SDLK_F2;
keymap[B_F3_KEY] = SDLK_F3;
keymap[B_F4_KEY] = SDLK_F4;
keymap[B_F5_KEY] = SDLK_F5;
keymap[B_F6_KEY] = SDLK_F6;
keymap[B_F7_KEY] = SDLK_F7;
keymap[B_F8_KEY] = SDLK_F8;
keymap[B_F9_KEY] = SDLK_F9;
keymap[B_F10_KEY] = SDLK_F10;
keymap[B_F11_KEY] = SDLK_F11;
keymap[B_F12_KEY] = SDLK_F12;
keymap[B_PRINT_KEY] = SDLK_PRINT;
keymap[B_SCROLL_KEY] = SDLK_SCROLLOCK;
keymap[B_PAUSE_KEY] = SDLK_PAUSE;
keymap[0x11] = SDLK_BACKQUOTE;
keymap[0x12] = SDLK_1;
keymap[0x13] = SDLK_2;
keymap[0x14] = SDLK_3;
keymap[0x15] = SDLK_4;
keymap[0x16] = SDLK_5;
keymap[0x17] = SDLK_6;
keymap[0x18] = SDLK_7;
keymap[0x19] = SDLK_8;
keymap[0x1a] = SDLK_9;
keymap[0x1b] = SDLK_0;
keymap[0x1c] = SDLK_MINUS;
keymap[0x1d] = SDLK_EQUALS;
keymap[0x1e] = SDLK_BACKSPACE;
keymap[0x1f] = SDLK_INSERT;
keymap[0x20] = SDLK_HOME;
keymap[0x21] = SDLK_PAGEUP;
keymap[0x22] = SDLK_NUMLOCK;
keymap[0x23] = SDLK_KP_DIVIDE;
keymap[0x24] = SDLK_KP_MULTIPLY;
keymap[0x25] = SDLK_KP_MINUS;
keymap[0x26] = SDLK_TAB;
keymap[0x27] = SDLK_q;
keymap[0x28] = SDLK_w;
keymap[0x29] = SDLK_e;
keymap[0x2a] = SDLK_r;
keymap[0x2b] = SDLK_t;
keymap[0x2c] = SDLK_y;
keymap[0x2d] = SDLK_u;
keymap[0x2e] = SDLK_i;
keymap[0x2f] = SDLK_o;
keymap[0x30] = SDLK_p;
keymap[0x31] = SDLK_LEFTBRACKET;
keymap[0x32] = SDLK_RIGHTBRACKET;
keymap[0x33] = SDLK_BACKSLASH;
keymap[0x34] = SDLK_DELETE;
keymap[0x35] = SDLK_END;
keymap[0x36] = SDLK_PAGEDOWN;
keymap[0x37] = SDLK_KP7;
keymap[0x38] = SDLK_KP8;
keymap[0x39] = SDLK_KP9;
keymap[0x3a] = SDLK_KP_PLUS;
keymap[0x3b] = SDLK_CAPSLOCK;
keymap[0x3c] = SDLK_a;
keymap[0x3d] = SDLK_s;
keymap[0x3e] = SDLK_d;
keymap[0x3f] = SDLK_f;
keymap[0x40] = SDLK_g;
keymap[0x41] = SDLK_h;
keymap[0x42] = SDLK_j;
keymap[0x43] = SDLK_k;
keymap[0x44] = SDLK_l;
keymap[0x45] = SDLK_SEMICOLON;
keymap[0x46] = SDLK_QUOTE;
keymap[0x47] = SDLK_RETURN;
keymap[0x48] = SDLK_KP4;
keymap[0x49] = SDLK_KP5;
keymap[0x4a] = SDLK_KP6;
keymap[0x4b] = SDLK_LSHIFT;
keymap[0x4c] = SDLK_z;
keymap[0x4d] = SDLK_x;
keymap[0x4e] = SDLK_c;
keymap[0x4f] = SDLK_v;
keymap[0x50] = SDLK_b;
keymap[0x51] = SDLK_n;
keymap[0x52] = SDLK_m;
keymap[0x53] = SDLK_COMMA;
keymap[0x54] = SDLK_PERIOD;
keymap[0x55] = SDLK_SLASH;
keymap[0x56] = SDLK_RSHIFT;
keymap[0x57] = SDLK_UP;
keymap[0x58] = SDLK_KP1;
keymap[0x59] = SDLK_KP2;
keymap[0x5a] = SDLK_KP3;
keymap[0x5b] = SDLK_KP_ENTER;
keymap[0x5c] = SDLK_LCTRL;
keymap[0x5d] = SDLK_LALT;
keymap[0x5e] = SDLK_SPACE;
keymap[0x5f] = SDLK_RALT;
keymap[0x60] = SDLK_RCTRL;
keymap[0x61] = SDLK_LEFT;
keymap[0x62] = SDLK_DOWN;
keymap[0x63] = SDLK_RIGHT;
keymap[0x64] = SDLK_KP0;
keymap[0x65] = SDLK_KP_PERIOD;
keymap[0x66] = SDLK_LMETA;
keymap[0x67] = SDLK_RMETA;
keymap[0x68] = SDLK_MENU;
keymap[0x69] = SDLK_EURO;
keymap[0x6a] = SDLK_KP_EQUALS;
keymap[0x6b] = SDLK_POWER;
}
}; /* Extern C */
void SDL_BWin::DispatchMessage(BMessage *msg, BHandler *target)
{
switch (msg->what) {
case B_MOUSE_MOVED:
{
SDL_VideoDevice *view = current_video;
BPoint where;
int32 transit;
if (msg->FindPoint("where", &where) == B_OK && msg->FindInt32("be:transit", &transit) == B_OK) {
int x, y;
GetXYOffset(x, y);
x = (int)where.x - x;
y = (int)where.y - y;
//BeSman: I need another method for cursor catching !!!
if (view->input_grab != SDL_GRAB_OFF)
{
bool clipped = false;
if ( x < 0 ) {
x = 0;
clipped = true;
} else if ( x >= SDL_VideoSurface->w ) {
x = (SDL_VideoSurface->w-1);
clipped = true;
}
if ( y < 0 ) {
y = 0;
clipped = true;
} else if ( y >= SDL_VideoSurface->h ) {
y = (SDL_VideoSurface->h-1);
clipped = true;
}
if ( clipped ) {
BPoint edge;
GetXYOffset(edge.x, edge.y);
edge.x += x;
edge.y += y;
ConvertToScreen(&edge);
set_mouse_position((int)edge.x, (int)edge.y);
}
transit = B_INSIDE_VIEW;
}
if (transit == B_EXITED_VIEW) {
if ( SDL_GetAppState() & SDL_APPMOUSEFOCUS ) {
SDL_PrivateAppActive(0, SDL_APPMOUSEFOCUS);
#if SDL_VIDEO_OPENGL
// for some reason, SDL_EraseCursor fails for OpenGL
if (this->the_view != this->SDL_GLView)
#endif
SDL_EraseCursor(SDL_VideoSurface);
be_app->SetCursor(B_HAND_CURSOR);
}
} else {
if ( !(SDL_GetAppState() & SDL_APPMOUSEFOCUS) ) {
SDL_PrivateAppActive(1, SDL_APPMOUSEFOCUS);
#if SDL_VIDEO_OPENGL
// for some reason, SDL_EraseCursor fails for OpenGL
if (this->the_view != this->SDL_GLView)
#endif
SDL_EraseCursor(SDL_VideoSurface);
SDL_SetCursor(NULL);
}
if ( mouse_relative ) {
int half_w = (SDL_VideoSurface->w/2);
int half_h = (SDL_VideoSurface->h/2);
x -= half_w;
y -= half_h;
if ( x || y ) {
BPoint center;
GetXYOffset(center.x, center.y);
center.x += half_w;
center.y += half_h;
ConvertToScreen(¢er);
set_mouse_position((int)center.x, (int)center.y);
SDL_PrivateMouseMotion(0, 1, x, y);
}
} else {
SDL_PrivateMouseMotion(0, 0, x, y);
}
}
}
break;
}
case B_MOUSE_DOWN:
{
/* it looks like mouse down is send only for first clicked
button, each next is not send while last one is holded */
int32 buttons;
int sdl_buttons = 0;
if (msg->FindInt32("buttons", &buttons) == B_OK) {
/* Add any mouse button events */
if (buttons & B_PRIMARY_MOUSE_BUTTON) {
sdl_buttons |= SDL_BUTTON_LEFT;
}
if (buttons & B_SECONDARY_MOUSE_BUTTON) {
sdl_buttons |= SDL_BUTTON_RIGHT;
}
if (buttons & B_TERTIARY_MOUSE_BUTTON) {
sdl_buttons |= SDL_BUTTON_MIDDLE;
}
SDL_PrivateMouseButton(SDL_PRESSED, sdl_buttons, 0, 0);
last_buttons = buttons;
}
break;
}
case B_MOUSE_UP:
{
/* mouse up doesn't give which button was released,
only state of buttons (after release, so it's always = 0),
which is not what we need ;]
So we need to store button in mouse down, and restore
in mouse up :(
mouse up is (similarly to mouse down) send only for
first button down (ie. it's no send if we click another button
without releasing previous one first) - but that's probably
because of how drivers are written?, not BeOS itself. */
int32 buttons;
int sdl_buttons = 0;
if (msg->FindInt32("buttons", &buttons) == B_OK) {
/* Add any mouse button events */
if ((buttons ^ B_PRIMARY_MOUSE_BUTTON) & last_buttons) {
sdl_buttons |= SDL_BUTTON_LEFT;
}
if ((buttons ^ B_SECONDARY_MOUSE_BUTTON) & last_buttons) {
sdl_buttons |= SDL_BUTTON_RIGHT;
}
if ((buttons ^ B_TERTIARY_MOUSE_BUTTON) & last_buttons) {
sdl_buttons |= SDL_BUTTON_MIDDLE;
}
SDL_PrivateMouseButton(SDL_RELEASED, sdl_buttons, 0, 0);
last_buttons = buttons;
}
break;
}
case B_MOUSE_WHEEL_CHANGED:
{
float x, y;
x = y = 0;
if (msg->FindFloat("be:wheel_delta_x", &x) == B_OK && msg->FindFloat("be:wheel_delta_y", &y) == B_OK) {
if (x < 0 || y < 0) {
SDL_PrivateMouseButton(SDL_PRESSED, SDL_BUTTON_WHEELDOWN, 0, 0);
SDL_PrivateMouseButton(SDL_RELEASED, SDL_BUTTON_WHEELDOWN, 0, 0);
} else if (x > 0 || y > 0) {
SDL_PrivateMouseButton(SDL_PRESSED, SDL_BUTTON_WHEELUP, 0, 0);
SDL_PrivateMouseButton(SDL_RELEASED, SDL_BUTTON_WHEELUP, 0, 0);
}
}
break;
}
case B_KEY_DOWN:
case B_UNMAPPED_KEY_DOWN: /* modifier keys are unmapped */
{
int32 key;
int32 modifiers;
int32 key_repeat;
/* Workaround for SDL message queue being filled too fast because of BeOS own key-repeat mechanism */
if (msg->FindInt32("be:key_repeat", &key_repeat) == B_OK && key_repeat > 0)
break;
if (msg->FindInt32("key", &key) == B_OK && msg->FindInt32("modifiers", &modifiers) == B_OK) {
SDL_keysym keysym;
keysym.scancode = key;
if (key < 128) {
keysym.sym = keymap[key];
} else {
keysym.sym = SDLK_UNKNOWN;
}
/* FIX THIS?
it seems SDL_PrivateKeyboard() changes mod value
anyway, and doesn't care about what we setup here */
keysym.mod = KMOD_NONE;
keysym.unicode = 0;
if (SDL_TranslateUNICODE) {
const char *bytes;
if (msg->FindString("bytes", &bytes) == B_OK) {
/* FIX THIS?
this cares only about first "letter",
so if someone maps some key to print
"BeOS rulez!" only "B" will be used. */
keysym.unicode = Translate2Unicode(bytes);
}
}
SDL_PrivateKeyboard(SDL_PRESSED, &keysym);
}
break;
}
case B_KEY_UP:
case B_UNMAPPED_KEY_UP: /* modifier keys are unmapped */
{
int32 key;
int32 modifiers;
if (msg->FindInt32("key", &key) == B_OK && msg->FindInt32("modifiers", &modifiers) == B_OK) {
SDL_keysym keysym;
keysym.scancode = key;
if (key < 128) {
keysym.sym = keymap[key];
} else {
keysym.sym = SDLK_UNKNOWN;
}
keysym.mod = KMOD_NONE; /* FIX THIS? */
keysym.unicode = 0;
if (SDL_TranslateUNICODE) {
const char *bytes;
if (msg->FindString("bytes", &bytes) == B_OK) {
keysym.unicode = Translate2Unicode(bytes);
}
}
SDL_PrivateKeyboard(SDL_RELEASED, &keysym);
}
break;
}
default:
/* move it after switch{} so it's always handled
that way we keep BeOS feautures like:
- CTRL+Q to close window (and other shortcuts)
- PrintScreen to make screenshot into /boot/home
- etc.. */
//BDirectWindow::DispatchMessage(msg, target);
break;
}
BDirectWindow::DispatchMessage(msg, target);
}
void SDL_BWin::DirectConnected(direct_buffer_info *info) {
switch (info->buffer_state & B_DIRECT_MODE_MASK) {
case B_DIRECT_START:
case B_DIRECT_MODIFY:
{
int32 width = info->window_bounds.right -
info->window_bounds.left;
int32 height = info->window_bounds.bottom -
info->window_bounds.top;
SDL_PrivateResize(width, height);
break;
}
default:
break;
}
#if SDL_VIDEO_OPENGL
// If it is a BGLView, it is apparently required to
// call DirectConnected() on it as well
if (this->the_view == this->SDL_GLView)
this->SDL_GLView->DirectConnected(info);
#endif
}
| 412 | 0.983534 | 1 | 0.983534 | game-dev | MEDIA | 0.892156 | game-dev | 0.951227 | 1 | 0.951227 |
Solen1985/CivOne | 2,310 | src/Screens/UnitStack.cs | // CivOne
//
// To the extent possible under law, the person who associated CC0 with
// CivOne has waived all copyright and related or neighboring rights
// to CivOne.
//
// You should have received a copy of the CC0 legalcode along with this
// work. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
using System.Linq;
using CivOne.Enums;
using CivOne.Events;
using CivOne.Graphics;
using CivOne.Units;
namespace CivOne.Screens
{
internal class UnitStack : BaseScreen
{
private const int XX = 101;
private const int WIDTH = 121;
private readonly int _x, _y;
private readonly IUnit[] _units;
private bool _update = true;
protected override bool HasUpdate(uint gameTick)
{
if (_update)
{
if (!_units.Any())
{
// No units, close the dialog
Destroy();
return true;
}
int height = (16 * _units.Length) + 6;
int yy = (200 - height) / 2;
Picture dialog = new Picture(WIDTH, height)
.FillRectangle(1, 1, WIDTH - 2, height - 2, 3)
.DrawRectangle3D()
.As<Picture>();
for (int i = 0; i < _units.Length; i++)
{
IUnit unit = _units[i];
dialog.AddLayer(unit.ToBitmap(), 4, (i * 16) + 3)
.DrawText(unit.Name + (unit.Veteran ? " (V)" : ""), 0, 15, 27, (i * 16) + 4)
.DrawText(unit.Home == null ? "NONE" : unit.Home.Name, 0, 14, 27, (i * 16) + 12);
}
this.FillRectangle(XX - 1, yy - 1, WIDTH + 2, height + 2, 5)
.AddLayer(dialog, XX, yy);
return true;
}
return false;
}
public override bool KeyDown(KeyboardEventArgs args)
{
Destroy();
return true;
}
public override bool MouseDown(ScreenEventArgs args)
{
if (args.X >= XX && args.X < (XX + WIDTH))
{
int height = (16 * _units.Length) + 6;
int yy = (200 - height) / 2;
if (args.Y >= yy && args.Y < (yy + height))
{
int y = (args.Y - yy - 3);
int uid = (y - (y % 16)) / 16;
if (uid < 0 || uid >= _units.Length)
return true;
Game.ActiveUnit = _units[uid];
_units[uid].Busy = false;
return true;
}
}
Destroy();
return true;
}
internal UnitStack(int x, int y) : base(MouseCursor.Pointer)
{
_x = x;
_y = y;
_units = Map[_x, _y].Units.Take(12).ToArray();
Palette = Common.TopScreen.Palette;
}
}
} | 412 | 0.764971 | 1 | 0.764971 | game-dev | MEDIA | 0.411067 | game-dev | 0.862495 | 1 | 0.862495 |
berthrage/DMC3-Crimson | 39,606 | ThirdParty/SDL2/SDL_joystick.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_joystick.h
*
* Include file for SDL joystick event handling
*
* The term "device_index" identifies currently plugged in joystick devices between 0 and SDL_NumJoysticks(), with the exact joystick
* behind a device_index changing as joysticks are plugged and unplugged.
*
* The term "instance_id" is the current instantiation of a joystick device in the system, if the joystick is removed and then re-inserted
* then it will get a new instance_id, instance_id's are monotonically increasing identifiers of a joystick plugged in.
*
* The term "player_index" is the number assigned to a player on a specific
* controller. For XInput controllers this returns the XInput user index.
* Many joysticks will not be able to supply this information.
*
* The term JoystickGUID is a stable 128-bit identifier for a joystick device that does not change over time, it identifies class of
* the device (a X360 wired controller for example). This identifier is platform dependent.
*/
#ifndef SDL_joystick_h_
#define SDL_joystick_h_
#include "SDL_stdinc.h"
#include "SDL_error.h"
#include "SDL_guid.h"
#include "SDL_mutex.h"
#include "begin_code.h"
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
extern "C" {
#endif
/**
* \file SDL_joystick.h
*
* In order to use these functions, SDL_Init() must have been called
* with the ::SDL_INIT_JOYSTICK flag. This causes SDL to scan the system
* for joysticks, and load appropriate drivers.
*
* If you would like to receive joystick updates while the application
* is in the background, you should set the following hint before calling
* SDL_Init(): SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS
*/
/**
* The joystick structure used to identify an SDL joystick
*/
#ifdef SDL_THREAD_SAFETY_ANALYSIS
extern SDL_mutex *SDL_joystick_lock;
#endif
struct _SDL_Joystick;
typedef struct _SDL_Joystick SDL_Joystick;
/* A structure that encodes the stable unique id for a joystick device */
typedef SDL_GUID SDL_JoystickGUID;
/**
* This is a unique ID for a joystick for the time it is connected to the system,
* and is never reused for the lifetime of the application. If the joystick is
* disconnected and reconnected, it will get a new ID.
*
* The ID value starts at 0 and increments from there. The value -1 is an invalid ID.
*/
typedef Sint32 SDL_JoystickID;
typedef enum
{
SDL_JOYSTICK_TYPE_UNKNOWN,
SDL_JOYSTICK_TYPE_GAMECONTROLLER,
SDL_JOYSTICK_TYPE_WHEEL,
SDL_JOYSTICK_TYPE_ARCADE_STICK,
SDL_JOYSTICK_TYPE_FLIGHT_STICK,
SDL_JOYSTICK_TYPE_DANCE_PAD,
SDL_JOYSTICK_TYPE_GUITAR,
SDL_JOYSTICK_TYPE_DRUM_KIT,
SDL_JOYSTICK_TYPE_ARCADE_PAD,
SDL_JOYSTICK_TYPE_THROTTLE
} SDL_JoystickType;
typedef enum
{
SDL_JOYSTICK_POWER_UNKNOWN = -1,
SDL_JOYSTICK_POWER_EMPTY, /* <= 5% */
SDL_JOYSTICK_POWER_LOW, /* <= 20% */
SDL_JOYSTICK_POWER_MEDIUM, /* <= 70% */
SDL_JOYSTICK_POWER_FULL, /* <= 100% */
SDL_JOYSTICK_POWER_WIRED,
SDL_JOYSTICK_POWER_MAX
} SDL_JoystickPowerLevel;
typedef enum
{
SDL_JOYSTICK_BUTTON_INVALID = -1,
SDL_JOYSTICK_BUTTON_A = 0,
SDL_JOYSTICK_BUTTON_B = 1,
SDL_JOYSTICK_BUTTON_X = 2,
SDL_JOYSTICK_BUTTON_Y = 3,
SDL_JOYSTICK_BUTTON_LEFTSHOULDER = 4,
SDL_JOYSTICK_BUTTON_RIGHTSHOULDER = 5,
SDL_JOYSTICK_BUTTON_BACK = 6,
SDL_JOYSTICK_BUTTON_START = 7,
SDL_JOYSTICK_BUTTON_LEFTSTICK = 8,
SDL_JOYSTICK_BUTTON_RIGHTSTICK = 9,
SDL_JOYSTICK_BUTTON_GUIDE,
SDL_JOYSTICK_BUTTON_MAX
} SDL_JoystickButton;
/* Set max recognized G-force from accelerometer
See src/joystick/uikit/SDL_sysjoystick.m for notes on why this is needed
*/
#define SDL_IPHONE_MAX_GFORCE 5.0
/* Function prototypes */
/**
* Locking for multi-threaded access to the joystick API
*
* If you are using the joystick API or handling events from multiple threads
* you should use these locking functions to protect access to the joysticks.
*
* In particular, you are guaranteed that the joystick list won't change, so
* the API functions that take a joystick index will be valid, and joystick
* and game controller events will not be delivered.
*
* As of SDL 2.26.0, you can take the joystick lock around reinitializing the
* joystick subsystem, to prevent other threads from seeing joysticks in an
* uninitialized state. However, all open joysticks will be closed and SDL
* functions called with them will fail.
*
* \since This function is available since SDL 2.0.7.
*/
extern DECLSPEC void SDLCALL SDL_LockJoysticks(void) SDL_ACQUIRE(SDL_joystick_lock);
/**
* Unlocking for multi-threaded access to the joystick API
*
* If you are using the joystick API or handling events from multiple threads
* you should use these locking functions to protect access to the joysticks.
*
* In particular, you are guaranteed that the joystick list won't change, so
* the API functions that take a joystick index will be valid, and joystick
* and game controller events will not be delivered.
*
* \since This function is available since SDL 2.0.7.
*/
extern DECLSPEC void SDLCALL SDL_UnlockJoysticks(void) SDL_RELEASE(SDL_joystick_lock);
/**
* Count the number of joysticks attached to the system.
*
* \returns the number of attached joysticks on success or a negative error
* code on failure; call SDL_GetError() for more information.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_JoystickName
* \sa SDL_JoystickPath
* \sa SDL_JoystickOpen
*/
extern DECLSPEC int SDLCALL SDL_NumJoysticks(void);
/**
* Get the implementation dependent name of a joystick.
*
* This can be called before any joysticks are opened.
*
* \param device_index the index of the joystick to query (the N'th joystick
* on the system)
* \returns the name of the selected joystick. If no name can be found, this
* function returns NULL; call SDL_GetError() for more information.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_JoystickName
* \sa SDL_JoystickOpen
*/
extern DECLSPEC const char *SDLCALL SDL_JoystickNameForIndex(int device_index);
/**
* Get the implementation dependent path of a joystick.
*
* This can be called before any joysticks are opened.
*
* \param device_index the index of the joystick to query (the N'th joystick
* on the system)
* \returns the path of the selected joystick. If no path can be found, this
* function returns NULL; call SDL_GetError() for more information.
*
* \since This function is available since SDL 2.24.0.
*
* \sa SDL_JoystickPath
* \sa SDL_JoystickOpen
*/
extern DECLSPEC const char *SDLCALL SDL_JoystickPathForIndex(int device_index);
/**
* Get the player index of a joystick, or -1 if it's not available This can be
* called before any joysticks are opened.
*
* \since This function is available since SDL 2.0.9.
*/
extern DECLSPEC int SDLCALL SDL_JoystickGetDevicePlayerIndex(int device_index);
/**
* Get the implementation-dependent GUID for the joystick at a given device
* index.
*
* This function can be called before any joysticks are opened.
*
* \param device_index the index of the joystick to query (the N'th joystick
* on the system
* \returns the GUID of the selected joystick. If called on an invalid index,
* this function returns a zero GUID
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_JoystickGetGUID
* \sa SDL_JoystickGetGUIDString
*/
extern DECLSPEC SDL_JoystickGUID SDLCALL SDL_JoystickGetDeviceGUID(int device_index);
/**
* Get the USB vendor ID of a joystick, if available.
*
* This can be called before any joysticks are opened. If the vendor ID isn't
* available this function returns 0.
*
* \param device_index the index of the joystick to query (the N'th joystick
* on the system
* \returns the USB vendor ID of the selected joystick. If called on an
* invalid index, this function returns zero
*
* \since This function is available since SDL 2.0.6.
*/
extern DECLSPEC Uint16 SDLCALL SDL_JoystickGetDeviceVendor(int device_index);
/**
* Get the USB product ID of a joystick, if available.
*
* This can be called before any joysticks are opened. If the product ID isn't
* available this function returns 0.
*
* \param device_index the index of the joystick to query (the N'th joystick
* on the system
* \returns the USB product ID of the selected joystick. If called on an
* invalid index, this function returns zero
*
* \since This function is available since SDL 2.0.6.
*/
extern DECLSPEC Uint16 SDLCALL SDL_JoystickGetDeviceProduct(int device_index);
/**
* Get the product version of a joystick, if available.
*
* This can be called before any joysticks are opened. If the product version
* isn't available this function returns 0.
*
* \param device_index the index of the joystick to query (the N'th joystick
* on the system
* \returns the product version of the selected joystick. If called on an
* invalid index, this function returns zero
*
* \since This function is available since SDL 2.0.6.
*/
extern DECLSPEC Uint16 SDLCALL SDL_JoystickGetDeviceProductVersion(int device_index);
/**
* Get the type of a joystick, if available.
*
* This can be called before any joysticks are opened.
*
* \param device_index the index of the joystick to query (the N'th joystick
* on the system
* \returns the SDL_JoystickType of the selected joystick. If called on an
* invalid index, this function returns `SDL_JOYSTICK_TYPE_UNKNOWN`
*
* \since This function is available since SDL 2.0.6.
*/
extern DECLSPEC SDL_JoystickType SDLCALL SDL_JoystickGetDeviceType(int device_index);
/**
* Get the instance ID of a joystick.
*
* This can be called before any joysticks are opened.
*
* \param device_index the index of the joystick to query (the N'th joystick
* on the system
* \returns the instance id of the selected joystick. If called on an invalid
* index, this function returns -1.
*
* \since This function is available since SDL 2.0.6.
*/
extern DECLSPEC SDL_JoystickID SDLCALL SDL_JoystickGetDeviceInstanceID(int device_index);
/**
* Open a joystick for use.
*
* The `device_index` argument refers to the N'th joystick presently
* recognized by SDL on the system. It is **NOT** the same as the instance ID
* used to identify the joystick in future events. See
* SDL_JoystickInstanceID() for more details about instance IDs.
*
* The joystick subsystem must be initialized before a joystick can be opened
* for use.
*
* \param device_index the index of the joystick to query
* \returns a joystick identifier or NULL if an error occurred; call
* SDL_GetError() for more information.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_JoystickClose
* \sa SDL_JoystickInstanceID
*/
extern DECLSPEC SDL_Joystick *SDLCALL SDL_JoystickOpen(int device_index);
/**
* Get the SDL_Joystick associated with an instance id.
*
* \param instance_id the instance id to get the SDL_Joystick for
* \returns an SDL_Joystick on success or NULL on failure; call SDL_GetError()
* for more information.
*
* \since This function is available since SDL 2.0.4.
*/
extern DECLSPEC SDL_Joystick *SDLCALL SDL_JoystickFromInstanceID(SDL_JoystickID instance_id);
/**
* Get the SDL_Joystick associated with a player index.
*
* \param player_index the player index to get the SDL_Joystick for
* \returns an SDL_Joystick on success or NULL on failure; call SDL_GetError()
* for more information.
*
* \since This function is available since SDL 2.0.12.
*/
extern DECLSPEC SDL_Joystick *SDLCALL SDL_JoystickFromPlayerIndex(int player_index);
/**
* Attach a new virtual joystick.
*
* \returns the joystick's device index, or -1 if an error occurred.
*
* \since This function is available since SDL 2.0.14.
*/
extern DECLSPEC int SDLCALL SDL_JoystickAttachVirtual(SDL_JoystickType type,
int naxes,
int nbuttons,
int nhats);
/**
* The structure that defines an extended virtual joystick description
*
* The caller must zero the structure and then initialize the version with `SDL_VIRTUAL_JOYSTICK_DESC_VERSION` before passing it to SDL_JoystickAttachVirtualEx()
* All other elements of this structure are optional and can be left 0.
*
* \sa SDL_JoystickAttachVirtualEx
*/
typedef struct SDL_VirtualJoystickDesc
{
Uint16 version; /**< `SDL_VIRTUAL_JOYSTICK_DESC_VERSION` */
Uint16 type; /**< `SDL_JoystickType` */
Uint16 naxes; /**< the number of axes on this joystick */
Uint16 nbuttons; /**< the number of buttons on this joystick */
Uint16 nhats; /**< the number of hats on this joystick */
Uint16 vendor_id; /**< the USB vendor ID of this joystick */
Uint16 product_id; /**< the USB product ID of this joystick */
Uint16 padding; /**< unused */
Uint32 button_mask; /**< A mask of which buttons are valid for this controller
e.g. (1 << SDL_CONTROLLER_BUTTON_A) */
Uint32 axis_mask; /**< A mask of which axes are valid for this controller
e.g. (1 << SDL_CONTROLLER_AXIS_LEFTX) */
const char *name; /**< the name of the joystick */
void *userdata; /**< User data pointer passed to callbacks */
void (SDLCALL *Update)(void *userdata); /**< Called when the joystick state should be updated */
void (SDLCALL *SetPlayerIndex)(void *userdata, int player_index); /**< Called when the player index is set */
int (SDLCALL *Rumble)(void *userdata, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble); /**< Implements SDL_JoystickRumble() */
int (SDLCALL *RumbleTriggers)(void *userdata, Uint16 left_rumble, Uint16 right_rumble); /**< Implements SDL_JoystickRumbleTriggers() */
int (SDLCALL *SetLED)(void *userdata, Uint8 red, Uint8 green, Uint8 blue); /**< Implements SDL_JoystickSetLED() */
int (SDLCALL *SendEffect)(void *userdata, const void *data, int size); /**< Implements SDL_JoystickSendEffect() */
} SDL_VirtualJoystickDesc;
/**
* \brief The current version of the SDL_VirtualJoystickDesc structure
*/
#define SDL_VIRTUAL_JOYSTICK_DESC_VERSION 1
/**
* Attach a new virtual joystick with extended properties.
*
* \returns the joystick's device index, or -1 if an error occurred.
*
* \since This function is available since SDL 2.24.0.
*/
extern DECLSPEC int SDLCALL SDL_JoystickAttachVirtualEx(const SDL_VirtualJoystickDesc *desc);
/**
* Detach a virtual joystick.
*
* \param device_index a value previously returned from
* SDL_JoystickAttachVirtual()
* \returns 0 on success, or -1 if an error occurred.
*
* \since This function is available since SDL 2.0.14.
*/
extern DECLSPEC int SDLCALL SDL_JoystickDetachVirtual(int device_index);
/**
* Query whether or not the joystick at a given device index is virtual.
*
* \param device_index a joystick device index.
* \returns SDL_TRUE if the joystick is virtual, SDL_FALSE otherwise.
*
* \since This function is available since SDL 2.0.14.
*/
extern DECLSPEC SDL_bool SDLCALL SDL_JoystickIsVirtual(int device_index);
/**
* Set values on an opened, virtual-joystick's axis.
*
* Please note that values set here will not be applied until the next call to
* SDL_JoystickUpdate, which can either be called directly, or can be called
* indirectly through various other SDL APIs, including, but not limited to
* the following: SDL_PollEvent, SDL_PumpEvents, SDL_WaitEventTimeout,
* SDL_WaitEvent.
*
* Note that when sending trigger axes, you should scale the value to the full
* range of Sint16. For example, a trigger at rest would have the value of
* `SDL_JOYSTICK_AXIS_MIN`.
*
* \param joystick the virtual joystick on which to set state.
* \param axis the specific axis on the virtual joystick to set.
* \param value the new value for the specified axis.
* \returns 0 on success, -1 on error.
*
* \since This function is available since SDL 2.0.14.
*/
extern DECLSPEC int SDLCALL SDL_JoystickSetVirtualAxis(SDL_Joystick *joystick, int axis, Sint16 value);
/**
* Set values on an opened, virtual-joystick's button.
*
* Please note that values set here will not be applied until the next call to
* SDL_JoystickUpdate, which can either be called directly, or can be called
* indirectly through various other SDL APIs, including, but not limited to
* the following: SDL_PollEvent, SDL_PumpEvents, SDL_WaitEventTimeout,
* SDL_WaitEvent.
*
* \param joystick the virtual joystick on which to set state.
* \param button the specific button on the virtual joystick to set.
* \param value the new value for the specified button.
* \returns 0 on success, -1 on error.
*
* \since This function is available since SDL 2.0.14.
*/
extern DECLSPEC int SDLCALL SDL_JoystickSetVirtualButton(SDL_Joystick *joystick, int button, Uint8 value);
/**
* Set values on an opened, virtual-joystick's hat.
*
* Please note that values set here will not be applied until the next call to
* SDL_JoystickUpdate, which can either be called directly, or can be called
* indirectly through various other SDL APIs, including, but not limited to
* the following: SDL_PollEvent, SDL_PumpEvents, SDL_WaitEventTimeout,
* SDL_WaitEvent.
*
* \param joystick the virtual joystick on which to set state.
* \param hat the specific hat on the virtual joystick to set.
* \param value the new value for the specified hat.
* \returns 0 on success, -1 on error.
*
* \since This function is available since SDL 2.0.14.
*/
extern DECLSPEC int SDLCALL SDL_JoystickSetVirtualHat(SDL_Joystick *joystick, int hat, Uint8 value);
/**
* Get the implementation dependent name of a joystick.
*
* \param joystick the SDL_Joystick obtained from SDL_JoystickOpen()
* \returns the name of the selected joystick. If no name can be found, this
* function returns NULL; call SDL_GetError() for more information.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_JoystickNameForIndex
* \sa SDL_JoystickOpen
*/
extern DECLSPEC const char *SDLCALL SDL_JoystickName(SDL_Joystick *joystick);
/**
* Get the implementation dependent path of a joystick.
*
* \param joystick the SDL_Joystick obtained from SDL_JoystickOpen()
* \returns the path of the selected joystick. If no path can be found, this
* function returns NULL; call SDL_GetError() for more information.
*
* \since This function is available since SDL 2.24.0.
*
* \sa SDL_JoystickPathForIndex
*/
extern DECLSPEC const char *SDLCALL SDL_JoystickPath(SDL_Joystick *joystick);
/**
* Get the player index of an opened joystick.
*
* For XInput controllers this returns the XInput user index. Many joysticks
* will not be able to supply this information.
*
* \param joystick the SDL_Joystick obtained from SDL_JoystickOpen()
* \returns the player index, or -1 if it's not available.
*
* \since This function is available since SDL 2.0.9.
*/
extern DECLSPEC int SDLCALL SDL_JoystickGetPlayerIndex(SDL_Joystick *joystick);
/**
* Set the player index of an opened joystick.
*
* \param joystick the SDL_Joystick obtained from SDL_JoystickOpen()
* \param player_index Player index to assign to this joystick, or -1 to clear
* the player index and turn off player LEDs.
*
* \since This function is available since SDL 2.0.12.
*/
extern DECLSPEC void SDLCALL SDL_JoystickSetPlayerIndex(SDL_Joystick *joystick, int player_index);
/**
* Get the implementation-dependent GUID for the joystick.
*
* This function requires an open joystick.
*
* \param joystick the SDL_Joystick obtained from SDL_JoystickOpen()
* \returns the GUID of the given joystick. If called on an invalid index,
* this function returns a zero GUID; call SDL_GetError() for more
* information.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_JoystickGetDeviceGUID
* \sa SDL_JoystickGetGUIDString
*/
extern DECLSPEC SDL_JoystickGUID SDLCALL SDL_JoystickGetGUID(SDL_Joystick *joystick);
/**
* Get the USB vendor ID of an opened joystick, if available.
*
* If the vendor ID isn't available this function returns 0.
*
* \param joystick the SDL_Joystick obtained from SDL_JoystickOpen()
* \returns the USB vendor ID of the selected joystick, or 0 if unavailable.
*
* \since This function is available since SDL 2.0.6.
*/
extern DECLSPEC Uint16 SDLCALL SDL_JoystickGetVendor(SDL_Joystick *joystick);
/**
* Get the USB product ID of an opened joystick, if available.
*
* If the product ID isn't available this function returns 0.
*
* \param joystick the SDL_Joystick obtained from SDL_JoystickOpen()
* \returns the USB product ID of the selected joystick, or 0 if unavailable.
*
* \since This function is available since SDL 2.0.6.
*/
extern DECLSPEC Uint16 SDLCALL SDL_JoystickGetProduct(SDL_Joystick *joystick);
/**
* Get the product version of an opened joystick, if available.
*
* If the product version isn't available this function returns 0.
*
* \param joystick the SDL_Joystick obtained from SDL_JoystickOpen()
* \returns the product version of the selected joystick, or 0 if unavailable.
*
* \since This function is available since SDL 2.0.6.
*/
extern DECLSPEC Uint16 SDLCALL SDL_JoystickGetProductVersion(SDL_Joystick *joystick);
/**
* Get the firmware version of an opened joystick, if available.
*
* If the firmware version isn't available this function returns 0.
*
* \param joystick the SDL_Joystick obtained from SDL_JoystickOpen()
* \returns the firmware version of the selected joystick, or 0 if
* unavailable.
*
* \since This function is available since SDL 2.24.0.
*/
extern DECLSPEC Uint16 SDLCALL SDL_JoystickGetFirmwareVersion(SDL_Joystick *joystick);
/**
* Get the serial number of an opened joystick, if available.
*
* Returns the serial number of the joystick, or NULL if it is not available.
*
* \param joystick the SDL_Joystick obtained from SDL_JoystickOpen()
* \returns the serial number of the selected joystick, or NULL if
* unavailable.
*
* \since This function is available since SDL 2.0.14.
*/
extern DECLSPEC const char * SDLCALL SDL_JoystickGetSerial(SDL_Joystick *joystick);
/**
* Get the type of an opened joystick.
*
* \param joystick the SDL_Joystick obtained from SDL_JoystickOpen()
* \returns the SDL_JoystickType of the selected joystick.
*
* \since This function is available since SDL 2.0.6.
*/
extern DECLSPEC SDL_JoystickType SDLCALL SDL_JoystickGetType(SDL_Joystick *joystick);
/**
* Get an ASCII string representation for a given SDL_JoystickGUID.
*
* You should supply at least 33 bytes for pszGUID.
*
* \param guid the SDL_JoystickGUID you wish to convert to string
* \param pszGUID buffer in which to write the ASCII string
* \param cbGUID the size of pszGUID
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_JoystickGetDeviceGUID
* \sa SDL_JoystickGetGUID
* \sa SDL_JoystickGetGUIDFromString
*/
extern DECLSPEC void SDLCALL SDL_JoystickGetGUIDString(SDL_JoystickGUID guid, char *pszGUID, int cbGUID);
/**
* Convert a GUID string into a SDL_JoystickGUID structure.
*
* Performs no error checking. If this function is given a string containing
* an invalid GUID, the function will silently succeed, but the GUID generated
* will not be useful.
*
* \param pchGUID string containing an ASCII representation of a GUID
* \returns a SDL_JoystickGUID structure.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_JoystickGetGUIDString
*/
extern DECLSPEC SDL_JoystickGUID SDLCALL SDL_JoystickGetGUIDFromString(const char *pchGUID);
/**
* Get the device information encoded in a SDL_JoystickGUID structure
*
* \param guid the SDL_JoystickGUID you wish to get info about
* \param vendor A pointer filled in with the device VID, or 0 if not
* available
* \param product A pointer filled in with the device PID, or 0 if not
* available
* \param version A pointer filled in with the device version, or 0 if not
* available
* \param crc16 A pointer filled in with a CRC used to distinguish different
* products with the same VID/PID, or 0 if not available
*
* \since This function is available since SDL 2.26.0.
*
* \sa SDL_JoystickGetDeviceGUID
*/
extern DECLSPEC void SDLCALL SDL_GetJoystickGUIDInfo(SDL_JoystickGUID guid, Uint16 *vendor, Uint16 *product, Uint16 *version, Uint16 *crc16);
/**
* Get the status of a specified joystick.
*
* \param joystick the joystick to query
* \returns SDL_TRUE if the joystick has been opened, SDL_FALSE if it has not;
* call SDL_GetError() for more information.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_JoystickClose
* \sa SDL_JoystickOpen
*/
extern DECLSPEC SDL_bool SDLCALL SDL_JoystickGetAttached(SDL_Joystick *joystick);
/**
* Get the instance ID of an opened joystick.
*
* \param joystick an SDL_Joystick structure containing joystick information
* \returns the instance ID of the specified joystick on success or a negative
* error code on failure; call SDL_GetError() for more information.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_JoystickOpen
*/
extern DECLSPEC SDL_JoystickID SDLCALL SDL_JoystickInstanceID(SDL_Joystick *joystick);
/**
* Get the number of general axis controls on a joystick.
*
* Often, the directional pad on a game controller will either look like 4
* separate buttons or a POV hat, and not axes, but all of this is up to the
* device and platform.
*
* \param joystick an SDL_Joystick structure containing joystick information
* \returns the number of axis controls/number of axes on success or a
* negative error code on failure; call SDL_GetError() for more
* information.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_JoystickGetAxis
* \sa SDL_JoystickOpen
*/
extern DECLSPEC int SDLCALL SDL_JoystickNumAxes(SDL_Joystick *joystick);
/**
* Get the number of trackballs on a joystick.
*
* Joystick trackballs have only relative motion events associated with them
* and their state cannot be polled.
*
* Most joysticks do not have trackballs.
*
* \param joystick an SDL_Joystick structure containing joystick information
* \returns the number of trackballs on success or a negative error code on
* failure; call SDL_GetError() for more information.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_JoystickGetBall
*/
extern DECLSPEC int SDLCALL SDL_JoystickNumBalls(SDL_Joystick *joystick);
/**
* Get the number of POV hats on a joystick.
*
* \param joystick an SDL_Joystick structure containing joystick information
* \returns the number of POV hats on success or a negative error code on
* failure; call SDL_GetError() for more information.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_JoystickGetHat
* \sa SDL_JoystickOpen
*/
extern DECLSPEC int SDLCALL SDL_JoystickNumHats(SDL_Joystick *joystick);
/**
* Get the number of buttons on a joystick.
*
* \param joystick an SDL_Joystick structure containing joystick information
* \returns the number of buttons on success or a negative error code on
* failure; call SDL_GetError() for more information.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_JoystickGetButton
* \sa SDL_JoystickOpen
*/
extern DECLSPEC int SDLCALL SDL_JoystickNumButtons(SDL_Joystick *joystick);
/**
* Update the current state of the open joysticks.
*
* This is called automatically by the event loop if any joystick events are
* enabled.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_JoystickEventState
*/
extern DECLSPEC void SDLCALL SDL_JoystickUpdate(void);
/**
* Enable/disable joystick event polling.
*
* If joystick events are disabled, you must call SDL_JoystickUpdate()
* yourself and manually check the state of the joystick when you want
* joystick information.
*
* It is recommended that you leave joystick event handling enabled.
*
* **WARNING**: Calling this function may delete all events currently in SDL's
* event queue.
*
* \param state can be one of `SDL_QUERY`, `SDL_IGNORE`, or `SDL_ENABLE`
* \returns 1 if enabled, 0 if disabled, or a negative error code on failure;
* call SDL_GetError() for more information.
*
* If `state` is `SDL_QUERY` then the current state is returned,
* otherwise the new processing state is returned.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_GameControllerEventState
*/
extern DECLSPEC int SDLCALL SDL_JoystickEventState(int state);
#define SDL_JOYSTICK_AXIS_MAX 32767
#define SDL_JOYSTICK_AXIS_MIN -32768
/**
* Get the current state of an axis control on a joystick.
*
* SDL makes no promises about what part of the joystick any given axis refers
* to. Your game should have some sort of configuration UI to let users
* specify what each axis should be bound to. Alternately, SDL's higher-level
* Game Controller API makes a great effort to apply order to this lower-level
* interface, so you know that a specific axis is the "left thumb stick," etc.
*
* The value returned by SDL_JoystickGetAxis() is a signed integer (-32768 to
* 32767) representing the current position of the axis. It may be necessary
* to impose certain tolerances on these values to account for jitter.
*
* \param joystick an SDL_Joystick structure containing joystick information
* \param axis the axis to query; the axis indices start at index 0
* \returns a 16-bit signed integer representing the current position of the
* axis or 0 on failure; call SDL_GetError() for more information.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_JoystickNumAxes
*/
extern DECLSPEC Sint16 SDLCALL SDL_JoystickGetAxis(SDL_Joystick *joystick,
int axis);
/**
* Get the initial state of an axis control on a joystick.
*
* The state is a value ranging from -32768 to 32767.
*
* The axis indices start at index 0.
*
* \param joystick an SDL_Joystick structure containing joystick information
* \param axis the axis to query; the axis indices start at index 0
* \param state Upon return, the initial value is supplied here.
* \return SDL_TRUE if this axis has any initial value, or SDL_FALSE if not.
*
* \since This function is available since SDL 2.0.6.
*/
extern DECLSPEC SDL_bool SDLCALL SDL_JoystickGetAxisInitialState(SDL_Joystick *joystick,
int axis, Sint16 *state);
/**
* \name Hat positions
*/
/* @{ */
#define SDL_HAT_CENTERED 0x00
#define SDL_HAT_UP 0x01
#define SDL_HAT_RIGHT 0x02
#define SDL_HAT_DOWN 0x04
#define SDL_HAT_LEFT 0x08
#define SDL_HAT_RIGHTUP (SDL_HAT_RIGHT|SDL_HAT_UP)
#define SDL_HAT_RIGHTDOWN (SDL_HAT_RIGHT|SDL_HAT_DOWN)
#define SDL_HAT_LEFTUP (SDL_HAT_LEFT|SDL_HAT_UP)
#define SDL_HAT_LEFTDOWN (SDL_HAT_LEFT|SDL_HAT_DOWN)
/* @} */
/**
* Get the current state of a POV hat on a joystick.
*
* The returned value will be one of the following positions:
*
* - `SDL_HAT_CENTERED`
* - `SDL_HAT_UP`
* - `SDL_HAT_RIGHT`
* - `SDL_HAT_DOWN`
* - `SDL_HAT_LEFT`
* - `SDL_HAT_RIGHTUP`
* - `SDL_HAT_RIGHTDOWN`
* - `SDL_HAT_LEFTUP`
* - `SDL_HAT_LEFTDOWN`
*
* \param joystick an SDL_Joystick structure containing joystick information
* \param hat the hat index to get the state from; indices start at index 0
* \returns the current hat position.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_JoystickNumHats
*/
extern DECLSPEC Uint8 SDLCALL SDL_JoystickGetHat(SDL_Joystick *joystick,
int hat);
/**
* Get the ball axis change since the last poll.
*
* Trackballs can only return relative motion since the last call to
* SDL_JoystickGetBall(), these motion deltas are placed into `dx` and `dy`.
*
* Most joysticks do not have trackballs.
*
* \param joystick the SDL_Joystick to query
* \param ball the ball index to query; ball indices start at index 0
* \param dx stores the difference in the x axis position since the last poll
* \param dy stores the difference in the y axis position since the last poll
* \returns 0 on success or a negative error code on failure; call
* SDL_GetError() for more information.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_JoystickNumBalls
*/
extern DECLSPEC int SDLCALL SDL_JoystickGetBall(SDL_Joystick *joystick,
int ball, int *dx, int *dy);
/**
* Get the current state of a button on a joystick.
*
* \param joystick an SDL_Joystick structure containing joystick information
* \param button the button index to get the state from; indices start at
* index 0
* \returns 1 if the specified button is pressed, 0 otherwise.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_JoystickNumButtons
*/
extern DECLSPEC Uint8 SDLCALL SDL_JoystickGetButton(SDL_Joystick *joystick,
int button);
/**
* Start a rumble effect.
*
* Each call to this function cancels any previous rumble effect, and calling
* it with 0 intensity stops any rumbling.
*
* \param joystick The joystick to vibrate
* \param low_frequency_rumble The intensity of the low frequency (left)
* rumble motor, from 0 to 0xFFFF
* \param high_frequency_rumble The intensity of the high frequency (right)
* rumble motor, from 0 to 0xFFFF
* \param duration_ms The duration of the rumble effect, in milliseconds
* \returns 0, or -1 if rumble isn't supported on this joystick
*
* \since This function is available since SDL 2.0.9.
*
* \sa SDL_JoystickHasRumble
*/
extern DECLSPEC int SDLCALL SDL_JoystickRumble(SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble, Uint32 duration_ms);
/**
* Start a rumble effect in the joystick's triggers
*
* Each call to this function cancels any previous trigger rumble effect, and
* calling it with 0 intensity stops any rumbling.
*
* Note that this is rumbling of the _triggers_ and not the game controller as
* a whole. This is currently only supported on Xbox One controllers. If you
* want the (more common) whole-controller rumble, use SDL_JoystickRumble()
* instead.
*
* \param joystick The joystick to vibrate
* \param left_rumble The intensity of the left trigger rumble motor, from 0
* to 0xFFFF
* \param right_rumble The intensity of the right trigger rumble motor, from 0
* to 0xFFFF
* \param duration_ms The duration of the rumble effect, in milliseconds
* \returns 0, or -1 if trigger rumble isn't supported on this joystick
*
* \since This function is available since SDL 2.0.14.
*
* \sa SDL_JoystickHasRumbleTriggers
*/
extern DECLSPEC int SDLCALL SDL_JoystickRumbleTriggers(SDL_Joystick *joystick, Uint16 left_rumble, Uint16 right_rumble, Uint32 duration_ms);
/**
* Query whether a joystick has an LED.
*
* An example of a joystick LED is the light on the back of a PlayStation 4's
* DualShock 4 controller.
*
* \param joystick The joystick to query
* \return SDL_TRUE if the joystick has a modifiable LED, SDL_FALSE otherwise.
*
* \since This function is available since SDL 2.0.14.
*/
extern DECLSPEC SDL_bool SDLCALL SDL_JoystickHasLED(SDL_Joystick *joystick);
/**
* Query whether a joystick has rumble support.
*
* \param joystick The joystick to query
* \return SDL_TRUE if the joystick has rumble, SDL_FALSE otherwise.
*
* \since This function is available since SDL 2.0.18.
*
* \sa SDL_JoystickRumble
*/
extern DECLSPEC SDL_bool SDLCALL SDL_JoystickHasRumble(SDL_Joystick *joystick);
/**
* Query whether a joystick has rumble support on triggers.
*
* \param joystick The joystick to query
* \return SDL_TRUE if the joystick has trigger rumble, SDL_FALSE otherwise.
*
* \since This function is available since SDL 2.0.18.
*
* \sa SDL_JoystickRumbleTriggers
*/
extern DECLSPEC SDL_bool SDLCALL SDL_JoystickHasRumbleTriggers(SDL_Joystick *joystick);
/**
* Update a joystick's LED color.
*
* An example of a joystick LED is the light on the back of a PlayStation 4's
* DualShock 4 controller.
*
* \param joystick The joystick to update
* \param red The intensity of the red LED
* \param green The intensity of the green LED
* \param blue The intensity of the blue LED
* \returns 0 on success, -1 if this joystick does not have a modifiable LED
*
* \since This function is available since SDL 2.0.14.
*/
extern DECLSPEC int SDLCALL SDL_JoystickSetLED(SDL_Joystick *joystick, Uint8 red, Uint8 green, Uint8 blue);
/**
* Send a joystick specific effect packet
*
* \param joystick The joystick to affect
* \param data The data to send to the joystick
* \param size The size of the data to send to the joystick
* \returns 0, or -1 if this joystick or driver doesn't support effect packets
*
* \since This function is available since SDL 2.0.16.
*/
extern DECLSPEC int SDLCALL SDL_JoystickSendEffect(SDL_Joystick *joystick, const void *data, int size);
/**
* Close a joystick previously opened with SDL_JoystickOpen().
*
* \param joystick The joystick device to close
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_JoystickOpen
*/
extern DECLSPEC void SDLCALL SDL_JoystickClose(SDL_Joystick *joystick);
/**
* Get the battery level of a joystick as SDL_JoystickPowerLevel.
*
* \param joystick the SDL_Joystick to query
* \returns the current battery level as SDL_JoystickPowerLevel on success or
* `SDL_JOYSTICK_POWER_UNKNOWN` if it is unknown
*
* \since This function is available since SDL 2.0.4.
*/
extern DECLSPEC SDL_JoystickPowerLevel SDLCALL SDL_JoystickCurrentPowerLevel(SDL_Joystick *joystick);
/* Ends C function definitions when using C++ */
#ifdef __cplusplus
}
#endif
#include "close_code.h"
#endif /* SDL_joystick_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| 412 | 0.733574 | 1 | 0.733574 | game-dev | MEDIA | 0.966487 | game-dev | 0.615156 | 1 | 0.615156 |
hebohang/HEngine | 6,540 | Engine/Source/ThirdParty/bullet3/src/BulletCollision/BroadphaseCollision/btDbvtBroadphase.h | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
///btDbvtBroadphase implementation by Nathanael Presson
#ifndef BT_DBVT_BROADPHASE_H
#define BT_DBVT_BROADPHASE_H
#include "BulletCollision/BroadphaseCollision/btDbvt.h"
#include "BulletCollision/BroadphaseCollision/btOverlappingPairCache.h"
//
// Compile time config
//
#define DBVT_BP_PROFILE 0
//#define DBVT_BP_SORTPAIRS 1
#define DBVT_BP_PREVENTFALSEUPDATE 0
#define DBVT_BP_ACCURATESLEEPING 0
#define DBVT_BP_ENABLE_BENCHMARK 0
//#define DBVT_BP_MARGIN (btScalar)0.05
extern btScalar gDbvtMargin;
#if DBVT_BP_PROFILE
#define DBVT_BP_PROFILING_RATE 256
#include "LinearMath/btQuickprof.h"
#endif
//
// btDbvtProxy
//
struct btDbvtProxy : btBroadphaseProxy
{
/* Fields */
//btDbvtAabbMm aabb;
btDbvtNode* leaf;
btDbvtProxy* links[2];
int stage;
/* ctor */
btDbvtProxy(const btVector3& aabbMin, const btVector3& aabbMax, void* userPtr, int collisionFilterGroup, int collisionFilterMask) : btBroadphaseProxy(aabbMin, aabbMax, userPtr, collisionFilterGroup, collisionFilterMask)
{
links[0] = links[1] = 0;
}
};
typedef btAlignedObjectArray<btDbvtProxy*> btDbvtProxyArray;
///The btDbvtBroadphase implements a broadphase using two dynamic AABB bounding volume hierarchies/trees (see btDbvt).
///One tree is used for static/non-moving objects, and another tree is used for dynamic objects. Objects can move from one tree to the other.
///This is a very fast broadphase, especially for very dynamic worlds where many objects are moving. Its insert/add and remove of objects is generally faster than the sweep and prune broadphases btAxisSweep3 and bt32BitAxisSweep3.
struct btDbvtBroadphase : btBroadphaseInterface
{
/* Config */
enum
{
DYNAMIC_SET = 0, /* Dynamic set index */
FIXED_SET = 1, /* Fixed set index */
STAGECOUNT = 2 /* Number of stages */
};
/* Fields */
btDbvt m_sets[2]; // Dbvt sets
btDbvtProxy* m_stageRoots[STAGECOUNT + 1]; // Stages list
btOverlappingPairCache* m_paircache; // Pair cache
btScalar m_prediction; // Velocity prediction
int m_stageCurrent; // Current stage
int m_fupdates; // % of fixed updates per frame
int m_dupdates; // % of dynamic updates per frame
int m_cupdates; // % of cleanup updates per frame
int m_newpairs; // Number of pairs created
int m_fixedleft; // Fixed optimization left
unsigned m_updates_call; // Number of updates call
unsigned m_updates_done; // Number of updates done
btScalar m_updates_ratio; // m_updates_done/m_updates_call
int m_pid; // Parse id
int m_cid; // Cleanup index
int m_gid; // Gen id
bool m_releasepaircache; // Release pair cache on delete
bool m_deferedcollide; // Defere dynamic/static collision to collide call
bool m_needcleanup; // Need to run cleanup?
btAlignedObjectArray<btAlignedObjectArray<const btDbvtNode*> > m_rayTestStacks;
#if DBVT_BP_PROFILE
btClock m_clock;
struct
{
unsigned long m_total;
unsigned long m_ddcollide;
unsigned long m_fdcollide;
unsigned long m_cleanup;
unsigned long m_jobcount;
} m_profiling;
#endif
/* Methods */
btDbvtBroadphase(btOverlappingPairCache* paircache = 0);
~btDbvtBroadphase();
void collide(btDispatcher* dispatcher);
void optimize();
/* btBroadphaseInterface Implementation */
btBroadphaseProxy* createProxy(const btVector3& aabbMin, const btVector3& aabbMax, int shapeType, void* userPtr, int collisionFilterGroup, int collisionFilterMask, btDispatcher* dispatcher);
virtual void destroyProxy(btBroadphaseProxy* proxy, btDispatcher* dispatcher);
virtual void setAabb(btBroadphaseProxy* proxy, const btVector3& aabbMin, const btVector3& aabbMax, btDispatcher* dispatcher);
virtual void rayTest(const btVector3& rayFrom, const btVector3& rayTo, btBroadphaseRayCallback& rayCallback, const btVector3& aabbMin = btVector3(0, 0, 0), const btVector3& aabbMax = btVector3(0, 0, 0));
virtual void aabbTest(const btVector3& aabbMin, const btVector3& aabbMax, btBroadphaseAabbCallback& callback);
virtual void getAabb(btBroadphaseProxy* proxy, btVector3& aabbMin, btVector3& aabbMax) const;
virtual void calculateOverlappingPairs(btDispatcher* dispatcher);
virtual btOverlappingPairCache* getOverlappingPairCache();
virtual const btOverlappingPairCache* getOverlappingPairCache() const;
virtual void getBroadphaseAabb(btVector3& aabbMin, btVector3& aabbMax) const;
virtual void printStats();
///reset broadphase internal structures, to ensure determinism/reproducability
virtual void resetPool(btDispatcher* dispatcher);
void performDeferredRemoval(btDispatcher* dispatcher);
void setVelocityPrediction(btScalar prediction)
{
m_prediction = prediction;
}
btScalar getVelocityPrediction() const
{
return m_prediction;
}
///this setAabbForceUpdate is similar to setAabb but always forces the aabb update.
///it is not part of the btBroadphaseInterface but specific to btDbvtBroadphase.
///it bypasses certain optimizations that prevent aabb updates (when the aabb shrinks), see
///http://code.google.com/p/bullet/issues/detail?id=223
void setAabbForceUpdate(btBroadphaseProxy* absproxy, const btVector3& aabbMin, const btVector3& aabbMax, btDispatcher* /*dispatcher*/);
static void benchmark(btBroadphaseInterface*);
};
#endif
| 412 | 0.970336 | 1 | 0.970336 | game-dev | MEDIA | 0.975586 | game-dev | 0.991274 | 1 | 0.991274 |
jdaster64/ttyd-tot | 105,847 | ttyd-tools/rel/source/tot_party_mowz.cpp | #include "tot_party_mowz.h"
#include "evt_cmd.h"
#include "mod.h"
#include "patches_battle.h"
#include "patches_battle_seq.h"
#include "tot_generate_item.h"
#include "tot_gsw.h"
#include "tot_manager_move.h"
#include "tot_manager_reward.h"
#include "tot_state.h"
#include <ttyd/battle.h>
#include <ttyd/battle_camera.h>
#include <ttyd/battle_database_common.h>
#include <ttyd/battle_event_cmd.h>
#include <ttyd/battle_event_default.h>
#include <ttyd/battle_event_subset.h>
#include <ttyd/battle_weapon_power.h>
#include <ttyd/battle_icon.h>
#include <ttyd/battle_message.h>
#include <ttyd/battle_sub.h>
#include <ttyd/battle_unit.h>
#include <ttyd/evt_audience.h>
#include <ttyd/evt_eff.h>
#include <ttyd/evt_snd.h>
#include <ttyd/evt_sub.h>
#include <ttyd/evtmgr_cmd.h>
#include <ttyd/icondrv.h>
#include <ttyd/item_data.h>
#include <ttyd/mario_pouch.h>
#include <ttyd/msgdrv.h>
#include <ttyd/npcdrv.h>
#include <ttyd/unit_party_chuchurina.h>
namespace mod::tot::party_mowz {
namespace {
// Including entire namespaces for convenience.
using namespace ::ttyd::battle_camera;
using namespace ::ttyd::battle_database_common;
using namespace ::ttyd::battle_event_cmd;
using namespace ::ttyd::battle_event_default;
using namespace ::ttyd::battle_event_subset;
using namespace ::ttyd::battle_icon;
using namespace ::ttyd::battle_message;
using namespace ::ttyd::battle_weapon_power;
using namespace ::ttyd::evt_audience;
using namespace ::ttyd::evt_eff;
using namespace ::ttyd::evt_snd;
using namespace ::ttyd::evt_sub;
using namespace ::ttyd::unit_party_chuchurina;
using ::ttyd::evtmgr_cmd::evtGetValue;
using ::ttyd::evtmgr_cmd::evtSetValue;
using ::ttyd::evtmgr_cmd::evtSetValue;
namespace IconType = ::ttyd::icondrv::IconType;
namespace ItemType = ::ttyd::item_data::ItemType;
} // namespace
// Declaration of weapon structs.
extern BattleWeapon customWeapon_MowzLoveSlapL;
extern BattleWeapon customWeapon_MowzLoveSlapR;
extern BattleWeapon customWeapon_MowzLoveSlapLFinal;
extern BattleWeapon customWeapon_MowzLoveSlapRFinal;
extern BattleWeapon customWeapon_MowzKissThief;
extern BattleWeapon customWeapon_MowzTease;
extern BattleWeapon customWeapon_MowzSmooch;
extern BattleWeapon customWeapon_MowzEmbargo;
extern BattleWeapon customWeapon_MowzSmokeBomb;
BattleWeapon* g_WeaponTable[] = {
&customWeapon_MowzLoveSlapLFinal, &customWeapon_MowzKissThief,
&customWeapon_MowzTease, &customWeapon_MowzEmbargo,
&customWeapon_MowzSmokeBomb, &customWeapon_MowzSmooch
};
void MakeSelectWeaponTable(
ttyd::battle::BattleWorkCommand* command_work, int32_t* num_options) {
for (int32_t i = 0; i < 6; ++i) {
auto& weapon_entry = command_work->weapon_table[*num_options];
BattleWeapon* weapon = g_WeaponTable[i];
if (MoveManager::GetUnlockedLevel(MoveType::MOWZ_BASE + i)) {
weapon_entry.index = MoveType::MOWZ_BASE + i;
weapon_entry.item_id = 0;
weapon_entry.weapon = weapon;
weapon_entry.icon = weapon->icon;
weapon_entry.unk_04 = 0;
weapon_entry.unk_18 = 0;
weapon_entry.name = ttyd::msgdrv::msgSearch(weapon->name);
++*num_options;
}
}
}
// Gets an enemy's item held position.
EVT_DECLARE_USER_FUNC(evtTot_GetHeldItemPosition, 4)
EVT_DEFINE_USER_FUNC(evtTot_GetHeldItemPosition) {
auto* battleWork = ttyd::battle::g_BattleWork;
int32_t id = evtGetValue(evt, evt->evtArguments[0]);
id = ttyd::battle_sub::BattleTransID(evt, id);
auto* unit = ttyd::battle::BattleGetUnitPtr(battleWork, id);
evtSetValue(evt, evt->evtArguments[1],
unit->position.x + unit->held_item_base_offset.x);
evtSetValue(evt, evt->evtArguments[2],
unit->position.y + unit->held_item_base_offset.y);
evtSetValue(evt, evt->evtArguments[3],
unit->position.z + unit->held_item_base_offset.z);
return 2;
}
// Removes item from enemy and gets item id.
EVT_DECLARE_USER_FUNC(evtTot_ConfiscateItem, 2)
EVT_DEFINE_USER_FUNC(evtTot_ConfiscateItem) {
auto* battleWork = ttyd::battle::g_BattleWork;
int32_t id = evtGetValue(evt, evt->evtArguments[0]);
id = ttyd::battle_sub::BattleTransID(evt, id);
auto* unit = ttyd::battle::BattleGetUnitPtr(battleWork, id);
int32_t item = unit->held_item;
unit->held_item = 0;
evtSetValue(evt, evt->evtArguments[1], item);
// Reset badge effects.
if (item >= ItemType::POWER_JUMP && item < ItemType::MAX_ITEM_TYPE &&
unit->current_kind < BattleUnitType::BONETAIL) {
ttyd::battle::BtlUnit_EquipItem(unit, 1, 0);
}
return 2;
}
// Dynamically sets the damage and status chance parameters based on AC success.
EVT_DECLARE_USER_FUNC(evtTot_MakeTeaseWeapon, 3)
EVT_DEFINE_USER_FUNC(evtTot_MakeTeaseWeapon) {
auto* weapon = (BattleWeapon*)evtGetValue(evt, evt->evtArguments[0]);
int32_t ac_result = evtGetValue(evt, evt->evtArguments[1]);
int32_t move_type = evtGetValue(evt, evt->evtArguments[2]);
int32_t move_level = MoveManager::GetSelectedLevel(move_type);
int32_t turn_count = GetSWByte(GSW_Battle_DooplissMove) ? 2 : 1;
// Make changes in place, since the parameters are unchanged between uses.
if (move_type == MoveType::MOWZ_TEASE) {
weapon->confuse_chance = ac_result * 1.27;
weapon->confuse_time = turn_count;
} else { // Smoke Bomb
int32_t success_level = 1 + (move_level + 2) * ac_result / 100;
weapon->damage_function_params[0] = success_level;
weapon->dizzy_time = turn_count;
// 33%, 66%, 100% base rate max at level 1, 2, 3.
weapon->dizzy_chance =
100 * (success_level > 2 ? success_level - 2 : 0) / 3;
}
return 2;
}
// Dynamically sets the status parameters for Smooch based on level / AC result.
EVT_DECLARE_USER_FUNC(evtTot_MakeSmoochWeapon, 3)
EVT_DEFINE_USER_FUNC(evtTot_MakeSmoochWeapon) {
auto* weapon = (BattleWeapon*)evtGetValue(evt, evt->evtArguments[0]);
int32_t move_level = evtGetValue(evt, evt->evtArguments[1]);
int32_t turn_count = evtGetValue(evt, evt->evtArguments[2]);
weapon->hp_regen_strength = 0;
weapon->hp_regen_time = 0;
weapon->fp_regen_strength = 0;
weapon->fp_regen_time = 0;
if (move_level >= 1) {
weapon->hp_regen_strength = 5;
weapon->hp_regen_time = turn_count;
}
if (move_level >= 2) {
weapon->fp_regen_strength = 5;
weapon->fp_regen_time = turn_count;
}
if (move_level >= 3) {
patch::battle_seq::StoreGradualSpRegenEffect(turn_count);
}
return 2;
}
// Replaces vanilla logic for choosing items to steal.
EVT_DECLARE_USER_FUNC(evtTot_GetKissThiefResult, 3)
EVT_DEFINE_USER_FUNC(evtTot_GetKissThiefResult) {
auto* battleWork = ttyd::battle::g_BattleWork;
int32_t id = evtGetValue(evt, evt->evtArguments[0]);
id = ttyd::battle_sub::BattleTransID(evt, id);
auto* unit = ttyd::battle::BattleGetUnitPtr(battleWork, id);
uint32_t ac_result = evtGetValue(evt, evt->evtArguments[2]);
int32_t item = unit->held_item;
// No held item; pick a random item to steal;
// 30% chance of item (20% common, 10% rare), 10% badge, 60% coin.
if (!item) {
item = PickRandomItem(RNG_STOLEN_ITEM, 25, 5, 10, 60);
if (!item) item = ItemType::COIN;
}
if ((ac_result & 2) == 0 || !ttyd::mario_pouch::pouchGetItem(item)) {
// Action command unsuccessful, or out of inventory space for the item.
evtSetValue(evt, evt->evtArguments[1], 0);
} else {
// Remove the unit's held item.
unit->held_item = 0;
// Remove the corresponding held/stolen item from the NPC setup,
// if this was one of the initial enemies in the loadout.
if (!ttyd::battle_unit::BtlUnit_CheckUnitFlag(unit, 0x40000000)) {
if (unit->group_index >= 0) {
battleWork->fbat_info->wBattleInfo->wHeldItems
[unit->group_index] = 0;
}
} else {
ttyd::battle_unit::BtlUnit_OffUnitFlag(unit, 0x40000000);
if (unit->group_index >= 0) {
auto* npc_battle_info = battleWork->fbat_info->wBattleInfo;
npc_battle_info->wHeldItems[unit->group_index] = 0;
npc_battle_info->wStolenItems[unit->group_index] = 0;
}
}
// If a badge was stolen, re-equip the target unit's remaining badges.
if (item >= ItemType::POWER_JUMP && item < ItemType::MAX_ITEM_TYPE) {
int32_t kind = unit->current_kind;
if (kind == BattleUnitType::MARIO) {
ttyd::battle::BtlUnit_EquipItem(unit, 3, 0);
} else if (kind >= BattleUnitType::GOOMBELLA) {
ttyd::battle::BtlUnit_EquipItem(unit, 5, 0);
} else {
ttyd::battle::BtlUnit_EquipItem(unit, 1, 0);
}
}
evtSetValue(evt, evt->evtArguments[1], item);
}
return 2;
}
EVT_BEGIN(partyChuchurinaAttack_NormalAttack)
USER_FUNC(btlevtcmd_JumpSetting, -2, 20, FLOAT(0.0), FLOAT(0.70))
USER_FUNC(btlevtcmd_CommandGetWeaponAddress, -2, LW(12))
IF_EQUAL((int32_t)GSW_Battle_DooplissMove, 0)
USER_FUNC(btlevtcmd_GetSelectEnemy, LW(3), LW(4))
ELSE()
USER_FUNC(btlevtcmd_GetEnemyBelong, -2, LW(0))
USER_FUNC(btlevtcmd_SamplingEnemy, -2, LW(0), LW(12))
USER_FUNC(btlevtcmd_ChoiceSamplingEnemy, LW(12), LW(3), LW(4))
END_IF()
IF_EQUAL(LW(3), -1)
GOTO(99)
END_IF()
USER_FUNC(btlevtcmd_WeaponAftereffect, LW(12))
USER_FUNC(btlevtcmd_AttackDeclare, -2, LW(3), LW(4))
USER_FUNC(btlevtcmd_WaitGuardMove)
USER_FUNC(btlevtcmd_CommandPayWeaponCost, -2)
USER_FUNC(btlevtcmd_RunDataEventChild, -2, 7)
USER_FUNC(evt_btl_camera_set_mode, 0, 11)
USER_FUNC(evt_btl_camera_set_homing_unitparts, 0, -2, 1, LW(3), LW(4))
USER_FUNC(evt_btl_camera_set_moveSpeedLv, 0, 2)
USER_FUNC(evt_btl_camera_set_zoom, 0, 200)
USER_FUNC(btlevtcmd_CommandPreCheckDamage, -2, LW(3), LW(4), 256, LW(5))
IF_EQUAL(LW(5), 5)
USER_FUNC(btlevtcmd_GetStatusMg, LW(3), LW(6))
MULF(LW(6), 40)
USER_FUNC(btlevtcmd_GetPos, LW(3), LW(0), LW(1), LW(2))
USER_FUNC(btlevtcmd_TransStageFloorPosition, LW(0), LW(1), LW(2))
USER_FUNC(btlevtcmd_FaceDirectionAdd, LW(3), LW(0), LW(6))
USER_FUNC(btlevtcmd_CalculateFaceDirection, -2, -1, LW(0), LW(2), 1, LW(15))
USER_FUNC(btlevtcmd_ChangeFaceDirection, -2, LW(15))
USER_FUNC(btlevtcmd_AnimeChangePoseType, -2, 1, 40)
USER_FUNC(btlevtcmd_SetMoveSpeed, -2, FLOAT(3.0))
USER_FUNC(btlevtcmd_MovePosition, -2, LW(0), LW(1), LW(2), 0, -1, 0)
USER_FUNC(btlevtcmd_CommandCheckDamage, -2, LW(3), LW(4), 256, LW(5))
END_IF()
USER_FUNC(btlevtcmd_GetStatusMg, -2, LW(5))
MULF(LW(5), 12)
USER_FUNC(_get_binta_hit_position, -2, LW(3), LW(4), LW(0), LW(1), LW(2))
USER_FUNC(btlevtcmd_FaceDirectionAdd, LW(3), LW(0), LW(5))
USER_FUNC(btlevtcmd_TransStageFloorPosition, LW(0), LW(1), LW(2))
USER_FUNC(btlevtcmd_CalculateFaceDirection, -2, -1, LW(0), LW(2), 1, LW(15))
USER_FUNC(btlevtcmd_ChangeFaceDirection, -2, LW(15))
USER_FUNC(btlevtcmd_AnimeChangePoseType, -2, 1, 40)
USER_FUNC(btlevtcmd_SetMoveSpeed, -2, FLOAT(3.0))
ADD(LW(2), 5)
USER_FUNC(btlevtcmd_MovePosition, -2, LW(0), LW(1), LW(2), 0, -1, 0)
USER_FUNC(btlevtcmd_CalculateFaceDirection, -2, -1, LW(3), LW(4), 16, LW(15))
USER_FUNC(btlevtcmd_ChangeFaceDirection, -2, LW(15))
USER_FUNC(evt_btl_camera_set_moveSpeedLv, 0, 2)
USER_FUNC(evt_btl_camera_set_zoom, 0, 350)
USER_FUNC(btlevtcmd_AnimeChangePose, -2, 1, PTR("PCH_A1_1"))
BROTHER_EVT_ID(LW(0))
IF_EQUAL((int32_t)GSW_Battle_DooplissMove, 0)
USER_FUNC(btlevtcmd_CommandGetWeaponActionLv, LW(0))
USER_FUNC(btlevtcmd_AcSetDifficulty, -2, LW(0))
USER_FUNC(btlevtcmd_AcGetDifficulty, LW(0))
SUB(LW(0), 3)
SWITCH(LW(0))
CASE_SMALL_EQUAL(-3)
SET(LW(1), 25)
SET(LW(2), 30)
CASE_EQUAL(-2)
SET(LW(1), 20)
SET(LW(2), 30)
CASE_EQUAL(-1)
SET(LW(1), 17)
SET(LW(2), 30)
CASE_EQUAL(0)
SET(LW(1), 15)
SET(LW(2), 30)
CASE_EQUAL(1)
SET(LW(1), 14)
SET(LW(2), 30)
CASE_EQUAL(2)
SET(LW(1), 13)
SET(LW(2), 30)
CASE_ETC()
SET(LW(1), 12)
SET(LW(2), 30)
END_SWITCH()
// Change gauge parameters based on move level (up to 2-4 extra hits).
USER_FUNC(evtTot_GetMoveSelectedLevel, MoveType::MOWZ_BASE, LW(0))
SWITCH(LW(0))
CASE_EQUAL(1)
USER_FUNC(btlevtcmd_AcSetParamAll, 14, 210, 178, LW(1), LW(2), 50, 51, EVT_NULLPTR)
USER_FUNC(btlevtcmd_AcSetGaugeParam, 50, 100, 100, 100)
CASE_EQUAL(2)
USER_FUNC(btlevtcmd_AcSetParamAll, 14, 210, 178, LW(1), LW(2), 34, 35, EVT_NULLPTR)
USER_FUNC(btlevtcmd_AcSetGaugeParam, 34, 67, 100, 100)
CASE_ETC()
USER_FUNC(btlevtcmd_AcSetParamAll, 14, 210, 178, LW(1), LW(2), 25, 26, EVT_NULLPTR)
USER_FUNC(btlevtcmd_AcSetGaugeParam, 25, 50, 75, 100)
END_SWITCH()
// Start with 1 base hit.
USER_FUNC(btlevtcmd_AcSetFlag, 64)
USER_FUNC(btlevtcmd_SetupAC, -2, 6, 1, 0)
WAIT_FRM(1)
USER_FUNC(btlevtcmd_StartAC, 1)
END_IF()
END_BROTHER()
USER_FUNC(btlevtcmd_WaitEventEnd, LW(0))
BROTHER_EVT_ID(LW(14))
SET(LW(6), 0)
SET(LW(5), 5)
DO(LW(5))
ADD(LW(6), 1)
SET(LW(0), LW(6))
DIV(LW(0), 2)
MOD(LW(0), 2)
IF_EQUAL(LW(0), 0)
USER_FUNC(btlevtcmd_SetScale, -2, FLOAT(1.05), FLOAT(1.05), FLOAT(1.0))
ELSE()
USER_FUNC(btlevtcmd_SetScale, -2, FLOAT(1.0), FLOAT(1.0), FLOAT(1.0))
END_IF()
WAIT_FRM(1)
SET(LW(5), 5)
WHILE()
END_BROTHER()
BROTHER_EVT_ID(LW(15))
SET(LW(5), 5)
SET(LW(6), 0)
DO(LW(5))
IF_EQUAL((int32_t)GSW_Battle_DooplissMove, 0)
USER_FUNC(btlevtcmd_AcGetOutputParam, 1, LW(0))
ELSE()
IF_SMALL(LW(6), 100)
ADD(LW(6), 2)
END_IF()
SET(LW(0), LW(6))
END_IF()
SET(LW(1), 255)
SET(LW(2), 190)
MUL(LW(2), LW(0))
DIV(LW(2), 100)
SUB(LW(1), LW(2))
USER_FUNC(btlevtcmd_SetRGB, -2, 1, 255, LW(1), LW(1))
WAIT_FRM(1)
SET(LW(5), 5)
WHILE()
END_BROTHER()
IF_EQUAL((int32_t)GSW_Battle_DooplissMove, 0)
USER_FUNC(btlevtcmd_ResultAC)
ELSE()
WAIT_FRM(90)
USER_FUNC(evtTot_GetMoveSelectedLevel, MoveType::MOWZ_BASE, LW(0))
ADD(LW(0), 2)
USER_FUNC(btlevtcmd_AcSetOutputParam, 2, LW(0))
END_IF()
DELETE_EVT(LW(14))
DELETE_EVT(LW(15))
// Number of hits based on AC output param 2, rather than move level.
USER_FUNC(btlevtcmd_AcGetOutputParam, 2, LW(0))
USER_FUNC(btlevtcmd_SetUnitWork, -2, 5, LW(0))
USER_FUNC(evt_btl_camera_set_moveSpeedLv, 0, 2)
USER_FUNC(evt_btl_camera_set_zoom, 0, 300)
USER_FUNC(btlevtcmd_SetRGB, -2, 1, 255, 255, 255)
BROTHER_EVT_ID(LW(14))
SET(LW(8), -75)
USER_FUNC(btlevtcmd_GetRotate, -2, EVT_NULLPTR, LW(0), EVT_NULLPTR)
IF_LARGE_EQUAL(LW(0), 180)
SUB(LW(0), 360)
END_IF()
USER_FUNC(evt_sub_intpl_init, 5, LW(0), LW(8), 8)
DO(8)
USER_FUNC(evt_sub_intpl_get_value)
USER_FUNC(btlevtcmd_SetRotate, -2, 0, LW(0), 0)
WAIT_FRM(1)
WHILE()
SET(LW(8), -60)
SET(LW(9), -75)
USER_FUNC(evt_sub_intpl_init, 11, LW(9), LW(8), 4)
DO(4)
USER_FUNC(evt_sub_intpl_get_value)
USER_FUNC(btlevtcmd_SetRotate, -2, 0, LW(0), 0)
WAIT_FRM(1)
WHILE()
END_BROTHER()
USER_FUNC(btlevtcmd_WaitEventEnd, LW(14))
SET(LW(13), 18)
SET(LW(10), 0)
USER_FUNC(btlevtcmd_SetUnitWork, -2, 4, 0)
LBL(10)
ADD(LW(10), 1)
USER_FUNC(btlevtcmd_AnimeChangePose, -2, 1, PTR("PCH_A1_2"))
IF_LARGE_EQUAL(LW(10), 2)
USER_FUNC(btlevtcmd_CommandPreCheckDamage, -2, LW(3), LW(4), 1048832, LW(5))
ELSE()
USER_FUNC(btlevtcmd_CommandPreCheckDamage, -2, LW(3), LW(4), 256, LW(5))
END_IF()
SWITCH(LW(5))
CASE_OR(2)
CASE_OR(3)
CASE_OR(6)
CASE_OR(4)
CASE_END()
CASE_EQUAL(1)
CASE_ETC()
WAIT_MSEC(1000)
END_SWITCH()
IF_NOT_EQUAL(LW(5), 1)
DELETE_EVT(LW(14))
SET(LW(14), 0)
IF_EQUAL((int32_t)GSW_Battle_DooplissMove, 0)
USER_FUNC(btlevtcmd_StopAC)
END_IF()
IF_EQUAL(LW(5), 3)
USER_FUNC(btlevtcmd_StartAvoid, LW(3), 38)
END_IF()
IF_EQUAL(LW(5), 6)
USER_FUNC(btlevtcmd_StartAvoid, LW(3), 39)
END_IF()
IF_EQUAL(LW(5), 2)
USER_FUNC(btlevtcmd_StartAvoid, LW(3), 40)
END_IF()
DO(20)
USER_FUNC(btlevtcmd_AddRotate, -2, 0, 18, 0)
WAIT_FRM(1)
WHILE()
DO(36)
USER_FUNC(btlevtcmd_AddRotate, -2, 0, 10, 0)
WAIT_FRM(1)
WHILE()
USER_FUNC(btlevtcmd_SetRotate, -2, 0, 0, 0)
USER_FUNC(btlevtcmd_AnimeChangePose, -2, 1, PTR("PCH_A2_4"))
WAIT_FRM(52)
// USER_FUNC(btlevtcmd_InviteApInfoReport)
GOTO(95)
END_IF()
SET(LW(0), LW(10))
MOD(LW(0), 2)
IF_NOT_EQUAL(LW(0), 0)
SET(LW(12), PTR(&customWeapon_MowzLoveSlapR))
ELSE()
SET(LW(12), PTR(&customWeapon_MowzLoveSlapL))
END_IF()
USER_FUNC(btlevtcmd_GetUnitWork, -2, 4, LW(15))
IF_NOT_EQUAL(LW(15), 0)
DELETE_EVT(LW(15))
USER_FUNC(btlevtcmd_SetUnitWork, -2, 4, 0)
END_IF()
IF_NOT_EQUAL(LW(14), 0)
DELETE_EVT(LW(14))
SET(LW(14), 0)
END_IF()
USER_FUNC(btlevtcmd_GetUnitWork, -2, 5, LW(0))
IF_LARGE_EQUAL(LW(10), LW(0))
GOTO(20)
ELSE()
IF_EQUAL((int32_t)GSW_Battle_DooplissMove, 0)
USER_FUNC(btlevtcmd_GetResultAC, LW(6))
ELSE()
SET(LW(6), 0x2)
END_IF()
IF_NOT_FLAG(LW(6), 0x2)
GOTO(20)
END_IF()
END_IF()
GOTO(21)
LBL(20)
IF_EQUAL(LW(12), PTR(&customWeapon_MowzLoveSlapL))
SET(LW(12), PTR(&customWeapon_MowzLoveSlapLFinal))
ELSE()
SET(LW(12), PTR(&customWeapon_MowzLoveSlapRFinal))
END_IF()
LBL(21)
USER_FUNC(btlevtcmd_PreCheckCounter, -2, LW(3), LW(4), LW(12), 256, LW(0))
SWITCH(LW(0))
CASE_OR(7)
CASE_OR(8)
CASE_OR(9)
CASE_OR(10)
CASE_OR(11)
CASE_OR(12)
CASE_OR(13)
CASE_OR(14)
CASE_OR(15)
CASE_OR(16)
CASE_OR(17)
IF_EQUAL(LW(12), PTR(&customWeapon_MowzLoveSlapL))
SET(LW(12), PTR(&customWeapon_MowzLoveSlapLFinal))
ELSE()
SET(LW(12), PTR(&customWeapon_MowzLoveSlapRFinal))
END_IF()
BROTHER_EVT_ID(LW(15))
SET(LW(7), LW(13))
USER_FUNC(btlevtcmd_GetRotate, -2, EVT_NULLPTR, LW(0), EVT_NULLPTR)
IF_LARGE_EQUAL(LW(0), 180)
SUB(LW(0), 360)
END_IF()
USER_FUNC(evt_sub_intpl_init, 11, LW(0), 0, 4)
DO(4)
USER_FUNC(evt_sub_intpl_get_value)
USER_FUNC(btlevtcmd_SetRotate, -2, 0, 0, LW(0))
WAIT_FRM(1)
IF_EQUAL(LW(1), 1)
DO_BREAK()
END_IF()
WHILE()
USER_FUNC(btlevtcmd_SetRotate, -2, 0, 0, 0)
END_BROTHER()
USER_FUNC(btlevtcmd_WaitEventEnd, LW(15))
IF_EQUAL((int32_t)GSW_Battle_DooplissMove, 0)
USER_FUNC(btlevtcmd_GetResultAC, LW(6))
ELSE()
SET(LW(6), 0x2)
END_IF()
USER_FUNC(btlevtcmd_ResultACDefence, LW(3), LW(12))
IF_FLAG(LW(6), 0x2)
USER_FUNC(btlevtcmd_CheckDamage, -2, LW(3), LW(4), LW(12), 131328, LW(5))
ELSE()
USER_FUNC(btlevtcmd_CheckDamage, -2, LW(3), LW(4), LW(12), 256, LW(5))
END_IF()
RETURN()
CASE_END()
END_SWITCH()
USER_FUNC(evt_btl_camera_shake_h, 0, 2, 0, 12, 13)
USER_FUNC(btlevtcmd_ResultACDefence, LW(3), LW(12))
USER_FUNC(btlevtcmd_GetUnitWork, -2, 5, LW(0))
IF_LARGE_EQUAL(LW(10), LW(0))
USER_FUNC(evt_snd_sfxon, PTR("SFX_BTL_CHUCHURINA_ATTACK3"), 0)
IF_FLAG(LW(6), 0x2)
USER_FUNC(btlevtcmd_CheckDamage, -2, LW(3), LW(4), LW(12), 131328, LW(5))
ELSE()
USER_FUNC(btlevtcmd_CheckDamage, -2, LW(3), LW(4), LW(12), 256, LW(5))
END_IF()
ELSE()
SET(LW(0), LW(10))
AND(LW(0), 1)
IF_EQUAL(LW(0), 0)
USER_FUNC(evt_snd_sfxon, PTR("SFX_BTL_CHUCHURINA_ATTACK2"), 0)
ELSE()
USER_FUNC(evt_snd_sfxon, PTR("SFX_BTL_CHUCHURINA_ATTACK1"), 0)
END_IF()
IF_FLAG(LW(6), 0x2)
USER_FUNC(btlevtcmd_CheckDamage, -2, LW(3), LW(4), LW(12), 131072, LW(5))
ELSE()
USER_FUNC(btlevtcmd_CheckDamage, -2, LW(3), LW(4), LW(12), 256, LW(5))
END_IF()
END_IF()
IF_EQUAL((int32_t)GSW_Battle_DooplissMove, 0)
USER_FUNC(btlevtcmd_GetResultAC, LW(6))
IF_FLAG(LW(6), 0x2)
USER_FUNC(btlevtcmd_AcGetOutputParam, 2, LW(0))
// Changed Nice / Good / Great thresholds to 2, 4, 5 hits.
IF_EQUAL(LW(0), 2)
ADD(LW(0), 1)
END_IF()
SUB(LW(0), 3)
IF_LARGE_EQUAL(LW(0), 0)
USER_FUNC(btlevtcmd_GetResultPrizeLv, LW(3), LW(0), LW(11))
USER_FUNC(btlevtcmd_GetHitPos, LW(3), LW(4), LW(0), LW(1), LW(2))
USER_FUNC(btlevtcmd_ACSuccessEffect, LW(11), LW(0), LW(1), LW(2))
USER_FUNC(btlevtcmd_AudienceDeclareACResult, LW(12), LW(11))
ELSE()
USER_FUNC(btlevtcmd_AudienceDeclareACResult, LW(12), -1)
END_IF()
ELSE()
USER_FUNC(btlevtcmd_AudienceDeclareACResult, LW(12), -1)
END_IF()
END_IF()
IF_FLAG(LW(6), 0x2)
SWITCH(LW(10))
CASE_SMALL_EQUAL(2)
BROTHER_EVT_ID(LW(15))
SET(LW(7), LW(13))
IF_LARGE_EQUAL(LW(7), 0)
SET(LW(8), 75)
ELSE()
SET(LW(8), -75)
END_IF()
USER_FUNC(btlevtcmd_GetRotate, -2, EVT_NULLPTR, LW(0), EVT_NULLPTR)
IF_LARGE_EQUAL(LW(0), 180)
SUB(LW(0), 360)
END_IF()
USER_FUNC(evt_sub_intpl_init, 5, LW(0), LW(8), 14)
DO(14)
USER_FUNC(evt_sub_intpl_get_value)
USER_FUNC(btlevtcmd_SetRotate, -2, 0, LW(0), 0)
WAIT_FRM(1)
WHILE()
USER_FUNC(btlevtcmd_GetUnitWork, -2, 5, LW(0))
IF_SMALL(LW(10), LW(0))
SET(LW(7), LW(13))
IF_LARGE_EQUAL(LW(7), 0)
SET(LW(8), 75)
SET(LW(9), 75)
ELSE()
SET(LW(8), -75)
SET(LW(9), -75)
END_IF()
USER_FUNC(evt_sub_intpl_init, 11, LW(9), LW(8), 6)
DO(6)
USER_FUNC(evt_sub_intpl_get_value)
USER_FUNC(btlevtcmd_SetRotate, -2, 0, LW(0), 0)
WAIT_FRM(1)
WHILE()
ELSE()
SET(LW(7), LW(13))
IF_LARGE_EQUAL(LW(7), 0)
SET(LW(8), 0)
SET(LW(9), 75)
ELSE()
SET(LW(8), 0)
SET(LW(9), -75)
END_IF()
USER_FUNC(evt_sub_intpl_init, 11, LW(9), LW(8), 12)
DO(12)
USER_FUNC(evt_sub_intpl_get_value)
USER_FUNC(btlevtcmd_SetRotate, -2, 0, LW(0), 0)
WAIT_FRM(1)
WHILE()
END_IF()
END_BROTHER()
USER_FUNC(btlevtcmd_WaitEventEnd, LW(15))
CASE_ETC()
BROTHER_EVT_ID(LW(15))
USER_FUNC(btlevtcmd_GetRotate, -2, EVT_NULLPTR, LW(8), EVT_NULLPTR)
SET(LW(7), 360)
USER_FUNC(btlevtcmd_GetUnitWork, -2, 5, LW(0))
IF_LARGE_EQUAL(LW(10), LW(0))
SET(LW(0), LW(8))
IF_LARGE_EQUAL(LW(8), 180)
SUB(LW(0), 360)
END_IF()
IF_LARGE_EQUAL(LW(13), 0)
SUB(LW(7), LW(0))
ELSE()
ADD(LW(7), LW(0))
END_IF()
ELSE()
ADD(LW(7), 60)
SET(LW(0), LW(8))
IF_LARGE_EQUAL(LW(8), 180)
SUB(LW(0), 360)
END_IF()
IF_LARGE_EQUAL(LW(13), 0)
SUB(LW(7), LW(0))
ELSE()
ADD(LW(7), LW(0))
END_IF()
END_IF()
IF_SMALL(LW(13), 0)
MUL(LW(7), -1)
END_IF()
USER_FUNC(evt_sub_intpl_init, 5, 0, LW(7), 20)
DO(20)
USER_FUNC(evt_sub_intpl_get_value)
ADD(LW(0), LW(8))
USER_FUNC(btlevtcmd_SetRotate, -2, 0, LW(0), 0)
WAIT_FRM(1)
WHILE()
END_BROTHER()
USER_FUNC(btlevtcmd_SetUnitWork, -2, 4, LW(15))
WAIT_FRM(10)
END_SWITCH()
ELSE()
BROTHER_EVT_ID(LW(15))
USER_FUNC(btlevtcmd_GetRotate, -2, EVT_NULLPTR, LW(8), EVT_NULLPTR)
SET(LW(7), 720)
IF_LARGE_EQUAL(LW(10), 1)
SET(LW(0), LW(8))
IF_LARGE_EQUAL(LW(8), 180)
SUB(LW(0), 360)
END_IF()
SUB(LW(7), LW(0))
END_IF()
IF_SMALL(LW(13), 0)
MUL(LW(7), -1)
END_IF()
USER_FUNC(evt_sub_intpl_init, 0, 0, LW(7), 60)
DO(60)
USER_FUNC(evt_sub_intpl_get_value)
ADD(LW(0), LW(8))
USER_FUNC(btlevtcmd_SetRotate, -2, 0, LW(0), 0)
WAIT_FRM(1)
WHILE()
END_BROTHER()
USER_FUNC(btlevtcmd_WaitEventEnd, LW(15))
USER_FUNC(btlevtcmd_SetRotate, -2, 0, 0, 0)
USER_FUNC(btlevtcmd_AnimeChangePose, -2, 1, PTR("PCH_X_1"))
WAIT_FRM(60)
IF_EQUAL((int32_t)GSW_Battle_DooplissMove, 0)
USER_FUNC(btlevtcmd_StopAC)
END_IF()
// USER_FUNC(btlevtcmd_InviteApInfoReport)
GOTO(95)
END_IF()
MUL(LW(13), -1)
USER_FUNC(btlevtcmd_GetUnitWork, -2, 5, LW(0))
IF_SMALL(LW(10), LW(0))
GOTO(10)
END_IF()
LBL(90)
IF_EQUAL((int32_t)GSW_Battle_DooplissMove, 0)
USER_FUNC(btlevtcmd_StopAC)
END_IF()
// USER_FUNC(btlevtcmd_InviteApInfoReport)
USER_FUNC(btlevtcmd_AnimeChangePose, -2, 1, PTR("PCH_A1_3"))
WAIT_FRM(40)
LBL(95)
USER_FUNC(evt_btl_camera_set_mode, 0, 0)
USER_FUNC(evt_btl_camera_set_moveSpeedLv, 0, 1)
USER_FUNC(btlevtcmd_GetHomePos, -2, LW(0), LW(1), LW(2))
USER_FUNC(btlevtcmd_CalculateFaceDirection, -2, -1, LW(0), LW(2), 1, LW(15))
USER_FUNC(btlevtcmd_ChangeFaceDirection, -2, LW(15))
USER_FUNC(btlevtcmd_SetMoveSpeed, -2, FLOAT(3.0))
USER_FUNC(btlevtcmd_GetMoveFrame, -2, LW(0), LW(1), LW(2), 0, LW(14))
USER_FUNC(btlevtcmd_AnimeChangePoseType, -2, 1, 42)
USER_FUNC(btlevtcmd_GetHomePos, -2, LW(0), LW(1), LW(2))
BROTHER_EVT_ID(LW(15))
USER_FUNC(btlevtcmd_MovePosition, -2, LW(0), LW(1), LW(2), LW(14), -1, 0)
END_BROTHER()
IF_EQUAL((int32_t)GSW_Battle_DooplissMove, 0)
SET(LW(11), LW(14))
SUB(LW(11), 11)
SUB(LW(14), 1)
IF_LARGE(LW(14), LW(11))
SET(LW(13), LW(14))
SUB(LW(13), 10)
IF_FLAG(LW(6), 0x2)
USER_FUNC(btlevtcmd_ACRStart, -2, 0, LW(13), LW(14), 0)
USER_FUNC(btlevtcmd_ACRGetResult, LW(6), LW(7))
IF_LARGE_EQUAL(LW(6), 2)
DELETE_EVT(LW(15))
USER_FUNC(evtTot_LogActiveMoveStylish, 0)
USER_FUNC(btlevtcmd_GetPos, -2, LW(0), LW(1), LW(2))
USER_FUNC(btlevtcmd_SetFallAccel, -2, FLOAT(0.5))
USER_FUNC(btlevtcmd_FaceDirectionAdd, -2, LW(0), 30)
USER_FUNC(btlevtcmd_AnimeChangePose, -2, 1, PTR("PCH_O_1"))
USER_FUNC(btlevtcmd_AudienceDeclareAcrobatResult, LW(12), 1, 0, 0, 0)
USER_FUNC(btlevtcmd_JumpPosition, -2, LW(0), LW(1), LW(2), 20, -1)
USER_FUNC(btlevtcmd_AnimeChangePoseType, -2, 1, 42)
USER_FUNC(btlevtcmd_GetHomePos, -2, LW(0), LW(1), LW(2))
USER_FUNC(btlevtcmd_SetMoveSpeed, -2, FLOAT(3.0))
USER_FUNC(btlevtcmd_MovePosition, -2, LW(0), LW(1), LW(2), 0, -1, 0)
USER_FUNC(btlevtcmd_SetHomePos, -2, LW(0), LW(1), LW(2))
GOTO(99)
END_IF()
END_IF()
END_IF()
END_IF()
USER_FUNC(btlevtcmd_WaitEventEnd, LW(15))
LBL(99)
IF_EQUAL((int32_t)GSW_Battle_DooplissMove, 0)
// Move Star Power generation to the end so Stylishes affect it.
USER_FUNC(btlevtcmd_InviteApInfoReport)
END_IF()
USER_FUNC(btlevtcmd_ResetFaceDirection, -2)
RUN_CHILD_EVT(PTR(&btldefaultevt_SuitoruBadgeEffect))
USER_FUNC(btlevtcmd_StartWaitEvent, -2)
RETURN()
EVT_END()
EVT_BEGIN(partyChuchurinaAttack_ItemSteal)
USER_FUNC(btlevtcmd_GetSelectEnemy, LW(3), LW(4))
IF_EQUAL(LW(3), -1)
GOTO(99)
END_IF()
USER_FUNC(btlevtcmd_CommandGetWeaponAddress, -2, LW(12))
USER_FUNC(btlevtcmd_WeaponAftereffect, LW(12))
USER_FUNC(btlevtcmd_AttackDeclareAll, -2)
USER_FUNC(btlevtcmd_WaitGuardMove)
USER_FUNC(btlevtcmd_CommandPayWeaponCost, -2)
USER_FUNC(btlevtcmd_RunDataEventChild, -2, 7)
SET(LW(14), 0)
USER_FUNC(btlevtcmd_PreCheckDamage, -2, LW(3), LW(4), PTR(&customWeapon_MowzKissThief), 256, LW(5))
IF_EQUAL(LW(5), 5)
USER_FUNC(btlevtcmd_AnimeChangePoseType, -2, 1, 42)
USER_FUNC(btlevtcmd_SetMoveSpeed, -2, FLOAT(3.0))
USER_FUNC(btlevtcmd_GetWidth, LW(3), LW(15))
DIV(LW(15), 2)
USER_FUNC(btlevtcmd_GetHitPos, LW(3), LW(4), LW(0), LW(1), LW(2))
USER_FUNC(btlevtcmd_FaceDirectionAdd, LW(3), LW(0), LW(15))
USER_FUNC(btlevtcmd_FaceDirectionAdd, LW(3), LW(0), 20)
USER_FUNC(btlevtcmd_TransStageFloorPosition, LW(0), LW(1), LW(2))
USER_FUNC(btlevtcmd_GetMoveFrame, -2, LW(0), LW(1), LW(2), 0, LW(8))
BROTHER_EVT_ID(LW(9))
USER_FUNC(btlevtcmd_MovePosition, -2, LW(0), LW(1), LW(2), LW(8), -1, 0)
END_BROTHER()
IF_LARGE(LW(8), 5)
SUB(LW(8), 2)
SET(LW(15), LW(8))
DIV(LW(15), 3)
SET(LW(8), LW(15))
MUL(LW(8), 2)
USER_FUNC(btlevtcmd_ACRStart, -2, LW(15), LW(8), LW(8), 0)
USER_FUNC(btlevtcmd_ACRGetResult, LW(6), LW(7))
SWITCH(LW(6))
CASE_LARGE_EQUAL(2)
DELETE_EVT(LW(9))
USER_FUNC(evtTot_LogActiveMoveStylish, 0)
USER_FUNC(btlevtcmd_AudienceDeclareAcrobatResult, LW(12), 1, 0, 0, 0)
USER_FUNC(btlevtcmd_AnimeChangePose, -2, 1, PTR("PCH_Y_1"))
USER_FUNC(btlevtcmd_AnimeWaitPlayComplete, -2, 1)
USER_FUNC(btlevtcmd_AnimeChangePoseType, -2, 1, 42)
USER_FUNC(btlevtcmd_MovePosition, -2, LW(0), LW(1), LW(2), 0, -1, 0)
CASE_ETC()
USER_FUNC(evt_audience_acrobat_notry)
END_SWITCH()
ELSE()
USER_FUNC(btlevtcmd_WaitEventEnd, LW(9))
END_IF()
USER_FUNC(btlevtcmd_CheckDamage, -2, LW(3), LW(4), PTR(&customWeapon_MowzKissThief), 256, LW(5))
RETURN()
END_IF()
USER_FUNC(btlevtcmd_AnimeChangePoseType, -2, 1, 42)
USER_FUNC(btlevtcmd_SetMoveSpeed, -2, FLOAT(3.0))
USER_FUNC(btlevtcmd_GetWidth, LW(3), LW(15))
MUL(LW(15), 2)
DIV(LW(15), 3)
ADD(LW(15), 10)
USER_FUNC(btlevtcmd_GetHitPos, LW(3), LW(4), LW(0), LW(1), LW(2))
USER_FUNC(btlevtcmd_FaceDirectionAdd, LW(3), LW(0), LW(15))
ADD(LW(2), 8)
USER_FUNC(btlevtcmd_TransStageFloorPosition, LW(0), LW(1), LW(2))
USER_FUNC(btlevtcmd_GetMoveFrame, -2, LW(0), LW(1), LW(2), 0, LW(8))
BROTHER_EVT_ID(LW(9))
USER_FUNC(btlevtcmd_MovePosition, -2, LW(0), LW(1), LW(2), LW(8), -1, 0)
END_BROTHER()
IF_LARGE(LW(8), 5)
SUB(LW(8), 2)
SET(LW(15), LW(8))
DIV(LW(15), 3)
SET(LW(8), LW(15))
MUL(LW(8), 2)
USER_FUNC(btlevtcmd_ACRStart, -2, LW(15), LW(8), LW(8), 0)
USER_FUNC(btlevtcmd_ACRGetResult, LW(6), LW(7))
SWITCH(LW(6))
CASE_LARGE_EQUAL(2)
DELETE_EVT(LW(9))
USER_FUNC(evtTot_LogActiveMoveStylish, 0)
USER_FUNC(btlevtcmd_AudienceDeclareAcrobatResult, LW(12), 1, 0, 0, 0)
USER_FUNC(btlevtcmd_AnimeChangePose, -2, 1, PTR("PCH_Y_1"))
USER_FUNC(btlevtcmd_AnimeWaitPlayComplete, -2, 1)
USER_FUNC(btlevtcmd_AnimeChangePoseType, -2, 1, 42)
USER_FUNC(btlevtcmd_MovePosition, -2, LW(0), LW(1), LW(2), 0, -1, 0)
CASE_ETC()
USER_FUNC(evt_audience_acrobat_notry)
USER_FUNC(btlevtcmd_WaitEventEnd, LW(9))
END_SWITCH()
ELSE()
USER_FUNC(btlevtcmd_WaitEventEnd, LW(9))
END_IF()
USER_FUNC(evt_btl_camera_set_mode, 0, 7)
USER_FUNC(evt_btl_camera_set_homing_unit, 0, -2, 1)
USER_FUNC(evt_btl_camera_set_moveSpeedLv, 0, 2)
USER_FUNC(evt_btl_camera_set_zoom, 0, 350)
WAIT_MSEC(200)
USER_FUNC(btlevtcmd_AnimeChangePose, -2, 1, PTR("PCH_K_1"))
WAIT_FRM(6)
IF_NOT_EQUAL(LW(5), 1)
WAIT_FRM(20)
USER_FUNC(btlevtcmd_AnimeChangePoseType, -2, 1, 43)
SWITCH(LW(5))
CASE_OR(4)
CASE_END()
CASE_EQUAL(3)
USER_FUNC(btlevtcmd_StartAvoid, LW(3), 38)
CASE_EQUAL(6)
USER_FUNC(btlevtcmd_StartAvoid, LW(3), 39)
CASE_EQUAL(2)
USER_FUNC(btlevtcmd_StartAvoid, LW(3), 40)
CASE_EQUAL(1)
CASE_ETC()
END_SWITCH()
WAIT_FRM(30)
USER_FUNC(btlevtcmd_StopAC)
GOTO(90)
END_IF()
USER_FUNC(evt_btl_camera_set_moveSpeedLv, 0, 2)
USER_FUNC(evt_btl_camera_set_zoom, 0, 350)
USER_FUNC(btlevtcmd_CheckDamage, -2, LW(3), LW(4), PTR(&customWeapon_MowzKissThief), 256, LW(5))
USER_FUNC(btlevtcmd_GetPos, -2, LW(0), LW(1), LW(2))
USER_FUNC(btlevtcmd_GetHeight, -2, LW(15))
MUL(LW(15), 2)
DIV(LW(15), 3)
ADD(LW(1), LW(15))
USER_FUNC(btlevtcmd_FaceDirectionAdd, -2, LW(0), 20)
USER_FUNC(evt_eff, PTR(""), PTR("kiss"), 0, LW(0), LW(1), LW(2), 1, 0, 0, 0, 0, 0, 0, 0)
USER_FUNC(btlevtcmd_snd_se, -2, PTR("SFX_BTL_CHURINA_KISS1"), EVT_NULLPTR, 0, EVT_NULLPTR)
USER_FUNC(btlevtcmd_OnUnitFlag, LW(3), 33554432)
WAIT_FRM(20)
USER_FUNC(btlevtcmd_AnimeChangePose, -2, 1, PTR("PCH_Z_1"))
USER_FUNC(evt_btl_camera_set_mode, 0, 3)
USER_FUNC(btlevtcmd_AnimeFlagOnOff, -2, 1, 256, 1)
WAIT_FRM(1)
USER_FUNC(mono_capture_event)
RUN_EVT_ID(PTR(&main_evt), LW(13))
INLINE_EVT()
USER_FUNC(mono_on)
END_INLINE()
USER_FUNC(btlevtcmd_CommandGetWeaponActionLv, LW(0))
USER_FUNC(btlevtcmd_AcSetDifficulty, -2, LW(0))
USER_FUNC(_get_itemsteal_param, LW(3), LW(0), LW(1))
USER_FUNC(btlevtcmd_AcSetParamAll, 1, LW(0), 2, 2, LW(1), EVT_NULLPTR, EVT_NULLPTR, EVT_NULLPTR)
USER_FUNC(btlevtcmd_AcSetFlag, 0)
USER_FUNC(btlevtcmd_SetupAC, -2, 15, 1, 0)
WAIT_FRM(22)
USER_FUNC(btlevtcmd_StartAC, 1)
USER_FUNC(btlevtcmd_ResultAC)
USER_FUNC(btlevtcmd_GetResultAC, LW(6))
IF_FLAG(LW(6), 0x2)
USER_FUNC(btlevtcmd_AnimeChangePose, -2, 1, PTR("PCH_A4_1"))
END_IF()
WAIT_FRM(35)
USER_FUNC(evt_snd_sfxon, PTR("SFX_BTL_CHURINA_EYE1"), 0)
WAIT_FRM(47)
USER_FUNC(btlevtcmd_GetPos, LW(3), LW(0), LW(1), LW(2))
USER_FUNC(btlevtcmd_GetWidth, LW(3), LW(15))
DIV(LW(15), 2)
ADD(LW(0), LW(15))
USER_FUNC(btlevtcmd_GetHeight, LW(3), LW(15))
ADD(LW(1), LW(15))
ADD(LW(1), 5)
ADD(LW(2), 8)
USER_FUNC(btlevtcmd_SetFallAccel, -2, FLOAT(0.70))
USER_FUNC(btlevtcmd_JumpPosition, -2, LW(0), LW(1), LW(2), 16, -1)
USER_FUNC(btlevtcmd_GetResultAC, LW(6))
USER_FUNC(evtTot_GetKissThiefResult, LW(3), LW(14), LW(6))
IF_EQUAL(LW(14), 0)
USER_FUNC(btlevtcmd_JumpContinue, -2)
USER_FUNC(btlevtcmd_AnimeChangePose, -2, 1, PTR("PCH_F_1"))
WAIT_FRM(22)
INLINE_EVT()
USER_FUNC(mono_off)
DELETE_EVT(LW(13))
END_INLINE()
WAIT_FRM(20)
USER_FUNC(btlevtcmd_OffUnitFlag, LW(3), 33554432)
USER_FUNC(btlevtcmd_AudienceDeclareACResult, LW(12), -1)
USER_FUNC(evt_btl_camera_set_mode, 0, 0)
USER_FUNC(evt_btl_camera_set_moveSpeedLv, 0, 1)
USER_FUNC(btlevtcmd_SetMoveSpeed, -2, FLOAT(3.0))
USER_FUNC(btlevtcmd_AnimeChangePose, -2, 1, PTR("PCH_R_2"))
USER_FUNC(btlevtcmd_AddRotate, -2, 0, 180, 0)
USER_FUNC(btlevtcmd_GetHomePos, -2, LW(0), LW(1), LW(2))
USER_FUNC(btlevtcmd_DivePosition, -2, LW(0), LW(1), LW(2), 0, 0, 2, 0, -1)
USER_FUNC(btlevtcmd_SetRotate, -2, 0, 0, 0)
GOTO(99)
END_IF()
USER_FUNC(btlevtcmd_GetResultPrizeLv, 0, 0, LW(6))
USER_FUNC(btlevtcmd_GetHitPos, LW(3), LW(4), LW(0), LW(1), LW(2))
USER_FUNC(btlevtcmd_ACSuccessEffect, LW(6), LW(0), LW(1), LW(2))
USER_FUNC(btlevtcmd_AudienceDeclareACResult, LW(12), LW(6))
USER_FUNC(evt_snd_sfxon, PTR("SFX_BTL_CHURINA_HEARTCATCH1"), 0)
USER_FUNC(btlevtcmd_OffUnitFlag, LW(3), 33554432)
INLINE_EVT()
USER_FUNC(mono_off)
DELETE_EVT(LW(13))
END_INLINE()
USER_FUNC(btlevtcmd_GetPos, -2, LW(0), LW(1), LW(2))
USER_FUNC(btlevtcmd_FaceDirectionSub, -2, LW(0), 50)
USER_FUNC(btlevtcmd_TransStageFloorPosition, LW(0), LW(1), LW(2))
USER_FUNC(btlevtcmd_SetFallAccel, -2, FLOAT(0.30))
INLINE_EVT()
USER_FUNC(btlevtcmd_AnimeChangePose, -2, 1, PTR("PCH_A3_1"))
USER_FUNC(btlevtcmd_SetRotateOffset, -2, 0, 10, 0)
DO(18)
USER_FUNC(btlevtcmd_AddRotate, -2, 0, 0, 20)
WAIT_FRM(1)
WHILE()
USER_FUNC(btlevtcmd_SetRotate, -2, 0, 0, 0)
USER_FUNC(btlevtcmd_SetRotateOffset, -2, 0, 0, 0)
END_INLINE()
USER_FUNC(btlevtcmd_JumpPosition, -2, LW(0), LW(1), LW(2), 30, -1)
LBL(90)
USER_FUNC(evt_btl_camera_set_mode, 0, 0)
USER_FUNC(evt_btl_camera_set_moveSpeedLv, 0, 1)
IF_NOT_EQUAL(LW(14), 0)
USER_FUNC(btlevtcmd_GetPos, -2, LW(0), LW(1), LW(2))
USER_FUNC(btlevtcmd_GetHeight, -2, LW(5))
ADD(LW(1), LW(5))
ADD(LW(1), 5)
USER_FUNC(btlevtcmd_BtlIconEntryItemId, LW(14), LW(0), LW(1), LW(2), LW(8))
BROTHER_EVT_ID(LW(15))
USER_FUNC(btlevtcmd_SetMoveSpeed, -2, FLOAT(3.0))
USER_FUNC(btlevtcmd_AnimeChangePoseType, -2, 1, 42)
USER_FUNC(btlevtcmd_AddRotate, -2, 0, 180, 0)
USER_FUNC(btlevtcmd_GetHomePos, -2, LW(0), LW(1), LW(2))
USER_FUNC(btlevtcmd_DivePosition, -2, LW(0), LW(1), LW(2), 0, 0, 2, 0, -1)
USER_FUNC(btlevtcmd_SetRotate, -2, 0, 0, 0)
END_BROTHER()
LBL(91)
USER_FUNC(btlevtcmd_GetPos, -2, LW(0), LW(1), LW(2))
USER_FUNC(btlevtcmd_GetHeight, -2, LW(5))
ADD(LW(1), LW(5))
ADD(LW(1), 5)
USER_FUNC(btlevtcmd_BtlIconSetPosition, LW(8), LW(0), LW(1), LW(2))
CHK_EVT(LW(15), LW(0))
IF_NOT_EQUAL(LW(0), 0)
WAIT_FRM(1)
GOTO(91)
END_IF()
USER_FUNC(btlevtcmd_AnimeChangePose, -2, 1, PTR("PCH_A2_2"))
WAIT_FRM(4)
USER_FUNC(btlevtcmd_AnnounceSetParam, 0, LW(14))
USER_FUNC(btlevtcmd_AnnounceMessage, 1, 0, 0, PTR("btl_msg_steal_item_get"), 90)
// If a Star Piece was stolen, award the player a move rank-up.
IF_EQUAL(LW(14), (int32_t)ItemType::STAR_PIECE)
USER_FUNC(evtTot_RankUpRandomMoveInBattle, LW(14))
IF_NOT_EQUAL(LW(14), 0)
WAIT_FRM(5)
USER_FUNC(btlevtcmd_AnnounceMessage, 3, 0, 0, LW(14), 120)
END_IF()
END_IF()
USER_FUNC(btlevtcmd_BtlIconDelete, LW(8))
ELSE()
USER_FUNC(btlevtcmd_SetMoveSpeed, -2, FLOAT(3.0))
USER_FUNC(btlevtcmd_AnimeChangePoseType, -2, 1, 42)
USER_FUNC(btlevtcmd_AddRotate, -2, 0, 180, 0)
USER_FUNC(btlevtcmd_GetHomePos, -2, LW(0), LW(1), LW(2))
USER_FUNC(btlevtcmd_DivePosition, -2, LW(0), LW(1), LW(2), 0, 0, 2, 0, -1)
USER_FUNC(btlevtcmd_SetRotate, -2, 0, 0, 0)
END_IF()
LBL(99)
USER_FUNC(evt_audience_ap_recovery)
USER_FUNC(btlevtcmd_InviteApInfoReport)
USER_FUNC(btlevtcmd_ResetFaceDirection, -2)
USER_FUNC(btlevtcmd_StartWaitEvent, -2)
RETURN()
EVT_END()
EVT_BEGIN(partyChuchurinaAttack_MadowaseAttack)
USER_FUNC(btlevtcmd_CommandGetWeaponAddress, -2, LW(12))
IF_EQUAL((int32_t)GSW_Battle_DooplissMove, 0)
USER_FUNC(btlevtcmd_GetSelectEnemy, LW(3), LW(4))
ELSE()
USER_FUNC(btlevtcmd_GetEnemyBelong, -2, LW(0))
USER_FUNC(btlevtcmd_SamplingEnemy, -2, LW(0), LW(12))
USER_FUNC(btlevtcmd_ChoiceSamplingEnemy, LW(12), LW(3), LW(4))
END_IF()
IF_EQUAL(LW(3), -1)
GOTO(99)
END_IF()
USER_FUNC(btlevtcmd_WeaponAftereffect, LW(12))
USER_FUNC(btlevtcmd_AttackDeclareAll, -2)
USER_FUNC(btlevtcmd_WaitGuardMove)
USER_FUNC(btlevtcmd_CommandPayWeaponCost, -2)
USER_FUNC(btlevtcmd_RunDataEventChild, -2, 7)
USER_FUNC(btlevtcmd_CommandGetWeaponActionLv, LW(0))
IF_EQUAL((int32_t)GSW_Battle_DooplissMove, 0)
USER_FUNC(btlevtcmd_AcSetDifficulty, -2, LW(0))
USER_FUNC(btlevtcmd_AcSetFlag, 41)
USER_FUNC(btlevtcmd_AcGetDifficulty, LW(0))
SUB(LW(0), 3)
SWITCH(LW(0))
CASE_SMALL_EQUAL(-3)
SET(LW(0), 3)
SET(LW(1), 50)
CASE_EQUAL(-2)
SET(LW(0), 4)
SET(LW(1), 80)
CASE_EQUAL(-1)
SET(LW(0), 5)
SET(LW(1), 100)
CASE_EQUAL(0)
SET(LW(0), 7)
SET(LW(1), 100)
CASE_EQUAL(1)
SET(LW(0), 8)
SET(LW(1), 110)
USER_FUNC(btlevtcmd_AcSetFlag, 49)
CASE_EQUAL(2)
SET(LW(0), 10)
SET(LW(1), 120)
USER_FUNC(btlevtcmd_AcSetFlag, 49)
CASE_ETC()
SET(LW(0), 12)
SET(LW(1), 130)
USER_FUNC(btlevtcmd_AcSetFlag, 49)
END_SWITCH()
// Set gauge colors + success params based on move used.
SWITCH(LW(12))
CASE_EQUAL(PTR(&customWeapon_MowzSmokeBomb))
USER_FUNC(evtTot_GetMoveSelectedLevel, MoveType::MOWZ_SMOKE_BOMB, LW(2))
SWITCH(LW(2))
CASE_EQUAL(1)
USER_FUNC(btlevtcmd_AcSetGaugeParam, 67, 100, 100, 100)
SET(LW(2), 68)
CASE_EQUAL(2)
USER_FUNC(btlevtcmd_AcSetGaugeParam, 50, 75, 100, 100)
SET(LW(2), 51)
CASE_ETC()
USER_FUNC(btlevtcmd_AcSetGaugeParam, 40, 60, 80, 100)
SET(LW(2), 41)
END_SWITCH()
CASE_EQUAL(PTR(&customWeapon_MowzEmbargo))
USER_FUNC(btlevtcmd_AcSetGaugeParam, 75, 100, 100, 100)
SET(LW(2), 75)
CASE_ETC()
USER_FUNC(btlevtcmd_AcSetGaugeParam, 34, 68, 100, 100)
SET(LW(2), 1)
END_SWITCH()
USER_FUNC(btlevtcmd_AcSetParamAll, 1, 240, 178, LW(0), LW(1), 100, LW(2), EVT_NULLPTR)
USER_FUNC(btlevtcmd_SetupAC, -2, 6, 1, 0)
END_IF()
USER_FUNC(btlevtcmd_GetPos, -2, LW(0), EVT_NULLPTR, EVT_NULLPTR)
USER_FUNC(evt_btl_camera_set_mode, 0, 3)
USER_FUNC(evt_btl_camera_set_moveto, 1, LW(0), 73, 400, LW(0), 43, 0, 40, 5)
IF_EQUAL((int32_t)GSW_Battle_DooplissMove, 0)
WAIT_FRM(22)
USER_FUNC(btlevtcmd_StartAC, 1)
USER_FUNC(btlevtcmd_ResultAC)
USER_FUNC(btlevtcmd_StopAC)
WAIT_FRM(20)
ELSE()
WAIT_FRM(20)
END_IF()
USER_FUNC(btlevtcmd_AnimeChangePose, -2, 1, PTR("PCH_I_1"))
DO(40)
USER_FUNC(btlevtcmd_AddRotate, -2, 0, 36, 0)
WAIT_FRM(1)
WHILE()
USER_FUNC(btlevtcmd_SetRotate, -2, 0, 0, 0)
USER_FUNC(btlevtcmd_AnimeChangePose, -2, 1, PTR("PCH_A4_1"))
USER_FUNC(btlevtcmd_SetWalkSound, -2, PTR("SFX_BTL_CHURINA_CONFUSE_MOVE1L"), PTR("SFX_BTL_CHURINA_CONFUSE_MOVE1R"), 0, 15, 13)
USER_FUNC(btlevtcmd_SetRunSound, -2, PTR("SFX_BTL_CHURINA_CONFUSE_MOVE1L"), PTR("SFX_BTL_CHURINA_CONFUSE_MOVE1R"), 0, 7, 7)
USER_FUNC(btlevtcmd_SetDiveSound, -2, PTR("SFX_BTL_CHURINA_CONFUSE_MOVE1L"), PTR("SFX_BTL_CHURINA_CONFUSE_MOVE1R"), 0, 7, 7)
USER_FUNC(btlevtcmd_SetJumpSound, -2, PTR("SFX_BTL_CHURINA_CONFUSE_JUMP1"), PTR("SFX_BTL_CHURINA_CONFUSE_LANDING1"))
USER_FUNC(btlevtcmd_SetPartsWalkSound, -2, 2, PTR("SFX_BTL_CHURINA_CONFUSE_MOVE1L"), PTR("SFX_BTL_CHURINA_CONFUSE_MOVE1R"), 0, 15, 13)
USER_FUNC(btlevtcmd_SetPartsRunSound, -2, 2, PTR("SFX_BTL_CHURINA_CONFUSE_MOVE1L"), PTR("SFX_BTL_CHURINA_CONFUSE_MOVE1R"), 0, 7, 7)
USER_FUNC(btlevtcmd_SetPartsDiveSound, -2, 2, PTR("SFX_BTL_CHURINA_CONFUSE_MOVE1L"), PTR("SFX_BTL_CHURINA_CONFUSE_MOVE1R"), 0, 7, 7)
USER_FUNC(btlevtcmd_SetPartsJumpSound, -2, 2, PTR("SFX_BTL_CHURINA_CONFUSE_JUMP1"), PTR("SFX_BTL_CHURINA_CONFUSE_LANDING1"))
USER_FUNC(btlevtcmd_SetPartsWalkSound, -2, 3, PTR("SFX_BTL_CHURINA_CONFUSE_MOVE1L"), PTR("SFX_BTL_CHURINA_CONFUSE_MOVE1R"), 0, 15, 13)
USER_FUNC(btlevtcmd_SetPartsRunSound, -2, 3, PTR("SFX_BTL_CHURINA_CONFUSE_MOVE1L"), PTR("SFX_BTL_CHURINA_CONFUSE_MOVE1R"), 0, 7, 7)
USER_FUNC(btlevtcmd_SetPartsDiveSound, -2, 3, PTR("SFX_BTL_CHURINA_CONFUSE_MOVE1L"), PTR("SFX_BTL_CHURINA_CONFUSE_MOVE1R"), 0, 7, 7)
USER_FUNC(btlevtcmd_SetPartsJumpSound, -2, 3, PTR("SFX_BTL_CHURINA_CONFUSE_JUMP1"), PTR("SFX_BTL_CHURINA_CONFUSE_LANDING1"))
USER_FUNC(btlevtcmd_SetPartsWalkSound, -2, 4, PTR("SFX_BTL_CHURINA_CONFUSE_MOVE1L"), PTR("SFX_BTL_CHURINA_CONFUSE_MOVE1R"), 0, 15, 13)
USER_FUNC(btlevtcmd_SetPartsRunSound, -2, 4, PTR("SFX_BTL_CHURINA_CONFUSE_MOVE1L"), PTR("SFX_BTL_CHURINA_CONFUSE_MOVE1R"), 0, 7, 7)
USER_FUNC(btlevtcmd_SetPartsDiveSound, -2, 4, PTR("SFX_BTL_CHURINA_CONFUSE_MOVE1L"), PTR("SFX_BTL_CHURINA_CONFUSE_MOVE1R"), 0, 7, 7)
USER_FUNC(btlevtcmd_SetPartsJumpSound, -2, 4, PTR("SFX_BTL_CHURINA_CONFUSE_JUMP1"), PTR("SFX_BTL_CHURINA_CONFUSE_LANDING1"))
USER_FUNC(btlevtcmd_GetPos, -2, LW(0), LW(1), LW(2))
ADD(LW(1), 40)
SUB(LW(2), 20)
USER_FUNC(btlevtcmd_FaceDirectionAdd, -2, LW(0), 20)
USER_FUNC(btlevtcmd_SetPartsPos, -2, 2, LW(0), LW(1), LW(2))
USER_FUNC(btlevtcmd_SetPartsRotate, -2, 2, 0, 180, 0)
USER_FUNC(btlevtcmd_AnimeChangePose, -2, 2, PTR("PCH_A3_1"))
USER_FUNC(btlevtcmd_OffPartsAttribute, -2, 2, 50331648)
USER_FUNC(evt_eff, PTR(""), PTR("bomb"), 0, LW(0), LW(1), LW(2), FLOAT(1.0), 0, 0, 0, 0, 0, 0, 0)
USER_FUNC(btlevtcmd_snd_se, -2, PTR("SFX_BTL_CHURINA_CONFUSE1"), EVT_NULLPTR, 0, EVT_NULLPTR)
BROTHER_EVT()
WAIT_FRM(30)
USER_FUNC(btlevtcmd_SetPartsFallAccel, -2, 2, FLOAT(0.30))
USER_FUNC(btlevtcmd_GetPartsPos, -2, 2, LW(0), LW(1), LW(2))
USER_FUNC(btlevtcmd_TransStageFloorPosition, LW(0), LW(1), LW(2))
USER_FUNC(btlevtcmd_FallPartsPosition, -2, 2, LW(0), LW(1), LW(2), 25)
USER_FUNC(btlevtcmd_SetPartsRotate, -2, 2, 0, 0, 0)
USER_FUNC(btlevtcmd_AnimeChangePoseType, -2, 2, 43)
END_BROTHER()
USER_FUNC(btlevtcmd_GetPos, -2, LW(0), LW(1), LW(2))
ADD(LW(1), 20)
SUB(LW(2), 10)
USER_FUNC(btlevtcmd_FaceDirectionAdd, -2, LW(0), 10)
USER_FUNC(btlevtcmd_SetPartsPos, -2, 3, LW(0), LW(1), LW(2))
USER_FUNC(btlevtcmd_SetPartsRotate, -2, 3, 0, 0, 0)
USER_FUNC(btlevtcmd_AnimeChangePose, -2, 3, PTR("PCH_A3_2"))
USER_FUNC(btlevtcmd_OffPartsAttribute, -2, 3, 50331648)
USER_FUNC(evt_eff, PTR(""), PTR("bomb"), 0, LW(0), LW(1), LW(2), FLOAT(1.0), 0, 0, 0, 0, 0, 0, 0)
BROTHER_EVT()
WAIT_FRM(30)
USER_FUNC(btlevtcmd_SetPartsFallAccel, -2, 3, FLOAT(0.30))
USER_FUNC(btlevtcmd_GetPartsPos, -2, 3, LW(0), LW(1), LW(2))
USER_FUNC(btlevtcmd_TransStageFloorPosition, LW(0), LW(1), LW(2))
USER_FUNC(btlevtcmd_FallPartsPosition, -2, 3, LW(0), LW(1), LW(2), 25)
USER_FUNC(btlevtcmd_SetPartsRotate, -2, 3, 0, 0, 0)
USER_FUNC(btlevtcmd_AnimeChangePoseType, -2, 3, 43)
END_BROTHER()
USER_FUNC(btlevtcmd_GetPos, -2, LW(0), LW(1), LW(2))
ADD(LW(1), 30)
ADD(LW(2), 10)
USER_FUNC(btlevtcmd_FaceDirectionAdd, -2, LW(0), -10)
USER_FUNC(btlevtcmd_SetPartsPos, -2, 4, LW(0), LW(1), LW(2))
USER_FUNC(btlevtcmd_SetPartsRotate, -2, 4, 0, 180, 0)
USER_FUNC(btlevtcmd_AnimeChangePose, -2, 4, PTR("PCH_A3_3"))
USER_FUNC(btlevtcmd_OffPartsAttribute, -2, 4, 50331648)
USER_FUNC(evt_eff, PTR(""), PTR("bomb"), 0, LW(0), LW(1), LW(2), FLOAT(1.0), 0, 0, 0, 0, 0, 0, 0)
BROTHER_EVT()
WAIT_FRM(30)
USER_FUNC(btlevtcmd_SetPartsFallAccel, -2, 4, FLOAT(0.30))
USER_FUNC(btlevtcmd_GetPartsPos, -2, 4, LW(0), LW(1), LW(2))
USER_FUNC(btlevtcmd_TransStageFloorPosition, LW(0), LW(1), LW(2))
USER_FUNC(btlevtcmd_FallPartsPosition, -2, 4, LW(0), LW(1), LW(2), 25)
USER_FUNC(btlevtcmd_SetPartsRotate, -2, 4, 0, 0, 0)
USER_FUNC(btlevtcmd_AnimeChangePoseType, -2, 4, 43)
END_BROTHER()
WAIT_FRM(85)
USER_FUNC(btlevtcmd_AnimeChangePoseType, -2, 1, 43)
USER_FUNC(btlevtcmd_SetUnitWork, -2, 0, 1)
USER_FUNC(btlevtcmd_SetUnitWork, -2, 1, 1)
USER_FUNC(btlevtcmd_SetUnitWork, -2, 2, 1)
USER_FUNC(btlevtcmd_SetUnitWork, -2, 3, 1)
USER_FUNC(btlevtcmd_SetPartsBlur, -2, 1, 255, 255, 255, 255, 100, 100, 100, 50, 1)
USER_FUNC(btlevtcmd_OnPartsAttribute, -2, 1, 67108864)
USER_FUNC(btlevtcmd_SetPartsBlur, -2, 2, 255, 255, 255, 255, 100, 100, 100, 50, 1)
USER_FUNC(btlevtcmd_OnPartsAttribute, -2, 2, 67108864)
USER_FUNC(btlevtcmd_SetPartsBlur, -2, 3, 255, 255, 255, 255, 100, 100, 100, 50, 1)
USER_FUNC(btlevtcmd_OnPartsAttribute, -2, 3, 67108864)
USER_FUNC(btlevtcmd_SetPartsBlur, -2, 4, 255, 255, 255, 255, 100, 100, 100, 50, 1)
USER_FUNC(btlevtcmd_OnPartsAttribute, -2, 4, 67108864)
BROTHER_EVT()
WAIT_FRM(40)
USER_FUNC(btlevtcmd_AnimeChangePoseType, -2, 1, 42)
USER_FUNC(btlevtcmd_GetPos, -2, LW(0), LW(1), LW(2))
USER_FUNC(btlevtcmd_GetStageSize, LW(5), EVT_NULLPTR, EVT_NULLPTR)
DIV(LW(5), 3)
SET(LW(0), 0)
USER_FUNC(btlevtcmd_FaceDirectionAdd, -2, LW(0), LW(5))
USER_FUNC(btlevtcmd_GetMoveFrame, -2, LW(0), LW(1), LW(2), FLOAT(3.0), LW(7))
USER_FUNC(evt_btl_camera_set_mode, 0, 3)
USER_FUNC(evt_btl_camera_set_moveto, 1, LW(0), 90, 500, LW(0), 60, 0, LW(7), 0)
END_BROTHER()
BROTHER_EVT()
USER_FUNC(btlevtcmd_SetFallAccel, -2, FLOAT(0.70))
WAIT_FRM(40)
USER_FUNC(btlevtcmd_AnimeChangePoseType, -2, 1, 42)
USER_FUNC(btlevtcmd_GetPos, -2, LW(0), LW(1), LW(2))
USER_FUNC(btlevtcmd_GetStageSize, LW(5), EVT_NULLPTR, EVT_NULLPTR)
DIV(LW(5), 3)
SET(LW(0), 0)
USER_FUNC(btlevtcmd_FaceDirectionAdd, -2, LW(0), LW(5))
USER_FUNC(btlevtcmd_SetMoveSpeed, -2, FLOAT(3.0))
USER_FUNC(btlevtcmd_DivePosition, -2, LW(0), LW(1), LW(2), 0, 0, 2, 0, -1)
USER_FUNC(btlevtcmd_GetPos, -2, LW(0), LW(1), LW(2))
ADD(LW(0), 40)
USER_FUNC(btlevtcmd_JumpPosition, -2, LW(0), LW(1), LW(2), 20, -1)
SUB(LW(0), 60)
USER_FUNC(btlevtcmd_SetRotate, -2, 0, 180, 0)
USER_FUNC(btlevtcmd_JumpPosition, -2, LW(0), LW(1), LW(2), 20, -1)
ADD(LW(0), 40)
USER_FUNC(btlevtcmd_SetRotate, -2, 0, 0, 0)
USER_FUNC(btlevtcmd_JumpPosition, -2, LW(0), LW(1), LW(2), 20, -1)
SUB(LW(0), 60)
USER_FUNC(btlevtcmd_SetRotate, -2, 0, 180, 0)
USER_FUNC(btlevtcmd_JumpPosition, -2, LW(0), LW(1), LW(2), 20, -1)
ADD(LW(0), 40)
USER_FUNC(btlevtcmd_SetRotate, -2, 0, 0, 0)
USER_FUNC(btlevtcmd_JumpPosition, -2, LW(0), LW(1), LW(2), 20, -1)
USER_FUNC(evt_eff, PTR(""), PTR("bomb"), 0, LW(0), LW(1), LW(2), FLOAT(1.0), 0, 0, 0, 0, 0, 0, 0)
USER_FUNC(btlevtcmd_OffPartsAttribute, -2, 1, 67108864)
USER_FUNC(btlevtcmd_SetUnitWork, -2, 0, 0)
END_BROTHER()
BROTHER_EVT()
SET(LW(6), 2)
USER_FUNC(btlevtcmd_SetPartsFallAccel, -2, LW(6), FLOAT(0.70))
USER_FUNC(btlevtcmd_AnimeChangePoseType, -2, LW(6), 42)
USER_FUNC(btlevtcmd_GetPartsPos, -2, LW(6), LW(0), LW(1), LW(2))
USER_FUNC(btlevtcmd_GetStageSize, LW(5), EVT_NULLPTR, EVT_NULLPTR)
DIV(LW(5), 3)
SET(LW(0), 0)
USER_FUNC(btlevtcmd_FaceDirectionAdd, -2, LW(0), LW(5))
USER_FUNC(btlevtcmd_SetPartsMoveSpeed, -2, LW(6), FLOAT(3.0))
USER_FUNC(btlevtcmd_DivePartsPosition, -2, LW(6), LW(0), LW(1), LW(2), 0, 0, 2, 0, -1)
USER_FUNC(btlevtcmd_GetPartsPos, -2, LW(6), LW(0), LW(1), LW(2))
ADD(LW(0), 60)
USER_FUNC(btlevtcmd_JumpPartsPosition, -2, LW(6), LW(0), LW(1), LW(2), 25, -1)
SUB(LW(0), 90)
USER_FUNC(btlevtcmd_SetPartsRotate, -2, LW(6), 0, 180, 0)
USER_FUNC(btlevtcmd_JumpPartsPosition, -2, LW(6), LW(0), LW(1), LW(2), 25, -1)
ADD(LW(0), 60)
USER_FUNC(btlevtcmd_SetPartsRotate, -2, LW(6), 0, 0, 0)
USER_FUNC(btlevtcmd_JumpPartsPosition, -2, LW(6), LW(0), LW(1), LW(2), 25, -1)
SUB(LW(0), 90)
USER_FUNC(btlevtcmd_SetPartsRotate, -2, LW(6), 0, 180, 0)
USER_FUNC(btlevtcmd_JumpPartsPosition, -2, LW(6), LW(0), LW(1), LW(2), 25, -1)
SUB(LW(0), 30)
USER_FUNC(btlevtcmd_SetPartsRotate, -2, LW(6), 0, 180, 0)
USER_FUNC(btlevtcmd_JumpPartsPosition, -2, LW(6), LW(0), LW(1), LW(2), 25, -1)
ADD(LW(0), 30)
USER_FUNC(btlevtcmd_SetPartsRotate, -2, LW(6), 0, 0, 0)
USER_FUNC(btlevtcmd_JumpPartsPosition, -2, LW(6), LW(0), LW(1), LW(2), 25, -1)
USER_FUNC(evt_eff, PTR(""), PTR("bomb"), 0, LW(0), LW(1), LW(2), FLOAT(1.0), 0, 0, 0, 0, 0, 0, 0)
USER_FUNC(btlevtcmd_OnPartsAttribute, -2, 2, 50331648)
USER_FUNC(btlevtcmd_OffPartsAttribute, -2, 2, 67108864)
USER_FUNC(btlevtcmd_SetUnitWork, -2, 1, 0)
END_BROTHER()
BROTHER_EVT()
SET(LW(6), 3)
USER_FUNC(btlevtcmd_SetPartsFallAccel, -2, LW(6), FLOAT(0.70))
WAIT_FRM(20)
USER_FUNC(btlevtcmd_AnimeChangePoseType, -2, LW(6), 42)
USER_FUNC(btlevtcmd_GetPartsPos, -2, LW(6), LW(0), LW(1), LW(2))
USER_FUNC(btlevtcmd_GetStageSize, LW(5), EVT_NULLPTR, EVT_NULLPTR)
DIV(LW(5), 3)
SET(LW(0), 0)
USER_FUNC(btlevtcmd_FaceDirectionAdd, -2, LW(0), LW(5))
USER_FUNC(btlevtcmd_SetPartsMoveSpeed, -2, LW(6), FLOAT(3.0))
USER_FUNC(btlevtcmd_DivePartsPosition, -2, LW(6), LW(0), LW(1), LW(2), 0, 0, 2, 0, -1)
USER_FUNC(btlevtcmd_GetPartsPos, -2, LW(6), LW(0), LW(1), LW(2))
SUB(LW(0), 80)
USER_FUNC(btlevtcmd_SetPartsRotate, -2, LW(6), 0, 180, 0)
USER_FUNC(btlevtcmd_JumpPartsPosition, -2, LW(6), LW(0), LW(1), LW(2), 25, -1)
ADD(LW(0), 160)
USER_FUNC(btlevtcmd_SetPartsRotate, -2, LW(6), 0, 0, 0)
USER_FUNC(btlevtcmd_JumpPartsPosition, -2, LW(6), LW(0), LW(1), LW(2), 40, -1)
SUB(LW(0), 40)
USER_FUNC(btlevtcmd_SetPartsRotate, -2, LW(6), 0, 180, 0)
USER_FUNC(btlevtcmd_JumpPartsPosition, -2, LW(6), LW(0), LW(1), LW(2), 15, -1)
SUB(LW(0), 60)
USER_FUNC(btlevtcmd_SetPartsRotate, -2, LW(6), 0, 180, 0)
USER_FUNC(btlevtcmd_JumpPartsPosition, -2, LW(6), LW(0), LW(1), LW(2), 20, -1)
ADD(LW(0), 20)
USER_FUNC(btlevtcmd_SetPartsRotate, -2, LW(6), 0, 0, 0)
USER_FUNC(btlevtcmd_JumpPartsPosition, -2, LW(6), LW(0), LW(1), LW(2), 20, -1)
USER_FUNC(evt_eff, PTR(""), PTR("bomb"), 0, LW(0), LW(1), LW(2), FLOAT(1.0), 0, 0, 0, 0, 0, 0, 0)
USER_FUNC(btlevtcmd_OnPartsAttribute, -2, 3, 50331648)
USER_FUNC(btlevtcmd_OffPartsAttribute, -2, 3, 67108864)
USER_FUNC(btlevtcmd_SetUnitWork, -2, 2, 0)
END_BROTHER()
BROTHER_EVT()
SET(LW(6), 4)
USER_FUNC(btlevtcmd_SetPartsFallAccel, -2, LW(6), FLOAT(0.70))
WAIT_FRM(60)
USER_FUNC(btlevtcmd_AnimeChangePoseType, -2, LW(6), 42)
USER_FUNC(btlevtcmd_GetPartsPos, -2, LW(6), LW(0), LW(1), LW(2))
USER_FUNC(btlevtcmd_GetStageSize, LW(5), EVT_NULLPTR, EVT_NULLPTR)
DIV(LW(5), 3)
SET(LW(0), 0)
USER_FUNC(btlevtcmd_FaceDirectionAdd, -2, LW(0), LW(5))
USER_FUNC(btlevtcmd_SetPartsMoveSpeed, -2, LW(6), FLOAT(3.0))
USER_FUNC(btlevtcmd_DivePartsPosition, -2, LW(6), LW(0), LW(1), LW(2), 0, 0, 2, 0, -1)
USER_FUNC(btlevtcmd_GetPartsPos, -2, LW(6), LW(0), LW(1), LW(2))
ADD(LW(0), 30)
USER_FUNC(btlevtcmd_JumpPartsPosition, -2, LW(6), LW(0), LW(1), LW(2), 10, -1)
ADD(LW(0), 30)
USER_FUNC(btlevtcmd_SetPartsRotate, -2, LW(6), 0, 0, 0)
USER_FUNC(btlevtcmd_JumpPartsPosition, -2, LW(6), LW(0), LW(1), LW(2), 10, -1)
SUB(LW(0), 30)
USER_FUNC(btlevtcmd_SetPartsRotate, -2, LW(6), 0, 180, 0)
USER_FUNC(btlevtcmd_JumpPartsPosition, -2, LW(6), LW(0), LW(1), LW(2), 10, -1)
SUB(LW(0), 30)
USER_FUNC(btlevtcmd_SetPartsRotate, -2, LW(6), 0, 180, 0)
USER_FUNC(btlevtcmd_JumpPartsPosition, -2, LW(6), LW(0), LW(1), LW(2), 10, -1)
SUB(LW(0), 30)
USER_FUNC(btlevtcmd_SetPartsRotate, -2, LW(6), 0, 180, 0)
USER_FUNC(btlevtcmd_JumpPartsPosition, -2, LW(6), LW(0), LW(1), LW(2), 10, -1)
SUB(LW(0), 30)
USER_FUNC(btlevtcmd_SetPartsRotate, -2, LW(6), 0, 180, 0)
USER_FUNC(btlevtcmd_JumpPartsPosition, -2, LW(6), LW(0), LW(1), LW(2), 10, -1)
ADD(LW(0), 30)
USER_FUNC(btlevtcmd_SetPartsRotate, -2, LW(6), 0, 0, 0)
USER_FUNC(btlevtcmd_JumpPartsPosition, -2, LW(6), LW(0), LW(1), LW(2), 10, -1)
SUB(LW(0), 30)
USER_FUNC(btlevtcmd_SetPartsRotate, -2, LW(6), 0, 180, 0)
USER_FUNC(btlevtcmd_JumpPartsPosition, -2, LW(6), LW(0), LW(1), LW(2), 10, -1)
USER_FUNC(evt_eff, PTR(""), PTR("bomb"), 0, LW(0), LW(1), LW(2), FLOAT(1.0), 0, 0, 0, 0, 0, 0, 0)
USER_FUNC(btlevtcmd_OnPartsAttribute, -2, 4, 50331648)
USER_FUNC(btlevtcmd_OffPartsAttribute, -2, 4, 67108864)
USER_FUNC(btlevtcmd_SetUnitWork, -2, 3, 0)
END_BROTHER()
LBL(9)
SET(LW(0), 0)
USER_FUNC(btlevtcmd_GetUnitWork, -2, 0, LW(1))
ADD(LW(0), LW(1))
USER_FUNC(btlevtcmd_GetUnitWork, -2, 1, LW(1))
ADD(LW(0), LW(1))
USER_FUNC(btlevtcmd_GetUnitWork, -2, 2, LW(1))
ADD(LW(0), LW(1))
USER_FUNC(btlevtcmd_GetUnitWork, -2, 3, LW(1))
ADD(LW(0), LW(1))
IF_NOT_EQUAL(LW(0), 0)
WAIT_FRM(1)
GOTO(9)
END_IF()
USER_FUNC(evt_snd_sfxon, PTR("SFX_BTL_CHURINA_CONFUSE1"), 0)
SET(LW(10), 0)
// Count total number of enemies hit successfully.
SET(LW(15), 0)
LBL(10)
// Clear fog and have bigger smoke effect than usual.
IF_EQUAL(LW(12), PTR(&customWeapon_MowzSmokeBomb))
USER_FUNC(btlevtcmd_StageDispellFog)
USER_FUNC(btlevtcmd_GetPos, -2, LW(0), LW(1), LW(2))
USER_FUNC(evt_eff, PTR(""), PTR("bomb"), 0, LW(0), LW(1), LW(2), FLOAT(4.0), 0, 0, 0, 0, 0, 0, 0)
END_IF()
USER_FUNC(btlevtcmd_CommandPreCheckDamage, -2, LW(3), LW(4), 256, LW(6))
IF_NOT_EQUAL(LW(6), 1)
IF_EQUAL(LW(6), 3)
USER_FUNC(btlevtcmd_StartAvoid, LW(3), 38)
END_IF()
IF_EQUAL(LW(6), 6)
USER_FUNC(btlevtcmd_StartAvoid, LW(3), 39)
END_IF()
IF_EQUAL(LW(6), 2)
USER_FUNC(btlevtcmd_StartAvoid, LW(3), 40)
END_IF()
GOTO(50)
END_IF()
// Make weapons and set AC success level.
SET(LW(13), -1)
IF_EQUAL((int32_t)GSW_Battle_DooplissMove, 1)
USER_FUNC(btlevtcmd_AcSetOutputParam, 1, 95)
END_IF()
USER_FUNC(btlevtcmd_AcGetOutputParam, 1, LW(0))
SWITCH(LW(12))
CASE_EQUAL(PTR(&customWeapon_MowzSmokeBomb))
USER_FUNC(evtTot_MakeTeaseWeapon, LW(12), LW(0), MoveType::MOWZ_SMOKE_BOMB)
USER_FUNC(evtTot_GetMoveSelectedLevel, MoveType::MOWZ_SMOKE_BOMB, LW(1))
ADD(LW(1), 2)
MUL(LW(0), LW(1))
DIV(LW(0), 100)
SUB(LW(0), 2)
IF_SMALL(LW(0), 0)
SET(LW(0), -1)
END_IF()
SET(LW(13), LW(0))
CASE_EQUAL(PTR(&customWeapon_MowzTease))
USER_FUNC(evtTot_MakeTeaseWeapon, LW(12), LW(0), MoveType::MOWZ_TEASE)
IF_LARGE(LW(0), 0)
SET(LW(13), 0)
END_IF()
CASE_ETC()
IF_LARGE_EQUAL(LW(0), 75)
SET(LW(13), 0)
END_IF()
END_SWITCH()
// By default, consider action unsuccessful.
SET(LW(11), -1)
IF_EQUAL(LW(10), 0)
USER_FUNC(btlevtcmd_ResultACDefence, LW(3), LW(12))
SET(LW(10), 1)
END_IF()
IF_NOT_EQUAL(LW(12), PTR(&customWeapon_MowzEmbargo))
IF_LARGE_EQUAL(LW(13), 0)
USER_FUNC(btlevtcmd_CheckDamage, -2, LW(3), LW(4), LW(12), 131328, LW(5))
IF_EQUAL((int32_t)GSW_Battle_DooplissMove, 0)
// Only considered successful if damaged or status procs.
USER_FUNC(btlevtcmd_GetResultPrizeLv, LW(3), LW(13), LW(11))
END_IF()
ELSE()
GOTO(30)
END_IF()
ELSE()
IF_LARGE_EQUAL(LW(13), 0)
// For Embargo, mark as successful if the enemy had an item.
USER_FUNC(evtTot_ConfiscateItem, LW(3), LW(14))
IF_NOT_EQUAL(LW(14), 0)
SET(LW(11), 0)
// If the enemy has an item, have it get tossed away in a random dir.
BROTHER_EVT()
USER_FUNC(evtTot_GetHeldItemPosition, LW(3), LW(0), LW(1), LW(2))
USER_FUNC(btlevtcmd_BtlIconEntryItemId, LW(14), LW(0), LW(1), LW(2), LW(8))
// Initial movement vector.
USER_FUNC(evt_sub_random, 200, LW(5))
SUB(LW(5), 100)
DIVF(LW(5), FLOAT(50.0))
USER_FUNC(evt_sub_random, 17, LW(6))
ADD(LW(6), 36)
DIVF(LW(6), FLOAT(10.0))
// Update movement.
DO(75)
ADDF(LW(0), LW(5))
ADDF(LW(1), LW(6))
ADDF(LW(6), FLOAT(-0.1))
WAIT_FRM(1)
USER_FUNC(btlevtcmd_BtlIconSetPosition, LW(8), LW(0), LW(1), LW(2))
WHILE()
// Puff of smoke on disappearing.
WAIT_FRM(1)
USER_FUNC(btlevtcmd_BtlIconDelete, LW(8))
USER_FUNC(evt_eff, PTR(""), PTR("bomb"), 0, LW(0), LW(1), LW(2), FLOAT(1.0), 0, 0, 0, 0, 0, 0, 0)
END_BROTHER()
// Have enemy react with "damaged" animation.
BROTHER_EVT()
WAIT_FRM(1)
USER_FUNC(btlevtcmd_AnimeChangePoseType, LW(3), LW(4), 39)
WAIT_FRM(100)
USER_FUNC(btlevtcmd_AnimeChangePoseFromTable, LW(3), 1)
END_BROTHER()
ELSE()
GOTO(30)
END_IF()
ELSE()
GOTO(30)
END_IF()
END_IF()
GOTO(40)
LBL(30)
USER_FUNC(btlevtcmd_CheckDamage, -2, LW(3), LW(4), LW(12), 256, LW(5))
LBL(40)
// Increment number of successful hits if appropriate.
IF_LARGE_EQUAL(LW(11), 0)
ADD(LW(15), 1)
END_IF()
LBL(50)
USER_FUNC(btlevtcmd_GetSelectNextEnemy, LW(3), LW(4))
IF_NOT_EQUAL(LW(3), -1)
GOTO(10)
END_IF()
// If there were any successful hits, give the appropriate reward.
IF_EQUAL((int32_t)GSW_Battle_DooplissMove, 0)
IF_LARGE(LW(15), 0)
USER_FUNC(btlevtcmd_GetPos, -2, LW(0), LW(1), LW(2))
USER_FUNC(btlevtcmd_GetResultPrizeLv, -1, LW(13), LW(11))
USER_FUNC(btlevtcmd_ACSuccessEffect, LW(11), LW(0), LW(1), LW(2))
USER_FUNC(btlevtcmd_AudienceDeclareACResult, LW(12), LW(11))
ELSE()
USER_FUNC(btlevtcmd_AudienceDeclareACResult, LW(12), -1)
END_IF()
END_IF()
LBL(80)
USER_FUNC(evt_btl_camera_set_mode, 0, 0)
USER_FUNC(evt_btl_camera_set_moveSpeedLv, 0, 1)
USER_FUNC(btlevtcmd_ResetFaceDirection, -2)
USER_FUNC(btlevtcmd_AnimeChangePose, -2, 1, PTR("PCH_B_1"))
USER_FUNC(btlevtcmd_GetPos, -2, LW(0), LW(1), LW(2))
USER_FUNC(btlevtcmd_FaceDirectionSub, -2, LW(0), 80)
USER_FUNC(btlevtcmd_SetFallAccel, -2, FLOAT(0.15))
BROTHER_EVT()
USER_FUNC(btlevtcmd_snd_se, -2, PTR("SFX_BTL_CHURINA_CONFUSE1_2"), EVT_NULLPTR, 0, EVT_NULLPTR)
USER_FUNC(btlevtcmd_SetRotateOffset, -2, 0, 5, 0)
USER_FUNC(btlevtcmd_GetFaceDirection, -2, LW(5))
MUL(LW(5), 9)
DO(40)
USER_FUNC(btlevtcmd_AddRotate, -2, 0, 0, LW(5))
WAIT_FRM(1)
WHILE()
USER_FUNC(btlevtcmd_GetFaceDirection, -2, LW(5))
MUL(LW(5), 36)
DO(20)
USER_FUNC(btlevtcmd_AddRotate, -2, 0, 0, LW(5))
WAIT_FRM(1)
WHILE()
USER_FUNC(btlevtcmd_SetRotate, -2, 0, 0, 0)
END_BROTHER()
IF_EQUAL((int32_t)GSW_Battle_DooplissMove, 0)
BROTHER_EVT()
USER_FUNC(btlevtcmd_ACRStart, -2, 40, 59, 59, 0)
END_BROTHER()
USER_FUNC(btlevtcmd_JumpPosition, -2, LW(0), LW(1), LW(2), 60, -1)
USER_FUNC(btlevtcmd_ACRGetResult, LW(6), LW(7))
ELSE()
SET(LW(6), 0)
END_IF()
SWITCH(LW(6))
CASE_LARGE_EQUAL(2)
USER_FUNC(evtTot_LogActiveMoveStylish, 0)
USER_FUNC(btlevtcmd_AudienceDeclareAcrobatResult, LW(12), 1, 0, 0, 0)
USER_FUNC(btlevtcmd_AnimeChangePose, -2, 1, PTR("PCH_Y_1"))
USER_FUNC(btlevtcmd_AnimeWaitPlayComplete, -2, 1)
WAIT_MSEC(300)
USER_FUNC(evt_audience_ap_recovery)
USER_FUNC(btlevtcmd_InviteApInfoReport)
USER_FUNC(evt_btl_camera_set_mode, 0, 0)
USER_FUNC(evt_btl_camera_set_moveSpeedLv, 0, 1)
USER_FUNC(btlevtcmd_AnimeChangePoseType, -2, 1, 42)
USER_FUNC(btlevtcmd_AddRotate, -2, 0, 180, 0)
USER_FUNC(btlevtcmd_GetHomePos, -2, LW(0), LW(1), LW(2))
USER_FUNC(btlevtcmd_DivePosition, -2, LW(0), LW(1), LW(2), 0, 0, 2, 0, -1)
USER_FUNC(btlevtcmd_SetRotate, -2, 0, 0, 0)
CASE_ETC()
USER_FUNC(btlevtcmd_SetRotate, -2, 0, 0, 0)
IF_EQUAL((int32_t)GSW_Battle_DooplissMove, 0)
USER_FUNC(evt_audience_acrobat_notry)
USER_FUNC(evt_audience_ap_recovery)
USER_FUNC(btlevtcmd_InviteApInfoReport)
END_IF()
USER_FUNC(evt_btl_camera_set_mode, 0, 0)
USER_FUNC(evt_btl_camera_set_moveSpeedLv, 0, 1)
USER_FUNC(btlevtcmd_AnimeChangePose, -2, 1, PTR("PCH_R_2"))
USER_FUNC(btlevtcmd_AddRotate, -2, 0, 180, 0)
USER_FUNC(btlevtcmd_GetHomePos, -2, LW(0), LW(1), LW(2))
USER_FUNC(btlevtcmd_DivePosition, -2, LW(0), LW(1), LW(2), 0, 0, 2, 0, -1)
USER_FUNC(btlevtcmd_SetRotate, -2, 0, 0, 0)
END_SWITCH()
LBL(99)
USER_FUNC(btlevtcmd_ResetFaceDirection, -2)
RUN_CHILD_EVT(PTR(&btldefaultevt_SuitoruBadgeEffect))
USER_FUNC(btlevtcmd_SetWalkSound, -2, PTR("SFX_PARTY_BATTLE_MOVE1L"), PTR("SFX_PARTY_BATTLE_MOVE1R"), 0, 15, 13)
USER_FUNC(btlevtcmd_SetRunSound, -2, PTR("SFX_PARTY_BATTLE_MOVE1L"), PTR("SFX_PARTY_BATTLE_MOVE1R"), 0, 7, 7)
USER_FUNC(btlevtcmd_SetDiveSound, -2, PTR("SFX_PARTY_BATTLE_MOVE1L"), PTR("SFX_PARTY_BATTLE_MOVE1R"), 0, 7, 7)
USER_FUNC(btlevtcmd_SetJumpSound, -2, PTR("SFX_PARTY_BATTLE_JUMP1"), PTR("SFX_PARTY_BATTLE_LANDING1"))
USER_FUNC(btlevtcmd_StartWaitEvent, -2)
RETURN()
EVT_END()
// HP Healing variant of Smooch (no longer in use).
/*
EVT_BEGIN(partyChuchurinaAttack_Kiss)
USER_FUNC(btlevtcmd_GetSelectEnemy, LW(3), LW(4))
IF_EQUAL(LW(3), -1)
GOTO(99)
END_IF()
USER_FUNC(btlevtcmd_CommandGetWeaponAddress, -2, LW(12))
USER_FUNC(btlevtcmd_WeaponAftereffect, LW(12))
USER_FUNC(btlevtcmd_CommandPayWeaponCost, -2)
USER_FUNC(btlevtcmd_RunDataEventChild, -2, 7)
USER_FUNC(evt_btl_camera_set_mode, 0, 7)
USER_FUNC(evt_btl_camera_set_homing_unit, 0, -2, -2)
USER_FUNC(evt_btl_camera_set_moveSpeedLv, 0, 1)
USER_FUNC(evt_btl_camera_set_zoom, 0, 250)
USER_FUNC(btlevtcmd_GetUnitId, -2, LW(0))
IF_NOT_EQUAL(LW(0), LW(3))
USER_FUNC(btlevtcmd_CalculateFaceDirection, -2, -1, LW(3), LW(4), 16, LW(15))
USER_FUNC(btlevtcmd_ChangeFaceDirection, -2, LW(15))
END_IF()
RUN_CHILD_EVT(PTR(&unk_evt_803537c4))
IF_NOT_EQUAL(LW(0), 0)
USER_FUNC(btlevtcmd_CalculateFaceDirection, LW(3), LW(4), -2, -1, 16, LW(15))
USER_FUNC(btlevtcmd_ChangeFaceDirection, LW(3), LW(15))
END_IF()
USER_FUNC(btlevtcmd_CommandGetWeaponActionLv, LW(0))
USER_FUNC(btlevtcmd_AcSetDifficulty, -2, LW(0))
USER_FUNC(btlevtcmd_AcGetDifficulty, LW(0))
SUB(LW(0), 3)
SWITCH(LW(0))
CASE_SMALL_EQUAL(-3)
SET(LW(0), 300)
SET(LW(1), 20)
SET(LW(2), 20)
CASE_EQUAL(-2)
SET(LW(0), 270)
SET(LW(1), 18)
SET(LW(2), 22)
CASE_EQUAL(-1)
SET(LW(0), 240)
SET(LW(1), 17)
SET(LW(2), 24)
CASE_EQUAL(0)
SET(LW(0), 210)
SET(LW(1), 16)
SET(LW(2), 25)
CASE_EQUAL(1)
SET(LW(0), 195)
SET(LW(1), 14)
SET(LW(2), 26)
CASE_EQUAL(2)
SET(LW(0), 180)
SET(LW(1), 13)
SET(LW(2), 27)
CASE_ETC()
SET(LW(0), 150)
SET(LW(1), 12)
SET(LW(2), 30)
END_SWITCH()
// Change gauge parameters based on move level.
// Heal up to 5, 10, 15 HP with a full bar.
USER_FUNC(evtTot_GetMoveSelectedLevel, MoveType::MOWZ_SMOOCH, LW(6))
SWITCH(LW(6))
CASE_EQUAL(1)
USER_FUNC(btlevtcmd_AcSetParamAll, 11, LW(0), 178, LW(1), LW(2), 20, 100, EVT_NULLPTR)
USER_FUNC(btlevtcmd_AcSetGaugeParam, 100, 100, 100, 100)
CASE_EQUAL(2)
USER_FUNC(btlevtcmd_AcSetParamAll, 11, LW(0), 178, LW(1), LW(2), 10, 50, EVT_NULLPTR)
USER_FUNC(btlevtcmd_AcSetGaugeParam, 50, 100, 100, 100)
CASE_ETC()
USER_FUNC(btlevtcmd_AcSetParamAll, 11, LW(0), 178, LW(1), LW(2), 7, 36, EVT_NULLPTR)
USER_FUNC(btlevtcmd_AcSetGaugeParam, 35, 70, 100, 100)
END_SWITCH()
// Disable the vanilla 1 HP base.
USER_FUNC(btlevtcmd_AcSetFlag, 1)
USER_FUNC(btlevtcmd_SetupAC, -2, 6, 1, 0)
WAIT_FRM(22)
USER_FUNC(btlevtcmd_StartAC, 1)
BROTHER_EVT()
USER_FUNC(btlevtcmd_AnimeChangePoseType, -2, 1, 40)
USER_FUNC(btlevtcmd_GetStatusMg, -2, LW(6))
USER_FUNC(btlevtcmd_GetStatusMg, LW(3), LW(7))
MULF(LW(6), 12)
MULF(LW(7), 7)
USER_FUNC(btlevtcmd_GetPos, LW(3), LW(0), LW(1), LW(2))
USER_FUNC(btlevtcmd_FaceDirectionAdd, LW(3), LW(0), LW(6))
USER_FUNC(btlevtcmd_FaceDirectionAdd, LW(3), LW(0), LW(7))
USER_FUNC(btlevtcmd_MovePosition, -2, LW(0), LW(1), LW(2), 235, -1, 0)
USER_FUNC(btlevtcmd_CalculateFaceDirection, -2, -1, LW(3), LW(4), 16, LW(15))
USER_FUNC(btlevtcmd_ChangeFaceDirection, -2, LW(15))
END_BROTHER()
USER_FUNC(btlevtcmd_ResultAC)
USER_FUNC(btlevtcmd_AcGetOutputParam, 2, LW(5))
// Action command success: 5 - Nice, 10 - Good, 15 - Great.
SWITCH(LW(5))
CASE_LARGE_EQUAL(15)
SET(LW(5), 2)
CASE_LARGE_EQUAL(10)
SET(LW(5), 1)
CASE_LARGE_EQUAL(5)
SET(LW(5), 0)
CASE_ETC()
SET(LW(5), -1)
END_SWITCH()
IF_LARGE_EQUAL(LW(5), 0)
USER_FUNC(btlevtcmd_GetPos, -2, LW(0), LW(1), LW(2))
USER_FUNC(btlevtcmd_GetResultPrizeLv, -5, LW(5), LW(6))
USER_FUNC(btlevtcmd_ACSuccessEffect, LW(6), LW(0), LW(1), LW(2))
USER_FUNC(btlevtcmd_AudienceDeclareACResult, LW(12), LW(6))
ELSE()
USER_FUNC(btlevtcmd_AudienceDeclareACResult, LW(12), -1)
END_IF()
USER_FUNC(btlevtcmd_GetResultAC, LW(6))
USER_FUNC(btlevtcmd_StopAC)
USER_FUNC(evt_btl_camera_set_moveSpeedLv, 0, 2)
USER_FUNC(evt_btl_camera_set_zoom, 0, 350)
USER_FUNC(btlevtcmd_AnimeChangePose, -2, 1, PTR("PCH_K_1"))
WAIT_FRM(6)
IF_LARGE_EQUAL(LW(5), 0)
RUN_CHILD_EVT(PTR(&unk_evt_803537c4))
IF_NOT_EQUAL(LW(0), 0)
USER_FUNC(btlevtcmd_AnimeChangePoseType, LW(3), LW(4), 59)
END_IF()
END_IF()
USER_FUNC(btlevtcmd_GetStatusMg, -2, LW(6))
MULF(LW(6), 16)
USER_FUNC(btlevtcmd_GetPos, -2, LW(0), LW(1), LW(2))
USER_FUNC(btlevtcmd_FaceDirectionAdd, -2, LW(0), LW(6))
USER_FUNC(btlevtcmd_GetStatusMg, -2, LW(6))
MULF(LW(6), 40)
ADD(LW(1), LW(6))
USER_FUNC(btlevtcmd_GetFaceDirection, LW(3), LW(6))
MUL(LW(6), 45)
USER_FUNC(evt_eff, 0, PTR("kiss"), 0, LW(0), LW(1), LW(2), LW(6), 0, 0, 0, 0, 0, 0, 0)
USER_FUNC(btlevtcmd_snd_se, -2, PTR("SFX_BTL_CHURINA_KISS1"), EVT_NULLPTR, 0, EVT_NULLPTR)
WAIT_FRM(40)
DIV(LW(6), 5)
// Heal target (Mario).
USER_FUNC(btlevtcmd_GetPartsPos, LW(3), LW(4), LW(12), LW(13), LW(14))
USER_FUNC(btlevtcmd_GetHeight, LW(3), LW(5))
USER_FUNC(btlevtcmd_GetStatusMg, LW(3), LW(7))
MULF(LW(5), LW(7))
ADD(LW(13), LW(5))
SUB(LW(12), LW(6)) // move hearts apart in X dir; only if healing both
USER_FUNC(btlevtcmd_AcGetOutputParam, 2, LW(5))
USER_FUNC(evt_eff, PTR("eff"), PTR("recovery"), 0, LW(12), LW(13), LW(14), LW(5), 0, 0, 0, 0, 0, 0, 0)
INLINE_EVT_ID(LW(15))
WAIT_FRM(120)
USER_FUNC(btlevtcmd_RecoverHp, LW(3), LW(4), LW(5))
END_INLINE()
// Also heal self.
USER_FUNC(btlevtcmd_GetPartsPos, -2, 1, LW(12), LW(13), LW(14))
USER_FUNC(btlevtcmd_GetHeight, LW(3), LW(5))
USER_FUNC(btlevtcmd_GetStatusMg, LW(3), LW(7))
MULF(LW(5), LW(7))
ADD(LW(13), LW(5))
SUB(LW(14), 10) // to prevent z-fighting
ADD(LW(12), LW(6)) // move hearts apart in X dir; only if healing both
USER_FUNC(btlevtcmd_AcGetOutputParam, 2, LW(5))
USER_FUNC(evt_eff, PTR("eff"), PTR("recovery"), 0, LW(12), LW(13), LW(14), LW(5), 0, 0, 0, 0, 0, 0, 0)
INLINE_EVT_ID(LW(15))
WAIT_FRM(120)
USER_FUNC(btlevtcmd_RecoverHp, -2, 1, LW(5))
END_INLINE()
USER_FUNC(btlevtcmd_ACRStart, -2, 0, 15, 15, 20)
USER_FUNC(btlevtcmd_ACRGetResult, LW(6), LW(7))
SWITCH(LW(6))
CASE_LARGE_EQUAL(2)
USER_FUNC(evtTot_LogActiveMoveStylish, 0)
USER_FUNC(btlevtcmd_CommandGetWeaponAddress, -2, LW(12))
USER_FUNC(btlevtcmd_AudienceDeclareAcrobatResult, LW(12), 1, 0, 0, 0)
USER_FUNC(btlevtcmd_AnimeChangePose, -2, 1, PTR("PCH_Y_1"))
USER_FUNC(btlevtcmd_AnimeWaitPlayComplete, -2, 1)
USER_FUNC(btlevtcmd_AnimeChangePoseType, -2, 1, 43)
WAIT_MSEC(300)
CASE_ETC()
USER_FUNC(evt_audience_acrobat_notry)
END_SWITCH()
USER_FUNC(btlevtcmd_WaitEventEnd, LW(15))
USER_FUNC(evt_btl_camera_set_mode, 0, 0)
USER_FUNC(evt_btl_camera_set_moveSpeedLv, 0, 1)
USER_FUNC(evt_audience_ap_recovery)
USER_FUNC(btlevtcmd_InviteApInfoReport)
RUN_CHILD_EVT(PTR(&unk_evt_803537c4))
IF_NOT_EQUAL(LW(0), 0)
USER_FUNC(btlevtcmd_ResetFaceDirection, LW(3))
USER_FUNC(btlevtcmd_StartWaitEvent, LW(3))
END_IF()
USER_FUNC(btlevtcmd_AnimeChangePoseType, -2, 1, 42)
USER_FUNC(btlevtcmd_GetHomePos, -2, LW(0), LW(1), LW(2))
USER_FUNC(btlevtcmd_SetMoveSpeed, -2, FLOAT(4.0))
USER_FUNC(btlevtcmd_MovePosition, -2, LW(0), LW(1), LW(2), 0, -1, 0)
USER_FUNC(btlevtcmd_ResetFaceDirection, -2)
USER_FUNC(btlevtcmd_StartWaitEvent, -2)
RETURN()
EVT_END()
*/
// Regen-status variant of Smooch.
EVT_BEGIN(partyChuchurinaAttack_Kiss)
USER_FUNC(btlevtcmd_GetSelectEnemy, LW(3), LW(4))
IF_EQUAL(LW(3), -1)
GOTO(99)
END_IF()
USER_FUNC(btlevtcmd_CommandGetWeaponAddress, -2, LW(12))
USER_FUNC(btlevtcmd_WeaponAftereffect, LW(12))
USER_FUNC(btlevtcmd_CommandPayWeaponCost, -2)
USER_FUNC(btlevtcmd_RunDataEventChild, -2, 7)
USER_FUNC(evt_btl_camera_set_mode, 0, 7)
USER_FUNC(evt_btl_camera_set_homing_unit, 0, -2, -2)
USER_FUNC(evt_btl_camera_set_moveSpeedLv, 0, 1)
USER_FUNC(evt_btl_camera_set_zoom, 0, 250)
USER_FUNC(btlevtcmd_GetUnitId, -2, LW(0))
IF_NOT_EQUAL(LW(0), LW(3))
USER_FUNC(btlevtcmd_CalculateFaceDirection, -2, -1, LW(3), LW(4), 16, LW(15))
USER_FUNC(btlevtcmd_ChangeFaceDirection, -2, LW(15))
END_IF()
RUN_CHILD_EVT(PTR(&unk_evt_803537c4))
IF_NOT_EQUAL(LW(0), 0)
USER_FUNC(btlevtcmd_CalculateFaceDirection, LW(3), LW(4), -2, -1, 16, LW(15))
USER_FUNC(btlevtcmd_ChangeFaceDirection, LW(3), LW(15))
END_IF()
USER_FUNC(btlevtcmd_CommandGetWeaponActionLv, LW(0))
USER_FUNC(btlevtcmd_AcSetDifficulty, -2, LW(0))
USER_FUNC(btlevtcmd_AcGetDifficulty, LW(0))
SUB(LW(0), 3)
SWITCH(LW(0))
CASE_SMALL_EQUAL(-3)
SET(LW(0), 300)
SET(LW(1), 20)
SET(LW(2), 20)
CASE_EQUAL(-2)
SET(LW(0), 270)
SET(LW(1), 18)
SET(LW(2), 22)
CASE_EQUAL(-1)
SET(LW(0), 240)
SET(LW(1), 17)
SET(LW(2), 24)
CASE_EQUAL(0)
SET(LW(0), 210)
SET(LW(1), 16)
SET(LW(2), 25)
CASE_EQUAL(1)
SET(LW(0), 195)
SET(LW(1), 14)
SET(LW(2), 26)
CASE_EQUAL(2)
SET(LW(0), 180)
SET(LW(1), 13)
SET(LW(2), 27)
CASE_ETC()
SET(LW(0), 150)
SET(LW(1), 12)
SET(LW(2), 30)
END_SWITCH()
// Bar has three divisions; hitting 1/3, 2/3, 3/3 should give 1, 2, 3 turns.
USER_FUNC(btlevtcmd_AcSetParamAll, 11, LW(0), 178, LW(1), LW(2), 33, 34, EVT_NULLPTR)
USER_FUNC(btlevtcmd_AcSetGaugeParam, 34, 68, 100, 100)
// Disable the vanilla 1 base.
USER_FUNC(btlevtcmd_AcSetFlag, 1)
USER_FUNC(btlevtcmd_SetupAC, -2, 6, 1, 0)
WAIT_FRM(22)
USER_FUNC(btlevtcmd_StartAC, 1)
BROTHER_EVT()
USER_FUNC(btlevtcmd_AnimeChangePoseType, -2, 1, 40)
USER_FUNC(btlevtcmd_GetStatusMg, -2, LW(6))
USER_FUNC(btlevtcmd_GetStatusMg, LW(3), LW(7))
MULF(LW(6), 12)
MULF(LW(7), 7)
USER_FUNC(btlevtcmd_GetPos, LW(3), LW(0), LW(1), LW(2))
USER_FUNC(btlevtcmd_FaceDirectionAdd, LW(3), LW(0), LW(6))
USER_FUNC(btlevtcmd_FaceDirectionAdd, LW(3), LW(0), LW(7))
USER_FUNC(btlevtcmd_MovePosition, -2, LW(0), LW(1), LW(2), 235, -1, 0)
USER_FUNC(btlevtcmd_CalculateFaceDirection, -2, -1, LW(3), LW(4), 16, LW(15))
USER_FUNC(btlevtcmd_ChangeFaceDirection, -2, LW(15))
END_BROTHER()
USER_FUNC(btlevtcmd_ResultAC)
// Action command success level - subtract two from ac result (1 - 4).
USER_FUNC(btlevtcmd_AcGetOutputParam, 2, LW(5))
SUB(LW(5), 2)
IF_SMALL(LW(5), 0)
SET(LW(5), -1)
END_IF()
IF_LARGE_EQUAL(LW(5), 0)
USER_FUNC(btlevtcmd_GetPos, -2, LW(0), LW(1), LW(2))
USER_FUNC(btlevtcmd_GetResultPrizeLv, -5, LW(5), LW(6))
USER_FUNC(btlevtcmd_ACSuccessEffect, LW(6), LW(0), LW(1), LW(2))
USER_FUNC(btlevtcmd_AudienceDeclareACResult, LW(12), LW(6))
ELSE()
USER_FUNC(btlevtcmd_AudienceDeclareACResult, LW(12), -1)
END_IF()
USER_FUNC(btlevtcmd_GetResultAC, LW(6))
USER_FUNC(btlevtcmd_StopAC)
USER_FUNC(evt_btl_camera_set_moveSpeedLv, 0, 2)
USER_FUNC(evt_btl_camera_set_zoom, 0, 350)
USER_FUNC(btlevtcmd_AnimeChangePose, -2, 1, PTR("PCH_K_1"))
WAIT_FRM(6)
IF_LARGE_EQUAL(LW(5), 0)
RUN_CHILD_EVT(PTR(&unk_evt_803537c4))
IF_NOT_EQUAL(LW(0), 0)
USER_FUNC(btlevtcmd_AnimeChangePoseType, LW(3), LW(4), 59)
END_IF()
END_IF()
USER_FUNC(btlevtcmd_GetStatusMg, -2, LW(6))
MULF(LW(6), 16)
USER_FUNC(btlevtcmd_GetPos, -2, LW(0), LW(1), LW(2))
USER_FUNC(btlevtcmd_FaceDirectionAdd, -2, LW(0), LW(6))
USER_FUNC(btlevtcmd_GetStatusMg, -2, LW(6))
MULF(LW(6), 40)
ADD(LW(1), LW(6))
USER_FUNC(btlevtcmd_GetFaceDirection, LW(3), LW(6))
MUL(LW(6), 45)
USER_FUNC(evt_eff, 0, PTR("kiss"), 0, LW(0), LW(1), LW(2), LW(6), 0, 0, 0, 0, 0, 0, 0)
USER_FUNC(btlevtcmd_snd_se, -2, PTR("SFX_BTL_CHURINA_KISS1"), EVT_NULLPTR, 0, EVT_NULLPTR)
WAIT_FRM(40)
DIV(LW(6), 5)
// Apply statuses based on level.
IF_LARGE_EQUAL(LW(5), 0)
ADD(LW(5), 1)
USER_FUNC(evtTot_GetMoveSelectedLevel, MoveType::MOWZ_SMOOCH, LW(6))
USER_FUNC(evtTot_MakeSmoochWeapon, LW(12), LW(6), LW(5))
USER_FUNC(btlevtcmd_CheckDamage, -2, LW(3), LW(4), LW(12), 256, LW(5))
// For level 3 only, add "SP regen" effect / text.
IF_LARGE_EQUAL(LW(6), 3)
USER_FUNC(btlevtcmd_GetPos, LW(3), LW(0), LW(1), LW(2))
USER_FUNC(evt_eff, PTR(""), PTR("stardust"), 2, LW(0), LW(1), LW(2), 50, 50, 50, 100, 0, 0, 0, 0)
USER_FUNC(patch::battle::evtTot_ApplyCustomStatus,
LW(3), LW(4), 0,
/* splash colors */ 0xccf4ff, 0xffa0ff,
PTR("SFX_CONDITION_REST_HP_SLOW1"),
PTR("tot_sp_regen_effect"))
END_IF()
END_IF()
USER_FUNC(btlevtcmd_ACRStart, -2, 0, 15, 15, 20)
USER_FUNC(btlevtcmd_ACRGetResult, LW(6), LW(7))
SWITCH(LW(6))
CASE_LARGE_EQUAL(2)
USER_FUNC(evtTot_LogActiveMoveStylish, 0)
USER_FUNC(btlevtcmd_CommandGetWeaponAddress, -2, LW(12))
USER_FUNC(btlevtcmd_AudienceDeclareAcrobatResult, LW(12), 1, 0, 0, 0)
USER_FUNC(btlevtcmd_AnimeChangePose, -2, 1, PTR("PCH_Y_1"))
USER_FUNC(btlevtcmd_AnimeWaitPlayComplete, -2, 1)
USER_FUNC(btlevtcmd_AnimeChangePoseType, -2, 1, 43)
WAIT_MSEC(300)
CASE_ETC()
USER_FUNC(evt_audience_acrobat_notry)
END_SWITCH()
USER_FUNC(btlevtcmd_WaitEventEnd, LW(15))
USER_FUNC(evt_btl_camera_set_mode, 0, 0)
USER_FUNC(evt_btl_camera_set_moveSpeedLv, 0, 1)
USER_FUNC(evt_audience_ap_recovery)
USER_FUNC(btlevtcmd_InviteApInfoReport)
RUN_CHILD_EVT(PTR(&unk_evt_803537c4))
IF_NOT_EQUAL(LW(0), 0)
USER_FUNC(btlevtcmd_ResetFaceDirection, LW(3))
USER_FUNC(btlevtcmd_StartWaitEvent, LW(3))
END_IF()
USER_FUNC(btlevtcmd_AnimeChangePoseType, -2, 1, 42)
USER_FUNC(btlevtcmd_GetHomePos, -2, LW(0), LW(1), LW(2))
USER_FUNC(btlevtcmd_SetMoveSpeed, -2, FLOAT(4.0))
USER_FUNC(btlevtcmd_MovePosition, -2, LW(0), LW(1), LW(2), 0, -1, 0)
USER_FUNC(btlevtcmd_ResetFaceDirection, -2)
USER_FUNC(btlevtcmd_StartWaitEvent, -2)
RETURN()
EVT_END()
BattleWeapon customWeapon_MowzLoveSlapL = {
.name = "btl_wn_pcr_normal",
.icon = IconType::PARTNER_MOVE_0,
.item_id = 0,
.description = "msg_pch_binta",
.base_accuracy = 100,
.base_fp_cost = 0,
.base_sp_cost = 0,
.superguards_allowed = 1,
.unk_14 = 1.0,
.stylish_multiplier = 1,
.unk_19 = 1,
.bingo_card_chance = 100,
.unk_1b = 50,
.damage_function = (void*)weaponGetPowerDefault,
.damage_function_params = { 1, 0, 0, 0, 0, 0, 0, 0 },
.fp_damage_function = nullptr,
.fp_damage_function_params = { 0, 0, 0, 0, 0, 0, 0, 0 },
.target_class_flags =
AttackTargetClass_Flags::SINGLE_TARGET |
AttackTargetClass_Flags::ONLY_TARGET_PREFERRED_PARTS |
AttackTargetClass_Flags::CANNOT_TARGET_SELF |
AttackTargetClass_Flags::CANNOT_TARGET_SAME_ALLIANCE |
AttackTargetClass_Flags::CANNOT_TARGET_SYSTEM_UNITS |
AttackTargetClass_Flags::CANNOT_TARGET_TREE_OR_SWITCH,
.target_property_flags =
AttackTargetProperty_Flags::TARGET_OPPOSING_ALLIANCE_DIR |
AttackTargetProperty_Flags::ONLY_FRONT |
AttackTargetProperty_Flags::HAMMERLIKE,
.element = AttackElement::NORMAL,
.damage_pattern = 0x15,
.weapon_ac_level = 3,
.unk_6f = 2,
.ac_help_msg = "msg_ac_binta",
.special_property_flags =
AttackSpecialProperty_Flags::TOT_PARTY_UNGUARDABLE |
AttackSpecialProperty_Flags::USABLE_IF_CONFUSED |
AttackSpecialProperty_Flags::GROUNDS_WINGED |
AttackSpecialProperty_Flags::DEFENSE_PIERCING |
AttackSpecialProperty_Flags::DIMINISHING_BY_HIT |
AttackSpecialProperty_Flags::ALL_BUFFABLE,
// Removed Payback, added Front-spiky.
.counter_resistance_flags =
AttackCounterResistance_Flags::TOP_SPIKY |
AttackCounterResistance_Flags::FRONT_SPIKY,
.target_weighting_flags =
AttackTargetWeighting_Flags::WEIGHTED_RANDOM |
AttackTargetWeighting_Flags::UNKNOWN_0x2000 |
AttackTargetWeighting_Flags::PREFER_FRONT,
// status chances
.attack_evt_code = (void*)partyChuchurinaAttack_NormalAttack,
.bg_a1_a2_fall_weight = 0,
.bg_a1_fall_weight = 0,
.bg_a2_fall_weight = 0,
.bg_no_a_fall_weight = 100,
.bg_b_fall_weight = 0,
.nozzle_turn_chance = 4,
.nozzle_fire_chance = 3,
.ceiling_fall_chance = 0,
.object_fall_chance = 0,
};
BattleWeapon customWeapon_MowzLoveSlapR = {
.name = "btl_wn_pcr_normal",
.icon = IconType::PARTNER_MOVE_0,
.item_id = 0,
.description = "msg_pch_binta",
.base_accuracy = 100,
.base_fp_cost = 0,
.base_sp_cost = 0,
.superguards_allowed = 1,
.unk_14 = 1.0,
.stylish_multiplier = 1,
.unk_19 = 1,
.bingo_card_chance = 100,
.unk_1b = 50,
.damage_function = (void*)weaponGetPowerDefault,
.damage_function_params = { 1, 0, 0, 0, 0, 0, 0, 0 },
.fp_damage_function = nullptr,
.fp_damage_function_params = { 0, 0, 0, 0, 0, 0, 0, 0 },
.target_class_flags =
AttackTargetClass_Flags::SINGLE_TARGET |
AttackTargetClass_Flags::ONLY_TARGET_PREFERRED_PARTS |
AttackTargetClass_Flags::CANNOT_TARGET_SELF |
AttackTargetClass_Flags::CANNOT_TARGET_SAME_ALLIANCE |
AttackTargetClass_Flags::CANNOT_TARGET_SYSTEM_UNITS |
AttackTargetClass_Flags::CANNOT_TARGET_TREE_OR_SWITCH,
.target_property_flags =
AttackTargetProperty_Flags::TARGET_OPPOSING_ALLIANCE_DIR |
AttackTargetProperty_Flags::ONLY_FRONT |
AttackTargetProperty_Flags::HAMMERLIKE,
.element = AttackElement::NORMAL,
.damage_pattern = 0x16,
.weapon_ac_level = 3,
.unk_6f = 2,
.ac_help_msg = "msg_ac_binta",
.special_property_flags =
AttackSpecialProperty_Flags::TOT_PARTY_UNGUARDABLE |
AttackSpecialProperty_Flags::USABLE_IF_CONFUSED |
AttackSpecialProperty_Flags::GROUNDS_WINGED |
AttackSpecialProperty_Flags::DEFENSE_PIERCING |
AttackSpecialProperty_Flags::DIMINISHING_BY_HIT |
AttackSpecialProperty_Flags::ALL_BUFFABLE,
// Removed Payback, added Front-spiky.
.counter_resistance_flags =
AttackCounterResistance_Flags::TOP_SPIKY |
AttackCounterResistance_Flags::FRONT_SPIKY,
.target_weighting_flags =
AttackTargetWeighting_Flags::WEIGHTED_RANDOM |
AttackTargetWeighting_Flags::UNKNOWN_0x2000 |
AttackTargetWeighting_Flags::PREFER_FRONT,
// status chances
.attack_evt_code = (void*)partyChuchurinaAttack_NormalAttack,
.bg_a1_a2_fall_weight = 0,
.bg_a1_fall_weight = 0,
.bg_a2_fall_weight = 0,
.bg_no_a_fall_weight = 100,
.bg_b_fall_weight = 0,
.nozzle_turn_chance = 4,
.nozzle_fire_chance = 3,
.ceiling_fall_chance = 0,
.object_fall_chance = 0,
};
BattleWeapon customWeapon_MowzLoveSlapLFinal = {
.name = "btl_wn_pcr_normal",
.icon = IconType::PARTNER_MOVE_0,
.item_id = 0,
.description = "msg_pch_binta",
.base_accuracy = 100,
.base_fp_cost = 0,
.base_sp_cost = 0,
.superguards_allowed = 1,
.unk_14 = 1.0,
.stylish_multiplier = 1,
.unk_19 = 1,
.bingo_card_chance = 100,
.unk_1b = 50,
.damage_function = (void*)weaponGetPowerDefault,
.damage_function_params = { 1, 0, 0, 0, 0, 0, 0, 0 },
.fp_damage_function = nullptr,
.fp_damage_function_params = { 0, 0, 0, 0, 0, 0, 0, 0 },
.target_class_flags =
AttackTargetClass_Flags::SINGLE_TARGET |
AttackTargetClass_Flags::ONLY_TARGET_PREFERRED_PARTS |
AttackTargetClass_Flags::CANNOT_TARGET_SELF |
AttackTargetClass_Flags::CANNOT_TARGET_SAME_ALLIANCE |
AttackTargetClass_Flags::CANNOT_TARGET_SYSTEM_UNITS |
AttackTargetClass_Flags::CANNOT_TARGET_TREE_OR_SWITCH,
.target_property_flags =
AttackTargetProperty_Flags::TARGET_OPPOSING_ALLIANCE_DIR |
AttackTargetProperty_Flags::ONLY_FRONT |
AttackTargetProperty_Flags::HAMMERLIKE,
.element = AttackElement::NORMAL,
.damage_pattern = 0x17,
.weapon_ac_level = 3,
.unk_6f = 2,
.ac_help_msg = "msg_ac_binta",
.special_property_flags =
AttackSpecialProperty_Flags::TOT_PARTY_UNGUARDABLE |
AttackSpecialProperty_Flags::USABLE_IF_CONFUSED |
AttackSpecialProperty_Flags::GROUNDS_WINGED |
AttackSpecialProperty_Flags::DEFENSE_PIERCING |
AttackSpecialProperty_Flags::DIMINISHING_BY_HIT |
AttackSpecialProperty_Flags::ALL_BUFFABLE,
// Removed Payback, added Front-spiky.
.counter_resistance_flags =
AttackCounterResistance_Flags::TOP_SPIKY |
AttackCounterResistance_Flags::FRONT_SPIKY,
.target_weighting_flags =
AttackTargetWeighting_Flags::WEIGHTED_RANDOM |
AttackTargetWeighting_Flags::UNKNOWN_0x2000 |
AttackTargetWeighting_Flags::PREFER_FRONT,
// status chances
.attack_evt_code = (void*)partyChuchurinaAttack_NormalAttack,
.bg_a1_a2_fall_weight = 0,
.bg_a1_fall_weight = 0,
.bg_a2_fall_weight = 0,
.bg_no_a_fall_weight = 100,
.bg_b_fall_weight = 0,
.nozzle_turn_chance = 4,
.nozzle_fire_chance = 2,
.ceiling_fall_chance = 0,
.object_fall_chance = 0,
};
BattleWeapon customWeapon_MowzLoveSlapRFinal = {
.name = "btl_wn_pcr_normal",
.icon = IconType::PARTNER_MOVE_0,
.item_id = 0,
.description = "msg_pch_binta",
.base_accuracy = 100,
.base_fp_cost = 0,
.base_sp_cost = 0,
.superguards_allowed = 1,
.unk_14 = 1.0,
.stylish_multiplier = 1,
.unk_19 = 1,
.bingo_card_chance = 100,
.unk_1b = 50,
.damage_function = (void*)weaponGetPowerDefault,
.damage_function_params = { 1, 0, 0, 0, 0, 0, 0, 0 },
.fp_damage_function = nullptr,
.fp_damage_function_params = { 0, 0, 0, 0, 0, 0, 0, 0 },
.target_class_flags =
AttackTargetClass_Flags::SINGLE_TARGET |
AttackTargetClass_Flags::ONLY_TARGET_PREFERRED_PARTS |
AttackTargetClass_Flags::CANNOT_TARGET_SELF |
AttackTargetClass_Flags::CANNOT_TARGET_SAME_ALLIANCE |
AttackTargetClass_Flags::CANNOT_TARGET_SYSTEM_UNITS |
AttackTargetClass_Flags::CANNOT_TARGET_TREE_OR_SWITCH,
.target_property_flags =
AttackTargetProperty_Flags::TARGET_OPPOSING_ALLIANCE_DIR |
AttackTargetProperty_Flags::ONLY_FRONT |
AttackTargetProperty_Flags::HAMMERLIKE,
.element = AttackElement::NORMAL,
.damage_pattern = 0x18,
.weapon_ac_level = 3,
.unk_6f = 2,
.ac_help_msg = "msg_ac_binta",
.special_property_flags =
AttackSpecialProperty_Flags::TOT_PARTY_UNGUARDABLE |
AttackSpecialProperty_Flags::USABLE_IF_CONFUSED |
AttackSpecialProperty_Flags::GROUNDS_WINGED |
AttackSpecialProperty_Flags::DEFENSE_PIERCING |
AttackSpecialProperty_Flags::DIMINISHING_BY_HIT |
AttackSpecialProperty_Flags::ALL_BUFFABLE,
// Removed Payback, added Front-spiky.
.counter_resistance_flags =
AttackCounterResistance_Flags::TOP_SPIKY |
AttackCounterResistance_Flags::FRONT_SPIKY,
.target_weighting_flags =
AttackTargetWeighting_Flags::WEIGHTED_RANDOM |
AttackTargetWeighting_Flags::UNKNOWN_0x2000 |
AttackTargetWeighting_Flags::PREFER_FRONT,
// status chances
.attack_evt_code = (void*)partyChuchurinaAttack_NormalAttack,
.bg_a1_a2_fall_weight = 0,
.bg_a1_fall_weight = 0,
.bg_a2_fall_weight = 0,
.bg_no_a_fall_weight = 100,
.bg_b_fall_weight = 0,
.nozzle_turn_chance = 4,
.nozzle_fire_chance = 2,
.ceiling_fall_chance = 0,
.object_fall_chance = 0,
};
BattleWeapon customWeapon_MowzKissThief = {
.name = "btl_wn_pcr_steal",
.icon = IconType::PARTNER_MOVE_1,
.item_id = 0,
.description = "msg_pch_heart_catch",
.base_accuracy = 100,
.base_fp_cost = 2,
.base_sp_cost = 0,
.superguards_allowed = 0,
.unk_14 = 1.0,
.stylish_multiplier = 1,
.unk_19 = 5,
.bingo_card_chance = 100,
.unk_1b = 50,
.damage_function = nullptr,
.damage_function_params = { 0, 0, 0, 0, 0, 0, 0, 0 },
.fp_damage_function = nullptr,
.fp_damage_function_params = { 0, 0, 0, 0, 0, 0, 0, 0 },
.target_class_flags =
AttackTargetClass_Flags::SINGLE_TARGET |
AttackTargetClass_Flags::ONLY_TARGET_PREFERRED_PARTS |
AttackTargetClass_Flags::CANNOT_TARGET_SELF |
AttackTargetClass_Flags::CANNOT_TARGET_SAME_ALLIANCE |
AttackTargetClass_Flags::CANNOT_TARGET_SYSTEM_UNITS |
AttackTargetClass_Flags::CANNOT_TARGET_TREE_OR_SWITCH,
.target_property_flags =
// Can now target any enemy, not just front ground-level one.
AttackTargetProperty_Flags::TARGET_OPPOSING_ALLIANCE_DIR,
.element = AttackElement::NORMAL,
.damage_pattern = 0x14,
.weapon_ac_level = 3,
.unk_6f = 2,
.ac_help_msg = "msg_ac_heart_catch",
.special_property_flags = AttackSpecialProperty_Flags::UNGUARDABLE,
.counter_resistance_flags =
// Ignores all contact hazards, aside from lit Bob-ombs.
AttackCounterResistance_Flags::ALL &
~AttackCounterResistance_Flags::VOLATILE_EXPLOSIVE,
.target_weighting_flags =
AttackTargetWeighting_Flags::WEIGHTED_RANDOM |
AttackTargetWeighting_Flags::UNKNOWN_0x2000 |
AttackTargetWeighting_Flags::PREFER_FRONT,
// status chances
.attack_evt_code = (void*)partyChuchurinaAttack_ItemSteal,
.bg_a1_a2_fall_weight = 0,
.bg_a1_fall_weight = 0,
.bg_a2_fall_weight = 0,
.bg_no_a_fall_weight = 100,
.bg_b_fall_weight = 0,
.nozzle_turn_chance = 0,
.nozzle_fire_chance = 5,
.ceiling_fall_chance = 0,
.object_fall_chance = 0,
};
BattleWeapon customWeapon_MowzTease = {
.name = "btl_wn_pcr_madowase",
.icon = IconType::PARTNER_MOVE_1,
.item_id = 0,
.description = "msg_pch_madowaseru",
.base_accuracy = 100,
.base_fp_cost = 3,
.base_sp_cost = 0,
.superguards_allowed = 2,
.unk_14 = 1.0,
.stylish_multiplier = 1,
.unk_19 = 5,
.bingo_card_chance = 100,
.unk_1b = 50,
.damage_function = nullptr,
.damage_function_params = { 0, 0, 0, 0, 0, 0, 0, 0 },
.fp_damage_function = nullptr,
.fp_damage_function_params = { 0, 0, 0, 0, 0, 0, 0, 0 },
.target_class_flags =
AttackTargetClass_Flags::MULTIPLE_TARGET |
AttackTargetClass_Flags::ONLY_TARGET_PREFERRED_PARTS |
AttackTargetClass_Flags::CANNOT_TARGET_SELF |
AttackTargetClass_Flags::CANNOT_TARGET_SAME_ALLIANCE |
AttackTargetClass_Flags::CANNOT_TARGET_SYSTEM_UNITS |
AttackTargetClass_Flags::CANNOT_TARGET_TREE_OR_SWITCH,
.target_property_flags =
AttackTargetProperty_Flags::TARGET_OPPOSING_ALLIANCE_DIR,
.element = AttackElement::NORMAL,
.damage_pattern = 0,
.weapon_ac_level = 3,
.unk_6f = 2,
.ac_help_msg = "msg_ac_madowaseru",
.special_property_flags = AttackSpecialProperty_Flags::TOT_PARTY_UNGUARDABLE,
.counter_resistance_flags = AttackCounterResistance_Flags::ALL,
.target_weighting_flags =
AttackTargetWeighting_Flags::UNKNOWN_0x2000 |
AttackTargetWeighting_Flags::PREFER_FRONT,
// status chances
.confuse_chance = 100,
.confuse_time = 1,
// unused field - use this to determine confuse proc rate.
.pad_ae = MoveType::MOWZ_TEASE,
.attack_evt_code = (void*)partyChuchurinaAttack_MadowaseAttack,
.bg_a1_a2_fall_weight = 0,
.bg_a1_fall_weight = 0,
.bg_a2_fall_weight = 0,
.bg_no_a_fall_weight = 100,
.bg_b_fall_weight = 0,
.nozzle_turn_chance = 0,
.nozzle_fire_chance = 5,
.ceiling_fall_chance = 0,
.object_fall_chance = 0,
};
BattleWeapon customWeapon_MowzSmooch = {
.name = "btl_wn_pcr_kiss",
.icon = IconType::PARTNER_MOVE_3,
.item_id = 0,
.description = "msg_pch_kiss",
.base_accuracy = 100,
.base_fp_cost = 10,
.base_sp_cost = 0,
.superguards_allowed = 0,
.unk_14 = 1.0,
.stylish_multiplier = 1,
.unk_19 = 5,
.bingo_card_chance = 100,
.unk_1b = 50,
.damage_function = nullptr,
.damage_function_params = { 0, 0, 0, 0, 0, 0, 0, 0 },
.fp_damage_function = nullptr,
.fp_damage_function_params = { 0, 0, 0, 0, 0, 0, 0, 0 },
.target_class_flags =
AttackTargetClass_Flags::SINGLE_TARGET |
AttackTargetClass_Flags::ONLY_TARGET_PREFERRED_PARTS |
AttackTargetClass_Flags::CANNOT_TARGET_SELF |
AttackTargetClass_Flags::CANNOT_TARGET_OPPOSING_ALLIANCE |
AttackTargetClass_Flags::CANNOT_TARGET_SYSTEM_UNITS |
AttackTargetClass_Flags::CANNOT_TARGET_TREE_OR_SWITCH |
// Explicitly add this to exclude Infatuated targets.
AttackTargetClass_Flags::ONLY_TARGET_MARIO,
.target_property_flags =
AttackTargetProperty_Flags::TARGET_SAME_ALLIANCE_DIR,
.element = AttackElement::NORMAL,
.damage_pattern = 0,
.weapon_ac_level = 3,
.unk_6f = 2,
.ac_help_msg = "msg_ac_chuchurina_kiss",
.special_property_flags =
AttackSpecialProperty_Flags::UNGUARDABLE |
AttackSpecialProperty_Flags::CANNOT_MISS,
.counter_resistance_flags = AttackCounterResistance_Flags::ALL,
.target_weighting_flags =
AttackTargetWeighting_Flags::WEIGHTED_RANDOM |
AttackTargetWeighting_Flags::UNKNOWN_0x2000 |
AttackTargetWeighting_Flags::PREFER_IN_PERIL |
AttackTargetWeighting_Flags::PREFER_LOWER_HP |
AttackTargetWeighting_Flags::PREFER_LESS_HEALTHY,
// status chances
.attack_evt_code = (void*)partyChuchurinaAttack_Kiss,
.bg_a1_a2_fall_weight = 0,
.bg_a1_fall_weight = 0,
.bg_a2_fall_weight = 0,
.bg_no_a_fall_weight = 100,
.bg_b_fall_weight = 0,
.nozzle_turn_chance = 0,
.nozzle_fire_chance = 5,
.ceiling_fall_chance = 0,
.object_fall_chance = 0,
};
BattleWeapon customWeapon_MowzEmbargo = {
.name = "tot_ptr7_embargo",
.icon = IconType::PARTNER_MOVE_1,
.item_id = 0,
.description = "tot_ptr7_embargo_desc",
.base_accuracy = 100,
.base_fp_cost = 3,
.base_sp_cost = 0,
.superguards_allowed = 0,
.unk_14 = 1.0,
.stylish_multiplier = 1,
.unk_19 = 5,
.bingo_card_chance = 100,
.unk_1b = 50,
.damage_function = nullptr,
.damage_function_params = { 0, 0, 0, 0, 0, 0, 0, 0 },
.fp_damage_function = nullptr,
.fp_damage_function_params = { 0, 0, 0, 0, 0, 0, 0, 0 },
.target_class_flags =
AttackTargetClass_Flags::MULTIPLE_TARGET |
AttackTargetClass_Flags::ONLY_TARGET_PREFERRED_PARTS |
AttackTargetClass_Flags::CANNOT_TARGET_SELF |
AttackTargetClass_Flags::CANNOT_TARGET_SAME_ALLIANCE |
AttackTargetClass_Flags::CANNOT_TARGET_SYSTEM_UNITS |
AttackTargetClass_Flags::CANNOT_TARGET_TREE_OR_SWITCH,
.target_property_flags =
AttackTargetProperty_Flags::TARGET_OPPOSING_ALLIANCE_DIR,
.element = AttackElement::NORMAL,
.damage_pattern = 0,
.weapon_ac_level = 3,
.unk_6f = 2,
.ac_help_msg = "msg_ac_madowaseru",
.special_property_flags = AttackSpecialProperty_Flags::UNGUARDABLE,
.counter_resistance_flags = AttackCounterResistance_Flags::ALL,
.target_weighting_flags =
AttackTargetWeighting_Flags::WEIGHTED_RANDOM |
AttackTargetWeighting_Flags::UNKNOWN_0x2000 |
AttackTargetWeighting_Flags::PREFER_FRONT,
// status chances
.attack_evt_code = (void*)partyChuchurinaAttack_MadowaseAttack,
.bg_a1_a2_fall_weight = 0,
.bg_a1_fall_weight = 0,
.bg_a2_fall_weight = 0,
.bg_no_a_fall_weight = 100,
.bg_b_fall_weight = 0,
.nozzle_turn_chance = 0,
.nozzle_fire_chance = 0,
.ceiling_fall_chance = 0,
.object_fall_chance = 0,
};
BattleWeapon customWeapon_MowzSmokeBomb = {
.name = "tot_ptr7_smokebomb",
.icon = IconType::PARTNER_MOVE_2,
.item_id = 0,
.description = "tot_ptr7_smokebomb_desc",
.base_accuracy = 100,
.base_fp_cost = 3,
.base_sp_cost = 0,
.superguards_allowed = 2,
.unk_14 = 1.0,
.stylish_multiplier = 1,
.unk_19 = 5,
.bingo_card_chance = 100,
.unk_1b = 50,
.damage_function = (void*)weaponGetPowerDefault,
.damage_function_params = { 1, 0, 0, 0, 0, 0, 0, 0 },
.fp_damage_function = nullptr,
.fp_damage_function_params = { 0, 0, 0, 0, 0, 0, 0, 0 },
.target_class_flags =
AttackTargetClass_Flags::MULTIPLE_TARGET |
AttackTargetClass_Flags::ONLY_TARGET_PREFERRED_PARTS |
AttackTargetClass_Flags::CANNOT_TARGET_SELF |
AttackTargetClass_Flags::CANNOT_TARGET_SAME_ALLIANCE |
AttackTargetClass_Flags::CANNOT_TARGET_SYSTEM_UNITS |
AttackTargetClass_Flags::CANNOT_TARGET_TREE_OR_SWITCH,
.target_property_flags =
AttackTargetProperty_Flags::TARGET_OPPOSING_ALLIANCE_DIR,
.element = AttackElement::EXPLOSION,
.damage_pattern = 0,
.weapon_ac_level = 3,
.unk_6f = 2,
.ac_help_msg = "msg_ac_madowaseru",
.special_property_flags =
AttackSpecialProperty_Flags::TOT_PARTY_UNGUARDABLE |
AttackSpecialProperty_Flags::DEFENSE_PIERCING |
AttackSpecialProperty_Flags::ALL_BUFFABLE,
.counter_resistance_flags = AttackCounterResistance_Flags::ALL,
.target_weighting_flags =
AttackTargetWeighting_Flags::UNKNOWN_0x2000 |
AttackTargetWeighting_Flags::PREFER_FRONT,
// status chances
.dizzy_chance = 60,
.dizzy_time = 1,
.attack_evt_code = (void*)partyChuchurinaAttack_MadowaseAttack,
.bg_a1_a2_fall_weight = 0,
.bg_a1_fall_weight = 10,
.bg_a2_fall_weight = 10,
.bg_no_a_fall_weight = 100,
.bg_b_fall_weight = 10,
.nozzle_turn_chance = 10,
.nozzle_fire_chance = 10,
.ceiling_fall_chance = 0,
.object_fall_chance = 0,
};
} // namespace mod::tot::party_mowz | 412 | 0.918308 | 1 | 0.918308 | game-dev | MEDIA | 0.983757 | game-dev | 0.986828 | 1 | 0.986828 |
Wynntils/Wynntils | 2,862 | common/src/main/java/com/wynntils/mc/event/PlayerInteractEvent.java | /*
* Copyright © Wynntils 2022-2025.
* This file is released under LGPLv3. See LICENSE for full license details.
*/
package com.wynntils.mc.event;
import com.google.common.base.Preconditions;
import net.minecraft.core.BlockPos;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.EntityHitResult;
import net.neoforged.bus.api.ICancellableEvent;
public abstract class PlayerInteractEvent extends PlayerEvent {
private final InteractionHand hand;
private InteractionResult cancellationResult = InteractionResult.PASS;
private PlayerInteractEvent(Player player, InteractionHand hand) {
super(player);
this.hand = hand;
}
public InteractionHand getHand() {
return this.hand;
}
public ItemStack getItemStack() {
return this.getPlayer().getItemInHand(this.hand);
}
public Level getWorld() {
return this.getPlayer().getCommandSenderWorld();
}
public InteractionResult getCancellationResult() {
return this.cancellationResult;
}
public void setCancellationResult(InteractionResult result) {
this.cancellationResult = result;
}
public static class RightClickBlock extends PlayerInteractEvent implements ICancellableEvent {
private final BlockPos pos;
private final BlockHitResult hitVec;
public RightClickBlock(Player player, InteractionHand hand, BlockPos pos, BlockHitResult hitVec) {
super(player, hand);
this.pos = Preconditions.checkNotNull(pos, "Null position in PlayerInteractEvent!");
this.hitVec = hitVec;
}
public BlockPos getPos() {
return this.pos;
}
public BlockHitResult getHitVec() {
return hitVec;
}
}
public static class Interact extends PlayerInteractEvent implements ICancellableEvent {
private final Entity target;
public Interact(Player player, InteractionHand hand, Entity target) {
super(player, hand);
this.target = target;
}
public Entity getTarget() {
return target;
}
}
public static class InteractAt extends Interact {
private final EntityHitResult entityHitResult;
public InteractAt(Player player, InteractionHand hand, Entity target, EntityHitResult entityHitResult) {
super(player, hand, target);
this.entityHitResult = entityHitResult;
}
public EntityHitResult getEntityHitResult() {
return entityHitResult;
}
}
}
| 412 | 0.854368 | 1 | 0.854368 | game-dev | MEDIA | 0.937166 | game-dev | 0.666302 | 1 | 0.666302 |
marrub--/GLOOME | 3,300 | src/g_strife/a_entityboss.cpp | /*
#include "actor.h"
#include "m_random.h"
#include "a_action.h"
#include "p_local.h"
#include "p_enemy.h"
#include "s_sound.h"
#include "a_strifeglobal.h"
#include "thingdef/thingdef.h"
#include "g_level.h"
*/
static FRandom pr_entity ("Entity");
DEFINE_ACTION_FUNCTION(AActor, A_SubEntityDeath)
{
if (CheckBossDeath (self))
{
G_ExitLevel (0, false);
}
}
void A_SpectralMissile (AActor *self, const char *missilename)
{
if (self->target != NULL)
{
AActor *missile = P_SpawnMissileXYZ (self->x, self->y, self->z + 32*FRACUNIT,
self, self->target, PClass::FindClass(missilename), false);
if (missile != NULL)
{
missile->tracer = self->target;
P_CheckMissileSpawn(missile, self->radius);
}
}
}
DECLARE_ACTION(A_SpotLightning)
DECLARE_ACTION(A_Spectre3Attack)
DEFINE_ACTION_FUNCTION(AActor, A_EntityAttack)
{
// Apparent Strife bug: Case 5 was unreachable because they used % 5 instead of % 6.
// I've fixed that by making case 1 duplicate it, since case 1 did nothing.
switch (pr_entity() % 5)
{
case 0:
CALL_ACTION(A_SpotLightning, self);
break;
case 2:
A_SpectralMissile (self, "SpectralLightningH3");
break;
case 3:
CALL_ACTION(A_Spectre3Attack, self);
break;
case 4:
A_SpectralMissile (self, "SpectralLightningBigV2");
break;
case 1:
case 5:
A_SpectralMissile (self, "SpectralLightningBigBall2");
break;
}
}
DEFINE_ACTION_FUNCTION(AActor, A_SpawnEntity)
{
AActor *entity = Spawn("EntityBoss", self->x, self->y, self->z + 70*FRACUNIT, ALLOW_REPLACE);
if (entity != NULL)
{
entity->angle = self->angle;
entity->CopyFriendliness(self, true);
entity->velz = 5*FRACUNIT;
entity->tracer = self;
}
}
DEFINE_ACTION_FUNCTION(AActor, A_EntityDeath)
{
AActor *second;
fixed_t secondRadius = GetDefaultByName("EntitySecond")->radius * 2;
angle_t an;
AActor *spot = self->tracer;
if (spot == NULL) spot = self;
fixed_t SpawnX = spot->x;
fixed_t SpawnY = spot->y;
fixed_t SpawnZ = spot->z + (self->tracer? 70*FRACUNIT : 0);
an = self->angle >> ANGLETOFINESHIFT;
second = Spawn("EntitySecond", SpawnX + FixedMul (secondRadius, finecosine[an]),
SpawnY + FixedMul (secondRadius, finesine[an]), SpawnZ, ALLOW_REPLACE);
second->CopyFriendliness(self, true);
//second->target = self->target;
A_FaceTarget (second);
an = second->angle >> ANGLETOFINESHIFT;
second->velx += FixedMul (finecosine[an], 320000);
second->vely += FixedMul (finesine[an], 320000);
an = (self->angle + ANGLE_90) >> ANGLETOFINESHIFT;
second = Spawn("EntitySecond", SpawnX + FixedMul (secondRadius, finecosine[an]),
SpawnY + FixedMul (secondRadius, finesine[an]), SpawnZ, ALLOW_REPLACE);
second->CopyFriendliness(self, true);
//second->target = self->target;
second->velx = FixedMul (secondRadius, finecosine[an]) << 2;
second->vely = FixedMul (secondRadius, finesine[an]) << 2;
A_FaceTarget (second);
an = (self->angle - ANGLE_90) >> ANGLETOFINESHIFT;
second = Spawn("EntitySecond", SpawnX + FixedMul (secondRadius, finecosine[an]),
SpawnY + FixedMul (secondRadius, finesine[an]), SpawnZ, ALLOW_REPLACE);
second->CopyFriendliness(self, true);
//second->target = self->target;
second->velx = FixedMul (secondRadius, finecosine[an]) << 2;
second->vely = FixedMul (secondRadius, finesine[an]) << 2;
A_FaceTarget (second);
}
| 412 | 0.836899 | 1 | 0.836899 | game-dev | MEDIA | 0.962672 | game-dev | 0.924174 | 1 | 0.924174 |
Alpine-DAV/ascent | 5,011 | src/libs/ascent/runtimes/expressions/ascent_blueprint_type_utils.cpp | //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Copyright (c) Lawrence Livermore National Security, LLC and other Ascent
// Project developers. See top-level LICENSE AND COPYRIGHT files for dates and
// other details. No copyright assignment is required to contribute to Ascent.
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
#include "ascent_blueprint_type_utils.hpp"
//-----------------------------------------------------------------------------
// -- begin ascent:: --
//-----------------------------------------------------------------------------
namespace ascent
{
//-----------------------------------------------------------------------------
// -- begin ascent::runtime --
//-----------------------------------------------------------------------------
namespace runtime
{
//-----------------------------------------------------------------------------
// -- begin ascent::runtime::expressions--
//-----------------------------------------------------------------------------
namespace expressions
{
//-----------------------------------------------------------------------------
bool mcarray_is_float32(const conduit::Node &node)
{
const int children = node.number_of_children();
if(children == 0)
{
return node.dtype().is_float32();
}
else
{
// there has to be one or more children so ask the first
return node.child(0).dtype().is_float32();
}
}
//-----------------------------------------------------------------------------
bool mcarray_is_float64(const conduit::Node &node)
{
const int children = node.number_of_children();
if(children == 0)
{
return node.dtype().is_float64();
}
else
{
// there has to be one or more children so ask the first
return node.child(0).dtype().is_float64();
}
}
//-----------------------------------------------------------------------------
bool mcarray_is_int32(const conduit::Node &node)
{
const int children = node.number_of_children();
if(children == 0)
{
return node.dtype().is_int32();
}
else
{
// there has to be one or more children so ask the first
return node.child(0).dtype().is_int32();
}
}
//-----------------------------------------------------------------------------
bool mcarray_is_int64(const conduit::Node &node)
{
const int children = node.number_of_children();
if(children == 0)
{
return node.dtype().is_int64();
}
else
{
// there has to be one or more children so ask the first
return node.child(0).dtype().is_int64();
}
}
//-----------------------------------------------------------------------------
bool field_is_float32(const conduit::Node &field)
{
const int children = field["values"].number_of_children();
if(children == 0)
{
return field["values"].dtype().is_float32();
}
else
{
// there has to be one or more children so ask the first
return field["values"].child(0).dtype().is_float32();
}
}
//-----------------------------------------------------------------------------
bool field_is_float64(const conduit::Node &field)
{
const int children = field["values"].number_of_children();
if(children == 0)
{
return field["values"].dtype().is_float64();
}
else
{
// there has to be one or more children so ask the first
return field["values"].child(0).dtype().is_float64();
}
}
//-----------------------------------------------------------------------------
bool field_is_int32(const conduit::Node &field)
{
const int children = field["values"].number_of_children();
if(children == 0)
{
return field["values"].dtype().is_int32();
}
else
{
// there has to be one or more children so ask the first
return field["values"].child(0).dtype().is_int32();
}
}
//-----------------------------------------------------------------------------
bool field_is_int64(const conduit::Node &field)
{
const int children = field["values"].number_of_children();
if(children == 0)
{
return field["values"].dtype().is_int64();
}
else
{
// there has to be one or more children so ask the first
return field["values"].child(0).dtype().is_int64();
}
}
//-----------------------------------------------------------------------------
};
//-----------------------------------------------------------------------------
// -- end ascent::runtime::expressions--
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
};
//-----------------------------------------------------------------------------
// -- end ascent::runtime --
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
};
//-----------------------------------------------------------------------------
// -- end ascent:: --
//-----------------------------------------------------------------------------
| 412 | 0.806203 | 1 | 0.806203 | game-dev | MEDIA | 0.570181 | game-dev | 0.573473 | 1 | 0.573473 |
ProjectIgnis/CardScripts | 1,105 | official/c64335804.lua | --レッドアイズ・ブラックメタルドラゴン
--Red-Eyes Black Metal Dragon
local s,id=GetID()
function s.initial_effect(c)
c:EnableReviveLimit()
--spsummon proc
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_SPSUMMON_PROC)
e1:SetProperty(EFFECT_FLAG_UNCOPYABLE)
e1:SetRange(LOCATION_DECK)
e1:SetCondition(s.spcon)
e1:SetTarget(s.sptg)
e1:SetOperation(s.spop)
c:RegisterEffect(e1)
end
s.listed_names={CARD_REDEYES_B_DRAGON,68540058}
function s.spfilter(c,tp)
return c:IsCode(CARD_REDEYES_B_DRAGON) and c:GetEquipGroup():IsExists(Card.IsCode,1,nil,68540058)
end
function s.spcon(e,c)
if c==nil then return true end
return Duel.CheckReleaseGroup(c:GetControler(),s.spfilter,1,false,1,true,c,c:GetControler(),nil,false,nil)
end
function s.sptg(e,tp,eg,ep,ev,re,r,rp,c)
local g=Duel.SelectReleaseGroup(tp,s.spfilter,1,1,false,true,true,c,nil,nil,false,nil)
if g then
g:KeepAlive()
e:SetLabelObject(g)
return true
end
return false
end
function s.spop(e,tp,eg,ep,ev,re,r,rp,c)
local g=e:GetLabelObject()
if not g then return end
Duel.Release(g,REASON_COST)
g:DeleteGroup()
end | 412 | 0.915438 | 1 | 0.915438 | game-dev | MEDIA | 0.917732 | game-dev | 0.973417 | 1 | 0.973417 |
awgil/ffxiv_bossmod | 5,226 | BossMod/Modules/Endwalker/Savage/P9SKokytos/ArchaicRockbreaker.cs | namespace BossMod.Endwalker.Savage.P9SKokytos;
class ArchaicRockbreakerCenter(BossModule module) : Components.StandardAOEs(module, AID.ArchaicRockbreakerCenter, 6);
class ArchaicRockbreakerShockwave(BossModule module) : Components.Knockback(module, AID.ArchaicRockbreakerShockwave, true)
{
private readonly Uplift? _uplift = module.FindComponent<Uplift>();
private readonly DateTime _activation = module.WorldState.FutureTime(6.5f);
public override IEnumerable<Source> Sources(int slot, Actor actor)
{
float distance = 21;
if (_uplift?.WallDirection != null)
{
var offset = actor.Position - Module.Center;
var dot = Math.Abs(_uplift.WallDirection.Value.ToDirection().Dot(offset.Normalized()));
bool againstWall = dot is > 0.9238795f or < 0.3826834f;
if (againstWall)
distance = Module.Bounds.Radius - offset.Length() - 0.5f;
}
yield return new(Module.Center, distance, _activation);
}
}
class ArchaicRockbreakerPairs : Components.UniformStackSpread
{
public ArchaicRockbreakerPairs(BossModule module) : base(module, 6, 0, 2)
{
foreach (var p in Raid.WithoutSlot(true).Where(p => p.Class.IsSupport()))
AddStack(p, WorldState.FutureTime(7.8f));
}
public override void OnEventCast(Actor caster, ActorCastEvent spell)
{
if ((AID)spell.Action.ID == AID.ArchaicRockbreakerPairs)
Stacks.Clear();
}
}
class ArchaicRockbreakerLine(BossModule module) : Components.StandardAOEs(module, AID.ArchaicRockbreakerLine, 8, maxCasts: 8);
class ArchaicRockbreakerCombination(BossModule module) : Components.GenericAOEs(module)
{
private readonly List<AOEInstance> _aoes = [];
private static readonly AOEShapeCircle _shapeOut = new(12);
private static readonly AOEShapeDonut _shapeIn = new(8, 20);
private static readonly AOEShapeCone _shapeCleave = new(40, 90.Degrees());
public override IEnumerable<AOEInstance> ActiveAOEs(int slot, Actor actor)
{
return _aoes.Take(1);
}
public override void AddMovementHints(int slot, Actor actor, MovementHints movementHints)
{
foreach (var p in SafeSpots())
movementHints.Add(actor.Position, p, ArenaColor.Safe);
}
public override void OnCastStarted(Actor caster, ActorCastInfo spell)
{
var (inOutShape, offset) = (AID)spell.Action.ID switch
{
AID.FrontCombinationOut => (_shapeOut, 0.Degrees()),
AID.FrontCombinationIn => (_shapeIn, 0.Degrees()),
AID.RearCombinationOut => (_shapeOut, 180.Degrees()),
AID.RearCombinationIn => (_shapeIn, 180.Degrees()),
_ => ((AOEShape?)null, 0.Degrees())
};
if (inOutShape != null)
{
_aoes.Add(new(inOutShape, Module.PrimaryActor.Position, default, WorldState.FutureTime(6.9f)));
_aoes.Add(new(_shapeCleave, Module.PrimaryActor.Position, Module.PrimaryActor.Rotation + offset, WorldState.FutureTime(10)));
}
}
public override void OnEventCast(Actor caster, ActorCastEvent spell)
{
switch ((AID)spell.Action.ID)
{
case AID.InsideRoundhouseAOE:
PopAOE();
_aoes.Add(new(_shapeIn, Module.PrimaryActor.Position, default, WorldState.FutureTime(6)));
break;
case AID.OutsideRoundhouseAOE:
PopAOE();
_aoes.Add(new(_shapeOut, Module.PrimaryActor.Position, default, WorldState.FutureTime(6)));
break;
case AID.SwingingKickFrontAOE:
case AID.SwingingKickRearAOE:
PopAOE();
break;
}
}
private void PopAOE()
{
++NumCasts;
if (_aoes.Count > 0)
_aoes.RemoveAt(0);
}
private IEnumerable<WPos> SafeSpots()
{
if (NumCasts == 0 && _aoes.Count > 0 && _aoes[0].Shape == _shapeOut && Module.FindComponent<ArchaicRockbreakerLine>() is var forbidden && forbidden?.NumCasts == 0)
{
var safespots = new ArcList(_aoes[0].Origin, _shapeOut.Radius + 0.25f);
foreach (var f in forbidden.ActiveCasters)
safespots.ForbidCircle(f.Position, ((AOEShapeCircle)forbidden.Shape).Radius);
if (safespots.Forbidden.Segments.Count > 0)
{
foreach (var a in safespots.Allowed(default))
{
var mid = ((a.min.Rad + a.max.Rad) * 0.5f).Radians();
yield return safespots.Center + safespots.Radius * mid.ToDirection();
}
}
}
}
}
class ArchaicDemolish(BossModule module) : Components.UniformStackSpread(module, 6, 0, 4)
{
public override void OnCastStarted(Actor caster, ActorCastInfo spell)
{
if ((AID)spell.Action.ID == AID.ArchaicDemolish)
AddStacks(Raid.WithoutSlot(true).Where(a => a.Role == Role.Healer), Module.CastFinishAt(spell, 1.2f));
}
public override void OnEventCast(Actor caster, ActorCastEvent spell)
{
if ((AID)spell.Action.ID == AID.ArchaicDemolishAOE)
Stacks.Clear();
}
}
| 412 | 0.955599 | 1 | 0.955599 | game-dev | MEDIA | 0.961893 | game-dev | 0.950535 | 1 | 0.950535 |
magefree/mage | 2,899 | Mage.Sets/src/mage/cards/s/SpitefulShadows.java | package mage.cards.s;
import mage.abilities.Ability;
import mage.abilities.common.DealtDamageAttachedTriggeredAbility;
import mage.abilities.effects.OneShotEffect;
import mage.abilities.effects.common.AttachEffect;
import mage.abilities.keyword.EnchantAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.*;
import mage.game.Game;
import mage.game.permanent.Permanent;
import mage.players.Player;
import mage.target.TargetPermanent;
import mage.target.common.TargetCreaturePermanent;
import mage.target.targetpointer.FixedTarget;
import java.util.UUID;
/**
* @author North
*/
public final class SpitefulShadows extends CardImpl {
public SpitefulShadows(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.ENCHANTMENT}, "{1}{B}");
this.subtype.add(SubType.AURA);
// Enchant creature
TargetPermanent auraTarget = new TargetCreaturePermanent();
this.getSpellAbility().addTarget(auraTarget);
this.getSpellAbility().addEffect(new AttachEffect(Outcome.UnboostCreature));
this.addAbility(new EnchantAbility(auraTarget));
// Whenever enchanted creature is dealt damage, it deals that much damage to its controller.
this.addAbility(new DealtDamageAttachedTriggeredAbility(Zone.BATTLEFIELD, new SpitefulShadowsEffect(),
false, SetTargetPointer.PERMANENT));
}
private SpitefulShadows(final SpitefulShadows card) {
super(card);
}
@Override
public SpitefulShadows copy() {
return new SpitefulShadows(this);
}
}
class SpitefulShadowsEffect extends OneShotEffect {
SpitefulShadowsEffect() {
super(Outcome.Damage);
this.staticText = "it deals that much damage to its controller";
}
private SpitefulShadowsEffect(final SpitefulShadowsEffect effect) {
super(effect);
}
@Override
public SpitefulShadowsEffect copy() {
return new SpitefulShadowsEffect(this);
}
@Override
public boolean apply(Game game, Ability source) {
Integer damageAmount = (Integer) this.getValue("damage");
if (damageAmount != null) {
Permanent permanent = game.getPermanent(getTargetPointer().getFirst(game, source));
if (permanent == null) {
FixedTarget fixedTarget = (FixedTarget) getTargetPointer();
permanent = (Permanent) game.getLastKnownInformation(fixedTarget.getTarget(), Zone.BATTLEFIELD, fixedTarget.getZoneChangeCounter());
}
if (permanent != null) {
Player player = game.getPlayer(permanent.getControllerId());
if (player != null) {
player.damage(damageAmount, permanent.getId(), source, game);
return true;
}
}
}
return false;
}
}
| 412 | 0.958892 | 1 | 0.958892 | game-dev | MEDIA | 0.953142 | game-dev | 0.988128 | 1 | 0.988128 |
Ilya3point999K/RAL | 14,739 | old/fps.c | /*
A weird little demo game where you collect golden heads. It demonstrates how
immediate-mode rendering of triangles can be used to throw together things
with simple code. The head model is loaded from an OBJ file, and the rest of
the terrain is generated randomly. This uses a trick where the random number
generator seed is reset before use to recall the same set of numbers without
having to store them.
Use WASD or the arrow keys to move, and mouse to look.
*/
#define RND RAL_D2F(rand() / (float)RAND_MAX)
#include <time.h> // random number seed
#include <stdio.h>
#include "SDL.h"
#include "ral.h"
int main(int argument_count, char ** arguments) {
int width = 640;
int height = 480;
setbuf(stdout, NULL);
SDL_Init(SDL_INIT_VIDEO);
SDL_Window * window = SDL_CreateWindow("", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, 0);
SDL_Renderer * renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_PRESENTVSYNC);
SDL_Texture * texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, width, height);
RAL_CONTEXT context = {0};
context.far = RAL_ONE * 100;
context.near = RAL_ONE / 10;
uint32_t * pixels = malloc(width * height * sizeof(pixels[0]));
RAL_F * depth = malloc(width * height * sizeof(depth[0]));
RAL_INIT(&context, pixels, depth, width, height, RAL_I2F(90));
// Barebones .obj file loader.
char * file_name = "moai.obj";
if (argument_count == 2) file_name = arguments[1];
int vert_count = 0;
RAL_F * triangles = NULL;
{
int vi = 0, ti = 0;
RAL_F * vertices = NULL;
FILE * obj_file = fopen(file_name, "r");
if (!obj_file) {
printf("Failed to load file '%s'.\n", file_name);
exit(1);
}
char line[128];
float x, y, z;
while (fgets(line, 128, obj_file)) {
if (line[0] == 'v' && sscanf(line, " v %f %f %f ", &x, &y, &z)) {
vertices = realloc(vertices, (vi+3) * sizeof(vertices[0]));
vertices[vi++] = RAL_D2F(x);
vertices[vi++] = RAL_D2F(y);
vertices[vi++] = RAL_D2F(z);
}
}
rewind(obj_file);
int a, b, c;
while (fgets(line, 128, obj_file)) {
if (line[0] == 'f') {
// Erase texture and normal information.
for (int i = 0; i < 128; ++i) {
if (line[i] == '/') {
while (line[i] != ' ' && line[i] != '\n' && line[i] != '\0') {
line[i++] = ' ';
}
}
}
if (sscanf(line, " f %d %d %d ", &a, &b, &c)) {
a--, b--, c--;
triangles = realloc(triangles, (ti+9) * sizeof(triangles[0]));
triangles[ti++] = vertices[(a*3)+0];
triangles[ti++] = vertices[(a*3)+1];
triangles[ti++] = vertices[(a*3)+2];
triangles[ti++] = vertices[(b*3)+0];
triangles[ti++] = vertices[(b*3)+1];
triangles[ti++] = vertices[(b*3)+2];
triangles[ti++] = vertices[(c*3)+0];
triangles[ti++] = vertices[(c*3)+1];
triangles[ti++] = vertices[(c*3)+2];
}
}
}
free(vertices);
vert_count = ti;
}
RAL_F player_x = -RAL_ONE;
RAL_F player_z = -RAL_ONE * 3;
RAL_F player_height = RAL_ONE;
RAL_F player_yaw = RAL_ONE;
RAL_F player_pitch = 0;
RAL_F player_forward_speed = 0;
RAL_F player_strafe_speed = 0;
RAL_F mouse_sensitivity = RAL_ONE / 100;
int up = 0, down = 0, left = 0, right = 0, crouch = 0;
SDL_SetRelativeMouseMode(1);
int world_size = 20 * RAL_ONE;
RAL_F boundary = RAL_ONE * 2 + (RAL_ONE / 2);
int seed = time(NULL);
srand(seed);
RAL_F heads[16];
for (int i = 0; i < 16; ++i) {
heads[i] = (int)((RAL_FMUL(RND, (world_size-boundary)) * 2) - (world_size-boundary));
}
printf("%i\n", RAL_D2F(3.1415926535));
int heads_found = 0;
RAL_F head_radius = RAL_ONE / 2;
RAL_F head_confetti_y = RAL_ONE * 2;
SDL_SetWindowTitle(window, "Find The Golden Heads");
while (1) {
SDL_Event event;
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) {
exit(0);
} else if (event.type == SDL_KEYDOWN || event.type == SDL_KEYUP) {
int sc = event.key.keysym.scancode;
if (sc == SDL_SCANCODE_UP || sc == SDL_SCANCODE_W) {
up = event.key.state;
} else if (sc == SDL_SCANCODE_DOWN || sc == SDL_SCANCODE_S) {
down = event.key.state;
} else if (sc == SDL_SCANCODE_LEFT || sc == SDL_SCANCODE_A) {
left = event.key.state;
} else if (sc == SDL_SCANCODE_RIGHT || sc == SDL_SCANCODE_D) {
right = event.key.state;
} else if (sc == SDL_SCANCODE_LSHIFT || sc == SDL_SCANCODE_RSHIFT || sc == SDL_SCANCODE_C) {
crouch = event.key.state;
} else if (sc == SDL_SCANCODE_ESCAPE) {
exit(0);
}
} else if (event.type == SDL_MOUSEMOTION) {
player_yaw -= event.motion.xrel * mouse_sensitivity;
player_pitch += event.motion.yrel * mouse_sensitivity;
if (player_pitch < -(RAL_ONE + (RAL_ONE / 3))) player_pitch = -(RAL_ONE + (RAL_ONE / 3));
if (player_pitch > RAL_ONE + (RAL_ONE / 3)) player_pitch = RAL_ONE + (RAL_ONE / 3);
}
}
RAL_CLEAR(&context);
RAL_F t = SDL_GetTicks() * (RAL_ONE / 100);
// A basic version of standard (mouse-look) FPS controls.
if (up) player_forward_speed = RAL_ONE / 10;
if (down) player_forward_speed = -RAL_ONE / 10;
if (left) player_strafe_speed = RAL_ONE / 10;
if (right) player_strafe_speed = -RAL_ONE / 10;
player_height += RAL_FMUL(((crouch ? RAL_ONE / 2 : RAL_ONE) - player_height), (RAL_ONE / 10));
player_x -= RAL_FMUL(RAL_FCOS(player_yaw - RAL_ONE - (RAL_ONE / 2)), player_forward_speed);
player_z -= RAL_FMUL(RAL_FSIN(player_yaw - RAL_ONE - (RAL_ONE / 2)), player_forward_speed);
player_x -= RAL_FMUL(RAL_FCOS(player_yaw), player_strafe_speed);
player_z -= RAL_FMUL(RAL_FSIN(player_yaw), player_strafe_speed);
player_forward_speed = 0;
player_strafe_speed = 0;
// Collision with world edge.
if (player_x < -(world_size-boundary)) player_x = -world_size+boundary;
if (player_x > (world_size-boundary)) player_x = world_size-boundary;
if (player_z < -(world_size-boundary)) player_z = -world_size+boundary;
if (player_z > (world_size-boundary)) player_z = world_size-boundary;
RAL_SET_CAMERA(&context, player_x, player_height, player_z, player_yaw, player_pitch, 0);
// Draw a checkerboard floor.
RAL_RESET(&context);
/*
for (int z = -RAL_F2I(world_size); z < RAL_F2I(world_size); ++z) {
for (int x = -RAL_F2I(world_size); x < RAL_F2I(world_size); ++x) {
uint32_t c = (x+z) & 1 ? 0x424C88 : 0xF7C396;
RAL_F xx = RAL_I2F(x);
RAL_F zz = RAL_I2F(z);
RAL_TRIANGLE(&context, xx+(RAL_ONE / 2), 0, zz+(RAL_ONE / 2), xx-(RAL_ONE / 2), 0, zz-(RAL_ONE / 2), xx-(RAL_ONE / 2), 0, zz+(RAL_ONE / 2), c);
RAL_TRIANGLE(&context, xx+(RAL_ONE / 2), 0, zz+(RAL_ONE / 2), xx+(RAL_ONE / 2), 0, zz-(RAL_ONE / 2), xx-(RAL_ONE / 2), 0, zz-(RAL_ONE / 2), c);
}
}
*/
for (int z = -20; z < 20; ++z) {
for (int x = -20; x < 20; ++x) {
uint32_t c = (x+z) & 1 ? 0x424C88 : 0xF7C396;
RAL_F xx = RAL_I2F(x);
RAL_F zz = RAL_I2F(z);
if(z == 0 && x == 0){
RAL_TRIANGLE(&context, xx+(RAL_ONE / 2), 0, zz+(RAL_ONE / 2), xx-(RAL_ONE / 2), 0, zz-(RAL_ONE / 2), xx-(RAL_ONE / 2), 0, zz+(RAL_ONE / 2), 0xFF0000);
RAL_TRIANGLE(&context, xx+(RAL_ONE / 2), 0, zz+(RAL_ONE / 2), xx+(RAL_ONE / 2), 0, zz-(RAL_ONE / 2), xx-(RAL_ONE / 2), 0, zz-(RAL_ONE / 2), 0xFF0000);
} else{
RAL_TRIANGLE(&context, xx+(RAL_ONE / 2), 0, zz+(RAL_ONE / 2), xx-(RAL_ONE / 2), 0, zz-(RAL_ONE / 2), xx-(RAL_ONE / 2), 0, zz+(RAL_ONE / 2), c);
RAL_TRIANGLE(&context, xx+(RAL_ONE / 2), 0, zz+(RAL_ONE / 2), xx+(RAL_ONE / 2), 0, zz-(RAL_ONE / 2), xx-(RAL_ONE / 2), 0, zz-(RAL_ONE / 2), c);
}
}
}
// Draw the golden heads.
for (int h = 0; h < 16; h += 2) {
RAL_F x = heads[h];
RAL_F z = heads[h+1];
// If the player is close to a head, mark it as found using NAN.
if (RAL_ABS(player_x - x) < head_radius && RAL_ABS(player_z - z) < head_radius) {
heads[h] = 0;
heads[h+1] = 0;
++heads_found;
char title[64];
snprintf(title, 64, "%d / 8 heads found", heads_found);
SDL_SetWindowTitle(window, title);
}
// Draw the remaining heads.
if (!(heads[h] == 0)) {
RAL_RESET(&context);
RAL_ROTY(&context, RAL_I2F(h)+t);
RAL_SCALE(&context, RAL_ONE ,RAL_ONE,RAL_ONE);
RAL_TRANSLATE(&context, x, (RAL_ONE / 3) + RAL_FMUL(RAL_FSIN(RAL_I2F(h)+t),(RAL_ONE / 10)), z);
srand(h);
for (int i = 0; i < vert_count; i += 9) {
uint32_t r = 200 + (RAL_F2I(RND * 50));
uint32_t g = 150 + (RAL_F2I(RND * 50));
uint32_t b = 50 + (RAL_F2I(RND * 50));
RAL_TRIANGLE(&context,
triangles[i + 0], triangles[i + 1], triangles[i + 2],
triangles[i + 3], triangles[i + 4], triangles[i + 5],
triangles[i + 6], triangles[i + 7], triangles[i + 8],
(r << 16 | g << 8 | b)
);
}
}
}
// Make a jagged border around the world using stretched cubes.
srand(seed);
for (int i = -RAL_F2I(world_size); i < RAL_F2I(world_size); i+=2) {
for (int j = 0; j < 4; ++j) {
RAL_F x = i * RAL_ONE, z = i * RAL_ONE;
switch (j) {
case 0: x = -world_size; break;
case 1: x = world_size; break;
case 2: z = -world_size; break;
case 3: z = world_size; break;
}
RAL_RESET(&context);
RAL_ROTY(&context, RAL_FMUL(RND, RAL_PI));
RAL_ROTX(&context, RAL_FMUL(RND, RAL_PI));
RAL_ROTZ(&context, RAL_FMUL(RND, RAL_PI));
RAL_SCALE(&context, (RAL_ONE) + RND * 2, (RAL_ONE) + RND * 8, (RAL_ONE) + RND * 2);
RAL_TRANSLATE(&context, x, (RAL_ONE / 2), z);
RAL_TRIANGLE(&context, -(RAL_ONE / 2),-(RAL_ONE / 2),-(RAL_ONE / 2), -(RAL_ONE / 2), (RAL_ONE / 2),-(RAL_ONE / 2), (RAL_ONE / 2), (RAL_ONE / 2),-(RAL_ONE / 2), 0xfcd0a1);
RAL_TRIANGLE(&context, -(RAL_ONE / 2),-(RAL_ONE / 2),-(RAL_ONE / 2), (RAL_ONE / 2), (RAL_ONE / 2),-(RAL_ONE / 2), (RAL_ONE / 2),-(RAL_ONE / 2),-(RAL_ONE / 2), 0xb1b695);
RAL_TRIANGLE(&context, (RAL_ONE / 2),-(RAL_ONE / 2),-(RAL_ONE / 2), (RAL_ONE / 2), (RAL_ONE / 2),-(RAL_ONE / 2), (RAL_ONE / 2), (RAL_ONE / 2), (RAL_ONE / 2), 0x53917e);
RAL_TRIANGLE(&context, (RAL_ONE / 2),-(RAL_ONE / 2),-(RAL_ONE / 2), (RAL_ONE / 2), (RAL_ONE / 2), (RAL_ONE / 2), (RAL_ONE / 2),-(RAL_ONE / 2), (RAL_ONE / 2), 0x63535b);
RAL_TRIANGLE(&context, (RAL_ONE / 2),-(RAL_ONE / 2), (RAL_ONE / 2), (RAL_ONE / 2), (RAL_ONE / 2), (RAL_ONE / 2), -(RAL_ONE / 2), (RAL_ONE / 2), (RAL_ONE / 2), 0x6d1a36);
RAL_TRIANGLE(&context, (RAL_ONE / 2),-(RAL_ONE / 2), (RAL_ONE / 2), -(RAL_ONE / 2), (RAL_ONE / 2), (RAL_ONE / 2), -(RAL_ONE / 2),-(RAL_ONE / 2), (RAL_ONE / 2), 0xd4e09b);
RAL_TRIANGLE(&context, -(RAL_ONE / 2),-(RAL_ONE / 2), (RAL_ONE / 2), -(RAL_ONE / 2), (RAL_ONE / 2), (RAL_ONE / 2), -(RAL_ONE / 2), (RAL_ONE / 2),-(RAL_ONE / 2), 0xf6f4d2);
RAL_TRIANGLE(&context, -(RAL_ONE / 2),-(RAL_ONE / 2), (RAL_ONE / 2), -(RAL_ONE / 2), (RAL_ONE / 2),-(RAL_ONE / 2), -(RAL_ONE / 2),-(RAL_ONE / 2),-(RAL_ONE / 2), 0xcbdfbd);
RAL_TRIANGLE(&context, -(RAL_ONE / 2), (RAL_ONE / 2),-(RAL_ONE / 2), -(RAL_ONE / 2), (RAL_ONE / 2), (RAL_ONE / 2), (RAL_ONE / 2), (RAL_ONE / 2), (RAL_ONE / 2), 0xf19c79);
RAL_TRIANGLE(&context, -(RAL_ONE / 2), (RAL_ONE / 2),-(RAL_ONE / 2), (RAL_ONE / 2), (RAL_ONE / 2), (RAL_ONE / 2), (RAL_ONE / 2), (RAL_ONE / 2),-(RAL_ONE / 2), 0xa44a3f);
RAL_TRIANGLE(&context, (RAL_ONE / 2),-(RAL_ONE / 2), (RAL_ONE / 2), -(RAL_ONE / 2),-(RAL_ONE / 2), (RAL_ONE / 2), -(RAL_ONE / 2),-(RAL_ONE / 2),-(RAL_ONE / 2), 0x5465ff);
RAL_TRIANGLE(&context, (RAL_ONE / 2),-(RAL_ONE / 2), (RAL_ONE / 2), -(RAL_ONE / 2),-(RAL_ONE / 2),-(RAL_ONE / 2), (RAL_ONE / 2),-(RAL_ONE / 2),-(RAL_ONE / 2), 0x788bff);
}
}
// Scatter some pyramids around in the world.
srand(seed);
for (int i = 0; i < 20; ++i) {
RAL_RESET(&context);
RAL_SCALE(&context, RAL_ONE, RAL_ONE + RND * 3, RAL_ONE);
RAL_ROTY(&context, RAL_FMUL(RND, RAL_PI));
RAL_TRANSLATE(&context, (RAL_FMUL(RND, world_size) * 2) - world_size, 0, (RAL_FMUL(RND, world_size) * 2) - world_size);
RAL_TRIANGLE(&context, 10, (RAL_ONE * 2), 10,-(RAL_ONE), 10, (RAL_ONE), (RAL_ONE), 10, (RAL_ONE), 0x004749);
RAL_TRIANGLE(&context, 10, (RAL_ONE * 2), 10, (RAL_ONE), 10, (RAL_ONE), (RAL_ONE), 10,-(RAL_ONE), 0x00535a);
RAL_TRIANGLE(&context, 10, (RAL_ONE * 2), 10, (RAL_ONE), 10,-(RAL_ONE),-(RAL_ONE), 10,-(RAL_ONE), 0x00746b);
RAL_TRIANGLE(&context, 10, (RAL_ONE * 2), 10,-(RAL_ONE), 10,-(RAL_ONE),-(RAL_ONE), 10, (RAL_ONE), 0x00945c);
}
// Display the pixel buffer on the screen.
SDL_Delay(1);
SDL_RenderClear(renderer);
SDL_UpdateTexture(texture, NULL, pixels, width * sizeof(uint32_t));
SDL_RenderCopy(renderer, texture, NULL, NULL);
SDL_RenderPresent(renderer);
//printf("frame\n");
}
}
| 412 | 0.673467 | 1 | 0.673467 | game-dev | MEDIA | 0.619504 | game-dev,graphics-rendering | 0.836344 | 1 | 0.836344 |
stuffbydavid/Mine-imator | 14,862 | CppProject/World/Chunk.cpp | #include "World.hpp"
#include "NBT.hpp"
namespace CppProject
{
WorldVec blockFaceOffset[Chunk::FaceDirectionAmount][4] = {
{ { 1, 0, 1 }, { 1, 0, 0 }, { 1, 1, 0 }, { 1, 1, 1 } }, // Right
{ { 0, 0, 0 }, { 0, 0, 1 }, { 0, 1, 1 }, { 0, 1, 0 } }, // Left
{ { 0, 1, 1 }, { 1, 1, 1 }, { 1, 1, 0 }, { 0, 1, 0 } }, // Up
{ { 1, 0, 0 }, { 1, 0, 1 }, { 0, 0, 1 }, { 0, 0, 0 } }, // Down
{ { 0, 0, 1 }, { 1, 0, 1 }, { 1, 1, 1 }, { 0, 1, 1 } }, // Front
{ { 1, 0, 0 }, { 0, 0, 0 }, { 0, 1, 0 }, { 1, 1, 0 } } // Back
};
WorldVec blockFaceMergeVec[Chunk::FaceDirectionAmount][2] = {
{ { 0, 0, 1 }, { 0, 1, 0 } }, // Right
{ { 0, 0, 1 }, { 0, 1, 0 } }, // Left
{ { 1, 0, 0 }, { 0, 0, 1 } }, // Up
{ { 1, 0, 0 }, { 0, 0, 1 } }, // Down
{ { 1, 0, 0 }, { 0, 1, 0 } }, // Front
{ { 1, 0, 0 }, { 0, 1, 0 } } // Back
};
Chunk::Chunk(Region* region, QByteArray& data, const WorldBox& box) : region(region)
{
memset(sections, 0, sizeof(sections));
try
{
NbtStream stream(data, {
{ TAG_BYTE, { "Y" } },
{ TAG_BYTE_ARRAY, { "SkyLight", "BlockLight", "Blocks", "Data", "Biomes", "Add" }},
{ TAG_COMPOUND, { "Level", "Properties", "block_states", "block_entities", "TileEntities", "biomes" }},
{ TAG_LIST, { "sections", "Sections", "palette", "Palette" }},
{ TAG_LONG_ARRAY, { "data", "BlockStates"}},
{ TAG_STRING, { "Name", "Status" }},
{ TAG_INT, { "DataVersion", "xPos", "zPos" }},
});
NbtCompound chunkCompound(stream);
// Get block format
format = region->anvilFormat ? JAVA_1_2 : PRE_JAVA_1_2;
if (chunkCompound.HasKey("DataVersion"))
{
IntType dataVersion = chunkCompound.Int("DataVersion");
if (dataVersion >= JAVA_1_18)
format = JAVA_1_18;
else if (dataVersion >= JAVA_1_16)
format = JAVA_1_16;
else if (dataVersion >= JAVA_1_13)
format = JAVA_1_13;
}
// Use Level compound as root (removed in 1.18)
NbtCompound* chunkRoot = chunkCompound.HasKey("Level") ? chunkCompound.Compound("Level") : &chunkCompound;
// Get region offset
x = ((IntType)chunkRoot->Int("xPos") & 31); // x % 32
z = ((IntType)chunkRoot->Int("zPos") & 31); // z % 32
rightEdge = (x == REGION_SIZE_CHUNKS - 1);
leftEdge = (x == 0);
frontEdge = (z == REGION_SIZE_CHUNKS - 1);
backEdge = (z == 0);
regionIndex = (z << 5) + x; // z * 32 + x
// Get region position in blocks
regionPos.x = x << 4; // x * 16
regionPos.y = CHUNK_HEIGHT_MIN;
regionPos.z = z << 4; // z * 16
// Check chunk box with given selection
WorldVec worldPos = region->pos + regionPos;
if (box.active && !box.Intersects({ worldPos, worldPos + WorldVec(SECTION_SIZE, CHUNK_HEIGHT_SIZE, SECTION_SIZE) }))
return;
// Parse legacy 16x16 biomes
if (chunkRoot->HasKey("Biomes"))
{
const Heap<int8_t>& biomesArray = chunkRoot->ByteArray("Biomes");
const Map& legacyIdsMap = DsMap(global::legacy_biomes_ids_map);
legacyBiomes.Alloc(SECTION_SIZE * SECTION_SIZE);
for (IntType x = 0; x < SECTION_SIZE; x++)
for (IntType z = 0; z < SECTION_SIZE; z++)
legacyBiomes[z * SECTION_SIZE + x] = Preview::mcBiomeIdIndexMap[legacyIdsMap.Value(biomesArray.Value(z * SECTION_SIZE + x))];
}
// Parse existing sections
if (format >= JAVA_1_2)
{
// Must be fully loaded
if (chunkRoot->HasKey("Status")) {
StringType status = chunkRoot->String("Status").Replaced("minecraft:", "");
if (status != "full" &&
status != "fullchunk" &&
status != "postprocessed")
return;
}
StringType sectionsName = (format >= JAVA_1_18 ? "sections" : "Sections");
if (!chunkRoot->HasKey(sectionsName))
return;
QVector<NbtCompound*> sectionsList = chunkRoot->List<TAG_COMPOUND, NbtCompound>(sectionsName);
for (NbtCompound* comp : sectionsList)
{
IntType y = comp->Byte("Y");
if (y < CHUNK_SECTION_MIN || y >= CHUNK_SECTION_MIN + CHUNK_SECTIONS)
continue;
Section* section = new Section(this, y, box);
sections[section->chunkIndex] = section;
if (!section->Load(comp, format))
{
error = true;
return;
}
}
}
// Parse block data arrays (16x16x128 before 1.2)
else
for (IntType y = 0; y < 128 / SECTION_SIZE; y++)
{
Section* section = new Section(this, y, box);
sections[section->chunkIndex] = section;
if (!section->Load(chunkRoot, format))
{
error = true;
return;
}
}
// Parse block entities if box is active
if (box.active)
{
StringType blockEntitiesName = "block_entities";
if (chunkRoot->HasKey("TileEntities"))
blockEntitiesName = "TileEntities";
QVector<NbtCompound*> blockEntities = chunkRoot->List<TAG_COMPOUND, NbtCompound>(blockEntitiesName);
for (IntType i = 0; i < blockEntities.size(); i++)
{
NbtCompound* blockEntity = blockEntities.value(i);
StringType id;
WorldVec worldPos;
// Get id and world position
if (blockEntity->HasKey("id"))
{
id = blockEntity->String("id");
worldPos = { blockEntity->Int("x"), blockEntity->Int("y"), blockEntity->Int("z")};
}
else
{
id = blockEntity->String("Id");
QVector<NbtInt*> posList = blockEntity->List<TAG_INT, NbtInt>("Pos");
worldPos = { posList[0]->value, posList[1]->value, posList[2]->value };
}
// Get script
id = id.Replaced("minecraft:", "");
IntType scriptId = asset_get_index("block_tile_entity_" + id.ToLower());
// Create block entity relative to box start
if (scriptId > -1 && box.Contains(worldPos))
{
this->blockEntities.append({
worldPos - box.start,
FindScript(scriptId),
blockEntity
});
((NbtList*)chunkRoot->value[blockEntitiesName])->value.Erase(i); // Erase from list to avoid deletion
}
}
}
else
// Add sections where needed for preview mesh generation
for (IntType i = 0; i < CHUNK_SECTIONS; i++)
if (!sections[i])
sections[i] = new Section(this, i + CHUNK_SECTION_MIN, box);
}
catch (const QString& ex)
{
WARNING("Error reading chunk at " + NumStr(x) + ", " + NumStr(z) + ": " + ex);
error = true;
return;
}
}
Chunk::~Chunk()
{
// Erase sections not needed by the scenery builder
for (Section* section : sections)
if (section && section->dataType != Section::BUILDER)
delete section;
}
void Chunk::GeneratePreview(Region::GenerateMode mode)
{
// Find start and end XZ in the sections to generate
WorldVec startPos = { 0, 0, 0 }, endPos = { SECTION_SIZE, SECTION_SIZE, SECTION_SIZE };
if (mode < Region::GenerateMode::LEFT_BACK_CORNER)
{
// Check if chunk is on region edge, those blocks need other regions to be loaded first
if (rightEdge)
endPos.x--;
else if (leftEdge)
startPos.x++;
if (frontEdge)
endPos.z--;
else if (backEdge)
startPos.z++;
}
switch (mode)
{
// Region edges only
case Region::GenerateMode::RIGHT_EDGE:
{
if (rightEdge)
startPos.x = SECTION_SIZEM1, endPos.x = SECTION_SIZE;
else
return;
break;
}
case Region::GenerateMode::LEFT_EDGE:
{
if (leftEdge)
startPos.x = 0, endPos.x = 1;
else
return;
break;
}
case Region::GenerateMode::FRONT_EDGE:
{
if (frontEdge)
startPos.z = SECTION_SIZEM1, endPos.z = SECTION_SIZE;
else
return;
break;
}
case Region::GenerateMode::BACK_EDGE:
{
if (backEdge)
startPos.z = 0, endPos.z = 1;
else
return;
break;
}
// Region corners only
case Region::GenerateMode::LEFT_BACK_CORNER:
{
if (leftEdge && backEdge)
endPos.x = 1, endPos.z = 1;
else
return;
break;
}
case Region::GenerateMode::RIGHT_BACK_CORNER:
{
if (rightEdge && backEdge)
startPos.x = SECTION_SIZEM1, endPos.z = 1;
else
return;
break;
}
case Region::GenerateMode::RIGHT_FRONT_CORNER:
{
if (rightEdge && frontEdge)
startPos.x = SECTION_SIZEM1, startPos.z = SECTION_SIZEM1;
else
return;
break;
}
case Region::GenerateMode::LEFT_FRONT_CORNER:
{
if (leftEdge && frontEdge)
startPos.z = SECTION_SIZEM1, endPos.x = 1;
else
return;
break;
}
}
// Calculate face/vertex data dimensions per section
faceDataSizeX = endPos.x - startPos.x;
faceDataSizeXZ = faceDataSizeX * (endPos.z - startPos.z);
faceDataSizeTotal = faceDataSizeXZ * SECTION_SIZE;
vertexDataSizeX = endPos.x + 1 - startPos.x;
vertexDataSizeXZ = vertexDataSizeX * (endPos.z + 1 - startPos.z);
vertexDataSizeTotal = vertexDataSizeXZ * SECTION_SIZE;
// Allocate face/vertex data for each section
for (IntType m = 0; m < Region::MeshTypeAmount; m++)
{
for (IntType s = 0; s < CHUNK_SECTIONS; s++)
{
if (Section* section = sections[s])
{
if (section->preview.hasBlocks && (m != Region::TRANSPARENT || section->preview.hasTransparent))
{
meshes[m].faceData[s].Alloc(faceDataSizeTotal);
// Allocate vertex data for this section and next (to support Y=16 vertices outside section)
if (!meshes[m].vertexData[s].Size())
meshes[m].vertexData[s].Alloc(vertexDataSizeTotal);
meshes[m].vertexData[s + 1].Alloc(vertexDataSizeTotal);
}
}
}
}
// Generate block faces
for (IntType s = 0; s < CHUNK_SECTIONS; s++)
if (Section* section = sections[s])
if (section->preview.hasBlocks)
section->GenerateFaces(mode, startPos, endPos);
for (Mesh& mesh : meshes)
{
mesh.vertices.Alloc(8192);
mesh.indices.Alloc(4096);
// Create triangles from faces
for (uint8_t s = 0; s < CHUNK_SECTIONS; s++)
{
uint16_t sy = s * SECTION_SIZE;
Heap<FaceData>& faceData = mesh.faceData[s];
if (!faceData.Size())
continue;
// Right/Left face in XYZ order
for (uint8_t x = startPos.x; x < endPos.x; x++)
for (uint8_t y = 0; y < SECTION_SIZE; y++)
for (uint8_t z = startPos.z; z < endPos.z; z++)
{
GenerateFaceTriangles(mesh, RIGHT, faceData, x, sy + y, z, startPos, endPos);
GenerateFaceTriangles(mesh, LEFT, faceData, x, sy + y, z, startPos, endPos);
}
// Top/Bottom face in YZX order
for (uint8_t y = 0; y < SECTION_SIZE; y++)
for (uint8_t z = startPos.z; z < endPos.z; z++)
for (uint8_t x = startPos.x; x < endPos.x; x++)
{
GenerateFaceTriangles(mesh, TOP, faceData, x, sy + y, z, startPos, endPos);
GenerateFaceTriangles(mesh, BOTTOM, faceData, x, sy + y, z, startPos, endPos);
}
// Front/Back face in ZYX order
for (uint8_t z = startPos.z; z < endPos.z; z++)
for (uint8_t y = 0; y < SECTION_SIZE; y++)
for (uint8_t x = startPos.x; x < endPos.x; x++)
{
GenerateFaceTriangles(mesh, FRONT, faceData, x, sy + y, z, startPos, endPos);
GenerateFaceTriangles(mesh, BACK, faceData, x, sy + y, z, startPos, endPos);
}
}
// Free data
for (uint8_t s = 0; s < CHUNK_SECTIONS; s++)
{
mesh.faceData[s].FreeData();
mesh.vertexData[s].FreeData();
}
}
}
void Chunk::GenerateFaceTriangles(Mesh& mesh, Chunk::FaceDirection dir, Heap<FaceData>& faceData, uint16_t x, uint16_t y, uint16_t z, const WorldVec& startPos, const WorldVec& endPos)
{
IntType faceDataIndex = (y & SECTION_SIZEM1) * faceDataSizeXZ + (z - startPos.z) * faceDataSizeX + (x - startPos.x);
const uint16_t& blockData = faceData.Value(faceDataIndex).blockData[dir];
if (!blockData)
return;
// Make face as big as possible by merging with identical data
WorldVec faceOffset = { 0, 0, 0 };
WorldVec pos = { x, y, z };
// Returns whether the current data is equal to another face at a given position in the chunk
auto faceMatch = [&](const WorldVec& pos, uint16_t*& outBlockData)
{
if (pos.x < startPos.x || pos.y < 0 || pos.z < startPos.z ||
pos.x == endPos.x || pos.y >= CHUNK_HEIGHT_SIZE || pos.z == endPos.z)
return false;
uint8_t sectionIndex = pos.y / SECTION_SIZE;
if (!mesh.faceData[sectionIndex].Size()) // No faces in target section
return false;
uint16_t faceDataIndex = (pos.y & SECTION_SIZEM1) * faceDataSizeXZ + (pos.z - startPos.z) * faceDataSizeX + (pos.x - startPos.x);
outBlockData = &mesh.faceData[sectionIndex][faceDataIndex].blockData[dir];
return *outBlockData == blockData;
};
// Resize in first direction
uint8_t d0;
for (d0 = 1; d0 < SECTION_SIZE; d0++)
{
WorldVec offset = blockFaceMergeVec[dir][0] * d0;
uint16_t* offsetBlockData = nullptr;
if (!faceMatch(pos + offset, offsetBlockData))
break;
*offsetBlockData = 0; // Erase data of face
faceOffset = offset;
}
// Resize in second direction
uint16_t* offsetBlockData[SECTION_SIZE];
for (uint8_t d1 = 1, d2; d1 < SECTION_SIZE; d1++)
{
WorldVec offset = blockFaceMergeVec[dir][1] * d1;
BoolType exit = false;
for (d2 = 0; d2 < d0; d2++) // Check faces in first direction
{
if (!faceMatch(pos + offset, offsetBlockData[d2]))
{
exit = true;
break;
}
offset = offset + blockFaceMergeVec[dir][0];
}
if (exit)
break;
for (uint8_t b = 0; b < d2; b++) // Erase data of row faces
*(offsetBlockData[b]) = 0;
faceOffset = faceOffset + blockFaceMergeVec[dir][1];
}
// Add vertices of face
uint32_t index[4];
WorldVec faceSize = faceOffset + 1;
for (uint8_t c = 0; c < 4; c++)
{
const WorldVec& cornerVec = blockFaceOffset[dir][c];
WorldVec vertPos = pos + cornerVec * faceSize;
IntType vertexDataIndex = (vertPos.y & SECTION_SIZEM1) * vertexDataSizeXZ + (vertPos.z - startPos.z) * vertexDataSizeX + (vertPos.x - startPos.x);
VertexData& vertexData = mesh.vertexData[vertPos.y / SECTION_SIZE][vertexDataIndex];
if (!vertexData.blockData) // First use of vertex
{
vertexData.blockData = blockData;
vertexData.index = index[c] = mesh.vertices.Append({ regionPos + vertPos, blockData });
}
else if (vertexData.blockData == blockData) // Re-use vertex
index[c] = vertexData.index;
else // Unique, add new
index[c] = mesh.vertices.Append({ regionPos + vertPos, blockData });
}
// Add indices for two triangles
mesh.indices.Append(index[0]);
mesh.indices.Append(index[1]);
mesh.indices.Append(index[2]);
mesh.indices.Append(index[2]);
mesh.indices.Append(index[3]);
mesh.indices.Append(index[0]);
}
void Chunk::FreePreviewData()
{
// Section data on edges may be needed for new regions
if (region->generatedAmount < Region::GenerateModeAmount && (leftEdge || rightEdge || backEdge || frontEdge))
return;
// Free mesh generation data
for (IntType i = 0; i < CHUNK_SECTIONS; i++)
{
if (Section* section = sections[i])
{
section->preview.blockStyleIndices.FreeData();
section->preview.states.FreeData();
section->preview.biomeIndices.FreeData();
}
}
}
}
| 412 | 0.939338 | 1 | 0.939338 | game-dev | MEDIA | 0.903496 | game-dev | 0.984721 | 1 | 0.984721 |
boy0001/FastAsyncWorldedit | 4,970 | sponge112/src/main/java/com/boydti/fawe/sponge/FaweSponge.java | package com.boydti.fawe.sponge;
import com.boydti.fawe.Fawe;
import com.boydti.fawe.IFawe;
import com.boydti.fawe.SpongeCommand;
import com.boydti.fawe.config.BBC;
import com.boydti.fawe.object.FaweCommand;
import com.boydti.fawe.object.FawePlayer;
import com.boydti.fawe.object.FaweQueue;
import com.boydti.fawe.regions.FaweMaskManager;
import com.boydti.fawe.util.MainUtil;
import com.boydti.fawe.util.TaskManager;
import com.sk89q.worldedit.sponge.chat.SpongeChatManager;
import com.sk89q.worldedit.world.World;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.UUID;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.profile.GameProfile;
import org.spongepowered.api.profile.GameProfileManager;
import org.spongepowered.api.text.serializer.TextSerializers;
import static org.spongepowered.api.Sponge.getGame;
public class FaweSponge implements IFawe {
public final SpongeMain plugin;
public FaweSponge instance;
public FaweSponge(SpongeMain plugin) {
instance = this;
this.plugin = plugin;
try {
Fawe.set(this);
Fawe.setupInjector();
com.sk89q.worldedit.sponge.SpongePlayer.inject();
Fawe.get().setChatManager(new SpongeChatManager());
} catch (final Throwable e) {
MainUtil.handleError(e);
}
}
@Override
public void debug(String message) {
message = BBC.color(message);
Sponge.getServer().getConsole().sendMessage(TextSerializers.LEGACY_FORMATTING_CODE.deserialize(BBC.color(message)));
}
@Override
public boolean isOnlineMode() {
return Sponge.getServer().getOnlineMode();
}
@Override
public String getPlatformVersion() {
return Sponge.getPlatform().getMinecraftVersion().getName();
}
@Override
public int getPlayerCount() {
return Sponge.getServer().getOnlinePlayers().size();
}
@Override
public File getDirectory() {
return new File("config/FastAsyncWorldEdit");
}
@Override
public void setupCommand(String label, FaweCommand cmd) {
getGame().getCommandManager().register(plugin, new SpongeCommand(cmd), label);
}
@Override
public FawePlayer wrap(Object obj) {
if (obj.getClass() == String.class) {
String name = (String) obj;
FawePlayer existing = Fawe.get().getCachedPlayer(name);
if (existing != null) {
return existing;
}
Player player = Sponge.getServer().getPlayer(name).orElseGet(null);
return player != null ? new SpongePlayer(player) : null;
} else if (obj instanceof Player) {
Player player = (Player) obj;
FawePlayer existing = Fawe.get().getCachedPlayer(player.getName());
return existing != null ? existing : new SpongePlayer(player);
} else {
return null;
}
}
@Override
public void setupVault() {
debug("Permission hook not implemented yet!");
}
@Override
public TaskManager getTaskManager() {
return new SpongeTaskMan(plugin);
}
@Override
public FaweQueue getNewQueue(World world, boolean fast) {
return new com.boydti.fawe.sponge.v1_12.SpongeQueue_1_12(getWorldName(world));
}
@Override
public FaweQueue getNewQueue(String world, boolean fast) {
return new com.boydti.fawe.sponge.v1_12.SpongeQueue_1_12(world);
}
@Override
public String getWorldName(World world) {
return world.getName();
}
@Override
public Collection<FaweMaskManager> getMaskManagers() {
return new ArrayList<>();
}
@Override
public void startMetrics() {
try {
SpongeMetrics metrics = new SpongeMetrics(Sponge.getGame(), Sponge.getPluginManager().fromInstance(plugin).get());
metrics.start();
} catch (Throwable e) {
debug("[FAWE] &cFailed to load up metrics.");
}
}
@Override
public String getPlatform() {
return "sponge";
}
@Override
public UUID getUUID(String name) {
try {
GameProfileManager pm = Sponge.getServer().getGameProfileManager();
GameProfile profile = pm.get(name).get();
return profile != null ? profile.getUniqueId() : null;
} catch (Exception e) {
return null;
}
}
@Override
public String getName(UUID uuid) {
try {
GameProfileManager pm = Sponge.getServer().getGameProfileManager();
GameProfile profile = pm.get(uuid).get();
return profile != null ? profile.getName().orElse(null) : null;
} catch (Exception e) {
return null;
}
}
@Override
public Object getBlocksHubApi() {
return null;
}
}
| 412 | 0.951116 | 1 | 0.951116 | game-dev | MEDIA | 0.796106 | game-dev | 0.949016 | 1 | 0.949016 |
TerraformersMC/Terrestria | 3,429 | worldgen/src/main/java/com/terraformersmc/terrestria/surfacebuilders/CanyonSurfaceBuilder.java | package com.terraformersmc.terrestria.surfacebuilders;
import com.terraformersmc.biolith.api.surface.BiolithSurfaceBuilder;
import com.terraformersmc.terraform.noise.OpenSimplexNoise;
import net.minecraft.block.BlockState;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.random.Random;
import net.minecraft.world.biome.Biome;
import net.minecraft.world.biome.source.BiomeAccess;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.gen.chunk.BlockColumn;
public class CanyonSurfaceBuilder extends BiolithSurfaceBuilder {
private static final OpenSimplexNoise CLIFF_NOISE = new OpenSimplexNoise(346987);
private final BlockState cliffMaterial;
private final BlockState topMaterial;
private final BlockState underMaterial;
public CanyonSurfaceBuilder(BlockState cliffMaterial, BlockState topMaterial, BlockState underMaterial) {
this.cliffMaterial = cliffMaterial;
this.topMaterial = topMaterial;
this.underMaterial = underMaterial;
}
private static int underNoiseToLayers(double noise, int cliffLayers) {
int underLayers = (int) (noise * 3 + 0.5);
if (cliffLayers > 5) {
underLayers += 1;
}
if (cliffLayers > 10) {
underLayers += 3;
}
if (cliffLayers > 15) {
underLayers += 4;
}
return underLayers;
}
/**
* "terraces" the input noise (from 0.0 to 1.0) returning an integer from 1 to 40, inclusive
* Domain: [-1.0, 1.0]
* Range: [1, 40]
*/
private static int cliffNoiseToLayers(double noise) {
// Domain transformation:
// [0.0, 1.0] -> [0, 60]
noise = MathHelper.clamp(noise, 0, 1);
noise *= 60;
int height = 1;
if (noise > 3) {
height += 2;
}
if (noise > 5) {
height += 3;
}
if (noise > 9) {
height += 4;
}
if (noise > 14) {
height += 4;
}
if (noise > 20) {
height += 5;
}
if (noise > 27) {
height += 6;
}
if (noise > 39) {
height += 7;
}
if (noise > 55) {
height += 8;
}
return height;
}
@Override
public void generate(BiomeAccess biomeAccess, BlockColumn column, Random rand, Chunk chunk, Biome biome, int x, int z, int vHeight, int seaLevel) {
if (vHeight < seaLevel + 5) {
// In the future make this dig down instead
// This will break some stuff like water flowing down so it may need an edge biome first
return;
}
int y = seaLevel - 1;
// Generate noise values
double cliffNoise = Math.abs(CLIFF_NOISE.sample(x * 0.015, z * 0.015));
double underNoise = Math.abs(CLIFF_NOISE.sample(x * 0.015 - 1024, z * 0.015 - 1024));
double topNoise = Math.abs(CLIFF_NOISE.sample(x * 0.015 + 1024, z * 0.015 + 1024));
// Prevent huge cliffs near borders, make them slightly smaller cliffs
if (vHeight < seaLevel + 8 && cliffNoise > 0.3) {
// seaLevel+5 -> 1/4, seaLevel+6 -> 2/4, seaLevel+7 -> 3/4
cliffNoise *= (vHeight - seaLevel - 3) * 0.25;
}
// Convert noise values to layer counts
int cliffLayers = cliffNoiseToLayers(cliffNoise);
int underLayers = underNoiseToLayers(underNoise, cliffLayers);
int topLayers = (int) (topNoise * 2.5) + 1;
// Place cliff material
for (int i = 0; i < cliffLayers; i++) {
column.setState(y, cliffMaterial);
++y;
}
// Place under material
for (int i = 0; i < underLayers; i++) {
column.setState(y, underMaterial);
++y;
}
// Place top material
for (int i = 0; i < topLayers; i++) {
column.setState(y, topMaterial);
++y;
}
}
}
| 412 | 0.929305 | 1 | 0.929305 | game-dev | MEDIA | 0.946854 | game-dev | 0.980777 | 1 | 0.980777 |
PPrism/TerrariaOGC | 1,966 | TerrariaOGC/Dependencies/GamerServices/GamerServicesDispatcher.cs | #region License
/* FNA.NetStub - XNA4 Xbox Live Stub DLL
* Copyright 2019 Ethan "flibitijibibo" Lee
*
* Released under the Microsoft Public License.
* See LICENSE for details.
*/
#endregion
#region Using Statements
using System;
using System.Collections.Generic;
#endregion
namespace Microsoft.Xna.Framework.GamerServices
{
public static class GamerServicesDispatcher
{
#region Public Static Properties
public static bool IsInitialized
{
get;
private set;
}
public static IntPtr WindowHandle
{
get;
set;
}
#endregion
#region Public Static Events
#pragma warning disable 0067
// This should never happen, but lol XNA4 compliance -flibit
public static event EventHandler<EventArgs> InstallingTitleUpdate;
#pragma warning restore 0067
#endregion
#region Public Static Methods
public static void Initialize(IServiceProvider serviceProvider)
{
IsInitialized = true;
AppDomain.CurrentDomain.ProcessExit += (o, e) =>
{
IsInitialized = false;
};
List<SignedInGamer> startGamers = new List<SignedInGamer>(1);
startGamers.Add(new SignedInGamer(
"Stub Gamer",
IsInitialized
));
// FIXME: This is stupid -flibit
startGamers.Add(new SignedInGamer(
"Stub Gamer (1)",
IsInitialized,
true,
PlayerIndex.Two
));
startGamers.Add(new SignedInGamer(
"Stub Gamer (2)",
IsInitialized,
true,
PlayerIndex.Three
));
startGamers.Add(new SignedInGamer(
"Stub Gamer (3)",
IsInitialized,
true,
PlayerIndex.Four
));
Gamer.SignedInGamers = new SignedInGamerCollection(startGamers);
foreach (SignedInGamer gamer in Gamer.SignedInGamers)
{
SignedInGamer.OnSignIn(gamer);
}
}
public static void Update()
{
}
internal static bool UpdateAsync()
{
// If a thread's calling this after we quit, tell it to panic!
if (IsInitialized)
{
Update();
}
return IsInitialized;
}
#endregion
}
}
| 412 | 0.817916 | 1 | 0.817916 | game-dev | MEDIA | 0.524752 | game-dev | 0.580395 | 1 | 0.580395 |
bitsai/book-exercises | 2,401 | Learn You a Haskell for Great Good/ch12.hs | import Control.Monad
applyMaybe :: Maybe a -> (a -> Maybe b) -> Maybe b
applyMaybe Nothing f = Nothing
applyMaybe (Just x) f = f x
type Birds = Int
type Pole = (Birds, Birds)
landLeft :: Birds -> Pole -> Maybe Pole
landLeft n (left, right)
| abs ((left + n) - right) < 4 = Just (left + n, right)
| otherwise = Nothing
landRight :: Birds -> Pole -> Maybe Pole
landRight n (left, right)
| abs (left - (right + n)) < 4 = Just (left, right + n)
| otherwise = Nothing
x -: f = f x
banana :: Pole -> Maybe Pole
banana _ = Nothing
foo :: Maybe String
foo = do
x <- Just 3
y <- Just "!"
Just (show x ++ y)
marySue :: Maybe Bool
marySue = do
x <- Just 9
Just (x > 8)
routine :: Maybe Pole
routine = do
start <- return (0, 0)
first <- landLeft 2 start
Nothing
second <- landRight 2 first
landLeft 1 second
wopwop :: Maybe Char
wopwop = do
(x:xs) <- Just ""
return x
listOfTuples :: [(Int, Char)]
listOfTuples = do
n <- [1, 2]
ch <- ['a', 'b']
return (n, ch)
sevensOnly :: [Int]
sevensOnly = do
x <- [1..50]
guard ('7' `elem` show x)
return x
type KnightPos = (Int, Int)
moveKnight :: KnightPos -> [KnightPos]
moveKnight (c, r) = do
(c', r') <- [(c + 2, r - 1), (c + 2, r + 1), (c - 2, r - 1),
(c - 2, r + 1), (c + 1, r - 2), (c + 1, r + 2),
(c - 1, r - 2), (c - 1, r + 2)]
guard (c' `elem` [1..8] && r' `elem` [1..8])
return (c', r')
in3 :: KnightPos -> [KnightPos]
in3 start = do
first <- moveKnight start
second <- moveKnight first
moveKnight second
canReachIn3 :: KnightPos -> KnightPos -> Bool
canReachIn3 start end = end `elem` in3 start
validPos :: KnightPos -> Bool
validPos (c, r) = c `elem` [1..8] && r `elem` [1..8]
nextMoves :: KnightPos -> [KnightPos]
nextMoves (c, r) =
filter validPos [(c + 2, r - 1), (c + 2, r + 1), (c - 2, r - 1),
(c - 2, r + 1), (c + 1, r - 2), (c + 1, r + 2),
(c - 1, r - 2), (c - 1, r + 2)]
moveKnight' :: [KnightPos] -> [[KnightPos]]
moveKnight' moves =
[moves ++ [nextMove] | nextMove <- nextMoves (last moves)]
in3' :: [KnightPos] -> [[KnightPos]]
in3' start = return start >>= moveKnight' >>= moveKnight' >>= moveKnight'
canReachIn3' :: KnightPos -> KnightPos -> [[KnightPos]]
canReachIn3' start end =
let allMoves = in3' [start]
reachesEnd moves = (last moves) == end in
filter reachesEnd allMoves
| 412 | 0.889389 | 1 | 0.889389 | game-dev | MEDIA | 0.769801 | game-dev | 0.993731 | 1 | 0.993731 |
jaseowns/uo_outlands_razor_scripts | 3,796 | outlands.uorazorscripts.com/script/dd62d674-a5b8-4c6d-a6ce-dad424cb990d | # This is an automated backup - check out https://outlands.uorazorscripts.com/script/dd62d674-a5b8-4c6d-a6ce-dad424cb990d for latest
# Automation by Jaseowns
## Script: Pretty Bag Item Stack
## Created by: Jaseowns#6694
#############################################
// Pretty Bag Item Stack by Jaseowns
// move items by type into a stack but offset
# drop prettyBag -1 -1 -1 - same as dropping on the container
# drop prettyBag 0 0 0 - top left of bag
# -info to get the Position coordinates
// @setvar! prettyBag 0x40238ECE
@setvar! prettyBag 0x401E08E3
@setvar! globalTimeout 650
// 100 100 0 center of a backpack and pouch
// 65 75 0 center of a bag
@setvar! itemCounter 0
@setvar! itemStartPositionX 100
@setvar! itemStartPositionY 100
@clearignore
// Earth
while findtype 3985 backpack 2767 as item
if counttype 3985 backpack 2767 as totalItems
@setvar! itemStartPositionY 100
if totalItems = 9
@setvar! itemStartPositionX 100
elseif totalItems = 8
@setvar! itemStartPositionX 101
elseif totalItems = 7
@setvar! itemStartPositionX 102
elseif totalItems = 6
@setvar! itemStartPositionX 103
elseif totalItems = 5
@setvar! itemStartPositionX 104
elseif totalItems = 4
@setvar! itemStartPositionX 105
elseif totalItems = 3
@setvar! itemStartPositionX 106
elseif totalItems = 2
@setvar! itemStartPositionX 107
elseif totalItems = 1
@setvar! itemStartPositionX 108
else
@setvar! itemStartPositionX 100
endif
endif
lift item 1
drop prettyBag itemStartPositionX itemStartPositionY 0
wait globalTimeout
@ignore item
endwhile
// Air
while findtype 3985 backpack 2263 as item
if counttype 3985 backpack 2263 as totalItems
@setvar! itemStartPositionY 150
if totalItems = 9
@setvar! itemStartPositionX 100
elseif totalItems = 8
@setvar! itemStartPositionX 101
elseif totalItems = 7
@setvar! itemStartPositionX 102
elseif totalItems = 6
@setvar! itemStartPositionX 103
elseif totalItems = 5
@setvar! itemStartPositionX 104
elseif totalItems = 4
@setvar! itemStartPositionX 105
elseif totalItems = 3
@setvar! itemStartPositionX 106
elseif totalItems = 2
@setvar! itemStartPositionX 107
elseif totalItems = 1
@setvar! itemStartPositionX 108
else
@setvar! itemStartPositionX 100
endif
endif
lift item 1
drop prettyBag itemStartPositionX itemStartPositionY 0
wait globalTimeout
@ignore item
endwhile
// Blood
while findtype 3985 backpack 2087 as item
if counttype 3985 backpack 2087 as totalItems
@setvar! itemStartPositionY 50
if totalItems = 9
@setvar! itemStartPositionX 100
elseif totalItems = 8
@setvar! itemStartPositionX 101
elseif totalItems = 7
@setvar! itemStartPositionX 102
elseif totalItems = 6
@setvar! itemStartPositionX 103
elseif totalItems = 5
@setvar! itemStartPositionX 104
elseif totalItems = 4
@setvar! itemStartPositionX 105
elseif totalItems = 3
@setvar! itemStartPositionX 106
elseif totalItems = 2
@setvar! itemStartPositionX 107
elseif totalItems = 1
@setvar! itemStartPositionX 108
else
@setvar! itemStartPositionX 100
endif
endif
lift item 1
drop prettyBag itemStartPositionX itemStartPositionY 0
wait globalTimeout
@ignore item
endwhile
@clearignore | 412 | 0.679505 | 1 | 0.679505 | game-dev | MEDIA | 0.928989 | game-dev | 0.707637 | 1 | 0.707637 |
dennyzhang/code.dennyzhang.com | 5,397 | problems/number-of-islands-ii/README.org | * Leetcode: Number of Islands II :BLOG:Medium:
#+STARTUP: showeverything
#+OPTIONS: toc:nil \n:t ^:nil creator:nil d:nil
:PROPERTIES:
:type: unionfind, graph, graphchangecell, island
:END:
---------------------------------------------------------------------
Number of Islands II
---------------------------------------------------------------------
#+BEGIN_HTML
<a href="https://github.com/dennyzhang/code.dennyzhang.com/tree/master/problems/number-of-islands-ii"><img align="right" width="200" height="183" src="https://www.dennyzhang.com/wp-content/uploads/denny/watermark/github.png" /></a>
#+END_HTML
Similar Problems:
- [[https://code.dennyzhang.com/followup-island][Series: Island & Follow-up]]
- [[https://cheatsheet.dennyzhang.com/cheatsheet-leetcode-A4][CheatSheet: Leetcode For Code Interview]]
- [[https://cheatsheet.dennyzhang.com/cheatsheet-followup-A4][CheatSheet: Common Code Problems & Follow-ups]]
- Tag: [[https://code.dennyzhang.com/review-graph][#graph]], [[https://code.dennyzhang.com/review-unionfind][#unionfind]], [[https://code.dennyzhang.com/review-graphchangecell][#graphchangecell]], [[https://code.dennyzhang.com/review-island][#island]]
---------------------------------------------------------------------
A 2d grid map of m rows and n columns is initially filled with water. We may perform an addLand operation which turns the water at position (row, col) into a land. Given a list of positions to operate, count the number of islands after each addLand operation. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example:
Given m = 3, n = 3, positions = [[0,0], [0,1], [1,2], [2,1]].
Initially, the 2d grid grid is filled with water. (Assume 0 represents water and 1 represents land).
#+BEGIN_EXAMPLE
0 0 0
0 0 0
0 0 0
#+END_EXAMPLE
Operation #1: addLand(0, 0) turns the water at grid[0][0] into a land.
#+BEGIN_EXAMPLE
1 0 0
0 0 0 Number of islands = 1
0 0 0
#+END_EXAMPLE
Operation #2: addLand(0, 1) turns the water at grid[0][1] into a land.
#+BEGIN_EXAMPLE
1 1 0
0 0 0 Number of islands = 1
0 0 0
#+END_EXAMPLE
Operation #3: addLand(1, 2) turns the water at grid[1][2] into a land.
#+BEGIN_EXAMPLE
1 1 0
0 0 1 Number of islands = 2
0 0 0
#+END_EXAMPLE
Operation #4: addLand(2, 1) turns the water at grid[2][1] into a land.
#+BEGIN_EXAMPLE
1 1 0
0 0 1 Number of islands = 3
0 1 0
#+END_EXAMPLE
We return the result as an array: [1, 1, 2, 3]
Challenge:
Can you do it in time complexity O(k log mn), where k is the length of the positions?
Github: [[https://github.com/dennyzhang/code.dennyzhang.com/tree/master/problems/number-of-islands-ii][code.dennyzhang.com]]
Credits To: [[https://leetcode.com/problems/number-of-islands-ii/description/][leetcode.com]]
Leave me comments, if you have better ways to solve.
---------------------------------------------------------------------
#+BEGIN_SRC go
// https://code.dennyzhang.com/number-of-islands-ii
// Basic Ideas: unionfind
//
// When add a new position, check with 4 adjacent cells
// If no adjacent islands, increase the counter
// Otherwise, the counter may be the same or decrease
//
// Complexity: Time O(m*n+k), Space O(m*n)
type UF struct {
parent []int
groupCnt int
}
func constructor(size int) UF {
parent := make([]int, size)
for i, _ := range parent {
parent[i] = i
}
return UF{parent:parent}
}
func (uf *UF) union(x, y int) {
n1, n2 := uf.find(x), uf.find(y)
if n1 == n2 {
return
}
if n1>n2{
n1,n2 = n2,n1
x,y = y,x
}
uf.parent[n2] = n1
uf.groupCnt--
}
func (uf *UF) find(x int) int {
// TODO: path compression
for uf.parent[x] != x {
x = uf.parent[x]
}
return x
}
func numIslands2(m int, n int, positions [][]int) []int {
uf := constructor(m*n)
grid := make([][]int, m)
for i, _ := range grid {
grid[i] = make([]int, n)
}
res := make([]int, len(positions))
for k, p := range positions {
i, j := p[0], p[1]
// if current cell is already island, no change
if grid[i][j] == 0 {
grid[i][j] = 1
uf.groupCnt++
for _, offset := range [][]int{[]int{1, 0}, []int{-1, 0}, []int{0, 1}, []int{0, -1}} {
i2, j2 := i+offset[0], j+offset[1]
if i2<0 || i2>=m || j2<0 || j2>=n {
continue
}
if grid[i2][j2] == 1 {
n1, n2 := i*n+j, i2*n+j2
uf.union(n1, n2)
}
}
}
res[k] = uf.groupCnt
}
return res
}
#+END_SRC
#+BEGIN_HTML
<div style="overflow: hidden;">
<div style="float: left; padding: 5px"> <a href="https://www.linkedin.com/in/dennyzhang001"><img src="https://www.dennyzhang.com/wp-content/uploads/sns/linkedin.png" alt="linkedin" /></a></div>
<div style="float: left; padding: 5px"><a href="https://github.com/dennyzhang"><img src="https://www.dennyzhang.com/wp-content/uploads/sns/github.png" alt="github" /></a></div>
<div style="float: left; padding: 5px"><a href="https://www.dennyzhang.com/slack" target="_blank" rel="nofollow"><img src="https://www.dennyzhang.com/wp-content/uploads/sns/slack.png" alt="slack"/></a></div>
</div>
#+END_HTML
| 412 | 0.824284 | 1 | 0.824284 | game-dev | MEDIA | 0.454126 | game-dev | 0.885179 | 1 | 0.885179 |
yigao/NFShmXFrame | 3,393 | game/MMO/NFLogicComm/DescStore/RankingButtonDesc.cpp | #include "RankingButtonDesc.h"
#include "NFComm/NFPluginModule/NFCheck.h"
RankingButtonDesc::RankingButtonDesc()
{
if (EN_OBJ_MODE_INIT == NFShmMgr::Instance()->GetCreateMode()) {
CreateInit();
}
else {
ResumeInit();
}
}
RankingButtonDesc::~RankingButtonDesc()
{
}
int RankingButtonDesc::CreateInit()
{
return 0;
}
int RankingButtonDesc::ResumeInit()
{
return 0;
}
int RankingButtonDesc::Load(NFResDB *pDB)
{
NFLogTrace(NF_LOG_SYSTEMLOG, 0, "--begin--");
CHECK_EXPR(pDB != NULL, -1, "pDB == NULL");
NFLogTrace(NF_LOG_SYSTEMLOG, 0, "RankingButtonDesc::Load() strFileName = {}", GetFileName());
proto_ff::Sheet_RankingButton table;
NFResTable* pResTable = pDB->GetTable(GetFileName());
CHECK_EXPR(pResTable != NULL, -1, "pTable == NULL, GetTable:{} Error", GetFileName());
int iRet = 0;
iRet = pResTable->FindAllRecord(GetDBName(), &table);
CHECK_EXPR(iRet == 0, -1, "FindAllRecord Error:{}", GetFileName());
//NFLogTrace(NF_LOG_SYSTEMLOG, 0, "{}", table.Utf8DebugString());
if ((table.e_rankingbutton_list_size() < 0) || (table.e_rankingbutton_list_size() > (int)(m_astDescMap.max_size())))
{
NFLogError(NF_LOG_SYSTEMLOG, 0, "Invalid TotalNum:{}", table.e_rankingbutton_list_size());
return -2;
}
m_minId = INVALID_ID;
for (int i = 0; i < (int)table.e_rankingbutton_list_size(); i++)
{
const proto_ff::E_RankingButton& desc = table.e_rankingbutton_list(i);
if (desc.has_m_buttonid() == false && desc.ByteSize() == 0)
{
NFLogError(NF_LOG_SYSTEMLOG, 0, "the desc no value, {}", desc.Utf8DebugString());
continue;
}
if (m_minId == INVALID_ID)
{
m_minId = desc.m_buttonid();
}
else
{
if (desc.m_buttonid() < m_minId)
{
m_minId = desc.m_buttonid();
}
}
//NFLogTrace(NF_LOG_SYSTEMLOG, 0, "{}", desc.Utf8DebugString());
if (m_astDescMap.find(desc.m_buttonid()) != m_astDescMap.end())
{
if (IsReloading())
{
auto pDesc = GetDesc(desc.m_buttonid());
NF_ASSERT_MSG(pDesc, "the desc:{} Reload, GetDesc Failed!, id:{}", GetClassName(), desc.m_buttonid());
pDesc->read_from_pbmsg(desc);
}
else
{
NFLogError(NF_LOG_SYSTEMLOG, 0, "the desc:{} id:{} exist", GetClassName(), desc.m_buttonid());
}
continue;
}
CHECK_EXPR_ASSERT(m_astDescMap.size() < m_astDescMap.max_size(), -1, "m_astDescMap Space Not Enough");
auto pDesc = &m_astDescMap[desc.m_buttonid()];
CHECK_EXPR_ASSERT(pDesc, -1, "m_astDescMap Insert Failed desc.id:{}", desc.m_buttonid());
pDesc->read_from_pbmsg(desc);
CHECK_EXPR_ASSERT(GetDesc(desc.m_buttonid()) == pDesc, -1, "GetDesc != pDesc, id:{}", desc.m_buttonid());
}
for(int i = 0; i < (int)m_astDescIndex.size(); i++)
{
m_astDescIndex[i] = INVALID_ID;
}
for(auto iter = m_astDescMap.begin(); iter != m_astDescMap.end(); iter++)
{
int64_t index = (int64_t)iter->first - (int64_t)m_minId;
if (index >= 0 && index < (int64_t)m_astDescIndex.size())
{
m_astDescIndex[index] = iter.m_curNode->m_self;
CHECK_EXPR_ASSERT(iter == m_astDescMap.get_iterator(m_astDescIndex[index]), -1, "index error");
CHECK_EXPR_ASSERT(GetDesc(iter->first) == &iter->second, -1, "GetDesc != iter->second, id:{}", iter->first);
}
}
NFLogTrace(NF_LOG_SYSTEMLOG, 0, "load {}, num={}", iRet, table.e_rankingbutton_list_size());
NFLogTrace(NF_LOG_SYSTEMLOG, 0, "--end--");
return 0;
}
int RankingButtonDesc::CheckWhenAllDataLoaded()
{
return 0;
}
| 412 | 0.967096 | 1 | 0.967096 | game-dev | MEDIA | 0.49498 | game-dev,databases | 0.983003 | 1 | 0.983003 |
MarkGG8181/stripped-1.8.9 | 1,775 | src/main/java/net/minecraft/nbt/NBTTagByte.java | package net.minecraft.nbt;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
public class NBTTagByte extends NBTBase.NBTPrimitive {
/**
* The byte value for the tag.
*/
private byte data;
NBTTagByte() {
}
public NBTTagByte(byte data) {
this.data = data;
}
/**
* Write the actual data contents of the tag, implemented in NBT extension classes
*/
void write(DataOutput output) throws IOException {
output.writeByte(this.data);
}
void read(DataInput input, int depth, NBTSizeTracker sizeTracker) throws IOException {
sizeTracker.read(72L);
this.data = input.readByte();
}
/**
* Gets the type byte for the tag.
*/
public byte getId() {
return (byte)1;
}
@Override
public String toString() {
return this.data + "b";
}
/**
* Creates a clone of the tag.
*/
public NBTBase copy() {
return new NBTTagByte(this.data);
}
public boolean equals(Object p_equals_1_) {
if (super.equals(p_equals_1_)) {
NBTTagByte nbttagbyte = (NBTTagByte)p_equals_1_;
return this.data == nbttagbyte.data;
}
else {
return false;
}
}
public int hashCode() {
return super.hashCode() ^ this.data;
}
public long getLong() {
return (long)this.data;
}
public int getInt() {
return this.data;
}
public short getShort() {
return (short)this.data;
}
public byte getByte() {
return this.data;
}
public double getDouble() {
return (double)this.data;
}
public float getFloat() {
return (float)this.data;
}
}
| 412 | 0.721914 | 1 | 0.721914 | game-dev | MEDIA | 0.517019 | game-dev,networking | 0.626718 | 1 | 0.626718 |
dcaslin/d2-checklist | 5,914 | src/app/gear/gear/shard-mode-dialog/shard-mode-dialog.component.ts | import { ChangeDetectionStrategy, Component, Inject, OnInit } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { GearService } from '@app/service/gear.service';
import { IconService } from '@app/service/icon.service';
import { GearMetaData, InventoryItem, ItemType, Player } from '@app/service/model';
import { NotificationService } from '@app/service/notification.service';
import { StorageService } from '@app/service/storage.service';
import { ChildComponent } from '@app/shared/child.component';
import { BehaviorSubject, Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { GearComponent } from '../gear.component';
interface Tuple {
held: number;
toMove: number;
}
interface ShardModeDialogData {
junkWeapons: Tuple;
junkArmor: Tuple;
junkAll: Tuple;
blueWeapons: Tuple;
blueArmor: Tuple;
blueAll: Tuple;
}
function buildEmptyData(): ShardModeDialogData {
return {
junkWeapons: { held: 0, toMove: 0 },
junkArmor: { held: 0, toMove: 0 },
junkAll: { held: 0, toMove: 0 },
blueWeapons: { held: 0, toMove: 0 },
blueArmor: { held: 0, toMove: 0 },
blueAll: { held: 0, toMove: 0 }
};
}
@Component({
changeDetection: ChangeDetectionStrategy.OnPush,
selector: 'd2c-shard-mode-dialog',
templateUrl: './shard-mode-dialog.component.html',
styleUrls: ['./shard-mode-dialog.component.scss']
})
export class ShardModeDialogComponent extends ChildComponent {
parent: GearComponent;
ItemType = ItemType;
data$ = new BehaviorSubject<ShardModeDialogData>(buildEmptyData());
operating$ = new BehaviorSubject<boolean>(false);
gm$ = new BehaviorSubject<GearMetaData>(null);
constructor(
storageService: StorageService,
public iconService: IconService,
public dialogRef: MatDialogRef<ShardModeDialogComponent>,
public gearService: GearService,
private notificationService: NotificationService,
@Inject(MAT_DIALOG_DATA) public data: any) {
super(storageService);
this.parent = data.parent;
// subscribe to parent's filter updates
this.parent.player$.pipe(takeUntil(this.unsubscribe$)).subscribe((player: Player) => {
if (!player) {
return;
}
this.gm$.next(player.gearMetaData);
const target = player.characters[0];
data = buildEmptyData();
for (const item of player.gear) {
if (!(item.type == ItemType.Weapon || item.type == ItemType.Armor)) {
continue;
}
const held = item.owner.getValue().id == target.id;
if (item.tier == 'Rare' && (item.mark == 'junk' || item.mark == null)) {
if (item.type == ItemType.Weapon) {
// is item held by current char
held ? data.blueWeapons.held++ : data.blueWeapons.toMove++;
} else if (item.type == ItemType.Armor) {
held ? data.blueArmor.held++ : data.blueArmor.toMove++;
}
held ? data.blueAll.held++ : data.blueAll.toMove++;
}
if (item.mark == 'junk') {
if (item.type == ItemType.Weapon) {
held ? data.junkWeapons.held++ : data.junkWeapons.toMove++;
} else if (item.type == ItemType.Armor) {
held ? data.junkArmor.held++ : data.junkArmor.toMove++;
}
held ? data.junkAll.held++ : data.junkAll.toMove++;
}
}
this.data$.next(data);
});
}
public async syncLocks() {
this.operating$.next(true);
try {
this.parent.gearService.setExplicitOperatingOnMessage(`Refreshing inventory from Bungie`);
await this.parent.load(true);
await this.parent.gearService.processGearLocks(this.parent.player$.getValue(), true);
} finally {
this.parent.gearService.clearOperatingOn();
this.operating$.next(false);
}
}
public async shardMode(itemType?: ItemType) {
this.operating$.next(true);
try {
this.parent.gearService.setExplicitOperatingOnMessage(`Refreshing inventory from Bungie`);
await this.parent.load(true);
// dummy subject to avoid repainting gear component prematurely
const msg = await this.parent.gearService.shardMode(this.parent.player$.getValue(), new Subject<void>(), itemType);
this.parent.gearFilterStateService.filterUpdated$.next();
await this.parent.load(true);
await this.parent.syncLocks();
this.parent.gearFilterStateService.filterUpdated$.next();
this.notificationService.success(msg);
} finally {
this.parent.gearService.clearOperatingOn();
this.operating$.next(false);
}
}
public async shardBlues(itemType?: ItemType) {
this.operating$.next(true);
try {
this.parent.gearService.setExplicitOperatingOnMessage(`Refreshing inventory from Bungie`);
await this.parent.load(true);
const msg = await this.parent.gearService.shardBlues(this.parent.player$.getValue(), new Subject<void>(), itemType);
await this.parent.load(true);
await this.parent.syncLocks();
this.parent.gearFilterStateService.filterUpdated$.next();
this.notificationService.success(msg);
} finally {
this.parent.gearService.clearOperatingOn();
this.operating$.next(false);
}
}
public async emptyVault() {
this.operating$.next(true);
try {
this.parent.gearService.setExplicitOperatingOnMessage(`Refreshing inventory from Bungie`);
await this.parent.load(true);
const totalMoved = await this.parent.gearService.emptyVault(this.parent.player$.getValue(), new Subject<void>());
await this.parent.load(true);
await this.parent.syncLocks();
this.parent.gearFilterStateService.filterUpdated$.next();
this.notificationService.info(`Moved ${totalMoved} items from vault to idle characters.`);
} finally {
this.parent.gearService.clearOperatingOn();
this.operating$.next(false);
}
}
}
| 412 | 0.950493 | 1 | 0.950493 | game-dev | MEDIA | 0.914459 | game-dev | 0.985231 | 1 | 0.985231 |
GalacticDynamics-Oxford/Agama | 2,269 | src/particles_io.h | /** \file particles_io.h
\brief Input/output of Nbody snapshots in various formats
\author EV
\date 2010-2020
The routines 'readSnapshot' and 'writeSnapshot' provide the top-level interface
to a variety of file formats (Text, NEMO, Gadget).
*/
#pragma once
#include "particles_base.h"
#include "units.h"
#include <string>
namespace particles {
/** Read an N-body snapshot in arbitrary format.
\param[in] fileName is the file to read, its format is determined automatically;
\param[in] unitConverter is the instance of unit conversion object (may be a trivial one);
\returns a new instance of ParticleArray containing the particles read from the file.
*/
ParticleArrayAux readSnapshot(
const std::string& fileName,
const units::ExternalUnits& unitConverter = units::ExternalUnits());
/** Write an N-body snapshot in the given format.
\param[in] fileName is the file to write;
\param[in] particles is the array of particles to write;
\param[in] fileFormat is the string specifying the output file format
(only the first letter matters, case-insensitive: 't' - Text, 'n' - Nemo, 'g' - Gadget);
\param[in] unitConverter is the optional instance of unit conversion (may be a trivial one);
\param[in] header is the optional header string (not for all formats);
\param[in] time is the timestamp of the snapshot (not for all formats);
\param[in] append is the flag specifying whether to append to an existing file or
overwrite the file (only for Nemo format, other formats always overwrite).
\throw std::runtime_error if the format name string is incorrect, or file name is empty,
or if the file could not be written.
\tparam particle type: could be position in some coordinate system (e.g. PosCar),
or position+velocity (e.g. PosVelCyl), or particle with additional attributes (ParticleAux)
*/
template<typename ParticleT>
void writeSnapshot(
const std::string& fileName,
const ParticleArray<ParticleT>& particles,
const std::string &fileFormat="Text",
const units::ExternalUnits& unitConverter = units::ExternalUnits(),
const std::string& header="",
const double time=NAN,
const bool append=false);
} // namespace
| 412 | 0.903949 | 1 | 0.903949 | game-dev | MEDIA | 0.25149 | game-dev | 0.771712 | 1 | 0.771712 |
EssentialGG/Essential-Mod | 3,008 | src/main/kotlin/gg/essential/gui/friends/message/v2/SkinEmbedImpl.kt | /*
* Copyright (c) 2024 ModCore Inc. All rights reserved.
*
* This code is part of ModCore Inc.'s Essential Mod repository and is protected
* under copyright registration # TX0009138511. For the full license, see:
* https://github.com/EssentialGG/Essential/blob/main/LICENSE
*
* You may not use, copy, reproduce, modify, sell, license, distribute,
* commercialize, or otherwise exploit, or create derivative works based
* upon, this file or any other in this repository, all of which is reserved by Essential.
*/
package gg.essential.gui.friends.message.v2
import gg.essential.Essential
import gg.essential.elementa.constraints.*
import gg.essential.elementa.dsl.*
import gg.essential.gui.EssentialPalette
import gg.essential.gui.elementa.state.v2.stateOf
import gg.essential.gui.layoutdsl.*
import gg.essential.gui.notification.Notifications
import gg.essential.gui.util.hoveredState
import gg.essential.gui.wardrobe.modals.SkinModal
import gg.essential.mod.Skin
import gg.essential.mod.cosmetics.CosmeticSlot
import gg.essential.mod.cosmetics.preview.PerspectiveCamera
import gg.essential.universal.USound
import gg.essential.util.*
import gg.essential.util.GuiEssentialPlatform.Companion.platform
import gg.essential.vigilance.utils.onLeftClick
class SkinEmbedImpl(
skin: Skin,
messageWrapper: MessageWrapper,
) : SkinEmbed(skin, messageWrapper) {
init {
colorState.rebind(hoveredState().map { if (it) EssentialPalette.GRAY_BUTTON_HOVER else EssentialPalette.GRAY_BUTTON })
constrain {
width = ChildBasedMaxSizeConstraint()
height = ChildBasedMaxSizeConstraint()
}
val ui3DPlayer = platform.newUIPlayer(
camera = stateOf(PerspectiveCamera.forCosmeticSlot(CosmeticSlot.FULL_BODY)),
profile = stateOf(Pair(skin, null)),
cosmetics = stateOf(emptyMap()),
)
bubble.layoutAsBox(Modifier.width(103f).height(106f).hoverScope()) {
ui3DPlayer(Modifier.height(73f))
icon(EssentialPalette.EXPAND_6X, Modifier.alignBoth(Alignment.End(6f)).color(EssentialPalette.TEXT).hoverColor(EssentialPalette.TEXT_HIGHLIGHT))
}
val cosmeticsManager = Essential.getInstance().connectionManager.cosmeticsManager
val skinsManager = Essential.getInstance().connectionManager.skinsManager
bubble.onLeftClick {
if (skinsManager.skins.get().size >= cosmeticsManager.wardrobeSettings.skinsLimit.get()) {
Notifications.push("Error adding skin", "You have the maximum number of skins!")
return@onLeftClick
}
USound.playButtonPress()
GuiUtil.pushModal {
SkinModal.add(it, skin, initialName = skinsManager.getNextIncrementalSkinName())
}
}
bubble.onRightClick {
messageWrapper.openOptionMenu(it, this@SkinEmbedImpl)
}
}
override fun beginHighlight() {}
override fun releaseHighlight() {}
}
| 412 | 0.628764 | 1 | 0.628764 | game-dev | MEDIA | 0.962901 | game-dev | 0.72611 | 1 | 0.72611 |
MaartenKok8/PneumaticCraft | 1,873 | src/pneumaticCraft/common/thirdparty/waila/WailaFMPHandler.java | package pneumaticCraft.common.thirdparty.waila;
import java.util.List;
import mcp.mobius.waila.api.IWailaConfigHandler;
import mcp.mobius.waila.api.IWailaFMPAccessor;
import mcp.mobius.waila.api.IWailaFMPProvider;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import pneumaticCraft.common.block.BlockPressureTube;
import pneumaticCraft.common.block.tubes.TubeModule;
import pneumaticCraft.common.thirdparty.ModInteractionUtils;
import pneumaticCraft.common.tileentity.TileEntityPressureTube;
public class WailaFMPHandler implements IWailaFMPProvider{
@Override
public List<String> getWailaHead(ItemStack itemStack, List<String> currenttip, IWailaFMPAccessor accessor, IWailaConfigHandler config){
return currenttip;
}
@Override
public List<String> getWailaBody(ItemStack itemStack, List<String> currenttip, IWailaFMPAccessor accessor, IWailaConfigHandler config){
TileEntityPressureTube tube = ModInteractionUtils.getInstance().getTube(accessor.getTileEntity());
if(tube != null) {
NBTTagCompound tubeTag = accessor.getNBTData().getCompoundTag("tube");
tube.currentAir = tubeTag.getInteger("currentAir");
WailaPneumaticHandler.addTipToMachine(currenttip, tube);
TubeModule module = BlockPressureTube.getLookedModule(accessor.getWorld(), accessor.getTileEntity().xCoord, accessor.getTileEntity().yCoord, accessor.getTileEntity().zCoord, accessor.getPlayer());
if(module != null) {
WailaTubeModuleHandler.addModuleInfo(currenttip, tube, tubeTag, module.getDirection());
}
}
return currenttip;
}
@Override
public List<String> getWailaTail(ItemStack itemStack, List<String> currenttip, IWailaFMPAccessor accessor, IWailaConfigHandler config){
return currenttip;
}
}
| 412 | 0.831201 | 1 | 0.831201 | game-dev | MEDIA | 0.549596 | game-dev | 0.591926 | 1 | 0.591926 |
FeatureIDE/FeatureIDE | 1,932 | plugins/de.ovgu.featureide.fm.ui/src/de/ovgu/featureide/fm/ui/editors/featuremodel/actions/CollapseLevelAction.java | package de.ovgu.featureide.fm.ui.editors.featuremodel.actions;
import static de.ovgu.featureide.fm.core.localization.StringTable.LEVEL;
import static de.ovgu.featureide.fm.core.localization.StringTable.LEVELS;
import static de.ovgu.featureide.fm.core.localization.StringTable.SHOW;
import org.eclipse.jface.resource.ImageDescriptor;
import de.ovgu.featureide.fm.ui.FMUIPlugin;
import de.ovgu.featureide.fm.ui.editors.IGraphicalFeatureModel;
import de.ovgu.featureide.fm.ui.editors.featuremodel.operations.CollapseLevelOperation;
import de.ovgu.featureide.fm.ui.editors.featuremodel.operations.FeatureModelOperationWrapper;
/**
* Action to show the subtree up to a certain level. See {@link CollapseLevelOperation}.
*
* @author Philipp Vulpius
* @author Soeren Viegener
*/
public class CollapseLevelAction extends SingleSelectionAction {
public static final String ID = "de.ovgu.featureide.collapselevel";
private final ImageDescriptor imageDescriptor = FMUIPlugin.getDefault().getImageDescriptor("icons/expand.gif");
private final IGraphicalFeatureModel graphicalFeatureModel;
private final int level;
/**
* @param viewer viewer that calls this action
* @param graphicalFeatureModel graphical feature model
* @param level level to which the subtree is shown, starting with the selected feature.
*/
public CollapseLevelAction(Object viewer, IGraphicalFeatureModel graphicalFeatureModel, int level) {
// label: "Show 3 Levels" or "Show 1 Level"
super(SHOW + " " + level + " " + ((level == 1) ? LEVEL : LEVELS), viewer, ID, graphicalFeatureModel.getFeatureModelManager());
setImageDescriptor(imageDescriptor);
this.graphicalFeatureModel = graphicalFeatureModel;
this.level = level;
}
@Override
public void run() {
FeatureModelOperationWrapper.run(new CollapseLevelOperation(getSelectedFeature().getName(), graphicalFeatureModel, level));
}
@Override
protected void updateProperties() {}
}
| 412 | 0.942404 | 1 | 0.942404 | game-dev | MEDIA | 0.632005 | game-dev | 0.985433 | 1 | 0.985433 |
onnoj/DeusExEchelonRenderer | 2,492 | INCLUDE/deusex/Editor/Inc/EditorClasses.h | /*===========================================================================
C++ class definitions exported from UnrealScript.
This is automatically generated by the tools.
DO NOT modify this manually! Edit the corresponding .uc files instead!
===========================================================================*/
#if _MSC_VER
#pragma pack (push,4)
#endif
#ifndef EDITOR_API
#define EDITOR_API DLL_IMPORT
#endif
#ifndef NAMES_ONLY
#define AUTOGENERATE_NAME(name) extern EDITOR_API FName EDITOR_##name;
#define AUTOGENERATE_FUNCTION(cls,idx,name)
#endif
AUTOGENERATE_NAME(Build)
#ifndef NAMES_ONLY
struct UBrushBuilder_eventBuild_Parms
{
BITFIELD ReturnValue;
};
class EDITOR_API UBrushBuilder : public UObject
{
public:
TArray<FVector> Vertices;
TArray<FBuilderPoly> Polys;
FName Group;
BITFIELD MergeCoplanars:1 GCC_PACK(4);
DECLARE_FUNCTION(execPolyEnd);
DECLARE_FUNCTION(execPolyi);
DECLARE_FUNCTION(execPolyBegin);
DECLARE_FUNCTION(execPoly4i);
DECLARE_FUNCTION(execPoly3i);
DECLARE_FUNCTION(execVertex3f);
DECLARE_FUNCTION(execVertexv);
DECLARE_FUNCTION(execBadParameters);
DECLARE_FUNCTION(execGetPolyCount);
DECLARE_FUNCTION(execGetVertex);
DECLARE_FUNCTION(execGetVertexCount);
DECLARE_FUNCTION(execEndBrush);
DECLARE_FUNCTION(execBeginBrush);
BITFIELD eventBuild()
{
UBrushBuilder_eventBuild_Parms Parms;
Parms.ReturnValue=0;
ProcessEvent(FindFunctionChecked(EDITOR_Build),&Parms);
return Parms.ReturnValue;
}
DECLARE_CLASS(UBrushBuilder,UObject,0)
#include "UBrushBuilder.h"
};
#endif
AUTOGENERATE_FUNCTION(UBrushBuilder,-1,execPolyEnd);
AUTOGENERATE_FUNCTION(UBrushBuilder,-1,execPolyi);
AUTOGENERATE_FUNCTION(UBrushBuilder,-1,execPolyBegin);
AUTOGENERATE_FUNCTION(UBrushBuilder,-1,execPoly4i);
AUTOGENERATE_FUNCTION(UBrushBuilder,-1,execPoly3i);
AUTOGENERATE_FUNCTION(UBrushBuilder,-1,execVertex3f);
AUTOGENERATE_FUNCTION(UBrushBuilder,-1,execVertexv);
AUTOGENERATE_FUNCTION(UBrushBuilder,-1,execBadParameters);
AUTOGENERATE_FUNCTION(UBrushBuilder,-1,execGetPolyCount);
AUTOGENERATE_FUNCTION(UBrushBuilder,-1,execGetVertex);
AUTOGENERATE_FUNCTION(UBrushBuilder,-1,execGetVertexCount);
AUTOGENERATE_FUNCTION(UBrushBuilder,-1,execEndBrush);
AUTOGENERATE_FUNCTION(UBrushBuilder,-1,execBeginBrush);
#ifndef NAMES_ONLY
#undef AUTOGENERATE_NAME
#undef AUTOGENERATE_FUNCTION
#endif NAMES_ONLY
#if _MSC_VER
#pragma pack (pop)
#endif
| 412 | 0.60703 | 1 | 0.60703 | game-dev | MEDIA | 0.377953 | game-dev | 0.628504 | 1 | 0.628504 |
orange-cpp/omath | 3,421 | include/omath/engines/unreal_engine/traits/pred_engine_trait.hpp | //
// Created by Vlad on 8/6/2025.
//
#pragma once
#include "omath/engines/unreal_engine/formulas.hpp"
#include "omath/projectile_prediction/projectile.hpp"
#include "omath/projectile_prediction/target.hpp"
#include <optional>
namespace omath::unreal_engine
{
class PredEngineTrait final
{
public:
constexpr static Vector3<float> predict_projectile_position(const projectile_prediction::Projectile& projectile,
const float pitch, const float yaw,
const float time, const float gravity) noexcept
{
auto current_pos = projectile.m_origin
+ forward_vector({PitchAngle::from_degrees(-pitch), YawAngle::from_degrees(yaw),
RollAngle::from_degrees(0)})
* projectile.m_launch_speed * time;
current_pos.y -= (gravity * projectile.m_gravity_scale) * (time * time) * 0.5f;
return current_pos;
}
[[nodiscard]]
static constexpr Vector3<float> predict_target_position(const projectile_prediction::Target& target,
const float time, const float gravity) noexcept
{
auto predicted = target.m_origin + target.m_velocity * time;
if (target.m_is_airborne)
predicted.y -= gravity * (time * time) * 0.5f;
return predicted;
}
[[nodiscard]]
static float calc_vector_2d_distance(const Vector3<float>& delta) noexcept
{
return std::sqrt(delta.x * delta.x + delta.z * delta.z);
}
[[nodiscard]]
constexpr static float get_vector_height_coordinate(const Vector3<float>& vec) noexcept
{
return vec.y;
}
[[nodiscard]]
static Vector3<float> calc_viewpoint_from_angles(const projectile_prediction::Projectile& projectile,
Vector3<float> predicted_target_position,
const std::optional<float> projectile_pitch) noexcept
{
const auto delta2d = calc_vector_2d_distance(predicted_target_position - projectile.m_origin);
const auto height = delta2d * std::tan(angles::degrees_to_radians(projectile_pitch.value()));
return {predicted_target_position.x, predicted_target_position.y, projectile.m_origin.z + height};
}
// Due to specification of maybe_calculate_projectile_launch_pitch_angle, pitch angle must be:
// 89 look up, -89 look down
[[nodiscard]]
static float calc_direct_pitch_angle(const Vector3<float>& origin, const Vector3<float>& view_to) noexcept
{
const auto direction = (view_to - origin).normalized();
return angles::radians_to_degrees(std::asin(direction.z));
}
[[nodiscard]]
static float calc_direct_yaw_angle(const Vector3<float>& origin, const Vector3<float>& view_to) noexcept
{
const auto direction = (view_to - origin).normalized();
return angles::radians_to_degrees(std::atan2(direction.y, direction.x));
};
};
} // namespace omath::unreal_engine
| 412 | 0.676873 | 1 | 0.676873 | game-dev | MEDIA | 0.910909 | game-dev | 0.948085 | 1 | 0.948085 |
eaglerforge/EaglerForge-old | 7,607 | sources/main/java/net/eaglerforge/gui/GuiMods.java | package net.eaglerforge.gui;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.teavm.jso.JSBody;
import com.google.common.collect.Lists;
import net.lax1dude.eaglercraft.v1_8.EagRuntime;
import net.lax1dude.eaglercraft.v1_8.internal.FileChooserResult;
import net.lax1dude.eaglercraft.v1_8.internal.vfs2.VFile2;
import net.lax1dude.eaglercraft.v1_8.log4j.LogManager;
import net.lax1dude.eaglercraft.v1_8.log4j.Logger;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiListExtended;
import net.minecraft.client.gui.GuiOptionButton;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.GuiSelectWorld;
import net.minecraft.client.gui.GuiSlot;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.resources.I18n;
public class GuiMods extends GuiScreen {
private static final Logger logger = LogManager.getLogger();
private final GuiScreen parentScreen;
public ArrayList<VFile2> modList;
public int selectedModIdx = -1;
private GuiModList rows;
public Minecraft mc = Minecraft.getMinecraft();
private GuiButton deleteButton;
@JSBody(params = { "name" }, script = "return window.prompt(name, '') || '';")
private static native String prompt(String name);
public void updateModsList() {
// what is this 'vfs' thing! doesn't even have ability to index a directory!!
try {
VFile2 modListData = new VFile2("mods.txt");
modList = new ArrayList<VFile2>();
if (modListData.getAllChars() == null) {
modListData.setAllChars("");
}
String[] filenames = modListData.getAllChars().split("\\|");
System.out.println(filenames.toString());
for (int i = 0; i < filenames.length; i++) {
if (filenames[i] != "") {
modList.add(new VFile2("mods", filenames[i]));
}
}
} catch (Exception e) {
// TODO: handle exception
}
}
public GuiMods(GuiScreen parentScreenIn) {
this.parentScreen = parentScreenIn;
updateModsList();
}
/**
* +
* Adds the buttons (and other controls) to the screen in
* question. Called when the GUI is displayed and when the
* window resizes, the buttonList is cleared beforehand.
*/
public void initGui() {
GuiButton btn;
this.buttonList.add(btn = new GuiOptionButton(1, this.width / 2 - 154, this.height - 24,
I18n.format("eaglerforge.menu.mods.addmod"
+ "", new Object[0])));
this.buttonList.add(btn = new GuiOptionButton(2, this.width / 2, this.height - 24,
I18n.format("gui.done"
+ "", new Object[0])));
this.buttonList.add(deleteButton = new GuiOptionButton(3, this.width / 2 - 154, this.height - 48,
I18n.format("selectWorld.delete"
+ "", new Object[0])));
this.buttonList.add(btn = new GuiOptionButton(4, this.width / 2, this.height - 48,
I18n.format("eaglerforge.menu.mods.addmodurl"
+ "", new Object[0])));
deleteButton.enabled = false;
rows = new GuiModList(Minecraft.getMinecraft(), this.width, this.height, 48, this.height - 56, 14, this);
rows.registerScrollButtons(4, 5);
}
public void handleMouseInput() throws IOException {
super.handleMouseInput();
this.rows.handleMouseInput();
}
/**
* +
* Called by the controls from the buttonList when activated.
* (Mouse pressed for buttons)
*/
protected void actionPerformed(GuiButton parGuiButton) {
if (parGuiButton.enabled) {
if (parGuiButton.id == 2) {
Minecraft.getMinecraft().displayGuiScreen(parentScreen);
} else if (parGuiButton.id == 1) {
EagRuntime.displayFileChooser("text/javascript", "js");
} else if (parGuiButton.id == 3) {
VFile2 modListData = new VFile2("mods.txt");
String[] mods = modListData.getAllChars().split("\\|");
String[] mods_new = new String[mods.length - 1];
for (int i = 0, k = 0; i < mods.length; i++) {
if (i != selectedModIdx) {
mods_new[k] = mods[i];
k++;
}
}
modListData.setAllChars(String.join("|", mods_new));
//After a bunch of debugging, I think this doesn't properly cleanup anything, as indexedDb is still polluted with deleted mods.
try {
modList.get(selectedModIdx).delete();
} catch (Exception e) {
// remote mod (url)
}
updateModsList();
} else if (parGuiButton.id == 4) {
String url = GuiMods.prompt("Enter the mod url: ");
if (url != "" && url != null) {
VFile2 modListData = new VFile2("mods.txt");
String[] mods = modListData.getAllChars().split("\\|");
String[] mods_new = new String[mods.length + 1];
for (int i = 0; i < mods.length; i++) {
mods_new[i] = mods[i];
}
mods_new[mods.length] = "web@" + url;
modListData.setAllChars(String.join("|", mods_new));
updateModsList();
}
} else {
rows.actionPerformed(parGuiButton);
}
} else {
rows.actionPerformed(parGuiButton);
}
}
/**
* +
* Draws the screen and all the components in it. Args : mouseX,
* mouseY, renderPartialTicks
*/
public void drawScreen(int i, int j, float f) {
this.drawBackground(0);
this.rows.drawScreen(i, j, f);
this.drawCenteredString(this.fontRendererObj, I18n.format("eaglerforge.menu.mods", new Object[0]),
this.width / 2,
8, 0xFFFFFF);
mc.fontRendererObj.drawSplitString(
"Warning: Mods can run any Javascript code they want, potentially running malicious code. They can also ip-grab you and wipe all saved Eaglercraft data.",
0, 24, this.width - 20, 0xFF2200); // I18n.format("eaglerforge.menu.mods.info", new Object[0]) Don't
// know where
// to change this, so hardcoded for now :P
super.drawScreen(i, j, f);
}
public void updateScreen() {
FileChooserResult modFile = null;
if (EagRuntime.fileChooserHasResult()) {
modFile = EagRuntime.getFileChooserResult();
VFile2 idbModFile = new VFile2("mods", modFile.fileName);
idbModFile.setAllBytes(modFile.fileData);
VFile2 modListData = new VFile2("mods.txt");
String[] mods = modListData.getAllChars().split("\\|");
String[] mods_new = new String[mods.length + 1];
for (int i = 0; i < mods.length; i++) {
mods_new[i] = mods[i];
}
mods_new[mods.length] = modFile.fileName;
modListData.setAllChars(String.join("|", mods_new));
updateModsList();
}
}
private class GuiModList extends GuiSlot {
private GuiMods parentGui;
private int slotHeight;
public GuiModList(Minecraft mcIn, int widthIn, int heightIn, int topIn, int bottomIn, int slotHeightIn,
GuiMods parent) {
super(mcIn, widthIn, heightIn, topIn, bottomIn, slotHeightIn);
parentGui = parent;
slotHeight = slotHeightIn;
setEnabled(true);
}
@Override
protected int getContentHeight() {
return parentGui.modList.size() * slotHeight;
}
@Override
protected int getSize() {
return parentGui.modList.size();
}
@Override
protected void elementClicked(int index, boolean isDoubleClick, int mouseX, int mouseY) {
// Handle the event when an element is clicked
parentGui.selectedModIdx = index;
parentGui.deleteButton.enabled = true;
}
@Override
protected boolean isSelected(int index) {
// Return true if the specified element is selected
return parentGui.selectedModIdx == index;
}
@Override
protected void drawBackground() {
// Draw the background for the list elements
}
@Override
protected void drawSlot(int entryID, int x, int y, int mouseXIn, int mouseYIn,
int var6) {
mc.fontRendererObj.drawStringWithShadow(modList.get(entryID).getName(), x, y, 0xFFFFFF);
}
}
}
| 412 | 0.842641 | 1 | 0.842641 | game-dev | MEDIA | 0.907285 | game-dev | 0.963462 | 1 | 0.963462 |
id-Software/DOOM-3-BFG | 3,151 | neo/ui/FieldWindow.cpp | /*
===========================================================================
Doom 3 BFG Edition GPL Source Code
Copyright (C) 1993-2012 id Software LLC, a ZeniMax Media company.
This file is part of the Doom 3 BFG Edition GPL Source Code ("Doom 3 BFG Edition Source Code").
Doom 3 BFG Edition Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Doom 3 BFG Edition Source Code is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Doom 3 BFG Edition Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Doom 3 BFG Edition Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 BFG Edition Source Code. If not, please request a copy in writing from id Software at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
#pragma hdrstop
#include "../idlib/precompiled.h"
#include "DeviceContext.h"
#include "Window.h"
#include "UserInterfaceLocal.h"
#include "FieldWindow.h"
void idFieldWindow::CommonInit() {
cursorPos = 0;
lastTextLength = 0;
lastCursorPos = 0;
paintOffset = 0;
showCursor = false;
}
idFieldWindow::idFieldWindow(idUserInterfaceLocal *g) : idWindow(g) {
gui = g;
CommonInit();
}
idFieldWindow::~idFieldWindow() {
}
bool idFieldWindow::ParseInternalVar(const char *_name, idTokenParser *src) {
if (idStr::Icmp(_name, "cursorvar") == 0) {
ParseString(src, cursorVar);
return true;
}
if (idStr::Icmp(_name, "showcursor") == 0) {
showCursor = src->ParseBool();
return true;
}
return idWindow::ParseInternalVar(_name, src);
}
void idFieldWindow::CalcPaintOffset(int len) {
lastCursorPos = cursorPos;
lastTextLength = len;
paintOffset = 0;
int tw = dc->TextWidth(text, textScale, -1);
if (tw < textRect.w) {
return;
}
while (tw > textRect.w && len > 0) {
tw = dc->TextWidth(text, textScale, --len);
paintOffset++;
}
}
void idFieldWindow::Draw(int time, float x, float y) {
float scale = textScale;
int len = text.Length();
cursorPos = gui->State().GetInt( cursorVar );
if (len != lastTextLength || cursorPos != lastCursorPos) {
CalcPaintOffset(len);
}
idRectangle rect = textRect;
if (paintOffset >= len) {
paintOffset = 0;
}
if (cursorPos > len) {
cursorPos = len;
}
dc->DrawText(&text[paintOffset], scale, 0, foreColor, rect, false, ((flags & WIN_FOCUS) || showCursor) ? cursorPos - paintOffset : -1);
}
| 412 | 0.921477 | 1 | 0.921477 | game-dev | MEDIA | 0.686741 | game-dev | 0.901658 | 1 | 0.901658 |
WhoCraft/TardisRefined | 9,661 | common/src/main/java/whocraft/tardis_refined/client/TardisClientData.java | package whocraft.tardis_refined.client;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.AnimationState;
import net.minecraft.world.level.Level;
import net.minecraft.world.phys.Vec3;
import whocraft.tardis_refined.common.VortexRegistry;
import whocraft.tardis_refined.common.soundscape.hum.HumEntry;
import whocraft.tardis_refined.common.soundscape.hum.TardisHums;
import whocraft.tardis_refined.common.network.messages.sync.S2CSyncTardisClientData;
import whocraft.tardis_refined.common.tardis.themes.ShellTheme;
import whocraft.tardis_refined.constants.NbtConstants;
import whocraft.tardis_refined.patterns.ShellPatterns;
import java.util.ArrayList;
import java.util.List;
public class TardisClientData {
private static final List<TardisClientData> DATA = new ArrayList<>();
public static int FOG_TICK_DELTA = 0; // This is for the fading in and out of the fog.
static int MAX_FOG_TICK_DELTA = 2 * 20; // This is for adjusting how fast the fog will fade in and out.
private final ResourceKey<Level> levelKey;
public AnimationState ROTOR_ANIMATION = new AnimationState();
public AnimationState CRASHING_ANIMATION = new AnimationState();
public AnimationState LANDING_ANIMATION = new AnimationState();
public AnimationState TAKEOFF_ANIMATION = new AnimationState();
public int landingTime = 0, takeOffTime = 0;
//Not saved to disk, no real reason to be
int nextAmbientNoiseCall = 40;
// Independent of the hums logic
int nextVoiceAmbientCall = 12000;
private boolean flying = false;
// Control specifics
private int throttleStage = 0;
private boolean isLanding = false;
private boolean isHandbrakeEngaged = false;
private boolean isTakingOff = false;
private boolean isInDangerZone = false;
private boolean isCrashing = false;
private boolean isOnCooldown = false;
private float flightShakeScale = 0;
private double fuel = 0;
private double maximumFuel = 0;
private int tardisState = 0;
private int recoveryTicks = 0;
private float journeyProgress = 0;
private ResourceLocation shellTheme = ShellTheme.HALF_BAKED.getId();
private ResourceLocation vortex = VortexRegistry.FLOW.getId();
private ResourceLocation shellPattern = ShellPatterns.DEFAULT.id();
private HumEntry humEntry = TardisHums.getDefaultHum();
public TardisClientData(ResourceKey<Level> resourceKey) {
this.levelKey = resourceKey;
}
public static void add(TardisClientData tardisClientData) {
DATA.add(tardisClientData);
}
public ResourceLocation getVortex() {
return vortex;
}
public void setVortex(ResourceLocation vortex) {
this.vortex = vortex;
}
/**
* Retrieves information about a Tardis instance.
*
* @param levelResourceKey The resource key of the level the Tardis is in.
* @return The TardisIntReactions instance containing information about the Tardis.
*/
public static TardisClientData getInstance(ResourceKey<Level> levelResourceKey) {
for (TardisClientData data : DATA) {
if (data.getLevelKey().equals(levelResourceKey)) {
return data;
}
}
TardisClientData newData = new TardisClientData(levelResourceKey);
DATA.add(newData);
return newData;
}
public static List<TardisClientData> getAllEntries() {
return new ArrayList<>(DATA);
}
public static void clearAll() {
DATA.clear();
}
/**
* @return The resource key for the level in which this Tardis instance is located.
*/
public ResourceKey<Level> getLevelKey() {
return levelKey;
}
public float getJourneyProgress() {
return journeyProgress;
}
public void setJourneyProgress(float journeyProgress) {
this.journeyProgress = journeyProgress;
}
public ResourceLocation getShellTheme() {
return shellTheme;
}
public void setShellTheme(ResourceLocation shellTheme) {
this.shellTheme = shellTheme;
}
public HumEntry getHumEntry() {
return humEntry;
}
public void setHumEntry(HumEntry humEntry) {
this.humEntry = humEntry;
}
public int getThrottleStage() {
return this.throttleStage;
}
public void setThrottleStage(int stage) {
this.throttleStage = stage;
}
public ResourceLocation getShellPattern() {
return shellPattern;
}
public void setShellPattern(ResourceLocation shellPattern) {
this.shellPattern = shellPattern;
}
public boolean isFlying() {
return flying;
}
public void setFlying(boolean flying) {
this.flying = flying;
}
public void setIsLanding(boolean landing) {
this.isLanding = landing;
}
public boolean isLanding() {
return isLanding;
}
public void setIsTakingOff(boolean takingOff) {
this.isTakingOff = takingOff;
}
public boolean isTakingOff() {
return isTakingOff;
}
public void setIsCrashing(boolean isCrashing) {
this.isCrashing = isCrashing;
}
public boolean isCrashing() {
return isCrashing;
}
public void setIsOnCooldown(boolean isCooldown) {
this.isOnCooldown = isCooldown;
}
public boolean isInRecovery() {
return isOnCooldown;
}
public double getFuel() {
return fuel;
}
public void setFuel(double fuel) {
this.fuel = fuel;
}
public double getMaximumFuel() {
return maximumFuel;
}
public void setMaximumFuel(double fuel) {
this.maximumFuel = fuel;
}
/**
* Serializes the Tardis instance to a CompoundTag.
*
* @return A CompoundTag containing the serialized Tardis data.
*/
public CompoundTag serializeNBT() {
CompoundTag compoundTag = new CompoundTag();
compoundTag.putBoolean("flying", flying);
compoundTag.putInt(NbtConstants.THROTTLE_STAGE, throttleStage);
compoundTag.putInt("recoveryTicks", recoveryTicks);
compoundTag.putFloat("journeyProgress", journeyProgress);
compoundTag.putBoolean(NbtConstants.HANDBRAKE_ENGAGED, isHandbrakeEngaged);
compoundTag.putBoolean("isLanding", isLanding);
compoundTag.putBoolean("isTakingOff", isTakingOff);
compoundTag.putBoolean("isInDangerZone", this.isInDangerZone);
compoundTag.putFloat("flightShakeScale", this.flightShakeScale);
compoundTag.putBoolean("isOnCooldown", this.isOnCooldown);
// Save shellTheme and shellPattern
compoundTag.putString("shellTheme", shellTheme.toString());
compoundTag.putString("vortex", vortex.toString());
compoundTag.putString("shellPattern", shellPattern.toString());
compoundTag.putString(NbtConstants.TARDIS_CURRENT_HUM, humEntry.getIdentifier().toString());
compoundTag.putDouble(NbtConstants.FUEL, fuel);
compoundTag.putDouble(NbtConstants.MAXIMUM_FUEL, maximumFuel);
return compoundTag;
}
/**
* Deserializes the Tardis instance from a CompoundTag.
*
* @param compoundTag A CompoundTag containing the serialized Tardis data.
*/
public void deserializeNBT(CompoundTag compoundTag) {
flying = compoundTag.getBoolean("flying");
throttleStage = compoundTag.getInt(NbtConstants.THROTTLE_STAGE);
isHandbrakeEngaged = compoundTag.getBoolean(NbtConstants.HANDBRAKE_ENGAGED);
isLanding = compoundTag.getBoolean("isLanding");
isTakingOff = compoundTag.getBoolean("isTakingOff");
isInDangerZone = compoundTag.getBoolean("isInDangerZone");
flightShakeScale = compoundTag.getFloat("flightShakeScale");
isOnCooldown = compoundTag.getBoolean("isOnCooldown");
recoveryTicks = compoundTag.getInt("recoveryTicks");
journeyProgress = compoundTag.getFloat("journeyProgress");
// Load shellTheme and shellPattern
shellTheme = new ResourceLocation(compoundTag.getString("shellTheme"));
shellPattern = new ResourceLocation(compoundTag.getString("shellPattern"));
vortex = new ResourceLocation(compoundTag.getString("vortex"));
setHumEntry(TardisHums.getHumById(new ResourceLocation(compoundTag.getString(NbtConstants.TARDIS_CURRENT_HUM))));
fuel = compoundTag.getDouble(NbtConstants.FUEL);
maximumFuel = compoundTag.getDouble(NbtConstants.MAXIMUM_FUEL);
}
/**
* Syncs the Tardis instance with the specified server level. This method should only be called
* server-side, as calling it client-side may cause the game to crash.
*/
public void sync() {
new S2CSyncTardisClientData(getLevelKey(), serializeNBT()).sendToAll();
}
public Vec3 fogColor(boolean isCrashing) {
if (isCrashing) {
return new Vec3(1, 0, 0);
}
return new Vec3(0.14F, 0.15F, 0.22F);
}
public boolean isHandbrakeEngaged() {
return isHandbrakeEngaged;
}
public void setHandbrakeEngaged(boolean handbrakeEngaged) {
isHandbrakeEngaged = handbrakeEngaged;
}
public int getTardisState() {
return tardisState;
}
public void setTardisState(int tardisState) {
this.tardisState = tardisState;
}
public void setRecoveryProgress(int crashRecoveryTicks) {
this.recoveryTicks = crashRecoveryTicks;
}
public int getRecoveryTicks() {
return recoveryTicks;
}
}
| 412 | 0.890667 | 1 | 0.890667 | game-dev | MEDIA | 0.986049 | game-dev | 0.953005 | 1 | 0.953005 |
team-phoenix/Phoenix | 11,037 | backend/core/libretrorunner.cpp | #include "libretrorunner.h"
#include "mousestate.h"
#include <QDebug>
#include <QOpenGLContext>
#include <QOpenGLFunctions>
#include <QString>
#include <QStringBuilder>
#include <QThread>
#include <QMutexLocker>
#include "SDL.h"
#include "SDL_gamecontroller.h"
#include "SDL_haptic.h"
void LibretroRunner::commandIn( Command command, QVariant data, qint64 timeStamp ) {
// Command is not relayed to children automatically
switch( command ) {
case Command::Play: {
// Make sure we're only connecting LibretroCore to this node if it's a command that only shows up when
// emulation is active (in other words, never during loading)
if( !connectedToCore ) {
connectedToCore = true;
qDebug() << "LibretroRunner will now emit signals from LibretroCore";
connect( &libretroCore, &LibretroCore::dataOut, this, &LibretroRunner::dataOut );
connect( &libretroCore, &LibretroCore::commandOut, this, &LibretroRunner::commandOut );
}
qCDebug( phxCore ) << command;
libretroCore.state = State::Playing;
emit commandOut( Command::Play, QVariant(), nodeCurrentTime() );
break;
}
case Command::Pause: {
if( !connectedToCore ) {
connectedToCore = true;
qDebug() << "LibretroRunner will now emit signals from LibretroCore";
connect( &libretroCore, &LibretroCore::dataOut, this, &LibretroRunner::dataOut );
connect( &libretroCore, &LibretroCore::commandOut, this, &LibretroRunner::commandOut );
}
qCDebug( phxCore ) << command;
libretroCore.state = State::Paused;
emit commandOut( Command::Pause, QVariant(), nodeCurrentTime() );
break;
}
case Command::Stop: {
if( !connectedToCore ) {
connectedToCore = true;
qDebug() << "LibretroRunner will now emit signals from LibretroCore";
connect( &libretroCore, &LibretroCore::dataOut, this, &LibretroRunner::dataOut );
connect( &libretroCore, &LibretroCore::commandOut, this, &LibretroRunner::commandOut );
}
qCDebug( phxCore ) << command;
libretroCore.state = State::Unloading;
emit commandOut( Command::Unload, QVariant(), nodeCurrentTime() );
// Write SRAM
qCInfo( phxCore ) << "=======Saving game...=======";
LibretroCoreStoreSaveData();
qCInfo( phxCore ) << "============================";
// Unload core
{
// symbols.retro_api_version is reasonably expected to be defined if the core is loaded
if( libretroCore.symbols.retro_api_version ) {
libretroCore.symbols.retro_unload_game();
libretroCore.symbols.retro_deinit();
libretroCore.symbols.clear();
libretroCore.coreFile.unload();
qCDebug( phxCore ) << "Unloaded core successfully";
} else {
qCCritical( phxCore ) << "stop() called on an unloaded core!";
}
}
// Unload game (if we've read its contents into a buffer)
{
libretroCore.gameData.clear();
}
// Disconnect LibretroCore from the rest of the pipeline
disconnect( &libretroCore, &LibretroCore::dataOut, this, &LibretroRunner::dataOut );
disconnect( &libretroCore, &LibretroCore::commandOut, this, &LibretroRunner::commandOut );
connectedToCore = false;
// Delete the FBO
{
if( libretroCore.fbo ) {
delete libretroCore.fbo;
}
libretroCore.fbo = nullptr;
}
// Reset video mode to 2D (will be set to 3D if the next core asks for it)
libretroCore.videoFormat.videoMode = SOFTWARERENDER;
libretroCore.state = State::Stopped;
emit commandOut( Command::Stop, QVariant(), nodeCurrentTime() );
break;
}
case Command::Heartbeat: {
// Drop any heartbeats from too far in the past
if( nodeCurrentTime() - timeStamp > 50 ) {
return;
}
emit commandOut( command, data, timeStamp );
if( libretroCore.state == State::Playing ) {
// If in 3D mode, lock the mutex before emulating then activate our context and FBO
// This is because we're not sure exactly when the core will render to the texture. So, we'll just lock the
// mutex for the *entire* frame to be safe and not just from the start of the frame until the video callback
// In 2D mode it's simpler: We know that the data will come in a buffer which we can quickly copy within
// the video callback.
if( libretroCore.videoFormat.videoMode == HARDWARERENDER ) {
libretroCore.videoMutex.lock();
//qDebug() << "LibretroRunner lock";
libretroCore.context->makeCurrent( libretroCore.surface );
libretroCore.fbo->bind();
}
// Invoke libretro core
libretroCore.symbols.retro_run();
// Update rumble state
// TODO: Apply per-controller
for( GamepadState &gamepad : libretroCore.gamepads ) {
if( gamepad.instanceID == -1 || !gamepad.haptic ) {
//qDebug() << gamepad.instanceID << ( !gamepad.haptic ) << ( gamepad.hapticID < 0 );
continue;
}
else if( libretroCore.fallbackRumbleCurrentStrength[ gamepad.instanceID ] != gamepad.fallbackRumbleRequestedStrength ) {
//qDebug() << "from" << core.fallbackRumbleCurrentStrength[ gamepad.instanceID ] << "to" << gamepad.fallbackRumbleRequestedStrength;
libretroCore.fallbackRumbleCurrentStrength[ gamepad.instanceID ] = gamepad.fallbackRumbleRequestedStrength;
SDL_HapticRumbleStop( gamepad.haptic );
if( SDL_HapticRumblePlay( gamepad.haptic, libretroCore.fallbackRumbleCurrentStrength[ gamepad.instanceID ], SDL_HAPTIC_INFINITY ) != 0 ) {
qWarning() << gamepad.friendlyName << SDL_GetError();
qWarning().nospace() << gamepad.friendlyName << ": SDL_HapticRumblePlay( "
<< gamepad.haptic << ", "
<< libretroCore.fallbackRumbleCurrentStrength
<< ", SDL_HAPTIC_INFINITY ) != 0, rumble not available";
qWarning() << "SDL:" << SDL_GetError();
}
// Reset the requested strength
// Implicitly reset by incoming Gamepads overwriting the value set by us with the default of 0.0
// gamepad.fallbackRumbleRequestedStrength = 0.0;
}
}
if( libretroCore.videoFormat.videoMode == HARDWARERENDER ) {
libretroCore.context->makeCurrent( libretroCore.surface );
libretroCore.context->functions()->glFlush();
libretroCore.context->doneCurrent();
//qDebug() << "LibretroRunner unlock";
libretroCore.videoMutex.unlock();
}
// Flush stderr, some cores may still write to it despite having RETRO_LOG
fflush( stderr );
}
break;
}
case Command::SetWindowGeometry: {
emit commandOut( command, data, timeStamp );
libretroCore.windowGeometry = data.toRect();
emit commandOut( command, data, timeStamp );
break;
}
case Command::SetAspectRatioMode: {
libretroCore.aspectMode = data.toInt();
emit commandOut( command, data, timeStamp );
break;
}
case Command::SetLibretroVariable: {
LibretroVariable var = data.value<LibretroVariable>();
libretroCore.variables.insert( var.key(), var );
libretroCore.variablesAreDirty = true;
emit commandOut( command, data, timeStamp );
break;
}
case Command::AddController: {
if( !connectedToCore ) {
connectedToCore = true;
qDebug() << "LibretroRunner will now emit signals from LibretroCore";
connect( &libretroCore, &LibretroCore::dataOut, this, &LibretroRunner::dataOut );
connect( &libretroCore, &LibretroCore::commandOut, this, &LibretroRunner::commandOut );
}
GamepadState gamepad = data.value<GamepadState>();
int instanceID = gamepad.instanceID;
libretroCore.fallbackRumbleCurrentStrength[ instanceID ] = 0.0;
emit commandOut( command, data, timeStamp );
break;
}
case Command::RemoveController: {
if( !connectedToCore ) {
connectedToCore = true;
qDebug() << "LibretroRunner will now emit signals from LibretroCore";
connect( &libretroCore, &LibretroCore::dataOut, this, &LibretroRunner::dataOut );
connect( &libretroCore, &LibretroCore::commandOut, this, &LibretroRunner::commandOut );
}
GamepadState gamepad = data.value<GamepadState>();
int instanceID = gamepad.instanceID;
libretroCore.gamepads.remove( instanceID );
emit commandOut( command, data, timeStamp );
break;
}
default: {
emit commandOut( command, data, timeStamp );
break;
}
}
}
void LibretroRunner::dataIn( DataType type, QMutex *mutex, void *data, size_t bytes, qint64 timeStamp ) {
emit dataOut( type, mutex, data, bytes, timeStamp );
switch( type ) {
// Make a copy of the data into our own gamepad list
case DataType::Input: {
mutex->lock();
GamepadState gamepad = *static_cast<GamepadState *>( data );
mutex->unlock();
int instanceID = gamepad.instanceID;
libretroCore.gamepads[ instanceID ] = gamepad;
break;
}
// Make a copy of the incoming data and store it
case DataType::MouseInput: {
mutex->lock();
libretroCore.mouse = *static_cast<MouseState *>( data );
mutex->unlock();
break;
}
default:
break;
}
}
| 412 | 0.934336 | 1 | 0.934336 | game-dev | MEDIA | 0.381883 | game-dev | 0.718849 | 1 | 0.718849 |
PickAID/CrychicDoc | 8,275 | docs/zh/develop/modding/1.20.4/Neoforge/flandre/out_40_Fluid.md | ---
title: 40 流体
published: 2024-04-14T00:00:00.000Z
tags:
- Minecraft1_20_4
- NeoForge20_3
- Tutorial
description: 40 流体 相关教程
image: ./covers/db5375b0efcd53976a3fe5d47fbd8f3b3216e0f8.jpg
category: Minecraft1_20_4_NeoForge_Tutorial
authors:
- Flandre923
hidden: false
priority: 0
---
# 参考
https://boson.v2mcdev.com/fluid/firstfluid.html
## 流体
这次我们来说怎么创建流体。
在游戏中你看到的流体一把是在世界中存在的流动的和源头的两中,不过还有就是机器中处理的,桶这样的形势存在的。
当在桶内装的时候,是一个BucketItem的类,而在世界中不断的流动的就是一种特殊的方块,你可以尝试删除某个 流体的贴图你会发发现都是黑紫块了。
说明流体在世界中就是一种特殊的方块,不过这种特殊的方块有着类似方块和方块实体的这样的特殊关系,方块和对应的流体关联起来。
对于流体有两种状态我们需要创建这两种装填的流体,流动的flow,和源头source以及流体的type,这三个类是我们需要处理的,以及将创建的流体和对于的方块做出关联。
我们先来看下流体的type怎么处理,由于原版的fluidtype直接使用不方便,这里就给他包裹一层,然后我们使用我们创建的这个basefluidtype创建流体的type。
下面我们来看看这个类都提供了什么功能,和流体的那些属性有关。
```java
// 用于定义了流体类型
public class BaseFluidType extends FluidType {
// 定义了源source的纹理图片,流动的纹理图片,以及流体覆盖层的图片(指的是颜色,例如水的蓝色纹理,岩浆的红色纹理,你可以到原版对应的位置看看是什么图片就知道了)
private final ResourceLocation stillTexture;
private final ResourceLocation flowingTexture;
private final ResourceLocation overlayTexture;
// 流体的着色颜色
private final int tintColor;
// 从流体中看外面的雾的颜色
private final Vector3f fogColor;
//构造函数
public BaseFluidType(final ResourceLocation stillTexture, final ResourceLocation flowingTexture, final ResourceLocation overlayTexture,
final int tintColor, final Vector3f fogColor, final Properties properties) {
super(properties);
this.stillTexture = stillTexture;
this.flowingTexture = flowingTexture;
this.overlayTexture = overlayTexture;
this.tintColor = tintColor;
this.fogColor = fogColor;
}
// 对应的get函数
public ResourceLocation getStillTexture() {
return stillTexture;
}
public ResourceLocation getFlowingTexture() {
return flowingTexture;
}
public int getTintColor() {
return tintColor;
}
public ResourceLocation getOverlayTexture() {
return overlayTexture;
}
public Vector3f getFogColor() {
return fogColor;
}
// 对于我们的几个纹理,如果如果想生效的话,就需要重写这个方法,在对于的方法将我们的RL的资源定位的图片返回。
@Override
public void initializeClient(Consumer<IClientFluidTypeExtensions> consumer) {
consumer.accept(new IClientFluidTypeExtensions() {
@Override
public ResourceLocation getStillTexture() {
return stillTexture;
}
@Override
public ResourceLocation getFlowingTexture() {
return flowingTexture;
}
@Override
public @Nullable ResourceLocation getOverlayTexture() {
return overlayTexture;
}
@Override
public int getTintColor() {
return tintColor;
}
// 修改从流体中看雾的颜色
@Override
public @NotNull Vector3f modifyFogColor(Camera camera, float partialTick, ClientLevel level,
int renderDistance, float darkenWorldAmount, Vector3f fluidFogColor) {
return fogColor;
}
// 液体中的能见度 或者 说雾的范围
@Override
public void modifyFogRender(Camera camera, FogRenderer.FogMode mode, float renderDistance, float partialTick,
float nearDistance, float farDistance, FogShape shape) {
RenderSystem.setShaderFogStart(1f);
RenderSystem.setShaderFogEnd(6f); // distance when the fog starts
}
});
}
}
```
好了我们可以看到流体类型fluidType类和流体的颜色,贴图等属性有关。
我们接下来看怎么使用BaseFluidType创建我们的流体类型。并注册到总线。
```java
public class ModFluidType {
// 图片的位置,这里的source和flow,直接使用的原版的,所以没有第一个参数传入modid。
public static final ResourceLocation WATER_STILL_RL = new ResourceLocation("block/water_still");
public static final ResourceLocation WATER_FLOWING_RL = new ResourceLocation("block/water_flow");
// 这里的流体的overlay的图片使用是自己的图片,直接原版的water修改的。
public static final ResourceLocation MY_FLUID_RL = new ResourceLocation(ExampleMod.MODID, "misc/my_fluid");
// 怎么获得流体类型FluidType的注册器,有一点特殊,不是直接在Registires类下,而是在NeoForgeRegistries.Keys下
// 这应该是因为原版并没有流体类型FluidType这样的概念。
public static final DeferredRegister<FluidType> FLUID_TYPES =
DeferredRegister.create(NeoForgeRegistries.Keys.FLUID_TYPES, ExampleMod.MODID);
// 我们看到使用了register这个方法,这个方法是我们自己写的。
// 对于register在下面介绍,我们来看参数
// 第一参数name,没什么好说的,第二个参数是对流体的类型的属性进行一些设置 FluidType.Properties这个类就是对属性的一些设置。
// create返回一个properties实例,lightlevel设置亮度等级2,density设置密度,viscosity设置粘度,sound设置流体声音。
// 这些数值是直接复制的水的,对于其中的一些具体的效果,就自己调试看看效果把。也可以大家弹幕评论补充
public static final Supplier<FluidType> MY_FLUID_TYPE = register("my_fluid",
FluidType.Properties.create().lightLevel(2).density(15).viscosity(5).sound(SoundAction.get("drink"),
SoundEvents.HONEY_DRINK));
// 这个是我们自己写的注册的方法
// 并没有什么特殊的,直接返回了new baseFludType的supplier方法。
private static Supplier<FluidType> register(String name, FluidType.Properties properties) {
return FLUID_TYPES.register(name, () -> new BaseFluidType(WATER_STILL_RL, WATER_FLOWING_RL, MY_FLUID_RL,
0xA1E038D0, new Vector3f(224f / 255f, 56f / 255f, 208f / 255f), properties));
}
// 记得注册到总线
public static void register(IEventBus eventBus) {
FLUID_TYPES.register(eventBus);
}
}
```
好了,流体类型说完了,我们来看怎么处理流体了,包含了流体的source和flow,其实source和flow都是继承FlowingFluid类的。不过Neoforge为我们提供了BaseFlowingFluid类以及Source和Flowing子类帮助我们创建对应的实例。
```java
public class ModFluids {
// 流体注册器
public static final DeferredRegister<Fluid> FLUIDS = DeferredRegister.create(Registries.FLUID, ExampleMod.MODID);
// 注册对应流体的source和flow,使用NeoForge提供的BaseFlowingFluid来注册
// 其中source和flow都需要填入一个参数,这个参数是流体的属性,在下面定义
public static Supplier<FlowingFluid> MY_SOURCE_FLUID_BLOCK = FLUIDS.register("my_fluid", () -> new BaseFlowingFluid.Source(ModFluids.MY_FLUID_PROPERTIES));
public static Supplier<FlowingFluid> MY_FLOWING_FLUID_BLOCK = FLUIDS.register("my_fluid_flow", () -> new BaseFlowingFluid.Flowing(ModFluids.MY_FLUID_PROPERTIES));
// 定义流体的属性
// 这个流体的属性要传入的内容比较多,我们挨个介绍,我们使用了BaseFlowingFluid的Properties内部类创建对应的Properties,其中第一个参数是对应的流体的类体类型FluidType,然后第二个参数是对应的source流体,第三个参数是flow流体,都是我们刚刚写过的,看起来比较绕,大家自己理清下关系。
// 通过bucket这个设置流体和对应的流体桶的绑定,等会我们注册这个bucketitem
// 通过block绑定对应的流体和方块的绑定,这个方块等会我们注册。
// slopeFindDistance寻找斜坡的距离
// levelDecreasePerBlock 每个方块流体的减少量。
// 后两个数据是用于流体的流动的,主要是斜坡时候优先流,不会扩散。
// 以及流体最多能流多远,例如原版的水是8格
// 可以自己调试这几个数值试试,也可以去wiki看看具体的含义。
private static final BaseFlowingFluid.Properties MY_FLUID_PROPERTIES = new BaseFlowingFluid.Properties(ModFluidType.MY_FLUID_TYPE, ModFluids.MY_SOURCE_FLUID_BLOCK, ModFluids.MY_FLOWING_FLUID_BLOCK).bucket(ModItems.MY_FLUID_BUCKET).slopeFindDistance(2).levelDecreasePerBlock(2).block(ModBlocks.MY_FLUID_BLOCK);
// 别忘记注册到总线
public static void register(IEventBus eventBus) {
FLUIDS.register(eventBus);
}
}
```
下面我们来看对应的流体的方块和物品。
先看方块。
```java
// 注册方块,不过我们没有使用我么自己的那个方法,而是直接使用BLOCK的register方法,主要是我们不需要提供对应的item。因为我们还要注册对应的bucketitem。
public static final Supplier<LiquidBlock> MY_FLUID_BLOCK = BLOCKS.register("my_fluid_block",
()->new LiquidBlock(ModFluids.MY_SOURCE_FLUID_BLOCK,BlockBehaviour.Properties.ofFullCopy(Blocks.WATER)));
```
流体桶
```java
// 流体桶,craftRemainder表示合成之后保留桶
public static final Supplier<Item> MY_FLUID_BUCKET = register("my_fluid_bucket", ()->new BucketItem(ModFluids.MY_SOURCE_FLUID_BLOCK,new Item.Properties().craftRemainder(Items.BUCKET).stacksTo(1)));
```
流体的渲染,由于我们的流体是一个半透明的材质,所以指定流体的渲染为:translucent
对于source和flow都需要指定。
```java
@Mod.EventBusSubscriber(bus = Mod.EventBusSubscriber.Bus.MOD,value = Dist.CLIENT)
public class ModClientEventHandler {
@SubscribeEvent
public static void onClientEvent(FMLClientSetupEvent event){
event.enqueueWork(()->{
//fluid
ItemBlockRenderTypes.setRenderLayer(ModFluids.MY_SOURCE_FLUID_BLOCK.get(), RenderType.translucent());
ItemBlockRenderTypes.setRenderLayer(ModFluids.MY_FLOWING_FLUID_BLOCK.get(), RenderType.translucent());
});
}
```
好了,别忘记了注册到总线,然后你就可以进入游戏中看看了。
| 412 | 0.640163 | 1 | 0.640163 | game-dev | MEDIA | 0.490389 | game-dev | 0.723837 | 1 | 0.723837 |
ProjectSkyfire/SkyFire_548 | 14,388 | src/server/game/Groups/Group.h | /*
* This file is part of Project SkyFire https://www.projectskyfire.org.
* See LICENSE.md file for Copyright information
*/
#ifndef SKYFIRESERVER_GROUP_H
#define SKYFIRESERVER_GROUP_H
#include "DBCEnums.h"
#include "GroupRefManager.h"
#include "LootMgr.h"
#include "QueryResult.h"
#include "SharedDefines.h"
class Battlefield;
class Battleground;
class Creature;
class GroupReference;
class InstanceSave;
class Map;
class Player;
class Unit;
class WorldObject;
class WorldPacket;
class WorldSession;
struct MapEntry;
#define MAXGROUPSIZE 5
#define MAXRAIDSIZE 40
#define MAX_RAID_SUBGROUPS MAXRAIDSIZE/MAXGROUPSIZE
#define TARGETICONCOUNT 8
enum GroupMemberOnlineStatus
{
MEMBER_STATUS_OFFLINE = 0x0000,
MEMBER_STATUS_ONLINE = 0x0001, // Lua_UnitIsConnected
MEMBER_STATUS_PVP = 0x0002, // Lua_UnitIsPVP
MEMBER_STATUS_DEAD = 0x0004, // Lua_UnitIsDead
MEMBER_STATUS_GHOST = 0x0008, // Lua_UnitIsGhost
MEMBER_STATUS_PVP_FFA = 0x0010, // Lua_UnitIsPVPFreeForAll
MEMBER_STATUS_UNK3 = 0x0020, // used in calls from Lua_GetPlayerMapPosition/Lua_GetBattlefieldFlagPosition
MEMBER_STATUS_AFK = 0x0040, // Lua_UnitIsAFK
MEMBER_STATUS_DND = 0x0080 // Lua_UnitIsDND
};
enum class GroupMemberFlags
{
MEMBER_FLAG_ASSISTANT = 0x01,
MEMBER_FLAG_MAINTANK = 0x02,
MEMBER_FLAG_MAINASSIST = 0x04
};
enum class GroupMemberAssignment
{
GROUP_ASSIGN_MAINTANK = 0,
GROUP_ASSIGN_MAINASSIST = 1
};
enum GroupType
{
GROUPTYPE_NORMAL = 0x00,
GROUPTYPE_BG = 0x01,
GROUPTYPE_RAID = 0x02,
GROUPTYPE_BGRAID = GROUPTYPE_BG | GROUPTYPE_RAID, // mask
GROUPTYPE_UNK1 = 0x04,
GROUPTYPE_LFG = 0x08,
GROUPTYPE_EVERYONE_IS_ASSISTANT = 0x40
// 0x10, leave/change group?, I saw this flag when leaving group and after leaving BG while in group
};
enum GroupUpdateFlags
{
GROUP_UPDATE_FLAG_NONE = 0x00000000, // nothing
GROUP_UPDATE_FLAG_STATUS = 0x00000001, // uint16 (GroupMemberStatusFlag)
GROUP_UPDATE_FLAG_UNK = 0x00000002, // uint8 (), uint8 ()
GROUP_UPDATE_FLAG_CUR_HP = 0x00000004, // uint32 (HP)
GROUP_UPDATE_FLAG_MAX_HP = 0x00000008, // uint32 (HP)
GROUP_UPDATE_FLAG_POWER_TYPE = 0x00000010, // uint8 (PowerType)
GROUP_UPDATE_FLAG_UNK2 = 0x00000020,
GROUP_UPDATE_FLAG_CUR_POWER = 0x00000040, // int16 (power value)
GROUP_UPDATE_FLAG_MAX_POWER = 0x00000080, // int16 (power value)
GROUP_UPDATE_FLAG_LEVEL = 0x00000100, // uint16 (level value)
GROUP_UPDATE_FLAG_ZONE = 0x00000200, // uint16 (zone id)
GROUP_UPDATE_FLAG_UNK400 = 0x00000400, // int16 ()
GROUP_UPDATE_FLAG_POSITION = 0x00000800, // uint16 (x), uint16 (y), uint16 (z)
GROUP_UPDATE_FLAG_AURAS = 0x00001000, // uint8 (unk), uint64 (mask), uint32 (count), for each bit set: uint32 (spell id) + uint16 (AuraFlags) (if has flags Scalable -> 3x int32 (bps))
GROUP_UPDATE_FLAG_PET_GUID = 0x00002000, // uint64 (pet guid)
GROUP_UPDATE_FLAG_PET_NAME = 0x00004000, // cstring (name, NULL terminated string)
GROUP_UPDATE_FLAG_PET_MODEL_ID = 0x00008000, // uint16 (model id)
GROUP_UPDATE_FLAG_PET_CUR_HP = 0x00010000, // uint32 (HP)
GROUP_UPDATE_FLAG_PET_MAX_HP = 0x00020000, // uint32 (HP)
GROUP_UPDATE_FLAG_PET_POWER_TYPE = 0x00040000, // uint8 (PowerType)
GROUP_UPDATE_FLAG_PET_UNK2 = 0x00080000,
GROUP_UPDATE_FLAG_PET_CUR_POWER = 0x00100000, // uint16 (power value)
GROUP_UPDATE_FLAG_PET_MAX_POWER = 0x00200000, // uint16 (power value)
GROUP_UPDATE_FLAG_PET_AURAS = 0x00400000, // [see GROUP_UPDATE_FLAG_AURAS]
GROUP_UPDATE_FLAG_VEHICLE_SEAT = 0x00800000, // int32 (vehicle seat id)
GROUP_UPDATE_FLAG_PHASE = 0x01000000, // int32 (unk), uint32 (phase count), for (count) uint16(phaseId)
GROUP_UPDATE_PET = GROUP_UPDATE_FLAG_PET_GUID | GROUP_UPDATE_FLAG_PET_NAME | GROUP_UPDATE_FLAG_PET_MODEL_ID |
GROUP_UPDATE_FLAG_PET_CUR_HP | GROUP_UPDATE_FLAG_PET_MAX_HP | GROUP_UPDATE_FLAG_PET_POWER_TYPE |
GROUP_UPDATE_FLAG_PET_CUR_POWER | GROUP_UPDATE_FLAG_PET_MAX_POWER /*| GROUP_UPDATE_FLAG_PET_AURAS*/, // all pet flags
GROUP_UPDATE_FULL = GROUP_UPDATE_FLAG_STATUS | GROUP_UPDATE_FLAG_CUR_HP | GROUP_UPDATE_FLAG_MAX_HP |
GROUP_UPDATE_FLAG_POWER_TYPE | GROUP_UPDATE_FLAG_CUR_POWER | GROUP_UPDATE_FLAG_MAX_POWER |
GROUP_UPDATE_FLAG_LEVEL | GROUP_UPDATE_FLAG_ZONE | GROUP_UPDATE_FLAG_POSITION |
/* GROUP_UPDATE_FLAG_AURAS | */GROUP_UPDATE_PET | GROUP_UPDATE_FLAG_PHASE // all known flags, VEHICLE_SEAT
};
class Roll : public LootValidatorRef
{
public:
Roll(uint64 _guid, LootItem const& li);
~Roll();
void setLoot(Loot* pLoot);
Loot* getLoot();
void targetObjectBuildLink();
uint64 itemGUID;
uint32 itemid;
int32 itemRandomPropId;
uint32 itemRandomSuffix;
uint8 itemCount;
typedef std::map<uint64, RollType> PlayerVote;
PlayerVote playerVote; //vote position correspond with player position (in group)
uint8 totalPlayersRolling;
uint8 totalNeed;
uint8 totalGreed;
uint8 totalPass;
uint8 itemSlot;
uint8 rollVoteMask;
};
struct InstanceGroupBind
{
InstanceSave* save;
bool perm;
/* permanent InstanceGroupBinds exist if the leader has a permanent
PlayerInstanceBind for the same instance. */
InstanceGroupBind() : save(NULL), perm(false) { }
};
/** request member stats checken **/
/// @todo uninvite people that not accepted invite
class Group
{
public:
struct MemberSlot
{
MemberSlot() : guid(0), group(0), flags(0), roles(0), readyCheckHasResponded(false) { }
uint64 guid;
std::string name;
uint8 group;
uint8 flags;
uint8 roles;
bool readyCheckHasResponded;
};
typedef std::list<MemberSlot> MemberSlotList;
typedef MemberSlotList::const_iterator member_citerator;
typedef UNORDERED_MAP< uint32 /*mapId*/, InstanceGroupBind> BoundInstancesMap;
protected:
typedef MemberSlotList::iterator member_witerator;
typedef std::set<Player*> InvitesList;
typedef std::vector<Roll*> Rolls;
public:
Group();
~Group();
// group manipulation methods
bool Create(Player* leader);
void LoadGroupFromDB(Field* field);
void LoadMemberFromDB(uint32 guidLow, uint8 memberFlags, uint8 subgroup, uint8 roles);
bool AddInvite(Player* player);
void RemoveInvite(Player* player);
void RemoveAllInvites();
bool AddLeaderInvite(Player* player);
bool AddMember(Player* player);
bool RemoveMember(uint64 guid, const RemoveMethod& method = GROUP_REMOVEMETHOD_DEFAULT, uint64 kicker = 0, const char* reason = NULL);
void ChangeLeader(uint64 guid);
void SetLootMethod(LootMethod method);
void SetLooterGuid(uint64 guid);
void UpdateLooterGuid(WorldObject* pLootedObject, bool ifneed = false);
void SetLootThreshold(ItemQualities threshold);
void Disband(bool hideDestroy = false);
void SetLfgRoles(uint64 guid, const uint8 roles);
// properties accessories
bool IsFull() const;
bool isLFGGroup() const;
bool isRaidGroup() const;
bool isBGGroup() const;
bool isBFGroup() const;
bool IsCreated() const;
uint64 GetLeaderGUID() const;
uint64 GetGUID() const;
uint32 GetLowGUID() const;
const char* GetLeaderName() const;
LootMethod GetLootMethod() const;
uint64 GetLooterGuid() const;
ItemQualities GetLootThreshold() const;
uint32 GetDbStoreId() const { return m_dbStoreId; };
// member manipulation methods
bool IsMember(uint64 guid) const;
bool IsLeader(uint64 guid) const;
uint64 GetMemberGUID(const std::string& name);
bool IsAssistant(uint64 guid) const;
bool ReadyCheckInProgress() const { return _readyCheckInProgress; }
bool ReadyCheckAllResponded() const;
Player* GetInvited(uint64 guid) const;
Player* GetInvited(const std::string& name) const;
bool SameSubGroup(uint64 guid1, uint64 guid2) const;
bool SameSubGroup(uint64 guid1, MemberSlot const* slot2) const;
bool SameSubGroup(Player const* member1, Player const* member2) const;
bool HasFreeSlotSubGroup(uint8 subgroup) const;
MemberSlotList const& GetMemberSlots() const { return m_memberSlots; }
GroupReference* GetFirstMember() { return m_memberMgr.getFirst(); }
GroupReference const* GetFirstMember() const { return m_memberMgr.getFirst(); }
uint32 GetMembersCount() const { return m_memberSlots.size(); }
uint8 GetMemberGroup(uint64 guid) const;
void ChangeFlagEveryoneAssistant(bool apply);
void ConvertToLFG();
void ConvertToRaid();
void ConvertToGroup();
void SetBattlegroundGroup(Battleground* bg);
void SetBattlefieldGroup(Battlefield* bf);
GroupJoinBattlegroundResult CanJoinBattlegroundQueue(Battleground const* bgOrTemplate, BattlegroundQueueTypeId bgQueueTypeId, uint32 MinPlayerCount, uint32 MaxPlayerCount, bool isRated, uint32 arenaSlot);
void ChangeMembersGroup(uint64 guid, uint8 group);
void ChangeMembersGroup(Player* player, uint8 group);
void SetTargetIcon(uint8 id, ObjectGuid whoGuid, ObjectGuid targetGuid, uint8 Index);
void SetGroupMemberFlag(uint64 guid, bool apply, GroupMemberFlags flag);
void RemoveUniqueGroupMemberFlag(GroupMemberFlags flag);
void SetMemberRole(uint64 guid, uint32 role);
uint32 GetMemberRole(uint64 guid) const;
bool RoleCheckAllResponded() const;
DifficultyID GetDifficulty(MapEntry const* mapEntry) const;
DifficultyID GetDungeonDifficulty() const { return m_dungeonDifficulty; }
DifficultyID GetRaidDifficulty() const { return m_raidDifficulty; }
void SetDungeonDifficulty(DifficultyID difficulty);
void SetRaidDifficulty(DifficultyID difficulty);
bool InCombatToInstance(uint32 instanceId);
void ResetInstances(InstanceResetMethod method, bool isRaid, Player* SendMsgTo);
void ReadyCheck(bool state) { _readyCheckInProgress = state; }
void ReadyCheckMemberHasResponded(uint64 guid);
void ReadyCheckResetResponded();
// -no description-
//void SendInit(WorldSession* session);
void SendTargetIconList(WorldSession* session);
void SendUpdate();
void SendUpdateToPlayer(uint64 playerGUID, MemberSlot* slot = NULL);
void UpdatePlayerOutOfRange(Player* player);
void SendReadyCheckCompleted();
// ignore: GUID of player that will be ignored
void BroadcastPacket(WorldPacket* packet, bool ignorePlayersInBGRaid, int group = -1, uint64 ignore = 0);
void BroadcastAddonMessagePacket(WorldPacket* packet, const std::string& prefix, bool ignorePlayersInBGRaid, int group = -1, uint64 ignore = 0);
void BroadcastReadyCheck(WorldPacket* packet);
void OfflineReadyCheck();
/*********************************************************/
/*** LOOT SYSTEM ***/
/*********************************************************/
bool isRollLootActive() const;
void SendLootStartRoll(uint32 CountDown, uint32 mapid, const Roll& r);
void SendLootStartRollToPlayer(uint32 countDown, uint32 mapId, Player* p, bool canNeed, Roll const& r);
void SendLootRoll(uint64 SourceGuid, uint64 TargetGuid, uint8 RollNumber, RollType RollType, const Roll& r);
void SendLootRollWon(uint64 SourceGuid, uint64 TargetGuid, uint8 RollNumber, RollType RollType, const Roll& r);
void SendLootAllPassed(Roll const& roll);
void SendLooter(Creature* creature, Player* pLooter);
void GroupLoot(Loot* loot, WorldObject* pLootedObject);
void NeedBeforeGreed(Loot* loot, WorldObject* pLootedObject);
void MasterLoot(Loot* loot, WorldObject* pLootedObject);
Rolls::iterator GetRoll(uint64 Guid);
void CountTheRoll(Rolls::iterator roll);
void CountRollVote(uint64 playerGUID, uint64 Guid, RollType Choise);
void EndRoll(Loot* loot);
// related to disenchant rolls
void ResetMaxEnchantingLevel();
void LinkMember(GroupReference* pRef);
void DelinkMember(uint64 guid);
InstanceGroupBind* BindToInstance(InstanceSave* save, bool permanent, bool load = false);
void UnbindInstance(uint32 mapid, uint8 difficulty, bool unload = false);
InstanceGroupBind* GetBoundInstance(Player* player);
InstanceGroupBind* GetBoundInstance(Map* aMap);
InstanceGroupBind* GetBoundInstance(MapEntry const* mapEntry);
InstanceGroupBind* GetBoundInstance(DifficultyID difficulty, uint32 mapId);
BoundInstancesMap& GetBoundInstances(DifficultyID difficulty);
// FG: evil hacks
void BroadcastGroupUpdate(void);
protected:
bool _setMembersGroup(uint64 guid, uint8 group);
void _homebindIfInstance(Player* player);
void _initRaidSubGroupsCounter();
member_citerator _getMemberCSlot(uint64 Guid) const;
member_witerator _getMemberWSlot(uint64 Guid);
void SubGroupCounterIncrease(uint8 subgroup);
void SubGroupCounterDecrease(uint8 subgroup);
void ToggleGroupMemberFlag(member_witerator slot, GroupMemberFlags flag, bool apply);
MemberSlotList m_memberSlots;
GroupRefManager m_memberMgr;
InvitesList m_invitees;
uint64 m_leaderGuid;
std::string m_leaderName;
GroupType m_groupType;
DifficultyID m_dungeonDifficulty;
DifficultyID m_raidDifficulty;
Battleground* m_bgGroup;
Battlefield* m_bfGroup;
uint64 m_targetIcons[TARGETICONCOUNT] = { };
LootMethod m_lootMethod;
ItemQualities m_lootThreshold;
uint64 m_looterGuid;
Rolls RollId;
BoundInstancesMap m_boundInstances[15];
uint8* m_subGroupsCounts;
uint64 m_guid;
uint32 m_counter; // used only in SMSG_GROUP_LIST
uint32 m_maxEnchantingLevel;
uint32 m_dbStoreId; // Represents the ID used in database (Can be reused by other groups if group was disbanded)
bool _readyCheckInProgress;
};
#endif
| 412 | 0.864566 | 1 | 0.864566 | game-dev | MEDIA | 0.853859 | game-dev | 0.861665 | 1 | 0.861665 |
Kaedrin/nwn2cc | 1,394 | NWN2 WIP/Override/override_latest/Scripts/cmi_s2_deeproots.NSS |
#include "cmi_includes"
#include "nwn2_inc_spells"
#include "x2_inc_spellhook"
void bDidYouMove(int nSpellId, location MyLoc)
{
location CurrentLoc = GetLocation(OBJECT_SELF);
float fDist = GetDistanceBetweenLocations(CurrentLoc, MyLoc);
if (fDist > 1.0f)
{
if (GetHasSpellEffect(nSpellId,OBJECT_SELF))
{
RemoveSpellEffects(nSpellId, OBJECT_SELF, OBJECT_SELF);
}
}
else
DelayCommand(2.0f, bDidYouMove(nSpellId, MyLoc));
}
void main()
{
int nSpellId = FOREST_MASTER_DEEP_ROOTS;
if (GetHasSpellEffect(nSpellId,OBJECT_SELF))
{
RemoveSpellEffects(nSpellId, OBJECT_SELF, OBJECT_SELF);
}
effect eVis = EffectVisualEffect(VFX_IMP_HEALING_G);
int nDexPenalty = GetAbilityScore(OBJECT_SELF, ABILITY_DEXTERITY) - 1;
effect eRegen = EffectRegenerate(5, 6.0);
effect eDur = EffectVisualEffect(VFX_DUR_REGENERATE);
effect eDex = EffectAbilityDecrease(ABILITY_DEXTERITY, nDexPenalty);
effect eLink = EffectLinkEffects(eRegen, eDur);
eLink = EffectLinkEffects(eLink, eDex);
location MyLoc = GetLocation(OBJECT_SELF);
SignalEvent(OBJECT_SELF, EventSpellCastAt(OBJECT_SELF, nSpellId, FALSE));
DelayCommand(0.1f, ApplyEffectToObject(DURATION_TYPE_TEMPORARY, eLink, OBJECT_SELF, HoursToSeconds(48)));
DelayCommand(0.1f, ApplyEffectToObject(DURATION_TYPE_INSTANT, eVis, OBJECT_SELF));
DelayCommand(2.0f, bDidYouMove(nSpellId, MyLoc));
} | 412 | 0.591619 | 1 | 0.591619 | game-dev | MEDIA | 0.73477 | game-dev,graphics-rendering | 0.628039 | 1 | 0.628039 |
CianLR/mazegen-rs | 1,517 | src/algos/prims.rs | use rand::prelude::*;
use crate::algos::algo::MazeAlgo;
use crate::maze::Maze;
pub struct PrimsAlgo {
animate: bool,
}
impl PrimsAlgo {
pub fn new(animate: bool) -> PrimsAlgo {
PrimsAlgo { animate: animate }
}
fn prims(&self, maze: &mut Maze) -> Result<(), String> {
let size = maze.get_size();
let mut rng = rand::thread_rng();
let mut in_maze = vec![vec![false; size]; size];
let mut walls: Vec<_> = maze.get_adjacent(0, 0)
.into_iter()
.map(|(x, y)| (0, 0, x, y))
.collect();
in_maze[0][0] = true;
while !walls.is_empty() {
let (x, y, x2, y2) = walls.remove(rng.gen_range(0, walls.len()));
if in_maze[x2][y2] {
continue; // Already connected.
}
in_maze[x2][y2] = true;
if self.animate {
self.frame(maze, 20);
}
maze.remove_wall(x, y, x2, y2);
walls.extend(maze.get_adjacent(x2, y2)
.into_iter()
.filter(|(x3, y3)| !in_maze[*x3][*y3])
.map(|(x3, y3)| (x2, y2, x3, y3)));
}
Ok(())
}
}
impl MazeAlgo for PrimsAlgo {
fn generate(&mut self, maze: &mut Maze) -> Result<(), String> {
self.prims(maze)
}
}
#[cfg(test)]
mod test {
use crate::algos::test_util::*;
#[test]
fn test_is_perfect() {
let m = apply_test_algo("prims");
assert!(is_perfect_maze(&m));
}
}
| 412 | 0.913388 | 1 | 0.913388 | game-dev | MEDIA | 0.925929 | game-dev | 0.964353 | 1 | 0.964353 |
microsoft/automatic-graph-layout | 11,475 | GraphLayout/MSAGL/Miscellaneous/NonOverlappingBoundaries/AllPairsNonOverlappingBoundaries.cs | using System;
using System.Collections.Generic;
using Microsoft.Msagl.Core.DataStructures;
using System.Diagnostics;
using Microsoft.Msagl.Core.Geometry;
using Microsoft.Msagl.Core.Geometry.Curves;
using Microsoft.Msagl.Core.Layout;
using Microsoft.Msagl.Layout.Incremental;
namespace Microsoft.Msagl.Prototype.NonOverlappingBoundaries {
/// <summary>
/// A CvxHull is Convex hull
/// </summary>
public abstract class CvxHull : IHull {
/// <summary>
/// We have a hierarchy of membership
/// </summary>
public ClusterConvexHull Parent { get; protected set; }
/// <summary>
/// see IHull
/// </summary>
public abstract Point Center { get; }
/// <summary>
/// move the center by delta
/// </summary>
/// <param name="delta"></param>
public abstract void MoveCenter(Point delta);
/// <summary>
/// see IHull
/// </summary>
public abstract RectangleNode<IHull,Point> RectangleNode { get; }
/// <summary>
///
/// </summary>
public abstract double Weight { get; }
/// <summary>
/// Gets the boundary translated to the current Center
/// </summary>
/// <returns></returns>
public abstract Polyline TranslatedBoundary();
/// <summary>
/// Resolves overlap between this and another CHull by moving on the minimum penetration depth vector
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public double Project(IHull other) {
var v = other as CvxHull;
var vc = v as ClusterConvexHull;
var c = this as ClusterConvexHull;
if (c!=null && c.Contains(v)) {
return 0;
}
if (vc != null && vc.Contains(this)) {
return 0;
}
Debug.Assert(v != null);
Point pd = PenetrationDepth.PenetrationDepthForPolylines(TranslatedBoundary(), v.TranslatedBoundary());
if (pd.Length > 0) {
Point wpd = pd / (Weight + v.Weight);
MoveCenter(v.Weight * wpd);
v.MoveCenter(-Weight * wpd);
}
return pd.Length;
}
}
/// <summary>
/// A CvxHull for rectangles
/// </summary>
public class RCHull : CvxHull {
internal Node mNode;
private Polyline boundary;
private Polyline translatedBoundary;
double w2, h2;
/// <summary>
/// Center of the node
/// </summary>
public override Point Center {
get { return mNode.Center; }
}
/// <summary>
/// Move by delta
/// </summary>
/// <param name="delta"></param>
public override void MoveCenter(Point delta) {
mNode.Center += delta;
}
/// <summary>
/// RectangleNode is used in region queries
/// </summary>
public override RectangleNode<IHull,Point> RectangleNode {
get {
var r = new Rectangle(Center.X - w2, Center.Y - h2, Center.X + w2, Center.Y + h2);
return new RectangleNode<IHull,Point>(this, r);
}
}
/// <summary>
///
/// </summary>
public override double Weight {
get { return ((FiNode)mNode.AlgorithmData).stayWeight; }
}
/// <summary>
///
/// </summary>
/// <param name="parent"></param>
/// <param name="padding"></param>
/// <param name="mNode"></param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "m")]
public RCHull(ClusterConvexHull parent, Node mNode, double padding) {
//var node = (FastIncrementalLayout.Node)mNode.AlgorithmData;
//this.w2 = node.width / 2.0 + padding;
//this.h2 = node.height / 2.0 + padding;
this.w2 = mNode.Width / 2.0 + padding;
this.h2 = mNode.Height / 2.0 + padding;
this.Parent = parent;
boundary = new Polyline(new Point[]{
new Point(-w2, -h2),
new Point(-w2, h2),
new Point(w2, h2),
new Point(w2, -h2)
});
boundary.Closed = true;
translatedBoundary = new Polyline(boundary);
translatedBoundary.Closed = true;
this.mNode = mNode;
}
/// <summary>
/// Gets the boundary translated to the current Center
/// </summary>
/// <returns></returns>
public override Polyline TranslatedBoundary() {
PolylinePoint qq = translatedBoundary.StartPoint;
for (PolylinePoint pp = boundary.StartPoint; pp != null; pp = pp.Next) {
qq.Point = pp.Point + Center;
qq = qq.Next;
}
return translatedBoundary;
}
}
/// <summary>
/// The convex hull of the constituents of a Cluster
/// </summary>
public class ClusterConvexHull : CvxHull {
internal Cluster cluster;
/// <summary>
/// The Barycenter of the cluster
/// </summary>
public override Point Center {
get { return cluster.SetBarycenter(); }
}
/// <summary>
/// Move contents by delta
/// </summary>
/// <param name="delta"></param>
public override void MoveCenter(Point delta)
{
cluster.ForEachNode(v => v.Center += delta);
}
/// <summary>
///
/// </summary>
public override double Weight {
get { return cluster.Weight; }
}
/// <summary>
/// Bounding box used in region queries
/// </summary>
public override RectangleNode<IHull,Point> RectangleNode {
get {
var r = new Rectangle(Center);
foreach (var node in cluster.Nodes)
r.Add(node.BoundingBox);
return new RectangleNode<IHull,Point>(this, r);
}
}
/// <summary>
/// The convex hull of the constituents of a Cluster
/// </summary>
/// <param name="cluster"></param>
/// <param name="parent"></param>
public ClusterConvexHull(Cluster cluster, ClusterConvexHull parent) {
this.cluster = cluster;
this.Parent = parent;
}
/// <summary>
/// Gets the boundary translated to the current Center
/// </summary>
/// <returns></returns>
public override Polyline TranslatedBoundary() {
return ComputeConvexHull();
}
/// <summary>
/// The convex hull of all the points of all the nodes in the cluster
/// </summary>
private Polyline ComputeConvexHull()
{
var points = new List<Point>();
foreach (Node v in cluster.Nodes)
{
CvxHull r = new RCHull(null, v, 0);
foreach (PolylinePoint p in r.TranslatedBoundary().PolylinePoints)
points.Add(p.Point);
}
foreach (Cluster c in cluster.Clusters)
{
points.AddRange(new ClusterConvexHull(c, this).TranslatedBoundary());
}
return new Polyline(ConvexHull.CalculateConvexHull(points)) {Closed = true};
}
/// <summary>
/// Search hierarchy to check if child is a descendent of this.
/// </summary>
/// <param name="child"></param>
/// <returns>true if child is a descendent of this cluster</returns>
public bool Contains(CvxHull child) {
if (child.Parent == null) {
return false;
}
if (child.Parent == this) {
return true;
}
return Contains(child.Parent);
}
}
/// <summary>
/// Prevents the boundaries of nodes and clusters from overlapping
/// </summary>
public class AllPairsNonOverlappingBoundaries : IConstraint {
List<IHull> hulls = new List<IHull>();
private void traverseClusters(ClusterConvexHull parent, Cluster cluster, double padding) {
ClusterConvexHull hull = new ClusterConvexHull(cluster, parent);
hulls.Add(hull);
foreach (var v in cluster.nodes) {
hulls.Add(new RCHull(hull, v, padding));
}
foreach (var c in cluster.clusters) {
traverseClusters(hull, c, padding);
}
}
/// <summary>
///
/// Non-overlap between nodes in the same cluster (or the root cluster), between the convex hulls
/// of clusters and nodes that do belong to those clusters and between clusters and clusters.
/// </summary>
/// <param name="cluster"></param>
/// <param name="settings">for padding extra space around nodes</param>
public AllPairsNonOverlappingBoundaries(Cluster cluster, FastIncrementalLayoutSettings settings) {
foreach (var v in cluster.nodes) {
hulls.Add(new RCHull(null,v, settings.NodeSeparation));
}
foreach (var c in cluster.clusters) {
traverseClusters(null, c, settings.NodeSeparation);
}
}
#region IConstraint Members
private static int AllPairsComputationLimit = 20;
/// <summary>
/// Uses Lev's fast proximity query to find pairs of nodes/clusters with overlapping bounding boxes.
/// When such are found, they are projected apart.
/// </summary>
public double Project() {
double displacement = 0;
if (hulls.Count < AllPairsComputationLimit) {
// if there are only a few nodes then do it the most straightforward n^2 way
for (int i = 0; i < hulls.Count - 1; ++i) {
IHull u = hulls[i];
for (int j = i + 1; j < hulls.Count; ++j) {
displacement += u.Project(hulls[j]);
}
}
} else {
var pq = new ProximityQuery(hulls);
List<Tuple<IHull, IHull>> closePairs = pq.GetAllIntersections();
//shuffle(ref closePairs);
foreach (var k in closePairs) {
displacement += k.Item1.Project(k.Item2);
}
}
return displacement;
}
//void shuffle<T>(ref List<T> l) {
// List<T> tmpList = new List<T>();
// while (l.Count > 0) {
// int i = rand.Next(l.Count);
// tmpList.Add(l[i]);
// l.RemoveAt(i);
// }
// l = tmpList;
//}
/// <summary>
/// NonOverlap constraints are a beautification thing, and therefore higher level than others
/// </summary>
/// <returns>2</returns>
public int Level { get { return 2; } }
#endregion
#region IConstraint Members
/// <summary>
///
/// </summary>
public IEnumerable<Node> Nodes {
get { return new List<Node>(); }
}
#endregion
}
}
| 412 | 0.739224 | 1 | 0.739224 | game-dev | MEDIA | 0.31522 | game-dev | 0.743812 | 1 | 0.743812 |
reegeek/StructLinq | 1,916 | src/StructLinq/Except/RefExceptEnumerator.cs | using System.Runtime.CompilerServices;
using StructLinq.Utils.Collections;
namespace StructLinq.Except
{
public struct RefExceptEnumerator<T, TEnumerator1, TEnumerator2, TComparer> : IRefStructEnumerator<T>
where TEnumerator1 : struct, IRefStructEnumerator<T>
where TEnumerator2 : struct, IRefStructEnumerator<T>
where TComparer : IInEqualityComparer<T>
{
private TEnumerator1 enumerator1;
private TEnumerator2 enumerator2;
private InPooledSet<T, TComparer> set;
internal RefExceptEnumerator(ref TEnumerator1 enumerator1, ref TEnumerator2 enumerator2, ref InPooledSet<T, TComparer> set)
: this()
{
this.enumerator1 = enumerator1;
this.enumerator2 = enumerator2;
this.set = set;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Dispose()
{
set.Dispose();
enumerator1.Dispose();
enumerator2.Dispose();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool MoveNext()
{
while (enumerator2.MoveNext())
{
ref var current = ref enumerator2.Current;
set.AddIfNotPresent(in current);
}
while (enumerator1.MoveNext())
{
ref var current = ref enumerator1.Current;
if (set.AddIfNotPresent(in current))
return true;
}
return false;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Reset()
{
set.Clear();
enumerator1.Reset();
enumerator2.Reset();
}
public ref T Current
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ref enumerator1.Current;
}
}
}
| 412 | 0.949692 | 1 | 0.949692 | game-dev | MEDIA | 0.144447 | game-dev | 0.944383 | 1 | 0.944383 |
XFactHD/FramedBlocks | 12,553 | src/main/java/io/github/xfacthd/framedblocks/common/block/slopepanelcorner/FramedExtendedDoubleCornerSlopePanelBlock.java | package io.github.xfacthd.framedblocks.common.block.slopepanelcorner;
import io.github.xfacthd.framedblocks.api.block.BlockUtils;
import io.github.xfacthd.framedblocks.api.block.FramedProperties;
import io.github.xfacthd.framedblocks.api.block.IFramedBlock;
import io.github.xfacthd.framedblocks.api.block.blockentity.FramedDoubleBlockEntity;
import io.github.xfacthd.framedblocks.api.block.doubleblock.CamoGetter;
import io.github.xfacthd.framedblocks.api.block.doubleblock.DoubleBlockParts;
import io.github.xfacthd.framedblocks.api.block.doubleblock.DoubleBlockTopInteractionMode;
import io.github.xfacthd.framedblocks.api.block.doubleblock.SolidityCheck;
import io.github.xfacthd.framedblocks.api.util.Utils;
import io.github.xfacthd.framedblocks.common.FBContent;
import io.github.xfacthd.framedblocks.common.block.FramedDoubleBlock;
import io.github.xfacthd.framedblocks.common.blockentity.doubled.slopepanelcorner.FramedExtendedDoubleCornerSlopePanelBlockEntity;
import io.github.xfacthd.framedblocks.common.blockentity.doubled.slopepanelcorner.FramedExtendedInnerDoubleCornerSlopePanelBlockEntity;
import io.github.xfacthd.framedblocks.common.data.BlockType;
import io.github.xfacthd.framedblocks.common.item.block.VerticalAndWallBlockItem;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.BlockItem;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.context.BlockPlaceContext;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Mirror;
import net.minecraft.world.level.block.Rotation;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.StateDefinition;
import org.jetbrains.annotations.Nullable;
public class FramedExtendedDoubleCornerSlopePanelBlock extends FramedDoubleBlock
{
public FramedExtendedDoubleCornerSlopePanelBlock(BlockType blockType, Properties props)
{
super(blockType, props);
registerDefaultState(defaultBlockState()
.setValue(FramedProperties.TOP, false)
.setValue(FramedProperties.Y_SLOPE, false)
);
}
@Override
protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder)
{
super.createBlockStateDefinition(builder);
builder.add(
FramedProperties.FACING_HOR, FramedProperties.TOP, FramedProperties.Y_SLOPE
);
}
@Override
@Nullable
public BlockState getStateForPlacement(BlockPlaceContext ctx)
{
return FramedCornerSlopePanelBlock.getStateForPlacement(
this, ctx, getBlockType() == BlockType.FRAMED_EXT_INNER_DOUBLE_CORNER_SLOPE_PANEL, true
);
}
@Override
public boolean handleBlockLeftClick(BlockState state, Level level, BlockPos pos, Player player)
{
return IFramedBlock.toggleYSlope(state, level, pos, player);
}
@Override
public BlockState rotate(BlockState state, Direction face, Rotation rot)
{
if (Utils.isY(face))
{
Direction dir = state.getValue(FramedProperties.FACING_HOR);
return state.setValue(FramedProperties.FACING_HOR, rot.rotate(dir));
}
return state.cycle(FramedProperties.TOP);
}
@Override
protected BlockState rotate(BlockState state, Rotation rot)
{
return rotate(state, Direction.UP, rot);
}
@Override
protected BlockState mirror(BlockState state, Mirror mirror)
{
return BlockUtils.mirrorCornerBlock(state, mirror);
}
@Override
public FramedDoubleBlockEntity newBlockEntity(BlockPos pos, BlockState state)
{
return switch (getBlockType())
{
case FRAMED_EXT_DOUBLE_CORNER_SLOPE_PANEL -> new FramedExtendedDoubleCornerSlopePanelBlockEntity(pos, state);
case FRAMED_EXT_INNER_DOUBLE_CORNER_SLOPE_PANEL -> new FramedExtendedInnerDoubleCornerSlopePanelBlockEntity(pos, state);
default -> throw new IllegalStateException("Unexpected type: " + getBlockType());
};
}
@Override
public DoubleBlockParts calculateParts(BlockState state)
{
Direction dir = state.getValue(FramedProperties.FACING_HOR);
boolean top = state.getValue(FramedProperties.TOP);
boolean ySlope = state.getValue(FramedProperties.Y_SLOPE);
return switch (getBlockType())
{
case FRAMED_EXT_DOUBLE_CORNER_SLOPE_PANEL -> new DoubleBlockParts(
FBContent.BLOCK_FRAMED_EXTENDED_CORNER_SLOPE_PANEL.value()
.defaultBlockState()
.setValue(FramedProperties.FACING_HOR, dir)
.setValue(FramedProperties.TOP, top)
.setValue(FramedProperties.Y_SLOPE, ySlope),
FBContent.BLOCK_FRAMED_LARGE_INNER_CORNER_SLOPE_PANEL.value()
.defaultBlockState()
.setValue(FramedProperties.FACING_HOR, dir)
.setValue(FramedProperties.TOP, !top)
.setValue(FramedProperties.Y_SLOPE, ySlope)
);
case FRAMED_EXT_INNER_DOUBLE_CORNER_SLOPE_PANEL -> new DoubleBlockParts(
FBContent.BLOCK_FRAMED_EXTENDED_INNER_CORNER_SLOPE_PANEL.value()
.defaultBlockState()
.setValue(FramedProperties.FACING_HOR, dir)
.setValue(FramedProperties.TOP, top)
.setValue(FramedProperties.Y_SLOPE, ySlope),
FBContent.BLOCK_FRAMED_SMALL_CORNER_SLOPE_PANEL.value()
.defaultBlockState()
.setValue(FramedProperties.FACING_HOR, dir)
.setValue(FramedProperties.TOP, !top)
.setValue(FramedProperties.Y_SLOPE, ySlope)
);
default -> throw new IllegalArgumentException("Unexpected type: " + getBlockType());
};
}
@Override
public DoubleBlockTopInteractionMode calculateTopInteractionMode(BlockState state)
{
boolean top = state.getValue(FramedProperties.TOP);
return top ? DoubleBlockTopInteractionMode.FIRST : DoubleBlockTopInteractionMode.EITHER;
}
@Override
public CamoGetter calculateCamoGetter(BlockState state, Direction side, @Nullable Direction edge)
{
return switch (getBlockType())
{
case FRAMED_EXT_DOUBLE_CORNER_SLOPE_PANEL ->
{
Direction facing = state.getValue(FramedProperties.FACING_HOR);
boolean top = state.getValue(FramedProperties.TOP);
Direction dirTwo = top ? Direction.UP : Direction.DOWN;
if (side == dirTwo)
{
yield CamoGetter.FIRST;
}
else if (side == facing.getOpposite() || side == facing.getClockWise())
{
yield CamoGetter.SECOND;
}
else if (side == facing)
{
if (edge == facing.getCounterClockWise() || edge == dirTwo)
{
yield CamoGetter.FIRST;
}
else if (edge == facing.getClockWise())
{
yield CamoGetter.SECOND;
}
}
else if (side == facing.getCounterClockWise())
{
if (edge == facing || edge == dirTwo)
{
yield CamoGetter.FIRST;
}
else if (edge == facing.getOpposite())
{
yield CamoGetter.SECOND;
}
}
else if (side == dirTwo.getOpposite() && (edge == facing.getClockWise() || edge == facing.getOpposite()))
{
yield CamoGetter.SECOND;
}
yield CamoGetter.NONE;
}
case FRAMED_EXT_INNER_DOUBLE_CORNER_SLOPE_PANEL ->
{
Direction facing = state.getValue(FramedProperties.FACING_HOR);
boolean top = state.getValue(FramedProperties.TOP);
Direction dirTwo = top ? Direction.UP : Direction.DOWN;
if (side == facing.getOpposite() || side == facing.getClockWise() || side == dirTwo)
{
yield CamoGetter.FIRST;
}
else if (side == dirTwo.getOpposite() && (edge == facing.getOpposite() || edge == facing.getClockWise()))
{
yield CamoGetter.FIRST;
}
else if (side == facing)
{
if (edge == dirTwo || edge == facing.getClockWise())
{
yield CamoGetter.FIRST;
}
else if (edge == facing.getCounterClockWise())
{
yield CamoGetter.SECOND;
}
}
else if (side == facing.getCounterClockWise())
{
if (edge == dirTwo || edge == facing.getOpposite())
{
yield CamoGetter.FIRST;
}
else if (edge == facing)
{
yield CamoGetter.SECOND;
}
}
yield CamoGetter.NONE;
}
default -> throw new IllegalArgumentException("Unexpected type: " + getBlockType());
};
}
@Override
public SolidityCheck calculateSolidityCheck(BlockState state, Direction side)
{
return switch (getBlockType())
{
case FRAMED_EXT_DOUBLE_CORNER_SLOPE_PANEL ->
{
if (Utils.isY(side))
{
boolean top = state.getValue(FramedProperties.TOP);
if (top ? (side == Direction.UP) : (side == Direction.DOWN))
{
yield SolidityCheck.FIRST;
}
}
Direction facing = state.getValue(FramedProperties.FACING_HOR);
if (side == facing.getOpposite() || side == facing.getClockWise())
{
yield SolidityCheck.SECOND;
}
yield SolidityCheck.BOTH;
}
case FRAMED_EXT_INNER_DOUBLE_CORNER_SLOPE_PANEL ->
{
boolean primaryYFace = false;
if (Utils.isY(side))
{
boolean top = state.getValue(FramedProperties.TOP);
primaryYFace = top ? (side == Direction.UP) : (side == Direction.DOWN);
}
Direction facing = state.getValue(FramedProperties.FACING_HOR);
if (primaryYFace || side == facing.getOpposite() || side == facing.getClockWise())
{
yield SolidityCheck.FIRST;
}
yield SolidityCheck.BOTH;
}
default -> throw new IllegalArgumentException("Unexpected type: " + getBlockType());
};
}
@Override
public BlockItem createBlockItem(Item.Properties props)
{
Block other = switch (getBlockType())
{
case FRAMED_EXT_DOUBLE_CORNER_SLOPE_PANEL -> FBContent.BLOCK_FRAMED_EXTENDED_DOUBLE_CORNER_SLOPE_PANEL_WALL.value();
case FRAMED_EXT_INNER_DOUBLE_CORNER_SLOPE_PANEL -> FBContent.BLOCK_FRAMED_EXTENDED_INNER_DOUBLE_CORNER_SLOPE_PANEL_WALL.value();
default -> throw new IllegalStateException("Unexpected type: " + getBlockType());
};
return new VerticalAndWallBlockItem(this, other, props);
}
@Override
public BlockState getItemModelSource()
{
boolean inner = getBlockType() == BlockType.FRAMED_EXT_INNER_DOUBLE_CORNER_SLOPE_PANEL;
return defaultBlockState().setValue(FramedProperties.FACING_HOR, inner ? Direction.EAST : Direction.WEST);
}
@Override
public BlockState getJadeRenderState(BlockState state)
{
return getItemModelSource();
}
}
| 412 | 0.894276 | 1 | 0.894276 | game-dev | MEDIA | 0.841306 | game-dev | 0.896037 | 1 | 0.896037 |
OversizedSunCoreDev/ArtilleryEco | 3,521 | Cabling/Source/Cabling/Cabling.Build.cs | // Copyright Epic Games, Inc. All Rights Reserved.
using System;
using System.IO;
using UnrealBuildTool;
public class Cabling : ModuleRules
{
//This is pulled from gameinputbase. we did try to take a dependency from that, but
// we actually don't need it and I'll be phasing it out permanently unless I can find a way to make it
//work without building the engine from source. right now, my goal is that bristle doesn't require that.
protected virtual bool HasGameInputSupport(ReadOnlyTargetRules Target)
{
// Console platforms will override this function and determine if they have GameInput support on their own.
// For the base functionality, we can only support Game Input on windows platforms.
if (!Target.Platform.IsInGroup(UnrealPlatformGroup.Windows))
{
return false;
}
// The Game Input SDK is installed when you install the GRDK, which will set the environment variable "GRDKLatest"
// We can then use that to look up the path to the GameInput.h and GameInput.lib files needed to use Game Input.
//
// https://learn.microsoft.com/en-us/gaming/gdk/_content/gc/input/overviews/input-overview
string GRDKLatestPath = Environment.GetEnvironmentVariable("GRDKLatest");
if (GRDKLatestPath != null)
{
System.Console.WriteLine("GRDK is installed but Cabling is using our weird pirate version. See GDKDependency dir.");
}
else
{
System.Console.WriteLine("GRDK is NOT installed but Cabling uses the version in GDKDependency dir. This may cause problems.");
}
return true; // Bristlecone packs with the relevant stuff because I couldn't stand it anymore.
}
public Cabling(ReadOnlyTargetRules Target) : base(Target)
{
PublicIncludePaths.AddRange(
new string[] {
Path.Combine(PluginDirectory,"Source/Cabling")
}
);
bEnableExceptions = true;
bool bHasGameInputSupport = HasGameInputSupport(Target);
System.Console.WriteLine("Known support: " + bHasGameInputSupport);
string gdkpath = Path.Combine(PluginDirectory, "GDKDependency", "GameKit", "Include");
PrivateIncludePaths.Add(gdkpath);
PublicIncludePaths.Add(gdkpath);
string gdklibpath = Path.Combine(PluginDirectory, "GDKDependency", "GameKit", "Lib", "amd64", "GameInput.lib");
PublicAdditionalLibraries.Add(gdklibpath);
PublicDependencyModuleNames.AddRange(new string[] {
"Core",
"CoreUObject",
"Engine",
"Slate",
"ApplicationCore",
"InputCore",
"Networking",
"Sockets",
"DeveloperSettings",
"LocomoCore", "SkeletonKey"
});
PrivateDependencyModuleNames.AddRange(
new string[]
{
"Core",
"CoreUObject",
"ApplicationCore",
"Engine",
"Slate",
"SlateCore",
"Engine",
"InputCore",
"Networking",
"Sockets",
"DeveloperSettings",
"NetCommon",
"LocomoCore"
});
DynamicallyLoadedModuleNames.AddRange(
new string[]
{
// ... add any modules that your module loads dynamically here ...
}
);
}
}
| 412 | 0.911763 | 1 | 0.911763 | game-dev | MEDIA | 0.495883 | game-dev,desktop-app | 0.518991 | 1 | 0.518991 |
amethyst/rustrogueliketutorial | 13,346 | chapter-19-food/src/inventory_system.rs | use specs::prelude::*;
use super::{WantsToPickupItem, Name, InBackpack, Position, gamelog::GameLog, WantsToUseItem,
Consumable, ProvidesHealing, CombatStats, WantsToDropItem, InflictsDamage, Map, SufferDamage,
AreaOfEffect, Confusion, Equippable, Equipped, WantsToRemoveItem, particle_system::ParticleBuilder,
ProvidesFood, HungerClock, HungerState};
pub struct ItemCollectionSystem {}
impl<'a> System<'a> for ItemCollectionSystem {
#[allow(clippy::type_complexity)]
type SystemData = ( ReadExpect<'a, Entity>,
WriteExpect<'a, GameLog>,
WriteStorage<'a, WantsToPickupItem>,
WriteStorage<'a, Position>,
ReadStorage<'a, Name>,
WriteStorage<'a, InBackpack>
);
fn run(&mut self, data : Self::SystemData) {
let (player_entity, mut gamelog, mut wants_pickup, mut positions, names, mut backpack) = data;
for pickup in wants_pickup.join() {
positions.remove(pickup.item);
backpack.insert(pickup.item, InBackpack{ owner: pickup.collected_by }).expect("Unable to insert backpack entry");
if pickup.collected_by == *player_entity {
gamelog.entries.push(format!("You pick up the {}.", names.get(pickup.item).unwrap().name));
}
}
wants_pickup.clear();
}
}
pub struct ItemUseSystem {}
impl<'a> System<'a> for ItemUseSystem {
#[allow(clippy::type_complexity)]
type SystemData = ( ReadExpect<'a, Entity>,
WriteExpect<'a, GameLog>,
ReadExpect<'a, Map>,
Entities<'a>,
WriteStorage<'a, WantsToUseItem>,
ReadStorage<'a, Name>,
ReadStorage<'a, Consumable>,
ReadStorage<'a, ProvidesHealing>,
ReadStorage<'a, InflictsDamage>,
WriteStorage<'a, CombatStats>,
WriteStorage<'a, SufferDamage>,
ReadStorage<'a, AreaOfEffect>,
WriteStorage<'a, Confusion>,
ReadStorage<'a, Equippable>,
WriteStorage<'a, Equipped>,
WriteStorage<'a, InBackpack>,
WriteExpect<'a, ParticleBuilder>,
ReadStorage<'a, Position>,
ReadStorage<'a, ProvidesFood>,
WriteStorage<'a, HungerClock>
);
#[allow(clippy::cognitive_complexity)]
fn run(&mut self, data : Self::SystemData) {
let (player_entity, mut gamelog, map, entities, mut wants_use, names,
consumables, healing, inflict_damage, mut combat_stats, mut suffer_damage,
aoe, mut confused, equippable, mut equipped, mut backpack, mut particle_builder, positions,
provides_food, mut hunger_clocks) = data;
for (entity, useitem) in (&entities, &wants_use).join() {
let mut used_item = true;
// Targeting
let mut targets : Vec<Entity> = Vec::new();
match useitem.target {
None => { targets.push( *player_entity ); }
Some(target) => {
let area_effect = aoe.get(useitem.item);
match area_effect {
None => {
// Single target in tile
let idx = map.xy_idx(target.x, target.y);
for mob in map.tile_content[idx].iter() {
targets.push(*mob);
}
}
Some(area_effect) => {
// AoE
let mut blast_tiles = rltk::field_of_view(target, area_effect.radius, &*map);
blast_tiles.retain(|p| p.x > 0 && p.x < map.width-1 && p.y > 0 && p.y < map.height-1 );
for tile_idx in blast_tiles.iter() {
let idx = map.xy_idx(tile_idx.x, tile_idx.y);
for mob in map.tile_content[idx].iter() {
targets.push(*mob);
}
particle_builder.request(tile_idx.x, tile_idx.y, rltk::RGB::named(rltk::ORANGE), rltk::RGB::named(rltk::BLACK), rltk::to_cp437('░'), 200.0);
}
}
}
}
}
// If it is equippable, then we want to equip it - and unequip whatever else was in that slot
let item_equippable = equippable.get(useitem.item);
match item_equippable {
None => {}
Some(can_equip) => {
let target_slot = can_equip.slot;
let target = targets[0];
// Remove any items the target has in the item's slot
let mut to_unequip : Vec<Entity> = Vec::new();
for (item_entity, already_equipped, name) in (&entities, &equipped, &names).join() {
if already_equipped.owner == target && already_equipped.slot == target_slot {
to_unequip.push(item_entity);
if target == *player_entity {
gamelog.entries.push(format!("You unequip {}.", name.name));
}
}
}
for item in to_unequip.iter() {
equipped.remove(*item);
backpack.insert(*item, InBackpack{ owner: target }).expect("Unable to insert backpack entry");
}
// Wield the item
equipped.insert(useitem.item, Equipped{ owner: target, slot: target_slot }).expect("Unable to insert equipped component");
backpack.remove(useitem.item);
if target == *player_entity {
gamelog.entries.push(format!("You equip {}.", names.get(useitem.item).unwrap().name));
}
}
}
// It it is edible, eat it!
let item_edible = provides_food.get(useitem.item);
match item_edible {
None => {}
Some(_) => {
used_item = true;
let target = targets[0];
let hc = hunger_clocks.get_mut(target);
if let Some(hc) = hc {
hc.state = HungerState::WellFed;
hc.duration = 20;
gamelog.entries.push(format!("You eat the {}.", names.get(useitem.item).unwrap().name));
}
}
}
// If it heals, apply the healing
let item_heals = healing.get(useitem.item);
match item_heals {
None => {}
Some(healer) => {
used_item = false;
for target in targets.iter() {
let stats = combat_stats.get_mut(*target);
if let Some(stats) = stats {
stats.hp = i32::min(stats.max_hp, stats.hp + healer.heal_amount);
if entity == *player_entity {
gamelog.entries.push(format!("You use the {}, healing {} hp.", names.get(useitem.item).unwrap().name, healer.heal_amount));
}
used_item = true;
let pos = positions.get(*target);
if let Some(pos) = pos {
particle_builder.request(pos.x, pos.y, rltk::RGB::named(rltk::GREEN), rltk::RGB::named(rltk::BLACK), rltk::to_cp437('♥'), 200.0);
}
}
}
}
}
// If it inflicts damage, apply it to the target cell
let item_damages = inflict_damage.get(useitem.item);
match item_damages {
None => {}
Some(damage) => {
used_item = false;
for mob in targets.iter() {
SufferDamage::new_damage(&mut suffer_damage, *mob, damage.damage);
if entity == *player_entity {
let mob_name = names.get(*mob).unwrap();
let item_name = names.get(useitem.item).unwrap();
gamelog.entries.push(format!("You use {} on {}, inflicting {} hp.", item_name.name, mob_name.name, damage.damage));
let pos = positions.get(*mob);
if let Some(pos) = pos {
particle_builder.request(pos.x, pos.y, rltk::RGB::named(rltk::RED), rltk::RGB::named(rltk::BLACK), rltk::to_cp437('‼'), 200.0);
}
}
used_item = true;
}
}
}
// Can it pass along confusion? Note the use of scopes to escape from the borrow checker!
let mut add_confusion = Vec::new();
{
let causes_confusion = confused.get(useitem.item);
match causes_confusion {
None => {}
Some(confusion) => {
used_item = false;
for mob in targets.iter() {
add_confusion.push((*mob, confusion.turns ));
if entity == *player_entity {
let mob_name = names.get(*mob).unwrap();
let item_name = names.get(useitem.item).unwrap();
gamelog.entries.push(format!("You use {} on {}, confusing them.", item_name.name, mob_name.name));
let pos = positions.get(*mob);
if let Some(pos) = pos {
particle_builder.request(pos.x, pos.y, rltk::RGB::named(rltk::MAGENTA), rltk::RGB::named(rltk::BLACK), rltk::to_cp437('?'), 200.0);
}
}
}
}
}
}
for mob in add_confusion.iter() {
confused.insert(mob.0, Confusion{ turns: mob.1 }).expect("Unable to insert status");
}
// If its a consumable, we delete it on use
if used_item {
let consumable = consumables.get(useitem.item);
match consumable {
None => {}
Some(_) => {
entities.delete(useitem.item).expect("Delete failed");
}
}
}
}
wants_use.clear();
}
}
pub struct ItemDropSystem {}
impl<'a> System<'a> for ItemDropSystem {
#[allow(clippy::type_complexity)]
type SystemData = ( ReadExpect<'a, Entity>,
WriteExpect<'a, GameLog>,
Entities<'a>,
WriteStorage<'a, WantsToDropItem>,
ReadStorage<'a, Name>,
WriteStorage<'a, Position>,
WriteStorage<'a, InBackpack>
);
fn run(&mut self, data : Self::SystemData) {
let (player_entity, mut gamelog, entities, mut wants_drop, names, mut positions, mut backpack) = data;
for (entity, to_drop) in (&entities, &wants_drop).join() {
let mut dropper_pos : Position = Position{x:0, y:0};
{
let dropped_pos = positions.get(entity).unwrap();
dropper_pos.x = dropped_pos.x;
dropper_pos.y = dropped_pos.y;
}
positions.insert(to_drop.item, Position{ x : dropper_pos.x, y : dropper_pos.y }).expect("Unable to insert position");
backpack.remove(to_drop.item);
if entity == *player_entity {
gamelog.entries.push(format!("You drop the {}.", names.get(to_drop.item).unwrap().name));
}
}
wants_drop.clear();
}
}
pub struct ItemRemoveSystem {}
impl<'a> System<'a> for ItemRemoveSystem {
#[allow(clippy::type_complexity)]
type SystemData = (
Entities<'a>,
WriteStorage<'a, WantsToRemoveItem>,
WriteStorage<'a, Equipped>,
WriteStorage<'a, InBackpack>
);
fn run(&mut self, data : Self::SystemData) {
let (entities, mut wants_remove, mut equipped, mut backpack) = data;
for (entity, to_remove) in (&entities, &wants_remove).join() {
equipped.remove(to_remove.item);
backpack.insert(to_remove.item, InBackpack{ owner: entity }).expect("Unable to insert backpack");
}
wants_remove.clear();
}
}
| 412 | 0.929427 | 1 | 0.929427 | game-dev | MEDIA | 0.825024 | game-dev | 0.989751 | 1 | 0.989751 |
CleverRaven/Cataclysm-DDA | 1,766 | src/talker_topic.h | #pragma once
#ifndef CATA_SRC_TALKER_TOPIC_H
#define CATA_SRC_TALKER_TOPIC_H
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "talker.h"
/*
* Talker wrapper class for an empty talker thats just topics
*/
class talker_topic_const: public const_talker_cloner<talker_topic_const>
{
public:
explicit talker_topic_const( std::vector<std::string> new_topics )
: topics( std::move( new_topics ) ) {}
talker_topic_const() = default;
talker_topic_const( const talker_topic_const & ) = default;
talker_topic_const( talker_topic_const && ) = delete;
talker_topic_const &operator=( const talker_topic_const & ) = default;
talker_topic_const &operator=( talker_topic_const && ) = delete;
~talker_topic_const() override = default;
std::vector<std::string> get_topics( bool radio_contact ) const override;
bool will_talk_to_u( const Character &/* you */, bool /* force */ ) const override {
return true;
}
private:
std::vector<std::string> topics;
};
class talker_topic: virtual public talker_topic_const, public talker_cloner<talker_topic>
{
public:
explicit talker_topic( std::vector<std::string> new_topics )
: talker_topic_const( std::move( new_topics ) ) {}
talker_topic() = default;
talker_topic( const talker_topic & ) = default;
talker_topic( talker_topic && ) = delete;
talker_topic &operator=( const talker_topic & ) = default;
talker_topic &operator=( talker_topic && ) = delete;
~talker_topic() override = default;
};
std::unique_ptr<talker> get_talker_for( const std::vector<std::string> &topics );
#endif // CATA_SRC_TALKER_TOPIC_H
| 412 | 0.686037 | 1 | 0.686037 | game-dev | MEDIA | 0.416024 | game-dev | 0.657531 | 1 | 0.657531 |
watabou/pixel-dungeon | 1,549 | src/com/watabou/pixeldungeon/actors/buffs/Invisibility.java | /*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.watabou.pixeldungeon.actors.buffs;
import com.watabou.pixeldungeon.Dungeon;
import com.watabou.pixeldungeon.actors.Char;
import com.watabou.pixeldungeon.ui.BuffIndicator;
public class Invisibility extends FlavourBuff {
public static final float DURATION = 15f;
@Override
public boolean attachTo( Char target ) {
if (super.attachTo( target )) {
target.invisible++;
return true;
} else {
return false;
}
}
@Override
public void detach() {
target.invisible--;
super.detach();
}
@Override
public int icon() {
return BuffIndicator.INVISIBLE;
}
@Override
public String toString() {
return "Invisible";
}
public static void dispel() {
Invisibility buff = Dungeon.hero.buff( Invisibility.class );
if (buff != null && Dungeon.hero.visibleEnemies() > 0) {
buff.detach();
}
}
}
| 412 | 0.79596 | 1 | 0.79596 | game-dev | MEDIA | 0.977534 | game-dev | 0.594221 | 1 | 0.594221 |
godlikepanos/anki-3d-engine | 1,524 | ThirdParty/Jolt/Samples/Utils/ShapeCreator.cpp | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
// SPDX-FileCopyrightText: 2022 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#include <TestFramework.h>
#include <Utils/ShapeCreator.h>
namespace ShapeCreator {
ShapeRefC CreateTorusMesh(float inTorusRadius, float inTubeRadius, uint inTorusSegments, uint inTubeSegments)
{
uint cNumVertices = inTorusSegments * inTubeSegments;
// Create torus
MeshShapeSettings mesh;
mesh.mTriangleVertices.reserve(cNumVertices);
mesh.mIndexedTriangles.reserve(cNumVertices * 2);
for (uint torus_segment = 0; torus_segment < inTorusSegments; ++torus_segment)
{
Mat44 rotation = Mat44::sRotation(Vec3::sAxisY(), float(torus_segment) * 2.0f * JPH_PI / inTorusSegments);
for (uint tube_segment = 0; tube_segment < inTubeSegments; ++tube_segment)
{
// Create vertices
float tube_angle = float(tube_segment) * 2.0f * JPH_PI / inTubeSegments;
Vec3 pos = rotation * Vec3(inTorusRadius + inTubeRadius * Sin(tube_angle), inTubeRadius * Cos(tube_angle), 0);
Float3 v;
pos.StoreFloat3(&v);
mesh.mTriangleVertices.push_back(v);
// Create indices
uint start_idx = torus_segment * inTubeSegments + tube_segment;
mesh.mIndexedTriangles.emplace_back(start_idx, (start_idx + 1) % cNumVertices, (start_idx + inTubeSegments) % cNumVertices);
mesh.mIndexedTriangles.emplace_back((start_idx + 1) % cNumVertices, (start_idx + inTubeSegments + 1) % cNumVertices, (start_idx + inTubeSegments) % cNumVertices);
}
}
return mesh.Create().Get();
}
};
| 412 | 0.790994 | 1 | 0.790994 | game-dev | MEDIA | 0.63156 | game-dev | 0.927289 | 1 | 0.927289 |
JetBrains/mapper | 4,022 | util/base/src/main/java/jetbrains/jetpad/base/SimpleAsync.java | /*
* Copyright 2012-2017 JetBrains s.r.o
*
* 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 jetbrains.jetpad.base;
import jetbrains.jetpad.base.function.Consumer;
import jetbrains.jetpad.base.function.Function;
import java.util.ArrayList;
import java.util.List;
public final class SimpleAsync<ItemT> implements ResolvableAsync<ItemT> {
private ItemT mySuccessItem;
private boolean mySucceeded = false;
private Throwable myFailureThrowable;
private boolean myFailed = false;
private List<Consumer<? super ItemT>> mySuccessHandlers = new ArrayList<>();
private List<Consumer<Throwable>> myFailureHandlers = new ArrayList<>();
@Override
public Registration onSuccess(final Consumer<? super ItemT> successHandler) {
if (alreadyHandled()) {
if (mySucceeded) {
successHandler.accept(mySuccessItem);
}
return Registration.EMPTY;
}
mySuccessHandlers.add(successHandler);
return new Registration() {
@Override
protected void doRemove() {
if (mySuccessHandlers != null) {
mySuccessHandlers.remove(successHandler);
}
}
};
}
@Override
public Registration onResult(Consumer<? super ItemT> successHandler, Consumer<Throwable> failureHandler) {
final Registration successRegistration = onSuccess(successHandler);
final Registration failureRegistration = onFailure(failureHandler);
return new Registration() {
@Override
protected void doRemove() {
successRegistration.remove();
failureRegistration.remove();
}
};
}
@Override
public Registration onFailure(final Consumer<Throwable> handler) {
if (alreadyHandled()) {
if (myFailed) {
handler.accept(myFailureThrowable);
}
return Registration.EMPTY;
}
myFailureHandlers.add(handler);
return new Registration() {
@Override
protected void doRemove() {
if (myFailureHandlers != null) {
myFailureHandlers.remove(handler);
}
}
};
}
@Override
public <ResultT> Async<ResultT> map(Function<? super ItemT, ? extends ResultT> success) {
return Asyncs.map(this, success, new SimpleAsync<ResultT>());
}
@Override
public <ResultT> Async<ResultT> flatMap(Function<? super ItemT, Async<ResultT>> success) {
return Asyncs.select(this, success, new SimpleAsync<ResultT>());
}
@Override
public void success(ItemT item) {
if (alreadyHandled()) {
throw new IllegalStateException("Async already completed");
}
mySuccessItem = item;
mySucceeded = true;
for (Consumer<? super ItemT> handler : mySuccessHandlers) {
try {
handler.accept(item);
} catch (Exception e) {
ThrowableHandlers.handle(e);
}
}
clearHandlers();
}
@Override
public void failure(Throwable throwable) {
if (alreadyHandled()) {
throw new IllegalStateException("Async already completed");
}
myFailureThrowable = throwable;
myFailed = true;
for (Consumer<Throwable> handler : myFailureHandlers) {
try {
handler.accept(throwable);
} catch (Throwable t) {
ThrowableHandlers.handle(t);
}
}
clearHandlers();
}
private void clearHandlers() {
mySuccessHandlers = null;
myFailureHandlers = null;
}
private boolean alreadyHandled() {
return mySucceeded || myFailed;
}
boolean hasSucceeded() {
return mySucceeded;
}
boolean hasFailed() {
return myFailed;
}
} | 412 | 0.904023 | 1 | 0.904023 | game-dev | MEDIA | 0.349422 | game-dev | 0.964313 | 1 | 0.964313 |
ProjectIgnis/CardScripts | 3,521 | official/c35488287.lua | --寿炎星-リシュンマオ
--Brotherhood of the Fire Fist - Panda
--Scripted by Hel
local s,id=GetID()
function s.initial_effect(c)
--Special summon itself from hand
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(id,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e1:SetProperty(EFFECT_FLAG_DELAY)
e1:SetCode(EVENT_CHAINING)
e1:SetRange(LOCATION_HAND)
e1:SetCountLimit(1,id)
e1:SetCondition(s.spcon1)
e1:SetTarget(s.sptg)
e1:SetOperation(s.spop)
c:RegisterEffect(e1)
--Substitute destruction for a "Fire Fist" monster(s)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e2:SetCode(EFFECT_DESTROY_REPLACE)
e2:SetRange(LOCATION_MZONE)
e2:SetCountLimit(1,{id,1})
e2:SetTarget(s.reptg)
e2:SetValue(s.repval)
c:RegisterEffect(e2)
end
s.listed_names={id}
s.listed_series={SET_FIRE_FORMATION,SET_FIRE_FIST}
function s.spcon1(e,tp,eg,ep,ev,re,r,rp)
return rp==tp and re:IsHasType(EFFECT_TYPE_ACTIVATE) and re:IsSpellTrapEffect() and re:GetHandler():IsSetCard(SET_FIRE_FORMATION)
end
function s.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,false,false) and Duel.GetLocationCount(tp,LOCATION_MZONE)>0 end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0)
Duel.SetPossibleOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_GRAVE)
end
function s.spfilter(c,e,tp)
return c:IsSetCard(SET_FIRE_FIST) and c:IsMonster() and c:IsCanBeSpecialSummoned(e,0,tp,false,false) and not c:IsCode(id)
end
function s.splimit(e,c,tp,sumtp,sumpos)
return not c:IsSetCard(SET_FIRE_FIST)
end
function s.spop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_CANNOT_SPECIAL_SUMMON)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET+EFFECT_FLAG_CLIENT_HINT)
e1:SetDescription(aux.Stringid(id,1))
e1:SetTargetRange(1,0)
e1:SetTarget(s.splimit)
e1:SetReset(RESET_PHASE|PHASE_END)
Duel.RegisterEffect(e1,tp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
if c:IsRelateToEffect(e) and Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEUP)>0 then
local g=Duel.GetMatchingGroup(aux.NecroValleyFilter(s.spfilter),tp,LOCATION_GRAVE,0,nil,e,tp)
if #g>0 and Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.SelectYesNo(tp,aux.Stringid(id,2)) then
Duel.BreakEffect()
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local sg=g:Select(tp,1,1,nil)
Duel.SpecialSummon(sg,0,tp,tp,false,false,POS_FACEUP)
end
end
end
function s.repfilter(c,tp)
return c:IsControler(tp) and c:IsLocation(LOCATION_MZONE) and c:IsSetCard(SET_FIRE_FIST) and c:IsFaceup()
and c:IsReason(REASON_EFFECT) and not c:IsReason(REASON_REPLACE)
and c:GetReasonPlayer()~=tp
end
function s.tgfilter(c)
return c:IsFaceup() and c:IsSetCard(SET_FIRE_FORMATION) and c:IsSpellTrap() and not c:IsStatus(STATUS_DESTROY_CONFIRMED)
end
function s.reptg(e,tp,eg,ep,ev,re,r,rp,chk)
local c=e:GetHandler()
if chk==0 then return eg:IsExists(s.repfilter,1,nil,tp)
and Duel.IsExistingMatchingCard(s.tgfilter,tp,LOCATION_ONFIELD,0,1,nil,e,tp) end
if Duel.SelectEffectYesNo(tp,c,96) then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE)
local sg=Duel.SelectMatchingCard(tp,s.tgfilter,tp,LOCATION_ONFIELD,0,1,1,nil)
Duel.Hint(HINT_CARD,0,id)
Duel.SendtoGrave(sg,REASON_EFFECT|REASON_REPLACE)
return true
else return false end
end
function s.repval(e,c)
return s.repfilter(c,e:GetHandlerPlayer())
end | 412 | 0.954687 | 1 | 0.954687 | game-dev | MEDIA | 0.978644 | game-dev | 0.961317 | 1 | 0.961317 |
kora-projects/kora | 2,157 | grpc/grpc-client/src/main/java/ru/tinkoff/grpc/client/config/DefaultServiceConfigConfigValueExtractor.java | package ru.tinkoff.grpc.client.config;
import jakarta.annotation.Nullable;
import ru.tinkoff.kora.config.common.ConfigValue;
import ru.tinkoff.kora.config.common.extractor.ConfigValueExtractor;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public final class DefaultServiceConfigConfigValueExtractor implements ConfigValueExtractor<DefaultServiceConfig> {
@Nullable
@Override
public DefaultServiceConfig extract(ConfigValue<?> value) {
if (value.isNull()) {
return null;
}
var object = value.asObject();
var map = this.toMap(object);
return new DefaultServiceConfig(map);
}
private Map<String, Object> toMap(ConfigValue.ObjectValue objectValue) {
var result = new HashMap<String, Object>();
for (var entry : objectValue) {
var key = entry.getKey();
var value = entry.getValue();
var object = this.toObject(value);
if (object != null) {
result.put(key, object);
}
}
return result;
}
private Object toObject(ConfigValue<?> value) {
if (value instanceof ConfigValue.StringValue str) {
return str.value();
} else if (value instanceof ConfigValue.BooleanValue bool) {
return bool.value();
} else if (value instanceof ConfigValue.NumberValue num) {
return num.value().doubleValue(); // service config accepts only double values
} else if (value instanceof ConfigValue.ObjectValue obj) {
return this.toMap(obj);
} else if (value instanceof ConfigValue.ArrayValue arr) {
var list = new ArrayList<>();
for (var item : arr) {
var object = this.toObject(item);
if (object != null) {
list.add(object);
}
}
return list;
} else if (value instanceof ConfigValue.NullValue) {
return null;
} else {
throw new IllegalArgumentException("Unsupported config value type: " + value.getClass());
}
}
}
| 412 | 0.918388 | 1 | 0.918388 | game-dev | MEDIA | 0.190653 | game-dev | 0.947931 | 1 | 0.947931 |
ASNeG/OpcUaStack | 3,811 | tst/OpcUaStackCore/StandardDataTypes/BuildInfo_t.cpp | #include "unittest.h"
#include "OpcUaStackCore/Core/Core.h"
#include "OpcUaStackCore/BuildInTypes/OpcUaIdentifier.h"
#include "OpcUaStackCore/BuildInTypes/OpcUaExtensionObject.h"
#include "OpcUaStackCore/StandardDataTypes/BuildInfo.h"
using namespace OpcUaStackCore;
BOOST_AUTO_TEST_SUITE(BuildInfo_)
BOOST_AUTO_TEST_CASE(BuildInfo_)
{
std::cout << "BuildInfo_t" << std::endl;
}
BOOST_AUTO_TEST_CASE(BuildInfo_encode_decode)
{
BuildInfo value1;
BuildInfo value2;
OpcUaDateTime now(boost::posix_time::microsec_clock::local_time());
value1.productUri() = "ProductUri";
value1.manufacturerName() = "ManufacturerName";
value1.productName() = "ProductName";
value1.softwareVersion() = "SoftwareVersion";
value1.buildNumber() = "BuildNumber";
value1.buildDate() = now;
std::stringstream ss;
value1.opcUaBinaryEncode(ss);
value2.opcUaBinaryDecode(ss);
BOOST_REQUIRE(value2.productUri().value() == "ProductUri");
BOOST_REQUIRE(value2.manufacturerName().value() == "ManufacturerName");
BOOST_REQUIRE(value2.productName().value() == "ProductName");
BOOST_REQUIRE(value2.softwareVersion().value() == "SoftwareVersion");
BOOST_REQUIRE(value2.buildNumber().value() == "BuildNumber");
BOOST_REQUIRE(value2.buildDate() == now);
}
BOOST_AUTO_TEST_CASE(BuildInfo_ExtensionObject)
{
Core core;
core.init();
OpcUaExtensionObject value1;
OpcUaExtensionObject value2;
OpcUaDateTime now(boost::posix_time::microsec_clock::local_time());
OpcUaNodeId typeId;
typeId.set(OpcUaId_BuildInfo_Encoding_DefaultBinary);
value1.typeId(typeId);
value1.parameter<BuildInfo>()->productUri() = "ProductUri";
value1.parameter<BuildInfo>()->manufacturerName() = "ManufacturerName";
value1.parameter<BuildInfo>()->productName() = "ProductName";
value1.parameter<BuildInfo>()->softwareVersion() = "SoftwareVersion";
value1.parameter<BuildInfo>()->buildNumber() = "BuildNumber";
value1.parameter<BuildInfo>()->buildDate() = now;
std::stringstream ss;
value1.opcUaBinaryEncode(ss);
value2.opcUaBinaryDecode(ss);
BOOST_REQUIRE(value2.parameter<BuildInfo>()->productUri().value() == "ProductUri");
BOOST_REQUIRE(value2.parameter<BuildInfo>()->manufacturerName().value() == "ManufacturerName");
BOOST_REQUIRE(value2.parameter<BuildInfo>()->productName().value() == "ProductName");
BOOST_REQUIRE(value2.parameter<BuildInfo>()->softwareVersion().value() == "SoftwareVersion");
BOOST_REQUIRE(value2.parameter<BuildInfo>()->buildNumber().value() == "BuildNumber");
BOOST_REQUIRE(value2.parameter<BuildInfo>()->buildDate() == now);
}
BOOST_AUTO_TEST_CASE(BuildInfo_ExtensionObject_copyTo)
{
Core core;
core.init();
OpcUaExtensionObject value1;
OpcUaExtensionObject value2;
OpcUaDateTime now(boost::posix_time::microsec_clock::local_time());
OpcUaNodeId typeId;
typeId.set(OpcUaId_BuildInfo_Encoding_DefaultBinary);
value1.typeId(typeId);
value1.parameter<BuildInfo>()->productUri() = "ProductUri";
value1.parameter<BuildInfo>()->manufacturerName() = "ManufacturerName";
value1.parameter<BuildInfo>()->productName() = "ProductName";
value1.parameter<BuildInfo>()->softwareVersion() = "SoftwareVersion";
value1.parameter<BuildInfo>()->buildNumber() = "BuildNumber";
value1.parameter<BuildInfo>()->buildDate() = now;
value1.copyTo(value2);
BOOST_REQUIRE(value2.parameter<BuildInfo>()->productUri().value() == "ProductUri");
BOOST_REQUIRE(value2.parameter<BuildInfo>()->manufacturerName().value() == "ManufacturerName");
BOOST_REQUIRE(value2.parameter<BuildInfo>()->productName().value() == "ProductName");
BOOST_REQUIRE(value2.parameter<BuildInfo>()->softwareVersion().value() == "SoftwareVersion");
BOOST_REQUIRE(value2.parameter<BuildInfo>()->buildNumber().value() == "BuildNumber");
BOOST_REQUIRE(value2.parameter<BuildInfo>()->buildDate() == now);
}
BOOST_AUTO_TEST_SUITE_END()
| 412 | 0.743532 | 1 | 0.743532 | game-dev | MEDIA | 0.240997 | game-dev | 0.664212 | 1 | 0.664212 |
alexchao26/advent-of-code-go | 13,221 | 2019/day15/part2/main.go | /*
Intcode struct is defined within this file
Robot struct houses an Intcode computer and its RecursiveMove method populates a map of
coordinates to the floor type (-1: wall, 1: hallway, 2: O2 tank, 5: origin)
That map is converted into a 2D grid (slice)
The shortest length is no longer needed
Two functions added that determine if the space is full of O2 and to spreadOxygen for one minute
*/
package main
import (
"fmt"
"log"
"strconv"
"strings"
"github.com/alexchao26/advent-of-code-go/algos"
"github.com/alexchao26/advent-of-code-go/mathy"
"github.com/alexchao26/advent-of-code-go/util"
)
func main() {
// read the input file, modify it to a slice of numbers
inputFile := util.ReadFile("../input.txt")
splitStrings := strings.Split(inputFile, ",")
inputNumbers := make([]int, len(splitStrings))
for i, v := range splitStrings {
inputNumbers[i], _ = strconv.Atoi(v)
}
robot := MakeRobot(inputNumbers)
// fire off recursive move function to populate the robot's floorDetails property
robot.RecursiveMove()
// make grid from the map of coordinates to floor types
grid := Draw(robot.floorDetails)
// overwrite the origin with a 1 (open floor space)
for y, row := range grid {
for x, tileType := range row {
if tileType == 5 {
grid[y][x] = 1
}
}
}
// while the grid is not full of oxygen, spread oxygen and increment minutes
var minutes int
for !isFullOfOxygen(grid) {
spreadOxygen(grid)
minutes++
}
fmt.Println("Minutes elapsed", minutes)
}
func isFullOfOxygen(grid [][]int) bool {
for _, row := range grid {
for _, tile := range row {
// if there is a hallway space that is not filled with O2, return false
if tile == 1 {
return false
}
}
}
// if entire looping passes, return true
return true
}
var dRow []int = []int{0, 0, -1, 1}
var dCol []int = []int{-1, 1, 0, 0}
// spreadOxygen will spread all oxygen to one neighboring cell
// returns boolean true if O2 has not spread everywhere (i.e. run again), false if O2 is everywhere
func spreadOxygen(grid [][]int) {
// traverse through grid and mark all cells that are a 1 and have a neighboring 2
// tag with -1
for i := 0; i < len(grid); i++ {
for j := 0; j < len(grid[0]); j++ {
if grid[i][j] == 1 {
// traverse around neighbors
for d := 0; d < 4; d++ {
neighborRow := i + dRow[d]
neighborCol := j + dCol[d]
inBounds := neighborRow >= 0 && neighborRow < len(grid) && neighborCol >= 0 && neighborCol < len(grid[0])
// if a neighboring cell is a 2 (i.e. filled with oxygen), then mark this cell
if inBounds && grid[neighborRow][neighborCol] == 2 {
grid[i][j] = -1
break
}
}
}
}
}
// then iterate through again changing all -1's to a 2
for i := 0; i < len(grid); i++ {
for j := 0; j < len(grid); j++ {
if grid[i][j] == -1 {
grid[i][j] = 2
}
}
}
}
// Robot struct to maintain detail's on the Robot's coordinates, path
type Robot struct {
fromTop, fromLeft int
floorDetails map[string]int // maps coordinates and type of tile (0 == wall, 1 == path, 2 == oxygen)
computer *Intcode
}
// MakeRobot returns an instance of a Robot
func MakeRobot(intcodeInput []int) *Robot {
return &Robot{
0,
0,
map[string]int{"0,0": 5}, // mark the origin specially with a 5
MakeComputer(intcodeInput),
}
}
var backtrack map[int]int = map[int]int{
1: 2, // north (1), south (2)
2: 1,
3: 4, // west (3), east(4)
4: 3,
}
// dx is the difference to add when traveling in the given direction
// i.e. add 0 for north and south, for west decrement 1, for east add 1
var dx map[int]int = map[int]int{
1: 0,
2: 0,
3: -1,
4: 1,
}
// dy is the vertical distance traveled
var dy map[int]int = map[int]int{
1: 1,
2: -1,
3: 0,
4: 0,
}
// RecursiveMove will populate a robot's floor details property by traveling in all directions
// and
func (robot *Robot) RecursiveMove() {
for i := 1; i <= 4; i++ {
// if next coordinates have already been detailed, skip all calculations
nextCoords := fmt.Sprintf("%v,%v", robot.fromTop+dy[i], robot.fromLeft+dx[i])
if robot.floorDetails[nextCoords] == 0 {
robot.computer.Step(i)
computerOutput := robot.computer.Outputs[len(robot.computer.Outputs)-1]
switch computerOutput {
case 0: // hit a wall, do not recurse
// update robot's wall coords to include the wall
// note representing walls with a -1 to avoid the zero value detection
robot.floorDetails[nextCoords] = -1
case 1, 2: // walked and hit the O2 tank or not
// update floorDetails
robot.floorDetails[nextCoords] = computerOutput
// continue to walk the robot. walk the robot into the nextCoords spot
robot.fromLeft += dx[i]
robot.fromTop += dy[i]
// recurse
robot.RecursiveMove()
// backtrack so the robot walks in the remainder of directions from this output
robot.fromLeft -= dx[i]
robot.fromTop -= dy[i]
// backtrack the computer
robot.computer.Step(backtrack[i])
}
}
}
}
/*
Intcode is an OOP approach *************************************************
MakeComputer is equivalent to the constructor
Step takes in an input int and updates properties in the computer:
- InstructionIndex: where to read the next instruction from
- LastOutput, what the last opcode 4 outputted
- PuzzleIndex based if the last instruction modified the puzzle at all
****************************************************************************/
type Intcode struct {
PuzzleInput []int // file/puzzle input parsed into slice of ints
InstructionIndex int // stores the index where the next instruction is
RelativeBase int // relative base for opcode 9 and param mode 2
Outputs []int // stores all outputs
IsRunning bool // will be true until a 99 opcode is hit
}
// MakeComputer initializes a new comp
func MakeComputer(PuzzleInput []int) *Intcode {
puzzleInputCopy := make([]int, len(PuzzleInput))
copy(puzzleInputCopy, PuzzleInput)
comp := Intcode{
puzzleInputCopy,
0,
0,
make([]int, 0),
true,
}
return &comp
}
// Step will read the next 4 values in the input `sli` and make updates
// according to the opcodes
func (comp *Intcode) Step(input int) {
// read the instruction, opcode and the indexes where the params point to
opcode, paramIndexes := comp.GetOpCodeAndParamIndexes()
param1, param2, param3 := paramIndexes[0], paramIndexes[1], paramIndexes[2]
// ensure params are within the bounds of PuzzleInput, resize if necessary
// Note: need to optimize this to not resize if the params are not being used
switch opcode {
case 1, 2, 7, 8:
comp.ResizeMemory(param1, param2, param3)
case 5, 6:
comp.ResizeMemory(param1, param2)
case 3, 4, 9:
comp.ResizeMemory(param1)
}
switch opcode {
case 99: // 99: Terminates program
fmt.Println("Terminating...")
comp.IsRunning = false
case 1: // 1: Add next two paramIndexes, store in third
comp.PuzzleInput[param3] = comp.PuzzleInput[param1] + comp.PuzzleInput[param2]
comp.InstructionIndex += 4
comp.Step(input)
case 2: // 2: Multiply next two and store in third
comp.PuzzleInput[param3] = comp.PuzzleInput[param1] * comp.PuzzleInput[param2]
comp.InstructionIndex += 4
comp.Step(input)
case 3: // 3: Takes one input and saves it to position of one parameter
// check if input has already been used (i.e. input == -1)
// if it's been used, return out to prevent further Steps
// NOTE: making a big assumption that -1 will never be an input...
if input == -1 {
return
}
// else recurse with a -1 to signal the initial input has been processed
comp.PuzzleInput[param1] = input
comp.InstructionIndex += 2
comp.Step(-1)
case 4: // 4: outputs its input value
// set LastOutput of the computer & log it
comp.Outputs = append(comp.Outputs, comp.PuzzleInput[param1])
// fmt.Printf("Opcode 4 output: %v\n", comp.LastOutput)
comp.InstructionIndex += 2
// continue running until terminates or asks for another input
comp.Step(input)
// 5: jump-if-true: if first param != 0, move pointer to second param, else nothing
case 5:
if comp.PuzzleInput[param1] != 0 {
comp.InstructionIndex = comp.PuzzleInput[param2]
} else {
comp.InstructionIndex += 3
}
comp.Step(input)
// 6: jump-if-false, if first param == 0 then set instruction pointer to 2nd param, else nothing
case 6:
if comp.PuzzleInput[param1] == 0 {
comp.InstructionIndex = comp.PuzzleInput[param2]
} else {
comp.InstructionIndex += 3
}
comp.Step(input)
// 7: less-than, if param1 < param2 then store 1 in postion of 3rd param, else store 0
case 7:
if comp.PuzzleInput[param1] < comp.PuzzleInput[param2] {
comp.PuzzleInput[param3] = 1
} else {
comp.PuzzleInput[param3] = 0
}
comp.InstructionIndex += 4
comp.Step(input)
// 8: equals, if param1 == param2 then set position of 3rd param to 1, else store 0
case 8:
if comp.PuzzleInput[param1] == comp.PuzzleInput[param2] {
comp.PuzzleInput[param3] = 1
} else {
comp.PuzzleInput[param3] = 0
}
comp.InstructionIndex += 4
comp.Step(input)
// 9: adjust relative base
case 9:
comp.RelativeBase += comp.PuzzleInput[param1]
comp.InstructionIndex += 2
comp.Step(input)
default:
log.Fatalf("Error: unknown opcode %v at index %v", opcode, comp.PuzzleInput[comp.InstructionIndex])
}
}
/*
GetOpCodeAndParamIndexes will parse the instruction at comp.PuzzleInput[comp.InstructionIndex]
- opcode will be the left two digits, mod by 100 will get that
- rest of instructions will be grabbed via mod 10
- these also have to be parsed for the
*/
func (comp *Intcode) GetOpCodeAndParamIndexes() (int, [3]int) {
instruction := comp.PuzzleInput[comp.InstructionIndex]
// opcode is the lowest two digits, so mod by 100
opcode := instruction % 100
instruction /= 100
// assign the indexes that need to be read by reading the parameter modes
var paramIndexes [3]int
for i := 1; i <= 3 && comp.InstructionIndex+i < len(comp.PuzzleInput); i++ {
// grab the mode with a mod, last digit
mode := instruction % 10
instruction /= 10
switch mode {
case 0: // position mode, index will be the value at the index
paramIndexes[i-1] = comp.PuzzleInput[comp.InstructionIndex+i]
case 1: // immediate mode, the index itself
paramIndexes[i-1] = comp.InstructionIndex + i
case 2: // relative mode, like position mode but index is added to relative base
paramIndexes[i-1] = comp.PuzzleInput[comp.InstructionIndex+i] + comp.RelativeBase
}
}
return opcode, paramIndexes
}
// ResizeMemory will take any number of integers and resize the computer's memory appropriately
func (comp *Intcode) ResizeMemory(sizes ...int) {
// get largest of input sizes
maxArg := sizes[0]
for _, v := range sizes {
if v > maxArg {
maxArg = v
}
}
// resize if PuzzleInput's length is shorter
if maxArg >= len(comp.PuzzleInput) {
// make empty slice to copy into, of the new, larger size
resizedPuzzleInput := make([]int, maxArg+1)
// copy old puzzle input values in
copy(resizedPuzzleInput, comp.PuzzleInput)
// overwrite puzzle input
comp.PuzzleInput = resizedPuzzleInput
}
}
// Draw was copied from day11. It converts a map of points mapped from a (0,0) origin to a 2D grid
// The origin loses its reference...
func Draw(mapCoordsToType map[string]int) [][]int {
var lowX, highX, lowY, highY int
for key := range mapCoordsToType {
coords := strings.Split(key, ",")
x, _ := strconv.Atoi(coords[0])
y, _ := strconv.Atoi(coords[1])
switch {
case x < lowX:
lowX = x
case x > highX:
highX = x
}
switch {
case y < lowY:
lowY = y
case y > highY:
highY = y
}
}
// Determine the bounds of the grid
edgeLength := 2 * mathy.MaxInt(-lowY, -lowX, highY, highX)
grid := make([][]int, edgeLength)
for i := 0; i < edgeLength; i++ {
// each character will initialize as a space character
grid[i] = make([]int, edgeLength)
}
// Iterate through all coordinates and transcribe x,y onto a 2D grid
// where the math is a little different...
for key, val := range mapCoordsToType {
// key is string coords
coords := strings.Split(key, ",")
x, _ := strconv.Atoi(coords[0])
y, _ := strconv.Atoi(coords[1])
x += edgeLength / 2
y += edgeLength / 2
// val is color to paint (1 or 0)
if val != -1 {
grid[x][y] = val
}
}
// trim off due to making the initial grid too large
grid = trim(grid)
// rotate it because of how I coded up the robot's coordinates :/
grid = algos.RotateIntGrid(grid)
// retrim
grid = trim(grid)
return grid
}
// helper function for Draw to remove whitespace from overestimating the size
// of the drawing space
func trim(grid [][]int) [][]int {
// remove all empty rows at top and bottom
removeRowsTop:
for i := 0; i < len(grid); {
for j := 0; j < len(grid[i]); j++ {
if grid[i][j] != 0 {
break removeRowsTop
}
}
grid = grid[1:]
}
// remove empty columns on left
removeColsLeft:
for i := 0; i < len(grid[0]); {
for j := 0; j < len(grid); j++ {
if grid[j][i] != 0 {
break removeColsLeft
}
}
// if loop hasn't broken out, iterate over first "column" and slice off "0-index"
for j := 0; j < len(grid); j++ {
grid[j] = grid[j][1:]
}
}
return grid
}
| 412 | 0.906042 | 1 | 0.906042 | game-dev | MEDIA | 0.531572 | game-dev | 0.862936 | 1 | 0.862936 |
CrucibleMC/Crucible | 5,465 | src/main/java/net/md_5/bungee/api/chat/TextComponent.java | package net.md_5.bungee.api.chat;
import net.md_5.bungee.api.ChatColor;
import java.beans.ConstructorProperties;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TextComponent
extends BaseComponent {
private static final Pattern url = Pattern.compile("^(?:(https?)://)?([-\\w_\\.]{2,}\\.[a-z]{2,4})(/\\S*)?$");
private String text;
public TextComponent(TextComponent textComponent) {
super(textComponent);
this.setText(textComponent.getText());
}
public /* varargs */ TextComponent(BaseComponent... extras) {
this.setText("");
this.setExtra(new ArrayList<BaseComponent>(Arrays.asList(extras)));
}
@ConstructorProperties(value = {"text"})
public TextComponent(String text) {
this.text = text;
}
public TextComponent() {
}
public static BaseComponent[] fromLegacyText(String message) {
ArrayList<TextComponent> components = new ArrayList<TextComponent>();
StringBuilder builder = new StringBuilder();
TextComponent component = new TextComponent();
Matcher matcher = url.matcher(message);
block8:
for (int i = 0; i < message.length(); ++i) {
TextComponent old;
char c = message.charAt(i);
if (c == '\u00a7') {
ChatColor format;
if ((c = message.charAt(++i)) >= 'A' && c <= 'Z') {
c = (char) (c + 32);
}
if ((format = ChatColor.getByChar(c)) == null) continue;
if (builder.length() > 0) {
old = component;
component = new TextComponent(old);
old.setText(builder.toString());
builder = new StringBuilder();
components.add(old);
}
switch (format) {
case BOLD: {
component.setBold(true);
continue block8;
}
case ITALIC: {
component.setItalic(true);
continue block8;
}
case UNDERLINE: {
component.setUnderlined(true);
continue block8;
}
case STRIKETHROUGH: {
component.setStrikethrough(true);
continue block8;
}
case MAGIC: {
component.setObfuscated(true);
continue block8;
}
case RESET: {
format = ChatColor.WHITE;
}
}
component = new TextComponent();
component.setColor(format);
continue;
}
int pos = message.indexOf(32, i);
if (pos == -1) {
pos = message.length();
}
if (matcher.region(i, pos).find()) {
if (builder.length() > 0) {
old = component;
component = new TextComponent(old);
old.setText(builder.toString());
builder = new StringBuilder();
components.add(old);
}
old = component;
component = new TextComponent(old);
String urlString = message.substring(i, pos);
component.setText(urlString);
component.setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, urlString.startsWith("http") ? urlString : "http://" + urlString));
components.add(component);
i += pos - i - 1;
component = old;
continue;
}
builder.append(c);
}
if (builder.length() > 0) {
component.setText(builder.toString());
components.add(component);
}
if (components.isEmpty()) {
components.add(new TextComponent(""));
}
return components.toArray(new BaseComponent[components.size()]);
}
@Override
public BaseComponent duplicate() {
return new TextComponent(this);
}
@Override
protected void toPlainText(StringBuilder builder) {
builder.append(this.text);
super.toPlainText(builder);
}
@Override
protected void toLegacyText(StringBuilder builder) {
builder.append(this.getColor());
if (this.isBold()) {
builder.append(ChatColor.BOLD);
}
if (this.isItalic()) {
builder.append(ChatColor.ITALIC);
}
if (this.isUnderlined()) {
builder.append(ChatColor.UNDERLINE);
}
if (this.isStrikethrough()) {
builder.append(ChatColor.STRIKETHROUGH);
}
if (this.isObfuscated()) {
builder.append(ChatColor.MAGIC);
}
builder.append(this.text);
super.toLegacyText(builder);
}
@Override
public String toString() {
return String.format("TextComponent{text=%s, %s}", this.text, super.toString());
}
public String getText() {
return this.text;
}
public void setText(String text) {
this.text = text;
}
}
| 412 | 0.766176 | 1 | 0.766176 | game-dev | MEDIA | 0.60459 | game-dev | 0.956526 | 1 | 0.956526 |
OpenEMS/openems | 7,461 | io.openems.edge.simulator/src/io/openems/edge/simulator/ess/asymmetric/reacting/SimulatorEssAsymmetricReactingImpl.java | package io.openems.edge.simulator.ess.asymmetric.reacting;
import java.io.IOException;
import org.osgi.service.cm.ConfigurationAdmin;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.ConfigurationPolicy;
import org.osgi.service.component.annotations.Deactivate;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.osgi.service.component.annotations.ReferencePolicy;
import org.osgi.service.component.annotations.ReferencePolicyOption;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventHandler;
import org.osgi.service.event.propertytypes.EventTopics;
import org.osgi.service.metatype.annotations.Designate;
import io.openems.common.channel.AccessMode;
import io.openems.common.exceptions.OpenemsException;
import io.openems.edge.common.component.AbstractOpenemsComponent;
import io.openems.edge.common.component.OpenemsComponent;
import io.openems.edge.common.event.EdgeEventConstants;
import io.openems.edge.common.modbusslave.ModbusSlave;
import io.openems.edge.common.modbusslave.ModbusSlaveNatureTable;
import io.openems.edge.common.modbusslave.ModbusSlaveTable;
import io.openems.edge.ess.api.AsymmetricEss;
import io.openems.edge.ess.api.ManagedAsymmetricEss;
import io.openems.edge.ess.api.ManagedSymmetricEss;
import io.openems.edge.ess.api.SymmetricEss;
import io.openems.edge.ess.power.api.Power;
import io.openems.edge.simulator.datasource.api.SimulatorDatasource;
import io.openems.edge.timedata.api.Timedata;
import io.openems.edge.timedata.api.TimedataProvider;
import io.openems.edge.timedata.api.utils.CalculateEnergyFromPower;
@Designate(ocd = Config.class, factory = true)
@Component(//
name = "Simulator.EssAsymmetric.Reacting", //
immediate = true, //
configurationPolicy = ConfigurationPolicy.REQUIRE //
)
@EventTopics({ //
EdgeEventConstants.TOPIC_CYCLE_AFTER_PROCESS_IMAGE //
})
public class SimulatorEssAsymmetricReactingImpl extends AbstractOpenemsComponent
implements SimulatorEssAsymmetricReacting, ManagedAsymmetricEss, AsymmetricEss, ManagedSymmetricEss,
SymmetricEss, OpenemsComponent, TimedataProvider, EventHandler, ModbusSlave {
private final CalculateEnergyFromPower calculateChargeEnergy = new CalculateEnergyFromPower(this,
SymmetricEss.ChannelId.ACTIVE_CHARGE_ENERGY);
private final CalculateEnergyFromPower calculateDischargeEnergy = new CalculateEnergyFromPower(this,
SymmetricEss.ChannelId.ACTIVE_DISCHARGE_ENERGY);
@Reference
private Power power;
@Reference(policy = ReferencePolicy.STATIC, policyOption = ReferencePolicyOption.GREEDY, cardinality = ReferenceCardinality.MANDATORY)
private SimulatorDatasource datasource;
@Reference
private ConfigurationAdmin cm;
@Reference(policy = ReferencePolicy.DYNAMIC, policyOption = ReferencePolicyOption.GREEDY, cardinality = ReferenceCardinality.OPTIONAL)
private volatile Timedata timedata = null;
/** Current state of charge. */
private float soc = 0;
private Config config;
public SimulatorEssAsymmetricReactingImpl() {
super(//
OpenemsComponent.ChannelId.values(), //
SymmetricEss.ChannelId.values(), //
ManagedSymmetricEss.ChannelId.values(), //
AsymmetricEss.ChannelId.values(), //
ManagedAsymmetricEss.ChannelId.values(), //
SimulatorEssAsymmetricReacting.ChannelId.values() //
);
}
@Activate
private void activate(ComponentContext context, Config config) throws IOException {
super.activate(context, config.id(), config.alias(), config.enabled());
// update filter for 'datasource'
if (OpenemsComponent.updateReferenceFilter(this.cm, this.servicePid(), "datasource", config.datasource_id())) {
return;
}
this.config = config;
this._setSoc(config.initialSoc());
this.soc = config.initialSoc();
this._setCapacity(config.capacity());
this._setMaxApparentPower(config.maxApparentPower());
this._setAllowedChargePower(config.maxApparentPower() * -1);
this._setAllowedDischargePower(config.maxApparentPower());
this._setGridMode(config.gridMode());
}
@Override
@Deactivate
protected void deactivate() {
super.deactivate();
}
@Override
public void handleEvent(Event event) {
if (!this.isEnabled()) {
return;
}
switch (event.getTopic()) {
case EdgeEventConstants.TOPIC_CYCLE_AFTER_PROCESS_IMAGE:
this.calculateEnergy();
break;
}
}
@Override
public String debugLog() {
return "SoC:" + this.getSoc().asString() //
+ "|L:" + this.getActivePower().asString() //
+ "|" + this.getGridModeChannel().value().asOptionString();
}
@Override
public Power getPower() {
return this.power;
}
@Override
public void applyPower(int activePowerL1, int reactivePowerL1, int activePowerL2, int reactivePowerL2,
int activePowerL3, int reactivePowerL3) throws OpenemsException {
var activePower = activePowerL1 + activePowerL2 + activePowerL3;
/*
* calculate State of charge
*/
var watthours = (float) activePower * this.datasource.getTimeDelta() / 3600;
var socChange = watthours / this.config.capacity();
this.soc -= socChange;
if (this.soc > 100) {
this.soc = 100;
} else if (this.soc < 0) {
this.soc = 0;
}
this._setSoc(Math.round(this.soc));
/*
* Apply Active/Reactive power to simulated channels
*/
this._setActivePowerL1(activePowerL1);
this._setActivePowerL2(activePowerL2);
this._setActivePowerL3(activePowerL3);
this._setActivePower(activePower);
var reactivePower = reactivePowerL1 + reactivePowerL2 + reactivePowerL3;
this._setReactivePowerL1(reactivePowerL1);
this._setReactivePowerL2(reactivePowerL2);
this._setReactivePowerL3(reactivePowerL3);
this._setReactivePower(reactivePower);
/*
* Set AllowedCharge / Discharge based on SoC
*/
if (this.soc == 100) {
this._setAllowedChargePower(0);
} else {
this._setAllowedChargePower(this.config.maxApparentPower() * -1);
}
if (this.soc == 0) {
this._setAllowedDischargePower(0);
} else {
this._setAllowedDischargePower(this.config.maxApparentPower());
}
}
@Override
public int getPowerPrecision() {
return 1;
}
@Override
public ModbusSlaveTable getModbusSlaveTable(AccessMode accessMode) {
return new ModbusSlaveTable(//
OpenemsComponent.getModbusSlaveNatureTable(accessMode), //
SymmetricEss.getModbusSlaveNatureTable(accessMode), //
ManagedSymmetricEss.getModbusSlaveNatureTable(accessMode), //
AsymmetricEss.getModbusSlaveNatureTable(accessMode), //
ManagedAsymmetricEss.getModbusSlaveNatureTable(accessMode), //
ModbusSlaveNatureTable.of(SimulatorEssAsymmetricReactingImpl.class, accessMode, 300) //
.build());
}
/**
* Calculate the Energy values from ActivePower.
*/
private void calculateEnergy() {
// Calculate Energy
var activePower = this.getActivePower().get();
if (activePower == null) {
// Not available
this.calculateChargeEnergy.update(null);
this.calculateDischargeEnergy.update(null);
} else if (activePower > 0) {
// Buy-From-Grid
this.calculateChargeEnergy.update(0);
this.calculateDischargeEnergy.update(activePower);
} else {
// Sell-To-Grid
this.calculateChargeEnergy.update(activePower * -1);
this.calculateDischargeEnergy.update(0);
}
}
@Override
public Timedata getTimedata() {
return this.timedata;
}
}
| 412 | 0.924031 | 1 | 0.924031 | game-dev | MEDIA | 0.267117 | game-dev | 0.938211 | 1 | 0.938211 |
StudentBlake/XCI-Explorer | 1,126 | XCI_Explorer/TreeViewFileSystem.cs | using System.Windows.Forms;
using XCI_Explorer.Helpers;
namespace XCI_Explorer;
public class TreeViewFileSystem
{
public TreeView treeView;
public TreeViewFileSystem(TreeView tv)
{
}
public BetterTreeNode AddDir(string name, BetterTreeNode parent = null)
{
BetterTreeNode betterTreeNode = new(name)
{
Offset = -1L,
Size = -1L
};
parent.Nodes.Add(betterTreeNode);
return betterTreeNode;
}
public BetterTreeNode AddFile(string name, BetterTreeNode parent, long offset, long size) => AddFile(name, parent, offset, size, 0, "", "");
public BetterTreeNode AddFile(string name, BetterTreeNode parent, long offset, long size, long HashedRegionSize, string ExpectedHash, string ActualHash)
{
BetterTreeNode betterTreeNode = new(name)
{
Offset = offset,
Size = size,
ExpectedHash = ExpectedHash,
ActualHash = ActualHash,
HashedRegionSize = HashedRegionSize
};
parent.Nodes.Add(betterTreeNode);
return betterTreeNode;
}
}
| 412 | 0.849567 | 1 | 0.849567 | game-dev | MEDIA | 0.253182 | game-dev | 0.90685 | 1 | 0.90685 |
gamingdotme/opensource-casino-v10 | 42,383 | casino/app/Games/WormVS/SlotSettings.php | <?php
namespace VanguardLTE\Games\WormVS
{
class SlotSettings
{
public $playerId = null;
public $splitScreen = null;
public $reelStrip1 = null;
public $reelStrip2 = null;
public $reelStrip3 = null;
public $reelStrip4 = null;
public $reelStrip5 = null;
public $reelStrip6 = null;
public $reelStripBonus1 = null;
public $reelStripBonus2 = null;
public $reelStripBonus3 = null;
public $reelStripBonus4 = null;
public $reelStripBonus5 = null;
public $reelStripBonus6 = null;
public $slotId = '';
public $slotDBId = '';
public $Line = null;
public $scaleMode = null;
public $numFloat = null;
public $gameLine = null;
public $Bet = null;
public $isBonusStart = null;
public $Balance = null;
public $SymbolGame = null;
public $GambleType = null;
public $lastEvent = null;
public $Jackpots = [];
public $keyController = null;
public $slotViewState = null;
public $hideButtons = null;
public $slotReelsConfig = null;
public $slotFreeCount = null;
public $slotFreeMpl = null;
public $slotWildMpl = null;
public $slotExitUrl = null;
public $slotBonus = null;
public $slotBonusType = null;
public $slotScatterType = null;
public $slotGamble = null;
public $Paytable = [];
public $slotSounds = [];
public $jpgs = null;
private $Bank = null;
private $Percent = null;
private $WinLine = null;
private $WinGamble = null;
private $Bonus = null;
private $shop_id = null;
public $currency = null;
public $user = null;
public $game = null;
public $shop = null;
public $jpgPercentZero = false;
public $count_balance = null;
public function __construct($sid, $playerId)
{
$this->slotId = $sid;
$this->playerId = $playerId;
$user = \VanguardLTE\User::lockForUpdate()->find($this->playerId);
$this->user = $user;
$this->shop_id = $user->shop_id;
$gamebank = \VanguardLTE\GameBank::where(['shop_id' => $this->shop_id])->lockForUpdate()->get();
$game = \VanguardLTE\Game::where([
'name' => $this->slotId,
'shop_id' => $this->shop_id
])->lockForUpdate()->first();
$this->shop = \VanguardLTE\Shop::find($this->shop_id);
$this->game = $game;
$this->MaxWin = $this->shop->max_win;
$this->increaseRTP = 1;
$this->CurrentDenom = $this->game->denomination;
$this->scaleMode = 0;
$this->numFloat = 0;
$this->Paytable['SYM_1'] = [
0,
0,
0,
100,
800,
10000
];
$this->Paytable['SYM_2'] = [
0,
0,
0,
0,
0,
0
];
$this->Paytable['SYM_3'] = [
0,
0,
0,
50,
350,
5000
];
$this->Paytable['SYM_4'] = [
0,
0,
0,
30,
200,
3000
];
$this->Paytable['SYM_5'] = [
0,
0,
0,
15,
80,
800
];
$this->Paytable['SYM_6'] = [
0,
0,
0,
12,
70,
400
];
$this->Paytable['SYM_7'] = [
0,
0,
0,
20,
20,
20
];
$this->Paytable['SYM_8'] = [
0,
0,
0,
10,
50,
250
];
$this->Paytable['SYM_9'] = [
0,
0,
0,
10,
35,
150
];
$this->Paytable['SYM_10'] = [
0,
0,
0,
10,
25,
100
];
$this->Paytable['SYM_11'] = [
0,
0,
0,
10,
20,
80
];
$this->Paytable['SYM_12'] = [
0,
0,
0,
0,
0,
0
];
$reel = new GameReel();
foreach( [
'reelStrip1',
'reelStrip2',
'reelStrip3',
'reelStrip4',
'reelStrip5',
'reelStrip6'
] as $reelStrip )
{
if( count($reel->reelsStrip[$reelStrip]) )
{
$this->$reelStrip = $reel->reelsStrip[$reelStrip];
}
}
foreach( [
'reelStripBonus1',
'reelStripBonus2',
'reelStripBonus3',
'reelStripBonus4',
'reelStripBonus5',
'reelStripBonus6'
] as $reelStrip )
{
if( count($reel->reelsStripBonus[$reelStrip]) )
{
$this->$reelStrip = $reel->reelsStripBonus[$reelStrip];
}
}
foreach( [
'reelStripBonus1',
'reelStripBonus2',
'reelStripBonus3',
'reelStripBonus4',
'reelStripBonus5',
'reelStripBonus6'
] as $reelStrip )
{
if( count($reel->reelsStripBonus[$reelStrip]) )
{
$this->$reelStrip = $reel->reelsStripBonus[$reelStrip];
}
}
$this->keyController = [
'13' => 'uiButtonSpin,uiButtonSkip',
'49' => 'uiButtonInfo',
'50' => 'uiButtonCollect',
'51' => 'uiButtonExit2',
'52' => 'uiButtonLinesMinus',
'53' => 'uiButtonLinesPlus',
'54' => 'uiButtonBetMinus',
'55' => 'uiButtonBetPlus',
'56' => 'uiButtonGamble',
'57' => 'uiButtonRed',
'48' => 'uiButtonBlack',
'189' => 'uiButtonAuto',
'187' => 'uiButtonSpin'
];
$this->slotReelsConfig = [
[
425,
142,
3
],
[
669,
142,
3
],
[
913,
142,
3
],
[
1157,
142,
3
],
[
1401,
142,
3
]
];
$this->slotBonusType = 1;
$this->slotScatterType = 0;
$this->splitScreen = false;
$this->slotBonus = true;
$this->slotGamble = true;
$this->slotFastStop = 1;
$this->slotExitUrl = '/';
$this->slotWildMpl = 1;
$this->GambleType = 1;
$this->slotFreeCount = 20;
$this->slotFreeMpl = 1;
$this->slotViewState = ($game->slotViewState == '' ? 'Normal' : $game->slotViewState);
$this->hideButtons = [];
$this->jpgs = \VanguardLTE\JPG::where('shop_id', $this->shop_id)->lockForUpdate()->get();
$this->Line = [
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15
];
$this->gameLine = [
1,
3,
5,
7,
9
];
$this->Bet = explode(',', $game->bet);
$this->Balance = $user->balance;
$this->SymbolGame = [
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12
];
$this->Bank = $game->get_gamebank();
$this->Percent = $this->shop->percent;
$this->WinGamble = $game->rezerv;
$this->slotDBId = $game->id;
$this->slotCurrency = $user->shop->currency;
$this->count_balance = $user->count_balance;
if( $user->address > 0 && $user->count_balance == 0 )
{
$this->Percent = 0;
$this->jpgPercentZero = true;
}
else if( $user->count_balance == 0 )
{
$this->Percent = 100;
}
if( !isset($this->user->session) || strlen($this->user->session) <= 0 )
{
$this->user->session = serialize([]);
}
$this->gameData = unserialize($this->user->session);
if( count($this->gameData) > 0 )
{
foreach( $this->gameData as $key => $vl )
{
if( $vl['timelife'] <= time() )
{
unset($this->gameData[$key]);
}
}
}
if( !isset($this->game->advanced) || strlen($this->game->advanced) <= 0 )
{
$this->game->advanced = serialize([]);
}
$this->gameDataStatic = unserialize($this->game->advanced);
if( count($this->gameDataStatic) > 0 )
{
foreach( $this->gameDataStatic as $key => $vl )
{
if( $vl['timelife'] <= time() )
{
unset($this->gameDataStatic[$key]);
}
}
}
}
public function is_active()
{
if( $this->game && $this->shop && $this->user && (!$this->game->view || $this->shop->is_blocked || $this->user->is_blocked || $this->user->status == \VanguardLTE\Support\Enum\UserStatus::BANNED) )
{
\VanguardLTE\Session::where('user_id', $this->user->id)->delete();
$this->user->update(['remember_token' => null]);
return false;
}
if( !$this->game->view )
{
return false;
}
if( $this->shop->is_blocked )
{
return false;
}
if( $this->user->is_blocked )
{
return false;
}
if( $this->user->status == \VanguardLTE\Support\Enum\UserStatus::BANNED )
{
return false;
}
return true;
}
public function SetGameData($key, $value)
{
$timeLife = 86400;
$this->gameData[$key] = [
'timelife' => time() + $timeLife,
'payload' => $value
];
}
public function GetGameData($key)
{
if( isset($this->gameData[$key]) )
{
return $this->gameData[$key]['payload'];
}
else
{
return 0;
}
}
public function FormatFloat($num)
{
$str0 = explode('.', $num);
if( isset($str0[1]) )
{
if( strlen($str0[1]) > 4 )
{
return round($num * 100) / 100;
}
else if( strlen($str0[1]) > 2 )
{
return floor($num * 100) / 100;
}
else
{
return $num;
}
}
else
{
return $num;
}
}
public function SaveGameData()
{
$this->user->session = serialize($this->gameData);
$this->user->save();
}
public function CheckBonusWin()
{
$allRateCnt = 0;
$allRate = 0;
foreach( $this->Paytable as $vl )
{
foreach( $vl as $vl2 )
{
if( $vl2 > 0 )
{
$allRateCnt++;
$allRate += $vl2;
break;
}
}
}
return $allRate / $allRateCnt;
}
public function GetRandomPay()
{
$allRate = [];
foreach( $this->Paytable as $vl )
{
foreach( $vl as $vl2 )
{
if( $vl2 > 0 )
{
$allRate[] = $vl2;
}
}
}
shuffle($allRate);
if( $this->game->stat_in < ($this->game->stat_out + ($allRate[0] * $this->AllBet)) )
{
$allRate[0] = 0;
}
return $allRate[0];
}
public function HasGameDataStatic($key)
{
if( isset($this->gameDataStatic[$key]) )
{
return true;
}
else
{
return false;
}
}
public function SaveGameDataStatic()
{
$this->game->advanced = serialize($this->gameDataStatic);
$this->game->save();
$this->game->refresh();
}
public function SetGameDataStatic($key, $value)
{
$timeLife = 86400;
$this->gameDataStatic[$key] = [
'timelife' => time() + $timeLife,
'payload' => $value
];
}
public function GetGameDataStatic($key)
{
if( isset($this->gameDataStatic[$key]) )
{
return $this->gameDataStatic[$key]['payload'];
}
else
{
return 0;
}
}
public function HasGameData($key)
{
if( isset($this->gameData[$key]) )
{
return true;
}
else
{
return false;
}
}
public function GetHistory()
{
$history = \VanguardLTE\GameLog::whereRaw('game_id=? and user_id=? ORDER BY id DESC LIMIT 10', [
$this->slotDBId,
$this->playerId
])->get();
$this->lastEvent = 'NULL';
foreach( $history as $log )
{
$tmpLog = json_decode($log->str);
if( $tmpLog->responseEvent != 'gambleResult' )
{
$this->lastEvent = $log->str;
break;
}
}
if( isset($tmpLog) )
{
return $tmpLog;
}
else
{
return 'NULL';
}
}
public function UpdateJackpots($bet)
{
$bet = $bet * $this->CurrentDenom;
$count_balance = $this->count_balance;
$jsum = [];
$payJack = 0;
for( $i = 0; $i < count($this->jpgs); $i++ )
{
if( $count_balance == 0 || $this->jpgPercentZero )
{
$jsum[$i] = $this->jpgs[$i]->balance;
}
else if( $count_balance < $bet )
{
$jsum[$i] = $count_balance / 100 * $this->jpgs[$i]->percent + $this->jpgs[$i]->balance;
}
else
{
$jsum[$i] = $bet / 100 * $this->jpgs[$i]->percent + $this->jpgs[$i]->balance;
}
if( $this->jpgs[$i]->get_pay_sum() < $jsum[$i] && $this->jpgs[$i]->get_pay_sum() > 0 )
{
if( $this->jpgs[$i]->user_id && $this->jpgs[$i]->user_id != $this->user->id )
{
}
else
{
$payJack = $this->jpgs[$i]->get_pay_sum() / $this->CurrentDenom;
$jsum[$i] = $jsum[$i] - $this->jpgs[$i]->get_pay_sum();
$this->SetBalance($this->jpgs[$i]->get_pay_sum() / $this->CurrentDenom);
if( $this->jpgs[$i]->get_pay_sum() > 0 )
{
\VanguardLTE\StatGame::create([
'user_id' => $this->playerId,
'balance' => $this->Balance * $this->CurrentDenom,
'bet' => 0,
'win' => $this->jpgs[$i]->get_pay_sum(),
'game' => $this->game->name . ' JPG ' . $this->jpgs[$i]->id,
'in_game' => 0,
'in_jpg' => 0,
'in_profit' => 0,
'shop_id' => $this->shop_id,
'date_time' => \Carbon\Carbon::now()
]);
}
}
$i++;
}
$this->jpgs[$i]->balance = $jsum[$i];
$this->jpgs[$i]->save();
if( $this->jpgs[$i]->balance < $this->jpgs[$i]->get_min('start_balance') )
{
$summ = $this->jpgs[$i]->get_start_balance();
if( $summ > 0 )
{
$this->jpgs[$i]->add_jpg('add', $summ);
}
}
}
if( $payJack > 0 )
{
$payJack = sprintf('%01.2f', $payJack);
$this->Jackpots['jackPay'] = $payJack;
}
}
public function GetBank($slotState = '')
{
if( $this->isBonusStart || $slotState == 'bonus' || $slotState == 'freespin' || $slotState == 'respin' )
{
$slotState = 'bonus';
}
else
{
$slotState = '';
}
$game = $this->game;
$this->Bank = $game->get_gamebank($slotState);
return $this->Bank / $this->CurrentDenom;
}
public function GetPercent()
{
return $this->Percent;
}
public function GetCountBalanceUser()
{
return $this->user->count_balance;
}
public function InternalErrorSilent($errcode)
{
$strLog = '';
$strLog .= "\n";
$strLog .= ('{"responseEvent":"error","responseType":"' . $errcode . '","serverResponse":"InternalError","request":' . json_encode($_REQUEST) . ',"requestRaw":' . file_get_contents('php://input') . '}');
$strLog .= "\n";
$strLog .= ' ############################################### ';
$strLog .= "\n";
$slg = '';
if( file_exists(storage_path('logs/') . $this->slotId . 'Internal.log') )
{
$slg = file_get_contents(storage_path('logs/') . $this->slotId . 'Internal.log');
}
file_put_contents(storage_path('logs/') . $this->slotId . 'Internal.log', $slg . $strLog);
}
public function InternalError($errcode)
{
$strLog = '';
$strLog .= "\n";
$strLog .= ('{"responseEvent":"error","responseType":"' . $errcode . '","serverResponse":"InternalError","request":' . json_encode($_REQUEST) . ',"requestRaw":' . file_get_contents('php://input') . '}');
$strLog .= "\n";
$strLog .= ' ############################################### ';
$strLog .= "\n";
$slg = '';
if( file_exists(storage_path('logs/') . $this->slotId . 'Internal.log') )
{
$slg = file_get_contents(storage_path('logs/') . $this->slotId . 'Internal.log');
}
file_put_contents(storage_path('logs/') . $this->slotId . 'Internal.log', $slg . $strLog);
exit( '' );
}
public function SetBank($slotState = '', $sum, $slotEvent = '')
{
if( $this->isBonusStart || $slotState == 'bonus' || $slotState == 'freespin' || $slotState == 'respin' )
{
$slotState = 'bonus';
}
else
{
$slotState = '';
}
if( $this->GetBank($slotState) + $sum < 0 )
{
$this->InternalError('Bank_ ' . $sum . ' CurrentBank_ ' . $this->GetBank($slotState) . ' CurrentState_ ' . $slotState . ' Trigger_ ' . ($this->GetBank($slotState) + $sum));
}
$sum = $sum * $this->CurrentDenom;
$game = $this->game;
$bankBonusSum = 0;
if( $sum > 0 && $slotEvent == 'bet' )
{
$this->toGameBanks = 0;
$this->toSlotJackBanks = 0;
$this->toSysJackBanks = 0;
$this->betProfit = 0;
$prc = $this->GetPercent();
$prc_b = 10;
if( $prc <= $prc_b )
{
$prc_b = 0;
}
$count_balance = $this->count_balance;
$gameBet = $sum / $this->GetPercent() * 100;
if( $count_balance < $gameBet && $count_balance > 0 )
{
$firstBid = $count_balance;
$secondBid = $gameBet - $firstBid;
if( isset($this->betRemains0) )
{
$secondBid = $this->betRemains0;
}
$bankSum = $firstBid / 100 * $this->GetPercent();
$sum = $bankSum + $secondBid;
$bankBonusSum = $firstBid / 100 * $prc_b;
}
else if( $count_balance > 0 )
{
$bankBonusSum = $gameBet / 100 * $prc_b;
}
for( $i = 0; $i < count($this->jpgs); $i++ )
{
if( !$this->jpgPercentZero )
{
if( $count_balance < $gameBet && $count_balance > 0 )
{
$this->toSlotJackBanks += ($count_balance / 100 * $this->jpgs[$i]->percent);
}
else if( $count_balance > 0 )
{
$this->toSlotJackBanks += ($gameBet / 100 * $this->jpgs[$i]->percent);
}
}
}
$this->toGameBanks = $sum;
$this->betProfit = $gameBet - $this->toGameBanks - $this->toSlotJackBanks - $this->toSysJackBanks;
}
if( $sum > 0 )
{
$this->toGameBanks = $sum;
}
if( $bankBonusSum > 0 )
{
$sum -= $bankBonusSum;
$game->set_gamebank($bankBonusSum, 'inc', 'bonus');
}
if( $sum == 0 && $slotEvent == 'bet' && isset($this->betRemains) )
{
$sum = $this->betRemains;
}
$game->set_gamebank($sum, 'inc', $slotState);
$game->save();
return $game;
}
public function SetBalance($sum, $slotEvent = '')
{
if( $this->GetBalance() + $sum < 0 )
{
$this->InternalError('Balance_ ' . $sum);
}
$sum = $sum * $this->CurrentDenom;
if( $sum < 0 && $slotEvent == 'bet' )
{
$user = $this->user;
if( $user->count_balance == 0 )
{
$remains = [];
$this->betRemains = 0;
$sm = abs($sum);
if( $user->address < $sm && $user->address > 0 )
{
$remains[] = $sm - $user->address;
}
for( $i = 0; $i < count($remains); $i++ )
{
if( $this->betRemains < $remains[$i] )
{
$this->betRemains = $remains[$i];
}
}
}
if( $user->count_balance > 0 && $user->count_balance < abs($sum) )
{
$remains0 = [];
$sm = abs($sum);
$tmpSum = $sm - $user->count_balance;
$this->betRemains0 = $tmpSum;
if( $user->address > 0 )
{
$this->betRemains0 = 0;
if( $user->address < $tmpSum && $user->address > 0 )
{
$remains0[] = $tmpSum - $user->address;
}
for( $i = 0; $i < count($remains0); $i++ )
{
if( $this->betRemains0 < $remains0[$i] )
{
$this->betRemains0 = $remains0[$i];
}
}
}
}
$sum0 = abs($sum);
if( $user->count_balance == 0 )
{
$sm = abs($sum);
if( $user->address < $sm && $user->address > 0 )
{
$user->address = 0;
}
else if( $user->address > 0 )
{
$user->address -= $sm;
}
}
else if( $user->count_balance > 0 && $user->count_balance < $sum0 )
{
$sm = $sum0 - $user->count_balance;
if( $user->address < $sm && $user->address > 0 )
{
$user->address = 0;
}
else if( $user->address > 0 )
{
$user->address -= $sm;
}
}
$this->user->count_balance = $this->user->updateCountBalance($sum, $this->count_balance);
$this->user->count_balance = $this->FormatFloat($this->user->count_balance);
}
$this->user->increment('balance', $sum);
$this->user->balance = $this->FormatFloat($this->user->balance);
$this->user->save();
return $this->user;
}
public function GetBalance()
{
$user = $this->user;
$this->Balance = $user->balance / $this->CurrentDenom;
return $this->Balance;
}
public function SaveLogReport($spinSymbols, $bet, $lines, $win, $slotState)
{
$reportName = $this->slotId . ' ' . $slotState;
if( $slotState == 'freespin' )
{
$reportName = $this->slotId . ' FG';
}
else if( $slotState == 'bet' )
{
$reportName = $this->slotId . '';
}
else if( $slotState == 'slotGamble' )
{
$reportName = $this->slotId . ' DG';
}
$game = $this->game;
if( $slotState == 'bet' )
{
$this->user->update_level('bet', $bet * $this->CurrentDenom);
}
if( $slotState != 'freespin' )
{
$game->increment('stat_in', $bet * $this->CurrentDenom);
}
$game->increment('stat_out', $win * $this->CurrentDenom);
$game->tournament_stat($slotState, $this->user->id, $bet * $this->CurrentDenom, $win * $this->CurrentDenom);
$this->user->update(['last_bid' => \Carbon\Carbon::now()]);
if( !isset($this->betProfit) )
{
$this->betProfit = 0;
$this->toGameBanks = 0;
$this->toSlotJackBanks = 0;
$this->toSysJackBanks = 0;
}
if( !isset($this->toGameBanks) )
{
$this->toGameBanks = 0;
}
$this->game->increment('bids');
$this->game->refresh();
$gamebank = \VanguardLTE\GameBank::where(['shop_id' => $game->shop_id])->first();
if( $gamebank )
{
list($slotsBank, $bonusBank, $fishBank, $tableBank, $littleBank) = \VanguardLTE\Lib\Banker::get_all_banks($game->shop_id);
}
else
{
$slotsBank = $game->get_gamebank('', 'slots');
$bonusBank = $game->get_gamebank('bonus', 'bonus');
$fishBank = $game->get_gamebank('', 'fish');
$tableBank = $game->get_gamebank('', 'table_bank');
$littleBank = $game->get_gamebank('', 'little');
}
$totalBank = $slotsBank + $bonusBank + $fishBank + $tableBank + $littleBank;
\VanguardLTE\GameLog::create([
'game_id' => $this->slotDBId,
'user_id' => $this->playerId,
'ip' => $_SERVER['REMOTE_ADDR'],
'str' => $spinSymbols,
'shop_id' => $this->shop_id
]);
\VanguardLTE\StatGame::create([
'user_id' => $this->playerId,
'balance' => $this->Balance * $this->CurrentDenom,
'bet' => $bet * $this->CurrentDenom,
'win' => $win * $this->CurrentDenom,
'game' => $reportName,
'in_game' => $this->toGameBanks,
'in_jpg' => $this->toSlotJackBanks,
'in_profit' => $this->betProfit,
'denomination' => $this->CurrentDenom,
'shop_id' => $this->shop_id,
'slots_bank' => (double)$slotsBank,
'bonus_bank' => (double)$bonusBank,
'fish_bank' => (double)$fishBank,
'table_bank' => (double)$tableBank,
'little_bank' => (double)$littleBank,
'total_bank' => (double)$totalBank,
'date_time' => \Carbon\Carbon::now()
]);
}
public function GetSpinSettings($garantType = 'bet', $bet, $lines)
{
$curField = 10;
switch( $lines )
{
case 10:
$curField = 10;
break;
case 9:
case 8:
$curField = 9;
break;
case 7:
case 6:
$curField = 7;
break;
case 5:
case 4:
$curField = 5;
break;
case 3:
case 2:
$curField = 3;
break;
case 1:
$curField = 1;
break;
default:
$curField = 10;
break;
}
if( $garantType != 'bet' )
{
$pref = '_bonus';
}
else
{
$pref = '';
}
$this->AllBet = $bet * $lines;
$linesPercentConfigSpin = $this->game->get_lines_percent_config('spin');
$linesPercentConfigBonus = $this->game->get_lines_percent_config('bonus');
$currentPercent = $this->shop->percent;
$currentSpinWinChance = 0;
$currentBonusWinChance = 0;
$percentLevel = '';
foreach( $linesPercentConfigSpin['line' . $curField . $pref] as $k => $v )
{
$l = explode('_', $k);
$l0 = $l[0];
$l1 = $l[1];
if( $l0 <= $currentPercent && $currentPercent <= $l1 )
{
$percentLevel = $k;
break;
}
}
$currentSpinWinChance = $linesPercentConfigSpin['line' . $curField . $pref][$percentLevel];
$currentBonusWinChance = $linesPercentConfigBonus['line' . $curField . $pref][$percentLevel];
$RtpControlCount = 200;
if( !$this->HasGameDataStatic('SpinWinLimit') )
{
$this->SetGameDataStatic('SpinWinLimit', 0);
}
if( !$this->HasGameDataStatic('RtpControlCount') )
{
$this->SetGameDataStatic('RtpControlCount', $RtpControlCount);
}
if( $this->game->stat_in > 0 )
{
$rtpRange = $this->game->stat_out / $this->game->stat_in * 100;
}
else
{
$rtpRange = 0;
}
if( $this->GetGameDataStatic('RtpControlCount') == 0 )
{
if( $currentPercent + rand(1, 2) < $rtpRange && $this->GetGameDataStatic('SpinWinLimit') <= 0 )
{
$this->SetGameDataStatic('SpinWinLimit', rand(25, 50));
}
if( $pref == '' && $this->GetGameDataStatic('SpinWinLimit') > 0 )
{
$currentBonusWinChance = 5000;
$currentSpinWinChance = 20;
$this->MaxWin = rand(1, 5);
if( $rtpRange < ($currentPercent - 1) )
{
$this->SetGameDataStatic('SpinWinLimit', 0);
$this->SetGameDataStatic('RtpControlCount', $this->GetGameDataStatic('RtpControlCount') - 1);
}
}
}
else if( $this->GetGameDataStatic('RtpControlCount') < 0 )
{
if( $currentPercent + rand(1, 2) < $rtpRange && $this->GetGameDataStatic('SpinWinLimit') <= 0 )
{
$this->SetGameDataStatic('SpinWinLimit', rand(25, 50));
}
$this->SetGameDataStatic('RtpControlCount', $this->GetGameDataStatic('RtpControlCount') - 1);
if( $pref == '' && $this->GetGameDataStatic('SpinWinLimit') > 0 )
{
$currentBonusWinChance = 5000;
$currentSpinWinChance = 20;
$this->MaxWin = rand(1, 5);
if( $rtpRange < ($currentPercent - 1) )
{
$this->SetGameDataStatic('SpinWinLimit', 0);
}
}
if( $this->GetGameDataStatic('RtpControlCount') < (-1 * $RtpControlCount) && $currentPercent - 1 <= $rtpRange && $rtpRange <= ($currentPercent + 2) )
{
$this->SetGameDataStatic('RtpControlCount', $RtpControlCount);
}
}
else
{
$this->SetGameDataStatic('RtpControlCount', $this->GetGameDataStatic('RtpControlCount') - 1);
}
$bonusWin = rand(1, $currentBonusWinChance);
$spinWin = rand(1, $currentSpinWinChance);
$return = [
'none',
0
];
if( $bonusWin == 1 && $this->slotBonus )
{
$this->isBonusStart = true;
$garantType = 'bonus';
$winLimit = $this->GetBank($garantType);
$return = [
'bonus',
$winLimit
];
if( $this->game->stat_in < ($this->CheckBonusWin() * $bet + $this->game->stat_out) || $winLimit < ($this->CheckBonusWin() * $bet) )
{
$return = [
'none',
0
];
}
}
else if( $spinWin == 1 )
{
$winLimit = $this->GetBank($garantType);
$return = [
'win',
$winLimit
];
}
if( $garantType == 'bet' && $this->GetBalance() <= (2 / $this->CurrentDenom) )
{
$randomPush = rand(1, 10);
if( $randomPush == 1 )
{
$winLimit = $this->GetBank('');
$return = [
'win',
$winLimit
];
}
}
return $return;
}
public function GetRandomScatterPos($rp)
{
$rpResult = [];
for( $i = 0; $i < count($rp); $i++ )
{
if( $rp[$i] == '7' )
{
if( isset($rp[$i + 1]) && isset($rp[$i - 1]) )
{
array_push($rpResult, $i);
}
if( isset($rp[$i - 1]) && isset($rp[$i - 2]) )
{
array_push($rpResult, $i - 1);
}
if( isset($rp[$i + 1]) && isset($rp[$i + 2]) )
{
array_push($rpResult, $i + 1);
}
}
}
shuffle($rpResult);
if( !isset($rpResult[0]) )
{
$rpResult[0] = rand(2, count($rp) - 3);
}
return $rpResult[0];
}
public function GetGambleSettings()
{
$spinWin = rand(1, $this->WinGamble);
return $spinWin;
}
public function GetReelStrips($winType, $slotEvent)
{
$game = $this->game;
if( $slotEvent == 'freespin' )
{
$reel = new GameReel();
$fArr = $reel->reelsStripBonus;
foreach( [
'reelStrip1',
'reelStrip2',
'reelStrip3',
'reelStrip4',
'reelStrip5',
'reelStrip6'
] as $reelStrip )
{
$curReel = array_shift($fArr);
if( count($curReel) )
{
$this->$reelStrip = $curReel;
}
}
}
if( $winType != 'bonus' )
{
$prs = [];
foreach( [
'reelStrip1',
'reelStrip2',
'reelStrip3',
'reelStrip4',
'reelStrip5',
'reelStrip6'
] as $index => $reelStrip )
{
if( is_array($this->$reelStrip) && count($this->$reelStrip) > 0 )
{
$prs[$index + 1] = mt_rand(0, count($this->$reelStrip) - 3);
}
}
}
else
{
$reelsId = [];
foreach( [
'reelStrip1',
'reelStrip2',
'reelStrip3',
'reelStrip4',
'reelStrip5',
'reelStrip6'
] as $index => $reelStrip )
{
if( is_array($this->$reelStrip) && count($this->$reelStrip) > 0 )
{
$prs[$index + 1] = $this->GetRandomScatterPos($this->$reelStrip);
$reelsId[] = $index + 1;
}
}
$scattersCnt = rand(3, count($reelsId));
shuffle($reelsId);
for( $i = 0; $i < count($reelsId); $i++ )
{
if( $i < $scattersCnt )
{
$prs[$reelsId[$i]] = $this->GetRandomScatterPos($this->{'reelStrip' . $reelsId[$i]});
}
else
{
$prs[$reelsId[$i]] = rand(0, count($this->{'reelStrip' . $reelsId[$i]}) - 3);
}
}
}
$reel = [
'rp' => []
];
foreach( $prs as $index => $value )
{
$key = $this->{'reelStrip' . $index};
$cnt = count($key);
$key[-1] = $key[$cnt - 1];
$key[$cnt] = $key[0];
$reel['reel' . $index][0] = $key[$value - 1];
$reel['reel' . $index][1] = $key[$value];
$reel['reel' . $index][2] = $key[$value + 1];
$reel['reel' . $index][3] = '';
$reel['rp'][] = $value;
}
return $reel;
}
}
}
| 412 | 0.612057 | 1 | 0.612057 | game-dev | MEDIA | 0.399125 | game-dev | 0.756694 | 1 | 0.756694 |
GlowstoneMC/Glowstone | 5,127 | src/main/java/net/glowstone/block/blocktype/BlockRedstoneRepeater.java | package net.glowstone.block.blocktype;
import net.glowstone.block.GlowBlock;
import net.glowstone.block.GlowBlockState;
import net.glowstone.block.ItemTable;
import net.glowstone.entity.GlowPlayer;
import net.glowstone.util.MaterialUtil;
import org.bukkit.Material;
import org.bukkit.block.BlockFace;
import org.bukkit.inventory.ItemStack;
import org.bukkit.material.Diode;
import org.bukkit.material.MaterialData;
import org.bukkit.util.Vector;
public class BlockRedstoneRepeater extends BlockNeedsAttached {
public BlockRedstoneRepeater() {
setDrops(new ItemStack(Material.REPEATER));
}
@Override
public boolean blockInteract(GlowPlayer player, GlowBlock block, BlockFace face,
Vector clickedLoc) {
Diode diode = (Diode) block.getState().getData();
diode.setDelay(diode.getDelay() == 4 ? 1 : diode.getDelay() + 1);
block.setData(diode.getData());
return true;
}
@Override
public void afterPlace(GlowPlayer player, GlowBlock block, ItemStack holding,
GlowBlockState oldState) {
updatePhysics(block);
}
@Override
public void onNearBlockChanged(GlowBlock block, BlockFace face, GlowBlock changedBlock,
Material oldType, byte oldData, Material newType, byte newData) {
updatePhysics(block);
}
@Override
public void placeBlock(GlowPlayer player, GlowBlockState state, BlockFace face,
ItemStack holding, Vector clickedLoc) {
super.placeBlock(player, state, face, holding, clickedLoc);
MaterialData data = state.getData();
if (data instanceof Diode) {
((Diode) data).setFacingDirection(player.getCardinalFacing());
state.setData(data);
} else {
warnMaterialData(Diode.class, data);
}
state.getWorld().requestPulse(state.getBlock());
}
@Override
public void updatePhysicsAfterEvent(GlowBlock me) {
super.updatePhysicsAfterEvent(me);
Diode diode = (Diode) me.getState().getData();
GlowBlock target = me.getRelative(diode.getFacing().getOppositeFace());
// TODO: 1.13 redstone ON data
boolean powered = target.getType() == Material.REDSTONE_TORCH || target.isBlockPowered()
|| target.getType() == Material.REDSTONE_WIRE
&& target.getData() > 0 && BlockRedstone.calculateConnections(target)
.contains(diode.getFacing())
|| target.getType() == Material.REPEATER
&& ((Diode) target.getState().getData()).getFacing() == diode.getFacing();
if (powered != (me.getType() == Material.REPEATER)) {
me.getWorld().requestPulse(me);
}
}
private void extraUpdate(GlowBlock block) {
Diode diode = (Diode) block.getState().getData();
ItemTable itemTable = ItemTable.instance();
GlowBlock target = block.getRelative(diode.getFacing());
if (target.getType().isSolid()) {
for (BlockFace face2 : ADJACENT) {
GlowBlock target2 = target.getRelative(face2);
BlockType notifyType = itemTable.getBlock(target2.getType());
if (notifyType != null) {
if (target2.getFace(block) == null) {
notifyType
.onNearBlockChanged(target2, BlockFace.SELF, block, block.getType(),
block.getData(), block.getType(), block.getData());
}
notifyType.onRedstoneUpdate(target2);
}
}
}
}
@Override
public void receivePulse(GlowBlock block) {
Diode diode = (Diode) block.getState().getData();
GlowBlock target = block.getRelative(diode.getFacing().getOppositeFace());
// TODO: redstone ON data
boolean powered = target.getType() == Material.REDSTONE_TORCH || target.isBlockPowered()
|| target.getType() == Material.REDSTONE_WIRE
&& target.getData() > 0 && BlockRedstone.calculateConnections(target)
.contains(diode.getFacing())
|| target.getType() == Material.REPEATER
&& ((Diode) target.getState().getData()).getFacing() == diode.getFacing();
if (!powered && block.getType() == Material.REPEATER) {
block.setTypeIdAndData(MaterialUtil.getId(Material.REPEATER), block.getData(),
true); // TODO: repeater off data
extraUpdate(block);
} else if (powered && block.getType() == Material.REPEATER) { // TODO: repeater off data
block.setTypeIdAndData(MaterialUtil.getId(Material.REPEATER), block.getData(),
true); // TODO: repeater on data
extraUpdate(block);
}
}
@Override
public boolean isPulseOnce(GlowBlock block) {
return true;
}
@Override
public int getPulseTickSpeed(GlowBlock block) {
Diode diode = (Diode) block.getState().getData();
return diode.getDelay() << 1;
}
}
| 412 | 0.806598 | 1 | 0.806598 | game-dev | MEDIA | 0.920507 | game-dev | 0.908986 | 1 | 0.908986 |
SwitchGDX/switch-gdx | 25,612 | switch-gdx/res/switchgdx/bullet/bullet/BulletDynamics/Featherstone/btMultiBody.h | /*
* PURPOSE:
* Class representing an articulated rigid body. Stores the body's
* current state, allows forces and torques to be set, handles
* timestepping and implements Featherstone's algorithm.
*
* COPYRIGHT:
* Copyright (C) Stephen Thompson, <stephen@solarflare.org.uk>, 2011-2013
* Portions written By Erwin Coumans: connection to LCP solver, various multibody constraints, replacing Eigen math library by Bullet LinearMath and a dedicated 6x6 matrix inverse (solveImatrix)
* Portions written By Jakub Stepien: support for multi-DOF constraints, introduction of spatial algebra and several other improvements
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef BT_MULTIBODY_H
#define BT_MULTIBODY_H
#include "LinearMath/btScalar.h"
#include "LinearMath/btVector3.h"
#include "LinearMath/btQuaternion.h"
#include "LinearMath/btMatrix3x3.h"
#include "LinearMath/btAlignedObjectArray.h"
///serialization data, don't change them if you are not familiar with the details of the serialization mechanisms
#ifdef BT_USE_DOUBLE_PRECISION
#define btMultiBodyData btMultiBodyDoubleData
#define btMultiBodyDataName "btMultiBodyDoubleData"
#define btMultiBodyLinkData btMultiBodyLinkDoubleData
#define btMultiBodyLinkDataName "btMultiBodyLinkDoubleData"
#else
#define btMultiBodyData btMultiBodyFloatData
#define btMultiBodyDataName "btMultiBodyFloatData"
#define btMultiBodyLinkData btMultiBodyLinkFloatData
#define btMultiBodyLinkDataName "btMultiBodyLinkFloatData"
#endif //BT_USE_DOUBLE_PRECISION
#include "btMultiBodyLink.h"
class btMultiBodyLinkCollider;
ATTRIBUTE_ALIGNED16(class) btMultiBody
{
public:
BT_DECLARE_ALIGNED_ALLOCATOR();
//
// initialization
//
btMultiBody(int n_links, // NOT including the base
btScalar mass, // mass of base
const btVector3 &inertia, // inertia of base, in base frame; assumed diagonal
bool fixedBase, // whether the base is fixed (true) or can move (false)
bool canSleep, bool deprecatedMultiDof=true);
virtual ~btMultiBody();
//note: fixed link collision with parent is always disabled
void setupFixed(int linkIndex,
btScalar mass,
const btVector3 &inertia,
int parent,
const btQuaternion &rotParentToThis,
const btVector3 &parentComToThisPivotOffset,
const btVector3 &thisPivotToThisComOffset, bool deprecatedDisableParentCollision=true);
void setupPrismatic(int i,
btScalar mass,
const btVector3 &inertia,
int parent,
const btQuaternion &rotParentToThis,
const btVector3 &jointAxis,
const btVector3 &parentComToThisPivotOffset,
const btVector3 &thisPivotToThisComOffset,
bool disableParentCollision);
void setupRevolute(int linkIndex, // 0 to num_links-1
btScalar mass,
const btVector3 &inertia,
int parentIndex,
const btQuaternion &rotParentToThis, // rotate points in parent frame to this frame, when q = 0
const btVector3 &jointAxis, // in my frame
const btVector3 &parentComToThisPivotOffset, // vector from parent COM to joint axis, in PARENT frame
const btVector3 &thisPivotToThisComOffset, // vector from joint axis to my COM, in MY frame
bool disableParentCollision=false);
void setupSpherical(int linkIndex, // 0 to num_links-1
btScalar mass,
const btVector3 &inertia,
int parent,
const btQuaternion &rotParentToThis, // rotate points in parent frame to this frame, when q = 0
const btVector3 &parentComToThisPivotOffset, // vector from parent COM to joint axis, in PARENT frame
const btVector3 &thisPivotToThisComOffset, // vector from joint axis to my COM, in MY frame
bool disableParentCollision=false);
void setupPlanar(int i, // 0 to num_links-1
btScalar mass,
const btVector3 &inertia,
int parent,
const btQuaternion &rotParentToThis, // rotate points in parent frame to this frame, when q = 0
const btVector3 &rotationAxis,
const btVector3 &parentComToThisComOffset, // vector from parent COM to this COM, in PARENT frame
bool disableParentCollision=false);
const btMultibodyLink& getLink(int index) const
{
return m_links[index];
}
btMultibodyLink& getLink(int index)
{
return m_links[index];
}
void setBaseCollider(btMultiBodyLinkCollider* collider)//collider can be NULL to disable collision for the base
{
m_baseCollider = collider;
}
const btMultiBodyLinkCollider* getBaseCollider() const
{
return m_baseCollider;
}
btMultiBodyLinkCollider* getBaseCollider()
{
return m_baseCollider;
}
btMultiBodyLinkCollider* getLinkCollider(int index)
{
if (index >= 0 && index < getNumLinks())
{
return getLink(index).m_collider;
}
return 0;
}
//
// get parent
// input: link num from 0 to num_links-1
// output: link num from 0 to num_links-1, OR -1 to mean the base.
//
int getParent(int link_num) const;
//
// get number of m_links, masses, moments of inertia
//
int getNumLinks() const { return m_links.size(); }
int getNumDofs() const { return m_dofCount; }
int getNumPosVars() const { return m_posVarCnt; }
btScalar getBaseMass() const { return m_baseMass; }
const btVector3 & getBaseInertia() const { return m_baseInertia; }
btScalar getLinkMass(int i) const;
const btVector3 & getLinkInertia(int i) const;
//
// change mass (incomplete: can only change base mass and inertia at present)
//
void setBaseMass(btScalar mass) { m_baseMass = mass; }
void setBaseInertia(const btVector3 &inertia) { m_baseInertia = inertia; }
//
// get/set pos/vel/rot/omega for the base link
//
const btVector3 & getBasePos() const { return m_basePos; } // in world frame
const btVector3 getBaseVel() const
{
return btVector3(m_realBuf[3],m_realBuf[4],m_realBuf[5]);
} // in world frame
const btQuaternion & getWorldToBaseRot() const
{
return m_baseQuat;
} // rotates world vectors into base frame
btVector3 getBaseOmega() const { return btVector3(m_realBuf[0],m_realBuf[1],m_realBuf[2]); } // in world frame
void setBasePos(const btVector3 &pos)
{
m_basePos = pos;
}
void setBaseWorldTransform(const btTransform& tr)
{
setBasePos(tr.getOrigin());
setWorldToBaseRot(tr.getRotation().inverse());
}
btTransform getBaseWorldTransform() const
{
btTransform tr;
tr.setOrigin(getBasePos());
tr.setRotation(getWorldToBaseRot().inverse());
return tr;
}
void setBaseVel(const btVector3 &vel)
{
m_realBuf[3]=vel[0]; m_realBuf[4]=vel[1]; m_realBuf[5]=vel[2];
}
void setWorldToBaseRot(const btQuaternion &rot)
{
m_baseQuat = rot; //m_baseQuat asumed to ba alias!?
}
void setBaseOmega(const btVector3 &omega)
{
m_realBuf[0]=omega[0];
m_realBuf[1]=omega[1];
m_realBuf[2]=omega[2];
}
//
// get/set pos/vel for child m_links (i = 0 to num_links-1)
//
btScalar getJointPos(int i) const;
btScalar getJointVel(int i) const;
btScalar * getJointVelMultiDof(int i);
btScalar * getJointPosMultiDof(int i);
const btScalar * getJointVelMultiDof(int i) const ;
const btScalar * getJointPosMultiDof(int i) const ;
void setJointPos(int i, btScalar q);
void setJointVel(int i, btScalar qdot);
void setJointPosMultiDof(int i, btScalar *q);
void setJointVelMultiDof(int i, btScalar *qdot);
//
// direct access to velocities as a vector of 6 + num_links elements.
// (omega first, then v, then joint velocities.)
//
const btScalar * getVelocityVector() const
{
return &m_realBuf[0];
}
/* btScalar * getVelocityVector()
{
return &real_buf[0];
}
*/
//
// get the frames of reference (positions and orientations) of the child m_links
// (i = 0 to num_links-1)
//
const btVector3 & getRVector(int i) const; // vector from COM(parent(i)) to COM(i), in frame i's coords
const btQuaternion & getParentToLocalRot(int i) const; // rotates vectors in frame parent(i) to vectors in frame i.
//
// transform vectors in local frame of link i to world frame (or vice versa)
//
btVector3 localPosToWorld(int i, const btVector3 &vec) const;
btVector3 localDirToWorld(int i, const btVector3 &vec) const;
btVector3 worldPosToLocal(int i, const btVector3 &vec) const;
btVector3 worldDirToLocal(int i, const btVector3 &vec) const;
//
// transform a frame in local coordinate to a frame in world coordinate
//
btMatrix3x3 localFrameToWorld(int i, const btMatrix3x3 &mat) const;
//
// calculate kinetic energy and angular momentum
// useful for debugging.
//
btScalar getKineticEnergy() const;
btVector3 getAngularMomentum() const;
//
// set external forces and torques. Note all external forces/torques are given in the WORLD frame.
//
void clearForcesAndTorques();
void clearConstraintForces();
void clearVelocities();
void addBaseForce(const btVector3 &f)
{
m_baseForce += f;
}
void addBaseTorque(const btVector3 &t) { m_baseTorque += t; }
void addLinkForce(int i, const btVector3 &f);
void addLinkTorque(int i, const btVector3 &t);
void addBaseConstraintForce(const btVector3 &f)
{
m_baseConstraintForce += f;
}
void addBaseConstraintTorque(const btVector3 &t) { m_baseConstraintTorque += t; }
void addLinkConstraintForce(int i, const btVector3 &f);
void addLinkConstraintTorque(int i, const btVector3 &t);
void addJointTorque(int i, btScalar Q);
void addJointTorqueMultiDof(int i, int dof, btScalar Q);
void addJointTorqueMultiDof(int i, const btScalar *Q);
const btVector3 & getBaseForce() const { return m_baseForce; }
const btVector3 & getBaseTorque() const { return m_baseTorque; }
const btVector3 & getLinkForce(int i) const;
const btVector3 & getLinkTorque(int i) const;
btScalar getJointTorque(int i) const;
btScalar * getJointTorqueMultiDof(int i);
//
// dynamics routines.
//
// timestep the velocities (given the external forces/torques set using addBaseForce etc).
// also sets up caches for calcAccelerationDeltas.
//
// Note: the caller must provide three vectors which are used as
// temporary scratch space. The idea here is to reduce dynamic
// memory allocation: the same scratch vectors can be re-used
// again and again for different Multibodies, instead of each
// btMultiBody allocating (and then deallocating) their own
// individual scratch buffers. This gives a considerable speed
// improvement, at least on Windows (where dynamic memory
// allocation appears to be fairly slow).
//
void computeAccelerationsArticulatedBodyAlgorithmMultiDof(btScalar dt,
btAlignedObjectArray<btScalar> &scratch_r,
btAlignedObjectArray<btVector3> &scratch_v,
btAlignedObjectArray<btMatrix3x3> &scratch_m,
bool isConstraintPass=false
);
///stepVelocitiesMultiDof is deprecated, use computeAccelerationsArticulatedBodyAlgorithmMultiDof instead
void stepVelocitiesMultiDof(btScalar dt,
btAlignedObjectArray<btScalar> &scratch_r,
btAlignedObjectArray<btVector3> &scratch_v,
btAlignedObjectArray<btMatrix3x3> &scratch_m,
bool isConstraintPass=false)
{
computeAccelerationsArticulatedBodyAlgorithmMultiDof(dt,scratch_r,scratch_v,scratch_m,isConstraintPass);
}
// calcAccelerationDeltasMultiDof
// input: force vector (in same format as jacobian, i.e.:
// 3 torque values, 3 force values, num_links joint torque values)
// output: 3 omegadot values, 3 vdot values, num_links q_double_dot values
// (existing contents of output array are replaced)
// calcAccelerationDeltasMultiDof must have been called first.
void calcAccelerationDeltasMultiDof(const btScalar *force, btScalar *output,
btAlignedObjectArray<btScalar> &scratch_r,
btAlignedObjectArray<btVector3> &scratch_v) const;
void applyDeltaVeeMultiDof2(const btScalar * delta_vee, btScalar multiplier)
{
for (int dof = 0; dof < 6 + getNumDofs(); ++dof)
{
m_deltaV[dof] += delta_vee[dof] * multiplier;
}
}
void processDeltaVeeMultiDof2()
{
applyDeltaVeeMultiDof(&m_deltaV[0],1);
for (int dof = 0; dof < 6 + getNumDofs(); ++dof)
{
m_deltaV[dof] = 0.f;
}
}
void applyDeltaVeeMultiDof(const btScalar * delta_vee, btScalar multiplier)
{
//for (int dof = 0; dof < 6 + getNumDofs(); ++dof)
// printf("%.4f ", delta_vee[dof]*multiplier);
//printf("\n");
//btScalar sum = 0;
//for (int dof = 0; dof < 6 + getNumDofs(); ++dof)
//{
// sum += delta_vee[dof]*multiplier*delta_vee[dof]*multiplier;
//}
//btScalar l = btSqrt(sum);
//if (l>m_maxAppliedImpulse)
//{
// multiplier *= m_maxAppliedImpulse/l;
//}
for (int dof = 0; dof < 6 + getNumDofs(); ++dof)
{
m_realBuf[dof] += delta_vee[dof] * multiplier;
btClamp(m_realBuf[dof],-m_maxCoordinateVelocity,m_maxCoordinateVelocity);
}
}
// timestep the positions (given current velocities).
void stepPositionsMultiDof(btScalar dt, btScalar *pq = 0, btScalar *pqd = 0);
//
// contacts
//
// This routine fills out a contact constraint jacobian for this body.
// the 'normal' supplied must be -n for body1 or +n for body2 of the contact.
// 'normal' & 'contact_point' are both given in world coordinates.
void fillContactJacobianMultiDof(int link,
const btVector3 &contact_point,
const btVector3 &normal,
btScalar *jac,
btAlignedObjectArray<btScalar> &scratch_r,
btAlignedObjectArray<btVector3> &scratch_v,
btAlignedObjectArray<btMatrix3x3> &scratch_m) const { fillConstraintJacobianMultiDof(link, contact_point, btVector3(0, 0, 0), normal, jac, scratch_r, scratch_v, scratch_m); }
//a more general version of fillContactJacobianMultiDof which does not assume..
//.. that the constraint in question is contact or, to be more precise, constrains linear velocity only
void fillConstraintJacobianMultiDof(int link,
const btVector3 &contact_point,
const btVector3 &normal_ang,
const btVector3 &normal_lin,
btScalar *jac,
btAlignedObjectArray<btScalar> &scratch_r,
btAlignedObjectArray<btVector3> &scratch_v,
btAlignedObjectArray<btMatrix3x3> &scratch_m) const;
//
// sleeping
//
void setCanSleep(bool canSleep)
{
m_canSleep = canSleep;
}
bool getCanSleep()const
{
return m_canSleep;
}
bool isAwake() const { return m_awake; }
void wakeUp();
void goToSleep();
void checkMotionAndSleepIfRequired(btScalar timestep);
bool hasFixedBase() const
{
return m_fixedBase;
}
int getCompanionId() const
{
return m_companionId;
}
void setCompanionId(int id)
{
//printf("for %p setCompanionId(%d)\n",this, id);
m_companionId = id;
}
void setNumLinks(int numLinks)//careful: when changing the number of m_links, make sure to re-initialize or update existing m_links
{
m_links.resize(numLinks);
}
btScalar getLinearDamping() const
{
return m_linearDamping;
}
void setLinearDamping( btScalar damp)
{
m_linearDamping = damp;
}
btScalar getAngularDamping() const
{
return m_angularDamping;
}
void setAngularDamping( btScalar damp)
{
m_angularDamping = damp;
}
bool getUseGyroTerm() const
{
return m_useGyroTerm;
}
void setUseGyroTerm(bool useGyro)
{
m_useGyroTerm = useGyro;
}
btScalar getMaxCoordinateVelocity() const
{
return m_maxCoordinateVelocity ;
}
void setMaxCoordinateVelocity(btScalar maxVel)
{
m_maxCoordinateVelocity = maxVel;
}
btScalar getMaxAppliedImpulse() const
{
return m_maxAppliedImpulse;
}
void setMaxAppliedImpulse(btScalar maxImp)
{
m_maxAppliedImpulse = maxImp;
}
void setHasSelfCollision(bool hasSelfCollision)
{
m_hasSelfCollision = hasSelfCollision;
}
bool hasSelfCollision() const
{
return m_hasSelfCollision;
}
void finalizeMultiDof();
void useRK4Integration(bool use) { m_useRK4 = use; }
bool isUsingRK4Integration() const { return m_useRK4; }
void useGlobalVelocities(bool use) { m_useGlobalVelocities = use; }
bool isUsingGlobalVelocities() const { return m_useGlobalVelocities; }
bool isPosUpdated() const
{
return __posUpdated;
}
void setPosUpdated(bool updated)
{
__posUpdated = updated;
}
//internalNeedsJointFeedback is for internal use only
bool internalNeedsJointFeedback() const
{
return m_internalNeedsJointFeedback;
}
void forwardKinematics(btAlignedObjectArray<btQuaternion>& scratch_q,btAlignedObjectArray<btVector3>& scratch_m);
void compTreeLinkVelocities(btVector3 *omega, btVector3 *vel) const;
void updateCollisionObjectWorldTransforms(btAlignedObjectArray<btQuaternion>& scratch_q,btAlignedObjectArray<btVector3>& scratch_m);
virtual int calculateSerializeBufferSize() const;
///fills the dataBuffer and returns the struct name (and 0 on failure)
virtual const char* serialize(void* dataBuffer, class btSerializer* serializer) const;
const char* getBaseName() const
{
return m_baseName;
}
///memory of setBaseName needs to be manager by user
void setBaseName(const char* name)
{
m_baseName = name;
}
///users can point to their objects, userPointer is not used by Bullet
void* getUserPointer() const
{
return m_userObjectPointer;
}
int getUserIndex() const
{
return m_userIndex;
}
int getUserIndex2() const
{
return m_userIndex2;
}
///users can point to their objects, userPointer is not used by Bullet
void setUserPointer(void* userPointer)
{
m_userObjectPointer = userPointer;
}
///users can point to their objects, userPointer is not used by Bullet
void setUserIndex(int index)
{
m_userIndex = index;
}
void setUserIndex2(int index)
{
m_userIndex2 = index;
}
private:
btMultiBody(const btMultiBody &); // not implemented
void operator=(const btMultiBody &); // not implemented
void solveImatrix(const btVector3& rhs_top, const btVector3& rhs_bot, btScalar result[6]) const;
void solveImatrix(const btSpatialForceVector &rhs, btSpatialMotionVector &result) const;
void updateLinksDofOffsets()
{
int dofOffset = 0, cfgOffset = 0;
for(int bidx = 0; bidx < m_links.size(); ++bidx)
{
m_links[bidx].m_dofOffset = dofOffset; m_links[bidx].m_cfgOffset = cfgOffset;
dofOffset += m_links[bidx].m_dofCount; cfgOffset += m_links[bidx].m_posVarCount;
}
}
void mulMatrix(btScalar *pA, btScalar *pB, int rowsA, int colsA, int rowsB, int colsB, btScalar *pC) const;
private:
btMultiBodyLinkCollider* m_baseCollider;//can be NULL
const char* m_baseName;//memory needs to be manager by user!
btVector3 m_basePos; // position of COM of base (world frame)
btQuaternion m_baseQuat; // rotates world points into base frame
btScalar m_baseMass; // mass of the base
btVector3 m_baseInertia; // inertia of the base (in local frame; diagonal)
btVector3 m_baseForce; // external force applied to base. World frame.
btVector3 m_baseTorque; // external torque applied to base. World frame.
btVector3 m_baseConstraintForce; // external force applied to base. World frame.
btVector3 m_baseConstraintTorque; // external torque applied to base. World frame.
btAlignedObjectArray<btMultibodyLink> m_links; // array of m_links, excluding the base. index from 0 to num_links-1.
//
// realBuf:
// offset size array
// 0 6 + num_links v (base_omega; base_vel; joint_vels) MULTIDOF [sysdof x sysdof for D matrices (TOO MUCH!) + pos_delta which is sys-cfg sized]
// 6+num_links num_links D
//
// vectorBuf:
// offset size array
// 0 num_links h_top
// num_links num_links h_bottom
//
// matrixBuf:
// offset size array
// 0 num_links+1 rot_from_parent
//
btAlignedObjectArray<btScalar> m_deltaV;
btAlignedObjectArray<btScalar> m_realBuf;
btAlignedObjectArray<btVector3> m_vectorBuf;
btAlignedObjectArray<btMatrix3x3> m_matrixBuf;
btMatrix3x3 m_cachedInertiaTopLeft;
btMatrix3x3 m_cachedInertiaTopRight;
btMatrix3x3 m_cachedInertiaLowerLeft;
btMatrix3x3 m_cachedInertiaLowerRight;
bool m_cachedInertiaValid;
bool m_fixedBase;
// Sleep parameters.
bool m_awake;
bool m_canSleep;
btScalar m_sleepTimer;
void* m_userObjectPointer;
int m_userIndex2;
int m_userIndex;
int m_companionId;
btScalar m_linearDamping;
btScalar m_angularDamping;
bool m_useGyroTerm;
btScalar m_maxAppliedImpulse;
btScalar m_maxCoordinateVelocity;
bool m_hasSelfCollision;
bool __posUpdated;
int m_dofCount, m_posVarCnt;
bool m_useRK4, m_useGlobalVelocities;
///the m_needsJointFeedback gets updated/computed during the stepVelocitiesMultiDof and it for internal usage only
bool m_internalNeedsJointFeedback;
};
struct btMultiBodyLinkDoubleData
{
btQuaternionDoubleData m_zeroRotParentToThis;
btVector3DoubleData m_parentComToThisComOffset;
btVector3DoubleData m_thisPivotToThisComOffset;
btVector3DoubleData m_jointAxisTop[6];
btVector3DoubleData m_jointAxisBottom[6];
btVector3DoubleData m_linkInertia; // inertia of the base (in local frame; diagonal)
double m_linkMass;
int m_parentIndex;
int m_jointType;
int m_dofCount;
int m_posVarCount;
double m_jointPos[7];
double m_jointVel[6];
double m_jointTorque[6];
double m_jointDamping;
double m_jointFriction;
double m_jointLowerLimit;
double m_jointUpperLimit;
double m_jointMaxForce;
double m_jointMaxVelocity;
char *m_linkName;
char *m_jointName;
btCollisionObjectDoubleData *m_linkCollider;
char *m_paddingPtr;
};
struct btMultiBodyLinkFloatData
{
btQuaternionFloatData m_zeroRotParentToThis;
btVector3FloatData m_parentComToThisComOffset;
btVector3FloatData m_thisPivotToThisComOffset;
btVector3FloatData m_jointAxisTop[6];
btVector3FloatData m_jointAxisBottom[6];
btVector3FloatData m_linkInertia; // inertia of the base (in local frame; diagonal)
int m_dofCount;
float m_linkMass;
int m_parentIndex;
int m_jointType;
float m_jointPos[7];
float m_jointVel[6];
float m_jointTorque[6];
int m_posVarCount;
float m_jointDamping;
float m_jointFriction;
float m_jointLowerLimit;
float m_jointUpperLimit;
float m_jointMaxForce;
float m_jointMaxVelocity;
char *m_linkName;
char *m_jointName;
btCollisionObjectFloatData *m_linkCollider;
char *m_paddingPtr;
};
///do not change those serialization structures, it requires an updated sBulletDNAstr/sBulletDNAstr64
struct btMultiBodyDoubleData
{
btTransformDoubleData m_baseWorldTransform;
btVector3DoubleData m_baseInertia; // inertia of the base (in local frame; diagonal)
double m_baseMass;
char *m_baseName;
btMultiBodyLinkDoubleData *m_links;
btCollisionObjectDoubleData *m_baseCollider;
char *m_paddingPtr;
int m_numLinks;
char m_padding[4];
};
///do not change those serialization structures, it requires an updated sBulletDNAstr/sBulletDNAstr64
struct btMultiBodyFloatData
{
char *m_baseName;
btMultiBodyLinkFloatData *m_links;
btCollisionObjectFloatData *m_baseCollider;
btTransformFloatData m_baseWorldTransform;
btVector3FloatData m_baseInertia; // inertia of the base (in local frame; diagonal)
float m_baseMass;
int m_numLinks;
};
#endif
| 412 | 0.983286 | 1 | 0.983286 | game-dev | MEDIA | 0.957337 | game-dev | 0.982944 | 1 | 0.982944 |
The-Evil-Pickle/Replay-the-Spire | 1,474 | src/main/java/com/megacrit/cardcrawl/mod/replay/actions/defect/TriggerPassiveAction.java | package com.megacrit.cardcrawl.mod.replay.actions.defect;
import com.megacrit.cardcrawl.actions.AbstractGameAction;
import com.megacrit.cardcrawl.core.*;
import com.megacrit.cardcrawl.dungeons.*;
import com.megacrit.cardcrawl.mod.replay.actions.*;
import com.megacrit.cardcrawl.mod.replay.orbs.*;
import com.megacrit.cardcrawl.orbs.AbstractOrb;
import java.util.*;
public class TriggerPassiveAction extends AbstractGameAction
{
private AbstractOrb targorb;
private int amount;
public TriggerPassiveAction() {
this(AbstractDungeon.player.orbs.get(0), 1);
}
public TriggerPassiveAction(AbstractOrb targorb) {
this(targorb, 1);
}
public TriggerPassiveAction(int amount) {
this(AbstractDungeon.player.orbs.get(0), amount);
}
public TriggerPassiveAction(int targindex, int amount) {
this(AbstractDungeon.player.orbs.get(targindex), amount);
}
public TriggerPassiveAction(AbstractOrb targorb, int amount) {
this.duration = Settings.ACTION_DUR_FAST;
this.targorb = targorb;
this.amount = amount;
if (AbstractDungeon.player.hasRelic("Cables") && AbstractDungeon.player.orbs.get(0) == targorb) {
this.amount++;
}
}
@Override
public void update() {
if (this.duration == Settings.ACTION_DUR_FAST && !AbstractDungeon.player.orbs.isEmpty()) {
for (int i = 0; i < this.amount; i++) {
this.targorb.onStartOfTurn();
this.targorb.onEndOfTurn();
}
}
this.tickDuration();
}
}
| 412 | 0.913158 | 1 | 0.913158 | game-dev | MEDIA | 0.941953 | game-dev | 0.979785 | 1 | 0.979785 |
OpenStarbound/OpenStarbound | 10,968 | source/game/StarDamage.cpp | #include "StarDamage.hpp"
#include "StarJsonExtra.hpp"
#include "StarDataStreamExtra.hpp"
#include "StarRoot.hpp"
namespace Star {
DamageSource::DamageSource()
: damageType(DamageType::NoDamage), damage(0.0), sourceEntityId(NullEntityId), rayCheck(false) {}
DamageSource::DamageSource(Json const& config) {
if (auto dtype = config.optString("damageType"))
damageType = DamageTypeNames.getLeft(*dtype);
else
damageType = DamageType::Damage;
if (config.contains("poly"))
damageArea = jsonToPolyF(config.get("poly"));
else if (config.contains("line"))
damageArea = jsonToLine2F(config.get("line"));
else
throw StarException("No 'poly' or 'line' key in DamageSource config");
damage = config.getFloat("damage");
trackSourceEntity = config.getBool("trackSourceEntity", true);
sourceEntityId = config.getInt("sourceEntityId", NullEntityId);
if (auto tconfig = config.opt("team")) {
team = EntityDamageTeam(*tconfig);
} else {
team.type = TeamTypeNames.getLeft(config.getString("teamType", "passive"));
team.team = config.getUInt("teamNumber", 0);
}
damageRepeatGroup = config.optString("damageRepeatGroup");
damageRepeatTimeout = config.optFloat("damageRepeatTimeout");
damageSourceKind = config.getString("damageSourceKind", "");
statusEffects = config.getArray("statusEffects", {}).transformed(jsonToEphemeralStatusEffect);
auto knockbackJson = config.get("knockback", Json(0.0f));
if (knockbackJson.isType(Json::Type::Array))
knockback = jsonToVec2F(knockbackJson);
else
knockback = knockbackJson.toFloat();
rayCheck = config.getBool("rayCheck", false);
}
DamageSource::DamageSource(DamageType damageType,
DamageArea damageArea,
float damage,
bool trackSourceEntity,
EntityId sourceEntityId,
EntityDamageTeam team,
Maybe<String> damageRepeatGroup,
Maybe<float> damageRepeatTimeout,
String damageSourceKind,
List<EphemeralStatusEffect> statusEffects,
Knockback knockback,
bool rayCheck)
: damageType(std::move(damageType)),
damageArea(std::move(damageArea)),
damage(std::move(damage)),
trackSourceEntity(std::move(trackSourceEntity)),
sourceEntityId(std::move(sourceEntityId)),
team(std::move(team)),
damageRepeatGroup(std::move(damageRepeatGroup)),
damageRepeatTimeout(std::move(damageRepeatTimeout)),
damageSourceKind(std::move(damageSourceKind)),
statusEffects(std::move(statusEffects)),
knockback(std::move(knockback)),
rayCheck(std::move(rayCheck)) {}
Json DamageSource::toJson() const {
Json damageAreaJson;
if (auto p = damageArea.ptr<PolyF>())
damageAreaJson = jsonFromPolyF(*p);
else if (auto l = damageArea.ptr<Line2F>())
damageAreaJson = jsonFromLine2F(*l);
Json knockbackJson;
if (auto p = knockback.ptr<float>())
knockbackJson = *p;
else if (auto p = knockback.ptr<Vec2F>())
knockbackJson = jsonFromVec2F(*p);
return JsonObject{{"damageType", DamageTypeNames.getRight(damageType)},
{"damageArea", damageAreaJson},
{"damage", damage},
{"trackSourceEntity", trackSourceEntity},
{"sourceEntityId", sourceEntityId},
{"team", team.toJson()},
{"damageRepeatGroup", jsonFromMaybe(damageRepeatGroup)},
{"damageRepeatTimeout", jsonFromMaybe(damageRepeatTimeout)},
{"damageSourceKind", damageSourceKind},
{"statusEffects", statusEffects.transformed(jsonFromEphemeralStatusEffect)},
{"knockback", knockbackJson},
{"rayCheck", rayCheck}};
}
bool DamageSource::intersectsWithPoly(WorldGeometry const& geometry, PolyF const& targetPoly) const {
if (auto poly = damageArea.ptr<PolyF>())
return geometry.polyIntersectsPoly(*poly, targetPoly);
else if (auto line = damageArea.ptr<Line2F>())
return geometry.lineIntersectsPoly(*line, targetPoly);
else
return false;
}
Vec2F DamageSource::knockbackMomentum(WorldGeometry const& worldGeometry, Vec2F const& targetCenter) const {
if (auto v = knockback.ptr<Vec2F>()) {
return *v;
} else if (auto s = knockback.ptr<float>()) {
if (*s != 0) {
if (auto poly = damageArea.ptr<PolyF>())
return worldGeometry.diff(targetCenter, poly->center()).normalized() * *s;
else if (auto line = damageArea.ptr<Line2F>())
return vnorm(line->diff()) * *s;
}
}
return Vec2F();
}
bool DamageSource::operator==(DamageSource const& rhs) const {
return tie(damageType, damageArea, damage, trackSourceEntity, sourceEntityId, team, damageSourceKind, statusEffects, knockback, rayCheck)
== tie(rhs.damageType,
rhs.damageArea,
rhs.damage,
rhs.trackSourceEntity,
rhs.sourceEntityId,
rhs.team,
rhs.damageSourceKind,
rhs.statusEffects,
rhs.knockback,
rhs.rayCheck);
}
DamageSource& DamageSource::translate(Vec2F const& position) {
if (auto poly = damageArea.ptr<PolyF>())
poly->translate(position);
else if (auto line = damageArea.ptr<Line2F>())
line->translate(position);
return *this;
}
DataStream& operator<<(DataStream& ds, DamageSource const& damageSource) {
ds.write(damageSource.damageType);
ds.write(damageSource.damageArea);
ds.write(damageSource.damage);
ds.write(damageSource.trackSourceEntity);
ds.write(damageSource.sourceEntityId);
ds.write(damageSource.team);
ds.write(damageSource.damageRepeatGroup);
ds.write(damageSource.damageRepeatTimeout);
ds.write(damageSource.damageSourceKind);
ds.write(damageSource.statusEffects);
ds.write(damageSource.knockback);
ds.write(damageSource.rayCheck);
return ds;
}
DataStream& operator>>(DataStream& ds, DamageSource& damageSource) {
ds.read(damageSource.damageType);
ds.read(damageSource.damageArea);
ds.read(damageSource.damage);
ds.read(damageSource.trackSourceEntity);
ds.read(damageSource.sourceEntityId);
ds.read(damageSource.team);
ds.read(damageSource.damageRepeatGroup);
ds.read(damageSource.damageRepeatTimeout);
ds.read(damageSource.damageSourceKind);
ds.read(damageSource.statusEffects);
ds.read(damageSource.knockback);
ds.read(damageSource.rayCheck);
return ds;
}
DamageRequest::DamageRequest()
: hitType(HitType::Hit), damageType(DamageType::Damage), damage(0.0f), sourceEntityId(NullEntityId) {}
DamageRequest::DamageRequest(Json const& v) {
hitType = HitTypeNames.getLeft(v.getString("hitType", "hit"));
damageType = DamageTypeNames.getLeft(v.getString("damageType", "damage"));
damage = v.getFloat("damage");
knockbackMomentum = jsonToVec2F(v.get("knockbackMomentum", JsonArray{0, 0}));
sourceEntityId = v.getInt("sourceEntityId", NullEntityId);
damageSourceKind = v.getString("damageSourceKind", "");
statusEffects = v.getArray("statusEffects", {}).transformed(jsonToEphemeralStatusEffect);
}
DamageRequest::DamageRequest(HitType hitType,
DamageType damageType,
float damage,
Vec2F const& knockbackMomentum,
EntityId sourceEntityId,
String const& damageSourceKind,
List<EphemeralStatusEffect> const& statusEffects)
: hitType(hitType),
damageType(damageType),
damage(damage),
knockbackMomentum(knockbackMomentum),
sourceEntityId(sourceEntityId),
damageSourceKind(damageSourceKind),
statusEffects(statusEffects) {}
Json DamageRequest::toJson() const {
return JsonObject{{"hitType", HitTypeNames.getRight(hitType)},
{"damageType", DamageTypeNames.getRight(damageType)},
{"damage", damage},
{"knockbackMomentum", jsonFromVec2F(knockbackMomentum)},
{"sourceEntityId", sourceEntityId},
{"damageSourceKind", damageSourceKind},
{"statusEffects", statusEffects.transformed(jsonFromEphemeralStatusEffect)}};
}
DataStream& operator<<(DataStream& ds, DamageRequest const& damageRequest) {
ds << damageRequest.hitType;
ds << damageRequest.damageType;
ds << damageRequest.damage;
ds << damageRequest.knockbackMomentum;
ds << damageRequest.sourceEntityId;
ds << damageRequest.damageSourceKind;
ds << damageRequest.statusEffects;
return ds;
}
DataStream& operator>>(DataStream& ds, DamageRequest& damageRequest) {
ds >> damageRequest.hitType;
ds >> damageRequest.damageType;
ds >> damageRequest.damage;
ds >> damageRequest.knockbackMomentum;
ds >> damageRequest.sourceEntityId;
ds >> damageRequest.damageSourceKind;
ds >> damageRequest.statusEffects;
return ds;
}
DamageNotification::DamageNotification() : sourceEntityId(), targetEntityId(), damageDealt(), healthLost() {}
DamageNotification::DamageNotification(Json const& v) {
sourceEntityId = v.getInt("sourceEntityId");
targetEntityId = v.getInt("targetEntityId");
position = jsonToVec2F(v.get("position"));
damageDealt = v.getFloat("damageDealt");
healthLost = v.getFloat("healthLost");
hitType = HitTypeNames.getLeft(v.getString("hitType"));
damageSourceKind = v.getString("damageSourceKind");
targetMaterialKind = v.getString("targetMaterialKind");
}
DamageNotification::DamageNotification(EntityId sourceEntityId,
EntityId targetEntityId,
Vec2F position,
float damageDealt,
float healthLost,
HitType hitType,
String damageSourceKind,
String targetMaterialKind)
: sourceEntityId(sourceEntityId),
targetEntityId(targetEntityId),
position(position),
damageDealt(damageDealt),
healthLost(healthLost),
hitType(hitType),
damageSourceKind(std::move(damageSourceKind)),
targetMaterialKind(std::move(targetMaterialKind)) {}
Json DamageNotification::toJson() const {
return JsonObject{{"sourceEntityId", sourceEntityId},
{"targetEntityId", targetEntityId},
{"position", jsonFromVec2F(position)},
{"damageDealt", damageDealt},
{"healthLost", healthLost},
{"hitType", HitTypeNames.getRight(hitType)},
{"damageSourceKind", damageSourceKind},
{"targetMaterialKind", targetMaterialKind}};
}
DataStream& operator<<(DataStream& ds, DamageNotification const& damageNotification) {
ds.viwrite(damageNotification.sourceEntityId);
ds.viwrite(damageNotification.targetEntityId);
ds.vfwrite(damageNotification.position[0], 0.01f);
ds.vfwrite(damageNotification.position[1], 0.01f);
ds.write(damageNotification.damageDealt);
ds.write(damageNotification.healthLost);
ds.write(damageNotification.hitType);
ds.write(damageNotification.damageSourceKind);
ds.write(damageNotification.targetMaterialKind);
return ds;
}
DataStream& operator>>(DataStream& ds, DamageNotification& damageNotification) {
ds.viread(damageNotification.sourceEntityId);
ds.viread(damageNotification.targetEntityId);
ds.vfread(damageNotification.position[0], 0.01f);
ds.vfread(damageNotification.position[1], 0.01f);
ds.read(damageNotification.damageDealt);
ds.read(damageNotification.healthLost);
ds.read(damageNotification.hitType);
ds.read(damageNotification.damageSourceKind);
ds.read(damageNotification.targetMaterialKind);
return ds;
}
}
| 412 | 0.798052 | 1 | 0.798052 | game-dev | MEDIA | 0.826814 | game-dev | 0.523129 | 1 | 0.523129 |
ndwzy/tcl-ha | 1,318 | custom_components/tcl/helpers.py | # TCL配置文件中设备属性的name并不唯一,identifier才是唯一的
# 用ATTR_NAME来存储需要替换的属性名称,也可以在这里修改描述不准确的属性名称,避免歧义
ATTR_NAME = {
"newWindECOSwitch": "新风节能",
"workMode": "模式",
"verticalWind": "上下扫风",
"selfCleanStatus": "蒸发器清洁状态",
"filterAgePercentage": "净化滤芯",
"screen": "灯光",
"beepSwitch": "提示音",
"sleep": "睡眠模式",
"targetTemperature": "温度",
"roomSize": "房间大小",
"windSpeedAutoSwitch": "风速自动",
"windSpeedPercentage": "风速",
"antiMoldew": "干燥",
"purifyDeodorizeSwitch": "净化除味",
"powerSwitch": "电源开关",
"ECO": "节能",
"newWindPercentage": "新风风速",
"newWindAutoSwitch": "新风风速自动",
"newWindSwitch": "新风开关",
"sensorTVOCLevel": "TVOC质量等级",
"healthy": "健康模式",
"selfLearn": "自学习",
"selfClean": "蒸发器清洁",
"PTC": "电辅热",
"horizontalWind": "左右扫风"
}
def try_read_as_bool(value):
if isinstance(value, bool):
return value
if isinstance(value, str):
return value == '1'
if isinstance(value, int):
return value == 1
raise ValueError('[{}]无法被转为bool'.format(value))
def get_key_by_value(d, value):
for key, val in d.items():
if val == value:
try:
return int(key)
except ValueError:
# 如果转换失败,返回原字符串
return key
return None # 如果没有找到,返回None
| 412 | 0.694619 | 1 | 0.694619 | game-dev | MEDIA | 0.192684 | game-dev | 0.566464 | 1 | 0.566464 |
Librelancer/Librelancer | 1,385 | src/LibreLancer/Utf/Ale/AlchemyFloats.cs | // MIT License - Copyright (c) Callum McGing
// This file is subject to the terms and conditions defined in
// LICENSE, which is part of this source code package
using System;
namespace LibreLancer.Utf.Ale
{
public class AlchemyFloats
{
public float SParam;
public EasingTypes Type;
public ValueTuple<float,float>[] Data;
public AlchemyFloats ()
{
}
public float GetValue(float time) {
//Only have one keyframe? Just return it.
if (Data.Length == 1) {
return Data [0].Item2;
}
//Locate the keyframes to interpolate between
float t1 = float.NegativeInfinity;
float t2 = 0, v1 = 0, v2 = 0;
for (int i = 0; i < Data.Length - 1; i++) {
if (time >= Data [i].Item1 && time <= Data [i + 1].Item1) {
t1 = Data [i].Item1;
t2 = Data [i + 1].Item1;
v1 = Data [i].Item2;
v2 = Data [i + 1].Item2;
break;
}
}
//Time wasn't between any values. Return max.
if (t1 == float.NegativeInfinity) {
return Data [Data.Length - 1].Item2;
}
//Interpolate!
return Easing.Ease(Type,time, t1, t2, v1, v2);
}
public float GetMax(bool abs)
{
float max = 0;
foreach (var i in Data)
{
var x = abs ? Math.Abs(i.Item2) : i.Item1;
if (x > max) max = x;
}
return max;
}
}
}
| 412 | 0.810823 | 1 | 0.810823 | game-dev | MEDIA | 0.47109 | game-dev | 0.952523 | 1 | 0.952523 |
armin-reichert/pacman-javafx | 5,771 | pacman-app-arcade-pacmanxxl/src/main/java/de/amr/pacmanfx/arcade/pacman_xxl/PacManXXL_PacMan_GameModel.java | /*
Copyright (c) 2021-2025 Armin Reichert (MIT License)
See file LICENSE in repository root directory for details.
*/
package de.amr.pacmanfx.arcade.pacman_xxl;
import de.amr.pacmanfx.GameContext;
import de.amr.pacmanfx.arcade.pacman.ArcadePacMan_GameModel;
import de.amr.pacmanfx.arcade.pacman.ArcadePacMan_HuntingTimer;
import de.amr.pacmanfx.arcade.pacman.Arcade_LevelData;
import de.amr.pacmanfx.arcade.pacman.actors.*;
import de.amr.pacmanfx.event.GameEventType;
import de.amr.pacmanfx.lib.Vector2i;
import de.amr.pacmanfx.lib.worldmap.TerrainLayer;
import de.amr.pacmanfx.lib.worldmap.TerrainTile;
import de.amr.pacmanfx.lib.worldmap.WorldMap;
import de.amr.pacmanfx.model.ArcadeHouse;
import de.amr.pacmanfx.model.GameLevel;
import de.amr.pacmanfx.model.MapSelectionMode;
import de.amr.pacmanfx.model.MapSelector;
import de.amr.pacmanfx.model.actors.Pac;
import de.amr.pacmanfx.steering.RuleBasedPacSteering;
import org.tinylog.Logger;
import java.io.File;
import java.util.List;
import static de.amr.pacmanfx.lib.RandomNumberSupport.randomInt;
import static de.amr.pacmanfx.lib.UsefulFunctions.halfTileRightOf;
import static de.amr.pacmanfx.model.DefaultWorldMapPropertyName.*;
/**
* Extension of Arcade Pac-Man with 8 new builtin mazes (thanks to the one and only
* <a href="https://github.com/masonicGIT/pacman">Shaun Williams</a>) and the possibility to
* play custom maps.
*/
public class PacManXXL_PacMan_GameModel extends ArcadePacMan_GameModel {
private static final int[] DEMO_LEVEL_NUMBERS = { 1, 3, 6, 10, 14, 18 };
// Warning: Constructor signature is used via reflection by GameUI_Builder, do not change!
public PacManXXL_PacMan_GameModel(GameContext gameContext, MapSelector mapSelector, File highScoreFile) {
super(gameContext, mapSelector, highScoreFile);
// Demo level map could be a custom map, so use generic auto-steering that also can cope with dead-ends:
demoLevelSteering = new RuleBasedPacSteering(gameContext);
}
@Override
public PacManXXL_Common_MapSelector mapSelector() { return (PacManXXL_Common_MapSelector) mapSelector; }
@Override
public GameLevel createLevel(int levelNumber, boolean demoLevel) {
final WorldMap worldMap = mapSelector.provideWorldMap(levelNumber);
final TerrainLayer terrain = worldMap.terrainLayer();
Vector2i houseMinTile = terrain.getTileProperty(POS_HOUSE_MIN_TILE);
if (houseMinTile == null) {
houseMinTile = ARCADE_MAP_HOUSE_MIN_TILE;
Logger.warn("No house min tile found in map, using {}", houseMinTile);
terrain.propertyMap().put(POS_HOUSE_MIN_TILE, String.valueOf(houseMinTile));
}
final ArcadeHouse house = new ArcadeHouse(houseMinTile);
terrain.setHouse(house);
final GameLevel newGameLevel = new GameLevel(this, levelNumber, worldMap, new ArcadePacMan_HuntingTimer());
newGameLevel.setDemoLevel(demoLevel);
newGameLevel.setGameOverStateTicks(90);
final Pac pacMan = ArcadePacMan_ActorFactory.createPacMan();
pacMan.setAutopilotSteering(autopilot);
newGameLevel.setPac(pacMan);
final Blinky blinky = ArcadePacMan_ActorFactory.createBlinky();
blinky.setStartPosition(halfTileRightOf(terrain.getTileProperty(POS_GHOST_1_RED)));
final Pinky pinky = ArcadePacMan_ActorFactory.createPinky();
pinky.setStartPosition(halfTileRightOf(terrain.getTileProperty(POS_GHOST_2_PINK)));
final Inky inky = ArcadePacMan_ActorFactory.createInky();
inky.setStartPosition(halfTileRightOf(terrain.getTileProperty(POS_GHOST_3_CYAN)));
final Clyde clyde = ArcadePacMan_ActorFactory.createClyde();
clyde.setStartPosition(halfTileRightOf(terrain.getTileProperty(POS_GHOST_4_ORANGE)));
newGameLevel.setGhosts(blinky, pinky, inky, clyde);
// Special tiles where attacking ghosts cannot move up
final List<Vector2i> oneWayDownTiles = terrain.tiles()
.filter(tile -> terrain.get(tile) == TerrainTile.ONE_WAY_DOWN.$)
.toList();
newGameLevel.ghosts().forEach(ghost -> ghost.setSpecialTerrainTiles(oneWayDownTiles));
// Each level has a single bonus symbol appearing twice during the level.
// From level 13 on, the same symbol (7, "key") appears.
byte symbol = BONUS_SYMBOLS_BY_LEVEL_NUMBER[Math.min(levelNumber, 13)];
newGameLevel.setBonusSymbol(0, symbol);
newGameLevel.setBonusSymbol(1, symbol);
levelCounter().setEnabled(true);
return newGameLevel;
}
@Override
public void buildDemoLevel() {
// Select random (standard) level with different map and map color scheme for each choice
int randomIndex = randomInt(0, DEMO_LEVEL_NUMBERS.length);
int levelNumber = DEMO_LEVEL_NUMBERS[randomIndex];
scoreManager().score().setLevelNumber(levelNumber);
mapSelector().setSelectionMode(MapSelectionMode.NO_CUSTOM_MAPS);
final GameLevel demoLevel = createLevel(levelNumber, true);
demoLevel.pac().setImmune(false);
demoLevel.pac().setUsingAutopilot(true);
demoLevel.pac().setAutopilotSteering(demoLevelSteering);
demoLevelSteering.init();
levelCounter().setEnabled(false);
gateKeeper.setLevelNumber(levelNumber);
demoLevel.worldMap().terrainLayer().optHouse().ifPresent(house -> gateKeeper.setHouse(house));
setGameLevel(demoLevel);
eventManager().publishEvent(GameEventType.LEVEL_CREATED);
}
@Override
public Arcade_LevelData levelData(GameLevel gameLevel) {
if (gameLevel.isDemoLevel()) {
return levelData(1);
}
return super.levelData(gameLevel);
}
} | 412 | 0.809493 | 1 | 0.809493 | game-dev | MEDIA | 0.984958 | game-dev | 0.971248 | 1 | 0.971248 |
QuiltServerTools/Ledger | 1,440 | src/main/kotlin/com/github/quiltservertools/ledger/callbacks/BlockBreakCallback.kt | package com.github.quiltservertools.ledger.callbacks
import com.github.quiltservertools.ledger.utility.Sources
import net.fabricmc.fabric.api.event.Event
import net.fabricmc.fabric.api.event.EventFactory
import net.minecraft.block.BlockState
import net.minecraft.block.entity.BlockEntity
import net.minecraft.entity.player.PlayerEntity
import net.minecraft.util.math.BlockPos
import net.minecraft.world.World
fun interface BlockBreakCallback {
fun breakBlock(
world: World,
pos: BlockPos,
state: BlockState,
entity: BlockEntity?,
source: String,
player: PlayerEntity?
)
fun breakBlock(world: World, pos: BlockPos, state: BlockState, entity: BlockEntity?, player: PlayerEntity) =
breakBlock(world, pos, state, entity, Sources.PLAYER, player)
fun breakBlock(world: World, pos: BlockPos, state: BlockState, entity: BlockEntity?, source: String) =
breakBlock(world, pos, state, entity, source, null)
companion object {
@JvmField
val EVENT: Event<BlockBreakCallback> =
EventFactory.createArrayBacked(BlockBreakCallback::class.java) { listeners ->
BlockBreakCallback { world, pos, state, entity, source, player ->
for (listener in listeners) {
listener.breakBlock(world, pos, state, entity, source, player)
}
}
}
}
}
| 412 | 0.867232 | 1 | 0.867232 | game-dev | MEDIA | 0.997908 | game-dev | 0.810063 | 1 | 0.810063 |
mangosthree/server | 42,601 | src/game/WorldHandlers/GossipDef.cpp | /**
* MaNGOS is a full featured server for World of Warcraft, supporting
* the following clients: 1.12.x, 2.4.3, 3.3.5a, 4.3.4a and 5.4.8
*
* Copyright (C) 2005-2025 MaNGOS <https://www.getmangos.eu>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* World of Warcraft, and all World of Warcraft or Warcraft art, images,
* and lore are copyrighted by Blizzard Entertainment, Inc.
*/
#include "GossipDef.h"
#include "QuestDef.h"
#include "ObjectMgr.h"
#include "Opcodes.h"
#include "WorldPacket.h"
#include "WorldSession.h"
#include "Formulas.h"
// Constructor for GossipMenu, initializes the session and reserves space for menu items
GossipMenu::GossipMenu(WorldSession* session) : m_session(session)
{
m_gItems.reserve(16); // can be set for max from most often sizes to speedup push_back and less memory use
m_gMenuId = 0;
}
// Destructor for GossipMenu, clears the menu items
GossipMenu::~GossipMenu()
{
ClearMenu();
}
// Adds a menu item to the gossip menu
void GossipMenu::AddMenuItem(uint8 Icon, const std::string& Message, uint32 dtSender, uint32 dtAction, const std::string& BoxMessage, uint32 BoxMoney, bool Coded)
{
MANGOS_ASSERT(m_gItems.size() <= GOSSIP_MAX_MENU_ITEMS);
GossipMenuItem gItem;
gItem.m_gIcon = Icon;
gItem.m_gMessage = Message;
gItem.m_gCoded = Coded;
gItem.m_gSender = dtSender;
gItem.m_gOptionId = dtAction;
gItem.m_gBoxMessage = BoxMessage;
gItem.m_gBoxMoney = BoxMoney;
m_gItems.push_back(gItem);
}
// Adds gossip menu item data
void GossipMenu::AddMenuItemData(int32 action_menu, uint32 action_poi, uint32 action_script)
{
GossipMenuItemData pItemData{};
pItemData.m_gAction_menu = action_menu;
pItemData.m_gAction_poi = action_poi;
pItemData.m_gAction_script = action_script;
m_gItemsData.push_back(pItemData);
}
// Overloaded method to add a menu item with fewer parameters
void GossipMenu::AddMenuItem(uint8 Icon, const std::string& Message, bool Coded)
{
AddMenuItem(Icon, Message, 0, 0, "", 0, Coded);
}
// Overloaded method to add a menu item with a C-style string message
void GossipMenu::AddMenuItem(uint8 Icon, char const* Message, bool Coded)
{
AddMenuItem(Icon, std::string(Message ? Message : ""), Coded);
}
void GossipMenu::AddMenuItem(uint8 Icon, char const* Message, uint32 dtSender, uint32 dtAction, char const* BoxMessage, uint32 BoxMoney, bool Coded)
{
AddMenuItem(Icon, std::string(Message ? Message : ""), dtSender, dtAction, std::string(BoxMessage ? BoxMessage : ""), BoxMoney, Coded);
}
void GossipMenu::AddMenuItem(uint8 Icon, int32 itemText, uint32 dtSender, uint32 dtAction, int32 boxText, uint32 BoxMoney, bool Coded)
{
uint32 loc_idx = m_session->GetSessionDbLocaleIndex();
char const* item_text = itemText ? sObjectMgr.GetMangosString(itemText, loc_idx) : "";
char const* box_text = boxText ? sObjectMgr.GetMangosString(boxText, loc_idx) : "";
AddMenuItem(Icon, std::string(item_text), dtSender, dtAction, std::string(box_text), BoxMoney, Coded);
}
// Returns the sender ID of a menu item
uint32 GossipMenu::MenuItemSender(unsigned int ItemId) const
{
if (ItemId >= m_gItems.size())
{
return 0;
}
return m_gItems[ItemId].m_gSender;
}
// Returns the action ID of a menu item
uint32 GossipMenu::MenuItemAction(unsigned int ItemId) const
{
if (ItemId >= m_gItems.size())
{
return 0;
}
return m_gItems[ItemId].m_gOptionId;
}
// Returns whether a menu item is coded
bool GossipMenu::MenuItemCoded(unsigned int ItemId) const
{
if (ItemId >= m_gItems.size())
{
return 0;
}
return m_gItems[ItemId].m_gCoded;
}
// Clears all menu items
void GossipMenu::ClearMenu()
{
m_gItems.clear();
m_gItemsData.clear();
m_gMenuId = 0;
}
// Constructor for PlayerMenu, initializes the gossip menu
PlayerMenu::PlayerMenu(WorldSession* session) : mGossipMenu(session)
{
}
// Destructor for PlayerMenu, clears all menus
PlayerMenu::~PlayerMenu()
{
ClearMenus();
}
// Clears all menus in the player menu
void PlayerMenu::ClearMenus()
{
mGossipMenu.ClearMenu();
mQuestMenu.ClearMenu();
}
// Returns the sender ID of a gossip option
uint32 PlayerMenu::GossipOptionSender(unsigned int Selection) const
{
return mGossipMenu.MenuItemSender(Selection);
}
// Returns the action ID of a gossip option
uint32 PlayerMenu::GossipOptionAction(unsigned int Selection) const
{
return mGossipMenu.MenuItemAction(Selection);
}
// Returns whether a gossip option is coded
bool PlayerMenu::GossipOptionCoded(unsigned int Selection) const
{
return mGossipMenu.MenuItemCoded(Selection);
}
// Sends the gossip menu to the player
void PlayerMenu::SendGossipMenu(uint32 TitleTextId, ObjectGuid objectGuid)
{
WorldPacket data(SMSG_GOSSIP_MESSAGE, (100)); // guess size
data << ObjectGuid(objectGuid);
data << uint32(mGossipMenu.GetMenuId()); // new 2.4.0
data << uint32(TitleTextId);
data << uint32(mGossipMenu.MenuItemCount()); // max count 0x20
for (uint32 iI = 0; iI < mGossipMenu.MenuItemCount(); ++iI)
{
GossipMenuItem const& gItem = mGossipMenu.GetItem(iI);
data << uint32(iI);
data << uint8(gItem.m_gIcon);
data << uint8(gItem.m_gCoded); // makes pop up box password
data << uint32(gItem.m_gBoxMoney); // money required to open menu, 2.0.3
data << gItem.m_gMessage; // text for gossip item, max 0x800
data << gItem.m_gBoxMessage; // accept text (related to money) pop up box, 2.0.3, max 0x800
}
data << uint32(mQuestMenu.MenuItemCount()); // max count 0x20
for (uint32 iI = 0; iI < mQuestMenu.MenuItemCount(); ++iI)
{
QuestMenuItem const& qItem = mQuestMenu.GetItem(iI);
uint32 questID = qItem.m_qId;
Quest const* pQuest = sObjectMgr.GetQuestTemplate(questID);
data << uint32(questID);
data << uint32(qItem.m_qIcon);
data << int32(pQuest->GetQuestLevel());
data << uint32(pQuest->GetQuestFlags()); // 3.3.3 quest flags
data << uint8(0); // 3.3.3 changes icon: blue question or yellow exclamation
int loc_idx = GetMenuSession()->GetSessionDbLocaleIndex();
std::string title = pQuest->GetTitle();
sObjectMgr.GetQuestLocaleStrings(questID, loc_idx, &title);
data << title; // max 0x200
}
GetMenuSession()->SendPacket(&data);
DEBUG_LOG("WORLD: Sent SMSG_GOSSIP_MESSAGE from %s", objectGuid.GetString().c_str());
}
// Closes the gossip menu
void PlayerMenu::CloseGossip() const
{
WorldPacket data(SMSG_GOSSIP_COMPLETE, 0);
GetMenuSession()->SendPacket(&data);
// DEBUG_LOG("WORLD: Sent SMSG_GOSSIP_COMPLETE");
}
// Sends a point of interest to the player (outdated method)
void PlayerMenu::SendPointOfInterest(float X, float Y, uint32 Icon, uint32 Flags, uint32 Data, char const* locName) const
{
WorldPacket data(SMSG_GOSSIP_POI, (4 + 4 + 4 + 4 + 4 + 10)); // guess size
data << uint32(Flags);
data << float(X);
data << float(Y);
data << uint32(Icon);
data << uint32(Data);
data << locName;
GetMenuSession()->SendPacket(&data);
// DEBUG_LOG("WORLD: Sent SMSG_GOSSIP_POI");
}
// Sends a point of interest to the player by ID
void PlayerMenu::SendPointOfInterest(uint32 poi_id) const
{
PointOfInterest const* poi = sObjectMgr.GetPointOfInterest(poi_id);
if (!poi)
{
sLog.outErrorDb("Requested send nonexistent POI (Id: %u), ignore.", poi_id);
return;
}
std::string icon_name = poi->icon_name;
int loc_idx = GetMenuSession()->GetSessionDbLocaleIndex();
if (loc_idx >= 0)
{
if (PointOfInterestLocale const* pl = sObjectMgr.GetPointOfInterestLocale(poi_id))
{
if (pl->IconName.size() > size_t(loc_idx) && !pl->IconName[loc_idx].empty())
{
icon_name = pl->IconName[loc_idx];
}
}
}
WorldPacket data(SMSG_GOSSIP_POI, (4 + 4 + 4 + 4 + 4 + 10)); // guess size
data << uint32(poi->flags);
data << float(poi->x);
data << float(poi->y);
data << uint32(poi->icon);
data << uint32(poi->data);
data << icon_name;
GetMenuSession()->SendPacket(&data);
// DEBUG_LOG("WORLD: Sent SMSG_GOSSIP_POI");
}
// Sends a talking message to the player by text ID
void PlayerMenu::SendTalking(uint32 textID) const
{
GossipText const* pGossip = sObjectMgr.GetGossipText(textID);
WorldPacket data(SMSG_NPC_TEXT_UPDATE, 100); // guess size
data << textID; // can be < 0
if (!pGossip)
{
for (uint32 i = 0; i < 8; ++i)
{
data << float(0);
data << "Greetings $N";
data << "Greetings $N";
data << uint32(0);
data << uint32(0);
data << uint32(0);
data << uint32(0);
data << uint32(0);
data << uint32(0);
data << uint32(0);
}
}
else
{
std::string Text_0[MAX_GOSSIP_TEXT_OPTIONS], Text_1[MAX_GOSSIP_TEXT_OPTIONS];
for (int i = 0; i < MAX_GOSSIP_TEXT_OPTIONS; ++i)
{
Text_0[i] = pGossip->Options[i].Text_0;
Text_1[i] = pGossip->Options[i].Text_1;
}
int loc_idx = GetMenuSession()->GetSessionDbLocaleIndex();
sObjectMgr.GetNpcTextLocaleStringsAll(textID, loc_idx, &Text_0, &Text_1);
for (int i = 0; i < MAX_GOSSIP_TEXT_OPTIONS; ++i)
{
data << pGossip->Options[i].Probability;
if (Text_0[i].empty())
{
data << Text_1[i];
}
else
{
data << Text_0[i];
}
if (Text_1[i].empty())
{
data << Text_0[i];
}
else
{
data << Text_1[i];
}
data << pGossip->Options[i].Language;
for (int j = 0; j < 3; ++j)
{
data << pGossip->Options[i].Emotes[j]._Delay;
data << pGossip->Options[i].Emotes[j]._Emote;
}
}
}
GetMenuSession()->SendPacket(&data);
DEBUG_LOG("WORLD: Sent SMSG_NPC_TEXT_UPDATE ");
}
// Sends a talking message to the player by title and text
void PlayerMenu::SendTalking(char const* title, char const* text) const
{
WorldPacket data(SMSG_NPC_TEXT_UPDATE, 50); // guess size
data << uint32(0);
for (uint32 i = 0; i < 8; ++i)
{
data << float(0);
data << title;
data << text;
data << uint32(0);
data << uint32(0);
data << uint32(0);
data << uint32(0);
data << uint32(0);
data << uint32(0);
data << uint32(0);
}
GetMenuSession()->SendPacket(&data);
DEBUG_LOG("WORLD: Sent SMSG_NPC_TEXT_UPDATE ");
}
/*********************************************************/
/*** QUEST SYSTEM ***/
/*********************************************************/
// Constructor for QuestMenu, reserves space for quest items
QuestMenu::QuestMenu()
{
m_qItems.reserve(16); // can be set for max from most often sizes to speedup push_back and less memory use
}
// Destructor for QuestMenu, clears the menu items
QuestMenu::~QuestMenu()
{
ClearMenu();
}
// Adds a quest menu item to the quest menu
void QuestMenu::AddMenuItem(uint32 QuestId, uint8 Icon)
{
Quest const* qinfo = sObjectMgr.GetQuestTemplate(QuestId);
if (!qinfo)
{
return;
}
MANGOS_ASSERT(m_qItems.size() <= GOSSIP_MAX_MENU_ITEMS);
QuestMenuItem qItem{};
qItem.m_qId = QuestId;
qItem.m_qIcon = Icon;
m_qItems.push_back(qItem);
}
// Checks if the quest menu has a specific item
bool QuestMenu::HasItem(uint32 questid) const
{
for (QuestMenuItemList::const_iterator i = m_qItems.begin(); i != m_qItems.end(); ++i)
{
if (i->m_qId == questid)
{
return true;
}
}
return false;
}
// Clears all quest menu items
void QuestMenu::ClearMenu()
{
m_qItems.clear();
}
// Sends the quest giver quest list to the player
void PlayerMenu::SendQuestGiverQuestList(QEmote eEmote, const std::string& Title, ObjectGuid npcGUID)
{
WorldPacket data(SMSG_QUESTGIVER_QUEST_LIST, 100); // guess size
data << ObjectGuid(npcGUID);
data << Title;
data << uint32(eEmote._Delay); // player emote
data << uint32(eEmote._Emote); // NPC emote
size_t count_pos = data.wpos();
data << uint8(mQuestMenu.MenuItemCount());
uint32 count = 0;
for (count = 0; count < mQuestMenu.MenuItemCount(); ++count)
{
QuestMenuItem const& qmi = mQuestMenu.GetItem(count);
uint32 questID = qmi.m_qId;
if (Quest const* pQuest = sObjectMgr.GetQuestTemplate(questID))
{
int loc_idx = GetMenuSession()->GetSessionDbLocaleIndex();
std::string title = pQuest->GetTitle();
sObjectMgr.GetQuestLocaleStrings(questID, loc_idx, &title);
data << uint32(questID);
data << uint32(qmi.m_qIcon);
data << int32(pQuest->GetQuestLevel());
data << uint32(pQuest->GetQuestFlags()); // 3.3.3 quest flags
data << uint8(0); // 3.3.3 changes icon: blue question or yellow exclamation
data << title;
}
}
data.put<uint8>(count_pos, count);
GetMenuSession()->SendPacket(&data);
DEBUG_LOG("WORLD: Sent SMSG_QUESTGIVER_QUEST_LIST NPC Guid = %s", npcGUID.GetString().c_str());
}
void PlayerMenu::SendQuestGiverStatus(uint32 questStatus, ObjectGuid npcGUID)
{
WorldPacket data(SMSG_QUESTGIVER_STATUS, 12);
data << npcGUID;
data << uint32(questStatus);
GetMenuSession()->SendPacket(&data);
DEBUG_LOG("WORLD: Sent SMSG_QUESTGIVER_STATUS for %s", npcGUID.GetString().c_str());
}
// Sends the quest giver quest details to the player
void PlayerMenu::SendQuestGiverQuestDetails(Quest const* pQuest, ObjectGuid guid, bool ActivateAccept) const
{
// Retrieve the quest title, details, and objectives
std::string Title = pQuest->GetTitle();
std::string Details = pQuest->GetDetails();
std::string Objectives = pQuest->GetObjectives();
std::string PortraitGiverName = pQuest->GetPortraitGiverName();
std::string PortraitGiverText = pQuest->GetPortraitGiverText();
std::string PortraitTurnInName = pQuest->GetPortraitTurnInName();
std::string PortraitTurnInText = pQuest->GetPortraitTurnInText();
// Get the locale index for the session
int loc_idx = GetMenuSession()->GetSessionDbLocaleIndex();
if (loc_idx >= 0)
{
// Retrieve localized quest strings if available
if (QuestLocale const* ql = sObjectMgr.GetQuestLocale(pQuest->GetQuestId()))
{
if (ql->Title.size() > (size_t)loc_idx && !ql->Title[loc_idx].empty())
{
Title = ql->Title[loc_idx];
}
if (ql->Details.size() > (size_t)loc_idx && !ql->Details[loc_idx].empty())
{
Details = ql->Details[loc_idx];
}
if (ql->Objectives.size() > (size_t)loc_idx && !ql->Objectives[loc_idx].empty())
{
Objectives = ql->Objectives[loc_idx];
}
if (ql->PortraitGiverName.size() > (size_t)loc_idx && !ql->PortraitGiverName[loc_idx].empty())
{
PortraitGiverName = ql->PortraitGiverName[loc_idx];
}
if (ql->PortraitGiverText.size() > (size_t)loc_idx && !ql->PortraitGiverText[loc_idx].empty())
{
PortraitGiverText = ql->PortraitGiverText[loc_idx];
}
if (ql->PortraitTurnInName.size() > (size_t)loc_idx && !ql->PortraitTurnInName[loc_idx].empty())
{
PortraitTurnInName = ql->PortraitTurnInName[loc_idx];
}
if (ql->PortraitTurnInText.size() > (size_t)loc_idx && !ql->PortraitTurnInText[loc_idx].empty())
{
PortraitTurnInText = ql->PortraitTurnInText[loc_idx];
}
}
}
// Prepare the packet to send quest details
WorldPacket data(SMSG_QUESTGIVER_QUEST_DETAILS, 100); // guess size
data << guid;
data << uint64(0); // wotlk, something todo with quest sharing?
data << uint32(pQuest->GetQuestId());
data << Title;
data << Details;
data << Objectives;
data << PortraitGiverText;
data << PortraitGiverName;
data << PortraitTurnInText;
data << PortraitTurnInName;
data << pQuest->GetPortraitGiver();
data << pQuest->GetPortraitTurnIn();
data << uint8(0); // this was used for auto quest accept, but it does not work
data << pQuest->GetQuestFlags(); // 3.3.3 questFlags
data << pQuest->GetSuggestedPlayers();
data << uint8(0); // IsFinished? value is sent back to server in quest accept packet
data << uint8(0); // is areatrigger quest
data << pQuest->GetReqSpellLearned();
data << pQuest->GetRewChoiceItemsCount();
for (uint32 i = 0; i < QUEST_REWARD_CHOICES_COUNT; ++i)
{
data << pQuest->RewChoiceItemId[i];
}
for (uint32 i = 0; i < QUEST_REWARD_CHOICES_COUNT; ++i)
{
data << pQuest->RewChoiceItemCount[i];
}
for (uint32 i = 0; i < QUEST_REWARD_CHOICES_COUNT; ++i)
if (ItemPrototype const* IProto = ObjectMgr::GetItemPrototype(pQuest->RewChoiceItemId[i]))
{
data << IProto->DisplayInfoID;
}
else
{
data << uint32(0);
}
data << pQuest->GetRewItemsCount();
for (uint32 i = 0; i < QUEST_REWARDS_COUNT; ++i)
{
data << pQuest->RewItemId[i];
}
for (uint32 i = 0; i < QUEST_REWARDS_COUNT; ++i)
{
data << pQuest->RewItemCount[i];
}
for (uint32 i = 0; i < QUEST_REWARDS_COUNT; ++i)
if (ItemPrototype const* IProto = ObjectMgr::GetItemPrototype(pQuest->RewItemId[i]))
{
data << IProto->DisplayInfoID;
}
else
{
data << uint32(0);
}
// send rewMoneyMaxLevel explicit for max player level, else send RewOrReqMoney
if (GetMenuSession()->GetPlayer()->getLevel() >= sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL))
{
data << pQuest->GetRewMoneyMaxLevel();
}
else
{
data << pQuest->GetRewOrReqMoney();
}
data << pQuest->XPValue(GetMenuSession()->GetPlayer());
data << pQuest->GetCharTitleId(); // CharTitleId, new 2.4.0, player gets this title (id from CharTitles)
data << uint32(0); // unk, unused 10 * GetRewHonorAddition ?
data << float(0); // unk, unused GetRewHonorMultiplier ?
data << pQuest->GetBonusTalents(); // bonus talents
data << uint32(0); // unk, unused bonus arena points?
data << uint32(0); // rep reward show mask?
for (int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i) // reward factions ids
{
data << pQuest->RewRepFaction[i];
}
for (int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i) // columnid in QuestFactionReward.dbc (if negative, from second row)
{
data << pQuest->RewRepValueId[i];
}
for (int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i) // reward reputation override. No bonus is expected given
{
data << int32(0);
}
// data << int32(pQuest->RewRepValue[i]); // current field for store of rep value, can be reused to implement "override value"
data << pQuest->GetRewSpell(); // reward spell, this spell will display (icon) (casted if RewSpellCast==0)
data << pQuest->GetRewSpellCast(); // casted spell
for (uint32 i = 0; i < QUEST_REWARD_CURRENCY_COUNT; ++i)
{
data << pQuest->RewCurrencyId[i];
}
for (uint32 i = 0; i < QUEST_REWARD_CURRENCY_COUNT; ++i)
{
data << pQuest->RewCurrencyCount[i];
}
data << pQuest->GetRewSkill();
data << pQuest->GetRewSkillValue();
data << uint32(QUEST_EMOTE_COUNT);
for (uint32 i = 0; i < QUEST_EMOTE_COUNT; ++i)
{
data << pQuest->DetailsEmote[i];
data << pQuest->DetailsEmoteDelay[i]; // DetailsEmoteDelay (in ms)
}
// Send the packet to the player
GetMenuSession()->SendPacket(&data);
// Log the sent packet
DEBUG_LOG("WORLD: Sent SMSG_QUESTGIVER_QUEST_DETAILS - for %s of %s, questid = %u", GetMenuSession()->GetPlayer()->GetGuidStr().c_str(), guid.GetString().c_str(), pQuest->GetQuestId());
}
// Sends the quest query response to the player
void PlayerMenu::SendQuestQueryResponse(Quest const* pQuest) const
{
std::string Title, Details, Objectives, EndText, CompletedText;
std::string PortraitGiverText, PortraitGiverName;
std::string PortraitTurnInText, PortraitTurnInName;
std::string ObjectiveText[QUEST_OBJECTIVES_COUNT];
Title = pQuest->GetTitle();
Details = pQuest->GetDetails();
Objectives = pQuest->GetObjectives();
EndText = pQuest->GetEndText();
CompletedText = pQuest->GetCompletedText();
PortraitGiverName = pQuest->GetPortraitGiverName();
PortraitGiverText = pQuest->GetPortraitGiverText();
PortraitTurnInName = pQuest->GetPortraitTurnInName();
PortraitTurnInText = pQuest->GetPortraitTurnInText();
for (int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
{
ObjectiveText[i] = pQuest->ObjectiveText[i];
}
// Get the locale index for the session
int loc_idx = GetMenuSession()->GetSessionDbLocaleIndex();
if (loc_idx >= 0)
{
// Retrieve localized quest strings if available
if (QuestLocale const* ql = sObjectMgr.GetQuestLocale(pQuest->GetQuestId()))
{
if (ql->Title.size() > (size_t)loc_idx && !ql->Title[loc_idx].empty())
{
Title = ql->Title[loc_idx];
}
if (ql->Details.size() > (size_t)loc_idx && !ql->Details[loc_idx].empty())
{
Details = ql->Details[loc_idx];
}
if (ql->Objectives.size() > (size_t)loc_idx && !ql->Objectives[loc_idx].empty())
{
Objectives = ql->Objectives[loc_idx];
}
if (ql->EndText.size() > (size_t)loc_idx && !ql->EndText[loc_idx].empty())
{
EndText = ql->EndText[loc_idx];
}
if (ql->CompletedText.size() > (size_t)loc_idx && !ql->CompletedText[loc_idx].empty())
{
CompletedText = ql->CompletedText[loc_idx];
}
if (ql->PortraitGiverName.size() > (size_t)loc_idx && !ql->PortraitGiverName[loc_idx].empty())
{
PortraitGiverName = ql->PortraitGiverName[loc_idx];
}
if (ql->PortraitGiverText.size() > (size_t)loc_idx && !ql->PortraitGiverText[loc_idx].empty())
{
PortraitGiverText = ql->PortraitGiverText[loc_idx];
}
if (ql->PortraitTurnInName.size() > (size_t)loc_idx && !ql->PortraitTurnInName[loc_idx].empty())
{
PortraitTurnInName = ql->PortraitTurnInName[loc_idx];
}
if (ql->PortraitTurnInText.size() > (size_t)loc_idx && !ql->PortraitTurnInText[loc_idx].empty())
{
PortraitTurnInText = ql->PortraitTurnInText[loc_idx];
}
for (int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
{
if (ql->ObjectiveText[i].size() > (size_t)loc_idx && !ql->ObjectiveText[i][loc_idx].empty())
{
ObjectiveText[i] = ql->ObjectiveText[i][loc_idx];
}
}
}
}
// Prepare the packet to send quest query response
WorldPacket data(SMSG_QUEST_QUERY_RESPONSE, 100); // guess size
data << uint32(pQuest->GetQuestId()); // quest id
data << uint32(pQuest->GetQuestMethod()); // Accepted values: 0, 1 or 2. 0==IsAutoComplete() (skip objectives/details)
data << int32(pQuest->GetQuestLevel()); // may be -1, static data, in other cases must be used dynamic level: Player::GetQuestLevelForPlayer (0 is not known, but assuming this is no longer valid for quest intended for client)
data << uint32(pQuest->GetMinLevel()); // min required level to obtain (added for 3.3). Assumed allowed (database) range is -1 to 255 (still using uint32, since negative value would not be of any known use for client)
data << uint32(pQuest->GetZoneOrSort()); // zone or sort to display in quest log
data << uint32(pQuest->GetType()); // quest type
data << uint32(pQuest->GetSuggestedPlayers()); // suggested players count
data << uint32(pQuest->GetRepObjectiveFaction()); // shown in quest log as part of quest objective
data << uint32(pQuest->GetRepObjectiveValue()); // shown in quest log as part of quest objective
data << uint32(0); // RequiredOppositeRepFaction
data << uint32(0); // RequiredOppositeRepValue, required faction value with another (oposite) faction (objective)
data << uint32(pQuest->GetNextQuestInChain()); // client will request this quest from NPC, if not 0
data << uint32(pQuest->GetRewXPId()); // column index in QuestXP.dbc (row based on quest level)
// unused 4.x.x ?
/*if (pQuest->HasQuestFlag(QUEST_FLAGS_HIDDEN_REWARDS))
data << uint32(0); // Hide money rewarded
else*/
{
data << uint32(pQuest->GetRewOrReqMoney()); // reward money (below max lvl)
}
data << uint32(pQuest->GetRewMoneyMaxLevel()); // used in XP calculation at client
data << uint32(pQuest->GetRewSpell()); // reward spell, this spell will display (icon) (casted if RewSpellCast==0)
data << uint32(pQuest->GetRewSpellCast()); // casted spell
// rewarded honor points
data << uint32(pQuest->GetRewHonorAddition()); // unused 4.x.x ?
data << float(pQuest->GetRewHonorMultiplier()); // unused 4.x.x ? new reward honor (multiplied by ~62 at client side)
data << uint32(pQuest->GetSrcItemId()); // source item id
data << uint32(pQuest->GetQuestFlags()); // quest flags
data << uint32(0); // MinimapTargetMark
data << uint32(pQuest->GetCharTitleId()); // CharTitleId, new 2.4.0, player gets this title (id from CharTitles)
data << uint32(pQuest->GetPlayersSlain()); // players slain
data << uint32(pQuest->GetBonusTalents()); // bonus talents
data << uint32(0); // unused 4.x.x ? bonus arena points
data << uint32(pQuest->GetRewSkill()); // Rewarded skill id
data << uint32(pQuest->GetRewSkillValue()); // Rewarded skill bonus points
data << uint32(0); // rew rep show mask?
data << uint32(pQuest->GetPortraitGiver());
data << uint32(pQuest->GetPortraitTurnIn());
// Add reward items
int iI;
// unused 4.?.?
/*if (pQuest->HasQuestFlag(QUEST_FLAGS_HIDDEN_REWARDS))
{
for (iI = 0; iI < QUEST_REWARDS_COUNT; ++iI)
{
data << uint32(0) << uint32(0);
}
for (iI = 0; iI < QUEST_REWARD_CHOICES_COUNT; ++iI)
{
data << uint32(0) << uint32(0);
}
}
else*/
{
for (iI = 0; iI < QUEST_REWARDS_COUNT; ++iI)
{
data << uint32(pQuest->RewItemId[iI]);
data << uint32(pQuest->RewItemCount[iI]);
}
for (iI = 0; iI < QUEST_REWARD_CHOICES_COUNT; ++iI)
{
data << uint32(pQuest->RewChoiceItemId[iI]);
data << uint32(pQuest->RewChoiceItemCount[iI]);
}
}
for (int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i) // reward factions ids
{
data << uint32(pQuest->RewRepFaction[i]);
}
for (int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i) // columnid in QuestFactionReward.dbc (if negative, from second row)
{
data << int32(pQuest->RewRepValueId[i]);
}
for (int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i) // reward reputation override. No bonus is expected given
{
data << int32(0);
}
// data << int32(pQuest->RewRepValue[i]); // current field for store of rep value, can be reused to implement "override value"
// Add quest point information
data << pQuest->GetPointMapId();
data << pQuest->GetPointX();
data << pQuest->GetPointY();
data << pQuest->GetPointOpt();
// Add quest texts
data << Title;
data << Objectives;
data << Details;
data << EndText;
data << CompletedText; // display in quest objectives window once all objectives are completed
// Add quest objectives
for (iI = 0; iI < QUEST_OBJECTIVES_COUNT; ++iI)
{
if (pQuest->ReqCreatureOrGOId[iI] < 0)
{
// client expected gameobject template id in form (id|0x80000000)
data << uint32((pQuest->ReqCreatureOrGOId[iI] * (-1)) | 0x80000000);
}
else
{
data << uint32(pQuest->ReqCreatureOrGOId[iI]);
}
data << uint32(pQuest->ReqCreatureOrGOCount[iI]);
data << uint32(pQuest->ReqSourceId[iI]);
data << uint32(pQuest->ReqSourceCount[iI]);
}
for (iI = 0; iI < QUEST_ITEM_OBJECTIVES_COUNT; ++iI)
{
data << uint32(pQuest->ReqItemId[iI]);
data << uint32(pQuest->ReqItemCount[iI]);
}
data << uint32(pQuest->GetReqSpellLearned());
for (iI = 0; iI < QUEST_OBJECTIVES_COUNT; ++iI)
{
data << ObjectiveText[iI];
}
for(iI = 0; iI < QUEST_REWARD_CURRENCY_COUNT; ++iI)
{
data << uint32(pQuest->RewCurrencyId[iI]);
data << uint32(pQuest->RewCurrencyCount[iI]);
}
for(iI = 0; iI < QUEST_REQUIRED_CURRENCY_COUNT; ++iI)
{
data << uint32(pQuest->ReqCurrencyId[iI]);
data << uint32(pQuest->ReqCurrencyCount[iI]);
}
data << PortraitGiverText;
data << PortraitGiverName;
data << PortraitTurnInText;
data << PortraitTurnInName;
data << uint32(pQuest->GetSoundAcceptId());
data << uint32(pQuest->GetSoundTurnInId());
GetMenuSession()->SendPacket(&data);
// Log the sent packet
DEBUG_LOG("WORLD: Sent SMSG_QUEST_QUERY_RESPONSE questid=%u", pQuest->GetQuestId());
}
void PlayerMenu::SendQuestGiverOfferReward(Quest const* pQuest, ObjectGuid npcGUID, bool EnableNext) const
{
// Retrieve the quest title and offer reward text
std::string Title = pQuest->GetTitle();
std::string OfferRewardText = pQuest->GetOfferRewardText();
std::string PortraitGiverName = pQuest->GetPortraitGiverName();
std::string PortraitGiverText = pQuest->GetPortraitGiverText();
std::string PortraitTurnInName = pQuest->GetPortraitTurnInName();
std::string PortraitTurnInText = pQuest->GetPortraitTurnInText();
// Get the locale index for the session
int loc_idx = GetMenuSession()->GetSessionDbLocaleIndex();
if (loc_idx >= 0)
{
// Retrieve localized quest strings if available
if (QuestLocale const* ql = sObjectMgr.GetQuestLocale(pQuest->GetQuestId()))
{
if (ql->Title.size() > (size_t)loc_idx && !ql->Title[loc_idx].empty())
{
Title = ql->Title[loc_idx];
}
if (ql->OfferRewardText.size() > (size_t)loc_idx && !ql->OfferRewardText[loc_idx].empty())
{
OfferRewardText = ql->OfferRewardText[loc_idx];
}
if (ql->PortraitGiverName.size() > (size_t)loc_idx && !ql->PortraitGiverName[loc_idx].empty())
{
PortraitGiverName = ql->PortraitGiverName[loc_idx];
}
if (ql->PortraitGiverText.size() > (size_t)loc_idx && !ql->PortraitGiverText[loc_idx].empty())
{
PortraitGiverText = ql->PortraitGiverText[loc_idx];
}
if (ql->PortraitTurnInName.size() > (size_t)loc_idx && !ql->PortraitTurnInName[loc_idx].empty())
{
PortraitTurnInName = ql->PortraitTurnInName[loc_idx];
}
if (ql->PortraitTurnInText.size() > (size_t)loc_idx && !ql->PortraitTurnInText[loc_idx].empty())
{
PortraitTurnInText = ql->PortraitTurnInText[loc_idx];
}
}
}
// Prepare the packet to send quest offer reward
WorldPacket data(SMSG_QUESTGIVER_OFFER_REWARD, 50); // guess size
// Add NPC GUID, quest ID, title, and offer reward text to the packet
data << ObjectGuid(npcGUID);
data << uint32(pQuest->GetQuestId());
data << Title;
data << OfferRewardText;
data << PortraitGiverText;
data << PortraitGiverName;
data << PortraitTurnInText;
data << PortraitTurnInName;
data << uint32(pQuest->GetPortraitGiver());
data << uint32(pQuest->GetPortraitTurnIn());
data << uint8(EnableNext ? 1 : 0); // Auto Finish
data << uint32(pQuest->GetQuestFlags()); // 3.3.3 questFlags
data << uint32(pQuest->GetSuggestedPlayers()); // SuggestedGroupNum
// Add quest emotes to the packet
uint32 EmoteCount = 0;
for (uint32 i = 0; i < QUEST_EMOTE_COUNT; ++i)
{
if (pQuest->OfferRewardEmote[i] <= 0)
{
break;
}
++EmoteCount;
}
data << EmoteCount; // Emote Count
for (uint32 i = 0; i < EmoteCount; ++i)
{
data << uint32(pQuest->OfferRewardEmoteDelay[i]); // Delay Emote
data << uint32(pQuest->OfferRewardEmote[i]);
}
data << uint32(pQuest->GetRewChoiceItemsCount());
for (uint32 i = 0; i < QUEST_REWARD_CHOICES_COUNT; ++i)
{
data << uint32(pQuest->RewChoiceItemId[i]);
}
for (uint32 i = 0; i < QUEST_REWARD_CHOICES_COUNT; ++i)
{
data << uint32(pQuest->RewChoiceItemCount[i]);
}
for (uint32 i = 0; i < QUEST_REWARD_CHOICES_COUNT; ++i)
if (ItemPrototype const* pItem = ObjectMgr::GetItemPrototype(pQuest->RewChoiceItemId[i]))
{
data << uint32(pItem->DisplayInfoID);
}
else
{
data << uint32(0);
}
// Add reward items to the packet
data << uint32(pQuest->GetRewItemsCount());
for (uint32 i = 0; i < QUEST_REWARDS_COUNT; ++i)
{
data << uint32(pQuest->RewItemId[i]);
}
for (uint32 i = 0; i < QUEST_REWARDS_COUNT; ++i)
{
data << uint32(pQuest->RewItemCount[i]);
}
for (uint32 i = 0; i < QUEST_REWARDS_COUNT; ++i)
if (ItemPrototype const* pItem = ObjectMgr::GetItemPrototype(pQuest->RewItemId[i]))
{
data << uint32(pItem->DisplayInfoID);
}
else
{
data << uint32(0);
}
// send rewMoneyMaxLevel explicit for max player level, else send RewOrReqMoney
if (GetMenuSession()->GetPlayer()->getLevel() >= sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL))
{
data << uint32(pQuest->GetRewMoneyMaxLevel());
}
else
{
data << uint32(pQuest->GetRewOrReqMoney());
}
// xp
data << uint32(pQuest->XPValue(GetMenuSession()->GetPlayer()));
data << uint32(pQuest->GetCharTitleId()); // character title
data << uint32(0); // unk, unused 10 * GetRewHonorAddition ?
data << float(0); // unk, unused GetRewHonorMultiplier ?
data << uint32(pQuest->GetBonusTalents()); // bonus talents
data << uint32(0); // unk, unused bonus arena points?
data << uint32(0); // rep reward show mask?
for (int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i) // reward factions ids
{
data << uint32(pQuest->RewRepFaction[i]);
}
for (int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i) // columnid in QuestFactionReward.dbc (if negative, from second row)
{
data << int32(pQuest->RewRepValueId[i]);
}
for (int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i) // reward reputation override. No diplomacy bonus is expected given, reward also does not display in chat window
{
data << int32(0);
}
// data << int32(pQuest->RewRepValue[i]);
data << uint32(pQuest->GetRewSpell()); // reward spell, this spell will display (icon) (casted if RewSpellCast==0)
data << uint32(pQuest->GetRewSpellCast()); // casted spell
for (uint32 i = 0; i < QUEST_REWARD_CURRENCY_COUNT; ++i)
{
data << uint32(pQuest->RewCurrencyId[i]);
}
for (uint32 i = 0; i < QUEST_REWARD_CURRENCY_COUNT; ++i)
{
data << uint32(pQuest->RewCurrencyCount[i]);
}
data << uint32(pQuest->GetRewSkill());
data << uint32(pQuest->GetRewSkillValue());
GetMenuSession()->SendPacket(&data);
// Log the sent packet
DEBUG_LOG("WORLD: Sent SMSG_QUESTGIVER_OFFER_REWARD NPCGuid = %s, questid = %u", npcGUID.GetString().c_str(), pQuest->GetQuestId());
}
void PlayerMenu::SendQuestGiverRequestItems(Quest const* pQuest, ObjectGuid npcGUID, bool Completable, bool CloseOnCancel) const
{
// We can always call to RequestItems, but this packet only goes out if there are actually
// items. Otherwise, we'll skip straight to the OfferReward
if (!pQuest->GetReqItemsCount() && !pQuest->GetReqCurrencyCount() && Completable)
{
SendQuestGiverOfferReward(pQuest, npcGUID, true);
return;
}
std::string Title = pQuest->GetTitle();
std::string RequestItemsText = pQuest->GetRequestItemsText();
// Get the locale index for the session
int loc_idx = GetMenuSession()->GetSessionDbLocaleIndex();
if (loc_idx >= 0)
{
// Retrieve localized quest strings if available
if (QuestLocale const* ql = sObjectMgr.GetQuestLocale(pQuest->GetQuestId()))
{
if (ql->Title.size() > (size_t)loc_idx && !ql->Title[loc_idx].empty())
{
Title = ql->Title[loc_idx];
}
if (ql->RequestItemsText.size() > (size_t)loc_idx && !ql->RequestItemsText[loc_idx].empty())
{
RequestItemsText = ql->RequestItemsText[loc_idx];
}
}
}
WorldPacket data(SMSG_QUESTGIVER_REQUEST_ITEMS, 50); // guess size
data << ObjectGuid(npcGUID); // NPC GUID
data << uint32(pQuest->GetQuestId()); // Quest ID
data << Title; // Quest title
data << RequestItemsText; // Request items text
data << uint32(0x00); // emote delay
// Add the appropriate emote based on whether the quest is completable
if (Completable)
{
data << pQuest->GetCompleteEmote(); // emote id
}
else
{
data << pQuest->GetIncompleteEmote();
}
// Add the close on cancel flag
if (CloseOnCancel)
{
data << uint32(0x01); // auto finish
}
else
{
data << uint32(0x00);
}
data << uint32(pQuest->GetQuestFlags()); // 3.3.3 questFlags
data << uint32(pQuest->GetSuggestedPlayers()); // SuggestedGroupNum
// Add the required money
data << uint32(pQuest->GetRewOrReqMoney() < 0 ? -pQuest->GetRewOrReqMoney() : 0);
// Add the required items
data << uint32(pQuest->GetReqItemsCount());
ItemPrototype const* pItem;
for (int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
{
if (!pQuest->ReqItemId[i])
{
continue;
}
pItem = ObjectMgr::GetItemPrototype(pQuest->ReqItemId[i]);
data << uint32(pQuest->ReqItemId[i]);
data << uint32(pQuest->ReqItemCount[i]);
if (pItem)
{
data << uint32(pItem->DisplayInfoID);
}
else
{
data << uint32(0);
}
}
data << uint32(pQuest->GetReqCurrencyCount());
for (int i = 0; i < QUEST_REQUIRED_CURRENCY_COUNT; ++i)
{
if (!pQuest->ReqCurrencyId[i])
{
continue;
}
data << uint32(pQuest->ReqCurrencyId[i]);
data << uint32(pQuest->ReqCurrencyCount[i]);
}
if (!Completable) // Completable = flags1 && flags2 && flags3 && flags4
{
data << uint32(0x00); // flags1
}
else
{
data << uint32(0x03);
}
data << uint32(0x04); // flags2
data << uint32(0x08); // flags3
data << uint32(0x10); // flags4
data << uint32(0x40); // flags5
// Send the packet to the player
GetMenuSession()->SendPacket(&data);
DEBUG_LOG("WORLD: Sent SMSG_QUESTGIVER_REQUEST_ITEMS NPCGuid = %s, questid = %u", npcGUID.GetString().c_str(), pQuest->GetQuestId());
}
| 412 | 0.884861 | 1 | 0.884861 | game-dev | MEDIA | 0.646328 | game-dev | 0.716322 | 1 | 0.716322 |
microsoft/MixedReality-WorldLockingTools-Samples | 4,324 | Advanced/QRSpacePins/Assets/MRTK/SDK/Features/UX/Scripts/Pointers/SpherePointerVisual.cs | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Microsoft.MixedReality.Toolkit.Utilities;
using Unity.Profiling;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Input
{
[AddComponentMenu("Scripts/MRTK/SDK/SpherePointerVisual")]
public class SpherePointerVisual : MonoBehaviour
{
public Transform TetherEndPoint => tetherEndPoint;
public bool TetherVisualsEnabled { get; private set; }
[Tooltip("The pointer these visuals decorate")]
private SpherePointer pointer;
[SerializeField]
[Tooltip("Tether will not be shown unless it is at least this long")]
private float minTetherLength = 0.03f;
[SerializeField]
private Transform visualsRoot = null;
[SerializeField]
private Transform tetherEndPoint = null;
/// Assumption: Tether line is a child of the visuals!
[SerializeField]
private BaseMixedRealityLineDataProvider tetherLine = null;
public void OnEnable()
{
CheckInitialization();
}
public void OnDestroy()
{
if (visualsRoot != null)
{
Destroy(visualsRoot.gameObject);
}
}
public void Start()
{
// put it at root of scene
MixedRealityPlayspace.AddChild(visualsRoot.transform);
visualsRoot.gameObject.name = $"{gameObject.name}_NearTetherVisualsRoot";
}
private void CheckInitialization()
{
if (pointer == null)
{
pointer = GetComponent<SpherePointer>();
}
if (pointer == null)
{
Debug.LogError($"No SpherePointer found on {gameObject.name}.");
}
CheckAsset(visualsRoot, "Visuals Root");
CheckAsset(tetherEndPoint, "Tether End Point");
CheckAsset(tetherLine, "Tether Line");
}
private void CheckAsset(object asset, string fieldname)
{
if (asset == null)
{
Debug.LogError($"No {fieldname} specified on {gameObject.name}.SpherePointerVisual. Did you forget to set the {fieldname}?");
}
}
private static readonly ProfilerMarker UpdatePerfMarker = new ProfilerMarker("[MRTK] SpherePointerVisual.Update");
public void Update()
{
using (UpdatePerfMarker.Auto())
{
TetherVisualsEnabled = false;
if (pointer.IsFocusLocked && pointer.IsTargetPositionLockedOnFocusLock && pointer.Result != null)
{
NearInteractionGrabbable grabbedObject = GetGrabbedObject();
if (grabbedObject != null && grabbedObject.ShowTetherWhenManipulating)
{
Vector3 graspPosition;
pointer.TryGetNearGraspPoint(out graspPosition);
tetherLine.FirstPoint = graspPosition;
Vector3 endPoint = pointer.Result.Details.Object.transform.TransformPoint(pointer.Result.Details.PointLocalSpace);
tetherLine.LastPoint = endPoint;
TetherVisualsEnabled = Vector3.Distance(tetherLine.FirstPoint, tetherLine.LastPoint) > minTetherLength;
tetherLine.enabled = TetherVisualsEnabled;
tetherEndPoint.gameObject.SetActive(TetherVisualsEnabled);
tetherEndPoint.position = endPoint;
}
}
visualsRoot.gameObject.SetActive(TetherVisualsEnabled);
}
}
private static readonly ProfilerMarker GetGrabbedObjectPerfMarker = new ProfilerMarker("[MRTK] SpherePointer.GetGrabbedObject");
private NearInteractionGrabbable GetGrabbedObject()
{
using (GetGrabbedObjectPerfMarker.Auto())
{
if (pointer.Result?.Details.Object != null)
{
return pointer.Result.Details.Object.GetComponent<NearInteractionGrabbable>();
}
else
{
return null;
}
}
}
}
} | 412 | 0.934692 | 1 | 0.934692 | game-dev | MEDIA | 0.657152 | game-dev,graphics-rendering | 0.950752 | 1 | 0.950752 |
wahidrachmawan/uNode | 1,199 | Assets/uNode3/Runtime/Script/Nodes/Behavior Trees/Decorators/Failer.cs | using UnityEngine;
using System.Collections;
namespace MaxyGames.UNode.Nodes {
[NodeMenu("Behavior Tree.Decorators", "Failer", scope = NodeScope.StateGraph, IsCoroutine = true)]
[Description("Always failure regardless of whether the targetNode success or failure.")]
public class Failer : CoroutineNode {
protected override bool AutoExit => false;
protected override IEnumerator OnExecutedCoroutine(Flow flow) {
if(!exit.isConnected) {
yield break;
}
flow.TriggerCoroutine(exit, out var wait, out var jump);
if(wait != null)
yield return wait;
var js = jump();
if(js != null) {
flow.jumpStatement = js;
yield break;
}
yield return false;
}
public override void OnGeneratorInitialize() {
//Register this node as state node, because this is coroutine node with state.
CG.RegisterAsStateFlow(enter);
CG.SetStateInitialization(enter, () => CG.GeneratePort(enter));
if(exit.isAssigned) {
CG.RegisterAsStateFlow(exit.GetTargetFlow());
}
CG.RegisterPort(enter, () => {
if(!exit.isAssigned)
throw new System.Exception("Exit is not assigned");
return CG.New(typeof(Runtime.Failer), CG.GetEvent(exit));
});
}
}
}
| 412 | 0.876504 | 1 | 0.876504 | game-dev | MEDIA | 0.689847 | game-dev | 0.830358 | 1 | 0.830358 |
jinglikeblue/ZeroGameKit | 1,074 | Assets/@Scripts/Examples/Game2DExample/Sokoban/Modules/LevelModule.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Zero;
using ZeroGameKit;
namespace Sokoban
{
public class LevelModule : BaseModule
{
/// <summary>
/// 当前的关卡模型
/// </summary>
public LevelModel lv { get; private set; }
public LevelModule()
{
SokobanGlobal.Ins.Notice.onLevelComplete += OnLevelComplete;
}
private void OnLevelComplete()
{
if (lv.id == Define.LEVEL_AMOUNT)
{
EnterLevel(1);
}
else
{
EnterLevel(lv.id + 1);
}
}
public void EnterLevel(int level)
{
lv = new LevelModel(level);
var loading = UIWinMgr.Ins.Open<LoadingWin>();
loading.onSwitch += () =>
{
UIPanelMgr.Ins.Switch<SokobanGamePanel>();
};
}
public override void Dispose()
{
}
}
}
| 412 | 0.605919 | 1 | 0.605919 | game-dev | MEDIA | 0.90695 | game-dev | 0.50374 | 1 | 0.50374 |
mtuomi/SecondReality | 9,257 | VISU/C/U2A.BBK | #include <stdio.h>
#include <conio.h>
#include <string.h>
#include <malloc.h>
#include "..\cd.h"
#include "..\c.h"
#define noDEBUG
int indemo=0;
extern char bg[];
char *bg2;
char scene[64]={"U2A"};
char tmpname[64];
char huge *scene0;
char huge *scenem;
int city=0;
int xit=0;
#define LONGAT(zz) *((long huge *)(zz))
#define INTAT(zz) *((int huge *)(zz))
#define CHARAT(zz) *((char huge *)(zz))
struct s_scl
{
char *data;
} scenelist[64];
int scl=0,sclp=0;
#define MAXOBJ 256
struct s_co
{
object *o;
long dist;
int index;
int on;
} co[MAXOBJ];
int conum;
FILE *fr;
object camobject;
rmatrix cam;
int order[MAXOBJ],ordernum;
unsigned char huge *sp;
long lsget(unsigned char f)
{
long l;
switch(f&3)
{
case 0 : l=0;
break;
case 1 : l=(long)(char)(*sp++);
break;
case 2 : l=*sp++;
l|=(long)(char)(*sp++)<<8;
break;
case 3 : l=*sp++;
l|=(long)(*sp++)<<8;
l|=(long)(*sp++)<<16;
l|=(long)(char)(*sp++)<<24;
break;
}
return(l);
}
void resetscene(void)
{
int a;
sp=(unsigned char *)(scenelist[sclp].data);
for(a=0;a<conum;a++)
{
memset(co[a].o->r,0,sizeof(rmatrix));
memset(co[a].o->r0,0,sizeof(rmatrix));
}
sclp++;
if(sclp>=scl)
{
sclp=0;
}
}
struct
{
int frames;
int ready; // 1=to be displayed, 0=displayed
} cl[4];
int clr=0,clw=0;
int clshow=-1,cldraw=-1,clshow1=0;
int deadlock=0;
int coppercnt=0;
int syncframe=0;
int currframe=0;
int copperdelay=16;
int repeat,avgrepeat;
#pragma check_stack(off)
void _loadds copper2(void)
{
int a,c1,c2,c3,c4;
syncframe++;
if(cl[0].ready==2) cl[0].ready=0;
if(cl[1].ready==2) cl[1].ready=0;
if(cl[2].ready==2) cl[2].ready=0;
if(cl[3].ready==2) cl[3].ready=0;
/*
c1=cl[0].ready;
c2=cl[1].ready;
c3=cl[2].ready;
c4=cl[3].ready;
_asm mov ah,byte ptr c1
_asm mov al,byte ptr c2
_asm mov bh,byte ptr c3
_asm mov bl,byte ptr c4
_asm mov ch,byte ptr clshow
_asm mov cl,byte ptr cldraw
_asm mov dh,byte ptr clr
_asm mov dl,byte ptr clw
_asm int 3
_asm nop
*/
deadlock++;
coppercnt++;
if(copperdelay>0)
{
copperdelay--;
return;
}
else copperdelay=0;
if(cl[clr].ready)
{
cl[(clr-1)&3].ready=2;
vid_setswitch(-1,clshow=clr);
copperdelay=cl[clr].frames;
clr++; clr&=3;
}
else avgrepeat++;
}
main(int argc,char *argv[])
{
char huge *sptemp;
int huge *ip;
unsigned int u;
char huge *cp;
int a,b,c,d,e,f,g,x,y,z;
#ifdef DEBUG
fr=fopen("tmp","wt");
#endif
indemo=1;
dis_partstart();
sprintf(tmpname,"%s.00M",scene);
if(!indemo) printf("Loading materials %s...\n",tmpname);
scene0=scenem=readfile(tmpname);
memcpy(scene0+16+192*3,bg+16,64*3);
bg2=halloc(16384,4);
for(u=z=0;z<4;z++)
{
for(y=0;y<200;y++)
{
for(x=z;x<320;x+=4)
{
a=bg[16+768+x+y*320];
bg2[u++]=a;
}
}
}
memcpy(bg,bg2,64000);
hfree(bg2);
if(scene0[15]=='C') city=1;
if(scene0[15]=='R') city=2;
ip=(int huge *)(scene0+LONGAT(scene0+4));
conum=d=*ip++;
for(f=-1,c=1;c<d;c++)
{
e=*ip++;
if(e>f)
{
f=e;
sprintf(tmpname,"%s.%03i",scene,e);
if(!indemo) printf("Loading %s... ",tmpname);
co[c].o=vis_loadobject(tmpname);
memset(co[c].o->r,0,sizeof(rmatrix));
memset(co[c].o->r0,0,sizeof(rmatrix));
co[c].index=e;
co[c].on=0;
if(!indemo) printf("(co[%i]:%s)\n",c,co[c].o->name);
}
else
{
if(!indemo) printf("Copying %s.%03i... ",scene,e);
for(g=0;g<c;g++) if(co[g].index==e) break;
memcpy(co+c,co+g,sizeof(struct s_co));
co[c].o=getmem(sizeof(object));
memcpy(co[c].o,co[g].o,sizeof(object));
co[c].o->r=getmem(sizeof(rmatrix));
co[c].o->r0=getmem(sizeof(rmatrix));
memset(co[c].o->r,0,sizeof(rmatrix));
memset(co[c].o->r0,0,sizeof(rmatrix));
co[c].on=0;
if(!indemo) printf("(co[%i]:%s)\n",c,co[c].o->name);
}
}
co[0].o=&camobject;
camobject.r=&cam;
camobject.r0=&cam;
sprintf(tmpname,"%s.0AA",scene);
if(!indemo) printf("Loading animations...\n",tmpname);
ip=readfile(tmpname);
while(*ip)
{
a=*ip;
if(a==-1) break;
sprintf(tmpname,"%s.0%c%c",scene,a/10+'A',a%10+'A');
if(!indemo) printf("Scene: %s ",tmpname);
scenelist[scl].data=readfile(tmpname);
printf("(%i:@%Fp)\n",scl,scenelist[scl].data);
scl++;
ip+=2;
}
if(!indemo)
{
printf("Press any key to continue...");
getch();
}
resetscene();
for(;;)
{
_asm
{
mov bx,6
int 0fch
mov a,cx
mov b,bx
}
if(a>10 && b>46) break;
}
vid_init(3); ////// oversample x 4
cp=(char *)(scenem+16);
vid_setpal(cp);
vid_window(0L,319L,25L,174L,512L,9999999L);
dis_setcopper(0,copper2);
dis_partstart();
xit=0;
coppercnt=0;
syncframe=0;
avgrepeat=1;
cl[0].ready=0;
cl[1].ready=0;
cl[2].ready=0;
cl[3].ready=1;
while(!dis_exit() && !xit)
{
int fov;
int onum;
long pflag;
long dis;
long l;
object *o;
rmatrix *r;
_asm
{
mov bx,6
int 0fch
mov a,cx
mov b,bx
}
if(a>11 && b>54) break;
if(cl[clw].ready) avgrepeat--;
if(!cl[(clw+1)&3].ready) avgrepeat++;
if(avgrepeat<1) avgrepeat=1;
if(avgrepeat>8) avgrepeat=8;
deadlock=a=0;
while(cl[clw].ready)
{
if(deadlock>16) break;
}
//repeat=(syncframe-currframe);
//avgrepeat=(repeat+avgrepeat)/2;
cldraw=-1;
vid_setswitch(cldraw=clw,-1);
vid_clearbg(bg);
a=(clw-1)&3;
cl[a].frames=avgrepeat;
cl[a].ready=1;
repeat=avgrepeat;
while(repeat-- && !xit)
{
currframe++;
// parse animation stream for 1 frame
onum=0;
while(!xit)
{
a=*sp++;
if(a==0xff)
{
a=*sp++;
if(a<=0x7f)
{
fov=a<<8;
break;
}
else if(a==0xff)
{
resetscene();
xit=1;
continue;
}
}
if((a&0xc0)==0xc0)
{
onum=((a&0x3f)<<4);
a=*sp++;
}
onum=(onum&0xff0)|(a&0xf);
b=0;
switch(a&0xc0)
{
case 0x80 : b=1; co[onum].on=1; break;
case 0x40 : b=1; co[onum].on=0; break;
}
#ifdef DEBUG
if(b) fprintf(fr,"[%i (%s) ",onum,co[onum].on?"on":"off");
else fprintf(fr,"[%i (--) ",onum,co[onum].on?"on":"off");
#endif
if(onum>=conum)
{
return(3);
}
r=co[onum].o->r0;
pflag=0;
switch(a&0x30)
{
case 0x00 : break;
case 0x10 : pflag|=*sp++; break;
case 0x20 : pflag|=sp[0];
pflag|=(long)sp[1]<<8;
sp+=2; break;
case 0x30 : pflag|=sp[0];
pflag|=(long)sp[1]<<8;
pflag|=(long)sp[2]<<16;
sp+=3; break;
}
#ifdef DEBUG
fprintf(fr,"pfl:%06lX",pflag);
#endif
l=lsget(pflag);
r->x+=l;
l=lsget(pflag>>2);
r->y+=l;
l=lsget(pflag>>4);
r->z+=l;
#ifdef DEBUG
fprintf(fr," XYZ:(%li,%li,%li)",r->x,r->y,r->z);
#endif
if(pflag&0x40)
{ // word matrix
for(b=0;b<9;b++) if(pflag&(0x80<<b))
{
r->m[b]+=lsget(2);
}
}
else
{ // byte matrix
for(b=0;b<9;b++) if(pflag&(0x80<<b))
{
r->m[b]+=lsget(1);
}
}
#ifdef DEBUG
fprintf(fr,"]\n");
#endif
}
}
// Field of vision
vid_cameraangle(fov);
// Calc matrices and add to order list (only enabled objects)
ordernum=0;
/* start at 1 to skip camera */
for(a=1;a<conum;a++) if(co[a].on)
{
order[ordernum++]=a;
o=co[a].o;
memcpy(o->r,o->r0,sizeof(rmatrix));
calc_applyrmatrix(o->r,&cam);
b=o->pl[0][1]; // center vertex
co[a].dist=calc_singlez(b,o->v0,o->r);
}
// Zsort
if(city==1)
{
co[2].dist=1000000000L; // for CITY scene, test
co[7].dist=1000000000L; // for CITY scene, test
co[13].dist=1000000000L; // for CITY scene, test
}
if(city==2)
{
co[14].dist=1000000000L; // for CITY scene, test
}
for(a=0;a<ordernum;a++)
{
dis=co[c=order[a]].dist;
for(b=a-1;b>=0 && dis>co[order[b]].dist;b--)
order[b+1]=order[b];
order[b+1]=c;
}
// Draw
for(a=0;a<ordernum;a++)
{
int x,y;
o=co[order[a]].o;
#ifdef DEBUG
fprintf(fr,"%s (i:%i Z:%li)\n",o->name,order[a],co[order[a]].dist);
#endif
vis_drawobject(o);
}
#ifdef DEBUG
fprintf(fr,"\n");
#endif
cl[clw].ready=3;
clw++; clw&=3;
}
dis_setcopper(0,NULL);
vid_setswitch(0,-1);
vid_clearbg(bg);
vid_setswitch(1,-1);
vid_clearbg(bg);
vid_setswitch(2,-1);
vid_clearbg(bg);
vid_setswitch(3,-1);
vid_clearbg(bg);
if(!dis_indemo())
{
vid_deinit();
}
#ifdef DEBUG
fclose(fr);
#endif
return(0);
}
//////////////////////////////////////////////////////////////////////////////
void *getmem(long size)
{
void *p;
if(size>160000L)
{
printf("GETMEM: attempting to reserved >160K (%li byte block)\n",size);
exit(3);
}
p=halloc(size/16L+1,16);
if(!p)
{
printf("GETMEM: out of memory (%li byte block)\n",size);
exit(3);
}
return(p);
}
void freemem(void *p)
{
hfree(p);
}
char *readfile(char *name)
{
FILE *f1;
long size;
char huge *p,*p0;
f1=fopen(name,"rb");
if(!f1)
{
printf("File '%s' not found.",name);
exit(3);
}
fseek(f1,0L,SEEK_END);
p0=p=getmem(size=ftell(f1));
fseek(f1,0L,SEEK_SET);
if(size>128000)
{
fread(p,64000,1,f1);
size-=64000;
_asm add word ptr p[2],4000
fread(p,64000,1,f1);
size-=64000;
_asm add word ptr p[2],4000
fread(p,(size_t)size,1,f1);
}
else if(size>64000)
{
fread(p,64000,1,f1);
size-=64000;
_asm
{
add word ptr p[2],4000
}
fread(p,(size_t)size,1,f1);
}
else fread(p,(size_t)size,1,f1);
fclose(f1);
return(p0);
}
| 412 | 0.797869 | 1 | 0.797869 | game-dev | MEDIA | 0.345579 | game-dev | 0.910728 | 1 | 0.910728 |
powsybl/powsybl-diagram | 1,895 | single-line-diagram/single-line-diagram-core/src/main/java/com/powsybl/sld/layout/LayoutContext.java | /**
* Copyright (c) 2022, RTE (http://www.rte-france.com)
* 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/.
*/
package com.powsybl.sld.layout;
import com.powsybl.sld.model.coordinate.Direction;
/**
* @author Benoit Jeanson {@literal <benoit.jeanson at rte-france.com>}
*/
public final class LayoutContext {
private final double firstBusY;
private final double lastBusY;
private final double maxInternCellHeight;
private final Direction direction;
private final boolean isInternCell;
private final boolean isFlat;
private final boolean isUnileg;
public LayoutContext(double firstBusY, double lastBusY, double maxInternCellHeight, Direction direction,
boolean isInternCell, boolean isFlat, boolean isUnileg) {
this.firstBusY = firstBusY;
this.lastBusY = lastBusY;
this.maxInternCellHeight = maxInternCellHeight;
this.direction = direction;
this.isInternCell = isInternCell;
this.isFlat = isFlat;
this.isUnileg = isUnileg;
}
public LayoutContext(double firstBusY, double lastBusY, double maxInternCellHeight, Direction direction) {
this(firstBusY, lastBusY, maxInternCellHeight, direction, false, false, false);
}
public double getFirstBusY() {
return firstBusY;
}
public double getLastBusY() {
return lastBusY;
}
public double getMaxInternCellHeight() {
return maxInternCellHeight;
}
public Direction getDirection() {
return direction;
}
public boolean isInternCell() {
return isInternCell;
}
public boolean isFlat() {
return isFlat;
}
public boolean isUnileg() {
return isUnileg;
}
}
| 412 | 0.571683 | 1 | 0.571683 | game-dev | MEDIA | 0.473387 | game-dev | 0.905503 | 1 | 0.905503 |
modernuo/ModernUO | 1,874 | Projects/UOContent/Spells/Gargoyle/SpellDefinitions/FlySpell.cs | using System;
using Server.Engines.BuffIcons;
using Server.Mobiles;
namespace Server.Spells
{
public class FlySpell : Spell
{
private static readonly SpellInfo _info = new("Gargoyle Flight", null, -1, 9002);
private bool m_Stop;
public FlySpell(Mobile caster) : base(caster, null, _info)
{
}
public override bool ClearHandsOnCast => false;
public override bool RevealOnCast => false;
public override double CastDelayFastScalar => 0;
public override TimeSpan CastDelayBase => TimeSpan.FromSeconds(.25);
public override TimeSpan GetCastRecovery() => TimeSpan.Zero;
public override int GetMana() => 0;
public override bool ConsumeReagents() => true;
public override bool CheckFizzle() => true;
public void Stop()
{
m_Stop = true;
Disturb(DisturbType.Hurt, false);
}
public override bool CheckDisturb(DisturbType type, bool checkFirst, bool resistable) =>
type != DisturbType.EquipRequest && type != DisturbType.UseRequest;
public override void DoHurtFizzle()
{
}
public override void DoFizzle()
{
}
public override void OnDisturb(DisturbType type, bool message)
{
if (message && !m_Stop)
{
Caster.SendLocalizedMessage(1113192); // You have been disrupted while attempting to fly!
}
}
public override void OnCast()
{
Caster.Flying = false;
Caster.Animate(60, 10, 1, true, false, 0);
Caster.SendLocalizedMessage(1112567); // You are flying.
Caster.Flying = true;
(Caster as PlayerMobile)?.AddBuff(new BuffInfo(BuffIcon.Fly, 1112567));
FinishSequence();
}
}
}
| 412 | 0.901047 | 1 | 0.901047 | game-dev | MEDIA | 0.783559 | game-dev | 0.941838 | 1 | 0.941838 |
ViaVersion/ViaFabricPlus | 3,063 | src/main/java/com/viaversion/viafabricplus/injection/mixin/features/bedrock/reach_around_raycast/MixinGameRenderer.java | /*
* This file is part of ViaFabricPlus - https://github.com/ViaVersion/ViaFabricPlus
* Copyright (C) 2021-2025 the original authors
* - FlorianMichael/EnZaXD <florian.michael07@gmail.com>
* - RK_01/RaphiMC
* Copyright (C) 2023-2025 ViaVersion and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.viaversion.viafabricplus.injection.mixin.features.bedrock.reach_around_raycast;
import com.llamalad7.mixinextras.injector.ModifyExpressionValue;
import com.viaversion.viafabricplus.protocoltranslator.ProtocolTranslator;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.render.GameRenderer;
import net.minecraft.entity.Entity;
import net.minecraft.util.hit.BlockHitResult;
import net.minecraft.util.hit.HitResult;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.raphimc.viabedrock.api.BedrockProtocolVersion;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
@Mixin(GameRenderer.class)
public abstract class MixinGameRenderer {
@Shadow
@Final
private MinecraftClient client;
@ModifyExpressionValue(method = "findCrosshairTarget", at = @At(value = "INVOKE", target = "Lnet/minecraft/entity/Entity;raycast(DFZ)Lnet/minecraft/util/hit/HitResult;"))
private HitResult bedrockReachAroundRaycast(HitResult hitResult) {
if (ProtocolTranslator.getTargetVersion().equals(BedrockProtocolVersion.bedrockLatest)) {
final Entity entity = this.client.getCameraEntity();
if (hitResult.getType() != HitResult.Type.MISS) return hitResult;
if (!this.viaFabricPlus$canReachAround(entity)) return hitResult;
final int x = MathHelper.floor(entity.getX());
final int y = MathHelper.floor(entity.getY() - 0.2F);
final int z = MathHelper.floor(entity.getZ());
final BlockPos floorPos = new BlockPos(x, y, z);
return new BlockHitResult(floorPos.toCenterPos(), entity.getHorizontalFacing(), floorPos, false);
}
return hitResult;
}
@Unique
private boolean viaFabricPlus$canReachAround(final Entity entity) {
return entity.isOnGround() && entity.getVehicle() == null && entity.getPitch() >= 45;
}
}
| 412 | 0.845668 | 1 | 0.845668 | game-dev | MEDIA | 0.943862 | game-dev | 0.904673 | 1 | 0.904673 |
emileb/OpenGames | 36,326 | opengames/src/main/jni/OpenJK/codemp/botlib/be_aas_move.cpp |
/*****************************************************************************
* name: be_aas_move.c
*
* desc: AAS
*
* $Archive: /MissionPack/code/botlib/be_aas_move.c $
* $Author: Ttimo $
* $Revision: 9 $
* $Modtime: 4/13/01 4:45p $
* $Date: 4/13/01 4:45p $
*
*****************************************************************************/
#include "qcommon/q_shared.h"
#include "l_memory.h"
#include "l_script.h"
#include "l_precomp.h"
#include "l_struct.h"
#include "l_libvar.h"
#include "aasfile.h"
#include "botlib.h"
#include "be_aas.h"
#include "be_aas_funcs.h"
#include "be_aas_def.h"
extern botlib_import_t botimport;
aas_settings_t aassettings;
//#define AAS_MOVE_DEBUG
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
int AAS_DropToFloor(vec3_t origin, vec3_t mins, vec3_t maxs)
{
vec3_t end;
bsp_trace_t trace;
VectorCopy(origin, end);
end[2] -= 100;
trace = AAS_Trace(origin, mins, maxs, end, 0, CONTENTS_SOLID);
if (trace.startsolid) return qfalse;
VectorCopy(trace.endpos, origin);
return qtrue;
} //end of the function AAS_DropToFloor
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
void AAS_InitSettings(void)
{
aassettings.phys_gravitydirection[0] = 0;
aassettings.phys_gravitydirection[1] = 0;
aassettings.phys_gravitydirection[2] = -1;
aassettings.phys_friction = LibVarValue("phys_friction", "6");
aassettings.phys_stopspeed = LibVarValue("phys_stopspeed", "100");
aassettings.phys_gravity = LibVarValue("phys_gravity", "800");
aassettings.phys_waterfriction = LibVarValue("phys_waterfriction", "1");
aassettings.phys_watergravity = LibVarValue("phys_watergravity", "400");
aassettings.phys_maxvelocity = LibVarValue("phys_maxvelocity", "320");
aassettings.phys_maxwalkvelocity = LibVarValue("phys_maxwalkvelocity", "320");
aassettings.phys_maxcrouchvelocity = LibVarValue("phys_maxcrouchvelocity", "100");
aassettings.phys_maxswimvelocity = LibVarValue("phys_maxswimvelocity", "150");
aassettings.phys_walkaccelerate = LibVarValue("phys_walkaccelerate", "10");
aassettings.phys_airaccelerate = LibVarValue("phys_airaccelerate", "1");
aassettings.phys_swimaccelerate = LibVarValue("phys_swimaccelerate", "4");
aassettings.phys_maxstep = LibVarValue("phys_maxstep", "19");
aassettings.phys_maxsteepness = LibVarValue("phys_maxsteepness", "0.7");
aassettings.phys_maxwaterjump = LibVarValue("phys_maxwaterjump", "18");
aassettings.phys_maxbarrier = LibVarValue("phys_maxbarrier", "33");
aassettings.phys_jumpvel = LibVarValue("phys_jumpvel", "270");
aassettings.phys_falldelta5 = LibVarValue("phys_falldelta5", "40");
aassettings.phys_falldelta10 = LibVarValue("phys_falldelta10", "60");
aassettings.rs_waterjump = LibVarValue("rs_waterjump", "400");
aassettings.rs_teleport = LibVarValue("rs_teleport", "50");
aassettings.rs_barrierjump = LibVarValue("rs_barrierjump", "100");
aassettings.rs_startcrouch = LibVarValue("rs_startcrouch", "300");
aassettings.rs_startgrapple = LibVarValue("rs_startgrapple", "500");
aassettings.rs_startwalkoffledge = LibVarValue("rs_startwalkoffledge", "70");
aassettings.rs_startjump = LibVarValue("rs_startjump", "300");
aassettings.rs_rocketjump = LibVarValue("rs_rocketjump", "500");
aassettings.rs_bfgjump = LibVarValue("rs_bfgjump", "500");
aassettings.rs_jumppad = LibVarValue("rs_jumppad", "250");
aassettings.rs_aircontrolledjumppad = LibVarValue("rs_aircontrolledjumppad", "300");
aassettings.rs_funcbob = LibVarValue("rs_funcbob", "300");
aassettings.rs_startelevator = LibVarValue("rs_startelevator", "50");
aassettings.rs_falldamage5 = LibVarValue("rs_falldamage5", "300");
aassettings.rs_falldamage10 = LibVarValue("rs_falldamage10", "500");
aassettings.rs_maxfallheight = LibVarValue("rs_maxfallheight", "0");
aassettings.rs_maxjumpfallheight = LibVarValue("rs_maxjumpfallheight", "450");
} //end of the function AAS_InitSettings
//===========================================================================
// returns qtrue if the bot is against a ladder
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
int AAS_AgainstLadder(vec3_t origin)
{
int areanum, i, facenum, side;
vec3_t org;
aas_plane_t *plane;
aas_face_t *face;
aas_area_t *area;
VectorCopy(origin, org);
areanum = AAS_PointAreaNum(org);
if (!areanum)
{
org[0] += 1;
areanum = AAS_PointAreaNum(org);
if (!areanum)
{
org[1] += 1;
areanum = AAS_PointAreaNum(org);
if (!areanum)
{
org[0] -= 2;
areanum = AAS_PointAreaNum(org);
if (!areanum)
{
org[1] -= 2;
areanum = AAS_PointAreaNum(org);
} //end if
} //end if
} //end if
} //end if
//if in solid... wrrr shouldn't happen
if (!areanum) return qfalse;
//if not in a ladder area
if (!(aasworld.areasettings[areanum].areaflags & AREA_LADDER)) return qfalse;
//if a crouch only area
if (!(aasworld.areasettings[areanum].presencetype & PRESENCE_NORMAL)) return qfalse;
//
area = &aasworld.areas[areanum];
for (i = 0; i < area->numfaces; i++)
{
facenum = aasworld.faceindex[area->firstface + i];
side = facenum < 0;
face = &aasworld.faces[abs(facenum)];
//if the face isn't a ladder face
if (!(face->faceflags & FACE_LADDER)) continue;
//get the plane the face is in
plane = &aasworld.planes[face->planenum ^ side];
//if the origin is pretty close to the plane
if (abs(DotProduct(plane->normal, origin) - plane->dist) < 3)
{
if (AAS_PointInsideFace(abs(facenum), origin, 0.1f)) return qtrue;
} //end if
} //end for
return qfalse;
} //end of the function AAS_AgainstLadder
//===========================================================================
// returns qtrue if the bot is on the ground
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
int AAS_OnGround(vec3_t origin, int presencetype, int passent)
{
aas_trace_t trace;
vec3_t end, up = {0, 0, 1};
aas_plane_t *plane;
VectorCopy(origin, end);
end[2] -= 10;
trace = AAS_TraceClientBBox(origin, end, presencetype, passent);
//if in solid
if (trace.startsolid) return qfalse;
//if nothing hit at all
if (trace.fraction >= 1.0) return qfalse;
//if too far from the hit plane
if (origin[2] - trace.endpos[2] > 10) return qfalse;
//check if the plane isn't too steep
plane = AAS_PlaneFromNum(trace.planenum);
if (DotProduct(plane->normal, up) < aassettings.phys_maxsteepness) return qfalse;
//the bot is on the ground
return qtrue;
} //end of the function AAS_OnGround
//===========================================================================
// returns qtrue if a bot at the given position is swimming
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
int AAS_Swimming(vec3_t origin)
{
vec3_t testorg;
VectorCopy(origin, testorg);
testorg[2] -= 2;
if (AAS_PointContents(testorg) & (CONTENTS_LAVA|CONTENTS_SLIME|CONTENTS_WATER)) return qtrue;
return qfalse;
} //end of the function AAS_Swimming
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
static vec3_t VEC_UP = {0, -1, 0};
static vec3_t MOVEDIR_UP = {0, 0, 1};
static vec3_t VEC_DOWN = {0, -2, 0};
static vec3_t MOVEDIR_DOWN = {0, 0, -1};
void AAS_SetMovedir(vec3_t angles, vec3_t movedir)
{
if (VectorCompare(angles, VEC_UP))
{
VectorCopy(MOVEDIR_UP, movedir);
} //end if
else if (VectorCompare(angles, VEC_DOWN))
{
VectorCopy(MOVEDIR_DOWN, movedir);
} //end else if
else
{
AngleVectors(angles, movedir, NULL, NULL);
} //end else
} //end of the function AAS_SetMovedir
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
void AAS_JumpReachRunStart(aas_reachability_t *reach, vec3_t runstart)
{
vec3_t hordir, start, cmdmove;
aas_clientmove_t move;
//
hordir[0] = reach->start[0] - reach->end[0];
hordir[1] = reach->start[1] - reach->end[1];
hordir[2] = 0;
VectorNormalize(hordir);
//start point
VectorCopy(reach->start, start);
start[2] += 1;
//get command movement
VectorScale(hordir, 400, cmdmove);
//
AAS_PredictClientMovement(&move, -1, start, PRESENCE_NORMAL, qtrue,
vec3_origin, cmdmove, 1, 2, 0.1f,
SE_ENTERWATER|SE_ENTERSLIME|SE_ENTERLAVA|
SE_HITGROUNDDAMAGE|SE_GAP, 0, qfalse);
VectorCopy(move.endpos, runstart);
//don't enter slime or lava and don't fall from too high
if (move.stopevent & (SE_ENTERSLIME|SE_ENTERLAVA|SE_HITGROUNDDAMAGE))
{
VectorCopy(start, runstart);
} //end if
} //end of the function AAS_JumpReachRunStart
//===========================================================================
// returns the Z velocity when rocket jumping at the origin
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
float AAS_WeaponJumpZVelocity(vec3_t origin, float radiusdamage)
{
vec3_t kvel, v, start, end, forward, right, viewangles, dir;
float mass, knockback, points;
vec3_t rocketoffset = {8, 8, -8};
vec3_t botmins = {-16, -16, -24};
vec3_t botmaxs = {16, 16, 32};
bsp_trace_t bsptrace;
//look down (90 degrees)
viewangles[PITCH] = 90;
viewangles[YAW] = 0;
viewangles[ROLL] = 0;
//get the start point shooting from
VectorCopy(origin, start);
start[2] += 8; //view offset Z
AngleVectors(viewangles, forward, right, NULL);
start[0] += forward[0] * rocketoffset[0] + right[0] * rocketoffset[1];
start[1] += forward[1] * rocketoffset[0] + right[1] * rocketoffset[1];
start[2] += forward[2] * rocketoffset[0] + right[2] * rocketoffset[1] + rocketoffset[2];
//end point of the trace
VectorMA(start, 500, forward, end);
//trace a line to get the impact point
bsptrace = AAS_Trace(start, NULL, NULL, end, 1, CONTENTS_SOLID);
//calculate the damage the bot will get from the rocket impact
VectorAdd(botmins, botmaxs, v);
VectorMA(origin, 0.5, v, v);
VectorSubtract(bsptrace.endpos, v, v);
//
points = radiusdamage - 0.5 * VectorLength(v);
if (points < 0) points = 0;
//the owner of the rocket gets half the damage
points *= 0.5;
//mass of the bot (p_client.c: PutClientInServer)
mass = 200;
//knockback is the same as the damage points
knockback = points;
//direction of the damage (from trace.endpos to bot origin)
VectorSubtract(origin, bsptrace.endpos, dir);
VectorNormalize(dir);
//damage velocity
VectorScale(dir, 1600.0 * (float)knockback / mass, kvel); //the rocket jump hack...
//rocket impact velocity + jump velocity
return kvel[2] + aassettings.phys_jumpvel;
} //end of the function AAS_WeaponJumpZVelocity
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
float AAS_RocketJumpZVelocity(vec3_t origin)
{
//rocket radius damage is 120 (p_weapon.c: Weapon_RocketLauncher_Fire)
return AAS_WeaponJumpZVelocity(origin, 120);
} //end of the function AAS_RocketJumpZVelocity
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
float AAS_BFGJumpZVelocity(vec3_t origin)
{
//bfg radius damage is 1000 (p_weapon.c: weapon_bfg_fire)
return AAS_WeaponJumpZVelocity(origin, 120);
} //end of the function AAS_BFGJumpZVelocity
//===========================================================================
// applies ground friction to the given velocity
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
void AAS_Accelerate(vec3_t velocity, float frametime, vec3_t wishdir, float wishspeed, float accel)
{
// q2 style
int i;
float addspeed, accelspeed, currentspeed;
currentspeed = DotProduct(velocity, wishdir);
addspeed = wishspeed - currentspeed;
if (addspeed <= 0) {
return;
}
accelspeed = accel*frametime*wishspeed;
if (accelspeed > addspeed) {
accelspeed = addspeed;
}
for (i=0 ; i<3 ; i++) {
velocity[i] += accelspeed*wishdir[i];
}
} //end of the function AAS_Accelerate
//===========================================================================
// applies ground friction to the given velocity
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
void AAS_ApplyFriction(vec3_t vel, float friction, float stopspeed,
float frametime)
{
float speed, control, newspeed;
//horizontal speed
speed = sqrt(vel[0] * vel[0] + vel[1] * vel[1]);
if (speed)
{
control = speed < stopspeed ? stopspeed : speed;
newspeed = speed - frametime * control * friction;
if (newspeed < 0) newspeed = 0;
newspeed /= speed;
vel[0] *= newspeed;
vel[1] *= newspeed;
} //end if
} //end of the function AAS_ApplyFriction
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
int AAS_ClipToBBox(aas_trace_t *trace, vec3_t start, vec3_t end, int presencetype, vec3_t mins, vec3_t maxs)
{
int i, j, side;
float front, back, frac, planedist;
vec3_t bboxmins, bboxmaxs, absmins, absmaxs, dir, mid;
AAS_PresenceTypeBoundingBox(presencetype, bboxmins, bboxmaxs);
VectorSubtract(mins, bboxmaxs, absmins);
VectorSubtract(maxs, bboxmins, absmaxs);
//
VectorCopy(end, trace->endpos);
trace->fraction = 1;
for (i = 0; i < 3; i++)
{
if (start[i] < absmins[i] && end[i] < absmins[i]) return qfalse;
if (start[i] > absmaxs[i] && end[i] > absmaxs[i]) return qfalse;
} //end for
//check bounding box collision
VectorSubtract(end, start, dir);
frac = 1;
for (i = 0; i < 3; i++)
{
//get plane to test collision with for the current axis direction
if (dir[i] > 0) planedist = absmins[i];
else planedist = absmaxs[i];
//calculate collision fraction
front = start[i] - planedist;
back = end[i] - planedist;
frac = front / (front-back);
//check if between bounding planes of next axis
side = i + 1;
if (side > 2) side = 0;
mid[side] = start[side] + dir[side] * frac;
if (mid[side] > absmins[side] && mid[side] < absmaxs[side])
{
//check if between bounding planes of next axis
side++;
if (side > 2) side = 0;
mid[side] = start[side] + dir[side] * frac;
if (mid[side] > absmins[side] && mid[side] < absmaxs[side])
{
mid[i] = planedist;
break;
} //end if
} //end if
} //end for
//if there was a collision
if (i != 3)
{
trace->startsolid = qfalse;
trace->fraction = frac;
trace->ent = 0;
trace->planenum = 0;
trace->area = 0;
trace->lastarea = 0;
//trace endpos
for (j = 0; j < 3; j++) trace->endpos[j] = start[j] + dir[j] * frac;
return qtrue;
} //end if
return qfalse;
} //end of the function AAS_ClipToBBox
//===========================================================================
// predicts the movement
// assumes regular bounding box sizes
// NOTE: out of water jumping is not included
// NOTE: grappling hook is not included
//
// Parameter: origin : origin to start with
// presencetype : presence type to start with
// velocity : velocity to start with
// cmdmove : client command movement
// cmdframes : number of frame cmdmove is valid
// maxframes : maximum number of predicted frames
// frametime : duration of one predicted frame
// stopevent : events that stop the prediction
// stopareanum : stop as soon as entered this area
// Returns: aas_clientmove_t
// Changes Globals: -
//===========================================================================
int AAS_ClientMovementPrediction(struct aas_clientmove_s *move,
int entnum, vec3_t origin,
int presencetype, int onground,
vec3_t velocity, vec3_t cmdmove,
int cmdframes,
int maxframes, float frametime,
int stopevent, int stopareanum,
vec3_t mins, vec3_t maxs, int visualize)
{
float phys_friction, phys_stopspeed, phys_gravity, phys_waterfriction;
float phys_watergravity;
float phys_walkaccelerate, phys_airaccelerate, phys_swimaccelerate;
float phys_maxwalkvelocity, phys_maxcrouchvelocity, phys_maxswimvelocity;
float phys_maxstep, phys_maxsteepness, phys_jumpvel, friction;
float gravity, delta, maxvel, wishspeed, accelerate;
//float velchange, newvel;
//int ax;
int n, i, j, pc, step, swimming, crouch, event, jump_frame, areanum;
int areas[20], numareas;
vec3_t points[20];
vec3_t org, end, feet, start, stepend, lastorg, wishdir;
vec3_t frame_test_vel, old_frame_test_vel, left_test_vel;
vec3_t up = {0, 0, 1};
aas_plane_t *plane, *plane2;
aas_trace_t trace, steptrace;
if (frametime <= 0) frametime = 0.1f;
//
phys_friction = aassettings.phys_friction;
phys_stopspeed = aassettings.phys_stopspeed;
phys_gravity = aassettings.phys_gravity;
phys_waterfriction = aassettings.phys_waterfriction;
phys_watergravity = aassettings.phys_watergravity;
phys_maxwalkvelocity = aassettings.phys_maxwalkvelocity;// * frametime;
phys_maxcrouchvelocity = aassettings.phys_maxcrouchvelocity;// * frametime;
phys_maxswimvelocity = aassettings.phys_maxswimvelocity;// * frametime;
phys_walkaccelerate = aassettings.phys_walkaccelerate;
phys_airaccelerate = aassettings.phys_airaccelerate;
phys_swimaccelerate = aassettings.phys_swimaccelerate;
phys_maxstep = aassettings.phys_maxstep;
phys_maxsteepness = aassettings.phys_maxsteepness;
phys_jumpvel = aassettings.phys_jumpvel * frametime;
//
Com_Memset(move, 0, sizeof(aas_clientmove_t));
Com_Memset(&trace, 0, sizeof(aas_trace_t));
//start at the current origin
VectorCopy(origin, org);
org[2] += 0.25;
//velocity to test for the first frame
VectorScale(velocity, frametime, frame_test_vel);
//
jump_frame = -1;
//predict a maximum of 'maxframes' ahead
for (n = 0; n < maxframes; n++)
{
swimming = AAS_Swimming(org);
//get gravity depending on swimming or not
gravity = swimming ? phys_watergravity : phys_gravity;
//apply gravity at the START of the frame
frame_test_vel[2] = frame_test_vel[2] - (gravity * 0.1 * frametime);
//if on the ground or swimming
if (onground || swimming)
{
friction = swimming ? phys_friction : phys_waterfriction;
//apply friction
VectorScale(frame_test_vel, 1/frametime, frame_test_vel);
AAS_ApplyFriction(frame_test_vel, friction, phys_stopspeed, frametime);
VectorScale(frame_test_vel, frametime, frame_test_vel);
} //end if
crouch = qfalse;
//apply command movement
if (n < cmdframes)
{
//ax = 0;
maxvel = phys_maxwalkvelocity;
accelerate = phys_airaccelerate;
VectorCopy(cmdmove, wishdir);
if (onground)
{
if (cmdmove[2] < -300)
{
crouch = qtrue;
maxvel = phys_maxcrouchvelocity;
} //end if
//if not swimming and upmove is positive then jump
if (!swimming && cmdmove[2] > 1)
{
//jump velocity minus the gravity for one frame + 5 for safety
frame_test_vel[2] = phys_jumpvel - (gravity * 0.1 * frametime) + 5;
jump_frame = n;
//jumping so air accelerate
accelerate = phys_airaccelerate;
} //end if
else
{
accelerate = phys_walkaccelerate;
} //end else
//ax = 2;
} //end if
if (swimming)
{
maxvel = phys_maxswimvelocity;
accelerate = phys_swimaccelerate;
//ax = 3;
} //end if
else
{
wishdir[2] = 0;
} //end else
//
wishspeed = VectorNormalize(wishdir);
if (wishspeed > maxvel) wishspeed = maxvel;
VectorScale(frame_test_vel, 1/frametime, frame_test_vel);
AAS_Accelerate(frame_test_vel, frametime, wishdir, wishspeed, accelerate);
VectorScale(frame_test_vel, frametime, frame_test_vel);
/*
for (i = 0; i < ax; i++)
{
velchange = (cmdmove[i] * frametime) - frame_test_vel[i];
if (velchange > phys_maxacceleration) velchange = phys_maxacceleration;
else if (velchange < -phys_maxacceleration) velchange = -phys_maxacceleration;
newvel = frame_test_vel[i] + velchange;
//
if (frame_test_vel[i] <= maxvel && newvel > maxvel) frame_test_vel[i] = maxvel;
else if (frame_test_vel[i] >= -maxvel && newvel < -maxvel) frame_test_vel[i] = -maxvel;
else frame_test_vel[i] = newvel;
} //end for
*/
} //end if
if (crouch)
{
presencetype = PRESENCE_CROUCH;
} //end if
else if (presencetype == PRESENCE_CROUCH)
{
if (AAS_PointPresenceType(org) & PRESENCE_NORMAL)
{
presencetype = PRESENCE_NORMAL;
} //end if
} //end else
//save the current origin
VectorCopy(org, lastorg);
//move linear during one frame
VectorCopy(frame_test_vel, left_test_vel);
j = 0;
do
{
VectorAdd(org, left_test_vel, end);
//trace a bounding box
trace = AAS_TraceClientBBox(org, end, presencetype, entnum);
//
//#ifdef AAS_MOVE_DEBUG
if (visualize)
{
if (trace.startsolid) botimport.Print(PRT_MESSAGE, "PredictMovement: start solid\n");
AAS_DebugLine(org, trace.endpos, LINECOLOR_RED);
} //end if
//#endif //AAS_MOVE_DEBUG
//
if (stopevent & (SE_ENTERAREA|SE_TOUCHJUMPPAD|SE_TOUCHTELEPORTER|SE_TOUCHCLUSTERPORTAL))
{
numareas = AAS_TraceAreas(org, trace.endpos, areas, points, 20);
for (i = 0; i < numareas; i++)
{
if (stopevent & SE_ENTERAREA)
{
if (areas[i] == stopareanum)
{
VectorCopy(points[i], move->endpos);
VectorScale(frame_test_vel, 1/frametime, move->velocity);
move->endarea = areas[i];
move->trace = trace;
move->stopevent = SE_ENTERAREA;
move->presencetype = presencetype;
move->endcontents = 0;
move->time = n * frametime;
move->frames = n;
return qtrue;
} //end if
} //end if
//NOTE: if not the first frame
if ((stopevent & SE_TOUCHJUMPPAD) && n)
{
if (aasworld.areasettings[areas[i]].contents & AREACONTENTS_JUMPPAD)
{
VectorCopy(points[i], move->endpos);
VectorScale(frame_test_vel, 1/frametime, move->velocity);
move->endarea = areas[i];
move->trace = trace;
move->stopevent = SE_TOUCHJUMPPAD;
move->presencetype = presencetype;
move->endcontents = 0;
move->time = n * frametime;
move->frames = n;
return qtrue;
} //end if
} //end if
if (stopevent & SE_TOUCHTELEPORTER)
{
if (aasworld.areasettings[areas[i]].contents & AREACONTENTS_TELEPORTER)
{
VectorCopy(points[i], move->endpos);
move->endarea = areas[i];
VectorScale(frame_test_vel, 1/frametime, move->velocity);
move->trace = trace;
move->stopevent = SE_TOUCHTELEPORTER;
move->presencetype = presencetype;
move->endcontents = 0;
move->time = n * frametime;
move->frames = n;
return qtrue;
} //end if
} //end if
if (stopevent & SE_TOUCHCLUSTERPORTAL)
{
if (aasworld.areasettings[areas[i]].contents & AREACONTENTS_CLUSTERPORTAL)
{
VectorCopy(points[i], move->endpos);
move->endarea = areas[i];
VectorScale(frame_test_vel, 1/frametime, move->velocity);
move->trace = trace;
move->stopevent = SE_TOUCHCLUSTERPORTAL;
move->presencetype = presencetype;
move->endcontents = 0;
move->time = n * frametime;
move->frames = n;
return qtrue;
} //end if
} //end if
} //end for
} //end if
//
if (stopevent & SE_HITBOUNDINGBOX)
{
if (AAS_ClipToBBox(&trace, org, trace.endpos, presencetype, mins, maxs))
{
VectorCopy(trace.endpos, move->endpos);
move->endarea = AAS_PointAreaNum(move->endpos);
VectorScale(frame_test_vel, 1/frametime, move->velocity);
move->trace = trace;
move->stopevent = SE_HITBOUNDINGBOX;
move->presencetype = presencetype;
move->endcontents = 0;
move->time = n * frametime;
move->frames = n;
return qtrue;
} //end if
} //end if
//move the entity to the trace end point
VectorCopy(trace.endpos, org);
//if there was a collision
if (trace.fraction < 1.0)
{
//get the plane the bounding box collided with
plane = AAS_PlaneFromNum(trace.planenum);
//
if (stopevent & SE_HITGROUNDAREA)
{
if (DotProduct(plane->normal, up) > phys_maxsteepness)
{
VectorCopy(org, start);
start[2] += 0.5;
if (AAS_PointAreaNum(start) == stopareanum)
{
VectorCopy(start, move->endpos);
move->endarea = stopareanum;
VectorScale(frame_test_vel, 1/frametime, move->velocity);
move->trace = trace;
move->stopevent = SE_HITGROUNDAREA;
move->presencetype = presencetype;
move->endcontents = 0;
move->time = n * frametime;
move->frames = n;
return qtrue;
} //end if
} //end if
} //end if
//assume there's no step
step = qfalse;
//if it is a vertical plane and the bot didn't jump recently
if (plane->normal[2] == 0 && (jump_frame < 0 || n - jump_frame > 2))
{
//check for a step
VectorMA(org, -0.25, plane->normal, start);
VectorCopy(start, stepend);
start[2] += phys_maxstep;
steptrace = AAS_TraceClientBBox(start, stepend, presencetype, entnum);
//
if (!steptrace.startsolid)
{
plane2 = AAS_PlaneFromNum(steptrace.planenum);
if (DotProduct(plane2->normal, up) > phys_maxsteepness)
{
VectorSubtract(end, steptrace.endpos, left_test_vel);
left_test_vel[2] = 0;
frame_test_vel[2] = 0;
//#ifdef AAS_MOVE_DEBUG
if (visualize)
{
if (steptrace.endpos[2] - org[2] > 0.125)
{
VectorCopy(org, start);
start[2] = steptrace.endpos[2];
AAS_DebugLine(org, start, LINECOLOR_BLUE);
} //end if
} //end if
//#endif //AAS_MOVE_DEBUG
org[2] = steptrace.endpos[2];
step = qtrue;
} //end if
} //end if
} //end if
//
if (!step)
{
//velocity left to test for this frame is the projection
//of the current test velocity into the hit plane
VectorMA(left_test_vel, -DotProduct(left_test_vel, plane->normal),
plane->normal, left_test_vel);
//store the old velocity for landing check
VectorCopy(frame_test_vel, old_frame_test_vel);
//test velocity for the next frame is the projection
//of the velocity of the current frame into the hit plane
VectorMA(frame_test_vel, -DotProduct(frame_test_vel, plane->normal),
plane->normal, frame_test_vel);
//check for a landing on an almost horizontal floor
if (DotProduct(plane->normal, up) > phys_maxsteepness)
{
onground = qtrue;
} //end if
if (stopevent & SE_HITGROUNDDAMAGE)
{
delta = 0;
if (old_frame_test_vel[2] < 0 &&
frame_test_vel[2] > old_frame_test_vel[2] &&
!onground)
{
delta = old_frame_test_vel[2];
} //end if
else if (onground)
{
delta = frame_test_vel[2] - old_frame_test_vel[2];
} //end else
if (delta)
{
delta = delta * 10;
delta = delta * delta * 0.0001;
if (swimming) delta = 0;
// never take falling damage if completely underwater
/*
if (ent->waterlevel == 3) return;
if (ent->waterlevel == 2) delta *= 0.25;
if (ent->waterlevel == 1) delta *= 0.5;
*/
if (delta > 40)
{
VectorCopy(org, move->endpos);
move->endarea = AAS_PointAreaNum(org);
VectorCopy(frame_test_vel, move->velocity);
move->trace = trace;
move->stopevent = SE_HITGROUNDDAMAGE;
move->presencetype = presencetype;
move->endcontents = 0;
move->time = n * frametime;
move->frames = n;
return qtrue;
} //end if
} //end if
} //end if
} //end if
} //end if
//extra check to prevent endless loop
if (++j > 20) return qfalse;
//while there is a plane hit
} while(trace.fraction < 1.0);
//if going down
if (frame_test_vel[2] <= 10)
{
//check for a liquid at the feet of the bot
VectorCopy(org, feet);
feet[2] -= 22;
pc = AAS_PointContents(feet);
//get event from pc
event = SE_NONE;
if (pc & CONTENTS_LAVA) event |= SE_ENTERLAVA;
if (pc & CONTENTS_SLIME) event |= SE_ENTERSLIME;
if (pc & CONTENTS_WATER) event |= SE_ENTERWATER;
//
areanum = AAS_PointAreaNum(org);
if (aasworld.areasettings[areanum].contents & AREACONTENTS_LAVA)
event |= SE_ENTERLAVA;
if (aasworld.areasettings[areanum].contents & AREACONTENTS_SLIME)
event |= SE_ENTERSLIME;
if (aasworld.areasettings[areanum].contents & AREACONTENTS_WATER)
event |= SE_ENTERWATER;
//if in lava or slime
if (event & stopevent)
{
VectorCopy(org, move->endpos);
move->endarea = areanum;
VectorScale(frame_test_vel, 1/frametime, move->velocity);
move->stopevent = event & stopevent;
move->presencetype = presencetype;
move->endcontents = pc;
move->time = n * frametime;
move->frames = n;
return qtrue;
} //end if
} //end if
//
onground = AAS_OnGround(org, presencetype, entnum);
//if onground and on the ground for at least one whole frame
if (onground)
{
if (stopevent & SE_HITGROUND)
{
VectorCopy(org, move->endpos);
move->endarea = AAS_PointAreaNum(org);
VectorScale(frame_test_vel, 1/frametime, move->velocity);
move->trace = trace;
move->stopevent = SE_HITGROUND;
move->presencetype = presencetype;
move->endcontents = 0;
move->time = n * frametime;
move->frames = n;
return qtrue;
} //end if
} //end if
else if (stopevent & SE_LEAVEGROUND)
{
VectorCopy(org, move->endpos);
move->endarea = AAS_PointAreaNum(org);
VectorScale(frame_test_vel, 1/frametime, move->velocity);
move->trace = trace;
move->stopevent = SE_LEAVEGROUND;
move->presencetype = presencetype;
move->endcontents = 0;
move->time = n * frametime;
move->frames = n;
return qtrue;
} //end else if
else if (stopevent & SE_GAP)
{
aas_trace_t gaptrace;
VectorCopy(org, start);
VectorCopy(start, end);
end[2] -= 48 + aassettings.phys_maxbarrier;
gaptrace = AAS_TraceClientBBox(start, end, PRESENCE_CROUCH, -1);
//if solid is found the bot cannot walk any further and will not fall into a gap
if (!gaptrace.startsolid)
{
//if it is a gap (lower than one step height)
if (gaptrace.endpos[2] < org[2] - aassettings.phys_maxstep - 1)
{
if (!(AAS_PointContents(end) & CONTENTS_WATER))
{
VectorCopy(lastorg, move->endpos);
move->endarea = AAS_PointAreaNum(lastorg);
VectorScale(frame_test_vel, 1/frametime, move->velocity);
move->trace = trace;
move->stopevent = SE_GAP;
move->presencetype = presencetype;
move->endcontents = 0;
move->time = n * frametime;
move->frames = n;
return qtrue;
} //end if
} //end if
} //end if
} //end else if
} //end for
//
VectorCopy(org, move->endpos);
move->endarea = AAS_PointAreaNum(org);
VectorScale(frame_test_vel, 1/frametime, move->velocity);
move->stopevent = SE_NONE;
move->presencetype = presencetype;
move->endcontents = 0;
move->time = n * frametime;
move->frames = n;
//
return qtrue;
} //end of the function AAS_ClientMovementPrediction
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
int AAS_PredictClientMovement(struct aas_clientmove_s *move,
int entnum, vec3_t origin,
int presencetype, int onground,
vec3_t velocity, vec3_t cmdmove,
int cmdframes,
int maxframes, float frametime,
int stopevent, int stopareanum, int visualize)
{
vec3_t mins, maxs;
return AAS_ClientMovementPrediction(move, entnum, origin, presencetype, onground,
velocity, cmdmove, cmdframes, maxframes,
frametime, stopevent, stopareanum,
mins, maxs, visualize);
} //end of the function AAS_PredictClientMovement
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
int AAS_ClientMovementHitBBox(struct aas_clientmove_s *move,
int entnum, vec3_t origin,
int presencetype, int onground,
vec3_t velocity, vec3_t cmdmove,
int cmdframes,
int maxframes, float frametime,
vec3_t mins, vec3_t maxs, int visualize)
{
return AAS_ClientMovementPrediction(move, entnum, origin, presencetype, onground,
velocity, cmdmove, cmdframes, maxframes,
frametime, SE_HITBOUNDINGBOX, 0,
mins, maxs, visualize);
} //end of the function AAS_ClientMovementHitBBox
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
void AAS_TestMovementPrediction(int entnum, vec3_t origin, vec3_t dir)
{
vec3_t velocity, cmdmove;
aas_clientmove_t move;
VectorClear(velocity);
if (!AAS_Swimming(origin)) dir[2] = 0;
VectorNormalize(dir);
VectorScale(dir, 400, cmdmove);
cmdmove[2] = 224;
AAS_ClearShownDebugLines();
AAS_PredictClientMovement(&move, entnum, origin, PRESENCE_NORMAL, qtrue,
velocity, cmdmove, 13, 13, 0.1f, SE_HITGROUND, 0, qtrue);//SE_LEAVEGROUND);
if (move.stopevent & SE_LEAVEGROUND)
{
botimport.Print(PRT_MESSAGE, "leave ground\n");
} //end if
} //end of the function TestMovementPrediction
//===========================================================================
// calculates the horizontal velocity needed to perform a jump from start
// to end
//
// Parameter: zvel : z velocity for jump
// start : start position of jump
// end : end position of jump
// *speed : returned speed for jump
// Returns: qfalse if too high or too far from start to end
// Changes Globals: -
//===========================================================================
int AAS_HorizontalVelocityForJump(float zvel, vec3_t start, vec3_t end, float *velocity)
{
float phys_gravity, phys_maxvelocity;
float maxjump, height2fall, t, top;
vec3_t dir;
phys_gravity = aassettings.phys_gravity;
phys_maxvelocity = aassettings.phys_maxvelocity;
//maximum height a player can jump with the given initial z velocity
maxjump = 0.5 * phys_gravity * (zvel / phys_gravity) * (zvel / phys_gravity);
//top of the parabolic jump
top = start[2] + maxjump;
//height the bot will fall from the top
height2fall = top - end[2];
//if the goal is to high to jump to
if (height2fall < 0)
{
*velocity = phys_maxvelocity;
return 0;
} //end if
//time a player takes to fall the height
t = sqrt(height2fall / (0.5 * phys_gravity));
//direction from start to end
VectorSubtract(end, start, dir);
//
if ( (t + zvel / phys_gravity) == 0.0f ) {
*velocity = phys_maxvelocity;
return 0;
}
//calculate horizontal speed
*velocity = sqrt(dir[0]*dir[0] + dir[1]*dir[1]) / (t + zvel / phys_gravity);
//the horizontal speed must be lower than the max speed
if (*velocity > phys_maxvelocity)
{
*velocity = phys_maxvelocity;
return 0;
} //end if
return 1;
} //end of the function AAS_HorizontalVelocityForJump
| 412 | 0.9305 | 1 | 0.9305 | game-dev | MEDIA | 0.945285 | game-dev | 0.981894 | 1 | 0.981894 |
moo-man/WFRP4e-FoundryVTT | 3,213 | scripts/YN8719gme9AxYtyY.js | let characteristics = {
"ws" : 10,
"bs" : 0,
"s" : 5,
"t" : 15,
"i" : 20,
"ag" : 15,
"dex" : 20,
"int" : 35,
"wp" : 30,
"fel" : 10
}
let skills = ["Channelling", "Cool", "Dodge", "Entertain (Storytelling)", "Intuition", "Language (Magick)", "Leadership", "Lore (Magic)", "Lore (Theology)", "Perception"]
let skillAdvancements = [20, 25, 20, 25, 30, 25, 15, 20, 10, 30]
let talents = ["Aethyric Attunement", "Instinctive Diction", "Instinctive Diction", "Luck", "Magical Sense", "Menacing", "Arcane Magic", "Petty Magic", "Second Sight", "Sixth Sense"]
let trappings = ["Hand Weapon", "Robes", "Quarterstaff"]
let specialItems = [
{name: "Magic Item", type: "trapping", trappingType: "misc" },
]
let items = [];
let updateObj = this.actor.toObject();
for (let ch in characteristics)
{
updateObj.system.characteristics[ch].modifier += characteristics[ch];
}
for (let item of specialItems) {
let newItem
if (item.type == "weapon") {
newItem = new ItemWFRP4e({ name: item.name, type: item.type, system: { equipped: true, damage: {value: item.damage}} })
} else if (item.type == "trapping") {
newItem = new ItemWFRP4e({ img: "systems/wfrp4e/icons/blank.png", name: item.name, type: item.type, system: { worn: true, trappingType: { value: item.trappingType} } } )
} else {
newItem = new ItemWfrp4e({ img: "systems/wfrp4e/icons/blank.png", name: item.name, type: item.type })
}
items.push(newItem.toObject())
}
for (let index = 0; index < skills.length; index++)
{
let skill = skills[index]
let skillItem;
skillItem = updateObj.items.find(i => i.name == skill && i.type == "skill")
if (skillItem)
skillItem.system.advances.value += skillAdvancements[index]
else
{
skillItem = await game.wfrp4e.utility.findSkill(skill)
skillItem = skillItem.toObject();
skillItem.system.advances.value = skillAdvancements[index];
items.push(skillItem);
}
}
for (let talent of talents)
{
let talentItem = await game.wfrp4e.utility.findTalent(talent)
if (talentItem)
{
items.push(talentItem.toObject());
}
else
{
ui.notifications.warn(`Could not find ${talent}`, {permanent : true})
}
}
for (let trapping of trappings)
{
let trappingItem = await game.wfrp4e.utility.findItem(trapping)
if (trappingItem)
{
trappingItem = trappingItem.toObject()
trappingItem.system.equipped.value = true;
items.push(trappingItem);
}
else
{
ui.notifications.warn(`Could not find ${trapping}`, {permanent : true})
}
}
let ride = await foundry.applications.api.DialogV2.confirm({window : {title : "Skill"}, content : "Add Chaos Steed and +20 Ride (Horse)?"})
if (ride)
{
let skill = await game.wfrp4e.utility.findSkill("Ride (Horse)")
skill = skill.toObject();
skill.system.advances.value = 20;
items = items.concat({name : "Chaos Steed", type: "trapping", "system.trappingType.value" : "misc"}, skill)
}
updateObj.name = updateObj.name += " " + this.effect.name
await this.actor.update(updateObj)
this.actor.createEmbeddedDocuments("Item", items);
| 412 | 0.70516 | 1 | 0.70516 | game-dev | MEDIA | 0.953503 | game-dev | 0.984326 | 1 | 0.984326 |
diekmann/wasm-fizzbuzz | 4,729 | doom/linuxdoom-1.10/d_player.h | // Emacs style mode select -*- C++ -*-
//-----------------------------------------------------------------------------
//
// $Id:$
//
// Copyright (C) 1993-1996 by id Software, Inc.
//
// This source is available for distribution and/or modification
// only under the terms of the DOOM Source Code License as
// published by id Software. All rights reserved.
//
// The source is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// FITNESS FOR A PARTICULAR PURPOSE. See the DOOM Source Code License
// for more details.
//
// DESCRIPTION:
//
//
//-----------------------------------------------------------------------------
#ifndef __D_PLAYER__
#define __D_PLAYER__
// The player data structure depends on a number
// of other structs: items (internal inventory),
// animation states (closely tied to the sprites
// used to represent them, unfortunately).
#include "d_items.h"
#include "p_pspr.h"
// In addition, the player is just a special
// case of the generic moving object/actor.
#include "p_mobj.h"
// Finally, for odd reasons, the player input
// is buffered within the player data struct,
// as commands per game tick.
#include "d_ticcmd.h"
#ifdef __GNUG__
#pragma interface
#endif
//
// Player states.
//
typedef enum
{
// Playing or camping.
PST_LIVE,
// Dead on the ground, view follows killer.
PST_DEAD,
// Ready to restart/respawn???
PST_REBORN
} playerstate_t;
//
// Player internal flags, for cheats and debug.
//
typedef enum
{
// No clipping, walk through barriers.
CF_NOCLIP = 1,
// No damage, no health loss.
CF_GODMODE = 2,
// Not really a cheat, just a debug aid.
CF_NOMOMENTUM = 4
} cheat_t;
//
// Extended player object info: player_t
//
typedef struct player_s
{
mobj_t* mo;
playerstate_t playerstate;
ticcmd_t cmd;
// Determine POV,
// including viewpoint bobbing during movement.
// Focal origin above r.z
fixed_t viewz;
// Base height above floor for viewz.
fixed_t viewheight;
// Bob/squat speed.
fixed_t deltaviewheight;
// bounded/scaled total momentum.
fixed_t bob;
// This is only used between levels,
// mo->health is used during levels.
int health;
int armorpoints;
// Armor type is 0-2.
int armortype;
// Power ups. invinc and invis are tic counters.
int powers[NUMPOWERS];
boolean cards[NUMCARDS];
boolean backpack;
// Frags, kills of other players.
int frags[MAXPLAYERS];
weapontype_t readyweapon;
// Is wp_nochange if not changing.
weapontype_t pendingweapon;
boolean weaponowned[NUMWEAPONS];
int ammo[NUMAMMO];
int maxammo[NUMAMMO];
// True if button down last tic.
int attackdown;
int usedown;
// Bit flags, for cheats and debug.
// See cheat_t, above.
int cheats;
// Refired shots are less accurate.
int refire;
// For intermission stats.
int killcount;
int itemcount;
int secretcount;
// Hint messages.
char* message;
// For screen flashing (red or bright).
int damagecount;
int bonuscount;
// Who did damage (NULL for floors/ceilings).
mobj_t* attacker;
// So gun flashes light up areas.
int extralight;
// Current PLAYPAL, ???
// can be set to REDCOLORMAP for pain, etc.
int fixedcolormap;
// Player skin colorshift,
// 0-3 for which color to draw player.
int colormap;
// Overlay view sprites (gun, etc).
pspdef_t psprites[NUMPSPRITES];
// True if secret level has been done.
boolean didsecret;
} player_t;
//
// INTERMISSION
// Structure passed e.g. to WI_Start(wb)
//
typedef struct
{
boolean in; // whether the player is in game
// Player stats, kills, collected items etc.
int skills;
int sitems;
int ssecret;
int stime;
int frags[4];
int score; // current score on entry, modified on return
} wbplayerstruct_t;
typedef struct
{
int epsd; // episode # (0-2)
// if true, splash the secret level
boolean didsecret;
// previous and next levels, origin 0
int last;
int next;
int maxkills;
int maxitems;
int maxsecret;
int maxfrags;
// the par time
int partime;
// index of this player in game
int pnum;
wbplayerstruct_t plyr[MAXPLAYERS];
} wbstartstruct_t;
#endif
//-----------------------------------------------------------------------------
//
// $Log:$
//
//-----------------------------------------------------------------------------
| 412 | 0.679116 | 1 | 0.679116 | game-dev | MEDIA | 0.980408 | game-dev | 0.537011 | 1 | 0.537011 |
rashiph/DecompliedDotNetLibraries | 5,648 | System.Workflow.ComponentModel/System/Workflow/ComponentModel/PathParser.cs | namespace System.Workflow.ComponentModel
{
using System;
using System.Collections.Generic;
using System.Runtime;
internal sealed class PathParser
{
private List<SourceValueInfo> al = new List<SourceValueInfo>();
private DrillIn drillIn;
private static List<SourceValueInfo> EmptyInfo = new List<SourceValueInfo>(1);
private string error = string.Empty;
private int index;
private const char NullChar = '\0';
private int pathLength;
private string pathValue;
private static string SpecialChars = ".[]";
private State state;
private void AddIndexer()
{
int index = this.index;
int num2 = 1;
while (num2 > 0)
{
if (this.index >= this.pathLength)
{
return;
}
if (this.pathValue[this.index] == '[')
{
num2++;
}
else if (this.pathValue[this.index] == ']')
{
num2--;
}
this.index++;
}
string n = this.pathValue.Substring(index, (this.index - index) - 1).Trim();
SourceValueInfo item = new SourceValueInfo(SourceValueType.Indexer, this.drillIn, n);
this.al.Add(item);
this.StartNewLevel();
}
private void AddProperty()
{
int index = this.index;
while ((this.index < this.pathLength) && (SpecialChars.IndexOf(this.pathValue[this.index]) < 0))
{
this.index++;
}
string n = this.pathValue.Substring(index, this.index - index).Trim();
SourceValueInfo item = new SourceValueInfo(SourceValueType.Property, this.drillIn, n);
this.al.Add(item);
this.StartNewLevel();
}
internal List<SourceValueInfo> Parse(string path, bool returnResultBeforeError)
{
this.pathValue = (path != null) ? path.Trim() : string.Empty;
this.pathLength = this.pathValue.Length;
this.index = 0;
this.drillIn = DrillIn.IfNeeded;
this.al.Clear();
this.error = null;
this.state = State.Init;
if ((this.pathLength > 0) && (this.pathValue[0] == '.'))
{
SourceValueInfo item = new SourceValueInfo(SourceValueType.Property, this.drillIn, string.Empty);
this.al.Add(item);
}
while (this.state != State.Done)
{
bool flag;
char ch = (this.index < this.pathLength) ? this.pathValue[this.index] : '\0';
switch (this.state)
{
case State.Init:
switch (ch)
{
case ']':
goto Label_010C;
}
goto Label_015C;
case State.Prop:
flag = false;
switch (ch)
{
case '\0':
goto Label_018C;
case '.':
goto Label_017F;
case '[':
goto Label_0188;
}
goto Label_019C;
default:
{
continue;
}
}
this.state = State.Prop;
continue;
Label_010C:;
this.error = string.Concat(new object[] { "path[", this.index, "] = ", ch });
if (!returnResultBeforeError)
{
return EmptyInfo;
}
return this.al;
Label_015C:
this.AddProperty();
continue;
Label_017F:
this.drillIn = DrillIn.Never;
goto Label_01EC;
Label_0188:
flag = true;
goto Label_01EC;
Label_018C:
this.index--;
goto Label_01EC;
Label_019C:;
this.error = string.Concat(new object[] { "path[", this.index, "] = ", ch });
if (!returnResultBeforeError)
{
return EmptyInfo;
}
return this.al;
Label_01EC:
this.index++;
if (flag)
{
this.AddIndexer();
}
else
{
this.AddProperty();
}
}
if ((this.error != null) && !returnResultBeforeError)
{
return EmptyInfo;
}
return this.al;
}
private void StartNewLevel()
{
if (this.index >= this.pathLength)
{
this.state = State.Done;
}
this.drillIn = DrillIn.Never;
}
internal string Error
{
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
get
{
return this.error;
}
}
private enum State
{
Init,
Prop,
Done
}
}
}
| 412 | 0.925045 | 1 | 0.925045 | game-dev | MEDIA | 0.298927 | game-dev | 0.962085 | 1 | 0.962085 |
phosxd/PowerKey | 2,823 | addons/PowerKey/Editor/PKExp Builder/PKExp Builder.gd | @tool
extends Window
enum ExpTypes {ASSIGN,LINK,EXECUTE}
const Assign_expression_template:String = 'A:%s %s'
const Link_expression_template:String = 'L:%s %s'
const Execute_expression_template:String = 'E %s'
const Eval_expression_template:String = 'V:%s %s'
signal finished(raw:String)
func init() -> void:
%Result.init('',Array([],TYPE_DICTIONARY,'',null))
func _update_assign_expression_result(property, value) -> void:
if not property: property = %'Assign Property LineEdit'.text
if not value: value = %'Assign Value LineEdit'.text
%Result.set_text(Assign_expression_template % [property, value])
func _update_link_expression_result(property, frequency, value) -> void:
if not property: property = %'Link Property LineEdit'.text
if not frequency: frequency = %'Link Frequency SpinBox'.value
if not value: value = %'Link Value LineEdit'.text
if frequency == 0.0: frequency = ''
%Result.set_text(Link_expression_template % [','.join([property,frequency]).rstrip(','), value])
func _update_execute_expression_result(code) -> void:
if not code: code = %'Execute Code TextEdit'.text
%Result.set_text(Execute_expression_template % code)
func _update_gdexp_expression_result(property, expression) -> void:
if not property: property = %'Eval Property LineEdit'.text
if not expression: expression = %'GD Expression TextEdit'.text
%Result.set_text(Eval_expression_template % [property,expression])
# UI Callbacks.
# ------------
func _on_close_requested() -> void:
self.queue_free()
func _on_button_cancel_pressed() -> void:
_on_close_requested()
func _on_type_options_item_selected(index:int) -> void:
var count:int = 0
for child in %Details.get_children():
if count == index: child.visible = true
else: child.visible = false
count += 1
func _on_assign_value_text_changed(new_text:String) -> void:
_update_assign_expression_result(null, new_text)
func _on_assign_property_text_changed(new_text: String) -> void:
_update_assign_expression_result(new_text, null)
func _on_link_value_text_changed(new_text: String) -> void:
_update_link_expression_result(null, null, new_text)
func _on_link_frequency_value_changed(value: float) -> void:
_update_link_expression_result(null, value, null)
func _on_link_property_text_changed(new_text: String) -> void:
_update_link_expression_result(new_text, null, null)
func _on_execute_code_text_changed() -> void:
var text = %'Execute Code TextEdit'.text.replace('\n',';')
_update_execute_expression_result(text)
func _on_gd_expression_text_changed(new_text:String) -> void:
_update_gdexp_expression_result(null, new_text)
func _on_eval_property_text_changed(new_text:String) -> void:
_update_gdexp_expression_result(new_text, null)
func _on_button_done_pressed() -> void:
if not %Result.Invalid:
finished.emit(%Result.Raw)
_on_close_requested()
| 412 | 0.877203 | 1 | 0.877203 | game-dev | MEDIA | 0.42253 | game-dev | 0.880619 | 1 | 0.880619 |
omicronapps/7-Zip-JBinding-4Android | 2,635 | sevenzipjbinding/src/main/cpp/7zip/CPP/Windows/Clipboard.cpp | // Windows/Clipboard.cpp
#include "StdAfx.h"
#ifdef UNDER_CE
#include <winuserm.h>
#endif
#include "../Common/StringConvert.h"
#include "Clipboard.h"
#include "Defs.h"
#include "MemoryGlobal.h"
#include "Shell.h"
namespace NWindows {
bool CClipboard::Open(HWND wndNewOwner) throw()
{
m_Open = BOOLToBool(::OpenClipboard(wndNewOwner));
return m_Open;
}
bool CClipboard::Close() throw()
{
if (!m_Open)
return true;
m_Open = !BOOLToBool(CloseClipboard());
return !m_Open;
}
bool ClipboardIsFormatAvailableHDROP()
{
return BOOLToBool(IsClipboardFormatAvailable(CF_HDROP));
}
/*
bool ClipboardGetTextString(AString &s)
{
s.Empty();
if (!IsClipboardFormatAvailable(CF_TEXT))
return false;
CClipboard clipboard;
if (!clipboard.Open(NULL))
return false;
HGLOBAL h = ::GetClipboardData(CF_TEXT);
if (h != NULL)
{
NMemory::CGlobalLock globalLock(h);
const char *p = (const char *)globalLock.GetPointer();
if (p != NULL)
{
s = p;
return true;
}
}
return false;
}
*/
/*
bool ClipboardGetFileNames(UStringVector &names)
{
names.Clear();
if (!IsClipboardFormatAvailable(CF_HDROP))
return false;
CClipboard clipboard;
if (!clipboard.Open(NULL))
return false;
HGLOBAL h = ::GetClipboardData(CF_HDROP);
if (h != NULL)
{
NMemory::CGlobalLock globalLock(h);
void *p = (void *)globalLock.GetPointer();
if (p != NULL)
{
NShell::CDrop drop(false);
drop.Attach((HDROP)p);
drop.QueryFileNames(names);
return true;
}
}
return false;
}
*/
static bool ClipboardSetData(UINT uFormat, const void *data, size_t size) throw()
{
NMemory::CGlobal global;
if (!global.Alloc(GMEM_DDESHARE | GMEM_MOVEABLE, size))
return false;
{
NMemory::CGlobalLock globalLock(global);
LPVOID p = globalLock.GetPointer();
if (!p)
return false;
memcpy(p, data, size);
}
if (::SetClipboardData(uFormat, global) == NULL)
return false;
global.Detach();
return true;
}
bool ClipboardSetText(HWND owner, const UString &s)
{
CClipboard clipboard;
if (!clipboard.Open(owner))
return false;
if (!::EmptyClipboard())
return false;
bool res;
res = ClipboardSetData(CF_UNICODETEXT, (const wchar_t *)s, (s.Len() + 1) * sizeof(wchar_t));
#ifndef _UNICODE
AString a = UnicodeStringToMultiByte(s, CP_ACP);
if (ClipboardSetData(CF_TEXT, (const char *)a, (a.Len() + 1) * sizeof(char)))
res = true;
a = UnicodeStringToMultiByte(s, CP_OEMCP);
if (ClipboardSetData(CF_OEMTEXT, (const char *)a, (a.Len() + 1) * sizeof(char)))
res = true;
#endif
return res;
}
}
| 412 | 0.846215 | 1 | 0.846215 | game-dev | MEDIA | 0.373808 | game-dev | 0.78331 | 1 | 0.78331 |
vmanot/Swallow | 2,261 | Sources/Swallow/Intermodular/Helpers/Swift/Boolean.swift | //
// Copyright (c) Vatsal Manot
//
import Swift
/// A boolean type.
public protocol Boolean {
/// The boolean representation of this value.
var boolValue: Bool { get }
}
// MARK: - Extensions
extension Boolean {
public func orThrow(_ error: Error) throws {
if !boolValue {
throw error
}
}
public func orThrow() throws {
try orThrow(_BooleanAssertionError.isFalse)
}
}
infix operator &&->: LogicalConjunctionPrecedence
extension Boolean {
@inlinable
public func then<T>(_ value: @autoclosure () throws -> T) rethrows -> T? {
return boolValue ? try value() : nil
}
@discardableResult
@inlinable
public static func &&-> <T>(lhs: Self, rhs: @autoclosure () throws -> T) rethrows -> T? {
return try lhs.then(rhs())
}
@inlinable
public func then<T>(_ value: @autoclosure () throws -> T?) rethrows -> T? {
return boolValue ? try value() : nil
}
@discardableResult @inlinable
public static func &&-> <T>(lhs: Self, rhs: @autoclosure () throws -> T?) rethrows -> T? {
return try lhs.then(rhs())
}
}
extension Boolean {
@inlinable
public func or<T>(_ value: @autoclosure () throws -> T) rethrows -> T? {
return !boolValue ? try value() : nil
}
@inlinable
public func or<T>(_ value: @autoclosure () throws -> T?) rethrows -> T? {
return !boolValue ? try value() : nil
}
}
infix operator &&=: AssignmentPrecedence
infix operator ||=: AssignmentPrecedence
extension Boolean {
@inlinable
public static func &&= (lhs: inout Self, rhs: @autoclosure () throws -> Self) rethrows {
if lhs.boolValue {
lhs = try rhs()
}
}
@inlinable
public static func ||= (lhs: inout Self, rhs: @autoclosure () throws -> Self) rethrows {
if !lhs.boolValue {
let rhs = try rhs()
if rhs.boolValue {
lhs = rhs
}
}
}
}
// MARK: - Auxiliary
private enum _BooleanAssertionError: Error {
case isFalse
}
// MARK: - Helpers
extension BooleanInitiable {
public init<T: Boolean>(boolean: T) {
self.init(boolean.boolValue)
}
}
| 412 | 0.92334 | 1 | 0.92334 | game-dev | MEDIA | 0.237127 | game-dev | 0.974221 | 1 | 0.974221 |
100askTeam/xiaozhi-linux | 3,756 | gui/lvgl/env_support/pikascript/pika_lvgl_lv_obj.c | #if defined(LV_LVGL_H_INCLUDE_SIMPLE)
#include "lvgl.h"
#else
#include "../../lvgl.h"
#endif
#ifdef PIKASCRIPT
#include "pika_lvgl_lv_obj.h"
#include "BaseObj.h"
#include "dataStrs.h"
#include "pika_lvgl.h"
#include "pika_lvgl_arc.h"
#include "pika_lvgl_lv_event.h"
extern PikaObj* pika_lv_event_listener_g;
void pika_lvgl_lv_obj_center(PikaObj* self) {
lv_obj_t* lv_obj = obj_getPtr(self, "lv_obj");
lv_obj_center(lv_obj);
}
void pika_lvgl_lv_obj_set_size(PikaObj* self, int size_x, int size_y) {
lv_obj_t* lv_obj = obj_getPtr(self, "lv_obj");
lv_obj_set_size(lv_obj, size_x, size_y);
}
void pika_lvgl_lv_obj_align(PikaObj* self, int align, int x_ofs, int y_ofs) {
lv_obj_t* lv_obj = obj_getPtr(self, "lv_obj");
lv_obj_align(lv_obj, align, x_ofs, y_ofs);
}
void pika_lvgl_lv_obj_set_height(PikaObj* self, int h) {
lv_obj_t* lv_obj = obj_getPtr(self, "lv_obj");
lv_obj_set_height(lv_obj, h);
}
void pika_lvgl_lv_obj_update_layout(PikaObj* self) {
lv_obj_t* lv_obj = obj_getPtr(self, "lv_obj");
lv_obj_update_layout(lv_obj);
}
void pika_lvgl_lv_obj_set_width(PikaObj* self, int w) {
lv_obj_t* lv_obj = obj_getPtr(self, "lv_obj");
lv_obj_set_width(lv_obj, w);
}
void pika_lvgl_lv_obj_add_state(PikaObj* self, int state) {
lv_obj_t* lv_obj = obj_getPtr(self, "lv_obj");
lv_obj_add_state(lv_obj, state);
}
PikaObj* eventListener_getHandler(PikaObj* self, uintptr_t event_id) {
Args buffs = {0};
char* event_name =
strsFormat(&buffs, PIKA_SPRINTF_BUFF_SIZE, "%d", event_id);
PikaObj* event_item = obj_getObj(self, event_name);
PikaObj* event_handler = obj_getPtr(event_item, "handler");
strsDeinit(&buffs);
return event_handler;
}
static void __pika_event_cb(lv_event_t* e) {
lv_obj_t* target = lv_event_get_target(e);
PikaObj* event_handler =
eventListener_getHandler(pika_lv_event_listener_g, (uintptr_t)target);
PikaObj* evt = obj_getObj(event_handler, "_event_evt");
obj_setPtr(evt, "lv_event", e);
obj_run(event_handler, "_event_cb(_event_evt)");
}
void eventListener_registerEvent(PikaObj* self,
uintptr_t event_id,
PikaObj* event_handler) {
Args buffs = {0};
char* event_name =
strsFormat(&buffs, PIKA_SPRINTF_BUFF_SIZE, "%d", event_id);
obj_newDirectObj(self, event_name, New_TinyObj);
PikaObj* event_item = obj_getObj(self, event_name);
obj_setRef(event_item, "handler", event_handler);
strsDeinit(&buffs);
}
void pika_lvgl_lv_obj_add_event_cb(PikaObj* self,
Arg* event_cb,
int filter,
void* user_data) {
lv_obj_t* lv_obj = obj_getPtr(self, "lv_obj");
lv_obj_add_event_cb(lv_obj, __pika_event_cb, filter, NULL);
obj_setArg(self, "_event_cb", event_cb);
obj_setPtr(self, "_event_user_data", user_data);
obj_newDirectObj(self, "_event_evt", New_pika_lvgl_lv_event);
eventListener_registerEvent(pika_lv_event_listener_g, (uintptr_t)lv_obj, self);
}
void pika_lvgl_lv_obj_add_style(PikaObj *self, PikaObj* style, int selector){
lv_obj_t* lv_obj = obj_getPtr(self, "lv_obj");
lv_style_t* lv_style = obj_getPtr(style, "lv_style");
lv_obj_add_style(lv_obj, lv_style, selector);
}
int pika_lvgl_lv_obj_get_x(PikaObj *self){
lv_obj_t* lv_obj = obj_getPtr(self, "lv_obj");
return lv_obj_get_x(lv_obj);
}
int pika_lvgl_lv_obj_get_y(PikaObj *self){
lv_obj_t* lv_obj = obj_getPtr(self, "lv_obj");
return lv_obj_get_y(lv_obj);
}
void pika_lvgl_lv_obj_set_pos(PikaObj *self, int x, int y){
lv_obj_t* lv_obj = obj_getPtr(self, "lv_obj");
lv_obj_set_pos(lv_obj, x, y);
}
#endif
| 412 | 0.827292 | 1 | 0.827292 | game-dev | MEDIA | 0.600284 | game-dev,graphics-rendering | 0.847115 | 1 | 0.847115 |
sienaiwun/Unity_GPU_Driven_Particles | 9,342 | Packages/src/com.unity.render-pipelines.core/Editor/LookDev/EnvironmentLibrary.cs | using UnityEngine;
using UnityEngine.Rendering;
using System;
using System.Collections.Generic;
using UnityEngine.UIElements;
using System.Linq;
using System.IO;
using System.Linq.Expressions;
using System.Reflection;
using UnityEditor.UIElements;
namespace UnityEditor.Rendering.LookDev
{
/// <summary>
/// Class containing a collection of Environment
/// </summary>
public class EnvironmentLibrary : BaseEnvironmentLibrary
{
[field: SerializeField]
List<Environment> environments { get; set; } = new List<Environment>();
/// <summary>
/// Number of elements in the collection
/// </summary>
public int Count => environments.Count;
/// <summary>
/// Indexer giving access to contained Environment
/// </summary>
public Environment this[int index] => environments[index];
/// <summary>
/// Create a new empty Environment at the end of the collection
/// </summary>
/// <returns>The created Environment</returns>
public Environment Add()
{
Environment environment = ScriptableObject.CreateInstance<Environment>();
environment.name = "New Environment";
Undo.RegisterCreatedObjectUndo(environment, "Add Environment");
environments.Add(environment);
// Store this new environment as a subasset so we can reference it safely afterwards.
AssetDatabase.AddObjectToAsset(environment, this);
// Force save / refresh. Important to do this last because SaveAssets can cause effect to become null!
EditorUtility.SetDirty(this);
AssetDatabase.SaveAssets();
return environment;
}
/// <summary>
/// Remove Environment of the collection at given index
/// </summary>
/// <param name="index">Index where to remove Environment</param>
public void Remove(int index)
{
Environment environment = environments[index];
Undo.RecordObject(this, "Remove Environment");
environments.RemoveAt(index);
Undo.DestroyObjectImmediate(environment);
// Force save / refresh
EditorUtility.SetDirty(this);
AssetDatabase.SaveAssets();
}
/// <summary>
/// Duplicate the Environment at given index and add it at the end of the Collection
/// </summary>
/// <param name="fromIndex">Index where to take data for duplication</param>
/// <returns>The created Environment</returns>
public Environment Duplicate(int fromIndex)
{
Environment environment = ScriptableObject.CreateInstance<Environment>();
Environment environmentToCopy = environments[fromIndex];
environmentToCopy.CopyTo(environment);
Undo.RegisterCreatedObjectUndo(environment, "Duplicate Environment");
environments.Add(environment);
// Store this new environment as a subasset so we can reference it safely afterwards.
AssetDatabase.AddObjectToAsset(environment, this);
// Force save / refresh. Important to do this last because SaveAssets can cause effect to become null!
EditorUtility.SetDirty(this);
AssetDatabase.SaveAssets();
return environment;
}
/// <summary>
/// Compute position of given Environment in the collection
/// </summary>
/// <param name="environment">Environment to look at</param>
/// <returns>Index of the searched environment. If not found, -1.</returns>
public int IndexOf(Environment environment)
=> environments.IndexOf(environment);
}
[CustomEditor(typeof(EnvironmentLibrary))]
class EnvironmentLibraryEditor : Editor
{
VisualElement root;
public sealed override VisualElement CreateInspectorGUI()
{
var library = target as EnvironmentLibrary;
root = new VisualElement();
Button open = new Button(() =>
{
if (!LookDev.open)
LookDev.Open();
LookDev.currentContext.UpdateEnvironmentLibrary(library);
LookDev.currentEnvironmentDisplayer.Repaint();
})
{
text = "Open in LookDev window"
};
root.Add(open);
return root;
}
// Don't use ImGUI
public sealed override void OnInspectorGUI() { }
}
class EnvironmentLibraryCreator : ProjectWindowCallback.EndNameEditAction
{
ObjectField m_Field = null;
public void SetField(ObjectField field)
=> m_Field = field;
public override void Cancelled(int instanceId, string pathName, string resourceFile)
=> m_Field = null;
public override void Action(int instanceId, string pathName, string resourceFile)
{
var newAsset = CreateInstance<EnvironmentLibrary>();
newAsset.name = Path.GetFileName(pathName);
AssetDatabase.CreateAsset(newAsset, pathName);
ProjectWindowUtil.ShowCreatedAsset(newAsset);
if (m_Field != null)
m_Field.value = newAsset;
m_Field = null;
}
[MenuItem("Assets/Create/LookDev/Environment Library", priority = 2000)]
static void Create()
{
var icon = EditorGUIUtility.FindTexture("ScriptableObject Icon");
ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0, ScriptableObject.CreateInstance<EnvironmentLibraryCreator>(), "New EnvironmentLibrary.asset", icon, null);
}
public static void CreateAndAssignTo(ObjectField field)
{
var icon = EditorGUIUtility.FindTexture("ScriptableObject Icon");
var assetCreator = ScriptableObject.CreateInstance<EnvironmentLibraryCreator>();
assetCreator.SetField(field);
ProjectWindowUtil.StartNameEditingIfProjectWindowExists(assetCreator.GetInstanceID(), assetCreator, "New EnvironmentLibrary.asset", icon, null);
}
}
static class EnvironmentLibraryLoader
{
public static void Load(Action onInspectorRedrawRequested)
{
UnityEngine.Object target = LookDev.currentContext.environmentLibrary;
UIElementObjectSelectorWorkaround.Show(target, typeof(EnvironmentLibrary), LoadCallback(onInspectorRedrawRequested));
}
static Action<UnityEngine.Object> LoadCallback(Action onUpdate)
{
return (UnityEngine.Object newLibrary) =>
{
LookDev.currentContext.UpdateEnvironmentLibrary(newLibrary as EnvironmentLibrary);
onUpdate?.Invoke();
};
}
// As in UIElement.ObjectField we cannot support cancel when closing window
static class UIElementObjectSelectorWorkaround
{
static Action<UnityEngine.Object, Type, Action<UnityEngine.Object>> ShowObjectSelector;
static UIElementObjectSelectorWorkaround()
{
Type playerSettingsType = typeof(PlayerSettings);
Type objectSelectorType = playerSettingsType.Assembly.GetType("UnityEditor.ObjectSelector");
var instanceObjectSelectorInfo = objectSelectorType.GetProperty("get", BindingFlags.Static | BindingFlags.Public);
var showInfo = objectSelectorType.GetMethod("Show", BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { typeof(UnityEngine.Object), typeof(Type), typeof(SerializedProperty), typeof(bool), typeof(List<int>), typeof(Action<UnityEngine.Object>), typeof(Action<UnityEngine.Object>) }, null);
var objectSelectorVariable = Expression.Variable(objectSelectorType, "objectSelector");
var objectParameter = Expression.Parameter(typeof(UnityEngine.Object), "unityObject");
var typeParameter = Expression.Parameter(typeof(Type), "type");
var onChangedObjectParameter = Expression.Parameter(typeof(Action<UnityEngine.Object>), "onChangedObject");
var showObjectSelectorBlock = Expression.Block(
new[] { objectSelectorVariable },
Expression.Assign(objectSelectorVariable, Expression.Call(null, instanceObjectSelectorInfo.GetGetMethod())),
Expression.Call(objectSelectorVariable, showInfo, objectParameter, typeParameter, Expression.Constant(null, typeof(SerializedProperty)), Expression.Constant(false), Expression.Constant(null, typeof(List<int>)), Expression.Constant(null, typeof(Action<UnityEngine.Object>)), onChangedObjectParameter)
);
var showObjectSelectorLambda = Expression.Lambda<Action<UnityEngine.Object, Type, Action<UnityEngine.Object>>>(showObjectSelectorBlock, objectParameter, typeParameter, onChangedObjectParameter);
ShowObjectSelector = showObjectSelectorLambda.Compile();
}
public static void Show(UnityEngine.Object obj, Type type, Action<UnityEngine.Object> onObjectChanged)
{
ShowObjectSelector(obj, type, onObjectChanged);
}
}
}
}
| 412 | 0.770108 | 1 | 0.770108 | game-dev | MEDIA | 0.838863 | game-dev | 0.934641 | 1 | 0.934641 |
magefree/mage | 3,312 | Mage.Sets/src/mage/cards/g/GhostlyWings.java |
package mage.cards.g;
import java.util.UUID;
import mage.abilities.Ability;
import mage.abilities.common.SimpleActivatedAbility;
import mage.abilities.common.SimpleStaticAbility;
import mage.abilities.costs.common.DiscardCardCost;
import mage.abilities.effects.Effect;
import mage.abilities.effects.OneShotEffect;
import mage.abilities.effects.common.AttachEffect;
import mage.abilities.effects.common.continuous.BoostEnchantedEffect;
import mage.abilities.effects.common.continuous.GainAbilityAttachedEffect;
import mage.abilities.keyword.EnchantAbility;
import mage.abilities.keyword.FlyingAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.*;
import mage.game.Game;
import mage.game.permanent.Permanent;
import mage.players.Player;
import mage.target.TargetPermanent;
import mage.target.common.TargetCreaturePermanent;
/**
*
* @author LevelX2
*/
public final class GhostlyWings extends CardImpl {
public GhostlyWings(UUID ownerId, CardSetInfo setInfo) {
super(ownerId,setInfo,new CardType[]{CardType.ENCHANTMENT},"{1}{U}");
this.subtype.add(SubType.AURA);
// Enchant creature
TargetPermanent auraTarget = new TargetCreaturePermanent();
this.getSpellAbility().addTarget(auraTarget);
this.getSpellAbility().addEffect(new AttachEffect(Outcome.AddAbility));
Ability ability = new EnchantAbility(auraTarget);
this.addAbility(ability);
// Enchanted creature gets +1/+1 and has flying.
Effect effect = new BoostEnchantedEffect(1, 1, Duration.WhileOnBattlefield);
effect.setText("Enchanted creature gets +1/+1");
ability = new SimpleStaticAbility(effect);
effect = new GainAbilityAttachedEffect(FlyingAbility.getInstance(), AttachmentType.AURA);
effect.setText("and has flying");
ability.addEffect(effect);
this.addAbility(ability);
// Discard a card: Return enchanted creature to its owner's hand.
this.addAbility(new SimpleActivatedAbility(new GhostlyWingsReturnEffect(), new DiscardCardCost()));
}
private GhostlyWings(final GhostlyWings card) {
super(card);
}
@Override
public GhostlyWings copy() {
return new GhostlyWings(this);
}
}
class GhostlyWingsReturnEffect extends OneShotEffect {
GhostlyWingsReturnEffect() {
super(Outcome.ReturnToHand);
staticText = "Return enchanted creature to its owner's hand";
}
private GhostlyWingsReturnEffect(final GhostlyWingsReturnEffect effect) {
super(effect);
}
@Override
public GhostlyWingsReturnEffect copy() {
return new GhostlyWingsReturnEffect(this);
}
@Override
public boolean apply(Game game, Ability source) {
Permanent permanent = game.getPermanentOrLKIBattlefield(source.getSourceId());
Player controller = game.getPlayer(source.getControllerId());
if (controller != null && permanent != null && permanent.getAttachedTo() != null) {
Permanent enchantedCreature = game.getPermanent(permanent.getAttachedTo());
if (enchantedCreature != null) {
controller.moveCards(enchantedCreature, Zone.HAND, source, game);
}
return true;
}
return false;
}
}
| 412 | 0.971692 | 1 | 0.971692 | game-dev | MEDIA | 0.973224 | game-dev | 0.994723 | 1 | 0.994723 |
pixelcmtd/CXClient | 1,554 | src/minecraft/net/minecraft/enchantment/EnumEnchantmentType.java | package net.minecraft.enchantment;
import net.minecraft.item.Item;
import net.minecraft.item.ItemArmor;
import net.minecraft.item.ItemBow;
import net.minecraft.item.ItemFishingRod;
import net.minecraft.item.ItemSword;
import net.minecraft.item.ItemTool;
public enum EnumEnchantmentType
{
ALL,
ARMOR,
ARMOR_FEET,
ARMOR_LEGS,
ARMOR_TORSO,
ARMOR_HEAD,
WEAPON,
DIGGER,
FISHING_ROD,
BREAKABLE,
BOW;
/**
* Return true if the item passed can be enchanted by a enchantment of this type.
*/
public boolean canEnchantItem(Item p_77557_1_)
{
if (this == ALL)
{
return true;
}
else if (this == BREAKABLE && p_77557_1_.isDamageable())
{
return true;
}
else if (p_77557_1_ instanceof ItemArmor)
{
if (this == ARMOR)
{
return true;
}
else
{
ItemArmor itemarmor = (ItemArmor)p_77557_1_;
return itemarmor.armorType == 0 ? this == ARMOR_HEAD : (itemarmor.armorType == 2 ? this == ARMOR_LEGS : (itemarmor.armorType == 1 ? this == ARMOR_TORSO : (itemarmor.armorType == 3 ? this == ARMOR_FEET : false)));
}
}
else
{
return p_77557_1_ instanceof ItemSword ? this == WEAPON : (p_77557_1_ instanceof ItemTool ? this == DIGGER : (p_77557_1_ instanceof ItemBow ? this == BOW : (p_77557_1_ instanceof ItemFishingRod ? this == FISHING_ROD : false)));
}
}
}
| 412 | 0.715926 | 1 | 0.715926 | game-dev | MEDIA | 0.99854 | game-dev | 0.714971 | 1 | 0.714971 |
PotRooms/AzurPromiliaData | 4,876 | Lua/config/chs/worldmap_611.lua | local worldmap_611 = {
[1000010] = {
[-1] = -1,
[-2] = -2,
[-3] = {
-3,
-4,
-5
},
[-4] = {
-6,
-7,
-6
},
[-5] = -6,
[-6] = -8,
[-7] = -9,
[-8] = {
[-9] = -10
},
[-10] = -6,
[-11] = -6,
[-12] = -6,
[-13] = {},
[-14] = {},
[-15] = {},
[-16] = {-11},
[-17] = -11,
[-18] = -6,
[-19] = {},
[-20] = {},
[-21] = -6,
[-22] = -6,
[-23] = -11,
[-24] = -6
},
[1200004] = {
[-1] = -12,
[-2] = -2,
[-3] = {
-3,
-4,
-5
},
[-4] = {
-6,
-13,
-6
},
[-5] = -6,
[-6] = -14,
[-7] = -6,
[-8] = {},
[-10] = -6,
[-11] = -6,
[-12] = -6,
[-13] = {},
[-14] = {},
[-15] = {},
[-16] = {},
[-17] = -6,
[-18] = -6,
[-19] = {},
[-20] = {},
[-21] = -6,
[-22] = -6,
[-23] = -11,
[-24] = -6
},
[1200006] = {
[-1] = -15,
[-2] = -2,
[-3] = {
-3,
-16,
-5
},
[-4] = {
-6,
-17,
-6
},
[-5] = -6,
[-6] = -18,
[-7] = -6,
[-8] = {},
[-10] = -6,
[-11] = -6,
[-12] = -6,
[-13] = {},
[-14] = {},
[-15] = {},
[-16] = {-19},
[-17] = -6,
[-18] = -6,
[-19] = {-20},
[-20] = {
{-21, -22}
},
[-21] = -6,
[-22] = -6,
[-23] = -11,
[-24] = -6
},
[1200015] = {
[-1] = -23,
[-2] = -2,
[-3] = {
-24,
-25,
-26
},
[-4] = {
-6,
-6,
-6
},
[-5] = -27,
[-6] = -28,
[-7] = -6,
[-8] = {},
[-10] = -6,
[-11] = -6,
[-12] = -6,
[-13] = {},
[-14] = {},
[-15] = {},
[-16] = {},
[-17] = -6,
[-18] = -6,
[-19] = {},
[-20] = {},
[-21] = -6,
[-22] = -6,
[-23] = -6,
[-24] = -6
}
}
local key_to_index_map = {
id = -1,
cityId = -2,
position = -3,
rotation = -4,
scale = -5,
spawnerId = -6,
expandId = -7,
expandParams = -8,
displayCount = -9,
aiTree = -10,
blueprint = -11,
fsm = -12,
statusReward = -13,
appearCond = -14,
disappearCond = -15,
commonTag = -16,
allBlockShow = -17,
keepOnComplete = -18,
interactOptions = -19,
interactOverrideParams = -20,
filterMark = -21,
randomEvtId = -22,
initStatus = -23,
initialCompleteState = -24
}
local index_to_key_map = {}
for k, v in pairs(key_to_index_map) do
index_to_key_map[v] = k
end
local value_to_index_map = {
[1000010] = -1,
[611] = -2,
[162.3] = -3,
[52.396] = -4,
[204.9] = -5,
[0.0] = -6,
[69.527] = -7,
[99010] = -8,
[10170] = -9,
["3"] = -10,
[1] = -11,
[1200004] = -12,
[184.161] = -13,
[50100] = -14,
[1200006] = -15,
[51.396] = -16,
[72.117] = -17,
[26003] = -18,
[11] = -19,
[64] = -20,
["14"] = -21,
["\228\184\139\228\184\128\233\152\182\230\174\181,1"] = -22,
[1200015] = -23,
[187.7] = -24,
[-36.75] = -25,
[208.8] = -26,
[1.1] = -27,
[170570] = -28
}
local index_to_value_map = {}
for k, v in pairs(value_to_index_map) do
index_to_value_map[v] = k
end
local function SetReadonlyTable(t)
for k, v in pairs(t) do
if type(v) == "table" then
t[k] = SetReadonlyTable(v)
end
end
local mt = {
__data = t,
__index_to_key_map = index_to_key_map,
__key_to_index_map = key_to_index_map,
__index_to_value_map = index_to_value_map,
__index = function(t, k)
local tmt = getmetatable(t)
local data = tmt.__data
local value_index
if tmt.__key_to_index_map[k] ~= nil then
value_index = data[tmt.__key_to_index_map[k]]
else
value_index = data[k]
end
if type(value_index) == "table" then
return value_index
else
return tmt.__index_to_value_map[value_index]
end
end,
__newindex = function(t, k, v)
errorf("attempt to modify a read-only talbe!", 2)
end,
__pairs = function(t, k)
return function(t, k)
local tmt = getmetatable(t)
local data = tmt.__data
local nk, nv
if tmt.__key_to_index_map[k] ~= nil then
local iter_key = tmt.__key_to_index_map[k]
nk, nv = next(data, iter_key)
else
nk, nv = next(data, k)
end
local key, value
if tmt.__index_to_key_map[nk] ~= nil then
key = tmt.__index_to_key_map[nk]
else
key = nk
end
if type(nv) == "table" then
value = nv
else
value = tmt.__index_to_value_map[nv]
end
return key, value
end, t, nil
end,
__len = function(t)
local tmt = getmetatable(t)
local data = tmt.__data
return #data
end
}
t = setmetatable({}, mt)
return t
end
worldmap_611 = SetReadonlyTable(worldmap_611)
return worldmap_611
| 412 | 0.54017 | 1 | 0.54017 | game-dev | MEDIA | 0.864482 | game-dev | 0.684961 | 1 | 0.684961 |
storax/kubedoom | 7,719 | dockerdoom/trunk/src/doomstat.h | // Emacs style mode select -*- C++ -*-
//-----------------------------------------------------------------------------
//
// Copyright(C) 1993-1996 Id Software, Inc.
// Copyright(C) 2000 by David Koppenhofer
// Copyright(C) 2005 Simon Howard
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
// 02111-1307, USA.
//
// DESCRIPTION:
// All the global variables that store the internal state.
// Theoretically speaking, the internal state of the engine
// should be found by looking at the variables collected
// here, and every relevant module will have to include
// this header file.
// In practice, things are a bit messy.
//
//-----------------------------------------------------------------------------
#ifndef __D_STATE__
#define __D_STATE__
// We need globally shared data structures,
// for defining the global state variables.
#include "doomdata.h"
#include "d_net.h"
// We need the playr data structure as well.
#include "d_player.h"
// ------------------------
// Command line parameters.
//
extern boolean nomonsters; // checkparm of -nomonsters
// *** PID BEGIN ***
// This makes a 'no monsters' that is persistant across save games
// and level warps.
extern boolean nomonstersperiod; // checkparm of '-nomonsters.'
// This makes items respawn as in -altdeath (ie. no dropped items,
// no invis, no invun)
extern boolean respawnitems; // checkparm of -respawnitems
// *** PID END ***
extern boolean respawnparm; // checkparm of -respawn
extern boolean fastparm; // checkparm of -fast
extern boolean devparm; // DEBUG: launched with -devparm
extern boolean screensaver_mode; // game running as a screensaver?
// -----------------------------------------------------
// Game Mode - identify IWAD as shareware, retail etc.
//
extern GameMode_t gamemode;
extern GameMission_t gamemission;
extern GameVersion_t gameversion;
extern char *gamedescription;
// Set if homebrew PWAD stuff has been added.
extern boolean modifiedgame;
// -------------------------------------------
// Selected skill type, map etc.
//
// Defaults for menu, methinks.
extern skill_t startskill;
extern int startepisode;
extern int startmap;
// Savegame slot to load on startup. This is the value provided to
// the -loadgame option. If this has not been provided, this is -1.
extern int startloadgame;
extern boolean autostart;
// Selected by user.
extern skill_t gameskill;
extern int gameepisode;
extern int gamemap;
// If non-zero, exit the level after this number of minutes
extern int timelimit;
// vertical movement from mouse/joystick disabled
extern int novert;
// Nightmare mode flag, single player.
extern boolean respawnmonsters;
// Netgame? Only true if >1 player.
extern boolean netgame;
// Flag: true only if started as net deathmatch.
// An enum might handle altdeath/cooperative better.
extern boolean deathmatch;
// -------------------------
// Internal parameters for sound rendering.
// These have been taken from the DOS version,
// but are not (yet) supported with Linux
// (e.g. no sound volume adjustment with menu.
// From m_menu.c:
// Sound FX volume has default, 0 - 15
// Music volume has default, 0 - 15
// These are multiplied by 8.
extern int sfxVolume;
extern int musicVolume;
// Current music/sfx card - index useless
// w/o a reference LUT in a sound module.
// Ideally, this would use indices found
// in: /usr/include/linux/soundcard.h
extern int snd_MusicDevice;
extern int snd_SfxDevice;
// Config file? Same disclaimer as above.
extern int snd_DesiredMusicDevice;
extern int snd_DesiredSfxDevice;
// -------------------------
// Status flags for refresh.
//
// Depending on view size - no status bar?
// Note that there is no way to disable the
// status bar explicitely.
extern boolean statusbaractive;
extern boolean automapactive; // In AutoMap mode?
extern boolean menuactive; // Menu overlayed?
extern boolean paused; // Game Pause?
extern boolean viewactive;
extern boolean nodrawers;
extern boolean noblit;
extern int viewwindowx;
extern int viewwindowy;
extern int viewheight;
extern int viewwidth;
extern int scaledviewwidth;
extern boolean testcontrols;
// This one is related to the 3-screen display mode.
// ANG90 = left side, ANG270 = right
extern int viewangleoffset;
// Player taking events, and displaying.
extern int consoleplayer;
extern int displayplayer;
// -------------------------------------
// Scores, rating.
// Statistics on a given map, for intermission.
//
extern int totalkills;
extern int totalitems;
extern int totalsecret;
// Timer, for scores.
extern int levelstarttic; // gametic at level start
extern int leveltime; // tics in game play for par
// --------------------------------------
// DEMO playback/recording related stuff.
// No demo, there is a human player in charge?
// Disable save/end game?
extern boolean usergame;
//?
extern boolean demoplayback;
extern boolean demorecording;
// Round angleturn in ticcmds to the nearest 256. This is used when
// recording Vanilla demos in netgames.
extern boolean lowres_turn;
// Quit after playing a demo from cmdline.
extern boolean singledemo;
//?
extern gamestate_t gamestate;
//-----------------------------
// Internal parameters, fixed.
// These are set by the engine, and not changed
// according to user inputs. Partly load from
// WAD, partly set at startup time.
extern int gametic;
// Bookkeeping on players - state.
extern player_t players[MAXPLAYERS];
// Alive? Disconnected?
extern boolean playeringame[MAXPLAYERS];
// Player spawn spots for deathmatch.
#define MAX_DM_STARTS 10
extern mapthing_t deathmatchstarts[MAX_DM_STARTS];
extern mapthing_t* deathmatch_p;
// Player spawn spots.
extern mapthing_t playerstarts[MAXPLAYERS];
// Intermission stats.
// Parameters for world map / intermission.
extern wbstartstruct_t wminfo;
// LUT of ammunition limits for each kind.
// This doubles with BackPack powerup item.
extern int maxammo[NUMAMMO];
//-----------------------------------------
// Internal parameters, used for engine.
//
// File handling stuff.
extern char * savegamedir;
extern char basedefault[1024];
// if true, load all graphics at level load
extern boolean precache;
// wipegamestate can be set to -1
// to force a wipe on the next draw
extern gamestate_t wipegamestate;
extern int mouseSensitivity;
//?
// debug flag to cancel adaptiveness
extern boolean singletics;
extern int bodyqueslot;
// Needed to store the number of the dummy sky flat.
// Used for rendering,
// as well as tracking projectiles etc.
extern int skyflatnum;
// Netgame stuff (buffers and pointers, i.e. indices).
extern int rndindex;
extern int maketic;
extern int nettics[MAXPLAYERS];
extern ticcmd_t netcmds[MAXPLAYERS][BACKUPTICS];
extern int ticdup;
#endif
| 412 | 0.686366 | 1 | 0.686366 | game-dev | MEDIA | 0.737995 | game-dev | 0.704305 | 1 | 0.704305 |
Tryibion/FlaxFmod | 3,199 | Source/FlaxFmod/FmodAudioSettings.h | #pragma once
#include "Engine/Core/Config.h"
#include "Engine/Core/Config/Settings.h"
#include "Engine/Core/Collections/Array.h"
#include "Engine/Core/Types/String.h"
API_CLASS() class FLAXFMOD_API FmodAudioSettings : public SettingsBase
{
API_AUTO_SERIALIZATION();
DECLARE_SCRIPTING_TYPE_MINIMAL(FmodAudioSettings);
DECLARE_SETTINGS_GETTER(FmodAudioSettings);
public:
// Global settings
/// <summary>
/// Whether to load all the banks that are located in the bank path.
/// </summary>
API_FIELD() bool LoadAllBanks = true;
/// <summary>
/// The name of the master bank.
/// </summary>
API_FIELD() String MasterBankName = TEXT("Master");
/// <summary>
/// An array of the banks to preload. Only used if LoadAllBanks is false.
/// </summary>
API_FIELD() Array<String> BanksToPreload;
/// <summary>
/// The FMOD folder used for storing banks in a built game and generating assets.
/// This is relative to the startup folder.
/// </summary>
API_FIELD() String BuiltProjectBankRelativeFolderPath = TEXT("Content/fmod");
/// <summary>
/// The name of the library related to a fmod plugin. This needs to match the plugin's DLL name.
/// This will search and use the plugin in the project directory first. If it does not exist it will search in the studio install location.
/// </summary>
API_FIELD() Array<String> FmodPluginNames;
/// <summary>
/// The FMOD folder used for storing generating assets. Please put this in the Content Folder somewhere.
/// This is relative to the project folder.
/// </summary>
API_FIELD(Attributes="EditorDisplay(\"Editor\"), CustomEditorAlias(\"FlaxFmod.Editor.FolderPathEditor\")")
String EditorStorageRelativeFolderPath = TEXT("Content/FMOD");
/// <summary>
/// The folder where the .fspro project is located.
/// This is relative to the project folder.
/// </summary>
API_FIELD(Attributes="EditorDisplay(\"Editor\"), CustomEditorAlias(\"FlaxFmod.Editor.FolderPathEditor\")")
String FmodStudioRelativeProjectPath = TEXT("FMOD");
/// <summary>
/// Editor Only. The environment variable where Fmod studio location is stored. Absolute path will be used if this does not exist.
/// </summary>
API_FIELD(Attributes="EditorDisplay(\"Editor\")") String FmodStudioLocationEnvironmentVariable = TEXT("FMOD_STUDIO");
/// <summary>
/// Editor Only. The absolute install location of fmod studio. Used if the environment variable is not found.
/// </summary>
API_FIELD(Attributes="EditorDisplay(\"Editor\")") String FmodStudioInstallLocation = TEXT("C:\\Program Files/FMOD SoundSystem/FMOD Studio 2.03.08"); // Todo: make this a file path editor
// Init settings
/// <summary>
/// The max channels that can be used with the FMOD system when initialized.
/// </summary>
API_FIELD(Attributes="EditorDisplay(\"Init\"), Limit(0)") int MaxChannels = 512;
/// <summary>
/// Loads the sample data from banks when they are loaded. Increases memory usage.
/// </summary>
API_FIELD(Attributes="EditorDisplay(\"Init\")") bool PreloadBankSampleData = true;
};
| 412 | 0.943532 | 1 | 0.943532 | game-dev | MEDIA | 0.557056 | game-dev,desktop-app | 0.781395 | 1 | 0.781395 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.