text
stringlengths 8
6.88M
|
|---|
#ifndef STEK_HPP
#define STEK_HPP
#include "vect.hpp"
class Stek : private Vect {
private:
int* arr;
int size;
public:
Stek ();
~Stek ();
Stek (Stek& obj);
Stek(Stek&& obj);
Stek (int a);
void pushStek (int a);
void popStek ();
};
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2012 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#ifndef DESKTOPOPUIINFO_H
#define DESKTOPOPUIINFO_H
#include "modules/pi/ui/OpUiInfo.h"
#define g_desktop_op_ui_info static_cast<DesktopOpUiInfo*>(g_op_ui_info)
/**
* DesktopOpUiInfo extends the OpUiInfo porting interface
* with functionality specific for the desktop projects.
*/
class DesktopOpUiInfo : public OpUiInfo
{
public:
/**
* Returns the color a non active persona window is dimmed with
* Format: 0xAABBGGRR
*/
virtual UINT32 GetPersonaDimColor() const
{
return OP_RGBA(255, 255, 255, 76);
}
/**
* Returns whether touch is available as an input method
*/
virtual bool IsTouchInputAvailable() { return false; }
/**
* Returns whether touch events support is wanted on web pages.
*/
virtual bool IsTouchEventSupportWanted() { return false; }
/**
* Returns whether we want a touch optimized UI
*/
virtual bool IsTouchUIWanted() { return false; }
};
#endif // DESKTOPOPUIINFO_H
|
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "ListeningItem.h"
#include "TestGlowItem.generated.h"
/**
*
*/
UCLASS()
class HYPOXIA_API ATestGlowItem : public AListeningItem
{
GENERATED_BODY()
public:
ATestGlowItem();
virtual void Hear(float volume) override;
virtual void Tick(float deltaTime) override;
private:
UPointLightComponent* Light;
float GlowIntensity;
};
|
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <algorithm>
#include <QMainWindow>
#include <QAction>
#include <QFileDialog>
#include <QMessageBox>
#include <QDateTime>
#include <QSettings>
#include <QMouseEvent>
#include <QVector>
#include <QMap>
#include <QTimer>
#include <QDebug>
#include <QRadioButton>
#include <opencv2/opencv.hpp>
#include "velocalib.h"
#include "coordinateconvertion.h"
#include "colormap.h"
#include "coordinatetransform.h"
/**
* @brief 记录位置信息
*/
class Position {
public:
double x;
double y;
double z;
double heading;
double pitch;
double roll;
Position()
: x(0), y(0), z(0), heading(0), pitch(0), roll(0) {}
Position(double x, double y, double z, double heading, double pitch, double roll)
: x(x), y(y), z(z), heading(heading), pitch(pitch), roll(roll) {}
};
#define PIXELSIZE 0.5
#define GRID 81
#define VELOPIXELSIZE 0.1
#define VELOGRID (PIXELSIZE * GRID / VELOPIXELSIZE)
#define RATIO (PIXELSIZE / VELOPIXELSIZE)
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow {
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private:
Ui::MainWindow *ui;
/**
* @brief 根据配置文件打开相关文件
*/
bool openFile();
/**
* @brief 导出标注的栅格地图
*/
void exportFile();
/**
* @brief 只导出栅格地图背景
*/
void exportBackground();
/**
* @brief exportLabelMap
*/
void exportLabelMap();
/**
* @brief 导入相关文件
*
* 需要对应的文件在openFile中已经被正确打开
*/
void loadFile();
/**
* @brief 扫描输入文件,把必要的信息存储在内存中
*/
void scan();
/**
* @brief 设置需要可视化的时间范围
*/
void setTime();
/**
* @brief 执行可视化
*/
void execute();
cv::Mat img;
cv::Mat imgBackground;
cv::Mat originMap;
cv::Mat maskMap;
cv::Mat veloImg;
cv::Mat veloMap;
cv::Mat camImg, cam, cam_raw;
bool initialized; /** 数据是否初始化 */
void fillGrid(cv::Mat mat, int m, int n, double pixelSize, cv::Scalar color = cv::Scalar(0, 0, 0));
void fillCircle(cv::Mat mat, int m, int n, double pixelSize, cv::Scalar color = cv::Scalar(0, 0, 0));
void setGridMask(cv::Mat mat, int m, int n, int value);
void setGridMaskF(cv::Mat mat, int m, int n, float value);
QVector<QPoint> calculateLine(QPoint p1, QPoint p2);
QVector<QPoint> calculateInner(QVector<QPoint> polygon);
QSettings *setting;
CoordinateConvertion coord;
void rotate(X::Point3d &p, double heading, double pitch = 0, double roll = 0);
QMap<int, cv::Scalar> colorTable;
int currentType;
QString graphType;
QVector<QPoint> pointStack;
QString pointType;
int startTime, endTime;
QString velodyneFilename, gpsFilename, imuFilename;
QString ladybugFilename, ladybugTimeFilename;
cv::VideoCapture video;
QTimer renderTimer;
QVector<int> gpsTimeList;
QVector<Position> posList;
QVector<int> veloTimeList;
QVector<int64> veloPosList;
QVector<int> cameraTimeList;
QVector<int> imageFrameList;
VeloCalib innerCalib;
QString calibFilename;
QMap<int, QString> labelGroup;
/**
* @brief 更新所有需要可视化的图像
*/
void updateImage();
/**
* @brief 把标注的激光点绘制到图像上
* @param laser 激光点序列
* @param color 和激光点序列对应的颜色序列
* @param image 被绘制的图像
*/
void drawCalibVelodyneOnImage(QVector<cv::Point3d> laser, QVector<cv::Scalar> color, cv::Mat& image);
protected:
void mousePressEvent(QMouseEvent *event);
void mouseMoveEvent(QMouseEvent *event);
void keyPressEvent(QKeyEvent *event);
};
#endif // MAINWINDOW_H
|
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
void GetInput(string& s){
cin>>s;
if(not(s=="가위"||s=="바위"||s=="보"))
throw "\"가위\", \"바위\", \"보\" 중에서만 선택하세요.";
}
void ComputerInput(string& t){
srand((unsigned int)time(NULL));
int n=rand()%3;
if (n==0)
t="가위";
else if(n==1)
t="바위";
else
t="보";
}
int main(){
string s;
string t;
try{
cout<<"가위, 바위, 보 게임입니다.\n";
cout<<"무엇을 내시겠습니까 : ";
GetInput(s);
ComputerInput(t);
cout<<"컴퓨터는 "<<t<<"를 냈습니다.\n\n";
if((s=="가위"&&t=="바위")||(s=="바위"&&t=="보")||(s=="보"&&t=="가위"))
cout<<"당신이 졌습니다.\n";
else if((s=="가위"&&t=="가위")||(s=="바위"&&t=="바위")||(s=="보"&&t=="보"))
cout<<"비겼습니다.\n";
else
cout<<"당신이 이겼습니다.\n";
}
catch(const char* e){
cerr<<"오류 : "<<e<<endl;
return -1;
}
catch(...){
cerr<<"오류";
}
return 0;
}
|
// Blood_Node.cpp
// Ben Howe
// COSC 2030
// 10/24/2018
/*
Modified node class that was provided for Lab 2.
Modifications:
- converted from singly-linked to doubly-linked
- additional data elements added
*/
#include "Blood_Node.h"
Blood_Node::Blood_Node(float min, float max, string sum, unsigned long delta, unsigned long cnt)
: min_(min), max_(max), sum_(sum), delta_(delta), cnt_(cnt),prev_(NULL), next_(NULL)
{
//cout << "Blood_Node( " << entry_ << ", p_"<< prev_ << ", n_" << next_ << " ) created at " << this << endl;
}
Blood_Node::Blood_Node(float min, float max, string sum, unsigned long delta, unsigned long cnt, Blood_Node * prev, Blood_Node * next)
: min_(min), max_(max), sum_(sum), delta_(delta), cnt_(cnt), prev_(prev), next_(next)
{
//cout << "Blood_Node( " << entry_ << ", p_" << prev_ << ", n_" << next_ << " ) created at " << this << endl;
}
Blood_Node::~Blood_Node()
{
//cout << "Blood_Node( " << entry_ << ", p_" << prev_ << ", n_" << next_ << " ) created at " << this << endl;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style: "stroustrup" -*-
*
* Copyright (C) 2012 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#ifndef MEDIATHREAD_H
#define MEDIATHREAD_H
#ifdef MEDIA_HTML_SUPPORT
#include "modules/dom/domenvironment.h"
#include "modules/dom/domeventtypes.h"
#include "modules/ecmascript_utils/essched.h"
#include "modules/ecmascript_utils/esthread.h"
#include "modules/util/simset.h"
class MediaThread;
/** An interface for observing events on MediaThreads. */
class MediaThreadListener
{
public:
virtual ~MediaThreadListener() {}
/** Called when a thread has finished.
*
* @param thread The thread that finished.
*/
virtual void OnThreadFinished(MediaThread* thread) = 0;
};
/** Represents a thread which handles a media event. */
class MediaThread
: public ListElement<MediaThread>
{
public:
/** Construct a new MediaThread.
*
* @param listener An object that will observe events on the thread.
* @param thread The actual ECMAScript event thread.
*/
MediaThread(MediaThreadListener* listener, ES_Thread* thread);
/** Is this a timeupdate event handler thread? */
BOOL IsTimeUpdateThread() const;
/** Has this thread started?
*
* @return TRUE if the thread has started, FALSE if it only is scheduled
* to start.
*/
BOOL IsStarted() const { return m_thread->IsStarted(); }
/** Cancel a thread (even if the thread has started).
*
* @return OpStatus::OK, or OpStatus::ERR_NO_MEMORY. Note that the
* cancelling itself will always succeed; only thread signalling
* can fail.
*/
OP_STATUS Cancel();
private:
/** Called when a signal is received from @c m_thread. */
void OnThreadSignal();
/** This class is an implementation of ES_ThreadListener.
*
* Because both ListElement and ES_ThreadListener inherit from Link,
* we use a nested class to resolve ambiguities.
*/
class Listener
: public ES_ThreadListener
{
public:
Listener(MediaThread* owner);
// Implements ES_ThreadListener.
virtual OP_STATUS Signal(ES_Thread* thread, ES_ThreadSignal signal);
private:
MediaThread* m_owner;
};
// This object listens for events on @c m_thread.
Listener m_proxy_listener;
// An object which receives notifications when something significant
// happens to the MediaThread.
MediaThreadListener* m_listener;
// The actual ECMAScript thread.
ES_Thread* m_thread;
// For access to OnThreadSignal.
friend class Listener;
};
/** An interface for observing events on MediaThreadQueues.
*
* A class may implement this interface if it needs to know when
* there are no more queued threads of a certain type. This can
* for example be used to ensure that events are fired one after
* another.
*/
class MediaThreadQueueListener
{
public:
virtual ~MediaThreadQueueListener() {}
/** The last timeupdate event handler has finished.
*
* In other words, this is called when the observed MediaThreadQueue
* transitions from a state of one (or more) timeupdate event
* handlers, to a state of zero timeupdate event handlers.
*/
virtual void OnTimeUpdateThreadsFinished() = 0;
};
/** Create and keep track of a set of related event handler threads.
*
* One feature of this class is the ability to cancel the queued event
* threads, or "tasks" as it were in HTML5. It can also keep track of the
* number of running (and scheduled) event handler threads of a certain event
* type. This is useful for clients which do not wish to queue an event handler
* thread of a certain type if one such event handler is already running, or
* scheduled to run.
*
* @see http://www.whatwg.org/html#queue-a-task
*/
class MediaThreadQueue
: public MediaThreadListener
{
public:
/** Construct a new MediaThreadQueue.
*
* @param listener An observer of significant events in the MediaThreadQueue.
*/
MediaThreadQueue(MediaThreadQueueListener* listener);
/** Queue an event in the specified DOM_Environment.
*
* @param environment The DOM_Environment to fire the event in.
* @param data The event data for DOM_Environment::HandleEvent.
* @return OpStatus::OK on success, or OpStatus::ERR_NO_MEMORY.
*/
OP_STATUS QueueEvent(DOM_Environment* environment, const DOM_Environment::EventData &data);
/** Cancel all MediaThreads which have not yet started.
*
* MediaThreads which have already started will be allowed to finish, and
* the MediaThreadQueue will continue to keep track of them until they do
* finish.
*/
void CancelAll();
/** Is a timeupdate event thread is running, or scheduled to run? */
BOOL IsTimeUpdateQueued() const { return m_timeupdate_queued > 0; }
private:
/** Cancel a scheduled MediaThread.
*
* If the provided thread is already started, the thread will be allowed
* to finish. If the thread is merely scheduled, it will be cancelled.
*
* @param thread The MediaThread to cancel (if possible).
*/
void Cancel(MediaThread* thread);
/** Remove a MediaThread from the list of threads.
*
* Calling this simply causes the MediaThreadQueue to stop listening
* for threads signals from the specified thread, and delete all
* references to it. It does not cancel the thread.
*
* @param thread The MediaThread to remove from the list.
*/
void Remove(MediaThread* thread);
// Implements MediaThreadListener.
virtual void OnThreadFinished(MediaThread* thread);
// An object which receives notifications when something significant
// happens to the MediaThreadQueue.
MediaThreadQueueListener* m_listener;
// The number of queued timeupdate event threads.
unsigned m_timeupdate_queued;
// The list of queued threads. Some of these may be in progress, others
// may simply be scheduled to run.
AutoDeleteList<MediaThread> m_threads;
};
#endif // MEDIA_HTML_SUPPORT
#endif // MEDIATHREAD_H
|
// Copyright 2017 Elias Kosunen
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// This file is a part of scnlib:
// https://github.com/eliaskosunen/scnlib
#ifndef SCN_UTIL_EXPECTED_H
#define SCN_UTIL_EXPECTED_H
#include "memory.h"
namespace scn {
SCN_BEGIN_NAMESPACE
/**
* expected-like type.
* For situations where there can be a value in case of success or an error
* code.
*/
template <typename T, typename Error, typename Enable>
class expected;
/**
* expected-like type for default-constructible success values.
* Not optimized for space-efficiency (both members are stored
* simultaneously).
* `error` is used as the error value and discriminant flag.
*/
template <typename T, typename Error>
class expected<T,
Error,
typename std::enable_if<
std::is_default_constructible<T>::value>::type> {
public:
using success_type = T;
using error_type = Error;
constexpr expected() = default;
constexpr expected(success_type s) : m_s(s) {}
constexpr expected(error_type e) : m_e(e) {}
SCN_NODISCARD constexpr bool has_value() const noexcept
{
return m_e == Error{};
}
constexpr explicit operator bool() const noexcept
{
return has_value();
}
constexpr bool operator!() const noexcept
{
return !operator bool();
}
SCN_CONSTEXPR14 success_type& value() & noexcept
{
return m_s;
}
constexpr success_type value() const& noexcept
{
return m_s;
}
SCN_CONSTEXPR14 success_type value() && noexcept
{
return SCN_MOVE(m_s);
}
SCN_CONSTEXPR14 error_type& error() noexcept
{
return m_e;
}
constexpr error_type error() const noexcept
{
return m_e;
}
private:
success_type m_s{};
error_type m_e{error_type::success_tag()};
};
/**
* expected-like type for non-default-constructible success values.
* Not optimized for space-efficiency.
* `error` is used as the error value and discriminant flag.
*/
template <typename T, typename Error>
class expected<T,
Error,
typename std::enable_if<
!std::is_default_constructible<T>::value>::type> {
public:
using success_type = T;
using success_storage = detail::erased_storage<T>;
using error_type = Error;
expected(success_type s) : m_s(SCN_MOVE(s)) {}
constexpr expected(error_type e) : m_e(e) {}
SCN_NODISCARD constexpr bool has_value() const noexcept
{
return m_e == Error{};
}
constexpr explicit operator bool() const noexcept
{
return has_value();
}
constexpr bool operator!() const noexcept
{
return !operator bool();
}
SCN_CONSTEXPR14 success_type& value() noexcept
{
return *m_s;
}
constexpr const success_type& value() const noexcept
{
return *m_s;
}
SCN_CONSTEXPR14 error_type& error() noexcept
{
return m_e;
}
constexpr error_type error() const noexcept
{
return m_e;
}
private:
success_storage m_s{};
error_type m_e{error_type::success_tag()};
};
template <typename T,
typename U = typename std::remove_cv<
typename std::remove_reference<T>::type>::type>
expected<U> make_expected(T&& val)
{
return expected<U>(std::forward<T>(val));
}
SCN_END_NAMESPACE
} // namespace scn
#endif
|
#include <iostream>
#include <sstream>
#include <string>
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
return 0;
}
|
#include "InfoBoard.h"
#include "Serial.h"
#include "Command.h"
#include "Util.h"
#include "Maths.h"
#include <iostream>
InfoBoard::InfoBoard(int serialId) : serialId(serialId), serial(NULL), errorRaised(false), goReceived(false), goRequested(false), firstAngle(true), targetSide(Side::UNKNOWN) {
serial = new Serial();
if (serial->open(serialId) == Serial::OK) {
std::cout << "+ InfoBoard found on port '" << serial->getPortName() << "'" << std::endl;
} else {
std::cout << "- Failed to open InfoBoard serial #" << serialId << " on any of the serial ports" << std::endl;
}
};
InfoBoard::~InfoBoard() {
if (serial != NULL) {
delete serial;
serial = NULL;
}
}
void InfoBoard::addListener(InfoBoardListener* listener) {
listeners.push_back(listener);
}
void InfoBoard::setTargetSide(Side side) {
targetSide = side;
if (side == Side::BLUE) {
serial->write("<goal:0>");
} else if (side == Side::YELLOW) {
serial->write("<goal:1>");
}
}
void InfoBoard::setGo(bool mode) {
goRequested = mode;
goReceived = true;
if (goRequested) {
serial->write("<start:1>");
} else {
serial->write("<start:0>");
}
}
void InfoBoard::step(double dt) {
if (!serial->isOpen()) {
return;
}
serial->write("<angle>");
std::string message;
while (serial->available() > 0) {
message = serial->read();
if (Command::isValid(message)) {
Command cmd = Command::parse(message);
if (cmd.name == "goal" && cmd.params.size() == 1) {
int sideValue = Util::toInt(cmd.params[0]);
bool sideChanged = false;
if (sideValue == 0 && targetSide != Side::BLUE) {
targetSide = Side::BLUE;
sideChanged = true;
} else if (sideValue == 1 && targetSide != Side::YELLOW) {
targetSide = Side::YELLOW;
sideChanged = true;
}
serial->write("<goal:" + Util::toString(sideValue) + ">");
if (sideChanged) {
for (std::vector<InfoBoardListener*>::iterator it = listeners.begin(); it != listeners.end(); it++) {
(*it)->onTargetSideChange(targetSide);
}
}
} else if (cmd.name == "start" && cmd.params.size() == 1) {
int startValue = Util::toInt(cmd.params[0]);
bool goChanged = false;
if (startValue == 0 && (!goReceived || goRequested != false)) {
goRequested = false;
goReceived = true;
goChanged = true;
} else if (startValue == 1 && (!goReceived || goRequested != true)) {
goRequested = true;
goReceived = true;
goChanged = true;
}
serial->write("<start:" + Util::toString(startValue) + ">");
if (goChanged) {
for (std::vector<InfoBoardListener*>::iterator it = listeners.begin(); it != listeners.end(); it++) {
(*it)->onGoRequestedChange(goRequested);
}
}
} else if (cmd.name == "id") {
// never mind..
} else if (cmd.name == "Gyroscope" && cmd.params.size() == 1) {
if (firstAngle) {
std::cout << "! Ignoring first gyro angle reading" << std::endl;
firstAngle = false;
continue;
}
//float angle = Math::degToRad(Util::toFloat(cmd.params[0])) * -1.0f;
float angle = (float)(Util::toDouble(cmd.params[0]) / -1000000000.0);
/*int measurementNr = Util::toInt(cmd.params[1]);
std::cout << "@ ANGLE #" << measurementNr << ": " << angle << std::endl;*/
for (std::vector<InfoBoardListener*>::iterator it = listeners.begin(); it != listeners.end(); it++) {
(*it)->onGyroChange(angle);
}
} else {
std::cout << "- Invalid info-board command: " << cmd.name << " " << Util::toString(cmd.params) << std::endl;
}
}
}
if (targetSide == Side::UNKNOWN) {
serial->write("<goal>");
}
if (!goReceived) {
serial->write("<start>");
}
serial->write("<error:" + Util::toString(errorRaised || targetSide == Side::UNKNOWN || !goReceived ? 1 : 0) + ">");
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2008 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*/
#ifndef EOI_FRAGMENTS_H
#define EOI_FRAGMENTS_H
#include "modules/display/FontAtt.h"
#include "modules/img/image.h"
#include "modules/widgets/OpWidget.h"
struct EoiPaintInfo
{
EoiPaintInfo(OpWidget *root, COLORREF text_color, VisualDevice* vis_dev, OpPoint anchor_origin, OpRect paint_rect) :
root(root),
text_color(text_color),
vis_dev(vis_dev),
anchor_origin(anchor_origin),
paint_rect(paint_rect) { }
OpWidget *root;
COLORREF text_color;
VisualDevice* vis_dev;
OpPoint anchor_origin;
OpRect paint_rect;
};
class TextAnchorFragment;
/** Anchor fragment. Used with AnchorRegion.
*
* One AnchorFragment represents a fragment of the anchor, and it is either one
* image, or one piece of text.
*/
class AnchorFragment : public Link
{
protected:
OpRect rect;
int x;
int y;
public:
AnchorFragment() : x(0), y(0) {}
virtual ~AnchorFragment() { }
AnchorFragment* Suc() const { return (AnchorFragment*) Link::Suc(); }
AnchorFragment* Pred() const { return (AnchorFragment*) Link::Pred(); }
void ExpandRect(const OpRect& new_rect) { rect.UnionWith(new_rect); }
const OpRect& GetRect() const { return rect; }
virtual void SetRect(const OpRect& r, int internal_y) { rect = r; }
virtual void SetPos(int x, int y) { this->x = x; this->y = y; }
virtual void OffsetPosBy(int dx, int dy) { this->x += dx; this->y += dy; }
virtual int GetWidth() { return rect.width; }
virtual int GetHeight() { return rect.height; }
virtual OP_STATUS Paint(EoiPaintInfo& paint_info) = 0;
virtual TextAnchorFragment *GetTextAnchorFragment() { return NULL; }
virtual BOOL IsImageFragment() { return FALSE; }
};
/** Text fragment of an anchor. */
class TextAnchorFragment : public AnchorFragment
{
private:
OpWidgetString widgetstring;
OpMultilineEdit *multi_edit;
OpString text;
int max_width;
public:
TextAnchorFragment() : multi_edit(NULL), max_width(0) {}
OP_STATUS AppendText(const uni_char* txt, size_t length) { return text.Append(txt, length); }
const uni_char* GetText() { return text.CStr(); }
virtual void SetRect(const OpRect& r, int internal_y);
virtual void OffsetPosBy(int dx, int dy);
OP_STATUS UpdateWidgetString(OpWidget *widget, int max_width, BOOL wrap);
virtual int GetWidth();
virtual int GetHeight();
virtual OP_STATUS Paint(EoiPaintInfo& paint_info);
virtual TextAnchorFragment *GetTextAnchorFragment() { return this; }
};
/** Widget in an anchor. */
class WidgetAnchorFragment : public AnchorFragment
{
private:
public:
WidgetAnchorFragment(FormObject *form_obj) { }
virtual OP_STATUS Paint(EoiPaintInfo& paint_info) { return OpStatus::OK; }
};
/** Image in an anchor. */
class ImageAnchorFragment : public AnchorFragment
{
private:
Image img;
public:
ImageAnchorFragment(const Image& img) : img(img) { }
virtual OP_STATUS Paint(EoiPaintInfo& paint_info);
virtual BOOL IsImageFragment() { return TRUE; }
};
#endif // EOI_FRAGMENTS_H
|
// bytebear
// Creative Commons Attribution 3.0 License
// http://creativecommons.org/licenses/by/3.0/
class ByteBear {
public:
ByteBear();
~ByteBear();
unsigned char* d;
int Run(unsigned long t);
};
|
/* @author Aytaç Kahveci */
#ifndef KRLREAL_H
#define KRLREAL_H
#include <kuka_ros_open_comm/KRLVariable.h>
#include <string>
class KRLReal
{
private:
std::string name_;
int id_;
long readTime_;
KRLVariable* krl_var_;
public:
double value_ = (double) NULL;
KRLReal(){}
KRLReal(std::string name)
{
krl_var_ = new KRLVariable(name);
name_ = krl_var_->getName();
id_ = krl_var_->getId();
}
~KRLReal()
{
delete krl_var_;
}
double getValue()
{
return value_;
}
std::string getStringValue()
{
return std::to_string(value_);
}
void update(int id, std::string strValue, long readTime)
{
if( id_ != id)
{
throw std::runtime_error("The returned id does not match the variable id! Should not happen...");
}
readTime_ = readTime;
setValueFromString(strValue);
}
std::vector<unsigned char> getReadCommand()
{
return krl_var_->getReadCommand();
}
std::vector<unsigned char> getWriteCommand()
{
return krl_var_->getWriteCommand(getStringValue());
}
void setValue(double value)
{
value_ = value;
}
private:
void setValueFromString(std::string strValue)
{
std::string::size_type sz;
value_ = std::stod(strValue, &sz);
}
};
#endif
|
#include <SFML/Graphics.hpp>
#include "Constants.hh"
#include "World.hh"
void SineWave(sf::Vector2f &p, int time, int middle)
{
if (p.x < middle - 50 || p.x > middle + 50)
{
if (p.x < middle)
p.y += sin((p.x / 8) + time) * 20;
else
p.y += sin((p.x / 8) - time) * 20;
}
}
void disruptImg(sf::Image &initial, sf::Image &rendered, int time)
{
sf::Vector2f posBefore;
sf::Vector2f posAfter;
sf::Color color;
int Height = initial.getSize().y;
int Width = initial.getSize().x;
for (int y = 0; y < Height; y++)
{
for (int x = 0; x < Width; x++)
{
posAfter.x = x;
posAfter.y = y;
SineWave(posAfter, time, SCREEN_WIDTH / 2);
if (posAfter.x < 0 || posAfter.x > Width || posAfter.y < 0 || posAfter.y > Height)
color = sf::Color::White;
else
color = initial.getPixel(posAfter.x, posAfter.y);
rendered.setPixel(x, y, color);
}
}
}
|
// Created on: 2015-07-13
// Created by: Irina KRYLOVA
// Copyright (c) 2015 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _StepDimTol_ToleranceZoneTarget_HeaderFile
#define _StepDimTol_ToleranceZoneTarget_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <StepData_SelectType.hxx>
#include <Standard_Integer.hxx>
class Standard_Transient;
class StepDimTol_GeometricTolerance;
class StepDimTol_GeneralDatumReference;
class StepShape_DimensionalLocation;
class StepShape_DimensionalSize;
class StepDimTol_ToleranceZoneTarget : public StepData_SelectType
{
public:
DEFINE_STANDARD_ALLOC
//! Returns a ToleranceZoneTarget select type
Standard_EXPORT StepDimTol_ToleranceZoneTarget();
//! Recognizes a ToleranceZoneTarget Kind Entity that is :
//! 1 -> DimensionalLocation
//! 2 -> DimensionalSize
//! 3 -> GeometricTolerance
//! 4 -> GeneralDatumReference
//! 0 else
Standard_EXPORT Standard_Integer CaseNum (const Handle(Standard_Transient)& ent) const;
//! returns Value as a DimensionalLocation (Null if another type)
Standard_EXPORT Handle(StepShape_DimensionalLocation) DimensionalLocation() const;
//! returns Value as a DimensionalSize (Null if another type)
Standard_EXPORT Handle(StepShape_DimensionalSize) DimensionalSize() const;
//! returns Value as a GeometricTolerance (Null if another type)
Standard_EXPORT Handle(StepDimTol_GeometricTolerance) GeometricTolerance() const;
//! returns Value as a GeneralDatumReference (Null if another type)
Standard_EXPORT Handle(StepDimTol_GeneralDatumReference) GeneralDatumReference() const;
};
#endif // _StepDimTol_ToleranceZoneTarget_HeaderFile
|
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Person
{
public:
Person(int age)
{
this->age = age;
}
Person operator+(Person &p2)
{
Person p(this->age + p2.age);
return p;
}
int age;
};
#if 0
Person operator + (Person &p1, Person &p2)
{
Person p(p1.age + p2.age);
return p;
}
void test01()
{
Person p1(10);
Person p2(20);
Person p3 = p1 + p2;
cout << p3.age << endl;
}
#endif
void test02()
{
Person p1(10);
Person p2(20);
Person p3 = p1 + p2;
cout << p3.age << endl;
}
int main(int argc, char **argv)
{
test02();
return 0;
}
|
#include "shader_program.h"
#include <fstream>
#include <sstream>
// Shader base path is found by SDL the first time it is needed
std::string ShaderProgram::shader_base_path_ = "";
// The folder to look in relative to the base path
#define SHADER_FOLDER "shaders"
#ifdef _WIN32
#define PATH_SEPERATOR '\\'
#else
#define PATH_SEPERATOR '/'
#endif
ShaderProgram::ShaderProgram() :
vertex_shader_(0),
fragment_shader_(0)
{}
void ShaderProgram::init( std::string vertex_file_path, std::string fragment_file_path )
{
loadVertexSourceFile( vertex_file_path );
loadFragmentSourceFile( fragment_file_path );
init();
}
bool ShaderProgram::init()
{
bool success = true;
const GLchar* source_ptr = nullptr;
if( !vertex_source_.empty() )
{
vertex_shader_ = glCreateShader( GL_VERTEX_SHADER );
if( vertex_shader_ == 0 )
{
SDL_Log( "ERROR could not create vertex shader" );
success = false;
}
// Shader strings have to be converted to const GLchar* so OpenGL can compile them
source_ptr = (const GLchar*)vertex_source_.c_str();
glShaderSource( vertex_shader_, 1, &source_ptr, NULL );
glCompileShader( vertex_shader_ );
if( did_shader_compile_ok( vertex_shader_ ) )
vertex_source_.resize(0);
else
success = false;
}
else
{
SDL_Log( "ERROR vertex shader source was empty! (not set)" );
}
if( !fragment_source_.empty() )
{
// Create the fragment shader
fragment_shader_ = glCreateShader( GL_FRAGMENT_SHADER );
if( fragment_shader_ == 0 )
{
SDL_Log( "ERROR could not create fragment shader" );
success = false;
}
// Shader strings have to be converted to const GLchar* so OpenGL can compile them
source_ptr = (const GLchar*)fragment_source_.c_str();
glShaderSource( fragment_shader_, 1, &source_ptr , NULL );
glCompileShader( fragment_shader_ );
if( did_shader_compile_ok( fragment_shader_ ) )
fragment_source_.resize(0);
else
success = false;
}
else
{
SDL_Log( "ERROR fragment shader source was empty! (not set)" );
}
if( success ) {
// Create the shader program, attach the vertex and fragment shaders
program_ = glCreateProgram();
glAttachShader( program_, vertex_shader_ );
glAttachShader( program_, fragment_shader_ );
glBindFragDataLocation( program_, 0, "outColour" );
glLinkProgram( program_ );
// now cleanup the shaders
// TODO: it's possible we want to the same vertex/fagment/etc. shader multple times in different programs
// TODO: find a way of supporting this without the caller having to do extra work, on the other hand it might not be worth it
glDetachShader( program_, vertex_shader_ );
glDetachShader( program_, fragment_shader_ );
glDeleteShader( vertex_shader_ );
glDeleteShader( fragment_shader_ );
}
// Return true on success, false on error
return success;
}
void ShaderProgram::shutdown()
{
glDeleteProgram( program_ );
glDeleteShader( vertex_shader_ );
glDeleteShader( fragment_shader_ );
}
void ShaderProgram::bind() const
{
glUseProgram( program_ );
}
GLint ShaderProgram::getUniformLocation( const GLchar* name ) const
{
GLint uniform = glGetUniformLocation( program_, name );
if( uniform == -1 ) {
SDL_Log("ERROR did not find uniform '%s' in shader program '%i'", name, program_ );
}
return uniform;
}
GLint ShaderProgram::getAttribLocation( const GLchar* name ) const
{
GLint attribute = glGetAttribLocation( program_, name );
if( attribute == -1 ) {
SDL_Log("ERROR did not find attribute '%s' in shader program '%i'", name, program_ );
}
return attribute;
}
bool ShaderProgram::loadVertexSourceFile( std::string file_path )
{
return load_file( file_path, &vertex_source_ );
}
bool ShaderProgram::loadFragmentSourceFile( std::string file_path )
{
return load_file( file_path, &fragment_source_ );
}
// TODO: convert this to SDL rw ops and move to seperate header file
bool ShaderProgram::load_file( std::string filename, std::string* file_contents )
{
// Use SDL to get the base resource path the first time only;
if( shader_base_path_ == "" )
{
get_shader_base_path();
}
std::ifstream file( shader_base_path_ + filename );
if( !file.good() )
{
SDL_Log("Could not load %s!", filename.c_str() );
return false;
}
std::stringstream buffer;
buffer << file.rdbuf();
*file_contents = buffer.str();
return true;
}
bool ShaderProgram::did_shader_compile_ok( GLuint shader )
{
// Check the shader was compiled succesfully
GLint status;
glGetShaderiv( shader, GL_COMPILE_STATUS, &status );
if( status != GL_TRUE )
{
// Get the length of the error log
GLint log_length = 0;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &log_length);
// Now get the error log itself
GLchar* buffer = new GLchar[log_length];
glGetShaderInfoLog( shader, log_length, NULL, buffer );
// Print the error
// TODO: if we have the source then could we print the line that was broken?
SDL_Log( "ERROR: compiling shader..." );
SDL_Log( "%s", buffer );
delete[] buffer;
return false;
}
return true;
}
void ShaderProgram::get_shader_base_path()
{
// Use SDL to get the base path of the exe
char* charPath = SDL_GetBasePath();
// Add the shader folder to the project base path and a seperator on the end
shader_base_path_ = std::string(charPath) + SHADER_FOLDER + PATH_SEPERATOR;
// Free the SDL allocated string
SDL_free(charPath);
}
|
#ifndef SPRITEBATCH_H
#define SPRITEBATCH_H
#include "../maths/MathCore.h"
#include "RecTangle.h"
#include "SystemDefs.h"
class SpriteBatch
{
public:
SpriteBatch();
~SpriteBatch();
//Function: Initialize SpriteBatch
//PostCondition: SpriteBatch is initialized
void Initialize();
//Function: Render 2D plane
//PostCondition: 2D Plane rendered
void Draw(RecTangle& rect);
//Function: Render 2D plane
//PostCondition: 2D Plane rendered
void Draw(RecTangle& rect, Vector2 pTexs[4]);
//Function: Render 2D plane
//PostCondition: 2D Plane rendered
void Draw(RecTangle& rect, Vector2 pTexs[4], float pScale);
//Function: Render 2D plane
//PostCondition: 2D Plane rendered
void Draw(RecTangle& rect, float pScale);
//Function: Renders a 2D plane
//PostCondition: 2D Plane rendered
void Draw(RecTangle& rect, RecTangle& sourceRect);
private:
U32 m_vertexBufferID;
U32 m_texBufferID;
U32 m_indexBufferID;
U32 m_vertexArrayID;
int m_indicesCount;
U32 m_indices[6];
Vector3 m_verts[4];
Vector2 m_texs[4];
};
#endif
|
#include <stdio.h>
#define MAXN 10
typedef float ElementType;
ElementType Median( ElementType A[], int N );
int main ()
{
ElementType A[MAXN];
int N, i;
scanf("%d", &N);
for ( i=0; i<N; i++ )
scanf("%f", &A[i]);
printf("%.2f\n", Median(A, N));
return 0;
}
#include <stdlib.h>
#include <limits.h>
int compare_ElementType(const void* a, const void* b)
{
ElementType arg1 = *(const ElementType*)a;
ElementType arg2 = *(const ElementType*)b;
if (arg1 < arg2) return 1;
if (arg1 > arg2) return -1;
return 0;
// return (arg1 > arg2) - (arg1 < arg2); // possible shortcut
}
ElementType Median( ElementType A[], int N ){
int size = sizeof A / sizeof *A;
qsort(A, size, sizeof(ElementType), compare_ElementType);
return A[N/2];
}
|
// https://oj.leetcode.com/problems/powx-n/
class Solution {
public:
double pow(double x, int n) {
// not a number
volatile double t = x;
if (t != t) {
return x;
}
if (x == 1.0) {
return 1.0;
} else if (x == -1.0) {
return (n % 2 == 0) ? 1.0: -1.0;
}
double result = 1.0;
if (n < 0) {
n = -n;
while (n-- > 0) {
result = result / x;
if (abs(result) < numeric_limits<double>::epsilon()) {
return 0.0;
}
}
} else {
while (n-- > 0) {
result = result * x;
if (abs(result) < numeric_limits<double>::epsilon()) {
return 0.0;
}
}
}
return result;
}
};
|
//任意一个5位数,比如:34256,
//把它的各位数字打乱,重新排列,可以得到一个最大的数:65432,一个最小的数23456。
//求这两个数字的差,得:41976,把这个数字再次重复上述过程(如果不足5位,则前边补0)。
//如此往复,数字会落入某个循环圈(称为数字黑洞)。
//比如,刚才的数字会落入:[82962, 75933, 63954, 61974] 这个循环圈。
#include <iostream>
#include <vector>
#include <algorithm>
#define number 5
using namespace std;
vector<int> heidong;
vector<int> zonghe;
vector<int>::iterator it;
int get_max_number(int x){
int a[number]={0,0,0,0,0};
int max=0;
int t=0,i;
for(i=0;i<number;i++){
a[i]=x%10;
x=x/10;
}
for(i=0;i<number;i++)
for(int j=i+1;j<number;j++)if(a[i]<a[j])swap(a[i],a[j]);
for(i=0;i<number;i++)
max=max*10+a[i];
return max;
}
int get_min_number(int x){
int a[number]={0,0,0,0};
int min=0,i;
for(i=0;i<number;i++){
a[i]=x%10;
x=x/10;
}
for(i=0;i<number;i++)
for(int j=i+1;j<number;j++)if(a[i]>a[j])swap(a[i],a[j]);
for(i=0;i<number;i++)
min=min*10+a[i];
return min;
}
void findheidong(int x){
int max,min,y;
max=get_max_number(x);
min=get_min_number(x);
y=max-min;
it=find(heidong.begin(),heidong.end(),y);
if( it == heidong.end() ){
heidong.push_back(y);
}
else if( (find(zonghe.begin(),zonghe.end(),*it)) != zonghe.end() ){
heidong.clear();
return;
}
else if(*it==0){
heidong.clear();
return;
}
else{
int i=0;
for(;it!=heidong.end();it++){
zonghe.push_back(*it);
if(i==0)cout<<"[";
if( (it+1) != heidong.end() ){
cout<<*it<<","<<" ";
}
else{
cout<<*it<<"]"<<"\n";
}
i++;
}
heidong.clear();
return;
}
findheidong(y);
}
int main(){
int i=10000;
for(i;i<100000;i++)findheidong(i);
return 0;
}
|
#include <stdio.h>
#include <string.h>
main()
{
char str[100];
char str1[100];
char str2[100];
int i,j,k,p,h=0,m=0;
printf("Enter a phrase:");
gets(str);
for(p=strlen(str);p>=0;p--)
{
str2[h]=str[p];
h++;
}
for(i=0;i<=strlen(str);i++)
{
if (str2[i]==' '||str2[i]=='\0')
{
k = 0;
for (j = m; j < i; j++)
{
// printf("i value %d\n",i);
str1[k] = str2[j];
k++;
}
str1[k] = '\0';
strrev(str1);
printf("%s ", str1);
m = i + 1;
}
}
for(p =0; p <= strlen(str); p++)
{
if(str[p] != ' ')
printf("%c",str[p]);
else
break;
}
printf("\n");
return 0;
}
|
template <typename T>
struct unique_handle
{
using THANDLE = typename T::HandleType;
unique_handle(THANDLE h) : handle(h) {}
//NON COPYABLE
unique_handle(const unique_handle&) = delete;
unique_handle& operator=(const unique_handle&) = delete;
//MOVEABLE
unique_handle(unique_handle&& other)
: handle(other.handle)
{
other.handle = T::INVALID_HANDLE;
}
unique_handle& operator = (unique_handle&& other)
{
if (this != &other) {
handle = other.handle;
other.handle = T::INVALID_HANDLE;
}
return *this;
}
~unique_handle()
{
if(handle != T::INVALID_HANDLE)
T::CloseHandle(handle);
}
operator THANDLE() const & noexcept { return handle; }
private:
THANDLE handle;
};
|
#include <bits/stdc++.h>
#define ll long long
#define ull unsigned long long
#define FOR(i,n) for(ll i=0;i<n;i++)
#define FOR1(i,n) for(ll i=1;i<n;i++)
#define FORn1(i,n) for(ll i=1;i<=n;i++)
#define FORmap(i,mp) for(auto i=mp.begin();i!=mp.end();i++)
#define vll vector<ll>
#define vs vector<string>
#define pb(x) push_back(x)
#define fast ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define mod 1000000007
using namespace std;
int main() {
// your code goes here
fast;
ll t;
cin>>t;
while(t--)
{
ll n,k;
cin>>n>>k;
if(k==1)
cout<<"NO\n";
else if(((n/k)%k)==0)
cout<<"NO\n";
else
cout<<"YES\n";
}
return 0;
}
|
/**
* Peripheral Definition File
*
* GPIO - General purpose and alternate function I/Os
*
* MCUs containing this peripheral:
* - STM32H7xx
*/
#pragma once
#include <cstdint>
#include <cstddef>
#include "io/reg/stm32/_common/gpio_v2.hpp"
namespace io {
namespace base {
static const size_t GPIOA = 0x58020000;
static const size_t GPIOB = 0x58020400;
static const size_t GPIOC = 0x58020800;
static const size_t GPIOD = 0x58020c00;
static const size_t GPIOE = 0x58021000;
static const size_t GPIOF = 0x58021400;
static const size_t GPIOG = 0x58021800;
static const size_t GPIOH = 0x58021c00;
static const size_t GPIOI = 0x58022000;
static const size_t GPIOJ = 0x58022400;
static const size_t GPIOK = 0x58022800;
}
static Gpio &GPIOA = *reinterpret_cast<Gpio *>(base::GPIOA);
static Gpio &GPIOB = *reinterpret_cast<Gpio *>(base::GPIOB);
static Gpio &GPIOC = *reinterpret_cast<Gpio *>(base::GPIOC);
static Gpio &GPIOD = *reinterpret_cast<Gpio *>(base::GPIOD);
static Gpio &GPIOE = *reinterpret_cast<Gpio *>(base::GPIOE);
static Gpio &GPIOF = *reinterpret_cast<Gpio *>(base::GPIOF);
static Gpio &GPIOG = *reinterpret_cast<Gpio *>(base::GPIOG);
static Gpio &GPIOH = *reinterpret_cast<Gpio *>(base::GPIOH);
static Gpio &GPIOI = *reinterpret_cast<Gpio *>(base::GPIOI);
static Gpio &GPIOJ = *reinterpret_cast<Gpio *>(base::GPIOJ);
static Gpio &GPIOK = *reinterpret_cast<Gpio *>(base::GPIOK);
}
|
#pragma once
class ITFMvMBossProgressUserAutoList {};
class CTFMvMBossProgressUser : public ITFMvMBossProgressUserAutoList
{
public:
virtual const char *GetBossProgressImageName() const = 0;
virtual float GetBossStatusProgress() const = 0;
};
|
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "common.hpp"
#include "game_asset_manager.hpp"
#include "native_engine.hpp"
#include "texture_manager.hpp"
#include <GLES3/gl3.h>
#include <GLES3/gl3ext.h>
enum TextureFileFormat {
TEXTUREFILE_KTX = 0,
TEXTUREFILE_ASTC,
TEXTUREFILE_UNKNOWN
};
// ETC2 bpp sizes
#if 0
static const uint32_t ETC2_BitsPerPixel[] = {
4, // GL_COMPRESSED_RGB8_ETC2
4, // GL_COMPRESSED_SRGB8_ETC2
4, // GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2
4, // GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2
8, // GL_COMPRESSED_RGBA8_ETC2_EAC
8 // GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC
};
#endif
// ASTC GL internalformat values
static const GLenum COMPRESSED_RGBA_ASTC_4x4_KHR = 0x93B0;
static const GLenum COMPRESSED_RGBA_ASTC_5x4_KHR = 0x93B1;
static const GLenum COMPRESSED_RGBA_ASTC_5x5_KHR = 0x93B2;
static const GLenum COMPRESSED_RGBA_ASTC_6x5_KHR = 0x93B3;
static const GLenum COMPRESSED_RGBA_ASTC_6x6_KHR = 0x93B4;
static const GLenum COMPRESSED_RGBA_ASTC_8x5_KHR = 0x93B5;
static const GLenum COMPRESSED_RGBA_ASTC_8x6_KHR = 0x93B6;
static const GLenum COMPRESSED_RGBA_ASTC_8x8_KHR = 0x93B7;
static const GLenum COMPRESSED_RGBA_ASTC_10x5_KHR = 0x93B8;
static const GLenum COMPRESSED_RGBA_ASTC_10x6_KHR = 0x93B9;
static const GLenum COMPRESSED_RGBA_ASTC_10x8_KHR = 0x93BA;
static const GLenum COMPRESSED_RGBA_ASTC_10x10_KHR = 0x93BB;
static const GLenum COMPRESSED_RGBA_ASTC_12x10_KHR = 0x93BC;
static const GLenum COMPRESSED_RGBA_ASTC_12x12_KHR = 0x93BD;
// .astc file format info
static const char *ASTC_EXTENSION_STRING = "GL_OES_texture_compression_astc";
static const int ASTC_MAGIC_SIZE = 4;
static const uint8_t ASTC_MAGIC[ASTC_MAGIC_SIZE] = {0x13, 0xAB, 0xA1, 0x5C};
struct ASTCHeader {
uint8_t magic[ASTC_MAGIC_SIZE];
uint8_t blockWidth;
uint8_t blockHeight;
uint8_t blockDepth;
uint8_t texWidth[3];
uint8_t texHeight[3];
uint8_t texDepth[3];
};
// .ktx file format info
static const int KTX_IDENTIFIER_SIZE = 12;
static const uint8_t KTX_11_IDENTIFIER[KTX_IDENTIFIER_SIZE] = {
0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
};
struct KTXHeader {
uint8_t identifier[12];
uint32_t endianness;
uint32_t glType;
uint32_t glTypeSize;
uint32_t glFormat;
uint32_t glInternalFormat;
uint32_t glBaseInternalFormat;
uint32_t pixelWidth;
uint32_t pixelHeight;
uint32_t pixelDepth;
uint32_t numberOfArrayElements;
uint32_t numberOfFaces;
uint32_t numberOfMipmapLevels;
uint32_t bytesOfKeyValueData;
};
// File format identification utility function
static TextureFileFormat GetFileFormat(const uint8_t *fileData, const size_t fileSize) {
if (fileSize > sizeof(ASTCHeader)) {
bool bValidMagic = true;
for (int i = 0; i < ASTC_MAGIC_SIZE; ++i) {
if (fileData[i] != ASTC_MAGIC[i]) {
bValidMagic = false;
break;
}
}
if (bValidMagic) {
return TEXTUREFILE_ASTC;
}
}
if (fileSize > sizeof(KTXHeader)) {
bool bValidIdentifier = true;
for (int i = 0; i < KTX_IDENTIFIER_SIZE; ++i) {
if (fileData[i] != KTX_11_IDENTIFIER[i]) {
bValidIdentifier = false;
break;
}
}
if (bValidIdentifier) {
return TEXTUREFILE_KTX;
}
}
return TEXTUREFILE_UNKNOWN;
}
// .astc texture file loader
static bool
CreateFromASTCFile(const uint8_t *fileData, const size_t fileSize, GLuint *textureID) {
bool success = false;
const ASTCHeader *header = reinterpret_cast<const ASTCHeader *>(fileData);
if (header->blockDepth == 1 && header->texDepth[0] == 1) {
GLsizei textureWidth =
header->texWidth[0] | (header->texWidth[1] << 8) | (header->texWidth[2] << 8);
GLsizei textureHeight = header->texHeight[0] | (header->texHeight[1] << 8) |
(header->texHeight[2] << 8);
GLenum textureFormat = 0;
const GLsizei textureSize = static_cast<const GLsizei>(fileSize - sizeof(ASTCHeader));
switch (header->blockWidth) {
case 4:
if (header->blockHeight == 4) textureFormat = COMPRESSED_RGBA_ASTC_4x4_KHR;
break;
case 5:
if (header->blockHeight == 4) textureFormat = COMPRESSED_RGBA_ASTC_5x4_KHR;
else if (header->blockHeight == 5) textureFormat = COMPRESSED_RGBA_ASTC_5x5_KHR;
break;
case 6:
if (header->blockHeight == 5) textureFormat = COMPRESSED_RGBA_ASTC_6x5_KHR;
else if (header->blockHeight == 6) textureFormat = COMPRESSED_RGBA_ASTC_6x6_KHR;
break;
case 8:
if (header->blockHeight == 5) textureFormat = COMPRESSED_RGBA_ASTC_8x5_KHR;
else if (header->blockHeight == 6) textureFormat = COMPRESSED_RGBA_ASTC_8x6_KHR;
else if (header->blockHeight == 8) textureFormat = COMPRESSED_RGBA_ASTC_8x8_KHR;
break;
case 10:
if (header->blockHeight == 5) textureFormat = COMPRESSED_RGBA_ASTC_10x5_KHR;
else if (header->blockHeight == 6)
textureFormat = COMPRESSED_RGBA_ASTC_10x6_KHR;
else if (header->blockHeight == 8)
textureFormat = COMPRESSED_RGBA_ASTC_10x8_KHR;
else if (header->blockHeight == 10)
textureFormat = COMPRESSED_RGBA_ASTC_10x10_KHR;
break;
case 12:
if (header->blockHeight == 10) textureFormat = COMPRESSED_RGBA_ASTC_12x10_KHR;
else if (header->blockHeight == 12)
textureFormat = COMPRESSED_RGBA_ASTC_12x12_KHR;
break;
default:
break;
}
if (textureFormat > 0) {
const void *textureData = reinterpret_cast<const void *>(header + 1);
glGetError();
glGenTextures(1, textureID);
glBindTexture(GL_TEXTURE_2D, *textureID);
glCompressedTexImage2D(GL_TEXTURE_2D, 0, textureFormat, textureWidth, textureHeight,
0, textureSize, textureData);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
GLenum glErr = glGetError();
if (glErr == GL_NO_ERROR) {
success = true;
} else {
ALOGE("CreateFromASTCFile glCompressedTexImage2D error %d", glErr);
}
}
}
return success;
}
// .ktx texture file loader
// This is not a robust KTX loader, ala libktx. It is only intended to load the KTX 1.1
// ETC2 format, mip-mapped 2D texture files included with this example
static bool
CreateFromKTXFile(const uint8_t *fileData, const size_t fileSize, GLuint *textureID,
uint32_t *textureMipCount) {
bool success = false;
const KTXHeader *header = reinterpret_cast<const KTXHeader *>(fileData);
// end of key-value data is padded to four-byte alignment
const size_t textureOffset = (sizeof(KTXHeader) + header->bytesOfKeyValueData + 3) & (~3);
const uint32_t *textureSize = reinterpret_cast<const uint32_t *>(fileData + textureOffset);
const uint8_t *textureData = reinterpret_cast<const uint8_t *>(textureSize + 1);
uint32_t currentMipWidth = header->pixelWidth;
uint32_t currentMipHeight = header->pixelHeight;
if (header->glInternalFormat >= GL_COMPRESSED_RGB8_ETC2 &&
header->glInternalFormat <= GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC) {
const GLint minFilter = header->numberOfMipmapLevels > 1 ?
GL_LINEAR_MIPMAP_LINEAR : GL_LINEAR;
// Clear error
glGetError();
glGenTextures(1, textureID);
glBindTexture(GL_TEXTURE_2D, *textureID);
uint32_t actualMipCount = 0;
for (uint32_t currentMipLevel = 0; currentMipLevel < header->numberOfMipmapLevels;
++currentMipLevel) {
const uint32_t currentMipSize = *textureSize;
glCompressedTexImage2D(GL_TEXTURE_2D, currentMipLevel, header->glInternalFormat,
currentMipWidth, currentMipHeight,
0, currentMipSize, textureData);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minFilter);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
GLenum glErr = glGetError();
if (glErr == GL_NO_ERROR) {
success = true;
} else {
success = false;
ALOGE("CreateFromKTXFile glCompressedTexImage2D error %d", glErr);
break;
}
textureSize = reinterpret_cast<const uint32_t *>(textureData + currentMipSize);
textureData = reinterpret_cast<const uint8_t *>(textureSize + 1);
currentMipWidth >>= 1;
currentMipHeight >>= 1;
++actualMipCount;
// Drop out if we fall block the 4x4 block size
if (currentMipWidth <= 4 || currentMipHeight <= 4) {
break;
}
}
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, actualMipCount - 1);
*textureMipCount = actualMipCount;
}
return success;
}
TextureManager::TextureManager() {
mDeviceSupportsASTC = false;
mLastTextureFormat = TEXTUREFORMAT_ETC2;
GLint extensionCount = 0;
glGetIntegerv(GL_NUM_EXTENSIONS, &extensionCount);
for (GLint i = 0; i < extensionCount; i++) {
const GLubyte *extensionString = glGetStringi(GL_EXTENSIONS, i);
if (strcmp(reinterpret_cast<const char *>(extensionString), ASTC_EXTENSION_STRING) == 0) {
mDeviceSupportsASTC = true;
break;
}
}
ALOGI("ASTC Textures: %s", (mDeviceSupportsASTC ? "Supported" : "Not Supported"));
}
TextureManager::~TextureManager() {
glBindTexture(GL_TEXTURE_2D, 0);
for (std::vector<TextureReference>::iterator iter = mTextures.begin(); iter != mTextures.end();
++iter) {
GLuint textureID = static_cast<GLuint>(iter->mTextureReference);
glDeleteTextures(1, &textureID);
}
mTextures.clear();
}
bool TextureManager::IsTextureLoaded(const char *textureName) {
TextureManager::TextureReference textureRef = FindReferenceForName(textureName);
return (textureRef.mTextureReference != TextureManager::INVALID_TEXTURE_REF);
}
bool TextureManager::LoadTexture(const char *textureName) {
bool success = false;
if (!IsTextureLoaded(textureName)) {
GameAssetManager *gameAssetManager = NativeEngine::GetInstance()->GetGameAssetManager();
uint64_t fileSize = gameAssetManager->GetGameAssetSize(textureName);
if (fileSize > 0) {
uint8_t *fileBuffer = static_cast<uint8_t *>(malloc(fileSize));
if (gameAssetManager->LoadGameAsset(textureName, fileSize, fileBuffer)) {
success = CreateTexture(textureName, fileSize, fileBuffer);
} else {
ALOGE("TextureManager: failed to load texture file: %s", textureName);
}
}
}
return success;
}
bool TextureManager::CreateTexture(const char *textureName, const size_t textureSize,
const uint8_t *textureData) {
bool success = false;
const TextureFileFormat fileFormat = GetFileFormat(textureData, textureSize);
GLuint textureID = 0;
uint32_t textureMipCount = 1;
if (fileFormat == TEXTUREFILE_ASTC && mDeviceSupportsASTC) {
success = CreateFromASTCFile(textureData, textureSize, &textureID);
mLastTextureFormat = TEXTUREFORMAT_ASTC;
} else if (fileFormat == TEXTUREFILE_KTX) {
success = CreateFromKTXFile(textureData, textureSize, &textureID, &textureMipCount);
mLastTextureFormat = TEXTUREFORMAT_ETC2;
} else {
ALOGE("TextureManager: unknown texture file format in file: %s", textureName);
}
if (success) {
mTextures.push_back(TextureManager::TextureReference(textureMipCount, textureName,
static_cast<uint64_t>(textureID)));
}
free((void *) textureData);
return success;
}
uint32_t TextureManager::GetTextureMipCount(const char *textureName) {
TextureManager::TextureReference textureRef = FindReferenceForName(textureName);
return textureRef.mTextureMipCount;
}
uint64_t TextureManager::GetTextureReference(const char *textureName) {
TextureManager::TextureReference textureRef = FindReferenceForName(textureName);
return textureRef.mTextureReference;
}
TextureManager::TextureReference TextureManager::FindReferenceForName(const char *textureName) {
for (std::vector<TextureReference>::iterator iter = mTextures.begin();
iter != mTextures.end(); ++iter) {
if (strcmp(textureName, iter->mTextureName) == 0) {
return *iter;
}
}
TextureManager::TextureReference emptyReference(0, NULL, INVALID_TEXTURE_REF);
return emptyReference;
}
|
#include <iostream>
#include <string>
#include <stdlib.h>
#include <stdio.h>
#ifdef __unix__
#include <unistd.h>
#endif
#include "sicarioClient.h"
#include "errors.h"
void catchError(unsigned short error) {
if(errorList[error].critical == true) {
std::cerr << errorList[error].text;
exit(error);
} else {
std::cerr << errorList[error].text;
}
}
// Warning: Platform-specific!
void sleepFor(unsigned long long seconds) {
sleep(seconds);
}
const std::string msg_copyright = "// Sicario_CPP // 2018 // Made by Erusima and Dante383 //\n\n";
int main(int argc, char** argv) {
std::cout << msg_copyright;
SicarioClient client(argv[1], 7319);
client.registerUser();
client.disconnect();
while(true) {
sleepFor(client.connInterval);
try {
client.reconnect();
client.loginUser(client.userKey);
std::string data = "";
do {
data = client.receiveData();
std::string result = client.interpretCommand(data);
client.sendData(result);
} while(data != "");
client.disconnect();
} catch(unsigned short error) {
catchError(error);
}
}
}
|
////////////////////////
// Filename: Models.h
////////////////////////
#pragma once
#include <d3d11.h>
#include <D3DX10math.h>
#include "TextureClass.h"
#include <fstream>
#include "objfilemodel.h"
#include "LightShaderClass.h"
#include "LightClass.h"
using namespace std;
/////////////////////////
// Class name: Models
/////////////////////////
class Models
{
private:
struct VertexType
{
D3DXVECTOR3 position;
D3DXVECTOR2 texture;
D3DXVECTOR3 normal;
};
ID3D11Buffer *m_vertexBuffer, *m_indexBuffer;
int m_vertexCount, m_indexCount;
TextureClass* m_Texture;
D3DXVECTOR3 m_position;
D3DXVECTOR3 m_rotation;
ObjFileModel* m_object;
float m_bounding_sphere_centre_x, m_bounding_sphere_centre_y, m_bounding_sphere_centre_z, m_bounding_sphere_centre_radius;
bool InitializeBuffers(ID3D11Device*);
void ShutdownBuffers();
void RenderBuffers(ID3D11DeviceContext*);
bool LoadTexture(ID3D11Device*, WCHAR*);
void ReleaseTexture();
bool LoadModel(char*, ID3D11Device*, ID3D11DeviceContext*);
public:
Models();
Models(const Models&);
~Models();
bool Initialize(ID3D11Device*, char*, WCHAR*, ID3D11DeviceContext*);
void Shutdown();
bool Render(ID3D11DeviceContext*, LightShaderClass*, D3DXMATRIX, D3DXMATRIX, D3DXMATRIX, LightClass*);
int GetIndexCount();
int GetVertexCount();
ID3D11ShaderResourceView* GetTexture();
//SceneNode requirered methods
void CalculateModelCentrePoint();
void CalculateBoundingSphereRadius();
float GetBoundingSphereRadius();
float GetBoundingSphereX();
float GetBoundingSphereY();
float GetBoundingSphereZ();
void SetPosition(float, float, float);
void SetRotation(float, float, float);
};
|
#include "nrfs.h"
#include <sys/time.h>
#define COUNT 50
char name[][10] = {"/file1", "/file2", "/file3", "/file4", "/file5", "/file6"};
nrfs fs;
nrfsFile file;
struct timeval tv;
long long t1, t2;
int thread_num;
int filesize;
char buf[0x10000010];
void filesystem_test()
{
int op, i;
char path[255] = {0};
struct timeval tv;
long long t1, t2;
while(true)
{
scanf("%d", &op);
switch(op)
{
case 1:
{
gettimeofday(&tv, NULL);
t1 = (tv.tv_sec * 1000 * 1000) + (tv.tv_usec);
for(i = 0; i < COUNT; i++)
{
sprintf(path, "/file_%d", i);
nrfsMknod(fs, path);
}
gettimeofday(&tv, NULL);
t2 = (tv.tv_sec * 1000 * 1000) + (tv.tv_usec);
printf("mknod 100 times, time cost: %d\n", (int)(t2 - t1));
break;
}
case 2:
{
gettimeofday(&tv, NULL);
t1 = (tv.tv_sec * 1000 * 1000) + (tv.tv_usec);
for(i = 0; i < COUNT; i++)
{
sprintf(path, "/file_%d", 1);
nrfsAccess(fs, path);
}
gettimeofday(&tv, NULL);
t2 = (tv.tv_sec * 1000 * 1000) + (tv.tv_usec);
printf("access 100 times, time cost: %d\n", (int)(t2 - t1));
break;
}
case 3:
{
FileMeta attr;
gettimeofday(&tv, NULL);
t1 = (tv.tv_sec * 1000 * 1000) + (tv.tv_usec);
for(i = 0; i < COUNT; i++)
{
sprintf(path, "/file_%d", 1);
nrfsGetAttribute(fs, path, &attr);
}
gettimeofday(&tv, NULL);
t2 = (tv.tv_sec * 1000 * 1000) + (tv.tv_usec);
printf("getattr 100 times, time cost: %d\n", (int)(t2 - t1));
break;
}
case 4:
{
memset(path, '\0', 255);
sprintf(path, "/dir");
nrfsCreateDirectory(fs, path);
gettimeofday(&tv, NULL);
t1 = (tv.tv_sec * 1000 * 1000) + (tv.tv_usec);
for(i = 0; i < COUNT; i++)
{
sprintf(path, "/dir/dir_%d", i);
nrfsCreateDirectory(fs, path);
}
gettimeofday(&tv, NULL);
t2 = (tv.tv_sec * 1000 * 1000) + (tv.tv_usec);
printf("mkdir 100 times, time cost: %d\n", (int)(t2 - t1));
break;
}
case 5:
{
char newpath[255] = {0};
memset(path, '\0', 255);
gettimeofday(&tv, NULL);
t1 = (tv.tv_sec * 1000 * 1000) + (tv.tv_usec);
for(i = 0; i < COUNT; i++)
{
sprintf(path, "/file_%d", i);
sprintf(newpath, "/file_%d", (i + 100));
nrfsRename(fs, path, newpath);
}
gettimeofday(&tv, NULL);
t2 = (tv.tv_sec * 1000 * 1000) + (tv.tv_usec);
printf("rename 100 times, time cost: %d\n", (int)(t2 - t1));
break;
}
case 6:
{
memset(path, '\0', 255);
gettimeofday(&tv, NULL);
t1 = (tv.tv_sec * 1000 * 1000) + (tv.tv_usec);
for(i = 0; i < COUNT; i++)
{
sprintf(path, "/file_%d", i + 100);
nrfsDelete(fs, path);
}
gettimeofday(&tv, NULL);
t2 = (tv.tv_sec * 1000 * 1000) + (tv.tv_usec);
printf("remove 100 times, time cost: %d\n", (int)(t2 - t1));
break;
}
case 7:
{
memset(path, '\0', 255);
gettimeofday(&tv, NULL);
t1 = (tv.tv_sec * 1000 * 1000) + (tv.tv_usec);
for(i = 0; i < COUNT; i++)
{
sprintf(path, "/dir/dir_%d", i);
nrfsDelete(fs, path);
}
gettimeofday(&tv, NULL);
t2 = (tv.tv_sec * 1000 * 1000) + (tv.tv_usec);
printf("rmdir 100 times, time cost: %d\n", (int)(t2 - t1));
nrfsDelete(fs, "/dir");
break;
}
case 8:
{
memset(path, '\0', 255);
gettimeofday(&tv, NULL);
t1 = (tv.tv_sec * 1000 * 1000) + (tv.tv_usec);
for(i = 0; i < COUNT; i++)
{
sprintf(path, "/dir/dir_%d", i);
nrfsTest(fs, 0);
}
gettimeofday(&tv, NULL);
t2 = (tv.tv_sec * 1000 * 1000) + (tv.tv_usec);
printf("test rpc 100 times, time cost: %d\n", (int)(t2 - t1));
break;
}
case 9:
{
memset(path, '\0', 255);
gettimeofday(&tv, NULL);
t1 = (tv.tv_sec * 1000 * 1000) + (tv.tv_usec);
for(i = 0; i < COUNT; i++)
{
sprintf(path, "/dir/dir_%d", i);
nrfsRawRPC(fs);
}
gettimeofday(&tv, NULL);
t2 = (tv.tv_sec * 1000 * 1000) + (tv.tv_usec);
printf("test RawRPC 100 times, time cost: %d\n", (int)(t2 - t1));
break;
}
default:
break;
}
}
}
void test(int i)
{
char path[25];
nrfsFile file;
sprintf(path, "/a%d", i);
int j;
for(j = 0; j < 0x10000010; j++)
buf[j] = 'a';
buf[1000] = 'b';
buf[10000] = 'b';
buf[0x1000000] = 'b';
buf[0x10000001] = 'b';
file = nrfsOpenFile(fs, path, O_CREAT);
nrfsWrite(fs, file, buf, 0x10000010, 0);
memset(buf, '\0', 0x10000010);
nrfsRead(fs, file, buf, 0x10000010, 0);
printf("%c %c %c %c", buf[1001], buf[10000], buf[0x1000001], buf[0x10000001]);
nrfsCloseFile(fs, file);
nrfsDelete(fs, path);
}
void test_client()
{
int i;
gettimeofday(&tv, NULL);
t1 = (tv.tv_sec * 1000 * 1000) + (tv.tv_usec);
for(i = 0; i < 1024; i++)
;//nrfsTest(fs, name[0]);
gettimeofday(&tv, NULL);
t2 = (tv.tv_sec * 1000 * 1000) + (tv.tv_usec);
printf("time cost: %d\n", (int)(t2 - t1));
}
int main(int argc, char* argv[])
{
if(argc < 2)
{
printf("Usage: ./nrfstest filesize");
return 0;
}
filesize = atoi(argv[1]);
fs = nrfsConnect("default", 0, 0);
// file = nrfsOpenFile(fs, name[0], 0);
// thread t[20];
// int i, ret;
// nrfsMknod(fs, "/a");
// nrfsWrite(fs, "/a", "a", 1, 1024 * 1024 -1);
// nrfsWrite(fs, "/a", "a", 1, 2 * 1024 * 1024 -1);
// nrfsWrite(fs, "/a", "a", 1, 3 * 1024 * 1024 -1);
// nrfsWrite(fs, "/a", "a", 1, 4 * 1024 * 1024 -1);
filesystem_test();
gettimeofday(&tv, NULL);
t1 = (tv.tv_sec * 1000 * 1000) + (tv.tv_usec);
//test(0);
gettimeofday(&tv, NULL);
t2 = (tv.tv_sec * 1000 * 1000) + (tv.tv_usec);
printf("time cost: %d\n", (int)(t2 - t1));
// nrfsCloseFile(fs, file);
//filesystem_test();
nrfsDisconnect(fs);
// FileMeta attr;
// fs = nrfsConnect("default", 10086, 13);
// nrfsMknod(fs, "/a");
// nrfsGetAttribute(fs, "/a", &attr);
// nrfsDelete(fs, "/a");
// nrfsDisconnect(fs);
}
|
//
// Created by Ilya on 1/21/2018.
//
#include <sstream>
#include "Mountain.h"
namespace mtm {
Mountain::Mountain(const std::string &name) : Area(name) {
this->dominating_group = "";
}
Mountain::~Mountain() = default;
static void isAreaLegit(const string &group_name, const string &clan,
map<string, Clan> &clan_map) {
auto it = clan_map.find(clan);
if (it == clan_map.end()) {
throw AreaClanNotFoundInMap();
}
if (!((it->second).doesContain(group_name))) {
throw AreaGroupNotInClan();
}
}
static bool isGroupInArea(const string &group_name, std::vector<GroupPointer> groups){
for(const auto &group: groups){
if(group->getName()==group_name) return true;
}
return false;
}
void Mountain::groupArrive(const string &group_name, const string &clan,
map<string, Clan> &clan_map) {
auto it = clan_map.find(clan);
isAreaLegit(group_name,clan, clan_map);
GroupPointer current_dominating_group = getDomintaingGroupObject(
clan_map);
GroupPointer arriving_group_p = (it->second.getGroup(group_name));
if (dominating_group.empty()) {
dominating_group = group_name;
groups.push_back(arriving_group_p);
current_dominating_group = getDomintaingGroupObject(clan_map);
} else {
if (arriving_group_p->getName() ==
current_dominating_group->getName() || isGroupInArea(group_name,groups)) {
throw AreaGroupAlreadyIn();
}
if (*arriving_group_p > *current_dominating_group &&
arriving_group_p->getClan() ==
current_dominating_group->getClan()) {
dominating_group = arriving_group_p->getName();
} else if (arriving_group_p->getClan() !=
current_dominating_group->getClan()) {
FIGHT_RESULT result = arriving_group_p->fight(
*current_dominating_group);
if (result == WON) {
dominating_group = arriving_group_p->getName();
}
}
groups.push_back(arriving_group_p);
}
}
GroupPointer
Mountain::getDomintaingGroupObject(map<string, Clan> &clan_map) {
GroupPointer current_dominating_group = nullptr;
for (const auto &clan_pair: clan_map) {
if ((clan_pair.second).doesContain(dominating_group)) {
current_dominating_group = ((clan_pair).second.getGroup(
dominating_group));
}
}
if (current_dominating_group != nullptr) {
dominating_clan = current_dominating_group->getClan();
}
return current_dominating_group;
}
const std::string
Mountain::getMaximumGroupMount(const std::string &group_name) {
if (groups.size() != 0) {
GroupPointer maximum = *(groups.begin());
for (size_t i = 0; i < groups.size(); i++) {
if (*groups[i] > *maximum &&
(*(groups[i])).getName() != group_name)
maximum = groups[i];
}
return maximum->getName();
} else {
return "";
}
}
const std::string
Mountain::getMaximumGroupClan(const std::string &group_name) {
if (groups.size() != 0) {
GroupPointer maximum = *(groups.begin());
for (size_t i = 0; i < groups.size(); i++) {
if ((*(groups[i])).getName() == dominating_clan &&
(*(groups[i])).getName() != group_name) {
maximum = *maximum > (*(groups[i])) ? maximum : groups[i];
}
}
if ((*maximum).getClan() == dominating_clan) {
return maximum->getName();
} else {
return "";
}
} else {
return "";
}
}
void Mountain::groupLeave(const std::string &group_name) {
int flag = 0;
if (group_name.empty()) {
throw AreaGroupNotFound();
}
for (auto i = groups.begin(); i != groups.end(); i++) {
if ((*i)->getName() == group_name) {
groups.erase(i);
flag++;
break;
}
}
if (flag == 0) {
throw AreaGroupNotFound();
}
if (dominating_group == group_name) {
std::string dominating_group_from_clan = getMaximumGroupClan(
group_name);
std::string dominating_group_overall = getMaximumGroupMount(
group_name);
if (!(dominating_group_from_clan.empty())) {
dominating_group = dominating_group_from_clan;
} else if (!(dominating_group_overall.empty())) {
dominating_group = dominating_group_overall;
} else {
dominating_group = "";
dominating_clan = "";
}
} else {
return;
}
}
}
|
#include "kmint/ufo/human.hpp"
#include "kmint/random.hpp"
#include <string>
namespace kmint::ufo {
namespace {
constexpr char const *image_path = "resources/human.png";
graphics::image human_image() { return graphics::image{image_path}; }
math::vector2d random_location() {
return {random_scalar(60, 900), random_scalar(60, 700)};
}
} // namespace
human::human()
: play::free_roaming_actor{ random_location() },
drawable_{ *this, human_image() } {
}
} // namespace kmint::ufo
|
///
/// @author Florian Feuerstein
///
/// @date 02/2017
///
/// @class ProjectionModel
///
/// @brief
///
#pragma once
#include <Eigen/Core>
#include <memory>
namespace Cvl
{
class ProjectionModel
{
public:
using Uptr = std::unique_ptr<ProjectionModel>;
ProjectionModel(
double focalLengthX,
double focalLengthY,
double principalPointX,
double principalPointY) :
mFocalLengthX(focalLengthX),
mFocalLengthY(focalLengthY),
mPrincipalPointX(principalPointX),
mPrincipalPointY(principalPointY)
{}
virtual ~ProjectionModel() {}
virtual ProjectionModel::Uptr clone() const = 0;
virtual Eigen::Array2Xd project(Eigen::Array2Xd const& distortedPoints) const = 0;
virtual Eigen::Array2Xd unproject(Eigen::Array2Xd const& imagePoints) const = 0;
Eigen::Matrix3d getPinholeCameraMatrix() const;
Eigen::Matrix3d getInversePinholeCameraMatrix() const;
void setParameters(double focalLengthX, double focalLengthY, double principalPointX, double principalPointY);
void setParameters(Eigen::Vector4d const & parameters);
Eigen::Vector4d getParameters() const;
protected:
double mFocalLengthX;
double mFocalLengthY;
double mPrincipalPointX;
double mPrincipalPointY;
};
}
|
#include<iostream>
#include<cstdio>
#include<map>
#include<set>
#include<vector>
#include<stack>
#include<queue>
#include<string>
#include<cstring>
#include<sstream>
#include<algorithm>
#include<cmath>
#define INF 0x3f3f3f3f
#define eps 1e-8
#define pi acos(-1.0)
using namespace std;
typedef long long LL;
bool vis[300100][2];
set<string> S;
string st,ss;
int main() {
cin >> st;
int n = st.size();
vis[n][0] = vis[n][1] = true;
if (n >= 7) {
vis[n-2][0] = true;
ss = "";ss += st[n-2];ss += st[n-1];S.insert(ss);
}
if (n >= 8) {
vis[n-3][1] = true;
ss = "";ss += st[n-3];ss += st[n-2];ss += st[n-1];S.insert(ss);
}
for (int i = n-4;i >= 5; i--) {
if (vis[i+2][1] || (vis[i+2][0] && (st[i] != st[i+2] || st[i+1] != st[i+3]))) {
vis[i][0] = true;
ss = "";ss += st[i];ss += st[i+1];S.insert(ss);
}
if (i+5 > n) continue;
if (vis[i+3][0] || (vis[i+3][1] && (st[i] != st[i+3] || st[i+1] != st[i+4] || st[i+2] != st[i+5]))) {
vis[i][1] = true;
ss = "";ss += st[i];ss += st[i+1];ss += st[i+2];S.insert(ss);
}
}
//for (int i = n-1;i >= 0; i--)
// cout << vis[i][0] << " " << vis[i][1] << endl;
printf("%d\n",S.size());
for (set<string>::iterator i = S.begin();i != S.end(); i++)
cout << *i << endl;
return 0;
}
|
#include<iostream>
#include<cstdio>
#include<map>
#include<set>
#include<vector>
#include<stack>
#include<queue>
#include<string>
#include<cstring>
#include<sstream>
#include<algorithm>
#include<cmath>
#define INF 0x3f3f3f3f
#define eps 1e-8
#define pi acos(-1.0)
using namespace std;
typedef long long LL;
int a[110][110],f[110][110][4];
int main() {
int n,m;
scanf("%d%d",&n,&m);
for (int k = 1;k <= n; k++) {
for (int i = 1;i <= m; i++) scanf("%d",&a[k][i]);
for (int i = 1;i <= m; i++)
for (int j = i+1;j <= m; j++) {
f[i][j][a[k][i]*2+a[k][j]]++;
}
}
int ans = n+1,x,y;
for (int i = 1;i <= m; i++)
for (int j = i+1;j <= m; j++) {
int rec = f[i][j][0];
for (int k = 1;k < 4; k++) rec = max(rec,f[i][j][k]);
//cout << i << " " << j << " " << rec << endl;
if (rec < ans) {
ans = rec;
x = i;y = j;
}
}
printf("%d\n%d %d\n",ans,x,y);
return 0;
}
|
#pragma once
#ifndef VERSION_H
constexpr int MAJOR_VERSION = 0;
constexpr int MINOR_VERSION = 0;
constexpr int BUILD_VERSION = 1;
constexpr int YEAR = 2020;
constexpr char AUTHOR[] = "Danylo Lebediev";
#endif // !VERSION_H
|
#pragma once
#ifndef ZOMBIEEVENT_HPP
# define ZOMBIEEVENT_HPP
# include "Zombie.hpp"
# include <string>
# include <iostream>
# include <cstdlib>
# include <ctime> // time()
# define NAMES_NUM 7
class ZombieEvent
{
private:
std::string type_;
static std::string names_list_[NAMES_NUM];
int getRandomNumber_(int min, int max) const;
public:
ZombieEvent();
~ZombieEvent();
void setZombieType(const std::string &type);
Zombie *newZombie(std::string name);
Zombie *randomChump(void);
};
#endif
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2008 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
*/
#include "core/pch.h"
#ifdef AUTO_UPDATE_SUPPORT
#include "adjunct/quick/dialogs/AutoUpdateCheckDialog.h"
#include "adjunct/quick_toolkit/widgets/OpBar.h"
#include "modules/locale/locale-enum.h"
#include "modules/locale/oplanguagemanager.h"
#include "modules/prefs/prefsmanager/collections/pc_ui.h"
/***********************************************************************************
** Constructor
** Adds itself as a listener of AutoUpdateManager, retrieves some default strings.
**
** AutoUpdateCheckDialog::AutoUpdateCheckDialog
**
***********************************************************************************/
AutoUpdateCheckDialog::AutoUpdateCheckDialog()
{
g_autoupdate_manager->AddListener(this);
g_languageManager->GetString(Str::D_UPDATE_MINIMIZE, m_minimize_text);
}
/***********************************************************************************
** Destructor
** Removes itself as a listener of AutoUpdateManager.
**
** AutoUpdateCheckDialog::~AutoUpdateCheckDialog
**
***********************************************************************************/
AutoUpdateCheckDialog::~AutoUpdateCheckDialog()
{
g_autoupdate_manager->RemoveListener(this);
}
/***********************************************************************************
** Sets the text of the OK button.
**
** AutoUpdateCheckDialog::GetOkText
**
***********************************************************************************/
const uni_char* AutoUpdateCheckDialog::GetOkText()
{
g_languageManager->GetString(Dialog::GetCancelTextID(), m_cancel_text);
return m_cancel_text.CStr();
}
/***********************************************************************************
** Sets the action of the OK button.
**
** AutoUpdateCheckDialog::GetOkAction
**
***********************************************************************************/
OpInputAction* AutoUpdateCheckDialog::GetOkAction()
{
return OP_NEW(OpInputAction, (OpInputAction::ACTION_CANCEL_AUTO_UPDATE));
}
/***********************************************************************************
** Sets the text of the Cancel button. The Cancel button the one that minimizes the
** update.
**
** AutoUpdateCheckDialog::GetCancelText
**
***********************************************************************************/
const uni_char* AutoUpdateCheckDialog::GetCancelText()
{
g_languageManager->GetString(Str::D_UPDATE_MINIMIZE, m_minimize_text);
return m_minimize_text.CStr();
}
/***********************************************************************************
** Initializes the dialog. Saves regularly updated widgets for later use.
**
** AutoUpdateCheckDialog::OnInit
**
***********************************************************************************/
void AutoUpdateCheckDialog::OnInit()
{
}
/***********************************************************************************
** Handles dialog actions, triggered by the custom actions set for OK and Cancel
** button, and the 'resume' button. It informs the autoupdate manager about
** decisions made by the user.
**
** AutoUpdateCheckDialog::OnInputAction
** @param action The action that needs to be handled
**
***********************************************************************************/
BOOL AutoUpdateCheckDialog::OnInputAction(OpInputAction* action)
{
switch (action->GetAction())
{
case OpInputAction::ACTION_GET_ACTION_STATE:
{
OpInputAction* child_action = action->GetChildAction();
switch (child_action->GetAction())
{
case OpInputAction::ACTION_MINIMIZE_AUTO_UPDATE_DIALOG:
{
INT32 statusbar_alignment = g_pcui->GetIntegerPref(PrefsCollectionUI::StatusbarAlignment);
if(statusbar_alignment == OpBar::ALIGNMENT_OFF)
{
child_action->SetEnabled(FALSE);
}
return TRUE;
}
}
break;
}
case OpInputAction::ACTION_CANCEL_AUTO_UPDATE:
{
CloseDialog(FALSE); // cancel means: minimize
g_autoupdate_manager->CancelUpdate();
return TRUE;
}
case OpInputAction::ACTION_MINIMIZE_AUTO_UPDATE_DIALOG:
{
CloseDialog(TRUE); // cancel means: minimize
return TRUE;
}
}
return Dialog::OnInputAction(action);
}
/***********************************************************************************
** Cancel minimizes the update, ie. closes the dialog and shows the 'minimized update'
** button in the toolbar. Triggered both by the 'X' in the dialog decoration and the
** cancel button.
**
** AutoUpdateCheckDialog::OnCancel
**
***********************************************************************************/
void AutoUpdateCheckDialog::OnCancel()
{
g_autoupdate_manager->SetUpdateMinimized(TRUE);
}
/***********************************************************************************
**
**
** AutoUpdateCheckDialog::OnUpToDate
**
***********************************************************************************/
void AutoUpdateCheckDialog::OnUpToDate()
{
CloseDialog(FALSE);
}
/***********************************************************************************
**
**
** AutoUpdateCheckDialog::OnChecking
**
***********************************************************************************/
void AutoUpdateCheckDialog::OnChecking()
{
// this callback should never be called within this dialog
OP_ASSERT(FALSE);
CloseDialog(FALSE);
}
/***********************************************************************************
**
**
** AutoUpdateCheckDialog::OnUpdateAvailable
** @param context The context of the available update
**
***********************************************************************************/
void AutoUpdateCheckDialog::OnUpdateAvailable(AvailableUpdateContext* context)
{
CloseDialog(FALSE);
}
/***********************************************************************************
**
**
** AutoUpdateCheckDialog::OnError
** @param context
**
***********************************************************************************/
void AutoUpdateCheckDialog::OnError(UpdateErrorContext* context)
{
CloseDialog(FALSE);
}
/***********************************************************************************
** Minimizing the dialog is not actually minimizing it, but closing and re-opening
** it.
**
** AutoUpdateCheckDialog::OnMinimizedStateChanged
** @param minimized If auto-update dialogs are minimized or not
** @see AutoUpdateCheckDialog::OnCancel
**
***********************************************************************************/
void AutoUpdateCheckDialog::OnMinimizedStateChanged(BOOL minimized)
{
// do nothing: the dialog is about to close (see OnCancel)
}
#endif // AUTO_UPDATE_SUPPORT
|
#include<iostream>
#include<stdlib.h>
using namespace std;
struct node
{
string s;
struct node*next;
};
typedef struct node Node;
Node *head,*rear,*ptr;
void insertfront(string a)
{
Node *p=(Node*)calloc(1,sizeof(Node));
p->s+=a;
if(head==NULL)
{
head=p;
rear=p;
}
else {
p->next=head;
head=p;
}
}
void insertend(string a)
{
Node *p=(Node*)calloc(1,sizeof(Node));
p->s+=a;
if(rear==NULL)
{
head=p;rear=p;
}
else {
rear->next=p;
p->next=NULL;
rear=p;
}
}
int main()
{
string input,temp;
int i,key;
while(getline(cin,input))
{
head=NULL;rear=NULL;
temp.clear();
key=0;
for(i=0;i<input.size();i++)
{
if(input.at(i)=='[')
{
if(temp!="")
{if(key==0)
{insertend(temp);temp.clear();}
else if(key==1)
{insertfront(temp);temp.clear();}
else if(key==2)
{insertend(temp);temp.clear();}
}
key=1;
}
else if(input.at(i)==']')
{
if(temp!="")
{if(key==0)
{insertend(temp);temp.clear();}
else if(key==1)
{insertfront(temp);temp.clear();}
else if(key==2)
{insertend(temp);temp.clear();}
}
key=2;
}
else
{
temp+=input.at(i);
}
if(i==input.size()-1)
{
if(temp!="")
{if(key==0)
{insertend(temp);temp.clear();}
else if(key==1)
{insertfront(temp);temp.clear();}
else if(key==2)
{insertend(temp);temp.clear();}
}
}
}
ptr=head;
while(ptr!=NULL)
{
cout<<ptr->s;
ptr=ptr->next;
}
cout<<endl;
}
return 0;
}
|
#define NUM_AVG_VAL 25
// cal constant air = .01027
// cal constant water = .04854
int analogPin = 0;
float val = 0;
float avg = 0;
//float calConstant = 0.01027;
float calConstant = .047921;
int i = 0;
float prevVals[NUM_AVG_VAL];
float distance = 0;
void setup()
{
Serial.begin(9600);
Serial.print("Send any value to start test\n");
}
void loop()
{
if (Serial.available() > 0) {
val = analogRead(analogPin);
Serial.print("Value: ");
Serial.print(val);
Serial.print(" mV");
Serial.print("\t");
distance = calConstant * val;
Serial.print(distance);
Serial.print(" meters");
Serial.print("\t");
prevVals[i] = distance;
i++;
avg = average(prevVals);
Serial.print("Average is: ");
Serial.print(avg);
Serial.print(" meters\n");
if (i == NUM_AVG_VAL) {
i = 0;
}
}
}
float average(float prevVals[])
{
float sum = 0;
for (int i = 0; i < NUM_AVG_VAL; i++) {
sum += prevVals[i];
}
return (sum / NUM_AVG_VAL);
}
|
/*
kamalsam
*/
#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector<int> v;
int sum=0,c;
int a[101],i,j=0,n;
for(i=1;i<=100;i++)
{
sum+=(i*i);
a[i]=sum;
}
cin>>c;
while(c!=0)
{
v.push_back(c);
cin>>c;
}
for(i=0;i<v.size();i++)
cout<<a[v[i]]<<endl;
return 0;
}
|
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=//
// Простая программа-пример рекурсии. Все рекурсии должны иметь условие для завершения!
// Рекурсия позволяет осуществлять повторяющиеся инструкции без использования циклов.
// V 1.0
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=//
#include<iostream>
#include <unistd.h> // Библиотека для вызова задержки в сек.
using namespace std;
void countOut(int count) {
sleep(1); // Задержка в сек.
std::cout << "push " << count << '\n';
if (count > 1) { // Условие завершения
countOut(--count); // функция countOut() вызывает рекурсивно сама себя и заполняет стек визовов
}
std::cout << "push" << endl; // Очистка стека вызовов
}
int main() { // Стек вызовов
countOut(4);
return 0;
}
// Output:
/*
*/
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=//
// END FILE
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=//
|
/*
Crayfish - A collection of tools for TUFLOW and other hydraulic modelling packages
Copyright (C) 2016 Lutra Consulting
info at lutraconsulting dot co dot uk
Lutra Consulting
23 Chestnut Close
Burgess Hill
West Sussex
RH15 8HN
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "crayfish.h"
#include "crayfish_dataset.h"
#include "crayfish_gdal.h"
#include "crayfish_output.h"
#include "crayfish_renderer.h" // for MapToPixel
static void exportRawDataElements(Element::Type elemType, const Output* output, RawData* rd, const MapToPixel& xform)
{
const Mesh* mesh = output->dataSet->mesh();
const Mesh::Elements& elems = mesh->elements();
for (int i=0; i < elems.count(); i++)
{
const Element& elem = elems[i];
if(elem.eType() != elemType)
continue;
if (elem.isDummy())
continue;
// If the element's activity flag is off, ignore it
if(!output->isActive(i))
continue;
const BBox& bbox = mesh->projectedBBox(i);
// Get the BBox of the element in pixels
QPointF ll = xform.realToPixel(bbox.minX, bbox.minY);
QPointF ur = xform.realToPixel(bbox.maxX, bbox.maxY);
// TODO: floor/ceil ?
int topLim = ur.y();
int bottomLim = ll.y();
int leftLim = ll.x();
int rightLim = ur.x();
double val;
for (int j=topLim; j<=bottomLim; j++)
{
float* line = rd->scanLine(j);
for (int k=leftLim; k<=rightLim; k++)
{
Q_ASSERT(k >= 0 && k < rd->cols());
QPointF p = xform.pixelToReal(k, j);
if( mesh->valueAt(i, p.x(), p.y(), &val, output) )
line[k] = val; // The supplied point was inside the element
}
}
}
}
//! Return new raw data image for the given dataset/output time, sampled with given resolution
static RawData* exportRawData(const Output* output, double mupp)
{
if (!output)
return 0;
if (mupp <= 0)
return 0;
const Mesh* mesh = output->dataSet->mesh();
// keep one pixel around
// e.g. if we have mesh with coords 0..10 with sampling of 1, then we actually need 11 pixels
BBox bbox = mesh->projectedExtent();
double xMin = bbox.minX - mupp;
double xMax = bbox.maxX + mupp;
double yMin = bbox.minY - mupp;
double yMax = bbox.maxY + mupp;
// calculate transform
// (uses envelope of the mesh)
int imgWidth = ceil((xMax - xMin) / mupp);
int imgHeight = ceil((yMax - yMin) / mupp);
if (!imgWidth || !imgHeight)
return 0;
MapToPixel xform(xMin, yMin, mupp, imgHeight);
// prepare geometry transform
yMax = yMin + imgHeight*mupp; // this is different from yMax previously - due to using fixed pixel size
// also shift the exported raster by half of pixel size in both directions
// sampled value for X needs to occupy interval (X-mupp/2,X+mupp/2) - without the shift the value would be misaligned to (X,X+mupp)
QVector<double> geo;
geo << xMin - mupp/2 << mupp << 0
<< yMax + mupp/2 << 0 << -mupp;
RawData* rd = new RawData(imgWidth, imgHeight, geo);
// First export quads, then triangles.
// We use this ordering because from 1D simulation we will get tesselated river polygons from linestrings
// and we want them to be on top of the terrain (quads)
exportRawDataElements(Element::ENP, output, rd, xform);
exportRawDataElements(Element::E4Q, output, rd, xform);
exportRawDataElements(Element::E3T, output, rd, xform);
exportRawDataElements(Element::E2L, output, rd, xform);
return rd;
}
bool Crayfish::exportRawDataToTIF(const Output* output, double mupp, const QString& outFilename, const QString& projWkt)
{
RawData* rd = exportRawData(output, mupp);
if (!rd)
return false;
bool res = CrayfishGDAL::writeGeoTIFF(outFilename, rd, projWkt);
delete rd;
return res;
}
|
#ifndef PROFILEEDITORUI_HPP
#define PROFILEEDITORUI_HPP
#include <QWidget>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QGroupBox>
class SettingProfileEditorUI : public QWidget
{
Q_OBJECT
public:
explicit SettingProfileEditorUI(QWidget *parent = nullptr);
void initLayout();
void initConnection();
signals:
public slots:
void updatePasswdClicked();
void updateNameClicked();
private:
QLabel *pLabelNewPasswd;
QLabel *pLabelNewPasswdConfirm;
QLineEdit *pLineNewPasswd;
QLineEdit *pLineNewPasswdConfirm;
QPushButton *pButtonUpdatePasswd;
QLabel *pLabelNewName;
QLineEdit *pLineNewName;
QPushButton *pButtonUpdateName;
};
#endif // PROFILEEDITORUI_HPP
|
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved.
#include "Hypoxia.h"
IMPLEMENT_PRIMARY_GAME_MODULE( FDefaultGameModuleImpl, Hypoxia, "Hypoxia" );
|
#include "calc/Calculator.h"
Calculator::Calculator()
{
adder = new Adder;
}
Calculator::~Calculator()
{
delete adder;
adder = nullptr;
}
double
Calculator::plus(double left, double right)
{
return adder->plus(left, right);
}
double
Calculator::minus(double left, double right)
{
return left - right;
}
double
Calculator::divide(double left, double right)
{
return left / right;
}
double
Calculator::multiply(double left, double right)
{
return left * right;
}
|
#pragma once
#include <stdio.h>
/**
* \brief Base Class
*/
class Object {
public:
Object() = default;
virtual ~Object() = default;
virtual char* toString() {
char *buf = new char[32];
sprintf_s(buf, 32,"Object(0x%p)",this);
return buf;
}
};
|
/* iffy: blinkt doesn't seem to work with this project */
#include <stdio.h>
#include <string.h>
#include "pico/stdlib.h"
#include "hardware/spi.h"
#include "hardware/gpio.h"
#include "hardware/pwm.h"
#include "hardware/clocks.h"
#include "hardware/irq.h"
#include "pace.h"
#include "../mcp4921/pico-hard-song-mcp4921/data.h"
#define PIN_SCK 2
#define PIN_MOSI 3
#define PIN_MISO 4
#define PIN_CS 5
using u16 = uint16_t;
void my_pwm_wrap_isr();
#define LED 25
#define SPK 19
unsigned int slice_num;
const int sampling_freq = 44100;
const int top = 1023;
//const int f_pwm = 32000;
void my_pwm_wrap_isr()
{
pwm_clear_irq(slice_num);
//const int time_scale = f_pwm / 8000;
const int vol_scale = (top+1)/256;
static int i = 0;
//u16 v = data_bin[i/time_scale];
u16 v = data_bin[i];
i++;
if(i == data_bin_len) i = 0;
//a_pwm.set_level(v*vol_scale);
int new_level = v*vol_scale;
pwm_set_gpio_level(SPK, new_level);
}
int main()
{
stdio_init_all();
int err = pace_config_pwm_irq(&slice_num, SPK, sampling_freq, top, my_pwm_wrap_isr);
if(err) {
puts("Can't set PWM");
for(;;); // loop forever, effectively halting
}
gpio_init(LED);
gpio_set_dir(LED, GPIO_OUT);
gpio_put(LED, 1);
while(1); // actual playing of track is handled by my_pwm_wrap_isr()
return 0;
}
|
// 导入 ros 头文件
#include "roscpp_tutorials/TwoInts.h"
#include <ros/ros.h>
bool serviceCallback(roscpp_tutorials::TwoInts::Request &request,
roscpp_tutorials::TwoInts::Response &response) {
// 返回值 bool:true代表成功响应,false代表拒绝响应
// 可根据业务实际情况返回相应数据,本例就不做false处理了
response.sum = request.a + request.b;
return true;
}
int main(int argc, char **argv) {
// 创建 ros 的节点名称
char node_name[] = "cpp_server";
// 初始化 ros 节点
ros::init(argc, argv, node_name);
// 创建一个节点对象
ros::NodeHandle node;
// 创建 service 名称
char service_name[] = "demo_service";
// 创建一个 server
const ros::ServiceServer &server =
node.advertiseService(service_name, serviceCallback);
// 进入一个简单的事件循环
ros::spin();
return 0;
}
|
#include "mpi.h"
#include<stdio.h>
#include<stdlib.h>
void Hello(void);
int main(void)
{
int rank,option,size;
MPI_Init(NULL,NULL);
MPI_Comm_rank(MPI_COMM_WORLD,&rank);
MPI_Comm_size(MPI_COMM_WORLD,&size);
if(size<2){
fprintf(stderr, "systest requires at least 2 processors\n");
MPI_Abort(MPI_COMM_WORLD,1);
}
fprintf(stderr, "I am processor %d\n",rank);
MPI_Barrier(MPI_COMM_WORLD);
Hello();
MPI_Finalize();
}
void Hello(void)
{
int nproc,me;
int type=1;
int buffer[2],node;
MPI_Status status;
MPI_Comm_rank(MPI_COMM_WORLD,&me);
MPI_Comm_size(MPI_COMM_WORLD,&nproc);
if(me==0){
printf("\nhello test from all to all\n");
fflush(stdout);
}
for (node=0;node<nproc;node++)//every processors send a buffer message to other processors(node)
{
if(node!=me)
{
buffer[0]=me;
buffer[1]=node;
MPI_Send(buffer,2,MPI_INT,node,type,MPI_COMM_WORLD);//send to all node
MPI_Recv(buffer,2,MPI_INT,node,type,MPI_COMM_WORLD,&status);//recieve form all node
if((buffer[0]!=node)||(buffer[1]!=me)){
(void)fprintf(stderr, "Hello:%d!=%d or %d!=%d\n",buffer[0],node,buffer[1],me);
printf("Mismarch on hello processor ids;node= %d\n",node);
}
printf("hello from %d to %d\n",me,node);
fflush(stdout);
}
}
}
|
// Created on: 1996-01-25
// Created by: Frederic MAUPAS
// Copyright (c) 1996-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _GeomToStep_MakeRectangularTrimmedSurface_HeaderFile
#define _GeomToStep_MakeRectangularTrimmedSurface_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <GeomToStep_Root.hxx>
class StepGeom_RectangularTrimmedSurface;
class Geom_RectangularTrimmedSurface;
//! This class implements the mapping between class
//! RectangularTrimmedSurface from Geom and the class
//! RectangularTrimmedSurface from
//! StepGeom which describes a
//! rectangular_trimmed_surface from ISO-IS 10303-42
class GeomToStep_MakeRectangularTrimmedSurface : public GeomToStep_Root
{
public:
DEFINE_STANDARD_ALLOC
Standard_EXPORT GeomToStep_MakeRectangularTrimmedSurface(const Handle(Geom_RectangularTrimmedSurface)& RTSurf);
Standard_EXPORT const Handle(StepGeom_RectangularTrimmedSurface)& Value() const;
protected:
private:
Handle(StepGeom_RectangularTrimmedSurface) theRectangularTrimmedSurface;
};
#endif // _GeomToStep_MakeRectangularTrimmedSurface_HeaderFile
|
== 原稿料・デザイン料の決定
原稿料は、この本については出ません。各自の善意によって成り立っている本であり、収益に関しては「技術書界隈を盛り上げる会」の運営に使うことを明記したうえで著者の募集を行っています。
それぞれが「寄稿」という形で少しずつ原稿を書き、みんなで作り上げるという形式の本にしています。
表紙のデザイン料については悩みました。執筆と違い「要件定義」「デザイン」「フィードバック」という工程を何度も繰り返す、かなり負荷の高い作業ですので、デザイン料を設定することにしました。
具体的なデザイン料については、coconalaというCD・書籍デザインを請け負う人たちの集まるポータルサイトを参考に、2万円という価格で合意をいただきました。
デザイナごとに価格も違いますし、相場というものが公開されにくい業界です。
表紙は本の顔であり、本の売れ行きにも直結します。そのため、歩合制でという考えも検討されましたが、どこまでの期間までの売り上げを対象とするのかが難しいことや、早めに支払いをしたほうがデザイナにとっても嬉しいという話から、金額を設定し、支払う方式とさせていただきました。
|
#include "testApp.h"
#include "ofxIldaFrame.h"
//--------------------------------------------------------------
void testApp::setup(){
showHud = true;
w = 1.0;//ofGetWidth();
h = 1.0;//ofGetHeight();
ofBackground(0);
// ofSetFrameRate(30);
etherdream.setup();
etherdream.setPPS(25000);
ildaFrame.params.output.doCapX=true;
ildaFrame.params.output.doCapY=true;
ildaFrame.params.output.blankCount=10;
ildaFrame.params.output.endCount=10;
ildaFrame.polyProcessor.params.targetPointCount=400;
// ildaFrame.polyProcessor.params.optimizeTolerance = 0.2;
demo = testApp::OSCILLATIONS;
///////////
switch (demo) {
case DOODLES:{
break;
}
case OSCILLATIONS:{
break;
}
case TEXT:{
break;
}
case NONE:{
ildaFrame.getPolys().clear();
break;
}
default:
break;
}
}
//--------------------------------------------------------------
void testApp::update(){
switch (demo) {
case OSCILLATIONS:{
ildaFrame.getPolys().clear();
ildaFrame.addPoly(ofFloatColor(
(int)ofGetElapsedTimef()%3,
(int)ofGetElapsedTimef()%5,
(int)ofGetElapsedTimef()%7,
1));
ofxIlda::Poly& p = ildaFrame.getLastPoly();
p.clear();
for (int i = 0 ; i < 35 ; i ++){
float t = (ofGetElapsedTimef() + i * 0.5);
float scale = sqrt(abs(sin(ofGetElapsedTimef())));
ofPoint pnt = (ofPoint(0.5,0.5) + scale * ofPoint(0.5*cos(t*1.1), 0.5*sin(t)));
p.lineTo(pnt);
}
break;
}
case MILKYWAY:{
ildaFrame.getPolys().clear();
ildaFrame.addPoly(ofFloatColor(
(int)ofGetElapsedTimef()%11,
(int)ofGetElapsedTimef()%5,
(int)ofGetElapsedTimef()%7,
1));
ofxIlda::Poly& q = ildaFrame.getLastPoly();
q.clear();
for (int i = 0 ; i < 150 ; i ++){
float t = (ofGetElapsedTimef() + i*0.5);
float scale = sqrt(i/150.0);
ofPoint pnt = (ofPoint(0.5,0.5) + scale * ofPoint(0.5*cos(t*1.1), 0.5*sin(t)));
q.lineTo(pnt);
}
break;
}
default:
ildaFrame.clear();
break;
}
// drawSomething(EYE, ofPoint(0.5,0.5), 0.2, ofFloatColor(0,1,1,1));
drawSomething(TRIANGLE, ofPoint(0.5,0.5), 0.05*(sqrt(ofGetSystemTime()%53)), ofFloatColor(1,0,0,1));
drawSomething(TRIANGLE, ofPoint(0.5,0.5), 0.05*(sqrt(ofGetSystemTime()%73)), ofFloatColor(0,0,1,1));
drawSomething(TRIANGLE, ofPoint(0.5,0.5), 0.05*(sqrt(ofGetSystemTime()%101)), ofFloatColor(1,1,0,1));
}
//--------------------------------------------------------------
void testApp::draw() {
// do your thang
ildaFrame.update();
// draw to the screen
ildaFrame.draw(0, 0, ofGetWidth(), ofGetHeight());
// send points to the etherdream
etherdream.setPoints(ildaFrame);
ofSetColor(255);
// poly.draw();
// poly.getResampledByCount(2).draw();
ildaFrame.params;
if (showHud) ofDrawBitmapString(ildaFrame.getString(), 10, 30);
}
//--------------------------------------------------------------
void testApp::keyPressed(int key){
switch(key) {
case 'f': ofToggleFullscreen(); break;
// clear the frame
case 'c': ildaFrame.clear(); break;
// draw rectangle
case 'r': {
ofPolyline p = ofPolyline::fromRectangle(ofRectangle(ofRandomuf()/2, ofRandomuf()/2, ofRandomuf()/2, ofRandomuf()/2));
ildaFrame.addPoly(p);
}
break;
// change color
case 'R': ildaFrame.params.output.color.r = 1 - ildaFrame.params.output.color.r; break;
case 'G': ildaFrame.params.output.color.g = 1 - ildaFrame.params.output.color.g; break;
case 'B': ildaFrame.params.output.color.b = 1 - ildaFrame.params.output.color.b; break;
// toggle draw lines (on screen only)
case 'l': ildaFrame.params.draw.lines ^= true; break;
// toggle loop for last poly
case 'o': ildaFrame.getLastPoly().setClosed(ildaFrame.getLastPoly().isClosed()); break;
// toggle draw points (on screen only)
case 'p': ildaFrame.params.draw.points ^= true; break;
// adjust point count
case '.': ildaFrame.polyProcessor.params.targetPointCount++; break;
case ',': if(ildaFrame.polyProcessor.params.targetPointCount > 10) ildaFrame.polyProcessor.params.targetPointCount--; break;
// adjust point count quicker
case '>': ildaFrame.polyProcessor.params.targetPointCount += 10; break;
case '<': if(ildaFrame.polyProcessor.params.targetPointCount > 20) ildaFrame.polyProcessor.params.targetPointCount -= 10; break;
// flip image
case 'x': ildaFrame.params.output.transform.doFlipX ^= true; break;
case 'y': ildaFrame.params.output.transform.doFlipY ^= true; break;
// cap image
case 'X': ildaFrame.params.output.doCapX ^= true; break;
case 'Y': ildaFrame.params.output.doCapY ^= true; break;
// move output around
case OF_KEY_UP: ildaFrame.params.output.transform.offset.y -= 0.05; break;
case OF_KEY_DOWN: ildaFrame.params.output.transform.offset.y += 0.05; break;
case OF_KEY_LEFT: ildaFrame.params.output.transform.offset.x -= 0.05; break;
case OF_KEY_RIGHT: ildaFrame.params.output.transform.offset.x += 0.05; break;
// scale output
case 'w': ildaFrame.params.output.transform.scale.y += 0.05; break;
case 's': ildaFrame.params.output.transform.scale.y -= 0.05; break;
case 'a': ildaFrame.params.output.transform.scale.x -= 0.05; break;
case 'd': ildaFrame.params.output.transform.scale.x += 0.05; break;
case 'C': ildaFrame.drawCalibration(); break;
case '1': ildaFrame.params.output.blankCount-=2; break;
case '2': ildaFrame.params.output.blankCount+=2; break;
case '3': ildaFrame.params.output.endCount-=2; break;
case '4': ildaFrame.params.output.endCount+=2; break;
case '|': showHud ^= showHud;
}
}
//--------------------------------------------------------------
void testApp::mouseDragged(int x, int y, int button){
// draw a line to the mouse cursor (normalized coordinates) in the last poly created
ildaFrame.getLastPoly().lineTo(x / (float)ofGetWidth(), y / (float)ofGetHeight());
}
//--------------------------------------------------------------
void testApp::mousePressed(int x, int y, int button){
// create a new poly in the ILDA frame
ildaFrame.addPoly();
}
void testApp::drawSomething(doodle d, ofPoint center, float scale, ofFloatColor c){
switch (d) {
case EYE:{
ofxIlda::Poly p1, p2;
p1.arc(center, scale, 0.2*scale, -90, 270, true, 10);
p1.arc(center, scale*0.2, scale*0.2, -90,270,true,8);
p2.arc(center, scale*0.01, scale*0.01, 0,360,true,2);
ildaFrame.addPoly(p1, c);
ildaFrame.addPoly(p2, c);
}
break;
case TRIANGLE:{
/* Triangle */
ofxIlda::Poly p;
p.lineTo(center + scale * ofPoint(0.0,-0.5));
p.lineTo(center + scale * ofPoint(-0.5,0.5));
p.lineTo(center + scale * ofPoint(0.5,0.5));
p.lineTo(center + scale * ofPoint(0.0,-0.5));
ildaFrame.addPoly(p,c);
}
break;
default:
break;
}
}
|
// Created on: 1999-01-04
// Created by: Xuan PHAM PHU
// Copyright (c) 1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _TopOpeBRepTool_REGUS_HeaderFile
#define _TopOpeBRepTool_REGUS_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <TopTools_DataMapOfShapeListOfShape.hxx>
#include <TopoDS_Shape.hxx>
#include <TopTools_IndexedMapOfShape.hxx>
#include <Standard_Integer.hxx>
#include <TopTools_MapOfShape.hxx>
#include <TopTools_ListOfShape.hxx>
class TopoDS_Face;
class TopoDS_Edge;
class TopOpeBRepTool_REGUS
{
public:
DEFINE_STANDARD_ALLOC
Standard_EXPORT TopOpeBRepTool_REGUS();
Standard_EXPORT void Init (const TopoDS_Shape& S);
Standard_EXPORT const TopoDS_Shape& S() const;
Standard_EXPORT Standard_Boolean MapS();
Standard_EXPORT static Standard_Boolean WireToFace (const TopoDS_Face& Fanc, const TopTools_ListOfShape& nWs, TopTools_ListOfShape& nFs);
Standard_EXPORT static Standard_Boolean SplitF (const TopoDS_Face& Fanc, TopTools_ListOfShape& FSplits);
Standard_EXPORT Standard_Boolean SplitFaces();
Standard_EXPORT Standard_Boolean REGU();
Standard_EXPORT void SetFsplits (TopTools_DataMapOfShapeListOfShape& Fsplits);
Standard_EXPORT void GetFsplits (TopTools_DataMapOfShapeListOfShape& Fsplits) const;
Standard_EXPORT void SetOshNsh (TopTools_DataMapOfShapeListOfShape& OshNsh);
Standard_EXPORT void GetOshNsh (TopTools_DataMapOfShapeListOfShape& OshNsh) const;
Standard_EXPORT Standard_Boolean InitBlock();
Standard_EXPORT Standard_Boolean NextinBlock();
Standard_EXPORT Standard_Boolean NearestF (const TopoDS_Edge& e, const TopTools_ListOfShape& lof, TopoDS_Face& ffound) const;
protected:
private:
Standard_Boolean hasnewsplits;
TopTools_DataMapOfShapeListOfShape myFsplits;
TopTools_DataMapOfShapeListOfShape myOshNsh;
TopoDS_Shape myS;
TopTools_DataMapOfShapeListOfShape mymapeFsstatic;
TopTools_DataMapOfShapeListOfShape mymapeFs;
TopTools_IndexedMapOfShape mymapemult;
Standard_Integer mynF;
Standard_Integer myoldnF;
TopoDS_Shape myf;
TopTools_MapOfShape myedstoconnect;
TopTools_ListOfShape mylFinBlock;
};
#endif // _TopOpeBRepTool_REGUS_HeaderFile
|
#pragma once
#include "AncillaryRecord.h"
namespace OpenFlight
{
//-------------------------------------------------------------------------
class OFR_API IndexedStringRecord : public AncillaryRecord
{
public:
IndexedStringRecord() = delete;
explicit IndexedStringRecord(PrimaryRecord* ipParent);
IndexedStringRecord(const IndexedStringRecord&) = delete;
IndexedStringRecord& operator=(const IndexedStringRecord&) = delete;
virtual ~IndexedStringRecord() {}
// Getters
uint32_t getIndex() const;
std::string getString() const;
// Setters
//void setIndex(uint32_t);
//void setString(std::string);
protected:
virtual bool parseRecord(std::ifstream& iRawRecord, int iVersion) override;
uint32_t mIndex;
std::string mString;
};
}
|
#include "stdafx.h"
#ifndef SHARED_HANDLERS
#include "CocosTool.h"
#endif
#include "CocosToolDoc.h"
#include "CocosToolView.h"
#include <CCStdC.h>
#include <CCApplication.h>
#include "MainFrm.h"
#include "GtGLView.h"
#include "GnLayerMain.h"
#include "ActorMacro.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
GnVector2 ActorBasePosition( 0, 0 );
const float CCocosToolView::msWidth = 480.0f;
const float CCocosToolView::msHeight = 320.0f;
// CCocosToolView
IMPLEMENT_DYNCREATE(CCocosToolView, CFormView)
BEGIN_MESSAGE_MAP(CCocosToolView, CFormView)
ON_WM_CONTEXTMENU()
ON_WM_RBUTTONUP()
ON_COMMAND(IDC_RBBT_PLAY, &CCocosToolView::OnAniPlay)
ON_COMMAND(IDC_RBBT_PAUSE, &CCocosToolView::OnAniPause)
ON_WM_TIMER()
ON_COMMAND(IDC_MODIFY_COLLISIONBOXS, &CCocosToolView::OnModifyCollisionboxs)
ON_UPDATE_COMMAND_UI(IDC_MODIFY_COLLISIONBOXS, &CCocosToolView::OnUpdateModifyCollisionboxs)
ON_COMMAND(IDC_ANICURRENTTIME, &CCocosToolView::OnAnicurrenttime)
ON_COMMAND(IDC_ANITIMESLIDER, &CCocosToolView::OnAnitimeslider)
ON_COMMAND(ID_BT_LOADBACKGROUND, &CCocosToolView::OnBtLoadbackground)
ON_COMMAND(ID_SCALERANGE, &CCocosToolView::OnScaleRange)
ON_COMMAND(ID_BT_FLIPX, &CCocosToolView::OnFlipx)
ON_COMMAND(ID_ACTOR_CENTER, &CCocosToolView::OnActorCenter)
ON_UPDATE_COMMAND_UI(ID_ACTOR_CENTER, &CCocosToolView::OnUpdateActorCenter)
END_MESSAGE_MAP()
// CCocosToolView 생성/소멸
CCocosToolView::CCocosToolView() :CFormView( CCocosToolView::IDD ), mpApp( NULL )
, mpSpinCurrentTime(NULL), mpCollisionModify(NULL)
{
mfCurrentTime = 0.0f;
mBforeTime = 0.0f;
mfStartTime = 0.0f;
mfEndTime = 0.0f;
mfTick = 0.0f;
mfLastTick = 0.0f;
}
CCocosToolView::~CCocosToolView()
{
}
void CCocosToolView::DoDataExchange(CDataExchange* pDX)
{
// TODO: 여기에 특수화된 코드를 추가 및/또는 기본 클래스를 호출합니다.
CFormView::DoDataExchange(pDX);
DDX_Control(pDX, IDC_LOCATION_RENDER, mLoactionRender);
}
BOOL CCocosToolView::PreCreateWindow(CREATESTRUCT& cs)
{
// TODO: CREATESTRUCT cs를 수정하여 여기에서
// Window 클래스 또는 스타일을 수정합니다.
return CFormView::PreCreateWindow(cs);
}
void CCocosToolView::OnRButtonUp(UINT /* nFlags */, CPoint point)
{
ClientToScreen(&point);
OnContextMenu(this, point);
}
void CCocosToolView::OnContextMenu(CWnd* /* pWnd */, CPoint point)
{
#ifndef SHARED_HANDLERS
theApp.GetContextMenuManager()->ShowPopupMenu(IDR_POPUP_EDIT, point.x, point.y, this, TRUE);
#endif
}
// CCocosToolView 진단
#ifdef _DEBUG
void CCocosToolView::AssertValid() const
{
CFormView::AssertValid();
}
void CCocosToolView::Dump(CDumpContext& dc) const
{
CFormView::Dump(dc);
}
CCocosToolDoc* CCocosToolView::GetDocument() const // 디버그되지 않은 버전은 인라인으로 지정됩니다.
{
ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CCocosToolDoc)));
return (CCocosToolDoc*)m_pDocument;
}
#endif //_DEBUG
void CCocosToolView::OnInitialUpdate()
{
CFormView::OnInitialUpdate();
if( mpApp == NULL )
{
AttachNeedMessage( GTMG_SELECTOBJECT );
AttachNeedMessage( GTMG_SELECT2DOBJECT );
AttachNeedMessage( GTMG_SELECTSEQUENCE );
AttachNeedMessage( GTMG_REDRAW );
AttachNeedMessage( GTMG_DESTORY );
AttachNeedMessage( GTMG_CHAGESEQUENCEANITIME );
mpApp = new GtCocos2DApp;
// Initialize instance and cocos2d.
GtGLView * pMainWnd = new GtGLView();
pMainWnd->Create(mLoactionRender.GetSafeHwnd(), (int)msWidth, (int)msHeight);
// initialize director
CCDirector *pDirector = CCDirector::sharedDirector();
pDirector->setOpenGLView(pMainWnd);
if (! mpApp->initInstance() || ! mpApp->applicationDidFinishLaunching())
{
return;
}
GnSceneManager* man = GetSceneManager();
GetSceneManager()->GetMainGameLayer()->setColor( ccc3(0,0,255) );
GetSceneManager()->GetMainGameLayer()->setOpacity( 255 );
GetSceneManager()->GetMainGameLayer()->setContentSize( CCSizeMake(msWidth, msHeight) );
mpCollisionModify = GtCollisionModify::Create( msWidth, msHeight );
CMainFrame* mainFrame = (CMainFrame*)AfxGetMainWnd();
mCategoryAnimation.Create( mainFrame->GetRibbonBar() );
CCFileUtils::setIsPopupNotify(false );
Loadbackground( GtToolSettings::GetBackgroundFilePath() );
GetDrawObjectManager()->Reset();
}
mModifyCollsionBoxsCheck = false;
mActorCenterCheck = false;
}
void CCocosToolView::PostNcDestroy()
{
if( mpCollisionModify )
delete mpCollisionModify;
delete mpApp;
CFormView::PostNcDestroy();
}
void CCocosToolView::ReceiveMediateMessage(gtuint messageIndex
, GcMediateObjectMessage* pMessage)
{
switch( messageIndex )
{
case GTMG_DESTORY:
GetDrawObjectManager()->Reset();
if( pMessage && *((bool*)(pMessage->mTempMessage)) )
break;
GetSceneManager()->GetMainGameLayer()->removeAllChildrenWithCleanup( true );
if( mpCollisionModify )
delete mpCollisionModify;
mpCollisionModify = GtCollisionModify::Create( msWidth, msHeight );
Loadbackground( GtToolSettings::GetBackgroundFilePath() );
break;
case GTMG_SELECTOBJECT:
{
GetDrawObjectManager()->SelectActor( pMessage->mpObject );
AddCurrentActorToLayerDrawPprimitives();
}
break;
case GTMG_SELECT2DOBJECT:
{
GetDrawObjectManager()->Select2DObject( pMessage->mpObject );
}
break;
case GTMG_SELECTSEQUENCE:
{
GcSequenceMessage* sequenceMessage = (GcSequenceMessage*)pMessage;
if( GetDrawObjectManager()->SelectSequence( sequenceMessage->mpSequenceInfo ) == false )
break;
ChageSequenceAniTime( GetDrawObjectManager()->GetSequence() );
mBforeTime = 0.0f;
mfCurrentTime = 0.0f;
mCategoryAnimation.GetAniTimeSpin()->SetEditText( _T("0.000") );
}
break;
case GTMG_CHAGESEQUENCEANITIME:
{
if( GetDrawObjectManager()->GetSequence() )
ChageSequenceAniTime( GetDrawObjectManager()->GetSequence() );
}
break;
case GTMG_REDRAW:
{
Invalidate( FALSE );
}
break;
}
}
void CCocosToolView::OnDraw(CDC* /*pDC*/)
{
CCocosToolDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
if (!pDoc)
return;
float deltaTime = GetCurrentTime() - mBforeTime;
GetDrawObjectManager()->Update( deltaTime );
CCDirector::sharedDirector()->setDeltaTime( deltaTime );
CCDirector::sharedDirector()->mainLoop();
mBforeTime = GetCurrentTime();
}
void CCocosToolView::OnAniPlay()
{
mfTick = GnGetTicks();
SetTimer(mTimerID, 0, NULL);
}
void CCocosToolView::OnAniPause()
{
KillTimer(mTimerID);
}
void CCocosToolView::OnTimer(UINT_PTR nIDEvent)
{
CFormView::OnTimer(nIDEvent);
if( GetCurrentTime() >= mfEndTime )
{
mBforeTime = 0.0f;
mfTick = GnGetTicks();
}
mfLastTick = GnGetTicks();
SetCurrentTimeFromOnTimer();
Invalidate(FALSE);
}
void CCocosToolView::OnAnicurrenttime()
{
CString intTime = mCategoryAnimation.GetAniTimeSpin()->GetEditText();
if( mStrCurrentTime == intTime )
return;
if( GetDrawObjectManager()->GetActor() == NULL
|| GetDrawObjectManager()->GetSequence() == NULL )
return;
float num = 0.0f;
_stscanf_s( intTime.GetString(), _T("%f"), &num );
num /= 100;
if( mfEndTime > num )
{
SetCurrentTime( num );
}
CString floatTime;
floatTime.Format( _T("%.3f"), GetCurrentTime() );
mCategoryAnimation.GetAniTimeSpin()->SetEditText( floatTime );
mStrCurrentTime = floatTime;
Invalidate(FALSE);
}
void CCocosToolView::OnAnitimeslider()
{
if( GetDrawObjectManager()->GetActor() == NULL
|| GetDrawObjectManager()->GetSequence()== NULL )
return;
if( GetCurrentTime() >= mfEndTime )
return;
Invalidate(FALSE);
}
void CCocosToolView::SetCurrentTime(float val)
{
mfCurrentTime = val;
GcMediateObjectMessage msg;
msg.mTempMessage = &mfCurrentTime;
SendMediateMessage( GTMG_TIMECHANGE, &msg );
}
void CCocosToolView::SetCurrentTimeFromOnTimer()
{
SetCurrentTime( mfLastTick - mfTick );
if( mpSpinCurrentTime )
{
mpSpinCurrentTime->SetPos( (int)(GetCurrentTime()*100) );
}
CString floatTime;
floatTime.Format( _T("%.3f"), GetCurrentTime() );
mCategoryAnimation.GetAniTimeSpin()->SetEditText( floatTime );
mStrCurrentTime = floatTime;
}
void CCocosToolView::ChageSequenceAniTime(Gt2DSequence* sequence)
{
mfStartTime = sequence->GetSequence()->GetStartTime();
mfEndTime = sequence->GetSequence()->GetEndTime();
CString time;
time.Format( _T("%.3f"), mfStartTime );
mCategoryAnimation.GetAniStartTime()->SetEditText( time );
time.Format( _T("%.3f"), mfEndTime );
mCategoryAnimation.GetAniEndTime()->SetEditText( time );
Invalidate( FALSE );
mCategoryAnimation.GetAniTimeSpin()->EnableSpinButtons( (int)mfStartTime
, (int)(mfEndTime * 100) );
CMainFrame* mainFrame = (CMainFrame*)AfxGetMainWnd();
CWnd* ps = mainFrame->GetRibbonBar()->GetDlgItem(IDC_ANICURRENTTIME);
mpSpinCurrentTime = (CMFCSpinButtonCtrl*)mainFrame->GetRibbonBar()->GetNextDlgGroupItem( ps );
if( mpSpinCurrentTime )
mpSpinCurrentTime->SetPos( 0 );
}
void CCocosToolView::OnUpdateModifyCollisionboxs(CCmdUI *pCmdUI)
{
pCmdUI->SetCheck( mModifyCollsionBoxsCheck );
}
void CCocosToolView::OnModifyCollisionboxs()
{
mModifyCollsionBoxsCheck = !mModifyCollsionBoxsCheck;
AddCurrentActorToLayerDrawPprimitives();
}
void CCocosToolView::OnActorCenter()
{
mActorCenterCheck = !mActorCenterCheck;
GetDrawObjectManager()->SetObjectCenter( mActorCenterCheck );
if( mpCollisionModify )
mpCollisionModify->SetActorPosition( ActorBasePosition );
Invalidate( FALSE );
}
void CCocosToolView::OnUpdateActorCenter(CCmdUI *pCmdUI)
{
pCmdUI->SetCheck( mActorCenterCheck );
}
void CCocosToolView::AddCurrentActorToLayerDrawPprimitives()
{
// TODO: 여기에 명령 처리기 코드를 추가합니다.
if( mModifyCollsionBoxsCheck )
{
if( GetDrawObjectManager()->GetActor() && GetDrawObjectManager()->GetSequence() )
{
std::string strName = GtToolSettings::GetWorkPath();
strName += gsActorPath;
strName += GetDrawObjectManager()->GetActor()->GetObjectName();
strName += "/";
strName += GetDrawObjectManager()->GetActor()->GetGATFileName();
mpCollisionModify->LoadBasicActor( strName.c_str() );
mpCollisionModify->SetBasicSequenceID( 1 );
mpCollisionModify->SetVisible( true, GetDrawObjectManager()->GetActor()->GetRootNode() );
}
}
else
{
mpCollisionModify->SetVisible( false );
}
Invalidate( FALSE );
}
void CCocosToolView::OnBtLoadbackground()
{
CFileDialog dlg(true, _T("IMG"), NULL
, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT | OFN_NOCHANGEDIR
, gsTextureFileFilter, this );
if( IDOK == dlg.DoModal() )
{
GtConvertString filePath = dlg.GetPathName().GetString();
Loadbackground( filePath.GetAciiString() );
GtToolSettings::SetBackgroundFilePath( filePath.GetAciiString() );
Invalidate(FALSE);
}
}
void CCocosToolView::Loadbackground(const gchar* pcFilePath)
{
if( GnStrlen(pcFilePath) )
{
GnLayerMain* main = (GnLayerMain*)GetSceneManager()->GetMainGameLayer();
GnVerify( main->CreateBackgroundFromFile( pcFilePath ) );
}
}
LRESULT CCocosToolView::WindowProc(UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_CHAR:
{
GnLayerMain* main = (GnLayerMain*)GetSceneManager()->GetMainGameLayer();
if( main->GetBackground() )
{
switch( wParam )
{
case 'd':
{
CCPoint point = main->GetBackground()->getPosition();
point.x -= 20;
main->GetBackground()->setPosition( point );
Invalidate( FALSE );
}
break;
case 'a':
{
CCPoint point = main->GetBackground()->getPosition();
point.x += 20;
main->GetBackground()->setPosition( point );
Invalidate( FALSE );
}
break;
}
}
}
break;
}
return CFormView::WindowProc(message, wParam, lParam);
}
void CCocosToolView::OnScaleRange()
{
CMainFrame* mainFrame = (CMainFrame*)AfxGetMainWnd();
CWnd* ps = mainFrame->GetRibbonBar()->GetDlgItem( ID_SCALERANGE );
if( ps )
{
CMFCSpinButtonCtrl* spin =
(CMFCSpinButtonCtrl*)mainFrame->GetRibbonBar()->GetNextDlgGroupItem( ps );
if( spin )
{
if( GtToolSettings::GetScalePercent() == 100 )
{
int btRet = MessageBox(
_T("스케일을 조정 하면 데이터를 저장 할 수 없습니다. 미리 저장 하시겠습니까?")
,_T("Warring"), MB_YESNOCANCEL );
if( btRet == IDOK )
GetObjectFactory()->SaveObjects(true);
else if( btRet == IDCANCEL )
{
spin->SetPos( GtToolSettings::GetScalePercent() );
return;
}
}
GetObjectFactory()->RemvoeAllObject();
SendMediateMessage( GTMG_DESTORY, NULL );
GtToolSettings::SetScalsePercent( spin->GetPos() );
GetGameState()->SetGameScale( GtToolSettings::GetScale() );
}
//if( GetDrawObjectManager()->GetActor() )
// GetDrawObjectManager()->GetActor()->GetRootNode()->SetScale( 1.0f );
Invalidate( false );
}
}
void CCocosToolView::OnFlipx()
{
if( GetDrawObjectManager()->GetActor() )
{
Gn2DMeshObject* mesh = GetDrawObjectManager()->GetActor()->GetRootNode();
if( mesh )
{
mesh->SetFlipX( !mesh->GetMesh()->isFlipX() );
// for( gtuint i = 0; i < mesh->GetExtraDataSize(); i++ )
// {
// GnVector2ExtraData* vectorData = GnDynamicCast(GnVector2ExtraData, mesh->GetExtraData( i ));
// if( vectorData )
// {
// if( mesh->GetAVData() )
// {
// if( mesh->GetFlipX() )
// {
// Gn2DAVData::CollisionRect& baseRect = mesh->GetAVData()->GetCollisionRect( 0 );
// float center = baseRect.mRect.GetWidth();
// vectorData->SetValueX( center - vectorData->GetValueVector2().x );
// }
// else
// {
// Gn2DAVData::CollisionRect& baseRect = mesh->GetAVData()->GetCollisionRect( 0 );
// float center = baseRect.mRect.GetWidth();// - vectorData->GetValueVector2().x;
// vectorData->SetValueX( center - vectorData->GetValueVector2().x);
// }
// }
// }
// }
Invalidate( false );
}
}
}
|
#pragma once
#include "EverydayTools/Bitset/EnumBitset.h"
namespace keng::graphics
{
enum class DeviceBufferUsage
{
Default,
Immutable,
Dynamic,
Staging,
Last
};
}
namespace edt
{
template<>
struct enable_enum_bitset<keng::graphics::DeviceBufferUsage>
{
static constexpr bool value = true;
};
}
|
// -*- Mode: C; indent-tabs-mode: nil -*-
#include "pty.h"
#include "VT100.h"
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <signal.h>
#include <pwd.h>
#include <termios.h>
#include <sys/ioctl.h>
#include <pthread.h>
#include <cstring>
#include <iostream>
static std::string getUsersShell()
{
// getpwuid isn't reentrant
struct passwd* pass = getpwuid(getuid());
if ((pass != NULL) && (pass->pw_shell != NULL)) {
return pass->pw_shell;
}
if (char* shellEnv = getenv("SHELL")) {
return shellEnv;
}
return std::string();
}
Pty::Pty(VT100* emulator)
: masterfd_(-1)
, emulator(emulator)
{
std::string shellPath = getUsersShell();
if (shellPath.empty()) {
fprintf(stderr, "Could not find your shell.");
exit(ERROR_GET_USERS_SHELL);
}
init(shellPath);
initializeReadWriteLoop();
}
Pty::~Pty()
{
sem_wait(&loopSemaphore_);
pthread_join(readWriteThread, NULL);
pthread_mutex_destroy(&writeMutex_);
}
static void* runReadWriteLoopThread(void* pty)
{
static_cast<Pty*>(pty)->readWriteLoop();
return NULL;
}
void Pty::initializeReadWriteLoop()
{
pthread_create(&readWriteThread, NULL, runReadWriteLoopThread, this);
}
void Pty::closeMasterFd() {
close(masterfd_);
masterfd_ = -1;
}
PtyInitResult Pty::init(const std::string& pathToExecutable) {
// todo: check?
pthread_mutex_init(&writeMutex_, NULL);
sem_init(&loopSemaphore_, 0, 1);
readBuffer_ = (char*)malloc(PTY_READ_BUFFER_SIZE);
writeBuffer_ = (char*)malloc(PTY_BUFFER_SIZE);
writeEnd_ = writeBuffer_;
// TODO: add some code to not fork is pathToExecutable is invalid.
int interactive = isatty(STDIN_FILENO);
char* ptsNameStr;
pid_t pid;
struct termios orig_termios;
if (interactive) {
if (tcgetattr(STDIN_FILENO, &orig_termios) < 0) {
return ERROR_TCGETATTR;
}
}
if((masterfd_ = posix_openpt(O_RDWR)) < 0) {
return ERROR_OPENPT;
}
// grant access to the slave pseudo-terminal
if(grantpt(masterfd_) < 0) {
this->closeMasterFd();
return ERROR_GRANTPT;
}
// unlock a pseudo-terminal master/slave pair
if(unlockpt(masterfd_) < 0) {
this->closeMasterFd();
return ERROR_UNLOCKPT;
}
// user the reentrant verstion of ptsname...
// ptsname isn't reentrant
if((ptsNameStr = ptsname(masterfd_)) == NULL) {
this->closeMasterFd();
return ERROR_PTSNAME;
}
// set masterfd to nonblocking i/o
int statusFlagsResult = fcntl(masterfd_, F_GETFL);
if ((statusFlagsResult != -1) && !(statusFlagsResult & O_NONBLOCK)) {
if(fcntl(masterfd_, F_SETFL, statusFlagsResult | O_NONBLOCK) < 0) {
this->closeMasterFd();
return ERROR_SET_NONBLOCK;
}
}
if((pid = fork()) < 0) {
this->closeMasterFd();
return ERROR_FORK;
}
else if(pid == 0) { // child
// creates a session and sets the process group ID
if(setsid() < 0) {
// TODO: better child error handling
printf("ERROR: setsid\n");
this->closeMasterFd();
exit(EXIT_FAILURE);
}
int slavefd;
// open slavefd
if((slavefd = open(ptsNameStr, O_RDWR)) < 0) {
// TODO: better child error handling
printf("ERROR: setsid\n");
this->closeMasterFd();
exit(EXIT_FAILURE);
}
this->closeMasterFd();
if (interactive) {
if (tcsetattr(slavefd, TCSANOW, &orig_termios) < 0) {
// TODO: better child error handling
printf("tcsetattr error on slave pty\n");
exit(EXIT_FAILURE);
}
}
// Slave becomes stdin/stdout/stderr of child.
if(dup2(slavefd, STDIN_FILENO) != STDIN_FILENO) {
printf("ERROR: dup2 stdin\n");
exit(EXIT_FAILURE);
}
if(dup2(slavefd, STDOUT_FILENO) != STDOUT_FILENO) {
printf("ERROR: dup2 stdout\n");
exit(EXIT_FAILURE);
}
std::cerr << "3 " << slavefd << ":" << STDERR_FILENO << std::endl;
if(dup2(slavefd, STDERR_FILENO) != STDERR_FILENO) {
printf("ERROR: dup2 stderr\n");
exit(EXIT_FAILURE);
}
if (slavefd != STDIN_FILENO && slavefd != STDOUT_FILENO &&
slavefd != STDERR_FILENO) {
close(slavefd);
}
execlp(pathToExecutable.c_str(), pathToExecutable.c_str(), NULL);
// TODO: better child error handling
printf("ERROR: exec issues\n");
exit(EXIT_FAILURE);
}
return SUCCESS;
}
int Pty::ptyWrite(const char* buffer, const int count) {
if (count <= 0) {
return 0;
}
pthread_mutex_lock(&writeMutex_);
ssize_t writeCount = 0;
// if the buffer is empty, try to write
if (writeBuffer_ == writeEnd_) {
writeCount = write(masterfd_, buffer, count);
if(count == writeCount) {
pthread_mutex_unlock(&writeMutex_);
return count;
}
}
// add to buffer anything that couldn't be written to the fd
int bufferSpace = PTY_BUFFER_SIZE - (writeEnd_ - writeBuffer_);
int toCopyAmount = count - writeCount;
if(toCopyAmount > bufferSpace) {
// @TODO log error out of buffer space
toCopyAmount = bufferSpace;
}
memcpy(writeEnd_, buffer + writeCount, toCopyAmount);
writeEnd_ += toCopyAmount;
pthread_mutex_unlock(&writeMutex_);
return toCopyAmount + writeCount;
}
int Pty::putChar(const char character) {
return this->ptyWrite(&character, 1);
}
void Pty::readWriteLoop() {
int amount, semval;
while(true) {
sem_getvalue(&loopSemaphore_, &semval);
if(semval <= 0) return;
amount = read(masterfd_, readBuffer_, PTY_READ_BUFFER_SIZE);
if(amount > 0) {
this->emulator->parseBuffer(readBuffer_,
readBuffer_ + amount);
}
pthread_mutex_lock(&writeMutex_);
// if the buffer is empty, try to write
if (writeBuffer_ != writeEnd_) {
ssize_t totalWriteAvailable = writeEnd_ - writeBuffer_;
ssize_t writeCount =
write(masterfd_, writeBuffer_, totalWriteAvailable);
// didn't write it all, memmove to beginning
if(totalWriteAvailable != writeCount) {
memmove(writeBuffer_, writeBuffer_ + writeCount,
totalWriteAvailable - writeCount);
// subtract the amount written from write end
writeEnd_ -= writeCount;
}
else {
// reset the write end;
writeEnd_ = writeBuffer_;
}
}
pthread_mutex_unlock(&writeMutex_);
pthread_yield();
}
}
void Pty::setSize(int columns, int rows)
{
printf("set size: %i %i\n", columns, rows);
struct winsize size = { rows, columns, 0, 0};
if (ioctl(masterfd_, TIOCSWINSZ, &size) < 0)
printf("TIOCSWINSZ error on master pty\n");
}
|
#include<iostream>
#include<vector>
#include<stdlib.h>
#include<fstream>
#include "goldchase.h"
#include "Map.h"
#include<unistd.h>
#include<errno.h>
#include<sys/types.h>
#include <fcntl.h> /* For O_* constants */
#include <sys/stat.h> /* For mode constants */
#include <semaphore.h>
#include <sys/mman.h>
#include <signal.h>
#include <mqueue.h>
#include <sstream>
#include <string>
#include <cstring>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include "fancyRW.h"
#include "mapboard.h"
using namespace std;
extern sem_t *sem;
extern string msgquename[];
string servmsgqname;
int sockfd; //file descriptor for the socket
int status; //for error checking
int new_sockfd; // file descriptor for each connection
string cliquename;
mqd_t msgquefd[5];
unsigned char *local_map; // local copy of map for server
mapboard *servmap_pointer;
//string msgquename[5]={"/PLAYER_QUEUE_1","/PLAYER_QUEUE_2","/PLAYER_QUEUE_3","/PLAYER_QUEUE_4","/PLAYER_QUEUE_5"};
//close(2);
//int fd=open("/home/pinakdas163/611myfiles/project4/pinakfifo", O_WRONLY);
unsigned char activePlayers() {
unsigned char activplayers=0;
if(servmap_pointer->players[0]!=0)
activplayers |= G_PLR0;
if(servmap_pointer->players[1]!=0)
activplayers |= G_PLR1;
if(servmap_pointer->players[2]!=0)
activplayers |= G_PLR2;
if(servmap_pointer->players[3]!=0)
activplayers |= G_PLR3;
if(servmap_pointer->players[4]!=0)
activplayers |= G_PLR4;
return activplayers;
}
void serversighandler(int handler)
{
if(handler==SIGHUP) {
unsigned char activeplayer = activePlayers();
unsigned char socketplayer = G_SOCKPLR|activeplayer;
//WRITE(2, &socketplayer, sizeof(char));
WRITE(new_sockfd, &socketplayer, sizeof(socketplayer));
if(socketplayer==G_SOCKPLR)
{
//WRITE(2, "All\n", 3);
//close(shm_fd);
shm_unlink("/TAG_mymap");
sem_close(sem);
sem_unlink("/mySem");
exit(0);
}
}
else if(handler==SIGUSR1)
{
std::vector<std::pair<short, unsigned char> > sockmap;
for(short i=0; i< servmap_pointer->rows*servmap_pointer->cols;i++)
{
if(local_map[i]!=servmap_pointer->map[i])
{
sockmap.push_back(std::make_pair(i, servmap_pointer->map[i]));
local_map[i]=servmap_pointer->map[i];
}
}
if(sockmap.size()>0)
{
short n = sockmap.size();
unsigned char byt = 0;
WRITE(new_sockfd, &byt, sizeof(byt));
WRITE(new_sockfd, &n, sizeof(n));
for(short i=0; i< n; i++)
{
short offset= sockmap[i].first;
unsigned char value = sockmap[i].second;
WRITE(new_sockfd, &offset, sizeof(offset));
WRITE(new_sockfd, &value, sizeof(value));
}
}
}
}
void servsigusr2handler(int) {
unsigned char sendtoclient;
//char* playermsg;
for(int i=0;i<5;i++)
{
int err;
char msg[250];
memset(msg, 0, 250);
while((err=mq_receive(msgquefd[i], msg, 250, NULL))!=-1) {
sendtoclient=G_SOCKMSG;
if(i==0)
{
sendtoclient |= G_PLR0;
}
else if(i==1)
{
sendtoclient|=G_PLR1;
}
else if(i==2)
{
sendtoclient|=G_PLR2;
}
else if(i==3)
{
sendtoclient|=G_PLR3;
}
else if(i==4)
{
sendtoclient|=G_PLR4;
}
short msgsize= strlen(msg);
//playermsg=msg;
WRITE(new_sockfd,&sendtoclient,sizeof(sendtoclient));
WRITE(new_sockfd,&msgsize,sizeof(msgsize));
WRITE(new_sockfd,&msg,msgsize);
}
}
}
void createServer() {
// close(2);
// int fd=open("/home/pinakdas163/611myfiles/project4/pinakfifo", O_WRONLY);
// server daemon start up
int shm_fd1=shm_open("/TAG_mymap",O_RDWR, S_IRUSR|S_IWUSR|S_IRWXU);
if(shm_fd1==-1)
{
WRITE(2, "shm_fd1 failed", sizeof("shm_fd1 failed"));
}
int rowp, colp;
if(read(shm_fd1, &rowp, sizeof(int))!=sizeof(int))
{
WRITE(2, "read-A failed\n",sizeof("read-a failed."));
}
if(read(shm_fd1, &colp, sizeof(int))!=sizeof(int))
{
WRITE(2, "read-B failed\n",sizeof("read-a failed."));
}
//WRITE(2, "just read rows/cols\n", sizeof("just read rows/cols\n"));
servmap_pointer=(mapboard*)mmap(NULL, (rowp*colp)+sizeof(mapboard), PROT_READ|PROT_WRITE,
MAP_SHARED, shm_fd1, 0);
if(servmap_pointer==MAP_FAILED)
{
WRITE(2, "map failed", sizeof("map failed"));
}
servmap_pointer->daemonID=getpid();
local_map = new unsigned char[rowp*colp];
memcpy(local_map, servmap_pointer->map, rowp*colp);
struct sigaction serversig_struct; // signal struct
sigemptyset(&serversig_struct.sa_mask);
serversig_struct.sa_flags=0;
serversig_struct.sa_restorer=NULL;
serversig_struct.sa_handler=serversighandler;
//
sigaction(SIGHUP, &serversig_struct, NULL);
sigaction(SIGUSR1, &serversig_struct, NULL);
struct mq_attr mq_servdaemon;
mq_servdaemon.mq_maxmsg=10;
mq_servdaemon.mq_msgsize=250;
mq_servdaemon.mq_flags=0;
serversig_struct.sa_handler=servsigusr2handler;
sigaction(SIGUSR2, &serversig_struct, NULL);
// ending of setup
// server connection establishment
//change this # between 2000-65k before using
const char* portno="62010";
struct addrinfo hints;
memset(&hints, 0, sizeof(hints)); //zero out everything in structure
hints.ai_family = AF_UNSPEC; //don't care. Either IPv4 or IPv6
hints.ai_socktype=SOCK_STREAM; // TCP stream sockets
hints.ai_flags=AI_PASSIVE; //file in the IP of the server for me
struct addrinfo *servinfo;
if((status=getaddrinfo(NULL, portno, &hints, &servinfo))==-1)
{
fprintf(stderr, "getaddrinfo error: %s\n", gai_strerror(status));
exit(1);
}
sockfd=socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol);
/*avoid "Address already in use" error*/
int yes=1;
if(setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int))==-1)
{
perror("setsockopt");
exit(1);
}
//We need to "bind" the socket to the port number so that the kernel
//can match an incoming packet on a port to the proper process
if((status=bind(sockfd, servinfo->ai_addr, servinfo->ai_addrlen))==-1)
{
perror("bind");
exit(1);
}
//when done, release dynamically allocated memory
freeaddrinfo(servinfo);
if(listen(sockfd,1)==-1)
{
perror("listen");
exit(1);
}
//printf("Blocking, waiting for client to connect\n");
struct sockaddr_in client_addr;
socklen_t clientSize=sizeof(client_addr);
do {
new_sockfd=accept(sockfd, (struct sockaddr*) &client_addr, &clientSize);
}while(new_sockfd==-1 && errno==EINTR);
if(new_sockfd==-1 && errno!=EINTR)
{
perror("accept");
exit(1);
}
// read and write to the socket will be here
unsigned char servplayers = activePlayers();
unsigned char playersock = G_SOCKPLR|servplayers;
WRITE(new_sockfd, &rowp, sizeof(rowp));
WRITE(new_sockfd, &colp, sizeof(colp));
for(int i=0;i<rowp*colp;i++)
{
WRITE(new_sockfd, &local_map[i], sizeof(local_map[i]));
}
WRITE(new_sockfd, &playersock, sizeof(playersock));
while(true) {
unsigned char protocol, newmapbyte;
short noOfchangedmap, offset;
unsigned char playerbit[5]= {G_PLR0, G_PLR1, G_PLR2, G_PLR3, G_PLR4};
short msglength;
char msgreceived[250];
READ(new_sockfd, &protocol, sizeof(protocol));
if(protocol & G_SOCKPLR)
{
for(int i=0;i<5; i++)
{
if(protocol & playerbit[i] && servmap_pointer->players[i]==0)
{
struct mq_attr mq_clientplayer;
mq_clientplayer.mq_flags=0;
mq_clientplayer.mq_maxmsg=10;
mq_clientplayer.mq_msgsize=250;
cliquename=msgquename[i];
if((msgquefd[i]=mq_open(cliquename.c_str(), O_CREAT|O_RDONLY|O_EXCL|O_NONBLOCK,
S_IRUSR|S_IWUSR, &mq_clientplayer))==-1)
{
perror("mq_open");
exit(1);
}
struct sigevent mq_notification_event;
mq_notification_event.sigev_notify=SIGEV_SIGNAL;
mq_notification_event.sigev_signo=SIGUSR2;
mq_notify(msgquefd[i], &mq_notification_event);
servmap_pointer->players[i]=getpid();
}
else if((protocol & playerbit[i])==false && servmap_pointer->players[i]!=0)
{
servmap_pointer->players[i]=0;
cliquename=msgquename[i];
mq_close(msgquefd[i]);
mq_unlink(cliquename.c_str());
}
}
if(protocol==G_SOCKPLR)
{
shm_unlink("/TAG_mymap");
sem_close(sem);
sem_unlink("/mySem");
exit(0);
}
}
else if(protocol==0) {
READ(new_sockfd, &noOfchangedmap, sizeof(noOfchangedmap));
for(short i=0;i<noOfchangedmap; i++)
{
READ(new_sockfd, &offset, sizeof(offset));
READ(new_sockfd, &newmapbyte, sizeof(newmapbyte));
servmap_pointer->map[offset]=newmapbyte;
local_map[offset]=newmapbyte;
}
for(int i=0;i<5; i++)
{
if(servmap_pointer->players[i]!=0 && servmap_pointer->players[i]!=getpid())
{
kill(servmap_pointer->players[i], SIGUSR1);
}
}
}
else if(protocol & G_SOCKMSG)
{
unsigned char serverplayermsg;
if(protocol & G_PLR0)
{
serverplayermsg=G_PLR0;
servmsgqname=msgquename[0];
}
else if(protocol & G_PLR1)
{
serverplayermsg=G_PLR1;
servmsgqname=msgquename[1];
}
else if(protocol & G_PLR2)
{
serverplayermsg=G_PLR2;
servmsgqname=msgquename[2];
}
else if(protocol & G_PLR3)
{
serverplayermsg=G_PLR3;
servmsgqname=msgquename[3];
}
else if(protocol & G_PLR4)
{
serverplayermsg=G_PLR4;
servmsgqname=msgquename[4];
}
READ(new_sockfd, &msglength, sizeof(msglength));
READ(new_sockfd, &msgreceived, msglength);
mqd_t serverplayerwrite;
if((serverplayerwrite=mq_open(servmsgqname.c_str(), O_WRONLY|O_NONBLOCK))==-1)
{
perror("mq_open error in server daemon");
exit(1);
}
//cerr << "fd=" << writequeue_fd << endl;
char message[250];
memset(message, 0, 250);
strncpy(message, msgreceived, 250);
if(mq_send(serverplayerwrite, message, strlen(message), 0)==-1)
{
perror("mq_send error from daemon");
exit(1);
}
mq_close(serverplayerwrite);
}
}
close(sockfd);
close(new_sockfd);
delete local_map;
}
void create_server_daemon()
{
if(fork() > 0)
{
return;
}
if(fork()>0)
exit(0);
if(setsid()==-1) //child obtains its own SID & Process Group
exit(1);
for(int i=0; i<sysconf(_SC_OPEN_MAX); ++i)
close(i);
open("/dev/null", O_RDWR); //fd 0
open("/dev/null", O_RDWR); //fd 1
open("/dev/null", O_RDWR); //fd 2
// int fd=open("/home/pinakdas163/611myfiles/project4/pinakfifo", O_WRONLY);
// if(fd==-1)
// {
// exit(99);
// }
umask(0);
chdir("/");
//now do whatever you want the daemon to do
createServer();
}
|
class v3 {
public:
float x,y,z;
v3();
v3(float, float, float);
void randomize();
__host__ __device__ void normalize();
__host__ __device__ void scramble();
};
|
#include<iostream>
#include<cstdlib>
using namespace std;
typedef int ElemType;
typedef struct node {
ElemType data;
struct node *next;
}LNode, *LinkList;
LinkList CreateLinkList(int n)
{
LinkList p, q, list = NULL;
ElemType e;
for (int i = 1; i <= n; i ++) {
cout << "Please input number:" << endl;
cin >> e;
p = (LinkList)malloc(sizeof(LNode));
p -> data = e;
p -> next = NULL;
if (! list) {
list = p;
} else {
q -> next = p;
}
q = p;
}
return list;
}
void insertLinkList(LinkList *list, LinkList q, ElemType e)
{
LinkList p;
p = (LinkList)malloc(sizeof(LNode));
p -> data = e;
if (! *list) {
*list = p;
p -> next = NULL;
} else {
p -> next = q -> next;
q -> next = p;
}
}
void deleteLinkList(LinkList *list, LinkList q)
{
LinkList p;
if (q == *list) {
*list = q -> next;
free(q);
} else {
for (p = *list; p -> next != q; p = p -> next);
if (p -> next != NULL) {
p -> next = q -> next;
free(q);
}
}
}
void destoryLinkList(LinkList *list)
{
LinkList p, q;
p = *list;
while (p) {
q = p -> next;
free(p);
p = q;
}
*list = NULL;
}
// 输入一个单向链表,输出该链表中倒数第K 个节点,链表的倒数第0个节点为链表的尾指针
int main()
{
LinkList list, q;
ElemType e;
list = CreateLinkList(1);
q = list;
cin >> e;
while (e) {
insertLinkList(&list, q, e);
q = q -> next;
cin >> e;
}
q = list;
cout << endl << "The LinkList content is:" << endl;
while (q) {
cout << q -> data << " ";
q = q -> next;
}
q = list;
cout << endl << "delete fifth element :" << endl;
for (int i = 0; i < 4; i ++) {
if (q == NULL) {
cout << "LinkList is short!" << endl;
}
q = q -> next;
}
deleteLinkList(&list, q);
q = list;
while (q) {
cout << q -> data << " ";
q = q -> next;
}
destoryLinkList(&list);
return 0;
}
|
// Created on: 1994-03-24
// Created by: model
// Copyright (c) 1994-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _Adaptor3d_TopolTool_HeaderFile
#define _Adaptor3d_TopolTool_HeaderFile
#include <Adaptor2d_Line2d.hxx>
#include <Adaptor3d_HVertex.hxx>
#include <Adaptor3d_Surface.hxx>
#include <TColStd_Array1OfReal.hxx>
#include <TColStd_HArray1OfReal.hxx>
#include <TopAbs_State.hxx>
#include <TopAbs_Orientation.hxx>
class Adaptor3d_HVertex;
DEFINE_STANDARD_HANDLE(Adaptor3d_TopolTool, Standard_Transient)
//! This class provides a default topological tool,
//! based on the Umin,Vmin,Umax,Vmax of an HSurface from Adaptor3d.
//! All methods and fields may be redefined when inheriting from this class.
//! This class is used to instantiate algorithms as Intersection, outlines,...
class Adaptor3d_TopolTool : public Standard_Transient
{
public:
Standard_EXPORT Adaptor3d_TopolTool();
Standard_EXPORT Adaptor3d_TopolTool(const Handle(Adaptor3d_Surface)& Surface);
Standard_EXPORT virtual void Initialize();
Standard_EXPORT virtual void Initialize (const Handle(Adaptor3d_Surface)& S);
Standard_EXPORT virtual void Initialize (const Handle(Adaptor2d_Curve2d)& Curve);
Standard_EXPORT virtual void Init();
Standard_EXPORT virtual Standard_Boolean More();
Standard_EXPORT virtual Handle(Adaptor2d_Curve2d) Value();
Standard_EXPORT virtual void Next();
Standard_EXPORT virtual void InitVertexIterator();
Standard_EXPORT virtual Standard_Boolean MoreVertex();
Standard_EXPORT virtual Handle(Adaptor3d_HVertex) Vertex();
Standard_EXPORT virtual void NextVertex();
Standard_EXPORT virtual TopAbs_State Classify (const gp_Pnt2d& P, const Standard_Real Tol, const Standard_Boolean ReacdreOnPeriodic = Standard_True);
Standard_EXPORT virtual Standard_Boolean IsThePointOn (const gp_Pnt2d& P, const Standard_Real Tol, const Standard_Boolean ReacdreOnPeriodic = Standard_True);
//! If the function returns the orientation of the arc.
//! If the orientation is FORWARD or REVERSED, the arc is
//! a "real" limit of the surface.
//! If the orientation is INTERNAL or EXTERNAL, the arc is
//! considered as an arc on the surface.
Standard_EXPORT virtual TopAbs_Orientation Orientation (const Handle(Adaptor2d_Curve2d)& C);
//! Returns the orientation of the vertex V.
//! The vertex has been found with an exploration on
//! a given arc. The orientation is the orientation
//! of the vertex on this arc.
Standard_EXPORT virtual TopAbs_Orientation Orientation (const Handle(Adaptor3d_HVertex)& V);
//! Returns True if the vertices V1 and V2 are identical.
//! This method does not take the orientation of the
//! vertices in account.
Standard_EXPORT virtual Standard_Boolean Identical (const Handle(Adaptor3d_HVertex)& V1, const Handle(Adaptor3d_HVertex)& V2);
//! answers if arcs and vertices may have 3d representations,
//! so that we could use Tol3d and Pnt methods.
Standard_EXPORT virtual Standard_Boolean Has3d() const;
//! returns 3d tolerance of the arc C
Standard_EXPORT virtual Standard_Real Tol3d (const Handle(Adaptor2d_Curve2d)& C) const;
//! returns 3d tolerance of the vertex V
Standard_EXPORT virtual Standard_Real Tol3d (const Handle(Adaptor3d_HVertex)& V) const;
//! returns 3d point of the vertex V
Standard_EXPORT virtual gp_Pnt Pnt (const Handle(Adaptor3d_HVertex)& V) const;
Standard_EXPORT virtual void ComputeSamplePoints();
//! compute the sample-points for the intersections algorithms
Standard_EXPORT virtual Standard_Integer NbSamplesU();
//! compute the sample-points for the intersections algorithms
Standard_EXPORT virtual Standard_Integer NbSamplesV();
//! compute the sample-points for the intersections algorithms
Standard_EXPORT virtual Standard_Integer NbSamples();
//! return the set of U parameters on the surface
//! obtained by the method SamplePnts
Standard_EXPORT void UParameters (TColStd_Array1OfReal& theArray) const;
//! return the set of V parameters on the surface
//! obtained by the method SamplePnts
Standard_EXPORT void VParameters (TColStd_Array1OfReal& theArray) const;
Standard_EXPORT virtual void SamplePoint (const Standard_Integer Index, gp_Pnt2d& P2d, gp_Pnt& P3d);
Standard_EXPORT virtual Standard_Boolean DomainIsInfinite();
Standard_EXPORT virtual Standard_Address Edge() const;
//! Compute the sample-points for the intersections algorithms by adaptive algorithm for BSpline surfaces.
//! For other surfaces algorithm is the same as in method ComputeSamplePoints(),
//! but only fill arrays of U and V sample parameters;
//! @param theDefl [in] a required deflection
//! @param theNUmin [in] minimal nb points for U
//! @param theNVmin [in] minimal nb points for V
Standard_EXPORT virtual void SamplePnts (const Standard_Real theDefl,
const Standard_Integer theNUmin,
const Standard_Integer theNVmin);
//! Compute the sample-points for the intersections algorithms
//! by adaptive algorithm for BSpline surfaces - is used in SamplePnts
//! @param theDefl [in] required deflection
//! @param theNUmin [in] minimal nb points for U
//! @param theNVmin [in] minimal nb points for V
Standard_EXPORT virtual void BSplSamplePnts (const Standard_Real theDefl,
const Standard_Integer theNUmin,
const Standard_Integer theNVmin);
//! Returns true if provide uniform sampling of points.
Standard_EXPORT virtual Standard_Boolean IsUniformSampling() const;
//! Computes the cone's apex parameters.
//! @param[in] theC conical surface
//! @param[in] theU U parameter of cone's apex
//! @param[in] theV V parameter of cone's apex
Standard_EXPORT static void GetConeApexParam (const gp_Cone& theC, Standard_Real& theU, Standard_Real& theV);
DEFINE_STANDARD_RTTIEXT(Adaptor3d_TopolTool,Standard_Transient)
protected:
Handle(Adaptor3d_Surface) myS;
Standard_Integer myNbSamplesU;
Standard_Integer myNbSamplesV;
Handle(TColStd_HArray1OfReal) myUPars;
Handle(TColStd_HArray1OfReal) myVPars;
private:
Standard_Integer nbRestr;
Standard_Integer idRestr;
Standard_Real Uinf;
Standard_Real Usup;
Standard_Real Vinf;
Standard_Real Vsup;
Handle(Adaptor2d_Line2d) myRestr[4];
Standard_Integer nbVtx;
Standard_Integer idVtx;
Handle(Adaptor3d_HVertex) myVtx[2];
};
#endif // _Adaptor3d_TopolTool_HeaderFile
|
/*
* Created by Peng Qixiang on 2018/5/27.
*/
/*
* 输入一个整数数组,实现一个函数来调整该数组中数字的顺序。
* 使得所有的奇数位于数组的前半部分,所有的偶数位于位于数组的后半部分
* 并保证奇数和奇数,偶数和偶数之间的相对位置不变。
*
*/
# include <iostream>
# include <vector>
# include <stack>
using namespace std;
void reOrderArray(vector<int> &array) {
stack<int> odd;
stack<int> pair;
for(int i = 0; i < array.size(); i++){
if(array[i] % 2 == 1){
odd.push(array[i]);
}
else{
pair.push(array[i]);
}
}
int i = array.size() - 1;
while(!pair.empty()){
array[i] = pair.top();
pair.pop();
i--;
}
while(!odd.empty()){
array[i] = odd.top();
odd.pop();
i--;
}
}
int main(){
vector<int> a = vector<int>(4,0);
a[0] = 1;
a[1] = 2;
a[2] = 3;
a[3] = 4;
for(int i = 0; i < a.size(); i++){
cout << a[i] << endl;
}
reOrderArray(a);
for(int i = 0; i < a.size(); i++){
cout << a[i] << endl;
}
return 0;
}
|
#include <iostream>
#include <fstream>
#include <vector>
#include <time.h>
#include "Grafo.h"
#include "No.h"
#include "Adjacencia.h"
#include "Test.h"
int main(int argc, const char *argv[])
{
// GrafosGrupo2.exe instancias/instance_30.txt 20 100 0.2 10 5
if (argc <= 6) {
std::cout << "Uso: nome_do_programa <arquivo_de_entrada> <numero_execucoes> <numero_iteracoes> <alpha_randomizado> <bloco_iteracoes> <numero_alphas>";
return 1;
}
const char *arquivoEntrada = argv[1];
int numExecucoes = strtol(argv[2], NULL, 10);
int numIteracoes = strtol(argv[3], NULL, 10);
float alpha = strtof(argv[4], NULL);
int blocoIteracoes = strtol(argv[5], NULL, 10);
int numAlphas = strtol(argv[6], NULL, 10);
srand(time(NULL));
Grafo *grafo = new Grafo(false, false);
if (!grafo->lerArquivo(arquivoEntrada)) {
std::cout << "Arquivo n" << char(198) << "o encontrado!";
return 1;
}
grafo->imprimeInterferencias();
int melhor;
std::cout << "Guloso:" << std::endl;
grafo->gulosoFrequencias();
// grafo->imprimeGrafo();
std::cout << "Interferencia total: " << grafo->calculaInterferenciaTotal() << std::endl;
std::cout << std::endl << "Guloso randomizado:" << std::endl;
for (int i = 0; i < numExecucoes; ++i) {
melhor = grafo->gulosoRandomizadoFrequencias(numIteracoes, alpha);
// grafo->imprimeGrafo();
std::cout << "Interferencia total: " << melhor << std::endl;
}
std::cout << std::endl << "Guloso randomizado reativo:" << std::endl;
for (int i = 0; i < numExecucoes; ++i) {
melhor = grafo->gulosoRandomizadoReativoFrequencias(numIteracoes, blocoIteracoes, numAlphas);
// grafo->imprimeGrafo();
std::cout << "Interferencia total: " << melhor << std::endl;
}
return 0;
}
|
//-----------------------------------graphl.cpp------------------------------
//Johnathan Hewit
//Created: 02/04/2019
//Modified: 02/16/2019
//---------------------------------------------------------------------------
//Purpose: Implementation file for GraphL class. GraphL is designed to read a
// .txt file formatted to provide an int (number of nodes), strings
// (names of locations), and 2 ints (number of starting node and ending
// node). This program then inserts that information into a graph, and
// uses the depth-first search algorithm to locate a path to each node.
//---------------------------------------------------------------------------
//Notes: Assumption: NodeData (container for strings of names of locations)
// provides proper data checking and overloads appropriate operators
// for comparison, and the file being provided is formatted correctly.
//---------------------------------------------------------------------------
#include "graphl.h"
using namespace std;
//--------------------------------GraphL-------------------------------------
//Description: Empty Constructor - sets default value for size; 0.
//---------------------------------------------------------------------------
GraphL::GraphL()
{
this->size = 0;
} //end of GraphL
//-------------------------------~GraphL-------------------------------------
//Description: Deconstructor - Deletes (deallocates memory) of EdgeNodes along
// each Node in the nodes array. Then deletes the NodeData, and
// finally the nodes array.
//---------------------------------------------------------------------------
GraphL::~GraphL()
{
if (this->size > 0) //Only proceed if the object isn't empty
{
for (int i = 1; i <= this->size; i++) //Loop over each node in the array
{
while (nodes[i].edgeHead != nullptr) //Then loop over each edge
{ //attached to the node
EdgeNode *temp = nodes[i].edgeHead; //Assigning a temporary holder for
nodes[i].edgeHead = nodes[i].edgeHead->nextEdge; //the object, then
temp->nextEdge = nullptr; //moving the pointer ahead to the
delete temp; //next Edge, and delete the old
}
delete nodes[i].data; //Delete the data for the node, and reassign the
nodes[i].data = nullptr; //pointer to null
}
delete[] nodes; //Delete the array
}
} //end of ~GraphL
//-----------------------------buildGraph------------------------------------
//Description: Public function to build the graph from data in a .txt file.
// Receives the file ifstream oject from a main driver, and first
// establishes the number of nodes in the graph (int), followed by
// the location (string), then finally the starting node, and its
// adjacent edge node. Assumption: Data in the .txt file is
// properly formatted.
//---------------------------------------------------------------------------
bool GraphL::buildGraph(ifstream &inFile)
{
inFile >> this->size; //Establish size based on number of nodes
int fromNode, toNode;
if (this->size <= 0) //If it's empty, don't do anything
{
return false;
}
else //Otherwise, create the array, with its size equal the number of nodes + 1
{ //due to the array's first used element starting at 1
nodes = new GraphNode[size + 1];
inFile.get(); //Remove the chars in following the int ("\n")
inFile.get();
for (int i = 1; i <= size; i++)
{ //Next loop over each of the nodes, initializing default values
nodes[i].data = new NodeData; //Allocate memory for the NodeData
nodes[i].data->setData(inFile); //Set the NodeData from string in file,
nodes[i].edgeHead = nullptr; //then assign it to the data in the Node
nodes[i].visited = false;
}
for (;;) //Loop until broken
{
inFile >> fromNode >> toNode; //Assign each variable
if (inFile.eof())
{
break;
} //Break if at the end of the file, or if the values of the variables are 0
if (fromNode == 0 || toNode == 0)
{
break;
}
insertEdge(fromNode, toNode); //Call private function to insert the Edge
} //as an EdgeNode
}
return true;
} //end of buildGraph
//-----------------------------insertEdge------------------------------------
//Description: Private helper function to insert an edge into an EdgeNode
// given its starting node and its adjacent.
//---------------------------------------------------------------------------
bool GraphL::insertEdge(const int fromNode, const int toNode)
{
if (fromNode != toNode) //If the nodes are the same, there is no edge
{
EdgeNode *newEdge = new EdgeNode; //Allocate memory for the new edge
newEdge->adjGraphNode = toNode; //Store the location of the adjacent node
if(nodes[fromNode].edgeHead == nullptr)
{ //If there is no edge currently attached to the Node, set this one as head
newEdge->nextEdge = nullptr;
nodes[fromNode].edgeHead = newEdge;
}
else
{ //Otherwise, attach the old head to the end of the new edge, and the set
newEdge->nextEdge = nodes[fromNode].edgeHead; //the new edge as head
nodes[fromNode].edgeHead = newEdge; //(allowing output to appear in reverse
} //order compared to the file)
return true;
}
return false;
} //end of insertEdge
//--------------------------depthFirstSearch---------------------------------
//Description: Public function to execute a search on a graph using the
// depth-first search algorithm to traverse each node in the graph
// in order. Outputs the results of traversal. Calls the dfsHelper
// private recursive helper function.
//---------------------------------------------------------------------------
bool GraphL::depthFirstSearch() const
{
if (this->size == 0) //If the graph is empty, do nothing
{
return false;
}
else
{
for (int i = 1; i <= this->size; i++) //Loop over each node, and set them to
{ //unvisited
nodes[i].visited = false;
}
cout << "Depth-first ordering: "; //Format to indicate the order of traversal
for (int v = 1; v <= size; v++) //Loop over each node, check if it's been
{ //visited, and if not, call the helper
if (!(nodes[v].visited))
{
dfsHelper(v);
}
}
}
cout << endl << endl; //Double new line to stay consistent with required format
return true;
} //end of depthFirstSearch
//------------------------------dfsHelper------------------------------------
//Description: Private recursive helper function for depthFirstSearch. Outputs
// results of traversal according to required formatting. Parameter
// received is that of an unvisited node.
//---------------------------------------------------------------------------
void GraphL::dfsHelper(const int v) const
{
nodes[v].visited = true; //Mark the node as visited, and print the node
cout << v << " ";
EdgeNode *current = nodes[v].edgeHead; //Establish a current to traverse list
while (current != nullptr)
{
if (!(nodes[current->adjGraphNode].visited)) //If the adjacent node has not
{ //been visited, keep traversing
dfsHelper(current->adjGraphNode);
}
current = current->nextEdge;
}
} //end of dfsHelper
//----------------------------displayGraph-----------------------------------
//Description: Public function to display the contents of the graph in required
// format.
//---------------------------------------------------------------------------
void GraphL::displayGraph() const
{
if (this->size > 0) //Only display if the graph is not empty
{
cout << "Graph:" << endl; //Header
for (int i = 1; i <= this->size; i++)
{ //Loop over each nodes and format header for the node and print its value
cout << "Node" << i << " " << *nodes[i].data << endl;
if (nodes[i].edgeHead != nullptr)
{ //If there is adjacent and connected node, continue with traversing list
EdgeNode *current = nodes[i].edgeHead;
while (current != nullptr)
{ //Print the value of the adjacent node and continue through the list
cout << " edge " << i << " " << current->adjGraphNode << endl;
current = current->nextEdge;
}
}
}
}
cout << endl; //New line to stay consistent with output format
} //end of displayGraph
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <quic/state/OutstandingPacket.h>
#include <quic/state/QuicStreamUtilities.h>
#include <quic/state/StateData.h>
namespace quic {
QuicStreamState::QuicStreamState(StreamId idIn, QuicConnectionStateBase& connIn)
: conn(connIn), id(idIn) {
// Note: this will set a windowSize for a locally-initiated unidirectional
// stream even though that value is meaningless.
flowControlState.windowSize = isUnidirectionalStream(idIn)
? conn.transportSettings.advertisedInitialUniStreamFlowControlWindow
: isLocalStream(connIn.nodeType, idIn)
? conn.transportSettings.advertisedInitialBidiLocalStreamFlowControlWindow
: conn.transportSettings
.advertisedInitialBidiRemoteStreamFlowControlWindow;
flowControlState.advertisedMaxOffset = isUnidirectionalStream(idIn)
? conn.transportSettings.advertisedInitialUniStreamFlowControlWindow
: isLocalStream(connIn.nodeType, idIn)
? conn.transportSettings.advertisedInitialBidiLocalStreamFlowControlWindow
: conn.transportSettings
.advertisedInitialBidiRemoteStreamFlowControlWindow;
// Note: this will set a peerAdvertisedMaxOffset for a peer-initiated
// unidirectional stream even though that value is meaningless.
flowControlState.peerAdvertisedMaxOffset = isUnidirectionalStream(idIn)
? conn.flowControlState.peerAdvertisedInitialMaxStreamOffsetUni
: isLocalStream(connIn.nodeType, idIn)
? conn.flowControlState.peerAdvertisedInitialMaxStreamOffsetBidiRemote
: conn.flowControlState.peerAdvertisedInitialMaxStreamOffsetBidiLocal;
if (isUnidirectionalStream(idIn)) {
if (isLocalStream(connIn.nodeType, idIn)) {
recvState = StreamRecvState::Invalid;
} else {
sendState = StreamSendState::Invalid;
}
}
priority = connIn.transportSettings.defaultPriority;
}
QuicStreamState::QuicStreamState(
StreamId idIn,
const folly::Optional<StreamGroupId>& groupIdIn,
QuicConnectionStateBase& connIn)
: QuicStreamState(idIn, connIn) {
groupId = groupIdIn;
}
std::ostream& operator<<(std::ostream& os, const QuicConnectionStateBase& st) {
if (st.clientConnectionId) {
os << "client CID=" << *st.clientConnectionId;
} else {
os << "client CID=None";
}
if (st.serverConnectionId) {
os << " server CID=" << *st.serverConnectionId;
} else {
os << " server CID=None";
}
os << " peer address=" << st.peerAddress;
return os;
}
AckStateVersion::AckStateVersion(
uint64_t initialVersion,
uint64_t handshakeVersion,
uint64_t appDataVersion)
: initialAckStateVersion(initialVersion),
handshakeAckStateVersion(handshakeVersion),
appDataAckStateVersion(appDataVersion) {}
bool AckStateVersion::operator==(const AckStateVersion& other) const {
return initialAckStateVersion == other.initialAckStateVersion &&
handshakeAckStateVersion == other.handshakeAckStateVersion &&
appDataAckStateVersion == other.appDataAckStateVersion;
}
bool AckStateVersion::operator!=(const AckStateVersion& other) const {
return !operator==(other);
}
PacingRate::PacingRate(
std::chrono::microseconds intervalIn,
uint64_t burstSizeIn)
: interval(intervalIn), burstSize(burstSizeIn) {}
PacingRate::Builder&& PacingRate::Builder::setInterval(
std::chrono::microseconds intervalIn) && {
interval_ = intervalIn;
return std::move(*this);
}
PacingRate::Builder&& PacingRate::Builder::setBurstSize(
uint64_t burstSizeIn) && {
burstSize_ = burstSizeIn;
return std::move(*this);
}
PacingRate PacingRate::Builder::build() && {
return PacingRate(interval_, burstSize_);
}
bool QuicConnectionStateBase::retireAndSwitchPeerConnectionIds() {
const auto end = peerConnectionIds.end();
auto replacementConnIdDataIt{end};
auto currentConnIdDataIt{end};
auto& mainPeerId = nodeType == QuicNodeType::Client ? serverConnectionId
: clientConnectionId;
if (!mainPeerId) {
throw QuicTransportException(
"Attempting to retire null peer conn id",
TransportErrorCode::INTERNAL_ERROR);
}
// Retrieve the sequence number of the current cId, and find an unused
// ConnectionIdData.
for (auto it = peerConnectionIds.begin(); it != end; it++) {
if (replacementConnIdDataIt != end && currentConnIdDataIt != end) {
break;
}
if (it->connId == mainPeerId) {
currentConnIdDataIt = it;
} else if (replacementConnIdDataIt == end) {
replacementConnIdDataIt = it;
}
}
if (replacementConnIdDataIt == end) {
return false;
}
DCHECK(currentConnIdDataIt != end);
pendingEvents.frames.push_back(
RetireConnectionIdFrame(currentConnIdDataIt->sequenceNumber));
mainPeerId = replacementConnIdDataIt->connId;
peerConnectionIds.erase(currentConnIdDataIt);
return true;
}
} // namespace quic
|
#ifndef MULTITIMER_H_MYIDENTIFY_1985
#define MULTITIMER_H_MYIDENTIFY_1985
#include <boost/function.hpp>
namespace threadpool
{
typedef boost::function<void()> task_type;
//used for multi timers.
class multitimer
{
private:
task_type m_timertask;
int m_delaysec;
int m_elapse;
bool m_inuse;
bool m_repeat;
int m_timerid; //the unique id for each timer.
static int timer_counter;
public:
multitimer(const task_type& task=NULL,int delaysec=0,bool repeat=false);
void add_elapse(int elapse);
bool isready();
bool inuse();
task_type& get_timertask_and_reset();
int getuniqueid();
void deletetimer();
};
}
#endif
|
// IPDetective Project
//
// Status: Aborted
//
// by Alessandro Polo 2002
// eWorld Network :: www.ewgate.net
//------------------------------------------------------------------------------
#ifndef mainH
#define mainH
//---------------------------------------------------------------------------
#include <Classes.hpp>
#include <Controls.hpp>
#include <StdCtrls.hpp>
#include <Forms.hpp>
#include <ComCtrls.hpp>
#include <ExtCtrls.hpp>
#include <Menus.hpp>
#include <CheckLst.hpp>
#include <Dialogs.hpp>
#include "cdiroutl.h"
//#include <Grids.hpp>
//#include <Outline.hpp>
//#include "SHDocVw_OCX.h"
//#include <OleServer.hpp>
#include <ImgList.hpp>
#include <Graphics.hpp>
// Serial IO Stuff
#include <vector>
// TrayIcon Stuff
#define MYWM_NOTIFY (WM_APP+100)
#define IDC_MYICON 1006
extern HINSTANCE g_hinst;
LRESULT IconDrawItem(LPDRAWITEMSTRUCT lpdi);
//---------------------------------------------------------------------------
class TmainFrm : public TForm
{
__published: // IDE-managed Components
TMainMenu *MainMenu;
TPanel *Panel1;
TMenuItem *File1;
TMenuItem *Edit1;
TMenuItem *About1;
TPageControl *ViewControlTabs;
TStatusBar *StatusBar1;
TTabSheet *Tab_Settings;
TTabSheet *Tab_LocalInfos;
TTabSheet *Tab_Automations;
TTabSheet *Tab_Services;
TMenuItem *IPDetective1;
TMenuItem *N1;
TMenuItem *SurfeWorld;
TMenuItem *N2;
TMenuItem *Exit1;
TTabSheet *Tab_ActiveConnection;
TTabSheet *Tab_Servers;
TPageControl *ServicesTab;
TTabSheet *TabPinger;
TTabSheet *TabFinger;
TTabSheet *TabPortScanner;
TTabSheet *TabTraceRoute;
TTabSheet *TabWhois;
TTabSheet *TabOSDetection;
TTabSheet *TabEMailValidator;
TTabSheet *TabSimpleServices;
TTabSheet *Tab_Terminal;
TTabSheet *Tab_ShortCuts;
TTabSheet *Tab_References;
TListView *ShortCutsListView;
TStaticText *IPHost0_slb;
TEdit *TargetIP_txt;
TTabSheet *TabWWWService;
TButton *Button1;
TButton *Button2;
TMenuItem *Upgrades1;
TMemo *TConsole_Memo;
TTabSheet *TabTRScannerService;
TOpenDialog *OpenDialog;
TSaveDialog *SaveDialog;
TTabSheet *TabLANServices;
TMemo *LANInfo_Memo;
TMemo *Pinger_Memo;
TButton *PingConnect_Btn;
TCheckListBox *Auto_CListBox;
TListView *Ref_ListView;
TTabSheet *TabICQ;
TGroupBox *GroupBox2;
TEdit *RFCFiles_Ed;
TLabel *Label2;
TMemo *WhoIs_Memo;
TGroupBox *GroupBox3;
TGroupBox *GroupBox4;
TButton *WhoisSend_btn;
TLabel *Label3;
TCheckListBox *WhoIsServers_lbx;
TButton *AddWIs_btn;
TEdit *WhoIsTargetIP_txt;
TStaticText *IPHost1_slb;
TButton *ImportWhoIsServers_btn;
TButton *ExportWhoIsServers_btn;
TMenuItem *ReportBugs1;
TButton *RemoveWIs_btn;
TTreeView *LanInfos_TreeView;
TGroupBox *GroupBox5;
TMemo *SimpleS_Memo;
TComboBox *SimpleServices_cmb;
TRadioButton *SimpleSProtocolTCP_opt;
TRadioButton *RadioButton6;
TLabel *Label4;
TEdit *SimpleSTargetPort_txt;
TListView *TrojanListView;
TGroupBox *GroupBox6;
TLabel *Label6;
TStaticText *StaticText4;
TButton *TrojanListReflesh_btn;
TButton *Button19;
TLabel *Label5;
TCheckBox *LANReportClean_chk;
TPageControl *SettingsTabs;
TTabSheet *SettingsGen_TabS;
TTabSheet *SettingsConn_TabS;
TTabSheet *SettingsDir_TabS;
TGroupBox *Term_Cmd_grp;
TButton *TermConnect_btn;
TButton *Button21;
TStaticText *TerminalCmdPath_slb;
TImage *OpenCmdList_img;
TListBox *TerminalCmdList_lbx;
TButton *Term_FileOpt_btn;
TButton *TermSendListCmds_btn;
TCheckBox *TermLCmdSync_chk;
TGroupBox *GroupBox11;
TEdit *TermTargetIP_txt;
TLabel *Label7;
TEdit *TermTargetPort_txt;
TLabel *Label8;
TButton *TermDisconnect_btn;
TTreeView *AppDirTreeView;
TGroupBox *GroupBox1;
TStaticText *DirActPath_stlb;
TLabel *Label9;
TLabel *Label10;
TStaticText *DirDefPath_stlb;
TImage *OpenData_img;
TGroupBox *ShortCutsListGroup;
TButton *ShortCutsListFileOpt_btn;
TImage *ShortCutOpenList_img;
TStaticText *ShortCutsFileList_slb;
TButton *Button25;
TGroupBox *GroupBox9;
TComboBox *LocalServer_cmb;
TLabel *Label11;
TLabel *Label12;
TLabel *Label13;
TEdit *Edit10;
TButton *Button26;
TButton *Button27;
TGroupBox *GroupBox12;
TListView *ListView1;
TGroupBox *GroupBox13;
TRadioButton *RadioButton10;
TRadioButton *RadioButton11;
TRadioButton *RadioButton12;
TListView *ListView3;
TGroupBox *GroupBox14;
TLabel *Label14;
TLabel *Label15;
TStaticText *PortScannerDataB_slb;
TButton *Button28;
TButton *Button29;
TRadioGroup *RadioGroup3;
TRadioButton *RadioButton13;
TRadioButton *RadioButton14;
TRadioButton *RadioButton15;
TRadioGroup *RadioGroup4;
TGroupBox *GroupBox7;
TRadioButton *RadioButton7;
TRadioButton *RadioButton8;
TRadioButton *RadioButton9;
TRadioButton *RadioButton16;
TRadioButton *TRCheckAll_opt;
TRadioButton *RadioButton18;
TButton *PortScanning_btn;
TButton *Button31;
TStaticText *DirDescript_stlb;
TLabel *Label16;
TButton *RFCRefleshList_btn;
TButton *RFCManageFiles_btn;
TGroupBox *GroupBox15;
TMemo *Memo2;
TGroupBox *GroupBox16;
TRadioButton *RadioButton20;
TEdit *PingN_txt;
TUpDown *UpDown1;
TRadioButton *PingLoop_opt;
TLabel *Label17;
TEdit *PingT_txt;
TUpDown *UpDown2;
TLabel *Label18;
TEdit *PingD_txt;
TUpDown *UpDown3;
TLabel *Label19;
TEdit *PingPn_txt;
TUpDown *UpDown4;
TLabel *Label20;
TEdit *PingPsize_txt;
TUpDown *UpDown5;
TMemo *Finger_Memo;
TMemo *Memo6;
TMemo *Memo7;
TMemo *Memo8;
TGroupBox *GroupBox17;
TButton *Button32;
TCheckBox *PingDefaults_chk;
TMenuItem *N3;
TMenuItem *N4;
TMenuItem *PasteIP1;
TMenuItem *CopyIP1;
TGroupBox *GroupBox18;
TRadioButton *SaveToReg_Opt;
TRadioButton *RadioButton2;
TGroupBox *GroupBox19;
TButton *SettingsConnApply_Btn;
TButton *ReLoadConnSettings_btn;
TButton *SettingsGenApply_Btn;
TButton *ReLoadGenSettings_btn;
TMenuItem *Windows1;
TMenuItem *WinMain_Mnu;
TMenuItem *N5;
TMenuItem *WinShortcuts_Mnu;
TMenuItem *WinTerminal_Mnu;
TMenuItem *WinActiveConnections_Mnu;
TMenuItem *N6;
TMenuItem *Loaddesktop1;
TMenuItem *default1;
TMenuItem *DesktopLastSaved_Mnu;
TMenuItem *SaveDesktop_Btn;
TCheckBox *TrayIcon_chk;
TCheckBox *Tray_NotClose_chk;
TCheckBox *Tray_Minimize_chk;
TGroupBox *GroupBox20;
TCheckBox *RunStartUp_chk;
TCheckBox *SplashShow_chk;
TPopupMenu *ShortCutsList_PopMnu;
TMenuItem *Update1;
TMenuItem *MenuItem1;
TMenuItem *Style1;
TMenuItem *SmallIcons1;
TMenuItem *Icons1;
TMenuItem *List1;
TMenuItem *Report1;
TMenuItem *MenuItem2;
TPopupMenu *Terminal_PopMnu;
TMenuItem *MenuItem3;
TMenuItem *MenuItem4;
TMenuItem *MenuItem5;
TMenuItem *TerminalFont_mnu;
TMenuItem *TerminalColor_mnu;
TMenuItem *MenuItem10;
TMenuItem *MenuItem11;
TPopupMenu *Ticon_PopupMnu;
TMenuItem *Properties1;
TMenuItem *WinShortcuts_Mnu2;
TMenuItem *Shutdown_Mnu;
TCheckBox *Tray_ShowAl_chk;
TMenuItem *TrayIcon_Mnu;
TMenuItem *WinTerminal_Mnu2;
TMenuItem *WinActiveConn_Mnu2;
TMenuItem *N7;
TPageControl *LS_PageControl;
TTabSheet *TabSheet5;
TMemo *OSInfo_Memo;
TButton *GetOSInfo_Btn;
TCheckBox *OSReportClean_chk;
TTreeView *LocalInfos_TreeView;
TTabSheet *TabSheet6;
TGroupBox *GroupBox21;
TButton *SerialConnect_Btn;
TGroupBox *GroupBox23;
TGroupBox *GroupBox24;
TButton *SerialOpenSocket_Btn;
TRichEdit *SerialOutData_REd;
TLabel *Label21;
TComboBox *SerialPort_CBox;
TLabel *Label22;
TComboBox *SerialBaud_CBox;
TLabel *Label23;
TStaticText *SerialStatus_Lb;
TButton *SerialSend_Btn;
TRichEdit *SerialDataIn_REd;
TCheckBox *DisableScreenSaver_chk;
TTabSheet *TabSheet7;
TGroupBox *GroupBox22;
TGroupBox *GroupBox25;
TButton *CaptureScreen_Btn;
TButton *CaptureSave_Btn;
TRadioButton *CaptureFullScreen_opt;
TRadioButton *RadioButton22;
TImage *CaptureShot_Img;
TEdit *CaptureWindow_Ed;
TGroupBox *GroupBox26;
TRadioButton *SystemPerf_opt;
TRadioButton *RadioButton23;
TCheckBox *Opt_LoadDLLs_chk;
TCheckBox *Opt_LoadData_chk;
TTabSheet *EventLog_TabS;
TMemo *Log_Memo;
TCheckBox *SaveonExit_chk;
TCheckBox *DesktopAutoSave_chk;
TGroupBox *GroupBox27;
TCheckBox *CheckBox8;
TComboBox *ComboBox3;
TLabel *Label24;
TLabel *Label25;
TStaticText *SettingsConnCurrConn_slb;
TButton *Button6;
TPopupMenu *txtBox_Popup;
TMenuItem *ClearLog_mnu;
TMenuItem *N8;
TMenuItem *SaveLogtoFile_mnu;
TMenuItem *Connections1;
TCheckBox *KeepLog_chk;
TGroupBox *GroupBox28;
TButton *Map_btn;
TButton *unMap_btn;
TGroupBox *GroupBox29;
TImage *ShortCutOpenItemPath_img;
TEdit *ShortCutName_txt;
TCheckBox *CheckBox2;
TButton *AddShortCut_btn;
TGroupBox *GroupBox30;
TGroupBox *GroupBox31;
TListBox *ListBox2;
TUpDown *UpDown6;
TImageList *MenuImageList;
TButton *WhoIsValidateServers_btn;
TGroupBox *GroupBox32;
TStaticText *IPHost2_slb;
TEdit *FingerTargetIP_txt;
TStaticText *StaticText6;
TEdit *FingerTargetPort_txt;
TGroupBox *GroupBox33;
TButton *FingerSend_btn;
TButton *Button5;
TGroupBox *GroupBox34;
TEdit *ShortCutPath_txt;
TMenuItem *N9;
TMenuItem *ShowLog_mnu;
TColorDialog *ColorDialog;
TFontDialog *FontDialog;
TFindDialog *FindDialog;
TImageList *LocalSysImageList;
TTabSheet *TabSheet4;
TImageList *LANImageList;
TTabSheet *TabSheet9;
TButton *LAN_CPModem_btn;
TButton *LAN_CPSystem_btn;
TButton *LAN_CPInternet_btn;
TButton *LAN_IntExpl_btn;
TButton *LAN_LocExpl_btn;
TStaticText *IPHost3_slb;
TEdit *SimpleSTargetIP_txt;
TEdit *PingTargetIP_txt;
TStaticText *IPHost4_slb;
TButton *GetLANInfo_Btn;
TLabel *Label26;
TPanel *Panel2;
TMemo *Memo1;
TMemo *CleagLogs_Memo;
TButton *LogsClear_btn;
TTreeView *IELogs_TreeView;
TCheckBox *CleagLogsReportClean_chk;
TCheckBox *CleagLogsShowAlert_chk;
TTabSheet *DeskTop_TabS;
TGroupBox *GroupBox35;
TComboBox *TranspForm_cmb;
TTrackBar *TranspTrackBar;
TButton *TraspApply_btn;
TButton *TransReset_btn;
TGroupBox *GroupBox36;
TStaticText *IPHos5_slb;
TEdit *TraceTargetIP_txt;
TButton *ReLoadDesktopSettings_btn;
TButton *SaveDesktopSetting_btn;
TButton *SaveAllSettings_btn;
TButton *ReLoadAllSettings_btn;
TStaticText *StaticText1;
TEdit *PingTargetPort_txt;
TGroupBox *GroupBox37;
TStaticText *StaticText2;
TEdit *PortScannerTargetIP_txt;
TImage *Image1;
TLabel *Label1;
TGroupBox *GroupBox38;
TRadioButton *RadioButton3;
TRadioButton *RadioButton4;
TEdit *Edit3;
TButton *Button9;
TButton *Button10;
TGroupBox *GroupBox39;
TEdit *ShortCutsCommandP_txt;
TComboBox *TConsole_cmb;
TPopupMenu *ShortCutsPopupMnu;
TMenuItem *OpenFile;
TMenuItem *EditwithNotepad;
TMenuItem *N10;
TMenuItem *loadDefault;
TGroupBox *GroupBox8;
TStaticText *SimpleServiceDesc_slb;
TGroupBox *GroupBox40;
TStaticText *StaticText3;
TEdit *OSDetectTargetIP_txt;
TMemo *OSDetect_Memo;
TGroupBox *GroupBox41;
TRadioButton *RadioButton5;
TRadioButton *RadioButton17;
TRadioButton *RadioButton19;
TCheckBox *CheckBox1;
TComboBox *ComboBox1;
TLabel *Label27;
TLabel *Label28;
TLabel *Label30;
TStaticText *PingAdvanced_slb;
TEdit *FingerUserName_txt;
TGroupBox *GroupBox42;
TGroupBox *GroupBox43;
TCheckBox *CheckBox3;
TListBox *ListBox1;
TStaticText *StaticText5;
TStaticText *StaticText7;
TImage *Image2;
TButton *Button3;
TButton *Button4;
TLabel *Label29;
TComboBox *LANComputer_Cmb;
TGroupBox *PingAdvanced_grp;
TEdit *PingMessage_txt;
TLabel *Label31;
TButton *SimpleSConnect_btn;
TMenuItem *N11;
TMenuItem *Find_Log_mnu;
TPanel *Panel3;
TPanel *Panel4;
TGroupBox *GroupBox10;
TStaticText *StaticText8;
TEdit *AttackTargetIP_txt;
TStaticText *StaticText9;
TEdit *AttackTargetPort_txt;
TGroupBox *GroupBox44;
TListBox *AttackDLLs_lbx;
TStaticText *AttackDLLPath_stb;
TGroupBox *GroupBox45;
TListBox *AttackFunctions_lbx;
TGroupBox *GroupBox46;
TStaticText *AttackFunctionDesc_stb;
TButton *AttackConnect_btn;
TButton *Button8;
TButton *AttackLoadDLL_btn;
TMemo *Attack_Memo;
TImage *AttackOpenDLL_img;
TImage *AttackLoadDLLDir_img;
TButton *AttackUnloadDLL_btn;
TImage *AttackLoadDLLList_img;
TGroupBox *GroupBox47;
TLabel *Label32;
TLabel *Label33;
TLabel *Label34;
TEdit *Edit2;
TEdit *Edit4;
TEdit *Edit5;
TButton *LS_Win2K_EnableLogOn_btn;
TButton *Button11;
void __fastcall GetOSInfo_BtnClick(TObject *Sender);
void __fastcall Map_btnClick(TObject *Sender);
void __fastcall Ref_ListViewClick(TObject *Sender);
void __fastcall IPDetective1Click(TObject *Sender);
void __fastcall WinShortcuts_MnuClick(TObject *Sender);
void __fastcall WinTerminal_MnuClick(TObject *Sender);
void __fastcall TrayIcon_MnuClick(TObject *Sender);
void __fastcall Shutdown_MnuClick(TObject *Sender);
void __fastcall WinActiveConn_MnuClick(TObject *Sender);
void __fastcall WinMain_MnuClick(TObject *Sender);
void __fastcall FormClose(TObject *Sender, TCloseAction &Action);
void __fastcall Button1Click(TObject *Sender);
void __fastcall SurfeWorldClick(TObject *Sender);
void __fastcall SerialConnect_BtnClick(TObject *Sender);
void __fastcall SerialOpenSocket_BtnClick(TObject *Sender);
void __fastcall SerialSend_BtnClick(TObject *Sender);
void __fastcall Ref_ListViewSelectItem(TObject *Sender,
TListItem *Item, bool Selected);
void __fastcall PingConnect_BtnClick(TObject *Sender);
void __fastcall CaptureScreen_BtnClick(TObject *Sender);
void __fastcall CaptureSave_BtnClick(TObject *Sender);
void __fastcall WhoisSend_btnClick(TObject *Sender);
void __fastcall TabWhoisShow(TObject *Sender);
void __fastcall SaveDesktop_BtnClick(TObject *Sender);
void __fastcall FormShow(TObject *Sender);
void __fastcall DesktopLastSaved_MnuClick(TObject *Sender);
void __fastcall TabICQShow(TObject *Sender);
void __fastcall SettingsGenApply_BtnClick(TObject *Sender);
void __fastcall ClearLog_mnuClick(TObject *Sender);
void __fastcall SaveLogtoFile_mnuClick(TObject *Sender);
void __fastcall ExportWhoIsServers_btnClick(TObject *Sender);
void __fastcall ImportWhoIsServers_btnClick(TObject *Sender);
void __fastcall unMap_btnClick(TObject *Sender);
void __fastcall Button6Click(TObject *Sender);
void __fastcall AppDirTreeViewChange(TObject *Sender,
TTreeNode *Node);
void __fastcall TermConnect_btnClick(TObject *Sender);
void __fastcall TermDisconnect_btnClick(TObject *Sender);
void __fastcall LocalServer_cmbChange(TObject *Sender);
void __fastcall Auto_CListBoxDragOver(TObject *Sender,
TObject *Source, int X, int Y, TDragState State, bool &Accept);
void __fastcall Auto_CListBoxDragDrop(TObject *Sender,
TObject *Source, int X, int Y);
void __fastcall RFCFiles_EdDblClick(TObject *Sender);
void __fastcall AddShortCut_btnClick(TObject *Sender);
void __fastcall AddWIs_btnClick(TObject *Sender);
void __fastcall RemoveWIs_btnClick(TObject *Sender);
void __fastcall PingPsize_txtChange(TObject *Sender);
void __fastcall PingT_txtChange(TObject *Sender);
void __fastcall PingD_txtChange(TObject *Sender);
void __fastcall PingPn_txtChange(TObject *Sender);
void __fastcall PingDefaults_chkClick(TObject *Sender);
void __fastcall ShortCutOpenItemPath_imgClick(TObject *Sender);
void __fastcall ShortCutsListViewSelectItem(TObject *Sender,
TListItem *Item, bool Selected);
void __fastcall ShowLog_mnuClick(TObject *Sender);
void __fastcall TerminalFont_mnuClick(TObject *Sender);
void __fastcall TerminalColor_mnuClick(TObject *Sender);
void __fastcall OpenCmdList_imgClick(TObject *Sender);
void __fastcall TermSendListCmds_btnClick(TObject *Sender);
void __fastcall TerminalCmdList_lbxClick(TObject *Sender);
void __fastcall LogsClear_btnClick(TObject *Sender);
void __fastcall LAN_CPModem_btnClick(TObject *Sender);
void __fastcall TRCheckAll_optClick(TObject *Sender);
void __fastcall OpenData_imgClick(TObject *Sender);
void __fastcall RFCManageFiles_btnClick(TObject *Sender);
void __fastcall ShortCutOpenList_imgClick(TObject *Sender);
void __fastcall LAN_CPInternet_btnClick(TObject *Sender);
void __fastcall LAN_CPSystem_btnClick(TObject *Sender);
void __fastcall TerminalCmdList_lbxDblClick(TObject *Sender);
void __fastcall IPorHost_slbClick(TObject *Sender);
void __fastcall TabPingerShow(TObject *Sender);
void __fastcall TabFingerShow(TObject *Sender);
void __fastcall TabPortScannerShow(TObject *Sender);
void __fastcall TabTraceRouteShow(TObject *Sender);
void __fastcall TabOSDetectionShow(TObject *Sender);
void __fastcall TabEMailValidatorShow(TObject *Sender);
void __fastcall TabLANServicesShow(TObject *Sender);
void __fastcall TabTRScannerServiceShow(TObject *Sender);
void __fastcall TabWWWServiceShow(TObject *Sender);
void __fastcall TabSimpleServicesShow(TObject *Sender);
void __fastcall RFCRefleshList_btnClick(TObject *Sender);
void __fastcall GetLANInfo_BtnClick(TObject *Sender);
void __fastcall LAN_LocExpl_btnClick(TObject *Sender);
void __fastcall LAN_IntExpl_btnClick(TObject *Sender);
void __fastcall TraspApply_btnClick(TObject *Sender);
void __fastcall TransReset_btnClick(TObject *Sender);
void __fastcall SaveAllSettings_btnClick(TObject *Sender);
void __fastcall ReLoadGenSettings_btnClick(TObject *Sender);
void __fastcall ReLoadAllSettings_btnClick(TObject *Sender);
void __fastcall TConsole_cmbKeyPress(TObject *Sender, char &Key);
void __fastcall ShortCutsListFileOpt_btnClick(TObject *Sender);
void __fastcall EditwithNotepadClick(TObject *Sender);
void __fastcall OpenFileClick(TObject *Sender);
void __fastcall ShortCutsCommandP_txtKeyPress(TObject *Sender,
char &Key);
void __fastcall SimpleServices_cmbChange(TObject *Sender);
void __fastcall WhoIsValidateServers_btnClick(TObject *Sender);
void __fastcall PortScanning_btnClick(TObject *Sender);
void __fastcall PingAdvanced_slbClick(TObject *Sender);
void __fastcall FingerSend_btnClick(TObject *Sender);
void __fastcall SettingsConn_TabSShow(TObject *Sender);
void __fastcall SimpleSConnect_btnClick(TObject *Sender);
void __fastcall Find_Log_mnuClick(TObject *Sender);
void __fastcall Term_FileOpt_btnClick(TObject *Sender);
void __fastcall LANComputer_CmbChange(TObject *Sender);
void __fastcall Auto_CListBoxKeyPress(TObject *Sender, char &Key);
void __fastcall AttackLoadDLL_btnClick(TObject *Sender);
void __fastcall AttackOpenDLL_imgClick(TObject *Sender);
void __fastcall AttackLoadDLLDir_imgClick(TObject *Sender);
void __fastcall AttackFunctions_lbxClick(TObject *Sender);
void __fastcall AttackConnect_btnClick(TObject *Sender);
void __fastcall AttackUnloadDLL_btnClick(TObject *Sender);
void __fastcall AttackLoadDLLList_imgClick(TObject *Sender);
void __fastcall LS_Win2K_EnableLogOn_btnClick(TObject *Sender);
private: // private user declarations
void __fastcall DrawItem(TMessage& Msg);
void __fastcall MyNotify(TMessage& Msg);
bool __fastcall TrayMessage(DWORD dwMessage);
PSTR __fastcall TipText(void);
// Tray Icon Stuff
LONG __fastcall TmainFrm::RegOpenOrCreateKeyEx(LPCTSTR KeyString, HKEY &hkey, HKEY RootKey = HKEY_LOCAL_MACHINE);
bool __fastcall TmainFrm::SaveWindowSetting(TForm * curForm, HKEY &hkey);
bool __fastcall TmainFrm::LoadWindowSetting(TForm * curForm, HKEY &hkey);
bool __fastcall TmainFrm::SaveSettReg(AnsiString name, bool value, HKEY &hkey);
DWORD __fastcall TmainFrm::LoadSettReg(AnsiString name, HKEY &hkey);
bool __fastcall TmainFrm::SaveServiceData(int ServiceID);
bool __fastcall TmainFrm::LoadServiceData(int ServiceID);
// Application Setting Saving
// bool __fastcall TmainFrm::OpenService(ServiceDLL Service, bool Report);
// Service DLL loading report
void __fastcall WndProc(Messages::TMessage &Message);
// Various System Stuff
std::vector <BYTE> m_TextStream; // Serial Port IO
TBackgroundCommThread *m_CommThread;
public: // public user declarations
__fastcall TmainFrm(TComponent* Owner);
BEGIN_MESSAGE_MAP
MESSAGE_HANDLER(WM_DRAWITEM,TMessage,DrawItem)
MESSAGE_HANDLER(MYWM_NOTIFY,TMessage,MyNotify)
END_MESSAGE_MAP(TForm)
void NewBytesReceived(const std::vector<BYTE> &stream);// Serial Port IO
};
//---------------------------------------------------------------------------
extern PACKAGE TmainFrm *mainFrm;
//---------------------------------------------------------------------------
class AppData
{
private:
AnsiString FileName;
int DataType; // 0 = INI
// 1 = TXT 1 Column
// 2 = Database
AnsiString defFileName;
AnsiString Description;
bool Status;
public:
AppData(AnsiString newFileName, int nDataType, AnsiString newDescription = "" );
bool SetFileName(AnsiString newFileName);
AnsiString GetTypeString();
AnsiString GetDescription(){return Description;};
AnsiString GetFileName(){return FileName;};
AnsiString GetdefFileName(){return defFileName;};
bool GetStatus(){return (this->Status);};
int GetType() {return (this->DataType);};
};
AppData DesktopINI("desktop.ini", 0, "Desktop Settings");
AppData SettingsINI("settings.ini", 0, "Application Settings");
AppData PortNames("portsnm.db", 2, "Ports' Names DataBase");
AppData OSReference("osfinger.db", 2, "OS Detercion Data");
AppData TRPortNames("trports.db", 2, "Trojan Ports List");
AppData ShortCutsList("shortcuts.db", 2, "ShortCuts List");
AppData ReferenceList("refs.db", 2, "Files Reference List");
AppData WhoIsServersList("wislist.txt", 1, "WhoIs Servers List");
AppData AppLog("log.txt", 1, "Application Log");
AppData *AllData[] = { &DesktopINI ,
&SettingsINI ,
&PortNames ,
&OSReference ,
&TRPortNames ,
&ShortCutsList ,
&ReferenceList };
#endif
|
#include<bits/stdc++.h>
typedef long long ll;
using namespace std;
char str[100000000];
main()
{
while(cin>>str)
{
ll len = strlen(str);
ll i, B_cont=0, u_cont=0, l_cont=0, b_cont=0, a_cont=0, s_cont=0, r_cont=0, t_cont=0;
for(i=0; i<len ; i++)
{
if(str[i]=='B')B_cont++;
else if(str[i]=='u')u_cont++;
else if(str[i]=='l')l_cont++;
else if(str[i]=='b')b_cont++;
else if(str[i]=='a')a_cont++;
else if(str[i]=='s')s_cont++;
else if(str[i]=='r')r_cont++;
}
if(B_cont>0 && u_cont>1 && l_cont>0 && b_cont>0 && a_cont>1 && s_cont>0 && r_cont>0)
{
u_cont = u_cont/2;
a_cont = a_cont/2;
cout<<min(B_cont, min(u_cont, min(l_cont, min(b_cont, min(a_cont, min(s_cont, r_cont)))))) <<endl;
}
else
cout<<t_cont<<endl;
}
return 0;
}
|
#include <iostream>
using namespace std;
int main ()
{
int array[1000], element_to_search, size_of_array;
cout<<"Enter the size of the array :- "<<" ";
cin>>size_of_array;
for(int i = 0; i<size_of_array; i++){
cin>>array[i]; //Input by the user
}
cout<<"Enter the element to search :- ";
cin>>element_to_search;
for (int i = 0; i<size_of_array; i++){
if (array[i] == element_to_search){
cout <<"element found at index i = "<<i; //Checking weather the element is present in array or not
}
}
return 0;
}
|
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <map>
#include <specex_unbls.h>
#include <specex_message.h>
#include <specex_string.h>
#include <specex_trace.h>
#include <specex_spot.h>
#include <specex_spot_array.h>
#include <specex_lamp_lines_utils.h>
#include <specex_fits.h>
#include <specex_psf_fitter.h>
#include <specex_tokens.h>
#include <specex_pyoptions.h>
#include <specex_pyio.h>
#include <specex_pyprior.h>
#include <specex_pyimage.h>
#include <specex_pyfitting.h>
using namespace std;
using namespace specex;
#define _GNU_SOURCE 1
#ifndef __USE_GNU
#define __USE_GNU
#endif
#include <portable_fenv.h>
/*
input format of fits file
HDU 0 : blank
HDU 1 ELECTRONS : 2D image of noisy electrons
- RDNOISE is in header
HDU 2 IVAR : Inverse variance [1/electrons^2]
- ivar = 1/(pix.clip(0) + rdnoise**2)
HDU 3 MASK : 0=good. Currently all 0.
HDU 4 XCOEFF : Legendre coefficients for mapping wavelength -> x
- WAVEMIN, WAVEMAX : domain for mapping to [-1,1] for Legendre polynomials
- image is coefficients for each fiber
HDU 5 YCOEFF : Legendre coefficients for mapping wavelength -> y
HDU 5 TRUE_ELECTRONS : original noiseless image in electrons
ELECTRONS = poisson(TRUE_ELECTRONS) + gaussian(rdnoise)
*/
int specex::PyFitting::fit_psf(
specex::PyOptions opts,
specex::PyIO pyio,
specex::PyPrior pypr,
specex::PyImage pymg,
specex::PyPSF& pyps
){
// to crash when NaN
feenableexcept (FE_INVALID|FE_DIVBYZERO|FE_OVERFLOW);
// set message prefix
std::stringstream mess;
if (pymg.header.find("CAMERA") != pymg.header.end() ) {
if (mess.str() != "" ) mess << "-";
string cam=pymg.header["CAMERA"];
std::replace(cam.begin(),cam.end(),'\'',' ');
trim(cam);
mess << cam;
}
if (pymg.header.find("EXPID") != pymg.header.end() ) {
if (mess.str() != "" ) mess << "-";
mess << std::setw(8) << std::setfill('0') << pymg.header["EXPID"];
}
{
if (mess.str() != "" ) mess << "-";
mess << std::setw(2) << std::setfill('0') << opts.first_fiber_bundle;
}
if (opts.last_fiber_bundle > opts.first_fiber_bundle ) {
if (mess.str() != "" ) mess << "-";
mess << std::setw(2) << std::setfill('0') << opts.last_fiber_bundle;
}
if (mess.str() != "" ) {
mess << ":";
specex_set_message_prefix(mess.str());
}
// copy to local psf pointer
specex::PSF_p psf = pyps.psf;
SPECEX_INFO("using lamp lines file " << opts.lamp_lines_filename);
if(opts.trace_prior_deg>0) SPECEX_INFO("Will apply a prior on the traces high order terms in a bundle");
// set broken fibers
vector<string> tokens = split(opts.broken_fibers_string,',');
vector<int> broken_fibers;
for(size_t i=0;i<tokens.size();i++) {
broken_fibers.push_back(atoi(tokens[i].c_str())%500);
}
SPECEX_DEBUG("number of input broken fibers: " << broken_fibers.size());
for(size_t i=0;i<broken_fibers.size();i++) {
SPECEX_DEBUG("input broken fiber #" << broken_fibers[i]);
}
for(size_t i=0;i<broken_fibers.size();i++) {
psf->FiberTraces[broken_fibers[i]].mask = 3;
SPECEX_DEBUG("Fiber trace " << broken_fibers[i] << " OFF=" << psf->FiberTraces[broken_fibers[i]].Off());
}
psf->ccd_image_n_cols = pymg.image.n_cols();
psf->ccd_image_n_rows = pymg.image.n_rows();
// bundle sizes
int number_of_fibers_per_bundle=0;
if(opts.single_bundle) {
number_of_fibers_per_bundle = psf->FiberTraces.size();
}else {
number_of_fibers_per_bundle = eval_bundle_size(psf->FiberTraces);
}
int number_of_fiber_bundles_per_ccd=psf->FiberTraces.size()/number_of_fibers_per_bundle;
if(opts.first_fiber_bundle<0 || opts.first_fiber_bundle>= number_of_fiber_bundles_per_ccd) {
SPECEX_ERROR("invalid first fiber bundle");
}
if(opts.last_fiber_bundle<opts.first_fiber_bundle || opts.last_fiber_bundle>= number_of_fiber_bundles_per_ccd) {
SPECEX_ERROR("invalid last fiber bundle");
}
// main body
try {
// init PSF fitter
// --------------------------------------------
PSF_Fitter fitter(psf,pymg.image,pymg.weight,pymg.rdnoise);
fitter.polynomial_degree_along_x = opts.legendre_deg_x;
fitter.polynomial_degree_along_wave = opts.legendre_deg_wave;
fitter.psf->psf_error = opts.psf_error;
fitter.corefootprint_weight_bst = opts.psf_core_wscale;
fitter.write_tmp_results = opts.write_tmp_results;
fitter.trace_prior_deg = opts.trace_prior_deg;
#ifdef EXTERNAL_TAIL
fitter.scheduled_fit_of_psf_tail = opts.fit_psf_tails;
#endif
#ifdef CONTINUUM
fitter.scheduled_fit_of_continuum = opts.fit_continuum;
#endif
fitter.scheduled_fit_with_weight_model = opts.use_variance_model;
fitter.scheduled_fit_of_traces = opts.fit_traces;
fitter.scheduled_fit_of_sigmas = opts.fit_sigmas;
fitter.scheduled_fit_of_psf = opts.fit_thepsf;
fitter.direct_simultaneous_fit = true; // use_input_specex_psf;
fitter.max_number_of_lines = opts.max_number_of_lines;
fitter.psf->gain = 1; // images are already in electrons
fitter.psf->readout_noise = 0; // readnoise is a property of image, not PSF
if(pymg.header.find("CAMERA") != pymg.header.end()) {
fitter.psf->camera_id = pymg.header["CAMERA"];
SPECEX_INFO("CAMERA = " << fitter.psf->camera_id );
}else{
SPECEX_WARNING("CAMERA Id not found in header");
}
fitter.priors = pypr.priors;
fitter.mask.Clear();
SPECEX_INFO(
"PSF '" << opts.psf_model << "' stamp size = "
<< psf->hSizeX << "x" << psf->hSizeY );
int first_fitted_fiber=-1;
int last_fitted_fiber=-1;
// loop on fiber bundles
// --------------------------------------------
for(int bundle = opts.first_fiber_bundle; bundle <= opts.last_fiber_bundle ; bundle ++) {
// allocate bundle in PSF if necessary
if(psf->ParamsOfBundles.find(bundle)==psf->ParamsOfBundles.end()) {
psf->ParamsOfBundles[bundle] = specex::PSF_Params();
psf->ParamsOfBundles[bundle].bundle_id = bundle;
psf->ParamsOfBundles[bundle].fiber_min = number_of_fibers_per_bundle*bundle;
psf->ParamsOfBundles[bundle].fiber_max = psf->ParamsOfBundles[bundle].fiber_min+number_of_fibers_per_bundle-1; // included
}
// now check mask ?
if(psf->ParamsOfBundles[bundle].fiber_min < opts.first_fiber) {
psf->ParamsOfBundles[bundle].fiber_min = opts.first_fiber;
SPECEX_INFO("restricting fiber range first fiber = " << opts.first_fiber);
}
if(psf->ParamsOfBundles[bundle].fiber_max > opts.last_fiber) {
psf->ParamsOfBundles[bundle].fiber_max = opts.last_fiber;
SPECEX_INFO("restricting fiber range last fiber = " << opts.last_fiber);
}
fitter.SelectFiberBundle(bundle);
// loading arc lamp spots belonging to this bundle
// --------------------------------------------
int ymin = 0; // range of usable CCD coordinates, hard coded for now
int ymax = pymg.image.n_rows(); // range of usable CCD coordinates, hard coded for now
/*
SPECEX_WARNING("RESTRICTING Y RANGE !!!!!");
if(psf->camera_id=="b1") {ymin=696; ymax = 3516;};
if(psf->camera_id=="b2") {ymin=696; ymax = 3516;};
if(psf->camera_id=="r1") {ymin=200; ymax = 3668;};
if(psf->camera_id=="r2") {ymin=200; ymax = 3668;};
*/
int margin = -psf->hSizeY+1; // we need to include spots that contribute to the image signal
ymin+=margin;
ymax-=margin;
SPECEX_INFO("valid y(=rows) range = " << ymin << " " << ymax);
vector<Spot_p> spots;
double min_wavelength = 0;
double max_wavelength = 1e6;
allocate_spots_of_bundle(spots,opts.lamp_lines_filename,psf->FiberTraces,
bundle,psf->ParamsOfBundles[bundle].fiber_min,
psf->ParamsOfBundles[bundle].fiber_max,ymin,ymax,
min_wavelength,max_wavelength);
SPECEX_INFO("number of spots = " << spots.size());
// starting fit
// --------------------------------------------
bool init_psf = (!pyio.use_input_specex_psf);
fitter.FitEverything(spots,init_psf);
int ndf = psf->ParamsOfBundles[bundle].ndata - psf->ParamsOfBundles[bundle].nparams;
SPECEX_INFO("Bundle " << bundle << " PSF fit status = " <<
psf->ParamsOfBundles[bundle].fit_status);
SPECEX_INFO("Bundle " << bundle << " PSF fit chi2/ndf = " <<
psf->ParamsOfBundles[bundle].chi2 << "/" << ndf <<
" = " << psf->ParamsOfBundles[bundle].chi2/ndf);
SPECEX_INFO("Bundle " << bundle << " PSF fit ndata = "<<
psf->ParamsOfBundles[bundle].ndata);
SPECEX_INFO("Bundle " << bundle << " PSF fit nspots = "<<
psf->ParamsOfBundles[bundle].nspots_in_fit);
SPECEX_INFO("Bundle " << bundle << " PSF fit chi2/ndata (core) = "<<
psf->ParamsOfBundles[bundle].chi2_in_core << "/" <<
psf->ParamsOfBundles[bundle].ndata_in_core << " = " <<
psf->ParamsOfBundles[bundle].chi2_in_core /
psf->ParamsOfBundles[bundle].ndata_in_core);
if(bundle == opts.first_fiber_bundle) {
first_fitted_fiber=psf->ParamsOfBundles[bundle].fiber_min;
last_fitted_fiber=psf->ParamsOfBundles[bundle].fiber_max;
}
first_fitted_fiber=min(first_fitted_fiber,psf->ParamsOfBundles[bundle].fiber_min);
last_fitted_fiber=max(last_fitted_fiber,psf->ParamsOfBundles[bundle].fiber_max);
for(size_t s=0;s<spots.size();s++) {
pyps.fitted_spots.push_back(spots[s]);
}
if(opts.fit_individual_spots_position) // for debugging
fitter.FitIndividualSpotPositions(spots);
} // end of loop on bundles
pyps.psf = fitter.psf;
// ending
// --------------------------------------------
}
catch (std::exception& e) {
cerr << "FATAL ERROR (other std) " << e.what() <<endl;
return EXIT_FAILURE;
}catch (...) {
cerr << "FATAL ERROR (unknown)" << endl;
return EXIT_FAILURE;
}
// may prevent crashing on non-floating point exceptions outside this function
fedisableexcept (FE_INVALID|FE_DIVBYZERO|FE_OVERFLOW);
return EXIT_SUCCESS;
}
|
/*In this program we will be seeing about LOOPS in C++ Program*/
/*In C++ while, do while and for are different loop Statements , which is used to execute certain number of codes for certain number of times. That is the code inside the loop will be execute certain number of times till the condition fails and loop comes out of the scope.*/
/*In this Example lets see how WHILE LOOP works in a program.*/
/*While loop is kind of LOOP , which is used to execute the code for certain number of times, till the condition fails. While loop is also know as 'ENTERY CHECK LOOP',that is loop will be execute only is the condition is True, if the condition is fails then the loop stop executing.*/
/*When the condition becomes false, then the program control passes to the line which is next to the loop end.*/
/*Syntax of while loop
while(condition)
{
Statement(S) / block of code ; //Any number of statements can present inside the loop
Increment;
}
*/
/*including preprocessor / header file in the program*/
#include <iostream>
/*using namespace*/
using namespace std ;
/*creating a main() function of the program*/
int main()
{
/* local variable definition */
int a = 1 ;
/*while loop*/
while ( a <= 10) /*While loop condition,Where condition will be checked.*/
{
cout<<"\nValue of a = " << a << endl ;
cout<<"\nThe WHILE LOOP is executed for " << a << endl ;
a++; /*Increment the value of variable a */
} /*End of while loop */
/*when this line is printed it print a = 11 , since 11 times the while condition has been checked and only at 11th time the condition has failed and while loop comes out the scope*/
cout<<"\nThe WHILE LOOP is checked for "<< a << " number of times." << endl ;
}
|
//My solution. Store the postion of each char. Not extendable to K distinct. 4ms
class Solution {
public:
int lengthOfLongestSubstringTwoDistinct(string s) {
vector<int> dict(128, -1);
int i, len = 0, curr = 0, count = 0;
for(i = 0; i < s.length(); ++i){
char c = s[i];
if(dict[c] < curr){
++count;
dict[c] = i;
if(count > 2){
len = max(len, i - curr);
count = 2;
curr = dict[s[i-1]];
}
}
if(c != s[i-1]) dict[c] = i;
}
len = max(len, i - curr);
return len;
}
};
//Extendable solution. 4ms
class Solution {
public:
int lengthOfLongestSubstringTwoDistinct(string s) {
vector<int> dict(128, 0);
int len = 0, curr = 0, count = 0;
for(int i = 0; i < s.length(); ++i){
char c = s[i];
++dict[c];
if(dict[c] == 1){
++count;
while(count > 2){
--dict[s[curr]];
if(!dict[s[curr]]) --count;
++curr;
}
}
len = max(len, i - curr + 1);
}
return len;
}
};
|
#include<bits/stdc++.h>
#define rep(i,n) for (int i =0; i <(n); i++)
using namespace std;
using ll = long long;
const double PI = 3.14159265358979323846;
int main(){
int N;
string S;
cin >> N >> S;
const ll num = 10000000000;
string S;
cin >> S;
if(S == "1"){
cout << num * 2 << endl;
return 0;
}
else if(S == "11" || S == "0" || S == "110"){
cout << num << endl;
return 0;
}
int r = 1;
int pos = 0;
//左端のはみ出てる部分をチェックしてスタート位置に この3パターンでなければ0
if(S.substr(0,1) == "0")pos = 1;
else if(S.substr(0,1) == "10")pos = 2;
else if(S.substr(0,2) == "110")pos = 3;
else {
cout << 0 << endl;
return 0;
}
while( pos < N){
if(pos + 3 <= N && S.substr(pos,3) == "110"){
r++;
pos += 3;
}
else if(pos ==2 && S.substr(pos,2) == "11"){
r++;
break;
}
else if(pos == 1 && S.substr(pos,1) == "1"){
r++;
break;
}
//ここまでに当てはまらなければ文字列は含まれない
else {
cout << 0 << endl;
return 0;
}
}
cout << num - r + 1 << endl;
return 0;
}
|
//hw2
#include <math.h>
#include <vector>
#include <algorithm>
#include <iostream>
#include <time.h>
#include <set>
//GLOBAL S boxes
int S1[4][4]={{1,0,3,2},{3,2,1,0},{0,2,1,3},{3,1,3,2}};
int S2[4][4]={{0,1,2,3},{2,0,1,3},{3,0,1,0},{2,1,0,3}};
//diffy helman stuff
std::vector<int> divis_2(int num){
// std::cout<<"IN DIVIS_2"<<std::endl;
std::vector<int> ret;
int r=0;
while (num%2==0){
// std::cout<<num<<std::endl;
r++;
num=num/2;
}
// std::cout<<std::endl;
ret.push_back(r);
ret.push_back(num);
return ret;
}
int mod_exp(int a, int e, int n){
int c=a;
int e2=e;
while(e2>1){
// std::cout<<e2<<std::endl;
if(e2%2==0){
c=(c*c)% n;
e2=e2/2;
}
else{
return (c*mod_exp(c,e2-1,n))%n;
}
}
return c;
}
bool check_prime(int n){
//2,7,61 test these 3.
// std::cout<<"IN CHECK PRIME"<<std::endl;
std::vector<int> wit={2,3,5,7,31,61,73};
std::vector<int> rd=divis_2(n-1);
int r=rd[0];
int d=rd[1];
for (int i = 0; i < wit.size(); ++i){
// int a=rand()%(n-4)+2;
int a=wit[i];
int x=mod_exp(a,d,n);
if(x==1 || x==(n-1)){
continue;
}
bool good=false;
for (int j = 0; j < r; ++j) {
x=mod_exp(x,2,n);
if (x==n-1){
good=true;
}
}
if (good){
continue;
}
return false;
}
return true;
}
int generate_prime(){
int a= rand();
// std::cout<<"HERE"<<std::endl;
while(!check_prime(a)){
// std::cout<<"CHECKING "<<a<<" FOR PRIME"<<std::endl;
a=rand();
}
return a;
}
int find_prime_root(int prime){
std::vector<int> factors;
int n=prime-1;
int check=2;
//get all factors.
while(!check_prime(n)){
if(n%check==0){
factors.push_back(check);
n=n/check;
}
else{
check++;
}
}
std::vector<int> factors2;
factors2.push_back(factors[0]);
for (int i = 0; i < factors.size(); ++i){
if(factors[i]!=factors2[factors2.size()-1]){
factors2.push_back(factors[i]);
}
}
for (int i=0; i<factors2.size(); ++i){
factors2[i]=(prime-1)/factors2[i];
}
int i=2;
while(i<prime){
bool is_root=true;
int j=0;
for (int j = 0; j < factors2.size(); ++j){
int a=mod_exp(i,factors2[j],prime);
if(a==1){
is_root=false;
break;
}
}
if(is_root){
return i;
}
i++;
}
}
//DES STUFF
int vector_to_int(std::vector<int> vec){
int val=0;
for (int i = 0; i < 8; ++i){
val+=pow(2,7-i)*vec[i];
}
return (char) val;
}
std::vector<int> int_to_vector(){}
std::vector<int> make_key(int num){
std::vector<int>fin(10);
for (int i = 0; i < 10; ++i){
fin[i]=num%2;
num/=2;
}
return fin;
}
std::vector<int> char_to_vector(char c){
std::vector<int> out(8);
for (int i = 7; i >= 0; --i){
out[i]=c&1;
c=c>>1;
}
return out;
}
char vector_to_char(std::vector<int> vec){
// 0,1,0,0,1,0,0,0
int val=0;
for (int i = 0; i < 8; ++i){
val+=pow(2,7-i)*vec[i];
}
return (char) val;
}
std::vector<std::vector<int>> string_to_matrix(std::string str){
std::vector<std::vector<int>>out;
for (int i = 0; i < str.length(); ++i){
out.push_back(char_to_vector(str[i]));
}
return out;
}
//THE DIFFERENT PERMUTATIONS
void ExP(std::vector<int>&in){
in.push_back(in[1]);
in.push_back(in[2]);
in.push_back(in[3]);
in.push_back(in[0]);
in[0]=in[6];
in[1]=in[7];
in[2]=in[4];
in[3]=in[5];
}
void P10(std::vector<int>&in){
//2 4 1 6 3 9 0 8 7 5
//0 1 2 3 4 5 6 7 8 9
int temp=0;
temp=in[0];
in[0]=in[2];
in[2]=in[1];
in[1]=in[4];
in[4]=in[3];
in[3]=in[6];
in[6]=temp;
//5,7,8,9
temp=in[5];
in[5]=in[9];
in[9]=temp;
temp=in[7];
in[7]=in[8];
in[8]=in[7];
}
void P8(std::vector<int>&in){
//5 2 6 3 7 4 9 8
//0 1 2 3 4 5 6 7 8 9
//NO 0 or 1
int temp=0;
in[0]=in[5];
in[5]=in[4];
in[4]=in[7];
in[7]=in[8];
in[1]=in[2];
in[2]=in[6];
in[6]=in[9];
in.pop_back();
in.pop_back();
}
void IP(std::vector<int>& in){
//15203746
//01234567
int temp=0;
//swap all the spots around in a set order
temp=in[0];
in[0]=in[1];
in[1]=in[5];
in[5]=in[7];
in[7]=in[6];
in[6]=in[4];
in[4]=in[3];
in[3]=temp;
}
void iIP(std::vector<int>& in){
//30246175
//01234567
int temp=0;
//swap all the spots back to where they were.
temp=in[0];
in[0]=in[3];
in[3]=in[4];
in[4]=in[6];
in[6]=in[7];
in[7]=in[5];
in[5]=in[1];
in[1]=temp;
}
void left_shift(std::vector<int>&in){
int temp=in[0];
for (int i = 0; i < in.size()-1; ++i){
in[i]=in[i+1];
}
in[in.size()]=temp;
}
std::vector<int> convert_Sbox(std::vector<int>input, int S[][4]){
int r=input[0]*2+input[3];
int c=input[1]*2+input[2];
int v= S[r][c];
std::vector<int> out(2);
out[0]=v%2;
v/=2;
out[1]=v%2;
return out;
}
std::vector<int> Key_gen(std::vector<int> key,int k1_k2){
//p10 of 10 bit key
P10(key);
//break into 2 5 bit pieces
std::vector<int> left(5);
std::vector<int> right(5);
for (int i = 0; i < 5; ++i){
left[i]=key[i];
right[i]=key[i+5];
}
//Left shift
left_shift(left);
left_shift(right);
//recombine for key 1.
std::vector<int>k1(10);
for (int i = 0; i < 5; ++i){
k1[i]=left[i];
k1[i+5]=right[i];
}
//send into P8 for k1
P8(k1);
//left shift again and send into p8 for k2
left_shift(left);
left_shift(right);
//recombine for key 1.
std::vector<int>k2(10);
for (int i = 0; i < 5; ++i){
k2[i]=left[i];
k2[i+5]=right[i];
}
P8(k2);
if(k1_k2==1){
return k1;
}
else return k2;
}
std::vector<int> F_box(std::vector<int> input, std::vector<int> key, int S1[][4], int S2[][4]){
//starts as 4 bit
//expansion permutation to make into 8 bit
ExP(input);
//xor with 8 bit key
std::vector<int> xor1(8);
for (int i = 0; i < 8; ++i){
if(input[i]==key[i]){
xor1[i]=0;
}
else
xor1[i]=1;
}
//break into 4 bit and 4 bit
std::vector<int> left(4);
std::vector<int> right(4);
for (int i = 0; i < 4; ++i){
left[i]=xor1[i];
right[i]=xor1[i+4];
}
//send into S-box1 and S-box2
std::vector<int> out1=convert_Sbox(left,S1);
std::vector<int> out2=convert_Sbox(right,S2);
//combine these 2 bit outputs using P4
std::vector<int>final={left[1],right[1],left[0],right[0]};
//return the 4 bit solution
return final;
}
std::vector<int> encrypt(std::vector<int> PT,std::vector<int> key,int S1[][4], int S2[][4],bool encrypt){
std::vector<int>K1;
std::vector<int>K2;
if(encrypt==true){
K1=Key_gen(key,1);
K2=Key_gen(key,2);
}
else{
K1=Key_gen(key,2);
K2=Key_gen(key,1);
}
IP(PT);
std::vector<int> Left(4);
std::vector<int> Right(4);
//split them
for (int i = 0; i < 4; ++i){
Left[i]=PT[i];
Right[i]=PT[i+4];
}
std::vector<int> out1=F_box(Right,K1,S1,S2);
std::vector<int>xor1(4);
//xor the 2
for (int i = 0; i < 4; ++i){
if(Left[i]==out1[i]){
xor1[i]=0;
}
else
xor1[i]=1;
}
std::vector<int> out2=F_box(xor1,K2,S1,S2);
std::vector<int>xor2(4);
//second xor
for (int i = 0; i < 4; ++i){
if(Right[i]==out2[i]){
xor2[i]=0;
}
else
xor2[i]=1;
}
//recombine to 8 bit
std::vector<int>CT(8);
for (int i = 0; i < 4; ++i){
CT[i]=xor2[i];
CT[i+4]=xor1[i];
}
//run through iIP
iIP(CT);
return CT;
}
void plain_to_crypt(char *pt, bool ptc, std::vector<int> key, char*ct){ //or visa versa
if(!ptc){
std::string ET_s(pt);
std::vector<std::vector<int>> ET_m=string_to_matrix(ET_s);
std::vector<std::vector<int>> DT_m;
for (int i = 0; i < ET_m.size(); ++i){
ct[i]=vector_to_char(encrypt(ET_m[i],key,S1,S2,false));
}
}
}
std::vector<int> int_to_key(int private_key,int public_key,int prime){
std::vector<int> KEY;
int shared_key=mod_exp(public_key,private_key,prime);
for (int i = 0; i < 10; ++i){
KEY.push_back(shared_key%2);
shared_key/=2;
}
return KEY;
}
void int_to_chars(int num, char array[]){
for (int i = 0; i < 4; ++i){
array[i]=num <<(8*i);
}
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*-
**
** Copyright (C) 1995-2004 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser.
** It may not be distributed under any circumstances.
**
** Edward Welbourne (by copy-and-bodge from unix_opsysteminfo.cpp)
*/
#include "core/pch.h" // Coding standards requirement.
#include "unix_opuiinfo.h"
// NB: that #defines UnixOpUiInfo to UnixOpSystemInfo
#include "modules/prefs/prefsmanager/collections/pc_fontcolor.h"
#include "modules/hardcore/mh/messages.h"
void UnixOpUiInfo::GetFont(OP_SYSTEM_FONT font, FontAtt &retval, BOOL use_system_default)
{
// hmm ... none of this is Unix-specific; why isn't it OpUiInfo's default implementation ?
OP_STATUS rc;
(void)rc;
// FIXME-PREFSMAN3: Handle use_system_default
g_pcfontscolors->GetFont(font, retval);
}
|
#ifndef _NETWORK_H
#define _NETWORK_H
#include <SDL_Net.h>
#include <string.h>
class Network{
private:
TCPsocket socket;
IPaddress myip;
char *hoststring;
Uint16 portnum;
public:
Network(){hoststring=0; portnum=0; socket=0;};
void setPort(Uint16 p){portnum=p;};
void setIp(const char *c){
hoststring = new char[strlen(c)+1];
strcpy(hoststring,c);
};
Network(const char *c, Uint16 p){
portnum=p;
hoststring = new char[strlen(c)+1];
strcpy(hoststring, c);
};
bool connect();
bool isConnected();
void sendNum(int);
void close(){
if(socket){
SDLNet_TCP_Close(socket);
socket=0;
}
};
~Network(){
close();
if(hoststring) delete [] hoststring;
};
int receiveHelper();
int receiveWait();
};
/*
Opens a connection and establishes tcp socket for use. Everything is handled internally regarding the socket.
*/
bool Network::connect(){
if(portnum==0 || hoststring==0)
return false;
SDLNet_ResolveHost(&myip, hoststring, portnum);
socket = SDLNet_TCP_Open(&myip);
if(socket) return true;
else return false;
}
bool Network::isConnected(){
if(socket) return true;
return false;
}
void Network::sendNum(int n){
char data[10];
SDLNet_Write32(n, data);
SDLNet_TCP_Send(socket,data,10);
}
int Network::receiveHelper(){
char data[10];
for(int i = 0; i < 10; i++) data[i]='\0';
int length = SDLNet_TCP_Recv(socket,data,10);
int n = SDLNet_Read32(data);
if(length>0) return n;
else return -1;
}
int Network::receiveWait(){
int receive = receiveHelper();
while(receive==-1) receive=receiveHelper();
return receive;
}
#endif
|
#ifndef uuid_guard_73cec3fe_6bb746c2_f6bee7d3_851fe697
#define uuid_guard_73cec3fe_6bb746c2_f6bee7d3_851fe697
namespace tul{
namespace crypto{
bool init();
}
}
#endif // uuid_guard_73cec3fe_6bb746c2_f6bee7d3_851fe697
|
class M113Ambul_UN_EP1;
class M113Ambul_UN_EP1_DZ : M113Ambul_UN_EP1 {
scope = 2;
displayName = $STR_VEH_NAME_M113_AMBULANCE_UN;
vehicleClass = "DayZ Epoch Vehicles";
crew = "";
typicalCargo[] = {};
class TransportMagazines{};
class TransportWeapons{};
commanderCanSee = 2+16+32;
gunnerCanSee = 2+16+32;
driverCanSee = 2+16+32;
transportMaxWeapons = 20;
transportMaxMagazines = 100;
transportmaxbackpacks = 6;
enableGPS = 0;
attendant = 0;
supplyRadius = 1.8;
class Upgrades {
ItemTankORP[] = {"M113Ambul_UN_EP1_DZE1",{"ItemToolbox","ItemCrowbar"},{},{{"ItemTankORP",1},{"PartEngine",6},{"PartGeneric",2},{"ItemScrews",2}}};
};
};
class M113Ambul_UN_EP1_DZE1: M113Ambul_UN_EP1_DZ {
displayName = "$STR_VEH_NAME_M113_AMBULANCE_UN+";
original = "M113Ambul_UN_EP1_DZ";
maxspeed = 90; // base 66
turnCoef = 0.5; // base 1
class Upgrades {
ItemTankAVE[] = {"M113Ambul_UN_EP1_DZE2",{"ItemToolbox","ItemCrowbar"},{},{{"ItemTankAVE",1},{"equip_metal_sheet",8},{"ItemScrews",2}}};
};
};
class M113Ambul_UN_EP1_DZE2: M113Ambul_UN_EP1_DZE1 {
displayName = "$STR_VEH_NAME_M113_AMBULANCE_UN++";
armor = 180; // base 105
damageResistance = 0.064; // base 0.03249
class Upgrades {
ItemTankLRK[] = {"M113Ambul_UN_EP1_DZE3",{"ItemToolbox","ItemCrowbar"},{},{{"ItemTankLRK",1},{"PartGeneric",4},{"ItemWoodCrateKit",2},{"ItemGunRackKit",2},{"ItemScrews",2}}};
};
};
class M113Ambul_UN_EP1_DZE3: M113Ambul_UN_EP1_DZE2 {
displayName = "$STR_VEH_NAME_M113_AMBULANCE_UN+++";
transportMaxWeapons = 40;
transportMaxMagazines = 200;
transportmaxbackpacks = 12;
class Upgrades {
ItemTankTNK[] = {"M113Ambul_UN_EP1_DZE4",{"ItemToolbox","ItemCrowbar"},{},{{"ItemTankTNK",1},{"PartFueltank",6},{"ItemFuelBarrel",4}}};
};
};
class M113Ambul_UN_EP1_DZE4: M113Ambul_UN_EP1_DZE3 {
displayName = "$STR_VEH_NAME_M113_AMBULANCE_UN++++";
fuelCapacity = 1200; // base 700
};
class M113Ambul_TK_EP1_DZ : M113Ambul_UN_EP1_DZ {
scope = 2;
displayName = $STR_VEH_NAME_M113_AMBULANCE_TK;
hiddenSelectionsTextures[] = {"\ca\Tracked_E\M113\Data\m113a3_01_TK_co.paa"};
class Upgrades {
ItemTankORP[] = {"M113Ambul_TK_EP1_DZE1",{"ItemToolbox","ItemCrowbar"},{},{{"ItemTankORP",1},{"PartEngine",6},{"PartGeneric",2},{"ItemScrews",2}}};
};
};
class M113Ambul_TK_EP1_DZE1: M113Ambul_TK_EP1_DZ {
displayName = "$STR_VEH_NAME_M113_AMBULANCE_TK+";
original = "M113Ambul_TK_EP1_DZ";
maxspeed = 90; // base 66
turnCoef = 0.5; // base 1
class Upgrades {
ItemTankAVE[] = {"M113Ambul_TK_EP1_DZE2",{"ItemToolbox","ItemCrowbar"},{},{{"ItemTankAVE",1},{"equip_metal_sheet",8},{"ItemScrews",2}}};
};
};
class M113Ambul_TK_EP1_DZE2: M113Ambul_TK_EP1_DZE1 {
displayName = "$STR_VEH_NAME_M113_AMBULANCE_TK++";
armor = 180; // base 105
damageResistance = 0.064; // base 0.03249
class Upgrades {
ItemTankLRK[] = {"M113Ambul_TK_EP1_DZE3",{"ItemToolbox","ItemCrowbar"},{},{{"ItemTankLRK",1},{"PartGeneric",4},{"ItemWoodCrateKit",2},{"ItemGunRackKit",2},{"ItemScrews",2}}};
};
};
class M113Ambul_TK_EP1_DZE3: M113Ambul_TK_EP1_DZE2 {
displayName = "$STR_VEH_NAME_M113_AMBULANCE_TK+++";
transportMaxWeapons = 40;
transportMaxMagazines = 200;
transportmaxbackpacks = 12;
class Upgrades {
ItemTankTNK[] = {"M113Ambul_TK_EP1_DZE4",{"ItemToolbox","ItemCrowbar"},{},{{"ItemTankTNK",1},{"PartFueltank",6},{"ItemFuelBarrel",4}}};
};
};
class M113Ambul_TK_EP1_DZE4: M113Ambul_TK_EP1_DZE3 {
displayName = "$STR_VEH_NAME_M113_AMBULANCE_TK++++";
fuelCapacity = 1200; // base 700
};
class M113_UN_EP1;
class M113_UN_EP1_DZ : M113_UN_EP1 {
scope = 2;
displayName = $STR_VEH_NAME_M113_UN;
vehicleClass = "DayZ Epoch Vehicles";
crew = "";
typicalCargo[] = {};
class TransportMagazines {};
class TransportWeapons {};
class Turrets;
class MainTurret;
transportMaxWeapons = 20;
transportMaxMagazines = 100;
transportmaxbackpacks = 6;
commanderCanSee = 2+16+32;
gunnerCanSee = 2+16+32;
driverCanSee = 2+16+32;
enableGPS = 0;
supplyRadius = 1.8;
};
class M113_UN_EP1_DZE: M113_UN_EP1_DZ {
class Turrets: Turrets {
class MainTurret: MainTurret {
magazines[] = {};
};
};
class Upgrades {
ItemTankORP[] = {"M113_UN_EP1_DZE1",{"ItemToolbox","ItemCrowbar"},{},{{"ItemTankORP",1},{"PartEngine",6},{"PartGeneric",2},{"ItemScrews",2}}};
};
};
class M113_UN_EP1_DZE1: M113_UN_EP1_DZE {
displayName = "$STR_VEH_NAME_M113_UN+";
original = "M113_UN_EP1_DZE";
maxspeed = 90; // base 66
turnCoef = 0.5; // base 1
class Upgrades {
ItemTankAVE[] = {"M113_UN_EP1_DZE2",{"ItemToolbox","ItemCrowbar"},{},{{"ItemTankAVE",1},{"equip_metal_sheet",8},{"ItemScrews",2}}};
};
};
class M113_UN_EP1_DZE2: M113_UN_EP1_DZE1 {
displayName = "$STR_VEH_NAME_M113_UN++";
armor = 180; // base 105
damageResistance = 0.064; // base 0.03249
class Upgrades {
ItemTankLRK[] = {"M113_UN_EP1_DZE3",{"ItemToolbox","ItemCrowbar"},{},{{"ItemTankLRK",1},{"PartGeneric",4},{"ItemWoodCrateKit",2},{"ItemGunRackKit",2},{"ItemScrews",2}}};
};
};
class M113_UN_EP1_DZE3: M113_UN_EP1_DZE2 {
displayName = "$STR_VEH_NAME_M113_UN+++";
transportMaxWeapons = 40;
transportMaxMagazines = 200;
transportmaxbackpacks = 12;
class Upgrades {
ItemTankTNK[] = {"M113_UN_EP1_DZE4",{"ItemToolbox","ItemCrowbar"},{},{{"ItemTankTNK",1},{"PartFueltank",6},{"ItemFuelBarrel",4}}};
};
};
class M113_UN_EP1_DZE4: M113_UN_EP1_DZE3 {
displayName = "$STR_VEH_NAME_M113_UN++++";
fuelCapacity = 1200; // base 700
};
class M113_TK_EP1_DZ : M113_UN_EP1_DZ {
scope = 2;
displayName = $STR_VEH_NAME_M113_TK;
hiddenSelectionsTextures[] = {"\ca\Tracked_E\M113\Data\m113a3_01_TK_co.paa"};
};
class M113_TK_EP1_DZE: M113_TK_EP1_DZ {
class Turrets: Turrets {
class MainTurret: MainTurret {
magazines[] = {};
};
};
class Upgrades {
ItemTankORP[] = {"M113_TK_EP1_DZE1",{"ItemToolbox","ItemCrowbar"},{},{{"ItemTankORP",1},{"PartEngine",6},{"PartGeneric",2},{"ItemScrews",2}}};
};
};
class M113_TK_EP1_DZE1: M113_TK_EP1_DZE {
displayName = "$STR_VEH_NAME_M113_TK+";
original = "M113_TK_EP1_DZE";
maxspeed = 90; // base 66
turnCoef = 0.5; // base 1
class Upgrades {
ItemTankAVE[] = {"M113_TK_EP1_DZE2",{"ItemToolbox","ItemCrowbar"},{},{{"ItemTankAVE",1},{"equip_metal_sheet",8},{"ItemScrews",2}}};
};
};
class M113_TK_EP1_DZE2: M113_TK_EP1_DZE1 {
displayName = "$STR_VEH_NAME_M113_TK++";
armor = 180; // base 105
damageResistance = 0.064; // base 0.03249
class Upgrades {
ItemTankLRK[] = {"M113_TK_EP1_DZE3",{"ItemToolbox","ItemCrowbar"},{},{{"ItemTankLRK",1},{"PartGeneric",4},{"ItemWoodCrateKit",2},{"ItemGunRackKit",2},{"ItemScrews",2}}};
};
};
class M113_TK_EP1_DZE3: M113_TK_EP1_DZE2 {
displayName = "$STR_VEH_NAME_M113_TK+++";
transportMaxWeapons = 40;
transportMaxMagazines = 200;
transportmaxbackpacks = 12;
class Upgrades {
ItemTankTNK[] = {"M113_TK_EP1_DZE4",{"ItemToolbox","ItemCrowbar"},{},{{"ItemTankTNK",1},{"PartFueltank",6},{"ItemFuelBarrel",4}}};
};
};
class M113_TK_EP1_DZE4: M113_TK_EP1_DZE3 {
displayName = "$STR_VEH_NAME_M113_TK++++";
fuelCapacity = 1200; // base 700
};
|
#pragma once
#include <fstream>
#include <string>
#include <cstdio>
#include <vector>
class MapLevel
{
public:
std::vector< std::vector < int > > level_data; // level_data[3][1]
MapLevel();
bool LoadFromFile(std::string path);
bool SaveToFile(std::string path);
int width, height;
};
|
#include <iostream>
#include <vector>
using namespace std;
int computeStairs(int n, vector<int> &memo)
{
if (memo[n] != 0)
return memo[n];
if (n == 1)
return 1;
if (n == 2)
return 2;
else
{
memo[n] = computeStairs(n - 1, memo) + computeStairs(n - 2, memo);
}
return memo[n];
}
int climbStairs(int n)
{
vector<int> memo(n + 1, 0);
return computeStairs(n, memo);
}
int main()
{
cout << climbStairs(3);
}
|
#include <vector>
#include <array>
#include <set>
#include <iterator>
#include <fstream>
#include <iostream>
#include "StringUtils.h"
#include <boost/utility/string_view.hpp>
#include <QFile>
#include <QtEndian>
#include <PhoneticService.h>
#include <sndfile.h>
#include <SpeechProcessing.h>
#include <WavUtils.h>
#include <SpeechAnnotation.h>
#include <XmlAudioMarkup.h>
#include "assertImpl.h"
namespace DslDictionaryConvertRunnerNS
{
using namespace PticaGovorun;
struct DslWordCard
{
QString Word;
QString SoundFileName;
};
// Parses word dictionary file (DSL).
// Each line contains a mungled word. The meta data associated with the word follows, indented with one TAB and
// may span multiple lines.
class DslDictionaryParser
{
public:
std::wstring errMsg_;
std::vector<DslWordCard> dictionaryWords;
std::map<QString, int> wordToDslEntryInd;
std::set<QString> wordsWithoutSoundFile;
public:
bool removeWordAdornments(const QString& adornedWord, QString& plainWord);
bool processDslFile(boost::wstring_view filePath);
void finishWordCard(const QString& word, const QStringList& wordDataLines);
void run();
};
bool DslDictionaryParser::removeWordAdornments(const QString& adornedWord, QString& plainWord)
{
plainWord = adornedWord;
while (true)
{
int openInd = plainWord.indexOf(QLatin1String("{["));
if (openInd == -1)
return true;
int insideInd = openInd+ 2; // +2 length("{[")=2
int closeInd = plainWord.indexOf(QLatin1String("]}"), insideInd);
if (closeInd == -1)
{
errMsg_ = QString("Can't remove adornments from word=%1").arg(adornedWord).toStdWString();
return false;
}
closeInd += 2; // +2 length("]}")=2
plainWord = plainWord.remove(openInd, closeInd - openInd);
}
}
bool DslDictionaryParser::processDslFile(boost::wstring_view filePath)
{
QFile wordCardsFile(toQString(filePath));
if (!wordCardsFile.open(QIODevice::ReadOnly))
{
errMsg_ = L"Can't open DSL file";
return false;
}
QTextStream txtStream;
txtStream.setDevice(&wordCardsFile);
int wordsCount = 0;
QString currentWordMungled;
QString currentWord;
QStringList wordDataLines;
auto finishWord = [&]() -> void
{
if (currentWord.isEmpty())
return;
// finish prev word
finishWordCard(currentWord, wordDataLines);
currentWord.clear();
currentWordMungled.clear();
wordDataLines.clear();
};
while (!txtStream.atEnd())
{
QString line = txtStream.readLine();
if (line.isEmpty())
continue;
if (line.startsWith(QChar('#'))) // comment
continue;
if (line.startsWith(QChar('\t')))
{
// data associated with current word
wordDataLines.append(line);
}
else
{
// next word
wordsCount++;
finishWord();
currentWordMungled = line;
removeWordAdornments(line, currentWord);
}
}
// finish the last word
finishWord();
std::wcout << L"wordsCount=" << wordsCount << std::endl;
return true;
}
std::tuple<bool, const char*> readVorbisFrames(wv::slice<uchar> vorbisData, std::vector<short>& samples, float *sampleRate)
{
struct DataReadingOp
{
uchar* Data;
size_t DataSize;
size_t ReadingDataOffset;
};
DataReadingOp context {vorbisData.data(), vorbisData.size(), 0};
SF_VIRTUAL_IO virtualIO;
virtualIO.get_filelen = [](void *user_data)->sf_count_t
{
DataReadingOp* context = reinterpret_cast<DataReadingOp*>(user_data);
return context->DataSize;
};
virtualIO.seek = [](sf_count_t offset, int whence, void *user_data)->sf_count_t
{
DataReadingOp* context = reinterpret_cast<DataReadingOp*>(user_data);
if (whence == SEEK_SET)
context->ReadingDataOffset = offset;
else PG_Assert(false);
return offset;
};
virtualIO.tell = [](void *user_data)->sf_count_t
{
DataReadingOp* context = reinterpret_cast<DataReadingOp*>(user_data);
return (sf_count_t)context->ReadingDataOffset;
};
virtualIO.read = [](void *ptr, sf_count_t count, void *user_data)->sf_count_t
{
uchar* outBuff = reinterpret_cast<uchar*>(ptr);
DataReadingOp* context = reinterpret_cast<DataReadingOp*>(user_data);
size_t availSize = std::min(count, (sf_count_t)(context->DataSize - context->ReadingDataOffset));
std::copy_n(context->Data + context->ReadingDataOffset, availSize, outBuff);
context->ReadingDataOffset += availSize; // update stream offset
return availSize;
};
//
SF_INFO sfInfo;
memset(&sfInfo, 0, sizeof(sfInfo));
sfInfo.channels = 1;
sfInfo.format = SF_FORMAT_OGG | SF_FORMAT_PCM_16;
SNDFILE* sf = sf_open_virtual(const_cast<SF_VIRTUAL_IO*>(&virtualIO), SFM_READ, &sfInfo, &context);
if (sf == nullptr)
{
auto err = sf_strerror(nullptr);
return std::make_tuple(false, err);
}
samples.resize(sfInfo.frames);
if (sampleRate != nullptr)
*sampleRate = sfInfo.samplerate;
long long count = 0;
std::array<short, 32> buf;
auto targetIt = std::begin(samples);
while (true)
{
auto readc = sf_read_short(sf, &buf[0], buf.size());
if (readc == 0)
break;
count += readc;
targetIt = std::copy(std::begin(buf), std::begin(buf) + readc, targetIt);
}
int code = sf_close(sf);
if (code != 0)
return std::make_tuple(false, sf_strerror(nullptr));
return std::make_tuple(true, nullptr);
}
void DslDictionaryParser::finishWordCard(const QString& word, const QStringList& wordDataLines)
{
auto wordIt = wordToDslEntryInd.find(word);
if (wordIt != wordToDslEntryInd.end())
{
std::wcout << L"duplicate word=" << word.toStdWString() << std::endl;
}
QStringRef soundFileName;
for (int i = 0; i < wordDataLines.size(); ++i)
{
const QString& line = wordDataLines.at(i);
int soundFileOpenInd = line.indexOf("[s]");
int soundFileCloseInd = line.indexOf("[/s]");
bool hasSoundFile = soundFileOpenInd != -1 && soundFileCloseInd != -1;
if (!hasSoundFile)
continue;
soundFileOpenInd += 3; // +3 length("[s]")=3
soundFileName = line.midRef(soundFileOpenInd, soundFileCloseInd - soundFileOpenInd);
break;
}
if (soundFileName.isNull())
{
wordsWithoutSoundFile.insert(word);
return;
}
QString soundFileNameQ = soundFileName.toString();
DslWordCard item;
item.Word = word;
item.SoundFileName = soundFileNameQ;
dictionaryWords.push_back(item);
}
void DslDictionaryParser::run()
{
std::wstring fileDsl = LR"path(C:\devb\PticaGovorunProj\data\BrownBear\wordCardsUk.dsl)path";
if (!processDslFile(fileDsl))
return;
}
struct AudioFileSegmentRef
{
std::string FileName; // the file name associated with the segment
uint32_t Offset; // offset (in bytes) in resource file RIDX where OGG file is lay out
uint32_t Size; // the size of OGG file
};
// http://www.stardict.org/StarDictFileFormat
/* (cut from the previous link)
The format of the res.ridx file:
filename; // A string end with '\0'.
offset; // 32 or 64 bits unsigned number in network byte order.
size; // 32 bits unsigned number in network byte order.
filename can include a path too, such as "pic/example.png". filename is
case sensitive, and there should have no two same filenames in all the
entries.
if "idxoffsetbits=64", then offset is 64 bits.
These three items are repeated as each entry.
The entries are sorted by the strcmp() function with the filename field.
It is possible that different filenames have the same offset and size.
*/
void readStarDictRidxFile32(boost::wstring_view resIndexfilePath, std::vector<AudioFileSegmentRef>& segmentRefs)
{
std::ifstream input(resIndexfilePath.data(), std::ios::binary);
std::vector<uchar> buffer((
std::istreambuf_iterator<char>(input)),
(std::istreambuf_iterator<char>()));
std::string fileName;
size_t pos = 0;
while (pos < buffer.size())
{
// read file name
size_t nameInd = pos;
while (buffer[nameInd] != '\0')
nameInd++;
fileName.assign(reinterpret_cast<char*>(&buffer[pos]), nameInd - pos);
// read offset
pos = nameInd + 1; // step next to \0
uint32_t offset = qFromBigEndian<uint32_t>(&buffer[pos]);
pos += 4;
uint32_t size = qFromBigEndian<uint32_t>(&buffer[pos]);
pos += 4; // to next record
AudioFileSegmentRef s;
s.FileName = fileName;
s.Offset = offset;
s.Size = size;
segmentRefs.push_back(s);
}
}
// 'phrase273.wav' -> 273
int parseSoundFileNameId(const QString& fileName)
{
int extInd = fileName.indexOf(QLatin1String(".wav"));
const int prefixLen = 6;
QStringRef numStr = fileName.midRef(prefixLen, extInd - prefixLen);
bool conv = false;
int id = numStr.toInt(&conv);
if (!conv)
return -1;
return id;
}
// Composes StarDict dictionary DSL file with audio data (in OMG, Vorbis format) to speech annotation
// format acceptable by PticaGovorun transcriber.
class DslAndAudioResDictIntoSpeechAnnotConverter
{
PhoneRegistry phoneReg;
DslDictionaryParser extr;
std::vector<AudioFileSegmentRef> segmentRefs; // pointers to audio data
std::map<std::string, const AudioFileSegmentRef*> fileNameToSegmentRefs;
std::vector<uchar> buffer; // concatenated audio OGG files per each word
std::unique_ptr<GrowOnlyPinArena<wchar_t>> stringArena;
std::vector<PhoneticWord> phoneticDict; // phonetic transcription of words in DSL dictionary
SpeechAnnotation annot;
const float outputSampleRate = 22050;
std::vector<short> framesConcat; // concatenated audio frames for all audio files
public:
std::wstring errMsg_;
DslAndAudioResDictIntoSpeechAnnotConverter();
void run();
void buildPhoneticDictionary();
void buildSpeechAnnot();
};
DslAndAudioResDictIntoSpeechAnnotConverter::DslAndAudioResDictIntoSpeechAnnotConverter()
{
stringArena = std::make_unique<GrowOnlyPinArena<wchar_t>>(1024 * 512);
bool allowSoftHardConsonant = true;
bool allowVowelStress = true;
// write in most specific way
phoneReg.setPalatalSupport(PalatalSupport::AsPalatal);
initPhoneRegistryUk(phoneReg, allowSoftHardConsonant, allowVowelStress);
}
void DslAndAudioResDictIntoSpeechAnnotConverter::buildPhoneticDictionary()
{
// load 'word to stressed syllable' dictionary
boost::filesystem::path stressDictFilePath = "path(C:\devb\PticaGovorunProj\data\stressDictUk.xml)path";
std::unordered_map<std::wstring, int> wordToStressedSyllable;
ErrMsgList errMsg;
if (!loadStressedSyllableDictionaryXml(stressDictFilePath, wordToStressedSyllable, &errMsg))
{
errMsg_ = combineErrorMessages(errMsg).toStdWString();
return;
}
auto getStressedSyllableIndFun = [&wordToStressedSyllable](boost::wstring_view word, std::vector<int>& stressedSyllableInds) -> bool
{
auto it = wordToStressedSyllable.find(std::wstring(word.data(), word.size()));
if (it == wordToStressedSyllable.end())
return false;
stressedSyllableInds.push_back(it->second);
return true;
};
WordPhoneticTranscriber phoneticTranscriber;
phoneticTranscriber.setStressedSyllableIndFun(getStressedSyllableIndFun);
for (const DslWordCard& card : extr.dictionaryWords)
{
const QString& word = card.Word.toLower();
std::wstring wordW = word.toStdWString();
phoneticTranscriber.transcribe(phoneReg, wordW);
if (phoneticTranscriber.hasError())
{
errMsg_ = std::wstring(L"Can't transcribe word=") + wordW;
return;
}
boost::wstring_view wordArena;
if (!registerWord(word, *stringArena, wordArena))
{
errMsg_ = L"Can't register word in the arena";
return;
}
PronunciationFlavour pron;
pron.PronCode = wordArena;
phoneticTranscriber.copyOutputPhoneIds(pron.Phones);
PhoneticWord phWord;
phWord.Word = wordArena;
phWord.Pronunciations.push_back(pron);
phoneticDict.push_back(phWord);
}
}
void DslAndAudioResDictIntoSpeechAnnotConverter::buildSpeechAnnot()
{
float sampleRate = 0;
std::vector<short> samples;
std::vector<short> samplesResampled;
const wchar_t* Speaker = L"BrownBear1";
annot.addSpeaker(Speaker, Speaker);
int maxMarkerId = 0;
size_t frameInd = 0;
int i = 0;
for (const DslWordCard& card : extr.dictionaryWords)
{
//if (i++ > 100)
// break;
const QString& word = card.Word.toLower();
const QString& soundFileName = card.SoundFileName;
int fileId = parseSoundFileNameId(soundFileName);
if (fileId == -1)
{
std::wcerr << L"Can't get id from file name" << soundFileName.toStdWString() << std::endl;
continue;
}
maxMarkerId = std::max(maxMarkerId, fileId);
QString soundFileNameFixed(soundFileName);
soundFileNameFixed = soundFileNameFixed.replace(QLatin1String(".wav"), QLatin1String(".ogg"), Qt::CaseSensitive);
auto segRefIt = fileNameToSegmentRefs.find(soundFileNameFixed.toStdString());
if (segRefIt == fileNameToSegmentRefs.end())
{
std::cerr << "Can't find the reference to audio data" << std::endl;
continue;
}
const AudioFileSegmentRef& segRef = *segRefIt->second;
samples.clear();
// binary data is the OGG container with audio in Vorbis format
wv::slice<uchar> vorbisData = wv::make_view(&buffer[segRef.Offset], segRef.Size);
bool readOp;
const char* errMsg;
std::tie(readOp, errMsg) = readVorbisFrames(vorbisData, samples, &sampleRate);
if (!readOp)
{
std::wcout << errMsg << std::endl;
return;
}
// resample samples
ErrMsgList errMsgL;
if (!resampleFrames(samples, sampleRate, outputSampleRate, samplesResampled, &errMsgL))
{
std::cout << str(errMsgL) << std::endl;
return;
}
//
std::copy(samplesResampled.begin(), samplesResampled.end(), std::back_inserter(framesConcat));
TimePointMarker m;
m.Id = fileId;
m.SampleInd = frameInd;
m.TranscripText = word;
m.Language = SpeechLanguage::Ukrainian;
m.LevelOfDetail = MarkerLevelOfDetail::Word;
m.SpeakerBriefId = Speaker;
annot.attachMarker(m);
frameInd += samplesResampled.size();
}
// add last marker
{
TimePointMarker m;
m.Id = maxMarkerId + 1;
m.SampleInd = frameInd;
m.Language = SpeechLanguage::NotSet;
m.LevelOfDetail = MarkerLevelOfDetail::Word;
annot.attachMarker(m);
}
}
void DslAndAudioResDictIntoSpeechAnnotConverter::run()
{
// load word to sound file name
extr.run();
if (!extr.errMsg_.empty())
{
errMsg_ = extr.errMsg_;
return;
}
buildPhoneticDictionary();
if (!errMsg_.empty())
return;
// load sound file name to the reference to the sound binary data
std::wstring fileRidx = LR"path(C:\devb\PticaGovorunProj\data\BrownBear\wordSoundUk.ridx)path";
readStarDictRidxFile32(fileRidx, segmentRefs);
for (const AudioFileSegmentRef& segRef : segmentRefs)
fileNameToSegmentRefs.insert({ segRef.FileName, &segRef });
// load audio
std::wstring fileRdic = LR"path(C:\devb\PticaGovorunProj\data\BrownBear\wordSoundUk.rdic)path";
std::ifstream input(fileRdic.data(), std::ios::binary);
buffer = std::vector<uchar>(std::istreambuf_iterator<char>(input), std::istreambuf_iterator<char>());
//
buildSpeechAnnot();
// dump results
std::string timeStampStr;
appendTimeStampNow(timeStampStr);
std::wstring timeStampStrW = QString::fromStdString(timeStampStr).toStdWString();
std::wstringstream dumpFileName;
dumpFileName << L"dict." << timeStampStrW << L".phonetic.xml";
ErrMsgList errMsg;
savePhoneticDictionaryXml(phoneticDict, dumpFileName.str(), phoneReg, &errMsg);
dumpFileName.str(L"");
dumpFileName << L"dict." << timeStampStrW << L".markers.xml";
saveAudioMarkupToXml(annot, dumpFileName.str());
std::stringstream dumpFileNameS;
dumpFileNameS << "dict." << timeStampStr << ".wav";
writeAllSamplesWav(framesConcat.data(), framesConcat.size(), dumpFileNameS.str(), (int)outputSampleRate);
}
void run()
{
DslAndAudioResDictIntoSpeechAnnotConverter c;
c.run();
if (!c.errMsg_.empty())
std::wcerr << c.errMsg_ << std::endl;
}
}
|
#include "Merchant.h"
#include "MerchantState.h"
Merchant::Merchant(int id) : BaseGameEntity(id)
{
_sm = new StateMachine<Merchant>(this);
_sm->SetCurrentState(StoreState::Instance());
//_sm->SetGlobalState(FactoryGlobalState::Instance());
}
Merchant::~Merchant()
{
delete _sm; _sm = nullptr;
}
void Merchant::Update()
{
_sm->Update();
}
bool Merchant::HandleEvent(const Event& src_event)
{
return _sm->HandleEvent(src_event);
}
|
/** Kabuki SDK
@file /.../Source/Kabuki_SDK/_2D/Point_i.cpp
@author Cale McCollough
@copyright Copyright © 2016 Cale McCollough
@license Free and open-source. You can find a copy of the license that YOU MUST READ in the accompanying ./ReadMe.md, file incorporated herein by this reference, or online at http://www.boost.org/LICENSE_1_0.txt
*/
#include "_2D/Point_i.h"
using namespace _2D;
Point_i::Point_i (int XValue = 0, int YValue = 0)
{
X = XValue;
Y = YValue;
}
void Point_i::Set (int XValue = 0, int YValue = 0)
{
X = XValue;
Y = YValue;
}
void Point_i::Set (const Point_i& a)
{
X = a.X;
Y = a.Y;
}
bool Point_i::Equals (const Point_i& a)
{
if (X != a.X || Y != a.Y)
return false;
return true;
}
void Point_i::Swap (Point_i a)
{
int tempX = a.X,
tempY = a.Y;
a.X = X;
a.Y = Y;
X = tempX;
Y = tempY;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2011 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*
* @author Arjan van Leeuwen (arjanl)
*/
#ifndef MANAGER_HOLDER_H
#define MANAGER_HOLDER_H
class GenericDesktopManager;
/** @brief A class that keeps track of managers (singletons)
* An object of this type is owned by Application.
*/
class ManagerHolder
{
public:
/**
* Constants for manager types. The order imposed by the values of the
* enumerators is the order that the managers are initialized in
* ManagerHolder::InitializeManagers().
*
* Inter-manager dependencies are expressed by combining (OR-ing) the
* appropriate constants, and respected by ManagerHolder.
*/
enum ManagerType
{
TYPE_FEATURE = (1 << 0),
#ifdef VEGA_OPPAINTER_SUPPORT
TYPE_QUICK_ANIMATION = (1 << 1),
#endif // VEGA_OPPAINTER_SUPPORT
TYPE_SECURITY_UI = (1 << 2),
TYPE_OPERA_ACCOUNT = (1 << 3),
TYPE_NOTIFICATION = (1 << 4),
TYPE_WEBMAIL = (1 << 5),
TYPE_FAV_ICON = (1 << 6) | TYPE_WEBMAIL,
#ifdef SUPPORT_SPEED_DIAL
TYPE_SPEED_DIAL = (1 << 7) | TYPE_FAV_ICON,
#endif // SUPPORT_SPEED_DIAL
#ifdef GADGET_SUPPORT
TYPE_GADGET = (1 << 8),
#endif // GADGET_SUPPORT
TYPE_HOTLIST = (1 << 9) | TYPE_FAV_ICON | TYPE_GADGET,
#ifdef WEBSERVER_SUPPORT
TYPE_WEB_SERVER = (1 << 10) | TYPE_OPERA_ACCOUNT | TYPE_GADGET | TYPE_HOTLIST,
#endif // WEBSERVER_SUPPORT
TYPE_HISTORY = (1 << 11) | TYPE_FAV_ICON | TYPE_HOTLIST,
TYPE_COOKIE = (1 << 12),
TYPE_SECURITY = (1 << 13),
#ifdef AUTO_UPDATE_SUPPORT
TYPE_AUTO_UPDATE = (1 << 14),
#endif // AUTO_UPDATE_SUPPORT
#ifdef SUPPORT_DATA_SYNC
TYPE_SYNC = (1 << 15),
#endif // SUPPORT_DATA_SYNC
TYPE_BOOKMARK = (1 << 16),
#ifdef M2_SUPPORT
TYPE_MAIL = (1 << 17) | TYPE_HOTLIST,
#endif // M2_SUPPORT
#ifdef WEB_TURBO_MODE
TYPE_OPERA_TURBO = (1 << 18),
#endif // WEB_TURBO_MODE
#ifdef OPERA_CONSOLE
TYPE_CONSOLE = (1 << 19),
#endif // OPERA_CONSOLE
TYPE_TRANSFER = (1 << 20),
TYPE_SESSION_AUTO_SAVE = (1 << 21),
TYPE_EXTERNAL_DOWNLOAD_MANAGER = (1 << 22),
TYPE_TOOLBAR = (1 << 23) | TYPE_HOTLIST,
#ifdef VEGA_OPPAINTER_SUPPORT
TYPE_MOUSE_GESTURE_UI = (1 << 24) | TYPE_QUICK_ANIMATION,
#endif // VEGA_OPPAINTER_SUPPORT
TYPE_EXTENSIONS = (1 << 25) | TYPE_GADGET | TYPE_NOTIFICATION | TYPE_SPEED_DIAL,
TYPE_TIPS = (1 << 26),
#ifdef PLUGIN_AUTO_INSTALL
TYPE_PLUGIN_INSTALL = (1 << 27) | TYPE_AUTO_UPDATE,
#endif // PLUGIN_AUTO_INSTALL
TYPE_REDIRECTION = (1 << 28) | TYPE_BOOKMARK | TYPE_SPEED_DIAL | TYPE_HOTLIST,
TYPE_CLIPBOARD = (1 << 29),
TYPE_ALL = 0xFFFFFFFF
};
ManagerHolder() : m_destroy_managers(false) {}
~ManagerHolder();
/**
* Initializes managers.
*
* @param type_mask a combination of ManagerType values specifying the set
* of managers to initialize. By default, all managers are
* initialized.
*/
OP_STATUS InitManagers(INT32 type_mask = TYPE_ALL);
private:
typedef GenericDesktopManager* (*ManagerCreator)();
typedef void (*ManagerDestroyer)();
struct ManagerDescr
{
ManagerDescr(ManagerType _type, ManagerCreator _creator, ManagerDestroyer _destroyer, const char* _name)
: type(_type), creator(_creator), destroyer(_destroyer), name(_name) {}
ManagerType type;
ManagerCreator creator;
ManagerDestroyer destroyer;
const char *name;
};
template<class T> static ManagerDescr CreateManagerDescr(ManagerType type, const char* name)
{ return ManagerDescr(type, T::CreateInstance, T::DestroyInstance, name); }
static int ManagerDescrLessThan(const void* lhs, const void* rhs);
/**
* A table of manager type "descriptors". Each descriptor maps a manager
* type constant into a C++ type.
*/
static ManagerDescr s_manager_descrs[];
/**
* This currently only here to be able to test DesktopBootstrap, i.e., create
* a DesktopBootstrap instance that doesn't destroy managers.
*/
bool m_destroy_managers;
};
#endif // MANAGER_HOLDER_H
|
/*
* File: player.h
* Author: Dirk Vermeir
* Edited by: Wouter Van Rossem
*
*/
#ifndef _PLAYER_H
#define _PLAYER_H
#include <set>
#include <map>
#include <sstream>
#include <dvutil/shared_ptr.h>
#include <dvnet/socket.h>
#include <dvthread/thread.h>
#include <dvthread/mailbox.h>
/** The Player class represents a user connected to the server. It is
* also a thread. The class is very simple and reusable: its main
* function (the one executed by the thread) simply reads commands
* from the socket connection (with the 'client/user') and sends them
* (via the Manager::request function) to the manager for processing,
* after which it displays the reply. It also reads replies from the
* manager from its regular mailbox and for an 'out of band data'
* mailbox (such data are sent to the player without a corresponding
* request from the player). All these replies are sent back to the
* user via the socket.
*/
class Player : public Dv::Thread::Thread
{
public:
/** The type of a message that the player sends out.
* It consists of a pointer to the player and the
* actual message (a string). The former is useful for allowing
* the player's manager to request extra services from the player, e.g.
* kill it.
*/
typedef std::pair<Player*, std::string> Message;
/** Type of mailbox where a player receives information.*/
typedef Dv::Thread::MailBox<std::string> MailBox;
/** Abstract class representing the player's manager. All input
* from a player is passed on to its manager.
*/
class Manager
{
public:
virtual void request (Player::Message, MailBox* = 0) = 0;
};
/** Factory method to create a new Player. This function also
* reports the creation to the manager via a 'newplayer' command.
*
* Note that the player will autodestruct after the thread
* finishes its main() function.
*
* Note also that a player will never wait indefinitely for any
* event: the calls to the manager time out, as do the read calls
* to the socket connection. Thus, a player that is killed will
* always notice this after a while.
*
* @param manager of this player
* @param so socket connection to player
* @param delay millisecs that the player will wait for the
* manager to reply before throwing an exception
* @param delay millisecs that the player will wait for the
* @param debug_level
* @param debug
* @return pointer to new Player object
*/
static Player* make (Manager& manager,
Dv::shared_ptr<Dv::Net::Socket> so, size_t delay, size_t
debug_level, Dv::Debugable* debug);
/** Type of sets of players. */
typedef std::set<Player*> Set;
/** Type of map from player names to players. */
typedef std::map<std::string, Player*> Map;
/** Get the name of this player.
* @return name of this player
*/
const std::string& name () const
{
return name_;
}
/** Set the name of this player.
* @param name new name of this player
*/
void set_name (const std::string& name)
{
name_ = name;
}
/** Send out-of-band data to this player by storing them
* in the incoming_ mailbox.
*/
void put (const std::string& text)
{
incoming_.put(text);
}
private:
/** Destructor */
~Player () { }
Player (const Player&);
Player & operator= (const Player&);
/** Main function. Note that this function should not return unless
* the player's manager has been informed.
*/
virtual int main ();
/** Constructor.
* @param manager of this player
* @param so socket connection of this player with the client
* @param delay millisecs that the player will wait for the
* manager to reply before throwing an exception
* @param debug_level only if the master debug level is larger
* than this level will debug output be generated
* @param debug object (may be 0)
*/
Player (Manager& manager, Dv::shared_ptr<Dv::Net::Socket> so, size_t delay,
size_t debug_level, Dv::Debugable* debug);
/** Clean up before exiting this thread, in particular send
* a 'quit' command to the manager. */
void quit ();
/** Read a line from a socket that may time out.
* While waiting for input, the function also checks any
* messages available in @c incoming_ and displays them
* on @c so.
* If successful, The read line is also trimmed (i.e. white
* space is removed from both ends).
* @param so socket to read from
* @param line to read
* @return 0 if a line was successfully read
* @return 2 if the player thread was killed (and input is ignored)
* @return 1 if the read did not succeed, e.g. because of an I/O error
*/
int get_line (Dv::Net::Socket& so, std::string& line);
/** Send a message to the player's manager and wait for a reply.
* @param message to send
* @return reply from manager on this message
* @sa Player::Manager::request
*/
std::string query_manager (const std::string& message);
/** Manager of this player. */
Manager& manager_;
/** Connection to user/client. */
Dv::shared_ptr<Dv::Net::Socket> so_;
/** Mailbox used to communicate with the manager: the player
* forwards commands to the manager who will store replies
* in this mailbox.
*/
MailBox mbox_;
/** Mailbox for incoming 'out of band' data. */
MailBox incoming_;
/** Name of the player. */
std::string name_;
/** Delay used when communicating with the manager or when doing
* I/O operations. */
size_t delay_;
};
#endif /* _PLAYER_H */
|
#include <iostream>
using namespace std;
typedef pair<int , int> P;
int main()
{
int n, t; cin >> n >> t;
int ans = 1001;
P ct;
for (int i = 0; i < n; i++) {
cin >> ct.first >> ct.second;
if (ct.second <= t && ct.first < ans) {
ans = ct.first;
}
}
if (ans == 1001) cout << "TLE" << endl;
else cout << ans << endl;
return 0;
}
|
//////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2006 Audiokinetic Inc. / All Rights Reserved
//
//////////////////////////////////////////////////////////////////////
#ifndef _AKVOLUMEAUTOMATION_H_
#define _AKVOLUMEAUTOMATION_H_
#include <AK/SoundEngine/Common/AkTypes.h>
#include <AK/SoundEngine/Common/AkCommonDefs.h>
#include <AK/SoundEngine/Common/AkSimd.h>
namespace AK
{
namespace DSP
{
// Takes and audio buffer, a volume automation buffer, and a transform, and applies the transformed volume automation to the audio buffer.
static inline void ApplyVolAutomation(AkAudioBuffer& in_pAudioBuffer, const AkModulatorXfrm in_xfrms, const AkReal32* in_pAutmBuf )
{
AKSIMD_V4F32 vOffset = AKSIMD_LOAD1_V4F32( in_xfrms.m_fOffset );
AKSIMD_V4F32 vScale = AKSIMD_LOAD1_V4F32( in_xfrms.m_fScale );
for( AkUInt32 ch = 0; ch < in_pAudioBuffer.NumChannels(); ++ch)
{
AKSIMD_V4F32 * AK_RESTRICT pModSrcBuf = (AKSIMD_V4F32* AK_RESTRICT) in_pAutmBuf;
AKSIMD_V4F32 * AK_RESTRICT pAudioBuf = (AKSIMD_V4F32* AK_RESTRICT) ( in_pAudioBuffer.GetChannel(ch) );
AKSIMD_V4F32 * AK_RESTRICT pAudioBufEnd = pAudioBuf + (in_pAudioBuffer.MaxFrames() / 4);
while ( pAudioBuf < pAudioBufEnd )
{
AKSIMD_V4F32 temp = AKSIMD_MADD_V4F32( *pModSrcBuf, vScale, vOffset );
*pAudioBuf = AKSIMD_MUL_V4F32(*pAudioBuf, temp );
pAudioBuf++;
pModSrcBuf++;
}
}
}
// Takes and audio buffer, an array of volume automation buffers, and an array of transforms, and applies each
// transformed volume automation to the audio buffer.
static inline void ApplyVolAutomation(AkAudioBuffer& in_pAudioBuffer, AkModulatorXfrm* in_arrayXfrms, AkReal32** in_pArrayAutmBufs, AkUInt32 in_uNumModulators )
{
for (AkUInt32 i = 0; i< in_uNumModulators; ++i )
{
const AkModulatorXfrm& xfrm = in_arrayXfrms[i];
const AkReal32* pAutmBuf = in_pArrayAutmBufs[i];
ApplyVolAutomation(in_pAudioBuffer, xfrm, pAutmBuf );
}
}
} // namespace DSP
} // namespace AK
#endif // _AKVOLUMEAUTOMATION_H_
|
#include <sys/stat.h>
#include <signal.h>
#include "IniFile.h"
#include "Configure.h"
#include "Logger.h"
#include "Util.h"
#include "Protocol.h"
#ifndef WIN32
#include <sys/time.h>
#include <sys/resource.h>
#include <unistd.h>
#include <getopt.h>
#endif
Configure::Configure() : GameConfig(GAME_TYPE, E_MSG_SOURCE_SERVER, E_CONFIG_ALLOC)
{
}
Configure::~Configure()
{
}
bool Configure::LoadGameConfig()
{
std::string svname = ReadString("system", "name", "server");
char tmp[64] = { 0 };
sprintf(tmp, "%s_%d", svname.c_str(), m_nServerId);
name = tmp;
numplayer = ReadInt("system", "numplayer", 1);
highlimit = ReadInt("system", "highlimit", 10000000);
mul = ReadInt("system", "mul", 10);
matchtime = ReadInt("system", "matchtime", 2);
allowrobot = ReadInt("system", "allowrobot", 0);
norobot = ReadInt("system", "norobot", 2);
return true;
}
|
// Copyright (c) 1999-2020 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _Express_Schema_HeaderFile
#define _Express_Schema_HeaderFile
#include <Express_DataMapOfAsciiStringItem.hxx>
#include <Express_HSequenceOfItem.hxx>
#include <Standard_Type.hxx>
class TCollection_HAsciiString;
class Express_HSequenceOfItem;
class Express_Item;
class TCollection_AsciiString;
class Express_Type;
//! Represents a schema as a list of items and provides general
//! tools for generating HXX/CXX files (including dictionary of
//! item names)
class Express_Schema : public Standard_Transient
{
public:
//! Creates a schema with given name and given set of items
//! and calls Prepare()
Standard_EXPORT Express_Schema (const Standard_CString theName,
const Handle(Express_HSequenceOfItem)& theItems);
//! Creates a schema with given name and given set of items
//! and calls Prepare()
Standard_EXPORT Express_Schema (const Handle(TCollection_HAsciiString)& theName,
const Handle(Express_HSequenceOfItem)& theItems);
//! Returns schema name
Standard_EXPORT const Handle(TCollection_HAsciiString)& Name() const;
//! Returns sequence of items
Standard_EXPORT const Handle(Express_HSequenceOfItem)& Items() const;
//! Returns number of items
Standard_EXPORT Standard_Integer NbItems() const;
//! Returns item by index
Standard_EXPORT Handle(Express_Item) Item (const Standard_Integer theNum) const;
//! Returns item by name
Standard_EXPORT Handle(Express_Item) Item (const Standard_CString theName,
const Standard_Boolean theSilent = Standard_False) const;
//! Returns item by name
Standard_EXPORT Handle(Express_Item) Item (const TCollection_AsciiString& theName) const;
//! Returns item by name
Standard_EXPORT Handle(Express_Item) Item (const Handle(TCollection_HAsciiString)& theName) const;
DEFINE_STANDARD_RTTIEXT(Express_Schema, Standard_Transient)
protected:
private:
//! Prepares data for further work. Converts all item names
//! from EXPRESS style (aaa_bb) to CASCADE style (AaaBb).
//! Then, makes a dictionary of item names and sets handles
//! to all items referred initially by name
Standard_EXPORT void Prepare();
//! Prepares type for work by setting its handle to item in the
//! schema according to dictionary (for types which refer items
//! by name)
Standard_EXPORT void PrepareType (const Handle(Express_Type)& theType) const;
private:
Handle(TCollection_HAsciiString) myName;
Handle(Express_HSequenceOfItem) myItems;
Express_DataMapOfAsciiStringItem myDict;
};
#endif // _Express_Schema_HeaderFile
|
/**
* created: 2013-4-9 15:21
* filename: FKLoginSvrConnecter
* author: FreeKnight
* Copyright (C):
* purpose:
*/
//------------------------------------------------------------------------
#include "FKLoginSvrConnecter.h"
#include "FKGameSvrSession.h"
#include "FKDBSvr.h"
#include "FKDBScript.h"
//------------------------------------------------------------------------
void CLoginSvrDBConnecter::OnIocpConnect(){
__super::OnIocpConnect();
DBService* dbsvr=DBService::instance();
dbsvr->m_Svr2SvrLoginCmd.m_now=time(NULL);
sendcmd(&dbsvr->m_Svr2SvrLoginCmd,sizeof(dbsvr->m_Svr2SvrLoginCmd));
}
//------------------------------------------------------------------------
void CLoginSvrDBConnecter::OnDisconnect(){
__super::OnDisconnect();
do {
DBService* dbsvr=DBService::instance();
AILOCKT(dbsvr->m_loginsvrconnter);
LoginServerHashCodeMap::iterator it,itnext;
for (it=dbsvr->m_loginsvrconnter_hashcode.begin(),itnext=it;it!=dbsvr->m_loginsvrconnter_hashcode.end();it=itnext){
itnext++;
if (it->second==this){
dbsvr->m_loginsvrconnter_hashcode.erase(it);
}
}
} while (false);
m_bovalid = false;
}
//------------------------------------------------------------------------
bool CLoginSvrDBConnecter::isvalid(){
return m_bovalid;
}
//------------------------------------------------------------------------
time_t CLoginSvrDBConnecter::valid_timeout(){
return 30;
}
//------------------------------------------------------------------------
bool CLoginSvrDBConnecter::msgParse(stBaseCmd* pcmd, unsigned int ncmdlen,stQueueMsgParam* bufferparam){
switch (pcmd->value)
{
case stSvr2SvrLoginCmd::_value:
{
return OnstSvr2SvrLoginCmd((stSvr2SvrLoginCmd*)pcmd,ncmdlen,bufferparam);
}
break;
}
return true;
}
//------------------------------------------------------------------------
bool CLoginSvrDBConnecter::OnstSvr2SvrLoginCmd(stSvr2SvrLoginCmd* pcmd, unsigned int ncmdlen,stQueueMsgParam* bufferparam){
FUNCTION_BEGIN;
if (svr_id_type_value != pcmd->svr_id_type_value) {
Terminate();
g_logger.error("连接的服务器(%u:%u <> %u:%u)与配置文件记录不一致...", svr_id, svr_type, pcmd->svr_id, pcmd->svr_type);
m_bovalid = false;
} else {
time_t difftime=time(NULL)-pcmd->m_now;
if ( difftime>(60*15) ){
g_logger.forceLog(zLogger::zERROR ,"服务器 %d(%d) [%s:%d] 系统时间异常( %s <> %s ),请校正所有服务器时间后重新启动服务!",
svr_id,svr_type,GetRemoteAddress(),GetRemotePort(),timetostr(time(NULL)) ,timetostr(pcmd->m_now));
}else if(difftime>10){
g_logger.forceLog(zLogger::zDEBUG ,"服务器 %d(%d) [%s:%d] 系统时间差为 %d 秒( %s <> %s )!",svr_id,svr_type,GetRemoteAddress(),GetRemotePort(),difftime,timetostr(time(NULL)) ,timetostr(pcmd->m_now));
}
do{
DBService* dbsvr=DBService::instance();
AILOCKT(dbsvr->cfg_lock);
}while(false);
m_bovalid = true;
g_logger.debug("帐号服务器 %d(%d) 登陆校验成功!",svr_id,svr_type);
}
return true;
}
//------------------------------------------------------------------------
|
/** Kabuki SDK
@file /.../Source/Kabuki_SDK/include/_Com/MIDI/ShortMessage.h
@author Cale McCollough
@copyright Copyright © 2016 Cale McCollough ©
@license Read accompanying /.../README.md or online at http://www.boost.org/LICENSE_1_0.txt
*/
#pragma once
#include "Message.h"
namespace _Com {
namespace MIDI {
class Port;
/** Represents a short MIDI message. */
class ShortMessage: Message
{
public:
explicit ShortMessage(uint32_t TimeStamp = 0);
ShortMessage(uint32_t Msg, uint32_t TimeStamp = 0);
ShortMessage(uint8_t Status, uint8_t Data1, uint8_t Data2, uint32_t TimeStamp);
ShortMessage(uint8_t Command, uint8_t Channel, uint8_t Data1, uint8_t Data2, uint32_t TimeStamp);
//void send(Port &thisDevice); //< Sends this Message out thisDevice.
//void SendMsgNoStatus(midi::CMIDIOutDevice &OutDevice); //< Sends message without status uint8_t
uint32_t length() const;
const uint8_t *message() const;
uint8_t status() const;
uint8_t channel() const;
uint8_t command() const;
uint8_t dataBYte1() const;
uint8_t dataBYte2() const;
void setMessage(uint8_t statusBYte, uint8_t bYte1, uint8_t bYte2);
void setMessage(uint8_t commandBYte, uint8_t channelBYte, uint8_t bYte1,
uint8_t bYte2);
/** Packs a short messages without status uint8_t. */
static uint32_t pack(uint8_t bYte1, uint8_t bYte2);
/** Packs a short messages with status uint8_t. */
static uint32_t pack(uint8_t statusBYte, uint8_t bYte1, uint8_t bYte2);
/** Packs a short messages on a given channel. */
static uint32_t pack(uint8_t commandBYte, uint8_t channelBYte, uint8_t bYte1,
uint8_t bYte2);
/** Unpacks AMessage. */
static void unpack(uint32_t AMessage, uint8_t &statusBYte, uint8_t &bYte1,
uint8_t &bYte2);
/** Unpacks AMessage. */
static void unpack(uint32_t AMessage, uint8_t &commandBYte, uint8_t &channelBYte,
uint8_t &bYte1, uint8_t &bYte2);
static const uint32_t LENGTH = 3;
private:
uint32_t message,
messageNoStatus;
};
}
}
|
#pragma once
#include <string>
#include <Poco/SharedPtr.h>
#include <Poco/JSON/Object.h>
#include <Poco/Net/IPAddress.h>
#include "gwmessage/GWMessage.h"
#include "model/GatewayID.h"
namespace BeeeOn {
/**
* @brief Represents message sent by the gateway after connecting to the server.
* Message is intended to gateway registration on the server.
*
* Server confirms successful registration with message GWGatewayAccepted.
*
* An example of a registration message:
* <pre>
* {
* "message_type": "gateway_register",
* "gateway_id": "1875034586645818",
* "version": "v2017.01",
* "ip_address": "192.168.0.1"
* }
* </pre>
*/
class GWGatewayRegister : public GWMessage {
public:
typedef Poco::SharedPtr<GWGatewayRegister> Ptr;
GWGatewayRegister();
GWGatewayRegister(const Poco::JSON::Object::Ptr object);
void setGatewayID(const GatewayID &gatewayID);
/**
* @returns ID of the gateway that is being registered
*/
GatewayID gatewayID() const;
void setVersion(const std::string &version);
/**
* @returns version of the gateway software
*/
std::string version() const;
void setIPAddress(const Poco::Net::IPAddress &ipAddress);
/**
* @returns IP address the gateway can see on the socket used
* for communication with the remote server
*/
Poco::Net::IPAddress ipAddress() const;
};
}
|
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "GameFramework/GameMode.h"
#include "MartellucciGameMode.generated.h"
UCLASS(minimalapi)
class AMartellucciGameMode : public AGameMode
{
GENERATED_BODY()
public:
AMartellucciGameMode(const FObjectInitializer& ObjectInitializer);
};
|
#include <rapidjson/document.h>
#include <rapidjson/writer.h>
#include <rapidjson/stringbuffer.h>
#include "cjson.h"
#include <iostream>
#include <memory.h>
using namespace rapidjson;
struct RapidWriter {
StringBuffer buf;
Writer<StringBuffer> *ptr;
};
#define CONVERT_WRITER_PTR(x) \
struct RapidWriter * rw = (struct RapidWriter*)x; \
Writer<StringBuffer> *writer = rw->ptr; \
void * json_create_writer() {
struct RapidWriter * writer = new struct RapidWriter;
writer->ptr = new Writer<StringBuffer>(writer->buf);
writer->ptr->StartObject();
return writer;
};
const char * json_dispose_writer(void * ptr) {
if (ptr != nullptr) {
CONVERT_WRITER_PTR(ptr);
writer->EndObject();
const char * json = rw->buf.GetString();
char * out = new char[strlen(json) + 1];
memcpy(out, json, strlen(json));
struct RapidWriter* wptr = (struct RapidWriter*)ptr;
if (wptr->ptr != nullptr) delete wptr->ptr;
if (wptr != nullptr) delete wptr;
return out;
}
return nullptr;
};
void json_append_int(void * ptr, const char * key, int val) {
if (ptr != nullptr) {
CONVERT_WRITER_PTR(ptr);
writer->Key(key);
writer->Int(val);
}
}
void json_append_float(void * ptr, const char * key, float val) {
if (ptr != nullptr) {
CONVERT_WRITER_PTR(ptr);
writer->Key(key);
writer->Double(val);
}
};
void json_append_double(void * ptr, const char * key, double val) {
if (ptr != nullptr) {
CONVERT_WRITER_PTR(ptr);
writer->Key(key);
writer->Double(val);
}
}
void json_append_string(void * ptr, const char * key, const char * val) {
if (ptr != nullptr) {
CONVERT_WRITER_PTR(ptr);
writer->Key(key);
writer->String(val);
}
}
void json_append_bool(void * ptr, const char * key, bool val) {
if (ptr != nullptr) {
CONVERT_WRITER_PTR(ptr);
writer->Key(key);
writer->Bool(val);
}
};
void json_append_bool_array(void * ptr, const char * key, bool * vals, int len) {
if (ptr != nullptr) {
CONVERT_WRITER_PTR(ptr);
writer->Key(key);
writer->StartArray();
for (int i = 0; i < len; i++)
writer->Bool(vals[i]);
writer->EndArray();
}
};
void json_append_int_array(void * ptr, const char * key, int * vals, int len) {
if (ptr != nullptr) {
CONVERT_WRITER_PTR(ptr);
writer->Key(key);
writer->StartArray();
for (int i = 0; i < len; i++)
writer->Int(vals[i]);
writer->EndArray();
}
};
void json_append_float_array(void * ptr, const char * key, float * vals, int len) {
if (ptr != nullptr) {
CONVERT_WRITER_PTR(ptr);
writer->Key(key);
writer->StartArray();
for (int i = 0; i < len; i++)
writer->Double(vals[i]);
writer->EndArray();
}
};
void json_append_double_array(void * ptr, const char * key, double * vals, int len) {
if (ptr != nullptr) {
CONVERT_WRITER_PTR(ptr);
writer->Key(key);
writer->StartArray();
for (int i = 0; i < len; i++)
writer->Double(vals[i]);
writer->EndArray();
}
};
void json_append_string_array(void * ptr, const char * key, const char *vals[], int len) {
if (ptr != nullptr) {
CONVERT_WRITER_PTR(ptr);
writer->Key(key);
writer->StartArray();
for (int i = 0; i < len; i++)
writer->String(vals[i]);
writer->EndArray();
}
};
void json_append_object(void * ptr, const char * key, const char * json, int len) {
if (ptr != nullptr) {
CONVERT_WRITER_PTR(ptr);
writer->Key(key);
writer->RawValue(json, len, rapidjson::kObjectType);
}
};
bool json_doc_has_key(const char * json, const char * key) {
Document doc;
doc.Parse(json);
return doc.HasMember(key);
}
bool json_doc_get_bool(const char * json, const char * key) {
Document doc;
doc.Parse(json);
if (doc.HasMember(key) && doc[key].IsBool()) {
return doc[key].GetBool();
}
return false;
};
int json_doc_get_int(const char * json, const char * key) {
Document doc;
doc.Parse(json);
if (doc.HasMember(key) && doc[key].IsInt()) {
return doc[key].GetInt();
}
return 0;
};
double json_doc_get_double(const char * json, const char * key) {
Document doc;
doc.Parse(json);
if (doc.HasMember(key) && doc[key].IsDouble()) {
return doc[key].GetDouble();
}
if (doc.HasMember(key) && doc[key].IsFloat()) {
return doc[key].GetFloat();
}
return 0;
};
const char * json_doc_get_string(const char * json, const char * key) {
Document doc;
doc.Parse(json);
if (doc.HasMember(key) && doc[key].IsString()) {
return doc[key].GetString();
}
return nullptr;
};
bool json_doc_get_bool_array(const char * json, const char * key, bool * array, int len) {
if (array == nullptr) {
std::cerr << "array cannot be nullptr" << std::endl;
return false;
}
Document doc;
doc.Parse(json);
if (doc.HasMember(key)) {
const Value& vals = doc[key];
if (vals.IsArray() && len >= (int)vals.Size()) {
for (SizeType i = 0; i < vals.Size(); i++)
if (vals[i].IsBool())
array[i] = vals[i].GetBool();
return true;
}
}
return false;
}
bool json_doc_get_int_array(const char * json, const char * key, int * array, int len) {
if (array == nullptr) {
std::cerr << "array cannot be nullptr" << std::endl;
return false;
}
Document doc;
doc.Parse(json);
if (doc.HasMember(key)) {
const Value& vals = doc[key];
if (vals.IsArray() && len >= (int)vals.Size()) {
for (SizeType i = 0; i < vals.Size(); i++)
if (vals[i].IsInt())
array[i] = vals[i].GetInt();
return true;
}
}
return false;
}
bool json_doc_get_double_array(const char * json, const char * key, double * array, int len) {
if (array == nullptr) {
std::cerr << "array cannot be nullptr" << std::endl;
return false;
}
Document doc;
doc.Parse(json);
if (doc.HasMember(key)) {
const Value& vals = doc[key];
if (vals.IsArray() && len >= (int)vals.Size()) {
for (SizeType i = 0; i < vals.Size(); i++) {
if (vals[i].IsFloat()) array[i] = vals[i].GetFloat();
if (vals[i].IsDouble()) array[i] = vals[i].GetDouble();
}
return true;
}
}
return false;
};
// get string array from json ['1', '2', '3', '4', '5', ..., 'n']
// @param strslen, the length of string array available
// @param len, each single string size available
bool json_doc_get_string_array(const char * json, const char * key, char * array[],
int strslen, int len) {
if (array == nullptr) {
std::cerr << "array cannot be nullptr" << std::endl;
return false;
}
Document doc;
doc.Parse(json);
if (doc.HasMember(key)) {
const Value& vals = doc[key];
if (vals.IsArray()) {
SizeType min_array_len = ((SizeType)strslen < vals.Size()) ? (SizeType)strslen : vals.Size();
// copy string to target
for (SizeType i = 0; i < min_array_len; i++) {
if (vals[i].IsString()) {
int min_copy_size = (len < (int)strlen(vals[i].GetString())) ?
len : strlen(vals[i].GetString());
memcpy(array[i], vals[i].GetString(), min_copy_size);
}
}
return true;
}
}
return false;
};
|
class hilux1_civil_1_open;
class hilux1_civil_1_open_DZE: hilux1_civil_1_open {
displayName = "$STR_VEH_NAME_PICKUP_TAN";
vehicleClass = "DayZ Epoch Vehicles";
terrainCoef = 2.5;
crew = "";
typicalCargo[] = {};
class TransportMagazines {};
class TransportWeapons {};
class HitPoints;
supplyRadius = 1.5;
class Upgrades {
ItemORP[] = {"hilux1_civil_1_open_DZE1",{"ItemToolbox"},{},{{"ItemORP",1},{"PartEngine",1},{"PartWheel",4},{"ItemScrews",2}}};
ItemARM[] = {"Pickup_PK_GUE_DZE",{"ItemToolbox"},{"PKM_DZ"},{{"ItemARM",1},{"PartGeneric",2},{"ItemPole",1},{"ItemScrews",2}}};
};
};
class hilux1_civil_1_open_DZE1: hilux1_civil_1_open_DZE {
displayName = "$STR_VEH_NAME_PICKUP_TAN+";
original = "hilux1_civil_1_open_DZE";
maxspeed = 150; // max engine limit 125-130
terrainCoef = 1.8;
class HitPoints: HitPoints {
class HitLFWheel;
class HitLBWheel;
class HitRFWheel;
class HitRBWheel;
class HitFuel;
class HitEngine;
class HitGlass1;
class HitGlass2;
class HitGlass3;
class HitGlass4;
};
class Upgrades {
ItemAVE[] = {"hilux1_civil_1_open_DZE2",{"ItemToolbox"},{},{{"ItemAVE",1},{"PartGeneric",6},{"ItemScrews",4}}};
ItemARM[] = {"Pickup_PK_GUE_DZE1",{"ItemToolbox"},{"PKM_DZ"},{{"ItemARM",1},{"PartGeneric",2},{"ItemPole",1},{"ItemScrews",2}}};
};
};
class hilux1_civil_1_open_DZE2: hilux1_civil_1_open_DZE1 {
displayName = "$STR_VEH_NAME_PICKUP_TAN++";
armor = 55; // car 20
damageResistance = 0.02099;
class HitPoints: HitPoints {
class HitLFWheel: HitLFWheel {
armor = 0.3;
};
class HitLBWheel: HitLBWheel {
armor = 0.3;
};
class HitRFWheel: HitRFWheel {
armor = 0.3;
};
class HitRBWheel: HitRBWheel {
armor = 0.3;
};
class HitFuel: HitFuel {
armor = 0.5;
};
class HitEngine: HitEngine {
armor = 1;
};
class HitGlass1: HitGlass1 {
armor = 0.3;
};
class HitGlass2: HitGlass2 {
armor = 0.3;
};
class HitGlass3: HitGlass3 {
armor = 0.3;
};
class HitGlass4: HitGlass4 {
armor = 0.3;
};
};
class Upgrades {
ItemLRK[] = {"hilux1_civil_1_open_DZE3",{"ItemToolbox"},{},{{"ItemLRK",1},{"PartGeneric",2},{"ItemWoodCrateKit",1},{"ItemGunRackKit",1},{"ItemScrews",2}}};
ItemARM[] = {"Pickup_PK_GUE_DZE2",{"ItemToolbox"},{"PKM_DZ"},{{"ItemARM",1},{"PartGeneric",2},{"ItemPole",1},{"ItemScrews",2}}};
};
};
class hilux1_civil_1_open_DZE3: hilux1_civil_1_open_DZE2 {
displayName = "$STR_VEH_NAME_PICKUP_TAN+++";
transportMaxWeapons = 20; // car 10
transportMaxMagazines = 100; // car 50
transportmaxbackpacks = 4; // car 2
class Upgrades {
ItemTNK[] = {"hilux1_civil_1_open_DZE4",{"ItemToolbox"},{},{{"ItemTNK",1},{"PartGeneric",2},{"PartFueltank",1},{"ItemJerrycan",2},{"ItemScrews",1}}};
ItemARM[] = {"Pickup_PK_GUE_DZE3",{"ItemToolbox"},{"PKM_DZ"},{{"ItemARM",1},{"PartGeneric",2},{"ItemPole",1},{"ItemScrews",2}}};
};
};
class hilux1_civil_1_open_DZE4: hilux1_civil_1_open_DZE3 {
displayName = "$STR_VEH_NAME_PICKUP_TAN++++";
fuelCapacity = 210; // car 100
class Upgrades {
ItemARM[] = {"Pickup_PK_GUE_DZE4",{"ItemToolbox"},{"PKM_DZ"},{{"ItemARM",1},{"PartGeneric",2},{"ItemPole",1},{"ItemScrews",2}}};
};
};
class hilux1_civil_2_covered;
class hilux1_civil_2_covered_DZE: hilux1_civil_2_covered {
displayName = "$STR_VEH_NAME_PICKUP_COVERED_RED";
vehicleClass = "DayZ Epoch Vehicles";
terrainCoef = 2.5;
crew = "";
typicalCargo[] = {};
class TransportMagazines {};
class TransportWeapons {};
class HitPoints;
supplyRadius = 1.5;
class Upgrades {
ItemORP[] = {"hilux1_civil_2_covered_DZE1",{"ItemToolbox"},{},{{"ItemORP",1},{"PartEngine",1},{"PartWheel",4},{"ItemScrews",2}}};
ItemARM[] = {"Pickup_PK_TK_GUE_EP1_DZE",{"ItemToolbox"},{"PKM_DZ"},{{"ItemARM",1},{"PartGeneric",2},{"ItemPole",1},{"ItemScrews",2}}};
};
};
class hilux1_civil_2_covered_DZE1: hilux1_civil_2_covered_DZE {
displayName = "$STR_VEH_NAME_PICKUP_COVERED_RED+";
original = "hilux1_civil_2_covered_DZE";
maxspeed = 150; // car 100
terrainCoef = 1.8;
class HitPoints: HitPoints {
class HitLFWheel;
class HitLBWheel;
class HitRFWheel;
class HitRBWheel;
class HitFuel;
class HitEngine;
class HitGlass1;
class HitGlass2;
class HitGlass3;
class HitGlass4;
};
class Upgrades {
ItemAVE[] = {"hilux1_civil_2_covered_DZE2",{"ItemToolbox"},{},{{"ItemAVE",1},{"PartGeneric",6},{"ItemScrews",4}}};
ItemARM[] = {"Pickup_PK_TK_GUE_EP1_DZE1",{"ItemToolbox"},{"PKM_DZ"},{{"ItemARM",1},{"PartGeneric",2},{"ItemPole",1},{"ItemScrews",2}}};
};
};
class hilux1_civil_2_covered_DZE2: hilux1_civil_2_covered_DZE1 {
displayName = "$STR_VEH_NAME_PICKUP_COVERED_RED++";
armor = 55; // car 20
damageResistance = 0.02099;
class HitPoints: HitPoints {
class HitLFWheel: HitLFWheel {
armor = 0.3;
};
class HitLBWheel: HitLBWheel {
armor = 0.3;
};
class HitRFWheel: HitRFWheel {
armor = 0.3;
};
class HitRBWheel: HitRBWheel {
armor = 0.3;
};
class HitFuel: HitFuel {
armor = 0.5;
};
class HitEngine: HitEngine {
armor = 1;
};
class HitGlass1: HitGlass1 {
armor = 0.3;
};
class HitGlass2: HitGlass2 {
armor = 0.3;
};
class HitGlass3: HitGlass3 {
armor = 0.3;
};
class HitGlass4: HitGlass4 {
armor = 0.3;
};
};
class Upgrades {
ItemLRK[] = {"hilux1_civil_2_covered_DZE3",{"ItemToolbox"},{},{{"ItemLRK",1},{"PartGeneric",2},{"ItemWoodCrateKit",1},{"ItemGunRackKit",1},{"ItemScrews",2}}};
ItemARM[] = {"Pickup_PK_TK_GUE_EP1_DZE2",{"ItemToolbox"},{"PKM_DZ"},{{"ItemARM",1},{"PartGeneric",2},{"ItemPole",1},{"ItemScrews",2}}};
};
};
class hilux1_civil_2_covered_DZE3: hilux1_civil_2_covered_DZE2 {
displayName = "$STR_VEH_NAME_PICKUP_COVERED_RED+++";
transportMaxWeapons = 20; // car 10
transportMaxMagazines = 100; // car 50
transportmaxbackpacks = 4; // car 2
class Upgrades {
ItemTNK[] = {"hilux1_civil_2_covered_DZE4",{"ItemToolbox"},{},{{"ItemTNK",1},{"PartGeneric",2},{"PartFueltank",1},{"ItemJerrycan",2},{"ItemScrews",1}}};
ItemARM[] = {"Pickup_PK_TK_GUE_EP1_DZE3",{"ItemToolbox"},{"PKM_DZ"},{{"ItemARM",1},{"PartGeneric",2},{"ItemPole",1},{"ItemScrews",2}}};
};
};
class hilux1_civil_2_covered_DZE4: hilux1_civil_2_covered_DZE3 {
displayName = "$STR_VEH_NAME_PICKUP_COVERED_RED++++";
fuelCapacity = 210; // car 100
class Upgrades {
ItemARM[] = {"Pickup_PK_TK_GUE_EP1_DZE4",{"ItemToolbox"},{"PKM_DZ"},{{"ItemARM",1},{"PartGeneric",2},{"ItemPole",1},{"ItemScrews",2}}};
};
};
class hilux1_civil_3_open;
class hilux1_civil_3_open_DZE: hilux1_civil_3_open {
displayName = "$STR_VEH_NAME_PICKUP_WHITE";
vehicleClass = "DayZ Epoch Vehicles";
terrainCoef = 2.5;
crew = "";
typicalCargo[] = {};
class TransportMagazines {};
class TransportWeapons {};
class HitPoints;
supplyRadius = 1.5;
class Upgrades {
ItemORP[] = {"hilux1_civil_3_open_DZE1",{"ItemToolbox"},{},{{"ItemORP",1},{"PartEngine",1},{"PartWheel",4},{"ItemScrews",2}}};
ItemARM[] = {"Pickup_PK_INS_DZE",{"ItemToolbox"},{"PKM_DZ"},{{"ItemARM",1},{"PartGeneric",2},{"ItemPole",1},{"ItemScrews",2}}};
};
};
class hilux1_civil_3_open_DZE1: hilux1_civil_3_open_DZE {
displayName = "$STR_VEH_NAME_PICKUP_WHITE+";
original = "hilux1_civil_3_open_DZE";
maxspeed = 150; // car 100
terrainCoef = 1.8;
class HitPoints: HitPoints {
class HitLFWheel;
class HitLBWheel;
class HitRFWheel;
class HitRBWheel;
class HitFuel;
class HitEngine;
class HitGlass1;
class HitGlass2;
class HitGlass3;
class HitGlass4;
};
class Upgrades {
ItemAVE[] = {"hilux1_civil_3_open_DZE2",{"ItemToolbox"},{},{{"ItemAVE",1},{"PartGeneric",6},{"ItemScrews",4}}};
ItemARM[] = {"Pickup_PK_INS_DZE1",{"ItemToolbox"},{"PKM_DZ"},{{"ItemARM",1},{"PartGeneric",2},{"ItemPole",1},{"ItemScrews",2}}};
};
};
class hilux1_civil_3_open_DZE2: hilux1_civil_3_open_DZE1 {
displayName = "$STR_VEH_NAME_PICKUP_WHITE++";
armor = 55; // car 20
damageResistance = 0.02099;
class HitPoints: HitPoints {
class HitLFWheel: HitLFWheel {
armor = 0.3;
};
class HitLBWheel: HitLBWheel {
armor = 0.3;
};
class HitRFWheel: HitRFWheel {
armor = 0.3;
};
class HitRBWheel: HitRBWheel {
armor = 0.3;
};
class HitFuel: HitFuel {
armor = 0.5;
};
class HitEngine: HitEngine {
armor = 1;
};
class HitGlass1: HitGlass1 {
armor = 0.3;
};
class HitGlass2: HitGlass2 {
armor = 0.3;
};
class HitGlass3: HitGlass3 {
armor = 0.3;
};
class HitGlass4: HitGlass4 {
armor = 0.3;
};
};
class Upgrades {
ItemLRK[] = {"hilux1_civil_3_open_DZE3",{"ItemToolbox"},{},{{"ItemLRK",1},{"PartGeneric",2},{"ItemWoodCrateKit",1},{"ItemGunRackKit",1},{"ItemScrews",2}}};
ItemARM[] = {"Pickup_PK_INS_DZE2",{"ItemToolbox"},{"PKM_DZ"},{{"ItemARM",1},{"PartGeneric",2},{"ItemPole",1},{"ItemScrews",2}}};
};
};
class hilux1_civil_3_open_DZE3: hilux1_civil_3_open_DZE2 {
displayName = "$STR_VEH_NAME_PICKUP_WHITE+++";
transportMaxWeapons = 20; // car 10
transportMaxMagazines = 100; // car 50
transportmaxbackpacks = 4; // car 2
class Upgrades {
ItemTNK[] = {"hilux1_civil_3_open_DZE4",{"ItemToolbox"},{},{{"ItemTNK",1},{"PartGeneric",2},{"PartFueltank",1},{"ItemJerrycan",2},{"ItemScrews",1}}};
ItemARM[] = {"Pickup_PK_INS_DZE3",{"ItemToolbox"},{"PKM_DZ"},{{"ItemARM",1},{"PartGeneric",2},{"ItemPole",1},{"ItemScrews",2}}};
};
};
class hilux1_civil_3_open_DZE4: hilux1_civil_3_open_DZE3 {
displayName = "$STR_VEH_NAME_PICKUP_WHITE++++";
fuelCapacity = 210; // car 100
class Upgrades {
ItemARM[] = {"Pickup_PK_INS_DZE4",{"ItemToolbox"},{"PKM_DZ"},{{"ItemARM",1},{"PartGeneric",2},{"ItemPole",1},{"ItemScrews",2}}};
};
};
|
#pragma once
#include <iostream>
using namespace std;
void InputVector(double a[], int n);
void OutputVector(double a[], int n);
void addVector(double a[], double b[], int n); //cong 2 vector
void multiVector(double a[], int n, double x); //nhan vector voi 1 so thuc
|
// RAVEN BEGIN
// bdube: note that this file is no longer merged with Doom3 updates
//
// MERGE_DATE 09/30/2004
#include "../idlib/precompiled.h"
#pragma hdrstop
#include "Game_local.h"
/*
===============================================================================
idItem
===============================================================================
*/
const idEventDef EV_DropToFloor( "<dropToFloor>" );
const idEventDef EV_RespawnItem( "respawn" );
const idEventDef EV_RespawnFx( "<respawnFx>" );
const idEventDef EV_GetPlayerPos( "<getplayerpos>" );
const idEventDef EV_HideObjective( "<hideobjective>", "e" );
const idEventDef EV_CamShot( "<camshot>" );
// RAVEN BEGIN
// abahr:
const idEventDef EV_SetGravity( "<setGravity>" );
// RAVEN END
CLASS_DECLARATION( idEntity, idItem )
EVENT( EV_DropToFloor, idItem::Event_DropToFloor )
EVENT( EV_Touch, idItem::Event_Touch )
EVENT( EV_Activate, idItem::Event_Trigger )
EVENT( EV_RespawnItem, idItem::Event_Respawn )
EVENT( EV_RespawnFx, idItem::Event_RespawnFx )
// RAVEN BEGIN
// abahr
EVENT( EV_SetGravity, idItem::Event_SetGravity )
// RAVEN END
END_CLASS
/*
================
idItem::idItem
================
*/
idItem::idItem() {
spin = false;
inView = false;
skin = NULL;
pickupSkin = NULL;
inViewTime = 0;
lastCycle = 0;
lastRenderViewTime = -1;
itemShellHandle = -1;
shellMaterial = NULL;
orgOrigin.Zero();
canPickUp = true;
fl.networkSync = true;
trigger = NULL;
syncPhysics = false;
srvReady = -1;
clReady = -1;
effectIdle = NULL;
itemPVSArea = 0;
effectIdle = NULL;
simpleItem = false;
pickedUp = false;
}
/*
================
idItem::~idItem
================
*/
idItem::~idItem() {
// remove the highlight shell
if ( itemShellHandle != -1 ) {
gameRenderWorld->FreeEntityDef( itemShellHandle );
}
if ( trigger ) {
delete trigger;
}
SetPhysics( NULL );
}
/*
================
idItem::Save
================
*/
void idItem::Save( idSaveGame *savefile ) const {
savefile->WriteClipModel( trigger );
savefile->WriteBool( spin );
savefile->WriteSkin( skin );
savefile->WriteSkin( pickupSkin );
savefile->WriteVec3( orgOrigin );
savefile->WriteBool( pulse );
savefile->WriteBool( canPickUp );
savefile->WriteStaticObject( physicsObj );
// savefile->WriteInt(itemShellHandle); // cnicholson: Set at end of Restore, do not save
savefile->WriteMaterial( shellMaterial );
savefile->WriteBool( inView );
savefile->WriteInt( inViewTime );
savefile->WriteInt( lastCycle );
savefile->WriteInt( lastRenderViewTime );
}
/*
================
idItem::Restore
================
*/
void idItem::Restore( idRestoreGame *savefile ) {
savefile->ReadClipModel( trigger );
savefile->ReadBool( spin );
savefile->ReadSkin( skin );
savefile->ReadSkin( pickupSkin );
savefile->ReadVec3( orgOrigin );
savefile->ReadBool( pulse );
savefile->ReadBool( canPickUp );
savefile->ReadStaticObject ( physicsObj );
// savefile->ReadInt(itemShellHandle); // cnicholson: Set at end of function, do not restore
savefile->ReadMaterial( shellMaterial );
savefile->ReadBool( inView );
savefile->ReadInt( inViewTime );
savefile->ReadInt( lastCycle );
savefile->ReadInt( lastRenderViewTime );
RestorePhysics( &physicsObj );
physicsObj.SetSelf( this );
itemShellHandle = -1;
}
/*
================
idItem::UpdateRenderEntity
================
*/
bool idItem::UpdateRenderEntity( renderEntity_s *renderEntity, const renderView_t *renderView ) const {
if( simpleItem ) {
return false;
}
if ( lastRenderViewTime == renderView->time ) {
return false;
}
lastRenderViewTime = renderView->time;
// check for glow highlighting if near the center of the view
idVec3 dir = renderEntity->origin - renderView->vieworg;
dir.Normalize();
float d = dir * renderView->viewaxis[0];
// two second pulse cycle
float cycle = ( renderView->time - inViewTime ) / 2000.0f;
if ( d > 0.94f ) {
if ( !inView ) {
inView = true;
if ( cycle > lastCycle ) {
// restart at the beginning
inViewTime = renderView->time;
cycle = 0.0f;
}
}
} else {
if ( inView ) {
inView = false;
lastCycle = ceil( cycle );
}
}
// fade down after the last pulse finishes
if ( !inView && cycle > lastCycle ) {
renderEntity->shaderParms[4] = 0.0f;
} else {
// pulse up in 1/4 second
cycle -= (int)cycle;
if ( cycle < 0.1f ) {
renderEntity->shaderParms[4] = cycle * 10.0f;
} else if ( cycle < 0.2f ) {
renderEntity->shaderParms[4] = 1.0f;
} else if ( cycle < 0.3f ) {
renderEntity->shaderParms[4] = 1.0f - ( cycle - 0.2f ) * 10.0f;
} else {
// stay off between pulses
renderEntity->shaderParms[4] = 0.0f;
}
}
// update every single time this is in view
return true;
}
/*
================
idItem::UpdateTrigger
================
*/
void idItem::UpdateTrigger ( void ) {
// update trigger position
// RAVEN BEGIN
// ddynerman: multiple clip worlds
trigger->Link( this, 0, GetPhysics()->GetOrigin(), mat3_identity );
// RAVEN END
}
/*
================
idItem::ModelCallback
================
*/
bool idItem::ModelCallback( renderEntity_t *renderEntity, const renderView_t *renderView ) {
const idItem *ent;
// this may be triggered by a model trace or other non-view related source
if ( !renderView ) {
return false;
}
ent = static_cast<idItem *>(gameLocal.entities[ renderEntity->entityNum ]);
if ( !ent ) {
gameLocal.Error( "idItem::ModelCallback: callback with NULL game entity" );
}
return ent->UpdateRenderEntity( renderEntity, renderView );
}
/*
================
idItem::GetPhysicsToVisualTransform
================
*/
bool idItem::GetPhysicsToVisualTransform( idVec3 &origin, idMat3 &axis ) {
if( simpleItem ) {
if ( gameLocal.GetLocalPlayer() && gameLocal.GetLocalPlayer()->GetRenderView() ) {
if( gameLocal.GetLocalPlayer()->spectating ) {
idPlayer* spec = (idPlayer*)gameLocal.entities[ gameLocal.GetLocalPlayer()->spectator ];
if( spec && spec->GetRenderView() ) {
axis = spec->GetRenderView()->viewaxis;
}
} else {
axis = gameLocal.GetLocalPlayer()->GetRenderView()->viewaxis;
}
} else {
// dedicated server for instance
axis = mat3_identity;
}
origin = idVec3( 0.0f, 0.0f, 32.0f );
return true;
}
if( !spin || (gameLocal.isServer && !gameLocal.isListenServer) ) {
return false;
}
idAngles ang;
ang.pitch = ang.roll = 0.0f;
ang.yaw = ( gameLocal.time & 4095 ) * 360.0f / -4096.0f;
axis = ang.ToMat3() * GetPhysics()->GetAxis();
float scale = 0.005f;
float offset = entityNumber * 0.685145f; // rjohnson: just a random number here to shift the cos curve
origin.Zero();
origin += GetPhysics()->GetAxis()[2] * (4.0f + idMath::Cos( ( ( gameLocal.time + 1000 ) * scale ) + offset ) * 4.0f);
return true;
}
// RAVEN BEGIN
// mekberg: added
/*
================
idItem::Collide
================
*/
bool idItem::Collide( const trace_t &collision, const idVec3 &velocity ) {
idEntity* lol = gameLocal.entities[ collision.c.entityNum ];
if ( gameLocal.isMultiplayer && collision.c.contents & CONTENTS_ITEMCLIP && lol && !lol->IsType( idItem::GetClassType() ) ) {
PostEventMS( &EV_Remove, 0 );
}
return false;
}
// RAVEN END
/*
================
idItem::Think
================
*/
void idItem::Think( void ) {
if ( thinkFlags & TH_PHYSICS ) {
RunPhysics();
UpdateTrigger();
}
if ( gameLocal.IsMultiplayer() && g_skipItemShadowsMP.GetBool() ) {
renderEntity.suppressShadowInViewID = gameLocal.localClientNum + 1;
} else {
renderEntity.suppressShadowInViewID = 0;
}
if( !(simpleItem && pickedUp) ) {
UpdateVisuals();
Present();
}
}
/*
================
idItem::Present
================
*/
void idItem::Present( void ) {
idEntity::Present();
if ( !fl.hidden && pulse ) {
// also add a highlight shell model
renderEntity_t shell;
shell = renderEntity;
// we will mess with shader parms when the item is in view
// to give the "item pulse" effect
shell.callback = idItem::ModelCallback;
shell.entityNum = entityNumber;
shell.customShader = shellMaterial;
if ( itemShellHandle == -1 ) {
itemShellHandle = gameRenderWorld->AddEntityDef( &shell );
} else {
gameRenderWorld->UpdateEntityDef( itemShellHandle, &shell );
}
}
}
/*
================
idItem::InstanceJoin
================
*/
void idItem::InstanceJoin( void ) {
idEntity::InstanceJoin();
UpdateModelTransform();
if ( !simpleItem && spawnArgs.GetString( "fx_idle" ) ) {
PlayEffect( "fx_idle", renderEntity.origin, renderEntity.axis, true );
}
}
/*
================
idItem::InstanceLeave
================
*/
void idItem::InstanceLeave( void ) {
idEntity::InstanceLeave();
StopEffect( "fx_idle", true );
}
/*
================
idItem::Spawn
================
*/
void idItem::Spawn( void ) {
idStr giveTo;
idEntity * ent;
idVec3 vSize;
idBounds bounds(vec3_origin);
// check for triggerbounds, which allows for non-square triggers (useful for, say, a CTF flag)
if ( spawnArgs.GetVector( "triggerbounds", "16 16 16", vSize )) {
bounds.AddPoint(idVec3( vSize.x*0.5f, vSize.y*0.5f, 0.0f));
bounds.AddPoint(idVec3(-vSize.x*0.5f, -vSize.y*0.5f, vSize.z));
}
else {
// create a square trigger for item pickup
float tsize;
spawnArgs.GetFloat( "triggersize", "16.0", tsize );
bounds.ExpandSelf( tsize );
}
// RAVEN BEGIN
// mwhitlock: Dynamic memory consolidation
RV_PUSH_HEAP_MEM(this);
// RAVEN END
trigger = new idClipModel( idTraceModel( bounds ));
// RAVEN BEGIN
// mwhitlock: Dynamic memory consolidation
RV_POP_HEAP();
// RAVEN END
// RAVEN BEGIN
// ddynerman: multiple clip worlds
trigger->Link( this, 0, GetPhysics()->GetOrigin(), GetPhysics()->GetAxis() );
// RAVEN END
physicsObj.SetSelf ( this );
// RAVEN BEGIN
// mwhitlock: Dynamic memory consolidation
RV_PUSH_HEAP_MEM(this);
// RAVEN END
physicsObj.SetClipModel( new idClipModel( GetPhysics()->GetClipModel() ), 1.0f );
// RAVEN BEGIN
// mwhitlock: Dynamic memory consolidation
RV_POP_HEAP();
// RAVEN END
physicsObj.SetOrigin( GetPhysics()->GetOrigin() );
physicsObj.SetAxis( GetPhysics()->GetAxis() );
physicsObj.SetGravity( gameLocal.GetGravity() );
physicsObj.SetContents( 0 );
physicsObj.SetClipMask( MASK_SOLID );
physicsObj.SetFriction( 0.0f, 0.0f, 6.0f );
SetPhysics( &physicsObj );
if ( spawnArgs.GetBool( "start_off" ) ) {
trigger->SetContents( 0 );
Hide();
} else {
trigger->SetContents( CONTENTS_TRIGGER );
}
giveTo = spawnArgs.GetString( "owner" );
if ( giveTo.Length() ) {
ent = gameLocal.FindEntity( giveTo );
if ( !ent ) {
gameLocal.Error( "Item couldn't find owner '%s'", giveTo.c_str() );
}
PostEventMS( &EV_Touch, 0, ent, NULL );
}
if ( spawnArgs.GetBool( "spin" ) || gameLocal.isMultiplayer ) {
spin = true;
BecomeActive( TH_THINK );
}
// pulse ( and therefore itemShellHandle ) was taken out and shot. do not sync
//pulse = !spawnArgs.GetBool( "nopulse" );
pulse = false;
orgOrigin = GetPhysics()->GetOrigin();
canPickUp = !( spawnArgs.GetBool( "triggerFirst" ) || spawnArgs.GetBool( "no_touch" ) );
inViewTime = -1000;
lastCycle = -1;
itemShellHandle = -1;
// RAVEN BEGIN
// abahr: move texture to def file for precaching
shellMaterial = declManager->FindMaterial( spawnArgs.GetString("mtr_highlight", "_default") );
PostEventMS( &EV_SetGravity, 0 );
// RAVEN END
if ( spawnArgs.GetString( "skin", NULL ) ) {
skin = declManager->FindSkin( spawnArgs.GetString( "skin" ), false );
if( skin ) {
SetSkin( skin );
srvReady = 1;
}
} else {
skin = NULL;
}
if ( spawnArgs.GetString( "skin_pickup", NULL ) ) {
pickupSkin = declManager->FindSkin( spawnArgs.GetString( "skin_pickup" ), false );
} else {
pickupSkin = NULL;
}
syncPhysics = spawnArgs.GetBool( "net_syncPhysics", "0" );
if ( srvReady == -1 ) {
srvReady = IsHidden() ? 0 : 1;
}
// RAVEN BEGIN
// mekberg: added for removing pickups in mp in pits
if ( gameLocal.isMultiplayer ) {
trigger->SetContents( trigger->GetContents() | CONTENTS_ITEMCLIP );
}
// RAVEN END
if( gameLocal.isMultiplayer ) {
itemPVSArea = gameLocal.pvs.GetPVSArea( GetPhysics()->GetOrigin() );
} else {
itemPVSArea = 0;
}
simpleItem = g_simpleItems.GetBool() && gameLocal.isMultiplayer && !IsType( rvItemCTFFlag::GetClassType() );
if( simpleItem ) {
memset( &renderEntity, 0, sizeof( renderEntity ) );
renderEntity.axis = mat3_identity;
renderEntity.shaderParms[ SHADERPARM_RED ] = 1.0f;
renderEntity.shaderParms[ SHADERPARM_GREEN ] = 1.0f;
renderEntity.shaderParms[ SHADERPARM_BLUE ] = 1.0f;
renderEntity.shaderParms[ SHADERPARM_ALPHA ] = 1.0f;
renderEntity.shaderParms[ SHADERPARM_SPRITE_WIDTH ] = 32.0f;
renderEntity.shaderParms[ SHADERPARM_SPRITE_HEIGHT ] = 32.0f;
renderEntity.hModel = renderModelManager->FindModel( "_sprite" );
renderEntity.callback = NULL;
renderEntity.numJoints = 0;
renderEntity.joints = NULL;
renderEntity.customSkin = 0;
renderEntity.noShadow = true;
renderEntity.noSelfShadow = true;
renderEntity.customShader = declManager->FindMaterial( spawnArgs.GetString( "mtr_simple_icon" ) );
renderEntity.referenceShader = 0;
renderEntity.bounds = renderEntity.hModel->Bounds( &renderEntity );
SetAxis( mat3_identity );
} else {
if ( spawnArgs.GetString( "fx_idle" ) ) {
UpdateModelTransform();
effectIdle = PlayEffect( "fx_idle", renderEntity.origin, renderEntity.axis, true );
}
}
GetPhysics( )->SetClipMask( GetPhysics( )->GetClipMask( ) | CONTENTS_ITEMCLIP );
pickedUp = false;
}
/*
================
idItem::Event_SetGravity
================
*/
void idItem::Event_SetGravity() {
// If the item isnt a dropped item then see if it should settle itself
// to the floor or not
if ( !spawnArgs.GetBool( "dropped" ) ) {
if ( spawnArgs.GetBool( "nodrop" ) ) {
physicsObj.PutToRest();
} else {
PostEventMS( &EV_DropToFloor, 0 );
}
}
}
// RAVEN END
/*
================
idItem::GetAttributes
================
*/
void idItem::GetAttributes( idDict &attributes ) {
int i;
const idKeyValue *arg;
for( i = 0; i < spawnArgs.GetNumKeyVals(); i++ ) {
arg = spawnArgs.GetKeyVal( i );
if ( arg->GetKey().Left( 4 ) == "inv_" ) {
attributes.Set( arg->GetKey().Right( arg->GetKey().Length() - 4 ), arg->GetValue() );
}
}
}
/*
================
idItem::GiveToPlayer
================
*/
bool idItem::GiveToPlayer( idPlayer *player ) {
if ( player == NULL ) {
return false;
}
if ( spawnArgs.GetBool( "inv_carry" ) ) {
return player->GiveInventoryItem( &spawnArgs );
}
// Handle the special ammo pickup that gives ammo for the weapon the player currently has
if ( spawnArgs.GetBool( "item_currentWeaponAmmo" ) ) {
const char *ammoName = player->weapon->GetAmmoNameForIndex(player->weapon->GetAmmoType());
if ( player->weapon->TotalAmmoCount() != player->weapon->maxAmmo && player->weapon->AmmoRequired() ) {
player->GiveItem(ammoName);
player->GiveInventoryItem( &spawnArgs );
return true;
}
return false;
}
return player->GiveItem( this );
}
/*
===============
idItem::SendPickupMsg
===============
*/
void idItem::SendPickupMsg( int clientNum ) {
idBitMsg msg;
byte msgBuf[MAX_GAME_MESSAGE_SIZE];
msg.Init( msgBuf, sizeof( msgBuf ) );
msg.WriteByte( GAME_UNRELIABLE_MESSAGE_EVENT );
msg.WriteBits( gameLocal.GetSpawnId( this ), 32 );
msg.WriteByte( EVENT_PICKUP );
msg.WriteByte( clientNum );
// send as unreliable to client picking up the item, so it can play HUD things
gameLocal.SendUnreliableMessagePVS( msg, this, itemPVSArea );
}
/*
================
idItem::Pickup
================
*/
bool idItem::Pickup( idPlayer *player ) {
//dropped weapon?
bool dropped = spawnArgs.GetBool( "dropped" );
if ( gameLocal.isMultiplayer && !dropped && spawnArgs.FindKey( "weaponclass" )
&& gameLocal.IsWeaponsStayOn() && gameLocal.time > player->lastPickupTime + 1000 ) {
idDict attr;
GetAttributes( attr );
const idKeyValue* arg = attr.FindKey( "weapon" );
if ( arg ) {
if ( !player->inventory.Give( player, player->spawnArgs, arg->GetKey(), arg->GetValue(), NULL, false, dropped, true ) ) {
StartSound( "snd_noacquire", SND_CHANNEL_ITEM, 0, false, NULL );
}
}
}
// only predict noacquire on client
if ( gameLocal.isClient ) {
return false;
}
int givenToPlayer = spawnArgs.GetInt( "givenToPlayer", "-1" );
if ( player == NULL || ( givenToPlayer != -1 && givenToPlayer != player->entityNumber ) ) {
// idPlayer::GiveItem spawns an idItem for pickup, which appears at the origin before being picked
// and could sometimes be picked by someone else, particularly in buy mode when there is a play spawn sitting on the origin ;-)
return false;
}
if ( !GiveToPlayer( player ) ) {
return false;
}
if ( gameLocal.isServer ) {
SendPickupMsg( player->entityNumber );
}
// Check for global acquire sounds in multiplayer
if ( gameLocal.isMultiplayer && spawnArgs.GetBool( "globalAcquireSound" ) ) {
gameLocal.mpGame.PlayGlobalItemAcquireSound( entityDefNumber );
} else {
StartSound( "snd_acquire", SND_CHANNEL_ITEM, 0, false, NULL );
}
// trigger our targets
ActivateTargets( player );
player->lastPickupTime = gameLocal.time;
//if a placed item and si_weaponStay is on and we're a weapon, don't remove and respawn
if ( gameLocal.IsMultiplayer() ) {
if ( !dropped ) {
if ( spawnArgs.FindKey( "weaponclass" ) ) {
if ( gameLocal.IsWeaponsStayOn() ) {
return true;
}
}
}
}
// clear our contents so the object isn't picked up twice
GetPhysics()->SetContents( 0 );
// hide the model, or switch to the pickup skin
if ( pickupSkin ) {
SetSkin( pickupSkin );
srvReady = 0;
} else {
Hide();
BecomeInactive( TH_THINK );
}
pickedUp = true;
// allow SetSkin or Hide() to get called regardless of simpleitem mode
if( simpleItem ) {
FreeModelDef();
UpdateVisuals();
}
// remove the highlight shell
if ( itemShellHandle != -1 ) {
gameRenderWorld->FreeEntityDef( itemShellHandle );
itemShellHandle = -1;
}
// asalmon: Added option for a differnt respawn rate based on gametype.
float respawn = spawnArgs.GetFloat(va("respawn_%s",gameLocal.serverInfo.GetString( "si_gameType" )), "-1.0");
if( respawn == -1.0f ) {
respawn = spawnArgs.GetFloat( "respawn", "5.0" );
}
bool no_respawn = spawnArgs.GetBool( "no_respawn" );
if ( !gameLocal.isMultiplayer ) {
respawn = 0.0f;
} else if ( gameLocal.mpGame.IsBuyingAllowedInTheCurrentGameMode() ) {
if ( givenToPlayer != -1 ) {
respawn = 0.0f;
}
}
if ( respawn && !dropped && !no_respawn ) {
const char *sfx = spawnArgs.GetString( "fx_Respawn" );
if ( sfx && *sfx ) {
PostEventSec( &EV_RespawnFx, respawn - 0.5f );
}
PostEventSec( &EV_RespawnItem, respawn );
} else if ( !spawnArgs.GetBool( "inv_objective" ) && !no_respawn ) {
// give some time for the pickup sound to play
// FIXME: Play on the owner
if ( !spawnArgs.GetBool( "inv_carry" ) ) {
PostEventMS( &EV_Remove, 5000 );
}
}
trigger->SetContents( 0 );
StopEffect( "fx_idle" );
return true;
}
/*
================
idItem::Hide
================
*/
void idItem::Hide( void ) {
srvReady = 0;
idEntity::Hide( );
trigger->SetContents( 0 );
}
/*
================
idItem::Show
================
*/
void idItem::Show( void ) {
srvReady = 1;
idEntity::Show( );
trigger->SetContents( CONTENTS_TRIGGER );
}
/*
================
idItem::ClientStale
================
*/
bool idItem::ClientStale( void ) {
idEntity::ClientStale();
StopEffect( "fx_idle" );
return false;
}
/*
================
idItem::ClientUnstale
================
*/
void idItem::ClientUnstale( void ) {
idEntity::ClientUnstale();
UpdateModelTransform();
if ( !simpleItem && spawnArgs.GetString( "fx_idle" ) ) {
PlayEffect( "fx_idle", renderEntity.origin, renderEntity.axis, true );
}
}
/*
================
idItem::ClientPredictionThink
================
*/
void idItem::ClientPredictionThink( void ) {
// only think forward because the state is not synced through snapshots
if ( !gameLocal.isNewFrame ) {
return;
}
Think();
}
/*
================
idItem::WriteFromSnapshot
================
*/
void idItem::WriteToSnapshot( idBitMsgDelta &msg ) const {
if ( syncPhysics ) {
physicsObj.WriteToSnapshot( msg );
}
assert( srvReady != -1 );
msg.WriteBits( ( srvReady == 1 ), 1 );
}
/*
================
idItem::ReadFromSnapshot
================
*/
void idItem::ReadFromSnapshot( const idBitMsgDelta &msg ) {
if ( syncPhysics ) {
physicsObj.ReadFromSnapshot( msg );
}
int newReady = ( msg.ReadBits( 1 ) != 0 );
idVec3 resetOrigin( 0, 0, 0 );
// client spawns the ent with ready == -1 so the state set happens at least once
if ( newReady != clReady ) {
if ( newReady ) {
// g_simpleItems might force a hide even with a pickup skin
if ( pickupSkin ) {
SetSkin( skin );
} else {
SetSkin( skin );
Show();
}
if( simpleItem ) {
UpdateVisuals();
}
pickedUp = false;
if ( effectIdle.GetEntity( ) ) {
UpdateModelTransform();
effectIdle->SetOrigin( resetOrigin );
} else if ( spawnArgs.GetString( "fx_idle" ) && !simpleItem ) {
UpdateModelTransform();
effectIdle = PlayEffect( "fx_idle", renderEntity.origin, renderEntity.axis, true );
}
} else {
if ( pickupSkin ) {
SetSkin( pickupSkin );
} else {
Hide();
}
if( simpleItem ) {
FreeModelDef();
UpdateVisuals();
}
pickedUp = true;
StopEffect( "fx_idle" );
effectIdle = NULL;
}
}
clReady = newReady;
}
/*
================
idItem::Event_Pickup
================
*/
void idItem::Event_Pickup( int clientNum ) {
idPlayer *player;
assert( gameLocal.isClient );
// play pickup sound
if ( !spawnArgs.GetBool( "globalAcquireSound" ) ) {
StartSound( "snd_acquire", SND_CHANNEL_ITEM, 0, false, NULL );
}
if( clientNum == gameLocal.localClientNum ) {
player = (idPlayer*)gameLocal.entities[ clientNum ];
player->lastPickupTime = gameLocal.time;
if ( player ) {
player->GiveItem( this );
}
}
}
/*
================
idItem::ClientReceiveEvent
================
*/
bool idItem::ClientReceiveEvent( int event, int time, const idBitMsg &msg ) {
switch( event ) {
case EVENT_PICKUP: {
int clientNum = msg.ReadByte();
if( clientNum >= 0 && clientNum < MAX_CLIENTS ) {
Event_Pickup( clientNum );
}
return true;
}
case EVENT_RESPAWNFX: {
Event_RespawnFx();
return true;
}
default: {
return idEntity::ClientReceiveEvent( event, time, msg );
}
}
//unreachable
// return false;
}
/*
================
idItem::Event_DropToFloor
================
*/
void idItem::Event_DropToFloor( void ) {
// don't drop the floor if bound to another entity
if ( GetBindMaster() != NULL && GetBindMaster() != this ) {
return;
}
physicsObj.DropToFloor( );
}
/*
================
idItem::Event_Touch
================
*/
void idItem::Event_Touch( idEntity *other, trace_t *trace ) {
// RAVEN BEGIN
// jnewquist: Use accessor for static class type
if ( !other->IsType( idPlayer::GetClassType() ) ) {
// RAVEN END
return;
}
if ( !canPickUp ) {
return;
}
Pickup( static_cast<idPlayer *>(other) );
}
/*
================
idItem::Event_Trigger
================
*/
void idItem::Event_Trigger( idEntity *activator ) {
if ( !canPickUp && spawnArgs.GetBool( "triggerFirst" ) ) {
canPickUp = true;
return;
}
// RAVEN BEGIN
// jnewquist: Use accessor for static class type
if ( activator && activator->IsType( idPlayer::GetClassType() ) ) {
// RAVEN END
Pickup( static_cast<idPlayer *>( activator ) );
}
}
/*
================
idItem::Event_Respawn
================
*/
void idItem::Event_Respawn( void ) {
// with simple items, re-show the item, but still set srvReady to true to let clients
// know how to deal
if ( pickupSkin ) {
srvReady = true;
if( !simpleItem ) {
SetSkin( skin );
}
}
if( !pickupSkin ) {
BecomeActive( TH_THINK );
Show();
}
if( simpleItem ) {
Show();
}
pickedUp = false;
inViewTime = -1000;
lastCycle = -1;
trigger->SetContents ( CONTENTS_TRIGGER );
SetOrigin( orgOrigin );
StartSound( "snd_respawn", SND_CHANNEL_ITEM, 0, false, NULL );
PostEventMS( &EV_SetGravity, 0 );
CancelEvents( &EV_RespawnItem ); // don't double respawn
if ( !simpleItem && spawnArgs.GetString( "fx_idle" ) ) {
UpdateModelTransform();
PlayEffect( "fx_idle", renderEntity.origin, renderEntity.axis, true );
}
}
/*
================
idItem::Event_RespawnFx
================
*/
void idItem::Event_RespawnFx( void ) {
idBitMsg msg;
byte msgBuf[MAX_GAME_MESSAGE_SIZE];
if ( gameLocal.isServer ) {
msg.Init( msgBuf, sizeof( msgBuf ) );
msg.WriteByte( GAME_UNRELIABLE_MESSAGE_EVENT );
msg.WriteBits( gameLocal.GetSpawnId( this ), 32 );
msg.WriteByte( EVENT_RESPAWNFX );
// send unreliable PVS-sensitive
gameLocal.SendUnreliableMessagePVS( msg, this, gameLocal.pvs.GetPVSArea( GetPhysics()->GetOrigin() ) );
}
if( !simpleItem ) {
gameLocal.PlayEffect( spawnArgs, "fx_respawn", GetPhysics()->GetOrigin(), idVec3(0,0,1).ToMat3(), false, vec3_origin );
}
}
/*
===============================================================================
idItemPowerup
===============================================================================
*/
/*
===============
idItemPowerup
===============
*/
CLASS_DECLARATION( idItem, idItemPowerup )
END_CLASS
/*
================
idItemPowerup::idItemPowerup
================
*/
idItemPowerup::idItemPowerup() {
time = 0;
type = 0;
droppedTime = 0;
unique = false;
}
/*
================
idItemPowerup::Save
================
*/
void idItemPowerup::Save( idSaveGame *savefile ) const {
savefile->WriteInt( time );
savefile->WriteInt( type );
savefile->WriteInt( droppedTime ); // cnicholson: Added unsaved var
}
/*
================
idItemPowerup::Restore
================
*/
void idItemPowerup::Restore( idRestoreGame *savefile ) {
savefile->ReadInt( time );
savefile->ReadInt( type );
savefile->ReadInt( droppedTime ); // cnicholson: Added unrestored var
}
/*
================
idItemPowerup::Spawn
================
*/
void idItemPowerup::Spawn( void ) {
time = SEC2MS( spawnArgs.GetInt( "time", "30" ) );
// SEC2MS screws up when we want -1 time (no expiration)
if( spawnArgs.GetInt( "time" ) == -1 ) {
time = -1;
}
type = spawnArgs.GetInt( "type", "0" );
// If the powerup was dropped then make it dissapear using its remaining time.
if ( spawnArgs.GetBool( "dropped" ) && time != -1 ) {
droppedTime = gameLocal.time + time;
PostEventMS( &EV_Remove, time );
}
// unique powerpus won't respawn while a player has them
unique = spawnArgs.GetBool( "unique", "0" );
if( unique ) {
spawnArgs.SetBool( "no_respawn", true );
}
if ( !idStr::Icmp( spawnArgs.GetString( "team" ), "strogg" ) ) {
team = TEAM_STROGG;
} else if( !idStr::Icmp( spawnArgs.GetString( "team" ), "marine" ) ) {
team = TEAM_MARINE;
} else {
team = -1;
}
}
/*
================
idItemPowerup::GiveToPlayer
================
*/
bool idItemPowerup::GiveToPlayer( idPlayer *player ) {
if ( player == NULL || player->spectating ) {
return false;
}
// only one arena CTF powerup at a time
if ( type >= POWERUP_AMMOREGEN && type <= POWERUP_SCOUT ) {
if ( ( player->inventory.powerups & ARENA_POWERUP_MASK ) != 0 ) {
return false;
}
}
// in flavours of arena CTF (or are idItemPowerups only used in Arena? or even, are idItemPowerups MP only?),
// ensure that items with a team can only be picked up by members of that team
if ( gameLocal.IsMultiplayer() && gameLocal.IsTeamGame() && team >= 0 ) {
if( team != player->team ) {
return false;
}
}
if ( droppedTime > 0 ) {
player->GivePowerUp( type, droppedTime - gameLocal.time );
} else {
player->GivePowerUp( type, time );
}
// also call idItem::GiveToPlayer so any inv_* keywords get applied
idItem::GiveToPlayer( player );
return true;
}
/*
================
idItemPowerup::Think
================
*/
void idItemPowerup::Think( void ) {
int i;
// idItem::Think() only needs to be called if we're spawned in
if( !IsHidden() || (pickupSkin && GetSkin() != pickupSkin ) ) {
// only get here if spawned in
idItem::Think();
return;
}
if( !unique ) {
// non-unique despawned powerups don't need to think
return;
}
for( i = 0; i < gameLocal.numClients; i++ ) {
idPlayer* p = (idPlayer*)gameLocal.entities[ i ];
if( p == NULL ) {
continue;
}
// only spawn back in if noone on your team has the powerup
if( p->PowerUpActive( type ) && p->team == team ) {
break;
}
}
if( i >= gameLocal.numClients ) {
PostEventMS( &EV_RespawnItem, 0 );
}
}
/*
================
idItemPowerup::Pickup
================
*/
bool idItemPowerup::Pickup( idPlayer* player ) {
// regular pickup routine, but unique items need to think to know when to respawn
bool pickup;
if( gameLocal.isClient ) {
// no client-side powerup prediction
return false;
}
pickup = idItem::Pickup( player );
if( unique ) {
BecomeActive( TH_THINK );
}
return pickup;
}
/*
===============================================================================
idObjective
===============================================================================
*/
CLASS_DECLARATION( idItem, idObjective )
EVENT( EV_Activate, idObjective::Event_Trigger )
EVENT( EV_HideObjective, idObjective::Event_HideObjective )
EVENT( EV_GetPlayerPos, idObjective::Event_GetPlayerPos )
EVENT( EV_CamShot, idObjective::Event_CamShot )
END_CLASS
/*
================
idObjective::idObjective
================
*/
idObjective::idObjective() {
playerPos.Zero();
// RAVEN BEGIN
// mekberg: store triggered time for timed removal.
triggerTime = 0;
// RAVEN END
}
/*
================
idObjective::Save
================
*/
void idObjective::Save( idSaveGame *savefile ) const {
savefile->WriteVec3( playerPos );
}
/*
================
idObjective::Restore
================
*/
void idObjective::Restore( idRestoreGame *savefile ) {
savefile->ReadVec3( playerPos );
// RAVEN BEGIN
// jnewquist: Don't do this on Xenon, we want prebuilt textures
#ifndef _XENON
PostEventMS( &EV_CamShot, 250 );
#endif
// RAVEN END
}
/*
================
idObjective::Spawn
================
*/
void idObjective::Spawn( void ) {
Hide();
// RAVEN BEGIN
// jnewquist: Only post a camshot event if the spawn args request it
#ifndef _XENON
const char *camName;
if ( spawnArgs.GetString( "camShot", "", &camName ) ) {
common->Warning( "SpawnArg camShot on %s is not recommended.", spawnArgs.GetString( "name" ) );
PostEventMS( &EV_CamShot, 250 );
}
#endif
// RAVEN END
}
/*
================
idObjective::Event_Screenshot
================
*/
void idObjective::Event_CamShot( ) {
const char *camName;
// RAVEN BEGIN
// bdube: changed screenshot location
idStr shotName = "gfx/objectives/";
shotName += spawnArgs.GetString( "screenshot" );
shotName.SetFileExtension( ".tga" );
// RAVEN END
if ( spawnArgs.GetString( "camShot", "", &camName ) ) {
idEntity *ent = gameLocal.FindEntity( camName );
if ( ent && ent->cameraTarget ) {
const renderView_t *view = ent->cameraTarget->GetRenderView();
renderView_t fullView = *view;
fullView.width = SCREEN_WIDTH;
fullView.height = SCREEN_HEIGHT;
// draw a view to a texture
renderSystem->CropRenderSize( 256, 256, true );
gameRenderWorld->RenderScene( &fullView );
// TTimo: I don't think this jives with SMP code, but I grepped through the final maps and didn't see any using it
renderSystem->CaptureRenderToFile( shotName );
renderSystem->UnCrop();
}
}
}
/*
================
idObjective::Event_Trigger
================
*/
void idObjective::Event_Trigger( idEntity *activator ) {
idPlayer *player = gameLocal.GetLocalPlayer();
if ( player ) {
if ( spawnArgs.GetString( "inv_objective", NULL ) ) {
// RAVEN BEGIN
// abahr: changed player->hud to player->GetHud so when in a vehicle we update the vehicle hud
// twhitaker: changed player->hud to player->GetObjectiveHud(), to resolve all issues
if ( player && player->GetObjectiveHud() ) {
// bdube: changed screenshot location
idStr shotName = spawnArgs.GetString( "screenshot" );
player->GetObjectiveHud()->SetStateString( "screenshot", shotName );
player->GetObjectiveHud()->SetStateString( "objective", "1" );
player->GetObjectiveHud()->SetStateString( "objectivetext", common->GetLocalizedString( spawnArgs.GetString( "objectivetext" ) ) );
player->GetObjectiveHud()->SetStateString( "objectivetitle", common->GetLocalizedString( spawnArgs.GetString( "objectivetitle" ) ) );
// RAVEN END
player->GiveObjective( spawnArgs.GetString( "objectivetitle" ), spawnArgs.GetString( "objectivetext" ), shotName );
// a tad slow but keeps from having to update all objectives in all maps with a name ptr
for( int i = 0; i < gameLocal.num_entities; i++ ) {
// RAVEN BEGIN
// jnewquist: Use accessor for static class type
if ( gameLocal.entities[ i ] && gameLocal.entities[ i ]->IsType( idObjectiveComplete::GetClassType() ) ) {
// RAVEN END
if ( idStr::Icmp( spawnArgs.GetString( "objectivetitle" ), gameLocal.entities[ i ]->spawnArgs.GetString( "objectivetitle" ) ) == 0 ){
gameLocal.entities[ i ]->spawnArgs.SetBool( "objEnabled", true );
break;
}
}
}
PostEventMS( &EV_GetPlayerPos, 2000 );
// RAVEN BEGIN
// mekberg: store triggered time for timed removal.
triggerTime = gameLocal.time;
// RAVEN END
}
}
}
}
/*
================
idObjective::Event_GetPlayerPos
================
*/
void idObjective::Event_GetPlayerPos() {
idPlayer *player = gameLocal.GetLocalPlayer();
if ( player ) {
playerPos = player->GetPhysics()->GetOrigin();
PostEventMS( &EV_HideObjective, 100, player );
}
}
/*
================
idObjective::Event_HideObjective
================
*/
void idObjective::Event_HideObjective(idEntity *e) {
idPlayer *player = gameLocal.GetLocalPlayer();
if ( player ) {
idVec3 v = player->GetPhysics()->GetOrigin() - playerPos;
// RAVEN BEGIN
// mekberg: hide time done internally now
if ( v.Length() > 64.0f || gameLocal.time > triggerTime + 5000 ) {
// RAVEN END
player->HideObjective ( );
PostEventMS( &EV_Remove, 0 );
} else {
PostEventMS( &EV_HideObjective, 100, player );
}
}
}
/*
===============================================================================
idMoveableItem
===============================================================================
*/
CLASS_DECLARATION( idItem, idMoveableItem )
EVENT( EV_Gib, idMoveableItem::Event_Gib )
END_CLASS
/*
================
idMoveableItem::idMoveableItem
================
*/
idMoveableItem::idMoveableItem() {
}
/*
================
idMoveableItem::~idMoveableItem
================
*/
idMoveableItem::~idMoveableItem() {
// If this entity has been allocated, but not spawned, the physics object will
// not have a self pointer, and will not unregister itself from the entity.
SetPhysics( NULL );
}
/*
================
idMoveableItem::Save
================
*/
void idMoveableItem::Save( idSaveGame *savefile ) const {
savefile->WriteStaticObject( physicsObj );
}
/*
================
idMoveableItem::Restore
================
*/
void idMoveableItem::Restore( idRestoreGame *savefile ) {
savefile->ReadStaticObject ( physicsObj );
RestorePhysics ( &physicsObj );
}
/*
================
idMoveableItem::Spawn
================
*/
void idMoveableItem::Spawn( void ) {
idTraceModel trm;
float density, friction, bouncyness;
idStr clipModelName;
idBounds bounds;
// if the model should be shrinked
if ( spawnArgs.GetBool( "clipshrink" ) ) {
trm.Shrink( CM_CLIP_EPSILON );
}
// get rigid body properties
spawnArgs.GetFloat( "density", "0.5", density );
density = idMath::ClampFloat( 0.001f, 1000.0f, density );
spawnArgs.GetFloat( "friction", "0.05", friction );
friction = idMath::ClampFloat( 0.0f, 1.0f, friction );
spawnArgs.GetFloat( "bouncyness", "0.6", bouncyness );
bouncyness = idMath::ClampFloat( 0.0f, 1.0f, bouncyness );
// setup the physics
physicsObj.SetSelf( this );
// RAVEN BEGIN
// mwhitlock: Dynamic memory consolidation
RV_PUSH_HEAP_MEM(this);
// check if a clip model is set
spawnArgs.GetString( "itemclipmodel", "", clipModelName );
if ( clipModelName[0] ) {
if ( collisionModelManager->TrmFromModel( gameLocal.GetMapName(), clipModelName, trm ) ) {
physicsObj.SetClipModel( new idClipModel( trm ), density );
} else {
// fallback
physicsObj.SetClipModel( new idClipModel( GetPhysics()->GetClipModel() ), density );
}
} else {
// fallback
physicsObj.SetClipModel( new idClipModel( GetPhysics()->GetClipModel() ), density );
}
// mwhitlock: Dynamic memory consolidation
RV_POP_HEAP();
// RAVEN END
physicsObj.SetOrigin( GetPhysics()->GetOrigin() );
physicsObj.SetAxis( GetPhysics()->GetAxis() );
physicsObj.SetBouncyness( bouncyness );
physicsObj.SetFriction( 0.6f, 0.6f, friction );
physicsObj.SetGravity( gameLocal.GetGravity() );
physicsObj.SetContents( CONTENTS_RENDERMODEL );
physicsObj.SetClipMask( MASK_SOLID | CONTENTS_MOVEABLECLIP );
SetPhysics( &physicsObj );
// RAVEN BEGIN
// mekberg: added
if ( spawnArgs.GetBool( "noimpact" ) || spawnArgs.GetBool( "notPushable" ) ) {
physicsObj.DisableImpact();
}
// RAVEN END
}
/*
================
idMoveableItem::Think
================
*/
void idMoveableItem::Think( void ) {
RunPhysics();
UpdateTrigger( );
Present();
}
/*
================
idMoveableItem::DropItem
================
*/
idEntity *idMoveableItem::DropItem( const char *classname, const idVec3 &origin, const idMat3 &axis, const idVec3 &velocity, int activateDelay, int removeDelay ) {
idDict args;
idEntity *item;
args.Set( "classname", classname );
args.Set( "dropped", "1" );
// we sometimes drop idMoveables here, so set 'nodrop' to 1 so that it doesn't get put on the floor
args.Set( "nodrop", "1" );
if ( activateDelay ) {
args.SetBool( "triggerFirst", true );
}
gameLocal.SpawnEntityDef( args, &item );
if ( item ) {
// set item position
item->GetPhysics()->SetOrigin( origin );
item->GetPhysics()->SetAxis( axis );
item->GetPhysics()->SetLinearVelocity( velocity );
item->UpdateVisuals();
if ( activateDelay ) {
item->PostEventMS( &EV_Activate, activateDelay, item );
}
if ( !removeDelay ) {
removeDelay = 5 * 60 * 1000;
}
// always remove a dropped item after 5 minutes in case it dropped to an unreachable location
item->PostEventMS( &EV_Remove, removeDelay );
}
return item;
}
/*
================
idMoveableItem::DropItems
The entity should have the following key/value pairs set:
"def_drop<type>Item" "item def"
"drop<type>ItemJoint" "joint name"
"drop<type>ItemRotation" "pitch yaw roll"
"drop<type>ItemOffset" "x y z"
"skin_drop<type>" "skin name"
To drop multiple items the following key/value pairs can be used:
"def_drop<type>Item<X>" "item def"
"drop<type>Item<X>Joint" "joint name"
"drop<type>Item<X>Rotation" "pitch yaw roll"
"drop<type>Item<X>Offset" "x y z"
where <X> is an aribtrary string.
================
*/
void idMoveableItem::DropItems( idAnimatedEntity *ent, const char *type, idList<idEntity *> *list ) {
const idKeyValue *kv;
const char *skinName, *c, *jointName;
idStr key, key2;
idVec3 origin;
idMat3 axis;
idAngles angles;
const idDeclSkin *skin;
jointHandle_t joint;
idEntity *item;
// drop all items
kv = ent->spawnArgs.MatchPrefix( va( "def_drop%sItem", type ), NULL );
while ( kv ) {
c = kv->GetKey().c_str() + kv->GetKey().Length();
if ( idStr::Icmp( c - 5, "Joint" ) != 0 && idStr::Icmp( c - 8, "Rotation" ) != 0 ) {
key = kv->GetKey().c_str() + 4;
key2 = key;
key += "Joint";
key2 += "Offset";
jointName = ent->spawnArgs.GetString( key );
joint = ent->GetAnimator()->GetJointHandle( jointName );
if ( !ent->GetJointWorldTransform( joint, gameLocal.time, origin, axis ) ) {
gameLocal.Warning( "%s refers to invalid joint '%s' on entity '%s'\n", key.c_str(), jointName, ent->name.c_str() );
origin = ent->GetPhysics()->GetOrigin();
axis = ent->GetPhysics()->GetAxis();
}
if ( g_dropItemRotation.GetString()[0] ) {
angles.Zero();
sscanf( g_dropItemRotation.GetString(), "%f %f %f", &angles.pitch, &angles.yaw, &angles.roll );
} else {
key = kv->GetKey().c_str() + 4;
key += "Rotation";
ent->spawnArgs.GetAngles( key, "0 0 0", angles );
}
axis *= angles.ToMat3() * axis;
origin += ent->spawnArgs.GetVector( key2, "0 0 0" );
item = DropItem( kv->GetValue(), origin, axis, vec3_origin, 0, 0 );
if ( list && item ) {
list->Append( item );
}
}
kv = ent->spawnArgs.MatchPrefix( va( "def_drop%sItem", type ), kv );
}
// change the skin to hide all items
skinName = ent->spawnArgs.GetString( va( "skin_drop%s", type ) );
if ( skinName[0] ) {
skin = declManager->FindSkin( skinName );
ent->SetSkin( skin );
}
}
/*
======================
idMoveableItem::WriteToSnapshot
======================
*/
void idMoveableItem::WriteToSnapshot( idBitMsgDelta &msg ) const {
physicsObj.WriteToSnapshot( msg );
}
/*
======================
idMoveableItem::ReadFromSnapshot
======================
*/
void idMoveableItem::ReadFromSnapshot( const idBitMsgDelta &msg ) {
physicsObj.ReadFromSnapshot( msg );
if ( msg.HasChanged() ) {
UpdateVisuals();
}
}
/*
============
idMoveableItem::Gib
============
*/
void idMoveableItem::Gib( const idVec3 &dir, const char *damageDefName ) {
// remove the entity
PostEventMS( &EV_Remove, 0 );
}
/*
============
idMoveableItem::Event_Gib
============
*/
void idMoveableItem::Event_Gib( const char *damageDefName ) {
Gib( idVec3( 0, 0, 1 ), damageDefName );
}
/*
===============================================================================
idItemRemover
===============================================================================
*/
CLASS_DECLARATION( idEntity, idItemRemover )
EVENT( EV_Activate, idItemRemover::Event_Trigger )
END_CLASS
/*
================
idItemRemover::Spawn
================
*/
void idItemRemover::Spawn( void ) {
}
/*
================
idItemRemover::RemoveItem
================
*/
void idItemRemover::RemoveItem( idPlayer *player ) {
const char *remove;
remove = spawnArgs.GetString( "remove" );
player->RemoveInventoryItem( remove );
}
/*
================
idItemRemover::Event_Trigger
================
*/
void idItemRemover::Event_Trigger( idEntity *activator ) {
// RAVEN BEGIN
// jnewquist: Use accessor for static class type
if ( activator->IsType( idPlayer::GetClassType() ) ) {
// RAVEN END
RemoveItem( static_cast<idPlayer *>(activator) );
}
}
/*
===============================================================================
idObjectiveComplete
===============================================================================
*/
CLASS_DECLARATION( idItemRemover, idObjectiveComplete )
EVENT( EV_Activate, idObjectiveComplete::Event_Trigger )
EVENT( EV_HideObjective, idObjectiveComplete::Event_HideObjective )
EVENT( EV_GetPlayerPos, idObjectiveComplete::Event_GetPlayerPos )
END_CLASS
/*
================
idObjectiveComplete::idObjectiveComplete
================
*/
idObjectiveComplete::idObjectiveComplete() {
playerPos.Zero();
// RAVEN BEGIN
// mekberg: store triggered time for timed removal.
triggerTime = 0;
// RAVEN END
}
/*
================
idObjectiveComplete::Save
================
*/
void idObjectiveComplete::Save( idSaveGame *savefile ) const {
savefile->WriteVec3( playerPos );
}
/*
================
idObjectiveComplete::Restore
================
*/
void idObjectiveComplete::Restore( idRestoreGame *savefile ) {
savefile->ReadVec3( playerPos );
}
/*
================
idObjectiveComplete::Spawn
================
*/
void idObjectiveComplete::Spawn( void ) {
spawnArgs.SetBool( "objEnabled", false );
Hide();
}
/*
================
idObjectiveComplete::Event_Trigger
================
*/
void idObjectiveComplete::Event_Trigger( idEntity *activator ) {
if ( !spawnArgs.GetBool( "objEnabled" ) ) {
return;
}
idPlayer *player = gameLocal.GetLocalPlayer();
if ( player ) {
RemoveItem( player );
if ( spawnArgs.GetString( "inv_objective", NULL ) ) {
// RAVEN BEGIN
// abahr: changed player->hud to player->GetHud so if in a vehicle we update that hud
// twhitaker: moved objective system to it's own hud, to solve vehicle hud issues.
if ( player->GetObjectiveHud() ) {
player->GetObjectiveHud()->SetStateString( "objective", "2" );
player->GetObjectiveHud()->SetStateString( "objectivetext", common->GetLocalizedString( spawnArgs.GetString( "objectivetext" ) ) );
player->GetObjectiveHud()->SetStateString( "objectivetitle", common->GetLocalizedString( spawnArgs.GetString( "objectivetitle" ) ) );
// RAVEN END
player->CompleteObjective( spawnArgs.GetString( "objectivetitle" ) );
PostEventMS( &EV_GetPlayerPos, 2000 );
// RAVEN BEGIN
// mekberg: store triggered time for timed removal.
triggerTime = gameLocal.time;
// RAVEN END
}
}
}
}
/*
================
idObjectiveComplete::Event_GetPlayerPos
================
*/
void idObjectiveComplete::Event_GetPlayerPos() {
idPlayer *player = gameLocal.GetLocalPlayer();
if ( player ) {
playerPos = player->GetPhysics()->GetOrigin();
PostEventMS( &EV_HideObjective, 100, player );
}
}
/*
================
idObjectiveComplete::Event_HideObjective
================
*/
void idObjectiveComplete::Event_HideObjective( idEntity *e ) {
idPlayer *player = gameLocal.GetLocalPlayer();
if ( player && player->GetObjectiveHud() ) {
idVec3 v = player->GetPhysics()->GetOrigin();
v -= playerPos;
// RAVEN BEGIN
// mekberg: hide time done internally now
if ( v.Length() > 64.0f || gameLocal.time > triggerTime + 5000 ) {
// RAVEN END
player->HideObjective ( );
PostEventMS( &EV_Remove, 0 );
} else {
PostEventMS( &EV_HideObjective, 100, player );
}
}
}
/*
===============================================================================
rvObjectiveFailed
===============================================================================
*/
CLASS_DECLARATION( idItemRemover, rvObjectiveFailed )
EVENT( EV_Activate, rvObjectiveFailed::Event_Trigger )
END_CLASS
rvObjectiveFailed::rvObjectiveFailed ( void ) {
}
/*
================
rvObjectiveFailed::Event_Trigger
================
*/
void rvObjectiveFailed::Event_Trigger( idEntity *activator ) {
idPlayer *player = gameLocal.GetLocalPlayer();
if ( !player || !player->GetObjectiveHud() ) {
return;
}
if ( !spawnArgs.GetString( "inv_objective", NULL ) ) {
return;
}
player->GetObjectiveHud()->SetStateString( "objective", "2" );
player->GetObjectiveHud()->SetStateString( "objectivetext", common->GetLocalizedString( spawnArgs.GetString( "objectivetext" ) ) );
player->GetObjectiveHud()->SetStateString( "objectivetitle", common->GetLocalizedString( spawnArgs.GetString( "objectivetitle" ) ) );
player->FailObjective( spawnArgs.GetString( "objectivetitle" ) );
}
/*
===============================================================================
rvItemCTFFlag
===============================================================================
*/
const idEventDef EV_ResetFlag ( "<resetflag>" );
const idEventDef EV_LinkTrigger( "<linktrigger>" );
CLASS_DECLARATION( idItem, rvItemCTFFlag )
EVENT( EV_ResetFlag, rvItemCTFFlag::Event_ResetFlag )
EVENT( EV_LinkTrigger, rvItemCTFFlag::Event_LinkTrigger )
END_CLASS
/*
================
rvItemCTFFlag::rvItemCTFFlag
================
*/
rvItemCTFFlag::rvItemCTFFlag() {
}
/*
================
rvItemCTFFlag::Spawn
================
*/
void rvItemCTFFlag::Spawn () {
/* rjohnson: I fixed the crash so we don't need to remove them...
//don't spawn outside of CTF games
if( (gameLocal.gameType != GAME_CTF) && (gameLocal.gameType != GAME_1F_CTF) &&
(gameLocal.gameType != GAME_ARENA_CTF) && (gameLocal.gameType != GAME_ARENA_1F_CTF) ){
//don't spawn!
gameLocal.Error("Flag spawn on in non-CTF gametype.");
PostEventMS ( &EV_Remove, 0 );
return;
}
*/
spawnArgs.GetBool ( "dropped", "0", dropped );
spawnArgs.GetInt ( "team", "0", team );
bool reset = false;
spawnArgs.GetBool ( "reset", "0", reset );
switch ( team ) {
case TEAM_MARINE: {
powerup = POWERUP_CTF_MARINEFLAG;
gameLocal.mpGame.SetFlagEntity( this, TEAM_MARINE );
break;
}
case TEAM_STROGG: {
powerup = POWERUP_CTF_STROGGFLAG;
gameLocal.mpGame.SetFlagEntity( this, TEAM_STROGG );
break;
}
case TEAM_MAX: {
powerup = POWERUP_CTF_ONEFLAG;
break;
}
default:
gameLocal.Warning ( "Unknown ctf flag team '%d' on entity '%s'", team, name.c_str() );
PostEventMS ( &EV_Remove, 0 );
return;
}
if ( dropped ) {
if ( !gameLocal.isClient ) {
((rvCTFGameState*)gameLocal.mpGame.GetGameState())->SetFlagState( team, FS_DROPPED );
}
if ( reset ) {
//PostEventSec( &EV_ResetFlag, 1 );
} else {
PostEventSec( &EV_ResetFlag, 30 );
}
// Let powerups settle for a frame before allowing them to be picked up - we need to
// make sure we hit the dropped state for VO, etc to work properly
trigger->SetContents( 0 );
PostEventSec( &EV_LinkTrigger, 0 );
} else {
if ( !gameLocal.isClient ) {
((rvCTFGameState*)gameLocal.mpGame.GetGameState())->SetFlagState( team, FS_AT_BASE );
}
}
GetPhysics( )->SetClipMask( GetPhysics( )->GetClipMask( ) | CONTENTS_ITEMCLIP );
spin = false;
}
/*
================
rvItemCTFFlag::Event_LinkTrigger
================
*/
void rvItemCTFFlag::Event_LinkTrigger( void ) {
trigger->SetContents( CONTENTS_TRIGGER | CONTENTS_ITEMCLIP );
}
/*
================
rvItemCTFFlag::GiveToPlayer
================
*/
bool rvItemCTFFlag::GiveToPlayer( idPlayer* player ) {
if ( !gameLocal.IsMultiplayer() ) {
return false;
}
if ( player->spectating || ((gameLocal.mpGame.GetGameState())->GetMPGameState() != GAMEON && (gameLocal.mpGame.GetGameState())->GetMPGameState() != SUDDENDEATH && !cvarSystem->GetCVarBool( "g_testCTF" )) ) {
return false;
}
int teamPowerup;
int enemyPowerup;
bool canPickup = ( team == player->team );
switch ( player->team ) {
default:
case TEAM_MARINE:
teamPowerup = POWERUP_CTF_MARINEFLAG;
enemyPowerup = POWERUP_CTF_STROGGFLAG;
break;
case TEAM_STROGG:
teamPowerup = POWERUP_CTF_STROGGFLAG;
enemyPowerup = POWERUP_CTF_MARINEFLAG;
break;
}
if( gameLocal.gameType == GAME_1F_CTF || gameLocal.gameType == GAME_ARENA_1F_CTF ) {
// in one flag CTF, we score touching the enemy's flag
canPickup = ( team == gameLocal.mpGame.OpposingTeam( player->team ) );
enemyPowerup = POWERUP_CTF_ONEFLAG;
}
// If the player runs over their own flag the only thing they
// can do is score or return it.
// when the player touches the one flag, he always gets it
if ( canPickup ) {
// If the flag was dropped, return it
if ( dropped ) {
gameLocal.mpGame.AddPlayerTeamScore( player, 2 );
statManager->FlagReturned( player );
ResetFlag ( teamPowerup );
// RITUAL BEGIN
// squirrel: Mode-agnostic buymenus
player->GiveCash( (float)gameLocal.mpGame.mpBuyingManager.GetIntValueForKey( "playerCashAward_flagReturned", 0 ) );
// RITUAL END
} else if ( player->PowerUpActive ( enemyPowerup ) ) {
// If they have the enemy flag then they score
if ( !gameLocal.mpGame.CanCapture ( player->team ) ) {
return false;
}
ResetFlag( enemyPowerup );
gameLocal.mpGame.FlagCaptured( player );
}
return false;
}
// only pickup one flag in arena CTF
if( ( gameLocal.gameType == GAME_1F_CTF || gameLocal.gameType == GAME_ARENA_1F_CTF ) && team != TEAM_MAX ) {
return false;
}
player->GivePowerUp( enemyPowerup, -1 );
// RITUAL BEGIN
// squirrel: Mode-agnostic buymenus
player->GiveCash( (float)gameLocal.mpGame.mpBuyingManager.GetIntValueForKey( "playerCashAward_flagStolen", 0 ) );
// RITUAL END
return true;
}
/*
================
rvItemCTFFlag::Pickup
================
*/
bool rvItemCTFFlag::Pickup( idPlayer *player ) {
if( gameLocal.isClient ) {
// no client-side CTF flag prediction
return false;
}
if ( !GiveToPlayer( player ) ) {
return false;
}
// ServerSendEvent( EVENT_PICKUP, NULL, false, -1 );
if ( gameLocal.isServer ) {
SendPickupMsg( player->entityNumber );
}
// Check for global acquire sounds in multiplayer
if ( gameLocal.isMultiplayer && spawnArgs.GetBool( "globalAcquireSound" ) ) {
gameLocal.mpGame.PlayGlobalItemAcquireSound( entityDefNumber );
} else {
StartSound( "snd_acquire", SND_CHANNEL_ITEM, 0, false, NULL );
}
// trigger our targets
ActivateTargets( player );
// clear our contents so the object isn't picked up twice
GetPhysics()->SetContents( 0 );
// hide the model
Hide();
gameLocal.mpGame.SetFlagEntity( NULL, team );
gameLocal.mpGame.AddPlayerTeamScore( player, 1 );
if( gameLocal.gameType == GAME_CTF || gameLocal.gameType == GAME_ARENA_CTF ) {
((rvCTFGameState*)gameLocal.mpGame.GetGameState())->SetFlagState( team, FS_TAKEN );
} else if( gameLocal.gameType == GAME_1F_CTF || gameLocal.gameType == GAME_ARENA_1F_CTF ) {
((rvCTFGameState*)gameLocal.mpGame.GetGameState())->SetFlagState( team, (player->team == TEAM_MARINE ? FS_TAKEN_MARINE : FS_TAKEN_STROGG) );
}
((rvCTFGameState*)gameLocal.mpGame.GetGameState())->SetFlagCarrier( team, player->entityNumber );
if ( spawnArgs.GetBool( "dropped" ) ) {
PostEventMS( &EV_Remove, 0 );
}
BecomeInactive( TH_THINK );
return true;
}
/*
================
rvItemCTFFlag::ResetFlag
================
*/
void rvItemCTFFlag::ResetFlag( int powerup ) {
idEntity* ent;
for ( ent = gameLocal.spawnedEntities.Next(); ent != NULL; ent = ent->spawnNode.Next() ) {
// Make sure no players have the flag anymore
// RAVEN BEGIN
// jnewquist: Use accessor for static class type
if ( ent->IsType ( idPlayer::GetClassType() ) ) {
// RAVEN END
static_cast<idPlayer*>(ent)->ClearPowerup ( powerup );
continue;
}
// If its not a CTF flag item then skip it
if ( !ent->IsType( rvItemCTFFlag::Type ) ) {
continue;
}
// Make sure its the right type first
rvItemCTFFlag* flag;
flag = static_cast<rvItemCTFFlag*>(ent);
if ( flag->powerup != powerup ) {
continue;
}
if ( flag->dropped ) {
flag->PostEventMS( &EV_Remove, 0 );
} else {
flag->PostEventMS( &EV_RespawnItem, 0 );
gameLocal.mpGame.SetFlagEntity( flag, flag->team );
}
}
if ( !gameLocal.isClient ) {
int team = -1;
if ( powerup == POWERUP_CTF_MARINEFLAG ) {
team = TEAM_MARINE;
} else if ( powerup == POWERUP_CTF_STROGGFLAG ) {
team = TEAM_STROGG;
} else if ( powerup == POWERUP_CTF_ONEFLAG ) {
team = TEAM_MAX;
}
((rvCTFGameState*)gameLocal.mpGame.GetGameState())->SetFlagState( team, FS_AT_BASE );
}
}
/*
================
rvItemCTFFlag::Event_ResetFlag
================
*/
void rvItemCTFFlag::Event_ResetFlag( void ) {
ResetFlag( powerup );
}
void rvItemCTFFlag::Think( void ) {
idItem::Think();
}
/*
================
rvItemCTFFlag::Collide
================
*/
bool rvItemCTFFlag::Collide( const trace_t &collision, const idVec3 &velocity ) {
idEntity* lol = gameLocal.entities[ collision.c.entityNum ];
if ( collision.c.contents & CONTENTS_ITEMCLIP && lol && !lol->IsType( idItem::GetClassType() ) ) {
ResetFlag( powerup );
}
return false;
}
// RAVEN END
const idEventDef EV_ResetSpawn ( "<resetspawn>" );
CLASS_DECLARATION( idItemPowerup, riDeadZonePowerup )
EVENT( EV_ResetSpawn, riDeadZonePowerup::Event_ResetSpawn )
END_CLASS
/*
================
riDeadZonePowerup::idItemPowerup
================
*/
riDeadZonePowerup::riDeadZonePowerup() {
}
/*
================
riDeadZonePowerup::Save
================
*/
void riDeadZonePowerup::Save( idSaveGame *savefile ) const {
}
/*
================
riDeadZonePowerup::Restore
================
*/
void riDeadZonePowerup::Restore( idRestoreGame *savefile ) {
}
/*
================
riDeadZonePowerup::Show
================
*/
void riDeadZonePowerup::Show()
{
idItem::Show();
}
/*
================
riDeadZonePowerup::Spawn
================
*/
void riDeadZonePowerup::Spawn( void ) {
powerup = POWERUP_DEADZONE;
time = SEC2MS( gameLocal.serverInfo.GetInt("si_deadZonePowerupTime") );
if ( spawnArgs.GetBool( "dropped" ) ) {
time = SEC2MS( spawnArgs.GetInt( "time", "10" ) );
if ( time > SEC2MS(10) )
time = SEC2MS(10);
Show();
CancelEvents(&EV_Remove);
PostEventSec( &EV_ResetSpawn, MS2SEC(time) );
}
else
Hide();
}
/*
================
riDeadZonePowerup::Pickup
================
*/
bool riDeadZonePowerup::Pickup( idPlayer* player ) {
// regular pickup routine, but unique items need to think to know when to respawn
bool pickup;
if ( player->PowerUpActive(POWERUP_DEADZONE) )
return false;
pickup = idItemPowerup::Pickup( player );
if ( spawnArgs.GetBool( "dropped" ) ) {
// Cancel the respawn so the powerup doesn't get removed
// from the player that just picked it up.
PostEventMS( &EV_Remove, 0 );
CancelEvents( &EV_ResetSpawn );
}
return pickup;
}
/*
================
riDeadZonePowerup::ResetSpawn
================
*/
void riDeadZonePowerup::ResetSpawn( int powerup ) {
int count = 1;
idEntity* ent;
riDeadZonePowerup* spawnSpot = 0;
for ( ent = gameLocal.spawnedEntities.Next(); ent != NULL; ent = ent->spawnNode.Next() ) {
// If its not a DeadZone powerup then skip it
if ( !ent->IsType( riDeadZonePowerup::Type ) ) {
continue;
}
// Make sure its the right type first
riDeadZonePowerup* flag;
flag = static_cast<riDeadZonePowerup*>(ent);
if ( flag->powerup != powerup ) {
continue;
}
if ( flag->spawnArgs.GetBool("dropped", "0") && flag == this ) {
flag->PostEventMS( &EV_Remove, 0 );
} else {
if ( !flag->IsVisible() ) {
if ( !(rand()%count) ) {
spawnSpot = flag;
if ( flag->spawnArgs.GetBool("dropped", "0") )
gameLocal.DPrintf("WARNING: Trying to spawn a powerup at a DROPPED location!");
}
count++;
}
}
}
if ( spawnSpot ) {
spawnSpot->Show();
spawnSpot->PostEventMS( &EV_RespawnItem, 0 );
}
else {
gameLocal.DPrintf("WARNING: Failed to find a valid spawn spot!");
}
}
/*
================
riDeadZonePowerup::Collide
================
*/
bool riDeadZonePowerup::Collide( const trace_t &collision, const idVec3 &velocity ) {
idEntity* lol = gameLocal.entities[ collision.c.entityNum ];
if ( gameLocal.isMultiplayer && collision.c.contents & CONTENTS_ITEMCLIP && lol && !lol->IsType( idItem::GetClassType() ) ) {
PostEventMS( &EV_ResetSpawn, 0 ); // Just respawn it.
}
return false;
}
/*
================
riDeadZonePowerup::Event_ResetFlag
================
*/
void riDeadZonePowerup::Event_ResetSpawn( void ) {
ResetSpawn( POWERUP_DEADZONE );
}
|
#include <cstdio>
#include <iostream>
#include <vector>
#include <string>
using namespace std;
bool isPalindrome(string s){
int length = s.length();
for(int i=0;i<length/2;i++){
if(s[i]!=s[length-1-i]) return false;
}
return true;
}
int minCut(string s){
int length = s.length();
if(length == 1) return 0;
int **a = new int*[length];
for(int i=0;i<length;i++)
a[i] = new int[length];
for(int i=0;i<length;i++){
for(int j=0;j<length;j++){
if(i == j) a[i][j] = 0;
else a[i][j] = 1000000;
}
}
for(int k=2;k<=length;k++){
for(int i=0;i<=length-k;i++){
string s1 = s.substr(i,k);
int l = i+k-1;
if(isPalindrome(s1)) a[i][l] = 0;
else{
for(int j=i;j<l;j++){
int min = a[i][j] + a[j+1][l] + 1;
if( min < a[i][l] )
a[i][l] = min;
}
}
}
}
return a[0][length-1];
}
int main(){
string s;
int res;
cin >> s;
cout << "Finish Input" <<endl;
res = minCut(s);
cout << res <<endl;
cout << "Finish Ouput" <<endl;
}
|
#include <bits/stdc++.h>
using namespace std;
#define f first
#define s second
#define pb push_back
#define rep(i, begin, end) \
for (__typeof(end) i = (begin) - ((begin) > (end)); \
i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end)))
#define db(x) cout << '>' << #x << ':' << x << endl;
#define sz(x) ((int)(x).size())
#define newl cout << "\n"
#define ll long long int
#define vi vector<int>
#define vll vector<long long>
#define vvll vector<vll>
#define pll pair<long long, long long>
#define fast_io() \
ios_base::sync_with_stdio(false); \
cin.tie(NULL); \
cout.tie(NULL);
const int mxN = 2e5 + 7;
const int mxM = 2e5 + 7;
const int inf = 1e9;
ll tc, n, m, k;
vll g1[mxN], g2[mxN];
ll vis[mxN], who[mxN];
vll tops, comp;
char ans[mxN];
void dfs1(ll u) {
vis[u] = 1;
for (auto v : g1[u]) {
if (!vis[v])
dfs1(v);
}
tops.pb(u);
}
void dfs2(ll u, ll sccid) {
vis[u] = 0;
who[u] = sccid;
for (auto v : g2[u]) {
if (vis[v])
dfs2(v, sccid);
}
comp.pb(u);
}
int main() {
// cses 2sat;
// all conditions' implications
/*
(any one is true or both true )
(a or b) => !a -> b, !b -> a
(any one is true but not both true)
(a xor b) is (a or b) && (!a or !b) => 4edges; (4 implications
(both same, either (0,0) or (1,1))
(a <-> b) is (!a xor b);
*/
fast_io();
#ifndef ONLINE_JUDGE
freopen("../input.txt", "r", stdin);
freopen("../output.txt", "w", stdout);
#endif
cin >> n >> m;
rep(i, 0, n) {
char a, b;
ll u, v;
cin >> a >> u >> b >> v;
u *= 2, v *= 2;
if (a == '-')
u = u ^ 1;
if (b == '-')
v = v ^ 1;
g1[u ^ 1].pb(v);
g1[v ^ 1].pb(u);
}
// since u can be upto 2m or 2m+1
for (int u = 1; u <= 2 * m + 1; u++) {
for (auto v : g1[u])
g2[v].pb(u);
}
for (int u = 1; u <= 2 * m + 1; u++) {
if (!vis[u])
dfs1(u);
}
// reverse process topsort;
for (int i = tops.size() - 1; i >= 0; i--) {
auto u = tops[i];
if (vis[u]) {
dfs2(u, i);
comp.clear();
}
}
// check 2 sat condition, x and !x shouldnt be in same component;
for (int u = 1; u <= m; u++) {
if (who[u * 2] == who[u * 2 + 1]) {
cout << "IMPOSSIBLE";
return 0;
}
// usually in topsort order, if comp[x] < comp[!x], then x is false;
// here, topsort ids are bigger to smaller;
ans[u] = (who[2 * u] > who[2 * u + 1]) ? '-' : '+';
}
for (int u = 1; u <= m; u++) {
cout << ans[u] << " ";
}
return 0;
}
// look for more problems in cp-algorithms, solved door problem.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.