blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 905
values | visit_date timestamp[us]date 2015-08-09 11:21:18 2023-09-06 10:45:07 | revision_date timestamp[us]date 1997-09-14 05:04:47 2023-09-17 19:19:19 | committer_date timestamp[us]date 1997-09-14 05:04:47 2023-09-06 06:22:19 | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22
values | gha_event_created_at timestamp[us]date 2012-06-07 00:51:45 2023-09-14 21:58:39 ⌀ | gha_created_at timestamp[us]date 2008-03-27 23:40:48 2023-08-21 23:17:38 ⌀ | gha_language stringclasses 141
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 115
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
02a85e138f7a8b8a5c8f0ef7b5145adbe1ae6cbe | c86269fcadcc2b8686199d32d168c84673709ba5 | /src/controller/Controller.cpp | 8027cd9deeff28de409d04c4fc27315dc194b156 | [] | no_license | Szkodnik128/PokerGame | b007a10f955ff86202265b9d9f8266c006235fbb | 93f98c1e4d4ebf4e7b40a0ad5b8fef4db3d4e445 | refs/heads/master | 2019-07-09T11:59:59.676386 | 2018-06-03T14:21:04 | 2018-06-03T14:21:04 | 34,904,229 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,817 | cpp | //
// Created by kuba on 18.03.18.
//
#include "Controller.h"
#include "event/EventRecvRequest.h"
#include "event/EventConnectionClosed.h"
Controller::Controller(BlockingQueue<Event *> *const blockingQueue, Model *const model)
: blockingQueue(blockingQueue),
model(model),
workerFlag(false)
{
/* Fill event strategy map */
this->eventStrategyMap[typeid(EventRecvRequest).name()] = &Controller::eventRecvRequestHandler;
this->eventStrategyMap[typeid(EventConnectionClosed).name()] = &Controller::eventConnectionClosedHandler;
/* Fill message strategy map */
this->messageStrategyMap[Request::PayloadCase::kLogin] = &Controller::messageLoginHandler;
this->messageStrategyMap[Request::PayloadCase::kCreateTable] = &Controller::messageCreateTableHandler;
this->messageStrategyMap[Request::PayloadCase::kJoinTable] = &Controller::messageJoinTableHandler;
this->messageStrategyMap[Request::PayloadCase::kLeaveTable] = &Controller::messageLeaveTableHandler;
this->messageStrategyMap[Request::PayloadCase::kRaiseBet] = &Controller::messageRaiseHandler;
this->messageStrategyMap[Request::PayloadCase::kFold] = &Controller::messageFoldHandler;
this->messageStrategyMap[Request::PayloadCase::kCall] = &Controller::messageCallHandler;
}
void Controller::run()
{
Event *event;
EventHandler handler;
this->workerFlag = true;
while (this->workerFlag) {
event = this->blockingQueue->pop();
handler = this->eventStrategyMap[typeid(*event).name()];
assert(handler != nullptr);
(this->*handler)(event);
delete event;
}
}
void Controller::setWorkerFlag(bool workerFlag) {
this->workerFlag = workerFlag;
}
void Controller::eventRecvRequestHandler(Event *event)
{
MessageHandler handler;
auto *eventRecvRequest = (EventRecvRequest *)event;
const Request &request = eventRecvRequest->getRequest();
handler = this->messageStrategyMap[request.payload_case()];
assert(handler != nullptr);
(this->*handler)(&request, (ClientHandler *const)eventRecvRequest->getClientHandler());
}
void Controller::eventConnectionClosedHandler(Event *event)
{
auto *eventConnectionClosed = (EventConnectionClosed *)event;
this->model->disconnect((ClientHandler *const)eventConnectionClosed->getClientHandler());
}
void Controller::messageLoginHandler(const Request *const request, ClientHandler *const clientHandler)
{
const Login &login = request->login();
this->model->login(login, clientHandler);
}
void Controller::messageCreateTableHandler(const Request *const request, ClientHandler *const clientHandler)
{
const CreateTable &createTable = request->createtable();
this->model->createTable(createTable, clientHandler);
}
void Controller::messageJoinTableHandler(const Request *const request, ClientHandler *const clientHandler)
{
const JoinTable &joinTable = request->jointable();
this->model->joinTable(joinTable, clientHandler);
}
void Controller::messageLeaveTableHandler(const Request *const request, ClientHandler *const clientHandler)
{
const LeaveTable &leaveTable = request->leavetable();
this->model->leaveTable(leaveTable, clientHandler);
}
void Controller::messageRaiseHandler(const Request *const request, ClientHandler *const clientHandler)
{
const Raise &raise = request->raise_bet();
this->model->raise(raise, clientHandler);
}
void Controller::messageFoldHandler(const Request *const request, ClientHandler *const clientHandler)
{
const Fold &fold = request->fold();
this->model->fold(fold, clientHandler);
}
void Controller::messageCallHandler(const Request *const request, ClientHandler *const clientHandler)
{
const Call &call = request->call();
this->model->call(call, clientHandler);
} | [
"ku3atonie@gmail.com"
] | ku3atonie@gmail.com |
0a040f07afc11a87345a30c7fd994772f0ed972b | a13a4dfcf577632bee9bfbc430ce469c1afe6652 | /libraries/ros_lib/pano_ros/PanoCaptureFeedback.h | 313e0be22d316aaecbf276c16cae6c87879aa4a4 | [] | no_license | kirancps/ROS_Arduino | 5cb8abeea6f87c2a8fa332ea9ebedc325ae5a0fb | 537b45aa9c200e8f5be9a8f4625e045c6a7a8509 | refs/heads/master | 2021-01-10T18:52:58.914367 | 2016-04-17T11:23:07 | 2016-04-17T11:23:07 | 56,432,459 | 2 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 1,687 | h | #ifndef _ROS_pano_ros_PanoCaptureFeedback_h
#define _ROS_pano_ros_PanoCaptureFeedback_h
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include "ros/msg.h"
namespace pano_ros
{
class PanoCaptureFeedback : public ros::Msg
{
public:
float n_captures;
PanoCaptureFeedback():
n_captures(0)
{
}
virtual int serialize(unsigned char *outbuffer) const
{
int offset = 0;
union {
float real;
uint32_t base;
} u_n_captures;
u_n_captures.real = this->n_captures;
*(outbuffer + offset + 0) = (u_n_captures.base >> (8 * 0)) & 0xFF;
*(outbuffer + offset + 1) = (u_n_captures.base >> (8 * 1)) & 0xFF;
*(outbuffer + offset + 2) = (u_n_captures.base >> (8 * 2)) & 0xFF;
*(outbuffer + offset + 3) = (u_n_captures.base >> (8 * 3)) & 0xFF;
offset += sizeof(this->n_captures);
return offset;
}
virtual int deserialize(unsigned char *inbuffer)
{
int offset = 0;
union {
float real;
uint32_t base;
} u_n_captures;
u_n_captures.base = 0;
u_n_captures.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0);
u_n_captures.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1);
u_n_captures.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2);
u_n_captures.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3);
this->n_captures = u_n_captures.real;
offset += sizeof(this->n_captures);
return offset;
}
const char * getType(){ return "pano_ros/PanoCaptureFeedback"; };
const char * getMD5(){ return "22ff7abf8b5e4a280047b5a08afb8cf1"; };
};
}
#endif | [
"scikiran@gmail.com"
] | scikiran@gmail.com |
40360636802f93b2ba1d0012663e40df42165a63 | 7233d7ee7502e6dc4638b8d2f283242db59d7557 | /include/StringTable.h | b0a2c0b18dcdefbf2daaec4b7e200c95442bbe3f | [] | no_license | wllxyz/xyz | 628c96f0e1fa903566257dfa37c74b2892d79952 | 70f90b400a03edf8c323310da7d6c5d858a11d6f | refs/heads/master | 2021-08-15T17:13:47.853375 | 2021-01-13T10:18:43 | 2021-01-13T10:18:43 | 49,399,603 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 807 | h | //<FILENAME>StringTable.h</FILENAME>
//<AUTHOR>WangLiLiang</AUTHOR>
//<DATE>2012.04.04</DATE>
//<TYPE>CPP PROGRAM CLASS</TYPE>
#ifndef STRING_TABLE_H
#define STRING_TABLE_H
#include <string>
#include <map>
#include <vector>
#include <iostream>
//#include <hash_map>
namespace Wll
{
class IndexOutOfBoundaryException
{
};
class StringTable
{
public:
typedef std::map<std::string,int> MapType;
public:
//获取字符串注册的索引,如果字符串不存在,首先注册,然后返回新注册的索引值
int GetIndexByName(const std::string& name);
//根据先前注册时分配的索引值获取字符串
const std::string& GetNameByIndex(int index);
private:
MapType name2index_table;
std::vector<std::string> index2name_table;
};
};//end of namespace Wll
#endif //STRING_TABLE_H
| [
"wangliliang@zizizizizi.com"
] | wangliliang@zizizizizi.com |
877cae8f9b0ff37c98ed5f8c69ccaa9094b3213f | 260f53f6449249e20ccbddedbbe854a1ef169d08 | /operators/multiply.cpp | f33b88f83085324db2c18be0cb2a3f02a1a661c5 | [] | no_license | ArnavMohan/ACP_KANBAN | 048712eaf4235ecab5e967a35f492b7e1db242cf | 5fa5b2cd569737f4ba54c0563d2e04341754dcf6 | refs/heads/master | 2021-08-30T05:13:11.085828 | 2017-12-16T04:40:50 | 2017-12-16T04:40:50 | 112,633,309 | 0 | 0 | null | 2017-12-12T15:04:23 | 2017-11-30T16:21:31 | C++ | UTF-8 | C++ | false | false | 682 | cpp | //Author: Rishi
//Operator: *
//Purpose: return the product of two complex numbers
#include "../complex.h"
complex operator*(const complex &lhs, const complex &rhs){
//foil out the two sides into First, Outisde, Inside, Last.
double first_foil = real(&lhs) * real(&rhs);
double outisde_foil = real(&lhs) * imag(&rhs);
double inside_foil = imag(&lhs) * real(&rhs);
double last_foil = imag(&lhs) * imag(&rhs);
//product refers to the product of the two params
//it's the item to be returned
double product_real = first_foil - last_foil;
double product_imag = outside_foil + inside_foil;
complex product = new complex(product_real, product_imag);
return product;
}
| [
"rishi.chandnap6@stu.austinisd.org"
] | rishi.chandnap6@stu.austinisd.org |
f8a9e2b9769f1f6e35d08652f7c2bb950f2c209f | 003f58454dd3cf9af1821b28e68f1f738d244d5e | /kernel/virtio/Network.cpp | 84ebc7b9b986fd54fa81880628c9fe5c6564913d | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | busybox11/skift | 7b5fd54e57e03ad23ab08b8ee8a8edb81a348c2d | 778ae3a0dc5ac29d7de02200c49d3533e47854c5 | refs/heads/master | 2023-01-04T21:38:24.421418 | 2020-08-09T15:02:17 | 2020-08-09T15:02:17 | 279,430,614 | 1 | 0 | NOASSERTION | 2020-07-13T23:10:19 | 2020-07-13T23:10:19 | null | UTF-8 | C++ | false | false | 304 | cpp | #include <libsystem/Logger.h>
#include "kernel/bus/PCI.h"
#include "kernel/virtio/Virtio.h"
bool virtio_network_match(DeviceInfo info)
{
return virtio_is_specific_virtio_device(info, VIRTIO_DEVICE_NETWORK);
}
void virtio_network_initialize(DeviceInfo info)
{
virtio_device_initialize(info);
}
| [
"nicolas.van.bossuyt@gmail.com"
] | nicolas.van.bossuyt@gmail.com |
606dbe0ea9f6f05a99e2d6765c35038d176b66af | c237ea629b644b698476c6965eb6988df46f92a8 | /alg6 - aula1.cpp | d602c81ec32be76d3dd6f6864017fac4541ac47a | [] | no_license | danielrsouza/algoritimos-C | 858957360dd23d74b9185dc28223d55dc753036d | 59ae45dae0448631e2af9854c1a10c3b3ceff57c | refs/heads/master | 2020-04-25T19:16:08.408297 | 2019-02-28T00:39:31 | 2019-02-28T00:39:31 | 173,010,231 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 360 | cpp | #include<stdio.h>
main(){
float n1, n2, n3, media;
printf("Digite a nota 1: \n");
scanf("%f",&n1);
printf("Digite a nota 2: \n");
scanf("%f",&n2);
printf("Digite a nota 3: \n");
scanf("%f",&n3);
media = (n1+n2+n3)/3;
printf("O resultado e: %f",media);
if(media > 7){
printf("voce foi aprovado.");
}else{
printf("voce foi reprovado.");
}
}
| [
"daniel.ricardo@rede.ulbra.br"
] | daniel.ricardo@rede.ulbra.br |
455016ed0c6f20ce7a1c5e22ab8cbd33db0acdc1 | 66213c48da0b752dc6c350789935fe2b2b9ef5ca | /abc/272/e.cpp | abb861c0b414129376f3369169d65837d4dfbda6 | [] | no_license | taketakeyyy/atcoder | 28c58ae52606ba85852687f9e726581ab2539b91 | a57067be27b27db3fee008cbcfe639f5309103cc | refs/heads/master | 2023-09-04T16:53:55.172945 | 2023-09-04T07:25:59 | 2023-09-04T07:25:59 | 123,848,306 | 0 | 0 | null | 2019-04-21T07:39:45 | 2018-03-05T01:37:20 | Python | UTF-8 | C++ | false | false | 3,405 | cpp | #define _USE_MATH_DEFINES // M_PI等のフラグ
#include <bits/stdc++.h>
#define MOD 1000000007
#define COUNTOF(array) (sizeof(array)/sizeof(array[0]))
#define rep(i,n) for (int i = 0; i < (n); ++i)
#define intceil(a,b) ((a+(b-1))/b)
using namespace std;
using ll = long long;
using pii = pair<int,int>;
using pll = pair<long,long>;
const long long INF = LONG_LONG_MAX - 1001001001001001;
void chmax(int& x, int y) { x = max(x,y); }
void chmin(int& x, int y) { x = min(x,y); }
string vs = "URDL"; // 上右下左
vector<ll> vy = { -1, 0, 1, 0 };
vector<ll> vx = { 0, 1, 0, -1 };
void solve() {
ll N, M; cin >> N >> M;
vector<vector<ll>> d(M);
for(ll i=1; i<=N; i++) {
ll a; cin >> a;
a += i;
// 0 <= a+i_x < N が成り立つiを列挙したい
ll l = (0 <= a) ? 0 : intceil(-a, i);
ll r = (N <= a) ? 0 : intceil(-(a-N), i);
r = min(r, M);
for(ll j=l; j<r; j++) {
d[j].push_back(a+i*j);
}
}
for(ll mi=0; mi<M; mi++) {
auto &b = d[mi];
ll sz = b.size();
vector<bool> e(sz+1); // 存在するか
for(ll i: b) e[i] = true;
ll ans = 0;
while(e[ans]) ans++;
cout << ans << endl;
}
}
/*
5 6
-2 -2 -5 -7 -15
*/
void solve2() {
ll N, M; cin >> N >> M;
vector<set<ll>> opSet(M+1); // opSet[i] := i回目の操作後の存在する[0,N]までの整数
for(ll i=1; i<=N; i++) {
ll a; cin >> a;
a += i;
// 0 <= a <= N となる範囲[li, ri]を探す
ll li, ri;
if (a>=0 && a<=N) {
li = 1;
ri = li + (N-a)/i;
}
else if (a < 0){
li = 1 + intceil(-a, i);
ll s = a + (li-1) * i;
ri = li + (N-s)/i;
}
else {
continue;
}
ri = min(ri, M);
for(ll j=li; j<=ri; j++) {
opSet[j].insert(a+i*(j-1));
}
}
// 出力 O(NM)な感じだがopSet[mi]はスカスカ
for(ll mi=1; mi<=M; mi++) {
for(ll mex=0; mex<=N; mex++) {
if (!opSet[mi].count(mex)) {
cout << mex << endl;
break;
}
}
}
}
void solve3() {
ll N, M; cin >> N >> M;
vector<set<ll>> opSet(M+1); // opSet[i] := i回目の操作後の存在する[0,N]までの整数
for(ll i=1; i<=N; i++) {
ll a; cin >> a;
// はじめて 0 <= a <= N となる操作回数の開始地点を探す
ll sj;
if ((a+i)>=0 && (a+i)<=N) {
sj = 1;
}
else if ((a+i) < 0){
sj = 1 + intceil(-(a+i), i);
}
else {
continue;
}
// j回目の操作後の整数をopSetに入れていく
a += sj*i;
for(ll j=sj; j<=M; j++) {
if (a > N) break;
opSet[j].insert(a);
a += i;
}
}
// 出力 O(NM)な感じだがopSet[mi]はスカスカ
for(ll mi=1; mi<=M; mi++) {
for(ll mex=0; mex<=N; mex++) {
if (!opSet[mi].count(mex)) {
cout << mex << endl;
break;
}
}
}
}
int main() {
// solve();
// solve2();
solve3();
return 0;
} | [
"taketakeyyy@gmail.com"
] | taketakeyyy@gmail.com |
05fcfb6e43f4bfd920027d73e74388d65325418c | f9a0c4ac2e3c303670f0d277bedfaaf27cb2b120 | /ee569/FMeasure.cpp | b088deeae6861132745fbd646e6c76846b1c0be7 | [] | no_license | gbudiman/ee569 | d0fdbd4e0e7b01a02ad966b5eb9615740ca6a6d5 | fefe9770121ac2dfbfdcd6cb39193d20b5505f33 | refs/heads/master | 2021-05-01T06:56:29.068732 | 2016-11-04T23:50:41 | 2016-11-04T23:50:41 | 66,734,259 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,453 | cpp | //
// FMeasure.cpp
// ee569
//
// Created by Gloria Budiman on 10/17/16.
// Finalized on 10/31/16
// gbudiman@usc.edu 6528-1836-50
// Copyright © 2016 gbudiman. All rights reserved.
//
#include "FMeasure.hpp"
FMeasure::FMeasure(Picture _base) {
base = _base;
dim_x = _base.get_dim_x();
dim_y = _base.get_dim_y();
result = Picture("", dim_x, dim_y, COLOR_RGB);
}
void FMeasure::compare_against(Picture _other) {
int false_positive, false_negative, true_positive, true_negative;
result.compare_f_measure(base, _other, true_positive, true_negative, false_negative, false_positive);
printf("%5.1f%% %5.1f%% %5.1f%% %5.1f%%\n", f_float(true_positive), f_float(true_negative), f_float(false_positive), f_float(false_negative));
printf(" Precision: %5.2f | Recall: %5.2f\n", f_precision(true_positive, false_positive), f_recall(true_positive, false_negative));
printf(" F: %5.2f\n", f_compute(true_positive, true_negative, false_positive, false_negative));
}
float FMeasure::f_float(int x) {
return (float) x * 100 / (float) (dim_x * dim_y);
}
float FMeasure::f_compute(int tp, int tn, int fp, int fn) {
float precision = f_precision(tp, fp);
float recall = f_recall(tp, fn);
return 2 * precision * recall / (precision + recall);
}
float FMeasure::f_precision(int tp, int fp) {
return (float) tp / (float) (tp + fp);
}
float FMeasure::f_recall(int tp, int fn) {
return (float) tp / (float) (tp + fn);
} | [
"wahyu.g@gmail.com"
] | wahyu.g@gmail.com |
91dc570a73bd2dcc5e54d1b07764051c68e8ad1f | 0b2e6d1c1ae0ebc4fe0dfb3c5ff46720fad8b22a | /Kernel/VM/MemoryManager.h | 3413e57945e4a047bef250bec4186f5e7fa64abb | [
"BSD-2-Clause"
] | permissive | vger92/serenity | b207e040eb1b735578c9d35276e5e5cd608212f5 | e83afe228a424fa096586bf4528cf859ea5b9965 | refs/heads/master | 2020-05-30T15:55:49.704687 | 2019-06-02T10:40:45 | 2019-06-02T10:40:45 | 189,833,848 | 0 | 0 | BSD-2-Clause | 2019-06-02T10:39:26 | 2019-06-02T10:39:26 | null | UTF-8 | C++ | false | false | 6,999 | h | #pragma once
#include "i386.h"
#include <AK/AKString.h>
#include <AK/Badge.h>
#include <AK/Bitmap.h>
#include <AK/ByteBuffer.h>
#include <AK/HashTable.h>
#include <AK/RetainPtr.h>
#include <AK/Retainable.h>
#include <AK/Types.h>
#include <AK/Vector.h>
#include <AK/Weakable.h>
#include <Kernel/FileSystem/InodeIdentifier.h>
#include <Kernel/LinearAddress.h>
#include <Kernel/VM/PhysicalPage.h>
#include <Kernel/VM/Region.h>
#include <Kernel/VM/VMObject.h>
#define PAGE_ROUND_UP(x) ((((dword)(x)) + PAGE_SIZE - 1) & (~(PAGE_SIZE - 1)))
class SynthFSInode;
enum class PageFaultResponse
{
ShouldCrash,
Continue,
};
#define MM MemoryManager::the()
class MemoryManager {
AK_MAKE_ETERNAL
friend class PageDirectory;
friend class PhysicalPage;
friend class Region;
friend class VMObject;
friend ByteBuffer procfs$mm(InodeIdentifier);
friend ByteBuffer procfs$memstat(InodeIdentifier);
public:
[[gnu::pure]] static MemoryManager& the();
static void initialize();
PageFaultResponse handle_page_fault(const PageFault&);
bool map_region(Process&, Region&);
bool unmap_region(Region&);
void populate_page_directory(PageDirectory&);
void enter_process_paging_scope(Process&);
bool validate_user_read(const Process&, LinearAddress) const;
bool validate_user_write(const Process&, LinearAddress) const;
enum class ShouldZeroFill
{
No,
Yes
};
RetainPtr<PhysicalPage> allocate_physical_page(ShouldZeroFill);
RetainPtr<PhysicalPage> allocate_supervisor_physical_page();
void remap_region(PageDirectory&, Region&);
size_t ram_size() const { return m_ram_size; }
int user_physical_pages_in_existence() const { return s_user_physical_pages_in_existence; }
int super_physical_pages_in_existence() const { return s_super_physical_pages_in_existence; }
void map_for_kernel(LinearAddress, PhysicalAddress);
RetainPtr<Region> allocate_kernel_region(size_t, String&& name);
void map_region_at_address(PageDirectory&, Region&, LinearAddress, bool user_accessible);
private:
MemoryManager();
~MemoryManager();
void register_vmo(VMObject&);
void unregister_vmo(VMObject&);
void register_region(Region&);
void unregister_region(Region&);
void remap_region_page(Region&, unsigned page_index_in_region, bool user_allowed);
void initialize_paging();
void flush_entire_tlb();
void flush_tlb(LinearAddress);
RetainPtr<PhysicalPage> allocate_page_table(PageDirectory&, unsigned index);
void map_protected(LinearAddress, size_t length);
void create_identity_mapping(PageDirectory&, LinearAddress, size_t length);
void remove_identity_mapping(PageDirectory&, LinearAddress, size_t);
static Region* region_from_laddr(Process&, LinearAddress);
static const Region* region_from_laddr(const Process&, LinearAddress);
bool copy_on_write(Region&, unsigned page_index_in_region);
bool page_in_from_inode(Region&, unsigned page_index_in_region);
bool zero_page(Region& region, unsigned page_index_in_region);
byte* quickmap_page(PhysicalPage&);
void unquickmap_page();
PageDirectory& kernel_page_directory() { return *m_kernel_page_directory; }
struct PageDirectoryEntry {
explicit PageDirectoryEntry(dword* pde)
: m_pde(pde)
{
}
dword* page_table_base() { return reinterpret_cast<dword*>(raw() & 0xfffff000u); }
void set_page_table_base(dword value)
{
*m_pde &= 0xfff;
*m_pde |= value & 0xfffff000;
}
dword raw() const { return *m_pde; }
dword* ptr() { return m_pde; }
enum Flags
{
Present = 1 << 0,
ReadWrite = 1 << 1,
UserSupervisor = 1 << 2,
WriteThrough = 1 << 3,
CacheDisabled = 1 << 4,
};
bool is_present() const { return raw() & Present; }
void set_present(bool b) { set_bit(Present, b); }
bool is_user_allowed() const { return raw() & UserSupervisor; }
void set_user_allowed(bool b) { set_bit(UserSupervisor, b); }
bool is_writable() const { return raw() & ReadWrite; }
void set_writable(bool b) { set_bit(ReadWrite, b); }
bool is_write_through() const { return raw() & WriteThrough; }
void set_write_through(bool b) { set_bit(WriteThrough, b); }
bool is_cache_disabled() const { return raw() & CacheDisabled; }
void set_cache_disabled(bool b) { set_bit(CacheDisabled, b); }
void set_bit(byte bit, bool value)
{
if (value)
*m_pde |= bit;
else
*m_pde &= ~bit;
}
dword* m_pde;
};
struct PageTableEntry {
explicit PageTableEntry(dword* pte)
: m_pte(pte)
{
}
dword* physical_page_base() { return reinterpret_cast<dword*>(raw() & 0xfffff000u); }
void set_physical_page_base(dword value)
{
*m_pte &= 0xfffu;
*m_pte |= value & 0xfffff000u;
}
dword raw() const { return *m_pte; }
dword* ptr() { return m_pte; }
enum Flags
{
Present = 1 << 0,
ReadWrite = 1 << 1,
UserSupervisor = 1 << 2,
WriteThrough = 1 << 3,
CacheDisabled = 1 << 4,
};
bool is_present() const { return raw() & Present; }
void set_present(bool b) { set_bit(Present, b); }
bool is_user_allowed() const { return raw() & UserSupervisor; }
void set_user_allowed(bool b) { set_bit(UserSupervisor, b); }
bool is_writable() const { return raw() & ReadWrite; }
void set_writable(bool b) { set_bit(ReadWrite, b); }
bool is_write_through() const { return raw() & WriteThrough; }
void set_write_through(bool b) { set_bit(WriteThrough, b); }
bool is_cache_disabled() const { return raw() & CacheDisabled; }
void set_cache_disabled(bool b) { set_bit(CacheDisabled, b); }
void set_bit(byte bit, bool value)
{
if (value)
*m_pte |= bit;
else
*m_pte &= ~bit;
}
dword* m_pte;
};
static unsigned s_user_physical_pages_in_existence;
static unsigned s_super_physical_pages_in_existence;
PageTableEntry ensure_pte(PageDirectory&, LinearAddress);
RetainPtr<PageDirectory> m_kernel_page_directory;
dword* m_page_table_zero;
LinearAddress m_quickmap_addr;
Vector<Retained<PhysicalPage>> m_free_physical_pages;
Vector<Retained<PhysicalPage>> m_free_supervisor_physical_pages;
HashTable<VMObject*> m_vmos;
HashTable<Region*> m_user_regions;
HashTable<Region*> m_kernel_regions;
size_t m_ram_size { 0 };
bool m_quickmap_in_use { false };
};
struct ProcessPagingScope {
ProcessPagingScope(Process&);
~ProcessPagingScope();
};
| [
"awesomekling@gmail.com"
] | awesomekling@gmail.com |
7084a0453c28e2abe5ef78a248271f650c836bd5 | a08801a75064ee658a5ff5f1dd241eeab45f8f96 | /main.cpp | a8725b59ca6fcab3a95f366d5447002c19b0ac42 | [] | no_license | aripramuja/warehousing-system | 0865e0a663bd67c8b4c93ff717c8ef0477b5bbf3 | d97bb5b457c9e8eff584eb6bd2e68fe1b0bad4dc | refs/heads/main | 2023-04-08T11:54:33.312083 | 2021-04-14T15:27:30 | 2021-04-14T15:27:30 | 357,952,808 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 25,636 | cpp | #include <iostream>
#include <fstream>
#include <stdlib.h>
using namespace std;
/// Laporan max
void laporan_pendingin();
void laporan_kimia();
void laporan_lemari();
void menuLaporan();
/// DATA BARANG
void DataDingin();
void DataLemari ();
void DataChemist ();
void menu_DataBarang ();
///DATA TRANSAKSI PENDINGNIN
void penerimaan_AreaDingin();
void pengeluaran_AreaDingin();
void menuPendingin();
int Penghitung_SisaPendingin(int capacity);
void Laporan_AreaDingin();
string pembuat_kode(string tanggalmasuk,string kodelokasi);
void menuPendingin()
{
int a;
cout<<"\n\n\t\t\t\t\t\t<==================>";
cout<<"\n\n\t\t\t\t\t\t 1. Data keluar";
cout<<"\n\n\t\t\t\t\t\t 2. Data masuk";
cout<<"\n\n\t\t\t\t\t\t<==================>\n";
cout<<"\t\t\t\t\t\t\t>>>";cin >> a;
switch (a){
case 1: pengeluaran_AreaDingin();break;
case 2: penerimaan_AreaDingin();break;
}
menuPendingin();
}
void pengeluaran_AreaDingin()
{
int kuotaDingin=500;
ifstream keluarDingin;
int Jum_bar[100];
int i=0,jum;
string Nam_bar[100];
string kirim;
keluarDingin.open("Area_pendingin.txt");
while (!keluarDingin.eof()){
keluarDingin >> Nam_bar[i];
keluarDingin >> Jum_bar[i];
i++;
}
ifstream Code;
string TAnggal[1000];
int q=0;
Code.open("dinginkode.txt");
while(!Code.eof()){
Code>>TAnggal[q];
q++;
}
cout << "================Data Barang================\n";
cout <<"| No | Nama Barang |Kode Barang| Jumlah Barang |\n";
for (int j=0;j<i-1;j++){
cout <<" "<<j+1<<". "<< Nam_bar[j]<<" "<<TAnggal[j]<< " "<<Jum_bar[j]<<endl;
}
cout << "================>>>>><<<<<=================\n";
cout << "Nama Barang yang ingin dikirim : " ;cin >> kirim;
int temu;
bool tampung=false;
for (int g=0;g<i-1;g++){
if (kirim == Nam_bar[g]){
tampung=true;
temu = g;
}else{
cout <<"";
}
}
if (tampung==true){
cout << "Jumlah Barang yang ingin dikirim : " ;cin >> jum;
if(Jum_bar[temu]>=jum)
{
Jum_bar[temu]=Jum_bar[temu]-jum;
cout<<Jum_bar[temu];
}
else
{
cout << "jumlah barang tidak cukup"<<endl;
}
}
else
{
cout << "================================"<<endl;
cout << " Barang tidak ada!!!";
cout << "\n================================\n"<<endl;
system("pause");
system("cls");
menuPendingin();
}
ofstream Updatedingin;
Updatedingin.open("Area_pendingin.txt");
for (int j=0;j<i-1;j++){
Updatedingin<<Nam_bar[j]<<" "<<Jum_bar[j]<<endl;
}
system("cls");
string tanya;
cout << "================================"<<endl;
cout << "|Do you want to see the update?|"<<endl;
cout << "================================"<<endl;
cout << " |Y| |N| "<<endl;
cin >> tanya;
if (tanya=="Y"){
cout << "-----------Update Barang------------"<<endl;
cout <<"| No | Nama Barang |Kode Barang| Jumlah Barang |\n";
for (int j=0;j<i-1;j++){
cout <<" "<<j+1<<". "<< Nam_bar[j]<<" "<<TAnggal[j]<< " "<<Jum_bar[j]<<endl;
}
cout << "Kapasitas area pendingin yang kosong adalah "<<Penghitung_SisaPendingin(kuotaDingin)<<" dari "<<kuotaDingin<<endl;
}else
{
system("cls");
menuPendingin();
}
system("pause");
system("cls");
keluarDingin.close();
Code.close();
}
void penerimaan_AreaDingin()
{
ofstream dingin;
int jumlah_Barang,diminta;
string Nama_Barang,Tanggal[1000];
dingin.open("Area_pendingin.txt",ios::app);
cout << "Berapa jenis barang : " ;cin>> diminta;
for (int i=0;i<diminta;i++){
cout << "---- Barang ke - "<<i+1<< "----\n";
cout << "Nama Barang : " ;cin>>Nama_Barang;
cout << "Jumlah Barang : "; cin>>jumlah_Barang;
cout << "Tanggal dan Bulan Transaksi(tanggal,bulan) : "; cin>>Tanggal[i];
dingin << Nama_Barang<< " ";
dingin <<jumlah_Barang<<endl;
}
dingin.close();
ofstream dinginKode;
dinginKode.open("dinginkode.txt",ios::app);
for (int j=0;j<diminta;j++){
dinginKode<<pembuat_kode(Tanggal[j],"AP")<<endl;
}
dinginKode.close();
system("pause");
system("cls");
}
int Penghitung_SisaPendingin(int capacity)
{
ifstream rekareh;
string apa;
int jumlahBarang[1000];
int Total_barang=0;
int sisa;
rekareh.open("Area_pendingin.txt");
int i=0;
while (!rekareh.eof()){
rekareh >> apa;
rekareh >> jumlahBarang[i];
i++;
}
for (int j=0;j<i-1;j++){
Total_barang=Total_barang+jumlahBarang[j];
}
sisa=capacity-Total_barang;
return sisa;
rekareh.close();
}
string pembuat_kode(string tanggalmasuk,string kodelokasi)
{
string gabung;
gabung=kodelokasi+tanggalmasuk;
return gabung;
}
///DATA TRANSAKSI KIMIA
void penerimaan_AreaKimia();
void pengeluaran_AreaKimia();
void menuKimia();
int Penghitung_SisaKimia(int capacity);
void Laporan_AreaKimia();
string pembuat_kode(string tanggalmasuk,string kodelokasi);
///DATA LEMARI
void penerimaan_AreaLemari();
void pengeluaran_AreaLemari();
void menuLemari();
int Penghitung_SisaLemari(int capacity);
void Laporan_AreaLemari();
///LAPORAN
struct dataBarang
{
string Nambar;
int JumBar;
};
void judul(){
cout<<"\n\n\n\n\n\n";
cout<<"\t\t\t\t________________________________________________________"<<endl;
cout<<endl;
cout<<"\t\t\t\t\tWelcome to our system (SISTEM PERGUDANGAN)"<<endl;
cout<<"\t\t\t\t________________________________________________________"<<endl;
}
void menu_utama()
{
int menu;
cout<<"\n\n";
cout<<"\t\tMAIN MENU"<<endl;
cout<<"\t\t=========";
cout<<"\n\n\t\t1. Data Barang";
cout<<"\n\n\t\t2. Data Transaksi";
cout<<"\n\n\t\t3. Laporan";
cout<<"\n\n\t\t4. Lokasi penyimpanan";
cout<<"\n\n\n";
cout<<"masukan nomor : ";
}
void barang()
{
cout<<"\n\n\t1. Data Penyimpanan";
cout<<"\n\n\t2. Data barang";
// cout<<"\n\n\t3. UPDATE";
cout<<endl;
int menu_barang;
cin>>menu_barang;
switch (menu_barang)
{
case 1:
{
string nama_barang,jenis_barang,lokasi_barang;
ofstream penyimpanan_barang;
penyimpanan_barang.open("barang.txt",ios::app);
cout<<"masukan nama barang: ";
cin>>nama_barang;
penyimpanan_barang<<nama_barang+"\n";
cout<<"masukan jenis barang: ";
cin>>jenis_barang;
penyimpanan_barang<<jenis_barang+"\n";
cout<<"lokasi barang: ";
cin>>lokasi_barang;
penyimpanan_barang<<lokasi_barang+"\n";
penyimpanan_barang.close();
break;
}
case 2:
{
char data_barang [1000];
fstream penyimpanan_barang;
penyimpanan_barang.open("barang.txt");
int counter = 0;
// cout<<"Nama |"<<"Jenis |"<<"Lokasi |\n";
while (!penyimpanan_barang.eof())
{
if(counter!=3){
penyimpanan_barang.getline(data_barang,1000);
cout<<data_barang<<""<< " "; //"|";
counter++;
}else{
counter = 0;
cout<<endl;
}
}
penyimpanan_barang.close();
break;
}
}
}
void transaksi()
{
cout<<"\n\n\t1. Area pendingin";
cout<<"\n\n\t2. Rak dan lemari";
cout<<"\n\n\t3. Area kimia";
cout<<"\n\n\t4. kembali";
cout<<"\n\n\n\t Masukan pilihan : ";
}
void laporan()
{
cout<<"\n\n\t1. Barang terbanyak";
}
void lokasipenyimpanan()
{
cout<<"\n\n\t1. Area pendingin";
cout<<"\n\n\t2. Rak dan lemari";
cout<<"\n\n\t3. Area bahan kimia";
}
int main()
{
string nama, nim;
int menu;
int menu_trans;
int menu_bar;
judul();
cout<<"\n\n";
cout<<"\t\t\t\t\tName : ";
cin>>nama;
cout<<"\t\t\t\t\tNim : ";
cin>>nim;
//
// if (nama!="ari" && nim!="105218000")
// {
// system("cls");
// judul();
// cout<<"\n\n";
// cout<<"\t\t\t\t\tName : ";
// cin>>nama;
// cout<<"\t\t\t\t\tNim : ";
// cin>>nim;
// }
//
// system("cls");
menu_utama();
cin>>menu;
if (menu==1)
{
system("cls");
menu_DataBarang();
system("pause");
system("cls");
// main();
}
if (menu==2)
{
system("cls");
transaksi();
cin>>menu_trans;
if(menu_trans==4)
{
system("cls");
menu_utama();
cin>>menu;
}
if (menu_trans==1)
{
system("cls");
menuPendingin();
}
if (menu_trans==3)
{
system("cls");
menuKimia();
}
if (menu_trans==2)
{
system("cls");
menuLemari();
}
system("pause");
system("cls");
// main();
}
if (menu==3)
{
system("cls");
menuLaporan();
system("pause");
system("cls");
// main();
}
if (menu==4)
{
system("cls");
lokasipenyimpanan();
cout<<endl<<"\n\n";
cout << "cek kapasitaas tersisa:\n";
cout<<"masukan pilihan: ";
cin>>menu;
switch(menu)
{
case 1:
cout << "Sisa ruang yang dapat diisi : "<<Penghitung_SisaPendingin(500)<<endl;break;
case 2:
cout << "Sisa ruang yang dapat diisi : "<<Penghitung_SisaLemari(500)<<endl;break;
case 3:
cout << "Sisa ruang yang dapat diisi : "<<Penghitung_SisaKimia(500)<<endl;break;
default : cout <<"\n";
}
system("pause");
system("cls");
// main();
}
}
///DATA BARANG
void DataDingin()
{
ifstream dataDingin;
int SumBarang[100];
int i=0,sum;
string NameBarang[100];
string send;
dataDingin.open("Data_pendingin.txt");
while (!dataDingin.eof()){
dataDingin >> NameBarang[i];
dataDingin >> SumBarang[i];
i++;
}
ifstream dataKodeDingin;
string gal[1000];
int gr=0;
dataKodeDingin.open("DataKodeDingin.txt");
while (!dataKodeDingin.eof()){
dataKodeDingin >> gal[gr];
gr++;
}
cout << "==================Data Barang==================\n";
cout <<"| No | Nama Barang |Kode Barang| Jumlah Barang |\n";
for (int j=0;j<-1;j++){
cout <<" "<<j+1<<". "<< NameBarang[j] <<" "<<gal[j]<< " "<<SumBarang[j]<<endl;
}
cout << "==================>>>>><<<<<===================\n";
dataDingin.close();
dataKodeDingin.close();
}
void DataLemari ()
{
ifstream dataLemari;
int SumBarang[100];
int i=0,sum;
string NameBarang[100];
string send;
dataLemari.open("Data_lemari.txt");
while (!dataLemari.eof()){
dataLemari >> NameBarang[i];
dataLemari >> SumBarang[i];
i++;
}
ifstream dataKodeLemari;
string gal[1000];
int gr=0;
dataKodeLemari.open("DataKodeLemari.txt");
while (!dataKodeLemari.eof()){
dataKodeLemari >> gal[gr];
gr++;
}
cout << "==================Data Barang==================\n";
cout <<"| No | Nama Barang |Kode Barang| Jumlah Barang |\n";
for (int j=0;j<i-1;j++){
cout <<" "<<j+1<<". "<< NameBarang[j] <<" "<<gal[j]<< " "<<SumBarang[j]<<endl;
}
cout << "==================>>>>><<<<<===================\n";
dataLemari.close();
dataKodeLemari.close();
}
void DataChemist ()
{
ifstream dataChemist;
int SumBarang[100];
int i=0,sum;
string NameBarang[100];
string send;
dataChemist.open("Data_chemist.txt");
while (!dataChemist.eof()){
dataChemist >> NameBarang[i];
dataChemist >> SumBarang[i];
i++;
}
ifstream dataKodeChemist;
string gal[1000];
int gr=0;
dataKodeChemist.open("DataKodeChemist.txt");
while (!dataKodeChemist.eof()){
dataKodeChemist >> gal[gr];
gr++;
}
cout << "==================Data Barang==================\n";
cout <<"| No | Nama Barang |Kode Barang| Jumlah Barang |\n";
for (int j=0;j<i-1;j++){
cout <<" "<<j+1<<". "<< NameBarang[j] <<" "<<gal[j]<< " "<<SumBarang[j]<<endl;
}
cout << "==================>>>>><<<<<===================\n";
dataChemist.close();
dataKodeChemist.close();
}
void menu_DataBarang ()
{
int kitaSemua;
cout << "============================================================= \n";
cout << "Berikut Adalah Lokasi Penyimpanan Barang Yang Ada : \n";
cout << "1. Data Area Lemari dan Rak \n";
cout << "2. Data Area Kimia \n";
cout << "3. Data Area Pendingin \n";
cout << "_____________________________________________________________ \n";
cout << "Silahkan Pilih Lokasi Yang Ingin Anda Cek Terlebih Dahulu : ";
cin >> kitaSemua;
cout << "_____________________________________________________________ \n";
switch (kitaSemua)
{
case 1 : DataLemari();break;
case 2 : DataChemist();break;
case 3 : DataDingin();break;
default : menu_DataBarang();
}
}
///DATA KIMIA
void menuKimia()
{
int a;
cout<<"\n\n\t\t\t\t\t\t<==================>";
cout<<"\n\n\t\t\t\t\t\t 1. Data keluar";
cout<<"\n\n\t\t\t\t\t\t 2. Data masuk";
cout<<"\n\n\t\t\t\t\t\t<==================>\n";
cout<<"\t\t\t\t\t\t\t>>>";cin >> a;
switch (a){
case 1: pengeluaran_AreaKimia();break;
case 2: penerimaan_AreaKimia();break;
default : main();
}
main();
}
void pengeluaran_AreaKimia()
{
int kuotaDingin=500;
ifstream keluarDingin;
int Jum_bar[100];
int i=0,jum;
string Nam_bar[100];
string kirim;
keluarDingin.open("Data_chemist.txt");
while (!keluarDingin.eof()){
keluarDingin >> Nam_bar[i];
keluarDingin >> Jum_bar[i];
i++;
}
ifstream Code;
string TAnggal[1000];
int q=0;
Code.open("DataKodechemist.txt");
while(!Code.eof()){
Code>>TAnggal[q];
q++;
}
cout << "================Data Barang================\n";
cout <<"| No | Nama Barang |Kode Barang| Jumlah Barang |\n";
for (int j=0;j<i-1;j++){
cout <<" "<<j+1<<". "<< Nam_bar[j]<<" "<<TAnggal[j]<< " "<<Jum_bar[j]<<endl;
}
cout << "================>>>>><<<<<=================\n";
cout << "Nama Barang yang ingin dikirim : " ;cin >> kirim;
int temu;
bool tampung=false;
for (int g=0;g<i-1;g++){
if (kirim == Nam_bar[g]){
tampung=true;
temu = g;
}else{
cout <<"";
}
}
if (tampung==true){
cout << "Jumlah Barang yang ingin dikirim : " ;cin >> jum;
if(Jum_bar[temu]>=jum)
{
Jum_bar[temu]=Jum_bar[temu]-jum;
}
else
{
cout << "jumlah barang tidak cukup"<<endl;
}
}
else
{
cout << "================================"<<endl;
cout << " Barang tidak ada!!!";
cout << "\n================================\n"<<endl;
system("pause");
system("cls");
menuKimia();
}
ofstream Updatedingin;
Updatedingin.open("Data_chemist.txt");
for (int j=0;j<i-1;j++){
Updatedingin<<Nam_bar[j]<<" "<<Jum_bar[j]<<endl;
}
system("cls");
string tanya;
cout << "================================"<<endl;
cout << "|Do you want to see the update?|"<<endl;
cout << "================================"<<endl;
cout << " |Y| |N| "<<endl;
cin >> tanya;
if (tanya=="Y"){
cout << "-----------Update Barang------------"<<endl;
cout <<"| No | Nama Barang |Kode Barang| Jumlah Barang |\n";
for (int j=0;j<i-1;j++){
cout <<" "<<j+1<<". "<< Nam_bar[j]<<" "<<TAnggal[j]<< " "<<Jum_bar[j]<<endl;
}
cout << "Kapasitas area pendingin yang kosong adalah "<<Penghitung_SisaKimia(kuotaDingin)<<" dari "<<kuotaDingin<<endl;
}else
{
system("cls");
main();
}
system("pause");
system("cls");
keluarDingin.close();
Code.close();
}
void penerimaan_AreaKimia()
{
ofstream dingin;
int jumlah_Barang,diminta;
string Nama_Barang,Tanggal[1000];
dingin.open("Data_chemist.txt",ios::app);
cout << "Berapa jenis barang : " ;cin>> diminta;
for (int i=0;i<diminta;i++){
cout << "---- Barang ke - "<<i+1<< "----\n";
cout << "Nama Barang : " ;cin>>Nama_Barang;
cout << "Jumlah Barang : "; cin>>jumlah_Barang;
cout << "Tanggal dan Bulan Transaksi(tanggal,bulan) : "; cin>>Tanggal[i];
dingin << Nama_Barang<< " ";
dingin <<jumlah_Barang<<endl;
}
dingin.close();
ofstream dinginKode;
dinginKode.open("DataKodechemist.txt",ios::app);
for (int j=0;j<diminta;j++){
dinginKode<<pembuat_kode(Tanggal[j],"AK")<<endl;
}
dinginKode.close();
system("pause");
system("cls");
}
int Penghitung_SisaKimia(int capacity)
{
ifstream rekareh;
string apa;
int jumlahBarang[1000];
int Total_barang=0;
int sisa;
rekareh.open("Data_chemist.txt");
int i=0;
while (!rekareh.eof()){
rekareh >> apa;
rekareh >> jumlahBarang[i];
i++;
}
for (int j=0;j<i-1;j++){
Total_barang=Total_barang+jumlahBarang[j];
}
sisa=capacity-Total_barang;
return sisa;
rekareh.close();
}
///DATA LEMARI
void menuLemari()
{
int a;
cout<<"\n\n\t\t\t\t\t\t<==================>";
cout<<"\n\n\t\t\t\t\t\t 1. Data keluar";
cout<<"\n\n\t\t\t\t\t\t 2. Data masuk";
cout<<"\n\n\t\t\t\t\t\t<==================>\n";
cout<<"\t\t\t\t\t\t\t>>>";cin >> a;
switch (a){
case 1: pengeluaran_AreaLemari();break;
case 2: penerimaan_AreaLemari();break;
default : main();
}
main();
}
void pengeluaran_AreaLemari()
{
int kuotaDingin=500;
ifstream keluarDingin;
int Jum_bar[100];
int i=0,jum;
string Nam_bar[100];
string kirim;
keluarDingin.open("Data_lemari.txt");
while (!keluarDingin.eof()){
keluarDingin >> Nam_bar[i];
keluarDingin >> Jum_bar[i];
i++;
}
ifstream Code;
string TAnggal[1000];
int q=0;
Code.open("DataKodelemari.txt");
while(!Code.eof()){
Code>>TAnggal[q];
q++;
}
cout << "================Data Barang================\n";
cout <<"| No | Nama Barang |Kode Barang| Jumlah Barang |\n";
for (int j=0;j<i-1;j++){
cout <<" "<<j+1<<". "<< Nam_bar[j]<<" "<<TAnggal[j]<< " "<<Jum_bar[j]<<endl;
}
cout << "================>>>>><<<<<=================\n";
cout << "Nama Barang yang ingin dikirim : " ;cin >> kirim;
int temu;
bool tampung=false;
for (int g=0;g<i-1;g++){
if (kirim == Nam_bar[g]){
tampung=true;
temu = g;
}else{
cout <<"";
}
}
if (tampung==true){
cout << "Jumlah Barang yang ingin dikirim : " ;cin >> jum;
if(Jum_bar[temu]>=jum)
{
Jum_bar[temu]=Jum_bar[temu]-jum;
}
else
{
cout << "jumlah barang tidak cukup"<<endl;
}
}
else
{
cout << "================================"<<endl;
cout << " Barang tidak ada!!!";
cout << "\n================================\n"<<endl;
system("pause");
system("cls");
menuLemari();
}
ofstream Updatedingin;
Updatedingin.open("Data_lemari.txt");
for (int j=0;j<i-1;j++){
Updatedingin<<Nam_bar[j]<<" "<<Jum_bar[j]<<endl;
}
system("cls");
string tanya;
cout << "================================"<<endl;
cout << "|Do you want to see the update?|"<<endl;
cout << "================================"<<endl;
cout << " |Y| |N| "<<endl;
cin >> tanya;
if (tanya=="Y"){
cout << "-----------Update Barang------------"<<endl;
cout <<"| No | Nama Barang |Kode Barang| Jumlah Barang |\n";
for (int j=0;j<i-1;j++){
cout <<" "<<j+1<<". "<< Nam_bar[j]<<" "<<TAnggal[j]<< " "<<Jum_bar[j]<<endl;
}
cout << "Kapasitas area pendingin yang kosong adalah "<<Penghitung_SisaLemari(kuotaDingin)<<" dari "<<kuotaDingin<<endl;
}else
{
system("cls");
main();
}
system("pause");
system("cls");
keluarDingin.close();
Code.close();
}
void penerimaan_AreaLemari()
{
ofstream dingin;
int jumlah_Barang,diminta;
string Nama_Barang,Tanggal[1000];
dingin.open("Data_lemari.txt",ios::app);
cout << "Berapa jenis barang : " ;cin>> diminta;
for (int i=0;i<diminta;i++){
cout << "---- Barang ke - "<<i+1<< "----\n";
cout << "Nama Barang : " ;cin>>Nama_Barang;
cout << "Jumlah Barang : "; cin>>jumlah_Barang;
cout << "Tanggal dan Bulan Transaksi(tanggal,bulan) : "; cin>>Tanggal[i];
dingin << Nama_Barang<< " ";
dingin <<jumlah_Barang<<endl;
}
dingin.close();
ofstream dinginKode;
dinginKode.open("DataKodelemari.txt",ios::app);
for (int j=0;j<diminta;j++){
dinginKode<<pembuat_kode(Tanggal[j],"AL")<<endl;
}
dinginKode.close();
system("pause");
system("cls");
}
int Penghitung_SisaLemari(int capacity)
{
ifstream rekareh;
string apa;
int jumlahBarang[1000];
int Total_barang=0;
int sisa;
rekareh.open("Data_lemari.txt");
int i=0;
while (!rekareh.eof()){
rekareh >> apa;
rekareh >> jumlahBarang[i];
i++;
}
for (int j=0;j<i-1;j++){
Total_barang=Total_barang+jumlahBarang[j];
}
sisa=capacity-Total_barang;
return sisa;
rekareh.close();
rekareh.open("Data_chemist.txt");
while (!rekareh.eof()){
rekareh >> apa;
rekareh >> jumlahBarang[i];
i++;
}
for (int j=0;j<i-1;j++){
Total_barang=Total_barang+jumlahBarang[j];
}
sisa=capacity-Total_barang;
return sisa;
rekareh.close();
}
void laporan_kimia(){
dataBarang DB[1000];
ifstream maximum;
int maxi,ngulang=0,index;
maximum.open("Data_chemist.txt");
while(!maximum.eof()){
maximum>>DB[ngulang].Nambar;
maximum>>DB[ngulang].JumBar;
ngulang++;
}
maxi=0;
for(int a=0;a<ngulang-1;a++){
if(DB[a].JumBar>=maxi){
maxi=DB[a].JumBar;
index=a;
}
}
cout << "Barang Terbanyaknya adalah "<<DB[index].Nambar<< " Sebanyak " << maxi<<" Item " <<endl;
maximum.close();
}
void laporan_pendingin(){
dataBarang DB[1000];
ifstream maximum;
int maxi,ngulang=0,index;
maximum.open("Data_pendingin.txt");
while(!maximum.eof()){
maximum>>DB[ngulang].Nambar;
maximum>>DB[ngulang].JumBar;
ngulang++;
}
maxi=0;
for(int a=0;a<ngulang-1;a++){
if(DB[a].JumBar>=maxi){
maxi=DB[a].JumBar;
index=a;
}
}
cout << "Barang Terbanyaknya adalah "<<DB[index].Nambar<< " Sebanyak " << maxi<<" Item " <<endl;
maximum.close();
}
void laporan_lemari(){
dataBarang DB[1000];
ifstream maximum;
int maxi,ngulang=0,index;
maximum.open("Data_lemari.txt");
while(!maximum.eof()){
maximum>>DB[ngulang].Nambar;
maximum>>DB[ngulang].JumBar;
ngulang++;
}
maxi=0;
for(int a=0;a<ngulang-1;a++){
if(DB[a].JumBar>=maxi){
maxi=DB[a].JumBar;
index=a;
}
}
cout << "Barang Terbanyaknya adalah "<<DB[index].Nambar<< " Sebanyak " << maxi<<" Item " <<endl;
maximum.close();
}
void menuLaporan(){
int w;
cout <<"================================\n";
cout <<"Pilih lokasi barang terbanyak\n";
cout << "================================\n";
cout << "1. Area kimia\n";
cout << "2. Area pendingin\n";
cout << "3. Area lemari\n";
cout << "==================\n";
cin >>w;
switch(w){
case 1:
laporan_kimia();break;
case 2:
laporan_pendingin();break;
case 3:
laporan_lemari();break;
default: menuLaporan();
}
}
| [
"105218009@student.universitaspertamina.ac.id"
] | 105218009@student.universitaspertamina.ac.id |
02d4e8feb321728110066055f580877ebf80f484 | 7cc47471cfd061d77409c4cbb9081f6de21e0fe7 | /Notes/Stack/htmlValidator/finish/html_fragment_validate.cpp | e0666b555491e92ccf2fa6e27be580b0439c65af | [] | no_license | kevinkuriachan/CSCE121 | 29e59e515ec51228a97e5d8536f793a990fd8730 | a6a988d6093e1225a50c12a893cde18e20cfe7cc | refs/heads/master | 2020-03-12T10:52:37.031613 | 2018-12-07T05:29:57 | 2018-12-07T05:29:57 | 130,583,210 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,434 | cpp | /* Basic HTML validator. Ok, a really, really basic one. */
#include <iostream>
#include <fstream>
#include <string>
#include <assert.h>
#include "stack.h"
int main(int argc, char *argv[])
{
stack_t *tag_stack = NULL;
if (argc != 2)
{
cerr << "Usage: " << argv[0] << " <input.html>" << endl;
return 1;
}
tag_stack = create_stack();
ifstream infile;
// Open the file
infile.open(argv[1], ios_base::in);
if (!infile) {
cerr << "Couldn't open '" << argv[1] << "', for reading." << endl;
//exit(1);
return 1;
}
bool document_valid = true;
string error_msg;
int line_count = 0;
string line;
size_t pos;
// Read in the file
while (getline(infile, line)) {
//cout << "Line #" << line_count << " '" << line << "'" << endl;
// Process line:
line_count++;
bool finished_line = false;
size_t pos, last_pos = 0;
while (!finished_line)
{
pos = line.find('<', last_pos);
if (pos != string::npos) {
// found opening, now find closing
size_t pos2 = line.find('>', pos);
if (pos2 != string::npos)
{
string tag = line.substr(pos, pos2 - pos + 1);
//cout << "Got tag '" << tag << "'" << endl;
if (tag[1] != '/')
{ // Opening tag
push_on_stack(tag_stack, tag);
}
else
{ // Closing tag
if (is_empty_stack(tag_stack))
{
error_msg = "Line #"+to_string(line_count)+": closing tag '" + tag + "' without opening one";
document_valid = false; // No closing!
break;
}
else
{
string top = pop_off_stack(tag_stack);
//cout << "Popped tag '" << top << "'" << endl;
string l = top.substr(1,top.size()-2);
//cout << "Popped trimmed to '" << l << "'" << endl;
string r = tag.substr(2,tag.size()-3);
//cout << "Compare with '" << r << "'" << endl;
if (r != l)
{
error_msg = "Line #"+to_string(line_count)+": '" + top + "' doesn't make sense with '" + tag + "'";
document_valid = false; // No closing!
break;
}
}
}
last_pos += pos2 + 1; // Move past this character
}
else
{
last_pos += line.size();
error_msg = "Line #"+to_string(line_count)+": no closing >";
document_valid = false; // No closing!
break;
}
}
else
{
// Check that there are no closing > without opening ones.
pos = line.find('>', last_pos);
if (pos != string::npos)
{
finished_line = true;
error_msg = "Line #"+to_string(line_count)+": has closing > without opening <";
document_valid = false; // No closing!
break;
}
else
finished_line = true;
}
}
if (!document_valid) break; // May as well quit now.
}
infile.close();
// Are there any reminants on the stack?
if ((document_valid) && (!is_empty_stack(tag_stack)))
{
error_msg = "Unclosed tags";
while (!is_empty_stack(tag_stack))
error_msg += " '" + pop_off_stack(tag_stack) + "'";
error_msg += " remain on the stack";
document_valid = false; // No closing!
}
if (document_valid)
{
cout << "File '" << argv[1] << "' passed my basic santity checks for valid HTML." << endl;
}
else
{
cout << "File '" << argv[1] << "' is not valid HTML." << endl;
cout << error_msg << endl;
}
destroy_stack(tag_stack);
return 0;
}
| [
"kevinkuriachan@compute.cs.tamu.edu"
] | kevinkuriachan@compute.cs.tamu.edu |
10737407f220c683515313bd229dda5455aa3905 | d7db098f4b1d1cd7d32952ebde8106e1f297252e | /AtCoder/ARC/040/B.cpp | 6dbc9f996121e4c8845183c2a113c01b8e1be77c | [] | no_license | monman53/online_judge | d1d3ce50f5a8a3364a259a78bb89980ce05b9419 | dec972d2b2b3922227d9eecaad607f1d9cc94434 | refs/heads/master | 2021-01-16T18:36:27.455888 | 2019-05-26T14:03:14 | 2019-05-26T14:03:14 | 25,679,069 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 420 | cpp | #include <iostream>
#include <algorithm>
using namespace std;
int main(){
int n, r;
string s;
int time=0;
cin >> n >> r;
cin >> s;
int start;
for(int i=n-1;i>=0;i--){
if(s[i] == '.'){
time+=max(0,i-r+1);
break;
}
}
for(int i=n-1;i>=0;){
if(s[i] == '.'){
i -= r;
time++;
}else if(s[i] == 'o'){
i--;
}
}
cout << time << '\n';
return 0;
}
| [
"tetsuro53@gmail.com"
] | tetsuro53@gmail.com |
cc5739cf68c7cfc582d2335a8f45542eaf1c5bba | 4e5fa5da1ffeb9d1a2e01c1145ab0bec9b424a2d | /Letters/Letters/Letters.cpp | b9a276a7662853ab6d1ac86cf600419790132645 | [] | no_license | PLaG-In/MLITA | a441bf670f500abcaa94cd04b60ec6fb5a621196 | 2e50290e4bfbae2a2a0eb7c8a8cadaad3ab0d9ab | refs/heads/master | 2021-05-30T09:40:57.852100 | 2016-01-21T17:38:11 | 2016-01-21T17:38:11 | null | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 1,448 | cpp | // Letters.cpp: определяет точку входа для консольного приложения.
//
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <map>
#include <algorithm>
using namespace std;
void CheckWords(map <string, int> &dict, const string &mainWord)
{
int counter, score = 0;
int pos;
std::vector<std::pair<string, int>> items;
string tempWord = mainWord;
/*sort(dict.begin(), dict.end());*/
for (auto it = dict.begin(); it != dict.end(); ++it)
{
string elem = it->first;
counter = 0;
tempWord = mainWord;
for (size_t i = 0; i < elem.length(); ++i)
{
pos = tempWord.find(elem[i]);
if (pos != -1)
{
counter++;
tempWord[pos] = '0';
}
else
{
counter = 0;
}
}
score += counter;
dict[elem] += counter;
}
ofstream fout("output.txt");
fout << score << endl;
for (auto it = dict.begin(); it != dict.end(); ++it)
{
if (it->second != 0){
items.push_back(pair<string, int>(it->first, it->second));
}
}
std::sort(items.begin(), items.end());
for (auto it = items.begin(); it != items.end(); ++it)
{
fout << it->first << endl;
}
}
int main(int argc, char* argv[])
{
ifstream fin("input.txt");
string mainWord, tempWord;
fin >> mainWord;
map <string, int> dict;
while (!fin.eof())
{
fin >> tempWord;
dict.insert(pair<string, int>(tempWord, 0));
}
CheckWords(dict, mainWord);
return 0;
}
| [
"vladimir.alt@inbox.ru"
] | vladimir.alt@inbox.ru |
572ff8e20e427eb2faa8404cd6a75ed44f53d57e | c18fb2aa33610daf4f241e1bd8d62c288030f699 | /MyProfessionalC++/c09_code/c09_code/WeatherPrediction/MyWeatherPrediction.cpp | 43fef67981b13e0de1e15f10aae11116d1048aa1 | [] | no_license | Chinkyu/CXXExercise | 73f4166bfd9fa69ad4bc5786ddd74fa11398b58f | ca493a82c4e872f8c50da3f2b4027ef4e4ecf814 | refs/heads/master | 2023-08-31T12:04:49.295552 | 2023-08-31T01:02:25 | 2023-08-31T01:02:25 | 72,819,670 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 1,324 | cpp | #include <iostream>
#include "MyWeatherPrediction.h"
using namespace std;
void MyWeatherPrediction::setCurrentTempCelsius(int inTemp)
{
int fahrenheitTemp = convertCelsiusToFahrenheit(inTemp);
setCurrentTempFahrenheit(fahrenheitTemp);
}
int MyWeatherPrediction::getTomorrowTempCelsius() const
{
int fahrenheitTemp = getTomorrowTempFahrenheit();
return convertFahrenheitToCelsius(fahrenheitTemp);
}
void MyWeatherPrediction::showResult() const
{
cout << "Tomorrow's temperature will be " <<
getTomorrowTempCelsius() << " degrees Celsius (" <<
getTomorrowTempFahrenheit() << " degrees Fahrenheit)" << endl;
cout << "The chance of rain is " << (getChanceOfRain() * 100) << " percent"
<< endl;
if (getChanceOfRain() > 0.5) {
cout << "Bring an umbrella!" << endl;
}
}
int MyWeatherPrediction::convertCelsiusToFahrenheit(int inCelsius)
{
return static_cast<int>((9.0 / 5.0) * inCelsius + 32);
}
int MyWeatherPrediction::convertFahrenheitToCelsius(int inFahrenheit)
{
return static_cast<int>((5.0 / 9.0) * (inFahrenheit - 32));
}
string MyWeatherPrediction::getTemperature() const
{
return WeatherPrediction::getTemperature() + "°F";
}
int main()
{
MyWeatherPrediction p;
p.setCurrentTempCelsius(33);
p.setPositionOfJupiter(80);
p.showResult();
cout << p.getTemperature() << endl;
return 0;
}
| [
"bamtori@hotmail.com"
] | bamtori@hotmail.com |
272adcb5ff68ac7642c544e9b073b84d7d65501e | 1c24264c0884b709a7943f30dd157d92168581d0 | /Programming_Principles_and_Practice_Using_C++/14_Graphics_Class_Design/Window.h | 78d468d39c88e3f51b12a16900e4b304facdb505 | [
"MIT"
] | permissive | KoaLaYT/Learn-Cpp | 56dbece554503ca2e0d1bea35ae4ddda3c03f236 | 0bfc98c3eca9c2fde5bff609c67d7e273fde5196 | refs/heads/master | 2020-12-22T13:08:02.582113 | 2020-10-26T02:33:24 | 2020-10-26T02:33:24 | 236,792,487 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,353 | h | #ifndef WINDOW_GUARD
#define WINDOW_GUARD 1
#include "Point.h"
#include "fltk.h"
#include "std_lib_facilities.h"
namespace Graph_lib {
class Shape; // "forward declare" Shape
class Widget;
class Window : public Fl_Window {
public:
Window(int w, int h, const string& title); // let the system pick the location
Window(Point xy, int w, int h, const string& title); // top left corner in xy
virtual ~Window() {}
int x_max() const { return w; }
int y_max() const { return h; }
void resize(int ww, int hh) {
w = ww, h = hh;
size(ww, hh);
}
void set_label(const string& s) { label(s.c_str()); }
void attach(Shape& s);
void attach(Widget& w);
void detach(Shape& s); // remove s from shapes
void detach(Widget& w); // remove w from window (deactivate callbacks)
void put_on_top(Shape& p); // put p on top of other shapes
protected:
void draw();
private:
vector<Shape*> shapes; // shapes attached to window
int w, h; // window size
void init();
};
int gui_main(); // invoke GUI library's main event loop
inline int x_max() { return Fl::w(); } // width of screen in pixels
inline int y_max() { return Fl::h(); } // height of screen in pixels
} // namespace Graph_lib
#endif
| [
"hytohyeah@outlook.com"
] | hytohyeah@outlook.com |
27ea713204f216324c15f633a5c574aa95ebee3e | d535109f8406a7c4cf8238bd03f1c584ad6464aa | /aliyun-api-pts/2015-08-01/src/ali_pts_get_tasks.cc | 3e43a981c66e1591b5a51edcff1f5f968d22f567 | [
"Apache-2.0"
] | permissive | bailehang/aliyun | 3cf08cb371e55fbff59fc3908e5c47c27b861af1 | ca80fb97ce2b4d10bfb5fd8252c730a995354646 | refs/heads/master | 2020-05-23T11:17:00.183793 | 2015-11-16T01:41:03 | 2015-11-16T01:41:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,713 | cc | #include <stdio.h>
#include "ali_api_core.h"
#include "ali_string_utils.h"
#include "ali_pts.h"
#include "json/value.h"
#include "json/reader.h"
using namespace aliyun;
namespace {
void Json2Type(const Json::Value& value, std::string* item);
void Json2Type(const Json::Value& value, PTSGetTasksResponseType* item);
template<typename T>
class Json2Array {
public:
Json2Array(const Json::Value& value, std::vector<T>* vec) {
if(!value.isArray()) {
return;
}
for(int i = 0; i < value.size(); i++) {
T val;
Json2Type(value[i], &val);
vec->push_back(val);
}
}
};
void Json2Type(const Json::Value& value, std::string* item) {
*item = value.asString();
}
void Json2Type(const Json::Value& value, PTSGetTasksResponseType* item) {
if(value.isMember("Tasks")) {
item->tasks = value["Tasks"].asString();
}
}
}
int PTS::GetTasks(const PTSGetTasksRequestType& req,
PTSGetTasksResponseType* response,
PTSErrorInfo* error_info) {
std::string str_response;
int status_code;
int ret = 0;
bool parse_success = false;
std::string secheme = this->use_tls_ ? "https" : "http";
AliRpcRequest* req_rpc = new AliRpcRequest(version_,
appid_,
secret_,
secheme + "://" + host_);
Json::Value val;
Json::Reader reader;
req_rpc->AddRequestQuery("Action","GetTasks");
if(!req.status.empty()) {
req_rpc->AddRequestQuery("Status", req.status);
}
if(!this->region_id_.empty()) {
req_rpc->AddRequestQuery("RegionId", this->region_id_);
}
if(req_rpc->CommitRequest() != 0) {
if(error_info) {
error_info->code = "connect to host failed";
}
ret = -1;
goto out;
}
status_code = req_rpc->WaitResponseHeaderComplete();
req_rpc->ReadResponseBody(str_response);
if(status_code > 0 && !str_response.empty()){
parse_success = reader.parse(str_response, val);
}
if(!parse_success) {
if(error_info) {
error_info->code = "parse response failed";
}
ret = -1;
goto out;
}
if(status_code!= 200 && error_info && parse_success) {
error_info->request_id = val.isMember("RequestId") ? val["RequestId"].asString(): "";
error_info->code = val.isMember("Code") ? val["Code"].asString(): "";
error_info->host_id = val.isMember("HostId") ? val["HostId"].asString(): "";
error_info->message = val.isMember("Message") ? val["Message"].asString(): "";
}
if(status_code== 200 && response) {
Json2Type(val, response);
}
ret = status_code;
out:
delete req_rpc;
return ret;
}
| [
"zcy421593@126.com"
] | zcy421593@126.com |
2a5012ad07fc50dfc116c9465cca18119a211893 | 914b2437727654ef663c9c9795715598597b8eba | /AncillaryDataEvent/TaggerModule.h | dc4093c59a9d8fa03979ebebc5f5631ed78a3f18 | [
"BSD-3-Clause"
] | permissive | fermi-lat/AncillaryDataEvent | 362ae7384513be6ea90cba5b00ffb880ba05cc5c | 4f8f9677971b36628b0949e3ccd8b708e4932c38 | refs/heads/master | 2022-02-17T03:07:33.552130 | 2019-08-27T17:26:54 | 2019-08-27T17:26:54 | 103,186,826 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 911 | h | #ifndef TAGGERMODULE_HH
#define TAGGERMODULE_HH
#include "TaggerLayer.h"
class TaggerModule
{
public:
TaggerModule(int moduleId);
~TaggerModule();
void processData();
void resetData();
int getId()
const {return m_moduleId;}
TaggerLayer *getLayer(int layerId)
const {return m_layers[layerId];}
TaggerChannel *getChannel(int layerId, int channelId)
const {return getLayer(layerId)->getChannel(channelId);}
double getXCrossingPosition() const {return m_xCrossingPosition;}
double getXCrossingError() const {return m_xCrossingError;}
double getYCrossingPosition() const {return m_yCrossingPosition;}
double getYCrossingError() const {return m_yCrossingError;}
private:
int m_moduleId;
TaggerLayer *m_layers[N_LAYERS_PER_MODULE];
double m_xCrossingPosition;
double m_xCrossingError;
double m_yCrossingPosition;
double m_yCrossingError;
};
#endif
| [
""
] | |
f71934402f18d768ba32d6db90931fdb24ef1b03 | 668c7477acc16c366196d8655dd554496c396a1b | /test/InstanceTests.cpp | 606959d27e571d446077c4c2341c971073d0c569 | [
"Unlicense"
] | permissive | lucasmpavelski/fsp-eval | 1eb9de961b168e761891c6f205972695b00db35b | 4a26be3af341324e9de106318f28c06027e3abd8 | refs/heads/master | 2023-02-09T14:53:33.208783 | 2021-01-01T14:00:12 | 2021-01-01T14:00:12 | 319,150,871 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,340 | cpp | #include <catch2/catch.hpp>
#include <vector>
#include <vector>
#include "../src/Instance.hpp"
using namespace fsp;
TEST_CASE("FSP data load from vector", "[fsp]")
{
const std::vector<unsigned> procTimes = { 1, 2, 3, 4, 5, 6 };
const int no_jobs = 2;
Instance instance(procTimes, no_jobs);
SECTION("number of machines is determined")
{
REQUIRE(instance.noMachines() == 3);
}
SECTION("vector is read by row")
{
REQUIRE(instance.pt(0, 1) == 2);
}
}
TEST_CASE("FSP data load from vector by jobs", "[fsp]")
{
const std::vector<unsigned> procTimes = { 1, 2, 3, 4, 5, 6 };
const int no_jobs = 2;
const bool jobsByMachines = true;
Instance instance(procTimes, no_jobs, jobsByMachines);
SECTION("vector is read by row")
{
REQUIRE(instance.pt(0, 1) == 4);
}
}
TEST_CASE("FSP data load from file", "[fsp]")
{
Instance instance("test/instance.txt");
SECTION("dimensions are correct")
{
REQUIRE(instance.noJobs() == 4);
REQUIRE(instance.noMachines() == 5);
}
SECTION("processing times are loaded")
{
REQUIRE(instance.pt(0, 0) == 5);
REQUIRE(instance.pt(0, 1) == 9);
}
}
TEST_CASE("FSP data can be compared with equals operator", "[fsp]")
{
Instance instance1("test/instance.txt");
Instance instance2("test/instance.txt");
REQUIRE(instance1 == instance2);
}
| [
"lmpavelski@yahoo.com.br"
] | lmpavelski@yahoo.com.br |
16361661eaf232450caac25332739b238997a416 | 85d9243f5c18af76e5c56987ed7ec477f75d66d6 | /src/Singleton/Singleton.hpp | efc243b34e107a23bb7dcbba873cee8627ba52f1 | [] | no_license | Mdopenfy/HeroicWar | 8b1a71c14cfeb49cd7915764a2410d06d88b62e2 | 0ef3f85b57234c56d7875bc62ad6a8c022132ca5 | refs/heads/master | 2021-01-01T17:05:37.611372 | 2013-03-04T20:06:50 | 2013-03-04T20:06:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,132 | hpp | /////////////////////////////////////////////////////////////////////////////
////
//// Singleton - modèle Singleton applicable à n'importe quelle classe.
////
///////////////////////////////////////////////////////////////////////////////
#include <cstddef>
template <typename T>
class Singleton
{
protected:
Singleton () { }
~Singleton () { }
public:
static T *getInstance ()
{
if (NULL == _singleton)
_singleton = new T;
return (static_cast<T*> (_singleton));
}
static void kill ()
{
if (NULL != _singleton)
{
delete _singleton;
_singleton = NULL;
}
}
static bool exist()
{
return (_singleton != NULL);
}
private:
static T *_singleton;
};
template <typename T>
T *Singleton<T>::_singleton = NULL;
| [
"meven.mognol@gmail.com"
] | meven.mognol@gmail.com |
09eb4ede6f8b9421e02a382c8415e6b57e5b6e80 | 16137a5967061c2f1d7d1ac5465949d9a343c3dc | /cpp_code/iostreams/07-ofstreams-pos.cc | 3d9931ad19e08a0f679010cc1ea2d5cbbff6b8f0 | [] | no_license | MIPT-ILab/cpp-lects-rus | 330f977b93f67771b118ad03ee7b38c3615deef3 | ba8412dbf4c8f3bee7c6344a89e0780ee1dd38f2 | refs/heads/master | 2022-07-28T07:36:59.831016 | 2022-07-20T08:34:26 | 2022-07-20T08:34:26 | 104,261,623 | 27 | 4 | null | 2021-02-04T21:39:23 | 2017-09-20T19:56:44 | TeX | UTF-8 | C++ | false | false | 282 | cc | #include <iostream>
#include <fstream>
int
main (void)
{
std::ofstream outfile("sample.tmp");
outfile << "This is an apple";
// auto pos = outfile.tellp();
// outfile.seekp (pos - static_cast<decltype(pos)>(7));
outfile.seekp (-7, std::ios::cur);
outfile << " sam";
}
| [
"konstantin.vladimirov@gmail.com"
] | konstantin.vladimirov@gmail.com |
d85c02212a408a89e2bcccae450d8cbacfc94d17 | 9cd87733a1958baa0e5c9fdee5e78f05f0ef7d36 | /kdtree2.cpp | 391296a65eb24b7ddc31f5a9366035c39cbbe923 | [] | no_license | brantr/shock-tracking | 4f754b2f3554486e9748f5a3278128b2d210ab32 | 60dab0327f07da2787b59809544b8cbb79c8ace1 | refs/heads/master | 2021-01-19T16:43:08.587659 | 2017-04-14T16:35:49 | 2017-04-14T16:35:49 | 88,284,529 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 25,212 | cpp |
//
// (c) Matthew B. Kennel, Institute for Nonlinear Science, UCSD (2004)
//
// Licensed under the Academic Free License version 1.1 found in file LICENSE
// with additional provisions in that same file.
// NB:license included in comments at the end of this file
#include "kdtree2.hpp"
#include <algorithm>
#include <iostream>
#include <stdio.h>
// utility
inline float squared(const float x) {
return(x*x);
}
inline void swap(int& a, int&b) {
int tmp;
tmp = a;
a = b;
b = tmp;
}
inline void swap(float& a, float&b) {
float tmp;
tmp = a;
a = b;
b = tmp;
}
//
// KDTREE2_RESULT implementation
//
inline bool operator<(const kdtree2_result& e1, const kdtree2_result& e2) {
return (e1.dis < e2.dis);
}
//
// KDTREE2_RESULT_VECTOR implementation
//
float kdtree2_result_vector::max_value() {
return( (*begin()).dis ); // very first element
}
vector<kdtree2_result>::iterator kdtree2_result_vector::lower_bound (const kdtree2_result& value)
{
vector<kdtree2_result>::iterator it;
vector<kdtree2_result>::iterator first = begin();
vector<kdtree2_result>::iterator last = end();
int count, step;
count = distance(first,last);
while(count>0)
{
it = first; step = count/2; advance(it,step);
//printf("*it %e value %e\n",(*it).dis,value.dis);
//if(*it<value)
if((*it).dis<value.dis)
{ first=++it; count-=step+1; }
else count=step;
}
return first;
}
void kdtree2_result_vector::push_element_and_heapify(kdtree2_result& e) {
push_back(e); // what a vector does.
push_heap( begin(), end() ); // and now heapify it, with the new elt.
}
float kdtree2_result_vector::replace_maxpri_elt_return_new_maxpri(kdtree2_result& e) {
// remove the maximum priority element on the queue and replace it
// with 'e', and return its priority.
//
// here, it means replacing the first element [0] with e, and re heapifying.
pop_heap( begin(), end() );
pop_back();
push_back(e); // insert new
push_heap(begin(), end() ); // and heapify.
return( (*this)[0].dis );
}
//
// KDTREE2 implementation
//
// constructor
kdtree2::kdtree2(kdtree2_array& data_in,bool rearrange_in,int dim_in)
: the_data(data_in),
N ( data_in.shape()[0] ),
dim( data_in.shape()[1] ),
sort_results(true),
rearrange(rearrange_in),
root(NULL),
data(NULL),
ind(N)
{
//
// initialize the constant references using this unusual C++
// feature.
//
if (dim_in > 0)
dim = dim_in;
build_tree();
//cout<<"Tree built.\n";
if (rearrange) {
// if we have a rearranged tree.
// allocate the memory for it.
//printf("rearranging\n");
rearranged_data.resize( extents[N][dim] );
// permute the data for it.
for (int i=0; i<N; i++) {
for (int j=0; j<dim; j++) {
rearranged_data[i][j] = the_data[ind[i]][j];
// wouldn't F90 be nice here?
}
}
data = &rearranged_data;
} else {
data = &the_data;
}
}
// destructor
kdtree2::~kdtree2() {
delete root;
}
// building routines
void kdtree2::build_tree() {
for (int i=0; i<N; i++) ind[i] = i;
root = build_tree_for_range(0,N-1,NULL);
}
kdtree2_node* kdtree2::build_tree_for_range(int l, int u, kdtree2_node* parent) {
// recursive function to build
kdtree2_node* node = new kdtree2_node(dim);
// the newly created node.
if (u<l) {
return(NULL); // no data in this node.
}
if ((u-l) <= bucketsize) {
// create a terminal node.
// always compute true bounding box for terminal node.
for (int i=0;i<dim;i++) {
spread_in_coordinate(i,l,u,node->box[i]);
}
node->cut_dim = 0;
node->cut_val = 0.0;
node->l = l;
node->u = u;
node->left = node->right = NULL;
} else {
//
// Compute an APPROXIMATE bounding box for this node.
// if parent == NULL, then this is the root node, and
// we compute for all dimensions.
// Otherwise, we copy the bounding box from the parent for
// all coordinates except for the parent's cut dimension.
// That, we recompute ourself.
//
int c = -1;
float maxspread = 0.0;
int m;
for (int i=0;i<dim;i++) {
if ((parent == NULL) || (parent->cut_dim == i)) {
spread_in_coordinate(i,l,u,node->box[i]);
} else {
node->box[i] = parent->box[i];
}
float spread = node->box[i].upper - node->box[i].lower;
if (spread>maxspread) {
maxspread = spread;
c=i;
}
}
//
// now, c is the identity of which coordinate has the greatest spread
//
if (false) {
m = (l+u)/2;
select_on_coordinate(c,m,l,u);
} else {
float sum;
float average;
if (true) {
sum = 0.0;
for (int k=l; k <= u; k++) {
sum += the_data[ind[k]][c];
}
average = sum / static_cast<float> (u-l+1);
} else {
// average of top and bottom nodes.
average = (node->box[c].upper + node->box[c].lower)*0.5;
}
m = select_on_coordinate_value(c,average,l,u);
}
// move the indices around to cut on dim 'c'.
node->cut_dim=c;
node->l = l;
node->u = u;
node->left = build_tree_for_range(l,m,node);
node->right = build_tree_for_range(m+1,u,node);
if (node->right == NULL) {
for (int i=0; i<dim; i++)
node->box[i] = node->left->box[i];
node->cut_val = node->left->box[c].upper;
node->cut_val_left = node->cut_val_right = node->cut_val;
} else if (node->left == NULL) {
for (int i=0; i<dim; i++)
node->box[i] = node->right->box[i];
node->cut_val = node->right->box[c].upper;
node->cut_val_left = node->cut_val_right = node->cut_val;
} else {
node->cut_val_right = node->right->box[c].lower;
node->cut_val_left = node->left->box[c].upper;
node->cut_val = (node->cut_val_left + node->cut_val_right) / 2.0;
//
// now recompute true bounding box as union of subtree boxes.
// This is now faster having built the tree, being logarithmic in
// N, not linear as would be from naive method.
//
for (int i=0; i<dim; i++) {
node->box[i].upper = max(node->left->box[i].upper,
node->right->box[i].upper);
node->box[i].lower = min(node->left->box[i].lower,
node->right->box[i].lower);
}
}
}
return(node);
}
void kdtree2:: spread_in_coordinate(int c, int l, int u, interval& interv)
{
// return the minimum and maximum of the indexed data between l and u in
// smin_out and smax_out.
float smin, smax;
float lmin, lmax;
int i;
smin = the_data[ind[l]][c];
smax = smin;
// process two at a time.
for (i=l+2; i<= u; i+=2) {
lmin = the_data[ind[i-1]] [c];
lmax = the_data[ind[i] ] [c];
if (lmin > lmax) {
swap(lmin,lmax);
// float t = lmin;
// lmin = lmax;
// lmax = t;
}
if (smin > lmin) smin = lmin;
if (smax <lmax) smax = lmax;
}
// is there one more element?
if (i == u+1) {
float last = the_data[ind[u]] [c];
if (smin>last) smin = last;
if (smax<last) smax = last;
}
interv.lower = smin;
interv.upper = smax;
// printf("Spread in coordinate %d=[%f,%f]\n",c,smin,smax);
}
void kdtree2::select_on_coordinate(int c, int k, int l, int u) {
//
// Move indices in ind[l..u] so that the elements in [l .. k]
// are less than the [k+1..u] elmeents, viewed across dimension 'c'.
//
while (l < u) {
int t = ind[l];
int m = l;
for (int i=l+1; i<=u; i++) {
if ( the_data[ ind[i] ] [c] < the_data[t][c]) {
m++;
swap(ind[i],ind[m]);
}
} // for i
swap(ind[l],ind[m]);
if (m <= k) l = m+1;
if (m >= k) u = m-1;
} // while loop
}
int kdtree2::select_on_coordinate_value(int c, float alpha, int l, int u) {
//
// Move indices in ind[l..u] so that the elements in [l .. return]
// are <= alpha, and hence are less than the [return+1..u]
// elmeents, viewed across dimension 'c'.
//
int lb = l, ub = u;
while (lb < ub) {
if (the_data[ind[lb]][c] <= alpha) {
lb++; // good where it is.
} else {
swap(ind[lb],ind[ub]);
ub--;
}
}
// here ub=lb
if (the_data[ind[lb]][c] <= alpha)
return(lb);
else
return(lb-1);
}
// void kdtree2::dump_data() {
// int upper1, upper2;
// upper1 = N;
// upper2 = dim;
// printf("Rearrange=%d\n",rearrange);
// printf("N=%d, dim=%d\n", upper1, upper2);
// for (int i=0; i<upper1; i++) {
// printf("the_data[%d][*]=",i);
// for (int j=0; j<upper2; j++)
// printf("%f,",the_data[i][j]);
// printf("\n");
// }
// for (int i=0; i<upper1; i++)
// printf("Indexes[%d]=%d\n",i,ind[i]);
// for (int i=0; i<upper1; i++) {
// printf("data[%d][*]=",i);
// for (int j=0; j<upper2; j++)
// printf("%f,",(*data)[i][j]);
// printf("\n");
// }
// }
//
// search record substructure
//
// one of these is created for each search.
// this holds useful information to be used
// during the search
static const float infinity = 1.0e38;
class searchrecord {
private:
friend class kdtree2;
friend class kdtree2_node;
vector<float>& qv;
int dim;
bool rearrange;
unsigned int nn; // , nfound;
float ballsize;
int centeridx, correltime;
kdtree2_result_vector& result; // results
const kdtree2_array* data;
const vector<int>& ind;
// constructor
public:
searchrecord(vector<float>& qv_in, kdtree2& tree_in,
kdtree2_result_vector& result_in) :
qv(qv_in),
result(result_in),
data(tree_in.data),
ind(tree_in.ind)
{
dim = tree_in.dim;
rearrange = tree_in.rearrange;
ballsize = infinity;
nn = 0;
};
};
void kdtree2::n_nearest_brute_force(vector<float>& qv, int nn, kdtree2_result_vector& result) {
result.clear();
for (int i=0; i<N; i++) {
float dis = 0.0;
kdtree2_result e;
for (int j=0; j<dim; j++) {
dis += squared( the_data[i][j] - qv[j]);
}
e.dis = dis;
e.idx = i;
result.push_back(e);
}
sort(result.begin(), result.end() );
}
void kdtree2::n_nearest(vector<float>& qv, int nn, kdtree2_result_vector& result) {
searchrecord sr(qv,*this,result);
vector<float> vdiff(dim,0.0);
result.clear();
sr.centeridx = -1;
sr.correltime = 0;
sr.nn = nn;
root->search(sr);
if (sort_results) sort(result.begin(), result.end());
}
// search for n nearest to a given query vector 'qv'.
void kdtree2::n_nearest_around_point(int idxin, int correltime, int nn,
kdtree2_result_vector& result) {
vector<float> qv(dim); // query vector
result.clear();
for (int i=0; i<dim; i++) {
qv[i] = the_data[idxin][i];
}
// copy the query vector.
{
searchrecord sr(qv, *this, result);
// construct the search record.
sr.centeridx = idxin;
sr.correltime = correltime;
sr.nn = nn;
root->search(sr);
}
if (sort_results) sort(result.begin(), result.end());
}
void kdtree2::r_nearest(vector<float>& qv, float r2, kdtree2_result_vector& result) {
// search for all within a ball of a certain radius
searchrecord sr(qv,*this,result);
vector<float> vdiff(dim,0.0);
result.clear();
sr.centeridx = -1;
sr.correltime = 0;
sr.nn = 0;
sr.ballsize = r2;
root->search(sr);
if (sort_results) sort(result.begin(), result.end());
}
int kdtree2::r_count(vector<float>& qv, float r2) {
// search for all within a ball of a certain radius
{
kdtree2_result_vector result;
searchrecord sr(qv,*this,result);
sr.centeridx = -1;
sr.correltime = 0;
sr.nn = 0;
sr.ballsize = r2;
root->search(sr);
return(result.size());
}
}
void kdtree2::r_nearest_around_point(int idxin, int correltime, float r2,
kdtree2_result_vector& result) {
vector<float> qv(dim); // query vector
result.clear();
for (int i=0; i<dim; i++) {
qv[i] = the_data[idxin][i];
}
// copy the query vector.
{
searchrecord sr(qv, *this, result);
// construct the search record.
sr.centeridx = idxin;
sr.correltime = correltime;
sr.ballsize = r2;
sr.nn = 0;
root->search(sr);
}
if (sort_results) sort(result.begin(), result.end());
}
int kdtree2::r_count_around_point(int idxin, int correltime, float r2)
{
vector<float> qv(dim); // query vector
for (int i=0; i<dim; i++) {
qv[i] = the_data[idxin][i];
}
// copy the query vector.
{
kdtree2_result_vector result;
searchrecord sr(qv, *this, result);
// construct the search record.
sr.centeridx = idxin;
sr.correltime = correltime;
sr.ballsize = r2;
sr.nn = 0;
root->search(sr);
return(result.size());
}
}
//
// KDTREE2_NODE implementation
//
// constructor
kdtree2_node::kdtree2_node(int dim) : box(dim) {
left = right = NULL;
//
// all other construction is handled for real in the
// kdtree2 building operations.
//
}
// destructor
kdtree2_node::~kdtree2_node() {
if (left != NULL) delete left;
if (right != NULL) delete right;
// maxbox and minbox
// will be automatically deleted in their own destructors.
}
void kdtree2_node::search(searchrecord& sr) {
// the core search routine.
// This uses true distance to bounding box as the
// criterion to search the secondary node.
//
// This results in somewhat fewer searches of the secondary nodes
// than 'search', which uses the vdiff vector, but as this
// takes more computational time, the overall performance may not
// be improved in actual run time.
//
if ( (left == NULL) && (right == NULL)) {
// we are on a terminal node
if (sr.nn == 0) {
process_terminal_node_fixedball(sr);
} else {
process_terminal_node(sr);
}
} else {
kdtree2_node *ncloser, *nfarther;
float extra;
float qval = sr.qv[cut_dim];
// value of the wall boundary on the cut dimension.
if (qval < cut_val) {
ncloser = left;
nfarther = right;
extra = cut_val_right-qval;
} else {
ncloser = right;
nfarther = left;
extra = qval-cut_val_left;
};
if (ncloser != NULL) ncloser->search(sr);
if ((nfarther != NULL) && (squared(extra) < sr.ballsize)) {
// first cut
if (nfarther->box_in_search_range(sr)) {
nfarther->search(sr);
}
}
}
}
inline float dis_from_bnd(float x, float amin, float amax) {
if (x > amax) {
return(x-amax);
} else if (x < amin)
return (amin-x);
else
return 0.0;
}
inline bool kdtree2_node::box_in_search_range(searchrecord& sr) {
//
// does the bounding box, represented by minbox[*],maxbox[*]
// have any point which is within 'sr.ballsize' to 'sr.qv'??
//
int dim = sr.dim;
float dis2 =0.0;
float ballsize = sr.ballsize;
for (int i=0; i<dim;i++) {
dis2 += squared(dis_from_bnd(sr.qv[i],box[i].lower,box[i].upper));
if (dis2 > ballsize)
return(false);
}
return(true);
}
void kdtree2_node::process_terminal_node(searchrecord& sr) {
int centeridx = sr.centeridx;
int correltime = sr.correltime;
unsigned int nn = sr.nn;
int dim = sr.dim;
float ballsize = sr.ballsize;
//
bool rearrange = sr.rearrange;
const kdtree2_array& data = *sr.data;
const bool debug = false;
if (debug) {
printf("Processing terminal node %d, %d\n",l,u);
cout << "Query vector = [";
for (int i=0; i<dim; i++) cout << sr.qv[i] << ',';
cout << "]\n";
cout << "nn = " << nn << '\n';
check_query_in_bound(sr);
}
for (int i=l; i<=u;i++) {
int indexofi; // sr.ind[i];
float dis;
bool early_exit;
if (rearrange) {
early_exit = false;
dis = 0.0;
for (int k=0; k<dim; k++) {
dis += squared(data[i][k] - sr.qv[k]);
if (dis > ballsize) {
early_exit=true;
break;
}
}
if(early_exit) continue; // next iteration of mainloop
// why do we do things like this? because if we take an early
// exit (due to distance being too large) which is common, then
// we need not read in the actual point index, thus saving main
// memory bandwidth. If the distance to point is less than the
// ballsize, though, then we need the index.
//
indexofi = sr.ind[i];
} else {
//
// but if we are not using the rearranged data, then
// we must always
indexofi = sr.ind[i];
early_exit = false;
dis = 0.0;
for (int k=0; k<dim; k++) {
dis += squared(data[indexofi][k] - sr.qv[k]);
if (dis > ballsize) {
early_exit= true;
break;
}
}
if(early_exit) continue; // next iteration of mainloop
} // end if rearrange.
if (centeridx > 0) {
// we are doing decorrelation interval
if (abs(indexofi-centeridx) < correltime) continue; // skip this point.
}
// here the point must be added to the list.
//
// two choices for any point. The list so far is either
// undersized, or it is not.
//
if (sr.result.size() < nn) {
kdtree2_result e;
e.idx = indexofi;
e.dis = dis;
sr.result.push_element_and_heapify(e);
if (debug) cout << "unilaterally pushed dis=" << dis;
if (sr.result.size() == nn) ballsize = sr.result.max_value();
// Set the ball radius to the largest on the list (maximum priority).
if (debug) {
cout << " ballsize = " << ballsize << "\n";
cout << "sr.result.size() = " << sr.result.size() << '\n';
}
} else {
//
// if we get here then the current node, has a squared
// distance smaller
// than the last on the list, and belongs on the list.
//
kdtree2_result e;
e.idx = indexofi;
e.dis = dis;
ballsize = sr.result.replace_maxpri_elt_return_new_maxpri(e);
if (debug) {
cout << "Replaced maximum dis with dis=" << dis <<
" new ballsize =" << ballsize << '\n';
}
}
} // main loop
sr.ballsize = ballsize;
}
void kdtree2_node::process_terminal_node_fixedball(searchrecord& sr) {
int centeridx = sr.centeridx;
int correltime = sr.correltime;
int dim = sr.dim;
float ballsize = sr.ballsize;
//
bool rearrange = sr.rearrange;
const kdtree2_array& data = *sr.data;
for (int i=l; i<=u;i++) {
int indexofi = sr.ind[i];
float dis;
bool early_exit;
if (rearrange) {
early_exit = false;
dis = 0.0;
for (int k=0; k<dim; k++) {
dis += squared(data[i][k] - sr.qv[k]);
if (dis > ballsize) {
early_exit=true;
break;
}
}
if(early_exit) continue; // next iteration of mainloop
// why do we do things like this? because if we take an early
// exit (due to distance being too large) which is common, then
// we need not read in the actual point index, thus saving main
// memory bandwidth. If the distance to point is less than the
// ballsize, though, then we need the index.
//
indexofi = sr.ind[i];
} else {
//
// but if we are not using the rearranged data, then
// we must always
indexofi = sr.ind[i];
early_exit = false;
dis = 0.0;
for (int k=0; k<dim; k++) {
dis += squared(data[indexofi][k] - sr.qv[k]);
if (dis > ballsize) {
early_exit= true;
break;
}
}
if(early_exit) continue; // next iteration of mainloop
} // end if rearrange.
if (centeridx > 0) {
// we are doing decorrelation interval
if (abs(indexofi-centeridx) < correltime) continue; // skip this point.
}
{
kdtree2_result e;
e.idx = indexofi;
e.dis = dis;
sr.result.push_back(e);
}
}
}
/*
The KDTREE2 software is licensed under the terms of the Academic Free
Software License, listed herein. In addition, users of this software
must give appropriate citation in relevant technical documentation or
journal paper to the author, Matthew B. Kennel, Institute For
Nonlinear Science, preferably via a reference to the www.arxiv.org
repository of this document, {\tt www.arxiv.org e-print:
physics/0408067}. This requirement will be deemed to be advisory and
not mandatory as is necessary to permit the free inclusion of the
present software with any software licensed under the terms of any
version of the GNU General Public License, or GNU Library General
Public License.
Academic Free License
Version 1.1
This Academic Free License applies to any original work of authorship
(the "Original Work") whose owner (the "Licensor") has placed the
following notice immediately following the copyright notice for the
Original Work: "Licensed under the Academic Free License version 1.1."
Grant of License. Licensor hereby grants to any person obtaining a
copy of the Original Work ("You") a world-wide, royalty-free,
non-exclusive, perpetual, non-sublicenseable license (1) to use, copy,
modify, merge, publish, perform, distribute and/or sell copies of the
Original Work and derivative works thereof, and (2) under patent
claims owned or controlled by the Licensor that are embodied in the
Original Work as furnished by the Licensor, to make, use, sell and
offer for sale the Original Work and derivative works thereof, subject
to the following conditions.
Right of Attribution. Redistributions of the Original Work must
reproduce all copyright notices in the Original Work as furnished by
the Licensor, both in the Original Work itself and in any
documentation and/or other materials provided with the distribution of
the Original Work in executable form.
Exclusions from License Grant. Neither the names of Licensor, nor the
names of any contributors to the Original Work, nor any of their
trademarks or service marks, may be used to endorse or promote
products derived from this Original Work without express prior written
permission of the Licensor.
WARRANTY AND DISCLAIMERS. LICENSOR WARRANTS THAT THE COPYRIGHT IN AND
TO THE ORIGINAL WORK IS OWNED BY THE LICENSOR OR THAT THE ORIGINAL
WORK IS DISTRIBUTED BY LICENSOR UNDER A VALID CURRENT LICENSE FROM THE
COPYRIGHT OWNER. EXCEPT AS EXPRESSLY STATED IN THE IMMEDIATELY
PRECEEDING SENTENCE, THE ORIGINAL WORK IS PROVIDED UNDER THIS LICENSE
ON AN "AS IS" BASIS, WITHOUT WARRANTY, EITHER EXPRESS OR IMPLIED,
INCLUDING, WITHOUT LIMITATION, THE WARRANTY OF NON-INFRINGEMENT AND
WARRANTIES THAT THE ORIGINAL WORK IS MERCHANTABLE OR FIT FOR A
PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL
WORK IS WITH YOU. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL
PART OF THIS LICENSE. NO LICENSE TO ORIGINAL WORK IS GRANTED HEREUNDER
EXCEPT UNDER THIS DISCLAIMER.
LIMITATION OF LIABILITY. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL
THEORY, WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE,
SHALL THE LICENSOR BE LIABLE TO ANY PERSON FOR ANY DIRECT, INDIRECT,
SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER ARISING
AS A RESULT OF THIS LICENSE OR THE USE OF THE ORIGINAL WORK INCLUDING,
WITHOUT LIMITATION, DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE,
COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL
DAMAGES OR LOSSES, EVEN IF SUCH PERSON SHALL HAVE BEEN INFORMED OF THE
POSSIBILITY OF SUCH DAMAGES. THIS LIMITATION OF LIABILITY SHALL NOT
APPLY TO LIABILITY FOR DEATH OR PERSONAL INJURY RESULTING FROM SUCH
PARTY'S NEGLIGENCE TO THE EXTENT APPLICABLE LAW PROHIBITS SUCH
LIMITATION. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OR
LIMITATION OF INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO THIS EXCLUSION
AND LIMITATION MAY NOT APPLY TO YOU.
License to Source Code. The term "Source Code" means the preferred
form of the Original Work for making modifications to it and all
available documentation describing how to access and modify the
Original Work. Licensor hereby agrees to provide a machine-readable
copy of the Source Code of the Original Work along with each copy of
the Original Work that Licensor distributes. Licensor reserves the
right to satisfy this obligation by placing a machine-readable copy of
the Source Code in an information repository reasonably calculated to
permit inexpensive and convenient access by You for as long as
Licensor continues to distribute the Original Work, and by publishing
the address of that information repository in a notice immediately
following the copyright notice that applies to the Original Work.
Mutual Termination for Patent Action. This License shall terminate
automatically and You may no longer exercise any of the rights granted
to You by this License if You file a lawsuit in any court alleging
that any OSI Certified open source software that is licensed under any
license containing this "Mutual Termination for Patent Action" clause
infringes any patent claims that are essential to use that software.
This license is Copyright (C) 2002 Lawrence E. Rosen. All rights
reserved. Permission is hereby granted to copy and distribute this
license without modification. This license may not be modified without
the express written permission of its copyright owner.
*/
| [
"brant@ucsc.edu"
] | brant@ucsc.edu |
c4f0254b63e398e8e20a841579f62fbfe37771d7 | 6b580bb5e7bbf83e0d9845818678fbb85ea14450 | /aws-cpp-sdk-chime-sdk-media-pipelines/include/aws/chime-sdk-media-pipelines/model/ListTagsForResourceResult.h | 5a05120ec7422740212b626619d536fc87536b50 | [
"MIT",
"Apache-2.0",
"JSON"
] | permissive | dimatd/aws-sdk-cpp | 870634473781731822e2636005bc215ad43a0339 | 3d3f3d0f98af842e06d3d74648a0fca383538bb3 | refs/heads/master | 2022-12-21T20:54:25.033076 | 2022-12-13T18:18:00 | 2022-12-13T18:18:00 | 219,980,346 | 0 | 0 | Apache-2.0 | 2019-11-06T11:23:20 | 2019-11-06T11:23:20 | null | UTF-8 | C++ | false | false | 2,078 | h | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/chime-sdk-media-pipelines/ChimeSDKMediaPipelines_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/chime-sdk-media-pipelines/model/Tag.h>
#include <utility>
namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;
namespace Utils
{
namespace Json
{
class JsonValue;
} // namespace Json
} // namespace Utils
namespace ChimeSDKMediaPipelines
{
namespace Model
{
class AWS_CHIMESDKMEDIAPIPELINES_API ListTagsForResourceResult
{
public:
ListTagsForResourceResult();
ListTagsForResourceResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
ListTagsForResourceResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
/**
* <p>The tag key-value pairs.</p>
*/
inline const Aws::Vector<Tag>& GetTags() const{ return m_tags; }
/**
* <p>The tag key-value pairs.</p>
*/
inline void SetTags(const Aws::Vector<Tag>& value) { m_tags = value; }
/**
* <p>The tag key-value pairs.</p>
*/
inline void SetTags(Aws::Vector<Tag>&& value) { m_tags = std::move(value); }
/**
* <p>The tag key-value pairs.</p>
*/
inline ListTagsForResourceResult& WithTags(const Aws::Vector<Tag>& value) { SetTags(value); return *this;}
/**
* <p>The tag key-value pairs.</p>
*/
inline ListTagsForResourceResult& WithTags(Aws::Vector<Tag>&& value) { SetTags(std::move(value)); return *this;}
/**
* <p>The tag key-value pairs.</p>
*/
inline ListTagsForResourceResult& AddTags(const Tag& value) { m_tags.push_back(value); return *this; }
/**
* <p>The tag key-value pairs.</p>
*/
inline ListTagsForResourceResult& AddTags(Tag&& value) { m_tags.push_back(std::move(value)); return *this; }
private:
Aws::Vector<Tag> m_tags;
};
} // namespace Model
} // namespace ChimeSDKMediaPipelines
} // namespace Aws
| [
"aws-sdk-cpp-automation@github.com"
] | aws-sdk-cpp-automation@github.com |
d8f771b217cf3c0e6a054f1c92b4c7383be52cc2 | e3e012664e3b4c016b7ed240cd9b81af1289149e | /thirdparty/linux/miracl/miracl_osmt/source/ecsign.cpp | 7c2b4410c85dc9f5298ab2988396d943c915dbd2 | [
"Unlicense"
] | permissive | osu-crypto/MultipartyPSI | b48ce23163fed8eb458a05e3af6e4432963f08c7 | 44e965607b0d27416420d32cd09e6fcc34782c3a | refs/heads/implement | 2023-07-20T10:16:55.866284 | 2021-05-12T22:01:12 | 2021-05-12T22:01:12 | 100,207,769 | 73 | 29 | Unlicense | 2023-07-11T04:42:04 | 2017-08-13T22:15:27 | C++ | UTF-8 | C++ | false | false | 2,812 | cpp | /*
* Elliptic Curve Digital Signature Algorithm (ECDSA)
*
*
* This program asks for the name of a <file>, computes its message digest,
* signs it, and outputs the signature to a file <file>.ecs. It is assumed
* that curve parameters are available from a file common.ecs, as well as
* the private key of the signer previously generated by the ecsgen program
*
* The curve is y^2=x^3+Ax+B mod p
*
* The file common.ecs is presumed to exist, and to contain the domain
* information {p,A,B,q,x,y}, where A and B are curve parameters, (x,y) are
* a point of order q, p is the prime modulus, and q is the order of the
* point (x,y). In fact normally q is the prime number of points counted
* on the curve.
*
* Requires: big.cpp ecn.cpp
*/
#include <iostream>
#include <cstring>
#include <fstream>
#include "ecn.h"
using namespace std;
#ifndef MR_NOFULLWIDTH
Miracl precision(200,256);
#else
Miracl precision(50,MAXBASE);
#endif
void strip(char *name)
{ /* strip off filename extension */
int i;
for (i=0;name[i]!='\0';i++)
{
if (name[i]!='.') continue;
name[i]='\0';
break;
}
}
static Big Hash(ifstream &fp)
{ /* compute hash function */
char ch,s[20];
Big h;
sha sh;
shs_init(&sh);
forever
{ /* read in bytes from message file */
fp.get(ch);
if (fp.eof()) break;
shs_process(&sh,ch);
}
shs_hash(&sh,s);
h=from_binary(20,s);
return h;
}
int main()
{
ifstream common("common.ecs"); /* construct file I/O streams */
ifstream private_key("private.ecs");
ifstream message;
ofstream signature;
char ifname[50],ofname[50];
ECn G;
Big a,b,p,q,x,y,h,r,s,d,k;
long seed;
int bits;
miracl *mip=&precision;
/* randomise */
cout << "Enter 9 digit random number seed = ";
cin >> seed;
irand(seed);
/* get common data */
common >> bits;
mip->IOBASE=16;
common >> p >> a >> b >> q >> x >> y;
mip->IOBASE=10;
/* calculate r - this can be done off-line,
and hence amortized to almost nothing */
ecurve(a,b,p,MR_PROJECTIVE);
G=ECn(x,y);
k=rand(q);
G*=k; /* see ebrick.cpp for technique to speed this up */
G.get(r);
r%=q;
/* get private key of recipient */
private_key >> d;
/* get message */
cout << "file to be signed = " ;
cin >> ifname;
strcpy(ofname,ifname);
strip(ofname);
strcat(ofname,".ecs");
message.open(ifname,ios::binary|ios::in);
if (!message)
{
cout << "Unable to open file " << ifname << "\n";
return 0;
}
h=Hash(message);
/* calculate s */
k=inverse(k,q);
s=((h+d*r)*k)%q;
signature.open(ofname);
signature << r << endl;
signature << s << endl;
return 0;
}
| [
"trieun@oregonstate.edu"
] | trieun@oregonstate.edu |
b067a2f67add7305f9459539960b4d598c70b022 | 67cf5d1d7ea62ca9e7b35c42c042efcf1c77ff36 | /mosixFastProjections/include/Projector/ProjectionLib/VanDerGrintenProjection.h | 5e318d9edca9500f865c50a70ddb6d01cdea4792 | [] | no_license | bpass/cegis | d3c84d2d29a084105b4c207391ddc6ace0cdf398 | 6c849e41974b8ff844f78e260de26d644c956afb | refs/heads/master | 2020-04-03T18:57:58.102939 | 2013-04-24T22:07:54 | 2013-04-24T22:07:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,869 | h | // $Id: VanDerGrintenProjection.h,v 1.1 2005/03/11 23:59:10 mschisler Exp $
// Last modified by $Author: mschisler $ on $Date: 2005/03/11 23:59:10 $
#ifndef _VanDerGrintenPROJECTION_H_
#define _VanDerGrintenPROJECTION_H_
#include "PseudocylindricalProjection.h"
namespace ProjLib
{
class VanDerGrintenProjection : public PseudocylindricalProjection
{
public:
VanDerGrintenProjection( double originLat, double sphereRadius,
double centralMeridian,
double falseEasting, double falseNorthing,
DATUM d, UNIT u,
DATUM geoDatum = DEFAULT_DATUM,
UNIT geoUnit = ARC_DEGREES );
VanDerGrintenProjection( const VanDerGrintenProjection& p );
// Accessors
PROJSYS getProjectionSystem() const throw();
double getOriginLatitude() const throw();
// Modifiers
void setOriginLatitude( double originLat ) throw();
/* Sets the origin latitude. The latitude must be in packed DMS
(DDDMMMSSS.SSS) format. */
// Operator overloads
bool operator==( const Projection& rhs ) const throw();
// Cloning
Projection* clone() const throw(std::bad_alloc);
// String override
std::string toString() const throw();
};
// ***************************************************************************
inline PROJSYS VanDerGrintenProjection::getProjectionSystem() const throw()
{
return VGRINT;
}
// ***************************************************************************
inline double VanDerGrintenProjection::getOriginLatitude() const throw()
{
return d_projParams[5];
}
// ***************************************************************************
inline void VanDerGrintenProjection::setOriginLatitude( double originLat )
throw()
{
d_projParams[5] = originLat;
}
} // namespace ProjLib
#endif
| [
"mschisler"
] | mschisler |
4b9a66fb0e6e128ac1d178dcd15109aa3cb1d177 | a6201151b9956af651570c1286bbf078556cf1c6 | /RectifierControlFView.cpp | e9199f89d2562b73013d27a9d39dd55e287f64d4 | [] | no_license | vladislav-007/RectifierControl | d73ea8dabf0c667823384406762dd6ab373f18f7 | 3b1281f6d0ec3f82a850c35554c06a9b0e1773a0 | refs/heads/master | 2020-03-12T13:01:01.062623 | 2019-06-10T03:19:53 | 2019-06-10T03:19:53 | 130,632,131 | 0 | 0 | null | 2018-11-28T02:18:10 | 2018-04-23T02:57:23 | C++ | UTF-8 | C++ | false | false | 855 | cpp | // RectifierControlFView.cpp : implementation file
//
#include "stdafx.h"
#include "RectifierControl.h"
#include "RectifierControlFView.h"
// CRectifierControlFView
IMPLEMENT_DYNCREATE(CRectifierControlFView, CFormView)
CRectifierControlFView::CRectifierControlFView()
: CFormView(IDD_RECTIFIERCONTROLFVIEW)
{
}
CRectifierControlFView::~CRectifierControlFView()
{
}
void CRectifierControlFView::DoDataExchange(CDataExchange* pDX)
{
CFormView::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CRectifierControlFView, CFormView)
END_MESSAGE_MAP()
// CRectifierControlFView diagnostics
#ifdef _DEBUG
void CRectifierControlFView::AssertValid() const
{
CFormView::AssertValid();
}
#ifndef _WIN32_WCE
void CRectifierControlFView::Dump(CDumpContext& dc) const
{
CFormView::Dump(dc);
}
#endif
#endif //_DEBUG
// CRectifierControlFView message handlers
| [
"vladisl@ngs.ru"
] | vladisl@ngs.ru |
3c41587310bd90eedfbebafd5e1188c20ce06a1a | da38e03e53832f864058e7d1517a8ba3ac17f15d | /CLI/Validators/InputValidators/LabelValidator.cpp | cf5fb87904a4d17457e3f03319323e8b8693aca2 | [] | no_license | IliaIlyin/ToDoList | 916c076726d64cffa8d09f5d82608cd28568fa8d | 04a7101a2057972e5f869407da95208bf0bf4485 | refs/heads/master | 2023-01-02T04:34:01.033413 | 2020-09-27T22:59:05 | 2020-09-27T22:59:05 | 281,182,314 | 0 | 0 | null | 2020-08-18T07:57:34 | 2020-07-20T17:25:21 | C++ | UTF-8 | C++ | false | false | 213 | cpp | //
// Created by illia.ilin on 8/25/2020.
//
#include "LabelValidator.h"
GeneralInputValidator::InputToken LabelValidator::validate(const std::string &str) {
return GeneralInputValidator::validateLabel(str);
}
| [
"fate98765@gmail.com"
] | fate98765@gmail.com |
f08648ecaf1e93558fe5f662754ab8e10fda4363 | 28ccd518e0c516f5e6dfce5b8373ba4a028d22ca | /14.10/marini/random.h | 85e1528b0c7077dc376af7b688ea79b0bb0907db | [] | no_license | eugnsp/CUJ | a3fd72f81ac18460febc090bb8be0c21164750b4 | 922ecf8f730a193dab63ec790c0b655477732dcf | refs/heads/master | 2023-08-19T07:48:19.948674 | 2021-09-19T08:55:58 | 2021-09-19T09:00:49 | 357,140,243 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,856 | h | /*
* random.h
* Header file for the implementation of a random number
* generator class. This class is based on the algorithm defined
* by Z(i) = AZ(i-1)modM. Where M is the prime number 2^31-1 =
* 2,147,483,647 and A is the value 62089911.
*/
#include <values.h>
#include <math.h>
// Unform Random Generator Class Definition (PMMLCG)
class RandomGenerator { // Generate U(0,1)
public:
RandomGenerator(void);
// virtual ~RandomGenerator(void);
virtual double Rand(void);
void Reset(void);
static void ResetStreamCount();
static void SelectSeed(long int seed);
protected:
long int current_seed;
private:
static int stream_count;
static long int base_seed;
long int my_start_seed;
};
// RandomGenerator Inline Functions
inline void RandomGenerator::ResetStreamCount(void)
{
stream_count = 0;
}
inline void RandomGenerator::SelectSeed(long int seed)
{
base_seed = seed;
}
inline void RandomGenerator::Reset(void)
{
current_seed = my_start_seed;
}
// End of RandomGenerator
// Uniform Random Generator Class Definition -- Generate U(a,b)
class UniformRandomGenerator : public RandomGenerator {
public:
UniformRandomGenerator(double high_limit = 1.0,
double low_limit = 0.0);
// virtual ~UniformRandomGenerator(void);
double Rand(void);
private:
double A;
double B;
};
// UniformRandomGenerator Inline Functions
inline
UniformRandomGenerator::UniformRandomGenerator(double high_limit,
double low_limit) : RandomGenerator(), A(low_limit),
B(high_limit)
{ // Constructor does nothing special
}
inline double UniformRandomGenerator::Rand(void)
{ // return Z = A + (B-A)*U(0,1)
return A + ((B - A) * RandomGenerator::Rand());
}
// End of UniformRandomGenerator
// Exponential Random Generator Class Def. -- Gen. Exp(a)
class ExponentialRandomGenerator : public RandomGenerator {
public:
ExponentialRandomGenerator(double m = 1.0);
// virtual ~ExponentialRandomGenerator(void);
double Rand(void);
private:
double mean;
};
// ExponentialRandomGenerator Inline Functions
inline
ExponentialRandomGenerator::ExponentialRandomGenerator(double m) :
RandomGenerator(), mean(m)
{ // Constructor does nothing special
}
inline double ExponentialRandomGenerator::Rand(void)
{ // return Z = -1*mean*ln(U(0,1))
return -1.0 * mean * log(RandomGenerator::Rand());
}
// End of ExponentialRandomGenerator
// Triangle Random Generator Class Def. -- Generate Triang(a,b,c)
class TriangleRandomGenerator : public RandomGenerator {
public:
TriangleRandomGenerator(double high_limit = 1.0,
double low_limit = 0.0,
double cut_value = 0.5);
// virtual ~TriangleRandomGenerator(void);
double Rand(void);
private:
double A;
double B;
double C;
};
// TriangleRandomGenerator Inline Function
inline
TriangleRandomGenerator::TriangleRandomGenerator(
double high_limit,double low_limit, double cut_value) :
RandomGenerator(), A(low_limit), B(high_limit)
{ // Calculate bend value
C = (cut_value - A) / (B - A);
}
inline double TriangleRandomGenerator::Rand(void)
{
/*
* If U(0,1) <= C, then return A + (B-A)*sqrt(C*U(0,1))
* otherwise
* return A + (B-A)*(1 - sqrt((1-C) * (1 - U(0,1))))
*/
double x = RandomGenerator::Rand();
if (x <= C)
return A + (B - A) * sqrt(C * x);
else
return A + (B - A) * (1.0 - sqrt((1.0 - C)*(1.0 - x)));
}
// End of ExponentialRandomGenerator
| [
"evgeny.sg@gmail.com"
] | evgeny.sg@gmail.com |
f712e1d970bc0a35adea0baa23dc2a867e1b0d0c | 942b7b337019aa52862bce84a782eab7111010b1 | /3rd party/imgui/imconfig.h | 769713a30a15d89c762a0a9576a9060213782d14 | [
"MIT",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | galek/xray15 | 338ad7ac5b297e9e497e223e0fc4d050a4a78da8 | 015c654f721e0fbed1ba771d3c398c8fa46448d9 | refs/heads/master | 2021-11-23T12:01:32.800810 | 2020-01-10T15:52:45 | 2020-01-10T15:52:45 | 168,657,320 | 0 | 0 | null | 2019-02-01T07:11:02 | 2019-02-01T07:11:01 | null | UTF-8 | C++ | false | false | 3,752 | h | //-----------------------------------------------------------------------------
// COMPILE-TIME OPTIONS FOR DEAR IMGUI
// Runtime options (clipboard callbacks, enabling various features, etc.) can generally be set via the ImGuiIO structure.
// You can use ImGui::SetAllocatorFunctions() before calling ImGui::CreateContext() to rewire memory allocation functions.
//-----------------------------------------------------------------------------
// A) You may edit imconfig.h (and not overwrite it when updating imgui, or maintain a patch/branch with your modifications to imconfig.h)
// B) or add configuration directives in your own file and compile with #define IMGUI_USER_CONFIG "myfilename.h"
// Note that options such as IMGUI_API, IM_VEC2_CLASS_EXTRA or ImDrawIdx needs to be defined consistently everywhere you include imgui.h, not only for the imgui*.cpp compilation units.
//-----------------------------------------------------------------------------
#pragma once
//---- Define assertion handler. Defaults to calling assert().
//#define IM_ASSERT(_EXPR) MyAssert(_EXPR)
//---- Define attributes of all API symbols declarations, e.g. for DLL under Windows.
//#define IMGUI_API __declspec( dllexport )
//#define IMGUI_API __declspec( dllimport )
#ifdef IMGUI_EXPORTS
#define IMGUI_API __declspec(dllexport)
#else
#define IMGUI_API __declspec(dllimport)
#endif
//---- Don't define obsolete functions/enums names. Consider enabling from time to time after updating to avoid using soon-to-be obsolete function/names
//#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS
//---- Don't implement default handlers for Windows (so as not to link with certain functions)
//#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS // Don't use and link with OpenClipboard/GetClipboardData/CloseClipboard etc.
//#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS // Don't use and link with ImmGetContext/ImmSetCompositionWindow.
//---- Don't implement demo windows functionality (ShowDemoWindow()/ShowStyleEditor()/ShowUserGuide() methods will be empty)
//---- It is very strongly recommended to NOT disable the demo windows during development. Please read the comments in imgui_demo.cpp.
//#define IMGUI_DISABLE_DEMO_WINDOWS
//---- Don't implement ImFormatString(), ImFormatStringV() so you can reimplement them yourself.
//#define IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS
//---- Include imgui_user.h at the end of imgui.h as a convenience
//#define IMGUI_INCLUDE_IMGUI_USER_H
//---- Pack colors to BGRA8 instead of RGBA8 (if you needed to convert from one to another anyway)
//#define IMGUI_USE_BGRA_PACKED_COLOR
//---- Implement STB libraries in a namespace to avoid linkage conflicts (defaults to global namespace)
//#define IMGUI_STB_NAMESPACE ImGuiStb
//---- Define constructor and implicit cast operators to convert back<>forth from your math types and ImVec2/ImVec4.
// This will be inlined as part of ImVec2 and ImVec4 class declarations.
/*
#define IM_VEC2_CLASS_EXTRA \
ImVec2(const MyVec2& f) { x = f.x; y = f.y; } \
operator MyVec2() const { return MyVec2(x,y); }
#define IM_VEC4_CLASS_EXTRA \
ImVec4(const MyVec4& f) { x = f.x; y = f.y; z = f.z; w = f.w; } \
operator MyVec4() const { return MyVec4(x,y,z,w); }
*/
//---- Use 32-bit vertex indices (default is 16-bit) to allow meshes with more than 64K vertices. Render function needs to support it.
//#define ImDrawIdx unsigned int
//---- Tip: You can add extra functions within the ImGui:: namespace, here or in your own headers files.
/*
namespace ImGui
{
void MyFunction(const char* name, const MyMatrix44& v);
}
*/
| [
"abramcumner@yandex.ru"
] | abramcumner@yandex.ru |
a289d5ed4da0d671eb266e09f622397185456236 | 9826489e216479f8b3c7b8d600208076b15028af | /libsolintent/ir/ExpressionInterface.h | d5b2242a0fbed2d2bbffe0b111e25dc1cc593c13 | [] | no_license | ScottWe/solintent | 117a1e3e157bbd42a21ae256c063480fdd90d5d7 | 85f8c4d9a2a8acd044a833b24a01dfcfffb465c7 | refs/heads/master | 2020-11-23T20:55:32.384223 | 2019-12-20T20:18:53 | 2019-12-20T20:18:53 | 227,817,149 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,784 | h | /**
* Analyzing Solidity expressions directly is not always practical. The AST is
* designed to be (1) readable and (2) JavaScript like. It can instead be
* helpful to have some intermediate form. Furthermore, it can be helpful if
* such an intermediate form is "adaptive". That is, it adjusts to the current
* needs of analysis (taint versus bounds versus etc.). This module provides a
* set of primitives to capture different views of the Solidity AST.
*/
/**
* @author Arthur Scott Wesley <aswesley@uwaterloo.ca>
* @date 2019
* Surface-level interfaces for the full ExpressionSummary hierarchy.
*/
#pragma once
#include <libsolidity/ast/ASTVisitor.h>
#include <libsolidity/ast/Types.h>
#include <libsolintent/ir/IRSummary.h>
#include <algorithm>
#include <list>
#include <optional>
#include <set>
namespace dev
{
namespace solintent
{
// -------------------------------------------------------------------------- //
/**
* A generalized summary of any expression. This is a shared base-type.
*/
class ExpressionSummary: public detail::SpecializedIR<solidity::Expression>
{
public:
/**
* Possible sources of data. Examples are given below.
* - [Length] `array.length`
* - [Balance] `address(contract).balance`
* - [Input] `x` in `function f(int x) public`
* - [Output] `x` in `function f() returns (int x) public`
* - [Miner] `block.num`
* - [Sender] `msg.value`
*/
enum class Source
{
Length, Balance, Input, Output, Miner, Sender, State
};
virtual ~ExpressionSummary() = 0;
/**
* If this expression is tainted by mutable variables, this will return all
* applicable tags.
*/
virtual std::optional<std::set<Source>> tags() const = 0;
/**
* Returns a list of the free variables upon which this operation is
* dependant.
*/
virtual std::set<std::reference_wrapper<ExpressionSummary const>> free() const = 0;
protected:
/**
* Declares that this summary wraps the given expression.
*
* _expr: the wrapped expression.
*/
explicit ExpressionSummary(solidity::Expression const& _expr);
};
// -------------------------------------------------------------------------- //
/**
* Represents a numeric expression in Solidity as either a literal, or an AST of
* operations.
*/
class NumericSummary: public ExpressionSummary
{
public:
virtual ~NumericSummary() = 0;
/**
* Produces the exact value of this expression, if possible.
*/
virtual std::optional<solidity::rational> exact() const = 0;
protected:
/**
* Declares that this summary wraps the given expression.
*
* _expr: the wrapped expression.
*/
explicit NumericSummary(solidity::Expression const& _expr);
};
// -------------------------------------------------------------------------- //
/**
* Represents a boolean expression in Solidity as either a literal, or an AST of
* operations.
*/
class BooleanSummary: public ExpressionSummary
{
public:
virtual ~BooleanSummary() = 0;
/**
* Produces the exact value of the expression, if possible.
*/
virtual std::optional<bool> exact() const = 0;
protected:
/**
* Declares that this summary wraps the given expression.
*
* _expr: the wrapped expression.
*/
explicit BooleanSummary(solidity::Expression const& _expr);
};
// -------------------------------------------------------------------------- //
/**
* A secondary base-class which endows variable-related summaries the ability to
* analyze their declarations.
*/
class SymbolicVariable
{
public:
virtual ~SymbolicVariable() = 0;
/**
* Allows the symbol to be tied to a unique name.
*/
std::string symb() const;
protected:
/**
* Resolves the identifier to its variable declaration. All labels and names
* will be populated in the process.
*
* _id: the identifier to resolve
*/
explicit SymbolicVariable(solidity::Identifier const& _id);
/**
* Resolves the member access to the appropriate initialization site. The
* path to reach this variable is expanded.
*
* _access: the member access to resolve
*/
explicit SymbolicVariable(solidity::MemberAccess const& _access);
/**
* Allows symbolic metadata to be forwarded to a new instantiation.
*
* _otr: the previously annotated symbolic variable.
*/
explicit SymbolicVariable(SymbolicVariable const& _otr);
/**
* Returns all tags resolved during itialization.
*/
std::set<ExpressionSummary::Source> symbolTags() const;
private:
/**
* Utility class to map scopable variables to path.
*/
class PathAnalyzer: private solidity::ASTConstVisitor
{
public:
/**
* _id: identifier to analyze, wrt its reference declaration.
*/
explicit PathAnalyzer(solidity::Identifier const& _id);
/**
* _mem: identifier to analyze, wrt its reference declaration.
*/
explicit PathAnalyzer(solidity::MemberAccess const& _mem);
/**
* Produces the full name of this variable
*/
std::string symb() const;
/**
* Returns the source of this variable. If there are no applicable
* source annotations then notion is returned.
*/
std::optional<ExpressionSummary::Source> source() const;
protected:
bool visit(solidity::VariableDeclaration const& _node) override;
bool visit(solidity::FunctionCall const& _node) override;
bool visit(solidity::MemberAccess const& _node) override;
void endVisit(solidity::Identifier const& _node) override;
private:
// Maintains a chain of all declarations, starting from top level.
std::string m_symb;
// If a variable source is resolved, it is stored here.
std::optional<ExpressionSummary::Source> m_source;
/**
* Pushes _str to the front of m_path. The '#' separator notation is
* obeyed.
*/
void prependToPath(std::string _str);
};
// Stores all tags extracted for this symbol during analysis.
std::set<ExpressionSummary::Source> m_tags;
// A unique identifier for this variable.
std::string m_symb;
/**
* Integrates the PathAnalysis results with the SymbolicVariable. This
* factors out some of the initialization logic.
*
* TODO: the initialization parameter object pattern (does this have a
* name?) would be more practical. Less error-prone...
*/
void applyPathAnalysis(PathAnalyzer const& _analysis);
};
// -------------------------------------------------------------------------- //
}
}
| [
"scott.wesley@ns.sympatico.ca"
] | scott.wesley@ns.sympatico.ca |
c9a7e693427d6b057fc891dd1ef488d3c11faed6 | 181968b591aa12c3081dbb78806717cce0fad98e | /src/modules/mesh_converter/MeshConverter.cpp | 9b2c7b4374df3f082785d06885a22ea6e7199d20 | [
"MIT"
] | permissive | Liudeke/CAE | d6d4c2dfbabe276a1e2acaa79038d8efcbe9d454 | 7eaa096e45fd32f55bd6de94c30dcf706c6f2093 | refs/heads/master | 2023-03-15T08:55:37.797303 | 2020-10-03T17:31:22 | 2020-10-03T17:36:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,660 | cpp | #include "MeshConverter.h"
#include "MeshCriteria.h"
#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/make_mesh_3.h>
#include <CGAL/Mesh_3/config.h>
#include <CGAL/Mesh_complex_3_in_triangulation_3.h>
#include <CGAL/Mesh_criteria_3.h>
#include <CGAL/Mesh_triangulation_3.h>
#include <CGAL/Mesh_polyhedron_3.h>
#include <CGAL/Polyhedral_mesh_domain_3.h>
#include <CGAL/Polyhedral_mesh_domain_with_features_3.h>
#include <CGAL/Polyhedron_3.h>
#include <CGAL/refine_mesh_3.h>
#include <CGAL/utility.h>
// IO
#include <iostream>
#include <fstream>
// Boost
#include <boost/algorithm/string/predicate.hpp>
#include <boost/lexical_cast.hpp>
// Eigen
#include <Eigen/Dense>
// std
#include <set>
#include <vector>
// CGAL feature detection
#include <CGAL/Polygon_mesh_processing/detect_features.h>
// concurrency tags
#ifdef CGAL_CONCURRENT_MESH_3
typedef CGAL::Parallel_tag Concurrency_tag;
#else
typedef CGAL::Sequential_tag Concurrency_tag;
#endif
// Polyhedron
typedef CGAL::Exact_predicates_inexact_constructions_kernel K;
typedef CGAL::Mesh_polyhedron_3<K>::type Polyhedron;
// Domain
typedef CGAL::Polyhedral_mesh_domain_with_features_3<K> Mesh_domain_features;
typedef CGAL::Polyhedral_mesh_domain_3<Polyhedron, K> Mesh_domain;
// Triangulation
typedef CGAL::Mesh_triangulation_3<Mesh_domain, CGAL::Default, Concurrency_tag>::type Tr;
typedef CGAL::Mesh_triangulation_3<Mesh_domain_features, CGAL::Default, Concurrency_tag>::type Tr_features;
typedef CGAL::Mesh_complex_3_in_triangulation_3<Tr> C3t3;
typedef CGAL::Mesh_complex_3_in_triangulation_3<Tr> C3t3_features;
// Criteria
typedef CGAL::Mesh_criteria_3<Tr> Mesh_criteria;
typedef Polyhedron::HalfedgeDS HalfedgeDS;
MeshConverter* MeshConverter::m_instance = new MeshConverter();
MeshConverter::MeshConverter()
{
}
// Helper function
template<typename T, unsigned int n>
void add_if_not_contains(std::vector<std::array<T, n>>& v, std::array<T, n> e)
{
for (unsigned int i = 0; i < v.size(); ++i)
{
bool equal = true;
for (unsigned int j = 0; j < n; ++j)
{
if (std::abs(v[i][j] - e[j]) > 0.0001)
equal = false;
}
if (equal)
return;
}
v.push_back(e);
}
template<typename Polyhedron>
void reset_sharp_edges(Polyhedron* pMesh)
{
typename boost::property_map<Polyhedron, CGAL::edge_is_feature_t>::type if_pm =
get(CGAL::edge_is_feature, *pMesh);
for(typename boost::graph_traits<Polyhedron>::edge_descriptor ed : edges(*pMesh))
{
put(if_pm,ed,false);
}
}
template<typename Polyhedron>
void detect_sharp_edges(Polyhedron* pMesh, const double angle)
{
reset_sharp_edges(pMesh);
// Detect edges in current polyhedron
typename boost::property_map<Polyhedron, CGAL::edge_is_feature_t>::type eif =
get(CGAL::edge_is_feature, *pMesh);
CGAL::Polygon_mesh_processing::detect_sharp_edges(*pMesh, angle, eif);
}
// Creates a CGAL Polyhedron from the given vertices and triangles.
Polyhedron createPolyhedron(
const Vectors& vertices,
const Faces& facets)
{
Polyhedron p;
CGAL::Polyhedron_incremental_builder_3<HalfedgeDS> builder( p.hds(), true);
typedef typename HalfedgeDS::Vertex Vertex;
typedef typename Vertex::Point Point;
builder.begin_surface(vertices.size(), facets.size(), 0);
for (const Eigen::Vector3d& v : vertices)
{
builder.add_vertex(Point(v(0), v(1), v(2)));
}
for (const std::array<unsigned int, 3>& f : facets)
{
builder.begin_facet();
builder.add_vertex_to_facet(f[0]);
builder.add_vertex_to_facet(f[1]);
builder.add_vertex_to_facet(f[2]);
builder.end_facet();
}
builder.end_surface();
return p;
}
template <typename Mesh_domain>
bool generateMeshFromCGALPolyhedron(
Mesh_domain& domain,
Vectors& vertices_out,
Faces& outer_facets_out,
Faces& facets_out,
Cells& cells_out,
const MeshCriteria& meshCriteria)
{
// Triangulation
typedef typename CGAL::Mesh_triangulation_3<Mesh_domain, CGAL::Default, Concurrency_tag>::type MeshTr;
typedef CGAL::Mesh_complex_3_in_triangulation_3<MeshTr> C3t3;
typedef CGAL::Mesh_criteria_3<MeshTr> Mesh_criteria;
Mesh_criteria criteria(
CGAL::parameters::cell_radius_edge_ratio=meshCriteria.getCellRadiusEdgeRatio(),
CGAL::parameters::cell_size=meshCriteria.getCellSize(),
CGAL::parameters::facet_angle=meshCriteria.getFacetAngle(),
CGAL::parameters::facet_size=meshCriteria.getFacetSize(),
CGAL::parameters::facet_distance=meshCriteria.getFaceDistance());
// Mesh_criteria criteria;
// Mesh generation
C3t3 c3t3 = CGAL::make_mesh_3<C3t3>(
domain, criteria,
CGAL::parameters::no_perturb(),
CGAL::parameters::no_exude());
// CONVERT FROM CGAL TO vectors
typedef typename C3t3::Triangulation Tr;
typedef typename C3t3::Facets_in_complex_iterator Facet_iterator;
typedef typename C3t3::Cells_in_complex_iterator Cell_iterator;
typedef typename Tr::Finite_vertices_iterator Finite_vertices_iterator;
typedef typename Tr::Vertex_handle Vertex_handle;
typedef typename Tr::Point Point_3;
const Tr& tr = c3t3.triangulation();
std::cout << "\nAfter Triangulation: \n" << "Vertices: "
<< tr.number_of_vertices() << "\n"
<< "Facets/Triangles: " << tr.number_of_facets() << "\n"
<< "Cells/Tetrahedra: " << tr.number_of_cells() << "\n";
//-------------------------------------------------------
// Vertices
//-------------------------------------------------------
boost::unordered_map<Vertex_handle, int> V;
int inum = 0;
for (Finite_vertices_iterator vit = tr.finite_vertices_begin();
vit != tr.finite_vertices_end(); ++vit) {
V[vit] = inum++;
Point_3 p = vit->point();
vertices_out.push_back(Eigen::Vector3d((float)CGAL::to_double(p.x()),
(float)CGAL::to_double(p.y()), (float)CGAL::to_double(p.z())));
}
//-------------------------------------------------------
// Facets
//-------------------------------------------------------
typename C3t3::size_type number_of_triangles =
c3t3.number_of_facets_in_complex();
for (Facet_iterator fit = c3t3.facets_in_complex_begin();
fit != c3t3.facets_in_complex_end(); ++fit) {
typename C3t3::Subdomain_index cell_sd=c3t3.subdomain_index(fit->first);
typename C3t3::Subdomain_index opp_sd=c3t3.subdomain_index(fit->first->neighbor(fit->second));
int j = -1;
std::array<unsigned int, 3> vertex;
for (int i = 0; i < 4; i++) {
if (i != fit->second) {
const Vertex_handle& vh = (*fit).first->vertex(i);
vertex[++j] = V[vh];
}
}
//facets.push_back(vertex);
// Only for outer Facets true (that one that lie on the boundary)
if (!(cell_sd != 0 && opp_sd != 0))
outer_facets_out.push_back(vertex);
}
//-------------------------------------------------------
// Tetrahedra
//-------------------------------------------------------
auto sortedFace = [](std::array<unsigned int, 3> f)
{
std::sort(f.begin(), f.end());
return f;
};
std::set<std::array<unsigned int, 3>> addedSortedFacets;
auto addFaceIfNotContains = [&sortedFace, &facets_out, &addedSortedFacets](
std::array<unsigned int, 3> f)
{
std::array<unsigned int, 3> sortedF = sortedFace(f);
if (addedSortedFacets.find(sortedF) == addedSortedFacets.end())
{
addedSortedFacets.insert(sortedF);
facets_out.push_back(f);
}
};
for (Cell_iterator cit = c3t3.cells_in_complex_begin();
cit != c3t3.cells_in_complex_end(); ++cit)
{
std::array<unsigned int, 4> f;
for (unsigned int i = 0; i < 4; i++)
f[i] = static_cast<unsigned int>(V[cit->vertex(static_cast<int>(i))]);
cells_out.push_back(f);
addFaceIfNotContains({f[0], f[1], f[2]});
addFaceIfNotContains({f[0], f[1], f[3]});
addFaceIfNotContains({f[0], f[2], f[3]});
addFaceIfNotContains({f[1], f[2], f[3]});
}
// correct the triangle indices
// The 3 vertex indices of a triangles must be ordered in a way
// that the cross product of the first two vertices:
// v1.cross(v2) points on the outside.
for (size_t i = 0; i < outer_facets_out.size(); ++i) {
std::array<unsigned int, 3>& facet = outer_facets_out[i];
// =====================================================================
// Disclaimer:
// This code part is responsible for fixing the vertex index order of
// each outer triangle so that the normal that points outside the
// polygon can be calculated in a consistent way. The same is already
// done in the constructor of Polygon3D so this part may be removed.
// It is left here for the case that one doesn't want to create a
// Polygon3D afterwards. It could be removed for the future to slightly
// improve the performance.
// find the outer facet (tetrahedron) that contains this triangle
// note, that since this is an outer triangle, there is only a single tetrahedron
// that containts it.
bool found = false;
unsigned int other_vertex_id = 0;
for (size_t j = 0; j < cells_out.size(); ++j)
{
Cell& c = cells_out[j];
if (std::find(c.begin(), c.end(), facet[0]) != c.end() &&
std::find(c.begin(), c.end(), facet[1]) != c.end()&&
std::find(c.begin(), c.end(), facet[2]) != c.end())
{
found = true;
// find the other vertex of the cell that is not part of the triangle
for (size_t k = 0; k < 4; ++k)
{
if (std::find(facet.begin(), facet.end(), c[k]) == facet.end())
{
other_vertex_id = c[k];
break;
}
}
break;
}
}
bool reverted = false;
if (!found)
{
std::cout << "Did not find cell for outer triangle.\n";
}
else
{
Eigen::Vector3d r_1 = vertices_out[facet[1]] - vertices_out[facet[0]];
Eigen::Vector3d r_2 = vertices_out[facet[2]] - vertices_out[facet[0]];
Eigen::Vector3d r_3 = vertices_out[other_vertex_id] - vertices_out[facet[0]];
// std::cout << "other_vertex_id = " << other_vertex_id << "\n";
if (r_1.cross(r_2).normalized().dot(r_3) > 0)
{
unsigned int temp = facet[1];
facet[1] = facet[2];
facet[2] = temp;
reverted = true;
}
}
// =====================================================================
// Check if this face is part of all faces. If so, revert the
// corresponding global facet if the outer facet was also reverted.
// Polygon3D doesn't necessarily require this to be done because
// it does it on its own as well, see
// Polygon3D::synchronizeTriangleIndexOrder()).
bool found2 = false;
for (size_t j = 0; j < facets_out.size(); ++j)
{
if (sortedFace(facets_out[j]) == sortedFace(facet))
{
found2 = true;
// revert the same face in facets_out as it was done in
// outer_facets_out
if (reverted)
{
std::array<unsigned int, 3>& facet = facets_out[j];
unsigned int temp = facet[1];
facet[1] = facet[2];
facet[2] = temp;
}
break;
}
}
if (!found2)
{
std::cout << "Outer face is not part of all faces.\n";
}
}
std::cout << "\nIn Output File: \n" << "Vertices: "
<< vertices_out.size() << "\n"
<< "Facets/Triangles: " << facets_out.size() << "\n"
<< "Outer Facets/Triangles: " << outer_facets_out.size() << "\n"
<< "Cells/Tethraedra: " << cells_out.size() << "\n";
return true;
}
// The same as the other generateMesh() but uses a CGAL Polyhedron.
// Calling createPolyhedron() and this method is equal to the other
// generateMesh().
bool generateMeshFromCGALPolyhedron(
Polyhedron& p,
Vectors& vertices_out,
Faces& outer_facets_out,
Faces& facets_out,
Cells& cells_out,
const MeshCriteria& meshCriteria)
{
if (meshCriteria.isEdgesAsFeatures())
{
typedef CGAL::Polyhedral_mesh_domain_with_features_3<K> Mesh_domain;
// Create domain
Mesh_domain domain(p, p);
domain.detect_features(meshCriteria.getMinFeatureEdgeAngleDeg());
return generateMeshFromCGALPolyhedron(
domain, vertices_out, outer_facets_out, facets_out, cells_out,
meshCriteria);
}
else
{
typedef CGAL::Polyhedral_mesh_domain_3<Polyhedron, K> Mesh_domain;
// Create domain
Mesh_domain domain(p);
return generateMeshFromCGALPolyhedron(
domain, vertices_out, outer_facets_out, facets_out, cells_out,
meshCriteria);
}
}
bool MeshConverter::generateMesh(
const Vectors& vertices,
const Faces& facets,
Vectors& vertices_out,
Faces& outer_facets_out,
Faces& facets_out,
Cells& cells_out,
const MeshCriteria& meshCriteria)
{
std::cout << "Input: \n "
<< "Vertices: " << vertices.size() << "\n"
<< "Facets/Triangles: " << facets.size() << "\n";
vertices_out.clear();
outer_facets_out.clear();
facets_out.clear();
cells_out.clear();
Polyhedron p = createPolyhedron(vertices, facets);
std::cout << "\nAfter Conversion to Polyhedron: \n"
<< "Vertices: " << p.size_of_vertices() << "\n"
<< "Facets/Triangles: " << p.size_of_facets() << "\n";
return generateMeshFromCGALPolyhedron(
p, vertices_out, outer_facets_out, facets_out, cells_out, meshCriteria);
}
| [
"daniel.roth@mailbase.info"
] | daniel.roth@mailbase.info |
6e55e2dc3ea65bb6db5ecbb007c678469ba972a3 | 2e5c33f159adf150b67ef1b19f14607d2d11f1fe | /engine/renderers/opengl/OpenGLFrameBuffer.cpp | 5fffdb39c9aa8bad3d774b7a93eba6827553acba | [
"Apache-2.0"
] | permissive | AeonGames/AeonEngine | 29fedf6dcba2548e594ec067f99c834d8f975f27 | 2cdbf540227c1c4bbf4d893145627564dbb2a8a3 | refs/heads/master | 2023-07-22T01:35:42.972067 | 2023-07-19T01:47:20 | 2023-07-19T01:47:20 | 54,066,866 | 17 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 4,434 | cpp | /*
Copyright (C) 2019,2021 Rodrigo Jose Hernandez Cordoba
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "aeongames/ProtoBufClasses.h"
#include "OpenGLFrameBuffer.h"
namespace AeonGames
{
OpenGLFrameBuffer::OpenGLFrameBuffer() = default;
OpenGLFrameBuffer::~OpenGLFrameBuffer()
{
Finalize();
}
void OpenGLFrameBuffer::Initialize()
{
// Frame Buffer
glGenFramebuffers ( 1, &mFBO );
OPENGL_CHECK_ERROR_THROW;
glBindFramebuffer ( GL_FRAMEBUFFER, mFBO );
OPENGL_CHECK_ERROR_THROW;
// Color Buffer
glGenTextures ( 1, &mColorBuffer );
OPENGL_CHECK_ERROR_THROW;
glBindTexture ( GL_TEXTURE_2D, mColorBuffer );
OPENGL_CHECK_ERROR_THROW;
glTexImage2D ( GL_TEXTURE_2D, 0, GL_RGB, 800, 600, 0, GL_RGB, GL_UNSIGNED_BYTE, nullptr );
OPENGL_CHECK_ERROR_THROW;
glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
OPENGL_CHECK_ERROR_THROW;
glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
OPENGL_CHECK_ERROR_THROW;
glBindTexture ( GL_TEXTURE_2D, 0 );
OPENGL_CHECK_ERROR_THROW;
glFramebufferTexture2D ( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, mColorBuffer, 0 );
OPENGL_CHECK_ERROR_THROW;
// Render Buffer
glGenRenderbuffers ( 1, &mRBO );
OPENGL_CHECK_ERROR_THROW;
glBindRenderbuffer ( GL_RENDERBUFFER, mRBO );
OPENGL_CHECK_ERROR_THROW;
glRenderbufferStorage ( GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, 800, 600 );
OPENGL_CHECK_ERROR_THROW;
glBindRenderbuffer ( GL_RENDERBUFFER, 0 );
OPENGL_CHECK_ERROR_THROW;
glFramebufferRenderbuffer ( GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, mRBO );
OPENGL_CHECK_ERROR_THROW;
if ( glCheckFramebufferStatus ( GL_FRAMEBUFFER ) != GL_FRAMEBUFFER_COMPLETE )
{
throw std::runtime_error ( "Incomplete Framebuffer." );
}
OPENGL_CHECK_ERROR_THROW;
glBindFramebuffer ( GL_FRAMEBUFFER, 0 );
OPENGL_CHECK_ERROR_THROW;
}
void OpenGLFrameBuffer::Finalize()
{
if ( glIsRenderbuffer ( mRBO ) )
{
OPENGL_CHECK_ERROR_NO_THROW;
glDeleteRenderbuffers ( 1, &mRBO );
OPENGL_CHECK_ERROR_NO_THROW;
mRBO = 0;
}
if ( glIsTexture ( mColorBuffer ) )
{
OPENGL_CHECK_ERROR_NO_THROW;
glDeleteTextures ( 1, &mColorBuffer );
OPENGL_CHECK_ERROR_NO_THROW;
mColorBuffer = 0;
}
if ( glIsFramebuffer ( mFBO ) )
{
OPENGL_CHECK_ERROR_NO_THROW;
glDeleteFramebuffers ( 1, &mFBO );
OPENGL_CHECK_ERROR_NO_THROW;
mFBO = 0;
}
OPENGL_CHECK_ERROR_NO_THROW;
}
void OpenGLFrameBuffer::Resize ( uint32_t aWidth, uint32_t aHeight )
{
glBindTexture ( GL_TEXTURE_2D, mColorBuffer );
glTexImage2D ( GL_TEXTURE_2D, 0, GL_RGB, aWidth, aHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, nullptr );
glBindRenderbuffer ( GL_RENDERBUFFER, mRBO );
glRenderbufferStorage ( GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, aWidth, aHeight );
glBindRenderbuffer ( GL_RENDERBUFFER, 0 );
}
void OpenGLFrameBuffer::Bind()
{
glBindFramebuffer ( GL_FRAMEBUFFER, mFBO );
OPENGL_CHECK_ERROR_NO_THROW;
}
void OpenGLFrameBuffer::Unbind()
{
glBindFramebuffer ( GL_FRAMEBUFFER, 0 );
OPENGL_CHECK_ERROR_NO_THROW;
}
GLuint OpenGLFrameBuffer::GetFBO() const
{
return mFBO;
}
OpenGLFrameBuffer::OpenGLFrameBuffer ( OpenGLFrameBuffer&& aOpenGLFrameBuffer )
{
std::swap ( mFBO, aOpenGLFrameBuffer.mFBO );
std::swap ( mColorBuffer, aOpenGLFrameBuffer.mColorBuffer );
std::swap ( mRBO, aOpenGLFrameBuffer.mRBO );
}
}
| [
"kwizatz@aeongames.com"
] | kwizatz@aeongames.com |
da4cfc2bd5206067402ebf416915dbe29392fd73 | 35db93efa1c425ce1073c15474729b46a3cc173f | /src/server/modules/parser.h | e15d502c61b4ae18c0d6cb8936b1a0bca668a1d4 | [] | no_license | Plasmarobo/SkyfullOfMetal | e0a0c6ca8ee30a9c9e220724ef85b22ded974420 | 6ef2d3ae44fb6e643f727f6bef7d7d2dc0d50be1 | refs/heads/master | 2021-01-22T06:23:02.435407 | 2017-06-02T16:04:37 | 2017-06-02T16:04:37 | 92,546,688 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 201 | h | #ifndef MODULE_PARSER_H
#define MODULE_PARSER_H
#include <flatbuffers/idl.h>
#include <flatbuffers/util.h>
#include <flatbuffers/flatbuffers.h>
class ModuleParser {
};
#endif /* MODULE_PARSER_H */
| [
"austen@thelevelup.com"
] | austen@thelevelup.com |
e44b3505659ac4e0be1bf709a843ef8202ead677 | 492976adfdf031252c85de91a185bfd625738a0c | /src/Game/AI/AI/aiPriestBossBowEquiped.cpp | d6c684f5b55bfdcf8e240e054eb9373660cc205f | [] | no_license | zeldaret/botw | 50ccb72c6d3969c0b067168f6f9124665a7f7590 | fd527f92164b8efdb746cffcf23c4f033fbffa76 | refs/heads/master | 2023-07-21T13:12:24.107437 | 2023-07-01T20:29:40 | 2023-07-01T20:29:40 | 288,736,599 | 1,350 | 117 | null | 2023-09-03T14:45:38 | 2020-08-19T13:16:30 | C++ | UTF-8 | C++ | false | false | 555 | cpp | #include "Game/AI/AI/aiPriestBossBowEquiped.h"
namespace uking::ai {
PriestBossBowEquiped::PriestBossBowEquiped(const InitArg& arg) : BowEquiped(arg) {}
PriestBossBowEquiped::~PriestBossBowEquiped() = default;
bool PriestBossBowEquiped::init_(sead::Heap* heap) {
return BowEquiped::init_(heap);
}
void PriestBossBowEquiped::enter_(ksys::act::ai::InlineParamPack* params) {
BowEquiped::enter_(params);
}
void PriestBossBowEquiped::leave_() {
BowEquiped::leave_();
}
void PriestBossBowEquiped::loadParams_() {}
} // namespace uking::ai
| [
"leo@leolam.fr"
] | leo@leolam.fr |
aa479687ab9f0098112b9af148ce1b659518bcfc | ac316dc53e018ee84008fe2cdacc75c73cb4a12a | /data_structure&algorithms/DataStructure&Algorithms/02_list/include/list/list_deduplicate.h | 0ce48e08b2c10d212f775b3fc11165b1ccb1db94 | [] | no_license | shixu312349410/vscode_cplusplus | 7701913254aa1754dc0853716338d4cf8536e31d | a961759431054d58a0eb9edc27f5957f55b2d83a | refs/heads/master | 2023-03-18T02:07:38.104946 | 2021-03-09T12:45:44 | 2021-03-09T12:45:44 | 339,215,392 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 824 | h | /******************************************************************************************
* Data Structures in C++
* ISBN: 7-302-33064-6 & 7-302-33065-3 & 7-302-29652-2 & 7-302-26883-3
* Junhui DENG, deng@tsinghua.edu.cn
* Computer Science & Technology, Tsinghua University
* Copyright (c) 2003-2019. All rights reserved.
******************************************************************************************/
#pragma once
template <typename T> int List<T>::deduplicate() {
int oldSize = _size;
ListNodePosi(T) p = first();
for ( Rank r = 0; p != trailer; p = p->succ ) //O(n)
if ( ListNodePosi(T) q = find(p->data, r, p) )
remove(q); //此时q与p雷同,但删除前者更为简明
else r++; //r为无重前缀的长度
return oldSize - _size; //删除元素总数
} | [
"312349410@qq.com"
] | 312349410@qq.com |
4965a320997643f9190a8df49fc01217216091c5 | a0423109d0dd871a0e5ae7be64c57afd062c3375 | /Aplicacion Movil/generated/bundles/login-transition/build/Android/Preview/app/src/main/include/OpenGL.GLTextureParameterValue.h | dcf65e94720302d8a6a3d130be7b98dba9a429bc | [
"Apache-2.0"
] | permissive | marferfer/SpinOff-LoL | 1c8a823302dac86133aa579d26ff90698bfc1ad6 | a9dba8ac9dd476ec1ef94712d9a8e76d3b45aca8 | refs/heads/master | 2020-03-29T20:09:20.322768 | 2018-10-09T10:19:33 | 2018-10-09T10:19:33 | 150,298,258 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 376 | h | // This file was generated based on C:/Users/JuanJose/AppData/Local/Fusetools/Packages/UnoCore/1.9.0/Source/OpenGL/GLEnums.uno.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Uno.Int.h>
namespace g{
namespace OpenGL{
// public extern enum GLTextureParameterValue :89
uEnumType* GLTextureParameterValue_typeof();
}} // ::g::OpenGL
| [
"mariofdezfdez@hotmail.com"
] | mariofdezfdez@hotmail.com |
7673470c67788a4ebf842044ef7897045e7d43ea | 1f752f8b0131d45ef869cc2e78618494ee1df8f4 | /src/gasnet_handlers.cpp | 10dd400d7d988214b77f86a15939ff49fe7c8795 | [] | no_license | vainamon/DSTM_P1 | e51682aba7ddaa0c37b73873533f340f14bd376f | 5dea9122dbcae336f5bbd5dca4dd7eed6730028e | refs/heads/master | 2020-04-04T10:28:21.974659 | 2018-11-02T11:35:17 | 2018-11-02T11:35:17 | 155,856,244 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,734 | cpp | /*
* gasnet_handlers.cpp
*
* Created on: 12.09.2011
* Author: igor
*/
#include "gasnet_handlers.h"
#include "dstm_gasnet_appl_wrapper.h"
#include "profiling.h"
#include "glue.h"
#include "dstm_malloc/dstm_malloc.h"
#include <gasnet_handler.h>
namespace dstm_pthread
{
#include "dstm_pthread/dstm_pthread.h"
}
Application* GLOBAL_APPLICATION;
int GLOBAL_END_EXECUTION = 0;
#ifdef TRANSACTIONS_STATS
#include "dstm_stats.h"
volatile int GLOBAL_RETRIVE_STATS = 0;
#endif
DEFINE_HANDLER_TIME_PROFILING(spawnthread, 1)
int
gasnet_handlers_init(Application* __application)
{
GLOBAL_APPLICATION = __application;
}
typedef void(*handler_func)();
gasnet_handlerentry_t htable[] = {
{ hidx_endexec_shrthandler, (handler_func)endexec_shrthandler },
{ hidx_endexec_succ_shrthandler, (handler_func)endexec_succ_shrthandler },
{ hidx_spawnthread_medhandler, (handler_func)spawnthread_medhandler },
{ hidx_spawnthread_succ_medhandler, (handler_func)spawnthread_succ_medhandler },
{ hidx_threadexited_shrthandler, (handler_func)threadexited_shrthandler },
{ hidx_threadexited_succ_shrthandler, (handler_func)threadexited_succ_shrthandler },
{ hidx_requestlocks_medhandler, (handler_func)requestlocks_medhandler },
{ hidx_requestlocks_succ_medhandler, (handler_func)requestlocks_succ_medhandler },
{ hidx_dstmfree_medhandler, (handler_func)dstmfree_medhandler },
{ hidx_dstmfree_succ_medhandler, (handler_func)dstmfree_succ_medhandler },
{ hidx_dstmmalloc_shrthandler, (handler_func)dstmmalloc_shrthandler },
{ hidx_dstmmalloc_succ_shrthandler, (handler_func)dstmmalloc_succ_shrthandler },
{ hidx_dstmstats_medhandler, (handler_func)dstmstats_medhandler },
{ hidx_dstmstats_succ_medhandler, (handler_func)dstmstats_succ_medhandler },
};
void
spawnthread_medhandler (gasnet_token_t token, void *buf, size_t nbytes, harg_t gtid)
{
BEGIN_TIME_PROFILING();
gasnet_node_t node;
gasnet_AMGetMsgSource(token, &node);
int ltid = 0;
if(GLOBAL_APPLICATION != 0){
ltid = GLOBAL_APPLICATION->runChildThread(buf, node, gtid);
}
GASNET_Safe(gasnet_AMReplyMedium1
(token, hidx_spawnthread_succ_medhandler, buf, nbytes, ltid));
END_TIME_PROFILING("");
}
void
spawnthread_succ_medhandler (gasnet_token_t token, void *buf, size_t nbytes, harg_t ltid)
{
BEGIN_TIME_PROFILING();
gasnet_node_t node;
gasnet_AMGetMsgSource(token, &node);
#ifdef LOGGING
VLOG(3)<<"Inside function "<<__PRETTY_FUNCTION__<<" from node = "<<node<<" ltid = "<<ltid;
#endif
int gtid = *dstm_pthread::newthread_ptr_t(buf)->__new_thread;
DSTMGASNetApplWrapper* applWrp = (DSTMGASNetApplWrapper*)(GLOBAL_APPLICATION);
Application::application_thread_ptr_t thread_ptr;
if(applWrp->inLocalThreads(gtid))
thread_ptr = applWrp->getLocalThread(gtid);
else
if(applWrp->inRemoteThreads(gtid))
thread_ptr = applWrp->getRemoteThread(gtid);
thread_ptr->ltid = ltid;
if(thread_ptr->state == Application::RUNNABLE)
thread_ptr->state = Application::RUNNING;
END_HANDLER_TIME_PROFILING(spawnthread, gtid);
END_TIME_PROFILING("");
}
void
threadexited_shrthandler (gasnet_token_t token, harg_t gtid, harg_t state)
{
#ifdef LOGGING
VLOG(3)<<"Inside function "<<__PRETTY_FUNCTION__<<" GTID = "<<gtid<<" state = "<<state;
#endif
BEGIN_TIME_PROFILING();
gasnet_node_t node;
gasnet_AMGetMsgSource(token, &node);
DSTMGASNetApplWrapper* applWrp = (DSTMGASNetApplWrapper*)(GLOBAL_APPLICATION);
if(applWrp->inLocalThreads(gtid)){
applWrp->getLocalThread(gtid)->state = state;
}else{
applWrp->getRemoteThread(gtid)->state = state;
}
GASNET_Safe(gasnet_AMReplyShort2
(token, hidx_threadexited_succ_shrthandler, gtid, state));
END_TIME_PROFILING("");
}
void
threadexited_succ_shrthandler (gasnet_token_t token, harg_t gtid, harg_t state)
{
}
void
requestlocks_medhandler(gasnet_token_t token, void* buf, size_t nbytes)
{
uint64_t* objects_versions = (uint64_t*)buf;
uint64_t* result = glue::processLocksRequest(objects_versions, nbytes);
if(result == NULL)
GASNET_Safe(gasnet_AMReplyMedium1
(token, hidx_requestlocks_succ_medhandler, buf, sizeof(uintptr_t), 0));
else {
/// first element - tx descriptor
result[0] = *((uint64_t*)buf);
GASNET_Safe(gasnet_AMReplyMedium1
(token, hidx_requestlocks_succ_medhandler, result, (result[1]+2)*sizeof(uint64_t), result[1]));
free(result);
}
}
void
requestlocks_succ_medhandler(gasnet_token_t, void* buf, size_t, harg_t nobjs)
{
uint64_t *tx = (uint64_t*)buf;
uint64_t *changedObjects = (uint64_t*)buf+2;
glue::locksRequestProcessed((uintptr_t)*tx, changedObjects, nobjs);
}
void
dstmfree_medhandler(gasnet_token_t token, void* buf, size_t nbytes)
{
glue::dstm_mallocFree(*((uint64_t*)buf));
GASNET_Safe(gasnet_AMReplyMedium0(token,hidx_dstmfree_succ_medhandler,NULL,0));
}
void
dstmfree_succ_medhandler(gasnet_token_t token, void* buf, size_t nbytes)
{
}
void
dstmmalloc_shrthandler(gasnet_token_t token, harg_t size,
harg_t remote_ptr_h, harg_t remote_ptr_l, harg_t remote_mutex_h,
harg_t remote_mutex_l) {
uintptr_t ptr;
ptr = glue::dstm_mallocMalloc(size);
/* fprintf(stderr, "%s size %d _ptr %p mutex %p ptr %p\n", __PRETTY_FUNCTION__, size,
UNPACK2(remote_ptr_h, remote_ptr_l),
UNPACK2(remote_mutex_h, remote_mutex_l),
ptr);
*/
GASNET_Safe(gasnet_AMReplyShort6(token,hidx_dstmmalloc_succ_shrthandler,
remote_ptr_h,remote_ptr_l,remote_mutex_h,remote_mutex_l,
GASNETI_HIWORD(ptr),GASNETI_LOWORD(ptr)));
}
void
dstmmalloc_succ_shrthandler(gasnet_token_t, harg_t ptr_h, harg_t ptr_l,
harg_t mutex_h, harg_t mutex_l, harg_t returned_ptr_h,
harg_t returned_ptr_l) {
uintptr_t* ptr = (uintptr_t*)UNPACK2(ptr_h,ptr_l);
*ptr = (uintptr_t)UNPACK2(returned_ptr_h,returned_ptr_l);
/*
fprintf(stderr, "%s _ptr %p mutex %p ptr %p\n", __PRETTY_FUNCTION__,
UNPACK2(ptr_h, ptr_l),
UNPACK2(mutex_h, mutex_l),
*ptr);
*/
uintptr_t *mtx = (uintptr_t*)UNPACK2(mutex_h,mutex_l);
*mtx = 1;
//gasnett_mutex_unlock((gasnett_mutex_t*) UNPACK2(mutex_h,mutex_l));
}
void
endexec_shrthandler(gasnet_token_t token)
{
GLOBAL_END_EXECUTION = 1;
GASNET_Safe(gasnet_AMReplyShort0(token,hidx_endexec_succ_shrthandler));
}
void
endexec_succ_shrthandler(gasnet_token_t token)
{
}
void
dstmstats_medhandler(gasnet_token_t token, void* buf, size_t nbytes)
{
#ifdef TRANSACTIONS_STATS
gasnet_node_t node;
gasnet_AMGetMsgSource(token, &node);
add_node_to_stat(node,*(node_stats_t*)buf);
GLOBAL_RETRIVE_STATS++;
#endif
}
void
dstmstats_succ_medhandler(gasnet_token_t token, void* buf, size_t nbytes)
{
}
| [
"vainamon@gmail.com"
] | vainamon@gmail.com |
5718606275e2839bab174ded6cdd024eaccb9dc6 | a3ca1f53459ef5bc3653f900d7381c2615c51ad9 | /Bhalim1.cpp | dc7cc3ef9374273e56cfe963fcd7c1acb173473e | [] | no_license | giongto35/CompetitveProgramming | cf7b02dfaecb46c4c949d903675817cd9c2e141b | 29b7cdf7796d4054f5e74d2bce7e0247a21968e8 | refs/heads/master | 2021-01-20T23:32:38.627994 | 2015-01-30T17:07:56 | 2015-01-30T17:07:56 | 30,082,220 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,460 | cpp | #include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <sstream>
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <queue>
using namespace std ;
#define FOREACH(it,c) for( __typeof((c).begin()) it=(c).begin();it!=(c).end();it++)
#define FOR(i,a,b) for( int i=(a),_b=(b);i<=_b;i++)
#define DOW(i,b,a) for( int i=(b),_a=(a);i>=_a;i--)
#define REP(i,n) FOR(i,0,(n)-1)
#define DEP(i,n) DOW(i,(n)-1,0)
#define all(a) (a).begin() , (a).end()
#define push(a,b) (a).push_back((b))
typedef vector<int> VI ;
typedef vector<string> VS ;
template<class T> inline int size(const T&c) { return c.size(); }
using namespace std;
const int maxn=300000+10;
int a[maxn],s[maxn],n,cs,j,T;
int res;
int main()
{
freopen("Bhalim1.inp","r",stdin);
//freopen("Bhalim1.out","w",stdout);
while (scanf("%d%d", &n,&cs) ==2)
{
FOR(i,1,n) {
cin>>a[i];
s[i]=s[i-1]+a[i];
}
j=1;
res=n+1;
FOR(i,1,n)
{
while (s[i]-s[j]>=cs) j++;
if (s[i]-s[j-1]>=cs)
res=min(res,i-j+1);
}
if (res==n+1) cout<<0; else cout<<res;
cout<<endl;
T--;
}
fclose(stdin);
fclose(stdout);
return 0;
}
| [
"giongto35@yahoo.com"
] | giongto35@yahoo.com |
d753c11cf26f5d85d557b8074c859a9de565b06a | a864b84c706a4432a3a3cf9dd11e3c940bb53860 | /Activation.h | 64afa56355d2c309377ac3a87a17bac242610e12 | [] | no_license | NehoraM/ML-identifying-numbers | b3669cfaf3a711ee50ec362fa348060f54f49d35 | 1e76cc02d92bd47ea7ded34773481bb466d2d408 | refs/heads/master | 2022-12-22T03:01:12.314833 | 2020-09-17T12:22:51 | 2020-09-17T12:22:51 | 296,318,116 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 853 | h | #ifndef ACTIVATION_H
#define ACTIVATION_H
#include "Matrix.h"
/**
* @enum ActivationType
* @brief Indicator of activation function.
*/
enum ActivationType
{
Relu,
Softmax
};
/**
* Activates softmax or relu
*/
class Activation
{
private:
ActivationType _type;
/**
*
* @param m tha matrix
* @return relu matrix
*/
Matrix &_relu(Matrix &m);
/**
*
* @param m matrix
* @return softmax matrix
*/
Matrix &_softmax(Matrix &m);
public:
/**
*
* @param t the type
*/
Activation(ActivationType t);
/**
*
* @return the activation type
*/
ActivationType getActivationType() const;
/**
*
* @param m the matrix
* @return matrix after activation function
*/
Matrix &operator()(Matrix &m);
};
#endif //ACTIVATION_H
| [
"you@example.com"
] | you@example.com |
08123dcf3def53504de3a9891c8ca8c7be463fe1 | 854daae5dfecf40c24b9dd6aa3ff18737377804f | /Engine/ResourceSystem.cpp | bbfe499035b29b2c45d280b28fd66aecc2d4db8f | [] | no_license | northwolf521/FlipEngine1 | 51f09af960503200085884294ce2b0b6be31169d | d1e562f03ff167c3e3f4e2cc9db27c242836bd89 | refs/heads/master | 2021-01-21T09:34:11.048692 | 2015-12-09T14:07:48 | 2015-12-09T14:07:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,632 | cpp | #include "ResourceSystem.h"
#include "Image.h"
#include "ImageLoader.h"
#include "Texture.h"
#include <algorithm>
#include <iostream>
#include "MeshLoaderB3D.h"
#include "Shader.h"
#include "glutils.h"
#include "../sys/sys_public.h"
#include "Mesh.h"
#include "Material.h"
#include "File.h"
#include "Model_lwo.h"
#include "MeshLoader3DS.h"
#include "../ShaderSource.h"
static LoaderPlugin loaderPlugin[] = {
{ "jpg", loadImageJPG},
{ "png", loadImagePNG},
{ "tga", loadImageTGA},
{ "bmp", loadImageBMP},
};
static int TexPluginCount = sizeof(loaderPlugin) / sizeof(LoaderPlugin);
static Texture* defaultTexture;
//--------------------------------------------------------------------------------------------
static Shader* LoadPostionShader()
{
Shader* shader = new Shader;
shader->LoadFromBuffer(position_vert, position_frag);
shader->SetName("position");
shader->BindAttribLocation(eAttrib_Position);
shader->GetUniformLocation(eUniform_MVP);
shader->GetUniformLocation(eUniform_Color);
GL_CheckError("LoadPostionShader");
return shader;
}
static Shader* LoadPositionTexShader()
{
Shader* shader = new Shader;
shader->LoadFromBuffer(positiontex_vert, positiontex_frag);
shader->SetName("positionTex");
shader->BindAttribLocation(eAttrib_Position);
shader->BindAttribLocation(eAttrib_TexCoord);
shader->GetUniformLocation(eUniform_MVP);
shader->GetUniformLocation(eUniform_Samper0);
GL_CheckError("LoadPositionTexShader");
return shader;
}
static Shader* LoadPhongShader()
{
Shader* shader = new Shader;
shader->LoadFromFile("../media/shader/phong.vert", "../media/shader/phong.frag");
shader->SetName("phong");
shader->BindAttribLocation(eAttrib_Position);
shader->BindAttribLocation(eAttrib_TexCoord);
shader->BindAttribLocation(eAttrib_Normal);
shader->GetUniformLocation(eUniform_MVP);
shader->GetUniformLocation(eUniform_EyePos);
shader->GetUniformLocation(eUniform_LightPos);
shader->GetUniformLocation(eUniform_ModelView);
shader->GetUniformLocation(eUniform_InvModelView);
shader->GetUniformLocation(eUniform_Samper0);
GL_CheckError("load phong shader");
return shader;
}
static Shader* LoadBumpShader()
{
Shader* shader = resourceSys->AddShaderFromFile("../media/shader/bump.vert",
"../media/shader/bump.frag");
shader->SetName("bump");
shader->BindAttribLocation(eAttrib_Position);
shader->BindAttribLocation(eAttrib_TexCoord);
shader->BindAttribLocation(eAttrib_Normal);
shader->BindAttribLocation(eAttrib_Tangent);
shader->BindAttribLocation(eAttrib_Binormal);
shader->GetUniformLocation(eUniform_MVP);
shader->GetUniformLocation(eUniform_EyePos);
shader->GetUniformLocation(eUniform_LightPos);
shader->GetUniformLocation(eUniform_ModelView);
shader->GetUniformLocation(eUniform_InvModelView);
shader->GetUniformLocation(eUniform_Samper0);
shader->GetUniformLocation(eUniform_BumpMap);
return shader;
}
static Shader* LoadBlurShader()
{
Shader* shader = new Shader;
shader->LoadFromFile("../media/blur.vs", "../media/blur.fs");
shader->SetName("blur");
shader->BindAttribLocation(eAttrib_Position);
shader->BindAttribLocation(eAttrib_TexCoord);
shader->GetUniformLocation(eUniform_MVP);
shader->GetUniformLocation(eUniform_Samper0);
return shader;
}
static ShaderPlugin shaderplugin[] = {
{ eShader_Position, LoadPostionShader },
{ eShader_PositionTex, LoadPositionTexShader },
//{ eShader_Phong, LoadPhongShader },
//{ eShader_Blur, LoadBlurShader },
//{ eShader_Bump, LoadBumpShader },
};
static int ShaderPluginCount = sizeof(shaderplugin) / sizeof(ShaderPlugin);
//--------------------------------------------------------------------------------------------
static sysTextContent_t textContent;
//ResourceManager* ResourceManager::sm_pSharedInstance = nullptr;
ResourceSystem::ResourceSystem()
{
}
ResourceSystem::~ResourceSystem()
{
}
Texture* ResourceSystem::AddTexture(const char* file)
{
Texture* texture = NULL;
lfStr fullPath = file;
void* it = _textures.Get(fullPath);
if( it != NULL ) {
texture = (Texture*)it;
return texture;
}
Image image;
std::string basename(file);
std::transform(basename.begin(), basename.end(), basename.begin(), ::tolower);
for (int i = 0; i < TexPluginCount; ++i)
{
if (basename.find(loaderPlugin[i].name) == std::string::npos)
continue;
if( !loaderPlugin[i].pFunc(fullPath.c_str(), image) )
{
Sys_Printf( "load image %s failed\n", fullPath.c_str() );
return defaultTexture;
}
else
{
texture = new Texture();
texture->Init(&image);
_textures.Put(fullPath, texture);
return texture;
}
}
Sys_Printf( "load image %s failed\n", fullPath.c_str() );
return defaultTexture;
};
Mesh* ResourceSystem::AddMesh(const char* file)
{
lfStr str = file;
if (str.Find(".lwo") != -1) {
unsigned int failId;
int failedPos;
lwObject* object = lwGetObject(file, &failId, &failedPos);
Mesh* mesh = new Mesh;
mesh->ConvertLWOToModelSurfaces(object);
delete object;
return mesh;
}
else if (str.Find(".3ds") != -1)
{
return LoadMesh3DS(file);
}
else {
MeshLoaderB3D meshLoader;
meshLoader.Load(file);
return meshLoader._mesh;
}
return NULL;
}
Texture* ResourceSystem::AddText( const char* text )
{
if( Sys_DrawText(text, &textContent))
{
// get the texture pixels, width, height
Texture* texture = new Texture;
texture->Init(textContent.w, textContent.h, textContent.pData);
return texture;
}
else
{
Sys_Printf("sys_drawtext error %s\n", text);
return defaultTexture;
}
}
Shader* ResourceSystem::AddShaderFromFile( const char* vfile, const char* ffile )
{
Shader* shader = new Shader;
shader->LoadFromFile(vfile, ffile);
return shader;
}
Material* ResourceSystem::AddMaterial( const char* file )
{
Material* mtr;
lfStr fullPath = file;
auto it = _materials.Get(fullPath);
if( it != NULL ) {
mtr = (Material*) it;
return mtr;
}
mtr = new Material();
mtr->SetName(file);
const char* buffer = F_ReadFileData(file); //"../media/Position.mtr");
if (buffer == NULL)
{
Sys_Error("add material failed %s, file data is null\n", file);
return NULL;
}
mtr->LoadMemory(buffer);
_materials.Put(fullPath, mtr);
return mtr;
}
bool ResourceSystem::LoadGLResource()
{
memset(_shaders, 0, 32);
for (int i =0; i<ShaderPluginCount; i++)
{
_shaders[shaderplugin[i].name] = shaderplugin[i].func();
}
defaultTexture = AddTexture("../Media/nskinbl.jpg");
return true;
}
Shader* ResourceSystem::FindShader( int shaderId )
{
if (shaderId >= MAX_SHADER_COUNT && shaderId < 0)
{
Sys_Error("find shader out of bounds");
return NULL;
}
return _shaders[shaderId];
}
| [
"356661627@qq.com"
] | 356661627@qq.com |
433088595ef4fd484ecbf91c0a53563860fb3d28 | 391b88509968575dfa92db8220a7d0ed1a222f0d | /MFC3.23(1)/MFC3.23(1)/stdafx.cpp | 760c22e5e036d37b4c682e7998b7553a46eff0ba | [] | no_license | ZouXinyi-a/ZXY | f6b6d65f3431b20f046ed3bb46117376c3795c8d | 03772e5569e21bac14d097192f648bce026bd2be | refs/heads/master | 2022-11-07T22:38:15.876992 | 2020-07-02T14:54:47 | 2020-07-02T14:54:47 | 265,002,732 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 169 | cpp |
// stdafx.cpp : 只包括标准包含文件的源文件
// MFC3.23(1).pch 将作为预编译头
// stdafx.obj 将包含预编译类型信息
#include "stdafx.h"
| [
"1749883446.qq.com@example.com"
] | 1749883446.qq.com@example.com |
6cfb044fe7c8836b3bba8677a5d83e069aa0f7ac | 05b72d3eb9bc9b836aea86045cef02f17b3de3ea | /src/graf/grafDrawer.cpp | 5d5c334c47097be35346e0bd0b4017af88542360 | [] | no_license | jjzhang166/GA_Interactive | 9b234c3611c041b9cc5e09a8e931678068af6b7a | c0fbb5f61d62727e56c70d0869c8af7bc9e9b010 | refs/heads/master | 2021-12-02T04:53:53.309527 | 2010-06-29T22:05:57 | 2010-06-29T22:05:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,478 | cpp | #include "grafDrawer.h"
grafDrawer::grafDrawer()
{
alpha = 1.f;
minLen = .005;
lineWidth = 2.0;
lineAlpha = .92;
lineScale = .05;
bSetupDrawer = false;
pctTransLine = .001;
flatTime = 0;
}
grafDrawer::~grafDrawer()
{
for( int i = 0; i < lines.size(); i++)
delete lines[i];
}
void grafDrawer::setup(grafTagMulti * myTag, float maxLen )
{
alpha = 1.f;
if( myTag->myStrokes.size() == 0 ) return;
if( lines.size() > 0 )
{
for( int i = 0; i < lines.size(); i++)
delete lines[i];
}
lines.clear();
for( int i = 0; i < myTag->myStrokes.size(); i++)
{
lines.push_back( new grafLineDrawer() );
}
for( int i = 0; i < myTag->myStrokes.size(); i++)
{
lines[i]->globalAlpha = lineAlpha;
lines[i]->lineScale = lineScale;
lines[i]->setup( myTag->myStrokes[i].pts, minLen, maxLen, .5f);
}
bSetupDrawer = false;
pctTransLine = .001;
}
void grafDrawer::setAlpha(float a)
{
lineAlpha = a;
for( int i = 0; i < lines.size(); i++)
{
lines[i]->globalAlpha = lineAlpha;
}
}
void grafDrawer::setLineScale(float val)
{
if( lineScale != val )
{
lineScale = val;
for( int i = 0; i < lines.size(); i++)
{
lines[i]->lineScale = val;
}
bSetupDrawer = true;
}
}
void grafDrawer::transition( float dt, float pct )
{
average(pct);
//alpha -= .35*dt;
}
void grafDrawer::transitionDeform( float dt, float pct, float * amps, int numAmps )
{
float pctMe = 1-pctTransLine;
float pctLn = pctTransLine;
for( int i = 0; i < lines.size(); i++)
{
for( int j = 0; j < lines[i]->pts_l.size(); j++)
{
int ps = 1+(j % (numAmps-1));
float bandH = pct*(amps[ps]);
lines[i]->pts_l[j].y = pctMe*lines[i]->pts_l[j].y+pctLn*(lines[i]->pts_lo[j].y+bandH);//.9*lines[i]->pts_l[j].y+.1*bandH;
lines[i]->pts_r[j].y = pctMe*lines[i]->pts_r[j].y+pctLn*(lines[i]->pts_ro[j].y+bandH);//.9*lines[i]->pts_r[j].y+.1*bandH;
lines[i]->pts_lout[j].y = pctMe*lines[i]->pts_lout[j].y+pctLn*(lines[i]->pts_lo[j].y+bandH);//.9*lines[i]->pts_l[j].y+.1*bandH;
lines[i]->pts_rout[j].y = pctMe*lines[i]->pts_rout[j].y+pctLn*(lines[i]->pts_ro[j].y+bandH);//.9*lines[i]->pts_r[j].y+.1*bandH;
}
}
//if( pctTransLine < .1 ) pctTransLine += .001;
}
void grafDrawer::transitionLineWidth( float dt, float avg )
{
float pctMe = 1-pctTransLine;
float pctLn = pctTransLine;
for( int i = 0; i < lines.size(); i++)
{
for( int j = 0; j < lines[i]->pts_l.size(); j++)
{
lines[i]->pts_l[j].x = pctMe*lines[i]->pts_l[j].x+pctLn*(lines[i]->pts_lo[j].x+avg*-lines[i]->vecs[j].x);
lines[i]->pts_l[j].y = pctMe*lines[i]->pts_l[j].y+pctLn*(lines[i]->pts_lo[j].y+avg*-lines[i]->vecs[j].y);
lines[i]->pts_r[j].x = pctMe*lines[i]->pts_r[j].x+pctLn*(lines[i]->pts_ro[j].x+avg*lines[i]->vecs[j].x);
lines[i]->pts_r[j].y = pctMe*lines[i]->pts_r[j].y+pctLn*(lines[i]->pts_ro[j].y+avg*lines[i]->vecs[j].y);
lines[i]->pts_lout[j].x = pctMe*lines[i]->pts_lout[j].x+pctLn*(lines[i]->pts_lo[j].x+avg*-lines[i]->vecs[j].x);
lines[i]->pts_lout[j].y = pctMe*lines[i]->pts_lout[j].y+pctLn*(lines[i]->pts_lo[j].y+avg*-lines[i]->vecs[j].y);
lines[i]->pts_rout[j].x = pctMe*lines[i]->pts_rout[j].x+pctLn*(lines[i]->pts_ro[j].x+avg*lines[i]->vecs[j].x);
lines[i]->pts_rout[j].y = pctMe*lines[i]->pts_rout[j].y+pctLn*(lines[i]->pts_ro[j].y+avg*lines[i]->vecs[j].y);
}
}
//if( pctTransLine < .1 ) pctTransLine += .001;
//alpha -= .35*dt;
}
void grafDrawer::transitionBounce( float dt, float avg )
{
float pctMe = 1-pctTransLine;
float pctLn = pctTransLine;
for( int i = 0; i < lines.size(); i++)
{
for( int j = 0; j < lines[i]->pts_l.size(); j++)
{
lines[i]->pts_l[j].y = pctMe*lines[i]->pts_l[j].y+pctLn*(lines[i]->pts_lo[j].y+avg);
lines[i]->pts_r[j].y = pctMe*lines[i]->pts_r[j].y+pctLn*(lines[i]->pts_ro[j].y+avg);
lines[i]->pts_lout[j].y = pctMe*lines[i]->pts_lout[j].y+pctLn*(lines[i]->pts_lo[j].y+avg);
lines[i]->pts_rout[j].y = pctMe*lines[i]->pts_rout[j].y+pctLn*(lines[i]->pts_ro[j].y+avg);
}
}
//if( pctTransLine < .1 ) pctTransLine += .001;
//alpha -= .35*dt;
}
void grafDrawer::transitionFlatten( float zDepth, float timeToDoIt )
{
if( flatTime == 0 )
flatTime = ofGetElapsedTimef();
float pct = 1 - ((ofGetElapsedTimef()-flatTime) / timeToDoIt);
for( int i = 0; i < lines.size(); i++)
{
for( int j = 0; j < lines[i]->pts_l.size(); j++)
{
lines[i]->pts_l[j].z = pct*lines[i]->pts_l[j].z + (1-pct)*zDepth;
lines[i]->pts_r[j].z = pct*lines[i]->pts_r[j].z + (1-pct)*zDepth;
lines[i]->pts_lout[j].z = pct*lines[i]->pts_lout[j].z + (1-pct)*zDepth;
lines[i]->pts_rout[j].z = pct*lines[i]->pts_rout[j].z + (1-pct)*zDepth;
}
}
}
void grafDrawer::resetTransitions()
{
pctTransLine =.001;
prelimTransTime = 0;
flatTime = 0;
}
void grafDrawer::average( float pct )
{
for( int i = 0; i < lines.size(); i++)
lines[i]->average(pct);
}
void grafDrawer::draw( int lastStroke, int lastPoint)
{
glEnable( GL_DEPTH_TEST);
for( int i = 0; i < lines.size(); i++)
{
if( i < lastStroke ) lines[i]->draw(-1,alpha);
else if( i == lastStroke ) lines[i]->draw(lastPoint,alpha);
//if( i < lastStroke ) lines[i]->drawOutline(-1,alpha,lineWidth);
//else if( i == lastStroke ) lines[i]->drawOutline(lastPoint,alpha,lineWidth);
}
glDisable( GL_DEPTH_TEST );
}
void grafDrawer::drawTimeLine(ofPoint center, float currentTime, float startTime, float z_const, ofTrueTypeFont * font, float scale )
{
ofSetColor(255,255,255,255);
float timeStart = startTime;
float printTime = currentTime;
currentTime = (1000 * currentTime )/ z_const;
float linePoints[6];
linePoints[0] = center.y;
linePoints[1] = center.x;
linePoints[2] = startTime;
linePoints[3] = center.y;
linePoints[4] = center.x;
linePoints[5] = currentTime;
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, 0, &linePoints[0]);
glDrawArrays(GL_LINES, 0, 2);
float h = .010;
int count = 0;
for( float t = timeStart; t < currentTime; t += (300 / z_const))
{
if( count % 2 == 0) h = .020;
else h = .010;
linePoints[2] = t;
linePoints[3] = center.y+h;
linePoints[5] = t;
glVertexPointer(3, GL_FLOAT, 0, &linePoints[0]);
glDrawArrays(GL_LINES, 0, 2);
count++;
}
// h = .030;
glDisableClientState(GL_VERTEX_ARRAY);
glPushMatrix();
glTranslatef(center.y,center.x,currentTime);
glRotatef(90,0,0,1);
glScalef(.5 * (1.0/scale),.5 * (1.0/scale),0);
font->drawString( ofToString( printTime, 2 ) , 2,0);
glPopMatrix();
}
void grafDrawer::drawBoundingBox( ofPoint pmin, ofPoint pmax, ofPoint pcenter )
{
glColor4f(1,1,1,1);
// draw cube
float pos[18];
glEnableClientState(GL_VERTEX_ARRAY);
// front
pos[0] = pmin.x;
pos[1] = pmax.y;
pos[2] = pmin.z;
pos[3] = pmax.x;
pos[4] = pmax.y;
pos[5] = pmin.z;
pos[6] = pmax.x;
pos[7] = pmin.y;
pos[8] = pmin.z;
pos[9] = pmin.x;
pos[10] = pmin.y;
pos[11] = pmin.z;
glVertexPointer(3, GL_FLOAT, 0, pos);
glDrawArrays(GL_LINE_LOOP, 0, 4);
// back
pos[0] = pmin.x;
pos[1] = pmax.y;
pos[2] = pmax.z;
pos[3] = pmax.x;
pos[4] = pmax.y;
pos[5] = pmax.z;
pos[6] = pmax.x;
pos[7] = pmin.y;
pos[8] = pmax.z;
pos[9] = pmin.x;
pos[10] = pmin.y;
pos[11] = pmax.z;
glVertexPointer(3, GL_FLOAT, 0, pos);
glDrawArrays(GL_LINE_LOOP, 0, 4);
// top
pos[0] = pmin.x;
pos[1] = pmax.y;
pos[2] = pmin.z;
pos[3] = pmin.x;
pos[4] = pmax.y;
pos[5] = pmax.z;
pos[6] = pmax.x;
pos[7] = pmin.y;
pos[8] = pmin.z;
pos[9] = pmax.x;
pos[10] = pmin.y;
pos[11] = pmax.z;
glVertexPointer(3, GL_FLOAT, 0, pos);
glDrawArrays(GL_LINE_LOOP, 0, 4);
// bottom
pos[0] = pmin.x;
pos[1] = pmin.y;
pos[2] = pmin.z;
pos[3] = pmin.x;
pos[4] = pmin.y;
pos[5] = pmax.z;
pos[6] = pmax.x;
pos[7] = pmin.y;
pos[8] = pmax.z;
pos[9] = pmax.x;
pos[10] = pmin.y;
pos[11] = pmin.z;
pos[12] = pmin.x;
pos[13] = pmin.y;
pos[14] = pmin.z;
glVertexPointer(3, GL_FLOAT, 0, pos);
glDrawArrays(GL_LINE_LOOP, 0, 5);
// centered
/*pos[0] = pcenter.x-100;
pos[1] = pcenter.y;
pos[2] = pcenter.z;
pos[3] = pcenter.x+100;
pos[4] = pcenter.y;
pos[5] = pcenter.z;
pos[6] = pcenter.x;
pos[7] = pcenter.y-100;
pos[8] = pcenter.z;
pos[9] = pcenter.x;
pos[10] = pcenter.y+100;
pos[11] = pcenter.z;*/
//glVertexPointer(3, GL_FLOAT, 0, pos);
//glDrawArrays(GL_LINES, 0, 4);
glDisable(GL_VERTEX_ARRAY);
}
| [
"csugrue@gmail.com"
] | csugrue@gmail.com |
fa9b7417f2021108ace1368a3680d6a79aa8ffee | 511a4a9bebd1f35731c6269a121961b9aa18d7b1 | /shaderSketch1/src/ofApp.h | efe139cfc6c2931d87f9df292525c32973c586c0 | [] | no_license | ofZach/ecalWorkshop | 0b98a6adb7a04aab6259700fcd78b366ce0594e6 | 4fb4c1a21bc24482fee5e43f65fb7367a0a85dd7 | refs/heads/main | 2023-05-01T17:43:50.543423 | 2021-05-05T18:39:27 | 2021-05-05T18:39:27 | 363,986,626 | 9 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 569 | h | #pragma once
#include "ofMain.h"
class ofApp : public ofBaseApp{
public:
void setup();
void update();
void draw();
void keyPressed(int key);
void keyReleased(int key);
void mouseMoved(int x, int y );
void mouseDragged(int x, int y, int button);
void mousePressed(int x, int y, int button);
void mouseReleased(int x, int y, int button);
void mouseEntered(int x, int y);
void mouseExited(int x, int y);
void windowResized(int w, int h);
void dragEvent(ofDragInfo dragInfo);
void gotMessage(ofMessage msg);
ofShader shader;
};
| [
"zach@sfpc.io"
] | zach@sfpc.io |
5a60c8352a5a1db085d189446ec5e8c091d1a489 | 0434508a7eb1237757b7a731d081a65559d88a0c | /FileTest2.cpp | e65414cb74eabbc1ffa8e31a49e09b07bbfe3272 | [] | no_license | poseneror/ass-spl-1 | 76c0cf72f87ce44463e0cc123a2bebf05bca062e | 2312be90cee5fc7d723f22e7563e1e67fed0d808 | refs/heads/master | 2021-09-05T19:36:47.484095 | 2018-01-30T15:54:45 | 2018-01-30T15:54:45 | 110,820,198 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,604 | cpp | //
// Created by Guy-Amit on 11/8/2017.
//
#include "Files.h"
#include "vector"
#include <string>
#include <iostream>
using namespace std;
int red=0;
vector<string> test = {"0","1","2","3","4","5","6","7","8","9"};
vector<int> testInt;
vector<string> temp;
vector<int> tempInt;
void extractVals(vector<BaseFile*> children){
temp.clear();
for (int i = 0; i <children.size() ; ++i) {
temp.push_back(children[i]->getName());
}
}
void extractValsInt(vector<BaseFile*> children){
tempInt.clear();
for (int i = 0; i <children.size() ; ++i) {
tempInt.push_back(children[i]->getSize());
}
}
template <typename T>
bool comperVec(vector<T> v1, vector<T> v2){
for (int i = 0; i <v1.size() ; ++i) {
if(v1[i]!=v2[i]) return false;
}
return true;
}
void null_check_parent(Directory root){
if(root.getParent()!= nullptr) red++;
}
int main(int , char **) {
string name="root";
Directory root(name , nullptr);
/*****************************/
/* Testing the root Directory*/
/*****************************/
null_check_parent(root);
File * f =new File("hugabuga",5);
root.addFile(f);
root.removeFile(f->getName()); //test remove by name-root should by empty after deletion
if(root.getChildren().size()>0) {red++; std::cout<<"the file hugabuga was not removed"<<std::endl; }
File * g =new File("hugabuga",5);
root.addFile(g);
root.removeFile(g); //test remove by pointer-root should be empty after deletion
if(root.getChildren().size()>0) {red++; std::cout<<"the file hugabuga was not removed"<<std::endl;}
root.removeFile("guy");
//should print "file does not exists"
std::cout<<"END of Root checks, please do not continue if there where errors"<<std::endl;
/*********************************************/
/* Testing files and directories from level 1*/
/*********************************************/
//adding files to root
for (int i = 0; i <10 ; ++i) {
root.addFile(new File(std::to_string(i),i));
}
// /addtion check
extractVals(root.getChildren());
if(!comperVec(test,temp)){
red++;
std::cout << "files addition filed" << std::endl;
}
//add same file check
try {
root.addFile(new File("0", 3));
root.addFile(new File("1", 4));
extractVals(root.getChildren());
if (!comperVec(test, temp)) {
red++;
std::cout << "you cant add the same file twice in the same directory" << std::endl;
}
}
catch(std::exception){}
//creating two directories under root
Directory* emptyDir=new Directory("emptyDir",&root);
Directory* dir1=new Directory("dir",&root);
root.addFile(emptyDir);
root.addFile(dir1);
//adding files to dir1
for (int i = 0; i <10 ; ++i) {
dir1->addFile(new File(std::to_string(i),i));
}
dir1->addFile(new File(std::to_string(10),10));
root.removeFile("1"); //should remove from root and not from dir1
test={"0","2","3","4","5","6","7","8","9","emptyDir","dir"};
extractVals(root.getChildren());
if(!comperVec(test,temp)) {
red++;
std::cout<<"the file '1' was not removed"<<std::endl;
}
//sort test
dir1->addFile(new File("01",2));
dir1->addFile(new File("02",5));
dir1->addFile(new File("00",4));
dir1->sortByName();
test={"0","00","01","02","1","10","2","3","4","5","6","7","8","9"};
extractVals(dir1->getChildren());
if(!comperVec(test,temp)) {
red++;
std::cout<<"sort by name does not work"<<std::endl;
}
dir1->sortBySize();
testInt ={0,1,2,2,3,4,4,5,5,6,7,8,9,10};
extractValsInt(dir1->getChildren());
if(!comperVec(test,temp)) {
red++;
std::cout<<"sort by size does not work"<<std::endl;
}
std::cout<<"END of level 1 checks, please do not continue if there where errors"<<std::endl;
/*********************************************/
/* Testing files and directories from level 2*/
/*********************************************/
Directory* innerDir=new Directory("innerDir",dir1);
dir1->addFile(innerDir);
std::string path_inner="/dir/innerDir";
//compare innerDir.GetAbsolutePath to path_inner
if(innerDir->getAbsolutePath()!=path_inner){
red++;
std::cout<<"absolute path is not correct"<<std::endl;
}
std::cout<<"END of level 2 checks, please do not continue if there where errors"<<std::endl;
std::cout << "the number of red test is:"<<red<<std::endl;
} | [
"posener.or@gmail.com"
] | posener.or@gmail.com |
2abb55959d4883b2ac0071a775dd0405a481eada | eda7f1e5c79682bf55cfa09582a82ce071ee6cee | /aspects/fluid/source/test/UtGunnsGasDisplacementPump.hh | 3b3455b116b293c625b6480045af302cd2c3e26c | [
"LicenseRef-scancode-us-govt-public-domain",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | nasa/gunns | 923f4f7218e2ecd0a18213fe5494c2d79a566bb3 | d5455e3eaa8b50599bdb16e4867a880705298f62 | refs/heads/master | 2023-08-30T06:39:08.984844 | 2023-07-27T12:18:42 | 2023-07-27T12:18:42 | 235,422,976 | 34 | 11 | NOASSERTION | 2023-08-30T15:11:41 | 2020-01-21T19:21:16 | C++ | UTF-8 | C++ | false | false | 7,786 | hh | #ifndef UtGunnsGasDisplacementPump_EXISTS
#define UtGunnsGasDisplacementPump_EXISTS
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @defgroup UT_TSM_GUNNS_FLUID_SOURCE_GAS_DISPLACEMENT_PUMP Gas Displacement Pump Unit Tests
/// @ingroup UT_TSM_GUNNS_FLUID_SOURCE
///
/// @copyright Copyright 2019 United States Government as represented by the Administrator of the
/// National Aeronautics and Space Administration. All Rights Reserved.
///
/// @details Unit Tests for the GUNNS Gas Displacement Pump link model.
/// @{
////////////////////////////////////////////////////////////////////////////////////////////////////
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/TestFixture.h>
#include "aspects/fluid/source/GunnsGasDisplacementPump.hh"
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Inherit from GunnsGasDisplacementPump and befriend UtGunnsGasDisplacementPump.
///
/// @details Class derived from the unit under test. It just has a constructor with the same
/// arguments as the parent and a default destructor, but it befriends the unit test case
/// driver class to allow it access to protected data members.
////////////////////////////////////////////////////////////////////////////////////////////////////
class FriendlyGunnsGasDisplacementPump : public GunnsGasDisplacementPump
{
public:
FriendlyGunnsGasDisplacementPump();
virtual ~FriendlyGunnsGasDisplacementPump();
friend class UtGunnsGasDisplacementPump;
};
inline FriendlyGunnsGasDisplacementPump::FriendlyGunnsGasDisplacementPump() : GunnsGasDisplacementPump() {};
inline FriendlyGunnsGasDisplacementPump::~FriendlyGunnsGasDisplacementPump() {}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Gas Displacement Pump unit tests.
///
/// @details This class provides the unit tests for the GUNNS Gas Displacement Pump link model
/// within the CPPUnit framework.
////////////////////////////////////////////////////////////////////////////////////////////////////
class UtGunnsGasDisplacementPump: public CppUnit::TestFixture
{
public:
/// @brief Default constructs this Gas Displacement Pump unit test.
UtGunnsGasDisplacementPump();
/// @brief Default destructs this Gas Displacement Pump unit test.
virtual ~UtGunnsGasDisplacementPump();
/// @brief Executes before each test.
void setUp();
/// @brief Executes after each test.
void tearDown();
/// @brief Tests config data.
void testConfig();
/// @brief Tests input data.
void testInput();
/// @brief Tests default construction.
void testDefaultConstruction();
/// @brief Tests initialize method.
void testNominalInitialization();
/// @brief Tests initialize method exceptions.
void testInitializationExceptions();
/// @brief Tests accessor methods.
void testAccessors();
/// @brief Tests modifier methods.
void testModifiers();
/// @brief Tests update state method.
void testUpdateState();
/// @brief Tests update fluid method.
void testUpdateFluid();
/// @brief Tests compute flows method.
void testComputeFlows();
private:
CPPUNIT_TEST_SUITE(UtGunnsGasDisplacementPump);
CPPUNIT_TEST(testConfig);
CPPUNIT_TEST(testInput);
CPPUNIT_TEST(testDefaultConstruction);
CPPUNIT_TEST(testNominalInitialization);
CPPUNIT_TEST(testInitializationExceptions);
CPPUNIT_TEST(testAccessors);
CPPUNIT_TEST(testModifiers);
CPPUNIT_TEST(testUpdateState);
CPPUNIT_TEST(testUpdateFluid);
CPPUNIT_TEST(testComputeFlows);
CPPUNIT_TEST_SUITE_END();
/// @brief Enumeration for the number of nodes and fluid constituents.
enum {N_NODES = 2, N_FLUIDS = 2};
FluidProperties::FluidType tTypes[N_FLUIDS]; /**< (--) Constituent fluid types array */
double tFractions[N_FLUIDS]; /**< (--) Constituent fluid mass fractions array */
DefinedFluidProperties* tFluidProperties; /**< (--) Predefined fluid properties */
PolyFluidConfigData* tFluidConfig; /**< (--) Fluid config data */
PolyFluidInputData* tFluidInput0; /**< (--) Fluid input data for node 0 */
PolyFluidInputData* tFluidInput1; /**< (--) Fluid input data for node 1 */
std::vector<GunnsBasicLink*> tLinks; /**< (--) Link vector */
std::string tName; /**< (--) Nominal name */
GunnsFluidNode tNodes[N_NODES]; /**< (--) Nominal connected nodes */
GunnsNodeList tNodeList; /**< (--) Network node structure */
int tPort0; /**< (--) Nominal inlet port index */
int tPort1; /**< (--) Nominal outlet port index */
double tCycleVolume; /**< (m3) Volume of fluid displaced per cycle */
double tDriveRatio; /**< (--) Gear ratio of motor to impeller speed */
double tThermalLength; /**< (m) Impeller length for thermal convection */
double tThermalDiameter; /**< (m) Impeller inner diameter for thermal convection */
double tSurfaceRoughness; /**< (m) Impeller wall surface roughness for thermal convection */
bool tCheckValveActive; /**< (--) Check valve active flag */
GunnsGasDisplacementPumpConfigData* tConfigData; /**< (--) Pointer to nominal config data */
bool tBlockageFlag; /**< (--) Blockage malf flag */
double tBlockage; /**< (--) Blockage malf value */
double tFlowDemand; /**< (kg/s) Initial flow demand */
double tMotorSpeed; /**< (rev/min) Initial motor speed */
double tWallTemperature; /**< (K) Initial wall temperature */
GunnsGasDisplacementPumpInputData* tInputData; /**< (--) Pointer to nominal input data */
FriendlyGunnsGasDisplacementPump* tArticle; /**< (--) Pointer to test article */
double tTimeStep; /**< (--) Nominal time step */
static const double PI; /**< (--) Units conversion constant */
static int TEST_ID; /**< (--) Test identification number. */
////////////////////////////////////////////////////////////////////////////////////////////
/// @details Copy constructor unavailable since declared private and not implemented.
////////////////////////////////////////////////////////////////////////////////////////////
UtGunnsGasDisplacementPump(const UtGunnsGasDisplacementPump&);
////////////////////////////////////////////////////////////////////////////////////////////
/// @details Assignment operator unavailable since declared private and not implemented.
////////////////////////////////////////////////////////////////////////////////////////////
UtGunnsGasDisplacementPump& operator =(const UtGunnsGasDisplacementPump&);
};
///@}
#endif
| [
"jason.l.harvey@nasa.gov"
] | jason.l.harvey@nasa.gov |
08612dabf1379c9bbe35b150ef5885723d6ce725 | d0d5fac9b0635f75dc211ceb68d16e9b4399bb11 | /src/hiphop-php/hphp/third_party/folly/folly/experimental/File.cpp | a0f05f6bb76913bfa18442833bde2749f2a990f0 | [
"Apache-2.0",
"PHP-3.01",
"Zend-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | NeoTim/hiphop-php-docker | 2ebf60db2c08bb93aef94ec9fab4d548f8f09bf4 | 51ae1a35e387c05f936cf59ed9d23965554d4b87 | refs/heads/master | 2020-04-16T09:17:51.394473 | 2017-12-03T18:45:36 | 2017-12-03T18:45:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,186 | cpp | /*
* Copyright 2012 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "folly/experimental/File.h"
#include <system_error>
#include <glog/logging.h>
namespace folly {
File::File(const char* name, int flags, mode_t mode)
: fd_(::open(name, flags, mode)), ownsFd_(false) {
if (fd_ == -1) {
throw std::system_error(errno, std::system_category(), "open() failed");
}
ownsFd_ = true;
}
void File::close() {
if (!closeNoThrow()) {
throw std::system_error(errno, std::system_category(), "close() failed");
}
}
bool File::closeNoThrow() {
int r = ownsFd_ ? ::close(fd_) : 0;
release();
return r == 0;
}
} // namespace folly
| [
"mikesjett@gmail.com"
] | mikesjett@gmail.com |
bca24069ea401dd820a74a76fc5c1381334897fe | 6923f79f1eaaba0ab28b25337ba6cb56be97d32d | /GPU-Gems-Book-Source-Code/GPU-Gems-1-CD-Content/Performance_and_Practicalities/Integrating_HW_Shading/source/Paint.h | 6771f1859243a09bb0fc69d25ac3027aa040d8b3 | [] | no_license | burakbayramli/books | 9fe7ba0cabf06e113eb125d62fe16d4946f4a4f0 | 5e9a0e03aa7ddf5e5ddf89943ccc68d94b539e95 | refs/heads/master | 2023-08-17T05:31:08.885134 | 2023-08-14T10:05:37 | 2023-08-14T10:05:37 | 72,460,321 | 223 | 174 | null | 2022-10-24T12:15:06 | 2016-10-31T17:24:00 | Jupyter Notebook | ISO-8859-1 | C++ | false | false | 371 | h | // from C4Dfx by Jörn Loviscach, www.l7h.cn
// a function to render a single object and a function to render the scene
#if !defined(PAINT_H)
#define PAINT_H
class ObjectIterator;
class Materials;
class BaseDocument;
class ShadowMaps;
extern void RenderSingleObject(ObjectIterator* oi);
extern void Paint(BaseDocument* doc, Materials* mat, ShadowMaps* shadow);
#endif | [
"me@yomama.com"
] | me@yomama.com |
2c31ecbd5855d8f648992e34791696c03ca717d2 | 1112f3dd177d9e1a7563ee5e8e98610482c328bc | /c++/zero-matrix.cpp | d2028158792b750bd5dbe6af38568029a2ec1140 | [] | no_license | SimonKocurek/Algorithms-and-Fun | 01d8d751af63766ae34fcbbd2bb46e9178707a66 | f4090393dfcdaba87babf7401876da161a16a1dd | refs/heads/master | 2022-02-28T10:28:40.353537 | 2019-09-15T12:39:54 | 2019-09-15T12:39:54 | 115,929,701 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,131 | cpp | #include <iostream>
#include <vector>
using namespace std;
struct point {
int x, y;
};
auto get_zero_points(vector<vector<int>> &matrix) {
vector<point> result;
for (int y = 0; y < matrix.size(); ++y) {
auto &line = matrix[y];
for (int x = 0; x < line.size(); ++x) {
if (line[x] == 0) {
result.push_back({x, y});
}
}
}
return result;
}
void zero_matrix(vector<vector<int>> &matrix) {
auto zero_points = get_zero_points(matrix);
for (auto &zero_point : zero_points) {
for (int x = 0; x < matrix[0].size(); ++x) {
matrix[zero_point.y][x] = 0;
}
for (int y = 0; y < matrix.size(); ++y) {
matrix[y][zero_point.x] = 0;
}
}
}
int main() {
vector<vector<int>> matrix = {
{1, 2, 3, 0},
{4, 5, 6, 7},
{8, 9, 10, 11},
{12, 0, 13, 14},
{15, 16, 17, 18}};
zero_matrix(matrix);
for (auto &line : matrix) {
for (auto value : line) {
cout << value << " ";
}
cout << "\n";
}
return 0;
}
| [
"simon.kocurek@gmail.com"
] | simon.kocurek@gmail.com |
2b382a3c792639941874e9dfc616596d7055e470 | 6bb8d364eeb7d41aff3abe9e5fd040bb9e6c3925 | /src/version.cpp | 4e82843e6b56d27bac96fbbd62658c55d5599703 | [
"MIT"
] | permissive | UKCDev/UKCoin | 533fe230fc08a05ccee839f779a389fe2768ca6f | 395aea978c1d61457a2b10e14f24350a9906a553 | refs/heads/master | 2021-01-21T13:30:16.084302 | 2018-05-13T12:05:51 | 2018-05-13T12:05:51 | 102,132,281 | 0 | 3 | null | 2017-09-25T16:11:54 | 2017-09-01T16:27:38 | C | UTF-8 | C++ | false | false | 2,638 | cpp | // Copyright (c) 2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <string>
#include "version.h"
// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("UK");
// Client version number
#define CLIENT_VERSION_SUFFIX "III"
// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
// generated by the build environment, possibly containing the output
// of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
// be defined (automatically using the export-subst git attribute), and
// GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
// * if BUILD_DESC is defined, use that literally (output of git-describe)
// * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
// * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added
// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
# include "build.h"
#endif
// git will put "#define GIT_ARCHIVE 1" on the next line inside archives.
#define GIT_ARCHIVE 1
#ifdef GIT_ARCHIVE
# define GIT_COMMIT_ID "" // More informative with version number at this time.
# define GIT_COMMIT_DATE ""
#endif
#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "" commit
#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) ""
#ifndef BUILD_DESC
# ifdef GIT_COMMIT_ID
# define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)
# else
# define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)
# endif
#endif
#ifndef BUILD_DATE
# ifdef GIT_COMMIT_DATE
# define BUILD_DATE GIT_COMMIT_DATE
# else
# define BUILD_DATE __DATE__ ", " __TIME__
# endif
#endif
const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
| [
"31538795+UKCDev@users.noreply.github.com"
] | 31538795+UKCDev@users.noreply.github.com |
1eec8028a74809b10e347c012591081e76ede39b | f552f8eceee3fd8ad48c5a679bce0366f8f310c0 | /XmlUtils.h | bc0b6b77f85142bc78c775f956ef9b4b00d5bda9 | [] | no_license | mihazet/avr-ide | 79689bf00c22d97cc2c728e60a4bc8d4c62297ce | 09bcaccd6b61e49800f77f4953aea7e6b9478f5f | refs/heads/master | 2021-01-10T21:06:56.814438 | 2013-07-22T06:28:12 | 2013-07-22T06:28:12 | 39,128,559 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,139 | h | #ifndef XML_UTILS_H
#define XML_UTILS_H
class XmlUtils
{
public:
// helper function for read/write xml
static wxString ReadElementStringByTag(wxXmlNode *parent, const wxString& tag)
{
wxXmlNode *children = parent->GetChildren();
while (children)
{
if (children->GetName() == tag)
return children->GetNodeContent();
children = children->GetNext();
}
return wxEmptyString;
}
static wxXmlNode *ReadElementByTag(wxXmlNode *parent, const wxString& tag)
{
wxXmlNode *children = parent->GetChildren();
while (children)
{
if (children->GetName() == tag)
return children;
children = children->GetNext();
}
return 0;
}
static void WriteElementString(wxXmlNode *parent, const wxString& key, const wxString& value)
{
wxXmlNode *node = new wxXmlNode(wxXML_ELEMENT_NODE, key);
new wxXmlNode(node, wxXML_TEXT_NODE, "", value);
parent->AddChild(node);
}
static wxXmlNode *WriteElement(wxXmlNode *parent, const wxString& name)
{
wxXmlNode *node = new wxXmlNode(wxXML_ELEMENT_NODE, name);
parent->AddChild(node);
return node;
}
};
#endif
| [
"miha8210@gmail.com"
] | miha8210@gmail.com |
7679d4d9ab6a6baf25121b4d2a767041cffc3fab | 9cb14eaff82ba9cf75c6c99e34c9446ee9d7c17b | /codeforces/557/a.cpp | 8b356f29c5592ef10ae53b6ee741d0b98b74aea4 | [] | no_license | rafa95359/programacionCOmpetitiva | fe7008e85a41e958517a0c336bdb5da9c8a5df83 | d471229758e9c4f3cac7459845e04c7056e2a1e0 | refs/heads/master | 2022-02-19T06:43:37.794325 | 2019-09-02T15:09:35 | 2019-09-02T15:09:35 | 183,834,924 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 445 | cpp | #include <bits/stdc++.h>
using namespace std;
#define para(i,a,n) for(int i=a;i<n;i++)
#define N 1000000
typedef long long Long ;
Long value(Long a,Long b,Long c ){
Long med=(a+b+c)/2;
return med;
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
Long n;
cin>>n;
para(i,0,n){
Long a,b,c;
cin>>a>>b>>c;
cout<<value(a,b,c)<<endl;
}
return 0;
} | [
"rafalopezlizana@gmail.com"
] | rafalopezlizana@gmail.com |
9e7f5d7988682aacdb7195e4c0e83f08e5596c11 | 3e637dc8bbd968017fff17ae78122dda07011775 | /third_party/skia/src/gpu/gl/GrGLProgram.cpp | f16812b54d179ebccdc4c434011b46c6566dfa08 | [
"BSD-3-Clause"
] | permissive | lineCode/chromium_ui | 8cba926b4e1deadb8dc81b7550719fb7fb2cda29 | e40185109eede35e80224780dd473dfe8369a397 | refs/heads/master | 2020-11-24T12:35:56.932529 | 2018-11-11T14:40:49 | 2018-11-11T14:40:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 54,932 | cpp | /*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "GrGLProgram.h"
#include "GrAllocator.h"
#include "GrCustomStage.h"
#include "GrGLProgramStage.h"
#include "gl/GrGLShaderBuilder.h"
#include "GrGLShaderVar.h"
#include "GrProgramStageFactory.h"
#include "SkTrace.h"
#include "SkXfermode.h"
namespace {
enum {
/// Used to mark a StageUniLocation field that should be bound
/// to a uniform during getUniformLocationsAndInitCache().
kUseUniform = 2000
};
} // namespace
#define PRINT_SHADERS 0
typedef GrGLProgram::ProgramDesc::StageDesc StageDesc;
#define VIEW_MATRIX_NAME "uViewM"
#define POS_ATTR_NAME "aPosition"
#define COL_ATTR_NAME "aColor"
#define COV_ATTR_NAME "aCoverage"
#define EDGE_ATTR_NAME "aEdge"
#define COL_UNI_NAME "uColor"
#define COV_UNI_NAME "uCoverage"
#define COL_FILTER_UNI_NAME "uColorFilter"
#define COL_MATRIX_UNI_NAME "uColorMatrix"
#define COL_MATRIX_VEC_UNI_NAME "uColorMatrixVec"
namespace {
inline void tex_attr_name(int coordIdx, GrStringBuilder* s) {
*s = "aTexCoord";
s->appendS32(coordIdx);
}
inline const char* float_vector_type_str(int count) {
return GrGLShaderVar::TypeString(GrSLFloatVectorType(count));
}
inline const char* vector_all_coords(int count) {
static const char* ALL[] = {"ERROR", "", ".xy", ".xyz", ".xyzw"};
GrAssert(count >= 1 && count < (int)GR_ARRAY_COUNT(ALL));
return ALL[count];
}
inline const char* all_ones_vec(int count) {
static const char* ONESVEC[] = {"ERROR", "1.0", "vec2(1,1)",
"vec3(1,1,1)", "vec4(1,1,1,1)"};
GrAssert(count >= 1 && count < (int)GR_ARRAY_COUNT(ONESVEC));
return ONESVEC[count];
}
inline const char* all_zeros_vec(int count) {
static const char* ZEROSVEC[] = {"ERROR", "0.0", "vec2(0,0)",
"vec3(0,0,0)", "vec4(0,0,0,0)"};
GrAssert(count >= 1 && count < (int)GR_ARRAY_COUNT(ZEROSVEC));
return ZEROSVEC[count];
}
inline const char* declared_color_output_name() { return "fsColorOut"; }
inline const char* dual_source_output_name() { return "dualSourceOut"; }
inline void tex_matrix_name(int stage, GrStringBuilder* s) {
*s = "uTexM";
s->appendS32(stage);
}
inline void sampler_name(int stage, GrStringBuilder* s) {
*s = "uSampler";
s->appendS32(stage);
}
inline void tex_domain_name(int stage, GrStringBuilder* s) {
*s = "uTexDom";
s->appendS32(stage);
}
}
GrGLProgram::GrGLProgram() {
}
GrGLProgram::~GrGLProgram() {
}
void GrGLProgram::overrideBlend(GrBlendCoeff* srcCoeff,
GrBlendCoeff* dstCoeff) const {
switch (fProgramDesc.fDualSrcOutput) {
case ProgramDesc::kNone_DualSrcOutput:
break;
// the prog will write a coverage value to the secondary
// output and the dst is blended by one minus that value.
case ProgramDesc::kCoverage_DualSrcOutput:
case ProgramDesc::kCoverageISA_DualSrcOutput:
case ProgramDesc::kCoverageISC_DualSrcOutput:
*dstCoeff = (GrBlendCoeff)GrGpu::kIS2C_GrBlendCoeff;
break;
default:
GrCrash("Unexpected dual source blend output");
break;
}
}
// assigns modulation of two vars to an output var
// vars can be vec4s or floats (or one of each)
// result is always vec4
// if either var is "" then assign to the other var
// if both are "" then assign all ones
static inline void modulate_helper(const char* outputVar,
const char* var0,
const char* var1,
GrStringBuilder* code) {
GrAssert(NULL != outputVar);
GrAssert(NULL != var0);
GrAssert(NULL != var1);
GrAssert(NULL != code);
bool has0 = '\0' != *var0;
bool has1 = '\0' != *var1;
if (!has0 && !has1) {
code->appendf("\t%s = %s;\n", outputVar, all_ones_vec(4));
} else if (!has0) {
code->appendf("\t%s = vec4(%s);\n", outputVar, var1);
} else if (!has1) {
code->appendf("\t%s = vec4(%s);\n", outputVar, var0);
} else {
code->appendf("\t%s = vec4(%s * %s);\n", outputVar, var0, var1);
}
}
// assigns addition of two vars to an output var
// vars can be vec4s or floats (or one of each)
// result is always vec4
// if either var is "" then assign to the other var
// if both are "" then assign all zeros
static inline void add_helper(const char* outputVar,
const char* var0,
const char* var1,
GrStringBuilder* code) {
GrAssert(NULL != outputVar);
GrAssert(NULL != var0);
GrAssert(NULL != var1);
GrAssert(NULL != code);
bool has0 = '\0' != *var0;
bool has1 = '\0' != *var1;
if (!has0 && !has1) {
code->appendf("\t%s = %s;\n", outputVar, all_zeros_vec(4));
} else if (!has0) {
code->appendf("\t%s = vec4(%s);\n", outputVar, var1);
} else if (!has1) {
code->appendf("\t%s = vec4(%s);\n", outputVar, var0);
} else {
code->appendf("\t%s = vec4(%s + %s);\n", outputVar, var0, var1);
}
}
// given two blend coeffecients determine whether the src
// and/or dst computation can be omitted.
static inline void needBlendInputs(SkXfermode::Coeff srcCoeff,
SkXfermode::Coeff dstCoeff,
bool* needSrcValue,
bool* needDstValue) {
if (SkXfermode::kZero_Coeff == srcCoeff) {
switch (dstCoeff) {
// these all read the src
case SkXfermode::kSC_Coeff:
case SkXfermode::kISC_Coeff:
case SkXfermode::kSA_Coeff:
case SkXfermode::kISA_Coeff:
*needSrcValue = true;
break;
default:
*needSrcValue = false;
break;
}
} else {
*needSrcValue = true;
}
if (SkXfermode::kZero_Coeff == dstCoeff) {
switch (srcCoeff) {
// these all read the dst
case SkXfermode::kDC_Coeff:
case SkXfermode::kIDC_Coeff:
case SkXfermode::kDA_Coeff:
case SkXfermode::kIDA_Coeff:
*needDstValue = true;
break;
default:
*needDstValue = false;
break;
}
} else {
*needDstValue = true;
}
}
/**
* Create a blend_coeff * value string to be used in shader code. Sets empty
* string if result is trivially zero.
*/
static void blendTermString(GrStringBuilder* str, SkXfermode::Coeff coeff,
const char* src, const char* dst,
const char* value) {
switch (coeff) {
case SkXfermode::kZero_Coeff: /** 0 */
*str = "";
break;
case SkXfermode::kOne_Coeff: /** 1 */
*str = value;
break;
case SkXfermode::kSC_Coeff:
str->printf("(%s * %s)", src, value);
break;
case SkXfermode::kISC_Coeff:
str->printf("((%s - %s) * %s)", all_ones_vec(4), src, value);
break;
case SkXfermode::kDC_Coeff:
str->printf("(%s * %s)", dst, value);
break;
case SkXfermode::kIDC_Coeff:
str->printf("((%s - %s) * %s)", all_ones_vec(4), dst, value);
break;
case SkXfermode::kSA_Coeff: /** src alpha */
str->printf("(%s.a * %s)", src, value);
break;
case SkXfermode::kISA_Coeff: /** inverse src alpha (i.e. 1 - sa) */
str->printf("((1.0 - %s.a) * %s)", src, value);
break;
case SkXfermode::kDA_Coeff: /** dst alpha */
str->printf("(%s.a * %s)", dst, value);
break;
case SkXfermode::kIDA_Coeff: /** inverse dst alpha (i.e. 1 - da) */
str->printf("((1.0 - %s.a) * %s)", dst, value);
break;
default:
GrCrash("Unexpected xfer coeff.");
break;
}
}
/**
* Adds a line to the fragment shader code which modifies the color by
* the specified color filter.
*/
static void addColorFilter(GrStringBuilder* fsCode, const char * outputVar,
SkXfermode::Coeff uniformCoeff,
SkXfermode::Coeff colorCoeff,
const char* inColor) {
GrStringBuilder colorStr, constStr;
blendTermString(&colorStr, colorCoeff, COL_FILTER_UNI_NAME,
inColor, inColor);
blendTermString(&constStr, uniformCoeff, COL_FILTER_UNI_NAME,
inColor, COL_FILTER_UNI_NAME);
add_helper(outputVar, colorStr.c_str(), constStr.c_str(), fsCode);
}
/**
* Adds code to the fragment shader code which modifies the color by
* the specified color matrix.
*/
static void addColorMatrix(GrStringBuilder* fsCode, const char * outputVar,
const char* inColor) {
fsCode->appendf("\t%s = %s * vec4(%s.rgb / %s.a, %s.a) + %s;\n", outputVar, COL_MATRIX_UNI_NAME, inColor, inColor, inColor, COL_MATRIX_VEC_UNI_NAME);
fsCode->appendf("\t%s.rgb *= %s.a;\n", outputVar, outputVar);
}
void GrGLProgram::genEdgeCoverage(const GrGLContextInfo& gl,
GrVertexLayout layout,
CachedData* programData,
GrStringBuilder* coverageVar,
GrGLShaderBuilder* segments) const {
if (layout & GrDrawTarget::kEdge_VertexLayoutBit) {
const char *vsName, *fsName;
segments->addVarying(kVec4f_GrSLType, "Edge", &vsName, &fsName);
segments->fVSAttrs.push_back().set(kVec4f_GrSLType,
GrGLShaderVar::kAttribute_TypeModifier, EDGE_ATTR_NAME);
segments->fVSCode.appendf("\t%s = " EDGE_ATTR_NAME ";\n", vsName);
switch (fProgramDesc.fVertexEdgeType) {
case GrDrawState::kHairLine_EdgeType:
segments->fFSCode.appendf("\tfloat edgeAlpha = abs(dot(vec3(gl_FragCoord.xy,1), %s.xyz));\n", fsName);
segments->fFSCode.append("\tedgeAlpha = max(1.0 - edgeAlpha, 0.0);\n");
break;
case GrDrawState::kQuad_EdgeType:
segments->fFSCode.append("\tfloat edgeAlpha;\n");
// keep the derivative instructions outside the conditional
segments->fFSCode.appendf("\tvec2 duvdx = dFdx(%s.xy);\n", fsName);
segments->fFSCode.appendf("\tvec2 duvdy = dFdy(%s.xy);\n", fsName);
segments->fFSCode.appendf("\tif (%s.z > 0.0 && %s.w > 0.0) {\n", fsName, fsName);
// today we know z and w are in device space. We could use derivatives
segments->fFSCode.appendf("\t\tedgeAlpha = min(min(%s.z, %s.w) + 0.5, 1.0);\n", fsName, fsName);
segments->fFSCode.append ("\t} else {\n");
segments->fFSCode.appendf("\t\tvec2 gF = vec2(2.0*%s.x*duvdx.x - duvdx.y,\n"
"\t\t 2.0*%s.x*duvdy.x - duvdy.y);\n",
fsName, fsName);
segments->fFSCode.appendf("\t\tedgeAlpha = (%s.x*%s.x - %s.y);\n", fsName, fsName, fsName);
segments->fFSCode.append("\t\tedgeAlpha = clamp(0.5 - edgeAlpha / length(gF), 0.0, 1.0);\n"
"\t}\n");
if (kES2_GrGLBinding == gl.binding()) {
segments->fHeader.printf("#extension GL_OES_standard_derivatives: enable\n");
}
break;
case GrDrawState::kHairQuad_EdgeType:
segments->fFSCode.appendf("\tvec2 duvdx = dFdx(%s.xy);\n", fsName);
segments->fFSCode.appendf("\tvec2 duvdy = dFdy(%s.xy);\n", fsName);
segments->fFSCode.appendf("\tvec2 gF = vec2(2.0*%s.x*duvdx.x - duvdx.y,\n"
"\t 2.0*%s.x*duvdy.x - duvdy.y);\n",
fsName, fsName);
segments->fFSCode.appendf("\tfloat edgeAlpha = (%s.x*%s.x - %s.y);\n", fsName, fsName, fsName);
segments->fFSCode.append("\tedgeAlpha = sqrt(edgeAlpha*edgeAlpha / dot(gF, gF));\n");
segments->fFSCode.append("\tedgeAlpha = max(1.0 - edgeAlpha, 0.0);\n");
if (kES2_GrGLBinding == gl.binding()) {
segments->fHeader.printf("#extension GL_OES_standard_derivatives: enable\n");
}
break;
case GrDrawState::kCircle_EdgeType:
segments->fFSCode.append("\tfloat edgeAlpha;\n");
segments->fFSCode.appendf("\tfloat d = distance(gl_FragCoord.xy, %s.xy);\n", fsName);
segments->fFSCode.appendf("\tfloat outerAlpha = smoothstep(d - 0.5, d + 0.5, %s.z);\n", fsName);
segments->fFSCode.appendf("\tfloat innerAlpha = %s.w == 0.0 ? 1.0 : smoothstep(%s.w - 0.5, %s.w + 0.5, d);\n", fsName, fsName, fsName);
segments->fFSCode.append("\tedgeAlpha = outerAlpha * innerAlpha;\n");
break;
default:
GrCrash("Unknown Edge Type!");
break;
}
*coverageVar = "edgeAlpha";
} else {
coverageVar->reset();
}
}
namespace {
void genInputColor(GrGLProgram::ProgramDesc::ColorInput colorInput,
GrGLProgram::CachedData* programData,
GrGLShaderBuilder* segments,
GrStringBuilder* inColor) {
switch (colorInput) {
case GrGLProgram::ProgramDesc::kAttribute_ColorInput: {
segments->fVSAttrs.push_back().set(kVec4f_GrSLType,
GrGLShaderVar::kAttribute_TypeModifier,
COL_ATTR_NAME);
const char *vsName, *fsName;
segments->addVarying(kVec4f_GrSLType, "Color", &vsName, &fsName);
segments->fVSCode.appendf("\t%s = " COL_ATTR_NAME ";\n", vsName);
*inColor = fsName;
} break;
case GrGLProgram::ProgramDesc::kUniform_ColorInput:
segments->addUniform(GrGLShaderBuilder::kFragment_VariableLifetime,
kVec4f_GrSLType, COL_UNI_NAME);
programData->fUniLocations.fColorUni = kUseUniform;
*inColor = COL_UNI_NAME;
break;
case GrGLProgram::ProgramDesc::kTransBlack_ColorInput:
GrAssert(!"needComputedColor should be false.");
break;
case GrGLProgram::ProgramDesc::kSolidWhite_ColorInput:
break;
default:
GrCrash("Unknown color type.");
break;
}
}
void genAttributeCoverage(GrGLShaderBuilder* segments,
GrStringBuilder* inOutCoverage) {
segments->fVSAttrs.push_back().set(kVec4f_GrSLType,
GrGLShaderVar::kAttribute_TypeModifier,
COV_ATTR_NAME);
const char *vsName, *fsName;
segments->addVarying(kVec4f_GrSLType, "Coverage", &vsName, &fsName);
segments->fVSCode.appendf("\t%s = " COV_ATTR_NAME ";\n", vsName);
if (inOutCoverage->size()) {
segments->fFSCode.appendf("\tvec4 attrCoverage = %s * %s;\n",
fsName, inOutCoverage->c_str());
*inOutCoverage = "attrCoverage";
} else {
*inOutCoverage = fsName;
}
}
void genUniformCoverage(GrGLShaderBuilder* segments,
GrGLProgram::CachedData* programData,
GrStringBuilder* inOutCoverage) {
segments->addUniform(GrGLShaderBuilder::kFragment_VariableLifetime,
kVec4f_GrSLType, COV_UNI_NAME);
programData->fUniLocations.fCoverageUni = kUseUniform;
if (inOutCoverage->size()) {
segments->fFSCode.appendf("\tvec4 uniCoverage = %s * %s;\n",
COV_UNI_NAME, inOutCoverage->c_str());
*inOutCoverage = "uniCoverage";
} else {
*inOutCoverage = COV_UNI_NAME;
}
}
}
void GrGLProgram::genGeometryShader(const GrGLContextInfo& gl,
GrGLShaderBuilder* segments) const {
#if GR_GL_EXPERIMENTAL_GS
if (fProgramDesc.fExperimentalGS) {
GrAssert(gl.glslGeneration() >= k150_GrGLSLGeneration);
segments->fGSHeader.append("layout(triangles) in;\n"
"layout(triangle_strip, max_vertices = 6) out;\n");
segments->fGSCode.append("void main() {\n"
"\tfor (int i = 0; i < 3; ++i) {\n"
"\t\tgl_Position = gl_in[i].gl_Position;\n");
if (this->fProgramDesc.fEmitsPointSize) {
segments->fGSCode.append("\t\tgl_PointSize = 1.0;\n");
}
GrAssert(segments->fGSInputs.count() == segments->fGSOutputs.count());
int count = segments->fGSInputs.count();
for (int i = 0; i < count; ++i) {
segments->fGSCode.appendf("\t\t%s = %s[i];\n",
segments->fGSOutputs[i].getName().c_str(),
segments->fGSInputs[i].getName().c_str());
}
segments->fGSCode.append("\t\tEmitVertex();\n"
"\t}\n"
"\tEndPrimitive();\n"
"}\n");
}
#endif
}
const char* GrGLProgram::adjustInColor(const GrStringBuilder& inColor) const {
if (inColor.size()) {
return inColor.c_str();
} else {
if (ProgramDesc::kSolidWhite_ColorInput == fProgramDesc.fColorInput) {
return all_ones_vec(4);
} else {
return all_zeros_vec(4);
}
}
}
// If this destructor is in the header file, we must include GrGLProgramStage
// instead of just forward-declaring it.
GrGLProgram::CachedData::~CachedData() {
for (int i = 0; i < GrDrawState::kNumStages; ++i) {
delete fCustomStage[i];
}
}
bool GrGLProgram::genProgram(const GrGLContextInfo& gl,
GrCustomStage** customStages,
GrGLProgram::CachedData* programData) const {
GrGLShaderBuilder segments;
const uint32_t& layout = fProgramDesc.fVertexLayout;
programData->fUniLocations.reset();
#if GR_GL_EXPERIMENTAL_GS
segments.fUsesGS = fProgramDesc.fExperimentalGS;
#endif
SkXfermode::Coeff colorCoeff, uniformCoeff;
bool applyColorMatrix = SkToBool(fProgramDesc.fColorMatrixEnabled);
// The rest of transfer mode color filters have not been implemented
if (fProgramDesc.fColorFilterXfermode < SkXfermode::kCoeffModesCnt) {
GR_DEBUGCODE(bool success =)
SkXfermode::ModeAsCoeff(static_cast<SkXfermode::Mode>
(fProgramDesc.fColorFilterXfermode),
&uniformCoeff, &colorCoeff);
GR_DEBUGASSERT(success);
} else {
colorCoeff = SkXfermode::kOne_Coeff;
uniformCoeff = SkXfermode::kZero_Coeff;
}
// no need to do the color filter / matrix at all if coverage is 0. The
// output color is scaled by the coverage. All the dual source outputs are
// scaled by the coverage as well.
if (ProgramDesc::kTransBlack_ColorInput == fProgramDesc.fCoverageInput) {
colorCoeff = SkXfermode::kZero_Coeff;
uniformCoeff = SkXfermode::kZero_Coeff;
applyColorMatrix = false;
}
// If we know the final color is going to be all zeros then we can
// simplify the color filter coeffecients. needComputedColor will then
// come out false below.
if (ProgramDesc::kTransBlack_ColorInput == fProgramDesc.fColorInput) {
colorCoeff = SkXfermode::kZero_Coeff;
if (SkXfermode::kDC_Coeff == uniformCoeff ||
SkXfermode::kDA_Coeff == uniformCoeff) {
uniformCoeff = SkXfermode::kZero_Coeff;
} else if (SkXfermode::kIDC_Coeff == uniformCoeff ||
SkXfermode::kIDA_Coeff == uniformCoeff) {
uniformCoeff = SkXfermode::kOne_Coeff;
}
}
bool needColorFilterUniform;
bool needComputedColor;
needBlendInputs(uniformCoeff, colorCoeff,
&needColorFilterUniform, &needComputedColor);
// the dual source output has no canonical var name, have to
// declare an output, which is incompatible with gl_FragColor/gl_FragData.
bool dualSourceOutputWritten = false;
segments.fHeader.printf(GrGetGLSLVersionDecl(gl.binding(),
gl.glslGeneration()));
GrGLShaderVar colorOutput;
bool isColorDeclared = GrGLSLSetupFSColorOuput(gl.glslGeneration(),
declared_color_output_name(),
&colorOutput);
if (isColorDeclared) {
segments.fFSOutputs.push_back(colorOutput);
}
segments.addUniform(GrGLShaderBuilder::kVertex_VariableLifetime,
kMat33f_GrSLType, VIEW_MATRIX_NAME);
programData->fUniLocations.fViewMatrixUni = kUseUniform;
segments.fVSAttrs.push_back().set(kVec2f_GrSLType,
GrGLShaderVar::kAttribute_TypeModifier, POS_ATTR_NAME);
segments.fVSCode.append(
"void main() {\n"
"\tvec3 pos3 = " VIEW_MATRIX_NAME " * vec3("POS_ATTR_NAME", 1);\n"
"\tgl_Position = vec4(pos3.xy, 0, pos3.z);\n");
// incoming color to current stage being processed.
GrStringBuilder inColor;
if (needComputedColor) {
genInputColor((ProgramDesc::ColorInput) fProgramDesc.fColorInput,
programData, &segments, &inColor);
}
// we output point size in the GS if present
if (fProgramDesc.fEmitsPointSize && !segments.fUsesGS){
segments.fVSCode.append("\tgl_PointSize = 1.0;\n");
}
segments.fFSCode.append("void main() {\n");
// add texture coordinates that are used to the list of vertex attr decls
GrStringBuilder texCoordAttrs[GrDrawState::kMaxTexCoords];
for (int t = 0; t < GrDrawState::kMaxTexCoords; ++t) {
if (GrDrawTarget::VertexUsesTexCoordIdx(t, layout)) {
tex_attr_name(t, texCoordAttrs + t);
segments.fVSAttrs.push_back().set(kVec2f_GrSLType,
GrGLShaderVar::kAttribute_TypeModifier,
texCoordAttrs[t].c_str());
}
}
///////////////////////////////////////////////////////////////////////////
// We need to convert generic effect representations to GL-specific
// backends so they can be accesseed in genStageCode() and in subsequent,
// uses of programData, but it's safest to do so below when we're *sure*
// we need them.
for (int s = 0; s < GrDrawState::kNumStages; ++s) {
programData->fCustomStage[s] = NULL;
}
///////////////////////////////////////////////////////////////////////////
// compute the final color
// if we have color stages string them together, feeding the output color
// of each to the next and generating code for each stage.
if (needComputedColor) {
GrStringBuilder outColor;
for (int s = 0; s < fProgramDesc.fFirstCoverageStage; ++s) {
if (fProgramDesc.fStages[s].isEnabled()) {
// create var to hold stage result
outColor = "color";
outColor.appendS32(s);
segments.fFSCode.appendf("\tvec4 %s;\n", outColor.c_str());
const char* inCoords;
// figure out what our input coords are
if (GrDrawTarget::StagePosAsTexCoordVertexLayoutBit(s) &
layout) {
inCoords = POS_ATTR_NAME;
} else {
int tcIdx = GrDrawTarget::VertexTexCoordsForStage(s, layout);
// we better have input tex coordinates if stage is enabled.
GrAssert(tcIdx >= 0);
GrAssert(texCoordAttrs[tcIdx].size());
inCoords = texCoordAttrs[tcIdx].c_str();
}
if (NULL != customStages[s]) {
const GrProgramStageFactory& factory =
customStages[s]->getFactory();
programData->fCustomStage[s] =
factory.createGLInstance(*customStages[s]);
}
this->genStageCode(gl,
s,
fProgramDesc.fStages[s],
inColor.size() ? inColor.c_str() : NULL,
outColor.c_str(),
inCoords,
&segments,
&programData->fUniLocations.fStages[s],
programData->fCustomStage[s]);
inColor = outColor;
}
}
}
// if have all ones or zeros for the "dst" input to the color filter then we
// may be able to make additional optimizations.
if (needColorFilterUniform && needComputedColor && !inColor.size()) {
GrAssert(ProgramDesc::kSolidWhite_ColorInput == fProgramDesc.fColorInput);
bool uniformCoeffIsZero = SkXfermode::kIDC_Coeff == uniformCoeff ||
SkXfermode::kIDA_Coeff == uniformCoeff;
if (uniformCoeffIsZero) {
uniformCoeff = SkXfermode::kZero_Coeff;
bool bogus;
needBlendInputs(SkXfermode::kZero_Coeff, colorCoeff,
&needColorFilterUniform, &bogus);
}
}
if (needColorFilterUniform) {
segments.addUniform(GrGLShaderBuilder::kFragment_VariableLifetime,
kVec4f_GrSLType, COL_FILTER_UNI_NAME);
programData->fUniLocations.fColorFilterUni = kUseUniform;
}
bool wroteFragColorZero = false;
if (SkXfermode::kZero_Coeff == uniformCoeff &&
SkXfermode::kZero_Coeff == colorCoeff &&
!applyColorMatrix) {
segments.fFSCode.appendf("\t%s = %s;\n",
colorOutput.getName().c_str(),
all_zeros_vec(4));
wroteFragColorZero = true;
} else if (SkXfermode::kDst_Mode != fProgramDesc.fColorFilterXfermode) {
segments.fFSCode.append("\tvec4 filteredColor;\n");
const char* color = adjustInColor(inColor);
addColorFilter(&segments.fFSCode, "filteredColor", uniformCoeff,
colorCoeff, color);
inColor = "filteredColor";
}
if (applyColorMatrix) {
segments.addUniform(GrGLShaderBuilder::kFragment_VariableLifetime,
kMat44f_GrSLType, COL_MATRIX_UNI_NAME);
segments.addUniform(GrGLShaderBuilder::kFragment_VariableLifetime,
kVec4f_GrSLType, COL_MATRIX_VEC_UNI_NAME);
programData->fUniLocations.fColorMatrixUni = kUseUniform;
programData->fUniLocations.fColorMatrixVecUni = kUseUniform;
segments.fFSCode.append("\tvec4 matrixedColor;\n");
const char* color = adjustInColor(inColor);
addColorMatrix(&segments.fFSCode, "matrixedColor", color);
inColor = "matrixedColor";
}
///////////////////////////////////////////////////////////////////////////
// compute the partial coverage (coverage stages and edge aa)
GrStringBuilder inCoverage;
bool coverageIsZero = ProgramDesc::kTransBlack_ColorInput ==
fProgramDesc.fCoverageInput;
// we don't need to compute coverage at all if we know the final shader
// output will be zero and we don't have a dual src blend output.
if (!wroteFragColorZero ||
ProgramDesc::kNone_DualSrcOutput != fProgramDesc.fDualSrcOutput) {
if (!coverageIsZero) {
this->genEdgeCoverage(gl,
layout,
programData,
&inCoverage,
&segments);
switch (fProgramDesc.fCoverageInput) {
case ProgramDesc::kSolidWhite_ColorInput:
// empty string implies solid white
break;
case ProgramDesc::kAttribute_ColorInput:
genAttributeCoverage(&segments, &inCoverage);
break;
case ProgramDesc::kUniform_ColorInput:
genUniformCoverage(&segments, programData, &inCoverage);
break;
default:
GrCrash("Unexpected input coverage.");
}
GrStringBuilder outCoverage;
const int& startStage = fProgramDesc.fFirstCoverageStage;
for (int s = startStage; s < GrDrawState::kNumStages; ++s) {
if (fProgramDesc.fStages[s].isEnabled()) {
// create var to hold stage output
outCoverage = "coverage";
outCoverage.appendS32(s);
segments.fFSCode.appendf("\tvec4 %s;\n",
outCoverage.c_str());
const char* inCoords;
// figure out what our input coords are
if (GrDrawTarget::StagePosAsTexCoordVertexLayoutBit(s) &
layout) {
inCoords = POS_ATTR_NAME;
} else {
int tcIdx =
GrDrawTarget::VertexTexCoordsForStage(s, layout);
// we better have input tex coordinates if stage is
// enabled.
GrAssert(tcIdx >= 0);
GrAssert(texCoordAttrs[tcIdx].size());
inCoords = texCoordAttrs[tcIdx].c_str();
}
if (NULL != customStages[s]) {
const GrProgramStageFactory& factory =
customStages[s]->getFactory();
programData->fCustomStage[s] =
factory.createGLInstance(*customStages[s]);
}
this->genStageCode(gl, s,
fProgramDesc.fStages[s],
inCoverage.size() ? inCoverage.c_str() : NULL,
outCoverage.c_str(),
inCoords,
&segments,
&programData->fUniLocations.fStages[s],
programData->fCustomStage[s]);
inCoverage = outCoverage;
}
}
}
if (ProgramDesc::kNone_DualSrcOutput != fProgramDesc.fDualSrcOutput) {
segments.fFSOutputs.push_back().set(kVec4f_GrSLType,
GrGLShaderVar::kOut_TypeModifier,
dual_source_output_name());
bool outputIsZero = coverageIsZero;
GrStringBuilder coeff;
if (!outputIsZero &&
ProgramDesc::kCoverage_DualSrcOutput !=
fProgramDesc.fDualSrcOutput && !wroteFragColorZero) {
if (!inColor.size()) {
outputIsZero = true;
} else {
if (fProgramDesc.fDualSrcOutput ==
ProgramDesc::kCoverageISA_DualSrcOutput) {
coeff.printf("(1 - %s.a)", inColor.c_str());
} else {
coeff.printf("(vec4(1,1,1,1) - %s)", inColor.c_str());
}
}
}
if (outputIsZero) {
segments.fFSCode.appendf("\t%s = %s;\n",
dual_source_output_name(),
all_zeros_vec(4));
} else {
modulate_helper(dual_source_output_name(),
coeff.c_str(),
inCoverage.c_str(),
&segments.fFSCode);
}
dualSourceOutputWritten = true;
}
}
///////////////////////////////////////////////////////////////////////////
// combine color and coverage as frag color
if (!wroteFragColorZero) {
if (coverageIsZero) {
segments.fFSCode.appendf("\t%s = %s;\n",
colorOutput.getName().c_str(),
all_zeros_vec(4));
} else {
modulate_helper(colorOutput.getName().c_str(),
inColor.c_str(),
inCoverage.c_str(),
&segments.fFSCode);
}
if (ProgramDesc::kUnpremultiplied_RoundDown_OutputConfig ==
fProgramDesc.fOutputConfig) {
segments.fFSCode.appendf("\t%s = %s.a <= 0.0 ? vec4(0,0,0,0) : vec4(floor(%s.rgb / %s.a * 255.0)/255.0, %s.a);\n",
colorOutput.getName().c_str(),
colorOutput.getName().c_str(),
colorOutput.getName().c_str(),
colorOutput.getName().c_str(),
colorOutput.getName().c_str());
} else if (ProgramDesc::kUnpremultiplied_RoundUp_OutputConfig ==
fProgramDesc.fOutputConfig) {
segments.fFSCode.appendf("\t%s = %s.a <= 0.0 ? vec4(0,0,0,0) : vec4(ceil(%s.rgb / %s.a * 255.0)/255.0, %s.a);\n",
colorOutput.getName().c_str(),
colorOutput.getName().c_str(),
colorOutput.getName().c_str(),
colorOutput.getName().c_str(),
colorOutput.getName().c_str());
}
}
segments.fVSCode.append("}\n");
segments.fFSCode.append("}\n");
///////////////////////////////////////////////////////////////////////////
// insert GS
#if GR_DEBUG
this->genGeometryShader(gl, &segments);
#endif
///////////////////////////////////////////////////////////////////////////
// compile and setup attribs and unis
if (!CompileShaders(gl, segments, programData)) {
return false;
}
if (!this->bindOutputsAttribsAndLinkProgram(gl, texCoordAttrs,
isColorDeclared,
dualSourceOutputWritten,
programData)) {
return false;
}
this->getUniformLocationsAndInitCache(gl, programData);
return true;
}
namespace {
inline void expand_decls(const VarArray& vars,
const GrGLContextInfo& gl,
GrStringBuilder* string) {
const int count = vars.count();
for (int i = 0; i < count; ++i) {
vars[i].appendDecl(gl, string);
}
}
inline void print_shader(int stringCnt,
const char** strings,
int* stringLengths) {
for (int i = 0; i < stringCnt; ++i) {
if (NULL == stringLengths || stringLengths[i] < 0) {
GrPrintf(strings[i]);
} else {
GrPrintf("%.*s", stringLengths[i], strings[i]);
}
}
}
typedef SkTArray<const char*, true> StrArray;
#define PREALLOC_STR_ARRAY(N) SkSTArray<(N), const char*, true>
typedef SkTArray<int, true> LengthArray;
#define PREALLOC_LENGTH_ARRAY(N) SkSTArray<(N), int, true>
// these shouldn't relocate
typedef GrTAllocator<GrStringBuilder> TempArray;
#define PREALLOC_TEMP_ARRAY(N) GrSTAllocator<(N), GrStringBuilder>
inline void append_string(const GrStringBuilder& str,
StrArray* strings,
LengthArray* lengths) {
int length = (int) str.size();
if (length) {
strings->push_back(str.c_str());
lengths->push_back(length);
}
GrAssert(strings->count() == lengths->count());
}
inline void append_decls(const VarArray& vars,
const GrGLContextInfo& gl,
StrArray* strings,
LengthArray* lengths,
TempArray* temp) {
expand_decls(vars, gl, &temp->push_back());
append_string(temp->back(), strings, lengths);
}
}
bool GrGLProgram::CompileShaders(const GrGLContextInfo& gl,
const GrGLShaderBuilder& segments,
CachedData* programData) {
enum { kPreAllocStringCnt = 8 };
PREALLOC_STR_ARRAY(kPreAllocStringCnt) strs;
PREALLOC_LENGTH_ARRAY(kPreAllocStringCnt) lengths;
PREALLOC_TEMP_ARRAY(kPreAllocStringCnt) temps;
GrStringBuilder unis;
GrStringBuilder inputs;
GrStringBuilder outputs;
append_string(segments.fHeader, &strs, &lengths);
append_decls(segments.fVSUnis, gl, &strs, &lengths, &temps);
append_decls(segments.fVSAttrs, gl, &strs, &lengths, &temps);
append_decls(segments.fVSOutputs, gl, &strs, &lengths, &temps);
append_string(segments.fVSCode, &strs, &lengths);
#if PRINT_SHADERS
print_shader(strs.count(), &strs[0], &lengths[0]);
GrPrintf("\n");
#endif
programData->fVShaderID =
CompileShader(gl, GR_GL_VERTEX_SHADER, strs.count(),
&strs[0], &lengths[0]);
if (!programData->fVShaderID) {
return false;
}
if (segments.fUsesGS) {
strs.reset();
lengths.reset();
temps.reset();
append_string(segments.fHeader, &strs, &lengths);
append_string(segments.fGSHeader, &strs, &lengths);
append_decls(segments.fGSInputs, gl, &strs, &lengths, &temps);
append_decls(segments.fGSOutputs, gl, &strs, &lengths, &temps);
append_string(segments.fGSCode, &strs, &lengths);
#if PRINT_SHADERS
print_shader(strs.count(), &strs[0], &lengths[0]);
GrPrintf("\n");
#endif
programData->fGShaderID =
CompileShader(gl, GR_GL_GEOMETRY_SHADER, strs.count(),
&strs[0], &lengths[0]);
} else {
programData->fGShaderID = 0;
}
strs.reset();
lengths.reset();
temps.reset();
append_string(segments.fHeader, &strs, &lengths);
GrStringBuilder precisionStr(GrGetGLSLShaderPrecisionDecl(gl.binding()));
append_string(precisionStr, &strs, &lengths);
append_decls(segments.fFSUnis, gl, &strs, &lengths, &temps);
append_decls(segments.fFSInputs, gl, &strs, &lengths, &temps);
// We shouldn't have declared outputs on 1.10
GrAssert(k110_GrGLSLGeneration != gl.glslGeneration() ||
segments.fFSOutputs.empty());
append_decls(segments.fFSOutputs, gl, &strs, &lengths, &temps);
append_string(segments.fFSFunctions, &strs, &lengths);
append_string(segments.fFSCode, &strs, &lengths);
#if PRINT_SHADERS
print_shader(strs.count(), &strs[0], &lengths[0]);
GrPrintf("\n");
#endif
programData->fFShaderID =
CompileShader(gl, GR_GL_FRAGMENT_SHADER, strs.count(),
&strs[0], &lengths[0]);
if (!programData->fFShaderID) {
return false;
}
return true;
}
#define GL_CALL(X) GR_GL_CALL(gl.interface(), X)
#define GL_CALL_RET(R, X) GR_GL_CALL_RET(gl.interface(), R, X)
GrGLuint GrGLProgram::CompileShader(const GrGLContextInfo& gl,
GrGLenum type,
int stringCnt,
const char** strings,
int* stringLengths) {
SK_TRACE_EVENT1("GrGLProgram::CompileShader",
"stringCount", SkStringPrintf("%i", stringCnt).c_str());
GrGLuint shader;
GL_CALL_RET(shader, CreateShader(type));
if (0 == shader) {
return 0;
}
GrGLint compiled = GR_GL_INIT_ZERO;
GL_CALL(ShaderSource(shader, stringCnt, strings, stringLengths));
GL_CALL(CompileShader(shader));
GL_CALL(GetShaderiv(shader, GR_GL_COMPILE_STATUS, &compiled));
if (!compiled) {
GrGLint infoLen = GR_GL_INIT_ZERO;
GL_CALL(GetShaderiv(shader, GR_GL_INFO_LOG_LENGTH, &infoLen));
SkAutoMalloc log(sizeof(char)*(infoLen+1)); // outside if for debugger
if (infoLen > 0) {
// retrieve length even though we don't need it to workaround
// bug in chrome cmd buffer param validation.
GrGLsizei length = GR_GL_INIT_ZERO;
GL_CALL(GetShaderInfoLog(shader, infoLen+1,
&length, (char*)log.get()));
print_shader(stringCnt, strings, stringLengths);
GrPrintf("\n%s", log.get());
}
GrAssert(!"Shader compilation failed!");
GL_CALL(DeleteShader(shader));
return 0;
}
return shader;
}
bool GrGLProgram::bindOutputsAttribsAndLinkProgram(
const GrGLContextInfo& gl,
GrStringBuilder texCoordAttrNames[],
bool bindColorOut,
bool bindDualSrcOut,
CachedData* programData) const {
GL_CALL_RET(programData->fProgramID, CreateProgram());
if (!programData->fProgramID) {
return false;
}
const GrGLint& progID = programData->fProgramID;
GL_CALL(AttachShader(progID, programData->fVShaderID));
if (programData->fGShaderID) {
GL_CALL(AttachShader(progID, programData->fGShaderID));
}
GL_CALL(AttachShader(progID, programData->fFShaderID));
if (bindColorOut) {
GL_CALL(BindFragDataLocation(programData->fProgramID,
0, declared_color_output_name()));
}
if (bindDualSrcOut) {
GL_CALL(BindFragDataLocationIndexed(programData->fProgramID,
0, 1, dual_source_output_name()));
}
// Bind the attrib locations to same values for all shaders
GL_CALL(BindAttribLocation(progID, PositionAttributeIdx(), POS_ATTR_NAME));
for (int t = 0; t < GrDrawState::kMaxTexCoords; ++t) {
if (texCoordAttrNames[t].size()) {
GL_CALL(BindAttribLocation(progID,
TexCoordAttributeIdx(t),
texCoordAttrNames[t].c_str()));
}
}
GL_CALL(BindAttribLocation(progID, ColorAttributeIdx(), COL_ATTR_NAME));
GL_CALL(BindAttribLocation(progID, CoverageAttributeIdx(), COV_ATTR_NAME));
GL_CALL(BindAttribLocation(progID, EdgeAttributeIdx(), EDGE_ATTR_NAME));
GL_CALL(LinkProgram(progID));
GrGLint linked = GR_GL_INIT_ZERO;
GL_CALL(GetProgramiv(progID, GR_GL_LINK_STATUS, &linked));
if (!linked) {
GrGLint infoLen = GR_GL_INIT_ZERO;
GL_CALL(GetProgramiv(progID, GR_GL_INFO_LOG_LENGTH, &infoLen));
SkAutoMalloc log(sizeof(char)*(infoLen+1)); // outside if for debugger
if (infoLen > 0) {
// retrieve length even though we don't need it to workaround
// bug in chrome cmd buffer param validation.
GrGLsizei length = GR_GL_INIT_ZERO;
GL_CALL(GetProgramInfoLog(progID,
infoLen+1,
&length,
(char*)log.get()));
GrPrintf((char*)log.get());
}
GrAssert(!"Error linking program");
GL_CALL(DeleteProgram(progID));
programData->fProgramID = 0;
return false;
}
return true;
}
void GrGLProgram::getUniformLocationsAndInitCache(const GrGLContextInfo& gl,
CachedData* programData) const {
const GrGLint& progID = programData->fProgramID;
if (kUseUniform == programData->fUniLocations.fViewMatrixUni) {
GL_CALL_RET(programData->fUniLocations.fViewMatrixUni,
GetUniformLocation(progID, VIEW_MATRIX_NAME));
GrAssert(kUnusedUniform != programData->fUniLocations.fViewMatrixUni);
}
if (kUseUniform == programData->fUniLocations.fColorUni) {
GL_CALL_RET(programData->fUniLocations.fColorUni,
GetUniformLocation(progID, COL_UNI_NAME));
GrAssert(kUnusedUniform != programData->fUniLocations.fColorUni);
}
if (kUseUniform == programData->fUniLocations.fColorFilterUni) {
GL_CALL_RET(programData->fUniLocations.fColorFilterUni,
GetUniformLocation(progID, COL_FILTER_UNI_NAME));
GrAssert(kUnusedUniform != programData->fUniLocations.fColorFilterUni);
}
if (kUseUniform == programData->fUniLocations.fColorMatrixUni) {
GL_CALL_RET(programData->fUniLocations.fColorMatrixUni,
GetUniformLocation(progID, COL_MATRIX_UNI_NAME));
}
if (kUseUniform == programData->fUniLocations.fColorMatrixVecUni) {
GL_CALL_RET(programData->fUniLocations.fColorMatrixVecUni,
GetUniformLocation(progID, COL_MATRIX_VEC_UNI_NAME));
}
if (kUseUniform == programData->fUniLocations.fCoverageUni) {
GL_CALL_RET(programData->fUniLocations.fCoverageUni,
GetUniformLocation(progID, COV_UNI_NAME));
GrAssert(kUnusedUniform != programData->fUniLocations.fCoverageUni);
}
for (int s = 0; s < GrDrawState::kNumStages; ++s) {
StageUniLocations& locations = programData->fUniLocations.fStages[s];
if (fProgramDesc.fStages[s].isEnabled()) {
if (kUseUniform == locations.fTextureMatrixUni) {
GrStringBuilder texMName;
tex_matrix_name(s, &texMName);
GL_CALL_RET(locations.fTextureMatrixUni,
GetUniformLocation(progID, texMName.c_str()));
GrAssert(kUnusedUniform != locations.fTextureMatrixUni);
}
if (kUseUniform == locations.fSamplerUni) {
GrStringBuilder samplerName;
sampler_name(s, &samplerName);
GL_CALL_RET(locations.fSamplerUni,
GetUniformLocation(progID,samplerName.c_str()));
GrAssert(kUnusedUniform != locations.fSamplerUni);
}
if (kUseUniform == locations.fTexDomUni) {
GrStringBuilder texDomName;
tex_domain_name(s, &texDomName);
GL_CALL_RET(locations.fTexDomUni,
GetUniformLocation(progID, texDomName.c_str()));
GrAssert(kUnusedUniform != locations.fTexDomUni);
}
if (NULL != programData->fCustomStage[s]) {
programData->fCustomStage[s]->
initUniforms(gl.interface(), progID);
}
}
}
GL_CALL(UseProgram(progID));
// init sampler unis and set bogus values for state tracking
for (int s = 0; s < GrDrawState::kNumStages; ++s) {
if (kUnusedUniform != programData->fUniLocations.fStages[s].fSamplerUni) {
GL_CALL(Uniform1i(programData->fUniLocations.fStages[s].fSamplerUni, s));
}
programData->fTextureMatrices[s] = GrMatrix::InvalidMatrix();
programData->fTextureDomain[s].setEmpty();
// this is arbitrary, just initialize to something
programData->fTextureOrientation[s] =
GrGLTexture::kBottomUp_Orientation;
// Must not reset fStageOverride[] here.
}
programData->fViewMatrix = GrMatrix::InvalidMatrix();
programData->fViewportSize.set(-1, -1);
programData->fColor = GrColor_ILLEGAL;
programData->fColorFilterColor = GrColor_ILLEGAL;
}
//============================================================================
// Stage code generation
//============================================================================
void GrGLProgram::genStageCode(const GrGLContextInfo& gl,
int stageNum,
const GrGLProgram::StageDesc& desc,
const char* fsInColor, // NULL means no incoming color
const char* fsOutColor,
const char* vsInCoord,
GrGLShaderBuilder* segments,
StageUniLocations* locations,
GrGLProgramStage* customStage) const {
GrAssert(stageNum >= 0 && stageNum <= GrDrawState::kNumStages);
GrAssert((desc.fInConfigFlags & StageDesc::kInConfigBitMask) ==
desc.fInConfigFlags);
/// Vertex Shader Stuff
// decide whether we need a matrix to transform texture coords
// and whether the varying needs a perspective coord.
const char* matName = NULL;
if (desc.fOptFlags & StageDesc::kIdentityMatrix_OptFlagBit) {
segments->fVaryingDims = segments->fCoordDims;
} else {
GrStringBuilder texMatName;
tex_matrix_name(stageNum, &texMatName);
const GrGLShaderVar* mat = &segments->addUniform(
GrGLShaderBuilder::kVertex_VariableLifetime, kMat33f_GrSLType,
texMatName.c_str());
// Can't use texMatName.c_str() because it's on the stack!
matName = mat->getName().c_str();
locations->fTextureMatrixUni = kUseUniform;
if (desc.fOptFlags & StageDesc::kNoPerspective_OptFlagBit) {
segments->fVaryingDims = segments->fCoordDims;
} else {
segments->fVaryingDims = segments->fCoordDims + 1;
}
}
GrAssert(segments->fVaryingDims > 0);
// Must setup variables after computing segments->fVaryingDims
if (NULL != customStage) {
customStage->setupVariables(segments, stageNum);
}
GrStringBuilder samplerName;
sampler_name(stageNum, &samplerName);
// const GrGLShaderVar* sampler = &
segments->addUniform(GrGLShaderBuilder::kFragment_VariableLifetime,
kSampler2D_GrSLType, samplerName.c_str());
locations->fSamplerUni = kUseUniform;
const char *varyingVSName, *varyingFSName;
segments->addVarying(GrSLFloatVectorType(segments->fVaryingDims),
"Stage",
stageNum,
&varyingVSName,
&varyingFSName);
if (!matName) {
GrAssert(segments->fVaryingDims == segments->fCoordDims);
segments->fVSCode.appendf("\t%s = %s;\n", varyingVSName, vsInCoord);
} else {
// varying = texMatrix * texCoord
segments->fVSCode.appendf("\t%s = (%s * vec3(%s, 1))%s;\n",
varyingVSName, matName, vsInCoord,
vector_all_coords(segments->fVaryingDims));
}
// GrGLShaderVar* kernel = NULL;
// const char* imageIncrementName = NULL;
if (NULL != customStage) {
segments->fVSCode.appendf("\t{ // stage %d %s\n",
stageNum, customStage->name());
customStage->emitVS(segments, varyingVSName);
segments->fVSCode.appendf("\t}\n");
}
/// Fragment Shader Stuff
segments->fSampleCoords = varyingFSName;
GrGLShaderBuilder::SamplerMode sampleMode =
GrGLShaderBuilder::kExplicitDivide_SamplerMode;
if (desc.fOptFlags & (StageDesc::kIdentityMatrix_OptFlagBit |
StageDesc::kNoPerspective_OptFlagBit)) {
sampleMode = GrGLShaderBuilder::kDefault_SamplerMode;
} else if (NULL == customStage) {
sampleMode = GrGLShaderBuilder::kProj_SamplerMode;
}
segments->setupTextureAccess(sampleMode, stageNum);
segments->computeSwizzle(desc.fInConfigFlags);
segments->computeModulate(fsInColor);
static const uint32_t kMulByAlphaMask =
(StageDesc::kMulRGBByAlpha_RoundUp_InConfigFlag |
StageDesc::kMulRGBByAlpha_RoundDown_InConfigFlag);
if (desc.fOptFlags & StageDesc::kCustomTextureDomain_OptFlagBit) {
GrStringBuilder texDomainName;
tex_domain_name(stageNum, &texDomainName);
// const GrGLShaderVar* texDomain = &
segments->addUniform(
GrGLShaderBuilder::kFragment_VariableLifetime,
kVec4f_GrSLType, texDomainName.c_str());
GrStringBuilder coordVar("clampCoord");
segments->fFSCode.appendf("\t%s %s = clamp(%s, %s.xy, %s.zw);\n",
float_vector_type_str(segments->fCoordDims),
coordVar.c_str(),
segments->fSampleCoords.c_str(),
texDomainName.c_str(),
texDomainName.c_str());
segments->fSampleCoords = coordVar;
locations->fTexDomUni = kUseUniform;
}
// NOTE: GrGLProgramStages are now responsible for fetching
if (NULL == customStage) {
if (desc.fInConfigFlags & kMulByAlphaMask) {
// only one of the mul by alpha flags should be set
GrAssert(GrIsPow2(kMulByAlphaMask & desc.fInConfigFlags));
GrAssert(!(desc.fInConfigFlags &
StageDesc::kSmearAlpha_InConfigFlag));
GrAssert(!(desc.fInConfigFlags &
StageDesc::kSmearRed_InConfigFlag));
segments->fFSCode.appendf("\t%s = %s(%s, %s)%s;\n",
fsOutColor,
segments->fTexFunc.c_str(),
samplerName.c_str(),
segments->fSampleCoords.c_str(),
segments->fSwizzle.c_str());
if (desc.fInConfigFlags &
StageDesc::kMulRGBByAlpha_RoundUp_InConfigFlag) {
segments->fFSCode.appendf("\t%s = vec4(ceil(%s.rgb*%s.a*255.0)/255.0,%s.a)%s;\n",
fsOutColor, fsOutColor, fsOutColor,
fsOutColor, segments->fModulate.c_str());
} else {
segments->fFSCode.appendf("\t%s = vec4(floor(%s.rgb*%s.a*255.0)/255.0,%s.a)%s;\n",
fsOutColor, fsOutColor, fsOutColor,
fsOutColor, segments->fModulate.c_str());
}
} else {
segments->emitDefaultFetch(fsOutColor, samplerName.c_str());
}
}
if (NULL != customStage) {
// Enclose custom code in a block to avoid namespace conflicts
segments->fFSCode.appendf("\t{ // stage %d %s \n",
stageNum, customStage->name());
customStage->emitFS(segments, fsOutColor, fsInColor,
samplerName.c_str());
segments->fFSCode.appendf("\t}\n");
}
}
| [
"gloam@163.com"
] | gloam@163.com |
19ae199086b2f10c4eae1bc647fe99ab519f8b5e | a815edcd3c7dcbb79d7fc20801c0170f3408b1d6 | /chrome/browser/chromeos/child_accounts/screen_time_controller.cc | c48859a58e00ed7a6bc7f6d1ebc39d2943f97419 | [
"BSD-3-Clause"
] | permissive | oguzzkilic/chromium | 06be90df9f2e7f218bff6eee94235b6e684e2b40 | 1de71b638f99c15a3f97ec7b25b0c6dc920fbee0 | refs/heads/master | 2023-03-04T00:01:27.864257 | 2018-07-17T10:33:19 | 2018-07-17T10:33:19 | 141,275,697 | 1 | 0 | null | 2018-07-17T10:48:53 | 2018-07-17T10:48:52 | null | UTF-8 | C++ | false | false | 18,193 | cc | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/child_accounts/screen_time_controller.h"
#include "ash/public/cpp/vector_icons/vector_icons.h"
#include "base/optional.h"
#include "chrome/browser/chromeos/profiles/profile_helper.h"
#include "chrome/browser/notifications/notification_display_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/ash/login_screen_client.h"
#include "chrome/common/pref_names.h"
#include "chrome/grit/generated_resources.h"
#include "chromeos/dbus/dbus_thread_manager.h"
#include "chromeos/dbus/session_manager_client.h"
#include "components/prefs/pref_registry_simple.h"
#include "components/prefs/pref_service.h"
#include "components/session_manager/core/session_manager.h"
#include "content/public/browser/browser_context.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/l10n/time_format.h"
#include "ui/message_center/public/cpp/notification.h"
namespace chromeos {
namespace {
constexpr base::TimeDelta kWarningNotificationTimeout =
base::TimeDelta::FromMinutes(5);
constexpr base::TimeDelta kExitNotificationTimeout =
base::TimeDelta::FromMinutes(1);
constexpr base::TimeDelta kScreenTimeUsageUpdateFrequency =
base::TimeDelta::FromMinutes(1);
// The notification id. All the time limit notifications share the same id so
// that a subsequent notification can replace the previous one.
constexpr char kTimeLimitNotificationId[] = "time-limit-notification";
// The notifier id representing the app.
constexpr char kTimeLimitNotifierId[] = "family-link";
// Dictionary keys for prefs::kScreenTimeLastState.
constexpr char kScreenStateLocked[] = "locked";
constexpr char kScreenStateCurrentPolicyType[] = "active_policy";
constexpr char kScreenStateTimeUsageLimitEnabled[] = "time_usage_limit_enabled";
constexpr char kScreenStateRemainingUsage[] = "remaining_usage";
constexpr char kScreenStateUsageLimitStarted[] = "usage_limit_started";
constexpr char kScreenStateNextStateChangeTime[] = "next_state_change_time";
constexpr char kScreenStateNextPolicyType[] = "next_active_policy";
constexpr char kScreenStateNextUnlockTime[] = "next_unlock_time";
constexpr char kScreenStateLastStateChanged[] = "last_state_changed";
} // namespace
// static
void ScreenTimeController::RegisterProfilePrefs(PrefRegistrySimple* registry) {
registry->RegisterTimePref(prefs::kCurrentScreenStartTime, base::Time());
registry->RegisterTimePref(prefs::kFirstScreenStartTime, base::Time());
registry->RegisterIntegerPref(prefs::kScreenTimeMinutesUsed, 0);
registry->RegisterDictionaryPref(prefs::kUsageTimeLimit);
registry->RegisterDictionaryPref(prefs::kScreenTimeLastState);
}
ScreenTimeController::ScreenTimeController(content::BrowserContext* context)
: context_(context),
pref_service_(Profile::FromBrowserContext(context)->GetPrefs()) {
session_manager::SessionManager::Get()->AddObserver(this);
pref_change_registrar_.Init(pref_service_);
pref_change_registrar_.Add(
prefs::kUsageTimeLimit,
base::BindRepeating(&ScreenTimeController::OnPolicyChanged,
base::Unretained(this)));
}
ScreenTimeController::~ScreenTimeController() {
session_manager::SessionManager::Get()->RemoveObserver(this);
SaveScreenTimeProgressBeforeExit();
}
base::TimeDelta ScreenTimeController::GetScreenTimeDuration() const {
base::TimeDelta previous_duration = base::TimeDelta::FromMinutes(
pref_service_->GetInteger(prefs::kScreenTimeMinutesUsed));
if (current_screen_start_time_.is_null())
return previous_duration;
base::TimeDelta current_screen_duration =
base::Time::Now() - current_screen_start_time_;
return current_screen_duration + previous_duration;
}
void ScreenTimeController::CheckTimeLimit() {
// Stop any currently running timer.
ResetTimers();
base::Time now = base::Time::Now();
base::Optional<usage_time_limit::State> last_state = GetLastStateFromPref();
// Used time should be 0 when time usage limit is disabled.
base::TimeDelta used_time = base::TimeDelta::FromMinutes(0);
if (last_state && last_state->is_time_usage_limit_enabled)
used_time = GetScreenTimeDuration();
const base::DictionaryValue* time_limit =
pref_service_->GetDictionary(prefs::kUsageTimeLimit);
usage_time_limit::State state =
usage_time_limit::GetState(time_limit->CreateDeepCopy(), used_time,
first_screen_start_time_, now, last_state);
SaveCurrentStateToPref(state);
// Show/hide time limits message based on the policy enforcement.
UpdateTimeLimitsMessage(
state.is_locked, state.is_locked ? state.next_unlock_time : base::Time());
if (state.is_locked) {
DCHECK(!state.next_unlock_time.is_null());
if (!session_manager::SessionManager::Get()->IsScreenLocked())
ForceScreenLockByPolicy(state.next_unlock_time);
} else {
base::Optional<TimeLimitNotificationType> notification_type;
switch (state.next_state_active_policy) {
case usage_time_limit::ActivePolicies::kFixedLimit:
notification_type = kBedTime;
break;
case usage_time_limit::ActivePolicies::kUsageLimit:
notification_type = kScreenTime;
break;
case usage_time_limit::ActivePolicies::kNoActivePolicy:
case usage_time_limit::ActivePolicies::kOverride:
break;
default:
NOTREACHED();
}
if (notification_type.has_value()) {
// Schedule notification based on the remaining screen time until lock.
const base::TimeDelta remaining_time = state.next_state_change_time - now;
if (remaining_time >= kWarningNotificationTimeout) {
warning_notification_timer_.Start(
FROM_HERE, remaining_time - kWarningNotificationTimeout,
base::BindRepeating(
&ScreenTimeController::ShowNotification, base::Unretained(this),
notification_type.value(), kWarningNotificationTimeout));
}
if (remaining_time >= kExitNotificationTimeout) {
exit_notification_timer_.Start(
FROM_HERE, remaining_time - kExitNotificationTimeout,
base::BindRepeating(
&ScreenTimeController::ShowNotification, base::Unretained(this),
notification_type.value(), kExitNotificationTimeout));
}
}
// The screen limit should start counting only when the time usage limit is
// set, ignoring the amount of time that the device was used before.
if (state.is_time_usage_limit_enabled &&
(!last_state || !last_state->is_time_usage_limit_enabled)) {
RefreshScreenLimit();
}
}
if (!state.next_state_change_time.is_null()) {
next_state_timer_.Start(
FROM_HERE, state.next_state_change_time - base::Time::Now(),
base::BindRepeating(&ScreenTimeController::CheckTimeLimit,
base::Unretained(this)));
}
// Schedule timer to refresh the screen time usage.
base::Time reset_time =
usage_time_limit::GetExpectedResetTime(time_limit->CreateDeepCopy(), now);
if (reset_time <= now) {
RefreshScreenLimit();
} else {
reset_screen_time_timer_.Start(
FROM_HERE, reset_time - now,
base::BindRepeating(&ScreenTimeController::RefreshScreenLimit,
base::Unretained(this)));
}
}
void ScreenTimeController::ForceScreenLockByPolicy(
base::Time next_unlock_time) {
DCHECK(!session_manager::SessionManager::Get()->IsScreenLocked());
chromeos::DBusThreadManager::Get()
->GetSessionManagerClient()
->RequestLockScreen();
// Update the time limits message when the lock screen UI is ready.
next_unlock_time_ = next_unlock_time;
}
void ScreenTimeController::UpdateTimeLimitsMessage(
bool visible,
base::Time next_unlock_time) {
DCHECK(visible || next_unlock_time.is_null());
if (!session_manager::SessionManager::Get()->IsScreenLocked())
return;
AccountId account_id =
chromeos::ProfileHelper::Get()
->GetUserByProfile(Profile::FromBrowserContext(context_))
->GetAccountId();
LoginScreenClient::Get()->login_screen()->SetAuthEnabledForUser(
account_id, !visible,
visible ? next_unlock_time : base::Optional<base::Time>());
}
void ScreenTimeController::ShowNotification(
ScreenTimeController::TimeLimitNotificationType type,
const base::TimeDelta& time_remaining) {
const base::string16 title = l10n_util::GetStringUTF16(
type == kScreenTime ? IDS_SCREEN_TIME_NOTIFICATION_TITLE
: IDS_BED_TIME_NOTIFICATION_TITLE);
std::unique_ptr<message_center::Notification> notification =
message_center::Notification::CreateSystemNotification(
message_center::NOTIFICATION_TYPE_SIMPLE, kTimeLimitNotificationId,
title,
ui::TimeFormat::Simple(ui::TimeFormat::FORMAT_DURATION,
ui::TimeFormat::LENGTH_LONG, time_remaining),
gfx::Image(),
l10n_util::GetStringUTF16(IDS_TIME_LIMIT_NOTIFICATION_DISPLAY_SOURCE),
GURL(),
message_center::NotifierId(
message_center::NotifierId::SYSTEM_COMPONENT,
kTimeLimitNotifierId),
message_center::RichNotificationData(),
new message_center::NotificationDelegate(),
ash::kNotificationSupervisedUserIcon,
message_center::SystemNotificationWarningLevel::NORMAL);
NotificationDisplayService::GetForProfile(
Profile::FromBrowserContext(context_))
->Display(NotificationHandler::Type::TRANSIENT, *notification);
}
void ScreenTimeController::RefreshScreenLimit() {
base::Time now = base::Time::Now();
pref_service_->SetTime(prefs::kFirstScreenStartTime, now);
pref_service_->SetTime(prefs::kCurrentScreenStartTime, now);
pref_service_->SetInteger(prefs::kScreenTimeMinutesUsed, 0);
pref_service_->CommitPendingWrite();
first_screen_start_time_ = now;
current_screen_start_time_ = now;
}
void ScreenTimeController::OnPolicyChanged() {
CheckTimeLimit();
}
void ScreenTimeController::ResetTimers() {
next_state_timer_.Stop();
warning_notification_timer_.Stop();
exit_notification_timer_.Stop();
save_screen_time_timer_.Stop();
reset_screen_time_timer_.Stop();
}
void ScreenTimeController::SaveScreenTimeProgressBeforeExit() {
pref_service_->SetInteger(prefs::kScreenTimeMinutesUsed,
GetScreenTimeDuration().InMinutes());
pref_service_->ClearPref(prefs::kCurrentScreenStartTime);
pref_service_->CommitPendingWrite();
current_screen_start_time_ = base::Time();
ResetTimers();
}
void ScreenTimeController::SaveScreenTimeProgressPeriodically() {
pref_service_->SetInteger(prefs::kScreenTimeMinutesUsed,
GetScreenTimeDuration().InMinutes());
current_screen_start_time_ = base::Time::Now();
pref_service_->SetTime(prefs::kCurrentScreenStartTime,
current_screen_start_time_);
pref_service_->CommitPendingWrite();
}
void ScreenTimeController::SaveCurrentStateToPref(
const usage_time_limit::State& state) {
auto state_dict =
std::make_unique<base::Value>(base::Value::Type::DICTIONARY);
state_dict->SetKey(kScreenStateLocked, base::Value(state.is_locked));
state_dict->SetKey(kScreenStateCurrentPolicyType,
base::Value(static_cast<int>(state.active_policy)));
state_dict->SetKey(kScreenStateTimeUsageLimitEnabled,
base::Value(state.is_time_usage_limit_enabled));
state_dict->SetKey(kScreenStateRemainingUsage,
base::Value(state.remaining_usage.InMinutes()));
state_dict->SetKey(kScreenStateUsageLimitStarted,
base::Value(state.time_usage_limit_started.ToDoubleT()));
state_dict->SetKey(kScreenStateNextStateChangeTime,
base::Value(state.next_state_change_time.ToDoubleT()));
state_dict->SetKey(
kScreenStateNextPolicyType,
base::Value(static_cast<int>(state.next_state_active_policy)));
state_dict->SetKey(kScreenStateNextUnlockTime,
base::Value(state.next_unlock_time.ToDoubleT()));
state_dict->SetKey(kScreenStateLastStateChanged,
base::Value(state.last_state_changed.ToDoubleT()));
pref_service_->Set(prefs::kScreenTimeLastState, *state_dict);
pref_service_->CommitPendingWrite();
}
base::Optional<usage_time_limit::State>
ScreenTimeController::GetLastStateFromPref() {
const base::DictionaryValue* last_state =
pref_service_->GetDictionary(prefs::kScreenTimeLastState);
usage_time_limit::State result;
if (last_state->empty())
return base::nullopt;
// Verify is_locked from the pref is a boolean value.
const base::Value* is_locked = last_state->FindKey(kScreenStateLocked);
if (!is_locked || !is_locked->is_bool())
return base::nullopt;
result.is_locked = is_locked->GetBool();
// Verify active policy type is a value of usage_time_limit::ActivePolicies.
const base::Value* active_policy =
last_state->FindKey(kScreenStateCurrentPolicyType);
// TODO(crbug.com/823536): Add kCount in usage_time_limit::ActivePolicies
// instead of checking kUsageLimit here.
if (!active_policy || !active_policy->is_int() ||
active_policy->GetInt() < 0 ||
active_policy->GetInt() >
static_cast<int>(usage_time_limit::ActivePolicies::kUsageLimit)) {
return base::nullopt;
}
result.active_policy =
static_cast<usage_time_limit::ActivePolicies>(active_policy->GetInt());
// Verify time_usage_limit_enabled from the pref is a boolean value.
const base::Value* time_usage_limit_enabled =
last_state->FindKey(kScreenStateTimeUsageLimitEnabled);
if (!time_usage_limit_enabled || !time_usage_limit_enabled->is_bool())
return base::nullopt;
result.is_time_usage_limit_enabled = time_usage_limit_enabled->GetBool();
// Verify remaining_usage from the pref is a int value.
const base::Value* remaining_usage =
last_state->FindKey(kScreenStateRemainingUsage);
if (!remaining_usage || !remaining_usage->is_int())
return base::nullopt;
result.remaining_usage =
base::TimeDelta::FromMinutes(remaining_usage->GetInt());
// Verify time_usage_limit_started from the pref is a double value.
const base::Value* time_usage_limit_started =
last_state->FindKey(kScreenStateUsageLimitStarted);
if (!time_usage_limit_started || !time_usage_limit_started->is_double())
return base::nullopt;
result.time_usage_limit_started =
base::Time::FromDoubleT(time_usage_limit_started->GetDouble());
// Verify next_state_change_time from the pref is a double value.
const base::Value* next_state_change_time =
last_state->FindKey(kScreenStateNextStateChangeTime);
if (!next_state_change_time || !next_state_change_time->is_double())
return base::nullopt;
result.next_state_change_time =
base::Time::FromDoubleT(next_state_change_time->GetDouble());
// Verify next policy type is a value of usage_time_limit::ActivePolicies.
const base::Value* next_active_policy =
last_state->FindKey(kScreenStateNextPolicyType);
if (!next_active_policy || !next_active_policy->is_int() ||
next_active_policy->GetInt() < 0 ||
next_active_policy->GetInt() >
static_cast<int>(usage_time_limit::ActivePolicies::kUsageLimit)) {
return base::nullopt;
}
result.next_state_active_policy =
static_cast<usage_time_limit::ActivePolicies>(
next_active_policy->GetInt());
// Verify next_unlock_time from the pref is a double value.
const base::Value* next_unlock_time =
last_state->FindKey(kScreenStateNextUnlockTime);
if (!next_unlock_time || !next_unlock_time->is_double())
return base::nullopt;
result.next_unlock_time =
base::Time::FromDoubleT(next_unlock_time->GetDouble());
// Verify last_state_changed from the pref is a double value.
const base::Value* last_state_changed =
last_state->FindKey(kScreenStateLastStateChanged);
if (!last_state_changed || !last_state_changed->is_double())
return base::nullopt;
result.last_state_changed =
base::Time::FromDoubleT(last_state_changed->GetDouble());
return result;
}
void ScreenTimeController::OnSessionStateChanged() {
session_manager::SessionState session_state =
session_manager::SessionManager::Get()->session_state();
if (session_state == session_manager::SessionState::LOCKED) {
if (next_unlock_time_) {
UpdateTimeLimitsMessage(true /*visible*/, next_unlock_time_.value());
next_unlock_time_.reset();
}
SaveScreenTimeProgressBeforeExit();
} else if (session_state == session_manager::SessionState::ACTIVE) {
base::Time now = base::Time::Now();
const base::Time first_screen_start_time =
pref_service_->GetTime(prefs::kFirstScreenStartTime);
if (first_screen_start_time.is_null()) {
pref_service_->SetTime(prefs::kFirstScreenStartTime, now);
first_screen_start_time_ = now;
} else {
first_screen_start_time_ = first_screen_start_time;
}
const base::Time current_screen_start_time =
pref_service_->GetTime(prefs::kCurrentScreenStartTime);
if (!current_screen_start_time.is_null() &&
current_screen_start_time < now &&
(now - current_screen_start_time) <
2 * kScreenTimeUsageUpdateFrequency) {
current_screen_start_time_ = current_screen_start_time;
} else {
// If kCurrentScreenStartTime is not set or it's been too long since the
// last update, set the time to now.
current_screen_start_time_ = now;
}
pref_service_->SetTime(prefs::kCurrentScreenStartTime,
current_screen_start_time_);
pref_service_->CommitPendingWrite();
CheckTimeLimit();
save_screen_time_timer_.Start(
FROM_HERE, kScreenTimeUsageUpdateFrequency,
base::BindRepeating(
&ScreenTimeController::SaveScreenTimeProgressPeriodically,
base::Unretained(this)));
}
}
} // namespace chromeos
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
9fea92ccdca8488d1a52af72db2b62769532b23a | e4516bc1ef2407c524af95f5b6754b3a3c37b3cc | /answers/pat/1073. Scientific Notation (20).cpp | 83260d4ef3419d4d92436b767a4b4d83bae6e2dc | [
"MIT"
] | permissive | FeiZhan/Algo-Collection | 7102732d61f324ffe5509ee48c5015b2a96cd58d | 9ecfe00151aa18e24846e318c8ed7bea9af48a57 | refs/heads/master | 2023-06-10T17:36:53.473372 | 2023-06-02T01:33:59 | 2023-06-02T01:33:59 | 3,762,869 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,314 | cpp | //
#include <cstdio>
#include <iostream>
using namespace std;
#include <cstdlib>
#include <string>
int main (int argc, char *argv[]) {
string scien;
while (cin >> scien) {
size_t found = scien.find('e');
if (found == string::npos) {
found = scien.find('E');
}
string fractional = scien.substr(0, found);
int exponent = atoi(scien.substr(found + 1).c_str());
size_t dot = fractional.find('.');
if (string::npos == dot) {
dot = fractional.length();
}
//cout << fractional << " e " << exponent << endl;
if (exponent > 0) {
int zeros = exponent - fractional.length() + dot + 1;
if (zeros > 0) {
fractional += string(zeros, '0');
}
if (fractional.size() > dot && '.' == fractional[dot]) {
fractional.erase(dot, 1);
}
if (fractional.size() > dot + exponent) {
fractional.insert(dot + exponent, 1, '.');
}
}
else {
int zeros = - exponent - dot + 2;
if (zeros > 0) {
fractional.insert(1, zeros, '0');
}
if (fractional.size() > dot + zeros + 1 && '.' == fractional[dot + zeros]) {
fractional.erase(dot + zeros, 1);
}
fractional.insert(dot + zeros + exponent, 1, '.');
}
if ('+' == fractional[0]) {
fractional.erase(0, 1);
}
cout << fractional << endl;
}
return 0;
} | [
"dog217@126.com"
] | dog217@126.com |
418b6c3245f4254019c741db7db4745e9c8d5ef9 | 66511b371329a068a3e52452c47a161e4d650109 | /fgame/flamethrower.h | ba778c604d5989fede10f3b72ec3a5a2dabcc3f8 | [] | no_license | HaZardModding/fakk2_coop_mod | 8f619f288e09dbce6a1dc8adfe25759bdf682b8c | 3ab0c8ce011c93ff861924f02284f7948c7ce8b8 | refs/heads/master | 2022-11-21T02:35:04.523416 | 2020-07-22T06:40:16 | 2020-07-22T06:40:16 | 281,033,547 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,580 | h | //-----------------------------------------------------------------------------
//
// $Logfile:: /fakk2_code/fakk2_new/fgame/flamethrower.h $
// $Revision:: 6 $
// $Author:: Markd $
// $Date:: 6/14/00 3:50p $
//
// Copyright (C) 1998 by Ritual Entertainment, Inc.
// All rights reserved.
//
// This source may not be distributed and/or modified without
// expressly written permission by Ritual Entertainment, Inc.
//
// $Log:: /fakk2_code/fakk2_new/fgame/flamethrower.h $
//
// 6 6/14/00 3:50p Markd
// Cleaned up more Intel Compiler warnings
//
// 5 5/26/00 7:44p Markd
// 2nd phase save games
//
// 4 5/24/00 3:14p Markd
// first phase of save/load games
//
// 3 5/05/00 5:18p Aldie
// comment
//
// 2 5/05/00 5:17p Aldie
// Flamethrower
//
// DESCRIPTION:
// Flamethrower weapon
#ifndef __FLAMETHROWER_H__
#define __FLAMETHROWER_H__
#include "weapon.h"
#include "weaputils.h"
class Flamethrower : public Weapon
{
private:
Animate *m_gas;
public:
CLASS_PROTOTYPE( Flamethrower );
Flamethrower();
virtual void Shoot( Event *ev );
virtual void Archive( Archiver &arc );
};
inline void Flamethrower::Archive
(
Archiver &arc
)
{
Weapon::Archive( arc );
arc.ArchiveObjectPointer( ( Class ** )&m_gas );
}
#endif // __FLAMETHROWER_H__
| [
"chrissstrahl@yahoo.de"
] | chrissstrahl@yahoo.de |
2c56e9d9c0ec790cf09ad0f2d8785bffa665d13e | 90047daeb462598a924d76ddf4288e832e86417c | /base/metrics/histogram_functions.h | 5960aca657497357e7146aff8b0e5997b9d356f6 | [
"BSD-3-Clause"
] | permissive | massbrowser/android | 99b8c21fa4552a13c06bbedd0f9c88dd4a4ad080 | a9c4371682c9443d6e1d66005d4db61a24a9617c | refs/heads/master | 2022-11-04T21:15:50.656802 | 2017-06-08T12:31:39 | 2017-06-08T12:31:39 | 93,747,579 | 2 | 2 | BSD-3-Clause | 2022-10-31T10:34:25 | 2017-06-08T12:36:07 | null | UTF-8 | C++ | false | false | 4,966 | h | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef BASE_METRICS_HISTOGRAM_FUNCTIONS_H_
#define BASE_METRICS_HISTOGRAM_FUNCTIONS_H_
#include "base/metrics/histogram.h"
#include "base/metrics/histogram_base.h"
#include "base/time/time.h"
// Functions for recording metrics.
//
// For best practices on deciding when to emit to a histogram and what form
// the histogram should take, see
// https://chromium.googlesource.com/chromium/src.git/+/HEAD/tools/metrics/histograms/README.md
// Functions for recording UMA histograms. These can be used for cases
// when the histogram name is generated at runtime. The functionality is
// equivalent to macros defined in histogram_macros.h but allowing non-constant
// histogram names. These functions are slower compared to their macro
// equivalent because the histogram objects are not cached between calls.
// So, these shouldn't be used in performance critical code.
namespace base {
// For histograms with linear buckets.
// Used for capturing integer data with a linear bucketing scheme. This can be
// used when you want the exact value of some small numeric count, with a max of
// 100 or less. If you need to capture a range of greater than 100, we recommend
// the use of the COUNT histograms below.
// Sample usage:
// base::UmaHistogramExactLinear("Histogram.Linear", some_value, 10);
BASE_EXPORT void UmaHistogramExactLinear(const std::string& name,
int sample,
int value_max);
// For adding sample to enum histogram.
// Sample usage:
// base::UmaHistogramEnumeration("My.Enumeration", VALUE, EVENT_MAX_VALUE);
// Note that new Enum values can be added, but existing enums must never be
// renumbered or deleted and reused.
template <typename T>
void UmaHistogramEnumeration(const std::string& name, T sample, T max) {
static_assert(std::is_enum<T>::value,
"Non enum passed to UmaHistogramEnumeration");
DCHECK_LE(static_cast<uintmax_t>(max), static_cast<uintmax_t>(INT_MAX));
DCHECK_LE(static_cast<uintmax_t>(sample), static_cast<uintmax_t>(max));
return UmaHistogramExactLinear(name, static_cast<int>(sample),
static_cast<int>(max));
}
// For adding boolean sample to histogram.
// Sample usage:
// base::UmaHistogramBoolean("My.Boolean", true)
BASE_EXPORT void UmaHistogramBoolean(const std::string& name, bool sample);
// For adding histogram with percent.
// Percents are integer between 1 and 100.
// Sample usage:
// base::UmaHistogramPercentage("My.Percent", 69)
BASE_EXPORT void UmaHistogramPercentage(const std::string& name, int percent);
// For adding counts histogram.
// Sample usage:
// base::UmaHistogramCustomCounts("My.Counts", some_value, 1, 600, 30)
BASE_EXPORT void UmaHistogramCustomCounts(const std::string& name,
int sample,
int min,
int max,
int buckets);
// Counts specialization for maximum counts 100, 1000, 10k, 100k, 1M and 10M.
BASE_EXPORT void UmaHistogramCounts100(const std::string& name, int sample);
BASE_EXPORT void UmaHistogramCounts1000(const std::string& name, int sample);
BASE_EXPORT void UmaHistogramCounts10000(const std::string& name, int sample);
BASE_EXPORT void UmaHistogramCounts100000(const std::string& name, int sample);
BASE_EXPORT void UmaHistogramCounts1M(const std::string& name, int sample);
BASE_EXPORT void UmaHistogramCounts10M(const std::string& name, int sample);
// For histograms storing times.
BASE_EXPORT void UmaHistogramCustomTimes(const std::string& name,
TimeDelta sample,
TimeDelta min,
TimeDelta max,
int buckets);
// For short timings from 1 ms up to 10 seconds (50 buckets).
BASE_EXPORT void UmaHistogramTimes(const std::string& name, TimeDelta sample);
// For medium timings up to 3 minutes (50 buckets).
BASE_EXPORT void UmaHistogramMediumTimes(const std::string& name,
TimeDelta sample);
// For time intervals up to 1 hr (50 buckets).
BASE_EXPORT void UmaHistogramLongTimes(const std::string& name,
TimeDelta sample);
// For recording memory related histograms.
// Used to measure common KB-granularity memory stats. Range is up to 500M.
BASE_EXPORT void UmaHistogramMemoryKB(const std::string& name, int sample);
// Used to measure common MB-granularity memory stats. Range is up to ~64G.
BASE_EXPORT void UmaHistogramMemoryLargeMB(const std::string& name, int sample);
} // namespace base
#endif // BASE_METRICS_HISTOGRAM_FUNCTIONS_H_
| [
"xElvis89x@gmail.com"
] | xElvis89x@gmail.com |
d7f3fca77a83762ccb7bd230b5a517537dc4a688 | f6439b5ed1614fd8db05fa963b47765eae225eb5 | /media/cast/test/receiver.cc | e87055420f891f8b2219d102766a0bf78515e3c4 | [
"BSD-3-Clause"
] | permissive | aranajhonny/chromium | b8a3c975211e1ea2f15b83647b4d8eb45252f1be | caf5bcb822f79b8997720e589334266551a50a13 | refs/heads/master | 2021-05-11T00:20:34.020261 | 2018-01-21T03:31:45 | 2018-01-21T03:31:45 | 118,301,142 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 22,936 | cc | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <algorithm>
#include <climits>
#include <cstdarg>
#include <cstdio>
#include <deque>
#include <map>
#include <string>
#include <utility>
#include "base/at_exit.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "base/memory/ref_counted.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop/message_loop.h"
#include "base/synchronization/lock.h"
#include "base/synchronization/waitable_event.h"
#include "base/threading/thread.h"
#include "base/time/default_tick_clock.h"
#include "base/timer/timer.h"
#include "media/audio/audio_io.h"
#include "media/audio/audio_manager.h"
#include "media/audio/audio_parameters.h"
#include "media/audio/fake_audio_log_factory.h"
#include "media/base/audio_bus.h"
#include "media/base/channel_layout.h"
#include "media/base/video_frame.h"
#include "media/cast/cast_config.h"
#include "media/cast/cast_environment.h"
#include "media/cast/cast_receiver.h"
#include "media/cast/logging/logging_defines.h"
#include "media/cast/net/udp_transport.h"
#include "media/cast/test/utility/audio_utility.h"
#include "media/cast/test/utility/barcode.h"
#include "media/cast/test/utility/default_config.h"
#include "media/cast/test/utility/in_process_receiver.h"
#include "media/cast/test/utility/input_builder.h"
#include "media/cast/test/utility/standalone_cast_environment.h"
#include "net/base/net_util.h"
#if defined(OS_LINUX)
#include "media/cast/test/linux_output_window.h"
#endif // OS_LINUX
namespace media {
namespace cast {
// Settings chosen to match default sender settings.
#define DEFAULT_SEND_PORT "0"
#define DEFAULT_RECEIVE_PORT "2344"
#define DEFAULT_SEND_IP "0.0.0.0"
#define DEFAULT_AUDIO_FEEDBACK_SSRC "2"
#define DEFAULT_AUDIO_INCOMING_SSRC "1"
#define DEFAULT_AUDIO_PAYLOAD_TYPE "127"
#define DEFAULT_VIDEO_FEEDBACK_SSRC "12"
#define DEFAULT_VIDEO_INCOMING_SSRC "11"
#define DEFAULT_VIDEO_PAYLOAD_TYPE "96"
#if defined(OS_LINUX)
const char* kVideoWindowWidth = "1280";
const char* kVideoWindowHeight = "720";
#endif // OS_LINUX
void GetPorts(int* tx_port, int* rx_port) {
test::InputBuilder tx_input(
"Enter send port.", DEFAULT_SEND_PORT, 1, INT_MAX);
*tx_port = tx_input.GetIntInput();
test::InputBuilder rx_input(
"Enter receive port.", DEFAULT_RECEIVE_PORT, 1, INT_MAX);
*rx_port = rx_input.GetIntInput();
}
std::string GetIpAddress(const std::string display_text) {
test::InputBuilder input(display_text, DEFAULT_SEND_IP, INT_MIN, INT_MAX);
std::string ip_address = input.GetStringInput();
// Ensure IP address is either the default value or in correct form.
while (ip_address != DEFAULT_SEND_IP &&
std::count(ip_address.begin(), ip_address.end(), '.') != 3) {
ip_address = input.GetStringInput();
}
return ip_address;
}
void GetAudioSsrcs(FrameReceiverConfig* audio_config) {
test::InputBuilder input_tx(
"Choose audio sender SSRC.", DEFAULT_AUDIO_FEEDBACK_SSRC, 1, INT_MAX);
audio_config->feedback_ssrc = input_tx.GetIntInput();
test::InputBuilder input_rx(
"Choose audio receiver SSRC.", DEFAULT_AUDIO_INCOMING_SSRC, 1, INT_MAX);
audio_config->incoming_ssrc = input_rx.GetIntInput();
}
void GetVideoSsrcs(FrameReceiverConfig* video_config) {
test::InputBuilder input_tx(
"Choose video sender SSRC.", DEFAULT_VIDEO_FEEDBACK_SSRC, 1, INT_MAX);
video_config->feedback_ssrc = input_tx.GetIntInput();
test::InputBuilder input_rx(
"Choose video receiver SSRC.", DEFAULT_VIDEO_INCOMING_SSRC, 1, INT_MAX);
video_config->incoming_ssrc = input_rx.GetIntInput();
}
#if defined(OS_LINUX)
void GetWindowSize(int* width, int* height) {
// Resolution values based on sender settings
test::InputBuilder input_w(
"Choose window width.", kVideoWindowWidth, 144, 1920);
*width = input_w.GetIntInput();
test::InputBuilder input_h(
"Choose window height.", kVideoWindowHeight, 176, 1080);
*height = input_h.GetIntInput();
}
#endif // OS_LINUX
void GetAudioPayloadtype(FrameReceiverConfig* audio_config) {
test::InputBuilder input("Choose audio receiver payload type.",
DEFAULT_AUDIO_PAYLOAD_TYPE,
96,
127);
audio_config->rtp_payload_type = input.GetIntInput();
}
FrameReceiverConfig GetAudioReceiverConfig() {
FrameReceiverConfig audio_config = GetDefaultAudioReceiverConfig();
GetAudioSsrcs(&audio_config);
GetAudioPayloadtype(&audio_config);
audio_config.rtp_max_delay_ms = 300;
return audio_config;
}
void GetVideoPayloadtype(FrameReceiverConfig* video_config) {
test::InputBuilder input("Choose video receiver payload type.",
DEFAULT_VIDEO_PAYLOAD_TYPE,
96,
127);
video_config->rtp_payload_type = input.GetIntInput();
}
FrameReceiverConfig GetVideoReceiverConfig() {
FrameReceiverConfig video_config = GetDefaultVideoReceiverConfig();
GetVideoSsrcs(&video_config);
GetVideoPayloadtype(&video_config);
video_config.rtp_max_delay_ms = 300;
return video_config;
}
AudioParameters ToAudioParameters(const FrameReceiverConfig& config) {
const int samples_in_10ms = config.frequency / 100;
return AudioParameters(AudioParameters::AUDIO_PCM_LOW_LATENCY,
GuessChannelLayout(config.channels),
config.frequency, 32, samples_in_10ms);
}
// An InProcessReceiver that renders video frames to a LinuxOutputWindow and
// audio frames via Chromium's audio stack.
//
// InProcessReceiver pushes audio and video frames to this subclass, and these
// frames are pushed into a queue. Then, for audio, the Chromium audio stack
// will make polling calls on a separate, unknown thread whereby audio frames
// are pulled out of the audio queue as needed. For video, however, NaivePlayer
// is responsible for scheduling updates to the screen itself. For both, the
// queues are pruned (i.e., received frames are skipped) when the system is not
// able to play back as fast as frames are entering the queue.
//
// This is NOT a good reference implementation for a Cast receiver player since:
// 1. It only skips frames to handle slower-than-expected playout, or halts
// playback to handle frame underruns.
// 2. It makes no attempt to synchronize the timing of playout of the video
// frames with the audio frames.
// 3. It does nothing to smooth or hide discontinuities in playback due to
// timing issues or missing frames.
class NaivePlayer : public InProcessReceiver,
public AudioOutputStream::AudioSourceCallback {
public:
NaivePlayer(const scoped_refptr<CastEnvironment>& cast_environment,
const net::IPEndPoint& local_end_point,
const net::IPEndPoint& remote_end_point,
const FrameReceiverConfig& audio_config,
const FrameReceiverConfig& video_config,
int window_width,
int window_height)
: InProcessReceiver(cast_environment,
local_end_point,
remote_end_point,
audio_config,
video_config),
// Maximum age is the duration of 3 video frames. 3 was chosen
// arbitrarily, but seems to work well.
max_frame_age_(base::TimeDelta::FromSeconds(1) * 3 /
video_config.max_frame_rate),
#if defined(OS_LINUX)
render_(0, 0, window_width, window_height, "Cast_receiver"),
#endif // OS_LINUX
num_video_frames_processed_(0),
num_audio_frames_processed_(0),
currently_playing_audio_frame_start_(-1) {}
virtual ~NaivePlayer() {}
virtual void Start() OVERRIDE {
AudioManager::Get()->GetTaskRunner()->PostTask(
FROM_HERE,
base::Bind(&NaivePlayer::StartAudioOutputOnAudioManagerThread,
base::Unretained(this)));
// Note: No need to wait for audio polling to start since the push-and-pull
// mechanism is synchronized via the |audio_playout_queue_|.
InProcessReceiver::Start();
}
virtual void Stop() OVERRIDE {
// First, stop audio output to the Chromium audio stack.
base::WaitableEvent done(false, false);
DCHECK(!AudioManager::Get()->GetTaskRunner()->BelongsToCurrentThread());
AudioManager::Get()->GetTaskRunner()->PostTask(
FROM_HERE,
base::Bind(&NaivePlayer::StopAudioOutputOnAudioManagerThread,
base::Unretained(this),
&done));
done.Wait();
// Now, stop receiving new frames.
InProcessReceiver::Stop();
// Finally, clear out any frames remaining in the queues.
while (!audio_playout_queue_.empty()) {
const scoped_ptr<AudioBus> to_be_deleted(
audio_playout_queue_.front().second);
audio_playout_queue_.pop_front();
}
video_playout_queue_.clear();
}
private:
void StartAudioOutputOnAudioManagerThread() {
DCHECK(AudioManager::Get()->GetTaskRunner()->BelongsToCurrentThread());
DCHECK(!audio_output_stream_);
audio_output_stream_.reset(AudioManager::Get()->MakeAudioOutputStreamProxy(
ToAudioParameters(audio_config()), ""));
if (audio_output_stream_.get() && audio_output_stream_->Open()) {
audio_output_stream_->Start(this);
} else {
LOG(ERROR) << "Failed to open an audio output stream. "
<< "Audio playback disabled.";
audio_output_stream_.reset();
}
}
void StopAudioOutputOnAudioManagerThread(base::WaitableEvent* done) {
DCHECK(AudioManager::Get()->GetTaskRunner()->BelongsToCurrentThread());
if (audio_output_stream_.get()) {
audio_output_stream_->Stop();
audio_output_stream_->Close();
audio_output_stream_.reset();
}
done->Signal();
}
////////////////////////////////////////////////////////////////////
// InProcessReceiver overrides.
virtual void OnVideoFrame(const scoped_refptr<VideoFrame>& video_frame,
const base::TimeTicks& playout_time,
bool is_continuous) OVERRIDE {
DCHECK(cast_env()->CurrentlyOn(CastEnvironment::MAIN));
LOG_IF(WARNING, !is_continuous)
<< "Video: Discontinuity in received frames.";
video_playout_queue_.push_back(std::make_pair(playout_time, video_frame));
ScheduleVideoPlayout();
uint16 frame_no;
if (media::cast::test::DecodeBarcode(video_frame, &frame_no)) {
video_play_times_.insert(
std::pair<uint16, base::TimeTicks>(frame_no, playout_time));
} else {
VLOG(2) << "Barcode decode failed!";
}
}
virtual void OnAudioFrame(scoped_ptr<AudioBus> audio_frame,
const base::TimeTicks& playout_time,
bool is_continuous) OVERRIDE {
DCHECK(cast_env()->CurrentlyOn(CastEnvironment::MAIN));
LOG_IF(WARNING, !is_continuous)
<< "Audio: Discontinuity in received frames.";
base::AutoLock auto_lock(audio_lock_);
uint16 frame_no;
if (media::cast::DecodeTimestamp(audio_frame->channel(0),
audio_frame->frames(),
&frame_no)) {
// Since there are lots of audio packets with the same frame_no,
// we really want to make sure that we get the playout_time from
// the first one. If is_continous is true, then it's possible
// that we already missed the first one.
if (is_continuous && frame_no == last_audio_frame_no_ + 1) {
audio_play_times_.insert(
std::pair<uint16, base::TimeTicks>(frame_no, playout_time));
}
last_audio_frame_no_ = frame_no;
} else {
VLOG(2) << "Audio decode failed!";
last_audio_frame_no_ = -2;
}
audio_playout_queue_.push_back(
std::make_pair(playout_time, audio_frame.release()));
}
// End of InProcessReceiver overrides.
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
// AudioSourceCallback implementation.
virtual int OnMoreData(AudioBus* dest, AudioBuffersState buffers_state)
OVERRIDE {
// Note: This method is being invoked by a separate thread unknown to us
// (i.e., outside of CastEnvironment).
int samples_remaining = dest->frames();
while (samples_remaining > 0) {
// Get next audio frame ready for playout.
if (!currently_playing_audio_frame_.get()) {
base::AutoLock auto_lock(audio_lock_);
// Prune the queue, skipping entries that are too old.
// TODO(miu): Use |buffers_state| to account for audio buffering delays
// upstream.
const base::TimeTicks earliest_time_to_play =
cast_env()->Clock()->NowTicks() - max_frame_age_;
while (!audio_playout_queue_.empty() &&
audio_playout_queue_.front().first < earliest_time_to_play) {
PopOneAudioFrame(true);
}
if (audio_playout_queue_.empty())
break;
currently_playing_audio_frame_ = PopOneAudioFrame(false).Pass();
currently_playing_audio_frame_start_ = 0;
}
// Copy some or all of the samples in |currently_playing_audio_frame_| to
// |dest|. Once all samples in |currently_playing_audio_frame_| have been
// consumed, release it.
const int num_samples_to_copy =
std::min(samples_remaining,
currently_playing_audio_frame_->frames() -
currently_playing_audio_frame_start_);
currently_playing_audio_frame_->CopyPartialFramesTo(
currently_playing_audio_frame_start_,
num_samples_to_copy,
0,
dest);
samples_remaining -= num_samples_to_copy;
currently_playing_audio_frame_start_ += num_samples_to_copy;
if (currently_playing_audio_frame_start_ ==
currently_playing_audio_frame_->frames()) {
currently_playing_audio_frame_.reset();
}
}
// If |dest| has not been fully filled, then an underrun has occurred; and
// fill the remainder of |dest| with zeros.
if (samples_remaining > 0) {
// Note: Only logging underruns after the first frame has been received.
LOG_IF(WARNING, currently_playing_audio_frame_start_ != -1)
<< "Audio: Playback underrun of " << samples_remaining << " samples!";
dest->ZeroFramesPartial(dest->frames() - samples_remaining,
samples_remaining);
}
return dest->frames();
}
virtual void OnError(AudioOutputStream* stream) OVERRIDE {
LOG(ERROR) << "AudioOutputStream reports an error. "
<< "Playback is unlikely to continue.";
}
// End of AudioSourceCallback implementation.
////////////////////////////////////////////////////////////////////
void ScheduleVideoPlayout() {
DCHECK(cast_env()->CurrentlyOn(CastEnvironment::MAIN));
// Prune the queue, skipping entries that are too old.
const base::TimeTicks now = cast_env()->Clock()->NowTicks();
const base::TimeTicks earliest_time_to_play = now - max_frame_age_;
while (!video_playout_queue_.empty() &&
video_playout_queue_.front().first < earliest_time_to_play) {
PopOneVideoFrame(true);
}
// If the queue is not empty, schedule playout of its first frame.
if (video_playout_queue_.empty()) {
video_playout_timer_.Stop();
} else {
video_playout_timer_.Start(
FROM_HERE,
video_playout_queue_.front().first - now,
base::Bind(&NaivePlayer::PlayNextVideoFrame,
base::Unretained(this)));
}
}
void PlayNextVideoFrame() {
DCHECK(cast_env()->CurrentlyOn(CastEnvironment::MAIN));
if (!video_playout_queue_.empty()) {
const scoped_refptr<VideoFrame> video_frame = PopOneVideoFrame(false);
#ifdef OS_LINUX
render_.RenderFrame(video_frame);
#endif // OS_LINUX
}
ScheduleVideoPlayout();
CheckAVSync();
}
scoped_refptr<VideoFrame> PopOneVideoFrame(bool is_being_skipped) {
DCHECK(cast_env()->CurrentlyOn(CastEnvironment::MAIN));
if (is_being_skipped) {
VLOG(1) << "VideoFrame[" << num_video_frames_processed_
<< " (dt=" << (video_playout_queue_.front().first -
last_popped_video_playout_time_).InMicroseconds()
<< " usec)]: Skipped.";
} else {
VLOG(1) << "VideoFrame[" << num_video_frames_processed_
<< " (dt=" << (video_playout_queue_.front().first -
last_popped_video_playout_time_).InMicroseconds()
<< " usec)]: Playing "
<< (cast_env()->Clock()->NowTicks() -
video_playout_queue_.front().first).InMicroseconds()
<< " usec later than intended.";
}
last_popped_video_playout_time_ = video_playout_queue_.front().first;
const scoped_refptr<VideoFrame> ret = video_playout_queue_.front().second;
video_playout_queue_.pop_front();
++num_video_frames_processed_;
return ret;
}
scoped_ptr<AudioBus> PopOneAudioFrame(bool was_skipped) {
audio_lock_.AssertAcquired();
if (was_skipped) {
VLOG(1) << "AudioFrame[" << num_audio_frames_processed_
<< " (dt=" << (audio_playout_queue_.front().first -
last_popped_audio_playout_time_).InMicroseconds()
<< " usec)]: Skipped.";
} else {
VLOG(1) << "AudioFrame[" << num_audio_frames_processed_
<< " (dt=" << (audio_playout_queue_.front().first -
last_popped_audio_playout_time_).InMicroseconds()
<< " usec)]: Playing "
<< (cast_env()->Clock()->NowTicks() -
audio_playout_queue_.front().first).InMicroseconds()
<< " usec later than intended.";
}
last_popped_audio_playout_time_ = audio_playout_queue_.front().first;
scoped_ptr<AudioBus> ret(audio_playout_queue_.front().second);
audio_playout_queue_.pop_front();
++num_audio_frames_processed_;
return ret.Pass();
}
void CheckAVSync() {
if (video_play_times_.size() > 30 &&
audio_play_times_.size() > 30) {
size_t num_events = 0;
base::TimeDelta delta;
std::map<uint16, base::TimeTicks>::iterator audio_iter, video_iter;
for (video_iter = video_play_times_.begin();
video_iter != video_play_times_.end();
++video_iter) {
audio_iter = audio_play_times_.find(video_iter->first);
if (audio_iter != audio_play_times_.end()) {
num_events++;
// Positive values means audio is running behind video.
delta += audio_iter->second - video_iter->second;
}
}
if (num_events > 30) {
VLOG(0) << "Audio behind by: "
<< (delta / num_events).InMilliseconds()
<< "ms";
video_play_times_.clear();
audio_play_times_.clear();
}
} else if (video_play_times_.size() + audio_play_times_.size() > 500) {
// We are decoding audio or video timestamps, but not both, clear it out.
video_play_times_.clear();
audio_play_times_.clear();
}
}
// Frames in the queue older than this (relative to NowTicks()) will be
// dropped (i.e., playback is falling behind).
const base::TimeDelta max_frame_age_;
// Outputs created, started, and destroyed by this NaivePlayer.
#ifdef OS_LINUX
test::LinuxOutputWindow render_;
#endif // OS_LINUX
scoped_ptr<AudioOutputStream> audio_output_stream_;
// Video playout queue.
typedef std::pair<base::TimeTicks, scoped_refptr<VideoFrame> >
VideoQueueEntry;
std::deque<VideoQueueEntry> video_playout_queue_;
base::TimeTicks last_popped_video_playout_time_;
int64 num_video_frames_processed_;
base::OneShotTimer<NaivePlayer> video_playout_timer_;
// Audio playout queue, synchronized by |audio_lock_|.
base::Lock audio_lock_;
typedef std::pair<base::TimeTicks, AudioBus*> AudioQueueEntry;
std::deque<AudioQueueEntry> audio_playout_queue_;
base::TimeTicks last_popped_audio_playout_time_;
int64 num_audio_frames_processed_;
// These must only be used on the audio thread calling OnMoreData().
scoped_ptr<AudioBus> currently_playing_audio_frame_;
int currently_playing_audio_frame_start_;
std::map<uint16, base::TimeTicks> audio_play_times_;
std::map<uint16, base::TimeTicks> video_play_times_;
int32 last_audio_frame_no_;
};
} // namespace cast
} // namespace media
int main(int argc, char** argv) {
base::AtExitManager at_exit;
CommandLine::Init(argc, argv);
InitLogging(logging::LoggingSettings());
scoped_refptr<media::cast::CastEnvironment> cast_environment(
new media::cast::StandaloneCastEnvironment);
// Start up Chromium audio system.
media::FakeAudioLogFactory fake_audio_log_factory_;
const scoped_ptr<media::AudioManager> audio_manager(
media::AudioManager::Create(&fake_audio_log_factory_));
CHECK(media::AudioManager::Get());
media::cast::FrameReceiverConfig audio_config =
media::cast::GetAudioReceiverConfig();
media::cast::FrameReceiverConfig video_config =
media::cast::GetVideoReceiverConfig();
// Determine local and remote endpoints.
int remote_port, local_port;
media::cast::GetPorts(&remote_port, &local_port);
if (!local_port) {
LOG(ERROR) << "Invalid local port.";
return 1;
}
std::string remote_ip_address = media::cast::GetIpAddress("Enter remote IP.");
std::string local_ip_address = media::cast::GetIpAddress("Enter local IP.");
net::IPAddressNumber remote_ip_number;
net::IPAddressNumber local_ip_number;
if (!net::ParseIPLiteralToNumber(remote_ip_address, &remote_ip_number)) {
LOG(ERROR) << "Invalid remote IP address.";
return 1;
}
if (!net::ParseIPLiteralToNumber(local_ip_address, &local_ip_number)) {
LOG(ERROR) << "Invalid local IP address.";
return 1;
}
net::IPEndPoint remote_end_point(remote_ip_number, remote_port);
net::IPEndPoint local_end_point(local_ip_number, local_port);
// Create and start the player.
int window_width = 0;
int window_height = 0;
#if defined(OS_LINUX)
media::cast::GetWindowSize(&window_width, &window_height);
#endif // OS_LINUX
media::cast::NaivePlayer player(cast_environment,
local_end_point,
remote_end_point,
audio_config,
video_config,
window_width,
window_height);
player.Start();
base::MessageLoop().Run(); // Run forever (i.e., until SIGTERM).
NOTREACHED();
return 0;
}
| [
"jhonnyjosearana@gmail.com"
] | jhonnyjosearana@gmail.com |
77add05879219a88a29082eb5d2aefa1924b3370 | cd6a693f5d02d4b25c49d5804fabdb1b2c150a82 | /include/EnumReflector.h | 5361a5a09ba287a8a90d8d5b3d3d0970b932da90 | [] | no_license | minortones/kissur | f9b04e560964728f5d6a436f448172b1b6b0c4be | 72b69c135975a332f5c7662a80a43f1c69bd34e0 | refs/heads/master | 2020-05-17T15:37:11.332273 | 2016-02-21T04:07:46 | 2016-02-21T04:07:46 | 21,754,863 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,160 | h |
#ifndef ENUM_REFLECTOR_H
#define ENUM_REFLECTOR_H
#include "Reflector.h"
#include "EnumString.h"
template<typename T>
class EnumReflector : public IReflector
{
public:
EnumReflector();
~EnumReflector();
const char* ToString(const void* pValue) const override;
const char* Typename() const override;
ksU32 TypeID() const override;
};
template<typename T>
EnumReflector<T>::EnumReflector()
{}
template<typename T>
EnumReflector<T>::~EnumReflector()
{}
template<typename T>
const char* EnumReflector<T>::ToString( const void* pValue) const
{
return enumToString( *static_cast<const T*>(pValue) );
}
template<typename T>
kissType EnumReflector<T>::TypeID() const { return TypeUID<T>::TypeID(); }
template<typename T>
const char* EnumReflector<T>::Typename() const { return TypeUID<T>::Typename(); }
/////////////////////////////////////////////////////////////////////////////
//
/////////////////////////////////////////////////////////////////////////////
template<typename T>
IReflector* Refl::getReflectInterface(const enable_if_t< std::is_enum<T>::value, T>& pRHS)
{
static EnumReflector<T> enumReflect;
return &enumReflect;
}
#endif | [
"minortones@yahoo.com"
] | minortones@yahoo.com |
fc7f8dfe1e4db7486ec6b0407e5f57ebf33327fb | 792f2ee67210556f224daf88ef0b9785becadc9b | /atcoder/Other/chokudai_S001_k.cpp | ccf43a9acc942654b49aad21823c6dd3beb28bc0 | [] | no_license | firiexp/contest_log | e5b345286e7d69ebf2a599d4a81bdb19243ca18d | 6474a7127d3a2fed768ebb62031d5ff30eeeef86 | refs/heads/master | 2021-07-20T01:16:47.869936 | 2020-04-30T03:27:51 | 2020-04-30T03:27:51 | 150,196,219 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,457 | cpp | #include <iostream>
#include <algorithm>
#include <iomanip>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <numeric>
#include <bitset>
#include <cmath>
static const int MOD = 1000000007;
using ll = long long;
using u32 = unsigned;
using u64 = unsigned long long;
using namespace std;
template<class T> constexpr T INF = ::numeric_limits<T>::max()/32*15+208;
template<u32 M = 1000000007>
struct modint{
u32 val;
modint(): val(0){}
template<typename T>
modint(T t){t %= (T)M; if(t < 0) t += (T)M; val = t;}
modint pow(ll k) const {
modint res(1), x(val);
while(k){
if(k&1) res *= x;
x *= x;
k >>= 1;
}
return res;
}
template<typename T>
modint& operator=(T t){t %= (T)M; if(t < 0) t += (T)M; val = t; return *this;}
modint inv() const {return pow(M-2);}
modint& operator+=(modint a){val += a.val; if(val >= M) val -= M; return *this;}
modint& operator-=(modint a){if(val < a.val) val += M-a.val; else val -= a.val; return *this;}
modint& operator*=(modint a){val = (u64)val*a.val%M; return *this;}
modint& operator/=(modint a){return (*this) *= a.inv();}
modint operator+(modint a) const {return modint(val) +=a;}
modint operator-(modint a) const {return modint(val) -=a;}
modint operator*(modint a) const {return modint(val) *=a;}
modint operator/(modint a) const {return modint(val) /=a;}
modint operator-(){return modint(M-val);}
bool operator==(const modint a) const {return val == a.val;}
bool operator!=(const modint a) const {return val != a.val;}
bool operator<(const modint a) const {return val < a.val;}
};
class Factorial {
using mint = modint<MOD>;
vector<mint> facts, factinv;
public:
explicit Factorial(int n) : facts(static_cast<u32>(n+1)), factinv(static_cast<u32>(n+1)) {
facts[0] = 1;
for (int i = 1; i < n+1; ++i) facts[i] = facts[i-1]*mint(i);
factinv[n] = facts[n].inv();
for (int i = n-1; i >= 0; --i) factinv[i] = factinv[i+1] * mint(i+1);
}
mint fact(int k) const {
if(k >= 0) return facts[k]; else return factinv[-k];
}
mint operator[](const int &k) const {
if(k >= 0) return facts[k]; else return factinv[-k];
}
mint C(int p, int q) const {
if(q < 0 || p < q) return 0;
return facts[p] * factinv[q] * factinv[p-q];
}
mint P(int p, int q) const {
if(q < 0 || p < q) return 0;
return facts[p] * factinv[p-q];
}
mint H(int p, int q) const {
if(p < 0 || q < 0) return 0;
return q == 0 ? 1 : C(p+q-1, q);
}
};
using mint = modint<MOD>;
template<class T>
class BIT {
vector<T> bit;
public:
BIT(int n): bit(vector<T>(n+1, 0)){}
T sum(int k){
T ret = 0;
for (++k; k > 0; k -= (k & -k)) ret += bit[k];
return ret;
}
void add(int k, T x){
for (++k; k < bit.size(); k += (k & -k)) bit[k] += x;
}
};
int main() {
int n;
cin >> n;
vector<int> v(n);
for (auto &&i : v) scanf("%d", &i);
mint ans = 1;
Factorial f(n);
BIT<int> S(n+1);
for (int i = 0; i < n; ++i) {
ans += f[n-i-1]*mint(v[i]-1-S.sum(v[i]-1));
S.add(v[i], 1);
}
cout << ans.val << "\n";
return 0;
} | [
"firiexp@PC.localdomain"
] | firiexp@PC.localdomain |
e636d8b443b7ab336f2de789fc6756534ba050ba | 30f1c38a36d1c2730cd0feb50d6e8399506df53c | /src/scenes/heatherMolnarScene/heatherMolnarScene.h | 35f0eac9f6ea4e482426ac1998e55f1e2a913f18 | [
"MIT"
] | permissive | ffeng271/recoded | 1832032b847b5a261fd0d4ff4af2c57972862174 | 934e1184c7502d192435c406e56b8a2106e9b6b4 | refs/heads/master | 2020-03-29T22:38:14.124047 | 2017-11-15T17:22:45 | 2017-11-15T17:22:45 | 150,431,859 | 1 | 0 | MIT | 2018-09-26T13:34:12 | 2018-09-26T13:34:12 | null | UTF-8 | C++ | false | false | 600 | h | #pragma once
#include "ofMain.h"
#include "baseScene.h"
class heatherMolnarScene : public baseScene {
public:
void setup();
void update();
void draw();
ofPoint calculateStartCoordinates(int columnPosition, int rowPosition);
int calculateAngleRangeForColumn(int distanceFromEdge);
void drawLineWithAngleAndThickness(ofPoint startingPoint, int angle, int distance);
int columns, rows, offset, cellSize;
float midPoint, possibleAngleVariation;
ofParameter<int> thickness;
ofParameter<int> minAngle;
ofParameter<int> maxMidpointAngle;
};
| [
"moore.hj@gmail.com"
] | moore.hj@gmail.com |
f235d573d827721584c030d391e1e01e47023c9c | 5095bbe94f3af8dc3b14a331519cfee887f4c07e | /howwet/Shared/Gobjs/GSTRING.CPP | a73da018425274269db6226a0de400b6b74534f7 | [] | no_license | sativa/apsim_development | efc2b584459b43c89e841abf93830db8d523b07a | a90ffef3b4ed8a7d0cce1c169c65364be6e93797 | refs/heads/master | 2020-12-24T06:53:59.364336 | 2008-09-17T05:31:07 | 2008-09-17T05:31:07 | 64,154,433 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,656 | cpp | #include <consts.h>
#include <gobjs\gstring.h>
#include <iostream.h>
#include <strstrea.h>
#include <stdio.h>
IMPLEMENT_CASTABLE(GString);
IMPLEMENT_STREAMABLE(GString);
// *******************************************************************
void GString::Streamer::Write(opstream& os) const {
// *******************************************************************
// Short description:
// Writes an instance of GString to the passed ipstream.
// Notes:
// Changes:
// DPH 23/6/94
// Calls:
// Internal variables
// -------------------- Executable code section ----------------------
string& St = *GetObject();
os << St;
}
// *******************************************************************
void *GString::Streamer::Read(ipstream& is, uint32 /*version*/) const {
// *******************************************************************
// Short description:
// Reads an instance of GString from the passed ipstream.
// Notes:
// Changes:
// DPH 23/6/94
// Calls:
// Internal variables
// -------------------- Executable code section ----------------------
string& St = *GetObject();
is >> St;
return GetObject();
}
// *******************************************************************
void GString::Replace(const GString& String1, const GString& String2) {
// *******************************************************************
// Short description:
// Replace string 1 with string 2 and return result.
// Notes:
// Changes:
// DPH 17/11/94
// Calls:
// Internal variables
size_t Pos; // Position in string
// -------------------- Executable code section ----------------------
// Determine if there is something to replace.
Pos = find(String1);
while (Pos != NPOS)
{
replace(Pos, String1.length(), String2);
Pos = find(String1, Pos + String2.length());
}
}
// *******************************************************************
void GString::Replace(const char *String1, const char *String2) {
// *******************************************************************
// Short description:
// Replace string 1 with string 2 and return result.
// Notes:
// Changes:
// DPH 17/11/94
// Calls:
// Internal variables
GString Str1; // String1
GString Str2; // String2
// -------------------- Executable code section ----------------------
Str1.assign(String1);
Str2.assign(String2);
Replace(Str1, Str2);
};
// *******************************************************************
void GString::Assign (const GString& Str, size_t Pos, size_t n) {
// *******************************************************************
// Short description:
// Assign a portion of string Str
// Notes:
// Changes:
// DPH 18/11/94
// Calls:
// Internal variables
// none
// -------------------- Executable code section ----------------------
assign(Str, Pos);
if (n < length())
remove(n);
}
// *******************************************************************
char GString::Read_token(istream& In_stream,
const GString& Init_skip_chars,
const GString& Delimiter_chars) {
// *******************************************************************
// Short description:
// Read in a token. Skip all leading skip characters and stop when a delimiter
// character is found. Returns the character causing a parse stop.
// Notes:
// Changes:
// DPH 21/11/94
// Calls:
// Internal variables
char Character[2]; // Character read from stream.
bool Still_skipping_init = true; // Are we still skipping initial chars?
// -------------------- Executable code section ----------------------
// Clear the strings contents
assign("");
// Skip all initial characters.
while (In_stream && Still_skipping_init)
{
In_stream.get((char*) &Character, 2, 0);
if (strlen(Character) == 0)
Still_skipping_init = false;
else if (Init_skip_chars.contains(Character))
Still_skipping_init = true;
else
Still_skipping_init = false;
}
// Append characters to string until a delimiter is found.
while (strlen(Character) != 0 && !Delimiter_chars.contains(Character) && In_stream)
{
append(Character);
In_stream.get((char*) &Character, 2, 0);
}
// If reached end of file then return 0;
if (!In_stream)
return 0;
return Character[0];
}
// *******************************************************************
void *GString::Get_pointer(void) {
// *******************************************************************
// Short description:
// Treat string as a pointer.
// Notes:
// Changes:
// DPH 21/11/94
// Calls:
// Internal variables
void *Pointer_to_return; // pointer to return to caller.
// -------------------- Executable code section ----------------------
sscanf(c_str(), "%p", &Pointer_to_return);
return Pointer_to_return;
}
// *******************************************************************
void GString::Set_pointer(void *Pointer) {
// *******************************************************************
// Short description:
// Set string up as a pointer
// Notes:
// Changes:
// DPH 21/11/94
// Calls:
// Internal variables
char Temp_string[50]; // Temporary string.
// -------------------- Executable code section ----------------------
sprintf(Temp_string, "%p", Pointer);
assign(Temp_string);
}
// *******************************************************************
float GString::Get_real(void) {
// *******************************************************************
// Short description:
// Treat string as a real value
// Notes:
// Changes:
// DPH 21/11/94
// Calls:
// Internal variables
float Real_value = 0.0; // Real value to return
char *End_char;
// -------------------- Executable code section ----------------------
if (length() > 0)
{
Real_value = strtod(c_str(), &End_char);
if (*End_char != NULL && *End_char != ' ')
Real_value = 0.0;
}
return Real_value;
}
// *******************************************************************
void GString::Set_real(float Real_value) {
// *******************************************************************
// Short description:
// Set string up as a pointer
// Notes:
// Changes:
// DPH 21/11/94
// Calls:
// Internal variables
char Temp_string[50]; // Temporary string.
// -------------------- Executable code section ----------------------
ostrstream Out_stream(Temp_string, sizeof(Temp_string));
Out_stream << Real_value << ends;
assign(Temp_string);
}
// *******************************************************************
int GString::Get_integer(void) {
// *******************************************************************
// Short description:
// Treat string as an integer value
// Notes:
// Changes:
// DPH 21/11/94
// Calls:
// Internal variables
int Integer_value = 0; // integer value to return
// -------------------- Executable code section ----------------------
if (length() > 0)
Integer_value = atoi(c_str());
return Integer_value;
}
// *******************************************************************
void GString::Set_integer(int Integer_value) {
// *******************************************************************
// Short description:
// Set string up as a pointer
// Notes:
// Changes:
// DPH 21/11/94
// Calls:
// Internal variables
char Temp_string[50]; // Temporary string.
// -------------------- Executable code section ----------------------
ostrstream Out_stream(Temp_string, sizeof(Temp_string));
Out_stream << Integer_value << ends;
assign(Temp_string);
}
// *******************************************************************
char GString::Get_last_char(void) {
// *******************************************************************
// Short description:
// Return the last non blank character to caller.
// Notes:
// Changes:
// DPH 23/11/94
// Calls:
// Internal variables
size_t Pos; // Position of last non blank character
char Return_char; // Character to return to caller.
// -------------------- Executable code section ----------------------
Pos = find_last_not_of(" ");
if (Pos > length())
Return_char = 0;
else
Return_char = get_at(Pos);
return Return_char;
}
// *******************************************************************
void GString::Strip(StripType s, char c) {
// *******************************************************************
// Short description:
// Strip away unwanted chars from string.
// Notes:
// Changes:
// DPH 14/12/94
// Calls:
// Internal variables
size_t Pos; // Position in string
// -------------------- Executable code section ----------------------
if (length() > 0)
{
if (s == string::Both || s == string::Leading)
{
Pos = find_first_not_of(c);
if (Pos == NPOS)
Pos = length();
remove(0, Pos);
}
}
if (length() > 0)
{
if (s == string::Both || s == string::Trailing)
{
Pos = find_last_not_of(c);
if (Pos < length() - 1)
remove(Pos + 1);
}
}
}
// *******************************************************************
ipstream& operator >> (ipstream& is, String_array& Obj) {
// *******************************************************************
// Short description:
// Read a string array from an ipstream.
// Notes:
// Changes:
// DPH 21/9/95
// Calls:
// Internal variables
int Num_elements; // Number of elements to add to list.
GString Str; // String read from stream.
// -------------------- Executable code section ----------------------
Obj.Flush();
is >> Num_elements;
for (int Element = 0;
Element < Num_elements;
Element++)
{
is >> Str;
Obj.Add(Str);
}
return is;
}
// *******************************************************************
opstream& operator << (opstream& os, const String_array& Obj) {
// *******************************************************************
// Short description:
// Write a string array to an opstream.
// Notes:
// Changes:
// DPH 21/9/95
// Calls:
// Internal variables
// -------------------- Executable code section ----------------------
os << Obj.GetItemsInContainer();
for (int Element = 0;
Element < Obj.GetItemsInContainer();
Element++)
{
os << Obj[Element];
}
return os;
}
// *******************************************************************
bool GString::Is_numerical(void) {
// *******************************************************************
// Short description:
// returns TRUE if string is numerical
// Notes:
// Changes:
// DPH 14/12/94
// Calls:
// Internal variables
char *End_char;
// -------------------- Executable code section ----------------------
strtod(c_str(), &End_char);
return !(*End_char != NULL && *End_char != ' ');
}
| [
"hol353@8bb03f63-af10-0410-889a-a89e84ef1bc8"
] | hol353@8bb03f63-af10-0410-889a-a89e84ef1bc8 |
e11226157d525ebf80b614e85c5a2a00ebb174b5 | 761c1ae19594e49d7047d059b25640c3e558f3d5 | /HighFrequency/288. Unique Word Abbreviation.cpp | 9ab0e07f35004737ed8ce746c83d0172905831c1 | [] | no_license | SunNEET/LeetCode | a09772c4f3c23788afebceb4f6c2150d3c127695 | 96b08c45f5241579aaf27625510570d718965ec2 | refs/heads/master | 2020-03-12T15:43:07.019708 | 2019-06-25T03:53:56 | 2019-06-25T03:53:56 | 130,697,627 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,125 | cpp | class ValidWordAbbr {
// 題目解讀有坑, 簡單的說, 每個字典裡的字都一律縮寫成只保留頭尾, 中間變數字
// 規則解讀
// (1)isUnique("apple"): 假如apple沒在字典裡出現過, a3e也沒出現過 -> unique
// (2)isUnique("deer"): 假如deer在字典出現過n次, 而且只有他會縮寫成d2r -> unique
private:
unordered_map<string,int> dict_cnt;
unordered_map<string,int> abbr_cnt;
public:
ValidWordAbbr(vector<string> dictionary) {
for(int i=0;i<(int)dictionary.size();i++) {
dict_cnt[dictionary[i]]++;
abbr_cnt[makeAbbr(dictionary[i])]++;
}
}
string makeAbbr(string s) {
string res="";
res += s[0] + to_string((int)s.length()-2) + s[(int)s.length()-1];
return res;
}
bool isUnique(string word) {
if(dict_cnt[word]!=abbr_cnt[makeAbbr(word)])
return false;
return true;
}
};
/**
* Your ValidWordAbbr object will be instantiated and called as such:
* ValidWordAbbr obj = new ValidWordAbbr(dictionary);
* bool param_1 = obj.isUnique(word);
*/ | [
"sunnyinvadeher@gmail.com"
] | sunnyinvadeher@gmail.com |
ba6d7c419415601f98a0d725e84be9c08b68b2fc | cf7cfaf8483150bdf38b393bfb43d8c3f33481d7 | /D3d8to9/d3d8to9_device.cpp | 7ddf0e35d718420c0d8d1659d73391b293355b60 | [
"Zlib"
] | permissive | StanleyRS/dxwrapper | 4d084101c6feb985d2815827820154693c7147c4 | ba53b5987e04d8d9bf21f5879ee07d3ffbfa1495 | refs/heads/master | 2020-03-21T04:48:59.287489 | 2018-06-20T06:49:26 | 2018-06-20T06:49:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 72,268 | cpp | /**
* Copyright (C) 2015 Patrick Mours. All rights reserved.
* License: https://github.com/crosire/d3d8to9#license
*/
#include "d3dx9.hpp"
#include "d3d8to9.hpp"
#include <regex>
#include <assert.h>
struct VertexShaderInfo
{
IDirect3DVertexShader9 *Shader;
IDirect3DVertexDeclaration9 *Declaration;
};
// IDirect3DDevice8
Direct3DDevice8::Direct3DDevice8(Direct3D8 *d3d, IDirect3DDevice9 *ProxyInterface, BOOL EnableZBufferDiscarding) :
D3D(d3d), ProxyInterface(ProxyInterface), ZBufferDiscarding(EnableZBufferDiscarding)
{
ProxyAddressLookupTable = new AddressLookupTable(this);
PaletteFlag = SupportsPalettes();
}
Direct3DDevice8::~Direct3DDevice8()
{
delete ProxyAddressLookupTable;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::QueryInterface(REFIID riid, void **ppvObj)
{
if (ppvObj == nullptr)
{
return E_POINTER;
}
if (riid == __uuidof(this) ||
riid == __uuidof(IUnknown))
{
AddRef();
*ppvObj = this;
return S_OK;
}
return ProxyInterface->QueryInterface(riid, ppvObj);
}
ULONG STDMETHODCALLTYPE Direct3DDevice8::AddRef()
{
return ProxyInterface->AddRef();
}
ULONG STDMETHODCALLTYPE Direct3DDevice8::Release()
{
ULONG LastRefCount = ProxyInterface->Release();
if (LastRefCount == 0)
{
delete this;
}
return LastRefCount;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::TestCooperativeLevel()
{
return ProxyInterface->TestCooperativeLevel();
}
UINT STDMETHODCALLTYPE Direct3DDevice8::GetAvailableTextureMem()
{
return ProxyInterface->GetAvailableTextureMem();
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::ResourceManagerDiscardBytes(DWORD Bytes)
{
UNREFERENCED_PARAMETER(Bytes);
return ProxyInterface->EvictManagedResources();
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::GetDirect3D(Direct3D8 **ppD3D8)
{
if (ppD3D8 == nullptr)
{
return D3DERR_INVALIDCALL;
}
D3D->AddRef();
*ppD3D8 = D3D;
return D3D_OK;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::GetDeviceCaps(D3DCAPS8 *pCaps)
{
if (pCaps == nullptr)
{
return D3DERR_INVALIDCALL;
}
D3DCAPS9 DeviceCaps;
const HRESULT hr = ProxyInterface->GetDeviceCaps(&DeviceCaps);
if (FAILED(hr))
{
return hr;
}
ConvertCaps(DeviceCaps, *pCaps);
return D3D_OK;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::GetDisplayMode(D3DDISPLAYMODE *pMode)
{
return ProxyInterface->GetDisplayMode(0, pMode);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::GetCreationParameters(D3DDEVICE_CREATION_PARAMETERS *pParameters)
{
return ProxyInterface->GetCreationParameters(pParameters);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::SetCursorProperties(UINT XHotSpot, UINT YHotSpot, Direct3DSurface8 *pCursorBitmap)
{
if (pCursorBitmap == nullptr)
{
return D3DERR_INVALIDCALL;
}
return ProxyInterface->SetCursorProperties(XHotSpot, YHotSpot, pCursorBitmap->GetProxyInterface());
}
void STDMETHODCALLTYPE Direct3DDevice8::SetCursorPosition(UINT XScreenSpace, UINT YScreenSpace, DWORD Flags)
{
ProxyInterface->SetCursorPosition(XScreenSpace, YScreenSpace, Flags);
}
BOOL STDMETHODCALLTYPE Direct3DDevice8::ShowCursor(BOOL bShow)
{
return ProxyInterface->ShowCursor(bShow);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::CreateAdditionalSwapChain(D3DPRESENT_PARAMETERS8 *pPresentationParameters, Direct3DSwapChain8 **ppSwapChain)
{
#ifndef D3D8TO9NOLOG
LOG << "Redirecting '" << "IDirect3DDevice8::CreateAdditionalSwapChain" << "(" << this << ", " << pPresentationParameters << ", " << ppSwapChain << ")' ..." << std::endl;
#endif
if (pPresentationParameters == nullptr || ppSwapChain == nullptr)
{
return D3DERR_INVALIDCALL;
}
*ppSwapChain = nullptr;
D3DPRESENT_PARAMETERS PresentParams;
ConvertPresentParameters(*pPresentationParameters, PresentParams);
// Get multisample quality level
if (PresentParams.MultiSampleType != D3DMULTISAMPLE_NONE)
{
DWORD QualityLevels = 0;
D3DDEVICE_CREATION_PARAMETERS CreationParams;
ProxyInterface->GetCreationParameters(&CreationParams);
if (D3D->GetProxyInterface()->CheckDeviceMultiSampleType(CreationParams.AdapterOrdinal,
CreationParams.DeviceType, PresentParams.BackBufferFormat, PresentParams.Windowed,
PresentParams.MultiSampleType, &QualityLevels) == S_OK &&
D3D->GetProxyInterface()->CheckDeviceMultiSampleType(CreationParams.AdapterOrdinal,
CreationParams.DeviceType, PresentParams.AutoDepthStencilFormat, PresentParams.Windowed,
PresentParams.MultiSampleType, &QualityLevels) == S_OK)
{
PresentParams.MultiSampleQuality = (QualityLevels != 0) ? QualityLevels - 1 : 0;
}
}
IDirect3DSwapChain9 *SwapChainInterface = nullptr;
const HRESULT hr = ProxyInterface->CreateAdditionalSwapChain(&PresentParams, &SwapChainInterface);
if (FAILED(hr))
{
return hr;
}
*ppSwapChain = new Direct3DSwapChain8(this, SwapChainInterface);
return D3D_OK;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::Reset(D3DPRESENT_PARAMETERS8 *pPresentationParameters)
{
#ifndef D3D8TO9NOLOG
LOG << "Redirecting '" << "IDirect3DDevice8::Reset" << "(" << this << ", " << pPresentationParameters << ")' ..." << std::endl;
#endif
if (pPresentationParameters == nullptr)
{
return D3DERR_INVALIDCALL;
}
D3DPRESENT_PARAMETERS PresentParams;
ConvertPresentParameters(*pPresentationParameters, PresentParams);
// Get multisample quality level
if (PresentParams.MultiSampleType != D3DMULTISAMPLE_NONE)
{
DWORD QualityLevels = 0;
D3DDEVICE_CREATION_PARAMETERS CreationParams;
ProxyInterface->GetCreationParameters(&CreationParams);
if (D3D->GetProxyInterface()->CheckDeviceMultiSampleType(CreationParams.AdapterOrdinal,
CreationParams.DeviceType, PresentParams.BackBufferFormat, PresentParams.Windowed,
PresentParams.MultiSampleType, &QualityLevels) == S_OK &&
D3D->GetProxyInterface()->CheckDeviceMultiSampleType(CreationParams.AdapterOrdinal,
CreationParams.DeviceType, PresentParams.AutoDepthStencilFormat, PresentParams.Windowed,
PresentParams.MultiSampleType, &QualityLevels) == S_OK)
{
PresentParams.MultiSampleQuality = (QualityLevels != 0) ? QualityLevels - 1 : 0;
}
}
return ProxyInterface->Reset(&PresentParams);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::Present(const RECT *pSourceRect, const RECT *pDestRect, HWND hDestWindowOverride, const RGNDATA *pDirtyRegion)
{
UNREFERENCED_PARAMETER(pDirtyRegion);
return ProxyInterface->Present(pSourceRect, pDestRect, hDestWindowOverride, nullptr);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::GetBackBuffer(UINT iBackBuffer, D3DBACKBUFFER_TYPE Type, Direct3DSurface8 **ppBackBuffer)
{
if (ppBackBuffer == nullptr)
{
return D3DERR_INVALIDCALL;
}
*ppBackBuffer = nullptr;
IDirect3DSurface9 *SurfaceInterface = nullptr;
const HRESULT hr = ProxyInterface->GetBackBuffer(0, iBackBuffer, Type, &SurfaceInterface);
if (FAILED(hr))
{
return hr;
}
*ppBackBuffer = ProxyAddressLookupTable->FindAddress<Direct3DSurface8>(SurfaceInterface);
return D3D_OK;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::GetRasterStatus(D3DRASTER_STATUS *pRasterStatus)
{
return ProxyInterface->GetRasterStatus(0, pRasterStatus);
}
void STDMETHODCALLTYPE Direct3DDevice8::SetGammaRamp(DWORD Flags, const D3DGAMMARAMP *pRamp)
{
ProxyInterface->SetGammaRamp(0, Flags, pRamp);
}
void STDMETHODCALLTYPE Direct3DDevice8::GetGammaRamp(D3DGAMMARAMP *pRamp)
{
ProxyInterface->GetGammaRamp(0, pRamp);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::CreateTexture(UINT Width, UINT Height, UINT Levels, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, Direct3DTexture8 **ppTexture)
{
if (ppTexture == nullptr)
{
return D3DERR_INVALIDCALL;
}
*ppTexture = nullptr;
if (Pool == D3DPOOL_DEFAULT)
{
D3DDEVICE_CREATION_PARAMETERS CreationParams;
ProxyInterface->GetCreationParameters(&CreationParams);
if ((Usage & D3DUSAGE_DYNAMIC) == 0 &&
SUCCEEDED(D3D->GetProxyInterface()->CheckDeviceFormat(CreationParams.AdapterOrdinal, CreationParams.DeviceType, D3DFMT_X8R8G8B8, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE, Format)))
{
Usage |= D3DUSAGE_RENDERTARGET;
}
else if (Usage != D3DUSAGE_DEPTHSTENCIL)
{
Usage |= D3DUSAGE_DYNAMIC;
}
}
IDirect3DTexture9 *TextureInterface = nullptr;
const HRESULT hr = ProxyInterface->CreateTexture(Width, Height, Levels, Usage, Format, Pool, &TextureInterface, nullptr);
if (FAILED(hr))
{
return hr;
}
*ppTexture = new Direct3DTexture8(this, TextureInterface);
return D3D_OK;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::CreateVolumeTexture(UINT Width, UINT Height, UINT Depth, UINT Levels, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, Direct3DVolumeTexture8 **ppVolumeTexture)
{
if (ppVolumeTexture == nullptr)
{
return D3DERR_INVALIDCALL;
}
*ppVolumeTexture = nullptr;
IDirect3DVolumeTexture9 *TextureInterface = nullptr;
const HRESULT hr = ProxyInterface->CreateVolumeTexture(Width, Height, Depth, Levels, Usage, Format, Pool, &TextureInterface, nullptr);
if (FAILED(hr))
{
return hr;
}
*ppVolumeTexture = new Direct3DVolumeTexture8(this, TextureInterface);
return D3D_OK;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::CreateCubeTexture(UINT EdgeLength, UINT Levels, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, Direct3DCubeTexture8 **ppCubeTexture)
{
if (ppCubeTexture == nullptr)
{
return D3DERR_INVALIDCALL;
}
*ppCubeTexture = nullptr;
IDirect3DCubeTexture9 *TextureInterface = nullptr;
const HRESULT hr = ProxyInterface->CreateCubeTexture(EdgeLength, Levels, Usage, Format, Pool, &TextureInterface, nullptr);
if (FAILED(hr))
{
return hr;
}
*ppCubeTexture = new Direct3DCubeTexture8(this, TextureInterface);
return D3D_OK;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::CreateVertexBuffer(UINT Length, DWORD Usage, DWORD FVF, D3DPOOL Pool, Direct3DVertexBuffer8 **ppVertexBuffer)
{
if (ppVertexBuffer == nullptr)
{
return D3DERR_INVALIDCALL;
}
*ppVertexBuffer = nullptr;
IDirect3DVertexBuffer9 *BufferInterface = nullptr;
const HRESULT hr = ProxyInterface->CreateVertexBuffer(Length, Usage, FVF, Pool, &BufferInterface, nullptr);
if (FAILED(hr))
{
return hr;
}
*ppVertexBuffer = new Direct3DVertexBuffer8(this, BufferInterface);
return D3D_OK;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::CreateIndexBuffer(UINT Length, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, Direct3DIndexBuffer8 **ppIndexBuffer)
{
if (ppIndexBuffer == nullptr)
{
return D3DERR_INVALIDCALL;
}
*ppIndexBuffer = nullptr;
IDirect3DIndexBuffer9 *BufferInterface = nullptr;
const HRESULT hr = ProxyInterface->CreateIndexBuffer(Length, Usage, Format, Pool, &BufferInterface, nullptr);
if (FAILED(hr))
{
return hr;
}
*ppIndexBuffer = new Direct3DIndexBuffer8(this, BufferInterface);
return D3D_OK;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::CreateRenderTarget(UINT Width, UINT Height, D3DFORMAT Format, D3DMULTISAMPLE_TYPE MultiSample, BOOL Lockable, Direct3DSurface8 **ppSurface)
{
if (ppSurface == nullptr)
{
return D3DERR_INVALIDCALL;
}
*ppSurface = nullptr;
DWORD QualityLevels = 0;
// Get multisample quality level
if (MultiSample != D3DMULTISAMPLE_NONE)
{
D3DDEVICE_CREATION_PARAMETERS CreationParams;
ProxyInterface->GetCreationParameters(&CreationParams);
D3D->GetProxyInterface()->CheckDeviceMultiSampleType(CreationParams.AdapterOrdinal, CreationParams.DeviceType, Format, FALSE, MultiSample, &QualityLevels);
QualityLevels = (QualityLevels != 0) ? QualityLevels - 1 : 0;
}
IDirect3DSurface9 *SurfaceInterface = nullptr;
HRESULT hr = ProxyInterface->CreateRenderTarget(Width, Height, Format, MultiSample, QualityLevels, Lockable, &SurfaceInterface, nullptr);
if (FAILED(hr))
{
return hr;
}
pCurrentRenderTarget = SurfaceInterface;
*ppSurface = new Direct3DSurface8(this, SurfaceInterface);
return D3D_OK;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::CreateDepthStencilSurface(UINT Width, UINT Height, D3DFORMAT Format, D3DMULTISAMPLE_TYPE MultiSample, Direct3DSurface8 **ppSurface)
{
if (ppSurface == nullptr)
{
return D3DERR_INVALIDCALL;
}
*ppSurface = nullptr;
DWORD QualityLevels = 0;
// Get multisample quality level
if (MultiSample != D3DMULTISAMPLE_NONE)
{
D3DDEVICE_CREATION_PARAMETERS CreationParams;
ProxyInterface->GetCreationParameters(&CreationParams);
D3D->GetProxyInterface()->CheckDeviceMultiSampleType(CreationParams.AdapterOrdinal, CreationParams.DeviceType, Format, FALSE, MultiSample, &QualityLevels);
QualityLevels = (QualityLevels != 0) ? QualityLevels - 1 : 0;
}
IDirect3DSurface9 *SurfaceInterface = nullptr;
HRESULT hr = ProxyInterface->CreateDepthStencilSurface(Width, Height, Format, MultiSample, QualityLevels, ZBufferDiscarding, &SurfaceInterface, nullptr);
if (FAILED(hr))
{
return hr;
}
*ppSurface = new Direct3DSurface8(this, SurfaceInterface);
return D3D_OK;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::CreateImageSurface(UINT Width, UINT Height, D3DFORMAT Format, Direct3DSurface8 **ppSurface)
{
#ifndef D3D8TO9NOLOG
LOG << "Redirecting '" << "IDirect3DDevice8::CreateImageSurface" << "(" << this << ", " << Width << ", " << Height << ", " << Format << ", " << ppSurface << ")' ..." << std::endl;
#endif
if (ppSurface == nullptr)
{
return D3DERR_INVALIDCALL;
}
*ppSurface = nullptr;
if (Format == D3DFMT_R8G8B8)
{
#ifndef D3D8TO9NOLOG
LOG << "> Replacing format 'D3DFMT_R8G8B8' with 'D3DFMT_X8R8G8B8' ..." << std::endl;
#endif
Format = D3DFMT_X8R8G8B8;
}
IDirect3DSurface9 *SurfaceInterface = nullptr;
const HRESULT hr = ProxyInterface->CreateOffscreenPlainSurface(Width, Height, Format, D3DPOOL_SYSTEMMEM, &SurfaceInterface, nullptr);
if (FAILED(hr))
{
#ifndef D3D8TO9NOLOG
LOG << "> 'IDirect3DDevice9::CreateOffscreenPlainSurface' failed with error code " << std::hex << hr << std::dec << "!" << std::endl;
#endif
return hr;
}
*ppSurface = new Direct3DSurface8(this, SurfaceInterface);
return D3D_OK;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::CopyRects(Direct3DSurface8 *pSourceSurface, const RECT *pSourceRectsArray, UINT cRects, Direct3DSurface8 *pDestinationSurface, const POINT *pDestPointsArray)
{
if (pSourceSurface == nullptr || pDestinationSurface == nullptr || pSourceSurface == pDestinationSurface)
{
return D3DERR_INVALIDCALL;
}
D3DSURFACE_DESC SourceDesc, DestinationDesc;
pSourceSurface->GetProxyInterface()->GetDesc(&SourceDesc);
pDestinationSurface->GetProxyInterface()->GetDesc(&DestinationDesc);
if (SourceDesc.Format != DestinationDesc.Format)
{
return D3DERR_INVALIDCALL;
}
HRESULT hr = D3DERR_INVALIDCALL;
if (cRects == 0)
{
cRects = 1;
}
for (UINT i = 0; i < cRects; i++)
{
RECT SourceRect, DestinationRect;
if (pSourceRectsArray != nullptr)
{
SourceRect = pSourceRectsArray[i];
}
else
{
SourceRect.left = 0;
SourceRect.right = SourceDesc.Width;
SourceRect.top = 0;
SourceRect.bottom = SourceDesc.Height;
}
if (pDestPointsArray != nullptr)
{
DestinationRect.left = pDestPointsArray[i].x;
DestinationRect.right = DestinationRect.left + (SourceRect.right - SourceRect.left);
DestinationRect.top = pDestPointsArray[i].y;
DestinationRect.bottom = DestinationRect.top + (SourceRect.bottom - SourceRect.top);
}
else
{
DestinationRect = SourceRect;
}
if (SourceDesc.Pool == D3DPOOL_MANAGED || DestinationDesc.Pool != D3DPOOL_DEFAULT)
{
if (D3DXLoadSurfaceFromSurface != nullptr)
{
hr = D3DXLoadSurfaceFromSurface(pDestinationSurface->GetProxyInterface(), nullptr, &DestinationRect, pSourceSurface->GetProxyInterface(), nullptr, &SourceRect, D3DX_FILTER_NONE, 0);
}
else
{
hr = D3DERR_INVALIDCALL;
}
}
else if (SourceDesc.Pool == D3DPOOL_DEFAULT)
{
hr = ProxyInterface->StretchRect(pSourceSurface->GetProxyInterface(), &SourceRect, pDestinationSurface->GetProxyInterface(), &DestinationRect, D3DTEXF_NONE);
}
else if (SourceDesc.Pool == D3DPOOL_SYSTEMMEM)
{
const POINT pt = { DestinationRect.left, DestinationRect.top };
hr = ProxyInterface->UpdateSurface(pSourceSurface->GetProxyInterface(), &SourceRect, pDestinationSurface->GetProxyInterface(), &pt);
}
if (FAILED(hr))
{
#ifndef D3D8TO9NOLOG
LOG << "Failed to translate 'IDirect3DDevice8::CopyRects' call from '[" << SourceDesc.Width << "x" << SourceDesc.Height << ", " << SourceDesc.Format << ", " << SourceDesc.MultiSampleType << ", " << SourceDesc.Usage << ", " << SourceDesc.Pool << "]' to '[" << DestinationDesc.Width << "x" << DestinationDesc.Height << ", " << DestinationDesc.Format << ", " << DestinationDesc.MultiSampleType << ", " << DestinationDesc.Usage << ", " << DestinationDesc.Pool << "]'!" << std::endl;
#endif
break;
}
}
return hr;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::UpdateTexture(Direct3DBaseTexture8 *pSourceTexture, Direct3DBaseTexture8 *pDestinationTexture)
{
if (pSourceTexture == nullptr || pDestinationTexture == nullptr || pSourceTexture->GetType() != pDestinationTexture->GetType())
{
return D3DERR_INVALIDCALL;
}
IDirect3DBaseTexture9 *SourceBaseTextureInterface, *DestinationBaseTextureInterface;
switch (pSourceTexture->GetType())
{
case D3DRTYPE_TEXTURE:
SourceBaseTextureInterface = static_cast<Direct3DTexture8 *>(pSourceTexture)->GetProxyInterface();
DestinationBaseTextureInterface = static_cast<Direct3DTexture8 *>(pDestinationTexture)->GetProxyInterface();
break;
case D3DRTYPE_VOLUMETEXTURE:
SourceBaseTextureInterface = static_cast<Direct3DVolumeTexture8 *>(pSourceTexture)->GetProxyInterface();
DestinationBaseTextureInterface = static_cast<Direct3DVolumeTexture8 *>(pDestinationTexture)->GetProxyInterface();
break;
case D3DRTYPE_CUBETEXTURE:
SourceBaseTextureInterface = static_cast<Direct3DCubeTexture8 *>(pSourceTexture)->GetProxyInterface();
DestinationBaseTextureInterface = static_cast<Direct3DCubeTexture8 *>(pDestinationTexture)->GetProxyInterface();
break;
default:
return D3DERR_INVALIDCALL;
}
return ProxyInterface->UpdateTexture(SourceBaseTextureInterface, DestinationBaseTextureInterface);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::GetFrontBuffer(Direct3DSurface8 *pDestSurface)
{
if (pDestSurface == nullptr)
{
return D3DERR_INVALIDCALL;
}
return ProxyInterface->GetFrontBufferData(0, pDestSurface->GetProxyInterface());
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::SetRenderTarget(Direct3DSurface8 *pRenderTarget, Direct3DSurface8 *pNewZStencil)
{
HRESULT hr;
if (pRenderTarget != nullptr)
{
hr = ProxyInterface->SetRenderTarget(0, pRenderTarget->GetProxyInterface());
if (FAILED(hr))
{
return hr;
}
pCurrentRenderTarget = pRenderTarget->GetProxyInterface();
}
if (pNewZStencil != nullptr)
{
hr = ProxyInterface->SetDepthStencilSurface(pNewZStencil->GetProxyInterface());
if (FAILED(hr))
{
return hr;
}
}
else
{
ProxyInterface->SetDepthStencilSurface(nullptr);
}
return D3D_OK;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::GetRenderTarget(Direct3DSurface8 **ppRenderTarget)
{
if (ppRenderTarget == nullptr)
{
return D3DERR_INVALIDCALL;
}
IDirect3DSurface9 *SurfaceInterface = nullptr;
const HRESULT hr = ProxyInterface->GetRenderTarget(0, &SurfaceInterface);
if (FAILED(hr))
{
return hr;
}
pCurrentRenderTarget = SurfaceInterface;
*ppRenderTarget = ProxyAddressLookupTable->FindAddress<Direct3DSurface8>(SurfaceInterface);
return D3D_OK;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::GetDepthStencilSurface(Direct3DSurface8 **ppZStencilSurface)
{
if (ppZStencilSurface == nullptr)
{
return D3DERR_INVALIDCALL;
}
IDirect3DSurface9 *SurfaceInterface = nullptr;
const HRESULT hr = ProxyInterface->GetDepthStencilSurface(&SurfaceInterface);
if (FAILED(hr))
{
return hr;
}
*ppZStencilSurface = ProxyAddressLookupTable->FindAddress<Direct3DSurface8>(SurfaceInterface);
return D3D_OK;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::BeginScene()
{
return ProxyInterface->BeginScene();
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::EndScene()
{
return ProxyInterface->EndScene();
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::Clear(DWORD Count, const D3DRECT *pRects, DWORD Flags, D3DCOLOR Color, float Z, DWORD Stencil)
{
return ProxyInterface->Clear(Count, pRects, Flags, Color, Z, Stencil);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::SetTransform(D3DTRANSFORMSTATETYPE State, const D3DMATRIX *pMatrix)
{
return ProxyInterface->SetTransform(State, pMatrix);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::GetTransform(D3DTRANSFORMSTATETYPE State, D3DMATRIX *pMatrix)
{
return ProxyInterface->GetTransform(State, pMatrix);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::MultiplyTransform(D3DTRANSFORMSTATETYPE State, const D3DMATRIX *pMatrix)
{
return ProxyInterface->MultiplyTransform(State, pMatrix);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::SetViewport(const D3DVIEWPORT8 *pViewport)
{
if (pCurrentRenderTarget != nullptr)
{
D3DSURFACE_DESC Desc;
HRESULT hr = pCurrentRenderTarget->GetDesc(&Desc);
if (SUCCEEDED(hr) && (pViewport->Height > Desc.Height || pViewport->Width > Desc.Width))
{
return D3DERR_INVALIDCALL;
}
}
return ProxyInterface->SetViewport(pViewport);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::GetViewport(D3DVIEWPORT8 *pViewport)
{
return ProxyInterface->GetViewport(pViewport);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::SetMaterial(const D3DMATERIAL8 *pMaterial)
{
return ProxyInterface->SetMaterial(pMaterial);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::GetMaterial(D3DMATERIAL8 *pMaterial)
{
return ProxyInterface->GetMaterial(pMaterial);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::SetLight(DWORD Index, const D3DLIGHT8 *pLight)
{
return ProxyInterface->SetLight(Index, pLight);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::GetLight(DWORD Index, D3DLIGHT8 *pLight)
{
return ProxyInterface->GetLight(Index, pLight);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::LightEnable(DWORD Index, BOOL Enable)
{
return ProxyInterface->LightEnable(Index, Enable);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::GetLightEnable(DWORD Index, BOOL *pEnable)
{
return ProxyInterface->GetLightEnable(Index, pEnable);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::SetClipPlane(DWORD Index, const float *pPlane)
{
if (pPlane == nullptr || Index >= MAX_CLIP_PLANES) return D3DERR_INVALIDCALL;
memcpy(StoredClipPlanes[Index], pPlane, sizeof(StoredClipPlanes[0]));
return D3D_OK;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::GetClipPlane(DWORD Index, float *pPlane)
{
if (pPlane == nullptr || Index >= MAX_CLIP_PLANES) return D3DERR_INVALIDCALL;
memcpy(pPlane, StoredClipPlanes[Index], sizeof(StoredClipPlanes[0]));
return D3D_OK;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::SetRenderState(D3DRENDERSTATETYPE State, DWORD Value)
{
FLOAT Biased;
HRESULT hr;
switch (static_cast<DWORD>(State))
{
case D3DRS_LINEPATTERN:
case D3DRS_ZVISIBLE:
case D3DRS_EDGEANTIALIAS:
case D3DRS_PATCHSEGMENTS:
return D3DERR_INVALIDCALL;
case D3DRS_SOFTWAREVERTEXPROCESSING:
return D3D_OK;
case D3DRS_CLIPPLANEENABLE:
hr = ProxyInterface->SetRenderState(State, Value);
if (SUCCEEDED(hr))
{
ClipPlaneRenderState = Value;
}
return hr;
case D3DRS_ZBIAS:
Biased = static_cast<FLOAT>(Value) * -0.000005f;
Value = *reinterpret_cast<const DWORD *>(&Biased);
State = D3DRS_DEPTHBIAS;
default:
return ProxyInterface->SetRenderState(State, Value);
}
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::GetRenderState(D3DRENDERSTATETYPE State, DWORD *pValue)
{
if (pValue == nullptr)
{
return D3DERR_INVALIDCALL;
}
HRESULT hr;
*pValue = 0;
switch (static_cast<DWORD>(State))
{
case D3DRS_LINEPATTERN:
case D3DRS_ZVISIBLE:
case D3DRS_EDGEANTIALIAS:
return D3DERR_INVALIDCALL;
case D3DRS_ZBIAS:
hr = ProxyInterface->GetRenderState(D3DRS_DEPTHBIAS, pValue);
*pValue = static_cast<DWORD>(*reinterpret_cast<const FLOAT *>(pValue) * -500000.0f);
return hr;
case D3DRS_SOFTWAREVERTEXPROCESSING:
*pValue = ProxyInterface->GetSoftwareVertexProcessing();
return D3D_OK;
case D3DRS_PATCHSEGMENTS:
*pValue = 1;
return D3D_OK;
default:
return ProxyInterface->GetRenderState(State, pValue);
}
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::BeginStateBlock()
{
return ProxyInterface->BeginStateBlock();
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::EndStateBlock(DWORD *pToken)
{
if (pToken == nullptr)
{
return D3DERR_INVALIDCALL;
}
return ProxyInterface->EndStateBlock(reinterpret_cast<IDirect3DStateBlock9 **>(pToken));
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::ApplyStateBlock(DWORD Token)
{
if (Token == 0)
{
return D3DERR_INVALIDCALL;
}
return reinterpret_cast<IDirect3DStateBlock9 *>(Token)->Apply();
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::CaptureStateBlock(DWORD Token)
{
if (Token == 0)
{
return D3DERR_INVALIDCALL;
}
return reinterpret_cast<IDirect3DStateBlock9 *>(Token)->Capture();
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::DeleteStateBlock(DWORD Token)
{
if (Token == 0)
{
return D3DERR_INVALIDCALL;
}
reinterpret_cast<IDirect3DStateBlock9 *>(Token)->Release();
return D3D_OK;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::CreateStateBlock(D3DSTATEBLOCKTYPE Type, DWORD *pToken)
{
#ifndef D3D8TO9NOLOG
LOG << "Redirecting '" << "IDirect3DDevice8::CreateStateBlock" << "(" << Type << ", " << pToken << ")' ..." << std::endl;
#endif
if (pToken == nullptr)
{
return D3DERR_INVALIDCALL;
}
return ProxyInterface->CreateStateBlock(Type, reinterpret_cast<IDirect3DStateBlock9 **>(pToken));
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::SetClipStatus(const D3DCLIPSTATUS8 *pClipStatus)
{
return ProxyInterface->SetClipStatus(pClipStatus);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::GetClipStatus(D3DCLIPSTATUS8 *pClipStatus)
{
return ProxyInterface->GetClipStatus(pClipStatus);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::GetTexture(DWORD Stage, Direct3DBaseTexture8 **ppTexture)
{
if (ppTexture == nullptr)
{
return D3DERR_INVALIDCALL;
}
*ppTexture = nullptr;
IDirect3DBaseTexture9 *BaseTextureInterface = nullptr;
const HRESULT hr = ProxyInterface->GetTexture(Stage, &BaseTextureInterface);
if (FAILED(hr))
{
return hr;
}
if (BaseTextureInterface != nullptr)
{
IDirect3DTexture9 *TextureInterface = nullptr;
IDirect3DCubeTexture9 *CubeTextureInterface = nullptr;
IDirect3DVolumeTexture9 *VolumeTextureInterface = nullptr;
switch (BaseTextureInterface->GetType())
{
case D3DRTYPE_TEXTURE:
BaseTextureInterface->QueryInterface(IID_PPV_ARGS(&TextureInterface));
*ppTexture = ProxyAddressLookupTable->FindAddress<Direct3DTexture8>(TextureInterface);
break;
case D3DRTYPE_VOLUMETEXTURE:
BaseTextureInterface->QueryInterface(IID_PPV_ARGS(&VolumeTextureInterface));
*ppTexture = ProxyAddressLookupTable->FindAddress<Direct3DVolumeTexture8>(VolumeTextureInterface);
break;
case D3DRTYPE_CUBETEXTURE:
BaseTextureInterface->QueryInterface(IID_PPV_ARGS(&CubeTextureInterface));
*ppTexture = ProxyAddressLookupTable->FindAddress<Direct3DCubeTexture8>(CubeTextureInterface);
break;
default:
return D3DERR_INVALIDCALL;
}
}
return D3D_OK;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::SetTexture(DWORD Stage, Direct3DBaseTexture8 *pTexture)
{
if (pTexture == nullptr)
{
return ProxyInterface->SetTexture(Stage, nullptr);
}
IDirect3DBaseTexture9 *BaseTextureInterface;
switch (pTexture->GetType())
{
case D3DRTYPE_TEXTURE:
BaseTextureInterface = static_cast<Direct3DTexture8 *>(pTexture)->GetProxyInterface();
break;
case D3DRTYPE_VOLUMETEXTURE:
BaseTextureInterface = static_cast<Direct3DVolumeTexture8 *>(pTexture)->GetProxyInterface();
break;
case D3DRTYPE_CUBETEXTURE:
BaseTextureInterface = static_cast<Direct3DCubeTexture8 *>(pTexture)->GetProxyInterface();
break;
default:
return D3DERR_INVALIDCALL;
}
return ProxyInterface->SetTexture(Stage, BaseTextureInterface);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::GetTextureStageState(DWORD Stage, D3DTEXTURESTAGESTATETYPE Type, DWORD *pValue)
{
switch (static_cast<DWORD>(Type))
{
case D3DTSS_ADDRESSU:
return ProxyInterface->GetSamplerState(Stage, D3DSAMP_ADDRESSU, pValue);
case D3DTSS_ADDRESSV:
return ProxyInterface->GetSamplerState(Stage, D3DSAMP_ADDRESSV, pValue);
case D3DTSS_ADDRESSW:
return ProxyInterface->GetSamplerState(Stage, D3DSAMP_ADDRESSW, pValue);
case D3DTSS_BORDERCOLOR:
return ProxyInterface->GetSamplerState(Stage, D3DSAMP_BORDERCOLOR, pValue);
case D3DTSS_MAGFILTER:
return ProxyInterface->GetSamplerState(Stage, D3DSAMP_MAGFILTER, pValue);
case D3DTSS_MINFILTER:
return ProxyInterface->GetSamplerState(Stage, D3DSAMP_MINFILTER, pValue);
case D3DTSS_MIPFILTER:
return ProxyInterface->GetSamplerState(Stage, D3DSAMP_MIPFILTER, pValue);
case D3DTSS_MIPMAPLODBIAS:
return ProxyInterface->GetSamplerState(Stage, D3DSAMP_MIPMAPLODBIAS, pValue);
case D3DTSS_MAXMIPLEVEL:
return ProxyInterface->GetSamplerState(Stage, D3DSAMP_MAXMIPLEVEL, pValue);
case D3DTSS_MAXANISOTROPY:
return ProxyInterface->GetSamplerState(Stage, D3DSAMP_MAXANISOTROPY, pValue);
default:
return ProxyInterface->GetTextureStageState(Stage, Type, pValue);
}
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::SetTextureStageState(DWORD Stage, D3DTEXTURESTAGESTATETYPE Type, DWORD Value)
{
switch (static_cast<DWORD>(Type))
{
case D3DTSS_ADDRESSU:
return ProxyInterface->SetSamplerState(Stage, D3DSAMP_ADDRESSU, Value);
case D3DTSS_ADDRESSV:
return ProxyInterface->SetSamplerState(Stage, D3DSAMP_ADDRESSV, Value);
case D3DTSS_ADDRESSW:
return ProxyInterface->SetSamplerState(Stage, D3DSAMP_ADDRESSW, Value);
case D3DTSS_BORDERCOLOR:
return ProxyInterface->SetSamplerState(Stage, D3DSAMP_BORDERCOLOR, Value);
case D3DTSS_MAGFILTER:
return ProxyInterface->SetSamplerState(Stage, D3DSAMP_MAGFILTER, Value);
case D3DTSS_MINFILTER:
return ProxyInterface->SetSamplerState(Stage, D3DSAMP_MINFILTER, Value);
case D3DTSS_MIPFILTER:
return ProxyInterface->SetSamplerState(Stage, D3DSAMP_MIPFILTER, Value);
case D3DTSS_MIPMAPLODBIAS:
return ProxyInterface->SetSamplerState(Stage, D3DSAMP_MIPMAPLODBIAS, Value);
case D3DTSS_MAXMIPLEVEL:
return ProxyInterface->SetSamplerState(Stage, D3DSAMP_MAXMIPLEVEL, Value);
case D3DTSS_MAXANISOTROPY:
return ProxyInterface->SetSamplerState(Stage, D3DSAMP_MAXANISOTROPY, Value);
default:
return ProxyInterface->SetTextureStageState(Stage, Type, Value);
}
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::ValidateDevice(DWORD *pNumPasses)
{
return ProxyInterface->ValidateDevice(pNumPasses);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::GetInfo(DWORD DevInfoID, void *pDevInfoStruct, DWORD DevInfoStructSize)
{
UNREFERENCED_PARAMETER(DevInfoID);
UNREFERENCED_PARAMETER(pDevInfoStruct);
UNREFERENCED_PARAMETER(DevInfoStructSize);
#ifndef D3D8TO9NOLOG
LOG << "Redirecting '" << "IDirect3DDevice8::GetInfo" << "(" << this << ", " << DevInfoID << ", " << pDevInfoStruct << ", " << DevInfoStructSize << ")' ..." << std::endl;
#endif
return S_FALSE;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::SetPaletteEntries(UINT PaletteNumber, const PALETTEENTRY *pEntries)
{
if (pEntries == nullptr)
{
return D3DERR_INVALIDCALL;
}
return ProxyInterface->SetPaletteEntries(PaletteNumber, pEntries);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::GetPaletteEntries(UINT PaletteNumber, PALETTEENTRY *pEntries)
{
if (pEntries == nullptr)
{
return D3DERR_INVALIDCALL;
}
return ProxyInterface->GetPaletteEntries(PaletteNumber, pEntries);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::SetCurrentTexturePalette(UINT PaletteNumber)
{
if (!PaletteFlag)
{
return D3DERR_INVALIDCALL;
}
return ProxyInterface->SetCurrentTexturePalette(PaletteNumber);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::GetCurrentTexturePalette(UINT *pPaletteNumber)
{
if (!PaletteFlag)
{
return D3DERR_INVALIDCALL;
}
return ProxyInterface->GetCurrentTexturePalette(pPaletteNumber);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::DrawPrimitive(D3DPRIMITIVETYPE PrimitiveType, UINT StartVertex, UINT PrimitiveCount)
{
ApplyClipPlanes();
return ProxyInterface->DrawPrimitive(PrimitiveType, StartVertex, PrimitiveCount);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::DrawIndexedPrimitive(D3DPRIMITIVETYPE PrimitiveType, UINT MinIndex, UINT NumVertices, UINT StartIndex, UINT PrimitiveCount)
{
ApplyClipPlanes();
return ProxyInterface->DrawIndexedPrimitive(PrimitiveType, CurrentBaseVertexIndex, MinIndex, NumVertices, StartIndex, PrimitiveCount);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::DrawPrimitiveUP(D3DPRIMITIVETYPE PrimitiveType, UINT PrimitiveCount, const void *pVertexStreamZeroData, UINT VertexStreamZeroStride)
{
ApplyClipPlanes();
return ProxyInterface->DrawPrimitiveUP(PrimitiveType, PrimitiveCount, pVertexStreamZeroData, VertexStreamZeroStride);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::DrawIndexedPrimitiveUP(D3DPRIMITIVETYPE PrimitiveType, UINT MinVertexIndex, UINT NumVertexIndices, UINT PrimitiveCount, const void *pIndexData, D3DFORMAT IndexDataFormat, const void *pVertexStreamZeroData, UINT VertexStreamZeroStride)
{
ApplyClipPlanes();
return ProxyInterface->DrawIndexedPrimitiveUP(PrimitiveType, MinVertexIndex, NumVertexIndices, PrimitiveCount, pIndexData, IndexDataFormat, pVertexStreamZeroData, VertexStreamZeroStride);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::ProcessVertices(UINT SrcStartIndex, UINT DestIndex, UINT VertexCount, Direct3DVertexBuffer8 *pDestBuffer, DWORD Flags)
{
if (pDestBuffer == nullptr)
{
return D3DERR_INVALIDCALL;
}
return ProxyInterface->ProcessVertices(SrcStartIndex, DestIndex, VertexCount, pDestBuffer->GetProxyInterface(), nullptr, Flags);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::CreateVertexShader(const DWORD *pDeclaration, const DWORD *pFunction, DWORD *pHandle, DWORD Usage)
{
UNREFERENCED_PARAMETER(Usage);
#ifndef D3D8TO9NOLOG
LOG << "Redirecting '" << "IDirect3DDevice8::CreateVertexShader" << "(" << this << ", " << pDeclaration << ", " << pFunction << ", " << pHandle << ", " << Usage << ")' ..." << std::endl;
#endif
if (pDeclaration == nullptr || pHandle == nullptr)
{
return D3DERR_INVALIDCALL;
}
*pHandle = 0;
UINT ElementIndex = 0;
const UINT ElementLimit = 32;
std::string ConstantsCode;
WORD Stream = 0, Offset = 0;
DWORD VertexShaderInputs[ElementLimit];
D3DVERTEXELEMENT9 VertexElements[ElementLimit];
#ifndef D3D8TO9NOLOG
LOG << "> Translating vertex declaration ..." << std::endl;
#endif
static const BYTE DeclTypes[][2] =
{
{ D3DDECLTYPE_FLOAT1, 4 },
{ D3DDECLTYPE_FLOAT2, 8 },
{ D3DDECLTYPE_FLOAT3, 12 },
{ D3DDECLTYPE_FLOAT4, 16 },
{ D3DDECLTYPE_D3DCOLOR, 4 },
{ D3DDECLTYPE_UBYTE4, 4 },
{ D3DDECLTYPE_SHORT2, 4 },
{ D3DDECLTYPE_SHORT4, 8 },
{ D3DDECLTYPE_UBYTE4N, 4 },
{ D3DDECLTYPE_SHORT2N, 4 },
{ D3DDECLTYPE_SHORT4N, 8 },
{ D3DDECLTYPE_USHORT2N, 4 },
{ D3DDECLTYPE_USHORT4N, 8 },
{ D3DDECLTYPE_UDEC3, 6 },
{ D3DDECLTYPE_DEC3N, 6 },
{ D3DDECLTYPE_FLOAT16_2, 8 },
{ D3DDECLTYPE_FLOAT16_4, 16 }
};
static const BYTE DeclAddressUsages[][2] =
{
{ D3DDECLUSAGE_POSITION, 0 },
{ D3DDECLUSAGE_BLENDWEIGHT, 0 },
{ D3DDECLUSAGE_BLENDINDICES, 0 },
{ D3DDECLUSAGE_NORMAL, 0 },
{ D3DDECLUSAGE_PSIZE, 0 },
{ D3DDECLUSAGE_COLOR, 0 },
{ D3DDECLUSAGE_COLOR, 1 },
{ D3DDECLUSAGE_TEXCOORD, 0 },
{ D3DDECLUSAGE_TEXCOORD, 1 },
{ D3DDECLUSAGE_TEXCOORD, 2 },
{ D3DDECLUSAGE_TEXCOORD, 3 },
{ D3DDECLUSAGE_TEXCOORD, 4 },
{ D3DDECLUSAGE_TEXCOORD, 5 },
{ D3DDECLUSAGE_TEXCOORD, 6 },
{ D3DDECLUSAGE_TEXCOORD, 7 },
{ D3DDECLUSAGE_POSITION, 1 },
{ D3DDECLUSAGE_NORMAL, 1 }
};
while (ElementIndex < ElementLimit)
{
const DWORD Token = *pDeclaration;
const DWORD TokenType = (Token & D3DVSD_TOKENTYPEMASK) >> D3DVSD_TOKENTYPESHIFT;
if (Token == D3DVSD_END())
{
break;
}
else if (TokenType == D3DVSD_TOKEN_STREAM)
{
Stream = static_cast<WORD>((Token & D3DVSD_STREAMNUMBERMASK) >> D3DVSD_STREAMNUMBERSHIFT);
Offset = 0;
}
else if (TokenType == D3DVSD_TOKEN_STREAMDATA && !(Token & 0x10000000))
{
VertexElements[ElementIndex].Stream = Stream;
VertexElements[ElementIndex].Offset = Offset;
const DWORD type = (Token & D3DVSD_DATATYPEMASK) >> D3DVSD_DATATYPESHIFT;
VertexElements[ElementIndex].Type = DeclTypes[type][0];
Offset += DeclTypes[type][1];
VertexElements[ElementIndex].Method = D3DDECLMETHOD_DEFAULT;
const DWORD Address = (Token & D3DVSD_VERTEXREGMASK) >> D3DVSD_VERTEXREGSHIFT;
VertexElements[ElementIndex].Usage = DeclAddressUsages[Address][0];
VertexElements[ElementIndex].UsageIndex = DeclAddressUsages[Address][1];
VertexShaderInputs[ElementIndex++] = Address;
}
else if (TokenType == D3DVSD_TOKEN_STREAMDATA && (Token & 0x10000000))
{
Offset += ((Token & D3DVSD_SKIPCOUNTMASK) >> D3DVSD_SKIPCOUNTSHIFT) * sizeof(DWORD);
}
else if (TokenType == D3DVSD_TOKEN_TESSELLATOR && !(Token & 0x10000000))
{
VertexElements[ElementIndex].Stream = Stream;
VertexElements[ElementIndex].Offset = Offset;
const DWORD UsageType = (Token & D3DVSD_VERTEXREGINMASK) >> D3DVSD_VERTEXREGINSHIFT;
for (UINT r = 0; r < ElementIndex; ++r)
{
if (VertexElements[r].Usage == DeclAddressUsages[UsageType][0] && VertexElements[r].UsageIndex == DeclAddressUsages[UsageType][1])
{
VertexElements[ElementIndex].Stream = VertexElements[r].Stream;
VertexElements[ElementIndex].Offset = VertexElements[r].Offset;
break;
}
}
VertexElements[ElementIndex].Type = D3DDECLTYPE_FLOAT3;
VertexElements[ElementIndex].Method = D3DDECLMETHOD_CROSSUV;
const DWORD Address = (Token & 0xF);
VertexElements[ElementIndex].Usage = DeclAddressUsages[Address][0];
VertexElements[ElementIndex].UsageIndex = DeclAddressUsages[Address][1];
if (VertexElements[ElementIndex].Usage == D3DDECLUSAGE_BLENDINDICES)
{
VertexElements[ElementIndex].Method = D3DDECLMETHOD_DEFAULT;
}
VertexShaderInputs[ElementIndex++] = Address;
}
else if (TokenType == D3DVSD_TOKEN_TESSELLATOR && (Token & 0x10000000))
{
VertexElements[ElementIndex].Stream = 0;
VertexElements[ElementIndex].Offset = 0;
VertexElements[ElementIndex].Type = D3DDECLTYPE_UNUSED;
VertexElements[ElementIndex].Method = D3DDECLMETHOD_UV;
const DWORD Address = (Token & 0xF);
VertexElements[ElementIndex].Usage = DeclAddressUsages[Address][0];
VertexElements[ElementIndex].UsageIndex = DeclAddressUsages[Address][1];
if (VertexElements[ElementIndex].Usage == D3DDECLUSAGE_BLENDINDICES)
{
VertexElements[ElementIndex].Method = D3DDECLMETHOD_DEFAULT;
}
VertexShaderInputs[ElementIndex++] = Address;
}
else if (TokenType == D3DVSD_TOKEN_CONSTMEM)
{
const DWORD RegisterCount = 4 * ((Token & D3DVSD_CONSTCOUNTMASK) >> D3DVSD_CONSTCOUNTSHIFT);
DWORD Address = (Token & D3DVSD_CONSTADDRESSMASK) >> D3DVSD_CONSTADDRESSSHIFT;
for (DWORD RegisterIndex = 0; RegisterIndex < RegisterCount; RegisterIndex += 4, ++Address)
{
ConstantsCode += " def c" + std::to_string(Address) + ", " +
std::to_string(*reinterpret_cast<const float *>(&pDeclaration[RegisterIndex + 1])) + ", " +
std::to_string(*reinterpret_cast<const float *>(&pDeclaration[RegisterIndex + 2])) + ", " +
std::to_string(*reinterpret_cast<const float *>(&pDeclaration[RegisterIndex + 3])) + ", " +
std::to_string(*reinterpret_cast<const float *>(&pDeclaration[RegisterIndex + 4])) + " /* vertex declaration constant */\n";
}
pDeclaration += RegisterCount;
}
else
{
#ifndef D3D8TO9NOLOG
LOG << "> Failed because token type '" << TokenType << "' is not supported!" << std::endl;
#endif
return D3DERR_INVALIDCALL;
}
++pDeclaration;
}
const D3DVERTEXELEMENT9 Terminator = D3DDECL_END();
VertexElements[ElementIndex] = Terminator;
HRESULT hr;
VertexShaderInfo *ShaderInfo;
if (pFunction != nullptr)
{
#ifndef D3D8TO9NOLOG
LOG << "> Disassembling shader and translating assembly to Direct3D 9 compatible code ..." << std::endl;
#endif
if (*pFunction < D3DVS_VERSION(1, 0) || *pFunction > D3DVS_VERSION(1, 1))
{
#ifndef D3D8TO9NOLOG
LOG << "> Failed because of version mismatch ('" << std::showbase << std::hex << *pFunction << std::dec << std::noshowbase << "')! Only 'vs_1_x' shaders are supported." << std::endl;
#endif
return D3DERR_INVALIDCALL;
}
ID3DXBuffer *Disassembly = nullptr, *Assembly = nullptr, *ErrorBuffer = nullptr;
if (D3DXDisassembleShader != nullptr)
{
hr = D3DXDisassembleShader(pFunction, FALSE, nullptr, &Disassembly);
}
else
{
hr = D3DERR_INVALIDCALL;
}
if (FAILED(hr))
{
#ifndef D3D8TO9NOLOG
LOG << "> Failed to disassemble shader with error code " << std::hex << hr << std::dec << "!" << std::endl;
#endif
return hr;
}
std::string SourceCode(static_cast<const char *>(Disassembly->GetBufferPointer()), Disassembly->GetBufferSize() - 1);
#ifndef D3D8TO9NOLOG
LOG << "> Dumping original shader assembly:" << std::endl << std::endl << SourceCode << std::endl;
#endif
const size_t VersionPosition = SourceCode.find("vs_1_");
assert(VersionPosition != std::string::npos);
if (SourceCode.at(VersionPosition + 5) == '0')
{
#ifndef D3D8TO9NOLOG
LOG << "> Replacing version 'vs_1_0' with 'vs_1_1' ..." << std::endl;
#endif
SourceCode.replace(VersionPosition, 6, "vs_1_1");
}
size_t DeclPosition = VersionPosition + 7;
for (UINT k = 0; k < ElementIndex; k++)
{
std::string DeclCode = " ";
switch (VertexElements[k].Usage)
{
case D3DDECLUSAGE_POSITION:
DeclCode += "dcl_position";
break;
case D3DDECLUSAGE_BLENDWEIGHT:
DeclCode += "dcl_blendweight";
break;
case D3DDECLUSAGE_BLENDINDICES:
DeclCode += "dcl_blendindices";
break;
case D3DDECLUSAGE_NORMAL:
DeclCode += "dcl_normal";
break;
case D3DDECLUSAGE_PSIZE:
DeclCode += "dcl_psize";
break;
case D3DDECLUSAGE_COLOR:
DeclCode += "dcl_color";
break;
case D3DDECLUSAGE_TEXCOORD:
DeclCode += "dcl_texcoord";
break;
}
if (VertexElements[k].UsageIndex > 0)
{
DeclCode += std::to_string(VertexElements[k].UsageIndex);
}
DeclCode += " v" + std::to_string(VertexShaderInputs[k]) + '\n';
SourceCode.insert(DeclPosition, DeclCode);
DeclPosition += DeclCode.length();
}
#pragma region Fill registers with default value
SourceCode.insert(DeclPosition, ConstantsCode);
// Get number of arithmetic instructions used
const size_t InstructionPosition = SourceCode.find("instruction");
size_t InstructionCount = InstructionPosition > 2 && InstructionPosition < SourceCode.size() ? strtoul(SourceCode.substr(InstructionPosition - 4, 4).c_str(), nullptr, 10) : 0;
for (size_t j = 0; j < 8; j++)
{
const std::string reg = "oT" + std::to_string(j);
if (SourceCode.find(reg) != std::string::npos && InstructionCount < 128)
{
++InstructionCount;
SourceCode.insert(DeclPosition + ConstantsCode.size(), " mov " + reg + ", c0 /* initialize output register " + reg + " */\n");
}
}
for (size_t j = 0; j < 2; j++)
{
const std::string reg = "oD" + std::to_string(j);
if (SourceCode.find(reg) != std::string::npos && InstructionCount < 128)
{
++InstructionCount;
SourceCode.insert(DeclPosition + ConstantsCode.size(), " mov " + reg + ", c0 /* initialize output register " + reg + " */\n");
}
}
for (size_t j = 0; j < 12; j++)
{
const std::string reg = "r" + std::to_string(j);
if (SourceCode.find(reg) != std::string::npos && InstructionCount < 128)
{
++InstructionCount;
SourceCode.insert(DeclPosition + ConstantsCode.size(), " mov " + reg + ", c0 /* initialize register " + reg + " */\n");
}
}
#pragma endregion
SourceCode = std::regex_replace(SourceCode, std::regex(" \\/\\/ vs\\.1\\.1\\n((?! ).+\\n)+"), "");
SourceCode = std::regex_replace(SourceCode, std::regex("([^\\n]\\n)[\\s]*#line [0123456789]+.*\\n"), "$1");
SourceCode = std::regex_replace(SourceCode, std::regex("(oFog|oPts)\\.x"), "$1 /* removed swizzle */");
SourceCode = std::regex_replace(SourceCode, std::regex("(add|sub|mul|min|max) (oFog|oPts), ([cr][0-9]+), (.+)\\n"), "$1 $2, $3.x /* added swizzle */, $4\n");
SourceCode = std::regex_replace(SourceCode, std::regex("(add|sub|mul|min|max) (oFog|oPts), (.+), ([cr][0-9]+)\\n"), "$1 $2, $3, $4.x /* added swizzle */\n");
SourceCode = std::regex_replace(SourceCode, std::regex("mov (oFog|oPts)(.*), (-?)([crv][0-9]+(?![\\.0-9]))"), "mov $1$2, $3$4.x /* select single component */");
// Destination register cannot be the same as first source register for m*x* instructions.
if (std::regex_search(SourceCode, std::regex("m.x.")))
{
// Check for unused register
size_t r;
for (r = 0; r < 12; r++)
{
if (SourceCode.find("r" + std::to_string(r)) == std::string::npos) break;
}
// Check if first source register is the same as the destination register
for (size_t j = 0; j < 12; j++)
{
const std::string reg = "(m.x.) (r" + std::to_string(j) + "), ((-?)r" + std::to_string(j) + "([\\.xyzw]*))(?![0-9])";
while (std::regex_search(SourceCode, std::regex(reg)))
{
// If there is enough remaining instructions and an unused register then update to use a temp register
if (r < 12 && InstructionCount < 128)
{
++InstructionCount;
SourceCode = std::regex_replace(SourceCode, std::regex(reg),
"mov r" + std::to_string(r) + ", $2 /* added line */\n $1 $2, $4r" + std::to_string(r) + "$5 /* changed $3 to r" + std::to_string(r) + " */",
std::regex_constants::format_first_only);
}
// Disable line to prevent assembly error
else
{
SourceCode = std::regex_replace(SourceCode, std::regex("(.*" + reg + ".*)"), "/*$1*/ /* disabled this line */");
break;
}
}
}
}
#ifndef D3D8TO9NOLOG
LOG << "> Dumping translated shader assembly:" << std::endl << std::endl << SourceCode << std::endl;
#endif
if (D3DXAssembleShader != nullptr)
{
hr = D3DXAssembleShader(SourceCode.data(), static_cast<UINT>(SourceCode.size()), nullptr, nullptr, D3DXASM_FLAGS, &Assembly, &ErrorBuffer);
}
else
{
hr = D3DERR_INVALIDCALL;
}
Disassembly->Release();
if (FAILED(hr))
{
if (ErrorBuffer != nullptr)
{
#ifndef D3D8TO9NOLOG
LOG << "> Failed to reassemble shader:" << std::endl << std::endl << static_cast<const char *>(ErrorBuffer->GetBufferPointer()) << std::endl;
#endif
ErrorBuffer->Release();
}
else
{
#ifndef D3D8TO9NOLOG
LOG << "> Failed to reassemble shader with error code " << std::hex << hr << std::dec << "!" << std::endl;
#endif
}
return hr;
}
ShaderInfo = new VertexShaderInfo();
hr = ProxyInterface->CreateVertexShader(static_cast<const DWORD *>(Assembly->GetBufferPointer()), &ShaderInfo->Shader);
Assembly->Release();
}
else
{
ShaderInfo = new VertexShaderInfo();
ShaderInfo->Shader = nullptr;
hr = D3D_OK;
}
if (SUCCEEDED(hr))
{
hr = ProxyInterface->CreateVertexDeclaration(VertexElements, &ShaderInfo->Declaration);
if (SUCCEEDED(hr))
{
// Since 'Shader' is at least 8 byte aligned, we can safely shift it to right and end up not overwriting the top bit
assert((reinterpret_cast<DWORD>(ShaderInfo) & 1) == 0);
const DWORD ShaderMagic = reinterpret_cast<DWORD>(ShaderInfo) >> 1;
*pHandle = ShaderMagic | 0x80000000;
}
else
{
#ifndef D3D8TO9NOLOG
LOG << "> 'IDirect3DDevice9::CreateVertexDeclaration' failed with error code " << std::hex << hr << std::dec << "!" << std::endl;
#endif
if (ShaderInfo->Shader != nullptr)
{
ShaderInfo->Shader->Release();
}
}
}
else
{
#ifndef D3D8TO9NOLOG
LOG << "> 'IDirect3DDevice9::CreateVertexShader' failed with error code " << std::hex << hr << std::dec << "!" << std::endl;
#endif
}
if (FAILED(hr))
{
delete ShaderInfo;
}
return hr;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::SetVertexShader(DWORD Handle)
{
HRESULT hr;
if ((Handle & 0x80000000) == 0)
{
ProxyInterface->SetVertexShader(nullptr);
hr = ProxyInterface->SetFVF(Handle);
CurrentVertexShaderHandle = 0;
}
else
{
const DWORD handleMagic = Handle << 1;
VertexShaderInfo *const ShaderInfo = reinterpret_cast<VertexShaderInfo *>(handleMagic);
hr = ProxyInterface->SetVertexShader(ShaderInfo->Shader);
ProxyInterface->SetVertexDeclaration(ShaderInfo->Declaration);
CurrentVertexShaderHandle = Handle;
}
return hr;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::GetVertexShader(DWORD *pHandle)
{
if (pHandle == nullptr)
{
return D3DERR_INVALIDCALL;
}
if (CurrentVertexShaderHandle == 0)
{
return ProxyInterface->GetFVF(pHandle);
}
else
{
*pHandle = CurrentVertexShaderHandle;
return D3D_OK;
}
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::DeleteVertexShader(DWORD Handle)
{
if ((Handle & 0x80000000) == 0)
{
return D3DERR_INVALIDCALL;
}
if (CurrentVertexShaderHandle == Handle)
{
SetVertexShader(0);
}
const DWORD HandleMagic = Handle << 1;
VertexShaderInfo *const ShaderInfo = reinterpret_cast<VertexShaderInfo *>(HandleMagic);
if (ShaderInfo->Shader != nullptr)
{
ShaderInfo->Shader->Release();
}
if (ShaderInfo->Declaration != nullptr)
{
ShaderInfo->Declaration->Release();
}
delete ShaderInfo;
return D3D_OK;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::SetVertexShaderConstant(DWORD Register, const void *pConstantData, DWORD ConstantCount)
{
return ProxyInterface->SetVertexShaderConstantF(Register, static_cast<const float *>(pConstantData), ConstantCount);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::GetVertexShaderConstant(DWORD Register, void *pConstantData, DWORD ConstantCount)
{
return ProxyInterface->GetVertexShaderConstantF(Register, static_cast<float *>(pConstantData), ConstantCount);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::GetVertexShaderDeclaration(DWORD Handle, void *pData, DWORD *pSizeOfData)
{
UNREFERENCED_PARAMETER(Handle);
UNREFERENCED_PARAMETER(pData);
UNREFERENCED_PARAMETER(pSizeOfData);
#ifndef D3D8TO9NOLOG
LOG << "Redirecting '" << "IDirect3DDevice8::GetVertexShaderDeclaration" << "(" << this << ", " << Handle << ", " << pData << ", " << pSizeOfData << ")' ..." << std::endl;
LOG << "> 'IDirect3DDevice8::GetVertexShaderDeclaration' is not implemented!" << std::endl;
#endif
return D3DERR_INVALIDCALL;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::GetVertexShaderFunction(DWORD Handle, void *pData, DWORD *pSizeOfData)
{
#ifndef D3D8TO9NOLOG
LOG << "Redirecting '" << "IDirect3DDevice8::GetVertexShaderFunction" << "(" << this << ", " << Handle << ", " << pData << ", " << pSizeOfData << ")' ..." << std::endl;
#endif
if ((Handle & 0x80000000) == 0)
{
return D3DERR_INVALIDCALL;
}
const DWORD HandleMagic = Handle << 1;
IDirect3DVertexShader9 *VertexShaderInterface = reinterpret_cast<VertexShaderInfo *>(HandleMagic)->Shader;
if (VertexShaderInterface == nullptr)
{
return D3DERR_INVALIDCALL;
}
#ifndef D3D8TO9NOLOG
LOG << "> Returning translated shader byte code." << std::endl;
#endif
return VertexShaderInterface->GetFunction(pData, reinterpret_cast<UINT *>(pSizeOfData));
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::SetStreamSource(UINT StreamNumber, Direct3DVertexBuffer8 *pStreamData, UINT Stride)
{
if (pStreamData == nullptr)
{
return D3DERR_INVALIDCALL;
}
return ProxyInterface->SetStreamSource(StreamNumber, pStreamData->GetProxyInterface(), 0, Stride);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::GetStreamSource(UINT StreamNumber, Direct3DVertexBuffer8 **ppStreamData, UINT *pStride)
{
if (ppStreamData == nullptr)
{
return D3DERR_INVALIDCALL;
}
else
{
*ppStreamData = nullptr;
}
UINT StreamOffset = 0;
IDirect3DVertexBuffer9 *VertexBufferInterface = nullptr;
const HRESULT hr = ProxyInterface->GetStreamSource(StreamNumber, &VertexBufferInterface, &StreamOffset, pStride);
if (FAILED(hr))
{
return hr;
}
if (VertexBufferInterface != nullptr)
{
*ppStreamData = ProxyAddressLookupTable->FindAddress<Direct3DVertexBuffer8>(VertexBufferInterface);
}
return D3D_OK;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::SetIndices(Direct3DIndexBuffer8 *pIndexData, UINT BaseVertexIndex)
{
if (pIndexData == nullptr || BaseVertexIndex > 0x7FFFFFFF)
{
return D3DERR_INVALIDCALL;
}
CurrentBaseVertexIndex = static_cast<INT>(BaseVertexIndex);
return ProxyInterface->SetIndices(pIndexData->GetProxyInterface());
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::GetIndices(Direct3DIndexBuffer8 **ppIndexData, UINT *pBaseVertexIndex)
{
if (ppIndexData == nullptr)
{
return D3DERR_INVALIDCALL;
}
*ppIndexData = nullptr;
if (pBaseVertexIndex != nullptr)
{
*pBaseVertexIndex = static_cast<UINT>(CurrentBaseVertexIndex);
}
IDirect3DIndexBuffer9 *IntexBufferInterface = nullptr;
const HRESULT hr = ProxyInterface->GetIndices(&IntexBufferInterface);
if (FAILED(hr))
{
return hr;
}
if (IntexBufferInterface != nullptr)
{
*ppIndexData = ProxyAddressLookupTable->FindAddress<Direct3DIndexBuffer8>(IntexBufferInterface);
}
return D3D_OK;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::CreatePixelShader(const DWORD *pFunction, DWORD *pHandle)
{
#ifndef D3D8TO9NOLOG
LOG << "Redirecting '" << "IDirect3DDevice8::CreatePixelShader" << "(" << this << ", " << pFunction << ", " << pHandle << ")' ..." << std::endl;
#endif
if (pFunction == nullptr || pHandle == nullptr)
{
return D3DERR_INVALIDCALL;
}
*pHandle = 0;
#ifndef D3D8TO9NOLOG
LOG << "> Disassembling shader and translating assembly to Direct3D 9 compatible code ..." << std::endl;
#endif
if (*pFunction < D3DPS_VERSION(1, 0) || *pFunction > D3DPS_VERSION(1, 4))
{
#ifndef D3D8TO9NOLOG
LOG << "> Failed because of version mismatch ('" << std::showbase << std::hex << *pFunction << std::dec << std::noshowbase << "')! Only 'ps_1_x' shaders are supported." << std::endl;
#endif
return D3DERR_INVALIDCALL;
}
ID3DXBuffer *Disassembly = nullptr, *Assembly = nullptr, *ErrorBuffer = nullptr;
HRESULT hr = D3DERR_INVALIDCALL;
if (D3DXDisassembleShader != nullptr)
{
hr = D3DXDisassembleShader(pFunction, FALSE, nullptr, &Disassembly);
}
if (FAILED(hr))
{
#ifndef D3D8TO9NOLOG
LOG << "> Failed to disassemble shader with error code " << std::hex << hr << std::dec << "!" << std::endl;
#endif
return hr;
}
std::string SourceCode(static_cast<const char *>(Disassembly->GetBufferPointer()), Disassembly->GetBufferSize() - 1);
const size_t VersionPosition = SourceCode.find("ps_1_");
assert(VersionPosition != std::string::npos);
if (SourceCode.at(VersionPosition + 5) == '0')
{
#ifndef D3D8TO9NOLOG
LOG << "> Replacing version 'ps_1_0' with 'ps_1_1' ..." << std::endl;
#endif
SourceCode.replace(VersionPosition, 6, "ps_1_1");
}
// Get number of arithmetic instructions used
const size_t ArithmeticPosition = SourceCode.find("arithmetic");
size_t ArithmeticCount = ArithmeticPosition > 2 && ArithmeticPosition < SourceCode.size() ? strtoul(SourceCode.substr(ArithmeticPosition - 2, 2).c_str(), nullptr, 10) : 0;
ArithmeticCount = (ArithmeticCount != 0) ? ArithmeticCount : 10; // Default to 10
// Remove lines when " // ps.1.1" string is found and the next line does not start with a space
SourceCode = std::regex_replace(SourceCode,
std::regex(" \\/\\/ ps\\.1\\.[1-4]\\n((?! ).+\\n)+"),
"");
// Remove debug lines
SourceCode = std::regex_replace(SourceCode,
std::regex("([^\\n]\\n)[\\s]*#line [0123456789]+.*\\n"),
"$1");
// Fix '-' modifier for constant values when using 'add' arithmetic by changing it to use 'sub'
SourceCode = std::regex_replace(SourceCode,
std::regex("(add)([_satxd248]*) (r[0-9][\\.wxyz]*), ((1-|)[crtv][0-9][\\.wxyz_abdis2]*), (-)(c[0-9][\\.wxyz]*)(_bx2|_bias|_x2|_d[zbwa]|)(?![_\\.wxyz])"),
"sub$2 $3, $4, $7$8 /* changed 'add' to 'sub' removed modifier $6 */");
// Create temporary varables for ps_1_4
std::string SourceCode14 = SourceCode;
int ArithmeticCount14 = ArithmeticCount;
// Fix modifiers for constant values by using any remaining arithmetic places to add an instruction to move the constant value to a temporary register
while (std::regex_search(SourceCode, std::regex("-c[0-9]|c[0-9][\\.wxyz]*_")) && ArithmeticCount < 8)
{
// Make sure that the dest register is not already being used
std::string tmpLine = "\n" + std::regex_replace(SourceCode, std::regex("1?-(c[0-9])[\\._a-z0-9]*|(c[0-9])[\\.wxyz]*_[a-z0-9]*"), "-$1$2") + "\n";
size_t start = tmpLine.substr(0, tmpLine.find("-c")).rfind("\n") + 1;
tmpLine = tmpLine.substr(start, tmpLine.find("\n", start) - start);
const std::string destReg = std::regex_replace(tmpLine, std::regex("[ \\+]+[a-z_\\.0-9]+ (r[0-9]).*-c[0-9].*"),"$1");
const std::string sourceReg = std::regex_replace(tmpLine, std::regex("[ \\+]+[a-z_\\.0-9]+ r[0-9][\\._a-z0-9]*, (.*)-c[0-9](.*)"), "$1$2");
if (sourceReg.find(destReg) != std::string::npos)
{
break;
}
// Replace one constant modifier using the dest register as a temporary register
size_t SourceSize = SourceCode.size();
SourceCode = std::regex_replace(SourceCode,
std::regex(" (...)(_[_satxd248]*|) (r[0-9])([\\.wxyz]*), (1?-?[crtv][0-9][\\.wxyz_abdis2]*, )?(1?-?[crtv][0-9][\\.wxyz_abdis2]*, )?(1?-?[crtv][0-9][\\.wxyz_abdis2]*, )?((1?-)(c[0-9])([\\.wxyz]*)(_bx2|_bias|_x2|_d[zbwa]|)|(1?-?)(c[0-9])([\\.wxyz]*)(_bx2|_bias|_x2|_d[zbwa]))(?![_\\.wxyz])"),
" mov $3$4, $10$11$14$15 /* added line */\n $1$2 $3$4, $5$6$9$13$3$12$16 /* changed $10$11$14$15 to $3 */", std::regex_constants::format_first_only);
// Replace one constant modifier on coissued commands using the dest register as a temporary register
if (SourceSize == SourceCode.size())
{
SourceCode = std::regex_replace(SourceCode,
std::regex("( .*\\n) \\+ (...)(_[_satxd248]*|) (r[0-9])([\\.wxyz]*), (1?-?[crtv][0-9][\\.wxyz_abdis2]*, )?(1?-?[crtv][0-9][\\.wxyz_abdis2]*, )?(1?-?[crtv][0-9][\\.wxyz_abdis2]*, )?((1?-)(c[0-9])([\\.wxyz]*)(_bx2|_bias|_x2|_d[zbwa]|)|(1?-?)(c[0-9])([\\.wxyz]*)(_bx2|_bias|_x2|_d[zbwa]))(?![_\\.wxyz])"),
" mov $4$5, $11$12$15$16 /* added line */\n$1 + $2$3 $4$5, $6$7$10$14$4$13$17 /* changed $11$12$15$16 to $4 */", std::regex_constants::format_first_only);
}
if (SourceSize == SourceCode.size())
{
break;
}
ArithmeticCount++;
}
// Check if this should be converted to ps_1_4
if (std::regex_search(SourceCode, std::regex("-c[0-9]|c[0-9][\\.wxyz]*_")) && // Check for modifiers on constants
!std::regex_search(SourceCode, std::regex("tex[bcdmr]")) && // Verify unsupported instructions are not used
std::regex_search(SourceCode, std::regex("ps_1_[0-3]"))) // Verify PixelShader is using version 1.0 to 1.3
{
bool ConvertError = false;
bool RegisterUsed[7] = { false };
RegisterUsed[6] = true;
struct MyStrings
{
std::string dest;
std::string source;
};
std::vector<MyStrings> ReplaceReg;
std::string NewSourceCode = " ps_1_4 /* converted */\n";
// Ensure at least one command will be above the phase marker
bool PhaseMarkerSet = (ArithmeticCount14 >= 8);
if (SourceCode14.find("def c") == std::string::npos && !PhaseMarkerSet)
{
for (size_t j = 0; j < 8; j++)
{
const std::string reg = "c" + std::to_string(j);
if (SourceCode14.find(reg) == std::string::npos)
{
PhaseMarkerSet = true;
NewSourceCode.append(" def " + reg + ", 0, 0, 0, 0 /* added line */\n");
break;
}
}
}
// Update registers to use different numbers from textures
size_t FirstReg = 0;
for (size_t j = 0; j < 2; j++)
{
const std::string reg = "r" + std::to_string(j);
if (SourceCode14.find(reg) != std::string::npos)
{
while (SourceCode14.find("t" + std::to_string(FirstReg)) != std::string::npos ||
(SourceCode14.find("r" + std::to_string(FirstReg)) != std::string::npos && j != FirstReg))
{
FirstReg++;
}
SourceCode14 = std::regex_replace(SourceCode14, std::regex(reg), "r" + std::to_string(FirstReg));
FirstReg++;
}
}
// Set phase location
size_t PhasePosition = NewSourceCode.length();
size_t TexturePosition = 0;
// Loop through each line
size_t LinePosition = 1;
std::string NewLine = SourceCode14;
while (true)
{
// Get next line
size_t tmpLinePos = SourceCode14.find("\n", LinePosition) + 1;
if (tmpLinePos == std::string::npos || tmpLinePos < LinePosition)
{
break;
}
LinePosition = tmpLinePos;
NewLine = SourceCode14.substr(LinePosition, SourceCode14.length());
tmpLinePos = NewLine.find("\n");
if (tmpLinePos != std::string::npos)
{
NewLine.resize(tmpLinePos);
}
// Skip 'ps_x_x' lines
if (std::regex_search(NewLine, std::regex("ps_._.")))
{
// Do nothing
}
// Check for 'def' and add before 'phase' statement
else if (NewLine.find("def c") != std::string::npos)
{
PhaseMarkerSet = true;
const std::string tmpLine = NewLine + "\n";
NewSourceCode.insert(PhasePosition, tmpLine);
PhasePosition += tmpLine.length();
}
// Check for 'tex' and update to 'texld'
else if (NewLine.find("tex t") != std::string::npos)
{
const std::string regNum = std::regex_replace(NewLine, std::regex(".*tex t([0-9]).*"), "$1");
const std::string tmpLine = " texld r" + regNum + ", t" + regNum + "\n";
// Mark as a texture register and add 'texld' statement before or after the 'phase' statement
const unsigned long Num = strtoul(regNum.c_str(), nullptr, 10);
RegisterUsed[(Num < 6) ? Num : 6] = true;
NewSourceCode.insert(PhasePosition, tmpLine);
if (PhaseMarkerSet)
{
TexturePosition += tmpLine.length();
}
else
{
PhaseMarkerSet = true;
PhasePosition += tmpLine.length();
}
}
// Other instructions
else
{
// Check for constant modifiers and update them to use unused temp register
if (std::regex_search(NewLine, std::regex("-c[0-9]|c[0-9][\\.wxyz]*_")))
{
for (size_t j = 0; j < 6; j++)
{
std::string reg = "r" + std::to_string(j);
if (NewSourceCode.find(reg) == std::string::npos)
{
const std::string constReg = std::regex_replace(NewLine, std::regex(".*-(c[0-9]).*|.*(c[0-9])[\\.wxyz]*_.*"), "$1$2");
// Check if this constant has modifiers in more than one line
if (std::regex_search(SourceCode14.substr(LinePosition + NewLine.length(), SourceCode14.length()), std::regex("-" + constReg + "|" + constReg + "[\\.wxyz]*_")))
{
// Find an unused register
while (j < 6 &&
(NewSourceCode.find("r" + std::to_string(j)) != std::string::npos ||
SourceCode14.find("r" + std::to_string(j)) != std::string::npos))
{
j++;
}
// Replace all constants with the unused register
if (j < 6)
{
reg = "r" + std::to_string(j);
SourceCode14 = std::regex_replace(SourceCode14, std::regex(constReg), reg);
}
}
const std::string tmpLine = " mov " + reg + ", " + constReg + "\n";
// Update the constant in this line and add 'mov' statement before or after the 'phase' statement
NewLine = std::regex_replace(NewLine, std::regex(constReg), reg);
if (ArithmeticCount14 < 8)
{
NewSourceCode.insert(PhasePosition + TexturePosition, tmpLine);
ArithmeticCount14++;
}
else
{
PhaseMarkerSet = true;
NewSourceCode.insert(PhasePosition, tmpLine);
PhasePosition += tmpLine.length();
}
break;
}
}
}
// Update register from vector once it is used for the last time
if (ReplaceReg.size() > 0)
{
for (size_t x = 0; x < ReplaceReg.size(); x++)
{
// Check if register is used in this line
if (NewLine.find(ReplaceReg[x].dest) != std::string::npos)
{
// Get position of all lines after this line
size_t start = LinePosition + NewLine.length();
// Move position to next line if the first line is a co-issed command
start = (SourceCode14.substr(start, 4).find("+") == std::string::npos) ? start : SourceCode14.find("\n", start + 1);
// Check if register is used in the code after this position
if (SourceCode14.find(ReplaceReg[x].dest, start) == std::string::npos)
{
// Update dest register using source register from the vector
NewLine = std::regex_replace(NewLine, std::regex("([ \\+]+[a-z_\\.0-9]+ )r[0-9](.*)"), "$1" + ReplaceReg[x].source + "$2");
ReplaceReg.erase(ReplaceReg.begin() + x);
break;
}
}
}
}
// Check if texture is no longer being used and update the dest register
if (std::regex_search(NewLine, std::regex("t[0-9]")))
{
const std::string texNum = std::regex_replace(NewLine, std::regex(".*t([0-9]).*"), "$1");
// Get position of all lines after this line
size_t start = LinePosition + NewLine.length();
// Move position to next line if the first line is a co-issed command
start = (SourceCode14.substr(start, 4).find("+") == std::string::npos) ? start : SourceCode14.find("\n", start + 1);
// Check if texture is used in the code after this position
if (SourceCode14.find("t" + texNum, start) == std::string::npos)
{
const std::string destRegNum = std::regex_replace(NewLine, std::regex("[ \\+]+[a-z_\\.0-9]+ r([0-9]).*"), "$1");
// Check if destination register is already being used by a texture register
const unsigned long Num = strtoul(destRegNum.c_str(), nullptr, 10);
if (!RegisterUsed[(Num < 6) ? Num : 6])
{
// Check if line is using more than one texture and error out
if (std::regex_search(std::regex_replace(NewLine, std::regex("t" + texNum), "r" + texNum), std::regex("t[0-9]")))
{
ConvertError = true;
break;
}
// Check if this is the first or last time the register is used
if (NewSourceCode.find("r" + destRegNum) == std::string::npos ||
SourceCode14.find("r" + destRegNum, start) == std::string::npos)
{
// Update dest register using texture register
NewLine = std::regex_replace(NewLine, std::regex("([ \\+]+[a-z_\\.0-9]+ )r[0-9](.*)"), "$1r" + texNum + "$2");
// Update code replacing all regsiters after the marked position with the texture register
const std::string tempSourceCode = std::regex_replace(SourceCode14.substr(start, SourceCode14.length()), std::regex("r" + destRegNum), "r" + texNum);
SourceCode14.resize(start);
SourceCode14.append(tempSourceCode);
}
else
{
// If register is still being used then add registers to vector to be replaced later
RegisterUsed[(Num < 6) ? Num : 6] = true;
MyStrings tempReplaceReg;
tempReplaceReg.dest = "r" + destRegNum;
tempReplaceReg.source = "r" + texNum;
ReplaceReg.push_back(tempReplaceReg);
}
}
}
}
// Add line to SourceCode
NewLine = std::regex_replace(NewLine, std::regex("t([0-9])"), "r$1") + "\n";
NewSourceCode.append(NewLine);
}
}
// Add 'phase' instruction
NewSourceCode.insert(PhasePosition, " phase\n");
// If no errors were encountered then check if code assembles
if (!ConvertError)
{
// Test if ps_1_4 assembles
if (SUCCEEDED(D3DXAssembleShader(NewSourceCode.data(), static_cast<UINT>(NewSourceCode.size()), nullptr, nullptr, 0, &Assembly, &ErrorBuffer)))
{
SourceCode = NewSourceCode;
}
else
{
#ifndef D3D8TO9NOLOG
LOG << "> Failed to convert shader to ps_1_4" << std::endl;
LOG << "> Dumping translated shader assembly:" << std::endl << std::endl << NewSourceCode << std::endl;
LOG << "> Failed to reassemble shader:" << std::endl << std::endl << static_cast<const char *>(ErrorBuffer->GetBufferPointer()) << std::endl;
#endif
}
}
}
// Change '-' modifier for constant values when using 'mad' arithmetic by changing it to use 'sub'
SourceCode = std::regex_replace(SourceCode,
std::regex("(mad)([_satxd248]*) (r[0-9][\\.wxyz]*), (1?-?[crtv][0-9][\\.wxyz_abdis2]*), (1?-?[crtv][0-9][\\.wxyz_abdis2]*), (-)(c[0-9][\\.wxyz]*)(_bx2|_bias|_x2|_d[zbwa]|)(?![_\\.wxyz])"),
"sub$2 $3, $4, $7$8 /* changed 'mad' to 'sub' removed $5 removed modifier $6 */");
// Remove trailing modifiers for constant values
SourceCode = std::regex_replace(SourceCode,
std::regex("(c[0-9][\\.wxyz]*)(_bx2|_bias|_x2|_d[zbwa])"),
"$1 /* removed modifier $2 */");
// Remove remaining modifiers for constant values
SourceCode = std::regex_replace(SourceCode,
std::regex("(1?-)(c[0-9][\\.wxyz]*(?![\\.wxyz]))"),
"$2 /* removed modifier $1 */");
#ifndef D3D8TO9NOLOG
LOG << "> Dumping translated shader assembly:" << std::endl << std::endl << SourceCode << std::endl;
#endif
if (D3DXAssembleShader != nullptr)
{
hr = D3DXAssembleShader(SourceCode.data(), static_cast<UINT>(SourceCode.size()), nullptr, nullptr, D3DXASM_FLAGS, &Assembly, &ErrorBuffer);
}
else
{
hr = D3DERR_INVALIDCALL;
}
Disassembly->Release();
if (FAILED(hr))
{
if (ErrorBuffer != nullptr)
{
#ifndef D3D8TO9NOLOG
LOG << "> Failed to reassemble shader:" << std::endl << std::endl << static_cast<const char *>(ErrorBuffer->GetBufferPointer()) << std::endl;
#endif
ErrorBuffer->Release();
}
else
{
#ifndef D3D8TO9NOLOG
LOG << "> Failed to reassemble shader with error code " << std::hex << hr << std::dec << "!" << std::endl;
#endif
}
return hr;
}
hr = ProxyInterface->CreatePixelShader(static_cast<const DWORD *>(Assembly->GetBufferPointer()), reinterpret_cast<IDirect3DPixelShader9 **>(pHandle));
if (FAILED(hr))
{
#ifndef D3D8TO9NOLOG
LOG << "> 'IDirect3DDevice9::CreatePixelShader' failed with error code " << std::hex << hr << std::dec << "!" << std::endl;
#endif
}
return hr;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::SetPixelShader(DWORD Handle)
{
CurrentPixelShaderHandle = Handle;
return ProxyInterface->SetPixelShader(reinterpret_cast<IDirect3DPixelShader9 *>(Handle));
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::GetPixelShader(DWORD *pHandle)
{
if (pHandle == nullptr)
{
return D3DERR_INVALIDCALL;
}
*pHandle = CurrentPixelShaderHandle;
return D3D_OK;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::DeletePixelShader(DWORD Handle)
{
if (Handle == 0)
{
return D3DERR_INVALIDCALL;
}
if (CurrentPixelShaderHandle == Handle)
{
SetPixelShader(0);
}
reinterpret_cast<IDirect3DPixelShader9 *>(Handle)->Release();
return D3D_OK;
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::SetPixelShaderConstant(DWORD Register, const void *pConstantData, DWORD ConstantCount)
{
return ProxyInterface->SetPixelShaderConstantF(Register, static_cast<const float *>(pConstantData), ConstantCount);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::GetPixelShaderConstant(DWORD Register, void *pConstantData, DWORD ConstantCount)
{
return ProxyInterface->GetPixelShaderConstantF(Register, static_cast<float *>(pConstantData), ConstantCount);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::GetPixelShaderFunction(DWORD Handle, void *pData, DWORD *pSizeOfData)
{
#ifndef D3D8TO9NOLOG
LOG << "Redirecting '" << "IDirect3DDevice8::GetPixelShaderFunction" << "(" << this << ", " << Handle << ", " << pData << ", " << pSizeOfData << ")' ..." << std::endl;
#endif
if (Handle == 0)
{
return D3DERR_INVALIDCALL;
}
IDirect3DPixelShader9 *const PixelShaderInterface = reinterpret_cast<IDirect3DPixelShader9 *>(Handle);
#ifndef D3D8TO9NOLOG
LOG << "> Returning translated shader byte code." << std::endl;
#endif
return PixelShaderInterface->GetFunction(pData, reinterpret_cast<UINT *>(pSizeOfData));
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::DrawRectPatch(UINT Handle, const float *pNumSegs, const D3DRECTPATCH_INFO *pRectPatchInfo)
{
return ProxyInterface->DrawRectPatch(Handle, pNumSegs, pRectPatchInfo);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::DrawTriPatch(UINT Handle, const float *pNumSegs, const D3DTRIPATCH_INFO *pTriPatchInfo)
{
return ProxyInterface->DrawTriPatch(Handle, pNumSegs, pTriPatchInfo);
}
HRESULT STDMETHODCALLTYPE Direct3DDevice8::DeletePatch(UINT Handle)
{
return ProxyInterface->DeletePatch(Handle);
}
void Direct3DDevice8::ApplyClipPlanes()
{
DWORD index = 0;
for (const auto clipPlane : StoredClipPlanes)
{
if ((ClipPlaneRenderState & (1 << index)) != 0)
{
ProxyInterface->SetClipPlane(index, clipPlane);
}
index++;
}
} | [
"elisha@novicemail.com"
] | elisha@novicemail.com |
02547823300519c88356eb0c0a03472751f74aef | 6fcdbb23b52acbd3c1f32c55308801f1067a6ac6 | /ProgramForClient/NewOnlineInstall/DUILIB/Demos/duidemo/SkinManager.h | 77f4ee8a21713ffdfb3886f25a8274728d34118e | [] | no_license | jyqiu1216/Rino | e507b70a2796cb356cd7ce90578981802ee5008c | eb8c110e7a551ee9bd736792a957a544c5ffdeb5 | refs/heads/master | 2020-04-13T21:41:26.474356 | 2017-05-19T07:39:42 | 2017-05-19T07:39:42 | 86,565,153 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,066 | h | #ifndef __SKIN_MANAGER_H__
#define __SKIN_MANAGER_H__
#include "..\..\DuiLib\UIlib.h"
struct SkinChangedParam
{
bool bColor;
DWORD bkcolor;
CDuiString bgimage;
};
typedef class ObserverImpl<BOOL, SkinChangedParam> SkinChangedObserver;
typedef class ReceiverImpl<BOOL, SkinChangedParam> SkinChangedReceiver;
class CSkinManager
{
public:
static CSkinManager* GetSkinManager()
{
if (m_pSkinManager == NULL)
{
m_pSkinManager = new CSkinManager();
}
return m_pSkinManager;
}
public:
void AddReceiver(ReceiverImpl<BOOL, SkinChangedParam>* receiver)
{
m_SkinChangeObserver.AddReceiver(receiver);
}
void RemoveReceiver(ReceiverImpl<BOOL, SkinChangedParam>* receiver)
{
m_SkinChangeObserver.RemoveReceiver(receiver);
}
void Broadcast(SkinChangedParam param)
{
m_SkinChangeObserver.Broadcast(param);
}
void Notify(SkinChangedParam param)
{
m_SkinChangeObserver.Notify(param);
}
private:
CSkinManager(){}
private:
SkinChangedObserver m_SkinChangeObserver;
static CSkinManager* m_pSkinManager;
};
#endif // __SKIN_MANAGER_H__ | [
"qiujy"
] | qiujy |
9dfc09288a8176e22aaa5cdfc53bce5bfc72071b | 9a3ec3eb5371a0e719b50bbf832a732e829b1ce4 | /GameOps/IslandPortal7.h | eb5b4cb6a04a2c1070d4273c764f11a38fcb9109 | [] | no_license | elestranobaron/T4C-Serveur-Multiplateformes | 5cb4dac8b8bd79bfd2bbd2be2da6914992fa7364 | f4a5ed21db1cd21415825cc0e72ddb57beee053e | refs/heads/master | 2022-10-01T20:13:36.217655 | 2022-09-22T02:43:33 | 2022-09-22T02:43:33 | 96,352,559 | 12 | 8 | null | null | null | null | UTF-8 | C++ | false | false | 331 | h | #include <NPCStructure.h>
#ifndef __ISLANDPORTAL7_H
#define __ISLANDPORTAL7_H
class IslandPortal7 : public NPCstructure{
public:
IslandPortal7();
~IslandPortal7();
void Create( void );
void OnTalk( UNIT_FUNC_PROTOTYPE );
void OnAttacked( UNIT_FUNC_PROTOTYPE );
void OnInitialise( UNIT_FUNC_PROTOTYPE );
};
#endif
| [
"lloancythomas@hotmail.co"
] | lloancythomas@hotmail.co |
3476552727f79e860fc2e317bee5af682f7a60e5 | b1098a2540fd27d05f33219e6bb2868cdda04c89 | /imperative/python/src/module_trace.cpp | 44cb72768b4c98b789541dc6b5f56535e053e23a | [
"LicenseRef-scancode-generic-cla",
"Apache-2.0"
] | permissive | chenjiahui0131/MegEngine | de5f96a8a855a7b2d324316e79ea071c34f8ab6a | 6579c984704767086d2721ba3ec3881a3ac24f83 | refs/heads/master | 2023-08-23T21:56:30.765344 | 2021-10-20T10:03:29 | 2021-10-20T10:03:29 | 400,480,179 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,355 | cpp | /**
* \file imperative/python/src/module_trace.cpp
* MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
*
* Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied.
*/
#include "./module_trace.h"
#include "./helper.h" // include op pybind11 caster
namespace py = pybind11;
namespace mgb::imperative::python {
apply_result_t apply_module_trace(ApplyContext& ctx) {
apply_result_t outputs;
auto args = py::tuple(ctx.nargs + 1);
args[0] = py::cast(ctx.op);
for (size_t i = 0; i < ctx.nargs; i++) {
args[i + 1] = TensorWrapper::make(ctx.args[i]->shared_from_this());
}
auto pyout = PyObject_Call(cpp_apply_module_trace, args.ptr(), nullptr);
if (!pyout) throw py::error_already_set();
auto ret = py::reinterpret_steal<py::object>(pyout);
// assumption: python function always returns PyList
auto tup = py::reinterpret_borrow<py::list>(ret);
for (auto i = 0; i < tup.size(); i++) {
auto tw = TensorWrapper::try_cast(tup[i].ptr());
outputs.emplace_back(tw->m_tensor);
}
return outputs;
}
} // namespace mgb::imperative::python
| [
"megengine@megvii.com"
] | megengine@megvii.com |
73f3f7177e37639629441fec3929bcb69b5fad6d | 6c9b803226601ed8e6fab9c1a9b5183c43a59f23 | /ConsoleApplication6/ConsoleApplication6.cpp | 8be3f3e4ee698a2b156962a2548b6d2417f2cfd8 | [] | no_license | happyDmac09/BMI-Calculator | 4da9571dd9ccbc0d5a644c7b84f8e690a9b44b73 | 80e8e2bfd36863875557d8dbac8272ee3472fba4 | refs/heads/master | 2021-04-28T18:49:37.691651 | 2018-02-17T18:04:09 | 2018-02-17T18:04:09 | 121,880,999 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 138 | cpp | // ConsoleApplication6.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
int main()
{
return 0;
}
| [
"35273499+happyDmac09@users.noreply.github.com"
] | 35273499+happyDmac09@users.noreply.github.com |
e3fcc856a282ec2a76ed85615796015f117baee3 | 72c4ecebf49a1239ab015e9b15a80319a0c27448 | /shooting/Object/Player.h | 10627cac41bf92afb0cb016562d1c753dd433681 | [] | no_license | NakagawaTenmaa/on-line_shooting | 256ddad54b95fc3fccff89d1c721e8a245b88a87 | b39534c511c8872ce7ba1eca6b567b40d3e257a8 | refs/heads/master | 2021-10-08T12:29:56.169844 | 2018-12-12T01:25:36 | 2018-12-12T01:25:36 | 160,271,683 | 0 | 0 | null | 2018-12-12T00:52:36 | 2018-12-04T00:22:34 | C++ | UTF-8 | C++ | false | false | 486 | h | #pragma once
#include <vector>
#include "Object.h"
#include "Bullet.h"
/// <summary>
/// プレイヤークラス
/// </summary>
class Player : public Object
{
public:
// コンストラクタ
Player();
// デストラクタ
~Player();
// 更新
bool Update();
// 描画
void Render();
// 力
int GetPower();
private:
// 弾の管理
std::vector<Bullet*> m_bullet;
static const int BULLET_SIZE;
int m_timer;
int m_power;
// 画像の状態
byte m_imageState;
}; | [
"tenko1177@gmail.com"
] | tenko1177@gmail.com |
16a2e2b98ffcb53921571a5d7146d8041c1b4fdd | ee37acbe7a5a4e7e5bda93ca236240f9d03943b7 | /src/ofApp.cpp | 1a057ff1ad79e8e4a6f36350bbead6e26153acc0 | [] | no_license | noseshape/dda_pubSubOsc_wekinator | c1a23e25b242cc948b2555c592b1eefb34264f0d | e3f1b3be44050747eaf286fac8554320f72201a9 | refs/heads/master | 2021-06-26T00:00:14.691187 | 2017-09-10T15:03:11 | 2017-09-10T15:03:11 | 103,038,381 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,596 | cpp | #include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup(){
ofSetFrameRate(60);
ofSetWindowShape(800, 600);
ofBackground(255, 255, 255);
//graph
col[0] = ofColor(255, 0, 0);
col[1] = ofColor(0, 255, 0);
col[2] = ofColor(0, 0, 255);
col[3] = ofColor(255, 255, 0);
pos = ofVec2f(700, 450);
graphScale = 300.0;
//gui
gui.setup();
gui.add(max.setup("Max", 1.00, 0.00, 1.50));
gui.add(min.setup("min", -0.10, -0.50, 1.00));
gui.add(bSerial.setup("serial", false));
gui.add(servoMin.setup("servoMin", 169, 0, 360));
gui.add(servoMax.setup("servoMax", 145, 0, 360));
angle = 0;
//arduino serial
serial.setup("/dev/cu.usbmodem1411",9600);
//receiver
receiver.setup(12000);
}
//--------------------------------------------------------------
void ofApp::update(){
ofSetWindowTitle(ofToString(ofGetFrameRate()));
//receiver
while(receiver.hasWaitingMessages()){
ofxOscMessage p;
receiver.getNextMessage(p);
for(int i=0;i<3;i++){
wekv[i]=p.getArgAsFloat(i);
cout<<ofToString(i)+": "+ofToString(wekv[i])<<endl;
}
}
//serial value adjusting
if(wekv[1] > min && wekv[1] < max){
angle = ofMap(wekv[1], min, max, servoMin, servoMax);
}
//serial value
if(bSerial && ofGetFrameNum()%12 == 0){
if(bSerial!=bbSerial){
serial.writeByte(255);
}else{
serial.writeByte(angle);
}
bbSerial = bSerial;
}
}
//--------------------------------------------------------------
void ofApp::draw(){
ofBackground(255, 255, 255);
//scale
ofSetColor(0, 0, 0);
ofDrawBitmapString("dda_valueControler", 10, 10);
//graph
ofPushMatrix();
ofTranslate(pos);
ofPushMatrix();
ofScale(ofVec2f(-1, -1)); //x:右→左, y:下→上
ofSetLineWidth(2);
for(int n = 0; n < stateNum; n++){
for(int i = 60*5-1; i > 0; i--){
pastValue[n][i] = pastValue[n][i-1];
}
pastValue[n][0] = wekv[n];
ofPolyline line;
for(int i = 0; i < 60*5; i++){
line.addVertex(ofVec2f(i, pastValue[n][i] * graphScale));
}
ofSetColor(col[n]);
line.draw();
}
ofSetColor(255, 120, 150);
ofDrawLine(0, max * graphScale, 60 * 5, max * graphScale);
ofSetColor(120, 255, 255);
ofDrawLine(0, min * graphScale, 60 * 5, min * graphScale);
ofSetColor(0, 0, 0);
ofSetLineWidth(1);
ofNoFill();
ofDrawRectangle(0, 0, 60*5, graphScale);
for(int i = 0; i <= 5; i++){
ofDrawLine(60*i, 0, 60*i, graphScale);
ofDrawBitmapString(ofToString(i) + 's', 60*i, -15);
}
ofPopMatrix();
ofPopMatrix();
//gui
gui.draw();
//receive
ofDrawBitmapString("receive", 10, 185);
for(int i = 0; i < stateNum; i++){
string log_state = "state" + ofToString(i) + ": " + ofToString(wekv[i]);
ofDrawBitmapString(log_state, 10, 200 + 30*i);
}
//send
ofDrawBitmapString("send", 10, 390);
ofDrawBitmapString("angle: " + ofToString(angle), 10, 400);
if(ofGetFrameNum() % 12 == 0){
}
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseEntered(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseExited(int x, int y){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
| [
"noseshape@gmail.com"
] | noseshape@gmail.com |
0db65adad7df12a718f3b6a687228d4206f03fab | 813284b9dac4477f4893cb6b30ffafab8e181cc4 | /src/qt/guiutil.h | 86da5e103545252cdfef249ce1c222c65e25a708 | [
"MIT"
] | permissive | phoenixkonsole/xbtx | 609809c29c32e2c4373a26204480a0e2a9f0922e | 2f9db3d0ca34103e315a5bc9ef2fa2d42cb71810 | refs/heads/master | 2023-05-11T17:37:28.762478 | 2023-05-03T09:54:14 | 2023-05-03T09:54:14 | 243,993,348 | 3 | 11 | MIT | 2023-05-03T09:54:15 | 2020-02-29T15:30:47 | C++ | UTF-8 | C++ | false | false | 9,818 | h | // Copyright (c) 2011-2016 The Bitcoin Core developers
// Copyright (c) 2017 The BitcoinSubsidium Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BitcoinSubsidium_QT_GUIUTIL_H
#define BitcoinSubsidium_QT_GUIUTIL_H
#include "amount.h"
#include "fs.h"
#include <QEvent>
#include <QHeaderView>
#include <QMessageBox>
#include <QObject>
#include <QProgressBar>
#include <QString>
#include <QTableView>
#include <QLabel>
class QValidatedLineEdit;
class SendCoinsRecipient;
QT_BEGIN_NAMESPACE
class QAbstractItemView;
class QDateTime;
class QFont;
class QLineEdit;
class QUrl;
class QWidget;
class QGraphicsDropShadowEffect;
QT_END_NAMESPACE
/** Utility functions used by the BitcoinSubsidium Qt UI.
*/
namespace GUIUtil
{
// Get the font for the sub labels
QFont getSubLabelFont();
QFont getSubLabelFontBolded();
// Get the font for the main labels
QFont getTopLabelFont();
QFont getTopLabelFontBolded();
QFont getTopLabelFont(int weight, int pxsize);
QGraphicsDropShadowEffect* getShadowEffect();
// Create human-readable string from date
QString dateTimeStr(const QDateTime &datetime);
QString dateTimeStr(qint64 nTime);
// Return a monospace font
QFont fixedPitchFont();
// Set up widgets for address and amounts
void setupAddressWidget(QValidatedLineEdit *widget, QWidget *parent);
void setupAmountWidget(QLineEdit *widget, QWidget *parent);
// Parse "BitcoinSubsidium:" URI into recipient object, return true on successful parsing
bool parseBitcoinSubsidiumURI(const QUrl &uri, SendCoinsRecipient *out);
bool parseBitcoinSubsidiumURI(QString uri, SendCoinsRecipient *out);
QString formatBitcoinSubsidiumURI(const SendCoinsRecipient &info);
// Returns true if given address+amount meets "dust" definition
bool isDust(const QString& address, const CAmount& amount);
// HTML escaping for rich text controls
QString HtmlEscape(const QString& str, bool fMultiLine=false);
QString HtmlEscape(const std::string& str, bool fMultiLine=false);
/** Copy a field of the currently selected entry of a view to the clipboard. Does nothing if nothing
is selected.
@param[in] column Data column to extract from the model
@param[in] role Data role to extract from the model
@see TransactionView::copyLabel, TransactionView::copyAmount, TransactionView::copyAddress
*/
void copyEntryData(QAbstractItemView *view, int column, int role=Qt::EditRole);
/** Return a field of the currently selected entry as a QString. Does nothing if nothing
is selected.
@param[in] column Data column to extract from the model
@see TransactionView::copyLabel, TransactionView::copyAmount, TransactionView::copyAddress
*/
QList<QModelIndex> getEntryData(QAbstractItemView *view, int column);
void setClipboard(const QString& str);
/** Get save filename, mimics QFileDialog::getSaveFileName, except that it appends a default suffix
when no suffix is provided by the user.
@param[in] parent Parent window (or 0)
@param[in] caption Window caption (or empty, for default)
@param[in] dir Starting directory (or empty, to default to documents directory)
@param[in] filter Filter specification such as "Comma Separated Files (*.csv)"
@param[out] selectedSuffixOut Pointer to return the suffix (file type) that was selected (or 0).
Can be useful when choosing the save file format based on suffix.
*/
QString getSaveFileName(QWidget *parent, const QString &caption, const QString &dir,
const QString &filter,
QString *selectedSuffixOut);
/** Get open filename, convenience wrapper for QFileDialog::getOpenFileName.
@param[in] parent Parent window (or 0)
@param[in] caption Window caption (or empty, for default)
@param[in] dir Starting directory (or empty, to default to documents directory)
@param[in] filter Filter specification such as "Comma Separated Files (*.csv)"
@param[out] selectedSuffixOut Pointer to return the suffix (file type) that was selected (or 0).
Can be useful when choosing the save file format based on suffix.
*/
QString getOpenFileName(QWidget *parent, const QString &caption, const QString &dir,
const QString &filter,
QString *selectedSuffixOut);
/** Get connection type to call object slot in GUI thread with invokeMethod. The call will be blocking.
@returns If called from the GUI thread, return a Qt::DirectConnection.
If called from another thread, return a Qt::BlockingQueuedConnection.
*/
Qt::ConnectionType blockingGUIThreadConnection();
// Determine whether a widget is hidden behind other windows
bool isObscured(QWidget *w);
// Open debug.log
void openDebugLogfile();
// Open the config file
bool openBitcoinSubsidiumConf();
// Replace invalid default fonts with known good ones
void SubstituteFonts(const QString& language);
// Concatenate a string given the painter, static text width, left side of rect, and right side of rect
// and which side the concatenated string is on (default left)
void concatenate(QPainter* painter, QString& strToCon, int static_width, int left_side, int right_size);
/** Qt event filter that intercepts ToolTipChange events, and replaces the tooltip with a rich text
representation if needed. This assures that Qt can word-wrap long tooltip messages.
Tooltips longer than the provided size threshold (in characters) are wrapped.
*/
class ToolTipToRichTextFilter : public QObject
{
Q_OBJECT
public:
explicit ToolTipToRichTextFilter(int size_threshold, QObject *parent = 0);
protected:
bool eventFilter(QObject *obj, QEvent *evt);
private:
int size_threshold;
};
/**
* Makes a QTableView last column feel as if it was being resized from its left border.
* Also makes sure the column widths are never larger than the table's viewport.
* In Qt, all columns are resizable from the right, but it's not intuitive resizing the last column from the right.
* Usually our second to last columns behave as if stretched, and when on strech mode, columns aren't resizable
* interactively or programmatically.
*
* This helper object takes care of this issue.
*
*/
class TableViewLastColumnResizingFixer: public QObject
{
Q_OBJECT
public:
TableViewLastColumnResizingFixer(QTableView* table, int lastColMinimumWidth, int allColsMinimumWidth, QObject *parent);
void stretchColumnWidth(int column);
private:
QTableView* tableView;
int lastColumnMinimumWidth;
int allColumnsMinimumWidth;
int lastColumnIndex;
int columnCount;
int secondToLastColumnIndex;
void adjustTableColumnsWidth();
int getAvailableWidthForColumn(int column);
int getColumnsWidth();
void connectViewHeadersSignals();
void disconnectViewHeadersSignals();
void setViewHeaderResizeMode(int logicalIndex, QHeaderView::ResizeMode resizeMode);
void resizeColumn(int nColumnIndex, int width);
private Q_SLOTS:
void on_sectionResized(int logicalIndex, int oldSize, int newSize);
void on_geometriesChanged();
};
bool GetStartOnSystemStartup();
bool SetStartOnSystemStartup(bool fAutoStart);
/* Convert QString to OS specific boost path through UTF-8 */
fs::path qstringToBoostPath(const QString &path);
/* Convert OS specific boost path to QString through UTF-8 */
QString boostPathToQString(const fs::path &path);
/* Convert seconds into a QString with days, hours, mins, secs */
QString formatDurationStr(int secs);
/* Format CNodeStats.nServices bitmask into a user-readable string */
QString formatServicesStr(quint64 mask);
/* Format a CNodeCombinedStats.dPingTime into a user-readable string or display N/A, if 0*/
QString formatPingTime(double dPingTime);
/* Format a CNodeCombinedStats.nTimeOffset into a user-readable string. */
QString formatTimeOffset(int64_t nTimeOffset);
QString formatNiceTimeOffset(qint64 secs);
QString formatBytes(uint64_t bytes);
class ClickableLabel : public QLabel
{
Q_OBJECT
Q_SIGNALS:
/** Emitted when the label is clicked. The relative mouse coordinates of the click are
* passed to the signal.
*/
void clicked(const QPoint& point);
protected:
void mouseReleaseEvent(QMouseEvent *event);
};
class ClickableProgressBar : public QProgressBar
{
Q_OBJECT
Q_SIGNALS:
/** Emitted when the progressbar is clicked. The relative mouse coordinates of the click are
* passed to the signal.
*/
void clicked(const QPoint& point);
protected:
void mouseReleaseEvent(QMouseEvent *event);
};
#if defined(Q_OS_MAC) && QT_VERSION >= 0x050000
// workaround for Qt OSX Bug:
// https://bugreports.qt-project.org/browse/QTBUG-15631
// QProgressBar uses around 10% CPU even when app is in background
class ProgressBar : public ClickableProgressBar
{
bool event(QEvent *e) {
return (e->type() != QEvent::StyleAnimationUpdate) ? QProgressBar::event(e) : false;
}
};
#else
typedef ClickableProgressBar ProgressBar;
#endif
} // namespace GUIUtil
#endif // BitcoinSubsidium_QT_GUIUTIL_H
| [
"william.kibbler@googlemail.com"
] | william.kibbler@googlemail.com |
bfc5408e8962bd74cb7f4e9308ce872e31fe2785 | 13a28512d570eabb27d40362bce194805f4ab266 | /Lab3/Src/Application/myMesh.h | 6960defe1b12ee7156f3064d38a10b25a96b1ed0 | [] | no_license | hmpbmp/CGLabs | c5116f04a7f84cba56f3f20e537cfb2b9d157ec3 | f7ccaa556cf3dba3c217444e392786a9b1b3be7a | refs/heads/master | 2020-05-20T03:53:42.042286 | 2014-12-19T22:00:02 | 2014-12-19T22:00:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 866 | h | #ifndef MY_MESH_INCLUDED
#define MY_MESH_INCLUDED
/**
@file myMesh.h
@brief User-defined mesh class definition
@date Created on 13/10/2014
@project D3DBase
@author Semyon Kozyrev
*/
// *******************************************************************
// includes
#include <windows.h>
#include <windowsx.h>
#include <d3dx9.h>
#include <stdlib.h>
// *******************************************************************
// defines & constants
// *******************************************************************
// classes
class MyMesh
{
public:
//Loading mesh from file
void load(char *filename, IDirect3DDevice9 *device);
//Rendering
void render(IDirect3DDevice9 *device);
//Release mesh and materials
void release();
private:
ID3DXMesh *mesh;
D3DMATERIAL9 *materials;
DWORD matNum = 0;
HRESULT meshLoadResult;
};
#endif | [
"ck-47@mail.ru"
] | ck-47@mail.ru |
de584f340dc73e14c0a831dad9ae96d3c30518b7 | 9df1684efcd7618f1dd46780274caacc1908433a | /infer/tests/codetoanalyze/cpp/nullable/example.cpp | 91e05a3614473f3f3899242915d1f8074498b7a7 | [
"MIT",
"GPL-1.0-or-later"
] | permissive | Abd-Elrazek/infer | a9f02c971c0c80e1d419bf51665e9570f6716174 | be4c5aaa0fc7cb2e259f1ad683c04c8cfa11875c | refs/heads/master | 2020-04-15T05:08:20.331302 | 2019-01-07T08:01:29 | 2019-01-07T08:04:32 | 164,410,091 | 1 | 0 | MIT | 2019-05-25T17:09:51 | 2019-01-07T09:38:22 | OCaml | UTF-8 | C++ | false | false | 1,395 | cpp | /*
* Copyright (c) 2017-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
class T {
private:
int* unnanotated_field;
int* _Nullable nullable_field;
int* _Nonnull nonnull_field;
public:
void assign_nullable_field_to_null_okay() { nullable_field = nullptr; }
public:
void assign_unnanotated_field_to_null_bad() { unnanotated_field = nullptr; }
public:
void assign_nonnull_field_to_null_bad() { nonnull_field = nullptr; }
public:
void test_nullable_field_for_null_okay() {
if (nullable_field == nullptr) {
}
}
public:
void test_unnanotated_field_for_null_bad() {
if (unnanotated_field == nullptr) {
}
}
public:
void test_nonnull_field_for_null_bad() {
if (nonnull_field == nullptr) {
}
}
public:
void dereference_unnanotated_field_okay() { *unnanotated_field = 42; }
public:
void dereference_nonnull_field_okay() { *nonnull_field = 42; }
public:
void dereference_nullable_field_bad() { *nullable_field = 42; }
public:
void dereference_unnanotated_field_after_test_for_null_bad() {
if (unnanotated_field == nullptr) {
*unnanotated_field = 42;
}
}
public:
void FP_dereference_nonnull_field_after_test_for_null_okay() {
if (nonnull_field == nullptr) {
*nonnull_field = 42;
}
}
};
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
43f3e829d5aa84f8e7cd2421ff564273a646ea6d | f252f75a66ff3ff35b6eaa5a4a28248eb54840ee | /external/opencore/oscl/oscl/config/android/osclconfig.h | 616cfe6eb66cd74ad70ec17eb4d3efa4aa20f7ff | [
"MIT",
"LicenseRef-scancode-other-permissive",
"Artistic-2.0",
"LicenseRef-scancode-philippe-de-muyter",
"Apache-2.0",
"LicenseRef-scancode-mpeg-iso",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | abgoyal-archive/OT_4010A | 201b246c6f685cf35632c9a1e1bf2b38011ff196 | 300ee9f800824658acfeb9447f46419b8c6e0d1c | refs/heads/master | 2022-04-12T23:17:32.814816 | 2015-02-06T12:15:20 | 2015-02-06T12:15:20 | 30,410,715 | 0 | 1 | null | 2020-03-07T00:35:22 | 2015-02-06T12:14:16 | C | UTF-8 | C++ | false | false | 1,849 | h |
// -*- c++ -*-
// = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
// O S C L C O N F I G ( P L A T F O R M C O N F I G I N F O )
// = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
#ifndef OSCLCONFIG_H_INCLUDED
#define OSCLCONFIG_H_INCLUDED
// system includes for dynamic registry
#include <dirent.h>
#include <dlfcn.h>
#define OSCL_HAS_ANDROID_SUPPORT 1
#define OSCL_HAS_ANDROID_FILE_IO_SUPPORT 1
#define OSCL_EXPORT_REF __attribute__ ((visibility("default")))
#define OSCL_IMPORT_REF __attribute__ ((visibility("default")))
// include common include for determining sizes from limits.h
#include "osclconfig_limits_typedefs.h"
//This switch turns off some profiling and debug settings
#ifdef NDEBUG
#define OSCL_RELEASE_BUILD 1
#else
#define OSCL_RELEASE_BUILD 0
#endif
// include common unix definitions
#include "osclconfig_unix_android.h"
// define the suffix for unsigned constants
#define OSCL_UNSIGNED_CONST(x) x##u
// override the common definition for
#undef OSCL_NATIVE_UINT64_TYPE
#define OSCL_NATIVE_UINT64_TYPE u_int64_t
// include the definitions for the processor
#include "osclconfig_ix86.h"
// the syntax for explicitly calling the destructor varies on some platforms
// below is the default syntax as defined by another ARM project
#define OSCL_TEMPLATED_DESTRUCTOR_CALL(type,simple_type) ~type ()
#define __TFS__ <>
#define OSCL_BEGIN_PACKED
#define OSCL_PACKED_VAR(x) x __attribute__((packed))
#define OSCL_PACKED_STRUCT_BEGIN
#define OSCL_PACKED_STRUCT_END __attribute__((packed))
#define OSCL_END_PACKED
#define PVLOGGER_INST_LEVEL 0
#define PVLOGGER_ANDROIDLOG_LEVEL 0
//set this to 1 to enable OSCL_ASSERT in release builds.
#define OSCL_ASSERT_ALWAYS 0
// check all osclconfig required macros are defined
#include "osclconfig_check.h"
#endif
| [
"abgoyal@gmail.com"
] | abgoyal@gmail.com |
1808c4ee11d3a8ed6c6c80c8a8babf18a9fbe968 | 3ad968797a01a4e4b9a87e2200eeb3fb47bf269a | /Ultimate TCP-IP/Security/Examples/Server/Echo/StdAfx.cpp | dbf537794d9fd92b4bad8962e53c976256a51ad4 | [] | no_license | LittleDrogon/MFC-Examples | 403641a1ae9b90e67fe242da3af6d9285698f10b | 1d8b5d19033409cd89da3aba3ec1695802c89a7a | refs/heads/main | 2023-03-20T22:53:02.590825 | 2020-12-31T09:56:37 | 2020-12-31T09:56:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 289 | cpp | // stdafx.cpp : source file that includes just the standard includes
// EchoServer.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| [
"pkedpekr@gmail.com"
] | pkedpekr@gmail.com |
5a4a49dacad3d582aaa587c417c14b4cc6a0330b | b88d8ff12b358236fb95b139f643e2e881695172 | /ABC/ABC161/a2.cpp | 8a479fed798e8434585b1a016765a038f1f58b8d | [] | no_license | Pikeruman-f18/C-_Practice | a7551a5fb55556da400305be4f3535ddce6a289b | 57c0dfbaf17afe7bb481f5761c06a56a5d084e38 | refs/heads/master | 2020-12-19T19:56:26.736532 | 2020-04-12T13:08:53 | 2020-04-12T13:08:53 | 235,836,037 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,196 | cpp | #include <bits/stdc++.h>
#define rep(i,n) for (int i = 0; i < (n); ++i)
using namespace std;
using ll = long long;
using P = pair<int,int>;
int main()
{
cin.tie(0);
ios::sync_with_stdio(false);
int n,m,a1;
vector<int> a;
cin>>n>>m;
if(m<1 || n<1)
{
return 0;
}
if(m>100 || n>100)
{
return 0;
}
for(int i=0; i<n; i++)
{
cin>>a1;
a.push_back(a1);
}
sort(a.begin(), a.end());
int goukei;
for(int i=0; i<n; i++)
{
goukei += a.at(i);
}
double goukei4;
goukei4 = goukei * ((double)(1 / (4*(double)m)));
int cnt=0;
for(int i=0; i<n; i++)
{
if(a.at(i) > goukei4)
{
cnt++;
}
}
/*cout<<"goukei:"<<goukei<<endl;
cout<<"goukei4:"<<goukei4<<endl;
cout<<"CNT:"<<cnt<<endl;
cout<<"N:"<<n<<endl;
cout<<"M:"<<m<<endl;
cout<<a.at(0)<<endl;*/
if(m==1 && a.at(n-1) >= goukei4)
{
cout<<"Yes"<<endl;
return 0;
}
else if (cnt>=m)
{
cout<<"Yes"<<endl;
return 0;
}
else
{
cout<<"No"<<endl;
return 0;
}
return 0;
} | [
"wataru.miyaji@gmail.com"
] | wataru.miyaji@gmail.com |
7419442508a500f232d865e2c1b51b43542b2203 | 2fd1b8e948e3afb85534c4e3ec73939cfc93b51c | /Analyzer/PPCoincMap.h | 85a6588e94a17f5d57f9a460ec8f6ed693b25cd5 | [] | no_license | jrtomps/phdwork | 0b6f7f7cccbbd0cffd969a9a445339f69528ae16 | 7fa546aa65e631c1a1922c143bcae43c9f4bff1c | refs/heads/master | 2020-12-24T07:35:31.384799 | 2016-10-29T02:15:05 | 2016-10-29T02:15:05 | 56,644,636 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,912 | h |
// PPCoincMap.h
//
// Author : Jeromy Tompkins
// Date : 7/13/2010
//
// Purpose: To implement a version of plot.C that runs PROOF
#ifndef PPCoincMap_h
#define PPCoincMap_h
#include <iostream>
#include <vector>
#include <utility>
#include "TH1.h"
#include "TH2.h"
#include "TCutG.h"
#include "ConfigManager.h"
#include "ConfigEntry.h"
#include "TBranch.h"
#include "TLine.h"
#include "TChain.h"
#include "TSelector.h"
/* class PPCoincMap; */
class PPCoincMap : public TSelector {
public:
std::vector<Float_t> fPed;
std::vector<Float_t> fThresh;
std::vector<Float_t> fLowCut;
std::vector<Float_t> fHighCut;
std::vector<Float_t> fLowCut2;
std::vector<Float_t> fHighCut2;
std::vector<Float_t> fLowCut3;
std::vector<Float_t> fHighCut3;
std::vector<Float_t> fLowTOFCut;
std::vector<Float_t> fHighTOFCut;
std::vector<Float_t> fPedThresh;
TTree *fChain; //!pointer to the analyzed TTree or TChain
Int_t runcount;
Int_t nentries;
ConfigManager cm;
ConfigEntry *pce;
Double_t bpmval;
Double_t tdcval;
Double_t bpm_calib;
Double_t desired_max_ph;
TH2D* coinc_map_aa;
TH2D* coinc_map_ff;
TH2D* coinc_map_fa;
TH2D* coinc_map_mult_a;
TH2D* coinc_map_mult_f;
TH1D* coinc_map_anota;
TH1D* coinc_map_fnota;
TH1D* coinc_mult_a;
TH1D* coinc_mult_f;
std::vector<Bool_t> adc_vals_a;
std::vector<Bool_t> adc_vals_f;
std::vector<Int_t> runnumber;
std::vector<Int_t> starttime;
std::vector<Int_t> endtime;
std::vector<Int_t> n_phys_events;
std::vector<Int_t> max_clock;
std::vector<Float_t> adc_edge;
// Declaration of leaf types
Int_t nt_evtype;
Double_t nt_bpm;
Int_t nt_evnum;
Int_t nt_run;
Double_t nt_trigger;
Double_t nt_clock;
Double_t VetoClock;
Double_t FinalClock;
Double_t FinalVetoClock;
std::vector<Double_t> nt_tdc;
std::vector<Double_t> nt_adc;
// Declaration of branches
TBranch* b_evnum; //!
TBranch* b_run; //!
TBranch* b_start; //!
TBranch* b_end; //!
TBranch* b_nphyev; //!
TBranch* b_evtype; //!
TBranch* b_latch; //!
TBranch* b_bpm; //!
TBranch* b_trigger; //!
std::vector<TBranch*> b_tdc;
std::vector<TBranch*> b_adc;
std::vector<TBranch*> b_tac;
PPCoincMap(ConfigEntry* ce, bool save=true);
PPCoincMap(PPCoincMap const& obj);
virtual ~PPCoincMap();
virtual Int_t Version() const { return 3;}
virtual void Begin(TTree *tree);
virtual void SlaveBegin(TTree *tree);
virtual void Init(TTree *tree);
virtual Bool_t Notify()
{
#ifdef DEBUG
std::cout << "notify" << std::endl;
#endif
return kTRUE;
}
virtual Bool_t Process(Long64_t entry);
virtual Int_t GetEntry(Long64_t entry, Int_t getall = 0)
{ return fChain ? fChain->GetTree()->GetEntry(entry, getall) : 0; }
virtual void SetOption(const char *option) { fOption = option; }
virtual void SetObject(TObject *obj) { fObject = obj; }
virtual void SetInputList(TList *input) { fInput = input; }
virtual TList* GetOutputList() const { return fOutput; }
virtual void SlaveTerminate();
virtual void Terminate();
void LoadSettings(ConfigEntry *dbentry);
UInt_t FindNonZeroBin(std::vector<Bool_t>& vec);
void SafeDeleteTH2D(TH2D* h);
void SafeDeleteTH1D(TH1D* h);
protected:
static const Char_t* outfname_base;
Bool_t willSave;
Int_t ndet;
Int_t nadc_ch;
Int_t ntdc_ch;
Int_t incr;
Int_t incr1;
UInt_t multiplicity_a;
UInt_t multiplicity_f;
UInt_t mult_mismatch;
private:
ClassDef(PPCoincMap,0);
};
#endif
| [
"tompkins@nscl.msu.edu"
] | tompkins@nscl.msu.edu |
003e7987e97b70b0f8113b92779af6b2e1710172 | 46ecae56f6d7e37b00fe2a9e676d62928fff343e | /code/log.cpp | 1d1207f80f3194873970016ff05b47a31d8f8e95 | [] | no_license | chuckrector/vccnow | 5da617ad5392b1f5b85bf604c4cc1471439e98b9 | 659568dcf08f1730268c3e9d5ee2d8f6d1d78da2 | refs/heads/master | 2022-11-11T08:07:12.167187 | 2020-06-28T19:10:33 | 2020-06-28T19:10:33 | 262,224,045 | 0 | 1 | null | 2020-06-28T19:10:35 | 2020-05-08T04:08:37 | C++ | UTF-8 | C++ | false | false | 524 | cpp | #include "log.hpp"
#include "types.hpp"
#include <stdarg.h>
void
Fail(char *Format, ...)
{
printf("FAIL\n");
va_list Args;
va_start(Args, Format);
vprintf(Format, Args);
va_end(Args);
*(int *)0 = 0;
// exit(-1);
}
void
Log(char *Format, ...)
{
va_list Args;
va_start(Args, Format);
vprintf(Format, Args);
va_end(Args);
}
void
DebugLog(DebugLevel_e Level, char *Format, ...)
{
if (Level > DebugLevel)
return;
va_list Args;
va_start(Args, Format);
vprintf(Format, Args);
va_end(Args);
}
| [
"choosetheforce@gmail.com"
] | choosetheforce@gmail.com |
a0125e07ce2e3323a4e762db9f8b98c7e1794aad | e30253dd5b8e508d37c680b34740add366f16c73 | /Libraries/xcassets/Sources/StickerDurationType.cpp | bc6a4851c46ea115bd1464e8baefb8c27fb0944d | [
"LicenseRef-scancode-philippe-de-muyter",
"BSD-3-Clause",
"NCSA",
"Zlib",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] | permissive | darlinghq/xcbuild | e77e8d88ed42f1922afd7abad2a4508c18255a88 | a903c6952fc5617816113cbb7b551ac701dba2ff | refs/heads/master | 2023-08-03T03:18:18.383673 | 2023-07-26T18:15:17 | 2023-07-26T18:15:17 | 131,655,910 | 10 | 2 | null | 2018-04-30T23:15:55 | 2018-04-30T23:15:54 | null | UTF-8 | C++ | false | false | 1,089 | cpp | /**
Copyright (c) 2015-present, Facebook, Inc.
All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree. An additional grant
of patent rights can be found in the PATENTS file in the same directory.
*/
#include <xcassets/StickerDurationType.h>
#include <cstdlib>
using xcassets::StickerDurationType;
using xcassets::StickerDurationTypes;
ext::optional<StickerDurationType> StickerDurationTypes::
Parse(std::string const &value)
{
if (value == "fixed") {
return StickerDurationType::Fixed;
} else if (value == "fps") {
return StickerDurationType::FPS;
} else {
fprintf(stderr, "warning: unknown sticker duration type %s\n", value.c_str());
return ext::nullopt;
}
}
std::string StickerDurationTypes::
String(StickerDurationType stickerDurationType)
{
switch (stickerDurationType) {
case StickerDurationType::Fixed:
return "fixed";
case StickerDurationType::FPS:
return "fps";
}
abort();
}
| [
"github@grantpaul.com"
] | github@grantpaul.com |
aaac4873959d0b3cee5a483ab3bb0139f7c746ab | 485d20ffb43ddced64d6508ea770c874325ed2ad | /current/sceneManager/src/testApp.h | 5dcda885439c680d309be7a1da94d86406cae0fa | [] | no_license | firmread/aynir | 16af463e26ad72e313814260b0accd1ff475df03 | d625f1a8b6785daee49951521cc192dc14311678 | refs/heads/master | 2021-01-24T23:36:00.262194 | 2013-05-13T01:49:38 | 2013-05-13T01:49:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 921 | h | #define SCENE_NUMBER 5
#pragma once
#include "ofMain.h"
#include "ofxiPhone.h"
#include "ofxiPhoneExtras.h"
#include "baseScene.h"
#include "openingScene.h"
#include "springScene.h"
//example scenes
#include "circleScene.h"
#include "squareScene.h"
#include "imageScene.h"
class testApp : public ofxiPhoneApp{
public:
void setup();
void update();
void draw();
void exit();
void touchDown(ofTouchEventArgs & touch);
void touchMoved(ofTouchEventArgs & touch);
void touchUp(ofTouchEventArgs & touch);
void touchDoubleTap(ofTouchEventArgs & touch);
void touchCancelled(ofTouchEventArgs & touch);
void lostFocus();
void gotFocus();
void gotMemoryWarning();
void deviceOrientationChanged(int newOrientation);
baseScene * scenes[SCENE_NUMBER];
int currentScene;
};
| [
"litchirhythm@gmail.com"
] | litchirhythm@gmail.com |
cae3a82e1c8b4a288e2b6e0d45dedd981bd9a457 | 6b8fff0eeb75ad266af0ec2b9e9aaf28462c2a73 | /Sapi_Dataset/Data/user13/labor9/feladat1/Worker.h | aef6e50fcc31bf87eecbfa24635428636aad4991 | [] | no_license | kotunde/SourceFileAnalyzer_featureSearch_and_classification | 030ab8e39dd79bcc029b38d68760c6366d425df5 | 9a3467e6aae5455142bc7a5805787f9b17112d17 | refs/heads/master | 2020-09-22T04:04:41.722623 | 2019-12-07T11:59:06 | 2019-12-07T11:59:06 | 225,040,703 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 300 | h | #pragma once
#ifndef WORKER_H
#define WORKER_H
#include <iostream>
#include <string>
#include "Szemely.h"
using namespace std;
class Worker:public Person {
protected:
string job;
public:
Worker(string fisrt,string last,int bDate,string job);
void print(ostream& out);
};
#endif | [
"tundekoncsard3566@gmail.com"
] | tundekoncsard3566@gmail.com |
af3037dbbcd012b90cb644281d16204cdceba83a | 9d0001b4035a61a31aba84de99966aa40adb4643 | /src/rtavis.cpp | 521db0cd5edb3082565719f2d59215f789112e03 | [
"MIT"
] | permissive | tiantianhan/rtavis | 4548833374cbea4c8cf0b8b792b0d5a1a762a17f | 325cbe22b28b98924cf8ff0dd6444e39bea1e17d | refs/heads/master | 2023-05-13T02:45:04.728165 | 2021-06-10T12:33:17 | 2021-06-10T12:33:17 | 285,031,941 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,403 | cpp | /**
* @file rtavis.cpp
* @author tina
* @brief Raytracer practice project based on the "Raytracing in One Weekend"
* series by Peter Shirley https://raytracing.github.io/
* @version 0.2
* @date 2021-05-30
*
* @copyright https://opensource.org/licenses/MIT
*
* Loads a file of sphere model information and render as ppm file.
*
*/
#include <iostream>
#include <fstream>
#include <cstring>
#include "..\tests\test.hpp"
#include "raytracer.hpp"
#include "utils\timer.hpp"
#include "io\load_obj.hpp"
// Inputs
struct main_inputs{
std::string in_file_path;
size_t image_width;
size_t image_height;
std::string out_file_path;
double aspect_ratio;
size_t samples_per_pixel;
size_t max_ray_recursion_depth;
};
// Defaults
const std::string default_input_file = "";
const std::string default_output_file = "rtavis_out.ppm";
const double default_aspect_ratio = 16.0 / 9.0;
const size_t default_samples_per_pixel = 3;
const size_t default_max_ray_recursion_depth = 10;
// Declarations
std::ostream& operator<<(std::ostream &out, const main_inputs& inputs);
bool parse_args(int argc, char *argv[], main_inputs& inputs);
void print_usage();
void set_default_args();
int main(int argc, char *argv[]){
// Parse inputs
main_inputs inputs;
bool is_success = parse_args(argc, argv, inputs);
if(!is_success){
print_usage();
std::cerr << "Error parsing arguments, exiting.\n";
return 1;
}
std::cout << "Got inputs: \n" << inputs << "\n\n";
// Output file
std::cout << "Opening output file...\n";
std::ofstream out_image;
out_image.open(inputs.out_file_path);
if(out_image.is_open() == false)
std::cout << "Failed to open output file " << inputs.out_file_path << "\n";
// Input file
std::cout << "Opening input file...\n";
std::ifstream in_file;
in_file.open(inputs.in_file_path);
if(in_file.is_open() == false)
std::cout << "Failed to open input file " << inputs.in_file_path << "\n";
// Setup raytracer
Raytracer raytracer(inputs.image_width, inputs.image_height);
raytracer.samples_per_pixel = inputs.samples_per_pixel;
raytracer.max_ray_recursion_depth = inputs.max_ray_recursion_depth;
// Load
if(in_file.is_open() == false){
raytracer.load_default_world();
} else {
raytracer.load(in_file);
}
// Render
Timer render_timer;
raytracer.render(out_image);
std::cout << "Render time: " << render_timer << "\n";
// Test // TODO: Write more tests?
//std::cout << "\nTesting load obj file...\n";
//tiny_obj_loader_test(inputs.in_file_path);
// test();
in_file.close();
out_image.close();
std::cout << "All done.\n";
return 0;
}
// Argument parsing helpers
std::ostream& operator<<(std::ostream &out, const main_inputs& inputs){
return out << "Input file path: " << inputs.in_file_path << "\n"
<< "Output file path: " << inputs.out_file_path << "\n"
<< "Image size: " << inputs.image_width << " x "
<< inputs.image_height << " "
<< "Aspect ratio: " << inputs.aspect_ratio << "\n"
<< "Samples per pixel: " << inputs.samples_per_pixel << "\n"
<< "Max recursion depth: " << inputs.max_ray_recursion_depth;
}
void print_usage(){
std::cerr << "Usage: rtavis image_width "
<< "[-i in_file_path]"
<< "[-o out_file_path]"
<< "[-spp samples_per_pixel] "
<< "[-depth max_ray_recursion_depth]\n";
}
void set_default_args(main_inputs &inputs){
inputs.in_file_path = default_input_file;
inputs.out_file_path = default_output_file;
std::cout << "Using default aspect ratio\n";
inputs.aspect_ratio = default_aspect_ratio;
inputs.image_height = round(inputs.image_width / inputs.aspect_ratio);
inputs.samples_per_pixel = default_samples_per_pixel;
inputs.max_ray_recursion_depth = default_max_ray_recursion_depth;
}
//Parse arguments. Returns true if successful and false if not successful.
bool parse_args(int argc, char *argv[], main_inputs& inputs){
const int opt_arg_start = 2;
const int total_arg = 10;
// Check number of arguments
if(argc < opt_arg_start || argc > total_arg){
return false;
}
// Arguments
int temp_width = atoi(argv[1]);
if(temp_width <= 0){
std::cerr << "Width should be an integer > 0\n";
return false;
}
inputs.image_width = temp_width;
// Defaults
set_default_args(inputs);
// Optional arguments
for(int i = opt_arg_start; i < argc; i+=2){
if((i + 1) >= argc) break;
if(strcmp(argv[i], "-i") == 0){
inputs.in_file_path = std::string(argv[i + 1]);
} else if(strcmp(argv[i], "-o") == 0){
inputs.out_file_path = std::string(argv[i + 1]);
} else if(strcmp(argv[i], "-spp") == 0){
int temp_smp = atoi(argv[i + 1]);
if(temp_smp <= 0){
std::cerr << "Samples per pixel should be an integer >= 1, using default.\n";
} else {
inputs.samples_per_pixel = temp_smp;
}
} else if(strcmp(argv[i], "-depth") == 0){
int temp_maxr = atoi(argv[i + 1]);
if(temp_maxr <= 0){
std::cerr << "Max recursion depth should be an integer >= 1, using default.\n";
} else {
inputs.max_ray_recursion_depth = temp_maxr;
}
} else {
std::cerr << argv[i] << " is not recognized flag\n";
return false;
}
}
return true;
} | [
"tina.han.tiantian@gmail.com"
] | tina.han.tiantian@gmail.com |
daf1417011111be6b2a039f0b99f0ba7f9433720 | d03d052c0ca220d06ec17d170e2b272f4e935a0c | /clang_x86/gen/mojo/public/interfaces/application/application_connector.mojom-common.h | e84aa0ab6f48de62010f3d876be6b8df74e738ec | [
"Apache-2.0"
] | permissive | amplab/ray-artifacts | f7ae0298fee371d9b33a40c00dae05c4442dc211 | 6954850f8ef581927df94be90313c1e783cd2e81 | refs/heads/master | 2023-07-07T20:45:43.526694 | 2016-08-06T19:53:55 | 2016-08-06T19:53:55 | 65,099,400 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 8,858 | h | // NOTE: This file was generated by the Mojo bindings generator.
#ifndef MOJO_PUBLIC_INTERFACES_APPLICATION_APPLICATION_CONNECTOR_MOJOM_COMMON_H_
#define MOJO_PUBLIC_INTERFACES_APPLICATION_APPLICATION_CONNECTOR_MOJOM_COMMON_H_
#include <stdint.h>
#include <iosfwd>
#include "mojo/public/cpp/bindings/array.h"
#include "mojo/public/cpp/bindings/callback.h"
#include "mojo/public/cpp/bindings/interface_handle.h"
#include "mojo/public/cpp/bindings/interface_request.h"
#include "mojo/public/cpp/bindings/map.h"
#include "mojo/public/cpp/bindings/message_validator.h"
#include "mojo/public/cpp/bindings/string.h"
#include "mojo/public/cpp/bindings/struct_ptr.h"
#include "mojo/public/cpp/system/buffer.h"
#include "mojo/public/cpp/system/data_pipe.h"
#include "mojo/public/cpp/system/handle.h"
#include "mojo/public/cpp/system/message_pipe.h"
#include "mojo/public/interfaces/application/application_connector.mojom-internal.h"
#include "mojo/public/interfaces/application/service_provider.mojom-common.h"
namespace mojo {
// --- Interface Forward Declarations ---
class ApplicationConnector;
class ApplicationConnectorRequestValidator;
class ApplicationConnector_Synchronous;
// --- Struct Forward Declarations ---
// --- Union Forward Declarations ---
// --- Enums Declarations ---
// --- Constants ---
// --- Interface declarations ---
namespace internal {
class ApplicationConnector_Base {
public:
static const uint32_t Version_ = 0;
using RequestValidator_ = ApplicationConnectorRequestValidator;
using ResponseValidator_ = mojo::internal::PassThroughValidator;
using Synchronous_ = ApplicationConnector_Synchronous;
enum class MessageOrdinals : uint32_t {
ConnectToApplication = 0,
Duplicate = 1,
};
virtual ~ApplicationConnector_Base() {}
};
} // namespace internal
// Async interface declaration
class ApplicationConnectorProxy;
class ApplicationConnectorStub;
class ApplicationConnector_Synchronous;
class ApplicationConnectorRequestValidator;
class ApplicationConnector : public internal::ApplicationConnector_Base {
public:
virtual ~ApplicationConnector() override {}
using Proxy_ = ApplicationConnectorProxy;
using Stub_ = ApplicationConnectorStub;
virtual void ConnectToApplication(const mojo::String& application_url, mojo::InterfaceRequest<mojo::ServiceProvider> services) = 0;
virtual void Duplicate(mojo::InterfaceRequest<ApplicationConnector> application_connector_request) = 0;
};
} // namespace mojo
// --- Internal Template Specializations ---
namespace mojo {
namespace internal {
} // internal
} // mojo
namespace mojo {
// --- Interface Request Validators ---
class ApplicationConnectorRequestValidator
: public mojo::internal::MessageValidator {
public:
mojo::internal::ValidationError Validate(const mojo::Message* message,
std::string* err) override;
};
// --- Interface Response Validators ---
// --- Interface enum operators ---
// --- Unions ---
// Unions must be declared first because they can be members of structs.
// --- Inlined structs ---
// --- Non-inlined structs ---
// --- Struct serialization helpers ---
// --- Union serialization helpers ---
// --- Request and response parameter structs for Interface methods ---
class ApplicationConnector_ConnectToApplication_Params;
using ApplicationConnector_ConnectToApplication_ParamsPtr = mojo::StructPtr<ApplicationConnector_ConnectToApplication_Params>;
size_t GetSerializedSize_(const ApplicationConnector_ConnectToApplication_Params& input);
mojo::internal::ValidationError Serialize_(
ApplicationConnector_ConnectToApplication_Params* input,
mojo::internal::Buffer* buffer,
internal::ApplicationConnector_ConnectToApplication_Params_Data** output);
void Deserialize_(internal::ApplicationConnector_ConnectToApplication_Params_Data* input,
ApplicationConnector_ConnectToApplication_Params* output);
class ApplicationConnector_ConnectToApplication_Params {
public:
using Data_ = internal::ApplicationConnector_ConnectToApplication_Params_Data;
static ApplicationConnector_ConnectToApplication_ParamsPtr New();
template <typename U>
static ApplicationConnector_ConnectToApplication_ParamsPtr From(const U& u) {
return mojo::TypeConverter<ApplicationConnector_ConnectToApplication_ParamsPtr, U>::Convert(u);
}
template <typename U>
U To() const {
return mojo::TypeConverter<U, ApplicationConnector_ConnectToApplication_Params>::Convert(*this);
}
ApplicationConnector_ConnectToApplication_Params();
~ApplicationConnector_ConnectToApplication_Params();
// Returns the number of bytes it would take to serialize this struct's data.
size_t GetSerializedSize() const;
// Returns true on successful serialization. On failure, part of the data may
// be serialized, until the point of failure. This API does not support
// serializing handles. If not null, |bytes_written| is set to the number of
// bytes written to |buf|, even if this function return false.
//
// TODO(vardhan): For now, we return true for success. Should we define a
// public error type for serialization? Should we open up
// internal::ValidationError?
bool Serialize(void* buf, size_t buf_size, size_t* bytes_written = nullptr);
// Deserializes the given |buf| of size |buf_size| representing a serialized
// version of this struct. The buffer is validated before it is deserialized.
// Returns true on successful deserialization.
// TODO(vardhan): Recover the validation error if there is one?
bool Deserialize(void* buf, size_t buf_size);
// Deserializes the given |buf| representing a serialized version of this
// struct. The buffer is NOT validated before it is deserialized, so the user
// must be confident of its validity and that |buf| points to enough data to
// finish deserializing.
void DeserializeWithoutValidation(void* buf);
bool Equals(const ApplicationConnector_ConnectToApplication_Params& other) const;
mojo::String application_url;
mojo::InterfaceRequest<mojo::ServiceProvider> services;
};
class ApplicationConnector_Duplicate_Params;
using ApplicationConnector_Duplicate_ParamsPtr = mojo::StructPtr<ApplicationConnector_Duplicate_Params>;
size_t GetSerializedSize_(const ApplicationConnector_Duplicate_Params& input);
mojo::internal::ValidationError Serialize_(
ApplicationConnector_Duplicate_Params* input,
mojo::internal::Buffer* buffer,
internal::ApplicationConnector_Duplicate_Params_Data** output);
void Deserialize_(internal::ApplicationConnector_Duplicate_Params_Data* input,
ApplicationConnector_Duplicate_Params* output);
class ApplicationConnector_Duplicate_Params {
public:
using Data_ = internal::ApplicationConnector_Duplicate_Params_Data;
static ApplicationConnector_Duplicate_ParamsPtr New();
template <typename U>
static ApplicationConnector_Duplicate_ParamsPtr From(const U& u) {
return mojo::TypeConverter<ApplicationConnector_Duplicate_ParamsPtr, U>::Convert(u);
}
template <typename U>
U To() const {
return mojo::TypeConverter<U, ApplicationConnector_Duplicate_Params>::Convert(*this);
}
ApplicationConnector_Duplicate_Params();
~ApplicationConnector_Duplicate_Params();
// Returns the number of bytes it would take to serialize this struct's data.
size_t GetSerializedSize() const;
// Returns true on successful serialization. On failure, part of the data may
// be serialized, until the point of failure. This API does not support
// serializing handles. If not null, |bytes_written| is set to the number of
// bytes written to |buf|, even if this function return false.
//
// TODO(vardhan): For now, we return true for success. Should we define a
// public error type for serialization? Should we open up
// internal::ValidationError?
bool Serialize(void* buf, size_t buf_size, size_t* bytes_written = nullptr);
// Deserializes the given |buf| of size |buf_size| representing a serialized
// version of this struct. The buffer is validated before it is deserialized.
// Returns true on successful deserialization.
// TODO(vardhan): Recover the validation error if there is one?
bool Deserialize(void* buf, size_t buf_size);
// Deserializes the given |buf| representing a serialized version of this
// struct. The buffer is NOT validated before it is deserialized, so the user
// must be confident of its validity and that |buf| points to enough data to
// finish deserializing.
void DeserializeWithoutValidation(void* buf);
bool Equals(const ApplicationConnector_Duplicate_Params& other) const;
mojo::InterfaceRequest<ApplicationConnector> application_connector_request;
};
} // namespace mojo
#endif // MOJO_PUBLIC_INTERFACES_APPLICATION_APPLICATION_CONNECTOR_MOJOM_COMMON_H_
| [
"pcmoritz@gmail.com"
] | pcmoritz@gmail.com |
62d0e73116f38e93e597a110a29904995a4f0370 | 037664902b196257640ab5fb30f9b4945f6230fa | /RTCCore/Network/network_request_plugin.cpp | 8356da15ef366cf4cf6a9f0c477e16bd4247d470 | [] | no_license | blockspacer/meeting_chat | e7e7c68ead1c7df7b8bd5698e8814e0bdaf65a68 | 2a406bcd5a02fa0003ffe4c9bc286dc5389c1adf | refs/heads/master | 2022-12-25T22:26:32.873374 | 2020-10-12T09:14:42 | 2020-10-12T09:14:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,248 | cpp | #include "network_request_plugin.h"
#include <assert.h>
#include "network_request_task.h"
#include <QDebug>
namespace core {
NetworkRequestPlugin::NetworkRequestPlugin()
{
_pendingTasks.insert(std::make_pair(RequestPriority::LOW, std::deque<std::shared_ptr<NetworkRequestTask>>()));
_pendingTasks.insert(std::make_pair(RequestPriority::NORMAL, std::deque<std::shared_ptr<NetworkRequestTask>>()));
_pendingTasks.insert(std::make_pair(RequestPriority::HIGH, std::deque<std::shared_ptr<NetworkRequestTask>>()));
_pendingTasks.insert(std::make_pair(RequestPriority::SEPECIFIC, std::deque<std::shared_ptr<NetworkRequestTask>>()));
}
NetworkRequestPlugin::~NetworkRequestPlugin()
{
}
void NetworkRequestPlugin::addRequestConsumer(RequestRoute route, const std::shared_ptr<INetworkRequestConsumer>& consumer)
{
_consumers[route] = consumer;
}
void NetworkRequestPlugin::cancelAll()
{
cancelAllPendingTasks();
cancelAllConsumers();
}
void NetworkRequestPlugin::cancelRequest(const std::shared_ptr<NetworkRequest>& request)
{
assert(request != nullptr);
request->setCancelled(true);
if (isRequestInPending(request)) {
//callXApiResponseCallback(NetworkFailType::CANCELLED, request);
} else {
for (auto iter = _consumers.begin(); iter != _consumers.end(); ++iter) {
(iter->second)->cancelRequest(request);
}
}
}
void NetworkRequestPlugin::appendTask(const std::shared_ptr<NetworkRequestTask>& task, bool isTail)
{
{
std::lock_guard<std::mutex> guard(_lock);
if (isTail) {
_pendingTasks[task->priority()].push_back(task);
} else {
_pendingTasks[task->priority()].push_front(task);
}
}
}
void NetworkRequestPlugin::addRequest(const std::shared_ptr<NetworkRequest>& request, bool isTail)
{
assert(request != nullptr);
auto task = std::make_shared<NetworkRequestTask>(request);
appendTask(task, isTail);
notifyRequestArrived(request->requestRoute());
}
std::string NetworkRequestPlugin::pluginName() const
{
return _pluginName;
}
void NetworkRequestPlugin::onNetworkStatusChanged(bool online)
{
}
const std::shared_ptr<NetworkRequest> NetworkRequestPlugin::produceRequest(RequestRoute route)
{
std::shared_ptr<NetworkRequestTask> result = nullptr;
qDebug() << "---------------------------- produceRequest ----------------------------";
{
std::lock_guard<std::mutex> guard(_lock);
for (int32_t index = (int32_t)RequestPriority::SEPECIFIC; index >= (int32_t)RequestPriority::LOW; --index) {
if (!canProduceRequest(static_cast<RequestPriority>(index))) {
break;
}
result = nextTaskInQueue(route, _pendingTasks[(RequestPriority)index]);
if (result) {
break;
}
}
if (result != nullptr) {
assert(result->request() != nullptr);
//changeTaskWeight(m_pendingTasks[ApiRequestPriority::NORMAL], m_pendingTasks[ApiRequestPriority::HIGH], kApiRequestHighWeight);
//changeTaskWeight(m_pendingTasks[ApiRequestPriority::LOW], m_pendingTasks[ApiRequestPriority::NORMAL], kApiRequestNormalWeight);
}
}
return result == nullptr ? nullptr : result->request();
}
// private
bool NetworkRequestPlugin::canProduceRequest(RequestPriority /*priority*/)
{
return true;
}
bool NetworkRequestPlugin::isConsumerAvailable(RequestRoute route)
{
bool isAvailable = true;
auto iter = _consumers.find(route);
if (iter != _consumers.end()) {
isAvailable = (iter->second)->isAvailiable();
}
return isAvailable;
}
bool NetworkRequestPlugin::canBeHandled(RequestRoute route, const std::shared_ptr<NetworkRequestTask>& task)
{
return (task->requestRoute() == route) || ((static_cast<int>(task->requestRoute() == route) != 0) && isConsumerAvailable(route));
}
std::shared_ptr<NetworkRequestTask> NetworkRequestPlugin::nextTaskInQueue(RequestRoute route,
std::deque<std::shared_ptr<NetworkRequestTask>>& queue)
{
auto iter = queue.begin();
while (iter != queue.end()) {
if (canBeHandled(route, (*iter))) {
auto task = *iter;
queue.erase(iter);
return task;
} else {
++iter;
}
}
return nullptr;
}
void NetworkRequestPlugin::notifyRequestArrived(RequestRoute route)
{
for (int32_t i = (int)RequestRoute::REQUEST_ROUTE_MAX; i >= (int)RequestRoute::HTTP; i >>= 1) {
auto iter = _consumers.find(RequestRoute(i));
if (iter != _consumers.end()) {
if ((iter->second)->canHandleRequest(route)) {
(iter->second)->onNetworkRequestArrived();
}
}
}
}
void NetworkRequestPlugin::cancelAllConsumers()
{
for (auto iter = _consumers.begin(); iter != _consumers.end(); ++iter) {
(iter->second)->cancelAll();
}
}
void NetworkRequestPlugin::cancelAllPendingTasks()
{
{
std::lock_guard<std::mutex> guard(_lock);
for (auto iter = _pendingTasks.begin(); iter != _pendingTasks.end(); ++iter) {
auto queue = iter->second;
for (auto queueIter = queue.begin(); queueIter != queue.end(); ++queueIter) {
auto task = *queueIter;
//callXApiResponseCallback(NetworkFailType::CANCELLED, task->request());
}
}
_pendingTasks.clear();
}
}
bool NetworkRequestPlugin::isRequestInPending(const std::shared_ptr<NetworkRequest>& request)
{
bool exist = false;
{
std::lock_guard<std::mutex> guard(_lock);
for (auto iter = _pendingTasks.begin(); iter != _pendingTasks.end(); ++iter) {
auto queue = iter->second;
for (auto queueIter = queue.begin(); queueIter != queue.end(); ++queueIter) {
auto task = *queueIter;
if (task->request()->requestId() == request->requestId()) {
exist = true;
break;
}
}
if (exist) {
break;
}
}
}
return exist;
}
}
| [
"jackie.ou@ringcentral.com"
] | jackie.ou@ringcentral.com |
c47cc29a6ae02a5b03b9e9ffa0fff38ab9f059bf | 19b4aea6c829b272ae29692ccc51f9ab8dcf573f | /src/winrt/impl/Windows.UI.Notifications.Management.2.h | 20032b7daeb18f2bf52ef5814e9421c8a7cb9575 | [
"MIT"
] | permissive | liquidboy/X | 9665573b6e30dff8912ab64a8daf08f9f3176628 | bf94a0af4dd06ab6c66027afdcda88eda0b4ae47 | refs/heads/master | 2022-12-10T17:41:15.490231 | 2021-12-07T01:31:38 | 2021-12-07T01:31:38 | 51,222,325 | 29 | 9 | null | 2021-08-04T21:30:44 | 2016-02-06T21:16:04 | C++ | UTF-8 | C++ | false | false | 665 | h | // C++/WinRT v1.0.170906.1
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
#pragma once
#include "winrt/impl/Windows.UI.Notifications.1.h"
#include "winrt/impl/Windows.UI.Notifications.Management.1.h"
WINRT_EXPORT namespace winrt::Windows::UI::Notifications::Management {
}
namespace winrt::impl {
}
WINRT_EXPORT namespace winrt::Windows::UI::Notifications::Management {
struct WINRT_EBO UserNotificationListener :
Windows::UI::Notifications::Management::IUserNotificationListener
{
UserNotificationListener(std::nullptr_t) noexcept {}
static Windows::UI::Notifications::Management::UserNotificationListener Current();
};
}
| [
"fajardo_jf@hotmail.com"
] | fajardo_jf@hotmail.com |
45e01e51701e536231d14282c06c58e362d39994 | 2b339e93f27f300983112fa8bd5bb3f58dcee51a | /source/scene/object/make.hpp | eaa99d85919878c64620ee0644172c7ebee8661e | [] | no_license | octopus-prime/gamma-ray-2 | caf11e2b2f2d349f2845233b1fa8ef163d8ce690 | 873fad52635b48875469ad4a28903a438e0a7bbe | refs/heads/master | 2021-01-10T05:47:58.255511 | 2017-12-22T17:57:14 | 2017-12-22T17:57:14 | 51,027,037 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 256 | hpp | /*
* make.hpp
*
* Created on: 22.02.2015
* Author: mike_gresens
*/
#pragma once
#include "description.hpp"
#include "instance.hpp"
namespace rt {
namespace scene {
namespace object {
instance_t
make(const description_t& description);
}
}
}
| [
"mike_gresens@notebook"
] | mike_gresens@notebook |
158ad381ec837f28fe07ac762b0849138d12073d | c8bca2e7cd5556382a7f00531c5f24dc7d5daf27 | /mainwindow.h | e2ce7b8ceddcb96b464dac367fe08fdc451abecc | [] | no_license | McVago/8Reinas | 46dc67e1af8c0b53d757847ad4014718c1b3cbbb | 92ef313f8d859275c83f4be723fd09efa8872876 | refs/heads/master | 2020-04-05T03:01:21.602546 | 2018-11-07T06:18:18 | 2018-11-07T06:18:18 | 156,498,576 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 735 | h | #ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QGraphicsScene>
#include <QGraphicsPixmapItem>
#include <QGraphicsView>
#include <QGraphicsRectItem>
#include <vector>
#include<bits/stdc++.h>
#define N 8
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
void generateboard();
private slots:
void on_pushButton_clicked();
private:
Ui::MainWindow *ui;
QGraphicsScene* scene;
QGraphicsPixmapItem* queen;
std::vector<QGraphicsPixmapItem*> queens;
std::vector<int> solutions;
int solutionNumber;
};
#endif // MAINWINDOW_H
| [
"andresmcvago@gmail.com"
] | andresmcvago@gmail.com |
94ca1011351879bb80485533d205d154f6805b81 | a2e319ef4342d753111d12c31ad209fbce0dbf6a | /cpp/lecture_08/04.cpp | e0cff71c67c5e56ff569cad664c7c64852a59e45 | [] | no_license | SylwiaBoniecka/nauka | a322798370e0ae0e454729d6fddc1707f871b411 | 08a5af95d8c31e952802b50c3be84069fc7b58cc | refs/heads/main | 2023-06-21T20:20:32.192456 | 2021-07-22T13:03:21 | 2021-07-22T13:03:21 | 329,991,934 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 222 | cpp | #include <iostream>
using namespace std;
int main()
{
int a = 7;
int *p = &a;
cout << "a = " << a << "\t address: " << &a << endl;
cout << "p = " << *p << "\t address: " << p << endl;
return 0;
} | [
"sylwia.boniecka@gmail.com"
] | sylwia.boniecka@gmail.com |
9b19c521481e32d73eebadfe55e9e60f5f0a31d6 | 6bc516189b66e17a9395ce676926ba74ea72f2f9 | /Competitive Programming 3/Chapter 2/1DArray/UVA755.cpp | 926c14b2755962014f5672bf6620abec6eb66e16 | [] | no_license | michaelzhiluo/UVA-Online-Judge | 1b1915af75e2f24b53715cfc4269631e289a78e0 | 1e653b79a3fa0f8161763899023c3ae2635ab328 | refs/heads/master | 2021-01-17T18:10:58.760890 | 2017-07-20T09:02:47 | 2017-07-20T09:02:47 | 71,186,964 | 2 | 1 | null | 2016-10-18T06:05:54 | 2016-10-17T22:35:42 | Java | UTF-8 | C++ | false | false | 1,638 | cpp | #include <iostream>
#include <bits/stdc++.h>
using namespace std;
string convertToString(char* c){
string answer = "";
for(int i=0; i<strlen(c); i++){
int x = (int)c[i];
if(x >= 48 && x<=57){
answer+=c[i];
}else if(x>=65 && x<= 67){
answer+='2';
}else if(x>=68 && x<= 70){
answer+='3';
}else if(x>=71 && x<= 73){
answer+='4';
}else if(x>=74 && x<= 76){
answer+='5';
}else if(x>=77 && x<= 79){
answer+='6';
}else if(x>=80 && x<= 83 && x!=81){
answer+='7';
}else if(x>=84 && x<= 86){
answer+='8';
}else if(x>=87 && x<= 89){
answer+='9';
}
}
return answer.substr(0, 3) + "-" + answer.substr(3);
}
bool pairCompare(pair<string, int>& firstElem, pair<string, int>& secondElem){
return firstElem.first < secondElem.first;
}
int main(){
int TC, length;
char c[1000];
scanf("%d", &TC);
map<string, int> phonenumber;
vector< pair<string, int> > answer;
loop:
while(TC--){
answer.clear();
phonenumber.clear();
scanf("%d\n", &length);
while(length--){
fgets(c, 1000, stdin);
string temp = convertToString(c);
if(phonenumber.find(temp) == phonenumber.end()){
phonenumber[temp] = 1;
}else{
phonenumber[temp]++;
}
}
for(map<string, int>::iterator i = phonenumber.begin(); i!= phonenumber.end(); i++){
if(i->second>1){
answer.push_back(make_pair(i->first, i->second));
}
}
sort(answer.begin(), answer.end(), pairCompare);
for(int i=0; i<answer.size(); i++){
printf("%s %d\n", answer[i].first.c_str(), answer[i].second);
}
if(answer.size() ==0){
printf("No duplicates.\n");
}
if(TC){
printf("\n");
}
}
return 0;
} | [
"michael.luo@berkeley.edu"
] | michael.luo@berkeley.edu |
88087f95de061577d20c091a403a36e25439d0ec | 3300d25038f1441eda24c902c28703f8f11469f3 | /asg4/code/protocol.h | b96785cd04fcbfba359dd1c4c5ab6a359161132f | [] | no_license | RishabJain27/Advanced-Programming | 129490108edaa70bce8890ff778bf65b164b6bd8 | dee76e68e5af0c92f4b5a199cfc658caaba6568e | refs/heads/master | 2020-09-20T02:38:24.436044 | 2019-11-27T06:22:52 | 2019-11-27T06:22:52 | 224,359,002 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 921 | h | //Rhea Lingaiah rlingaia
//Rishab Jain rjain9
#ifndef __PROTOCOL__H__
#define __PROTOCOL__H__
#include <cstdint>
#include <cstring>
#include <iostream>
using namespace std;
#include "sockets.h"
enum class cix_command : uint8_t {
ERROR = 0, EXIT, GET, HELP, LS, PUT, RM, FILEOUT, LSOUT, ACK, NAK,
};
constexpr size_t FILENAME_SIZE = 59;
constexpr size_t HEADER_SIZE = 64;
struct cix_header {
uint32_t nbytes {};
cix_command command {cix_command::ERROR};
char filename[FILENAME_SIZE] {};
};
void send_packet (base_socket& socket,
const void* buffer, size_t bufsize);
void recv_packet (base_socket& socket, void* buffer, size_t bufsize);
ostream& operator<< (ostream& out, const cix_header& header);
string get_cix_server_host (const vector<string>& args, size_t index);
in_port_t get_cix_server_port (const vector<string>& args,
size_t index);
#endif
| [
"rjain9@ucsc.edu"
] | rjain9@ucsc.edu |
7734e933e1d53b4df824c9485dea02fc78fe6368 | 0033659a033b4afac9b93c0ac80b8918a5ff9779 | /game/server/hl2/hl2_player.cpp | 0418912d710f678c8d6b94b9e83dcda5e07f28fc | [] | no_license | jonnyboy0719/situation-outbreak-two | d03151dc7a12a97094fffadacf4a8f7ee6ec7729 | 50037e27e738ff78115faea84e235f865c61a68f | refs/heads/master | 2021-01-10T09:59:39.214171 | 2011-01-11T01:15:33 | 2011-01-11T01:15:33 | 53,858,955 | 1 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 114,976 | cpp | //========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose: Player for HL2.
//
//=============================================================================//
#include "cbase.h"
#include "hl2_player.h"
#include "globalstate.h"
#include "game.h"
#include "gamerules.h"
#include "trains.h"
#include "basehlcombatweapon_shared.h"
#include "vcollide_parse.h"
#include "in_buttons.h"
#include "ai_interactions.h"
#include "ai_squad.h"
#include "igamemovement.h"
#include "ai_hull.h"
#include "hl2_shareddefs.h"
#include "info_camera_link.h"
#include "point_camera.h"
#include "engine/IEngineSound.h"
#include "ndebugoverlay.h"
#include "iservervehicle.h"
#include "IVehicle.h"
#include "globals.h"
#include "collisionutils.h"
#include "coordsize.h"
#include "effect_color_tables.h"
#include "vphysics/player_controller.h"
#include "player_pickup.h"
#include "weapon_physcannon.h"
#include "script_intro.h"
#include "effect_dispatch_data.h"
#include "te_effect_dispatch.h"
#include "ai_basenpc.h"
#include "AI_Criteria.h"
#include "npc_barnacle.h"
#include "entitylist.h"
#include "env_zoom.h"
#include "hl2_gamerules.h"
#include "prop_combine_ball.h"
#include "datacache/imdlcache.h"
#include "eventqueue.h"
#include "GameStats.h"
#include "filters.h"
#include "tier0/icommandline.h"
#ifdef HL2_EPISODIC
#include "npc_alyx_episodic.h"
#endif
/////
// SO2 - James
// Do not allow players to fire weapons while sprinting
// Base each player's speed on their health
#include "so_player.h"
/////
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
extern ConVar weapon_showproficiency;
extern ConVar autoaim_max_dist;
// Do not touch with without seeing me, please! (sjb)
// For consistency's sake, enemy gunfire is traced against a scaled down
// version of the player's hull, not the hitboxes for the player's model
// because the player isn't aware of his model, and can't do anything about
// preventing headshots and other such things. Also, game difficulty will
// not change if the model changes. This is the value by which to scale
// the X/Y of the player's hull to get the volume to trace bullets against.
#define PLAYER_HULL_REDUCTION 0.70
// This switches between the single primary weapon, and multiple weapons with buckets approach (jdw)
#define HL2_SINGLE_PRIMARY_WEAPON_MODE 0
#define TIME_IGNORE_FALL_DAMAGE 10.0
extern int gEvilImpulse101;
ConVar sv_autojump( "sv_autojump", "0" );
ConVar hl2_walkspeed( "hl2_walkspeed", "150" );
ConVar hl2_normspeed( "hl2_normspeed", "190" );
ConVar hl2_sprintspeed( "hl2_sprintspeed", "320" );
ConVar hl2_darkness_flashlight_factor ( "hl2_darkness_flashlight_factor", "1" );
#ifdef HL2MP
/////
// SO2 - James
// Base each player's speed on their health
/*#define HL2_WALK_SPEED 150
#define HL2_NORM_SPEED 190
#define HL2_SPRINT_SPEED 320*/
#define HL2_WALK_SPEED SO_WALK_SPEED
#define HL2_NORM_SPEED SO_NORM_SPEED
#define HL2_SPRINT_SPEED SO_SPRINT_SPEED
/////
#else
#define HL2_WALK_SPEED hl2_walkspeed.GetFloat()
#define HL2_NORM_SPEED hl2_normspeed.GetFloat()
#define HL2_SPRINT_SPEED hl2_sprintspeed.GetFloat()
#endif
ConVar player_showpredictedposition( "player_showpredictedposition", "0" );
ConVar player_showpredictedposition_timestep( "player_showpredictedposition_timestep", "1.0" );
ConVar player_squad_transient_commands( "player_squad_transient_commands", "1", FCVAR_REPLICATED );
ConVar player_squad_double_tap_time( "player_squad_double_tap_time", "0.25" );
ConVar sv_infinite_aux_power( "sv_infinite_aux_power", "0", FCVAR_CHEAT );
ConVar autoaim_unlock_target( "autoaim_unlock_target", "0.8666" );
ConVar sv_stickysprint("sv_stickysprint", "0", FCVAR_ARCHIVE | FCVAR_ARCHIVE_XBOX);
#define FLASH_DRAIN_TIME 1.1111 // 100 units / 90 secs
#define FLASH_CHARGE_TIME 50.0f // 100 units / 2 secs
//==============================================================================================
// CAPPED PLAYER PHYSICS DAMAGE TABLE
//==============================================================================================
static impactentry_t cappedPlayerLinearTable[] =
{
{ 150*150, 5 },
{ 250*250, 10 },
{ 450*450, 20 },
{ 550*550, 30 },
//{ 700*700, 100 },
//{ 1000*1000, 500 },
};
static impactentry_t cappedPlayerAngularTable[] =
{
{ 100*100, 10 },
{ 150*150, 20 },
{ 200*200, 30 },
//{ 300*300, 500 },
};
static impactdamagetable_t gCappedPlayerImpactDamageTable =
{
cappedPlayerLinearTable,
cappedPlayerAngularTable,
ARRAYSIZE(cappedPlayerLinearTable),
ARRAYSIZE(cappedPlayerAngularTable),
24*24.0f, // minimum linear speed
360*360.0f, // minimum angular speed
2.0f, // can't take damage from anything under 2kg
5.0f, // anything less than 5kg is "small"
5.0f, // never take more than 5 pts of damage from anything under 5kg
36*36.0f, // <5kg objects must go faster than 36 in/s to do damage
0.0f, // large mass in kg (no large mass effects)
1.0f, // large mass scale
2.0f, // large mass falling scale
320.0f, // min velocity for player speed to cause damage
};
// Flashlight utility
bool g_bCacheLegacyFlashlightStatus = true;
bool g_bUseLegacyFlashlight;
bool Flashlight_UseLegacyVersion( void )
{
// If this is the first run through, cache off what the answer should be (cannot change during a session)
if ( g_bCacheLegacyFlashlightStatus )
{
char modDir[MAX_PATH];
if ( UTIL_GetModDir( modDir, sizeof(modDir) ) == false )
return false;
g_bUseLegacyFlashlight = ( !Q_strcmp( modDir, "hl2" ) || !Q_strcmp( modDir, "episodic" ) );
g_bCacheLegacyFlashlightStatus = false;
}
// Return the results
return g_bUseLegacyFlashlight;
}
//-----------------------------------------------------------------------------
// Purpose: Used to relay outputs/inputs from the player to the world and viceversa
//-----------------------------------------------------------------------------
class CLogicPlayerProxy : public CLogicalEntity
{
DECLARE_CLASS( CLogicPlayerProxy, CLogicalEntity );
private:
DECLARE_DATADESC();
public:
COutputEvent m_OnFlashlightOn;
COutputEvent m_OnFlashlightOff;
COutputEvent m_PlayerHasAmmo;
COutputEvent m_PlayerHasNoAmmo;
COutputEvent m_PlayerDied;
COutputEvent m_PlayerMissedAR2AltFire; // Player fired a combine ball which did not dissolve any enemies.
COutputInt m_RequestedPlayerHealth;
void InputRequestPlayerHealth( inputdata_t &inputdata );
void InputSetFlashlightSlowDrain( inputdata_t &inputdata );
void InputSetFlashlightNormalDrain( inputdata_t &inputdata );
void InputSetPlayerHealth( inputdata_t &inputdata );
void InputRequestAmmoState( inputdata_t &inputdata );
void InputLowerWeapon( inputdata_t &inputdata );
void InputEnableCappedPhysicsDamage( inputdata_t &inputdata );
void InputDisableCappedPhysicsDamage( inputdata_t &inputdata );
void InputSetLocatorTargetEntity( inputdata_t &inputdata );
void Activate ( void );
bool PassesDamageFilter( const CTakeDamageInfo &info );
EHANDLE m_hPlayer;
};
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
void CC_ToggleZoom( void )
{
CBasePlayer* pPlayer = UTIL_GetCommandClient();
if( pPlayer )
{
CHL2_Player *pHL2Player = dynamic_cast<CHL2_Player*>(pPlayer);
if( pHL2Player && pHL2Player->IsSuitEquipped() )
{
pHL2Player->ToggleZoom();
}
}
}
static ConCommand toggle_zoom("toggle_zoom", CC_ToggleZoom, "Toggles zoom display" );
// ConVar cl_forwardspeed( "cl_forwardspeed", "400", FCVAR_CHEAT ); // Links us to the client's version
ConVar xc_crouch_range( "xc_crouch_range", "0.85", FCVAR_ARCHIVE, "Percentarge [1..0] of joystick range to allow ducking within" ); // Only 1/2 of the range is used
ConVar xc_use_crouch_limiter( "xc_use_crouch_limiter", "0", FCVAR_ARCHIVE, "Use the crouch limiting logic on the controller" );
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
void CC_ToggleDuck( void )
{
CBasePlayer* pPlayer = UTIL_GetCommandClient();
if ( pPlayer == NULL )
return;
// Cannot be frozen
if ( pPlayer->GetFlags() & FL_FROZEN )
return;
static bool bChecked = false;
static ConVar *pCVcl_forwardspeed = NULL;
if ( !bChecked )
{
bChecked = true;
pCVcl_forwardspeed = ( ConVar * )cvar->FindVar( "cl_forwardspeed" );
}
// If we're not ducked, do extra checking
if ( xc_use_crouch_limiter.GetBool() )
{
if ( pPlayer->GetToggledDuckState() == false )
{
float flForwardSpeed = 400.0f;
if ( pCVcl_forwardspeed )
{
flForwardSpeed = pCVcl_forwardspeed->GetFloat();
}
flForwardSpeed = max( 1.0f, flForwardSpeed );
// Make sure we're not in the blindspot on the crouch detection
float flStickDistPerc = ( pPlayer->GetStickDist() / flForwardSpeed ); // Speed is the magnitude
if ( flStickDistPerc > xc_crouch_range.GetFloat() )
return;
}
}
// Toggle the duck
pPlayer->ToggleDuck();
}
static ConCommand toggle_duck("toggle_duck", CC_ToggleDuck, "Toggles duck" );
#ifndef HL2MP
#ifndef PORTAL
LINK_ENTITY_TO_CLASS( player, CHL2_Player );
#endif
#endif
PRECACHE_REGISTER(player);
CBaseEntity *FindEntityForward( CBasePlayer *pMe, bool fHull );
BEGIN_SIMPLE_DATADESC( LadderMove_t )
DEFINE_FIELD( m_bForceLadderMove, FIELD_BOOLEAN ),
DEFINE_FIELD( m_bForceMount, FIELD_BOOLEAN ),
DEFINE_FIELD( m_flStartTime, FIELD_TIME ),
DEFINE_FIELD( m_flArrivalTime, FIELD_TIME ),
DEFINE_FIELD( m_vecGoalPosition, FIELD_POSITION_VECTOR ),
DEFINE_FIELD( m_vecStartPosition, FIELD_POSITION_VECTOR ),
DEFINE_FIELD( m_hForceLadder, FIELD_EHANDLE ),
DEFINE_FIELD( m_hReservedSpot, FIELD_EHANDLE ),
END_DATADESC()
// Global Savedata for HL2 player
BEGIN_DATADESC( CHL2_Player )
DEFINE_FIELD( m_nControlClass, FIELD_INTEGER ),
DEFINE_EMBEDDED( m_HL2Local ),
DEFINE_FIELD( m_bSprintEnabled, FIELD_BOOLEAN ),
DEFINE_FIELD( m_flTimeAllSuitDevicesOff, FIELD_TIME ),
DEFINE_FIELD( m_fIsSprinting, FIELD_BOOLEAN ),
DEFINE_FIELD( m_fIsWalking, FIELD_BOOLEAN ),
/*
// These are initialized every time the player calls Activate()
DEFINE_FIELD( m_bIsAutoSprinting, FIELD_BOOLEAN ),
DEFINE_FIELD( m_fAutoSprintMinTime, FIELD_TIME ),
*/
// Field is used within a single tick, no need to save restore
// DEFINE_FIELD( m_bPlayUseDenySound, FIELD_BOOLEAN ),
// m_pPlayerAISquad reacquired on load
DEFINE_AUTO_ARRAY( m_vecMissPositions, FIELD_POSITION_VECTOR ),
DEFINE_FIELD( m_nNumMissPositions, FIELD_INTEGER ),
// m_pPlayerAISquad
DEFINE_EMBEDDED( m_CommanderUpdateTimer ),
// m_RealTimeLastSquadCommand
DEFINE_FIELD( m_QueuedCommand, FIELD_INTEGER ),
DEFINE_FIELD( m_flTimeIgnoreFallDamage, FIELD_TIME ),
DEFINE_FIELD( m_bIgnoreFallDamageResetAfterImpact, FIELD_BOOLEAN ),
// Suit power fields
DEFINE_FIELD( m_flSuitPowerLoad, FIELD_FLOAT ),
DEFINE_FIELD( m_flIdleTime, FIELD_TIME ),
DEFINE_FIELD( m_flMoveTime, FIELD_TIME ),
DEFINE_FIELD( m_flLastDamageTime, FIELD_TIME ),
DEFINE_FIELD( m_flTargetFindTime, FIELD_TIME ),
DEFINE_FIELD( m_flAdmireGlovesAnimTime, FIELD_TIME ),
DEFINE_FIELD( m_flNextFlashlightCheckTime, FIELD_TIME ),
DEFINE_FIELD( m_flFlashlightPowerDrainScale, FIELD_FLOAT ),
DEFINE_FIELD( m_bFlashlightDisabled, FIELD_BOOLEAN ),
DEFINE_FIELD( m_bUseCappedPhysicsDamageTable, FIELD_BOOLEAN ),
DEFINE_FIELD( m_hLockedAutoAimEntity, FIELD_EHANDLE ),
DEFINE_EMBEDDED( m_LowerWeaponTimer ),
DEFINE_EMBEDDED( m_AutoaimTimer ),
DEFINE_INPUTFUNC( FIELD_FLOAT, "IgnoreFallDamage", InputIgnoreFallDamage ),
DEFINE_INPUTFUNC( FIELD_FLOAT, "IgnoreFallDamageWithoutReset", InputIgnoreFallDamageWithoutReset ),
DEFINE_INPUTFUNC( FIELD_VOID, "OnSquadMemberKilled", OnSquadMemberKilled ),
DEFINE_INPUTFUNC( FIELD_VOID, "DisableFlashlight", InputDisableFlashlight ),
DEFINE_INPUTFUNC( FIELD_VOID, "EnableFlashlight", InputEnableFlashlight ),
DEFINE_INPUTFUNC( FIELD_VOID, "ForceDropPhysObjects", InputForceDropPhysObjects ),
DEFINE_SOUNDPATCH( m_sndLeeches ),
DEFINE_SOUNDPATCH( m_sndWaterSplashes ),
DEFINE_FIELD( m_flArmorReductionTime, FIELD_TIME ),
DEFINE_FIELD( m_iArmorReductionFrom, FIELD_INTEGER ),
DEFINE_FIELD( m_flTimeUseSuspended, FIELD_TIME ),
DEFINE_FIELD( m_hLocatorTargetEntity, FIELD_EHANDLE ),
DEFINE_FIELD( m_flTimeNextLadderHint, FIELD_TIME ),
//DEFINE_FIELD( m_hPlayerProxy, FIELD_EHANDLE ), //Shut up class check!
END_DATADESC()
CHL2_Player::CHL2_Player()
{
m_nNumMissPositions = 0;
m_pPlayerAISquad = 0;
m_bSprintEnabled = true;
m_flArmorReductionTime = 0.0f;
m_iArmorReductionFrom = 0;
}
//
// SUIT POWER DEVICES
//
/////
// SO2 - James
// Change how quickly suit power (stamina) recharges
//#define SUITPOWER_CHARGE_RATE 12.5 // 100 units in 8 seconds
#define SUITPOWER_CHARGE_RATE 6.25 // 100 units in 16 seconds
/////
#ifdef HL2MP
CSuitPowerDevice SuitDeviceSprint( bits_SUIT_DEVICE_SPRINT, 25.0f ); // 100 units in 4 seconds
#else
CSuitPowerDevice SuitDeviceSprint( bits_SUIT_DEVICE_SPRINT, 12.5f ); // 100 units in 8 seconds
#endif
#ifdef HL2_EPISODIC
CSuitPowerDevice SuitDeviceFlashlight( bits_SUIT_DEVICE_FLASHLIGHT, 1.111 ); // 100 units in 90 second
#else
CSuitPowerDevice SuitDeviceFlashlight( bits_SUIT_DEVICE_FLASHLIGHT, 2.222 ); // 100 units in 45 second
#endif
CSuitPowerDevice SuitDeviceBreather( bits_SUIT_DEVICE_BREATHER, 6.7f ); // 100 units in 15 seconds (plus three padded seconds)
IMPLEMENT_SERVERCLASS_ST(CHL2_Player, DT_HL2_Player)
SendPropDataTable(SENDINFO_DT(m_HL2Local), &REFERENCE_SEND_TABLE(DT_HL2Local), SendProxy_SendLocalDataTable),
SendPropBool( SENDINFO(m_fIsSprinting) ),
END_SEND_TABLE()
void CHL2_Player::Precache( void )
{
BaseClass::Precache();
PrecacheScriptSound( "HL2Player.SprintNoPower" );
PrecacheScriptSound( "HL2Player.SprintStart" );
PrecacheScriptSound( "HL2Player.UseDeny" );
PrecacheScriptSound( "HL2Player.FlashLightOn" );
PrecacheScriptSound( "HL2Player.FlashLightOff" );
PrecacheScriptSound( "HL2Player.PickupWeapon" );
PrecacheScriptSound( "HL2Player.TrainUse" );
PrecacheScriptSound( "HL2Player.Use" );
PrecacheScriptSound( "HL2Player.BurnPain" );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CHL2_Player::CheckSuitZoom( void )
{
//#ifndef _XBOX
//Adrian - No zooming without a suit!
if ( IsSuitEquipped() )
{
if ( m_afButtonReleased & IN_ZOOM )
{
StopZooming();
}
else if ( m_afButtonPressed & IN_ZOOM )
{
StartZooming();
}
}
//#endif//_XBOX
}
void CHL2_Player::EquipSuit( bool bPlayEffects )
{
MDLCACHE_CRITICAL_SECTION();
BaseClass::EquipSuit();
m_HL2Local.m_bDisplayReticle = true;
if ( bPlayEffects == true )
{
StartAdmireGlovesAnimation();
}
}
void CHL2_Player::RemoveSuit( void )
{
BaseClass::RemoveSuit();
m_HL2Local.m_bDisplayReticle = false;
}
void CHL2_Player::HandleSpeedChanges( void )
{
int buttonsChanged = m_afButtonPressed | m_afButtonReleased;
bool bCanSprint = CanSprint();
bool bIsSprinting = IsSprinting();
bool bWantSprint = ( bCanSprint && IsSuitEquipped() && (m_nButtons & IN_SPEED) );
if ( bIsSprinting != bWantSprint && (buttonsChanged & IN_SPEED) )
{
// If someone wants to sprint, make sure they've pressed the button to do so. We want to prevent the
// case where a player can hold down the sprint key and burn tiny bursts of sprint as the suit recharges
// We want a full debounce of the key to resume sprinting after the suit is completely drained
if ( bWantSprint )
{
if ( sv_stickysprint.GetBool() )
{
StartAutoSprint();
}
else
{
StartSprinting();
}
}
else
{
if ( !sv_stickysprint.GetBool() )
{
StopSprinting();
}
// Reset key, so it will be activated post whatever is suppressing it.
m_nButtons &= ~IN_SPEED;
}
}
bool bIsWalking = IsWalking();
// have suit, pressing button, not sprinting or ducking
bool bWantWalking;
if( IsSuitEquipped() )
{
bWantWalking = (m_nButtons & IN_WALK) && !IsSprinting() && !(m_nButtons & IN_DUCK);
}
else
{
bWantWalking = true;
}
if( bIsWalking != bWantWalking )
{
if ( bWantWalking )
{
StartWalking();
}
else
{
StopWalking();
}
}
}
//-----------------------------------------------------------------------------
// This happens when we powerdown from the mega physcannon to the regular one
//-----------------------------------------------------------------------------
void CHL2_Player::HandleArmorReduction( void )
{
if ( m_flArmorReductionTime < gpGlobals->curtime )
return;
if ( ArmorValue() <= 0 )
return;
float flPercent = 1.0f - (( m_flArmorReductionTime - gpGlobals->curtime ) / ARMOR_DECAY_TIME );
int iArmor = Lerp( flPercent, m_iArmorReductionFrom, 0 );
SetArmorValue( iArmor );
}
//-----------------------------------------------------------------------------
// Purpose: Allow pre-frame adjustments on the player
//-----------------------------------------------------------------------------
void CHL2_Player::PreThink(void)
{
if ( player_showpredictedposition.GetBool() )
{
Vector predPos;
UTIL_PredictedPosition( this, player_showpredictedposition_timestep.GetFloat(), &predPos );
NDebugOverlay::Box( predPos, NAI_Hull::Mins( GetHullType() ), NAI_Hull::Maxs( GetHullType() ), 0, 255, 0, 0, 0.01f );
NDebugOverlay::Line( GetAbsOrigin(), predPos, 0, 255, 0, 0, 0.01f );
}
#ifdef HL2_EPISODIC
if( m_hLocatorTargetEntity != NULL )
{
// Keep track of the entity here, the client will pick up the rest of the work
m_HL2Local.m_vecLocatorOrigin = m_hLocatorTargetEntity->WorldSpaceCenter();
}
else
{
m_HL2Local.m_vecLocatorOrigin = vec3_invalid; // This tells the client we have no locator target.
}
#endif//HL2_EPISODIC
// Riding a vehicle?
if ( IsInAVehicle() )
{
VPROF( "CHL2_Player::PreThink-Vehicle" );
// make sure we update the client, check for timed damage and update suit even if we are in a vehicle
UpdateClientData();
CheckTimeBasedDamage();
// Allow the suit to recharge when in the vehicle.
SuitPower_Update();
CheckSuitUpdate();
CheckSuitZoom();
WaterMove();
return;
}
// This is an experiment of mine- autojumping!
// only affects you if sv_autojump is nonzero.
if( (GetFlags() & FL_ONGROUND) && sv_autojump.GetFloat() != 0 )
{
VPROF( "CHL2_Player::PreThink-Autojump" );
// check autojump
Vector vecCheckDir;
vecCheckDir = GetAbsVelocity();
float flVelocity = VectorNormalize( vecCheckDir );
if( flVelocity > 200 )
{
// Going fast enough to autojump
vecCheckDir = WorldSpaceCenter() + vecCheckDir * 34 - Vector( 0, 0, 16 );
trace_t tr;
UTIL_TraceHull( WorldSpaceCenter() - Vector( 0, 0, 16 ), vecCheckDir, NAI_Hull::Mins(HULL_TINY_CENTERED),NAI_Hull::Maxs(HULL_TINY_CENTERED), MASK_PLAYERSOLID, this, COLLISION_GROUP_PLAYER, &tr );
//NDebugOverlay::Line( tr.startpos, tr.endpos, 0,255,0, true, 10 );
if( tr.fraction == 1.0 && !tr.startsolid )
{
// Now trace down!
UTIL_TraceLine( vecCheckDir, vecCheckDir - Vector( 0, 0, 64 ), MASK_PLAYERSOLID, this, COLLISION_GROUP_NONE, &tr );
//NDebugOverlay::Line( tr.startpos, tr.endpos, 0,255,0, true, 10 );
if( tr.fraction == 1.0 && !tr.startsolid )
{
// !!!HACKHACK
// I KNOW, I KNOW, this is definitely not the right way to do this,
// but I'm prototyping! (sjb)
Vector vecNewVelocity = GetAbsVelocity();
vecNewVelocity.z += 250;
SetAbsVelocity( vecNewVelocity );
}
}
}
}
VPROF_SCOPE_BEGIN( "CHL2_Player::PreThink-Speed" );
HandleSpeedChanges();
#ifdef HL2_EPISODIC
HandleArmorReduction();
#endif
if( sv_stickysprint.GetBool() && m_bIsAutoSprinting )
{
// If we're ducked and not in the air
if( IsDucked() && GetGroundEntity() != NULL )
{
StopSprinting();
}
// Stop sprinting if the player lets off the stick for a moment.
else if( GetStickDist() == 0.0f )
{
if( gpGlobals->curtime > m_fAutoSprintMinTime )
{
StopSprinting();
}
}
else
{
// Stop sprinting one half second after the player stops inputting with the move stick.
m_fAutoSprintMinTime = gpGlobals->curtime + 0.5f;
}
}
else if ( IsSprinting() )
{
// Disable sprint while ducked unless we're in the air (jumping)
if ( IsDucked() && ( GetGroundEntity() != NULL ) )
{
StopSprinting();
}
}
VPROF_SCOPE_END();
if ( g_fGameOver || IsPlayerLockedInPlace() )
return; // finale
VPROF_SCOPE_BEGIN( "CHL2_Player::PreThink-ItemPreFrame" );
ItemPreFrame( );
VPROF_SCOPE_END();
VPROF_SCOPE_BEGIN( "CHL2_Player::PreThink-WaterMove" );
WaterMove();
VPROF_SCOPE_END();
if ( g_pGameRules && g_pGameRules->FAllowFlashlight() )
m_Local.m_iHideHUD &= ~HIDEHUD_FLASHLIGHT;
else
m_Local.m_iHideHUD |= HIDEHUD_FLASHLIGHT;
VPROF_SCOPE_BEGIN( "CHL2_Player::PreThink-CommanderUpdate" );
CommanderUpdate();
VPROF_SCOPE_END();
// Operate suit accessories and manage power consumption/charge
VPROF_SCOPE_BEGIN( "CHL2_Player::PreThink-SuitPower_Update" );
SuitPower_Update();
VPROF_SCOPE_END();
// checks if new client data (for HUD and view control) needs to be sent to the client
VPROF_SCOPE_BEGIN( "CHL2_Player::PreThink-UpdateClientData" );
UpdateClientData();
VPROF_SCOPE_END();
VPROF_SCOPE_BEGIN( "CHL2_Player::PreThink-CheckTimeBasedDamage" );
CheckTimeBasedDamage();
VPROF_SCOPE_END();
VPROF_SCOPE_BEGIN( "CHL2_Player::PreThink-CheckSuitUpdate" );
CheckSuitUpdate();
VPROF_SCOPE_END();
VPROF_SCOPE_BEGIN( "CHL2_Player::PreThink-CheckSuitZoom" );
CheckSuitZoom();
VPROF_SCOPE_END();
if (m_lifeState >= LIFE_DYING)
{
PlayerDeathThink();
return;
}
#ifdef HL2_EPISODIC
CheckFlashlight();
#endif // HL2_EPISODIC
// So the correct flags get sent to client asap.
//
if ( m_afPhysicsFlags & PFLAG_DIROVERRIDE )
AddFlag( FL_ONTRAIN );
else
RemoveFlag( FL_ONTRAIN );
// Train speed control
if ( m_afPhysicsFlags & PFLAG_DIROVERRIDE )
{
CBaseEntity *pTrain = GetGroundEntity();
float vel;
if ( pTrain )
{
if ( !(pTrain->ObjectCaps() & FCAP_DIRECTIONAL_USE) )
pTrain = NULL;
}
if ( !pTrain )
{
if ( GetActiveWeapon() && (GetActiveWeapon()->ObjectCaps() & FCAP_DIRECTIONAL_USE) )
{
m_iTrain = TRAIN_ACTIVE | TRAIN_NEW;
if ( m_nButtons & IN_FORWARD )
{
m_iTrain |= TRAIN_FAST;
}
else if ( m_nButtons & IN_BACK )
{
m_iTrain |= TRAIN_BACK;
}
else
{
m_iTrain |= TRAIN_NEUTRAL;
}
return;
}
else
{
trace_t trainTrace;
// Maybe this is on the other side of a level transition
UTIL_TraceLine( GetAbsOrigin(), GetAbsOrigin() + Vector(0,0,-38),
MASK_PLAYERSOLID_BRUSHONLY, this, COLLISION_GROUP_NONE, &trainTrace );
if ( trainTrace.fraction != 1.0 && trainTrace.m_pEnt )
pTrain = trainTrace.m_pEnt;
if ( !pTrain || !(pTrain->ObjectCaps() & FCAP_DIRECTIONAL_USE) || !pTrain->OnControls(this) )
{
// Warning( "In train mode with no train!\n" );
m_afPhysicsFlags &= ~PFLAG_DIROVERRIDE;
m_iTrain = TRAIN_NEW|TRAIN_OFF;
return;
}
}
}
else if ( !( GetFlags() & FL_ONGROUND ) || pTrain->HasSpawnFlags( SF_TRACKTRAIN_NOCONTROL ) || (m_nButtons & (IN_MOVELEFT|IN_MOVERIGHT) ) )
{
// Turn off the train if you jump, strafe, or the train controls go dead
m_afPhysicsFlags &= ~PFLAG_DIROVERRIDE;
m_iTrain = TRAIN_NEW|TRAIN_OFF;
return;
}
SetAbsVelocity( vec3_origin );
vel = 0;
if ( m_afButtonPressed & IN_FORWARD )
{
vel = 1;
pTrain->Use( this, this, USE_SET, (float)vel );
}
else if ( m_afButtonPressed & IN_BACK )
{
vel = -1;
pTrain->Use( this, this, USE_SET, (float)vel );
}
if (vel)
{
m_iTrain = TrainSpeed(pTrain->m_flSpeed, ((CFuncTrackTrain*)pTrain)->GetMaxSpeed());
m_iTrain |= TRAIN_ACTIVE|TRAIN_NEW;
}
}
else if (m_iTrain & TRAIN_ACTIVE)
{
m_iTrain = TRAIN_NEW; // turn off train
}
//
// If we're not on the ground, we're falling. Update our falling velocity.
//
if ( !( GetFlags() & FL_ONGROUND ) )
{
m_Local.m_flFallVelocity = -GetAbsVelocity().z;
}
if ( m_afPhysicsFlags & PFLAG_ONBARNACLE )
{
bool bOnBarnacle = false;
CNPC_Barnacle *pBarnacle = NULL;
do
{
// FIXME: Not a good or fast solution, but maybe it will catch the bug!
pBarnacle = (CNPC_Barnacle*)gEntList.FindEntityByClassname( pBarnacle, "npc_barnacle" );
if ( pBarnacle )
{
if ( pBarnacle->GetEnemy() == this )
{
bOnBarnacle = true;
}
}
} while ( pBarnacle );
if ( !bOnBarnacle )
{
Warning( "Attached to barnacle?\n" );
Assert( 0 );
m_afPhysicsFlags &= ~PFLAG_ONBARNACLE;
}
else
{
SetAbsVelocity( vec3_origin );
}
}
// StudioFrameAdvance( );//!!!HACKHACK!!! Can't be hit by traceline when not animating?
// Update weapon's ready status
UpdateWeaponPosture();
/////
// SO2 - James
// Disable suit zooming functionality
/*// Disallow shooting while zooming
if ( IsX360() )
{
if ( IsZooming() )
{
if( GetActiveWeapon() && !GetActiveWeapon()->IsWeaponZoomed() )
{
// If not zoomed because of the weapon itself, do not attack.
m_nButtons &= ~(IN_ATTACK|IN_ATTACK2);
}
}
}
else
{
if ( m_nButtons & IN_ZOOM )
{
//FIXME: Held weapons like the grenade get sad when this happens
#ifdef HL2_EPISODIC
// Episodic allows players to zoom while using a func_tank
CBaseCombatWeapon* pWep = GetActiveWeapon();
if ( !m_hUseEntity || ( pWep && pWep->IsWeaponVisible() ) )
#endif
m_nButtons &= ~(IN_ATTACK|IN_ATTACK2);
}
}*/
/////
}
void CHL2_Player::PostThink( void )
{
BaseClass::PostThink();
if ( !g_fGameOver && !IsPlayerLockedInPlace() && IsAlive() )
{
HandleAdmireGlovesAnimation();
}
}
void CHL2_Player::StartAdmireGlovesAnimation( void )
{
MDLCACHE_CRITICAL_SECTION();
CBaseViewModel *vm = GetViewModel( 0 );
if ( vm && !GetActiveWeapon() )
{
vm->SetWeaponModel( "models/weapons/v_hands.mdl", NULL );
ShowViewModel( true );
int idealSequence = vm->SelectWeightedSequence( ACT_VM_IDLE );
if ( idealSequence >= 0 )
{
vm->SendViewModelMatchingSequence( idealSequence );
m_flAdmireGlovesAnimTime = gpGlobals->curtime + vm->SequenceDuration( idealSequence );
}
}
}
void CHL2_Player::HandleAdmireGlovesAnimation( void )
{
CBaseViewModel *pVM = GetViewModel();
if ( pVM && pVM->GetOwningWeapon() == NULL )
{
if ( m_flAdmireGlovesAnimTime != 0.0 )
{
if ( m_flAdmireGlovesAnimTime > gpGlobals->curtime )
{
pVM->m_flPlaybackRate = 1.0f;
pVM->StudioFrameAdvance( );
}
else if ( m_flAdmireGlovesAnimTime < gpGlobals->curtime )
{
m_flAdmireGlovesAnimTime = 0.0f;
pVM->SetWeaponModel( NULL, NULL );
}
}
}
else
m_flAdmireGlovesAnimTime = 0.0f;
}
#define HL2PLAYER_RELOADGAME_ATTACK_DELAY 1.0f
void CHL2_Player::Activate( void )
{
BaseClass::Activate();
InitSprinting();
#ifdef HL2_EPISODIC
// Delay attacks by 1 second after loading a game.
if ( GetActiveWeapon() )
{
float flRemaining = GetActiveWeapon()->m_flNextPrimaryAttack - gpGlobals->curtime;
if ( flRemaining < HL2PLAYER_RELOADGAME_ATTACK_DELAY )
{
GetActiveWeapon()->m_flNextPrimaryAttack = gpGlobals->curtime + HL2PLAYER_RELOADGAME_ATTACK_DELAY;
}
flRemaining = GetActiveWeapon()->m_flNextSecondaryAttack - gpGlobals->curtime;
if ( flRemaining < HL2PLAYER_RELOADGAME_ATTACK_DELAY )
{
GetActiveWeapon()->m_flNextSecondaryAttack = gpGlobals->curtime + HL2PLAYER_RELOADGAME_ATTACK_DELAY;
}
}
#endif
GetPlayerProxy();
}
//------------------------------------------------------------------------------
// Purpose :
// Input :
// Output :
//------------------------------------------------------------------------------
Class_T CHL2_Player::Classify ( void )
{
// If player controlling another entity? If so, return this class
if (m_nControlClass != CLASS_NONE)
{
return m_nControlClass;
}
else
{
if(IsInAVehicle())
{
IServerVehicle *pVehicle = GetVehicle();
return pVehicle->ClassifyPassenger( this, CLASS_PLAYER );
}
else
{
return CLASS_PLAYER;
}
}
}
//-----------------------------------------------------------------------------
// Purpose: This is a generic function (to be implemented by sub-classes) to
// handle specific interactions between different types of characters
// (For example the barnacle grabbing an NPC)
// Input : Constant for the type of interaction
// Output : true - if sub-class has a response for the interaction
// false - if sub-class has no response
//-----------------------------------------------------------------------------
bool CHL2_Player::HandleInteraction(int interactionType, void *data, CBaseCombatCharacter* sourceEnt)
{
if ( interactionType == g_interactionBarnacleVictimDangle )
return false;
if (interactionType == g_interactionBarnacleVictimReleased)
{
m_afPhysicsFlags &= ~PFLAG_ONBARNACLE;
SetMoveType( MOVETYPE_WALK );
return true;
}
else if (interactionType == g_interactionBarnacleVictimGrab)
{
#ifdef HL2_EPISODIC
CNPC_Alyx *pAlyx = CNPC_Alyx::GetAlyx();
if ( pAlyx )
{
// Make Alyx totally hate this barnacle so that she saves the player.
int priority;
priority = pAlyx->IRelationPriority(sourceEnt);
pAlyx->AddEntityRelationship( sourceEnt, D_HT, priority + 5 );
}
#endif//HL2_EPISODIC
m_afPhysicsFlags |= PFLAG_ONBARNACLE;
ClearUseEntity();
return true;
}
return false;
}
void CHL2_Player::PlayerRunCommand(CUserCmd *ucmd, IMoveHelper *moveHelper)
{
// Handle FL_FROZEN.
if ( m_afPhysicsFlags & PFLAG_ONBARNACLE )
{
ucmd->forwardmove = 0;
ucmd->sidemove = 0;
ucmd->upmove = 0;
ucmd->buttons &= ~IN_USE;
}
// Can't use stuff while dead
if ( IsDead() )
{
ucmd->buttons &= ~IN_USE;
}
//Update our movement information
if ( ( ucmd->forwardmove != 0 ) || ( ucmd->sidemove != 0 ) || ( ucmd->upmove != 0 ) )
{
m_flIdleTime -= TICK_INTERVAL * 2.0f;
if ( m_flIdleTime < 0.0f )
{
m_flIdleTime = 0.0f;
}
m_flMoveTime += TICK_INTERVAL;
if ( m_flMoveTime > 4.0f )
{
m_flMoveTime = 4.0f;
}
}
else
{
m_flIdleTime += TICK_INTERVAL;
if ( m_flIdleTime > 4.0f )
{
m_flIdleTime = 4.0f;
}
m_flMoveTime -= TICK_INTERVAL * 2.0f;
if ( m_flMoveTime < 0.0f )
{
m_flMoveTime = 0.0f;
}
}
//Msg("Player time: [ACTIVE: %f]\t[IDLE: %f]\n", m_flMoveTime, m_flIdleTime );
BaseClass::PlayerRunCommand( ucmd, moveHelper );
}
//-----------------------------------------------------------------------------
// Purpose: Sets HL2 specific defaults.
//-----------------------------------------------------------------------------
void CHL2_Player::Spawn(void)
{
#ifndef HL2MP
#ifndef PORTAL
SetModel( "models/player.mdl" );
#endif
#endif
BaseClass::Spawn();
//
// Our player movement speed is set once here. This will override the cl_xxxx
// cvars unless they are set to be lower than this.
//
//m_flMaxspeed = 320;
if ( !IsSuitEquipped() )
StartWalking();
SuitPower_SetCharge( 100 );
m_Local.m_iHideHUD |= HIDEHUD_CHAT;
m_pPlayerAISquad = g_AI_SquadManager.FindCreateSquad(AllocPooledString(PLAYER_SQUADNAME));
InitSprinting();
// Setup our flashlight values
#ifdef HL2_EPISODIC
m_HL2Local.m_flFlashBattery = 100.0f;
#endif
GetPlayerProxy();
SetFlashlightPowerDrainScale( 1.0f );
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CHL2_Player::UpdateLocatorPosition( const Vector &vecPosition )
{
#ifdef HL2_EPISODIC
m_HL2Local.m_vecLocatorOrigin = vecPosition;
#endif//HL2_EPISODIC
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CHL2_Player::InitSprinting( void )
{
StopSprinting();
}
//-----------------------------------------------------------------------------
// Purpose: Returns whether or not we are allowed to sprint now.
//-----------------------------------------------------------------------------
bool CHL2_Player::CanSprint()
{
return ( m_bSprintEnabled && // Only if sprint is enabled
!IsWalking() && // Not if we're walking
!( m_Local.m_bDucked && !m_Local.m_bDucking ) && // Nor if we're ducking
(GetWaterLevel() != 3) && // Certainly not underwater
(GlobalEntity_GetState("suit_no_sprint") != GLOBAL_ON) ); // Out of the question without the sprint module
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CHL2_Player::StartAutoSprint()
{
if( IsSprinting() )
{
StopSprinting();
}
else
{
StartSprinting();
m_bIsAutoSprinting = true;
m_fAutoSprintMinTime = gpGlobals->curtime + 1.5f;
}
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CHL2_Player::StartSprinting( void )
{
if( m_HL2Local.m_flSuitPower < 10 )
{
// Don't sprint unless there's a reasonable
// amount of suit power.
// debounce the button for sound playing
if ( m_afButtonPressed & IN_SPEED )
{
CPASAttenuationFilter filter( this );
filter.UsePredictionRules();
EmitSound( filter, entindex(), "HL2Player.SprintNoPower" );
}
return;
}
if( !SuitPower_AddDevice( SuitDeviceSprint ) )
return;
CPASAttenuationFilter filter( this );
filter.UsePredictionRules();
EmitSound( filter, entindex(), "HL2Player.SprintStart" );
/////
// SO2 - James
// Do not allow players to fire weapons while sprinting
CSO_Player *pSOPlayer = ToSOPlayer( this );
if ( pSOPlayer )
{
pSOPlayer->SetHolsteredWeapon( pSOPlayer->GetActiveWeapon() );
CBaseCombatWeapon *pHolsteredWeapon = pSOPlayer->GetHolsteredWeapon();
if ( pHolsteredWeapon )
pHolsteredWeapon->Holster();
}
/////
SetMaxSpeed( HL2_SPRINT_SPEED );
m_fIsSprinting = true;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CHL2_Player::StopSprinting( void )
{
if ( m_HL2Local.m_bitsActiveDevices & SuitDeviceSprint.GetDeviceID() )
{
SuitPower_RemoveDevice( SuitDeviceSprint );
}
/////
// SO2 - James
// Do not allow players to fire weapons while sprinting
CSO_Player *pSOPlayer = ToSOPlayer( this );
if ( pSOPlayer )
{
CBaseCombatWeapon *pHolsteredWeapon = pSOPlayer->GetHolsteredWeapon();
if ( pHolsteredWeapon )
{
pHolsteredWeapon->Deploy();
pSOPlayer->SetHolsteredWeapon( NULL ); // weapon is no longer holstered; reset variable
}
}
/////
if( IsSuitEquipped() )
{
SetMaxSpeed( HL2_NORM_SPEED );
}
else
{
SetMaxSpeed( HL2_WALK_SPEED );
}
m_fIsSprinting = false;
if ( sv_stickysprint.GetBool() )
{
m_bIsAutoSprinting = false;
m_fAutoSprintMinTime = 0.0f;
}
}
//-----------------------------------------------------------------------------
// Purpose: Called to disable and enable sprint due to temporary circumstances:
// - Carrying a heavy object with the physcannon
//-----------------------------------------------------------------------------
void CHL2_Player::EnableSprint( bool bEnable )
{
if ( !bEnable && IsSprinting() )
{
StopSprinting();
}
m_bSprintEnabled = bEnable;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CHL2_Player::StartWalking( void )
{
SetMaxSpeed( HL2_WALK_SPEED );
m_fIsWalking = true;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CHL2_Player::StopWalking( void )
{
SetMaxSpeed( HL2_NORM_SPEED );
m_fIsWalking = false;
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CHL2_Player::CanZoom( CBaseEntity *pRequester )
{
if ( IsZooming() )
return false;
//Check our weapon
return true;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CHL2_Player::ToggleZoom(void)
{
if( IsZooming() )
{
StopZooming();
}
else
{
StartZooming();
}
}
//-----------------------------------------------------------------------------
// Purpose: +zoom suit zoom
//-----------------------------------------------------------------------------
void CHL2_Player::StartZooming( void )
{
/////
// SO2 - James
// Disable suit zooming functionality
/*int iFOV = 25;
if ( SetFOV( this, iFOV, 0.4f ) )
{
m_HL2Local.m_bZooming = true;
}*/
/////
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CHL2_Player::StopZooming( void )
{
/////
// SO2 - James
// Disable suit zooming functionality
/*int iFOV = GetZoomOwnerDesiredFOV( m_hZoomOwner );
if ( SetFOV( this, iFOV, 0.2f ) )
{
m_HL2Local.m_bZooming = false;
}*/
/////
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CHL2_Player::IsZooming( void )
{
if ( m_hZoomOwner != NULL )
return true;
return false;
}
class CPhysicsPlayerCallback : public IPhysicsPlayerControllerEvent
{
public:
int ShouldMoveTo( IPhysicsObject *pObject, const Vector &position )
{
CHL2_Player *pPlayer = (CHL2_Player *)pObject->GetGameData();
if ( pPlayer )
{
if ( pPlayer->TouchedPhysics() )
{
return 0;
}
}
return 1;
}
};
static CPhysicsPlayerCallback playerCallback;
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CHL2_Player::InitVCollision( const Vector &vecAbsOrigin, const Vector &vecAbsVelocity )
{
BaseClass::InitVCollision( vecAbsOrigin, vecAbsVelocity );
// Setup the HL2 specific callback.
IPhysicsPlayerController *pPlayerController = GetPhysicsController();
if ( pPlayerController )
{
pPlayerController->SetEventHandler( &playerCallback );
}
}
CHL2_Player::~CHL2_Player( void )
{
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
bool CHL2_Player::CommanderFindGoal( commandgoal_t *pGoal )
{
CAI_BaseNPC *pAllyNpc;
trace_t tr;
Vector vecTarget;
Vector forward;
EyeVectors( &forward );
//---------------------------------
// MASK_SHOT on purpose! So that you don't hit the invisible hulls of the NPCs.
CTraceFilterSkipTwoEntities filter( this, PhysCannonGetHeldEntity( GetActiveWeapon() ), COLLISION_GROUP_INTERACTIVE_DEBRIS );
UTIL_TraceLine( EyePosition(), EyePosition() + forward * MAX_COORD_RANGE, MASK_SHOT, &filter, &tr );
if( !tr.DidHitWorld() )
{
CUtlVector<CAI_BaseNPC *> Allies;
AISquadIter_t iter;
for ( pAllyNpc = m_pPlayerAISquad->GetFirstMember(&iter); pAllyNpc; pAllyNpc = m_pPlayerAISquad->GetNextMember(&iter) )
{
if ( pAllyNpc->IsCommandable() )
Allies.AddToTail( pAllyNpc );
}
for( int i = 0 ; i < Allies.Count() ; i++ )
{
if( Allies[ i ]->IsValidCommandTarget( tr.m_pEnt ) )
{
pGoal->m_pGoalEntity = tr.m_pEnt;
return true;
}
}
}
if( tr.fraction == 1.0 || (tr.surface.flags & SURF_SKY) )
{
// Move commands invalid against skybox.
pGoal->m_vecGoalLocation = tr.endpos;
return false;
}
if ( tr.m_pEnt->IsNPC() && ((CAI_BaseNPC *)(tr.m_pEnt))->IsCommandable() )
{
pGoal->m_vecGoalLocation = tr.m_pEnt->GetAbsOrigin();
}
else
{
vecTarget = tr.endpos;
Vector mins( -16, -16, 0 );
Vector maxs( 16, 16, 0 );
// Back up from whatever we hit so that there's enough space at the
// target location for a bounding box.
// Now trace down.
//UTIL_TraceLine( vecTarget, vecTarget - Vector( 0, 0, 8192 ), MASK_SOLID, this, COLLISION_GROUP_NONE, &tr );
UTIL_TraceHull( vecTarget + tr.plane.normal * 24,
vecTarget - Vector( 0, 0, 8192 ),
mins,
maxs,
MASK_SOLID_BRUSHONLY,
this,
COLLISION_GROUP_NONE,
&tr );
if ( !tr.startsolid )
pGoal->m_vecGoalLocation = tr.endpos;
else
pGoal->m_vecGoalLocation = vecTarget;
}
pAllyNpc = GetSquadCommandRepresentative();
if ( !pAllyNpc )
return false;
vecTarget = pGoal->m_vecGoalLocation;
if ( !pAllyNpc->FindNearestValidGoalPos( vecTarget, &pGoal->m_vecGoalLocation ) )
return false;
return ( ( vecTarget - pGoal->m_vecGoalLocation ).LengthSqr() < Square( 15*12 ) );
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
CAI_BaseNPC *CHL2_Player::GetSquadCommandRepresentative()
{
if ( m_pPlayerAISquad != NULL )
{
CAI_BaseNPC *pAllyNpc = m_pPlayerAISquad->GetFirstMember();
if ( pAllyNpc )
{
return pAllyNpc->GetSquadCommandRepresentative();
}
}
return NULL;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
int CHL2_Player::GetNumSquadCommandables()
{
AISquadIter_t iter;
int c = 0;
for ( CAI_BaseNPC *pAllyNpc = m_pPlayerAISquad->GetFirstMember(&iter); pAllyNpc; pAllyNpc = m_pPlayerAISquad->GetNextMember(&iter) )
{
if ( pAllyNpc->IsCommandable() )
c++;
}
return c;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
int CHL2_Player::GetNumSquadCommandableMedics()
{
AISquadIter_t iter;
int c = 0;
for ( CAI_BaseNPC *pAllyNpc = m_pPlayerAISquad->GetFirstMember(&iter); pAllyNpc; pAllyNpc = m_pPlayerAISquad->GetNextMember(&iter) )
{
if ( pAllyNpc->IsCommandable() && pAllyNpc->IsMedic() )
c++;
}
return c;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CHL2_Player::CommanderUpdate()
{
CAI_BaseNPC *pCommandRepresentative = GetSquadCommandRepresentative();
bool bFollowMode = false;
if ( pCommandRepresentative )
{
bFollowMode = ( pCommandRepresentative->GetCommandGoal() == vec3_invalid );
// set the variables for network transmission (to show on the hud)
m_HL2Local.m_iSquadMemberCount = GetNumSquadCommandables();
m_HL2Local.m_iSquadMedicCount = GetNumSquadCommandableMedics();
m_HL2Local.m_fSquadInFollowMode = bFollowMode;
// debugging code for displaying extra squad indicators
/*
char *pszMoving = "";
AISquadIter_t iter;
for ( CAI_BaseNPC *pAllyNpc = m_pPlayerAISquad->GetFirstMember(&iter); pAllyNpc; pAllyNpc = m_pPlayerAISquad->GetNextMember(&iter) )
{
if ( pAllyNpc->IsCommandMoving() )
{
pszMoving = "<-";
break;
}
}
NDebugOverlay::ScreenText(
0.932, 0.919,
CFmtStr( "%d|%c%s", GetNumSquadCommandables(), ( bFollowMode ) ? 'F' : 'S', pszMoving ),
255, 128, 0, 128,
0 );
*/
}
else
{
m_HL2Local.m_iSquadMemberCount = 0;
m_HL2Local.m_iSquadMedicCount = 0;
m_HL2Local.m_fSquadInFollowMode = true;
}
if ( m_QueuedCommand != CC_NONE && ( m_QueuedCommand == CC_FOLLOW || gpGlobals->realtime - m_RealTimeLastSquadCommand >= player_squad_double_tap_time.GetFloat() ) )
{
CommanderExecute( m_QueuedCommand );
m_QueuedCommand = CC_NONE;
}
else if ( !bFollowMode && pCommandRepresentative && m_CommanderUpdateTimer.Expired() && player_squad_transient_commands.GetBool() )
{
m_CommanderUpdateTimer.Set(2.5);
if ( pCommandRepresentative->ShouldAutoSummon() )
CommanderExecute( CC_FOLLOW );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//
// bHandled - indicates whether to continue delivering this order to
// all allies. Allows us to stop delivering certain types of orders once we find
// a suitable candidate. (like picking up a single weapon. We don't wish for
// all allies to respond and try to pick up one weapon).
//-----------------------------------------------------------------------------
bool CHL2_Player::CommanderExecuteOne( CAI_BaseNPC *pNpc, const commandgoal_t &goal, CAI_BaseNPC **Allies, int numAllies )
{
if ( goal.m_pGoalEntity )
{
return pNpc->TargetOrder( goal.m_pGoalEntity, Allies, numAllies );
}
else if ( pNpc->IsInPlayerSquad() )
{
pNpc->MoveOrder( goal.m_vecGoalLocation, Allies, numAllies );
}
return true;
}
//---------------------------------------------------------
//---------------------------------------------------------
void CHL2_Player::CommanderExecute( CommanderCommand_t command )
{
CAI_BaseNPC *pPlayerSquadLeader = GetSquadCommandRepresentative();
if ( !pPlayerSquadLeader )
{
EmitSound( "HL2Player.UseDeny" );
return;
}
int i;
CUtlVector<CAI_BaseNPC *> Allies;
commandgoal_t goal;
if ( command == CC_TOGGLE )
{
if ( pPlayerSquadLeader->GetCommandGoal() != vec3_invalid )
command = CC_FOLLOW;
else
command = CC_SEND;
}
else
{
if ( command == CC_FOLLOW && pPlayerSquadLeader->GetCommandGoal() == vec3_invalid )
return;
}
if ( command == CC_FOLLOW )
{
goal.m_pGoalEntity = this;
goal.m_vecGoalLocation = vec3_invalid;
}
else
{
goal.m_pGoalEntity = NULL;
goal.m_vecGoalLocation = vec3_invalid;
// Find a goal for ourselves.
if( !CommanderFindGoal( &goal ) )
{
EmitSound( "HL2Player.UseDeny" );
return; // just keep following
}
}
#ifdef _DEBUG
if( goal.m_pGoalEntity == NULL && goal.m_vecGoalLocation == vec3_invalid )
{
DevMsg( 1, "**ERROR: Someone sent an invalid goal to CommanderExecute!\n" );
}
#endif // _DEBUG
AISquadIter_t iter;
for ( CAI_BaseNPC *pAllyNpc = m_pPlayerAISquad->GetFirstMember(&iter); pAllyNpc; pAllyNpc = m_pPlayerAISquad->GetNextMember(&iter) )
{
if ( pAllyNpc->IsCommandable() )
Allies.AddToTail( pAllyNpc );
}
//---------------------------------
// If the trace hits an NPC, send all ally NPCs a "target" order. Always
// goes to targeted one first
#ifdef DEBUG
int nAIs = g_AI_Manager.NumAIs();
#endif
CAI_BaseNPC * pTargetNpc = (goal.m_pGoalEntity) ? goal.m_pGoalEntity->MyNPCPointer() : NULL;
bool bHandled = false;
if( pTargetNpc )
{
bHandled = !CommanderExecuteOne( pTargetNpc, goal, Allies.Base(), Allies.Count() );
}
for ( i = 0; !bHandled && i < Allies.Count(); i++ )
{
if ( Allies[i] != pTargetNpc && Allies[i]->IsPlayerAlly() )
{
bHandled = !CommanderExecuteOne( Allies[i], goal, Allies.Base(), Allies.Count() );
}
Assert( nAIs == g_AI_Manager.NumAIs() ); // not coded to support mutating set of NPCs
}
}
//-----------------------------------------------------------------------------
// Enter/exit commander mode, manage ally selection.
//-----------------------------------------------------------------------------
void CHL2_Player::CommanderMode()
{
float commandInterval = gpGlobals->realtime - m_RealTimeLastSquadCommand;
m_RealTimeLastSquadCommand = gpGlobals->realtime;
if ( commandInterval < player_squad_double_tap_time.GetFloat() )
{
m_QueuedCommand = CC_FOLLOW;
}
else
{
m_QueuedCommand = (player_squad_transient_commands.GetBool()) ? CC_SEND : CC_TOGGLE;
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : iImpulse -
//-----------------------------------------------------------------------------
void CHL2_Player::CheatImpulseCommands( int iImpulse )
{
switch( iImpulse )
{
case 50:
{
CommanderMode();
break;
}
case 51:
{
// Cheat to create a dynamic resupply item
Vector vecForward;
AngleVectors( EyeAngles(), &vecForward );
CBaseEntity *pItem = (CBaseEntity *)CreateEntityByName( "item_dynamic_resupply" );
if ( pItem )
{
Vector vecOrigin = GetAbsOrigin() + vecForward * 256 + Vector(0,0,64);
QAngle vecAngles( 0, GetAbsAngles().y - 90, 0 );
pItem->SetAbsOrigin( vecOrigin );
pItem->SetAbsAngles( vecAngles );
pItem->KeyValue( "targetname", "resupply" );
pItem->Spawn();
pItem->Activate();
}
break;
}
case 52:
{
// Rangefinder
trace_t tr;
UTIL_TraceLine( EyePosition(), EyePosition() + EyeDirection3D() * MAX_COORD_RANGE, MASK_SHOT, this, COLLISION_GROUP_NONE, &tr );
if( tr.fraction != 1.0 )
{
float flDist = (tr.startpos - tr.endpos).Length();
float flDist2D = (tr.startpos - tr.endpos).Length2D();
DevMsg( 1,"\nStartPos: %.4f %.4f %.4f --- EndPos: %.4f %.4f %.4f\n", tr.startpos.x,tr.startpos.y,tr.startpos.z,tr.endpos.x,tr.endpos.y,tr.endpos.z );
DevMsg( 1,"3D Distance: %.4f units (%.2f feet) --- 2D Distance: %.4f units (%.2f feet)\n", flDist, flDist / 12.0, flDist2D, flDist2D / 12.0 );
}
break;
}
default:
BaseClass::CheatImpulseCommands( iImpulse );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CHL2_Player::SetupVisibility( CBaseEntity *pViewEntity, unsigned char *pvs, int pvssize )
{
BaseClass::SetupVisibility( pViewEntity, pvs, pvssize );
int area = pViewEntity ? pViewEntity->NetworkProp()->AreaNum() : NetworkProp()->AreaNum();
PointCameraSetupVisibility( this, area, pvs, pvssize );
// If the intro script is playing, we want to get it's visibility points
if ( g_hIntroScript )
{
Vector vecOrigin;
CBaseEntity *pCamera;
if ( g_hIntroScript->GetIncludedPVSOrigin( &vecOrigin, &pCamera ) )
{
// If it's a point camera, turn it on
CPointCamera *pPointCamera = dynamic_cast< CPointCamera* >(pCamera);
if ( pPointCamera )
{
pPointCamera->SetActive( true );
}
engine->AddOriginToPVS( vecOrigin );
}
}
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CHL2_Player::SuitPower_Update( void )
{
if( SuitPower_ShouldRecharge() )
{
SuitPower_Charge( SUITPOWER_CHARGE_RATE * gpGlobals->frametime );
}
else if( m_HL2Local.m_bitsActiveDevices )
{
float flPowerLoad = m_flSuitPowerLoad;
//Since stickysprint quickly shuts off sprint if it isn't being used, this isn't an issue.
if ( !sv_stickysprint.GetBool() )
{
if( SuitPower_IsDeviceActive(SuitDeviceSprint) )
{
if( !fabs(GetAbsVelocity().x) && !fabs(GetAbsVelocity().y) )
{
// If player's not moving, don't drain sprint juice.
flPowerLoad -= SuitDeviceSprint.GetDeviceDrainRate();
}
}
}
if( SuitPower_IsDeviceActive(SuitDeviceFlashlight) )
{
float factor;
factor = 1.0f / m_flFlashlightPowerDrainScale;
flPowerLoad -= ( SuitDeviceFlashlight.GetDeviceDrainRate() * (1.0f - factor) );
}
if( !SuitPower_Drain( flPowerLoad * gpGlobals->frametime ) )
{
// TURN OFF ALL DEVICES!!
if( IsSprinting() )
{
StopSprinting();
}
if ( Flashlight_UseLegacyVersion() )
{
if( FlashlightIsOn() )
{
#ifndef HL2MP
FlashlightTurnOff();
#endif
}
}
}
if ( Flashlight_UseLegacyVersion() )
{
// turn off flashlight a little bit after it hits below one aux power notch (5%)
if( m_HL2Local.m_flSuitPower < 4.8f && FlashlightIsOn() )
{
#ifndef HL2MP
FlashlightTurnOff();
#endif
}
}
}
}
//-----------------------------------------------------------------------------
// Charge battery fully, turn off all devices.
//-----------------------------------------------------------------------------
void CHL2_Player::SuitPower_Initialize( void )
{
m_HL2Local.m_bitsActiveDevices = 0x00000000;
m_HL2Local.m_flSuitPower = 100.0;
m_flSuitPowerLoad = 0.0;
}
//-----------------------------------------------------------------------------
// Purpose: Interface to drain power from the suit's power supply.
// Input: Amount of charge to remove (expressed as percentage of full charge)
// Output: Returns TRUE if successful, FALSE if not enough power available.
//-----------------------------------------------------------------------------
bool CHL2_Player::SuitPower_Drain( float flPower )
{
// Suitpower cheat on?
if ( sv_infinite_aux_power.GetBool() )
return true;
m_HL2Local.m_flSuitPower -= flPower;
if( m_HL2Local.m_flSuitPower < 0.0 )
{
// Power is depleted!
// Clamp and fail
m_HL2Local.m_flSuitPower = 0.0;
return false;
}
return true;
}
//-----------------------------------------------------------------------------
// Purpose: Interface to add power to the suit's power supply
// Input: Amount of charge to add
//-----------------------------------------------------------------------------
void CHL2_Player::SuitPower_Charge( float flPower )
{
m_HL2Local.m_flSuitPower += flPower;
if( m_HL2Local.m_flSuitPower > 100.0 )
{
// Full charge, clamp.
m_HL2Local.m_flSuitPower = 100.0;
}
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
bool CHL2_Player::SuitPower_IsDeviceActive( const CSuitPowerDevice &device )
{
return (m_HL2Local.m_bitsActiveDevices & device.GetDeviceID()) != 0;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
bool CHL2_Player::SuitPower_AddDevice( const CSuitPowerDevice &device )
{
// Make sure this device is NOT active!!
if( m_HL2Local.m_bitsActiveDevices & device.GetDeviceID() )
return false;
if( !IsSuitEquipped() )
return false;
m_HL2Local.m_bitsActiveDevices |= device.GetDeviceID();
m_flSuitPowerLoad += device.GetDeviceDrainRate();
return true;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
bool CHL2_Player::SuitPower_RemoveDevice( const CSuitPowerDevice &device )
{
// Make sure this device is active!!
if( ! (m_HL2Local.m_bitsActiveDevices & device.GetDeviceID()) )
return false;
if( !IsSuitEquipped() )
return false;
// Take a little bit of suit power when you disable a device. If the device is shutting off
// because the battery is drained, no harm done, the battery charge cannot go below 0.
// This code in combination with the delay before the suit can start recharging are a defense
// against exploits where the player could rapidly tap sprint and never run out of power.
SuitPower_Drain( device.GetDeviceDrainRate() * 0.1f );
m_HL2Local.m_bitsActiveDevices &= ~device.GetDeviceID();
m_flSuitPowerLoad -= device.GetDeviceDrainRate();
if( m_HL2Local.m_bitsActiveDevices == 0x00000000 )
{
// With this device turned off, we can set this timer which tells us when the
// suit power system entered a no-load state.
m_flTimeAllSuitDevicesOff = gpGlobals->curtime;
}
return true;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
#define SUITPOWER_BEGIN_RECHARGE_DELAY 0.5f
bool CHL2_Player::SuitPower_ShouldRecharge( void )
{
// Make sure all devices are off.
if( m_HL2Local.m_bitsActiveDevices != 0x00000000 )
return false;
// Is the system fully charged?
if( m_HL2Local.m_flSuitPower >= 100.0f )
return false;
// Has the system been in a no-load state for long enough
// to begin recharging?
if( gpGlobals->curtime < m_flTimeAllSuitDevicesOff + SUITPOWER_BEGIN_RECHARGE_DELAY )
return false;
return true;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
ConVar sk_battery( "sk_battery","0" );
bool CHL2_Player::ApplyBattery( float powerMultiplier )
{
const float MAX_NORMAL_BATTERY = 100;
if ((ArmorValue() < MAX_NORMAL_BATTERY) && IsSuitEquipped())
{
int pct;
char szcharge[64];
IncrementArmorValue( sk_battery.GetFloat() * powerMultiplier, MAX_NORMAL_BATTERY );
CPASAttenuationFilter filter( this, "ItemBattery.Touch" );
EmitSound( filter, entindex(), "ItemBattery.Touch" );
CSingleUserRecipientFilter user( this );
user.MakeReliable();
UserMessageBegin( user, "ItemPickup" );
WRITE_STRING( "item_battery" );
MessageEnd();
// Suit reports new power level
// For some reason this wasn't working in release build -- round it.
pct = (int)( (float)(ArmorValue() * 100.0) * (1.0/MAX_NORMAL_BATTERY) + 0.5);
pct = (pct / 5);
if (pct > 0)
pct--;
Q_snprintf( szcharge,sizeof(szcharge),"!HEV_%1dP", pct );
//UTIL_EmitSoundSuit(edict(), szcharge);
//SetSuitUpdate(szcharge, FALSE, SUIT_NEXT_IN_30SEC);
return true;
}
return false;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
int CHL2_Player::FlashlightIsOn( void )
{
return IsEffectActive( EF_DIMLIGHT );
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CHL2_Player::FlashlightTurnOn( void )
{
if( m_bFlashlightDisabled )
return;
if ( Flashlight_UseLegacyVersion() )
{
if( !SuitPower_AddDevice( SuitDeviceFlashlight ) )
return;
}
#ifdef HL2_DLL
if( !IsSuitEquipped() )
return;
#endif
AddEffects( EF_DIMLIGHT );
EmitSound( "HL2Player.FlashLightOn" );
variant_t flashlighton;
flashlighton.SetFloat( m_HL2Local.m_flSuitPower / 100.0f );
FirePlayerProxyOutput( "OnFlashlightOn", flashlighton, this, this );
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CHL2_Player::FlashlightTurnOff( void )
{
if ( Flashlight_UseLegacyVersion() )
{
if( !SuitPower_RemoveDevice( SuitDeviceFlashlight ) )
return;
}
RemoveEffects( EF_DIMLIGHT );
EmitSound( "HL2Player.FlashLightOff" );
variant_t flashlightoff;
flashlightoff.SetFloat( m_HL2Local.m_flSuitPower / 100.0f );
FirePlayerProxyOutput( "OnFlashlightOff", flashlightoff, this, this );
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
#define FLASHLIGHT_RANGE Square(600)
bool CHL2_Player::IsIlluminatedByFlashlight( CBaseEntity *pEntity, float *flReturnDot )
{
if( !FlashlightIsOn() )
return false;
if( pEntity->Classify() == CLASS_BARNACLE && pEntity->GetEnemy() == this )
{
// As long as my flashlight is on, the barnacle that's pulling me in is considered illuminated.
// This is because players often shine their flashlights at Alyx when they are in a barnacle's
// grasp, and wonder why Alyx isn't helping. Alyx isn't helping because the light isn't pointed
// at the barnacle. This will allow Alyx to see the barnacle no matter which way the light is pointed.
return true;
}
// Within 50 feet?
float flDistSqr = GetAbsOrigin().DistToSqr(pEntity->GetAbsOrigin());
if( flDistSqr > FLASHLIGHT_RANGE )
return false;
// Within 45 degrees?
Vector vecSpot = pEntity->WorldSpaceCenter();
Vector los;
// If the eyeposition is too close, move it back. Solves problems
// caused by the player being too close the target.
if ( flDistSqr < (128 * 128) )
{
Vector vecForward;
EyeVectors( &vecForward );
Vector vecMovedEyePos = EyePosition() - (vecForward * 128);
los = ( vecSpot - vecMovedEyePos );
}
else
{
los = ( vecSpot - EyePosition() );
}
VectorNormalize( los );
Vector facingDir = EyeDirection3D( );
float flDot = DotProduct( los, facingDir );
if ( flReturnDot )
{
*flReturnDot = flDot;
}
if ( flDot < 0.92387f )
return false;
if( !FVisible(pEntity) )
return false;
return true;
}
//-----------------------------------------------------------------------------
// Purpose: Let NPCs know when the flashlight is trained on them
//-----------------------------------------------------------------------------
void CHL2_Player::CheckFlashlight( void )
{
if ( !FlashlightIsOn() )
return;
if ( m_flNextFlashlightCheckTime > gpGlobals->curtime )
return;
m_flNextFlashlightCheckTime = gpGlobals->curtime + FLASHLIGHT_NPC_CHECK_INTERVAL;
// Loop through NPCs looking for illuminated ones
for ( int i = 0; i < g_AI_Manager.NumAIs(); i++ )
{
CAI_BaseNPC *pNPC = g_AI_Manager.AccessAIs()[i];
float flDot;
if ( IsIlluminatedByFlashlight( pNPC, &flDot ) )
{
pNPC->PlayerHasIlluminatedNPC( this, flDot );
}
}
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CHL2_Player::SetPlayerUnderwater( bool state )
{
if ( state )
{
SuitPower_AddDevice( SuitDeviceBreather );
}
else
{
SuitPower_RemoveDevice( SuitDeviceBreather );
}
BaseClass::SetPlayerUnderwater( state );
}
//-----------------------------------------------------------------------------
bool CHL2_Player::PassesDamageFilter( const CTakeDamageInfo &info )
{
CBaseEntity *pAttacker = info.GetAttacker();
if( pAttacker && pAttacker->MyNPCPointer() && pAttacker->MyNPCPointer()->IsPlayerAlly() )
{
return false;
}
if( m_hPlayerProxy && !m_hPlayerProxy->PassesDamageFilter( info ) )
{
return false;
}
return BaseClass::PassesDamageFilter( info );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CHL2_Player::SetFlashlightEnabled( bool bState )
{
m_bFlashlightDisabled = !bState;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CHL2_Player::InputDisableFlashlight( inputdata_t &inputdata )
{
if( FlashlightIsOn() )
FlashlightTurnOff();
SetFlashlightEnabled( false );
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CHL2_Player::InputEnableFlashlight( inputdata_t &inputdata )
{
SetFlashlightEnabled( true );
}
//-----------------------------------------------------------------------------
// Purpose: Prevent the player from taking fall damage for [n] seconds, but
// reset back to taking fall damage after the first impact (so players will be
// hurt if they bounce off what they hit). This is the original behavior.
//-----------------------------------------------------------------------------
void CHL2_Player::InputIgnoreFallDamage( inputdata_t &inputdata )
{
float timeToIgnore = inputdata.value.Float();
if ( timeToIgnore <= 0.0 )
timeToIgnore = TIME_IGNORE_FALL_DAMAGE;
m_flTimeIgnoreFallDamage = gpGlobals->curtime + timeToIgnore;
m_bIgnoreFallDamageResetAfterImpact = true;
}
//-----------------------------------------------------------------------------
// Purpose: Absolutely prevent the player from taking fall damage for [n] seconds.
//-----------------------------------------------------------------------------
void CHL2_Player::InputIgnoreFallDamageWithoutReset( inputdata_t &inputdata )
{
float timeToIgnore = inputdata.value.Float();
if ( timeToIgnore <= 0.0 )
timeToIgnore = TIME_IGNORE_FALL_DAMAGE;
m_flTimeIgnoreFallDamage = gpGlobals->curtime + timeToIgnore;
m_bIgnoreFallDamageResetAfterImpact = false;
}
//-----------------------------------------------------------------------------
// Purpose: Notification of a player's npc ally in the players squad being killed
//-----------------------------------------------------------------------------
void CHL2_Player::OnSquadMemberKilled( inputdata_t &data )
{
// send a message to the client, to notify the hud of the loss
CSingleUserRecipientFilter user( this );
user.MakeReliable();
UserMessageBegin( user, "SquadMemberDied" );
MessageEnd();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CHL2_Player::NotifyFriendsOfDamage( CBaseEntity *pAttackerEntity )
{
CAI_BaseNPC *pAttacker = pAttackerEntity->MyNPCPointer();
if ( pAttacker )
{
const Vector &origin = GetAbsOrigin();
for ( int i = 0; i < g_AI_Manager.NumAIs(); i++ )
{
const float NEAR_Z = 12*12;
const float NEAR_XY_SQ = Square( 50*12 );
CAI_BaseNPC *pNpc = g_AI_Manager.AccessAIs()[i];
if ( pNpc->IsPlayerAlly() )
{
const Vector &originNpc = pNpc->GetAbsOrigin();
if ( fabsf( originNpc.z - origin.z ) < NEAR_Z )
{
if ( (originNpc.AsVector2D() - origin.AsVector2D()).LengthSqr() < NEAR_XY_SQ )
{
pNpc->OnFriendDamaged( this, pAttacker );
}
}
}
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
ConVar test_massive_dmg("test_massive_dmg", "30" );
ConVar test_massive_dmg_clip("test_massive_dmg_clip", "0.5" );
int CHL2_Player::OnTakeDamage( const CTakeDamageInfo &info )
{
if ( GlobalEntity_GetState( "gordon_invulnerable" ) == GLOBAL_ON )
return 0;
// ignore fall damage if instructed to do so by input
if ( ( info.GetDamageType() & DMG_FALL ) && m_flTimeIgnoreFallDamage > gpGlobals->curtime )
{
// usually, we will reset the input flag after the first impact. However there is another input that
// prevents this behavior.
if ( m_bIgnoreFallDamageResetAfterImpact )
{
m_flTimeIgnoreFallDamage = 0;
}
return 0;
}
if( info.GetDamageType() & DMG_BLAST_SURFACE )
{
if( GetWaterLevel() > 2 )
{
// Don't take blast damage from anything above the surface.
if( info.GetInflictor()->GetWaterLevel() == 0 )
{
return 0;
}
}
}
if ( info.GetDamage() > 0.0f )
{
m_flLastDamageTime = gpGlobals->curtime;
if ( info.GetAttacker() )
NotifyFriendsOfDamage( info.GetAttacker() );
}
// Modify the amount of damage the player takes, based on skill.
CTakeDamageInfo playerDamage = info;
// Should we run this damage through the skill level adjustment?
bool bAdjustForSkillLevel = true;
if( info.GetDamageType() == DMG_GENERIC && info.GetAttacker() == this && info.GetInflictor() == this )
{
// Only do a skill level adjustment if the player isn't his own attacker AND inflictor.
// This prevents damage from SetHealth() inputs from being adjusted for skill level.
bAdjustForSkillLevel = false;
}
if ( GetVehicleEntity() != NULL && GlobalEntity_GetState("gordon_protect_driver") == GLOBAL_ON )
{
if( playerDamage.GetDamage() > test_massive_dmg.GetFloat() && playerDamage.GetInflictor() == GetVehicleEntity() && (playerDamage.GetDamageType() & DMG_CRUSH) )
{
playerDamage.ScaleDamage( test_massive_dmg_clip.GetFloat() / playerDamage.GetDamage() );
}
}
if( bAdjustForSkillLevel )
{
playerDamage.AdjustPlayerDamageTakenForSkillLevel();
}
gamestats->Event_PlayerDamage( this, info );
return BaseClass::OnTakeDamage( playerDamage );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : &info -
//-----------------------------------------------------------------------------
int CHL2_Player::OnTakeDamage_Alive( const CTakeDamageInfo &info )
{
// Drown
if( info.GetDamageType() & DMG_DROWN )
{
if( m_idrowndmg == m_idrownrestored )
{
EmitSound( "Player.DrownStart" );
}
else
{
EmitSound( "Player.DrownContinue" );
}
}
// Burnt
if ( info.GetDamageType() & DMG_BURN )
{
EmitSound( "HL2Player.BurnPain" );
}
if( (info.GetDamageType() & DMG_SLASH) && hl2_episodic.GetBool() )
{
if( m_afPhysicsFlags & PFLAG_USING )
{
// Stop the player using a rotating button for a short time if hit by a creature's melee attack.
// This is for the antlion burrow-corking training in EP1 (sjb).
SuspendUse( 0.5f );
}
}
// Call the base class implementation
return BaseClass::OnTakeDamage_Alive( info );
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CHL2_Player::OnDamagedByExplosion( const CTakeDamageInfo &info )
{
if ( info.GetInflictor() && info.GetInflictor()->ClassMatches( "mortarshell" ) )
{
// No ear ringing for mortar
UTIL_ScreenShake( info.GetInflictor()->GetAbsOrigin(), 4.0, 1.0, 0.5, 1000, SHAKE_START, false );
return;
}
BaseClass::OnDamagedByExplosion( info );
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
bool CHL2_Player::ShouldShootMissTarget( CBaseCombatCharacter *pAttacker )
{
if( gpGlobals->curtime > m_flTargetFindTime )
{
// Put this off into the future again.
m_flTargetFindTime = gpGlobals->curtime + random->RandomFloat( 3, 5 );
return true;
}
return false;
}
//-----------------------------------------------------------------------------
// Purpose: Notifies Alyx that player has put a combine ball into a socket so she can comment on it.
// Input : pCombineBall - ball the was socketed
//-----------------------------------------------------------------------------
void CHL2_Player::CombineBallSocketed( CPropCombineBall *pCombineBall )
{
#ifdef HL2_EPISODIC
CNPC_Alyx *pAlyx = CNPC_Alyx::GetAlyx();
if ( pAlyx )
{
pAlyx->CombineBallSocketed( pCombineBall->NumBounces() );
}
#endif
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CHL2_Player::Event_KilledOther( CBaseEntity *pVictim, const CTakeDamageInfo &info )
{
BaseClass::Event_KilledOther( pVictim, info );
#ifdef HL2_EPISODIC
CAI_BaseNPC **ppAIs = g_AI_Manager.AccessAIs();
for ( int i = 0; i < g_AI_Manager.NumAIs(); i++ )
{
if ( ppAIs[i] && ppAIs[i]->IRelationType(this) == D_LI )
{
ppAIs[i]->OnPlayerKilledOther( pVictim, info );
}
}
#endif
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CHL2_Player::Event_Killed( const CTakeDamageInfo &info )
{
BaseClass::Event_Killed( info );
FirePlayerProxyOutput( "PlayerDied", variant_t(), this, this );
NotifyScriptsOfDeath();
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CHL2_Player::NotifyScriptsOfDeath( void )
{
CBaseEntity *pEnt = gEntList.FindEntityByClassname( NULL, "scripted_sequence" );
while( pEnt )
{
variant_t emptyVariant;
pEnt->AcceptInput( "ScriptPlayerDeath", NULL, NULL, emptyVariant, 0 );
pEnt = gEntList.FindEntityByClassname( pEnt, "scripted_sequence" );
}
pEnt = gEntList.FindEntityByClassname( NULL, "logic_choreographed_scene" );
while( pEnt )
{
variant_t emptyVariant;
pEnt->AcceptInput( "ScriptPlayerDeath", NULL, NULL, emptyVariant, 0 );
pEnt = gEntList.FindEntityByClassname( pEnt, "logic_choreographed_scene" );
}
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CHL2_Player::GetAutoaimVector( autoaim_params_t ¶ms )
{
BaseClass::GetAutoaimVector( params );
if ( IsX360() )
{
if( IsInAVehicle() )
{
if( m_hLockedAutoAimEntity && m_hLockedAutoAimEntity->IsAlive() && ShouldKeepLockedAutoaimTarget(m_hLockedAutoAimEntity) )
{
if( params.m_hAutoAimEntity && params.m_hAutoAimEntity != m_hLockedAutoAimEntity )
{
// Autoaim has picked a new target. Switch.
m_hLockedAutoAimEntity = params.m_hAutoAimEntity;
}
// Ignore autoaim and just keep aiming at this target.
params.m_hAutoAimEntity = m_hLockedAutoAimEntity;
Vector vecTarget = m_hLockedAutoAimEntity->BodyTarget( EyePosition(), false );
Vector vecDir = vecTarget - EyePosition();
VectorNormalize( vecDir );
params.m_vecAutoAimDir = vecDir;
params.m_vecAutoAimPoint = vecTarget;
return;
}
else
{
m_hLockedAutoAimEntity = NULL;
}
}
// If the player manually gets his crosshair onto a target, make that target sticky
if( params.m_fScale != AUTOAIM_SCALE_DIRECT_ONLY )
{
// Only affect this for 'real' queries
//if( params.m_hAutoAimEntity && params.m_bOnTargetNatural )
if( params.m_hAutoAimEntity )
{
// Turn on sticky.
m_HL2Local.m_bStickyAutoAim = true;
if( IsInAVehicle() )
{
m_hLockedAutoAimEntity = params.m_hAutoAimEntity;
}
}
else if( !params.m_hAutoAimEntity )
{
// Turn off sticky only if there's no target at all.
m_HL2Local.m_bStickyAutoAim = false;
m_hLockedAutoAimEntity = NULL;
}
}
}
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
bool CHL2_Player::ShouldKeepLockedAutoaimTarget( EHANDLE hLockedTarget )
{
Vector vecLooking;
Vector vecToTarget;
vecToTarget = hLockedTarget->WorldSpaceCenter() - EyePosition();
float flDist = vecToTarget.Length2D();
VectorNormalize( vecToTarget );
if( flDist > autoaim_max_dist.GetFloat() )
return false;
float flDot;
vecLooking = EyeDirection3D();
flDot = DotProduct( vecLooking, vecToTarget );
if( flDot < autoaim_unlock_target.GetFloat() )
return false;
return true;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : iCount -
// iAmmoIndex -
// bSuppressSound -
// Output : int
//-----------------------------------------------------------------------------
int CHL2_Player::GiveAmmo( int nCount, int nAmmoIndex, bool bSuppressSound)
{
// Don't try to give the player invalid ammo indices.
if (nAmmoIndex < 0)
return 0;
bool bCheckAutoSwitch = false;
if (!HasAnyAmmoOfType(nAmmoIndex))
{
bCheckAutoSwitch = true;
}
int nAdd = BaseClass::GiveAmmo(nCount, nAmmoIndex, bSuppressSound);
if ( nCount > 0 && nAdd == 0 )
{
// we've been denied the pickup, display a hud icon to show that
CSingleUserRecipientFilter user( this );
user.MakeReliable();
UserMessageBegin( user, "AmmoDenied" );
WRITE_SHORT( nAmmoIndex );
MessageEnd();
}
//
// If I was dry on ammo for my best weapon and justed picked up ammo for it,
// autoswitch to my best weapon now.
//
if (bCheckAutoSwitch)
{
CBaseCombatWeapon *pWeapon = g_pGameRules->GetNextBestWeapon(this, GetActiveWeapon());
if ( pWeapon && pWeapon->GetPrimaryAmmoType() == nAmmoIndex )
{
SwitchToNextBestWeapon(GetActiveWeapon());
}
}
return nAdd;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
bool CHL2_Player::Weapon_CanUse( CBaseCombatWeapon *pWeapon )
{
#ifndef HL2MP
if ( pWeapon->ClassMatches( "weapon_stunstick" ) )
{
if ( ApplyBattery( 0.5 ) )
UTIL_Remove( pWeapon );
return false;
}
#endif
return BaseClass::Weapon_CanUse( pWeapon );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *pWeapon -
//-----------------------------------------------------------------------------
void CHL2_Player::Weapon_Equip( CBaseCombatWeapon *pWeapon )
{
#if HL2_SINGLE_PRIMARY_WEAPON_MODE
if ( pWeapon->GetSlot() == WEAPON_PRIMARY_SLOT )
{
Weapon_DropSlot( WEAPON_PRIMARY_SLOT );
}
#endif
if( GetActiveWeapon() == NULL )
{
m_HL2Local.m_bWeaponLowered = false;
}
BaseClass::Weapon_Equip( pWeapon );
}
//-----------------------------------------------------------------------------
// Purpose: Player reacts to bumping a weapon.
// Input : pWeapon - the weapon that the player bumped into.
// Output : Returns true if player picked up the weapon
//-----------------------------------------------------------------------------
bool CHL2_Player::BumpWeapon( CBaseCombatWeapon *pWeapon )
{
#if HL2_SINGLE_PRIMARY_WEAPON_MODE
CBaseCombatCharacter *pOwner = pWeapon->GetOwner();
// Can I have this weapon type?
if ( pOwner || !Weapon_CanUse( pWeapon ) || !g_pGameRules->CanHavePlayerItem( this, pWeapon ) )
{
if ( gEvilImpulse101 )
{
UTIL_Remove( pWeapon );
}
return false;
}
// ----------------------------------------
// If I already have it just take the ammo
// ----------------------------------------
if (Weapon_OwnsThisType( pWeapon->GetClassname(), pWeapon->GetSubType()))
{
//Only remove the weapon if we attained ammo from it
if ( Weapon_EquipAmmoOnly( pWeapon ) == false )
return false;
// Only remove me if I have no ammo left
// Can't just check HasAnyAmmo because if I don't use clips, I want to be removed,
if ( pWeapon->UsesClipsForAmmo1() && pWeapon->HasPrimaryAmmo() )
return false;
UTIL_Remove( pWeapon );
return false;
}
// -------------------------
// Otherwise take the weapon
// -------------------------
else
{
//Make sure we're not trying to take a new weapon type we already have
if ( Weapon_SlotOccupied( pWeapon ) )
{
CBaseCombatWeapon *pActiveWeapon = Weapon_GetSlot( WEAPON_PRIMARY_SLOT );
if ( pActiveWeapon != NULL && pActiveWeapon->HasAnyAmmo() == false && Weapon_CanSwitchTo( pWeapon ) )
{
Weapon_Equip( pWeapon );
return true;
}
//Attempt to take ammo if this is the gun we're holding already
if ( Weapon_OwnsThisType( pWeapon->GetClassname(), pWeapon->GetSubType() ) )
{
Weapon_EquipAmmoOnly( pWeapon );
}
return false;
}
pWeapon->CheckRespawn();
pWeapon->AddSolidFlags( FSOLID_NOT_SOLID );
pWeapon->AddEffects( EF_NODRAW );
Weapon_Equip( pWeapon );
EmitSound( "HL2Player.PickupWeapon" );
return true;
}
#else
return BaseClass::BumpWeapon( pWeapon );
#endif
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *cmd -
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CHL2_Player::ClientCommand( const CCommand &args )
{
#if HL2_SINGLE_PRIMARY_WEAPON_MODE
//Drop primary weapon
if ( !Q_stricmp( args[0], "DropPrimary" ) )
{
Weapon_DropSlot( WEAPON_PRIMARY_SLOT );
return true;
}
#endif
if ( !Q_stricmp( args[0], "emit" ) )
{
CSingleUserRecipientFilter filter( this );
if ( args.ArgC() > 1 )
{
EmitSound( filter, entindex(), args[ 1 ] );
}
else
{
EmitSound( filter, entindex(), "Test.Sound" );
}
return true;
}
return BaseClass::ClientCommand( args );
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : void CBasePlayer::PlayerUse
//-----------------------------------------------------------------------------
void CHL2_Player::PlayerUse ( void )
{
// Was use pressed or released?
if ( ! ((m_nButtons | m_afButtonPressed | m_afButtonReleased) & IN_USE) )
return;
if ( m_afButtonPressed & IN_USE )
{
// Currently using a latched entity?
if ( ClearUseEntity() )
{
return;
}
else
{
if ( m_afPhysicsFlags & PFLAG_DIROVERRIDE )
{
m_afPhysicsFlags &= ~PFLAG_DIROVERRIDE;
m_iTrain = TRAIN_NEW|TRAIN_OFF;
return;
}
else
{ // Start controlling the train!
CBaseEntity *pTrain = GetGroundEntity();
if ( pTrain && !(m_nButtons & IN_JUMP) && (GetFlags() & FL_ONGROUND) && (pTrain->ObjectCaps() & FCAP_DIRECTIONAL_USE) && pTrain->OnControls(this) )
{
m_afPhysicsFlags |= PFLAG_DIROVERRIDE;
m_iTrain = TrainSpeed(pTrain->m_flSpeed, ((CFuncTrackTrain*)pTrain)->GetMaxSpeed());
m_iTrain |= TRAIN_NEW;
EmitSound( "HL2Player.TrainUse" );
return;
}
}
}
// Tracker 3926: We can't +USE something if we're climbing a ladder
if ( GetMoveType() == MOVETYPE_LADDER )
{
return;
}
}
if( m_flTimeUseSuspended > gpGlobals->curtime )
{
// Something has temporarily stopped us being able to USE things.
// Obviously, this should be used very carefully.(sjb)
return;
}
CBaseEntity *pUseEntity = FindUseEntity();
bool usedSomething = false;
// Found an object
if ( pUseEntity )
{
//!!!UNDONE: traceline here to prevent +USEing buttons through walls
int caps = pUseEntity->ObjectCaps();
variant_t emptyVariant;
if ( m_afButtonPressed & IN_USE )
{
// Robin: Don't play sounds for NPCs, because NPCs will allow respond with speech.
if ( !pUseEntity->MyNPCPointer() )
{
EmitSound( "HL2Player.Use" );
}
}
if ( ( (m_nButtons & IN_USE) && (caps & FCAP_CONTINUOUS_USE) ) ||
( (m_afButtonPressed & IN_USE) && (caps & (FCAP_IMPULSE_USE|FCAP_ONOFF_USE)) ) )
{
if ( caps & FCAP_CONTINUOUS_USE )
m_afPhysicsFlags |= PFLAG_USING;
pUseEntity->AcceptInput( "Use", this, this, emptyVariant, USE_TOGGLE );
usedSomething = true;
}
// UNDONE: Send different USE codes for ON/OFF. Cache last ONOFF_USE object to send 'off' if you turn away
else if ( (m_afButtonReleased & IN_USE) && (pUseEntity->ObjectCaps() & FCAP_ONOFF_USE) ) // BUGBUG This is an "off" use
{
pUseEntity->AcceptInput( "Use", this, this, emptyVariant, USE_TOGGLE );
usedSomething = true;
}
#if HL2_SINGLE_PRIMARY_WEAPON_MODE
//Check for weapon pick-up
if ( m_afButtonPressed & IN_USE )
{
CBaseCombatWeapon *pWeapon = dynamic_cast<CBaseCombatWeapon *>(pUseEntity);
if ( ( pWeapon != NULL ) && ( Weapon_CanSwitchTo( pWeapon ) ) )
{
//Try to take ammo or swap the weapon
if ( Weapon_OwnsThisType( pWeapon->GetClassname(), pWeapon->GetSubType() ) )
{
Weapon_EquipAmmoOnly( pWeapon );
}
else
{
Weapon_DropSlot( pWeapon->GetSlot() );
Weapon_Equip( pWeapon );
}
usedSomething = true;
}
}
#endif
}
else if ( m_afButtonPressed & IN_USE )
{
// Signal that we want to play the deny sound, unless the user is +USEing on a ladder!
// The sound is emitted in ItemPostFrame, since that occurs after GameMovement::ProcessMove which
// lets the ladder code unset this flag.
m_bPlayUseDenySound = true;
}
// Debounce the use key
if ( usedSomething && pUseEntity )
{
m_Local.m_nOldButtons |= IN_USE;
m_afButtonPressed &= ~IN_USE;
}
}
ConVar sv_show_crosshair_target( "sv_show_crosshair_target", "0" );
//-----------------------------------------------------------------------------
// Purpose: Updates the posture of the weapon from lowered to ready
//-----------------------------------------------------------------------------
void CHL2_Player::UpdateWeaponPosture( void )
{
CBaseCombatWeapon *pWeapon = dynamic_cast<CBaseCombatWeapon *>(GetActiveWeapon());
if ( pWeapon && m_LowerWeaponTimer.Expired() && pWeapon->CanLower() )
{
m_LowerWeaponTimer.Set( .3 );
VPROF( "CHL2_Player::UpdateWeaponPosture-CheckLower" );
Vector vecAim = BaseClass::GetAutoaimVector( AUTOAIM_SCALE_DIRECT_ONLY );
const float CHECK_FRIENDLY_RANGE = 50 * 12;
trace_t tr;
UTIL_TraceLine( EyePosition(), EyePosition() + vecAim * CHECK_FRIENDLY_RANGE, MASK_SHOT, this, COLLISION_GROUP_NONE, &tr );
CBaseEntity *aimTarget = tr.m_pEnt;
//If we're over something
if ( aimTarget && !tr.DidHitWorld() )
{
if ( !aimTarget->IsNPC() || aimTarget->MyNPCPointer()->GetState() != NPC_STATE_COMBAT )
{
Disposition_t dis = IRelationType( aimTarget );
//Debug info for seeing what an object "cons" as
if ( sv_show_crosshair_target.GetBool() )
{
int text_offset = BaseClass::DrawDebugTextOverlays();
char tempstr[255];
switch ( dis )
{
case D_LI:
Q_snprintf( tempstr, sizeof(tempstr), "Disposition: Like" );
break;
case D_HT:
Q_snprintf( tempstr, sizeof(tempstr), "Disposition: Hate" );
break;
case D_FR:
Q_snprintf( tempstr, sizeof(tempstr), "Disposition: Fear" );
break;
case D_NU:
Q_snprintf( tempstr, sizeof(tempstr), "Disposition: Neutral" );
break;
default:
case D_ER:
Q_snprintf( tempstr, sizeof(tempstr), "Disposition: !!!ERROR!!!" );
break;
}
//Draw the text
NDebugOverlay::EntityText( aimTarget->entindex(), text_offset, tempstr, 0 );
}
//See if we hates it
if ( dis == D_LI )
{
//We're over a friendly, drop our weapon
if ( Weapon_Lower() == false )
{
//FIXME: We couldn't lower our weapon!
}
return;
}
}
}
if ( Weapon_Ready() == false )
{
//FIXME: We couldn't raise our weapon!
}
}
if( g_pGameRules->GetAutoAimMode() != AUTOAIM_NONE )
{
if( !pWeapon )
{
// This tells the client to draw no crosshair
m_HL2Local.m_bWeaponLowered = true;
return;
}
else
{
if( !pWeapon->CanLower() && m_HL2Local.m_bWeaponLowered )
m_HL2Local.m_bWeaponLowered = false;
}
if( !m_AutoaimTimer.Expired() )
return;
m_AutoaimTimer.Set( .1 );
VPROF( "hl2_x360_aiming" );
// Call the autoaim code to update the local player data, which allows the client to update.
autoaim_params_t params;
params.m_vecAutoAimPoint.Init();
params.m_vecAutoAimDir.Init();
params.m_fScale = AUTOAIM_SCALE_DEFAULT;
params.m_fMaxDist = autoaim_max_dist.GetFloat();
GetAutoaimVector( params );
m_HL2Local.m_hAutoAimTarget.Set( params.m_hAutoAimEntity );
m_HL2Local.m_vecAutoAimPoint.Set( params.m_vecAutoAimPoint );
m_HL2Local.m_bAutoAimTarget = ( params.m_bAutoAimAssisting || params.m_bOnTargetNatural );
return;
}
else
{
// Make sure there's no residual autoaim target if the user changes the xbox_aiming convar on the fly.
m_HL2Local.m_hAutoAimTarget.Set(NULL);
}
}
//-----------------------------------------------------------------------------
// Purpose: Lowers the weapon posture (for hovering over friendlies)
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CHL2_Player::Weapon_Lower( void )
{
VPROF( "CHL2_Player::Weapon_Lower" );
// Already lowered?
if ( m_HL2Local.m_bWeaponLowered )
return true;
m_HL2Local.m_bWeaponLowered = true;
CBaseCombatWeapon *pWeapon = dynamic_cast<CBaseCombatWeapon *>(GetActiveWeapon());
if ( pWeapon == NULL )
return false;
return pWeapon->Lower();
}
//-----------------------------------------------------------------------------
// Purpose: Returns the weapon posture to normal
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CHL2_Player::Weapon_Ready( void )
{
VPROF( "CHL2_Player::Weapon_Ready" );
// Already ready?
if ( m_HL2Local.m_bWeaponLowered == false )
return true;
m_HL2Local.m_bWeaponLowered = false;
CBaseCombatWeapon *pWeapon = dynamic_cast<CBaseCombatWeapon *>(GetActiveWeapon());
if ( pWeapon == NULL )
return false;
return pWeapon->Ready();
}
//-----------------------------------------------------------------------------
// Purpose: Returns whether or not we can switch to the given weapon.
// Input : pWeapon -
//-----------------------------------------------------------------------------
bool CHL2_Player::Weapon_CanSwitchTo( CBaseCombatWeapon *pWeapon )
{
CBasePlayer *pPlayer = (CBasePlayer *)this;
#if !defined( CLIENT_DLL )
IServerVehicle *pVehicle = pPlayer->GetVehicle();
#else
IClientVehicle *pVehicle = pPlayer->GetVehicle();
#endif
if (pVehicle && !pPlayer->UsingStandardWeaponsInVehicle())
return false;
/////
// SO2 - James
// Allow players to switch to weapons that do not have any ammo
/*if ( !pWeapon->HasAnyAmmo() && !GetAmmoCount( pWeapon->m_iPrimaryAmmoType ) )
return false;*/
/////
if ( !pWeapon->CanDeploy() )
return false;
if ( GetActiveWeapon() )
{
if ( PhysCannonGetHeldEntity( GetActiveWeapon() ) == pWeapon &&
Weapon_OwnsThisType( pWeapon->GetClassname(), pWeapon->GetSubType()) )
{
return true;
}
if ( !GetActiveWeapon()->CanHolster() )
return false;
}
return true;
}
void CHL2_Player::PickupObject( CBaseEntity *pObject, bool bLimitMassAndSize )
{
// can't pick up what you're standing on
if ( GetGroundEntity() == pObject )
return;
if ( bLimitMassAndSize == true )
{
if ( CBasePlayer::CanPickupObject( pObject, 35, 128 ) == false )
return;
}
// Can't be picked up if NPCs are on me
if ( pObject->HasNPCsOnIt() )
return;
PlayerPickupObject( this, pObject );
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : CBaseEntity
//-----------------------------------------------------------------------------
bool CHL2_Player::IsHoldingEntity( CBaseEntity *pEnt )
{
return PlayerPickupControllerIsHoldingEntity( m_hUseEntity, pEnt );
}
float CHL2_Player::GetHeldObjectMass( IPhysicsObject *pHeldObject )
{
float mass = PlayerPickupGetHeldObjectMass( m_hUseEntity, pHeldObject );
if ( mass == 0.0f )
{
mass = PhysCannonGetHeldObjectMass( GetActiveWeapon(), pHeldObject );
}
return mass;
}
CBaseEntity *CHL2_Player::GetHeldObject( void )
{
return PhysCannonGetHeldEntity( GetActiveWeapon() );
}
//-----------------------------------------------------------------------------
// Purpose: Force the player to drop any physics objects he's carrying
//-----------------------------------------------------------------------------
void CHL2_Player::ForceDropOfCarriedPhysObjects( CBaseEntity *pOnlyIfHoldingThis )
{
if ( PhysIsInCallback() )
{
variant_t value;
g_EventQueue.AddEvent( this, "ForceDropPhysObjects", value, 0.01f, pOnlyIfHoldingThis, this );
return;
}
#ifdef HL2_EPISODIC
if ( hl2_episodic.GetBool() )
{
CBaseEntity *pHeldEntity = PhysCannonGetHeldEntity( GetActiveWeapon() );
if( pHeldEntity && pHeldEntity->ClassMatches( "grenade_helicopter" ) )
{
return;
}
}
#endif
// Drop any objects being handheld.
ClearUseEntity();
// Then force the physcannon to drop anything it's holding, if it's our active weapon
PhysCannonForceDrop( GetActiveWeapon(), NULL );
}
void CHL2_Player::InputForceDropPhysObjects( inputdata_t &data )
{
ForceDropOfCarriedPhysObjects( data.pActivator );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CHL2_Player::UpdateClientData( void )
{
if (m_DmgTake || m_DmgSave || m_bitsHUDDamage != m_bitsDamageType)
{
// Comes from inside me if not set
Vector damageOrigin = GetLocalOrigin();
// send "damage" message
// causes screen to flash, and pain compass to show direction of damage
damageOrigin = m_DmgOrigin;
// only send down damage type that have hud art
int iShowHudDamage = g_pGameRules->Damage_GetShowOnHud();
int visibleDamageBits = m_bitsDamageType & iShowHudDamage;
m_DmgTake = clamp( m_DmgTake, 0, 255 );
m_DmgSave = clamp( m_DmgSave, 0, 255 );
// If we're poisoned, but it wasn't this frame, don't send the indicator
// Without this check, any damage that occured to the player while they were
// recovering from a poison bite would register as poisonous as well and flash
// the whole screen! -- jdw
if ( visibleDamageBits & DMG_POISON )
{
float flLastPoisonedDelta = gpGlobals->curtime - m_tbdPrev;
if ( flLastPoisonedDelta > 0.1f )
{
visibleDamageBits &= ~DMG_POISON;
}
}
CSingleUserRecipientFilter user( this );
user.MakeReliable();
UserMessageBegin( user, "Damage" );
WRITE_BYTE( m_DmgSave );
WRITE_BYTE( m_DmgTake );
WRITE_LONG( visibleDamageBits );
WRITE_FLOAT( damageOrigin.x ); //BUG: Should be fixed point (to hud) not floats
WRITE_FLOAT( damageOrigin.y ); //BUG: However, the HUD does _not_ implement bitfield messages (yet)
WRITE_FLOAT( damageOrigin.z ); //BUG: We use WRITE_VEC3COORD for everything else
MessageEnd();
m_DmgTake = 0;
m_DmgSave = 0;
m_bitsHUDDamage = m_bitsDamageType;
// Clear off non-time-based damage indicators
int iTimeBasedDamage = g_pGameRules->Damage_GetTimeBased();
m_bitsDamageType &= iTimeBasedDamage;
}
// Update Flashlight
#ifdef HL2_EPISODIC
if ( Flashlight_UseLegacyVersion() == false )
{
if ( FlashlightIsOn() && sv_infinite_aux_power.GetBool() == false )
{
m_HL2Local.m_flFlashBattery -= FLASH_DRAIN_TIME * gpGlobals->frametime;
if ( m_HL2Local.m_flFlashBattery < 0.0f )
{
FlashlightTurnOff();
m_HL2Local.m_flFlashBattery = 0.0f;
}
}
else
{
m_HL2Local.m_flFlashBattery += FLASH_CHARGE_TIME * gpGlobals->frametime;
if ( m_HL2Local.m_flFlashBattery > 100.0f )
{
m_HL2Local.m_flFlashBattery = 100.0f;
}
}
}
else
{
m_HL2Local.m_flFlashBattery = -1.0f;
}
#endif // HL2_EPISODIC
BaseClass::UpdateClientData();
}
//---------------------------------------------------------
//---------------------------------------------------------
void CHL2_Player::OnRestore()
{
BaseClass::OnRestore();
m_pPlayerAISquad = g_AI_SquadManager.FindCreateSquad(AllocPooledString(PLAYER_SQUADNAME));
}
//---------------------------------------------------------
//---------------------------------------------------------
Vector CHL2_Player::EyeDirection2D( void )
{
Vector vecReturn = EyeDirection3D();
vecReturn.z = 0;
vecReturn.AsVector2D().NormalizeInPlace();
return vecReturn;
}
//---------------------------------------------------------
//---------------------------------------------------------
Vector CHL2_Player::EyeDirection3D( void )
{
Vector vecForward;
// Return the vehicle angles if we request them
if ( GetVehicle() != NULL )
{
CacheVehicleView();
EyeVectors( &vecForward );
return vecForward;
}
AngleVectors( EyeAngles(), &vecForward );
return vecForward;
}
//---------------------------------------------------------
//---------------------------------------------------------
bool CHL2_Player::Weapon_Switch( CBaseCombatWeapon *pWeapon, int viewmodelindex )
{
MDLCACHE_CRITICAL_SECTION();
// Recalculate proficiency!
SetCurrentWeaponProficiency( CalcWeaponProficiency( pWeapon ) );
// Come out of suit zoom mode
if ( IsZooming() )
{
StopZooming();
}
return BaseClass::Weapon_Switch( pWeapon, viewmodelindex );
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
WeaponProficiency_t CHL2_Player::CalcWeaponProficiency( CBaseCombatWeapon *pWeapon )
{
WeaponProficiency_t proficiency;
proficiency = WEAPON_PROFICIENCY_PERFECT;
if( weapon_showproficiency.GetBool() != 0 )
{
Msg("Player switched to %s, proficiency is %s\n", pWeapon->GetClassname(), GetWeaponProficiencyName( proficiency ) );
}
return proficiency;
}
//-----------------------------------------------------------------------------
// Purpose: override how single player rays hit the player
//-----------------------------------------------------------------------------
bool LineCircleIntersection(
const Vector2D ¢er,
const float radius,
const Vector2D &vLinePt,
const Vector2D &vLineDir,
float *fIntersection1,
float *fIntersection2)
{
// Line = P + Vt
// Sphere = r (assume we've translated to origin)
// (P + Vt)^2 = r^2
// VVt^2 + 2PVt + (PP - r^2)
// Solve as quadratic: (-b +/- sqrt(b^2 - 4ac)) / 2a
// If (b^2 - 4ac) is < 0 there is no solution.
// If (b^2 - 4ac) is = 0 there is one solution (a case this function doesn't support).
// If (b^2 - 4ac) is > 0 there are two solutions.
Vector2D P;
float a, b, c, sqr, insideSqr;
// Translate circle to origin.
P[0] = vLinePt[0] - center[0];
P[1] = vLinePt[1] - center[1];
a = vLineDir.Dot(vLineDir);
b = 2.0f * P.Dot(vLineDir);
c = P.Dot(P) - (radius * radius);
insideSqr = b*b - 4*a*c;
if(insideSqr <= 0.000001f)
return false;
// Ok, two solutions.
sqr = (float)FastSqrt(insideSqr);
float denom = 1.0 / (2.0f * a);
*fIntersection1 = (-b - sqr) * denom;
*fIntersection2 = (-b + sqr) * denom;
return true;
}
static void Collision_ClearTrace( const Vector &vecRayStart, const Vector &vecRayDelta, CBaseTrace *pTrace )
{
pTrace->startpos = vecRayStart;
pTrace->endpos = vecRayStart;
pTrace->endpos += vecRayDelta;
pTrace->startsolid = false;
pTrace->allsolid = false;
pTrace->fraction = 1.0f;
pTrace->contents = 0;
}
bool IntersectRayWithAACylinder( const Ray_t &ray,
const Vector ¢er, float radius, float height, CBaseTrace *pTrace )
{
Assert( ray.m_IsRay );
Collision_ClearTrace( ray.m_Start, ray.m_Delta, pTrace );
// First intersect the ray with the top + bottom planes
float halfHeight = height * 0.5;
// Handle parallel case
Vector vStart = ray.m_Start - center;
Vector vEnd = vStart + ray.m_Delta;
float flEnterFrac, flLeaveFrac;
if (FloatMakePositive(ray.m_Delta.z) < 1e-8)
{
if ( (vStart.z < -halfHeight) || (vStart.z > halfHeight) )
{
return false; // no hit
}
flEnterFrac = 0.0f; flLeaveFrac = 1.0f;
}
else
{
// Clip the ray to the top and bottom of box
flEnterFrac = IntersectRayWithAAPlane( vStart, vEnd, 2, 1, halfHeight);
flLeaveFrac = IntersectRayWithAAPlane( vStart, vEnd, 2, 1, -halfHeight);
if ( flLeaveFrac < flEnterFrac )
{
float temp = flLeaveFrac;
flLeaveFrac = flEnterFrac;
flEnterFrac = temp;
}
if ( flLeaveFrac < 0 || flEnterFrac > 1)
{
return false;
}
}
// Intersect with circle
float flCircleEnterFrac, flCircleLeaveFrac;
if ( !LineCircleIntersection( vec3_origin.AsVector2D(), radius,
vStart.AsVector2D(), ray.m_Delta.AsVector2D(), &flCircleEnterFrac, &flCircleLeaveFrac ) )
{
return false; // no hit
}
Assert( flCircleEnterFrac <= flCircleLeaveFrac );
if ( flCircleLeaveFrac < 0 || flCircleEnterFrac > 1)
{
return false;
}
if ( flEnterFrac < flCircleEnterFrac )
flEnterFrac = flCircleEnterFrac;
if ( flLeaveFrac > flCircleLeaveFrac )
flLeaveFrac = flCircleLeaveFrac;
if ( flLeaveFrac < flEnterFrac )
return false;
VectorMA( ray.m_Start, flEnterFrac , ray.m_Delta, pTrace->endpos );
pTrace->fraction = flEnterFrac;
pTrace->contents = CONTENTS_SOLID;
// Calculate the point on our center line where we're nearest the intersection point
Vector collisionCenter;
CalcClosestPointOnLineSegment( pTrace->endpos, center + Vector( 0, 0, halfHeight ), center - Vector( 0, 0, halfHeight ), collisionCenter );
// Our normal is the direction from that center point to the intersection point
pTrace->plane.normal = pTrace->endpos - collisionCenter;
VectorNormalize( pTrace->plane.normal );
return true;
}
bool CHL2_Player::TestHitboxes( const Ray_t &ray, unsigned int fContentsMask, trace_t& tr )
{
if( g_pGameRules->IsMultiplayer() )
{
return BaseClass::TestHitboxes( ray, fContentsMask, tr );
}
else
{
Assert( ray.m_IsRay );
Vector mins, maxs;
mins = WorldAlignMins();
maxs = WorldAlignMaxs();
if ( IntersectRayWithAACylinder( ray, WorldSpaceCenter(), maxs.x * PLAYER_HULL_REDUCTION, maxs.z - mins.z, &tr ) )
{
tr.hitbox = 0;
CStudioHdr *pStudioHdr = GetModelPtr( );
if (!pStudioHdr)
return false;
mstudiohitboxset_t *set = pStudioHdr->pHitboxSet( m_nHitboxSet );
if ( !set || !set->numhitboxes )
return false;
mstudiobbox_t *pbox = set->pHitbox( tr.hitbox );
mstudiobone_t *pBone = pStudioHdr->pBone(pbox->bone);
tr.surface.name = "**studio**";
tr.surface.flags = SURF_HITBOX;
tr.surface.surfaceProps = physprops->GetSurfaceIndex( pBone->pszSurfaceProp() );
}
return true;
}
}
//---------------------------------------------------------
// Show the player's scaled down bbox that we use for
// bullet impacts.
//---------------------------------------------------------
void CHL2_Player::DrawDebugGeometryOverlays(void)
{
BaseClass::DrawDebugGeometryOverlays();
if (m_debugOverlays & OVERLAY_BBOX_BIT)
{
Vector mins, maxs;
mins = WorldAlignMins();
maxs = WorldAlignMaxs();
mins.x *= PLAYER_HULL_REDUCTION;
mins.y *= PLAYER_HULL_REDUCTION;
maxs.x *= PLAYER_HULL_REDUCTION;
maxs.y *= PLAYER_HULL_REDUCTION;
NDebugOverlay::Box( GetAbsOrigin(), mins, maxs, 255, 0, 0, 100, 0 );
}
}
//-----------------------------------------------------------------------------
// Purpose: Helper to remove from ladder
//-----------------------------------------------------------------------------
void CHL2_Player::ExitLadder()
{
if ( MOVETYPE_LADDER != GetMoveType() )
return;
SetMoveType( MOVETYPE_WALK );
SetMoveCollide( MOVECOLLIDE_DEFAULT );
// Remove from ladder
m_HL2Local.m_hLadder.Set( NULL );
}
surfacedata_t *CHL2_Player::GetLadderSurface( const Vector &origin )
{
extern const char *FuncLadder_GetSurfaceprops(CBaseEntity *pLadderEntity);
CBaseEntity *pLadder = m_HL2Local.m_hLadder.Get();
if ( pLadder )
{
const char *pSurfaceprops = FuncLadder_GetSurfaceprops(pLadder);
// get ladder material from func_ladder
return physprops->GetSurfaceData( physprops->GetSurfaceIndex( pSurfaceprops ) );
}
return BaseClass::GetLadderSurface(origin);
}
//-----------------------------------------------------------------------------
// Purpose: Queues up a use deny sound, played in ItemPostFrame.
//-----------------------------------------------------------------------------
void CHL2_Player::PlayUseDenySound()
{
m_bPlayUseDenySound = true;
}
void CHL2_Player::ItemPostFrame()
{
BaseClass::ItemPostFrame();
if ( m_bPlayUseDenySound )
{
m_bPlayUseDenySound = false;
EmitSound( "HL2Player.UseDeny" );
}
}
void CHL2_Player::StartWaterDeathSounds( void )
{
CPASAttenuationFilter filter( this );
if ( m_sndLeeches == NULL )
{
m_sndLeeches = (CSoundEnvelopeController::GetController()).SoundCreate( filter, entindex(), CHAN_STATIC, "coast.leech_bites_loop" , ATTN_NORM );
}
if ( m_sndLeeches )
{
(CSoundEnvelopeController::GetController()).Play( m_sndLeeches, 1.0f, 100 );
}
if ( m_sndWaterSplashes == NULL )
{
m_sndWaterSplashes = (CSoundEnvelopeController::GetController()).SoundCreate( filter, entindex(), CHAN_STATIC, "coast.leech_water_churn_loop" , ATTN_NORM );
}
if ( m_sndWaterSplashes )
{
(CSoundEnvelopeController::GetController()).Play( m_sndWaterSplashes, 1.0f, 100 );
}
}
void CHL2_Player::StopWaterDeathSounds( void )
{
if ( m_sndLeeches )
{
(CSoundEnvelopeController::GetController()).SoundFadeOut( m_sndLeeches, 0.5f, true );
m_sndLeeches = NULL;
}
if ( m_sndWaterSplashes )
{
(CSoundEnvelopeController::GetController()).SoundFadeOut( m_sndWaterSplashes, 0.5f, true );
m_sndWaterSplashes = NULL;
}
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CHL2_Player::MissedAR2AltFire()
{
if( GetPlayerProxy() != NULL )
{
GetPlayerProxy()->m_PlayerMissedAR2AltFire.FireOutput( this, this );
}
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CHL2_Player::DisplayLadderHudHint()
{
#if !defined( CLIENT_DLL )
if( gpGlobals->curtime > m_flTimeNextLadderHint )
{
m_flTimeNextLadderHint = gpGlobals->curtime + 60.0f;
CFmtStr hint;
hint.sprintf( "#Valve_Hint_Ladder" );
UTIL_HudHintText( this, hint.Access() );
}
#endif//CLIENT_DLL
}
//-----------------------------------------------------------------------------
// Shuts down sounds
//-----------------------------------------------------------------------------
void CHL2_Player::StopLoopingSounds( void )
{
if ( m_sndLeeches != NULL )
{
(CSoundEnvelopeController::GetController()).SoundDestroy( m_sndLeeches );
m_sndLeeches = NULL;
}
if ( m_sndWaterSplashes != NULL )
{
(CSoundEnvelopeController::GetController()).SoundDestroy( m_sndWaterSplashes );
m_sndWaterSplashes = NULL;
}
BaseClass::StopLoopingSounds();
}
//-----------------------------------------------------------------------------
void CHL2_Player::ModifyOrAppendPlayerCriteria( AI_CriteriaSet& set )
{
BaseClass::ModifyOrAppendPlayerCriteria( set );
if ( GlobalEntity_GetIndex( "gordon_precriminal" ) == -1 )
{
set.AppendCriteria( "gordon_precriminal", "0" );
}
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
const impactdamagetable_t &CHL2_Player::GetPhysicsImpactDamageTable()
{
if ( m_bUseCappedPhysicsDamageTable )
return gCappedPlayerImpactDamageTable;
return BaseClass::GetPhysicsImpactDamageTable();
}
//-----------------------------------------------------------------------------
// Purpose: Makes a splash when the player transitions between water states
//-----------------------------------------------------------------------------
void CHL2_Player::Splash( void )
{
CEffectData data;
data.m_fFlags = 0;
data.m_vOrigin = GetAbsOrigin();
data.m_vNormal = Vector(0,0,1);
data.m_vAngles = QAngle( 0, 0, 0 );
if ( GetWaterType() & CONTENTS_SLIME )
{
data.m_fFlags |= FX_WATER_IN_SLIME;
}
float flSpeed = GetAbsVelocity().Length();
if ( flSpeed < 300 )
{
data.m_flScale = random->RandomFloat( 10, 12 );
DispatchEffect( "waterripple", data );
}
else
{
data.m_flScale = random->RandomFloat( 6, 8 );
DispatchEffect( "watersplash", data );
}
}
CLogicPlayerProxy *CHL2_Player::GetPlayerProxy( void )
{
CLogicPlayerProxy *pProxy = dynamic_cast< CLogicPlayerProxy* > ( m_hPlayerProxy.Get() );
if ( pProxy == NULL )
{
pProxy = (CLogicPlayerProxy*)gEntList.FindEntityByClassname(NULL, "logic_playerproxy" );
if ( pProxy == NULL )
return NULL;
pProxy->m_hPlayer = this;
m_hPlayerProxy = pProxy;
}
return pProxy;
}
void CHL2_Player::FirePlayerProxyOutput( const char *pszOutputName, variant_t variant, CBaseEntity *pActivator, CBaseEntity *pCaller )
{
if ( GetPlayerProxy() == NULL )
return;
GetPlayerProxy()->FireNamedOutput( pszOutputName, variant, pActivator, pCaller );
}
LINK_ENTITY_TO_CLASS( logic_playerproxy, CLogicPlayerProxy);
BEGIN_DATADESC( CLogicPlayerProxy )
DEFINE_OUTPUT( m_OnFlashlightOn, "OnFlashlightOn" ),
DEFINE_OUTPUT( m_OnFlashlightOff, "OnFlashlightOff" ),
DEFINE_OUTPUT( m_RequestedPlayerHealth, "PlayerHealth" ),
DEFINE_OUTPUT( m_PlayerHasAmmo, "PlayerHasAmmo" ),
DEFINE_OUTPUT( m_PlayerHasNoAmmo, "PlayerHasNoAmmo" ),
DEFINE_OUTPUT( m_PlayerDied, "PlayerDied" ),
DEFINE_OUTPUT( m_PlayerMissedAR2AltFire, "PlayerMissedAR2AltFire" ),
DEFINE_INPUTFUNC( FIELD_VOID, "RequestPlayerHealth", InputRequestPlayerHealth ),
DEFINE_INPUTFUNC( FIELD_VOID, "SetFlashlightSlowDrain", InputSetFlashlightSlowDrain ),
DEFINE_INPUTFUNC( FIELD_VOID, "SetFlashlightNormalDrain", InputSetFlashlightNormalDrain ),
DEFINE_INPUTFUNC( FIELD_INTEGER, "SetPlayerHealth", InputSetPlayerHealth ),
DEFINE_INPUTFUNC( FIELD_VOID, "RequestAmmoState", InputRequestAmmoState ),
DEFINE_INPUTFUNC( FIELD_VOID, "LowerWeapon", InputLowerWeapon ),
DEFINE_INPUTFUNC( FIELD_VOID, "EnableCappedPhysicsDamage", InputEnableCappedPhysicsDamage ),
DEFINE_INPUTFUNC( FIELD_VOID, "DisableCappedPhysicsDamage", InputDisableCappedPhysicsDamage ),
DEFINE_INPUTFUNC( FIELD_STRING, "SetLocatorTargetEntity", InputSetLocatorTargetEntity ),
DEFINE_FIELD( m_hPlayer, FIELD_EHANDLE ),
END_DATADESC()
void CLogicPlayerProxy::Activate( void )
{
BaseClass::Activate();
if ( m_hPlayer == NULL )
{
m_hPlayer = AI_GetSinglePlayer();
}
}
bool CLogicPlayerProxy::PassesDamageFilter( const CTakeDamageInfo &info )
{
if (m_hDamageFilter)
{
CBaseFilter *pFilter = (CBaseFilter *)(m_hDamageFilter.Get());
return pFilter->PassesDamageFilter(info);
}
return true;
}
void CLogicPlayerProxy::InputSetPlayerHealth( inputdata_t &inputdata )
{
if ( m_hPlayer == NULL )
return;
m_hPlayer->SetHealth( inputdata.value.Int() );
}
void CLogicPlayerProxy::InputRequestPlayerHealth( inputdata_t &inputdata )
{
if ( m_hPlayer == NULL )
return;
m_RequestedPlayerHealth.Set( m_hPlayer->GetHealth(), inputdata.pActivator, inputdata.pCaller );
}
void CLogicPlayerProxy::InputSetFlashlightSlowDrain( inputdata_t &inputdata )
{
if( m_hPlayer == NULL )
return;
CHL2_Player *pPlayer = dynamic_cast<CHL2_Player*>(m_hPlayer.Get());
if( pPlayer )
pPlayer->SetFlashlightPowerDrainScale( hl2_darkness_flashlight_factor.GetFloat() );
}
void CLogicPlayerProxy::InputSetFlashlightNormalDrain( inputdata_t &inputdata )
{
if( m_hPlayer == NULL )
return;
CHL2_Player *pPlayer = dynamic_cast<CHL2_Player*>(m_hPlayer.Get());
if( pPlayer )
pPlayer->SetFlashlightPowerDrainScale( 1.0f );
}
void CLogicPlayerProxy::InputRequestAmmoState( inputdata_t &inputdata )
{
if( m_hPlayer == NULL )
return;
CHL2_Player *pPlayer = dynamic_cast<CHL2_Player*>(m_hPlayer.Get());
for ( int i = 0 ; i < pPlayer->WeaponCount(); ++i )
{
CBaseCombatWeapon* pCheck = pPlayer->GetWeapon( i );
if ( pCheck )
{
if ( pCheck->HasAnyAmmo() && (pCheck->UsesPrimaryAmmo() || pCheck->UsesSecondaryAmmo()))
{
m_PlayerHasAmmo.FireOutput( this, this, 0 );
return;
}
}
}
m_PlayerHasNoAmmo.FireOutput( this, this, 0 );
}
void CLogicPlayerProxy::InputLowerWeapon( inputdata_t &inputdata )
{
if( m_hPlayer == NULL )
return;
CHL2_Player *pPlayer = dynamic_cast<CHL2_Player*>(m_hPlayer.Get());
pPlayer->Weapon_Lower();
}
void CLogicPlayerProxy::InputEnableCappedPhysicsDamage( inputdata_t &inputdata )
{
if( m_hPlayer == NULL )
return;
CHL2_Player *pPlayer = dynamic_cast<CHL2_Player*>(m_hPlayer.Get());
pPlayer->EnableCappedPhysicsDamage();
}
void CLogicPlayerProxy::InputDisableCappedPhysicsDamage( inputdata_t &inputdata )
{
if( m_hPlayer == NULL )
return;
CHL2_Player *pPlayer = dynamic_cast<CHL2_Player*>(m_hPlayer.Get());
pPlayer->DisableCappedPhysicsDamage();
}
void CLogicPlayerProxy::InputSetLocatorTargetEntity( inputdata_t &inputdata )
{
if( m_hPlayer == NULL )
return;
CBaseEntity *pTarget = NULL; // assume no target
string_t iszTarget = MAKE_STRING( inputdata.value.String() );
if( iszTarget != NULL_STRING )
{
pTarget = gEntList.FindEntityByName( NULL, iszTarget );
}
CHL2_Player *pPlayer = dynamic_cast<CHL2_Player*>(m_hPlayer.Get());
pPlayer->SetLocatorTargetEntity(pTarget);
}
| [
"MadKowa@ec9d42d2-91e1-33f0-ec5d-f2a905d45d61"
] | MadKowa@ec9d42d2-91e1-33f0-ec5d-f2a905d45d61 |
773626907369c5ea8ebd4a13f1d339a9eb69f100 | 089985f5f295d6fc9b4d9a92cddb4d07cdc50c86 | /iOS/PrivateFrameworks/iWorkImport.framework/Frameworks/EquationKit.framework/Frameworks/KeynoteQuicklook.framework/Frameworks/NumbersQuicklook.framework/Frameworks/PagesQuicklook.framework/CDStructures.h | 88028f597d692f1e254eabb4873360324b20a977 | [] | no_license | lawrence-liuyue/Apple-Runtime-Headers | 6035855edbf558300c62bcf77c77cc38fcd08305 | 5e50ad05dfd7d7b69fc2e0e685765fc054166b3c | refs/heads/master | 2022-12-05T19:04:26.333712 | 2020-08-28T16:48:15 | 2020-08-28T16:48:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,408 | h | //
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Oct 15 2018 10:31:50).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//
#pragma mark Blocks
typedef void (^CDUnknownBlockType)(void); // return type and parameters are unknown
#pragma mark Named Structures
struct CGAffineTransform {
double a;
double b;
double c;
double d;
double tx;
double ty;
};
struct CGPoint {
double x;
double y;
};
struct CGRect {
struct CGPoint origin;
struct CGSize size;
};
struct CGSize {
double width;
double height;
};
struct TPSectionEnumerator {
id _field1;
unsigned long long _field2;
struct _NSRange _field3;
struct _NSRange _field4;
};
struct _NSRange {
unsigned long long location;
unsigned long long length;
};
struct __tree_end_node<std::__1::__tree_node_base<void *>*> {
struct __tree_node_base<void *> *__left_;
};
struct multimap<unsigned long, TPPageLayout *, std::__1::less<unsigned long>, std::__1::allocator<std::__1::pair<const unsigned long, TPPageLayout *>>> {
struct __tree<std::__1::__value_type<unsigned long, TPPageLayout *>, std::__1::__map_value_compare<unsigned long, std::__1::__value_type<unsigned long, TPPageLayout *>, std::__1::less<unsigned long>, true>, std::__1::allocator<std::__1::__value_type<unsigned long, TPPageLayout *>>> {
struct __tree_end_node<std::__1::__tree_node_base<void *>*> *__begin_node_;
struct __compressed_pair<std::__1::__tree_end_node<std::__1::__tree_node_base<void *>*>, std::__1::allocator<std::__1::__tree_node<std::__1::__value_type<unsigned long, TPPageLayout *>, void *>>> {
struct __tree_end_node<std::__1::__tree_node_base<void *>*> __value_;
} __pair1_;
struct __compressed_pair<unsigned long, std::__1::__map_value_compare<unsigned long, std::__1::__value_type<unsigned long, TPPageLayout *>, std::__1::less<unsigned long>, true>> {
unsigned long long __value_;
} __pair3_;
} __tree_;
};
struct pair<double, double> {
double _field1;
double _field2;
};
#pragma mark Typedef'd Structures
// Template types
typedef struct multimap<unsigned long, TPPageLayout *, std::__1::less<unsigned long>, std::__1::allocator<std::__1::pair<const unsigned long, TPPageLayout *>>> {
struct __tree<std::__1::__value_type<unsigned long, TPPageLayout *>, std::__1::__map_value_compare<unsigned long, std::__1::__value_type<unsigned long, TPPageLayout *>, std::__1::less<unsigned long>, true>, std::__1::allocator<std::__1::__value_type<unsigned long, TPPageLayout *>>> {
struct __tree_end_node<std::__1::__tree_node_base<void *>*> *__begin_node_;
struct __compressed_pair<std::__1::__tree_end_node<std::__1::__tree_node_base<void *>*>, std::__1::allocator<std::__1::__tree_node<std::__1::__value_type<unsigned long, TPPageLayout *>, void *>>> {
struct __tree_end_node<std::__1::__tree_node_base<void *>*> __value_;
} __pair1_;
struct __compressed_pair<unsigned long, std::__1::__map_value_compare<unsigned long, std::__1::__value_type<unsigned long, TPPageLayout *>, std::__1::less<unsigned long>, true>> {
unsigned long long __value_;
} __pair3_;
} __tree_;
} multimap_41f9c887;
typedef struct pair<double, double> {
double _field1;
double _field2;
} pair_b2618ff2;
| [
"leo.natan@outlook.com"
] | leo.natan@outlook.com |
5be211fd74576b7e73e66a860297b44757c22e53 | 4b3dee7793db94fcb5eedca5f0b39b4bc4364017 | /engine/FontRenderer.cpp | 36a0aaa660959570b010155585ca9da5679a88c6 | [] | no_license | shenchi/code_blank | 33917d1d3b19ca506accfd58fe3443bc6cf56eed | 74d775b557f268f84ea1bf75301aa5b5612aa661 | refs/heads/master | 2021-09-14T02:13:21.562526 | 2018-05-04T20:34:40 | 2018-05-04T20:34:40 | 115,167,180 | 0 | 1 | null | 2017-12-30T11:40:07 | 2017-12-23T03:20:51 | C++ | UTF-8 | C++ | false | false | 6,565 | cpp | #include "FontRenderer.h"
#include "Renderer.h"
#include "MemoryAllocator.h"
#include <cstring>
#include "TofuMath.h"
extern "C" {
#include <fontstash.h>
}
namespace
{
using namespace tofu;
int TofuRenderCreate(void* userPtr, int width, int height)
{
FontRendererContext* ctx = reinterpret_cast<FontRendererContext*>(userPtr);
CreateTextureParams* params = MemoryAllocator::FrameAlloc<CreateTextureParams>();
params->InitAsTexture2D(ctx->tex, width, height, kFormatR8Unorm);
ctx->cmdBuf->Add(RendererCommand::kCommandCreateTexture, params);
ctx->width = width;
ctx->height = height;
return 1;
}
int TofuRenderResize(void* userPtr, int width, int height)
{
FontRendererContext* ctx = reinterpret_cast<FontRendererContext*>(userPtr);
ctx->cmdBuf->Add(RendererCommand::kCommandDestroyTexture, &(ctx->tex));
if (1 != TofuRenderCreate(userPtr, width, height))
{
return 0;
}
ctx->updateRectX = 0;
ctx->updateRectY = 0;
ctx->updateRectW = ctx->width;
ctx->updateRectH = ctx->height;
return 1;
}
void TofuRenderUpdate(void* userPtr, int* rect, const unsigned char* data)
{
FontRendererContext* ctx = reinterpret_cast<FontRendererContext*>(userPtr);
int w = rect[2] - rect[0];
int h = rect[3] - rect[1];
if (!ctx->tex)
return;
ctx->texData = data;
if (ctx->updateRectW == 0 || ctx->updateRectH == 0)
{
ctx->updateRectX = rect[0];
ctx->updateRectY = rect[1];
ctx->updateRectW = w;
ctx->updateRectH = h;
}
else
{
int left = ctx->updateRectX;
int top = ctx->updateRectY;
int right = ctx->updateRectX + ctx->updateRectW;
int bottom = ctx->updateRectY + ctx->updateRectH;
left = math::min(left, rect[0]);
top = math::min(top, rect[1]);
right = math::max(right, rect[2]);
bottom = math::max(bottom, rect[3]);
ctx->updateRectX = left;
ctx->updateRectY = top;
ctx->updateRectW = right - left;
ctx->updateRectH = bottom - top;
}
}
void TofuRenderDraw(void* userPtr, const float* verts, const float* tcoords, const unsigned int* colors, int nverts)
{
FontRendererContext* ctx = reinterpret_cast<FontRendererContext*>(userPtr);
if (ctx->numVerts + nverts > ctx->maxVerts) return;
for (uint32_t i = 0; i < nverts; i++)
{
uint16_t vid = uint16_t(ctx->numVerts + i);
float* vert = ctx->vertices + (vid * 9);
*(vert + 0) = verts[i * 2 + 0];
*(vert + 1) = verts[i * 2 + 1];
*(vert + 2) = 0.0f;
*(vert + 3) = 1.0f;
*(vert + 4) = 1.0f;
*(vert + 5) = 1.0f;
*(vert + 6) = 1.0f;
*(vert + 7) = tcoords[i * 2 + 0];
*(vert + 8) = tcoords[i * 2 + 1];
}
ctx->numVerts += nverts;
}
void TofuRenderDelete(void* userPtr)
{
FontRendererContext* ctx = reinterpret_cast<FontRendererContext*>(userPtr);
ctx->cmdBuf->Add(RendererCommand::kCommandDestroyTexture, &(ctx->tex));
}
}
namespace tofu
{
int32_t FontRenderer::Setup(PipelineStateHandle pso, TextureHandle tex, SamplerHandle samp, BufferHandle vb, BufferHandle cb, uint32_t maxVertices)
{
this->pso = pso;
context.tex = tex;
this->samp = samp;
this->vb = vb;
this->cb = cb;
context.maxVerts = maxVertices;
return kOK;
}
int32_t FontRenderer::Init()
{
FONSparams params = {};
params.width = 1024;
params.height = 1024;
params.flags = FONS_ZERO_TOPLEFT;
params.userPtr = &context;
params.renderCreate = TofuRenderCreate;
params.renderResize = TofuRenderResize;
params.renderUpdate = TofuRenderUpdate;
params.renderDraw = TofuRenderDraw;
params.renderDelete = TofuRenderDelete;
fonsContext = fonsCreateInternal(¶ms);
if (nullptr == fonsContext)
return kErrUnknown;
font = fonsAddFont(fonsContext, "Conthrax Sb", "assets/conthrax-sb.ttf");
//font = fonsAddFont(fonsContext, "Arial Regular", "C:\\Windows\\Fonts\\arial.ttf");
//font = fonsAddFont(fonsContext, "sans", "D:\\DroidSerif-Regular.ttf");
if (font == FONS_INVALID) {
return kErrUnknown;
}
return kOK;
}
int32_t FontRenderer::Shutdown()
{
fonsDeleteInternal(fonsContext);
return kOK;
}
int32_t FontRenderer::Reset(RendererCommandBuffer* cmdBuf)
{
//if (nullptr == fonsContext) return kOK;
context.cmdBuf = cmdBuf;
context.vertices = reinterpret_cast<float*>(
MemoryAllocator::FrameAlloc(context.maxVerts * sizeof(float) * 9u)
);
context.numVerts = 0;
context.texData = nullptr;
context.updateRectX = 0;
context.updateRectY = 0;
context.updateRectW = 0;
context.updateRectH = 0;
return kOK;
}
int32_t FontRenderer::Render(const char * text, float x, float y)
{
float lh = 0;
fonsClearState(fonsContext);
fonsSetSize(fonsContext, 18.0f);
fonsSetFont(fonsContext, font);
fonsVertMetrics(fonsContext, nullptr, nullptr, &lh);
fonsSetColor(fonsContext, 0xffffffffu);
x = fonsDrawText(fonsContext, x, y + lh, text, nullptr);
return kOK;
}
int32_t FontRenderer::UploadTexture()
{
if (nullptr != context.texData && context.updateRectW > 0 && context.updateRectH > 0)
{
uint8_t* ptr = const_cast<uint8_t*>(context.texData);
ptr += context.updateRectX + context.updateRectY * context.width;
UpdateTextureParams* params = MemoryAllocator::FrameAlloc<UpdateTextureParams>();
params->handle = context.tex;
params->data = ptr;
params->pitch = context.width;
params->left = context.updateRectX;
params->top = context.updateRectY;
params->right = context.updateRectX + context.updateRectW;
params->bottom = context.updateRectY + context.updateRectH;
params->front = 0;
params->back = 1;
context.cmdBuf->Add(RendererCommand::kCommandUpdateTexture, params);
context.texData = nullptr;
context.updateRectX = 0;
context.updateRectY = 0;
context.updateRectW = 0;
context.updateRectH = 0;
}
return kOK;
}
int32_t FontRenderer::Submit()
{
if (context.numVerts == 0) return kOK;
{
UpdateBufferParams* params = MemoryAllocator::FrameAlloc<UpdateBufferParams>();
params->handle = vb;
params->data = context.vertices;
params->size = context.numVerts * sizeof(float) * 9u;
context.cmdBuf->Add(RendererCommand::kCommandUpdateBuffer, params);
}
{
DrawParams* params = MemoryAllocator::FrameAlloc<DrawParams>();
params->pipelineState = pso;
params->vertexBuffer = vb;
params->indexBuffer = BufferHandle();
params->vsConstantBuffers[0] = { cb, 0, 0 };
params->psShaderResources[0] = context.tex;
params->psSamplers[0] = samp;
params->indexCount = context.numVerts;
context.cmdBuf->Add(RendererCommand::kCommandDraw, params);
}
return kOK;
}
} | [
"shenchi710@gmail.com"
] | shenchi710@gmail.com |
67469017ab553267ea7d9221761cc14ea0e5d711 | c5df61ec848d64ade567218c24554f47cef011d6 | /Actions/EditStatement.cpp | b45ebd908f9a7a977e1af93e0beccd11775cefaf | [] | no_license | abdallahmagdy1993/Flowchart-Simulator | cfa46026bb4526a5698351ecb6a88157b3e40958 | 4a5350e0d5627bba6945833902e921c27521d6e3 | refs/heads/master | 2021-01-10T14:44:52.371199 | 2018-02-21T11:34:17 | 2018-02-21T11:34:17 | 53,350,385 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,536 | cpp | #include "EditStatement.h"
#include "..\ApplicationManager.h"
#include "..\Statements\Statement.h"
#include "..\GUI\input.h"
#include "..\GUI\Output.h"
#include <sstream>
using namespace std;
//constructor: set the ApplicationManager pointer inside this action
EditStatement::EditStatement(ApplicationManager *pAppManager):Action(pAppManager)
{Stat=NULL;}
void EditStatement::ReadActionParameters()
{
Input *pIn = pManager->GetInput();
Output *pOut = pManager->GetOutput();
Stat=pManager->GetSelectedStatement();
if(Stat==NULL)
{
pOut->PrintMessage("no selected Statement");
return;
}
}
void EditStatement::Execute()
{
ReadActionParameters();
Input *pIn = pManager->GetInput();
Output *pOut = pManager->GetOutput();
if(Stat==NULL)
return;
if(Stat->GetStatType()=="VAR"||Stat->GetStatType()=="SNGLOP"||Stat->GetStatType()=="COND")
{
pManager->deleteVariable(Stat->getVar(0));
pManager->deleteVariable(Stat->getVar(1));
}
else pManager->deleteVariable(Stat->getVar(0));
Stat->Edit(pOut,pIn);
if(Stat->GetStatType()=="VAR"||Stat->GetStatType()=="SNGLOP"||Stat->GetStatType()=="COND")
{
Variable *V=pManager->AddVariable(Stat->getVar(0));
if(V)
Stat->setVar(V,0);
V=pManager->AddVariable(Stat->getVar(1));
if(V)
Stat->setVar(V,1);
}
else {
Variable *V= pManager->AddVariable(Stat->getVar(0));
if(V)
Stat->setVar(V,0);
}
if(Stat->GetStatType()!="STRT"&&Stat->GetStatType()!="END")
Stat->PrintInfo(pOut);
pManager->setEditedDesign(true);
pManager->UndoRedo();
}
| [
"abdallahmagdy1993@gmail.com"
] | abdallahmagdy1993@gmail.com |
761aa352e617c854e196235dab5c7048c6175ef5 | 2a89b925f76509239527425939a16a710919ee21 | /Cubby-master/Sources/GameGUI/InventoryGUI.cpp | 54b1dbcd371e24206d2d58962d27f74fb7c10b3b | [] | no_license | Hamule/Cubbys | c7f595f80539190e4a01c89470c266a2e365d087 | d0a2e4b86a3b78e7a8457c33416c7199577ac075 | refs/heads/master | 2021-01-11T05:42:07.046885 | 2016-11-01T15:26:39 | 2016-11-01T15:26:39 | 71,549,076 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 62,388 | cpp | /*************************************************************************
> File Name: InventoryGUI.h
> Project Name: Cubby
> Author: Chan-Ho Chris Ohk
> Purpose: Inventory GUI class.
> Created Time: 2016/09/01
> Copyright (c) 2016, Chan-Ho Chris Ohk
*************************************************************************/
#include <algorithm>
#include <CubbyGame.h>
#include <Models/VoxelObject.h>
#include <Utils/Random.h>
#include "ActionBar.h"
#include "InventoryGUI.h"
// Constructor, Destructor
InventoryGUI::InventoryGUI(Renderer* pRenderer, OpenGLGUI* pGUI, FrontendManager* pFrontendManager, ChunkManager* pChunkManager, Player* pPlayer, InventoryManager* pInventoryManager, int windowWidth, int windowHeight)
{
m_pRenderer = pRenderer;
m_pGUI = pGUI;
m_pFrontendManager = pFrontendManager;
m_pChunkManager = pChunkManager;
m_pPlayer = pPlayer;
m_pInventoryManager = pInventoryManager;
m_windowWidth = windowWidth;
m_windowHeight = windowHeight;
// Inventory Window
m_pInventoryWindow = new GUIWindow(m_pRenderer, m_pFrontendManager->GetFrontendFontMedium(), "Inventory");
m_pInventoryWindow->AllowMoving(true);
m_pInventoryWindow->AllowClosing(false);
m_pInventoryWindow->AllowMinimizing(false);
m_pInventoryWindow->AllowScrolling(false);
m_pInventoryWindow->SetRenderTitleBar(true);
m_pInventoryWindow->SetRenderWindowBackground(true);
m_pInventoryWindow->SetApplicationDimensions(m_windowWidth, m_windowHeight);
m_pInventoryWindow->Hide();
m_pTitleBarIcon = new Icon(m_pRenderer, "", 44, 44);
m_pTitleBarIcon->SetDepth(4.0f);
m_pInventoryWindowBackgroundIcon = new Icon(m_pRenderer, "", 400, 211);
m_pInventoryWindowBackgroundIcon->SetDepth(1.0f);
m_pTitleBarBackgroundIcon = new Icon(m_pRenderer, "", 133, 35);
m_pTitleBarBackgroundIcon->SetDepth(1.0f);
m_pCloseExitButton = new Button(m_pRenderer, m_pFrontendManager->GetFrontendFont30(), m_pFrontendManager->GetFrontendFont30Outline(), "", Color(1.0f, 1.0f, 1.0f, 1.0f), Color(0.0f, 0.0f, 0.0f, 1.0f));
m_pCloseExitButton->SetLabelOffset(0, 5);
m_pCloseExitButton->SetCallBackFunction(_CloseExitPressed);
m_pCloseExitButton->SetCallBackData(this);
m_pDestroyIcon = new Icon(m_pRenderer, "", 175, 65);
m_pDestroyIcon->SetDepth(2.1f);
char destroyText[] = "DESTROY";
m_pDestroyLabel = new Label(m_pRenderer, m_pFrontendManager->GetFrontendFont50(), destroyText, Color(1.0f, 1.0f, 1.0f, 0.25f));
m_pDestroyLabel->SetOutline(true);
m_pDestroyLabel->SetOutlineColor(Color(0.0f, 0.0f, 0.0f, 1.0f));
m_pDestroyLabel->SetOutlineFont(m_pFrontendManager->GetFrontendFont50Outline());
m_pDestroyLabel->SetDepth(3.0f);
m_pDropIcon = new Icon(m_pRenderer, "", 175, 65);
m_pDropIcon->SetDepth(2.1f);
char dropText[] = "DROP";
m_pDropLabel = new Label(m_pRenderer, m_pFrontendManager->GetFrontendFont50(), dropText, Color(1.0f, 1.0f, 1.0f, 0.25f));
m_pDropLabel->SetOutline(true);
m_pDropLabel->SetOutlineColor(Color(0.0f, 0.0f, 0.0f, 1.0f));
m_pDropLabel->SetOutlineFont(m_pFrontendManager->GetFrontendFont50Outline());
m_pDropLabel->SetDepth(3.0f);
m_pInventoryWindow->SetBackgroundIcon(m_pInventoryWindowBackgroundIcon);
m_pInventoryWindow->SetTitlebarBackgroundIcon(m_pTitleBarBackgroundIcon);
m_pInventoryWindow->AddComponent(m_pTitleBarIcon);
m_pInventoryWindow->AddComponent(m_pCloseExitButton);
m_pInventoryBackgroundSlotBorderCommon = new Icon(m_pRenderer, "", 64, 64);
m_pInventoryBackgroundSlotBorderCommon->SetDepth(2.0f);
m_pInventoryBackgroundSlotBorderUncommon = new Icon(m_pRenderer, "", 64, 64);
m_pInventoryBackgroundSlotBorderUncommon->SetDepth(2.0f);
m_pInventoryBackgroundSlotBorderMagical = new Icon(m_pRenderer, "", 64, 64);
m_pInventoryBackgroundSlotBorderMagical->SetDepth(2.0f);
m_pInventoryBackgroundSlotBorderRare = new Icon(m_pRenderer, "", 64, 64);
m_pInventoryBackgroundSlotBorderRare->SetDepth(2.0f);
m_pInventoryBackgroundSlotBorderEpic = new Icon(m_pRenderer, "", 64, 64);
m_pInventoryBackgroundSlotBorderEpic->SetDepth(2.0f);
// Tooltip
m_pTooltipBackgroundCommon = new Icon(m_pRenderer, "", 200, 220);
m_pTooltipBackgroundCommon->SetDepth(5.5f);
m_pTooltipBackgroundUncommon = new Icon(m_pRenderer, "", 200, 220);
m_pTooltipBackgroundUncommon->SetDepth(5.5f);
m_pTooltipBackgroundMagical = new Icon(m_pRenderer, "", 200, 220);
m_pTooltipBackgroundMagical->SetDepth(5.5f);
m_pTooltipBackgroundRare = new Icon(m_pRenderer, "", 200, 220);
m_pTooltipBackgroundRare->SetDepth(5.5f);
m_pTooltipBackgroundEpic = new Icon(m_pRenderer, "", 200, 220);
m_pTooltipBackgroundEpic->SetDepth(5.5f);
char nameText[] = "[ITEM]";
m_pTooltipNameLabel = new Label(m_pRenderer, m_pFrontendManager->GetFrontendFont30(), nameText, Color(1.0f, 1.0f, 1.0f, 1.0f));
m_pTooltipNameLabel->SetOutline(true);
m_pTooltipNameLabel->SetOutlineColor(Color(0.0f, 0.0f, 0.0f, 1.0f));
m_pTooltipNameLabel->SetOutlineFont(m_pFrontendManager->GetFrontendFont30Outline());
m_pTooltipNameLabel->SetDepth(5.5f);
char descText[] = "[REPLACE ME]";
m_pTooltipDescriptionLabel = new FormattedLabel(m_pRenderer, m_pFrontendManager->GetFrontendFont25(), m_pFrontendManager->GetFrontendFont25(), m_pFrontendManager->GetFrontendFont25(), descText);
m_pTooltipDescriptionLabel->SetOutline(true);
m_pTooltipDescriptionLabel->SetColor(Color(1.0f, 1.0f, 1.0f, 1.0f));
m_pTooltipDescriptionLabel->SetOutlineColor(Color(0.0f, 0.0f, 0.0f, 1.0f));
m_pTooltipDescriptionLabel->SetOutlineFont(m_pFrontendManager->GetFrontendFont25Outline());
m_pTooltipDescriptionLabel->SetDepth(5.5f);
m_pTooltipDescriptionLabel->SetWordWrap(true);
char slotText[] = "[SLOT]";
m_pTooltipSlotLabel = new Label(m_pRenderer, m_pFrontendManager->GetFrontendFont20(), slotText, Color(0.5f, 0.5f, 0.5f, 1.0f));
m_pTooltipSlotLabel->SetOutline(true);
m_pTooltipSlotLabel->SetOutlineColor(Color(0.0f, 0.0f, 0.0f, 1.0f));
m_pTooltipSlotLabel->SetOutlineFont(m_pFrontendManager->GetFrontendFont20Outline());
m_pTooltipSlotLabel->SetDepth(5.5f);
char qualityText[] = "[QUALITY]";
m_pTooltipQualityLabel = new Label(m_pRenderer, m_pFrontendManager->GetFrontendFont20(), qualityText, Color(0.5f, 0.5f, 0.5f, 1.0f));
m_pTooltipQualityLabel->SetOutline(true);
m_pTooltipQualityLabel->SetOutlineColor(Color(0.0f, 0.0f, 0.0f, 1.0f));
m_pTooltipQualityLabel->SetOutlineFont(m_pFrontendManager->GetFrontendFont20Outline());
m_pTooltipQualityLabel->SetDepth(5.5f);
// Popup
char popupTitleText[] = "[POPUP TITLE]";
m_popupTitle = new Label(m_pRenderer, m_pFrontendManager->GetFrontendFont40(), popupTitleText, Color(1.0f, 0.0f, 0.0f, 1.0f));
m_popupTitle->SetOutline(true);
m_popupTitle->SetOutlineColor(Color(0.0f, 0.0f, 0.0f, 1.0f));
m_popupTitle->SetOutlineFont(m_pFrontendManager->GetFrontendFont40Outline());
m_popupTitle->SetDepth(9.0f);
char popupText[] = "[POPUP TEXT]";
m_popupText = new FormattedLabel(m_pRenderer, m_pFrontendManager->GetFrontendFont25(), m_pFrontendManager->GetFrontendFont25(), m_pFrontendManager->GetFrontendFont25(), popupText);
m_popupText->SetOutline(true);
m_popupText->SetColor(Color(1.0f, 1.0f, 1.0f, 1.0f));
m_popupText->SetOutlineColor(Color(0.0f, 0.0f, 0.0f, 1.0f));
m_popupText->SetOutlineFont(m_pFrontendManager->GetFrontendFont25Outline());
m_popupText->SetDepth(9.0f);
m_popupText->SetWordWrap(true);
m_popupText->SetHorizontalAlignment(HorizontalAlignment::Center);
m_pPopupBackgroundIcon = new Icon(m_pRenderer, "", 270, 200);
m_pPopupBackgroundIcon->SetDepth(2.0f);
m_pPopupConfirmButton = new Button(m_pRenderer, m_pFrontendManager->GetFrontendFont30(), m_pFrontendManager->GetFrontendFont30Outline(), "Yes", Color(1.0f, 1.0f, 1.0f, 1.0f), Color(0.0f, 0.0f, 0.0f, 1.0f));
m_pPopupConfirmButton->SetLabelOffset(0, 3);
m_pPopupConfirmButton->SetPressedOffset(0, -4);
m_pPopupConfirmButton->SetCallBackFunction(_PopupConfirmPressed);
m_pPopupConfirmButton->SetCallBackData(this);
m_pPopupConfirmButton->SetDepth(9.0f);
m_pPopupCancelButton = new Button(m_pRenderer, m_pFrontendManager->GetFrontendFont30(), m_pFrontendManager->GetFrontendFont30Outline(), "No", Color(1.0f, 1.0f, 1.0f, 1.0f), Color(0.0f, 0.0f, 0.0f, 1.0f));
m_pPopupCancelButton->SetLabelOffset(0, 3);
m_pPopupCancelButton->SetPressedOffset(0, -4);
m_pPopupCancelButton->SetCallBackFunction(_PopupCancelPressed);
m_pPopupCancelButton->SetCallBackData(this);
m_pPopupCancelButton->SetDepth(9.1f);
SetWindowDimensions(m_windowWidth, m_windowHeight);
m_pInventoryItemToDelete = nullptr;
// Load delay
m_loadDelay = false;
m_loadDelayTime = 0.0f;
m_loaded = false;
}
InventoryGUI::~InventoryGUI()
{
delete m_pInventoryWindow;
delete m_pTitleBarIcon;
delete m_pTitleBarBackgroundIcon;
delete m_pInventoryWindowBackgroundIcon;
delete m_pCloseExitButton;
delete m_pDestroyIcon;
delete m_pDestroyLabel;
delete m_pDropIcon;
delete m_pDropLabel;
delete m_pInventoryBackgroundSlotBorderCommon;
delete m_pInventoryBackgroundSlotBorderUncommon;
delete m_pInventoryBackgroundSlotBorderMagical;
delete m_pInventoryBackgroundSlotBorderRare;
delete m_pInventoryBackgroundSlotBorderEpic;
// Tooltip
delete m_pTooltipBackgroundCommon;
delete m_pTooltipBackgroundUncommon;
delete m_pTooltipBackgroundMagical;
delete m_pTooltipBackgroundRare;
delete m_pTooltipBackgroundEpic;
delete m_pTooltipNameLabel;
delete m_pTooltipDescriptionLabel;
delete m_pTooltipSlotLabel;
delete m_pTooltipQualityLabel;
// Popup
delete m_popupTitle;
delete m_popupText;
delete m_pPopupConfirmButton;
delete m_pPopupCancelButton;
delete m_pPopupBackgroundIcon;
}
void InventoryGUI::SetCharacterGUI(CharacterGUI* pCharacterGUI)
{
m_pCharacterGUI = pCharacterGUI;
}
void InventoryGUI::SetLootGUI(LootGUI* pLootGUI)
{
m_pLootGUI = pLootGUI;
}
void InventoryGUI::SetActionBar(ActionBar* pActionBar)
{
m_pActionBar = pActionBar;
}
void InventoryGUI::SetItemManager(ItemManager *pItemManager)
{
m_pItemManager = pItemManager;
}
// Skinning the GUI
void InventoryGUI::SkinGUI()
{
std::string themeName = CubbyGame::GetInstance()->GetModsManager()->GetHUDTextureTheme();
std::string iconName = "Resources/textures/gui/" + themeName + "/InventoryGUI/inventory_title_icon.tga";
m_pTitleBarIcon->SetIcon(iconName);
iconName = "Resources/textures/gui/" + themeName + "/InventoryGUI/inventory_window_background.tga";
m_pInventoryWindowBackgroundIcon->SetIcon(iconName);
iconName = "Resources/textures/gui/" + themeName + "/InventoryGUI/titlebar_background.tga";
m_pTitleBarBackgroundIcon->SetIcon(iconName);
m_pInventoryWindow->SetBackgroundIcon(m_pInventoryWindowBackgroundIcon);
m_pInventoryWindow->SetTitlebarBackgroundIcon(m_pTitleBarBackgroundIcon);
Point location = m_pInventoryWindow->GetLocation();
m_pInventoryWindow->SetDimensions(location.x, location.y, m_inventoryWindowWidth, m_inventoryWindowHeight);
m_pInventoryWindow->SetTitleBarDimensions(0, 0, m_titlebarWidth, m_titlebarHeight);
iconName = "Resources/textures/gui/" + themeName + "/InventoryGUI/delete_background.tga";
m_pDestroyIcon->SetIcon(iconName);
iconName = "Resources/textures/gui/" + themeName + "/InventoryGUI/drop_background.tga";
m_pDropIcon->SetIcon(iconName);
iconName = "Resources/textures/gui/" + themeName + "/common/popup_background.tga";
m_pPopupBackgroundIcon->SetIcon(iconName);
m_pFrontendManager->SetButtonIcons(m_pPopupConfirmButton, ButtonSize::Size110x47);
m_pFrontendManager->SetButtonIcons(m_pPopupCancelButton, ButtonSize::Size110x47);
m_pCloseExitButton->SetDefaultIcon(m_pFrontendManager->GetCloseExitButtonIcon());
m_pCloseExitButton->SetHoverIcon(m_pFrontendManager->GetCloseExitButtonIconHover());
m_pCloseExitButton->SetSelectedIcon(m_pFrontendManager->GetCloseExitButtonIconPressed());
m_pCloseExitButton->SetDisabledIcon(m_pFrontendManager->GetCloseExitButtonIcon());
iconName = "Resources/textures/gui/" + themeName + "/common/items/border_common.tga";
m_pInventoryBackgroundSlotBorderCommon->SetIcon(iconName);
iconName = "Resources/textures/gui/" + themeName + "/common/items/border_uncommon.tga";
m_pInventoryBackgroundSlotBorderUncommon->SetIcon(iconName);
iconName = "Resources/textures/gui/" + themeName + "/common/items/border_magical.tga";
m_pInventoryBackgroundSlotBorderMagical->SetIcon(iconName);
iconName = "Resources/textures/gui/" + themeName + "/common/items/border_rare.tga";
m_pInventoryBackgroundSlotBorderRare->SetIcon(iconName);
iconName = "Resources/textures/gui/" + themeName + "/common/items/border_epic.tga";
m_pInventoryBackgroundSlotBorderEpic->SetIcon(iconName);
iconName = "Resources/textures/gui/" + themeName + "/common/Tooltips/tooltip_background_common.tga";
m_pTooltipBackgroundCommon->SetIcon(iconName);
iconName = "Resources/textures/gui/" + themeName + "/common/Tooltips/tooltip_background_uncommon.tga";
m_pTooltipBackgroundUncommon->SetIcon(iconName);
iconName = "Resources/textures/gui/" + themeName + "/common/Tooltips/tooltip_background_magical.tga";
m_pTooltipBackgroundMagical->SetIcon(iconName);
iconName = "Resources/textures/gui/" + themeName + "/common/Tooltips/tooltip_background_rare.tga";
m_pTooltipBackgroundRare->SetIcon(iconName);
iconName = "Resources/textures/gui/" + themeName + "/common/Tooltips/tooltip_background_epic.tga";
m_pTooltipBackgroundEpic->SetIcon(iconName);
m_pPopupConfirmButton->SetNormalLabelColor(m_pFrontendManager->GetNormalFontColor());
m_pPopupConfirmButton->SetHoverLabelColor(m_pFrontendManager->GetHoverFontColor());
m_pPopupConfirmButton->SetPressedLabelColor(m_pFrontendManager->GetPressedFontColor());
m_pPopupCancelButton->SetNormalLabelColor(m_pFrontendManager->GetNormalFontColor());
m_pPopupCancelButton->SetHoverLabelColor(m_pFrontendManager->GetHoverFontColor());
m_pPopupCancelButton->SetPressedLabelColor(m_pFrontendManager->GetPressedFontColor());
m_pInventoryManager->SetInventoryGUINeedsUpdate(true);
}
// ReSharper disable once CppMemberFunctionMayBeStatic
void InventoryGUI::UnSkinGUI() const
{
// Do nothing
}
// Loading
void InventoryGUI::Load(bool loadDelay, float loadDelayTime)
{
m_loadDelay = loadDelay;
m_loadDelayTime = loadDelayTime;
if (m_pInventoryManager->InventoryGUINeedsUpdate())
{
DeleteInventoryItems();
CreateInventoryItems();
UpdateActionBar();
for (size_t i = 0; i < m_vpInventorySlotItems.size(); ++i)
{
m_pInventoryWindow->AddComponent(m_vpInventorySlotItems[i]->m_pInventoryIcon);
}
}
if (m_loadDelay == false)
{
m_pGUI->AddWindow(m_pInventoryWindow);
m_pInventoryWindow->Show();
}
m_pPopupConfirmButton->SetLabelColor(m_pFrontendManager->GetNormalFontColor());
m_pPopupCancelButton->SetLabelColor(m_pFrontendManager->GetNormalFontColor());
m_pressedX = 0;
m_pressedY = 0;
m_pPressedInventoryItem = nullptr;
m_toolTipVisible = false;
m_tooltipAppearDelayTimer = 0.0f;
m_toolTipComponentsAdded = false;
m_tooltipQuality = ItemQuality::Common;
m_pInventoryItemToDelete = nullptr;
m_loaded = true;
}
void InventoryGUI::Unload()
{
m_loadDelay = false;
m_loadDelayTime = 0.0f;
HideTooltip();
m_pGUI->RemoveWindow(m_pInventoryWindow);
if (m_pPressedInventoryItem != nullptr)
{
m_pPressedInventoryItem->m_pInventoryIcon->SetDepth(3.0f);
m_pInventoryWindow->DepthSortComponentChildren();
m_pPressedInventoryItem->m_pInventoryIcon->SetLocation(m_pressedX, m_pressedY);
}
ClosePopup();
m_pGUI->RemoveComponent(m_pPopupBackgroundIcon);
m_pInventoryWindow->RemoveComponent(m_pDestroyIcon);
m_pInventoryWindow->RemoveComponent(m_pDestroyLabel);
m_pInventoryWindow->RemoveComponent(m_pDropIcon);
m_pInventoryWindow->RemoveComponent(m_pDropLabel);
m_loaded = false;
if (CubbyGame::GetInstance()->IsGUIWindowStillDisplayed() == false)
{
CubbyGame::GetInstance()->TurnCursorOff(false);
if (CubbyGame::GetInstance()->ShouldRestorePreviousCameraMode())
{
CubbyGame::GetInstance()->RestorePreviousCameraMode();
CubbyGame::GetInstance()->InitializeCameraRotation();
}
}
}
bool InventoryGUI::IsLoadDelayed() const
{
return (m_loadDelay == true && m_loadDelayTime > 0.0f);
}
void InventoryGUI::SetWindowDimensions(int windowWidth, int windowHeight)
{
m_windowWidth = windowWidth;
m_windowHeight = windowHeight;
m_inventoryWindowWidth = 412;
m_inventoryWindowHeight = 212;
m_titlebarWidth = 153;
m_titlebarHeight = 35;
m_popupWidth = 270;
m_popupHeight = 200;
m_popupBorderSpacer = 25;
m_popupTitleSpacer = 35;
m_popupIconSize = 50;
m_popupIconSpacer = 10;
m_pInventoryWindow->SetDimensions(m_windowWidth - 434, 175, m_inventoryWindowWidth, m_inventoryWindowHeight);
m_pInventoryWindow->SetTitleBarDimensions(0, 0, m_titlebarWidth, m_titlebarHeight);
m_pInventoryWindow->SetTitleOffset(50, 5);
m_pInventoryWindow->SetApplicationDimensions(m_windowWidth, m_windowHeight);
m_pInventoryWindow->SetApplicationBorder(25, 15, 10, 40);
m_pTitleBarIcon->SetDimensions(0, m_inventoryWindowHeight, 44, 44);
m_pCloseExitButton->SetDimensions(m_inventoryWindowWidth - 32, m_inventoryWindowHeight, 32, 32);
int x;
int y;
int width;
int height;
GetDestroySlotDimensions(&x, &y, &width, &height);
m_pDestroyIcon->SetDimensions(x, y, width, height);
int textWidth = m_pRenderer->GetFreeTypeTextWidth(m_pFrontendManager->GetFrontendFont50(), "%s", m_pDestroyLabel->GetText().c_str());
int textHeight = m_pRenderer->GetFreeTypeTextHeight(m_pFrontendManager->GetFrontendFont50(), "%s", m_pDestroyLabel->GetText().c_str());
m_pDestroyLabel->SetLocation(x + static_cast<int>((width * 0.5f) - (textWidth * 0.5f)), y + static_cast<int>((height * 0.5f) - (textHeight * 0.5f)) + 5);
GetDropSlotDimensions(&x, &y, &width, &height);
m_pDropIcon->SetDimensions(x, y, width, height);
textWidth = m_pRenderer->GetFreeTypeTextWidth(m_pFrontendManager->GetFrontendFont50(), "%s", m_pDropLabel->GetText().c_str());
textHeight = m_pRenderer->GetFreeTypeTextHeight(m_pFrontendManager->GetFrontendFont50(), "%s", m_pDropLabel->GetText().c_str());
m_pDropLabel->SetLocation(x + static_cast<int>((width * 0.5f) - (textWidth * 0.5f)), y + static_cast<int>((height * 0.5f) - (textHeight * 0.5f)) + 5);
// Popup
m_pPopupBackgroundIcon->SetDimensions(static_cast<int>((windowWidth * 0.5f) - (m_popupWidth * 0.5f)), static_cast<int>((windowHeight * 0.5f) - (m_popupHeight * 0.5f)) + 100, m_popupWidth, m_popupHeight);
}
// ReSharper disable once CppMemberFunctionMayBeStatic
void InventoryGUI::GetInventoryDimensions(int indexX, int indexY, int* x, int* y, int* width, int *height) const
{
int slotSize = 64;
int slotSpacer = 4;
int borderSize = 4;
int xSlotPos = borderSize + ((slotSize + slotSpacer) * indexX);
int ySlotPos = 4 + borderSize + ((slotSize + slotSpacer) * indexY);
*x = xSlotPos;
*y = ySlotPos;
*width = slotSize;
*height = slotSize;
}
// ReSharper disable once CppMemberFunctionMayBeStatic
void InventoryGUI::GetDestroySlotDimensions(int* x, int* y, int* width, int* height) const
{
*x = 220;
*y = -75;
*width = 175;
*height = 65;
}
// ReSharper disable once CppMemberFunctionMayBeStatic
void InventoryGUI::GetDropSlotDimensions(int* x, int* y, int* width, int* height) const
{
*x = 10;
*y = -75;
*width = 175;
*height = 65;
}
GUIWindow* InventoryGUI::GetInventoryWindow() const
{
return m_pInventoryWindow;
}
void InventoryGUI::CreateInventoryItems()
{
// Item draggable Buttons
for (int i = 0; i < MAX_NUM_SLOTS_VERTICAL; ++i)
{
for (int j = 0; j < MAX_NUM_SLOTS_HORIZONTAL; ++j)
{
InventoryItem* pItem = m_pInventoryManager->GetInventoryItemForSlot(j, i);
if (pItem != nullptr)
{
int x;
int y;
int width;
int height;
GetInventoryDimensions(j, i, &x, &y, &width, &height);
DraggableRenderRectangle* pNewSlotItem = new DraggableRenderRectangle(m_pRenderer);
switch (pItem->m_itemQuality)
{
case ItemQuality::Common: { pNewSlotItem->SetIcon(m_pInventoryBackgroundSlotBorderCommon); break; }
case ItemQuality::Uncommon: { pNewSlotItem->SetIcon(m_pInventoryBackgroundSlotBorderUncommon); break; }
case ItemQuality::Magical: { pNewSlotItem->SetIcon(m_pInventoryBackgroundSlotBorderMagical); break; }
case ItemQuality::Rare: { pNewSlotItem->SetIcon(m_pInventoryBackgroundSlotBorderRare); break; }
case ItemQuality::Epic: { pNewSlotItem->SetIcon(m_pInventoryBackgroundSlotBorderEpic); break; }
default: throw std::logic_error("Invalid ItemQuality in CreateInventoryItems()");
}
pNewSlotItem->SetDimensions(x, y, width, height);
pNewSlotItem->SetDepth(3.0f);
char itemTexture[128];
sprintf(itemTexture, "%s", pItem->m_iconFileName.c_str());
pNewSlotItem->AddIcon(m_pRenderer, itemTexture, 64, 64, 56, 56, 4, 4, 1.5f);
std::string themeName = CubbyGame::GetInstance()->GetModsManager()->GetHUDTextureTheme();
switch (pItem->m_itemQuality)
{
case ItemQuality::Common:
{
std::string itemBackgroundIcon = "Resources/textures/gui/" + themeName + "/common/items/item_background_common.tga";
pNewSlotItem->AddIcon(m_pRenderer, itemBackgroundIcon.c_str(), 64, 64, 64, 64, 0, 0, 1.0f);
break;
}
case ItemQuality::Uncommon:
{
std::string itemBackgroundIcon = "Resources/textures/gui/" + themeName + "/common/items/item_background_uncommon.tga";
pNewSlotItem->AddIcon(m_pRenderer, itemBackgroundIcon.c_str(), 64, 64, 64, 64, 0, 0, 1.0f);
break;
}
case ItemQuality::Magical:
{
std::string itemBackgroundIcon = "Resources/textures/gui/" + themeName + "/common/items/item_background_magical.tga";
pNewSlotItem->AddIcon(m_pRenderer, itemBackgroundIcon.c_str(), 64, 64, 64, 64, 0, 0, 1.0f);
break;
}
case ItemQuality::Rare:
{
std::string itemBackgroundIcon = "Resources/textures/gui/" + themeName + "/common/items/item_background_rare.tga";
pNewSlotItem->AddIcon(m_pRenderer, itemBackgroundIcon.c_str(), 64, 64, 64, 64, 0, 0, 1.0f);
break;
}
case ItemQuality::Epic:
{
std::string itemBackgroundIcon = "Resources/textures/gui/" + themeName + "/common/items/item_background_epic.tga";
pNewSlotItem->AddIcon(m_pRenderer, itemBackgroundIcon.c_str(), 64, 64, 64, 64, 0, 0, 1.0f);
break;
}
default: throw std::logic_error("Invalid ItemQuality in CreateInventoryItems()");
}
if (pItem->m_quantity != -1)
{
char quantity[128];
sprintf(quantity, "%i", pItem->m_quantity);
int textWidth = m_pRenderer->GetFreeTypeTextWidth(m_pFrontendManager->GetFrontendFont18(), "%s", quantity);
pNewSlotItem->AddText(m_pRenderer, m_pFrontendManager->GetFrontendFont18(), m_pFrontendManager->GetFrontendFont18Outline(), quantity, Color(1.0f, 1.0f, 1.0f, 1.0f), width - 10 - textWidth, 8, true, Color(0.0f, 0.0f, 0.0f, 1.0f));
}
InventorySlotItem* pNewItem = new InventorySlotItem();
pNewItem->m_pInventoryGUI = this;
pNewItem->m_pInventoryItem = pItem;
pNewItem->m_pInventoryIcon = pNewSlotItem;
pNewItem->m_slotX = j;
pNewItem->m_slotY = i;
pNewItem->m_dropshadowAdded = false;
pNewItem->m_erase = false;
m_vpInventorySlotItems.push_back(pNewItem);
pNewSlotItem->SetPressedCallBackFunction(_InventoryItemPressed);
pNewSlotItem->SetPressedCallBackData(pNewItem);
pNewSlotItem->SetReleasedCallBackFunction(_InventoryItemReleased);
pNewSlotItem->SetReleasedCallBackData(pNewItem);
pNewSlotItem->SetEnterCallBackFunction(_InventoryItemEntered);
pNewSlotItem->SetEnterCallBackData(pNewItem);
pNewSlotItem->SetExitCallBackFunction(_InventoryItemExited);
pNewSlotItem->SetExitCallBackData(pNewItem);
}
}
}
m_pInventoryManager->SetInventoryGUINeedsUpdate(false);
}
void InventoryGUI::DeleteInventoryItems()
{
// Clear item draggable buttons
for (size_t i = 0; i < m_vpInventorySlotItems.size(); ++i)
{
m_pInventoryWindow->RemoveComponent(m_vpInventorySlotItems[i]->m_pInventoryIcon);
delete m_vpInventorySlotItems[i]->m_pInventoryIcon;
m_vpInventorySlotItems[i]->m_pInventoryIcon = nullptr;
delete m_vpInventorySlotItems[i];
m_vpInventorySlotItems[i] = nullptr;
}
m_vpInventorySlotItems.clear();
}
void InventoryGUI::UpdateActionBar()
{
// We need to relink the action bar to the inventory GUI, since we have deleted and re-created the inventory buttons
for (size_t i = 0; i < m_vpInventorySlotItems.size(); ++i)
{
for (int j = 0; j < ActionBar::MAX_NUM_ACTION_SLOTS; ++j)
{
ActionButtonItem* pActionBarItem = m_pActionBar->GetActionButtonForSlot(j);
if (pActionBarItem != nullptr)
{
if (pActionBarItem->m_inventoryX == m_vpInventorySlotItems[i]->m_slotX && pActionBarItem->m_inventoryY == m_vpInventorySlotItems[i]->m_slotY)
{
if (pActionBarItem->m_inventoryX == -1 && pActionBarItem->m_inventoryY == -1)
{
if (pActionBarItem->m_equipSlot == m_vpInventorySlotItems[i]->m_pInventoryItem->m_equipSlot)
{
// In the situation where the loaded action button has a -1, -1 slot index, we also need to check the item slot type before assigning this pointer
pActionBarItem->m_itemTitle = m_vpInventorySlotItems[i]->m_pInventoryItem->m_title;
}
}
else
{
pActionBarItem->m_itemTitle = m_vpInventorySlotItems[i]->m_pInventoryItem->m_title;
}
}
}
}
}
}
// Tooltips
void InventoryGUI::UpdateToolTipAppear(float dt)
{
if (m_toolTipVisible)
{
if (m_tooltipAppearDelayTimer <= 0.0f)
{
if (m_toolTipComponentsAdded == false)
{
switch (m_tooltipQuality)
{
case ItemQuality::Common: { m_pInventoryWindow->AddComponent(m_pTooltipBackgroundCommon); break; }
case ItemQuality::Uncommon: { m_pInventoryWindow->AddComponent(m_pTooltipBackgroundUncommon); break; }
case ItemQuality::Magical: { m_pInventoryWindow->AddComponent(m_pTooltipBackgroundMagical); break; }
case ItemQuality::Rare: { m_pInventoryWindow->AddComponent(m_pTooltipBackgroundRare); break; }
case ItemQuality::Epic: { m_pInventoryWindow->AddComponent(m_pTooltipBackgroundEpic); break; }
default: throw std::logic_error("Invalid ItemQuality in UpdateToolTipAppear()");
}
m_pInventoryWindow->AddComponent(m_pTooltipNameLabel);
m_pInventoryWindow->AddComponent(m_pTooltipDescriptionLabel);
m_pInventoryWindow->AddComponent(m_pTooltipSlotLabel);
m_pInventoryWindow->AddComponent(m_pTooltipQualityLabel);
m_toolTipComponentsAdded = true;
}
}
else
{
m_tooltipAppearDelayTimer -= dt;
}
}
}
void InventoryGUI::ShowTooltip(InventorySlotItem* pInventoryItem)
{
if (m_toolTipVisible == true)
{
return;
}
// Set the focused window when we show a tooltip
m_pInventoryWindow->SetFocusWindow();
// Replace the tooltip name
m_pTooltipNameLabel->SetText(pInventoryItem->m_pInventoryItem->m_title);
// Replace the tooltip description
std::string DescriptionText = pInventoryItem->m_pInventoryItem->m_description + pInventoryItem->m_pInventoryItem->GetStatsAttributeString();
m_pTooltipDescriptionLabel->SetText(DescriptionText);
// Replace the tooltip equipslot text
char slotText[32];
switch (pInventoryItem->m_pInventoryItem->m_equipSlot)
{
case EquipSlot::NoSlot: { sprintf(slotText, ""); break; }
case EquipSlot::LeftHand:
{
if (pInventoryItem->m_pInventoryItem->m_right)
{
sprintf(slotText, "Two Handed");
}
else
{
sprintf(slotText, "Left Hand");
}
break;
}
case EquipSlot::RightHand:
{
if (pInventoryItem->m_pInventoryItem->m_left)
{
sprintf(slotText, "Two Handed");
}
else
{
sprintf(slotText, "Right Hand");
}
break;
}
case EquipSlot::Head: { sprintf(slotText, "Head"); break; }
case EquipSlot::Shoulders: { sprintf(slotText, "Shoulders"); break; }
case EquipSlot::Body: { sprintf(slotText, "Body"); break; }
case EquipSlot::Legs: { sprintf(slotText, "Legs"); break; }
case EquipSlot::Hand: { sprintf(slotText, "Hand"); break; }
case EquipSlot::Feet: { sprintf(slotText, "Feet"); break; }
case EquipSlot::Accessory1: { sprintf(slotText, "Accessory 1"); break; }
case EquipSlot::Accessory2: { sprintf(slotText, "Accessory 2"); break; }
default: throw std::logic_error("Invalid EquipSlot in ShowTooltip()");
}
m_pTooltipSlotLabel->SetText(slotText);
// Replace the tooltip quality text
char qualityText[32];
Color qualityColor;
switch (pInventoryItem->m_pInventoryItem->m_itemQuality)
{
case ItemQuality::Common: { sprintf(qualityText, "Common"); qualityColor = Color(0.5f, 0.5f, 0.5f, 1.0f); break; }
case ItemQuality::Uncommon: { sprintf(qualityText, "Uncommon"); qualityColor = Color(0.95f, 1.0f, 0.2f, 1.0f); break; }
case ItemQuality::Magical: { sprintf(qualityText, "Magical"); qualityColor = Color(0.0f, 1.0f, 0.0f, 1.0f); break; }
case ItemQuality::Rare: { sprintf(qualityText, "Rare"); qualityColor = Color(0.0f, 0.5f, 1.0f, 1.0f); break; }
case ItemQuality::Epic: { sprintf(qualityText, "Epic"); qualityColor = Color(0.64f, 0.2f, 0.93f, 1.0f); break; }
default: throw std::logic_error("Invalid ItemQuality in ShowTooltip()");
}
m_pTooltipQualityLabel->SetText(qualityText);
m_pTooltipQualityLabel->SetColor(qualityColor);
m_pTooltipNameLabel->SetColor(qualityColor);
// Set tooltip dimensions
m_tooltipWidth = 200;
m_tooltipHeight = 220;
m_tooltipDescBorder = 15;
int x;
int y;
int width;
int height;
GetInventoryDimensions(pInventoryItem->m_slotX, pInventoryItem->m_slotY, &x, &y, &width, &height);
if (CubbyGame::GetInstance()->GetWindowCursorX() > m_tooltipWidth + 50)
{
x = x + 20 - m_tooltipWidth;
}
else
{
x = x + 30;
}
if ((m_windowHeight - CubbyGame::GetInstance()->GetWindowCursorY()) > m_windowHeight - m_tooltipHeight - 50)
{
y = y + 20 - m_tooltipHeight;
}
else
{
y = y + 30;
}
m_pTooltipBackgroundCommon->SetDimensions(x, y, m_tooltipWidth, m_tooltipHeight);
m_pTooltipBackgroundUncommon->SetDimensions(x, y, m_tooltipWidth, m_tooltipHeight);
m_pTooltipBackgroundMagical->SetDimensions(x, y, m_tooltipWidth, m_tooltipHeight);
m_pTooltipBackgroundRare->SetDimensions(x, y, m_tooltipWidth, m_tooltipHeight);
m_pTooltipBackgroundEpic->SetDimensions(x, y, m_tooltipWidth, m_tooltipHeight);
int textWidth = m_pRenderer->GetFreeTypeTextWidth(m_pFrontendManager->GetFrontendFont30(), "%s", m_pTooltipNameLabel->GetText().c_str());
m_pTooltipNameLabel->SetLocation(x + static_cast<int>(m_tooltipWidth * 0.5f) - static_cast<int>(textWidth * 0.5f), y + m_tooltipHeight - 35);
m_pTooltipDescriptionLabel->SetDimensions(x + m_tooltipDescBorder, y + m_tooltipDescBorder, m_tooltipWidth - (m_tooltipDescBorder * 2), m_tooltipHeight - (m_tooltipDescBorder * 2) - 35);
m_pTooltipSlotLabel->SetLocation(x + m_tooltipDescBorder, y + m_tooltipDescBorder);
textWidth = m_pRenderer->GetFreeTypeTextWidth(m_pFrontendManager->GetFrontendFont20(), "%s", m_pTooltipQualityLabel->GetText().c_str());
m_pTooltipQualityLabel->SetLocation(x + m_tooltipWidth - m_tooltipDescBorder - textWidth, y + m_tooltipDescBorder);
m_tooltipQuality = pInventoryItem->m_pInventoryItem->m_itemQuality;
m_tooltipAppearDelayTimer = m_pFrontendManager->GetToolTipAppearDelay();
m_toolTipVisible = true;
m_toolTipComponentsAdded = false;
}
void InventoryGUI::HideTooltip()
{
m_pInventoryWindow->RemoveComponent(m_pTooltipBackgroundCommon);
m_pInventoryWindow->RemoveComponent(m_pTooltipBackgroundUncommon);
m_pInventoryWindow->RemoveComponent(m_pTooltipBackgroundMagical);
m_pInventoryWindow->RemoveComponent(m_pTooltipBackgroundRare);
m_pInventoryWindow->RemoveComponent(m_pTooltipBackgroundEpic);
m_pInventoryWindow->RemoveComponent(m_pTooltipNameLabel);
m_pInventoryWindow->RemoveComponent(m_pTooltipDescriptionLabel);
m_pInventoryWindow->RemoveComponent(m_pTooltipSlotLabel);
m_pInventoryWindow->RemoveComponent(m_pTooltipQualityLabel);
m_toolTipVisible = false;
}
void InventoryGUI::OpenPopup(std::string popupTitle, std::string popupText) const
{
m_pPopupConfirmButton->SetLabelColor(m_pFrontendManager->GetNormalFontColor());
m_pPopupCancelButton->SetLabelColor(m_pFrontendManager->GetNormalFontColor());
int textWidth = m_pRenderer->GetFreeTypeTextWidth(m_pFrontendManager->GetFrontendFont40(), "%s", popupTitle.c_str());
m_popupTitle->SetLocation(static_cast<int>((m_windowWidth * 0.5f) - (textWidth * 0.5f)), static_cast<int>((m_windowHeight * 0.5f) + (m_popupHeight * 0.5f)) - m_popupTitleSpacer - m_popupBorderSpacer + 100);
m_popupText->SetDimensions(static_cast<int>((m_windowWidth * 0.5f) - (m_popupWidth * 0.5f)) + m_popupBorderSpacer, static_cast<int>((m_windowHeight * 0.5f) - (m_popupHeight * 0.5f)) + 100, m_popupWidth - (m_popupBorderSpacer * 2), m_popupHeight - m_popupBorderSpacer - m_popupTitleSpacer);
m_pPopupConfirmButton->SetDimensions(static_cast<int>((m_windowWidth * 0.5f) + (m_popupWidth * 0.5f)) - static_cast<int>(m_popupBorderSpacer * 0.5f) - 110, static_cast<int>((m_windowHeight * 0.5f) - (m_popupIconSize * 0.5f)) - 50 + 100, 110, 47);
m_pPopupCancelButton->SetDimensions(static_cast<int>((m_windowWidth * 0.5f) - (m_popupWidth * 0.5f)) + static_cast<int>(m_popupBorderSpacer * 0.5f), static_cast<int>((m_windowHeight * 0.5f) - (m_popupIconSize * 0.5f)) - 50 + 100, 110, 47);
m_popupTitle->SetText(popupTitle);
m_popupText->SetText(popupText);
m_pGUI->AddComponent(m_popupTitle);
m_pGUI->AddComponent(m_popupText);
m_pGUI->AddComponent(m_pPopupConfirmButton);
m_pGUI->AddComponent(m_pPopupCancelButton);
m_pGUI->AddComponent(m_pPopupBackgroundIcon);
}
void InventoryGUI::ClosePopup() const
{
m_pGUI->RemoveComponent(m_popupTitle);
m_pGUI->RemoveComponent(m_popupText);
m_pGUI->RemoveComponent(m_pPopupConfirmButton);
m_pGUI->RemoveComponent(m_pPopupCancelButton);
m_pGUI->RemoveComponent(m_pPopupBackgroundIcon);
}
bool InventoryGUI::IsLoaded() const
{
return m_loaded;
}
InventorySlotItem* InventoryGUI::GetInventorySlotItem(int x, int y)
{
for (size_t i = 0; i < m_vpInventorySlotItems.size(); ++i)
{
if (m_vpInventorySlotItems[i]->m_slotX == x && m_vpInventorySlotItems[i]->m_slotY == y)
{
return m_vpInventorySlotItems[i];
}
}
return nullptr;
}
InventorySlotItem* InventoryGUI::GetInventorySlotItemEquipped(EquipSlot equipSlot)
{
InventoryItem* pInventoryItem = m_pInventoryManager->GetInventoryItemForEquipSlot(equipSlot);
if (pInventoryItem != nullptr)
{
for (size_t i = 0; i < m_vpInventorySlotItems.size(); ++i)
{
if (m_vpInventorySlotItems[i]->m_pInventoryItem == pInventoryItem)
{
return m_vpInventorySlotItems[i];
}
}
}
return nullptr;
}
void InventoryGUI::SetEquippedItem(EquipSlot equipSlot, std::string title)
{
m_pEquippedItems[static_cast<int>(equipSlot)] = title;
}
void InventoryGUI::SetBlockType(InventoryItem* pInventoryItem)
{
if (pInventoryItem->m_item == ItemType::BlockDirt)
{
m_pPlayer->SetNowBlock(ItemType::BlockDirt);
}
else if (pInventoryItem->m_item == ItemType::BlockSnow)
{
m_pPlayer->SetNowBlock(ItemType::BlockSnow);
}
else if (pInventoryItem->m_item == ItemType::BlockSand)
{
m_pPlayer->SetNowBlock(ItemType::BlockSand);
}
else if (pInventoryItem->m_item == ItemType::BlockWood)
{
m_pPlayer->SetNowBlock(ItemType::BlockWood);
}
else if (pInventoryItem->m_item == ItemType::BlockGrass)
{
m_pPlayer->SetNowBlock(ItemType::BlockGrass);
}
}
void InventoryGUI::EquipItem(InventoryItem* pInventoryItem, int inventoryX, int inventoryY)
{
// Set the player to know that we have equipped an item
m_pPlayer->EquipItem(pInventoryItem);
SetBlockType(pInventoryItem);
// If we already have an item in this equipment slot, switch it out
if (m_pEquippedItems[static_cast<int>(pInventoryItem->m_equipSlot)] != "")
{
m_pActionBar->UpdateActionBarSlots(m_pEquippedItems[static_cast<int>(pInventoryItem->m_equipSlot)], inventoryX, inventoryY);
}
m_pActionBar->UpdateActionBarSlots(pInventoryItem, -1, -1);
// Equip the new item
m_pEquippedItems[static_cast<int>(pInventoryItem->m_equipSlot)] = pInventoryItem->m_title;
}
void InventoryGUI::EquipItem(LootSlotItem* pLootItem) const
{
// Set the player to know that we have equipped an item
m_pPlayer->EquipItem(pLootItem->m_pInventoryItem);
}
void InventoryGUI::EquipItem(InventorySlotItem* pInventoryItem)
{
// Set the player to know that we have equipped an item
m_pPlayer->EquipItem(pInventoryItem->m_pInventoryItem);
// If we already have an item in this equipment slot, switch it out
if (m_pEquippedItems[static_cast<int>(pInventoryItem->m_pInventoryItem->m_equipSlot)] != "")
{
m_pActionBar->UpdateActionBarSlots(m_pEquippedItems[static_cast<int>(pInventoryItem->m_pInventoryItem->m_equipSlot)], pInventoryItem->m_slotX, pInventoryItem->m_slotY);
}
m_pActionBar->UpdateActionBarSlots(pInventoryItem->m_pInventoryItem, -1, -1);
// Equip the new item
m_pEquippedItems[static_cast<int>(pInventoryItem->m_pInventoryItem->m_equipSlot)] = pInventoryItem->m_pInventoryItem->m_title;
pInventoryItem->m_slotX = -1;
pInventoryItem->m_slotY = -1;
}
void InventoryGUI::UnequipItem(EquipSlot equipSlot, bool left, bool right)
{
m_pEquippedItems[static_cast<int>(equipSlot)] = "";
m_pPlayer->UnequipItem(equipSlot, left, right);
}
void InventoryGUI::Update(float dt)
{
if (m_loadDelay == true)
{
if (m_loadDelayTime <= 0.0f)
{
m_loadDelay = false;
m_pGUI->AddWindow(m_pInventoryWindow);
m_pInventoryWindow->Show();
}
else
{
m_loadDelayTime -= dt;
}
}
UpdateToolTipAppear(dt);
// Check if the inventory GUI needs update (we have moved items in the inventory or got new items)
if (m_pInventoryManager->InventoryGUINeedsUpdate() && IsLoaded() == true)
{
m_pGUI->RemoveWindow(m_pInventoryWindow);
DeleteInventoryItems();
CreateInventoryItems();
UpdateActionBar();
for (size_t i = 0; i < m_vpInventorySlotItems.size(); ++i)
{
m_pInventoryWindow->AddComponent(m_vpInventorySlotItems[i]->m_pInventoryIcon);
}
m_pGUI->AddWindow(m_pInventoryWindow);
m_pInventoryWindow->Show();
}
}
void InventoryGUI::_InventoryItemPressed(void* pData)
{
InventorySlotItem* pInventoryItem = static_cast<InventorySlotItem*>(pData);
pInventoryItem->m_pInventoryGUI->InventoryItemPressed(pInventoryItem);
}
void InventoryGUI::InventoryItemPressed(InventorySlotItem* pInventoryItem)
{
m_pPressedInventoryItem = pInventoryItem;
Dimensions dimensions = m_pPressedInventoryItem->m_pInventoryIcon->GetDimensions();
m_pressedX = dimensions.x;
m_pressedY = dimensions.y;
m_pInventoryWindow->AddComponent(m_pDestroyIcon);
m_pInventoryWindow->AddComponent(m_pDestroyLabel);
m_pInventoryWindow->AddComponent(m_pDropIcon);
m_pInventoryWindow->AddComponent(m_pDropLabel);
// Temporarily increase the depth of the dragged icon
if (m_pPressedInventoryItem->m_dropshadowAdded == false)
{
m_pPressedInventoryItem->m_dropshadowAdded = true;
m_pPressedInventoryItem->m_pInventoryIcon->SetDepth(5.0f);
//m_pPressedInventoryItem->m_pInventoryIcon->SetLocation(m_pressedX - 4, m_pressedY + 4);
std::string themeName = CubbyGame::GetInstance()->GetModsManager()->GetHUDTextureTheme();
std::string dropShadowIcon = "Resources/textures/gui/" + themeName + "/common/items/drop_shadow.tga";
m_pPressedInventoryItem->m_pInventoryIcon->AddIcon(m_pRenderer, dropShadowIcon.c_str(), 64, 64, 64, 64, 4, -4, 0.5f);
}
m_pInventoryWindow->DepthSortComponentChildren();
HideTooltip();
}
bool IsNeedErase(InventorySlotItem* item)
{
bool isNeedErase = item->m_erase;
if (isNeedErase == true)
{
delete item->m_pInventoryIcon;
delete item;
}
return isNeedErase;
}
void InventoryGUI::_InventoryItemReleased(void* pData)
{
InventorySlotItem* pInventoryItem = static_cast<InventorySlotItem*>(pData);
pInventoryItem->m_pInventoryGUI->InventoryItemReleased(pInventoryItem);
}
void InventoryGUI::InventoryItemReleased(InventorySlotItem* pInventoryItem)
{
if (m_pPressedInventoryItem == nullptr)
{
return;
}
m_pPressedInventoryItem = nullptr;
if (m_pPlayer->IsCrafting())
{
// Don't allow to do any inventory changing if we are crafting.
// Reset back to the original position
pInventoryItem->m_pInventoryIcon->SetLocation(m_pressedX, m_pressedY);
if (pInventoryItem->m_dropshadowAdded == true)
{
pInventoryItem->m_dropshadowAdded = false;
std::string themeName = CubbyGame::GetInstance()->GetModsManager()->GetHUDTextureTheme();
std::string dropShadowIcon = "Resources/textures/gui/" + themeName + "/common/items/drop_shadow.tga";
pInventoryItem->m_pInventoryIcon->RemoveIcon(dropShadowIcon.c_str());
}
m_pInventoryWindow->RemoveComponent(m_pDestroyIcon);
m_pInventoryWindow->RemoveComponent(m_pDestroyLabel);
m_pInventoryWindow->RemoveComponent(m_pDropIcon);
m_pInventoryWindow->RemoveComponent(m_pDropLabel);
return;
}
// Figure out if we need to change to a different inventory slot
int x;
int y;
int width;
int height;
POINT mouse = { CubbyGame::GetInstance()->GetWindowCursorX(), (m_windowHeight - CubbyGame::GetInstance()->GetWindowCursorY()) };
bool switched = false;
for (int i = 0; i < MAX_NUM_SLOTS_VERTICAL; ++i)
{
for (int j = 0; j < MAX_NUM_SLOTS_HORIZONTAL; ++j)
{
GetInventoryDimensions(j, i, &x, &y, &width, &height);
// Check if we released (mouse cursor) in the boundary of another slot
if (mouse.x > m_pInventoryWindow->GetDimensions().x + x && mouse.x < m_pInventoryWindow->GetDimensions().x + x + width && mouse.y > m_pInventoryWindow->GetDimensions().y + y && mouse.y < m_pInventoryWindow->GetDimensions().y + y + height)
{
if (pInventoryItem->m_pInventoryItem->m_equipped == true)
{
// Check if another inventory item already exists in this slot
InventorySlotItem* pInventorySlotItem = GetInventorySlotItem(j, i);
if (pInventorySlotItem == nullptr)
{
// We are unequipping an item that is in one of the equipment slots
m_pInventoryManager->UnequipItem(j, i, pInventoryItem->m_pInventoryItem->m_equipSlot);
UnequipItem(pInventoryItem->m_pInventoryItem->m_equipSlot, pInventoryItem->m_pInventoryItem->m_left, pInventoryItem->m_pInventoryItem->m_right);
// Set the new location for the released inventory icon
pInventoryItem->m_slotX = j;
pInventoryItem->m_slotY = i;
pInventoryItem->m_pInventoryIcon->SetLocation(x, y);
m_pActionBar->UpdateActionBarSlots(pInventoryItem->m_pInventoryItem, j, i);
switched = true;
}
else
{
if (pInventorySlotItem->m_pInventoryItem->m_equipSlot == pInventoryItem->m_pInventoryItem->m_equipSlot)
{
// We are swapping an equipped item for one in the inventory
UnequipItem(pInventoryItem->m_pInventoryItem->m_equipSlot, pInventoryItem->m_pInventoryItem->m_left, pInventoryItem->m_pInventoryItem->m_right);
m_pInventoryManager->UnequipItem(j, i, pInventoryItem->m_pInventoryItem->m_equipSlot);
// Equip the new item
//m_pInventoryManager->EquipInventoryItem(pInventorySlotItem->m_slotX, pInventorySlotItem->m_slotY, pInventorySlotItem->m_pInventoryItem->m_equipSlot);
EquipItem(pInventorySlotItem);
// Set the new location for the released inventory icon
pInventoryItem->m_slotX = j;
pInventoryItem->m_slotY = i;
pInventoryItem->m_pInventoryIcon->SetLocation(x, y);
switched = true;
}
}
}
else
{
// Check if another inventory item already exists in this slot
InventorySlotItem* pInventorySlotItem = GetInventorySlotItem(j, i);
// Switch the inventory item in this slot to the pressed (previous) position
if (pInventorySlotItem != nullptr)
{
pInventorySlotItem->m_slotX = pInventoryItem->m_slotX;
pInventorySlotItem->m_slotY = pInventoryItem->m_slotY;
pInventorySlotItem->m_pInventoryIcon->SetLocation(m_pressedX, m_pressedY);
m_pActionBar->UpdateActionBarSlots(pInventorySlotItem->m_pInventoryItem, pInventoryItem->m_slotX, pInventoryItem->m_slotY);
}
// Switch the items in the inventory manager
m_pInventoryManager->SwitchInventoryItems(pInventoryItem->m_slotX, pInventoryItem->m_slotY, j, i);
// Set the new location for the released inventory icon
pInventoryItem->m_slotX = j;
pInventoryItem->m_slotY = i;
pInventoryItem->m_pInventoryIcon->SetLocation(x, y);
m_pActionBar->UpdateActionBarSlots(pInventoryItem->m_pInventoryItem, j, i);
switched = true;
}
}
}
}
if (switched)
{
ShowTooltip(pInventoryItem);
}
bool equipped = false;
bool deleted = false;
if (switched == false)
{
if (pInventoryItem->m_pInventoryItem->m_equipSlot != EquipSlot::NoSlot)
{
// Check if we need to equip the item after dropping on the player portrait
if (m_pCharacterGUI->IsLoaded())
{
m_pCharacterGUI->GetPlayerPortraitDimensions(&x, &y, &width, &height);
GUIWindow* pCharacterWindow = m_pCharacterGUI->GetCharacterWindow();
if (mouse.x > pCharacterWindow->GetDimensions().x + x && mouse.x < pCharacterWindow->GetDimensions().x + x + width && mouse.y > pCharacterWindow->GetDimensions().y + y && mouse.y < pCharacterWindow->GetDimensions().y + y + height)
{
if (pInventoryItem->m_pInventoryItem->m_equipped == false)
{
// Dual handed weapon checks
if (pInventoryItem->m_pInventoryItem->m_equipSlot == EquipSlot::RightHand)
{
InventoryItem* pLeftHanded = m_pInventoryManager->GetInventoryItemForEquipSlot(EquipSlot::LeftHand);
if (pInventoryItem->m_pInventoryItem->m_left || (pLeftHanded != nullptr && pLeftHanded->m_right))
{
int slotX;
int slotY;
// Unequip the left hand slot since we are dual handed, OR the already equipped left hand item needs both hands
UnequipItem(EquipSlot::LeftHand, false, false);
if (m_pInventoryManager->UnequipItemToFreeInventorySlot(EquipSlot::LeftHand, &slotX, &slotY) == false)
{
// We can't fit the other item in the inventory
}
else if (pLeftHanded != nullptr)
{
m_pActionBar->UpdateActionBarSlots(pLeftHanded, slotX, slotY);
}
}
}
if (pInventoryItem->m_pInventoryItem->m_equipSlot == EquipSlot::LeftHand)
{
InventoryItem* pRightHanded = m_pInventoryManager->GetInventoryItemForEquipSlot(EquipSlot::RightHand);
if (pInventoryItem->m_pInventoryItem->m_right || (pRightHanded != nullptr && pRightHanded->m_left))
{
int slotX;
int slotY;
// Unequip the right hand slot since we are dual handed, OR the already equipped right hand item needs both hands
UnequipItem(EquipSlot::RightHand, false, false);
if (m_pInventoryManager->UnequipItemToFreeInventorySlot(EquipSlot::RightHand, &slotX, &slotY) == false)
{
// We can't fit the other item in the inventory
}
else if (pRightHanded != nullptr)
{
m_pActionBar->UpdateActionBarSlots(pRightHanded, slotX, slotY);
}
}
}
m_pPlayer->UnequipItem(pInventoryItem->m_pInventoryItem->m_equipSlot, pInventoryItem->m_pInventoryItem->m_left, pInventoryItem->m_pInventoryItem->m_right);
m_pInventoryManager->EquipInventoryItem(pInventoryItem->m_slotX, pInventoryItem->m_slotY, pInventoryItem->m_pInventoryItem->m_equipSlot);
EquipItem(pInventoryItem);
m_pInventoryWindow->RemoveComponent(pInventoryItem->m_pInventoryIcon);
pInventoryItem->m_erase = true;
m_vpInventorySlotItems.erase(remove_if(m_vpInventorySlotItems.begin(), m_vpInventorySlotItems.end(), IsNeedErase), m_vpInventorySlotItems.end());
m_pInventoryManager->SetInventoryGUINeedsUpdate(true);
m_pInventoryManager->SetCharacterGUINeedsUpdate(true);
m_pCharacterGUI->HideEquipHover();
equipped = true;
}
}
if (equipped == false)
{
// Check if we need to equip the item after dropping on a equipment slot
switch (pInventoryItem->m_pInventoryItem->m_equipSlot)
{
case EquipSlot::NoSlot: { x = 0; y = 0; width = 0; height = 0; } break;
case EquipSlot::RightHand: { m_pCharacterGUI->GetPlayerWeaponRightDimensions(&x, &y, &width, &height); } break;
case EquipSlot::LeftHand: { m_pCharacterGUI->GetPlayerWeaponLeftDimensions(&x, &y, &width, &height); } break;
case EquipSlot::Head: { m_pCharacterGUI->GetPlayerHeadDimensions(&x, &y, &width, &height); } break;
case EquipSlot::Shoulders: { m_pCharacterGUI->GetPlayerShoulderDimensions(&x, &y, &width, &height); } break;
case EquipSlot::Body: { m_pCharacterGUI->GetPlayerBodyDimensions(&x, &y, &width, &height); } break;
case EquipSlot::Legs: { m_pCharacterGUI->GetPlayerLegsDimensions(&x, &y, &width, &height); } break;
case EquipSlot::Hand: { m_pCharacterGUI->GetPlayerHandDimensions(&x, &y, &width, &height); } break;
case EquipSlot::Feet: { m_pCharacterGUI->GetPlayerFeetDimensions(&x, &y, &width, &height); } break;
case EquipSlot::Accessory1: { m_pCharacterGUI->GetPlayerAccessory1Dimensions(&x, &y, &width, &height); } break;
case EquipSlot::Accessory2: { m_pCharacterGUI->GetPlayerAccessory2Dimensions(&x, &y, &width, &height); } break;
default: throw std::logic_error("Invalid EquipSlot in InventoryItemReleased()");
}
GUIWindow* pCharacterWindow2 = m_pCharacterGUI->GetCharacterWindow();
if (mouse.x > pCharacterWindow2->GetDimensions().x + x && mouse.x < pCharacterWindow2->GetDimensions().x + x + width && mouse.y > pCharacterWindow2->GetDimensions().y + y && mouse.y < pCharacterWindow2->GetDimensions().y + y + height)
{
if (pInventoryItem->m_pInventoryItem->m_equipped == false)
{
// Dual handed weapon checks
if (pInventoryItem->m_pInventoryItem->m_equipSlot == EquipSlot::RightHand)
{
InventoryItem* pLeftHanded = m_pInventoryManager->GetInventoryItemForEquipSlot(EquipSlot::LeftHand);
if (pInventoryItem->m_pInventoryItem->m_left || (pLeftHanded != nullptr && pLeftHanded->m_right))
{
int slotX;
int slotY;
// Unequip the left hand slot since we are dual handed, OR the already equipped left hand item needs both hands
UnequipItem(EquipSlot::LeftHand, false, false);
if (m_pInventoryManager->UnequipItemToFreeInventorySlot(EquipSlot::LeftHand, &slotX, &slotY) == false)
{
// We can't fit the other item in the inventory
}
else if (pLeftHanded != nullptr)
{
m_pActionBar->UpdateActionBarSlots(pLeftHanded, slotX, slotY);
}
}
}
if (pInventoryItem->m_pInventoryItem->m_equipSlot == EquipSlot::LeftHand)
{
InventoryItem* pRightHanded = m_pInventoryManager->GetInventoryItemForEquipSlot(EquipSlot::RightHand);
if (pInventoryItem->m_pInventoryItem->m_right || (pRightHanded != nullptr && pRightHanded->m_left))
{
int slotX;
int slotY;
// Unequip the right hand slot since we are dual handed, OR the already equipped right hand item needs both hands
UnequipItem(EquipSlot::RightHand, false, false);
if (m_pInventoryManager->UnequipItemToFreeInventorySlot(EquipSlot::RightHand, &slotX, &slotY) == false)
{
// We can't fit the other item in the inventory
}
else if (pRightHanded != nullptr)
{
m_pActionBar->UpdateActionBarSlots(pRightHanded, slotX, slotY);
}
}
}
m_pPlayer->UnequipItem(pInventoryItem->m_pInventoryItem->m_equipSlot, pInventoryItem->m_pInventoryItem->m_left, pInventoryItem->m_pInventoryItem->m_right);
m_pInventoryManager->EquipInventoryItem(pInventoryItem->m_slotX, pInventoryItem->m_slotY, pInventoryItem->m_pInventoryItem->m_equipSlot);
EquipItem(pInventoryItem);
m_pInventoryWindow->RemoveComponent(pInventoryItem->m_pInventoryIcon);
pInventoryItem->m_erase = true;
m_vpInventorySlotItems.erase(remove_if(m_vpInventorySlotItems.begin(), m_vpInventorySlotItems.end(), IsNeedErase), m_vpInventorySlotItems.end());
m_pInventoryManager->SetInventoryGUINeedsUpdate(true);
m_pInventoryManager->SetCharacterGUINeedsUpdate(true);
m_pCharacterGUI->HideEquipHover();
equipped = true;
}
}
}
}
}
if (equipped == false)
{
// Check if we have released on a loot slot
if (m_pLootGUI->IsLoaded())
{
for (int i = 0; i < LootGUI::MAX_NUM_SLOTS_VERTICAL; ++i)
{
for (int j = 0; j < LootGUI::MAX_NUM_SLOTS_HORIZONTAL; ++j)
{
m_pLootGUI->GetLootDimensions(j, i, &x, &y, &width, &height);
GUIWindow* pLootWindow = m_pLootGUI->GetLootWindow();
// Check if we released (mouse cursor) in the boundary of another slot
if (mouse.x > pLootWindow->GetDimensions().x + x && mouse.x < pLootWindow->GetDimensions().x + x + width && mouse.y > pLootWindow->GetDimensions().y + y && mouse.y < pLootWindow->GetDimensions().y + y + height)
{
if (m_pLootGUI->GetLootSlotItem(j, i) == NULL) // ONLY if an item doesn't already exist in the loot slot position
{
m_pLootGUI->AddLootItemFromInventory(pInventoryItem->m_pInventoryItem, j, i);
m_pInventoryManager->RemoveInventoryItem(pInventoryItem->m_slotX, pInventoryItem->m_slotY);
m_pActionBar->RemoveInventoryItemFromActionBar(pInventoryItem->m_pInventoryItem->m_title);
m_pInventoryWindow->RemoveComponent(pInventoryItem->m_pInventoryIcon);
pInventoryItem->m_erase = true;
m_vpInventorySlotItems.erase(remove_if(m_vpInventorySlotItems.begin(), m_vpInventorySlotItems.end(), IsNeedErase), m_vpInventorySlotItems.end());
m_pCharacterGUI->HideEquipHover();
switched = true;
deleted = true;
}
}
}
}
}
// Check if we released on a action bar slot
if (CubbyGame::GetInstance()->GetCubbySettings()->m_renderGUI)
{
if (m_pActionBar->IsLoaded())
{
for (int i = 0; i < ActionBar::MAX_NUM_ACTION_SLOTS; ++i)
{
m_pActionBar->GetActionSlotDimensions(i, &x, &y, &width, &height);
// Check if we released (mouse cursor) in the boundary of another slot
if (mouse.x > x && mouse.x < x + width && mouse.y > y && mouse.y < y + height)
{
m_pActionBar->AddItemToActionBar(pInventoryItem->m_pInventoryItem, i, pInventoryItem->m_slotX, pInventoryItem->m_slotY);
m_pActionBar->ExportActionBar(m_pPlayer->GetName());
}
}
}
}
if (switched == false)
{
// Check if we need to drop the item into the world
GetDropSlotDimensions(&x, &y, &width, &height);
if (mouse.x > m_pInventoryWindow->GetDimensions().x + x && mouse.x < m_pInventoryWindow->GetDimensions().x + x + width && mouse.y > m_pInventoryWindow->GetDimensions().y + y && mouse.y < m_pInventoryWindow->GetDimensions().y + y + height)
{
if (pInventoryItem->m_slotX == -1 && pInventoryItem->m_slotY == -1)
{
// Do nothing
}
else
{
// Drop the item in the world
glm::vec3 vel = glm::vec3(GetRandomNumber(-1, 1, 2), 0.0f, GetRandomNumber(-1, 1, 2)) * GetRandomNumber(2, 3, 2);
Item* pItem = m_pItemManager->CreateItem(m_pPlayer->GetCenter(), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 0.0f, 0.0f), pInventoryItem->m_pInventoryItem->m_fileName.c_str(), ItemType::DroppedItem, pInventoryItem->m_pInventoryItem->m_title.c_str(), true, false, 0.08f);
if (pItem != nullptr)
{
pItem->SetGravityDirection(glm::vec3(0.0f, -1.0f, 0.0f));
pItem->SetVelocity(normalize(vel)*4.5f + glm::vec3(0.0f, 9.5f + GetRandomNumber(3, 6, 2), 0.0f));
pItem->SetRotation(glm::vec3(0.0f, GetRandomNumber(0, 360, 2), 0.0f));
pItem->SetAngularVelocity(glm::vec3(0.0f, 90.0f, 0.0f));
pItem->SetDroppedItem(pInventoryItem->m_pInventoryItem->m_fileName.c_str(), pInventoryItem->m_pInventoryItem->m_iconFileName.c_str(), pInventoryItem->m_pInventoryItem->m_itemType, pInventoryItem->m_pInventoryItem->m_item, pInventoryItem->m_pInventoryItem->m_status, pInventoryItem->m_pInventoryItem->m_equipSlot, pInventoryItem->m_pInventoryItem->m_itemQuality, pInventoryItem->m_pInventoryItem->m_left, pInventoryItem->m_pInventoryItem->m_right, pInventoryItem->m_pInventoryItem->m_title.c_str(), pInventoryItem->m_pInventoryItem->m_description.c_str(), pInventoryItem->m_pInventoryItem->m_placementR, pInventoryItem->m_pInventoryItem->m_placementG, pInventoryItem->m_pInventoryItem->m_placementB, pInventoryItem->m_pInventoryItem->m_quantity);
pItem->SetCollisionEnabled(false);
for (int i = 0; i < static_cast<int>(pInventoryItem->m_pInventoryItem->m_vpStatAttributes.size()); ++i)
{
pItem->GetDroppedInventoryItem()->AddStatAttribute(pInventoryItem->m_pInventoryItem->m_vpStatAttributes[i]->GetType(), pInventoryItem->m_pInventoryItem->m_vpStatAttributes[i]->GetModifyAmount());
}
int numY = pItem->GetVoxelItem()->GetAnimatedSection(0)->pVoxelObject->GetQubicleModel()->GetQubicleMatrix(0)->m_matrixSizeY;
pItem->GetVoxelItem()->SetRenderOffset(glm::vec3(0.0f, numY * 0.5f, 0.0f));
}
m_pInventoryManager->RemoveInventoryItem(pInventoryItem->m_slotX, pInventoryItem->m_slotY);
m_pActionBar->RemoveInventoryItemFromActionBar(pInventoryItem->m_pInventoryItem->m_title);
m_pInventoryWindow->RemoveComponent(pInventoryItem->m_pInventoryIcon);
pInventoryItem->m_erase = true;
m_vpInventorySlotItems.erase(remove_if(m_vpInventorySlotItems.begin(), m_vpInventorySlotItems.end(), IsNeedErase), m_vpInventorySlotItems.end());
m_pCharacterGUI->HideEquipHover();
switched = true;
deleted = true;
}
}
// Check if we need to delete the item
GetDestroySlotDimensions(&x, &y, &width, &height);
if (mouse.x > m_pInventoryWindow->GetDimensions().x + x && mouse.x < m_pInventoryWindow->GetDimensions().x + x + width && mouse.y > m_pInventoryWindow->GetDimensions().y + y && mouse.y < m_pInventoryWindow->GetDimensions().y + y + height)
{
if (pInventoryItem->m_slotX == -1 && pInventoryItem->m_slotY == -1)
{
// Do nothing
}
else
{
if (CubbyGame::GetInstance()->GetCubbySettings()->m_confirmItemDelete)
{
char popupTitle[256];
sprintf(popupTitle, "Delete");
char popupText[256];
sprintf(popupText, "Are you sure you want to delete [C=Custom(00A2E8)]%s[C=White]?", pInventoryItem->m_pInventoryItem->m_title.c_str());
OpenPopup(popupTitle, popupText);
m_pInventoryItemToDelete = pInventoryItem;
m_pCharacterGUI->HideEquipHover();
switched = false;
deleted = false;
}
else
{
if (pInventoryItem != nullptr)
{
m_pInventoryManager->RemoveInventoryItem(pInventoryItem->m_slotX, pInventoryItem->m_slotY);
m_pActionBar->RemoveInventoryItemFromActionBar(pInventoryItem->m_pInventoryItem->m_title);
m_pInventoryWindow->RemoveComponent(pInventoryItem->m_pInventoryIcon);
pInventoryItem->m_erase = true;
m_vpInventorySlotItems.erase(remove_if(m_vpInventorySlotItems.begin(), m_vpInventorySlotItems.end(), IsNeedErase), m_vpInventorySlotItems.end());
switched = true;
deleted = true;
}
}
}
}
}
}
}
// Revert depth back to normal for inventory icons
if (deleted == false && equipped == false)
{
pInventoryItem->m_pInventoryIcon->SetDepth(3.0f);
if (pInventoryItem->m_dropshadowAdded == true)
{
pInventoryItem->m_dropshadowAdded = false;
std::string themeName = CubbyGame::GetInstance()->GetModsManager()->GetHUDTextureTheme();
std::string dropShadowIcon = "Resources/textures/gui/" + themeName + "/common/items/drop_shadow.tga";
pInventoryItem->m_pInventoryIcon->RemoveIcon(dropShadowIcon.c_str());
}
m_pInventoryWindow->DepthSortComponentChildren();
}
// Reset back to the original position
if (switched == false && equipped == false)
{
pInventoryItem->m_pInventoryIcon->SetLocation(m_pressedX, m_pressedY);
if (pInventoryItem->m_dropshadowAdded == true)
{
pInventoryItem->m_dropshadowAdded = false;
std::string themeName = CubbyGame::GetInstance()->GetModsManager()->GetHUDTextureTheme();
std::string dropShadowIcon = "Resources/textures/gui/" + themeName + "/common/items/drop_shadow.tga";
pInventoryItem->m_pInventoryIcon->RemoveIcon(dropShadowIcon.c_str());
}
}
m_pInventoryWindow->RemoveComponent(m_pDestroyIcon);
m_pInventoryWindow->RemoveComponent(m_pDestroyLabel);
m_pInventoryWindow->RemoveComponent(m_pDropIcon);
m_pInventoryWindow->RemoveComponent(m_pDropLabel);
}
void InventoryGUI::_InventoryItemEntered(void* pData)
{
InventorySlotItem* pInventoryItem = static_cast<InventorySlotItem*>(pData);
pInventoryItem->m_pInventoryGUI->InventoryItemEntered(pInventoryItem);
}
void InventoryGUI::InventoryItemEntered(InventorySlotItem* pInventoryItem)
{
ShowTooltip(pInventoryItem);
if (m_pCharacterGUI->IsLoaded())
{
m_pCharacterGUI->ShowEquipHover(pInventoryItem->m_pInventoryItem->m_equipSlot);
}
}
void InventoryGUI::_InventoryItemExited(void* pData)
{
InventorySlotItem* pInventoryItem = static_cast<InventorySlotItem*>(pData);
pInventoryItem->m_pInventoryGUI->InventoryItemExited(pInventoryItem);
}
void InventoryGUI::InventoryItemExited(InventorySlotItem* pInventoryItem)
{
HideTooltip();
m_pCharacterGUI->HideEquipHover();
}
void InventoryGUI::_CloseExitPressed(void *pData)
{
InventoryGUI* pInventoryGUI = static_cast<InventoryGUI*>(pData);
pInventoryGUI->CloseExitPressed();
}
void InventoryGUI::CloseExitPressed()
{
Unload();
}
void InventoryGUI::_PopupConfirmPressed(void* pData)
{
InventoryGUI* pInventoryGUI = static_cast<InventoryGUI*>(pData);
pInventoryGUI->PopupConfirmPressed();
}
void InventoryGUI::PopupConfirmPressed()
{
if (m_pInventoryItemToDelete != nullptr)
{
m_pInventoryManager->RemoveInventoryItem(m_pInventoryItemToDelete->m_slotX, m_pInventoryItemToDelete->m_slotY);
m_pActionBar->RemoveInventoryItemFromActionBar(m_pInventoryItemToDelete->m_pInventoryItem->m_title);
m_pInventoryWindow->RemoveComponent(m_pInventoryItemToDelete->m_pInventoryIcon);
m_pInventoryItemToDelete->m_erase = true;
m_vpInventorySlotItems.erase(remove_if(m_vpInventorySlotItems.begin(), m_vpInventorySlotItems.end(), IsNeedErase), m_vpInventorySlotItems.end());
}
ClosePopup();
}
void InventoryGUI::_PopupCancelPressed(void* pData)
{
InventoryGUI* pInventoryGUI = static_cast<InventoryGUI*>(pData);
pInventoryGUI->PopupCancelPressed();
}
void InventoryGUI::PopupCancelPressed()
{
m_pInventoryItemToDelete = nullptr;
ClosePopup();
} | [
"black4roach@gmail.com"
] | black4roach@gmail.com |
0d2d18769ada564287724aee183dd011c0a2f1df | 256d76e96e3a70d5b3b025d8baa098c82d77d7fd | /untitled/animatedgraphicsitem.cpp | 303dd63a82c15752b2b503b6ab538b0f4d2138db | [] | no_license | creepcontrol/rpg_game | 368faf67be59e17feef20571912a8769dd48120c | d7892903c6c2a9319b62e43e35b271709c0a884b | refs/heads/master | 2020-03-19T06:51:31.869467 | 2018-06-05T02:57:21 | 2018-06-05T02:57:21 | 136,060,925 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,184 | cpp | #include "animatedgraphicsitem.h"
AnimatedGraphicsItem::AnimatedGraphicsItem(QObject *parent)
: QObject(parent)
{
connect(&m_timer, SIGNAL(timeout()), SLOT(on_timerTick()));
}
void AnimatedGraphicsItem::animation(AnimationID animationId, Mode mode,
bool randomStartFrame, int framerate) {
m_frames = &ANIMATION_POOL.get(animationId);
m_mode = mode;
m_timer.stop();
m_nFrames = m_frames->size();
if(randomStartFrame)
m_curFrameIndex = qrand() % m_nFrames;
else
m_curFrameIndex = 0;
setPixmap(*(*m_frames)[m_curFrameIndex]);
if (framerate > 0) {
m_timer.setInterval(1000/framerate);
m_timer.start();
}
}
void AnimatedGraphicsItem::on_timerTick() {
++m_curFrameIndex;
if (m_mode == Loop) {
if (m_curFrameIndex >= m_nFrames)
m_curFrameIndex = 0;
setPixmap(*(*m_frames)[m_curFrameIndex]);
}
else
{
if (m_curFrameIndex >= m_nFrames) {
m_timer.stop();
hide();
emit animationFinished();
}
else {
setPixmap(*(*m_frames)[m_curFrameIndex]);
}
}
}
| [
"creepcontrol@gmail.com"
] | creepcontrol@gmail.com |
e8391581cd9a3ddc9d67059feeeda8181aa7b2ce | c646eda22844eb3aadc832a55dc8a7a8d8b28656 | /CodeForces/ProblemSet/788A--Functions again.cpp | c6a7f386afc53770c3d40fc57fe3c31a29f27acf | [] | no_license | daidai21/ExerciseProblem | 78f41f20f6d12cd71c510241d5fe829af676a764 | cdc526fdb4ee1ca8e0d6334fecc4932d55019cea | refs/heads/master | 2021-11-22T21:54:13.106707 | 2021-11-14T10:54:37 | 2021-11-14T10:54:37 | 213,108,530 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,182 | cpp | // https://codeforces.com/problemset/problem/788/A
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; ++i)
cin >> a[i];
vector<int> b(n);
for (int i = 0; i < n - 1; ++i)
b[i] = abs(a[i] - a[i + 1]);
vector<vector<long long int>> dp(2, vector<long long int>(n));
dp[1][0] = b[0];
dp[0][0] = 0;
long long int res = dp[1][0];
for (int i = 1; i < n - 1; ++i) {
dp[1][i] = max(0LL + b[i], dp[0][i - 1] + b[i]);
dp[0][i] = dp[1][i - 1] - b[i];
res = max(res, dp[1][i]);
res = max(res, dp[0][i]);
}
cout << res << endl;
return 0;
}
/*
// overtime
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; ++i)
cin >> a[i];
int result = 0;
for (int l = 0; l < n - 1; ++l) {
for (int r = l + 1; r < n; ++r) {
int f_sum = 0;
for (int i = l; i < r; ++i) {
f_sum += abs(a[i] - a[i + 1]) * pow(-1, i - l);
}
result = max(result, f_sum);
}
}
cout << result << endl;
return 0;
}
*/
| [
"daidai4269@aliyun.com"
] | daidai4269@aliyun.com |
62bda1f85a7d459e8f2cad6be7f7d0bf96c66924 | 1f1cc05377786cc2aa480cbdfde3736dd3930f73 | /xulrunner-sdk-26/xulrunner-sdk/include/nsIDOMConstructor.h | c270c51a698330dd5af8ba987a42a84abce9f5c5 | [
"Apache-2.0"
] | permissive | julianpistorius/gp-revolution-gaia | 84c3ec5e2f3b9e76f19f45badc18d5544bb76e0d | 6e27b83efb0d4fa4222eaf25fb58b062e6d9d49e | refs/heads/master | 2021-01-21T02:49:54.000389 | 2014-03-27T09:58:17 | 2014-03-27T09:58:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,438 | h | /*
* DO NOT EDIT. THIS FILE IS GENERATED FROM /builds/slave/m-cen-l64-xr-ntly-000000000000/build/dom/interfaces/base/nsIDOMConstructor.idl
*/
#ifndef __gen_nsIDOMConstructor_h__
#define __gen_nsIDOMConstructor_h__
#ifndef __gen_domstubs_h__
#include "domstubs.h"
#endif
/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
/* starting interface: nsIDOMDOMConstructor */
#define NS_IDOMDOMCONSTRUCTOR_IID_STR "0ccbcf19-d1b4-489e-984c-cd8c43672bb9"
#define NS_IDOMDOMCONSTRUCTOR_IID \
{0x0ccbcf19, 0xd1b4, 0x489e, \
{ 0x98, 0x4c, 0xcd, 0x8c, 0x43, 0x67, 0x2b, 0xb9 }}
class NS_NO_VTABLE nsIDOMDOMConstructor : public nsISupports {
public:
NS_DECLARE_STATIC_IID_ACCESSOR(NS_IDOMDOMCONSTRUCTOR_IID)
/* AString toString (); */
NS_IMETHOD ToString(nsAString & _retval) = 0;
};
NS_DEFINE_STATIC_IID_ACCESSOR(nsIDOMDOMConstructor, NS_IDOMDOMCONSTRUCTOR_IID)
/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSIDOMDOMCONSTRUCTOR \
NS_IMETHOD ToString(nsAString & _retval);
/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSIDOMDOMCONSTRUCTOR(_to) \
NS_IMETHOD ToString(nsAString & _retval) { return _to ToString(_retval); }
/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSIDOMDOMCONSTRUCTOR(_to) \
NS_IMETHOD ToString(nsAString & _retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->ToString(_retval); }
#if 0
/* Use the code below as a template for the implementation class for this interface. */
/* Header file */
class nsDOMDOMConstructor : public nsIDOMDOMConstructor
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIDOMDOMCONSTRUCTOR
nsDOMDOMConstructor();
private:
~nsDOMDOMConstructor();
protected:
/* additional members */
};
/* Implementation file */
NS_IMPL_ISUPPORTS1(nsDOMDOMConstructor, nsIDOMDOMConstructor)
nsDOMDOMConstructor::nsDOMDOMConstructor()
{
/* member initializers and constructor code */
}
nsDOMDOMConstructor::~nsDOMDOMConstructor()
{
/* destructor code */
}
/* AString toString (); */
NS_IMETHODIMP nsDOMDOMConstructor::ToString(nsAString & _retval)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* End of implementation class template. */
#endif
#endif /* __gen_nsIDOMConstructor_h__ */
| [
"luis@geeksphone.com"
] | luis@geeksphone.com |
535925ac8d2b200c4ecdc09c255479f521637066 | fb7efe44f4d9f30d623f880d0eb620f3a81f0fbd | /chrome/browser/sync_file_system/local/local_file_change_tracker.cc | b8a8b232d206b51fa01b097b604754b22e5f5600 | [
"BSD-3-Clause"
] | permissive | wzyy2/chromium-browser | 2644b0daf58f8b3caee8a6c09a2b448b2dfe059c | eb905f00a0f7e141e8d6c89be8fb26192a88c4b7 | refs/heads/master | 2022-11-23T20:25:08.120045 | 2018-01-16T06:41:26 | 2018-01-16T06:41:26 | 117,618,467 | 3 | 2 | BSD-3-Clause | 2022-11-20T22:03:57 | 2018-01-16T02:09:10 | null | UTF-8 | C++ | false | false | 21,320 | cc | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/sync_file_system/local/local_file_change_tracker.h"
#include <stddef.h>
#include <utility>
#include "base/containers/circular_deque.h"
#include "base/containers/queue.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/macros.h"
#include "base/metrics/histogram_macros.h"
#include "base/sequenced_task_runner.h"
#include "base/stl_util.h"
#include "chrome/browser/sync_file_system/local/local_file_sync_status.h"
#include "chrome/browser/sync_file_system/syncable_file_system_util.h"
#include "storage/browser/fileapi/file_system_context.h"
#include "storage/browser/fileapi/file_system_file_util.h"
#include "storage/browser/fileapi/file_system_operation_context.h"
#include "storage/common/fileapi/file_system_util.h"
#include "third_party/leveldatabase/env_chromium.h"
#include "third_party/leveldatabase/src/include/leveldb/db.h"
#include "third_party/leveldatabase/src/include/leveldb/write_batch.h"
using storage::FileSystemContext;
using storage::FileSystemFileUtil;
using storage::FileSystemOperationContext;
using storage::FileSystemURL;
using storage::FileSystemURLSet;
namespace sync_file_system {
namespace {
const base::FilePath::CharType kDatabaseName[] =
FILE_PATH_LITERAL("LocalFileChangeTracker");
const char kMark[] = "d";
} // namespace
// A database class that stores local file changes in a local database. This
// object must be destructed on file_task_runner.
class LocalFileChangeTracker::TrackerDB {
public:
TrackerDB(const base::FilePath& base_path,
leveldb::Env* env_override);
SyncStatusCode MarkDirty(const std::string& url);
SyncStatusCode ClearDirty(const std::string& url);
SyncStatusCode GetDirtyEntries(base::queue<FileSystemURL>* dirty_files);
SyncStatusCode WriteBatch(std::unique_ptr<leveldb::WriteBatch> batch);
private:
enum RecoveryOption {
REPAIR_ON_CORRUPTION,
FAIL_ON_CORRUPTION,
};
SyncStatusCode Init(RecoveryOption recovery_option);
SyncStatusCode Repair(const std::string& db_path);
void HandleError(const base::Location& from_here,
const leveldb::Status& status);
const base::FilePath base_path_;
leveldb::Env* env_override_;
std::unique_ptr<leveldb::DB> db_;
SyncStatusCode db_status_;
DISALLOW_COPY_AND_ASSIGN(TrackerDB);
};
LocalFileChangeTracker::ChangeInfo::ChangeInfo() : change_seq(-1) {}
LocalFileChangeTracker::ChangeInfo::~ChangeInfo() {}
// LocalFileChangeTracker ------------------------------------------------------
LocalFileChangeTracker::LocalFileChangeTracker(
const base::FilePath& base_path,
leveldb::Env* env_override,
base::SequencedTaskRunner* file_task_runner)
: initialized_(false),
file_task_runner_(file_task_runner),
tracker_db_(new TrackerDB(base_path, env_override)),
current_change_seq_number_(0),
num_changes_(0) {
}
LocalFileChangeTracker::~LocalFileChangeTracker() {
DCHECK(file_task_runner_->RunsTasksInCurrentSequence());
tracker_db_.reset();
}
void LocalFileChangeTracker::OnStartUpdate(const FileSystemURL& url) {
DCHECK(file_task_runner_->RunsTasksInCurrentSequence());
if (base::ContainsKey(changes_, url) ||
base::ContainsKey(demoted_changes_, url)) {
return;
}
// TODO(nhiroki): propagate the error code (see http://crbug.com/152127).
MarkDirtyOnDatabase(url);
}
void LocalFileChangeTracker::OnEndUpdate(const FileSystemURL& url) {}
void LocalFileChangeTracker::OnCreateFile(const FileSystemURL& url) {
RecordChange(url, FileChange(FileChange::FILE_CHANGE_ADD_OR_UPDATE,
SYNC_FILE_TYPE_FILE));
}
void LocalFileChangeTracker::OnCreateFileFrom(const FileSystemURL& url,
const FileSystemURL& src) {
RecordChange(url, FileChange(FileChange::FILE_CHANGE_ADD_OR_UPDATE,
SYNC_FILE_TYPE_FILE));
}
void LocalFileChangeTracker::OnRemoveFile(const FileSystemURL& url) {
RecordChange(url, FileChange(FileChange::FILE_CHANGE_DELETE,
SYNC_FILE_TYPE_FILE));
}
void LocalFileChangeTracker::OnModifyFile(const FileSystemURL& url) {
RecordChange(url, FileChange(FileChange::FILE_CHANGE_ADD_OR_UPDATE,
SYNC_FILE_TYPE_FILE));
}
void LocalFileChangeTracker::OnCreateDirectory(const FileSystemURL& url) {
RecordChange(url, FileChange(FileChange::FILE_CHANGE_ADD_OR_UPDATE,
SYNC_FILE_TYPE_DIRECTORY));
}
void LocalFileChangeTracker::OnRemoveDirectory(const FileSystemURL& url) {
RecordChange(url, FileChange(FileChange::FILE_CHANGE_DELETE,
SYNC_FILE_TYPE_DIRECTORY));
}
void LocalFileChangeTracker::GetNextChangedURLs(
base::circular_deque<FileSystemURL>* urls,
int max_urls) {
DCHECK(file_task_runner_->RunsTasksInCurrentSequence());
DCHECK(urls);
urls->clear();
// Mildly prioritizes the URLs that older changes and have not been updated
// for a while.
for (ChangeSeqMap::iterator iter = change_seqs_.begin();
iter != change_seqs_.end() &&
(max_urls == 0 || urls->size() < static_cast<size_t>(max_urls));
++iter) {
urls->push_back(iter->second);
}
}
void LocalFileChangeTracker::GetChangesForURL(
const FileSystemURL& url, FileChangeList* changes) {
DCHECK(file_task_runner_->RunsTasksInCurrentSequence());
DCHECK(changes);
changes->clear();
FileChangeMap::iterator found = changes_.find(url);
if (found == changes_.end()) {
found = demoted_changes_.find(url);
if (found == demoted_changes_.end())
return;
}
*changes = found->second.change_list;
}
void LocalFileChangeTracker::ClearChangesForURL(const FileSystemURL& url) {
DCHECK(file_task_runner_->RunsTasksInCurrentSequence());
ClearDirtyOnDatabase(url);
mirror_changes_.erase(url);
demoted_changes_.erase(url);
FileChangeMap::iterator found = changes_.find(url);
if (found == changes_.end())
return;
change_seqs_.erase(found->second.change_seq);
changes_.erase(found);
UpdateNumChanges();
}
void LocalFileChangeTracker::CreateFreshMirrorForURL(
const storage::FileSystemURL& url) {
DCHECK(file_task_runner_->RunsTasksInCurrentSequence());
DCHECK(!base::ContainsKey(mirror_changes_, url));
mirror_changes_[url] = ChangeInfo();
}
void LocalFileChangeTracker::RemoveMirrorAndCommitChangesForURL(
const storage::FileSystemURL& url) {
DCHECK(file_task_runner_->RunsTasksInCurrentSequence());
FileChangeMap::iterator found = mirror_changes_.find(url);
if (found == mirror_changes_.end())
return;
mirror_changes_.erase(found);
if (base::ContainsKey(changes_, url) ||
base::ContainsKey(demoted_changes_, url)) {
MarkDirtyOnDatabase(url);
} else {
ClearDirtyOnDatabase(url);
}
UpdateNumChanges();
}
void LocalFileChangeTracker::ResetToMirrorAndCommitChangesForURL(
const storage::FileSystemURL& url) {
DCHECK(file_task_runner_->RunsTasksInCurrentSequence());
FileChangeMap::iterator found = mirror_changes_.find(url);
if (found == mirror_changes_.end() || found->second.change_list.empty()) {
ClearChangesForURL(url);
return;
}
const ChangeInfo& info = found->second;
if (base::ContainsKey(demoted_changes_, url)) {
DCHECK(!base::ContainsKey(changes_, url));
demoted_changes_[url] = info;
} else {
DCHECK(!base::ContainsKey(demoted_changes_, url));
change_seqs_[info.change_seq] = url;
changes_[url] = info;
}
RemoveMirrorAndCommitChangesForURL(url);
}
void LocalFileChangeTracker::DemoteChangesForURL(
const storage::FileSystemURL& url) {
DCHECK(file_task_runner_->RunsTasksInCurrentSequence());
FileChangeMap::iterator found = changes_.find(url);
if (found == changes_.end())
return;
DCHECK(!base::ContainsKey(demoted_changes_, url));
change_seqs_.erase(found->second.change_seq);
demoted_changes_.insert(*found);
changes_.erase(found);
UpdateNumChanges();
}
void LocalFileChangeTracker::PromoteDemotedChangesForURL(
const storage::FileSystemURL& url) {
DCHECK(file_task_runner_->RunsTasksInCurrentSequence());
FileChangeMap::iterator iter = demoted_changes_.find(url);
if (iter == demoted_changes_.end())
return;
FileChangeList::List change_list = iter->second.change_list.list();
// Make sure that this URL is in no queues.
DCHECK(!base::ContainsKey(change_seqs_, iter->second.change_seq));
DCHECK(!base::ContainsKey(changes_, url));
change_seqs_[iter->second.change_seq] = url;
changes_.insert(*iter);
demoted_changes_.erase(iter);
UpdateNumChanges();
}
bool LocalFileChangeTracker::PromoteDemotedChanges() {
DCHECK(file_task_runner_->RunsTasksInCurrentSequence());
if (demoted_changes_.empty())
return false;
while (!demoted_changes_.empty()) {
storage::FileSystemURL url = demoted_changes_.begin()->first;
PromoteDemotedChangesForURL(url);
}
UpdateNumChanges();
return true;
}
SyncStatusCode LocalFileChangeTracker::Initialize(
FileSystemContext* file_system_context) {
DCHECK(file_task_runner_->RunsTasksInCurrentSequence());
DCHECK(!initialized_);
DCHECK(file_system_context);
SyncStatusCode status = CollectLastDirtyChanges(file_system_context);
if (status == SYNC_STATUS_OK)
initialized_ = true;
return status;
}
void LocalFileChangeTracker::ResetForFileSystem(const GURL& origin,
storage::FileSystemType type) {
DCHECK(file_task_runner_->RunsTasksInCurrentSequence());
std::unique_ptr<leveldb::WriteBatch> batch(new leveldb::WriteBatch);
for (FileChangeMap::iterator iter = changes_.begin();
iter != changes_.end();) {
storage::FileSystemURL url = iter->first;
int change_seq = iter->second.change_seq;
// Advance |iter| before calling ResetForURL to avoid the iterator
// invalidation in it.
++iter;
if (url.origin() == origin && url.type() == type)
ResetForURL(url, change_seq, batch.get());
}
for (FileChangeMap::iterator iter = demoted_changes_.begin();
iter != demoted_changes_.end();) {
storage::FileSystemURL url = iter->first;
int change_seq = iter->second.change_seq;
// Advance |iter| before calling ResetForURL to avoid the iterator
// invalidation in it.
++iter;
if (url.origin() == origin && url.type() == type)
ResetForURL(url, change_seq, batch.get());
}
// Fail to apply batch to database wouldn't have critical effect, they'll be
// just marked deleted on next relaunch.
tracker_db_->WriteBatch(std::move(batch));
UpdateNumChanges();
}
void LocalFileChangeTracker::UpdateNumChanges() {
base::AutoLock lock(num_changes_lock_);
num_changes_ = static_cast<int64_t>(change_seqs_.size());
}
void LocalFileChangeTracker::GetAllChangedURLs(FileSystemURLSet* urls) {
DCHECK(file_task_runner_->RunsTasksInCurrentSequence());
base::circular_deque<FileSystemURL> url_deque;
GetNextChangedURLs(&url_deque, 0);
urls->clear();
urls->insert(url_deque.begin(), url_deque.end());
}
void LocalFileChangeTracker::DropAllChanges() {
DCHECK(file_task_runner_->RunsTasksInCurrentSequence());
changes_.clear();
change_seqs_.clear();
mirror_changes_.clear();
UpdateNumChanges();
}
SyncStatusCode LocalFileChangeTracker::MarkDirtyOnDatabase(
const FileSystemURL& url) {
std::string serialized_url;
if (!SerializeSyncableFileSystemURL(url, &serialized_url))
return SYNC_FILE_ERROR_INVALID_URL;
return tracker_db_->MarkDirty(serialized_url);
}
SyncStatusCode LocalFileChangeTracker::ClearDirtyOnDatabase(
const FileSystemURL& url) {
DCHECK(file_task_runner_->RunsTasksInCurrentSequence());
std::string serialized_url;
if (!SerializeSyncableFileSystemURL(url, &serialized_url))
return SYNC_FILE_ERROR_INVALID_URL;
return tracker_db_->ClearDirty(serialized_url);
}
SyncStatusCode LocalFileChangeTracker::CollectLastDirtyChanges(
FileSystemContext* file_system_context) {
DCHECK(file_task_runner_->RunsTasksInCurrentSequence());
base::queue<FileSystemURL> dirty_files;
const SyncStatusCode status = tracker_db_->GetDirtyEntries(&dirty_files);
if (status != SYNC_STATUS_OK)
return status;
FileSystemFileUtil* file_util =
file_system_context->sandbox_delegate()->sync_file_util();
DCHECK(file_util);
std::unique_ptr<FileSystemOperationContext> context(
new FileSystemOperationContext(file_system_context));
base::File::Info file_info;
base::FilePath platform_path;
while (!dirty_files.empty()) {
const FileSystemURL url = dirty_files.front();
dirty_files.pop();
DCHECK_EQ(url.type(), storage::kFileSystemTypeSyncable);
switch (file_util->GetFileInfo(context.get(), url,
&file_info, &platform_path)) {
case base::File::FILE_OK: {
if (!file_info.is_directory) {
RecordChange(url, FileChange(FileChange::FILE_CHANGE_ADD_OR_UPDATE,
SYNC_FILE_TYPE_FILE));
break;
}
RecordChange(url, FileChange(
FileChange::FILE_CHANGE_ADD_OR_UPDATE,
SYNC_FILE_TYPE_DIRECTORY));
// Push files and directories in this directory into |dirty_files|.
std::unique_ptr<FileSystemFileUtil::AbstractFileEnumerator> enumerator(
file_util->CreateFileEnumerator(context.get(), url));
base::FilePath path_each;
while (!(path_each = enumerator->Next()).empty()) {
dirty_files.push(CreateSyncableFileSystemURL(
url.origin(), path_each));
}
break;
}
case base::File::FILE_ERROR_NOT_FOUND: {
// File represented by |url| has already been deleted. Since we cannot
// figure out if this file was directory or not from the URL, file
// type is treated as SYNC_FILE_TYPE_UNKNOWN.
//
// NOTE: Directory to have been reverted (that is, ADD -> DELETE) is
// also treated as FILE_CHANGE_DELETE.
RecordChange(url, FileChange(FileChange::FILE_CHANGE_DELETE,
SYNC_FILE_TYPE_UNKNOWN));
break;
}
case base::File::FILE_ERROR_FAILED:
default:
// TODO(nhiroki): handle file access error (http://crbug.com/155251).
LOG(WARNING) << "Failed to access local file.";
break;
}
}
return SYNC_STATUS_OK;
}
void LocalFileChangeTracker::RecordChange(
const FileSystemURL& url, const FileChange& change) {
DCHECK(file_task_runner_->RunsTasksInCurrentSequence());
int change_seq = current_change_seq_number_++;
if (base::ContainsKey(demoted_changes_, url)) {
RecordChangeToChangeMaps(url, change, change_seq,
&demoted_changes_, nullptr);
} else {
RecordChangeToChangeMaps(url, change, change_seq, &changes_, &change_seqs_);
}
if (base::ContainsKey(mirror_changes_, url)) {
RecordChangeToChangeMaps(url, change, change_seq, &mirror_changes_,
nullptr);
}
UpdateNumChanges();
}
// static
void LocalFileChangeTracker::RecordChangeToChangeMaps(
const FileSystemURL& url,
const FileChange& change,
int new_change_seq,
FileChangeMap* changes,
ChangeSeqMap* change_seqs) {
ChangeInfo& info = (*changes)[url];
if (info.change_seq >= 0 && change_seqs)
change_seqs->erase(info.change_seq);
info.change_list.Update(change);
if (info.change_list.empty()) {
changes->erase(url);
return;
}
info.change_seq = new_change_seq;
if (change_seqs)
(*change_seqs)[info.change_seq] = url;
}
void LocalFileChangeTracker::ResetForURL(const storage::FileSystemURL& url,
int change_seq,
leveldb::WriteBatch* batch) {
mirror_changes_.erase(url);
demoted_changes_.erase(url);
change_seqs_.erase(change_seq);
changes_.erase(url);
std::string serialized_url;
if (!SerializeSyncableFileSystemURL(url, &serialized_url)) {
NOTREACHED() << "Failed to serialize: " << url.DebugString();
return;
}
batch->Delete(serialized_url);
}
// TrackerDB -------------------------------------------------------------------
LocalFileChangeTracker::TrackerDB::TrackerDB(const base::FilePath& base_path,
leveldb::Env* env_override)
: base_path_(base_path),
env_override_(env_override),
db_status_(SYNC_STATUS_OK) {}
SyncStatusCode LocalFileChangeTracker::TrackerDB::Init(
RecoveryOption recovery_option) {
if (db_.get() && db_status_ == SYNC_STATUS_OK)
return SYNC_STATUS_OK;
std::string path =
storage::FilePathToString(base_path_.Append(kDatabaseName));
leveldb_env::Options options;
options.max_open_files = 0; // Use minimum.
options.create_if_missing = true;
if (env_override_)
options.env = env_override_;
leveldb::Status status = leveldb_env::OpenDB(options, path, &db_);
UMA_HISTOGRAM_ENUMERATION("SyncFileSystem.TrackerDB.Open",
leveldb_env::GetLevelDBStatusUMAValue(status),
leveldb_env::LEVELDB_STATUS_MAX);
if (status.ok()) {
return SYNC_STATUS_OK;
}
HandleError(FROM_HERE, status);
if (!status.IsCorruption())
return LevelDBStatusToSyncStatusCode(status);
// Try to repair the corrupted DB.
switch (recovery_option) {
case FAIL_ON_CORRUPTION:
return SYNC_DATABASE_ERROR_CORRUPTION;
case REPAIR_ON_CORRUPTION:
return Repair(path);
}
NOTREACHED();
return SYNC_DATABASE_ERROR_FAILED;
}
SyncStatusCode LocalFileChangeTracker::TrackerDB::Repair(
const std::string& db_path) {
DCHECK(!db_.get());
LOG(WARNING) << "Attempting to repair TrackerDB.";
leveldb_env::Options options;
options.reuse_logs = false; // Compact log file if repairing.
options.max_open_files = 0; // Use minimum.
if (leveldb::RepairDB(db_path, options).ok() &&
Init(FAIL_ON_CORRUPTION) == SYNC_STATUS_OK) {
// TODO(nhiroki): perform some consistency checks between TrackerDB and
// syncable file system.
LOG(WARNING) << "Repairing TrackerDB completed.";
return SYNC_STATUS_OK;
}
LOG(WARNING) << "Failed to repair TrackerDB.";
return SYNC_DATABASE_ERROR_CORRUPTION;
}
// TODO(nhiroki): factor out the common methods into somewhere else.
void LocalFileChangeTracker::TrackerDB::HandleError(
const base::Location& from_here,
const leveldb::Status& status) {
LOG(ERROR) << "LocalFileChangeTracker::TrackerDB failed at: "
<< from_here.ToString() << " with error: " << status.ToString();
}
SyncStatusCode LocalFileChangeTracker::TrackerDB::MarkDirty(
const std::string& url) {
if (db_status_ != SYNC_STATUS_OK)
return db_status_;
db_status_ = Init(REPAIR_ON_CORRUPTION);
if (db_status_ != SYNC_STATUS_OK) {
db_.reset();
return db_status_;
}
leveldb::Status status = db_->Put(leveldb::WriteOptions(), url, kMark);
if (!status.ok()) {
HandleError(FROM_HERE, status);
db_status_ = LevelDBStatusToSyncStatusCode(status);
db_.reset();
return db_status_;
}
return SYNC_STATUS_OK;
}
SyncStatusCode LocalFileChangeTracker::TrackerDB::ClearDirty(
const std::string& url) {
if (db_status_ != SYNC_STATUS_OK)
return db_status_;
// Should not reach here before initializing the database. The database should
// be cleared after read, and should be initialized during read if
// uninitialized.
DCHECK(db_.get());
leveldb::Status status = db_->Delete(leveldb::WriteOptions(), url);
if (!status.ok() && !status.IsNotFound()) {
HandleError(FROM_HERE, status);
db_status_ = LevelDBStatusToSyncStatusCode(status);
db_.reset();
return db_status_;
}
return SYNC_STATUS_OK;
}
SyncStatusCode LocalFileChangeTracker::TrackerDB::GetDirtyEntries(
base::queue<FileSystemURL>* dirty_files) {
if (db_status_ != SYNC_STATUS_OK)
return db_status_;
db_status_ = Init(REPAIR_ON_CORRUPTION);
if (db_status_ != SYNC_STATUS_OK) {
db_.reset();
return db_status_;
}
std::unique_ptr<leveldb::Iterator> iter(
db_->NewIterator(leveldb::ReadOptions()));
iter->SeekToFirst();
FileSystemURL url;
while (iter->Valid()) {
if (!DeserializeSyncableFileSystemURL(iter->key().ToString(), &url)) {
LOG(WARNING) << "Failed to deserialize an URL. "
<< "TrackerDB might be corrupted.";
db_status_ = SYNC_DATABASE_ERROR_CORRUPTION;
iter.reset(); // Must delete before closing the database.
db_.reset();
return db_status_;
}
dirty_files->push(url);
iter->Next();
}
return SYNC_STATUS_OK;
}
SyncStatusCode LocalFileChangeTracker::TrackerDB::WriteBatch(
std::unique_ptr<leveldb::WriteBatch> batch) {
if (db_status_ != SYNC_STATUS_OK)
return db_status_;
leveldb::Status status = db_->Write(leveldb::WriteOptions(), batch.get());
if (!status.ok() && !status.IsNotFound()) {
HandleError(FROM_HERE, status);
db_status_ = LevelDBStatusToSyncStatusCode(status);
db_.reset();
return db_status_;
}
return SYNC_STATUS_OK;
}
} // namespace sync_file_system
| [
"jacob-chen@iotwrt.com"
] | jacob-chen@iotwrt.com |
4d9fab3c0896b688475c2a057c130b38018a5838 | 2c7e90851722a92a6b321935c09a6e3f6650adb4 | /TabuSearch_for_TSP/AreaOfSolutions.cpp | f4d509696cd869eeaf3a24e3215f6b81274172c8 | [] | no_license | czarny247/ts-for-tsp | f68dd0f88a344e43b4000c8766dc49ba429d681b | b9f40723ea3a099499c7f4bc9c6c87f22b09ce8b | refs/heads/master | 2021-01-10T12:41:53.097427 | 2016-02-03T10:49:19 | 2016-02-03T10:49:19 | 50,418,228 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 209 | cpp | #include "AreaOfSolutions.h"
AreaOfSolutions::AreaOfSolutions()
{
}
void AreaOfSolutions::addSolution(Solution sol)
{
sSolutions.insert(&sol);
}
Solution AreaOfSolutions::getSolution(int position)
{
}
| [
"mateusz.hercun@gmail.com"
] | mateusz.hercun@gmail.com |
1335d1662b3ec750463043fd84e4eb74a85ccda2 | 3ea4848953688c5ff2ca0c3a79b26372cc839dc8 | /reports/MinDegree.h | 7569a9659e4c63ba0ba23e1fca0a571f5c7639fa | [] | no_license | rostam/CGTea | a612b758b3d4448062cbd12b02fe3f0a5ae40f99 | 56291e8c7c5ad54e3d29aaf7a07caf0e4e4f6d57 | refs/heads/master | 2023-08-05T09:54:07.123882 | 2023-07-20T10:39:41 | 2023-07-20T10:39:41 | 212,271,988 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 794 | h | //
// Created by rostam on 15.10.19.
//
#ifndef CGTEA_MINDEGREE_H
#define CGTEA_MINDEGREE_H
#include "ReportInterface.h"
class MinDegree : public ReportInterface{
public:
string report(const Graph& g) override {
int min_degree = boost::num_vertices(g) + 1;
for_each_v_const(g, [&](Ver v){
int deg = boost::out_degree(v, g);
if(deg < min_degree) min_degree = deg;
});
return std::to_string(min_degree);
};
string name() const override {
return "Minimum degree";
};
string description() const override {
return "Minimum degree";
};
string type() const override {
return "int";
};
string category() const override {
return "General";
};
};
#endif //CGTEA_MAXDEGREE_H
| [
"rostamiev@gmail.com"
] | rostamiev@gmail.com |
e1b1a85d62118ce9d4025a013e63333d3cc70173 | 9dc335630cb97246a7d67ddf652b404701cece61 | /CAD/CAD_Verano/Ejercicio2_5_Wtime_SEND/Ejercicio2_5_Wtime_SEND.cpp | 25bb60e4e0ab93f41cedffbe53616efe22f7739c | [] | no_license | getmiranda/sistemas_itver | 1e952e97a1a82891646c7df257c60870445fcae2 | f768d5783a9f570f5debe6a7d18d175f0503e8da | refs/heads/master | 2020-07-10T02:39:15.715234 | 2019-08-24T11:12:56 | 2019-08-24T11:12:56 | 204,145,537 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,006 | cpp | #include <stdio.h>
#include "mpi.h"
int main(int argc, char* arcv[]) {
int nombre_proceso, total_procesos, flag = 0, origen, destino;
//double inicio, termina;
int valor;
MPI_Status status;
MPI_Init(NULL, NULL);
MPI_Comm_rank(MPI_COMM_WORLD, &nombre_proceso);
MPI_Comm_size(MPI_COMM_WORLD, &total_procesos);
if (nombre_proceso != 0)
{
valor = 1;
destino = 0;
MPI_Send(&valor, 1, MPI_INT, destino, flag, MPI_COMM_WORLD);
printf("Esclavo. Proceso: %d enviando valor %d a master.", nombre_proceso, valor);
}
else
{
for (int origen = 1; origen < total_procesos; origen++)
{
//Inicia el intervalo
double inicio = MPI_Wtime();
MPI_Recv(&valor, 1, MPI_INT, MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
//Finaliza el intervalo
double termina = MPI_Wtime();
printf("Master. Proceso: %d ha recibido el valor %d del proceso %d. Tiempo de proceso: %f\n",
nombre_proceso, valor, status.MPI_SOURCE, (termina - inicio));
}
}
MPI_Finalize();
return 0;
} | [
"androidgalaxys42@gmail.com"
] | androidgalaxys42@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.