hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
109
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
48.5k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a75ec2a97804b4ce42cf41c1ff57a6147687152c
| 1,142
|
cpp
|
C++
|
Homework/03/task_3.cpp
|
Ignatoff/FMI-DSA-2018
|
24d2a3f5127a0d9c97ae165daad3b8601593b1ca
|
[
"MIT"
] | 1
|
2018-11-26T19:17:21.000Z
|
2018-11-26T19:17:21.000Z
|
Homework/03/task_3.cpp
|
Ignatoff/FMI-DSA-2018
|
24d2a3f5127a0d9c97ae165daad3b8601593b1ca
|
[
"MIT"
] | null | null | null |
Homework/03/task_3.cpp
|
Ignatoff/FMI-DSA-2018
|
24d2a3f5127a0d9c97ae165daad3b8601593b1ca
|
[
"MIT"
] | 1
|
2019-03-17T17:16:12.000Z
|
2019-03-17T17:16:12.000Z
|
#include <iostream>
const int MAXN = 100001;
int n, k;
long long arr[MAXN];
bool check(long long ans)
{
long long usedBlows = ans;
for (size_t i = 0; i < n; i++)
{
long long diff = arr[i] - ans;
if (diff > 0)
{
long long neededBlows = diff / (k - 1);
if (diff % (k - 1) != 0) neededBlows++;
if (usedBlows < neededBlows) return false;
else usedBlows -= neededBlows;
}
}
return true;
}
int binarySeach(long long* arr, int l, int r)
{
long long ans = -1;
while (l <= r)
{
int m = (l + r) / 2;
if (check(m))
{
ans = m;
r = m - 1;
}
else l = m + 1;
}
return ans;
}
int main()
{
long long maxVal = -1, zeroCnt = 0;
std::cin >> n >> k;
for (size_t i = 0; i < n; i++)
{
std::cin >> arr[i];
if (arr[i] > maxVal) maxVal = arr[i];
if (arr[i] == 0) zeroCnt++;
}
if (zeroCnt == n) std::cout << 0 << '\n';
else if (k == 1) std::cout << maxVal << '\n';
else std::cout << binarySeach(arr, 0, maxVal) << '\n';
}
| 20.035088
| 58
| 0.443958
|
Ignatoff
|
a75f3c63c5b8c1f914ebbd767d708001d0effbfb
| 718
|
hpp
|
C++
|
include/blackhole/formatter.hpp
|
JakariaBlaine/blackhole
|
e340329c6e2e3166858d8466656ad12300b686bd
|
[
"MIT"
] | 193
|
2015-01-05T08:48:05.000Z
|
2022-01-31T22:04:01.000Z
|
include/blackhole/formatter.hpp
|
JakariaBlaine/blackhole
|
e340329c6e2e3166858d8466656ad12300b686bd
|
[
"MIT"
] | 135
|
2015-01-13T13:02:49.000Z
|
2022-01-12T15:06:48.000Z
|
include/blackhole/formatter.hpp
|
JakariaBlaine/blackhole
|
e340329c6e2e3166858d8466656ad12300b686bd
|
[
"MIT"
] | 40
|
2015-01-21T16:37:30.000Z
|
2022-01-25T15:54:04.000Z
|
#pragma once
namespace blackhole {
inline namespace v1 {
class record_t;
class writer_t;
/// Represents an interface that every formatter must implement.
///
/// Formatters are responsible for formatting the input logging record using the specified writer.
class formatter_t {
public:
formatter_t() = default;
formatter_t(const formatter_t& other) = default;
formatter_t(formatter_t&& other) = default;
virtual ~formatter_t() = 0;
/// Formats the specified logging event record by invoking formatter renderers and writing the
/// result into the given writer.
virtual auto format(const record_t& record, writer_t& writer) -> void = 0;
};
} // namespace v1
} // namespace blackhole
| 25.642857
| 98
| 0.727019
|
JakariaBlaine
|
a7654e6b4165c66b565fd7eeb97b0c540bb05a64
| 2,285
|
hpp
|
C++
|
src/mlpack/core/data/load_arff.hpp
|
shubham1206agra/mlpack
|
2c656fcba850134f3f5d1dd1a6a1a15743aa7661
|
[
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] | null | null | null |
src/mlpack/core/data/load_arff.hpp
|
shubham1206agra/mlpack
|
2c656fcba850134f3f5d1dd1a6a1a15743aa7661
|
[
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] | null | null | null |
src/mlpack/core/data/load_arff.hpp
|
shubham1206agra/mlpack
|
2c656fcba850134f3f5d1dd1a6a1a15743aa7661
|
[
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] | null | null | null |
/**
* @file core/data/load_arff.hpp
* @author Ryan Curtin
*
* Load an ARFF dataset.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#ifndef MLPACK_CORE_DATA_LOAD_ARFF_HPP
#define MLPACK_CORE_DATA_LOAD_ARFF_HPP
#include <mlpack/prereqs.hpp>
#include "dataset_mapper.hpp"
#include "string_algorithms.hpp"
namespace mlpack {
namespace data {
/**
* A utility function to load an ARFF dataset as numeric features (that is, as
* an Armadillo matrix without any modification). An exception will be thrown
* if any features are non-numeric.
*/
template<typename eT>
void LoadARFF(const std::string& filename, arma::Mat<eT>& matrix);
/**
* A utility function to load an ARFF dataset as numeric and categorical
* features, using the DatasetInfo structure for mapping. An exception will be
* thrown upon failure.
*
* A pre-existing DatasetInfo object can be passed in, but if the dimensionality
* of the given DatasetInfo object (info.Dimensionality()) does not match the
* dimensionality of the data, a std::invalid_argument exception will be thrown.
* If an empty DatasetInfo object is given (constructed with the default
* constructor or otherwise, so that info.Dimensionality() is 0), it will be set
* to the right dimensionality.
*
* This ability to pass in pre-existing DatasetInfo objects is very necessary
* when, e.g., loading a test set after training. If the same DatasetInfo from
* loading the training set is not used, then the test set may be loaded with
* different mappings---which can cause horrible problems!
*
* @param filename Name of ARFF file to load.
* @param matrix Matrix to load data into.
* @param info DatasetInfo object; can be default-constructed or pre-existing
* from another call to LoadARFF().
*/
template<typename eT, typename PolicyType>
void LoadARFF(const std::string& filename,
arma::Mat<eT>& matrix,
DatasetMapper<PolicyType>& info);
} // namespace data
} // namespace mlpack
// Include implementation.
#include "load_arff_impl.hpp"
#endif
| 35.703125
| 80
| 0.742232
|
shubham1206agra
|
a76e4c326be1cdbaaba675e06b78a454a62cda9a
| 1,162
|
cpp
|
C++
|
Codeforces/160A.cpp
|
DT3264/ProgrammingContestsSolutions
|
a297f2da654c2ca2815b9aa375c2b4ca0052269d
|
[
"MIT"
] | null | null | null |
Codeforces/160A.cpp
|
DT3264/ProgrammingContestsSolutions
|
a297f2da654c2ca2815b9aa375c2b4ca0052269d
|
[
"MIT"
] | null | null | null |
Codeforces/160A.cpp
|
DT3264/ProgrammingContestsSolutions
|
a297f2da654c2ca2815b9aa375c2b4ca0052269d
|
[
"MIT"
] | null | null | null |
#include<stdio.h>
int arr[100];
int part(int arr[], int left, int right, int piv){
while(left<=right){
while(arr[left]<piv){
left++;
}
while(arr[right]>piv){
right--;
}
if(left<=right){
int temp=arr[left];
arr[left]=arr[right];
arr[right]=temp;
left++;
right--;
}
}
return left;
}
void quickSort(int arr[], int left, int right){
if(left<right){
int piv=arr[(left+right)/2];
int pos = part(arr, left, right, piv);
quickSort(arr, left, pos-1);
quickSort(arr, pos, right);
}
}
int main(){
int n, i;
scanf("%d", &n);
for(i=0; i<n; i++){
scanf("%d", &arr[i]);
}
quickSort(arr, 0, n-1);
int left = 0;
int right = n-1;
int him=0;
int me=0;
int coins=0;
while(left<=right){
me+=arr[right--];
coins++;
while(left<=right && him<me){
him+=arr[left++];
}
}
if(him>=me){
left--;
him-=arr[left];
me+=arr[left];
coins++;
}
printf("%d", coins);
}
| 19.694915
| 50
| 0.436317
|
DT3264
|
a76fc4ad2af54b3aa80a99b1e0fa4e22ef6239a2
| 5,736
|
cpp
|
C++
|
BasiliskII/src/Windows/router/udp.cpp
|
jvernet/macemu
|
c616a0dae0f451fc15016765c896175fae3f46cf
|
[
"Intel",
"X11"
] | 940
|
2015-01-04T12:20:10.000Z
|
2022-03-29T12:35:27.000Z
|
BasiliskII/src/Windows/router/udp.cpp
|
Seanpm2001-virtual-machines/macemu
|
c616a0dae0f451fc15016765c896175fae3f46cf
|
[
"Intel",
"X11"
] | 163
|
2015-02-10T09:08:10.000Z
|
2022-03-13T05:48:10.000Z
|
BasiliskII/src/Windows/router/udp.cpp
|
Seanpm2001-virtual-machines/macemu
|
c616a0dae0f451fc15016765c896175fae3f46cf
|
[
"Intel",
"X11"
] | 188
|
2015-01-07T19:46:11.000Z
|
2022-03-26T19:06:00.000Z
|
/*
* udp.cpp - ip router
*
* Basilisk II (C) 1997-2008 Christian Bauer
*
* Windows platform specific code copyright (C) Lauri Pesonen
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "sysdeps.h"
#include "main.h"
#include "cpu_emulation.h"
#include "prefs.h"
#include "ether_windows.h"
#include "ether.h"
#include "router.h"
#include "router_types.h"
#include "dynsockets.h"
#include "ipsocket.h"
#include "iphelp.h"
#include "udp.h"
#include "dump.h"
#if DEBUG
#pragma optimize("",off)
#endif
#include "debug.h"
void CALLBACK udp_read_completion(
DWORD error,
DWORD bytes_read,
LPWSAOVERLAPPED lpOverlapped,
DWORD flags
)
{
D(bug("udp_read_completion(error=0x%x, bytes_read=%d, flags=0x%x)\r\n", error, bytes_read, flags));
socket_t *cmpl = (socket_t *)lpOverlapped->hEvent;
// It's not easy to know whether empty upd datagrams should be passed along. doh.
if(error == 0 && bytes_read > 0) {
if(bytes_read > 1460) {
D(bug("discarding oversized udp packet, size = \r\n", bytes_read));
} else {
struct sockaddr_in name;
int namelen = sizeof(name);
memset( &name, 0, sizeof(name) );
if( _getsockname( cmpl->s, (struct sockaddr *)&name, &namelen ) == SOCKET_ERROR ) {
D(bug("_getsockname() failed, error=%d\r\n", _WSAGetLastError() ));
} else {
D(bug("_getsockname(): port=%d\r\n", ntohs(name.sin_port) ));
}
int udp_size = sizeof(udp_t) + bytes_read;
udp_t *udp = (udp_t *)malloc( udp_size );
if(udp) {
mac_t *mac = (mac_t *)udp;
ip_t *ip = (ip_t *)udp;
// Build MAC
// memcpy( udp->ip.mac.dest, cmpl->mac_src, 6 );
memcpy( mac->dest, ether_addr, 6 );
memcpy( mac->src, router_mac_addr, 6 );
mac->type = htons(mac_type_ip4);
// Build IP
ip->version = 4;
ip->header_len = 5;
ip->tos = 0;
ip->total_len = htons(sizeof(udp_t) - sizeof(mac_t) + bytes_read); // no options
ip->ident = htons(next_ip_ident_number++); // htons() might be a macro... but does not really matter here.
ip->flags_n_frag_offset = 0;
ip->ttl = 128; // one hop actually!
ip->proto = ip_proto_udp;
ip->src = htonl(cmpl->ip_dest);
ip->dest = htonl(cmpl->ip_src);
make_ip4_checksum( (ip_t *)udp );
// Copy payload (used by UDP checksum)
memcpy( (char *)udp + sizeof(udp_t), cmpl->buffers[0].buf, bytes_read );
// Build UDP
udp->src_port = htons(cmpl->dest_port);
udp->dest_port = htons(cmpl->src_port);
udp->msg_len = htons(sizeof(udp_t) - sizeof(ip_t) + bytes_read); // no options
make_udp_checksum( udp );
dump_bytes( (uint8 *)udp, udp_size );
enqueue_packet( (uint8 *)udp, udp_size );
free(udp);
}
}
}
if(!is_router_shutting_down && cmpl->s != INVALID_SOCKET && cmpl->b_recfrom()) {
cmpl->socket_ttl = GetTickCount() + 60000L;
} else {
delete_socket( cmpl );
}
}
void write_udp( udp_t *udp, int len )
{
if( len < sizeof(udp_t) ) {
D(bug("Too small udp packet(%d), dropped\r\n", len));
return;
}
uint16 src_port = ntohs(udp->src_port);
uint16 dest_port = ntohs(udp->dest_port);
BOOL ok = true;
socket_t *cmpl = find_socket( src_port, dest_port, IPPROTO_UDP );
BOOL old_socket_found = cmpl != 0;
if(!cmpl) {
cmpl = new socket_t(IPPROTO_UDP);
if(cmpl) {
cmpl->s = _socket( AF_INET, SOCK_DGRAM, IPPROTO_UDP );
if(cmpl->s == INVALID_SOCKET) {
delete cmpl;
cmpl = 0;
ok = false;
} else {
cmpl->src_port = src_port;
cmpl->dest_port = dest_port;
add_socket( cmpl );
}
} else {
ok = false;
}
}
if(ok) {
cmpl->src_port = src_port;
cmpl->dest_port = dest_port;
cmpl->ip_src = ntohl(udp->ip.src);
cmpl->ip_dest = ntohl(udp->ip.dest);
struct sockaddr_in to;
memset( &to, 0, sizeof(to) );
to.sin_family = AF_INET;
to.sin_port = udp->dest_port;
to.sin_addr.s_addr = udp->ip.dest;
char *data = (char *)udp + sizeof(udp_t);
int dlen = len - sizeof(udp_t);
// ttl changed, update checksum
make_udp_checksum( udp );
cmpl->set_ttl( udp->ip.ttl );
bool please_close = true;
/*
Note that broadcast messages fill fail, no setsockopt(SO_BROADCAST).
That's exactly what I want.
*/
if(SOCKET_ERROR != _sendto( cmpl->s, data, dlen, 0, (struct sockaddr *)&to, sizeof(to) )) {
if(old_socket_found) {
// This socket is not overlapped.
please_close = false;
} else {
if(cmpl->b_recfrom()) please_close = false;
}
cmpl->socket_ttl = GetTickCount() + 60000L;
} else {
int socket_error = _WSAGetLastError();
D(bug("_sendto() completed with error %d\r\n", socket_error));
// TODO: check this out: error_winsock_2_icmp() uses router_ip_address
// as source ip; but it's probably allright
error_winsock_2_icmp( socket_error, (ip_t *)udp, len );
}
if(please_close) {
delete_socket(cmpl);
}
}
}
void init_udp()
{
}
void final_udp()
{
}
| 27.710145
| 111
| 0.629707
|
jvernet
|
a7723d0dfd956b5ee13c5cc381229db6ac9a6003
| 7,445
|
cc
|
C++
|
example/http/reply.cc
|
lilialexlee/kit
|
94492e04832749fcdfb7f9fb8a778bb949d5e7d6
|
[
"MIT"
] | 1
|
2015-09-22T15:33:30.000Z
|
2015-09-22T15:33:30.000Z
|
example/http/reply.cc
|
lilialexlee/kit
|
94492e04832749fcdfb7f9fb8a778bb949d5e7d6
|
[
"MIT"
] | null | null | null |
example/http/reply.cc
|
lilialexlee/kit
|
94492e04832749fcdfb7f9fb8a778bb949d5e7d6
|
[
"MIT"
] | null | null | null |
/*
* reply.cc
*
*/
#include "example/http/reply.h"
#include <sstream>
namespace http {
Reply::Reply()
: status_(),
headers_(),
content_() {
}
Reply::~Reply() {
}
namespace {
static const std::string kOkContent = "";
static const std::string kCreatedContent = "<html>"
"<head><title>Created</title></head>"
"<body><h1>201 Created</h1></body>"
"</html>";
static const std::string kAcceptedContent = "<html>"
"<head><title>Accepted</title></head>"
"<body><h1>202 Accepted</h1></body>"
"</html>";
static const std::string kNoContentContent = "<html>"
"<head><title>No Content</title></head>"
"<body><h1>204 Content</h1></body>"
"</html>";
static const std::string kMultipleChoicesContent = "<html>"
"<head><title>Multiple Choices</title></head>"
"<body><h1>300 Multiple Choices</h1></body>"
"</html>";
static const std::string kMovedPermanentlyContent = "<html>"
"<head><title>Moved Permanently</title></head>"
"<body><h1>301 Moved Permanently</h1></body>"
"</html>";
static const std::string kMovedTemporarilyContent = "<html>"
"<head><title>Moved Temporarily</title></head>"
"<body><h1>302 Moved Temporarily</h1></body>"
"</html>";
static const std::string kNotModifiedContent = "<html>"
"<head><title>Not Modified</title></head>"
"<body><h1>304 Not Modified</h1></body>"
"</html>";
static const std::string kBadRequestContent = "<html>"
"<head><title>Bad Request</title></head>"
"<body><h1>400 Bad Request</h1></body>"
"</html>";
static const std::string kUnauthorizedContent = "<html>"
"<head><title>Unauthorized</title></head>"
"<body><h1>401 Unauthorized</h1></body>"
"</html>";
static const std::string kForbiddenContent = "<html>"
"<head><title>Forbidden</title></head>"
"<body><h1>403 Forbidden</h1></body>"
"</html>";
static const std::string kNotFoundContent = "<html>"
"<head><title>Not Found</title></head>"
"<body><h1>404 Not Found</h1></body>"
"</html>";
static const std::string kInternalServerErrorContent = "<html>"
"<head><title>Internal Server Error</title></head>"
"<body><h1>500 Internal Server Error</h1></body>"
"</html>";
static const std::string kNotImplementedContent = "<html>"
"<head><title>Not Implemented</title></head>"
"<body><h1>501 Not Implemented</h1></body>"
"</html>";
static const std::string kBadGatewayContent = "<html>"
"<head><title>Bad Gateway</title></head>"
"<body><h1>502 Bad Gateway</h1></body>"
"</html>";
static const std::string kServiceUnavailableContent = "<html>"
"<head><title>Service Unavailable</title></head>"
"<body><h1>503 Service Unavailable</h1></body>"
"</html>";
const std::string& ToContent(StatusType status) {
switch (status) {
case kOk:
return kOkContent;
case kCreated:
return kCreatedContent;
case kAccepted:
return kAcceptedContent;
case kNoContent:
return kNoContentContent;
case kMultipleChoices:
return kMultipleChoicesContent;
case kMovedPermanently:
return kMovedPermanentlyContent;
case kMovedTemporarily:
return kMovedTemporarilyContent;
case kNotModified:
return kNotModifiedContent;
case kBadRequest:
return kBadRequestContent;
case kUnauthorized:
return kUnauthorizedContent;
case kForbidden:
return kForbiddenContent;
case kNotFound:
return kNotFoundContent;
case kInternalServerError:
return kInternalServerErrorContent;
case kNotImplemented:
return kNotImplementedContent;
case kBadGateway:
return kBadGatewayContent;
case kServiceUnavailable:
return kServiceUnavailableContent;
default:
return kInternalServerErrorContent;
}
}
static const std::string kOkStatusLine = "HTTP/1.0 200 OK\r\n";
static const std::string kCreatedStatusLine = "HTTP/1.0 201 Created\r\n";
static const std::string kAcceptedStatusLine = "HTTP/1.0 202 Accepted\r\n";
static const std::string kNoContentStatusLine = "HTTP/1.0 204 No Content\r\n";
static const std::string kMultipleChoicesStatusLine =
"HTTP/1.0 300 Multiple Choices\r\n";
static const std::string kMovedPermanentlyStatusLine =
"HTTP/1.0 301 Moved Permanently\r\n";
static const std::string kMovedTemporarilyStatusLine =
"HTTP/1.0 302 Moved Temporarily\r\n";
static const std::string kNotModifiedStatusLine =
"HTTP/1.0 304 Not Modified\r\n";
static const std::string kBadRequestStatusLine = "HTTP/1.0 400 Bad Request\r\n";
static const std::string kUnauthorizedStatusLine =
"HTTP/1.0 401 Unauthorized\r\n";
static const std::string kForbiddenStatusLine = "HTTP/1.0 403 Forbidden\r\n";
static const std::string kNotFoundStatusLine = "HTTP/1.0 404 Not Found\r\n";
static const std::string kInternalServerErrorStatusLine =
"HTTP/1.0 500 Internal Server Error\r\n";
static const std::string kNotImplementedStatusLine =
"HTTP/1.0 501 Not Implemented\r\n";
static const std::string kBadGatewayStatusLine = "HTTP/1.0 502 Bad Gateway\r\n";
static const std::string kServiceUnavailableStatusLine =
"HTTP/1.0 503 Service Unavailable\r\n";
const std::string& ToStatusLine(StatusType status) {
switch (status) {
case kOk:
return kOkStatusLine;
case kCreated:
return kCreatedStatusLine;
case kAccepted:
return kAcceptedStatusLine;
case kNoContent:
return kNoContentStatusLine;
case kMultipleChoices:
return kMultipleChoicesStatusLine;
case kMovedPermanently:
return kMovedPermanentlyStatusLine;
case kMovedTemporarily:
return kMovedTemporarilyStatusLine;
case kNotModified:
return kNotModifiedStatusLine;
case kBadRequest:
return kBadRequestStatusLine;
case kUnauthorized:
return kUnauthorizedStatusLine;
case kForbidden:
return kForbiddenStatusLine;
case kNotFound:
return kNotFoundStatusLine;
case kInternalServerError:
return kInternalServerErrorStatusLine;
case kNotImplemented:
return kNotImplementedStatusLine;
case kBadGateway:
return kBadGatewayStatusLine;
case kServiceUnavailable:
return kServiceUnavailableStatusLine;
default:
return kInternalServerErrorStatusLine;
}
}
static const std::string kNameValueSeparator = ": ";
static const std::string kcrlf = "\r\n";
}
ReplyPtr Reply::StockReply(StatusType status) {
ReplyPtr reply(new Reply);
reply->status_ = status;
reply->content_ = ToContent(status);
reply->headers_.resize(2);
reply->headers_[0].name = "Content-Length";
std::ostringstream oss;
oss << reply->content_.size();
reply->headers_[0].value = oss.str();
reply->headers_[1].name = "Content-Type";
reply->headers_[1].value = "text/html";
return reply;
}
int Reply::Decode(kit::Buffer *input) {
//TODO use in client
return -1;
}
void Reply::Encode(kit::Buffer *output) {
output->Write(ToStatusLine(status_));
for (std::size_t i = 0; i < headers_.size(); ++i) {
Header& h = headers_[i];
output->Write(h.name);
output->Write(kNameValueSeparator);
output->Write(h.value);
output->Write(kcrlf);
}
output->Write(kcrlf);
output->Write(content_);
}
}
| 33.088889
| 81
| 0.666353
|
lilialexlee
|
a7737d63dee10bc2687b07e41b2a3cdbe75f5f0f
| 1,449
|
hpp
|
C++
|
PS2b/src/CelestialBody.hpp
|
1ssepehr/UML-Comp-IV
|
b6ae1f9acbb12948ac4da17daa21dfbc353d6ac5
|
[
"MIT"
] | null | null | null |
PS2b/src/CelestialBody.hpp
|
1ssepehr/UML-Comp-IV
|
b6ae1f9acbb12948ac4da17daa21dfbc353d6ac5
|
[
"MIT"
] | null | null | null |
PS2b/src/CelestialBody.hpp
|
1ssepehr/UML-Comp-IV
|
b6ae1f9acbb12948ac4da17daa21dfbc353d6ac5
|
[
"MIT"
] | null | null | null |
// (C) Copyright Seyedsepehr Madani, 2021.
// Distributed under MIT license, available at
// https://opensource.org/licenses/MIT.
#ifndef PS2B_SRC_CELESTIALBODY_HPP_
#define PS2B_SRC_CELESTIALBODY_HPP_ 1
#include <iostream>
#include <stdexcept>
#include <string>
#include <SFML/Graphics.hpp>
#include <SFML/System/Vector2.hpp>
typedef sf::Vector2<double> Point;
class CelestialBody : public sf::Drawable {
public:
CelestialBody() {}
CelestialBody(int x, int y, double v_x, double v_y, double mass,
std::string filename);
void setPosition(float x, float y) { sprite.setPosition(x, y); }
void setScale(float scale) { sprite.setScale(scale, scale); }
private:
// Initialize the object of the target
void loadArtifacts();
virtual void draw(sf::RenderTarget &target, sf::RenderStates states) const; // NOLINT
friend std::istream &operator>>(std::istream &in, CelestialBody &body);
friend std::ostream &operator<<(std::ostream &out, CelestialBody &body);
friend class Universe;
Point r; // Position
Point v; // Velocity
Point a; // Acceleration
Point f; // Net force acting on the body
double mass = 1;
// Runge-Kutta 4th order calculations
Point k1r, k2r, k3r, k4r;
Point k1v, k2v, k3v, k4v;
std::string filename; // Path to file for the texture
sf::Sprite sprite;
sf::Texture texture;
};
#endif // PS2B_SRC_CELESTIALBODY_HPP_
| 28.98
| 89
| 0.6853
|
1ssepehr
|
a77412b46948a37282940d663b0ff44c3f6d3ff7
| 9,535
|
cc
|
C++
|
src/main.cc
|
couetilj/OpenPano
|
f2f9c02cbb82ffed5fceed172a9c458eee5aace3
|
[
"MIT"
] | 1,318
|
2017-02-22T15:59:36.000Z
|
2022-03-31T07:18:41.000Z
|
src/main.cc
|
couetilj/OpenPano
|
f2f9c02cbb82ffed5fceed172a9c458eee5aace3
|
[
"MIT"
] | 91
|
2017-02-14T11:53:46.000Z
|
2022-02-02T21:02:55.000Z
|
src/main.cc
|
couetilj/OpenPano
|
f2f9c02cbb82ffed5fceed172a9c458eee5aace3
|
[
"MIT"
] | 439
|
2017-02-15T04:53:39.000Z
|
2022-03-24T02:16:50.000Z
|
// File: main.cc
// Date: Wed Jun 17 20:29:58 2015 +0800
// Author: Yuxin Wu
#define _USE_MATH_DEFINES
#include <cmath>
#include "feature/extrema.hh"
#include "feature/matcher.hh"
#include "feature/orientation.hh"
#include "lib/mat.h"
#include "lib/config.hh"
#include "lib/geometry.hh"
#include "lib/imgproc.hh"
#include "lib/planedrawer.hh"
#include "lib/polygon.hh"
#include "lib/timer.hh"
#include "stitch/cylstitcher.hh"
#include "stitch/match_info.hh"
#include "stitch/stitcher.hh"
#include "stitch/transform_estimate.hh"
#include "stitch/warp.hh"
#include "common/common.hh"
#include <ctime>
#include <cassert>
#ifdef DISABLE_JPEG
#define IMGFILE(x) #x ".png"
#else
#define IMGFILE(x) #x ".jpg"
#endif
using namespace std;
using namespace pano;
using namespace config;
bool TEMPDEBUG = false;
const int LABEL_LEN = 7;
void test_extrema(const char* fname, int mode) {
auto mat = read_img(fname);
ScaleSpace ss(mat, NUM_OCTAVE, NUM_SCALE);
DOGSpace dog(ss);
ExtremaDetector ex(dog);
PlaneDrawer pld(mat);
if (mode == 0) {
auto extrema = ex.get_raw_extrema();
PP(extrema.size());
for (auto &i : extrema)
pld.cross(i, LABEL_LEN / 2);
} else if (mode == 1) {
auto extrema = ex.get_extrema();
cout << extrema.size() << endl;
for (auto &i : extrema) {
Coor c{(int)(i.real_coor.x * mat.width()), (int)(i.real_coor.y * mat.height())};
pld.cross(c, LABEL_LEN / 2);
}
}
write_rgb(IMGFILE(extrema), mat);
}
void test_orientation(const char* fname) {
auto mat = read_img(fname);
ScaleSpace ss(mat, NUM_OCTAVE, NUM_SCALE);
DOGSpace dog(ss);
ExtremaDetector ex(dog);
auto extrema = ex.get_extrema();
OrientationAssign ort(dog, ss, extrema);
auto oriented_keypoint = ort.work();
PlaneDrawer pld(mat);
pld.set_rand_color();
cout << "FeaturePoint size: " << oriented_keypoint.size() << endl;
for (auto &i : oriented_keypoint)
pld.arrow(Coor(i.real_coor.x * mat.width(), i.real_coor.y * mat.height()), i.dir, LABEL_LEN);
write_rgb(IMGFILE(orientation), mat);
}
// draw feature and their match
void test_match(const char* f1, const char* f2) {
list<Mat32f> imagelist;
Mat32f pic1 = read_img(f1);
Mat32f pic2 = read_img(f2);
imagelist.push_back(pic1);
imagelist.push_back(pic2);
unique_ptr<FeatureDetector> detector;
detector.reset(new SIFTDetector);
vector<Descriptor> feat1 = detector->detect_feature(pic1),
feat2 = detector->detect_feature(pic2);
print_debug("Feature: %lu, %lu\n", feat1.size(), feat2.size());
Mat32f concatenated = hconcat(imagelist);
PlaneDrawer pld(concatenated);
FeatureMatcher match(feat1, feat2);
auto ret = match.match();
print_debug("Match size: %d\n", ret.size());
for (auto &x : ret.data) {
pld.set_rand_color();
Vec2D coor1 = feat1[x.first].coor,
coor2 = feat2[x.second].coor;
Coor icoor1 = Coor(coor1.x + pic1.width()/2, coor1.y + pic1.height()/2);
Coor icoor2 = Coor(coor2.x + pic2.width()/2 + pic1.width(), coor2.y + pic2.height()/2);
pld.circle(icoor1, LABEL_LEN);
pld.circle(icoor2, LABEL_LEN);
pld.line(icoor1, icoor2);
}
write_rgb(IMGFILE(match), concatenated);
}
// draw inliers of the estimated homography
void test_inlier(const char* f1, const char* f2) {
list<Mat32f> imagelist;
Mat32f pic1 = read_img(f1);
Mat32f pic2 = read_img(f2);
imagelist.push_back(pic1);
imagelist.push_back(pic2);
unique_ptr<FeatureDetector> detector;
detector.reset(new SIFTDetector);
vector<Descriptor> feat1 = detector->detect_feature(pic1),
feat2 = detector->detect_feature(pic2);
vector<Vec2D> kp1; for (auto& d : feat1) kp1.emplace_back(d.coor);
vector<Vec2D> kp2; for (auto& d : feat2) kp2.emplace_back(d.coor);
print_debug("Feature: %lu, %lu\n", feat1.size(), feat2.size());
Mat32f concatenated = hconcat(imagelist);
PlaneDrawer pld(concatenated);
FeatureMatcher match(feat1, feat2);
auto ret = match.match();
print_debug("Match size: %d\n", ret.size());
TransformEstimation est(ret, kp1, kp2,
{pic1.width(), pic1.height()}, {pic2.width(), pic2.height()});
MatchInfo info;
est.get_transform(&info);
print_debug("Inlier size: %lu, conf=%lf\n", info.match.size(), info.confidence);
if (info.match.size() == 0)
return;
for (auto &x : info.match) {
pld.set_rand_color();
Vec2D coor1 = x.first,
coor2 = x.second;
Coor icoor1 = Coor(coor1.x + pic1.width()/2, coor1.y + pic1.height()/2);
Coor icoor2 = Coor(coor2.x + pic2.width()/2, coor2.y + pic2.height()/2);
pld.circle(icoor1, LABEL_LEN);
pld.circle(icoor2 + Coor(pic1.width(), 0), LABEL_LEN);
pld.line(icoor1, icoor2 + Coor(pic1.width(), 0));
}
pld.set_color(Color(0,0,0));
Vec2D offset1(pic1.width()/2, pic1.height()/2);
Vec2D offset2(pic2.width()/2 + pic1.width(), pic2.height()/2);
// draw convex hull of inliers
/*
*vector<Vec2D> pts1, pts2;
*for (auto& x : info.match) {
* pts1.emplace_back(x.first + offset1);
* pts2.emplace_back(x.second + offset2, 0));
*}
*auto hull = convex_hull(pts1);
*pld.polygon(hull);
*hull = convex_hull(pts2);
*pld.polygon(hull);
*/
// draw warped four edges
Shape2D shape2{pic2.width(), pic2.height()}, shape1{pic1.width(), pic1.height()};
// draw overlapping region
Matrix homo(3,3);
REP(i, 9) homo.ptr()[i] = info.homo[i];
Homography inv = info.homo.inverse();
auto p = overlap_region(shape1, shape2, homo, inv);
PA(p);
for (auto& v: p) v += offset1;
pld.polygon(p);
Matrix invM(3, 3);
REP(i, 9) invM.ptr()[i] = inv[i];
p = overlap_region(shape2, shape1, invM, info.homo);
PA(p);
for (auto& v: p) v += offset2;
pld.polygon(p);
write_rgb(IMGFILE(inlier), concatenated);
}
void test_warp(int argc, char* argv[]) {
CylinderWarper warp(1);
REPL(i, 2, argc) {
Mat32f mat = read_img(argv[i]);
warp.warp(mat);
write_rgb(("warp" + to_string(i) + ".jpg").c_str(), mat);
}
}
void work(int argc, char* argv[]) {
/*
* vector<Mat32f> imgs(argc - 1);
* {
* GuardedTimer tm("Read images");
*#pragma omp parallel for schedule(dynamic)
* REPL(i, 1, argc)
* imgs[i-1] = read_img(argv[i]);
* }
*/
vector<string> imgs;
REPL(i, 1, argc) imgs.emplace_back(argv[i]);
Mat32f res;
if (CYLINDER) {
CylinderStitcher p(move(imgs));
res = p.build();
} else {
Stitcher p(move(imgs));
res = p.build();
}
if (CROP) {
int oldw = res.width(), oldh = res.height();
res = crop(res);
print_debug("Crop from %dx%d to %dx%d\n", oldw, oldh, res.width(), res.height());
}
{
GuardedTimer tm("Writing image");
write_rgb(IMGFILE(out), res);
}
}
void init_config() {
#define CFG(x) \
x = Config.get(#x)
const char* config_file = "config.cfg";
ConfigParser Config(config_file);
CFG(CYLINDER);
CFG(TRANS);
CFG(ESTIMATE_CAMERA);
if (int(CYLINDER) + int(TRANS) + int(ESTIMATE_CAMERA) >= 2)
error_exit("You set two many modes...\n");
if (CYLINDER)
print_debug("Run with cylinder mode.\n");
else if (TRANS)
print_debug("Run with translation mode.\n");
else if (ESTIMATE_CAMERA)
print_debug("Run with camera estimation mode.\n");
else
print_debug("Run with naive mode.\n");
CFG(ORDERED_INPUT);
if (!ORDERED_INPUT && !ESTIMATE_CAMERA)
error_exit("Require ORDERED_INPUT under this mode!\n");
CFG(CROP);
CFG(STRAIGHTEN);
CFG(FOCAL_LENGTH);
CFG(MAX_OUTPUT_SIZE);
CFG(LAZY_READ); // TODO in cyl mode
CFG(SIFT_WORKING_SIZE);
CFG(NUM_OCTAVE);
CFG(NUM_SCALE);
CFG(SCALE_FACTOR);
CFG(GAUSS_SIGMA);
CFG(GAUSS_WINDOW_FACTOR);
CFG(JUDGE_EXTREMA_DIFF_THRES);
CFG(CONTRAST_THRES);
CFG(PRE_COLOR_THRES);
CFG(EDGE_RATIO);
CFG(CALC_OFFSET_DEPTH);
CFG(OFFSET_THRES);
CFG(ORI_RADIUS);
CFG(ORI_HIST_SMOOTH_COUNT);
CFG(DESC_HIST_SCALE_FACTOR);
CFG(DESC_INT_FACTOR);
CFG(MATCH_REJECT_NEXT_RATIO);
CFG(RANSAC_ITERATIONS);
CFG(RANSAC_INLIER_THRES);
CFG(INLIER_IN_MATCH_RATIO);
CFG(INLIER_IN_POINTS_RATIO);
CFG(SLOPE_PLAIN);
CFG(LM_LAMBDA);
CFG(MULTIPASS_BA);
CFG(MULTIBAND);
#undef CFG
}
void planet(const char* fname) {
Mat32f test = read_img(fname);
int w = test.width(), h = test.height();
const int OUTSIZE = 1000, center = OUTSIZE / 2;
Mat32f ret(OUTSIZE, OUTSIZE, 3);
fill(ret, Color::NO);
REP(i, OUTSIZE) REP(j, OUTSIZE) {
real_t dist = hypot(center - i, center - j);
if (dist >= center || dist == 0) continue;
dist = dist / center;
//dist = sqr(dist); // TODO you can change this to see different effect
dist = h - dist * h;
real_t theta;
if (j == center) {
if (i < center)
theta = M_PI / 2;
else
theta = 3 * M_PI / 2;
} else {
theta = atan((real_t)(center - i) / (center - j));
if (theta < 0) theta += M_PI;
if ((theta == 0) && (j > center)) theta += M_PI;
if (center < i) theta += M_PI;
}
m_assert(0 <= theta);
m_assert(2 * M_PI + EPS >= theta);
theta = theta / (M_PI * 2) * w;
update_min(dist, (real_t)h - 1);
Color c = interpolate(test, dist, theta);
float* p = ret.ptr(i, j);
c.write_to(p);
}
write_rgb(IMGFILE(planet), ret);
}
int main(int argc, char* argv[]) {
if (argc <= 2)
error_exit("Need at least two images to stitch.\n");
TotalTimerGlobalGuard _g;
srand(time(NULL));
init_config();
string command = argv[1];
if (command == "raw_extrema")
test_extrema(argv[2], 0);
else if (command == "keypoint")
test_extrema(argv[2], 1);
else if (command == "orientation")
test_orientation(argv[2]);
else if (command == "match")
test_match(argv[2], argv[3]);
else if (command == "inlier")
test_inlier(argv[2], argv[3]);
else if (command == "warp")
test_warp(argc, argv);
else if (command == "planet")
planet(argv[2]);
else
// the real routine
work(argc, argv);
}
| 26.634078
| 95
| 0.669324
|
couetilj
|
a77778e26d27915561c2da2e9eb3194c38dade69
| 9,974
|
cpp
|
C++
|
014_mirror_plane_fb/main.cpp
|
capnramses/gfx_expmts
|
f32f6f50a832383f24eccc43918069e51e6382b5
|
[
"Apache-2.0"
] | 46
|
2019-10-23T01:44:21.000Z
|
2021-06-28T07:48:57.000Z
|
014_mirror_plane_fb/main.cpp
|
capnramses/gfx_expmts
|
f32f6f50a832383f24eccc43918069e51e6382b5
|
[
"Apache-2.0"
] | null | null | null |
014_mirror_plane_fb/main.cpp
|
capnramses/gfx_expmts
|
f32f6f50a832383f24eccc43918069e51e6382b5
|
[
"Apache-2.0"
] | 2
|
2020-06-01T02:12:41.000Z
|
2021-04-13T16:53:47.000Z
|
/******************************************************************************\
| OpenGL 4 Example Code. |
| Accompanies written series "Anton's OpenGL 4 Tutorials" |
| Email: anton at antongerdelan dot net |
| First version 27 Jan 2014 |
| Copyright Dr Anton Gerdelan, Trinity College Dublin, Ireland. |
| See individual libraries for separate legal notices |
|******************************************************************************|
| Doing post-processing with a secondary framebuffer |
\******************************************************************************/
#include "gl_utils.h"
#include "obj_parser.h"
#include "maths_funcs.h"
#include <GL/glew.h> // include GLEW and new version of GL on Windows
#include <GLFW/glfw3.h> // GLFW helper library
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#define POST_VS "post.vert"
#define POST_FS "post.frag"
#define SPHERE_VS "sphere.vert"
#define SPHERE_FS "sphere.frag"
#define MESH_FILE "sphere.obj"
/* window global variables */
int g_gl_width = 800;
int g_gl_height = 800;
GLFWwindow* g_window = NULL;
/* global variables for the secondary framebuffer handle and attached texture */
GLuint g_fb = 0;
GLuint g_fb_tex = 0;
/* global variable for the screen-space quad that we will draw */
GLuint g_ss_quad_vao = 0;
/* sphere */
GLuint g_sphere_vao = 0;
int g_sphere_point_count = 0;
struct Material_Water {
GLuint sp;
GLint P_loc, V_loc, M_loc;
GLint tex_loc;
GLuint tex_id;
};
Material_Water g_material_water;
/* initialise secondary framebuffer. this will just allow us to render our main
scene to a texture instead of directly to the screen. returns false if something
went wrong in the framebuffer creation */
bool init_fb () {
glGenFramebuffers (1, &g_fb);
/* create the texture that will be attached to the fb. should be the same
dimensions as the viewport */
glGenTextures (1, &g_fb_tex);
glBindTexture (GL_TEXTURE_2D, g_fb_tex);
glTexImage2D (
GL_TEXTURE_2D,
0,
GL_RGBA,
g_gl_width,
g_gl_height,
0,
GL_RGBA,
GL_UNSIGNED_BYTE,
NULL
);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
/* attach the texture to the framebuffer */
glBindFramebuffer (GL_FRAMEBUFFER, g_fb);
glFramebufferTexture2D (
GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, g_fb_tex, 0
);
/* create a renderbuffer which allows depth-testing in the framebuffer */
GLuint rb = 0;
glGenRenderbuffers (1, &rb);
glBindRenderbuffer (GL_RENDERBUFFER, rb);
glRenderbufferStorage (
GL_RENDERBUFFER, GL_DEPTH_COMPONENT, g_gl_width, g_gl_height
);
/* attach renderbuffer to framebuffer */
glFramebufferRenderbuffer (
GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rb
);
/* tell the framebuffer to expect a colour output attachment (our texture) */
GLenum draw_bufs[] = { GL_COLOR_ATTACHMENT0 };
glDrawBuffers (1, draw_bufs);
/* validate the framebuffer - an 'incomplete' error tells us if an invalid
image format is attached or if the glDrawBuffers information is invalid */
GLenum status = glCheckFramebufferStatus (GL_FRAMEBUFFER);
if (GL_FRAMEBUFFER_COMPLETE != status) {
fprintf (stderr, "ERROR: incomplete framebuffer\n");
if (GL_FRAMEBUFFER_UNDEFINED == status) {
fprintf (stderr, "GL_FRAMEBUFFER_UNDEFINED\n");
} else if (GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT == status) {
fprintf (stderr, "GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT\n");
} else if (GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT == status) {
fprintf (stderr, "GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT\n");
} else if (GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER == status) {
fprintf (stderr, "GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER\n");
} else if (GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER== status) {
fprintf (stderr, "GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER\n");
} else if (GL_FRAMEBUFFER_UNSUPPORTED == status) {
fprintf (stderr, "GL_FRAMEBUFFER_UNSUPPORTED\n");
} else if (GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE == status) {
fprintf (stderr, "GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE\n");
} else if (GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS == status) {
fprintf (stderr, "GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS\n");
} else {
fprintf (stderr, "unspecified error\n");
}
return false;
}
/* re-bind the default framebuffer as a safe precaution */
glBindFramebuffer (GL_FRAMEBUFFER, 0);
return true;
}
/* create 2 triangles that cover the whole screen. after rendering the scene to
a texture we will texture the quad with it. this will look like a normal scene
rendering, but means that we can perform image filters after all the rendering
is done */
void init_ss_quad () {
// x,y vertex positions
GLfloat ss_quad_pos[] = {
-1.0, -1.0,
1.0, -1.0,
1.0, 1.0,
1.0, 1.0,
-1.0, 1.0,
-1.0, -1.0
};
// create VBOs and VAO in the usual way
glGenVertexArrays (1, &g_ss_quad_vao);
glBindVertexArray (g_ss_quad_vao);
GLuint vbo;
glGenBuffers (1, &vbo);
glBindBuffer (GL_ARRAY_BUFFER, vbo);
glBufferData (
GL_ARRAY_BUFFER,
sizeof (ss_quad_pos),
ss_quad_pos,
GL_STATIC_DRAW
);
glVertexAttribPointer (0, 2, GL_FLOAT, GL_FALSE, 0, NULL);
glEnableVertexAttribArray (0);
}
void load_sphere () {
float* points = NULL;
float* tex_coords = NULL;
float* normals = NULL;
g_sphere_point_count = 0;
assert (load_obj_file (
MESH_FILE,
points,
tex_coords,
normals,
g_sphere_point_count
));
glGenVertexArrays (1, &g_sphere_vao);
glBindVertexArray (g_sphere_vao);
GLuint vbo;
glGenBuffers (1, &vbo);
glBindBuffer (GL_ARRAY_BUFFER, vbo);
glBufferData (
GL_ARRAY_BUFFER,
sizeof (float) * 3 * g_sphere_point_count,
points,
GL_STATIC_DRAW
);
glVertexAttribPointer (0, 3, GL_FLOAT, GL_FALSE, 0, NULL);
glEnableVertexAttribArray (0);
}
int main () {
assert (restart_gl_log ());
assert (start_gl ());
init_ss_quad ();
/* set up framebuffer with texture attachment */
assert (init_fb ());
/* load the post-processing effect shaders */
GLuint post_sp = create_programme_from_files (POST_VS, POST_FS);
GLint post_t_loc = glGetUniformLocation (post_sp, "t");
/* load a mesh to draw in the main scene */
load_sphere ();
GLuint sphere_sp = create_programme_from_files (SPHERE_VS, SPHERE_FS);
GLint sphere_P_loc = glGetUniformLocation (sphere_sp, "P");
GLint sphere_V_loc = glGetUniformLocation (sphere_sp, "V");
assert (sphere_P_loc > -1);
assert (sphere_V_loc > -1);
/* set up view and projection matrices for sphere shader */
mat4 P = perspective (
67.0f, (float)g_gl_width / (float)g_gl_height, 0.1f, 100.0f);
mat4 V = look_at (
vec3 (0.0f, 5.0f, 10.0f), vec3 (0.0f, 0.0f, 0.0f), normalise (vec3 (0.0f, 1.0f, -2.0f)));
glUseProgram (sphere_sp);
glUniformMatrix4fv (sphere_P_loc, 1, GL_FALSE, P.m);
glUniformMatrix4fv (sphere_V_loc, 1, GL_FALSE, V.m);
// water bits
memset (&g_material_water, 0, sizeof (Material_Water));
g_material_water.sp = create_programme_from_files ("water.vert", "water.frag");
g_material_water.P_loc = glGetUniformLocation (g_material_water.sp, "P");
g_material_water.V_loc = glGetUniformLocation (g_material_water.sp, "V");
g_material_water.M_loc = glGetUniformLocation (g_material_water.sp, "M");
g_material_water.tex_loc = glGetUniformLocation (g_material_water.sp, "tex");
glUseProgram (g_material_water.sp);
glUniformMatrix4fv (g_material_water.P_loc, 1, GL_FALSE, P.m);
glUniformMatrix4fv (g_material_water.V_loc, 1, GL_FALSE, V.m);
mat4 M = rotate_x_deg (scale (identity_mat4 (), vec3 (10.0f, 10.0f, 10.0f)), 90.0f);
glUniformMatrix4fv (g_material_water.M_loc, 1, GL_FALSE, M.m);
glUniform1i (g_material_water.tex_loc, 0);
glViewport (0, 0, g_gl_width, g_gl_height);
while (!glfwWindowShouldClose (g_window)) {
_update_fps_counter (g_window);
/* bind the 'render to a texture' framebuffer for main scene */
glBindFramebuffer (GL_FRAMEBUFFER, g_fb);
/* clear the framebuffer's colour and depth buffers */
glClearColor (0.2, 0.2, 0.2, 1.0);
glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable (GL_DEPTH_TEST);
glDepthFunc (GL_LESS);
glEnable (GL_CULL_FACE); // cull face
glCullFace (GL_BACK); // cull back face
glFrontFace (GL_CW); // GL_CCW for counter clock-wise
// render an obj or something
glUseProgram (sphere_sp);
glBindVertexArray (g_sphere_vao);
glDrawArrays (GL_TRIANGLES, 0, g_sphere_point_count);
// draw water plane
glBindVertexArray (g_ss_quad_vao);
glUseProgram (g_material_water.sp);
// glEnable (GL_DEPTH_TEST);
// glEnable (GL_CULL_FACE); // cull face
glDrawArrays (GL_TRIANGLES, 0, 6);
/* bind default framebuffer for post-processing effects. sample texture
from previous pass */
glBindFramebuffer (GL_FRAMEBUFFER, 0);
// clear the framebuffer's colour and depth buffers
//glClearColor (0.0, 0.0, 0.0, 1.0);
glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// use our post-processing shader for the screen-space quad
glUseProgram (post_sp);
glUniform1f (post_t_loc, (float)glfwGetTime ());
// bind the quad's VAO
glBindVertexArray (g_ss_quad_vao);
glDisable (GL_DEPTH_TEST);
glDisable (GL_CULL_FACE); // cull face
// activate the first texture slot and put texture from previous pass in it
glActiveTexture (GL_TEXTURE0);
glBindTexture (GL_TEXTURE_2D, g_fb_tex);
// draw the quad that covers the screen area
glDrawArrays (GL_TRIANGLES, 0, 6);
// flip drawn framebuffer onto the display
glfwSwapBuffers (g_window);
glfwPollEvents ();
if (GLFW_PRESS == glfwGetKey (g_window, GLFW_KEY_ESCAPE)) {
glfwSetWindowShouldClose (g_window, 1);
}
}
return 0;
}
| 35.749104
| 91
| 0.707941
|
capnramses
|
a779d6b1197f511f6387dd2004753de9d8971b39
| 5,729
|
cpp
|
C++
|
source/MaterialXRender/TinyObjLoader.cpp
|
mjyip-lucasfilm/MaterialX
|
19b0bd84c4537539350c1c065cc68fb400567f05
|
[
"BSD-3-Clause"
] | null | null | null |
source/MaterialXRender/TinyObjLoader.cpp
|
mjyip-lucasfilm/MaterialX
|
19b0bd84c4537539350c1c065cc68fb400567f05
|
[
"BSD-3-Clause"
] | null | null | null |
source/MaterialXRender/TinyObjLoader.cpp
|
mjyip-lucasfilm/MaterialX
|
19b0bd84c4537539350c1c065cc68fb400567f05
|
[
"BSD-3-Clause"
] | null | null | null |
//
// TM & (c) 2017 Lucasfilm Entertainment Company Ltd. and Lucasfilm Ltd.
// All rights reserved. See LICENSE.txt for license.
//
#include <MaterialXRender/TinyObjLoader.h>
#include <MaterialXCore/Util.h>
#if defined(__GNUC__) && !defined(__clang__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
#endif
#define TINYOBJLOADER_IMPLEMENTATION
#include <MaterialXRender/External/TinyObjLoader/tiny_obj_loader.h>
#if defined(__GNUC__) && !defined(__clang__)
#pragma GCC diagnostic pop
#endif
#include <iostream>
namespace MaterialX
{
namespace {
const float MAX_FLOAT = std::numeric_limits<float>::max();
const size_t FACE_VERTEX_COUNT = 3;
class VertexVector : public VectorN<VertexVector, float, 8>
{
public:
using VectorN<VertexVector, float, 8>::VectorN;
VertexVector(const Vector3& p, const Vector3& n, const Vector2& t) : VectorN(Uninit{})
{
_arr = {p[0], p[1], p[2], n[0], n[1], n[2], t[0], t[1]};
}
};
using VertexIndexMap = std::unordered_map<VertexVector, uint32_t, VertexVector::Hash>;
} // anonymous namespace
//
// TinyObjLoader methods
//
bool TinyObjLoader::load(const FilePath& filePath, MeshList& meshList)
{
tinyobj::attrib_t attrib;
vector<tinyobj::shape_t> shapes;
vector<tinyobj::material_t> materials;
string err;
bool load = tinyobj::LoadObj(&attrib, &shapes, &materials, nullptr, &err,
filePath.asString().c_str(), nullptr, true, false);
if (!load)
{
std::cerr << err << std::endl;
return false;
}
if (!attrib.vertices.size())
{
return false;
}
MeshPtr mesh = Mesh::create(filePath);
meshList.push_back(mesh);
mesh->setSourceUri(filePath);
MeshStreamPtr positionStream = MeshStream::create("i_" + MeshStream::POSITION_ATTRIBUTE, MeshStream::POSITION_ATTRIBUTE, 0);
MeshStreamPtr normalStream = MeshStream::create("i_" + MeshStream::NORMAL_ATTRIBUTE, MeshStream::NORMAL_ATTRIBUTE, 0);
MeshStreamPtr texcoordStream = MeshStream::create("i_" + MeshStream::TEXCOORD_ATTRIBUTE + "_0", MeshStream::TEXCOORD_ATTRIBUTE, 0);
texcoordStream->setStride(MeshStream::STRIDE_2D);
Vector3 boxMin = { MAX_FLOAT, MAX_FLOAT, MAX_FLOAT };
Vector3 boxMax = { -MAX_FLOAT, -MAX_FLOAT, -MAX_FLOAT };
VertexIndexMap vertexIndexMap;
uint32_t nextVertexIndex = 0;
bool normalsFound = false;
for (const tinyobj::shape_t& shape : shapes)
{
size_t indexCount = shape.mesh.indices.size();
if (indexCount == 0)
{
continue;
}
size_t faceCount = indexCount / FACE_VERTEX_COUNT;
MeshPartitionPtr part = MeshPartition::create();
part->setName(shape.name);
part->setFaceCount(faceCount);
mesh->addPartition(part);
MeshIndexBuffer& indices = part->getIndices();
indices.resize(indexCount);
for (size_t i = 0; i < shape.mesh.indices.size(); i++)
{
const tinyobj::index_t& indexObj = shape.mesh.indices[i];
// Read vertex components.
Vector3 position, normal;
Vector2 texcoord;
for (unsigned int k = 0; k < MeshStream::STRIDE_3D; k++)
{
position[k] = attrib.vertices[indexObj.vertex_index * MeshStream::STRIDE_3D + k];
if (indexObj.normal_index >= 0)
{
normal[k] = attrib.normals[indexObj.normal_index * MeshStream::STRIDE_3D + k];
normalsFound = true;
}
if (indexObj.texcoord_index >= 0 && k < MeshStream::STRIDE_2D)
{
texcoord[k] = attrib.texcoords[indexObj.texcoord_index * MeshStream::STRIDE_2D + k];
}
}
// Check for duplicate vertices.
VertexVector vec(position, normal, texcoord);
VertexIndexMap::iterator it = vertexIndexMap.find(vec);
if (it != vertexIndexMap.end())
{
indices[i] = it->second;
continue;
}
vertexIndexMap[vec] = nextVertexIndex;
// Store vertex components.
for (unsigned int k = 0; k < MeshStream::STRIDE_3D; k++)
{
positionStream->getData().push_back(position[k]);
normalStream->getData().push_back(normal[k]);
if (k < MeshStream::STRIDE_2D)
{
texcoordStream->getData().push_back(texcoord[k]);
}
// Update bounds.
boxMin[k] = std::min(position[k], boxMin[k]);
boxMax[k] = std::max(position[k], boxMax[k]);
}
// Store index data.
indices[i] = nextVertexIndex++;
}
}
// Generate normals if needed.
if (!normalsFound)
{
normalStream = mesh->generateNormals(positionStream);
}
// Generate tangents.
MeshStreamPtr tangentStream = mesh->generateTangents(positionStream, normalStream, texcoordStream);
// Assign streams to mesh.
mesh->addStream(positionStream);
mesh->addStream(normalStream);
mesh->addStream(texcoordStream);
if (tangentStream)
{
mesh->addStream(tangentStream);
}
// Assign properties to mesh.
mesh->setVertexCount(positionStream->getData().size() / MeshStream::STRIDE_3D);
mesh->setMinimumBounds(boxMin);
mesh->setMaximumBounds(boxMax);
Vector3 sphereCenter = (boxMax + boxMin) * 0.5;
mesh->setSphereCenter(sphereCenter);
mesh->setSphereRadius((sphereCenter - boxMin).getMagnitude());
return true;
}
} // namespace MaterialX
| 31.651934
| 135
| 0.612149
|
mjyip-lucasfilm
|
a77a5dffee4dc9215b1a738b3cfdee76b21af1d8
| 7,516
|
hpp
|
C++
|
include/eglplus/context.hpp
|
Extrunder/oglplus
|
c7c8266a1571d0b4c8b02d9c8ca6a7b6a6f51791
|
[
"BSL-1.0"
] | 459
|
2016-03-16T04:11:37.000Z
|
2022-03-31T08:05:21.000Z
|
include/eglplus/context.hpp
|
Extrunder/oglplus
|
c7c8266a1571d0b4c8b02d9c8ca6a7b6a6f51791
|
[
"BSL-1.0"
] | 2
|
2016-08-08T18:26:27.000Z
|
2017-05-08T23:42:22.000Z
|
include/eglplus/context.hpp
|
Extrunder/oglplus
|
c7c8266a1571d0b4c8b02d9c8ca6a7b6a6f51791
|
[
"BSL-1.0"
] | 47
|
2016-05-31T15:55:52.000Z
|
2022-03-28T14:49:40.000Z
|
/**
* @file eglplus/context.hpp
* @brief Declares and implements wrapper for EGLContext
*
* @author Matus Chochlik
*
* Copyright 2012-2015 Matus Chochlik. Distributed under the Boost
* Software License, Version 1.0. (See accompanying file
* LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#pragma once
#ifndef EGLPLUS_CONTEXT_1305291005_HPP
#define EGLPLUS_CONTEXT_1305291005_HPP
#include <eglplus/eglfunc.hpp>
#include <eglplus/error/basic.hpp>
#include <eglplus/boolean.hpp>
#include <eglplus/display.hpp>
#include <eglplus/configs.hpp>
#include <eglplus/surface.hpp>
#include <eglplus/attrib_list.hpp>
#include <eglplus/context_attrib.hpp>
#include <eglplus/context_flag.hpp>
#include <eglplus/opengl_profile_bit.hpp>
#include <eglplus/opengl_rns.hpp>
namespace eglplus {
struct ContextValueTypeToContextAttrib
{
#ifdef EGL_CONTEXT_FLAGS
static ContextFlag
ValueType(std::integral_constant<int, 0>);
ContextAttrib operator()(ContextFlag) const
{
return ContextAttrib::Flags;
}
#endif
#ifdef EGL_CONTEXT_OPENGL_PROFILE_MASK
static OpenGLProfileBit
ValueType(std::integral_constant<int, 1>);
ContextAttrib operator()(OpenGLProfileBit) const
{
return ContextAttrib::OpenGLProfileMask;
}
#endif
#ifdef EGL_CONTEXT_OPENGL_RESET_NOTIFICATION_STRATEGY
static OpenGLResetNotificationStrategy
ValueType(std::integral_constant<int, 2>);
ContextAttrib operator()(OpenGLResetNotificationStrategy) const
{
return ContextAttrib::OpenGLResetNotificationStrategy;
}
#endif
static std::integral_constant<int, 2> MaxValueType(void);
};
/// Attribute list for context attributes
typedef AttributeList<
ContextAttrib,
ContextValueTypeToContextAttrib,
AttributeListTraits
> ContextAttribs;
/// Finished list of context attribute values
typedef FinishedAttributeList<
ContextAttrib,
AttributeListTraits
> FinishedContextAttribs;
class Context;
::EGLContext GetEGLHandle(const Context&)
OGLPLUS_NOEXCEPT(true);
/// Wrapper around EGLContext
class Context
{
private:
Display _display;
::EGLContext _handle;
friend ::EGLContext GetEGLHandle(const Context&)
OGLPLUS_NOEXCEPT(true);
Context(const Context&);
Context(
Display display,
::EGLContext handle
): _display(display)
, _handle(handle)
{ }
static ::EGLContext _init(
const Display& display,
const Config& config,
::EGLContext share_context,
const EGLint* attribs
)
{
::EGLContext result = EGLPLUS_EGLFUNC(CreateContext)(
GetEGLHandle(display),
GetEGLHandle(config),
share_context,
attribs
);
EGLPLUS_VERIFY_SIMPLE(CreateContext);
return result;
}
public:
/// Contexts are move constructible
Context(Context&& tmp)
: _display(tmp._display)
, _handle(tmp._handle)
{
tmp._handle = EGL_NO_CONTEXT;
}
/// Construct a non-sharing context without any attributes
/**
* @eglsymbols
* @eglfunref{CreateContext}
*/
Context(
const Display& display,
const Config& config
): _display(display)
, _handle(_init(display, config, EGL_NO_CONTEXT, nullptr))
{ }
/// Construct a sharing context without any attributes
/**
* @eglsymbols
* @eglfunref{CreateContext}
*/
Context(
const Display& display,
const Config& config,
const Context& shared_context
): _display(display)
, _handle(_init(display, config, shared_context._handle, nullptr))
{ }
/// Construct a non-sharing context with attributes
/**
* @eglsymbols
* @eglfunref{CreateContext}
*/
Context(
const Display& display,
const Config& config,
const FinishedContextAttribs& attribs
): _display(display)
, _handle(_init(display, config, EGL_NO_CONTEXT, attribs.Get()))
{ }
/// Construct a sharing context without any attributes
/**
* @eglsymbols
* @eglfunref{CreateContext}
*/
Context(
const Display& display,
const Config& config,
const Context& shared_context,
const FinishedContextAttribs& attribs
): _display(display)
, _handle(_init(display, config, shared_context._handle, attribs.Get()))
{ }
/// Destroys the wrapped context
/**
* @eglsymbols
* @eglfunref{DestroyContext}
*/
~Context(void)
{
if(_handle != EGL_NO_CONTEXT)
{
EGLPLUS_EGLFUNC(DestroyContext)(
GetEGLHandle(_display),
_handle
);
EGLPLUS_VERIFY_SIMPLE(DestroyContext);
}
}
/// Makes the context current
/**
* @eglsymbols
* @eglfunref{MakeCurrent}
*/
Boolean MakeCurrent(
const Surface& draw_surface,
const Surface& read_surface
)
{
Boolean result(
EGLPLUS_EGLFUNC(MakeCurrent)(
GetEGLHandle(_display),
GetEGLHandle(draw_surface),
GetEGLHandle(read_surface),
_handle
), std::nothrow
);
EGLPLUS_CHECK_SIMPLE(MakeCurrent);
return result;
}
/// Makes the context current
/**
* @eglsymbols
* @eglfunref{MakeCurrent}
*/
Boolean MakeCurrent(const Surface& surface)
{
Boolean result(
EGLPLUS_EGLFUNC(MakeCurrent)(
GetEGLHandle(_display),
GetEGLHandle(surface),
GetEGLHandle(surface),
_handle
), std::nothrow
);
EGLPLUS_CHECK_SIMPLE(MakeCurrent);
return result;
}
/// Makes the context current without surfaces
/**
* @note This function works only if EGL implements
* the EGL_KHR_surfaceless_context extension.
*
* @eglsymbols
* @eglfunref{MakeCurrent}
*/
Boolean MakeCurrent(void)
{
Boolean result(
EGLPLUS_EGLFUNC(MakeCurrent)(
GetEGLHandle(_display),
EGL_NO_SURFACE,
EGL_NO_SURFACE,
_handle
), std::nothrow
);
EGLPLUS_CHECK_SIMPLE(MakeCurrent);
return result;
}
/// Releases the current context without assigning a new one
/**
* @eglsymbols
* @eglfunref{MakeCurrent}
*/
Boolean Release(void)
{
Boolean result(
EGLPLUS_EGLFUNC(MakeCurrent)(
GetEGLHandle(_display),
EGL_NO_SURFACE,
EGL_NO_SURFACE,
EGL_NO_CONTEXT
), std::nothrow
);
EGLPLUS_CHECK_SIMPLE(MakeCurrent);
return result;
}
/// Queries a context attribute
/**
* @eglsymbols
* @eglfunref{QueryContext}
*/
Boolean Query(ContextAttrib attrib, EGLint& value) const
{
Boolean result(
EGLPLUS_EGLFUNC(QueryContext)(
GetEGLHandle(_display),
_handle,
EGLint(EGLenum(attrib)),
&value
), std::nothrow
);
EGLPLUS_CHECK_SIMPLE(QueryContext);
return result;
}
/// Returns the context framebuffer config id
/**
* @eglsymbols
* @eglfunref{QueryContext}
*/
EGLint ConfigId(void) const
{
EGLint result = 0;
EGLPLUS_EGLFUNC(QueryContext)(
GetEGLHandle(_display),
_handle,
EGLint(EGL_CONFIG_ID),
&result
);
EGLPLUS_CHECK_SIMPLE(QueryContext);
return result;
}
/// Wait for client API commands to complete
/**
* @eglsymbols
* @eglfunref{WaitClient}
*/
Boolean WaitClient(void) const
{
Boolean result(
EGLPLUS_EGLFUNC(WaitClient)(),
std::nothrow
);
EGLPLUS_VERIFY_SIMPLE(WaitClient);
return result;
}
/// Wait for GL API commands to complete
/**
* @eglsymbols
* @eglfunref{WaitGL}
*/
Boolean WaitGL(void) const
{
Boolean result(
EGLPLUS_EGLFUNC(WaitGL)(),
std::nothrow
);
EGLPLUS_VERIFY_SIMPLE(WaitGL);
return result;
}
/// Wait for native API commands to complete
/**
* @eglsymbols
* @eglfunref{WaitNative}
*/
Boolean WaitNative(EGLint engine) const
{
Boolean result(
EGLPLUS_EGLFUNC(WaitNative)(engine),
std::nothrow
);
EGLPLUS_VERIFY_SIMPLE(WaitNative);
return result;
}
};
inline
::EGLContext GetEGLHandle(const Context& context)
OGLPLUS_NOEXCEPT(true)
{
return context._handle;
}
} // namespace eglplus
#endif // include guard
| 20.368564
| 74
| 0.719931
|
Extrunder
|
a77aed6a55c2a9108d9f042484d45a15fc588ef1
| 4,100
|
hpp
|
C++
|
include/System/LocalDataStoreHolder.hpp
|
v0idp/virtuoso-codegen
|
6f560f04822c67f092d438a3f484249072c1d21d
|
[
"Unlicense"
] | null | null | null |
include/System/LocalDataStoreHolder.hpp
|
v0idp/virtuoso-codegen
|
6f560f04822c67f092d438a3f484249072c1d21d
|
[
"Unlicense"
] | null | null | null |
include/System/LocalDataStoreHolder.hpp
|
v0idp/virtuoso-codegen
|
6f560f04822c67f092d438a3f484249072c1d21d
|
[
"Unlicense"
] | 1
|
2022-03-30T21:07:35.000Z
|
2022-03-30T21:07:35.000Z
|
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System
namespace System {
// Forward declaring type: LocalDataStore
class LocalDataStore;
}
// Completed forward declares
// Type namespace: System
namespace System {
// Forward declaring type: LocalDataStoreHolder
class LocalDataStoreHolder;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::System::LocalDataStoreHolder);
DEFINE_IL2CPP_ARG_TYPE(::System::LocalDataStoreHolder*, "System", "LocalDataStoreHolder");
// Type namespace: System
namespace System {
// Size: 0x18
#pragma pack(push, 1)
// Autogenerated type: System.LocalDataStoreHolder
// [TokenAttribute] Offset: FFFFFFFF
class LocalDataStoreHolder : public ::Il2CppObject {
public:
public:
// private System.LocalDataStore m_Store
// Size: 0x8
// Offset: 0x10
::System::LocalDataStore* m_Store;
// Field size check
static_assert(sizeof(::System::LocalDataStore*) == 0x8);
public:
// Creating conversion operator: operator ::System::LocalDataStore*
constexpr operator ::System::LocalDataStore*() const noexcept {
return m_Store;
}
// Get instance field reference: private System.LocalDataStore m_Store
[[deprecated("Use field access instead!")]] ::System::LocalDataStore*& dyn_m_Store();
// public System.LocalDataStore get_Store()
// Offset: 0x107992C
::System::LocalDataStore* get_Store();
// public System.Void .ctor(System.LocalDataStore store)
// Offset: 0x1079890
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static LocalDataStoreHolder* New_ctor(::System::LocalDataStore* store) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::LocalDataStoreHolder::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<LocalDataStoreHolder*, creationType>(store)));
}
// protected override System.Void Finalize()
// Offset: 0x10798BC
// Implemented from: System.Object
// Base method: System.Void Object::Finalize()
void Finalize();
}; // System.LocalDataStoreHolder
#pragma pack(pop)
static check_size<sizeof(LocalDataStoreHolder), 16 + sizeof(::System::LocalDataStore*)> __System_LocalDataStoreHolderSizeCheck;
static_assert(sizeof(LocalDataStoreHolder) == 0x18);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: System::LocalDataStoreHolder::get_Store
// Il2CppName: get_Store
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::LocalDataStore* (System::LocalDataStoreHolder::*)()>(&System::LocalDataStoreHolder::get_Store)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::LocalDataStoreHolder*), "get_Store", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::LocalDataStoreHolder::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: System::LocalDataStoreHolder::Finalize
// Il2CppName: Finalize
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::LocalDataStoreHolder::*)()>(&System::LocalDataStoreHolder::Finalize)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::LocalDataStoreHolder*), "Finalize", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
| 45.054945
| 176
| 0.734634
|
v0idp
|
a77c5f4c7480608e40356270899a1a92621ec23c
| 551
|
hpp
|
C++
|
src/models/Light.hpp
|
sophia-x/RayTracing
|
1092971b08ff17e8642e408e2cb0c518d6591e2b
|
[
"MIT"
] | 1
|
2016-05-05T10:20:45.000Z
|
2016-05-05T10:20:45.000Z
|
src/models/Light.hpp
|
sophia-x/RayTracing
|
1092971b08ff17e8642e408e2cb0c518d6591e2b
|
[
"MIT"
] | null | null | null |
src/models/Light.hpp
|
sophia-x/RayTracing
|
1092971b08ff17e8642e408e2cb0c518d6591e2b
|
[
"MIT"
] | null | null | null |
#ifndef LIGHT
#define LIGHT
#include "Model.hpp"
#include "../common.hpp"
class Scene;
class Light : public Model {
protected:
vec3 __emission_color;
public:
Light(const Material &material, const vec3 &emission_color): Model(material), __emission_color(emission_color) {}
virtual ~Light() {}
virtual vec3 calcShade(const Scene *scene_ptr, const vec3 &hit_position, float &shade_idx) const = 0;
virtual void transform(const mat4 &transform_matrix) = 0;
inline const vec3 &getEmissionColor() const {
return __emission_color;
}
};
#endif
| 21.192308
| 114
| 0.747731
|
sophia-x
|
a78464a51ea39caa21a418362eff6c4b0ea1d679
| 1,257
|
cpp
|
C++
|
ScriptHookW3/logger.cpp
|
Traderain/ScriptHookW3
|
f80325557662303ff818b3ea1dd0ba8dcebf8c63
|
[
"MIT"
] | 1
|
2021-05-16T19:54:54.000Z
|
2021-05-16T19:54:54.000Z
|
ScriptHookW3/logger.cpp
|
Traderain/ScriptHookW3
|
f80325557662303ff818b3ea1dd0ba8dcebf8c63
|
[
"MIT"
] | null | null | null |
ScriptHookW3/logger.cpp
|
Traderain/ScriptHookW3
|
f80325557662303ff818b3ea1dd0ba8dcebf8c63
|
[
"MIT"
] | null | null | null |
#include "logger.h"
shw3::Logger::Logger() {
this->filestream.open("..\\" TARGET_NAME ".log");
}
shw3::Logger::~Logger() {
if (this->filestream.is_open()) {
std::lock_guard<std::mutex> guard(mtx);
filestream.flush();
filestream.close();
}
}
void shw3::Logger::writeLine() {
if (this->filestream.is_open()) {
std::lock_guard<std::mutex> guard(mtx);
filestream << std::endl;
}
}
std::string shw3::Logger::getTimestamp() {
char buffer[256];
time_t rawtime;
struct tm timeinfo;
time(&rawtime);
localtime_s(&timeinfo, &rawtime);
strftime(buffer, 256, "[%Y-%m-%d %H:%M:%S]", &timeinfo);
return std::string(buffer);
}
std::string shw3::Logger::getThreadId()
{
std::stringstream stream;
stream
<< "0x"
<< std::uppercase
<< std::setfill('0')
<< std::setw(4)
<< std::hex
<< std::this_thread::get_id()
<< std::dec
<< std::setw(0)
<< std::setfill(' ');
return stream.str();
}
std::string shw3::Logger::getLogLevelString(LogLevel level)
{
switch (level) {
case LL_NON:
return "NON";
break;
case LL_ERR:
return "ERR";
break;
case LL_WRN:
return "WRN";
break;
case LL_NFO:
return "NFO";
break;
case LL_DBG:
return "DBG";
break;
case LL_TRC:
return "TRC";
break;
default:
return "UNK";
}
}
| 17.458333
| 59
| 0.627685
|
Traderain
|
a7899a4d67348f36205dd9c07420c0466a4856d7
| 6,053
|
hpp
|
C++
|
include/occa/kernel.hpp
|
v-dobrev/occa
|
58e47f5ccf0d87f5b91e6851b2d74a9456c46b2c
|
[
"MIT"
] | null | null | null |
include/occa/kernel.hpp
|
v-dobrev/occa
|
58e47f5ccf0d87f5b91e6851b2d74a9456c46b2c
|
[
"MIT"
] | null | null | null |
include/occa/kernel.hpp
|
v-dobrev/occa
|
58e47f5ccf0d87f5b91e6851b2d74a9456c46b2c
|
[
"MIT"
] | null | null | null |
/* The MIT License (MIT)
*
* Copyright (c) 2014-2018 David Medina and Tim Warburton
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
*/
#ifndef OCCA_KERNEL_HEADER
#define OCCA_KERNEL_HEADER
#include <iostream>
#include <stdint.h>
#include <vector>
#include <occa/defines.hpp>
#include <occa/kernelArg.hpp>
#include <occa/lang/kernelMetadata.hpp>
#include <occa/tools/gc.hpp>
#include <occa/tools/properties.hpp>
#include <occa/types.hpp>
namespace occa {
class modeKernel_t; class kernel;
class modeMemory_t; class memory;
class modeDevice_t; class device;
class kernelBuilder;
namespace lang {
class parser_t;
}
typedef std::map<hash_t, kernel> hashedKernelMap;
typedef hashedKernelMap::iterator hashedKernelMapIterator;
typedef hashedKernelMap::const_iterator cHashedKernelMapIterator;
typedef std::vector<kernelBuilder> kernelBuilderVector;
typedef kernelBuilderVector::iterator kernelBuilderVectorIterator;
typedef kernelBuilderVector::const_iterator cKernelBuilderVectorIterator;
//---[ modeKernel_t ]---------------------
class modeKernel_t : public gc::ringEntry_t {
public:
occa::modeDevice_t *modeDevice;
std::string name;
std::string sourceFilename, binaryFilename;
occa::properties properties;
gc::ring_t<kernel> kernelRing;
dim outerDims, innerDims;
std::vector<kernelArg> arguments;
lang::kernelMetadata metadata;
modeKernel_t(modeDevice_t *modeDevice_,
const std::string &name_,
const std::string &sourceFilename_,
const occa::properties &properties_);
void dontUseRefs();
void addKernelRef(kernel *ker);
void removeKernelRef(kernel *ker);
bool needsFree() const;
kernelArg* argumentsPtr();
int argumentCount();
void setMetadata(lang::parser_t &parser);
//---[ Virtual Methods ]------------
virtual ~modeKernel_t() = 0;
// Must be able to be called multiple times safely
virtual void free() = 0;
virtual int maxDims() const = 0;
virtual dim maxOuterDims() const = 0;
virtual dim maxInnerDims() const = 0;
virtual void run() const = 0;
//==================================
};
//====================================
//---[ kernel ]-----------------------
class kernel : public gc::ringEntry_t {
friend class occa::modeKernel_t;
friend class occa::device;
private:
modeKernel_t *modeKernel;
public:
kernel();
kernel(modeKernel_t *modeKernel_);
kernel(const kernel &k);
kernel& operator = (const kernel &k);
kernel& operator = (modeKernel_t *modeKernel_);
~kernel();
private:
void assertInitialized() const;
void setModeKernel(modeKernel_t *modeKernel_);
void removeKernelRef();
public:
void dontUseRefs();
bool isInitialized();
const std::string& mode() const;
const occa::properties& properties() const;
modeKernel_t* getModeKernel();
occa::device getDevice();
bool operator == (const occa::kernel &other) const;
bool operator != (const occa::kernel &other) const;
const std::string& name();
const std::string& sourceFilename();
const std::string& binaryFilename();
int maxDims();
dim maxOuterDims();
dim maxInnerDims();
void setRunDims(dim outerDims, dim innerDims);
void addArgument(const int argPos, const kernelArg &arg);
void run() const;
void clearArgumentList();
#include "kernelOperators.hpp"
void free();
};
//====================================
//---[ kernelBuilder ]----------------
class kernelBuilder {
protected:
std::string source_;
std::string function_;
occa::properties props_;
hashedKernelMap kernelMap;
bool buildingFromFile;
public:
kernelBuilder();
kernelBuilder(const kernelBuilder &k);
kernelBuilder& operator = (const kernelBuilder &k);
static kernelBuilder fromFile(const std::string &filename,
const std::string &function,
const occa::properties &props = occa::properties());
static kernelBuilder fromString(const std::string &content,
const std::string &function,
const occa::properties &props = occa::properties());
bool isInitialized();
occa::kernel build(occa::device device);
occa::kernel build(occa::device device,
const occa::properties &props);
occa::kernel build(occa::device device,
const hash_t &hash);
occa::kernel build(occa::device device,
const hash_t &hash,
const occa::properties &props);
occa::kernel operator [] (occa::device device);
void free();
};
//====================================
//---[ Kernel Properties ]------------
std::string assembleHeader(const occa::properties &props);
//====================================
}
#endif
| 28.687204
| 88
| 0.641004
|
v-dobrev
|
a78b450ec07cc7ce52de39a928ef60d518fc2db5
| 5,070
|
cpp
|
C++
|
tests/Core/JPetReader/JPetReaderTest.cpp
|
BlurredChoise/j-pet-framework
|
f6728e027fae2b6ac0bdf274141254689894aa08
|
[
"Apache-2.0"
] | 10
|
2016-07-04T14:54:14.000Z
|
2021-04-11T14:19:29.000Z
|
tests/Core/JPetReader/JPetReaderTest.cpp
|
BlurredChoise/j-pet-framework
|
f6728e027fae2b6ac0bdf274141254689894aa08
|
[
"Apache-2.0"
] | 119
|
2016-06-17T20:22:07.000Z
|
2022-02-21T08:50:22.000Z
|
tests/Core/JPetReader/JPetReaderTest.cpp
|
BlurredChoise/j-pet-framework
|
f6728e027fae2b6ac0bdf274141254689894aa08
|
[
"Apache-2.0"
] | 30
|
2016-06-17T17:56:35.000Z
|
2020-12-30T22:20:19.000Z
|
/**
* @copyright Copyright 2018 The J-PET Framework Authors. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may find a copy of the License in the LICENCE file.
*
* 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.
*
* @file JPetReaderTest.cpp
*/
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE JPetReaderTest
#include "JPetReader/JPetReader.h"
#include "JPetWriter/JPetWriter.h"
#include <TError.h>
#include <TObjString.h>
#include <boost/test/unit_test.hpp>
#include <cstddef>
#include <iostream>
#include <vector>
BOOST_AUTO_TEST_SUITE(JPetReaderTestSuite)
BOOST_AUTO_TEST_CASE(default_constructor)
{
JPetReader reader;
BOOST_REQUIRE_EQUAL(std::string(reader.getCurrentEntry().GetName()), std::string("Empty event"));
BOOST_REQUIRE(!reader.isOpen());
BOOST_REQUIRE(!reader.nextEntry());
BOOST_REQUIRE(!reader.firstEntry());
BOOST_REQUIRE(!reader.lastEntry());
BOOST_REQUIRE(!reader.nthEntry(0));
BOOST_REQUIRE(!reader.nthEntry(1));
BOOST_REQUIRE(!reader.nthEntry(-1));
BOOST_REQUIRE_EQUAL(reader.getCurrentEntryNumber(), -1);
BOOST_REQUIRE_EQUAL(reader.getNbOfAllEntries(), 0);
BOOST_REQUIRE(!reader.getHeaderClone());
BOOST_REQUIRE(!reader.getObjectFromFile("testObj"));
}
BOOST_AUTO_TEST_CASE(bad_file)
{
gErrorIgnoreLevel = 6000;
JPetReader reader;
BOOST_REQUIRE(!reader.openFileAndLoadData("bad_file.txt", "tree"));
BOOST_REQUIRE(!reader.isOpen());
BOOST_REQUIRE_EQUAL(std::string(reader.getCurrentEntry().GetName()), std::string("Empty event"));
BOOST_REQUIRE(!reader.nextEntry());
BOOST_REQUIRE(!reader.firstEntry());
BOOST_REQUIRE(!reader.lastEntry());
BOOST_REQUIRE(!reader.nthEntry(0));
BOOST_REQUIRE(!reader.nthEntry(1));
BOOST_REQUIRE(!reader.nthEntry(-1));
BOOST_REQUIRE_EQUAL(reader.getCurrentEntryNumber(), -1);
BOOST_REQUIRE_EQUAL(reader.getNbOfAllEntries(), 0);
BOOST_REQUIRE(!reader.getHeaderClone());
BOOST_REQUIRE(!reader.getObjectFromFile("testObj"));
}
BOOST_AUTO_TEST_CASE(good_file_with_constructor)
{
JPetReader reader("unitTestData/JPetReaderTest/timewindows_v2.root", "tree");
BOOST_REQUIRE(reader.isOpen());
BOOST_REQUIRE_EQUAL(std::string(reader.getCurrentEntry().GetName()), std::string("JPetTimeWindow"));
BOOST_REQUIRE_EQUAL(reader.getCurrentEntryNumber(), 0);
BOOST_REQUIRE(reader.nextEntry());
BOOST_REQUIRE_EQUAL(reader.getCurrentEntryNumber(), 1);
BOOST_REQUIRE(reader.nextEntry());
BOOST_REQUIRE_EQUAL(reader.getCurrentEntryNumber(), 2);
BOOST_REQUIRE(reader.firstEntry());
BOOST_REQUIRE_EQUAL(reader.getCurrentEntryNumber(), 0);
BOOST_REQUIRE(reader.lastEntry());
BOOST_REQUIRE_EQUAL(reader.getCurrentEntryNumber(), 9);
BOOST_REQUIRE(reader.nthEntry(0));
BOOST_REQUIRE_EQUAL(reader.getCurrentEntryNumber(), 0);
BOOST_REQUIRE(reader.nthEntry(5));
BOOST_REQUIRE_EQUAL(reader.getCurrentEntryNumber(), 5);
BOOST_REQUIRE_EQUAL(reader.getNbOfAllEntries(), 10);
BOOST_REQUIRE(reader.getHeaderClone());
}
BOOST_AUTO_TEST_CASE(good_file_getObject)
{
JPetReader reader("unitTestData/JPetReaderTest/timewindows_v2.root", "tree");
BOOST_REQUIRE(!reader.getObjectFromFile("nonExistentObj"));
BOOST_REQUIRE(reader.getObjectFromFile("tree"));
}
BOOST_AUTO_TEST_CASE(good_file_openFileAndLoadData)
{
JPetReader reader;
BOOST_REQUIRE(reader.openFileAndLoadData("unitTestData/JPetReaderTest/timewindows_v2.root", "tree"));
BOOST_REQUIRE(reader.isOpen());
BOOST_REQUIRE_EQUAL(std::string(reader.getCurrentEntry().GetName()), std::string("JPetTimeWindow"));
BOOST_REQUIRE(reader.firstEntry());
BOOST_REQUIRE(reader.nextEntry());
BOOST_REQUIRE(reader.lastEntry());
BOOST_REQUIRE(reader.nthEntry(0));
BOOST_REQUIRE(reader.nthEntry(5));
BOOST_REQUIRE_EQUAL(reader.getCurrentEntryNumber(), 5);
BOOST_REQUIRE_EQUAL(reader.getNbOfAllEntries(), 10);
BOOST_REQUIRE(reader.getHeaderClone());
}
BOOST_AUTO_TEST_CASE(good_file_closeFile)
{
JPetReader reader;
BOOST_REQUIRE(reader.openFileAndLoadData("unitTestData/JPetReaderTest/timewindows_v2.root", "tree"));
BOOST_REQUIRE(reader.isOpen());
reader.closeFile();
BOOST_REQUIRE(!reader.isOpen());
BOOST_REQUIRE(std::string(reader.getCurrentEntry().GetName()) == std::string("Empty event"));
BOOST_REQUIRE(!reader.nextEntry());
BOOST_REQUIRE(!reader.firstEntry());
BOOST_REQUIRE(!reader.lastEntry());
BOOST_REQUIRE(!reader.nthEntry(0));
BOOST_REQUIRE(!reader.nthEntry(1));
BOOST_REQUIRE(!reader.nthEntry(-1));
BOOST_REQUIRE_EQUAL(reader.getCurrentEntryNumber(), -1);
BOOST_REQUIRE_EQUAL(reader.getNbOfAllEntries(), 0);
BOOST_REQUIRE(!reader.getHeaderClone());
BOOST_REQUIRE(!reader.getObjectFromFile("testObj"));
}
BOOST_AUTO_TEST_SUITE_END()
| 38.120301
| 103
| 0.772781
|
BlurredChoise
|
a78ca61dac9e8f82d618ae48dad53e42dba146c1
| 1,568
|
cpp
|
C++
|
benchmark/rrr_vector/src/generate_rnd_bitvector.cpp
|
qPCR4vir/sdsl-lite
|
3ae7ac30c3837553cf20243cc3df8ee658b9f00f
|
[
"BSD-3-Clause"
] | 20
|
2017-12-26T16:04:18.000Z
|
2022-02-09T03:30:13.000Z
|
benchmark/rrr_vector/src/generate_rnd_bitvector.cpp
|
Irallia/sdsl-lite
|
9a0d5676fd09fb8b52af214eca2d5809c9a32dbe
|
[
"BSD-3-Clause"
] | 6
|
2018-11-12T15:14:24.000Z
|
2021-04-29T14:07:13.000Z
|
benchmark/rrr_vector/src/generate_rnd_bitvector.cpp
|
Irallia/sdsl-lite
|
9a0d5676fd09fb8b52af214eca2d5809c9a32dbe
|
[
"BSD-3-Clause"
] | 4
|
2018-11-12T14:36:34.000Z
|
2021-01-26T22:16:32.000Z
|
#include <iostream>
#include <fstream>
#include <sdsl/int_vector.hpp>
#include <sdsl/util.hpp>
#include <string>
using namespace std;
using namespace sdsl;
int main(int argc, char* argv[])
{
if (argc < 4) {
cout << "Usage: " << argv[0] << " length density file" << endl;
cout << " generates a bit_vector of`length` bits, populates it with " << endl;
cout << " `density`\% set bits and saves it to `file`.\n" << endl;
cout << "`length` format:\n";
cout << " X, where X is the length in number of bytes\n";
cout << " XkB, where X is the length in number of kilobytes\n";
cout << " XMB, where X is the length in number of megabytes\n";
cout << " XGB, where X is the length in number of gigabytes\n";
return 1;
}
uint64_t length = 0;
length = atoll(argv[1])*8; // length in bits
string length_str(argv[1]);
size_t Bpos = length_str.find_first_of("B");
if (Bpos != string::npos and Bpos > 1) {
char order = length_str.substr(Bpos-1,1)[0];
if (order == 'k' or order == 'K')
length <<= 10;
else if (order == 'm' or order == 'M')
length <<= 20;
else if (order == 'g' or order == 'G')
length <<= 30;
}
const uint64_t density = atoi(argv[2]);
cout << length << endl;
bit_vector v(length);
srand(17);
for (uint64_t i=0; i<v.size(); ++i) {
if ((uint64_t)(rand()%100) < density) {
v[i] = 1;
}
}
if (!store_to_file(v, argv[3]))
return 1;
}
| 32.666667
| 86
| 0.540816
|
qPCR4vir
|
a78e212b6fb040f2cb26c273eb05fe0de165d1cb
| 3,409
|
cpp
|
C++
|
IfcPlusPlus/src/ifcpp/IFC4/lib/IfcFireSuppressionTerminalTypeEnum.cpp
|
AlexVlk/ifcplusplus
|
2f8cd5457312282b8d90b261dbf8fb66e1c84057
|
[
"MIT"
] | 426
|
2015-04-12T10:00:46.000Z
|
2022-03-29T11:03:02.000Z
|
IfcPlusPlus/src/ifcpp/IFC4/lib/IfcFireSuppressionTerminalTypeEnum.cpp
|
AlexVlk/ifcplusplus
|
2f8cd5457312282b8d90b261dbf8fb66e1c84057
|
[
"MIT"
] | 124
|
2015-05-15T05:51:00.000Z
|
2022-02-09T15:25:12.000Z
|
IfcPlusPlus/src/ifcpp/IFC4/lib/IfcFireSuppressionTerminalTypeEnum.cpp
|
AlexVlk/ifcplusplus
|
2f8cd5457312282b8d90b261dbf8fb66e1c84057
|
[
"MIT"
] | 214
|
2015-05-06T07:30:37.000Z
|
2022-03-26T16:14:04.000Z
|
/* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */
#include <sstream>
#include <limits>
#include <map>
#include "ifcpp/reader/ReaderUtil.h"
#include "ifcpp/writer/WriterUtil.h"
#include "ifcpp/model/BasicTypes.h"
#include "ifcpp/model/BuildingException.h"
#include "ifcpp/IFC4/include/IfcFireSuppressionTerminalTypeEnum.h"
// TYPE IfcFireSuppressionTerminalTypeEnum = ENUMERATION OF (BREECHINGINLET ,FIREHYDRANT ,HOSEREEL ,SPRINKLER ,SPRINKLERDEFLECTOR ,USERDEFINED ,NOTDEFINED);
shared_ptr<BuildingObject> IfcFireSuppressionTerminalTypeEnum::getDeepCopy( BuildingCopyOptions& options )
{
shared_ptr<IfcFireSuppressionTerminalTypeEnum> copy_self( new IfcFireSuppressionTerminalTypeEnum() );
copy_self->m_enum = m_enum;
return copy_self;
}
void IfcFireSuppressionTerminalTypeEnum::getStepParameter( std::stringstream& stream, bool is_select_type ) const
{
if( is_select_type ) { stream << "IFCFIRESUPPRESSIONTERMINALTYPEENUM("; }
switch( m_enum )
{
case ENUM_BREECHINGINLET: stream << ".BREECHINGINLET."; break;
case ENUM_FIREHYDRANT: stream << ".FIREHYDRANT."; break;
case ENUM_HOSEREEL: stream << ".HOSEREEL."; break;
case ENUM_SPRINKLER: stream << ".SPRINKLER."; break;
case ENUM_SPRINKLERDEFLECTOR: stream << ".SPRINKLERDEFLECTOR."; break;
case ENUM_USERDEFINED: stream << ".USERDEFINED."; break;
case ENUM_NOTDEFINED: stream << ".NOTDEFINED."; break;
}
if( is_select_type ) { stream << ")"; }
}
const std::wstring IfcFireSuppressionTerminalTypeEnum::toString() const
{
switch( m_enum )
{
case ENUM_BREECHINGINLET: return L"BREECHINGINLET";
case ENUM_FIREHYDRANT: return L"FIREHYDRANT";
case ENUM_HOSEREEL: return L"HOSEREEL";
case ENUM_SPRINKLER: return L"SPRINKLER";
case ENUM_SPRINKLERDEFLECTOR: return L"SPRINKLERDEFLECTOR";
case ENUM_USERDEFINED: return L"USERDEFINED";
case ENUM_NOTDEFINED: return L"NOTDEFINED";
}
return L"";
}
shared_ptr<IfcFireSuppressionTerminalTypeEnum> IfcFireSuppressionTerminalTypeEnum::createObjectFromSTEP( const std::wstring& arg, const std::map<int,shared_ptr<BuildingEntity> >& map )
{
if( arg.compare( L"$" ) == 0 ) { return shared_ptr<IfcFireSuppressionTerminalTypeEnum>(); }
if( arg.compare( L"*" ) == 0 ) { return shared_ptr<IfcFireSuppressionTerminalTypeEnum>(); }
shared_ptr<IfcFireSuppressionTerminalTypeEnum> type_object( new IfcFireSuppressionTerminalTypeEnum() );
if( std_iequal( arg, L".BREECHINGINLET." ) )
{
type_object->m_enum = IfcFireSuppressionTerminalTypeEnum::ENUM_BREECHINGINLET;
}
else if( std_iequal( arg, L".FIREHYDRANT." ) )
{
type_object->m_enum = IfcFireSuppressionTerminalTypeEnum::ENUM_FIREHYDRANT;
}
else if( std_iequal( arg, L".HOSEREEL." ) )
{
type_object->m_enum = IfcFireSuppressionTerminalTypeEnum::ENUM_HOSEREEL;
}
else if( std_iequal( arg, L".SPRINKLER." ) )
{
type_object->m_enum = IfcFireSuppressionTerminalTypeEnum::ENUM_SPRINKLER;
}
else if( std_iequal( arg, L".SPRINKLERDEFLECTOR." ) )
{
type_object->m_enum = IfcFireSuppressionTerminalTypeEnum::ENUM_SPRINKLERDEFLECTOR;
}
else if( std_iequal( arg, L".USERDEFINED." ) )
{
type_object->m_enum = IfcFireSuppressionTerminalTypeEnum::ENUM_USERDEFINED;
}
else if( std_iequal( arg, L".NOTDEFINED." ) )
{
type_object->m_enum = IfcFireSuppressionTerminalTypeEnum::ENUM_NOTDEFINED;
}
return type_object;
}
| 41.072289
| 185
| 0.748313
|
AlexVlk
|
a78f0b6453de2bb9b8a28ddaf432d5ad50064c51
| 1,460
|
cpp
|
C++
|
src/ray.cpp
|
core-exe/NonEuclideanRayTracing
|
4316fa118af6b29c86c99bd4d863dfba1f089c7c
|
[
"MIT"
] | 1
|
2021-12-02T06:25:54.000Z
|
2021-12-02T06:25:54.000Z
|
src/ray.cpp
|
core-exe/NonEuclideanRayTracing
|
4316fa118af6b29c86c99bd4d863dfba1f089c7c
|
[
"MIT"
] | null | null | null |
src/ray.cpp
|
core-exe/NonEuclideanRayTracing
|
4316fa118af6b29c86c99bd4d863dfba1f089c7c
|
[
"MIT"
] | null | null | null |
# include <vecmath.h>
# include "ray.hpp"
# include "geometry.hpp"
# include "trajectory.hpp"
# include "utils.hpp"
Ray4::Ray4(Vector4f _r, Vector4f _dr, Geometry4* _geometry, float _importance){
r = _r;
dr = -_dr/_dr[0];
geometry = _geometry;
attached_vectors = vector<VectorOnTrajectory4>();
update_local_geometry();
is_ddr_update = false;
importance = _importance;
tracking_step = 0;
}
Ray4::Ray4(Vector4f _r, Vector3f spacial_dir, Geometry4* _geometry, float _importance){
r = _r;
geometry = _geometry;
update_local_geometry();
dr = get_negative_null_vector(-spacial_dir, g);
attached_vectors = vector<VectorOnTrajectory4>();
is_ddr_update = false;
importance = _importance;
tracking_step = 0;
}
Vector4f Ray4::get_ddr(){
if(is_ddr_update)
return ddr;
ddr = Vector4f();
for(int i=0; i<4; i++)
for(int j=0; j<4; j++)
for(int k=0; k<4; k++)
ddr[i] += -gamma[i][j][k]*dr[j]*dr[k];
return ddr;
}
void Ray4::update_coor(float dt){
if(!is_ddr_update)
get_ddr();
r = r + dr * dt + 0.5 * ddr * dt * dt;
dr = dr + ddr * dt;
}
void Ray4::step(float dt){
update_vectors(dt);
update_coor(dt);
update_local_geometry();
tracking_step++;
}
Vector4f Ray4::dr_equivalent(float dt){
get_ddr();
return dr + 0.5*dt*ddr;
}
float Ray4::inv_frequency(){
return -dot(Vector4f(1, Vector3f()), dr, g);
}
| 23.934426
| 87
| 0.619863
|
core-exe
|
042cd82b4f655b61e642d7bba4458d8a197c6e94
| 5,822
|
cpp
|
C++
|
qrtest/unitTests/pluginsTests/robotsTests/interpretersTests/interpreterCoreTests/interpreterTests/interpreterTest.cpp
|
ladaegorova18/trik-studio
|
f8d9ce50301fd93c948ac774e85c0e6bfff820bc
|
[
"Apache-2.0"
] | 17
|
2019-06-04T06:22:47.000Z
|
2022-02-11T18:27:25.000Z
|
qrtest/unitTests/pluginsTests/robotsTests/interpretersTests/interpreterCoreTests/interpreterTests/interpreterTest.cpp
|
ladaegorova18/trik-studio
|
f8d9ce50301fd93c948ac774e85c0e6bfff820bc
|
[
"Apache-2.0"
] | 1,248
|
2019-02-21T19:32:09.000Z
|
2022-03-29T16:50:04.000Z
|
qrtest/unitTests/pluginsTests/robotsTests/interpretersTests/interpreterCoreTests/interpreterTests/interpreterTest.cpp
|
khodand/trik-studio
|
3d2de6809d38b621433c7ccb1cd98da8868d022d
|
[
"Apache-2.0"
] | 17
|
2019-02-12T07:58:23.000Z
|
2022-03-10T11:39:21.000Z
|
/* Copyright 2007-2015 QReal Research Group
*
* 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 "interpreterTest.h"
#include <QtCore/QCoreApplication>
#include <qrtext/lua/luaToolbox.h>
#include "interpreterCore/interpreter/blockInterpreter.h"
using namespace qrTest::robotsTests::interpreterCoreTests;
using namespace interpreterCore::interpreter;
using namespace ::testing;
void InterpreterTest::SetUp()
{
mQrguiFacade.reset(new QrguiFacade("unittests/basicTest.qrs"));
mQrguiFacade->setActiveTab(qReal::Id::loadFromString(
"qrm:/RobotsMetamodel/RobotsDiagram/RobotsDiagramNode/{f08fa823-e187-4755-87ba-e4269ae4e798}"));
ON_CALL(mConfigurationInterfaceMock, devices()).WillByDefault(
Return(QList<kitBase::robotModel::robotParts::Device *>())
);
EXPECT_CALL(mConfigurationInterfaceMock, devices()).Times(0);
/// @todo: Do we need this code in some common place? Why do we need to write
/// it every time when we are going to use RobotModelManager mock?
ON_CALL(mModel, robotId()).WillByDefault(Return("mockRobot"));
EXPECT_CALL(mModel, robotId()).Times(AtLeast(1));
ON_CALL(mModel, name()).WillByDefault(Return("mockRobot"));
ON_CALL(mModel, needsConnection()).WillByDefault(Return(false));
EXPECT_CALL(mModel, needsConnection()).Times(AtLeast(0));
ON_CALL(mModel, init()).WillByDefault(Return());
EXPECT_CALL(mModel, init()).Times(AtLeast(0));
ON_CALL(mModel, configuration()).WillByDefault(ReturnRef(mConfigurationInterfaceMock));
EXPECT_CALL(mModel, configuration()).Times(AtLeast(0));
ON_CALL(mModel, connectToRobot()).WillByDefault(
Invoke(&mModelManager, &RobotModelManagerInterfaceMock::emitConnected)
);
EXPECT_CALL(mModel, connectToRobot()).Times(AtLeast(0));
ON_CALL(mModel, disconnectFromRobot()).WillByDefault(
Invoke(&mModelManager, &RobotModelManagerInterfaceMock::emitDisconnected)
);
EXPECT_CALL(mModel, disconnectFromRobot()).Times(AtLeast(0));
ON_CALL(mModel, configurablePorts()).WillByDefault(Return(QList<kitBase::robotModel::PortInfo>()));
EXPECT_CALL(mModel, configurablePorts()).Times(AtLeast(0));
ON_CALL(mModel, availablePorts()).WillByDefault(Return(QList<kitBase::robotModel::PortInfo>()));
EXPECT_CALL(mModel, availablePorts()).Times(AtLeast(0));
ON_CALL(mModel, buttonCodes()).WillByDefault(Return(StringIntHash()));
EXPECT_CALL(mModel, buttonCodes()).Times(AtLeast(1));
ON_CALL(mModel, applyConfiguration()).WillByDefault(
Invoke(&mModelManager, &RobotModelManagerInterfaceMock::emitAllDevicesConfigured)
);
EXPECT_CALL(mModel, applyConfiguration()).Times(1);
ON_CALL(mModel, connectionState()).WillByDefault(Return(RobotModelInterfaceMock::connectedState));
EXPECT_CALL(mModel, connectionState()).Times(2);
ON_CALL(mModel, timeline()).WillByDefault(ReturnRef(mTimeline));
EXPECT_CALL(mModel, timeline()).Times(AtLeast(1));
ON_CALL(mModel, updateIntervalForInterpretation()).WillByDefault(Return(10));
EXPECT_CALL(mModel, updateIntervalForInterpretation()).Times(0);
EXPECT_CALL(mModel, updateSensorsValues()).Times(0);
ON_CALL(mModelManager, model()).WillByDefault(ReturnRef(mModel));
EXPECT_CALL(mModelManager, model()).Times(AtLeast(1));
ON_CALL(mBlocksFactoryManager, addFactory(_, _)).WillByDefault(Return());
EXPECT_CALL(mBlocksFactoryManager, addFactory(_, _)).Times(0);
mParser.reset(new interpreterCore::textLanguage::RobotsBlockParser(mModelManager, []() { return 0; }));
mBlocksFactory.configure(
mQrguiFacade->graphicalModelAssistInterface()
, mQrguiFacade->logicalModelAssistInterface()
, mModelManager
, *mQrguiFacade->mainWindowInterpretersInterface().errorReporter()
, *mParser
);
ON_CALL(mBlocksFactoryManager, block(_, _)).WillByDefault(
Invoke([this] (qReal::Id const &id, kitBase::robotModel::RobotModelInterface const &robotModel) {
Q_UNUSED(robotModel)
return mBlocksFactory.block(id);
} )
);
EXPECT_CALL(mBlocksFactoryManager, block(_, _)).Times(AtLeast(0));
ON_CALL(mBlocksFactoryManager, enabledBlocks(_)).WillByDefault(
Invoke([this] (kitBase::robotModel::RobotModelInterface const &robotModel) {
Q_UNUSED(robotModel)
return mBlocksFactory.providedBlocks().toSet();
} )
);
EXPECT_CALL(mBlocksFactoryManager, enabledBlocks(_)).Times(0);
mInterpreter.reset(new BlockInterpreter(
mQrguiFacade->graphicalModelAssistInterface()
, mQrguiFacade->logicalModelAssistInterface()
, mQrguiFacade->mainWindowInterpretersInterface()
, mQrguiFacade->projectManagementInterface()
, mBlocksFactoryManager
, mModelManager
, *mParser
));
mInterpreterStopped = false;
QObject::connect(mInterpreter.data(), &kitBase::InterpreterInterface::stopped, [this]() {
mEventLoop.exit();
mInterpreterStopped = true;
});
}
TEST_F(InterpreterTest, interpret)
{
EXPECT_CALL(mModel, stopRobot()).Times(2);
mInterpreter->interpret();
if (!mInterpreterStopped) {
// Queued connections must work!
mEventLoop.exec();
}
}
TEST_F(InterpreterTest, stopRobot)
{
// It shall be called directly here, before interpretation and in destructor of a model.
EXPECT_CALL(mModel, stopRobot()).Times(3);
mInterpreter->interpret();
if (!mInterpreterStopped) {
// Queued connections must work!
mEventLoop.exec();
}
mInterpreter->stopRobot(qReal::interpretation::StopReason::finised);
}
| 35.5
| 104
| 0.760735
|
ladaegorova18
|
043271b45127ce22ea719af970abaea3f7f69b66
| 2,924
|
cpp
|
C++
|
src/joint_state_publisher.cpp
|
gezp/universal_robot_ign
|
c441c793db2373ab576233971f153f34b79ac157
|
[
"MIT"
] | 20
|
2021-02-26T22:58:23.000Z
|
2022-03-18T21:29:51.000Z
|
src/joint_state_publisher.cpp
|
gezp/universal_robot_ign
|
c441c793db2373ab576233971f153f34b79ac157
|
[
"MIT"
] | 1
|
2021-07-20T16:05:37.000Z
|
2021-07-24T00:30:22.000Z
|
src/joint_state_publisher.cpp
|
gezp/universal_robot_ign
|
c441c793db2373ab576233971f153f34b79ac157
|
[
"MIT"
] | 2
|
2021-01-20T16:20:44.000Z
|
2022-02-28T08:05:42.000Z
|
/*******************************************************************************
* Copyright (c) Gezp (https://github.com/gezp), All rights reserved.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the MIT License, See the MIT License for more details.
*
* You should have received a copy of the MIT License along with this program.
* If not, see <https://opensource.org/licenses/MIT/>.
*
******************************************************************************/
#include "universal_robot_ign/joint_state_publisher.hpp"
using namespace std;
using namespace universal_robot_ign;
JointStatePublisher::JointStatePublisher(const rclcpp::Node::SharedPtr& nh,
const std::vector<std::string>& joint_names,
const std::string& ros_topic,
const std::string& ign_topic,
const unsigned int update_rate)
{
// ROS and Ignition node
nh_ = nh;
ign_node_ = std::make_shared<ignition::transport::Node>();
joint_names_ = joint_names;
for (size_t i = 0; i < joint_names_.size(); i++) {
joint_names_map_[joint_names_[i]]=i;
}
//create ros pub and sub
ros_joint_state_pub_ = nh_->create_publisher<sensor_msgs::msg::JointState>(ros_topic, 10);
auto period = std::chrono::microseconds(1000000 / update_rate);
joint_state_timer_ = nh_->create_wall_timer(period, std::bind(&JointStatePublisher::jointStateTimerCb, this));
//create ignition sub
ign_node_->Subscribe(ign_topic, &JointStatePublisher::ignJointStateCb, this);
//init current_joint_msg_
for (auto i = 0u; i < joint_names_.size(); ++i) {
current_joint_msg_.name.push_back(joint_names_[i]);
current_joint_msg_.position.push_back(0);
current_joint_msg_.velocity.push_back(0);
current_joint_msg_.effort.push_back(0);
}
}
void JointStatePublisher::jointStateTimerCb()
{
ignition::msgs::Model model_msg;
{
std::lock_guard<std::mutex> lock(current_joint_msg_mut_);
model_msg=current_ign_joint_msg_;
}
//create JointState msg
current_joint_msg_.header.stamp = rclcpp::Clock().now();
current_joint_msg_.header.frame_id = model_msg.name();
for(int i = 0; i < model_msg.joint_size () ; ++i){
if (joint_names_map_.find(model_msg.joint(i).name()) != joint_names_map_.end()) {
int idx=joint_names_map_[model_msg.joint(i).name()];
current_joint_msg_.position[idx]=model_msg.joint(i).axis1().position();
current_joint_msg_.velocity[idx]=model_msg.joint(i).axis1().velocity();
current_joint_msg_.effort[idx]=model_msg.joint(i).axis1().force();
}
}
ros_joint_state_pub_->publish(current_joint_msg_);
}
void JointStatePublisher::ignJointStateCb(const ignition::msgs::Model& msg)
{
std::lock_guard<std::mutex> lock(current_joint_msg_mut_);
current_ign_joint_msg_ = msg;
}
| 41.183099
| 114
| 0.658003
|
gezp
|
0434fe5ca57d2c01e55b04d1e00088d6498409f3
| 1,047
|
cpp
|
C++
|
D&D/Laberinto/Jugador.cpp
|
kiinTheDovah/DnD-Project
|
2af354faa7b90795f2f35b8057fa2aeed3da0053
|
[
"MIT"
] | 2
|
2019-03-19T16:13:51.000Z
|
2019-03-19T16:13:53.000Z
|
D&D/Laberinto/Jugador.cpp
|
kiinTheDovah/DnD-Project
|
2af354faa7b90795f2f35b8057fa2aeed3da0053
|
[
"MIT"
] | 1
|
2018-10-12T17:03:25.000Z
|
2018-10-12T17:11:23.000Z
|
D&D/Laberinto/Jugador.cpp
|
kiinTheDovah/DnD-Project
|
2af354faa7b90795f2f35b8057fa2aeed3da0053
|
[
"MIT"
] | null | null | null |
/*
Archivo: Jugador.cpp
Autores:
Crhistian García Urbano 1832124
Nicolas Jaramillo Mayor 1840558
Email: nicolas.jaramillo@correounivalle.edu.co
garcia.crhistian@correounivalle.edu.co
Fecha creación: 2018/04/04
Última modificación: 2019/04/22
Versión: 0.7
Licencia: GPL
*/
#include <iostream>
#include "h/Jugador.h"
Jugador::Jugador(int fila_Jugador, int columna_Jugador)
{
this->fila_Jugador = fila_Jugador;
this->columna_Jugador = columna_Jugador;
}
Jugador::~Jugador()
{
}
void Jugador::cogerTesoro()
{
tesoros++;
}
bool Jugador::darTesdoro(int numTesoros)
{
if (tesoros >= numTesoros)
{
tesoros -= numTesoros;
return true;
}
else
tesoros = 0;
return false;
}
void Jugador::dondeEstas(int *fila, int *columna)
{
*fila = fila_Jugador;
*columna = columna_Jugador;
}
void Jugador::nuevaPosicion(int fila, int columna)
{
fila_Jugador = fila;
columna_Jugador = columna;
}
int Jugador::tesorosJugador()
{
return tesoros;
}
| 14.957143
| 55
| 0.667622
|
kiinTheDovah
|
0436276358613e7740a99981149dbc10ac2d8eb2
| 2,618
|
hpp
|
C++
|
contracts/mgp.vstaking/include/mgp.vstaking/staking.hpp
|
heying602657/MGP-Contracts-1
|
4e139b2cddda5dd285929ee7ad26306bb860146d
|
[
"MIT"
] | null | null | null |
contracts/mgp.vstaking/include/mgp.vstaking/staking.hpp
|
heying602657/MGP-Contracts-1
|
4e139b2cddda5dd285929ee7ad26306bb860146d
|
[
"MIT"
] | null | null | null |
contracts/mgp.vstaking/include/mgp.vstaking/staking.hpp
|
heying602657/MGP-Contracts-1
|
4e139b2cddda5dd285929ee7ad26306bb860146d
|
[
"MIT"
] | null | null | null |
#pragma once
#include <eosio/eosio.hpp>
#include <eosio/asset.hpp>
#include <eosio/singleton.hpp>
#include <eosio/transaction.hpp>
#include <eosio/system.hpp>
#include <eosio/crypto.hpp>
#include <eosio/action.hpp>
#include <string>
#include <deque>
#include <optional>
#include <type_traits>
#include "wasm_db.hpp"
#include "staking_entities.hpp"
namespace mgp {
using namespace wasm::db;
using eosio::asset;
using eosio::check;
using eosio::datastream;
using eosio::name;
using eosio::symbol;
using eosio::symbol_code;
using eosio::unsigned_int;
using std::string;
static constexpr eosio::name SYS_ACCOUNT{"mgpchain2222"_n};
static constexpr eosio::name SHOP_ACCOUNT{"mgpchainshop"_n};
static constexpr eosio::name AGENT_ACCOUNT{"mgpagentdiya"_n};
static constexpr eosio::name MASTER_ACCOUNT{"masteraychen"_n};
static constexpr symbol SYS_SYMBOL = symbol(symbol_code("MGP"), 4);
static constexpr uint64_t ADDRESSBOOK_SCOPE = 1000;
class [[eosio::contract("mgp.vstaking")]] smart_mgp: public eosio::contract {
public:
using contract::contract;
ACTION configure( string burn_memo, int destruction, bool redeemallow, asset minpay );
ACTION encorrection( bool enable_data_correction );
ACTION bindaddress(const name& account, const string& address);
ACTION delbind(const name& account, const string& address);
ACTION redeem(name account);
ACTION reloadnum(const name& from, const name& to, const asset& quant);
/// NOTE:
/// DO NOT CHANGE PARAM TYPES OTHERWISE CAUSING DATA LOADING ISSUES in EOSWEB
void transfer(name from, name to, asset quantity, string memo);
};
extern "C" void apply(uint64_t receiver, uint64_t code, uint64_t action) {
if ( code == SYS_BANK.value && action == "transfer"_n.value) {
eosio::execute_action( eosio::name(receiver),
eosio::name(code),
&smart_mgp::transfer );
} else if (code == receiver) {
switch (action) {
EOSIO_DISPATCH_HELPER( smart_mgp, (configure)(encorrection)
(redeem)(bindaddress)(delbind)(reloadnum) )
}
}
}
inline vector <string> string_split(string str, char delimiter) {
vector <string> r;
string tmpstr;
while (!str.empty()) {
int ind = str.find_first_of(delimiter);
if (ind == -1) {
r.push_back(str);
str.clear();
} else {
r.push_back(str.substr(0, ind));
str = str.substr(ind + 1, str.size() - ind - 1);
}
}
return r;
}
} //end of namespace mgpecoshare
| 29.41573
| 91
| 0.661192
|
heying602657
|
043b9f5cd056d1f52e1b7d99b1b483c546797c18
| 17,102
|
cpp
|
C++
|
src/notifybypopup.cpp
|
pasnox/knotifications
|
ef2871b2a485be5abe393e61c6cd93867420f896
|
[
"BSD-3-Clause"
] | null | null | null |
src/notifybypopup.cpp
|
pasnox/knotifications
|
ef2871b2a485be5abe393e61c6cd93867420f896
|
[
"BSD-3-Clause"
] | null | null | null |
src/notifybypopup.cpp
|
pasnox/knotifications
|
ef2871b2a485be5abe393e61c6cd93867420f896
|
[
"BSD-3-Clause"
] | null | null | null |
/*
Copyright (C) 2005-2009 by Olivier Goffart <ogoffart at kde.org>
Copyright (C) 2008 by Dmitry Suzdalev <dimsuz@gmail.com>
Copyright (C) 2014 by Martin Klapetek <mklapetek@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) version 3, or any
later version accepted by the membership of KDE e.V. (or its
successor approved by the membership of KDE e.V.), which shall
act as a proxy defined in Section 6 of version 3 of the license.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#include "notifybypopup.h"
#include "imageconverter.h"
#include "knotifyconfig.h"
#include "knotification.h"
#include "debug_p.h"
#include <QBuffer>
#include <QGuiApplication>
#include <QDBusConnection>
#include <QDBusConnectionInterface>
#include <QDBusServiceWatcher>
#include <QDBusMessage>
#include <QXmlStreamReader>
#include <QMap>
#include <QHash>
#include <QPointer>
#include <QMutableListIterator>
#include <QThread>
#include <QFontMetrics>
#include <QIcon>
#include <QUrl>
#include <kconfiggroup.h>
static const char dbusServiceName[] = "org.freedesktop.Notifications";
static const char dbusInterfaceName[] = "org.freedesktop.Notifications";
static const char dbusPath[] = "/org/freedesktop/Notifications";
class NotifyByPopupPrivate {
public:
NotifyByPopupPrivate(NotifyByPopup *parent) : q(parent) {}
/**
* Sends notification to DBus "org.freedesktop.notifications" interface.
* @param id knotify-sid identifier of notification
* @param config notification data
* @param update If true, will request the DBus service to update
the notification with new data from \c notification
* Otherwise will put new notification on screen
* @return true for success or false if there was an error.
*/
bool sendNotificationToServer(KNotification *notification, const KNotifyConfig &config, bool update = false);
/**
* Find the caption and the icon name of the application
*/
void getAppCaptionAndIconName(const KNotifyConfig &config, QString *appCaption, QString *iconName);
/*
* Query the dbus server for notification capabilities
* If no DBus server is present, use fallback capabilities for KPassivePopup
*/
void queryPopupServerCapabilities();
/**
* DBus notification daemon capabilities cache.
* Do not use this variable. Use #popupServerCapabilities() instead.
* @see popupServerCapabilities
*/
QStringList popupServerCapabilities;
/**
* In case we still don't know notification server capabilities,
* we need to query those first. That's done in an async way
* so we queue all notifications while waiting for the capabilities
* to return, then process them from this queue
*/
QList<QPair<KNotification*, KNotifyConfig> > notificationQueue;
/**
* Whether the DBus notification daemon capability cache is up-to-date.
*/
bool dbusServiceCapCacheDirty;
/*
* As we communicate with the notification server over dbus
* we use only ids, this is for fast KNotifications lookup
*/
QHash<uint, QPointer<KNotification>> notifications;
NotifyByPopup * const q;
};
//---------------------------------------------------------------------------------------
NotifyByPopup::NotifyByPopup(QObject *parent)
: KNotificationPlugin(parent),
d(new NotifyByPopupPrivate(this))
{
d->dbusServiceCapCacheDirty = true;
bool connected = QDBusConnection::sessionBus().connect(QString(), // from any service
QString::fromLatin1(dbusPath),
QString::fromLatin1(dbusInterfaceName),
QStringLiteral("ActionInvoked"),
this,
SLOT(onNotificationActionInvoked(uint,QString)));
if (!connected) {
qCWarning(LOG_KNOTIFICATIONS) << "warning: failed to connect to ActionInvoked dbus signal";
}
connected = QDBusConnection::sessionBus().connect(QString(), // from any service
QString::fromLatin1(dbusPath),
QString::fromLatin1(dbusInterfaceName),
QStringLiteral("NotificationClosed"),
this,
SLOT(onNotificationClosed(uint,uint)));
if (!connected) {
qCWarning(LOG_KNOTIFICATIONS) << "warning: failed to connect to NotificationClosed dbus signal";
}
}
NotifyByPopup::~NotifyByPopup()
{
delete d;
}
void NotifyByPopup::notify(KNotification *notification, KNotifyConfig *notifyConfig)
{
notify(notification, *notifyConfig);
}
void NotifyByPopup::notify(KNotification *notification, const KNotifyConfig ¬ifyConfig)
{
if (d->notifications.contains(notification->id())) {
// notification is already on the screen, do nothing
finish(notification);
return;
}
if (d->dbusServiceCapCacheDirty) {
// if we don't have the server capabilities yet, we need to query for them first;
// as that is an async dbus operation, we enqueue the notification and process them
// when we receive dbus reply with the server capabilities
d->notificationQueue.append(qMakePair(notification, notifyConfig));
d->queryPopupServerCapabilities();
} else {
if (!d->sendNotificationToServer(notification, notifyConfig)) {
finish(notification); //an error occurred.
}
}
}
void NotifyByPopup::update(KNotification *notification, KNotifyConfig *notifyConfig)
{
update(notification, *notifyConfig);
}
void NotifyByPopup::update(KNotification *notification, const KNotifyConfig ¬ifyConfig)
{
d->sendNotificationToServer(notification, notifyConfig, true);
}
void NotifyByPopup::close(KNotification *notification)
{
uint id = d->notifications.key(notification, 0);
if (id == 0) {
qCDebug(LOG_KNOTIFICATIONS) << "not found dbus id to close" << notification->id();
return;
}
QDBusMessage m = QDBusMessage::createMethodCall(QString::fromLatin1(dbusServiceName), QString::fromLatin1(dbusPath),
QString::fromLatin1(dbusInterfaceName), QStringLiteral("CloseNotification"));
QList<QVariant> args;
args.append(id);
m.setArguments(args);
// send(..) does not block
bool queued = QDBusConnection::sessionBus().send(m);
if (!queued) {
qCWarning(LOG_KNOTIFICATIONS) << "Failed to queue dbus message for closing a notification";
}
QMutableListIterator<QPair<KNotification*, KNotifyConfig> > iter(d->notificationQueue);
while (iter.hasNext()) {
auto &item = iter.next();
if (item.first == notification) {
iter.remove();
}
}
}
void NotifyByPopup::onNotificationActionInvoked(uint notificationId, const QString &actionKey)
{
auto iter = d->notifications.find(notificationId);
if (iter == d->notifications.end()) {
return;
}
KNotification *n = *iter;
if (n) {
if (actionKey == QLatin1String("default")) {
emit actionInvoked(n->id(), 0);
} else {
emit actionInvoked(n->id(), actionKey.toUInt());
}
} else {
d->notifications.erase(iter);
}
}
void NotifyByPopup::onNotificationClosed(uint dbus_id, uint reason)
{
auto iter = d->notifications.find(dbus_id);
if (iter == d->notifications.end()) {
return;
}
KNotification *n = *iter;
d->notifications.remove(dbus_id);
if (n) {
emit finished(n);
// The popup bubble is the only user facing part of a notification,
// if the user closes the popup, it means he wants to get rid
// of the notification completely, including playing sound etc
// Therefore we close the KNotification completely after closing
// the popup, but only if the reason is 2, which means "user closed"
if (reason == 2) {
n->close();
}
}
}
void NotifyByPopup::onServerReply(QDBusPendingCallWatcher *watcher)
{
// call deleteLater first, since we might return in the middle of the function
watcher->deleteLater();
KNotification *notification = watcher->property("notificationObject").value<KNotification*>();
if (!notification) {
qCWarning(LOG_KNOTIFICATIONS) << "Invalid notification object passed in DBus reply watcher; notification will probably break";
return;
}
QDBusPendingReply<uint> reply = *watcher;
d->notifications.insert(reply.argumentAt<0>(), notification);
}
void NotifyByPopup::onServerCapabilitiesReceived(const QStringList &capabilities)
{
d->popupServerCapabilities = capabilities;
d->dbusServiceCapCacheDirty = false;
// re-run notify() on all enqueued notifications
for (int i = 0, total = d->notificationQueue.size(); i < total; ++i) {
notify(d->notificationQueue.at(i).first, d->notificationQueue.at(i).second);
}
d->notificationQueue.clear();
}
void NotifyByPopupPrivate::getAppCaptionAndIconName(const KNotifyConfig ¬ifyConfig, QString *appCaption, QString *iconName)
{
KConfigGroup globalgroup(&(*notifyConfig.eventsfile), QStringLiteral("Global"));
*appCaption = globalgroup.readEntry("Name", globalgroup.readEntry("Comment", notifyConfig.appname));
KConfigGroup eventGroup(&(*notifyConfig.eventsfile), QStringLiteral("Event/%1").arg(notifyConfig.eventid));
if (eventGroup.hasKey("IconName")) {
*iconName = eventGroup.readEntry("IconName", notifyConfig.appname);
} else {
*iconName = globalgroup.readEntry("IconName", notifyConfig.appname);
}
}
bool NotifyByPopupPrivate::sendNotificationToServer(KNotification *notification, const KNotifyConfig ¬ifyConfig_nocheck, bool update)
{
uint updateId = notifications.key(notification, 0);
if (update) {
if (updateId == 0) {
// we have nothing to update; the notification we're trying to update
// has been already closed
return false;
}
}
QDBusMessage dbusNotificationMessage = QDBusMessage::createMethodCall(QString::fromLatin1(dbusServiceName), QString::fromLatin1(dbusPath), QString::fromLatin1(dbusInterfaceName), QStringLiteral("Notify"));
QList<QVariant> args;
QString appCaption;
QString iconName;
getAppCaptionAndIconName(notifyConfig_nocheck, &appCaption, &iconName);
//did the user override the icon name?
if (!notification->iconName().isEmpty()) {
iconName = notification->iconName();
}
args.append(appCaption); // app_name
args.append(updateId); // notification to update
args.append(iconName); // app_icon
QString title = notification->title().isEmpty() ? appCaption : notification->title();
QString text = notification->text();
if (!popupServerCapabilities.contains(QLatin1String("body-markup"))) {
title = q->stripRichText(title);
text = q->stripRichText(text);
}
args.append(title); // summary
args.append(text); // body
// freedesktop.org spec defines action list to be list like
// (act_id1, action1, act_id2, action2, ...)
//
// assign id's to actions like it's done in fillPopup() method
// (i.e. starting from 1)
QStringList actionList;
if (popupServerCapabilities.contains(QLatin1String("actions"))) {
QString defaultAction = notification->defaultAction();
if (!defaultAction.isEmpty()) {
actionList.append(QStringLiteral("default"));
actionList.append(defaultAction);
}
int actId = 0;
const auto listActions = notification->actions();
for (const QString &actionName : listActions) {
actId++;
actionList.append(QString::number(actId));
actionList.append(actionName);
}
}
args.append(actionList); // actions
QVariantMap hintsMap;
// Add the application name to the hints.
// According to freedesktop.org spec, the app_name is supposed to be the application's "pretty name"
// but in some places it's handy to know the application name itself
if (!notification->appName().isEmpty()) {
hintsMap[QStringLiteral("x-kde-appname")] = notification->appName();
}
if (!notification->eventId().isEmpty()) {
hintsMap[QStringLiteral("x-kde-eventId")] = notification->eventId();
}
if (notification->flags() & KNotification::SkipGrouping) {
hintsMap[QStringLiteral("x-kde-skipGrouping")] = 1;
}
if (!notification->urls().isEmpty()) {
hintsMap[QStringLiteral("x-kde-urls")] = QUrl::toStringList(notification->urls());
}
if (!(notification->flags() & KNotification::Persistent)) {
hintsMap[QStringLiteral("transient")] = true;
}
QString desktopFileName = QGuiApplication::desktopFileName();
if (!desktopFileName.isEmpty()) {
// handle apps which set the desktopFileName property with filename suffix,
// due to unclear API dox (https://bugreports.qt.io/browse/QTBUG-75521)
if (desktopFileName.endsWith(QLatin1String(".desktop"))) {
desktopFileName.chop(8);
}
hintsMap[QStringLiteral("desktop-entry")] = desktopFileName;
}
int urgency = -1;
switch (notification->urgency()) {
case KNotification::DefaultUrgency:
break;
case KNotification::LowUrgency:
urgency = 0;
break;
case KNotification::NormalUrgency:
Q_FALLTHROUGH();
// freedesktop.org notifications only know low, normal, critical
case KNotification::HighUrgency:
urgency = 1;
break;
case KNotification::CriticalUrgency:
urgency = 2;
break;
}
if (urgency > -1) {
hintsMap[QStringLiteral("urgency")] = urgency;
}
const QVariantMap hints = notification->hints();
for (auto it = hints.constBegin(); it != hints.constEnd(); ++it) {
hintsMap[it.key()] = it.value();
}
//FIXME - reenable/fix
// let's see if we've got an image, and store the image in the hints map
if (!notification->pixmap().isNull()) {
QByteArray pixmapData;
QBuffer buffer(&pixmapData);
buffer.open(QIODevice::WriteOnly);
notification->pixmap().save(&buffer, "PNG");
buffer.close();
hintsMap[QStringLiteral("image_data")] = ImageConverter::variantForImage(QImage::fromData(pixmapData));
}
args.append(hintsMap); // hints
// Persistent => 0 == infinite timeout
// CloseOnTimeout => -1 == let the server decide
int timeout = (notification->flags() & KNotification::Persistent) ? 0 : -1;
args.append(timeout); // expire timeout
dbusNotificationMessage.setArguments(args);
QDBusPendingCall notificationCall = QDBusConnection::sessionBus().asyncCall(dbusNotificationMessage, -1);
//parent is set to the notification so that no-one ever accesses a dangling pointer on the notificationObject property
QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(notificationCall, notification);
watcher->setProperty("notificationObject", QVariant::fromValue<KNotification*>(notification));
QObject::connect(watcher, &QDBusPendingCallWatcher::finished,
q, &NotifyByPopup::onServerReply);
return true;
}
void NotifyByPopupPrivate::queryPopupServerCapabilities()
{
if (dbusServiceCapCacheDirty) {
QDBusMessage m = QDBusMessage::createMethodCall(QString::fromLatin1(dbusServiceName),
QString::fromLatin1(dbusPath),
QString::fromLatin1(dbusInterfaceName),
QStringLiteral("GetCapabilities"));
QDBusConnection::sessionBus().callWithCallback(m,
q,
SLOT(onServerCapabilitiesReceived(QStringList)),
nullptr,
-1);
}
}
| 36.937365
| 209
| 0.642556
|
pasnox
|
0440b6c297a2c64bb8e3c6ad461b08d47e90c595
| 5,528
|
cc
|
C++
|
src/AndroidPreview.cc
|
carun/RealSenseID
|
63d8cee261a8b07a6aa8af49af4ffe461524c424
|
[
"Apache-2.0"
] | null | null | null |
src/AndroidPreview.cc
|
carun/RealSenseID
|
63d8cee261a8b07a6aa8af49af4ffe461524c424
|
[
"Apache-2.0"
] | null | null | null |
src/AndroidPreview.cc
|
carun/RealSenseID
|
63d8cee261a8b07a6aa8af49af4ffe461524c424
|
[
"Apache-2.0"
] | null | null | null |
// License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2020-2021 Intel Corporation. All Rights Reserved.
#include "AndroidPreview.h"
#include "Logger.h"
#include <stdexcept>
#include <android/api-level.h>
#include <unistd.h>
#include <chrono>
#include <thread>
#include <libusb.h>
#include <libuvc.h>
#include <sstream>
static const char* LOG_TAG = "AndroidPreview";
namespace RealSenseID
{
static void ThrowIfFailed(const char *what, uvc_error_t uvc_err)
{
if (uvc_err == UVC_SUCCESS)
return;
std::stringstream err_stream;
err_stream << what << " failed with error: " << uvc_err << " - " << uvc_strerror(uvc_err);
throw std::runtime_error(err_stream.str());
}
class CaptureResourceHandle
{
public:
CaptureResourceHandle(int sys_dev)
{
libusb_context *usb_context = NULL;
auto api_level = android_get_device_api_level();
// For some reason, in API level 23 (AOSP 6.0) uvc_init should be called with
// NULL usb_context, while in later API levels we tested, weak authority was required
// to be set.
// This condition was added to fulfill the different requirements.
// As more API levels will be tested this condition might change.
if (api_level != 23) {
int ret = libusb_set_option(usb_context, LIBUSB_OPTION_WEAK_AUTHORITY);
if (0 < ret)
{
std::stringstream err_stream;
err_stream << LOG_TAG << " - ERROR in libusb_set_option: " << ret;
throw std::runtime_error(err_stream.str());
}
}
uvc_error_t res;
res = uvc_init(&ctx, usb_context);
ThrowIfFailed("uvc_init", res);
res = uvc_wrap(sys_dev, ctx, &devh);
ThrowIfFailed("uvc_wrap", res);
uvc_stream_ctrl_t ctrl;
res = uvc_get_stream_ctrl_format_size(devh, &ctrl, /* result stored in ctrl */
UVC_FRAME_FORMAT_ANY, 352, 640, 30 /* width, height, fps */
);
ThrowIfFailed("uvc_get_stream_ctrl_format_size", res);
res = uvc_stream_open_ctrl(devh, &stream, &ctrl);
ThrowIfFailed("uvc_stream_open_ctrl", res);
res = uvc_stream_start(stream, NULL, (void*)this, 0);
ThrowIfFailed("uvc_stream_start", res);
};
~CaptureResourceHandle()
{
LOG_DEBUG(LOG_TAG, "release camera");
}
bool read(uvc_frame_t** frame)
{
uvc_error_t res;
res = uvc_stream_get_frame(stream, frame, 10000);
if (res != UVC_SUCCESS || *frame == NULL)
{
return false;
}
return true;
}
void stop_stream()
{
uvc_stop_streaming(devh);
uvc_close(devh);
uvc_exit(ctx);
}
private:
uvc_context_t* ctx = nullptr;
uvc_device_handle_t* devh = nullptr;
uvc_stream_handle_t* stream = nullptr;
};
AndroidPreview::AndroidPreview(const PreviewConfig& config) : _config(config) {};
AndroidPreview::~AndroidPreview()
{
try
{
Stop();
}
catch (...)
{
}
};
void AndroidPreview::Start(PreviewImageReadyCallback& callback)
{
_callback = &callback;
_paused = false;
_canceled = false;
if (_worker_thread.joinable())
{
return;
}
_worker_thread = std::thread([&]() {
try
{
unsigned int frameNumber = 0;
CaptureResourceHandle capture(_config.cameraNumber);
LOG_DEBUG(LOG_TAG, "started!");
while (!_canceled)
{
if (_paused)
{
std::this_thread::sleep_for(std::chrono::milliseconds {100});
continue;
}
uvc_frame_t* frame = NULL;
bool res = capture.read(&frame);
if (_canceled)
{
break;
}
if (_paused)
{
continue;
}
if (res)
{
RealSenseID::Image container;
unsigned char* data = (unsigned char*)frame->data;
container.buffer = data;
container.size = (unsigned int)(frame->data_bytes);
container.width = frame->width;
container.height = frame->height;
container.stride = (unsigned int)(frame->step);
container.number = frameNumber++;
_callback->OnPreviewImageReady(container);
}
else
{
continue;
}
}
capture.stop_stream();
}
catch (const std::exception& ex)
{
LOG_ERROR(LOG_TAG, "Streaming ERROR : %s", ex.what());
_canceled = true;
}
catch (...)
{
LOG_ERROR(LOG_TAG, "Streaming unknonwn exception");
_canceled = true;
}
});
}
void AndroidPreview::Stop()
{
LOG_DEBUG(LOG_TAG, "Stopping preview");
_canceled = true;
if (_worker_thread.joinable())
{
_worker_thread.join();
}
LOG_DEBUG(LOG_TAG, "Preview stopped");
}
void AndroidPreview::Pause()
{
LOG_DEBUG(LOG_TAG, "Pause preview");
_paused = true;
}
void AndroidPreview::Resume()
{
LOG_DEBUG(LOG_TAG, "Resume preview");
_paused = false;
}
} // namespace RealSenseID
| 27.502488
| 108
| 0.549204
|
carun
|
0441017029dbf6ecaaca24280315a83e10ae25d4
| 5,717
|
cpp
|
C++
|
gEarth.Pack/oepStyleSheet.cpp
|
songgod/gEarth
|
e4ea0fa15a40f08481c7ea7e42e6f4ace8659984
|
[
"MIT"
] | 5
|
2021-06-16T06:24:29.000Z
|
2022-03-10T03:41:44.000Z
|
gEarth.Pack/oepStyleSheet.cpp
|
songgod/gEarth
|
e4ea0fa15a40f08481c7ea7e42e6f4ace8659984
|
[
"MIT"
] | 1
|
2020-10-14T14:20:58.000Z
|
2020-10-14T14:20:58.000Z
|
gEarth.Pack/oepStyleSheet.cpp
|
songgod/gEarth
|
e4ea0fa15a40f08481c7ea7e42e6f4ace8659984
|
[
"MIT"
] | 2
|
2021-06-16T06:24:32.000Z
|
2021-08-02T09:05:42.000Z
|
#include "stdafx.h"
#include "oepStyleSheet.h"
using namespace gEarthPack;
using namespace osgEarth::Symbology;
oepStyleSheet::oepStyleSheet()
{
bind(new StyleSheet());
}
oepStyleSheet::oepScriptDef::oepScriptDef()
{
bind(new StyleSheet::ScriptDef());
}
String^ oepStyleSheet::oepScriptDef::Name::get()
{
return Str2Cli(as<osgEarth::StyleSheet::ScriptDef>()->name);
}
void oepStyleSheet::oepScriptDef::Name::set(String^ s)
{
as<osgEarth::StyleSheet::ScriptDef>()->name = Str2Std(s);
NotifyChanged("Name");
}
String^ oepStyleSheet::oepScriptDef::Code::get()
{
return Str2Cli(as<osgEarth::StyleSheet::ScriptDef>()->code);
}
void oepStyleSheet::oepScriptDef::Code::set(String^ s)
{
as<osgEarth::StyleSheet::ScriptDef>()->code = Str2Std(s);
NotifyChanged("Code");
}
String^ oepStyleSheet::oepScriptDef::Language::get()
{
return Str2Cli(as<osgEarth::StyleSheet::ScriptDef>()->language);
}
void oepStyleSheet::oepScriptDef::Language::set(String^ s)
{
as<osgEarth::StyleSheet::ScriptDef>()->language = Str2Std(s);
NotifyChanged("Language");
}
String^ oepStyleSheet::oepScriptDef::Profile::get()
{
return Str2Cli(as<osgEarth::StyleSheet::ScriptDef>()->profile);
}
void oepStyleSheet::oepScriptDef::Profile::set(String^ s)
{
as<osgEarth::StyleSheet::ScriptDef>()->profile = Str2Std(s);
NotifyChanged("Profile");
}
String^ oepStyleSheet::oepScriptDef::Url::get()
{
return Str2Cli(as<osgEarth::StyleSheet::ScriptDef>()->uri.value().full());
}
void oepStyleSheet::oepScriptDef::Url::set(String^ s)
{
as<osgEarth::StyleSheet::ScriptDef>()->uri.mutable_value() = Str2Std(s);
NotifyChanged("Url");
}
String^ oepStyleSheet::Name::get()
{
return Str2Cli(as<osgEarth::Symbology::StyleSheet>()->name().value());
}
void oepStyleSheet::Name::set(String^ s)
{
as<osgEarth::Symbology::StyleSheet>()->name() = Str2Std(s);
NotifyChanged("Name");
}
oepStyleMap^ oepStyleSheet::StyleMap::get()
{
return _stylemap;
}
void oepStyleSheet::StyleMap::set(oepStyleMap^ s)
{
StyleSheet* to = as<StyleSheet>();
if (to != NULL && s != nullptr)
{
to->styles() = *(s->Val());
}
NotifyChanged("StyleMap");
}
oepStyle^ oepStyleSheet::DefaultStyle::get()
{
oepStyle^ res = gcnew oepStyle();
res->bind(as<osgEarth::Symbology::StyleSheet>()->getDefaultStyle(),false);
return res;
}
oepStyleSelectorList^ oepStyleSheet::Selectors::get()
{
return _selectors;
}
void oepStyleSheet::Selectors::set(oepStyleSelectorList^ s)
{
StyleSheet* to = as<StyleSheet>();
if (to != NULL && s != nullptr)
{
to->selectors() = *(s->Val());
}
NotifyChanged("Selectors");
}
oepResourceLibraryMap^ oepStyleSheet::Resources::get()
{
return _resLibs;
}
void oepStyleSheet::Resources::set(oepResourceLibraryMap^ s)
{
_resLibs = s;
as<osgEarth::Symbology::StyleSheet>()->ClearResourceLibrary();
for each (oepResourceLibrary^ r in s)
{
as<osgEarth::Symbology::StyleSheet>()->addResourceLibrary(r->as<osgEarth::ResourceLibrary>());
}
NotifyChanged("Resources");
}
oepStyleSheet::oepScriptDef^ oepStyleSheet::Script::get()
{
return _script;
}
void oepStyleSheet::Script::set(oepStyleSheet::oepScriptDef^ s)
{
_script = s;
as<osgEarth::Symbology::StyleSheet>()->setScript(_script->as<osgEarth::StyleSheet::ScriptDef>());
NotifyChanged("Script");
}
void gEarthPack::oepStyleSheet::binded()
{
_stylemap = gcnew oepStyleMap();
_stylemap->bind(&(as<osgEarth::Symbology::StyleSheet>()->styles()),false);
_selectors = gcnew oepStyleSelectorList();
_selectors->bind(&(as<osgEarth::Symbology::StyleSheet>()->selectors()),false);
_script = gcnew oepScriptDef();
_script->bind(as<osgEarth::Symbology::StyleSheet>()->script());
_resLibs = gcnew oepResourceLibraryMap();
std::vector<std::string> names = as<osgEarth::Symbology::StyleSheet>()->getResourceNames();
for (size_t i = 0; i < names.size(); i++)
{
oepResourceLibrary^ r = gcnew oepResourceLibrary("","");
r->bind(as<osgEarth::Symbology::StyleSheet>()->getResourceLibrary(names[i]));
}
_resLibs->CollectionChanged += gcnew System::Collections::Specialized::NotifyCollectionChangedEventHandler(this, &gEarthPack::oepStyleSheet::OnResourceCollectionChanged);
}
void gEarthPack::oepStyleSheet::unbinded()
{
_stylemap->unbind();
_selectors->unbind();
_script->unbind();
}
void oepStyleSheet::OnResourceCollectionChanged(System::Object^ sender, System::Collections::Specialized::NotifyCollectionChangedEventArgs^ e)
{
switch (e->Action)
{
case System::Collections::Specialized::NotifyCollectionChangedAction::Add:
{
if (e->NewItems != nullptr && e->NewItems->Count > 0)
{
for (int i = 0; i < e->NewItems->Count; i++)
{
oepResourceLibrary^ r = dynamic_cast<oepResourceLibrary^>(e->NewItems[i]);
if (r != nullptr)
{
as<osgEarth::Symbology::StyleSheet>()->addResourceLibrary(r->as<osgEarth::ResourceLibrary>());
}
}
}
break;
}
case System::Collections::Specialized::NotifyCollectionChangedAction::Remove:
{
if (e->OldItems != nullptr && e->OldItems->Count > 0)
{
for (int i = 0; i < e->OldItems->Count; i++)
{
oepResourceLibrary^ r = dynamic_cast<oepResourceLibrary^>(e->NewItems[i]);
if (r != nullptr)
{
as<osgEarth::Symbology::StyleSheet>()->removeResourceLibrary(r->as<osgEarth::ResourceLibrary>());
}
}
}
break;
}
case System::Collections::Specialized::NotifyCollectionChangedAction::Replace:
{
throw gcnew NotImplementedException();
break;
}
case System::Collections::Specialized::NotifyCollectionChangedAction::Move:
{
throw gcnew NotImplementedException();
break;
}
case System::Collections::Specialized::NotifyCollectionChangedAction::Reset:
{
as<osgEarth::Symbology::StyleSheet>()->ClearResourceLibrary();
break;
}
default:
break;
}
}
| 25.185022
| 171
| 0.710687
|
songgod
|
0442b8701484addd1eebe0881a00d8117ee21d37
| 2,563
|
hpp
|
C++
|
include/merge.hpp
|
vreverdy/bit-algorithms
|
bc12928d46846eb32b3d9e0a006549a947c4803f
|
[
"BSD-3-Clause"
] | 16
|
2019-06-17T23:56:15.000Z
|
2021-07-04T23:35:31.000Z
|
include/merge.hpp
|
bkille/bit-algorithms
|
bc12928d46846eb32b3d9e0a006549a947c4803f
|
[
"BSD-3-Clause"
] | 3
|
2019-04-28T04:53:31.000Z
|
2019-06-01T15:15:11.000Z
|
include/merge.hpp
|
bkille/bit-algorithms
|
bc12928d46846eb32b3d9e0a006549a947c4803f
|
[
"BSD-3-Clause"
] | 6
|
2019-03-13T19:21:36.000Z
|
2020-01-01T12:31:34.000Z
|
// ================================= MERGE ================================= //
// Project: The Experimental Bit Algorithms Library
// Name: merge.hpp
// Description: bit_iterator overloads for std::merge
// Creator: Vincent Reverdy
// Contributor(s):
// License: BSD 3-Clause License
// ========================================================================== //
#ifndef _MERGE_HPP_INCLUDED
#define _MERGE_HPP_INCLUDED
// ========================================================================== //
// ============================== PREAMBLE ================================== //
// C++ standard library
// Project sources
// Third-party libraries
// Miscellaneous
namespace bit {
// ========================================================================== //
// Status: to do
template <class InputIt1, class InputIt2, class OutputIt>
constexpr bit_iterator<OutputIt> merge(bit_iterator<InputIt1> first1,
bit_iterator<InputIt1> last1, bit_iterator<InputIt2> first2,
bit_iterator<InputIt2> last2, bit_iterator<OutputIt> d_first) {
(first1, last1, first2, last2);
return d_first;
}
// Status: to do
template <class ExecutionPolicy, class ForwardIt1, class ForwardIt2,
class ForwardIt3> bit_iterator<ForwardIt3> merge(ExecutionPolicy&& policy,
bit_iterator<ForwardIt1> first1, bit_iterator<ForwardIt1> last1,
bit_iterator<ForwardIt2> first2, bit_iterator<ForwardIt2> last2,
bit_iterator<ForwardIt3> first3) {
(policy, first1, last1, first2, last2);
return first3;
}
// Status: on hold
template <class InputIt1, class InputIt2, class OutputIt, class Compare>
constexpr bit_iterator<OutputIt> merge(bit_iterator<InputIt1> first1,
bit_iterator<InputIt1> last1, bit_iterator<InputIt2> first2,
bit_iterator<InputIt2> last2, bit_iterator<OutputIt> d_first,
Compare comp) {
(first1, last1, first2, last2, comp);
return d_first;
}
// Status: on hold
template <class ExecutionPolicy, class ForwardIt1, class ForwardIt2,
class ForwardIt3, class Compare> bit_iterator<ForwardIt3> merge(
ExecutionPolicy&& policy, bit_iterator<ForwardIt1> first1,
bit_iterator<ForwardIt1> last1, bit_iterator<ForwardIt2> first2,
bit_iterator<ForwardIt2> last2, bit_iterator<ForwardIt3> d_first,
Compare comp) {
(policy, first1, last1, first2, last2, comp);
return d_first;
}
// ========================================================================== //
} // namespace bit
#endif // _MERGE_HPP_INCLUDED
// ========================================================================== //
| 37.691176
| 80
| 0.591104
|
vreverdy
|
04470163ff47debf6f7f98a552879cb8aa91ef21
| 4,268
|
hpp
|
C++
|
include/matazure/config.hpp
|
Lexxos/mtensor
|
feb120923dad3fb4ae3b31dd09931622a63c3d06
|
[
"MIT"
] | 1
|
2021-12-14T10:09:27.000Z
|
2021-12-14T10:09:27.000Z
|
include/matazure/config.hpp
|
Lexxos/mtensor
|
feb120923dad3fb4ae3b31dd09931622a63c3d06
|
[
"MIT"
] | null | null | null |
include/matazure/config.hpp
|
Lexxos/mtensor
|
feb120923dad3fb4ae3b31dd09931622a63c3d06
|
[
"MIT"
] | null | null | null |
#pragma once
#include <algorithm>
#include <cassert>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <functional>
#include <limits>
#include <memory>
#include <stdexcept>
#include <string>
#include <tuple>
#include <type_traits>
// for cuda
#if defined(__CUDACC__) && !defined(MATAZURE_DISABLE_CUDA)
#ifdef __clang__
#if __clang_major__ < 9
#error clang minimum version is 9 for cuda
#endif
#else
#if __CUDACC_VER_MAJOR__ < 9
#error CUDA minimum version is 10.0
#endif
#endif
#define MATAZURE_CUDA
#endif
#ifdef MATAZURE_CUDA
#define MATAZURE_GENERAL __host__ __device__
#define MATAZURE_DEVICE __device__
#define MATAZURE_GLOBAL __global__
#ifndef __clang__
#define MATAZURE_NV_EXE_CHECK_DISABLE #pragma nv_exec_check_disable
#else
#define MATAZURE_NV_EXE_CHECK_DISABLE
#endif
#else
#define MATAZURE_DEVICE
#define MATAZURE_GENERAL
#define MATAZURE_GLOBAL
#define MATAZURE_NV_EXE_CHECK_DISABLE
#endif
#ifdef _OPENMP
#define MATAZURE_OPENMP
#endif
#define MLAMBDA [=] MATAZURE_GENERAL
#if __cplusplus >= 201103L || (defined(_MSC_VER) && _MSC_VER >= 1900)
#else
#error "use c++11 at least"
#endif
// for using
namespace matazure {
typedef int int_t;
typedef unsigned int uint_t;
using std::make_shared;
using std::move;
using std::shared_ptr;
using std::unique_ptr;
typedef unsigned char byte;
using std::decay;
using std::forward;
using std::remove_all_extents;
using std::remove_const;
using std::remove_cv;
using std::remove_reference;
using std::is_assignable;
using std::is_convertible;
using std::conditional;
using std::enable_if;
using std::integral_constant;
using std::is_integral;
using std::is_same;
using std::numeric_limits;
using std::get;
using std::make_tuple;
using std::tie;
using std::tuple;
using std::tuple_element;
using std::tuple_size;
using std::string;
template <bool _Val>
using bool_constant = integral_constant<bool, _Val>;
template <typename _Ty>
using decay_t = typename decay<_Ty>::type;
template <typename _Ty>
using remove_reference_t = typename remove_reference<_Ty>::type;
template <bool _Test, class _Ty = void>
using enable_if_t = typename enable_if<_Test, _Ty>::type;
template <bool _Test, class _Ty1, class _Ty2>
using conditional_t = typename conditional<_Test, _Ty1, _Ty2>::type;
template <typename _Ty>
using remove_const_t = typename remove_const<_Ty>::type;
template <typename _Ty>
using remove_cv_t = typename remove_cv<_Ty>::type;
struct blank_t {};
} // namespace matazure
// for assert
#define MATAZURE_STATIC_ASSERT_DIM_MATCHED(T1, T2) \
static_assert(T1::rank == T2::rank, "the rank is not matched")
#define MATAZURE_STATIC_ASSERT_VALUE_TYPE_MATCHED(T1, T2) \
static_assert(std::is_same<typename T1::value_type, typename T2::value_type>::value, \
"the value type is not matched")
#define MATAZURE_STATIC_ASSERT_MEMORY_TYPE_MATCHED(T1, T2) \
static_assert(std::is_same<runtime_t<T1>, runtime_t<T2>>::value, \
"the memory type is not matched")
#define MATAZURE_STATIC_ASSERT_MATRIX_RANK(T) \
static_assert(T::rank == 2, "the matrix rank should be 2")
#define MATAZURE_CURRENT_FUNCTION "(unknown)"
#if defined(__has_builtin)
#if __has_builtin(__builtin_expect)
#define MATAZURE_LIKELY(x) __builtin_expect(x, 1)
#define MATAZURE_UNLIKELY(x) __builtin_expect(x, 0)
#else
#define MATAZURE_LIKELY(x) x
#define MATAZURE_UNLIKELY(x) x
#endif
#else
#define MATAZURE_LIKELY(x) x
#define MATAZURE_UNLIKELY(x) x
#endif
#if defined(MATAZURE_DISABLE_ASSERTS)
#define MATAZURE_ASSERT(expr, msg) ((void)0)
#else
namespace matazure {
class assert_failed : public std::runtime_error {
public:
assert_failed(const std::string& msg) : std::runtime_error(msg) {}
};
inline void assertion_failed(char const* expr, char const* msg, char const* function,
char const* file, long line) {
throw assert_failed(std::string(msg));
}
} // namespace matazure
#define MATAZURE_ASSERT(expr, msg) \
(MATAZURE_LIKELY(!!(expr)) ? ((void)0) \
: ::matazure::assertion_failed( \
#expr, msg, MATAZURE_CURRENT_FUNCTION, __FILE__, __LINE__))
#endif
| 23.977528
| 96
| 0.727273
|
Lexxos
|
044def072252e1c3ece99e19e44d776108764a0c
| 706
|
cpp
|
C++
|
src/Actions/Lexicon/LexiconClearAction.cpp
|
viveret/script-ai
|
15f8dc561e55812de034bb729e83ff01bec61743
|
[
"BSD-3-Clause"
] | null | null | null |
src/Actions/Lexicon/LexiconClearAction.cpp
|
viveret/script-ai
|
15f8dc561e55812de034bb729e83ff01bec61743
|
[
"BSD-3-Clause"
] | null | null | null |
src/Actions/Lexicon/LexiconClearAction.cpp
|
viveret/script-ai
|
15f8dc561e55812de034bb729e83ff01bec61743
|
[
"BSD-3-Clause"
] | null | null | null |
#include "../Actions.hpp"
#include "../../Program.hpp"
#include "../../AIModelAdapter.hpp"
#include "../../Data/DAOs.hpp"
#include "../../Data/Commands/Model/LexiconModel.hpp"
#include "../../Data/Commands/Lexicon/LexiconClearCmd.hpp"
#include <iostream>
using namespace ScriptAI;
using namespace Sql;
LexiconClearAction::LexiconClearAction(AIProgram *prog): MenuAction(prog) {
}
const char* LexiconClearAction::label() {
return "lexicon clear";
}
std::string LexiconClearAction::description() {
return "Clear lexicon from neural network";
}
void LexiconClearAction::run() {
LexiconClearCmd(SqlContext()).execute(nullptr);
this->_prog->lexicon->clear();
std::cout << "Success!" << std::endl;
}
| 23.533333
| 75
| 0.715297
|
viveret
|
0453831f45228f3c8945ca83fcfa519d78cf0473
| 515
|
cpp
|
C++
|
windows/image.cpp
|
LeeDark/libui
|
244c837fc510fdbaa4427be6d6a4b48e58aa000f
|
[
"MIT"
] | null | null | null |
windows/image.cpp
|
LeeDark/libui
|
244c837fc510fdbaa4427be6d6a4b48e58aa000f
|
[
"MIT"
] | null | null | null |
windows/image.cpp
|
LeeDark/libui
|
244c837fc510fdbaa4427be6d6a4b48e58aa000f
|
[
"MIT"
] | null | null | null |
#include "uipriv_windows.hpp"
struct uiImage {
double width;
double height;
//GPtrArray *images;
};
uiImage *uiNewImage(double width, double height)
{
uiImage *i;
i = uiNew(uiImage);
i->width = width;
i->height = height;
// i->images = g_ptr_array_new_with_free_func(freeImageRep);
return i;
}
void uiFreeImage(uiImage *i)
{
// g_ptr_array_free(i->images, TRUE);
uiFree(i);
}
void uiImageAppend(uiImage *i, void *pixels, int pixelWidth, int pixelHeight, int pixelStride)
{
return;
// TODO
}
| 15.606061
| 94
| 0.697087
|
LeeDark
|
04552e615c6777b472a2815807513997771de805
| 20,133
|
cpp
|
C++
|
apps/Viewer/src/SceneTreeBrowser.cpp
|
asuessenbach/pipeline
|
2e49968cc3b9948a57f7ee6c4cc3258925c92ab2
|
[
"BSD-3-Clause"
] | 217
|
2015-01-06T09:26:53.000Z
|
2022-03-23T14:03:18.000Z
|
apps/Viewer/src/SceneTreeBrowser.cpp
|
asuessenbach/pipeline
|
2e49968cc3b9948a57f7ee6c4cc3258925c92ab2
|
[
"BSD-3-Clause"
] | 10
|
2015-01-25T12:42:05.000Z
|
2017-11-28T16:10:16.000Z
|
apps/Viewer/src/SceneTreeBrowser.cpp
|
asuessenbach/pipeline
|
2e49968cc3b9948a57f7ee6c4cc3258925c92ab2
|
[
"BSD-3-Clause"
] | 44
|
2015-01-13T01:19:41.000Z
|
2022-02-21T21:35:08.000Z
|
// Copyright (c) 2013-2016, NVIDIA CORPORATION. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <QDialogButtonBox>
#include <QEvent>
#include <QFileDialog>
#include <QMessageBox>
#include <QPlainTextEdit>
#include <QMimeData>
#include <QDrag>
#include "CommandAddItem.h"
#include "CommandReplaceItem.h"
#include "ScenePropertiesWidget.h"
#include "SceneTreeBrowser.h"
#include "SceneTreeItem.h"
#include "Viewer.h"
#include <dp/fx/ParameterGroupSpec.h>
#include <dp/sg/core/GeoNode.h>
#include <dp/sg/core/ParameterGroupData.h>
#include <dp/sg/core/PipelineData.h>
using namespace dp::math;
using namespace dp::sg::core;
SceneTreeBrowser::SceneTreeBrowser( QWidget * parent )
: QDockWidget( "Scene Tree", parent )
, m_objectObserver(this)
{
setObjectName( "Scene Tree" );
setAcceptDrops( true );
m_tree = new QTreeWidget();
m_tree->setHeaderHidden( true );
connect( m_tree, SIGNAL(currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)), this, SLOT(currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)) );
connect( m_tree, SIGNAL(itemExpanded(QTreeWidgetItem*)), this, SLOT(itemExpanded(QTreeWidgetItem*)) );
connect( m_tree, SIGNAL(itemPressed(QTreeWidgetItem*,int)), this, SLOT(itemPressed(QTreeWidgetItem*,int)) );
setWidget( m_tree );
connect(GetApp(), SIGNAL(sceneTreeChanged()), this, SLOT(updateTree()));
}
SceneTreeBrowser::~SceneTreeBrowser()
{
DP_ASSERT( m_tree );
if ( m_tree->currentItem() )
{
DP_ASSERT( dynamic_cast<SceneTreeItem*>(m_tree->currentItem()) );
DP_ASSERT( static_cast<SceneTreeItem*>(m_tree->currentItem())->getObject() );
static_cast<SceneTreeItem*>(m_tree->currentItem())->getObject()->detach( &m_objectObserver );
}
}
QTreeWidget * SceneTreeBrowser::getTree() const
{
return( m_tree );
}
void SceneTreeBrowser::selectObject( dp::sg::core::PathSharedPtr const& path )
{
if ( isVisible() )
{
DP_ASSERT( dynamic_cast<SceneTreeItem*>(m_tree->topLevelItem( 0 )) );
SceneTreeItem * item = static_cast<SceneTreeItem *>(m_tree->topLevelItem( 0 ));
for ( unsigned int i=0 ; i<path->getLength() ; i++ )
{
if ( item->childCount() == 0 )
{
item->expandItem();
}
bool found = false;
for ( int j=0 ; j<item->childCount() && !found ; j++ )
{
if ( static_cast<SceneTreeItem*>(item->child( j ))->getObject() == path->getFromHead( i ) )
{
item = static_cast<SceneTreeItem*>(item->child( j ));
found = true;
}
}
DP_ASSERT( found );
}
m_tree->setCurrentItem( item );
}
}
void SceneTreeBrowser::setScene( SceneSharedPtr const & scene )
{
m_tree->clear();
if ( scene )
{
m_tree->addTopLevelItem( new SceneTreeItem( scene ) );
}
}
std::vector<dp::fx::ParameterGroupSpec::iterator> getEmptySamplerParameters( const ParameterGroupDataSharedPtr & parameterGroupData )
{
std::vector<dp::fx::ParameterGroupSpec::iterator> samplerParameters;
const dp::fx::ParameterGroupSpecSharedPtr & pgs = parameterGroupData->getParameterGroupSpec();
for ( dp::fx::ParameterGroupSpec::iterator it = pgs->beginParameterSpecs() ; it != pgs->endParameterSpecs() ; ++it )
{
if ( ( ( it->first.getType() & dp::fx::PT_POINTER_TYPE_MASK ) == dp::fx::PT_SAMPLER_PTR ) && ! parameterGroupData->getParameter<SamplerSharedPtr>( it ) )
{
samplerParameters.push_back( it );
}
}
return( samplerParameters );
}
void SceneTreeBrowser::contextMenuEvent( QContextMenuEvent * event )
{
QDockWidget::contextMenuEvent( event );
if ( dynamic_cast<SceneTreeItem*>(m_tree->currentItem()) && dynamic_cast<SceneTreeItem*>(m_tree->currentItem())->getObject() )
{
SceneTreeItem * currentItem = static_cast<SceneTreeItem*>(m_tree->currentItem());
QMenu menu( "Tree Context Menu", this );
dp::sg::core::ObjectCode objectCode = currentItem->getObject()->getObjectCode();
switch( objectCode )
{
case ObjectCode::GEO_NODE :
{
QAction * pipelineAction = menu.addAction( "&Show shader pipeline ..." );
connect( pipelineAction, SIGNAL(triggered()), this, SLOT(triggeredShowShaderPipeline()) );
}
break;
case ObjectCode::PRIMITIVE :
{
VertexAttributeSetSharedPtr vas = std::static_pointer_cast<Primitive>(currentItem->getObject())->getVertexAttributeSet();
if ( !vas->getVertexAttribute( VertexAttributeSet::AttributeID::TEXCOORD0 ).getBuffer() )
{
QMenu * subMenu = menu.addMenu( "Generate Texture &Coordinates" );
subMenu->addAction( "Cylindrical" );
subMenu->actions().back()->setData( static_cast<unsigned int>(TextureCoordType::CYLINDRICAL) );
subMenu->addAction( "Planar" );
subMenu->actions().back()->setData( static_cast<unsigned int>(TextureCoordType::PLANAR) );
subMenu->addAction( "Spherical" );
subMenu->actions().back()->setData( static_cast<unsigned int>(TextureCoordType::SPHERICAL) );
connect( subMenu, SIGNAL( triggered( QAction * ) ), this, SLOT( triggeredGenerateTextureCoordinatesMenu( QAction * ) ) );
}
if ( vas->getVertexAttribute( VertexAttributeSet::AttributeID::TEXCOORD0 ).getBuffer()
&& ! vas->getVertexAttribute( VertexAttributeSet::AttributeID::TEXCOORD6 ).getBuffer()
&& ! vas->getVertexAttribute( VertexAttributeSet::AttributeID::TEXCOORD7 ).getBuffer() )
{
QAction * action = menu.addAction( "Generate &Tangent Space" );
connect( action, SIGNAL(triggered()), this, SLOT(triggeredGenerateTangentSpace()) );
}
}
break;
case ObjectCode::PARAMETER_GROUP_DATA :
{
ParameterGroupDataSharedPtr parameterGroupData = std::static_pointer_cast<ParameterGroupData>(currentItem->getObject());
std::vector<dp::fx::ParameterGroupSpec::iterator> samplerParameters = getEmptySamplerParameters( parameterGroupData );
if ( ! samplerParameters.empty() )
{
QMenu * subMenu = menu.addMenu( "&Add Sampler for Parameter" );
for ( size_t i=0 ; i<samplerParameters.size() ; i++ )
{
subMenu->addAction( QApplication::translate( VIEWER_APPLICATION_NAME, samplerParameters[i]->first.getName().c_str() ) );
}
connect( subMenu, SIGNAL(triggered(QAction*)), this, SLOT(triggeredAddSamplerMenu(QAction*)) );
}
}
break;
case ObjectCode::PARALLEL_CAMERA :
case ObjectCode::PERSPECTIVE_CAMERA :
case ObjectCode::MATRIX_CAMERA :
{
QMenu * subMenu = menu.addMenu( "&Add Headlight" );
subMenu->addAction( "&Directed Light" );
subMenu->addAction( "&Point Light" );
subMenu->addAction( "&Spot Light" );
for ( int i=0 ; i<subMenu->actions().size() ; ++i )
{
subMenu->actions()[i]->setData( i );
}
connect( subMenu, SIGNAL(triggered(QAction*)), this, SLOT(triggeredAddHeadlightMenu(QAction*)) );
}
break;
case ObjectCode::PIPELINE_DATA :
{
QAction * saveAction = menu.addAction( "&Save EffectData ..." );
connect( saveAction, SIGNAL(triggered()), this, SLOT(triggeredSaveEffectData()) );
QAction * replaceAction = menu.addAction( "&Replace by Clone" );
connect( replaceAction, SIGNAL(triggered()), this, SLOT(triggeredReplaceByClone()) );
}
break;
}
if ( objectCode != ObjectCode::SCENE )
{
if ( ! menu.isEmpty() )
{
menu.addSeparator();
}
std::ostringstream oss;
oss << "&Delete " << objectCodeToName( objectCode );
QAction * deleteAction = menu.addAction( oss.str().c_str() );
connect( deleteAction, SIGNAL(triggered()), this, SLOT(triggeredDeleteObject()) );
}
menu.exec( event->globalPos() );
}
}
void SceneTreeBrowser::currentItemChanged( QTreeWidgetItem * current, QTreeWidgetItem * previous )
{
if ( previous )
{
DP_ASSERT( dynamic_cast<SceneTreeItem*>(previous) );
DP_ASSERT( static_cast<SceneTreeItem*>(previous)->getObject() );
static_cast<SceneTreeItem*>(previous)->getObject()->detach( &m_objectObserver );
}
if ( current )
{
DP_ASSERT( dynamic_cast<SceneTreeItem*>(current) );
DP_ASSERT( static_cast<SceneTreeItem*>(current)->getObject() );
static_cast<SceneTreeItem*>(current)->getObject()->attach( &m_objectObserver );
}
emit currentItemChanged( dynamic_cast<SceneTreeItem*>(current) ? static_cast<SceneTreeItem*>(current)->getObject() : ObjectSharedPtr()
, dynamic_cast<SceneTreeItem*>(previous) ? static_cast<SceneTreeItem*>(previous)->getObject() : ObjectSharedPtr() );
}
void SceneTreeBrowser::itemExpanded( QTreeWidgetItem * item )
{
DP_ASSERT( dynamic_cast<SceneTreeItem*>(item) );
static_cast<SceneTreeItem*>(item)->expandItem();
}
void SceneTreeBrowser::itemPressed( QTreeWidgetItem * item, int column )
{
DP_ASSERT( dynamic_cast<SceneTreeItem*>(item) );
if ( ( QApplication::mouseButtons() & Qt::LeftButton ) && ( static_cast<SceneTreeItem*>(item)->getObject()->getObjectCode() == ObjectCode::PIPELINE_DATA ) )
{
// start drag'n'drop on EffectData
// We don't set the EffectData as the MimeData, but the GeoNode, as both the material of the GeoNode and the geometry of the Primitive need to be copied!
dp::fx::EffectSpec::Type type = std::static_pointer_cast<dp::sg::core::PipelineData>(static_cast<SceneTreeItem*>(item)->getObject())->getEffectSpec()->getType();
if ( type == dp::fx::EffectSpec::Type::PIPELINE )
{
DP_ASSERT( item->parent() );
item = item->parent();
DP_ASSERT( std::dynamic_pointer_cast<GeoNode>(static_cast<SceneTreeItem*>(item)->getObject()) );
GeoNodeSharedPtr geoNode = std::static_pointer_cast<GeoNode>(static_cast<SceneTreeItem*>(item)->getObject());
QByteArray qba( reinterpret_cast<char*>(&geoNode), sizeof(void*) );
QMimeData * mimeData = new QMimeData;
mimeData->setData( "EffectData", qba );
QDrag * drag = new QDrag( this );
drag->setMimeData( mimeData );
drag->exec();
}
}
}
void SceneTreeBrowser::triggeredAddHeadlightMenu( QAction * action )
{
std::string name;
LightSourceSharedPtr lightSource;
switch ( action->data().toUInt() )
{
case 0 :
lightSource = createStandardDirectedLight( Vec3f( 0.0f, 0.0f, -1.0f ), Vec3f( 1.0f, 1.0f, 1.0f ) );
name = "SVDirectedLight";
break;
case 1 :
lightSource = createStandardPointLight( Vec3f( 0.0f, 0.0f, 0.0f ), Vec3f( 1.0f, 1.0f, 1.0f ) );
name = "SVPointLight";
break;
case 2 :
lightSource = createStandardSpotLight( Vec3f( 0.0f, 0.0f, 0.0f ), Vec3f( 0.0f, 0.0f, -1.0f ), Vec3f( 1.0f, 1.0f, 1.0f ) );
name = "SVSpotLight";
break;
default :
DP_ASSERT( false );
break;
}
DP_ASSERT( lightSource );
lightSource->setName( name );
DP_ASSERT( dynamic_cast<SceneTreeItem*>(m_tree->currentItem()) );
DP_ASSERT( std::dynamic_pointer_cast<Camera>(static_cast<SceneTreeItem*>(m_tree->currentItem())->getObject()) );
ExecuteCommand( new CommandAddItem( static_cast<SceneTreeItem*>(m_tree->currentItem()), new SceneTreeItem( lightSource ) ) );
}
void SceneTreeBrowser::triggeredAddSamplerMenu( QAction * action )
{
DP_ASSERT( dynamic_cast<SceneTreeItem*>(m_tree->currentItem()) );
DP_ASSERT( std::dynamic_pointer_cast<ParameterGroupData>(static_cast<SceneTreeItem*>(m_tree->currentItem())->getObject()) );
SamplerSharedPtr sampler = Sampler::create();
sampler->setName( action->text().toStdString() );
ExecuteCommand( new CommandAddItem( static_cast<SceneTreeItem*>(m_tree->currentItem()), new SceneTreeItem( sampler ) ) );
}
void SceneTreeBrowser::triggeredDeleteObject()
{
DP_ASSERT( dynamic_cast<SceneTreeItem*>(m_tree->currentItem()) );
DP_ASSERT( dynamic_cast<SceneTreeItem*>(m_tree->currentItem()->parent()) );
ExecuteCommand( new CommandAddItem( static_cast<SceneTreeItem*>(m_tree->currentItem()->parent()), static_cast<SceneTreeItem*>(m_tree->currentItem()), false ) );
}
void SceneTreeBrowser::triggeredGenerateTangentSpace()
{
DP_ASSERT( dynamic_cast<SceneTreeItem*>(m_tree->currentItem()) && dynamic_cast<SceneTreeItem*>(m_tree->currentItem())->getObject() );
SceneTreeItem * currentItem = static_cast<SceneTreeItem*>(m_tree->currentItem());
DP_ASSERT( std::dynamic_pointer_cast<Primitive>(currentItem->getObject()) );
ExecuteCommand(new CommandGenerateTangentSpace(std::static_pointer_cast<Primitive>(currentItem->getObject())));
}
void SceneTreeBrowser::triggeredGenerateTextureCoordinatesMenu( QAction * action )
{
DP_ASSERT( dynamic_cast<SceneTreeItem*>(m_tree->currentItem()) && dynamic_cast<SceneTreeItem*>(m_tree->currentItem())->getObject() );
SceneTreeItem * currentItem = static_cast<SceneTreeItem*>(m_tree->currentItem());
DP_ASSERT( std::dynamic_pointer_cast<Primitive>(currentItem->getObject()) );
TextureCoordType tct = static_cast<TextureCoordType>( action->data().toInt() );
ExecuteCommand(new CommandGenerateTextureCoordinates(std::static_pointer_cast<Primitive>(currentItem->getObject()), tct));
}
const char * domainCodeToName( dp::fx::Domain domain )
{
switch( domain )
{
case dp::fx::Domain::VERTEX : return( "Vertex Shader" );
case dp::fx::Domain::FRAGMENT : return( "Fragment Shader" );
case dp::fx::Domain::GEOMETRY : return( "Geometry Shader" );
case dp::fx::Domain::TESSELLATION_CONTROL : return( "Tessellation Control Shader" );
case dp::fx::Domain::TESSELLATION_EVALUATION : return( "Tessellation Evaluation Shader" );
default :
DP_ASSERT( false );
return( "Unknown Shader" );
}
}
void SceneTreeBrowser::triggeredReplaceByClone()
{
DP_ASSERT( dynamic_cast<SceneTreeItem*>(m_tree->currentItem()) && dynamic_cast<SceneTreeItem*>(m_tree->currentItem())->getObject() );
SceneTreeItem * currentItem = static_cast<SceneTreeItem*>(m_tree->currentItem());
DP_ASSERT( currentItem->parent() && dynamic_cast<SceneTreeItem*>(currentItem->parent()) );
ExecuteCommand(new CommandReplaceItem(static_cast<SceneTreeItem*>(currentItem->parent()), currentItem, new SceneTreeItem(std::static_pointer_cast<dp::sg::core::Object>(currentItem->getObject()->clone())), &m_objectObserver));
}
void SceneTreeBrowser::triggeredSaveEffectData()
{
DP_ASSERT( dynamic_cast<SceneTreeItem*>(m_tree->currentItem()) && dynamic_cast<SceneTreeItem*>(m_tree->currentItem())->getObject() );
DP_ASSERT( std::dynamic_pointer_cast<dp::sg::core::PipelineData>(static_cast<SceneTreeItem*>(m_tree->currentItem())->getObject()) );
dp::sg::core::PipelineDataSharedPtr pipelineData = std::static_pointer_cast<dp::sg::core::PipelineData>(static_cast<SceneTreeItem*>(m_tree->currentItem())->getObject());
std::string pipelineName = pipelineData->getEffectSpec()->getName();
QString fileName = QFileDialog::getSaveFileName( this, tr( "Save PipelineData" ), QString( pipelineName.c_str() ) + QString( ".xml" ), tr( "XML (*.xml)" ) );
if ( !fileName.isEmpty() )
{
pipelineData->save( fileName.toStdString() );
}
}
void SceneTreeBrowser::triggeredShowShaderPipeline()
{
DP_ASSERT( dynamic_cast<SceneTreeItem*>(m_tree->currentItem()) && dynamic_cast<SceneTreeItem*>(m_tree->currentItem())->getObject() );
DP_ASSERT(std::static_pointer_cast<GeoNode>(static_cast<SceneTreeItem*>(m_tree->currentItem())->getObject()));
GeoNodeSharedPtr geoNode = std::static_pointer_cast<GeoNode>(static_cast<SceneTreeItem*>(m_tree->currentItem())->getObject());
DP_ASSERT( GetApp() && GetApp()->getMainWindow() && GetApp()->getMainWindow()->getCurrentViewport() );
ViewerRendererWidget * vrw = GetApp()->getMainWindow()->getCurrentViewport();
dp::sg::ui::SceneRendererSharedPtr sceneRenderer = vrw->getSceneRenderer();
DP_ASSERT( sceneRenderer );
std::map<dp::fx::Domain,std::string> sources[2];
sources[0] = sceneRenderer->getShaderSources( geoNode, false );
sources[1] = sceneRenderer->getShaderSources( geoNode, true );
if ( sources[0].empty() && sources[1].empty() )
{
QMessageBox messageBox( QMessageBox::Information, tr( "Show Shader Pipeline" ), tr( "No Shader sources available." ), QMessageBox::Ok );
messageBox.exec();
}
else
{
static std::string passName[2] = { "Forward Pass", "Depth Pass" };
QTabWidget * topTab = new QTabWidget();
for ( int i=0 ; i<2 ; i++ )
{
QTabWidget * tab = new QTabWidget();
for ( std::map<dp::fx::Domain,std::string>::const_iterator it = sources[i].begin() ; it != sources[i].end() ; ++it )
{
QPlainTextEdit * edit = new QPlainTextEdit( tr( it->second.c_str() ) );
edit->setReadOnly( true );
edit->setLineWrapMode( QPlainTextEdit::NoWrap );
tab->addTab( edit, tr( domainCodeToName( it->first ) ) );
}
topTab->addTab( tab, tr( passName[i].c_str() ) );
}
QDialogButtonBox * buttonBox = new QDialogButtonBox( QDialogButtonBox::Close );
QVBoxLayout * layout = new QVBoxLayout();
layout->addWidget( topTab );
layout->addWidget( buttonBox );
QDialog * dialog = new QDialog( this );
dialog->setWindowTitle( QString( "Shader Pipeline: " ) + QString( geoNode->getMaterialPipeline()->getEffectSpec()->getName().c_str() ) );
dialog->setLayout( layout );
connect( buttonBox, SIGNAL(rejected()), dialog, SLOT(reject()) );
dialog->show();
}
}
void SceneTreeBrowser::updateTree()
{
if ( isVisible() )
{
DP_ASSERT( dynamic_cast<SceneTreeItem*>(m_tree->topLevelItem( 0 )) );
SceneTreeItem * item = static_cast<SceneTreeItem *>(m_tree->topLevelItem( 0 ));
item->update();
}
}
SceneTreeBrowser::ObjectObserver::ObjectObserver( SceneTreeBrowser * stb )
: m_stb(stb)
{
}
void SceneTreeBrowser::ObjectObserver::onNotify( const dp::util::Event &event, dp::util::Payload *payload )
{
DP_ASSERT( m_stb->getTree() && m_stb->getTree()->currentItem() );
DP_ASSERT( dynamic_cast<SceneTreeItem*>(m_stb->getTree()->currentItem()) );
SceneTreeItem * item = static_cast<SceneTreeItem*>(m_stb->getTree()->currentItem());
DP_ASSERT( item->getObject() );
std::string name = item->getObject()->getName();
if ( name.empty() )
{
name = "unnamed " + objectCodeToName( item->getObject()->getObjectCode() );
}
if ( name != item->text( 0 ).toStdString() )
{
item->setText( 0, name.c_str() );
}
}
void SceneTreeBrowser::ObjectObserver::onDestroyed( const dp::util::Subject& subject, dp::util::Payload* payload )
{
}
| 41.856549
| 227
| 0.682412
|
asuessenbach
|
045c6a3d29a48b144fbab8a8768ce0d00aa0f62d
| 6,118
|
cc
|
C++
|
third_party/protobuf/src/google/protobuf/compiler/cpp/metadata_test.cc
|
kvzhao/TensorRT-5.1.5
|
e47c3ca3247c8e63f0a236d547fc7b1327494e57
|
[
"Apache-2.0"
] | 83
|
2019-12-03T08:42:15.000Z
|
2022-03-30T13:22:37.000Z
|
third_party/protobuf/src/google/protobuf/compiler/cpp/metadata_test.cc
|
kvzhao/TensorRT-5.1.5
|
e47c3ca3247c8e63f0a236d547fc7b1327494e57
|
[
"Apache-2.0"
] | 8
|
2019-12-11T23:35:08.000Z
|
2021-10-06T13:31:32.000Z
|
third_party/protobuf/src/google/protobuf/compiler/cpp/metadata_test.cc
|
kvzhao/TensorRT-5.1.5
|
e47c3ca3247c8e63f0a236d547fc7b1327494e57
|
[
"Apache-2.0"
] | 45
|
2020-05-29T03:22:48.000Z
|
2022-03-21T16:19:01.000Z
|
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <memory>
#include <google/protobuf/compiler/cpp/cpp_helpers.h>
#include <google/protobuf/compiler/cpp/cpp_generator.h>
#include <google/protobuf/compiler/annotation_test_util.h>
#include <google/protobuf/compiler/command_line_interface.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/testing/file.h>
#include <google/protobuf/testing/file.h>
#include <google/protobuf/testing/googletest.h>
#include <gtest/gtest.h>
namespace google {
namespace protobuf {
namespace compiler {
namespace cpp {
namespace atu = annotation_test_util;
namespace {
class CppMetadataTest : public ::testing::Test {
public:
// Tries to capture a FileDescriptorProto, GeneratedCodeInfo, and output
// code from the previously added file with name `filename`. Returns true on
// success. If pb_h is non-null, expects a .pb.h and a .pb.h.meta (copied to
// pb_h and pb_h_info respecfively); similarly for proto_h and proto_h_info.
bool CaptureMetadata(const std::string& filename, FileDescriptorProto* file,
std::string* pb_h, GeneratedCodeInfo* pb_h_info,
std::string* proto_h, GeneratedCodeInfo* proto_h_info,
std::string* pb_cc) {
CommandLineInterface cli;
CppGenerator cpp_generator;
cli.RegisterGenerator("--cpp_out", &cpp_generator, "");
std::string cpp_out =
"--cpp_out=annotate_headers=true,"
"annotation_pragma_name=pragma_name,"
"annotation_guard_name=guard_name:" +
TestTempDir();
const bool result = atu::RunProtoCompiler(filename, cpp_out, &cli, file);
if (!result) {
return result;
}
std::string output_base = TestTempDir() + "/" + StripProto(filename);
if (pb_cc != NULL) {
GOOGLE_CHECK_OK(
File::GetContents(output_base + ".pb.cc", pb_cc, true));
}
if (pb_h != NULL && pb_h_info != NULL) {
GOOGLE_CHECK_OK(
File::GetContents(output_base + ".pb.h", pb_h, true));
if (!atu::DecodeMetadata(output_base + ".pb.h.meta", pb_h_info)) {
return false;
}
}
if (proto_h != NULL && proto_h_info != NULL) {
GOOGLE_CHECK_OK(File::GetContents(output_base + ".proto.h", proto_h,
true));
if (!atu::DecodeMetadata(output_base + ".proto.h.meta", proto_h_info)) {
return false;
}
}
return true;
}
};
const char kSmallTestFile[] =
"syntax = \"proto2\";\n"
"package foo;\n"
"enum Enum { VALUE = 0; }\n"
"message Message { }\n";
TEST_F(CppMetadataTest, CapturesEnumNames) {
FileDescriptorProto file;
GeneratedCodeInfo info;
std::string pb_h;
atu::AddFile("test.proto", kSmallTestFile);
EXPECT_TRUE(
CaptureMetadata("test.proto", &file, &pb_h, &info, NULL, NULL, NULL));
EXPECT_EQ("Enum", file.enum_type(0).name());
std::vector<int> enum_path;
enum_path.push_back(FileDescriptorProto::kEnumTypeFieldNumber);
enum_path.push_back(0);
const GeneratedCodeInfo::Annotation* enum_annotation =
atu::FindAnnotationOnPath(info, "test.proto", enum_path);
EXPECT_TRUE(NULL != enum_annotation);
EXPECT_TRUE(atu::AnnotationMatchesSubstring(pb_h, enum_annotation, "Enum"));
}
TEST_F(CppMetadataTest, AddsPragma) {
FileDescriptorProto file;
GeneratedCodeInfo info;
std::string pb_h;
atu::AddFile("test.proto", kSmallTestFile);
EXPECT_TRUE(
CaptureMetadata("test.proto", &file, &pb_h, &info, NULL, NULL, NULL));
EXPECT_TRUE(pb_h.find("#ifdef guard_name") != string::npos);
EXPECT_TRUE(pb_h.find("#pragma pragma_name \"test.pb.h.meta\"") !=
std::string::npos);
}
TEST_F(CppMetadataTest, CapturesMessageNames) {
FileDescriptorProto file;
GeneratedCodeInfo info;
std::string pb_h;
atu::AddFile("test.proto", kSmallTestFile);
EXPECT_TRUE(
CaptureMetadata("test.proto", &file, &pb_h, &info, NULL, NULL, NULL));
EXPECT_EQ("Message", file.message_type(0).name());
std::vector<int> message_path;
message_path.push_back(FileDescriptorProto::kMessageTypeFieldNumber);
message_path.push_back(0);
const GeneratedCodeInfo::Annotation* message_annotation =
atu::FindAnnotationOnPath(info, "test.proto", message_path);
EXPECT_TRUE(NULL != message_annotation);
EXPECT_TRUE(
atu::AnnotationMatchesSubstring(pb_h, message_annotation, "Message"));
}
} // namespace
} // namespace cpp
} // namespace compiler
} // namespace protobuf
} // namespace google
| 37.533742
| 78
| 0.708565
|
kvzhao
|
0465013a6e288944208b91815a24872c7b9cffe5
| 4,850
|
cpp
|
C++
|
src/modules/powerrename/lib/MRUListHandler.cpp
|
tameemzabalawi/PowerToys
|
5c6f7b1aea90ecd9ebe5cb8c7ddf82f8113fcb45
|
[
"MIT"
] | 4
|
2022-01-10T07:24:48.000Z
|
2022-02-07T02:08:03.000Z
|
src/modules/powerrename/lib/MRUListHandler.cpp
|
Nakatai-0322/PowerToys
|
1f64c1cf837ca958ad14dc3eb7887f36220a1ef9
|
[
"MIT"
] | 9
|
2021-05-12T17:12:35.000Z
|
2021-10-30T14:57:56.000Z
|
src/modules/powerrename/lib/MRUListHandler.cpp
|
Nakatai-0322/PowerToys
|
1f64c1cf837ca958ad14dc3eb7887f36220a1ef9
|
[
"MIT"
] | 3
|
2020-05-20T04:22:45.000Z
|
2021-03-11T00:22:20.000Z
|
#include "pch.h"
#include "MRUListHandler.h"
#include "Helpers.h"
#include <dll/PowerRenameConstants.h>
#include <common/SettingsAPI/settings_helpers.h>
namespace
{
const wchar_t c_mruList[] = L"MRUList";
const wchar_t c_insertionIdx[] = L"InsertionIdx";
const wchar_t c_maxMRUSize[] = L"MaxMRUSize";
}
MRUListHandler::MRUListHandler(unsigned int size, const std::wstring& filePath, const std::wstring& regPath) :
pushIdx(0),
nextIdx(1),
size(size),
jsonFilePath(PTSettingsHelper::get_module_save_folder_location(PowerRenameConstants::ModuleKey) + filePath),
registryFilePath(regPath)
{
items.resize(size);
Load();
}
void MRUListHandler::Push(const std::wstring& data)
{
if (Exists(data))
{
// TODO: Already existing item should be put on top of MRU list.
return;
}
items[pushIdx] = data;
pushIdx = (pushIdx + 1) % size;
Save();
}
bool MRUListHandler::Next(std::wstring& data)
{
if (nextIdx == size + 1)
{
Reset();
return false;
}
// Go backwards to consume latest items first.
unsigned int idx = (pushIdx + size - nextIdx) % size;
if (items[idx].empty())
{
Reset();
return false;
}
data = items[idx];
++nextIdx;
return true;
}
void MRUListHandler::Reset()
{
nextIdx = 1;
}
const std::vector<std::wstring>& MRUListHandler::GetItems()
{
return items;
}
void MRUListHandler::Load()
{
if (!std::filesystem::exists(jsonFilePath))
{
MigrateFromRegistry();
Save();
}
else
{
ParseJson();
}
}
void MRUListHandler::Save()
{
json::JsonObject jsonData;
jsonData.SetNamedValue(c_maxMRUSize, json::value(size));
jsonData.SetNamedValue(c_insertionIdx, json::value(pushIdx));
jsonData.SetNamedValue(c_mruList, Serialize());
json::to_file(jsonFilePath, jsonData);
}
json::JsonArray MRUListHandler::Serialize()
{
json::JsonArray searchMRU{};
std::wstring data{};
for (const std::wstring& item : items)
{
searchMRU.Append(json::value(item));
}
return searchMRU;
}
void MRUListHandler::MigrateFromRegistry()
{
std::wstring searchListKeys = GetRegString(c_mruList, registryFilePath);
std::sort(std::begin(searchListKeys), std::end(searchListKeys));
for (const wchar_t& key : searchListKeys)
{
Push(GetRegString(std::wstring(1, key), registryFilePath));
}
}
void MRUListHandler::ParseJson()
{
auto json = json::from_file(jsonFilePath);
if (json)
{
const json::JsonObject& jsonObject = json.value();
try
{
unsigned int oldSize{ size };
if (json::has(jsonObject, c_maxMRUSize, json::JsonValueType::Number))
{
oldSize = (unsigned int)jsonObject.GetNamedNumber(c_maxMRUSize);
}
unsigned int oldPushIdx{ 0 };
if (json::has(jsonObject, c_insertionIdx, json::JsonValueType::Number))
{
oldPushIdx = (unsigned int)jsonObject.GetNamedNumber(c_insertionIdx);
if (oldPushIdx < 0 || oldPushIdx >= oldSize)
{
oldPushIdx = 0;
}
}
if (json::has(jsonObject, c_mruList, json::JsonValueType::Array))
{
auto jsonArray = jsonObject.GetNamedArray(c_mruList);
if (oldSize == size)
{
for (uint32_t i = 0; i < jsonArray.Size(); ++i)
{
items[i] = std::wstring(jsonArray.GetStringAt(i));
}
pushIdx = oldPushIdx;
}
else
{
std::vector<std::wstring> temp;
for (unsigned int i = 0; i < min(jsonArray.Size(), size); ++i)
{
int idx = (oldPushIdx + oldSize - (i + 1)) % oldSize;
temp.push_back(std::wstring(jsonArray.GetStringAt(idx)));
}
if (size > oldSize)
{
std::reverse(std::begin(temp), std::end(temp));
pushIdx = (unsigned int)temp.size();
temp.resize(size);
}
else
{
temp.resize(size);
std::reverse(std::begin(temp), std::end(temp));
}
items = std::move(temp);
Save();
}
}
}
catch (const winrt::hresult_error&)
{
}
}
}
bool MRUListHandler::Exists(const std::wstring& data)
{
return std::find(std::begin(items), std::end(items), data) != std::end(items);
}
| 26.648352
| 112
| 0.537938
|
tameemzabalawi
|
0465f5e1bfb7fda559842de369d5c90adcc76489
| 465
|
hpp
|
C++
|
libraries/include/legendre_root.hpp
|
JoyM1K1/o3-sigma-model-TRG
|
2bbb5db3f5ea523e4dfb8a0b469e303abd9e563b
|
[
"MIT"
] | null | null | null |
libraries/include/legendre_root.hpp
|
JoyM1K1/o3-sigma-model-TRG
|
2bbb5db3f5ea523e4dfb8a0b469e303abd9e563b
|
[
"MIT"
] | null | null | null |
libraries/include/legendre_root.hpp
|
JoyM1K1/o3-sigma-model-TRG
|
2bbb5db3f5ea523e4dfb8a0b469e303abd9e563b
|
[
"MIT"
] | null | null | null |
#ifndef O3_SIGMA_MODEL_LEGENDRE_ROOT_HPP
#define O3_SIGMA_MODEL_LEGENDRE_ROOT_HPP
#include <vector>
namespace math {
namespace solver {
/// Derivative of Legendre polynomial. : P'n(x)
double d_legendre(int n, double x);
/// Newton's method.
double newton(int n, double x);
/// Calculate root of Legendre polynomial.
std::vector<double> legendre_root(int n);
}
}
#endif //O3_SIGMA_MODEL_LEGENDRE_ROOT_HPP
| 23.25
| 55
| 0.677419
|
JoyM1K1
|
046b5865b822ca9554fd3a7637795f57b79f706b
| 29,568
|
cpp
|
C++
|
src/openloco/windows/toolbar_top.cpp
|
panjacek/OpenLoco
|
0d6dc5e68e27082c0c56ab8334249561dfd7a909
|
[
"MIT"
] | null | null | null |
src/openloco/windows/toolbar_top.cpp
|
panjacek/OpenLoco
|
0d6dc5e68e27082c0c56ab8334249561dfd7a909
|
[
"MIT"
] | null | null | null |
src/openloco/windows/toolbar_top.cpp
|
panjacek/OpenLoco
|
0d6dc5e68e27082c0c56ab8334249561dfd7a909
|
[
"MIT"
] | null | null | null |
#include "../audio/audio.h"
#include "../companymgr.h"
#include "../config.h"
#include "../game_commands.h"
#include "../graphics/colours.h"
#include "../graphics/gfx.h"
#include "../graphics/image_ids.h"
#include "../input.h"
#include "../interop/interop.hpp"
#include "../localisation/string_ids.h"
#include "../objects/interface_skin_object.h"
#include "../objects/land_object.h"
#include "../objects/objectmgr.h"
#include "../objects/road_object.h"
#include "../objects/track_object.h"
#include "../objects/water_object.h"
#include "../stationmgr.h"
#include "../things/thingmgr.h"
#include "../things/vehicle.h"
#include "../townmgr.h"
#include "../ui/WindowManager.h"
#include "../ui/dropdown.h"
#include "toolbar_top_common.h"
#include <map>
using namespace openloco::interop;
namespace openloco::ui::windows::toolbar_top::game
{
static loco_global<uint8_t[40], 0x00113DB20> menu_options;
static loco_global<uint8_t, 0x00525FAA> last_railroad_option;
static loco_global<uint8_t, 0x00525FAB> last_road_option;
static loco_global<uint8_t, 0x00525FAF> last_vehicles_option;
static loco_global<uint8_t, 0x0052622C> last_build_vehicles_option;
static loco_global<uint32_t, 0x009C86F8> zoom_ticks;
static loco_global<uint8_t, 0x009C870C> last_town_option;
static loco_global<uint8_t, 0x009C870D> last_port_option;
static loco_global<int8_t[18], 0x0050A006> available_objects;
namespace widx
{
enum
{
railroad_menu = common::widx::w6
};
}
static widget_t _widgets[] = {
make_widget({ 0, 0 }, { 30, 28 }, widget_type::wt_7, 0),
make_widget({ 30, 0 }, { 30, 28 }, widget_type::wt_7, 0),
make_widget({ 74, 0 }, { 30, 28 }, widget_type::wt_7, 1),
make_widget({ 104, 0 }, { 30, 28 }, widget_type::wt_7, 1),
make_widget({ 134, 0 }, { 30, 28 }, widget_type::wt_7, 1),
make_widget({ 267, 0 }, { 30, 28 }, widget_type::wt_7, 2),
make_widget({ 387, 0 }, { 30, 28 }, widget_type::wt_7, 2),
make_widget({ 357, 0 }, { 30, 28 }, widget_type::wt_7, 2),
make_widget({ 417, 0 }, { 30, 28 }, widget_type::wt_7, 2),
make_widget({ 417, 0 }, { 30, 28 }, widget_type::wt_7, 2),
make_widget({ 490, 0 }, { 30, 28 }, widget_type::wt_7, 3),
make_widget({ 520, 0 }, { 30, 28 }, widget_type::wt_7, 3),
make_widget({ 460, 0 }, { 30, 28 }, widget_type::wt_7, 3),
widget_end(),
};
static window_event_list _events;
static void on_mouse_down(window* window, widget_index widgetIndex);
static void on_dropdown(window* window, widget_index widgetIndex, int16_t itemIndex);
static void prepare_draw(window* window);
static void draw(window* window, gfx::drawpixelinfo_t* dpi);
// 0x00438B26
void open()
{
zoom_ticks = 0;
last_town_option = 0;
last_port_option = 0;
_events.on_resize = common::on_resize;
_events.event_03 = on_mouse_down;
_events.on_mouse_down = on_mouse_down;
_events.on_dropdown = on_dropdown;
_events.on_update = common::on_update;
_events.prepare_draw = prepare_draw;
_events.draw = draw;
auto window = WindowManager::createWindow(
WindowType::topToolbar,
{ 0, 0 },
gfx::ui_size_t(ui::width(), 28),
window_flags::stick_to_front | window_flags::transparent | window_flags::no_background,
&_events);
window->widgets = _widgets;
window->enabled_widgets = (1 << common::widx::loadsave_menu) | (1 << common::widx::audio_menu) | (1 << common::widx::zoom_menu) | (1 << common::widx::rotate_menu) | (1 << common::widx::view_menu) | (1 << common::widx::terraform_menu) | (1 << widx::railroad_menu) | (1 << common::widx::road_menu) | (1 << common::widx::port_menu) | (1 << common::widx::build_vehicles_menu) | (1 << common::widx::vehicles_menu) | (1 << common::widx::stations_menu) | (1 << common::widx::towns_menu);
window->init_scroll_widgets();
auto skin = objectmgr::get<interface_skin_object>();
if (skin != nullptr)
{
window->colours[0] = skin->colour_12;
window->colours[1] = skin->colour_13;
window->colours[2] = skin->colour_14;
window->colours[3] = skin->colour_15;
}
}
// 0x0043B0F7
static void loadsave_menu_mouse_down(window* window, widget_index widgetIndex)
{
dropdown::add(0, string_ids::menu_load_game);
dropdown::add(1, string_ids::menu_save_game);
dropdown::add(2, 0);
dropdown::add(3, string_ids::menu_about);
dropdown::add(4, string_ids::options);
dropdown::add(5, string_ids::menu_screenshot);
dropdown::add(6, 0);
dropdown::add(7, string_ids::menu_quit_to_menu);
dropdown::add(8, string_ids::menu_exit_openloco);
dropdown::show_below(window, widgetIndex, 9);
dropdown::set_highlighted_item(1);
}
// 0x0043B154
static void loadsave_menu_dropdown(window* window, widget_index widgetIndex, int16_t itemIndex)
{
if (itemIndex == -1)
itemIndex = dropdown::get_highlighted_item();
switch (itemIndex)
{
case 0:
// Load game
game_commands::do_21(0, 0);
break;
case 1:
// Save game
call(0x0043B1C4);
break;
case 3:
about::open();
break;
case 4:
options::open();
break;
case 5:
{
loco_global<uint8_t, 0x00508F16> screenshot_countdown;
screenshot_countdown = 10;
break;
}
case 7:
// Return to title screen
game_commands::do_21(0, 1);
break;
case 8:
// Exit to desktop
game_commands::do_21(0, 2);
break;
}
}
// 0x0043B04B
static void audio_menu_mouse_down(window* window, widget_index widgetIndex)
{
dropdown::add(0, string_ids::dropdown_without_checkmark, string_ids::menu_mute);
dropdown::add(1, string_ids::dropdown_without_checkmark, string_ids::menu_play_music);
dropdown::add(2, 0);
dropdown::add(3, string_ids::menu_music_options);
dropdown::show_below(window, widgetIndex, 4);
if (!audio::isAudioEnabled())
dropdown::set_item_selected(0);
if (config::get().music_playing)
dropdown::set_item_selected(1);
dropdown::set_highlighted_item(0);
}
// 0x0043B0B8
static void audio_menu_dropdown(window* window, widget_index widgetIndex, int16_t itemIndex)
{
if (itemIndex == -1)
itemIndex = dropdown::get_highlighted_item();
switch (itemIndex)
{
case 0:
audio::toggle_sound();
break;
case 1:
{
auto& config = config::get();
if (config.music_playing)
{
config.music_playing = false;
audio::stop_background_music();
}
else
{
config.music_playing = true;
}
config::write();
break;
}
case 3:
options::open_music_settings();
break;
}
}
// 0x0043A2B0
static void railroad_menu_mouse_down(window* window, widget_index widgetIndex)
{
// Load objects.
registers regs;
regs.edi = (uint32_t)&available_objects[0];
call(0x004A6841, regs);
// Sanity check: any objects available?
uint32_t i = 0;
while (available_objects[i] != -1 && i < std::size(available_objects))
i++;
if (i == 0)
return;
auto company_colour = companymgr::get_player_company_colour();
// Add available objects to dropdown.
uint16_t highlighted_item = 0;
for (i = 0; available_objects[i] != -1 && i < std::size(available_objects); i++)
{
uint32_t obj_image;
string_id obj_string_id;
int objIndex = available_objects[i];
if ((objIndex & (1 << 7)) != 0)
{
auto road = objectmgr::get<road_object>(objIndex & 0x7F);
obj_string_id = road->name;
obj_image = gfx::recolour(road->var_0E, company_colour);
}
else
{
auto track = objectmgr::get<track_object>(objIndex);
obj_string_id = track->name;
obj_image = gfx::recolour(track->var_1E, company_colour);
}
dropdown::add(i, string_ids::menu_sprite_stringid_construction, { obj_image, obj_string_id });
if (objIndex == last_railroad_option)
highlighted_item = i;
}
dropdown::show_below(window, widgetIndex, i, 25);
dropdown::set_highlighted_item(highlighted_item);
}
// 0x0043A39F
static void railroad_menu_dropdown(window* window, widget_index widgetIndex, int16_t itemIndex)
{
if (itemIndex == -1)
itemIndex = dropdown::get_highlighted_item();
if (itemIndex == -1)
return;
uint8_t objIndex = available_objects[itemIndex];
construction::openWithFlags(objIndex);
}
// 0x0043A965
static void port_menu_mouse_down(window* window, widget_index widgetIndex)
{
uint8_t ddIndex = 0;
auto interface = objectmgr::get<interface_skin_object>();
if (addr<0x525FAC, int8_t>() != -1)
{
dropdown::add(ddIndex, string_ids::menu_sprite_stringid_construction, { interface->img + interface_skin::image_ids::toolbar_menu_airport, string_ids::menu_airport });
menu_options[ddIndex] = 0;
ddIndex++;
}
if (addr<0x525FAD, int8_t>() != -1)
{
dropdown::add(ddIndex, string_ids::menu_sprite_stringid_construction, { interface->img + interface_skin::image_ids::toolbar_menu_ship_port, string_ids::menu_ship_port });
menu_options[ddIndex] = 1;
ddIndex++;
}
if (ddIndex == 0)
return;
dropdown::show_below(window, widgetIndex, ddIndex, 25);
ddIndex = 0;
if (last_port_option != menu_options[0])
ddIndex++;
dropdown::set_highlighted_item(ddIndex);
}
// 0x0043AA0A
static void port_menu_dropdown(window* window, widget_index widgetIndex, int16_t itemIndex)
{
if (itemIndex == -1)
itemIndex = dropdown::get_highlighted_item();
last_port_option = menu_options[itemIndex];
if (last_port_option == 0)
{
construction::openWithFlags(1 << 31);
}
else if (last_port_option == 1)
{
construction::openWithFlags(1 << 30);
}
}
struct VehicleTypeInterfaceParam
{
uint32_t image;
uint32_t build_image;
string_id build_string;
string_id num_singular;
string_id num_plural;
};
static const std::map<VehicleType, VehicleTypeInterfaceParam> VehicleTypeInterfaceParameters{
{ VehicleType::bus, { interface_skin::image_ids::vehicle_bus, interface_skin::image_ids::build_vehicle_bus_frame_0, string_ids::build_buses, string_ids::num_buses_singular, string_ids::num_buses_plural } },
{ VehicleType::plane, { interface_skin::image_ids::vehicle_aircraft, interface_skin::image_ids::build_vehicle_aircraft_frame_0, string_ids::build_aircraft, string_ids::num_aircrafts_singular, string_ids::num_aircrafts_plural } },
{ VehicleType::ship, { interface_skin::image_ids::vehicle_ship, interface_skin::image_ids::build_vehicle_ship_frame_0, string_ids::build_ships, string_ids::num_ships_singular, string_ids::num_ships_plural } },
{ VehicleType::train, { interface_skin::image_ids::vehicle_train, interface_skin::image_ids::build_vehicle_train_frame_0, string_ids::build_trains, string_ids::num_trains_singular, string_ids::num_trains_plural } },
{ VehicleType::tram, { interface_skin::image_ids::vehicle_tram, interface_skin::image_ids::build_vehicle_tram_frame_0, string_ids::build_trams, string_ids::num_trams_singular, string_ids::num_trams_plural } },
{ VehicleType::truck, { interface_skin::image_ids::vehicle_truck, interface_skin::image_ids::build_vehicle_truck_frame_0, string_ids::build_trucks, string_ids::num_trucks_singular, string_ids::num_trucks_plural } },
};
// 0x0043AD1F
static void build_vehicles_menu_mouse_down(window* window, widget_index widgetIndex)
{
auto company = companymgr::get(companymgr::get_controlling_id());
uint16_t available_vehicles = company->available_vehicles;
auto company_colour = companymgr::get_player_company_colour();
auto interface = objectmgr::get<interface_skin_object>();
uint8_t ddIndex = 0;
for (uint8_t vehicleType = 0; vehicleType < vehicleTypeCount; vehicleType++)
{
if ((available_vehicles & (1 << vehicleType)) == 0)
continue;
auto& interface_param = VehicleTypeInterfaceParameters.at(static_cast<VehicleType>(vehicleType));
uint32_t vehicle_image = gfx::recolour(interface_param.build_image, company_colour);
dropdown::add(ddIndex, string_ids::menu_sprite_stringid, { interface->img + vehicle_image, interface_param.build_string });
menu_options[ddIndex] = vehicleType;
ddIndex++;
}
dropdown::show_below(window, widgetIndex, ddIndex, 25);
dropdown::set_highlighted_item(last_build_vehicles_option);
}
// 0x0043ADC7
static void build_vehicles_menu_dropdown(window* window, widget_index widgetIndex, int16_t itemIndex)
{
if (itemIndex == -1)
itemIndex = dropdown::get_highlighted_item();
if (itemIndex == -1)
return;
itemIndex = menu_options[itemIndex];
last_build_vehicles_option = itemIndex;
build_vehicle::open(itemIndex, 1 << 31);
}
// 0x0043ABCB
static void vehicles_menu_mouse_down(window* window, widget_index widgetIndex)
{
auto player_company_id = companymgr::get_controlling_id();
auto company = companymgr::get(player_company_id);
uint16_t available_vehicles = company->available_vehicles;
auto company_colour = companymgr::get_player_company_colour();
auto interface = objectmgr::get<interface_skin_object>();
uint16_t vehicle_counts[vehicleTypeCount]{ 0 };
for (openloco::vehicle* v = thingmgr::first<openloco::vehicle>(); v != nullptr; v = v->next_vehicle())
{
if (v->owner != player_company_id)
continue;
if ((v->var_38 & things::vehicle::flags_38::unk_4) != 0)
continue;
vehicle_counts[static_cast<uint8_t>(v->vehicleType)]++;
}
uint8_t ddIndex = 0;
for (uint16_t vehicleType = 0; vehicleType < vehicleTypeCount; vehicleType++)
{
if ((available_vehicles & (1 << vehicleType)) == 0)
continue;
auto& interface_param = VehicleTypeInterfaceParameters.at(static_cast<VehicleType>(vehicleType));
uint32_t vehicle_image = gfx::recolour(interface_param.image, company_colour);
uint16_t vehicle_count = vehicle_counts[vehicleType];
// TODO: replace with locale-based plurals.
string_id vehicle_string_id;
if (vehicle_count == 1)
vehicle_string_id = interface_param.num_singular;
else
vehicle_string_id = interface_param.num_plural;
dropdown::add(ddIndex, string_ids::menu_sprite_stringid, { interface->img + vehicle_image, vehicle_string_id, vehicle_count });
menu_options[ddIndex] = vehicleType;
ddIndex++;
}
dropdown::show_below(window, widgetIndex, ddIndex, 25);
dropdown::set_highlighted_item(last_vehicles_option);
}
// 0x0043ACEF
static void vehicles_menu_dropdown(window* window, widget_index widgetIndex, int16_t itemIndex)
{
if (itemIndex == -1)
itemIndex = dropdown::get_highlighted_item();
if (itemIndex == -1)
return;
auto vehicleType = menu_options[itemIndex];
last_vehicles_option = vehicleType;
windows::vehicle_list::open(companymgr::get_controlling_id(), vehicleType);
}
// 0x0043A4E9
static void stations_menu_mouse_down(window* window, widget_index widgetIndex)
{
auto interface = objectmgr::get<interface_skin_object>();
uint32_t sprite_base = interface->img;
// Apply company colour.
uint32_t company_colour = companymgr::get_player_company_colour();
sprite_base = gfx::recolour(sprite_base, company_colour);
dropdown::add(0, string_ids::menu_sprite_stringid, { sprite_base + interface_skin::image_ids::all_stations, string_ids::all_stations });
dropdown::add(1, string_ids::menu_sprite_stringid, { sprite_base + interface_skin::image_ids::rail_stations, string_ids::rail_stations });
dropdown::add(2, string_ids::menu_sprite_stringid, { sprite_base + interface_skin::image_ids::road_stations, string_ids::road_stations });
dropdown::add(3, string_ids::menu_sprite_stringid, { sprite_base + interface_skin::image_ids::airports, string_ids::airports });
dropdown::add(4, string_ids::menu_sprite_stringid, { sprite_base + interface_skin::image_ids::ship_ports, string_ids::ship_ports });
dropdown::show_below(window, widgetIndex, 5, 25);
dropdown::set_highlighted_item(0);
}
// 0x0043A596
static void stations_menu_dropdown(window* window, widget_index widgetIndex, int16_t itemIndex)
{
if (itemIndex == -1)
itemIndex = dropdown::get_highlighted_item();
if (itemIndex > 4)
return;
windows::station_list::open(companymgr::get_controlling_id(), itemIndex);
}
// 0x0043A071
static void on_mouse_down(window* window, widget_index widgetIndex)
{
switch (widgetIndex)
{
case common::widx::loadsave_menu:
loadsave_menu_mouse_down(window, widgetIndex);
break;
case common::widx::audio_menu:
audio_menu_mouse_down(window, widgetIndex);
break;
case widx::railroad_menu:
railroad_menu_mouse_down(window, widgetIndex);
break;
case common::widx::port_menu:
port_menu_mouse_down(window, widgetIndex);
break;
case common::widx::build_vehicles_menu:
build_vehicles_menu_mouse_down(window, widgetIndex);
break;
case common::widx::vehicles_menu:
vehicles_menu_mouse_down(window, widgetIndex);
break;
case common::widx::stations_menu:
stations_menu_mouse_down(window, widgetIndex);
break;
default:
common::on_mouse_down(window, widgetIndex);
break;
}
}
static void on_dropdown(window* window, widget_index widgetIndex, int16_t itemIndex)
{
switch (widgetIndex)
{
case common::widx::loadsave_menu:
loadsave_menu_dropdown(window, widgetIndex, itemIndex);
break;
case common::widx::audio_menu:
audio_menu_dropdown(window, widgetIndex, itemIndex);
break;
case widx::railroad_menu:
railroad_menu_dropdown(window, widgetIndex, itemIndex);
break;
case common::widx::port_menu:
port_menu_dropdown(window, widgetIndex, itemIndex);
break;
case common::widx::build_vehicles_menu:
build_vehicles_menu_dropdown(window, widgetIndex, itemIndex);
break;
case common::widx::vehicles_menu:
vehicles_menu_dropdown(window, widgetIndex, itemIndex);
break;
case common::widx::stations_menu:
stations_menu_dropdown(window, widgetIndex, itemIndex);
break;
default:
common::on_dropdown(window, widgetIndex, itemIndex);
break;
}
}
// 0x00439DE4
static void draw(window* window, gfx::drawpixelinfo_t* dpi)
{
common::draw(window, dpi);
uint32_t company_colour = companymgr::get_player_company_colour();
if (window->widgets[widx::railroad_menu].type != widget_type::none)
{
uint32_t x = window->widgets[widx::railroad_menu].left + window->x;
uint32_t y = window->widgets[widx::railroad_menu].top + window->y;
uint32_t fg_image = 0;
// Figure out what icon to show on the button face.
uint8_t ebx = last_railroad_option;
if ((ebx & (1 << 7)) != 0)
{
ebx = ebx & ~(1 << 7);
auto obj = objectmgr::get<road_object>(ebx);
fg_image = gfx::recolour(obj->var_0E, company_colour);
}
else
{
auto obj = objectmgr::get<track_object>(ebx);
fg_image = gfx::recolour(obj->var_1E, company_colour);
}
auto interface = objectmgr::get<interface_skin_object>();
uint32_t bg_image = gfx::recolour(interface->img + interface_skin::image_ids::toolbar_empty_transparent, window->colours[2]);
y--;
if (input::is_dropdown_active(ui::WindowType::topToolbar, widx::railroad_menu))
{
y++;
bg_image++;
}
gfx::draw_image(dpi, x, y, fg_image);
y = window->widgets[widx::railroad_menu].top + window->y;
gfx::draw_image(dpi, x, y, bg_image);
}
{
uint32_t x = window->widgets[common::widx::vehicles_menu].left + window->x;
uint32_t y = window->widgets[common::widx::vehicles_menu].top + window->y;
static const uint32_t button_face_image_ids[] = {
interface_skin::image_ids::vehicle_train,
interface_skin::image_ids::vehicle_bus,
interface_skin::image_ids::vehicle_truck,
interface_skin::image_ids::vehicle_tram,
interface_skin::image_ids::vehicle_aircraft,
interface_skin::image_ids::vehicle_ship,
};
auto interface = objectmgr::get<interface_skin_object>();
uint32_t fg_image = gfx::recolour(interface->img + button_face_image_ids[last_vehicles_option], company_colour);
uint32_t bg_image = gfx::recolour(interface->img + interface_skin::image_ids::toolbar_empty_transparent, window->colours[3]);
y--;
if (input::is_dropdown_active(ui::WindowType::topToolbar, common::widx::vehicles_menu))
{
y++;
bg_image++;
}
gfx::draw_image(dpi, x, y, fg_image);
y = window->widgets[common::widx::vehicles_menu].top + window->y;
gfx::draw_image(dpi, x, y, bg_image);
}
{
uint32_t x = window->widgets[common::widx::build_vehicles_menu].left + window->x;
uint32_t y = window->widgets[common::widx::build_vehicles_menu].top + window->y;
static const uint32_t build_vehicle_images[] = {
interface_skin::image_ids::toolbar_build_vehicle_train,
interface_skin::image_ids::toolbar_build_vehicle_bus,
interface_skin::image_ids::toolbar_build_vehicle_truck,
interface_skin::image_ids::toolbar_build_vehicle_tram,
interface_skin::image_ids::toolbar_build_vehicle_airplane,
interface_skin::image_ids::toolbar_build_vehicle_boat,
};
// Figure out what icon to show on the button face.
auto interface = objectmgr::get<interface_skin_object>();
uint32_t fg_image = gfx::recolour(interface->img + build_vehicle_images[last_build_vehicles_option], company_colour);
if (input::is_dropdown_active(ui::WindowType::topToolbar, common::widx::build_vehicles_menu))
fg_image++;
gfx::draw_image(dpi, x, y, fg_image);
}
}
// 0x00439BCB
static void prepare_draw(window* window)
{
auto interface = objectmgr::get<interface_skin_object>();
if (!audio::isAudioEnabled())
{
window->activated_widgets |= (1 << common::widx::audio_menu);
window->widgets[common::widx::audio_menu].image = gfx::recolour(interface->img + interface_skin::image_ids::toolbar_audio_inactive, window->colours[0]);
}
else
{
window->activated_widgets &= ~(1 << common::widx::audio_menu);
window->widgets[common::widx::audio_menu].image = gfx::recolour(interface->img + interface_skin::image_ids::toolbar_audio_active, window->colours[0]);
}
if (last_port_option == 0 && addr<0x00525FAC, int8_t>() != -1 && addr<0x00525FAD, int8_t>() == -1)
last_port_option = 1;
window->widgets[common::widx::loadsave_menu].image = gfx::recolour(interface->img + interface_skin::image_ids::toolbar_loadsave, 0);
window->widgets[common::widx::zoom_menu].image = gfx::recolour(interface->img + interface_skin::image_ids::toolbar_zoom, 0);
window->widgets[common::widx::rotate_menu].image = gfx::recolour(interface->img + interface_skin::image_ids::toolbar_rotate, 0);
window->widgets[common::widx::view_menu].image = gfx::recolour(interface->img + interface_skin::image_ids::toolbar_view, 0);
window->widgets[common::widx::terraform_menu].image = gfx::recolour(interface->img + interface_skin::image_ids::toolbar_terraform, 0);
window->widgets[widx::railroad_menu].image = gfx::recolour(interface->img + interface_skin::image_ids::toolbar_empty_opaque, 0);
window->widgets[common::widx::road_menu].image = gfx::recolour(interface->img + interface_skin::image_ids::toolbar_empty_opaque, 0);
window->widgets[common::widx::port_menu].image = gfx::recolour(interface->img + interface_skin::image_ids::toolbar_empty_opaque, 0);
window->widgets[common::widx::build_vehicles_menu].image = gfx::recolour(interface->img + interface_skin::image_ids::toolbar_empty_opaque, 0);
window->widgets[common::widx::vehicles_menu].image = gfx::recolour(interface->img + interface_skin::image_ids::toolbar_empty_opaque, 0);
window->widgets[common::widx::stations_menu].image = gfx::recolour(interface->img + interface_skin::image_ids::toolbar_stations, 0);
if (last_town_option == 0)
window->widgets[common::widx::towns_menu].image = gfx::recolour(interface->img + interface_skin::image_ids::toolbar_towns, 0);
else
window->widgets[common::widx::towns_menu].image = gfx::recolour(interface->img + interface_skin::image_ids::toolbar_industries, 0);
if (last_port_option == 0)
window->widgets[common::widx::port_menu].image = gfx::recolour(interface->img + interface_skin::image_ids::toolbar_airports, 0);
else
window->widgets[common::widx::port_menu].image = gfx::recolour(interface->img + interface_skin::image_ids::toolbar_ports, 0);
if (last_road_option != 0xFF)
window->widgets[common::widx::road_menu].type = widget_type::wt_7;
else
window->widgets[common::widx::road_menu].type = widget_type::none;
if (last_railroad_option != 0xFF)
window->widgets[widx::railroad_menu].type = widget_type::wt_7;
else
window->widgets[widx::railroad_menu].type = widget_type::none;
if (addr<0x00525FAC, int8_t>() != -1 || addr<0x00525FAD, int8_t>() != -1)
window->widgets[common::widx::port_menu].type = widget_type::wt_7;
else
window->widgets[common::widx::port_menu].type = widget_type::none;
uint32_t x = std::max(640, ui::width()) - 1;
common::rightAlignTabs(window, x, { common::widx::towns_menu, common::widx::stations_menu, common::widx::vehicles_menu });
x -= 11;
common::rightAlignTabs(window, x, { common::widx::build_vehicles_menu });
if (window->widgets[common::widx::port_menu].type != widget_type::none)
{
common::rightAlignTabs(window, x, { common::widx::port_menu });
}
if (window->widgets[common::widx::road_menu].type != widget_type::none)
{
common::rightAlignTabs(window, x, { common::widx::road_menu });
}
if (window->widgets[widx::railroad_menu].type != widget_type::none)
{
common::rightAlignTabs(window, x, { widx::railroad_menu });
}
common::rightAlignTabs(window, x, { common::widx::terraform_menu });
}
}
| 39.582329
| 488
| 0.61641
|
panjacek
|
046d3311aa767e9e53653ce04fa6a436d9ef6525
| 11,248
|
hpp
|
C++
|
src/composable_kernel/composable_kernel/include/tensor_operation/reduction_functions_blockwise.hpp
|
j4yan/MIOpen
|
dc38f79bee97e047d866d9c1e25289cba86fab56
|
[
"MIT"
] | 745
|
2017-07-01T22:03:25.000Z
|
2022-03-26T23:46:27.000Z
|
src/composable_kernel/composable_kernel/include/tensor_operation/reduction_functions_blockwise.hpp
|
j4yan/MIOpen
|
dc38f79bee97e047d866d9c1e25289cba86fab56
|
[
"MIT"
] | 1,348
|
2017-07-02T12:37:48.000Z
|
2022-03-31T23:45:51.000Z
|
src/composable_kernel/composable_kernel/include/tensor_operation/reduction_functions_blockwise.hpp
|
j4yan/MIOpen
|
dc38f79bee97e047d866d9c1e25289cba86fab56
|
[
"MIT"
] | 158
|
2017-07-01T19:37:04.000Z
|
2022-03-30T11:57:04.000Z
|
/*******************************************************************************
*
* MIT License
*
* Copyright (c) 2020 Advanced Micro Devices, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*******************************************************************************/
#ifndef CK_REDUCTION_FUNCTIONS_BLOCKWISE_HPP
#define CK_REDUCTION_FUNCTIONS_BLOCKWISE_HPP
#include "data_type.hpp"
#include "reduction_common.hpp"
#include "reduction_operator.hpp"
#include "reduction_functions_binop.hpp"
namespace ck {
template <typename buffer2dDescType,
bool blockIsOneRow,
typename opReduce,
NanPropagation_t nanPropaOpt>
struct BlockwiseReduction_2d_block_buffer
{
using compType = typename opReduce::dataType;
static constexpr auto buffer2dDesc = buffer2dDescType{};
static constexpr index_t BlockSize =
blockIsOneRow ? buffer2dDesc.GetLength(Number<1>{}) : buffer2dDesc.GetLength(Number<0>{});
static constexpr index_t NumBlocks =
blockIsOneRow ? buffer2dDesc.GetLength(Number<0>{}) : buffer2dDesc.GetLength(Number<1>{});
using binop = detail::binop_with_nan_check<nanPropaOpt, opReduce, compType>;
// This interface does not accumulate on indices
template <typename BufferType>
__device__ static void
Reduce(BufferType& block_buffer, index_t toReduceBlocks, compType& accuData)
{
const index_t thread_local_id = get_thread_local_1d_id();
compType lAccuData = opReduce::GetReductionZeroVal();
index_t offset;
for(index_t otherDimInd = 0; otherDimInd < toReduceBlocks; otherDimInd++)
{
offset = blockIsOneRow
? buffer2dDesc.CalculateOffset(make_tuple(otherDimInd, thread_local_id))
: buffer2dDesc.CalculateOffset(make_tuple(thread_local_id, otherDimInd));
compType opData = type_convert<compType>{}(block_buffer[offset]);
binop::calculate(lAccuData, opData);
}
offset = blockIsOneRow ? buffer2dDesc.CalculateOffset(make_tuple(0, thread_local_id))
: buffer2dDesc.CalculateOffset(make_tuple(thread_local_id, 0));
block_buffer(offset) = lAccuData;
__syncthreads();
for(index_t indOffset = BlockSize / 2; indOffset > 0; indOffset /= 2)
{
if(thread_local_id < indOffset)
{
index_t offset1 =
blockIsOneRow ? buffer2dDesc.CalculateOffset(make_tuple(0, thread_local_id))
: buffer2dDesc.CalculateOffset(make_tuple(thread_local_id, 0));
index_t offset2 =
blockIsOneRow
? buffer2dDesc.CalculateOffset(make_tuple(0, thread_local_id + indOffset))
: buffer2dDesc.CalculateOffset(make_tuple(thread_local_id + indOffset, 0));
compType opData1 = type_convert<compType>{}(block_buffer[offset1]);
compType opData2 = type_convert<compType>{}(block_buffer[offset2]);
binop::calculate(opData1, opData2);
block_buffer(offset1) = type_convert<compType>{}(opData1);
}
__syncthreads();
}
if(thread_local_id == 0)
{
compType tmpVal = type_convert<compType>{}(block_buffer[0]);
binop::calculate(accuData, tmpVal);
}
};
// This interface accumulates on both data values and indices
template <typename BufferType, typename IdxBufferType>
__device__ static void Reduce2(BufferType& block_buffer,
IdxBufferType& block_indices_buffer,
index_t toReduceBlocks,
compType& accuData,
int& accuIndex)
{
const index_t thread_local_id = get_thread_local_1d_id();
compType lAccuData = opReduce::GetReductionZeroVal();
int lAccuIndex = 0;
if constexpr(blockIsOneRow)
{
for(index_t otherDimInd = 0; otherDimInd < toReduceBlocks; otherDimInd++)
{
for(index_t indOffset = 1; indOffset < BlockSize; indOffset *= 2)
{
if(thread_local_id % (indOffset * 2) == 0)
{
index_t offset1 =
buffer2dDesc.CalculateOffset(make_tuple(otherDimInd, thread_local_id));
index_t offset2 = buffer2dDesc.CalculateOffset(
make_tuple(otherDimInd, thread_local_id + indOffset));
compType currVal1 = type_convert<compType>{}(block_buffer[offset1]);
compType currVal2 = type_convert<compType>{}(block_buffer[offset2]);
int currIndex1 = block_indices_buffer[offset1];
int currIndex2 = block_indices_buffer[offset2];
binop::calculate(currVal1, currVal2, currIndex1, currIndex2);
block_buffer(offset1) = type_convert<compType>{}(currVal1);
block_indices_buffer(offset1) = currIndex1;
}
__syncthreads();
}
}
if(thread_local_id == 0)
{
for(index_t otherDimInd = 0; otherDimInd < toReduceBlocks; otherDimInd++)
{
index_t offset = buffer2dDesc.CalculateOffset(make_tuple(otherDimInd, 0));
compType tmpVal = type_convert<compType>{}(block_buffer[offset]);
int tmpIndex = block_indices_buffer[offset];
binop::calculate(lAccuData, tmpVal, lAccuIndex, tmpIndex);
}
binop::calculate(accuData, lAccuData, accuIndex, lAccuIndex);
}
}
else
{
index_t offset;
for(index_t otherDimInd = 0; otherDimInd < toReduceBlocks; otherDimInd++)
{
offset = buffer2dDesc.CalculateOffset(make_tuple(thread_local_id, otherDimInd));
compType currVal = type_convert<compType>{}(block_buffer[offset]);
int currIndex = block_indices_buffer[offset];
binop::calculate(lAccuData, currVal, lAccuIndex, currIndex);
}
offset = buffer2dDesc.CalculateOffset(make_tuple(thread_local_id, 0));
block_buffer(offset) = lAccuData;
block_indices_buffer(offset) = lAccuIndex;
__syncthreads();
for(index_t indOffset = 1; indOffset < BlockSize; indOffset *= 2)
{
if(thread_local_id % (indOffset * 2) == 0)
{
index_t offset1 = buffer2dDesc.CalculateOffset(make_tuple(thread_local_id, 0));
index_t offset2 =
buffer2dDesc.CalculateOffset(make_tuple(thread_local_id + indOffset, 0));
compType currVal1 = type_convert<compType>{}(block_buffer[offset1]);
compType currVal2 = type_convert<compType>{}(block_buffer[offset2]);
int currIndex1 = block_indices_buffer[offset1];
int currIndex2 = block_indices_buffer[offset2];
binop::calculate(currVal1, currVal2, currIndex1, currIndex2);
block_buffer(offset1) = type_convert<compType>{}(currVal1);
block_indices_buffer(offset1) = currIndex1;
}
__syncthreads();
}
if(thread_local_id == 0)
{
compType tmpVal = type_convert<compType>{}(block_buffer[0]);
int tmpIndex = block_indices_buffer[0];
binop::calculate(accuData, tmpVal, accuIndex, tmpIndex);
}
}
};
template <typename BufferType>
__device__ static void set_buffer_value(BufferType& block_buffer, compType value)
{
index_t thread_id = get_thread_local_1d_id();
for(index_t otherDimInd = 0; otherDimInd < NumBlocks; otherDimInd++)
{
index_t offset = blockIsOneRow
? buffer2dDesc.CalculateOffset(make_tuple(otherDimInd, thread_id))
: buffer2dDesc.CalculateOffset(make_tuple(thread_id, otherDimInd));
block_buffer(offset) = value;
__syncthreads();
}
};
// Initialize the block-wise indices buffer, the index for each element in the block-wise data
// buffer
// is calculated according to its position in the buffer and the global starting index
template <typename IdxBufferType>
__device__ static void init_buffer_indices(IdxBufferType& block_indices_buffer, int indexStart)
{
index_t thread_id = get_thread_local_1d_id();
for(index_t otherDimInd = 0; otherDimInd < NumBlocks; otherDimInd++)
{
index_t offset = blockIsOneRow
? buffer2dDesc.CalculateOffset(make_tuple(otherDimInd, thread_id))
: buffer2dDesc.CalculateOffset(make_tuple(thread_id, otherDimInd));
block_indices_buffer(offset) = offset + indexStart;
__syncthreads();
}
};
// Execute unary operation on the block buffer elements
template <typename unary_op_type, typename BufferType>
__device__ static void operate_on_elements(unary_op_type& unary_op, BufferType& block_buffer)
{
index_t thread_id = get_thread_local_1d_id();
for(index_t otherDimInd = 0; otherDimInd < NumBlocks; otherDimInd++)
{
index_t offset = blockIsOneRow
? buffer2dDesc.CalculateOffset(make_tuple(otherDimInd, thread_id))
: buffer2dDesc.CalculateOffset(make_tuple(thread_id, otherDimInd));
block_buffer(offset) = unary_op(block_buffer[offset]);
__syncthreads();
}
};
};
}; // end of namespace ck
#endif
| 41.352941
| 100
| 0.599129
|
j4yan
|
046e6e1f3f3a63e9acecf404a6c5c6029f6426bb
| 1,216
|
cpp
|
C++
|
D3D12Backend/APIWrappers/Resources/Textures/Views/RenderTargetView.cpp
|
bestdark/BoolkaEngine
|
35ae68dedb42baacb19908c0aaa047fe7f71f6b2
|
[
"MIT"
] | 27
|
2021-02-12T10:13:55.000Z
|
2022-03-24T14:44:06.000Z
|
D3D12Backend/APIWrappers/Resources/Textures/Views/RenderTargetView.cpp
|
bestdark/BoolkaEngine
|
35ae68dedb42baacb19908c0aaa047fe7f71f6b2
|
[
"MIT"
] | null | null | null |
D3D12Backend/APIWrappers/Resources/Textures/Views/RenderTargetView.cpp
|
bestdark/BoolkaEngine
|
35ae68dedb42baacb19908c0aaa047fe7f71f6b2
|
[
"MIT"
] | null | null | null |
#include "stdafx.h"
#include "RenderTargetView.h"
#include "APIWrappers/Device.h"
#include "APIWrappers/Resources/Textures/Texture2D.h"
namespace Boolka
{
RenderTargetView::RenderTargetView()
: m_CPUDescriptorHandle{}
{
}
RenderTargetView::~RenderTargetView()
{
BLK_ASSERT(m_CPUDescriptorHandle.ptr == 0);
}
bool RenderTargetView::Initialize(Device& device, Texture2D& texture, DXGI_FORMAT format,
D3D12_CPU_DESCRIPTOR_HANDLE destDescriptor)
{
BLK_ASSERT(m_CPUDescriptorHandle.ptr == 0);
D3D12_RENDER_TARGET_VIEW_DESC desc = {};
desc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D;
desc.Format = format;
device->CreateRenderTargetView(texture.Get(), &desc, destDescriptor);
m_CPUDescriptorHandle = destDescriptor;
return true;
}
void RenderTargetView::Unload()
{
BLK_ASSERT(m_CPUDescriptorHandle.ptr != 0);
m_CPUDescriptorHandle = {};
}
D3D12_CPU_DESCRIPTOR_HANDLE* RenderTargetView::GetCPUDescriptor()
{
BLK_ASSERT(m_CPUDescriptorHandle.ptr != 0);
return &m_CPUDescriptorHandle;
}
} // namespace Boolka
| 25.333333
| 93
| 0.664474
|
bestdark
|
047314440f2a7480aeb1f55845f90d8f53fb8cdd
| 13,432
|
hh
|
C++
|
include/tchecker/ts/builder.hh
|
karthik-314/PDTA_Reachability
|
86c380ed8558a40ae75d5634d68273902d59399d
|
[
"MIT"
] | 4
|
2019-04-09T16:28:45.000Z
|
2021-09-21T08:25:40.000Z
|
include/tchecker/ts/builder.hh
|
karthik-314/PDTA_Reachability
|
86c380ed8558a40ae75d5634d68273902d59399d
|
[
"MIT"
] | 8
|
2019-04-05T12:53:12.000Z
|
2019-06-22T05:49:31.000Z
|
include/tchecker/ts/builder.hh
|
karthik-314/PDTA_Reachability
|
86c380ed8558a40ae75d5634d68273902d59399d
|
[
"MIT"
] | 3
|
2019-04-01T21:23:51.000Z
|
2021-03-03T14:16:18.000Z
|
/*
* This file is a part of the TChecker project.
*
* See files AUTHORS and LICENSE for copyright details.
*
*/
#ifndef TCHECKER_TS_BUILDER_HH
#define TCHECKER_TS_BUILDER_HH
#include <tuple>
#include <type_traits>
#include "tchecker/basictypes.hh"
#include "tchecker/utils/iterator.hh"
/*!
\file builder.hh
\brief Transition system builder
*/
namespace tchecker {
namespace ts {
/*!
\class builder_t
\brief Build states and transitons of a transition system
\tparam TS : type of transition system (see tchecker::ts::ts_t)
\tparam ALLOCATOR : type of allocator (see tchecker::ts::allocator_t), should be garbage collected
*/
template <class TS, class ALLOCATOR>
class builder_t {
static_assert(std::is_base_of<typename TS::state_t, typename ALLOCATOR::state_t>::value, "");
static_assert(std::is_base_of<typename TS::transition_t, typename ALLOCATOR::transition_t>::value, "");
public:
/*!
\brief Type of pointer to state
*/
using state_ptr_t = typename ALLOCATOR::state_ptr_t;
/*!
\brief Type of pointer to transition
*/
using transition_ptr_t = typename ALLOCATOR::transition_ptr_t;
/*!
\brief Constructor
\param ts : a transition system
\param allocator : an allocator
\note this keeps a reference on ts and a reference on allocator
*/
builder_t(TS & ts, ALLOCATOR & allocator) : _ts(ts), _allocator(allocator)
{}
/*!
\brief Copy constructor
*/
builder_t(tchecker::ts::builder_t<TS, ALLOCATOR> const &) = default;
/*!
\brief Move constructor
*/
builder_t(tchecker::ts::builder_t<TS, ALLOCATOR> &&) = default;
/*!
\brief Destructor
*/
~builder_t() = default;
/*!
\brief Assignment operator
*/
tchecker::ts::builder_t<TS, ALLOCATOR> & operator= (tchecker::ts::builder_t<TS, ALLOCATOR> const &) = default;
/*!
\brief Move assignment operator
*/
tchecker::ts::builder_t<TS, ALLOCATOR> & operator= (tchecker::ts::builder_t<TS, ALLOCATOR> &&) = default;
/*!
\brief Compute initial state
\param v : initial iterator value from the transition system
\param sargs : parameters to ALLOCATOR::allocate_state()
\param targs : parameters to ALLOCATOR::allocate_transition()
\return a triple <state, transition, status> where state and transition are the initial state and transition
computed from v, and status is the tchecker::state_status_t status of state.
\note state points to nullptr if status != tchecker::STATE_OK
*/
template <class ... SARGS, class ... TARGS>
std::tuple<state_ptr_t, transition_ptr_t, tchecker::state_status_t>
initial_state(typename TS::initial_iterator_value_t const & v, std::tuple<SARGS...> && sargs, std::tuple<TARGS...> && targs)
{
state_ptr_t state = _allocator.construct_state(std::forward<std::tuple<SARGS...>>(sargs));
transition_ptr_t transition = _allocator.construct_transition(std::forward<std::tuple<TARGS...>>(targs));
tchecker::state_status_t status = _ts.initialize(*state, *transition, v);
return std::make_tuple((status == tchecker::STATE_OK ? state : state_ptr_t(nullptr)), transition, status);
}
/*!
\brief Compute next state
\param state : source state
\param v : outgoing iterator value from the transition system
\param sargs : parameters to ALLOCATOR::allocate_state()
\param targs : parameters to ALLOCATOR::allocate_transition()
\return a triple <next_state, transition, status> where next_state and transition are the next state
and the outgoing transition of state corresponding to v, and status is the tchecker::state_status_t
status of next_state.
\note next_state points to nullptr if status != tchecker::STATE_OK
*/
template <class ... SARGS, class ... TARGS>
std::tuple<state_ptr_t, transition_ptr_t, tchecker::state_status_t>
next_state(state_ptr_t & state,
typename TS::outgoing_edges_iterator_value_t const & v,
std::tuple<SARGS...> && sargs,
std::tuple<TARGS...> && targs)
{
state_ptr_t next_state = _allocator.construct_from_state(state, std::forward<std::tuple<SARGS...>>(sargs));
transition_ptr_t transition = _allocator.construct_transition(std::forward<std::tuple<TARGS...>>(targs));
tchecker::state_status_t status = _ts.next(*next_state, *transition, v);
return std::make_tuple((status == tchecker::STATE_OK ? next_state : state_ptr_t(nullptr)), transition, status);
}
protected:
TS & _ts; /*!< Transition system */
ALLOCATOR & _allocator; /*!< Allocator */
};
/*!
\class builder_ok_t
\brief Build states and transitions from a transition system skiping states which do not have status tchecker::STATE_OK
\param TS : type of transition system (see tchecker::ts::ts_t)
\tparam ALLOCATOR : type of allocator (see tchecker::ts::allocator_t), should be garbage collected
*/
template <class TS, class ALLOCATOR>
class builder_ok_t : private tchecker::ts::builder_t<TS, ALLOCATOR> {
public:
/*!
\brief Type of pointer to state
*/
using state_ptr_t = typename tchecker::ts::builder_t<TS, ALLOCATOR>::state_ptr_t;
/*!
\brief Type of pointer to transition
*/
using transition_ptr_t = typename tchecker::ts::builder_t<TS, ALLOCATOR>::transition_ptr_t;
/*!
\brief Constructors
*/
using tchecker::ts::builder_t<TS, ALLOCATOR>::builder_t;
/*!
\class iterator_t
\brief Iterator on pairs (state, transition)
\tparam TS_ITERATOR : iterator in TS
*/
template <class TS_ITERATOR>
class iterator_t {
public:
/*!
\brief Type of TS iterator
*/
using ts_iterator_t = TS_ITERATOR;
/*!
\brief Dereference type of TS iterator
*/
using ts_iterator_value_t = typename std::iterator_traits<ts_iterator_t>::value_type;
/*!
\brief Type of state/transition computing function
*/
using state_transition_computer_t
= std::function<std::tuple<state_ptr_t, transition_ptr_t, tchecker::state_status_t>(ts_iterator_value_t const &)>;
/*!
\brief Constructor
\param it : TS iterator, should provide method at_end()
\param computer : state/transition computing function
*/
iterator_t(TS_ITERATOR const & it, state_transition_computer_t computer)
: _it(it), _computer(std::move(computer))
{
skip_bad();
}
/*!
\brief Constructor
\param it : TS iterator, should provide nethod at_end()
\param computer : state/transition computing function
*/
iterator_t(TS_ITERATOR && it, state_transition_computer_t computer)
: _it(std::move(it)), _computer(std::move(computer))
{
skip_bad();
}
/*!
\brief Copy constructor
*/
iterator_t(tchecker::ts::builder_ok_t<TS, ALLOCATOR>::iterator_t<TS_ITERATOR> const &) = default;
/*!
\brief Move constructor
*/
iterator_t(tchecker::ts::builder_ok_t<TS, ALLOCATOR>::iterator_t<TS_ITERATOR> &&) = default;
/*!
\brief Destructor
*/
~iterator_t() = default;
/*!
\brief Assignment operator
*/
tchecker::ts::builder_ok_t<TS, ALLOCATOR>::iterator_t<TS_ITERATOR> &
operator= (tchecker::ts::builder_ok_t<TS, ALLOCATOR>::iterator_t<TS_ITERATOR> const &) = default;
/*!
\brief Move-assignment operator
*/
tchecker::ts::builder_ok_t<TS, ALLOCATOR>::iterator_t<TS_ITERATOR> &
operator= (tchecker::ts::builder_ok_t<TS, ALLOCATOR>::iterator_t<TS_ITERATOR> &&) = default;
/*!
\brief Equality predicate
\param it : an iterator
\return true if this and it are equal, false otherwise
*/
bool operator== (tchecker::ts::builder_ok_t<TS, ALLOCATOR>::iterator_t<TS_ITERATOR> const & it) const
{
return ((_it == it._it) && (_computer == it._computer));
}
/*!
\brief Disequality predicate
\param it : an iterator
\return false if this and it are equal, true otherwise
*/
inline bool operator!= (tchecker::ts::builder_ok_t<TS, ALLOCATOR>::iterator_t<TS_ITERATOR> const & it) const
{
return ! (*this == it);
}
/*!
\brief Accessor
\return true if this iterator is past-the-end, false otherwise
\note calling at_end() is more efficient than iterator comparison (i.e. == and !=)
*/
inline bool at_end() const
{
return _it.at_end();
}
/*!
\brief Increment operator
\pre not at_end() (checked by assertion)
\post either at_end() or the iterator points to the next valid (state, transition)
\return this after increment
*/
tchecker::ts::builder_ok_t<TS, ALLOCATOR>::iterator_t<TS_ITERATOR> & operator++ ()
{
assert( ! at_end() );
_current_state = nullptr;
_current_transition = nullptr;
++_it;
skip_bad();
return *this;
}
/*!
\brief Dereference operator
\pre not at_end() (checked by assertion)
\return pair (state, transition) pointed by this iterator
*/
std::tuple<state_ptr_t, transition_ptr_t> operator* () const
{
assert( ! at_end() );
return std::make_tuple(_current_state, _current_transition);
}
private:
/*!
\brief Skip states with bad status
\post either at_end() or _current_state is the next state with status tchecker::STATE_OK, and
_current_transition is the corresponding transition. _it has been moved to point to
(_current_state, _current_transition)
*/
void skip_bad()
{
tchecker::state_status_t status;
while (! _it.at_end()) {
std::tie(_current_state, _current_transition, status) = _computer(*_it);
if (status == tchecker::STATE_OK)
break;
++_it;
}
}
state_ptr_t _current_state; /*!< State pointed by iterator */
transition_ptr_t _current_transition; /*!< Transition pointed by iterator */
TS_ITERATOR _it; /*!< Iterator to curent position */
state_transition_computer_t _computer; /*!< State/transition computing function */
};
/*!
\brief Type of iterator over initial (state, transition)
*/
using initial_iterator_t = tchecker::ts::builder_ok_t<TS, ALLOCATOR>::iterator_t<typename TS::initial_iterator_t>;
/*!
\brief Accessor
\return range over initial (state, transition)
*/
tchecker::range_t<tchecker::ts::builder_ok_t<TS, ALLOCATOR>::initial_iterator_t> initial()
{
auto initial_range = tchecker::ts::builder_t<TS, ALLOCATOR>::_ts.initial();
auto computer = [&] (typename TS::initial_iterator_value_t const & v) {
return tchecker::ts::builder_t<TS, ALLOCATOR>::initial_state(v, std::make_tuple(), std::make_tuple());
};
return tchecker::make_range
(tchecker::ts::builder_ok_t<TS, ALLOCATOR>::initial_iterator_t(initial_range.begin(), computer),
tchecker::ts::builder_ok_t<TS, ALLOCATOR>::initial_iterator_t(initial_range.end(), computer));
}
/*!
\brief Type of iterator over outgoing (state, transition)
*/
using outgoing_iterator_t
= tchecker::ts::builder_ok_t<TS, ALLOCATOR>::iterator_t<typename TS::outgoing_edges_iterator_t>;
/*!
\brief Accessor
\param s : a state
\return range over outgoing (state, transition) of s
*/
tchecker::range_t<tchecker::ts::builder_ok_t<TS, ALLOCATOR>::outgoing_iterator_t> outgoing(state_ptr_t & s)
{
auto outgoing_range = tchecker::ts::builder_t<TS, ALLOCATOR>::_ts.outgoing_edges(*s);
auto computer = [&] (typename TS::outgoing_edges_iterator_value_t const & v) {
return tchecker::ts::builder_t<TS, ALLOCATOR>::next_state(s, v, std::make_tuple(), std::make_tuple());
};
return tchecker::make_range
(tchecker::ts::builder_ok_t<TS, ALLOCATOR>::outgoing_iterator_t(outgoing_range.begin(), computer),
tchecker::ts::builder_ok_t<TS, ALLOCATOR>::outgoing_iterator_t(outgoing_range.end(), computer));
}
};
} // end of namespace ts
} // end of namespace tchecker
#endif // TCHECKER_TS_BUILDER_HH
| 36.302703
| 130
| 0.604452
|
karthik-314
|
047525dc811a76475cbdfd147f6523cbcefe17e9
| 14,465
|
hpp
|
C++
|
src/Switch.System/include/Switch/System/Diagnostics/Stopwatch.hpp
|
victor-timoshin/Switch
|
8e8e687a8bdc4f79d482680da3968e9b3e464b8b
|
[
"MIT"
] | 4
|
2020-02-11T13:22:58.000Z
|
2022-02-24T00:37:43.000Z
|
src/Switch.System/include/Switch/System/Diagnostics/Stopwatch.hpp
|
sgf/Switch
|
8e8e687a8bdc4f79d482680da3968e9b3e464b8b
|
[
"MIT"
] | null | null | null |
src/Switch.System/include/Switch/System/Diagnostics/Stopwatch.hpp
|
sgf/Switch
|
8e8e687a8bdc4f79d482680da3968e9b3e464b8b
|
[
"MIT"
] | 2
|
2020-02-01T02:19:01.000Z
|
2021-12-30T06:44:00.000Z
|
/// @file
/// @brief Contains Switch::System::Diagnostics::Stopwatch class.
#pragma once
#include <Switch/Types.hpp>
#include <Switch/System/TimeSpan.hpp>
#include "../../SystemExport.hpp"
/// @brief The Switch namespace contains all fundamental classes to access Hardware, Os, System, and more.
namespace Switch {
/// @brief The System namespace contains fundamental classes and base classes that define commonly-used value and reference data types, events and event handlers, interfaces, attributes, and processing exceptions.
namespace System {
/// @brief The System::Diagnostics namespace provides classes that allow you to interact with system processes, event logs, and performance counters.
namespace Diagnostics {
/// @brief Provides a set of methods and properties that you can use to accurately measure elapsed time.
/// @par Library
/// Switch.System
/// @remarks A Stopwatch instance can measure elapsed time for one interval, or the total of elapsed time across multiple intervals. In a typical Stopwatch scenario, you call the Start method, then eventually call the Stop method, and then you check elapsed time using the Elapsed property.
/// @remarks A Stopwatch instance is either running or stopped; use IsRunning to determine the current state of a Stopwatch. Use Start to begin measuring elapsed time; use Stop to stop measuring elapsed time. Query the elapsed time value through the properties Elapsed, ElapsedMilliseconds, or ElapsedTicks. You can query the elapsed time properties while the instance is running or stopped. The elapsed time properties steadily increase while the Stopwatch is running; they remain constant when the instance is stopped.
/// @remarks By default, the elapsed time value of a Stopwatch instance equals the total of all measured time intervals. Each call to Start begins counting at the cumulative elapsed time; each call to Stop ends the current interval measurement and freezes the cumulative elapsed time value. Use the Reset method to clear the cumulative elapsed time in an existing Stopwatch instance.
/// @remarks The Stopwatch measures elapsed time by counting timer ticks in the underlying timer mechanism. If the installed hardware and operating system support a high-resolution performance counter, then the Stopwatch class uses that counter to measure elapsed time. Otherwise, the Stopwatch class uses the system timer to measure elapsed time. Use the Frequency and IsHighResolution fields to determine the precision and resolution of the Stopwatch timing implementation.
/// @remarks The Stopwatch class assists the manipulation of timing-related performance counters within managed code. Specifically, the Frequency field and GetTimestamp method can be used in place of the unmanaged Win32 APIs QueryPerformanceFrequency and QueryPerformanceCounter.
/// @par Examples
/// The following example demonstrates how to use the Stopwatch class to determine the execution time for an application.
/// @include Stopwatch.cpp
class system_export_ Stopwatch : public Object {
public:
/// @brief Gets the frequency of the timer as the number of ticks per second. This field is read-only.
/// @return The frequency of the timer as the number of ticks per second.
/// @remarks The timer frequency indicates the timer precision and resolution. For example, a timer frequency of 2 million ticks per second equals a timer resolution of 500 nanoseconds per tick. In other words, because one second equals 1 billion nanoseconds, a timer frequency of 2 million ticks per second is equivalent to 2 million ticks per 1 billion nanoseconds, which can be further simplified to 1 tick per 500 nanoseconds.
/// @remarks The Frequency value depends on the resolution of the underlying timing mechanism. If the installed hardware and operating system support a high-resolution performance counter, then the Frequency value reflects the frequency of that counter. Otherwise, the Frequency value is based on the system timer frequency.
/// @remarks Because the Stopwatch frequency depends on the installed hardware and operating system, the Frequency value remains constant while the system is running.
static property_<int64, readonly_> Frequency;
/// @brief Indicates whether the timer is based on a high-resolution performance counter. This field is read-only.
/// @return true if the timer is based on a high-resolution performance counte; otherwise, false.
/// @remarks The timer used by the Stopwatch class depends on the system hardware and operating system. IsHighResolution is true if the Stopwatch timer is based on a high-resolution performance counter. Otherwise, IsHighResolution is false, which indicates that the Stopwatch timer is based on the system timer.
static property_<bool, readonly_> IsHighResolution;
/// @brief Initializes a new instance of the Stopwatch class.
/// @remarks The returned Stopwatch instance is stopped, and the elapsed time property of the instance is zero.
/// @remarks Use the Start method to begin measuring elapsed time with the new Stopwatch instance. Use the StartNew method to initialize a new Stopwatch instance and immediately start it.
Stopwatch() = default;
/// @cond
Stopwatch(const Stopwatch& sw) : running(sw.running), start(sw.start), stop(sw.stop) {}
Stopwatch& operator =(const Stopwatch& sw) {
this->running = sw.running;
this->start = sw.start;
this->stop = sw.stop;
return *this;
}
/// @endcond
/// @brief Gets the total elapsed time measured by the current instance.
/// @return A TimeSpan representing the total elapsed time measured by the current instance.
/// @remarks In a typical Stopwatch scenario, you call the Start method, then eventually call the Stop method, and then you check elapsed time using the Elapsed property.
/// @remarks Use the Elapsed property to retrieve the elapsed time value using TimeSpan methods and properties. For example, you can format the returned TimeSpan instance into a text representation, or pass it to another class that requires a TimeSpan parameter.
/// @remarks You can query the properties Elapsed, ElapsedMilliseconds, and ElapsedTicks while the Stopwatch instance is running or stopped. The elapsed time properties steadily increase while the Stopwatch is running; they remain constant when the instance is stopped.
/// @remarks By default, the elapsed time value of a Stopwatch instance equals the total of all measured time intervals. Each call to Start begins counting at the cumulative elapsed time; each call to Stop ends the current interval measurement and freezes the cumulative elapsed time value. Use the Reset method to clear the cumulative elapsed time in an existing Stopwatch instance.
property_<TimeSpan, readonly_> Elapsed {
get_ {return TimeSpan::FromTicks(ElapsedTicks);}
};
/// @brief Gets the total elapsed time measured by the current instance, in milliseconds.
/// @return A long integer representing the total number of milliseconds measured by the current instance.
/// @remarks This property represents elapsed time rounded down to the nearest whole millisecond value. For higher precision measurements, use the Elapsed or ElapsedTicks properties.
/// @remarks You can query the properties Elapsed, ElapsedMilliseconds, and ElapsedTicks while the Stopwatch instance is running or stopped. The elapsed time properties steadily increase while the Stopwatch is running; they remain constant when the instance is stopped.
/// @remarks By default, the elapsed time value of a Stopwatch instance equals the total of all measured time intervals. Each call to Start begins counting at the cumulative elapsed time; each call to Stop ends the current interval measurement and freezes the cumulative elapsed time value. Use the Reset method to clear the cumulative elapsed time in an existing Stopwatch instance.
property_<int64, readonly_> ElapsedMilliseconds {
get_ {return this->GetElapsedTicks() / TimeSpan::TicksPerMillisecond;}
};
/// @brief Gets the total elapsed time measured by the current instance, in timer ticks.
/// @return A long integer representing the total number of timer ticks measured by the current instance.
/// @remarks This property represents the number of elapsed ticks in the underlying timer mechanism. A tick is the smallest unit of time that the Stopwatch timer can measure. Use the Frequency field to convert the ElapsedTicks value into a number of seconds.
/// @remarks You can query the properties Elapsed, ElapsedMilliseconds, and ElapsedTicks while the Stopwatch instance is running or stopped. The elapsed time properties steadily increase while the Stopwatch is running; they remain constant when the instance is stopped.
/// @remarks By default, the elapsed time value of a Stopwatch instance equals the total of all measured time intervals. Each call to Start begins counting at the cumulative elapsed time; each call to Stop ends the current interval measurement and freezes the cumulative elapsed time value. Use the Reset method to clear the cumulative elapsed time in an existing Stopwatch instance.
property_<int64, readonly_> ElapsedTicks {
get_ {return this->GetElapsedTicks();}
};
/// @brief Gets a value indicating whether the Stopwatch timer is running.
/// @return true if the Stopwatch instance is currently running and measuring elapsed time for an interval; otherwise, false.
/// @remarks A Stopwatch instance begins running with a call to Start or StartNew. The instance stops running with a call to Stop or Reset.
property_<bool, readonly_> IsRunning {
get_ {return this->running;}
};
/// @brief Gets the current number of ticks in the timer mechanism.
/// @return A long integer representing the tick counter value of the underlying timer mechanism.
/// @remarks If the Stopwatch class uses a high-resolution performance counter, GetTimestamp returns the current value of that counter. If the Stopwatch class uses the system timer, GetTimestamp returns the current DateTime.Ticks property of the DateTime.Now instance.
static int64 GetTimestamp();
/// @brief Stops time interval measurement and resets the elapsed time to zero.
/// @remarks A Stopwatch instance calculates and retains the cumulative elapsed time across multiple time intervals, until the instance is reset. Use Stop to stop the current interval measurement and retain the cumulative elapsed time value. Use Reset to stop any interval measurement in progress and clear the elapsed time value.
void Reset() {
this->start = this->stop = 0;
this->running = false;
}
/// @brief Stops time interval measurement, resets the elapsed time to zero, and starts measuring elapsed time.
/// @remarks A Stopwatch instance calculates and retains the cumulative elapsed time across multiple time intervals, until the instance is reset or restarted. Use Stop to stop the current interval measurement and retain the cumulative elapsed time value. Use Reset to stop any interval measurement in progress and clear the elapsed time value. Use Restart to stop current interval measurement and start a new interval measurement.
void Restart() {
this->Reset();
this->Start();
}
/// @brief Starts, or resumes, measuring elapsed time for an interval.
/// @remarks n a typical Stopwatch scenario, you call the Start method, then eventually call the Stop method, and then you check elapsed time using the Elapsed property.
/// @remarks Once started, a Stopwatch timer measures the current interval, in elapsed timer ticks, until the instance is stopped or reset. Starting a Stopwatch that is already running does not change the timer state or reset the elapsed time properties.
/// @remarks When a Stopwatch instance measures more than one interval, the Start method resumes measuring time from the current elapsed time value. A Stopwatch instance calculates and retains the cumulative elapsed time across multiple time intervals, until the instance is reset. Use the Reset method before calling Start to clear the cumulative elapsed time in a Stopwatch instance. Use the Restart method to Reset and Start the Stopwatch with a single command.
void Start() {
this->start = this->GetTimestamp() - (this->stop - this->start);
this->running = true;
}
/// @brief Initializes a new Stopwatch instance, sets the elapsed time property to zero, and starts measuring elapsed time.
/// @remarks This method is equivalent to calling the Stopwatch constructor and then calling Start on the new instance.
static Stopwatch StartNew() {return Stopwatch(true);}
/// @brief Stops measuring elapsed time for an interval.
/// @remarks In a typical Stopwatch scenario, you call the Start method, then eventually call the Stop method, and then you check elapsed time using the Elapsed property.
/// @remarks The Stop method ends the current time interval measurement. Stopping a Stopwatch that is not running does not change the timer state or reset the elapsed time properties.
/// @remarks When a Stopwatch instance measures more than one interval, the Stop method is equivalent to pausing the elapsed time measurement. A subsequent call to Start resumes measuring time from the current elapsed time value. Use the Reset method to clear the cumulative elapsed time in a Stopwatch instance.
void Stop() {
this->stop = this->GetTimestamp();
this->running = false;
}
private:
explicit Stopwatch(bool start) {
if (start)
Start();
}
int64 GetElapsedTicks() const {
if (this->running)
return this->GetTimestamp() - this->start;
return (this->stop - this->start);
}
bool running = false;
int64 start = 0;
int64 stop = 0;
};
}
}
}
using namespace Switch;
| 95.164474
| 526
| 0.742689
|
victor-timoshin
|
047550ae13bde11ae3025c41ea1b480d5f8d041a
| 224
|
cpp
|
C++
|
src/main.cpp
|
Alpha-Incorporated/Chatter-Box
|
96937353a75c2dcb8e89e99fb3d317211ff7e85c
|
[
"MIT"
] | 2
|
2020-02-21T04:24:21.000Z
|
2020-02-21T04:26:11.000Z
|
src/main.cpp
|
Alien-Inc/Chatter-Box
|
96937353a75c2dcb8e89e99fb3d317211ff7e85c
|
[
"MIT"
] | 2
|
2020-11-19T08:39:52.000Z
|
2020-11-19T08:50:19.000Z
|
src/main.cpp
|
Alpha-Incorporated/Chatter-Box
|
96937353a75c2dcb8e89e99fb3d317211ff7e85c
|
[
"MIT"
] | 1
|
2020-02-21T04:26:13.000Z
|
2020-02-21T04:26:13.000Z
|
#include <QApplication>
#include "gui.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
gui::welcome_dialog = new WelcomeDialog;
gui::welcome_dialog->show();
return a.exec();
}
| 17.230769
| 45
| 0.616071
|
Alpha-Incorporated
|
0476c180845ed58dc0a5a5faf59df7cea35fa20e
| 1,780
|
cpp
|
C++
|
src/altimeter.cpp
|
sawar7577/3d-flight-simulator
|
39735226fa4a8ed0c95e63be8c37ae49d156f1ba
|
[
"MIT"
] | null | null | null |
src/altimeter.cpp
|
sawar7577/3d-flight-simulator
|
39735226fa4a8ed0c95e63be8c37ae49d156f1ba
|
[
"MIT"
] | null | null | null |
src/altimeter.cpp
|
sawar7577/3d-flight-simulator
|
39735226fa4a8ed0c95e63be8c37ae49d156f1ba
|
[
"MIT"
] | null | null | null |
#include "main.h"
#include "altimeter.h"
Altimeter::Altimeter(float x, float y, float z) {
this->position = glm::vec3(x, y, z);
this->rotate = glm::mat4(1.0f);
GLfloat vertex_buffer_data[10001];
int j = 0;
// Altimeter
GLfloat *crosshar = Cuboid::CuboidArray(0.5f,0.5f,0.5f,0.5f,40.0f);
for(int i = 0 ; i < 6*6*3 ; ++i){
vertex_buffer_data[j++] = crosshar[i];
}
free(crosshar);
this->object = create3DObject(GL_TRIANGLES, j/3, vertex_buffer_data, COLOR_RED, GL_FILL);
crosshar = Cuboid::CuboidArray(2.0f,2.0f,2.0f,2.0f,0.5f);
j = 0;
for(int i = 0 ; i < 6*6*3 ; ++i) {
vertex_buffer_data[j++] = crosshar[i];
}
free(crosshar);
this->meter = create3DObject(GL_TRIANGLES, j/3, vertex_buffer_data, COLOR_RED, GL_FILL);
}
void Altimeter::draw(glm::mat4 VP) {
float top = screen_center_y + 30 / screen_zoom;
float bottom = screen_center_y - 30 / screen_zoom;
float left = screen_center_x - 30 / screen_zoom;
float right = screen_center_x + 30 / screen_zoom;
VP = glm::ortho(left, right, bottom, top, 0.0f, 500.0f);
Matrices.model = glm::mat4(1.0f);
glm::mat4 translate = glm::translate (this->position); // glTranslatef
Matrices.model = (translate * this->rotate);
glm::mat4 MVP = VP * Matrices.model;
glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]);
draw3DObject(this->object);
Matrices.model = glm::translate(this->meterposition) * Matrices.model;
MVP = VP * Matrices.model;
glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]);
draw3DObject(this->meter);
}
void Altimeter::changeHeight(Airplane &airp) {
this->meterposition = glm::vec3(0,-20+40*std::min((airp.position.y/1000.0f),1.0f),0);
}
| 36.326531
| 93
| 0.641011
|
sawar7577
|
047a3c395f7a7208df76da3ab7005ae6c3102fe0
| 15,823
|
cpp
|
C++
|
QueryEngine/WindowFunctionIR.cpp
|
sijialouintel/omniscidb
|
16c4e035a153cf0a88d04e1891c9f20b22c71963
|
[
"Apache-2.0"
] | 2
|
2020-03-04T12:01:10.000Z
|
2020-07-24T15:12:55.000Z
|
QueryEngine/WindowFunctionIR.cpp
|
sijialouintel/omniscidb
|
16c4e035a153cf0a88d04e1891c9f20b22c71963
|
[
"Apache-2.0"
] | 31
|
2021-06-22T07:52:23.000Z
|
2022-02-08T00:00:09.000Z
|
QueryEngine/WindowFunctionIR.cpp
|
vishalbelsare/mapd-core
|
16c4e035a153cf0a88d04e1891c9f20b22c71963
|
[
"Apache-2.0"
] | 10
|
2021-05-31T08:44:38.000Z
|
2022-01-27T08:24:50.000Z
|
/*
* Copyright 2018 OmniSci, 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 "CodeGenerator.h"
#include "Execute.h"
#include "WindowContext.h"
llvm::Value* Executor::codegenWindowFunction(const size_t target_index,
const CompilationOptions& co) {
AUTOMATIC_IR_METADATA(cgen_state_.get());
CodeGenerator code_generator(this);
const auto window_func_context =
WindowProjectNodeContext::get(this)->activateWindowFunctionContext(this,
target_index);
const auto window_func = window_func_context->getWindowFunction();
switch (window_func->getKind()) {
case SqlWindowFunctionKind::ROW_NUMBER:
case SqlWindowFunctionKind::RANK:
case SqlWindowFunctionKind::DENSE_RANK:
case SqlWindowFunctionKind::NTILE: {
return cgen_state_->emitCall("row_number_window_func",
{cgen_state_->llInt(reinterpret_cast<const int64_t>(
window_func_context->output())),
code_generator.posArg(nullptr)});
}
case SqlWindowFunctionKind::PERCENT_RANK:
case SqlWindowFunctionKind::CUME_DIST: {
return cgen_state_->emitCall("percent_window_func",
{cgen_state_->llInt(reinterpret_cast<const int64_t>(
window_func_context->output())),
code_generator.posArg(nullptr)});
}
case SqlWindowFunctionKind::LAG:
case SqlWindowFunctionKind::LEAD:
case SqlWindowFunctionKind::FIRST_VALUE:
case SqlWindowFunctionKind::LAST_VALUE: {
CHECK(WindowProjectNodeContext::get(this));
const auto& args = window_func->getArgs();
CHECK(!args.empty());
const auto arg_lvs = code_generator.codegen(args.front().get(), true, co);
CHECK_EQ(arg_lvs.size(), size_t(1));
return arg_lvs.front();
}
case SqlWindowFunctionKind::AVG:
case SqlWindowFunctionKind::MIN:
case SqlWindowFunctionKind::MAX:
case SqlWindowFunctionKind::SUM:
case SqlWindowFunctionKind::COUNT: {
return codegenWindowFunctionAggregate(co);
}
default: {
LOG(FATAL) << "Invalid window function kind";
}
}
return nullptr;
}
namespace {
std::string get_window_agg_name(const SqlWindowFunctionKind kind,
const SQLTypeInfo& window_func_ti) {
std::string agg_name;
switch (kind) {
case SqlWindowFunctionKind::MIN: {
agg_name = "agg_min";
break;
}
case SqlWindowFunctionKind::MAX: {
agg_name = "agg_max";
break;
}
case SqlWindowFunctionKind::AVG:
case SqlWindowFunctionKind::SUM: {
agg_name = "agg_sum";
break;
}
case SqlWindowFunctionKind::COUNT: {
agg_name = "agg_count";
break;
}
default: {
LOG(FATAL) << "Invalid window function kind";
}
}
switch (window_func_ti.get_type()) {
case kFLOAT: {
agg_name += "_float";
break;
}
case kDOUBLE: {
agg_name += "_double";
break;
}
default: {
break;
}
}
return agg_name;
}
SQLTypeInfo get_adjusted_window_type_info(const Analyzer::WindowFunction* window_func) {
const auto& args = window_func->getArgs();
return ((window_func->getKind() == SqlWindowFunctionKind::COUNT && !args.empty()) ||
window_func->getKind() == SqlWindowFunctionKind::AVG)
? args.front()->get_type_info()
: window_func->get_type_info();
}
} // namespace
llvm::Value* Executor::aggregateWindowStatePtr() {
AUTOMATIC_IR_METADATA(cgen_state_.get());
const auto window_func_context =
WindowProjectNodeContext::getActiveWindowFunctionContext(this);
const auto window_func = window_func_context->getWindowFunction();
const auto arg_ti = get_adjusted_window_type_info(window_func);
llvm::Type* aggregate_state_type =
arg_ti.get_type() == kFLOAT
? llvm::PointerType::get(get_int_type(32, cgen_state_->context_), 0)
: llvm::PointerType::get(get_int_type(64, cgen_state_->context_), 0);
const auto aggregate_state_i64 = cgen_state_->llInt(
reinterpret_cast<const int64_t>(window_func_context->aggregateState()));
return cgen_state_->ir_builder_.CreateIntToPtr(aggregate_state_i64,
aggregate_state_type);
}
llvm::Value* Executor::codegenWindowFunctionAggregate(const CompilationOptions& co) {
AUTOMATIC_IR_METADATA(cgen_state_.get());
const auto reset_state_false_bb = codegenWindowResetStateControlFlow();
auto aggregate_state = aggregateWindowStatePtr();
llvm::Value* aggregate_state_count = nullptr;
const auto window_func_context =
WindowProjectNodeContext::getActiveWindowFunctionContext(this);
const auto window_func = window_func_context->getWindowFunction();
if (window_func->getKind() == SqlWindowFunctionKind::AVG) {
const auto aggregate_state_count_i64 = cgen_state_->llInt(
reinterpret_cast<const int64_t>(window_func_context->aggregateStateCount()));
const auto pi64_type =
llvm::PointerType::get(get_int_type(64, cgen_state_->context_), 0);
aggregate_state_count =
cgen_state_->ir_builder_.CreateIntToPtr(aggregate_state_count_i64, pi64_type);
}
codegenWindowFunctionStateInit(aggregate_state);
if (window_func->getKind() == SqlWindowFunctionKind::AVG) {
const auto count_zero = cgen_state_->llInt(int64_t(0));
cgen_state_->emitCall("agg_id", {aggregate_state_count, count_zero});
}
cgen_state_->ir_builder_.CreateBr(reset_state_false_bb);
cgen_state_->ir_builder_.SetInsertPoint(reset_state_false_bb);
CHECK(WindowProjectNodeContext::get(this));
return codegenWindowFunctionAggregateCalls(aggregate_state, co);
}
llvm::BasicBlock* Executor::codegenWindowResetStateControlFlow() {
AUTOMATIC_IR_METADATA(cgen_state_.get());
const auto window_func_context =
WindowProjectNodeContext::getActiveWindowFunctionContext(this);
const auto bitset = cgen_state_->llInt(
reinterpret_cast<const int64_t>(window_func_context->partitionStart()));
const auto min_val = cgen_state_->llInt(int64_t(0));
const auto max_val = cgen_state_->llInt(window_func_context->elementCount() - 1);
const auto null_val = cgen_state_->llInt(inline_int_null_value<int64_t>());
const auto null_bool_val = cgen_state_->llInt<int8_t>(inline_int_null_value<int8_t>());
CodeGenerator code_generator(this);
const auto reset_state =
code_generator.toBool(cgen_state_->emitCall("bit_is_set",
{bitset,
code_generator.posArg(nullptr),
min_val,
max_val,
null_val,
null_bool_val}));
const auto reset_state_true_bb = llvm::BasicBlock::Create(
cgen_state_->context_, "reset_state.true", cgen_state_->current_func_);
const auto reset_state_false_bb = llvm::BasicBlock::Create(
cgen_state_->context_, "reset_state.false", cgen_state_->current_func_);
cgen_state_->ir_builder_.CreateCondBr(
reset_state, reset_state_true_bb, reset_state_false_bb);
cgen_state_->ir_builder_.SetInsertPoint(reset_state_true_bb);
return reset_state_false_bb;
}
void Executor::codegenWindowFunctionStateInit(llvm::Value* aggregate_state) {
AUTOMATIC_IR_METADATA(cgen_state_.get());
const auto window_func_context =
WindowProjectNodeContext::getActiveWindowFunctionContext(this);
const auto window_func = window_func_context->getWindowFunction();
const auto window_func_ti = get_adjusted_window_type_info(window_func);
const auto window_func_null_val =
window_func_ti.is_fp()
? cgen_state_->inlineFpNull(window_func_ti)
: cgen_state_->castToTypeIn(cgen_state_->inlineIntNull(window_func_ti), 64);
llvm::Value* window_func_init_val;
if (window_func_context->getWindowFunction()->getKind() ==
SqlWindowFunctionKind::COUNT) {
switch (window_func_ti.get_type()) {
case kFLOAT: {
window_func_init_val = cgen_state_->llFp(float(0));
break;
}
case kDOUBLE: {
window_func_init_val = cgen_state_->llFp(double(0));
break;
}
default: {
window_func_init_val = cgen_state_->llInt(int64_t(0));
break;
}
}
} else {
window_func_init_val = window_func_null_val;
}
const auto pi32_type =
llvm::PointerType::get(get_int_type(32, cgen_state_->context_), 0);
switch (window_func_ti.get_type()) {
case kDOUBLE: {
cgen_state_->emitCall("agg_id_double", {aggregate_state, window_func_init_val});
break;
}
case kFLOAT: {
aggregate_state =
cgen_state_->ir_builder_.CreateBitCast(aggregate_state, pi32_type);
cgen_state_->emitCall("agg_id_float", {aggregate_state, window_func_init_val});
break;
}
default: {
cgen_state_->emitCall("agg_id", {aggregate_state, window_func_init_val});
break;
}
}
}
llvm::Value* Executor::codegenWindowFunctionAggregateCalls(llvm::Value* aggregate_state,
const CompilationOptions& co) {
AUTOMATIC_IR_METADATA(cgen_state_.get());
const auto window_func_context =
WindowProjectNodeContext::getActiveWindowFunctionContext(this);
const auto window_func = window_func_context->getWindowFunction();
const auto window_func_ti = get_adjusted_window_type_info(window_func);
const auto window_func_null_val =
window_func_ti.is_fp()
? cgen_state_->inlineFpNull(window_func_ti)
: cgen_state_->castToTypeIn(cgen_state_->inlineIntNull(window_func_ti), 64);
const auto& args = window_func->getArgs();
llvm::Value* crt_val;
if (args.empty()) {
CHECK(window_func->getKind() == SqlWindowFunctionKind::COUNT);
crt_val = cgen_state_->llInt(int64_t(1));
} else {
CodeGenerator code_generator(this);
const auto arg_lvs = code_generator.codegen(args.front().get(), true, co);
CHECK_EQ(arg_lvs.size(), size_t(1));
if (window_func->getKind() == SqlWindowFunctionKind::SUM && !window_func_ti.is_fp()) {
crt_val = code_generator.codegenCastBetweenIntTypes(
arg_lvs.front(), args.front()->get_type_info(), window_func_ti, false);
} else {
crt_val = window_func_ti.get_type() == kFLOAT
? arg_lvs.front()
: cgen_state_->castToTypeIn(arg_lvs.front(), 64);
}
}
const auto agg_name = get_window_agg_name(window_func->getKind(), window_func_ti);
llvm::Value* multiplicity_lv = nullptr;
if (args.empty()) {
cgen_state_->emitCall(agg_name, {aggregate_state, crt_val});
} else {
cgen_state_->emitCall(agg_name + "_skip_val",
{aggregate_state, crt_val, window_func_null_val});
}
if (window_func->getKind() == SqlWindowFunctionKind::AVG) {
codegenWindowAvgEpilogue(crt_val, window_func_null_val, multiplicity_lv);
}
return codegenAggregateWindowState();
}
void Executor::codegenWindowAvgEpilogue(llvm::Value* crt_val,
llvm::Value* window_func_null_val,
llvm::Value* multiplicity_lv) {
AUTOMATIC_IR_METADATA(cgen_state_.get());
const auto window_func_context =
WindowProjectNodeContext::getActiveWindowFunctionContext(this);
const auto window_func = window_func_context->getWindowFunction();
const auto window_func_ti = get_adjusted_window_type_info(window_func);
const auto pi32_type =
llvm::PointerType::get(get_int_type(32, cgen_state_->context_), 0);
const auto pi64_type =
llvm::PointerType::get(get_int_type(64, cgen_state_->context_), 0);
const auto aggregate_state_type =
window_func_ti.get_type() == kFLOAT ? pi32_type : pi64_type;
const auto aggregate_state_count_i64 = cgen_state_->llInt(
reinterpret_cast<const int64_t>(window_func_context->aggregateStateCount()));
auto aggregate_state_count = cgen_state_->ir_builder_.CreateIntToPtr(
aggregate_state_count_i64, aggregate_state_type);
std::string agg_count_func_name = "agg_count";
switch (window_func_ti.get_type()) {
case kFLOAT: {
agg_count_func_name += "_float";
break;
}
case kDOUBLE: {
agg_count_func_name += "_double";
break;
}
default: {
break;
}
}
agg_count_func_name += "_skip_val";
cgen_state_->emitCall(agg_count_func_name,
{aggregate_state_count, crt_val, window_func_null_val});
}
llvm::Value* Executor::codegenAggregateWindowState() {
AUTOMATIC_IR_METADATA(cgen_state_.get());
const auto pi32_type =
llvm::PointerType::get(get_int_type(32, cgen_state_->context_), 0);
const auto pi64_type =
llvm::PointerType::get(get_int_type(64, cgen_state_->context_), 0);
const auto window_func_context =
WindowProjectNodeContext::getActiveWindowFunctionContext(this);
const Analyzer::WindowFunction* window_func = window_func_context->getWindowFunction();
const auto window_func_ti = get_adjusted_window_type_info(window_func);
const auto aggregate_state_type =
window_func_ti.get_type() == kFLOAT ? pi32_type : pi64_type;
auto aggregate_state = aggregateWindowStatePtr();
if (window_func->getKind() == SqlWindowFunctionKind::AVG) {
const auto aggregate_state_count_i64 = cgen_state_->llInt(
reinterpret_cast<const int64_t>(window_func_context->aggregateStateCount()));
auto aggregate_state_count = cgen_state_->ir_builder_.CreateIntToPtr(
aggregate_state_count_i64, aggregate_state_type);
const auto double_null_lv = cgen_state_->inlineFpNull(SQLTypeInfo(kDOUBLE));
switch (window_func_ti.get_type()) {
case kFLOAT: {
return cgen_state_->emitCall(
"load_avg_float", {aggregate_state, aggregate_state_count, double_null_lv});
}
case kDOUBLE: {
return cgen_state_->emitCall(
"load_avg_double", {aggregate_state, aggregate_state_count, double_null_lv});
}
case kDECIMAL: {
return cgen_state_->emitCall(
"load_avg_decimal",
{aggregate_state,
aggregate_state_count,
double_null_lv,
cgen_state_->llInt<int32_t>(window_func_ti.get_scale())});
}
default: {
return cgen_state_->emitCall(
"load_avg_int", {aggregate_state, aggregate_state_count, double_null_lv});
}
}
}
if (window_func->getKind() == SqlWindowFunctionKind::COUNT) {
return cgen_state_->ir_builder_.CreateLoad(
aggregate_state->getType()->getPointerElementType(), aggregate_state);
}
switch (window_func_ti.get_type()) {
case kFLOAT: {
return cgen_state_->emitCall("load_float", {aggregate_state});
}
case kDOUBLE: {
return cgen_state_->emitCall("load_double", {aggregate_state});
}
default: {
return cgen_state_->ir_builder_.CreateLoad(
aggregate_state->getType()->getPointerElementType(), aggregate_state);
}
}
}
| 41.098701
| 90
| 0.681097
|
sijialouintel
|
047ab81c66b36ba813285eac60e2c745033afcd9
| 1,666
|
hpp
|
C++
|
EndGame/Sandbox/SandboxApp.hpp
|
siddharthgarg4/EndGame
|
ba608714b3eacb5dc05d0c852db573231c867d8b
|
[
"MIT"
] | null | null | null |
EndGame/Sandbox/SandboxApp.hpp
|
siddharthgarg4/EndGame
|
ba608714b3eacb5dc05d0c852db573231c867d8b
|
[
"MIT"
] | null | null | null |
EndGame/Sandbox/SandboxApp.hpp
|
siddharthgarg4/EndGame
|
ba608714b3eacb5dc05d0c852db573231c867d8b
|
[
"MIT"
] | null | null | null |
//
// SandboxApp.hpp
// EndGame
//
// Created by Siddharth on 24/05/20.
// Copyright © 2020 Siddharth. All rights reserved.
//
#ifndef SandboxApp_hpp
#define SandboxApp_hpp
#include <glm/glm.hpp>
#include <EndGame/EndGame.h>
//need to include main only once thus user needs to include it
#include <EndGame/Src/EntryPoint.hpp>
#include <Sandbox/Sandbox2D.hpp>
#include <Sandbox/PacMan/PacManLayer.hpp>
class ExampleLayer : public EndGame::Layer {
public:
ExampleLayer();
void onUpdate(const float &timeSinceStart, const float &dtime) override;
void onRender(const float &alpha, const float &dtime) override;
void onEvent(EndGame::Event &event) override;
void onImguiRender() override;
private:
//rendering objects
EndGame::ShaderLibrary shaderLib;
std::shared_ptr<EndGame::VertexArray> vertexArray;
std::shared_ptr<EndGame::VertexArray> flatColorVertexArray;
EndGame::OrthographicCameraController cameraController;
std::shared_ptr<EndGame::Texture2D> texture;
std::shared_ptr<EndGame::Texture2D> semiTexture;
//event objects
glm::vec3 flatColor = {0.2f, 0.3f, 0.8f};
};
class Sandbox : public EndGame::Application {
public:
Sandbox(bool shouldAddDebugOverlay) : Application(shouldAddDebugOverlay, PacManLayer::pacManWindowTitle,
PacManLayer::pacManWindowWidth, PacManLayer::pacManWindowHeight) {
pushLayer(new PacManLayer());
}
~Sandbox() {}
};
//custom run the application as per the client
EndGame::Application *EndGame::createApplication() {
return new Sandbox(false);
}
#endif
| 32.038462
| 113
| 0.696279
|
siddharthgarg4
|
047bcb0793148ec658598270e5e37c64aa65e729
| 4,018
|
hpp
|
C++
|
src/graphlab/util/lock_free_pool.hpp
|
coreyp1/graphlab
|
637be90021c5f83ab7833ca15c48e76039057969
|
[
"ECL-2.0",
"Apache-2.0"
] | 333
|
2016-07-29T19:22:07.000Z
|
2022-03-30T02:40:34.000Z
|
src/graphlab/util/lock_free_pool.hpp
|
HybridGraph/GraphLab-PowerGraph
|
ba333c1cd82325ab2bfc6dd7ebb871b3fff64a94
|
[
"ECL-2.0",
"Apache-2.0"
] | 17
|
2016-09-15T00:31:59.000Z
|
2022-02-08T07:51:07.000Z
|
src/graphlab/util/lock_free_pool.hpp
|
HybridGraph/GraphLab-PowerGraph
|
ba333c1cd82325ab2bfc6dd7ebb871b3fff64a94
|
[
"ECL-2.0",
"Apache-2.0"
] | 163
|
2016-07-29T19:22:11.000Z
|
2022-03-07T07:15:24.000Z
|
/*
* Copyright (c) 2009 Carnegie Mellon University.
* All rights reserved.
*
* 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.
*
* For more about this software visit:
*
* http://www.graphlab.ml.cmu.edu
*
*/
#ifndef LOCK_FREE_POOL_HPP
#define LOCK_FREE_POOL_HPP
#include <stdint.h>
#include <vector>
#include <graphlab/logger/assertions.hpp>
#include <graphlab/parallel/atomic.hpp>
#include <graphlab/util/lock_free_internal.hpp>
#include <graphlab/util/branch_hints.hpp>
namespace graphlab {
template <typename T, typename index_type = uint32_t>
class lock_free_pool{
private:
std::vector<T> data;
T* lower_ptrlimit;
T* upper_ptrlimit;
// freelist[i] points to the next free list element
// if freelist[i] == index_type(-1), then it is the last element
// allocated entries are set to index_type(0), though
// note that there is no way to disambiguate between allocated
// and non-allocated entries by simply looking at the freelist
std::vector<index_type> freelist;
typedef lock_free_internal::reference_with_counter<index_type> queue_ref_type;
volatile queue_ref_type freelisthead;
public:
lock_free_pool(size_t poolsize = 0) { reset_pool(poolsize); }
void reset_pool(size_t poolsize) {
if (poolsize == 0) {
data.clear();
freelist.clear();
lower_ptrlimit = NULL;
upper_ptrlimit = NULL;
} else {
data.resize(poolsize);
freelist.resize(poolsize);
for (index_type i = 0;i < freelist.size(); ++i) {
freelist[i] = i + 1;
}
freelist[freelist.size() - 1] = index_type(-1);
lower_ptrlimit = &(data[0]);
upper_ptrlimit = &(data[data.size() - 1]);
}
freelisthead.q.val = 0;
freelisthead.q.counter = 0;
}
std::vector<T>& unsafe_get_pool_ref() { return data; }
T* alloc() {
// I need to atomically advance freelisthead to the freelist[head]
queue_ref_type oldhead;
queue_ref_type newhead;
do {
oldhead.combined = freelisthead.combined;
if (oldhead.q.val == index_type(-1)) return new T; // ran out of pool elements
newhead.q.val = freelist[oldhead.q.val];
newhead.q.counter = oldhead.q.counter + 1;
} while(!atomic_compare_and_swap(freelisthead.combined,
oldhead.combined,
newhead.combined));
freelist[oldhead.q.val] = index_type(-1);
return &(data[oldhead.q.val]);
}
void free(T* p) {
// is this from the pool?
// if it is below the pointer limits
if (__unlikely__(p < lower_ptrlimit || p > upper_ptrlimit)) {
delete p;
return;
}
index_type cur = index_type(p - &(data[0]));
// prepare for free list insertion
// I need to atomically set freelisthead == cur
// and freelist[cur] = freelisthead
queue_ref_type oldhead;
queue_ref_type newhead;
do{
oldhead.combined = freelisthead.combined;
freelist[cur] = oldhead.q.val;
newhead.q.val = cur;
newhead.q.counter = oldhead.q.counter + 1;
// now try to atomically move freelisthead
} while(!atomic_compare_and_swap(freelisthead.combined,
oldhead.combined,
newhead.combined));
}
}; // end of lock free pool
}; // end of graphlab namespace
#endif
| 33.483333
| 86
| 0.628422
|
coreyp1
|
0484162d5f8c7ac8563971f4cf1436e0727e09cd
| 3,386
|
cc
|
C++
|
src/reader/wgsl/parser_impl_unary_expression_test.cc
|
dorba/tint
|
f81c1081ea7d27ea55f373c0bfaf651e491da7e6
|
[
"Apache-2.0"
] | null | null | null |
src/reader/wgsl/parser_impl_unary_expression_test.cc
|
dorba/tint
|
f81c1081ea7d27ea55f373c0bfaf651e491da7e6
|
[
"Apache-2.0"
] | null | null | null |
src/reader/wgsl/parser_impl_unary_expression_test.cc
|
dorba/tint
|
f81c1081ea7d27ea55f373c0bfaf651e491da7e6
|
[
"Apache-2.0"
] | null | null | null |
// Copyright 2020 The Tint Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "gtest/gtest.h"
#include "src/ast/array_accessor_expression.h"
#include "src/ast/identifier_expression.h"
#include "src/ast/scalar_constructor_expression.h"
#include "src/ast/sint_literal.h"
#include "src/ast/unary_op_expression.h"
#include "src/reader/wgsl/parser_impl.h"
#include "src/reader/wgsl/parser_impl_test_helper.h"
namespace tint {
namespace reader {
namespace wgsl {
namespace {
TEST_F(ParserImplTest, UnaryExpression_Postix) {
auto* p = parser("a[2]");
auto e = p->unary_expression();
ASSERT_FALSE(p->has_error()) << p->error();
ASSERT_NE(e, nullptr);
ASSERT_TRUE(e->IsArrayAccessor());
auto* ary = e->AsArrayAccessor();
ASSERT_TRUE(ary->array()->IsIdentifier());
auto* ident = ary->array()->AsIdentifier();
EXPECT_EQ(ident->name(), "a");
ASSERT_TRUE(ary->idx_expr()->IsConstructor());
ASSERT_TRUE(ary->idx_expr()->AsConstructor()->IsScalarConstructor());
auto* init = ary->idx_expr()->AsConstructor()->AsScalarConstructor();
ASSERT_TRUE(init->literal()->IsSint());
ASSERT_EQ(init->literal()->AsSint()->value(), 2);
}
TEST_F(ParserImplTest, UnaryExpression_Minus) {
auto* p = parser("- 1");
auto e = p->unary_expression();
ASSERT_FALSE(p->has_error()) << p->error();
ASSERT_NE(e, nullptr);
ASSERT_TRUE(e->IsUnaryOp());
auto* u = e->AsUnaryOp();
ASSERT_EQ(u->op(), ast::UnaryOp::kNegation);
ASSERT_TRUE(u->expr()->IsConstructor());
ASSERT_TRUE(u->expr()->AsConstructor()->IsScalarConstructor());
auto* init = u->expr()->AsConstructor()->AsScalarConstructor();
ASSERT_TRUE(init->literal()->IsSint());
EXPECT_EQ(init->literal()->AsSint()->value(), 1);
}
TEST_F(ParserImplTest, UnaryExpression_Minus_InvalidRHS) {
auto* p = parser("-if(a) {}");
auto e = p->unary_expression();
ASSERT_TRUE(p->has_error());
ASSERT_EQ(e, nullptr);
EXPECT_EQ(p->error(), "1:2: unable to parse right side of - expression");
}
TEST_F(ParserImplTest, UnaryExpression_Bang) {
auto* p = parser("!1");
auto e = p->unary_expression();
ASSERT_FALSE(p->has_error()) << p->error();
ASSERT_NE(e, nullptr);
ASSERT_TRUE(e->IsUnaryOp());
auto* u = e->AsUnaryOp();
ASSERT_EQ(u->op(), ast::UnaryOp::kNot);
ASSERT_TRUE(u->expr()->IsConstructor());
ASSERT_TRUE(u->expr()->AsConstructor()->IsScalarConstructor());
auto* init = u->expr()->AsConstructor()->AsScalarConstructor();
ASSERT_TRUE(init->literal()->IsSint());
EXPECT_EQ(init->literal()->AsSint()->value(), 1);
}
TEST_F(ParserImplTest, UnaryExpression_Bang_InvalidRHS) {
auto* p = parser("!if (a) {}");
auto e = p->unary_expression();
ASSERT_TRUE(p->has_error());
ASSERT_EQ(e, nullptr);
EXPECT_EQ(p->error(), "1:2: unable to parse right side of ! expression");
}
} // namespace
} // namespace wgsl
} // namespace reader
} // namespace tint
| 32.557692
| 75
| 0.693739
|
dorba
|
0486c7d7315361d00a31c96e4a6804dbb9a8ecd5
| 402
|
cpp
|
C++
|
C++/watering-plants.cpp
|
Priyansh2/LeetCode-Solutions
|
d613da1881ec2416ccbe15f20b8000e36ddf1291
|
[
"MIT"
] | 3,269
|
2018-10-12T01:29:40.000Z
|
2022-03-31T17:58:41.000Z
|
C++/watering-plants.cpp
|
Priyansh2/LeetCode-Solutions
|
d613da1881ec2416ccbe15f20b8000e36ddf1291
|
[
"MIT"
] | 53
|
2018-12-16T22:54:20.000Z
|
2022-02-25T08:31:20.000Z
|
C++/watering-plants.cpp
|
Priyansh2/LeetCode-Solutions
|
d613da1881ec2416ccbe15f20b8000e36ddf1291
|
[
"MIT"
] | 1,236
|
2018-10-12T02:51:40.000Z
|
2022-03-30T13:30:37.000Z
|
// Time: O(n)
// Space: O(1)
class Solution {
public:
int wateringPlants(vector<int>& plants, int capacity) {
int result = size(plants), can = capacity;
for (int i = 0; i < size(plants); ++i) {
if (can < plants[i]) {
result += 2 * i;
can = capacity;
}
can -= plants[i];
}
return result;
}
};
| 22.333333
| 59
| 0.442786
|
Priyansh2
|
048c6d829f5088afb73dae1d1b967042aff73970
| 3,857
|
hpp
|
C++
|
include/etl/crtp/iterable.hpp
|
BeatWolf/etl
|
32e8153b38e0029176ca4fe2395b7fa6babe3189
|
[
"MIT"
] | 1
|
2020-02-19T13:13:10.000Z
|
2020-02-19T13:13:10.000Z
|
include/etl/crtp/iterable.hpp
|
BeatWolf/etl
|
32e8153b38e0029176ca4fe2395b7fa6babe3189
|
[
"MIT"
] | null | null | null |
include/etl/crtp/iterable.hpp
|
BeatWolf/etl
|
32e8153b38e0029176ca4fe2395b7fa6babe3189
|
[
"MIT"
] | null | null | null |
//=======================================================================
// Copyright (c) 2014-2018 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
/*!
* \file iterable.hpp
* \brief Use CRTP technique to inject functions for iterators.
*/
#pragma once
namespace etl {
/*!
* \brief CRTP class to inject iterators functions.
*
* This CRTP class injects iterators functions.
*/
template <typename D, bool DMA = false>
struct iterable {
using derived_t = D; ///< The derived type
/*!
* \brief Returns a reference to the derived object, i.e. the object using the CRTP injector.
* \return a reference to the derived object.
*/
derived_t& as_derived() noexcept {
return *static_cast<derived_t*>(this);
}
/*!
* \brief Returns a reference to the derived object, i.e. the object using the CRTP injector.
* \return a reference to the derived object.
*/
const derived_t& as_derived() const noexcept {
return *static_cast<const derived_t*>(this);
}
/*!
* \brief Return an iterator to the first element of the matrix
* \return a iterator pointing to the first element of the matrix
*/
auto begin() noexcept {
if constexpr (DMA) {
as_derived().ensure_cpu_up_to_date();
return as_derived().memory_start();
} else {
return typename derived_t::iterator{as_derived(), 0};
}
}
/*!
* \brief Return an iterator to the past-the-end element of the matrix
* \return an iterator pointing to the past-the-end element of the matrix
*/
auto end() noexcept {
if constexpr (DMA) {
as_derived().ensure_cpu_up_to_date();
return as_derived().memory_end();
} else {
return typename derived_t::iterator{as_derived(), etl::size(as_derived())};
}
}
/*!
* \brief Return an iterator to the first element of the matrix
* \return an const iterator pointing to the first element of the matrix
*/
auto cbegin() const noexcept {
if constexpr (DMA) {
as_derived().ensure_cpu_up_to_date();
return as_derived().memory_start();
} else {
return typename derived_t::const_iterator{as_derived(), 0};
}
}
/*!
* \brief Return an iterator to the past-the-end element of the matrix
* \return a const iterator pointing to the past-the-end element of the matrix
*/
auto cend() const noexcept {
if constexpr (DMA) {
as_derived().ensure_cpu_up_to_date();
return as_derived().memory_end();
} else {
return typename derived_t::const_iterator{as_derived(), etl::size(as_derived())};
}
}
/*!
* \brief Return an iterator to the first element of the matrix
* \return an const iterator pointing to the first element of the matrix
*/
auto begin() const noexcept {
if constexpr (DMA) {
as_derived().ensure_cpu_up_to_date();
return as_derived().memory_start();
} else {
return typename derived_t::const_iterator{as_derived(), 0};
}
}
/*!
* \brief Return an iterator to the past-the-end element of the matrix
* \return a const iterator pointing to the past-the-end element of the matrix
*/
auto end() const noexcept {
if constexpr (DMA) {
as_derived().ensure_cpu_up_to_date();
return as_derived().memory_end();
} else {
return typename derived_t::const_iterator{as_derived(), etl::size(as_derived())};
}
}
};
} //end of namespace etl
| 31.614754
| 97
| 0.590096
|
BeatWolf
|
048e74dd806c873ebf9e6ee8504ff98fe2f9541c
| 433
|
hpp
|
C++
|
src/render/camera/Camera.hpp
|
yzx9/NeuronSdfViewer
|
454164dfccf80b806aac3cd7cca09e2cb8bd3c2a
|
[
"MIT"
] | 1
|
2021-12-31T10:29:56.000Z
|
2021-12-31T10:29:56.000Z
|
src/render/camera/Camera.hpp
|
yzx9/NeuronSdfViewer
|
454164dfccf80b806aac3cd7cca09e2cb8bd3c2a
|
[
"MIT"
] | null | null | null |
src/render/camera/Camera.hpp
|
yzx9/NeuronSdfViewer
|
454164dfccf80b806aac3cd7cca09e2cb8bd3c2a
|
[
"MIT"
] | null | null | null |
#pragma once
#include <Eigen/Dense>
#include "../Ray.hpp"
class Camera
{
public:
Camera(float aspect_radio) : Camera({0.0f, 0.0f, 0.0f}, aspect_radio){};
Camera(Eigen::Vector3f position, float aspect_radio) : position(position), aspect_radio(aspect_radio){};
virtual ~Camera(){};
virtual Ray generate_primary_ray(float x, float y) const = 0;
protected:
Eigen::Vector3f position;
double aspect_radio;
};
| 20.619048
| 108
| 0.692841
|
yzx9
|
048e8111a2c515819b464a532240205bc4684d28
| 3,743
|
cc
|
C++
|
source/test/dbms/Float_test.cc
|
ciscoruiz/wepa
|
e6d922157543c91b6804f11073424a0a9c6e8f51
|
[
"MIT"
] | 2
|
2018-02-03T06:56:29.000Z
|
2021-04-20T10:28:32.000Z
|
source/test/dbms/Float_test.cc
|
ciscoruiz/wepa
|
e6d922157543c91b6804f11073424a0a9c6e8f51
|
[
"MIT"
] | 8
|
2018-02-18T21:00:07.000Z
|
2018-02-20T15:31:24.000Z
|
source/test/dbms/Float_test.cc
|
ciscoruiz/wepa
|
e6d922157543c91b6804f11073424a0a9c6e8f51
|
[
"MIT"
] | 1
|
2018-02-09T07:09:26.000Z
|
2018-02-09T07:09:26.000Z
|
// MIT License
//
// Copyright (c) 2018 Francisco Ruiz (francisco.ruiz.rayo@gmail.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
#include <iostream>
#include <time.h>
#include <gtest/gtest.h>
#include <coffee/dbms/datatype/Float.hpp>
#include <coffee/dbms/datatype/Integer.hpp>
using namespace coffee;
using namespace coffee::dbms;
TEST(FloatTest,is_nulleable)
{
datatype::Float column("nulleable", datatype::Constraint::CanBeNull);
ASSERT_FALSE(column.hasValue());
column.clear();
ASSERT_FALSE(column.hasValue());
ASSERT_THROW(column.getValue(), basis::RuntimeException);
ASSERT_THROW(column.getFloatValue(), basis::RuntimeException);
column.setValue(10.12);
ASSERT_TRUE(column.hasValue());
ASSERT_FLOAT_EQ(10.12, column.getValue());
column.clear();
ASSERT_FALSE(column.hasValue());;
}
TEST(FloatTest,is_not_nulleable)
{
datatype::Float column("not_nulleable", datatype::Constraint::CanNotBeNull);
ASSERT_TRUE(column.hasValue());
column.setValue(0.0);
ASSERT_TRUE(column.hasValue());
ASSERT_EQ(0.0, column.getValue());
column.clear();
ASSERT_TRUE(column.hasValue());
}
TEST(FloatTest,downcast)
{
datatype::Float column("float_downcast");
datatype::Abstract& abs = column;
ASSERT_TRUE(abs.hasValue());
const datatype::Float& other = coffee_datatype_downcast(datatype::Float, abs);
column.setValue(0.0006);
ASSERT_TRUE(other == column);
datatype::Integer zzz("zzz");
ASSERT_THROW(coffee_datatype_downcast(datatype::Float, zzz), dbms::InvalidDataException);
}
TEST(FloatTest,clone)
{
datatype::Float cannotBeNull("cannotBeNull", datatype::Constraint::CanNotBeNull);
datatype::Float canBeNull("canBeNull", datatype::Constraint::CanBeNull);
ASSERT_TRUE(cannotBeNull.hasValue());
ASSERT_FALSE(canBeNull.hasValue());
auto notnull(cannotBeNull.clone());
auto null(canBeNull.clone());
ASSERT_TRUE(notnull->hasValue());
ASSERT_FALSE(null->hasValue());
ASSERT_EQ(0, notnull->compare(cannotBeNull));
cannotBeNull.setValue(5.0);
ASSERT_EQ(5.0, cannotBeNull.getValue());
notnull = cannotBeNull.clone();
ASSERT_TRUE(notnull->hasValue());
ASSERT_EQ(0, notnull->compare(cannotBeNull));
canBeNull.setValue(25);
null = canBeNull.clone();
ASSERT_TRUE(null->hasValue());
ASSERT_EQ(0, null->compare(canBeNull));
ASSERT_EQ(1, null->compare(cannotBeNull));
ASSERT_EQ(-1, notnull->compare(canBeNull));
}
TEST(FloatTest,instantiate) {
auto data = datatype::Float::instantiate("nulleable");
ASSERT_TRUE(data->hasValue());
data = datatype::Float::instantiate("not-nulleable", datatype::Constraint::CanBeNull);
ASSERT_TRUE(!data->hasValue());
}
| 28.792308
| 92
| 0.729896
|
ciscoruiz
|
04909668432a1a8279e808316fda0e641e89d3bd
| 2,702
|
cpp
|
C++
|
Coin3D/src/hardcopy/PSVectorOutput.cpp
|
pniaz20/inventor-utils
|
2306b758b15bd1a0df3fb9bd250215b7bb7fac3f
|
[
"MIT"
] | null | null | null |
Coin3D/src/hardcopy/PSVectorOutput.cpp
|
pniaz20/inventor-utils
|
2306b758b15bd1a0df3fb9bd250215b7bb7fac3f
|
[
"MIT"
] | null | null | null |
Coin3D/src/hardcopy/PSVectorOutput.cpp
|
pniaz20/inventor-utils
|
2306b758b15bd1a0df3fb9bd250215b7bb7fac3f
|
[
"MIT"
] | null | null | null |
/**************************************************************************\
* Copyright (c) Kongsberg Oil & Gas Technologies AS
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
\**************************************************************************/
/*!
\class SoPSVectorOutput SoPSVectorOutput.h Inventor/Annex/HardCopy/SoPSVectorOutput.h
\brief The SoPSVectorOutput class is used for writing Postscript.
\ingroup hardcopy
\since Coin 2.1
\since TGS provides HardCopy support as a separate extension for TGS Inventor.
*/
#include <Inventor/annex/HardCopy/SoPSVectorOutput.h>
#include <Inventor/SbBasic.h>
class SoPSVectorOutputP {
public:
SbBool colored;
};
#define PRIVATE(p) (p->pimpl)
/*!
Constructor.
*/
SoPSVectorOutput::SoPSVectorOutput()
{
PRIVATE(this) = new SoPSVectorOutputP;
PRIVATE(this)->colored = TRUE;
}
/*!
Destructor.
*/
SoPSVectorOutput::~SoPSVectorOutput()
{
delete PRIVATE(this);
}
/*!
Sets whether the geometry should be colored.
*/
void
SoPSVectorOutput::setColored(SbBool flag)
{
PRIVATE(this)->colored = flag;
}
/*!
Returns whether geometry is colored.
*/
SbBool
SoPSVectorOutput::getColored(void) const
{
return PRIVATE(this)->colored;
}
#undef PRIVATE
| 30.359551
| 87
| 0.716506
|
pniaz20
|
04909895a6eaab0b4afc0321f1b9cad2d0039bd6
| 2,877
|
cpp
|
C++
|
Source/SystemQOR/Posix/math/isnand.cpp
|
mfaithfull/QOR
|
0fa51789344da482e8c2726309265d56e7271971
|
[
"BSL-1.0"
] | 9
|
2016-05-27T01:00:39.000Z
|
2021-04-01T08:54:46.000Z
|
Source/SystemQOR/Posix/math/isnand.cpp
|
mfaithfull/QOR
|
0fa51789344da482e8c2726309265d56e7271971
|
[
"BSL-1.0"
] | 1
|
2016-03-03T22:54:08.000Z
|
2016-03-03T22:54:08.000Z
|
Source/SystemQOR/Posix/math/isnand.cpp
|
mfaithfull/QOR
|
0fa51789344da482e8c2726309265d56e7271971
|
[
"BSL-1.0"
] | 4
|
2016-05-27T01:00:43.000Z
|
2018-08-19T08:47:49.000Z
|
/*
* ====================================================
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunPro, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*/
/*
FUNCTION
<<isnan>>, <<isnanf>>, <<isinf>>, <<isinff>>, <<finite>>, <<finitef>>---test for exceptional numbers
INDEX
isnan
INDEX
isinf
INDEX
finite
INDEX
isnanf
INDEX
isinff
INDEX
finitef
ANSI_SYNOPSIS
#include <ieeefp.h>
int isnan(double <[arg]>);
int isinf(double <[arg]>);
int finite(double <[arg]>);
int isnanf(float <[arg]>);
int isinff(float <[arg]>);
int finitef(float <[arg]>);
TRAD_SYNOPSIS
#include <ieeefp.h>
int isnan(<[arg]>)
double <[arg]>;
int isinf(<[arg]>)
double <[arg]>;
int finite(<[arg]>);
double <[arg]>;
int isnanf(<[arg]>);
float <[arg]>;
int isinff(<[arg]>);
float <[arg]>;
int finitef(<[arg]>);
float <[arg]>;
DESCRIPTION
These functions provide information on the floating-point
argument supplied.
There are five major number formats:
o+
o zero
A number which contains all zero bits.
o subnormal
A number with a zero exponent but a nonzero fraction.
o normal
A number with an exponent and a fraction.
o infinity
A number with an all 1's exponent and a zero fraction.
o NAN
A number with an all 1's exponent and a nonzero fraction.
o-
<<isnan>> returns 1 if the argument is a nan. <<isinf>>
returns 1 if the argument is infinity. <<finite>> returns 1 if the
argument is zero, subnormal or normal.
Note that by the C99 standard, <<isnan>> and <<isinf>> are macros
taking any type of floating-point and are declared in
<<math.h>>. Newlib has chosen to declare these as macros in
<<math.h>> and as functions in <<ieeefp.h>>.
The <<isnanf>>, <<isinff>> and <<finitef>> functions perform the same
operations as their <<isnan>>, <<isinf>> and <<finite>>
counterparts, but on single-precision floating-point numbers.
QUICKREF
isnan - pure
QUICKREF
isinf - pure
QUICKREF
finite - pure
QUICKREF
isnan - pure
QUICKREF
isinf - pure
QUICKREF
finite - pure
*/
/*
* __isnand(x) returns 1 is x is nan, else 0;
* no branching!
*/
#include "SystemQOR/Posix/Basemath.h"
//------------------------------------------------------------------------------
namespace nsBaseCRT
{
#ifndef _DOUBLE_IS_32BITS
//------------------------------------------------------------------------------
int Cmath::__isnand( double x )
{
Cmp_signed__int32 hx,lx;
extract_words( hx, lx, x );
hx &= 0x7fffffff;
hx |= (Cmp_unsigned__int32)( lx | ( -lx ) ) >> 31;
hx = 0x7ff00000 - hx;
return (int)( ( (Cmp_unsigned__int32)( hx ) ) >> 31 );
}
#endif /* _DOUBLE_IS_32BITS */
};//namespace nsBaseCRT
| 22.476563
| 101
| 0.612791
|
mfaithfull
|
049202855696f1f8193ba58cd33977bfa928a77b
| 420
|
cpp
|
C++
|
Code/customprocess.cpp
|
scigeliu/ViaLacteaVisualAnalytics
|
2ac79301ceaaab0415ec7105b8267552262c7650
|
[
"Apache-2.0"
] | 1
|
2021-12-15T15:15:50.000Z
|
2021-12-15T15:15:50.000Z
|
Code/customprocess.cpp
|
scigeliu/ViaLacteaVisualAnalytics
|
2ac79301ceaaab0415ec7105b8267552262c7650
|
[
"Apache-2.0"
] | null | null | null |
Code/customprocess.cpp
|
scigeliu/ViaLacteaVisualAnalytics
|
2ac79301ceaaab0415ec7105b8267552262c7650
|
[
"Apache-2.0"
] | null | null | null |
#include "customprocess.h"
#include <QProcess>
#include <QDebug>
#include <QCoreApplication>
CustomProcess::CustomProcess()
{
QProcess *process = new QProcess();
connect(process, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(onFinished()));
process->start("ls", QStringList());
if (!process->waitForStarted())
qDebug() << "error";
}
CustomProcess::~CustomProcess()
{
}
| 16.8
| 94
| 0.657143
|
scigeliu
|
049254fbbd301c05e703f078f07419d962caf7ee
| 15,847
|
cpp
|
C++
|
src/Engine/Core/SYS_Funct.cpp
|
slajerek/MTEngineSDL
|
19b5295d875c197ec03bc20ddacd48c228920365
|
[
"MIT"
] | 4
|
2021-12-16T11:22:30.000Z
|
2022-01-05T11:20:32.000Z
|
src/Engine/Core/SYS_Funct.cpp
|
slajerek/MTEngineSDL
|
19b5295d875c197ec03bc20ddacd48c228920365
|
[
"MIT"
] | 1
|
2022-01-07T10:41:38.000Z
|
2022-01-09T12:04:03.000Z
|
src/Engine/Core/SYS_Funct.cpp
|
slajerek/MTEngineSDL
|
19b5295d875c197ec03bc20ddacd48c228920365
|
[
"MIT"
] | null | null | null |
/*
* SYS_Funct.mm
* MobiTracker
*
* Created by Marcin Skoczylas on 10-07-15.
* Copyright 2010 Marcin Skoczylas. All rights reserved.
*
*/
#include "SYS_Funct.h"
#include "SYS_Main.h"
#include "SYS_FileSystem.h"
#include "CSlrString.h"
#if !defined(WIN32) && !defined(ANDROID)
#include <unistd.h>
#include <execinfo.h>
#include <sys/param.h>
#include <sys/times.h>
#include <sys/types.h>
#endif
#ifdef WIN32
#pragma comment(lib, "psapi.lib")
#include <psapi.h>
#endif
#if !defined(WIN32) && !defined(ANDROID)
#include <fstream>
#endif
#include <string.h>
#if defined(LINUX) || defined(MACOS)
#include <pthread.h>
#include <unistd.h>
#endif
// http://www.rawmaterialsoftware.com/viewtopic.php?f=4&t=4804
// TODO: -ffast-math
// TODO: hashtable: http://cboard.cprogramming.com/c-programming/152990-defn-inside-hash-table.html
unsigned NextPow2( unsigned x )
{
--x;
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
return ++x;
}
bool compare_str_num(char *str1, char *str2, u16 numChars)
{
for (u16 i = 0; i != numChars; i++)
{
if (str1[i] != str2[i])
return false;
}
return true;
}
void SYS_FixFileNameSlashes(char *buf)
{
int len = strlen(buf);
// normalize path separators
for (int i = 0; i < len; i++)
{
if (buf[i] == '\\' || buf[i] == '/')
buf[i] = SYS_FILE_SYSTEM_PATH_SEPARATOR;
}
// check if double path separators exist (fix for c:\dupa\/file.txt paths)
for (int i = 0; i < len-1; i++)
{
if (buf[i] == SYS_FILE_SYSTEM_PATH_SEPARATOR
&& buf[i+1] == SYS_FILE_SYSTEM_PATH_SEPARATOR)
{
for (int j = i; j < len-1; j++)
{
buf[j] = buf[j+1];
}
buf[len-1] = '\0';
len--;
}
}
}
bool SYS_FileNameHasExtension(char *fileName, char *extension)
{
int i = strlen(fileName) - 1;
int j = strlen(extension) - 1;
// x.ext - min 2 more
if (i < (j+2))
return false;
for ( ; j >= 0; )
{
if (fileName[i] != extension[j])
return false;
i--;
j--;
}
if (fileName[i] != '.')
return false;
return true;
}
void SYS_RemoveFileNameExtension(char *fileName)
{
// warning! if the fileName is const it will crash...
// don't forget to not use extensions in the const char* filenames
int l = strlen(fileName);
bool isExt = false;
for (int z = 0; z < l; z++)
{
if (fileName[z] == '.')
{
isExt = true;
break;
}
}
if (isExt == false)
return;
int pos = l;
int i = l-1;
for ( ; i >= 0; )
{
if (fileName[i] == '.')
{
pos = i;
break;
}
i--;
}
if (pos != l)
{
fileName[pos] = 0x00;
}
}
void SYS_Sleep(unsigned long milliseconds)
{
//LOGD("SYS_Sleep %d", milliseconds);
#ifdef WIN32
Sleep(milliseconds);
#else
long milisec = milliseconds;
struct timespec req={0};
time_t sec=(int)(milisec/1000);
milisec = milisec-(sec*1000);
req.tv_sec=sec;
req.tv_nsec=milisec*1000000L;
while(nanosleep(&req,&req)==-1)
continue;
#endif
//LOGD("SYS_Sleep of %d done", milliseconds);
}
bool FUN_IsNumber(char c)
{
if (c >= '0' && c <= '9')
return true;
return false;
}
bool FUN_IsNumber(char *str)
{
u64 l = strlen(str);
for (u64 n = 0; n < l; n++)
{
if (!isdigit( str[ n ] ))
{
return false;
}
}
return true;
}
bool FUN_IsHexDigit(char c)
{
if (c >= '0' && c <= '9')
return true;
if (c >= 'a' && c <= 'f')
return true;
if (c >= 'A' && c <= 'F')
return true;
return false;
}
bool FUN_IsHexNumber(char *str)
{
u64 l = strlen(str);
for (u64 i = 0; i < l; i++)
{
if (!FUN_IsHexDigit(str[i]))
{
return false;
}
}
return true;
}
char FUN_HexDigitToChar(u8 hexDigit)
{
u8 h = hexDigit % 16;
char hexDigits[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
return hexDigits[h];
}
u32 FUN_HexStrToValue(char *str)
{
u32 value;
sscanf(str, "%x", &value);
return value;
}
void FUN_IntToBinaryStr(unsigned value, char* binaryStr, int n)
{
for (int i = 0; i < n; i++)
{
binaryStr[i] = (value & (int)1<<(n-i-1)) ? '1' : '0';
}
binaryStr[n]='\0';
}
void FUN_ToUpperCaseStr(char *str)
{
u64 l = strlen(str);
for (u64 i = 0; i < l; i++)
{
str[i] = toupper(str[i]);
}
}
#if !defined(WIN32) && !defined(ANDROID) && !defined(IPHONE)
void process_mem_usage(double& vm_usage, double& resident_set)
{
using std::ios_base;
using std::ifstream;
using std::string;
vm_usage = 0.0;
resident_set = 0.0;
// 'file' stat seems to give the most reliable results
//
ifstream stat_stream("/proc/self/stat",ios_base::in);
// dummy vars for leading entries in stat that we don't care about
//
string pid, comm, state, ppid, pgrp, session, tty_nr;
string tpgid, flags, minflt, cminflt, majflt, cmajflt;
string utime, stime, cutime, cstime, priority, nice;
string O, itrealvalue, starttime;
// the two fields we want
//
unsigned long vsize;
long rss;
stat_stream >> pid >> comm >> state >> ppid >> pgrp >> session >> tty_nr
>> tpgid >> flags >> minflt >> cminflt >> majflt >> cmajflt
>> utime >> stime >> cutime >> cstime >> priority >> nice
>> O >> itrealvalue >> starttime >> vsize >> rss; // don't care about the rest
stat_stream.close();
long page_size_kb = sysconf(_SC_PAGE_SIZE) / 1024; // in case x86-64 is configured to use 2MB pages
vm_usage = vsize / 1024.0;
resident_set = rss * page_size_kb;
}
#endif
void SYS_PrintMemoryUsed()
{
#ifdef WIN32
PPROCESS_MEMORY_COUNTERS pMemCountr = new PROCESS_MEMORY_COUNTERS;
if( GetProcessMemoryInfo(GetCurrentProcess(), pMemCountr, sizeof(PROCESS_MEMORY_COUNTERS)))
{
LOGM("MEMORY=%d", pMemCountr->WorkingSetSize);
}
delete pMemCountr;
#elif !defined(ANDROID) && !defined(IPHONE)
double vm, rss;
process_mem_usage(vm, rss);
LOGMEM("MEMORY VM=%d RSS=%d", (int)vm, (int)rss);
#else
LOGError("SYS_PrintMemoryUsed: not implemented");
#endif
}
char *SYS_GetFileNameWithExtensionFromFullPath(const char *fileNameFull)
{
int len = strlen(fileNameFull);
if (len == 0)
{
char *ret = new char[1];
ret[0] = 0x00;
return ret;
}
// check if there's a path sign inside
bool foundPathSign = false;
for (int i = 0; i < len; i++)
{
if (fileNameFull[i] == '/' || fileNameFull[i] == '\\')
{
foundPathSign = true;
break;
}
}
// path sign is not found, just dup the original path as filename
if (foundPathSign == false)
{
char *ret = new char[len];
strcpy(ret, fileNameFull);
return ret;
}
char *fileName = SYS_GetCharBuf();
int i = len-1;
for ( ; i >= 0; i--)
{
if (fileNameFull[i] == '/' || fileNameFull[i] == '\\')
{
i++;
break;
}
}
u32 j = 0;
for ( ; i < len; i++, j++)
{
fileName[j] = fileNameFull[i];
}
fileName[j] = 0x00;
char *ret = new char[len];
strcpy(ret, fileName);
SYS_ReleaseCharBuf(fileName);
return ret;
}
char *SYS_GetPathFromFullPath(const char *fileNameFull)
{
char pathName[1024];
u32 len = strlen(fileNameFull);
int i = len-1;
for ( ; i >= 0; i--)
{
if (fileNameFull[i] == '/' || fileNameFull[i] == '\\')
{
i++;
break;
}
}
u32 j = 0;
for ( ; j < 1020; j++)
{
if (j == i)
break;
pathName[j] = fileNameFull[j];
}
pathName[j] = 0x00;
return STRALLOC(pathName);
}
char *FUN_SafeConvertStdStringToCharArray(std::string inString)
{
// LOGD("FUN_SafeConvertStdStringToCharArray");
int len = inString.length();
// LOGD(" len=%d", len);
char *buf = new char[len+1];
for (int i = 0; i < len; i++)
{
char c = inString[i];
// LOGD(" [%d]=%x '%c'", i, c, c);
buf[i] = c;
}
buf[len] = 0x00;
return buf;
}
const char hexTableSmall[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
const char hexTableSmallNoZero[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
void sprintfHexCode4(char *pszBuffer, uint8 value)
{
pszBuffer[0] = hexTableSmall[(value) & 0x0F];
pszBuffer[1] = 0x00;
}
void sprintfHexCode8(char *pszBuffer, uint8 value)
{
pszBuffer[0] = hexTableSmall[(value >> 4) & 0x0F];
pszBuffer[1] = hexTableSmall[(value) & 0x0F];
pszBuffer[2] = 0x00;
}
void sprintfHexCode16(char *pszBuffer, uint16 value)
{
pszBuffer[0] = hexTableSmall[(value >> 12) & 0x0F];
pszBuffer[1] = hexTableSmall[(value >> 8) & 0x0F];
pszBuffer[2] = hexTableSmall[(value >> 4) & 0x0F];
pszBuffer[3] = hexTableSmall[(value) & 0x0F];
pszBuffer[4] = 0x00;
}
void sprintfHexCode4WithoutZeroEnding(char *pszBuffer, uint8 value)
{
pszBuffer[0] = hexTableSmall[(value) & 0x0F];
}
void sprintfHexCode8WithoutZeroEnding(char *pszBuffer, uint8 value)
{
pszBuffer[0] = hexTableSmall[(value >> 4) & 0x0F];
pszBuffer[1] = hexTableSmall[(value) & 0x0F];
}
void sprintfHexCode16WithoutZeroEnding(char *pszBuffer, uint16 value)
{
pszBuffer[0] = hexTableSmall[(value >> 12) & 0x0F];
pszBuffer[1] = hexTableSmall[(value >> 8) & 0x0F];
pszBuffer[2] = hexTableSmall[(value >> 4) & 0x0F];
pszBuffer[3] = hexTableSmall[(value) & 0x0F];
}
void sprintfHexCode16WithoutZeroEndingAndNoLeadingZeros(char *pszBuffer, uint16 value)
{
pszBuffer[0] = hexTableSmallNoZero[(value >> 12) & 0x0F];
pszBuffer[1] = hexTableSmallNoZero[(value >> 8) & 0x0F];
pszBuffer[2] = hexTableSmallNoZero[(value >> 4) & 0x0F];
pszBuffer[3] = hexTableSmallNoZero[(value) & 0x0F];
if (pszBuffer[0] == '0')
{
pszBuffer[0] = ' ';
if (pszBuffer[1] == '0')
{
pszBuffer[1] = ' ';
if (pszBuffer[2] == '0')
{
pszBuffer[2] = ' ';
}
}
}
}
// special printf for numbers only
// see formatting information below
// Print the number "n" in the given "base"
// using exactly "numDigits"
// print +/- if signed flag "isSigned" is TRUE
// use the character specified in "padchar" to pad extra characters
//
// Examples:
// sprintfNum(pszBuffer, 6, 10, 6, TRUE, ' ', 1234); --> " +1234"
// sprintfNum(pszBuffer, 6, 10, 6, FALSE, '0', 1234); --> "001234"
// sprintfNum(pszBuffer, 6, 16, 6, FALSE, '.', 0x5AA5); --> "..5AA5"
#define hexchar(x) ((((x)&0x0F)>9)?((x)+'A'-10):((x)+'0'))
void sprintfNum(char *pszBuffer, int size, char base, char numDigits, char isSigned, char padchar, i64 n)
{
char *ptr = pszBuffer;
if (!pszBuffer)
{
return;
}
char *p, buf[32];
unsigned long long x;
unsigned char count;
// prepare negative number
if( isSigned && (n < 0) )
{
x = -n;
}
else
{
x = n;
}
// setup little string buffer
count = (numDigits-1)-(isSigned?1:0);
p = buf + sizeof (buf);
*--p = '\0';
// force calculation of first digit
// (to prevent zero from not printing at all!!!)
*--p = (char)hexchar(x%base);
x = x / base;
// calculate remaining digits
while(count--)
{
if(x != 0)
{
// calculate next digit
*--p = (char)hexchar(x%base);
x /= base;
}
else
{
// no more digits left, pad out to desired length
*--p = padchar;
}
}
// apply signed notation if requested
if( isSigned )
{
if(n < 0)
{
*--p = '-';
}
else if(n > 0)
{
*--p = '+';
}
else
{
*--p = ' ';
}
}
// print the string right-justified
count = numDigits;
while(count--)
{
*ptr++ = *p++;
}
return;
}
void sprintfHexCode64(char *pszBuffer, u64 n)
{
sprintfUnsignedNum(pszBuffer, 16, 16, 16, '0', n);
}
// special printf for numbers only
// see formatting information below
// Print the number "n" in the given "base"
// using exactly "numDigits"
// print +/- if signed flag "isSigned" is TRUE
// use the character specified in "padchar" to pad extra characters
//
// Examples:
// sprintfNum(pszBuffer, 6, 10, 6, TRUE, ' ', 1234); --> " +1234"
// sprintfNum(pszBuffer, 6, 10, 6, FALSE, '0', 1234); --> "001234"
// sprintfNum(pszBuffer, 6, 16, 6, FALSE, '.', 0x5AA5); --> "..5AA5"
void sprintfUnsignedNum(char *pszBuffer, int size, char base, char numDigits, char padchar, u64 n)
{
char *ptr = pszBuffer;
if (!pszBuffer)
{
return;
}
char *p, buf[64];
unsigned long long x;
unsigned char count;
{
x = n;
}
// setup little string buffer
count = (numDigits-1);
p = buf + sizeof (buf);
*--p = '\0';
// force calculation of first digit
// (to prevent zero from not printing at all!!!)
*--p = (char)hexchar(x%base);
x = x / base;
// calculate remaining digits
while(count--)
{
if(x != 0)
{
// calculate next digit
*--p = (char)hexchar(x%base);
x /= base;
}
else
{
// no more digits left, pad out to desired length
*--p = padchar;
}
}
// print the string right-justified
count = numDigits;
while(count--)
{
*ptr++ = *p++;
}
pszBuffer[numDigits] = 0x00;
return;
}
/*
// return whether a number is a power of two
inline UInt32 IsPowerOfTwo(UInt32 x)
{
return (x & (x-1)) == 0;
}
// count the leading zeroes in a word
#ifdef __MWERKS__
// Metrowerks Codewarrior. powerpc native count leading zeroes instruction:
#define CountLeadingZeroes(x) ((int)__cntlzw((unsigned int)x))
#elif TARGET_OS_WIN32
static int CountLeadingZeroes( int arg )
{
__asm{
bsr eax, arg
mov ecx, 63
cmovz eax, ecx
xor eax, 31
}
return arg;
}
#else
static __inline__ int CountLeadingZeroes(int arg) {
#if TARGET_CPU_PPC || TARGET_CPU_PPC64
__asm__ volatile("cntlzw %0, %1" : "=r" (arg) : "r" (arg));
return arg;
#elif TARGET_CPU_X86 || TARGET_CPU_X86_64
__asm__ volatile(
"bsrl %0, %0\n\t"
"movl $63, %%ecx\n\t"
"cmove %%ecx, %0\n\t"
"xorl $31, %0"
: "=r" (arg)
: "0" (arg) : "%ecx"
);
return arg;
#else
if (arg == 0) return 32;
return __builtin_clz(arg);
#endif
}
#endif
// count trailing zeroes
inline UInt32 CountTrailingZeroes(UInt32 x)
{
return 32 - CountLeadingZeroes(~x & (x-1));
}
// count leading ones
inline UInt32 CountLeadingOnes(UInt32 x)
{
return CountLeadingZeroes(~x);
}
// count trailing ones
inline UInt32 CountTrailingOnes(UInt32 x)
{
return 32 - CountLeadingZeroes(x & (~x-1));
}
// number of bits required to represent x.
inline UInt32 NumBits(UInt32 x)
{
return 32 - CountLeadingZeroes(x);
}
// base 2 log of next power of two greater or equal to x
inline UInt32 Log2Ceil(UInt32 x)
{
return 32 - CountLeadingZeroes(x - 1);
}
// next power of two greater or equal to x
inline UInt32 NextPowerOfTwo(UInt32 x)
{
return 1L << Log2Ceil(x);
}
// counting the one bits in a word
inline UInt32 CountOnes(UInt32 x)
{
// secret magic algorithm for counting bits in a word.
UInt32 t;
x = x - ((x >> 1) & 0x55555555);
t = ((x >> 2) & 0x33333333);
x = (x & 0x33333333) + t;
x = (x + (x >> 4)) & 0x0F0F0F0F;
x = x + (x << 8);
x = x + (x << 16);
return x >> 24;
}
// counting the zero bits in a word
inline UInt32 CountZeroes(UInt32 x)
{
return CountOnes(~x);
}
// return the bit position (0..31) of the least significant bit
inline UInt32 LSBitPos(UInt32 x)
{
return CountTrailingZeroes(x & -(SInt32)x);
}
// isolate the least significant bit
inline UInt32 LSBit(UInt32 x)
{
return x & -(SInt32)x;
}
// return the bit position (0..31) of the most significant bit
inline UInt32 MSBitPos(UInt32 x)
{
return 31 - CountLeadingZeroes(x);
}
// isolate the most significant bit
inline UInt32 MSBit(UInt32 x)
{
return 1UL << MSBitPos(x);
}
// Division optimized for power of 2 denominators
inline UInt32 DivInt(UInt32 numerator, UInt32 denominator)
{
if(IsPowerOfTwo(denominator))
return numerator >> (31 - CountLeadingZeroes(denominator));
else
return numerator/denominator;
}
*/
| 20.059494
| 120
| 0.59639
|
slajerek
|
0493b14a1aa6bc9f14b411cc08348a603717711a
| 477
|
cpp
|
C++
|
CodeChef/Mahasena.cpp
|
canis-majoris123/CompetitiveProgramming
|
be6c208abe6e0bd748c3bb0e715787506d73588d
|
[
"MIT"
] | null | null | null |
CodeChef/Mahasena.cpp
|
canis-majoris123/CompetitiveProgramming
|
be6c208abe6e0bd748c3bb0e715787506d73588d
|
[
"MIT"
] | null | null | null |
CodeChef/Mahasena.cpp
|
canis-majoris123/CompetitiveProgramming
|
be6c208abe6e0bd748c3bb0e715787506d73588d
|
[
"MIT"
] | null | null | null |
//https://www.codechef.com/problems/AMR15A
#include<bits/stdc++.h>
using namespace std ;
#define akriti long long int
#define sahaj while
int main()
{
ios_base::sync_with_stdio(false) ;
cin.tie(0) ;
akriti testcase{0} , num{0} , odd{0} , even{0} ;
cin >> testcase ;
sahaj(testcase--)
{
cin >> num ;
(num%2 == 0) ? even++ : odd++ ;
}
(even > odd) ? cout << "READY FOR BATTLE" << endl : cout << "NOT READY" ;
}
| 23.85
| 78
| 0.540881
|
canis-majoris123
|
049589f4419aea55582b4846b08ee3618bdc3b6e
| 539
|
cpp
|
C++
|
mod.cpp
|
johnb432/Zeus-Additions
|
faffc97c0ab939032fd442186376413fa2a5cfc1
|
[
"MIT"
] | null | null | null |
mod.cpp
|
johnb432/Zeus-Additions
|
faffc97c0ab939032fd442186376413fa2a5cfc1
|
[
"MIT"
] | 3
|
2021-02-08T18:48:20.000Z
|
2021-02-21T21:24:58.000Z
|
mod.cpp
|
johnb432/Zeus-Additions
|
faffc97c0ab939032fd442186376413fa2a5cfc1
|
[
"MIT"
] | null | null | null |
name = "Zeus Additions";
author = "johnb43";
tooltipOwned = "Zeus Additions";
hideName = 0;
hidePicture = 0;
actionName = "Github";
action = "https://github.com/johnb432/Zeus-Additions";
description = "A small mod that adds Zeus modules, made by johnb43.";
overview = "A small mod that adds Zeus modules, made by johnb43.";
picture = "\x\zeus_additions\addons\main\ui\logo_zeus_additions.paa";
logo = "\x\zeus_additions\addons\main\ui\logo_zeus_additions.paa";
overviewPicture = "\x\zeus_additions\addons\main\ui\logo_zeus_additions.paa";
| 41.461538
| 77
| 0.755102
|
johnb432
|
04965e6989c7d90ab56f2f23b7b4d946b9825f02
| 1,713
|
cc
|
C++
|
src/ExtensionRegistry.cc
|
pjaaskel/phsa-runtime
|
b37cd9bd8085632e89b02861da193bbd0fa25c5b
|
[
"MIT"
] | 7
|
2016-04-17T20:38:36.000Z
|
2017-12-28T17:46:21.000Z
|
src/ExtensionRegistry.cc
|
pjaaskel/phsa-runtime
|
b37cd9bd8085632e89b02861da193bbd0fa25c5b
|
[
"MIT"
] | 6
|
2016-03-11T15:54:28.000Z
|
2016-11-22T13:20:11.000Z
|
src/ExtensionRegistry.cc
|
pjaaskel/phsa-runtime
|
b37cd9bd8085632e89b02861da193bbd0fa25c5b
|
[
"MIT"
] | 4
|
2016-03-10T14:27:53.000Z
|
2020-05-03T22:16:51.000Z
|
/*
Copyright (c) 2016 General Processor Tech.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
*/
/**
* @author tomi.aijo@parmance.com for General Processor Tech.
*/
#include "ExtensionRegistry.hh"
ExtensionRegistry::ExtensionRegistry() {}
void ExtensionRegistry::registerExtension(Extension::Identifier Id,
Extension *E) {
Extensions.insert({Id, E});
}
std::pair<ExtensionRegistry::iterator, ExtensionRegistry::iterator>
ExtensionRegistry::findExtensions(Extension::Identifier Id) {
return Extensions.equal_range(Id);
}
ExtensionRegistry::~ExtensionRegistry() {
for (auto Ext : Extensions) {
delete Ext.second;
}
}
| 40.785714
| 80
| 0.737303
|
pjaaskel
|
0498ce99e33bdd3eeeb69b85d69a5d864c96a424
| 4,483
|
cpp
|
C++
|
src/physics/collision/bvh_model.cpp
|
Q-Minh/soft-body-simulator
|
f41640945df989d8c91d99e8f2e86d6af90211f6
|
[
"BSL-1.0"
] | 5
|
2021-12-17T01:45:48.000Z
|
2022-01-29T17:35:49.000Z
|
src/physics/collision/bvh_model.cpp
|
Q-Minh/soft-body-simulator
|
f41640945df989d8c91d99e8f2e86d6af90211f6
|
[
"BSL-1.0"
] | null | null | null |
src/physics/collision/bvh_model.cpp
|
Q-Minh/soft-body-simulator
|
f41640945df989d8c91d99e8f2e86d6af90211f6
|
[
"BSL-1.0"
] | null | null | null |
#include <cassert>
#include <sbs/common/mesh.h>
#include <sbs/physics/collision/bvh_model.h>
#include <sbs/physics/collision/contact.h>
#include <sbs/physics/collision/sdf_model.h>
#include <vector>
namespace sbs {
namespace physics {
namespace collision {
point_bvh_model_t::point_bvh_model_t() : kd_tree_type(0), surface_() {}
model_type_t point_bvh_model_t::model_type() const
{
return model_type_t::bvh;
}
primitive_type_t point_bvh_model_t::primitive_type() const
{
return primitive_type_t::point;
}
point_bvh_model_t::point_bvh_model_t(common::shared_vertex_surface_mesh_i const* surface)
: Discregrid::KDTree<Discregrid::BoundingSphere>(surface->vertex_count()), surface_(surface)
{
kd_tree_type::construct();
}
void point_bvh_model_t::collide(collision_model_t& other, contact_handler_t& handler)
{
model_type_t const other_model_type = other.model_type();
if (other_model_type == model_type_t::sdf)
{
sdf_model_t const& sdf_model = reinterpret_cast<sdf_model_t const&>(other);
auto const closest_point_on_aabb = [](Eigen::Vector3d const& p,
Eigen::AlignedBox3d const& aabb) {
Eigen::Vector3d c = p;
c.x() = std::clamp(c.x(), aabb.min().x(), aabb.max().x());
c.y() = std::clamp(c.y(), aabb.min().y(), aabb.max().y());
c.z() = std::clamp(c.z(), aabb.min().z(), aabb.max().z());
return c;
};
auto const is_sphere_colliding_with_sdf =
[this, &sdf_model, closest_point_on_aabb](unsigned int node_idx, unsigned int depth) -> bool {
Discregrid::BoundingSphere const& s = this->hull(node_idx);
Eigen::AlignedBox3d const& sdf_englobing_volume = sdf_model.volume();
auto const [sd, grad] = sdf_model.evaluate(s.x());
if (sd < 0.)
return true;
Eigen::Vector3d closest_point =
closest_point_on_aabb(s.x(), sdf_englobing_volume);
Eigen::Vector3d const diff = s.x() - closest_point;
scalar_type const dist2 = diff.squaredNorm();
scalar_type const r2 = s.r() * s.r();
return dist2 < r2;
};
auto const contact_callback =
[this, &sdf_model, &handler](unsigned int node_idx, unsigned int depth) {
kd_tree_type::Node const& node = this->node(node_idx);
if (!node.isLeaf())
return;
for (auto i = node.begin; i < node.begin + node.n; ++i)
{
index_type const vi = m_lst[i];
Eigen::Vector3d const& pi = surface_->vertex(vi).position;
auto const [signed_distance, grad] = sdf_model.evaluate(pi);
bool const is_vertex_penetrating = signed_distance < 0.;
if (!is_vertex_penetrating)
continue;
Eigen::Vector3d const contact_normal = grad.normalized();
Eigen::Vector3d const contact_point =
pi + std::abs(signed_distance) * contact_normal;
surface_mesh_particle_to_sdf_contact_t contact(
contact_t::type_t::surface_particle_to_sdf,
this->id(),
sdf_model.id(),
contact_point,
contact_normal,
vi);
handler.handle(contact);
}
};
traverseBreadthFirst(is_sphere_colliding_with_sdf, contact_callback);
}
}
void point_bvh_model_t::update(simulation_t const& simulation)
{
kd_tree_type::update();
}
Eigen::Vector3d point_bvh_model_t::entityPosition(unsigned int i) const
{
Eigen::Vector3d const position = surface_->vertex(i).position;
return position;
}
void point_bvh_model_t::computeHull(
unsigned int b,
unsigned int n,
Discregrid::BoundingSphere& hull) const
{
auto vertices_of_sphere = std::vector<Eigen::Vector3d>(n);
for (unsigned int i = b; i < n + b; ++i)
vertices_of_sphere[i - b] = surface_->vertex(m_lst[i]).position;
Discregrid::BoundingSphere const s(vertices_of_sphere);
hull.x() = s.x();
hull.r() = s.r();
}
} // namespace collision
} // namespace physics
} // namespace sbs
| 34.484615
| 106
| 0.58153
|
Q-Minh
|
049a698934812cf23f16e7e77d1ad15a044b00c2
| 622
|
hpp
|
C++
|
android-28/javax/security/auth/login/LoginException.hpp
|
YJBeetle/QtAndroidAPI
|
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
|
[
"Apache-2.0"
] | 12
|
2020-03-26T02:38:56.000Z
|
2022-03-14T08:17:26.000Z
|
android-31/javax/security/auth/login/LoginException.hpp
|
YJBeetle/QtAndroidAPI
|
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
|
[
"Apache-2.0"
] | 1
|
2021-01-27T06:07:45.000Z
|
2021-11-13T19:19:43.000Z
|
android-29/javax/security/auth/login/LoginException.hpp
|
YJBeetle/QtAndroidAPI
|
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
|
[
"Apache-2.0"
] | 3
|
2021-02-02T12:34:55.000Z
|
2022-03-08T07:45:57.000Z
|
#pragma once
#include "../../../../java/security/GeneralSecurityException.hpp"
class JString;
namespace javax::security::auth::login
{
class LoginException : public java::security::GeneralSecurityException
{
public:
// Fields
// QJniObject forward
template<typename ...Ts> explicit LoginException(const char *className, const char *sig, Ts...agv) : java::security::GeneralSecurityException(className, sig, std::forward<Ts>(agv)...) {}
LoginException(QJniObject obj);
// Constructors
LoginException();
LoginException(JString arg0);
// Methods
};
} // namespace javax::security::auth::login
| 23.923077
| 188
| 0.712219
|
YJBeetle
|
049b8ae47b402a1e85399f68172601e4fccb7e11
| 6,231
|
cpp
|
C++
|
audio_compression/masking.cpp
|
dustsigns/lecture-demos
|
50d5abb252e7e467e9648b61310ce93b85c6c5f0
|
[
"BSD-3-Clause"
] | 14
|
2018-03-26T13:43:58.000Z
|
2022-03-03T13:04:36.000Z
|
audio_compression/masking.cpp
|
dustsigns/lecture-demos
|
50d5abb252e7e467e9648b61310ce93b85c6c5f0
|
[
"BSD-3-Clause"
] | null | null | null |
audio_compression/masking.cpp
|
dustsigns/lecture-demos
|
50d5abb252e7e467e9648b61310ce93b85c6c5f0
|
[
"BSD-3-Clause"
] | 1
|
2019-08-03T23:12:08.000Z
|
2019-08-03T23:12:08.000Z
|
//Illustration of frequency masking
// Andreas Unterweger, 2017-2022
//This code is licensed under the 3-Clause BSD License. See LICENSE file for details.
#include <iostream>
#include <limits>
#include <array>
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include "common.hpp"
#include "sinewave.hpp"
#include "mixer.hpp"
#include "player.hpp"
#include "math.hpp"
#include "plot.hpp"
#include "colors.hpp"
#include "combine.hpp"
static constexpr unsigned int frequencies[] {400, 440};
static_assert(comutils::arraysize(frequencies) == 2, "This application can only illustrate masking for two frequencies in total");
static_assert(frequencies[1] > frequencies[0], "The second frequency has to be larger than the first");
using audio_type = short; //May be signed char (for 8 bits), short (16) or int (32)
struct audio_data
{
comutils::SineWaveGenerator<audio_type> generators[2];
comutils::WaveFormMixer<audio_type, 2> mixer;
sndutils::AudioPlayer<audio_type> player;
const std::string window_name;
audio_data(const std::string &window_name)
: generators{comutils::SineWaveGenerator<audio_type>(frequencies[0]), comutils::SineWaveGenerator<audio_type>(frequencies[1])},
mixer({&generators[0], &generators[1]}),
window_name(window_name) { }
};
static cv::Mat PlotWaves(const audio_data &data)
{
constexpr size_t sampling_frequency = 48000;
constexpr size_t displayed_samples = 5 * (sampling_frequency / frequencies[0]) + 1; //About five periods of the higher-frequency wave form plus one sample
std::array<std::vector<audio_type>, 3> samples { std::vector<audio_type>(displayed_samples), std::vector<audio_type>(displayed_samples), std::vector<audio_type>(displayed_samples) };
for (const auto &i : {0, 1})
data.generators[i].GetRepresentativeSamples(samples[i].size(), samples[i].data());
data.mixer.GetRepresentativeSamples(samples[2].size(), samples[2].data());
imgutils::Plot plot({imgutils::PointSet(samples[0], 1, imgutils::Red),
imgutils::PointSet(samples[1], 1, imgutils::Blue),
imgutils::PointSet(samples[2], 1, imgutils::Purple)});
plot.SetAxesLabels("t [ms]", "I(t)");
imgutils::Tick::GenerateTicks(plot.x_axis_ticks, 0, displayed_samples, 0.001 * sampling_frequency, 1, 0, 1000.0 / sampling_frequency); //Mark and label every ms with no decimal places and a relative scale (1000 for ms)
plot.x_axis_ticks.pop_back(); //Remove last tick and label so that the axis label is not overwritten
imgutils::Tick::GenerateTicks(plot.y_axis_ticks, std::numeric_limits<audio_type>::lowest() + 1, std::numeric_limits<audio_type>::max(), std::numeric_limits<audio_type>::max() / 2.0, 1, 1, 1.0 / std::numeric_limits<audio_type>::max()); //Mark and label every 0.5 units (0-1) with 1 decimal place and a relative scale (where the maximum is 1)
cv::Mat_<cv::Vec3b> image;
plot.DrawTo(image);
return image;
}
static cv::Mat PlotSpectrum(int (&levels_percent)[2])
{
constexpr auto max_frequency = frequencies[1] * 1.5;
imgutils::Plot plot({imgutils::PointSet({cv::Point2d(frequencies[0], -levels_percent[0])}, imgutils::Red, false, true), //No lines, but samples
imgutils::PointSet({cv::Point2d(frequencies[1], -levels_percent[1])}, imgutils::Blue, false, true)});
plot.SetAxesLabels("f [Hz]", "A(f) [dB]");
imgutils::Tick::GenerateTicks(plot.x_axis_ticks, 0, max_frequency, 100, 2); //Mark every 100 Hz, label every 200 Hz (0 - max. frequency)
imgutils::Tick::GenerateTicks(plot.y_axis_ticks, 0, -100, -10, 2); //Mark every 10 dB, label every 20 dB (0 - -100)
cv::Mat_<cv::Vec3b> image;
plot.DrawTo(image);
return image;
}
static std::string GetTrackbarName(const int i)
{
constexpr auto unit_name = " Hz level [-dB]";
const auto trackbar_name = std::to_string(frequencies[i]) + unit_name;
return trackbar_name;
}
static void TrackbarEvent(const int, void* user_data)
{
auto &data = *(static_cast<audio_data*>(user_data));
if (data.player.IsPlaying())
data.player.Stop();
int levels_percent[2];
for (const auto &i : {0, 1})
{
levels_percent[i] = cv::getTrackbarPos(GetTrackbarName(i), data.window_name);
const auto amplitude = comutils::GetValueFromLevel(-levels_percent[i], 1); //Interpret trackbar position as (negative) level in dB (due to attenuation). The reference value is 1 since the amplitude is specified relatively, i.e., between 0 and 1.
data.generators[i].SetAmplitude(amplitude);
}
data.player.Play(data.mixer);
const cv::Mat wave_image = PlotWaves(data);
const cv::Mat spectrum_image = PlotSpectrum(levels_percent);
const cv::Mat combined_image = imgutils::CombineImages({wave_image, spectrum_image}, imgutils::CombinationMode::Horizontal);
cv::imshow(data.window_name, combined_image);
}
static void ShowControls()
{
constexpr auto window_name = "Attenuation";
cv::namedWindow(window_name);
cv::moveWindow(window_name, 0, 0);
static audio_data data(window_name); //Make variable global so that it is not destroyed after the function returns (for the variable is needed later)
for (const auto &i : {0, 1})
{
const auto trackbar_name = GetTrackbarName(i);
cv::createTrackbar(trackbar_name, data.window_name, nullptr, 100, TrackbarEvent, static_cast<void*>(&data));
}
cv::createButton("Mute", [](const int, void * const user_data)
{
auto &data = *(static_cast<audio_data*>(user_data));
if (data.player.IsPlayingBack())
data.player.Pause();
else
data.player.Resume();
}, static_cast<void*>(&data), cv::QT_CHECKBOX);
cv::setTrackbarPos(GetTrackbarName(0), window_name, 0);
cv::setTrackbarPos(GetTrackbarName(1), window_name, 20); //Implies cv::imshow with second level at -20 dB
}
int main(const int argc, const char * const argv[])
{
if (argc != 1)
{
std::cout << "Illustrates frequency masking at different intensities." << std::endl;
std::cout << "Usage: " << argv[0] << std::endl;
return 1;
}
ShowControls();
cv::waitKey(0);
return 0;
}
| 45.816176
| 342
| 0.690258
|
dustsigns
|
049e5f828dfac3302190a5b1bd540fe1757e9e99
| 5,566
|
cc
|
C++
|
elements/tcp/tcpprocesstxt.cc
|
leeopop/ClickNF
|
5bca7586195d1b24d3a899fa084feafa93f81790
|
[
"MIT"
] | 32
|
2017-11-02T12:33:21.000Z
|
2022-02-07T22:25:58.000Z
|
elements/tcp/tcpprocesstxt.cc
|
leeopop/ClickNF
|
5bca7586195d1b24d3a899fa084feafa93f81790
|
[
"MIT"
] | 2
|
2019-02-18T08:47:16.000Z
|
2019-05-24T14:41:23.000Z
|
elements/tcp/tcpprocesstxt.cc
|
leeopop/ClickNF
|
5bca7586195d1b24d3a899fa084feafa93f81790
|
[
"MIT"
] | 10
|
2018-06-13T11:54:53.000Z
|
2020-09-08T06:52:43.000Z
|
/*
* tcpprocesstxt.{cc,hh} -- Process data in TCP packet
* Rafael Laufer, Massimo Gallo
*
* Copyright (c) 2017 Nokia Bell Labs
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*
*/
#include <click/config.h>
#include <click/args.hh>
#include <clicknet/ip.h>
#include <clicknet/tcp.h>
#include "tcpprocesstxt.hh"
#include "tcpstate.hh"
#include "tcpinfo.hh"
#include "util.hh"
CLICK_DECLS
TCPProcessTxt::TCPProcessTxt()
{
}
Packet *
TCPProcessTxt::smaction(Packet *p)
{
TCPState *s = TCP_STATE_ANNO(p);
const click_ip *ip = p->ip_header();
const click_tcp *th = p->tcp_header();
click_assert(s && ip && th);
// Get data length
uint16_t len = TCP_LEN(ip, th);
// RFC 793:
// "sixth, check the URG bit (ignored)"
//
// "seventh, process the segment text"
switch (s->state) {
case TCP_ESTABLISHED:
case TCP_FIN_WAIT1:
case TCP_FIN_WAIT2:
// "Once in the ESTABLISHED state, it is possible to deliver segment
// text to user RECEIVE buffers. Text from segments can be moved
// into buffers until either the buffer is full or the segment is
// empty. If the segment empties and carries an PUSH flag, then
// the user is informed, when the buffer is returned, that a PUSH
// has been received.
//
// When the TCP takes responsibility for delivering the data to the
// user it must also acknowledge the receipt of the data.
//
// Once the TCP takes responsibility for the data it advances
// RCV.NXT over the data accepted, and adjusts RCV.WND as
// apporopriate to the current buffer availability. The total of
// RCV.NXT and RCV.WND should not be reduced.
//
// Please note the window management suggestions in section 3.7.
//
// Send an acknowledgment of the form:
//
// <SEQ=SND.NXT><ACK=RCV.NXT><CTL=ACK>
//
// This acknowledgment should be piggybacked on a segment being
// transmitted if possible without incurring undue delay."
// Make sure sequence number is correct
click_assert(TCP_SEQ(th) == s->rcv_nxt);
// If packet has data, add it to RX queue
if (len > 0) {
// Break segment chain for cloned packet (only header needed)
Packet *q = p->seg_split();
// Clone packet
Packet *c = p->clone();
// Concatenate segment chain again
if (q)
p->seg_join(q);
// Strip IP/TCP headers of the original packet
p->pull((ip->ip_hl + th->th_off) << 2);
// Insert original packet into RX queue, one segment at a time
while (p) {
q = p->seg_split();
s->rxq.push_back(p);
p = q;
}
// Adjust receive variables
s->rcv_nxt += len;
s->rcv_wnd -= len;
// If more buffered segments are coming, do not send an ACK
if (!TCP_MS_FLAG_ANNO(c)) {
#if HAVE_TCP_DELAYED_ACK
// If ACK flag is set, this is the last segment of a batch that
// fills a gap, send ACK acknowledging everything immmediately
if (TCP_ACK_FLAG_ANNO(c) || s->delayed_ack_timer.scheduled() ||
len >= ((s->rcv_mss - (s->snd_ts_ok ? 12 : 0)) << 1)) {
s->delayed_ack_timer.unschedule();
SET_TCP_ACK_FLAG_ANNO(c);
}
else {
uint32_t timeout = MIN(TCP_DELAYED_ACK, TCP_RTO_MIN >> 1);
Timestamp now = c->timestamp_anno();
if (now) {
Timestamp tmo = now + Timestamp::make_msec(timeout);
s->delayed_ack_timer.schedule_at_steady(tmo);
}
else
s->delayed_ack_timer.schedule_after_msec(timeout);
}
#else
// Without delayed ACK, send an ACK for every new data packet
SET_TCP_ACK_FLAG_ANNO(c);
#endif
}
// Wake user task
s->wake_up(TCP_WAIT_RXQ_NONEMPTY);
// Send the clone to be slaughtered
return c;
}
break;
case TCP_CLOSE_WAIT:
case TCP_CLOSING:
case TCP_LAST_ACK:
case TCP_TIME_WAIT:
// "This should not occur, since a FIN has been received from the
// remote side. Ignore the segment text."
break;
default:
assert(0);
}
return p;
}
void
TCPProcessTxt::push(int, Packet *p)
{
if (Packet *q = smaction(p))
output(0).push(q);
}
Packet *
TCPProcessTxt::pull(int)
{
if (Packet *p = input(0).pull())
return smaction(p);
else
return NULL;
}
CLICK_ENDDECLS
EXPORT_ELEMENT(TCPProcessTxt)
| 30.922222
| 148
| 0.699784
|
leeopop
|
049eedd4d9d62aeb732880e6cbf42ba97765e728
| 1,965
|
hpp
|
C++
|
libs/renderer/include/sge/renderer/occlusion_query/object.hpp
|
cpreh/spacegameengine
|
313a1c34160b42a5135f8223ffaa3a31bc075a01
|
[
"BSL-1.0"
] | 2
|
2016-01-27T13:18:14.000Z
|
2018-05-11T01:11:32.000Z
|
libs/renderer/include/sge/renderer/occlusion_query/object.hpp
|
cpreh/spacegameengine
|
313a1c34160b42a5135f8223ffaa3a31bc075a01
|
[
"BSL-1.0"
] | null | null | null |
libs/renderer/include/sge/renderer/occlusion_query/object.hpp
|
cpreh/spacegameengine
|
313a1c34160b42a5135f8223ffaa3a31bc075a01
|
[
"BSL-1.0"
] | 3
|
2018-05-11T01:11:34.000Z
|
2021-04-24T19:47:45.000Z
|
// Copyright Carl Philipp Reh 2006 - 2019.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef SGE_RENDERER_OCCLUSION_QUERY_OBJECT_HPP_INCLUDED
#define SGE_RENDERER_OCCLUSION_QUERY_OBJECT_HPP_INCLUDED
#include <sge/core/detail/class_symbol.hpp>
#include <sge/renderer/detail/symbol.hpp>
#include <sge/renderer/occlusion_query/blocking_wait.hpp>
#include <sge/renderer/occlusion_query/object_fwd.hpp>
#include <sge/renderer/occlusion_query/optional_pixel_count_fwd.hpp>
#include <fcppt/nonmovable.hpp>
namespace sge::renderer::occlusion_query
{
class SGE_CORE_DETAIL_CLASS_SYMBOL object
{
FCPPT_NONMOVABLE(object);
protected:
SGE_RENDERER_DETAIL_SYMBOL
object();
public:
SGE_RENDERER_DETAIL_SYMBOL
virtual ~object();
/**
\brief Begins the query
Every pixel that passes the depth test starting from here on
will increase the result value by one.
*/
virtual void begin() = 0;
/**
\brief Stops the query
The result can then be obtained using the <code>result()</code>
function.
*/
virtual void end() = 0;
/**
\brief Returns the result of the query, if available
After a call to <code>end()</code> the result can be obtained using
this function. \a block specifies if the implementation should block
while waiting for the result. If \a block is false and the result is
not available, then the function returns an empty optional. Note, that
even with \a block set to true, the return value can still be empty. In
such a case, the issued query must be restarted.
\param block Whether the wait should block
\return The number of pixels that passed the depth test or an empty
optional if the result could not be obtained
*/
[[nodiscard]] virtual sge::renderer::occlusion_query::optional_pixel_count
result(sge::renderer::occlusion_query::blocking_wait block) const = 0;
};
}
#endif
| 28.478261
| 76
| 0.759796
|
cpreh
|
04a06b3c1d48aa821465a10b4f68da138e373563
| 3,596
|
cpp
|
C++
|
src/Transform.cpp
|
gmryuuko/CG-FPSGame
|
816da7cc491cccb062d56863fa8266fda67066f9
|
[
"MIT"
] | null | null | null |
src/Transform.cpp
|
gmryuuko/CG-FPSGame
|
816da7cc491cccb062d56863fa8266fda67066f9
|
[
"MIT"
] | null | null | null |
src/Transform.cpp
|
gmryuuko/CG-FPSGame
|
816da7cc491cccb062d56863fa8266fda67066f9
|
[
"MIT"
] | null | null | null |
#include "Transform.h"
#include <glm/gtx/string_cast.hpp>
using namespace std;
using namespace glm;
Transform::Transform(const Transform& transform) {
this->position = transform.position;
this->rotation = transform.rotation;
this->scale = transform.scale;
SetDirty();
}
Transform::Transform(vec3 position, vec3 rotation, vec3 scale) {
this->position = position;
this->rotation = rotation;
this->scale = scale;
SetDirty();
}
void Transform::UpdateModelMatrix() {
// 位移矩阵
translateMatrix = translate(mat4(1), position);
// 旋转矩阵,内旋顺序Z-Y-X,相当于外旋顺序X-Y-Z
mat4 rx = rotate(mat4(1), radians(rotation.x), vec3(1, 0, 0));
mat4 ry = rotate(mat4(1), radians(rotation.y), vec3(0, 1, 0));
mat4 rz = rotate(mat4(1), radians(rotation.z), vec3(0, 0, 1));
rotationMatrix = rz * ry * rx;
// 缩放矩阵
scaleMatrix = glm::scale(mat4(1), scale);
// model matrix,缩放->旋转->位移
modelMatrix = translateMatrix * rotationMatrix * scaleMatrix * mat4(1);
// local 坐标轴
axisX = rotationMatrix * vec4(1, 0, 0, 0);
axisY = rotationMatrix * vec4(0, 1, 0, 0);
axisZ = rotationMatrix * vec4(0, 0, 1, 0);
if (parent != nullptr) {
modelMatrix = parent->GetTranslateMatrix() * parent->GetRotationMatrix() * modelMatrix;
}
// inverse model matrix
inverseModelMatrix = glm::inverse(modelMatrix);
dirty = false;
}
void Transform::SetDirty() {
if (!dirty) {
dirty = true;
for (auto child : children) {
child->SetDirty();
}
}
}
void Transform::CheckDirty() {
if (dirty) {
UpdateModelMatrix();
}
}
mat4 Transform::GetModelMatrix() {
CheckDirty();
return modelMatrix;
}
mat4 Transform::GetTranslateMatrix() {
CheckDirty();
return translateMatrix;
}
mat4 Transform::GetRotationMatrix() {
CheckDirty();
return rotationMatrix;
}
mat4 Transform::GetScaleMatrix() {
CheckDirty();
return scaleMatrix;
}
glm::mat4 Transform::GetInverseModelMatrix() {
CheckDirty();
return inverseModelMatrix;
}
void Transform::SetPosition(const vec3& position) {
this->position = position;
SetDirty();
}
void Transform::SetRotation(const vec3& rotation) {
this->rotation = rotation;
SetDirty();
}
void Transform::SetScale(const vec3& scale) {
this->scale = scale;
SetDirty();
}
vec3 Transform::GetPosition() const {
return position;
}
vec3 Transform::GetRotation() const {
return rotation;
}
vec3 Transform::GetScale() const {
return scale;
}
void Transform::SetParent(Transform* parent) {
if (this->parent != nullptr) {
RemoveParent();
}
if (parent == nullptr) return;
this->parent = parent;
parent->children.emplace_back(this);
SetDirty();
}
void Transform::RemoveParent() {
if (parent != nullptr) {
for (vector<Transform*>::iterator i = parent->children.begin();
i != parent->children.end(); i++) {
if (*i == this) {
parent->children.erase(i);
break;
}
}
parent = nullptr;
SetDirty();
}
}
vec3 Transform::GetAxisX() {
CheckDirty();
return axisX;
}
vec3 Transform::GetAxisY() {
CheckDirty();
return axisY;
}
vec3 Transform::GetAxisZ() {
CheckDirty();
return axisZ;
}
void Transform::Translate(const vec3& direction, float distance) {
vec3 move = normalize(direction) * distance;
// cout << glm::to_string(move) << std::endl;
position += move;
SetDirty();
}
void Transform::RotateX(float pitch, bool limit, float lower, float upper) {
rotation.x += pitch;
if (limit) {
if (rotation.x > upper)
rotation.x = upper;
if (rotation.x < lower)
rotation.x = lower;
}
SetDirty();
}
void Transform::RotateY(float yaw) {
rotation.y += yaw;
SetDirty();
}
void Transform::RotateZ(float roll) {
rotation.z += roll;
SetDirty();
}
| 19.650273
| 89
| 0.679088
|
gmryuuko
|
04a07df482a821a82f2b19ce3cbe2239bbe37d2a
| 525
|
cpp
|
C++
|
niuke_HW/ds_zuo/7_10_minStrength.cpp
|
drt4243566/leetcode_learn
|
ef51f215079556895eec2252d84965cd1c3a7bf4
|
[
"MIT"
] | null | null | null |
niuke_HW/ds_zuo/7_10_minStrength.cpp
|
drt4243566/leetcode_learn
|
ef51f215079556895eec2252d84965cd1c3a7bf4
|
[
"MIT"
] | null | null | null |
niuke_HW/ds_zuo/7_10_minStrength.cpp
|
drt4243566/leetcode_learn
|
ef51f215079556895eec2252d84965cd1c3a7bf4
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <queue>
using namespace std;
int main(){
int M;
cin>>M;
priority_queue<int,vector<int>,greater<int>> minHeap;
int n;
for(int i=0;i<M;i++){
cin>>n;
minHeap.push(n);
}
int sum = 0;
int heap1,heap2;
while(minHeap.size()>1){
heap1 = minHeap.top();
minHeap.pop();
heap2 = minHeap.top();
minHeap.pop();
sum = sum + heap1 + heap2;
minHeap.push(heap1+heap2);
}
cout<<sum<<endl;
return 0;
}
| 18.75
| 57
| 0.52381
|
drt4243566
|
04a18154b58766a2f939d75309b479aa14fbd49e
| 293
|
cpp
|
C++
|
cpp/cinexample.cpp
|
Mysterypancake1/GMod-Fun
|
d57e69f88691f679fbb3a1fb14eeb44466287cfc
|
[
"MIT"
] | 24
|
2017-07-20T12:33:15.000Z
|
2022-03-09T06:13:13.000Z
|
cpp/cinexample.cpp
|
Mysterypancake1/GMod-Fun
|
d57e69f88691f679fbb3a1fb14eeb44466287cfc
|
[
"MIT"
] | null | null | null |
cpp/cinexample.cpp
|
Mysterypancake1/GMod-Fun
|
d57e69f88691f679fbb3a1fb14eeb44466287cfc
|
[
"MIT"
] | 8
|
2017-12-06T04:13:19.000Z
|
2020-05-25T13:01:01.000Z
|
#include <iostream>
using namespace std;
int main()
{
string firstName, lastName;
cout << "Please type your first and last name: \n";
cin >> firstName >> lastName;
cout << "First name is " << firstName << '\n';
cout << "Last name is " << lastName << '\n';
return 0;
}
| 18.3125
| 53
| 0.587031
|
Mysterypancake1
|
04a1e222ef9a66d5a04b153c56f03f70ab34f351
| 1,366
|
hh
|
C++
|
server/modules/filter/dbfwfilter/test/tempfile.hh
|
sdrik/MaxScale
|
c6c318b36dde0a25f22ac3fd59c9d33d774fe37a
|
[
"BSD-3-Clause"
] | null | null | null |
server/modules/filter/dbfwfilter/test/tempfile.hh
|
sdrik/MaxScale
|
c6c318b36dde0a25f22ac3fd59c9d33d774fe37a
|
[
"BSD-3-Clause"
] | null | null | null |
server/modules/filter/dbfwfilter/test/tempfile.hh
|
sdrik/MaxScale
|
c6c318b36dde0a25f22ac3fd59c9d33d774fe37a
|
[
"BSD-3-Clause"
] | null | null | null |
/*
* Copyright (c) 2018 MariaDB Corporation Ab
*
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file and at www.mariadb.com/bsl11.
*
* Change Date: 2026-01-04
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2 or later of the General
* Public License.
*/
#pragma once
#include <string>
/**
* TempFile is a class using which a temporary file can be created and
* written to.
*/
class TempFile
{
TempFile(const TempFile&);
TempFile& operator=(const TempFile&);
public:
/**
* Constructor
*
* Create temporary file in /tmp
*/
TempFile();
/**
* Destructor
*
* Close and unlink file.
*/
~TempFile();
/**
* The name of the created temporary file.
*
* @return The name of the file.
*/
std::string name() const
{
return m_name;
}
/**
* Write data to the file.
*
* @param pData Pointer to data.
* @param count The number of bytes to write.
*/
void write(const void* pData, size_t count);
/**
* Write data to the file.
*
* @param zData Null terminated buffer to write.
*/
void write(const char* zData);
private:
int m_fd;
std::string m_name;
};
| 19.514286
| 75
| 0.597365
|
sdrik
|
04a238c3449a39e4e251d6f4dc7f4821c7dc39fd
| 4,806
|
cpp
|
C++
|
src/server/SoundManager.cpp
|
paps/Open-Trading
|
b62f85f391be9975a161713f87aeff0cae0a1e37
|
[
"BSD-2-Clause"
] | 23
|
2015-07-24T15:45:36.000Z
|
2021-11-23T15:35:33.000Z
|
src/server/SoundManager.cpp
|
paps/Open-Trading
|
b62f85f391be9975a161713f87aeff0cae0a1e37
|
[
"BSD-2-Clause"
] | null | null | null |
src/server/SoundManager.cpp
|
paps/Open-Trading
|
b62f85f391be9975a161713f87aeff0cae0a1e37
|
[
"BSD-2-Clause"
] | 21
|
2015-07-12T16:42:01.000Z
|
2020-08-23T22:56:50.000Z
|
// The Open Trading Project - open-trading.org
//
// Copyright (c) 2011 Martin Tapia - martin.tapia@open-trading.org
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "SoundManager.hpp"
#define CLASS "[Server/SoundManager] "
#ifdef CMAKE_FMODEX
#include "Gui.hpp"
#include "sound/SoundSystem.hpp"
#include "Logger.hpp"
#include "tools/ToString.hpp"
#include "Server.hpp"
#include "conf/Conf.hpp"
namespace Server
{
SoundManager::SoundManager(Gui& gui) :
_gui(gui)
{
Conf::Conf& conf = this->_gui.GetServer().GetConf();
this->_soundLogger = new Logger(this->_gui, conf.Read<bool>("soundLogToUi", true), conf.Read<bool>("soundLogToStdOut", false));
this->_soundSystem = new Sound::SoundSystem(conf.Read<bool>("debugSound", false), *this->_soundLogger);
this->_soundLogger->Log(CLASS "Compiled with sound support (\"" CMAKE_FMODEX "\").");
// Sounds Id Path Enabled
this->_AddSound(SoundError, conf.Read<std::string>("soundPathError", "error.wav"), conf.Read<bool>("soundEnableError", true));
this->_AddSound(SoundWarning, conf.Read<std::string>("soundPathWarning", "warning.wav"), conf.Read<bool>("soundEnableWarning", true));
this->_AddSound(SoundUp, conf.Read<std::string>("soundPathUp", "up.wav"), conf.Read<bool>("soundEnableUp", true));
}
SoundManager::~SoundManager()
{
std::map<int, SoundEntity*>::iterator it = this->_sounds.begin();
std::map<int, SoundEntity*>::iterator itEnd = this->_sounds.end();
for (; it != itEnd; ++it)
{
this->_soundSystem->UnloadSound(it->second->sound);
delete it->second;
}
delete this->_soundSystem;
delete this->_soundLogger;
}
void SoundManager::EnableSound(int id, bool enable)
{
std::map<int, SoundEntity*>::iterator it = this->_sounds.find(id);
if (it == this->_sounds.end())
this->_soundLogger->Log(CLASS "Invalid sound id " + Tools::ToString(id) + ".", ::Logger::Warning);
else
it->second->enabled = enable;
}
void SoundManager::PlaySound(int id)
{
std::map<int, SoundEntity*>::iterator it = this->_sounds.find(id);
if (it == this->_sounds.end())
this->_soundLogger->Log(CLASS "Invalid sound id " + Tools::ToString(id) + ".", ::Logger::Warning);
else if (it->second->enabled)
this->_soundSystem->PlaySound(it->second->sound);
}
void SoundManager::_AddSound(int id, std::string const& path, bool enabled)
{
SoundEntity* s = new SoundEntity;
s->enabled = enabled;
this->_soundSystem->LoadSound(s->sound, path);
this->_sounds[id] = s;
}
}
#else
#include "Server.hpp"
#include "Gui.hpp"
#include "Logger.hpp"
#include "conf/Conf.hpp"
namespace Server
{
SoundManager::SoundManager(Gui& gui) :
_gui(gui)
{
Conf::Conf& conf = this->_gui.GetServer().GetConf();
this->_soundLogger = new Logger(this->_gui, conf.Read<bool>("soundLogToUi", true), conf.Read<bool>("soundLogToStdOut", false));
this->_soundLogger->Log(CLASS "Not compiled with sound support.");
}
SoundManager::~SoundManager()
{
delete this->_soundLogger;
}
void SoundManager::PlaySound(int)
{
}
void SoundManager::EnableSound(int, bool)
{
}
}
#endif
| 36.687023
| 150
| 0.648148
|
paps
|
04a2a3da1808cb6f8ee140dbb3a5c3407b6e0537
| 890
|
cpp
|
C++
|
Intuit/minimum_swaps.cpp
|
pilipi-puu-puu/6companies30Days
|
9dd3e60f06a6e09483f64b79ccf918a6dd725239
|
[
"MIT"
] | 3
|
2022-01-09T13:16:32.000Z
|
2022-01-25T15:23:44.000Z
|
Intuit/minimum_swaps.cpp
|
pilipi-puu-puu/6companies30Days
|
9dd3e60f06a6e09483f64b79ccf918a6dd725239
|
[
"MIT"
] | null | null | null |
Intuit/minimum_swaps.cpp
|
pilipi-puu-puu/6companies30Days
|
9dd3e60f06a6e09483f64b79ccf918a6dd725239
|
[
"MIT"
] | 1
|
2022-01-08T09:47:13.000Z
|
2022-01-08T09:47:13.000Z
|
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
class Solution
{
public:
int minSwaps(vector<vector<int>> &grid)
{
int n = grid.size();
vector<int> countArr;
for (int i = 0; i < n; i++)
{
int count = 0;
for (int j = n - 1; j >= 0; j--)
{
if (grid[i][j] == 0)
count++;
else
break;
}
countArr.push_back(count);
}
int swaps = 0;
for (int i = 0; i < n; i++)
{
if (countArr[i] >= n - i - 1)
continue;
int j = i + 1;
while (j < n)
{
if (countArr[j] >= n - i - 1)
break;
j++;
}
if (j == n)
return -1;
while (i < j)
{
swaps++;
swap(countArr[j], countArr[j - 1]);
j--;
}
}
return swaps;
}
};
| 17.115385
| 44
| 0.379775
|
pilipi-puu-puu
|
04aae9cb9223518f20b06a82289166f7055cf7dd
| 12,898
|
cpp
|
C++
|
firmware/Vscode_PlatformIO_Proj/Hex_Link_Nano/src/ASW/Motion_Detect.cpp
|
Ualker/HEX-LINK
|
93ef659c047a7e8556d0c49123d6455db8dba929
|
[
"MulanPSL-1.0"
] | 181
|
2021-07-01T06:22:16.000Z
|
2022-03-30T05:07:23.000Z
|
firmware/Vscode_PlatformIO_Proj/Hex_Link_Nano/src/ASW/Motion_Detect.cpp
|
Ualker/HEX-LINK
|
93ef659c047a7e8556d0c49123d6455db8dba929
|
[
"MulanPSL-1.0"
] | 1
|
2021-07-15T06:24:40.000Z
|
2021-07-27T17:50:28.000Z
|
firmware/Vscode_PlatformIO_Proj/Hex_Link_Nano/src/ASW/Motion_Detect.cpp
|
Ualker/HEX-LINK
|
93ef659c047a7e8556d0c49123d6455db8dba929
|
[
"MulanPSL-1.0"
] | 25
|
2021-07-03T06:29:54.000Z
|
2022-02-04T11:43:38.000Z
|
#include "Universal_Headers.h"
#include "IMU.h"
#include "COM.h"
#include "ISR.h"
#include "Motion_Detect.h"
bool Action_Found = false;
uint8_t Silent_Count = SILENT_VALVE;
#define LEFT_VALVE_ACX 131
#define RIGHT_VALVE_ACX 124
#define JUMP_VALVE_ACZ 130
const Ellipse_Para_Type Ctrl_Ellipse = {185,130,25,35,150};/* x_0,y_0,a,b,Theta */
const Ellipse_Para_Type Hook_Ellipse = {120,176,25,20,0};
const Ellipse_Para_Type Attack_Ellipse = {115,69,16,30,118};
const Ellipse_Para_Type Defend_Ellipse = {81,141,12,20,109};
const Ellipse_Para_Type Aim_Ellipse = {80,120,15,10,10};
#define WALK_VALVE 25
#define RUN_VALVE 14
#define TOOL_USE_VALVE 132
#define TOOL_UNUSE_VALVE 123
#define TOOL_CONTINUS_VALVE 5
Std_ReturnType Fit_Ellipse(float x, float y, const Ellipse_Para_Type * Elli_Para){
Std_ReturnType Ret_Val = false;
float Fit_Result = 0;
Fit_Result = (pow(((x-Elli_Para->x_0)*cos(Elli_Para->Theta/180*3.14159) + (y-Elli_Para->y_0)*sin(Elli_Para->Theta/180*3.14159)),2)/pow((Elli_Para->a),2)
+
pow((-1*(x-Elli_Para->x_0)*sin(Elli_Para->Theta/180*3.14159) + (y-Elli_Para->y_0)*cos(Elli_Para->Theta/180*3.14159)),2)/pow((Elli_Para->a),2));
if(Fit_Result<=1){
Ret_Val = true;
Serial.println(Fit_Result);
}
return Ret_Val;
}
void Prv_Init_Data(void){
for(uint8_t index = 0; index < IMU_DATA_BATCH;index ++){
Prv_AcData[index].AcX = IMU_DATA_INIT_VALUE;
Prv_AcData[index].AcY = IMU_DATA_INIT_VALUE;
Prv_AcData[index].AcZ = IMU_DATA_INIT_VALUE;
Prv_GyData[index].GyX = IMU_DATA_INIT_VALUE;
Prv_GyData[index].GyY = IMU_DATA_INIT_VALUE;
Prv_GyData[index].GyZ = IMU_DATA_INIT_VALUE;
}
}
void Prv_Max_Data(IMU_AcData_Type * OutAcData,IMU_GyData_Type * OutGyData){
uint8_t temVal_x;
uint8_t temVal_y;
uint8_t temVal_z;
temVal_x = 0;temVal_y = 0;temVal_y = 0;
for(uint8_t index = 0; index < IMU_DATA_BATCH;index ++){
if(Prv_AcData[index].AcX > temVal_x)temVal_x = Prv_AcData[index].AcX;
if(Prv_AcData[index].AcY > temVal_y)temVal_y = Prv_AcData[index].AcY;
if(Prv_AcData[index].AcZ > temVal_z)temVal_z = Prv_AcData[index].AcZ;
}
OutAcData->AcX = temVal_x;OutAcData->AcY = temVal_y;OutAcData->AcZ = temVal_z;
temVal_x = 0;temVal_y = 0;temVal_y = 0;
for(uint8_t index = 0; index < IMU_DATA_BATCH;index ++){
if(Prv_GyData[index].GyX > temVal_x)temVal_x = Prv_GyData[index].GyX;
if(Prv_GyData[index].GyY > temVal_y)temVal_y = Prv_GyData[index].GyY;
if(Prv_GyData[index].GyZ > temVal_z)temVal_z = Prv_GyData[index].GyZ;
}
OutGyData->GyX = temVal_x;OutGyData->GyY = temVal_y;OutGyData->GyZ = temVal_z;
}
void Prv_Min_Data(IMU_AcData_Type * OutAcData,IMU_GyData_Type * OutGyData){
uint8_t temVal_x;
uint8_t temVal_y;
uint8_t temVal_z;
temVal_x = 255;temVal_y = 255;temVal_y = 255;
for(uint8_t index = 0; index < IMU_DATA_BATCH;index ++){
if(Prv_AcData[index].AcX < temVal_x)temVal_x = Prv_AcData[index].AcX;
if(Prv_AcData[index].AcY < temVal_y)temVal_y = Prv_AcData[index].AcY;
if(Prv_AcData[index].AcZ < temVal_z)temVal_z = Prv_AcData[index].AcZ;
}
OutAcData->AcX = temVal_x;OutAcData->AcY = temVal_y;OutAcData->AcZ = temVal_z;
temVal_x = 0;temVal_y = 0;temVal_y = 0;
for(uint8_t index = 0; index < IMU_DATA_BATCH;index ++){
if(Prv_GyData[index].GyX < temVal_x)temVal_x = Prv_GyData[index].GyX;
if(Prv_GyData[index].GyY < temVal_y)temVal_y = Prv_GyData[index].GyY;
if(Prv_GyData[index].GyZ < temVal_z)temVal_z = Prv_GyData[index].GyZ;
}
OutGyData->GyX = temVal_x;OutGyData->GyY = temVal_y;OutGyData->GyZ = temVal_z;
}
void Prv_Ave_Data(IMU_AcData_Type * OutAcData,IMU_GyData_Type * OutGyData){
int16_t AcX_Sum = 0;
int16_t AcY_Sum = 0;
int16_t AcZ_Sum = 0;
int16_t GyX_Sum = 0;
int16_t GyY_Sum = 0;
int16_t GyZ_Sum = 0;
for(uint8_t index = 0; index < IMU_DATA_BATCH;index ++){
AcX_Sum += Prv_AcData[index].AcX;
AcY_Sum += Prv_AcData[index].AcY;
AcZ_Sum += Prv_AcData[index].AcZ;
GyX_Sum += Prv_GyData[index].GyX;
GyY_Sum += Prv_GyData[index].GyY;
GyZ_Sum += Prv_GyData[index].GyZ;
}
OutAcData->AcX = AcX_Sum/IMU_DATA_BATCH;
OutAcData->AcY = AcY_Sum/IMU_DATA_BATCH;
OutAcData->AcZ = AcZ_Sum/IMU_DATA_BATCH;
OutGyData->GyX = GyX_Sum/IMU_DATA_BATCH;
OutGyData->GyY = GyY_Sum/IMU_DATA_BATCH;
OutGyData->GyZ = GyZ_Sum/IMU_DATA_BATCH;
}
Std_ReturnType Chest_Motion_Detect(void){
static uint8_t Last_Highest_Point_X = 128;
static uint8_t Last_Lowest_Point_X = 127;
static double Last_Mid_Point_X = 128;
double K_Prv_AcData_X = (Prv_AcData[IMU_DATA_BATCH - 1].AcX - Prv_AcData[0].AcX)/(IMU_DATA_BATCH - 1);
IMU_AcData_Type Tmp_Max_AcData;
IMU_AcData_Type Tmp_Min_AcData;
IMU_GyData_Type Tmp_Max_GyData;
IMU_GyData_Type Tmp_Min_GyData;
IMU_AcData_Type Tmp_Ave_AcData;
IMU_GyData_Type Tmp_Ave_GyData;
Prv_Max_Data(&Tmp_Max_AcData, &Tmp_Max_GyData);
Prv_Min_Data(&Tmp_Min_AcData, &Tmp_Min_GyData);
Prv_Ave_Data(&Tmp_Ave_AcData, &Tmp_Ave_GyData);
if(abs(Tmp_Ave_AcData.AcX - 128)<=1){
Last_Highest_Point_X = 128;
Last_Lowest_Point_X = 128;
if(T_Cmd.Command != CHEST_MID){
T_Cmd.Command = CHEST_MID;
Action_Found = true;
Serial.println("CHEST_MID");
}
return CHEST_MID;
}
if(K_Prv_AcData_X < (Prv_AcData[1].AcX - Prv_AcData[0].AcX) && K_Prv_AcData_X > (Prv_AcData[IMU_DATA_BATCH - 1].AcX - Prv_AcData[IMU_DATA_BATCH - 2].AcX)){
Last_Highest_Point_X = Tmp_Max_AcData.AcX;
}
else if(K_Prv_AcData_X > (Prv_AcData[1].AcX - Prv_AcData[0].AcX) && K_Prv_AcData_X < (Prv_AcData[IMU_DATA_BATCH - 1].AcX - Prv_AcData[IMU_DATA_BATCH - 2].AcX)){
Last_Lowest_Point_X = Tmp_Min_AcData.AcX;
}
Last_Mid_Point_X = (Last_Highest_Point_X + Last_Lowest_Point_X)/2;
if(Last_Mid_Point_X > 0){
if(Last_Mid_Point_X > LEFT_VALVE_ACX){
if(T_Cmd.Command != CHEST_LEFT){
T_Cmd.Command = CHEST_LEFT;
Action_Found = true;
Serial.println("CHEST_LEFT");
}
return CHEST_LEFT;
}
else if(Last_Mid_Point_X < RIGHT_VALVE_ACX){
if(T_Cmd.Command != CHEST_RIGHT){
T_Cmd.Command = CHEST_RIGHT;
Action_Found = true;
Serial.println("CHEST_RIGHT");
}
return CHEST_RIGHT;
}
}
if(T_Cmd.Command != CHEST_MID){
T_Cmd.Command = CHEST_MID;
Action_Found = true;
Serial.println("CHEST_MID");
}
Last_Highest_Point_X = 128;
Last_Lowest_Point_X = 128;
return CHEST_MID;
}
Std_ReturnType Left_Arm_Motion_Detect(void){
IMU_AcData_Type Tmp_Max_AcData;
IMU_AcData_Type Tmp_Min_AcData;
IMU_GyData_Type Tmp_Max_GyData;
IMU_GyData_Type Tmp_Min_GyData;
IMU_AcData_Type Tmp_Ave_AcData;
IMU_GyData_Type Tmp_Ave_GyData;
Prv_Max_Data(&Tmp_Max_AcData, &Tmp_Max_GyData);
Prv_Min_Data(&Tmp_Min_AcData, &Tmp_Min_GyData);
Prv_Ave_Data(&Tmp_Ave_AcData, &Tmp_Ave_GyData);
if(Fit_Ellipse(Tmp_Ave_GyData.GyY,Tmp_Ave_GyData.GyZ,&Ctrl_Ellipse)){
Action_Found = true;
T_Cmd.Command = LEFT_ARM_CTRL;
Serial.println("Ctrl");
return LEFT_ARM_CTRL;
}
if(Fit_Ellipse(Tmp_Ave_GyData.GyY,Tmp_Ave_GyData.GyZ,&Hook_Ellipse)){
Action_Found = true;
T_Cmd.Command = LEFT_ARM_HOOK;
Serial.println("Hook");
return LEFT_ARM_HOOK;
}
return DEFAULT_COMMAND;
}
Std_ReturnType Right_Arm_Motion_Detect(void){
IMU_AcData_Type Tmp_Ave_AcData;
IMU_GyData_Type Tmp_Ave_GyData;
Prv_Ave_Data(&Tmp_Ave_AcData, &Tmp_Ave_GyData);
if(Fit_Ellipse(Tmp_Ave_GyData.GyY,Tmp_Ave_GyData.GyZ,&Attack_Ellipse)){
Action_Found = true;
T_Cmd.Command = RIGHT_ARM_ATTACK;
Serial.println("Attack");
return RIGHT_ARM_ATTACK;
}
if(Fit_Ellipse(Tmp_Ave_GyData.GyY,Tmp_Ave_GyData.GyZ,&Defend_Ellipse)){
Action_Found = true;
T_Cmd.Command = RIGHT_ARM_DEFEND;
Serial.println("Defend");
return RIGHT_ARM_DEFEND;
}
if(Fit_Ellipse(Tmp_Ave_GyData.GyX,Tmp_Ave_GyData.GyZ,&Aim_Ellipse)){
Action_Found = true;
T_Cmd.Command = RIGHT_ARM_TARGET;
Serial.println("Target");
return RIGHT_ARM_TARGET;
}
return DEFAULT_COMMAND;
}
Std_ReturnType Motion_Check_Left_Leg(void){
static uint16_t Last_Record_ISR_Count = 0;
static Motion_Point_Type Motion_Point_Status = MOTION_STAND_POINT;
static uint8_t Continus_High_Speed = 0;
static uint8_t Continus_Low_Speed = 0;
IMU_AcData_Type Tmp_Ave_AcData;
IMU_GyData_Type Tmp_Ave_GyData;
Prv_Ave_Data(&Tmp_Ave_AcData, &Tmp_Ave_GyData);
switch(Motion_Point_Status){
case MOTION_STAND_POINT:
if(Tmp_Ave_GyData.GyZ <= 115){
Motion_Point_Status = MOTION_LOW_POINT;
Last_Record_ISR_Count = ISR_Count;
if(T_Cmd.Command != LEFT_LEG_WALK){
Serial.println("Walk");
T_Cmd.Command = LEFT_LEG_WALK;
Action_Found = true;
}
}
else if(Tmp_Ave_GyData.GyZ >= 135){
Motion_Point_Status = MOTION_HIGH_POINT;
Last_Record_ISR_Count = ISR_Count;
if(T_Cmd.Command != LEFT_LEG_WALK){
Serial.println("Walk");
T_Cmd.Command = LEFT_LEG_WALK;
Action_Found = true;
}
}
break;
case MOTION_LOW_POINT:
if(Tmp_Ave_GyData.GyZ >= 135){
Motion_Point_Status = MOTION_HIGH_POINT;
Serial.println(ISR_Count - Last_Record_ISR_Count);
if(ISR_Count - Last_Record_ISR_Count <= RUN_VALVE){
Continus_Low_Speed = 0;
Continus_High_Speed += 1;
if(Continus_High_Speed == 3){
Continus_High_Speed = 0;
if(T_Cmd.Command != LEFT_LEG_RUN){
Serial.println("Run");
T_Cmd.Command = LEFT_LEG_RUN;
Action_Found = true;
}
}
}
else{
Continus_High_Speed = 0;
Continus_Low_Speed += 1;
if(Continus_Low_Speed == 3){
Continus_Low_Speed = 0;
if(T_Cmd.Command != LEFT_LEG_WALK){
Serial.println("Walk");
T_Cmd.Command = LEFT_LEG_WALK;
Action_Found = true;
}
}
}
Last_Record_ISR_Count = ISR_Count;
}
if(ISR_Count - Last_Record_ISR_Count >= WALK_VALVE){
Motion_Point_Status = MOTION_STAND_POINT;
if(T_Cmd.Command != LEFT_LEG_STOP){
Serial.println("Stopped");
T_Cmd.Command = LEFT_LEG_STOP;
Action_Found = true;
}
}
break;
case MOTION_HIGH_POINT:
if(Tmp_Ave_GyData.GyZ <= 115){
Motion_Point_Status = MOTION_LOW_POINT;
Serial.println(ISR_Count - Last_Record_ISR_Count);
if(ISR_Count - Last_Record_ISR_Count <= RUN_VALVE){
Continus_Low_Speed = 0;
Continus_High_Speed += 1;
if(Continus_High_Speed == 3){
Continus_High_Speed = 0;
if(T_Cmd.Command != LEFT_LEG_RUN){
Serial.println("Run");
T_Cmd.Command = LEFT_LEG_RUN;
Action_Found = true;
}
}
}
else{
Continus_High_Speed = 0;
Continus_Low_Speed += 1;
if(Continus_Low_Speed == 3){
Continus_Low_Speed = 0;
if(T_Cmd.Command != LEFT_LEG_WALK){
Serial.println("Walk");
T_Cmd.Command = LEFT_LEG_WALK;
Action_Found = true;
}
}
}
Last_Record_ISR_Count = ISR_Count;
}
if(ISR_Count - Last_Record_ISR_Count >= WALK_VALVE){
Motion_Point_Status = MOTION_STAND_POINT;
if(T_Cmd.Command != LEFT_LEG_STOP){
Serial.println("Stopped");
T_Cmd.Command = LEFT_LEG_STOP;
Action_Found = true;
}
}
break;
}
return T_Cmd.Command;
}
Std_ReturnType Motion_Check_Tool(void){
IMU_AcData_Type Tmp_Ave_AcData;
IMU_GyData_Type Tmp_Ave_GyData;
static uint8_t Continus_Tool_Use = 0;
static uint8_t Continus_Tool_Unuse = 0;
Prv_Ave_Data(&Tmp_Ave_AcData, &Tmp_Ave_GyData);
if(Tmp_Ave_AcData.AcY > TOOL_USE_VALVE){
Continus_Tool_Use += 1;
Continus_Tool_Unuse = 0;
if(Continus_Tool_Use >= TOOL_CONTINUS_VALVE){
Continus_Tool_Use = 0;
if(T_Cmd.Command != TOOL_USE){
Serial.println("Tool_Use");
T_Cmd.Command = TOOL_USE;
Action_Found = true;
}
return TOOL_USE;
}
}
if(Tmp_Ave_AcData.AcY < TOOL_UNUSE_VALVE){
Continus_Tool_Unuse += 1;
Continus_Tool_Use = 0;
if(Continus_Tool_Unuse >= TOOL_CONTINUS_VALVE){
Continus_Tool_Unuse = 0;
if(T_Cmd.Command != TOOL_UNUSE){
Serial.println("Tool_not_use");
T_Cmd.Command = TOOL_UNUSE;
Action_Found = true;
}
return TOOL_UNUSE;
}
}
return TOOL_UNUSE;
}
| 33.853018
| 162
| 0.667235
|
Ualker
|
04b4fb535ee129f1cbd5d245819f113e1911ac00
| 4,889
|
cpp
|
C++
|
src/game/cm_effect.cpp
|
crmaykish/project-rogue
|
bd1a4a7ed984baddc2844f180257475a09e75ce4
|
[
"MIT"
] | null | null | null |
src/game/cm_effect.cpp
|
crmaykish/project-rogue
|
bd1a4a7ed984baddc2844f180257475a09e75ce4
|
[
"MIT"
] | null | null | null |
src/game/cm_effect.cpp
|
crmaykish/project-rogue
|
bd1a4a7ed984baddc2844f180257475a09e75ce4
|
[
"MIT"
] | null | null | null |
#include <set>
#include <algorithm>
#include "cm_effect.h"
#include "cm_logger.h"
#include "cm_actor.h"
#include "cm_game_world.h"
namespace cm
{
static uint32_t EffectID = 0;
// Effect Map
void EffectMap::Add(EffectTrigger trigger, std::shared_ptr<Effect> effect)
{
Log("Adding effect", LOG_INFO);
if (Effects.find(trigger) == Effects.end())
{
// Create the vector
Effects.emplace(trigger, std::vector<std::shared_ptr<Effect>>());
}
// insert the effect
Effects.at(trigger).emplace_back(std::move(effect));
}
void EffectMap::Remove(uint32_t effectId)
{
Log("Remove effect: " + std::to_string(effectId));
for (auto &e : Effects)
{
e.second.erase(std::remove_if(e.second.begin(),
e.second.end(),
[=](auto &a) { return a->GetId() == effectId; }),
e.second.end());
}
}
// Effect Component
void EffectComponent::TriggerEffects(EffectTrigger trigger, Actor *source, Actor *target, GameWorld *world)
{
if (Effects.find(trigger) == Effects.end())
{
return;
}
for (const auto &e : Effects.at(trigger))
{
e->Use(source, target, world);
}
}
// Effect Base Class
Effect::Effect() : Id(EffectID++) {}
uint32_t Effect::GetId() { return Id; }
// Effect Implementations
void RetaliationEffect::Use(Actor *source, Actor *target, GameWorld *world)
{
Log(source->Name + " retaliates", LOG_INFO);
target->CombatComp->Damage({2, source}, *world);
}
void ExplosionEffect::Use(Actor *source, Actor *target, GameWorld *world)
{
// Set all of the neighboring tiles on fire
auto actor = target != nullptr ? target : source;
auto neighbors = world->GetLevel()->GetNeighbors(actor->Position, true);
for (auto t : neighbors)
{
t->OnFire = t->Flammability;
}
}
void LifeStealEffect::Use(Actor *source, Actor *target, GameWorld *world)
{
Log(source->Name + " steals life from " + target->Name, LOG_INFO);
// TODO: can't steal more life than the target has
target->CombatComp->Damage({2, source}, *world);
source->CombatComp->Heal({2, target}, *world);
}
void HealEffect::Use(Actor *source, Actor *target, GameWorld *world)
{
Log(source->Name + " healing", LOG_INFO);
source->CombatComp->Heal({4}, *world);
}
void SacrificeEffect::Use(Actor *source, Actor *target, GameWorld *world)
{
Log(source->Name + " sacrifices", LOG_INFO);
source->CombatComp->Damage({3}, *world);
}
void LearnAbilityEffect::Use(Actor *source, Actor *target, GameWorld *world)
{
Log(source->Name + " learns random ability", LOG_INFO);
auto freeSlot = source->AbilitiesComp->FreeSlot();
if (freeSlot >= 0)
{
// TODO: make sure the ability is something the actor doesn't already know
source->AbilitiesComp->SetAbility(freeSlot, RandomAbility());
}
}
void PoisonAuraEffect::Use(Actor *source, Actor *target, GameWorld *world)
{
for (auto n : world->GetLevel()->GetNeighbors(source->Position, true))
{
if (n->Walkable)
{
n->Poison = 3;
}
}
}
void ChainLightningEffect::Use(Actor *source, Actor *target, GameWorld *world)
{
// TODO: this is really ugly (and doesn't work)
std::set<Point> hit;
bool done = false;
while (!done && hit.size() < 3)
{
if (target != nullptr)
{
if (target->Friendly != source->Friendly)
{
// Hit this target with lightning then pick a neighbor
target->CombatComp->Damage({5, source}, *world);
hit.insert(target->Position);
// find a neighbor
auto neighbors = world->GetLevel()->GetNeighbors(target->Position, false);
for (auto n : neighbors)
{
target = world->GetActor(n->Position);
if (target != nullptr)
{
if (hit.find(target->Position) == hit.end())
{
break;
}
}
}
// no valid neighbors found
done = true;
}
}
else
{
done = true;
}
}
}
} // namespace cm
| 28.260116
| 111
| 0.506443
|
crmaykish
|
04b6061f2734efd847eca9b3e596dfa359c9bd43
| 1,569
|
cpp
|
C++
|
examples/Client.cpp
|
kadirlua/Socket
|
da6954f3abc2c4b161eb5c84bf9f76150b7b7101
|
[
"MIT"
] | null | null | null |
examples/Client.cpp
|
kadirlua/Socket
|
da6954f3abc2c4b161eb5c84bf9f76150b7b7101
|
[
"MIT"
] | null | null | null |
examples/Client.cpp
|
kadirlua/Socket
|
da6954f3abc2c4b161eb5c84bf9f76150b7b7101
|
[
"MIT"
] | null | null | null |
#include "Client.h"
#include "network/SocketOption.h"
namespace sdk {
namespace application {
using namespace network;
static inline bool callbackInterrupt(void* userdata_ptr)
{
Client* client = reinterpret_cast<Client*>(userdata_ptr);
return client->isInterrupted();
}
Client::Client(std::string ip, int port, network::protocol_type type /*= protocol_type::tcp*/, network::IpVersion ipVer /*= IpVersion::IPv4*/) :
m_socket{std::make_unique<Socket>(port, type, ipVer)}
{
m_socket->setIpAddress(ip);
m_socket->setInterruptCallback(&callbackInterrupt, this);
}
void Client::connectServer()
{
m_socket->connect();
SocketOption<Socket> socketOpt{ *m_socket };
socketOpt.setBlockingMode(1);
m_socket_obj = m_socket->createnewSocket(m_socket->getSocketId());
}
int Client::write(std::initializer_list<char> msg) const
{
return m_socket_obj->write(msg);
}
int Client::write(const char* msg, int msg_size) const
{
return m_socket_obj->write(msg, msg_size);
}
int Client::write(std::string& msg) const
{
return m_socket_obj->write(msg);
}
int Client::write(std::vector<unsigned char>& msg) const
{
return m_socket_obj->write(msg);
}
size_t Client::read(std::vector<unsigned char>& response_msg, int max_size /*= 0*/) const
{
return m_socket_obj->read(response_msg, max_size);
}
size_t Client::read(std::string& message, int max_size /*= 0*/) const
{
return m_socket_obj->read(message, max_size);
}
}
}
| 25.721311
| 147
| 0.668579
|
kadirlua
|
04b60e729572c84a08377baab66beb5f7ec11ae5
| 3,904
|
cpp
|
C++
|
csr_bench/csr_CComp/main.cpp
|
sampollard/graphBIG
|
6d0c1b125ae7e5ec26e04a27f7c327600d6b1036
|
[
"BSD-3-Clause"
] | 61
|
2015-02-13T02:14:21.000Z
|
2022-01-10T08:49:57.000Z
|
csr_bench/csr_CComp/main.cpp
|
sampollard/graphBIG
|
6d0c1b125ae7e5ec26e04a27f7c327600d6b1036
|
[
"BSD-3-Clause"
] | 9
|
2016-02-09T14:58:47.000Z
|
2022-01-11T11:00:10.000Z
|
csr_bench/csr_CComp/main.cpp
|
sampollard/graphBIG
|
6d0c1b125ae7e5ec26e04a27f7c327600d6b1036
|
[
"BSD-3-Clause"
] | 31
|
2015-07-10T01:17:01.000Z
|
2021-10-04T17:34:32.000Z
|
//====== Graph Benchmark Suites ======//
//
#include <vector>
#include <string>
#include <fstream>
#include "common.h"
#include "def.h"
#include "openG.h"
using namespace std;
extern unsigned seq_CC(
uint64_t * vertexlist,
uint64_t * edgelist, uint16_t * vproplist,
uint16_t * labellist,
uint64_t vertex_cnt, uint64_t edge_cnt);
extern unsigned parallel_CC(
uint64_t * vertexlist,
uint64_t * edgelist, uint16_t * vproplist,
uint16_t * labellist,
uint64_t vertex_cnt, uint64_t edge_cnt,
unsigned threadnum);
class vertex_property
{
public:
vertex_property():value(0){}
vertex_property(uint64_t x):value(x){}
uint64_t value;
};
class edge_property
{
public:
edge_property():value(0){}
edge_property(uint64_t x):value(x){}
uint64_t value;
};
typedef openG::extGraph<vertex_property, edge_property> graph_t;
typedef graph_t::vertex_iterator vertex_iterator;
typedef graph_t::edge_iterator edge_iterator;
//==============================================================//
//==============================================================//
void output(vector<uint16_t> & labellist)
{
cout<<"Connected Component Results:\n";
for(size_t i=0;i<labellist.size();i++)
{
cout<<"== vertex "<<i<<": component "<<labellist[i]<<endl;
}
}
//==============================================================//
int main(int argc, char * argv[])
{
graphBIG::print();
cout<<"Benchmark: Connected Component\n";
argument_parser arg;
#ifndef NO_PERF
gBenchPerf_event perf;
if (arg.parse(argc,argv,perf,false)==false)
{
arg.help();
return -1;
}
#else
if (arg.parse(argc,argv,false)==false)
{
arg.help();
return -1;
}
#endif
string path;
arg.get_value("dataset",path);
size_t threadnum;
arg.get_value("threadnum",threadnum);
double t1, t2;
cout<<"loading data... \n";
t1 = timer::get_usec();
string vfile = path + "/vertex.CSR";
string efile = path + "/edge.CSR";
vector<uint64_t> vertexlist, edgelist;
size_t vertex_num, edge_num;
graph_t::load_CSR_Graph(vfile, efile,
vertex_num, edge_num,
vertexlist, edgelist);
t2 = timer::get_usec();
cout<<"== "<<vertex_num<<" vertices "<<edge_num<<" edges\n";
#ifndef ENABLE_VERIFY
cout<<"== time: "<<t2-t1<<" sec\n";
#else
(void)t1;
(void)t2;
#endif
//================================================//
vector<uint16_t> vproplist(vertex_num, 0);
vector<uint16_t> labellist(vertex_num, 0);
//================================================//
unsigned ret=0;
t1 = timer::get_usec();
#ifndef NO_PERF
perf.start();
#endif
//================================================//
if (threadnum==1)
ret = seq_CC(&(vertexlist[0]),
&(edgelist[0]),
&(vproplist[0]),
&(labellist[0]),
vertexlist.size()-1,
edgelist.size());
else
ret = parallel_CC(&(vertexlist[0]),
&(edgelist[0]),
&(vproplist[0]),
&(labellist[0]),
vertexlist.size()-1,
edgelist.size(),
threadnum);
//================================================//
#ifndef NO_PERF
perf.stop();
#endif
t2 = timer::get_usec();
cout<<"\nCC finish: \n";
cout<<"== component: "<<ret<<endl;
cout<<"== thread num: "<<threadnum<<endl;
cout<<"== "<<vertex_num<<" vertices "<<edge_num<<" edges\n";
#ifndef ENABLE_VERIFY
cout<<"== time: "<<t2-t1<<" sec\n";
#ifndef NO_PERF
perf.print();
#endif
#endif
#ifdef ENABLE_OUTPUT
cout<<"\n";
output(labellist);
#endif
cout<<"==================================================================\n";
return 0;
} // end main
| 23.377246
| 81
| 0.511527
|
sampollard
|
04b8ca321f906a13d2c667d264973eead6237aa4
| 1,376
|
hpp
|
C++
|
include/UnityEngine/UI/ILayoutSelfController.hpp
|
RedBrumbler/virtuoso-codegen
|
e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3
|
[
"Unlicense"
] | null | null | null |
include/UnityEngine/UI/ILayoutSelfController.hpp
|
RedBrumbler/virtuoso-codegen
|
e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3
|
[
"Unlicense"
] | null | null | null |
include/UnityEngine/UI/ILayoutSelfController.hpp
|
RedBrumbler/virtuoso-codegen
|
e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3
|
[
"Unlicense"
] | 1
|
2022-03-30T21:07:35.000Z
|
2022-03-30T21:07:35.000Z
|
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: UnityEngine.UI.ILayoutController
#include "UnityEngine/UI/ILayoutController.hpp"
// Completed includes
// Type namespace: UnityEngine.UI
namespace UnityEngine::UI {
// Forward declaring type: ILayoutSelfController
class ILayoutSelfController;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::UnityEngine::UI::ILayoutSelfController);
DEFINE_IL2CPP_ARG_TYPE(::UnityEngine::UI::ILayoutSelfController*, "UnityEngine.UI", "ILayoutSelfController");
// Type namespace: UnityEngine.UI
namespace UnityEngine::UI {
// Size: 0x10
#pragma pack(push, 1)
// Autogenerated type: UnityEngine.UI.ILayoutSelfController
// [TokenAttribute] Offset: FFFFFFFF
class ILayoutSelfController/*, public ::UnityEngine::UI::ILayoutController*/ {
public:
// Creating interface conversion operator: operator ::UnityEngine::UI::ILayoutController
operator ::UnityEngine::UI::ILayoutController() noexcept {
return *reinterpret_cast<::UnityEngine::UI::ILayoutController*>(this);
}
}; // UnityEngine.UI.ILayoutSelfController
#pragma pack(pop)
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
| 40.470588
| 109
| 0.726744
|
RedBrumbler
|
04bd60679870025a6e61baa63f4606041a5147c9
| 33,331
|
cpp
|
C++
|
src/core/inputgate.cpp
|
MohamedHmini/win-vind
|
a33eba108a57481311bfd28ccb267dc54b62627f
|
[
"MIT"
] | null | null | null |
src/core/inputgate.cpp
|
MohamedHmini/win-vind
|
a33eba108a57481311bfd28ccb267dc54b62627f
|
[
"MIT"
] | null | null | null |
src/core/inputgate.cpp
|
MohamedHmini/win-vind
|
a33eba108a57481311bfd28ccb267dc54b62627f
|
[
"MIT"
] | null | null | null |
#include "inputgate.hpp"
#include "bind/bindedfunc.hpp"
#include "bind/bindinglist.hpp"
#include "bind/saferepeat.hpp"
#include "errlogger.hpp"
#include "keycodedef.hpp"
#include "keylgrbase.hpp"
#include "keylog.hpp"
#include "lgrparsermgr.hpp"
#include "maptable.hpp"
#include "mode.hpp"
#include "ntypelogger.hpp"
#include "util/container.hpp"
#include "util/debug.hpp"
#include "util/def.hpp"
#include "util/interval_timer.hpp"
#include "util/keystroke_repeater.hpp"
#include "util/winwrap.hpp"
#include <iterator>
#include <windows.h>
#include <array>
#include <chrono>
#include <functional>
#include <queue>
#include <sstream>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#define KEYUP_MASK 0x0001
#define SC_MAPHOOK static_cast<vind::SystemCall>(105)
#define SC_MAPHOOK_REPRD static_cast<vind::SystemCall>(100)
namespace
{
using namespace vind ;
using namespace vind::core ;
class MapHook : public bind::BindedFunc {
private:
SystemCall do_process() const override {
return SC_MAPHOOK ;
}
SystemCall do_process(core::NTypeLogger&) const override {
return SC_MAPHOOK ;
}
SystemCall do_process(const core::CharLogger&) const override {
return SC_MAPHOOK ;
}
public:
template <typename IDString>
explicit MapHook(IDString&& id)
: BindedFunc("maphook_" + id)
{}
} ;
class MapHookReproduce : public bind::BindedFunc {
private:
SystemCall do_process() const override {
return SC_MAPHOOK_REPRD ;
}
SystemCall do_process(core::NTypeLogger&) const override {
return SC_MAPHOOK_REPRD ;
}
SystemCall do_process(const core::CharLogger&) const override {
return SC_MAPHOOK_REPRD ;
}
public:
template <typename IDString>
explicit MapHookReproduce(IDString&& id)
: BindedFunc("maphook_reproduce_" + id)
{}
} ;
NTypeLogger generate_stated_logger(const Command& cmd) {
NTypeLogger lgr ;
KeyLog empty_log{} ;
for(const auto& keyset : cmd) {
/**
* NOTE:
* To simulate the input, make a state transition with an empty log.
* This is to make the logger recognize that it is a key release,
* not a long pressing of the key.
*/
if(NTYPE_EMPTY(lgr.logging_state(
KeyLog(keyset.cbegin(), keyset.cend())))) {
std::stringstream ss ;
ss << "Failed logging of " << keyset ;
throw RUNTIME_EXCEPT(ss.str()) ;
}
if(!NTYPE_EMPTY(lgr.logging_state(empty_log))) {
throw RUNTIME_EXCEPT("Failed to write an empty log.") ;
}
}
return lgr ;
}
using Key2KeysetMap = std::array<KeySet, 256> ;
/**
* NOTE: It solves recursive mappings in key2keyset to a single mapping.
* If a map is mapping to itself recursively, it will remove the map.
*/
void solve_recursive_key2keyset_mapping(Key2KeysetMap& key2keyset_table) {
for(unsigned char srckey = 1 ; srckey < 255 ; srckey ++) {
auto dst = key2keyset_table[srckey] ;
if(dst.empty()) {
continue ;
}
while(true) {
// Check mappings that refer to itself
if(std::find(dst.begin(), dst.end(), srckey) != dst.end()) {
dst.clear() ;
break ;
}
KeySet mapped {} ;
for(auto itr = dst.begin() ; itr != dst.end() ;) {
auto buf = key2keyset_table[itr->to_code()] ;
if(!buf.empty()) {
itr = dst.erase(itr) ;
mapped.insert(mapped.begin(), buf.begin(), buf.end()) ;
}
else {
itr ++ ;
}
}
if(mapped.empty()) {
break ;
}
dst.insert(dst.begin(), mapped.begin(), mapped.end()) ;
}
util::remove_deplication(dst) ;
key2keyset_table[srckey] = std::move(dst) ;
}
}
/*
* Apply the key2keyset mapping to a command.
*/
Command replace_command_with_key2keyset(
const Command& srccmd,
const Key2KeysetMap& key2keyset_table) {
Command replaced_cmd{} ;
for(const auto& keyset : srccmd) {
KeySet replaced_set{} ;
for(const auto& key : keyset) {
auto& mapset = key2keyset_table[key.to_code()] ;
if(!mapset.empty()) {
replaced_set.insert(
replaced_set.begin(),
mapset.begin(),
mapset.end()) ;
}
else {
replaced_set.push_back(key) ;
}
}
util::remove_deplication(replaced_set) ;
replaced_cmd.push_back(std::move(replaced_set)) ;
}
return replaced_cmd ;
}
/**
* It solves recursive mappings with the table of maps.
*
* @param[in] (map_table) MapCell unordered_map with MapCell::in_hash() as the key.
* @param[in] (key2keyset_table) If you want to apply key2keyset mapping, specify this. Empty mappings will be ignored.
* @return std::unordered_map<std::size_t, Command> Returns the solved map corresponding to the key of the map passed as the first argument.
*/
std::unordered_map<std::size_t, Command>
solve_recursive_cmd2cmd_mapping(
const std::unordered_map<std::size_t, Map>& map_table,
const Key2KeysetMap& key2keyset_table) {
std::unordered_map<std::size_t, NTypeLogger> loggers{} ;
std::unordered_map<std::size_t, Command> target_cmds{} ;
std::unordered_map<std::size_t, std::size_t> id_func2map{} ;
std::vector<LoggerParser::SPtr> parsers{} ;
// Setup LoggerParserManager for matching
for(const auto& [mapid, map] : map_table) {
auto func = std::make_shared<bind::BindedFunc>(
"map{" + map.trigger_command_string() + "}") ;
auto funcid = func->id() ;
id_func2map[funcid] = mapid ;
target_cmds[funcid] = replace_command_with_key2keyset(
map.target_command(), key2keyset_table) ;
loggers[funcid] = generate_stated_logger(target_cmds[funcid]) ;
auto parser = std::make_unique<LoggerParser>(func) ;
parser->append_binding(map.trigger_command()) ;
parsers.push_back(std::move(parser)) ;
}
LoggerParserManager solver{parsers} ;
for(auto parser_itr = parsers.begin() ; parser_itr != parsers.end() ;) {
auto func = (*parser_itr)->get_func() ;
auto& lgr = loggers[func->id()] ;
// Check if the logger will be mapped again after it has been mapped.
while(true) {
solver.reset_parser_states() ;
bind::BindedFunc::SPtr matched = nullptr ;
std::size_t matched_idx = 0 ;
for(auto logitr = lgr.cbegin() ; logitr != lgr.cend() ; logitr ++) {
auto buf = solver.find_parser_with_transition(*logitr) ;
if(buf) {
if(buf->is_accepted()) {
matched = buf->get_func() ;
matched_idx = static_cast<std::size_t>(logitr - lgr.cbegin()) ;
break ;
}
else if(!buf->is_waiting()) {
solver.reset_parser_states() ;
}
}
else {
solver.reset_parser_states() ;
}
}
if(!matched) {
parser_itr ++ ;
break ;
}
if(func->id() == matched->id()) {
// This func recursively remaps itself, so remove it from the output list.
parser_itr = parsers.erase(parser_itr) ;
break ;
}
auto& i_outcmd = target_cmds[func->id()] ;
const auto& m_incmd = map_table.at(id_func2map[matched->id()]).trigger_command() ;
const auto& m_outcmd = target_cmds.at(matched->id()) ;
Command merged ;
// Decide how much of the previous command you want to reuse.
const auto matched_begin_idx = matched_idx - (m_incmd.size() - 1) ;
for(std::size_t i = 0 ; i < matched_begin_idx ; i ++) {
merged.push_back(i_outcmd[i]) ;
}
for(auto i = matched_begin_idx ; i <= matched_idx ; i ++) {
KeySet mapped_set ;
const auto& m_keyset = *(m_incmd.cbegin() + i - matched_begin_idx) ;
for(auto key : i_outcmd[i]) {
if(std::find(m_keyset.cbegin(), m_keyset.cend(), key) == m_keyset.cend()) {
mapped_set.push_back(key) ;
}
}
util::remove_deplication(mapped_set) ;
if(!mapped_set.empty()) {
merged.push_back(std::move(mapped_set)) ;
}
}
// Append the mapping command.
merged.insert(
merged.end(),
m_outcmd.begin(),
m_outcmd.end()) ;
// Append the rest of the previous command.
merged.insert(
merged.end(),
i_outcmd.begin() + matched_idx + 1,
i_outcmd.end()) ;
i_outcmd = merged ;
lgr = generate_stated_logger(merged) ;
}
}
std::unordered_map<std::size_t, Command> solved_outcmd{} ;
for(const auto& parser : parsers) {
auto funcid = parser->get_func()->id() ;
auto mapid = id_func2map[funcid] ;
solved_outcmd[mapid] = std::move(target_cmds[funcid]) ;
}
return solved_outcmd ;
}
struct MapGate {
std::unordered_map<std::size_t, Command> cmdtable_{} ;
LoggerParserManager mgr_{} ;
Key2KeysetMap syncmap_{} ;
void reconstruct(Mode mode) {
std::unordered_map<std::size_t, Map> noremap_cmd2cmd{} ;
std::unordered_map<std::size_t, Map> map_cmd2cmd{} ;
std::array<Map, 256> map_key2keyset{} ;
syncmap_.fill(KeySet{}) ;
auto& maptable = core::MapTable::get_instance() ;
auto maps = maptable.get_allmaps(mode) ;
for(auto itr = std::make_move_iterator(maps.begin()) ;
itr != std::make_move_iterator(maps.end()) ; itr ++) {
const auto& trigger_cmd = itr->trigger_command() ;
const auto& target_cmd = itr->target_command() ;
// Ignore mappings to the same command.
if(trigger_cmd == target_cmd) {
continue ;
}
if(itr->is_noremap()) {
if(!bind::ref_global_funcs_bynames(itr->target_command_string())) {
noremap_cmd2cmd[itr->in_hash()] = std::move(*itr) ;
}
}
else { // remappable
// The key2keyset and key2key are mapped synchronously.
if(trigger_cmd.size() == 1 && trigger_cmd.front().size() == 1 // trigger is key?
&& target_cmd.size() == 1) { // target is keyset?
auto trigger_key = trigger_cmd.front().front() ;
auto target_keyset = target_cmd.front() ;
syncmap_[trigger_key.to_code()] = KeySet(
target_keyset.begin(), target_keyset.end()) ;
map_key2keyset[trigger_key.to_code()] = std::move(*itr) ;
}
else {
map_cmd2cmd[itr->in_hash()] = std::move(*itr) ;
}
}
}
solve_recursive_key2keyset_mapping(syncmap_) ;
for(int i = 1 ; i < 255 ; i ++) {
if(syncmap_[i].empty()) {
if(!map_key2keyset[i].empty()) {
PRINT_ERROR(
mode_to_prefix(mode) + "map " + \
map_key2keyset[i].trigger_command_string() + " " +
map_key2keyset[i].target_command_string() +
" recursively remaps itself.") ;
}
}
else {
std::sort(syncmap_[i].begin(), syncmap_[i].end()) ;
}
}
cmdtable_.clear() ;
auto solved_target_cmds = solve_recursive_cmd2cmd_mapping(map_cmd2cmd, syncmap_) ;
std::vector<LoggerParser::SPtr> parsers{} ;
for(const auto& [mapid, map] : map_cmd2cmd) {
if(solved_target_cmds.find(mapid) == solved_target_cmds.end()) {
PRINT_ERROR(
mode_to_prefix(mode) + "map " + \
map.trigger_command_string() + " " +
map.target_command_string() +
" recursively remaps itself.") ;
continue ;
}
auto func = std::make_shared<MapHookReproduce>(
map.trigger_command_string()) ;
auto parser = std::make_shared<LoggerParser>(func) ;
parser->append_binding(map.trigger_command()) ;
parsers.push_back(parser) ;
cmdtable_[func->id()] = solved_target_cmds[mapid] ;
}
for(const auto& [mapid, map] : noremap_cmd2cmd) {
auto func = std::make_shared<MapHook>(
map.trigger_command_string()) ;
auto parser = std::make_shared<LoggerParser>(func) ;
parser->append_binding(map.trigger_command()) ;
parsers.push_back(parser) ;
cmdtable_[func->id()] = map.target_command() ;
}
mgr_ = LoggerParserManager(std::move(parsers)) ;
}
} ;
} // namespace
namespace vind
{
namespace core
{
struct InputGate::Impl {
HHOOK hook_ ;
// Use bit-based optimization with std::vector<bool>.
std::vector<bool> lowlevel_state_ ;
std::vector<bool> real_state_ ;
std::vector<bool> state_ ; //Keyboard state win-vind understands.
std::vector<bool> port_state_ ;
std::array<std::chrono::system_clock::time_point, 256> timestamps_ ;
bool absorb_state_ ;
NTypeLogger lgr_ ;
ModeArray<MapGate> mapgate_ ;
std::queue<KeySet> pool_ ;
bool pool_reprd_mode_ ;
Impl()
: hook_(nullptr),
lowlevel_state_(256, false),
real_state_(256, false),
state_(256, false),
port_state_(256, false),
timestamps_(),
absorb_state_(true),
lgr_(),
mapgate_(),
pool_(),
pool_reprd_mode_(false)
{}
~Impl() noexcept = default ;
Impl(const Impl&) = delete ;
Impl& operator=(const Impl&) = delete ;
} ;
InputGate::InputGate()
: pimpl(std::make_unique<Impl>())
{}
InputGate::~InputGate() noexcept {
uninstall_hook() ;
}
InputGate& InputGate::get_instance() {
static InputGate instance ;
return instance ;
}
void InputGate::install_hook() {
if(!pimpl->hook_) {
pimpl->hook_ = SetWindowsHookEx(
WH_KEYBOARD_LL,
&InputGate::hook_proc,
NULL, 0
) ;
}
if(!pimpl->hook_) {
throw RUNTIME_EXCEPT("KeyAbosorber's hook handle is null") ;
}
}
void InputGate::uninstall_hook() noexcept {
if(pimpl->hook_) {
if(!UnhookWindowsHookEx(pimpl->hook_)) {
PRINT_ERROR("Cannot unhook LowLevelKeyboardProc") ;
}
pimpl->hook_ = nullptr ;
}
// prohibit to keep pressing after termination.
for(unsigned char i = 1 ; i < 255 ; i ++) {
try {
if(pimpl->real_state_[i]) {
release_keystate(i) ;
}
}
catch(const std::exception& e) {
PRINT_ERROR(e.what()) ;
continue ;
}
}
}
void InputGate::reconstruct() {
// Extraction of registered maps
for(std::size_t mode = 0 ; mode < mode_num() ; mode ++) {
pimpl->mapgate_[mode].reconstruct(static_cast<Mode>(mode)) ;
}
}
LRESULT CALLBACK InputGate::hook_proc(int n_code, WPARAM w_param, LPARAM l_param) {
if(n_code < HC_ACTION) { //not processed
return CallNextHookEx(NULL, n_code, w_param, l_param) ;
}
auto& self = get_instance() ;
auto kbd = reinterpret_cast<KBDLLHOOKSTRUCT*>(l_param) ;
auto code = static_cast<unsigned char>(kbd->vkCode) ;
if(!(kbd->flags & LLKHF_INJECTED)) {
// The message is not generated with SendInput.
auto state = !(w_param & KEYUP_MASK) ;
self.pimpl->lowlevel_state_[code] = state ;
self.pimpl->timestamps_[code] = std::chrono::system_clock::now() ;
core::KeyCode keycode(code) ;
if(auto repcode = keycode.to_representative()) {
if(self.map_syncstate(repcode, state) || \
self.map_syncstate(keycode, state)) {
return 1 ;
}
self.pimpl->real_state_[repcode.to_code()] = state ;
self.pimpl->state_[repcode.to_code()] = state ;
}
else if(self.map_syncstate(keycode, state)) {
return 1 ;
}
self.pimpl->real_state_[code] = state ;
self.pimpl->state_[code] = state ;
}
if(self.pimpl->port_state_[code]) {
return CallNextHookEx(NULL, HC_ACTION, w_param, l_param) ;
}
if(self.pimpl->absorb_state_) {
return 1 ;
}
return CallNextHookEx(NULL, HC_ACTION, w_param, l_param) ;
}
//
// It makes the toggle keys behave just like any general keys.
// However, the current implementation has a small delay in releasing the state.
// This is because LowLevelKeyboardProc (LLKP) and SetWindowsHookEx can only
// capture the down event of the toggle key, not the up event, and the strange event cycle.
//
// (1)
// For example, we press CapsLock for 3 seconds. Then we will get the following signal in LLKP.
//
// Signal in LLKP:
//
// ______________________
// ____| _ _ _ _
// 0 1 2 3
//
// Thus, LLKP could not capture up event.
//
// (2)
// So, let's use g_low_level_state to detect if the LLKP has been called or not.
// Then, if the hook is not called for a while, it will release CapsLock.
//
// Signal out of LLKP:
//
// __ ___________________~~~~_____
// ____| |__(about 500ms)_________| ~~~~ |____
// 0 1 .... 3 (has some delay)
//
// The toggle key is sending me a stroke instead of a key state (e.g. h.... hhhhhhh).
// This means that there will be a buffer time of about 500ms after the first positive signal.
// If you assign <CapsLock> to <Ctrl> and press <CapsLock-s>,
// as there is a high chance of collision during this buffer time, so it's so bad.
//
// (3)
// As a result, I implemented to be released toggle keys
// when LLKP has not been called for more than the buffer time.
// This way, even if the key is actually released, if it is less than 500 ms,
// it will continue to be pressed, causing a delay.
//
//
// Unfortunately, for keymap and normal mode, the flow of key messages needs
// to be stopped, and this can only be done using Hook.
// Therefore, this is a challenging task. If you have any ideas, we welcome pull requests.
//
void InputGate::refresh_toggle_state() {
static util::IntervalTimer timer(5'000) ;
if(!timer.is_passed()) {
return ;
}
static auto toggles =[] {
std::vector<core::KeyCode> buf ;
for(unsigned char i = 1 ; i < 255 ; i ++) {
core::KeyCode k(i) ;
if(k.is_toggle()) {
buf.push_back(std::move(k)) ;
}
}
return buf ;
}() ;
for(auto k : toggles) {
if(!pimpl->lowlevel_state_[k.to_code()]) {
continue ;
}
using namespace std::chrono ;
if((system_clock::now() - pimpl->timestamps_[k.to_code()]) > 515ms) {
map_syncstate(k, false) ;
release_keystate(k) ;
pimpl->real_state_[k.to_code()] = false ;
pimpl->state_[k.to_code()] = false ;
pimpl->lowlevel_state_[k.to_code()] = false ;
}
}
}
bool InputGate::is_pressed(KeyCode keycode) noexcept {
return pimpl->state_[keycode.to_code()] ;
}
bool InputGate::is_really_pressed(KeyCode keycode) noexcept {
return pimpl->real_state_[keycode.to_code()] ;
}
KeyLog InputGate::pressed_list() {
KeyLog::Data res{} ;
for(unsigned char i = 1 ; i < 255 ; i ++) {
if(is_pressed(i)) {
res.insert(i) ;
}
}
return KeyLog(res) ;
}
bool InputGate::is_absorbed() noexcept {
return pimpl->absorb_state_ ;
}
void InputGate::absorb() noexcept {
pimpl->absorb_state_ = true ;
}
void InputGate::unabsorb() noexcept {
pimpl->absorb_state_ = false ;
}
void InputGate::close_some_ports(
std::initializer_list<KeyCode>&& keys) noexcept {
for(auto k : keys) {
pimpl->port_state_[k.to_code()] = true ;
}
}
void InputGate::close_some_ports(
std::initializer_list<KeyCode>::const_iterator begin,
std::initializer_list<KeyCode>::const_iterator end) noexcept {
for(auto itr = begin ; itr != end ; itr ++) {
pimpl->port_state_[itr->to_code()] = false ;
}
}
void InputGate::close_some_ports(
std::vector<KeyCode>&& keys) noexcept {
for(auto k : keys) {
pimpl->port_state_[k.to_code()] = false ;
}
}
void InputGate::close_some_ports(
std::vector<KeyCode>::const_iterator begin,
std::vector<KeyCode>::const_iterator end) noexcept {
for(auto itr = begin ; itr != end ; itr ++) {
pimpl->port_state_[itr->to_code()] = false ;
}
}
void InputGate::close_some_ports(
const KeyLog::Data& keys) noexcept {
for(auto k : keys) {
pimpl->port_state_[k.to_code()] = false ;
}
}
void InputGate::close_port(KeyCode key) noexcept {
pimpl->port_state_[key.to_code()] = false ;
}
void InputGate::close_all_ports() noexcept {
std::fill(
pimpl->port_state_.begin(),
pimpl->port_state_.end(),
false) ;
}
void InputGate::close_all_ports_with_refresh() {
// If this function is called by pressed button,
// it has to send message "KEYUP" to OS (not absorbed).
for(unsigned char i = 1 ; i < 255 ; i ++) {
if(pimpl->state_[i]) {
// open a port to release the key state.
open_port(i) ;
release_keystate(i) ;
}
}
std::fill(
pimpl->port_state_.begin(),
pimpl->port_state_.end(),
false) ;
}
void InputGate::open_some_ports(
std::initializer_list<KeyCode>&& keys) noexcept {
for(auto k : keys) {
pimpl->port_state_[k.to_code()] = true ;
}
}
void InputGate::open_some_ports(
std::initializer_list<KeyCode>::const_iterator begin,
std::initializer_list<KeyCode>::const_iterator end) noexcept {
for(auto itr = begin ; itr != end ; itr ++) {
pimpl->port_state_[itr->to_code()] = true ;
}
}
void InputGate::open_some_ports(
std::vector<KeyCode>&& keys) noexcept {
for(auto k : keys) {
pimpl->port_state_[k.to_code()] = true ;
}
}
void InputGate::open_some_ports(
std::vector<KeyCode>::const_iterator begin,
std::vector<KeyCode>::const_iterator end) noexcept {
for(auto itr = begin ; itr != end ; itr ++) {
pimpl->port_state_[itr->to_code()] = true ;
}
}
void InputGate::open_some_ports(
const KeyLog::Data& keys) noexcept {
for(auto k : keys) {
pimpl->port_state_[k.to_code()] = true ;
}
}
void InputGate::open_port(KeyCode key) noexcept {
pimpl->port_state_[key.to_code()] = true ;
}
void InputGate::release_virtually(KeyCode key) noexcept {
pimpl->state_[key.to_code()] = false ;
}
void InputGate::press_virtually(KeyCode key) noexcept {
pimpl->state_[key.to_code()] = true ;
}
bool InputGate::map_syncstate(
KeyCode hook_key,
bool press_sync_state,
Mode mode) {
auto midx = static_cast<int>(mode) ;
auto target = pimpl->mapgate_[midx].syncmap_[hook_key.to_code()] ;
if(target.empty()) {
return false ;
}
if(press_sync_state) {
open_some_ports(target.begin(), target.end()) ;
press_keystate(target.begin(), target.end()) ;
close_some_ports(target.begin(), target.end()) ;
}
else {
open_some_ports(target.begin(), target.end()) ;
release_keystate(target.begin(), target.end()) ;
close_some_ports(target.begin(), target.end()) ;
}
return true ;
}
KeyLog InputGate::pop_log(Mode mode) {
if(!pimpl->pool_.empty()) {
auto keyset = std::move(pimpl->pool_.front()) ;
pimpl->pool_.pop() ;
if(pimpl->pool_reprd_mode_ && !keyset.empty()) {
pushup(keyset.begin(), keyset.end()) ;
}
return KeyLog(
std::make_move_iterator(keyset.begin()),
std::make_move_iterator(keyset.end())) ;
}
auto log = pressed_list() ;
if(NTYPE_EMPTY(pimpl->lgr_.logging_state(log))) {
return log ;
}
auto& gate = pimpl->mapgate_[static_cast<int>(mode)] ;
auto parser = gate.mgr_.find_parser_with_transition(log) ;
if(!parser) {
pimpl->lgr_.reject() ;
gate.mgr_.reset_parser_states() ;
return log ;
}
if(parser->is_accepted()) {
pimpl->lgr_.accept() ;
gate.mgr_.reset_parser_states() ;
auto func = parser->get_func() ;
auto sc = func->process() ;
pimpl->pool_reprd_mode_ = sc == SC_MAPHOOK_REPRD ;
const auto& cmd = gate.cmdtable_.at(func->id()) ;
auto itr = cmd.begin() ;
log = KeyLog(itr->begin(), itr->end()) ;
if(pimpl->pool_reprd_mode_) {
pushup(itr->begin(), itr->end()) ;
}
itr ++ ;
//
// To simulate the input, make a state transition with an empty log.
// This is to make the logger recognize that it is a key release,
// not a long pressing of the key.
//
while(itr != cmd.end()) {
pimpl->pool_.emplace() ;
pimpl->pool_.push(*itr) ;
itr ++ ;
}
}
else if(parser->is_rejected_with_ready()) {
gate.mgr_.backward_parser_states(1) ;
pimpl->lgr_.remove_from_back(1) ;
}
return log ;
}
} // namespace core
} // namespace vind
namespace
{
bool is_pressed_actually(KeyCode key) noexcept {
return GetAsyncKeyState(key.to_code()) & 0x8000 ;
}
}
namespace vind
{
namespace core
{
struct ScopedKey::Impl {
INPUT in_ ;
KeyCode key_ ;
explicit Impl(KeyCode keycode)
: in_(),
key_(keycode)
{
in_.type = INPUT_KEYBOARD ;
in_.ki.wVk = static_cast<WORD>(key_.to_code()) ;
in_.ki.wScan = static_cast<WORD>(MapVirtualKeyA(in_.ki.wVk, MAPVK_VK_TO_VSC)) ;
}
} ;
ScopedKey::ScopedKey(KeyCode key)
: pimpl(std::make_unique<Impl>(key))
{}
ScopedKey::~ScopedKey() noexcept {
try {release() ;}
catch(const std::exception& e) {
PRINT_ERROR(e.what()) ;
}
}
ScopedKey::ScopedKey(ScopedKey&&) = default ;
ScopedKey& ScopedKey::operator=(ScopedKey&&) = default ;
void ScopedKey::send_event(bool pressed) {
pimpl->in_.ki.dwFlags = (pressed ? 0 : KEYEVENTF_KEYUP) | extended_key_flag(pimpl->in_.ki.wVk) ;
if(!SendInput(1, &pimpl->in_, sizeof(INPUT))) {
throw RUNTIME_EXCEPT("failed sending keyboard event") ;
}
}
void ScopedKey::press() {
auto& igate = InputGate::get_instance() ;
igate.open_port(pimpl->key_) ;
send_event(true) ;
igate.close_all_ports() ;
if(!is_pressed_actually(pimpl->key_)) {
throw RUNTIME_EXCEPT("You sent a key pressing event successfully, but the state of its key was not changed.") ;
}
}
void ScopedKey::release() {
auto& igate = InputGate::get_instance() ;
igate.open_port(pimpl->key_) ;
send_event(false) ;
igate.close_all_ports() ;
if(is_pressed_actually(pimpl->key_)) {
throw RUNTIME_EXCEPT("You sent a key releasing event successfully, but the state of its key was not changed.") ;
}
}
InstantKeyAbsorber::InstantKeyAbsorber()
: flag_(false)
{
auto& igate = InputGate::get_instance() ;
flag_ = igate.is_absorbed() ;
igate.close_all_ports_with_refresh() ;
igate.absorb() ;
}
InstantKeyAbsorber::~InstantKeyAbsorber() noexcept {
if(!flag_) {
InputGate::get_instance().unabsorb() ;
}
}
} // namespace core
} // namespace vind
| 34.938155
| 144
| 0.492334
|
MohamedHmini
|
04be42cc3c0ece84d93aa58354db03fbdd8da485
| 1,482
|
cpp
|
C++
|
ReferenceTests_v3/src/tests/Catch_Testset02/UT_Tests03.cpp
|
dmkozh/TestAdapter_Catch2
|
6584596594f11bf477fddebfd1211483ca091ee3
|
[
"MIT"
] | null | null | null |
ReferenceTests_v3/src/tests/Catch_Testset02/UT_Tests03.cpp
|
dmkozh/TestAdapter_Catch2
|
6584596594f11bf477fddebfd1211483ca091ee3
|
[
"MIT"
] | null | null | null |
ReferenceTests_v3/src/tests/Catch_Testset02/UT_Tests03.cpp
|
dmkozh/TestAdapter_Catch2
|
6584596594f11bf477fddebfd1211483ca091ee3
|
[
"MIT"
] | null | null | null |
/** Basic Info **
Copyright: 2018 Johnny Hendriks
Author : Johnny Hendriks
Year : 2018
Project: VSTestAdapter for Catch2
Licence: MIT
Notes: None
** Basic Info **/
/************
* Includes *
************/
// Catch2
#include <catch2/catch_test_macros.hpp>
/**************
* Start code *
**************/
namespace CatchTestset02
{
namespace
{
class TestFixture
{
protected:
int x = 42;
int y = 42;
};
}
TEST_CASE_METHOD(TestFixture, "Testset02. Test1", "[Testname]")
{
CHECK(x == y);
}
TEST_CASE_METHOD(TestFixture, "Testset02. Test2", "[Testname]")
{
CHECK(x == y);
}
TEST_CASE_METHOD(TestFixture, "Testset02.Level0. Test1", "[Testname]")
{
CHECK(x == y);
}
TEST_CASE_METHOD(TestFixture, "Testset02.Level0. Test2", "[Testname]")
{
CHECK(x == y);
}
TEST_CASE_METHOD(TestFixture, "Testset02.Level0.Level1. Test1", "[Testname]")
{
CHECK(x == y);
}
TEST_CASE_METHOD(TestFixture, "Testset02.Level0.Level1. Test2", "[Testname]")
{
CHECK(x == y);
}
TEST_CASE_METHOD(TestFixture, "Testset02.Level0.Level1.Level2. Test1", "[Testname]")
{
CHECK(x == y);
}
TEST_CASE_METHOD(TestFixture, "Testset02.Level0.Level1.Level2. Test2", "[Testname]")
{
CHECK(x == y);
}
} // End namespace: CatchTestset02
/************
* End code *
************/
| 17.435294
| 88
| 0.539136
|
dmkozh
|
04bfe4e4d9ac62a654b62a9ac7a4196215da0065
| 764
|
cpp
|
C++
|
TopEarners.cpp
|
MISabic/Uber
|
1232d18bf2ffcd8d8de82c744a2736adee0497bf
|
[
"MIT"
] | null | null | null |
TopEarners.cpp
|
MISabic/Uber
|
1232d18bf2ffcd8d8de82c744a2736adee0497bf
|
[
"MIT"
] | null | null | null |
TopEarners.cpp
|
MISabic/Uber
|
1232d18bf2ffcd8d8de82c744a2736adee0497bf
|
[
"MIT"
] | null | null | null |
#ifndef TOP_EARNERS_CPP
#define TOP_EARNERS_CPP
#include "TopEarners.h"
template<class ItemType>
TopEarners<ItemType>::TopEarners( ) {
ReadData( );
}
template<class ItemType>
void TopEarners<ItemType>::ReadData( ) {
ifstream inFile( "MonthlyEarners.txt" );
string name;
double totalIncome;
while( inFile >> name >> totalIncome ) {
pq.Enqueue( MaxElem( name, totalIncome ) );
}
inFile.close( );
}
template<class ItemType>
vector<string> TopEarners<ItemType>::GetTopFive( ) {
MaxElem me;
vector<string> res;
int sz = pq.GetSize() < 5 ? pq.GetSize() : 5;
for( int i = 0; i < sz; i++ ) {
pq.Dequeue( me );
res.push_back( me.GetName( ) );
}
return res;
}
#endif // TOP_EARNERS_CPP
| 18.190476
| 52
| 0.624346
|
MISabic
|
04c20cc64811bcc56954399b9198089788e342cd
| 317
|
cpp
|
C++
|
source/fps.cpp
|
vitodtagliente/vdtplatform
|
8b38a84fc2a582ea04743dcf19b70b2f3416c744
|
[
"MIT"
] | null | null | null |
source/fps.cpp
|
vitodtagliente/vdtplatform
|
8b38a84fc2a582ea04743dcf19b70b2f3416c744
|
[
"MIT"
] | null | null | null |
source/fps.cpp
|
vitodtagliente/vdtplatform
|
8b38a84fc2a582ea04743dcf19b70b2f3416c744
|
[
"MIT"
] | null | null | null |
#include <vdtplatform/fps.h>
namespace platform
{
FPS::FPS()
: m_frames()
, m_time()
, m_fps()
{
}
void FPS::update(const double deltaTime)
{
++m_frames;
m_time += deltaTime;
if (m_time >= 1.0)
{
m_fps = static_cast<unsigned int>(m_frames / m_time);
m_frames = 0;
m_time = 0.0;
}
}
}
| 13.208333
| 56
| 0.59306
|
vitodtagliente
|
04c301b08149627ba558bd91bf386dd222190455
| 298
|
hpp
|
C++
|
packets/PKT_S2C_HighlightHUDElement.hpp
|
HoDANG/OGLeague2
|
21efea8ea480972a6d686c4adefea03d57da5e9d
|
[
"MIT"
] | 1
|
2022-03-27T10:21:41.000Z
|
2022-03-27T10:21:41.000Z
|
packets/PKT_S2C_HighlightHUDElement.hpp
|
HoDANG/OGLeague2
|
21efea8ea480972a6d686c4adefea03d57da5e9d
|
[
"MIT"
] | null | null | null |
packets/PKT_S2C_HighlightHUDElement.hpp
|
HoDANG/OGLeague2
|
21efea8ea480972a6d686c4adefea03d57da5e9d
|
[
"MIT"
] | 3
|
2019-07-20T03:59:10.000Z
|
2022-03-27T10:20:09.000Z
|
#ifndef HPP_164_PKT_S2C_HighlightHUDElement_HPP
#define HPP_164_PKT_S2C_HighlightHUDElement_HPP
#include "base.hpp"
#pragma pack(push, 1)
struct PKT_S2C_HighlightHUDElement_s : DefaultPacket<PKT_S2C_HighlightHUDElement>
{
char elementType;
char elementNumber;
};
#pragma pack(pop)
#endif
| 21.285714
| 81
| 0.818792
|
HoDANG
|
04c3f6e8ab421fcb474ca63624ddf4977e741d24
| 5,107
|
cpp
|
C++
|
RVAF-GUI/teechart/horizlineseries.cpp
|
YangQun1/RVAF-GUI
|
f187e2325fc8fdbac84a63515b7dd67c09e2fc72
|
[
"BSD-2-Clause"
] | 4
|
2018-03-31T10:45:19.000Z
|
2021-10-09T02:57:13.000Z
|
RVAF-GUI/teechart/horizlineseries.cpp
|
P-Chao/RVAF-GUI
|
3bbeed7d2ffa400f754f095e7c08400f701813d4
|
[
"BSD-2-Clause"
] | 1
|
2018-04-22T05:12:36.000Z
|
2018-04-22T05:12:36.000Z
|
RVAF-GUI/teechart/horizlineseries.cpp
|
YangQun1/RVAF-GUI
|
f187e2325fc8fdbac84a63515b7dd67c09e2fc72
|
[
"BSD-2-Clause"
] | 5
|
2018-01-13T15:57:14.000Z
|
2019-11-12T03:23:18.000Z
|
// Machine generated IDispatch wrapper class(es) created by Microsoft Visual C++
// NOTE: Do not modify the contents of this file. If this class is regenerated by
// Microsoft Visual C++, your modifications will be overwritten.
#include "stdafx.h"
#include "horizlineseries.h"
// Dispatch interfaces referenced by this interface
#include "pointer.h"
#include "pen.h"
#include "brush.h"
#include "teeshadow.h"
#include "gradient.h"
/////////////////////////////////////////////////////////////////////////////
// CHorizLineSeries properties
/////////////////////////////////////////////////////////////////////////////
// CHorizLineSeries operations
CPointer CHorizLineSeries::GetPointer()
{
LPDISPATCH pDispatch;
InvokeHelper(0x1, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&pDispatch, NULL);
return CPointer(pDispatch);
}
BOOL CHorizLineSeries::GetStairs()
{
BOOL result;
InvokeHelper(0x2, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL);
return result;
}
void CHorizLineSeries::SetStairs(BOOL bNewValue)
{
static BYTE parms[] =
VTS_BOOL;
InvokeHelper(0x2, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms,
bNewValue);
}
BOOL CHorizLineSeries::GetInvertedStairs()
{
BOOL result;
InvokeHelper(0x3, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL);
return result;
}
void CHorizLineSeries::SetInvertedStairs(BOOL bNewValue)
{
static BYTE parms[] =
VTS_BOOL;
InvokeHelper(0x3, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms,
bNewValue);
}
CPen1 CHorizLineSeries::GetLinePen()
{
LPDISPATCH pDispatch;
InvokeHelper(0x4, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&pDispatch, NULL);
return CPen1(pDispatch);
}
long CHorizLineSeries::GetLineBrush()
{
long result;
InvokeHelper(0x5, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL);
return result;
}
void CHorizLineSeries::SetLineBrush(long nNewValue)
{
static BYTE parms[] =
VTS_I4;
InvokeHelper(0x5, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms,
nNewValue);
}
BOOL CHorizLineSeries::GetClickableLine()
{
BOOL result;
InvokeHelper(0x6, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL);
return result;
}
void CHorizLineSeries::SetClickableLine(BOOL bNewValue)
{
static BYTE parms[] =
VTS_BOOL;
InvokeHelper(0x6, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms,
bNewValue);
}
long CHorizLineSeries::GetLineHeight()
{
long result;
InvokeHelper(0x4c, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL);
return result;
}
void CHorizLineSeries::SetLineHeight(long nNewValue)
{
static BYTE parms[] =
VTS_I4;
InvokeHelper(0x4c, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms,
nNewValue);
}
BOOL CHorizLineSeries::GetDark3D()
{
BOOL result;
InvokeHelper(0x49, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL);
return result;
}
void CHorizLineSeries::SetDark3D(BOOL bNewValue)
{
static BYTE parms[] =
VTS_BOOL;
InvokeHelper(0x49, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms,
bNewValue);
}
CBrush1 CHorizLineSeries::GetBrush()
{
LPDISPATCH pDispatch;
InvokeHelper(0x9, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&pDispatch, NULL);
return CBrush1(pDispatch);
}
BOOL CHorizLineSeries::GetColorEachLine()
{
BOOL result;
InvokeHelper(0x51, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL);
return result;
}
void CHorizLineSeries::SetColorEachLine(BOOL bNewValue)
{
static BYTE parms[] =
VTS_BOOL;
InvokeHelper(0x51, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms,
bNewValue);
}
CPen1 CHorizLineSeries::GetOutline()
{
LPDISPATCH pDispatch;
InvokeHelper(0x7, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&pDispatch, NULL);
return CPen1(pDispatch);
}
long CHorizLineSeries::GetTransparency()
{
long result;
InvokeHelper(0x52, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL);
return result;
}
void CHorizLineSeries::SetTransparency(long nNewValue)
{
static BYTE parms[] =
VTS_I4;
InvokeHelper(0x52, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms,
nNewValue);
}
CTeeShadow CHorizLineSeries::GetShadow()
{
LPDISPATCH pDispatch;
InvokeHelper(0xc9, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&pDispatch, NULL);
return CTeeShadow(pDispatch);
}
long CHorizLineSeries::GetTreatNulls()
{
long result;
InvokeHelper(0xca, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL);
return result;
}
void CHorizLineSeries::SetTreatNulls(long nNewValue)
{
static BYTE parms[] =
VTS_I4;
InvokeHelper(0xca, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms,
nNewValue);
}
long CHorizLineSeries::GetStacked()
{
long result;
InvokeHelper(0x8, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL);
return result;
}
void CHorizLineSeries::SetStacked(long nNewValue)
{
static BYTE parms[] =
VTS_I4;
InvokeHelper(0x8, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms,
nNewValue);
}
CGradient CHorizLineSeries::GetGradient()
{
LPDISPATCH pDispatch;
InvokeHelper(0x12d, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&pDispatch, NULL);
return CGradient(pDispatch);
}
| 23.753488
| 83
| 0.706285
|
YangQun1
|
04c3f6f3f6b8cc44aa3709be1b911408e4c8c75b
| 12,159
|
cpp
|
C++
|
libs/geometry/test/algorithms/distance.cpp
|
ballisticwhisper/boost
|
f72119ab640b564c4b983bd457457046b52af9ee
|
[
"BSL-1.0"
] | 2
|
2015-01-02T14:24:56.000Z
|
2015-01-02T14:25:17.000Z
|
libs/geometry/test/algorithms/distance.cpp
|
ballisticwhisper/boost
|
f72119ab640b564c4b983bd457457046b52af9ee
|
[
"BSL-1.0"
] | 2
|
2019-01-13T23:45:51.000Z
|
2019-02-03T08:13:26.000Z
|
libs/geometry/test/algorithms/distance.cpp
|
ballisticwhisper/boost
|
f72119ab640b564c4b983bd457457046b52af9ee
|
[
"BSL-1.0"
] | 1
|
2016-05-29T13:41:15.000Z
|
2016-05-29T13:41:15.000Z
|
// Boost.Geometry (aka GGL, Generic Geometry Library)
// Unit Test
// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.
// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.
// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.
// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library
// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.
// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <sstream>
#include <algorithms/test_distance.hpp>
#include <boost/mpl/if.hpp>
#include <boost/array.hpp>
#include <boost/geometry/geometries/geometries.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
#include <boost/geometry/geometries/adapted/c_array.hpp>
#include <boost/geometry/geometries/adapted/boost_tuple.hpp>
#include <test_common/test_point.hpp>
#include <test_geometries/custom_segment.hpp>
#include <test_geometries/wrapped_boost_array.hpp>
BOOST_GEOMETRY_REGISTER_C_ARRAY_CS(cs::cartesian)
BOOST_GEOMETRY_REGISTER_BOOST_TUPLE_CS(cs::cartesian)
// Register boost array as a linestring
namespace boost { namespace geometry { namespace traits
{
template <typename Point, std::size_t PointCount>
struct tag< boost::array<Point, PointCount> >
{
typedef linestring_tag type;
};
}}}
template <typename P>
void test_distance_point()
{
namespace services = bg::strategy::distance::services;
typedef typename bg::default_distance_result<P>::type return_type;
// Basic, trivial test
P p1;
bg::set<0>(p1, 1);
bg::set<1>(p1, 1);
P p2;
bg::set<0>(p2, 2);
bg::set<1>(p2, 2);
return_type d = bg::distance(p1, p2);
BOOST_CHECK_CLOSE(d, return_type(1.4142135), 0.001);
// Test specifying strategy manually
typename services::default_strategy<bg::point_tag, P>::type strategy;
d = bg::distance(p1, p2, strategy);
BOOST_CHECK_CLOSE(d, return_type(1.4142135), 0.001);
{
// Test custom strategy
BOOST_CONCEPT_ASSERT( (bg::concept::PointDistanceStrategy<taxicab_distance, P, P>) );
typedef typename services::return_type<taxicab_distance, P, P>::type cab_return_type;
BOOST_MPL_ASSERT((boost::is_same<cab_return_type, typename bg::coordinate_type<P>::type>));
taxicab_distance tcd;
cab_return_type d = bg::distance(p1, p2, tcd);
BOOST_CHECK( bg::math::abs(d - cab_return_type(2)) <= cab_return_type(0.01) );
}
{
// test comparability
typedef typename services::default_strategy<bg::point_tag, P>::type strategy_type;
typedef typename services::comparable_type<strategy_type>::type comparable_strategy_type;
strategy_type strategy;
comparable_strategy_type comparable_strategy = services::get_comparable<strategy_type>::apply(strategy);
return_type comparable = services::result_from_distance<comparable_strategy_type, P, P>::apply(comparable_strategy, 3);
BOOST_CHECK_CLOSE(comparable, return_type(9), 0.001);
}
}
template <typename P>
void test_distance_segment()
{
typedef typename bg::default_distance_result<P>::type return_type;
typedef typename bg::coordinate_type<P>::type coordinate_type;
P s1; bg::set<0>(s1, 1); bg::set<1>(s1, 1);
P s2; bg::set<0>(s2, 4); bg::set<1>(s2, 4);
// Check points left, right, projected-left, projected-right, on segment
P p1; bg::set<0>(p1, 0); bg::set<1>(p1, 1);
P p2; bg::set<0>(p2, 1); bg::set<1>(p2, 0);
P p3; bg::set<0>(p3, 3); bg::set<1>(p3, 1);
P p4; bg::set<0>(p4, 1); bg::set<1>(p4, 3);
P p5; bg::set<0>(p5, 3); bg::set<1>(p5, 3);
bg::model::referring_segment<P const> const seg(s1, s2);
return_type d1 = bg::distance(p1, seg);
return_type d2 = bg::distance(p2, seg);
return_type d3 = bg::distance(p3, seg);
return_type d4 = bg::distance(p4, seg);
return_type d5 = bg::distance(p5, seg);
BOOST_CHECK_CLOSE(d1, return_type(1), 0.001);
BOOST_CHECK_CLOSE(d2, return_type(1), 0.001);
BOOST_CHECK_CLOSE(d3, return_type(1.4142135), 0.001);
BOOST_CHECK_CLOSE(d4, return_type(1.4142135), 0.001);
BOOST_CHECK_CLOSE(d5, return_type(0), 0.001);
// Reverse case: segment/point instead of point/segment
return_type dr1 = bg::distance(seg, p1);
return_type dr2 = bg::distance(seg, p2);
BOOST_CHECK_CLOSE(dr1, d1, 0.001);
BOOST_CHECK_CLOSE(dr2, d2, 0.001);
// Test specifying strategy manually:
// 1) point-point-distance
typename bg::strategy::distance::services::default_strategy<bg::point_tag, P>::type pp_strategy;
d1 = bg::distance(p1, seg, pp_strategy);
BOOST_CHECK_CLOSE(d1, return_type(1), 0.001);
// 2) point-segment-distance
typename bg::strategy::distance::services::default_strategy<bg::segment_tag, P>::type ps_strategy;
d1 = bg::distance(p1, seg, ps_strategy);
BOOST_CHECK_CLOSE(d1, return_type(1), 0.001);
// 3) custom point strategy
taxicab_distance tcd;
d1 = bg::distance(p1, seg, tcd);
BOOST_CHECK_CLOSE(d1, return_type(1), 0.001);
}
template <typename Point, typename Geometry, typename T>
void test_distance_linear(std::string const& wkt_point, std::string const& wkt_geometry, T const& expected)
{
Point p;
bg::read_wkt(wkt_point, p);
Geometry g;
bg::read_wkt(wkt_geometry, g);
typedef typename bg::default_distance_result<Point>::type return_type;
return_type d = bg::distance(p, g);
// For point-to-linestring (or point-to-polygon), both a point-strategy and a point-segment-strategy can be specified.
// Test this.
return_type ds1 = bg::distance(p, g, bg::strategy::distance::pythagoras<>());
return_type ds2 = bg::distance(p, g, bg::strategy::distance::projected_point<>());
BOOST_CHECK_CLOSE(d, return_type(expected), 0.001);
BOOST_CHECK_CLOSE(ds1, return_type(expected), 0.001);
BOOST_CHECK_CLOSE(ds2, return_type(expected), 0.001);
}
template <typename P>
void test_distance_array_as_linestring()
{
typedef typename bg::default_distance_result<P>::type return_type;
// Normal array does not have
boost::array<P, 2> points;
bg::set<0>(points[0], 1);
bg::set<1>(points[0], 1);
bg::set<0>(points[1], 3);
bg::set<1>(points[1], 3);
P p;
bg::set<0>(p, 2);
bg::set<1>(p, 1);
return_type d = bg::distance(p, points);
BOOST_CHECK_CLOSE(d, return_type(0.70710678), 0.001);
bg::set<0>(p, 5); bg::set<1>(p, 5);
d = bg::distance(p, points);
BOOST_CHECK_CLOSE(d, return_type(2.828427), 0.001);
}
template <typename P>
void test_all()
{
test_distance_point<P>();
test_distance_segment<P>();
test_distance_array_as_linestring<P>();
test_geometry<P, bg::model::segment<P> >("POINT(1 3)", "LINESTRING(1 1,4 4)", sqrt(2.0));
test_geometry<P, bg::model::segment<P> >("POINT(3 1)", "LINESTRING(1 1,4 4)", sqrt(2.0));
test_geometry<P, P>("POINT(1 1)", "POINT(2 2)", sqrt(2.0));
test_geometry<P, P>("POINT(0 0)", "POINT(0 3)", 3.0);
test_geometry<P, P>("POINT(0 0)", "POINT(4 0)", 4.0);
test_geometry<P, P>("POINT(0 3)", "POINT(4 0)", 5.0);
test_geometry<P, bg::model::linestring<P> >("POINT(1 3)", "LINESTRING(1 1,4 4)", sqrt(2.0));
test_geometry<P, bg::model::linestring<P> >("POINT(3 1)", "LINESTRING(1 1,4 4)", sqrt(2.0));
test_geometry<P, bg::model::linestring<P> >("POINT(50 50)", "LINESTRING(50 40, 40 50)", sqrt(50.0));
test_geometry<P, bg::model::linestring<P> >("POINT(50 50)", "LINESTRING(50 40, 40 50, 0 90)", sqrt(50.0));
test_geometry<bg::model::linestring<P>, P>("LINESTRING(1 1,4 4)", "POINT(1 3)", sqrt(2.0));
test_geometry<bg::model::linestring<P>, P>("LINESTRING(50 40, 40 50)", "POINT(50 50)", sqrt(50.0));
test_geometry<bg::model::linestring<P>, P>("LINESTRING(50 40, 40 50, 0 90)", "POINT(50 50)", sqrt(50.0));
// Rings
test_geometry<P, bg::model::ring<P> >("POINT(1 3)", "POLYGON((1 1,4 4,5 0,1 1))", sqrt(2.0));
test_geometry<P, bg::model::ring<P> >("POINT(3 1)", "POLYGON((1 1,4 4,5 0,1 1))", 0.0);
// other way round
test_geometry<bg::model::ring<P>, P>("POLYGON((1 1,4 4,5 0,1 1))", "POINT(3 1)", 0.0);
// open ring
test_geometry<P, bg::model::ring<P, true, false> >("POINT(1 3)", "POLYGON((4 4,5 0,1 1))", sqrt(2.0));
// Polygons
test_geometry<P, bg::model::polygon<P> >("POINT(1 3)", "POLYGON((1 1,4 4,5 0,1 1))", sqrt(2.0));
test_geometry<P, bg::model::polygon<P> >("POINT(3 1)", "POLYGON((1 1,4 4,5 0,1 1))", 0.0);
// other way round
test_geometry<bg::model::polygon<P>, P>("POLYGON((1 1,4 4,5 0,1 1))", "POINT(3 1)", 0.0);
// open polygon
test_geometry<P, bg::model::polygon<P, true, false> >("POINT(1 3)", "POLYGON((4 4,5 0,1 1))", sqrt(2.0));
// Polygons with holes
std::string donut = "POLYGON ((0 0,1 9,8 1,0 0),(1 1,4 1,1 4,1 1))";
test_geometry<P, bg::model::polygon<P> >("POINT(2 2)", donut, 0.5 * sqrt(2.0));
test_geometry<P, bg::model::polygon<P> >("POINT(3 3)", donut, 0.0);
// other way round
test_geometry<bg::model::polygon<P>, P>(donut, "POINT(2 2)", 0.5 * sqrt(2.0));
// open
test_geometry<P, bg::model::polygon<P, true, false> >("POINT(2 2)", "POLYGON ((0 0,1 9,8 1),(1 1,4 1,1 4))", 0.5 * sqrt(2.0));
// Should (currently) give compiler assertion
// test_geometry<bg::model::polygon<P>, bg::model::polygon<P> >(donut, donut, 0.5 * sqrt(2.0));
// DOES NOT COMPILE - cannot do read_wkt (because boost::array is not variably sized)
// test_geometry<P, boost::array<P, 2> >("POINT(3 1)", "LINESTRING(1 1,4 4)", sqrt(2.0));
test_geometry<P, test::wrapped_boost_array<P, 2> >("POINT(3 1)", "LINESTRING(1 1,4 4)", sqrt(2.0));
test_distance_linear<P, bg::model::linestring<P> >("POINT(3 1)", "LINESTRING(1 1,4 4)", sqrt(2.0));
}
template <typename P>
void test_empty_input()
{
P p;
bg::model::linestring<P> line_empty;
bg::model::polygon<P> poly_empty;
bg::model::ring<P> ring_empty;
test_empty_input(p, line_empty);
test_empty_input(p, poly_empty);
test_empty_input(p, ring_empty);
}
void test_large_integers()
{
typedef bg::model::point<int, 2, bg::cs::cartesian> int_point_type;
typedef bg::model::point<double, 2, bg::cs::cartesian> double_point_type;
// point-point
{
std::string const a = "POINT(2544000 528000)";
std::string const b = "POINT(2768040 528000)";
int_point_type ia, ib;
double_point_type da, db;
bg::read_wkt(a, ia);
bg::read_wkt(b, ib);
bg::read_wkt(a, da);
bg::read_wkt(b, db);
BOOST_AUTO(idist, bg::distance(ia, ib));
BOOST_AUTO(ddist, bg::distance(da, db));
BOOST_CHECK_MESSAGE(std::abs(idist - ddist) < 0.1,
"within<a double> different from within<an int>");
}
// Point-segment
{
std::string const a = "POINT(2600000 529000)";
std::string const b = "LINESTRING(2544000 528000, 2768040 528000)";
int_point_type ia;
double_point_type da;
bg::model::segment<int_point_type> ib;
bg::model::segment<double_point_type> db;
bg::read_wkt(a, ia);
bg::read_wkt(b, ib);
bg::read_wkt(a, da);
bg::read_wkt(b, db);
BOOST_AUTO(idist, bg::distance(ia, ib));
BOOST_AUTO(ddist, bg::distance(da, db));
BOOST_CHECK_MESSAGE(std::abs(idist - ddist) < 0.1,
"within<a double> different from within<an int>");
}
}
int test_main(int, char* [])
{
#ifdef TEST_ARRAY
//test_all<int[2]>();
//test_all<float[2]>();
//test_all<double[2]>();
//test_all<test::test_point>(); // located here because of 3D
#endif
test_large_integers();
test_all<bg::model::d2::point_xy<int> >();
test_all<boost::tuple<float, float> >();
test_all<bg::model::d2::point_xy<float> >();
test_all<bg::model::d2::point_xy<double> >();
#ifdef HAVE_TTMATH
test_all<bg::model::d2::point_xy<ttmath_big> >();
#endif
test_empty_input<bg::model::d2::point_xy<int> >();
return 0;
}
| 35.761765
| 130
| 0.646188
|
ballisticwhisper
|
04c4a1e668c92d6d04fedc86ecec1fb61227f8bc
| 4,707
|
hpp
|
C++
|
source/backend/cpu/BinaryUtils.hpp
|
WillTao-RD/MNN
|
48575121859093bab8468d6992596962063b7aff
|
[
"Apache-2.0"
] | 2
|
2020-12-15T13:56:31.000Z
|
2022-01-26T03:20:28.000Z
|
source/backend/cpu/BinaryUtils.hpp
|
qaz734913414/MNN
|
a5d5769789054a76c6e4dce2ef97d1f45b0e7e2d
|
[
"Apache-2.0"
] | null | null | null |
source/backend/cpu/BinaryUtils.hpp
|
qaz734913414/MNN
|
a5d5769789054a76c6e4dce2ef97d1f45b0e7e2d
|
[
"Apache-2.0"
] | 1
|
2021-11-24T06:26:27.000Z
|
2021-11-24T06:26:27.000Z
|
#include <math.h>
#include <algorithm>
template <typename _Arg1, typename _Arg2, typename _ErrorCode>
struct BinaryMax : std::binary_function<_Arg1, _Arg2, _ErrorCode> {
_ErrorCode operator()(const _Arg1& x, const _Arg2& y) const {
return std::max(x, y);
}
};
template <typename _Arg1, typename _Arg2, typename _ErrorCode>
struct BinaryMin : std::binary_function<_Arg1, _Arg2, _ErrorCode> {
_ErrorCode operator()(const _Arg1& x, const _Arg2& y) const {
return std::min(x, y);
}
};
template <typename _Arg1, typename _Arg2, typename _ErrorCode>
struct BinaryMul : std::binary_function<_Arg1, _Arg2, _ErrorCode> {
_ErrorCode operator()(const _Arg1& x, const _Arg2& y) const {
return x * y;
}
};
template <typename _Arg1, typename _Arg2, typename _ErrorCode>
struct BinaryAdd : std::binary_function<_Arg1, _Arg2, _ErrorCode> {
_ErrorCode operator()(const _Arg1& x, const _Arg2& y) const {
return x + y;
}
};
template <typename _Arg1, typename _Arg2, typename _ErrorCode>
struct BinarySub : std::binary_function<_Arg1, _Arg2, _ErrorCode> {
_ErrorCode operator()(const _Arg1& x, const _Arg2& y) const {
return x - y;
}
};
template <typename _Arg1, typename _Arg2, typename _ErrorCode>
struct BinaryRealDiv : std::binary_function<_Arg1, _Arg2, _ErrorCode> {
_ErrorCode operator()(const _Arg1& x, const _Arg2& y) const {
return x / y;
}
};
template <typename _Arg1, typename _Arg2, typename _ErrorCode>
struct BinaryMod : std::binary_function<_Arg1, _Arg2, _ErrorCode> {
_ErrorCode operator()(const _Arg1& x, const _Arg2& y) const {
return x - x / y;
}
};
template <typename _Arg1, typename _Arg2, typename _ErrorCode>
struct BinaryGreater : std::binary_function<_Arg1, _Arg2, _ErrorCode> {
_ErrorCode operator()(const _Arg1& x, const _Arg2& y) const {
return (_ErrorCode)((x > y) ? 1 : 0);
}
};
template <typename _Arg1, typename _Arg2, typename _ErrorCode>
struct BinaryLess : std::binary_function<_Arg1, _Arg2, _ErrorCode> {
_ErrorCode operator()(const _Arg1& x, const _Arg2& y) const {
return (_ErrorCode)((x < y) ? 1 : 0);
}
};
template <typename _Arg1, typename _Arg2, typename _ErrorCode>
struct BinaryGreaterEqual : std::binary_function<_Arg1, _Arg2, _ErrorCode> {
_ErrorCode operator()(const _Arg1& x, const _Arg2& y) const {
return (_ErrorCode)((x >= y) ? 1 : 0);
}
};
template <typename _Arg1, typename _Arg2, typename _ErrorCode>
struct BinaryLessEqual : std::binary_function<_Arg1, _Arg2, _ErrorCode> {
_ErrorCode operator()(const _Arg1& x, const _Arg2& y) const {
return (_ErrorCode)((x <= y) ? 1 : 0);
}
};
template <typename _Arg1, typename _Arg2, typename _ErrorCode>
struct BinaryEqual : std::binary_function<_Arg1, _Arg2, _ErrorCode> {
_ErrorCode operator()(const _Arg1& x, const _Arg2& y) const {
return (_ErrorCode)((x == y) ? 1 : 0);
}
};
template <typename _Arg1, typename _Arg2, typename _ErrorCode>
struct BinaryFloorDiv : std::binary_function<_Arg1, _Arg2, _ErrorCode> {
_ErrorCode operator()(const _Arg1& x, const _Arg2& y) const {
return floor(static_cast<float>(x) / y);
}
};
template <typename _Arg1, typename _Arg2, typename _ErrorCode>
struct BinaryFloorMod : std::binary_function<_Arg1, _Arg2, _ErrorCode> {
_ErrorCode operator()(const _Arg1& x, const _Arg2& y) const {
return x - floor(x / y) * y;
}
};
template <typename _Arg1, typename _Arg2, typename _ErrorCode>
struct BinarySquaredDifference : std::binary_function<_Arg1, _Arg2, _ErrorCode> {
_ErrorCode operator()(const _Arg1& x, const _Arg2& y) const {
return (x - y) * (x - y);
}
};
template <typename _Arg1, typename _Arg2, typename _ErrorCode>
struct BinaryPow : std::binary_function<_Arg1, _Arg2, _ErrorCode> {
_ErrorCode operator()(const _Arg1& x, const _Arg2& y) const {
return pow(x, y);
}
};
template <typename _Arg1, typename _Arg2, typename _ErrorCode>
struct BinaryAtan2 : std::binary_function<_Arg1, _Arg2, _ErrorCode> {
_ErrorCode operator()(const _Arg1& x, const _Arg2& y) const {
return atan(x / y);
}
};
template <typename _Arg1, typename _Arg2, typename _ErrorCode>
struct BinaryLogicalOr : std::binary_function<_Arg1, _Arg2, _ErrorCode> {
_ErrorCode operator()(const _Arg1& x, const _Arg2& y) const {
return (_ErrorCode)((x || y) ? 1 : 0);
}
};
template <typename _Arg1, typename _Arg2, typename _ErrorCode>
struct BinaryNotEqual : std::binary_function<_Arg1, _Arg2, _ErrorCode> {
_ErrorCode operator()(const _Arg1& x, const _Arg2& y) const {
return (_ErrorCode)((x != y) ? 1 : 0);
}
};
| 35.931298
| 81
| 0.685575
|
WillTao-RD
|
04c66380d944ef3c3e85dce8af8ba6fe6bfff5e0
| 1,410
|
hpp
|
C++
|
cpp_module00/ex01/Phonebook.class.hpp
|
lesorres/CPP_Modules
|
9e7bba58320c92b39c0c81b630e9899f5b4d838a
|
[
"MIT"
] | null | null | null |
cpp_module00/ex01/Phonebook.class.hpp
|
lesorres/CPP_Modules
|
9e7bba58320c92b39c0c81b630e9899f5b4d838a
|
[
"MIT"
] | null | null | null |
cpp_module00/ex01/Phonebook.class.hpp
|
lesorres/CPP_Modules
|
9e7bba58320c92b39c0c81b630e9899f5b4d838a
|
[
"MIT"
] | null | null | null |
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* Phonebook.class.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: kmeeseek <kmeeseek@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/08/03 22:42:21 by kmeeseek #+# #+# */
/* Updated: 2021/08/09 20:44:32 by kmeeseek ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef PHONEBOOK_CLASS_HPP
# define PHONEBOOK_CLASS_HPP
# define CONT_NUM 8
# include "Contact.class.hpp"
# include <string>
#include <iostream>
#include <sstream>
class Phonebook
{
int _index;
int _full;
Contact _contact[CONT_NUM];
public:
void init_contacts();
void add_new_contact();
int print_contacts_table();
static void print_contact_atribute(std::string);
void print_index_cont(int i);
int get_index();
void set_full();
int get_full();
Phonebook(void);
~Phonebook(void);
};
#endif
| 33.571429
| 80
| 0.346809
|
lesorres
|
04ce514f7ca498b40cc050ad3ee2c30111d0f544
| 8,590
|
cpp
|
C++
|
simulator/GroupTuringTape.cpp
|
bcookOh1/TuringMachineSimulator
|
af413a8d5b6e188625d7e575b1944b9be3d816a5
|
[
"BSL-1.0"
] | null | null | null |
simulator/GroupTuringTape.cpp
|
bcookOh1/TuringMachineSimulator
|
af413a8d5b6e188625d7e575b1944b9be3d816a5
|
[
"BSL-1.0"
] | null | null | null |
simulator/GroupTuringTape.cpp
|
bcookOh1/TuringMachineSimulator
|
af413a8d5b6e188625d7e575b1944b9be3d816a5
|
[
"BSL-1.0"
] | null | null | null |
// file: GroupTuringTape.cpp
// Class: CS5800
// Project: Turing Machine Simulator
// Author: Bennett Cook
// Date: 4/08/2018
// Description: implementation the FLTK group control for the
// Turing Machine visual simulator
//
#include "GroupTuringTape.h"
#include <iostream>
#include <iomanip>
#include <boost\lexical_cast.hpp>
using namespace boost;
// ctor, note that the _width and _height are used in the parnet constructor
// these 2 vars must be static const types.
GroupTuringTape::GroupTuringTape(int x, int y) :
Fl_Scroll(x, y, _width, _height) {
Fl_Scroll::type(Fl_Scroll::HORIZONTAL_ALWAYS);
_initialXcoord = x;
_initialYcoord = y,
box(FL_THIN_UP_BOX);
color(FL_WHITE);
_tape = new Fl_Box(x + 4, y + 15, TAPE_SIZE, 48, TAPE_BOX_LABEL.c_str());
_tape->box(FL_BORDER_BOX);
_tape->color(FL_DARK2);
_tape->align(Fl_Align(FL_ALIGN_TOP_LEFT));
// the left index value allows
// for standard and two-way tape configurations
_leftIndexValue = 0;
int xOffset = 8;
int yOffset = 22;
for(std::size_t i = 0; i < NUMBER_TAPE_POSITIONS; i++) {
TapePosition *tp = new TapePosition(_initialXcoord + xOffset,
_initialYcoord + yOffset,
35, 35);
tp->SetValue('B');
tp->SetIndex(i);
xOffset += HEAD_OFFSET;
_positions.push_back(tp);
} // end for
_initialHeadxPosition = x + 8;
_initialHeadyPosition = y + 68;
// all tapeheads under the tape positions, this was not the original
// concept, which was make one and move it, but that didn't work with
// the fl_scroll, the x value changes with the scroll position
_currentHeadPosition = 0;
// try setting in all positions
for(std::size_t i = 0; i < NUMBER_TAPE_POSITIONS; i++) {
int hp = _initialHeadxPosition + (HEAD_OFFSET * (i));
TapeHead *h = new TapeHead(hp, _initialHeadyPosition);
// save the initial position for scroll positioning later
h->SetxPosition(hp);
// show the first hide the rest
if(i == _currentHeadPosition) {
h->Show();
}
else {
h->Hide();
} // end if
_headPositions.push_back(h);
} // end for
end(); // needed by fltk to end() addition of widgets to internal tree
} // end ctor
GroupTuringTape::~GroupTuringTape() {
// fltk deletes the widgets
} // end dtor
// SetConfiguration: setup the tape GUI elements
// pre: call this after configuration type is set following
// successful tm file readin
void GroupTuringTape::SetConfiguration(TmConfiguration configuration) {
// set the configurationType
if(TmConfiguration::Standard == configuration) {
_leftIndexValue = 0;
}
else {
_leftIndexValue = TWO_WAY_LEFT_INDEX;
} // end if
_currentHeadPosition = 0; // always zero at the start
// setup the tape with blanks and indexes for standard or two_way
for(std::size_t i = _currentHeadPosition; i < NUMBER_TAPE_POSITIONS; i++) {
_positions[i]->SetIndex(static_cast<int>(_leftIndexValue + i));
_positions[i]->SetValue(TAPE_BLANK_SYMBOL[0]);
} // end for
// set the initial head position
ResetHeadPosition();
return;
} // end SetConfiguration
// use this to initialize the entire tape
// after a run that may have written outside
// of the input string space
void GroupTuringTape::SetTapeToB() {
std::for_each(_positions.begin(), _positions.end(),
[&](TapePosition *tp){tp->SetValue(TAPE_BLANK_SYMBOL[0]);});
return;
} // end SetTapeToB
// return 0 success
// return -1 index out of range
int GroupTuringTape::SetSymbolAt(int idx, std::string symbol) {
int ret = -1;
if(static_cast<std::size_t>(idx) < _positions.size()) {
_positions[idx]->SetValue(symbol[0]);
ret = 0;
} // end if
return ret;
} // end SetSymbolAt
// return 0 success
// return -1 index out of range
int GroupTuringTape::SetIndexAt(int index, int value) {
int ret = -1;
if(static_cast<std::size_t>(index) < _positions.size()) {
_positions[index]->SetIndex(value);
ret = 0;
} // end if
return ret;
} // end SetIndexAt
// set the state string at current head position
// return 0 success
int GroupTuringTape::SetHeadState(std::string state) {
int ret = 0;
_headPositions[_currentHeadPosition]->SetState(state);
return ret;
} // end SetHeadState
// return 0 success
int GroupTuringTape::SetInitialHeadPosition() {
int ret = 0;
ResetHeadPosition();
return ret;
} // end SetInitialHeadPosition
// move the tape head so its positioned
// under the zero index tape cell
void GroupTuringTape::ResetHeadPosition() {
// ensure both head and tape vectors are the same size
if(_headPositions.size() != _positions.size()){
assert(false);
} // end if
_currentHeadPosition = GetZeroIndex();
for(std::size_t i = 0; i < _headPositions.size(); ++i){
if(i == _currentHeadPosition) {
_headPositions[i]->Show();
}
else {
_headPositions[i]->Hide();
} // end if
} // end for
KeepHeadInView();
return;
} // end ResetHeadPosition
// return the zero index value on the tape
// this is the index value not at _positions[0].
// needed to find zero cell in the two_way config
std::size_t GroupTuringTape::GetZeroIndex(){
std::size_t ret = 0;
for(std::size_t i = 0; i < _positions.size(); ++i) {
if(_positions[i]->GetIndex() == 0) {
ret = i;
break;
} // end if
} // end for
return ret;
} // end for
// move the tape head one cell to the right and
// keep the head in the scroll view.
// this will "show" the head at _currentHeadPosition (index)
// and hide the rest.
// return 0 on success
// return -1 on _currentHeadPosition >= NUMBER_TAPE_POSITIONS
int GroupTuringTape::MoveHeadRight() {
int ret = -1;
if(_currentHeadPosition < NUMBER_TAPE_POSITIONS){
_currentHeadPosition++;
for(std::size_t i = 0; i < _headPositions.size(); ++i) {
if(i == _currentHeadPosition) {
_headPositions[i]->Show();
}
else {
_headPositions[i]->Hide();
} // end if
} // end for
ret = 0;
} // end if
KeepHeadInView();
return ret;
} // end MoveHeadRight
// move the tape head one cell to the left and
// keep the head in the scroll view.
// this will "show" the head at _currentHeadPosition (index)
// and hide the rest.
// return 0 on success
// return -1 on _currentHeadPosition <= 0
int GroupTuringTape::MoveHeadLeft() {
int ret = -1;
if(_currentHeadPosition > 0) {
_currentHeadPosition--;
for(std::size_t i = 0; i < _headPositions.size(); ++i) {
if(i == _currentHeadPosition) {
_headPositions[i]->Show();
}
else {
_headPositions[i]->Hide();
} // end if
} // end for
ret = 0;
} // end if
KeepHeadInView();
return ret;
} // end MoveHeadLeft
// use the current head position to keep
// the head in the scroll view, use the actual head x position
// stored in the TapeHead class which allows the user to
// move the scroll bar and then on the next move KeepHeadInView()
// will put the head in the center (about) of the window
void GroupTuringTape::KeepHeadInView() {
int xPixelViewPosition = xposition();
int initialX = _headPositions[_currentHeadPosition]->GetxPosition();
// used to debug moving the scroll position
#ifdef _DEBUG
std::cout << "xv: " << xPixelViewPosition << ", initialX: "
<< initialX << std::endl;
#endif
// this will move the scroll position to center the head
// in the scroll window. it will only do this if necessary
// which shows about +/- 5 head positions until it moves again
if(initialX > xPixelViewPosition + _width) { // move right
int right = 0;
// set the right but limit to tape size right edge
if(initialX + (_width/2) < TAPE_SIZE)
right = initialX - (_width / 2);
else
right = TAPE_SIZE - _width;
scroll_to(right, Y_COORD_VIEW_POSITION);
}
else if(initialX < xPixelViewPosition) { // move left
int left = 0;
// set the left but limit to tape size left edge
if(initialX - (_width / 2) > HEAD_OFFSET)
left = initialX - (_width / 2);
else
left = 0;
scroll_to(left, Y_COORD_VIEW_POSITION);
} // end if
return;
} // end KeepHeadInView
| 26.269113
| 78
| 0.635157
|
bcookOh1
|
04cf21f546db2b88952083816ed1567c3082b624
| 1,352
|
cpp
|
C++
|
Engine/Src/SFEngine/Application/IOS/IOSApp.cpp
|
blue3k/StormForge
|
1557e699a673ae9adcc8f987868139f601ec0887
|
[
"Apache-2.0"
] | 1
|
2020-06-20T07:35:25.000Z
|
2020-06-20T07:35:25.000Z
|
Engine/Src/SFEngine/Application/IOS/IOSApp.cpp
|
blue3k/StormForge
|
1557e699a673ae9adcc8f987868139f601ec0887
|
[
"Apache-2.0"
] | null | null | null |
Engine/Src/SFEngine/Application/IOS/IOSApp.cpp
|
blue3k/StormForge
|
1557e699a673ae9adcc8f987868139f601ec0887
|
[
"Apache-2.0"
] | null | null | null |
////////////////////////////////////////////////////////////////////////////////
//
// CopyRight (c) 2017 Kyungkun Ko
//
// Author : KyungKun Ko
//
// Description : Basic IOS application
//
//
////////////////////////////////////////////////////////////////////////////////
#include "SFEnginePCH.h"
#if SF_PLATFORM == SF_PLATFORM_IOS
#include "SFAssert.h"
#include "Util/SFUtility.h"
#include "Application/IOS/IOSApp.h"
#include "Application/IOS/IOSAppTasks.h"
#include "Task/SFAsyncTaskManager.h"
#include "Util/SFLog.h"
#include "Util/SFLogComponent.h"
#include "Object/SFObjectManager.h"
#include "Util/SFTimeUtil.h"
#include "EngineObject/SFEngineObjectManager.h"
#include "EngineObject/SFEngineTaskManager.h"
#include "Net/SFNetSystem.h"
#include "Net/SFConnectionManager.h"
#include "Resource/SFResourceManager.h"
#include "Graphics/SFGraphicDeviceGLES.h"
#include "Net/SFNetConst.h"
#include "Service/SFEngineService.h"
namespace SF
{
constexpr StringCrc64 IOSApp::TypeName;
IOSApp::IOSApp()
{
}
IOSApp::~IOSApp()
{
}
Result IOSApp::InitializeComponent()
{
ApplicationBase::InitializeComponent();
return true;
}
void IOSApp::DeinitializeComponent()
{
ApplicationBase::DeinitializeComponent();
}
}
#else
void IOSApp_Dummy() {}
#endif
| 19.042254
| 81
| 0.610947
|
blue3k
|
04d159efcd1ee9d4c9e160b72a83fee2ffb1109f
| 3,598
|
cpp
|
C++
|
Tests/Source/UnorderedMapTests.cpp
|
seeduvax/LuaBridge
|
c0dcc9de066e797e4e171b5a215e0621b4f05f87
|
[
"X11",
"MIT"
] | 7
|
2020-10-16T11:34:27.000Z
|
2022-03-12T17:53:15.000Z
|
Tests/Source/UnorderedMapTests.cpp
|
seeduvax/LuaBridge
|
c0dcc9de066e797e4e171b5a215e0621b4f05f87
|
[
"X11",
"MIT"
] | 1
|
2020-10-06T17:52:17.000Z
|
2020-10-06T17:52:17.000Z
|
Tests/Source/UnorderedMapTests.cpp
|
seeduvax/LuaBridge
|
c0dcc9de066e797e4e171b5a215e0621b4f05f87
|
[
"X11",
"MIT"
] | 6
|
2021-05-06T15:09:52.000Z
|
2022-03-12T17:57:14.000Z
|
// https://github.com/vinniefalco/LuaBridge
//
// Copyright 2019, Dmitry Tarakanov
// SPDX-License-Identifier: MIT
#include "TestBase.h"
#include "LuaBridge/UnorderedMap.h"
#include <unordered_map>
struct UnorderedMapTests : TestBase
{
};
namespace {
struct Data
{
/* explicit */ Data(int i) : i(i) {}
int i;
};
} // namespace
namespace std {
template <>
struct hash <Data>
{
size_t operator() (const Data& value) const noexcept
{
return 0; // Don't care about hash collisions
}
};
template <>
struct hash <::luabridge::LuaRef>
{
size_t operator() (const ::luabridge::LuaRef& value) const
{
return 0; // Don't care about hash collisions
}
};
} // namespace std
TEST_F (UnorderedMapTests, LuaRef)
{
{
runLua ("result = {[false] = true, a = 'abc', [1] = 5, [3.14] = -1.1}");
using Map = std::unordered_map <luabridge::LuaRef, luabridge::LuaRef>;
Map expected {
{luabridge::LuaRef (L, false), luabridge::LuaRef (L, true)},
{luabridge::LuaRef (L, 'a'), luabridge::LuaRef (L, "abc")},
{luabridge::LuaRef (L, 1), luabridge::LuaRef (L, 5)},
{luabridge::LuaRef (L, 3.14), luabridge::LuaRef (L, -1.1)},
};
Map actual = result ();
ASSERT_EQ (expected, actual);
ASSERT_EQ (expected, result <Map> ());
}
{
runLua ("result = {'a', 'b', 'c'}");
using Int2Char = std::unordered_map <int, char>;
Int2Char expected {{1, 'a'}, {2, 'b'}, {3, 'c'}};
Int2Char actual = result ();
ASSERT_EQ (expected, actual);
ASSERT_EQ (expected, result <Int2Char> ());
}
}
TEST_F (UnorderedMapTests, PassToFunction)
{
runLua (
"function foo (map) "
" result = map "
"end");
auto foo = luabridge::getGlobal (L, "foo");
using Int2Bool = std::unordered_map <int, bool>;
resetResult ();
Int2Bool lvalue {{10, false}, {20, true}, {30, true}};
foo (lvalue);
ASSERT_TRUE (result ().isTable ());
ASSERT_EQ (lvalue, result <Int2Bool> ());
resetResult ();
const Int2Bool constLvalue = lvalue;
foo (constLvalue);
ASSERT_TRUE (result ().isTable ());
ASSERT_EQ (constLvalue, result <Int2Bool> ());
}
namespace {
bool operator== (const Data& lhs, const Data& rhs)
{
return lhs.i == rhs.i;
}
bool operator< (const Data& lhs, const Data& rhs)
{
return lhs.i < rhs.i;
}
std::ostream& operator<< (std::ostream& lhs, const Data& rhs)
{
lhs << "{" << rhs.i << "}";
return lhs;
}
std::unordered_map <Data, Data> processValues (const std::unordered_map <Data, Data>& data)
{
return data;
}
std::unordered_map <Data, Data> processPointers (const std::unordered_map <Data, const Data*>& data)
{
std::unordered_map <Data, Data> result;
for (const auto& item : data)
{
result.emplace (item.first, *item.second);
}
return result;
}
} // namespace
TEST_F (UnorderedMapTests, PassFromLua)
{
luabridge::getGlobalNamespace (L)
.beginClass <Data> ("Data")
.addConstructor <void (*) (int)> ()
.endClass ()
.addFunction ("processValues", &processValues)
.addFunction ("processPointers", &processPointers);
{
resetResult ();
runLua ("result = processValues ({[Data (-1)] = Data (2)})");
std::unordered_map <Data, Data> expected {{Data (-1), Data (2)}};
const auto actual = result <std::unordered_map <Data, Data>> ();
ASSERT_EQ (expected, actual);
}
{
resetResult ();
runLua ("result = processValues ({[Data (3)] = Data (-4)})");
std::unordered_map <Data, Data> expected {{Data (3), Data (-4)}};
const auto actual = result <std::unordered_map <Data, Data>> ();
ASSERT_EQ (expected, actual);
}
}
| 22.07362
| 100
| 0.619511
|
seeduvax
|
04d376050083642a6f25eb2b6d3bcc5a63abc4b0
| 19,850
|
cpp
|
C++
|
source/games/exhumed/src/lighting.cpp
|
DosFreak/Raze
|
389f760d45748da28ba758f12be1be2a9ba9b4b2
|
[
"RSA-MD"
] | null | null | null |
source/games/exhumed/src/lighting.cpp
|
DosFreak/Raze
|
389f760d45748da28ba758f12be1be2a9ba9b4b2
|
[
"RSA-MD"
] | null | null | null |
source/games/exhumed/src/lighting.cpp
|
DosFreak/Raze
|
389f760d45748da28ba758f12be1be2a9ba9b4b2
|
[
"RSA-MD"
] | null | null | null |
//-------------------------------------------------------------------------
/*
Copyright (C) 2010-2019 EDuke32 developers and contributors
Copyright (C) 2019 sirlemonhead, Nuke.YKT
This file is part of PCExhumed.
PCExhumed is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License version 2
as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
//-------------------------------------------------------------------------
#include "ns.h"
#include "aistuff.h"
#include "player.h"
#include "engine.h"
#include "exhumed.h"
#include "sound.h"
#include "interpolate.h"
#include <string.h>
#include <assert.h>
BEGIN_PS_NS
enum
{
kMaxFlashes = 2000,
kMaxFlickerMask = 25,
kMaxGlows = 50,
kMaxFlickers = 100,
kMaxFlows = 375,
};
struct Flash
{
int8_t nType;
int8_t shade;
DExhumedActor* pActor;
int nIndex;
int next;
};
struct Glow
{
short field_0;
short field_2;
short nSector;
short field_6;
};
struct Flicker
{
short field_0;
short nSector;
unsigned int field_4;
};
struct Flow
{
short objindex;
short type;
int xdelta;
int ydelta;
int angcos;
int angsin;
int xacc;
int yacc;
};
FreeListArray<Flash, kMaxFlashes> sFlash;
Glow sGlow[kMaxGlows];
Flicker sFlicker[kMaxFlickers];
Flow sFlowInfo[kMaxFlows];
int flickermask[kMaxFlickerMask];
short bTorch = 0;
short nFirstFlash = -1;
short nLastFlash = -1;
short nFlashDepth = 2;
short nFlowCount;
short nFlickerCount;
short nGlowCount;
int bDoFlicks = 0;
int bDoGlows = 0;
FSerializer& Serialize(FSerializer& arc, const char* keyname, Flash& w, Flash* def)
{
if (arc.BeginObject(keyname))
{
arc("at0", w.nType)
("shade", w.shade)
("at1", w.nIndex)
("next", w.next)
.EndObject();
}
return arc;
}
FSerializer& Serialize(FSerializer& arc, const char* keyname, Glow& w, Glow* def)
{
if (arc.BeginObject(keyname))
{
arc("at0", w.field_0)
("at2", w.field_2)
("sector", w.nSector)
("at6", w.field_6)
.EndObject();
}
return arc;
}
FSerializer& Serialize(FSerializer& arc, const char* keyname, Flicker& w, Flicker* def)
{
if (arc.BeginObject(keyname))
{
arc("at0", w.field_0)
("sector", w.nSector)
("at4", w.field_4)
.EndObject();
}
return arc;
}
FSerializer& Serialize(FSerializer& arc, const char* keyname, Flow& w, Flow* def)
{
if (arc.BeginObject(keyname))
{
arc("objindex", w.objindex)
("type", w.type)
("xdelta", w.xdelta)
("ydelta", w.ydelta)
("atc", w.angcos)
("at10", w.angsin)
("xacc", w.xacc)
("yacc", w.yacc)
.EndObject();
}
return arc;
}
void SerializeLighting(FSerializer& arc)
{
if (arc.BeginObject("lighting"))
{
arc("flash", sFlash)
("glowcount", nGlowCount)
.Array("glow", sGlow, nGlowCount)
("flickercount", nFlickerCount)
.Array("flicker", sFlicker, nFlickerCount)
("flowcount", nFlowCount)
.Array("flow", sFlowInfo, nFlowCount)
.Array("flickermask", flickermask, countof(flickermask))
("torch", bTorch)
("firstflash", nFirstFlash)
("lastflash", nLastFlash)
("flashdepth", nFlashDepth)
("doflicks", bDoFlicks)
("doglows", bDoGlows)
.EndObject();
}
}
// done
int GrabFlash()
{
int nFlash = sFlash.Get();
if (nFlash < 0) {
return -1;
}
sFlash[nFlash].next = -1;
if (nLastFlash <= -1)
{
nFirstFlash = nFlash;
}
else
{
sFlash[nLastFlash].next = nFlash;
}
nLastFlash = nFlash;
return nLastFlash;
}
void InitLights()
{
int i;
nFlickerCount = 0;
for (i = 0; i < kMaxFlickerMask; i++) {
flickermask[i] = RandomSize(0x1F) * 2;
}
nGlowCount = 0;
nFlowCount = 0;
bDoFlicks = false;
bDoGlows = false;
sFlash.Clear();
nFirstFlash = -1;
nLastFlash = -1;
}
void AddFlash(short nSector, int x, int y, int z, int val)
{
assert(nSector >= 0 && nSector < kMaxSectors);
int var_28 = 0;
int var_1C = val >> 8;
if (var_1C >= nFlashDepth) {
return;
}
unsigned int var_20 = val & 0x80;
unsigned int var_18 = val & 0x40;
val = ((var_1C + 1) << 8) | (val & 0xff);
int var_14 = 0;
short startwall = sector[nSector].wallptr;
short endwall = sector[nSector].wallptr + sector[nSector].wallnum;
for (int i = startwall; i < endwall; i++)
{
short wall2 = wall[i].point2;
int xAverage = (wall[i].x + wall[wall2].x) / 2;
int yAverage = (wall[i].y + wall[wall2].y) / 2;
sectortype *pNextSector = NULL;
if (wall[i].nextsector > -1) {
pNextSector = §or[wall[i].nextsector];
}
int ebx = -255;
if (!var_18)
{
int x2 = x - xAverage;
if (x2 < 0) {
x2 = -x2;
}
ebx = x2;
int y2 = y - yAverage;
if (y2 < 0) {
y2 = -y2;
}
ebx = ((y2 + ebx) >> 4) - 255;
}
if (ebx < 0)
{
var_14++;
var_28 += ebx;
if (wall[i].pal < 5)
{
if (!pNextSector || pNextSector->floorz < sector[nSector].floorz)
{
short nFlash = GrabFlash();
if (nFlash < 0) {
return;
}
sFlash[nFlash].nType = var_20 | 2;
sFlash[nFlash].shade = wall[i].shade;
sFlash[nFlash].nIndex = i;
wall[i].pal += 7;
ebx += wall[i].shade;
int eax = ebx;
if (ebx < -127) {
eax = -127;
}
wall[i].shade = eax;
if (!var_1C && !wall[i].overpicnum && pNextSector)
{
AddFlash(wall[i].nextsector, x, y, z, val);
}
}
}
}
}
if (var_14 && sector[nSector].floorpal < 4)
{
short nFlash = GrabFlash();
if (nFlash < 0) {
return;
}
sFlash[nFlash].nType = var_20 | 1;
sFlash[nFlash].nIndex = nSector;
sFlash[nFlash].shade = sector[nSector].floorshade;
sector[nSector].floorpal += 7;
int edx = sector[nSector].floorshade + var_28;
int eax = edx;
if (edx < -127) {
eax = -127;
}
sector[nSector].floorshade = eax;
if (!(sector[nSector].ceilingstat & 1))
{
if (sector[nSector].ceilingpal < 4)
{
short nFlash2 = GrabFlash();
if (nFlash2 >= 0)
{
sFlash[nFlash2].nType = var_20 | 3;
sFlash[nFlash2].nIndex = nSector;
sFlash[nFlash2].shade = sector[nSector].ceilingshade;
sector[nSector].ceilingpal += 7;
int edx = sector[nSector].ceilingshade + var_28;
int eax = edx;
if (edx < -127) {
eax = -127;
}
sector[nSector].ceilingshade = eax;
}
}
}
ExhumedSectIterator it(nSector);
while (auto pActor = it.Next())
{
auto pSprite = &pActor->s();
if (pSprite->pal < 4)
{
short nFlash3 = GrabFlash();
if (nFlash3 >= 0)
{
sFlash[nFlash3].nType = var_20 | 4;
sFlash[nFlash3].shade = pSprite->shade;
sFlash[nFlash3].nIndex = -1;
sFlash[nFlash3].pActor = pActor;
pSprite->pal += 7;
int eax = -255;
if (!var_18)
{
int xDiff = x - pSprite->x;
if (xDiff < 0) {
xDiff = -xDiff;
}
int yDiff = y - pSprite->y;
if (yDiff < 0) {
yDiff = -yDiff;
}
eax = ((xDiff + yDiff) >> 4) - 255;
}
if (eax < 0)
{
short shade = pSprite->shade + eax;
if (shade < -127) {
shade = -127;
}
pSprite->shade = (int8_t)shade;
}
}
}
}
}
}
void UndoFlashes()
{
int var_24 = 0; // CHECKME - Watcom error "initializer for variable var_24 may not execute
int edi = -1;
for (short nFlash = nFirstFlash; nFlash >= 0; nFlash = sFlash[nFlash].next)
{
assert(nFlash < 2000 && nFlash >= 0);
uint8_t type = sFlash[nFlash].nType & 0x3F;
short nIndex = sFlash[nFlash].nIndex;
if (sFlash[nFlash].nType & 0x80)
{
int flashtype = type - 1;
assert(flashtype >= 0);
int8_t *pShade = NULL;
switch (flashtype)
{
case 0:
{
assert(nIndex >= 0 && nIndex < kMaxSectors);
pShade = §or[nIndex].floorshade;
break;
}
case 1:
{
assert(nIndex >= 0 && nIndex < kMaxWalls);
pShade = &wall[nIndex].shade;
break;
}
case 2:
{
assert(nIndex >= 0 && nIndex < kMaxSectors);
pShade = §or[nIndex].ceilingshade;
break;
}
case 3:
{
auto ac = sFlash[nFlash].pActor;
if (!ac) continue;
auto sp = &ac->s();
if (sp->pal >= 7)
{
pShade = &sp->shade;
}
else {
goto loc_1868A;
}
break;
}
default:
break;
}
assert(pShade != NULL);
int thisshade = (*pShade) + 6;
int maxshade = sFlash[nFlash].shade;
if (thisshade < maxshade)
{
*pShade = (int8_t)thisshade;
edi = nFlash;
continue;
}
}
// loc_185FE
var_24 = type - 1; // CHECKME - Watcom error "initializer for variable var_24 may not execute
assert(var_24 >= 0);
switch (var_24)
{
default:
break;
case 0:
{
sector[nIndex].floorpal -= 7;
sector[nIndex].floorshade = sFlash[nFlash].shade;
break;
}
case 1:
{
wall[nIndex].pal -= 7;
wall[nIndex].shade = sFlash[nFlash].shade;
break;
}
case 2:
{
sector[nIndex].ceilingpal -= 7;
sector[nIndex].ceilingshade = sFlash[nFlash].shade;
break;
}
case 3:
{
auto ac = sFlash[nFlash].pActor;
auto sp = &ac->s();
if (sp->pal >= 7)
{
sp->pal -= 7;
sp->shade = sFlash[nFlash].shade;
}
break;
}
}
loc_1868A:
if (edi != -1)
{
sFlash[edi].next = sFlash[nFlash].next;
}
if (nFlash == nFirstFlash)
{
nFirstFlash = sFlash[nFirstFlash].next;
}
if (nFlash == nLastFlash)
{
nLastFlash = edi;
}
sFlash.Release(nFlash);
}
}
void AddGlow(short nSector, int nVal)
{
if (nGlowCount >= kMaxGlows) {
return;
}
sGlow[nGlowCount].field_6 = nVal;
sGlow[nGlowCount].nSector = nSector;
sGlow[nGlowCount].field_0 = -1;
sGlow[nGlowCount].field_2 = 0;
nGlowCount++;
}
// ok
void AddFlicker(short nSector, int nVal)
{
if (nFlickerCount >= kMaxFlickers) {
return;
}
sFlicker[nFlickerCount].field_0 = nVal;
sFlicker[nFlickerCount].nSector = nSector;
if (nVal >= 25) {
nVal = 24;
}
sFlicker[nFlickerCount].field_4 = flickermask[nVal];
nFlickerCount++;
}
void DoGlows()
{
bDoGlows++;
if (bDoGlows < 3) {
return;
}
bDoGlows = 0;
for (int i = 0; i < nGlowCount; i++)
{
sGlow[i].field_2++;
short nSector = sGlow[i].nSector;
short nShade = sGlow[i].field_0;
if (sGlow[i].field_2 >= sGlow[i].field_6)
{
sGlow[i].field_2 = 0;
sGlow[i].field_0 = -sGlow[i].field_0;
}
sector[nSector].ceilingshade += nShade;
sector[nSector].floorshade += nShade;
int startwall = sector[nSector].wallptr;
int endwall = startwall + sector[nSector].wallnum - 1;
for (int nWall = startwall; nWall <= endwall; nWall++)
{
wall[nWall].shade += nShade;
// CHECKME - ASM has edx decreasing here. why?
}
}
}
void DoFlickers()
{
bDoFlicks ^= 1;
if (!bDoFlicks) {
return;
}
for (int i = 0; i < nFlickerCount; i++)
{
short nSector = sFlicker[i].nSector;
unsigned int eax = (sFlicker[i].field_4 & 1);
unsigned int edx = (sFlicker[i].field_4 & 1) << 31;
unsigned int ebp = sFlicker[i].field_4 >> 1;
ebp |= edx;
edx = ebp & 1;
sFlicker[i].field_4 = ebp;
if (edx ^ eax)
{
short shade;
if (eax)
{
shade = sFlicker[i].field_0;
}
else
{
shade = -sFlicker[i].field_0;
}
sector[nSector].ceilingshade += shade;
sector[nSector].floorshade += shade;
int startwall = sector[nSector].wallptr;
int endwall = startwall + sector[nSector].wallnum - 1;
for (int nWall = endwall; nWall >= startwall; nWall--)
{
wall[nWall].shade += shade;
// CHECKME - ASM has edx decreasing here. why?
}
}
}
}
// nWall can also be passed in here via nSprite parameter - TODO - rename nSprite parameter :)
void AddFlow(int nIndex, int nSpeed, int b, int nAngle)
{
if (nFlowCount >= kMaxFlows)
return;
short nFlow = nFlowCount;
nFlowCount++;
if (b < 2)
{
short nPic = sector[nIndex].floorpicnum;
sFlowInfo[nFlow].xacc = (tileWidth(nPic) << 14) - 1;
sFlowInfo[nFlow].yacc = (tileHeight(nPic) << 14) - 1;
sFlowInfo[nFlow].angcos = -bcos(nAngle) * nSpeed;
sFlowInfo[nFlow].angsin = bsin(nAngle) * nSpeed;
sFlowInfo[nFlow].objindex = nIndex;
StartInterpolation(nIndex, b ? Interp_Sect_CeilingPanX : Interp_Sect_FloorPanX);
StartInterpolation(nIndex, b ? Interp_Sect_CeilingPanY : Interp_Sect_FloorPanY);
}
else
{
StartInterpolation(nIndex, Interp_Wall_PanX);
StartInterpolation(nIndex, Interp_Wall_PanY);
short nAngle;
if (b == 2) {
nAngle = 512;
}
else {
nAngle = 1536;
}
short nPic = wall[nIndex].picnum;
sFlowInfo[nFlow].xacc = (tileWidth(nPic) * wall[nIndex].xrepeat) << 8;
sFlowInfo[nFlow].yacc = (tileHeight(nPic) * wall[nIndex].yrepeat) << 8;
sFlowInfo[nFlow].angcos = -bcos(nAngle) * nSpeed;
sFlowInfo[nFlow].angsin = bsin(nAngle) * nSpeed;
sFlowInfo[nFlow].objindex = nIndex;
}
sFlowInfo[nFlow].ydelta = 0;
sFlowInfo[nFlow].xdelta = 0;
sFlowInfo[nFlow].type = b;
}
void DoFlows()
{
for (int i = 0; i < nFlowCount; i++)
{
sFlowInfo[i].xdelta += sFlowInfo[i].angcos;
sFlowInfo[i].ydelta += sFlowInfo[i].angsin;
switch (sFlowInfo[i].type)
{
case 0:
{
sFlowInfo[i].xdelta &= sFlowInfo[i].xacc;
sFlowInfo[i].ydelta &= sFlowInfo[i].yacc;
short nSector = sFlowInfo[i].objindex;
sector[nSector].setfloorxpan(sFlowInfo[i].xdelta / 16384.f);
sector[nSector].setfloorypan(sFlowInfo[i].ydelta / 16384.f);
break;
}
case 1:
{
short nSector = sFlowInfo[i].objindex;
sector[nSector].setceilingxpan(sFlowInfo[i].xdelta / 16384.f);
sector[nSector].setceilingypan(sFlowInfo[i].ydelta / 16384.f);
sFlowInfo[i].xdelta &= sFlowInfo[i].xacc;
sFlowInfo[i].ydelta &= sFlowInfo[i].yacc;
break;
}
case 2:
{
short nWall = sFlowInfo[i].objindex;
wall[nWall].setxpan(sFlowInfo[i].xdelta / 16384.f);
wall[nWall].setypan(sFlowInfo[i].ydelta / 16384.f);
if (sFlowInfo[i].xdelta < 0)
{
sFlowInfo[i].xdelta += sFlowInfo[i].xacc;
}
if (sFlowInfo[i].ydelta < 0)
{
sFlowInfo[i].ydelta += sFlowInfo[i].yacc;
}
break;
}
case 3:
{
short nWall = sFlowInfo[i].objindex;
wall[nWall].setxpan(sFlowInfo[i].xdelta / 16384.f);
wall[nWall].setypan(sFlowInfo[i].ydelta / 16384.f);
if (sFlowInfo[i].xdelta >= sFlowInfo[i].xacc)
{
sFlowInfo[i].xdelta -= sFlowInfo[i].xacc;
}
if (sFlowInfo[i].ydelta >= sFlowInfo[i].yacc)
{
sFlowInfo[i].ydelta -= sFlowInfo[i].yacc;
}
break;
}
}
}
}
void DoLights()
{
DoFlickers();
DoGlows();
DoFlows();
}
void SetTorch(int nPlayer, int bTorchOnOff)
{
if (bTorchOnOff == bTorch) {
return;
}
if (nPlayer != nLocalPlayer) {
return;
}
if (bTorchOnOff == 2) {
bTorch = !bTorch;
}
else {
bTorch = bTorchOnOff;
}
if (bTorch) {
PlayLocalSound(StaticSound[kSoundTorchOn], 0);
}
const char* buf = bTorch ? "TXT_EX_TORCHLIT" : "TXT_EX_TORCHOUT";
StatusMessage(150, GStrings(buf));
}
void BuildFlash(short nPlayer, short, int nVal)
{
if (nPlayer == nLocalPlayer)
{
flash = nVal;
flash = -nVal; // ???
}
}
END_PS_NS
| 23.886883
| 101
| 0.469521
|
DosFreak
|
04d56e553db29acc82a1c5268364981f0b0a08aa
| 2,645
|
cpp
|
C++
|
cilk_max.cpp
|
gonidelis/openCilk_algorithms
|
c8e7a12a545f9011c66dd00440899a763a8719e3
|
[
"MIT"
] | null | null | null |
cilk_max.cpp
|
gonidelis/openCilk_algorithms
|
c8e7a12a545f9011c66dd00440899a763a8719e3
|
[
"MIT"
] | null | null | null |
cilk_max.cpp
|
gonidelis/openCilk_algorithms
|
c8e7a12a545f9011c66dd00440899a763a8719e3
|
[
"MIT"
] | null | null | null |
#include <cilk/cilk.h>
#include "opencilk_reducer.hpp"
#include <cilk/reducer_max.h>
#include <iostream>
#include <chrono>
#include <fstream>
#include <vector>
#include <random>
#include <exception>
#define N 1'000'000
int test_count = 100;
unsigned int seed = std::random_device{}();
std::mt19937 gen(seed);
int measure_seq_max(std::vector<int> const& vec)
{
int max = vec[0];
// Compute the max of integers 1..n
for(unsigned int i = 1; i <= vec.size(); ++i)
{
if(vec[i] > max)
{
max = vec[i];
}
}
return max;
}
void measure_cilk_max(std::vector<int> const& vec)
{
cilk::reducer<cilk::op_max<int> > rm;
cilk_for (int i = 0; i < vec.size(); ++i)
{
rm->calc_max(vec[i]); // *rm = cilk::max_of(*max, vec[i])
}
// // TESTING. DON'T ENABLE IF BENCHMARKING RUNTIME
// if(measure_seq_max(vec) != rm.get_value())
// {
// std::cout << "Error!" << rm.get_value() << "!=" << measure_seq_max(vec) << std::endl;
// throw std::exception();
// }
// std::cout << "maximum value is " << rm.get_value() << std::endl;
}
double averageout_cilk_max(std::vector<int> const& vec)
{
auto start = std::chrono::high_resolution_clock::now();
// average out 100 executions to avoid varying results
for (auto i = 0; i < test_count; i++)
{
measure_cilk_max(vec);
}
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double, std::milli> elapsed_seconds = end-start;
return elapsed_seconds.count() / test_count;
}
double averageout_seq_max(std::vector<int> const& vec)
{
auto start = std::chrono::high_resolution_clock::now();
// average out 100 executions to avoid varying results
for (auto i = 0; i < test_count; i++)
{
measure_seq_max(vec);
}
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double, std::milli> elapsed_seconds = end-start;
return elapsed_seconds.count() / test_count;
}
int main(int argc, char* argv[])
{
std::ofstream f;
f.open ("max_times.csv");
f << "n,par,seq" << std::endl;
for(int n = 10 ; n < 1000000 ; n += 100 )
{
std::vector<int> vec(n);
std::iota(
std::begin(vec), std::end(vec), gen() % 1000);
auto time = averageout_cilk_max(vec);
f << n << "," << time << ',';
// time = averageout_seq_max(vec);
// f << time << std::endl;
f << std::endl;
// unsigned int correct = (N * (N+1)) / 2;
}
f.close();
return 0;
}
| 21.16
| 96
| 0.565974
|
gonidelis
|
3e2357eb5172c04336e7432bb42269bcc1602596
| 835
|
cc
|
C++
|
src/game/Strategic/LoadSaveStrategicMapElement.cc
|
oldlaptop/ja2-stracciatella
|
a29e729dfec564c3ef7f7990ed7d5cd6c2e1c2a8
|
[
"BSD-Source-Code"
] | null | null | null |
src/game/Strategic/LoadSaveStrategicMapElement.cc
|
oldlaptop/ja2-stracciatella
|
a29e729dfec564c3ef7f7990ed7d5cd6c2e1c2a8
|
[
"BSD-Source-Code"
] | null | null | null |
src/game/Strategic/LoadSaveStrategicMapElement.cc
|
oldlaptop/ja2-stracciatella
|
a29e729dfec564c3ef7f7990ed7d5cd6c2e1c2a8
|
[
"BSD-Source-Code"
] | null | null | null |
#include "Debug.h"
#include "FileMan.h"
#include "LoadSaveStrategicMapElement.h"
#include "LoadSaveData.h"
void ExtractStrategicMapElementFromFile(HWFILE const f, StrategicMapElement& e)
{
BYTE data[41];
FileRead(f, data, sizeof(data));
BYTE const* d = data;
EXTR_SKIP(d, 16)
EXTR_I8( d, e.bNameId)
EXTR_BOOL(d, e.fEnemyControlled)
EXTR_BOOL(d, e.fEnemyAirControlled)
EXTR_SKIP(d, 1)
EXTR_I8( d, e.bSAMCondition)
EXTR_SKIP(d, 20)
Assert(d == endof(data));
}
void InjectStrategicMapElementIntoFile(HWFILE const f, StrategicMapElement const& e)
{
BYTE data[41];
BYTE* d = data;
INJ_SKIP(d, 16)
INJ_I8( d, e.bNameId)
INJ_BOOL(d, e.fEnemyControlled)
INJ_BOOL(d, e.fEnemyAirControlled)
INJ_SKIP(d, 1)
INJ_I8( d, e.bSAMCondition)
INJ_SKIP(d, 20)
Assert(d == endof(data));
FileWrite(f, data, sizeof(data));
}
| 21.410256
| 84
| 0.720958
|
oldlaptop
|
3e23ea0bfa377348820266a3686d3453eca8633a
| 28,405
|
cpp
|
C++
|
src/common/umlReflection/src_gen/umlReflectionExec/LiteralRealObject.cpp
|
MDE4CPP/MDE4CPP
|
9db9352dd3b1ae26a5f640e614ed3925499b93f1
|
[
"MIT"
] | 12
|
2017-02-17T10:33:51.000Z
|
2022-03-01T02:48:10.000Z
|
src/common/umlReflection/src_gen/umlReflectionExec/LiteralRealObject.cpp
|
ndongmo/MDE4CPP
|
9db9352dd3b1ae26a5f640e614ed3925499b93f1
|
[
"MIT"
] | 28
|
2017-10-17T20:23:52.000Z
|
2021-03-04T16:07:13.000Z
|
src/common/umlReflection/src_gen/umlReflectionExec/LiteralRealObject.cpp
|
ndongmo/MDE4CPP
|
9db9352dd3b1ae26a5f640e614ed3925499b93f1
|
[
"MIT"
] | 22
|
2017-03-24T19:03:58.000Z
|
2022-03-31T12:10:07.000Z
|
#include "umlReflectionExec/LiteralRealObject.hpp"
//General Includes
#include "abstractDataTypes/SubsetUnion.hpp"
#include "uml/LiteralReal.hpp"
#include "umlReflection/UMLPackage.hpp"
#include "fUML/Semantics/Loci/Locus.hpp"
#include "uml/Class.hpp"
//Includes From Composite Structures
/*Not done for metamodel object classes*/
//Execution Engine Includes
#include "abstractDataTypes/Any.hpp"
#include "PSCS/Semantics/StructuredClassifiers/StructuredClassifiersFactory.hpp"
#include "PSCS/Semantics/StructuredClassifiers/CS_Reference.hpp"
#include "fUML/Semantics/SimpleClassifiers/SimpleClassifiersFactory.hpp"
#include "fUML/Semantics/Values/Value.hpp"
#include "fUML/Semantics/SimpleClassifiers/FeatureValue.hpp"
#include "PSCS/Semantics/StructuredClassifiers/CS_Link.hpp"
#include "PSCS/Semantics/StructuredClassifiers/CS_InteractionPoint.hpp"
#include "fUML/Semantics/CommonBehavior/Execution.hpp"
#include "fUML/Semantics/CommonBehavior/CommonBehaviorFactory.hpp"
#include "fUML/Semantics/Loci/ExecutionFactory.hpp"
#include "fUML/Semantics/Loci/ChoiceStrategy.hpp"
//UML Includes
#include "uml/umlPackage.hpp"
#include "uml/Association.hpp"
#include "uml/Connector.hpp"
#include "uml/ConnectorEnd.hpp"
#include "uml/Operation.hpp"
#include "uml/Property.hpp"
#include "uml/Port.hpp"
//Property Includes
#include "uml/Comment.hpp"
#include "umlReflectionExec/CommentObject.hpp"
#include "uml/Element.hpp"
#include "umlReflectionExec/ElementObject.hpp"
#include "uml/Element.hpp"
#include "umlReflectionExec/ElementObject.hpp"
#include "fUML/Semantics/SimpleClassifiers/RealValue.hpp"
#include "uml/Dependency.hpp"
#include "umlReflectionExec/DependencyObject.hpp"
#include "fUML/Semantics/SimpleClassifiers/StringValue.hpp"
#include "uml/StringExpression.hpp"
#include "umlReflectionExec/StringExpressionObject.hpp"
#include "uml/Namespace.hpp"
#include "umlReflectionExec/NamespaceObject.hpp"
#include "fUML/Semantics/SimpleClassifiers/StringValue.hpp"
#include "fUML/Semantics/SimpleClassifiers/EnumerationValue.hpp"
#include "uml/VisibilityKind.hpp"
#include "fUML/Semantics/SimpleClassifiers/EnumerationValue.hpp"
#include "uml/VisibilityKind.hpp"
#include "uml/TemplateParameter.hpp"
#include "umlReflectionExec/TemplateParameterObject.hpp"
#include "uml/TemplateParameter.hpp"
#include "umlReflectionExec/TemplateParameterObject.hpp"
#include "uml/Type.hpp"
#include "umlReflectionExec/TypeObject.hpp"
//Property Packages Includes
#include "primitivetypesReflection/PrimitiveTypesPackage.hpp"
using namespace UML;
LiteralRealObject::LiteralRealObject(std::shared_ptr<uml::LiteralReal> _element):
m_LiteralRealValue(_element)
{
this->getTypes()->insert(this->getTypes()->begin(), UML::UMLPackage::eInstance()->get_UML_LiteralReal());
}
LiteralRealObject::LiteralRealObject(LiteralRealObject &obj):
CS_ObjectImpl(obj)
{
}
LiteralRealObject::LiteralRealObject()
{
this->getTypes()->insert(this->getTypes()->begin(), UML::UMLPackage::eInstance()->get_UML_LiteralReal());
}
LiteralRealObject::~LiteralRealObject()
{
}
std::shared_ptr<ecore::EObject> LiteralRealObject::copy()
{
std::shared_ptr<LiteralRealObject> element(new LiteralRealObject(*this));
element->setThisLiteralRealObjectPtr(element);
return element;
}
void LiteralRealObject::destroy()
{
m_LiteralRealValue.reset();
fUML::Semantics::StructuredClassifiers::ObjectImpl::destroy();
}
std::shared_ptr<uml::Element> LiteralRealObject::getUmlValue() const
{
return getLiteralRealValue();
}
std::shared_ptr<uml::LiteralReal> LiteralRealObject::getLiteralRealValue() const
{
return m_LiteralRealValue;
}
void LiteralRealObject::setUmlValue(std::shared_ptr<uml::Element> _element)
{
setLiteralRealValue(std::dynamic_pointer_cast<uml::LiteralReal>(_element));
}
void LiteralRealObject::setLiteralRealValue(std::shared_ptr<uml::LiteralReal> _LiteralRealElement)
{
m_LiteralRealValue = _LiteralRealElement;
//set super type values
UML::LiteralSpecificationObject::setLiteralSpecificationValue(_LiteralRealElement);
}
void LiteralRealObject::setThisLiteralRealObjectPtr(std::weak_ptr<LiteralRealObject> thisObjectPtr)
{
setThisCS_ObjectPtr(thisObjectPtr);
}
bool LiteralRealObject::equals(std::shared_ptr<fUML::Semantics::Values::Value> otherValue)
{
bool isEqual = false;
std::shared_ptr<LiteralRealObject> otherLiteralRealObject = std::dynamic_pointer_cast<LiteralRealObject>(otherValue);
if(otherLiteralRealObject != nullptr)
{
if(this->getLiteralRealValue() == otherLiteralRealObject->getLiteralRealValue())
{
isEqual = true;
}
}
return isEqual;
}
std::string LiteralRealObject::toString()
{
std::string buffer = "Instance of 'LiteralRealObject', " + std::to_string(getTypes()->size()) + " types (";
for(unsigned int i = 0; i < getTypes()->size(); ++i)
{
buffer += "type{" + std::to_string(i) + "}: '" + getTypes()->at(i)->getName() + "', ";
}
buffer +=")";
return buffer;
}
std::shared_ptr<Bag<PSCS::Semantics::StructuredClassifiers::CS_Object>> LiteralRealObject::getDirectContainers()
{
std::shared_ptr<Bag<PSCS::Semantics::StructuredClassifiers::CS_Object>> directContainers(new Bag<PSCS::Semantics::StructuredClassifiers::CS_Object>());
/*Not done for metamodel object classes*/
return directContainers;
}
std::shared_ptr<Bag<PSCS::Semantics::StructuredClassifiers::CS_Link>> LiteralRealObject::getLinks(std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_InteractionPoint> interactionPoint)
{
std::shared_ptr<Bag<PSCS::Semantics::StructuredClassifiers::CS_Link>> allLinks(new Bag<PSCS::Semantics::StructuredClassifiers::CS_Link>());
/*Not done for metamodel object classes*/
return allLinks;
}
std::shared_ptr<Bag<fUML::Semantics::Values::Value>> LiteralRealObject::retrieveEndValueAsInteractionPoint(std::shared_ptr<fUML::Semantics::Values::Value> endValue, std::shared_ptr<uml::ConnectorEnd> end)
{
/*Not done for metamodel object classes*/
return nullptr;
}
void LiteralRealObject::removeValue(std::shared_ptr<uml::StructuralFeature> feature, std::shared_ptr<fUML::Semantics::Values::Value> value)
{
if (feature->getMetaElementID() != uml::umlPackage::PROPERTY_CLASS && feature->getMetaElementID() != uml::umlPackage::PORT_CLASS && feature->getMetaElementID() != uml::umlPackage::EXTENSIONEND_CLASS)
{
std::cerr << __PRETTY_FUNCTION__ << ": feature is null or not kind of uml::Property" << std::endl;
throw "feature is null or not kind of uml::Property";
}
if (m_LiteralRealValue == nullptr)
{
std::cerr << __PRETTY_FUNCTION__ << ": no value stored inside LiteralRealObject (property: " << feature->getName() << ")" << std::endl;
throw "NullPointerException";
}
if (feature == UML::UMLPackage::eInstance()->get_UML_Element_ownedComment())
{
if (value == nullptr) // clear mode
{
m_LiteralRealValue->getOwnedComment()->clear();
}
else
{
/* Should use PSCS::CS_Reference but dynamic_pointer_cast fails --> using fUML::Reference instead
std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_Reference> reference = std::dynamic_pointer_cast<PSCS::Semantics::StructuredClassifiers::CS_Reference>(value); */
std::shared_ptr<fUML::Semantics::StructuredClassifiers::Reference> reference = std::dynamic_pointer_cast<fUML::Semantics::StructuredClassifiers::Reference>(value);
std::shared_ptr<UML::CommentObject> inputValue = std::dynamic_pointer_cast<UML::CommentObject>(reference->getReferent());
if (inputValue != nullptr)
{
m_LiteralRealValue->getOwnedComment()->erase(inputValue->getCommentValue());
}
}
}
if (feature == UML::UMLPackage::eInstance()->get_UML_LiteralReal_value())
{
// no default value defined, clear not realized
}
if (feature == UML::UMLPackage::eInstance()->get_UML_NamedElement_name())
{
// no default value defined, clear not realized
}
if (feature == UML::UMLPackage::eInstance()->get_UML_NamedElement_nameExpression())
{
m_LiteralRealValue->getNameExpression().reset();
}
if (feature == UML::UMLPackage::eInstance()->get_UML_NamedElement_visibility())
{
// no default value defined, clear not realized
}
if (feature == UML::UMLPackage::eInstance()->get_UML_PackageableElement_visibility())
{
m_LiteralRealValue->setVisibility(uml::VisibilityKind::PUBLIC /*defined default value*/);
}
if (feature == UML::UMLPackage::eInstance()->get_UML_ParameterableElement_owningTemplateParameter())
{
m_LiteralRealValue->getOwningTemplateParameter().reset();
}
if (feature == UML::UMLPackage::eInstance()->get_UML_ParameterableElement_templateParameter())
{
m_LiteralRealValue->getTemplateParameter().reset();
}
if (feature == UML::UMLPackage::eInstance()->get_UML_TypedElement_type())
{
m_LiteralRealValue->getType().reset();
}
}
std::shared_ptr<Bag<fUML::Semantics::Values::Value>> LiteralRealObject::getValues(std::shared_ptr<uml::StructuralFeature> feature, std::shared_ptr<Bag<fUML::Semantics::SimpleClassifiers::FeatureValue>> featureValues)
{
if (feature->getMetaElementID() != uml::umlPackage::PROPERTY_CLASS && feature->getMetaElementID() != uml::umlPackage::PORT_CLASS && feature->getMetaElementID() != uml::umlPackage::EXTENSIONEND_CLASS)
{
std::cerr << __PRETTY_FUNCTION__ << ": feature is null or not kind of uml::Property" << std::endl;
throw "feature is null or not kind of uml::Property";
}
if (m_LiteralRealValue == nullptr)
{
std::cerr << __PRETTY_FUNCTION__ << ": no value stored inside LiteralRealObject (property: " << feature->getName() << ")" << std::endl;
throw "NullPointerException";
}
std::shared_ptr<Bag<fUML::Semantics::Values::Value>> values(new Bag<fUML::Semantics::Values::Value>());
if (feature == UML::UMLPackage::eInstance()->get_UML_Element_ownedComment())
{
std::shared_ptr<Bag<uml::Comment>> ownedCommentList = m_LiteralRealValue->getOwnedComment();
Bag<uml::Comment>::iterator iter = ownedCommentList->begin();
Bag<uml::Comment>::iterator end = ownedCommentList->end();
while (iter != end)
{
std::shared_ptr<UML::CommentObject> value(new UML::CommentObject());
value->setThisCommentObjectPtr(value);
value->setLocus(this->getLocus());
value->setCommentValue(*iter);
std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_Reference> reference = PSCS::Semantics::StructuredClassifiers::StructuredClassifiersFactory::eInstance()->createCS_Reference();
reference->setReferent(value);
reference->setCompositeReferent(value);
values->add(reference);
iter++;
}
}
if (feature == UML::UMLPackage::eInstance()->get_UML_Element_ownedElement())
{
std::shared_ptr<Bag<uml::Element>> ownedElementList = m_LiteralRealValue->getOwnedElement();
Bag<uml::Element>::iterator iter = ownedElementList->begin();
Bag<uml::Element>::iterator end = ownedElementList->end();
while (iter != end)
{
std::shared_ptr<UML::ElementObject> value(new UML::ElementObject());
value->setThisElementObjectPtr(value);
value->setLocus(this->getLocus());
value->setElementValue(*iter);
std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_Reference> reference = PSCS::Semantics::StructuredClassifiers::StructuredClassifiersFactory::eInstance()->createCS_Reference();
reference->setReferent(value);
reference->setCompositeReferent(value);
values->add(reference);
iter++;
}
}
if (feature == UML::UMLPackage::eInstance()->get_UML_Element_owner())
{
std::shared_ptr<UML::ElementObject> value(new UML::ElementObject());
value->setThisElementObjectPtr(value);
value->setLocus(this->getLocus());
value->setElementValue(m_LiteralRealValue->getOwner().lock());
std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_Reference> reference = PSCS::Semantics::StructuredClassifiers::StructuredClassifiersFactory::eInstance()->createCS_Reference();
reference->setReferent(value);
values->add(reference);
}
if (feature == UML::UMLPackage::eInstance()->get_UML_LiteralReal_value())
{
std::shared_ptr<fUML::Semantics::SimpleClassifiers::RealValue> value = fUML::Semantics::SimpleClassifiers::SimpleClassifiersFactory::eInstance()->createRealValue();
value->setValue(m_LiteralRealValue->getValue());
values->add(value);
}
if (feature == UML::UMLPackage::eInstance()->get_UML_NamedElement_clientDependency())
{
std::shared_ptr<Bag<uml::Dependency>> clientDependencyList = m_LiteralRealValue->getClientDependency();
Bag<uml::Dependency>::iterator iter = clientDependencyList->begin();
Bag<uml::Dependency>::iterator end = clientDependencyList->end();
while (iter != end)
{
std::shared_ptr<UML::DependencyObject> value(new UML::DependencyObject());
value->setThisDependencyObjectPtr(value);
value->setLocus(this->getLocus());
value->setDependencyValue(*iter);
std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_Reference> reference = PSCS::Semantics::StructuredClassifiers::StructuredClassifiersFactory::eInstance()->createCS_Reference();
reference->setReferent(value);
values->add(reference);
iter++;
}
}
if (feature == UML::UMLPackage::eInstance()->get_UML_NamedElement_name())
{
std::shared_ptr<fUML::Semantics::SimpleClassifiers::StringValue> value = fUML::Semantics::SimpleClassifiers::SimpleClassifiersFactory::eInstance()->createStringValue();
value->setValue(m_LiteralRealValue->getName());
values->add(value);
}
if (feature == UML::UMLPackage::eInstance()->get_UML_NamedElement_nameExpression())
{
std::shared_ptr<UML::StringExpressionObject> value(new UML::StringExpressionObject());
value->setThisStringExpressionObjectPtr(value);
value->setLocus(this->getLocus());
value->setStringExpressionValue(m_LiteralRealValue->getNameExpression());
std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_Reference> reference = PSCS::Semantics::StructuredClassifiers::StructuredClassifiersFactory::eInstance()->createCS_Reference();
reference->setReferent(value);
reference->setCompositeReferent(value);
values->add(reference);
}
if (feature == UML::UMLPackage::eInstance()->get_UML_NamedElement_namespace())
{
std::shared_ptr<UML::NamespaceObject> value(new UML::NamespaceObject());
value->setThisNamespaceObjectPtr(value);
value->setLocus(this->getLocus());
value->setNamespaceValue(m_LiteralRealValue->getNamespace().lock());
std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_Reference> reference = PSCS::Semantics::StructuredClassifiers::StructuredClassifiersFactory::eInstance()->createCS_Reference();
reference->setReferent(value);
values->add(reference);
}
if (feature == UML::UMLPackage::eInstance()->get_UML_NamedElement_qualifiedName())
{
std::shared_ptr<fUML::Semantics::SimpleClassifiers::StringValue> value = fUML::Semantics::SimpleClassifiers::SimpleClassifiersFactory::eInstance()->createStringValue();
value->setValue(m_LiteralRealValue->getQualifiedName());
values->add(value);
}
if (feature == UML::UMLPackage::eInstance()->get_UML_NamedElement_visibility())
{
uml::VisibilityKind visibility = m_LiteralRealValue->getVisibility();
std::shared_ptr<fUML::Semantics::SimpleClassifiers::EnumerationValue> value = fUML::Semantics::SimpleClassifiers::SimpleClassifiersFactory::eInstance()->createEnumerationValue();
if (visibility == uml::VisibilityKind::PUBLIC)
{
value->setLiteral(UML::UMLPackage::eInstance()->get_UML_VisibilityKind_public());
}
if (visibility == uml::VisibilityKind::PRIVATE)
{
value->setLiteral(UML::UMLPackage::eInstance()->get_UML_VisibilityKind_private());
}
if (visibility == uml::VisibilityKind::PROTECTED)
{
value->setLiteral(UML::UMLPackage::eInstance()->get_UML_VisibilityKind_protected());
}
if (visibility == uml::VisibilityKind::PACKAGE)
{
value->setLiteral(UML::UMLPackage::eInstance()->get_UML_VisibilityKind_package());
}
values->add(value);
}
if (feature == UML::UMLPackage::eInstance()->get_UML_PackageableElement_visibility())
{
uml::VisibilityKind visibility = m_LiteralRealValue->getVisibility();
std::shared_ptr<fUML::Semantics::SimpleClassifiers::EnumerationValue> value = fUML::Semantics::SimpleClassifiers::SimpleClassifiersFactory::eInstance()->createEnumerationValue();
if (visibility == uml::VisibilityKind::PUBLIC)
{
value->setLiteral(UML::UMLPackage::eInstance()->get_UML_VisibilityKind_public());
}
if (visibility == uml::VisibilityKind::PRIVATE)
{
value->setLiteral(UML::UMLPackage::eInstance()->get_UML_VisibilityKind_private());
}
if (visibility == uml::VisibilityKind::PROTECTED)
{
value->setLiteral(UML::UMLPackage::eInstance()->get_UML_VisibilityKind_protected());
}
if (visibility == uml::VisibilityKind::PACKAGE)
{
value->setLiteral(UML::UMLPackage::eInstance()->get_UML_VisibilityKind_package());
}
values->add(value);
}
if (feature == UML::UMLPackage::eInstance()->get_UML_ParameterableElement_owningTemplateParameter())
{
std::shared_ptr<UML::TemplateParameterObject> value(new UML::TemplateParameterObject());
value->setThisTemplateParameterObjectPtr(value);
value->setLocus(this->getLocus());
value->setTemplateParameterValue(m_LiteralRealValue->getOwningTemplateParameter().lock());
std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_Reference> reference = PSCS::Semantics::StructuredClassifiers::StructuredClassifiersFactory::eInstance()->createCS_Reference();
reference->setReferent(value);
values->add(reference);
}
if (feature == UML::UMLPackage::eInstance()->get_UML_ParameterableElement_templateParameter())
{
std::shared_ptr<UML::TemplateParameterObject> value(new UML::TemplateParameterObject());
value->setThisTemplateParameterObjectPtr(value);
value->setLocus(this->getLocus());
value->setTemplateParameterValue(m_LiteralRealValue->getTemplateParameter());
std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_Reference> reference = PSCS::Semantics::StructuredClassifiers::StructuredClassifiersFactory::eInstance()->createCS_Reference();
reference->setReferent(value);
values->add(reference);
}
if (feature == UML::UMLPackage::eInstance()->get_UML_TypedElement_type())
{
std::shared_ptr<UML::TypeObject> value(new UML::TypeObject());
value->setThisTypeObjectPtr(value);
value->setLocus(this->getLocus());
value->setTypeValue(m_LiteralRealValue->getType());
std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_Reference> reference = PSCS::Semantics::StructuredClassifiers::StructuredClassifiersFactory::eInstance()->createCS_Reference();
reference->setReferent(value);
values->add(reference);
}
return values;
}
std::shared_ptr<fUML::Semantics::SimpleClassifiers::FeatureValue> LiteralRealObject::retrieveFeatureValue(std::shared_ptr<uml::StructuralFeature> feature)
{
std::shared_ptr<fUML::Semantics::SimpleClassifiers::FeatureValue> featureValue(fUML::Semantics::SimpleClassifiers::SimpleClassifiersFactory::eInstance()->createFeatureValue());
featureValue->setFeature(feature);
std::shared_ptr<Bag<fUML::Semantics::SimpleClassifiers::FeatureValue>> featureValues(new Bag<fUML::Semantics::SimpleClassifiers::FeatureValue>());
std::shared_ptr<Bag<fUML::Semantics::Values::Value>> values = this->getValues(feature, featureValues);
unsigned int valuesSize = values->size();
for(unsigned int i = 0; i < valuesSize; i++)
{
featureValue->getValues()->add(values->at(i));
}
return featureValue;
}
void LiteralRealObject::setFeatureValue(std::shared_ptr<uml::StructuralFeature> feature, std::shared_ptr<Bag<fUML::Semantics::Values::Value>> values, int position)
{
if (feature->getMetaElementID() != uml::umlPackage::PROPERTY_CLASS && feature->getMetaElementID() != uml::umlPackage::PORT_CLASS && feature->getMetaElementID() != uml::umlPackage::EXTENSIONEND_CLASS)
{
std::cerr << __PRETTY_FUNCTION__ << ": feature is null or not kind of uml::Property" << std::endl;
throw "feature is null or not kind of uml::Property";
}
if (m_LiteralRealValue == nullptr)
{
std::cerr << __PRETTY_FUNCTION__ << ": no value stored inside LiteralRealObject (property: " << feature->getName() << ")" << std::endl;
throw "NullPointerException";
}
if (values->size() == 0)
{
std::cout << __PRETTY_FUNCTION__ << ": no input value given" << std::endl;
return;
}
if (feature == UML::UMLPackage::eInstance()->get_UML_Element_ownedComment())
{
Bag<fUML::Semantics::Values::Value>::iterator iter = values->begin();
Bag<fUML::Semantics::Values::Value>::iterator end = values->end();
m_LiteralRealValue->getOwnedComment()->clear();
while (iter != end)
{
std::shared_ptr<fUML::Semantics::Values::Value> inputValue = *iter;
std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_Reference> reference = std::dynamic_pointer_cast<PSCS::Semantics::StructuredClassifiers::CS_Reference>(inputValue);
std::shared_ptr<UML::CommentObject> value = std::dynamic_pointer_cast<UML::CommentObject>(reference->getReferent());
if (value != nullptr)
{
m_LiteralRealValue->getOwnedComment()->push_back(value->getCommentValue());
}
iter++;
}
}
if (feature == UML::UMLPackage::eInstance()->get_UML_LiteralReal_value())
{
std::shared_ptr<fUML::Semantics::Values::Value> inputValue = values->at(0);
std::shared_ptr<fUML::Semantics::SimpleClassifiers::RealValue> valueObject = std::dynamic_pointer_cast<fUML::Semantics::SimpleClassifiers::RealValue>(inputValue);
if (valueObject != nullptr)
{
m_LiteralRealValue->setValue(valueObject->getValue());
}
}
if (feature == UML::UMLPackage::eInstance()->get_UML_NamedElement_name())
{
std::shared_ptr<fUML::Semantics::Values::Value> inputValue = values->at(0);
std::shared_ptr<fUML::Semantics::SimpleClassifiers::StringValue> valueObject = std::dynamic_pointer_cast<fUML::Semantics::SimpleClassifiers::StringValue>(inputValue);
if (valueObject != nullptr)
{
m_LiteralRealValue->setName(valueObject->getValue());
}
}
if (feature == UML::UMLPackage::eInstance()->get_UML_NamedElement_nameExpression())
{
std::shared_ptr<fUML::Semantics::Values::Value> inputValue = values->at(0);
std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_Reference> reference = std::dynamic_pointer_cast<PSCS::Semantics::StructuredClassifiers::CS_Reference>(inputValue);
std::shared_ptr<UML::StringExpressionObject> value = std::dynamic_pointer_cast<UML::StringExpressionObject>(reference->getReferent());
if (value != nullptr)
{
m_LiteralRealValue->setNameExpression(value->getStringExpressionValue());
}
}
if (feature == UML::UMLPackage::eInstance()->get_UML_NamedElement_visibility())
{
std::shared_ptr<fUML::Semantics::Values::Value> inputValue = values->at(0);
std::shared_ptr<fUML::Semantics::SimpleClassifiers::EnumerationValue> enumValue = std::dynamic_pointer_cast<fUML::Semantics::SimpleClassifiers::EnumerationValue>(inputValue);
std::shared_ptr<uml::EnumerationLiteral> literal = enumValue->getLiteral();
if (literal == UML::UMLPackage::eInstance()->get_UML_VisibilityKind_public())
{
m_LiteralRealValue->setVisibility(uml::VisibilityKind::PUBLIC);
}
if (literal == UML::UMLPackage::eInstance()->get_UML_VisibilityKind_private())
{
m_LiteralRealValue->setVisibility(uml::VisibilityKind::PRIVATE);
}
if (literal == UML::UMLPackage::eInstance()->get_UML_VisibilityKind_protected())
{
m_LiteralRealValue->setVisibility(uml::VisibilityKind::PROTECTED);
}
if (literal == UML::UMLPackage::eInstance()->get_UML_VisibilityKind_package())
{
m_LiteralRealValue->setVisibility(uml::VisibilityKind::PACKAGE);
}
}
if (feature == UML::UMLPackage::eInstance()->get_UML_PackageableElement_visibility())
{
std::shared_ptr<fUML::Semantics::Values::Value> inputValue = values->at(0);
std::shared_ptr<fUML::Semantics::SimpleClassifiers::EnumerationValue> enumValue = std::dynamic_pointer_cast<fUML::Semantics::SimpleClassifiers::EnumerationValue>(inputValue);
std::shared_ptr<uml::EnumerationLiteral> literal = enumValue->getLiteral();
if (literal == UML::UMLPackage::eInstance()->get_UML_VisibilityKind_public())
{
m_LiteralRealValue->setVisibility(uml::VisibilityKind::PUBLIC);
}
if (literal == UML::UMLPackage::eInstance()->get_UML_VisibilityKind_private())
{
m_LiteralRealValue->setVisibility(uml::VisibilityKind::PRIVATE);
}
if (literal == UML::UMLPackage::eInstance()->get_UML_VisibilityKind_protected())
{
m_LiteralRealValue->setVisibility(uml::VisibilityKind::PROTECTED);
}
if (literal == UML::UMLPackage::eInstance()->get_UML_VisibilityKind_package())
{
m_LiteralRealValue->setVisibility(uml::VisibilityKind::PACKAGE);
}
}
if (feature == UML::UMLPackage::eInstance()->get_UML_ParameterableElement_templateParameter())
{
std::shared_ptr<fUML::Semantics::Values::Value> inputValue = values->at(0);
std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_Reference> reference = std::dynamic_pointer_cast<PSCS::Semantics::StructuredClassifiers::CS_Reference>(inputValue);
std::shared_ptr<UML::TemplateParameterObject> value = std::dynamic_pointer_cast<UML::TemplateParameterObject>(reference->getReferent());
if (value != nullptr)
{
m_LiteralRealValue->setTemplateParameter(value->getTemplateParameterValue());
}
}
if (feature == UML::UMLPackage::eInstance()->get_UML_TypedElement_type())
{
std::shared_ptr<fUML::Semantics::Values::Value> inputValue = values->at(0);
std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_Reference> reference = std::dynamic_pointer_cast<PSCS::Semantics::StructuredClassifiers::CS_Reference>(inputValue);
std::shared_ptr<UML::TypeObject> value = std::dynamic_pointer_cast<UML::TypeObject>(reference->getReferent());
if (value != nullptr)
{
m_LiteralRealValue->setType(value->getTypeValue());
}
}
}
void LiteralRealObject::assignFeatureValue(std::shared_ptr<uml::StructuralFeature> feature, std::shared_ptr<Bag<fUML::Semantics::Values::Value>> values, int position)
{
this->setFeatureValue(feature, values, position);
}
std::shared_ptr<Bag<fUML::Semantics::SimpleClassifiers::FeatureValue>> LiteralRealObject::retrieveFeatureValues()
{
std::shared_ptr<uml::Classifier> type = this->getTypes()->at(0);
std::shared_ptr<Bag<uml::Property>> allAttributes = type->getAllAttributes();
std::shared_ptr<Bag<fUML::Semantics::SimpleClassifiers::FeatureValue>> featureValues(new Bag<fUML::Semantics::SimpleClassifiers::FeatureValue>());
unsigned int allAttributesSize = allAttributes->size();
for(unsigned int i = 0; i < allAttributesSize; i++)
{
std::shared_ptr<uml::Property> property = allAttributes->at(i);
if (property == UML::UMLPackage::eInstance()->get_UML_Element_ownedComment() && m_LiteralRealValue->getOwnedComment() != nullptr)
{
featureValues->add(this->retrieveFeatureValue(property));
}
if (property == UML::UMLPackage::eInstance()->get_UML_Element_ownedElement() && m_LiteralRealValue->getOwnedElement() != nullptr)
{
featureValues->add(this->retrieveFeatureValue(property));
}
if (property == UML::UMLPackage::eInstance()->get_UML_Element_owner() && m_LiteralRealValue->getOwner().lock() != nullptr)
{
featureValues->add(this->retrieveFeatureValue(property));
}
if (property == UML::UMLPackage::eInstance()->get_UML_NamedElement_clientDependency() && m_LiteralRealValue->getClientDependency() != nullptr)
{
featureValues->add(this->retrieveFeatureValue(property));
}
if (property == UML::UMLPackage::eInstance()->get_UML_NamedElement_nameExpression() && m_LiteralRealValue->getNameExpression() != nullptr)
{
featureValues->add(this->retrieveFeatureValue(property));
}
if (property == UML::UMLPackage::eInstance()->get_UML_NamedElement_namespace() && m_LiteralRealValue->getNamespace().lock() != nullptr)
{
featureValues->add(this->retrieveFeatureValue(property));
}
if (property == UML::UMLPackage::eInstance()->get_UML_ParameterableElement_owningTemplateParameter() && m_LiteralRealValue->getOwningTemplateParameter().lock() != nullptr)
{
featureValues->add(this->retrieveFeatureValue(property));
}
if (property == UML::UMLPackage::eInstance()->get_UML_ParameterableElement_templateParameter() && m_LiteralRealValue->getTemplateParameter() != nullptr)
{
featureValues->add(this->retrieveFeatureValue(property));
}
if (property == UML::UMLPackage::eInstance()->get_UML_TypedElement_type() && m_LiteralRealValue->getType() != nullptr)
{
featureValues->add(this->retrieveFeatureValue(property));
}
}
return featureValues;
}
| 42.907855
| 216
| 0.757965
|
MDE4CPP
|
3e2804219cfd6c4d2c0f60099c2a7ec743ddb30b
| 1,580
|
hpp
|
C++
|
C-PhotoDeal_framework/numberPhoto.hpp
|
numberwolf/iOSDealFace
|
5a109690d143ac125a4b679a8ea6ef28a9f147e3
|
[
"Apache-2.0"
] | 8
|
2016-03-12T08:39:56.000Z
|
2021-07-12T01:48:20.000Z
|
C-PhotoDeal_framework/numberPhoto.hpp
|
numberwolf/iOSDealFace
|
5a109690d143ac125a4b679a8ea6ef28a9f147e3
|
[
"Apache-2.0"
] | null | null | null |
C-PhotoDeal_framework/numberPhoto.hpp
|
numberwolf/iOSDealFace
|
5a109690d143ac125a4b679a8ea6ef28a9f147e3
|
[
"Apache-2.0"
] | 2
|
2016-03-15T09:48:38.000Z
|
2017-02-04T23:53:32.000Z
|
//
// numberPhoto.hpp
// cameraDeal
//
// Created by numberwolf on 16/2/22.
// Copyright © 2016年 numberwolf. All rights reserved.
// hahah
/**************************************************************************
* Email:porschegt23@foxmail.com || numberwolf11@gmail.com
* Github:https://github.com/numberwolf
* APACHE 2.0 LICENSE
* Copyright [2016] [Chang Yanlong]
* 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
**************************************************************************/
#ifndef numberPhoto_hpp
#define numberPhoto_hpp
#include <stdio.h>
#include <iostream>
#include "Pixels.hpp"
class numberPhoto {
public:
numberPhoto() {
}
~numberPhoto() {
}
// 入口
static void method_zero(IplImage *pixels, int width, int height);
static void method_one(IplImage *pixels, int width, int height, int value);
static void method_two(IplImage *pixels, int width, int height, bool isCanny, int wRadius, int hRadius, int scanScaleOfRadius);
static void method_three(IplImage *pixels, int width, int height, int Radius);
static void otsuBinary(IplImage *pixels, int width, int height, bool isCanny, int wRadius, int hRadius);
static void testAction(IplImage *pixels, int width, int height);
static void sobelCanny(IplImage *pixels, int width, int height);
private:
protected:
};
#endif /* numberPhoto_hpp */
| 29.259259
| 131
| 0.63481
|
numberwolf
|
3e2ae2f0a7b0567fdfa05bbf2d84493f718b538d
| 113
|
cpp
|
C++
|
contest/yukicoder/285.cpp
|
not522/Competitive-Programming
|
be4a7d25caf5acbb70783b12899474a56c34dedb
|
[
"Unlicense"
] | 7
|
2018-04-14T14:55:51.000Z
|
2022-01-31T10:49:49.000Z
|
contest/yukicoder/285.cpp
|
not522/Competitive-Programming
|
be4a7d25caf5acbb70783b12899474a56c34dedb
|
[
"Unlicense"
] | 5
|
2018-04-14T14:28:49.000Z
|
2019-05-11T02:22:10.000Z
|
contest/yukicoder/285.cpp
|
not522/Competitive-Programming
|
be4a7d25caf5acbb70783b12899474a56c34dedb
|
[
"Unlicense"
] | null | null | null |
#include "template.hpp"
int main() {
long double d(in);
cout << std::setprecision(2) << d * 1.08 << endl;
}
| 16.142857
| 51
| 0.584071
|
not522
|
3e2c571ac38f4fd2af741d4d06a75eacb2950ac7
| 13,134
|
cpp
|
C++
|
test/MeLikeyCode-QtGameEngine-2a3d47c/testProject/main.cpp
|
JamesMBallard/qmake-unity
|
cf5006a83e7fb1bbd173a9506771693a673d387f
|
[
"MIT"
] | 16
|
2019-05-23T08:10:39.000Z
|
2021-12-21T11:20:37.000Z
|
test/MeLikeyCode-QtGameEngine-2a3d47c/testProject/main.cpp
|
JamesMBallard/qmake-unity
|
cf5006a83e7fb1bbd173a9506771693a673d387f
|
[
"MIT"
] | null | null | null |
test/MeLikeyCode-QtGameEngine-2a3d47c/testProject/main.cpp
|
JamesMBallard/qmake-unity
|
cf5006a83e7fb1bbd173a9506771693a673d387f
|
[
"MIT"
] | 2
|
2019-05-23T18:37:43.000Z
|
2021-08-24T21:29:40.000Z
|
#include <QApplication>
#include "qge/Entity.h"
#include "qge/Map.h"
#include "qge/MapGrid.h"
#include "qge/Sound.h"
#include "qge/Game.h"
#include "qge/SpriteSheet.h"
#include "qge/AngledSprite.h"
#include "qge/ECMouseFacer.h"
#include "qge/ECKeyboardMoverPerspective.h"
#include "qge/ECCameraFollower.h"
#include "qge/ECMapMover.h"
#include "qge/ECCurrentMapGrabber.h"
#include "qge/ECItemPickerUpper.h"
#include "qge/WeaponSlot.h"
#include "qge/RangedWeaponSlot.h"
#include "qge/AnimationAttack.h"
#include "qge/Axe.h"
#include "qge/ItemRainOfSpears.h"
#include "qge/ItemShardsOfFire.h"
#include "qge/ItemPushback.h"
#include "qge/InventoryUser.h"
#include "qge/RainWeather.h"
#include "qge/CItemDropper.h"
#include "qge/CHealthShower.h"
#include "qge/DialogGui.h"
#include "qge/TopDownSprite.h"
#include "qge/TerrainLayer.h"
#include "qge/Utilities.h"
#include "qge/MCSpawner.h"
#include "qge/ECMerchant.h"
#include "qge/RandomImageEntity.h"
#include "qge/Quests.h"
#include "qge/QuestAcceptor.h"
#include "qge/Inventory.h"
#include "qge/FogWeather.h"
#include "qge/ItemHealthPotion.h"
#include "qge/ItemTeleport.h"
#include "qge/FireballLauncher.h"
#include "qge/ECGuiShower.h"
#include "MyEventHandler.h"
#include "SpiderCreator.h"
using namespace qge;
Entity* player;
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
// play music in the background
Sound* bgMusic = new Sound("qrc:/resources/sounds/music3.mp3");
bgMusic->setVolume(50);
bgMusic->play(-1);
// create a MapGrid to put some Maps inside
MapGrid* mapGrid = new MapGrid(3,3);
// create the Maps
Map* map1 = new Map(new PathingMap(100,100,16));
Map* map2 = new Map(new PathingMap(50,50,64));
// put Maps in MapGrid
mapGrid->setMapAtPos(map1,0,1);
mapGrid->setMapAtPos(map2,0,0);
// create a Game to visualize the Maps
Game* game = new Game(mapGrid,0,1);
EventHandler* eventHandler = new EventHandler(game);
game->launch();
// create an entity that is controlled via keyboard/mouse
player = new Entity();
player->setGroup(1);
player->setMaxHealth(100);
player->setHealth(100);
player->pathingMap().fill();
// create an EntitySprite for the entity
SpriteSheet minitaurSpriteSheet(":/resources/graphics/characterSpritesheets/minotaur_alpha.png",24,8,128,128);
AngledSprite* sprplayer = new AngledSprite();
for (int i = 0, n = 8; i < n; ++i){ // for each angle
// stand
sprplayer->addFrames((180+45*i) % 360,"stand",minitaurSpriteSheet,Node(0,0+i),Node(3,0+i));
for (int j = 2; j > 0; --j){
sprplayer->addFrame(minitaurSpriteSheet.tileAt(Node(j,0+i)),"stand",(180+45*i) % 360);
}
// walk
sprplayer->addFrames((180+45*i) % 360,"walk",minitaurSpriteSheet,Node(4,0+i),Node(11,0+i));
// attack
sprplayer->addFrames((180+45*i) % 360,"attack",minitaurSpriteSheet,Node(12,0+i),Node(18,0+i));
}
player->setOrigin(QPointF(64,64));
player->setSprite(sprplayer);
player->setPathingMapPos(QPointF(64,64));
// add entity to a map
map1->addEntity(player);
player->setPos(QPointF(200,650));
// add controllers to control the behavior of the entity
ECMouseFacer* rotContr = new ECMouseFacer(player);
ECKeyboardMoverPerspective* moveContr = new ECKeyboardMoverPerspective(player);
ECCameraFollower* grabCamContr = new ECCameraFollower(player);
ECMapMover* moveToNMC = new ECMapMover(player);
ECCurrentMapGrabber* grabCM = new ECCurrentMapGrabber(player);
ECItemPickerUpper* pickUpItemContr = new ECItemPickerUpper(player);
// create some slots for the entity
WeaponSlot* rightHandMelee = new WeaponSlot();
rightHandMelee->setPosition(QPointF(25,50));
player->addSlot(rightHandMelee,"melee");
RangedWeaponSlot* rangedSlot = new RangedWeaponSlot();
rangedSlot->setPosition(QPointF(64,45));
player->addSlot(rangedSlot,"ranged");
// equip something in slot
AnimationAttack* animAttack = new AnimationAttack("attack","qrc:/resources/sounds/axe.wav",10,85,90);
player->inventory()->addItem(animAttack);
rightHandMelee->equip(animAttack);
// drop some items on the ground
Axe* axeItem = new Axe();
axeItem->setPos(QPointF(100,300));
map1->addEntity(axeItem);
ItemRainOfSpears* ros = new ItemRainOfSpears();
ros->setNumOfCharges(2);
ros->setPos(QPointF(200,200));
map1->addEntity(ros);
ItemShardsOfFire* sof = new ItemShardsOfFire();
sof->setNumOfCharges(10);
sof->setPos(QPointF(220,220));
map1->addEntity(sof);
ItemPushback* pushBackItem = new ItemPushback();
pushBackItem->setPos(QPointF(300,300));
map1->addEntity(pushBackItem);
// create a gui that allows visualizing/using of inventory of player
InventoryUser* invUser = new InventoryUser(game,player->inventory());
game->addGui(invUser);
// add a weather effect (can add multiple at the same time, if they play nice with each other)
RainWeather* rain = new RainWeather();
// map1->addWeatherEffect(*rain);
// FogWeather* fog = new FogWeather();
// map1->addWeatherEffect(*fog);
// create health shower
CHealthShower* hs = new CHealthShower();
hs->addEntity(player);
// create a dialog gui (to test gui shower)
DialogGui* dg = new DialogGui();
Response* startingText = new Response("Hello stranger, what brings thee here?");
Choice* startTextChoice1 = new Choice("Screw you!");
Choice* startTextChoice2 = new Choice("I'm looking for adventure!");
dg->addResponse(startingText);
dg->addChoice(startingText,startTextChoice1);
dg->addChoice(startingText,startTextChoice2);
dg->setResponse(startingText); // set initial text
Response* screwYouResponse = new Response("You're manners are not very good...you won't last long here, kid.");
Response* adventureResponse = new Response("I salute thee! You should talk to our village elder for some quests.");
dg->addResponse(screwYouResponse);
dg->addResponse(adventureResponse);
dg->setResponseForChoice(screwYouResponse,startTextChoice1);
dg->setResponseForChoice(adventureResponse,startTextChoice2);
Choice* backChoice = new Choice("<back>");
dg->addChoice(screwYouResponse, backChoice);
dg->setResponseForChoice(startingText, backChoice);
double guix = game->width() - dg->getGuiBoundingBox().width();
dg->setGuiPos(QPointF(guix,0));
// add a building
Entity* bEntity = new Entity();
QPixmap bPixmap(":/resources/graphics/buildings/bldg2.png");
bPixmap = bPixmap.scaled(0.85*bPixmap.width(),0.85*bPixmap.height());
TopDownSprite* bSprite = new TopDownSprite(bPixmap);
bEntity->setSprite(bSprite);
// add its pathing
QPixmap bPMPixmap(":/resources/graphics/buildings/bldg2pathing.png");
bPMPixmap = bPMPixmap.scaled(0.85*bPMPixmap.width(),0.85*bPMPixmap.height());
PathingMap* bPM = new PathingMap(bPMPixmap,32);
bEntity->setPathingMap(*bPM);
bEntity->setPos(QPointF(600,900));
map1->addEntity(bEntity);
QPixmap grassPatch (":/resources/graphics/terrain/grasspatch.png");
map1->addTerrainDecoration(grassPatch,bEntity->pos() - QPointF(grassPatch.width()/2,0));
// add well
Entity* well = new Entity();
QPixmap wellPixmap(":/resources/graphics/buildings/well.png");
wellPixmap = wellPixmap.scaledToWidth(wellPixmap.width()*0.5);
QPixmap wellPMPixmap(":/resources/graphics/buildings/wellpathing.png");
wellPMPixmap = wellPMPixmap.scaledToWidth(wellPMPixmap.width()*0.5);
well->setSprite(new TopDownSprite(wellPixmap));
well->setPathingMap(*(new PathingMap(wellPMPixmap,32)));
well->setPos(QPointF(1300,900));
map1->addEntity(well);
TerrainLayer* flowers = new TerrainLayer(2,2,QPixmap(":/resources/graphics/terrain/flowersopacity.png"));
flowers->fill();
map1->addTerrainLayer(flowers);
flowers->setPos(QPointF(750,500));
bEntity->setInvulnerable(true);
well->setInvulnerable(true);
addRandomTrees(map2,15,"Two",8);
addRandomTrees(map2,5,"Three",8);
addRandomTrees(map2,5,"Four",8);
// add weather effects in map 2
map2->addWeatherEffect(*(new FogWeather()));
map2->addWeatherEffect(*(new RainWeather()));
// create a spanwer in map 2
MCSpawner* spawner = new MCSpawner(map2,QRectF(0,0,map2->width(),map2->height()),100,1,new SpiderCreator());
// create villager that sells you stuff
// villager sprite
SpriteSheet villagerSS(":/resources/graphics/characterSpritesheets/villager.png",17,8,91,163);
AngledSprite* sprVillager = new AngledSprite();
for (int i = 0, n = 8; i < n; ++i){ // for each angle
// stand
sprVillager->addFrames((90+45*i) % 360,"stand",villagerSS,Node(16,0+i),Node(16,0+i));
// walk
sprVillager->addFrames((90+45*i) % 360,"walk",villagerSS,Node(0,0+i),Node(14,0+i));
}
// villager
sprVillager->play("stand",-1,1,0);
Entity* villager = new Entity();
villager->setInvulnerable(true);
villager->setOrigin(QPointF(91.0/2,163.0/2));
villager->setSprite(sprVillager);
villager->setPathingMapPos(QPointF(91.0/2,163.0/2));
villager->setPos(bEntity->botRight() - QPointF(150,150));
map1->addEntity(villager);
sprVillager->scale(0.65);
villager->setFacingAngle(135);
// sell
villager->inventory()->addItem(new ItemHealthPotion(10));
villager->inventory()->addItem(new ItemTeleport());
villager->inventory()->addItem(new ItemRainOfSpears());
villager->inventory()->addItem(new FireballLauncher());
ECMerchant* mc = new ECMerchant(villager);
mc->addEntityOfInterest(player);
PathingMap treePM(QPixmap(":/resources/graphics/tree/treeOnepathing.png"),32);
// create animated tree
Entity* animatedTree = new Entity();
TopDownSprite* animatedTreeSpr = new TopDownSprite();
animatedTreeSpr->addFrames(":/resources/graphics/tree/animTree",30,"animTree");
for (int i = 28, n = 1; i >= n; --i){
std::string fullPath = ":/resources/graphics/tree/animTree/animTree" + std::to_string(i) + ".png";
animatedTreeSpr->addFrame(QPixmap(fullPath.c_str()),"animTree");
}
animatedTree->setSprite(animatedTreeSpr);
animatedTree->setPathingMap(*(new PathingMap(QPixmap(":/resources/graphics/tree/animTree/animTreepathing.png"),32)));
animatedTree->setInvulnerable(true);
map1->addEntity(animatedTree);
animatedTree->sprite()->play("animTree",-1,8,0);
animatedTree->setPos(bEntity->pos() + QPointF(225,-400));
// create some more trees in map1
RandomImageEntity* tree2 = new RandomImageEntity(":/resources/graphics/tree", "treeOne" , 5, *(new PathingMap(treePM)));
RandomImageEntity* tree3 = new RandomImageEntity(":/resources/graphics/tree", "treeOne" , 5, *(new PathingMap(treePM)));
RandomImageEntity* tree4 = new RandomImageEntity(":/resources/graphics/tree", "treeOne" , 5, *(new PathingMap(treePM)));
RandomImageEntity* tree5 = new RandomImageEntity(":/resources/graphics/tree", "treeOne" , 5, *(new PathingMap(treePM)));
RandomImageEntity* tree6 = new RandomImageEntity(":/resources/graphics/tree", "treeOne" , 5, *(new PathingMap(treePM)));
addTag("scenery",{tree2,tree3,tree4,tree5});
map1->addEntity(tree2);
map1->addEntity(tree3);
map1->addEntity(tree4);
map1->addEntity(tree5);
map1->addEntity(tree6);
tree2->setPos(QPointF(300,300));
tree3->setPos(QPointF(800,375));
tree4->setPos(QPointF(1200,1400));
tree5->setPos(QPointF(200,1400));
tree6->setPos(QPointF(1400,200));
// create quest giver
Quests* quests = new Quests();
quests->addQuest(new Quest("Kill Spiders","We have a spider problem. Please kill 10 spiders from the northern forest."));
quests->addQuest(new Quest("Gather Gold","We are poor. Please gather 10 gold and bring it back to me."));
quests->addQuest(new Quest("Craft nets","We are hungry. Please make some nets from the vines found in the northern forest."));
quests->addQuest(new Quest("Craft Weapons","We have been getting raided by bandits. Please make some weapons that our villagers can use to defend themselves."));
quests->addQuest(new Quest("Chop trees","We need to build a wall. Please chop some trees and bring back the logs."));
QuestAcceptor* questAccepter = new QuestAcceptor(game);
questAccepter->setQuests(quests);
game->addGui(questAccepter);
questAccepter->setGuiPos(QPointF(game->width() - questAccepter->getGuiBoundingBox().width(),0));
ECGuiShower* questGuiShower = new ECGuiShower(villager,questAccepter);
questGuiShower->addEntityOfInterest(player);
player->inventory()->addItem(new FireballLauncher());
player->inventory()->addItem(new ItemTeleport());
player->inventory()->addItem(new ItemTeleport());
player->inventory()->addItem(new ItemTeleport());
player->inventory()->addItem(new ItemTeleport());
player->inventory()->addItem(new ItemTeleport());
player->inventory()->addItem(new ItemTeleport());
return a.exec();
}
| 39.920973
| 165
| 0.696361
|
JamesMBallard
|
3e2cfd1cf7f3f69c2d19a39ab1ffdeb4464b5bff
| 4,692
|
hpp
|
C++
|
src/Enzo/enzo_EnzoSolverHg.hpp
|
ThomasBolden/cello-mod
|
68431de28a3575c95bb40c47fce7a352c6b92145
|
[
"MIT",
"BSD-3-Clause"
] | null | null | null |
src/Enzo/enzo_EnzoSolverHg.hpp
|
ThomasBolden/cello-mod
|
68431de28a3575c95bb40c47fce7a352c6b92145
|
[
"MIT",
"BSD-3-Clause"
] | null | null | null |
src/Enzo/enzo_EnzoSolverHg.hpp
|
ThomasBolden/cello-mod
|
68431de28a3575c95bb40c47fce7a352c6b92145
|
[
"MIT",
"BSD-3-Clause"
] | null | null | null |
// See LICENSE_CELLO file for license and copyright information
/// @file enzo_EnzoSolverHg.hpp
/// @author James Bordner (jobordner@ucsd.edu)
/// @date 2015-06-02
/// @brief [\ref Enzo] Declaration of EnzoSolverHg
///
/// Multigrid for solving a linear system on the root-level grid only
#ifndef ENZO_ENZO_SOLVER_HG_HPP
#define ENZO_ENZO_SOLVER_HG_HPP
class EnzoSolverHg : public Solver {
/// @class EnzoSolverHg
/// @ingroup Enzo
///
/// @brief [\ref Enzo] Multigrid on the root-level grid. For use either
/// as a Gravity solver on non-adaptive problems, or as a preconditioner
/// for a Krylov subspace solver, as in Dan Reynold's HG solver.
public: // interface
/// Create a new EnzoSolverHg object
EnzoSolverHg
(const FieldDescr * field_descr,
int monitor_iter,
int rank,
int iter_max,
int index_solve_coarse,
Restrict * restrict,
Prolong * prolong,
int min_level,
int max_level);
EnzoSolverHg() {};
/// Charm++ PUP::able declarations
PUPable_decl(EnzoSolverHg);
/// Charm++ PUP::able migration constructor
EnzoSolverHg (CkMigrateMessage *m)
: A_(NULL),
index_solve_coarse_(-1),
restrict_(NULL),
prolong_(NULL),
rank_(0),
iter_max_(0),
monitor_iter_(0),
ib_(0), ic_(0), id_(0), ir_(0), ix_(0),
min_level_(0),
max_level_(0),
mx_(0),my_(0),mz_(0),
nx_(0),ny_(0),nz_(0),
gx_(0),gy_(0),gz_(0),
bs_(0), bc_(0)
{}
/// Destructor
~EnzoSolverHg () throw();
/// CHARM++ Pack / Unpack function
void pup (PUP::er &p)
{
// NOTE: change this function whenever attributes change
TRACEPUP;
Solver::pup(p);
p | A_;
p | index_solve_coarse_;
p | restrict_;
p | prolong_;
p | rank_;
p | iter_max_;
p | monitor_iter_;
p | ib_;
p | ic_;
p | id_;
p | ir_;
p | ix_;
p | min_level_;
p | max_level_;
p | mx_;
p | my_;
p | mz_;
p | nx_;
p | ny_;
p | nz_;
p | gx_;
p | gy_;
p | gz_;
p | bc_;
p | bs_;
}
/// Solve the linear system
virtual void apply ( Matrix * A, int ix, int ib, Block * block) throw();
virtual std::string name () const
{ return "hg"; }
void compute_correction(EnzoBlock * enzo_block) throw();
/// Apply pre-smoothing on the current level
template <class T>
void pre_smooth(EnzoBlock * enzo_block) throw();
/// Restrict residual to parent
template <class T>
void restrict_send(EnzoBlock * enzo_block) throw();
template <class T>
void restrict_recv(EnzoBlock * enzo_block) throw();
/// Access the Restrict operator by EnzoBlock
Restrict * restrict() { return restrict_; }
/// Access the Prolong operator by EnzoBlock
Prolong * prolong() { return prolong_; }
/// Solve the coarse-grid equation A*C = R
template <class T>
void solve_coarse(EnzoBlock * enzo_block) throw();
/// Prolong the correction C to the next-finer level
template <class T>
void prolong_recv(EnzoBlock * enzo_block) throw();
/// Apply post-smoothing to the current level
template <class T>
void post_smooth(EnzoBlock * enzo_block) throw();
void set_bs(long double bs) throw() { bs_ = bs; }
void set_bc(long double bc) throw() { bc_ = bc; }
template <class T>
void begin_solve(EnzoBlock * enzo_block) throw();
template <class T>
void end_cycle(EnzoBlock * enzo_block) throw();
protected: // methods
template <class T>
void enter_solver_(EnzoBlock * enzo_block) throw();
template <class T>
void begin_cycle_(EnzoBlock * enzo_block) throw();
/// Prolong the correction C to the next-finer level
template <class T>
void prolong_send_(EnzoBlock * enzo_block) throw();
void monitor_output_(EnzoBlock * enzo_block) throw();
bool is_converged_(EnzoBlock * enzo_block) const;
protected: // attributes
/// Matrix
Matrix * A_;
/// Solver index of the coarse solver
int index_solve_coarse_;
/// Restriction
Restrict * restrict_;
/// Prolongation
Prolong * prolong_;
/// Dimensionality of the problem
int rank_;
/// Maximum number of MG iterations
int iter_max_;
/// How often to display progress
int monitor_iter_;
/// Initial residual
long double rr0_;
/// MG vector id's
int ib_;
int ic_;
int id_;
int ir_;
int ix_;
/// Minimum refinement level (may be < 0)
int min_level_;
/// Maximum refinement level
int max_level_;
/// Block field attributes
int mx_,my_,mz_;
int nx_,ny_,nz_;
int gx_,gy_,gz_;
/// scalars used for projections of singular systems
long double bs_;
long double bc_;
};
#endif /* ENZO_ENZO_SOLVER_GRAVITY_HG_HPP */
| 21.823256
| 74
| 0.647272
|
ThomasBolden
|
3e328cfb83c3d0552fe6846a55521736fd260753
| 15,525
|
cpp
|
C++
|
src/o2requestor.cpp
|
someretical/o2
|
9784ebb9d287d959e4b7f856f39cdfc6ae256b59
|
[
"BSD-2-Clause"
] | null | null | null |
src/o2requestor.cpp
|
someretical/o2
|
9784ebb9d287d959e4b7f856f39cdfc6ae256b59
|
[
"BSD-2-Clause"
] | null | null | null |
src/o2requestor.cpp
|
someretical/o2
|
9784ebb9d287d959e4b7f856f39cdfc6ae256b59
|
[
"BSD-2-Clause"
] | null | null | null |
#include <cassert>
#include <QBuffer>
#include <QDebug>
#include <QTimer>
#if QT_VERSION >= 0x050000
#include <QUrlQuery>
#endif
#include "o0globals.h"
#include "o2.h"
#include "o2requestor.h"
O2Requestor::O2Requestor(QNetworkAccessManager *manager, O2 *authenticator, QObject *parent)
: QObject(parent), reply_(NULL), status_(Idle), addAccessTokenInQuery_(true), rawData_(false)
{
manager_ = manager;
authenticator_ = authenticator;
if (authenticator) {
timedReplies_.setIgnoreSslErrors(authenticator->ignoreSslErrors());
}
qRegisterMetaType<QNetworkReply::NetworkError>("QNetworkReply::NetworkError");
connect(authenticator, SIGNAL(refreshFinished(QNetworkReply::NetworkError)), this,
SLOT(onRefreshFinished(QNetworkReply::NetworkError)), Qt::QueuedConnection);
}
O2Requestor::~O2Requestor() {}
void O2Requestor::setAddAccessTokenInQuery(bool value)
{
addAccessTokenInQuery_ = value;
}
void O2Requestor::setAccessTokenInAuthenticationHTTPHeaderFormat(const QString &value)
{
accessTokenInAuthenticationHTTPHeaderFormat_ = value;
}
int O2Requestor::get(const QNetworkRequest &req, int timeout /* = 60*1000*/)
{
if (-1 == setup(req, QNetworkAccessManager::GetOperation)) {
return -1;
}
reply_ = manager_->get(request_);
timedReplies_.add(new O2Reply(reply_, timeout));
#if QT_VERSION < 0x051500
connect(reply_, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onRequestError(QNetworkReply::NetworkError)), Qt::QueuedConnection);
#else
connect(reply_, SIGNAL(errorOccurred(QNetworkReply::NetworkError)), this, SLOT(onRequestError(QNetworkReply::NetworkError)), Qt::QueuedConnection);
#endif
connect(reply_, SIGNAL(finished()), this, SLOT(onRequestFinished()), Qt::QueuedConnection);
return id_;
}
int O2Requestor::post(const QNetworkRequest &req, const QByteArray &data, int timeout /* = 60*1000*/)
{
if (-1 == setup(req, QNetworkAccessManager::PostOperation)) {
return -1;
}
rawData_ = true;
data_ = data;
reply_ = manager_->post(request_, data_);
timedReplies_.add(new O2Reply(reply_, timeout));
#if QT_VERSION < 0x051500
connect(reply_, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onRequestError(QNetworkReply::NetworkError)), Qt::QueuedConnection);
#else
connect(reply_, SIGNAL(errorOccurred(QNetworkReply::NetworkError)), this, SLOT(onRequestError(QNetworkReply::NetworkError)), Qt::QueuedConnection);
#endif
connect(reply_, SIGNAL(finished()), this, SLOT(onRequestFinished()), Qt::QueuedConnection);
connect(reply_, SIGNAL(uploadProgress(qint64, qint64)), this, SLOT(onUploadProgress(qint64, qint64)));
return id_;
}
int O2Requestor::post(const QNetworkRequest &req, QHttpMultiPart *data, int timeout /* = 60*1000*/)
{
if (-1 == setup(req, QNetworkAccessManager::PostOperation)) {
return -1;
}
rawData_ = false;
multipartData_ = data;
reply_ = manager_->post(request_, multipartData_);
multipartData_->setParent(reply_);
timedReplies_.add(new O2Reply(reply_, timeout));
#if QT_VERSION < 0x051500
connect(reply_, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onRequestError(QNetworkReply::NetworkError)), Qt::QueuedConnection);
#else
connect(reply_, SIGNAL(errorOccurred(QNetworkReply::NetworkError)), this, SLOT(onRequestError(QNetworkReply::NetworkError)), Qt::QueuedConnection);
#endif
connect(reply_, SIGNAL(finished()), this, SLOT(onRequestFinished()), Qt::QueuedConnection);
connect(reply_, SIGNAL(uploadProgress(qint64, qint64)), this, SLOT(onUploadProgress(qint64, qint64)));
return id_;
}
int O2Requestor::put(const QNetworkRequest &req, const QByteArray &data, int timeout /* = 60*1000*/)
{
if (-1 == setup(req, QNetworkAccessManager::PutOperation)) {
return -1;
}
rawData_ = true;
data_ = data;
reply_ = manager_->put(request_, data_);
timedReplies_.add(new O2Reply(reply_, timeout));
#if QT_VERSION < 0x051500
connect(reply_, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onRequestError(QNetworkReply::NetworkError)), Qt::QueuedConnection);
#else
connect(reply_, SIGNAL(errorOccurred(QNetworkReply::NetworkError)), this, SLOT(onRequestError(QNetworkReply::NetworkError)), Qt::QueuedConnection);
#endif
connect(reply_, SIGNAL(finished()), this, SLOT(onRequestFinished()), Qt::QueuedConnection);
connect(reply_, SIGNAL(uploadProgress(qint64, qint64)), this, SLOT(onUploadProgress(qint64, qint64)));
return id_;
}
int O2Requestor::put(const QNetworkRequest &req, QHttpMultiPart *data, int timeout /* = 60*1000*/)
{
if (-1 == setup(req, QNetworkAccessManager::PutOperation)) {
return -1;
}
rawData_ = false;
multipartData_ = data;
reply_ = manager_->put(request_, multipartData_);
multipartData_->setParent(reply_);
timedReplies_.add(new O2Reply(reply_, timeout));
#if QT_VERSION < 0x051500
connect(reply_, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onRequestError(QNetworkReply::NetworkError)), Qt::QueuedConnection);
#else
connect(reply_, SIGNAL(errorOccurred(QNetworkReply::NetworkError)), this, SLOT(onRequestError(QNetworkReply::NetworkError)), Qt::QueuedConnection);
#endif
connect(reply_, SIGNAL(finished()), this, SLOT(onRequestFinished()), Qt::QueuedConnection);
connect(reply_, SIGNAL(uploadProgress(qint64, qint64)), this, SLOT(onUploadProgress(qint64, qint64)));
return id_;
}
int O2Requestor::deleteResource(const QNetworkRequest &req, int timeout /* = 60*1000*/)
{
if (-1 == setup(req, QNetworkAccessManager::DeleteOperation)) {
return -1;
}
rawData_ = false;
reply_ = manager_->deleteResource(request_);
timedReplies_.add(new O2Reply(reply_, timeout));
#if QT_VERSION < 0x051500
connect(reply_, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onRequestError(QNetworkReply::NetworkError)), Qt::QueuedConnection);
#else
connect(reply_, SIGNAL(errorOccurred(QNetworkReply::NetworkError)), this, SLOT(onRequestError(QNetworkReply::NetworkError)), Qt::QueuedConnection);
#endif
connect(reply_, SIGNAL(finished()), this, SLOT(onRequestFinished()), Qt::QueuedConnection);
return id_;
}
int O2Requestor::customRequest(
const QNetworkRequest &req, const QByteArray &verb, const QByteArray &data, int timeout /* = 60*1000*/)
{
(void)timeout;
if (-1 == setup(req, QNetworkAccessManager::CustomOperation, verb)) {
return -1;
}
data_ = data;
QBuffer *buffer = new QBuffer;
buffer->setData(data_);
reply_ = manager_->sendCustomRequest(request_, verb, buffer);
buffer->setParent(reply_);
timedReplies_.add(new O2Reply(reply_));
#if QT_VERSION < 0x051500
connect(reply_, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onRequestError(QNetworkReply::NetworkError)), Qt::QueuedConnection);
#else
connect(reply_, SIGNAL(errorOccurred(QNetworkReply::NetworkError)), this, SLOT(onRequestError(QNetworkReply::NetworkError)), Qt::QueuedConnection);
#endif
connect(reply_, SIGNAL(finished()), this, SLOT(onRequestFinished()), Qt::QueuedConnection);
connect(reply_, SIGNAL(uploadProgress(qint64, qint64)), this, SLOT(onUploadProgress(qint64, qint64)));
return id_;
}
int O2Requestor::customRequest(
const QNetworkRequest &req, const QByteArray &verb, QHttpMultiPart *data, int timeout /* = 60*1000*/)
{
(void)timeout;
if (-1 == setup(req, QNetworkAccessManager::CustomOperation, verb)) {
return -1;
}
rawData_ = false;
multipartData_ = data;
reply_ = manager_->sendCustomRequest(request_, verb, multipartData_);
multipartData_->setParent(reply_);
timedReplies_.add(new O2Reply(reply_, timeout));
#if QT_VERSION < 0x051500
connect(reply_, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onRequestError(QNetworkReply::NetworkError)), Qt::QueuedConnection);
#else
connect(reply_, SIGNAL(errorOccurred(QNetworkReply::NetworkError)), this, SLOT(onRequestError(QNetworkReply::NetworkError)), Qt::QueuedConnection);
#endif
connect(reply_, SIGNAL(finished()), this, SLOT(onRequestFinished()), Qt::QueuedConnection);
connect(reply_, SIGNAL(uploadProgress(qint64, qint64)), this, SLOT(onUploadProgress(qint64, qint64)));
return id_;
}
int O2Requestor::head(const QNetworkRequest &req, int timeout /* = 60*1000*/)
{
if (-1 == setup(req, QNetworkAccessManager::HeadOperation)) {
return -1;
}
reply_ = manager_->head(request_);
timedReplies_.add(new O2Reply(reply_, timeout));
#if QT_VERSION < 0x051500
connect(reply_, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onRequestError(QNetworkReply::NetworkError)), Qt::QueuedConnection);
#else
connect(reply_, SIGNAL(errorOccurred(QNetworkReply::NetworkError)), this, SLOT(onRequestError(QNetworkReply::NetworkError)), Qt::QueuedConnection);
#endif
connect(reply_, SIGNAL(finished()), this, SLOT(onRequestFinished()), Qt::QueuedConnection);
return id_;
}
void O2Requestor::onRefreshFinished(QNetworkReply::NetworkError error)
{
if (status_ != Requesting) {
qWarning() << "O2Requestor::onRefreshFinished: No pending request";
return;
}
if (QNetworkReply::NoError == error) {
QTimer::singleShot(100, this, SLOT(retry()));
}
else {
error_ = error;
QTimer::singleShot(10, this, SLOT(finish()));
}
}
void O2Requestor::onRequestFinished()
{
if (status_ == Idle) {
return;
}
if (reply_ != qobject_cast<QNetworkReply *>(sender())) {
return;
}
if (reply_->error() == QNetworkReply::NoError) {
QTimer::singleShot(10, this, SLOT(finish()));
}
}
void O2Requestor::onRequestError(QNetworkReply::NetworkError error)
{
qWarning() << "O2Requestor::onRequestError: Error" << (int)error;
if (status_ == Idle) {
return;
}
if (reply_ != qobject_cast<QNetworkReply *>(sender())) {
return;
}
int httpStatus = reply_->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
qWarning() << "O2Requestor::onRequestError: HTTP status" << httpStatus
<< reply_->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString();
if ((status_ == Requesting) && (httpStatus == 401)) {
// Call O2::refresh. Note the O2 instance might live in a different thread
if (QMetaObject::invokeMethod(authenticator_, "refresh")) {
return;
}
qCritical() << "O2Requestor::onRequestError: Invoking remote refresh failed";
}
error_ = error;
QTimer::singleShot(10, this, SLOT(finish()));
}
void O2Requestor::onUploadProgress(qint64 uploaded, qint64 total)
{
if (status_ == Idle) {
qWarning() << "O2Requestor::onUploadProgress: No pending request";
return;
}
if (reply_ != qobject_cast<QNetworkReply *>(sender())) {
return;
}
// Restart timeout because request in progress
O2Reply *o2Reply = timedReplies_.find(reply_);
if (o2Reply)
o2Reply->start();
Q_EMIT uploadProgress(id_, uploaded, total);
}
int O2Requestor::setup(const QNetworkRequest &req, QNetworkAccessManager::Operation operation, const QByteArray &verb)
{
static int currentId;
if (status_ != Idle) {
qWarning() << "O2Requestor::setup: Another request pending";
return -1;
}
request_ = req;
operation_ = operation;
id_ = currentId++;
url_ = req.url();
QUrl url = url_;
if (addAccessTokenInQuery_) {
#if QT_VERSION < 0x050000
url.addQueryItem(O2_OAUTH2_ACCESS_TOKEN, authenticator_->token());
#else
QUrlQuery query(url);
query.addQueryItem(O2_OAUTH2_ACCESS_TOKEN, authenticator_->token());
url.setQuery(query);
#endif
}
request_.setUrl(url);
// If the service require the access token to be sent as a Authentication HTTP header, we add the access token.
if (!accessTokenInAuthenticationHTTPHeaderFormat_.isEmpty()) {
request_.setRawHeader(O2_HTTP_AUTHORIZATION_HEADER,
accessTokenInAuthenticationHTTPHeaderFormat_.arg(authenticator_->token()).toLatin1());
}
if (!verb.isEmpty()) {
request_.setRawHeader(O2_HTTP_HTTP_HEADER, verb);
}
status_ = Requesting;
error_ = QNetworkReply::NoError;
return id_;
}
void O2Requestor::finish()
{
QByteArray data;
if (status_ == Idle) {
qWarning() << "O2Requestor::finish: No pending request";
return;
}
data = reply_->readAll();
status_ = Idle;
timedReplies_.remove(reply_);
reply_->disconnect(this);
reply_->deleteLater();
QList<QNetworkReply::RawHeaderPair> headers = reply_->rawHeaderPairs();
Q_EMIT finished(id_, error_, data);
Q_EMIT finished(id_, error_, reply_->errorString(), data);
Q_EMIT finished(id_, error_, data, headers);
Q_EMIT finished(id_, error_, reply_->errorString(), data, headers);
Q_EMIT finished(td::NR{error_, reply_->errorString(), data});
}
void O2Requestor::retry()
{
if (status_ != Requesting) {
qWarning() << "O2Requestor::retry: No pending request";
return;
}
timedReplies_.remove(reply_);
reply_->disconnect(this);
reply_->deleteLater();
QUrl url = url_;
if (addAccessTokenInQuery_) {
#if QT_VERSION < 0x050000
url.addQueryItem(O2_OAUTH2_ACCESS_TOKEN, authenticator_->token());
#else
QUrlQuery query(url);
query.addQueryItem(O2_OAUTH2_ACCESS_TOKEN, authenticator_->token());
url.setQuery(query);
#endif
}
request_.setUrl(url);
// If the service require the access token to be sent as a Authentication HTTP header,
// we update the access token when retrying.
if (!accessTokenInAuthenticationHTTPHeaderFormat_.isEmpty()) {
request_.setRawHeader(O2_HTTP_AUTHORIZATION_HEADER,
accessTokenInAuthenticationHTTPHeaderFormat_.arg(authenticator_->token()).toLatin1());
}
status_ = ReRequesting;
switch (operation_) {
case QNetworkAccessManager::GetOperation:
reply_ = manager_->get(request_);
break;
case QNetworkAccessManager::PostOperation:
reply_ = rawData_ ? manager_->post(request_, data_) : manager_->post(request_, multipartData_);
break;
case QNetworkAccessManager::CustomOperation: {
QBuffer *buffer = new QBuffer;
buffer->setData(data_);
reply_ = manager_->sendCustomRequest(request_, request_.rawHeader(O2_HTTP_HTTP_HEADER), buffer);
buffer->setParent(reply_);
} break;
case QNetworkAccessManager::PutOperation:
reply_ = rawData_ ? manager_->post(request_, data_) : manager_->put(request_, multipartData_);
break;
case QNetworkAccessManager::HeadOperation:
reply_ = manager_->head(request_);
break;
default:
assert(!"Unspecified operation for request");
reply_ = manager_->get(request_);
break;
}
timedReplies_.add(reply_);
#if QT_VERSION < 0x051500
connect(reply_, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onRequestError(QNetworkReply::NetworkError)), Qt::QueuedConnection);
#else
connect(reply_, SIGNAL(errorOccurred(QNetworkReply::NetworkError)), this, SLOT(onRequestError(QNetworkReply::NetworkError)), Qt::QueuedConnection);
#endif
connect(reply_, SIGNAL(finished()), this, SLOT(onRequestFinished()), Qt::QueuedConnection);
connect(reply_, SIGNAL(uploadProgress(qint64, qint64)), this, SLOT(onUploadProgress(qint64, qint64)));
}
| 38.333333
| 151
| 0.703704
|
someretical
|
3e3709714ceb4e5dd903c0333ddae2a0f756ed05
| 448
|
hpp
|
C++
|
src/Printer.hpp
|
amoulis/Chessy
|
7a31a79ee15eef25037ba316918c6a6f603caf6c
|
[
"Unlicense"
] | null | null | null |
src/Printer.hpp
|
amoulis/Chessy
|
7a31a79ee15eef25037ba316918c6a6f603caf6c
|
[
"Unlicense"
] | null | null | null |
src/Printer.hpp
|
amoulis/Chessy
|
7a31a79ee15eef25037ba316918c6a6f603caf6c
|
[
"Unlicense"
] | null | null | null |
/***************************************************************************
Printer.hpp
Prints data on screen (board display with the pieces)
***************************************************************************/
#ifndef PRINTER_HPP
#define PRINTER_HPP
namespace printer{
class
Printer {
public:
Printer();
void print_screen(char board[8][24]);
private:
int m_length;
int m_width;
};
} // namespace printer
#endif //Printer_HPP
| 18.666667
| 76
| 0.482143
|
amoulis
|
3e39e755701a12634d8cc52fb7a45973baaa1767
| 3,608
|
cc
|
C++
|
ThirdParty/webrtc/src/net/proxy/proxy_resolver_error_observer_mojo_unittest.cc
|
JokeJoe8806/licode-windows
|
2bfdaf6e87669df2b9960da50c6800bc3621b80b
|
[
"MIT"
] | 8
|
2018-12-27T14:57:13.000Z
|
2021-04-07T07:03:15.000Z
|
ThirdParty/webrtc/src/net/proxy/proxy_resolver_error_observer_mojo_unittest.cc
|
JokeJoe8806/licode-windows
|
2bfdaf6e87669df2b9960da50c6800bc3621b80b
|
[
"MIT"
] | 1
|
2019-03-13T01:35:03.000Z
|
2020-10-08T04:13:04.000Z
|
ThirdParty/webrtc/src/net/proxy/proxy_resolver_error_observer_mojo_unittest.cc
|
JokeJoe8806/licode-windows
|
2bfdaf6e87669df2b9960da50c6800bc3621b80b
|
[
"MIT"
] | 9
|
2018-12-28T11:45:12.000Z
|
2021-05-11T02:15:31.000Z
|
// Copyright 2015 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 "net/proxy/proxy_resolver_error_observer_mojo.h"
#include <utility>
#include <vector>
#include "base/bind.h"
#include "base/location.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/utf_string_conversions.h"
#include "base/threading/thread.h"
#include "mojo/common/common_type_converters.h"
#include "net/test/event_waiter.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace net {
namespace {
class ErrorObserverClient : public interfaces::ProxyResolverErrorObserver {
public:
enum Event {
ERROR_RECEIVED,
};
explicit ErrorObserverClient(
mojo::InterfaceRequest<interfaces::ProxyResolverErrorObserver> request);
EventWaiter<Event>& event_waiter() { return event_waiter_; }
const std::vector<std::pair<int, base::string16>>& errors() const {
return errors_;
}
private:
void OnPacScriptError(int32_t line_number,
const mojo::String& error) override;
mojo::Binding<interfaces::ProxyResolverErrorObserver> binding_;
EventWaiter<Event> event_waiter_;
std::vector<std::pair<int, base::string16>> errors_;
DISALLOW_COPY_AND_ASSIGN(ErrorObserverClient);
};
ErrorObserverClient::ErrorObserverClient(
mojo::InterfaceRequest<interfaces::ProxyResolverErrorObserver> request)
: binding_(this, request.Pass()) {
}
void ErrorObserverClient::OnPacScriptError(int32_t line_number,
const mojo::String& error) {
errors_.push_back(std::make_pair(line_number, error.To<base::string16>()));
event_waiter_.NotifyEvent(ERROR_RECEIVED);
}
} // namespace
class ProxyResolverErrorObserverMojoTest : public testing::Test {
public:
ProxyResolverErrorObserver& error_observer() { return *error_observer_; }
ErrorObserverClient& client() { return *client_; }
private:
void SetUp() override {
interfaces::ProxyResolverErrorObserverPtr error_observer_ptr;
client_.reset(new ErrorObserverClient(mojo::GetProxy(&error_observer_ptr)));
error_observer_ =
ProxyResolverErrorObserverMojo::Create(error_observer_ptr.Pass());
ASSERT_TRUE(error_observer_);
}
scoped_ptr<ErrorObserverClient> client_;
scoped_ptr<ProxyResolverErrorObserver> error_observer_;
};
TEST_F(ProxyResolverErrorObserverMojoTest, NullHandle) {
EXPECT_FALSE(ProxyResolverErrorObserverMojo::Create(
interfaces::ProxyResolverErrorObserverPtr()));
}
TEST_F(ProxyResolverErrorObserverMojoTest, ErrorReportedOnMainThread) {
base::string16 error(base::ASCIIToUTF16("error message"));
error_observer().OnPACScriptError(123, error);
client().event_waiter().WaitForEvent(ErrorObserverClient::ERROR_RECEIVED);
ASSERT_EQ(1u, client().errors().size());
EXPECT_EQ(123, client().errors()[0].first);
EXPECT_EQ(error, client().errors()[0].second);
}
TEST_F(ProxyResolverErrorObserverMojoTest, ErrorReportedOnAnotherThread) {
base::Thread other_thread("error reporting thread");
base::string16 error(base::ASCIIToUTF16("error message"));
other_thread.Start();
other_thread.task_runner()->PostTask(
FROM_HERE, base::Bind(&ProxyResolverErrorObserver::OnPACScriptError,
base::Unretained(&error_observer()), 123, error));
client().event_waiter().WaitForEvent(ErrorObserverClient::ERROR_RECEIVED);
ASSERT_EQ(1u, client().errors().size());
EXPECT_EQ(123, client().errors()[0].first);
EXPECT_EQ(error, client().errors()[0].second);
}
} // namespace net
| 34.037736
| 80
| 0.747506
|
JokeJoe8806
|
3e3af43e9f9b213887a4a9b476a565c78d7ff490
| 71,993
|
cpp
|
C++
|
lathraea-rhodopaea/src/front-end/eventManagerMenu.cpp
|
SSIvanov19/lathraea-rhodopaea
|
d38510e69a15d0868ba4385574f41bd9dc666a0f
|
[
"MIT"
] | 9
|
2022-02-15T21:17:45.000Z
|
2022-02-22T05:16:06.000Z
|
lathraea-rhodopaea/src/front-end/eventManagerMenu.cpp
|
SSIvanov19/lathraea-rhodopaea
|
d38510e69a15d0868ba4385574f41bd9dc666a0f
|
[
"MIT"
] | 7
|
2022-02-15T23:51:44.000Z
|
2022-02-16T05:17:52.000Z
|
lathraea-rhodopaea/src/front-end/eventManagerMenu.cpp
|
SSIvanov19/lathraea-rhodopaea
|
d38510e69a15d0868ba4385574f41bd9dc666a0f
|
[
"MIT"
] | null | null | null |
/*! @file eventManagerMenu.cpp
* @brief A source file for the event menu handaling system.
*/
#include <front-end/output.h>
#include <front-end/graphics.h>
#include <front-end/enumerations.h>
#include <front-end/helperFunctions.h>
#include <front-end/eventManagerMenu.h>
void addOtherEvent(EventManager* eventManager, bool approve)
{
printFullyOpenedBook();
std::string title;
outputPosition(81, 10);
std::cout << "Enter the title of the event you want to add: " << std::endl;
outputPosition(81, 12);
getline(std::cin, title);
while (title.empty())
{
outputPosition(81, 12);
std::cout << "Title can not be empty, please enter again: ";
outputPosition(81, 14);
getline(std::cin, title);
}
printFullyOpenedBook();
std::string period;
outputPosition(81, 10);
std::cout << "Enter the starting and ending year and date";
outputPosition(81, 12);
std::cout << "Example - (20 apr 1876, 15 may 1876)";
outputPosition(81, 14);
getline(std::cin, period);
while (!checkDatesValidation(period))
{
outputPosition(81, 14);
std::cout << "The data you've entered is incorrect!";
outputPosition(81, 16);
std::cout << "Please enter a date/s - ex(24 apr 809, 27 apr 810)";
outputPosition(81, 18);
getline(std::cin, period);
}
separateDates(period);
printFullyOpenedBook();
printMapPopUp();
printBulgarianMap();
short x = 56;
short y = 20;
char key;
outputPosition(x, y);
std::cout << char(254);
while ((key = _getch()) != (char)ARROW_KEYS::KEY_ENTER)
{
switch (key)
{
case (char)ARROW_KEYS::KEY_UP:
outputPosition(x, y);
std::cout << " ";
y -= 1;
outputPosition(x, y);
std::cout << char(254);
break;
case (char)ARROW_KEYS::KEY_DOWN:
outputPosition(x, y);
std::cout << " ";
y += 1;
outputPosition(x, y);
std::cout << char(254);
break;
case (char)ARROW_KEYS::KEY_LEFT:
outputPosition(x, y);
std::cout << " ";
x += 1;
outputPosition(x, y);
std::cout << char(254);
break;
case (char)ARROW_KEYS::KEY_RIGHT:
outputPosition(x, y);
std::cout << " ";
x -= 1;
outputPosition(x, y);
std::cout << char(254);
break;
case (char)ARROW_KEYS::KEY_ENTER:
printFullyOpenedBook();
break;
}
}
Coordinates coordinates{ x, y };
printFullyOpenedBook();
std::string additionalNotes;
outputPosition(81, 10);
std::cout << "Enter some additional notes for the event, if any: ";
outputPosition(81, 12);
getline(std::cin, additionalNotes);
try
{
eventManager->addOtherEvent(title, separateDates(period), coordinates, additionalNotes);
}
catch (std::string errorMessage)
{
std::cout << errorMessage;
}
}
void addUprisingEvent(EventManager* eventManager, bool approve)
{
std::string title;
printFullyOpenedBook();
outputPosition(81, 10);
std::cout << "Enter the title of the event you want to add: " << std::endl;
outputPosition(81, 12);
getline(std::cin, title);
while (title.empty())
{
outputPosition(81, 12);
std::cout << "Title can not be empty, please enter again: ";
outputPosition(81, 14);
getline(std::cin, title);
}
printFullyOpenedBook();
std::string period;
outputPosition(81, 10);
std::cout << "Enter the starting and ending year and date";
outputPosition(81, 12);
std::cout << "Example - (20 apr 1876, 15 may 1876)";
outputPosition(81, 14);
getline(std::cin, period);
while (!checkDatesValidation(period))
{
outputPosition(81, 14);
std::cout << "The data you've entered is incorrect!";
outputPosition(81, 16);
std::cout << "Please enter a date/s - ex(24 apr 809, 27 apr 810)";
outputPosition(81, 18);
std::cout << " ";
outputPosition(81, 18);
getline(std::cin, period);
}
separateDates(period);
printFullyOpenedBook();
printMapPopUp();
printBulgarianMap();
short x = 56;
short y = 20;
char key;
outputPosition(x, y);
std::cout << char(254);
while ((key = _getch()) != (char)ARROW_KEYS::KEY_ENTER)
{
switch (key)
{
case (char)ARROW_KEYS::KEY_UP:
outputPosition(x, y);
std::cout << " ";
y -= 1;
outputPosition(x, y);
std::cout << char(254);
break;
case (char)ARROW_KEYS::KEY_DOWN:
outputPosition(x, y);
std::cout << " ";
y += 1;
outputPosition(x, y);
std::cout << char(254);
break;
case (char)ARROW_KEYS::KEY_LEFT:
outputPosition(x, y);
std::cout << " ";
x += 1;
outputPosition(x, y);
std::cout << char(254);
break;
case (char)ARROW_KEYS::KEY_RIGHT:
outputPosition(x, y);
std::cout << " ";
x -= 1;
outputPosition(x, y);
std::cout << char(254);
break;
case (char)ARROW_KEYS::KEY_ENTER:
printFullyOpenedBook();
break;
}
}
Coordinates coordinates{ x, y };
std::string organizers;
printFullyOpenedBook();
outputPosition(81, 10);
std::cout << "Enter the organizers of the event you want to add: ";
outputPosition(81, 12);
getline(std::cin, organizers);
while (organizers.empty())
{
outputPosition(81, 12);
std::cout << "Organizers can not be empty, please enter again: ";
outputPosition(81, 14);
getline(std::cin, organizers);
}
std::vector<std::string> organizersV;
organizersV.push_back(organizers);
printFullyOpenedBook();
bool isItSuccessful = true;
const std::vector<std::string> successOfEventOptions = {
"Successful",
"Unsuccessful"
};
outputPosition(81, 10);
std::cout << "Is the event successful?";
int selectedOption = 1;
char pressedKey = ' ';
while (pressedKey != (int)ARROW_KEYS::KEY_ENTER)
{
for (int i = 0; i < successOfEventOptions.size(); i++)
{
if (i + 1 == selectedOption)
{
outputPosition(81, 12 + i * 2);
std::cout << "-> ";
}
else
{
outputPosition(81, 12 + i * 2);
std::cout << " ";
}
std::cout << successOfEventOptions[i] << std::endl << std::endl;
}
pressedKey = _getch();
switch (pressedKey)
{
case (int)ARROW_KEYS::KEY_UP:
selectedOption--;
if (selectedOption == 0)
{
selectedOption += 1;
}
break;
case (int)ARROW_KEYS::KEY_DOWN:
selectedOption++;
if (selectedOption == successOfEventOptions.size() + 1)
{
selectedOption -= 1;
}
break;
case (int)ARROW_KEYS::KEY_ENTER:
switch (selectedOption)
{
case 1:
isItSuccessful = true;
printFullyOpenedBook();
break;
case 2:
isItSuccessful = false;
printFullyOpenedBook();
break;
}
}
}
int numberOfRebelions;
printFullyOpenedBook();
outputPosition(81, 10);
std::cout << "Enter the number of rebellions of the event: ";
outputPosition(81, 12);
std::cin >> numberOfRebelions;
std::string additionalNotes;
printFullyOpenedBook();
outputPosition(81, 10);
std::cout << "Enter some additional notes for the event, if any: ";
outputPosition(81, 12);
std::cin.ignore(INT_MAX, '\n');
getline(std::cin, additionalNotes);
try
{
eventManager->addUprisingEvent(
title,
separateDates(period),
coordinates,
organizersV,
isItSuccessful,
numberOfRebelions,
additionalNotes
);
if (approve)
{
eventManager->approveEvent(title);
}
}
catch (std::string errorMessage)
{
std::cout << errorMessage;
}
}
void addWarEvent(EventManager* eventManager, bool approve)
{
printFullyOpenedBook();
std::string title;
outputPosition(81, 10);
std::cout << "Enter the title of the event you want to add: " << std::endl;
outputPosition(81, 12);
getline(std::cin, title);
while (title.empty())
{
outputPosition(81, 12);
std::cout << "Title can not be empty, please enter again: ";
outputPosition(81, 14);
getline(std::cin, title);
}
printFullyOpenedBook();
std::string period;
outputPosition(81, 10);
std::cout << "Enter the starting and ending year and date";
outputPosition(81, 12);
std::cout << "Example - (20 apr 1876, 15 may 1876)";
outputPosition(81, 14);
getline(std::cin, period);
while (!checkDatesValidation(period))
{
outputPosition(81, 14);
std::cout << "The data you've entered is incorrect!";
outputPosition(81, 16);
std::cout << "Please enter a date/s - ex(24 apr 809, 27 apr 810)";
outputPosition(81, 18);
getline(std::cin, period);
}
separateDates(period);
printFullyOpenedBook();
printMapPopUp();
printBulgarianMap();
short x = 56;
short y = 20;
char key;
outputPosition(x, y);
std::cout << char(254);
while ((key = _getch()) != (char)ARROW_KEYS::KEY_ENTER)
{
switch (key)
{
case (char)ARROW_KEYS::KEY_UP:
outputPosition(x, y);
std::cout << " ";
y -= 1;
outputPosition(x, y);
std::cout << char(254);
break;
case (char)ARROW_KEYS::KEY_DOWN:
outputPosition(x, y);
std::cout << " ";
y += 1;
outputPosition(x, y);
std::cout << char(254);
break;
case (char)ARROW_KEYS::KEY_LEFT:
outputPosition(x, y);
std::cout << " ";
x += 1;
outputPosition(x, y);
std::cout << char(254);
break;
case (char)ARROW_KEYS::KEY_RIGHT:
outputPosition(x, y);
std::cout << " ";
x -= 1;
outputPosition(x, y);
std::cout << char(254);
break;
case (char)ARROW_KEYS::KEY_ENTER:
printFullyOpenedBook();
break;
}
}
Coordinates coordinates{ x, y };
printFullyOpenedBook();
std::string participatingCountries;
outputPosition(81, 10);
std::cout << "Enter the countries participating in the event: ";
outputPosition(81, 12);
getline(std::cin, participatingCountries);
while (participatingCountries.empty())
{
outputPosition(81, 12);
std::cout << "Participating countries can not be empty!";
outputPosition(81, 12);
std::cout << "Please enter again: ";
outputPosition(81, 14);
getline(std::cin, participatingCountries);
}
std::vector<std::string> participatingCountriesV;
participatingCountriesV.push_back(participatingCountries);
printFullyOpenedBook();
std::string winner;
outputPosition(81, 10);
std::cout << "Enter the winner of the event you want to add: " << std::endl;
outputPosition(81, 12);
getline(std::cin, winner);
while (winner.empty())
{
outputPosition(81, 12);
std::cout << "Winner can not be empty, please enter again: ";
outputPosition(81, 14);
getline(std::cin, winner);
}
printFullyOpenedBook();
std::string reasons;
outputPosition(81, 10);
std::cout << "Enter the reason that led to the event: " << std::endl;
outputPosition(81, 12);
getline(std::cin, reasons);
while (reasons.empty())
{
outputPosition(81, 12);
std::cout << "Reasons can not be empty, please enter again: ";
outputPosition(81, 14);
getline(std::cin, reasons);
}
printFullyOpenedBook();
std::string rulers;
outputPosition(81, 10);
std::cout << "Enter the rulers of the event you want to add: ";
outputPosition(81, 12);
getline(std::cin, rulers);
while (rulers.empty())
{
outputPosition(81, 12);
std::cout << "Rulers can not be empty, please enter again: ";
outputPosition(81, 14);
getline(std::cin, rulers);
}
std::vector<std::string> rulersV;
rulersV.push_back(rulers);
printFullyOpenedBook();
std::string additionalNotes;
outputPosition(81, 10);
std::cout << "Enter some additional notes for the event, if any: ";
outputPosition(81, 12);
getline(std::cin, additionalNotes);
try
{
eventManager->addWarEvent(
title,
separateDates(period),
coordinates,
participatingCountriesV,
winner,
reasons,
rulersV,
additionalNotes
);
if (approve)
{
eventManager->approveEvent(title);
}
}
catch (std::string errorMessage)
{
std::cout << errorMessage;
}
}
void addMovementEvent(EventManager* eventManager, bool approve)
{
printFullyOpenedBook();
std::string title;
outputPosition(81, 10);
std::cout << "Enter the title of the event you want to add: " << std::endl;
outputPosition(81, 12);
getline(std::cin, title);
while (title.empty())
{
outputPosition(81, 12);
std::cout << "Title can not be empty, please enter again: ";
outputPosition(81, 14);
getline(std::cin, title);
}
printFullyOpenedBook();
std::string period;
outputPosition(81, 10);
std::cout << "Enter the starting and ending year and date";
outputPosition(81, 12);
std::cout << "Example - (20 apr 1876, 15 may 1876)";
outputPosition(81, 14);
getline(std::cin, period);
while (!checkDatesValidation(period))
{
outputPosition(81, 14);
std::cout << "The data you've entered is incorrect!";
outputPosition(81, 16);
std::cout << "Please enter a date/s - ex(24 apr 809, 27 apr 810)";
outputPosition(81, 18);
getline(std::cin, period);
}
separateDates(period);
printFullyOpenedBook();
printMapPopUp();
printBulgarianMap();
short x = 56;
short y = 20;
char key;
outputPosition(x, y);
std::cout << char(254);
while ((key = _getch()) != (char)ARROW_KEYS::KEY_ENTER)
{
switch (key)
{
case (char)ARROW_KEYS::KEY_UP:
outputPosition(x, y);
std::cout << " ";
y -= 1;
outputPosition(x, y);
std::cout << char(254);
break;
case (char)ARROW_KEYS::KEY_DOWN:
outputPosition(x, y);
std::cout << " ";
y += 1;
outputPosition(x, y);
std::cout << char(254);
break;
case (char)ARROW_KEYS::KEY_LEFT:
outputPosition(x, y);
std::cout << " ";
x += 1;
outputPosition(x, y);
std::cout << char(254);
break;
case (char)ARROW_KEYS::KEY_RIGHT:
outputPosition(x, y);
std::cout << " ";
x -= 1;
outputPosition(x, y);
std::cout << char(254);
break;
case (char)ARROW_KEYS::KEY_ENTER:
printFullyOpenedBook();
break;
}
}
Coordinates coordinates{ x, y };
printFullyOpenedBook();
std::string howItStarted;
outputPosition(81, 10);
std::cout << "Enter the way the event started: " << std::endl;
outputPosition(81, 12);
getline(std::cin, howItStarted);
while (howItStarted.empty())
{
outputPosition(81, 12);
std::cout << "The way it started can not be empty!";
outputPosition(81, 14);
std::cout << "Please enter again: ";
outputPosition(81, 16);
getline(std::cin, howItStarted);
}
printFullyOpenedBook();
std::string ideas;
outputPosition(81, 10);
std::cout << "Enter ideas of the event you want to add: " << std::endl;
outputPosition(81, 12);
getline(std::cin, ideas);
while (ideas.empty())
{
outputPosition(81, 12);
std::cout << "The ideas can not be empty, please enter again: ";
outputPosition(81, 14);
getline(std::cin, ideas);
}
printFullyOpenedBook();
std::string aims;
outputPosition(81, 10);
std::cout << "Enter the aims of the event you want to add: " << std::endl;
outputPosition(81, 12);
getline(std::cin, aims);
while (aims.empty())
{
outputPosition(81, 10);
std::cout << "The aims can not be empty, please enter again: ";
outputPosition(81, 12);
getline(std::cin, aims);
}
printFullyOpenedBook();
std::string representatives;
outputPosition(81, 10);
std::cout << "Enter the representatives of the event: ";
outputPosition(81, 12);
getline(std::cin, representatives);
while (representatives.empty())
{
outputPosition(81, 12);
std::cout << "The representatives can not be empty!";
outputPosition(81, 14);
std::cout << "Please enter again: ";
outputPosition(81, 16);
getline(std::cin, representatives);
}
std::vector<std::string> representativesV;
representativesV.push_back(representatives);
printFullyOpenedBook();
std::string additionalNotes;
outputPosition(81, 10);
std::cout << "Enter some additional notes for the event, if any: ";
outputPosition(81, 12);
getline(std::cin, additionalNotes);
while (std::cin.fail())
{
std::cin.clear();
std::cin.ignore(INT_MAX, '\n');
outputPosition(81, 10);
std::cout << "Enter some additional notes for the event, if any: ";
outputPosition(81, 12);
getline(std::cin, additionalNotes);
}
try
{
eventManager->addMovementEvent(
title,
separateDates(period),
coordinates,
howItStarted,
ideas,
aims,
representativesV,
additionalNotes
);
if (approve)
{
eventManager->approveEvent(title);
}
}
catch (std::string errorMessage)
{
std::cout << errorMessage;
}
}
void addEvent(EventManager* eventManager, bool approve)
{
outputPosition(81, 10);
std::cout << "Choose the type of event you want to add!";
const std::vector<std::string> eventTypeOptions = {
"Uprising",
"War",
"Movement",
"Other"
};
int selectedOption = 1;
char pressedKey = ' ';
while (pressedKey != (int)ARROW_KEYS::KEY_ENTER)
{
for (int i = 0; i < eventTypeOptions.size(); i++)
{
if (i + 1 == selectedOption)
{
outputPosition(81, 12 + i * 2);
std::cout << "-> ";
}
else
{
outputPosition(81, 12 + i * 2);
std::cout << " ";
}
std::cout << eventTypeOptions[i] << std::endl << std::endl;
}
pressedKey = _getch();
switch (pressedKey)
{
case (int)ARROW_KEYS::KEY_UP:
selectedOption--;
if (selectedOption == 0)
{
selectedOption += 1;
}
break;
case (int)ARROW_KEYS::KEY_DOWN:
selectedOption++;
if (selectedOption == eventTypeOptions.size() + 1)
{
selectedOption -= 1;
}
break;
case (int)ARROW_KEYS::KEY_ENTER:
switch (selectedOption)
{
case 1:
addUprisingEvent(eventManager, approve);
break;
case 2:
addWarEvent(eventManager, approve);
break;
case 3:
addMovementEvent(eventManager, approve);
break;
case 4:
addOtherEvent(eventManager, approve);
break;
}
}
}
if (_getch())
{
clearConsole();
printClosedBook();
printBookDecorations();
printSnakeSword();
printTeamLogo();
}
}
void deleteEvent(EventManager* eventManager)
{
std::vector<Event> approveEvents = eventManager->getAllEvents(1);
std::vector<Event> unApproveEvents = eventManager->getAllEvents(0);
approveEvents.insert(
approveEvents.end(),
unApproveEvents.begin(),
unApproveEvents.end()
);
if (approveEvents.empty())
{
outputPosition(81, 10);
std::cout << "There are no storylines to display";
outputPosition(81, 11);
std::cout << "Press any key to go back!";
(void)_getch();
clearConsole();
printClosedBook();
printBookDecorations();
printSnakeSword();
printTeamLogo();
return;
}
printFullyOpenedBook();
outputPosition(81, 10);
std::cout << "Choose event that you want to remove:";
int selectedOption = 1;
char pressedKey = ' ';
while (pressedKey != (int)ARROW_KEYS::KEY_ENTER)
{
for (int i = 0; i < approveEvents.size(); i++)
{
if (i + 1 == selectedOption)
{
outputPosition(81, 12 + i * 2);
std::cout << "-> ";
}
else
{
outputPosition(81, 12 + i * 2);
std::cout << " ";
}
std::cout << approveEvents[i].title;
}
pressedKey = _getch();
switch (pressedKey)
{
case (int)ARROW_KEYS::KEY_UP:
selectedOption--;
if (selectedOption == 0)
{
selectedOption += 1;
}
break;
case (int)ARROW_KEYS::KEY_DOWN:
selectedOption++;
if (selectedOption == approveEvents.size() + 1)
{
selectedOption -= 1;
}
break;
case (int)ARROW_KEYS::KEY_ENTER:
clearConsole();
printFullyOpenedBook();
if (!eventManager->removeEvent(
&eventManager->eventList, approveEvents[__int64(selectedOption) - 1].title)
)
{
outputPosition(81, 20);
std::cout << "The event wasn't found";
}
return;
case (int)ARROW_KEYS::KEY_ESC:
// Return to main menu
clearConsole();
printClosedBook();
printBookDecorations();
printSnakeSword();
printTeamLogo();
return;
break;
}
}
if (_getch())
{
clearConsole();
printClosedBook();
printBookDecorations();
printSnakeSword();
printTeamLogo();
}
}
void displayEvent(const Event& e, bool approve, EventManager* eventManager)
{
DateManager dateManager;
printFullyOpenedBook();
outputPosition(81, 10);
std::cout << "Press ESC if you want to go back!";
switch (e.type)
{
case TypeOfEvent::UPRISING:
printFullyOpenedBook();
outputPosition(81, 12);
std::cout << "Title: " << e.title;
struct tm timeinfo;
localtime_s(&timeinfo, &e.timeOfCreation);
outputPosition(81, 14);
std::cout << "Time of creation: " << std::put_time(&timeinfo, "%x");
outputPosition(81, 16);
std::cout << "Type: Uprising";
outputPosition(81, 18);
std::cout << "Epoch: " << e.epochs[0];
if (e.period.size() == 2)
{
outputPosition(81, 21);
std::cout << "Start date: " << std::put_time(&e.period[0], "%x") << std::endl;
outputPosition(81, 23);
std::cout << "End date: " << std::put_time(&e.period[1], "%x") << std::endl;
outputPosition(81, 25);
std::cout << "Duration in days: " << dateManager.getDifference(
e.period[0], e.period[1]
) << std::endl;
outputPosition(81, 27);
std::cout << "Success: ";
switch (e.isItSuccessful)
{
case 0: std::cout << "No"; break;
case 1: std::cout << "Yes"; break;
}
outputPosition(81, 29);
std::cout << "Number of rebellions: " << e.numberOfRebelions;
outputPosition(81, 31);
std::cout << "Additional notes: ";
outputPosition(81, 32);
std::cout << e.additionalNotes;
}
else
{
outputPosition(81, 21);
std::cout << "Date: " << std::put_time(&e.period[0], "%x") << std::endl;
outputPosition(81, 23);
std::cout << "Success: ";
switch (e.isItSuccessful)
{
case 0: std::cout << "No"; break;
case 1: std::cout << "Yes"; break;
}
outputPosition(81, 25);
std::cout << "Number of rebellions: " << e.numberOfRebelions;
outputPosition(81, 27);
std::cout << "Additional notes: ";
outputPosition(81, 28);
std::cout << e.additionalNotes;
}
break;
case TypeOfEvent::WAR:
printFullyOpenedBook();
outputPosition(81, 12);
std::cout << "Title: " << e.title;
localtime_s(&timeinfo, &e.timeOfCreation);
outputPosition(81, 14);
std::cout << "Time of creation: " << std::put_time(&timeinfo, "%x");
outputPosition(81, 16);
std::cout << "Type: War";
outputPosition(81, 18);
std::cout << "Epoch: ";
for (size_t i = 0; i < e.epochs[0].size(); i++)
{
if (i != 0)
{
if (e.epochs[0][i - 1] == '>')
{
outputPosition(81, 19);
}
}
std::cout << e.epochs[0][i];
}
if (e.period.size() == 2)
{
outputPosition(81, 21);
std::cout << "Start date: " << std::put_time(&e.period[0], "%x") << std::endl;
outputPosition(81, 23);
std::cout << "End date: " << std::put_time(&e.period[1], "%x") << std::endl;
outputPosition(81, 25);
std::cout << "Duration in days: " << dateManager.getDifference(
e.period[0], e.period[1]
) << std::endl;
outputPosition(81, 27);
std::cout << "Participting countries: " << separate(e.participatingCountries);
outputPosition(81, 29);
std::cout << "Winner: " << e.winner;
outputPosition(81, 31);
std::cout << "Reason " << e.reason;
outputPosition(81, 33);
std::cout << "Rulers: " << separate(e.rulers);
outputPosition(81, 35);
std::cout << "Additional notes: ";
outputPosition(81, 36);
std::cout << e.additionalNotes;
}
else
{
outputPosition(81, 21);
std::cout << "Date: " << std::put_time(&e.period[0], "%x") << std::endl;
outputPosition(81, 23);
std::cout << "Participting countries: " << separate(e.participatingCountries);
outputPosition(81, 25);
std::cout << "Winner: " << e.winner;
outputPosition(81, 27);
std::cout << "Reason " << e.reason;
outputPosition(81, 29);
std::cout << "Rulers: " << separate(e.rulers);
outputPosition(81, 31);
std::cout << "Additional notes: ";
outputPosition(81, 32);
std::cout << e.additionalNotes;
}
break;
case TypeOfEvent::MOVEMENT:
printFullyOpenedBook();
outputPosition(81, 12);
std::cout << "Title: " << e.title;
localtime_s(&timeinfo, &e.timeOfCreation);
outputPosition(81, 14);
std::cout << "Time of creation: " << std::put_time(&timeinfo, "%x");
outputPosition(81, 16);
std::cout << "Type: Movement";
outputPosition(81, 18);
std::cout << "Epoch: ";
for (size_t i = 0; i < e.epochs[0].size(); i++)
{
if (i != 0)
{
if (e.epochs[0][i - 1] == '>')
{
outputPosition(81, 19);
}
}
std::cout << e.epochs[0][i];
}
if (e.period.size() == 2)
{
outputPosition(81, 21);
std::cout << "Start date: " << std::put_time(&e.period[0], "%x") << std::endl;
outputPosition(81, 23);
std::cout << "End date: " << std::put_time(&e.period[1], "%x") << std::endl;
outputPosition(81, 25);
std::cout << "Duration in days: " << dateManager.getDifference(
e.period[0], e.period[1]
) << std::endl;
outputPosition(81, 27);
std::cout << "How it started: " << e.howItStarted;
outputPosition(81, 29);
std::cout << "Ideas " << e.ideas;
outputPosition(81, 31);
std::cout << "Aims " << e.aims;
outputPosition(81, 33);
std::cout << "Representatives: " << separate(e.representatives);
outputPosition(81, 35);
std::cout << "Additional notes: ";
outputPosition(81, 36);
std::cout << e.additionalNotes;
}
else
{
outputPosition(81, 21);
std::cout << "Date: " << std::put_time(&e.period[0], "%x") << std::endl;
outputPosition(81, 23);
std::cout << "How it started: " << e.howItStarted;
outputPosition(81, 25);
std::cout << "Ideas " << e.ideas;
outputPosition(81, 27);
std::cout << "Aims " << e.aims;
outputPosition(81, 29);
std::cout << "Representatives: " << separate(e.representatives);
outputPosition(81, 31);
std::cout << "Additional notes: ";
outputPosition(81, 32);
std::cout << e.additionalNotes;
}
case TypeOfEvent::OTHER:
printFullyOpenedBook();
outputPosition(81, 12);
std::cout << "Title: " << e.title;
localtime_s(&timeinfo, &e.timeOfCreation);
outputPosition(81, 14);
std::cout << "Time of creation: " << std::put_time(&timeinfo, "%x");
outputPosition(81, 16);
std::cout << "Type: Other";
outputPosition(81, 18);
std::cout << "Epoch: ";
for (size_t i = 0; i < e.epochs[0].size(); i++)
{
if (i != 0)
{
if (e.epochs[0][i - 1] == '>')
{
outputPosition(81, 19);
}
}
std::cout << e.epochs[0][i];
}
if (e.period.size() == 2)
{
outputPosition(81, 21);
std::cout << "Start date: " << std::put_time(&e.period[0], "%x") << std::endl;
outputPosition(81, 23);
std::cout << "End date: " << std::put_time(&e.period[1], "%x") << std::endl;
outputPosition(81, 25);
std::cout << "Duration in days: " << dateManager.getDifference(
e.period[0], e.period[1]
) << std::endl;
outputPosition(81, 27);
std::cout << "Additional notes: ";
outputPosition(81, 28);
std::cout << e.additionalNotes;
}
else
{
outputPosition(81, 21);
std::cout << "Date: " << std::put_time(&e.period[0], "%x") << std::endl;
outputPosition(81, 23);
std::cout << "Additional notes: ";
outputPosition(81, 24);
std::cout << e.additionalNotes;
}
break;
}
if (approve)
{
short xCord;
switch (e.type)
{
case TypeOfEvent::UPRISING:
xCord = 26;
break;
case TypeOfEvent::WAR:
xCord = 30;
break;
case TypeOfEvent::MOVEMENT:
xCord = 30;
break;
case TypeOfEvent::OTHER:
xCord = 22;
break;
default:
xCord = 30;
break;
}
std::vector<std::string> options = {
"Approve",
"Disapprove (deleate)"
};
char pressedKey = ' ';
int selectedOption = 1;
outputPosition(81, xCord);
std::cout << "Choose option:";
while (pressedKey != (int)ARROW_KEYS::KEY_ENTER)
{
for (int i = 0; i < options.size(); i++)
{
if (i + 1 == selectedOption)
{
outputPosition(81, xCord + i + 1);
std::cout << "-> ";
}
else
{
outputPosition(81, xCord + i + 1);
std::cout << " ";
}
std::cout << options[i] << std::endl << std::endl;
}
pressedKey = _getch();
switch (pressedKey)
{
case (int)ARROW_KEYS::KEY_UP:
selectedOption--;
if (selectedOption == 0)
{
selectedOption += 1;
}
break;
case (int)ARROW_KEYS::KEY_DOWN:
selectedOption++;
if (selectedOption == options.size() + 1)
{
selectedOption -= 1;
}
break;
case (int)ARROW_KEYS::KEY_ENTER:
switch (selectedOption)
{
case 1:
eventManager->approveEvent(e.title);
break;
case 2:
eventManager->removeEvent(&eventManager->eventList, e.title);
break;
}
}
}
}
else
{
(void)_getch();
clearConsole();
printClosedBook();
printBookDecorations();
printSnakeSword();
printTeamLogo();
}
}
void printEventInfo(const std::vector<Event> events, int output)
{
int selectedOption = 1;
char pressedKey = ' ';
while (pressedKey != (int)ARROW_KEYS::KEY_ENTER)
{
for (int i = 0; i < events.size(); i++)
{
if (i + 1 == selectedOption)
{
outputPosition(81, 10 + i * 2);
std::cout << "-> ";
}
else
{
outputPosition(81, 10 + i * 2);
std::cout << " ";
}
if (output == 1) {
for (int j = 0; j < events[i].period.size(); j++)
{
outputPosition(84, 10 + i * 2);
std::cout << events[i].title << " - " << std::put_time(&events[i].period[j], "%x") << std::endl;
}
}
else if (output == 2)
{
for (int i = 0; i < events.size(); i++)
{
for (int j = 0; j < events[i].period.size(); j++)
{
outputPosition(84, 10 + i * 2);
std::cout << std::put_time(&events[i].period[j], "%x") << " - "
<< events[i].title;
}
}
}
}
pressedKey = _getch();
switch (pressedKey)
{
case (int)ARROW_KEYS::KEY_UP:
selectedOption--;
if (selectedOption == 0)
{
selectedOption += 1;
}
break;
case (int)ARROW_KEYS::KEY_DOWN:
selectedOption++;
if (selectedOption == events.size() + 1)
{
selectedOption -= 1;
}
break;
case (int)ARROW_KEYS::KEY_ENTER:
displayEvent(events[__int64(selectedOption) - 1]);
}
}
}
void displayAllEvents(EventManager* eventManager, int sorting, int& type, bool getAllEvents)
{
std::vector<Event> allEvents = eventManager->getAllEvents(true);
if (getAllEvents)
{
std::vector<Event> events = eventManager->getAllEvents(false);
allEvents.insert(allEvents.end(), events.begin(), events.end());
}
if (allEvents.empty())
{
outputPosition(81, 10);
std::cout << "There are no events to display";
outputPosition(81, 11);
std::cout << "Press any key to go back!";
(void)_getch();
clearConsole();
printClosedBook();
printBookDecorations();
printSnakeSword();
printTeamLogo();
return;
}
int output = 1;
if (sorting == 1 && type == 1)
{
allEvents = eventManager->sortAndGetAllEventsByTitle(allEvents);
}
else if (sorting == 1 && type == 2)
{
allEvents = eventManager->sortAndGetAllEventsByDate(allEvents);
output++;
}
else if (sorting == 1 && type == 3)
{
allEvents = eventManager->sortAndGetAllEventsByTimeOfCreation(allEvents);
}
else if (sorting == 2 && type == 1)
{
allEvents = eventManager->sortAndGetAllEventsByTitle(allEvents);
reverse(allEvents.begin(), allEvents.end());
}
else if (sorting == 2 && type == 2)
{
allEvents = eventManager->sortAndGetAllEventsByDate(allEvents);
reverse(allEvents.begin(), allEvents.end());
output++;
}
else if (sorting == 2 && type == 3)
{
allEvents = eventManager->sortAndGetAllEventsByTimeOfCreation(allEvents);
reverse(allEvents.begin(), allEvents.end());
}
printEventInfo(allEvents, output);
}
void chooseSorting(EventManager* eventManager, int type, bool getAllEvents)
{
printFullyOpenedBook();
outputPosition(81, 10);
std::cout << "How do you want to sort the events?" << std::endl;
int selectedOption = 1;
char pressedKey = ' ';
const std::vector<std::string> y�arSortingOptions =
{
"Ascending",
"Descending",
};
const std::vector<std::string> titleSortingOptions =
{
"A -> Z",
"Z -> A",
};
const std::vector<std::string> timeAddedSortingOptions =
{
"Newer -> Older",
"Older -> Newer",
};
while (pressedKey != (int)ARROW_KEYS::KEY_ENTER)
{
if (type == 1)
{
for (int i = 0; i < titleSortingOptions.size(); i++)
{
if (i + 1 == selectedOption)
{
outputPosition(81, 12 + i * 2);
std::cout << "-> ";
}
else
{
outputPosition(81, 12 + i * 2);
std::cout << " ";
}
std::cout << titleSortingOptions[i] << std::endl << std::endl;
}
}
else if (type == 2)
{
for (int i = 0; i < y�arSortingOptions.size(); i++)
{
if (i + 1 == selectedOption)
{
outputPosition(81, 12 + i * 2);
std::cout << "-> ";
}
else
{
outputPosition(81, 12 + i * 2);
std::cout << " ";
}
std::cout << y�arSortingOptions[i] << std::endl << std::endl;
}
}
else if (type == 3)
{
for (int i = 0; i < timeAddedSortingOptions.size(); i++)
{
if (i + 1 == selectedOption)
{
outputPosition(81, 12 + i * 2);
std::cout << "-> ";
}
else
{
outputPosition(81, 12 + i * 2);
std::cout << " ";
}
std::cout << timeAddedSortingOptions[i] << std::endl << std::endl;
}
}
pressedKey = _getch();
switch (pressedKey)
{
case (int)ARROW_KEYS::KEY_UP:
selectedOption--;
if (selectedOption == 0)
{
selectedOption += 1;
}
break;
case (int)ARROW_KEYS::KEY_DOWN:
selectedOption++;
if (selectedOption == y�arSortingOptions.size() + 1)
{
selectedOption -= 1;
}
break;
case (int)ARROW_KEYS::KEY_ENTER:
switch (selectedOption)
{
case 1:
printFullyOpenedBook();
displayAllEvents(eventManager, 1, type, getAllEvents);
break;
case 2:
printFullyOpenedBook();
displayAllEvents(eventManager, 2, type, getAllEvents);
break;
}
}
}
}
void printBy(EventManager* eventManager, bool getAllEvents)
{
outputPosition(81, 10);
std::cout << "How do you want to sort the events?" << std::endl;
int selectedOption = 1;
char pressedKey = ' ';
const std::vector<std::string> printByOptions =
{
"By title",
"By year, month and day",
"By time added"
};
while (pressedKey != (int)ARROW_KEYS::KEY_ENTER)
{
for (int i = 0; i < printByOptions.size(); i++)
{
if (i + 1 == selectedOption)
{
outputPosition(81, 12 + i * 2);
std::cout << "-> ";
}
else
{
outputPosition(81, 12 + i * 2);
std::cout << " ";
}
std::cout << printByOptions[i] << std::endl << std::endl;
}
pressedKey = _getch();
switch (pressedKey)
{
case (int)ARROW_KEYS::KEY_UP:
selectedOption--;
if (selectedOption == 0)
{
selectedOption += 1;
}
break;
case (int)ARROW_KEYS::KEY_DOWN:
selectedOption++;
if (selectedOption == printByOptions.size() + 1)
{
selectedOption -= 1;
}
break;
case (int)ARROW_KEYS::KEY_ENTER:
switch (selectedOption)
{
case 1:
printFullyOpenedBook();
chooseSorting(eventManager, 1, getAllEvents);
break;
case 2:
printFullyOpenedBook();
chooseSorting(eventManager, 2, getAllEvents);
break;
case 3:
printFullyOpenedBook();
chooseSorting(eventManager, 3, getAllEvents);
break;
}
case (int)ARROW_KEYS::KEY_ESC:
return;
}
}
}
void printAsMap(EventManager* eventManager, bool getAllEvents)
{
std::vector<Event> allEvents = eventManager->getAllEvents(true);
if (getAllEvents)
{
std::vector<Event> unApproveEvents = eventManager->getAllEvents(false);
allEvents.insert(allEvents.end(), unApproveEvents.begin(), unApproveEvents.end());
}
if (allEvents.empty())
{
outputPosition(81, 10);
std::cout << "There are no events to display";
outputPosition(81, 12);
std::cout << "Press Enter to go back!";
(void)_getch();
return;
}
int selectedOption = 1;
char pressedKey = ' ';
while (pressedKey != (int)ARROW_KEYS::KEY_ENTER)
{
for (int i = 0; i < allEvents.size(); i++)
{
if (i + 1 == selectedOption)
{
outputPosition(81, 10 + i * 2);
std::cout << "-> ";
}
else
{
outputPosition(81, 10 + i * 2);
std::cout << " ";
}
for (int j = 0; j < allEvents[i].period.size(); j++)
{
outputPosition(84, 10 + i * 2);
std::cout << allEvents[i].title << " - "
<< std::put_time(&allEvents[i].period[j], "%x") << std::endl;
}
}
pressedKey = _getch();
switch (pressedKey)
{
case (int)ARROW_KEYS::KEY_UP:
selectedOption--;
if (selectedOption == 0)
{
selectedOption += 1;
}
break;
case (int)ARROW_KEYS::KEY_DOWN:
selectedOption++;
if (selectedOption == allEvents.size() + 1)
{
selectedOption -= 1;
}
break;
case (int)ARROW_KEYS::KEY_ENTER:
printMapPopUp();
printBulgarianMap();
outputPosition(
(allEvents[__int64(selectedOption) - 1].coordinates.X),
(allEvents[__int64(selectedOption) - 1].coordinates.Y)
);
std::cout << char(254);
if (_getch())
{
return;
clearConsole();
printClosedBook();
printBookDecorations();
printSnakeSword();
printTeamLogo();
}
}
}
}
void editEvent(EventManager* eventManager)
{
std::vector<Event> approveEvents = eventManager->getAllEvents(1);
std::vector<Event> unApproveEvents = eventManager->getAllEvents(0);
approveEvents.insert(
approveEvents.end(),
unApproveEvents.begin(),
unApproveEvents.end()
);
if (approveEvents.empty())
{
outputPosition(81, 10);
std::cout << "There are no events to display";
outputPosition(81, 12);
std::cout << "Press Enter to go back!";
(void)_getch();
return;
}
int selectedOption = 1;
char pressedKey = ' ';
outputPosition(81, 10);
std::cout << "Choose the event you want to edit!";
while (pressedKey != (int)ARROW_KEYS::KEY_ENTER)
{
for (int i = 0; i < approveEvents.size(); i++)
{
if (i + 1 == selectedOption)
{
outputPosition(81, 12 + i * 2);
std::cout << "-> ";
}
else
{
outputPosition(81, 12 + i * 2);
std::cout << " ";
}
for (int j = 0; j < approveEvents[i].period.size(); j++)
{
outputPosition(84, 12 + i * 2);
std::cout << approveEvents[i].title << " - "
<< std::put_time(&approveEvents[i].period[j], "%x") << std::endl;
}
}
pressedKey = _getch();
switch (pressedKey)
{
case (int)ARROW_KEYS::KEY_UP:
selectedOption--;
if (selectedOption == 0)
{
selectedOption += 1;
}
break;
case (int)ARROW_KEYS::KEY_DOWN:
selectedOption++;
if (selectedOption == approveEvents.size() + 1)
{
selectedOption -= 1;
}
break;
case (int)ARROW_KEYS::KEY_ENTER:
std::vector<std::string> uprisingOptions
{
"Title",
"Date",
"Coordinates",
"Organizers",
"Number of rebellions",
"Success",
};
std::vector<std::string> warOptions
{
"Title",
"Date",
"Coordinates",
"Participating countries",
"Winner",
"Reason",
"Rulers",
};
std::vector<std::string> movementOptions
{
"Title",
"Date",
"Coordinates",
"How it started",
"Ideas",
"Aims",
"Representatives",
};
std::vector<std::string> otherOptions
{
"Title",
"Date",
"Coordinates",
};
if ((approveEvents[__int64(selectedOption) - 1].type == TypeOfEvent::UPRISING))
{
printFullyOpenedBook();
outputPosition(81, 10);
std::cout << "What do you want to edit?";
std::string title;
std::string period;
std::string organizers;
bool isItSuccessful = true;
int rebelions;
const std::vector<std::string> successOfEventOptions = {
"Successful",
"Unsuccessful"
};
short x = 56;
short y = 20;
char key;
int selectedOption1 = 1;
char pressedKey1 = ' ';
while (pressedKey1 != (int)ARROW_KEYS::KEY_ENTER)
{
for (int i = 0; i < uprisingOptions.size(); i++)
{
if (i + 1 == selectedOption1)
{
outputPosition(81, 12 + i * 2);
std::cout << "-> ";
}
else
{
outputPosition(81, 12 + i * 2);
std::cout << " ";
}
outputPosition(84, 12 + i * 2);
std::cout << uprisingOptions[i];
}
pressedKey1 = _getch();
switch (pressedKey1)
{
case (int)ARROW_KEYS::KEY_UP:
selectedOption1--;
if (selectedOption1 == 0)
{
selectedOption1 += 1;
}
break;
case (int)ARROW_KEYS::KEY_DOWN:
selectedOption1++;
if (selectedOption1 == uprisingOptions.size() + 1)
{
selectedOption1 -= 1;
}
break;
case (int)ARROW_KEYS::KEY_ENTER:
switch (selectedOption1)
{
case 1:
printFullyOpenedBook();
outputPosition(81, 10);
std::cout << "Enter the title of the event: " << std::endl;
outputPosition(81, 12);
getline(std::cin, title);
while (title.empty())
{
outputPosition(81, 12);
std::cout << "Title can not be empty, please enter again: ";
outputPosition(81, 14);
getline(std::cin, title);
}
outputPosition(81, 14);
std::cout << "Changes saved successfully!";
eventManager->setSingleValueField(
(eventManager->getEventWithName(
approveEvents[__int64(selectedOption) - 1].title
))->title, title);
break;
case 2:
printFullyOpenedBook();
outputPosition(81, 10);
std::cout << "Enter the starting and ending year and date";
outputPosition(81, 12);
std::cout << "Example - (20 apr 1876, 15 may 1876)";
outputPosition(81, 14);
getline(std::cin, period);
outputPosition(81, 16);
std::cout << "Changes saved successfully!";
while (!checkDatesValidation(period))
{
outputPosition(81, 14);
std::cout << "The data you've entered is incorrect!";
outputPosition(81, 16);
std::cout << "Please enter a date/s - ex(24 apr 809, 27 apr 810)";
outputPosition(81, 18);
getline(std::cin, period);
outputPosition(81, 20);
std::cout << "Changes saved successfully!";
}
DateManager dateManager;
eventManager->setMultiValueField((
eventManager->getEventWithName(
approveEvents[__int64(selectedOption) - 1].title
))->period,
dateManager.converVectorOfStringsToVectorOfDate(
separateDates(period)
));
break;
case 3:
printFullyOpenedBook();
printMapPopUp();
printBulgarianMap();
outputPosition(x, y);
std::cout << char(254);
while ((key = _getch()) != (char)ARROW_KEYS::KEY_ENTER)
{
switch (key)
{
case (char)ARROW_KEYS::KEY_UP:
outputPosition(x, y);
std::cout << " ";
y -= 1;
outputPosition(x, y);
std::cout << char(254);
break;
case (char)ARROW_KEYS::KEY_DOWN:
outputPosition(x, y);
std::cout << " ";
y += 1;
outputPosition(x, y);
std::cout << char(254);
break;
case (char)ARROW_KEYS::KEY_LEFT:
outputPosition(x, y);
std::cout << " ";
x += 1;
outputPosition(x, y);
std::cout << char(254);
break;
case (char)ARROW_KEYS::KEY_RIGHT:
outputPosition(x, y);
std::cout << " ";
x -= 1;
outputPosition(x, y);
std::cout << char(254);
break;
case (char)ARROW_KEYS::KEY_ENTER:
printFullyOpenedBook();
break;
}
}
eventManager->setSingleValueField(
(eventManager->getEventWithName(
approveEvents[__int64(selectedOption) - 1].title)
)->coordinates.X, (short)x);
eventManager->setSingleValueField(
(eventManager->getEventWithName(
approveEvents[__int64(selectedOption) - 1].title)
)->coordinates.Y, (short)y);
break;
case 4:
printFullyOpenedBook();
outputPosition(81, 10);
std::cout << "Enter the organizers of the event: " << std::endl;
outputPosition(81, 12);
getline(std::cin, organizers);
while (organizers.empty())
{
outputPosition(81, 12);
std::cout << "Organizers can not be empty, please enter again: ";
outputPosition(81, 14);
getline(std::cin, organizers);
}
outputPosition(81, 14);
std::cout << "Changes saved successfully!";
eventManager->setMultiValueField(
(eventManager->getEventWithName(
approveEvents[__int64(selectedOption) - 1].title)
)->organizers, { organizers });
break;
case 5:
printFullyOpenedBook();
outputPosition(81, 10);
std::cout << "Enter the numbers of rebellions: " << std::endl;
outputPosition(81, 12);
std::cin >> rebelions;
outputPosition(81, 14);
std::cout << "Changes saved successfully!";
eventManager->setSingleValueField(
(eventManager->getEventWithName(
approveEvents[__int64(selectedOption) - 1].title)
)->numberOfRebelions, rebelions);
break;
case 6:
printFullyOpenedBook();
outputPosition(81, 10);
std::cout << "Is the event successful?";
int selectedOption = 1;
char pressedKey = ' ';
while (pressedKey != (int)ARROW_KEYS::KEY_ENTER)
{
for (int i = 0; i < successOfEventOptions.size(); i++)
{
if (i + 1 == selectedOption)
{
outputPosition(81, 12 + i * 2);
std::cout << "-> ";
}
else
{
outputPosition(81, 12 + i * 2);
std::cout << " ";
}
std::cout << successOfEventOptions[i]
<< std::endl << std::endl;
}
pressedKey = _getch();
switch (pressedKey)
{
case (int)ARROW_KEYS::KEY_UP:
selectedOption--;
if (selectedOption == 0)
{
selectedOption += 1;
}
break;
case (int)ARROW_KEYS::KEY_DOWN:
selectedOption++;
if (selectedOption == successOfEventOptions.size() + 1)
{
selectedOption -= 1;
}
break;
case (int)ARROW_KEYS::KEY_ENTER:
switch (selectedOption)
{
case 1:
isItSuccessful = true;
break;
case 2:
isItSuccessful = false;
break;
}
}
}
eventManager->setSingleValueField(
(eventManager->getEventWithName(
approveEvents[__int64(selectedOption) - 1].title)
)->isItSuccessful, isItSuccessful);
break;
}
}
}
}
else if ((approveEvents[__int64(selectedOption) - 1].type == TypeOfEvent::WAR))
{
printFullyOpenedBook();
outputPosition(81, 10);
std::cout << "What do you want to edit?";
std::string title;
std::string period;
std::string participatingCountries;
std::string winner;
std::string reasons;
std::string rulers;
short x = 56;
short y = 20;
char key;
int selectedOption1 = 1;
char pressedKey1 = ' ';
while (pressedKey1 != (int)ARROW_KEYS::KEY_ENTER)
{
for (int i = 0; i < warOptions.size(); i++)
{
if (i + 1 == selectedOption1)
{
outputPosition(81, 12 + i * 2);
std::cout << "-> ";
}
else
{
outputPosition(81, 12 + i * 2);
std::cout << " ";
}
outputPosition(84, 12 + i * 2);
std::cout << warOptions[i];
}
pressedKey1 = _getch();
switch (pressedKey1)
{
case (int)ARROW_KEYS::KEY_UP:
selectedOption1--;
if (selectedOption1 == 0)
{
selectedOption1 += 1;
}
break;
case (int)ARROW_KEYS::KEY_DOWN:
selectedOption1++;
if (selectedOption1 == approveEvents.size() + 1)
{
selectedOption1 -= 1;
}
break;
case (int)ARROW_KEYS::KEY_ENTER:
switch (selectedOption1) {
case 1:
printFullyOpenedBook();
outputPosition(81, 10);
std::cout << "Enter the title of the event: " << std::endl;
outputPosition(81, 12);
getline(std::cin, title);
while (title.empty())
{
outputPosition(81, 12);
std::cout << "Title can not be empty, please enter again: ";
outputPosition(81, 14);
getline(std::cin, title);
}
outputPosition(81, 14);
std::cout << "Changes saved successfully!";
eventManager->setSingleValueField(
(eventManager->getEventWithName(
approveEvents[__int64(selectedOption) - 1].title)
)->title, title);
break;
case 2:
printFullyOpenedBook();
outputPosition(81, 10);
std::cout << "Enter the starting and ending year and date";
outputPosition(81, 12);
std::cout << "Example - (20 apr 1876, 15 may 1876)";
outputPosition(81, 14);
getline(std::cin, period);
outputPosition(81, 16);
std::cout << "Changes saved successfully!";
while (!checkDatesValidation(period))
{
outputPosition(81, 14);
std::cout << "The data you've entered is incorrect!";
outputPosition(81, 16);
std::cout << "Please enter a date/s - ex(24 apr 809, 27 apr 810)";
outputPosition(81, 18);
getline(std::cin, period);
outputPosition(81, 20);
std::cout << "Changes saved successfully!";
}
DateManager dateManager;
eventManager->setMultiValueField(
(eventManager->getEventWithName(approveEvents[__int64(
selectedOption) - 1].title)
)->period,
dateManager.converVectorOfStringsToVectorOfDate(
separateDates(period))
);
break;
case 3:
printFullyOpenedBook();
printMapPopUp();
printBulgarianMap();
outputPosition(x, y);
std::cout << char(254);
while ((key = _getch()) != (char)ARROW_KEYS::KEY_ENTER)
{
switch (key)
{
case (char)ARROW_KEYS::KEY_UP:
outputPosition(x, y);
std::cout << " ";
y -= 1;
outputPosition(x, y);
std::cout << char(254);
break;
case (char)ARROW_KEYS::KEY_DOWN:
outputPosition(x, y);
std::cout << " ";
y += 1;
outputPosition(x, y);
std::cout << char(254);
break;
case (char)ARROW_KEYS::KEY_LEFT:
outputPosition(x, y);
std::cout << " ";
x += 1;
outputPosition(x, y);
std::cout << char(254);
break;
case (char)ARROW_KEYS::KEY_RIGHT:
outputPosition(x, y);
std::cout << " ";
x -= 1;
outputPosition(x, y);
std::cout << char(254);
break;
case (char)ARROW_KEYS::KEY_ENTER:
printFullyOpenedBook();
break;
}
}
eventManager->setSingleValueField(
(eventManager->getEventWithName(
approveEvents[__int64(selectedOption) - 1].title)
)->coordinates.X, (short)x);
eventManager->setSingleValueField(
(eventManager->getEventWithName(
approveEvents[__int64(selectedOption) - 1].title)
)->coordinates.Y, (short)y);
break;
case 4:
printFullyOpenedBook();
outputPosition(81, 10);
std::cout << "Enter the participating countries of the event: " << std::endl;
outputPosition(81, 12);
getline(std::cin, participatingCountries);
while (participatingCountries.empty())
{
outputPosition(81, 12);
std::cout << "Participating countries can not be empty, please enter again: ";
outputPosition(81, 14);
getline(std::cin, participatingCountries);
}
outputPosition(81, 14);
std::cout << "Changes saved successfully!";
eventManager->setMultiValueField((
eventManager->getEventWithName(
approveEvents[__int64(selectedOption) - 1].title
))->participatingCountries,
{ participatingCountries });
break;
case 5:
printFullyOpenedBook();
outputPosition(81, 10);
std::cout << "Enter the winner of the event: "
<< std::endl;
outputPosition(81, 12);
getline(std::cin, winner);
while (winner.empty())
{
outputPosition(81, 12);
std::cout << "Winner can not be empty, please enter again: ";
outputPosition(81, 14);
getline(std::cin, winner);
}
outputPosition(81, 14);
std::cout << "Changes saved successfully!";
eventManager->setSingleValueField((
eventManager->getEventWithName(
approveEvents[__int64(selectedOption) - 1].title
))->winner, winner);
break;
case 6:
printFullyOpenedBook();
outputPosition(81, 10);
std::cout << "Enter the reasons of the event: " <<
std::endl;
outputPosition(81, 12);
getline(std::cin, reasons);
while (reasons.empty())
{
outputPosition(81, 12);
std::cout << "Reasons can not be empty, please enter again: ";
outputPosition(81, 14);
getline(std::cin, reasons);
}
outputPosition(81, 14);
std::cout << "Changes saved successfully!";
eventManager->setSingleValueField((
eventManager->getEventWithName(
approveEvents[__int64(selectedOption) - 1].title
))->reason, reasons);
break;
case 7:
printFullyOpenedBook();
outputPosition(81, 10);
std::cout << "Enter the rulers of the event: "
<< std::endl;
outputPosition(81, 12);
getline(std::cin, rulers);
while (rulers.empty())
{
outputPosition(81, 12);
std::cout << "Rulers can not be empty, please enter again: ";
outputPosition(81, 14);
getline(std::cin, rulers);
}
outputPosition(81, 14);
std::cout << "Changes saved successfully!";
eventManager->setSingleValueField((
eventManager->getEventWithName(
approveEvents[__int64(selectedOption) - 1].title
))->rulers, { rulers });
break;
}
}
}
}
else if ((
approveEvents[__int64(selectedOption) - 1].type == TypeOfEvent::MOVEMENT))
{
printFullyOpenedBook();
outputPosition(81, 10);
std::cout << "What do you want to edit?";
std::string title;
std::string period;
std::string howItStarted;
std::string ideas;
std::string aims;
std::string representatives;
short x = 56;
short y = 20;
char key;
int selectedOption1 = 1;
char pressedKey1 = ' ';
while (pressedKey1 != (int)ARROW_KEYS::KEY_ENTER)
{
for (int i = 0; i < movementOptions.size(); i++)
{
if (i + 1 == selectedOption1)
{
outputPosition(81, 12 + i * 2);
std::cout << "-> ";
}
else
{
outputPosition(81, 12 + i * 2);
std::cout << " ";
}
outputPosition(84, 12 + i * 2);
std::cout << movementOptions[i];
}
pressedKey1 = _getch();
switch (pressedKey1)
{
case (int)ARROW_KEYS::KEY_UP:
selectedOption1--;
if (selectedOption1 == 0)
{
selectedOption1 += 1;
}
break;
case (int)ARROW_KEYS::KEY_DOWN:
selectedOption1++;
if (selectedOption1 == approveEvents.size() + 1)
{
selectedOption1 -= 1;
}
break;
case (int)ARROW_KEYS::KEY_ENTER:
switch (selectedOption1)
{
case 1:
printFullyOpenedBook();
outputPosition(81, 10);
std::cout << "Enter the title of the event: "
<< std::endl;
outputPosition(81, 12);
getline(std::cin, title);
while (title.empty())
{
outputPosition(81, 12);
std::cout << "Title can not be empty, please enter again: ";
outputPosition(81, 14);
getline(std::cin, title);
}
outputPosition(81, 14);
std::cout << "Changes saved successfully!";
eventManager->setSingleValueField(
(eventManager->getEventWithName(
approveEvents[__int64(selectedOption) - 1].title
))->title, title);
break;
case 2:
printFullyOpenedBook();
outputPosition(81, 10);
std::cout << "Enter the starting and ending year and date";
outputPosition(81, 12);
std::cout << "Example - (20 apr 1876, 15 may 1876)";
outputPosition(81, 14);
getline(std::cin, period);
outputPosition(81, 16);
std::cout << "Changes saved successfully!";
while (!checkDatesValidation(period))
{
outputPosition(81, 14);
std::cout << "The data you've entered is incorrect!";
outputPosition(81, 16);
std::cout << "Please enter a date/s - ex(24 apr 809, 27 apr 810)";
outputPosition(81, 18);
getline(std::cin, period);
outputPosition(81, 20);
std::cout << "Changes saved successfully!";
}
DateManager dateManager;
eventManager->setMultiValueField((
eventManager->getEventWithName(
approveEvents[__int64(selectedOption) - 1].title)
)->period,
dateManager.converVectorOfStringsToVectorOfDate(
separateDates(period)
)
);
break;
case 3:
printFullyOpenedBook();
printMapPopUp();
printBulgarianMap();
outputPosition(x, y);
std::cout << char(254);
while ((key = _getch()) != (char)ARROW_KEYS::KEY_ENTER)
{
switch (key)
{
case (char)ARROW_KEYS::KEY_UP:
outputPosition(x, y);
std::cout << " ";
y -= 1;
outputPosition(x, y);
std::cout << char(254);
break;
case (char)ARROW_KEYS::KEY_DOWN:
outputPosition(x, y);
std::cout << " ";
y += 1;
outputPosition(x, y);
std::cout << char(254);
break;
case (char)ARROW_KEYS::KEY_LEFT:
outputPosition(x, y);
std::cout << " ";
x += 1;
outputPosition(x, y);
std::cout << char(254);
break;
case (char)ARROW_KEYS::KEY_RIGHT:
outputPosition(x, y);
std::cout << " ";
x -= 1;
outputPosition(x, y);
std::cout << char(254);
break;
case (char)ARROW_KEYS::KEY_ENTER:
printFullyOpenedBook();
break;
}
}
eventManager->setSingleValueField((
eventManager->getEventWithName(
approveEvents[__int64(selectedOption) - 1].title)
)->coordinates.X, (short)x);
eventManager->setSingleValueField((
eventManager->getEventWithName(
approveEvents[__int64(selectedOption) - 1].title)
)->coordinates.Y, (short)y);
break;
case 4:
printFullyOpenedBook();
outputPosition(81, 10);
std::cout << "Enter the way the event started: " << std::endl;
outputPosition(81, 12);
getline(std::cin, howItStarted);
while (howItStarted.empty())
{
outputPosition(81, 12);
std::cout << "The way the event started can not be empty, please enter again: ";
outputPosition(81, 14);
getline(std::cin, howItStarted);
}
outputPosition(81, 14);
std::cout << "Changes saved successfully!";
eventManager->setSingleValueField((
eventManager->getEventWithName(
approveEvents[__int64(selectedOption) - 1].title)
)->howItStarted, howItStarted);
break;
case 5:
printFullyOpenedBook();
outputPosition(81, 10);
std::cout << "Enter the ideas of the event: "
<< std::endl;
outputPosition(81, 12);
getline(std::cin, ideas);
while (ideas.empty())
{
outputPosition(81, 12);
std::cout << "The ideas can not be empty, please enter again: ";
outputPosition(81, 14);
getline(std::cin, ideas);
}
outputPosition(81, 14);
std::cout << "Changes saved successfully!";
eventManager->setSingleValueField((
eventManager->getEventWithName(
approveEvents[__int64(selectedOption) - 1].title)
)->ideas, ideas);
break;
case 6:
printFullyOpenedBook();
outputPosition(81, 10);
std::cout << "Enter the aims of the event: "
<< std::endl;
outputPosition(81, 12);
getline(std::cin, aims);
while (aims.empty())
{
outputPosition(81, 12);
std::cout << "The aims can not be empty, please enter again: ";
outputPosition(81, 14);
getline(std::cin, aims);
}
outputPosition(81, 14);
std::cout << "Changes saved successfully!";
eventManager->setSingleValueField((
eventManager->getEventWithName(
approveEvents[__int64(selectedOption) - 1].title)
)->aims, aims);
break;
case 7:
printFullyOpenedBook();
outputPosition(81, 10);
std::cout << "Enter the representatives of the event: "
<< std::endl;
outputPosition(81, 12);
getline(std::cin, representatives);
while (representatives.empty())
{
outputPosition(81, 12);
std::cout << "The representatives can not be empty, please enter again: ";
outputPosition(81, 14);
getline(std::cin, representatives);
}
outputPosition(81, 14);
std::cout << "Changes saved successfully!";
eventManager->setSingleValueField((
eventManager->getEventWithName(
approveEvents[__int64(selectedOption) - 1].title)
)->representatives, { representatives });
break;
}
}
}
}
else if ((
approveEvents[__int64(selectedOption) - 1].type == TypeOfEvent::OTHER
))
{
printFullyOpenedBook();
outputPosition(81, 10);
std::cout << "What do you want to edit?";
std::string title;
std::string period;
short x = 56;
short y = 20;
char key;
int selectedOption1 = 1;
char pressedKey1 = ' ';
while (pressedKey1 != (int)ARROW_KEYS::KEY_ENTER)
{
for (int i = 0; i < movementOptions.size(); i++)
{
if (i + 1 == selectedOption1)
{
outputPosition(81, 12 + i * 2);
std::cout << "-> ";
}
else
{
outputPosition(81, 12 + i * 2);
std::cout << " ";
}
outputPosition(84, 12 + i * 2);
std::cout << movementOptions[i];
}
pressedKey1 = _getch();
switch (pressedKey1)
{
case (int)ARROW_KEYS::KEY_UP:
selectedOption1--;
if (selectedOption1 == 0)
{
selectedOption1 += 1;
}
break;
case (int)ARROW_KEYS::KEY_DOWN:
selectedOption1++;
if (selectedOption1 == approveEvents.size() + 1)
{
selectedOption1 -= 1;
}
break;
case (int)ARROW_KEYS::KEY_ENTER:
switch (selectedOption1)
{
case 1:
printFullyOpenedBook();
outputPosition(81, 10);
std::cout << "Enter the title of the event: "
<< std::endl;
outputPosition(81, 12);
getline(std::cin, title);
while (title.empty())
{
outputPosition(81, 12);
std::cout << "Title can not be empty, please enter again: ";
outputPosition(81, 14);
getline(std::cin, title);
}
outputPosition(81, 14);
std::cout << "Changes saved successfully!";
eventManager->setSingleValueField((
eventManager->getEventWithName(
approveEvents[__int64(selectedOption) - 1].title)
)->title, title);
break;
case 2:
printFullyOpenedBook();
outputPosition(81, 10);
std::cout << "Enter the starting and ending year and date";
outputPosition(81, 12);
std::cout << "Example - (20 apr 1876, 15 may 1876)";
outputPosition(81, 14);
getline(std::cin, period);
outputPosition(81, 16);
std::cout << "Changes saved successfully!";
while (!checkDatesValidation(period))
{
outputPosition(81, 14);
std::cout << "The data you've entered is incorrect!";
outputPosition(81, 16);
std::cout << "Please enter a date/s - ex(24 apr 809, 27 apr 810)";
outputPosition(81, 18);
getline(std::cin, period);
outputPosition(81, 20);
std::cout << "Changes saved successfully!";
}
DateManager dateManager;
eventManager->setMultiValueField((
eventManager->getEventWithName(
approveEvents[__int64(selectedOption) - 1].title)
)->period,
dateManager.converVectorOfStringsToVectorOfDate(
separateDates(period)
)
);
break;
case 3:
printFullyOpenedBook();
printMapPopUp();
printBulgarianMap();
outputPosition(x, y);
std::cout << char(254);
while ((key = _getch()) != (char)ARROW_KEYS::KEY_ENTER)
{
switch (key)
{
case (char)ARROW_KEYS::KEY_UP:
outputPosition(x, y);
std::cout << " ";
y -= 1;
outputPosition(x, y);
std::cout << char(254);
break;
case (char)ARROW_KEYS::KEY_DOWN:
outputPosition(x, y);
std::cout << " ";
y += 1;
outputPosition(x, y);
std::cout << char(254);
break;
case (char)ARROW_KEYS::KEY_LEFT:
outputPosition(x, y);
std::cout << " ";
x += 1;
outputPosition(x, y);
std::cout << char(254);
break;
case (char)ARROW_KEYS::KEY_RIGHT:
outputPosition(x, y);
std::cout << " ";
x -= 1;
outputPosition(x, y);
std::cout << char(254);
break;
case (char)ARROW_KEYS::KEY_ENTER:
printFullyOpenedBook();
break;
}
}
eventManager->setSingleValueField((
eventManager->getEventWithName(
approveEvents[__int64(selectedOption) - 1].title)
)->coordinates.X, (short)x);
eventManager->setSingleValueField((
eventManager->getEventWithName(
approveEvents[__int64(selectedOption) - 1].title)
)->coordinates.Y, (short)y);
break;
}
}
}
}
(void)_getch();
clearConsole();
printClosedBook();
printBookDecorations();
printSnakeSword();
printTeamLogo();
}
}
}
void displayEvents(EventManager* eventManager, bool getAllEvents)
{
outputPosition(81, 10);
std::cout << "How you want to display the events?" << std::endl;
int selectedOption = 1;
char pressedKey = ' ';
const std::vector<std::string> visualizationOptions =
{
"As a map",
"As an encyclopedia"
};
while (pressedKey != (int)ARROW_KEYS::KEY_ENTER)
{
for (int i = 0; i < visualizationOptions.size(); i++)
{
if (i + 1 == selectedOption)
{
outputPosition(81, 12 + i * 2);
std::cout << "-> ";
}
else
{
outputPosition(81, 12 + i * 2);
std::cout << " ";
}
std::cout << visualizationOptions[i] << std::endl << std::endl;
}
pressedKey = _getch();
switch (pressedKey)
{
case (int)ARROW_KEYS::KEY_UP:
selectedOption--;
if (selectedOption == 0)
{
selectedOption += 1;
}
break;
case (int)ARROW_KEYS::KEY_DOWN:
selectedOption++;
if (selectedOption == visualizationOptions.size() + 1)
{
selectedOption -= 1;
}
break;
case (int)ARROW_KEYS::KEY_ENTER:
switch (selectedOption)
{
case 1:
printFullyOpenedBook();
printAsMap(eventManager, getAllEvents);
break;
case 2:
printFullyOpenedBook();
printBy(eventManager, getAllEvents);
break;
}
}
}
clearConsole();
printClosedBook();
printBookDecorations();
printSnakeSword();
printTeamLogo();
}
void approveEvent(EventManager* eventManager)
{
std::vector<Event> allUnapprovedEvents = eventManager->getAllEvents(false);
if (allUnapprovedEvents.empty())
{
outputPosition(81, 10);
std::cout << "There are no events to display";
outputPosition(81, 12);
std::cout << "Press Enter to go back!";
(void)_getch();
return;
}
printFullyOpenedBook();
outputPosition(81, 10);
std::cout << "Choose events that you want to approve:";
int selectedOption = 1;
char pressedKey = ' ';
while (pressedKey != (int)ARROW_KEYS::KEY_ENTER)
{
for (int i = 0; i < allUnapprovedEvents.size(); i++)
{
if (i + 1 == selectedOption)
{
outputPosition(81, 12 + i * 2);
std::cout << "-> ";
}
else
{
outputPosition(81, 12 + i * 2);
std::cout << " ";
}
std::cout << allUnapprovedEvents[i].title << std::endl << std::endl;
}
pressedKey = _getch();
switch (pressedKey)
{
case (int)ARROW_KEYS::KEY_UP:
selectedOption--;
if (selectedOption == 0)
{
selectedOption += 1;
}
break;
case (int)ARROW_KEYS::KEY_DOWN:
selectedOption++;
if (selectedOption == allUnapprovedEvents.size() + 1)
{
selectedOption -= 1;
}
break;
case (int)ARROW_KEYS::KEY_ENTER:
displayEvent(
allUnapprovedEvents[__int64(selectedOption) - 1],
true,
eventManager
);
return;
case (int)ARROW_KEYS::KEY_ESC:
// Return to main menu
clearConsole();
printClosedBook();
printBookDecorations();
printSnakeSword();
printTeamLogo();
return;
break;
}
}
if (_getch())
{
clearConsole();
printClosedBook();
printBookDecorations();
printSnakeSword();
printTeamLogo();
}
}
| 25.448215
| 102
| 0.567097
|
SSIvanov19
|
3e3b20ff37cdd09ff1267c3222b779b0d8da52e1
| 133,608
|
cpp
|
C++
|
src/bgame/bg_misc.cpp
|
jumptohistory/jaymod
|
92d0a0334ac27da94b12280b0b42b615b8813c23
|
[
"Apache-2.0"
] | 25
|
2016-05-27T11:53:58.000Z
|
2021-10-17T00:13:41.000Z
|
src/bgame/bg_misc.cpp
|
jumptohistory/jaymod
|
92d0a0334ac27da94b12280b0b42b615b8813c23
|
[
"Apache-2.0"
] | 1
|
2016-07-09T05:25:03.000Z
|
2016-07-09T05:25:03.000Z
|
src/bgame/bg_misc.cpp
|
jumptohistory/jaymod
|
92d0a0334ac27da94b12280b0b42b615b8813c23
|
[
"Apache-2.0"
] | 16
|
2016-05-28T23:06:50.000Z
|
2022-01-26T13:47:12.000Z
|
/*
* name: bg_misc.c
*
* desc: both games misc functions, all completely stateless
*
*/
#include <bgame/impl.h>
///////////////////////////////////////////////////////////////////////////////
#ifdef CGAMEDLL
extern vmCvar_t cg_gameType;
#define gametypeCvar cg_gameType
#elif GAMEDLL
extern vmCvar_t g_developer;
extern vmCvar_t g_gametype;
#define gametypeCvar g_gametype
#else
extern vmCvar_t ui_gameType;
#define gametypeCvar ui_gameType
#endif
const char* skillNames[SK_NUM_SKILLS] = {
"Battle Sense",
"Engineering",
"First Aid",
"Signals",
"Light Weapons",
"Heavy Weapons",
"Covert Ops"
};
const char* skillNamesLine1[SK_NUM_SKILLS] = {
"Battle",
"Engineering",
"First",
"Signals",
"Light",
"Heavy",
"Covert"
};
const char* skillNamesLine2[SK_NUM_SKILLS] = {
"Sense",
"",
"Aid",
"",
"Weapons",
"Weapons",
"Ops"
};
const char* medalNames[SK_NUM_SKILLS] = {
"Distinguished Service Medal",
"Steel Star",
"Silver Cross",
"Signals Medal",
"Infantry Medal",
"Bombardment Medal",
"Silver Snake"
};
// Jaybird - Custom skill levels
int skillLevels[SK_NUM_SKILLS][NUM_SKILL_LEVELS] = {
{ 0, 20, 50, 90, 140, 200 },
{ 0, 20, 50, 90, 140, 200 },
{ 0, 20, 50, 90, 140, 200 },
{ 0, 20, 50, 90, 140, 200 },
{ 0, 20, 50, 90, 140, 200 },
{ 0, 20, 50, 90, 140, 200 },
{ 0, 20, 50, 90, 140, 200 },
};
vec3_t playerlegsProneMins = { -13.5f, -13.5f, -24.f };
vec3_t playerlegsProneMaxs = { 13.5f, 13.5f, -14.4f };
int numSplinePaths;
splinePath_t splinePaths[MAX_SPLINE_PATHS];
int numPathCorners;
pathCorner_t pathCorners[MAX_PATH_CORNERS];
// these defines are matched with the character torso animations
#define DELAY_LOW 100 // machineguns, tesla, spear, flame
#define DELAY_HIGH 100 // mauser, garand
#define DELAY_PISTOL 100 // colt, luger, sp5, cross
#define DELAY_SHOULDER 50 // rl
#define DELAY_THROW 250 // grenades, dynamite
// Arnout: the new loadout for WolfXP
int weapBanksMultiPlayer[MAX_WEAP_BANKS_MP][MAX_WEAPS_IN_BANK_MP] = {
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, // empty bank '0'
{WP_KNIFE, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{WP_LUGER, WP_COLT, WP_AKIMBO_COLT, WP_AKIMBO_LUGER, WP_AKIMBO_SILENCEDCOLT, WP_AKIMBO_SILENCEDLUGER, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{WP_PANZERFAUST, WP_FLAMETHROWER, WP_MOBILE_MG42, WP_MORTAR, WP_GARAND, WP_CARBINE, WP_STEN, WP_FG42, WP_K43, WP_KAR98, WP_M97, WP_MP40, WP_THOMPSON,0, 0 }, // Jaybird - rearranged so SMG can be modified on-the-fly
{WP_GRENADE_LAUNCHER, WP_GRENADE_PINEAPPLE, WP_MOLOTOV, WP_POISON_SYRINGE, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{WP_MEDIC_SYRINGE, WP_PLIERS, WP_SMOKE_MARKER, WP_SMOKE_BOMB, WP_POISON_GAS, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{WP_DYNAMITE, WP_MEDKIT, WP_AMMO, WP_SATCHEL, WP_SATCHEL_DET, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{WP_LANDMINE, WP_LANDMINE_BBETTY, WP_LANDMINE_PGAS, WP_MEDIC_ADRENALINE, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{WP_BINOCULARS, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
};
// TAT 10/4/2002
// Using one unified list for which weapons can received ammo
// This is used both by the ammo pack code and by the bot code to determine if reloads are needed
int reloadableWeapons[] = {
WP_MP40, WP_THOMPSON, WP_STEN, WP_GARAND, WP_PANZERFAUST, WP_FLAMETHROWER,
WP_KAR98, WP_CARBINE, WP_FG42, WP_K43, WP_MOBILE_MG42, WP_COLT,
WP_LUGER, WP_MORTAR, WP_AKIMBO_COLT, WP_AKIMBO_LUGER, WP_M7, WP_GPG40,
WP_AKIMBO_SILENCEDCOLT, WP_AKIMBO_SILENCEDLUGER, WP_KNIFE, WP_M97, WP_MOLOTOV,
-1
};
// [0] = maxammo - max player ammo carrying capacity.
// [1] = uses - how many 'rounds' it takes/costs to fire one cycle.
// [2] = maxclip - max 'rounds' in a clip.
// [3] = reloadTime - time from start of reload until ready to fire.
// [4] = fireDelayTime - time from pressing 'fire' until first shot is fired. (used for delaying fire while weapon is 'readied' in animation)
// [5] = nextShotTime - when firing continuously, this is the time between shots
// [6] = maxHeat - max active firing time before weapon 'overheats' (at which point the weapon will fail for a moment)
// [7] = coolRate - how fast the weapon cools down.
// [8] = mod - means of death
// potential inclusions in the table:
// damage -
// splashDamage -
// soundRange - distance which ai can hear the weapon
// ammoWarning - amount we give the player a 'low on ammo' warning (just a HUD color change or something)
// clipWarning - amount we give the player a 'low in clip' warning (just a HUD color change or something)
// maxclip2 - allow the player to (mod/powerup) upgrade clip size when aplicable (luger has 8 round standard clip and 32 round snail magazine, for ex.)
//
//
//
#if defined( CGAMEDLL ) || defined( GAMEDLL )
// This will be a backup made of the table at {cgame,game} init-time.
ammotable_t ammoTableMP_BACKUP[WP_NUM_WEAPONS];
#endif
// Separate table for SP and MP allow us to make the ammo and med packs function differently and may allow use to balance
// weapons separately for each game.
// Gordon: changed to actually use the maxammo values
ammotable_t ammoTableMP[WP_NUM_WEAPONS] = {
// MAX USES MAX START START RELOAD FIRE NEXT HEAT, COOL, MOD, ...
// AMMO AMT. CLIP AMMO CLIP TIME DELAY SHOT
{ 0, 0, 0, 0, 0, 0, 50, 0, 0, 0, 0 }, // WP_NONE // 0
{ 4, 1, 1, 4, 1, 0, 50, 200, 0, 0, MOD_KNIFE }, // WP_KNIFE // 1
{ 24, 1, 8, 24, 8, 1500, DELAY_PISTOL, 400, 0, 0, MOD_LUGER }, // WP_LUGER // 2 // NOTE: also 32 round 'snail' magazine
{ 90, 1, 30, 30, 30, 2400, DELAY_LOW, 150, 0, 0, MOD_MP40 }, // WP_MP40 // 3
{ 45, 1, 15, 0, 4, 1000, DELAY_THROW, 1600, 0, 0, MOD_GRENADE_LAUNCHER }, // WP_GRENADE_LAUNCHER // 4
{ 4, 1, 1, 0, 4, 1000, 750 , 2000, 0, 0, MOD_PANZERFAUST }, // WP_PANZERFAUST // 5 // DHM - Nerve :: updated delay so prediction is correct
{ 200, 1, 200, 0, 200, 1000, DELAY_LOW, 50, 0, 0, MOD_FLAMETHROWER }, // WP_FLAMETHROWER // 6
{ 24, 1, 8, 24, 8, 1500, DELAY_PISTOL, 400, 0, 0, MOD_COLT }, // WP_COLT // 7
{ 90, 1, 30, 30, 30, 2400, DELAY_LOW, 150, 0, 0, MOD_THOMPSON }, // WP_THOMPSON // 8
{ 45, 1, 15, 0, 4, 1000, DELAY_THROW, 1600, 0, 0, MOD_GRENADE_PINEAPPLE }, // WP_GRENADE_PINEAPPLE // 9
{ 96, 1, 32, 32, 32, 3100, DELAY_LOW, 150, 1200, 450, MOD_STEN }, // WP_STEN // 10
{ 10, 1, 1, 0, 10, 1500, 50, 1000, 0, 0, MOD_SYRINGE }, // WP_MEDIC_SYRINGE // 11
{ 1, 0, 1, 0, 0, 3000, 50, 1000, 0, 0, MOD_AMMO, }, // WP_AMMO // 12
{ 1, 0, 1, 0, 1, 3000, 50, 1000, 0, 0, MOD_ARTY, }, // WP_ARTY // 13
{ 24, 1, 8, 24, 8, 1500, DELAY_PISTOL, 400, 0, 0, MOD_SILENCER }, // WP_SILENCER // 14
{ 1, 0, 10, 0, 0, 1000, DELAY_THROW, 1600, 0, 0, MOD_DYNAMITE }, // WP_DYNAMITE // 15
{ 999, 0, 999, 0, 0, 0, 50, 0, 0, 0, 0 }, // WP_SMOKETRAIL // 16
{ 999, 0, 999, 0, 0, 0, 50, 0, 0, 0, 0 }, // WP_MAPMORTAR // 17
{ 999, 0, 999, 0, 0, 0, 50, 0, 0, 0, 0 }, // VERYBIGEXPLOSION // 18
{ 999, 0, 999, 1, 1, 0, 50, 0, 0, 0, 0 }, // WP_MEDKIT // 19
{ 999, 0, 999, 0, 0, 0, 50, 0, 0, 0, 0 }, // WP_BINOCULARS // 20
{ 999, 0, 999, 0, 0, 0, 50, 0, 0, 0, 0 }, // WP_PLIERS // 21
{ 999, 0, 999, 0, 1, 0, 50, 0, 0, 0, MOD_AIRSTRIKE }, // WP_SMOKE_MARKER // 22
{ 30, 1, 10, 20, 10, 1500, DELAY_LOW, 400, 0, 0, MOD_KAR98 }, // WP_KAR98 // 23 K43 Engineer - No nade
{ 24, 1, 8, 16, 8, 1500, DELAY_LOW, 400, 0, 0, MOD_CARBINE }, // WP_CARBINE // 24 GARAND
{ 24, 1, 8, 16, 8, 1500, DELAY_LOW, 400, 0, 0, MOD_GARAND }, // WP_GARAND // 25 GARAND Sniper Rifle
{ 1, 0, 1, 0, 1, 100, DELAY_LOW, 100, 0, 0, MOD_LANDMINE }, // WP_LANDMINE // 26
{ 1, 0, 1, 0, 0, 3000, DELAY_LOW, 2000, 0, 0, MOD_SATCHEL }, // WP_SATCHEL // 27
{ 1, 0, 1, 0, 0, 3000, 722, 2000, 0, 0, 0, }, // WP_SATCHEL_DET // 28
{ 6, 1, 1, 0, 0, 2000, DELAY_HIGH, 2000, 0, 0, MOD_TRIPMINE }, // WP_TRIPMINE // 29
{ 1, 0, 10, 0, 1, 1000, DELAY_THROW, 1600, 0, 0, MOD_SMOKEBOMB }, // WP_SMOKE_BOMB // 30
{ 450, 1, 150, 0, 150, 3000, DELAY_LOW, 66, 1500, 300, MOD_MOBILE_MG42 }, // WP_MOBILE_MG42 // 31
{ 30, 1, 10, 20, 10, 1500, DELAY_LOW, 400, 0, 0, MOD_K43 }, // WP_K43 // 32 K43 Sniper Rifle
{ 60, 1, 20, 40, 20, 2000, DELAY_LOW, 100, 0, 0, MOD_FG42 }, // WP_FG42 // 33
{ 0, 0, 0, 0, 0, 0, 0, 0, 1500, 300, 0 }, // WP_DUMMY_MG42 // 34
{ 15, 1, 1, 0, 0, 0, 750, 1600, 0, 0, MOD_MORTAR }, // WP_MORTAR // 35
{ 999, 0, 1, 0, 0, 1000, 750, 1600, 0, 0, 0 }, // WP_LOCKPICK // 36
{ 48, 1, 8, 48, 8, 2700, DELAY_PISTOL, 200, 0, 0, MOD_AKIMBO_COLT }, // WP_AKIMBO_COLT // 37
{ 48, 1, 8, 48, 8, 2700, DELAY_PISTOL, 200, 0, 0, MOD_AKIMBO_LUGER }, // WP_AKIMBO_LUGER // 38
{ 4, 1, 1, 4, 1, 3000, DELAY_LOW, 400, 0, 0, MOD_GPG40 }, // WP_GPG40 // 39
{ 4, 1, 1, 4, 1, 3000, DELAY_LOW, 400, 0, 0, MOD_M7 }, // WP_M7 // 40
{ 24, 1, 8, 24, 8, 1500, DELAY_PISTOL, 400, 0, 0, MOD_SILENCED_COLT }, // WP_SILENCED_COLT // 41
{ 24, 1, 8, 16, 8, 1500, 0, 400, 0, 0, MOD_GARAND_SCOPE }, // WP_GARAND_SCOPE // 42 GARAND Sniper Rifle
{ 30, 1, 10, 20, 10, 1500, 0, 400, 0, 0, MOD_K43_SCOPE }, // WP_K43_SCOPE // 43 K43 Sniper Rifle
{ 60, 1, 20, 40, 20, 2000, DELAY_LOW, 400, 0, 0, MOD_FG42SCOPE }, // WP_FG42SCOPE // 44
{ 16, 1, 1, 12, 0, 0, 750, 1400, 0, 0, MOD_MORTAR }, // WP_MORTAR_SET // 45
{ 10, 1, 1, 0, 10, 1500, 50, 1000, 0, 0, MOD_SYRINGE }, // WP_MEDIC_ADRENALINE // 46
{ 48, 1, 8, 48, 8, 2700, DELAY_PISTOL, 200, 0, 0, MOD_AKIMBO_SILENCEDCOLT }, // WP_AKIMBO_SILENCEDCOLT // 47
{ 48, 1, 8, 48, 8, 2700, DELAY_PISTOL, 200, 0, 0, MOD_AKIMBO_SILENCEDLUGER}, // WP_AKIMBO_SILENCEDLUGER // 48
{ 450, 1, 150, 0, 150, 3000, DELAY_LOW, 66, 1500, 300, MOD_MOBILE_MG42 }, // WP_MOBILE_MG42_SET // 49
{ 4, 1, 1, 0, 4, 1500, 50, 1000, 0, 0, MOD_POISON_SYRINGE }, // WP_POISON_SYRINGE // 50
{ 10, 1, 1, 0, 10, 1500, 50, 1000, 0, 0, MOD_SYRINGE }, // WP_ADRENALINE_SHARE // 51
{ 18, 1, 6, 12, 6, 1250, DELAY_LOW, 1000, 0, 0, MOD_M97 }, // WP_M97 // 52
{ 1, 0, 10, 0, 1, 1000, DELAY_THROW, 1600, 0, 0, MOD_POISON_GAS }, // WP_POISON_GAS // 53
{ 1, 0, 1, 0, 1, 100, DELAY_LOW, 100, 0, 0, MOD_LANDMINE }, // WP_LANDMINE_BBETTY // 54
{ 1, 0, 1, 0, 1, 100, DELAY_LOW, 100, 0, 0, MOD_POISON_GAS }, // WP_LANDMINE_PGAS // 55
{ 3, 1, 3, 0, 3, 0, DELAY_THROW, 0, 0, 0, MOD_MOLOTOV }, // WP_MOLOTOV // 56
};
//----(SA) moved in here so both games can get to it
int weapAlts[] = {
WP_NONE, // 0 WP_NONE
WP_NONE, // 1 WP_KNIFE
WP_SILENCER, // 2 WP_LUGER
WP_NONE, // 3 WP_MP40
WP_NONE, // 4 WP_GRENADE_LAUNCHER
WP_NONE, // 5 WP_PANZERFAUST
WP_NONE, // 6 WP_FLAMETHROWER
WP_SILENCED_COLT, // 7 WP_COLT
WP_NONE, // 8 WP_THOMPSON
WP_NONE, // 9 WP_GRENADE_PINEAPPLE
WP_NONE, // 10 WP_STEN
WP_NONE, // 11 WP_MEDIC_SYRINGE // JPW NERVE
WP_NONE, // 12 WP_AMMO // JPW NERVE
WP_NONE, // 13 WP_ARTY // JPW NERVE
WP_LUGER, // 14 WP_SILENCER //----(SA) was sp5
WP_NONE, // 15 WP_DYNAMITE //----(SA) modified (not in rotation yet)
WP_NONE, // 16 WP_SMOKETRAIL
WP_NONE, // 17 WP_MAPMORTAR
WP_NONE, // 18 VERYBIGEXPLOSION
WP_NONE, // 19 WP_MEDKIT
WP_NONE, // 20 WP_BINOCULARS
WP_NONE, // 21 WP_PLIERS
WP_NONE, // 22 WP_SMOKE_MARKER
WP_GPG40, // 23 WP_KAR98
WP_M7, // 24 WP_CARBINE (GARAND really)
WP_GARAND_SCOPE, // 25 WP_GARAND
WP_NONE, // 26 WP_LANDMINE
WP_NONE, // 27 WP_SATCHEL
WP_NONE, // 28 WP_SATCHEL_DET
WP_NONE, // 29 WP_TRIPMINE
WP_NONE, // 30 WP_SMOKE_BOMB
WP_MOBILE_MG42_SET, // 31 WP_MOBILE_MG42
WP_K43_SCOPE, // 32 WP_K43
WP_FG42SCOPE, // 33 WP_FG42
WP_NONE, // 34 WP_DUMMY_MG42
WP_MORTAR_SET, // 35 WP_MORTAR
WP_NONE, // 36 WP_LOCKPICK Mad Doc - TDF
WP_NONE, // 37 WP_AKIMBO_COLT
WP_NONE, // 38 WP_AKIMBO_LUGER
WP_KAR98, // 39 WP_GPG40
WP_CARBINE, // 40 WP_M7
WP_COLT, // 41 WP_SILENCED_COLT
WP_GARAND, // 42 WP_GARAND_SCOPE
WP_K43, // 43 WP_K43_SCOPE
WP_FG42, // 44 WP_FG42SCOPE
WP_MORTAR, // 45 WP_MORTAR_SET
WP_ADRENALINE_SHARE,// 46 WP_MEDIC_ADRENALINE
WP_NONE, // 47 WP_AKIMBO_SILENCEDCOLT
WP_NONE, // 48 WP_AKIMBO_SILENCEDLUGER
WP_MOBILE_MG42, // 49 WP_MOBILE_MG42_SET
WP_NONE, // 50 WP_POISON_SYRINGE
WP_MEDIC_ADRENALINE,// 51 WP_ADRENALINE_SHARE
WP_NONE, // 52 WP_M97
WP_NONE, // 53 WP_POISON_GAS
WP_NONE, // 54 WP_LANDMINE_BBETTY
WP_NONE, // 55 WP_LANDMINE_PGAS
WP_NONE, // 56 WP_MOLOTOV
};
// new (10/18/00)
char *animStrings[] = {
"BOTH_DEATH1",
"BOTH_DEAD1",
"BOTH_DEAD1_WATER",
"BOTH_DEATH2",
"BOTH_DEAD2",
"BOTH_DEAD2_WATER",
"BOTH_DEATH3",
"BOTH_DEAD3",
"BOTH_DEAD3_WATER",
"BOTH_CLIMB",
"BOTH_CLIMB_DOWN",
"BOTH_CLIMB_DISMOUNT",
"BOTH_SALUTE",
"BOTH_PAIN1",
"BOTH_PAIN2",
"BOTH_PAIN3",
"BOTH_PAIN4",
"BOTH_PAIN5",
"BOTH_PAIN6",
"BOTH_PAIN7",
"BOTH_PAIN8",
"BOTH_GRAB_GRENADE",
"BOTH_ATTACK1",
"BOTH_ATTACK2",
"BOTH_ATTACK3",
"BOTH_ATTACK4",
"BOTH_ATTACK5",
"BOTH_EXTRA1",
"BOTH_EXTRA2",
"BOTH_EXTRA3",
"BOTH_EXTRA4",
"BOTH_EXTRA5",
"BOTH_EXTRA6",
"BOTH_EXTRA7",
"BOTH_EXTRA8",
"BOTH_EXTRA9",
"BOTH_EXTRA10",
"BOTH_EXTRA11",
"BOTH_EXTRA12",
"BOTH_EXTRA13",
"BOTH_EXTRA14",
"BOTH_EXTRA15",
"BOTH_EXTRA16",
"BOTH_EXTRA17",
"BOTH_EXTRA18",
"BOTH_EXTRA19",
"BOTH_EXTRA20",
"TORSO_GESTURE",
"TORSO_GESTURE2",
"TORSO_GESTURE3",
"TORSO_GESTURE4",
"TORSO_DROP",
"TORSO_RAISE", // (low)
"TORSO_ATTACK",
"TORSO_STAND",
"TORSO_STAND_ALT1",
"TORSO_STAND_ALT2",
"TORSO_READY",
"TORSO_RELAX",
"TORSO_RAISE2", // (high)
"TORSO_ATTACK2",
"TORSO_STAND2",
"TORSO_STAND2_ALT1",
"TORSO_STAND2_ALT2",
"TORSO_READY2",
"TORSO_RELAX2",
"TORSO_RAISE3", // (pistol)
"TORSO_ATTACK3",
"TORSO_STAND3",
"TORSO_STAND3_ALT1",
"TORSO_STAND3_ALT2",
"TORSO_READY3",
"TORSO_RELAX3",
"TORSO_RAISE4", // (shoulder)
"TORSO_ATTACK4",
"TORSO_STAND4",
"TORSO_STAND4_ALT1",
"TORSO_STAND4_ALT2",
"TORSO_READY4",
"TORSO_RELAX4",
"TORSO_RAISE5", // (throw)
"TORSO_ATTACK5",
"TORSO_ATTACK5B",
"TORSO_STAND5",
"TORSO_STAND5_ALT1",
"TORSO_STAND5_ALT2",
"TORSO_READY5",
"TORSO_RELAX5",
"TORSO_RELOAD1", // (low)
"TORSO_RELOAD2", // (high)
"TORSO_RELOAD3", // (pistol)
"TORSO_RELOAD4", // (shoulder)
"TORSO_MG42", // firing tripod mounted weapon animation
"TORSO_MOVE", // torso anim to play while moving and not firing (swinging arms type thing)
"TORSO_MOVE_ALT", // torso anim to play while moving and not firing (swinging arms type thing)
"TORSO_EXTRA",
"TORSO_EXTRA2",
"TORSO_EXTRA3",
"TORSO_EXTRA4",
"TORSO_EXTRA5",
"TORSO_EXTRA6",
"TORSO_EXTRA7",
"TORSO_EXTRA8",
"TORSO_EXTRA9",
"TORSO_EXTRA10",
"LEGS_WALKCR",
"LEGS_WALKCR_BACK",
"LEGS_WALK",
"LEGS_RUN",
"LEGS_BACK",
"LEGS_SWIM",
"LEGS_SWIM_IDLE",
"LEGS_JUMP",
"LEGS_JUMPB",
"LEGS_LAND",
"LEGS_IDLE",
"LEGS_IDLE_ALT", // "LEGS_IDLE2"
"LEGS_IDLECR",
"LEGS_TURN",
"LEGS_BOOT", // kicking animation
"LEGS_EXTRA1",
"LEGS_EXTRA2",
"LEGS_EXTRA3",
"LEGS_EXTRA4",
"LEGS_EXTRA5",
"LEGS_EXTRA6",
"LEGS_EXTRA7",
"LEGS_EXTRA8",
"LEGS_EXTRA9",
"LEGS_EXTRA10",
};
// old
char *animStringsOld[] = {
"BOTH_DEATH1",
"BOTH_DEAD1",
"BOTH_DEATH2",
"BOTH_DEAD2",
"BOTH_DEATH3",
"BOTH_DEAD3",
"BOTH_CLIMB",
"BOTH_CLIMB_DOWN",
"BOTH_CLIMB_DISMOUNT",
"BOTH_SALUTE",
"BOTH_PAIN1",
"BOTH_PAIN2",
"BOTH_PAIN3",
"BOTH_PAIN4",
"BOTH_PAIN5",
"BOTH_PAIN6",
"BOTH_PAIN7",
"BOTH_PAIN8",
"BOTH_EXTRA1",
"BOTH_EXTRA2",
"BOTH_EXTRA3",
"BOTH_EXTRA4",
"BOTH_EXTRA5",
"TORSO_GESTURE",
"TORSO_GESTURE2",
"TORSO_GESTURE3",
"TORSO_GESTURE4",
"TORSO_DROP",
"TORSO_RAISE", // (low)
"TORSO_ATTACK",
"TORSO_STAND",
"TORSO_READY",
"TORSO_RELAX",
"TORSO_RAISE2", // (high)
"TORSO_ATTACK2",
"TORSO_STAND2",
"TORSO_READY2",
"TORSO_RELAX2",
"TORSO_RAISE3", // (pistol)
"TORSO_ATTACK3",
"TORSO_STAND3",
"TORSO_READY3",
"TORSO_RELAX3",
"TORSO_RAISE4", // (shoulder)
"TORSO_ATTACK4",
"TORSO_STAND4",
"TORSO_READY4",
"TORSO_RELAX4",
"TORSO_RAISE5", // (throw)
"TORSO_ATTACK5",
"TORSO_ATTACK5B",
"TORSO_STAND5",
"TORSO_READY5",
"TORSO_RELAX5",
"TORSO_RELOAD1", // (low)
"TORSO_RELOAD2", // (high)
"TORSO_RELOAD3", // (pistol)
"TORSO_RELOAD4", // (shoulder)
"TORSO_MG42", // firing tripod mounted weapon animation
"TORSO_MOVE", // torso anim to play while moving and not firing (swinging arms type thing)
"TORSO_EXTRA2",
"TORSO_EXTRA3",
"TORSO_EXTRA4",
"TORSO_EXTRA5",
"LEGS_WALKCR",
"LEGS_WALKCR_BACK",
"LEGS_WALK",
"LEGS_RUN",
"LEGS_BACK",
"LEGS_SWIM",
"LEGS_JUMP",
"LEGS_LAND",
"LEGS_IDLE",
"LEGS_IDLE2",
"LEGS_IDLECR",
"LEGS_TURN",
"LEGS_BOOT", // kicking animation
"LEGS_EXTRA1",
"LEGS_EXTRA2",
"LEGS_EXTRA3",
"LEGS_EXTRA4",
"LEGS_EXTRA5",
};
/*QUAKED item_***** ( 0 0 0 ) (-16 -16 -16) (16 16 16) SUSPENDED SPIN PERSISTANT
DO NOT USE THIS CLASS, IT JUST HOLDS GENERAL INFORMATION.
SUSPENDED - will allow items to hang in the air, otherwise they are dropped to the next surface.
SPIN - will allow items to spin in place.
PERSISTANT - some items (ex. clipboards) can be picked up, but don't disappear
If an item is the target of another entity, it will not spawn in until fired.
An item fires all of its targets when it is picked up. If the toucher can't carry it, the targets won't be fired.
"notfree" if set to 1, don't spawn in free for all games
"notteam" if set to 1, don't spawn in team games
"notsingle" if set to 1, don't spawn in single player games
"wait" override the default wait before respawning. -1 = never respawn automatically, which can be used with targeted spawning.
"random" random number of plus or minus seconds varied from the respawn time
"count" override quantity or duration on most items.
"stand" if the item has a stand (ex: mp40_stand.md3) this specifies which stand tag to attach the weapon to ("stand":"4" would mean "tag_stand4" for example) only weapons support stands currently
*/
// JOSEPH 5-2-00
//----(SA) the addition of the 'ammotype' field was added by me, not removed by id (SA)
gitem_t bg_itemlist[] =
{
{
NULL,
NULL,
{
0,
0,
0
},
NULL, // icon
NULL, // ammo icon
NULL, // pickup
0,
IT_BAD,
0,
0, // ammotype
0, // cliptype
"", // precache
"", // sounds
// {0,0,0,0,0}
}, // leave index 0 alone
/*QUAKED item_treasure (1 1 0) (-8 -8 -8) (8 8 8) suspended
Items the player picks up that are just used to tally a score at end-level
"model" defaults to 'models/powerups/treasure/goldbar.md3'
"noise" sound to play on pickup. defaults to 'sound/pickup/treasure/gold.wav'
"message" what to call the item when it's picked up. defaults to "Treasure Item" (SA: temp)
-------- MODEL FOR RADIANT ONLY - DO NOT SET THIS AS A KEY --------
model="models/powerups/treasure/goldbar.md3"
*/
/*
"scriptName"
*/
{
"item_treasure",
"sound/pickup/treasure/gold.wav",
{
"models/powerups/treasure/goldbar.md3",
0,
0
},
NULL, // (SA) placeholder
NULL, // ammo icon
"Treasure Item", // (SA) placeholder
5,
IT_TREASURE,
0,
0,
0,
"",
"",
// {0,0,0,0,0}
},
//
// ARMOR/HEALTH/STAMINA
//
/*QUAKED item_health_small (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
-------- MODEL FOR RADIANT ONLY - DO NOT SET THIS AS A KEY --------
model="models/powerups/health/health_s.md3"
*/
{
"item_health_small",
"sound/items/n_health.wav",
{
"models/powerups/health/health_s.md3",
0,
0
},
NULL,
NULL, // ammo icon
"Small Health",
5,
IT_HEALTH,
0,
0,
0,
"",
"",
// {10,5,5,5,5}
},
/*QUAKED item_health (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
-------- MODEL FOR RADIANT ONLY - DO NOT SET THIS AS A KEY --------
model="models/powerups/health/health_m.md3"
*/
{
"item_health",
"sound/misc/health_pickup.wav",
// "sound/multiplayer/health_pickup.wav",
{
"models/multiplayer/medpack/medpack_pickup.md3", // JPW NERVE was "models/powerups/health/health_m.md3",
0,
0
},
NULL,
NULL, // ammo icon
"Med Health",
20,
IT_HEALTH,
0,
0,
0,
"",
"",
// {50,25,20,15,15}
},
/*QUAKED item_health_large (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
-------- MODEL FOR RADIANT ONLY - DO NOT SET THIS AS A KEY --------
model="models/powerups/health/health_m.md3"
*/
{
"item_health_large",
"sound/misc/health_pickup.wav",
// "sound/multiplayer/health_pickup.wav",
{
"models/multiplayer/medpack/medpack_pickup.md3", // JPW NERVE was "models/powerups/health/health_m.md3",
0,
0
},
NULL,
NULL, // ammo icon
"Med Health",
50, // xkan, 12/20/2002 - increased to 50 from 30 and used it for SP.
IT_HEALTH,
0,
0,
0,
"",
"",
// {50,25,20,15,15}
},
{
"item_health_cabinet",
"sound/misc/health_pickup.wav",
// "sound/multiplayer/health_pickup.wav",
{
0,
0,
0
},
NULL,
NULL, // ammo icon
"Health",
0,
IT_WEAPON,
0,
0,
0,
"",
"",
},
/*QUAKED item_health_turkey (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
multi-stage health item.
gives 40 on first use, then gives 20 on "finishing up"
player will only eat what he needs. health at 90, turkey fills up and leaves remains (leaving 15). health at 5 you eat the whole thing.
-------- MODEL FOR RADIANT ONLY - DO NOT SET THIS AS A KEY --------
model="models/powerups/health/health_t1.md3"
*/
{
"item_health_turkey",
"sound/items/hot_pickup.wav",
{
"models/powerups/health/health_t3.md3", // just plate (should now be destructable)
"models/powerups/health/health_t2.md3", // half eaten
"models/powerups/health/health_t1.md3" // whole turkey
},
NULL,
NULL, // ammo icon
"Hot Meal",
20, // amount given in last stage
IT_HEALTH,
0,
0,
0,
"",
"",
// {50,50,50,40,30} // amount given in first stage based on gameskill level
},
// xkan, 1/6/2002 - updated
/*QUAKED item_health_breadandmeat (.3 .3 1) (-16 -16 -16) (16 16 16) SUSPENDED SPIN - RESPAWN
multi-stage health item.
gives 30 on first use, then gives 15 on "finishing up"
-------- MODEL FOR RADIANT ONLY - DO NOT SET THIS AS A KEY --------
model="models/powerups/health/health_b1.md3"
*/
{
"item_health_breadandmeat",
"sound/items/cold_pickup.wav",
{ "models/powerups/health/health_b3.md3", // just plate (should now be destructable)
"models/powerups/health/health_b2.md3", // half eaten
"models/powerups/health/health_b1.md3" // whole turkey
},
NULL,
NULL, // ammo icon
"Cold Meal",
15, // amount given in last stage
IT_HEALTH,
0,
0,
0,
"",
"",
//{30,30,20,15} // amount given in first stage based on gameskill level
},
// xkan, 1/6/2002 - updated
/*QUAKED item_health_wall (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
defaults to 50 pts health
you will probably want to check the 'suspended' box to keep it from falling to the ground
-------- MODEL FOR RADIANT ONLY - DO NOT SET THIS AS A KEY --------
model="models/powerups/health/health_w.md3"
*/
{
"item_health_wall",
"sound/items/n_health.wav",
{
"models/powerups/health/health_w.md3",
0,
0
},
NULL,
NULL, // ammo icon
"Health",
25,
IT_HEALTH,
0,
0,
0,
"",
"",
// {25,25,25,25,25}
},
//
// STAMINA
//
//
// WEAPONS
//
// wolf weapons (SA)
/*QUAKED weapon_knife (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
-------- MODEL FOR RADIANT ONLY - DO NOT SET THIS AS A KEY --------
model="models/weapons2/knife/knife.md3"
*/
{
"weapon_knife",
"sound/misc/w_pkup.wav",
{
"models/multiplayer/knife/knife.md3",
"models/multiplayer/knife/v_knife.md3",
0
},
"icons/iconw_knife_1", // icon
"icons/ammo2", // ammo icon
"Knife", // pickup
50,
IT_WEAPON,
WP_KNIFE,
WP_KNIFE,
WP_KNIFE,
"", // precache
"", // sounds
// {0,0,0,0,0}
},
{
"weapon_molotov",
"", // pickup_sound: not used
{
"models/multiplayer/molotov/molotov.md3",
"models/multiplayer/molotov/v_molotov.md3",
0
},
"", // icon: not used
"", // ammo icon: not used
"Molotov", // pickup_name
0,
IT_WEAPON,
WP_MOLOTOV,
WP_MOLOTOV,
WP_MOLOTOV,
"", // precache
"", // sounds
// {0,0,0,0,0}
},
/*QUAKED weapon_luger (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
-------- MODEL FOR RADIANT ONLY - DO NOT SET THIS AS A KEY --------
model="models/weapons2/luger/luger.md3"
*/
{
"weapon_luger",
"sound/misc/w_pkup.wav",
{
"models/weapons2/luger/luger.md3",
"models/weapons2/luger/v_luger.md3",
0
},
"", // icon
"icons/ammo2", // ammo icon
"Luger", // pickup
50,
IT_WEAPON,
WP_LUGER,
WP_LUGER,
WP_LUGER,
"", // precache
"", // sounds
// {0,0,0,0,0}
},
/*QUAKED weapon_akimboluger (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
-------- MODEL FOR RADIANT ONLY - DO NOT SET THIS AS A KEY --------
model="models/weapons2/akimbo_luger/luger.md3"
*/
{
"weapon_akimboluger",
"sound/misc/w_pkup.wav",
{
"models/weapons2/luger/luger.md3",
"models/weapons2/akimbo_luger/v_akimbo_luger.md3",
0
},
"icons/iconw_colt_1", // icon // FIXME: need new icon
"icons/ammo2", // ammo icon
"Akimbo Luger", // pickup
50,
IT_WEAPON,
WP_AKIMBO_LUGER,
WP_LUGER,
WP_AKIMBO_LUGER,
"", // precache
"", // sounds
// {0,0,0,0,0}
},
/*QUAKED weapon_akimbosilencedluger (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
-------- MODEL FOR RADIANT ONLY - DO NOT SET THIS AS A KEY --------
model="models/weapons2/akimbo_luger/luger.md3"
*/
{
"weapon_akimbosilencedluger",
"sound/misc/w_pkup.wav",
{
"models/weapons2/luger/luger.md3",
"models/weapons2/akimbo_luger/v_akimbo_luger.md3",
0
},
"icons/iconw_colt_1", // icon // FIXME: need new icon
"icons/ammo2", // ammo icon
"Silenced Akimbo Luger", // pickup
50,
IT_WEAPON,
WP_AKIMBO_SILENCEDLUGER,
WP_LUGER,
WP_AKIMBO_LUGER,
"", // precache
"", // sounds
// {0,0,0,0,0}
},
/*QUAKED weapon_thompson (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
-------- MODEL FOR RADIANT ONLY - DO NOT SET THIS AS A KEY --------
model="models/weapons2/thompson/thompson.md3"
*/
{
"weapon_thompson",
"sound/misc/w_pkup.wav",
{
"models/weapons2/thompson/thompson.md3",
// "models/multiplayer/mg42/v_mg42.md3",
"models/weapons2/thompson/v_thompson.md3",
0
},
"icons/iconw_thompson_1", // icon
"icons/ammo2", // ammo icon
"Thompson", // pickup
30,
IT_WEAPON,
WP_THOMPSON,
WP_THOMPSON,
WP_THOMPSON,
"", // precache
"", // sounds
// {0,0,0,0,0}
},
{
"weapon_dummy",
"",
{
0,
0,
0
},
"", // icon
"", // ammo icon
"BLANK", // pickup
0, // quantity
IT_WEAPON, // item type
WP_DUMMY_MG42, // giTag
WP_DUMMY_MG42, // giAmmoIndex
WP_DUMMY_MG42, // giClipIndex
"", // precache
"", // sounds
},
/*QUAKED weapon_m97 (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
-------- MODEL FOR RADIANT ONLY - DO NOT SET THIS AS A KEY --------
model="models/weapons2/m97/m97.md3"
*/
{
"weapon_m97",
"sound/misc/w_pkup.wav",
{
"models/weapons2/m97/m97.md3",
"models/weapons2/thompson/v_thompson.md3",
0
},
"icons/iconw_thompson_1", // icon
"icons/ammo2", // ammo icon
"M97", // pickup
30,
IT_WEAPON,
WP_M97,
WP_M97,
WP_M97,
"", // precache
"", // sounds
// {0,0,0,0,0}
},
{
"weapon_dummy",
"",
{
0,
0,
0
},
"", // icon
"", // ammo icon
"BLANK", // pickup
0, // quantity
IT_WEAPON, // item type
WP_DUMMY_MG42, // giTag
WP_DUMMY_MG42, // giAmmoIndex
WP_DUMMY_MG42, // giClipIndex
"", // precache
"", // sounds
},
/*QUAKED weapon_sten (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
-------- MODEL FOR RADIANT ONLY - DO NOT SET THIS AS A KEY --------
model="models/weapons2/sten/sten.md3"
*/
{
"weapon_sten",
"sound/misc/w_pkup.wav",
{
"models/weapons2/sten/sten.md3",
"models/weapons2/sten/v_sten.md3",
0
},
"icons/iconw_sten_1", // icon
"icons/ammo2", // ammo icon
"Sten", // pickup
30,
IT_WEAPON,
WP_STEN,
WP_STEN,
WP_STEN,
"", // precache
"", // sounds
// {0,0,0,0,0}
},
/*QUAKED weapon_colt (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
-------- MODEL FOR RADIANT ONLY - DO NOT SET THIS AS A KEY --------
model="models/weapons2/colt/colt.md3"
*/
{
"weapon_colt",
"sound/misc/w_pkup.wav",
{
"models/weapons2/colt/colt.md3",
"models/weapons2/colt/v_colt.md3",
0
},
"icons/iconw_colt_1", // icon
"icons/ammo2", // ammo icon
"Colt", // pickup
50,
IT_WEAPON,
WP_COLT,
WP_COLT,
WP_COLT,
"", // precache
"", // sounds
// {0,0,0,0,0}
},
/*QUAKED weapon_akimbocolt (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
-------- MODEL FOR RADIANT ONLY - DO NOT SET THIS AS A KEY --------
model="models/weapons2/akimbo_colt/colt.md3"
*/
{
"weapon_akimbocolt",
"sound/misc/w_pkup.wav",
{
"models/weapons2/colt/colt.md3",
"models/weapons2/akimbo_colt/v_akimbo_colt.md3",
0
},
"icons/iconw_colt_1", // icon // FIXME: need new icon
"icons/ammo2", // ammo icon
"Akimbo Colt", // pickup
50,
IT_WEAPON,
WP_AKIMBO_COLT,
WP_COLT,
WP_AKIMBO_COLT,
"", // precache
"", // sounds
// {0,0,0,0,0}
},
/*QUAKED weapon_akimbosilencedcolt (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
-------- MODEL FOR RADIANT ONLY - DO NOT SET THIS AS A KEY --------
model="models/weapons2/akimbo_colt/colt.md3"
*/
{
"weapon_akimbosilencedcolt",
"sound/misc/w_pkup.wav",
{
"models/weapons2/colt/colt.md3",
"models/weapons2/akimbo_colt/v_akimbo_colt.md3",
0
},
"icons/iconw_colt_1", // icon // FIXME: need new icon
"icons/ammo2", // ammo icon
"Silenced Akimbo Colt", // pickup
50,
IT_WEAPON,
WP_AKIMBO_SILENCEDCOLT,
WP_COLT,
WP_AKIMBO_COLT,
"", // precache
"", // sounds
// {0,0,0,0,0}
},
/*QUAKED weapon_mp40 (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
"stand" values:
no value: laying in a default position on it's side (default)
2: upright, barrel pointing up, slightly angled (rack mount)
-------- MODEL FOR RADIANT ONLY - DO NOT SET THIS AS A KEY --------
model="models\weapons2\mp40\mp40.md3"
*/
{
"weapon_mp40",
"sound/misc/w_pkup.wav",
{
"models/weapons2/mp40/mp40.md3",
"models/weapons2/mp40/v_mp40.md3",
0
},
"icons/iconw_mp40_1", // icon
"icons/ammo2", // ammo icon
"MP40", // pickup
30,
IT_WEAPON,
WP_MP40,
WP_MP40,
WP_MP40,
"", // precache
"", // sounds
// {0,0,0,0,0}
},
/*QUAKED weapon_panzerfaust (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
-------- MODEL FOR RADIANT ONLY - DO NOT SET THIS AS A KEY --------
model="models/weapons2/panzerfaust/pf.md3"
*/
{
"weapon_panzerfaust",
"sound/misc/w_pkup.wav",
{
"models/weapons2/panzerfaust/pf.md3",
"models/weapons2/panzerfaust/v_pf.md3",
0
},
"icons/iconw_panzerfaust_1", // icon
"icons/ammo6", // ammo icon
"Panzerfaust", // pickup
1,
IT_WEAPON,
WP_PANZERFAUST,
WP_PANZERFAUST,
WP_PANZERFAUST,
"", // precache
"", // sounds
// {0,0,0,0,0}
},
//----(SA) removed the quaked for this. we don't actually have a grenade launcher as such. It's given implicitly
// by virtue of getting grenade ammo. So we don't need to have them in maps
/*
weapon_grenadelauncher
*/
{
"weapon_grenadelauncher",
"sound/misc/w_pkup.wav",
{
"models/weapons2/grenade/grenade.md3",
"models/weapons2/grenade/v_grenade.md3",
0
},
"icons/iconw_grenade_1", // icon
"icons/icona_grenade", // ammo icon
"Grenade", // pickup
6,
IT_WEAPON,
WP_GRENADE_LAUNCHER,
WP_GRENADE_LAUNCHER,
WP_GRENADE_LAUNCHER,
"", // precache
"", // sounds
// {0,0,0,0,0}
},
/*
weapon_grenadePineapple
*/
{
"weapon_grenadepineapple",
"sound/misc/w_pkup.wav",
{
"models/weapons2/grenade/pineapple.md3",
"models/weapons2/grenade/v_pineapple.md3",
0
},
"icons/iconw_pineapple_1", // icon
"icons/icona_pineapple", // ammo icon
"Pineapple", // pickup
6,
IT_WEAPON,
WP_GRENADE_PINEAPPLE,
WP_GRENADE_PINEAPPLE,
WP_GRENADE_PINEAPPLE,
"", // precache
"", // sounds
// {0,0,0,0,0}
},
/* JPW NERVE
weapon_grenadesmoke
*/
{
"weapon_grenadesmoke",
"sound/misc/w_pkup.wav",
{
"models/multiplayer/smokegrenade/smokegrenade.md3",
"models/multiplayer/smokegrenade/v_smokegrenade.md3",
0
},
"icons/iconw_smokegrenade_1", // icon
"icons/ammo2", // ammo icon
"smokeGrenade", // pickup
50,
IT_WEAPON,
WP_SMOKE_MARKER,
WP_SMOKE_MARKER,
WP_SMOKE_MARKER,
"", // precache
"", // sounds
// {0,0,0,0,0}
},
// jpw
/* JPW NERVE
weapon_smoketrail -- only used as a special effects emitter for smoke trails (artillery spotter etc)
*/
{
"weapon_smoketrail",
"sound/misc/w_pkup.wav",
{
"models/multiplayer/smokegrenade/smokegrenade.md3",
"models/multiplayer/smokegrenade/v_smokegrenade.md3",
0
},
"icons/iconw_smokegrenade_1", // icon
"icons/ammo2", // ammo icon
"smokeTrail", // pickup
50,
IT_WEAPON,
WP_SMOKETRAIL,
WP_SMOKETRAIL,
WP_SMOKETRAIL,
"", // precache
"", // sounds
// {0,0,0,0,0}
},
// jpw
// DHM - Nerve
/*
weapon_medic_heal
*/
{
"weapon_medic_heal",
"sound/misc/w_pkup.wav",
{
"models/multiplayer/medpack/medpack.md3",
"models/multiplayer/medpack/v_medpack.md3",
0
},
"icons/iconw_medheal_1", // icon
"icons/ammo2", // ammo icon
"medicheal", // pickup
50,
IT_WEAPON,
WP_MEDKIT,
WP_MEDKIT,
WP_MEDKIT,
"", // precache
"", // sounds
// {0,0,0,0,0}
},
// dhm
/*
weapon_dynamite
*/
{
"weapon_dynamite",
"sound/misc/w_pkup.wav",
{
"models/multiplayer/dynamite/dynamite_3rd.md3", // JPW NERVE
"models/weapons2/dynamite/v_dynamite.md3", // JPW NERVE
0
},
"icons/iconw_dynamite_1", // icon
"icons/ammo9", // ammo icon
"Dynamite Weapon", // pickup
7,
IT_WEAPON,
WP_DYNAMITE,
WP_DYNAMITE,
WP_DYNAMITE,
"models/multiplayer/dynamite/dynamite.md3 models/multiplayer/dynamite/dynamite_3rd.md3", // precache // JPW NERVE
"", // sounds
// {0,0,0,0,0}
},
/*QUAKED weapon_flamethrower (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
-------- MODEL FOR RADIANT ONLY - DO NOT SET THIS AS A KEY --------
model="models/weapons2/flamethrower/flamethrower.md3"
*/
{
"weapon_flamethrower",
"sound/misc/w_pkup.wav",
{
"models/weapons2/flamethrower/flamethrower.md3",
"models/weapons2/flamethrower/v_flamethrower.md3",
"models/weapons2/flamethrower/pu_flamethrower.md3"
},
"icons/iconw_flamethrower_1", // icon
"icons/ammo10", // ammo icon
"Flamethrower", // pickup
200,
IT_WEAPON,
WP_FLAMETHROWER,
WP_FLAMETHROWER,
WP_FLAMETHROWER,
"", // precache
"", // sounds
// {0,0,0,0,0}
},
/*
weapon_mortar (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
*/
{
"weapon_mapmortar",
"sound/misc/w_pkup.wav",
{
"models/weapons2/grenade/grenade.md3",
"models/weapons2/grenade/v_grenade.md3",
0
},
"icons/iconw_grenade_1", // icon
"icons/icona_grenade", // ammo icon
"nopickup(WP_MAPMORTAR)", // pickup
6,
IT_WEAPON,
WP_MAPMORTAR,
WP_MAPMORTAR,
WP_MAPMORTAR,
"", // precache
"sound/weapons/mortar/mortarf1.wav", // sounds
// {0,0,0,0,0}
},
// JPW NERVE -- class-specific multiplayer weapon, can't be picked up, dropped, or placed in map
/*
weapon_class_special (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
*/
{
"weapon_class_special",
"sound/misc/w_pkup.wav",
{
"models/multiplayer/pliers/pliers.md3",
"models/multiplayer/pliers/v_pliers.md3",
0
},
"icons/iconw_pliers_1", // icon
"icons/ammo2", // ammo icon
"Special", // pickup
50, // this should never be picked up
IT_WEAPON,
WP_PLIERS,
WP_PLIERS,
WP_PLIERS,
"", // precache
"", // sounds
// {0,0,0,0,0}
},
/*
weapon_arty (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
*/
{
"weapon_arty",
"sound/misc/w_pkup.wav",
{
"models/multiplayer/syringe/syringe.md3",
"models/multiplayer/syringe/v_syringe.md3",
0
},
"icons/iconw_syringe_1", // icon
"icons/ammo2", // ammo icon
"Artillery", // pickup
50, // this should never be picked up
IT_WEAPON,
WP_ARTY,
WP_ARTY,
WP_ARTY,
"", // precache
"", // sounds
// {0,0,0,0,0}
},
/*
weapon_medic_syringe (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
*/
{
"weapon_medic_syringe",
"sound/misc/w_pkup.wav",
{
"models/multiplayer/syringe/syringe.md3",
"models/multiplayer/syringe/v_syringe.md3",
0
},
"icons/iconw_syringe_1", // icon
"icons/ammo2", // ammo icon
"Syringe", // pickup
50, // this should never be picked up
IT_WEAPON,
WP_MEDIC_SYRINGE,
WP_MEDIC_SYRINGE,
WP_MEDIC_SYRINGE,
"", // precache
"sound/misc/vo_revive.wav", // sounds
// {0,0,0,0,0}
},
/*
weapon_poison_syringe (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
*/
{
"weapon_poison_syringe",
"sound/misc/w_pkup.wav",
{
"models/multiplayer/syringe/syringe.md3",
"models/multiplayer/syringe/v_syringe.md3",
0
},
"icons/iconw_syringe_1", // icon
"icons/ammo2", // ammo icon
"poison", // pickup
50, // this should never be picked up
IT_WEAPON,
WP_POISON_SYRINGE,
WP_POISON_SYRINGE,
WP_POISON_SYRINGE,
"", // precache
"sound/misc/vo_revive.wav", // sounds
// {0,0,0,0,0}
},
/*
weapon_medic_adrenaline (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
*/
{
"weapon_medic_adrenaline",
"sound/misc/w_pkup.wav",
{
"models/multiplayer/syringe/syringe.md3",
"models/multiplayer/syringe/v_syringe.md3",
0
},
"icons/iconw_syringe_1", // icon
"icons/ammo2", // ammo icon
"Adrenaline Syringe", // pickup
50, // this should never be picked up
IT_WEAPON,
WP_MEDIC_ADRENALINE,
WP_MEDIC_SYRINGE,
WP_MEDIC_SYRINGE,
"", // precache
"", // sounds
// {0,0,0,0,0}
},
/*
weapon_adrenaline_share (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
*/
{
"weapon_adrenaline_share",
"sound/misc/w_pkup.wav",
{
"models/multiplayer/syringe/syringe.md3",
"models/multiplayer/syringe/v_syringe.md3",
0
},
"icons/iconw_syringe_1", // icon
"icons/ammo2", // ammo icon
"adrenaline_share", // pickup
50, // this should never be picked up
IT_WEAPON,
WP_ADRENALINE_SHARE,
WP_MEDIC_SYRINGE,
WP_MEDIC_SYRINGE,
"", // precache
"sound/misc/vo_revive.wav", // sounds
// {0,0,0,0,0}
},
/*
weapon_magicammo (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
*/
{
"weapon_magicammo",
"sound/misc/w_pkup.wav",
{
"models/multiplayer/ammopack/ammopack.md3",
"models/multiplayer/ammopack/v_ammopack.md3",
"models/multiplayer/ammopack/ammopack_pickup.md3"
},
"icons/iconw_ammopack_1", // icon
"icons/ammo2", // ammo icon
"Ammo Pack", // pickup
50, // this should never be picked up
IT_WEAPON,
WP_AMMO,
WP_AMMO,
WP_AMMO,
"", // precache
"", // sounds
// {0,0,0,0,0}
},
{
"weapon_magicammo2",
"sound/misc/w_pkup.wav",
{
"models/multiplayer/binocs/v_binocs.md3",
"models/multiplayer/binocs/v_binocs.md3",
"models/multiplayer/binocs/v_binocs.md3",
// "models/multiplayer/ammopack/ammopack.md3",
// "models/multiplayer/ammopack/v_ammopack.md3",
// "models/multiplayer/ammopack/ammopack_pickup_s.md3"
},
"icons/iconw_ammopack_1", // icon
"icons/ammo2", // ammo icon
"Mega Ammo Pack", // pickup
50, // this should never be picked up
IT_WEAPON,
WP_AMMO,
WP_AMMO,
WP_AMMO,
"", // precache
"", // sounds
},
/*
weapon_binoculars (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
*/
{
"weapon_binoculars",
"sound/misc/w_pkup.wav",
{
"",
"models/multiplayer/binocs/v_binocs.md3",
0
},
"", // icon
"", // ammo icon
"Binoculars", // pickup
50, // this should never be picked up
IT_WEAPON,
WP_BINOCULARS,
WP_BINOCULARS,
WP_BINOCULARS,
"", // precache
"", // sounds
// {0,0,0,0,0}
},
/*QUAKED weapon_k43 (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
-------- MODEL FOR RADIANT ONLY - DO NOT SET THIS AS A KEY --------
model=""
*/
{
"weapon_kar43",
"sound/misc/w_pkup.wav",
{
"models/multiplayer/kar98/kar98_3rd.md3",
"models/multiplayer/kar98/v_kar98.md3",
"models/multiplayer/mauser/mauser_pickup.md3"
},
"icons/iconw_mauser_1", // icon
"icons/ammo3", // ammo icon
"K43 Rifle", // pickup
50,
IT_WEAPON,
WP_K43,
WP_K43,
WP_K43,
"", // precache
"", // sounds
// {0,0,0,0,0}
},
/*QUAKED weapon_kar43_scope (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
-------- MODEL FOR RADIANT ONLY - DO NOT SET THIS AS A KEY --------
model=""
*/
{
"weapon_kar43_scope",
"sound/misc/w_pkup.wav",
{
"models/multiplayer/kar98/kar98_3rd.md3",
"models/multiplayer/kar98/v_kar98.md3",
"models/multiplayer/mauser/mauser_pickup.md3"
},
"icons/iconw_mauser_1", // icon
"icons/ammo3", // ammo icon
"K43 Rifle Scope", // pickup
50,
IT_WEAPON,
WP_K43_SCOPE,
WP_K43,
WP_K43,
"", // precache
"", // sounds
// {0,0,0,0,0}
},
/*QUAKED weapon_kar98Rifle (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
-------- MODEL FOR RADIANT ONLY - DO NOT SET THIS AS A KEY --------
model="models/weapons2/mauser/mauser.md3"
*/
{
"weapon_kar98Rifle",
"sound/misc/w_pkup.wav",
/* {
"models/weapons2/mauser/kar98.md3",
"models/multiplayer/kar98/v_kar98.md3",
"models/multiplayer/mauser/kar98_pickup.md3"
},
"icons/iconw_kar98_1", // icon
"icons/ammo3", // ammo icon*/
{
"models/multiplayer/kar98/kar98_3rd.md3",
"models/multiplayer/kar98/v_kar98.md3",
"models/multiplayer/mauser/mauser_pickup.md3"
},
"icons/iconw_kar98_1", // icon
"icons/ammo3", // ammo icon
"K43", // pickup
50,
IT_WEAPON,
WP_KAR98,
WP_KAR98,
WP_KAR98,
"", // precache
"", // sounds
// {0,0,0,0,0}
},
/*QUAKED weapon_gpg40 (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
-------- MODEL FOR RADIANT ONLY - DO NOT SET THIS AS A KEY --------
model="models/weapons2/mauser/mauser.md3"
*/
{
"weapon_gpg40",
"sound/misc/w_pkup.wav",
{
"models/multiplayer/kar98/kar98_3rd.md3",
"models/multiplayer/kar98/v_kar98.md3",
"models/multiplayer/mauser/mauser_pickup.md3"
},
"icons/iconw_kar98_1", // icon
"icons/ammo10", // ammo icon
"GPG40", // pickup
200,
IT_WEAPON,
WP_GPG40,
WP_GPG40,
WP_GPG40,
"", // precache
"", // sounds
// {0,0,0,0,0}
},
/*QUAKED weapon_gpg40_allied (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
-------- MODEL FOR RADIANT ONLY - DO NOT SET THIS AS A KEY --------
model="models/weapons2/mauser/mauser.md3"
*/
{
"weapon_gpg40_allied",
"sound/misc/w_pkup.wav",
{
"models/multiplayer/m1_garand/m1_garand_3rd.md3",
"models/multiplayer/m1_garand/v_m1_garand.md3",
"models/multiplayer/mauser/mauser_pickup.md3"
},
"icons/iconw_m1_garand_1", // icon
"icons/ammo10", // ammo icon
"GPG40A", // pickup
200,
IT_WEAPON,
WP_M7,
WP_M7,
WP_M7,
"", // precache
"", // sounds
// {0,0,0,0,0}
},
/*QUAKED weapon_M1CarbineRifle (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
-------- MODEL FOR RADIANT ONLY - DO NOT SET THIS AS A KEY --------
model="models/weapons2/mauser/mauser.md3"
*/
{
"weapon_M1CarbineRifle",
"sound/misc/w_pkup.wav",
/* {
"models/weapons2/mauser/mauser.md3",
"models/weapons2/mauser/v_mauser.md3",
"models/multiplayer/mauser/mauser_pickup.md3"
},*/
{
"models/multiplayer/m1_garand/m1_garand_3rd.md3",
"models/multiplayer/m1_garand/v_m1_garand.md3",
"models/multiplayer/mauser/mauser_pickup.md3"
},
"icons/iconw_m1_garand_1", // icon
"icons/ammo3", // ammo icon
"M1 Garand", // pickup
50,
IT_WEAPON,
WP_CARBINE,
WP_CARBINE,
WP_CARBINE,
"", // precache
"", // sounds
// {0,0,0,0,0}
},
/*
weapon_garandRifle (.3 .3 1) (-16 -16 -16) (16 16 16) SUSPENDED SPIN
-------- MODEL FOR RADIANT ONLY - DO NOT SET THIS AS A KEY --------
model="models/weapons2/garand/garand.md3"
*/
{
"weapon_garandRifle",
"sound/misc/w_pkup.wav",
{
"models/multiplayer/m1_garand/m1_garand_3rd.md3",
"models/multiplayer/m1_garand/v_m1_garand.md3",
"models/multiplayer/mauser/mauser_pickup.md3"
},
"icons/iconw_mauser_1", // icon
"icons/ammo3", // ammo icon
"Garand", // pickup
50,
IT_WEAPON,
WP_GARAND,
WP_GARAND,
WP_GARAND,
"", // precache
"", // sounds
// {0,0,0,0}
},
/*
weapon_garandRifleScope (.3 .3 1) (-16 -16 -16) (16 16 16) SUSPENDED SPIN
-------- MODEL FOR RADIANT ONLY - DO NOT SET THIS AS A KEY --------
model="models/weapons2/garand/garand.md3"
*/
{
"weapon_garandRifleScope",
"sound/misc/w_pkup.wav",
{
"models/multiplayer/m1_garand/m1_garand_3rd.md3",
"models/multiplayer/m1_garand/v_m1_garand.md3",
"models/multiplayer/mauser/mauser_pickup.md3"
},
"icons/iconw_mauser_1", // icon
"icons/ammo3", // ammo icon
"M1 Garand Scope", // pickup
50,
IT_WEAPON,
WP_GARAND_SCOPE,
WP_GARAND,
WP_GARAND,
"", // precache
"", // sounds
// {0,0,0,0}
},
/*QUAKED weapon_fg42 (.3 .3 1) (-16 -16 -16) (16 16 16) SUSPENDED
-------- MODEL FOR RADIANT ONLY - DO NOT SET THIS AS A KEY --------
model="models/weapons2/fg42/fg42.md3"
*/
{
"weapon_fg42",
"sound/misc/w_pkup.wav",
{
"models/weapons2/fg42/fg42.md3",
"models/weapons2/fg42/v_fg42.md3",
"models/weapons2/fg42/pu_fg42.md3"
},
"icons/iconw_fg42_1", // icon
"icons/ammo5", // ammo icon
"FG42 Paratroop Rifle", // pickup
10,
IT_WEAPON,
WP_FG42,
WP_FG42,
WP_FG42,
"", // precache
"", // sounds
// {0,0,0,0}
},
/*QUAKED weapon_fg42scope (.3 .3 1) (-16 -16 -16) (16 16 16) SUSPENDED
-------- MODEL FOR RADIANT ONLY - DO NOT SET THIS AS A KEY --------
model="models/weapons2/fg42/fg42.md3"
*/
{
"weapon_fg42scope", //----(SA) modified
"sound/misc/w_pkup.wav",
{ "models/weapons2/fg42/fg42.md3",
"models/weapons2/fg42/v_fg42.md3",
"models/weapons2/fg42/pu_fg42.md3"
},
"icons/iconw_fg42_1", // icon
"icons/ammo5", // ammo icon
"FG42 Scope", // pickup //----(SA) modified
0,
IT_WEAPON,
WP_FG42SCOPE, // this weap
WP_FG42, // shares ammo w/
WP_FG42, // shares clip w/
"", // precache
"", // sounds
// {0,0,0,0}
},
/*
weapon_mortar (.3 .3 1) (-16 -16 -16) (16 16 16) SUSPENDED SPIN
-------- MODEL FOR RADIANT ONLY - DO NOT SET THIS AS A KEY --------
model="models/weapons2/bla?bla?/bla!.md3"
*/
{
"weapon_mortar",
"sound/misc/w_pkup.wav",
{ "models/multiplayer/mortar/mortar_3rd.md3",
"models/multiplayer/mortar/v_mortar.md3",
0
},
"icons/iconw_mortar_1", // icon
"icons/ammo5", // ammo icon
"Mortar", // pickup //----(SA) modified
0,
IT_WEAPON,
WP_MORTAR, // this weap
WP_MORTAR, // shares ammo w/
WP_MORTAR, // shares clip w/
"", // precache
"", // sounds
// {0,0,0,0}
},
{
"weapon_mortar_set",
"sound/misc/w_pkup.wav",
{ "models/multiplayer/mortar/mortar_3rd.md3",
"models/multiplayer/mortar/v_mortar.md3",
0
},
"icons/iconw_mortar_1", // icon
"icons/ammo5", // ammo icon
"Mounted Mortar", // pickup //----(SA) modified
0,
IT_WEAPON,
WP_MORTAR_SET, // this weap
WP_MORTAR, // shares ammo w/
WP_MORTAR, // shares clip w/
"", // precache
"", // sounds
// {0,0,0,0}
},
/*
weapon_landmine
*/
{
"weapon_landmine",
"",
{
"models/multiplayer/landmine/landmine.md3",
"models/multiplayer/landmine/v_landmine.md3",
0
},
"icons/iconw_landmine_1", // icon
"icons/ammo9", // ammo icon
"Landmine", // pickup
7,
IT_WEAPON,
WP_LANDMINE,
WP_LANDMINE,
WP_LANDMINE,
"models/multiplayer/landmine/landmine.md3",
"", // sounds
// {0,0,0,0,0}
},
/*
weapon_satchel (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
*/
{
"weapon_satchel",
"sound/misc/w_pkup.wav",
{
"models/multiplayer/satchel/satchel.md3",
"models/multiplayer/satchel/v_satchel.md3",
0
},
"icons/iconw_satchel_1", // icon
"icons/ammo2", // ammo icon
"Satchel Charge", // pickup
0,
IT_WEAPON,
WP_SATCHEL,
WP_SATCHEL,
WP_SATCHEL,
"", // precache
"", // sounds
// {0,0,0,0,0}
},
{
"weapon_satchelDetonator",
"",
{
"models/multiplayer/satchel/radio.md3",
"models/multiplayer/satchel/v_satchel.md3",
0
},
"icons/iconw_radio_1", // icon
"icons/ammo2", // ammo icon
"Satchel Charge Detonator", // pickup
0,
IT_WEAPON,
WP_SATCHEL_DET,
WP_SATCHEL_DET,
WP_SATCHEL_DET,
"", // precache
"", // sounds
// {0,0,0,0,0}
},
{
"weapon_smokebomb",
"",
{
"models/multiplayer/smokebomb/smokebomb.md3",
"models/multiplayer/smokebomb/v_smokebomb.md3",
0
},
"icons/iconw_dynamite_1", // icon
"icons/ammo9", // ammo icon
"Smoke Bomb", // pickup
0,
IT_WEAPON,
WP_SMOKE_BOMB,
WP_SMOKE_BOMB,
WP_SMOKE_BOMB,
"", // precache
"", // sounds
// {0,0,0,0,0}
},
{
"weapon_tripmine",
"sound/misc/w_pkup.wav",
{
"models/multiplayer/dynamite/dynamite_3rd.md3",
"models/weapons2/dynamite/v_dynamite.md3",
0
},
"icons/iconw_dynamite_1", // icon
"icons/ammo9", // ammo icon
"Tripmine", // pickup
7,
IT_WEAPON,
WP_TRIPMINE,
WP_TRIPMINE,
WP_TRIPMINE,
"models/multiplayer/dynamite/dynamite.md3 models/multiplayer/dynamite/dynamite_3rd.md3",
"", // sounds
// {0,0,0,0,0}
},
/*QUAKED weapon_mobile_mg42 (.3 .3 1) (-16 -16 -16) (16 16 16) suspended spin - respawn
-------- MODEL FOR RADIANT ONLY - DO NOT SET THIS AS A KEY --------
model="models/multiplayer/mg42/v_mg42.md3"
*/
{
"weapon_mobile_mg42",
"sound/misc/w_pkup.wav",
{
"models/multiplayer/mg42/mg42_3rd.md3",
"models/multiplayer/mg42/v_mg42.md3",
0
},
"icons/iconw_mg42_1", // icon
"icons/ammo2", // ammo icon
"Mobile MG42", // pickup
30,
IT_WEAPON,
WP_MOBILE_MG42,
WP_MOBILE_MG42,
WP_MOBILE_MG42,
"", // precache
"", // sounds
// {0,0,0,0,0}
},
{
"weapon_mobile_mg42_set",
"sound/misc/w_pkup.wav",
{
"models/multiplayer/mg42/mg42_3rd.md3",
"models/multiplayer/mg42/v_mg42.md3",
0
},
"icons/iconw_mg42_1", // icon
"icons/ammo2", // ammo icon
"Mobile MG42 Bipod", // pickup
30,
IT_WEAPON,
WP_MOBILE_MG42_SET,
WP_MOBILE_MG42,
WP_MOBILE_MG42,
"", // precache
"", // sounds
// {0,0,0,0,0}
},
{
"weapon_silencer",
"sound/misc/w_pkup.wav",
{ "models/weapons2/silencer/silencer.md3", //----(SA) changed 10/25
"models/weapons2/silencer/v_silencer.md3",
"models/weapons2/silencer/pu_silencer.md3"
},
"icons/iconw_silencer_1", // icon
"icons/ammo5", // ammo icon
// "Silencer", // pickup
"sp5 pistol",
10,
IT_WEAPON,
WP_SILENCER,
WP_LUGER,
WP_LUGER,
"", // precache
"", // sounds
// {0,0,0,0}
},
/*QUAKED weapon_colt (.3 .3 1) (-16 -16 -16) (16 16 16) suspended
-------- MODEL FOR RADIANT ONLY - DO NOT SET THIS AS A KEY --------
model="models/weapons2/colt/colt.md3"
*/
{
"weapon_silencedcolt",
"sound/misc/w_pkup.wav",
{
"models/weapons2/colt/colt.md3",
"models/multiplayer/silencedcolt/v_silencedcolt.md3",
0
},
"icons/iconw_colt_1", // icon
"icons/ammo2", // ammo icon
"Silenced Colt", // pickup
50,
IT_WEAPON,
WP_SILENCED_COLT,
WP_COLT,
WP_COLT,
"", // precache
"", // sounds
// {0,0,0,0,0}
},
// DHM - Nerve
/*
weapon_medic_heal
*/
{
"weapon_medic_heal",
"sound/misc/w_pkup.wav",
{
"models/multiplayer/medpack/medpack.md3",
"models/multiplayer/medpack/v_medpack.md3",
0
},
"icons/iconw_medheal_1", // icon
"icons/ammo2", // ammo icon
"medicheal", // pickup
50,
IT_WEAPON,
WP_MEDKIT,
WP_MEDKIT,
WP_MEDKIT,
"", // precache
"", // sounds
// {0,0,0,0,0}
},
// dhm
/*QUAKED ammo_syringe (.3 .3 1) (-16 -16 -16) (16 16 16) SUSPENDED SPIN - RESPAWN
used by: medic
-------- MODEL FOR RADIANT ONLY - DO NOT SET THIS AS A KEY --------
model="models/ammo/syringe/syringe.md3
*/
{
"ammo_syringe",
"sound/misc/am_pkup.wav",
{ "models/ammo/syringe/syringe.md3",
0, 0},
"",// icon
NULL, // ammo icon
"syringe", // pickup //----(SA) changed
1,
IT_AMMO,
WP_MEDIC_SYRINGE,
WP_MEDIC_SYRINGE,
WP_MEDIC_SYRINGE,
"", // precache
"", // sounds
},
/*QUAKED ammo_smoke_grenade (.3 .3 1) (-16 -16 -16) (16 16 16) SUSPENDED SPIN - RESPAWN
used by: engineer
-------- MODEL FOR RADIANT ONLY - DO NOT SET THIS AS A KEY --------
model="models/ammo/smoke_grenade/smoke_grenade.md3"
*/
{
"ammo_smoke_grenade",
"sound/misc/am_pkup.wav",
{ "models/ammo/smoke_grenade/smoke_grenade.md3",
0, 0 },
"",// icon
NULL, // ammo icon
"smoke grenade", // pickup //----(SA) changed
1,
IT_AMMO,
WP_SMOKE_BOMB,
WP_SMOKE_BOMB,
WP_SMOKE_BOMB,
"", // precache
"", // sounds
},
/*QUAKED ammo_dynamite (.3 .3 1) (-16 -16 -16) (16 16 16) SUSPENDED SPIN - RESPAWN
used by: engineer
-------- MODEL FOR RADIANT ONLY - DO NOT SET THIS AS A KEY --------
model="models/ammo/dynamite/dynamite.md3"
*/
{
"ammo_dynamite",
"sound/misc/am_pkup.wav",
{ "models/ammo/dynamite/dynamite.md3",
0, 0},
"",// icon
NULL, // ammo icon
"dynamite", // pickup //----(SA) changed
1,
IT_AMMO,
WP_DYNAMITE,
WP_DYNAMITE,
WP_DYNAMITE,
"", // precache
"", // sounds
},
/*QUAKED ammo_disguise (.3 .3 1) (-16 -16 -16) (16 16 16) SUSPENDED SPIN - RESPAWN
used by: covertops
-------- MODEL FOR RADIANT ONLY - DO NOT SET THIS AS A KEY --------
model="models/ammo/disguise/disguise.md3"
*/
{
"ammo_disguise",
"sound/misc/am_pkup.wav",
{ "models/ammo/disguise/disguise.md3",
0, 0},
"",// icon
NULL, // ammo icon
"disguise", // pickup //----(SA) changed
1,
IT_AMMO,
-1, // ignored
-1, // ignored
-1, // ignored
"", // precache
"", // sounds
},
/*QUAKED ammo_airstrike (.3 .3 1) (-16 -16 -16) (16 16 16) SUSPENDED SPIN - RESPAWN
used by: LT
-------- MODEL FOR RADIANT ONLY - DO NOT SET THIS AS A KEY --------
model="models/ammo/airstrike/airstrike.md3"
*/
{
"ammo_airstrike",
"sound/misc/am_pkup.wav",
{ "models/ammo/disguise/disguise.md3",
0, 0},
"",// icon
NULL, // ammo icon
"airstrike canister", // pickup //----(SA) changed
1,
IT_AMMO,
WP_SMOKE_MARKER,
WP_SMOKE_MARKER,
WP_SMOKE_MARKER,
"", // precache
"", // sounds
},
/*QUAKED ammo_landmine (.3 .3 1) (-16 -16 -16) (16 16 16) SUSPENDED SPIN - RESPAWN
used by: LT
-------- MODEL FOR RADIANT ONLY - DO NOT SET THIS AS A KEY --------
model="models/ammo/landmine/landmine.md3"
*/
{
"ammo_landmine",
"sound/misc/am_pkup.wav",
{ "models/ammo/landmine/landmine.md3",
0, 0 },
"",// icon
NULL, // ammo icon
"landmine", // pickup //----(SA) changed
1,
IT_AMMO,
WP_LANDMINE,
WP_LANDMINE,
WP_LANDMINE,
"", // precache
"", // sounds
},
/*QUAKED ammo_satchel_charge (.3 .3 1) (-16 -16 -16) (16 16 16) SUSPENDED SPIN - RESPAWN
used by: LT
-------- MODEL FOR RADIANT ONLY - DO NOT SET THIS AS A KEY --------
model="models/ammo/satchel/satchel.md3"
*/
{
"ammo_satchel_charge",
"sound/misc/am_pkup.wav",
{ "models/ammo/satchel/satchel.md3",
0, 0 },
"",// icon
NULL, // ammo icon
"satchel charge", // pickup //----(SA) changed
1,
IT_AMMO,
WP_SATCHEL,
WP_SATCHEL,
WP_SATCHEL,
"", // precache
"", // sounds
},
//
// AMMO ITEMS
//
/*QUAKED ammo_9mm_small (.3 .3 1) (-16 -16 -16) (16 16 16) SUSPENDED SPIN - RESPAWN
used by: Luger pistol, MP40 machinegun
-------- MODEL FOR RADIANT ONLY - DO NOT SET THIS AS A KEY --------
model="models/powerups/ammo/am9mm_s.md3"
*/
{
"ammo_9mm_small",
"sound/misc/am_pkup.wav",
{ "models/powerups/ammo/am9mm_s.md3",
0, 0 },
"",// icon
NULL, // ammo icon
"9mm Rounds", // pickup
8,
IT_AMMO,
WP_LUGER,
WP_LUGER,
WP_LUGER,
"", // precache
"", // sounds
// {32,24,16,16}
},
/*QUAKED ammo_9mm (.3 .3 1) (-16 -16 -16) (16 16 16) SUSPENDED SPIN - RESPAWN
used by: Luger pistol, MP40 machinegun
-------- MODEL FOR RADIANT ONLY - DO NOT SET THIS AS A KEY --------
model="models/powerups/ammo/am9mm_m.md3"
*/
{
"ammo_9mm",
"sound/misc/am_pkup.wav",
{ "models/powerups/ammo/am9mm_m.md3",
0, 0 },
"",// icon
NULL, // ammo icon
"9mm", // pickup //----(SA) changed
16,
IT_AMMO,
WP_LUGER,
WP_LUGER,
WP_LUGER,
"", // precache
"", // sounds
// {64,48,32,32}
},
/*QUAKED ammo_9mm_large (.3 .3 1) (-16 -16 -16) (16 16 16) SUSPENDED SPIN - RESPAWN
used by: Luger pistol, MP40 machinegun
-------- MODEL FOR RADIANT ONLY - DO NOT SET THIS AS A KEY --------
model="models/powerups/ammo/am9mm_l.md3"
*/
{
"ammo_9mm_large",
"sound/misc/am_pkup.wav",
{ "models/powerups/ammo/am9mm_l.md3",
0, 0 },
"",// icon
NULL, // ammo icon
"9mm Box", // pickup
24,
IT_AMMO,
WP_LUGER,
WP_LUGER,
WP_LUGER,
"", // precache
"", // sounds
// {96,64,48,48}
},
/*QUAKED ammo_45cal_small (.3 .3 1) (-16 -16 -16) (16 16 16) SUSPENDED SPIN - RESPAWN
used by: Thompson, Colt
-------- MODEL FOR RADIANT ONLY - DO NOT SET THIS AS A KEY --------
model="models/powerups/ammo/am45cal_s.md3"
*/
{
"ammo_45cal_small",
"sound/misc/am_pkup.wav",
{ "models/powerups/ammo/am45cal_s.md3",
0, 0 },
"",// icon
NULL, // ammo icon
".45cal Rounds", // pickup
8,
IT_AMMO,
WP_COLT,
WP_COLT,
WP_COLT,
"", // precache
"", // sounds
// {30,20,15,15}
},
/*QUAKED ammo_45cal (.3 .3 1) (-16 -16 -16) (16 16 16) SUSPENDED SPIN - RESPAWN
used by: Thompson, Colt
-------- MODEL FOR RADIANT ONLY - DO NOT SET THIS AS A KEY --------
model="models/powerups/ammo/am45cal_m.md3"
*/
{
"ammo_45cal",
"sound/misc/am_pkup.wav",
{ "models/powerups/ammo/am45cal_m.md3",
0, 0 },
"",// icon
NULL, // ammo icon
".45cal", // pickup //----(SA) changed
16,
IT_AMMO,
WP_COLT,
WP_COLT,
WP_COLT,
"", // precache
"", // sounds
// {60,45,30,30}
},
/*QUAKED ammo_45cal_large (.3 .3 1) (-16 -16 -16) (16 16 16) SUSPENDED SPIN - RESPAWN
used by: Thompson, Colt
-------- MODEL FOR RADIANT ONLY - DO NOT SET THIS AS A KEY --------
model="models/powerups/ammo/am45cal_l.md3"
*/
{
"ammo_45cal_large",
"sound/misc/am_pkup.wav",
{ "models/powerups/ammo/am45cal_l.md3",
0, 0 },
"",// icon
NULL, // ammo icon
".45cal Box", // pickup
24,
IT_AMMO,
WP_COLT,
WP_COLT,
WP_COLT,
"", // precache
"", // sounds
// {90,60,45,45}
},
/*QUAKED ammo_30cal_small (.3 .3 1) (-16 -16 -16) (16 16 16) SUSPENDED SPIN - RESPAWN
used by: Garand rifle
-------- MODEL FOR RADIANT ONLY - DO NOT SET THIS AS A KEY --------
model="models/powerups/ammo/am30cal_s.md3"
*/
{
"ammo_30cal_small",
"sound/misc/am_pkup.wav",
{ "models/powerups/ammo/am30cal_s.md3",
0, 0},
"", // icon
NULL, // ammo icon
".30cal Rounds", // pickup
8,
IT_AMMO,
WP_GARAND,
WP_GARAND,
WP_GARAND,
"", // precache
"", // sounds
// {5,2,2,2}
},
/*QUAKED ammo_30cal (.3 .3 1) (-16 -16 -16) (16 16 16) SUSPENDED SPIN - RESPAWN
used by: Garand rifle
-------- MODEL FOR RADIANT ONLY - DO NOT SET THIS AS A KEY --------
model="models/powerups/ammo/am30cal_m.md3"
*/
{
"ammo_30cal",
"sound/misc/am_pkup.wav",
{ "models/powerups/ammo/am30cal_m.md3",
0, 0 },
"", // icon
NULL, // ammo icon
".30cal", // pickup //----(SA) changed
16,
IT_AMMO,
WP_GARAND,
WP_GARAND,
WP_GARAND,
"", // precache
"", // sounds
// {5,5,5,5 }
},
/*QUAKED ammo_30cal_large (.3 .3 1) (-16 -16 -16) (16 16 16) SUSPENDED SPIN - RESPAWN
used by: Garand rifle
-------- MODEL FOR RADIANT ONLY - DO NOT SET THIS AS A KEY --------
model="models/powerups/ammo/am30cal_l.md3"
*/
{
"ammo_30cal_large",
"sound/misc/am_pkup.wav",
{ "models/powerups/ammo/am30cal_l.md3",
0, 0 },
"", // icon
NULL, // ammo icon
".30cal Box", // pickup
24,
IT_AMMO,
WP_GARAND,
WP_GARAND,
WP_GARAND,
"", // precache
"", // sounds
// {10,10,10,5}
},
//
// POWERUP ITEMS
//
/*QUAKED team_CTF_redflag (1 0 0) (-16 -16 -16) (16 16 16)
Only in CTF games
-------- MODEL FOR RADIANT ONLY - DO NOT SET THIS AS A KEY --------
model="models/flags/r_flag.md3"
*/
{
"team_CTF_redflag",
"",
{
0,
0,
0
},
"", // icon
NULL, // ammo icon
"Objective", // pickup
0,
IT_TEAM,
PW_REDFLAG,
0,
0,
"", // precache
"", // sounds
// {0,0,0,0,0}
},
/*QUAKED team_CTF_blueflag (0 0 1) (-16 -16 -16) (16 16 16)
Only in CTF games
-------- MODEL FOR RADIANT ONLY - DO NOT SET THIS AS A KEY --------
model="models/flags/b_flag.md3"
*/
{
"team_CTF_blueflag",
"",
{
0,
0,
0
},
"", // icon
NULL, // ammo icon
"Blue Flag", // pickup
0,
IT_TEAM,
PW_BLUEFLAG,
0,
0,
"", // precache
"", // sounds
// {0,0,0,0,0}
},
{
"weapon_poisonGas",
"",
{
"models/multiplayer/smokebomb/smokebomb.md3",
"models/multiplayer/smokebomb/v_smokebomb.md3",
0
},
"icons/iconw_dynamite_1", // icon
"icons/ammo9", // ammo icon
"Poison Gas", // pickup
0,
IT_WEAPON,
WP_POISON_GAS,
WP_POISON_GAS,
WP_POISON_GAS,
"", // precache
"", // sounds
// {0,0,0,0,0}
},
{
"weapon_landmine_bbetty",
"",
{
"models/multiplayer/landmine/landmine.md3",
"models/multiplayer/landmine/v_landmine.md3",
0
},
"icons/iconw_landmine_1", // icon
"icons/ammo9", // ammo icon
"Landmine BBetty", // pickup
7,
IT_WEAPON,
WP_LANDMINE_BBETTY,
WP_LANDMINE_BBETTY,
WP_LANDMINE_BBETTY,
"models/multiplayer/landmine/landmine.md3",
"", // sounds
// {0,0,0,0,0}
},
{
"weapon_landmine_pgas",
"",
{
"models/multiplayer/landmine/landmine.md3",
"models/multiplayer/landmine/v_landmine.md3",
0
},
"icons/iconw_landmine_1", // icon
"icons/ammo9", // ammo icon
"Landmine PGas", // pickup
7,
IT_WEAPON,
WP_LANDMINE_PGAS,
WP_LANDMINE_PGAS,
WP_LANDMINE_PGAS,
"models/multiplayer/landmine/landmine.md3",
"", // sounds
// {0,0,0,0,0}
},
{
"ammo_landmine_bbetty",
"sound/misc/am_pkup.wav",
{ "models/ammo/landmine/landmine.md3",
0, 0 },
"",// icon
NULL, // ammo icon
"landmine bbetty", // pickup //----(SA) changed
1,
IT_AMMO,
WP_LANDMINE_BBETTY,
WP_LANDMINE_BBETTY,
WP_LANDMINE_BBETTY,
"", // precache
"", // sounds
},
{
"ammo_landmine_pgas",
"sound/misc/am_pkup.wav",
{ "models/ammo/landmine/landmine.md3",
0, 0 },
"",// icon
NULL, // ammo icon
"landmine pgas", // pickup //----(SA) changed
1,
IT_AMMO,
WP_LANDMINE_PGAS,
WP_LANDMINE_PGAS,
WP_LANDMINE_PGAS,
"", // precache
"", // sounds
},
//---- (SA) Wolf keys
/* QUAKED key_1 (1 1 0) (-8 -8 -8) (8 8 8) SUSPENDED SPIN - RESPAWN
key 1
pickup sound : "sound/misc/w_pkup.wav"
-------- MODEL FOR RADIANT ONLY - DO NOT SET THIS AS A KEY --------
model="models/powerups/xp_key/key.md3"
*/
/*
{
"key_key1",
"sound/misc/w_pkup.wav", //"sound/pickup/keys/skull.wav",
{
"models/powerups/xp_key/key.md3",
0, 0
},
"", //"icons/iconk_skull", // icon
NULL, // ammo icon
"Key 1", // pickup
0,
IT_KEY,
KEY_1,
0,
0,
"", // precache
"models/keys/key.wav", // sounds
//{0,0,0,0}
},
*/
// end of list marker
{ NULL }
};
// END JOSEPH
int bg_numItems = sizeof(bg_itemlist) / sizeof(bg_itemlist[0]) - 1;
/*
===============
BG_FindItemForWeapon
===============
*/
gitem_t *BG_FindItemForWeapon( weapon_t weapon ) {
gitem_t *it;
for ( it = bg_itemlist + 1 ; it->classname ; it++) {
if ( it->giType == IT_WEAPON && it->giTag == weapon ) {
return it;
}
}
Com_Error( ERR_DROP, "Couldn't find item for weapon %i", weapon);
return NULL;
}
//----(SA) added
#define DEATHMATCH_SHARED_AMMO 0
/*
==============
BG_FindClipForWeapon
==============
*/
weapon_t BG_FindClipForWeapon( weapon_t weapon) {
gitem_t *it;
for ( it = bg_itemlist + 1 ; it->classname ; it++) {
if ( it->giType == IT_WEAPON && it->giTag == weapon ) {
return (weapon_t)it->giClipIndex;
}
}
return WP_NONE;
}
/*
==============
BG_FindAmmoForWeapon
==============
*/
weapon_t BG_FindAmmoForWeapon( weapon_t weapon ) {
gitem_t *it;
for ( it = bg_itemlist + 1 ; it->classname ; it++) {
if ( it->giType == IT_WEAPON && it->giTag == weapon ) {
return (weapon_t)it->giAmmoIndex;
}
}
return WP_NONE;
}
/*
==============
BG_AkimboFireSequence
returns 'true' if it's the left hand's turn to fire, 'false' if it's the right hand's turn
==============
*/
qboolean BG_AkimboFireSequence( int weapon, int akimboClip, int mainClip ) {
if( !BG_IsAkimboWeapon( weapon ) )
return qfalse;
if( !akimboClip )
return qfalse;
// no ammo in main weapon, must be akimbo turn
if( !mainClip )
return qtrue;
// at this point, both have ammo
// now check 'cycle' // (removed old method 11/5/2001)
if( (akimboClip + mainClip) & 1) {
return qfalse;
}
return qtrue;
}
/*
==============
BG_IsAkimboWeapon
==============
*/
qboolean BG_IsAkimboWeapon( int weaponNum ) {
if( weaponNum == WP_AKIMBO_COLT ||
weaponNum == WP_AKIMBO_SILENCEDCOLT ||
weaponNum == WP_AKIMBO_LUGER ||
weaponNum == WP_AKIMBO_SILENCEDLUGER )
return qtrue;
else
return qfalse;
}
/*
==============
BG_IsAkimboSideArm
==============
*/
qboolean BG_IsAkimboSideArm( int weaponNum, playerState_t *ps ) {
switch( weaponNum )
{
case WP_COLT: if( ps->weapon == WP_AKIMBO_COLT || ps->weapon == WP_AKIMBO_SILENCEDCOLT ) return qtrue; break;
case WP_LUGER: if( ps->weapon == WP_AKIMBO_LUGER || ps->weapon == WP_AKIMBO_SILENCEDLUGER ) return qtrue; break;
}
return qfalse;
}
/*
==============
BG_AkimboSidearm
==============
*/
int BG_AkimboSidearm( int weaponNum ) {
switch( weaponNum )
{
case WP_AKIMBO_COLT: return WP_COLT; break;
case WP_AKIMBO_SILENCEDCOLT: return WP_COLT; break;
case WP_AKIMBO_LUGER: return WP_LUGER; break;
case WP_AKIMBO_SILENCEDLUGER: return WP_LUGER; break;
default: return WP_NONE; break;
}
}
/*
==============
BG_AkimboForSideArm
==============
*/
/*int BG_AkimboForSideArm( int weaponNum ) {
switch( weaponNum )
{
case WP_COLT: return WP_AKIMBO_COLT; break;
case WP_SILENCED_COLT: return WP_AKIMBO_SILENCEDCOLT; break;
case WP_LUGER: return WP_AKIMBO_LUGER; break;
case WP_SILENCER: return WP_AKIMBO_SILENCEDLUGER; break;
default: return WP_NONE; break;
}
}*/
//----(SA) Added keys
/*
==============
BG_FindItemForKey
==============
*/
/*gitem_t *BG_FindItemForKey(wkey_t k, int *indexreturn)
{
int i;
for ( i = 0 ; i < bg_numItems ; i++ ) {
if ( bg_itemlist[i].giType == IT_KEY && bg_itemlist[i].giTag == k ) {
{
if(indexreturn)
*indexreturn = i;
return &bg_itemlist[i];
}
}
}
Com_Error( ERR_DROP, "Key %d not found", k );
return NULL;
}*/
//----(SA) end
//----(SA) added
/*
==============
BG_FindItemForAmmo
==============
*/
gitem_t *BG_FindItemForAmmo(int ammo)
{
int i = 0;
for (;i < bg_numItems; i++)
{
if ( bg_itemlist[i].giType == IT_AMMO && bg_itemlist[i].giAmmoIndex == ammo )
return &bg_itemlist[i];
}
Com_Error( ERR_DROP, "Item not found for ammo: %d", ammo );
return NULL;
}
//----(SA) end
/*
===============
BG_FindItem
===============
*/
gitem_t *BG_FindItem( const char *pickupName ) {
gitem_t *it;
for ( it = bg_itemlist + 1 ; it->classname ; it++ ) {
if ( !Q_stricmp( it->pickup_name, pickupName ) )
return it;
}
return NULL;
}
gitem_t *BG_FindItemForClassName( const char *className ) {
gitem_t *it;
for ( it = bg_itemlist + 1 ; it->classname ; it++ ) {
if ( !Q_stricmp( it->classname, className ) )
return it;
}
return NULL;
}
// DHM - Nerve :: returns qtrue if a weapon is indeed used in multiplayer
// Gordon: FIXME: er, we shouldnt really need this, just remove all the weapons we dont actually want :)
qboolean BG_WeaponInWolfMP( int weapon ) {
switch ( weapon ) {
case WP_ADRENALINE_SHARE:
case WP_AKIMBO_COLT:
case WP_AKIMBO_LUGER:
case WP_AKIMBO_SILENCEDCOLT:
case WP_AKIMBO_SILENCEDLUGER:
case WP_AMMO:
case WP_ARTY:
case WP_BINOCULARS:
case WP_CARBINE:
case WP_COLT:
case WP_DYNAMITE:
case WP_FG42:
case WP_FG42SCOPE:
case WP_FLAMETHROWER:
case WP_GARAND:
case WP_GARAND_SCOPE:
case WP_GPG40:
case WP_GRENADE_LAUNCHER:
case WP_GRENADE_PINEAPPLE:
case WP_K43:
case WP_K43_SCOPE:
case WP_KAR98:
case WP_KNIFE:
case WP_LANDMINE:
case WP_LANDMINE_BBETTY:
case WP_LANDMINE_PGAS:
case WP_LUGER:
case WP_M7:
case WP_M97:
case WP_MEDIC_ADRENALINE:
case WP_MEDIC_SYRINGE:
case WP_MEDKIT:
case WP_MOBILE_MG42:
case WP_MOBILE_MG42_SET:
case WP_MOLOTOV:
case WP_MORTAR:
case WP_MORTAR_SET:
case WP_MP40:
case WP_PANZERFAUST:
case WP_PLIERS:
case WP_POISON_GAS:
case WP_POISON_SYRINGE:
case WP_SATCHEL:
case WP_SATCHEL_DET:
case WP_SILENCED_COLT:
case WP_SILENCER:
case WP_SMOKETRAIL:
case WP_SMOKE_BOMB:
case WP_SMOKE_MARKER:
case WP_STEN:
case WP_THOMPSON:
return qtrue;
default:
return qfalse;
}
}
/*
============
BG_PlayerTouchesItem
Items can be picked up without actually touching their physical bounds to make
grabbing them easier
============
*/
qboolean BG_PlayerTouchesItem( playerState_t *ps, entityState_t *item, int atTime ) {
vec3_t origin;
BG_EvaluateTrajectory( &item->pos, atTime, origin, qfalse, item->effect2Time );
// we are ignoring ducked differences here
if ( ps->origin[0] - origin[0] > 36
|| ps->origin[0] - origin[0] < -36
|| ps->origin[1] - origin[1] > 36
|| ps->origin[1] - origin[1] < -36
|| ps->origin[2] - origin[2] > 36
|| ps->origin[2] - origin[2] < -36 ) {
return qfalse;
}
return qtrue;
}
/*
=================================
BG_AddMagicAmmo:
if numOfClips is 0, no ammo is added, it just return whether any ammo CAN be added;
otherwise return whether any ammo was ACTUALLY added.
WARNING: when numOfClips is 0, DO NOT CHANGE ANYTHING under ps.
=================================
*/
// Jaybird - Sniper War
// This is here so that people cannot pick up grenades
// during a sniper war. Stupid n00bs.
int BG_GrenadesForClass( int cls, int* skills ) {
int num = 0;
switch (cls) {
case PC_ENGINEER:
if (skills[SK_EXPLOSIVES_AND_CONSTRUCTION] >= 5 && cvars::bg_sk5_eng.ivalue & SK5_ENG_GRENADES)
num = 10;
else
num = 8;
break;
case PC_SOLDIER:
if (skills[SK_HEAVY_WEAPONS] >= 5 && cvars::bg_sk5_soldier.ivalue & SK5_SOL_GRENADES)
num = 8;
else
num = 4;
break;
case PC_MEDIC:
if (skills[SK_FIRST_AID] >= 5 && cvars::bg_sk5_medic.ivalue & SK5_MED_GRENADES)
num = 4;
else if (skills[SK_FIRST_AID] >= 1)
num = 2;
else
num = 1;
break;
case PC_FIELDOPS:
if (skills[SK_SIGNALS] >= 5 && cvars::bg_sk5_fdops.ivalue & SK5_FDO_GRENADES)
num = 4;
else if (skills[SK_SIGNALS] >= 1)
num = 2;
else
num = 1;
break;
case PC_COVERTOPS:
if (cvars::bg_sniperWar.ivalue)
num = 0;
else if (skills[SK_MILITARY_INTELLIGENCE_AND_SCOPED_WEAPONS] >= 5 && cvars::bg_sk5_cvops.ivalue & SK5_CVO_GRENADES)
num = 4;
else
num = 2;
break;
}
return num;
}
weapon_t BG_GrenadeTypeForTeam( team_t team ) {
switch( team ) {
case TEAM_AXIS:
return WP_GRENADE_LAUNCHER;
case TEAM_ALLIES:
return WP_GRENADE_PINEAPPLE;
default:
return WP_NONE;
}
}
// Gordon: setting numOfClips = 0 allows you to check if the client needs ammo, but doesnt give any
qboolean BG_AddMagicAmmo( playerState_t *ps, int *skill, int teamNum, int numOfClips ) {
int i, weapon;
qboolean ammoAdded = qfalse;
int maxammo;
int clip;
int weapNumOfClips;
// Gordon: handle grenades first
i = BG_GrenadesForClass( ps->stats[STAT_PLAYER_CLASS], skill );
weapon = BG_GrenadeTypeForTeam( (team_t)teamNum );
clip = BG_FindClipForWeapon( (weapon_t)weapon );
if( ps->ammoclip[clip] < i ) {
// Gordon: early out
if( !numOfClips ) {
return qtrue;
}
ps->ammoclip[clip] += numOfClips;
ammoAdded = qtrue;
COM_BitSet(ps->weapons, weapon);
if( ps->ammoclip[clip] > i) {
ps->ammoclip[clip] = i;
}
}
// Jaybird - add adrenaline so others can restock
if( COM_BitCheck( ps->weapons, WP_MEDIC_SYRINGE ) ||
COM_BitCheck( ps->weapons, WP_MEDIC_ADRENALINE) ||
COM_BitCheck( ps->weapons, WP_ADRENALINE_SHARE)) {
i = skill[ SK_FIRST_AID ] >= 2 ? 12 : 10;
clip = BG_FindClipForWeapon( WP_MEDIC_SYRINGE );
if( ps->ammoclip[ clip ] < i ) {
if( !numOfClips ) {
return qtrue;
}
ps->ammoclip[ clip ] += numOfClips;
ammoAdded = qtrue;
if( ps->ammoclip[ clip ] > i) {
ps->ammoclip[ clip ] = i;
}
}
}
// Jaybird - Poison needles
if( COM_BitCheck( ps->weapons, WP_POISON_SYRINGE )) {
int i = GetAmmoTableData(WP_POISON_SYRINGE)->maxammo;
if (skill[SK_FIRST_AID] >= 2)
i += 2;
clip = BG_FindClipForWeapon( WP_POISON_SYRINGE );
if( ps->ammoclip[ clip ] < i ) {
if( !numOfClips ) {
return qtrue;
}
ps->ammoclip[ clip ] += numOfClips;
ammoAdded = qtrue;
if( ps->ammoclip[ clip ] > i) {
ps->ammoclip[ clip ] = i;
}
}
}
// Gordon: now other weapons
for (i = 0; reloadableWeapons[i] >= 0; i++) {
weapon = reloadableWeapons[i];
if (!COM_BitCheck( ps->weapons, weapon ))
continue;
maxammo = BG_MaxAmmoForWeapon( (weapon_t)weapon, skill );
// handle clip vs. ammo
switch (weapon) {
case WP_FLAMETHROWER:
clip = BG_FindAmmoForWeapon( (weapon_t)weapon );
if (ps->ammoclip[clip] < maxammo) {
// early out
if (!numOfClips)
return qtrue;
ammoAdded = qtrue;
ps->ammoclip[clip] = maxammo;
}
break;
case WP_MOLOTOV:
case WP_PANZERFAUST:
clip = BG_FindAmmoForWeapon( (weapon_t)weapon );
if (ps->ammoclip[clip] < maxammo) {
// early out
if (!numOfClips)
return qtrue;
ammoAdded = qtrue;
ps->ammoclip[clip] += numOfClips;
if (ps->ammoclip[clip] > maxammo )
ps->ammoclip[clip] = maxammo;
}
break;
default:
clip = BG_FindAmmoForWeapon( (weapon_t)weapon );
if (ps->ammo[clip] < maxammo) {
// early out
if(!numOfClips) {
return qtrue;
}
ammoAdded = qtrue;
if( BG_IsAkimboWeapon( weapon ) ) {
weapNumOfClips = numOfClips * 2; // double clips babeh!
} else {
weapNumOfClips = numOfClips;
}
// add and limit check
ps->ammo[clip] += weapNumOfClips * GetAmmoTableData(weapon)->maxclip;
if (ps->ammo[clip] > maxammo) {
ps->ammo[clip] = maxammo;
}
}
break;
}
}
// Jaybird - pick up a helmet if set to do so
if (ps->eFlags & EF_HEADSHOT && (cvars::bg_weapons.ivalue & SBW_HELMET)) {
if (!numOfClips)
return qtrue;
ps->eFlags &= ~EF_HEADSHOT;
ammoAdded = qtrue;
}
return ammoAdded;
}
/*
================
BG_CanUseWeapon: can a player of the specified team and class use this weapon?
extracted and adapted from Bot_GetWeaponForClassAndTeam.
================
- added by xkan, 01/02/03
*/
qboolean BG_CanUseWeapon(int classNum, int teamNum, weapon_t weapon) {
switch (classNum) {
case PC_ENGINEER:
switch (weapon) {
case WP_DYNAMITE:
case WP_LANDMINE:
case WP_LANDMINE_BBETTY:
case WP_LANDMINE_PGAS:
case WP_M97:
case WP_PLIERS:
return qtrue;
case WP_KAR98:
case WP_MP40:
return (teamNum == TEAM_AXIS) ? qtrue : qfalse;
case WP_CARBINE:
case WP_THOMPSON:
return (teamNum == TEAM_ALLIES) ? qtrue : qfalse;
default:
break;
}
break;
case PC_FIELDOPS:
switch (weapon) {
case WP_STEN:
case WP_M97:
return qtrue;
case WP_MP40:
return (teamNum == TEAM_AXIS) ? qtrue : qfalse;
case WP_THOMPSON:
return (teamNum == TEAM_ALLIES) ? qtrue : qfalse;
default:
break;
}
break;
case PC_SOLDIER:
switch (weapon) {
case WP_FG42:
case WP_FLAMETHROWER:
case WP_M97:
case WP_MOBILE_MG42:
case WP_MOBILE_MG42_SET:
case WP_MORTAR:
case WP_MORTAR_SET:
case WP_PANZERFAUST:
case WP_STEN:
return qtrue;
case WP_MP40:
return (teamNum == TEAM_AXIS) ? qtrue : qfalse;
case WP_THOMPSON:
return (teamNum == TEAM_ALLIES) ? qtrue : qfalse;
default:
break;
}
break;
case PC_MEDIC:
switch (weapon) {
case WP_M97:
case WP_MEDIC_SYRINGE:
case WP_MEDKIT:
case WP_POISON_SYRINGE:
return qtrue;
case WP_MP40:
return (teamNum == TEAM_AXIS) ? qtrue : qfalse;
case WP_THOMPSON:
return (teamNum == TEAM_ALLIES) ? qtrue : qfalse;
default:
break;
}
break;
case PC_COVERTOPS:
switch (weapon) {
case WP_AMMO:
case WP_FG42:
case WP_POISON_GAS:
case WP_SATCHEL:
case WP_SMOKE_BOMB:
case WP_STEN:
return qtrue;
case WP_K43:
return (teamNum == TEAM_AXIS) ? qtrue : qfalse;
case WP_GARAND:
return (teamNum == TEAM_ALLIES) ? qtrue : qfalse;
default:
break;
}
break;
}
switch (weapon) {
case WP_COLT:
case WP_KNIFE:
case WP_LUGER:
case WP_NONE:
return qtrue;
default:
break;
}
return qfalse;
}
#define AMMOFORWEAP BG_FindAmmoForWeapon(item->giTag)
/*
================
BG_CanItemBeGrabbed
Returns false if the item should not be picked up.
This needs to be the same for client side prediction and server use.
================
*/
qboolean BG_CanItemBeGrabbed( const entityState_t *ent, const playerState_t *ps, int *skill, int teamNum ) {
gitem_t *item;
if ( ent->modelindex < 1 || ent->modelindex >= bg_numItems ) {
Com_Error( ERR_DROP, "BG_CanItemBeGrabbed: index out of range" );
}
item = &bg_itemlist[ent->modelindex];
switch( item->giType ) {
case IT_WEAPON:
if( item->giTag == WP_AMMO ) {
// magic ammo for any two-handed weapon
// xkan, 11/21/2002 - only pick up if ammo is not full, numClips is 0, so ps will
// NOT be changed (I know, it places the burden on the programmer, rather than the
// compiler, to ensure that).
return BG_AddMagicAmmo( (playerState_t *)ps, skill, teamNum, 0); // Arnout: had to cast const away
}
return qtrue;
case IT_AMMO:
return qfalse;
case IT_ARMOR:
return qfalse;
case IT_HEALTH:
// Gordon: ps->teamNum is really class.... thx whoever decided on that...
if( ps->teamNum == PC_MEDIC ) {
// Gordon: medics can go up to 12% extra on max health as they have perm. regen
if( ps->stats[STAT_HEALTH] >= (int)(ps->stats[STAT_MAX_HEALTH] * 1.12) ) {
return qfalse;
}
} else {
if( ps->stats[STAT_HEALTH] >= ps->stats[STAT_MAX_HEALTH] ) {
return qfalse;
}
}
return qtrue;
case IT_TEAM: // team items, such as flags
// density tracks how many uses left
if((ent->density < 1) || (((ps->persistant[PERS_TEAM] == TEAM_AXIS) ? ps->powerups[PW_BLUEFLAG] : ps->powerups[PW_REDFLAG]) != 0) )
return qfalse;
// DHM - Nerve :: otherEntity2 is now used instead of modelindex2
// ent->modelindex2 is non-zero on items if they are dropped
// we need to know this because we can pick up our dropped flag (and return it)
// but we can't pick up our flag at base
if (ps->persistant[PERS_TEAM] == TEAM_AXIS) {
if (item->giTag == PW_BLUEFLAG ||
(item->giTag == PW_REDFLAG && ent->otherEntityNum2 /*ent->modelindex2*/) ||
(item->giTag == PW_REDFLAG && ps->powerups[PW_BLUEFLAG]))
return qtrue;
} else if (ps->persistant[PERS_TEAM] == TEAM_ALLIES) {
if (item->giTag == PW_REDFLAG ||
(item->giTag == PW_BLUEFLAG && ent->otherEntityNum2 /*ent->modelindex2*/) ||
(item->giTag == PW_BLUEFLAG && ps->powerups[PW_REDFLAG]))
return qtrue;
}
return qfalse;
case IT_HOLDABLE:
return qtrue;
case IT_TREASURE: // treasure always picked up
return qtrue;
case IT_KEY:
return qtrue; // keys are always picked up
case IT_BAD:
Com_Error( ERR_DROP, "BG_CanItemBeGrabbed: IT_BAD" );
}
return qfalse;
}
//======================================================================
void BG_CalculateSpline_r(splinePath_t* spline, vec3_t out1, vec3_t out2, float tension) {
vec3_t points[18];
int i;
int count = spline->numControls + 2;
vec3_t dist;
VectorCopy( spline->point.origin, points[0] );
for( i = 0; i < spline->numControls; i++ ) {
VectorCopy( spline->controls[i].origin, points[i+1] );
}
if(!spline->next) {
return;
// Com_Error( ERR_DROP, "Spline (%s) with no target referenced", spline->point.name );
}
VectorCopy( spline->next->point.origin, points[i+1] );
while(count > 2) {
for( i = 0; i < count-1; i++ ) {
VectorSubtract( points[i+1], points[i], dist );
VectorMA(points[i], tension, dist, points[i]);
}
count--;
}
VectorCopy( points[0], out1 );
VectorCopy( points[1], out2 );
}
qboolean BG_TraverseSpline( float* deltaTime, splinePath_t** pSpline) {
float dist;
while( (*deltaTime) > 1 ) {
(*deltaTime) -= 1;
dist = (*pSpline)->length * (*deltaTime);
if(!(*pSpline)->next || !(*pSpline)->next->length) {
return qfalse;
// Com_Error( ERR_DROP, "Spline path end passed (%s)", (*pSpline)->point.name );
}
(*pSpline) = (*pSpline)->next;
*deltaTime = dist / (*pSpline)->length;
}
while( (*deltaTime) < 0 ) {
dist = -((*pSpline)->length * (*deltaTime));
if(!(*pSpline)->prev || !(*pSpline)->prev->length) {
return qfalse;
// Com_Error( ERR_DROP, "Spline path end passed (%s)", (*pSpline)->point.name );
}
(*pSpline) = (*pSpline)->prev;
(*deltaTime) = 1 - (dist / (*pSpline)->length);
}
return qtrue;
}
/*
================
BG_RaySphereIntersection
================
*/
qboolean BG_RaySphereIntersection( float radius, vec3_t origin, splineSegment_t* path, float *t0, float *t1 ) {
vec3_t v;
float b, c, d;
VectorSubtract( path->start, origin, v );
b = 2 * DotProduct( v, path->v_norm );
c = DotProduct( v, v ) - (radius * radius);
d = (b * b) - (4 * c);
if( d < 0 ) {
return qfalse;
}
d = sqrt( d );
*t0 = (-b + d) * 0.5f;
*t1 = (-b - d) * 0.5f;
return qtrue;
}
void BG_LinearPathOrigin2(float radius, splinePath_t** pSpline, float *deltaTime, vec3_t result, qboolean backwards) {
qboolean first = qtrue;
float t = 0.f;
int i = (int)( floor((*deltaTime) * (MAX_SPLINE_SEGMENTS)) );
float frac;
// int x = 0;
// splinePath_t* start = *pSpline;
if(i >= MAX_SPLINE_SEGMENTS) {
i = MAX_SPLINE_SEGMENTS - 1;
frac = 1.f;
} else {
frac = (((*deltaTime) * (MAX_SPLINE_SEGMENTS)) - i);
}
while(qtrue) {
float t0, t1;
while(qtrue) {
if(BG_RaySphereIntersection( radius, result, &(*pSpline)->segments[i], &t0, &t1 )) {
qboolean found = qfalse;
t0 /= (*pSpline)->segments[i].length;
t1 /= (*pSpline)->segments[i].length;
if(first) {
if(radius < 0) {
if(t0 < frac && (t0 >= 0.f && t0 <= 1.f)) {
t = t0;
found = qtrue;
} else if (t1 < frac) {
t = t1;
found = qtrue;
}
} else {
if(t0 > frac && (t0 >= 0.f && t0 <= 1.f)) {
t = t0;
found = qtrue;
} else if (t1 > frac) {
t = t1;
found = qtrue;
}
}
} else {
if(radius < 0) {
if(t0 < t1 && (t0 >= 0.f && t0 <= 1.f)) {
t = t0;
found = qtrue;
} else {
t = t1;
found = qtrue;
}
} else {
if(t0 > t1 && (t0 >= 0.f && t0 <= 1.f)) {
t = t0;
found = qtrue;
} else {
t = t1;
found = qtrue;
}
}
}
if( found ) {
if(t >= 0.f && t <= 1.f) {
*deltaTime = (i / (float)(MAX_SPLINE_SEGMENTS)) + (t / (float)(MAX_SPLINE_SEGMENTS));
VectorMA( (*pSpline)->segments[i].start, t * (*pSpline)->segments[i].length, (*pSpline)->segments[i].v_norm, result );
return;
}
}
found = qfalse;
}
first = qfalse;
if(radius < 0) {
i--;
if(i < 0) {
i = MAX_SPLINE_SEGMENTS - 1;
break;
}
} else {
i++;
if(i >= MAX_SPLINE_SEGMENTS) {
i = 0;
break;
}
}
}
if( radius < 0 ) {
if(!(*pSpline)->prev) {
return;
// Com_Error( ERR_DROP, "End of spline reached (%s)\n", start->point.name );
}
*pSpline = (*pSpline)->prev;
} else {
if(!(*pSpline)->next) {
return;
// Com_Error( ERR_DROP, "End of spline reached (%s)\n", start->point.name );
}
*pSpline = (*pSpline)->next;
}
}
}
void BG_ComputeSegments(splinePath_t* pSpline) {
int i;
float granularity = 1 / ((float)(MAX_SPLINE_SEGMENTS));
vec3_t vec[4];
memset( vec, 0, sizeof(vec) );
for( i = 0; i < MAX_SPLINE_SEGMENTS; i++ ) {
BG_CalculateSpline_r( pSpline, vec[0], vec[1], i * granularity );
VectorSubtract( vec[1], vec[0], pSpline->segments[i].start );
VectorMA(vec[0], i * granularity, pSpline->segments[i].start, pSpline->segments[i].start );
BG_CalculateSpline_r( pSpline, vec[2], vec[3], (i + 1) * granularity );
VectorSubtract( vec[3], vec[2], vec[0] );
VectorMA(vec[2], (i + 1) * granularity, vec[0], vec[0] );
VectorSubtract( vec[0], pSpline->segments[i].start, pSpline->segments[i].v_norm );
pSpline->segments[i].length = VectorLength( pSpline->segments[i].v_norm );
VectorNormalize( pSpline->segments[i].v_norm );
}
}
/*
================
BG_EvaluateTrajectory
================
*/
void BG_EvaluateTrajectory( const trajectory_t *tr, int atTime, vec3_t result, qboolean isAngle, int splinePath ) {
float deltaTime;
float phase;
vec3_t v;
splinePath_t* pSpline;
vec3_t vec[2];
memset( vec, 0, sizeof(vec) );
qboolean backwards = qfalse;
float deltaTime2;
switch( tr->trType ) {
case TR_STATIONARY:
case TR_INTERPOLATE:
case TR_GRAVITY_PAUSED: //----(SA)
VectorCopy( tr->trBase, result );
break;
case TR_LINEAR:
deltaTime = ( atTime - tr->trTime ) * 0.001; // milliseconds to seconds
VectorMA( tr->trBase, deltaTime, tr->trDelta, result );
break;
case TR_SINE:
deltaTime = ( atTime - tr->trTime ) / (float) tr->trDuration;
phase = sin( deltaTime * M_PI * 2 );
VectorMA( tr->trBase, phase, tr->trDelta, result );
break;
//----(SA) removed
case TR_LINEAR_STOP:
if ( atTime > tr->trTime + tr->trDuration ) {
atTime = tr->trTime + tr->trDuration;
}
deltaTime = ( atTime - tr->trTime ) * 0.001; // milliseconds to seconds
if ( deltaTime < 0 ) {
deltaTime = 0;
}
VectorMA( tr->trBase, deltaTime, tr->trDelta, result );
break;
case TR_GRAVITY:
deltaTime = ( atTime - tr->trTime ) * 0.001; // milliseconds to seconds
VectorMA( tr->trBase, deltaTime, tr->trDelta, result );
result[2] -= 0.5 * DEFAULT_GRAVITY * deltaTime * deltaTime; // FIXME: local gravity...
break;
// Ridah
case TR_GRAVITY_LOW:
deltaTime = ( atTime - tr->trTime ) * 0.001; // milliseconds to seconds
VectorMA( tr->trBase, deltaTime, tr->trDelta, result );
result[2] -= 0.5 * (DEFAULT_GRAVITY * 0.3) * deltaTime * deltaTime; // FIXME: local gravity...
break;
// done.
//----(SA)
case TR_GRAVITY_FLOAT:
deltaTime = ( atTime - tr->trTime ) * 0.001; // milliseconds to seconds
VectorMA( tr->trBase, deltaTime, tr->trDelta, result );
result[2] -= 0.5 * (DEFAULT_GRAVITY * 0.2) * deltaTime;
break;
//----(SA) end
// RF, acceleration
case TR_ACCELERATE: // trDelta is the ultimate speed
if ( atTime > tr->trTime + tr->trDuration ) {
atTime = tr->trTime + tr->trDuration;
}
deltaTime = ( atTime - tr->trTime ) * 0.001; // milliseconds to seconds
// phase is the acceleration constant
phase = VectorLength( tr->trDelta ) / (tr->trDuration*0.001);
// trDelta at least gives us the acceleration direction
VectorNormalize2( tr->trDelta, result );
// get distance travelled at current time
VectorMA( tr->trBase, phase * 0.5 * deltaTime * deltaTime, result, result );
break;
case TR_DECCELERATE: // trDelta is the starting speed
if ( atTime > tr->trTime + tr->trDuration ) {
atTime = tr->trTime + tr->trDuration;
}
deltaTime = ( atTime - tr->trTime ) * 0.001; // milliseconds to seconds
// phase is the breaking constant
phase = VectorLength( tr->trDelta ) / (tr->trDuration*0.001);
// trDelta at least gives us the acceleration direction
VectorNormalize2( tr->trDelta, result );
// get distance travelled at current time (without breaking)
VectorMA( tr->trBase, deltaTime, tr->trDelta, v );
// subtract breaking force
VectorMA( v, -phase * 0.5 * deltaTime * deltaTime, result, result );
break;
case TR_SPLINE:
if(!(pSpline = BG_GetSplineData( splinePath, &backwards ))) {
return;
}
deltaTime = tr->trDuration ? (atTime - tr->trTime) / ((float)tr->trDuration) : 0;
if(deltaTime < 0.f) {
deltaTime = 0.f;
} else if(deltaTime > 1.f) {
deltaTime = 1.f;
}
if(backwards) {
deltaTime = 1 - deltaTime;
}
/* if(pSpline->isStart) {
deltaTime = 1 - sin((1 - deltaTime) * M_PI * 0.5f);
} else if(pSpline->isEnd) {
deltaTime = sin(deltaTime * M_PI * 0.5f);
}*/
deltaTime2 = deltaTime;
BG_CalculateSpline_r( pSpline, vec[0], vec[1], deltaTime );
if(isAngle) {
qboolean dampin = qfalse;
qboolean dampout = qfalse;
float base1;
if(tr->trBase[0]) {
// int pos = 0;
vec3_t result2;
splinePath_t* pSp2 = pSpline;
deltaTime2 += tr->trBase[0] / pSpline->length;
if(BG_TraverseSpline( &deltaTime2, &pSp2 )) {
VectorSubtract( vec[1], vec[0], result );
VectorMA(vec[0], deltaTime, result, result);
BG_CalculateSpline_r( pSp2, vec[0], vec[1], deltaTime2 );
VectorSubtract( vec[1], vec[0], result2 );
VectorMA(vec[0], deltaTime2, result2, result2);
if( tr->trBase[0] < 0 ) {
VectorSubtract( result, result2, result );
} else {
VectorSubtract( result2, result, result );
}
} else {
VectorSubtract( vec[1], vec[0], result );
}
} else {
VectorSubtract( vec[1], vec[0], result );
}
vectoangles( result, result );
base1 = tr->trBase[1];
if(base1 >= 10000 || base1 < -10000) {
dampin = qtrue;
if(base1 < 0) {
base1 += 10000;
} else {
base1 -= 10000;
}
}
if(base1 >= 1000 || base1 < -1000) {
dampout = qtrue;
if(base1 < 0) {
base1 += 1000;
} else {
base1 -= 1000;
}
}
if(dampin && dampout) {
result[ROLL] = base1 + ((sin(((deltaTime * 2) - 1) * M_PI * 0.5f) + 1) * 0.5f * tr->trBase[2]);
} else if(dampin) {
result[ROLL] = base1 + (sin(deltaTime * M_PI * 0.5f) * tr->trBase[2]);
} else if(dampout) {
result[ROLL] = base1 + ((1 - sin((1 - deltaTime) * M_PI * 0.5f)) * tr->trBase[2]);
} else {
result[ROLL] = base1 + (deltaTime * tr->trBase[2]);
}
} else {
VectorSubtract( vec[1], vec[0], result );
VectorMA(vec[0], deltaTime, result, result);
}
break;
case TR_LINEAR_PATH:
if(!(pSpline = BG_GetSplineData( splinePath, &backwards ))) {
return;
}
deltaTime = tr->trDuration ? (atTime - tr->trTime) / ((float)tr->trDuration) : 0;
if(deltaTime < 0.f) {
deltaTime = 0.f;
} else if(deltaTime > 1.f) {
deltaTime = 1.f;
}
if(backwards) {
deltaTime = 1 - deltaTime;
}
if(isAngle) {
int pos = (int)( floor(deltaTime * (MAX_SPLINE_SEGMENTS)) );
float frac;
if(pos >= MAX_SPLINE_SEGMENTS) {
pos = MAX_SPLINE_SEGMENTS - 1;
frac = pSpline->segments[pos].length;
} else {
frac = ((deltaTime * (MAX_SPLINE_SEGMENTS)) - pos) * pSpline->segments[pos].length;
}
if(tr->trBase[0]) {
VectorMA( pSpline->segments[pos].start, frac, pSpline->segments[pos].v_norm, result );
VectorCopy( result, v );
BG_LinearPathOrigin2( tr->trBase[0], &pSpline, &deltaTime, v, backwards );
if( tr->trBase[0] < 0 ) {
VectorSubtract( v, result, result );
} else {
VectorSubtract( result, v, result );
}
vectoangles( result, result );
} else {
vectoangles( pSpline->segments[pos].v_norm, result );
}
} else {
int pos = (int)( floor(deltaTime * (MAX_SPLINE_SEGMENTS)) );
float frac;
if(pos >= MAX_SPLINE_SEGMENTS) {
pos = MAX_SPLINE_SEGMENTS - 1;
frac = pSpline->segments[pos].length;
} else {
frac = ((deltaTime * (MAX_SPLINE_SEGMENTS)) - pos) * pSpline->segments[pos].length;
}
VectorMA( pSpline->segments[pos].start, frac, pSpline->segments[pos].v_norm, result );
}
break;
default:
Com_Error( ERR_DROP, "BG_EvaluateTrajectory: unknown trType: %i", tr->trTime );
break;
}
}
/*
================
BG_EvaluateTrajectoryDelta
For determining velocity at a given time
================
*/
void BG_EvaluateTrajectoryDelta( const trajectory_t *tr, int atTime, vec3_t result, qboolean isAngle, int splineData ) {
float deltaTime;
float phase;
switch( tr->trType ) {
case TR_STATIONARY:
case TR_INTERPOLATE:
VectorClear( result );
break;
case TR_LINEAR:
VectorCopy( tr->trDelta, result );
break;
case TR_SINE:
deltaTime = ( atTime - tr->trTime ) / (float) tr->trDuration;
phase = cos( deltaTime * M_PI * 2 ); // derivative of sin = cos
phase *= 0.5;
VectorScale( tr->trDelta, phase, result );
break;
//----(SA) removed
case TR_LINEAR_STOP:
if ( atTime > tr->trTime + tr->trDuration ) {
VectorClear( result );
return;
}
VectorCopy( tr->trDelta, result );
break;
case TR_GRAVITY:
deltaTime = ( atTime - tr->trTime ) * 0.001; // milliseconds to seconds
VectorCopy( tr->trDelta, result );
result[2] -= DEFAULT_GRAVITY * deltaTime; // FIXME: local gravity...
break;
// Ridah
case TR_GRAVITY_LOW:
deltaTime = ( atTime - tr->trTime ) * 0.001; // milliseconds to seconds
VectorCopy( tr->trDelta, result );
result[2] -= (DEFAULT_GRAVITY * 0.3) * deltaTime; // FIXME: local gravity...
break;
// done.
//----(SA)
case TR_GRAVITY_FLOAT:
deltaTime = ( atTime - tr->trTime ) * 0.001; // milliseconds to seconds
VectorCopy( tr->trDelta, result );
result[2] -= (DEFAULT_GRAVITY * 0.2) * deltaTime;
break;
//----(SA) end
// RF, acceleration
case TR_ACCELERATE: // trDelta is eventual speed
if ( atTime > tr->trTime + tr->trDuration ) {
VectorClear( result );
return;
}
deltaTime = ( atTime - tr->trTime ) * 0.001; // milliseconds to seconds
phase = deltaTime / (float)tr->trDuration;
VectorScale( tr->trDelta, deltaTime * deltaTime, result );
break;
case TR_DECCELERATE: // trDelta is breaking force
if ( atTime > tr->trTime + tr->trDuration ) {
VectorClear( result );
return;
}
deltaTime = ( atTime - tr->trTime ) * 0.001; // milliseconds to seconds
VectorScale( tr->trDelta, deltaTime, result );
break;
case TR_SPLINE:
case TR_LINEAR_PATH:
VectorClear( result );
break;
default:
Com_Error( ERR_DROP, "BG_EvaluateTrajectoryDelta: unknown trType: %i", tr->trTime );
break;
}
}
/*
============
BG_GetMarkDir
used to find a good directional vector for a mark projection, which will be more likely
to wrap around adjacent surfaces
dir is the direction of the projectile or trace that has resulted in a surface being hit
============
*/
void BG_GetMarkDir( const vec3_t dir, const vec3_t normal, vec3_t out ) {
vec3_t ndir, lnormal;
float minDot = 0.3;
int x = 0;
if( dir[0] < 0.001 && dir[1] < 0.001 ) {
VectorCopy( dir, out );
return;
}
if( VectorLengthSquared( normal ) < SQR(1.f) ) { // this is needed to get rid of (0,0,0) normals (happens with entities?)
VectorSet( lnormal, 0.f, 0.f, 1.f );
} else {
//VectorCopy( normal, lnormal );
//VectorNormalizeFast( lnormal );
VectorNormalize2( normal, lnormal );
}
VectorNegate( dir, ndir );
VectorNormalize( ndir );
if( normal[2] > .8f ) {
minDot = .7f;
}
// make sure it makrs the impact surface
while( DotProduct( ndir, lnormal ) < minDot && x < 10 ) {
VectorMA( ndir, .5, lnormal, ndir );
VectorNormalize( ndir );
x++;
}
#ifdef GAMEDLL
if( x >= 10 ) {
if( g_developer.integer ) {
Com_Printf( "BG_GetMarkDir loops: %i\n", x );
}
}
#endif // GAMEDLL
VectorCopy( ndir, out );
}
char *eventnames[] = {
"EV_NONE",
"EV_DEATH1",
"EV_DEATH2",
"EV_DEATH3",
"EV_STEP_4",
"EV_STEP_8",
"EV_STEP_12",
"EV_STEP_16",
#include <bgame/bg_entity_event.cpp.inc>
"EV_MAX_EVENTS",
};
/*
===============
BG_AddPredictableEventToPlayerstate
Handles the sequence numbers
===============
*/
void trap_Cvar_VariableStringBuffer( const char *var_name, char *buffer, int bufsize );
void BG_AddPredictableEventToPlayerstate( int newEvent, int eventParm, playerState_t *ps ) {
#ifdef _DEBUG
{
char buf[256];
trap_Cvar_VariableStringBuffer("showevents", buf, sizeof(buf));
if ( atof(buf) != 0 ) {
#ifdef QAGAME
Com_Printf(" game event svt %5d -> %5d: num = %20s parm %d\n", ps->pmove_framecount/*ps->commandTime*/, ps->eventSequence, eventnames[newEvent], eventParm);
#else
Com_Printf("Cgame event svt %5d -> %5d: num = %20s parm %d\n", ps->pmove_framecount/*ps->commandTime*/, ps->eventSequence, eventnames[newEvent], eventParm);
#endif
}
}
#endif
ps->events[ps->eventSequence & (MAX_EVENTS-1)] = newEvent;
ps->eventParms[ps->eventSequence & (MAX_EVENTS-1)] = eventParm;
ps->eventSequence++;
}
// Gordon: would like to just inline this but would likely break qvm support
#define SETUP_MOUNTEDGUN_STATUS( ps ) \
switch( ps->persistant[PERS_HWEAPON_USE] ) { \
case 1: \
ps->eFlags |= EF_MG42_ACTIVE; \
ps->eFlags &= ~EF_AAGUN_ACTIVE; \
ps->powerups[PW_OPS_DISGUISED] = 0; \
break; \
case 2: \
ps->eFlags |= EF_AAGUN_ACTIVE; \
ps->eFlags &= ~EF_MG42_ACTIVE; \
ps->powerups[PW_OPS_DISGUISED] = 0; \
break; \
default: \
ps->eFlags &= ~EF_MG42_ACTIVE; \
ps->eFlags &= ~EF_AAGUN_ACTIVE; \
break; \
}
/*
========================
BG_PlayerStateToEntityState
This is done after each set of usercmd_t on the server,
and after local prediction on the client
========================
*/
void BG_PlayerStateToEntityState( playerState_t *ps, entityState_t *s, int time, qboolean snap ) {
int i;
if(ps->pm_type == PM_INTERMISSION || ps->pm_type == PM_SPECTATOR) {// || ps->pm_flags & PMF_LIMBO ) { // JPW NERVE limbo
s->eType = ET_INVISIBLE;
} else if ( ps->stats[STAT_HEALTH] <= GIB_HEALTH ) {
s->eType = ET_INVISIBLE;
} else {
s->eType = ET_PLAYER;
}
s->number = ps->clientNum;
s->pos.trType = TR_INTERPOLATE;
s->pos.trTime = time; // zinx - help out new synced animations.
VectorCopy( ps->origin, s->pos.trBase );
if ( snap ) {
SnapVector( s->pos.trBase );
}
s->apos.trType = TR_INTERPOLATE;
VectorCopy( ps->viewangles, s->apos.trBase );
if ( snap ) {
SnapVector( s->apos.trBase );
}
if (ps->movementDir > 128)
s->angles2[YAW] = (float)ps->movementDir - 256;
else
s->angles2[YAW] = ps->movementDir;
// Jaybird - lock the animation here so that the player does not flail
if(!(ps->eFlags & EF_PLAYDEAD)) {
s->legsAnim = ps->legsAnim;
s->torsoAnim = ps->torsoAnim;
s->clientNum = ps->clientNum; // ET_PLAYER looks here instead of at number
}
else {
s->apos.trBase[PITCH] = 0;
switch ( s->legsAnim & ~ANIM_TOGGLEBIT ) {
case BOTH_DEATH1:
case BOTH_DEAD1:
default:
s->torsoAnim = s->legsAnim = BOTH_DEAD1;
break;
case BOTH_DEATH2:
case BOTH_DEAD2:
s->torsoAnim = s->legsAnim = BOTH_DEAD2;
break;
case BOTH_DEATH3:
case BOTH_DEAD3:
s->torsoAnim = s->legsAnim = BOTH_DEAD3;
break;
}
}
// ET_PLAYER looks here instead of at number
// so corpses can also reference the proper config
// Ridah, let clients know if this person is using a mounted weapon
// so they don't show any client muzzle flashes
if( ps->eFlags & EF_MOUNTEDTANK ) {
ps->eFlags &= ~EF_MG42_ACTIVE;
ps->eFlags &= ~EF_AAGUN_ACTIVE;
} else {
SETUP_MOUNTEDGUN_STATUS( ps );
}
s->eFlags = ps->eFlags;
if ( ps->stats[STAT_HEALTH] <= 0 ) {
s->eFlags |= EF_DEAD;
} else {
s->eFlags &= ~EF_DEAD;
}
// from MP
if ( ps->externalEvent ) {
s->event = ps->externalEvent;
s->eventParm = ps->externalEventParm;
} else if ( ps->entityEventSequence < ps->eventSequence ) {
int seq;
if ( ps->entityEventSequence < ps->eventSequence - MAX_EVENTS) {
ps->entityEventSequence = ps->eventSequence - MAX_EVENTS;
}
seq = ps->entityEventSequence & (MAX_EVENTS-1);
s->event = ps->events[ seq ] | ( ( ps->entityEventSequence & 3 ) << 8 );
s->eventParm = ps->eventParms[ seq ];
ps->entityEventSequence++;
}
// end
// Ridah, now using a circular list of events for all entities
// add any new events that have been added to the playerState_t
// (possibly overwriting entityState_t events)
for (i = ps->oldEventSequence; i != ps->eventSequence; i++) {
s->events[s->eventSequence & (MAX_EVENTS-1)] = ps->events[i & (MAX_EVENTS-1)];
s->eventParms[s->eventSequence & (MAX_EVENTS-1)] = ps->eventParms[i & (MAX_EVENTS-1)];
s->eventSequence++;
}
ps->oldEventSequence = ps->eventSequence;
s->weapon = ps->weapon;
s->groundEntityNum = ps->groundEntityNum;
s->powerups = 0;
for ( i = 0 ; i < MAX_POWERUPS ; i++ ) {
if ( ps->powerups[ i ] ) {
s->powerups |= 1 << i;
}
}
s->nextWeapon = ps->nextWeapon; // Ridah
// s->loopSound = ps->loopSound;
s->teamNum = ps->teamNum;
s->aiState = ps->aiState; // xkan, 1/10/2003
}
/*
========================
BG_PlayerStateToEntityStateExtraPolate
This is done after each set of usercmd_t on the server,
and after local prediction on the client
========================
*/
void BG_PlayerStateToEntityStateExtraPolate( playerState_t *ps, entityState_t *s, int time, qboolean snap ) {
int i;
if(ps->pm_type == PM_INTERMISSION || ps->pm_type == PM_SPECTATOR) {// || ps->pm_flags & PMF_LIMBO ) { // JPW NERVE limbo
s->eType = ET_INVISIBLE;
} else if ( ps->stats[STAT_HEALTH] <= GIB_HEALTH ) {
s->eType = ET_INVISIBLE;
} else {
s->eType = ET_PLAYER;
}
s->number = ps->clientNum;
s->pos.trType = TR_LINEAR_STOP;
VectorCopy( ps->origin, s->pos.trBase );
if ( snap ) {
SnapVector( s->pos.trBase );
}
// set the trDelta for flag direction and linear prediction
VectorCopy( ps->velocity, s->pos.trDelta );
// set the time for linear prediction
s->pos.trTime = time;
// set maximum extra polation time
s->pos.trDuration = 50; // 1000 / sv_fps (default = 20)
s->apos.trType = TR_INTERPOLATE;
VectorCopy( ps->viewangles, s->apos.trBase );
if ( snap ) {
SnapVector( s->apos.trBase );
}
s->angles2[YAW] = ps->movementDir;
// Jaybird - lock the animation here so that the player does not flail
if(!(ps->eFlags & EF_PLAYDEAD)) {
s->legsAnim = ps->legsAnim;
s->torsoAnim = ps->torsoAnim;
s->clientNum = ps->clientNum; // ET_PLAYER looks here instead of at number
}
else {
s->apos.trBase[PITCH] = 0;
switch ( s->legsAnim & ~ANIM_TOGGLEBIT ) {
case BOTH_DEATH1:
case BOTH_DEAD1:
default:
s->torsoAnim = s->legsAnim = BOTH_DEAD1;
break;
case BOTH_DEATH2:
case BOTH_DEAD2:
s->torsoAnim = s->legsAnim = BOTH_DEAD2;
break;
case BOTH_DEATH3:
case BOTH_DEAD3:
s->torsoAnim = s->legsAnim = BOTH_DEAD3;
break;
}
}
// ET_PLAYER looks here instead of at number
// so corpses can also reference the proper config
if( ps->eFlags & EF_MOUNTEDTANK ) {
ps->eFlags &= ~EF_MG42_ACTIVE;
ps->eFlags &= ~EF_AAGUN_ACTIVE;
} else {
SETUP_MOUNTEDGUN_STATUS( ps );
}
s->eFlags = ps->eFlags;
if ( ps->stats[STAT_HEALTH] <= 0 ) {
s->eFlags |= EF_DEAD;
} else {
s->eFlags &= ~EF_DEAD;
}
if ( ps->externalEvent ) {
s->event = ps->externalEvent;
s->eventParm = ps->externalEventParm;
} else if ( ps->entityEventSequence < ps->eventSequence ) {
int seq;
if ( ps->entityEventSequence < ps->eventSequence - MAX_EVENTS) {
ps->entityEventSequence = ps->eventSequence - MAX_EVENTS;
}
seq = ps->entityEventSequence & (MAX_EVENTS-1);
s->event = ps->events[ seq ] | ( ( ps->entityEventSequence & 3 ) << 8 );
s->eventParm = ps->eventParms[ seq ];
ps->entityEventSequence++;
}
// Ridah, now using a circular list of events for all entities
// add any new events that have been added to the playerState_t
// (possibly overwriting entityState_t events)
for (i = ps->oldEventSequence; i != ps->eventSequence; i++) {
s->events[s->eventSequence & (MAX_EVENTS-1)] = ps->events[i & (MAX_EVENTS-1)];
s->eventParms[s->eventSequence & (MAX_EVENTS-1)] = ps->eventParms[i & (MAX_EVENTS-1)];
s->eventSequence++;
}
ps->oldEventSequence = ps->eventSequence;
s->weapon = ps->weapon;
s->groundEntityNum = ps->groundEntityNum;
s->powerups = 0;
for ( i = 0 ; i < MAX_POWERUPS ; i++ ) {
if ( ps->powerups[ i ] ) {
s->powerups |= 1 << i;
}
}
s->nextWeapon = ps->nextWeapon; // Ridah
s->teamNum = ps->teamNum;
s->aiState = ps->aiState; // xkan, 1/10/2003
}
// Gordon: some weapons are duplicated for code puposes.... just want to treat them as a single
weapon_t BG_DuplicateWeapon( weapon_t weap ) {
switch( weap ) {
case WP_M7: return WP_GPG40;
case WP_GARAND_SCOPE: return WP_GARAND;
case WP_K43_SCOPE: return WP_K43;
case WP_GRENADE_PINEAPPLE: return WP_GRENADE_LAUNCHER;
default: return weap;
}
}
gitem_t* BG_ValidStatWeapon( weapon_t weap ) {
weapon_t weap2;
switch(weap) {
case WP_MEDKIT:
case WP_PLIERS:
case WP_SMOKETRAIL:
case WP_MEDIC_SYRINGE:
case WP_SMOKE_BOMB:
case WP_POISON_GAS:
case WP_AMMO:
return NULL;
default:
break;
}
if(!BG_WeaponInWolfMP(weap)) {
return NULL;
}
weap2 = BG_DuplicateWeapon( weap );
if( weap != weap2 ) {
return NULL;
}
return BG_FindItemForWeapon( weap );
}
weapon_t BG_WeaponForMOD( int MOD ) {
weapon_t i;
for(i = WP_NONE; i < WP_NUM_WEAPONS; i = (weapon_t)( i+1 )) {
if(GetAmmoTableData(i)->mod == MOD) {
return i;
}
}
return WP_NONE;
}
const char* rankSoundNames_Allies[NUM_EXPERIENCE_LEVELS] = {
"",
"allies_hq_promo_private",
"allies_hq_promo_corporal",
"allies_hq_promo_sergeant",
"allies_hq_promo_lieutenant",
"allies_hq_promo_captain",
"allies_hq_promo_major",
"allies_hq_promo_colonel",
"allies_hq_promo_general_brigadier",
"allies_hq_promo_general_lieutenant",
"allies_hq_promo_general",
};
const char* rankSoundNames_Axis[NUM_EXPERIENCE_LEVELS] = {
"",
"axis_hq_promo_private",
"axis_hq_promo_corporal",
"axis_hq_promo_sergeant",
"axis_hq_promo_lieutenant",
"axis_hq_promo_captain",
"axis_hq_promo_major",
"axis_hq_promo_colonel",
"axis_hq_promo_general_major",
"axis_hq_promo_general_lieutenant",
"axis_hq_promo_general",
};
const char* rankNames_Axis[NUM_EXPERIENCE_LEVELS] = {
"Schutze",
"Oberschutze",
"Gefreiter",
"Feldwebel",
"Leutnant",
"Hauptmann",
"Major",
"Oberst",
"Generalmajor",
"Generalleutnant",
"General",
};
const char* rankNames_Allies[NUM_EXPERIENCE_LEVELS] = {
"Private",
"Private 1st Class",
"Corporal",
"Sergeant",
"Lieutenant",
"Captain",
"Major",
"Colonel",
"Brigadier General",
"Lieutenant General",
"General",
};
const char* miniRankNames_Axis[NUM_EXPERIENCE_LEVELS] = {
"Stz",
"Otz",
"Gfr",
"Fwb",
"Ltn",
"Hpt",
"Mjr",
"Obs",
"BGn",
"LtG",
"Gen",
};
const char* miniRankNames_Allies[NUM_EXPERIENCE_LEVELS] = {
"Pvt",
"PFC",
"Cpl",
"Sgt",
"Lt",
"Cpt",
"Maj",
"Cnl",
"GMj",
"GLt",
"Gen",
};
/*
=============
BG_Find_PathCorner
=============
*/
pathCorner_t *BG_Find_PathCorner (const char *match)
{
int i;
for (i = 0 ; i < numPathCorners; i++) {
if (!Q_stricmp (pathCorners[i].name, match))
return &pathCorners[i];
}
return NULL;
}
/*
=============
BG_AddPathCorner
=============
*/
void BG_AddPathCorner(const char* name, vec3_t origin) {
if(numPathCorners >= MAX_PATH_CORNERS ) {
Com_Error( ERR_DROP, "MAX PATH CORNERS (%i) hit", MAX_PATH_CORNERS );
}
VectorCopy( origin, pathCorners[numPathCorners].origin );
Q_strncpyz( pathCorners[numPathCorners].name, name, 64 );
numPathCorners++;
}
/*
=============
BG_Find_Spline
=============
*/
splinePath_t *BG_Find_Spline (const char *match) {
int i;
for (i = 0 ; i < numSplinePaths; i++) {
if (!Q_stricmp (splinePaths[i].point.name, match))
return &splinePaths[i];
}
return NULL;
}
splinePath_t* BG_AddSplinePath(const char* name, const char* target, vec3_t origin) {
splinePath_t* spline;
if(numSplinePaths >= MAX_SPLINE_PATHS) {
Com_Error( ERR_DROP, "MAX SPLINES (%i) hit", MAX_SPLINE_PATHS );
}
spline = &splinePaths[numSplinePaths];
memset( spline, 0, sizeof( splinePath_t ) );
VectorCopy( origin, spline->point.origin );
Q_strncpyz( spline->point.name, name, 64 );
Q_strncpyz( spline->strTarget, target ? target : "", 64 );
spline->numControls = 0;
numSplinePaths++;
return spline;
}
void BG_AddSplineControl(splinePath_t* spline, const char* name) {
if(spline->numControls >= MAX_SPLINE_CONTROLS) {
Com_Error( ERR_DROP, "MAX SPLINE CONTROLS (%i) hit", MAX_SPLINE_CONTROLS );
}
Q_strncpyz( spline->controls[spline->numControls].name, name, 64 );
spline->numControls++;
}
float BG_SplineLength(splinePath_t* pSpline) {
float i;
float granularity = 0.01f;
float dist = 0;
// float tension;
vec3_t vec[2];
vec3_t lastPoint = { 0.0f, 0.0f, 0.0f };
vec3_t result;
for(i = 0; i <= 1.f; i += granularity ) {
/* if(pSpline->isStart) {
tension = 1 - sin((1 - i) * M_PI * 0.5f);
} else if(pSpline->isEnd) {
tension = sin(i * M_PI * 0.5f);
} else {
tension = i;
}*/
BG_CalculateSpline_r( pSpline, vec[0], vec[1], i );
VectorSubtract( vec[1], vec[0], result );
VectorMA(vec[0], i, result, result);
if( i != 0 ) {
VectorSubtract( result, lastPoint, vec[0] );
dist += VectorLength( vec[0] );
}
VectorCopy( result, lastPoint );
}
return dist;
}
void BG_BuildSplinePaths() {
int i, j;
pathCorner_t* pnt;
splinePath_t *spline, *st;
for( i = 0; i < numSplinePaths; i++ ) {
spline = &splinePaths[i];
if(*spline->strTarget) {
for( j = 0; j < spline->numControls; j++) {
pnt = BG_Find_PathCorner( spline->controls[j].name );
if( !pnt ) {
Com_Printf( "^1Cant find control point (%s) for spline (%s)\n", spline->controls[j].name, spline->point.name );
// Gordon: Just changing to a warning for now, easier for region compiles...
continue;
} else {
VectorCopy( pnt->origin, spline->controls[j].origin );
}
}
st = BG_Find_Spline( spline->strTarget );
if( !st ) {
Com_Printf( "^1Cant find target point (%s) for spline (%s)\n", spline->strTarget, spline->point.name );
// Gordon: Just changing to a warning for now, easier for region compiles...
continue;
}
spline->next = st;
spline->length = BG_SplineLength(spline);
BG_ComputeSegments( spline );
}
}
for( i = 0; i < numSplinePaths; i++ ) {
spline = &splinePaths[i];
if(spline->next) {
spline->next->prev = spline;
}
}
}
splinePath_t* BG_GetSplineData( int number, qboolean* backwards ) {
if( number < 0 ) {
*backwards = qtrue;
number = -number;
} else {
*backwards = qfalse;
}
number--;
if( number < 0 || number >= numSplinePaths ) {
return NULL;
}
return &splinePaths[number];
}
int BG_MaxAmmoForWeapon( weapon_t weaponNum, int *skill ) {
switch( weaponNum ) {
//case WP_KNIFE:
case WP_LUGER:
case WP_COLT:
case WP_STEN:
case WP_SILENCER:
case WP_CARBINE:
case WP_KAR98:
case WP_SILENCED_COLT:
if( skill[SK_LIGHT_WEAPONS] >= 1 )
return( GetAmmoTableData(weaponNum)->maxammo + GetAmmoTableData(weaponNum)->maxclip );
else
return( GetAmmoTableData(weaponNum)->maxammo );
break;
case WP_MP40:
case WP_THOMPSON:
case WP_M97:
if( skill[SK_FIRST_AID] >= 1 || skill[SK_LIGHT_WEAPONS] >= 1 )
return( GetAmmoTableData(weaponNum)->maxammo + GetAmmoTableData(weaponNum)->maxclip );
else
return( GetAmmoTableData(weaponNum)->maxammo );
break;
case WP_M7:
case WP_GPG40:
if( skill[SK_EXPLOSIVES_AND_CONSTRUCTION] >= 1 )
return( GetAmmoTableData(weaponNum)->maxammo + 4 );
else
return( GetAmmoTableData(weaponNum)->maxammo );
break;
case WP_GRENADE_PINEAPPLE:
case WP_GRENADE_LAUNCHER:
// FIXME: this is class dependant, not ammo table
if( skill[SK_EXPLOSIVES_AND_CONSTRUCTION] >= 1 )
return( GetAmmoTableData(weaponNum)->maxammo + 4 );
else if( skill[SK_FIRST_AID] >= 1 )
return( GetAmmoTableData(weaponNum)->maxammo + 1 );
else
return( GetAmmoTableData(weaponNum)->maxammo );
break;
/*case WP_MOBILE_MG42:
case WP_PANZERFAUST:
case WP_FLAMETHROWER:
if( skill[SK_HEAVY_WEAPONS] >= 1 )
return( GetAmmoTableData(weaponNum)->maxammo + GetAmmoTableData(weaponNum)->maxclip );
else
return( GetAmmoTableData(weaponNum)->maxammo );
break;
case WP_MORTAR:
case WP_MORTAR_SET:
if( skill[SK_HEAVY_WEAPONS] >= 1 )
return( GetAmmoTableData(weaponNum)->maxammo + 2 );
else
return( GetAmmoTableData(weaponNum)->maxammo );
break;*/
case WP_MEDIC_SYRINGE:
if( skill[SK_FIRST_AID] >= 2 )
return( GetAmmoTableData(weaponNum)->maxammo + 2 );
else
return( GetAmmoTableData(weaponNum)->maxammo );
break;
case WP_GARAND:
case WP_K43:
case WP_FG42:
if( skill[SK_MILITARY_INTELLIGENCE_AND_SCOPED_WEAPONS] >= 1 || skill[SK_LIGHT_WEAPONS] >= 1 )
return( GetAmmoTableData(weaponNum)->maxammo + GetAmmoTableData(weaponNum)->maxclip );
else
return( GetAmmoTableData(weaponNum)->maxammo );
break;
case WP_GARAND_SCOPE:
case WP_K43_SCOPE:
case WP_FG42SCOPE:
if( skill[SK_MILITARY_INTELLIGENCE_AND_SCOPED_WEAPONS] >= 1 )
return( GetAmmoTableData(weaponNum)->maxammo + GetAmmoTableData(weaponNum)->maxclip );
else
return( GetAmmoTableData(weaponNum)->maxammo );
break;
default:
break;
}
return( GetAmmoTableData(weaponNum)->maxammo );
}
/*
================
BG_CreateRotationMatrix
================
*/
void BG_CreateRotationMatrix(const vec3_t angles, vec3_t matrix[3]) {
AngleVectors(angles, matrix[0], matrix[1], matrix[2]);
VectorInverse(matrix[1]);
}
/*
================
BG_TransposeMatrix
================
*/
void BG_TransposeMatrix(const vec3_t matrix[3], vec3_t transpose[3]) {
int i, j;
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
transpose[i][j] = matrix[j][i];
}
}
}
/*
================
BG_RotatePoint
================
*/
void BG_RotatePoint(vec3_t point, const vec3_t matrix[3]) {
vec3_t tvec;
VectorCopy(point, tvec);
point[0] = DotProduct(matrix[0], tvec);
point[1] = DotProduct(matrix[1], tvec);
point[2] = DotProduct(matrix[2], tvec);
}
/*
================
BG_AdjustAAGunMuzzleForBarrel
================
*/
void BG_AdjustAAGunMuzzleForBarrel( vec_t* origin, vec_t* forward, vec_t* right, vec_t* up, int barrel ) {
switch( barrel ) {
case 0:
VectorMA( origin, 64, forward, origin );
VectorMA( origin, 20, right, origin );
VectorMA( origin, 40, up, origin );
break;
case 1:
VectorMA( origin, 64, forward, origin );
VectorMA( origin, 20, right, origin );
VectorMA( origin, 20, up, origin );
break;
case 2:
VectorMA( origin, 64, forward, origin );
VectorMA( origin, -20, right, origin );
VectorMA( origin, 40, up, origin );
break;
case 3:
VectorMA( origin, 64, forward, origin );
VectorMA( origin, -20, right, origin );
VectorMA( origin, 20, up, origin );
break;
}
}
/*
=================
PC_SourceWarning
=================
*/
void PC_SourceWarning(int handle, char *format, ...) {
int line;
char filename[128];
va_list argptr;
static char string[4096];
va_start (argptr, format);
Q_vsnprintf (string, sizeof(string), format, argptr);
va_end (argptr);
filename[0] = '\0';
line = 0;
trap_PC_SourceFileAndLine(handle, filename, &line);
Com_Printf(S_COLOR_YELLOW "WARNING: %s, line %d: %s\n", filename, line, string);
}
/*
=================
PC_SourceError
=================
*/
void PC_SourceError(int handle, char *format, ...) {
int line;
char filename[128];
va_list argptr;
static char string[4096];
va_start (argptr, format);
Q_vsnprintf (string, sizeof(string), format, argptr);
va_end (argptr);
filename[0] = '\0';
line = 0;
trap_PC_SourceFileAndLine(handle, filename, &line);
#ifdef GAMEDLL
Com_Error( ERR_DROP, S_COLOR_RED "ERROR: %s, line %d: %s\n", filename, line, string);
#else
Com_Printf(S_COLOR_RED "ERROR: %s, line %d: %s\n", filename, line, string);
#endif
}
/*
=================
PC_Float_Parse
=================
*/
qboolean PC_Float_Parse(int handle, float *f) {
pc_token_t token;
int negative = qfalse;
if (!trap_PC_ReadToken(handle, &token))
return qfalse;
if (token.string[0] == '-') {
if (!trap_PC_ReadToken(handle, &token))
return qfalse;
negative = qtrue;
}
if (token.type != TT_NUMBER) {
PC_SourceError(handle, "expected float but found %s\n", token.string);
return qfalse;
}
if (negative)
*f = -token.floatvalue;
else
*f = token.floatvalue;
return qtrue;
}
/*
=================
PC_Color_Parse
=================
*/
qboolean PC_Color_Parse(int handle, vec4_t *c) {
int i;
float f;
for (i = 0; i < 4; i++) {
if (!PC_Float_Parse(handle, &f)) {
return qfalse;
}
(*c)[i] = f;
}
return qtrue;
}
/*
=================
PC_Vec_Parse
=================
*/
qboolean PC_Vec_Parse(int handle, vec3_t *c) {
int i;
float f;
for (i = 0; i < 3; i++) {
if (!PC_Float_Parse(handle, &f)) {
return qfalse;
}
(*c)[i] = f;
}
return qtrue;
}
/*
=================
PC_Int_Parse
=================
*/
qboolean PC_Int_Parse(int handle, int *i) {
pc_token_t token;
int negative = qfalse;
if (!trap_PC_ReadToken(handle, &token))
return qfalse;
if (token.string[0] == '-') {
if (!trap_PC_ReadToken(handle, &token))
return qfalse;
negative = qtrue;
}
if (token.type != TT_NUMBER) {
PC_SourceError(handle, "expected integer but found %s\n", token.string);
return qfalse;
}
*i = token.intvalue;
if (negative)
*i = - *i;
return qtrue;
}
#ifdef GAMEDLL
/*
=================
PC_String_Parse
=================
*/
const char* PC_String_Parse(int handle) {
static char buf[MAX_TOKEN_CHARS];
pc_token_t token;
if (!trap_PC_ReadToken(handle, &token))
return NULL;
Q_strncpyz( buf, token.string, MAX_TOKEN_CHARS );
return buf;
}
#else
/*
=================
PC_String_Parse
=================
*/
qboolean PC_String_Parse(int handle, const char **out) {
pc_token_t token;
if (!trap_PC_ReadToken(handle, &token))
return qfalse;
*(out) = String_Alloc(token.string);
return qtrue;
}
#endif
/*
=================
PC_String_ParseNoAlloc
Same as one above, but uses a static buff and not the string memory pool
=================
*/
qboolean PC_String_ParseNoAlloc(int handle, char *out, size_t size) {
pc_token_t token;
if( !trap_PC_ReadToken(handle, &token) )
return qfalse;
Q_strncpyz( out, token.string, size );
return qtrue;
}
const char* bg_fireteamNames[MAX_FIRETEAMS / 2] = {
"Alpha",
"Bravo",
"Charlie",
"Delta",
"Echo",
"Foxtrot",
};
const voteType_t voteToggles[] =
{
{ "vote_allow_comp", CV_SVF_COMP },
{ "vote_allow_gametype", CV_SVF_GAMETYPE },
{ "vote_allow_kick", CV_SVF_KICK },
{ "vote_allow_map", CV_SVF_MAP },
{ "vote_allow_matchreset", CV_SVF_MATCHRESET },
{ "vote_allow_mutespecs", CV_SVF_MUTESPECS },
{ "vote_allow_nextmap", CV_SVF_NEXTMAP },
{ "vote_allow_pub", CV_SVF_PUB },
{ "vote_allow_referee", CV_SVF_REFEREE },
{ "vote_allow_shuffleteamsxp", CV_SVF_SHUFFLETEAMS },
{ "vote_allow_swapteams", CV_SVF_SWAPTEAMS },
{ "vote_allow_friendlyfire", CV_SVF_FRIENDLYFIRE },
{ "vote_allow_timelimit", CV_SVF_TIMELIMIT },
{ "vote_allow_warmupdamage", CV_SVF_WARMUPDAMAGE },
{ "vote_allow_balancedteams", CV_SVF_BALANCEDTEAMS },
{ "vote_allow_muting", CV_SVF_MUTING },
{ "vote_allow_generic", CV_SVF_GENERIC },
{ "vote_allow_matchrestart", CV_SVF_MATCHRESTART },
{ "vote_allow_startmatch", CV_SVF_STARTMATCH }
};
int numVotesAvailable = sizeof(voteToggles) / sizeof(voteType_t);
// consts to offset random reinforcement seeds
const unsigned int aReinfSeeds[MAX_REINFSEEDS] = { 11, 3, 13, 7, 2, 5, 1, 17 };
// Weapon full names + headshot capability
const weap_ws_t aWeaponInfo[WS_MAX] = {
{ qfalse, "KNIF", "Knife" }, // 0
{ qtrue, "LUGR", "Luger" }, // 1
{ qtrue, "COLT", "Colt" }, // 2
{ qtrue, "MP40", "MP-40" }, // 3
{ qtrue, "TMPS", "Thompson" }, // 4
{ qtrue, "STEN", "Sten" }, // 5
{ qtrue, "FG42", "FG-42" }, // 6
{ qtrue, "PNZR", "Panzer" }, // 7
{ qtrue, "FLAM", "F.Thrower" }, // 8
{ qfalse, "GRND", "Grenade" }, // 9
{ qfalse, "MRTR", "Mortar" }, // 10
{ qfalse, "DYNA", "Dynamite" }, // 11
{ qfalse, "ARST", "Airstrike" }, // 12
{ qfalse, "ARTY", "Artillery" }, // 13
{ qfalse, "SRNG", "Syringe" }, // 14
{ qfalse, "SMOK", "SmokeScrn" }, // 15
{ qfalse, "STCH", "Satchel" }, // 16
{ qfalse, "GRLN", "G.Launchr" }, // 17
{ qfalse, "LNMN", "Landmine" }, // 18
{ qtrue, "MG42", "MG-42 Gun" }, // 19
{ qtrue, "GARN", "Garand" }, // 20
{ qtrue, "K-43", "K43 Rifle" }, // 21
{ qfalse, "POIS", "PoisonSyr" }, // 22
{ qfalse, "THKN", "Th. Knife" }, // 23
{ qfalse, "M-97", "M-97" }, // 24
{ qfalse, "PGAS", "PoisonGas" }, // 25
{ qfalse, "GMBA", "Goomba" }, // 26
{ qfalse, "MTOV", "Molotov" }, // 27
};
// Multiview: Convert weaponstate to simpler format
int BG_simpleWeaponState(int ws)
{
switch(ws)
{
case WEAPON_READY:
case WEAPON_READYING:
case WEAPON_RELAXING:
return(WSTATE_IDLE);
case WEAPON_RAISING:
case WEAPON_DROPPING:
case WEAPON_DROPPING_TORELOAD:
return(WSTATE_SWITCH);
case WEAPON_FIRING:
case WEAPON_FIRINGALT:
return(WSTATE_FIRE);
case WEAPON_RELOADING:
return(WSTATE_RELOAD);
}
return(WSTATE_IDLE);
}
// Multiview: Reduce hint info to 2 bits. However, we can really
// have up to 8 values, as some hints will have a 0 value for
// cursorHintVal
int BG_simpleHintsCollapse(int hint, int val)
{
switch(hint) {
case HINT_DISARM:
if(val > 0) return(0);
case HINT_BUILD:
if(val > 0) return(1);
case HINT_BREAKABLE:
if(val == 0) return(1);
case HINT_DOOR_ROTATING:
case HINT_BUTTON:
case HINT_MG42:
if(val == 0) return(2);
case HINT_BREAKABLE_DYNAMITE:
if(val == 0) return(3);
}
return(0);
}
// Multiview: Expand the hints. Because we map a couple hints
// into a single value, we can't replicate the proper hint back
// in all cases.
int BG_simpleHintsExpand(int hint, int val)
{
switch(hint) {
case 0: return((val >= 0) ? HINT_DISARM : 0);
case 1: return((val >= 0) ? HINT_BUILD : HINT_BREAKABLE);
case 2: return((val >= 0) ? HINT_BUILD : HINT_MG42);
case 3: return((val >= 0) ? HINT_BUILD : HINT_BREAKABLE_DYNAMITE);
}
return(0);
}
// Real printable charater count
int BG_drawStrlen(const char *str)
{
int cnt = 0;
while(*str) {
if(Q_IsColorString(str)) str += 2;
else {
cnt++;
str++;
}
}
return(cnt);
}
// Copies a color string, with limit of real chars to print
// in = reference buffer w/color
// out = target buffer
// str_max = max size of printable string
// out_max = max size of target buffer
//
// Returns size of printable string
int BG_colorstrncpyz(char *in, char *out, int str_max, int out_max)
{
int str_len = 0; // current printable string size
int out_len = 0; // current true string size
const int in_len = strlen(in);
out_max--;
while(*in && out_len < out_max && str_len < str_max) {
if(*in == '^') {
if(out_len + 2 >= in_len && out_len + 2 >= out_max)
break;
*out++ = *in++;
*out++ = *in++;
out_len += 2;
continue;
}
*out++ = *in++;
str_len++;
out_len++;
}
*out = 0;
return(str_len);
}
int BG_strRelPos(char *in, int index)
{
int cPrintable = 0;
const char *ref = in;
while(*ref && cPrintable < index) {
if(Q_IsColorString(ref)) ref += 2;
else {
ref++;
cPrintable++;
}
}
return(ref - in);
}
// strip colors and control codes, copying up to dwMaxLength-1 "good" chars and nul-terminating
// returns the length of the cleaned string
// CHRUKER: b069 - Cleaned up a few compiler warnings
int BG_cleanName( const char *pszIn, char *pszOut, int dwMaxLength, qboolean fCRLF )
{
const char *pInCopy = pszIn;
const char *pszOutStart = pszOut;
while( *pInCopy && ( pszOut - pszOutStart < dwMaxLength - 1 ) ) {
if( *pInCopy == '^' )
pInCopy += ((pInCopy[1] == 0) ? 1 : 2);
else if( (*pInCopy < 32 && (!fCRLF || *pInCopy != '\n')) || (*pInCopy > 126))
pInCopy++;
else
*pszOut++ = *pInCopy++;
}
*pszOut = 0;
return( pszOut - pszOutStart );
}
// Only used locally
typedef struct {
char *colorname;
vec4_t *color;
} colorTable_t;
// Colors for crosshairs
colorTable_t OSP_Colortable[] =
{
{ "white", &colorWhite },
{ "red", &colorRed },
{ "green", &colorGreen },
{ "blue", &colorBlue },
{ "yellow", &colorYellow },
{ "magenta", &colorMagenta },
{ "cyan", &colorCyan },
{ "orange", &colorOrange },
{ "mdred", &colorMdRed },
{ "mdgreen", &colorMdGreen },
{ "dkgreen", &colorDkGreen },
{ "mdcyan", &colorMdCyan },
{ "mdyellow", &colorMdYellow },
{ "mdorange", &colorMdOrange },
{ "mdblue", &colorMdBlue },
{ "ltgrey", &colorLtGrey },
{ "mdgrey", &colorMdGrey },
{ "dkgrey", &colorDkGrey },
{ "black", &colorBlack },
{ NULL, NULL }
};
extern void trap_Cvar_Set( const char *var_name, const char *value );
void BG_setCrosshair(char *colString, float *col, float alpha, char *cvarName)
{
char *s = colString;
col[0] = 1.0f;
col[1] = 1.0f;
col[2] = 1.0f;
col[3] = (alpha > 1.0f) ? 1.0f : (alpha < 0.0f) ? 0.0f : alpha;
if(*s == '0' && (*(s+1) == 'x' || *(s+1) == 'X')) {
s +=2;
//parse rrggbb
if(Q_IsHexColorString(s)) {
col[0] = ((float)(gethex(*(s)) * 16 + gethex(*(s+1)))) / 255.00;
col[1] = ((float)(gethex(*(s+2)) * 16 + gethex(*(s+3)))) / 255.00;
col[2] = ((float)(gethex(*(s+4)) * 16 + gethex(*(s+5)))) / 255.00;
return;
}
} else {
int i = 0;
while(OSP_Colortable[i].colorname != NULL) {
if(Q_stricmp(s, OSP_Colortable[i].colorname) == 0) {
col[0] = (*OSP_Colortable[i].color)[0];
col[1] = (*OSP_Colortable[i].color)[1];
col[2] = (*OSP_Colortable[i].color)[2];
return;
}
i++;
}
}
trap_Cvar_Set(cvarName, "White");
}
qboolean BG_isLightWeaponSupportingFastReload( int weapon ) {
if( weapon == WP_LUGER ||
weapon == WP_COLT ||
weapon == WP_MP40 ||
weapon == WP_THOMPSON ||
weapon == WP_STEN ||
weapon == WP_SILENCER ||
weapon == WP_FG42 ||
weapon == WP_SILENCED_COLT )
return qtrue;
return qfalse;
}
qboolean BG_IsScopedWeapon( int weapon ) {
switch( weapon ) {
case WP_GARAND_SCOPE:
case WP_K43_SCOPE:
case WP_FG42SCOPE:
return qtrue;
}
return qfalse;
}
///////////////////////////////////////////////////////////////////////////////
typedef struct locInfo_s {
vec2_t gridStartCoord;
vec2_t gridStep;
} locInfo_t;
static locInfo_t locInfo;
void BG_InitLocations( vec2_t world_mins, vec2_t world_maxs )
{
// keep this in sync with CG_DrawGrid
locInfo.gridStep[0] = 1200.f;
locInfo.gridStep[1] = 1200.f;
// ensure minimal grid density
while( ( world_maxs[0] - world_mins[0] ) / locInfo.gridStep[0] < 7 )
locInfo.gridStep[0] -= 50.f;
while( ( world_mins[1] - world_maxs[1] ) / locInfo.gridStep[1] < 7 )
locInfo.gridStep[1] -= 50.f;
locInfo.gridStartCoord[0] = world_mins[0] + .5f * ( ( ( ( world_maxs[0] - world_mins[0] ) / locInfo.gridStep[0] ) - ( (int)(( world_maxs[0] - world_mins[0] ) / locInfo.gridStep[0] ) ) ) * locInfo.gridStep[0] );
locInfo.gridStartCoord[1] = world_mins[1] - .5f * ( ( ( ( world_mins[1] - world_maxs[1] ) / locInfo.gridStep[1] ) - ( (int)(( world_mins[1] - world_maxs[1] ) / locInfo.gridStep[1] ) ) ) * locInfo.gridStep[1] );
}
char *BG_GetLocationString( vec_t* pos )
{
static char coord[6];
int x, y;
coord[0] = '\0';
x = (int)( (pos[0] - locInfo.gridStartCoord[0]) / locInfo.gridStep[0] );
y = (int)( (locInfo.gridStartCoord[1] - pos[1]) / locInfo.gridStep[1] );
if( x < 0 ) x = 0;
if( y < 0 ) y = 0;
Com_sprintf( coord, sizeof(coord), "%c,%i", 'A' + x, y );
return coord;
}
qboolean BG_BBoxCollision( vec3_t min1, vec3_t max1, vec3_t min2, vec3_t max2 ) {
int i;
for( i = 0; i < 3; i++ ) {
if( min1[i] > max2[i] ) {
return qfalse;
}
if( min2[i] > max1[i] ) {
return qfalse;
}
}
return qtrue;
}
weapon_t bg_heavyWeapons[NUM_HEAVY_WEAPONS] = {
WP_FLAMETHROWER,
WP_MOBILE_MG42,
WP_MOBILE_MG42_SET,
WP_PANZERFAUST,
WP_MORTAR,
WP_MORTAR_SET
};
/////////////////////////
int BG_FootstepForSurface( int surfaceFlags ) {
if ( surfaceFlags & SURF_NOSTEPS ) {
return FOOTSTEP_TOTAL;
}
if ( surfaceFlags & SURF_METAL ) {
return FOOTSTEP_METAL;
}
if ( surfaceFlags & SURF_WOOD ) {
return FOOTSTEP_WOOD;
}
if ( surfaceFlags & SURF_GRASS ) {
return FOOTSTEP_GRASS;
}
if ( surfaceFlags & SURF_GRAVEL ) {
return FOOTSTEP_GRAVEL;
}
if ( surfaceFlags & SURF_ROOF ) {
return FOOTSTEP_ROOF;
}
if ( surfaceFlags & SURF_SNOW ) {
return FOOTSTEP_SNOW;
}
if ( surfaceFlags & SURF_CARPET ) {
return FOOTSTEP_CARPET;
}
if ( surfaceFlags & SURF_SPLASH ) {
return FOOTSTEP_SPLASH;
}
return FOOTSTEP_NORMAL;
}
/*
============
Q_vsnprintf
vsnprintf portability:
C99 standard: vsnprintf returns the number of characters (excluding the trailing
'\0') which would have been written to the final string if enough space had been available
snprintf and vsnprintf do not write more than size bytes (including the trailing '\0')
win32: _vsnprintf returns the number of characters written, not including the terminating null character,
or a negative value if an output error occurs. If the number of characters to write exceeds count,
then count characters are written and -1 is returned and no trailing '\0' is added.
Q_vsnPrintf: always append a trailing '\0', returns number of characters written or
returns -1 on failure or if the buffer would be overflowed.
copied over from common.c implementation
============
*/
int Q_vsnprintf( char *dest, int size, const char *fmt, va_list argptr ) {
int ret;
#ifdef _WIN32
#undef _vsnprintf
ret = _vsnprintf( dest, size-1, fmt, argptr );
#define _vsnprintf use_idStr_vsnPrintf
#else
#undef vsnprintf
ret = vsnprintf( dest, size, fmt, argptr );
#define vsnprintf use_idStr_vsnPrintf
#endif
dest[size-1] = '\0';
if ( ret < 0 || ret >= size ) {
return -1;
}
return ret;
}
| 24.121322
| 235
| 0.60807
|
jumptohistory
|
3e3bf20cc9a5f0a8537791823182aee5be3bc681
| 18,624
|
cpp
|
C++
|
WorkScript/Function/FunctionFragment.cpp
|
jingjiajie/WorkScript
|
6b80932fcdbae0e915c37bac19d262025234074b
|
[
"MIT"
] | 3
|
2018-07-23T10:59:00.000Z
|
2019-04-05T04:57:19.000Z
|
WorkScript/Function/FunctionFragment.cpp
|
jingjiajie/WorkScript
|
6b80932fcdbae0e915c37bac19d262025234074b
|
[
"MIT"
] | null | null | null |
WorkScript/Function/FunctionFragment.cpp
|
jingjiajie/WorkScript
|
6b80932fcdbae0e915c37bac19d262025234074b
|
[
"MIT"
] | 1
|
2019-06-28T05:57:47.000Z
|
2019-06-28T05:57:47.000Z
|
#include "Variable.h"
#include "FunctionFragment.h"
#include "InstantialContext.h"
#include "ParameterDecl.h"
#include "Locales.h"
#include "Exception.h"
#include "Function.h"
#include "MultiValue.h"
#include "GeneralSymbolInfo.h"
using namespace WorkScript;
using namespace std;
FunctionFragment::FunctionFragment(const DebugInfo &d,
AbstractContext *ctx,
const std::wstring &name,
const std::vector<ParameterDecl*> ¶ms,
bool isConst,
bool isRuntimeVarargs,
const std::optional<std::wstring> &staticVarargsName,
const LinkageType <,
const std::vector<Expression*>& constraints,
const std::vector<Expression*>& implements,
Type *declReturnType) noexcept
:name(name), context(d, ctx, ctx->getFunctionFragmentCount()),parameters(params),declReturnType(declReturnType),
_staticVarargs(staticVarargsName.has_value()), staticVarargsName(staticVarargsName.value_or(L"")), _runtimeVarargs(isRuntimeVarargs),
_const(isConst), linkageType(lt), constraints(constraints), implements(implements)
{
}
WorkScript::FunctionFragment::~FunctionFragment() noexcept
{
for (auto expr : this->constraints) {
delete expr;
}
for (auto expr : this->implements) {
delete expr;
}
}
Type * FunctionFragment::getReturnType(const DebugInfo &d, InstantialContext * ctx, const std::vector<Type*> ¶mTypes)
{
if(this->declReturnType) return this->declReturnType;
size_t implCount = this->implements.size();
if (implCount == 0)return VoidType::get();
size_t realParamCount = paramTypes.size();
InstantialContext innerCtx(&this->context, ctx);
if(this->_staticVarargs) innerCtx.setBlockAttribute(BlockAttributeItem::SFINAE, true);
auto &instSymbolTable = *innerCtx.getInstanceSymbolTable();
for (size_t i = 0; i < this->parameters.size(); ++i) {
//获取当前分支参数的符号信息,加入符号表
ParameterDecl *myParam = this->parameters[i];
Type *curParamType = nullptr;
if (i < realParamCount) {
if (myParam->getType()) {
curParamType = myParam->getType();
} else {
curParamType = paramTypes[i];
}
} else {
curParamType = myParam->getDefaultValue()->deduce(ctx);
}
instSymbolTable.setSymbol(
GeneralSymbolInfo(d, myParam->getName(), ValueDescriptor(curParamType, ValueKind::VALUE),
LinkageType::INTERNAL));
}
//处理可能的变参情况,注意参数个数相等的情况也要处理变参,此时变参匹配数量为0
if (this->_staticVarargs)
{
long varargLen = paramTypes.size() - this->parameters.size();
if(varargLen < 0){
varargLen = 0;
}
vector<Type *> varargItemTypes;
varargItemTypes.insert(varargItemTypes.end(), paramTypes.begin() + (paramTypes.size() - varargLen),
paramTypes.end());
vector<ValueDescriptor> varargItemDescs;
varargItemDescs.reserve(varargItemTypes.size());
for(size_t i=0; i<varargItemTypes.size(); ++i){
varargItemDescs.push_back(ValueDescriptor(varargItemTypes[i], ValueKind::VARIABLE));
}
instSymbolTable.setSymbol(GeneralSymbolInfo(d, this->staticVarargsName, varargItemDescs));
} else if (this->_runtimeVarargs)
{
/*什么都不用做*/
}
try {
//TODO 推导返回值类型没必要把每条语句都推导一次, 应该记录下来各个变量的声明语句,在推导返回值类型需要变量时,直接推导声明语句即可
for(size_t i=0; i<implCount-1; ++i) {
this->implements[i]->deduce(&innerCtx);
}
return this->implements[implCount - 1]->deduce(&innerCtx);
}
catch (const CancelException &ex)
{
ex.rethrowAbove(CancelScope::FUNCTION_FRAGMENT);
throw CancelException(CancelScope::EXPRESSION);
}
}
llvm::BasicBlock * FunctionFragment::generateBlock(GenerateContext * outerCtx,
const std::vector<Type*> &realParamTypes,
Type *returnType,
llvm::Function *llvmFunc,
llvm::BasicBlock *falseBlock)
{
GenerateContext innerCtx(&this->context ,outerCtx);
if (this->_staticVarargs) innerCtx.setBlockAttribute(BlockAttributeItem::SFINAE, true);
SymbolTable &instSymbolTable = *innerCtx.getInstanceSymbolTable();
size_t realParamCount = realParamTypes.size();
size_t myParamCount = this->parameters.size();
/*开始创建LLVM对象*/
llvm::BasicBlock *fragmentBlock = llvm::BasicBlock::Create(*outerCtx->getLLVMContext(), "branch", llvmFunc);
llvm::IRBuilder<> &builder = *innerCtx.getIRBuilder();
builder.SetInsertPoint(fragmentBlock);
//将具名实参加入符号表
vector<llvm::Value*> llvmArgs;
llvmArgs.reserve(myParamCount > realParamCount ? myParamCount : realParamCount);
auto itLLVMArg = llvmFunc->arg_begin();
for (size_t i = 0; i < (myParamCount < realParamCount ? myParamCount : realParamCount); ++i) {
ParameterDecl *curDeclParam = this->parameters[i];
//获取参数的LLVM Argument,如果跟本分支的类型不相同,还要做一个类型转换
llvm::Value *llvmPtrArg = itLLVMArg;
if(this->parameters[i]->getType() && !realParamTypes[i]->equals(this->parameters[i]->getType())){
//创建临时变量
wstring tmpVarName = L"$"+to_wstring(i);
SymbolInfo *info = instSymbolTable.setSymbol(GeneralSymbolInfo(this->getDebugInfo(), tmpVarName,
ValueDescriptor(realParamTypes[i], ValueKind::VARIABLE),LinkageType::INTERNAL));
((GeneralSymbolInfo*)info)->setLLVMValue(llvmPtrArg);
Variable tmpVar(ExpressionInfo(nullptr, this->getDebugInfo(), &this->context), tmpVarName);
llvmPtrArg = ValueDescriptor::generateLLVMConvert(this->getDebugInfo(), &innerCtx, &tmpVar, ValueDescriptor(this->parameters[i]->getType(), ValueKind::VARIABLE));
}
SymbolInfo *myParamInfo = instSymbolTable.setSymbol(
GeneralSymbolInfo(this->getDebugInfo(), curDeclParam->getName(), ValueDescriptor(curDeclParam->getType(), ValueKind::VARIABLE), LinkageType::INTERNAL, llvmPtrArg));
llvmArgs.push_back(llvmPtrArg);
++itLLVMArg;
}
//记录需要生成默认参数值的参数, 并生成默认值的赋值
vector<Type *> finalParamTypes = realParamTypes;
if (realParamCount < myParamCount) {
/*如果实参少于形参,肯定形参有默认值,要不之前不会匹配过来。为默认值生成赋值*/
for (size_t i = realParamCount; i < myParamCount; ++i) {
ParameterDecl *curDeclParam = this->parameters[i];
Type *defaultValueType = curDeclParam->getType();
if (!defaultValueType) defaultValueType = curDeclParam->getDefaultValue()->deduce(&innerCtx);
SymbolInfo *myParamInfo = instSymbolTable.setSymbol(
GeneralSymbolInfo(this->getDebugInfo(), curDeclParam->getName(),
ValueDescriptor(defaultValueType, ValueKind::VARIABLE), LinkageType::INTERNAL));
finalParamTypes.push_back(defaultValueType);
llvm::Value *llvmVar = myParamInfo->generateLLVMIR(&innerCtx);
llvm::Value *llvmVal = curDeclParam->getDefaultValue()->generateIR(&innerCtx).getValue();
builder.CreateStore(llvmVal, llvmVar);
llvmArgs.push_back(llvmVal);
}
}
/*动态变参的处理:
* fragment的constraint部分生成在父级Block里,为fragment的implements单独生成一个stub函数。
* 若constraint匹配成功,则生成impl的Block,在block里插入一行call,调用并返回stub函数的结果。
* 在生成stub函数之前,将有名字的形参对应的实参加入符号表。然后将所有的implements都生成在stub函数里。
* */
bool isNative = this->isNative();
if (this->_runtimeVarargs || isNative) {
return this->generateStubBlock(outerCtx, &innerCtx, finalParamTypes, returnType, llvmFunc, llvmArgs, fragmentBlock,
falseBlock, isNative);
/*======================不是动态变参(静态变参或者无变参的处理)=======================*/
} else if (this->_staticVarargs) //如果是静态变参,将多余的实参组合成MultiValue,放进符号表里。
{
//将变参的参数放进符号表里,使用Variable进行引用
vector<Expression *> varargs;
size_t i = 0;
while (itLLVMArg != llvmFunc->arg_end()) {
llvm::Argument *llvmArg = itLLVMArg++;
wstring curArgName = Locales::toWideChar(Encoding::ANSI, llvmArg->getName());
SymbolInfo *info = instSymbolTable.setSymbol(
GeneralSymbolInfo(this->getDebugInfo(), curArgName,
ValueDescriptor(finalParamTypes[myParamCount + i], ValueKind::VARIABLE),
LinkageType::INTERNAL, llvmArg));
auto *cur = new Variable(
ExpressionInfo(this->context.getModule(), this->getDebugInfo(), &this->context), curArgName);
varargs.push_back(cur);
++i;
}
auto *multiValue = new MultiValue(
ExpressionInfo(this->context.getModule(), this->getDebugInfo(), &this->context),
varargs);
SymbolInfo *info = instSymbolTable.setSymbol(
GeneralSymbolInfo(this->getDebugInfo(), this->staticVarargsName,
multiValue->deduce(&innerCtx).getValueDescriptors()));
}
llvm::BasicBlock *implBlock = nullptr;
try {
this->generateConstraints(&innerCtx, llvmFunc, falseBlock, &implBlock);
if (!implBlock) implBlock = fragmentBlock;
this->generateImplements(&innerCtx, implBlock, returnType);
}
catch (const CancelException &ex) {
ex.rethrowAbove(CancelScope::FUNCTION_FRAGMENT);
if (implBlock != fragmentBlock) {
implBlock->removeFromParent();
implBlock->deleteValue();
}
fragmentBlock->removeFromParent();
fragmentBlock->deleteValue();
throw CancelException(CancelScope::EXPRESSION);
}
return fragmentBlock;
}
bool FunctionFragment::match(const DebugInfo &d, const FunctionQuery &query) noexcept
{
const vector<Type *> &realParamTypes = query.getParameterTypes();
size_t declParamCount = this->parameters.size();
size_t realParamCount = realParamTypes.size();
if (!this->_const && query.isConst()) return false;
if (realParamTypes.size() > declParamCount && !this->_runtimeVarargs && !this->_staticVarargs) return false;
for (size_t i = 0; i < declParamCount; ++i) {
Type *declParamType = this->parameters[i]->getType();
if (i >= realParamCount) {
if (this->parameters[i]->getDefaultValue()) continue;
else return false;
}
if (!realParamTypes[i]) return false;
if (declParamType && !ValueDescriptor::convertableTo(d, ValueDescriptor(realParamTypes[i], ValueKind::VALUE),
ValueDescriptor(declParamType, ValueKind::VARIABLE)))
return false;
}
return true;
}
void FunctionFragment::generateConstraints(GenerateContext *context, llvm::Function *llvmFunc, llvm::BasicBlock *falseBlock, llvm::BasicBlock **outMatchedBlock)
{
auto &builder = *context->getIRBuilder();
size_t condCount = this->constraints.size();
if (condCount > 0)
{
llvm::BasicBlock *matchedBlock = llvm::BasicBlock::Create(*context->getLLVMContext(), "matched", llvmFunc);
*outMatchedBlock = matchedBlock;
for (size_t i = 0; i < this->constraints.size(); ++i)
{
try
{
llvm::Value *res = this->constraints[i]->generateIR(context).getValue();
builder.CreateCondBr(res, matchedBlock, falseBlock);
}
catch (const CancelException &ex)
{
ex.rethrowAbove(CancelScope::EXPRESSION);
continue;
}
}
}else{
*outMatchedBlock = nullptr;
}
}
void FunctionFragment::generateImplements(GenerateContext *context, llvm::BasicBlock *block, Type *returnType)
{
auto &builder = *context->getIRBuilder();
builder.SetInsertPoint(block);
size_t codeCount = this->implements.size();
for (size_t i = 0; i < codeCount; ++i)
{
Expression *curExpr = this->implements[i];
try {
if (i != codeCount - 1) {
llvm::Value *res = curExpr->generateIR(context).getValue();
} else {
if (returnType->getClassification() == TypeClassification::VOID) {
builder.CreateRetVoid();
} else {
//如果分支返回值类型与函数返回值类型不同,则生成类型转换
ValueDescriptor branchReturnDesc = curExpr->deduce(context);
llvm::Value *res = ValueDescriptor::generateLLVMConvert(curExpr->getDebugInfo(), context, curExpr,
ValueDescriptor(returnType,
ValueKind::VALUE)).getValue();
builder.CreateRet(res);
}
}
}
catch (const CancelException &ex)
{
ex.rethrowAbove(CancelScope::EXPRESSION);
continue;
}
}
}
bool FunctionFragment::canBeNative() const noexcept
{
if (!this->declReturnType) return false;
if(this->_staticVarargs) return false;
if (!this->linkageType.equals(LinkageType::EXTERNAL)) return false;
for (size_t i = 0; i < this->parameters.size(); ++i)
{
if (!this->parameters[i]->getType()) return false;
}
return true;
}
/*如果当前块中只有自己一个函数canBeNative,则isNative*/
bool FunctionFragment::isNative() noexcept
{
if(!this->canBeNative()) return false;
auto fragmentsOfSameName = this->context.getBaseContext()->getLocalFunctionFragments(this->getDebugInfo(), this->name);
for(FunctionFragment *fragment : fragmentsOfSameName){
if(fragment == this) continue;
if(fragment->canBeNative()) return false;
}
return true;
}
llvm::BasicBlock* FunctionFragment::generateStubBlock(
GenerateContext *outerCtx,
GenerateContext *innerCtx,
const std::vector<Type*> ¶mTypes,
Type *returnType,
llvm::Function *llvmFunc,
const std::vector<llvm::Value*> &llvmArgs,
llvm::BasicBlock *fragmentBlock,
llvm::BasicBlock *falseBlock,
bool isNative)
{
if(this->_staticVarargs){
throw InternalException(L"FunctionFragment::generateStubBlock 不接受静态变参!");
}
size_t stubParamCount = this->_runtimeVarargs ? this->parameters.size() : paramTypes.size();
size_t myParamCount = this->parameters.size();
//vector<Type*> stubParamTypes(paramTypes.begin(), paramTypes.begin()+stubParamCount);
//计算stub的参数类型,如果本函数有明确声明类型的参数,则取声明的类型。否则取实参的类型
vector<Type*> stubParamTypes;
stubParamTypes.reserve(stubParamCount);
for(size_t i=0; i < stubParamCount; ++i){
if(i < myParamCount && this->parameters[i]->getType()){
stubParamTypes.push_back(this->parameters[i]->getType());
}else{
stubParamTypes.push_back(paramTypes[i]);
}
}
llvm::Function *stubFunc = nullptr;
FunctionCache *functionCache = innerCtx->getFunctionCache();
if(!functionCache->getCachedStub(this->getDebugInfo(),this,FunctionTypeQuery(stubParamTypes,false,this->isRuntimeVarargs()), &stubFunc))
{
wstring stubFuncName;
if (isNative)
{
stubFuncName = this->context.getBaseContext()->getBlockPrefix() + this->name;
} else {
stubFuncName = Function::getMangledFunctionName(this->getDebugInfo(), this->name, stubParamTypes,
this->_runtimeVarargs) + L"@.stub";
}
vector<llvm::Type *> llvmParamTypes;
llvmParamTypes.reserve(stubParamCount);
for (size_t i = 0; i < stubParamCount; ++i)
{
//注意,这里不能用llvmFunc->getParamType(),因为有可能有fragment的参数默认值,llvmFunc的参数数量少于paramTypes数量
llvmParamTypes.push_back(paramTypes[i]->getLLVMType(innerCtx));
}
auto llvmReturnType = returnType->getLLVMType(innerCtx);
stubFunc = llvm::Function::Create(llvm::FunctionType::get(llvmReturnType, llvmParamTypes, this->_runtimeVarargs),
llvm::Function::ExternalLinkage,
Locales::fromWideChar(Encoding::ANSI, stubFuncName), innerCtx->getLLVMModule());
size_t myParamCount = this->parameters.size();
GenerateContext stubCtx(&this->context, outerCtx);
auto stubSymbolTable = stubCtx.getInstanceSymbolTable();
auto itLLVMArg = stubFunc->arg_begin();
for(size_t i=0; i < stubParamCount; ++i){
wstring paramName = this->parameters[i]->getName();
itLLVMArg->setName(Locales::fromWideChar(Encoding::ANSI, paramName));
auto info = stubSymbolTable->setSymbol(GeneralSymbolInfo(this->getDebugInfo(), paramName,ValueDescriptor(paramTypes[i], ValueKind::VARIABLE), LinkageType::INTERNAL, itLLVMArg));
++itLLVMArg;
}
llvm::BasicBlock *stubEntry = nullptr;
try
{
if (!this->implements.empty())
{
stubEntry = llvm::BasicBlock::Create(*innerCtx->getLLVMContext(), "entry", stubFunc);
this->generateImplements(&stubCtx, stubEntry, returnType);
}
functionCache->cacheStub(this->getDebugInfo(), this,
FunctionType::get(stubParamTypes, returnType, this->isRuntimeVarargs(),
this->isConst()), stubFunc);
}
catch (const CancelException &ex)
{
ex.rethrowAbove(CancelScope::FUNCTION_FRAGMENT);
fragmentBlock->removeFromParent();
fragmentBlock->deleteValue();
if (stubFunc){
stubFunc->removeFromParent();
stubFunc->deleteValue();
}
if (stubEntry){
stubEntry->removeFromParent();
stubEntry->deleteValue();
}
throw CancelException(CancelScope::EXPRESSION);
}
}
auto &builder = *innerCtx->getIRBuilder();
builder.SetInsertPoint(fragmentBlock);
llvm::BasicBlock *implBlock = nullptr;
try
{
this->generateConstraints(innerCtx, llvmFunc, falseBlock, &implBlock);
}catch (const CancelException &ex){
ex.rethrowAbove(CancelScope::FUNCTION_FRAGMENT);
fragmentBlock->removeFromParent();
fragmentBlock->deleteValue();
if(implBlock){
implBlock->removeFromParent();
implBlock->deleteValue();
}
}
if (!implBlock) implBlock = fragmentBlock;
builder.SetInsertPoint(implBlock);
llvm::Value *stubRet = builder.CreateCall(stubFunc, llvmArgs);
if (returnType->getClassification() == TypeClassification::VOID) {
builder.CreateRetVoid();
}
else {
builder.CreateRet(stubRet);
}
return fragmentBlock;
}
| 42.520548
| 189
| 0.633054
|
jingjiajie
|
3e3c2a0b7a6dcf223c185ff02f697577bf409e94
| 23,974
|
cpp
|
C++
|
devices/K32L2A41A/mcuxpresso/startup_k32l2a41a.cpp
|
mmahadevan108/mcux-sdk
|
a242602a02fee2945287d446801217904a26fc7e
|
[
"Apache-2.0"
] | 175
|
2021-01-19T17:11:01.000Z
|
2022-03-31T06:04:43.000Z
|
devices/K32L2A41A/mcuxpresso/startup_k32l2a41a.cpp
|
tannewt/mcux-sdk
|
1f15787b0abb7886f24434297cd293cf16ad04ab
|
[
"Apache-2.0"
] | 69
|
2021-01-27T08:18:51.000Z
|
2022-03-29T12:16:57.000Z
|
devices/K32L2A41A/mcuxpresso/startup_k32l2a41a.cpp
|
tannewt/mcux-sdk
|
1f15787b0abb7886f24434297cd293cf16ad04ab
|
[
"Apache-2.0"
] | 72
|
2021-01-19T14:34:20.000Z
|
2022-03-21T09:02:18.000Z
|
//*****************************************************************************
// K32L2A41A startup code for use with MCUXpresso IDE
//
// Version : 160420
//*****************************************************************************
//
// Copyright 2016-2020 NXP
// All rights reserved.
//
// SPDX-License-Identifier: BSD-3-Clause
//*****************************************************************************
#if defined (DEBUG)
#pragma GCC push_options
#pragma GCC optimize ("Og")
#endif // (DEBUG)
#if defined (__cplusplus)
#ifdef __REDLIB__
#error Redlib does not support C++
#else
//*****************************************************************************
//
// The entry point for the C++ library startup
//
//*****************************************************************************
extern "C" {
extern void __libc_init_array(void);
}
#endif
#endif
#define WEAK __attribute__ ((weak))
#define WEAK_AV __attribute__ ((weak, section(".after_vectors")))
#define ALIAS(f) __attribute__ ((weak, alias (#f)))
//*****************************************************************************
#if defined (__cplusplus)
extern "C" {
#endif
//*****************************************************************************
// Flash Configuration block : 16-byte flash configuration field that stores
// default protection settings (loaded on reset) and security information that
// allows the MCU to restrict access to the Flash Memory module.
// Placed at address 0x400 by the linker script.
//*****************************************************************************
__attribute__ ((used,section(".FlashConfig"))) const struct {
unsigned int word1;
unsigned int word2;
unsigned int word3;
unsigned int word4;
} Flash_Config = {0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFF3DFE};
//*****************************************************************************
// Declaration of external SystemInit function
//*****************************************************************************
#if defined (__USE_CMSIS)
extern void SystemInit(void);
#endif // (__USE_CMSIS)
//*****************************************************************************
// Forward declaration of the core exception handlers.
// When the application defines a handler (with the same name), this will
// automatically take precedence over these weak definitions.
// If your application is a C++ one, then any interrupt handlers defined
// in C++ files within in your main application will need to have C linkage
// rather than C++ linkage. To do this, make sure that you are using extern "C"
// { .... } around the interrupt handler within your main application code.
//*****************************************************************************
void ResetISR(void);
WEAK void NMI_Handler(void);
WEAK void HardFault_Handler(void);
WEAK void SVC_Handler(void);
WEAK void PendSV_Handler(void);
WEAK void SysTick_Handler(void);
WEAK void IntDefaultHandler(void);
//*****************************************************************************
// Forward declaration of the application IRQ handlers. When the application
// defines a handler (with the same name), this will automatically take
// precedence over weak definitions below
//*****************************************************************************
WEAK void DMA0_04_IRQHandler(void);
WEAK void DMA0_15_IRQHandler(void);
WEAK void DMA0_26_IRQHandler(void);
WEAK void DMA0_37_IRQHandler(void);
WEAK void CTI0_DMA0_Error_IRQHandler(void);
WEAK void FLEXIO0_IRQHandler(void);
WEAK void TPM0_IRQHandler(void);
WEAK void TPM1_IRQHandler(void);
WEAK void TPM2_IRQHandler(void);
WEAK void LPIT0_IRQHandler(void);
WEAK void LPSPI0_IRQHandler(void);
WEAK void LPSPI1_IRQHandler(void);
WEAK void LPUART0_IRQHandler(void);
WEAK void LPUART1_IRQHandler(void);
WEAK void LPI2C0_IRQHandler(void);
WEAK void LPI2C1_IRQHandler(void);
WEAK void Reserved32_IRQHandler(void);
WEAK void PORTA_IRQHandler(void);
WEAK void PORTB_IRQHandler(void);
WEAK void PORTC_IRQHandler(void);
WEAK void PORTD_IRQHandler(void);
WEAK void PORTE_IRQHandler(void);
WEAK void LLWU_IRQHandler(void);
WEAK void Reserved39_IRQHandler(void);
WEAK void USB0_IRQHandler(void);
WEAK void ADC0_IRQHandler(void);
WEAK void LPTMR0_IRQHandler(void);
WEAK void RTC_Seconds_IRQHandler(void);
WEAK void INTMUX0_0_IRQHandler(void);
WEAK void INTMUX0_1_IRQHandler(void);
WEAK void INTMUX0_2_IRQHandler(void);
WEAK void INTMUX0_3_IRQHandler(void);
WEAK void LPTMR1_IRQHandler(void);
WEAK void Reserved49_IRQHandler(void);
WEAK void Reserved50_IRQHandler(void);
WEAK void Reserved51_IRQHandler(void);
WEAK void LPSPI2_IRQHandler(void);
WEAK void LPUART2_IRQHandler(void);
WEAK void EMVSIM0_IRQHandler(void);
WEAK void LPI2C2_IRQHandler(void);
WEAK void TSI0_IRQHandler(void);
WEAK void PMC_IRQHandler(void);
WEAK void FTFA_IRQHandler(void);
WEAK void SCG_IRQHandler(void);
WEAK void WDOG0_IRQHandler(void);
WEAK void DAC0_IRQHandler(void);
WEAK void TRNG_IRQHandler(void);
WEAK void RCM_IRQHandler(void);
WEAK void CMP0_IRQHandler(void);
WEAK void CMP1_IRQHandler(void);
WEAK void RTC_IRQHandler(void);
//*****************************************************************************
// Forward declaration of the driver IRQ handlers. These are aliased
// to the IntDefaultHandler, which is a 'forever' loop. When the driver
// defines a handler (with the same name), this will automatically take
// precedence over these weak definitions
//*****************************************************************************
void DMA0_04_DriverIRQHandler(void) ALIAS(IntDefaultHandler);
void DMA0_15_DriverIRQHandler(void) ALIAS(IntDefaultHandler);
void DMA0_26_DriverIRQHandler(void) ALIAS(IntDefaultHandler);
void DMA0_37_DriverIRQHandler(void) ALIAS(IntDefaultHandler);
void CTI0_DMA0_Error_DriverIRQHandler(void) ALIAS(IntDefaultHandler);
void FLEXIO0_DriverIRQHandler(void) ALIAS(IntDefaultHandler);
void TPM0_DriverIRQHandler(void) ALIAS(IntDefaultHandler);
void TPM1_DriverIRQHandler(void) ALIAS(IntDefaultHandler);
void TPM2_DriverIRQHandler(void) ALIAS(IntDefaultHandler);
void LPIT0_DriverIRQHandler(void) ALIAS(IntDefaultHandler);
void LPSPI0_DriverIRQHandler(void) ALIAS(IntDefaultHandler);
void LPSPI1_DriverIRQHandler(void) ALIAS(IntDefaultHandler);
void LPUART0_DriverIRQHandler(void) ALIAS(IntDefaultHandler);
void LPUART1_DriverIRQHandler(void) ALIAS(IntDefaultHandler);
void LPI2C0_DriverIRQHandler(void) ALIAS(IntDefaultHandler);
void LPI2C1_DriverIRQHandler(void) ALIAS(IntDefaultHandler);
void Reserved32_DriverIRQHandler(void) ALIAS(IntDefaultHandler);
void PORTA_DriverIRQHandler(void) ALIAS(IntDefaultHandler);
void PORTB_DriverIRQHandler(void) ALIAS(IntDefaultHandler);
void PORTC_DriverIRQHandler(void) ALIAS(IntDefaultHandler);
void PORTD_DriverIRQHandler(void) ALIAS(IntDefaultHandler);
void PORTE_DriverIRQHandler(void) ALIAS(IntDefaultHandler);
void LLWU_DriverIRQHandler(void) ALIAS(IntDefaultHandler);
void Reserved39_DriverIRQHandler(void) ALIAS(IntDefaultHandler);
void USB0_DriverIRQHandler(void) ALIAS(IntDefaultHandler);
void ADC0_DriverIRQHandler(void) ALIAS(IntDefaultHandler);
void LPTMR0_DriverIRQHandler(void) ALIAS(IntDefaultHandler);
void RTC_Seconds_DriverIRQHandler(void) ALIAS(IntDefaultHandler);
void INTMUX0_0_DriverIRQHandler(void) ALIAS(IntDefaultHandler);
void INTMUX0_1_DriverIRQHandler(void) ALIAS(IntDefaultHandler);
void INTMUX0_2_DriverIRQHandler(void) ALIAS(IntDefaultHandler);
void INTMUX0_3_DriverIRQHandler(void) ALIAS(IntDefaultHandler);
void LPTMR1_DriverIRQHandler(void) ALIAS(IntDefaultHandler);
void Reserved49_DriverIRQHandler(void) ALIAS(IntDefaultHandler);
void Reserved50_DriverIRQHandler(void) ALIAS(IntDefaultHandler);
void Reserved51_DriverIRQHandler(void) ALIAS(IntDefaultHandler);
void LPSPI2_DriverIRQHandler(void) ALIAS(IntDefaultHandler);
void LPUART2_DriverIRQHandler(void) ALIAS(IntDefaultHandler);
void EMVSIM0_DriverIRQHandler(void) ALIAS(IntDefaultHandler);
void LPI2C2_DriverIRQHandler(void) ALIAS(IntDefaultHandler);
void TSI0_DriverIRQHandler(void) ALIAS(IntDefaultHandler);
void PMC_DriverIRQHandler(void) ALIAS(IntDefaultHandler);
void FTFA_DriverIRQHandler(void) ALIAS(IntDefaultHandler);
void SCG_DriverIRQHandler(void) ALIAS(IntDefaultHandler);
void WDOG0_DriverIRQHandler(void) ALIAS(IntDefaultHandler);
void DAC0_DriverIRQHandler(void) ALIAS(IntDefaultHandler);
void TRNG_DriverIRQHandler(void) ALIAS(IntDefaultHandler);
void RCM_DriverIRQHandler(void) ALIAS(IntDefaultHandler);
void CMP0_DriverIRQHandler(void) ALIAS(IntDefaultHandler);
void CMP1_DriverIRQHandler(void) ALIAS(IntDefaultHandler);
void RTC_DriverIRQHandler(void) ALIAS(IntDefaultHandler);
//*****************************************************************************
// The entry point for the application.
// __main() is the entry point for Redlib based applications
// main() is the entry point for Newlib based applications
//*****************************************************************************
#if defined (__REDLIB__)
extern void __main(void);
#endif
extern int main(void);
//*****************************************************************************
// External declaration for the pointer to the stack top from the Linker Script
//*****************************************************************************
extern void _vStackTop(void);
//*****************************************************************************
#if defined (__cplusplus)
} // extern "C"
#endif
//*****************************************************************************
// The vector table.
// This relies on the linker script to place at correct location in memory.
//*****************************************************************************
extern void (* const g_pfnVectors[])(void);
extern void * __Vectors __attribute__ ((alias ("g_pfnVectors")));
__attribute__ ((used, section(".isr_vector")))
void (* const g_pfnVectors[])(void) = {
// Core Level - CM0P
&_vStackTop, // The initial stack pointer
ResetISR, // The reset handler
NMI_Handler, // The NMI handler
HardFault_Handler, // The hard fault handler
0, // Reserved
0, // Reserved
0, // Reserved
0, // Reserved
0, // Reserved
0, // Reserved
0, // Reserved
SVC_Handler, // SVCall handler
0, // Reserved
0, // Reserved
PendSV_Handler, // The PendSV handler
SysTick_Handler, // The SysTick handler
// Chip Level - K32L2A41A
DMA0_04_IRQHandler, // 16: DMA0 channel 0/4 transfer complete
DMA0_15_IRQHandler, // 17: DMA0 channel 1/5 transfer complete
DMA0_26_IRQHandler, // 18: DMA0 channel 2/6 transfer complete
DMA0_37_IRQHandler, // 19: DMA0 channel 3/7 transfer complete
CTI0_DMA0_Error_IRQHandler, // 20: CTI0 or DMA0 error
FLEXIO0_IRQHandler, // 21: FLEXIO0
TPM0_IRQHandler, // 22: TPM0 single interrupt vector for all sources
TPM1_IRQHandler, // 23: TPM1 single interrupt vector for all sources
TPM2_IRQHandler, // 24: TPM2 single interrupt vector for all sources
LPIT0_IRQHandler, // 25: LPIT0 interrupt
LPSPI0_IRQHandler, // 26: LPSPI0 single interrupt vector for all sources
LPSPI1_IRQHandler, // 27: LPSPI1 single interrupt vector for all sources
LPUART0_IRQHandler, // 28: LPUART0 status and error
LPUART1_IRQHandler, // 29: LPUART1 status and error
LPI2C0_IRQHandler, // 30: LPI2C0 interrupt
LPI2C1_IRQHandler, // 31: LPI2C1 interrupt
Reserved32_IRQHandler, // 32: Reserved interrupt
PORTA_IRQHandler, // 33: PORTA Pin detect
PORTB_IRQHandler, // 34: PORTB Pin detect
PORTC_IRQHandler, // 35: PORTC Pin detect
PORTD_IRQHandler, // 36: PORTD Pin detect
PORTE_IRQHandler, // 37: PORTE Pin detect
LLWU_IRQHandler, // 38: Low leakage wakeup
Reserved39_IRQHandler, // 39: Reserved interrupt
USB0_IRQHandler, // 40: USB0 interrupt
ADC0_IRQHandler, // 41: ADC0 interrupt
LPTMR0_IRQHandler, // 42: LPTMR0 interrupt
RTC_Seconds_IRQHandler, // 43: RTC seconds
INTMUX0_0_IRQHandler, // 44: INTMUX0 channel 0 interrupt
INTMUX0_1_IRQHandler, // 45: INTMUX0 channel 1 interrupt
INTMUX0_2_IRQHandler, // 46: INTMUX0 channel 2 interrupt
INTMUX0_3_IRQHandler, // 47: INTMUX0 channel 3 interrupt
LPTMR1_IRQHandler, // 48: LPTMR1 interrupt (INTMUX source IRQ0)
Reserved49_IRQHandler, // 49: Reserved interrupt
Reserved50_IRQHandler, // 50: Reserved interrupt
Reserved51_IRQHandler, // 51: Reserved interrupt
LPSPI2_IRQHandler, // 52: LPSPI2 single interrupt vector for all sources (INTMUX source IRQ4)
LPUART2_IRQHandler, // 53: LPUART2 status and error (INTMUX source IRQ5)
EMVSIM0_IRQHandler, // 54: EMVSIM0 interrupt (INTMUX source IRQ6)
LPI2C2_IRQHandler, // 55: LPI2C2 interrupt (INTMUX source IRQ7)
TSI0_IRQHandler, // 56: TSI0 interrupt (INTMUX source IRQ8)
PMC_IRQHandler, // 57: PMC interrupt (INTMUX source IRQ9)
FTFA_IRQHandler, // 58: FTFA interrupt (INTMUX source IRQ10)
SCG_IRQHandler, // 59: SCG interrupt (INTMUX source IRQ11)
WDOG0_IRQHandler, // 60: WDOG0 interrupt (INTMUX source IRQ12)
DAC0_IRQHandler, // 61: DAC0 interrupt (INTMUX source IRQ13)
TRNG_IRQHandler, // 62: TRNG interrupt (INTMUX source IRQ14)
RCM_IRQHandler, // 63: RCM interrupt (INTMUX source IRQ15)
CMP0_IRQHandler, // 64: CMP0 interrupt (INTMUX source IRQ16)
CMP1_IRQHandler, // 65: CMP1 interrupt (INTMUX source IRQ17)
RTC_IRQHandler, // 66: RTC Alarm interrupt (INTMUX source IRQ18)
}; /* End of g_pfnVectors */
//*****************************************************************************
// Functions to carry out the initialization of RW and BSS data sections. These
// are written as separate functions rather than being inlined within the
// ResetISR() function in order to cope with MCUs with multiple banks of
// memory.
//*****************************************************************************
__attribute__ ((section(".after_vectors.init_data")))
void data_init(unsigned int romstart, unsigned int start, unsigned int len) {
unsigned int *pulDest = (unsigned int*) start;
unsigned int *pulSrc = (unsigned int*) romstart;
unsigned int loop;
for (loop = 0; loop < len; loop = loop + 4)
*pulDest++ = *pulSrc++;
}
__attribute__ ((section(".after_vectors.init_bss")))
void bss_init(unsigned int start, unsigned int len) {
unsigned int *pulDest = (unsigned int*) start;
unsigned int loop;
for (loop = 0; loop < len; loop = loop + 4)
*pulDest++ = 0;
}
//*****************************************************************************
// The following symbols are constructs generated by the linker, indicating
// the location of various points in the "Global Section Table". This table is
// created by the linker via the Code Red managed linker script mechanism. It
// contains the load address, execution address and length of each RW data
// section and the execution and length of each BSS (zero initialized) section.
//*****************************************************************************
extern unsigned int __data_section_table;
extern unsigned int __data_section_table_end;
extern unsigned int __bss_section_table;
extern unsigned int __bss_section_table_end;
//*****************************************************************************
// Reset entry point for your code.
// Sets up a simple runtime environment and initializes the C/C++
// library.
//*****************************************************************************
__attribute__ ((naked, section(".after_vectors.reset")))
void ResetISR(void) {
// Disable interrupts
__asm volatile ("cpsid i");
#if defined (__USE_CMSIS)
// If __USE_CMSIS defined, then call CMSIS SystemInit code
SystemInit();
#else
// Disable Watchdog
// Write watchdog update key to unlock
*((volatile unsigned int *)0x40076004) = 0xD928C520;
// Set timeout value
*((volatile unsigned int *)0x40076008) = 0xFFFF;
// Now disable watchdog via control register
volatile unsigned int *WDOG_CS = (unsigned int *) 0x40076000;
*WDOG_CS = (*WDOG_CS & ~(1 << 7)) | (1 << 5);
#endif // (__USE_CMSIS)
//
// Copy the data sections from flash to SRAM.
//
unsigned int LoadAddr, ExeAddr, SectionLen;
unsigned int *SectionTableAddr;
// Load base address of Global Section Table
SectionTableAddr = &__data_section_table;
// Copy the data sections from flash to SRAM.
while (SectionTableAddr < &__data_section_table_end) {
LoadAddr = *SectionTableAddr++;
ExeAddr = *SectionTableAddr++;
SectionLen = *SectionTableAddr++;
data_init(LoadAddr, ExeAddr, SectionLen);
}
// At this point, SectionTableAddr = &__bss_section_table;
// Zero fill the bss segment
while (SectionTableAddr < &__bss_section_table_end) {
ExeAddr = *SectionTableAddr++;
SectionLen = *SectionTableAddr++;
bss_init(ExeAddr, SectionLen);
}
#if !defined (__USE_CMSIS)
// Assume that if __USE_CMSIS defined, then CMSIS SystemInit code
// will setup the VTOR register
// Check to see if we are running the code from a non-zero
// address (eg RAM, external flash), in which case we need
// to modify the VTOR register to tell the CPU that the
// vector table is located at a non-0x0 address.
unsigned int * pSCB_VTOR = (unsigned int *) 0xE000ED08;
if ((unsigned int *)g_pfnVectors!=(unsigned int *) 0x00000000) {
*pSCB_VTOR = (unsigned int)g_pfnVectors;
}
#endif // (__USE_CMSIS)
#if defined (__cplusplus)
//
// Call C++ library initialisation
//
__libc_init_array();
#endif
// Reenable interrupts
__asm volatile ("cpsie i");
#if defined (__REDLIB__)
// Call the Redlib library, which in turn calls main()
__main();
#else
main();
#endif
//
// main() shouldn't return, but if it does, we'll just enter an infinite loop
//
while (1) {
;
}
}
//*****************************************************************************
// Default core exception handlers. Override the ones here by defining your own
// handler routines in your application code.
//*****************************************************************************
WEAK_AV void NMI_Handler(void)
{ while(1) {}
}
WEAK_AV void HardFault_Handler(void)
{ while(1) {}
}
WEAK_AV void SVC_Handler(void)
{ while(1) {}
}
WEAK_AV void PendSV_Handler(void)
{ while(1) {}
}
WEAK_AV void SysTick_Handler(void)
{ while(1) {}
}
//*****************************************************************************
// Processor ends up here if an unexpected interrupt occurs or a specific
// handler is not present in the application code.
//*****************************************************************************
WEAK_AV void IntDefaultHandler(void)
{ while(1) {}
}
//*****************************************************************************
// Default application exception handlers. Override the ones here by defining
// your own handler routines in your application code. These routines call
// driver exception handlers or IntDefaultHandler() if no driver exception
// handler is included.
//*****************************************************************************
WEAK_AV void DMA0_04_IRQHandler(void)
{ DMA0_04_DriverIRQHandler();
}
WEAK_AV void DMA0_15_IRQHandler(void)
{ DMA0_15_DriverIRQHandler();
}
WEAK_AV void DMA0_26_IRQHandler(void)
{ DMA0_26_DriverIRQHandler();
}
WEAK_AV void DMA0_37_IRQHandler(void)
{ DMA0_37_DriverIRQHandler();
}
WEAK_AV void CTI0_DMA0_Error_IRQHandler(void)
{ CTI0_DMA0_Error_DriverIRQHandler();
}
WEAK_AV void FLEXIO0_IRQHandler(void)
{ FLEXIO0_DriverIRQHandler();
}
WEAK_AV void TPM0_IRQHandler(void)
{ TPM0_DriverIRQHandler();
}
WEAK_AV void TPM1_IRQHandler(void)
{ TPM1_DriverIRQHandler();
}
WEAK_AV void TPM2_IRQHandler(void)
{ TPM2_DriverIRQHandler();
}
WEAK_AV void LPIT0_IRQHandler(void)
{ LPIT0_DriverIRQHandler();
}
WEAK_AV void LPSPI0_IRQHandler(void)
{ LPSPI0_DriverIRQHandler();
}
WEAK_AV void LPSPI1_IRQHandler(void)
{ LPSPI1_DriverIRQHandler();
}
WEAK_AV void LPUART0_IRQHandler(void)
{ LPUART0_DriverIRQHandler();
}
WEAK_AV void LPUART1_IRQHandler(void)
{ LPUART1_DriverIRQHandler();
}
WEAK_AV void LPI2C0_IRQHandler(void)
{ LPI2C0_DriverIRQHandler();
}
WEAK_AV void LPI2C1_IRQHandler(void)
{ LPI2C1_DriverIRQHandler();
}
WEAK_AV void Reserved32_IRQHandler(void)
{ Reserved32_DriverIRQHandler();
}
WEAK_AV void PORTA_IRQHandler(void)
{ PORTA_DriverIRQHandler();
}
WEAK_AV void PORTB_IRQHandler(void)
{ PORTB_DriverIRQHandler();
}
WEAK_AV void PORTC_IRQHandler(void)
{ PORTC_DriverIRQHandler();
}
WEAK_AV void PORTD_IRQHandler(void)
{ PORTD_DriverIRQHandler();
}
WEAK_AV void PORTE_IRQHandler(void)
{ PORTE_DriverIRQHandler();
}
WEAK_AV void LLWU_IRQHandler(void)
{ LLWU_DriverIRQHandler();
}
WEAK_AV void Reserved39_IRQHandler(void)
{ Reserved39_DriverIRQHandler();
}
WEAK_AV void USB0_IRQHandler(void)
{ USB0_DriverIRQHandler();
}
WEAK_AV void ADC0_IRQHandler(void)
{ ADC0_DriverIRQHandler();
}
WEAK_AV void LPTMR0_IRQHandler(void)
{ LPTMR0_DriverIRQHandler();
}
WEAK_AV void RTC_Seconds_IRQHandler(void)
{ RTC_Seconds_DriverIRQHandler();
}
WEAK_AV void INTMUX0_0_IRQHandler(void)
{ INTMUX0_0_DriverIRQHandler();
}
WEAK_AV void INTMUX0_1_IRQHandler(void)
{ INTMUX0_1_DriverIRQHandler();
}
WEAK_AV void INTMUX0_2_IRQHandler(void)
{ INTMUX0_2_DriverIRQHandler();
}
WEAK_AV void INTMUX0_3_IRQHandler(void)
{ INTMUX0_3_DriverIRQHandler();
}
WEAK_AV void LPTMR1_IRQHandler(void)
{ LPTMR1_DriverIRQHandler();
}
WEAK_AV void Reserved49_IRQHandler(void)
{ Reserved49_DriverIRQHandler();
}
WEAK_AV void Reserved50_IRQHandler(void)
{ Reserved50_DriverIRQHandler();
}
WEAK_AV void Reserved51_IRQHandler(void)
{ Reserved51_DriverIRQHandler();
}
WEAK_AV void LPSPI2_IRQHandler(void)
{ LPSPI2_DriverIRQHandler();
}
WEAK_AV void LPUART2_IRQHandler(void)
{ LPUART2_DriverIRQHandler();
}
WEAK_AV void EMVSIM0_IRQHandler(void)
{ EMVSIM0_DriverIRQHandler();
}
WEAK_AV void LPI2C2_IRQHandler(void)
{ LPI2C2_DriverIRQHandler();
}
WEAK_AV void TSI0_IRQHandler(void)
{ TSI0_DriverIRQHandler();
}
WEAK_AV void PMC_IRQHandler(void)
{ PMC_DriverIRQHandler();
}
WEAK_AV void FTFA_IRQHandler(void)
{ FTFA_DriverIRQHandler();
}
WEAK_AV void SCG_IRQHandler(void)
{ SCG_DriverIRQHandler();
}
WEAK_AV void WDOG0_IRQHandler(void)
{ WDOG0_DriverIRQHandler();
}
WEAK_AV void DAC0_IRQHandler(void)
{ DAC0_DriverIRQHandler();
}
WEAK_AV void TRNG_IRQHandler(void)
{ TRNG_DriverIRQHandler();
}
WEAK_AV void RCM_IRQHandler(void)
{ RCM_DriverIRQHandler();
}
WEAK_AV void CMP0_IRQHandler(void)
{ CMP0_DriverIRQHandler();
}
WEAK_AV void CMP1_IRQHandler(void)
{ CMP1_DriverIRQHandler();
}
WEAK_AV void RTC_IRQHandler(void)
{ RTC_DriverIRQHandler();
}
//*****************************************************************************
#if defined (DEBUG)
#pragma GCC pop_options
#endif // (DEBUG)
| 35.78209
| 107
| 0.63986
|
mmahadevan108
|
3e3edb1e7e2343c734c4bd70d0f2a930a6a755a0
| 1,706
|
hpp
|
C++
|
include/mizuiro/image/detail/subview_pitch.hpp
|
cpreh/mizuiro
|
5ab15bde4e72e3a4978c034b8ff5700352932485
|
[
"BSL-1.0"
] | 1
|
2015-08-22T04:19:39.000Z
|
2015-08-22T04:19:39.000Z
|
include/mizuiro/image/detail/subview_pitch.hpp
|
freundlich/mizuiro
|
5ab15bde4e72e3a4978c034b8ff5700352932485
|
[
"BSL-1.0"
] | null | null | null |
include/mizuiro/image/detail/subview_pitch.hpp
|
freundlich/mizuiro
|
5ab15bde4e72e3a4978c034b8ff5700352932485
|
[
"BSL-1.0"
] | null | null | null |
// Copyright Carl Philipp Reh 2009 - 2016.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef MIZUIRO_IMAGE_DETAIL_SUBVIEW_PITCH_HPP_INCLUDED
#define MIZUIRO_IMAGE_DETAIL_SUBVIEW_PITCH_HPP_INCLUDED
#include <mizuiro/no_init.hpp>
#include <mizuiro/image/bound_impl.hpp>
#include <mizuiro/image/dimension_impl.hpp>
#include <mizuiro/image/move_iterator.hpp>
#include <mizuiro/image/detail/edge_pos_begin.hpp>
#include <mizuiro/image/detail/edge_pos_end.hpp>
#include <mizuiro/image/detail/pitch_difference.hpp>
namespace mizuiro::image::detail
{
template <typename View>
typename View::pitch_type subview_pitch(View const &_view, typename View::bound_type const &_bound)
{
using pitch_type = typename View::pitch_type;
pitch_type ret{mizuiro::no_init{}};
for (typename pitch_type::size_type index = 0; index < pitch_type::static_size; ++index)
{
typename View::dim const edge_pos_end(mizuiro::image::detail::edge_pos_end(_bound, index));
ret[index] = _view.size()[index] > 1
? mizuiro::image::detail::pitch_difference(
mizuiro::image::move_iterator(_view, edge_pos_end),
mizuiro::image::move_iterator(
_view, mizuiro::image::detail::edge_pos_begin(_bound, index)))
: 0;
// if the end is one past the parent view's dim,
// the pitch will be skipped by the iterator, so readd it
if (edge_pos_end[index] == _view.size()[index])
{
ret[index] += _view.pitch()[index];
}
}
return ret;
}
}
#endif
| 32.807692
| 99
| 0.680539
|
cpreh
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.