hexsha stringlengths 40 40 | size int64 22 2.4M | ext stringclasses 5
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 260 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 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 3 260 | max_issues_repo_name stringlengths 5 109 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | 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 3 260 | max_forks_repo_name stringlengths 5 109 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 22 2.4M | avg_line_length float64 5 169k | max_line_length int64 5 786k | alphanum_fraction float64 0.06 0.95 | matches listlengths 1 11 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
05dfdd3b778738036c6ebf6e0893768cc6584384 | 2,380 | h | C | src/yb/gutil/stringprintf.h | hstenzel/yugabyte-db | b25c8f4d7a9e66d106c41c446b71af870aefa304 | [
"Apache-2.0",
"CC0-1.0"
] | 3,702 | 2019-09-17T13:49:56.000Z | 2022-03-31T21:50:59.000Z | src/yb/gutil/stringprintf.h | hstenzel/yugabyte-db | b25c8f4d7a9e66d106c41c446b71af870aefa304 | [
"Apache-2.0",
"CC0-1.0"
] | 9,291 | 2019-09-16T21:47:07.000Z | 2022-03-31T23:52:28.000Z | src/yb/gutil/stringprintf.h | hstenzel/yugabyte-db | b25c8f4d7a9e66d106c41c446b71af870aefa304 | [
"Apache-2.0",
"CC0-1.0"
] | 673 | 2019-09-16T21:27:53.000Z | 2022-03-31T22:23:59.000Z | // Copyright 2002 and onwards Google Inc.
//
// The following only applies to changes made to this file as part of YugaByte development.
//
// Portions Copyright (c) YugaByte, 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.
//
// Printf variants that place their output in a C++ string.
//
// Usage:
// string result = StringPrintf("%d %s\n", 10, "hello");
// SStringPrintf(&result, "%d %s\n", 10, "hello");
// StringAppendF(&result, "%d %s\n", 20, "there");
#ifndef _BASE_STRINGPRINTF_H
#define _BASE_STRINGPRINTF_H
#include <stdarg.h>
#include <string>
using std::string;
#include <vector>
using std::vector;
#include "yb/gutil/port.h"
// Return a C++ string
extern string StringPrintf(const char* format, ...)
// Tell the compiler to do printf format string checking.
PRINTF_ATTRIBUTE(1,2);
// Store result into a supplied string and return it
extern const string& SStringPrintf(string* dst, const char* format, ...)
// Tell the compiler to do printf format string checking.
PRINTF_ATTRIBUTE(2,3);
// Append result to a supplied string
extern void StringAppendF(string* dst, const char* format, ...)
// Tell the compiler to do printf format string checking.
PRINTF_ATTRIBUTE(2,3);
// Lower-level routine that takes a va_list and appends to a specified
// string. All other routines are just convenience wrappers around it.
extern void StringAppendV(string* dst, const char* format, va_list ap);
// The max arguments supported by StringPrintfVector
extern const int kStringPrintfVectorMaxArgs;
// You can use this version when all your arguments are strings, but
// you don't know how many arguments you'll have at compile time.
// StringPrintfVector will LOG(FATAL) if v.size() > kStringPrintfVectorMaxArgs
extern string StringPrintfVector(const char* format, const vector<string>& v);
#endif /* _BASE_STRINGPRINTF_H */
| 37.777778 | 100 | 0.734454 | [
"vector"
] |
05e696cf1b3529f1703b393fa1adb673046ada45 | 8,616 | h | C | src/BaseIOSocketBuffer.h | LazyPanda07/SocketStreams | 9b2915e550286a77aa177c21e2ff6c88433c3408 | [
"MIT"
] | null | null | null | src/BaseIOSocketBuffer.h | LazyPanda07/SocketStreams | 9b2915e550286a77aa177c21e2ff6c88433c3408 | [
"MIT"
] | 1 | 2020-06-28T11:24:07.000Z | 2020-07-04T19:13:50.000Z | src/BaseIOSocketBuffer.h | LazyPanda07/SocketStreams | 9b2915e550286a77aa177c21e2ff6c88433c3408 | [
"MIT"
] | null | null | null | #pragma once
#include <streambuf>
#include <memory>
#include "BaseNetwork.h"
namespace buffers
{
template<typename ContainerT = std::vector<char>>
class BaseIOSocketBuffer :
public std::streambuf
{
public:
using typename std::streambuf::int_type;
using typename std::streambuf::char_type;
using typename std::streambuf::traits_type;
using std::streambuf::pbase;
using std::streambuf::pptr;
using std::streambuf::epptr;
using std::streambuf::setp;
using std::streambuf::pbump;
using std::streambuf::eback;
using std::streambuf::gptr;
using std::streambuf::egptr;
using std::streambuf::setg;
using std::streambuf::gbump;
protected:
enum class IOType : uint8_t
{
input,
output
};
protected:
ContainerT outBuffer;
ContainerT inBuffer;
std::unique_ptr<web::BaseNetwork<ContainerT>> network;
int lastPacketSize;
IOType type;
protected:
void setPointers();
int_type overflow(int_type ch) override;
int_type underflow() override;
std::streamsize xsputn(const char_type* s, std::streamsize count) override;
std::streamsize xsgetn(char_type* s, std::streamsize count) override;
int sync() override;
ContainerT dataPart() noexcept;
public:
BaseIOSocketBuffer() = default;
BaseIOSocketBuffer(const BaseIOSocketBuffer&) = delete;
BaseIOSocketBuffer(BaseIOSocketBuffer&& other) noexcept;
BaseIOSocketBuffer(SOCKET clientSocket);
BaseIOSocketBuffer(SOCKET clientSocket, size_t bufferSize);
template<typename FirstStringT, typename SecondStringT>
BaseIOSocketBuffer(const FirstStringT& ip, const SecondStringT& port);
template<typename FirstStringT, typename SecondStringT>
BaseIOSocketBuffer(const FirstStringT& ip, const SecondStringT& port, size_t bufferSize);
BaseIOSocketBuffer(std::unique_ptr<web::BaseNetwork<ContainerT>>&& networkSubclass);
BaseIOSocketBuffer(std::unique_ptr<web::BaseNetwork<ContainerT>>&& networkSubclass, size_t bufferSize);
BaseIOSocketBuffer& operator = (const BaseIOSocketBuffer&) = delete;
BaseIOSocketBuffer& operator = (BaseIOSocketBuffer&& other) noexcept;
virtual void setInputType() final;
virtual void setOutputType() final;
virtual const std::unique_ptr<web::BaseNetwork<ContainerT>>& getNetwork() const final;
virtual std::unique_ptr<web::BaseNetwork<ContainerT>>& getNetwork() final;
virtual int getLastPacketSize();
virtual ~BaseIOSocketBuffer() = default;
};
template<typename ContainerT>
void BaseIOSocketBuffer<ContainerT>::setPointers()
{
setp(outBuffer.data(), outBuffer.data() + outBuffer.size() - 1);
}
template<typename ContainerT>
typename BaseIOSocketBuffer<ContainerT>::int_type BaseIOSocketBuffer<ContainerT>::overflow(int_type ch)
{
*pptr() = ch;
pbump(1);
type = IOType::output;
if (this->sync() == -1)
{
return traits_type::eof();
}
return 0;
}
template<typename ContainerT>
typename BaseIOSocketBuffer<ContainerT>::int_type BaseIOSocketBuffer<ContainerT>::underflow()
{
type = IOType::input;
if (!eback())
{
if (this->sync() == -1)
{
return traits_type::eof();
}
}
if (gptr() < egptr())
{
return *gptr();
}
setg(nullptr, nullptr, nullptr);
return traits_type::eof();
}
template<typename ContainerT>
std::streamsize BaseIOSocketBuffer<ContainerT>::xsputn(const char_type* s, std::streamsize count)
{
type = IOType::output;
if (network->getResizeMode() == web::BaseNetwork<ContainerT>::ReceiveMode::allowResize && outBuffer.size() < count)
{
if constexpr (utility::checkResize<ContainerT>::value)
{
web::BaseNetwork<ContainerT>::resizeFunction(outBuffer, count);
this->setPointers();
}
}
for (size_t i = 0; i < count; i++)
{
if (pptr() == epptr())
{
if (this->overflow(s[i]) == -1)
{
return -1;
}
}
else
{
*pptr() = s[i];
pbump(1);
}
}
if (pptr() != pbase())
{
if (this->sync() == -1)
{
return -1;
}
}
return count;
}
template<typename ContainerT>
std::streamsize BaseIOSocketBuffer<ContainerT>::xsgetn(char_type* s, std::streamsize count)
{
type = IOType::input;
if (!eback())
{
if (this->sync() == -1)
{
return -1;
}
}
ptrdiff_t size = egptr() - eback();
if (!size)
{
return 0;
}
for (size_t i = 0; i < count; i++)
{
if (gptr() == egptr())
{
s[i] = *gptr();
setg(nullptr, nullptr, nullptr);
return size;
}
else
{
s[i] = *gptr();
gbump(1);
}
}
return count ? count : traits_type::eof();
}
template<typename ContainerT>
int BaseIOSocketBuffer<ContainerT>::sync()
{
switch (type)
{
case IOType::input:
lastPacketSize = network->receiveData(inBuffer);
if (lastPacketSize == -1)
{
return -1;
}
setg(inBuffer.data(), inBuffer.data(), inBuffer.data() + lastPacketSize);
break;
case IOType::output:
{
ptrdiff_t size = pptr() - pbase();
if constexpr (utility::checkBegin<ContainerT>::value && utility::checkEnd<ContainerT>::value && utility::checkInitializerListConstructor<ContainerT>::value)
{
lastPacketSize = network->sendData(this->dataPart());
}
else
{
lastPacketSize = network->sendData(outBuffer);
}
pbump(-size);
if (lastPacketSize == -1)
{
return -1;
}
}
break;
}
return 0;
}
template<typename ContainerT>
typename ContainerT BaseIOSocketBuffer<ContainerT>::dataPart() noexcept
{
return ContainerT(pbase(), pptr());
}
template<typename ContainerT>
BaseIOSocketBuffer<ContainerT>::BaseIOSocketBuffer(BaseIOSocketBuffer&& other) noexcept :
outBuffer(std::move(other.outBuffer)),
inBuffer(std::move(other.inBuffer)),
network(std::move(other.network)),
lastPacketSize(other.lastPacketSize),
type(other.type)
{
}
template<typename ContainerT>
BaseIOSocketBuffer<ContainerT>::BaseIOSocketBuffer(SOCKET clientSocket) :
network(std::make_unique<web::BaseNetwork<ContainerT>>(clientSocket))
{
this->setPointers();
}
template<typename ContainerT>
BaseIOSocketBuffer<ContainerT>::BaseIOSocketBuffer(SOCKET clientSocket, size_t bufferSize) :
network(std::make_unique<web::BaseNetwork<ContainerT>>(clientSocket, web::BaseNetwork<ContainerT>::ReceiveMode::prohibitResize)),
outBuffer(bufferSize),
inBuffer(bufferSize)
{
this->setPointers();
}
template<typename ContainerT>
template<typename FirstStringT, typename SecondStringT>
BaseIOSocketBuffer<ContainerT>::BaseIOSocketBuffer(const FirstStringT& ip, const SecondStringT& port) :
network(std::make_unique<web::BaseNetwork<ContainerT>>(ip, port))
{
this->setPointers();
}
template<typename ContainerT>
template<typename FirstStringT, typename SecondStringT>
BaseIOSocketBuffer<ContainerT>::BaseIOSocketBuffer(const FirstStringT& ip, const SecondStringT& port, size_t bufferSize) :
network(std::make_unique<web::BaseNetwork<ContainerT>>(ip, port, web::BaseNetwork<ContainerT>::ReceiveMode::prohibitResize)),
outBuffer(bufferSize),
inBuffer(bufferSize)
{
this->setPointers();
}
template<typename ContainerT>
BaseIOSocketBuffer<ContainerT>::BaseIOSocketBuffer(std::unique_ptr<web::BaseNetwork<ContainerT>>&& networkSubclass) :
network(std::move(networkSubclass))
{
this->setPointers();
}
template<typename ContainerT>
BaseIOSocketBuffer<ContainerT>::BaseIOSocketBuffer(std::unique_ptr<web::BaseNetwork<ContainerT>>&& networkSubclass, size_t bufferSize) :
network(std::move(networkSubclass)),
outBuffer(bufferSize),
inBuffer(bufferSize)
{
this->setPointers();
}
template<typename ContainerT>
BaseIOSocketBuffer<ContainerT>& BaseIOSocketBuffer<ContainerT>::operator = (BaseIOSocketBuffer&& other) noexcept
{
outBuffer = std::move(other.outBuffer);
inBuffer = std::move(other.inBuffer);
network = std::move(other.network);
lastPacketSize = other.lastPacketSize;
type = other.type;
return *this;
}
template<typename ContainerT>
void BaseIOSocketBuffer<ContainerT>::setInputType()
{
type = IOType::input;
}
template<typename ContainerT>
void BaseIOSocketBuffer<ContainerT>::setOutputType()
{
type = IOType::output;
}
template<typename ContainerT>
const std::unique_ptr<web::BaseNetwork<ContainerT>>& BaseIOSocketBuffer<ContainerT>::getNetwork() const
{
return network;
}
template<typename ContainerT>
std::unique_ptr<web::BaseNetwork<ContainerT>>& BaseIOSocketBuffer<ContainerT>::getNetwork()
{
return network;
}
template<typename ContainerT>
int BaseIOSocketBuffer<ContainerT>::getLastPacketSize()
{
return lastPacketSize;
}
using IOSocketBuffer = BaseIOSocketBuffer<std::vector<char>>;
}
| 22.914894 | 159 | 0.709494 | [
"vector"
] |
05e8c4cfcd2de13c220b5b42d00c3930f4aba82f | 2,709 | c | C | md5.c | kolbma/cowpatty | 0a274975040960d85cd68550facf801fc3a9d7df | [
"BSD-3-Clause"
] | 127 | 2017-09-18T09:43:20.000Z | 2022-02-20T12:21:02.000Z | md5.c | SynecticLabs/cowpatty | 0a274975040960d85cd68550facf801fc3a9d7df | [
"BSD-3-Clause"
] | 6 | 2018-06-16T19:50:19.000Z | 2019-02-15T14:28:23.000Z | md5.c | SynecticLabs/cowpatty | 0a274975040960d85cd68550facf801fc3a9d7df | [
"BSD-3-Clause"
] | 34 | 2018-01-25T05:38:15.000Z | 2021-12-01T14:48:33.000Z | /*
* MD5 hash implementation and interface functions
* Copyright (c) 2003-2004, Jouni Malinen <jkmaline@cc.hut.fi>
*
* This program 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.
*
* Alternatively, this software may be distributed under the terms of BSD
* license.
*
* See README and COPYING for more details.
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#ifdef OPENSSL
#include <openssl/md5.h>
#endif
#include "common.h"
#include "md5.h"
void md5_mac(u8 * key, size_t key_len, u8 * data, size_t data_len, u8 * mac)
{
MD5_CTX context;
MD5_Init(&context);
MD5_Update(&context, key, key_len);
MD5_Update(&context, data, data_len);
MD5_Update(&context, key, key_len);
MD5_Final(mac, &context);
}
/* HMAC code is based on RFC 2104 */
void hmac_md5_vector(u8 * key, size_t key_len, size_t num_elem,
u8 * addr[], size_t * len, u8 * mac)
{
MD5_CTX context;
u8 k_ipad[65]; /* inner padding - key XORd with ipad */
u8 k_opad[65]; /* outer padding - key XORd with opad */
u8 tk[16];
int i;
/* if key is longer than 64 bytes reset it to key = MD5(key) */
if (key_len > 64) {
MD5_Init(&context);
MD5_Update(&context, key, key_len);
MD5_Final(tk, &context);
key = tk;
key_len = 16;
}
/* the HMAC_MD5 transform looks like:
*
* MD5(K XOR opad, MD5(K XOR ipad, text))
*
* where K is an n byte key
* ipad is the byte 0x36 repeated 64 times
* opad is the byte 0x5c repeated 64 times
* and text is the data being protected */
/* start out by storing key in pads */
memset(k_ipad, 0, sizeof(k_ipad));
memset(k_opad, 0, sizeof(k_opad));
memcpy(k_ipad, key, key_len);
memcpy(k_opad, key, key_len);
/* XOR key with ipad and opad values */
for (i = 0; i < 64; i++) {
k_ipad[i] ^= 0x36;
k_opad[i] ^= 0x5c;
}
/* perform inner MD5 */
MD5_Init(&context); /* init context for 1st pass */
MD5_Update(&context, k_ipad, 64); /* start with inner pad */
/* then text of datagram; all fragments */
for (i = 0; i < num_elem; i++) {
MD5_Update(&context, addr[i], len[i]);
}
MD5_Final(mac, &context); /* finish up 1st pass */
/* perform outer MD5 */
MD5_Init(&context); /* init context for 2nd pass */
MD5_Update(&context, k_opad, 64); /* start with outer pad */
MD5_Update(&context, mac, 16); /* then results of 1st hash */
MD5_Final(mac, &context); /* finish up 2nd pass */
}
void hmac_md5(u8 * key, size_t key_len, u8 * data, size_t data_len, u8 * mac)
{
hmac_md5_vector(key, key_len, 1, &data, &data_len, mac);
}
#ifndef OPENSSL
#error "OpenSSL is required for WPA/MD5 support."
#endif /* OPENSSL */
| 26.821782 | 77 | 0.667405 | [
"transform"
] |
05fb6d29f26bed63b8e4e72928b1bd51de8e11e9 | 12,766 | c | C | util/src/bst_hashed_vector.c | TheComet93/clither | 58d5f936ee7621bc1e2864b8dbc8a080f944c530 | [
"MIT"
] | 1 | 2016-12-06T08:40:31.000Z | 2016-12-06T08:40:31.000Z | util/src/bst_hashed_vector.c | TheComet93/clither | 58d5f936ee7621bc1e2864b8dbc8a080f944c530 | [
"MIT"
] | null | null | null | util/src/bst_hashed_vector.c | TheComet93/clither | 58d5f936ee7621bc1e2864b8dbc8a080f944c530 | [
"MIT"
] | 1 | 2018-06-18T15:34:16.000Z | 2018-06-18T15:34:16.000Z | #include "util/bst_hashed_vector.h"
#include "util/hash.h"
#include "util/memory.h"
#include "util/string.h"
#include <string.h>
#include <assert.h>
/* default hash function */
static uint32_t(*g_hash_func)(const char*, uint32_t len) = hash_jenkins_oaat;
/* ------------------------------------------------------------------------- */
void
bsthv_set_string_hash_func(uint32_t(*func)(const char*, uint32_t len))
{
g_hash_func = func;
}
/* ------------------------------------------------------------------------- */
void
bsthv_restore_default_hash_func(void)
{
g_hash_func = hash_jenkins_oaat;
}
/* ------------------------------------------------------------------------- */
uint32_t
bsthv_hash_string(const char* str)
{
return g_hash_func(str, strlen(str));
}
/* ------------------------------------------------------------------------- */
struct bsthv_t*
bsthv_create(void)
{
struct bsthv_t* bsthv;
if(!(bsthv = (struct bsthv_t*)MALLOC(sizeof *bsthv, "bsthv_create()")))
return NULL;
bsthv_init(bsthv);
return bsthv;
}
/* ------------------------------------------------------------------------- */
void
bsthv_init(struct bsthv_t* bsthv)
{
assert(bsthv);
ordered_vector_init(&bsthv->vector, sizeof(struct bsthv_key_value_t));
bsthv->count = 0;
}
/* ------------------------------------------------------------------------- */
void
bsthv_destroy(struct bsthv_t* bsthv)
{
assert(bsthv);
bsthv_clear_free(bsthv);
FREE(bsthv);
}
/* ------------------------------------------------------------------------- */
/* algorithm taken from GNU GCC stdlibc++'s lower_bound function, line 2121 in stl_algo.h */
/* https://gcc.gnu.org/onlinedocs/libstdc++/libstdc++-html-USERS-4.3/a02014.html */
static struct bsthv_key_value_t*
bsthv_find_lower_bound(const struct bsthv_t* bsthv, uint32_t hash)
{
uint32_t half;
struct bsthv_key_value_t* middle;
struct bsthv_key_value_t* data;
uint32_t len;
assert(bsthv);
data = (struct bsthv_key_value_t*)bsthv->vector.data;
len = bsthv->vector.count;
/* if the vector has no data, return NULL */
if(!len)
return NULL;
while(len > 0)
{
half = len >> 1;
middle = data + half;
if(middle->hash < hash)
{
data = middle;
++data;
len = len - half - 1;
}
else
len = half;
}
/* if "data" is pointing outside of the valid elements in the vector, also return NULL */
if((intptr_t)data >= (intptr_t)bsthv->vector.data + (intptr_t)bsthv->vector.count * (intptr_t)bsthv->vector.element_size)
return NULL;
else
return data;
}
/* ------------------------------------------------------------------------- */
char
bsthv_insert(struct bsthv_t* bsthv, const char* key, void* value)
{
struct bsthv_key_value_t* new_kv;
uint32_t hash = bsthv_hash_string(key);
/* get the lower bound of the insertion point */
struct bsthv_key_value_t* lower_bound = bsthv_find_lower_bound(bsthv, hash);
/* hash collision */
if(lower_bound && lower_bound->hash == hash)
{
/*
* Get to the end of the chain and make sure no existing keys match the
* new key.
*/
struct bsthv_value_chain_t* vc = &lower_bound->value_chain;
do
{
/* sanity check - all values in chain must have a key */
assert(vc->key);
if(strcmp(key, vc->key) == 0)
return 0; /* key exists, abort */
} while(vc->next && (vc = vc->next));
/* allocate and link a new value at the end of the chain */
vc->next = (struct bsthv_value_chain_t*)MALLOC(sizeof *vc, "bsthv_insert()");
if(!vc->next)
return 0;
memset(vc->next, 0, sizeof *vc->next);
/* key */
vc->next->key = malloc_string(key);
if(!vc->next->key)
{
FREE(vc->next);
return 0;
}
/* value */
vc->next->value = value;
++(bsthv->count);
return 1;
}
/*
* No hash collision. Either push back or insert, depending on whether
* there is already data in the bsthv.
*/
if(!lower_bound)
new_kv = (struct bsthv_key_value_t*)ordered_vector_push_emplace(&bsthv->vector);
else
new_kv = ordered_vector_insert_emplace(&bsthv->vector,
lower_bound - (struct bsthv_key_value_t*)bsthv->vector.data);
if(!new_kv)
return 0;
memset(new_kv, 0, sizeof *new_kv);
new_kv->hash = hash;
new_kv->value_chain.value = value;
new_kv->value_chain.key = malloc_string(key);
if(!new_kv->value_chain.key)
{
ordered_vector_erase_element(&bsthv->vector, new_kv);
return 0;
}
++(bsthv->count);
return 1;
}
/* ------------------------------------------------------------------------- */
void
bsthv_set(struct bsthv_t* bsthv, const char* key, void* value)
{
struct bsthv_key_value_t* kv;
struct bsthv_value_chain_t* vc;
uint32_t hash;
assert(bsthv);
assert(key);
/*
* Compute hash and look up the key-value object. If the returned object
* doesn't have the same hash as the computed hash, it means the key
* doesn't exist.
*/
hash = bsthv_hash_string(key);
kv = bsthv_find_lower_bound(bsthv, hash);
if(!kv || kv->hash != hash)
return;
/*
* If there are no further values in the value chain, this must be the
* value.
*/
if(!kv->value_chain.next)
{
kv->value_chain.value = value;
return;
}
/*
* Iterate the value chain and compare each string with the key until it is
* found. Then set the value.
*/
vc = &kv->value_chain;
do
{
if(strcmp(key, vc->key) == 0)
{
vc->value = value;
return;
}
vc = vc->next;
} while(vc);
}
/* ------------------------------------------------------------------------- */
void*
bsthv_find(const struct bsthv_t* bsthv, const char* key)
{
struct bsthv_key_value_t* data;
struct bsthv_value_chain_t* vc;
uint32_t hash;
assert(bsthv);
/*
* Compute hash and look up the key-value object. If the returned object
* doesn't have the same hash as the computed hash, it means the key
* doesn't exist.
*/
hash = bsthv_hash_string(key);
data = bsthv_find_lower_bound(bsthv, hash);
if(!data || data->hash != hash)
return NULL;
/*
* If there is only one value in the chain then it must be the value we're
* looking for.
*/
if(!data->value_chain.next)
return data->value_chain.value;
/*
* Iterate chain and string compare each key with the key we're looking for
* until a matching key is found.
*/
vc = &data->value_chain;
do
{
if(strcmp(key, vc->key) == 0)
return vc->value;
vc = vc->next;
} while(vc);
return NULL;
}
/* ------------------------------------------------------------------------- */
const char*
bsthv_find_element(const struct bsthv_t* bsthv, const void* value)
{
assert(bsthv);
ORDERED_VECTOR_FOR_EACH(&bsthv->vector, struct bsthv_key_value_t, kv)
struct bsthv_value_chain_t* vc = &kv->value_chain;
do
{
if(vc->value == value)
return vc->key;
vc = vc->next;
} while(vc);
ORDERED_VECTOR_END_EACH
return NULL;
}
/* ------------------------------------------------------------------------- */
void*
bsthv_get_any_element(const struct bsthv_t* bsthv)
{
struct bsthv_key_value_t* kv;
assert(bsthv);
kv = (struct bsthv_key_value_t*)ordered_vector_back(&bsthv->vector);
if(kv)
return kv->value_chain.value;
return NULL;
}
/* ------------------------------------------------------------------------- */
char
bsthv_key_exists(struct bsthv_t* bsthv, const char* key)
{
struct bsthv_key_value_t* data;
struct bsthv_value_chain_t* vc;
uint32_t hash;
assert(bsthv);
/*
* Compute hash and look up the key-value object. If the returned object
* doesn't have the same hash as the computed hash, it means the key
* doesn't exist.
*/
hash = bsthv_hash_string(key);
data = bsthv_find_lower_bound(bsthv, hash);
if(!data || data->hash != hash)
return 0;
/*
* Iterate over chain and find the key we're looking for.
*/
vc = &data->value_chain;
do
{
if(strcmp(key, vc->key) == 0)
return 1;
vc = vc->next;
} while(vc);
return 0;
}
/* ------------------------------------------------------------------------- */
void*
bsthv_erase(struct bsthv_t* bsthv, const char* key)
{
struct bsthv_key_value_t* kv;
uint32_t hash;
assert(bsthv);
assert(key);
/*
* Compute hash and look up the key-value object. If the returned object
* doesn't have the same hash as the computed hash, it means the key
* doesn't exist.
*/
hash = bsthv_hash_string(key);
kv = bsthv_find_lower_bound(bsthv, hash);
if(!kv || kv->hash != hash)
return NULL;
/* kv object exists and is valid. Remove it */
return bsthv_erase_key_value_object(bsthv, key, kv);
}
/* ------------------------------------------------------------------------- */
void*
bsthv_erase_key_value_object(struct bsthv_t* bsthv,
const char* key,
struct bsthv_key_value_t* kv)
{
struct bsthv_value_chain_t* vc;
struct bsthv_value_chain_t* parent_vc;
if(!kv->value_chain.next)
{
void* value = kv->value_chain.value;
free_string(kv->value_chain.key);
ordered_vector_erase_element(&bsthv->vector, kv);
--(bsthv->count);
return value;
}
/*
* Special case: If the first value in the chain has the key we're looking
* for, it must be erased from the vector (and if there are any further
* values down the chain, the next value must be copied into the vector and
* deallocated to maintain the structure).
*/
vc = &kv->value_chain;
if(strcmp(key, kv->value_chain.key) == 0)
{
struct bsthv_value_chain_t* replacement = vc->next;
void* ret_value = vc->value;
/* we have everything we need, free current and move replacement into its place */
free_string(vc->key);
memcpy(vc, replacement, sizeof *vc); /* copies the next value into the bsthv's internal vector */
FREE(replacement);
/* done */
--(bsthv->count);
return ret_value;
}
/*
* Iterate chain and find a value with a matching key. When it is found,
* unlink it from the chain and free it.
*/
parent_vc = vc; /* required for unlinking */
vc = vc->next; /* next will always exist, or we wouldn't be here */
do
{
if(strcmp(key, vc->key) == 0)
{
void* value = vc->value;
free_string(vc->key);
parent_vc->next = vc->next; /* unlink this value by linking next with parent */
FREE(vc);
--(bsthv->count);
return value;
}
parent_vc = vc;
vc = vc->next;
} while(vc);
return NULL;
}
/* ------------------------------------------------------------------------- */
void*
bsthv_erase_element(struct bsthv_t* bsthv, void* value)
{
const char* key;
assert(bsthv);
if(!(key = bsthv_find_element(bsthv, value)))
return NULL;
bsthv_erase(bsthv, key);
return value;
}
/* ------------------------------------------------------------------------- */
static void
bsthv_free_all_chains_and_keys(struct bsthv_t* bsthv)
{
assert(bsthv);
ORDERED_VECTOR_FOR_EACH(&bsthv->vector, struct bsthv_key_value_t, kv)
struct bsthv_value_chain_t* vc = kv->value_chain.next;
free_string(kv->value_chain.key);
while(vc)
{
struct bsthv_value_chain_t* to_free = vc;
vc = vc->next;
free_string(to_free->key);
FREE(to_free);
}
ORDERED_VECTOR_END_EACH
}
/* ------------------------------------------------------------------------- */
void
bsthv_clear(struct bsthv_t* bsthv)
{
assert(bsthv);
bsthv_free_all_chains_and_keys(bsthv);
ordered_vector_clear(&bsthv->vector);
bsthv->count = 0;
}
/* ------------------------------------------------------------------------- */
void bsthv_clear_free(struct bsthv_t* bsthv)
{
assert(bsthv);
bsthv_free_all_chains_and_keys(bsthv);
ordered_vector_clear_free(&bsthv->vector);
bsthv->count = 0;
}
| 26.989429 | 125 | 0.53384 | [
"object",
"vector"
] |
af003d13161807f4c1488a97587447ab15a3a3df | 1,586 | h | C | StereoKitC/systems/render.h | slitcch/StereoKit | eb90f42226a96c0d8bfbcdcce1d91b9ade8844b8 | [
"MIT"
] | 1 | 2021-11-23T00:36:09.000Z | 2021-11-23T00:36:09.000Z | StereoKitC/systems/render.h | slitcch/StereoKit | eb90f42226a96c0d8bfbcdcce1d91b9ade8844b8 | [
"MIT"
] | null | null | null | StereoKitC/systems/render.h | slitcch/StereoKit | eb90f42226a96c0d8bfbcdcce1d91b9ade8844b8 | [
"MIT"
] | null | null | null | #pragma once
#include "../stereokit.h"
#include "../libraries/array.h"
#include <directxmath.h>
namespace sk {
struct render_stats_t {
int swaps_mesh;
int swaps_shader;
int swaps_texture;
int swaps_material;
int draw_calls;
int draw_instances;
};
struct render_item_t {
DirectX::XMMATRIX transform;
color128 color;
mesh_t mesh;
material_t material;
uint64_t sort_id;
};
enum render_list_state_ {
render_list_state_empty = 0,
render_list_state_used,
render_list_state_rendered,
};
struct _render_list_t {
array_t<render_item_t> queue;
render_stats_t stats;
render_list_state_ state;
};
typedef _render_list_t* render_list_t;
matrix render_get_projection();
color32 render_get_clear_color();
vec2 render_get_clip();
void render_draw_matrix (const matrix *views, const matrix *projs, int32_t view_count);
void render_clear ();
vec3 render_unproject_pt(vec3 normalized_screen_pt);
void render_update_projection();
bool render_initialize();
void render_update();
void render_shutdown();
void render_set_material(material_t material);
void render_set_shader (shader_t shader);
void render_set_mesh (mesh_t mesh);
void render_draw_item (int count);
render_list_t render_list_create ();
void render_list_free (render_list_t list);
void render_list_push (render_list_t list);
void render_list_pop ();
void render_list_execute(render_list_t list, const matrix *views, const matrix *projs, int32_t view_count);
void render_list_clear (render_list_t list);
} // namespace sk | 24.78125 | 116 | 0.752207 | [
"mesh",
"transform"
] |
af01dffa27e4c6171321bd9402ac33384a07a9c0 | 352 | h | C | PhysX.Net-3.4/PhysX.Net-3/Source/ActiveTransform.h | Golangltd/PhysX.Net | fb71e0422d441a16a05ed51348d8afb0328d4b90 | [
"MIT"
] | 1 | 2018-06-22T16:01:55.000Z | 2018-06-22T16:01:55.000Z | PhysX.Net-3.4/PhysX.Net-3/Source/ActiveTransform.h | Golangltd/PhysX.Net | fb71e0422d441a16a05ed51348d8afb0328d4b90 | [
"MIT"
] | null | null | null | PhysX.Net-3.4/PhysX.Net-3/Source/ActiveTransform.h | Golangltd/PhysX.Net | fb71e0422d441a16a05ed51348d8afb0328d4b90 | [
"MIT"
] | null | null | null | #pragma once
namespace PhysX
{
ref class Actor;
/// <summary>
/// Data struct for use with Active Transform Notification.
/// </summary>
public ref class ActiveTransform
{
internal:
static ActiveTransform^ ToManaged(PxActiveTransform transform);
public:
property PhysX::Actor^ Actor;
property Matrix ActorToWorldTransform;
};
}; | 17.6 | 66 | 0.724432 | [
"transform"
] |
af039acbd898e700db18a492bea12bca455aef91 | 1,630 | h | C | source/backend/hiai/3rdParty/include/c/compatible/hiai_model_tensor_info.h | SunXuan90/MNN | dc0b62e817884f8fbc884f159b590feab2b0f0f8 | [
"Apache-2.0"
] | null | null | null | source/backend/hiai/3rdParty/include/c/compatible/hiai_model_tensor_info.h | SunXuan90/MNN | dc0b62e817884f8fbc884f159b590feab2b0f0f8 | [
"Apache-2.0"
] | null | null | null | source/backend/hiai/3rdParty/include/c/compatible/hiai_model_tensor_info.h | SunXuan90/MNN | dc0b62e817884f8fbc884f159b590feab2b0f0f8 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) Huawei Technologies Co., Ltd. 2020-2021. All rights reserved.
* Description: model tensor info(deprecated)
*/
#ifndef FRAMEWORK_C_LEGACY_HIAI_MODEL_TENSOR_INFO_H
#define FRAMEWORK_C_LEGACY_HIAI_MODEL_TENSOR_INFO_H
#include "c/hiai_c_api_export.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct {
int inputCnt;
int outputCnt;
int* inputShape;
int* outputShape;
} HIAI_ModelTensorInfo;
AICP_C_API_EXPORT void HIAI_ModelManager_releaseModelTensorInfo(HIAI_ModelTensorInfo* modelTensor);
// v2
typedef enum {
HIAI_IO_INPUT = 0,
HIAI_IO_OUTPUT = 1,
HIAI_IO_INVALID = 255,
} HIAI_IO_TYPE;
typedef struct HIAI_TensorDescriptionV2 HIAI_TensorDescriptionV2;
typedef struct HIAI_ModelTensorInfoV2 HIAI_ModelTensorInfoV2;
AICP_C_API_EXPORT void HIAI_ModelManager_releaseModelTensorInfoV2(HIAI_ModelTensorInfoV2* modelTensor);
AICP_C_API_EXPORT int HIAI_ModelTensorInfoV2_getIOCount(const HIAI_ModelTensorInfoV2* tensorInfo, HIAI_IO_TYPE type);
AICP_C_API_EXPORT HIAI_TensorDescriptionV2* HIAI_ModelTensorInfoV2_getTensorDescription(
const HIAI_ModelTensorInfoV2* tensorInfo, HIAI_IO_TYPE type, int index);
AICP_C_API_EXPORT HIAI_TensorBuffer* HIAI_TensorBuffer_createFromTensorDescV2(HIAI_TensorDescriptionV2* tensor);
AICP_C_API_EXPORT int HIAI_TensorDescriptionV2_getDimensions(
const HIAI_TensorDescriptionV2* tensorDesc, int* n, int* c, int* h, int* w);
AICP_C_API_EXPORT const char* HIAI_TensorDescriptionV2_getName(const HIAI_TensorDescriptionV2* tensorDesc);
#ifdef __cplusplus
} // extern "C"
#endif
#endif // FRAMEWORK_C_LEGACY_HIAI_MODEL_TENSOR_INFO_H
| 31.346154 | 117 | 0.826994 | [
"model"
] |
af0ec5d7cfb2d41a43e4f3758c57c88f29eb6667 | 1,276 | h | C | src/HAL/Graphics/Renderer.h | gameraccoon/HideAndSeek | bc1e9c8dd725968ad4bc204877d8ddca2132ace7 | [
"MIT"
] | null | null | null | src/HAL/Graphics/Renderer.h | gameraccoon/HideAndSeek | bc1e9c8dd725968ad4bc204877d8ddca2132ace7 | [
"MIT"
] | null | null | null | src/HAL/Graphics/Renderer.h | gameraccoon/HideAndSeek | bc1e9c8dd725968ad4bc204877d8ddca2132ace7 | [
"MIT"
] | null | null | null | #pragma once
#include <array>
#include <vector>
#include <glm/fwd.hpp>
#include "GameData/Geometry/Vector2D.h"
#include "HAL/Base/Types.h"
#include "HAL/EngineFwd.h"
struct SDL_Renderer;
namespace HAL
{
namespace Internal
{
class Window;
}
}
namespace Graphics
{
class Font;
class Texture;
class Surface;
namespace Render
{
void BindSurface(const Surface& surface);
void DrawQuad(const glm::mat4& transform, Vector2D size, QuadUV uv, float alpha = 1.0f);
void DrawQuad(Vector2D pos, Vector2D size);
void DrawQuad(Vector2D pos, Vector2D size, Vector2D anchor, float rotation, QuadUV uv, float alpha = 1.0f);
void DrawFan(const std::vector<DrawPoint>& points, const glm::mat4& transform, float alpha);
void DrawStrip(const std::vector<DrawPoint>& points, const glm::mat4& transform, float alpha);
void DrawTiledQuad(Vector2D start, Vector2D size, const QuadUV& uv);
}
class Renderer
{
public:
Renderer() = default;
Renderer(const Renderer&) = delete;
Renderer& operator=(const Renderer&) = delete;
Renderer(Renderer&&) = delete;
Renderer& operator=(Renderer&&) = delete;
void renderText(const Font& font, Vector2D pos, Color color, const char* text);
std::array<int, 2> getTextSize(const Font& font, const char* text);
};
}
| 23.62963 | 109 | 0.721787 | [
"geometry",
"render",
"vector",
"transform"
] |
af1000b955cda80f9d6f159e66b08945e7b44689 | 10,117 | c | C | src/modules/game.c | Brendo-Lino/Star-Jam | 38d37c684bca1c2ab7ad782e4670a15a2eb81d71 | [
"MIT"
] | null | null | null | src/modules/game.c | Brendo-Lino/Star-Jam | 38d37c684bca1c2ab7ad782e4670a15a2eb81d71 | [
"MIT"
] | null | null | null | src/modules/game.c | Brendo-Lino/Star-Jam | 38d37c684bca1c2ab7ad782e4670a15a2eb81d71 | [
"MIT"
] | null | null | null | #include "game.h"
/* Structural Variables */
int running = 1;
int playing = 0;
int selecting = 1;
int waiting = 0;
int lost = 0;
int paused = 0;
int boss = 50;
int op_shots= 0;
/* Display and Event Queue */
ALLEGRO_DISPLAY *display = NULL;
ALLEGRO_EVENT_QUEUE *event_queue = NULL;
/* Timers */
ALLEGRO_TIMER *timer = NULL;
/* Fonts */
ALLEGRO_FONT *size_64 = NULL;
ALLEGRO_FONT *size_32 = NULL;
ALLEGRO_FONT *size_24 = NULL;
ALLEGRO_FONT *size_16 = NULL;
ALLEGRO_BITMAP *img_game_over = NULL;
ALLEGRO_BITMAP *img_press_start = NULL;
/* Sounds */
ALLEGRO_SAMPLE *soundtrack = NULL;
int main()
{
game_load();
game_run();
/* End-Game procedures */
al_destroy_display(display);
return 1;
}
void game_start(void)
{
game_reset();
playing = 1;
selecting = 0;
waiting = 0;
lost = 0;
}
void game_stop(void)
{
playing = 0;
waiting = 1;
}
void game_lose(void)
{
lost = 1;
playing = 0;
/* Saves the record */
if (score > record)
{
FILE *file;
file = fopen("data.txt", "w");
printf("%d", score);
fprintf(file, "%d", score);
fclose(file);
record = score;
}
}
void game_reset(void)
{
coins = 0;
score = 0;
boss = 20;
/* Loads the record */
FILE *record_file = fopen("data.txt", "r");
fscanf(record_file, "%d", &record);
fclose(record_file);
/* Resets the ship */
ship_reset();
shots_reset();
entities_reset();
planets_reset();
drops_reset();
/* Resets the timers*/
game_reset_timers();
}
void game_run(void)
{
al_play_sample(soundtrack, 0.1f, 0, 1.0, ALLEGRO_PLAYMODE_LOOP, 0);
srand(time(NULL));
game_reset_timers();
Ship *ship;
ship = ship_get_ship();
while (running)
{
ALLEGRO_EVENT event;
/* Waits for an event to happen */
al_wait_for_event(event_queue, &event);
/* Closes screen (Press X) */
if (event.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
{
running = 0;
break;
}
/* Timers flips */
if (event.type == ALLEGRO_EVENT_TIMER && !paused)
{
/* Display timer (60 flips per second) */
if (event.timer.source == timer)
{
// background
backgrounds_update();
if (playing)
{
/* Updates */
entities_update();
shots_update();
ship_update();
planets_update();
stats_update();
drops_update();
}
char score_text[100];
sprintf(score_text, "Record: %d", record);
if (selecting)
{
al_draw_text(size_64, al_map_rgb(255, 255, 255), 1280 / 2, 720 / 2 + al_get_bitmap_height(img_game_over) / 2, ALLEGRO_ALIGN_CENTER, score_text);
al_draw_bitmap(img_press_start, 1280 / 2 - al_get_bitmap_width(img_press_start) / 2, 720 / 2 - al_get_bitmap_height(img_press_start) / 2, 0);
}
if (lost)
{
al_draw_bitmap(img_game_over, 1280 / 2 - al_get_bitmap_width(img_game_over) / 2, 720 / 2 - al_get_bitmap_height(img_game_over) / 2, 0);
if (score >= record)
{
al_draw_text(size_64, al_map_rgb(255, 255, 255), 1280 / 2, 720 / 2 + al_get_bitmap_height(img_game_over) * 0.75, ALLEGRO_ALIGN_CENTER, "Congrats, new record!");
}
al_draw_text(size_64, al_map_rgb(255, 255, 255), 1280 / 2, 720 / 2 + al_get_bitmap_height(img_game_over) / 2, ALLEGRO_ALIGN_CENTER, score_text);
}
al_flip_display();
}
}
/* Keyboard Inputs Down */
if (event.type == ALLEGRO_EVENT_KEY_DOWN || event.type == ALLEGRO_EVENT_KEY_UP)
{
game_process_keyboard(&event);
}
}
}
void game_process_keyboard(ALLEGRO_EVENT *event)
{
Ship *ship;
ship = ship_get_ship();
Shot *shots;
shots = shots_get_shots();
/* Keyboard Inputs Down */
if (event->type == ALLEGRO_EVENT_KEY_DOWN)
{
if (playing)
{
switch (event->keyboard.keycode)
{
case ALLEGRO_KEY_UP:
ship->object.dirY--;
break;
case ALLEGRO_KEY_DOWN:
ship->object.dirY++;
break;
case ALLEGRO_KEY_LEFT:
ship->object.dirX--;
break;
case ALLEGRO_KEY_RIGHT:
ship->object.dirX++;
break;
case ALLEGRO_KEY_SPACE:
ship->shot_charging = 1;
break;
case ALLEGRO_KEY_P:
paused = !paused;
break;
case ALLEGRO_KEY_O:
op_shots = !op_shots;
break;
}
}
}
/* Keyboard Inputs Up */
if (event->type == ALLEGRO_EVENT_KEY_UP)
{
if (playing)
{
switch (event->keyboard.keycode)
{
case ALLEGRO_KEY_UP:
ship->object.dirY++;
break;
case ALLEGRO_KEY_DOWN:
ship->object.dirY--;
break;
case ALLEGRO_KEY_LEFT:
ship->object.dirX++;
break;
case ALLEGRO_KEY_RIGHT:
ship->object.dirX--;
break;
case ALLEGRO_KEY_SPACE:
ship->shot_charging = 0;
ship_fire_shot();
break;
}
}
if (selecting || lost)
{
switch (event->keyboard.keycode)
{
case ALLEGRO_KEY_ENTER:
game_start();
break;
}
}
}
}
void game_load(void)
{
game_setup_allegro();
stats_load();
backgrounds_load();
entities_load();
planets_load();
shots_load();
ship_load();
drops_load();
/* Sounds */
soundtrack = al_load_sample("assets/soundtrack/default.ogg");
/* Images */
img_game_over = al_load_bitmap("assets/stats/game_over.png");
img_press_start = al_load_bitmap("assets/stats/press_start.png");
al_reserve_samples(100);
game_reset();
}
void game_load_fonts(void)
{
// Loads the file vcr.ttf from VCR font and defines that will be used the size of 32 size_64 = al_load_font("vcr.ttf", 64, 1);
size_64 = al_load_font("fonts/vcr.ttf", 64, 1);
if (size_64 == NULL)
{
fprintf(stderr, "font file does not exist or cannot be accessed!\n");
}
// Loads the file vcr.ttf from VCR font and defines that will be used the size of 32
size_32 = al_load_font("fonts/vcr.ttf", 32, 1);
if (size_32 == NULL)
{
fprintf(stderr, "font file does not exist or cannot be accessed!\n");
}
// Loads the file vcr.ttf from VCR font and defines that will be used the size of 24
size_24 = al_load_font("fonts/vcr.ttf", 24, 1);
if (size_24 == NULL)
{
fprintf(stderr, "font file does not exist or cannot be accessed!\n");
}
// Loads the file vcr.ttf from VCR font and defines that will be used the size of 16
size_16 = al_load_font("fonts/vcr.ttf", 16, 1);
if (size_16 == NULL)
{
fprintf(stderr, "font file does not exist or cannot be accessed!\n");
}
}
int game_reset_timers(void)
{
// Creates a timer that increases one unit each 1.0/UPS second
timer = al_create_timer(1.0 / UPS);
if (!timer)
{
fprintf(stderr, "failed to create timer!\n");
return -1;
}
// Initializes the timer
al_start_timer(timer);
al_register_event_source(event_queue, al_get_timer_event_source(timer));
return 1;
}
int game_setup_allegro(void)
{
// Initializes Allegro
if (!al_init())
{
fprintf(stderr, "failed to initialize allegro!\n");
return 0;
}
// Initializes Allegro's primitive modules
if (!al_init_primitives_addon())
{
fprintf(stderr, "failed to initialize primitives!\n");
return 0;
}
// Initializes the module that allows loading images
if (!al_init_image_addon())
{
fprintf(stderr, "failed to initialize image module!\n");
return 0;
}
// Installs the keyboard
if (!al_install_keyboard())
{
fprintf(stderr, "failed to install keyboard!\n");
return 0;
}
// Installs the mouse
if (!al_install_mouse())
{
fprintf(stderr, "failed to initialize mouse!\n");
return 0;
}
// Installs the audio
if (!al_install_audio())
{
fprintf(stderr, "failed to initialize audio!\n");
return 0;
}
// Inits the audio codec
if (!al_init_acodec_addon())
{
fprintf(stderr, "failed to initialize audio codec!\n");
return 0;
}
// Initializes the font modules
al_init_font_addon();
// Initializes allegro's module that understand tff font files
if (!al_init_ttf_addon())
{
fprintf(stderr, "failed to load tff font module!\n");
return 0;
}
game_load_fonts();
// Creates a display with screen dimensions of SCREEN_W, SCREEN_H pixels
display = al_create_display(SCREEN_W, SCREEN_H);
if (!display)
{
fprintf(stderr, "failed to create display!\n");
return -1;
}
// Creates events queue
event_queue = al_create_event_queue();
if (!event_queue)
{
fprintf(stderr, "failed to create event_queue!\n");
al_destroy_display(display);
return -1;
}
// Register events
al_register_event_source(event_queue, al_get_display_event_source(display));
al_register_event_source(event_queue, al_get_keyboard_event_source());
al_register_event_source(event_queue, al_get_mouse_event_source());
return 1;
}
| 23.973934 | 184 | 0.553721 | [
"object"
] |
af1066d528db474be6a41292bc90cd08e89651e8 | 1,635 | h | C | compiler/loco/include/loco/IR/TensorShape.h | wateret/ONE_private | 9789c52633e665d2e10273d88d6f7970faa8aee9 | [
"Apache-2.0"
] | null | null | null | compiler/loco/include/loco/IR/TensorShape.h | wateret/ONE_private | 9789c52633e665d2e10273d88d6f7970faa8aee9 | [
"Apache-2.0"
] | null | null | null | compiler/loco/include/loco/IR/TensorShape.h | wateret/ONE_private | 9789c52633e665d2e10273d88d6f7970faa8aee9 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2019 Samsung Electronics Co., Ltd. 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.
*/
#ifndef __LOCO_IR_TENSOR_SHAPE_H__
#define __LOCO_IR_TENSOR_SHAPE_H__
#include "loco/IR/Dimension.h"
#include <initializer_list>
#include <vector>
namespace loco
{
class TensorShape
{
public:
TensorShape() = default;
TensorShape(std::initializer_list<Dimension> dims) : _dims(dims.begin(), dims.end()) {}
public:
uint32_t rank(void) const { return _dims.size(); }
void rank(uint32_t r) { _dims.resize(r); }
const Dimension &dim(uint32_t axis) const { return _dims.at(axis); }
Dimension &dim(uint32_t axis) { return _dims.at(axis); }
private:
std::vector<Dimension> _dims;
};
/**
* @brief Return the number of elements in a tensor of given shape
*
* NOTE 1.
*
* "volume" returns 1 if the rank is 0.
*
* NOTE 2.
*
* "caller" SHOULD pass a valid shape that has no unknown dimension.
* - The behavior of "volume" on invalid is undefined.
*
*/
uint32_t element_count(const loco::TensorShape *tensor_shape);
} // namespace loco
#endif // __LOCO_IR_TENSOR_SHAPE_H__
| 25.952381 | 89 | 0.720489 | [
"shape",
"vector"
] |
af132a80bef7b36b6d7790c1a6f56bbf2f154de1 | 8,396 | c | C | uFFT.c | cpuimage/ufft | 8bde703cb9467afeadc55cccece067490892f1e9 | [
"MIT"
] | 4 | 2020-01-29T12:45:18.000Z | 2021-07-11T08:29:35.000Z | uFFT.c | cpuimage/ufft | 8bde703cb9467afeadc55cccece067490892f1e9 | [
"MIT"
] | null | null | null | uFFT.c | cpuimage/ufft | 8bde703cb9467afeadc55cccece067490892f1e9 | [
"MIT"
] | 3 | 2018-08-28T10:17:30.000Z | 2021-05-25T01:46:38.000Z | #include "uFFT.h"
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#ifndef TWO_PI
#define TWO_PI (2.0f*3.14159265358979323846f)
#endif
#define FAST_MATH
#ifdef FAST_MATH
static float fastAbs(float f) {
int i = ((*(int *) &f) & 0x7fffffff);
return (*(float *) &i);
}
#endif
static float fastSin(float x) {
#ifdef FAST_MATH
const float pi = 3.14159265358979323846f;
const float B = 4 / pi;
const float C = -4 / (pi * pi);
const float P = 0.224008178776f;
const float Q = 0.775991821224f;
float y = (B + C * fastAbs(x)) * x;
return (Q + P * fastAbs(y)) * y;
#else
return sinf(x);
#endif
}
static float fastCos(float x) {
#ifdef FAST_MATH
const float pi = 3.14159265358979323846f;
const float P = 0.224008178776f;
const float Q = 0.775991821224f;
const float pi_2 = pi * 0.5f;
const float twopi = 2 * pi;
const float B = 4 / pi;
const float C = -4 / (pi * pi);
x += pi_2;
if (x > pi) {
x -= twopi;
}
float y = (B + C * fastAbs(x)) * x;
return (Q + P * fastAbs(y)) * y;
#else
return cosf(x);
#endif
}
static int ctz(size_t N) {
int ctz1 = 0;
while (N) {
ctz1++;
N >>= 1;
}
return ctz1 - 1;
}
static size_t revbits(size_t v, int J) {
size_t r = 0;
for (int j = 0; j < J; j++) {
r |= ((v >> j) & 1) << (J - 1 - j);
}
return r;
}
#ifndef USE_DIF
static void nop_split(const fft_complex *x, fft_complex *X, size_t N) {
size_t halfOfN = N >> 1;
const fft_complex *px = x;
const fft_complex *halfOfx = x + halfOfN;
fft_complex *pX = X;
for (size_t n = 0; n < halfOfN; n++) {
pX[0] = px[0];
pX[1] = halfOfx[0];
pX += 2;
halfOfx++;
px++;
}
}
static void fft_split(const fft_complex *x, fft_complex *X, size_t N, float phi) {
float t = (-TWO_PI) * phi;
fft_complex cexp;
cexp.real = fastCos(t);
cexp.imag = fastSin(t);
fft_complex val;
size_t halfOfN = N >> 1;
const fft_complex *px = x;
const fft_complex *halfOfx = x + halfOfN;
fft_complex *pX = X;
for (size_t n = 0; n < halfOfN; n++) {
pX[0].real = (px[0].real + halfOfx[0].real);
pX[0].imag = (px[0].imag + halfOfx[0].imag);
val.real = ((px[0].real - halfOfx[0].real));
val.imag = ((px[0].imag - halfOfx[0].imag));
pX[1].real = val.real * cexp.real - val.imag * cexp.imag;
pX[1].imag = val.real * cexp.imag + val.imag * cexp.real;
pX += 2;
px++;
halfOfx++;
}
}
static void ifft_split(const fft_complex *x, fft_complex *X, size_t N, float phi) {
float t = TWO_PI * phi;
fft_complex cexp;
cexp.real = fastCos(t);
cexp.imag = fastSin(t);
fft_complex val;
size_t halfOfN = N >> 1;
const fft_complex *px = x;
const fft_complex *halfOfx = x + halfOfN;
fft_complex *pX = X;
for (size_t n = 0; n < N / 2; n++) {
pX[0].real = (px[0].real + halfOfx[0].real) * 0.5f;
pX[0].imag = (px[0].imag + halfOfx[0].imag) * 0.5f;
val.real = ((0.5f * (px[0].real - halfOfx[0].real)));
val.imag = ((0.5f * (px[0].imag - halfOfx[0].imag)));
pX[1].real = val.real * cexp.real - val.imag * cexp.imag;
pX[1].imag = val.real * cexp.imag + val.imag * cexp.real;
pX += 2;
px++;
halfOfx++;
}
}
static int nop_reverse(int b, fft_complex *buffers[2], size_t N) {
int J = ctz(N);
for (int j = J - 2; j >= 0; j--, b++) {
size_t delta = N >> j;
for (size_t n = 0; n < N; n += delta) {
nop_split(buffers[b & 1] + n, buffers[~b & 1] + n, delta);
}
}
return b;
}
static int fft_reverse(int b, fft_complex *buffers[2], size_t N) {
int J = ctz(N);
for (int j = J - 1; j >= 0; j--, b++) {
size_t delta = N >> j;
for (size_t n = 0; n < N; n += delta) {
float phi = (float) revbits(n / delta, j) / (float) (2 << j);
fft_split(buffers[b & 1] + n, buffers[~b & 1] + n, delta, phi);
}
}
return b;
}
static int ifft_reverse(int b, fft_complex *buffers[2], size_t N) {
int J = ctz(N);
for (int j = J - 1; j >= 0; j--, b++) {
size_t delta = N >> j;
for (size_t n = 0; n < N; n += delta) {
float phi = (float) revbits(n / delta, j) / (float) (2 << j);
ifft_split(buffers[b & 1] + n, buffers[~b & 1] + n, delta, phi);
}
}
return b;
}
#else
static void nop_split(const fft_complex *x, fft_complex *X, size_t N) {
size_t halfOfN = N >> 1;
const fft_complex *px = x;
fft_complex *pX = X;
fft_complex *halfOfX = X + halfOfN;
for (size_t n = 0; n < halfOfN; n++) {
pX[0] = px[0];
halfOfX[0] = px[1];
px += 2;
pX++;
halfOfX++;
}
}
static void fft_split(const fft_complex *x, fft_complex *X, size_t N, float phi) {
float t = (-TWO_PI) * phi;
fft_complex cexp;
cexp.real = fastCos(t);
cexp.imag = fastSin(t);
fft_complex val;
size_t halfOfN = N >> 1;
const fft_complex *px = x;
fft_complex *pX = X;
fft_complex *halfOfX = X + halfOfN;
for (size_t n = 0; n < halfOfN; n++) {
val.real = px[1].real * cexp.real - px[1].imag * cexp.imag;
val.imag = px[1].real * cexp.imag + px[1].imag * cexp.real;
pX[0].real = (px[0].real + val.real);
pX[0].imag = (px[0].imag + val.imag);
halfOfX[0].real = (px[0].real - val.real);
halfOfX[0].imag = (px[0].imag - val.imag);
px += 2;
pX++;
halfOfX++;
}
}
static void ifft_split(const fft_complex *x, fft_complex *X, size_t N, float phi) {
float t = TWO_PI * phi;
fft_complex cexp;
cexp.real = fastCos(t);
cexp.imag = fastSin(t);
fft_complex val;
size_t halfOfN = N >> 1;
const fft_complex *px = x;
fft_complex *pX = X;
fft_complex *halfOfX = X + halfOfN;
for (size_t n = 0; n < halfOfN; n++) {
val.real = px[1].real * cexp.real - px[1].imag * cexp.imag;
val.imag = px[1].real * cexp.imag + px[1].imag * cexp.real;
pX[0].real = (px[0].real + val.real) * 0.5f;
pX[0].imag = (px[0].imag + val.imag) * 0.5f;
halfOfX[0].real = (px[0].real - val.real) * 0.5f;
halfOfX[0].imag = (px[0].imag - val.imag) * 0.5f;
px += 2;
pX++;
halfOfX++;
}
}
static int nop_reverse(int b, fft_complex *buffers[2], size_t N) {
int J = ctz(N);
for (int j = 0; j < J - 1; j++, b++) {
size_t delta = N >> j;
for (size_t n = 0; n < N; n += delta) {
nop_split(buffers[b & 1] + n, buffers[~b & 1] + n, delta);
}
}
return b;
}
static int fft_reverse(int b, fft_complex *buffers[2], size_t N) {
int J = ctz(N);
for (int j = 0; j < J; j++, b++) {
size_t delta = N >> j;
for (size_t n = 0; n < N; n += delta) {
float phi = (float) revbits(n / delta, j) / (float) (2 << j);
fft_split(buffers[b & 1] + n, buffers[~b & 1] + n, delta, phi);
}
}
return b;
}
static int ifft_reverse(int b, fft_complex *buffers[2], size_t N) {
int J = ctz(N);
for (int j = 0; j < J; j++, b++) {
size_t delta = N >> j;
for (size_t n = 0; n < N; n += delta) {
float phi = ((float) revbits(n / delta, j) / (float) (2 << j));
ifft_split(buffers[b & 1] + n, buffers[~b & 1] + n, delta, phi);
}
}
return b;
}
#endif
int fft(fft_complex *vector, size_t N) {
if (!N) return 0;
if (N & (N - 1)) return 1;
fft_complex *buffers[2] = {vector, malloc(N * sizeof(fft_complex))};
if (!buffers[1]) return -1;
int b = 0;
b = nop_reverse(b, buffers, N);
b = fft_reverse(b, buffers, N);
b = nop_reverse(b, buffers, N);
memmove(vector, buffers[b & 1], N * sizeof(fft_complex));
free(buffers[1]);
return 0;
}
int ifft(fft_complex *vector, size_t N) {
if (!N) return 0;
if (N & (N - 1)) return 1;
fft_complex *buffers[2] = {vector, malloc(N * sizeof(fft_complex))};
if (!buffers[1]) return -1;
int b = 0;
b = nop_reverse(b, buffers, N);
b = ifft_reverse(b, buffers, N);
b = nop_reverse(b, buffers, N);
memmove(vector, buffers[b & 1], N * sizeof(fft_complex));
free(buffers[1]);
return 0;
}
| 26.738854 | 83 | 0.52132 | [
"vector"
] |
af2de0383da0f72c28125089ab51421ca5e387a5 | 594 | h | C | include/ionshared/misc/helpers.h | ionlang/ionutil | a69abee226abcaf8f98fb56c03d3bc4605353728 | [
"Unlicense"
] | 1 | 2020-08-31T05:41:21.000Z | 2020-08-31T05:41:21.000Z | include/ionshared/misc/helpers.h | ionlang/ionutil | a69abee226abcaf8f98fb56c03d3bc4605353728 | [
"Unlicense"
] | null | null | null | include/ionshared/misc/helpers.h | ionlang/ionutil | a69abee226abcaf8f98fb56c03d3bc4605353728 | [
"Unlicense"
] | 1 | 2020-10-12T15:28:40.000Z | 2020-10-12T15:28:40.000Z | #pragma once
#include <map>
#include <string>
#include <optional>
#include <memory>
#include <vector>
#include <functional>
namespace ionshared {
template<typename T>
using Ptr = std::shared_ptr<T>;
template<typename T>
using ConstPtr = Ptr<const T>;
template<typename T>
using OptPtr = std::optional<Ptr<T>>;
template<typename T>
using Ref = std::reference_wrapper<T>;
template<typename T>
using OptRef = std::optional<Ref<T>>;
/**
* Alias for a reference vector.
*/
template<typename T>
using RefV = std::vector<Ref<T>>;
}
| 18.5625 | 42 | 0.643098 | [
"vector"
] |
af358f6daa694f61e8c1d1623ccd90ca2479be95 | 19,108 | c | C | lang/c/tests/test_aingle_data.c | AIngleLab/aae | 6e95f89fad60e62bb5305afe97c72f3278d8e04b | [
"Apache-2.0"
] | null | null | null | lang/c/tests/test_aingle_data.c | AIngleLab/aae | 6e95f89fad60e62bb5305afe97c72f3278d8e04b | [
"Apache-2.0"
] | null | null | null | lang/c/tests/test_aingle_data.c | AIngleLab/aae | 6e95f89fad60e62bb5305afe97c72f3278d8e04b | [
"Apache-2.0"
] | null | null | null | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to you 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
*
*
*
* 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 "aingle.h"
#include "aingle_private.h"
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
char buf[4096];
aingle_reader_t reader;
aingle_writer_t writer;
typedef int (*aingle_test) (void);
/*
* Use a custom allocator that verifies that the size that we use to
* free an object matches the size that we use to allocate it.
*/
static void *
test_allocator(void *ud, void *ptr, size_t osize, size_t nsize)
{
AINGLE_UNUSED(ud);
AINGLE_UNUSED(osize);
if (nsize == 0) {
size_t *size = ((size_t *) ptr) - 1;
if (osize != *size) {
fprintf(stderr,
"Error freeing %p:\n"
"Size passed to aingle_free (%" PRIsz ") "
"doesn't match size passed to "
"aingle_malloc (%" PRIsz ")\n",
ptr, osize, *size);
abort();
//exit(EXIT_FAILURE);
}
free(size);
return NULL;
} else {
size_t real_size = nsize + sizeof(size_t);
size_t *old_size = ptr? ((size_t *) ptr)-1: NULL;
size_t *size = (size_t *) realloc(old_size, real_size);
*size = nsize;
return (size + 1);
}
}
void init_rand(void)
{
srand(time(NULL));
}
double rand_number(double from, double to)
{
double range = to - from;
return from + ((double)rand() / (RAND_MAX + 1.0)) * range;
}
int64_t rand_int64(void)
{
return (int64_t) rand_number(LONG_MIN, LONG_MAX);
}
int32_t rand_int32(void)
{
return (int32_t) rand_number(INT_MIN, INT_MAX);
}
void
write_read_check(aingle_schema_t writers_schema, aingle_datum_t datum,
aingle_schema_t readers_schema, aingle_datum_t expected, char *type)
{
aingle_datum_t datum_out;
int validate;
for (validate = 0; validate <= 1; validate++) {
reader = aingle_reader_memory(buf, sizeof(buf));
writer = aingle_writer_memory(buf, sizeof(buf));
if (!expected) {
expected = datum;
}
/* Validating read/write */
if (aingle_write_data
(writer, validate ? writers_schema : NULL, datum)) {
fprintf(stderr, "Unable to write %s validate=%d\n %s\n",
type, validate, aingle_strerror());
exit(EXIT_FAILURE);
}
int64_t size =
aingle_size_data(writer, validate ? writers_schema : NULL,
datum);
if (size != aingle_writer_tell(writer)) {
fprintf(stderr,
"Unable to calculate size %s validate=%d "
"(%"PRId64" != %"PRId64")\n %s\n",
type, validate, size, aingle_writer_tell(writer),
aingle_strerror());
exit(EXIT_FAILURE);
}
if (aingle_read_data
(reader, writers_schema, readers_schema, &datum_out)) {
fprintf(stderr, "Unable to read %s validate=%d\n %s\n",
type, validate, aingle_strerror());
fprintf(stderr, " %s\n", aingle_strerror());
exit(EXIT_FAILURE);
}
if (!aingle_datum_equal(expected, datum_out)) {
fprintf(stderr,
"Unable to encode/decode %s validate=%d\n %s\n",
type, validate, aingle_strerror());
exit(EXIT_FAILURE);
}
aingle_reader_dump(reader, stderr);
aingle_datum_decref(datum_out);
aingle_reader_free(reader);
aingle_writer_free(writer);
}
}
static void test_json(aingle_datum_t datum, const char *expected)
{
char *json = NULL;
aingle_datum_to_json(datum, 1, &json);
if (strcasecmp(json, expected) != 0) {
fprintf(stderr, "Unexpected JSON encoding: %s\n", json);
exit(EXIT_FAILURE);
}
free(json);
}
static int test_string(void)
{
unsigned int i;
const char *strings[] = { "Four score and seven years ago",
"our father brought forth on this continent",
"a new nation", "conceived in Liberty",
"and dedicated to the proposition that all men are created equal."
};
aingle_schema_t writer_schema = aingle_schema_string();
for (i = 0; i < sizeof(strings) / sizeof(strings[0]); i++) {
aingle_datum_t datum = aingle_givestring(strings[i], NULL);
write_read_check(writer_schema, datum, NULL, NULL, "string");
aingle_datum_decref(datum);
}
aingle_datum_t datum = aingle_givestring(strings[0], NULL);
test_json(datum, "\"Four score and seven years ago\"");
aingle_datum_decref(datum);
// The following should bork if we don't copy the string value
// correctly (since we'll try to free a static string).
datum = aingle_string("this should be copied");
aingle_string_set(datum, "also this");
aingle_datum_decref(datum);
aingle_schema_decref(writer_schema);
return 0;
}
static int test_bytes(void)
{
char bytes[] = { 0xDE, 0xAD, 0xBE, 0xEF };
aingle_schema_t writer_schema = aingle_schema_bytes();
aingle_datum_t datum;
aingle_datum_t expected_datum;
datum = aingle_givebytes(bytes, sizeof(bytes), NULL);
write_read_check(writer_schema, datum, NULL, NULL, "bytes");
test_json(datum, "\"\\u00de\\u00ad\\u00be\\u00ef\"");
aingle_datum_decref(datum);
aingle_schema_decref(writer_schema);
datum = aingle_givebytes(NULL, 0, NULL);
aingle_givebytes_set(datum, bytes, sizeof(bytes), NULL);
expected_datum = aingle_givebytes(bytes, sizeof(bytes), NULL);
if (!aingle_datum_equal(datum, expected_datum)) {
fprintf(stderr,
"Expected equal bytes instances.\n");
exit(EXIT_FAILURE);
}
aingle_datum_decref(datum);
aingle_datum_decref(expected_datum);
// The following should bork if we don't copy the bytes value
// correctly (since we'll try to free a static string).
datum = aingle_bytes("original", 8);
aingle_bytes_set(datum, "alsothis", 8);
aingle_datum_decref(datum);
aingle_schema_decref(writer_schema);
return 0;
}
static int test_int32(void)
{
int i;
aingle_schema_t writer_schema = aingle_schema_int();
aingle_schema_t long_schema = aingle_schema_long();
aingle_schema_t float_schema = aingle_schema_float();
aingle_schema_t double_schema = aingle_schema_double();
for (i = 0; i < 100; i++) {
int32_t value = rand_int32();
aingle_datum_t datum = aingle_int32(value);
aingle_datum_t long_datum = aingle_int64(value);
aingle_datum_t float_datum = aingle_float(value);
aingle_datum_t double_datum = aingle_double(value);
write_read_check(writer_schema, datum, NULL, NULL, "int");
write_read_check(writer_schema, datum,
long_schema, long_datum, "int->long");
write_read_check(writer_schema, datum,
float_schema, float_datum, "int->float");
write_read_check(writer_schema, datum,
double_schema, double_datum, "int->double");
aingle_datum_decref(datum);
aingle_datum_decref(long_datum);
aingle_datum_decref(float_datum);
aingle_datum_decref(double_datum);
}
aingle_datum_t datum = aingle_int32(10000);
test_json(datum, "10000");
aingle_datum_decref(datum);
aingle_schema_decref(writer_schema);
aingle_schema_decref(long_schema);
aingle_schema_decref(float_schema);
aingle_schema_decref(double_schema);
return 0;
}
static int test_int64(void)
{
int i;
aingle_schema_t writer_schema = aingle_schema_long();
aingle_schema_t float_schema = aingle_schema_float();
aingle_schema_t double_schema = aingle_schema_double();
for (i = 0; i < 100; i++) {
int64_t value = rand_int64();
aingle_datum_t datum = aingle_int64(value);
aingle_datum_t float_datum = aingle_float(value);
aingle_datum_t double_datum = aingle_double(value);
write_read_check(writer_schema, datum, NULL, NULL, "long");
write_read_check(writer_schema, datum,
float_schema, float_datum, "long->float");
write_read_check(writer_schema, datum,
double_schema, double_datum, "long->double");
aingle_datum_decref(datum);
aingle_datum_decref(float_datum);
aingle_datum_decref(double_datum);
}
aingle_datum_t datum = aingle_int64(10000);
test_json(datum, "10000");
aingle_datum_decref(datum);
aingle_schema_decref(writer_schema);
aingle_schema_decref(float_schema);
aingle_schema_decref(double_schema);
return 0;
}
static int test_double(void)
{
int i;
aingle_schema_t schema = aingle_schema_double();
for (i = 0; i < 100; i++) {
aingle_datum_t datum = aingle_double(rand_number(-1.0E10, 1.0E10));
write_read_check(schema, datum, NULL, NULL, "double");
aingle_datum_decref(datum);
}
aingle_datum_t datum = aingle_double(2000.0);
test_json(datum, "2000.0");
aingle_datum_decref(datum);
aingle_schema_decref(schema);
return 0;
}
static int test_float(void)
{
int i;
aingle_schema_t schema = aingle_schema_float();
aingle_schema_t double_schema = aingle_schema_double();
for (i = 0; i < 100; i++) {
float value = rand_number(-1.0E10, 1.0E10);
aingle_datum_t datum = aingle_float(value);
aingle_datum_t double_datum = aingle_double(value);
write_read_check(schema, datum, NULL, NULL, "float");
write_read_check(schema, datum,
double_schema, double_datum, "float->double");
aingle_datum_decref(datum);
aingle_datum_decref(double_datum);
}
aingle_datum_t datum = aingle_float(2000.0);
test_json(datum, "2000.0");
aingle_datum_decref(datum);
aingle_schema_decref(schema);
aingle_schema_decref(double_schema);
return 0;
}
static int test_boolean(void)
{
int i;
const char *expected_json[] = { "false", "true" };
aingle_schema_t schema = aingle_schema_boolean();
for (i = 0; i <= 1; i++) {
aingle_datum_t datum = aingle_boolean(i);
write_read_check(schema, datum, NULL, NULL, "boolean");
test_json(datum, expected_json[i]);
aingle_datum_decref(datum);
}
aingle_schema_decref(schema);
return 0;
}
static int test_null(void)
{
aingle_schema_t schema = aingle_schema_null();
aingle_datum_t datum = aingle_null();
write_read_check(schema, datum, NULL, NULL, "null");
test_json(datum, "null");
aingle_datum_decref(datum);
return 0;
}
static int test_record(void)
{
aingle_schema_t schema = aingle_schema_record("person", NULL);
aingle_schema_record_field_append(schema, "name", aingle_schema_string());
aingle_schema_record_field_append(schema, "age", aingle_schema_int());
aingle_datum_t datum = aingle_record(schema);
aingle_datum_t name_datum, age_datum;
name_datum = aingle_givestring("Joseph Campbell", NULL);
age_datum = aingle_int32(83);
aingle_record_set(datum, "name", name_datum);
aingle_record_set(datum, "age", age_datum);
write_read_check(schema, datum, NULL, NULL, "record");
test_json(datum, "{\"name\": \"Joseph Campbell\", \"age\": 83}");
int rc;
aingle_record_set_field_value(rc, datum, int32, "age", 104);
int32_t age = 0;
aingle_record_get_field_value(rc, datum, int32, "age", &age);
if (age != 104) {
fprintf(stderr, "Incorrect age value\n");
exit(EXIT_FAILURE);
}
aingle_datum_decref(name_datum);
aingle_datum_decref(age_datum);
aingle_datum_decref(datum);
aingle_schema_decref(schema);
return 0;
}
static int test_nested_record(void)
{
const char *json =
"{"
" \"type\": \"record\","
" \"name\": \"list\","
" \"fields\": ["
" { \"name\": \"x\", \"type\": \"int\" },"
" { \"name\": \"y\", \"type\": \"int\" },"
" { \"name\": \"next\", \"type\": [\"null\",\"list\"]}"
" ]"
"}";
int rval;
aingle_schema_t schema = NULL;
aingle_schema_error_t error;
aingle_schema_from_json(json, strlen(json), &schema, &error);
aingle_datum_t head = aingle_datum_from_schema(schema);
aingle_record_set_field_value(rval, head, int32, "x", 10);
aingle_record_set_field_value(rval, head, int32, "y", 10);
aingle_datum_t next = NULL;
aingle_datum_t tail = NULL;
aingle_record_get(head, "next", &next);
aingle_union_set_discriminant(next, 1, &tail);
aingle_record_set_field_value(rval, tail, int32, "x", 20);
aingle_record_set_field_value(rval, tail, int32, "y", 20);
aingle_record_get(tail, "next", &next);
aingle_union_set_discriminant(next, 0, NULL);
write_read_check(schema, head, NULL, NULL, "nested record");
aingle_schema_decref(schema);
aingle_datum_decref(head);
return 0;
}
static int test_enum(void)
{
enum aingle_languages {
AINGLE_C,
AINGLE_CPP,
AINGLE_PYTHON,
AINGLE_RUBY,
AINGLE_JAVA
};
aingle_schema_t schema = aingle_schema_enum("language");
aingle_datum_t datum = aingle_enum(schema, AINGLE_C);
aingle_schema_enum_symbol_append(schema, "C");
aingle_schema_enum_symbol_append(schema, "C++");
aingle_schema_enum_symbol_append(schema, "Python");
aingle_schema_enum_symbol_append(schema, "Ruby");
aingle_schema_enum_symbol_append(schema, "Java");
if (aingle_enum_get(datum) != AINGLE_C) {
fprintf(stderr, "Unexpected enum value AINGLE_C\n");
exit(EXIT_FAILURE);
}
if (strcmp(aingle_enum_get_name(datum), "C") != 0) {
fprintf(stderr, "Unexpected enum value name C\n");
exit(EXIT_FAILURE);
}
write_read_check(schema, datum, NULL, NULL, "enum");
test_json(datum, "\"C\"");
aingle_enum_set(datum, AINGLE_CPP);
if (strcmp(aingle_enum_get_name(datum), "C++") != 0) {
fprintf(stderr, "Unexpected enum value name C++\n");
exit(EXIT_FAILURE);
}
write_read_check(schema, datum, NULL, NULL, "enum");
test_json(datum, "\"C++\"");
aingle_enum_set_name(datum, "Python");
if (aingle_enum_get(datum) != AINGLE_PYTHON) {
fprintf(stderr, "Unexpected enum value AINGLE_PYTHON\n");
exit(EXIT_FAILURE);
}
write_read_check(schema, datum, NULL, NULL, "enum");
test_json(datum, "\"Python\"");
aingle_datum_decref(datum);
aingle_schema_decref(schema);
return 0;
}
static int test_array(void)
{
int i, rval;
aingle_schema_t schema = aingle_schema_array(aingle_schema_int());
aingle_datum_t datum = aingle_array(schema);
for (i = 0; i < 10; i++) {
aingle_datum_t i32_datum = aingle_int32(i);
rval = aingle_array_append_datum(datum, i32_datum);
aingle_datum_decref(i32_datum);
if (rval) {
exit(EXIT_FAILURE);
}
}
if (aingle_array_size(datum) != 10) {
fprintf(stderr, "Unexpected array size");
exit(EXIT_FAILURE);
}
write_read_check(schema, datum, NULL, NULL, "array");
test_json(datum, "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]");
aingle_datum_decref(datum);
aingle_schema_decref(schema);
return 0;
}
static int test_map(void)
{
aingle_schema_t schema = aingle_schema_map(aingle_schema_long());
aingle_datum_t datum = aingle_map(schema);
int64_t i = 0;
char *nums[] =
{ "zero", "one", "two", "three", "four", "five", "six", NULL };
while (nums[i]) {
aingle_datum_t i_datum = aingle_int64(i);
aingle_map_set(datum, nums[i], i_datum);
aingle_datum_decref(i_datum);
i++;
}
if (aingle_array_size(datum) != 7) {
fprintf(stderr, "Unexpected map size\n");
exit(EXIT_FAILURE);
}
aingle_datum_t value;
const char *key;
aingle_map_get_key(datum, 2, &key);
aingle_map_get(datum, key, &value);
int64_t val;
aingle_int64_get(value, &val);
if (val != 2) {
fprintf(stderr, "Unexpected map value 2\n");
exit(EXIT_FAILURE);
}
int index;
if (aingle_map_get_index(datum, "two", &index)) {
fprintf(stderr, "Can't get index for key \"two\": %s\n",
aingle_strerror());
exit(EXIT_FAILURE);
}
if (index != 2) {
fprintf(stderr, "Unexpected index for key \"two\"\n");
exit(EXIT_FAILURE);
}
if (!aingle_map_get_index(datum, "foobar", &index)) {
fprintf(stderr, "Unexpected index for key \"foobar\"\n");
exit(EXIT_FAILURE);
}
write_read_check(schema, datum, NULL, NULL, "map");
test_json(datum,
"{\"zero\": 0, \"one\": 1, \"two\": 2, \"three\": 3, "
"\"four\": 4, \"five\": 5, \"six\": 6}");
aingle_datum_decref(datum);
aingle_schema_decref(schema);
return 0;
}
static int test_union(void)
{
aingle_schema_t schema = aingle_schema_union();
aingle_datum_t union_datum;
aingle_datum_t datum;
aingle_datum_t union_datum1;
aingle_datum_t datum1;
aingle_schema_union_append(schema, aingle_schema_string());
aingle_schema_union_append(schema, aingle_schema_int());
aingle_schema_union_append(schema, aingle_schema_null());
datum = aingle_givestring("Follow your bliss.", NULL);
union_datum = aingle_union(schema, 0, datum);
if (aingle_union_discriminant(union_datum) != 0) {
fprintf(stderr, "Unexpected union discriminant\n");
exit(EXIT_FAILURE);
}
if (aingle_union_current_branch(union_datum) != datum) {
fprintf(stderr, "Unexpected union branch datum\n");
exit(EXIT_FAILURE);
}
union_datum1 = aingle_datum_from_schema(schema);
aingle_union_set_discriminant(union_datum1, 0, &datum1);
aingle_givestring_set(datum1, "Follow your bliss.", NULL);
if (!aingle_datum_equal(datum, datum1)) {
fprintf(stderr, "Union values should be equal\n");
exit(EXIT_FAILURE);
}
write_read_check(schema, union_datum, NULL, NULL, "union");
test_json(union_datum, "{\"string\": \"Follow your bliss.\"}");
aingle_datum_decref(datum);
aingle_union_set_discriminant(union_datum, 2, &datum);
test_json(union_datum, "null");
aingle_datum_decref(union_datum);
aingle_datum_decref(datum);
aingle_datum_decref(union_datum1);
aingle_schema_decref(schema);
return 0;
}
static int test_fixed(void)
{
char bytes[] = { 0xD, 0xA, 0xD, 0xA, 0xB, 0xA, 0xB, 0xA };
aingle_schema_t schema = aingle_schema_fixed("msg", sizeof(bytes));
aingle_datum_t datum;
aingle_datum_t expected_datum;
datum = aingle_givefixed(schema, bytes, sizeof(bytes), NULL);
write_read_check(schema, datum, NULL, NULL, "fixed");
test_json(datum, "\"\\r\\n\\r\\n\\u000b\\n\\u000b\\n\"");
aingle_datum_decref(datum);
datum = aingle_givefixed(schema, NULL, sizeof(bytes), NULL);
aingle_givefixed_set(datum, bytes, sizeof(bytes), NULL);
expected_datum = aingle_givefixed(schema, bytes, sizeof(bytes), NULL);
if (!aingle_datum_equal(datum, expected_datum)) {
fprintf(stderr,
"Expected equal fixed instances.\n");
exit(EXIT_FAILURE);
}
aingle_datum_decref(datum);
aingle_datum_decref(expected_datum);
// The following should bork if we don't copy the fixed value
// correctly (since we'll try to free a static string).
datum = aingle_fixed(schema, "original", 8);
aingle_fixed_set(datum, "alsothis", 8);
aingle_datum_decref(datum);
aingle_schema_decref(schema);
return 0;
}
int main(void)
{
aingle_set_allocator(test_allocator, NULL);
unsigned int i;
struct aingle_tests {
char *name;
aingle_test func;
} tests[] = {
{
"string", test_string}, {
"bytes", test_bytes}, {
"int", test_int32}, {
"long", test_int64}, {
"float", test_float}, {
"double", test_double}, {
"boolean", test_boolean}, {
"null", test_null}, {
"record", test_record}, {
"nested_record", test_nested_record}, {
"enum", test_enum}, {
"array", test_array}, {
"map", test_map}, {
"fixed", test_fixed}, {
"union", test_union}
};
init_rand();
for (i = 0; i < sizeof(tests) / sizeof(tests[0]); i++) {
struct aingle_tests *test = tests + i;
fprintf(stderr, "**** Running %s tests ****\n", test->name);
if (test->func() != 0) {
return EXIT_FAILURE;
}
}
return EXIT_SUCCESS;
}
| 27.894891 | 75 | 0.71279 | [
"object"
] |
660d3647fb408250841c4cbfcf14dd35422d1213 | 1,530 | h | C | rh_engine_lib/Engine/VulkanImpl/VulkanRayTracingPipeline.h | petrgeorgievsky/gtaRenderHook | 124358410c3edca56de26381e239ca29aa6dc1cc | [
"MIT"
] | 232 | 2016-08-29T00:33:32.000Z | 2022-03-29T22:39:51.000Z | rh_engine_lib/Engine/VulkanImpl/VulkanRayTracingPipeline.h | petrgeorgievsky/gtaRenderHook | 124358410c3edca56de26381e239ca29aa6dc1cc | [
"MIT"
] | 10 | 2021-01-02T12:40:49.000Z | 2021-08-31T06:31:04.000Z | rh_engine_lib/Engine/VulkanImpl/VulkanRayTracingPipeline.h | petrgeorgievsky/gtaRenderHook | 124358410c3edca56de26381e239ca29aa6dc1cc | [
"MIT"
] | 40 | 2017-12-18T06:14:39.000Z | 2022-01-29T16:35:23.000Z | //
// Created by peter on 02.05.2020.
//
#pragma once
#include "VulkanGPUInfo.h"
#include <Engine/Common/ArrayProxy.h>
#include <Engine/Common/IPipeline.h>
#include <common.h>
namespace rh::engine
{
enum class RTShaderGroupType
{
General,
TriangleHitGroup,
ProceduralGeometry
};
struct RayTracingGroup
{
RTShaderGroupType mType;
uint32_t mGeneralId = ~0u;
uint32_t mAnyHitId = ~0u;
uint32_t mClosestHitId = ~0u;
uint32_t mIntersectionId = ~0u;
};
struct RayTracingPipelineCreateInfo
{
IPipelineLayout * mLayout;
ArrayProxy<ShaderStageDesc> mShaderStages;
ArrayProxy<RayTracingGroup> mShaderGroups;
};
struct VulkanRayTracingPipelineCreateInfo : RayTracingPipelineCreateInfo
{
// Dependencies...
vk::Device mDevice;
const VulkanRayTracingInfo &mGPUInfo;
};
class VulkanRayTracingPipeline
{
public:
VulkanRayTracingPipeline(
const VulkanRayTracingPipelineCreateInfo &create_info );
~VulkanRayTracingPipeline();
std::vector<uint8_t> GetShaderBindingTable();
uint32_t GetSBTHandleSize();
uint32_t GetSBTHandleSizeUnalign();
operator vk::Pipeline() { return mPipelineImpl; }
private:
vk::Pipeline mPipelineImpl;
vk::PipelineLayout mPipelineLayout;
vk::Device mDevice;
uint32_t mGroupCount;
const VulkanRayTracingInfo &mGPUInfo;
};
} // namespace rh::engine | 25.081967 | 72 | 0.659477 | [
"vector"
] |
660de2f20de7cdf5d7fe971f3c1cff20a25cfe27 | 468 | h | C | src/hypro/datastructures/HybridAutomaton/Pathv2.h | hypro/hypro | 52ae4ffe0a8427977fce8d7979fffb82a1bc28f6 | [
"MIT"
] | 22 | 2016-10-05T12:19:01.000Z | 2022-01-23T09:14:41.000Z | src/hypro/datastructures/HybridAutomaton/Pathv2.h | hypro/hypro | 52ae4ffe0a8427977fce8d7979fffb82a1bc28f6 | [
"MIT"
] | 23 | 2017-05-08T15:02:39.000Z | 2021-11-03T16:43:39.000Z | src/hypro/datastructures/HybridAutomaton/Pathv2.h | hypro/hypro | 52ae4ffe0a8427977fce8d7979fffb82a1bc28f6 | [
"MIT"
] | 12 | 2017-06-07T23:51:09.000Z | 2022-01-04T13:06:21.000Z | #pragma once
#include "../../types.h"
#include "Transition.h"
namespace hypro {
template <class Number>
struct Path {
Location<Number> const* rootLocation{};
std::vector<std::pair<carl::Interval<SegmentInd>, Transition<Number> const*> > elements{}; ///< Path in pairs of time and discrete steps. Intervals holds the information when the transition was taken.
Path() = default;
Path( size_t numElements )
: elements( numElements ) {}
};
} // namespace hypro | 26 | 201 | 0.711538 | [
"vector"
] |
6615f8c3ba2ee3936fd33a94ae07bb92dc08a276 | 6,550 | h | C | bundle/deepracer_msgs/include/deepracer_msgs/SetVisualVisibleRequest.h | larsll/deepracer-simapp | 9251c32ff33d49955b63ccca4f38d01a0c721d4f | [
"MIT"
] | 1 | 2022-02-23T20:34:00.000Z | 2022-02-23T20:34:00.000Z | bundle/deepracer_msgs/include/deepracer_msgs/SetVisualVisibleRequest.h | Bandwidth/deepracer-simapp | 9bf0a5f9c55e37ecef8e72b1b6dc15ecb0370bc1 | [
"MIT"
] | null | null | null | bundle/deepracer_msgs/include/deepracer_msgs/SetVisualVisibleRequest.h | Bandwidth/deepracer-simapp | 9bf0a5f9c55e37ecef8e72b1b6dc15ecb0370bc1 | [
"MIT"
] | null | null | null | // Generated by gencpp from file deepracer_msgs/SetVisualVisibleRequest.msg
// DO NOT EDIT!
#ifndef DEEPRACER_MSGS_MESSAGE_SETVISUALVISIBLEREQUEST_H
#define DEEPRACER_MSGS_MESSAGE_SETVISUALVISIBLEREQUEST_H
#include <string>
#include <vector>
#include <map>
#include <ros/types.h>
#include <ros/serialization.h>
#include <ros/builtin_message_traits.h>
#include <ros/message_operations.h>
namespace deepracer_msgs
{
template <class ContainerAllocator>
struct SetVisualVisibleRequest_
{
typedef SetVisualVisibleRequest_<ContainerAllocator> Type;
SetVisualVisibleRequest_()
: link_name()
, visual_name()
, visible(false)
, block(false) {
}
SetVisualVisibleRequest_(const ContainerAllocator& _alloc)
: link_name(_alloc)
, visual_name(_alloc)
, visible(false)
, block(false) {
(void)_alloc;
}
typedef std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > _link_name_type;
_link_name_type link_name;
typedef std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > _visual_name_type;
_visual_name_type visual_name;
typedef uint8_t _visible_type;
_visible_type visible;
typedef uint8_t _block_type;
_block_type block;
typedef boost::shared_ptr< ::deepracer_msgs::SetVisualVisibleRequest_<ContainerAllocator> > Ptr;
typedef boost::shared_ptr< ::deepracer_msgs::SetVisualVisibleRequest_<ContainerAllocator> const> ConstPtr;
}; // struct SetVisualVisibleRequest_
typedef ::deepracer_msgs::SetVisualVisibleRequest_<std::allocator<void> > SetVisualVisibleRequest;
typedef boost::shared_ptr< ::deepracer_msgs::SetVisualVisibleRequest > SetVisualVisibleRequestPtr;
typedef boost::shared_ptr< ::deepracer_msgs::SetVisualVisibleRequest const> SetVisualVisibleRequestConstPtr;
// constants requiring out of line definition
template<typename ContainerAllocator>
std::ostream& operator<<(std::ostream& s, const ::deepracer_msgs::SetVisualVisibleRequest_<ContainerAllocator> & v)
{
ros::message_operations::Printer< ::deepracer_msgs::SetVisualVisibleRequest_<ContainerAllocator> >::stream(s, "", v);
return s;
}
template<typename ContainerAllocator1, typename ContainerAllocator2>
bool operator==(const ::deepracer_msgs::SetVisualVisibleRequest_<ContainerAllocator1> & lhs, const ::deepracer_msgs::SetVisualVisibleRequest_<ContainerAllocator2> & rhs)
{
return lhs.link_name == rhs.link_name &&
lhs.visual_name == rhs.visual_name &&
lhs.visible == rhs.visible &&
lhs.block == rhs.block;
}
template<typename ContainerAllocator1, typename ContainerAllocator2>
bool operator!=(const ::deepracer_msgs::SetVisualVisibleRequest_<ContainerAllocator1> & lhs, const ::deepracer_msgs::SetVisualVisibleRequest_<ContainerAllocator2> & rhs)
{
return !(lhs == rhs);
}
} // namespace deepracer_msgs
namespace ros
{
namespace message_traits
{
template <class ContainerAllocator>
struct IsFixedSize< ::deepracer_msgs::SetVisualVisibleRequest_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct IsFixedSize< ::deepracer_msgs::SetVisualVisibleRequest_<ContainerAllocator> const>
: FalseType
{ };
template <class ContainerAllocator>
struct IsMessage< ::deepracer_msgs::SetVisualVisibleRequest_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::deepracer_msgs::SetVisualVisibleRequest_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct HasHeader< ::deepracer_msgs::SetVisualVisibleRequest_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct HasHeader< ::deepracer_msgs::SetVisualVisibleRequest_<ContainerAllocator> const>
: FalseType
{ };
template<class ContainerAllocator>
struct MD5Sum< ::deepracer_msgs::SetVisualVisibleRequest_<ContainerAllocator> >
{
static const char* value()
{
return "d93faa2da1676999e4228e6094b3f85f";
}
static const char* value(const ::deepracer_msgs::SetVisualVisibleRequest_<ContainerAllocator>&) { return value(); }
static const uint64_t static_value1 = 0xd93faa2da1676999ULL;
static const uint64_t static_value2 = 0xe4228e6094b3f85fULL;
};
template<class ContainerAllocator>
struct DataType< ::deepracer_msgs::SetVisualVisibleRequest_<ContainerAllocator> >
{
static const char* value()
{
return "deepracer_msgs/SetVisualVisibleRequest";
}
static const char* value(const ::deepracer_msgs::SetVisualVisibleRequest_<ContainerAllocator>&) { return value(); }
};
template<class ContainerAllocator>
struct Definition< ::deepracer_msgs::SetVisualVisibleRequest_<ContainerAllocator> >
{
static const char* value()
{
return "string link_name\n"
"string visual_name\n"
"bool visible\n"
"bool block\n"
;
}
static const char* value(const ::deepracer_msgs::SetVisualVisibleRequest_<ContainerAllocator>&) { return value(); }
};
} // namespace message_traits
} // namespace ros
namespace ros
{
namespace serialization
{
template<class ContainerAllocator> struct Serializer< ::deepracer_msgs::SetVisualVisibleRequest_<ContainerAllocator> >
{
template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m)
{
stream.next(m.link_name);
stream.next(m.visual_name);
stream.next(m.visible);
stream.next(m.block);
}
ROS_DECLARE_ALLINONE_SERIALIZER
}; // struct SetVisualVisibleRequest_
} // namespace serialization
} // namespace ros
namespace ros
{
namespace message_operations
{
template<class ContainerAllocator>
struct Printer< ::deepracer_msgs::SetVisualVisibleRequest_<ContainerAllocator> >
{
template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::deepracer_msgs::SetVisualVisibleRequest_<ContainerAllocator>& v)
{
s << indent << "link_name: ";
Printer<std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > >::stream(s, indent + " ", v.link_name);
s << indent << "visual_name: ";
Printer<std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > >::stream(s, indent + " ", v.visual_name);
s << indent << "visible: ";
Printer<uint8_t>::stream(s, indent + " ", v.visible);
s << indent << "block: ";
Printer<uint8_t>::stream(s, indent + " ", v.block);
}
};
} // namespace message_operations
} // namespace ros
#endif // DEEPRACER_MSGS_MESSAGE_SETVISUALVISIBLEREQUEST_H
| 28.982301 | 169 | 0.763359 | [
"vector"
] |
661db33a621d8b41906f9cd41e75a803fb35a8dd | 824 | h | C | Source/Core/CPU/PassManager.h | Sonicadvance1/X86Emu | 329e9eb1a60ef8353d1200fda454f835002e1ff0 | [
"CC0-1.0"
] | 13 | 2018-12-13T09:33:46.000Z | 2021-03-29T18:40:22.000Z | Source/Core/CPU/PassManager.h | Sonicadvance1/X86Emu | 329e9eb1a60ef8353d1200fda454f835002e1ff0 | [
"CC0-1.0"
] | null | null | null | Source/Core/CPU/PassManager.h | Sonicadvance1/X86Emu | 329e9eb1a60ef8353d1200fda454f835002e1ff0 | [
"CC0-1.0"
] | 4 | 2018-12-21T12:58:39.000Z | 2020-06-10T23:55:50.000Z | #pragma once
#include <string>
#include <vector>
namespace Emu::IR {
class PassManager;
class Pass {
public:
virtual std::string GetName() = 0;
protected:
friend PassManager;
Pass() {}
virtual void Run() = 0;
};
class BlockPass : public Pass {
public:
private:
virtual void Run() override final { RunOnBlock(); }
virtual void RunOnBlock() = 0;
};
class FunctionPass : public Pass {
public:
private:
virtual void Run() override final { RunOnFunction(); }
virtual void RunOnFunction() = 0;
};
class PassManager {
public:
virtual void Run() = 0;
void AddPass(Pass* pass) { passes.emplace_back(); }
private:
std::vector<Pass*> passes;
};
class BlockPassManager final : public PassManager {
public:
void Run();
};
class FunctionPassManager final : public PassManager {
public:
void Run();
};
}
| 15.54717 | 56 | 0.686893 | [
"vector"
] |
663f03cbeaf66850e709d7a8630de81f0c806a0c | 4,362 | c | C | src/shared/shared_session.c | LarsGardien/HackerDogeAir | a78d3dc8773d78b4f944f4dec573565858f4e5d1 | [
"MIT"
] | null | null | null | src/shared/shared_session.c | LarsGardien/HackerDogeAir | a78d3dc8773d78b4f944f4dec573565858f4e5d1 | [
"MIT"
] | null | null | null | src/shared/shared_session.c | LarsGardien/HackerDogeAir | a78d3dc8773d78b4f944f4dec573565858f4e5d1 | [
"MIT"
] | null | null | null | #include "shared/shared_session.h"
#include <time.h>
#include <kore/kore.h>
#include "shared/shared_error.h"
#include "model/session.h"
#include "model/user.h"
#include "model/role.h"
int
auth_user(struct http_request *req, const char *cookie)
{
uint32_t error = 0;
if (cookie == NULL)
{
return (KORE_RESULT_ERROR);
}
//find session
Session *session = session_find_by_session_identifier(cookie, &error);
if(error != (SHARED_OK) && error != (DATABASE_ENGINE_ERROR_NO_RESULTS))
{
kore_log(LOG_ERR, "auth_user: Failed to get session from database. error: %d", error);
return (KORE_RESULT_ERROR);
}
else if (error == (DATABASE_ENGINE_ERROR_NO_RESULTS))
{
return (KORE_RESULT_ERROR);
}
//check expiration time
time_t epoch_expiration_time = mktime(&session->expiration_time);
time_t epoch_current_time = time(NULL);
if(epoch_current_time > epoch_expiration_time)
{
auth_remove(req);
session_destroy(&session);
return (KORE_RESULT_ERROR);
}
//update expiration time
time_t epoch_new_expiration_time = epoch_current_time + 60 * 60;
struct tm *new_expiration_time = localtime(&epoch_new_expiration_time);
session->expiration_time = *new_expiration_time;
if((error = session_update(session)) != (SHARED_OK))
{
kore_log(LOG_ERR, "auth_user: failed to update session");
session_destroy(&session);
return (KORE_RESULT_ERROR);
}
//update cookie expiration time
http_response_cookie(req, "session", cookie, "/", epoch_new_expiration_time, 60*60, NULL);
session_destroy(&session);
return (KORE_RESULT_OK);
}
int
auth_admin(struct http_request *req, const char *cookie)
{
uint32_t error = 0;
if (cookie == NULL)
{
return (KORE_RESULT_ERROR);
}
//find session
Session *session = session_find_by_session_identifier(cookie, &error);
if(error != (SHARED_OK) && error != (DATABASE_ENGINE_ERROR_NO_RESULTS))
{
kore_log(LOG_ERR, "auth_admin: Failed to get session from database. error: %d", error);
return (KORE_RESULT_ERROR);
}
else if (error == (DATABASE_ENGINE_ERROR_NO_RESULTS))
{
return (KORE_RESULT_ERROR);
}
//check expiration time
time_t epoch_expiration_time = mktime(&session->expiration_time);
time_t epoch_current_time = time(NULL);
if(epoch_current_time > epoch_expiration_time)
{
auth_remove(req);
session_destroy(&session);
return (KORE_RESULT_ERROR);
}
//check admin
User *user = user_find_by_identifier(session->user_identifier, &error);
if(error != (SHARED_OK) || user == NULL)
{
kore_log(LOG_ERR, "auth_admin: Failed to get user from database.");
session_destroy(&session);
return (KORE_RESULT_ERROR);
}
else if(user->role != ADMIN)
{
kore_log(LOG_WARNING, "auth_admin: A non-privileged user tried to access /admin/*");
return (KORE_RESULT_ERROR);
}
//update expiration time
time_t epoch_new_expiration_time = epoch_current_time + 60 * 60;
struct tm *new_expiration_time = localtime(&epoch_new_expiration_time);
session->expiration_time = *new_expiration_time;
if((error = session_update(session)) != (SHARED_OK))
{
kore_log(LOG_ERR, "auth_admin: failed to update session");
session_destroy(&session);
return (KORE_RESULT_ERROR);
}
//update cookie expiration time
http_response_cookie(req, "session", cookie, "/", epoch_new_expiration_time, 60*60, NULL);
session_destroy(&session);
return (KORE_RESULT_OK);
}
int
auth_remove(struct http_request *req)
{
uint32_t error = 0;
char *session_identifier;
http_populate_cookies(req);
if (http_request_cookie(req, "session", &session_identifier) != (KORE_RESULT_OK))
{
kore_log(LOG_DEBUG, "COOKIE not found. can't log out");
return (SHARED_OK); //nothing to do
}
http_response_cookie(req, "session", "", "/", 0, 0, NULL);
//remove from db
Session session = {
.identifier = session_identifier
};
if((error = session_delete(&session)) != (SHARED_OK))
{
kore_log(LOG_ERR, "auth_remove: failed to remove session");
return error;
}
return (SHARED_OK);
}
| 30.71831 | 95 | 0.664374 | [
"model"
] |
664ab32172aff7449e06b99e79f9f03c78048dbf | 3,571 | c | C | source/main.c | tomjxyz/imposter_run | 905d7464978e156001fd6c88a275890de0ab7b40 | [
"WTFPL"
] | null | null | null | source/main.c | tomjxyz/imposter_run | 905d7464978e156001fd6c88a275890de0ab7b40 | [
"WTFPL"
] | null | null | null | source/main.c | tomjxyz/imposter_run | 905d7464978e156001fd6c88a275890de0ab7b40 | [
"WTFPL"
] | null | null | null | #include <stdio.h>
#include <wiiuse/wpad.h>
#include <grrlib.h>
#define BODY_COLOUR 0xC71012FF
#define EYES_COLOUR 0x95CADCFF
#define GRAVITY 1
#define JUMP_SPEED 15
typedef struct {
int x;
int y;
} Point;
typedef struct {
int width;
int height;
int xpos;
int ypos;
int speed;
} Block;
int scrWidth;
int scrHeight;
// For blocks to jump over
Block blocks[10];
// Properties for main imposter
Point imposterPos;
int velocity;
bool dead = false;
void resetBlocks(Block *blocks, int arrSize) {
for (int i = 0; i < arrSize; i++) {
blocks[i].width = scrHeight/16;
blocks[i].height = scrHeight/8;
blocks[i].speed = 5;
blocks[i].xpos = scrWidth+blocks[i].width + ((scrWidth+blocks[i].width)/arrSize-1)*i;
blocks[i].ypos = ((scrHeight/6)*5)-blocks[i].height;
}
}
// Draw character
void drawCrewmate(Point pos, u32 colour, bool dead){
int bodyW = scrHeight/12;
int bodyH = scrHeight/6;
if (!dead) {
// Body
GRRLIB_Rectangle(pos.x, pos.y, bodyW, bodyH, colour, true);
// Eye
GRRLIB_Rectangle(pos.x+5, pos.y+8, bodyW, scrHeight/16, EYES_COLOUR, true);
// Leg gap
GRRLIB_Rectangle(pos.x+(bodyW/2)-2, pos.y+(bodyH-20), 5, 20, 0x000000FF, true);
} else {
// Body
GRRLIB_Rectangle(pos.x, pos.y+bodyH/2, bodyW, bodyH/2, colour, true);
// Bone
GRRLIB_Rectangle(pos.x+(bodyW/2)-4, pos.y+(bodyH/2)-20, 8, 20, 0xFFFFFFFF, true);
GRRLIB_Circle(pos.x+(bodyW/2), pos.y+(bodyH/2)-20, 8, 0xFFFFFFFF, true);
// Leg gap
GRRLIB_Rectangle(pos.x+(bodyW/2)-2, pos.y+((bodyH/2)+20), 5, 20, 0x000000FF, true);
}
}
void gameplay() {
GRRLIB_FillScreen(0x000000FF); // Clear the screen
// Test character
// If touching floor
if (imposterPos.y+scrHeight/6 >= (scrHeight/6)*5) {
if (WPAD_ButtonsHeld(0) & WPAD_BUTTON_A && !dead)
velocity = -JUMP_SPEED; // Add upwards velocity when A pressed and still alive
else
velocity = 0;
}
else { // Add gravity to pull back down
velocity += GRAVITY;
}
// Move main character if jumping
imposterPos.y += velocity;
// Draw main imposter
drawCrewmate(imposterPos, BODY_COLOUR, dead);
// Floor
GRRLIB_Rectangle(0, (scrHeight/6)*5, scrWidth, (scrHeight/6)*5, 0xBABABAFF, true);
// Blocks to jump over
for (int i = 0; i < 4; i++) {
GRRLIB_Rectangle(blocks[i].xpos, blocks[i].ypos, blocks[i].width, blocks[i].height, 0x969696FF, true);
// If player hits a block
if (GRRLIB_RectOnRect(imposterPos.x, imposterPos.y, scrHeight/12, scrHeight/6,
blocks[i].xpos, blocks[i].ypos, blocks[i].width, blocks[i].height)) {
dead = true;
}
if (!dead) {
if (blocks[i].xpos < 0-blocks[i].width)
blocks[i].xpos = scrWidth;
else
blocks[i].xpos -= blocks[i].speed;
}
}
}
// Main entry point
int main() {
// Initialise graphics library
GRRLIB_Init();
scrWidth = rmode->fbWidth;
scrHeight = rmode->efbHeight;
// Initialise WiiMotes
WPAD_Init();
WPAD_SetDataFormat(WPAD_CHAN_0, WPAD_FMT_BTNS_ACC_IR);
imposterPos.x = scrWidth/5;
imposterPos.y = (scrHeight/5)*3;
// Initial blocks
resetBlocks(blocks, 4);
// Game loop
while(1) {
// Scan WiiMotes
WPAD_ScanPads();
// Get buttons pressed py p1
u32 pressed = WPAD_ButtonsDown(0);
// If home pressed, exit
if (pressed & WPAD_BUTTON_HOME)
break;
// Reset game after death
if (pressed & WPAD_BUTTON_B && dead) {
dead = !dead;
resetBlocks(blocks, 4);
}
// ------------ Place drawing code here -------------------
gameplay();
GRRLIB_Render(); // Render frame buffer to tv
}
GRRLIB_Exit(); // Clear memory used by graphics lib
return 0; // Return no error
}
| 23.493421 | 104 | 0.6634 | [
"render"
] |
666292b27205cff1ea91bb2286b1dc58c5057817 | 8,521 | h | C | include/mfmm/build_list.h | hjabird/exafmm-t | 9b6c4689b93eb47659bc2e70813073bf22d820a5 | [
"BSD-3-Clause"
] | null | null | null | include/mfmm/build_list.h | hjabird/exafmm-t | 9b6c4689b93eb47659bc2e70813073bf22d820a5 | [
"BSD-3-Clause"
] | null | null | null | include/mfmm/build_list.h | hjabird/exafmm-t | 9b6c4689b93eb47659bc2e70813073bf22d820a5 | [
"BSD-3-Clause"
] | null | null | null | #pragma once
/******************************************************************************
*
* mfmm
* A high-performance fast multipole method library using C++.
*
* A fork of ExaFMM (BSD-3-Clause lisence).
* Originally copyright Wang, Yokota and Barba.
*
* Modifications copyright HJA Bird.
*
******************************************************************************/
#ifndef INCLUDE_MFMM_BUILD_LIST_H_
#define INCLUDE_MFMM_BUILD_LIST_H_
#include <queue>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include "fmm.h"
#include "geometry.h"
#include "mfmm.h"
#include "octree_location.h"
namespace mfmm {
/** Generate the mapping from Morton keys to node indices in the tree.
* @param nodes Tree.
* @return Keys to indices mapping.
*/
template <typename T>
std::unordered_map<octree_location, size_t> get_key2id(const Nodes<T>& nodes) {
std::unordered_map<octree_location, size_t> key2id;
for (size_t i = 0; i < nodes.size(); ++i) {
key2id[nodes[i].location()] = nodes[i].index();
}
return key2id;
}
/** Generate the set of keys of all leaf nodes.
* @param nodes Tree.
* @return Set of all leaf keys with level offset.
*/
template <typename T>
std::unordered_set<octree_location> get_leaf_keys(const Nodes<T>& nodes) {
// we cannot use leafs to generate leaf keys, since it does not include
// empty leaf nodes where ntrgs and nsrcs are 0.
std::unordered_set<octree_location> leafKeys;
for (size_t i = 0; i < nodes.size(); ++i) {
if (nodes[i].is_leaf()) {
leafKeys.insert(nodes[i].location());
}
}
return leafKeys;
}
/** Given the 3D index of an octant and its depth, return the key of
* the leaf that contains the octant. If such leaf does not exist, return the
* key of the original octant.
* @param iX Integer index of the octant.
* @param level The level of the octant.
* @return Morton index with level offset.
*/
octree_location find_key(const ivec3& iX, int level,
const std::unordered_set<octree_location>& leafKeys) {
octree_location originalKey(iX, level);
octree_location currentKey = originalKey;
while (level > 0) {
if (leafKeys.find(currentKey) != leafKeys.end()) { // if key is leaf
return currentKey;
} else { // else go 1 level up
currentKey = currentKey.parent();
level--;
}
}
return originalKey;
}
/** Build lists for P2P, P2L and M2P operators for a given node.
* @param node Node.
* @param nodes Tree.
* @param leafKeys The set of all leaf keys.
* @param key2id The mapping from a node's key to its index in the tree.
*/
template <typename FmmT>
void build_other_list(
Node<typename FmmT::potential_t>* node,
Nodes<typename FmmT::potential_t>& nodes, const FmmT& fmm,
const std::unordered_set<octree_location>& leafKeys,
const std::unordered_map<octree_location, size_t>& key2id) {
using node_t = Node<typename FmmT::potential_t>;
std::set<node_t*> p2pSet, m2pSet, p2lSet;
node_t& currentNode = *node;
if (currentNode.location() != octree_location(0, 0)) {
node_t* parent = currentNode.parent();
ivec3 min3dIdx = {0, 0, 0};
ivec3 max3dIdx = ivec3::Ones(3) * (1 << node->location().level());
ivec3 current3dIdx = currentNode.location().get_3D_index();
ivec3 parent3dIdx = parent->location().get_3D_index();
// search in every direction
for (int i = -2; i < 4; i++) {
for (int j = -2; j < 4; j++) {
for (int k = -2; k < 4; k++) {
ivec3 direction{i, j, k};
direction += parent3dIdx * 2;
if ((direction.array() >= min3dIdx.array()).all() &&
(direction.array() < max3dIdx.array()).all() &&
direction != current3dIdx) {
octree_location resKey =
find_key(direction, currentNode.location().level(), leafKeys);
bool adj = resKey.is_adjacent(currentNode.location());
node_t& res = nodes[key2id.at(resKey)];
if (res.location().level() <
currentNode.location().level()) { // when res node is a leaf
if (adj) {
if (currentNode.is_leaf()) {
p2pSet.insert(&res);
}
} else {
if (currentNode.is_leaf() &&
currentNode.num_targets() <= fmm.m_numSurf) {
p2pSet.insert(&res);
} else {
p2lSet.insert(&res);
}
}
}
if (res.location().level() ==
currentNode.location().level()) { // when res is a colleague
if (adj) {
if (currentNode.is_leaf()) {
std::queue<node_t*> buffer;
buffer.push(&res);
while (!buffer.empty()) {
node_t& temp = *buffer.front();
buffer.pop();
if (!temp.location().is_adjacent(currentNode.location())) {
if (temp.is_leaf() &&
temp.num_sources() <= fmm.m_numSurf) {
p2pSet.insert(&temp);
} else {
m2pSet.insert(&temp);
}
} else {
if (temp.is_leaf()) {
p2pSet.insert(&temp);
} else {
for (int i = 0; i < NCHILD; i++) {
if (temp.has_child(i)) {
buffer.push(&temp.child(i));
}
}
}
}
}
}
}
}
}
}
}
}
}
if (currentNode.is_leaf()) {
p2pSet.insert(¤tNode);
}
for (auto i = p2pSet.begin(); i != p2pSet.end(); i++) {
if ((*i) != nullptr) {
currentNode.P2Plist().push_back(*i);
}
}
for (auto i = p2lSet.begin(); i != p2lSet.end(); i++) {
if ((*i) != nullptr) {
currentNode.P2Llist().push_back(*i);
}
}
for (auto i = m2pSet.begin(); i != m2pSet.end(); i++) {
if ((*i) != nullptr) {
currentNode.M2Plist().push_back(*i);
}
}
}
/** Build M2L interaction list for a given node.
* @param node Node.
* @param nodes Tree.
* @param key2id The mapping from a node's key to its index in the tree.
*/
template <typename T>
void build_M2L_list(Node<T>* node, Nodes<T>& nodes,
const std::unordered_map<octree_location, size_t>& key2id) {
using node_t = Node<T>;
node->M2Llist().resize(REL_COORD_M2L.size(), nullptr);
node_t& currentNode = *node;
ivec3 min3dIdx = {0, 0, 0};
ivec3 max3dIdx = ivec3::Ones(3) * (1 << currentNode.location().level());
if (!currentNode.is_leaf()) {
ivec3 current3dIdx = currentNode.location().get_3D_index();
for (int i = -1; i <= 1; i++) {
for (int j = -1; j <= 1; j++) {
for (int k = -1; k <= 1; k++) {
if (i || j || k) { // exclude current node itself
ivec3 relativeCoord{i, j, k};
ivec3 nearby3dIdx = current3dIdx + relativeCoord;
if ((nearby3dIdx.array() >= min3dIdx.array()).all() &&
(nearby3dIdx.array() < max3dIdx.array()).all()) {
octree_location nearbyLoc(nearby3dIdx,
currentNode.location().level());
if (key2id.find(nearbyLoc) != key2id.end()) {
node_t& nearbyNode = nodes[key2id.at(nearbyLoc)];
if (!nearbyNode.is_leaf()) {
size_t idx = REL_COORD_M2L.hash(relativeCoord);
currentNode.M2Llist()[idx] = &nearbyNode;
}
}
}
}
}
}
}
}
}
/** Build lists for all operators for all nodes in the tree.
* @param nodes Tree.
* @param fmm The FMM instance.
*/
template <typename FmmT>
void build_list(Nodes<typename FmmT::potential_t>& nodes, const FmmT& fmm) {
using node_t = Node<typename FmmT::potential_t>;
std::unordered_map<octree_location, size_t> key2id = get_key2id(nodes);
std::unordered_set<octree_location> leaf_keys = get_leaf_keys(nodes);
#pragma omp parallel for schedule(dynamic)
for (int i = 0; i < static_cast<int>(nodes.size()); i++) {
node_t* node = &nodes[i];
build_M2L_list(node, nodes, key2id);
build_other_list(node, nodes, fmm, leaf_keys, key2id);
}
}
} // namespace mfmm
#endif // INCLUDE_MFMM_BUILD_LIST_H_
| 35.065844 | 80 | 0.548997 | [
"geometry",
"3d"
] |
e2f906b2d75c00d8fe541a135ffa894e089906e4 | 244 | h | C | Vulkan/src/engine/vulkan/ShaderModule.h | dtrajko/HazelGameEngineSeries | 7210151d6422078ced080be9b8886e9a1ad79d7a | [
"Apache-2.0"
] | null | null | null | Vulkan/src/engine/vulkan/ShaderModule.h | dtrajko/HazelGameEngineSeries | 7210151d6422078ced080be9b8886e9a1ad79d7a | [
"Apache-2.0"
] | null | null | null | Vulkan/src/engine/vulkan/ShaderModule.h | dtrajko/HazelGameEngineSeries | 7210151d6422078ced080be9b8886e9a1ad79d7a | [
"Apache-2.0"
] | null | null | null | #pragma once
#define GLFW_INCLUDE_VULKAN
#include <GLFW/glfw3.h>
#include <vector>
class ShaderModule
{
public:
ShaderModule(VkDevice device, const std::vector<char>& code);
~ShaderModule();
public:
VkShaderModule m_ShaderModule;
};
| 11.619048 | 62 | 0.745902 | [
"vector"
] |
e2fa42b68ea47b6391aeaa983f28975165b0f0ea | 1,529 | h | C | src/transfer_context.h | totalorder/godot-jvm | d3a856d10d2f6fccef1e63b73b96b6b79bb8536d | [
"MIT"
] | null | null | null | src/transfer_context.h | totalorder/godot-jvm | d3a856d10d2f6fccef1e63b73b96b6b79bb8536d | [
"MIT"
] | null | null | null | src/transfer_context.h | totalorder/godot-jvm | d3a856d10d2f6fccef1e63b73b96b6b79bb8536d | [
"MIT"
] | null | null | null | #ifndef GODOT_JVM_TRANSFER_CONTEXT_H
#define GODOT_JVM_TRANSFER_CONTEXT_H
#include "java_instance_wrapper.h"
#include "kt_variant.h"
#define MAX_ARGS_SIZE 16
class TransferContext : public JavaInstanceWrapper {
public:
struct SharedBuffer {
void* ptr;
int capacity;
};
TransferContext(jni::JObject p_wrapped, jni::JObject p_class_loader);
~TransferContext() = default;
TransferContext(const TransferContext&) = delete;
void operator=(const TransferContext&) = delete;
void write_return_value(jni::Env& p_env, const KtVariant& p_value);
KtVariant read_return_value(jni::Env& p_env, bool p_refresh_buffer);
void write_args(jni::Env& p_env, const Vector<KtVariant>& p_args);
Vector<KtVariant> read_args(jni::Env& p_env, bool p_refresh_buffer);
static void icall(JNIEnv* rawEnv, jobject instance, jlong jPtr,
jstring jClassName, jstring jMethod,
jint expectedReturnType, bool p_refresh_buffer);
static jlong invoke_constructor(JNIEnv* p_raw_env, jobject p_instance, jstring p_class_name);
static void set_script(JNIEnv* p_raw_env, jobject p_instance, jlong p_raw_ptr, jstring p_class_name, jobject p_object,
jobject p_class_loader);
static void free_object(JNIEnv* p_raw_env, jobject p_instance, jlong p_raw_ptr);
private:
SharedBuffer* get_buffer(jni::Env& p_env, bool p_refresh_buffer);
bool ensure_capacity(jni::Env& p_env, long p_capacity);
};
#endif //GODOT_JVM_TRANSFER_CONTEXT_H
| 36.404762 | 122 | 0.737737 | [
"vector"
] |
39028d63102c40d8ec28ed1b76ee477e89a01669 | 3,235 | h | C | osgVegetation/ov_TerrainShadingStateSet.h | leadcoder/osgVegetation | c13bb8e0225467c97b0bc85f3d38826f793c368e | [
"MIT"
] | 22 | 2015-01-22T17:51:17.000Z | 2021-12-24T06:59:46.000Z | osgVegetation/ov_TerrainShadingStateSet.h | leadcoder/osgVegetation | c13bb8e0225467c97b0bc85f3d38826f793c368e | [
"MIT"
] | null | null | null | osgVegetation/ov_TerrainShadingStateSet.h | leadcoder/osgVegetation | c13bb8e0225467c97b0bc85f3d38826f793c368e | [
"MIT"
] | 10 | 2015-12-31T05:52:30.000Z | 2020-03-13T05:31:51.000Z | #pragma once
#include "ov_Common.h"
#include "ov_TerrainStateSet.h"
#include <osg/Vec2>
#include <osg/Program>
#include <osg/Texture2D>
#include <osg/Texture2DArray>
#include <osgDB/ReadFile>
#include <osgDB/FileUtils>
#include <vector>
namespace osgVegetation
{
class TerrainShadingStateSetConfig : public TerrainStateSetConfig
{
public:
TerrainShadingStateSetConfig() : TerrainStateSetConfig(), UseTessellation(false),
NoiseTexture(Register.TexUnits.GetUnit(OV_TERRAIN_NOISE_TEXTURE_ID))
{
}
TextureConfig NoiseTexture;
bool UseTessellation;
};
class TerrainShadingStateSet : public TerrainStateSet
{
public:
TerrainShadingStateSet(const TerrainShadingStateSetConfig& config) : TerrainStateSet(config)
{
if (config.UseTessellation)
setDefine("OV_TERRAIN_TESSELLATION");
_SetNoiseTexture(config.NoiseTexture);
osg::Program* program = _CreateProgram(config);
setAttribute(program, osg::StateAttribute::PROTECTED | osg::StateAttribute::ON);
}
private:
osg::Program* _CreateProgram(const TerrainShadingStateSetConfig& config)
{
osg::Program* program = new osg::Program;
program->addShader(osg::Shader::readShaderFile(osg::Shader::VERTEX, osgDB::findDataFile("ov_terrain_vertex.glsl")));
program->addShader(osg::Shader::readShaderFile(osg::Shader::VERTEX, osgDB::findDataFile("ov_terrain_elevation.glsl")));
program->addShader(osg::Shader::readShaderFile(osg::Shader::VERTEX, osgDB::findDataFile("ov_shadow_vertex.glsl")));
if (config.UseTessellation)
{
program->addShader(osg::Shader::readShaderFile(osg::Shader::TESSCONTROL, osgDB::findDataFile("ov_terrain_tess_ctrl.glsl")));
program->addShader(osg::Shader::readShaderFile(osg::Shader::TESSEVALUATION, osgDB::findDataFile("ov_shadow_vertex.glsl")));
program->addShader(osg::Shader::readShaderFile(osg::Shader::TESSEVALUATION, osgDB::findDataFile("ov_terrain_elevation.glsl")));
program->addShader(osg::Shader::readShaderFile(osg::Shader::TESSEVALUATION, osgDB::findDataFile("ov_terrain_tess_eval.glsl")));
}
program->addShader(osg::Shader::readShaderFile(osg::Shader::FRAGMENT, osgDB::findDataFile("ov_common_fragment.glsl")));
program->addShader(osg::Shader::readShaderFile(osg::Shader::FRAGMENT, osgDB::findDataFile("ov_shadow_fragment.glsl")));
program->addShader(osg::Shader::readShaderFile(osg::Shader::FRAGMENT, osgDB::findDataFile("ov_terrain_color.glsl")));
program->addShader(osg::Shader::readShaderFile(osg::Shader::FRAGMENT, osgDB::findDataFile("ov_terrain_fragment.glsl")));
return program;
}
void _SetNoiseTexture(TextureConfig config)
{
//auto generate id
if (config.TexUnit < 0 && config.Texture || config.File != "")
{
config.TexUnit = Register.TexUnits.CreateOrGetUnit(OV_TERRAIN_NOISE_TEXTURE_ID);
}
_ApplyTextureConfig(config);
if (config.TexUnit >= 0)
{
addUniform(new osg::Uniform("ov_noise_texture", config.TexUnit));
setDefine("OV_NOISE_TEXTURE");
}
}
};
class TerrainShadingEffect : public osg::Group
{
public:
TerrainShadingEffect(const TerrainShadingStateSetConfig& config)
{
osg::ref_ptr<osg::StateSet> state_set = new TerrainShadingStateSet(config);
setStateSet(state_set);
}
};
} | 36.761364 | 131 | 0.752396 | [
"vector"
] |
39036b95c7e7b2c625f0a3586a72f1f2678f74fd | 5,315 | h | C | apps/Viewer/inc/ScenePropertiesWidget.h | asuessenbach/pipeline | 2e49968cc3b9948a57f7ee6c4cc3258925c92ab2 | [
"BSD-3-Clause"
] | 217 | 2015-01-06T09:26:53.000Z | 2022-03-23T14:03:18.000Z | apps/Viewer/inc/ScenePropertiesWidget.h | asuessenbach/pipeline | 2e49968cc3b9948a57f7ee6c4cc3258925c92ab2 | [
"BSD-3-Clause"
] | 10 | 2015-01-25T12:42:05.000Z | 2017-11-28T16:10:16.000Z | apps/Viewer/inc/ScenePropertiesWidget.h | asuessenbach/pipeline | 2e49968cc3b9948a57f7ee6c4cc3258925c92ab2 | [
"BSD-3-Clause"
] | 44 | 2015-01-13T01:19:41.000Z | 2022-02-21T21:35:08.000Z |
// Copyright NVIDIA Corporation 2009-2010
// 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.
#pragma once
#include <dp/sg/core/Object.h>
#include <QBoxLayout>
#include <QDockWidget>
#include <QValidator>
class ScenePropertiesWidget : public QDockWidget
{
Q_OBJECT
public:
ScenePropertiesWidget(QWidget *parent = 0);
virtual ~ScenePropertiesWidget();
virtual void clear();
public slots:
void adjustRangesClicked( bool checked );
void colorButtonClicked( bool checked );
void currentColorChanged( const QColor & color );
void currentItemChanged( dp::sg::core::ObjectSharedPtr current, dp::sg::core::ObjectSharedPtr previous );
void editingFinishedFloat();
void editingFinishedString();
void editingFinishedUInt();
void enumIndexChanged( int index );
void spinValueChanged( int value );
void stateChangedBool( int state );
void textureSelectionClicked( bool checked );
void valueChangedArray( double value );
void valueChangedFloat( int value );
protected:
void displayItem( dp::sg::core::ObjectSharedPtr const & object );
void updateItem();
private:
class ObjectObserver : public dp::util::Observer
{
public:
ObjectObserver( ScenePropertiesWidget * spw )
: m_spw(spw)
{
}
virtual void onNotify( const dp::util::Event &event, dp::util::Payload *payload )
{
m_spw->updateItem();
}
virtual void onDestroyed( const dp::util::Subject& subject, dp::util::Payload* payload )
{
}
private:
ScenePropertiesWidget * m_spw;
};
private:
QWidget * createEdit( bool value, dp::util::PropertyId pid, bool enabled );
QLayout * createEdit( float value, dp::util::PropertyId pid, bool enabled );
template<unsigned int N> QLayout * createEdit( const dp::math::Vecnt<N,float> & value, dp::util::PropertyId pid, bool enabled );
QWidget * createEdit( int value, dp::util::PropertyId pid, bool enabled );
QWidget * createEdit( unsigned int value, dp::util::PropertyId pid, bool enabled );
QWidget * createEdit( const std::string & value, dp::util::PropertyId pid, bool enabled );
QWidget * createEdit( const dp::sg::core::TextureSharedPtr & value, dp::util::PropertyId pid, bool enabled );
QLayout * createEdit( const dp::math::Quatf & value, dp::util::PropertyId pid, bool enabled );
QHBoxLayout * createLabledSlider( dp::util::PropertyId pid, float value, float min, float max, unsigned int size = 0, unsigned int index = 0 );
void updateEdit( QWidget * widget, bool value );
void updateEdit( QLayout * layout, float value, dp::util::PropertyId pid );
template<unsigned int N> void updateEdit( QLayout * layout, const dp::math::Vecnt<N,float> & value, dp::util::PropertyId pid );
void updateEdit( QWidget * widget, int value, dp::util::PropertyId pid );
void updateEdit( QWidget * widget, unsigned int value );
void updateEdit( QWidget * widget, const std::string & value );
void updateEdit( QLayout * layout, const dp::math::Quatf & value );
void updateEdit( QWidget * widget, const dp::sg::core::TextureSharedPtr & value );
void updateLabledSlider( QHBoxLayout * layout, float value );
template<typename T> bool setValue( dp::util::PropertyId pid, const T & value );
template<typename T> bool setValue( dp::util::PropertyId pid, unsigned int size, unsigned int index, const T & value );
template<typename T, unsigned int N> bool setSubValue( dp::util::PropertyId pid, unsigned int index, const T & value );
private:
QRegExpValidator * m_hexValidator;
dp::sg::core::ObjectSharedPtr m_object;
ObjectObserver m_objectObserver;
};
| 45.818966 | 148 | 0.692568 | [
"object"
] |
3904c5868dddd76c1aba7963161a54ff0759de30 | 358 | h | C | HBImagePicker/View/PreviewVideoCell.h | jiutianhuanpei/HBImagePicker | 2a39f50cf90cdd9c37a647e161d924b5436071aa | [
"MIT"
] | 1 | 2019-08-14T14:09:23.000Z | 2019-08-14T14:09:23.000Z | HBImagePicker/View/PreviewVideoCell.h | jiutianhuanpei/HBImagePicker | 2a39f50cf90cdd9c37a647e161d924b5436071aa | [
"MIT"
] | null | null | null | HBImagePicker/View/PreviewVideoCell.h | jiutianhuanpei/HBImagePicker | 2a39f50cf90cdd9c37a647e161d924b5436071aa | [
"MIT"
] | null | null | null | //
// PreviewVideoCell.h
// ImagePickerDemo
//
// Created by 沈红榜 on 2018/7/4.
// Copyright © 2018年 沈红榜. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "AssetModel.h"
@interface PreviewVideoCell : UICollectionViewCell
@property (nonatomic, strong, readonly) AssetModel *model;
- (void)configModel:(AssetModel *)model;
- (void)stopPlay;
@end
| 17.9 | 58 | 0.715084 | [
"model"
] |
3929062e5fd9bac8aa93262a5fad28e7ddce1d8c | 519 | h | C | Foundation/library/tests/TTString.test.h | jamoma/JamomaCore | 7b1becc7f6ae2bc1f283a34af0b3986ce20f3a43 | [
"BSD-3-Clause"
] | 31 | 2015-02-28T23:51:10.000Z | 2021-12-25T04:16:01.000Z | Foundation/library/tests/TTString.test.h | jamoma/JamomaCore | 7b1becc7f6ae2bc1f283a34af0b3986ce20f3a43 | [
"BSD-3-Clause"
] | 126 | 2015-01-01T13:42:05.000Z | 2021-07-13T14:11:42.000Z | Foundation/library/tests/TTString.test.h | jamoma/JamomaCore | 7b1becc7f6ae2bc1f283a34af0b3986ce20f3a43 | [
"BSD-3-Clause"
] | 14 | 2015-02-10T15:08:32.000Z | 2019-09-17T01:21:25.000Z | /*
* Unit tests for the TTString object
* Copyright © 2012, Timothy Place
*
* License: This code is licensed under the terms of the "New BSD License"
* http://creativecommons.org/licenses/BSD/
*/
#ifndef __TT_STRINGTEST_H__
#define __TT_STRINGTEST_H__
#include "TTDataObjectBase.h"
#include "TTUnitTest.h"
/** Provide unit tests for #TTString */
class TTStringTest : public TTDataObjectBase {
TTCLASS_SETUP(TTStringTest)
virtual TTErr test(TTValue& returnedTestInfo);
};
#endif // __TT_STRINGTEST_H__
| 21.625 | 74 | 0.749518 | [
"object"
] |
392d54bc33cc5b3954a2f6f7efe666c0a0d505dd | 668 | h | C | renderer/rend/boundingsphere.h | flaming0/software-renderer | dfeb24eb4ac6f90552e65cc7e0cf97d7d693ad7b | [
"MIT"
] | 14 | 2015-03-22T16:18:32.000Z | 2017-08-08T14:07:44.000Z | renderer/rend/boundingsphere.h | nslobodin/software-renderer | dfeb24eb4ac6f90552e65cc7e0cf97d7d693ad7b | [
"MIT"
] | null | null | null | renderer/rend/boundingsphere.h | nslobodin/software-renderer | dfeb24eb4ac6f90552e65cc7e0cf97d7d693ad7b | [
"MIT"
] | 2 | 2015-08-31T03:01:57.000Z | 2016-12-20T06:09:32.000Z | /*
* boundingsphere.h
*
* Created on: Mar 10, 2012
* Author: flamingo
*/
#ifndef BOUNDINGSPHERE_H
#define BOUNDINGSPHERE_H
#include "../math/vec3.h"
namespace rend
{
class BoundingSphere
{
math::vec3 m_centerPoint;
float m_radius;
public:
BoundingSphere();
BoundingSphere(const std::vector<math::vec3> &vertices);
~BoundingSphere();
math::vec3 center() const { return m_centerPoint; }
float radius() const { return m_radius; }
void calculate(const std::vector<math::vec3> &vertices);
bool valid() const { return m_radius > 0.; }
};
}
#endif // BOUNDINGSPHERE_H
| 18.054054 | 68 | 0.616766 | [
"vector"
] |
393219d673676c27b2f3c032886a907edce80f39 | 21,977 | c | C | ble/app_ble.c | bojanpotocnik/nrf52_ble_app_template | 4b76430f738b8cd4d62eaa6a65be4c55a502de70 | [
"MIT"
] | 1 | 2021-04-12T05:08:13.000Z | 2021-04-12T05:08:13.000Z | ble/app_ble.c | bojanpotocnik/nrf52_ble_app_template | 4b76430f738b8cd4d62eaa6a65be4c55a502de70 | [
"MIT"
] | null | null | null | ble/app_ble.c | bojanpotocnik/nrf52_ble_app_template | 4b76430f738b8cd4d62eaa6a65be4c55a502de70 | [
"MIT"
] | 1 | 2019-11-26T22:56:05.000Z | 2019-11-26T22:56:05.000Z | //
// Created by Bojan on 29/01/2019.
//
#include "app_ble.h"
// nRF SDK
#include "nordic_common.h"
#include "nrf.h"
#include "app_error.h"
// nRF SDK Logging
#include "nrf_log.h"
#include "nrf_log_ctrl.h"
// SoftDevice Handler
#include "nrf_sdh.h"
#include "nrf_sdh_soc.h"
#include "nrf_sdh_ble.h"
// BLE
#include "ble.h"
#include "ble_hci.h"
#include "ble_config.h"
#include "ble_advdata.h"
#include "ble_advertising.h"
#include "ble_srv_common.h"
#include "ble_conn_params.h"
#include "ble_conn_state.h"
#include "nrf_ble_gatt.h"
#include "nrf_ble_qwr.h"
#include "peer_manager.h"
#include "peer_manager_handler.h"
// BLE Services
#include "ble_dis.h"
#include "ble_bas.h"
// Other application includes
#include "version.h"
#define APP_BLE_CONN_CFG_TAG 1 /**< A tag identifying the SoftDevice BLE configuration. */
static void on_ble_event(ble_evt_t const *p_ble_evt, void *p_context);
static void on_gatt_event(nrf_ble_gatt_t *p_gatt, nrf_ble_gatt_evt_t const *p_evt);
static void on_advertising_event(ble_adv_evt_t ble_adv_evt);
static void on_conn_params_event(ble_conn_params_evt_t *p_evt);
static void on_peer_manager_event(pm_evt_t const *p_evt);
NRF_BLE_GATT_DEF(m_gatt); /**< GATT module instance. */
NRF_BLE_QWR_DEF(m_qwr); /**< Context for the Queued Write module.*/
BLE_ADVERTISING_DEF(m_advertising); /**< Advertising module instance. */
BLE_BAS_DEF(m_bas); /**< Battery Service instance. */
// YOUR_JOB: Declare all other services structure your application is using
/** Device's current transmit power level when in a connection.
* Supported values: -40dBm, -20dBm, -16dBm, -12dBm, -8dBm, -4dBm, 0dBm, +2dBm,
* +3dBm, +4dBm, +5dBm, +6dBm, +7dBm and +8dBm.
*/
static int8_t m_tx_power = 0;
// The whole advertising packet cannot be larger than default MTU length, therefore device name
// also cannot be larger (minus 1 B for OP-Code and 2 B for Handle, plus null termination).
static char ble_device_name[BLE_GATT_ATT_MTU_DEFAULT - 3 + 1];
/** The UUIDs for service(s) used in the application. */
static ble_uuid_t m_adv_uuids[] = {
{BLE_UUID_DEVICE_INFORMATION_SERVICE, BLE_UUID_TYPE_BLE}
// YOUR_JOB: Use UUIDs for service(s) used in your application.
};
/** Advertising configuration, initially initialized in advertising_init().
*/
static ble_advertising_init_t m_adv_init = {
// Advertising data
.advdata = {
.name_type = BLE_ADVDATA_FULL_NAME,
.include_appearance = true,
.flags = BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE,
.p_tx_power_level = &m_tx_power,
.uuids_more_available = {
.uuid_cnt = 0,
.p_uuids = NULL
},
.uuids_complete = {
.uuid_cnt = sizeof(m_adv_uuids) / sizeof(m_adv_uuids[0]),
.p_uuids = m_adv_uuids
},
.uuids_solicited = {
.uuid_cnt = 0,
.p_uuids = NULL
},
.p_slave_conn_int = NULL,
.p_manuf_specific_data = NULL,
.p_service_data_array = NULL,
.service_data_count = 0,
.include_ble_device_addr = false
},
// Scan response data
/*.srdata = {
.name_type = BLE_ADVDATA_FULL_NAME,
.short_name_len = 0,
.include_appearance = true,
.flags = BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE,
.p_tx_power_level = NULL,
.uuids_more_available = {
.uuid_cnt = 0,
.p_uuids = NULL
},
.uuids_complete = {
.uuid_cnt = sizeof(m_adv_uuids) / sizeof(m_adv_uuids[0]),
.p_uuids = m_adv_uuids
},
.uuids_solicited = {
.uuid_cnt = 0,
.p_uuids = NULL
},
.p_slave_conn_int = NULL,
.p_manuf_specific_data = NULL,
.p_service_data_array = NULL,
.service_data_count = 0,
.include_ble_device_addr = false
},*/
// Advertising modes and intervals
.config = {
.ble_adv_on_disconnect_disabled = false,
.ble_adv_whitelist_enabled = false,
.ble_adv_directed_high_duty_enabled = false,
.ble_adv_directed_enabled = false,
.ble_adv_fast_enabled = true,
.ble_adv_slow_enabled = true,
.ble_adv_directed_interval = 0,
.ble_adv_directed_timeout = 0,
.ble_adv_fast_interval = APP_ADV_FAST_INTERVAL,
.ble_adv_fast_timeout = APP_ADV_FAST_DURATION,
.ble_adv_slow_interval = APP_ADV_SLOW_INTERVAL,
.ble_adv_slow_timeout = APP_ADV_SLOW_DURATION,
.ble_adv_extended_enabled = false
},
// Event handler that will be called upon advertising events
.evt_handler = on_advertising_event,
// Error handler that will propagate internal errors to the main applications.
.error_handler = app_error_handler_bare
};
/** Handle of the current connection. */
static uint16_t m_conn_handle = BLE_CONN_HANDLE_INVALID;
// region Public functions
void ble_stack_init(void) {
ret_code_t err_code;
err_code = nrf_sdh_enable_request();
APP_ERROR_CHECK(err_code);
// Configure the BLE stack using the default settings.
// Fetch the start address of the application RAM.
uint32_t ram_start = 0;
err_code = nrf_sdh_ble_default_cfg_set(APP_BLE_CONN_CFG_TAG, &ram_start);
APP_ERROR_CHECK(err_code);
// Enable BLE stack.
err_code = nrf_sdh_ble_enable(&ram_start);
APP_ERROR_CHECK(err_code);
// Register a handler for BLE events.
NRF_SDH_BLE_OBSERVER(m_ble_observer, APP_BLE_OBSERVER_PRIO, on_ble_event, NULL);
}
void ble_set_device_name(const char *name) {
ble_gap_conn_sec_mode_t sec_mode;
BLE_GAP_CONN_SEC_MODE_SET_OPEN(&sec_mode);
strncat(ble_device_name, name, sizeof(ble_device_name) - 1);
ret_code_t err_code = sd_ble_gap_device_name_set(&sec_mode,
(const uint8_t *) ble_device_name,
(uint16_t) strlen(ble_device_name));
APP_ERROR_CHECK(err_code);
}
void gap_params_init(void) {
ret_code_t err_code;
ble_gap_conn_params_t gap_conn_params = {0};
ble_set_device_name(DEVICE_NAME);
// YOUR_JOB: Use an appearance value matching the application's use case.
err_code = sd_ble_gap_appearance_set(BLE_APPEARANCE_UNKNOWN);
APP_ERROR_CHECK(err_code);
gap_conn_params.min_conn_interval = MIN_CONN_INTERVAL;
gap_conn_params.max_conn_interval = MAX_CONN_INTERVAL;
gap_conn_params.slave_latency = SLAVE_LATENCY;
gap_conn_params.conn_sup_timeout = CONN_SUP_TIMEOUT;
err_code = sd_ble_gap_ppcp_set(&gap_conn_params);
APP_ERROR_CHECK(err_code);
}
void gatt_init(void) {
ret_code_t err_code = nrf_ble_gatt_init(&m_gatt, on_gatt_event);
APP_ERROR_CHECK(err_code);
}
void advertising_init(void) {
ret_code_t err_code;
err_code = ble_advertising_init(&m_advertising, &m_adv_init);
APP_ERROR_CHECK(err_code);
ble_advertising_conn_cfg_tag_set(&m_advertising, APP_BLE_CONN_CFG_TAG);
// Set initial power level for advertising.
// Advertising must first be initialized for handle to be valid.
err_code = sd_ble_gap_tx_power_set(BLE_GAP_TX_POWER_ROLE_ADV, m_advertising.adv_handle, m_tx_power);
APP_ERROR_CHECK(err_code);
}
void services_init(void) {
ret_code_t err_code;
uint16_t max_char_length = 0;
// region Initialize Queued Write Module
nrf_ble_qwr_init_t qwr_init = {0};
qwr_init.error_handler = app_error_handler_bare;
err_code = nrf_ble_qwr_init(&m_qwr, &qwr_init);
APP_ERROR_CHECK(err_code);
// endregion Initialize Queued Write Module
// region Initialize Device Information Service
ble_dis_init_t dis_init = {0};
ble_srv_ascii_to_utf8(&dis_init.manufact_name_str, "info@bojanpotocnik.com");
ble_srv_ascii_to_utf8(&dis_init.model_num_str, "Model Template");
ble_srv_ascii_to_utf8(&dis_init.hw_rev_str, (char *) VERSION_HW);
// Automatic MAC + UUID as a serial number.
char ser_num_str[sizeof("001122334455-0011223344556677") + 1];
sprintf(ser_num_str, "%04X%08X-%08X%08X",
(uint16_t) NRF_FICR->DEVICEADDR[1], NRF_FICR->DEVICEADDR[0],
NRF_FICR->DEVICEID[1], NRF_FICR->DEVICEID[0]);
ble_srv_ascii_to_utf8(&dis_init.serial_num_str, ser_num_str);
// Automatic version and build date/time as a FW Revision String.
char fw_rev_str[sizeof("MMM.mmm.bbb ( )") + sizeof(VERSION_FW_BUILD_DATE) + sizeof(VERSION_FW_BUILD_TIME) + 1];
sprintf(fw_rev_str, "%d.%d.%d (%s %s)",
VERSION_FW_MAJOR, VERSION_FW_MINOR, VERSION_FW_BUILD,
VERSION_FW_BUILD_DATE, VERSION_FW_BUILD_TIME);
ble_srv_ascii_to_utf8(&dis_init.fw_rev_str, fw_rev_str);
dis_init.dis_char_rd_sec = SEC_OPEN;
// Check for maximum length
max_char_length = MAX(max_char_length, dis_init.manufact_name_str.length);
max_char_length = MAX(max_char_length, dis_init.model_num_str.length);
max_char_length = MAX(max_char_length, dis_init.serial_num_str.length);
max_char_length = MAX(max_char_length, dis_init.hw_rev_str.length);
max_char_length = MAX(max_char_length, dis_init.fw_rev_str.length);
max_char_length = MAX(max_char_length, dis_init.sw_rev_str.length);
if (dis_init.p_sys_id != NULL) {
max_char_length = MAX(max_char_length, sizeof(*dis_init.p_sys_id));
}
if (dis_init.p_reg_cert_data_list != NULL) {
max_char_length = MAX(max_char_length, dis_init.p_reg_cert_data_list->list_len);
}
if (dis_init.p_pnp_id != NULL) {
max_char_length = MAX(max_char_length, sizeof(*dis_init.p_pnp_id));
}
err_code = ble_dis_init(&dis_init);
APP_ERROR_CHECK(err_code);
// endregion Initialize Device Information Service
// region Initialize Battery Service
ble_bas_init_t bas_init = {0};
bas_init.support_notification = true;
bas_init.initial_batt_level = 99;
bas_init.bl_rd_sec = SEC_OPEN;
bas_init.bl_cccd_wr_sec = SEC_OPEN;
bas_init.bl_report_rd_sec = SEC_OPEN;
max_char_length = MAX(max_char_length, (uint8_t) 2);
err_code = ble_bas_init(&m_bas, &bas_init);
APP_ERROR_CHECK(err_code);
// endregion Initialize Battery Service
/* YOUR_JOB: Add code to initialize the services used by the application.
ble_xxs_init_t xxs_init;
ble_yys_init_t yys_init;
// Initialize XXX Service.
memset(&xxs_init, 0, sizeof(xxs_init));
xxs_init.evt_handler = NULL;
xxs_init.is_xxx_notify_supported = true;
xxs_init.ble_xx_initial_value.level = 100;
// Update maximum characteristic length
max_char_length = MAX(max_char_length, sizeof(ble_xxs_data_t));
err_code = ble_bas_init(&m_xxs, &xxs_init);
APP_ERROR_CHECK(err_code);
// Initialize YYY Service.
memset(&yys_init, 0, sizeof(yys_init));
yys_init.evt_handler = on_yys_evt;
yys_init.ble_yy_initial_value.counter = 0;
// Update maximum characteristic length
max_char_length = MAX(max_char_length, sizeof(ble_xxy_char_abc_data_t));
max_char_length = MAX(max_char_length, sizeof(ble_xxy_char_123_data_t));
err_code = ble_yy_service_init(&yys_init, &yy_init);
APP_ERROR_CHECK(err_code);
*/
/* Now, when all of the characteristics are added, maximum length can be retrieved and the
* desired MTU size used for new connection can be updated to the length of the largest
* characteristics value for for the maximum performance.
*
* The ATT_MTU size can be modified freely between BLE_GATT_ATT_MTU_DEFAULT and NRF_SDH_BLE_GATT_MAX_MTU_SIZE.
* This value shall be updated before GATT initialization so all new connections will be updates to this
* desired MTU size. For the maximum performance this values should be set to the maximum length of any
* of the defined characteristic (but still limited to NRF_SDH_BLE_GATT_MAX_MTU_SIZE).
*
* There is also 1 byte used for the OP-code and 2 bytes for the Handle ID.
*/
const uint16_t mtu_size = (uint16_t)
MIN(MAX(max_char_length + 3, (BLE_GATT_ATT_MTU_DEFAULT)), (NRF_SDH_BLE_GATT_MAX_MTU_SIZE));
NRF_LOG_DEBUG("Desired MTU size = %d (largest char. = %d)", mtu_size, max_char_length);
err_code = nrf_ble_gatt_att_mtu_periph_set(&m_gatt, mtu_size);
APP_ERROR_CHECK(err_code);
}
void conn_params_init(void) {
ret_code_t err_code;
ble_conn_params_init_t cp_init = {0};
cp_init.p_conn_params = NULL;
cp_init.first_conn_params_update_delay = FIRST_CONN_PARAMS_UPDATE_DELAY;
cp_init.next_conn_params_update_delay = NEXT_CONN_PARAMS_UPDATE_DELAY;
cp_init.max_conn_params_update_count = MAX_CONN_PARAMS_UPDATE_COUNT;
cp_init.start_on_notify_cccd_handle = BLE_GATT_HANDLE_INVALID;
cp_init.disconnect_on_fail = false;
cp_init.evt_handler = on_conn_params_event;
cp_init.error_handler = app_error_handler_bare;
err_code = ble_conn_params_init(&cp_init);
APP_ERROR_CHECK(err_code);
}
void peer_manager_init(void) {
ret_code_t err_code;
ble_gap_sec_params_t sec_param = {0};
err_code = pm_init();
APP_ERROR_CHECK(err_code);
// Security parameters to be used for all security procedures.
sec_param.bond = SEC_PARAM_BOND;
sec_param.mitm = SEC_PARAM_MITM;
sec_param.lesc = SEC_PARAM_LESC;
sec_param.keypress = SEC_PARAM_KEYPRESS;
sec_param.io_caps = SEC_PARAM_IO_CAPABILITIES;
sec_param.oob = SEC_PARAM_OOB;
sec_param.min_key_size = SEC_PARAM_MIN_KEY_SIZE;
sec_param.max_key_size = SEC_PARAM_MAX_KEY_SIZE;
sec_param.kdist_own.enc = 1;
sec_param.kdist_own.id = 1;
sec_param.kdist_peer.enc = 1;
sec_param.kdist_peer.id = 1;
err_code = pm_sec_params_set(&sec_param);
APP_ERROR_CHECK(err_code);
err_code = pm_register(on_peer_manager_event);
APP_ERROR_CHECK(err_code);
}
void advertising_start(bool erase_bonds) {
if (erase_bonds == true) {
NRF_LOG_INFO("Erase bonds!");
ret_code_t err_code = pm_peers_delete();
APP_ERROR_CHECK(err_code);
// Advertising is started by PM_EVT_PEERS_DELETED_SUCEEDED event
}
else {
ret_code_t err_code = ble_advertising_start(&m_advertising, BLE_ADV_MODE_FAST);
APP_ERROR_CHECK(err_code);
}
}
bool ble_is_device_connected(void) {
return (m_conn_handle != BLE_CONN_HANDLE_INVALID);
}
// endregion Public functions
/**@brief Function for handling BLE events.
*
* @param[in] p_ble_evt Bluetooth stack event.
* @param[in] p_context Unused.
*/
static void on_ble_event(ble_evt_t const *p_ble_evt, void *p_context) {
ret_code_t err_code;
switch (p_ble_evt->header.evt_id) {
case BLE_GAP_EVT_CONNECTED: {
// p_ble_evt->evt.gap_evt.params.connected
NRF_LOG_INFO("Connected.");
m_conn_handle = p_ble_evt->evt.gap_evt.conn_handle;
err_code = nrf_ble_qwr_conn_handle_assign(&m_qwr, m_conn_handle);
APP_ERROR_CHECK(err_code);
break;
}
case BLE_GAP_EVT_DISCONNECTED: {
// p_ble_evt->evt.gap_evt.params.disconnected
NRF_LOG_INFO("Disconnected.");
// LED indication will be changed when advertising starts.
break;
}
case BLE_GAP_EVT_PHY_UPDATE_REQUEST: {
// p_ble_evt->evt.gap_evt.params.phy_update_request
NRF_LOG_DEBUG("PHY update request.");
ble_gap_phys_t const phys = {
.rx_phys = BLE_GAP_PHY_AUTO,
.tx_phys = BLE_GAP_PHY_AUTO,
};
err_code = sd_ble_gap_phy_update(p_ble_evt->evt.gap_evt.conn_handle, &phys);
APP_ERROR_CHECK(err_code);
break;
}
case BLE_GATTC_EVT_TIMEOUT: {
// Disconnect on GATT Client timeout event.
NRF_LOG_DEBUG("GATT Client Timeout.");
err_code = sd_ble_gap_disconnect(p_ble_evt->evt.gattc_evt.conn_handle,
BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
APP_ERROR_CHECK(err_code);
break;
}
case BLE_GATTS_EVT_TIMEOUT: {
// Disconnect on GATT Server timeout event.
NRF_LOG_DEBUG("GATT Server Timeout.");
err_code = sd_ble_gap_disconnect(p_ble_evt->evt.gatts_evt.conn_handle,
BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
APP_ERROR_CHECK(err_code);
break;
}
case BLE_GAP_EVT_SEC_PARAMS_REQUEST: {
// Pairing not supported.
err_code = sd_ble_gap_sec_params_reply(m_conn_handle, BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP, NULL, NULL);
APP_ERROR_CHECK(err_code);
break;
}
case BLE_GATTS_EVT_SYS_ATTR_MISSING: {
// No system attributes have been stored.
err_code = sd_ble_gatts_sys_attr_set(m_conn_handle, NULL, 0, 0);
APP_ERROR_CHECK(err_code);
break;
}
case BLE_EVT_USER_MEM_REQUEST: {
err_code = sd_ble_user_mem_reply(p_ble_evt->evt.gattc_evt.conn_handle, NULL);
APP_ERROR_CHECK(err_code);
break;
}
case BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST: {
ble_gap_data_length_params_t dl_params = {0};
// Clearing the struct will effectively set members to @ref BLE_GAP_DATA_LENGTH_AUTO.
err_code = sd_ble_gap_data_length_update(p_ble_evt->evt.gap_evt.conn_handle, &dl_params, NULL);
APP_ERROR_CHECK(err_code);
break;
}
case BLE_GATTS_EVT_EXCHANGE_MTU_REQUEST: {
const uint16_t mtu_requested = p_ble_evt->evt.gatts_evt.params.exchange_mtu_request.client_rx_mtu;
NRF_LOG_DEBUG("Exchange MTU Request (to %d for 0x%x)", mtu_requested, m_conn_handle);
err_code = sd_ble_gatts_exchange_mtu_reply(p_ble_evt->evt.gatts_evt.conn_handle, mtu_requested);
APP_ERROR_CHECK(err_code);
break;
}
default:
// No implementation needed.
break;
}
}
/**@brief Function for handling events from the GATT library.
*/
static void on_gatt_event(nrf_ble_gatt_t *p_gatt, nrf_ble_gatt_evt_t const *p_evt) {
switch (p_evt->evt_id) {
case NRF_BLE_GATT_EVT_ATT_MTU_UPDATED: {
NRF_LOG_INFO("ATT MTU updated (central %d, periph. %d) to %d B on connection 0x%x",
p_gatt->att_mtu_desired_central, p_gatt->att_mtu_desired_periph,
p_evt->params.att_mtu_effective, p_evt->conn_handle);
// Note that the actual payload length is att_mtu_effective - Op. Code length (1) - Handle length (2).
break;
}
case NRF_BLE_GATT_EVT_DATA_LENGTH_UPDATED:
NRF_LOG_INFO("ATT data length updated to %u B on connection 0x%x",
p_evt->params.data_length, p_evt->conn_handle);
break;
}
// YOUR_JOB: Call any service-specific GATT event handler or update their MTU/data sizes.
// ble_xxx_on_gatt_evt(&m_xxx, p_evt);
}
/**@brief Function for handling advertising events.
*
* @details This function will be called for advertising events which are passed to the application.
*
* @param[in] ble_adv_evt Advertising event.
*/
static void on_advertising_event(ble_adv_evt_t ble_adv_evt) {
// uint32_t err_code;
switch (ble_adv_evt) {
case BLE_ADV_EVT_FAST:
//err_code = bsp_indication_set(BSP_INDICATE_ADVERTISING);
//APP_ERROR_CHECK(err_code);
break;
case BLE_ADV_EVT_IDLE:
//sleep_mode_enter();
break;
default:
break;
}
}
/**@brief Function for handling the Connection Parameters Module.
*
* @details This function will be called for all events in the Connection Parameters Module which
* are passed to the application.
* @note All this function does is to disconnect. This could have been done by simply
* setting the disconnect_on_fail config parameter, but instead we use the event
* handler mechanism to demonstrate its use.
*
* @param[in] p_evt Event received from the Connection Parameters Module.
*/
static void on_conn_params_event(ble_conn_params_evt_t *p_evt) {
ret_code_t err_code;
if (p_evt->evt_type == BLE_CONN_PARAMS_EVT_FAILED) {
err_code = sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_CONN_INTERVAL_UNACCEPTABLE);
APP_ERROR_CHECK(err_code);
}
}
/**@brief Function for handling Peer Manager events.
*
* @param[in] p_evt Peer Manager event.
*/
static void on_peer_manager_event(pm_evt_t const *p_evt) {
pm_handler_on_pm_evt(p_evt);
pm_handler_flash_clean(p_evt);
switch (p_evt->evt_id) {
case PM_EVT_PEERS_DELETE_SUCCEEDED:
advertising_start(false);
break;
default:
break;
}
}
/**@brief Function for handling the YYY Service events.
* YOUR_JOB implement a service handler function depending on the event the service you are using can generate
*
* @details This function will be called for all YY Service events which are passed to
* the application.
*
* @param[in] p_yy_service YY Service structure.
* @param[in] p_evt Event received from the YY Service.
*
*
static void on_yys_evt(ble_yy_service_t * p_yy_service,
ble_yy_service_evt_t * p_evt)
{
switch (p_evt->evt_type)
{
case BLE_YY_NAME_EVT_WRITE:
APPL_LOG("[APPL]: charact written with value %s. ", p_evt->params.char_xx.value.p_str);
break;
default:
// No implementation needed.
break;
}
}
*/
| 34.664038 | 115 | 0.679074 | [
"model"
] |
39397d3eee37623b1082a3f5f32342387c007f7f | 43,256 | c | C | extern/gtk/gdk/win32/gdkcursor-win32.c | PableteProgramming/download | 013e35bb5c085e5dfdb57a3a0a39cdf2fd3064b8 | [
"MIT"
] | null | null | null | extern/gtk/gdk/win32/gdkcursor-win32.c | PableteProgramming/download | 013e35bb5c085e5dfdb57a3a0a39cdf2fd3064b8 | [
"MIT"
] | null | null | null | extern/gtk/gdk/win32/gdkcursor-win32.c | PableteProgramming/download | 013e35bb5c085e5dfdb57a3a0a39cdf2fd3064b8 | [
"MIT"
] | null | null | null | /* GDK - The GIMP Drawing Kit
* Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
* Copyright (C) 1998-2002 Tor Lillqvist
*
* 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 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#include "config.h"
#define GDK_PIXBUF_ENABLE_BACKEND /* Ugly? */
#include "gdkdisplay.h"
#include "gdkcursor.h"
#include "gdkwin32.h"
#include "gdktextureprivate.h"
#include "gdkintl.h"
#include "gdkdisplay-win32.h"
#ifdef __MINGW32__
#include <w32api.h>
#endif
#include "xcursors.h"
typedef struct _DefaultCursor {
char *name;
char *id;
} DefaultCursor;
static DefaultCursor default_cursors[] = {
{ "appstarting", IDC_APPSTARTING },
{ "arrow", IDC_ARROW },
{ "cross", IDC_CROSS },
{ "hand", IDC_HAND },
{ "help", IDC_HELP },
{ "ibeam", IDC_IBEAM },
/* an X cursor name, for compatibility with GTK: */
{ "left_ptr_watch", IDC_APPSTARTING },
{ "sizeall", IDC_SIZEALL },
{ "sizenesw", IDC_SIZENESW },
{ "sizens", IDC_SIZENS },
{ "sizenwse", IDC_SIZENWSE },
{ "sizewe", IDC_SIZEWE },
{ "uparrow", IDC_UPARROW },
{ "wait", IDC_WAIT },
/* css cursor names: */
{ "default", IDC_ARROW },
{ "pointer", IDC_HAND },
{ "progress", IDC_APPSTARTING },
{ "crosshair", IDC_CROSS },
{ "text", IDC_IBEAM },
{ "move", IDC_SIZEALL },
{ "not-allowed", IDC_NO },
{ "all-scroll", IDC_SIZEALL },
{ "ew-resize", IDC_SIZEWE },
{ "e-resize", IDC_SIZEWE },
{ "w-resize", IDC_SIZEWE },
{ "col-resize", IDC_SIZEWE },
{ "ns-resize", IDC_SIZENS },
{ "n-resize", IDC_SIZENS },
{ "s-resize", IDC_SIZENS },
{ "row-resize", IDC_SIZENS },
{ "nesw-resize", IDC_SIZENESW },
{ "ne-resize", IDC_SIZENESW },
{ "sw-resize", IDC_SIZENESW },
{ "nwse-resize", IDC_SIZENWSE },
{ "nw-resize", IDC_SIZENWSE },
{ "se-resize", IDC_SIZENWSE }
};
typedef struct _GdkWin32HCursorTableEntry GdkWin32HCursorTableEntry;
struct _GdkWin32HCursorTableEntry
{
HCURSOR handle;
guint64 refcount;
gboolean destroyable;
};
struct _GdkWin32HCursor
{
GObject parent_instance;
/* Do not do any modifications to the handle
* (i.e. do not call DestroyCursor() on it).
* It's a "read-only" copy, the original is stored
* in the display instance.
*/
HANDLE readonly_handle;
/* This is a way to access the real handle stored
* in the display.
* TODO: make it a weak reference
*/
GdkWin32Display *display;
/* A copy of the "destoyable" attribute of the handle */
gboolean readonly_destroyable;
};
struct _GdkWin32HCursorClass
{
GObjectClass parent_class;
};
enum
{
PROP_0,
PROP_DISPLAY,
PROP_HANDLE,
PROP_DESTROYABLE,
NUM_PROPERTIES
};
G_DEFINE_TYPE (GdkWin32HCursor, gdk_win32_hcursor, G_TYPE_OBJECT)
static void
gdk_win32_hcursor_init (GdkWin32HCursor *win32_hcursor)
{
}
static void
gdk_win32_hcursor_finalize (GObject *gobject)
{
GdkWin32HCursor *win32_hcursor = GDK_WIN32_HCURSOR (gobject);
if (win32_hcursor->display)
_gdk_win32_display_hcursor_unref (win32_hcursor->display, win32_hcursor->readonly_handle);
g_clear_object (&win32_hcursor->display);
G_OBJECT_CLASS (gdk_win32_hcursor_parent_class)->finalize (G_OBJECT (win32_hcursor));
}
static void
gdk_win32_hcursor_set_property (GObject *object,
guint prop_id,
const GValue *value,
GParamSpec *pspec)
{
GdkWin32HCursor *win32_hcursor;
win32_hcursor = GDK_WIN32_HCURSOR (object);
switch (prop_id)
{
case PROP_DISPLAY:
g_set_object (&win32_hcursor->display, g_value_get_object (value));
break;
case PROP_DESTROYABLE:
win32_hcursor->readonly_destroyable = g_value_get_boolean (value);
break;
case PROP_HANDLE:
win32_hcursor->readonly_handle = g_value_get_pointer (value);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gdk_win32_hcursor_get_property (GObject *object,
guint prop_id,
GValue *value,
GParamSpec *pspec)
{
GdkWin32HCursor *win32_hcursor;
win32_hcursor = GDK_WIN32_HCURSOR (object);
switch (prop_id)
{
case PROP_DISPLAY:
g_value_set_object (value, win32_hcursor->display);
break;
case PROP_DESTROYABLE:
g_value_set_boolean (value, win32_hcursor->readonly_destroyable);
break;
case PROP_HANDLE:
g_value_set_pointer (value, win32_hcursor->readonly_handle);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gdk_win32_hcursor_constructed (GObject *object)
{
GdkWin32HCursor *win32_hcursor;
win32_hcursor = GDK_WIN32_HCURSOR (object);
g_assert_nonnull (win32_hcursor->display);
g_assert_nonnull (win32_hcursor->readonly_handle);
_gdk_win32_display_hcursor_ref (win32_hcursor->display,
win32_hcursor->readonly_handle,
win32_hcursor->readonly_destroyable);
}
static GParamSpec *hcursor_props[NUM_PROPERTIES] = { NULL, };
static void
gdk_win32_hcursor_class_init (GdkWin32HCursorClass *klass)
{
GObjectClass *object_class = G_OBJECT_CLASS (klass);
object_class->finalize = gdk_win32_hcursor_finalize;
object_class->constructed = gdk_win32_hcursor_constructed;
object_class->get_property = gdk_win32_hcursor_get_property;
object_class->set_property = gdk_win32_hcursor_set_property;
hcursor_props[PROP_DISPLAY] =
g_param_spec_object ("display",
P_("Display"),
P_("The display that will use this cursor"),
GDK_TYPE_DISPLAY,
G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE);
hcursor_props[PROP_HANDLE] =
g_param_spec_pointer ("handle",
P_("Handle"),
P_("The HCURSOR handle for this cursor"),
G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE);
hcursor_props[PROP_DESTROYABLE] =
g_param_spec_boolean ("destroyable",
P_("Destroyable"),
P_("Whether calling DestroyCursor() is allowed on this cursor"),
TRUE,
G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE);
g_object_class_install_properties (object_class, NUM_PROPERTIES, hcursor_props);
}
GdkWin32HCursor *
gdk_win32_hcursor_new (GdkWin32Display *display,
HCURSOR handle,
gboolean destroyable)
{
return g_object_new (GDK_TYPE_WIN32_HCURSOR,
"display", display,
"handle", handle,
"destroyable", destroyable,
NULL);
}
void
_gdk_win32_display_hcursor_ref (GdkWin32Display *display,
HCURSOR handle,
gboolean destroyable)
{
GdkWin32HCursorTableEntry *entry;
entry = g_hash_table_lookup (display->cursor_reftable, handle);
if (entry)
{
if (entry->destroyable != destroyable)
g_warning ("Destroyability metadata for cursor handle 0x%p does not match", handle);
entry->refcount += 1;
return;
}
entry = g_new0 (GdkWin32HCursorTableEntry, 1);
entry->handle = handle;
entry->destroyable = destroyable;
entry->refcount = 1;
g_hash_table_insert (display->cursor_reftable, handle, entry);
display->cursors_for_destruction = g_list_remove_all (display->cursors_for_destruction, handle);
}
static gboolean
delayed_cursor_destruction (gpointer user_data)
{
GdkWin32Display *win32_display = GDK_WIN32_DISPLAY (user_data);
HANDLE current_hcursor = GetCursor ();
GList *p;
win32_display->idle_cursor_destructor_id = 0;
for (p = win32_display->cursors_for_destruction; p; p = p->next)
{
HCURSOR handle = (HCURSOR) p->data;
if (handle == NULL)
continue;
if (current_hcursor == handle)
{
SetCursor (NULL);
current_hcursor = NULL;
}
if (!DestroyCursor (handle))
g_warning (G_STRLOC ": DestroyCursor (%p) failed: %lu", handle, GetLastError ());
}
g_list_free (win32_display->cursors_for_destruction);
win32_display->cursors_for_destruction = NULL;
return G_SOURCE_REMOVE;
}
void
_gdk_win32_display_hcursor_unref (GdkWin32Display *display,
HCURSOR handle)
{
GdkWin32HCursorTableEntry *entry;
gboolean destroyable;
entry = g_hash_table_lookup (display->cursor_reftable, handle);
if (!entry)
{
g_warning ("Trying to forget cursor handle 0x%p that is not in the table", handle);
return;
}
entry->refcount -= 1;
if (entry->refcount > 0)
return;
destroyable = entry->destroyable;
g_hash_table_remove (display->cursor_reftable, handle);
g_free (entry);
if (!destroyable)
return;
/* GDK tends to destroy a cursor first, then set a new one.
* This results in repeated oscillations between SetCursor(NULL)
* and SetCursor(hcursor). To avoid that, delay cursor destruction a bit
* to let GDK set a new one first. That way cursors are switched
* seamlessly, without a NULL cursor between them.
* If GDK sets the new cursor to the same handle the old cursor had,
* the cursor handle is taken off the destruction list.
*/
if (g_list_find (display->cursors_for_destruction, handle) == NULL)
{
display->cursors_for_destruction = g_list_prepend (display->cursors_for_destruction, handle);
if (display->idle_cursor_destructor_id == 0)
display->idle_cursor_destructor_id = g_idle_add (delayed_cursor_destruction, display);
}
}
#ifdef gdk_win32_hcursor_get_handle
#undef gdk_win32_hcursor_get_handle
#endif
HCURSOR
gdk_win32_hcursor_get_handle (GdkWin32HCursor *cursor)
{
return cursor->readonly_handle;
}
static HCURSOR
hcursor_from_x_cursor (int i,
const char *name)
{
int j, x, y, ofs;
HCURSOR rv;
int w, h;
guchar *and_plane, *xor_plane;
w = GetSystemMetrics (SM_CXCURSOR);
h = GetSystemMetrics (SM_CYCURSOR);
and_plane = g_malloc ((w/8) * h);
memset (and_plane, 0xff, (w/8) * h);
xor_plane = g_malloc ((w/8) * h);
memset (xor_plane, 0, (w/8) * h);
if (strcmp (name, "none") != 0)
{
#define SET_BIT(v,b) (v |= (1 << b))
#define RESET_BIT(v,b) (v &= ~(1 << b))
for (j = 0, y = 0; y < cursors[i].height && y < h ; y++)
{
ofs = (y * w) / 8;
j = y * cursors[i].width;
for (x = 0; x < cursors[i].width && x < w ; x++, j++)
{
int pofs = ofs + x / 8;
guchar data = (cursors[i].data[j/4] & (0xc0 >> (2 * (j%4)))) >> (2 * (3 - (j%4)));
int bit = 7 - (j % cursors[i].width) % 8;
if (data)
{
RESET_BIT (and_plane[pofs], bit);
if (data == 1)
SET_BIT (xor_plane[pofs], bit);
}
}
}
#undef SET_BIT
#undef RESET_BIT
rv = CreateCursor (_gdk_app_hmodule, cursors[i].hotx, cursors[i].hoty,
w, h, and_plane, xor_plane);
}
else
{
rv = CreateCursor (_gdk_app_hmodule, 0, 0,
w, h, and_plane, xor_plane);
}
if (rv == NULL)
WIN32_API_FAILED ("CreateCursor");
g_free (and_plane);
g_free (xor_plane);
return rv;
}
static GdkWin32HCursor *
win32_cursor_create_win32hcursor (GdkWin32Display *display,
Win32Cursor *cursor,
const char *name)
{
GdkWin32HCursor *result;
switch (cursor->load_type)
{
case GDK_WIN32_CURSOR_LOAD_FROM_FILE:
result = gdk_win32_hcursor_new (display,
LoadImageW (NULL,
cursor->resource_name,
IMAGE_CURSOR,
cursor->width,
cursor->height,
cursor->load_flags),
cursor->load_flags & LR_SHARED ? FALSE : TRUE);
break;
case GDK_WIN32_CURSOR_LOAD_FROM_RESOURCE_NULL:
result = gdk_win32_hcursor_new (display,
LoadImageA (NULL,
(const char *) cursor->resource_name,
IMAGE_CURSOR,
cursor->width,
cursor->height,
cursor->load_flags),
cursor->load_flags & LR_SHARED ? FALSE : TRUE);
break;
case GDK_WIN32_CURSOR_LOAD_FROM_RESOURCE_THIS:
result = gdk_win32_hcursor_new (display,
LoadImageA (_gdk_app_hmodule,
(const char *) cursor->resource_name,
IMAGE_CURSOR,
cursor->width,
cursor->height,
cursor->load_flags),
cursor->load_flags & LR_SHARED ? FALSE : TRUE);
break;
case GDK_WIN32_CURSOR_LOAD_FROM_RESOURCE_GTK:
result = gdk_win32_hcursor_new (display,
LoadImageA (_gdk_dll_hinstance,
(const char *) cursor->resource_name,
IMAGE_CURSOR,
cursor->width,
cursor->height,
cursor->load_flags),
cursor->load_flags & LR_SHARED ? FALSE : TRUE);
break;
case GDK_WIN32_CURSOR_CREATE:
result = gdk_win32_hcursor_new (display,
hcursor_from_x_cursor (cursor->xcursor_number,
name),
TRUE);
break;
default:
result = NULL;
}
return result;
}
static Win32Cursor *
win32_cursor_new (GdkWin32CursorLoadType load_type,
gpointer resource_name,
int width,
int height,
guint load_flags,
int xcursor_number)
{
Win32Cursor *result;
result = g_new (Win32Cursor, 1);
result->load_type = load_type;
result->resource_name = resource_name;
result->width = width;
result->height = height;
result->load_flags = load_flags;
result->xcursor_number = xcursor_number;
return result;
}
static void
win32_cursor_destroy (gpointer data)
{
Win32Cursor *cursor = data;
/* resource_name could be a resource ID (uint16_t stored as a pointer),
* which shouldn't be freed.
*/
if (cursor->load_type == GDK_WIN32_CURSOR_LOAD_FROM_FILE)
g_free (cursor->resource_name);
g_free (cursor);
}
static void
win32_cursor_theme_load_from (Win32CursorTheme *theme,
int size,
const char *dir)
{
GDir *gdir;
const char *filename;
HCURSOR hcursor;
gdir = g_dir_open (dir, 0, NULL);
if (gdir == NULL)
return;
while ((filename = g_dir_read_name (gdir)) != NULL)
{
char *fullname;
gunichar2 *filenamew;
char *cursor_name;
char *dot;
Win32Cursor *cursor;
fullname = g_build_filename (dir, filename, NULL);
filenamew = g_utf8_to_utf16 (fullname, -1, NULL, NULL, NULL);
g_free (fullname);
if (filenamew == NULL)
continue;
hcursor = LoadImageW (NULL, filenamew, IMAGE_CURSOR, size, size,
LR_LOADFROMFILE | (size == 0 ? LR_DEFAULTSIZE : 0));
if (hcursor == NULL)
{
g_free (filenamew);
continue;
}
DestroyCursor (hcursor);
dot = strchr (filename, '.');
cursor_name = dot ? g_strndup (filename, dot - filename) : g_strdup (filename);
cursor = win32_cursor_new (GDK_WIN32_CURSOR_LOAD_FROM_FILE,
filenamew,
size,
size,
LR_LOADFROMFILE | (size == 0 ? LR_DEFAULTSIZE : 0),
0);
g_hash_table_insert (theme->named_cursors, cursor_name, cursor);
}
}
static void
win32_cursor_theme_load_from_dirs (Win32CursorTheme *theme,
const char *name,
int size)
{
char *theme_dir;
const char * const *dirs;
int i;
dirs = g_get_system_data_dirs ();
/* <prefix>/share/icons */
for (i = 0; dirs[i]; i++)
{
theme_dir = g_build_filename (dirs[i], "icons", name, "cursors", NULL);
win32_cursor_theme_load_from (theme, size, theme_dir);
g_free (theme_dir);
}
/* ~/.icons */
theme_dir = g_build_filename (g_get_home_dir (), "icons", name, "cursors", NULL);
win32_cursor_theme_load_from (theme, size, theme_dir);
g_free (theme_dir);
}
static void
win32_cursor_theme_load_system (Win32CursorTheme *theme,
int size)
{
int i;
HCURSOR shared_hcursor;
HCURSOR x_hcursor;
Win32Cursor *cursor;
for (i = 0; i < G_N_ELEMENTS (cursors); i++)
{
if (cursors[i].name == NULL)
break;
shared_hcursor = NULL;
x_hcursor = NULL;
/* Prefer W32 cursors */
if (cursors[i].builtin)
shared_hcursor = LoadImageA (NULL, cursors[i].builtin, IMAGE_CURSOR,
size, size,
LR_SHARED | (size == 0 ? LR_DEFAULTSIZE : 0));
/* Fall back to X cursors, but only if we've got no theme cursor */
if (shared_hcursor == NULL && g_hash_table_lookup (theme->named_cursors, cursors[i].name) == NULL)
x_hcursor = hcursor_from_x_cursor (i, cursors[i].name);
if (shared_hcursor == NULL && x_hcursor == NULL)
continue;
else if (x_hcursor != NULL)
DestroyCursor (x_hcursor);
cursor = win32_cursor_new (shared_hcursor ? GDK_WIN32_CURSOR_LOAD_FROM_RESOURCE_NULL : GDK_WIN32_CURSOR_CREATE,
(gpointer) cursors[i].builtin,
size,
size,
LR_SHARED | (size == 0 ? LR_DEFAULTSIZE : 0),
x_hcursor ? i : 0);
g_hash_table_insert (theme->named_cursors,
g_strdup (cursors[i].name),
cursor);
}
for (i = 0; i < G_N_ELEMENTS (default_cursors); i++)
{
if (default_cursors[i].name == NULL)
break;
shared_hcursor = LoadImageA (NULL, default_cursors[i].id, IMAGE_CURSOR, size, size,
LR_SHARED | (size == 0 ? LR_DEFAULTSIZE : 0));
if (shared_hcursor == NULL)
continue;
cursor = win32_cursor_new (GDK_WIN32_CURSOR_LOAD_FROM_RESOURCE_NULL,
(gpointer) default_cursors[i].id,
size,
size,
LR_SHARED | (size == 0 ? LR_DEFAULTSIZE : 0),
0);
g_hash_table_insert (theme->named_cursors,
g_strdup (default_cursors[i].name),
cursor);
}
}
Win32CursorTheme *
win32_cursor_theme_load (const char *name,
int size)
{
Win32CursorTheme *result = g_new0 (Win32CursorTheme, 1);
result->named_cursors = g_hash_table_new_full (g_str_hash,
g_str_equal,
g_free,
win32_cursor_destroy);
if (strcmp (name, "system") == 0)
{
win32_cursor_theme_load_from_dirs (result, "Adwaita", size);
win32_cursor_theme_load_system (result, size);
}
else
{
win32_cursor_theme_load_from_dirs (result, name, size);
}
if (g_hash_table_size (result->named_cursors) > 0)
return result;
win32_cursor_theme_destroy (result);
return NULL;
}
void
win32_cursor_theme_destroy (Win32CursorTheme *theme)
{
g_hash_table_destroy (theme->named_cursors);
g_free (theme);
}
Win32Cursor *
win32_cursor_theme_get_cursor (Win32CursorTheme *theme,
const char *name)
{
return g_hash_table_lookup (theme->named_cursors, name);
}
static void
gdk_win32_cursor_remove_from_cache (gpointer data, GObject *cursor)
{
GdkDisplay *display = data;
GdkWin32Display *win32_display = GDK_WIN32_DISPLAY (display);
/* Unrefs the GdkWin32HCursor value object automatically */
g_hash_table_remove (win32_display->cursors, cursor);
}
void
_gdk_win32_display_finalize_cursors (GdkWin32Display *display)
{
GHashTableIter iter;
gpointer cursor;
if (display->cursors)
{
g_hash_table_iter_init (&iter, display->cursors);
while (g_hash_table_iter_next (&iter, &cursor, NULL))
g_object_weak_unref (G_OBJECT (cursor),
gdk_win32_cursor_remove_from_cache,
GDK_DISPLAY (display));
g_hash_table_unref (display->cursors);
}
g_free (display->cursor_theme_name);
g_list_free (display->cursors_for_destruction);
display->cursors_for_destruction = NULL;
if (display->cursor_theme)
win32_cursor_theme_destroy (display->cursor_theme);
}
void
_gdk_win32_display_init_cursors (GdkWin32Display *display)
{
display->cursors = g_hash_table_new_full (gdk_cursor_hash,
gdk_cursor_equal,
NULL,
g_object_unref);
display->cursor_reftable = g_hash_table_new (NULL, NULL);
display->cursor_theme_name = g_strdup ("system");
}
/* This is where we use the names mapped to the equivalents that Windows defines by default */
static GdkWin32HCursor *
win32hcursor_idc_from_name (GdkWin32Display *display,
const char *name)
{
int i;
for (i = 0; i < G_N_ELEMENTS (default_cursors); i++)
{
if (strcmp (default_cursors[i].name, name) != 0)
continue;
return gdk_win32_hcursor_new (display,
LoadImageA (NULL, default_cursors[i].id, IMAGE_CURSOR, 0, 0,
LR_SHARED | LR_DEFAULTSIZE),
FALSE);
}
return NULL;
}
static GdkWin32HCursor *
win32hcursor_x_from_name (GdkWin32Display *display,
const char *name)
{
int i;
for (i = 0; i < G_N_ELEMENTS (cursors); i++)
if (cursors[i].name == NULL || strcmp (cursors[i].name, name) == 0)
return gdk_win32_hcursor_new (display, hcursor_from_x_cursor (i, name), TRUE);
return NULL;
}
static GdkWin32HCursor *
win32hcursor_from_theme (GdkWin32Display *display,
const char *name)
{
Win32CursorTheme *theme;
Win32Cursor *theme_cursor;
GdkWin32Display *win32_display = GDK_WIN32_DISPLAY (display);
if (name == NULL)
return NULL;
theme = _gdk_win32_display_get_cursor_theme (win32_display);
theme_cursor = win32_cursor_theme_get_cursor (theme, name);
if (theme_cursor == NULL)
return NULL;
return win32_cursor_create_win32hcursor (win32_display, theme_cursor, name);
}
static GdkWin32HCursor *
win32hcursor_from_name (GdkWin32Display *display,
const char *name)
{
GdkWin32HCursor *win32hcursor;
/* Try current theme first */
win32hcursor = win32hcursor_from_theme (display, name);
if (win32hcursor != NULL)
return win32hcursor;
win32hcursor = win32hcursor_idc_from_name (display, name);
if (win32hcursor != NULL)
return win32hcursor;
win32hcursor = win32hcursor_x_from_name (display, name);
return win32hcursor;
}
/* Create a blank cursor */
static GdkWin32HCursor *
create_blank_win32hcursor (GdkWin32Display *display)
{
int w, h;
guchar *and_plane, *xor_plane;
HCURSOR rv;
w = GetSystemMetrics (SM_CXCURSOR);
h = GetSystemMetrics (SM_CYCURSOR);
and_plane = g_malloc ((w/8) * h);
memset (and_plane, 0xff, (w/8) * h);
xor_plane = g_malloc ((w/8) * h);
memset (xor_plane, 0, (w/8) * h);
rv = CreateCursor (_gdk_app_hmodule, 0, 0,
w, h, and_plane, xor_plane);
if (rv == NULL)
WIN32_API_FAILED ("CreateCursor");
return gdk_win32_hcursor_new (display, rv, TRUE);
}
static GdkWin32HCursor *
gdk_win32hcursor_create_for_name (GdkWin32Display *display,
const char *name)
{
GdkWin32HCursor *win32hcursor = NULL;
/* Blank cursor case */
if (strcmp (name, "none") == 0)
return create_blank_win32hcursor (display);
win32hcursor = win32hcursor_from_name (display, name);
if (win32hcursor)
return win32hcursor;
/* Allow to load named cursor resources linked into the executable.
* Cursors obtained with LoadCursor() cannot be destroyed.
*/
return gdk_win32_hcursor_new (display, LoadCursor (_gdk_app_hmodule, name), FALSE);
}
static HICON
pixbuf_to_hicon (GdkPixbuf *pixbuf,
gboolean is_icon,
int x,
int y);
static GdkWin32HCursor *
gdk_win32hcursor_create_for_texture (GdkWin32Display *display,
GdkTexture *texture,
int x,
int y)
{
cairo_surface_t *surface;
GdkPixbuf *pixbuf;
int width, height;
HICON icon;
surface = gdk_texture_download_surface (texture);
width = cairo_image_surface_get_width (surface);
height = cairo_image_surface_get_height (surface);
pixbuf = gdk_pixbuf_get_from_surface (surface, 0, 0, width, height);
icon = pixbuf_to_hicon (pixbuf, TRUE, 0, 0);
g_object_unref (pixbuf);
return gdk_win32_hcursor_new (display, (HCURSOR) icon, TRUE);
}
static gboolean
_gdk_win32_cursor_update (GdkWin32Display *win32_display,
GdkCursor *cursor,
GdkWin32HCursor *win32_hcursor,
GList **update_cursors,
GList **update_win32hcursors)
{
GdkWin32HCursor *win32hcursor_new = NULL;
Win32CursorTheme *theme;
Win32Cursor *theme_cursor;
const char *name = gdk_cursor_get_name (cursor);
/* Do nothing if this is not a named cursor. */
if (name == NULL)
return FALSE;
theme = _gdk_win32_display_get_cursor_theme (win32_display);
theme_cursor = win32_cursor_theme_get_cursor (theme, name);
if (theme_cursor != NULL)
win32hcursor_new = win32_cursor_create_win32hcursor (win32_display, theme_cursor, name);
if (win32hcursor_new == NULL)
{
g_warning (G_STRLOC ": Unable to load %s from the cursor theme", name);
win32hcursor_new = win32hcursor_idc_from_name (win32_display, name);
if (win32hcursor_new == NULL)
win32hcursor_new = win32hcursor_x_from_name (win32_display, name);
if (win32hcursor_new == NULL)
return FALSE;
}
if (GetCursor () == win32_hcursor->readonly_handle)
SetCursor (win32hcursor_new->readonly_handle);
/* Don't modify the hash table mid-iteration, put everything into a list
* and update the table later on.
*/
*update_cursors = g_list_prepend (*update_cursors, cursor);
*update_win32hcursors = g_list_prepend (*update_win32hcursors, win32hcursor_new);
return TRUE;
}
void
_gdk_win32_display_update_cursors (GdkWin32Display *display)
{
GHashTableIter iter;
GdkCursor *cursor;
GdkWin32HCursor *win32hcursor;
GList *update_cursors = NULL;
GList *update_win32hcursors = NULL;
g_hash_table_iter_init (&iter, display->cursors);
while (g_hash_table_iter_next (&iter, (gpointer *) &cursor, (gpointer *) &win32hcursor))
_gdk_win32_cursor_update (display, cursor, win32hcursor, &update_cursors, &update_win32hcursors);
while (update_cursors != NULL && update_win32hcursors != NULL)
{
g_hash_table_replace (display->cursors, update_cursors->data, update_win32hcursors->data);
update_cursors = g_list_delete_link (update_cursors, update_cursors);
update_win32hcursors = g_list_delete_link (update_win32hcursors, update_win32hcursors);
}
g_assert (update_cursors == NULL && update_win32hcursors == NULL);
}
GdkPixbuf *
gdk_win32_icon_to_pixbuf_libgtk_only (HICON hicon,
double *x_hot,
double *y_hot)
{
GdkPixbuf *pixbuf = NULL;
ICONINFO ii;
struct
{
BITMAPINFOHEADER bi;
RGBQUAD colors[2];
} bmi;
HDC hdc;
guchar *pixels, *bits;
int rowstride, x, y, w, h;
if (!GDI_CALL (GetIconInfo, (hicon, &ii)))
return NULL;
if (!(hdc = CreateCompatibleDC (NULL)))
{
WIN32_GDI_FAILED ("CreateCompatibleDC");
goto out0;
}
memset (&bmi, 0, sizeof (bmi));
bmi.bi.biSize = sizeof (bmi.bi);
if (ii.hbmColor != NULL)
{
/* Colour cursor */
gboolean no_alpha;
if (!GDI_CALL (GetDIBits, (hdc, ii.hbmColor, 0, 1, NULL, (BITMAPINFO *)&bmi, DIB_RGB_COLORS)))
goto out1;
w = bmi.bi.biWidth;
h = bmi.bi.biHeight;
bmi.bi.biBitCount = 32;
bmi.bi.biCompression = BI_RGB;
bmi.bi.biHeight = -h;
bits = g_malloc0 (4 * w * h);
/* color data */
if (!GDI_CALL (GetDIBits, (hdc, ii.hbmColor, 0, h, bits, (BITMAPINFO *)&bmi, DIB_RGB_COLORS)))
goto out2;
pixbuf = gdk_pixbuf_new (GDK_COLORSPACE_RGB, TRUE, 8, w, h);
pixels = gdk_pixbuf_get_pixels (pixbuf);
rowstride = gdk_pixbuf_get_rowstride (pixbuf);
no_alpha = TRUE;
for (y = 0; y < h; y++)
{
for (x = 0; x < w; x++)
{
pixels[2] = bits[(x+y*w) * 4];
pixels[1] = bits[(x+y*w) * 4 + 1];
pixels[0] = bits[(x+y*w) * 4 + 2];
pixels[3] = bits[(x+y*w) * 4 + 3];
if (no_alpha && pixels[3] > 0)
no_alpha = FALSE;
pixels += 4;
}
pixels += (w * 4 - rowstride);
}
/* mask */
if (no_alpha &&
GDI_CALL (GetDIBits, (hdc, ii.hbmMask, 0, h, bits, (BITMAPINFO *)&bmi, DIB_RGB_COLORS)))
{
pixels = gdk_pixbuf_get_pixels (pixbuf);
for (y = 0; y < h; y++)
{
for (x = 0; x < w; x++)
{
pixels[3] = 255 - bits[(x + y * w) * 4];
pixels += 4;
}
pixels += (w * 4 - rowstride);
}
}
}
else
{
/* B&W cursor */
int bpl;
if (!GDI_CALL (GetDIBits, (hdc, ii.hbmMask, 0, 0, NULL, (BITMAPINFO *)&bmi, DIB_RGB_COLORS)))
goto out1;
w = bmi.bi.biWidth;
h = ABS (bmi.bi.biHeight) / 2;
bits = g_malloc0 (4 * w * h);
/* masks */
if (!GDI_CALL (GetDIBits, (hdc, ii.hbmMask, 0, h*2, bits, (BITMAPINFO *)&bmi, DIB_RGB_COLORS)))
goto out2;
pixbuf = gdk_pixbuf_new (GDK_COLORSPACE_RGB, TRUE, 8, w, h);
pixels = gdk_pixbuf_get_pixels (pixbuf);
rowstride = gdk_pixbuf_get_rowstride (pixbuf);
bpl = ((w-1)/32 + 1)*4;
#if 0
for (y = 0; y < h*2; y++)
{
for (x = 0; x < w; x++)
{
const int bit = 7 - (x % 8);
printf ("%c ", ((bits[bpl*y+x/8])&(1<<bit)) ? ' ' : 'X');
}
printf ("\n");
}
#endif
for (y = 0; y < h; y++)
{
const guchar *andp, *xorp;
if (bmi.bi.biHeight < 0)
{
andp = bits + bpl*y;
xorp = bits + bpl*(h+y);
}
else
{
andp = bits + bpl*(h-y-1);
xorp = bits + bpl*(h+h-y-1);
}
for (x = 0; x < w; x++)
{
const int bit = 7 - (x % 8);
if ((*andp) & (1<<bit))
{
if ((*xorp) & (1<<bit))
pixels[2] = pixels[1] = pixels[0] = 0xFF;
else
pixels[2] = pixels[1] = pixels[0] = 0;
pixels[3] = 0xFF;
}
else
{
pixels[2] = pixels[1] = pixels[0] = 0;
pixels[3] = 0;
}
pixels += 4;
if (bit == 0)
{
andp++;
xorp++;
}
}
pixels += (w * 4 - rowstride);
}
}
if (x_hot)
*x_hot = ii.xHotspot;
if (y_hot)
*y_hot = ii.yHotspot;
/* release temporary resources */
out2:
g_free (bits);
out1:
DeleteDC (hdc);
out0:
DeleteObject (ii.hbmColor);
DeleteObject (ii.hbmMask);
return pixbuf;
}
/* Convert a pixbuf to an HICON (or HCURSOR). Supports alpha under
* Windows XP, thresholds alpha otherwise. Also used from
* gdksurface-win32.c for creating application icons.
*/
static HBITMAP
create_alpha_bitmap (int size,
guchar **outdata)
{
BITMAPV5HEADER bi;
HDC hdc;
HBITMAP hBitmap;
ZeroMemory (&bi, sizeof (BITMAPV5HEADER));
bi.bV5Size = sizeof (BITMAPV5HEADER);
bi.bV5Height = bi.bV5Width = size;
bi.bV5Planes = 1;
bi.bV5BitCount = 32;
bi.bV5Compression = BI_BITFIELDS;
/* The following mask specification specifies a supported 32 BPP
* alpha format for Windows XP (BGRA format).
*/
bi.bV5RedMask = 0x00FF0000;
bi.bV5GreenMask = 0x0000FF00;
bi.bV5BlueMask = 0x000000FF;
bi.bV5AlphaMask = 0xFF000000;
/* Create the DIB section with an alpha channel. */
hdc = GetDC (NULL);
if (!hdc)
{
WIN32_GDI_FAILED ("GetDC");
return NULL;
}
hBitmap = CreateDIBSection (hdc, (BITMAPINFO *)&bi, DIB_RGB_COLORS,
(PVOID *) outdata, NULL, (DWORD)0);
if (hBitmap == NULL)
WIN32_GDI_FAILED ("CreateDIBSection");
ReleaseDC (NULL, hdc);
return hBitmap;
}
static HBITMAP
create_color_bitmap (int size,
guchar **outdata,
int bits)
{
struct {
BITMAPV4HEADER bmiHeader;
RGBQUAD bmiColors[2];
} bmi;
HDC hdc;
HBITMAP hBitmap;
ZeroMemory (&bmi, sizeof (bmi));
bmi.bmiHeader.bV4Size = sizeof (BITMAPV4HEADER);
bmi.bmiHeader.bV4Height = bmi.bmiHeader.bV4Width = size;
bmi.bmiHeader.bV4Planes = 1;
bmi.bmiHeader.bV4BitCount = bits;
bmi.bmiHeader.bV4V4Compression = BI_RGB;
/* when bits is 1, these will be used.
* bmiColors[0] already zeroed from ZeroMemory()
*/
bmi.bmiColors[1].rgbBlue = 0xFF;
bmi.bmiColors[1].rgbGreen = 0xFF;
bmi.bmiColors[1].rgbRed = 0xFF;
hdc = GetDC (NULL);
if (!hdc)
{
WIN32_GDI_FAILED ("GetDC");
return NULL;
}
hBitmap = CreateDIBSection (hdc, (BITMAPINFO *)&bmi, DIB_RGB_COLORS,
(PVOID *) outdata, NULL, (DWORD)0);
if (hBitmap == NULL)
WIN32_GDI_FAILED ("CreateDIBSection");
ReleaseDC (NULL, hdc);
return hBitmap;
}
static gboolean
pixbuf_to_hbitmaps_alpha_winxp (GdkPixbuf *pixbuf,
HBITMAP *color,
HBITMAP *mask)
{
/* Based on code from
* http://www.dotnet247.com/247reference/msgs/13/66301.aspx
*/
HBITMAP hColorBitmap, hMaskBitmap;
guchar *indata, *inrow;
guchar *colordata, *colorrow, *maskdata, *maskbyte;
int width, height, size, i, i_offset, j, j_offset, rowstride;
guint maskstride, mask_bit;
width = gdk_pixbuf_get_width (pixbuf); /* width of icon */
height = gdk_pixbuf_get_height (pixbuf); /* height of icon */
/* The bitmaps are created square */
size = MAX (width, height);
hColorBitmap = create_alpha_bitmap (size, &colordata);
if (!hColorBitmap)
return FALSE;
hMaskBitmap = create_color_bitmap (size, &maskdata, 1);
if (!hMaskBitmap)
{
DeleteObject (hColorBitmap);
return FALSE;
}
/* MSDN says mask rows are aligned to "LONG" boundaries */
maskstride = (((size + 31) & ~31) >> 3);
indata = gdk_pixbuf_get_pixels (pixbuf);
rowstride = gdk_pixbuf_get_rowstride (pixbuf);
if (width > height)
{
i_offset = 0;
j_offset = (width - height) / 2;
}
else
{
i_offset = (height - width) / 2;
j_offset = 0;
}
for (j = 0; j < height; j++)
{
colorrow = colordata + 4*(j+j_offset)*size + 4*i_offset;
maskbyte = maskdata + (j+j_offset)*maskstride + i_offset/8;
mask_bit = (0x80 >> (i_offset % 8));
inrow = indata + (height-j-1)*rowstride;
for (i = 0; i < width; i++)
{
colorrow[4*i+0] = inrow[4*i+2];
colorrow[4*i+1] = inrow[4*i+1];
colorrow[4*i+2] = inrow[4*i+0];
colorrow[4*i+3] = inrow[4*i+3];
if (inrow[4*i+3] == 0)
maskbyte[0] |= mask_bit; /* turn ON bit */
else
maskbyte[0] &= ~mask_bit; /* turn OFF bit */
mask_bit >>= 1;
if (mask_bit == 0)
{
mask_bit = 0x80;
maskbyte++;
}
}
}
*color = hColorBitmap;
*mask = hMaskBitmap;
return TRUE;
}
static gboolean
pixbuf_to_hbitmaps_normal (GdkPixbuf *pixbuf,
HBITMAP *color,
HBITMAP *mask)
{
/* Based on code from
* http://www.dotnet247.com/247reference/msgs/13/66301.aspx
*/
HBITMAP hColorBitmap, hMaskBitmap;
guchar *indata, *inrow;
guchar *colordata, *colorrow, *maskdata, *maskbyte;
int width, height, size, i, i_offset, j, j_offset, rowstride, nc, bmstride;
gboolean has_alpha;
guint maskstride, mask_bit;
width = gdk_pixbuf_get_width (pixbuf); /* width of icon */
height = gdk_pixbuf_get_height (pixbuf); /* height of icon */
/* The bitmaps are created square */
size = MAX (width, height);
hColorBitmap = create_color_bitmap (size, &colordata, 24);
if (!hColorBitmap)
return FALSE;
hMaskBitmap = create_color_bitmap (size, &maskdata, 1);
if (!hMaskBitmap)
{
DeleteObject (hColorBitmap);
return FALSE;
}
/* rows are always aligned on 4-byte boundaries */
bmstride = size * 3;
if (bmstride % 4 != 0)
bmstride += 4 - (bmstride % 4);
/* MSDN says mask rows are aligned to "LONG" boundaries */
maskstride = (((size + 31) & ~31) >> 3);
indata = gdk_pixbuf_get_pixels (pixbuf);
rowstride = gdk_pixbuf_get_rowstride (pixbuf);
nc = gdk_pixbuf_get_n_channels (pixbuf);
has_alpha = gdk_pixbuf_get_has_alpha (pixbuf);
if (width > height)
{
i_offset = 0;
j_offset = (width - height) / 2;
}
else
{
i_offset = (height - width) / 2;
j_offset = 0;
}
for (j = 0; j < height; j++)
{
colorrow = colordata + (j+j_offset)*bmstride + 3*i_offset;
maskbyte = maskdata + (j+j_offset)*maskstride + i_offset/8;
mask_bit = (0x80 >> (i_offset % 8));
inrow = indata + (height-j-1)*rowstride;
for (i = 0; i < width; i++)
{
if (has_alpha && inrow[nc*i+3] < 128)
{
colorrow[3*i+0] = colorrow[3*i+1] = colorrow[3*i+2] = 0;
maskbyte[0] |= mask_bit; /* turn ON bit */
}
else
{
colorrow[3*i+0] = inrow[nc*i+2];
colorrow[3*i+1] = inrow[nc*i+1];
colorrow[3*i+2] = inrow[nc*i+0];
maskbyte[0] &= ~mask_bit; /* turn OFF bit */
}
mask_bit >>= 1;
if (mask_bit == 0)
{
mask_bit = 0x80;
maskbyte++;
}
}
}
*color = hColorBitmap;
*mask = hMaskBitmap;
return TRUE;
}
static HICON
pixbuf_to_hicon (GdkPixbuf *pixbuf,
gboolean is_icon,
int x,
int y)
{
ICONINFO ii;
HICON icon;
gboolean success;
if (pixbuf == NULL)
return NULL;
if (gdk_pixbuf_get_has_alpha (pixbuf))
success = pixbuf_to_hbitmaps_alpha_winxp (pixbuf, &ii.hbmColor, &ii.hbmMask);
else
success = pixbuf_to_hbitmaps_normal (pixbuf, &ii.hbmColor, &ii.hbmMask);
if (!success)
return NULL;
ii.fIcon = is_icon;
ii.xHotspot = x;
ii.yHotspot = y;
icon = CreateIconIndirect (&ii);
DeleteObject (ii.hbmColor);
DeleteObject (ii.hbmMask);
return icon;
}
HICON
_gdk_win32_texture_to_hicon (GdkTexture *texture)
{
cairo_surface_t *surface;
GdkPixbuf *pixbuf;
int width, height;
HICON icon;
surface = gdk_texture_download_surface (texture);
width = cairo_image_surface_get_width (surface);
height = cairo_image_surface_get_height (surface);
pixbuf = gdk_pixbuf_get_from_surface (surface, 0, 0, width, height);
icon = pixbuf_to_hicon (pixbuf, TRUE, 0, 0);
g_object_unref (pixbuf);
return icon;
}
HICON
_gdk_win32_pixbuf_to_hcursor (GdkPixbuf *pixbuf,
int x_hotspot,
int y_hotspot)
{
return pixbuf_to_hicon (pixbuf, FALSE, x_hotspot, y_hotspot);
}
/**
* gdk_win32_display_get_win32hcursor:
* @display: (type GdkWin32Display): a `GdkDisplay`
* @cursor: a `GdkCursor`
*
* Returns the Win32 HCURSOR wrapper object belonging to a `GdkCursor`,
* potentially creating the cursor object.
*
* Be aware that the returned cursor may not be unique to @cursor.
* It may for example be shared with its fallback cursor.
*
* Returns: a GdkWin32HCursor
*/
GdkWin32HCursor *
gdk_win32_display_get_win32hcursor (GdkWin32Display *display,
GdkCursor *cursor)
{
GdkWin32Display *win32_display = GDK_WIN32_DISPLAY (display);
GdkWin32HCursor *win32hcursor;
const char *cursor_name;
GdkCursor *fallback;
g_return_val_if_fail (cursor != NULL, NULL);
if (gdk_display_is_closed (GDK_DISPLAY (display)))
return NULL;
win32hcursor = g_hash_table_lookup (win32_display->cursors, cursor);
if (win32hcursor != NULL)
return win32hcursor;
cursor_name = gdk_cursor_get_name (cursor);
if (cursor_name)
win32hcursor = gdk_win32hcursor_create_for_name (display, cursor_name);
else
win32hcursor = gdk_win32hcursor_create_for_texture (display,
gdk_cursor_get_texture (cursor),
gdk_cursor_get_hotspot_x (cursor),
gdk_cursor_get_hotspot_y (cursor));
if (win32hcursor != NULL)
{
g_object_weak_ref (G_OBJECT (cursor), gdk_win32_cursor_remove_from_cache, display);
g_hash_table_insert (win32_display->cursors, cursor, win32hcursor);
return win32hcursor;
}
fallback = gdk_cursor_get_fallback (cursor);
if (fallback)
return gdk_win32_display_get_win32hcursor (display, fallback);
return NULL;
}
| 27.889104 | 117 | 0.596911 | [
"object"
] |
393d77ff2198c1a143037fde9812fc65457c92c5 | 417 | h | C | test/test_http/http.h | jimi36/librabbit | 32a44f0ebeef6c54f248505073772895e4ebb9c9 | [
"Apache-2.0"
] | 1 | 2019-12-22T06:03:01.000Z | 2019-12-22T06:03:01.000Z | test/test_http/http.h | jimi36/librabbit | 32a44f0ebeef6c54f248505073772895e4ebb9c9 | [
"Apache-2.0"
] | null | null | null | test/test_http/http.h | jimi36/librabbit | 32a44f0ebeef6c54f248505073772895e4ebb9c9 | [
"Apache-2.0"
] | null | null | null | #ifndef test_http_h
#define test_http_h
#include <string>
#include <pump/init.h>
#include <pump/time/timestamp.h>
#include <pump/proto/http/uri.h>
#include <pump/proto/http/client.h>
#include <pump/proto/http/server.h>
using namespace pump::proto;
void start_http_client(pump::service *sv, const std::vector<std::string> &urls);
void start_http_server(pump::service *sv, const std::string &ip, int port);
#endif | 23.166667 | 80 | 0.748201 | [
"vector"
] |
394332fd046e751657efc4a323a8b492cbd75d91 | 16,765 | c | C | src/lua/lua_rsa.c | wiedi/rspamd | 9c9527faa922fff90f04a7c22788a282b4b02fa1 | [
"BSD-2-Clause"
] | null | null | null | src/lua/lua_rsa.c | wiedi/rspamd | 9c9527faa922fff90f04a7c22788a282b4b02fa1 | [
"BSD-2-Clause"
] | null | null | null | src/lua/lua_rsa.c | wiedi/rspamd | 9c9527faa922fff90f04a7c22788a282b4b02fa1 | [
"BSD-2-Clause"
] | null | null | null | /* Copyright (c) 2013, Vsevolod Stakhov
* 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 ''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 AUTHOR BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file lua_rsa.c
* This module exports routines to load rsa keys, check inline or external
* rsa signatures. It assumes sha256 based signatures.
*/
#include "lua_common.h"
#ifdef HAVE_OPENSSL
#include <openssl/err.h>
#include <openssl/sha.h>
#include <openssl/rsa.h>
#include <openssl/pem.h>
LUA_FUNCTION_DEF (rsa_pubkey, load);
LUA_FUNCTION_DEF (rsa_pubkey, create);
LUA_FUNCTION_DEF (rsa_pubkey, gc);
LUA_FUNCTION_DEF (rsa_privkey, load);
LUA_FUNCTION_DEF (rsa_privkey, create);
LUA_FUNCTION_DEF (rsa_privkey, gc);
LUA_FUNCTION_DEF (rsa_signature, create);
LUA_FUNCTION_DEF (rsa_signature, load);
LUA_FUNCTION_DEF (rsa_signature, save);
LUA_FUNCTION_DEF (rsa_signature, gc);
LUA_FUNCTION_DEF (rsa, verify_memory);
LUA_FUNCTION_DEF (rsa, verify_file);
LUA_FUNCTION_DEF (rsa, sign_file);
LUA_FUNCTION_DEF (rsa, sign_memory);
static const struct luaL_reg rsalib_f[] = {
LUA_INTERFACE_DEF (rsa, verify_memory),
LUA_INTERFACE_DEF (rsa, verify_file),
LUA_INTERFACE_DEF (rsa, sign_memory),
LUA_INTERFACE_DEF (rsa, sign_file),
{NULL, NULL}
};
static const struct luaL_reg rsapubkeylib_f[] = {
LUA_INTERFACE_DEF (rsa_pubkey, load),
LUA_INTERFACE_DEF (rsa_pubkey, create),
{NULL, NULL}
};
static const struct luaL_reg rsapubkeylib_m[] = {
{"__tostring", rspamd_lua_class_tostring},
{"__gc", lua_rsa_pubkey_gc},
{NULL, NULL}
};
static const struct luaL_reg rsaprivkeylib_f[] = {
LUA_INTERFACE_DEF (rsa_privkey, load),
LUA_INTERFACE_DEF (rsa_privkey, create),
{NULL, NULL}
};
static const struct luaL_reg rsaprivkeylib_m[] = {
{"__tostring", rspamd_lua_class_tostring},
{"__gc", lua_rsa_privkey_gc},
{NULL, NULL}
};
static const struct luaL_reg rsasignlib_f[] = {
LUA_INTERFACE_DEF (rsa_signature, load),
LUA_INTERFACE_DEF (rsa_signature, create),
{NULL, NULL}
};
static const struct luaL_reg rsasignlib_m[] = {
LUA_INTERFACE_DEF (rsa_signature, save),
{"__tostring", rspamd_lua_class_tostring},
{"__gc", lua_rsa_signature_gc},
{NULL, NULL}
};
static RSA *
lua_check_rsa_pubkey (lua_State * L, int pos)
{
void *ud = luaL_checkudata (L, pos, "rspamd{rsa_pubkey}");
luaL_argcheck (L, ud != NULL, 1, "'rsa_pubkey' expected");
return ud ? *((RSA **)ud) : NULL;
}
static RSA *
lua_check_rsa_privkey (lua_State * L, int pos)
{
void *ud = luaL_checkudata (L, pos, "rspamd{rsa_privkey}");
luaL_argcheck (L, ud != NULL, 1, "'rsa_privkey' expected");
return ud ? *((RSA **)ud) : NULL;
}
static rspamd_fstring_t *
lua_check_rsa_sign (lua_State * L, int pos)
{
void *ud = luaL_checkudata (L, pos, "rspamd{rsa_signature}");
luaL_argcheck (L, ud != NULL, 1, "'rsa_signature' expected");
return ud ? *((rspamd_fstring_t **)ud) : NULL;
}
static gint
lua_rsa_pubkey_load (lua_State *L)
{
RSA *rsa = NULL, **prsa;
const gchar *filename;
FILE *f;
filename = luaL_checkstring (L, 1);
if (filename != NULL) {
f = fopen (filename, "r");
if (f == NULL) {
msg_err ("cannot open pubkey from file: %s, %s",
filename,
strerror (errno));
lua_pushnil (L);
}
else {
if (!PEM_read_RSA_PUBKEY (f, &rsa, NULL, NULL)) {
msg_err ("cannot open pubkey from file: %s, %s", filename,
ERR_error_string (ERR_get_error (), NULL));
lua_pushnil (L);
}
else {
prsa = lua_newuserdata (L, sizeof (RSA *));
rspamd_lua_setclass (L, "rspamd{rsa_pubkey}", -1);
*prsa = rsa;
}
fclose (f);
}
}
else {
lua_pushnil (L);
}
return 1;
}
static gint
lua_rsa_pubkey_create (lua_State *L)
{
RSA *rsa = NULL, **prsa;
const gchar *buf;
BIO *bp;
buf = luaL_checkstring (L, 1);
if (buf != NULL) {
bp = BIO_new_mem_buf ((void *)buf, -1);
if (!PEM_read_bio_RSA_PUBKEY (bp, &rsa, NULL, NULL)) {
msg_err ("cannot parse pubkey: %s",
ERR_error_string (ERR_get_error (), NULL));
lua_pushnil (L);
}
else {
prsa = lua_newuserdata (L, sizeof (RSA *));
rspamd_lua_setclass (L, "rspamd{rsa_pubkey}", -1);
*prsa = rsa;
}
BIO_free (bp);
}
else {
lua_pushnil (L);
}
return 1;
}
static gint
lua_rsa_pubkey_gc (lua_State *L)
{
RSA *rsa = lua_check_rsa_pubkey (L, 1);
if (rsa != NULL) {
RSA_free (rsa);
}
return 0;
}
static gint
lua_rsa_privkey_load (lua_State *L)
{
RSA *rsa = NULL, **prsa;
const gchar *filename;
FILE *f;
filename = luaL_checkstring (L, 1);
if (filename != NULL) {
f = fopen (filename, "r");
if (f == NULL) {
msg_err ("cannot open private key from file: %s, %s",
filename,
strerror (errno));
lua_pushnil (L);
}
else {
if (!PEM_read_RSAPrivateKey (f, &rsa, NULL, NULL)) {
msg_err ("cannot open private key from file: %s, %s", filename,
ERR_error_string (ERR_get_error (), NULL));
lua_pushnil (L);
}
else {
prsa = lua_newuserdata (L, sizeof (RSA *));
rspamd_lua_setclass (L, "rspamd{rsa_privkey}", -1);
*prsa = rsa;
}
fclose (f);
}
}
else {
lua_pushnil (L);
}
return 1;
}
static gint
lua_rsa_privkey_create (lua_State *L)
{
RSA *rsa = NULL, **prsa;
const gchar *buf;
BIO *bp;
buf = luaL_checkstring (L, 1);
if (buf != NULL) {
bp = BIO_new_mem_buf ((void *)buf, -1);
if (!PEM_read_bio_RSAPrivateKey (bp, &rsa, NULL, NULL)) {
msg_err ("cannot parse private key: %s",
ERR_error_string (ERR_get_error (), NULL));
lua_pushnil (L);
}
else {
prsa = lua_newuserdata (L, sizeof (RSA *));
rspamd_lua_setclass (L, "rspamd{rsa_privkey}", -1);
*prsa = rsa;
}
BIO_free (bp);
}
else {
lua_pushnil (L);
}
return 1;
}
static gint
lua_rsa_privkey_gc (lua_State *L)
{
RSA *rsa = lua_check_rsa_privkey (L, 1);
if (rsa != NULL) {
RSA_free (rsa);
}
return 0;
}
static gint
lua_rsa_signature_load (lua_State *L)
{
rspamd_fstring_t *sig, **psig;
const gchar *filename;
gpointer data;
int fd;
struct stat st;
filename = luaL_checkstring (L, 1);
if (filename != NULL) {
fd = open (filename, O_RDONLY);
if (fd == -1) {
msg_err ("cannot open signature file: %s, %s", filename,
strerror (errno));
lua_pushnil (L);
}
else {
sig = g_malloc (sizeof (rspamd_fstring_t));
if (fstat (fd, &st) == -1 ||
(data =
mmap (NULL, st.st_size, PROT_READ, MAP_SHARED, fd,
0)) == MAP_FAILED) {
msg_err ("cannot mmap file %s: %s", filename, strerror (errno));
lua_pushnil (L);
}
else {
sig->size = st.st_size;
sig->len = sig->size;
sig->begin = g_malloc (sig->len);
memcpy (sig->begin, data, sig->len);
psig = lua_newuserdata (L, sizeof (rspamd_fstring_t *));
rspamd_lua_setclass (L, "rspamd{rsa_signature}", -1);
*psig = sig;
munmap (data, st.st_size);
}
close (fd);
}
}
else {
lua_pushnil (L);
}
return 1;
}
static gint
lua_rsa_signature_save (lua_State *L)
{
rspamd_fstring_t *sig;
gint fd, flags;
const gchar *filename;
gboolean forced = FALSE, res = TRUE;
sig = lua_check_rsa_sign (L, 1);
filename = luaL_checkstring (L, 2);
if (lua_gettop (L) > 2) {
forced = lua_toboolean (L, 3);
}
if (sig != NULL && filename != NULL) {
flags = O_WRONLY | O_CREAT;
if (forced) {
flags |= O_TRUNC;
}
else {
flags |= O_EXCL;
}
fd = open (filename, flags, 00644);
if (fd == -1) {
msg_err ("cannot create a signature file: %s, %s",
filename,
strerror (errno));
lua_pushboolean (L, FALSE);
}
else {
while (write (fd, sig->begin, sig->len) == -1) {
if (errno == EINTR) {
continue;
}
msg_err ("cannot write to a signature file: %s, %s",
filename,
strerror (errno));
res = FALSE;
break;
}
lua_pushboolean (L, res);
close (fd);
}
}
else {
lua_pushboolean (L, FALSE);
}
return 1;
}
static gint
lua_rsa_signature_create (lua_State *L)
{
rspamd_fstring_t *sig, **psig;
const gchar *data;
data = luaL_checkstring (L, 1);
if (data != NULL) {
sig = g_malloc (sizeof (rspamd_fstring_t));
sig->len = strlen (data);
sig->size = sig->len;
sig->begin = g_malloc (sig->len);
memcpy (sig->begin, data, sig->len);
psig = lua_newuserdata (L, sizeof (rspamd_fstring_t *));
rspamd_lua_setclass (L, "rspamd{rsa_signature}", -1);
*psig = sig;
}
return 1;
}
static gint
lua_rsa_signature_gc (lua_State *L)
{
rspamd_fstring_t *sig = lua_check_rsa_sign (L, 1);
if (sig != NULL) {
if (sig->begin != NULL) {
g_free (sig->begin);
}
g_free (sig);
}
return 0;
}
/**
* Check memory using specified rsa key and signature
*
* arguments:
* (rsa_pubkey, rsa_signature, string)
*
* returns:
* true - if string match rsa signature
* false - otherwise
*/
static gint
lua_rsa_verify_memory (lua_State *L)
{
RSA *rsa;
rspamd_fstring_t *signature;
const gchar *data;
gchar *data_sig;
gint ret;
rsa = lua_check_rsa_pubkey (L, 1);
signature = lua_check_rsa_sign (L, 2);
data = luaL_checkstring (L, 3);
if (rsa != NULL && signature != NULL && data != NULL) {
data_sig = g_compute_checksum_for_string (G_CHECKSUM_SHA256, data, -1);
ret = RSA_verify (NID_sha1, data_sig, strlen (data_sig),
signature->begin, signature->len, rsa);
if (ret == 0) {
msg_info ("cannot check rsa signature for data: %s",
ERR_error_string (ERR_get_error (), NULL));
lua_pushboolean (L, FALSE);
}
else {
lua_pushboolean (L, TRUE);
}
g_free (data_sig);
}
else {
lua_pushnil (L);
}
return 1;
}
/**
* Check memory using specified rsa key and signature
*
* arguments:
* (rsa_pubkey, rsa_signature, string)
*
* returns:
* true - if string match rsa signature
* false - otherwise
*/
static gint
lua_rsa_verify_file (lua_State *L)
{
RSA *rsa;
rspamd_fstring_t *signature;
const gchar *filename;
gchar *data = NULL, *data_sig;
gint ret, fd;
struct stat st;
rsa = lua_check_rsa_pubkey (L, 1);
signature = lua_check_rsa_sign (L, 2);
filename = luaL_checkstring (L, 3);
if (rsa != NULL && signature != NULL && filename != NULL) {
fd = open (filename, O_RDONLY);
if (fd == -1) {
msg_err ("cannot open file %s: %s", filename, strerror (errno));
lua_pushnil (L);
}
else {
if (fstat (fd, &st) == -1 ||
(data =
mmap (NULL, st.st_size, PROT_READ, MAP_SHARED, fd,
0)) == MAP_FAILED) {
msg_err ("cannot mmap file %s: %s", filename, strerror (errno));
lua_pushnil (L);
}
else {
data_sig = g_compute_checksum_for_data (G_CHECKSUM_SHA256,
data,
st.st_size);
ret = RSA_verify (NID_sha1, data_sig, strlen (data_sig),
signature->begin, signature->len, rsa);
if (ret == 0) {
msg_info ("cannot check rsa signature for file: %s, %s",
filename, ERR_error_string (ERR_get_error (), NULL));
lua_pushboolean (L, FALSE);
}
else {
lua_pushboolean (L, TRUE);
}
g_free (data_sig);
munmap (data, st.st_size);
}
close (fd);
}
}
else {
lua_pushnil (L);
}
return 1;
}
/**
* Sign memory using specified rsa key and signature
*
* arguments:
* (rsa_privkey, string)
*
* returns:
* rspamd_signature object
* nil - otherwise
*/
static gint
lua_rsa_sign_memory (lua_State *L)
{
RSA *rsa;
rspamd_fstring_t *signature, **psig;
const gchar *data;
gchar *data_sig;
gint ret;
rsa = lua_check_rsa_privkey (L, 1);
data = luaL_checkstring (L, 2);
if (rsa != NULL && data != NULL) {
signature = g_malloc (sizeof (rspamd_fstring_t));
signature->len = RSA_size (rsa);
signature->size = signature->len;
signature->begin = g_malloc (signature->len);
data_sig = g_compute_checksum_for_string (G_CHECKSUM_SHA256, data, -1);
ret = RSA_sign (NID_sha1, data_sig, strlen (data_sig),
signature->begin, (guint *)&signature->len, rsa);
if (ret == 0) {
msg_info ("cannot make a signature for data: %s",
ERR_error_string (ERR_get_error (), NULL));
lua_pushnil (L);
g_free (signature->begin);
g_free (signature);
}
else {
psig = lua_newuserdata (L, sizeof (rspamd_fstring_t *));
rspamd_lua_setclass (L, "rspamd{rsa_signature}", -1);
*psig = signature;
}
g_free (data_sig);
}
else {
lua_pushnil (L);
}
return 1;
}
/**
* Sign file using specified rsa key and signature
*
* arguments:
* (rsa_privkey, rsa_signature, string)
*
* returns:
* true - if string match rsa signature
* false - otherwise
*/
static gint
lua_rsa_sign_file (lua_State *L)
{
RSA *rsa;
rspamd_fstring_t *signature, **psig;
const gchar *filename;
gchar *data = NULL, *data_sig;
gint ret, fd;
struct stat st;
rsa = lua_check_rsa_privkey (L, 1);
filename = luaL_checkstring (L, 2);
if (rsa != NULL && filename != NULL) {
fd = open (filename, O_RDONLY);
if (fd == -1) {
msg_err ("cannot open file %s: %s", filename, strerror (errno));
lua_pushnil (L);
}
else {
if (fstat (fd, &st) == -1 ||
(data =
mmap (NULL, st.st_size, PROT_READ, MAP_SHARED, fd,
0)) == MAP_FAILED) {
msg_err ("cannot mmap file %s: %s", filename, strerror (errno));
lua_pushnil (L);
}
else {
signature = g_malloc (sizeof (rspamd_fstring_t));
signature->len = RSA_size (rsa);
signature->size = signature->len;
signature->begin = g_malloc (signature->len);
data_sig = g_compute_checksum_for_string (G_CHECKSUM_SHA256,
data,
st.st_size);
ret = RSA_sign (NID_sha1, data_sig, strlen (data_sig),
signature->begin, (guint *)&signature->len, rsa);
if (ret == 0) {
msg_info ("cannot make a signature for data: %s",
ERR_error_string (ERR_get_error (), NULL));
lua_pushnil (L);
g_free (signature->begin);
g_free (signature);
}
else {
psig = lua_newuserdata (L, sizeof (rspamd_fstring_t *));
rspamd_lua_setclass (L, "rspamd{rsa_signature}", -1);
*psig = signature;
}
g_free (data_sig);
munmap (data, st.st_size);
}
close (fd);
}
}
else {
lua_pushnil (L);
}
return 1;
}
static gint
lua_load_pubkey (lua_State * L)
{
lua_newtable (L);
luaL_register (L, NULL, rsapubkeylib_f);
return 1;
}
static gint
lua_load_privkey (lua_State * L)
{
lua_newtable (L);
luaL_register (L, NULL, rsaprivkeylib_f);
return 1;
}
static gint
lua_load_signature (lua_State * L)
{
lua_newtable (L);
luaL_register (L, NULL, rsasignlib_f);
return 1;
}
static gint
lua_load_rsa (lua_State * L)
{
lua_newtable (L);
luaL_register (L, NULL, rsalib_f);
return 1;
}
void
luaopen_rsa (lua_State * L)
{
luaL_newmetatable (L, "rspamd{rsa_pubkey}");
lua_pushstring (L, "__index");
lua_pushvalue (L, -2);
lua_settable (L, -3);
lua_pushstring (L, "class");
lua_pushstring (L, "rspamd{rsa_pubkey}");
lua_rawset (L, -3);
luaL_register (L, NULL, rsapubkeylib_m);
rspamd_lua_add_preload (L, "rspamd_rsa_pubkey", lua_load_pubkey);
luaL_newmetatable (L, "rspamd{rsa_privkey}");
lua_pushstring (L, "__index");
lua_pushvalue (L, -2);
lua_settable (L, -3);
lua_pushstring (L, "class");
lua_pushstring (L, "rspamd{rsa_privkey}");
lua_rawset (L, -3);
luaL_register (L, NULL, rsaprivkeylib_m);
rspamd_lua_add_preload (L, "rspamd_rsa_privkey", lua_load_privkey);
luaL_newmetatable (L, "rspamd{rsa_signature}");
lua_pushstring (L, "__index");
lua_pushvalue (L, -2);
lua_settable (L, -3);
lua_pushstring (L, "class");
lua_pushstring (L, "rspamd{rsa_signature}");
lua_rawset (L, -3);
luaL_register (L, NULL, rsasignlib_m);
rspamd_lua_add_preload (L, "rspamd_rsa_signature", lua_load_signature);
rspamd_lua_add_preload (L, "rspamd_rsa", lua_load_rsa);
lua_settop (L, 0);
}
#else
void
luaopen_rsa (lua_State * L)
{
msg_info ("this rspamd version is not linked against openssl, therefore no "
"RSA support is available");
}
#endif
| 22.903005 | 80 | 0.659588 | [
"object"
] |
39460ad496ecd5f73a0f230d0417d9412fca745b | 1,265 | c | C | test/test_image.c | zhuguangxiang/koala-lang-pre | b9fc6e0027b61ec89521419c41b0fd5a9b1cebf5 | [
"MIT"
] | null | null | null | test/test_image.c | zhuguangxiang/koala-lang-pre | b9fc6e0027b61ec89521419c41b0fd5a9b1cebf5 | [
"MIT"
] | null | null | null | test/test_image.c | zhuguangxiang/koala-lang-pre | b9fc6e0027b61ec89521419c41b0fd5a9b1cebf5 | [
"MIT"
] | 1 | 2021-03-14T09:19:44.000Z | 2021-03-14T09:19:44.000Z |
#include "image.h"
#include "atomstring.h"
#include "intobject.h"
#include "stringobject.h"
#include "opcode.h"
void test_image(void)
{
KImage *image = KImage_New("test");
Vector *ret = Vector_New();
TypeDesc *desc = TypeDesc_Get_Base(BASE_STRING);
TYPE_INCREF(desc);
Vector_Append(ret, desc);
desc = TypeDesc_Get_Base(BASE_INT);
TYPE_INCREF(desc);
Vector_Append(ret, desc);
TypeDesc *proto = TypeDesc_Get_Proto(NULL, ret);
uint8 *psudo = malloc(4);
psudo[0] = LOAD;
psudo[1] = LOAD_CONST;
psudo[2] = ADD;
psudo[3] = RETURN;
KImage_Add_Func(image, "Foo", proto, psudo, 4);
desc = TypeDesc_Get_Base(BASE_STRING);
KImage_Add_Var(image, "Greeting", desc, 0);
desc = TypeDesc_Get_Base(BASE_INT);
KImage_Add_Var(image, "MAX_LENGTH", desc, 1);
KImage_Finish(image);
KImage_Show(image);
KImage_Write_File(image, "foo.klc");
KImage_Free(image);
image = KImage_Read_File("foo.klc", 0);
KImage_Show(image);
KImage_Free(image);
}
int main(int argc, char *argv[])
{
UNUSED_PARAMETER(argc);
UNUSED_PARAMETER(argv);
AtomString_Init();
Init_TypeDesc();
Init_String_Klass();
Init_Integer_Klass();
test_image();
Fini_String_Klass();
Fini_Integer_Klass();
Fini_TypeDesc();
AtomString_Fini();
return 0;
}
| 23.867925 | 50 | 0.702767 | [
"vector"
] |
3950028bf513a6fbb4ad52a229f37ca2843bc570 | 86,570 | c | C | src/amd/vulkan/radv_acceleration_structure.c | SoftReaper/Mesa-Renoir-deb | 8d1de1f66058d62b41fe55d36522efea2bdf996d | [
"MIT"
] | null | null | null | src/amd/vulkan/radv_acceleration_structure.c | SoftReaper/Mesa-Renoir-deb | 8d1de1f66058d62b41fe55d36522efea2bdf996d | [
"MIT"
] | null | null | null | src/amd/vulkan/radv_acceleration_structure.c | SoftReaper/Mesa-Renoir-deb | 8d1de1f66058d62b41fe55d36522efea2bdf996d | [
"MIT"
] | null | null | null | /*
* Copyright © 2021 Bas Nieuwenhuizen
*
* 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 (including the next
* paragraph) 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 "radv_acceleration_structure.h"
#include "radv_private.h"
#include "util/format/format_utils.h"
#include "util/half_float.h"
#include "nir_builder.h"
#include "radv_cs.h"
#include "radv_meta.h"
VKAPI_ATTR void VKAPI_CALL
radv_GetAccelerationStructureBuildSizesKHR(
VkDevice _device, VkAccelerationStructureBuildTypeKHR buildType,
const VkAccelerationStructureBuildGeometryInfoKHR *pBuildInfo,
const uint32_t *pMaxPrimitiveCounts, VkAccelerationStructureBuildSizesInfoKHR *pSizeInfo)
{
uint64_t triangles = 0, boxes = 0, instances = 0;
STATIC_ASSERT(sizeof(struct radv_bvh_triangle_node) == 64);
STATIC_ASSERT(sizeof(struct radv_bvh_aabb_node) == 64);
STATIC_ASSERT(sizeof(struct radv_bvh_instance_node) == 128);
STATIC_ASSERT(sizeof(struct radv_bvh_box16_node) == 64);
STATIC_ASSERT(sizeof(struct radv_bvh_box32_node) == 128);
for (uint32_t i = 0; i < pBuildInfo->geometryCount; ++i) {
const VkAccelerationStructureGeometryKHR *geometry;
if (pBuildInfo->pGeometries)
geometry = &pBuildInfo->pGeometries[i];
else
geometry = pBuildInfo->ppGeometries[i];
switch (geometry->geometryType) {
case VK_GEOMETRY_TYPE_TRIANGLES_KHR:
triangles += pMaxPrimitiveCounts[i];
break;
case VK_GEOMETRY_TYPE_AABBS_KHR:
boxes += pMaxPrimitiveCounts[i];
break;
case VK_GEOMETRY_TYPE_INSTANCES_KHR:
instances += pMaxPrimitiveCounts[i];
break;
case VK_GEOMETRY_TYPE_MAX_ENUM_KHR:
unreachable("VK_GEOMETRY_TYPE_MAX_ENUM_KHR unhandled");
}
}
uint64_t children = boxes + instances + triangles;
uint64_t internal_nodes = 0;
while (children > 1) {
children = DIV_ROUND_UP(children, 4);
internal_nodes += children;
}
/* The stray 128 is to ensure we have space for a header
* which we'd want to use for some metadata (like the
* total AABB of the BVH) */
uint64_t size = boxes * 128 + instances * 128 + triangles * 64 + internal_nodes * 128 + 192;
pSizeInfo->accelerationStructureSize = size;
/* 2x the max number of nodes in a BVH layer (one uint32_t each) */
pSizeInfo->updateScratchSize = pSizeInfo->buildScratchSize =
MAX2(4096, 2 * (boxes + instances + triangles) * sizeof(uint32_t));
}
VKAPI_ATTR VkResult VKAPI_CALL
radv_CreateAccelerationStructureKHR(VkDevice _device,
const VkAccelerationStructureCreateInfoKHR *pCreateInfo,
const VkAllocationCallbacks *pAllocator,
VkAccelerationStructureKHR *pAccelerationStructure)
{
RADV_FROM_HANDLE(radv_device, device, _device);
RADV_FROM_HANDLE(radv_buffer, buffer, pCreateInfo->buffer);
struct radv_acceleration_structure *accel;
accel = vk_alloc2(&device->vk.alloc, pAllocator, sizeof(*accel), 8,
VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
if (accel == NULL)
return vk_error(device, VK_ERROR_OUT_OF_HOST_MEMORY);
vk_object_base_init(&device->vk, &accel->base, VK_OBJECT_TYPE_ACCELERATION_STRUCTURE_KHR);
accel->mem_offset = buffer->offset + pCreateInfo->offset;
accel->size = pCreateInfo->size;
accel->bo = buffer->bo;
*pAccelerationStructure = radv_acceleration_structure_to_handle(accel);
return VK_SUCCESS;
}
VKAPI_ATTR void VKAPI_CALL
radv_DestroyAccelerationStructureKHR(VkDevice _device,
VkAccelerationStructureKHR accelerationStructure,
const VkAllocationCallbacks *pAllocator)
{
RADV_FROM_HANDLE(radv_device, device, _device);
RADV_FROM_HANDLE(radv_acceleration_structure, accel, accelerationStructure);
if (!accel)
return;
vk_object_base_finish(&accel->base);
vk_free2(&device->vk.alloc, pAllocator, accel);
}
VKAPI_ATTR VkDeviceAddress VKAPI_CALL
radv_GetAccelerationStructureDeviceAddressKHR(
VkDevice _device, const VkAccelerationStructureDeviceAddressInfoKHR *pInfo)
{
RADV_FROM_HANDLE(radv_acceleration_structure, accel, pInfo->accelerationStructure);
return radv_accel_struct_get_va(accel);
}
VKAPI_ATTR VkResult VKAPI_CALL
radv_WriteAccelerationStructuresPropertiesKHR(
VkDevice _device, uint32_t accelerationStructureCount,
const VkAccelerationStructureKHR *pAccelerationStructures, VkQueryType queryType,
size_t dataSize, void *pData, size_t stride)
{
RADV_FROM_HANDLE(radv_device, device, _device);
char *data_out = (char*)pData;
for (uint32_t i = 0; i < accelerationStructureCount; ++i) {
RADV_FROM_HANDLE(radv_acceleration_structure, accel, pAccelerationStructures[i]);
const char *base_ptr = (const char *)device->ws->buffer_map(accel->bo);
if (!base_ptr)
return vk_error(device, VK_ERROR_OUT_OF_HOST_MEMORY);
const struct radv_accel_struct_header *header = (const void*)(base_ptr + accel->mem_offset);
if (stride * i + sizeof(VkDeviceSize) <= dataSize) {
uint64_t value;
switch (queryType) {
case VK_QUERY_TYPE_ACCELERATION_STRUCTURE_COMPACTED_SIZE_KHR:
value = header->compacted_size;
break;
case VK_QUERY_TYPE_ACCELERATION_STRUCTURE_SERIALIZATION_SIZE_KHR:
value = header->serialization_size;
break;
default:
unreachable("Unhandled acceleration structure query");
}
*(VkDeviceSize *)(data_out + stride * i) = value;
}
device->ws->buffer_unmap(accel->bo);
}
return VK_SUCCESS;
}
struct radv_bvh_build_ctx {
uint32_t *write_scratch;
char *base;
char *curr_ptr;
};
static void
build_triangles(struct radv_bvh_build_ctx *ctx, const VkAccelerationStructureGeometryKHR *geom,
const VkAccelerationStructureBuildRangeInfoKHR *range, unsigned geometry_id)
{
const VkAccelerationStructureGeometryTrianglesDataKHR *tri_data = &geom->geometry.triangles;
VkTransformMatrixKHR matrix;
const char *index_data = (const char *)tri_data->indexData.hostAddress + range->primitiveOffset;
if (tri_data->transformData.hostAddress) {
matrix = *(const VkTransformMatrixKHR *)((const char *)tri_data->transformData.hostAddress +
range->transformOffset);
} else {
matrix = (VkTransformMatrixKHR){
.matrix = {{1.0, 0.0, 0.0, 0.0}, {0.0, 1.0, 0.0, 0.0}, {0.0, 0.0, 1.0, 0.0}}};
}
for (uint32_t p = 0; p < range->primitiveCount; ++p, ctx->curr_ptr += 64) {
struct radv_bvh_triangle_node *node = (void*)ctx->curr_ptr;
uint32_t node_offset = ctx->curr_ptr - ctx->base;
uint32_t node_id = node_offset >> 3;
*ctx->write_scratch++ = node_id;
for (unsigned v = 0; v < 3; ++v) {
uint32_t v_index = range->firstVertex;
switch (tri_data->indexType) {
case VK_INDEX_TYPE_NONE_KHR:
v_index += p * 3 + v;
break;
case VK_INDEX_TYPE_UINT8_EXT:
v_index += *(const uint8_t *)index_data;
index_data += 1;
break;
case VK_INDEX_TYPE_UINT16:
v_index += *(const uint16_t *)index_data;
index_data += 2;
break;
case VK_INDEX_TYPE_UINT32:
v_index += *(const uint32_t *)index_data;
index_data += 4;
break;
case VK_INDEX_TYPE_MAX_ENUM:
unreachable("Unhandled VK_INDEX_TYPE_MAX_ENUM");
break;
}
const char *v_data = (const char *)tri_data->vertexData.hostAddress + v_index * tri_data->vertexStride;
float coords[4];
switch (tri_data->vertexFormat) {
case VK_FORMAT_R32G32_SFLOAT:
coords[0] = *(const float *)(v_data + 0);
coords[1] = *(const float *)(v_data + 4);
coords[2] = 0.0f;
coords[3] = 1.0f;
break;
case VK_FORMAT_R32G32B32_SFLOAT:
coords[0] = *(const float *)(v_data + 0);
coords[1] = *(const float *)(v_data + 4);
coords[2] = *(const float *)(v_data + 8);
coords[3] = 1.0f;
break;
case VK_FORMAT_R32G32B32A32_SFLOAT:
coords[0] = *(const float *)(v_data + 0);
coords[1] = *(const float *)(v_data + 4);
coords[2] = *(const float *)(v_data + 8);
coords[3] = *(const float *)(v_data + 12);
break;
case VK_FORMAT_R16G16_SFLOAT:
coords[0] = _mesa_half_to_float(*(const uint16_t *)(v_data + 0));
coords[1] = _mesa_half_to_float(*(const uint16_t *)(v_data + 2));
coords[2] = 0.0f;
coords[3] = 1.0f;
break;
case VK_FORMAT_R16G16B16_SFLOAT:
coords[0] = _mesa_half_to_float(*(const uint16_t *)(v_data + 0));
coords[1] = _mesa_half_to_float(*(const uint16_t *)(v_data + 2));
coords[2] = _mesa_half_to_float(*(const uint16_t *)(v_data + 4));
coords[3] = 1.0f;
break;
case VK_FORMAT_R16G16B16A16_SFLOAT:
coords[0] = _mesa_half_to_float(*(const uint16_t *)(v_data + 0));
coords[1] = _mesa_half_to_float(*(const uint16_t *)(v_data + 2));
coords[2] = _mesa_half_to_float(*(const uint16_t *)(v_data + 4));
coords[3] = _mesa_half_to_float(*(const uint16_t *)(v_data + 6));
break;
case VK_FORMAT_R16G16_SNORM:
coords[0] = _mesa_snorm_to_float(*(const int16_t *)(v_data + 0), 16);
coords[1] = _mesa_snorm_to_float(*(const int16_t *)(v_data + 2), 16);
coords[2] = 0.0f;
coords[3] = 1.0f;
break;
case VK_FORMAT_R16G16B16A16_SNORM:
coords[0] = _mesa_snorm_to_float(*(const int16_t *)(v_data + 0), 16);
coords[1] = _mesa_snorm_to_float(*(const int16_t *)(v_data + 2), 16);
coords[2] = _mesa_snorm_to_float(*(const int16_t *)(v_data + 4), 16);
coords[3] = _mesa_snorm_to_float(*(const int16_t *)(v_data + 6), 16);
break;
case VK_FORMAT_R16G16B16A16_UNORM:
coords[0] = _mesa_unorm_to_float(*(const uint16_t *)(v_data + 0), 16);
coords[1] = _mesa_unorm_to_float(*(const uint16_t *)(v_data + 2), 16);
coords[2] = _mesa_unorm_to_float(*(const uint16_t *)(v_data + 4), 16);
coords[3] = _mesa_unorm_to_float(*(const uint16_t *)(v_data + 6), 16);
break;
default:
unreachable("Unhandled vertex format in BVH build");
}
for (unsigned j = 0; j < 3; ++j) {
float r = 0;
for (unsigned k = 0; k < 4; ++k)
r += matrix.matrix[j][k] * coords[k];
node->coords[v][j] = r;
}
node->triangle_id = p;
node->geometry_id_and_flags = geometry_id | (geom->flags << 28);
/* Seems to be needed for IJ, otherwise I = J = ? */
node->id = 9;
}
}
}
static VkResult
build_instances(struct radv_device *device, struct radv_bvh_build_ctx *ctx,
const VkAccelerationStructureGeometryKHR *geom,
const VkAccelerationStructureBuildRangeInfoKHR *range)
{
const VkAccelerationStructureGeometryInstancesDataKHR *inst_data = &geom->geometry.instances;
for (uint32_t p = 0; p < range->primitiveCount; ++p, ctx->curr_ptr += 128) {
const VkAccelerationStructureInstanceKHR *instance =
inst_data->arrayOfPointers
? (((const VkAccelerationStructureInstanceKHR *const *)inst_data->data.hostAddress)[p])
: &((const VkAccelerationStructureInstanceKHR *)inst_data->data.hostAddress)[p];
if (!instance->accelerationStructureReference) {
continue;
}
struct radv_bvh_instance_node *node = (void*)ctx->curr_ptr;
uint32_t node_offset = ctx->curr_ptr - ctx->base;
uint32_t node_id = (node_offset >> 3) | 6;
*ctx->write_scratch++ = node_id;
float transform[16], inv_transform[16];
memcpy(transform, &instance->transform.matrix, sizeof(instance->transform.matrix));
transform[12] = transform[13] = transform[14] = 0.0f;
transform[15] = 1.0f;
util_invert_mat4x4(inv_transform, transform);
memcpy(node->wto_matrix, inv_transform, sizeof(node->wto_matrix));
node->wto_matrix[3] = transform[3];
node->wto_matrix[7] = transform[7];
node->wto_matrix[11] = transform[11];
node->custom_instance_and_mask = instance->instanceCustomIndex | (instance->mask << 24);
node->sbt_offset_and_flags =
instance->instanceShaderBindingTableRecordOffset | (instance->flags << 24);
node->instance_id = p;
for (unsigned i = 0; i < 3; ++i)
for (unsigned j = 0; j < 3; ++j)
node->otw_matrix[i * 3 + j] = instance->transform.matrix[j][i];
RADV_FROM_HANDLE(radv_acceleration_structure, src_accel_struct,
(VkAccelerationStructureKHR)instance->accelerationStructureReference);
const void *src_base = device->ws->buffer_map(src_accel_struct->bo);
if (!src_base)
return vk_error(device, VK_ERROR_OUT_OF_HOST_MEMORY);
src_base = (const char *)src_base + src_accel_struct->mem_offset;
const struct radv_accel_struct_header *src_header = src_base;
node->base_ptr = radv_accel_struct_get_va(src_accel_struct) | src_header->root_node_offset;
for (unsigned j = 0; j < 3; ++j) {
node->aabb[0][j] = instance->transform.matrix[j][3];
node->aabb[1][j] = instance->transform.matrix[j][3];
for (unsigned k = 0; k < 3; ++k) {
node->aabb[0][j] += MIN2(instance->transform.matrix[j][k] * src_header->aabb[0][k],
instance->transform.matrix[j][k] * src_header->aabb[1][k]);
node->aabb[1][j] += MAX2(instance->transform.matrix[j][k] * src_header->aabb[0][k],
instance->transform.matrix[j][k] * src_header->aabb[1][k]);
}
}
device->ws->buffer_unmap(src_accel_struct->bo);
}
return VK_SUCCESS;
}
static void
build_aabbs(struct radv_bvh_build_ctx *ctx, const VkAccelerationStructureGeometryKHR *geom,
const VkAccelerationStructureBuildRangeInfoKHR *range, unsigned geometry_id)
{
const VkAccelerationStructureGeometryAabbsDataKHR *aabb_data = &geom->geometry.aabbs;
for (uint32_t p = 0; p < range->primitiveCount; ++p, ctx->curr_ptr += 64) {
struct radv_bvh_aabb_node *node = (void*)ctx->curr_ptr;
uint32_t node_offset = ctx->curr_ptr - ctx->base;
uint32_t node_id = (node_offset >> 3) | 7;
*ctx->write_scratch++ = node_id;
const VkAabbPositionsKHR *aabb =
(const VkAabbPositionsKHR *)((const char *)aabb_data->data.hostAddress +
p * aabb_data->stride);
node->aabb[0][0] = aabb->minX;
node->aabb[0][1] = aabb->minY;
node->aabb[0][2] = aabb->minZ;
node->aabb[1][0] = aabb->maxX;
node->aabb[1][1] = aabb->maxY;
node->aabb[1][2] = aabb->maxZ;
node->primitive_id = p;
node->geometry_id_and_flags = geometry_id;
}
}
static uint32_t
leaf_node_count(const VkAccelerationStructureBuildGeometryInfoKHR *info,
const VkAccelerationStructureBuildRangeInfoKHR *ranges)
{
uint32_t count = 0;
for (uint32_t i = 0; i < info->geometryCount; ++i) {
count += ranges[i].primitiveCount;
}
return count;
}
static void
compute_bounds(const char *base_ptr, uint32_t node_id, float *bounds)
{
for (unsigned i = 0; i < 3; ++i)
bounds[i] = INFINITY;
for (unsigned i = 0; i < 3; ++i)
bounds[3 + i] = -INFINITY;
switch (node_id & 7) {
case 0: {
const struct radv_bvh_triangle_node *node = (const void*)(base_ptr + (node_id / 8 * 64));
for (unsigned v = 0; v < 3; ++v) {
for (unsigned j = 0; j < 3; ++j) {
bounds[j] = MIN2(bounds[j], node->coords[v][j]);
bounds[3 + j] = MAX2(bounds[3 + j], node->coords[v][j]);
}
}
break;
}
case 5: {
const struct radv_bvh_box32_node *node = (const void*)(base_ptr + (node_id / 8 * 64));
for (unsigned c2 = 0; c2 < 4; ++c2) {
if (isnan(node->coords[c2][0][0]))
continue;
for (unsigned j = 0; j < 3; ++j) {
bounds[j] = MIN2(bounds[j], node->coords[c2][0][j]);
bounds[3 + j] = MAX2(bounds[3 + j], node->coords[c2][1][j]);
}
}
break;
}
case 6: {
const struct radv_bvh_instance_node *node = (const void*)(base_ptr + (node_id / 8 * 64));
for (unsigned j = 0; j < 3; ++j) {
bounds[j] = MIN2(bounds[j], node->aabb[0][j]);
bounds[3 + j] = MAX2(bounds[3 + j], node->aabb[1][j]);
}
break;
}
case 7: {
const struct radv_bvh_aabb_node *node = (const void*)(base_ptr + (node_id / 8 * 64));
for (unsigned j = 0; j < 3; ++j) {
bounds[j] = MIN2(bounds[j], node->aabb[0][j]);
bounds[3 + j] = MAX2(bounds[3 + j], node->aabb[1][j]);
}
break;
}
}
}
struct bvh_opt_entry {
uint64_t key;
uint32_t node_id;
};
static int
bvh_opt_compare(const void *_a, const void *_b)
{
const struct bvh_opt_entry *a = _a;
const struct bvh_opt_entry *b = _b;
if (a->key < b->key)
return -1;
if (a->key > b->key)
return 1;
if (a->node_id < b->node_id)
return -1;
if (a->node_id > b->node_id)
return 1;
return 0;
}
static void
optimize_bvh(const char *base_ptr, uint32_t *node_ids, uint32_t node_count)
{
if (node_count == 0)
return;
float bounds[6];
for (unsigned i = 0; i < 3; ++i)
bounds[i] = INFINITY;
for (unsigned i = 0; i < 3; ++i)
bounds[3 + i] = -INFINITY;
for (uint32_t i = 0; i < node_count; ++i) {
float node_bounds[6];
compute_bounds(base_ptr, node_ids[i], node_bounds);
for (unsigned j = 0; j < 3; ++j)
bounds[j] = MIN2(bounds[j], node_bounds[j]);
for (unsigned j = 0; j < 3; ++j)
bounds[3 + j] = MAX2(bounds[3 + j], node_bounds[3 + j]);
}
struct bvh_opt_entry *entries = calloc(node_count, sizeof(struct bvh_opt_entry));
if (!entries)
return;
for (uint32_t i = 0; i < node_count; ++i) {
float node_bounds[6];
compute_bounds(base_ptr, node_ids[i], node_bounds);
float node_coords[3];
for (unsigned j = 0; j < 3; ++j)
node_coords[j] = (node_bounds[j] + node_bounds[3 + j]) * 0.5;
int32_t coords[3];
for (unsigned j = 0; j < 3; ++j)
coords[j] = MAX2(
MIN2((int32_t)((node_coords[j] - bounds[j]) / (bounds[3 + j] - bounds[j]) * (1 << 21)),
(1 << 21) - 1),
0);
uint64_t key = 0;
for (unsigned j = 0; j < 21; ++j)
for (unsigned k = 0; k < 3; ++k)
key |= (uint64_t)((coords[k] >> j) & 1) << (j * 3 + k);
entries[i].key = key;
entries[i].node_id = node_ids[i];
}
qsort(entries, node_count, sizeof(entries[0]), bvh_opt_compare);
for (unsigned i = 0; i < node_count; ++i)
node_ids[i] = entries[i].node_id;
free(entries);
}
static VkResult
build_bvh(struct radv_device *device, const VkAccelerationStructureBuildGeometryInfoKHR *info,
const VkAccelerationStructureBuildRangeInfoKHR *ranges)
{
RADV_FROM_HANDLE(radv_acceleration_structure, accel, info->dstAccelerationStructure);
VkResult result = VK_SUCCESS;
uint32_t *scratch[2];
scratch[0] = info->scratchData.hostAddress;
scratch[1] = scratch[0] + leaf_node_count(info, ranges);
char *base_ptr = (char*)device->ws->buffer_map(accel->bo);
if (!base_ptr)
return vk_error(device, VK_ERROR_OUT_OF_HOST_MEMORY);
base_ptr = base_ptr + accel->mem_offset;
struct radv_accel_struct_header *header = (void*)base_ptr;
void *first_node_ptr = (char *)base_ptr + ALIGN(sizeof(*header), 64);
struct radv_bvh_build_ctx ctx = {.write_scratch = scratch[0],
.base = base_ptr,
.curr_ptr = (char *)first_node_ptr + 128};
uint64_t instance_offset = (const char *)ctx.curr_ptr - (const char *)base_ptr;
uint64_t instance_count = 0;
/* This initializes the leaf nodes of the BVH all at the same level. */
for (int inst = 1; inst >= 0; --inst) {
for (uint32_t i = 0; i < info->geometryCount; ++i) {
const VkAccelerationStructureGeometryKHR *geom =
info->pGeometries ? &info->pGeometries[i] : info->ppGeometries[i];
if ((inst && geom->geometryType != VK_GEOMETRY_TYPE_INSTANCES_KHR) ||
(!inst && geom->geometryType == VK_GEOMETRY_TYPE_INSTANCES_KHR))
continue;
switch (geom->geometryType) {
case VK_GEOMETRY_TYPE_TRIANGLES_KHR:
build_triangles(&ctx, geom, ranges + i, i);
break;
case VK_GEOMETRY_TYPE_AABBS_KHR:
build_aabbs(&ctx, geom, ranges + i, i);
break;
case VK_GEOMETRY_TYPE_INSTANCES_KHR: {
result = build_instances(device, &ctx, geom, ranges + i);
if (result != VK_SUCCESS)
goto fail;
instance_count += ranges[i].primitiveCount;
break;
}
case VK_GEOMETRY_TYPE_MAX_ENUM_KHR:
unreachable("VK_GEOMETRY_TYPE_MAX_ENUM_KHR unhandled");
}
}
}
uint32_t node_counts[2] = {ctx.write_scratch - scratch[0], 0};
optimize_bvh(base_ptr, scratch[0], node_counts[0]);
unsigned d;
/*
* This is the most naive BVH building algorithm I could think of:
* just iteratively builds each level from bottom to top with
* the children of each node being in-order and tightly packed.
*
* Is probably terrible for traversal but should be easy to build an
* equivalent GPU version.
*/
for (d = 0; node_counts[d & 1] > 1 || d == 0; ++d) {
uint32_t child_count = node_counts[d & 1];
const uint32_t *children = scratch[d & 1];
uint32_t *dst_ids = scratch[(d & 1) ^ 1];
unsigned dst_count;
unsigned child_idx = 0;
for (dst_count = 0; child_idx < MAX2(1, child_count); ++dst_count, child_idx += 4) {
unsigned local_child_count = MIN2(4, child_count - child_idx);
uint32_t child_ids[4];
float bounds[4][6];
for (unsigned c = 0; c < local_child_count; ++c) {
uint32_t id = children[child_idx + c];
child_ids[c] = id;
compute_bounds(base_ptr, id, bounds[c]);
}
struct radv_bvh_box32_node *node;
/* Put the root node at base_ptr so the id = 0, which allows some
* traversal optimizations. */
if (child_idx == 0 && local_child_count == child_count) {
node = first_node_ptr;
header->root_node_offset = ((char *)first_node_ptr - (char *)base_ptr) / 64 * 8 + 5;
} else {
uint32_t dst_id = (ctx.curr_ptr - base_ptr) / 64;
dst_ids[dst_count] = dst_id * 8 + 5;
node = (void*)ctx.curr_ptr;
ctx.curr_ptr += 128;
}
for (unsigned c = 0; c < local_child_count; ++c) {
node->children[c] = child_ids[c];
for (unsigned i = 0; i < 2; ++i)
for (unsigned j = 0; j < 3; ++j)
node->coords[c][i][j] = bounds[c][i * 3 + j];
}
for (unsigned c = local_child_count; c < 4; ++c) {
for (unsigned i = 0; i < 2; ++i)
for (unsigned j = 0; j < 3; ++j)
node->coords[c][i][j] = NAN;
}
}
node_counts[(d & 1) ^ 1] = dst_count;
}
compute_bounds(base_ptr, header->root_node_offset, &header->aabb[0][0]);
header->instance_offset = instance_offset;
header->instance_count = instance_count;
header->compacted_size = (char *)ctx.curr_ptr - base_ptr;
/* 16 bytes per invocation, 64 invocations per workgroup */
header->copy_dispatch_size[0] = DIV_ROUND_UP(header->compacted_size, 16 * 64);
header->copy_dispatch_size[1] = 1;
header->copy_dispatch_size[2] = 1;
header->serialization_size =
header->compacted_size + align(sizeof(struct radv_accel_struct_serialization_header) +
sizeof(uint64_t) * header->instance_count,
128);
fail:
device->ws->buffer_unmap(accel->bo);
return result;
}
VKAPI_ATTR VkResult VKAPI_CALL
radv_BuildAccelerationStructuresKHR(
VkDevice _device, VkDeferredOperationKHR deferredOperation, uint32_t infoCount,
const VkAccelerationStructureBuildGeometryInfoKHR *pInfos,
const VkAccelerationStructureBuildRangeInfoKHR *const *ppBuildRangeInfos)
{
RADV_FROM_HANDLE(radv_device, device, _device);
VkResult result = VK_SUCCESS;
for (uint32_t i = 0; i < infoCount; ++i) {
result = build_bvh(device, pInfos + i, ppBuildRangeInfos[i]);
if (result != VK_SUCCESS)
break;
}
return result;
}
VKAPI_ATTR VkResult VKAPI_CALL
radv_CopyAccelerationStructureKHR(VkDevice _device, VkDeferredOperationKHR deferredOperation,
const VkCopyAccelerationStructureInfoKHR *pInfo)
{
RADV_FROM_HANDLE(radv_device, device, _device);
RADV_FROM_HANDLE(radv_acceleration_structure, src_struct, pInfo->src);
RADV_FROM_HANDLE(radv_acceleration_structure, dst_struct, pInfo->dst);
char *src_ptr = (char *)device->ws->buffer_map(src_struct->bo);
if (!src_ptr)
return VK_ERROR_OUT_OF_HOST_MEMORY;
char *dst_ptr = (char *)device->ws->buffer_map(dst_struct->bo);
if (!dst_ptr) {
device->ws->buffer_unmap(src_struct->bo);
return VK_ERROR_OUT_OF_HOST_MEMORY;
}
src_ptr += src_struct->mem_offset;
dst_ptr += dst_struct->mem_offset;
const struct radv_accel_struct_header *header = (const void *)src_ptr;
memcpy(dst_ptr, src_ptr, header->compacted_size);
device->ws->buffer_unmap(src_struct->bo);
device->ws->buffer_unmap(dst_struct->bo);
return VK_SUCCESS;
}
static nir_ssa_def *
get_indices(nir_builder *b, nir_ssa_def *addr, nir_ssa_def *type, nir_ssa_def *id)
{
const struct glsl_type *uvec3_type = glsl_vector_type(GLSL_TYPE_UINT, 3);
nir_variable *result =
nir_variable_create(b->shader, nir_var_shader_temp, uvec3_type, "indices");
nir_push_if(b, nir_ult(b, type, nir_imm_int(b, 2)));
nir_push_if(b, nir_ieq(b, type, nir_imm_int(b, VK_INDEX_TYPE_UINT16)));
{
nir_ssa_def *index_id = nir_umul24(b, id, nir_imm_int(b, 6));
nir_ssa_def *indices[3];
for (unsigned i = 0; i < 3; ++i) {
indices[i] = nir_build_load_global(
b, 1, 16,
nir_iadd(b, addr, nir_u2u64(b, nir_iadd(b, index_id, nir_imm_int(b, 2 * i)))));
}
nir_store_var(b, result, nir_u2u32(b, nir_vec(b, indices, 3)), 7);
}
nir_push_else(b, NULL);
{
nir_ssa_def *index_id = nir_umul24(b, id, nir_imm_int(b, 12));
nir_ssa_def *indices =
nir_build_load_global(b, 3, 32, nir_iadd(b, addr, nir_u2u64(b, index_id)));
nir_store_var(b, result, indices, 7);
}
nir_pop_if(b, NULL);
nir_push_else(b, NULL);
{
nir_ssa_def *index_id = nir_umul24(b, id, nir_imm_int(b, 3));
nir_ssa_def *indices[] = {
index_id,
nir_iadd(b, index_id, nir_imm_int(b, 1)),
nir_iadd(b, index_id, nir_imm_int(b, 2)),
};
nir_push_if(b, nir_ieq(b, type, nir_imm_int(b, VK_INDEX_TYPE_NONE_KHR)));
{
nir_store_var(b, result, nir_vec(b, indices, 3), 7);
}
nir_push_else(b, NULL);
{
for (unsigned i = 0; i < 3; ++i) {
indices[i] =
nir_build_load_global(b, 1, 8, nir_iadd(b, addr, nir_u2u64(b, indices[i])));
}
nir_store_var(b, result, nir_u2u32(b, nir_vec(b, indices, 3)), 7);
}
nir_pop_if(b, NULL);
}
nir_pop_if(b, NULL);
return nir_load_var(b, result);
}
static void
get_vertices(nir_builder *b, nir_ssa_def *addresses, nir_ssa_def *format, nir_ssa_def *positions[3])
{
const struct glsl_type *vec3_type = glsl_vector_type(GLSL_TYPE_FLOAT, 3);
nir_variable *results[3] = {
nir_variable_create(b->shader, nir_var_shader_temp, vec3_type, "vertex0"),
nir_variable_create(b->shader, nir_var_shader_temp, vec3_type, "vertex1"),
nir_variable_create(b->shader, nir_var_shader_temp, vec3_type, "vertex2")};
VkFormat formats[] = {
VK_FORMAT_R32G32B32_SFLOAT, VK_FORMAT_R32G32B32A32_SFLOAT, VK_FORMAT_R16G16B16_SFLOAT,
VK_FORMAT_R16G16B16A16_SFLOAT, VK_FORMAT_R16G16_SFLOAT, VK_FORMAT_R32G32_SFLOAT,
VK_FORMAT_R16G16_SNORM, VK_FORMAT_R16G16B16A16_SNORM, VK_FORMAT_R16G16B16A16_UNORM,
};
for (unsigned f = 0; f < ARRAY_SIZE(formats); ++f) {
if (f + 1 < ARRAY_SIZE(formats))
nir_push_if(b, nir_ieq(b, format, nir_imm_int(b, formats[f])));
for (unsigned i = 0; i < 3; ++i) {
switch (formats[f]) {
case VK_FORMAT_R32G32B32_SFLOAT:
case VK_FORMAT_R32G32B32A32_SFLOAT:
nir_store_var(b, results[i],
nir_build_load_global(b, 3, 32, nir_channel(b, addresses, i)), 7);
break;
case VK_FORMAT_R32G32_SFLOAT:
case VK_FORMAT_R16G16_SFLOAT:
case VK_FORMAT_R16G16B16_SFLOAT:
case VK_FORMAT_R16G16B16A16_SFLOAT:
case VK_FORMAT_R16G16_SNORM:
case VK_FORMAT_R16G16B16A16_SNORM:
case VK_FORMAT_R16G16B16A16_UNORM: {
unsigned components = MIN2(3, vk_format_get_nr_components(formats[f]));
unsigned comp_bits =
vk_format_get_blocksizebits(formats[f]) / vk_format_get_nr_components(formats[f]);
unsigned comp_bytes = comp_bits / 8;
nir_ssa_def *values[3];
nir_ssa_def *addr = nir_channel(b, addresses, i);
for (unsigned j = 0; j < components; ++j)
values[j] = nir_build_load_global(
b, 1, comp_bits, nir_iadd(b, addr, nir_imm_int64(b, j * comp_bytes)));
for (unsigned j = components; j < 3; ++j)
values[j] = nir_imm_intN_t(b, 0, comp_bits);
nir_ssa_def *vec;
if (util_format_is_snorm(vk_format_to_pipe_format(formats[f]))) {
for (unsigned j = 0; j < 3; ++j) {
values[j] = nir_fdiv(b, nir_i2f32(b, values[j]),
nir_imm_float(b, (1u << (comp_bits - 1)) - 1));
values[j] = nir_fmax(b, values[j], nir_imm_float(b, -1.0));
}
vec = nir_vec(b, values, 3);
} else if (util_format_is_unorm(vk_format_to_pipe_format(formats[f]))) {
for (unsigned j = 0; j < 3; ++j) {
values[j] =
nir_fdiv(b, nir_u2f32(b, values[j]), nir_imm_float(b, (1u << comp_bits) - 1));
values[j] = nir_fmin(b, values[j], nir_imm_float(b, 1.0));
}
vec = nir_vec(b, values, 3);
} else if (comp_bits == 16)
vec = nir_f2f32(b, nir_vec(b, values, 3));
else
vec = nir_vec(b, values, 3);
nir_store_var(b, results[i], vec, 7);
break;
}
default:
unreachable("Unhandled format");
}
}
if (f + 1 < ARRAY_SIZE(formats))
nir_push_else(b, NULL);
}
for (unsigned f = 1; f < ARRAY_SIZE(formats); ++f) {
nir_pop_if(b, NULL);
}
for (unsigned i = 0; i < 3; ++i)
positions[i] = nir_load_var(b, results[i]);
}
struct build_primitive_constants {
uint64_t node_dst_addr;
uint64_t scratch_addr;
uint32_t dst_offset;
uint32_t dst_scratch_offset;
uint32_t geometry_type;
uint32_t geometry_id;
union {
struct {
uint64_t vertex_addr;
uint64_t index_addr;
uint64_t transform_addr;
uint32_t vertex_stride;
uint32_t vertex_format;
uint32_t index_format;
};
struct {
uint64_t instance_data;
uint32_t array_of_pointers;
};
struct {
uint64_t aabb_addr;
uint32_t aabb_stride;
};
};
};
struct build_internal_constants {
uint64_t node_dst_addr;
uint64_t scratch_addr;
uint32_t dst_offset;
uint32_t dst_scratch_offset;
uint32_t src_scratch_offset;
uint32_t fill_header;
};
/* This inverts a 3x3 matrix using cofactors, as in e.g.
* https://www.mathsisfun.com/algebra/matrix-inverse-minors-cofactors-adjugate.html */
static void
nir_invert_3x3(nir_builder *b, nir_ssa_def *in[3][3], nir_ssa_def *out[3][3])
{
nir_ssa_def *cofactors[3][3];
for (unsigned i = 0; i < 3; ++i) {
for (unsigned j = 0; j < 3; ++j) {
cofactors[i][j] =
nir_fsub(b, nir_fmul(b, in[(i + 1) % 3][(j + 1) % 3], in[(i + 2) % 3][(j + 2) % 3]),
nir_fmul(b, in[(i + 1) % 3][(j + 2) % 3], in[(i + 2) % 3][(j + 1) % 3]));
}
}
nir_ssa_def *det = NULL;
for (unsigned i = 0; i < 3; ++i) {
nir_ssa_def *det_part = nir_fmul(b, in[0][i], cofactors[0][i]);
det = det ? nir_fadd(b, det, det_part) : det_part;
}
nir_ssa_def *det_inv = nir_frcp(b, det);
for (unsigned i = 0; i < 3; ++i) {
for (unsigned j = 0; j < 3; ++j) {
out[i][j] = nir_fmul(b, cofactors[j][i], det_inv);
}
}
}
static nir_shader *
build_leaf_shader(struct radv_device *dev)
{
const struct glsl_type *vec3_type = glsl_vector_type(GLSL_TYPE_FLOAT, 3);
nir_builder b = radv_meta_init_shader(MESA_SHADER_COMPUTE, "accel_build_leaf_shader");
b.shader->info.workgroup_size[0] = 64;
nir_ssa_def *pconst0 =
nir_load_push_constant(&b, 4, 32, nir_imm_int(&b, 0), .base = 0, .range = 16);
nir_ssa_def *pconst1 =
nir_load_push_constant(&b, 4, 32, nir_imm_int(&b, 0), .base = 16, .range = 16);
nir_ssa_def *pconst2 =
nir_load_push_constant(&b, 4, 32, nir_imm_int(&b, 0), .base = 32, .range = 16);
nir_ssa_def *pconst3 =
nir_load_push_constant(&b, 4, 32, nir_imm_int(&b, 0), .base = 48, .range = 16);
nir_ssa_def *pconst4 =
nir_load_push_constant(&b, 1, 32, nir_imm_int(&b, 0), .base = 64, .range = 4);
nir_ssa_def *geom_type = nir_channel(&b, pconst1, 2);
nir_ssa_def *node_dst_addr = nir_pack_64_2x32(&b, nir_channels(&b, pconst0, 3));
nir_ssa_def *scratch_addr = nir_pack_64_2x32(&b, nir_channels(&b, pconst0, 12));
nir_ssa_def *node_dst_offset = nir_channel(&b, pconst1, 0);
nir_ssa_def *scratch_offset = nir_channel(&b, pconst1, 1);
nir_ssa_def *geometry_id = nir_channel(&b, pconst1, 3);
nir_ssa_def *global_id =
nir_iadd(&b,
nir_umul24(&b, nir_channels(&b, nir_load_workgroup_id(&b, 32), 1),
nir_imm_int(&b, b.shader->info.workgroup_size[0])),
nir_channels(&b, nir_load_local_invocation_id(&b), 1));
scratch_addr = nir_iadd(
&b, scratch_addr,
nir_u2u64(&b, nir_iadd(&b, scratch_offset, nir_umul24(&b, global_id, nir_imm_int(&b, 4)))));
nir_push_if(&b, nir_ieq(&b, geom_type, nir_imm_int(&b, VK_GEOMETRY_TYPE_TRIANGLES_KHR)));
{ /* Triangles */
nir_ssa_def *vertex_addr = nir_pack_64_2x32(&b, nir_channels(&b, pconst2, 3));
nir_ssa_def *index_addr = nir_pack_64_2x32(&b, nir_channels(&b, pconst2, 12));
nir_ssa_def *transform_addr = nir_pack_64_2x32(&b, nir_channels(&b, pconst3, 3));
nir_ssa_def *vertex_stride = nir_channel(&b, pconst3, 2);
nir_ssa_def *vertex_format = nir_channel(&b, pconst3, 3);
nir_ssa_def *index_format = nir_channel(&b, pconst4, 0);
unsigned repl_swizzle[4] = {0, 0, 0, 0};
nir_ssa_def *node_offset =
nir_iadd(&b, node_dst_offset, nir_umul24(&b, global_id, nir_imm_int(&b, 64)));
nir_ssa_def *triangle_node_dst_addr = nir_iadd(&b, node_dst_addr, nir_u2u64(&b, node_offset));
nir_ssa_def *indices = get_indices(&b, index_addr, index_format, global_id);
nir_ssa_def *vertex_addresses = nir_iadd(
&b, nir_u2u64(&b, nir_imul(&b, indices, nir_swizzle(&b, vertex_stride, repl_swizzle, 3))),
nir_swizzle(&b, vertex_addr, repl_swizzle, 3));
nir_ssa_def *positions[3];
get_vertices(&b, vertex_addresses, vertex_format, positions);
nir_ssa_def *node_data[16];
memset(node_data, 0, sizeof(node_data));
nir_variable *transform[] = {
nir_variable_create(b.shader, nir_var_shader_temp, glsl_vec4_type(), "transform0"),
nir_variable_create(b.shader, nir_var_shader_temp, glsl_vec4_type(), "transform1"),
nir_variable_create(b.shader, nir_var_shader_temp, glsl_vec4_type(), "transform2"),
};
nir_store_var(&b, transform[0], nir_imm_vec4(&b, 1.0, 0.0, 0.0, 0.0), 0xf);
nir_store_var(&b, transform[1], nir_imm_vec4(&b, 0.0, 1.0, 0.0, 0.0), 0xf);
nir_store_var(&b, transform[2], nir_imm_vec4(&b, 0.0, 0.0, 1.0, 0.0), 0xf);
nir_push_if(&b, nir_ine(&b, transform_addr, nir_imm_int64(&b, 0)));
nir_store_var(
&b, transform[0],
nir_build_load_global(&b, 4, 32, nir_iadd(&b, transform_addr, nir_imm_int64(&b, 0))), 0xf);
nir_store_var(
&b, transform[1],
nir_build_load_global(&b, 4, 32, nir_iadd(&b, transform_addr, nir_imm_int64(&b, 16))),
0xf);
nir_store_var(
&b, transform[2],
nir_build_load_global(&b, 4, 32, nir_iadd(&b, transform_addr, nir_imm_int64(&b, 32))),
0xf);
nir_pop_if(&b, NULL);
for (unsigned i = 0; i < 3; ++i)
for (unsigned j = 0; j < 3; ++j)
node_data[i * 3 + j] = nir_fdph(&b, positions[i], nir_load_var(&b, transform[j]));
node_data[12] = global_id;
node_data[13] = geometry_id;
node_data[15] = nir_imm_int(&b, 9);
for (unsigned i = 0; i < ARRAY_SIZE(node_data); ++i)
if (!node_data[i])
node_data[i] = nir_imm_int(&b, 0);
for (unsigned i = 0; i < 4; ++i) {
nir_build_store_global(&b, nir_vec(&b, node_data + i * 4, 4),
nir_iadd(&b, triangle_node_dst_addr, nir_imm_int64(&b, i * 16)),
.align_mul = 16);
}
nir_ssa_def *node_id = nir_ushr(&b, node_offset, nir_imm_int(&b, 3));
nir_build_store_global(&b, node_id, scratch_addr);
}
nir_push_else(&b, NULL);
nir_push_if(&b, nir_ieq(&b, geom_type, nir_imm_int(&b, VK_GEOMETRY_TYPE_AABBS_KHR)));
{ /* AABBs */
nir_ssa_def *aabb_addr = nir_pack_64_2x32(&b, nir_channels(&b, pconst2, 3));
nir_ssa_def *aabb_stride = nir_channel(&b, pconst2, 2);
nir_ssa_def *node_offset =
nir_iadd(&b, node_dst_offset, nir_umul24(&b, global_id, nir_imm_int(&b, 64)));
nir_ssa_def *aabb_node_dst_addr = nir_iadd(&b, node_dst_addr, nir_u2u64(&b, node_offset));
nir_ssa_def *node_id =
nir_iadd(&b, nir_ushr(&b, node_offset, nir_imm_int(&b, 3)), nir_imm_int(&b, 7));
nir_build_store_global(&b, node_id, scratch_addr);
aabb_addr = nir_iadd(&b, aabb_addr, nir_u2u64(&b, nir_imul(&b, aabb_stride, global_id)));
nir_ssa_def *min_bound =
nir_build_load_global(&b, 3, 32, nir_iadd(&b, aabb_addr, nir_imm_int64(&b, 0)));
nir_ssa_def *max_bound =
nir_build_load_global(&b, 3, 32, nir_iadd(&b, aabb_addr, nir_imm_int64(&b, 12)));
nir_ssa_def *values[] = {nir_channel(&b, min_bound, 0),
nir_channel(&b, min_bound, 1),
nir_channel(&b, min_bound, 2),
nir_channel(&b, max_bound, 0),
nir_channel(&b, max_bound, 1),
nir_channel(&b, max_bound, 2),
global_id,
geometry_id};
nir_build_store_global(&b, nir_vec(&b, values + 0, 4),
nir_iadd(&b, aabb_node_dst_addr, nir_imm_int64(&b, 0)),
.align_mul = 16);
nir_build_store_global(&b, nir_vec(&b, values + 4, 4),
nir_iadd(&b, aabb_node_dst_addr, nir_imm_int64(&b, 16)),
.align_mul = 16);
}
nir_push_else(&b, NULL);
{ /* Instances */
nir_variable *instance_addr_var =
nir_variable_create(b.shader, nir_var_shader_temp, glsl_uint64_t_type(), "instance_addr");
nir_push_if(&b, nir_ine(&b, nir_channel(&b, pconst2, 2), nir_imm_int(&b, 0)));
{
nir_ssa_def *ptr = nir_iadd(&b, nir_pack_64_2x32(&b, nir_channels(&b, pconst2, 3)),
nir_u2u64(&b, nir_imul(&b, global_id, nir_imm_int(&b, 8))));
nir_ssa_def *addr =
nir_pack_64_2x32(&b, nir_build_load_global(&b, 2, 32, ptr, .align_mul = 8));
nir_store_var(&b, instance_addr_var, addr, 1);
}
nir_push_else(&b, NULL);
{
nir_ssa_def *addr = nir_iadd(&b, nir_pack_64_2x32(&b, nir_channels(&b, pconst2, 3)),
nir_u2u64(&b, nir_imul(&b, global_id, nir_imm_int(&b, 64))));
nir_store_var(&b, instance_addr_var, addr, 1);
}
nir_pop_if(&b, NULL);
nir_ssa_def *instance_addr = nir_load_var(&b, instance_addr_var);
nir_ssa_def *inst_transform[] = {
nir_build_load_global(&b, 4, 32, nir_iadd(&b, instance_addr, nir_imm_int64(&b, 0))),
nir_build_load_global(&b, 4, 32, nir_iadd(&b, instance_addr, nir_imm_int64(&b, 16))),
nir_build_load_global(&b, 4, 32, nir_iadd(&b, instance_addr, nir_imm_int64(&b, 32)))};
nir_ssa_def *inst3 =
nir_build_load_global(&b, 4, 32, nir_iadd(&b, instance_addr, nir_imm_int64(&b, 48)));
nir_ssa_def *node_offset =
nir_iadd(&b, node_dst_offset, nir_umul24(&b, global_id, nir_imm_int(&b, 128)));
node_dst_addr = nir_iadd(&b, node_dst_addr, nir_u2u64(&b, node_offset));
nir_ssa_def *node_id =
nir_iadd(&b, nir_ushr(&b, node_offset, nir_imm_int(&b, 3)), nir_imm_int(&b, 6));
nir_build_store_global(&b, node_id, scratch_addr);
nir_variable *bounds[2] = {
nir_variable_create(b.shader, nir_var_shader_temp, vec3_type, "min_bound"),
nir_variable_create(b.shader, nir_var_shader_temp, vec3_type, "max_bound"),
};
nir_store_var(&b, bounds[0], nir_channels(&b, nir_imm_vec4(&b, NAN, NAN, NAN, NAN), 7), 7);
nir_store_var(&b, bounds[1], nir_channels(&b, nir_imm_vec4(&b, NAN, NAN, NAN, NAN), 7), 7);
nir_ssa_def *header_addr = nir_pack_64_2x32(&b, nir_channels(&b, inst3, 12));
nir_push_if(&b, nir_ine(&b, header_addr, nir_imm_int64(&b, 0)));
nir_ssa_def *header_root_offset =
nir_build_load_global(&b, 1, 32, nir_iadd(&b, header_addr, nir_imm_int64(&b, 0)));
nir_ssa_def *header_min =
nir_build_load_global(&b, 3, 32, nir_iadd(&b, header_addr, nir_imm_int64(&b, 8)));
nir_ssa_def *header_max =
nir_build_load_global(&b, 3, 32, nir_iadd(&b, header_addr, nir_imm_int64(&b, 20)));
nir_ssa_def *bound_defs[2][3];
for (unsigned i = 0; i < 3; ++i) {
bound_defs[0][i] = bound_defs[1][i] = nir_channel(&b, inst_transform[i], 3);
nir_ssa_def *mul_a = nir_fmul(&b, nir_channels(&b, inst_transform[i], 7), header_min);
nir_ssa_def *mul_b = nir_fmul(&b, nir_channels(&b, inst_transform[i], 7), header_max);
nir_ssa_def *mi = nir_fmin(&b, mul_a, mul_b);
nir_ssa_def *ma = nir_fmax(&b, mul_a, mul_b);
for (unsigned j = 0; j < 3; ++j) {
bound_defs[0][i] = nir_fadd(&b, bound_defs[0][i], nir_channel(&b, mi, j));
bound_defs[1][i] = nir_fadd(&b, bound_defs[1][i], nir_channel(&b, ma, j));
}
}
nir_store_var(&b, bounds[0], nir_vec(&b, bound_defs[0], 3), 7);
nir_store_var(&b, bounds[1], nir_vec(&b, bound_defs[1], 3), 7);
/* Store object to world matrix */
for (unsigned i = 0; i < 3; ++i) {
nir_ssa_def *vals[3];
for (unsigned j = 0; j < 3; ++j)
vals[j] = nir_channel(&b, inst_transform[j], i);
nir_build_store_global(&b, nir_vec(&b, vals, 3),
nir_iadd(&b, node_dst_addr, nir_imm_int64(&b, 92 + 12 * i)));
}
nir_ssa_def *m_in[3][3], *m_out[3][3], *m_vec[3][4];
for (unsigned i = 0; i < 3; ++i)
for (unsigned j = 0; j < 3; ++j)
m_in[i][j] = nir_channel(&b, inst_transform[i], j);
nir_invert_3x3(&b, m_in, m_out);
for (unsigned i = 0; i < 3; ++i) {
for (unsigned j = 0; j < 3; ++j)
m_vec[i][j] = m_out[i][j];
m_vec[i][3] = nir_channel(&b, inst_transform[i], 3);
}
for (unsigned i = 0; i < 3; ++i) {
nir_build_store_global(&b, nir_vec(&b, m_vec[i], 4),
nir_iadd(&b, node_dst_addr, nir_imm_int64(&b, 16 + 16 * i)));
}
nir_ssa_def *out0[4] = {
nir_ior(&b, nir_channel(&b, nir_unpack_64_2x32(&b, header_addr), 0), header_root_offset),
nir_channel(&b, nir_unpack_64_2x32(&b, header_addr), 1), nir_channel(&b, inst3, 0),
nir_channel(&b, inst3, 1)};
nir_build_store_global(&b, nir_vec(&b, out0, 4),
nir_iadd(&b, node_dst_addr, nir_imm_int64(&b, 0)));
nir_build_store_global(&b, global_id, nir_iadd(&b, node_dst_addr, nir_imm_int64(&b, 88)));
nir_pop_if(&b, NULL);
nir_build_store_global(&b, nir_load_var(&b, bounds[0]),
nir_iadd(&b, node_dst_addr, nir_imm_int64(&b, 64)));
nir_build_store_global(&b, nir_load_var(&b, bounds[1]),
nir_iadd(&b, node_dst_addr, nir_imm_int64(&b, 76)));
}
nir_pop_if(&b, NULL);
nir_pop_if(&b, NULL);
return b.shader;
}
static void
determine_bounds(nir_builder *b, nir_ssa_def *node_addr, nir_ssa_def *node_id,
nir_variable *bounds_vars[2])
{
nir_ssa_def *node_type = nir_iand(b, node_id, nir_imm_int(b, 7));
node_addr = nir_iadd(
b, node_addr,
nir_u2u64(b, nir_ishl(b, nir_iand(b, node_id, nir_imm_int(b, ~7u)), nir_imm_int(b, 3))));
nir_push_if(b, nir_ieq(b, node_type, nir_imm_int(b, 0)));
{
nir_ssa_def *positions[3];
for (unsigned i = 0; i < 3; ++i)
positions[i] =
nir_build_load_global(b, 3, 32, nir_iadd(b, node_addr, nir_imm_int64(b, i * 12)));
nir_ssa_def *bounds[] = {positions[0], positions[0]};
for (unsigned i = 1; i < 3; ++i) {
bounds[0] = nir_fmin(b, bounds[0], positions[i]);
bounds[1] = nir_fmax(b, bounds[1], positions[i]);
}
nir_store_var(b, bounds_vars[0], bounds[0], 7);
nir_store_var(b, bounds_vars[1], bounds[1], 7);
}
nir_push_else(b, NULL);
nir_push_if(b, nir_ieq(b, node_type, nir_imm_int(b, 5)));
{
nir_ssa_def *input_bounds[4][2];
for (unsigned i = 0; i < 4; ++i)
for (unsigned j = 0; j < 2; ++j)
input_bounds[i][j] = nir_build_load_global(
b, 3, 32, nir_iadd(b, node_addr, nir_imm_int64(b, 16 + i * 24 + j * 12)));
nir_ssa_def *bounds[] = {input_bounds[0][0], input_bounds[0][1]};
for (unsigned i = 1; i < 4; ++i) {
bounds[0] = nir_fmin(b, bounds[0], input_bounds[i][0]);
bounds[1] = nir_fmax(b, bounds[1], input_bounds[i][1]);
}
nir_store_var(b, bounds_vars[0], bounds[0], 7);
nir_store_var(b, bounds_vars[1], bounds[1], 7);
}
nir_push_else(b, NULL);
nir_push_if(b, nir_ieq(b, node_type, nir_imm_int(b, 6)));
{ /* Instances */
nir_ssa_def *bounds[2];
for (unsigned i = 0; i < 2; ++i)
bounds[i] =
nir_build_load_global(b, 3, 32, nir_iadd(b, node_addr, nir_imm_int64(b, 64 + i * 12)));
nir_store_var(b, bounds_vars[0], bounds[0], 7);
nir_store_var(b, bounds_vars[1], bounds[1], 7);
}
nir_push_else(b, NULL);
{ /* AABBs */
nir_ssa_def *bounds[2];
for (unsigned i = 0; i < 2; ++i)
bounds[i] =
nir_build_load_global(b, 3, 32, nir_iadd(b, node_addr, nir_imm_int64(b, i * 12)));
nir_store_var(b, bounds_vars[0], bounds[0], 7);
nir_store_var(b, bounds_vars[1], bounds[1], 7);
}
nir_pop_if(b, NULL);
nir_pop_if(b, NULL);
nir_pop_if(b, NULL);
}
static nir_shader *
build_internal_shader(struct radv_device *dev)
{
const struct glsl_type *vec3_type = glsl_vector_type(GLSL_TYPE_FLOAT, 3);
nir_builder b = radv_meta_init_shader(MESA_SHADER_COMPUTE, "accel_build_internal_shader");
b.shader->info.workgroup_size[0] = 64;
/*
* push constants:
* i32 x 2: node dst address
* i32 x 2: scratch address
* i32: dst offset
* i32: dst scratch offset
* i32: src scratch offset
* i32: src_node_count | (fill_header << 31)
*/
nir_ssa_def *pconst0 =
nir_load_push_constant(&b, 4, 32, nir_imm_int(&b, 0), .base = 0, .range = 16);
nir_ssa_def *pconst1 =
nir_load_push_constant(&b, 4, 32, nir_imm_int(&b, 0), .base = 16, .range = 16);
nir_ssa_def *node_addr = nir_pack_64_2x32(&b, nir_channels(&b, pconst0, 3));
nir_ssa_def *scratch_addr = nir_pack_64_2x32(&b, nir_channels(&b, pconst0, 12));
nir_ssa_def *node_dst_offset = nir_channel(&b, pconst1, 0);
nir_ssa_def *dst_scratch_offset = nir_channel(&b, pconst1, 1);
nir_ssa_def *src_scratch_offset = nir_channel(&b, pconst1, 2);
nir_ssa_def *src_node_count =
nir_iand(&b, nir_channel(&b, pconst1, 3), nir_imm_int(&b, 0x7FFFFFFFU));
nir_ssa_def *fill_header =
nir_ine(&b, nir_iand(&b, nir_channel(&b, pconst1, 3), nir_imm_int(&b, 0x80000000U)),
nir_imm_int(&b, 0));
nir_ssa_def *global_id =
nir_iadd(&b,
nir_umul24(&b, nir_channels(&b, nir_load_workgroup_id(&b, 32), 1),
nir_imm_int(&b, b.shader->info.workgroup_size[0])),
nir_channels(&b, nir_load_local_invocation_id(&b), 1));
nir_ssa_def *src_idx = nir_imul(&b, global_id, nir_imm_int(&b, 4));
nir_ssa_def *src_count = nir_umin(&b, nir_imm_int(&b, 4), nir_isub(&b, src_node_count, src_idx));
nir_ssa_def *node_offset =
nir_iadd(&b, node_dst_offset, nir_ishl(&b, global_id, nir_imm_int(&b, 7)));
nir_ssa_def *node_dst_addr = nir_iadd(&b, node_addr, nir_u2u64(&b, node_offset));
nir_ssa_def *src_nodes = nir_build_load_global(
&b, 4, 32,
nir_iadd(&b, scratch_addr,
nir_u2u64(&b, nir_iadd(&b, src_scratch_offset,
nir_ishl(&b, global_id, nir_imm_int(&b, 4))))));
nir_build_store_global(&b, src_nodes, nir_iadd(&b, node_dst_addr, nir_imm_int64(&b, 0)));
nir_ssa_def *total_bounds[2] = {
nir_channels(&b, nir_imm_vec4(&b, NAN, NAN, NAN, NAN), 7),
nir_channels(&b, nir_imm_vec4(&b, NAN, NAN, NAN, NAN), 7),
};
for (unsigned i = 0; i < 4; ++i) {
nir_variable *bounds[2] = {
nir_variable_create(b.shader, nir_var_shader_temp, vec3_type, "min_bound"),
nir_variable_create(b.shader, nir_var_shader_temp, vec3_type, "max_bound"),
};
nir_store_var(&b, bounds[0], nir_channels(&b, nir_imm_vec4(&b, NAN, NAN, NAN, NAN), 7), 7);
nir_store_var(&b, bounds[1], nir_channels(&b, nir_imm_vec4(&b, NAN, NAN, NAN, NAN), 7), 7);
nir_push_if(&b, nir_ilt(&b, nir_imm_int(&b, i), src_count));
determine_bounds(&b, node_addr, nir_channel(&b, src_nodes, i), bounds);
nir_pop_if(&b, NULL);
nir_build_store_global(&b, nir_load_var(&b, bounds[0]),
nir_iadd(&b, node_dst_addr, nir_imm_int64(&b, 16 + 24 * i)));
nir_build_store_global(&b, nir_load_var(&b, bounds[1]),
nir_iadd(&b, node_dst_addr, nir_imm_int64(&b, 28 + 24 * i)));
total_bounds[0] = nir_fmin(&b, total_bounds[0], nir_load_var(&b, bounds[0]));
total_bounds[1] = nir_fmax(&b, total_bounds[1], nir_load_var(&b, bounds[1]));
}
nir_ssa_def *node_id =
nir_iadd(&b, nir_ushr(&b, node_offset, nir_imm_int(&b, 3)), nir_imm_int(&b, 5));
nir_ssa_def *dst_scratch_addr = nir_iadd(
&b, scratch_addr,
nir_u2u64(&b, nir_iadd(&b, dst_scratch_offset, nir_ishl(&b, global_id, nir_imm_int(&b, 2)))));
nir_build_store_global(&b, node_id, dst_scratch_addr);
nir_push_if(&b, fill_header);
nir_build_store_global(&b, node_id, node_addr);
nir_build_store_global(&b, total_bounds[0], nir_iadd(&b, node_addr, nir_imm_int64(&b, 8)));
nir_build_store_global(&b, total_bounds[1], nir_iadd(&b, node_addr, nir_imm_int64(&b, 20)));
nir_pop_if(&b, NULL);
return b.shader;
}
enum copy_mode {
COPY_MODE_COPY,
COPY_MODE_SERIALIZE,
COPY_MODE_DESERIALIZE,
};
struct copy_constants {
uint64_t src_addr;
uint64_t dst_addr;
uint32_t mode;
};
static nir_shader *
build_copy_shader(struct radv_device *dev)
{
nir_builder b = radv_meta_init_shader(MESA_SHADER_COMPUTE, "accel_copy");
b.shader->info.workgroup_size[0] = 64;
nir_ssa_def *invoc_id = nir_load_local_invocation_id(&b);
nir_ssa_def *wg_id = nir_load_workgroup_id(&b, 32);
nir_ssa_def *block_size =
nir_imm_ivec4(&b, b.shader->info.workgroup_size[0], b.shader->info.workgroup_size[1],
b.shader->info.workgroup_size[2], 0);
nir_ssa_def *global_id =
nir_channel(&b, nir_iadd(&b, nir_imul(&b, wg_id, block_size), invoc_id), 0);
nir_variable *offset_var =
nir_variable_create(b.shader, nir_var_shader_temp, glsl_uint_type(), "offset");
nir_ssa_def *offset = nir_imul(&b, global_id, nir_imm_int(&b, 16));
nir_store_var(&b, offset_var, offset, 1);
nir_ssa_def *increment = nir_imul(&b, nir_channel(&b, nir_load_num_workgroups(&b, 32), 0),
nir_imm_int(&b, b.shader->info.workgroup_size[0] * 16));
nir_ssa_def *pconst0 =
nir_load_push_constant(&b, 4, 32, nir_imm_int(&b, 0), .base = 0, .range = 16);
nir_ssa_def *pconst1 =
nir_load_push_constant(&b, 1, 32, nir_imm_int(&b, 0), .base = 16, .range = 4);
nir_ssa_def *src_base_addr = nir_pack_64_2x32(&b, nir_channels(&b, pconst0, 3));
nir_ssa_def *dst_base_addr = nir_pack_64_2x32(&b, nir_channels(&b, pconst0, 0xc));
nir_ssa_def *mode = nir_channel(&b, pconst1, 0);
nir_variable *compacted_size_var =
nir_variable_create(b.shader, nir_var_shader_temp, glsl_uint64_t_type(), "compacted_size");
nir_variable *src_offset_var =
nir_variable_create(b.shader, nir_var_shader_temp, glsl_uint_type(), "src_offset");
nir_variable *dst_offset_var =
nir_variable_create(b.shader, nir_var_shader_temp, glsl_uint_type(), "dst_offset");
nir_variable *instance_offset_var =
nir_variable_create(b.shader, nir_var_shader_temp, glsl_uint_type(), "instance_offset");
nir_variable *instance_count_var =
nir_variable_create(b.shader, nir_var_shader_temp, glsl_uint_type(), "instance_count");
nir_variable *value_var =
nir_variable_create(b.shader, nir_var_shader_temp, glsl_vec4_type(), "value");
nir_push_if(&b, nir_ieq(&b, mode, nir_imm_int(&b, COPY_MODE_SERIALIZE)));
{
nir_ssa_def *instance_count = nir_build_load_global(
&b, 1, 32,
nir_iadd(&b, src_base_addr,
nir_imm_int64(&b, offsetof(struct radv_accel_struct_header, instance_count))));
nir_ssa_def *compacted_size = nir_build_load_global(
&b, 1, 64,
nir_iadd(&b, src_base_addr,
nir_imm_int64(&b, offsetof(struct radv_accel_struct_header, compacted_size))));
nir_ssa_def *serialization_size = nir_build_load_global(
&b, 1, 64,
nir_iadd(
&b, src_base_addr,
nir_imm_int64(&b, offsetof(struct radv_accel_struct_header, serialization_size))));
nir_store_var(&b, compacted_size_var, compacted_size, 1);
nir_store_var(
&b, instance_offset_var,
nir_build_load_global(&b, 1, 32,
nir_iadd(&b, src_base_addr,
nir_imm_int64(&b, offsetof(struct radv_accel_struct_header,
instance_offset)))),
1);
nir_store_var(&b, instance_count_var, instance_count, 1);
nir_ssa_def *dst_offset =
nir_iadd(&b, nir_imm_int(&b, sizeof(struct radv_accel_struct_serialization_header)),
nir_imul(&b, instance_count, nir_imm_int(&b, sizeof(uint64_t))));
nir_store_var(&b, src_offset_var, nir_imm_int(&b, 0), 1);
nir_store_var(&b, dst_offset_var, dst_offset, 1);
nir_push_if(&b, nir_ieq(&b, global_id, nir_imm_int(&b, 0)));
{
nir_build_store_global(
&b, serialization_size,
nir_iadd(&b, dst_base_addr,
nir_imm_int64(&b, offsetof(struct radv_accel_struct_serialization_header,
serialization_size))));
nir_build_store_global(
&b, compacted_size,
nir_iadd(&b, dst_base_addr,
nir_imm_int64(&b, offsetof(struct radv_accel_struct_serialization_header,
compacted_size))));
nir_build_store_global(
&b, nir_u2u64(&b, instance_count),
nir_iadd(&b, dst_base_addr,
nir_imm_int64(&b, offsetof(struct radv_accel_struct_serialization_header,
instance_count))));
}
nir_pop_if(&b, NULL);
}
nir_push_else(&b, NULL);
nir_push_if(&b, nir_ieq(&b, mode, nir_imm_int(&b, COPY_MODE_DESERIALIZE)));
{
nir_ssa_def *instance_count = nir_build_load_global(
&b, 1, 32,
nir_iadd(&b, src_base_addr,
nir_imm_int64(
&b, offsetof(struct radv_accel_struct_serialization_header, instance_count))));
nir_ssa_def *src_offset =
nir_iadd(&b, nir_imm_int(&b, sizeof(struct radv_accel_struct_serialization_header)),
nir_imul(&b, instance_count, nir_imm_int(&b, sizeof(uint64_t))));
nir_ssa_def *header_addr = nir_iadd(&b, src_base_addr, nir_u2u64(&b, src_offset));
nir_store_var(
&b, compacted_size_var,
nir_build_load_global(
&b, 1, 64,
nir_iadd(&b, header_addr,
nir_imm_int64(&b, offsetof(struct radv_accel_struct_header, compacted_size)))),
1);
nir_store_var(
&b, instance_offset_var,
nir_build_load_global(&b, 1, 32,
nir_iadd(&b, header_addr,
nir_imm_int64(&b, offsetof(struct radv_accel_struct_header,
instance_offset)))),
1);
nir_store_var(&b, instance_count_var, instance_count, 1);
nir_store_var(&b, src_offset_var, src_offset, 1);
nir_store_var(&b, dst_offset_var, nir_imm_int(&b, 0), 1);
}
nir_push_else(&b, NULL); /* COPY_MODE_COPY */
{
nir_store_var(
&b, compacted_size_var,
nir_build_load_global(
&b, 1, 64,
nir_iadd(&b, src_base_addr,
nir_imm_int64(&b, offsetof(struct radv_accel_struct_header, compacted_size)))),
1);
nir_store_var(&b, src_offset_var, nir_imm_int(&b, 0), 1);
nir_store_var(&b, dst_offset_var, nir_imm_int(&b, 0), 1);
nir_store_var(&b, instance_offset_var, nir_imm_int(&b, 0), 1);
nir_store_var(&b, instance_count_var, nir_imm_int(&b, 0), 1);
}
nir_pop_if(&b, NULL);
nir_pop_if(&b, NULL);
nir_ssa_def *instance_bound =
nir_imul(&b, nir_imm_int(&b, sizeof(struct radv_bvh_instance_node)),
nir_load_var(&b, instance_count_var));
nir_ssa_def *compacted_size = nir_build_load_global(
&b, 1, 32,
nir_iadd(&b, src_base_addr,
nir_imm_int64(&b, offsetof(struct radv_accel_struct_header, compacted_size))));
nir_push_loop(&b);
{
offset = nir_load_var(&b, offset_var);
nir_push_if(&b, nir_ilt(&b, offset, compacted_size));
{
nir_ssa_def *src_offset = nir_iadd(&b, offset, nir_load_var(&b, src_offset_var));
nir_ssa_def *dst_offset = nir_iadd(&b, offset, nir_load_var(&b, dst_offset_var));
nir_ssa_def *src_addr = nir_iadd(&b, src_base_addr, nir_u2u64(&b, src_offset));
nir_ssa_def *dst_addr = nir_iadd(&b, dst_base_addr, nir_u2u64(&b, dst_offset));
nir_ssa_def *value = nir_build_load_global(&b, 4, 32, src_addr, .align_mul = 16);
nir_store_var(&b, value_var, value, 0xf);
nir_ssa_def *instance_offset = nir_isub(&b, offset, nir_load_var(&b, instance_offset_var));
nir_ssa_def *in_instance_bound =
nir_iand(&b, nir_uge(&b, offset, nir_load_var(&b, instance_offset_var)),
nir_ult(&b, instance_offset, instance_bound));
nir_ssa_def *instance_start =
nir_ieq(&b,
nir_iand(&b, instance_offset,
nir_imm_int(&b, sizeof(struct radv_bvh_instance_node) - 1)),
nir_imm_int(&b, 0));
nir_push_if(&b, nir_iand(&b, in_instance_bound, instance_start));
{
nir_ssa_def *instance_id = nir_ushr(&b, instance_offset, nir_imm_int(&b, 7));
nir_push_if(&b, nir_ieq(&b, mode, nir_imm_int(&b, COPY_MODE_SERIALIZE)));
{
nir_ssa_def *instance_addr =
nir_imul(&b, instance_id, nir_imm_int(&b, sizeof(uint64_t)));
instance_addr =
nir_iadd(&b, instance_addr,
nir_imm_int(&b, sizeof(struct radv_accel_struct_serialization_header)));
instance_addr = nir_iadd(&b, dst_base_addr, nir_u2u64(&b, instance_addr));
nir_build_store_global(&b, nir_channels(&b, value, 3), instance_addr,
.align_mul = 8);
}
nir_push_else(&b, NULL);
{
nir_ssa_def *instance_addr =
nir_imul(&b, instance_id, nir_imm_int(&b, sizeof(uint64_t)));
instance_addr =
nir_iadd(&b, instance_addr,
nir_imm_int(&b, sizeof(struct radv_accel_struct_serialization_header)));
instance_addr = nir_iadd(&b, src_base_addr, nir_u2u64(&b, instance_addr));
nir_ssa_def *instance_value =
nir_build_load_global(&b, 2, 32, instance_addr, .align_mul = 8);
nir_ssa_def *values[] = {
nir_channel(&b, instance_value, 0),
nir_channel(&b, instance_value, 1),
nir_channel(&b, value, 2),
nir_channel(&b, value, 3),
};
nir_store_var(&b, value_var, nir_vec(&b, values, 4), 0xf);
}
nir_pop_if(&b, NULL);
}
nir_pop_if(&b, NULL);
nir_store_var(&b, offset_var, nir_iadd(&b, offset, increment), 1);
nir_build_store_global(&b, nir_load_var(&b, value_var), dst_addr, .align_mul = 16);
}
nir_push_else(&b, NULL);
{
nir_jump(&b, nir_jump_break);
}
nir_pop_if(&b, NULL);
}
nir_pop_loop(&b, NULL);
return b.shader;
}
void
radv_device_finish_accel_struct_build_state(struct radv_device *device)
{
struct radv_meta_state *state = &device->meta_state;
radv_DestroyPipeline(radv_device_to_handle(device), state->accel_struct_build.copy_pipeline,
&state->alloc);
radv_DestroyPipeline(radv_device_to_handle(device), state->accel_struct_build.internal_pipeline,
&state->alloc);
radv_DestroyPipeline(radv_device_to_handle(device), state->accel_struct_build.leaf_pipeline,
&state->alloc);
radv_DestroyPipelineLayout(radv_device_to_handle(device),
state->accel_struct_build.copy_p_layout, &state->alloc);
radv_DestroyPipelineLayout(radv_device_to_handle(device),
state->accel_struct_build.internal_p_layout, &state->alloc);
radv_DestroyPipelineLayout(radv_device_to_handle(device),
state->accel_struct_build.leaf_p_layout, &state->alloc);
}
VkResult
radv_device_init_accel_struct_build_state(struct radv_device *device)
{
VkResult result;
nir_shader *leaf_cs = build_leaf_shader(device);
nir_shader *internal_cs = build_internal_shader(device);
nir_shader *copy_cs = build_copy_shader(device);
const VkPipelineLayoutCreateInfo leaf_pl_create_info = {
.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO,
.setLayoutCount = 0,
.pushConstantRangeCount = 1,
.pPushConstantRanges = &(VkPushConstantRange){VK_SHADER_STAGE_COMPUTE_BIT, 0,
sizeof(struct build_primitive_constants)},
};
result = radv_CreatePipelineLayout(radv_device_to_handle(device), &leaf_pl_create_info,
&device->meta_state.alloc,
&device->meta_state.accel_struct_build.leaf_p_layout);
if (result != VK_SUCCESS)
goto fail;
VkPipelineShaderStageCreateInfo leaf_shader_stage = {
.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,
.stage = VK_SHADER_STAGE_COMPUTE_BIT,
.module = vk_shader_module_handle_from_nir(leaf_cs),
.pName = "main",
.pSpecializationInfo = NULL,
};
VkComputePipelineCreateInfo leaf_pipeline_info = {
.sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO,
.stage = leaf_shader_stage,
.flags = 0,
.layout = device->meta_state.accel_struct_build.leaf_p_layout,
};
result = radv_CreateComputePipelines(
radv_device_to_handle(device), radv_pipeline_cache_to_handle(&device->meta_state.cache), 1,
&leaf_pipeline_info, NULL, &device->meta_state.accel_struct_build.leaf_pipeline);
if (result != VK_SUCCESS)
goto fail;
const VkPipelineLayoutCreateInfo internal_pl_create_info = {
.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO,
.setLayoutCount = 0,
.pushConstantRangeCount = 1,
.pPushConstantRanges = &(VkPushConstantRange){VK_SHADER_STAGE_COMPUTE_BIT, 0,
sizeof(struct build_internal_constants)},
};
result = radv_CreatePipelineLayout(radv_device_to_handle(device), &internal_pl_create_info,
&device->meta_state.alloc,
&device->meta_state.accel_struct_build.internal_p_layout);
if (result != VK_SUCCESS)
goto fail;
VkPipelineShaderStageCreateInfo internal_shader_stage = {
.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,
.stage = VK_SHADER_STAGE_COMPUTE_BIT,
.module = vk_shader_module_handle_from_nir(internal_cs),
.pName = "main",
.pSpecializationInfo = NULL,
};
VkComputePipelineCreateInfo internal_pipeline_info = {
.sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO,
.stage = internal_shader_stage,
.flags = 0,
.layout = device->meta_state.accel_struct_build.internal_p_layout,
};
result = radv_CreateComputePipelines(
radv_device_to_handle(device), radv_pipeline_cache_to_handle(&device->meta_state.cache), 1,
&internal_pipeline_info, NULL, &device->meta_state.accel_struct_build.internal_pipeline);
if (result != VK_SUCCESS)
goto fail;
const VkPipelineLayoutCreateInfo copy_pl_create_info = {
.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO,
.setLayoutCount = 0,
.pushConstantRangeCount = 1,
.pPushConstantRanges =
&(VkPushConstantRange){VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(struct copy_constants)},
};
result = radv_CreatePipelineLayout(radv_device_to_handle(device), ©_pl_create_info,
&device->meta_state.alloc,
&device->meta_state.accel_struct_build.copy_p_layout);
if (result != VK_SUCCESS)
goto fail;
VkPipelineShaderStageCreateInfo copy_shader_stage = {
.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,
.stage = VK_SHADER_STAGE_COMPUTE_BIT,
.module = vk_shader_module_handle_from_nir(copy_cs),
.pName = "main",
.pSpecializationInfo = NULL,
};
VkComputePipelineCreateInfo copy_pipeline_info = {
.sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO,
.stage = copy_shader_stage,
.flags = 0,
.layout = device->meta_state.accel_struct_build.copy_p_layout,
};
result = radv_CreateComputePipelines(
radv_device_to_handle(device), radv_pipeline_cache_to_handle(&device->meta_state.cache), 1,
©_pipeline_info, NULL, &device->meta_state.accel_struct_build.copy_pipeline);
if (result != VK_SUCCESS)
goto fail;
ralloc_free(copy_cs);
ralloc_free(internal_cs);
ralloc_free(leaf_cs);
return VK_SUCCESS;
fail:
radv_device_finish_accel_struct_build_state(device);
ralloc_free(copy_cs);
ralloc_free(internal_cs);
ralloc_free(leaf_cs);
return result;
}
struct bvh_state {
uint32_t node_offset;
uint32_t node_count;
uint32_t scratch_offset;
uint32_t instance_offset;
uint32_t instance_count;
};
VKAPI_ATTR void VKAPI_CALL
radv_CmdBuildAccelerationStructuresKHR(
VkCommandBuffer commandBuffer, uint32_t infoCount,
const VkAccelerationStructureBuildGeometryInfoKHR *pInfos,
const VkAccelerationStructureBuildRangeInfoKHR *const *ppBuildRangeInfos)
{
RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer, commandBuffer);
struct radv_meta_saved_state saved_state;
radv_meta_save(
&saved_state, cmd_buffer,
RADV_META_SAVE_COMPUTE_PIPELINE | RADV_META_SAVE_DESCRIPTORS | RADV_META_SAVE_CONSTANTS);
struct bvh_state *bvh_states = calloc(infoCount, sizeof(struct bvh_state));
radv_CmdBindPipeline(radv_cmd_buffer_to_handle(cmd_buffer), VK_PIPELINE_BIND_POINT_COMPUTE,
cmd_buffer->device->meta_state.accel_struct_build.leaf_pipeline);
for (uint32_t i = 0; i < infoCount; ++i) {
RADV_FROM_HANDLE(radv_acceleration_structure, accel_struct,
pInfos[i].dstAccelerationStructure);
struct build_primitive_constants prim_consts = {
.node_dst_addr = radv_accel_struct_get_va(accel_struct),
.scratch_addr = pInfos[i].scratchData.deviceAddress,
.dst_offset = ALIGN(sizeof(struct radv_accel_struct_header), 64) + 128,
.dst_scratch_offset = 0,
};
bvh_states[i].node_offset = prim_consts.dst_offset;
bvh_states[i].instance_offset = prim_consts.dst_offset;
for (int inst = 1; inst >= 0; --inst) {
for (unsigned j = 0; j < pInfos[i].geometryCount; ++j) {
const VkAccelerationStructureGeometryKHR *geom =
pInfos[i].pGeometries ? &pInfos[i].pGeometries[j] : pInfos[i].ppGeometries[j];
if ((inst && geom->geometryType != VK_GEOMETRY_TYPE_INSTANCES_KHR) ||
(!inst && geom->geometryType == VK_GEOMETRY_TYPE_INSTANCES_KHR))
continue;
prim_consts.geometry_type = geom->geometryType;
prim_consts.geometry_id = j | (geom->flags << 28);
unsigned prim_size;
switch (geom->geometryType) {
case VK_GEOMETRY_TYPE_TRIANGLES_KHR:
prim_consts.vertex_addr =
geom->geometry.triangles.vertexData.deviceAddress +
ppBuildRangeInfos[i][j].firstVertex * geom->geometry.triangles.vertexStride +
(geom->geometry.triangles.indexType != VK_INDEX_TYPE_NONE_KHR
? ppBuildRangeInfos[i][j].primitiveOffset
: 0);
prim_consts.index_addr = geom->geometry.triangles.indexData.deviceAddress +
ppBuildRangeInfos[i][j].primitiveOffset;
prim_consts.transform_addr = geom->geometry.triangles.transformData.deviceAddress +
ppBuildRangeInfos[i][j].transformOffset;
prim_consts.vertex_stride = geom->geometry.triangles.vertexStride;
prim_consts.vertex_format = geom->geometry.triangles.vertexFormat;
prim_consts.index_format = geom->geometry.triangles.indexType;
prim_size = 64;
break;
case VK_GEOMETRY_TYPE_AABBS_KHR:
prim_consts.aabb_addr =
geom->geometry.aabbs.data.deviceAddress + ppBuildRangeInfos[i][j].primitiveOffset;
prim_consts.aabb_stride = geom->geometry.aabbs.stride;
prim_size = 64;
break;
case VK_GEOMETRY_TYPE_INSTANCES_KHR:
prim_consts.instance_data = geom->geometry.instances.data.deviceAddress;
prim_consts.array_of_pointers = geom->geometry.instances.arrayOfPointers ? 1 : 0;
prim_size = 128;
bvh_states[i].instance_count += ppBuildRangeInfos[i][j].primitiveCount;
break;
default:
unreachable("Unknown geometryType");
}
radv_CmdPushConstants(radv_cmd_buffer_to_handle(cmd_buffer),
cmd_buffer->device->meta_state.accel_struct_build.leaf_p_layout,
VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(prim_consts),
&prim_consts);
radv_unaligned_dispatch(cmd_buffer, ppBuildRangeInfos[i][j].primitiveCount, 1, 1);
prim_consts.dst_offset += prim_size * ppBuildRangeInfos[i][j].primitiveCount;
prim_consts.dst_scratch_offset += 4 * ppBuildRangeInfos[i][j].primitiveCount;
}
}
bvh_states[i].node_offset = prim_consts.dst_offset;
bvh_states[i].node_count = prim_consts.dst_scratch_offset / 4;
}
radv_CmdBindPipeline(radv_cmd_buffer_to_handle(cmd_buffer), VK_PIPELINE_BIND_POINT_COMPUTE,
cmd_buffer->device->meta_state.accel_struct_build.internal_pipeline);
bool progress = true;
for (unsigned iter = 0; progress; ++iter) {
progress = false;
for (uint32_t i = 0; i < infoCount; ++i) {
RADV_FROM_HANDLE(radv_acceleration_structure, accel_struct,
pInfos[i].dstAccelerationStructure);
if (iter && bvh_states[i].node_count == 1)
continue;
if (!progress) {
cmd_buffer->state.flush_bits |=
RADV_CMD_FLAG_CS_PARTIAL_FLUSH |
radv_src_access_flush(cmd_buffer, VK_ACCESS_2_SHADER_WRITE_BIT_KHR, NULL) |
radv_dst_access_flush(cmd_buffer,
VK_ACCESS_2_SHADER_READ_BIT_KHR | VK_ACCESS_2_SHADER_WRITE_BIT_KHR, NULL);
}
progress = true;
uint32_t dst_node_count = MAX2(1, DIV_ROUND_UP(bvh_states[i].node_count, 4));
bool final_iter = dst_node_count == 1;
uint32_t src_scratch_offset = bvh_states[i].scratch_offset;
uint32_t dst_scratch_offset = src_scratch_offset ? 0 : bvh_states[i].node_count * 4;
uint32_t dst_node_offset = bvh_states[i].node_offset;
if (final_iter)
dst_node_offset = ALIGN(sizeof(struct radv_accel_struct_header), 64);
const struct build_internal_constants consts = {
.node_dst_addr = radv_accel_struct_get_va(accel_struct),
.scratch_addr = pInfos[i].scratchData.deviceAddress,
.dst_offset = dst_node_offset,
.dst_scratch_offset = dst_scratch_offset,
.src_scratch_offset = src_scratch_offset,
.fill_header = bvh_states[i].node_count | (final_iter ? 0x80000000U : 0),
};
radv_CmdPushConstants(radv_cmd_buffer_to_handle(cmd_buffer),
cmd_buffer->device->meta_state.accel_struct_build.internal_p_layout,
VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(consts), &consts);
radv_unaligned_dispatch(cmd_buffer, dst_node_count, 1, 1);
if (!final_iter)
bvh_states[i].node_offset += dst_node_count * 128;
bvh_states[i].node_count = dst_node_count;
bvh_states[i].scratch_offset = dst_scratch_offset;
}
}
for (uint32_t i = 0; i < infoCount; ++i) {
RADV_FROM_HANDLE(radv_acceleration_structure, accel_struct,
pInfos[i].dstAccelerationStructure);
const size_t base = offsetof(struct radv_accel_struct_header, compacted_size);
struct radv_accel_struct_header header;
header.instance_offset = bvh_states[i].instance_offset;
header.instance_count = bvh_states[i].instance_count;
header.compacted_size = bvh_states[i].node_offset;
/* 16 bytes per invocation, 64 invocations per workgroup */
header.copy_dispatch_size[0] = DIV_ROUND_UP(header.compacted_size, 16 * 64);
header.copy_dispatch_size[1] = 1;
header.copy_dispatch_size[2] = 1;
header.serialization_size =
header.compacted_size + align(sizeof(struct radv_accel_struct_serialization_header) +
sizeof(uint64_t) * header.instance_count,
128);
radv_update_buffer_cp(cmd_buffer,
radv_buffer_get_va(accel_struct->bo) + accel_struct->mem_offset + base,
(const char *)&header + base, sizeof(header) - base);
}
free(bvh_states);
radv_meta_restore(&saved_state, cmd_buffer);
}
VKAPI_ATTR void VKAPI_CALL
radv_CmdCopyAccelerationStructureKHR(VkCommandBuffer commandBuffer,
const VkCopyAccelerationStructureInfoKHR *pInfo)
{
RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer, commandBuffer);
RADV_FROM_HANDLE(radv_acceleration_structure, src, pInfo->src);
RADV_FROM_HANDLE(radv_acceleration_structure, dst, pInfo->dst);
struct radv_meta_saved_state saved_state;
radv_meta_save(
&saved_state, cmd_buffer,
RADV_META_SAVE_COMPUTE_PIPELINE | RADV_META_SAVE_DESCRIPTORS | RADV_META_SAVE_CONSTANTS);
uint64_t src_addr = radv_accel_struct_get_va(src);
uint64_t dst_addr = radv_accel_struct_get_va(dst);
radv_CmdBindPipeline(radv_cmd_buffer_to_handle(cmd_buffer), VK_PIPELINE_BIND_POINT_COMPUTE,
cmd_buffer->device->meta_state.accel_struct_build.copy_pipeline);
const struct copy_constants consts = {
.src_addr = src_addr,
.dst_addr = dst_addr,
.mode = COPY_MODE_COPY,
};
radv_CmdPushConstants(radv_cmd_buffer_to_handle(cmd_buffer),
cmd_buffer->device->meta_state.accel_struct_build.copy_p_layout,
VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(consts), &consts);
radv_indirect_dispatch(cmd_buffer, src->bo,
src_addr + offsetof(struct radv_accel_struct_header, copy_dispatch_size));
radv_meta_restore(&saved_state, cmd_buffer);
}
VKAPI_ATTR void VKAPI_CALL
radv_GetDeviceAccelerationStructureCompatibilityKHR(
VkDevice _device, const VkAccelerationStructureVersionInfoKHR *pVersionInfo,
VkAccelerationStructureCompatibilityKHR *pCompatibility)
{
RADV_FROM_HANDLE(radv_device, device, _device);
uint8_t zero[VK_UUID_SIZE] = {
0,
};
bool compat =
memcmp(pVersionInfo->pVersionData, device->physical_device->driver_uuid, VK_UUID_SIZE) == 0 &&
memcmp(pVersionInfo->pVersionData + VK_UUID_SIZE, zero, VK_UUID_SIZE) == 0;
*pCompatibility = compat ? VK_ACCELERATION_STRUCTURE_COMPATIBILITY_COMPATIBLE_KHR
: VK_ACCELERATION_STRUCTURE_COMPATIBILITY_INCOMPATIBLE_KHR;
}
VKAPI_ATTR VkResult VKAPI_CALL
radv_CopyMemoryToAccelerationStructureKHR(VkDevice _device,
VkDeferredOperationKHR deferredOperation,
const VkCopyMemoryToAccelerationStructureInfoKHR *pInfo)
{
RADV_FROM_HANDLE(radv_device, device, _device);
RADV_FROM_HANDLE(radv_acceleration_structure, accel_struct, pInfo->dst);
char *base = device->ws->buffer_map(accel_struct->bo);
if (!base)
return VK_ERROR_OUT_OF_HOST_MEMORY;
base += accel_struct->mem_offset;
const struct radv_accel_struct_header *header = (const struct radv_accel_struct_header *)base;
const char *src = pInfo->src.hostAddress;
struct radv_accel_struct_serialization_header *src_header = (void *)src;
src += sizeof(*src_header) + sizeof(uint64_t) * src_header->instance_count;
memcpy(base, src, src_header->compacted_size);
for (unsigned i = 0; i < src_header->instance_count; ++i) {
uint64_t *p = (uint64_t *)(base + i * 128 + header->instance_offset);
*p = (*p & 63) | src_header->instances[i];
}
device->ws->buffer_unmap(accel_struct->bo);
return VK_SUCCESS;
}
VKAPI_ATTR VkResult VKAPI_CALL
radv_CopyAccelerationStructureToMemoryKHR(VkDevice _device,
VkDeferredOperationKHR deferredOperation,
const VkCopyAccelerationStructureToMemoryInfoKHR *pInfo)
{
RADV_FROM_HANDLE(radv_device, device, _device);
RADV_FROM_HANDLE(radv_acceleration_structure, accel_struct, pInfo->src);
const char *base = device->ws->buffer_map(accel_struct->bo);
if (!base)
return VK_ERROR_OUT_OF_HOST_MEMORY;
base += accel_struct->mem_offset;
const struct radv_accel_struct_header *header = (const struct radv_accel_struct_header *)base;
char *dst = pInfo->dst.hostAddress;
struct radv_accel_struct_serialization_header *dst_header = (void *)dst;
dst += sizeof(*dst_header) + sizeof(uint64_t) * header->instance_count;
memcpy(dst_header->driver_uuid, device->physical_device->driver_uuid, VK_UUID_SIZE);
memset(dst_header->accel_struct_compat, 0, VK_UUID_SIZE);
dst_header->serialization_size = header->serialization_size;
dst_header->compacted_size = header->compacted_size;
dst_header->instance_count = header->instance_count;
memcpy(dst, base, header->compacted_size);
for (unsigned i = 0; i < header->instance_count; ++i) {
dst_header->instances[i] =
*(const uint64_t *)(base + i * 128 + header->instance_offset) & ~63ull;
}
device->ws->buffer_unmap(accel_struct->bo);
return VK_SUCCESS;
}
VKAPI_ATTR void VKAPI_CALL
radv_CmdCopyMemoryToAccelerationStructureKHR(
VkCommandBuffer commandBuffer, const VkCopyMemoryToAccelerationStructureInfoKHR *pInfo)
{
RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer, commandBuffer);
RADV_FROM_HANDLE(radv_acceleration_structure, dst, pInfo->dst);
struct radv_meta_saved_state saved_state;
radv_meta_save(
&saved_state, cmd_buffer,
RADV_META_SAVE_COMPUTE_PIPELINE | RADV_META_SAVE_DESCRIPTORS | RADV_META_SAVE_CONSTANTS);
uint64_t dst_addr = radv_accel_struct_get_va(dst);
radv_CmdBindPipeline(radv_cmd_buffer_to_handle(cmd_buffer), VK_PIPELINE_BIND_POINT_COMPUTE,
cmd_buffer->device->meta_state.accel_struct_build.copy_pipeline);
const struct copy_constants consts = {
.src_addr = pInfo->src.deviceAddress,
.dst_addr = dst_addr,
.mode = COPY_MODE_DESERIALIZE,
};
radv_CmdPushConstants(radv_cmd_buffer_to_handle(cmd_buffer),
cmd_buffer->device->meta_state.accel_struct_build.copy_p_layout,
VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(consts), &consts);
radv_CmdDispatch(commandBuffer, 512, 1, 1);
radv_meta_restore(&saved_state, cmd_buffer);
}
VKAPI_ATTR void VKAPI_CALL
radv_CmdCopyAccelerationStructureToMemoryKHR(
VkCommandBuffer commandBuffer, const VkCopyAccelerationStructureToMemoryInfoKHR *pInfo)
{
RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer, commandBuffer);
RADV_FROM_HANDLE(radv_acceleration_structure, src, pInfo->src);
struct radv_meta_saved_state saved_state;
radv_meta_save(
&saved_state, cmd_buffer,
RADV_META_SAVE_COMPUTE_PIPELINE | RADV_META_SAVE_DESCRIPTORS | RADV_META_SAVE_CONSTANTS);
uint64_t src_addr = radv_accel_struct_get_va(src);
radv_CmdBindPipeline(radv_cmd_buffer_to_handle(cmd_buffer), VK_PIPELINE_BIND_POINT_COMPUTE,
cmd_buffer->device->meta_state.accel_struct_build.copy_pipeline);
const struct copy_constants consts = {
.src_addr = src_addr,
.dst_addr = pInfo->dst.deviceAddress,
.mode = COPY_MODE_SERIALIZE,
};
radv_CmdPushConstants(radv_cmd_buffer_to_handle(cmd_buffer),
cmd_buffer->device->meta_state.accel_struct_build.copy_p_layout,
VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(consts), &consts);
radv_indirect_dispatch(cmd_buffer, src->bo,
src_addr + offsetof(struct radv_accel_struct_header, copy_dispatch_size));
radv_meta_restore(&saved_state, cmd_buffer);
/* Set the header of the serialized data. */
uint8_t header_data[2 * VK_UUID_SIZE] = {0};
memcpy(header_data, cmd_buffer->device->physical_device->driver_uuid, VK_UUID_SIZE);
radv_update_buffer_cp(cmd_buffer, pInfo->dst.deviceAddress, header_data, sizeof(header_data));
}
| 41.922518 | 112 | 0.632228 | [
"geometry",
"object",
"transform"
] |
3955473cd6d50f882060167572618ecdfa94df8e | 3,323 | h | C | GraphicsMagick.NET/Results/TypeMetric.h | dlemstra/GraphicsMagick.NET | 332718f2315c3752eaeb84f4a6a30a553441e79e | [
"ImageMagick",
"Apache-2.0"
] | 35 | 2015-10-18T19:49:52.000Z | 2022-01-18T05:30:46.000Z | GraphicsMagick.NET/Results/TypeMetric.h | elyor0529/GraphicsMagick.NET | 332718f2315c3752eaeb84f4a6a30a553441e79e | [
"ImageMagick",
"Apache-2.0"
] | 12 | 2016-07-22T16:05:03.000Z | 2020-02-26T15:21:03.000Z | GraphicsMagick.NET/Results/TypeMetric.h | elyor0529/GraphicsMagick.NET | 332718f2315c3752eaeb84f4a6a30a553441e79e | [
"ImageMagick",
"Apache-2.0"
] | 12 | 2016-02-24T12:11:50.000Z | 2021-07-12T18:20:12.000Z | //=================================================================================================
// Copyright 2014-2015 Dirk Lemstra <https://graphicsmagick.codeplex.com/>
//
// Licensed under the ImageMagick License (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.imagemagick.org/script/license.php
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language governing permissions and
// limitations under the License.
//=================================================================================================
#pragma once
namespace GraphicsMagick
{
///=============================================================================================
///<summary>
/// Encapsulation of the ImageMagick TypeMetric object.
///</summary>
public ref class TypeMetric sealed
{
//===========================================================================================
private:
//===========================================================================================
double _Ascent;
double _Descent;
double _MaxHorizontalAdvance;
double _TextWidth;
double _TextHeight;
//===========================================================================================
internal:
//===========================================================================================
TypeMetric(Magick::TypeMetric* metrics);
//===========================================================================================
public:
///==========================================================================================
///<summary>
/// Ascent, the distance in pixels from the text baseline to the highest/upper grid coordinate
/// used to place an outline point.
///</summary>
property double Ascent
{
double get();
}
///==========================================================================================
///<summary>
/// Descent, the distance in pixels from the baseline to the lowest grid coordinate used to
/// place an outline point. Always a negative value.
///</summary>
property double Descent
{
double get();
}
///==========================================================================================
///<summary>
/// Maximum horizontal advance in pixels.
///</summary>
property double MaxHorizontalAdvance
{
double get();
}
///==========================================================================================
///<summary>
/// Text height in pixels.
///</summary>
property double TextHeight
{
double get();
}
///==========================================================================================
///<summary>
/// Text width in pixels.
///</summary>
property double TextWidth
{
double get();
}
//===========================================================================================
};
//==============================================================================================
} | 40.036145 | 100 | 0.376768 | [
"object"
] |
3958158dfbcdbc45adf117dc18a019c98446205c | 933 | h | C | Swing/Source/iOS/Swing (1.3.5)/ios/libs/core/include/objects/PTPObjectAssetPowerup.h | thatgamesguy/swing | 957452c9c37daeee7dda8a931b0ea199d7e323a6 | [
"MIT"
] | 1 | 2019-03-25T22:44:38.000Z | 2019-03-25T22:44:38.000Z | Swing/Source/iOS/Swing (1.3.5)/ios/libs/core/include/objects/PTPObjectAssetPowerup.h | thatgamesguy/swing | 957452c9c37daeee7dda8a931b0ea199d7e323a6 | [
"MIT"
] | null | null | null | Swing/Source/iOS/Swing (1.3.5)/ios/libs/core/include/objects/PTPObjectAssetPowerup.h | thatgamesguy/swing | 957452c9c37daeee7dda8a931b0ea199d7e323a6 | [
"MIT"
] | 4 | 2019-04-19T14:21:26.000Z | 2020-10-02T15:44:40.000Z | #ifndef PTPASSETPOWERUP_H
#define PTPASSETPOWERUP_H
#include "PTPObjectAsset.h"
#include "models/objects/PTModelObjectAssetPowerup.h"
#include "PTPAnimationObject.h"
class PTPObjectAssetPowerup : public PTPObjectAsset
{
public:
explicit PTPObjectAssetPowerup( PTModelObjectAsset* model);
~PTPObjectAssetPowerup();
virtual void initPhysics(b2World* world);
virtual void update(float dt);
virtual void beginContact(PTPObjectAsset *obj, b2Contact *contact );
virtual void setState( PTPObjectState s );
private:
void endAnimationDidEnd();
PTModelObjectAssetPowerup* _model;
PTPAnimationObject *_idleAnimation;
PTPAnimationObject *_startAnimation;
PTPAnimationObject *_endAnimation;
bool pRewardAnimation;
float pRewardAnimationCounter;
CCLabelBMFont* pRewardLabel;
bool _characterConstraint;
bool _screenConstarint;
float _duration;
};
#endif // PTPASSETCOIN_H
| 25.916667 | 73 | 0.771704 | [
"model"
] |
396edce1cc0434026ceda746cb784132d28e6036 | 8,750 | h | C | fkie_message_filters/include/fkie_message_filters/buffer_impl.h | fkie/message_filters | 4437729f01479c8ee7e5b40e7e868d7b219bd813 | [
"Apache-2.0"
] | 13 | 2019-01-18T14:41:46.000Z | 2022-02-04T06:47:29.000Z | fkie_message_filters/include/fkie_message_filters/buffer_impl.h | fkie/message_filters | 4437729f01479c8ee7e5b40e7e868d7b219bd813 | [
"Apache-2.0"
] | 1 | 2021-08-31T05:07:59.000Z | 2021-09-01T15:33:24.000Z | fkie_message_filters/include/fkie_message_filters/buffer_impl.h | fkie/message_filters | 4437729f01479c8ee7e5b40e7e868d7b219bd813 | [
"Apache-2.0"
] | 3 | 2019-04-30T14:05:23.000Z | 2021-06-20T10:25:34.000Z | /****************************************************************************
*
* fkie_message_filters
* Copyright © 2018-2020 Fraunhofer FKIE
* Author: Timo Röhling
*
* 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.
*
****************************************************************************/
#ifndef INCLUDE_FKIE_MESSAGE_FILTERS_BUFFER_IMPL_H_
#define INCLUDE_FKIE_MESSAGE_FILTERS_BUFFER_IMPL_H_
#include "buffer.h"
#include "helpers/tuple.h"
#include <ros/init.h>
namespace fkie_message_filters
{
template<class... Inputs>
struct Buffer<Inputs...>::Impl
{
Impl(Buffer* parent, BufferPolicy policy) noexcept
: parent_(parent), policy_(policy), epoch_(0)
{}
bool wait_for_queue_element(std::unique_lock<std::mutex>& lock) noexcept
{
#ifndef FKIE_MESSAGE_FILTERS_IGNORE_ROS_OK
while (ros::ok() && policy_ == BufferPolicy::Queue && queue_.empty())
{
cond_.wait_for(lock, std::chrono::milliseconds(100));
}
return ros::ok() && !queue_.empty();
#else
while (policy_ == BufferPolicy::Queue && queue_.empty()) cond_.wait(lock);
return !queue_.empty();
#endif
}
template<class Rep, class Period>
bool wait_for_queue_element(std::unique_lock<std::mutex>& lock, const std::chrono::duration<Rep, Period>& timeout) noexcept
{
std::chrono::system_clock::time_point deadline = std::chrono::system_clock::now() + timeout;
#ifndef FKIE_MESSAGE_FILTERS_IGNORE_ROS_OK
while (ros::ok() && policy_ == BufferPolicy::Queue && queue_.empty())
{
std::chrono::system_clock::duration remaining = deadline - std::chrono::system_clock::now();
if (remaining > std::chrono::milliseconds(100))
cond_.wait_for(lock, std::chrono::milliseconds(100));
else
cond_.wait_until(lock, deadline);
}
return ros::ok() && !queue_.empty();
#else
while (policy_ == BufferPolicy::Queue && queue_.empty()) cond_.wait_until(lock, deadline);
return !queue_.empty();
#endif
}
Buffer* parent_;
BufferPolicy policy_;
boost::circular_buffer<QueueElement> queue_;
std::mutex mutex_;
std::condition_variable cond_;
std::size_t epoch_;
};
template<class... Inputs>
class Buffer<Inputs...>::RosCB : public ros::CallbackInterface
{
public:
RosCB(const std::weak_ptr<Impl>& parent, std::size_t epoch) noexcept
: parent_(parent), epoch_(epoch) {}
CallResult call() noexcept override
{
std::shared_ptr<Impl> impl = parent_.lock();
if (impl)
{
std::unique_lock<std::mutex> lock(impl->mutex_);
if (!impl->queue_.empty() && epoch_ == impl->epoch_)
{
QueueElement e{impl->queue_.front()};
impl->queue_.pop_front();
lock.unlock();
impl->parent_->send_queue_element(e);
}
}
return Success;
}
private:
std::weak_ptr<Impl> parent_;
std::size_t epoch_;
};
template<class... Inputs>
Buffer<Inputs...>::Buffer(BufferPolicy policy, std::size_t max_queue_size, ros::CallbackQueueInterface* cbq) noexcept
: impl_(std::make_shared<Impl>(this, policy)), cbq_(cbq)
{
impl_->queue_.set_capacity(max_queue_size);
}
template<class... Inputs>
Buffer<Inputs...>::Buffer(const ros::NodeHandle& nh, std::size_t max_queue_size) noexcept
: impl_(std::make_shared<Impl>(this, BufferPolicy::Queue)), cbq_(nh.getCallbackQueue())
{
impl_->queue_.set_capacity(max_queue_size);
}
template<class... Inputs>
Buffer<Inputs...>::~Buffer()
{
set_policy(BufferPolicy::Discard);
}
template<class... Inputs>
void Buffer<Inputs...>::set_policy(BufferPolicy policy, std::size_t max_queue_size)
{
std::unique_lock<std::mutex> lock{impl_->mutex_};
impl_->policy_ = policy;
switch (policy)
{
case BufferPolicy::Discard:
impl_->queue_.clear();
++impl_->epoch_;
if (cbq_) cbq_->removeByID(reinterpret_cast<uint64_t>(this));
lock.unlock();
break;
case BufferPolicy::Queue:
if (max_queue_size > 0) impl_->queue_.set_capacity(max_queue_size);
lock.unlock();
break;
case BufferPolicy::Passthru:
++impl_->epoch_;
if (cbq_) cbq_->removeByID(reinterpret_cast<uint64_t>(this));
process_some(lock);
// lock is unlocked now
break;
}
impl_->cond_.notify_all();
}
template<class... Inputs>
void Buffer<Inputs...>::set_callback_queue(ros::CallbackQueueInterface* cbq) noexcept
{
std::lock_guard<std::mutex> lock{impl_->mutex_};
cbq_ = cbq;
}
template<class... Inputs>
void Buffer<Inputs...>::spin_once()
{
std::unique_lock<std::mutex> lock{impl_->mutex_};
process_some(lock);
}
template<class... Inputs>
void Buffer<Inputs...>::reset() noexcept
{
std::lock_guard<std::mutex> lock{impl_->mutex_};
impl_->queue_.clear();
++impl_->epoch_;
if (cbq_) cbq_->removeByID(reinterpret_cast<uint64_t>(this));
}
template<class... Inputs>
void Buffer<Inputs...>::process_some(std::unique_lock<std::mutex>& lock)
{
std::vector<QueueElement> tmp;
tmp.reserve(impl_->queue_.size());
std::copy(impl_->queue_.begin(), impl_->queue_.end(), std::back_inserter(tmp));
impl_->queue_.clear();
lock.unlock();
for (const QueueElement& e : tmp)
{
send_queue_element(e);
}
// lock stays unlocked
}
template<class... Inputs>
bool Buffer<Inputs...>::has_some() const noexcept
{
std::lock_guard<std::mutex> lock{impl_->mutex_};
return !impl_->queue_.empty();
}
template<class... Inputs>
bool Buffer<Inputs...>::wait() noexcept
{
std::unique_lock<std::mutex> lock{impl_->mutex_};
return impl_->wait_for_queue_element(lock);
}
template<class... Inputs>
template<class Rep, class Period>
bool Buffer<Inputs...>::wait_for(const std::chrono::duration<Rep, Period>& timeout) noexcept
{
std::unique_lock<std::mutex> lock{impl_->mutex_};
return impl_->wait_for_queue_element(lock, timeout);
}
template<class... Inputs>
bool Buffer<Inputs...>::process_one()
{
std::unique_lock<std::mutex> lock{impl_->mutex_};
if (impl_->wait_for_queue_element(lock))
{
QueueElement e{impl_->queue_.front()};
impl_->queue_.pop_front();
lock.unlock();
send_queue_element(e);
return true;
}
return false;
}
template<class... Inputs>
template<class Rep, class Period>
bool Buffer<Inputs...>::process_one(const std::chrono::duration<Rep, Period>& timeout)
{
std::unique_lock<std::mutex> lock{impl_->mutex_};
if (impl_->wait_for_queue_element(lock, timeout))
{
QueueElement e{impl_->queue_.front()};
impl_->queue_.pop_front();
lock.unlock();
send_queue_element(e);
return true;
}
return false;
}
template<class... Inputs>
void Buffer<Inputs...>::receive(const Inputs&... in)
{
std::unique_lock<std::mutex> lock{impl_->mutex_};
switch (impl_->policy_)
{
case BufferPolicy::Discard:
break;
case BufferPolicy::Queue:
impl_->queue_.push_back(QueueElement(in...));
if (cbq_) cbq_->addCallback(ros::CallbackInterfacePtr(new RosCB(impl_, impl_->epoch_)), reinterpret_cast<uint64_t>(this));
lock.unlock();
impl_->cond_.notify_one();
break;
case BufferPolicy::Passthru:
lock.unlock();
this->send(in...);
break;
}
}
template<class... Inputs>
void Buffer<Inputs...>::spin()
{
std::unique_lock<std::mutex> lock{impl_->mutex_};
while (impl_->wait_for_queue_element(lock))
{
QueueElement e{impl_->queue_.front()};
impl_->queue_.pop_front();
lock.unlock();
send_queue_element(e);
lock.lock();
}
}
template<class... Inputs>
void Buffer<Inputs...>::send_queue_element(const QueueElement& e)
{
helpers::index_apply<sizeof...(Inputs)>(
[&](auto... is)
{
this->send(std::get<is>(e)...);
}
);
}
} // namespace fkie_message_filters
#endif /* INCLUDE_FKIE_MESSAGE_FILTERS_BUFFER_IMPL_H_ */
| 29.965753 | 134 | 0.627886 | [
"vector"
] |
397181f441809667ad331a246b9a63b0900be439 | 9,671 | h | C | engine_files/engine_headers/engine_control/engine_control.h | Blizzardbay/pistonworks-engine | c739e193480499ba161c6acf96070d1023813225 | [
"BSD-3-Clause"
] | 2 | 2021-10-05T22:45:04.000Z | 2021-12-16T19:06:08.000Z | engine_files/engine_headers/engine_control/engine_control.h | Blizzardbay/pistonworks-engine | c739e193480499ba161c6acf96070d1023813225 | [
"BSD-3-Clause"
] | null | null | null | engine_files/engine_headers/engine_control/engine_control.h | Blizzardbay/pistonworks-engine | c739e193480499ba161c6acf96070d1023813225 | [
"BSD-3-Clause"
] | null | null | null | // BSD 3 - Clause License
//
// Copyright(c) 2021, Darrian Corkadel
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met :
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and /or other materials provided with the distribution.
//
// 3. Neither the name of 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.
#ifndef H_ENGINE_CONTROL
#define H_ENGINE_CONTROL
//////////////////////////////////
// #FILE_INFO#
// +(DUAL_FILE)
//////////////////////////////////
// C++ Headers
#include <Windows.h>
#include <stdio.h>
#include <chrono>
#include <iostream>
#include <stdlib.h>
#include <memory>
//////////////////////////////////
// Project Headers
#pragma warning(push)
#pragma warning(disable:26495)
#pragma warning(push)
#pragma warning(disable:26812)
#include <box2d\b2_fixture.h>
#pragma warning(pop)
#pragma warning(pop)
//////////////////////////////////
// Engine Common Headers
#include "engine_common\engine_constant.h"
//////////////////////////////////
// Engine Control Headers
#include "engine_control\engine_queue.h"
#include "engine_control\engine_file_loader.h"
#include "engine_control\engine_input.h"
#include "engine_control\engine_console_manip.h"
//////////////////////////////////
// Engine Structures Headers
#include "engine_structures\engine_event.h"
#include "engine_structures\engine_shader.h"
#include "engine_structures\engine_model.h"
#include "engine_structures\engine_texture.h"
#include "engine_structures\engine_game_scene.h"
#include "engine_structures\engine_camera.h"
#include "engine_structures\engine_text.h"
//////////////////////////////////
// Engine Macros
//////////////////////////////////
// Pistonworks Engine //
// Created By : Darrian Corkadel//
//////////////////////////////////
PW_NAMESPACE_SRT
//////////////////////////////////
//////////////////////////////////
CO_NAMESPACE_SRT
//////////////////////////////////
// //////////////////////////////////////////////////
// PW_CONTROL_API Class: pw::co::Engine_Control
// //////////////////////////////////////////////////
// Purpose:
// The main point of the application. Runs all
// events and calculations that take place in the
// engine.
// //////////////////////////////////////////////////
class PW_CONTROL_API Engine_Control : protected pw::cm::Engine_Constant {
// Default Class Structures
public:
// //////////////////////////////////////////////////
// PW_CONTROL_API CLASS_FUNCTION: Engine_Control::Engine_Control
// //////////////////////////////////////////////////
// Purpose:
// Creates a instance of the engine.
// //////////////////////////////////////////////////
// Parameters: NONE
// //////////////////////////////////////////////////
NO_USER_INTERACTION
CLASS_FUNCTION Engine_Control();
// //////////////////////////////////////////////////
// PW_CONTROL_API CLASS_FUNCTION: Engine_Control::~Engine_Control
// //////////////////////////////////////////////////
// Purpose:
// Deletes memory of the engine object.
// //////////////////////////////////////////////////
// Parameters: NONE
// //////////////////////////////////////////////////
NO_USER_INTERACTION
CLASS_FUNCTION ~Engine_Control();
private:
// Public Functions/Macros
public:
// //////////////////////////////////////////////////
// CORE Function: Engine_Control::Init_Engine
// //////////////////////////////////////////////////
// Purpose:
// Init engine make all of the default glew and glfw
// init's that are needed for the application to
// work. Also init's engine constants and runtime
// variables on top of shader control.
// //////////////////////////////////////////////////
// Parameters: 4
// (1) const wchar_t* display_name;
// Purpose:
// The name of the application.
// (2) int32_t display_width = 800;
// Purpose:
// The width of the application.
// (3) int32_t display_height = 608;
// Purpose:
// The height of the application.
// //////////////////////////////////////////////////
NO_USER_INTERACTION
CORE void Init_Engine(const wchar_t* display_name, int32_t display_width = 800, int32_t display_height = 608);
// //////////////////////////////////////////////////
// CORE Function: Engine_Control::Run_Engine
// //////////////////////////////////////////////////
// Purpose:
// Runs the engine queue system and makes sure the
// runtime exceptions are handled and that runtime
// variables are up to date when used. Check/handles
// input and if the window should close.
// //////////////////////////////////////////////////
// Parameters: NONE
// //////////////////////////////////////////////////
NO_USER_INTERACTION
CORE void Run_Engine();
// //////////////////////////////////////////////////
// CORE Function: Engine_Control::Terminate_Engine
// //////////////////////////////////////////////////
// Purpose:
// Destroys and deallocates all of the engine.
// //////////////////////////////////////////////////
// Parameters: NONE
// //////////////////////////////////////////////////
NO_USER_INTERACTION
CORE void Terminate_Engine();
// //////////////////////////////////////////////////
// CORE Function: Engine_Control::Create_Callbacks
// //////////////////////////////////////////////////
// Purpose:
// Creates the input callbacks.
// //////////////////////////////////////////////////
// Parameters: NONE
// //////////////////////////////////////////////////
NO_USER_INTERACTION
CORE void Create_Callbacks() const;
// //////////////////////////////////////////////////
// CORE Function: Engine_Control::Update_Engine_State
// //////////////////////////////////////////////////
// Purpose:
// Swaps opengl buffers.
// //////////////////////////////////////////////////
// Parameters: NONE
// //////////////////////////////////////////////////
NO_USER_INTERACTION
CORE void Update_Engine_State();
// //////////////////////////////////////////////////
// CORE Function: Engine_Control::Should_Close
// //////////////////////////////////////////////////
// Purpose:
// Tests if the window should close or not.
// //////////////////////////////////////////////////
// Parameters: NONE
// //////////////////////////////////////////////////
NO_USER_INTERACTION
CORE bool Should_Close() const;
// //////////////////////////////////////////////////
// CORE Function: Engine_Control::Init_Game
// //////////////////////////////////////////////////
// Purpose:
// User determined.
// //////////////////////////////////////////////////
// Parameters: NONE
// //////////////////////////////////////////////////
NO_USER_INTERACTION
virtual OVERLOAD CORE void Init_Game();
// //////////////////////////////////////////////////
// CORE Function: Engine_Control::Before_Queue
// //////////////////////////////////////////////////
// Purpose:
// User determined.
// //////////////////////////////////////////////////
// Parameters: NONE
// //////////////////////////////////////////////////
NO_USER_INTERACTION
virtual OVERLOAD CORE void Before_Queue();
// //////////////////////////////////////////////////
// CORE Function: Engine_Control::After_Queue
// //////////////////////////////////////////////////
// Purpose:
// User determined.
// //////////////////////////////////////////////////
// Parameters: NONE
// //////////////////////////////////////////////////
NO_USER_INTERACTION
virtual OVERLOAD CORE void After_Queue();
// Accessors
ACCESSOR bool No_Error();
// Public Variables
public:
// Private Functions/Macros
private:
// Private Variables
private:
PW_DUNI_PTR(GLFWwindow, Engine_Constant::Destroy_GLFW) main_window;
// For termination of the engine
bool m_no_error;
bool m_has_terminated;
// Initialization failures
bool m_console_complete;
bool m_glfw_complete;
// Loaded font
bool m_font_complete;
// Loaded queue
bool m_queue_complete;
};
// Functions
// Macros / Definitions
//////////////////////////////////
CO_NAMESPACE_END
//////////////////////////////////
//////////////////////////////////
PW_NAMESPACE_END
//////////////////////////////////
#endif // !H_ENGINE_CONTROL | 38.995968 | 113 | 0.490849 | [
"object"
] |
397a7713c239320f6cc5943dc83c4f52b353cf35 | 374 | h | C | 26_lab/src/line.h | alexndr03/2021-spring-polytech-cpp | 83627304552d8e8be26edd00382756bec5da3ace | [
"MIT"
] | 6 | 2021-02-08T15:26:20.000Z | 2021-03-22T10:19:07.000Z | 26_lab/src/line.h | Efremenkof/2021-spring-polytech-cpp | f4d788df8cfcb0980f35a6b116e6cbcc1347c95a | [
"MIT"
] | 11 | 2021-02-09T06:41:50.000Z | 2021-04-18T08:36:32.000Z | 26_lab/src/line.h | alexndr03/2021-spring-polytech-cpp | 83627304552d8e8be26edd00382756bec5da3ace | [
"MIT"
] | 48 | 2021-02-03T18:28:55.000Z | 2021-05-24T18:54:14.000Z | #ifndef INC_26_LAB_LINE_H
#define INC_26_LAB_LINE_H
#include "shape.h"
class Line : public Shape {
uint32_t x1, y1, x2, y2;
public:
Line(uint32_t x1t, uint32_t y1t, uint32_t x2t, uint32_t y2t) : x1(x1t), y1(y1t), x2(x2t), y2(y2t) {}
void draw() override;
void SetXY(uint32_t x1t, uint32_t y1t, uint32_t x2t, uint32_t y2t);
};
#endif //INC_26_LAB_LINE_H
| 22 | 104 | 0.695187 | [
"shape"
] |
397b6a656fed15660b4c8631f55436c48ec8d1a7 | 861 | h | C | include/cpMemory.h | barebear/php-cp | 5d25d545f3386fa4a60db1376ddf62b63c19b0ff | [
"Apache-2.0"
] | 697 | 2015-01-14T06:19:58.000Z | 2021-11-15T12:16:49.000Z | include/cpMemory.h | barebear/php-cp | 5d25d545f3386fa4a60db1376ddf62b63c19b0ff | [
"Apache-2.0"
] | 58 | 2015-02-01T13:06:07.000Z | 2020-09-28T08:07:26.000Z | include/cpMemory.h | barebear/php-cp | 5d25d545f3386fa4a60db1376ddf62b63c19b0ff | [
"Apache-2.0"
] | 210 | 2015-01-11T13:25:13.000Z | 2021-07-30T01:02:10.000Z | /*
* File: memory.h
* Author: guoxinhua
*
* Created on 2014年9月23日, 下午3:32
*/
#ifndef CP_MEMORY_H
#define CP_MEMORY_H
#ifdef __cplusplus
extern "C" {
#endif
#include <sys/mman.h>
#include <sys/shm.h>
typedef struct _cpShareMemory {
int size;
char mmap_name[100];
void *mem;
} cpShareMemory;
typedef struct _cpMasterInfo {
int server_fd;//fpm in server's fd
} cpMasterInfo;
typedef struct _cpWorkerInfo {
int len;
int pid;
int type;
} cpWorkerInfo;
typedef struct _cpTcpEvent {
int type;
int data;
} cpTcpEvent;
void *cp_mmap_calloc(int size);
void* cp_mmap_calloc_with_file(cpShareMemory *object);
int cp_create_mmap_file(cpShareMemory *object);
int cp_create_mmap_dir();
#ifdef __cplusplus
}
#endif
#endif /* MEMORY_H */
| 16.882353 | 58 | 0.636469 | [
"object"
] |
8225168eee77917b4fa4a100add03c13cc2ff169 | 1,369 | h | C | iRODS/lib/api/include/subStructFileRename.h | iychoi/cyverse-irods | 0070b8677a82e763f1d940ae6537b1c8839a628a | [
"BSD-3-Clause"
] | null | null | null | iRODS/lib/api/include/subStructFileRename.h | iychoi/cyverse-irods | 0070b8677a82e763f1d940ae6537b1c8839a628a | [
"BSD-3-Clause"
] | 7 | 2019-12-02T17:55:49.000Z | 2019-12-02T17:55:59.000Z | iRODS/lib/api/include/subStructFileRename.h | benlazarine/cyverse-irods | 2bf9cfae4c3a1062ffe2af92b1f086ddc5fce025 | [
"BSD-3-Clause"
] | 1 | 2019-12-02T05:40:13.000Z | 2019-12-02T05:40:13.000Z | /*** Copyright (c), The Regents of the University of California ***
*** For more information please refer to subStructFiles in the COPYRIGHT directory ***/
/* subStructFileRename.h
*/
#ifndef SUB_STRUCT_FILE_RENAME_H__
#define SUB_STRUCT_FILE_RENAME_H__
/* This is Object File I/O type API call */
#include "objInfo.h"
#include "rcConnect.h"
typedef struct SubStructFileRenameInp {
subFile_t subFile;
char newSubFilePath[MAX_NAME_LEN];
char resc_hier[ MAX_NAME_LEN ];
} subStructFileRenameInp_t;
#define SubStructFileRenameInp_PI "struct SubFile_PI; str newSubFilePath[MAX_NAME_LEN]; str resc_hier[MAX_NAME_LEN];"
#if defined(RODS_SERVER)
#define RS_SUB_STRUCT_FILE_RENAME rsSubStructFileRename
/* prototype for the server handler */
#include "rodsConnect.h"
int
rsSubStructFileRename( rsComm_t *rsComm, subStructFileRenameInp_t *subStructFileRenameInp );
int
_rsSubStructFileRename( rsComm_t *rsComm, subStructFileRenameInp_t *subStructFileRenameInp );
int
remoteSubStructFileRename( rsComm_t *rsComm, subStructFileRenameInp_t *subStructFileRenameInp,
rodsServerHost_t *rodsServerHost );
#else
#define RS_SUB_STRUCT_FILE_RENAME NULL
#endif
/* prototype for the client call */
int
rcSubStructFileRename( rcComm_t *conn, subStructFileRenameInp_t *subStructFileRenameInp );
#endif // SUB_STRUCT_FILE_RENAME_H__
| 33.390244 | 117 | 0.787436 | [
"object"
] |
8234face755024669e0f18168b1692488d1c144a | 6,574 | h | C | chua/chua.h | camilleg/vss | 27f1c8f73f8d7ef2d4e5de077e4b2ed7e4f72803 | [
"MIT"
] | null | null | null | chua/chua.h | camilleg/vss | 27f1c8f73f8d7ef2d4e5de077e4b2ed7e4f72803 | [
"MIT"
] | null | null | null | chua/chua.h | camilleg/vss | 27f1c8f73f8d7ef2d4e5de077e4b2ed7e4f72803 | [
"MIT"
] | null | null | null | #pragma once
#include "VAlgorithm.h"
#include "VHandler.h"
#include "VGenActor.h"
#define CHUA_DIM 3
#define TAUMAX 1000
// Note that some members are defined in the class definition
// owing to the lameness of our compiler.
//
class chuaAlg : public VAlgorithm
{
// synthesis parameters
float potentiometer;
double Q;
int cursamp;
int tau;
double R;
double R0;
double C1;
double C2;
double L;
double BPH1;
double BPH2;
double BP1;
double BP2;
double M0;
double M1;
double M2;
double M3;
double tstep;
float spectStep; /* will be converted to Hz */
int integStep; /* number of 1/SR steps per integration step */
double vector_pos[CHUA_DIM];
// for itegration
double g, REGbp1, REGbp2, REGbph1, REGbph2, REGbpdiff;
double g0BPH1, g0BPH2, AA, BB, MA, MB, rho, p5m;
public:
double getR() const { return R; }
double getR0() const { return R0; }
double getC1() const { return C1; }
double getC2() const { return C2; }
double getL() const { return L; }
double getBPH1() const { return BPH1; }
double getBPH2() const { return BPH2; }
double getBP1() const { return BP1; }
double getBP2() const { return BP2; }
double getM0() const { return M0; }
double getM1() const { return M1; }
double getM2() const { return M2; }
double getM3() const { return M3; }
void getVector(double* dst) const { memcpy(dst, vector_pos, CHUA_DIM*sizeof(double)); }
void setFundamental(float, float);
void setR(float newR) { R = newR; }
void setR0(float newR0) { R0 = newR0; }
void setC1(float newC1) { C1 = newC1; }
void setC2(float newC2) { C2 = newC2; }
void setL(float newL) { L = newL; }
void setBPH1(float newBPH1) { BPH1 = newBPH1; }
void setBPH2(float newBPH2) { BPH2 = newBPH2; }
void setBP1(float newBP1) { BP1 = newBP1; }
void setBP2(float newBP2) { BP2 = newBP2; }
void setM0(float newM0) { M0 = newM0; }
void setM1(float newM1) { M1 = newM1; }
void setM2(float newM2) { M2 = newM2; }
void setM3(float newM3) { M3 = newM3; }
void setVector(const double* src) { memcpy(vector_pos, src, CHUA_DIM*sizeof(double)); }
void resetChuaNote();
void resetControlForce();
void resetVector();
void resetState();
// Runge-Kutta integration.
void difeq(const double* xx, double* xdot)
{
// Define nonlinear resistor function g(v1)
g = (xx[0] < REGbph1) ?
M2 * (xx[0] - REGbph1) + g0BPH1 :
(xx[0] > REGbph2) ?
M3 * (xx[0] - REGbph2) + g0BPH2 :
MB * xx[0] + p5m * (fabs(xx[0] + REGbp1) - fabs(xx[0] - REGbp2) + REGbpdiff);
// Vector field
xdot[0] = AA * ( xx[1] - xx[0] - g);
xdot[1] = xx[0] - xx[1] + xx[2];
xdot[2] = - BB * (xx[1] + rho * xx[2]);
};
void rk4()
{
int l;
double k1[CHUA_DIM];
double k2[CHUA_DIM];
double k3[CHUA_DIM];
double xdot[CHUA_DIM];
double new_vp[CHUA_DIM];
difeq(vector_pos, xdot);
for(l=0;l<CHUA_DIM;l++)
new_vp[l] = vector_pos[l] + (k1[l]=tstep*xdot[l]*0.5);
difeq(new_vp, xdot);
for(l=0;l<CHUA_DIM;l++)
new_vp[l] = vector_pos[l] + (k2[l]=tstep*xdot[l])*0.5;
difeq(new_vp, xdot);
for(l=0;l<CHUA_DIM;l++)
new_vp[l] = vector_pos[l] + (k3[l]=tstep*xdot[l]);
difeq(new_vp, xdot);
for(l=0;l<CHUA_DIM;l++)
vector_pos[l] += (k1[l]+k2[l]+k3[l]+tstep*xdot[l]*0.5)/3.0;
// printf("R %f, R0 %f, C1 %e, C2 %e, L %f, BP1 %f, BP2 %f, M0 %e, M1 %e, M2 %e, M3 %e, X %f, Y %f, Z %f\n ",
// R, R0, C1, C2, L, BP1, BP2, M0, M1, M2, M3,
// vector_pos[0], vector_pos[1], vector_pos[2]);
};
void generateSamples(int);
chuaAlg();
~chuaAlg();
};
class chuaHand : public VHandler
{
float R, R0, C1, C2, L, BPH1, BPH2, BP1, BP2, M0, M1, M2, M3;
enum { isetR, isetR0, isetC1, isetC2, isetL, isetBPH1, isetBPH2, isetBP1, isetBP2, isetM0, isetM1, isetM2, isetM3 };
protected:
chuaAlg* getAlg() { return (chuaAlg*)VHandler::getAlg(); }
public:
// parameter modulation
void resetChuaState();
void SetAttribute(IParam iParam, float z);
void setR(float z, float t = timeDefault)
{ modulate(isetR, R, z, AdjustTime(t)); }
void setR0(float z, float t = timeDefault)
{ modulate(isetR0, R0, z, AdjustTime(t)); }
void setC1(float z, float t = timeDefault)
{ modulate(isetC1, C1, z, AdjustTime(t)); }
void setC2(float z, float t = timeDefault)
{ modulate(isetC2, C2, z, AdjustTime(t)); }
void setL(float z, float t = timeDefault)
{ modulate(isetL, L, z, AdjustTime(t)); }
void setBPH1(float z, float t = timeDefault)
{ modulate(isetBPH1, BPH1, z, AdjustTime(t)); }
void setBPH2(float z, float t = timeDefault)
{ modulate(isetBPH2, BPH2, z, AdjustTime(t)); }
void setBP1(float z, float t = timeDefault)
{ modulate(isetBP1, BP1, z, AdjustTime(t)); }
void setBP2(float z, float t = timeDefault)
{ modulate(isetBP2, BP2, z, AdjustTime(t)); }
void setM0(float z, float t = timeDefault)
{ modulate(isetM0, M0, z, AdjustTime(t)); }
void setM1(float z, float t = timeDefault)
{ modulate(isetM1, M1, z, AdjustTime(t)); }
void setM2(float z, float t = timeDefault)
{ modulate(isetM2, M2, z, AdjustTime(t)); }
void setM3(float z, float t = timeDefault)
{ modulate(isetM3, M3, z, AdjustTime(t)); }
float dampingTime() { return 0.03; }
chuaHand(chuaAlg* alg = new chuaAlg);
~chuaHand() {}
int receiveMessage(const char*);
};
class chuaActor : public VGeneratorActor
{
static int initialized;
public:
chuaActor();
~chuaActor() {}
VHandler* newHandler() { return new chuaHand(); }
void sendDefaults(VHandler*);
int receiveMessage(const char*);
void resetAllChuaState();
void setR(float z);
void setAllR(float z, float t = 0.);
void setR0(float z);
void setAllR0(float z, float t = 0.);
void setC1(float z);
void setAllC1(float z, float t = 0.);
void setC2(float z);
void setAllC2(float z, float t = 0.);
void setL(float z);
void setAllL(float z, float t = 0.);
void setBPH1(float z);
void setAllBPH1(float z, float t = 0.);
void setBPH2(float z);
void setAllBPH2(float z, float t = 0.);
void setBP1(float z);
void setAllBP1(float z, float t = 0.);
void setBP2(float z);
void setAllBP2(float z, float t = 0.);
void setM0(float z);
void setAllM0(float z, float t = 0.);
void setM1(float z);
void setAllM1(float z, float t = 0.);
void setM2(float z);
void setAllM2(float z, float t = 0.);
void setM3(float z);
void setAllM3(float z, float t = 0.);
protected:
float defaultR;
float defaultR0;
float defaultC1;
float defaultC2;
float defaultL;
float defaultBPH1;
float defaultBPH2;
float defaultBP1;
float defaultBP2;
float defaultM0;
float defaultM1;
float defaultM2;
float defaultM3;
};
| 26.942623 | 117 | 0.649224 | [
"vector"
] |
823b02f3b663a8fcb3711cdc810b3adcadfb0e00 | 132,469 | c | C | enduser/netmeeting/av/codecs/dec/dech263/sv_api.c | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | enduser/netmeeting/av/codecs/dec/dech263/sv_api.c | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | enduser/netmeeting/av/codecs/dec/dech263/sv_api.c | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /*
* @DEC_COPYRIGHT@
*/
/*
* HISTORY
* $Log: sv_api.c,v $
* Revision 1.1.8.11 1996/10/28 17:32:51 Hans_Graves
* MME-01402. Changed SvGet/SetParamInt() to qwords to allow for timestamps.
* [1996/10/28 17:09:33 Hans_Graves]
*
* Revision 1.1.8.10 1996/10/12 17:19:24 Hans_Graves
* Added initialization of SV_PARAM_SKIPPEL and SV_PARAM_HALFPEL to MPEG encode.
* [1996/10/12 17:16:28 Hans_Graves]
*
* Revision 1.1.8.9 1996/09/29 22:19:56 Hans_Graves
* Added stride to ScYuv411ToRgb() calls.
* [1996/09/29 21:34:40 Hans_Graves]
*
* Revision 1.1.8.8 1996/09/25 19:17:01 Hans_Graves
* Fix up support for YUY2 under MPEG.
* [1996/09/25 19:03:17 Hans_Graves]
*
* Revision 1.1.8.7 1996/09/18 23:51:11 Hans_Graves
* Added JPEG 4:1:1 to 4:2:2 conversions. Added BI_YVU9SEP and BI_RGB 24 support in MPEG decode.
* [1996/09/18 22:16:08 Hans_Graves]
*
* Revision 1.1.8.6 1996/07/30 20:25:50 Wei_Hsu
* Add Logarithmetic search for motion estimation.
* [1996/07/30 15:57:59 Wei_Hsu]
*
* Revision 1.1.8.5 1996/05/24 22:22:26 Hans_Graves
* Add GetImageSize MPEG support for BI_DECYUVDIB
* [1996/05/24 22:14:20 Hans_Graves]
*
* Revision 1.1.8.4 1996/05/08 16:24:32 Hans_Graves
* Put BITSTREAM_SUPPORT around BSIn in SvDecompress
* [1996/05/08 16:24:15 Hans_Graves]
*
* Revision 1.1.8.3 1996/05/07 21:24:05 Hans_Graves
* Add missing break in switch statement in SvRegisterCallback
* [1996/05/07 21:19:50 Hans_Graves]
*
* Revision 1.1.8.2 1996/05/07 19:56:46 Hans_Graves
* Added HUFF_SUPPORT. Remove NT warnings.
* [1996/05/07 17:27:18 Hans_Graves]
*
* Revision 1.1.6.12 1996/04/23 18:51:10 Karen_Dintino
* Fix the memory alloc for the ref buffer for WIN32
* [1996/04/23 18:49:23 Karen_Dintino]
*
* Revision 1.1.6.11 1996/04/17 23:44:35 Karen_Dintino
* added initializations for H.261/WIN32
* [1996/04/17 23:43:20 Karen_Dintino]
*
* Revision 1.1.6.10 1996/04/11 22:54:43 Karen_Dintino
* added casting for in SetFrameRate
* [1996/04/11 22:52:29 Karen_Dintino]
*
* Revision 1.1.6.9 1996/04/11 14:14:14 Hans_Graves
* Fix NT warnings
* [1996/04/11 14:09:53 Hans_Graves]
*
* Revision 1.1.6.8 1996/04/10 21:48:09 Hans_Graves
* Added SvGet/SetBoolean() functions.
* [1996/04/10 21:28:13 Hans_Graves]
*
* Revision 1.1.6.7 1996/04/09 20:50:44 Karen_Dintino
* Adding WIN32 support
* [1996/04/09 20:47:26 Karen_Dintino]
*
* Revision 1.1.6.6 1996/04/09 16:05:00 Hans_Graves
* Add some abs() around height params. SvRegisterCallback() cleanup
* [1996/04/09 15:39:31 Hans_Graves]
*
* Revision 1.1.6.5 1996/04/04 23:35:27 Hans_Graves
* Removed BI_YU16SEP support from MPEG decomp.
* [1996/04/04 23:12:02 Hans_Graves]
*
* Fixed up Multibuf size (MPEG) related stuff
* [1996/04/04 23:08:55 Hans_Graves]
*
* Revision 1.1.6.4 1996/04/01 15:17:47 Bjorn_Engberg
* Got rid of a compiler warning.
* [1996/04/01 15:02:35 Bjorn_Engberg]
*
* Revision 1.1.6.3 1996/03/29 22:22:36 Hans_Graves
* -Added JPEG_SUPPORT ifdefs.
* -Changed JPEG related structures to fit naming conventions.
* [1996/03/29 21:59:08 Hans_Graves]
*
* Revision 1.1.6.2 1996/03/16 20:13:51 Karen_Dintino
* Adding NT port changes for H.261
* [1996/03/16 19:48:31 Karen_Dintino]
*
* Revision 1.1.4.12 1996/02/26 18:42:32 Karen_Dintino
* fix PTT 01106 server crash in ICCompress
* [1996/02/26 18:41:33 Karen_Dintino]
*
* Revision 1.1.4.11 1996/02/22 17:35:19 Bjorn_Engberg
* Added support for JPEG Mono to BI_BITFIELDS 16 decompression on NT.
* [1996/02/22 17:34:53 Bjorn_Engberg]
*
* Revision 1.1.4.10 1996/02/08 13:48:44 Bjorn_Engberg
* Get rid of int to float compiler warning.
* [1996/02/08 13:48:20 Bjorn_Engberg]
*
* Revision 1.1.4.9 1996/02/07 23:24:08 Hans_Graves
* MPEG Key frame stats initialization
* [1996/02/07 23:14:41 Hans_Graves]
*
* Revision 1.1.4.8 1996/02/06 22:54:17 Hans_Graves
* Added SvGet/SetParam functions
* [1996/02/06 22:51:19 Hans_Graves]
*
* Revision 1.1.4.7 1996/01/08 20:19:33 Bjorn_Engberg
* Got rid of more compiler warnings.
* [1996/01/08 20:19:13 Bjorn_Engberg]
*
* Revision 1.1.4.6 1996/01/08 16:42:47 Hans_Graves
* Added MPEG II decoding support
* [1996/01/08 15:41:37 Hans_Graves]
*
* Revision 1.1.4.5 1996/01/02 18:32:14 Bjorn_Engberg
* Got rid of compiler warnings: Added Casts, Removed unused variables.
* [1996/01/02 17:26:21 Bjorn_Engberg]
*
* Revision 1.1.4.4 1995/12/28 18:40:06 Bjorn_Engberg
* IsSupported() sometimes returned garbage and thus a false match.
* SvDecompressQuery() and SvCompressQuery() were using the
* wrong lookup tables.
* [1995/12/28 18:39:30 Bjorn_Engberg]
*
* Revision 1.1.4.3 1995/12/08 20:01:30 Hans_Graves
* Added SvSetRate() and SvSetFrameRate() to H.261 compression open
* [1995/12/08 19:58:32 Hans_Graves]
*
* Revision 1.1.4.2 1995/12/07 19:32:17 Hans_Graves
* Added MPEG I & II Encoding support
* [1995/12/07 18:43:45 Hans_Graves]
*
* Revision 1.1.2.46 1995/11/30 20:17:06 Hans_Graves
* Added BI_DECGRAYDIB handling for JPEG decompression, used with Mono JPEG
* [1995/11/30 20:12:24 Hans_Graves]
*
* Revision 1.1.2.45 1995/11/29 17:53:26 Hans_Graves
* Added JPEG_DIB 8-bit to BI_DECGRAYDIB as supported format
* [1995/11/29 17:53:00 Hans_Graves]
*
* Revision 1.1.2.44 1995/11/28 22:47:33 Hans_Graves
* Added BI_BITFIELDS as supported decompression format for H261 and MPEG
* [1995/11/28 22:39:25 Hans_Graves]
*
* Revision 1.1.2.43 1995/11/17 21:31:28 Hans_Graves
* Added checks on ImageSize in SvDecompress()
* [1995/11/17 21:27:19 Hans_Graves]
*
* Query cleanup - Added lookup tables for supportted formats
* [1995/11/17 20:53:54 Hans_Graves]
*
* Revision 1.1.2.42 1995/11/03 16:36:25 Paul_Gauthier
* Reject requests to scale MPEG input during decompression
* [1995/11/03 16:34:01 Paul_Gauthier]
*
* Revision 1.1.2.41 1995/10/25 18:19:22 Bjorn_Engberg
* What was allocated with ScPaMalloc() must be freed with ScPaFree().
* [1995/10/25 18:02:04 Bjorn_Engberg]
*
* Revision 1.1.2.40 1995/10/25 17:38:04 Hans_Graves
* Removed some memory freeing calls on image memory in SvCloseCodec for H261 decoding. The app allocates the image buffer.
* [1995/10/25 17:37:35 Hans_Graves]
*
* Revision 1.1.2.39 1995/10/13 16:57:19 Bjorn_Engberg
* Added a cast to get rid of a compiler warning.
* [1995/10/13 16:56:29 Bjorn_Engberg]
*
* Revision 1.1.2.38 1995/10/06 20:51:47 Farokh_Morshed
* Enhance to handle BI_BITFIELDS for input to compression
* [1995/10/06 20:49:10 Farokh_Morshed]
*
* Revision 1.1.2.37 1995/10/02 19:31:03 Bjorn_Engberg
* Clarified what formats are supported and not.
* [1995/10/02 18:51:49 Bjorn_Engberg]
*
* Revision 1.1.2.36 1995/09/28 20:40:09 Farokh_Morshed
* Handle negative Height
* [1995/09/28 20:39:45 Farokh_Morshed]
*
* Revision 1.1.2.35 1995/09/26 17:49:47 Paul_Gauthier
* Fix H.261 output conversion to interleaved YUV
* [1995/09/26 17:49:20 Paul_Gauthier]
*
* Revision 1.1.2.34 1995/09/26 15:58:44 Paul_Gauthier
* Fix mono JPEG to interlaced 422 YUV conversion
* [1995/09/26 15:58:16 Paul_Gauthier]
*
* Revision 1.1.2.33 1995/09/25 21:18:14 Paul_Gauthier
* Added interleaved YUV output to decompression
* [1995/09/25 21:17:42 Paul_Gauthier]
*
* Revision 1.1.2.32 1995/09/22 12:58:50 Bjorn_Engberg
* More NT porting work; Added MPEG_SUPPORT and H261_SUPPORT.
* [1995/09/22 12:26:14 Bjorn_Engberg]
*
* Revision 1.1.2.31 1995/09/20 19:35:02 Hans_Graves
* Cleaned-up debugging statements
* [1995/09/20 19:33:07 Hans_Graves]
*
* Revision 1.1.2.30 1995/09/20 18:22:53 Karen_Dintino
* Free temp buffer after convert
* [1995/09/20 18:22:37 Karen_Dintino]
*
* Revision 1.1.2.29 1995/09/20 17:39:22 Karen_Dintino
* {** Merge Information **}
* {** Command used: bsubmit **}
* {** Ancestor revision: 1.1.2.27 **}
* {** Merge revision: 1.1.2.28 **}
* {** End **}
* Add RGB support to JPEG
* [1995/09/20 17:37:41 Karen_Dintino]
*
* Revision 1.1.2.28 1995/09/20 15:00:03 Bjorn_Engberg
* Port to NT
* [1995/09/20 14:43:15 Bjorn_Engberg]
*
* Revision 1.1.2.27 1995/09/13 19:42:44 Paul_Gauthier
* Added TGA2 support (direct 422 interleaved output from JPEG codec
* [1995/09/13 19:15:47 Paul_Gauthier]
*
* Revision 1.1.2.26 1995/09/11 18:53:45 Farokh_Morshed
* {** Merge Information **}
* {** Command used: bsubmit **}
* {** Ancestor revision: 1.1.2.24 **}
* {** Merge revision: 1.1.2.25 **}
* {** End **}
* Support BI_BITFIELDS format
* [1995/09/11 18:52:08 Farokh_Morshed]
*
* Revision 1.1.2.25 1995/09/05 14:05:01 Paul_Gauthier
* Add ICMODE_OLDQ flag on ICOpen for softjpeg to use old quant tables
* [1995/08/31 20:58:06 Paul_Gauthier]
*
* Revision 1.1.2.24 1995/08/16 19:56:46 Hans_Graves
* Fixed RELEASE_BUFFER callbacks for Images
* [1995/08/16 19:54:40 Hans_Graves]
*
* Revision 1.1.2.23 1995/08/15 19:14:18 Karen_Dintino
* pass H261 struct to inithuff & freehuff
* [1995/08/15 19:10:58 Karen_Dintino]
*
* Revision 1.1.2.22 1995/08/14 19:40:36 Hans_Graves
* Add CB_CODEC_DONE callback. Fixed Memory allocation and freeing under H261.
* [1995/08/14 18:45:22 Hans_Graves]
*
* Revision 1.1.2.21 1995/08/04 17:22:49 Hans_Graves
* Make END_SEQ callback happen after any H261 decompress error.
* [1995/08/04 17:20:55 Hans_Graves]
*
* Revision 1.1.2.20 1995/08/04 16:32:46 Karen_Dintino
* Free Huffman codes on end of Encode and Decode
* [1995/08/04 16:25:59 Karen_Dintino]
*
* Revision 1.1.2.19 1995/07/31 21:11:14 Karen_Dintino
* {** Merge Information **}
* {** Command used: bsubmit **}
* {** Ancestor revision: 1.1.2.17 **}
* {** Merge revision: 1.1.2.18 **}
* {** End **}
* Add 411YUVSEP Support
* [1995/07/31 20:41:28 Karen_Dintino]
*
* Revision 1.1.2.18 1995/07/31 20:19:58 Hans_Graves
* Set Format parameter in Frame callbacks
* [1995/07/31 20:16:06 Hans_Graves]
*
* Revision 1.1.2.17 1995/07/28 20:58:40 Hans_Graves
* Added Queue debugging messages.
* [1995/07/28 20:49:15 Hans_Graves]
*
* Revision 1.1.2.16 1995/07/28 17:36:10 Hans_Graves
* Fixed up H261 Compression and Decompression.
* [1995/07/28 17:26:17 Hans_Graves]
*
* Revision 1.1.2.15 1995/07/27 18:28:55 Hans_Graves
* Fixed AddBuffer() so it works with H261.
* [1995/07/27 18:24:37 Hans_Graves]
*
* Revision 1.1.2.14 1995/07/26 17:49:04 Hans_Graves
* Fixed SvCompressBegin() JPEG initialization. Added ImageQ support.
* [1995/07/26 17:41:24 Hans_Graves]
*
* Revision 1.1.2.13 1995/07/25 22:00:33 Hans_Graves
* Fixed H261 image size logic in SvCompressQuery().
* [1995/07/25 21:59:08 Hans_Graves]
*
* Revision 1.1.2.12 1995/07/21 17:41:20 Hans_Graves
* Renamed Callback related stuff.
* [1995/07/21 17:26:11 Hans_Graves]
*
* Revision 1.1.2.11 1995/07/18 17:26:56 Hans_Graves
* Fixed QCIF width parameter checking.
* [1995/07/18 17:24:55 Hans_Graves]
*
* Revision 1.1.2.10 1995/07/17 22:01:45 Hans_Graves
* Removed defines for CIF_WIDTH, CIF_HEIGHT, etc.
* [1995/07/17 21:48:51 Hans_Graves]
*
* Revision 1.1.2.9 1995/07/17 16:12:37 Hans_Graves
* H261 Cleanup.
* [1995/07/17 15:50:51 Hans_Graves]
*
* Revision 1.1.2.8 1995/07/12 19:48:30 Hans_Graves
* Fixed up some H261 Queue/Callback bugs.
* [1995/07/12 19:31:51 Hans_Graves]
*
* Revision 1.1.2.7 1995/07/11 22:12:00 Karen_Dintino
* Add SvCompressQuery, SvDecompressQuery support
* [1995/07/11 21:57:21 Karen_Dintino]
*
* Revision 1.1.2.6 1995/07/01 18:43:49 Karen_Dintino
* Add support for H.261 Decompress
* [1995/07/01 18:26:18 Karen_Dintino]
*
* Revision 1.1.2.5 1995/06/19 20:31:51 Karen_Dintino
* Adding support for H.261 Codec
* [1995/06/19 19:25:27 Karen_Dintino]
*
* Revision 1.1.2.4 1995/06/09 18:33:34 Hans_Graves
* Added SvGetInputBitstream(). Changed SvDecompressBegin() to handle NULL Image formats.
* [1995/06/09 16:35:29 Hans_Graves]
*
* Revision 1.1.2.3 1995/06/05 21:07:20 Hans_Graves
* Fixed logic in SvRegisterCallback().
* [1995/06/05 20:04:30 Hans_Graves]
*
* Revision 1.1.2.2 1995/05/31 18:12:42 Hans_Graves
* Inclusion in new SLIB location.
* [1995/05/31 17:18:53 Hans_Graves]
*
* Revision 1.1.2.10 1995/02/02 19:26:01 Paul_Gauthier
* Fix to blank bottom strip & server crash for softjpeg compress
* [1995/02/02 19:12:58 Paul_Gauthier]
*
* Revision 1.1.2.9 1995/01/20 21:45:57 Jim_Ludwig
* Add support for 16 bit YUV
* [1995/01/20 21:28:49 Jim_Ludwig]
*
* Revision 1.1.2.8 1994/12/12 15:38:54 Paul_Gauthier
* Merge changes from other SLIB versions
* [1994/12/12 15:34:21 Paul_Gauthier]
*
* Revision 1.1.2.7 1994/11/18 18:48:36 Paul_Gauthier
* Cleanup & bug fixes
* [1994/11/18 18:44:02 Paul_Gauthier]
*
* Revision 1.1.2.6 1994/10/28 19:56:30 Paul_Gauthier
* Additional Clean Up
* [1994/10/28 19:54:35 Paul_Gauthier]
*
* Revision 1.1.2.5 1994/10/17 19:03:28 Paul_Gauthier
* Fixed reversed Quality scale
* [1994/10/17 19:02:50 Paul_Gauthier]
*
* Revision 1.1.2.4 1994/10/13 20:34:27 Paul_Gauthier
* MPEG cleanup
* [1994/10/13 20:23:23 Paul_Gauthier]
*
* Revision 1.1.2.3 1994/10/10 21:45:50 Tom_Morris
* Rename Status to not conflict with X11
* [1994/10/10 21:44:16 Tom_Morris]
*
* Revision 1.1.2.2 1994/10/07 14:39:25 Paul_Gauthier
* SLIB v3.0 incl. MPEG Decode
* [1994/10/07 13:53:40 Paul_Gauthier]
*
* ******************************************************************
* Changes from original brance merged into this file 11/30/94 PSG
* ******************************************************************
* Revision 1.1.2.10 1994/08/11 21:27:24 Leela_Obilichetti
* Added in width and height checks into SvDecompressQuery and SvCompressQuery.
* [1994/08/11 21:03:38 Leela_Obilichetti]
*
* Revision 1.1.2.9 1994/08/09 18:52:40 Ken_Chiquoine
* set mode type in decode as well as encode
* [1994/08/09 18:52:17 Ken_Chiquoine]
*
* Revision 1.1.2.8 1994/08/04 22:06:33 Leela_Obilichetti
* oops, removed fprintf.
* [1994/08/04 21:54:11 Leela_Obilichetti]
*
* Revision 1.1.2.7 1994/08/04 21:34:04 Leela_Obilichetti
* v1 drop.
* [1994/08/04 21:05:01 Leela_Obilichetti]
*
* Revision 1.1.2.6 1994/07/15 23:31:43 Leela_Obilichetti
* added new stuff for compression - v4 of SLIB.
* [1994/07/15 23:29:17 Leela_Obilichetti]
*
* Revision 1.1.2.5 1994/06/08 16:44:28 Leela_Obilichetti
* fixes for YUV_to_RGB for OSF/1. Haven't tested on Microsoft.
* [1994/06/08 16:42:46 Leela_Obilichetti]
*
* Revision 1.1.2.4 1994/06/03 21:11:14 Leela_Obilichetti
* commment out the code to let in DECYUVDIB
* free memory that is allocated for YUV
* add in code to convert from DECSEPYUV to DECYUV -
* shouldn't get there since se don't allow YUV anymore
* [1994/06/03 21:03:42 Leela_Obilichetti]
*
* Revision 1.1.2.3 1994/05/11 21:02:17 Leela_Obilichetti
* bug fix for NT
* [1994/05/11 20:56:16 Leela_Obilichetti]
*
* Revision 1.1.2.2 1994/05/09 22:06:07 Leela_Obilichetti
* V3 drop
* [1994/05/09 21:51:30 Leela_Obilichetti]
*
* $EndLog$
*/
/*
**++
** FACILITY: Workstation Multimedia (WMM) v1.0
**
** FILE NAME:
** MODULE NAME:
**
** MODULE DESCRIPTION:
**
** DESIGN OVERVIEW:
**
**--
*/
/*****************************************************************************
** Copyright (c) Digital Equipment Corporation, 1994 **
** **
** All Rights Reserved. Unpublished rights reserved under the copyright **
** laws of the United States. **
** **
** The software contained on this media is proprietary to and embodies **
** the confidential technology of Digital Equipment Corporation. **
** Possession, use, duplication or dissemination of the software and **
** media is authorized only pursuant to a valid written license from **
** Digital Equipment Corporation. **
** **
** RESTRICTED RIGHTS LEGEND Use, duplication, or disclosure by the U.S. **
** Government is subject to restrictions as set forth in Subparagraph **
** (c)(1)(ii) of DFARS 252.227-7013, or in FAR 52.227-19, as applicable. **
******************************************************************************/
/*-------------------------------------------------------------------------
* Modification History: sv_api.c
*
* 08-Sep-94 PSG Added MPEG decode support
* 29-Jul-94 VB Added restrictions for compression
* 21-Jul-94 VB Rewrote/cleaned up sections of JPEG decompression
* 13-Jul-94 PSG Added support for encode/decode of grayscale only
* 07-Jul-94 PSG Converted to single Info structure (cmp/dcmp)
* 14-Jun-94 VB Added JPEG compression support
* 08-Jun-94 PSG Added support for BI_DECXIMAGEDIB (B,G,R,0)
* 06-Jun-94 PSG Bring code up to SLIB v0.04 spec
* 15-Apr-94 VB Added support for 24-bit,16-bit and 15-bit RGB output
* 24-Feb-94 PSG Bring code up to SLIB v0.02 spec
* 20-Jan-94 PSG added a number of new SLIB routines
* 12-Jan-94 VB Created (from SLIB spec.)
*
* Author(s):
* VB - Victor Bahl
* PSG - Paul Gauthier
--------------------------------------------------------------------------*/
/*
#define _SLIBDEBUG_
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "SV.h"
#include "sv_intrn.h"
#ifdef JPEG_SUPPORT
/*
* More JPEG code needs to be moved to sv_jpeg_init file
*/
#include "sv_jpeg_tables.h"
#endif /* JPEG_SUPPORT */
#include "sv_proto.h"
#include "SC.h"
#include "SC_conv.h"
#include "SC_err.h"
#ifdef WIN32
#include <mmsystem.h>
#endif
#ifdef _SLIBDEBUG_
#define _DEBUG_ 1 /* detailed debuging statements */
#define _VERBOSE_ 1 /* show progress */
#define _VERIFY_ 1 /* verify correct operation */
#define _WARN_ 0 /* warnings about strange behavior */
#endif
static void sv_copy_bmh (
BITMAPINFOHEADER *ImgFrom,
BITMAPINFOHEADER *ImgTo);
typedef struct SupportList_s {
int InFormat; /* Input format */
int InBits; /* Input number of bits */
int OutFormat; /* Output format */
int OutBits; /* Output number of bits */
} SupportList_t;
/*
** Input & Output Formats supported by SLIB Compression
*/
static SupportList_t _SvCompressionSupport[] = {
BI_DECYUVDIB, 16, JPEG_DIB, 8, /* YUV 4:2:2 Packed */
BI_DECYUVDIB, 16, JPEG_DIB, 24, /* YUV 4:2:2 Packed */
BI_DECYUVDIB, 16, MJPG_DIB, 24, /* YUV 4:2:2 Packed */
BI_YUY2, 16, JPEG_DIB, 8, /* YUV 4:2:2 Packed */
BI_YUY2, 16, JPEG_DIB, 24, /* YUV 4:2:2 Packed */
BI_YUY2, 16, MJPG_DIB, 24, /* YUV 4:2:2 Packed */
BI_S422, 16, JPEG_DIB, 8, /* YUV 4:2:2 Packed */
BI_S422, 16, JPEG_DIB, 24, /* YUV 4:2:2 Packed */
BI_S422, 16, MJPG_DIB, 24, /* YUV 4:2:2 Packed */
BI_BITFIELDS, 32, JPEG_DIB, 8, /* BITFIELDS */
BI_BITFIELDS, 32, JPEG_DIB, 24, /* BITFIELDS */
BI_BITFIELDS, 32, MJPG_DIB, 24, /* BITFIELDS */
BI_DECSEPRGBDIB, 32, JPEG_DIB, 8, /* RGB 32 Planar */
BI_DECSEPRGBDIB, 32, JPEG_DIB, 24, /* RGB 32 Planar */
BI_DECSEPRGBDIB, 32, MJPG_DIB, 24, /* RGB 32 Planar */
#ifdef WIN32
BI_RGB, 24, JPEG_DIB, 8, /* RGB 24 */
BI_RGB, 24, JPEG_DIB, 24, /* RGB 24 */
BI_RGB, 24, MJPG_DIB, 24, /* RGB 24 */
BI_RGB, 32, JPEG_DIB, 8, /* RGB 32 */
BI_RGB, 32, JPEG_DIB, 24, /* RGB 32 */
BI_RGB, 32, MJPG_DIB, 24, /* RGB 32 */
#endif /* WIN32 */
#ifndef WIN32
BI_DECGRAYDIB, 8, JPEG_DIB, 8, /* Gray 8 */
BI_DECXIMAGEDIB, 24, JPEG_DIB, 8, /* XIMAGE 24 */
BI_DECXIMAGEDIB, 24, JPEG_DIB, 24, /* XIMAGE 24 */
BI_DECXIMAGEDIB, 24, MJPG_DIB, 24, /* XIMAGE 24 */
#endif /* !WIN32 */
#ifdef H261_SUPPORT
BI_DECYUVDIB, 16, BI_DECH261DIB, 24, /* YUV 4:2:2 Packed */
BI_YU12SEP, 24, BI_DECH261DIB, 24, /* YUV 4:1:1 Planar */
BI_DECSEPYUV411DIB, 24, BI_DECH261DIB, 24, /* YUV 4:1:1 Planar */
BI_YU16SEP, 24, BI_DECH261DIB, 24, /* YUV 4:2:2 Planar */
BI_DECSEPYUVDIB, 24, BI_DECH261DIB, 24, /* YUV 4:2:2 Planar */
#endif /* H261_SUPPORT */
#ifdef H263_SUPPORT
BI_DECYUVDIB, 16, BI_DECH263DIB, 24, /* YUV 4:2:2 Packed */
BI_YU12SEP, 24, BI_DECH263DIB, 24, /* YUV 4:1:1 Planar */
BI_DECSEPYUV411DIB, 24, BI_DECH263DIB, 24, /* YUV 4:1:1 Planar */
BI_YU16SEP, 24, BI_DECH263DIB, 24, /* YUV 4:2:2 Planar */
BI_DECSEPYUVDIB, 24, BI_DECH263DIB, 24, /* YUV 4:2:2 Planar */
#endif /* H263_SUPPORT */
#ifdef MPEG_SUPPORT
BI_DECYUVDIB, 16, BI_DECMPEGDIB, 24, /* YUV 4:2:2 Packed */
BI_YU12SEP, 24, BI_DECMPEGDIB, 24, /* YUV 4:1:1 Planar */
BI_DECSEPYUV411DIB, 24, BI_DECMPEGDIB, 24, /* YUV 4:1:1 Planar */
BI_YU16SEP, 24, BI_DECMPEGDIB, 24, /* YUV 4:2:2 Planar */
BI_DECSEPYUVDIB, 24, BI_DECMPEGDIB, 24, /* YUV 4:2:2 Planar */
BI_YVU9SEP, 24, BI_DECMPEGDIB, 24, /* YUV 16:1:1 Planar */
BI_RGB, 24, BI_DECMPEGDIB, 24, /* RGB 24 */
#endif /* MPEG_SUPPORT */
#ifdef HUFF_SUPPORT
BI_DECYUVDIB, 16, BI_DECHUFFDIB, 24, /* YUV 4:2:2 Packed */
BI_YU12SEP, 24, BI_DECHUFFDIB, 24, /* YUV 4:1:1 Planar */
BI_DECSEPYUV411DIB, 24, BI_DECHUFFDIB, 24, /* YUV 4:1:1 Planar */
BI_YU16SEP, 24, BI_DECHUFFDIB, 24, /* YUV 4:2:2 Planar */
BI_DECSEPYUVDIB, 24, BI_DECHUFFDIB, 24, /* YUV 4:2:2 Planar */
#endif /* HUFF_SUPPORT */
0, 0, 0, 0
};
/*
** Input & Output Formats supported by SLIB Decompression
*/
static SupportList_t _SvDecompressionSupport[] = {
#ifdef JPEG_SUPPORT
JPEG_DIB, 8, BI_DECSEPYUVDIB, 24, /* YUV 4:2:2 Planar */
JPEG_DIB, 24, BI_DECSEPYUVDIB, 24, /* YUV 4:2:2 Planar */
MJPG_DIB, 24, BI_DECSEPYUVDIB, 24, /* YUV 4:2:2 Planar */
JPEG_DIB, 8, BI_YU16SEP, 24, /* YUV 4:2:2 Planar */
JPEG_DIB, 24, BI_YU16SEP, 24, /* YUV 4:2:2 Planar */
MJPG_DIB, 24, BI_YU16SEP, 24, /* YUV 4:2:2 Planar */
JPEG_DIB, 8, BI_DECYUVDIB, 16, /* YUV 4:2:2 Packed */
JPEG_DIB, 24, BI_DECYUVDIB, 16, /* YUV 4:2:2 Packed */
MJPG_DIB, 24, BI_DECYUVDIB, 16, /* YUV 4:2:2 Packed */
JPEG_DIB, 8, BI_YUY2, 16, /* YUV 4:2:2 Packed */
JPEG_DIB, 24, BI_YUY2, 16, /* YUV 4:2:2 Packed */
MJPG_DIB, 24, BI_YUY2, 16, /* YUV 4:2:2 Packed */
JPEG_DIB, 8, BI_BITFIELDS, 32, /* BITFIELDS */
JPEG_DIB, 24, BI_BITFIELDS, 32, /* BITFIELDS */
MJPG_DIB, 24, BI_BITFIELDS, 32, /* BITFIELDS */
JPEG_DIB, 8, BI_DECGRAYDIB, 8, /* Gray 8 */
#endif /* JPEG_SUPPORT */
#ifdef WIN32
JPEG_DIB, 8, BI_RGB, 16, /* RGB 16 */
JPEG_DIB, 24, BI_RGB, 16, /* RGB 16 */
MJPG_DIB, 24, BI_RGB, 16, /* RGB 16 */
JPEG_DIB, 8, BI_RGB, 24, /* RGB 24 */
JPEG_DIB, 24, BI_RGB, 24, /* RGB 24 */
MJPG_DIB, 24, BI_RGB, 24, /* RGB 24 */
JPEG_DIB, 8, BI_RGB, 32, /* RGB 32 */
JPEG_DIB, 24, BI_RGB, 32, /* RGB 32 */
MJPG_DIB, 24, BI_RGB, 32, /* RGB 32 */
JPEG_DIB, 8, BI_BITFIELDS, 16, /* BITFIELDS */
#ifdef H261_SUPPORT
BI_DECH261DIB, 24, BI_RGB, 16, /* RGB 16 */
BI_DECH261DIB, 24, BI_RGB, 24, /* RGB 24 */
BI_DECH261DIB, 24, BI_RGB, 32, /* RGB 32 */
#endif /* H261_SUPPORT */
#ifdef MPEG_SUPPORT
BI_DECMPEGDIB, 24, BI_RGB, 16, /* RGB 16 */
BI_DECMPEGDIB, 24, BI_RGB, 24, /* RGB 24 */
BI_DECMPEGDIB, 24, BI_RGB, 32, /* RGB 32 */
#endif /* MPEG_SUPPORT */
#endif /* WIN32 */
#ifndef WIN32
JPEG_DIB, 8, BI_DECXIMAGEDIB, 24, /* XIMAGE 24 */
JPEG_DIB, 24, BI_DECXIMAGEDIB, 24, /* XIMAGE 24 */
MJPG_DIB, 24, BI_DECXIMAGEDIB, 24, /* XIMAGE 24 */
#ifdef H261_SUPPORT
BI_DECH261DIB, 24, BI_DECXIMAGEDIB, 24, /* XIMAGE 24 */
#endif /* H261_SUPPORT */
#ifdef MPEG_SUPPORT
BI_DECMPEGDIB, 24, BI_DECXIMAGEDIB, 24, /* XIMAGE 24 */
#endif /* MPEG_SUPPORT */
#endif /* !WIN32 */
#ifdef H261_SUPPORT
BI_DECH261DIB, 24, BI_YU12SEP, 24, /* YUV 4:1:1 Planar */
BI_DECH261DIB, 24, BI_DECSEPYUV411DIB, 24, /* YUV 4:1:1 Planar */
BI_DECH261DIB, 24, BI_DECYUVDIB, 16, /* YUV 4:2:2 Packed */
BI_DECH261DIB, 24, BI_BITFIELDS, 32, /* BITFIELDS */
#endif /* H261_SUPPORT */
#ifdef H263_SUPPORT
BI_DECH263DIB, 24, BI_YU12SEP, 24, /* YUV 4:1:1 Planar */
BI_DECH263DIB, 24, BI_DECSEPYUV411DIB, 24, /* YUV 4:1:1 Planar */
BI_DECH263DIB, 24, BI_YUY2, 16, /* YUV 4:2:2 Packed */
BI_DECH263DIB, 24, BI_DECYUVDIB, 16, /* YUV 4:2:2 Packed */
#endif /* H263_SUPPORT */
#ifdef MPEG_SUPPORT
BI_DECMPEGDIB, 24, BI_YU12SEP, 24, /* YUV 4:1:1 Planar */
BI_DECMPEGDIB, 24, BI_DECSEPYUV411DIB, 24, /* YUV 4:1:1 Planar */
BI_DECMPEGDIB, 24, BI_DECYUVDIB, 16, /* YUV 4:2:2 Packed */
BI_DECMPEGDIB, 24, BI_YUY2, 16, /* YUV 4:2:2 Packed */
BI_DECMPEGDIB, 24, BI_YU16SEP, 24, /* YUV 4:2:2 Planar */
BI_DECMPEGDIB, 24, BI_BITFIELDS, 32, /* BITFIELDS */
#endif /* MPEG_SUPPORT */
#ifdef HUFF_SUPPORT
BI_DECHUFFDIB, 24, BI_YU12SEP, 24, /* YUV 4:1:1 Planar */
BI_DECHUFFDIB, 24, BI_DECSEPYUV411DIB, 24, /* YUV 4:1:1 Planar */
BI_DECHUFFDIB, 24, BI_DECYUVDIB, 16, /* YUV 4:2:2 Packed */
#endif /* HUFF_SUPPORT */
0, 0, 0, 0
};
/*
** Name: IsSupported
** Desc: Lookup the a given input and output format to see if it
** exists in a SupportList.
** Note: If OutFormat==-1 and OutBits==-1 then only input format
** is checked for support.
** If InFormat==-1 and InBits==-1 then only output format
** is checked for support.
** Return: NULL Formats not supported.
** not NULL A pointer to the list entry.
*/
static SupportList_t *IsSupported(SupportList_t *list,
int InFormat, int InBits,
int OutFormat, int OutBits)
{
if (OutFormat==-1 && OutBits==-1) /* Looking up only the Input format */
{
while (list->InFormat || list->InBits)
if (list->InFormat == InFormat && list->InBits==InBits)
return(list);
else
list++;
return(NULL);
}
if (InFormat==-1 && InBits==-1) /* Looking up only the Output format */
{
while (list->InFormat || list->InBits)
if (list->OutFormat == OutFormat && list->OutBits==OutBits)
return(list);
else
list++;
return(NULL);
}
/* Looking up both Input and Output */
while (list->InFormat || list->InBits)
if (list->InFormat == InFormat && list->InBits==InBits &&
list->OutFormat == OutFormat && list->OutBits==OutBits)
return(list);
else
list++;
return(NULL);
}
/*
** Name: SvOpenCodec
** Purpose: Open the specified codec. Return stat code.
**
** Args: CodecType = i.e. SV_JPEG_ENCODE, SV_JPEG_DECODE, etc.
** Svh = handle to software codec's Info structure.
*/
SvStatus_t SvOpenCodec (SvCodecType_e CodecType, SvHandle_t *Svh)
{
SvCodecInfo_t *Info = NULL;
_SlibDebug(_DEBUG_, printf("SvOpenCodec()\n") );
/* check if CODEC is supported */
switch (CodecType)
{
#ifdef JPEG_SUPPORT
case SV_JPEG_DECODE:
case SV_JPEG_ENCODE:
break;
#endif /* JPEG_SUPPORT */
#ifdef H261_SUPPORT
case SV_H261_ENCODE:
case SV_H261_DECODE:
break;
#endif /* H261_SUPPORT */
#ifdef H263_SUPPORT
case SV_H263_ENCODE:
case SV_H263_DECODE:
break;
#endif /* H263_SUPPORT */
#ifdef MPEG_SUPPORT
case SV_MPEG_ENCODE:
case SV_MPEG_DECODE:
case SV_MPEG2_ENCODE:
case SV_MPEG2_DECODE:
break;
#endif /* MPEG_SUPPORT */
#ifdef HUFF_SUPPORT
case SV_HUFF_ENCODE:
case SV_HUFF_DECODE:
break;
#endif /* HUFF_SUPPORT */
default:
return(SvErrorCodecType);
}
if (!Svh)
return (SvErrorBadPointer);
/*
** Allocate memory for the Codec Info structure:
*/
if ((Info = (SvCodecInfo_t *) ScAlloc(sizeof(SvCodecInfo_t))) == NULL)
return (SvErrorMemory);
memset (Info, 0, sizeof(SvCodecInfo_t));
Info->BSIn=NULL;
Info->BSOut=NULL;
Info->mode = CodecType;
Info->started = FALSE;
/*
** Allocate memory for Info structure and clear it
*/
switch (CodecType)
{
#ifdef JPEG_SUPPORT
case SV_JPEG_DECODE:
if ((Info->jdcmp = (SvJpegDecompressInfo_t *)
ScAlloc(sizeof(SvJpegDecompressInfo_t))) == NULL)
return(SvErrorMemory);
memset (Info->jdcmp, 0, sizeof(SvJpegDecompressInfo_t));
break;
case SV_JPEG_ENCODE:
if ((Info->jcomp = (SvJpegCompressInfo_t *)
ScAlloc(sizeof(SvJpegCompressInfo_t))) == NULL)
return (SvErrorMemory);
memset (Info->jcomp, 0, sizeof(SvJpegCompressInfo_t));
break;
#endif /* JPEG_SUPPORT */
#ifdef MPEG_SUPPORT
case SV_MPEG_DECODE:
case SV_MPEG2_DECODE:
if ((Info->mdcmp = (SvMpegDecompressInfo_t *)
ScAlloc(sizeof(SvMpegDecompressInfo_t))) == NULL)
return(SvErrorMemory);
memset (Info->mdcmp, 0, sizeof(SvMpegDecompressInfo_t));
Info->mdcmp->timecode0 = 0;
Info->mdcmp->timecode_state = MPEG_TIMECODE_START;
Info->mdcmp->timecodefps = 0.0F;
Info->mdcmp->fps = 0.0F;
Info->mdcmp->twostreams = 0;
Info->mdcmp->verbose=FALSE;
Info->mdcmp->quiet=TRUE;
ScBufQueueCreate(&Info->BufQ);
ScBufQueueCreate(&Info->ImageQ);
break;
case SV_MPEG_ENCODE:
case SV_MPEG2_ENCODE:
if ((Info->mcomp = (SvMpegCompressInfo_t *)
ScAlloc(sizeof(SvMpegCompressInfo_t))) == NULL)
return(SvErrorMemory);
memset (Info->mcomp, 0, sizeof(SvMpegCompressInfo_t));
Info->mcomp->quiet=1;
SvSetParamInt((SvHandle_t)Info, SV_PARAM_QUALITY, 100);
SvSetParamBoolean((SvHandle_t)Info, SV_PARAM_FASTENCODE, FALSE);
SvSetParamBoolean((SvHandle_t)Info, SV_PARAM_FASTDECODE, FALSE);
SvSetParamInt((SvHandle_t)Info, SV_PARAM_MOTIONALG, 0);
SvSetParamInt((SvHandle_t)Info, SV_PARAM_ALGFLAGS,
PARAM_ALGFLAG_HALFPEL);
SvSetParamInt((SvHandle_t)Info, SV_PARAM_BITRATE, 1152000);
SvSetParamFloat((SvHandle_t)Info, SV_PARAM_FPS, (float)25.0);
SvSetParamInt((SvHandle_t)Info, SV_PARAM_KEYSPACING, 12);
SvSetParamInt((SvHandle_t)Info, SV_PARAM_SUBKEYSPACING, 4);
ScBufQueueCreate(&Info->BufQ);
ScBufQueueCreate(&Info->ImageQ);
break;
#endif /* MPEG_SUPPORT */
#ifdef H261_SUPPORT
case SV_H261_DECODE:
if ((Info->h261 = (SvH261Info_t *)
ScAlloc(sizeof(SvH261Info_t))) == NULL)
return(SvErrorMemory);
memset (Info->h261, 0, sizeof(SvH261Info_t));
Info->h261->inited=FALSE;
SvSetParamInt((SvHandle_t)Info, SV_PARAM_QUALITY, 100);
ScBufQueueCreate(&Info->BufQ);
ScBufQueueCreate(&Info->ImageQ);
break;
case SV_H261_ENCODE:
if ((Info->h261 = (SvH261Info_t *)
ScAlloc(sizeof(SvH261Info_t))) == NULL)
return(SvErrorMemory);
memset (Info->h261, 0, sizeof(SvH261Info_t));
Info->h261->inited=FALSE;
SvSetParamInt((SvHandle_t)Info, SV_PARAM_QUALITY, 100);
SvSetParamInt((SvHandle_t)Info, SV_PARAM_MOTIONALG, ME_BRUTE);
SvSetParamInt((SvHandle_t)Info, SV_PARAM_MOTIONSEARCH, 5);
SvSetParamInt((SvHandle_t)Info, SV_PARAM_MOTIONTHRESH, 600);
SvSetParamInt((SvHandle_t)Info, SV_PARAM_ALGFLAGS, 0);
SvSetParamInt((SvHandle_t)Info, SV_PARAM_BITRATE, 352000);
SvSetParamInt((SvHandle_t)Info, SV_PARAM_QUANTI, 10); /* for VBR */
SvSetParamInt((SvHandle_t)Info, SV_PARAM_QUANTP, 10);
SvSetParamInt((SvHandle_t)Info, SV_PARAM_PACKETSIZE, 512);
SvSetParamFloat((SvHandle_t)Info, SV_PARAM_FPS, (float)15.0);
ScBufQueueCreate(&Info->BufQ);
ScBufQueueCreate(&Info->ImageQ);
break;
#endif /* H261_SUPPORT */
#ifdef H263_SUPPORT
case SV_H263_DECODE:
if ((Info->h263dcmp = (SvH263DecompressInfo_t *)
ScAlloc(sizeof(SvH263DecompressInfo_t))) == NULL)
return(SvErrorMemory);
memset (Info->h263dcmp, 0, sizeof(SvH263DecompressInfo_t));
Info->h263dcmp->inited=FALSE;
ScBufQueueCreate(&Info->BufQ);
ScBufQueueCreate(&Info->ImageQ);
break;
case SV_H263_ENCODE:
if ((Info->h263comp = (SvH263CompressInfo_t *)
ScAlloc(sizeof(SvH263CompressInfo_t))) == NULL)
return(SvErrorMemory);
memset (Info->h263comp, 0, sizeof(SvH263CompressInfo_t));
Info->h263comp->inited=FALSE;
SvSetParamInt((SvHandle_t)Info, SV_PARAM_MOTIONALG, 0);
SvSetParamInt((SvHandle_t)Info, SV_PARAM_BITRATE, 0);
SvSetParamFloat((SvHandle_t)Info, SV_PARAM_FPS, (float)30.0);
SvSetParamInt((SvHandle_t)Info, SV_PARAM_ALGFLAGS, 0);
SvSetParamInt((SvHandle_t)Info, SV_PARAM_PACKETSIZE, 512);
SvSetParamInt((SvHandle_t)Info, SV_PARAM_QUANTI, 10);
SvSetParamInt((SvHandle_t)Info, SV_PARAM_QUANTP, 10);
SvSetParamInt((SvHandle_t)Info, SV_PARAM_QUALITY, 0);
SvSetParamInt((SvHandle_t)Info, SV_PARAM_KEYSPACING, 120);
ScBufQueueCreate(&Info->BufQ);
ScBufQueueCreate(&Info->ImageQ);
break;
#endif /* H263_SUPPORT */
#ifdef HUFF_SUPPORT
case SV_HUFF_DECODE:
case SV_HUFF_ENCODE:
if ((Info->huff = (SvHuffInfo_t *)
ScAlloc(sizeof(SvHuffInfo_t))) == NULL)
return(SvErrorMemory);
memset (Info->huff, 0, sizeof(SvHuffInfo_t));
ScBufQueueCreate(&Info->BufQ);
ScBufQueueCreate(&Info->ImageQ);
break;
#endif /* HUFF_SUPPORT */
}
*Svh = (SvHandle_t) Info; /* Return handle */
_SlibDebug(_DEBUG_, printf("SvOpenCodec() returns Svh=%p\n", *Svh) );
return(NoErrors);
}
/*
** Name: SvCloseCodec
** Purpose: Closes the specified codec. Free the Info structure
**
** Args: Svh = handle to software codec's Info structure.
**
** XXX - needs to change since now we have compression also, i.e.
** Svh should be handle to the CodecInfo structure. (VB)
*/
SvStatus_t SvCloseCodec (SvHandle_t Svh)
{
SvCodecInfo_t *Info = (SvCodecInfo_t *)Svh;
_SlibDebug(_DEBUG_, printf("SvCloseCodec()\n") );
if (!Info)
return(SvErrorCodecHandle);
if (Info->BSIn)
ScBSDestroy(Info->BSIn);
if (Info->BSOut)
ScBSDestroy(Info->BSOut);
if (Info->BufQ);
ScBufQueueDestroy(Info->BufQ);
if (Info->ImageQ);
ScBufQueueDestroy(Info->ImageQ);
switch (Info->mode) /* free all associated codec memory */
{
#ifdef JPEG_SUPPORT
case SV_JPEG_DECODE:
{
int i;
for (i = 0; i < 4; i++) {
if (Info->jdcmp->DcHt[i])
ScPaFree(Info->jdcmp->DcHt[i]);
if (Info->jdcmp->AcHt[i])
ScPaFree(Info->jdcmp->AcHt[i]);
}
if (Info->jdcmp->compinfo)
ScFree(Info->jdcmp->compinfo);
if (Info->jdcmp) {
if (Info->jdcmp->TempImage)
ScPaFree(Info->jdcmp->TempImage);
if (Info->jdcmp->_SvBlockPtr)
ScFree(Info->jdcmp->_SvBlockPtr);
ScFree(Info->jdcmp);
}
}
break;
case SV_JPEG_ENCODE:
{
int i;
for (i = 0 ; i < Info->jcomp->NumComponents ; i++)
if (Info->jcomp->Qt[i])
ScPaFree(Info->jcomp->Qt[i]);
for (i = 0; i < 4; i++) {
if (Info->jcomp->DcHt[i])
ScPaFree(Info->jcomp->DcHt[i]);
if (Info->jcomp->AcHt[i])
ScPaFree(Info->jcomp->AcHt[i]);
}
if (Info->jcomp->compinfo)
ScFree(Info->jcomp->compinfo);
if (Info->jcomp) {
if (Info->jcomp->BlkBuffer)
ScPaFree(Info->jcomp->BlkBuffer);
if (Info->jcomp->BlkTable)
ScPaFree(Info->jcomp->BlkTable);
ScFree(Info->jcomp);
}
}
break;
#endif /* JPEG_SUPPORT */
#ifdef H261_SUPPORT
case SV_H261_ENCODE:
if (Info->h261)
{
svH261CompressFree(Info);
ScFree(Info->h261);
}
break;
case SV_H261_DECODE:
if (Info->h261)
{
svH261DecompressFree(Info);
ScFree(Info->h261);
}
break;
#endif /* H261_SUPPORT */
#ifdef H263_SUPPORT
case SV_H263_DECODE:
if (Info->h263dcmp)
{
svH263FreeDecompressor(Info);
ScFree(Info->h263dcmp);
}
break;
case SV_H263_ENCODE:
if (Info->h263comp)
{
svH263FreeCompressor(Info);
ScFree(Info->h263comp);
}
break;
#endif /* H263_SUPPORT */
#ifdef MPEG_SUPPORT
case SV_MPEG_DECODE:
case SV_MPEG2_DECODE:
if (Info->mdcmp) {
sv_MpegFreeDecoder(Info);
ScFree(Info->mdcmp);
}
break;
case SV_MPEG_ENCODE:
case SV_MPEG2_ENCODE:
if (Info->mcomp) {
ScFree(Info->mcomp);
}
break;
#endif /* MPEG_SUPPORT */
#ifdef HUFF_SUPPORT
case SV_HUFF_DECODE:
case SV_HUFF_ENCODE:
if (Info->huff) {
sv_HuffFreeDecoder(Info);
ScFree(Info->huff);
}
break;
break;
#endif /* HUFF_SUPPORT */
}
/*
** Free Info structure
*/
ScFree(Info);
return(NoErrors);
}
/*
** Name: SvDecompressBegin
** Purpose: Initialize the Decompression Codec. Call after SvOpenCodec &
** before SvDecompress (SvDecompress will call SvDecompressBegin
** on first call to codec after open if user doesn't call it)
**
** Args: Svh = handle to software codec's Info structure.
** ImgIn = format of input (uncompressed) image
** ImgOut = format of output (compressed) image
*/
SvStatus_t SvDecompressBegin (SvHandle_t Svh, BITMAPINFOHEADER *ImgIn,
BITMAPINFOHEADER *ImgOut)
{
int stat;
SvCodecInfo_t *Info = (SvCodecInfo_t *)Svh;
_SlibDebug(_DEBUG_, printf("SvDecompressBegin()\n") );
if (!Info)
return(SvErrorCodecHandle);
if (Info->started)
return(SvErrorNone);
/* if no Image header provided, use previous headers */
if (!ImgIn)
ImgIn = &Info->InputFormat;
if (!ImgOut)
ImgOut = &Info->OutputFormat;
stat=SvDecompressQuery (Svh, ImgIn, ImgOut);
RETURN_ON_ERROR(stat);
/*
** Save input & output formats for SvDecompress
*/
sv_copy_bmh(ImgIn, &Info->InputFormat);
sv_copy_bmh(ImgOut, &Info->OutputFormat);
Info->Width = Info->InputFormat.biWidth;
Info->Height = abs(Info->InputFormat.biHeight);
switch (Info->mode)
{
#ifdef JPEG_SUPPORT
case SV_JPEG_DECODE:
{
SvJpegDecompressInfo_t *DInfo;
/*
** Load the default Huffman tablse
*/
stat = sv_LoadDefaultHTable (Info);
RETURN_ON_ERROR (stat);
stat = sv_InitJpegDecoder (Info);
RETURN_ON_ERROR (stat);
/*
** Video-specific information will be filled in during processing
** of first frame
*/
DInfo = Info->jdcmp;
DInfo->InfoFilled = 0;
DInfo->ReInit = 1;
DInfo->DecompressStarted = TRUE;
DInfo->TempImage = NULL;
break;
}
#endif
#ifdef MPEG_SUPPORT
case SV_MPEG_DECODE:
case SV_MPEG2_DECODE:
Info->mdcmp->DecompressStarted = TRUE;
/* the default data source is the buffer queue */
if (Info->BSIn)
ScBSReset(Info->BSIn);
else
stat=SvSetDataSource (Svh, SV_USE_BUFFER_QUEUE, 0, NULL, 0);
RETURN_ON_ERROR (stat);
stat = sv_MpegInitDecoder(Info);
RETURN_ON_ERROR (stat);
break;
#endif /* MPEG_SUPPORT */
#ifdef H261_SUPPORT
case SV_H261_DECODE:
stat = svH261Init(Info);
RETURN_ON_ERROR (stat);
break;
#endif /* H261_SUPPORT */
#ifdef H263_SUPPORT
case SV_H263_DECODE:
stat = svH263InitDecompressor(Info);
RETURN_ON_ERROR (stat);
break;
#endif /* H263_SUPPORT */
#ifdef HUFF_SUPPORT
case SV_HUFF_DECODE:
Info->huff->DecompressStarted = TRUE;
/* the default data source is the buffer queue */
if (Info->BSIn)
ScBSReset(Info->BSIn);
else
stat=SvSetDataSource (Svh, SV_USE_BUFFER_QUEUE, 0, NULL, 0);
RETURN_ON_ERROR (stat);
stat = sv_HuffInitDecoder(Info);
RETURN_ON_ERROR (stat);
break;
#endif /* HUFF_SUPPORT */
}
Info->started=TRUE;
return (NoErrors);
}
/*
** Name: SvGetDecompressSize
** Purpose: Return minimum data buffer size to receive decompressed data
** for current settings on codec
**
** Args: Svh = handle to software codec's Info structure.
** MinSize = Returns minimum buffer size required
*/
SvStatus_t SvGetDecompressSize (SvHandle_t Svh, int *MinSize)
{
int pixels,lines;
SvCodecInfo_t *Info = (SvCodecInfo_t *)Svh;
if (!Info)
return(SvErrorCodecHandle);
switch (Info->mode) /* check that decompressor was started */
{
#ifdef JPEG_SUPPORT
case SV_JPEG_DECODE:
if (!Info->jdcmp->DecompressStarted)
return(SvErrorDcmpNotStarted);
break;
#endif /* JPEG_SUPPORT */
#ifdef MPEG_SUPPORT
case SV_MPEG_DECODE:
case SV_MPEG2_DECODE:
if (!Info->mdcmp->DecompressStarted)
return(SvErrorDcmpNotStarted);
break;
#endif /* MPEG_SUPPORT */
default:
break;
}
if (!MinSize)
return(SvErrorBadPointer);
pixels = Info->OutputFormat.biWidth;
lines = Info->OutputFormat.biHeight;
if (lines < 0) lines = -lines;
_SlibDebug(_VERBOSE_,
printf("OutputFormat.biWidth=%d OutputFormat.biHeight=%d\n",
pixels, lines) );
switch (Info->mode)
{
#ifdef JPEG_SUPPORT
case SV_JPEG_DECODE:
/*
** On output, accept: 8, 16 or 24 bit uncompressed RGB
** or YUV formats, 32 bit uncompressed RGB
*/
if (Info->OutputFormat.biBitCount == 8)
*MinSize = pixels * lines;
else if (Info->OutputFormat.biBitCount == 24) {
if (Info->OutputFormat.biCompression == BI_RGB)
*MinSize = 3 * pixels * lines;
else if (Info->OutputFormat.biCompression == BI_DECSEPRGBDIB)
*MinSize = 3 * pixels * lines;
else if (IsYUV422Packed(Info->OutputFormat.biCompression))
*MinSize = 2 * pixels * lines;
else if (Info->OutputFormat.biCompression == BI_DECXIMAGEDIB)
*MinSize = 4 * pixels * lines;
else if (IsYUV422Sep(Info->OutputFormat.biCompression))
*MinSize = 2 * pixels * lines;
else if (IsYUV411Sep(Info->OutputFormat.biCompression))
*MinSize = 2 * pixels * lines;
else
return(SvErrorUnrecognizedFormat);
}
else if (Info->OutputFormat.biBitCount == 16) {
if (IsYUV422Packed(Info->OutputFormat.biCompression))
*MinSize = 2 * pixels * lines;
else if (Info->OutputFormat.biCompression == BI_RGB)
*MinSize = 2 * pixels * lines;
}
else if (Info->OutputFormat.biBitCount == 32) {
if (Info->OutputFormat.biCompression == BI_RGB ||
Info->OutputFormat.biCompression == BI_BITFIELDS)
*MinSize = 4 * pixels * lines;
}
break;
#endif /* JPEG_SUPPORT */
#ifdef MPEG_SUPPORT
case SV_MPEG_DECODE:
case SV_MPEG2_DECODE:
/*
** MPEG multibuffer size = 3 pictures*(1Y + 1/4 U + 1/4 V)*imagesize
*/
if (IsYUV422Sep(SvGetParamInt(Svh, SV_PARAM_FINALFORMAT)) ||
IsYUV422Packed(SvGetParamInt(Svh, SV_PARAM_FINALFORMAT)))
*MinSize = 3 * pixels * lines * 2; /* 4:2:2 */
else
*MinSize = 3 * (pixels * lines * 3)/2; /* 4:1:1 */
break;
#endif /* MPEG_SUPPORT */
#ifdef H261_SUPPORT
case SV_H261_DECODE:
*MinSize = 3 * (pixels * lines * 3)/2; /* 4:1:1 */
break;
#endif /* H261_SUPPORT */
#ifdef H263_SUPPORT
case SV_H263_DECODE:
*MinSize = 3 * (pixels * lines * 3)/2; /* 4:1:1 */
break;
#endif /* H263_SUPPORT */
default:
return(SvErrorUnrecognizedFormat);
}
return(NoErrors);
}
/*
** Name: SvDecompressQuery
** Purpose: Determine if Codec can decompress desired format
**
** Args: Svh = handle to software codec's Info structure.
** ImgIn = Pointer to BITMAPINFOHEADER structure describing format
** ImgOut = Pointer to BITMAPINFOHEADER structure describing format
*/
SvStatus_t SvDecompressQuery (SvHandle_t Svh, BITMAPINFOHEADER *ImgIn,
BITMAPINFOHEADER *ImgOut)
{
SvCodecInfo_t *Info = (SvCodecInfo_t *)Svh;
if (!Info)
return(SvErrorCodecHandle);
if (!ImgIn && !ImgOut)
return(SvErrorBadPointer);
if (!IsSupported(_SvDecompressionSupport,
ImgIn ? ImgIn->biCompression : -1,
ImgIn ? ImgIn->biBitCount : -1,
ImgOut ? ImgOut->biCompression : -1,
ImgOut ? ImgOut->biBitCount : -1))
return(SvErrorUnrecognizedFormat);
if (ImgOut) /* Query output format */
{
/*
** XXX - check to see if the # of output lines/# of output
** pixels/line are a multiple of 8. If not can't decompress
** Note: This is an artifical restriction since the JPEG
** bitream will always be a multiple of 8x8, so we
** should have no problems decoding, only on the
** output will be have to add an extra copy operation
** XXX - will address/remove this restriction in the
** later release (VB)
*/
if (ImgOut->biWidth <= 0 || ImgOut->biHeight == 0)
return(SvErrorBadImageSize);
switch (Info->mode)
{
#ifdef JPEG_SUPPORT
case SV_JPEG_DECODE: /* 8x8 restriction */
if ((ImgOut->biWidth%8) || (ImgOut->biHeight%8))
return(SvErrorBadImageSize);
break;
#endif /* JPEG_SUPPORT */
#ifdef MPEG_SUPPORT
case SV_MPEG_DECODE:
case SV_MPEG2_DECODE:
/* MPEG 16x16 - because of Software Renderer YUV limitation */
if ((ImgOut->biWidth%16) || (ImgOut->biHeight%16))
return(SvErrorBadImageSize);
/* Reject requests to scale during decompression - renderer's job */
if (ImgIn && ImgOut &&
(ImgIn->biWidth != ImgOut->biWidth) ||
(abs(ImgIn->biHeight) != abs(ImgOut->biHeight)))
return (SvErrorBadImageSize);
break;
#endif /* MPEG_SUPPORT */
#ifdef H261_SUPPORT
case SV_H261_DECODE:
/* H261 16x16 - because of Software Renderer YUV limitation */
if ((ImgOut->biWidth%16) || (ImgOut->biHeight%16))
return(SvErrorBadImageSize);
if ((ImgOut->biWidth!=CIF_WIDTH && ImgOut->biWidth!=QCIF_WIDTH) ||
(abs(ImgOut->biHeight)!=CIF_HEIGHT && abs(ImgOut->biHeight)!=QCIF_HEIGHT))
return (SvErrorBadImageSize);
/* Reject requests to scale during decompression - renderer's job */
if (ImgIn && ImgOut &&
(ImgIn->biWidth != ImgOut->biWidth) ||
(abs(ImgIn->biHeight) != abs(ImgOut->biHeight)))
return (SvErrorBadImageSize);
break;
#endif /* H261_SUPPORT */
default:
break;
}
if (ImgOut->biCompression == BI_BITFIELDS &&
ValidateBI_BITFIELDS(ImgOut) == InvalidBI_BITFIELDS)
return (SvErrorUnrecognizedFormat);
}
if (ImgIn) /* Query input format also */
{
if (ImgIn->biWidth <= 0 || ImgIn->biHeight == 0)
return(SvErrorBadImageSize);
}
return(NoErrors);
}
/*
** Name: SvDecompress
** Purpose: Decompress a frame CompData -> YUV or RGB
**
** Args: Svh = handle to software codec's Info structure.
** Data = For JPEG points to compressed data (INPUT)
** For MPEG & H261, points to MultiBuf
** MaxDataSize = Length of Data buffer
** Image = buffer for decompressed data (OUTPUT)
** MaxImageSize = Size of output image buffer
**
*/
SvStatus_t SvDecompress(SvHandle_t Svh, u_char *Data, int MaxDataSize,
u_char *Image, int MaxImageSize)
{
int stat=NoErrors, UsedQ=FALSE, ImageSize;
SvCodecInfo_t *Info = (SvCodecInfo_t *)Svh;
u_char *YData=NULL, *CbData=NULL, *CrData=NULL;
int pixels, lines;
SvCallbackInfo_t CB;
u_char *ReturnImage=NULL;
_SlibDebug(_VERBOSE_, printf("SvDecompress() In\n") );
if (!Info)
return(SvErrorCodecHandle);
if (!Info->started)
return(SvErrorDcmpNotStarted);
if (!Data && !Info->BSIn)
return(SvErrorBadPointer);
/*
** If no image buffer is supplied, see if the Image Queue
** has any. If not do a callback to get a buffer.
*/
if (Image == NULL && Info->ImageQ)
{
if (ScBufQueueGetNum(Info->ImageQ))
{
ScBufQueueGetHead(Info->ImageQ, &Image, &MaxImageSize);
ScBufQueueRemove(Info->ImageQ);
UsedQ = TRUE;
_SlibDebug(_VERBOSE_, printf("SvDecompress() Got Image %p from Q\n",
Image) );
}
else if (Info->CallbackFunction)
{
CB.Message = CB_END_BUFFERS;
CB.Data = NULL;
CB.DataSize = 0;
CB.DataUsed = 0;
CB.DataType = CB_DATA_IMAGE;
CB.UserData = Info->BSIn?Info->BSIn->UserData:NULL;
CB.Action = CB_ACTION_CONTINUE;
_SlibDebug(_VERBOSE_,
printf("SvDecompress() Calling callback for Image\n") );
(*(Info->CallbackFunction))(Svh, &CB, NULL);
if (CB.Action == CB_ACTION_END)
{
_SlibDebug(_DEBUG_,
printf("SvDecompress() CB.Action = CB_ACTION_END\n") );
return(SvErrorClientEnd);
}
else if (ScBufQueueGetNum(Info->ImageQ))
{
ScBufQueueGetHead(Info->ImageQ, &Image, &MaxImageSize);
ScBufQueueRemove(Info->ImageQ);
UsedQ = TRUE;
_SlibDebug(_VERBOSE_,
printf("SvDecompress() Got Image %p from Q\n", Image) );
}
else
return(SvErrorNoImageBuffer);
}
}
if (!Image)
return(SvErrorNoImageBuffer);
ImageSize=MaxImageSize;
pixels = Info->OutputFormat.biWidth;
lines = Info->OutputFormat.biHeight;
if (lines<0) lines=-lines;
/*
** Decompress an image
*/
switch (Info->mode)
{
#ifdef MPEG_SUPPORT
case SV_MPEG_DECODE:
case SV_MPEG2_DECODE:
{
SvMpegDecompressInfo_t *MDInfo;
_SlibDebug(_DEBUG_, printf("SvDecompress() SV_MPEG_DECODE\n") );
if (!(MDInfo = Info->mdcmp))
return(SvErrorBadPointer);
if (!MDInfo->DecompressStarted)
return(SvErrorDcmpNotStarted);
if (MaxDataSize < MDInfo->finalbufsize)
return(SvErrorSmallBuffer);
if (!Data)
return(SvErrorBadPointer);
stat = sv_MpegDecompressFrame(Info, Data, &ReturnImage);
RETURN_ON_ERROR(stat);
/*
** Because the ReturnImage is a pointer into Data
** we need to copy it (do a format conversion if necessary).
*/
switch (Info->OutputFormat.biCompression)
{
case BI_YU12SEP:
/* native format is 4:1:1 planar, just copy */
ImageSize=(3 * lines * pixels)/2;
if (ImageSize > MaxImageSize)
return(SvErrorSmallBuffer);
memcpy(Image, ReturnImage, ImageSize);
break;
case BI_DECYUVDIB:
case BI_YUY2:
case BI_S422: /* 4:1:1 planar -> 4:2:2 interleaved */
ImageSize=(3 * lines * pixels)/2;
if (ImageSize > MaxImageSize)
return(SvErrorSmallBuffer);
ScSepYUVto422i(Image, Image+(lines*pixels),
Image+(lines*pixels*5)/4,
ReturnImage, pixels, lines);
break;
default: /* 4:1:1 planar -> RGB */
if (Info->OutputFormat.biCompression==BI_DECXIMAGEDIB)
ImageSize=lines*pixels *
(Info->OutputFormat.biBitCount==24 ? 4 : 1);
else
ImageSize=lines*pixels * (Info->OutputFormat.biBitCount/8);
if (ImageSize > MaxImageSize)
return(SvErrorSmallBuffer);
YData = ReturnImage;
CbData = YData + (pixels * lines);
CrData = CbData + (pixels * lines)/4;
ScYuv411ToRgb(&Info->OutputFormat, YData, CbData, CrData,
Image, pixels, lines, pixels);
break;
}
}
break;
#endif /* MPEG_SUPPORT */
#ifdef H261_SUPPORT
case SV_H261_DECODE:
{
SvH261Info_t *H261 = Info->h261;
_SlibDebug(_DEBUG_, printf("SvDecompress() SV_H261_DECODE\n") );
if (!H261)
return(SvErrorBadPointer);
if (!Data)
return(SvErrorBadPointer);
_SlibDebug(_DEBUG_, printf("sv_DecompressH261(Data=%p)\n",Data) );
stat=svH261Decompress(Info, Data, &ReturnImage);
if (stat==NoErrors)
{
/*
** Because the ReturnImage is a pointer into Data
** we need to copy it (do a format conversion if necessary).
*/
switch (Info->OutputFormat.biCompression)
{
case BI_YU12SEP:
/* native format is 4:1:1 planar, just copy */
ImageSize=(3 * lines * pixels)/2;
if (ImageSize > MaxImageSize)
return(SvErrorSmallBuffer);
memcpy(Image, ReturnImage, ImageSize);
break;
case BI_DECYUVDIB:
case BI_YUY2:
case BI_S422:
/* 4:1:1 planar -> 4:2:2 interleaved */
ImageSize=(3 * lines * pixels)/2;
if (ImageSize > MaxImageSize)
return(SvErrorSmallBuffer);
ScSepYUVto422i(Image, Image+(lines*pixels),
Image+(lines*pixels*5)/4,
ReturnImage, pixels, lines);
break;
default:
if (Info->OutputFormat.biCompression==BI_DECXIMAGEDIB)
ImageSize=lines*pixels *
(Info->OutputFormat.biBitCount==24 ? 4 : 1);
else
ImageSize=lines*pixels * (Info->OutputFormat.biBitCount/8);
if (ImageSize > MaxImageSize)
return(SvErrorSmallBuffer);
YData = ReturnImage;
CbData = YData + (pixels * lines * sizeof(u_char));
CrData = CbData + ((pixels * lines * sizeof(u_char))/4);
ScYuv411ToRgb(&Info->OutputFormat, YData, CbData, CrData,
Image, pixels, lines, pixels);
break;
}
}
else
{
ImageSize=0;
if (Info->CallbackFunction)
{
CB.Message = CB_SEQ_END;
CB.Data = NULL;
CB.DataSize = 0;
CB.DataType = CB_DATA_NONE;
CB.UserData = Info->BSIn?Info->BSIn->UserData:NULL;
CB.Action = CB_ACTION_CONTINUE;
(*Info->CallbackFunction)(Svh, &CB, NULL);
_SlibDebug(_DEBUG_,
printf("H261 Callback: CB_SEQ_END Data = 0x%x Action = %d\n",
CB.Data, CB.Action) );
if (CB.Action == CB_ACTION_END)
return (ScErrorClientEnd);
}
}
}
break;
#endif /* H261_SUPPORT */
#ifdef H263_SUPPORT
case SV_H263_DECODE:
{
SvH263DecompressInfo_t *H263Info = Info->h263dcmp;
_SlibDebug(_DEBUG_, printf("SvDecompress() SV_H261_DECODE\n") );
if (!H263Info)
return(SvErrorBadPointer);
_SlibDebug(_DEBUG_, printf("svH263Decompress(Data=%p)\n",Data) );
stat=svH263Decompress(Info, &ReturnImage);
if (stat==NoErrors)
{
/*
** Because the ReturnImage is a pointer into Data
** we need to copy it (do a format conversion if necessary).
*/
switch (Info->OutputFormat.biCompression)
{
case BI_YU12SEP:
/* native format is 4:1:1 planar, just copy */
ImageSize=(3 * lines * pixels)/2;
if (ImageSize > MaxImageSize)
return(SvErrorSmallBuffer);
memcpy(Image, ReturnImage, ImageSize);
break;
case BI_DECYUVDIB:
case BI_YUY2:
case BI_S422:
/* 4:1:1 planar -> 4:2:2 interleaved */
ImageSize=(3 * lines * pixels)/2;
if (ImageSize > MaxImageSize)
return(SvErrorSmallBuffer);
ScSepYUVto422i(Image, Image+(lines*pixels),
Image+(lines*pixels*5)/4,
ReturnImage, pixels, lines);
break;
default:
if (Info->OutputFormat.biCompression==BI_DECXIMAGEDIB)
ImageSize=lines*pixels *
(Info->OutputFormat.biBitCount==24 ? 4 : 1);
else
ImageSize=lines*pixels * (Info->OutputFormat.biBitCount/8);
if (ImageSize > MaxImageSize)
return(SvErrorSmallBuffer);
YData = ReturnImage;
CbData = YData + (pixels * lines * sizeof(u_char));
CrData = CbData + ((pixels * lines * sizeof(u_char))/4);
ScYuv411ToRgb(&Info->OutputFormat, YData, CbData, CrData,
Image, pixels, lines, pixels);
break;
}
}
else
{
ImageSize=0;
if (Info->CallbackFunction)
{
CB.Message = CB_SEQ_END;
CB.Data = NULL;
CB.DataSize = 0;
CB.DataType = CB_DATA_NONE;
CB.UserData = Info->BSIn?Info->BSIn->UserData:NULL;
CB.Action = CB_ACTION_CONTINUE;
(*Info->CallbackFunction)(Svh, &CB, NULL);
_SlibDebug(_DEBUG_,
printf("H263 Callback: CB_SEQ_END Data = 0x%x Action = %d\n",
CB.Data, CB.Action) );
if (CB.Action == CB_ACTION_END)
return (ScErrorClientEnd);
}
}
}
break;
#endif /* H263_SUPPORT */
#ifdef JPEG_SUPPORT
case SV_JPEG_DECODE:
{
SvJpegDecompressInfo_t *DInfo;
register int i;
JPEGINFOHEADER *jpegbm;
int maxMcu;
EXBMINFOHEADER * exbi;
_SlibDebug(_DEBUG_, printf("SvDecompress() SV_JPEG_DECODE\n") );
if (!(DInfo = Info->jdcmp))
return(SvErrorBadPointer);
exbi = (EXBMINFOHEADER *)&Info->InputFormat;
jpegbm = (JPEGINFOHEADER *)(
(unsigned long)exbi + exbi->biExtDataOffset);
/*
** In case the application forgot to call SvDecompressBegin().
*/
if (!DInfo->DecompressStarted)
return(SvErrorDcmpNotStarted);
/*
** If desired output is not separate YUV components, we have to
** convert from Sep. YUV to desired format. Create intermediate image.
*/
_SlibDebug(_DEBUG_, printf ("JPEGBitsPerSample %d \n",
jpegbm->JPEGBitsPerSample) );
if (lines < 0) lines = -lines;
_SlibDebug(_DEBUG_,
printf ("JPEG_RGB : %d - ", JPEG_RGB);
if (jpegbm->JPEGColorSpaceID == JPEG_RGB)
printf ("Color Space is RGB \n");
else
printf ("Color Space is %d \n", jpegbm->JPEGColorSpaceID) );
if (!IsYUV422Sep(Info->OutputFormat.biCompression) &&
!IsYUV411Sep(Info->OutputFormat.biCompression) &&
Info->OutputFormat.biCompression != BI_DECGRAYDIB)
{
/*
** should be done only once for each instance of the CODEC.
** - Note: this forces us to check the size parameters (pixels &
** lines) for each image to be decompressed. Should we
** support sequences that do not have constant frame sizes?
*/
if (!DInfo->TempImage) {
DInfo->TempImage = (u_char *)ScPaMalloc (3 * pixels * lines);
if (DInfo->TempImage == NULL)
return(SvErrorMemory);
}
YData = DInfo->TempImage;
CbData = YData + (pixels * lines * sizeof(u_char));
CrData = CbData + (pixels * lines * sizeof(u_char));
}
else {
/*
** For YUV Planar formats, no need to translate.
** Get pointers to individual components.
*/
_SlibDebug(_DEBUG_, printf ("sv_GetYUVComponentPointers\n") );
stat = sv_GetYUVComponentPointers(Info->OutputFormat.biCompression,
pixels, lines, Image, MaxImageSize,
&YData, &CbData, &CrData);
RETURN_ON_ERROR (stat);
}
_SlibDebug(_DEBUG_, printf ("sv_ParseFrame\n") );
stat = sv_ParseFrame (Data, MaxDataSize, Info);
RETURN_ON_ERROR (stat);
/*
** Fill Info structure with video-specific data on first frame
*/
if (!DInfo->InfoFilled) {
_SlibDebug(_DEBUG_, printf ("sv_InitJpegDecoder\n") );
stat = sv_InitJpegDecoder (Info);
RETURN_ON_ERROR (stat);
DInfo->InfoFilled = 1;
/*
** Error checking:
** make the assumption that for MJPEG we need to check for
** valid subsampling only once at the start of the seqence
*/
_SlibDebug(_DEBUG_, printf ("sv_CheckChroma\n") );
stat = sv_CheckChroma(Info);
RETURN_ON_ERROR (stat);
}
/*
** Decompress everything into MCU's
*/
if (!DInfo->ReInit) /* Reset the JPEG compressor */
sv_ReInitJpegDecoder (Info);
maxMcu = DInfo->MCUsPerRow * DInfo->MCUrowsInScan;
if (DInfo->ReInit)
DInfo->ReInit = 0;
DInfo->CurrBlockNumber = 0;
/*
** Create the BlockPtr array for the output buffers
*/
if ((YData != DInfo->Old_YData) ||
(CbData != DInfo->Old_CbData) ||
(CrData != DInfo->Old_CrData))
{
DInfo->Old_YData =YData;
DInfo->Old_CbData=CbData;
DInfo->Old_CrData=CrData;
stat = sv_MakeDecoderBlkTable (Info);
RETURN_ON_ERROR (stat);
}
CB.Message = CB_PROCESSING;
for (i = 0; i < maxMcu; i++) {
#if 0
if ((Info->CallbackFunction) && ((i % MCU_CALLBACK_COUNT) == 0)) {
(*Info->CallbackFunction)(Svh, &CB, &PictureInfo);
if (CB.Action == CB_ACTION_END)
return(SvErrorClientEnd);
}
#endif
_SlibDebug(_DEBUG_, printf ("sv_DecodeJpeg\n") );
stat = sv_DecodeJpeg (Info);
RETURN_ON_ERROR (stat);
}
#if 0
/*
** Check for multiple scans in the JPEG file
** - we do not support multiple scans
*/
if (sv_ParseScanHeader (Info) != SvErrorEOI)
_SlibDebug(_DEBUG_ || _WARN_ || _VERBOSE_,
printf(" *** Warning ***, Multiple Scans detected, unsupported\n") );
#endif
if (DInfo->compinfo[0].Vsf==2) /* 4:1:1->4:2:2 */
{
if (IsYUV422Packed(Info->OutputFormat.biCompression))
ScConvert411sTo422i_C(YData, CbData, CrData, Image,
pixels, lines);
else if IsYUV422Sep(Info->OutputFormat.biCompression)
ScConvert411sTo422s_C(YData, CbData, CrData, Image,
pixels, lines);
else if IsYUV411Sep(Info->OutputFormat.biCompression)
{
if (YData!=Image)
memcpy(Image, YData, pixels*lines);
memcpy(Image+pixels*lines, CbData, (pixels*lines)/4);
memcpy(Image+(pixels*lines*5)/4, CrData, (pixels*lines)/4);
}
else
{
ScConvert411sTo422s_C(YData, CbData, CrData, YData,
pixels, lines);
ScConvertSepYUVToOther(&Info->InputFormat, &Info->OutputFormat,
Image, YData, CbData, CrData);
}
}
else if (!IsYUV422Sep(Info->OutputFormat.biCompression) &&
!IsYUV411Sep(Info->OutputFormat.biCompression) &&
Info->OutputFormat.biCompression != BI_DECGRAYDIB)
ScConvertSepYUVToOther(&Info->InputFormat, &Info->OutputFormat,
Image, YData, CbData, CrData);
}
break; /* SV_JPEG_DECODE */
#endif /* JPEG_SUPPORT */
#ifdef HUFF_SUPPORT
case SV_HUFF_DECODE:
{
SvHuffInfo_t *HInfo;
_SlibDebug(_DEBUG_, printf("SvDecompress() SV_HUFF_DECODE\n") );
if (!(HInfo = Info->huff))
return(SvErrorBadPointer);
if (!HInfo->DecompressStarted)
return(SvErrorDcmpNotStarted);
stat = sv_HuffDecodeFrame(Info, Image);
RETURN_ON_ERROR(stat);
}
break;
#endif /* HUFF_SUPPORT */
default:
return(SvErrorCodecType);
}
Info->NumOperations++;
if (Info->CallbackFunction)
{
if (ImageSize>0)
{
CB.Message = CB_FRAME_READY;
CB.Data = Image;
CB.DataSize = MaxImageSize;
CB.DataUsed = ImageSize;
CB.DataType = CB_DATA_IMAGE;
CB.UserData = Info->BSIn?Info->BSIn->UserData:NULL;
CB.TimeStamp = 0;
CB.Flags = 0;
CB.Value = 0;
CB.Format = (void *)&Info->OutputFormat;
CB.Action = CB_ACTION_CONTINUE;
(*(Info->CallbackFunction))(Svh, &CB, NULL);
_SlibDebug(_DEBUG_,
printf("Decompress Callback: CB_FRAME_READY Addr=0x%x, Action=%d\n",
CB.Data, CB.Action) );
if (CB.Action == CB_ACTION_END)
return(SvErrorClientEnd);
}
/*
** If an Image buffer was taken from the queue, do a callback
** to let the client free or re-use the buffer.
*/
if (UsedQ)
{
CB.Message = CB_RELEASE_BUFFER;
CB.Data = Image;
CB.DataSize = MaxImageSize;
CB.DataUsed = ImageSize;
CB.DataType = CB_DATA_IMAGE;
CB.UserData = Info->BSIn?Info->BSIn->UserData:NULL;
CB.Action = CB_ACTION_CONTINUE;
(*(Info->CallbackFunction))(Svh, &CB, NULL);
_SlibDebug(_DEBUG_,
printf("Decompress Callback: RELEASE_BUFFER Addr=0x%x, Action=%d\n",
CB.Data, CB.Action) );
if (CB.Action == CB_ACTION_END)
return(SvErrorClientEnd);
}
}
_SlibDebug(_DEBUG_, printf("SvDecompress() Out\n") );
return(stat);
}
/*
** Name: SvDecompressEnd
** Purpose: Terminate the Decompression Codec. Call after all calls to
** SvDecompress are done.
**
** Args: Svh = handle to software codec's Info structure.
*/
SvStatus_t SvDecompressEnd (SvHandle_t Svh)
{
SvCodecInfo_t *Info = (SvCodecInfo_t *)Svh;
SvCallbackInfo_t CB;
_SlibDebug(_DEBUG_, printf("SvDecompressEnd()\n") );
if (!Info)
return(SvErrorCodecHandle);
if (!Info->started)
return(SvErrorDcmpNotStarted);
switch (Info->mode)
{
#ifdef JPEG_SUPPORT
case SV_JPEG_DECODE:
Info->jdcmp->DecompressStarted = FALSE;
break;
#endif /* JPEG_SUPPORT */
#ifdef MPEG_SUPPORT
case SV_MPEG_DECODE:
case SV_MPEG2_DECODE:
Info->mdcmp->DecompressStarted = FALSE;
Info->mdcmp->PicturePositioned = FALSE;
Info->mdcmp->lastI = -1;
Info->mdcmp->lastP = -1;
Info->mdcmp->N = 12;
Info->mdcmp->M = 3;
Info->mdcmp->framenum = 0;
break;
#endif /* MPEG_SUPPORT */
#ifdef H261_SUPPORT
case SV_H261_DECODE:
{
int status=svH261DecompressFree(Svh);
RETURN_ON_ERROR(status);
}
break;
#endif /* H261_SUPPORT */
#ifdef H263_SUPPORT
case SV_H263_DECODE:
{
int status=svH263FreeDecompressor(Info);
RETURN_ON_ERROR(status);
}
#endif /* H263_SUPPORT */
#ifdef HUFF_SUPPORT
case SV_HUFF_DECODE:
/*
{
int status=sv_HuffDecompressEnd(Svh);
RETURN_ON_ERROR(status);
}
*/
break;
#endif /* HUFF_SUPPORT */
}
/* Release any Image Buffers in the queue */
if (Info->ImageQ)
{
int datasize;
_SlibDebug(_VERBOSE_, printf("Info->ImageQ exists\n") );
while (ScBufQueueGetNum(Info->ImageQ))
{
_SlibDebug(_VERBOSE_, printf("Removing from ImageQ\n") );
ScBufQueueGetHead(Info->ImageQ, &CB.Data, &datasize);
ScBufQueueRemove(Info->ImageQ);
if (Info->CallbackFunction && CB.Data)
{
CB.Message = CB_RELEASE_BUFFER;
CB.DataSize = datasize;
CB.DataUsed = 0;
CB.DataType = CB_DATA_IMAGE;
CB.UserData = Info->BSIn?Info->BSIn->UserData:NULL;
CB.Action = CB_ACTION_CONTINUE;
(*(Info->CallbackFunction))(Svh, &CB, NULL);
_SlibDebug(_DEBUG_,
printf("SvDecompressEnd: RELEASE_BUFFER. Data = 0x%x, Action = %d\n",
CB.Data, CB.Action) );
}
}
}
if (Info->BSIn)
ScBSFlush(Info->BSIn); /* flush out any remaining compressed buffers */
if (Info->CallbackFunction)
{
CB.Message = CB_CODEC_DONE;
CB.Data = NULL;
CB.DataSize = 0;
CB.DataUsed = 0;
CB.DataType = CB_DATA_NONE;
CB.UserData = Info->BSIn?Info->BSIn->UserData:NULL;
CB.TimeStamp = 0;
CB.Flags = 0;
CB.Value = 0;
CB.Format = NULL;
CB.Action = CB_ACTION_CONTINUE;
(*Info->CallbackFunction)(Svh, &CB, NULL);
_SlibDebug(_DEBUG_,
printf("SvDecompressEnd Callback: CB_CODEC_DONE Action = %d\n",
CB.Action) );
if (CB.Action == CB_ACTION_END)
return (ScErrorClientEnd);
}
Info->started=FALSE;
return(NoErrors);
}
/*
** Name: SvSetDataSource
** Purpose: Set the data source used by the MPEG or H261 bitstream parsing code
** to either the Buffer Queue or File input. The default is
** to use the Buffer Queue where data buffers are added by calling
** SvAddBuffer. When using file IO, the data is read from a file
** descriptor into a buffer supplied by the user.
**
** Args: Svh = handle to software codec's Info structure.
** Source = SV_USE_BUFFER_QUEUE or SV_USE_FILE
** Fd = File descriptor to use if Source = SV_USE_FILE
** Buf = Pointer to buffer to use if Source = SV_USE_FILE
** BufSize= Size of buffer when Source = SV_USE_FILE
*/
SvStatus_t SvSetDataSource (SvHandle_t Svh, int Source, int Fd,
void *Buffer_UserData, int BufSize)
{
SvCodecInfo_t *Info = (SvCodecInfo_t *)Svh;
int stat=NoErrors;
if (!Info)
return(SvErrorCodecHandle);
if (Info->mode!=SV_MPEG_DECODE && Info->mode!=SV_MPEG2_DECODE
&& Info->mode!=SV_H261_DECODE && Info->mode!=SV_H263_DECODE
&& Info->mode!=SV_HUFF_DECODE)
return(SvErrorCodecType);
if (Info->BSIn)
{
ScBSDestroy(Info->BSIn);
Info->BSIn=NULL;
}
switch (Source)
{
case SV_USE_BUFFER:
_SlibDebug(_DEBUG_, printf("SvSetDataSource(SV_USE_BUFFER)\n") );
stat=ScBSCreateFromBuffer(&Info->BSIn, Buffer_UserData, BufSize);
break;
case SV_USE_BUFFER_QUEUE:
_SlibDebug(_DEBUG_, printf("SvSetDataSource(SV_USE_BUFFER_QUEUE)\n") );
stat=ScBSCreateFromBufferQueue(&Info->BSIn, Svh,
CB_DATA_COMPRESSED,
Info->BufQ,
(int (*)(ScHandle_t, ScCallbackInfo_t *, void *))Info->CallbackFunction,
(void *)Buffer_UserData);
break;
case SV_USE_FILE:
_SlibDebug(_DEBUG_, printf("SvSetDataSource(SV_USE_FILE)\n") );
stat=ScBSCreateFromFile(&Info->BSIn, Fd, Buffer_UserData, BufSize);
break;
default:
stat=SvErrorBadArgument;
}
return(stat);
}
/*
** Name: SvSetDataDestination
** Purpose: Set the data destination used by the MPEG or H261 bitstream
** writing code
** to either the Buffer Queue or File input. The default is
** to use the Buffer Queue where data buffers are added by calling
** SvAddBuffer. When using file IO, the data is read from a file
** descriptor into a buffer supplied by the user.
**
** Args: Svh = handle to software codec's Info structure.
** Source = SV_USE_BUFFER_QUEUE or SV_USE_FILE
** Fd = File descriptor to use if Source = SV_USE_FILE
** Buf = Pointer to buffer to use if Source = SV_USE_FILE
** BufSize= Size of buffer when Source = SV_USE_FILE
*/
SvStatus_t SvSetDataDestination(SvHandle_t Svh, int Dest, int Fd,
void *Buffer_UserData, int BufSize)
{
SvCodecInfo_t *Info = (SvCodecInfo_t *)Svh;
int stat=NoErrors;
if (!Info)
return(SvErrorCodecHandle);
if (Info->mode != SV_H261_ENCODE && Info->mode != SV_H263_ENCODE &&
Info->mode != SV_MPEG_ENCODE &&
Info->mode != SV_MPEG2_ENCODE && Info->mode != SV_HUFF_ENCODE)
return(SvErrorCodecType);
if (Info->BSOut)
{
ScBSDestroy(Info->BSOut);
Info->BSOut=NULL;
}
switch (Dest)
{
case SV_USE_BUFFER:
_SlibDebug(_DEBUG_, printf("SvSetDataDestination(SV_USE_BUFFER)\n") );
stat=ScBSCreateFromBuffer(&Info->BSOut, Buffer_UserData, BufSize);
break;
case SV_USE_BUFFER_QUEUE:
_SlibDebug(_DEBUG_,
printf("SvSetDataDestination(SV_USE_BUFFER_QUEUE)\n") );
stat=ScBSCreateFromBufferQueue(&Info->BSOut, Svh,
CB_DATA_COMPRESSED, Info->BufQ,
(int (*)(ScHandle_t, ScCallbackInfo_t *, void *))Info->CallbackFunction,
(void *)Buffer_UserData);
break;
case SV_USE_FILE:
_SlibDebug(_DEBUG_, printf("SvSetDataDestination(SV_USE_FILE)\n") );
stat=ScBSCreateFromFile(&Info->BSOut, Fd, Buffer_UserData, BufSize);
break;
default:
stat=SvErrorBadArgument;
}
return(stat);
}
/*
** Name: SvGetDataSource
** Purpose: Returns the current input bitstream being used by
** the Codec.
** Return: NULL if there no associated bitstream
** (currently H.261 and MPEG use a bitstream)
*/
ScBitstream_t *SvGetDataSource (SvHandle_t Svh)
{
SvCodecInfo_t *Info = (SvCodecInfo_t *)Svh;
if (!Info)
return(NULL);
return(Info->BSIn);
}
/*
** Name: SvGetDataDestination
** Purpose: Returns the current input bitstream being used by
** the Codec.
** Return: NULL if there no associated bitstream
** (currently H.261 and MPEG use a bitstream)
*/
ScBitstream_t *SvGetDataDestination(SvHandle_t Svh)
{
SvCodecInfo_t *Info = (SvCodecInfo_t *)Svh;
if (!Info)
return(NULL);
return(Info->BSOut);
}
/*
** Name: SvGetInputBitstream
** Purpose: Returns the current input bitstream being used by
** the Codec.
** Return: NULL if there no associated bitstream
** (currently H.261 and MPEG use a bitstream)
*/
ScBitstream_t *SvGetInputBitstream (SvHandle_t Svh)
{
return(SvGetDataSource(Svh));
}
/*
** Name: SvFlush
** Purpose: Flushes out current compressed buffers.
** Return: status
*/
SvStatus_t SvFlush(SvHandle_t Svh)
{
SvCodecInfo_t *Info = (SvCodecInfo_t *)Svh;
if (!Info)
return(SvErrorCodecHandle);
if (Info->BSIn)
ScBSFlush(Info->BSIn); /* flush out any remaining input compressed buffers */
if (Info->BSOut)
ScBSFlush(Info->BSOut); /* flush out any remaining output compressed buffers */
return(SvErrorNone);
}
/*
** Name: SvRegisterCallback
** Purpose: Specify the user-function that will be called during processing
** to determine if the codec should abort the frame.
** Args: Svh = handle to software codec's Info structure.
** Callback = callback function to register
**
*/
SvStatus_t SvRegisterCallback (SvHandle_t Svh,
int (*Callback)(SvHandle_t, SvCallbackInfo_t *, SvPictureInfo_t *),
void *UserData)
{
SvStatus_t stat=NoErrors;
SvCodecInfo_t *Info = (SvCodecInfo_t *)Svh;
_SlibDebug(_DEBUG_, printf("SvRegisterCallback()\n") );
if (!Info)
return(SvErrorCodecHandle);
if (!Callback)
return(SvErrorBadPointer);
switch (Info->mode)
{
#ifdef MPEG_SUPPORT
case SV_MPEG_DECODE:
case SV_MPEG2_DECODE:
Info->CallbackFunction = Callback;
if (Info->BSIn==NULL)
stat=SvSetDataSource(Svh, SV_USE_BUFFER_QUEUE, 0, UserData, 0);
break;
case SV_MPEG_ENCODE:
case SV_MPEG2_ENCODE:
Info->CallbackFunction = Callback;
if (Info->BSOut==NULL)
stat=SvSetDataDestination(Svh, SV_USE_BUFFER_QUEUE, 0, UserData, 0);
break;
#endif /* MPEG_SUPPORT */
#ifdef H261_SUPPORT
case SV_H261_DECODE:
Info->CallbackFunction = Callback;
if (Info->h261) /* copy callback to H261 structure */
Info->h261->CallbackFunction=Callback;
if (Info->BSIn==NULL)
stat=SvSetDataSource(Svh, SV_USE_BUFFER_QUEUE, 0, UserData, 0);
break;
case SV_H261_ENCODE:
Info->CallbackFunction = Callback;
if (Info->h261) /* copy callback to H261 structure */
Info->h261->CallbackFunction=Callback;
if (Info->BSOut==NULL)
stat=SvSetDataDestination(Svh, SV_USE_BUFFER_QUEUE, 0, UserData, 0);
break;
#endif /* H261_SUPPORT */
#ifdef H263_SUPPORT
case SV_H263_DECODE:
Info->CallbackFunction = Callback;
if (Info->BSIn==NULL)
stat=SvSetDataSource(Svh, SV_USE_BUFFER_QUEUE, 0, UserData, 0);
break;
case SV_H263_ENCODE:
Info->CallbackFunction = Callback;
if (Info->BSOut==NULL)
stat=SvSetDataDestination(Svh, SV_USE_BUFFER_QUEUE, 0, UserData, 0);
break;
#endif /* H263_SUPPORT */
#ifdef HUFF_SUPPORT
case SV_HUFF_DECODE:
Info->CallbackFunction = Callback;
if (Info->BSIn==NULL)
stat=SvSetDataSource(Svh, SV_USE_BUFFER_QUEUE, 0, UserData, 0);
break;
case SV_HUFF_ENCODE:
Info->CallbackFunction = Callback;
if (Info->BSOut==NULL)
stat=SvSetDataDestination(Svh, SV_USE_BUFFER_QUEUE, 0, UserData, 0);
break;
#endif /* HUFF_SUPPORT */
default:
return(SvErrorCodecType);
}
return(stat);
}
/*
** Name: SvAddBuffer
** Purpose: Add a buffer of MPEG bitstream data to the CODEC or add an image
** buffer to be filled by the CODEC (in streaming mode)
**
** Args: Svh = handle to software codec's Info structure.
** BufferInfo = structure describing buffer's address, type & size
*/
SvStatus_t SvAddBuffer (SvHandle_t Svh, SvCallbackInfo_t *BufferInfo)
{
SvCodecInfo_t *Info = (SvCodecInfo_t *)Svh;
ScQueue_t *Q=NULL;
_SlibDebug(_DEBUG_, printf("SvAddBuffer() length=%d\n",BufferInfo->DataSize));
if (!Info)
return(SvErrorCodecHandle);
if (BufferInfo->DataType != CB_DATA_COMPRESSED &&
BufferInfo->DataType != CB_DATA_IMAGE)
return(SvErrorBadArgument);
/*
** Compressed data can only be added for MPEG and H261
*/
if (BufferInfo->DataType == CB_DATA_COMPRESSED
#ifdef MPEG_SUPPORT
&& Info->mode != SV_MPEG_DECODE
&& Info->mode != SV_MPEG2_DECODE
&& Info->mode != SV_MPEG_ENCODE
&& Info->mode != SV_MPEG2_ENCODE
#endif /* MPEG_SUPPORT */
#ifdef H261_SUPPORT
&& Info->mode != SV_H261_DECODE
&& Info->mode != SV_H261_ENCODE
#endif /* H261_SUPPORT */
#ifdef H263_SUPPORT
&& Info->mode != SV_H263_DECODE
&& Info->mode != SV_H263_ENCODE
#endif /* H263_SUPPORT */
#ifdef HUFF_SUPPORT
&& Info->mode != SV_HUFF_DECODE
&& Info->mode != SV_HUFF_ENCODE
#endif /* HUFF_SUPPORT */
)
return(SvErrorCodecType);
if (!BufferInfo->Data || (BufferInfo->DataSize <= 0))
return(SvErrorBadArgument);
switch (BufferInfo->DataType)
{
case CB_DATA_COMPRESSED:
_SlibDebug(_DEBUG_, printf("SvAddBuffer() COMPRESSED\n") );
if (Info->BSOut && Info->BSOut->EOI)
ScBSReset(Info->BSOut);
if (Info->BSIn && Info->BSIn->EOI)
ScBSReset(Info->BSIn);
Q = Info->BufQ;
break;
case CB_DATA_IMAGE:
_SlibDebug(_DEBUG_, printf("SvAddBuffer() IMAGE\n") );
Q = Info->ImageQ;
break;
default:
return(SvErrorBadArgument);
}
if (Q)
ScBufQueueAdd(Q, BufferInfo->Data, BufferInfo->DataSize);
else
_SlibDebug(_DEBUG_, printf("ScBufQueueAdd() no Queue\n") );
return(NoErrors);
}
/*
** Name: SvFindNextPicture
** Purpose: Find the start of the next picture in a bitstream.
** Return the picture type to the caller.
**
** Args: Svh = handle to software codec's Info structure.
** PictureInfo = Structure used to select what type of pictures to
** search for and to return information about the
** picture that is found
*/
SvStatus_t SvFindNextPicture (SvHandle_t Svh, SvPictureInfo_t *PictureInfo)
{
SvCodecInfo_t *Info = (SvCodecInfo_t *)Svh;
_SlibDebug(_DEBUG_, printf("SvFindNextPicture()\n") );
if (!Info)
return(SvErrorCodecHandle);
switch (Info->mode)
{
#ifdef MPEG_SUPPORT
case SV_MPEG_DECODE:
case SV_MPEG2_DECODE:
if (!Info->mdcmp)
return(SvErrorBadPointer);
if (!Info->mdcmp->DecompressStarted)
return(SvErrorDcmpNotStarted);
{
SvStatus_t stat = sv_MpegFindNextPicture(Info, PictureInfo);
return(stat);
}
#endif /* MPEG_SUPPORT */
default:
return(SvErrorCodecType);
}
}
#ifdef MPEG_SUPPORT
/*
** Name: SvDecompressMPEG
** Purpose: Decompress the MPEG picture that starts at the current position
** of the bitstream. If the bitstream is not properly positioned
** then find the next picture.
**
** Args: Svh = handle to software codec's Info structure.
** MultiBuf = Specifies pointer to start of the Multibuffer, an area
** large enough to hold 3 decompressed images: the
** current image, the past reference image and the
** future reference image.
** MaxMultiSize = Size of the Multibuffer in bytes.
** ImagePtr = Returns a pointer to the current image. This will be
** somewhere within the Multibuffer.
*/
SvStatus_t SvDecompressMPEG (SvHandle_t Svh, u_char *MultiBuf,
int MaxMultiSize, u_char **ImagePtr)
{
SvCodecInfo_t *Info = (SvCodecInfo_t *)Svh;
SvMpegDecompressInfo_t *MDInfo;
_SlibDebug(_DEBUG_, printf("SvDecompressMPEG()\n") );
if (!Info)
return(SvErrorCodecHandle);
if (!(MDInfo = Info->mdcmp))
return(SvErrorBadPointer);
if (!MDInfo->DecompressStarted)
return(SvErrorDcmpNotStarted);
return(sv_MpegDecompressFrame(Info, MultiBuf, ImagePtr));
}
#endif /* MPEG_SUPPORT */
#ifdef H261_SUPPORT
SvStatus_t SvDecompressH261 (SvHandle_t Svh, u_char *MultiBuf,
int MaxMultiSize, u_char **ImagePtr)
{
SvCodecInfo_t *Info = (SvCodecInfo_t *)Svh;
SvH261Info_t *H261;
ScCallbackInfo_t CB;
SvStatus_t status;
if (!Info)
return(SvErrorCodecHandle);
if (!(H261 = Info->h261))
return(SvErrorBadPointer);
if (Info->BSIn->EOI)
return(SvErrorEndBitstream);
status = svH261Decompress(Info, MultiBuf, ImagePtr);
if (status == SvErrorEndBitstream && Info->CallbackFunction)
{
CB.Message = CB_SEQ_END;
CB.Data = NULL;
CB.DataSize = 0;
CB.DataType = CB_DATA_NONE;
CB.UserData = Info->BSIn?Info->BSIn->UserData:NULL;
CB.Action = CB_ACTION_CONTINUE;
(*Info->CallbackFunction)(Svh, &CB, NULL);
_SlibDebug(_DEBUG_,
printf("H261 Callback: CB_SEQ_END Data = 0x%x Action = %d\n",
CB.Data, CB.Action) );
if (CB.Action == CB_ACTION_END)
return (ScErrorClientEnd);
}
else if (status==NoErrors)
{
*ImagePtr = H261->Y;
if (Info->CallbackFunction)
{
CB.Message = CB_FRAME_READY;
CB.Data = *ImagePtr;
CB.DataSize = H261->PICSIZE+(H261->PICSIZE/2);
CB.DataUsed = CB.DataSize;
CB.DataType = CB_DATA_IMAGE;
CB.UserData = Info->BSIn?Info->BSIn->UserData:NULL;
CB.TimeStamp = 0;
CB.Flags = 0;
CB.Value = 0;
CB.Format = (void *)&Info->OutputFormat;
CB.Action = CB_ACTION_CONTINUE;
(*Info->CallbackFunction)(Svh, &CB, NULL);
_SlibDebug(_DEBUG_,
printf("H261 Callback: CB_FRAME_READY Data = 0x%x, Action = %d\n",
CB.Data, CB.Action) );
if (CB.Action == CB_ACTION_END)
return (ScErrorClientEnd);
}
}
return (status);
}
#endif /* H261_SUPPORT */
#ifdef JPEG_SUPPORT
/*---------------------------------------------------------------------
SLIB routines to Query and return CODEC Tables to caller
*---------------------------------------------------------------------*/
/*
** From JPEG Spec. :
** Huffman tables are specified in terms of a 16-byte list (BITS) giving
** the number of codes for each code length from 1 to 16. This is
** followed by a list of 8-bit symbol values (HUFVAL), each of which is
** assigned a Huffman code. The symbol values are placed in the list
** in order of increasing code length. Code length greater than 16-bits
** are not allowed.
*/
/*
** Name: SvSetDcmpHTables
** Purpose:
**
** Notes: Baseline process is the only supported mode:
** - uses 2 AC tables and 2 DC Tables
**
*/
SvStatus_t SvSetDcmpHTables (SvHandle_t Svh, SvHuffmanTables_t *Ht)
{
SvCodecInfo_t *Info = (SvCodecInfo_t *)Svh;
int i,stat,count;
SvHt_t **htblptr;
SvHTable_t *HTab;
register int j;
if (!Info)
return(SvErrorCodecHandle);
if (!Ht)
return(SvErrorBadPointer);
for (j = 0; j < 4; j++) {
switch(j) {
case 0: htblptr = &Info->jdcmp->DcHt[0];
HTab = &Ht->DcY;
break;
case 1: htblptr = &Info->jdcmp->AcHt[0];
HTab = &Ht->AcY;
break;
case 2: htblptr = &Info->jdcmp->DcHt[1];
HTab = &Ht->DcUV;
break;
case 3: htblptr = &Info->jdcmp->AcHt[1];
HTab = &Ht->AcUV;
break;
}
if (*htblptr == NULL)
*htblptr = (SvHt_t *) ScPaMalloc(sizeof(SvHt_t));
(*htblptr)->bits[0] = 0;
count = 0;
for (i = 1; i < BITS_LENGTH; i++) {
(*htblptr)->bits[i] = (u_char)HTab->bits[i-1];
count += (*htblptr)->bits[i];
}
if (count > 256)
return(SvErrorDHTTable);
/*
** Load Huffman table:
*/
for (i = 0; i < count; i++)
(*htblptr)->value[i] = (u_char)HTab->value[i];
}
stat = sv_LoadDefaultHTable (Info);
if (stat) return(stat);
return(NoErrors);
}
/*
** Name: SvGetDcmpHTables
** Purpose:
**
*/
SvStatus_t SvGetDcmpHTables (SvHandle_t Svh, SvHuffmanTables_t *Ht)
{
SvCodecInfo_t *Info = (SvCodecInfo_t *)Svh;
int i,count;
SvHt_t **htblptr;
SvHTable_t *HTab;
register int j;
if (!Info)
return (SvErrorCodecHandle);
if (!Ht)
return(SvErrorBadPointer);
for (j = 0; j < 4; j++) {
switch(j) {
case 0: htblptr = &Info->jdcmp->DcHt[0];
HTab = &Ht->DcY;
break;
case 1: htblptr = &Info->jdcmp->AcHt[0];
HTab = &Ht->AcY;
break;
case 2: htblptr = &Info->jdcmp->DcHt[1];
HTab = &Ht->DcUV;
break;
case 3: htblptr = &Info->jdcmp->AcHt[1];
HTab = &Ht->AcUV;
break;
}
if (*htblptr == NULL)
return(SvErrorHuffUndefined);
count = 0;
for (i = 1; i < BITS_LENGTH; i++) {
HTab->bits[i-1] = (int)(*htblptr)->bits[i];
count += (*htblptr)->bits[i];
}
if (count > 256)
return(SvErrorDHTTable);
/*
** Copy Huffman table:
*/
for (i = 0; i < count; i++)
HTab->value[i] = (u_int)(*htblptr)->value[i];
}
return(NoErrors);
}
/*
** Name: SvSetCompHTables
** Purpose:
**
*/
SvStatus_t SvSetCompHTables (SvHandle_t Svh, SvHuffmanTables_t *Ht)
{
return(SvErrorNotImplemented);
}
/*
** Name: SvGetCompHTables
** Purpose:
**
*/
SvStatus_t SvGetCompHTables (SvHandle_t Svh, SvHuffmanTables_t *Ht)
{
SvCodecInfo_t *Info = (SvCodecInfo_t *)Svh;
SvHt_t **htblptr;
SvHTable_t *HTab;
register int i, j, count;
if (!Info)
return (SvErrorCodecHandle);
if (!Ht)
return (SvErrorBadPointer);
for (j = 0; j < 4; j++) {
switch(j) {
case 0: htblptr = &Info->jcomp->DcHt[0];
HTab = &Ht->DcY;
break;
case 1: htblptr = &Info->jcomp->AcHt[0];
HTab = &Ht->AcY;
break;
case 2: htblptr = &Info->jcomp->DcHt[1];
HTab = &Ht->DcUV;
break;
case 3: htblptr = &Info->jcomp->AcHt[1];
HTab = &Ht->AcUV;
break;
}
if (*htblptr == NULL)
return (SvErrorHuffUndefined);
/*
** Copy the "bits" array (contains number of codes of each size)
*/
count = 0;
for (i = 1; i < BITS_LENGTH; i++) {
HTab->bits[i-1] = (int)(*htblptr)->bits[i];
count += (*htblptr)->bits[i];
}
if (count > 256)
/*
** total # of Huffman code words cannot exceed 256
*/
return (SvErrorDHTTable);
/*
** Copy the "value" array (contains values associated with above codes)
*/
for (i = 0; i < count; i++)
HTab->value[i] = (u_int)(*htblptr)->value[i];
}
return(NoErrors);
}
/*
** Name: SvSetDcmpQTables
** Purpose:
**
*/
SvStatus_t SvSetDcmpQTables (SvHandle_t Svh, SvQuantTables_t *Qt)
{
SvCodecInfo_t *Info = (SvCodecInfo_t *)Svh;
SvJpegDecompressInfo_t *DInfo;
if (!Info)
return(SvErrorCodecHandle);
DInfo = (SvJpegDecompressInfo_t *)Info->jdcmp;
if (!Qt)
return(SvErrorBadPointer);
if (DInfo->_SviquantTblPtrs[0] == NULL)
if ((DInfo->_SviquantTblPtrs[0] = (int *) ScAlloc(64*sizeof(int))) ==
(int *)NULL) return(SvErrorMemory);
if (DInfo->_SviquantTblPtrs[1] == NULL)
if ((DInfo->_SviquantTblPtrs[1] = (int *) ScAlloc(64*sizeof(int))) ==
(int *)NULL) return(SvErrorMemory);
bcopy (Qt->c1, DInfo->_SviquantTblPtrs[0], 64*sizeof(int));
bcopy (Qt->c2, DInfo->_SviquantTblPtrs[1], 64*sizeof(int));
bcopy (Qt->c3, DInfo->_SviquantTblPtrs[1], 64*sizeof(int));
return(NoErrors);
}
/*
** Name: SvGetDcmpQTables
** Purpose:
**
*/
SvStatus_t SvGetDcmpQTables (SvHandle_t Svh, SvQuantTables_t *Qt)
{
SvCodecInfo_t *Info = (SvCodecInfo_t *)Svh;
SvJpegDecompressInfo_t *DInfo;
if (!Info)
return(SvErrorCodecHandle);
DInfo = (SvJpegDecompressInfo_t *)Info->jdcmp;
if (!Qt)
return(SvErrorBadPointer);
if (DInfo->_SviquantTblPtrs[0])
bcopy (DInfo->_SviquantTblPtrs[0], Qt->c1, 64*sizeof(int));
else
bzero (Qt->c1, 64*sizeof(int));
if (DInfo->_SviquantTblPtrs[1])
bcopy(DInfo->_SviquantTblPtrs[1], Qt->c2, 64*sizeof(int));
else
bzero(Qt->c2, 64*sizeof(int));
/*
** XXX - when the structure is changed approprately remove the
** above and do the following:
**
** if ((!Qt->c1) || (!Qt->c2) || (!Qt->c3))
** return (SvErrorBadPointer);
** bcopy ((u_char *)DInfo->Qt, (u_char *)Qt, sizeof(SvQuantTables_t));
*/
return(NoErrors);
}
/*
** Name: SvSetCompQTables
** Purpose: Allows user to set quantization tables directly
**
*/
SvStatus_t SvSetCompQTables (SvHandle_t Svh, SvQuantTables_t *Qt)
{
SvCodecInfo_t *Info = (SvCodecInfo_t *)Svh;
if (!Info)
return (SvErrorCodecHandle);
if (!Info->jcomp->CompressStarted)
return (SvErrorCompNotStarted);
if (!Qt)
return (SvErrorBadPointer);
if ((!Qt->c1) || (!Qt->c2) || (!Qt->c3))
return (SvErrorBadPointer);
/*
** Convert SvQuantTables_t structure to internal SvQt_t structure.
*/
sv_ConvertQTable(Info, Qt);
return(NoErrors);
}
#endif /* JPEG_SUPPORT */
/*---------------------------------------------------------------------
SLIB Compression Routines
*---------------------------------------------------------------------*/
/*
** Name: SvCompressBegin
** Purpose: Initialize the Compression Codec. Call after SvOpenCodec &
** before SvCompress (SvCompress will call SvCompressBegin
** on first call to codec after open if user doesn't call it)
**
** Args: Svh = handle to software codec's Info structure.
** ImgIn = format of input (uncompressed) image
** ImgOut = format of output (compressed) image
*/
SvStatus_t SvCompressBegin (SvHandle_t Svh, BITMAPINFOHEADER *ImgIn,
BITMAPINFOHEADER *ImgOut)
{
int stat;
SvCodecInfo_t *Info = (SvCodecInfo_t *)Svh;
/*
** Sanity checks:
*/
if (!Info)
return (SvErrorCodecHandle);
if (!ImgIn || !ImgOut)
return (SvErrorBadPointer);
stat=SvCompressQuery (Svh, ImgIn, ImgOut);
RETURN_ON_ERROR(stat);
/*
** Save input & output formats for SvDecompress
*/
sv_copy_bmh(ImgIn, &Info->InputFormat);
sv_copy_bmh(ImgOut, &Info->OutputFormat);
Info->Width = Info->OutputFormat.biWidth;
Info->Height = abs(Info->OutputFormat.biHeight);
/*
** Initialize - the encoder structure
** Load - the default Huffman Tables
** Make - the internal Block Table
*/
switch (Info->mode)
{
#ifdef JPEG_SUPPORT
case SV_JPEG_ENCODE:
stat = sv_InitJpegEncoder (Info);
RETURN_ON_ERROR (stat);
/*
** Set up the default quantization matrices:
*/
stat = SvSetQuality (Svh, DEFAULT_Q_FACTOR);
Info->jcomp->CompressStarted = TRUE;
Info->jcomp->Quality = DEFAULT_Q_FACTOR;
RETURN_ON_ERROR (stat);
break;
#endif /* JPEG_SUPPORT */
#ifdef H261_SUPPORT
case SV_H261_ENCODE:
stat = svH261CompressInit(Info);
RETURN_ON_ERROR (stat);
break;
#endif /* H261_SUPPORT */
#ifdef H263_SUPPORT
case SV_H263_ENCODE:
stat = svH263InitCompressor(Info);
RETURN_ON_ERROR (stat);
break;
#endif /* MPEG_SUPPORT */
#ifdef MPEG_SUPPORT
case SV_MPEG_ENCODE:
case SV_MPEG2_ENCODE:
stat = sv_MpegInitEncoder (Info);
RETURN_ON_ERROR (stat);
sv_MpegEncoderBegin(Info);
break;
#endif /* MPEG_SUPPORT */
#ifdef HUFF_SUPPORT
case SV_HUFF_ENCODE:
stat = sv_HuffInitEncoder (Info);
RETURN_ON_ERROR (stat);
break;
#endif /* HUFF_SUPPORT */
default:
return(SvErrorCodecType);
}
return (NoErrors);
}
/*
** Name: SvCompressEnd
** Purpose: Terminate the Compression Codec. Call after all calls to
** SvCompress are done.
**
** Args: Svh = handle to software codec's Info structure.
*/
SvStatus_t SvCompressEnd (SvHandle_t Svh)
{
SvCodecInfo_t *Info = (SvCodecInfo_t *)Svh;
SvCallbackInfo_t CB;
SvStatus_t status=NoErrors;
_SlibDebug(_VERBOSE_, printf("SvCompressEnd()\n") );
if (!Info)
return (SvErrorCodecHandle);
switch (Info->mode)
{
#ifdef H261_SUPPORT
case SV_H261_ENCODE:
status=svH261CompressFree(Svh);
RETURN_ON_ERROR(status)
break;
#endif /* H261_SUPPORT */
#ifdef H263_SUPPORT
case SV_H263_ENCODE:
status=svH263FreeCompressor(Svh);
RETURN_ON_ERROR(status)
break;
#endif /* H263_SUPPORT */
#ifdef MPEG_SUPPORT
case SV_MPEG_ENCODE:
case SV_MPEG2_ENCODE:
sv_MpegEncoderEnd(Info);
sv_MpegFreeEncoder(Info);
break;
#endif /* MPEG_SUPPORT */
#ifdef JPEG_SUPPORT
case SV_JPEG_ENCODE:
if (!Info->jcomp)
return (SvErrorMemory);
Info->jcomp->CompressStarted = FALSE;
break;
#endif /* JPEG_SUPPORT */
#ifdef HUFF_SUPPORT
case SV_HUFF_ENCODE:
sv_HuffFreeEncoder(Info);
break;
#endif /* HUFF_SUPPORT */
default:
break;
}
/* Release any Image Buffers in the queue */
if (Info->ImageQ)
{
int datasize;
while (ScBufQueueGetNum(Info->ImageQ))
{
ScBufQueueGetHead(Info->ImageQ, &CB.Data, &datasize);
ScBufQueueRemove(Info->ImageQ);
if (Info->CallbackFunction && CB.Data)
{
CB.Message = CB_RELEASE_BUFFER;
CB.DataSize = datasize;
CB.DataUsed = 0;
CB.DataType = CB_DATA_IMAGE;
CB.UserData = Info->BSOut?Info->BSOut->UserData:NULL;
CB.Action = CB_ACTION_CONTINUE;
(*(Info->CallbackFunction))(Svh, &CB, NULL);
_SlibDebug(_DEBUG_,
printf("SvCompressEnd: RELEASE_BUFFER. Data = 0x%X, Action = %d\n",
CB.Data, CB.Action) );
}
}
}
if (Info->BSOut)
ScBSFlush(Info->BSOut); /* flush out the last compressed data */
if (Info->CallbackFunction)
{
CB.Message = CB_CODEC_DONE;
CB.Data = NULL;
CB.DataSize = 0;
CB.DataUsed = 0;
CB.DataType = CB_DATA_NONE;
CB.UserData = Info->BSOut?Info->BSOut->UserData:NULL;
CB.TimeStamp = 0;
CB.Flags = 0;
CB.Value = 0;
CB.Format = NULL;
CB.Action = CB_ACTION_CONTINUE;
(*Info->CallbackFunction)(Svh, &CB, NULL);
_SlibDebug(_DEBUG_,
printf("SvCompressEnd Callback: CB_CODEC_DONE Action = %d\n",
CB.Action) );
if (CB.Action == CB_ACTION_END)
return (ScErrorClientEnd);
}
return (status);
}
/*
** Name: SvCompress
** Purpose:
**
*/
SvStatus_t SvCompress(SvHandle_t Svh, u_char *CompData, int MaxCompLen,
u_char *Image, int ImageSize, int *CmpBytes)
{
SvCodecInfo_t *Info = (SvCodecInfo_t *)Svh;
SvCallbackInfo_t CB;
int stat=NoErrors, UsedQ=FALSE;
_SlibDebug(_DEBUG_, printf("SvCompress()\n") );
if (!Info)
return (SvErrorCodecHandle);
/*
** If no image buffer is supplied, see if the Image Queue
** has any. If not do a callback to get a buffer.
*/
if (Image == NULL && Info->ImageQ)
{
if (ScBufQueueGetNum(Info->ImageQ))
{
ScBufQueueGetHead(Info->ImageQ, &Image, &ImageSize);
ScBufQueueRemove(Info->ImageQ);
UsedQ = TRUE;
}
else if (Info->CallbackFunction)
{
CB.Message = CB_END_BUFFERS;
CB.Data = NULL;
CB.DataSize = 0;
CB.DataUsed = 0;
CB.DataType = CB_DATA_IMAGE;
CB.UserData = Info->BSOut?Info->BSOut->UserData:NULL;
CB.Action = CB_ACTION_CONTINUE;
(*(Info->CallbackFunction))(Svh, &CB, NULL);
if (CB.Action == CB_ACTION_END)
{
_SlibDebug(_DEBUG_,
printf("SvDecompress() CB.Action = CB_ACTION_END\n") );
return(SvErrorClientEnd);
}
else if (ScBufQueueGetNum(Info->ImageQ))
{
ScBufQueueGetHead(Info->ImageQ, &Image, &ImageSize);
ScBufQueueRemove(Info->ImageQ);
UsedQ = TRUE;
}
else
return(SvErrorNoImageBuffer);
}
}
if (Image == NULL)
return(SvErrorNoImageBuffer);
switch (Info->mode)
{
#ifdef H261_SUPPORT
case SV_H261_ENCODE:
stat = svH261Compress(Svh, Image);
if (CmpBytes)
*CmpBytes = (int)(Info->h261->TotalBits/8);
break;
#endif /* H261_SUPPORT */
#ifdef H263_SUPPORT
case SV_H263_ENCODE:
stat = svH263Compress(Svh, Image);
break;
#endif /* H261_SUPPORT */
#ifdef MPEG_SUPPORT
case SV_MPEG_ENCODE:
case SV_MPEG2_ENCODE:
stat = sv_MpegEncodeFrame(Svh, Image);
break;
#endif /* MPEG_SUPPORT */
#ifdef JPEG_SUPPORT
case SV_JPEG_ENCODE:
{
SvJpegCompressInfo_t *CInfo;
u_char *CompBuffer;
register int i;
int RetBytes, InLen;
CInfo = Info->jcomp;
/*
** In case the application forgot to call SvCompressBegin().
*/
if (!CInfo->CompressStarted)
return (SvErrorCompNotStarted);
if ((u_int)Image%8)
return (SvErrorNotAligned);
CompBuffer = CompData;
/*
** Start - add header information
** - needed if we want to conform to the interchange format
*/
stat = sv_AddJpegHeader (Svh, CompBuffer, MaxCompLen, &RetBytes);
RETURN_ON_ERROR (stat);
CompBuffer += RetBytes;
/*
** Separate input image directly into 8x8 blocks.
** level shift to go from signed to unsigned representation
** - since we support baseline DCT process only (i.e 8-bit
** precision) subtract raw data by 128
*/
sv_JpegExtractBlocks (Info, Image);
for (i = 0; i < CInfo->NumComponents; i++)
CInfo->lastDcVal[i] = 0;
/*
** JPEG business loop:
*/
{
register int Cid, HQid, blkN, mcuN, mbn, DcVal;
float *FQt, *FThresh, *FThreshNeg;
float *RawData;
SvRLE_t rle;
const static long Mask = 0xffL;
float DCTData[64];
register float tmp,AcVal;
CB.Message = CB_PROCESSING;
/*
** Processing within a frame is done on a MCU by MCU basis:
*/
for (blkN = 0, mcuN = 0 ; mcuN < (int) CInfo->NumMCU; mcuN++)
{
/*
** Callback user routine every now&then to see if we should abort
*/
if ((Info->CallbackFunction) && ((i % MCU_CALLBACK_COUNT) == 0))
{
SvPictureInfo_t DummyPictInfo;
(*Info->CallbackFunction)(Svh, &CB, &DummyPictInfo);
if (CB.Action == CB_ACTION_END)
return(SvErrorClientEnd);
}
/*
** Account for restart interval, emit restart marker if needed
*/
if (CInfo->restartInterval)
{
if (CInfo->restartsToGo == 0)
EmitRestart (CInfo);
CInfo->restartsToGo--;
}
/*
** Processing within an MCU is done on a block by block basis:
*/
for (mbn = 0; mbn < (int) CInfo->BlocksInMCU; mbn++, blkN++)
{
/*
** Figure out the component to which the current block belongs:
** -Due to the way input data is processed by "sv_extract_blocks"
** and under the assumption that the input is YCrCb,
** Cid is 0,0,1,2 for each block in the MCU
*/
switch (mbn) {
case 0:
case 1: Cid = 0; HQid = 0; break;
case 2: Cid = 1; HQid = 1; break;
case 3: Cid = 2; HQid = 1; break;
}
RawData = CInfo->BlkTable[blkN];
#ifndef _NO_DCT_
/*
** Discrete Cosine Transform:
** Perform the Forward DCT, take the input data from "RawData"
** and place the computed coefficients in "DCTData":
*/
ScFDCT8x8 (RawData, DCTData);
#ifndef _NO_QUANT_
/*
** Quantization:
**
** Identify the quantization tables:
*/
FQt = (float *) (CInfo->Qt[HQid])->fval;
FThresh = (float *) (CInfo->Qt[HQid])->fthresh;
FThreshNeg = (float *) (CInfo->Qt[HQid])->fthresh_neg;
/*
** Quantize the DC value first:
*/
tmp = DCTData[0] *FQt[0];
if (tmp < 0)
DcVal = (int) (tmp - 0.5);
else
DcVal = (int) (tmp + 0.5);
/*
** Go after (quantize) the AC coefficients now:
*/
for (rle.numAC = 0, i = 1; i < 64; i++)
{
AcVal = DCTData[ZagIndex[i]];
if (AcVal > FThresh[i]) {
rle.ac[rle.numAC].index = i;
rle.ac[rle.numAC++].value = (int) (AcVal * FQt[i] + 0.5);
}
else if (AcVal < FThreshNeg[i]) {
rle.ac[rle.numAC].index = i;
rle.ac[rle.numAC++].value = (int) (AcVal * FQt[i] - 0.5);
}
}
/*
** DPCM coding:
**
** Difference encoding of the DC value,
*/
rle.dc = DcVal - CInfo->lastDcVal[Cid];
CInfo->lastDcVal[Cid] = DcVal;
#ifndef _NO_HUFF_
/*
** Entropy Coding:
**
** Huffman encode the current block
*/
sv_EncodeOneBlock (&rle, CInfo->DcHt[HQid], CInfo->AcHt[HQid]);
FlushBytes(&CompBuffer);
#endif /* _NO_HUFF_ */
#endif /* _NO_QUANT_ */
#endif /* _NO_DCT_ */
}
}
}
(void ) sv_HuffEncoderTerm (&CompBuffer);
Info->OutputFormat.biSize = CompBuffer - CompData;
InLen = MaxCompLen - Info->OutputFormat.biSize;
/*
** JPEG End:
** - add trailer information to the compressed bitstream,
** - needed if we want to conform to the interchange format
*/
stat = sv_AddJpegTrailer (Svh, CompBuffer, InLen, &RetBytes);
RETURN_ON_ERROR (stat);
CompBuffer += RetBytes;
Info->OutputFormat.biSize += RetBytes;
if (CmpBytes)
*CmpBytes = CompBuffer - CompData;
}
break;
#endif /* JPEG_SUPPORT */
#ifdef HUFF_SUPPORT
case SV_HUFF_ENCODE:
stat = sv_HuffEncodeFrame(Svh, Image);
break;
#endif /* HUFF_SUPPORT */
default:
return(SvErrorCodecType);
}
Info->NumOperations++;
/*
** If an Image buffer was taken from the queue, do a callback
** to let the client free or re-use the buffer.
*/
if (Info->CallbackFunction && UsedQ)
{
CB.Message = CB_RELEASE_BUFFER;
CB.Data = Image;
CB.DataSize = ImageSize;
CB.DataUsed = ImageSize;
CB.DataType = CB_DATA_IMAGE;
CB.UserData = Info->BSOut?Info->BSOut->UserData:NULL;
CB.Action = CB_ACTION_CONTINUE;
(*(Info->CallbackFunction))(Svh, &CB, NULL);
_SlibDebug(_DEBUG_,
printf("Compress Callback: RELEASE_BUFFER Addr=0x%x, Action=%d\n",
CB.Data, CB.Action) );
if (CB.Action == CB_ACTION_END)
return(SvErrorClientEnd);
}
return (stat);
}
static SvStatus_t sv_ConvertRGBToSepComponent(u_char *Iimage,
BITMAPINFOHEADER * Bmh, u_char *comp1, u_char *comp2, u_char *comp3,
int pixels, int lines)
{
register i;
int bpp = Bmh->biBitCount;
u_int *Ip = (u_int *)Iimage;
u_short *Is = (u_short *)Iimage;
if (bpp == 24) {
if (Bmh->biCompression == BI_RGB) {
for (i = 0 ; i < pixels*lines ; i++) {
comp3[i] = *Iimage++; /* Blue */
comp2[i] = *Iimage++; /* Green */
comp1[i] = *Iimage++; /* Red */
}
}
else if (Bmh->biCompression == BI_DECXIMAGEDIB) {
/* RGBQUAD structures: (B,G,R,0) */
for (i = 0 ; i < pixels*lines ; i++) {
comp3[i] = *Iimage++; /* Blue */
comp2[i] = *Iimage++; /* Green */
comp1[i] = *Iimage++; /* Red */
Iimage++; /* Reserved */
}
}
}
else if (bpp == 32) { /* RGBQUAD structures: (B,G,R,0) */
for (i = 0 ; i < pixels*lines ; i++) {
comp3[i] = (Ip[i] >> 24) & 0xFF;
comp2[i] = (Ip[i] >> 16) & 0xFF;
comp1[i] = (Ip[i] >> 8) & 0xFF;
}
}
else if (bpp == 16) {
for (i = 0 ; i < pixels*lines ; i++) {
comp1[i] = (Is[i] >> 7) & 0xf8;
comp2[i] = (Is[i] >> 2) & 0xf8;
comp3[i] = (Is[i] << 3) & 0xf8;
}
}
return (NoErrors);
}
/*
** Name: SvCompressQuery
** Purpose: Determine if Codec can Compress desired format
**
** Args: Svh = handle to software codec's Info structure.
** ImgIn = Pointer to BITMAPINFOHEADER structure describing format
** ImgOut = Pointer to BITMAPINFOHEADER structure describing format
*/
SvStatus_t SvCompressQuery (SvHandle_t Svh, BITMAPINFOHEADER *ImgIn,
BITMAPINFOHEADER *ImgOut)
{
/*
** We don't *really* need the Info structures, but we check for
** NULL pointers to make sure the CODEC, whoes ability is being
** queried, was at least opened.
*/
SvCodecInfo_t *Info = (SvCodecInfo_t *)Svh;
if (!Info)
return(SvErrorCodecHandle);
if (!ImgIn && !ImgOut)
return(SvErrorBadPointer);
if (!IsSupported(_SvCompressionSupport,
ImgIn ? ImgIn->biCompression : -1,
ImgIn ? ImgIn->biBitCount : -1,
ImgOut ? ImgOut->biCompression : -1,
ImgOut ? ImgOut->biBitCount : -1))
return(SvErrorUnrecognizedFormat);
/*
** For speed we impose a restriction that the image size should be
** a multiple of 16x8. This insures that we would have at least one
** MCU for a 4:2:2 image
**
** NOTE: This is an artificial restriction from JPEG's perspective.
** In the case when the dimesnsions are otherwise, we should
** pixel replicate and/or line replicate before compressing.
*/
if (ImgIn)
{
if (ImgIn->biWidth <= 0 || ImgIn->biHeight == 0)
return(SvErrorBadImageSize);
if ((ImgIn->biWidth%16) || (ImgIn->biHeight%8))
return (SvErrorNotImplemented);
}
if (ImgOut) /* Query Output also */
{
if (ImgOut->biWidth <= 0 || ImgOut->biHeight == 0)
return (SvErrorBadImageSize);
if (ImgOut->biCompression == BI_DECH261DIB)
{
if ((ImgOut->biWidth != CIF_WIDTH && ImgOut->biWidth != QCIF_WIDTH) ||
(abs(ImgOut->biHeight) != CIF_HEIGHT && abs(ImgOut->biHeight) != QCIF_HEIGHT))
return (SvErrorBadImageSize);
}
}
return(NoErrors);
}
/*
** Name: SvGetCompressSize
** Purpose:
**
*/
SvStatus_t SvGetCompressSize (SvHandle_t Svh, int *MaxSize)
{
SvCodecInfo_t *Info = (SvCodecInfo_t *)Svh;
if (!Info)
return (SvErrorCodecHandle);
if (!MaxSize)
return (SvErrorBadPointer);
/*
** We are being extra cautious here, it would reflect poorly on the JPEG
** commitee is the compressed bitstream was so big
*/
*MaxSize = 2 * Info->InputFormat.biWidth * abs(Info->InputFormat.biHeight);
return(NoErrors);
}
#ifdef JPEG_SUPPORT
/*
** Name: SvGetQuality
** Purpose:
**
*/
SvStatus_t SvGetQuality (SvHandle_t Svh, int *Quality)
{
SvCodecInfo_t *Info = (SvCodecInfo_t *)Svh;
if (!Info)
return (SvErrorCodecHandle);
if (!Quality)
return (SvErrorBadPointer);
*Quality = Info->jcomp->Quality;
return (NoErrors);
}
#endif /* JPEG_SUPPORT */
#ifdef JPEG_SUPPORT
/*
** Name: SvSetQuality
** Purpose:
**
*/
SvStatus_t SvSetQuality (SvHandle_t Svh, int Quality)
{
int stat,ConvertedQuality;
SvCodecInfo_t *Info = (SvCodecInfo_t *)Svh;
if (!Info)
return (SvErrorCodecHandle);
if ((Quality < 0) || (Quality > 10000))
return (SvErrorValue);
Info->jcomp->Quality = Quality;
ConvertedQuality = 10000 - Quality;
if (ConvertedQuality < MIN_QUAL)
ConvertedQuality = MIN_QUAL;
stat = sv_MakeQTables (ConvertedQuality, Info);
return (stat);
}
#endif /* JPEG_SUPPORT */
#ifdef JPEG_SUPPORT
/*
** Name: SvGetCompQTables
** Purpose:
**
*/
SvStatus_t SvGetCompQTables (SvHandle_t Svh, SvQuantTables_t *Qt)
{
register int i;
SvCodecInfo_t *Info = (SvCodecInfo_t *)Svh;
if (!Info)
return (SvErrorCodecHandle);
if (!Info->jcomp->CompressStarted)
return (SvErrorCompNotStarted);
if (!Qt)
return (SvErrorBadPointer);
if ((!Qt->c1) || (!Qt->c2) || (!Qt->c3))
return (SvErrorBadPointer);
for (i = 0 ; i < 64 ; i++) {
register int zz = ZigZag[i];
Qt->c1[i] = (Info->jcomp->Qt[0])->ival[zz];
Qt->c2[i] = (Info->jcomp->Qt[1])->ival[zz];
Qt->c3[i] = (Info->jcomp->Qt[1])->ival[zz];
}
return(NoErrors);
}
#endif /* JPEG_SUPPORT */
/*
** Name: SvGetCodecInfo
** Purpose: Get info about the codec & the data
**
** Args: Svh = handle to software codec's Info structure.
**
** XXX - does not work for compression, this has to wait for the
** decompressor to use SvCodecInfo_t struct for this to work
*/
SvStatus_t SvGetInfo (SvHandle_t Svh, SV_INFO_t *lpinfo, BITMAPINFOHEADER *Bmh)
{
SvCodecInfo_t *Info = (SvCodecInfo_t *)Svh;
if (!Info)
return(SvErrorCodecHandle);
lpinfo->Version = SLIB_VERSION;
switch (Info->mode)
{
#ifdef JPEG_SUPPORT
case SV_JPEG_ENCODE:
lpinfo->CodecStarted = Info->jcomp->CompressStarted;
break;
case SV_JPEG_DECODE:
lpinfo->CodecStarted = Info->jdcmp->DecompressStarted;
break;
#endif /* JPEG_SUPPORT */
default:
lpinfo->CodecStarted = 0;
break;
}
lpinfo->NumOperations = Info->NumOperations;
*Bmh = Info->InputFormat;
return(NoErrors);
}
/*
** Name: sv_GetComponentPointers
** Purpose: Given a pointer to an image and its size,
** return pointers to the individual image components
**
** Args: pixels = number of pixels in a line.
** lines = number of lines in image.
** Image = Pointer to start of combined image data
** MaxLen = Size of image data in bytes
** comp1/2/3= pointers to pointers to individual components
*/
static SvStatus_t sv_GetYUVComponentPointers(int biCompression,
int pixels, int lines, u_char *Image,
int MaxLen, u_char **comp1, u_char **comp2, u_char **comp3)
{
u_int sz1,sz2,sz3,maxlen;
sz1 = pixels * lines;
sz2 = sz3 = (IsYUV411Sep(biCompression)) ? (sz1 / 4) :
((IsYUV1611Sep(biCompression)) ? (pixels * lines / 16)
: (sz1 / 2));
maxlen = (MaxLen > 0) ? (u_int) MaxLen : 0 ;
if (biCompression == BI_DECGRAYDIB) {
if (sz1 > maxlen)
return(SvErrorBadImageSize);
*comp1 = Image;
*comp2 = NULL;
*comp3 = NULL;
}
else {
if ((sz1+sz2+sz3) > maxlen)
return(SvErrorBadImageSize);
*comp1 = Image;
*comp2 = Image + sz1;
*comp3 = Image + sz1 + sz2;
}
return(SvErrorNone);
}
#ifdef JPEG_SUPPORT
/*
** Name: sv_JpegExtractBlocks
** Purpose:
**
** Note: If we did our job right, memory for all global structures should
** have been allocated by the upper layers, we do not waste time
** checking for NULL pointers at this point
**
*/
static SvStatus_t sv_JpegExtractBlocks (SvCodecInfo_t *Info, u_char *RawImage)
{
SvJpegCompressInfo_t *CInfo = (SvJpegCompressInfo_t *)Info->jcomp;
int size = Info->Width * Info->Height;
u_char *TempImage;
SvStatus_t stat;
if (IsYUV422Packed(Info->InputFormat.biCompression))
/*
** This will extract chunks of 64 bytes (8x8 blocks) from the uncompressed
** 4:2:2 interleaved input video frame and place them in three separate
** linear arrays for later processing.
** XXX - should also do level shifting in this routine
**
*/
ScConvert422iTo422sf_C(RawImage, 16,
(float *)(CInfo->BlkBuffer),
(float *)(CInfo->BlkBuffer + size),
(float *)(CInfo->BlkBuffer + size + size/2),
Info->Width,
Info->Height);
else if (IsYUV422Sep(Info->InputFormat.biCompression))
/*
** Same but RawImage is not interleaved. Three components are sequential.
*/
ScConvertSep422ToBlockYUV (RawImage, 16,
(float *)(CInfo->BlkBuffer),
(float *)(CInfo->BlkBuffer + size),
(float *)(CInfo->BlkBuffer + size + size/2),
Info->Width,
Info->Height);
else if (Info->InputFormat.biCompression == BI_DECGRAYDIB)
/*
** Grayscale: one component
*/
ScConvertGrayToBlock (RawImage,
8,
(float *)(CInfo->BlkBuffer),
Info->Width,
Info->Height);
if ((Info->InputFormat.biCompression == BI_RGB) ||
(Info->InputFormat.biCompression == BI_DECXIMAGEDIB) ||
(ValidateBI_BITFIELDS(&Info->InputFormat) != InvalidBI_BITFIELDS))
{
TempImage = (u_char *)ScPaMalloc (3 * Info->Width * Info->Height);
if (TempImage == NULL)
return(ScErrorMemory);
stat = ScRgbInterlToYuvInterl(
&Info->InputFormat,
(int)Info->Width,
(int)Info->Height,
RawImage,
(u_short *) TempImage);
RETURN_ON_ERROR (stat);
ScConvert422iTo422sf_C(
TempImage,
16,
(float *)(CInfo->BlkBuffer),
(float *)(CInfo->BlkBuffer + size),
(float *)(CInfo->BlkBuffer + size + size/2),
Info->Width,
Info->Height);
ScPaFree(TempImage);
}
return (NoErrors);
}
#endif /* JPEG_SUPPORT */
#ifdef JPEG_SUPPORT
/*
** Name: SvSetQuantMode
** Purpose: Used only in the "Q Conversion" program "jpegconvert" to
** set a flag in the comp & decomp info structures that causes
** the quantization algorithm to use the new or old versions
** of JPEG quantization.
**
*/
SvStatus_t SvSetQuantMode (SvHandle_t Svh, int QuantMode)
{
SvCodecInfo_t *Info = (SvCodecInfo_t *)Svh;
if (!Info)
return (SvErrorCodecHandle);
if ((QuantMode != SV_JPEG_QUANT_OLD) && (QuantMode != SV_JPEG_QUANT_NEW))
return (SvErrorValue);
if (Info->jdcmp)
Info->jdcmp->QuantMode = QuantMode;
if (Info->jcomp)
Info->jcomp->QuantMode = QuantMode;
return (NoErrors);
}
#endif /* JPEG_SUPPORT */
/*
** Name: SvSetParamBoolean()
** Desc: Generic call used to set specific BOOLEAN (TRUE or FALSE) parameters
** of the CODEC.
*/
SvStatus_t SvSetParamBoolean(SvHandle_t Svh, SvParameter_t param,
ScBoolean_t value)
{
SvCodecInfo_t *Info = (SvCodecInfo_t *)Svh;
if (!Info)
return(SvErrorCodecHandle);
_SlibDebug(_VERBOSE_, printf("SvSetParamBoolean()\n") );
switch (Info->mode)
{
#ifdef MPEG_SUPPORT
case SV_MPEG_DECODE:
case SV_MPEG2_DECODE:
case SV_MPEG_ENCODE:
case SV_MPEG2_ENCODE:
sv_MpegSetParamBoolean(Svh, param, value);
break;
#endif /* MPEG_SUPPORT */
#ifdef H261_SUPPORT
case SV_H261_DECODE:
case SV_H261_ENCODE:
svH261SetParamBoolean(Svh, param, value);
break;
#endif /* H263_SUPPORT */
#ifdef H263_SUPPORT
case SV_H263_DECODE:
case SV_H263_ENCODE:
svH263SetParamBoolean(Svh, param, value);
break;
#endif /* H263_SUPPORT */
default:
return(SvErrorCodecType);
}
return(NoErrors);
}
/*
** Name: SvSetParamInt()
** Desc: Generic call used to set specific INTEGER (qword) parameters
** of the CODEC.
*/
SvStatus_t SvSetParamInt(SvHandle_t Svh, SvParameter_t param, qword value)
{
SvCodecInfo_t *Info = (SvCodecInfo_t *)Svh;
if (!Info)
return(SvErrorCodecHandle);
_SlibDebug(_VERBOSE_, printf("SvSetParamInt()\n") );
switch (Info->mode)
{
#ifdef MPEG_SUPPORT
case SV_MPEG_DECODE:
case SV_MPEG2_DECODE:
case SV_MPEG_ENCODE:
case SV_MPEG2_ENCODE:
sv_MpegSetParamInt(Svh, param, value);
break;
#endif /* MPEG_SUPPORT */
#ifdef H261_SUPPORT
case SV_H261_DECODE:
case SV_H261_ENCODE:
svH261SetParamInt(Svh, param, value);
break;
#endif /* H261_SUPPORT */
#ifdef H263_SUPPORT
case SV_H263_DECODE:
case SV_H263_ENCODE:
svH263SetParamInt(Svh, param, value);
break;
#endif /* H263_SUPPORT */
default:
return(SvErrorCodecType);
}
return(NoErrors);
}
/*
** Name: SvSetParamFloat()
** Desc: Generic call used to set specific FLOAT parameters of the CODEC.
*/
SvStatus_t SvSetParamFloat(SvHandle_t Svh, SvParameter_t param, float value)
{
SvCodecInfo_t *Info = (SvCodecInfo_t *)Svh;
if (!Info)
return(SvErrorCodecHandle);
_SlibDebug(_VERBOSE_, printf("SvSetParamFloat()\n") );
switch (Info->mode)
{
#ifdef MPEG_SUPPORT
case SV_MPEG_DECODE:
case SV_MPEG2_DECODE:
case SV_MPEG_ENCODE:
case SV_MPEG2_ENCODE:
sv_MpegSetParamFloat(Svh, param, value);
break;
#endif /* MPEG_SUPPORT */
#ifdef H261_SUPPORT
case SV_H261_DECODE:
case SV_H261_ENCODE:
svH261SetParamFloat(Svh, param, value);
break;
#endif /* H261_SUPPORT */
#ifdef H263_SUPPORT
case SV_H263_DECODE:
case SV_H263_ENCODE:
svH263SetParamFloat(Svh, param, value);
break;
#endif /* H263_SUPPORT */
default:
return(SvErrorCodecType);
}
return(NoErrors);
}
/*
** Name: SvGetParamBoolean()
** Desc: Generic call used to get the setting of specific BOOLEAN (TRUE or FALSE)
** parameters of the CODEC.
*/
ScBoolean_t SvGetParamBoolean(SvHandle_t Svh, SvParameter_t param)
{
SvCodecInfo_t *Info = (SvCodecInfo_t *)Svh;
if (!Info)
return(FALSE);
switch (Info->mode)
{
#ifdef JPEG_SUPPORT
/* this code should be moved into JPEG codec: svJPEGGetParamBoolean() */
case SV_JPEG_DECODE:
case SV_JPEG_ENCODE:
switch (param)
{
case SV_PARAM_BITSTREAMING:
return(FALSE); /* this is a frame-based codecs */
}
break;
#endif /* JPEG_SUPPORT */
#ifdef MPEG_SUPPORT
case SV_MPEG_DECODE:
case SV_MPEG2_DECODE:
case SV_MPEG_ENCODE:
case SV_MPEG2_ENCODE:
return(sv_MpegGetParamBoolean(Svh, param));
break;
#endif /* MPEG_SUPPORT */
#ifdef H261_SUPPORT
/* this code should be moved into H261 codec: svH261GetParamBoolean() */
case SV_H261_DECODE:
case SV_H261_ENCODE:
return(svH261GetParamBoolean(Svh, param));
break;
#endif /* H261_SUPPORT */
#ifdef H263_SUPPORT
case SV_H263_DECODE:
case SV_H263_ENCODE:
return(svH263GetParamBoolean(Svh, param));
break;
#endif /* H263_SUPPORT */
}
return(FALSE);
}
/*
** Name: SvGetParamInt()
** Desc: Generic call used to get the setting of specific INTEGER (qword)
** parameters of the CODEC.
*/
qword SvGetParamInt(SvHandle_t Svh, SvParameter_t param)
{
SvCodecInfo_t *Info = (SvCodecInfo_t *)Svh;
if (!Info)
return(0);
switch (Info->mode)
{
#ifdef JPEG_SUPPORT
/* this code should be moved into JPEG codec: svJPEGGetParamInt() */
case SV_JPEG_DECODE:
case SV_JPEG_ENCODE:
switch (param)
{
case SV_PARAM_NATIVEFORMAT:
return(BI_YU16SEP);
}
break;
#endif /* JPEG_SUPPORT */
#ifdef H261_SUPPORT
/* this code should be moved into H261 codec: svH261GetParamInt() */
case SV_H261_DECODE:
case SV_H261_ENCODE:
return(svH261GetParamInt(Svh, param));
break;
#endif /* H261_SUPPORT */
#ifdef H263_SUPPORT
case SV_H263_DECODE:
case SV_H263_ENCODE:
return(svH263GetParamInt(Svh, param));
break;
#endif /* H263_SUPPORT */
#ifdef MPEG_SUPPORT
case SV_MPEG_DECODE:
case SV_MPEG2_DECODE:
case SV_MPEG_ENCODE:
case SV_MPEG2_ENCODE:
return(sv_MpegGetParamInt(Svh, param));
#endif /* MPEG_SUPPORT */
}
switch (param)
{
case SV_PARAM_FINALFORMAT:
return(Info->OutputFormat.biCompression);
}
return(0);
}
/*
** Name: SvGetParamBoolean()
** Desc: Generic call used to get the setting of specific FLOAT
** parameters of the CODEC.
*/
float SvGetParamFloat(SvHandle_t Svh, SvParameter_t param)
{
SvCodecInfo_t *Info = (SvCodecInfo_t *)Svh;
if (!Info)
return(0.0f);
switch (Info->mode)
{
#ifdef MPEG_SUPPORT
case SV_MPEG_DECODE:
case SV_MPEG2_DECODE:
case SV_MPEG_ENCODE:
case SV_MPEG2_ENCODE:
return(sv_MpegGetParamFloat(Svh, param));
#endif
#ifdef H261_SUPPORT
case SV_H261_DECODE:
case SV_H261_ENCODE:
return(svH261GetParamFloat(Svh, param));
#endif /* H261_SUPPORT */
#ifdef H263_SUPPORT
case SV_H263_DECODE:
case SV_H263_ENCODE:
return(svH263GetParamFloat(Svh, param));
#endif /* H263_SUPPORT */
}
return(0.0f);
}
/*
** Name: sv_copy_bmh
** Purpose: Copy a BITMAPINFOHEADER struct. For now, it only knows about the
** extra DWORD masks at the end of BI_BITFIELDS bitmapinfoheaders.
** Otherwise, it treats others (such as 8 bit rgb, or jpeg) the
** same as a vanilla bitmapinfoheader.
*/
static void sv_copy_bmh (
BITMAPINFOHEADER *ImgFrom,
BITMAPINFOHEADER *ImgTo)
{
*ImgTo = *ImgFrom;
if (ImgFrom->biCompression == BI_BITFIELDS)
bcopy(ImgFrom + 1, ImgTo + 1, 3*sizeof(DWORD));
}
| 32.96889 | 126 | 0.56774 | [
"transform"
] |
823b65391d2450c9291e41f976b91bb5498738cf | 1,782 | h | C | MEIClient/AMTHIClient/Include/GetEACStateCommand.h | Ganeshr93/wsman-mei-library | 095ed29d2960e5573efae9470d70fc20ba459399 | [
"Apache-2.0"
] | null | null | null | MEIClient/AMTHIClient/Include/GetEACStateCommand.h | Ganeshr93/wsman-mei-library | 095ed29d2960e5573efae9470d70fc20ba459399 | [
"Apache-2.0"
] | 1 | 2020-12-15T01:55:35.000Z | 2020-12-15T02:10:12.000Z | MEIClient/AMTHIClient/Include/GetEACStateCommand.h | isabella232/lms | 50d16f81b49aba6007388c001e8137352c5eb42e | [
"Apache-2.0"
] | 1 | 2020-12-15T01:02:46.000Z | 2020-12-15T01:02:46.000Z | /* SPDX-License-Identifier: Apache-2.0 */
/*
* Copyright (C) 2010-2019 Intel Corporation
*/
/*++
@file: GetEACStateCommand.h
--*/
#ifndef __GET_EAC_STATE_COMMAND_H__
#define __GET_EAC_STATE_COMMAND_H__
#include "AMTHICommand.h"
#include "MEIparser.h"
namespace Intel
{
namespace MEI_Client
{
namespace AMTHI_Client
{
typedef struct
{
uint32_t RequestId;
AMT_BOOLEAN EacEnabled;
void parse (std::vector<uint8_t>::const_iterator &itr, const std::vector<uint8_t>::const_iterator &end)
{
Intel::MEI_Client::parseData(RequestId, itr, end);
Intel::MEI_Client::parseData(EacEnabled, itr, end);
}
} GET_EAC_STATE_RESPONSE;
class GetEACStateRequest;
class GetEACStateCommand : public AMTHICommand
{
public:
GetEACStateCommand();
virtual ~GetEACStateCommand() {}
GET_EAC_STATE_RESPONSE getResponse();
private:
virtual void parseResponse(const std::vector<uint8_t>& buffer);
std::shared_ptr<AMTHICommandResponse<GET_EAC_STATE_RESPONSE>> m_response;
static const uint32_t RESPONSE_COMMAND_NUMBER = 0x04800049;
};
class GetEACStateRequest : public AMTHICommandRequest
{
public:
GetEACStateRequest() {
}
virtual ~GetEACStateRequest() {}
private:
static const uint32_t EAC_ID = 3;
static const uint32_t REQUEST_COMMAND_NUMBER = 0x04000049;
virtual unsigned int requestHeaderCommandNumber()
{
//this is the command number (taken from the AMTHI document)
return REQUEST_COMMAND_NUMBER;
}
virtual uint32_t requestDataSize()
{
return sizeof(uint32_t);
}
virtual std::vector<uint8_t> SerializeData();
};
} // namespace AMTHI_Client
} // namespace MEI_Client
} // namespace Intel
#endif //__GET_EAC_STATE_COMMAND_H__ | 22.556962 | 107 | 0.71156 | [
"vector"
] |
82490ed59111a86acc61585dfc493db80e405f20 | 2,251 | h | C | src/Library/Cameras/CameraTransforms.h | aravindkrishnaswamy/rise | 297d0339a7f7acd1418e322a30a21f44c7dbbb1d | [
"BSD-2-Clause"
] | 1 | 2018-12-20T19:31:02.000Z | 2018-12-20T19:31:02.000Z | src/Library/Cameras/CameraTransforms.h | aravindkrishnaswamy/rise | 297d0339a7f7acd1418e322a30a21f44c7dbbb1d | [
"BSD-2-Clause"
] | null | null | null | src/Library/Cameras/CameraTransforms.h | aravindkrishnaswamy/rise | 297d0339a7f7acd1418e322a30a21f44c7dbbb1d | [
"BSD-2-Clause"
] | null | null | null | //////////////////////////////////////////////////////////////////////
//
// CameraTransforms.h - Transformation helpers for cameras
//
// Author: Aravind Krishnaswamy
// Date of Birth: April 22, 2004
// Tabs: 4
// Comments:
//
// License Information: Please see the attached LICENSE.TXT file
//
//////////////////////////////////////////////////////////////////////
#ifndef CAMERA_TRANSFORMS_
#define CAMERA_TRANSFORMS_
namespace RISE
{
namespace Implementation
{
class CameraTransforms
{
protected:
CameraTransforms(){};
virtual ~CameraTransforms(){};
public:
static void AdjustCameraForOrientation(
const Vector3& vForward,
const Vector3& vUp,
Vector3& vNewForward,
Vector3& vNewUp,
const Vector3 orientation
)
{
vNewForward = vForward;
vNewUp = vUp;
if( orientation.x != 0 ) {
const Matrix4 mxRot =
Matrix4Ops::Rotation( Vector3Ops::Cross( vForward, vUp ), orientation.x );
vNewForward = Vector3Ops::Transform( mxRot, vNewForward );
vNewUp = Vector3Ops::Transform( mxRot, vNewUp );
}
if( orientation.y != 0 ) {
const Matrix4 mxRot =
Matrix4Ops::Rotation( vUp, orientation.y );
vNewForward = Vector3Ops::Transform( mxRot, vNewForward );
}
if( orientation.z != 0 ) {
const Matrix4 mxRot =
Matrix4Ops::Rotation( vForward, orientation.z );
vNewUp = Vector3Ops::Transform( mxRot, vNewUp );
}
}
static void AdjustCameraForThetaPhi(
const Vector2& target_orientation,
const Point3& position,
const Point3& lookat,
const Vector3& up,
Point3& ptNewPosition,
Vector3& vNewUp
)
{
Scalar theta = target_orientation.x;
theta = theta > PI_OV_TWO ? PI_OV_TWO : theta;
const Scalar phi = target_orientation.y;
const Vector3 vForward = Vector3Ops::Normalize(Vector3Ops::mkVector3( lookat, position ));
const Matrix4 mxRot =
Matrix4Ops::Rotation( up, phi ) *
Matrix4Ops::Rotation( Vector3Ops::Cross( vForward, up ), -theta );
ptNewPosition = Point3Ops::mkPoint3( lookat,
Vector3Ops::Transform( mxRot, Vector3Ops::mkVector3( position, lookat ) ) );
vNewUp = Vector3Ops::Transform( mxRot, up );
}
};
}
}
#endif
| 24.204301 | 94 | 0.617503 | [
"transform"
] |
825398b9e7a18b3b8cdeb0ec607ddbc30e1ca92e | 2,172 | h | C | src/sort_bubble.h | microentropie/Sort | 52498bea85acaaf107125456f95c0d25c318d7e8 | [
"MIT"
] | null | null | null | src/sort_bubble.h | microentropie/Sort | 52498bea85acaaf107125456f95c0d25c318d7e8 | [
"MIT"
] | null | null | null | src/sort_bubble.h | microentropie/Sort | 52498bea85acaaf107125456f95c0d25c318d7e8 | [
"MIT"
] | null | null | null | #ifndef _SORT_BUBBLE_
#define _SORT_BUBBLE_
/*
Author: Stefano Di Paolo
License: MIT, https://en.wikipedia.org/wiki/MIT_License
Date: 2016-12-18
Sort an array of objects.
In form of a C++ template libray, particularly suited for micros
thanks to the low memory usage.
Bubble Sort, from Wikipedia presudo-code
https://en.wikipedia.org/wiki/Bubble_sort
Supply a comparation function and it will sort any kind of objects.
The compare function inputs 2 pointers (to 2 instances of the object)
and returns:
* 0 if the objects (e1 and e2) are equals
* <0 if e1 < e2
* >0 id e1 > e2
Sources repository: https://github.com/microentropie/Sort
How to install:
https://www.arduino.cc/en/guide/libraries
*/
#include "sort_compare_numeric.h"
// classic Bubble Sort
// sort an array of pointers
// to be preferred !
template<typename T>
void bubbleSort(T *Ary[], int qtElem, int(*compareFn)(T *e1, T *e2))
{
int i, j;
T *pTemp;
for (i = 0; i < qtElem; i++)
{
for (j = i + 1; j < qtElem; j++)
{
if (compareFn(Ary[i], Ary[j]) > 0)
{
// swap pointers
pTemp = Ary[i];
Ary[i] = Ary[j];
Ary[j] = pTemp;
}
}
}
}
// classic Bubble Sort (low memory usage)
// sort an array of T objects
// entire T objects are swapped instead of their pointers
// this means a lot of memory copy operations, acceptable
// only if T is small (i.e. sizeof(T) <= sizeof(*T)).
// NOTE: the size of a pointer is 4 byte for 32 bit systems.
template<typename T>
void bubbleSort(T Ary[], int qtElem, int(*compareFn)(T *e1, T *e2))
{
int i, j;
T temp;
for (i = 0; i < qtElem; i++)
{
for (j = i + 1; j < qtElem; j++)
{
if (compareFn(&Ary[i], &Ary[j]) > 0)
{
// swap T instance
temp = Ary[i];
Ary[i] = Ary[j];
Ary[j] = temp;
}
}
}
}
// simplified method for numeric arrays or
// arrays of objects where a subtraction operator is defined
template<typename T>
void bubbleSort(T Ary[], int qtElem)
{
bubbleSort(Ary, qtElem, compareNumeric<T>);
}
#endif //_SORT_BUBBLE_
| 23.608696 | 70 | 0.609116 | [
"object"
] |
799f90e626012df768118718d41193611fada047 | 31,563 | h | C | VecGeom/volumes/SecondOrderSurfaceShell.h | cxwx/VecGeom | c86c00bd7d4db08f4fc20a625020da329784aaac | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2020-06-27T18:43:36.000Z | 2020-06-27T18:43:36.000Z | VecGeom/volumes/SecondOrderSurfaceShell.h | cxwx/VecGeom | c86c00bd7d4db08f4fc20a625020da329784aaac | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | VecGeom/volumes/SecondOrderSurfaceShell.h | cxwx/VecGeom | c86c00bd7d4db08f4fc20a625020da329784aaac | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | /// \file SecondOrderSurfaceShell.h
/// \author: swenzel
/// Created on: Aug 1, 2014
/// Modified and completed: mihaela.gheata@cern.ch
#ifndef VECGEOM_SECONDORDERSURFACESHELL_H_
#define VECGEOM_SECONDORDERSURFACESHELL_H_
#include "VecGeom/base/Vector3D.h"
#include "VecGeom/volumes/kernel/GenericKernels.h"
namespace vecgeom {
/**
* Templated class providing a (SOA) encapsulation of
* second order curved surfaces used in generic trap
*/
VECGEOM_DEVICE_FORWARD_DECLARE(class SecondOrderSurfaceShell;);
inline namespace VECGEOM_IMPL_NAMESPACE {
template <int N>
class SecondOrderSurfaceShell {
using Vertex_t = Vector3D<Precision>;
private:
// caching some important values for each of the curved planes
Precision fxa[N], fya[N], fxb[N], fyb[N], fxc[N], fyc[N], fxd[N], fyd[N]; /** Coordinates of vertices */
Precision ftx1[N], fty1[N], ftx2[N], fty2[N]; /** Connecting components */
Precision ft1crosst2[N]; /** Cross term ftx1[i]*fty2[i] - ftx2[i]*fty1[i] */
Precision fDeltatx[N]; /** Term ftx2[i] - ftx1[i] */
Precision fDeltaty[N]; /** Term fty2[i] - fty1[i] */
Precision fDz; /** height of surface (coming from the height of the GenTrap) */
Precision fDz2; /** 0.5/fDz */
Precision fiscurved[N]; /** Indicate which surfaces are planar */
bool fisplanar; /** Flag that all surfaces are planar */
bool fdegenerated[N]; /** Flags for each top-bottom edge marking that this is degenerated */
Vertex_t fNormals[N]; /** Pre-computed normals for the planar case */
// pre-computed cross products for normal computation
Vertex_t fViCrossHi0[N]; /** Pre-computed vi X hi0 */
Vertex_t fViCrossVj[N]; /** Pre-computed vi X vj */
Vertex_t fHi1CrossHi0[N]; /** Pre-computed hi1 X hi0 */
public:
/** @brief SecondOrderSurfaceShell dummy constructor */
VECCORE_ATT_HOST_DEVICE
SecondOrderSurfaceShell() : fDz(0), fDz2(0) {}
/** @brief SecondOrderSurfaceShell constructor
* @param verticesx X positions of vertices in array form
* @param verticesy Y positions of vertices in array form
* @param dz The half-height of the GenTrap
*/
VECCORE_ATT_HOST_DEVICE
SecondOrderSurfaceShell(const Precision *verticesx, const Precision *verticesy, Precision dz) : fDz(0.), fDz2(0.)
{
// Constructor
Initialize(verticesx, verticesy, dz);
}
VECCORE_ATT_HOST_DEVICE
void Initialize(const Precision *verticesx, const Precision *verticesy, Precision dz)
{
#ifndef VECCORE_CUDA
if (dz <= 0.) throw std::runtime_error("Half-length of generic trapezoid must be positive");
#endif
fDz = dz;
fDz2 = 0.5 / dz;
// Store vertex coordinates
Vertex_t va, vb, vc, vd;
for (int i = 0; i < N; ++i) {
int j = (i + 1) % N;
va.Set(verticesx[i], verticesy[i], -dz);
fxa[i] = verticesx[i];
fya[i] = verticesy[i];
vb.Set(verticesx[i + N], verticesy[i + N], dz);
fxb[i] = verticesx[i + N];
fyb[i] = verticesy[i + N];
vc.Set(verticesx[j], verticesy[j], -dz);
fxc[i] = verticesx[j];
fyc[i] = verticesy[j];
vd.Set(verticesx[j + N], verticesy[j + N], dz);
fxd[i] = verticesx[N + j];
fyd[i] = verticesy[N + j];
fdegenerated[i] = (Abs(fxa[i] - fxc[i]) < kTolerance) && (Abs(fya[i] - fyc[i]) < kTolerance) &&
(Abs(fxb[i] - fxd[i]) < kTolerance) && (Abs(fyb[i] - fyd[i]) < kTolerance);
ftx1[i] = fDz2 * (fxb[i] - fxa[i]);
fty1[i] = fDz2 * (fyb[i] - fya[i]);
ftx2[i] = fDz2 * (fxd[i] - fxc[i]);
fty2[i] = fDz2 * (fyd[i] - fyc[i]);
ft1crosst2[i] = ftx1[i] * fty2[i] - ftx2[i] * fty1[i];
fDeltatx[i] = ftx2[i] - ftx1[i];
fDeltaty[i] = fty2[i] - fty1[i];
fNormals[i] = Vertex_t::Cross(vb - va, vc - va);
// The computation of normals is done also for the curved surfaces, even if they will not be used
if (fNormals[i].Mag2() < kTolerance) {
// points i and i+1/N are overlapping - use i+N and j+N instead
fNormals[i] = Vertex_t::Cross(vb - va, vd - vb);
if (fNormals[i].Mag2() < kTolerance) fNormals[i].Set(0., 0., 1.); // No surface, just a line
}
fNormals[i].Normalize();
// Cross products used for normal computation
fViCrossHi0[i] = Vertex_t::Cross(vb - va, vc - va);
fViCrossVj[i] = Vertex_t::Cross(vb - va, vd - vc);
fHi1CrossHi0[i] = Vertex_t::Cross(vd - vb, vc - va);
}
// Analyze planarity and precompute normals
fisplanar = true;
for (int i = 0; i < N; ++i) {
fiscurved[i] = (((Abs(fxc[i] - fxa[i]) < kTolerance) && (Abs(fyc[i] - fya[i]) < kTolerance)) ||
((Abs(fxd[i] - fxb[i]) < kTolerance) && (Abs(fyd[i] - fyb[i]) < kTolerance)) ||
(Abs((fxc[i] - fxa[i]) * (fyd[i] - fyb[i]) - (fxd[i] - fxb[i]) * (fyc[i] - fya[i])) < kTolerance))
? 0
: 1;
if (fiscurved[i]) fisplanar = false;
}
}
//______________________________________________________________________________
template <typename Real_v>
VECGEOM_FORCE_INLINE
VECCORE_ATT_HOST_DEVICE
/** @brief Stripped down version of Inside method used for boundary and wrong side detection
* @param point Starting point in the local frame
* @param completelyinside Inside flag
* @param completelyoutside Onside flag
* @param onsurf On boundary flag
*/
void CheckInside(Vector3D<Real_v> const &point, vecCore::Mask_v<Real_v> &completelyinside,
vecCore::Mask_v<Real_v> &completelyoutside, vecCore::Mask_v<Real_v> &onsurf) const
{
using Bool_v = vecCore::Mask_v<Real_v>;
constexpr Precision tolerancesq = 10000. * kTolerance * kTolerance;
onsurf = Bool_v(false);
completelyinside = (Abs(point.z()) < MakeMinusTolerant<true>(fDz));
completelyoutside = (Abs(point.z()) > MakePlusTolerant<true>(fDz));
// if (vecCore::EarlyReturnAllowed()) {
if (vecCore::MaskFull(completelyoutside)) return;
// }
Real_v cross;
Real_v vertexX[N];
Real_v vertexY[N];
Real_v dzp = fDz + point[2];
// vectorizes for scalar backend
for (int i = 0; i < N; i++) {
// calculate x-y positions of vertex i at this z-height
vertexX[i] = fxa[i] + ftx1[i] * dzp;
vertexY[i] = fya[i] + fty1[i] * dzp;
}
Bool_v degenerated = Bool_v(true); // Can only happen if |zpoint| = fDz
for (int i = 0; i < N; i++) {
// if (fdegenerated[i])
// continue;
int j = (i + 1) % 4;
Real_v DeltaX = vertexX[j] - vertexX[i];
Real_v DeltaY = vertexY[j] - vertexY[i];
Real_v deltasq = DeltaX * DeltaX + DeltaY * DeltaY;
// If the current vertex is degenerated, ignore the check
Bool_v samevertex = deltasq < MakePlusTolerant<true>(0.);
degenerated = degenerated && samevertex;
// Cross product to check if point is right side or left side
// If vertices are same, this will be 0
cross = (point.x() - vertexX[i]) * DeltaY - (point.y() - vertexY[i]) * DeltaX;
onsurf = (cross * cross < tolerancesq * deltasq) && (!samevertex);
completelyoutside = completelyoutside || (((cross < MakeMinusTolerant<true>(0.)) && (!onsurf)));
completelyinside = completelyinside && (samevertex || ((cross > MakePlusTolerant<true>(0.)) && (!onsurf)));
}
onsurf = (!completelyoutside) && (!completelyinside);
// In fully degenerated case consider the point outside always
completelyoutside = completelyoutside || degenerated;
}
//______________________________________________________________________________
template <typename Real_v>
VECGEOM_FORCE_INLINE
VECCORE_ATT_HOST_DEVICE
/** @brief Compute distance to a set of curved/planar surfaces
* @param point Starting point in the local frame
* @param dir Direction in the local frame
*/
Real_v DistanceToOut(Vector3D<Real_v> const &point, Vector3D<Real_v> const &dir) const
{
using Bool_v = vecCore::Mask_v<Real_v>;
// Planar case
if (fisplanar) return DistanceToOutPlanar<Real_v>(point, dir);
// The algorithmic tolerance in distance
const Real_v tolerance(100. * kTolerance);
Real_v dist(InfinityLength<Real_v>());
Real_v smin[N], smax[N];
Vector3D<Real_v> unorm;
Real_v r(-1.0);
Real_v rz;
Bool_v completelyinside, completelyoutside, onsurf;
CheckInside<Real_v>(point, completelyinside, completelyoutside, onsurf);
// If on the wrong side, return -1.
Real_v wrongsidedist(-1.0);
vecCore::MaskedAssign(dist, completelyoutside, wrongsidedist);
if (vecCore::MaskFull(completelyoutside)) return dist;
// Solve the second order equation and return distance solutions for each surface
ComputeSminSmax<Real_v>(point, dir, smin, smax);
for (int i = 0; i < N; ++i) {
// Check if point(s) is(are) on boundary, and in this case compute normal
Bool_v crtbound = (Abs(smin[i]) < tolerance || Abs(smax[i]) < tolerance);
if (!vecCore::MaskEmpty(crtbound)) {
if (fiscurved[i])
UNormal<Real_v>(point, i, unorm, rz, r);
else
unorm = fNormals[i];
}
// Starting point may be propagated close to boundary
// === MaskedMultipleAssign needed
vecCore__MaskedAssignFunc(smin[i], !completelyoutside && Abs(smin[i]) < tolerance && dir.Dot(unorm) < 0,
InfinityLength<Real_v>());
vecCore__MaskedAssignFunc(smax[i], !completelyoutside && Abs(smax[i]) < tolerance && dir.Dot(unorm) < 0,
InfinityLength<Real_v>());
vecCore__MaskedAssignFunc(dist, !completelyoutside && (smin[i] > -tolerance) && (smin[i] < dist),
Max(smin[i], Real_v(0.)));
vecCore__MaskedAssignFunc(dist, !completelyoutside && (smax[i] > -tolerance) && (smax[i] < dist),
Max(smax[i], Real_v(0.)));
}
vecCore__MaskedAssignFunc(dist, dist < tolerance && onsurf, Real_v(0.));
return (dist);
} // end of function
//______________________________________________________________________________
/** @brief Compute distance to exiting the set of surfaces in the planar case.
* @param point Starting point in the local frame
* @param dir Direction in the local frame
*/
template <typename Real_v>
VECGEOM_FORCE_INLINE
VECCORE_ATT_HOST_DEVICE
Real_v DistanceToOutPlanar(Vector3D<Real_v> const &point, Vector3D<Real_v> const &dir) const
{
using Bool_v = vecCore::Mask_v<Real_v>;
// const Real_v tolerance = 100. * kTolerance;
Vertex_t va; // vertex i of lower base
Vector3D<Real_v> pa; // same vertex converted to backend type
Real_v distance = InfinityLength<Real_v>();
// Check every surface
Bool_v outside = (Abs(point.z()) > MakePlusTolerant<true>(fDz)); // If point is outside, we need to know
for (int i = 0; i < N && (!vecCore::MaskFull(outside)); ++i) {
if (fdegenerated[i]) continue;
// Point A is the current vertex on lower Z. P is the point we come from.
pa.Set(Real_v(fxa[i]), Real_v(fya[i]), Real_v(-fDz));
Vector3D<Real_v> vecAP = point - pa;
// Dot product between AP vector and normal to surface has to be negative
Real_v dotAPNorm = vecAP.Dot(fNormals[i]);
Bool_v otherside = (dotAPNorm > 10. * kTolerance);
// Dot product between direction and normal to surface has to be positive
Real_v dotDirNorm = dir.Dot(fNormals[i]);
Bool_v outgoing = (dotDirNorm > 0.);
// Update globally outside flag
outside = outside || otherside;
Bool_v valid = outgoing && (!otherside);
if (vecCore::MaskEmpty(valid)) continue;
Real_v snext = -dotAPNorm / NonZero(dotDirNorm);
vecCore__MaskedAssignFunc(distance, valid && snext < distance, Max(snext, Real_v(0.)));
}
// Return -1 for points actually outside
vecCore__MaskedAssignFunc(distance, distance < kTolerance, Real_v(0.));
vecCore__MaskedAssignFunc(distance, outside, Real_v(-1.));
return distance;
}
//______________________________________________________________________________
/** @brief Compute distance to entering the set of surfaces in the planar case.
* @param point Starting point in the local frame
* @param dir Direction in the local frame
*/
template <typename Real_v>
VECGEOM_FORCE_INLINE
VECCORE_ATT_HOST_DEVICE
Real_v DistanceToInPlanar(Vector3D<Real_v> const &point, Vector3D<Real_v> const &dir,
vecCore::Mask_v<Real_v> &done) const
{
// const Real_v tolerance = 100. * kTolerance;
using Bool_v = vecCore::Mask_v<Real_v>;
Vertex_t va; // vertex i of lower base
Vector3D<Real_v> pa; // same vertex converted to backend type
Real_v distance = InfinityLength<Real_v>();
// Check every surface
Bool_v inside = (Abs(point.z()) < MakeMinusTolerant<true>(fDz)); // If point is inside, we need to know
for (int i = 0; i < N; ++i) {
if (fdegenerated[i]) continue;
// Point A is the current vertex on lower Z. P is the point we come from.
pa.Set(Real_v(fxa[i]), Real_v(fya[i]), Real_v(-fDz));
Vector3D<Real_v> vecAP = point - pa;
// Dot product between AP vector and normal to surface has to be positive
Real_v dotAPNorm = vecAP.Dot(fNormals[i]);
Bool_v otherside = (dotAPNorm < -10. * kTolerance);
// Dot product between direction and normal to surface has to be negative
Real_v dotDirNorm = dir.Dot(fNormals[i]);
Bool_v ingoing = (dotDirNorm < 0.);
// Update globally outside flag
inside = inside && otherside;
Bool_v valid = ingoing && (!otherside);
if (vecCore::MaskEmpty(valid)) continue;
Real_v snext = -dotAPNorm / NonZero(dotDirNorm);
// Now propagate the point to surface and check if in range
Vector3D<Real_v> psurf = point + snext * dir;
valid = valid && InSurfLimits<Real_v>(psurf, i);
vecCore__MaskedAssignFunc(distance, (!done) && valid && snext < distance, Max(snext, Real_v(0.)));
}
// Return -1 for points actually inside
vecCore__MaskedAssignFunc(distance, (!done) && (distance < kTolerance), Real_v(0.));
vecCore__MaskedAssignFunc(distance, (!done) && inside, Real_v(-1.));
return distance;
}
//______________________________________________________________________________
template <typename Real_v>
VECGEOM_FORCE_INLINE
VECCORE_ATT_HOST_DEVICE
/**
* A generic function calculation the distance to a set of curved/planar surfaces
*
* things to improve: error handling for boundary cases
*
* another possibility relies on the following idea:
* we always have an even number of planar/curved surfaces. We could organize them in separate substructures...
*/
Real_v DistanceToIn(Vector3D<Real_v> const &point, Vector3D<Real_v> const &dir, vecCore::Mask_v<Real_v> &done) const
{
// Planar case
using Bool_v = vecCore::Mask_v<Real_v>;
if (fisplanar) return DistanceToInPlanar<Real_v>(point, dir, done);
Real_v crtdist;
Vector3D<Real_v> hit;
Real_v distance = InfinityLength<Real_v>();
Real_v tolerance(100. * kTolerance);
Vector3D<Real_v> unorm;
Real_v r(-1.0);
Real_v rz;
Bool_v completelyinside, completelyoutside, onsurf;
CheckInside<Real_v>(point, completelyinside, completelyoutside, onsurf);
// If on the wrong side, return -1.
Real_v wrongsidedist(-1.0);
vecCore::MaskedAssign(distance, Bool_v(completelyinside && (!done)), wrongsidedist);
Bool_v checked = completelyinside || done;
if (vecCore::MaskFull(checked)) return (distance);
// Now solve the second degree equation to find crossings
Real_v smin[N], smax[N];
ComputeSminSmax<Real_v>(point, dir, smin, smax);
// now we need to analyse which of those distances is good
// does not vectorize
for (int i = 0; i < N; ++i) {
crtdist = smin[i];
// Extrapolate with hit distance candidate
hit = point + crtdist * dir;
Bool_v crossing = (crtdist > -tolerance) && (Abs(hit.z()) < fDz + kTolerance);
// Early skip surface if not in Z range
if (!vecCore::MaskEmpty(Bool_v(crossing && (!checked)))) {
// Compute local un-normalized outwards normal direction and hit ratio factors
UNormal<Real_v>(hit, i, unorm, rz, r);
// Distance have to be positive within tolerance, and crossing must be inwards
crossing = crossing && dir.Dot(unorm) < 0.;
// Propagated hitpoint must be on surface (rz in [0,1] checked already)
crossing = crossing && (r >= 0.) && (r <= 1.);
vecCore__MaskedAssignFunc(distance, crossing && (!checked) && crtdist < distance, Max(crtdist, Real_v(0.)));
}
// For the particle(s) not crossing at smin, try smax
if (!vecCore::MaskFull(Bool_v(crossing || checked))) {
// Treat only particles not crossing at smin
crossing = !crossing;
crtdist = smax[i];
hit = point + crtdist * dir;
crossing = crossing && (crtdist > -tolerance) && (Abs(hit.z()) < fDz + kTolerance);
if (vecCore::MaskEmpty(crossing)) continue;
if (fiscurved[i])
UNormal<Real_v>(hit, i, unorm, rz, r);
else
unorm = fNormals[i];
crossing = crossing && (dir.Dot(unorm) < 0.);
crossing = crossing && (r >= 0.) && (r <= 1.);
vecCore__MaskedAssignFunc(distance, crossing && (!checked) && crtdist < distance, Max(crtdist, Real_v(0.)));
}
}
vecCore__MaskedAssignFunc(distance, distance < tolerance && onsurf, Real_v(0.));
return (distance);
} // end distanceToIn function
//______________________________________________________________________________
/**
* @brief A generic function calculation for the safety to a set of curved/planar surfaces.
Should be smaller than safmax
* @param point Starting point inside, in the local frame
* @param safmax current safety value
*/
template <typename Real_v>
VECGEOM_FORCE_INLINE
VECCORE_ATT_HOST_DEVICE
Real_v SafetyToOut(Vector3D<Real_v> const &point, Real_v const &safmax) const
{
using Bool_v = vecCore::Mask_v<Real_v>;
constexpr Precision eps = 100. * kTolerance;
Real_v safety = safmax;
Bool_v done = (Abs(safety) < eps);
if (vecCore::MaskFull(done)) return (safety);
Real_v safetyface = InfinityLength<Real_v>();
// loop lateral surfaces
// We can use the surface normals to get safety for non-curved surfaces
Vertex_t va; // vertex i of lower base
Vector3D<Real_v> pa; // same vertex converted to backend type
if (fisplanar) {
for (int i = 0; i < N; ++i) {
if (fdegenerated[i]) continue;
va.Set(fxa[i], fya[i], -fDz);
pa = va;
safetyface = (pa - point).Dot(fNormals[i]);
vecCore::MaskedAssign(safety, (safetyface < safety) && (!done), safetyface);
}
vecCore__MaskedAssignFunc(safety, Abs(safety) < eps, Real_v(0.));
return safety;
}
// Not fully planar - use mixed case
safetyface = SafetyCurved<Real_v>(point, Bool_v(true));
// std::cout << "safetycurved = " << safetyface << std::endl;
vecCore::MaskedAssign(safety, (safetyface < safety) && (!done), safetyface);
// std::cout << "safety = " << safety << std::endl;
vecCore__MaskedAssignFunc(safety, safety > 0. && safety < eps, Real_v(0.));
return safety;
} // end SafetyToOut
//______________________________________________________________________________
/**
* @brief A generic function calculation for the safety to a set of curved/planar surfaces.
Should be smaller than safmax
* @param point Starting point outside, in the local frame
* @param safmax current safety value
*/
template <typename Real_v>
VECGEOM_FORCE_INLINE
VECCORE_ATT_HOST_DEVICE
Real_v SafetyToIn(Vector3D<Real_v> const &point, Real_v const &safmax) const
{
using Bool_v = vecCore::Mask_v<Real_v>;
constexpr Precision eps = 100. * kTolerance;
Real_v safety = safmax;
Bool_v done = (Abs(safety) < eps);
if (vecCore::MaskFull(done)) return (safety);
Real_v safetyface = InfinityLength<Real_v>();
// loop lateral surfaces
// We can use the surface normals to get safety for non-curved surfaces
Vertex_t va; // vertex i of lower base
Vector3D<Real_v> pa; // same vertex converted to backend type
if (fisplanar) {
for (int i = 0; i < N; ++i) {
if (fdegenerated[i]) continue;
va.Set(fxa[i], fya[i], -fDz);
pa = va;
safetyface = (point - pa).Dot(fNormals[i]);
vecCore::MaskedAssign(safety, (safetyface > safety) && (!done), safetyface);
}
vecCore__MaskedAssignFunc(safety, Abs(safety) < eps, Real_v(0.));
return safety;
}
// Not fully planar - use mixed case
safetyface = SafetyCurved<Real_v>(point, Bool_v(false));
// std::cout << "safetycurved = " << safetyface << std::endl;
vecCore::MaskedAssign(safety, (safetyface > safety) && (!done), safetyface);
// std::cout << "safety = " << safety << std::endl;
vecCore__MaskedAssignFunc(safety, safety > 0. && safety < eps, Real_v(0.));
return (safety);
} // end SafetyToIn
//______________________________________________________________________________
/**
* @brief A generic function calculation for the safety to a set of curved/planar surfaces.
Should be smaller than safmax
* @param point Starting point
* @param in Inside value for starting point
*/
template <typename Real_v>
VECGEOM_FORCE_INLINE
VECCORE_ATT_HOST_DEVICE
Real_v SafetyCurved(Vector3D<Real_v> const &point, vecCore::Mask_v<Real_v> in) const
{
using Bool_v = vecCore::Mask_v<Real_v>;
Real_v safety = InfinityLength<Real_v>();
Real_v safplanar = InfinityLength<Real_v>();
Real_v tolerance = Real_v(100 * kTolerance);
vecCore__MaskedAssignFunc(tolerance, !in, -tolerance);
// loop over edges connecting points i with i+4
Real_v dx, dy, dpx, dpy, lsq, u;
Real_v dx1 = Real_v(0.);
Real_v dx2 = Real_v(0.);
Real_v dy1 = Real_v(0.);
Real_v dy2 = Real_v(0.);
Bool_v completelyinside, completelyoutside, onsurf;
CheckInside<Real_v>(point, completelyinside, completelyoutside, onsurf);
if (vecCore::MaskFull(onsurf)) return (Real_v(0.));
Bool_v wrong = in && (completelyoutside);
wrong = wrong || ((!in) && completelyinside);
if (vecCore::MaskFull(wrong)) {
return (Real_v(-1.));
}
Real_v vertexX[N];
Real_v vertexY[N];
Real_v dzp = fDz + point[2];
for (int i = 0; i < N; i++) {
// calculate x-y positions of vertex i at this z-height
vertexX[i] = fxa[i] + ftx1[i] * dzp;
vertexY[i] = fya[i] + fty1[i] * dzp;
}
Real_v umin = Real_v(0.);
for (int i = 0; i < N; i++) {
if (fiscurved[i] == 0) {
// We can use the surface normals to get safety for non-curved surfaces
Vector3D<Real_v> pa; // same vertex converted to backend type
pa.Set(Real_v(fxa[i]), Real_v(fya[i]), Real_v(-fDz));
Real_v sface = Abs((point - pa).Dot(fNormals[i]));
vecCore::MaskedAssign(safplanar, sface < safplanar, sface);
continue;
}
int j = (i + 1) % N;
dx = vertexX[j] - vertexX[i];
dy = vertexY[j] - vertexY[i];
dpx = point[0] - vertexX[i];
dpy = point[1] - vertexY[i];
lsq = dx * dx + dy * dy;
u = (dpx * dx + dpy * dy) / NonZero(lsq);
vecCore__MaskedAssignFunc(dpx, u > 1, point[0] - vertexX[j]);
vecCore__MaskedAssignFunc(dpy, u > 1, point[1] - vertexY[j]);
vecCore__MaskedAssignFunc(dpx, u >= 0 && u <= 1, dpx - u * dx);
vecCore__MaskedAssignFunc(dpy, u >= 0 && u <= 1, dpy - u * dy);
Real_v ssq = dpx * dpx + dpy * dpy; // safety squared
vecCore__MaskedAssignFunc(dx1, ssq < safety, Real_v(fxc[i] - fxa[i]));
vecCore__MaskedAssignFunc(dx2, ssq < safety, Real_v(fxd[i] - fxb[i]));
vecCore__MaskedAssignFunc(dy1, ssq < safety, Real_v(fyc[i] - fya[i]));
vecCore__MaskedAssignFunc(dy2, ssq < safety, Real_v(fyd[i] - fyb[i]));
vecCore::MaskedAssign(umin, ssq < safety, u);
vecCore::MaskedAssign(safety, ssq < safety, ssq);
}
vecCore__MaskedAssignFunc(umin, umin < 0 || umin > 1, Real_v(0.));
dx = dx1 + umin * (dx2 - dx1);
dy = dy1 + umin * (dy2 - dy1);
// Denominator below always positive as fDz>0
safety *= 1. - 4. * fDz * fDz / (dx * dx + dy * dy + 4. * fDz * fDz);
safety = Sqrt(safety);
vecCore::MaskedAssign(safety, safplanar < safety, safplanar);
vecCore__MaskedAssignFunc(safety, wrong, -safety);
vecCore__MaskedAssignFunc(safety, onsurf, Real_v(0.));
return safety;
} // end SafetyCurved
VECCORE_ATT_HOST_DEVICE
VECGEOM_FORCE_INLINE
Vertex_t const *GetNormals() const { return fNormals; }
//______________________________________________________________________________
/**
* @brief Computes if point on surface isurf is within surface limits
* @param point Starting point
* @param isurf Surface index
*/
template <typename Real_v>
VECGEOM_FORCE_INLINE
VECCORE_ATT_HOST_DEVICE
vecCore::Mask_v<Real_v> InSurfLimits(Vector3D<Real_v> const &point, int isurf) const
{
using Bool_v = vecCore::Mask_v<Real_v>;
// Check first if Z is in range
Real_v rz = fDz2 * (point.z() + fDz);
Bool_v insurf = (rz > MakeMinusTolerant<true>(0.)) && (rz < MakePlusTolerant<true>(1.));
if (vecCore::MaskEmpty(insurf)) return insurf;
Real_v r = InfinityLength<Real_v>();
Real_v num = (point.x() - fxa[isurf]) - rz * (fxb[isurf] - fxa[isurf]);
Real_v denom = (fxc[isurf] - fxa[isurf]) + rz * (fxd[isurf] - fxc[isurf] - fxb[isurf] + fxa[isurf]);
vecCore__MaskedAssignFunc(r, (Abs(denom) > 1.e-6), num / NonZero(denom));
num = (point.y() - fya[isurf]) - rz * (fyb[isurf] - fya[isurf]);
denom = (fyc[isurf] - fya[isurf]) + rz * (fyd[isurf] - fyc[isurf] - fyb[isurf] + fya[isurf]);
vecCore__MaskedAssignFunc(r, (Abs(denom) > 1.e-6), num / NonZero(denom));
insurf = insurf && (r > MakeMinusTolerant<true>(0.)) && (r < MakePlusTolerant<true>(1.));
return insurf;
}
//______________________________________________________________________________
/** @brief Computes un-normalized normal to surface isurf, on the input point */
template <typename Real_v>
VECGEOM_FORCE_INLINE
VECCORE_ATT_HOST_DEVICE
void UNormal(Vector3D<Real_v> const &point, int isurf, Vector3D<Real_v> &unorm, Real_v &rz, Real_v &r) const
{
// unorm = (vi X hi0) + rz*(vi X vj) + r*(hi1 X hi0)
// where: vi, vj are the vectors (AB) and (CD) (see constructor)
// hi0 = (AC) and hi1 = (BD)
// rz = 0.5*(point.z()+dz)/dz is the vertical ratio
// r = ((AP)-rz*vi) / (hi0+rz(vj-vi)) is the horizontal ratio
// Any point within the surface range should reurn r and rz in the range [0,1]
// These can be used as surface crossing criteria
rz = fDz2 * (point.z() + fDz);
/*
Vector3D<Real_v> a(fxa[isurf], fya[isurf], -fDz);
Vector3D<Real_v> vi(fxb[isurf]-fxa[isurf], fyb[isurf]-fya[isurf], 2*fDz);
Vector3D<Real_v> vj(fxd[isurf]-fxc[isurf], fyd[isurf]-fyc[isurf], 2*fDz);
Vector3D<Real_v> hi0(fxc[isurf]-fxa[isurf], fyc[isurf]-fya[isurf], 0.);
*/
Real_v num = (point.x() - fxa[isurf]) - rz * (fxb[isurf] - fxa[isurf]);
Real_v denom = (fxc[isurf] - fxa[isurf]) + rz * (fxd[isurf] - fxc[isurf] - fxb[isurf] + fxa[isurf]);
vecCore__MaskedAssignFunc(r, Abs(denom) > 1.e-6, num / NonZero(denom));
num = (point.y() - fya[isurf]) - rz * (fyb[isurf] - fya[isurf]);
denom = (fyc[isurf] - fya[isurf]) + rz * (fyd[isurf] - fyc[isurf] - fyb[isurf] + fya[isurf]);
vecCore__MaskedAssignFunc(r, Abs(denom) > 1.e-6, num / NonZero(denom));
unorm = (Vector3D<Real_v>)fViCrossHi0[isurf] + rz * (Vector3D<Real_v>)fViCrossVj[isurf] +
r * (Vector3D<Real_v>)fHi1CrossHi0[isurf];
} // end UNormal
//______________________________________________________________________________
/** @brief Solver for the second degree equation for curved surface crossing */
template <typename Real_v>
VECGEOM_FORCE_INLINE
VECCORE_ATT_HOST_DEVICE
/**
* Function to compute smin and smax crossings with the N lateral surfaces.
*/
void ComputeSminSmax(Vector3D<Real_v> const &point, Vector3D<Real_v> const &dir, Real_v smin[N], Real_v smax[N]) const
{
const Real_v big = InfinityLength<Real_v>();
Real_v dzp = fDz + point[2];
// calculate everything needed to solve the second order equation
Real_v a[N], b[N], c[N], d[N];
Real_v signa[N], inva[N];
// vectorizes
for (int i = 0; i < N; ++i) {
Real_v xs1 = fxa[i] + ftx1[i] * dzp;
Real_v ys1 = fya[i] + fty1[i] * dzp;
Real_v xs2 = fxc[i] + ftx2[i] * dzp;
Real_v ys2 = fyc[i] + fty2[i] * dzp;
Real_v dxs = xs2 - xs1;
Real_v dys = ys2 - ys1;
a[i] = (fDeltatx[i] * dir[1] - fDeltaty[i] * dir[0] + ft1crosst2[i] * dir[2]) * dir[2];
b[i] = dxs * dir[1] - dys * dir[0] +
(fDeltatx[i] * point[1] - fDeltaty[i] * point[0] + fty2[i] * xs1 - fty1[i] * xs2 + ftx1[i] * ys2 -
ftx2[i] * ys1) *
dir[2];
c[i] = dxs * point[1] - dys * point[0] + xs1 * ys2 - xs2 * ys1;
d[i] = b[i] * b[i] - 4 * a[i] * c[i];
}
// does not vectorize
for (int i = 0; i < N; ++i) {
// zero or one to start with
signa[i] = Real_v(0.);
vecCore__MaskedAssignFunc(signa[i], a[i] < -kTolerance, Real_v(-1.));
vecCore__MaskedAssignFunc(signa[i], a[i] > kTolerance, Real_v(1.));
inva[i] = c[i] / NonZero(b[i] * b[i]);
vecCore__MaskedAssignFunc(inva[i], Abs(a[i]) > kTolerance, 1. / NonZero(2. * a[i]));
}
// vectorizes
for (int i = 0; i < N; ++i) {
// treatment for curved surfaces. Invalid solutions will be excluded.
Real_v sqrtd = signa[i] * Sqrt(Abs(d[i]));
vecCore::MaskedAssign(sqrtd, d[i] < 0., big);
// what is the meaning of this??
smin[i] = (-b[i] - sqrtd) * inva[i];
smax[i] = (-b[i] + sqrtd) * inva[i];
}
// For the planar surfaces, the above may be wrong, redo the work using
// just the normal. This does not vectorize
for (int i = 0; i < N; ++i) {
if (fiscurved[i]) continue;
Vertex_t va; // vertex i of lower base
Vector3D<Real_v> pa; // same vertex converted to backend type
// Point A is the current vertex on lower Z. P is the point we come from.
pa.Set(Real_v(fxa[i]), Real_v(fya[i]), Real_v(-fDz));
Vector3D<Real_v> vecAP = point - pa;
// Dot product between AP vector and normal to surface has to be negative
Real_v dotAPNorm = vecAP.Dot(fNormals[i]);
// Dot product between direction and normal to surface has to be positive
Real_v dotDirNorm = dir.Dot(fNormals[i]);
smin[i] = -dotAPNorm / NonZero(dotDirNorm);
smax[i] = InfinityLength<Real_v>(); // not to be checked
}
} // end ComputeSminSmax
}; // end class definition
} // namespace VECGEOM_IMPL_NAMESPACE
} // namespace vecgeom
#endif /* SECONDORDERSURFACESHELL_H_ */
| 43.355769 | 120 | 0.631499 | [
"vector"
] |
79a82e4e6f76e6cc2f2f01c160828206cb50c87b | 822 | h | C | base/pnp/tools/infscan/precomp.h | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | base/pnp/tools/infscan/precomp.h | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | base/pnp/tools/infscan/precomp.h | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | #include <windows.h>
#include <objbase.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <tchar.h>
#include <setupapi.h>
#include <msg.h>
#include <process.h>
#include <new> // causes the 'new' operator to throw bad_alloc
#include <list>
#include <map>
#include <set>
#include <utility>
#include <vector>
#include <sstream>
#include <iomanip>
using namespace std ;
#include "safestring.h"
#include "common.h"
#include "blob.h"
#include "filters.h"
#include "worker.h"
#include "verinfo.h"
#include "parseinfctx.h"
#include "sppriv.h"
#include "globalscan.h"
#include "installscan.h"
#include "infscan.h"
//
// inline code
//
#include "common.inl"
#include "filters.inl"
#include "infscan.inl"
#include "installscan.inl"
#include "parseinfctx.inl"
| 18.681818 | 68 | 0.6691 | [
"vector"
] |
79a85aaba6b88d9d0d94cd69bb942475b79368e0 | 951 | h | C | design-patterns/design-patterns/Structural/Proxy/YoutubeManager/DPSYoutubeManager.h | danabeknar/design-patterns | 7e6b4a23c7725b01b38939e35554992830cc53ac | [
"MIT"
] | 12 | 2018-11-21T07:11:09.000Z | 2019-05-13T15:01:06.000Z | design-patterns/design-patterns/Structural/Proxy/YoutubeManager/DPSYoutubeManager.h | danabeknar/design-patterns | 7e6b4a23c7725b01b38939e35554992830cc53ac | [
"MIT"
] | null | null | null | design-patterns/design-patterns/Structural/Proxy/YoutubeManager/DPSYoutubeManager.h | danabeknar/design-patterns | 7e6b4a23c7725b01b38939e35554992830cc53ac | [
"MIT"
] | 1 | 2020-06-16T16:30:52.000Z | 2020-06-16T16:30:52.000Z | //
// DPSYoutubeManager.h
// design-patterns
//
// Created by Beknar Danabek on 13/03/2019.
// Copyright © 2019 beknar. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "DPSThirdPartyYoutubeLib.h"
// The GUI class that uses the service object. Instead of a real service, we will slip an object to him as a substitute.
// The client will not notice anything, as the proxy has the same interface as the service.”
@interface DPSYoutubeManager : NSObject
/**
Initialization with object implementing DPSThirdPartyYoutubeLib;
@param service Object implementing DPSThirdPartyYoutubeLib.
@return DPSCachedThirdPartyYoutubeLib object.
*/
- (instancetype)initWithService:(id<DPSThirdPartyYoutubeLib>)service;
/// Display the video page.
- (void)renderVideoPage;
/// Display a list of thumbnails of videos.
- (void)renderListPanel;
/// Display video page and thumbnails of videos at the same time.
- (void)handleUserInput;
@end
| 27.970588 | 120 | 0.764458 | [
"object"
] |
79ac4ada1da7d54731e53f98baacb0030cdfec9f | 981 | h | C | lib_ergc/utils.h | jbellis/superpixel-benchmark | 81a45649d426751d1ae450ef8ea0d2d9c7b3545f | [
"Unlicense"
] | 344 | 2016-12-16T10:11:05.000Z | 2022-03-29T06:08:14.000Z | lib_ergc/utils.h | jbellis/superpixel-benchmark | 81a45649d426751d1ae450ef8ea0d2d9c7b3545f | [
"Unlicense"
] | 12 | 2018-02-15T19:34:19.000Z | 2021-07-31T17:04:48.000Z | lib_ergc/utils.h | jbellis/superpixel-benchmark | 81a45649d426751d1ae450ef8ea0d2d9c7b3545f | [
"Unlicense"
] | 111 | 2016-12-08T07:19:21.000Z | 2022-03-29T06:08:16.000Z |
#ifndef __UTILS_H
#define __UTILS_H
#include <string>
#include <sstream>
#include <vector>
#include <stdio.h>
using namespace std;
vector<string> split_string(string line,string delim) {
string str=line;
vector<string> res;
size_t found;
found=str.find(delim);
while(found!=string::npos) {
string substr=str.substr(0,found);
res.push_back(substr);
str=str.substr(found+1,str.size()-found);
found=str.find(delim);
}
res.push_back(str);
return res;
}
string toString(int k) {
std::ostringstream out;
out << k;
return out.str();
}
void writeProgress (const char *what, int value, int max) {
const char *symbols = "\\|/-";
const char *sym = "";
if (*sym == '\0')
sym = symbols;
if (max)
fprintf (stdout, "%s: %c Processed: %d (%d%%) \r", what, *sym++, value, 100 * value / max);
else
fprintf (stdout, "%s: %c Processed: %d \r", what, *sym++, value);
fflush (stdout);
}
#endif // __UTILS_H
| 18.166667 | 97 | 0.61264 | [
"vector"
] |
79aeeff0a6119ad19e4b3b92d655630781d1299c | 5,667 | c | C | treecc.c.c | chrissch33/Binary-Tree-Level-Order-Print | 94b8f6fd299fc8fa2202704b78eecd579383e269 | [
"MIT"
] | 1 | 2019-06-14T06:18:05.000Z | 2019-06-14T06:18:05.000Z | treecc.c.c | chrissch33/Binary-Tree-Level-Order-Print | 94b8f6fd299fc8fa2202704b78eecd579383e269 | [
"MIT"
] | null | null | null | treecc.c.c | chrissch33/Binary-Tree-Level-Order-Print | 94b8f6fd299fc8fa2202704b78eecd579383e269 | [
"MIT"
] | null | null | null | // Created by: Christopher Schenkhuizen
// Most Recent Change: Updated comments to be more descriptive and added a full header
// Most Recent Change Date: 1/19/17
// This is completely original code and I do not mind if you use it, just please give me credit
// or I will be sad.
// Welcome to my C program that attempts to print a tree in "Level Order" or in
// more common terms, a Breadth-First search and then print.
// WARNING: The logic of this program is rather abstract using numbers converted
// to binary as a map of the tree. Drawing the tree and the binary values
// will help when trying to DEBUG or understand the code here.
// TODO: Add the following functions:
// - returns the number of levels of the binary tree (recursive?)
// TODO: Modify the following functions that already have functionality:
// - print function to add the appropriate number of spaces for larger
// numbers to keep a pleasing visual
// - Within the main method, add safeguards against NULL nodes when
// navigating through the tree
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// defining a basic structure node
typedef struct node {
struct node *left; // Binary tree left
struct node *right; // Binary tree right
int data; // Symbolic use of an int to represent anything the node could hold
} t_node;
// Function to create a new Binary Tree
// Essentially just returns a node with no pointers to any other node
t_node* t_new(int data) {
t_node* new = (t_node*) malloc(sizeof(t_node));
new->data = data;
new->left = NULL;
new->right = NULL;
return new;
}
// Using a head node, recursively adds a node in a binary fashion of greater than
// or less than, putting the node into the right or left respectively
t_node* t_insert(t_node* root, int data) {
if (root) { // NULL check
// This line here adds the node to the left of the root if the value is less
// than the head node (uses recursive call)
if (root->data >= data) root->left = t_insert(root->left, data);
else root->right = t_insert(root->right, data);
// returns the node to which the value was added below
return root;
}
// if the root was NULL, just create a new node
else {
return t_new(data);
}
}
// completely frees a tree of all nodes
// This is a recursive function
void t_clean(t_node* node) {
if (node) {
t_clean(node->left);
t_clean(node->right);
}
free(node);
}
// A quick function to do powers for testing purposes
int power(int a, int b) {
if (b == 0) return 1;
if (b < 0) return 0;
int temp, i;
temp = a;
for (i = 1; i < b; i++) {
a *= temp;
}
return a;
}
// Main method for testing purposes
int main() {
// The size of the array here is just the number of nodes in the tree
int* levelorder = (int*) malloc(sizeof(int) * 7);
int count = 1;
// Code block adds nodes to a tree to test if the tree properly properly adds nodes
t_node* root = t_new(5);
t_insert(root, 3);
t_insert(root, 7);
t_insert(root, 4);
t_insert(root, 1);
t_insert(root, 6);
t_insert(root, 11);
// A known value to me. Could be derrived through a recursive or looped function
int levels = 3;
// In order the print the tree in level order, I use a binary number to model
// the left vs right search
int binary;
// A pointer to take the place of the root without modifying the root pointer
t_node* place = root;
// Begin to record the data in level order and place it in an array
levelorder[0] = root->data;
// l is for the upper for loop to go through the levels of the array
// i is for going through the binary tree to keep track of the Left-Right pointer
// location of each node in the level
// c is to keep track of the maximum number of nodes allowed in a level (powers of 2)
// and to allow the most inner for-loop to go through each node in a level
int l, i, c;
// Loop through the levels of the binary tree
for (l = 2; l < levels + 1; l++) {
// reset the binary number to the proper number of values (powers of 2) for the current level
binary = power(2, l) - 1;
// Loops through the maximum number of nodes in a level
for (c = 0; c < power(2, l - 1); c++) {
// Reset the current placeholder called place to the root node
place = root;
// Loop through the binary number from before in terms of bits
for (i = l - 2; i >= 0; i--) {
// A switch statement to either move left or right down the binary tree
// given the binary map of the tree (using binary numbers)
switch (1 & (binary >> i)) {
// A 1 represents moving left down the tree
case 1:
place = place->left;
break;
// A 0 represents moving right down the tree
case 0:
place = place->right;
break;
// A safeguard against disaster and syntactical nessessity
default:
printf("ERROR! NOT BINARY!\n");
return 0;
}
}
// Change the binary map of the node by moving right along the tree (subtract 1)
binary--;
// A NULL node check
if (place)
// Inset the value of the node found after the binary navigation into the
// array of its values
levelorder[count] = place->data;
// Increment the place within the array and the count of the current number
// of nodes
count++;
}
}
// Begin the print function
printf("\n");
// The array holds the data values in level order, just print out the values now
for (i = 0; i < 7; i++) {
printf("%d\n", levelorder[i]);
}
// Release the memory held by the tree and free the memory of the nodes
t_clean(root);
// Return successful completion of the print function
return 0;
}
| 29.061538 | 95 | 0.672137 | [
"model"
] |
79c1045fc300402c04ab357481e2c8454f2f5070 | 1,955 | h | C | src/blockparttable.h | sizeofvoid/openbsdisks2 | 4bc053a9d15f4e367a9f7601e7e506cd3d72bd7c | [
"BSD-3-Clause"
] | 7 | 2021-05-13T07:43:10.000Z | 2022-01-09T12:18:48.000Z | src/blockparttable.h | sizeofvoid/openbsdisks2 | 4bc053a9d15f4e367a9f7601e7e506cd3d72bd7c | [
"BSD-3-Clause"
] | null | null | null | src/blockparttable.h | sizeofvoid/openbsdisks2 | 4bc053a9d15f4e367a9f7601e7e506cd3d72bd7c | [
"BSD-3-Clause"
] | null | null | null | /*
Copyright 2016 Gleb Popov <6yearold@gmail.com>
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.
*/
#pragma once
#include <QString>
#include <QStringList>
#include <memory>
class BlockPartTable
{
public:
BlockPartTable() = default;
void setTableType(const QString&);
QString tableType() const;
private:
QStringList partitionBlockNames;
QString m_tableType;
};
using TBlockPartTable = std::shared_ptr<BlockPartTable>;
using TBlockPartTableVec = std::vector<TBlockPartTable>;
| 39.1 | 80 | 0.770844 | [
"vector"
] |
79c69334f33dbe86c10d9d59b167787c054482b8 | 1,304 | h | C | src/guiTypeChartPlotter.h | ofTheo/ofxControlPanel | 04724ad86b82f1b7aa38895caff226ad967d518b | [
"MIT"
] | 34 | 2015-01-19T15:57:49.000Z | 2022-03-23T00:02:21.000Z | src/guiTypeChartPlotter.h | ofTheo/ofxControlPanel | 04724ad86b82f1b7aa38895caff226ad967d518b | [
"MIT"
] | 5 | 2015-09-24T18:07:46.000Z | 2021-03-05T19:49:46.000Z | src/guiTypeChartPlotter.h | ofTheo/ofxControlPanel | 04724ad86b82f1b7aa38895caff226ad967d518b | [
"MIT"
] | 10 | 2015-04-22T00:56:35.000Z | 2021-11-02T03:44:35.000Z | /*
* guiTypeChartPlotter.h
* ofxControlPanelDemo
*
* Created by theo on 01/04/2010.
* Copyright 2010 __MyCompanyName__. All rights reserved.
*
*/
#pragma once
#include "guiBaseObject.h"
class guiTypeChartPlotter : public guiBaseObject {
public:
guiTypeChartPlotter(){
minVal = 0.0;
maxVal = 1.0;
maxNum = 100;
}
virtual void setup(float minValY, float maxValY);
float getVerticalSpacing();
void updateText();
virtual void update();
void render();
#ifndef OFX_CONTROL_PANEL_NO_BATCH_RENDER
void addToRenderMesh( ofMesh& arenderMesh );
void addToLinesRenderMesh( ofMesh& arenderMesh );
virtual void addToTextRenderMesh( ofMesh& arenderMesh );
// ofMesh mTextMesh;
#endif
float minVal, maxVal;
vector <float> valueHistory;
int maxNum;
};
class guiTypeFPSChartPlotter : public guiTypeChartPlotter {
public:
virtual void setup(float minValY, float maxValY) override {
mFramerate.set("Framerate", 60.f );
value.addValue(mFramerate);
guiTypeChartPlotter::setup(minValY, maxValY);
}
virtual void update() override {
mFramerate = ofGetFrameRate();
guiTypeChartPlotter::update();
}
protected:
ofParameter<float> mFramerate;
};
| 21.733333 | 63 | 0.667178 | [
"render",
"vector"
] |
79dc4e1dd8b30b4ba4192d11ffcbdc18aedfa15c | 9,639 | c | C | chip/habitat/slur/slur.c | Museum-of-Art-and-Digital-Entertainment/Habitat | b59e2520fd8690bf99a1db43928a679f2fbc875c | [
"MIT"
] | 530 | 2016-07-06T19:49:59.000Z | 2022-03-01T20:52:50.000Z | chip/habitat/slur/slur.c | webyrd/habitat | 6f54b01b6d72deb081c24390c62ebfd9105e9e69 | [
"MIT"
] | 2 | 2017-04-14T01:32:33.000Z | 2017-04-29T15:23:54.000Z | chip/habitat/slur/slur.c | webyrd/habitat | 6f54b01b6d72deb081c24390c62ebfd9105e9e69 | [
"MIT"
] | 45 | 2016-07-07T20:05:13.000Z | 2021-12-27T19:50:47.000Z | /*
slur: Stupid Little Utility for Riddle
Turns contents vectors from Aric's region editor into riddle fragments.
Chip Morningstar
Lucasfilm Ltd.
18-June-1986
*/
#include <stdio.h>
#include "class_defs.h"
typedef unsigned char byte;
typedef unsigned short word;
typedef int bool;
#define TRUE 1
#define FALSE 0
typedef struct {
byte class;
byte isContainer;
byte style;
byte x;
byte y;
byte orientation;
byte animationState;
byte containedBy;
} object;
#define THE_REGION 0
#define CLASS_MAX 256
#define SIZE_OFFSET 12 /* was 11, then we added LRC checking */
int classSizes[CLASS_MAX];
char *className[CLASS_MAX] = {
#include "classNames.h"
};
#define OBJECT_MAX 256
object *objects[OBJECT_MAX];
int currentContainer;
char *regionName = NULL;
int tabLevel;
char *northNeighbor = NULL;
char *southNeighbor = NULL;
char *eastNeighbor = NULL;
char *westNeighbor = NULL;
char *direction = NULL;
char *teleportAddress = NULL;
bool turfFlag = FALSE;
char *classFileName = "class.dat";
FILE *classFyle;
FILE *cvFyle = stdin;
FILE *ofyle = stdout;
#define CV_MAX 256
byte contentsVector[CV_MAX];
void examineObjects();
void initialize();
void inputContentsVector();
int inputContentsVectorChunk();
void inputData();
void inputNoidClassList();
byte *malloc();
void repairObject();
void outputObject();
void outputRiddleFragment();
byte readByte();
void readClassFile();
word readWord();
void tab();
main(argc, argv)
int argc;
char *argv[];
{
initialize(argc, argv);
readClassFile();
inputContentsVector();
outputRiddleFragment();
}
void
initialize(argc, argv)
int argc;
char *argv[];
{
int i;
int j;
char **args;
char *arg;
for (i=0; i<OBJECT_MAX; ++i) {
objects[i] = NULL;
}
args = argv + 1;
for (i=1; i<argc; i++) {
arg = *args++;
if (*arg != '-') {
if ((cvFyle = fopen(arg, "r")) == NULL) {
fprintf(stderr, "slur: can't open cv file '%s'\n", arg);
exit(1);
}
continue;
}
for (j=1; arg[j]!='\0'; j++) switch (arg[j]) {
case 'c':
if (++i >= argc) {
fprintf(stderr, "slur: no class file name given on line after '-c'\n");
exit(1);
} else {
classFileName = *args++;
}
continue;
case 'o':
if (++i >= argc) {
fprintf(stderr, "slur: no output file name given online after '-o'\n");
exit(1);
} else if ((ofyle = fopen(*args, "w")) == NULL) {
fprintf(stderr, "slur: can't open output file '%s'\n", *args);
exit(1);
}
args++;
continue;
case 't':
turfFlag = TRUE;
continue;
case 'r':
if (++i >= argc) {
fprintf(stderr, "slur: no region name given on line after '-r'\n");
exit(1);
} else {
regionName = *args++;
}
continue;
case 'd':
if (++i >= argc) {
fprintf(stderr, "slur: no orientation direction given on line after '-d'\n");
exit(1);
} else {
direction = *args++;
}
continue;
case 'n':
if (++i >= argc) {
fprintf(stderr, "slur: no north neighbor name given on line after '-n'\n");
exit(1);
} else {
northNeighbor = *args++;
}
continue;
case 's':
if (++i >= argc) {
fprintf(stderr, "slur: no south neighbor name given on line after '-s'\n");
exit(1);
} else {
southNeighbor = *args++;
}
continue;
case 'e':
if (++i >= argc) {
fprintf(stderr, "slur: no east neighbor name given on line after '-e'\n");
exit(1);
} else {
eastNeighbor = *args++;
}
continue;
case 'w':
if (++i >= argc) {
fprintf(stderr, "slur: no west name given on line after '-w'\n");
exit(1);
} else {
westNeighbor = *args++;
}
continue;
case 'p':
if (++i >= argc) {
fprintf(stderr, "slur: no teleport address given on line after '-p'\n");
exit(1);
} else {
teleportAddress = *args++;
}
continue;
default:
fprintf(stderr, "slur: bad command line flag '%s'\n",
arg[j]);
continue;
}
}
if ((classFyle = fopen(classFileName, "r")) == NULL) {
fprintf(stderr, "slur: can't open class file '%s'\n",
classFileName);
exit(1);
}
}
void
readClassFile()
{
int i;
for (i=0; i<CLASS_MAX; ++i)
classSizes[i] = readWord(classFyle);
for (i=0; i<CLASS_MAX; ++i)
if (classSizes[i] == 0xFFFF)
classSizes[i] = 0;
else {
fseek(classFyle, classSizes[i]+SIZE_OFFSET, 0);
classSizes[i] = readByte(classFyle) & 0x7F;
}
}
void
inputContentsVector()
{
currentContainer = THE_REGION;
while ((currentContainer = inputContentsVectorChunk()) != 0)
;
}
int
inputContentsVectorChunk()
{
inputNoidClassList();
inputData();
return(readByte(cvFyle));
}
void
inputNoidClassList()
{
byte *cvPtr;
cvPtr = contentsVector;
while ((*cvPtr++ = readByte(cvFyle)) != 0)
*cvPtr++ = readByte(cvFyle);
}
void
inputData()
{
byte *cvPtr;
byte *optr;
int size;
int noid;
int class;
cvPtr = contentsVector;
while (*cvPtr != 0) {
noid = *cvPtr++;
optr = malloc((size = classSizes[class = *cvPtr++]) + 2);
objects[noid] = (object *)optr;
*optr++ = class;
*optr++ = FALSE;
while (size-- > 0)
*optr++ = readByte(cvFyle);
}
}
byte
readByte(fyle)
FILE *fyle;
{
return((byte)getc(fyle));
}
word
readWord(fyle)
FILE *fyle;
{
byte lo;
byte hi;
lo = readByte(fyle);
hi = readByte(fyle);
return((hi << 8) + lo);
}
void
outputRiddleFragment()
{
int i;
examineObjects();
if (regionName == NULL)
fprintf(ofyle, "@region {\n");
else
fprintf(ofyle, "@region $ %s {\n", regionName);
if (northNeighbor != NULL)
fprintf(ofyle, " north: %s.l;\n", northNeighbor);
if (southNeighbor != NULL)
fprintf(ofyle, " south: %s.l;\n", southNeighbor);
if (eastNeighbor != NULL)
fprintf(ofyle, " east: %s.l;\n", eastNeighbor);
if (westNeighbor != NULL)
fprintf(ofyle, " west: %s.l;\n", westNeighbor);
if (turfFlag)
fprintf(ofyle, " region_owner: 0.l;\n");
if (direction != NULL)
fprintf(ofyle, " region_orientation: %s;\n", direction);
fprintf(ofyle, " [\n");
tabLevel = 2;
for (i=0; i<OBJECT_MAX; ++i)
if (objects[i] != NULL && objects[i]->containedBy == 0) {
repairObject(objects[i]);
outputObject(objects[i]);
}
fprintf(ofyle, " ]\n");
fprintf(ofyle, "}\n");
}
void
examineObjects()
{
int i;
for (i=0; i<OBJECT_MAX; ++i)
if (objects[i] != NULL)
objects[i]->isContainer = FALSE;
for (i=0; i<OBJECT_MAX; ++i)
if (objects[i] != NULL && objects[i]->containedBy != 0)
objects[objects[i]->containedBy]->isContainer = TRUE;
}
#define OPEN_BIT 0x01
#define CLOSED_BIT 0x00
#define UNLOCKED_BIT 0x02
#define LOCKED_BIT 0x00
#define OPEN OPEN_BIT | UNLOCKED_BIT
#define CLOSED CLOSED_BIT | UNLOCKED_BIT
#define LOCKED CLOSED_BIT | LOCKED_BIT
void
repairObject(obj)
object *obj;
{
byte *dataPtr;
int i;
dataPtr = ((byte *)obj) + 8;
switch (obj->class) {
case CLASS_BAG:
case CLASS_BOX:
case CLASS_CHEST:
case CLASS_DOOR:
case CLASS_HOLE:
case CLASS_SAFE:
dataPtr[0] = CLOSED;
break;
case CLASS_COUNTERTOP:
case CLASS_DISPLAY_CASE:
case CLASS_GARBAGE_CAN:
case CLASS_TABLE:
case CLASS_VENDO_FRONT:
case CLASS_VENDO_INSIDE:
case CLASS_PAWN_MACHINE:
case CLASS_GLUE:
case CLASS_CRAT_IN_A_BOX:
dataPtr[0] = OPEN;
break;
case CLASS_BED:
case CLASS_CHAIR:
case CLASS_COUCH:
dataPtr[0] = OPEN;
break;
case CLASS_AMULET:
case CLASS_GEMSTONE:
case CLASS_MAGIC_STAFF:
case CLASS_MAGIC_WAND:
case CLASS_RING:
dataPtr[0] = 1;
break;
case CLASS_AQUARIUM:
case CLASS_BOTTLE:
dataPtr[0] = obj->animationState;
break;
case CLASS_DRUGS:
dataPtr[0] = 5;
break;
case CLASS_ESCAPE_DEVICE:
dataPtr[0] = 3;
break;
case CLASS_FAKE_GUN:
dataPtr[0] = obj->animationState;
case CLASS_FLASHLIGHT:
dataPtr[0] = 0;
break;
case CLASS_FLOOR_LAMP:
dataPtr[0] = 1;
break;
case CLASS_KEY:
dataPtr[0] = dataPtr[1] = 0xFF;
break;
case CLASS_KNICK_KNACK:
dataPtr[1] = 0;
dataPtr[0] = 0;
break;
case CLASS_PLANT:
case CLASS_ROCK:
dataPtr[0] = 1;
break;
case CLASS_TOKENS:
dataPtr[0] = 10;
dataPtr[1] = 0;
break;
}
}
void
outputObject(obj)
object *obj;
{
byte *dataPtr;
int i;
tab();
fprintf(ofyle, "@%s { ", className[obj->class]);
fprintf(ofyle, "x:%d; y:%d; or:%d; ", obj->x, obj->y, obj->orientation);
if (obj->style != 0)
fprintf(ofyle, "style:%d; ", obj->style);
if (obj->animationState != 0)
fprintf(ofyle, "gr_state:%d; ", obj->animationState);
if (classSizes[obj->class] == 6) {
fprintf(ofyle, "}\n");
return;
} else {
dataPtr = ((byte *)obj) + 8;
fprintf(ofyle, "\n"); tabLevel++;
for (i=7; i<=classSizes[obj->class]; ++i) {
tab(); fprintf(ofyle, "%d:%d;\n", i+1, *dataPtr++);
}
if (obj->class == CLASS_TELEPORT_BOOTH || obj->class ==
CLASS_ELEVATOR) {
i = 0;
tab(); fprintf(ofyle, "teleport_address: ");
if (teleportAddress != NULL)
for (; i<20 & teleportAddress[i]!='\0'; ++i)
if (i < 19)
fprintf(ofyle, "%d, ", teleportAddress[i]);
else
fprintf(ofyle, "%d;\n",teleportAddress[i]);
for (; i<20; ++i)
if (i < 19)
fprintf(ofyle, "%d, ", ' ');
else
fprintf(ofyle, "%d;\n", ' ');
}
tabLevel--;
}
if (obj->isContainer) {
tabLevel++;
fprintf(ofyle, "\n"); tab(); fprintf(ofyle, "[\n");
tabLevel++;
for (i=0; i<OBJECT_MAX; ++i)
if (objects[i] != NULL && objects[objects[i]->
containedBy] == obj) {
repairObject(objects[i]);
outputObject(objects[i]);
}
tabLevel--;
tab(); fprintf(ofyle, "]\n");
tabLevel--;
}
tab(); fprintf(ofyle, "}\n");
}
void
tab()
{
int i;
for (i=tabLevel; i>0; --i)
fprintf(ofyle, " ");
}
| 19.394366 | 81 | 0.611474 | [
"object"
] |
79e7c842f036686de9699284220a3f86901cc1cb | 2,765 | h | C | inc/db/MojDbMediaHandler.h | webosce/db8 | 994da8732319c6cafc59778eec5f82186f73b6ab | [
"Apache-2.0"
] | 4 | 2018-03-22T19:06:10.000Z | 2021-01-22T10:50:10.000Z | inc/db/MojDbMediaHandler.h | webosce/db8 | 994da8732319c6cafc59778eec5f82186f73b6ab | [
"Apache-2.0"
] | 5 | 2018-05-01T16:12:28.000Z | 2018-11-10T06:08:20.000Z | inc/db/MojDbMediaHandler.h | webosose/db8 | f89ea600f0505395f8f995923fd9b0c94ece5915 | [
"Apache-2.0"
] | 5 | 2018-03-22T19:06:12.000Z | 2018-08-21T05:52:46.000Z | // Copyright (c) 2013-2018 LG Electronics, 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.
//
// SPDX-License-Identifier: Apache-2.0
#ifndef MOJDBMEDIAHANDLER_H
#define MOJDBMEDIAHANDLER_H
#include "core/MojSignal.h"
#include "core/MojObject.h"
#include "core/MojServiceRequest.h"
#include "db/MojDbDefs.h"
#include "db/MojDbShardInfo.h"
#include <map>
#include <set>
#include <mutex>
class MojDbMediaHandler : public MojSignalHandler
{
typedef std::map<MojString, MojDbShardInfo> shard_cache_t;
typedef MojServiceRequest::ReplySignal::Slot<MojDbMediaHandler> Slot;
typedef MojRefCountedPtr<MojServiceRequest> ServiceRequest;
struct LunaRequest
{
LunaRequest(MojDbMediaHandler *parentClass, Slot::MethodType method);
MojErr subscribe(MojService *service, const MojChar *serviceName, const MojChar *methodName);
MojErr subscribe(MojService *service, const MojChar *serviceName, const MojChar *methodName, MojObject *payload);
MojErr send(MojService *service, const MojChar *serviceName, const MojChar *methodName, MojObject *payload, MojUInt32 numReplies = 1);
Slot m_slot;
ServiceRequest m_subscription;
};
public:
MojDbMediaHandler(MojDb &db);
MojErr configure(const MojObject& configure);
MojErr subscribe(MojService &service);
MojErr close();
MojErr handleDeviceListResponse(MojObject &payload, MojErr errCode);
private:
MojErr sendRelease(const MojString &deviceId, const MojString &subDeviceId, MojErr errCode);
MojErr sendUnRegister();
MojErr handleRegister(MojObject &payload, MojErr errCode);
MojErr handleUnRegister(MojObject &payload, MojErr errCode);
MojErr handleRelease(MojObject &payload, MojErr errCode);
MojErr cbDeviceListResponse(MojObject &payload, MojErr errCode);
MojErr convert(const MojObject &object, MojDbShardInfo &shardInfo);
bool existInCache(const MojString &id);
void copyShardCache(std::set<MojString> *);
LunaRequest m_deviceList;
LunaRequest m_deviceRegister;
LunaRequest m_deviceRelease;
LunaRequest m_deviceUnregister;
MojString m_serviceName;
MojService *m_service;
MojDb &m_db;
shard_cache_t m_shardCache;
std::mutex m_lock;
};
#endif
| 32.529412 | 142 | 0.749005 | [
"object"
] |
79ea54def67a5f839afa7490326819e94ae91696 | 3,783 | h | C | export/FileSequence.h | imageworks/Field3D | 0cf75ad982917e0919f59e5cb3d483517d06d7da | [
"BSD-3-Clause"
] | 169 | 2015-01-14T17:22:19.000Z | 2021-10-06T10:13:12.000Z | export/FileSequence.h | imageworks/Field3D | 0cf75ad982917e0919f59e5cb3d483517d06d7da | [
"BSD-3-Clause"
] | 14 | 2015-06-03T14:19:17.000Z | 2021-06-03T13:22:53.000Z | export/FileSequence.h | imageworks/Field3D | 0cf75ad982917e0919f59e5cb3d483517d06d7da | [
"BSD-3-Clause"
] | 53 | 2015-02-11T03:53:46.000Z | 2021-10-06T10:13:15.000Z | //----------------------------------------------------------------------------//
/*
* Copyright (c) 2014 Sony Pictures Imageworks Inc
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 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 Sony Pictures Imageworks 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.
*/
//----------------------------------------------------------------------------//
/*! \file FileSequence.h
\brief Contains the FileSequence class which can be used to turn strings
such as "file.1-20#.f3d" into a vector of strings
*/
//----------------------------------------------------------------------------//
#ifndef _INCLUDED_Field3D_FileSequence_H_
#define _INCLUDED_Field3D_FileSequence_H_
//----------------------------------------------------------------------------//
#include <string>
#include <vector>
//----------------------------------------------------------------------------//
#include "ns.h"
FIELD3D_NAMESPACE_OPEN
//----------------------------------------------------------------------------//
// FileSequence
//----------------------------------------------------------------------------//
class FileSequence
{
public:
// Typedefs ---
typedef std::vector<std::string> StringVec;
// Ctors, dtor ---
//! Default constructor. Creates an empty sequence
FileSequence()
{ }
//! Construct from a sequence string. If the sequence string is an actual
//! filename, we become a 1-length sequence. If the sequence can't be
//! resolved, we become a 0-length sequence.
//! \note Apart from checking if the sequence is itself a filename, no
//! checks are made to see that the actual resulting files exist.
FileSequence(const std::string &sequence);
//! Number of files in sequence
size_t size() const
{ return m_filenames.size(); }
//! Returns a single filename
const std::string& filename(const size_t idx) const
{ return m_filenames[idx]; }
//! Returns the full list of all filenames
const StringVec& filenames() const
{ return m_filenames; }
private:
// Data members ------------------------------------------------------------
//! Stores the resulting filenames
std::vector<std::string> m_filenames;
};
//----------------------------------------------------------------------------//
FIELD3D_NAMESPACE_HEADER_CLOSE
//----------------------------------------------------------------------------//
#endif // Include guard
| 33.776786 | 80 | 0.589479 | [
"vector"
] |
fbddd053ffdd9b56a417e11f215c153f3dd269a1 | 2,358 | c | C | common/motor/dualHBridgeMotor.c | f4deb/cen-electronic | 74302fb38cf41e060ccaf9435ccd8e8792f3e565 | [
"MIT"
] | null | null | null | common/motor/dualHBridgeMotor.c | f4deb/cen-electronic | 74302fb38cf41e060ccaf9435ccd8e8792f3e565 | [
"MIT"
] | null | null | null | common/motor/dualHBridgeMotor.c | f4deb/cen-electronic | 74302fb38cf41e060ccaf9435ccd8e8792f3e565 | [
"MIT"
] | null | null | null | #include "dualHBridgeMotor.h"
#include <stdlib.h>
#include "../../common/timer/cenTimer.h"
#include "../../common/timer/timerConstants.h"
#include "../../common/timer/timerList.h"
//#include "pin.h"
void initDualHBridge(DualHBridgeMotor* dualHBridgeMotor,
dualHBridgeMotorInitFunction* dualHBridgeMotorInit,
dualHBridgeMotorReadValueFunction* dualHBridgeMotorReadValue,
dualHBridgeMotorWriteValueFunction* dualHBridgeMotorWriteValue,
dualHBridgeMotorGetSoftwareRevisionFunction* dualHBridgeMotorGetSoftwareRevision,
int* object) {
dualHBridgeMotor->dualHBridgeMotorInit = dualHBridgeMotorInit;
dualHBridgeMotor->dualHBridgeMotorReadValue = dualHBridgeMotorReadValue;
dualHBridgeMotor->dualHBridgeMotorWriteValue = dualHBridgeMotorWriteValue;
dualHBridgeMotor->pin1StopEventType = NO_ACTION;
dualHBridgeMotor->pin2StopEventType = NO_ACTION;
dualHBridgeMotor->dualHBridgeMotorGetSoftwareRevision = dualHBridgeMotorGetSoftwareRevision;
dualHBridgeMotor->object = object;
}
void stopMotors(DualHBridgeMotor* dualHBridgeMotor) {
dualHBridgeMotor->dualHBridgeMotorWriteValue(dualHBridgeMotor, 0, 0);
}
void setMotorSpeeds(DualHBridgeMotor* dualHBridgeMotor, signed int hBridgeSpeed1, signed int hBridgeSpeed2) {
dualHBridgeMotor->dualHBridgeMotorWriteValue(dualHBridgeMotor, hBridgeSpeed1, hBridgeSpeed2);
}
// TIMER PART
/**
* The interrupt timer to know if we must stop the motor.
*/
void interruptMotorTimerCallbackFunc(Timer* timer) {
DualHBridgeMotor* dualHBridgeMotor = (DualHBridgeMotor*) timer->object;
if (dualHBridgeMotor->pin1UsageType != NO_USAGE) {
enum DualHBridgePinStopEventType pin1Stop = dualHBridgeMotor->pin1StopEventType;
/*
switch (pin1Stop):
case NO_ACTION:
}
if (pin1Stop != NO_ACTION) {
}
*/
}
}
void initDualHBridgeTimer(DualHBridgeMotor* dualHBridgeMotor) {
Timer* motorTimer = getTimerByCode(MOTOR_TIMER_CODE);
// Avoid to add several timer of the same nature
if (motorTimer == NULL) {
addTimer(MOTOR_TIMER_CODE,
TIME_DIVIDER_10_HERTZ,
&interruptMotorTimerCallbackFunc,
"MOTOR",
(int*) dualHBridgeMotor);
}
}
| 36.84375 | 110 | 0.712468 | [
"object"
] |
fbe41406447775caadc51f937cbe29558ebae6f2 | 7,257 | c | C | usb/sample/device/liteos/lib/src/lib_acm_test.c | openharmony-sig-ci/drivers_peripheral | 071339eec73d506f5de2107879a1f87e5f563172 | [
"Apache-2.0"
] | null | null | null | usb/sample/device/liteos/lib/src/lib_acm_test.c | openharmony-sig-ci/drivers_peripheral | 071339eec73d506f5de2107879a1f87e5f563172 | [
"Apache-2.0"
] | null | null | null | usb/sample/device/liteos/lib/src/lib_acm_test.c | openharmony-sig-ci/drivers_peripheral | 071339eec73d506f5de2107879a1f87e5f563172 | [
"Apache-2.0"
] | 2 | 2021-09-13T11:30:23.000Z | 2021-09-13T12:06:17.000Z | /*
* Copyright (c) 2013-2019, Huawei Technologies Co., Ltd. All rights reserved.
* Copyright (c) 2020, Huawei Device Co., Ltd. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 3. Neither the name of 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 "securec.h"
#include "hdf_log.h"
#include "osal_mem.h"
#include "hdf_io_service_if.h"
#include <unistd.h>
#include <sys/time.h>
#include <stdio.h>
#include "osal_thread.h"
#include "osal_mutex.h"
#include "osal_time.h"
#include "securec.h"
#define HDF_LOG_TAG cdc_acm_write
enum UsbSerialCmd {
USB_SERIAL_OPEN = 0,
USB_SERIAL_CLOSE,
USB_SERIAL_READ,
USB_SERIAL_WRITE,
USB_SERIAL_GET_BAUDRATE,
USB_SERIAL_SET_BAUDRATE,
USB_SERIAL_SET_PROP,
USB_SERIAL_GET_PROP,
USB_SERIAL_REGIST_PROP,
};
struct HdfSBuf *g_data;
struct HdfSBuf *g_reply;
struct HdfIoService *g_acmService;
int32_t check_service()
{
if (g_acmService == NULL || g_acmService->dispatcher == NULL || g_acmService->dispatcher->Dispatch == NULL) {
HDF_LOGE("%s: GetService err", __func__);
return HDF_FAILURE;
}
if (g_data == NULL || g_reply == NULL) {
HDF_LOGE("%s: GetService err", __func__);
return HDF_FAILURE;
}
return HDF_SUCCESS;
}
void acm_open()
{
int status;
g_acmService = HdfIoServiceBind("usbfn_cdcacm");
if (g_acmService == NULL || g_acmService->dispatcher == NULL || g_acmService->dispatcher->Dispatch == NULL) {
HDF_LOGE("%s: GetService err", __func__);
}
g_data = HdfSBufObtainDefaultSize();
g_reply = HdfSBufObtainDefaultSize();
if (g_data == NULL || g_reply == NULL) {
HDF_LOGE("%s: GetService err", __func__);
}
status = g_acmService->dispatcher->Dispatch(&g_acmService->object, USB_SERIAL_OPEN, g_data, g_reply);
if (status) {
HDF_LOGE("%s: Dispatch USB_SERIAL_OPEN err", __func__);
}
}
void acm_close()
{
int status;
if (check_service()) {
HDF_LOGE("%s: GetService err", __func__);
return;
}
status = g_acmService->dispatcher->Dispatch(&g_acmService->object, USB_SERIAL_CLOSE, g_data, g_reply);
if (status) {
HDF_LOGE("%s: Dispatch USB_SERIAL_CLOSE err", __func__);
}
HdfSBufRecycle(g_data);
HdfSBufRecycle(g_reply);
HdfIoServiceRecycle(g_acmService);
}
void acm_write(const char *buf)
{
if (check_service()) {
HDF_LOGE("%s: GetService err", __func__);
return;
}
HdfSbufFlush(g_data);
(void)HdfSbufWriteString(g_data, buf);
int status = g_acmService->dispatcher->Dispatch(&g_acmService->object, USB_SERIAL_WRITE, g_data, g_reply);
if (status <= 0) {
HDF_LOGE("%s: Dispatch USB_SERIAL_WRITE failed status = %d", __func__, status);
return;
}
printf("acm_write:%s\n", buf);
}
void acm_read(char *str, int timeout)
{
int ret;
if (check_service()) {
HDF_LOGE("%s: GetService err", __func__);
return;
}
while(timeout-- > 0) {
HdfSbufFlush(g_reply);
int status = g_acmService->dispatcher->Dispatch(&g_acmService->object, USB_SERIAL_READ, g_data, g_reply);
if (status) {
HDF_LOGE("%s: Dispatch USB_SERIAL_READ failed status = %d", __func__, status);
return;
}
const char *tmp = HdfSbufReadString(g_reply);
if (str && tmp && strlen(tmp) > 0) {
ret = memcpy_s(str, 256, tmp, strlen(tmp));
if (ret != EOK) {
HDF_LOGE("%s:%d ret=%d memcpy_s error", ret);
}
printf("acm_read:%s\n", tmp);
return;
}
sleep(1);
}
}
void acm_prop_regist(const char *propName, const char *propValue)
{
if (check_service()) {
HDF_LOGE("%s: GetService err", __func__);
return;
}
HdfSbufFlush(g_data);
(void)HdfSbufWriteString(g_data, propName);
(void)HdfSbufWriteString(g_data, propValue);
int status = g_acmService->dispatcher->Dispatch(&g_acmService->object, USB_SERIAL_REGIST_PROP, g_data, g_reply);
if (status) {
HDF_LOGE("%s: Dispatch USB_SERIAL_WRITE failed status = %d", __func__, status);
return;
}
printf("prop_regist:%s = %s\n", propName, propValue);
}
void acm_prop_write(const char *propName, const char *propValue)
{
if (check_service()) {
HDF_LOGE("%s: GetService err", __func__);
return;
}
HdfSbufFlush(g_data);
HdfSbufFlush(g_reply);
(void)HdfSbufWriteString(g_data, propName);
(void)HdfSbufWriteString(g_data, propValue);
if (g_acmService == NULL || g_acmService->dispatcher == NULL || g_acmService->dispatcher->Dispatch == NULL) {
HDF_LOGE("%s: GetService err", __func__);
}
int status = g_acmService->dispatcher->Dispatch(&g_acmService->object, USB_SERIAL_SET_PROP, g_data, g_reply);
if (status) {
HDF_LOGE("%s: Dispatch USB_SERIAL_WRITE failed status = %d", __func__, status);
return;
}
printf("prop_write:%s = %s\n", propName, propValue);
}
void acm_prop_read(const char *propName, char *propValue)
{
if (check_service()) {
HDF_LOGE("%s: GetService err", __func__);
return;
}
HdfSbufFlush(g_data);
HdfSbufFlush(g_reply);
(void)HdfSbufWriteString(g_data, propName);
int status = g_acmService->dispatcher->Dispatch(&g_acmService->object, USB_SERIAL_GET_PROP, g_data, g_reply);
if (status) {
HDF_LOGE("%s: Dispatch USB_SERIAL_GET_PROP failed status = %d", __func__, status);
return;
}
const char *tmp = HdfSbufReadString(g_reply);
if (propValue && tmp && strlen(tmp) > 0) {
errno_t err = memcpy_s(propValue, 256, tmp, strlen(tmp));
if (err != EOK) {
HDF_LOGE("%s:%d err=%d memcpy_s error", err);
}
printf("prop_read:%s\n", tmp);
return;
}
}
| 34.557143 | 116 | 0.665151 | [
"object"
] |
fbea71b516411a10800fe710f0e703de119016fc | 1,996 | h | C | graphics/cgal/Mesh_3/doc/Mesh_3/Concepts/MeshFacetCriteria_3.h | hlzz/dotfiles | 0591f71230c919c827ba569099eb3b75897e163e | [
"BSD-3-Clause"
] | 4 | 2016-03-30T14:31:52.000Z | 2019-02-02T05:01:32.000Z | graphics/cgal/Mesh_3/doc/Mesh_3/Concepts/MeshFacetCriteria_3.h | hlzz/dotfiles | 0591f71230c919c827ba569099eb3b75897e163e | [
"BSD-3-Clause"
] | null | null | null | graphics/cgal/Mesh_3/doc/Mesh_3/Concepts/MeshFacetCriteria_3.h | hlzz/dotfiles | 0591f71230c919c827ba569099eb3b75897e163e | [
"BSD-3-Clause"
] | null | null | null | /*!
\ingroup PkgMesh_3Concepts
\cgalConcept
The Delaunay refinement process involved in the
template functions `make_mesh_3()` and `refine_mesh_3()`
is guided by a set of elementary refinement criteria
that concern either mesh tetrahedra or surface facets.
The concept `MeshFacetCriteria_3` describes the types that
handle the refinement criteria for surface facets.
\cgalHasModel `CGAL::Mesh_facet_criteria_3<Tr>`
\sa `MeshCellCriteria_3`
\sa `MeshEdgeCriteria_3`
\sa `MeshCriteria_3`
\sa `CGAL::make_mesh_3()`
\sa `CGAL::refine_mesh_3()`
*/
class MeshFacetCriteria_3 {
public:
/// \name Types
/// @{
/*!
Type for the facets of the
triangulation. Must match the `Facet` type in the
triangulation type used by the mesh generation function.
*/
typedef unspecified_type Facet;
/*!
Handle type for the cells of the
triangulation. Must match the `Cell_handle` type in the
triangulation type used by the mesh generation function.
*/
typedef unspecified_type Cell_handle;
/*!
Type representing the quality of a
facet. Must be a model of CopyConstructible and
LessThanComparable. Between two facets, the one which has the lower
quality must have the lower `Facet_quality`.
*/
typedef unspecified_type Facet_quality;
/*!
Type representing if a facet is bad or not. This type
must be convertible to `bool`. If it converts to `true` then the facet is bad, otherwise
the facet is good with regard to the criteria.
In addition, an object of this type must contain an object of type
`Facet_quality` if it represents
a bad facet. `Facet_quality` must be accessible by
`operator*()`. Note that `boost::optional<Facet_quality>` is
a natural model of this concept
*/
typedef unspecified_type Is_facet_bad;
/// @}
/// \name Operations
/// @{
/*!
Returns `Is_facet_bad` value of facet `f`.
*/
Is_facet_bad operator()(Facet f);
/*!
Same as above with `f=(c,i)`.
*/
Is_facet_bad operator()(Cell_handle c, int i);
/// @}
}; /* end MeshFacetCriteria_3 */
| 24.641975 | 89 | 0.73998 | [
"mesh",
"object",
"model"
] |
fbf07a07d95c919ab647352db00daec222a08be1 | 830 | c | C | nitan/d/gumu/qianliu3.c | cantona/NT6 | 073f4d491b3cfe6bfbe02fbad12db8983c1b9201 | [
"MIT"
] | 1 | 2019-03-27T07:25:16.000Z | 2019-03-27T07:25:16.000Z | nitan/d/gumu/qianliu3.c | cantona/NT6 | 073f4d491b3cfe6bfbe02fbad12db8983c1b9201 | [
"MIT"
] | null | null | null | nitan/d/gumu/qianliu3.c | cantona/NT6 | 073f4d491b3cfe6bfbe02fbad12db8983c1b9201 | [
"MIT"
] | null | null | null | // This program is a part of NT MudLIB
#include <ansi.h>;
inherit ROOM;
void create()
{
set("short", HIR"潛流"NOR);
set("long", @LONG
你沒在水中,只覺水勢甚急,衝得你無法立足。你氣悶異常,只得屏氣摸
索潛行,當真是進退維谷。突覺下面似有股強大吸力把你猛往下扯,你不由自主地往下沉去.
LONG
);
setup();
}
void init()
{
object me;
me = this_player();
me->receive_damage("qi", 500 );
me->receive_damage("jing", 500 );
message_vision(HIB"$N的真氣正在流失,呼吸十分困難。\n"NOR, me);
call_out("down", 5, me);
if( query("qi", me)<10 || query("jing", me)<10 )
{
set_temp("die_reason", "在潛流中被淹死", me);
me->unconcious();
me->die();
return ;
}
}
void down(object me)
{
tell_object(me, "只覺腳底水流盤旋,一股強大的吸力把你往下拉去...\n");
me->move(__DIR__"hedi");
}
| 20.75 | 56 | 0.519277 | [
"object"
] |
fbf3013c7bd391890a6d2082f493ab0cf3ee2cbc | 757 | h | C | src/classes.h | Zirias/stoneage | 0c94d97ff9a5f6356b1243e123ee2e13cb1eb645 | [
"BSD-2-Clause-FreeBSD"
] | 1 | 2022-01-13T15:45:49.000Z | 2022-01-13T15:45:49.000Z | src/classes.h | Zirias/stoneage | 0c94d97ff9a5f6356b1243e123ee2e13cb1eb645 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | src/classes.h | Zirias/stoneage | 0c94d97ff9a5f6356b1243e123ee2e13cb1eb645 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | #ifndef STONEAGE_CLASSES_H
#define STONEAGE_CLASSES_H
/** @file classes.h
* Contains CLASS type registry
*/
/** Enumeration of all CLASS types
* Every class must be registered here, this info is needed for
* "RTTI" and secure CAST() functionality
*
* A notable exception is the class "Event". It does not inherit from Object
* and thus does not support RTTI. It is also not possible to inherit from
* "Event".
*/
enum Type {
CLASS_Screen,
CLASS_Board,
CLASS_Move,
CLASS_Level,
CLASS_EEarth,
CLASS_EWall,
CLASS_ERock,
CLASS_ECabbage,
CLASS_EWilly,
CLASS_SaMkres,
CLASS_Resource,
CLASS_Resfile,
CLASS_Stoneage,
CLASS_Entity,
CLASS_App,
CLASS_Object
};
typedef enum Type Type;
#endif
| 20.459459 | 76 | 0.704095 | [
"object"
] |
fbf37cc92b6a25fb82d3bf86c33b5e7bf5f0c00a | 658 | h | C | Classes/Networking/RequestBody/TMJSONEncodedRequestBody.h | turlodales/TMTumblrSDK | af5fa629a088ead0064f28ec5d611a59c25ca353 | [
"Apache-2.0"
] | 259 | 2015-01-05T08:30:59.000Z | 2022-03-21T06:39:52.000Z | Classes/Networking/RequestBody/TMJSONEncodedRequestBody.h | turlodales/TMTumblrSDK | af5fa629a088ead0064f28ec5d611a59c25ca353 | [
"Apache-2.0"
] | 74 | 2015-01-07T18:39:25.000Z | 2021-11-17T08:53:02.000Z | Classes/Networking/RequestBody/TMJSONEncodedRequestBody.h | turlodales/TMTumblrSDK | af5fa629a088ead0064f28ec5d611a59c25ca353 | [
"Apache-2.0"
] | 92 | 2015-02-01T07:44:29.000Z | 2021-12-09T05:56:02.000Z | //
// TMJSONEncodedRequestBody.h
// Pods
//
// Created by Kenny Ackerson on 4/25/16.
//
//
#import <Foundation/Foundation.h>
#import "TMRequestBody.h"
/**
* A request body that represents a JSON string.
*/
__attribute__((objc_subclassing_restricted))
@interface TMJSONEncodedRequestBody : NSObject <TMRequestBody>
/**
* Initialized instance of @c TMJSONEncodedRequestBody.
*
* @param JSONDictionary The JSON dictionary object that will be transformed into a request body.
*
* @return A newly initialized instance of @c TMJSONEncodedRequestBody.
*/
- (nonnull instancetype)initWithJSONDictionary:(nonnull NSDictionary *)JSONDictionary;
@end
| 23.5 | 98 | 0.753799 | [
"object"
] |
22080c06b63aa236edf50a29612c7fbfa2f2728a | 6,165 | c | C | physics.c | vcored/Gravity | 835b37f7d71f7652f321a15a822f0521f4eb0a9d | [
"MIT"
] | null | null | null | physics.c | vcored/Gravity | 835b37f7d71f7652f321a15a822f0521f4eb0a9d | [
"MIT"
] | null | null | null | physics.c | vcored/Gravity | 835b37f7d71f7652f321a15a822f0521f4eb0a9d | [
"MIT"
] | null | null | null | #include <math.h>
#include <stdbool.h>
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#include <pthread.h>
#include <sys/time.h>
#include "gravity.h"
#include "physics.h"
#define G 1e-4
int ms = 10;
int count = PARTICLES_MAX;
int next_m = 256;
double next_color[3] = { 0, 0, 0 };
/* flag is true when physics thread is busy making changes to the particles array */
bool running = false;
bool pause = false;
pthread_t thread_id;
pthread_mutex_t lock;
struct particle array[] =
{
{ .x = 320, .y = 240, .vx = 0, .vy = 0, .m = 65535, .color = { 1.0, 1.0, 0.0 }},
{ .x = 360, .y = 240, .vx = 0, .vy = 0.4, .m = 256, .color = { 1.0, 0.0, 0.0 }},
{ .x = 250, .y = 240, .vx = 0, .vy = 0.3, .m = 128, .color = { 0.0, 1.0, 0.5 }}, 0
};
double *new_color() {
next_color[0] = (rand() % 9 + 1) / 10.0;
next_color[1] = (rand() % 9 + 1) / 10.0;
next_color[2] = (rand() % 9 + 1) / 10.0;
return next_color;
}
void update() {
count = PARTICLES_MAX;
for (int i = 0; i < PARTICLES_MAX; i++) {
if (!array[i].m) count--;
}
}
bool check() {
update();
if (count+1 > PARTICLES_MAX) {
fputs("Out of memory\n", stderr);
running = false;
return false;
} else {
return true;
}
}
double timedifference_msec(struct timeval t0, struct timeval t1)
{
return (t1.tv_sec - t0.tv_sec) * 1000.0f + (t1.tv_usec - t0.tv_usec) / 1000.0f;
}
/* Returns radius of the object in pixels */
float particle_radius(struct particle *p) {
if (p->m < 2 && p->m > -2) return 1.0f;
return (float)(log(fabs(p->m)) / log(2) / 2);
}
/* Update velocities and positions of objects */
void physics_update() {
for (int i = 0; i < PARTICLES_MAX; i++) {
struct particle *p0 = &array[i];
if (!p0->m) continue;
for (int j = 0; j < PARTICLES_MAX; j++) {
struct particle *p = &array[j];
if (!p->m) continue;
if (i == j) continue;
double d = sqrt((p0->x-p->x) * (p0->x-p->x) + (p0->y-p->y) * (p0->y-p->y));
if (particle_radius(p0) + particle_radius(p) < d) {
/* Update velocity of the object p0 */
p0->vx += ((G * p->m) / (d * d)) * ((p->x - p0->x) / d);
p0->vy += ((G * p->m) / (d * d)) * ((p->y - p0->y) / d);
} else {
/* Collision, new object is created */
struct particle new;
new.x = (p0->m * p0->x + p->m * p->x) / (p0->m + p->m);
new.y = (p0->m * p0->y + p->m * p->y) / (p0->m + p->m);
new.vx = (p0->m * p0->vx + p->m * p->vx) / (p0->m + p->m);
new.vy = (p0->m * p0->vy + p->m * p->vy) / (p0->m + p->m);
new.m = (p0->m + p->m);
new.color[0] = (p0->m * p0->color[0] + p->m * p->color[0]) / (p0->m + p->m);
new.color[1] = (p0->m * p0->color[1] + p->m * p->color[1]) / (p0->m + p->m);
new.color[2] = (p0->m * p0->color[2] + p->m * p->color[2]) / (p0->m + p->m);
pthread_mutex_lock(&lock);
p0->m=0;
p->m=0;
if (check()) {
int i;
for (i = 0; array[i].m; i++); /* Get index of empty array element */
array[i] = new;
update();
}
pthread_mutex_unlock(&lock);
return;
}
}
/* Update x and y coordinates of the object p0 */
pthread_mutex_lock(&lock);
p0->x += p0->vx;
p0->y += p0->vy;
pthread_mutex_unlock(&lock);
}
}
void *physics_run() {
running = true;
struct timeval t0, t1;
gettimeofday(&t0, 0);
double delta = 0.0;
while (running) {
if (!pause) {
gettimeofday(&t1, 0);
delta += timedifference_msec(t0, t1) / ms;
t0 = t1;
if (delta >= 1.0) {
physics_update();
delta--;
}
} else gettimeofday(&t0, 0);
}
return NULL;
}
/* Those functions are called from main thread */
void physics_start() {
srand(time(NULL));
new_color();
update();
if (pthread_mutex_init(&lock, NULL) != 0) {
fprintf(stderr, "phtread_mutex_init failed\n");
return;
}
if (pthread_create(&thread_id, NULL, physics_run, NULL) != 0) {
fprintf(stderr, "phtread_create failed\n");
return;
}
while (!running);
}
void physics_stop() {
running = false;
pthread_join(thread_id, NULL);
pthread_mutex_destroy(&lock);
}
void particles_clear() {
pthread_mutex_lock(&lock);
for (int i = 0; i < PARTICLES_MAX; i++) {
array[i].m = 0;
}
pthread_mutex_unlock(&lock);
update();
}
void particle_add(double x, double y, double vx, double vy) {
pthread_mutex_lock(&lock);
if (check()) {
int i;
for (i = 0; array[i].m; i++); /* Get index of empty array element */
array[i] = (struct particle){ x, y, vx, vy, next_m, { next_color[0], next_color[1], next_color[2] } };
}
pthread_mutex_unlock(&lock);
update();
new_color();
}
void particle_remove(double x, double y) {
int closest = 0;
double d0 = +INFINITY;
pthread_mutex_lock(&lock);
for (int i = 0; i < PARTICLES_MAX; i++) {
struct particle *p0 = &array[i];
if (!p0->m) continue;
double px, py;
particle_getcoords(*p0, &px, &py);
double d = sqrt((px-x) * (px-x) + (py-y) * (py-y));
if (d<d0) {
d0 = d;
closest = i;
}
}
array[closest].m = 0;
pthread_mutex_unlock(&lock);
update();
}
double particle_getcoords(struct particle p, double *x, double *y) {
double alpha = 1.0;
if (p.x > WIDTH) {
*x = WIDTH;
alpha = 0.5;
} else if (p.x < 0) {
*x = 0;
alpha = 0.5;
} else *x = p.x;
if (p.y > HEIGHT) {
*y = HEIGHT;
alpha = 0.5;
} else if (p.y < 0) {
*y = 0;
alpha = 0.5;
} else *y = p.y;
return alpha;
}
| 25.37037 | 110 | 0.479157 | [
"object"
] |
220e1d0df9443f58d1643ce159c5b98fde0b01ed | 5,681 | h | C | src/include/storage/checkpoints/checkpoint.h | tpan496/project3 | 82714c4b36132d8c932de3d2819859e314ef1b7c | [
"MIT"
] | null | null | null | src/include/storage/checkpoints/checkpoint.h | tpan496/project3 | 82714c4b36132d8c932de3d2819859e314ef1b7c | [
"MIT"
] | null | null | null | src/include/storage/checkpoints/checkpoint.h | tpan496/project3 | 82714c4b36132d8c932de3d2819859e314ef1b7c | [
"MIT"
] | null | null | null | #pragma once
#include <catalog/catalog.h>
#include <common/managed_pointer.h>
#include <stdio.h>
#include <memory>
#include <mutex> // NOLINT
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#include "catalog/postgres/builder.h"
#include "catalog/postgres/pg_attribute.h"
#include "catalog/postgres/pg_constraint.h"
#include "catalog/postgres/pg_database.h"
#include "catalog/postgres/pg_index.h"
#include "common/worker_pool.h"
#include "storage/sql_table.h"
#include "transaction/transaction_manager.h"
namespace terrier::storage {
/**
* The Checkpoint class is responsible for taking checkpoints for a single database. The flow of checkpoint taking is
* as follows:
* 1. checkpoint class being constructed and called by a background thread
* 2. filter the log file to separate logs related to catalog tables
* 3. write data of user tables to disk using ArrowSerializer
*/
class Checkpoint {
public:
Checkpoint(const common::ManagedPointer<catalog::Catalog> catalog,
common::ManagedPointer<transaction::TransactionManager> txn_manager,
common::ManagedPointer<transaction::DeferredActionManager> deferred_action_manager,
common::ManagedPointer<storage::GarbageCollector> gc,
common::ManagedPointer<storage::LogManager> log_manager)
: catalog_(catalog),
txn_manager_(txn_manager),
deferred_action_manager_(deferred_action_manager),
gc_(gc),
log_manager_(log_manager) {
// Initialize catalog_table_schemas_ map
catalog_table_schemas_[catalog::postgres::CLASS_TABLE_OID] = catalog::postgres::Builder::GetClassTableSchema();
catalog_table_schemas_[catalog::postgres::NAMESPACE_TABLE_OID] =
catalog::postgres::Builder::GetNamespaceTableSchema();
catalog_table_schemas_[catalog::postgres::COLUMN_TABLE_OID] = catalog::postgres::Builder::GetColumnTableSchema();
catalog_table_schemas_[catalog::postgres::CONSTRAINT_TABLE_OID] =
catalog::postgres::Builder::GetConstraintTableSchema();
catalog_table_schemas_[catalog::postgres::INDEX_TABLE_OID] = catalog::postgres::Builder::GetIndexTableSchema();
catalog_table_schemas_[catalog::postgres::TYPE_TABLE_OID] = catalog::postgres::Builder::GetTypeTableSchema();
}
/**
* Take checkpoint of a database
* @param path the path on disk to save the checkpoint
* @param db the database to take the checkpoint of
* @param num_threads the number of threads used for thread_pool
* @param thread_pool_ the thread pool used for checkpoint taking
* @return True if succuessully take the checkpoint, False otherwise
*/
bool TakeCheckpoint(const std::string &path, catalog::db_oid_t db, const char *cur_log_file, uint32_t num_threads,
common::WorkerPool *thread_pool_);
/**
* Generate a file name for a table
* @tparam db_oid the oid of the database the table belongs to
* @param tb_oid the oid of the table
* @return a file name in the format db_oid-tb_oid.txt
*/
static std::string GenFileName(catalog::db_oid_t db_oid, catalog::table_oid_t tb_oid) {
return std::to_string((uint32_t)db_oid) + "-" + std::to_string((uint32_t)tb_oid);
}
/**
* Get the db_oid and tb_oit from the file name
* @param file_name the name of the checkpoint file
* @param db_oid the oid of the database the table belongs to
* @param tb_oid the oid of the table
* @return a file name in the format db_oid-tb_oid.txt
*/
static void GenOidFromFileName(const std::string &file_name, catalog::db_oid_t &db_oid,
catalog::table_oid_t &tb_oid) {
auto sep_ind = file_name.find("-");
db_oid = (catalog::db_oid_t)std::stoi(file_name.substr(0, sep_ind));
tb_oid = (catalog::table_oid_t)std::stoi(file_name.substr(sep_ind + 1, file_name.length()));
}
/**
* Splits a string into a vector
* @param s string to split
* @param delimiter that separates the string
* @return vector of strings
*/
static const std::vector<std::string> StringSplit(const std::string &s, const char &delimiter);
private:
// Catalog to fetch table pointers
friend class CheckpointBackgroundLoop;
const common::ManagedPointer<catalog::Catalog> catalog_;
common::ManagedPointer<transaction::TransactionManager> txn_manager_;
common::ManagedPointer<transaction::DeferredActionManager> deferred_action_manager_;
common::ManagedPointer<storage::GarbageCollector> gc_;
common::ManagedPointer<storage::LogManager> log_manager_;
std::unordered_map<catalog::table_oid_t, catalog::Schema> catalog_table_schemas_;
std::vector<std::pair<catalog::table_oid_t, storage::DataTable *>> queue; // for multithreading
std::mutex queue_latch;
/**
* Write the data of a database to disk in parallel (a user specified number of thread pulling table oid from a
* queue), called by TakeCheckpoint()
* @param path the path on disk to save the checkpoint
* @param accessor catalog accessor of the given database
* @param db_oid the database to be checkpointed
* @return None
*/
void WriteToDisk(const std::string &path, const std::unique_ptr<catalog::CatalogAccessor> &accessor,
catalog::db_oid_t db_oid);
/**
* Filter the logs in original log file to separate logs related to catalog tables to another file
* @param old_log_path the path of the original log file
* @param new_log_path the path of the new log file to save the logs related to catalog tables
* @return None
*/
void FilterCatalogLogs(const std::string &old_log_path, const std::string &new_log_path);
}; // class checkpoint
} // namespace terrier::storage
| 44.03876 | 117 | 0.73473 | [
"vector"
] |
2216d5833cd39136b5cf6f9573e0114c7e1a70b5 | 2,063 | h | C | Exercises/Motor2D/j1Render.h | jorgegh2/Split-screen | b7405a831301824785445b2d931e03bd21a91322 | [
"MIT"
] | 1 | 2019-06-06T20:34:56.000Z | 2019-06-06T20:34:56.000Z | Solution/Motor2D/j1Render.h | jorgegh2/Split-screen | b7405a831301824785445b2d931e03bd21a91322 | [
"MIT"
] | null | null | null | Solution/Motor2D/j1Render.h | jorgegh2/Split-screen | b7405a831301824785445b2d931e03bd21a91322 | [
"MIT"
] | 1 | 2020-04-22T06:20:39.000Z | 2020-04-22T06:20:39.000Z | #ifndef __j1RENDER_H__
#define __j1RENDER_H__
#include "SDL/include/SDL.h"
#include "Point.h"
#include "j1Module.h"
#include <vector>
enum class ORIENTATION
{
NO_TYPE = 0,
SQUARE_ORDER, //All cameras have the same width and height, even if it is not square order the maximum number of cameras.
HORIZONTAL, //The cameras aux will have more width than the rest to occupy the whole row.
VERTICAL, //The cameras aux will have more height than the rest to occupy the whole column.
};
class Camera;
class j1Render : public j1Module
{
public:
j1Render();
// Destructor
virtual ~j1Render();
// Called before render is available
bool Awake(pugi::xml_node&);
void CreateSplitScreen();
// Called before the first frame
bool Start();
// Called each loop iteration
bool PreUpdate();
bool PostUpdate();
// Called before quitting
bool CleanUp();
// Draw & Blit
void Blit(SDL_Texture* texture, int screen_x, int screen_y, Camera* camera, const SDL_Rect* section = NULL) const;
bool DrawLine(int x1, int y1, int x2, int y2, Uint8 r, Uint8 g, Uint8 b, Uint8 a = 255, bool use_camera = true) const;
bool IsOnCamera(const int & x, const int & y, const int & w, const int & h, Camera* camera) const;
// Set background color
void SetBackgroundColor(SDL_Color color);
public:
SDL_Renderer* renderer = nullptr;
std::vector<Camera*> cameras;
std::vector<Camera*> camera_saves;
SDL_Rect viewport;
SDL_Color background;
uint width_of_first_camera = 0;
uint height_of_first_camera = 0;
float margin = 0; //size of margin.
uint n_cameras_columns = 0; //number of columns.
uint n_cameras_rows = 0; //number of rows.
uint n_cameras_aux = 0; //number of cameras in the last row or column (regardless of the orientation, selected if its rows or columns in the orientation).
ORIENTATION orientation = ORIENTATION::NO_TYPE; //orientation of the cameras, look the declaration for more information.
bool debug = true;
};
#endif // __j1RENDER_H__ | 27.878378 | 166 | 0.700921 | [
"render",
"vector"
] |
222c128cb58fbd51d94a376bd0813ee770dfebfb | 8,846 | h | C | FMINestableTableView/FMINestableTableView.h | FlorianMielke/FMINestableTableView | d41c80d082668c915b9be6b8ae8bd9bfc122dca2 | [
"MIT"
] | 1 | 2017-07-21T11:44:17.000Z | 2017-07-21T11:44:17.000Z | FMINestableTableView/FMINestableTableView.h | FlorianMielke/FMINestableTableView | d41c80d082668c915b9be6b8ae8bd9bfc122dca2 | [
"MIT"
] | null | null | null | FMINestableTableView/FMINestableTableView.h | FlorianMielke/FMINestableTableView | d41c80d082668c915b9be6b8ae8bd9bfc122dca2 | [
"MIT"
] | null | null | null | //
// FMINestableTableView.h
// FMINestableTableView
//
// Created by Florian Mielke on 15.06.16.
// Copyright © 2016 Florian Mielke. All rights reserved.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@class FMINestableTableView;
/**
* The FMITableViewDataSourceNesting protocol is adopted by an object that mediates the application’s data model for a FMINestableTableView object.
* The data source provides the table-view object with the information it needs to construct and modify a table view.
*/
@protocol FMITableViewDataSourceNesting <NSObject>
/**
* Asks the data source to return the number of nested rows for a given index path.
* @param tableView The table-view object requesting this information.
* @param indexPath An index path locating a row in tableView.
* @return The number of nested rows for indexPath.
*/
- (NSInteger)nestableTableView:(FMINestableTableView *)tableView numberOfNestedRowsForRowAtIndexPath:(NSIndexPath *)indexPath;
/**
* Asks the data source to verify that the given row has nested rows.
* @param tableView The table-view object requesting this information.
* @param indexPath An index path locating a row in tableView.
* @return YES if the row indicated by indexPath has nested rows; otherwise, NO.
*/
- (BOOL)nestableTableView:(FMINestableTableView *)tableView hasNestedRowsForRowAtIndexPath:(NSIndexPath *)indexPath;
/**
* Asks the data source for a cell to insert in a particular location of the table view.
* @param tableView The table-view object requesting this information.
* @param indexPath An index path locating a row in tableView.
* @return An object inheriting from UITableViewCell that the table view can use for the specified row. An assertion is raised if you return nil.
*/
- (UITableViewCell *)nestableTableView:(FMINestableTableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
/**
* Asks the data source for a cell to insert in a nested location of the table view.
* @param tableView The table-view object requesting this information.
* @param index An index locating a nested row for the given rootRowIndexPath.
* @param rootIndexPath An index path locating a root row in tableView.
* @return An object inheriting from UITableViewCell that the table view can use for the specified row. An assertion is raised if you return nil.
*/
- (UITableViewCell *)nestableTableView:(FMINestableTableView *)tableView cellForNestedRowAtIndex:(NSUInteger)index rootRowIndexPath:(NSIndexPath *)rootIndexPath;
@optional
/**
* Asks the data source to verify that the given row is editable.
* @param tableView The table-view object requesting this information.
* @param indexPath An index path locating a row in tableView.
* @return YES if the row indicated by indexPath is editable; otherwise, NO.
*/
- (BOOL)nestableTableView:(FMINestableTableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath;
/**
* Asks the data source to verify that the given nested row is editable.
* @param tableView The table-view object requesting this information.
* @param index An index locating a nested row for the given rootRowIndexPath.
* @param rootIndexPath An index path locating a root row in tableView.
* @return
*/
- (BOOL)nestableTableView:(FMINestableTableView *)tableView canEditNestedRowAtIndex:(NSUInteger)index rootRowIndexPath:(NSIndexPath *)rootIndexPath;
/**
* Asks the data source to commit the insertion or deletion of a specified row in the receiver.
* @param tableView The table-view object requesting this information.
* @param editingStyle The cell editing style corresponding to a insertion or deletion requested for the row specified by indexPath.
* @param indexPath An index path locating the row in tableView.
*/
- (void)nestableTableView:(FMINestableTableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath;
/**
* Asks the data source to commit the insertion or deletion of a specified nested row in the receiver.
* @param tableView The table-view object requesting this information.
* @param editingStyle The cell editing style corresponding to a insertion or deletion requested for the nested row specified by indexPath.
* @param indexPath An index path locating the nested row in tableView.
* @param index An index locating a nested row for the given rootRowIndexPath.
* @param rootIndexPath An index path locating the root row in tableView.
*/
- (void)nestableTableView:(FMINestableTableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forNestedRowAtIndexPath:(NSIndexPath *)indexPath nestedItemIndex:(NSUInteger)index rootRowIndexPath:(NSIndexPath *)rootIndexPath;
@end
/**
* The delegate of a \c FMINestableTableView object must adopt the FMITableViewDelegateNesting protocol.
*/
@protocol FMITableViewDelegateNesting <NSObject>
/**
* Tells the delegate that the specified row is now selected.
* @param tableView The table-view object requesting this information.
* @param indexPath An index path locating the new selected row in tableView.
*/
- (void)nestableTableView:(FMINestableTableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;
/**
* Tells the delegate that the specified nested row is now selected.
* @param tableView The table-view object requesting this information.
* @param index An index locating the new selected nested row in tableView.
* @param rootIndexPath An index path that locates a root row in tableView.
*/
- (void)nestableTableView:(FMINestableTableView *)tableView didSelectNestedRowAtIndex:(NSUInteger)index rootRowIndexPath:(NSIndexPath *)rootIndexPath;
@end
/**
* An instance of FMINestableTableView enhances UITableView to handle nested rows.
*/
@interface FMINestableTableView : UITableView
/**
* The object that acts as the data source of the table view.
*/
@property (nullable, weak, NS_NONATOMIC_IOSONLY) IBOutlet id <FMITableViewDataSourceNesting> fmi_nestingDataSource;
/**
* The object that acts as the delegate of the table view.
*/
@property (nullable, weak, NS_NONATOMIC_IOSONLY) IBOutlet id <FMITableViewDelegateNesting> fmi_nestingDelegate;
/**
* A Boolean value that determines whether the table view can show nested rows.
*/
@property (NS_NONATOMIC_IOSONLY) IBInspectable BOOL fmi_allowsNestedRows;
/**
* A Boolean value that indicates whether the tabe view currently displays any nested row.
*/
@property (readonly, NS_NONATOMIC_IOSONLY) BOOL fmi_displaysNestedRows;
/**
* Returns the number of rows incl. any visible nested rows in a specified section.
* @param numberOfRows The number of rows when no nested rows where visible.
* @param section An index number that identifies a section of the table.
* @return The number of rows in the section.
*/
- (NSInteger)fmi_adjustedNumberOfRowsForNumberOfRows:(NSInteger)numberOfRows inSection:(NSInteger)section;
/**
* Passes to the data source to ask for a cell to insert in a particular location of the table view.
* @param indexPath An index path locating a row in tableView.
* @return An object inheriting from UITableViewCell that the table view can use for the specified row.
*/
- (UITableViewCell *)fmi_cellForRowAtIndexPath:(NSIndexPath *)indexPath;
/**
* Passes to the data source to verify that the given row is editable.
* @param indexPath An index path locating a row in tableView.
* @return YES if the row indicated by indexPath is editable; otherwise, NO.
*/
- (BOOL)fmi_canEditRowAtIndexPath:(NSIndexPath *)indexPath;
/**
* Passes to the delegate to tell that the specified row is now selected.
* @param indexPath
*/
- (void)fmi_didSelectRowAtIndexPath:(NSIndexPath *)indexPath;
/**
* Returns the adjusted index path of a given indexPath and considering any visible nested rows.
* @param indexPath An index path locating the row in tableView.
* @return An adjusted index path based on whether any nested rows are visible or not.
*/
- (NSIndexPath *)fmi_adjustedIndexPathForIndexPath:(NSIndexPath *)indexPath;
/**
* Asks the data source to verify that the given row is nested.
* @param indexPathn An index path locating a row in tableView.
* @return YES if the row indicated by indexPath is nested; otherwise, NO.
*/
- (BOOL)fmi_isNestedRowAtIndexPath:(NSIndexPath *)indexPath;
/**
* Passes to the data source to commit the insertion or deletion of a specified row in the receiver.
* @param editingStyle The cell editing style corresponding to a insertion or deletion requested for the row specified by indexPath.
* @param indexPath An index path locating the row in tableView.
*/
- (void)fmi_commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath;
/**
* Hides all visible nested rows if needed.
*/
- (void)fmi_hideNestedRows;
@end
NS_ASSUME_NONNULL_END
| 45.132653 | 250 | 0.783179 | [
"object",
"model"
] |
222f041fc1b6febdbc138429468a8bf30b79008c | 1,231 | h | C | Frameworks/XADMaster.framework/Versions/A/PrivateHeaders/XADArchiveParserDescriptions.h | ryochin/Simple-Comic | 86a2debab6d362117b8ac2603e31a015b7ddac2b | [
"MIT"
] | 727 | 2015-01-02T08:21:43.000Z | 2022-03-24T18:27:05.000Z | Frameworks/XADMaster.framework/Versions/A/PrivateHeaders/XADArchiveParserDescriptions.h | onurcanbektas/Simple-Comic | b3f8f0bffc172b193d1f4f220d4aa8752480e14e | [
"MIT"
] | 45 | 2015-01-18T08:38:54.000Z | 2021-11-01T21:49:55.000Z | Frameworks/XADMaster.framework/Versions/A/PrivateHeaders/XADArchiveParserDescriptions.h | onurcanbektas/Simple-Comic | b3f8f0bffc172b193d1f4f220d4aa8752480e14e | [
"MIT"
] | 187 | 2015-01-02T02:44:36.000Z | 2022-01-16T18:34:53.000Z | #import "XADArchiveParser.h"
@interface XADArchiveParser (Descriptions)
-(NSString *)descriptionOfValueInDictionary:(NSDictionary *)dict key:(NSString *)key;
-(NSString *)descriptionOfKey:(NSString *)key;
-(NSArray *)descriptiveOrderingOfKeysInDictionary:(NSDictionary *)dict;
@end
NSString *XADHumanReadableFileSize(uint64_t size);
NSString *XADShortHumanReadableFileSize(uint64_t size);
NSString *XADHumanReadableBoolean(uint64_t boolean);
NSString *XADHumanReadablePOSIXPermissions(uint64_t permissions);
NSString *XADHumanReadableAmigaProtectionBits(uint64_t protection);
NSString *XADHumanReadableDOSFileAttributes(uint64_t attributes);
NSString *XADHumanReadableWindowsFileAttributes(uint64_t attributes);
NSString *XADHumanReadableOSType(uint64_t ostype);
NSString *XADHumanReadableEntryWithDictionary(NSDictionary *dict,XADArchiveParser *parser);
NSString *XADHumanReadableObject(id object);
NSString *XADHumanReadableDate(NSDate *date);
NSString *XADHumanReadableData(NSData *data);
NSString *XADHumanReadableArray(NSArray *array);
NSString *XADHumanReadableDictionary(NSDictionary *dict);
NSString *XADHumanReadableList(NSArray *labels,NSArray *values);
NSString *XADIndentTextWithSpaces(NSString *text,int spaces);
| 43.964286 | 91 | 0.847279 | [
"object"
] |
223d6581cca0c00002783fff0a5895b4804614ce | 2,597 | h | C | documentation/Sounds.h | ToddButler93/tamods | d48509dda5e1f8020b86e26f8204da2242c62603 | [
"MIT"
] | 2 | 2021-09-16T15:32:20.000Z | 2022-03-19T06:49:03.000Z | documentation/Sounds.h | ToddButler93/tamods | d48509dda5e1f8020b86e26f8204da2242c62603 | [
"MIT"
] | null | null | null | documentation/Sounds.h | ToddButler93/tamods | d48509dda5e1f8020b86e26f8204da2242c62603 | [
"MIT"
] | 3 | 2021-09-16T15:33:00.000Z | 2022-03-19T10:20:21.000Z | /** @file */
/**
A permanently muted player, with individual options to mute different kind of messages
*/
struct MutedPlayer
{
/**
The username of the player
*/
string username;
/**
If the chat messages of the player should be muted
*/
bool muteText;
/**
If VGS of the player should be muted
*/
bool muteVGS;
/**
If PMs of the player should be muted
*/
bool muteDirectMessage;
};
/**
Create a MutedPlayer object muting everything for a given player
@param username The name of the player to mute
@return The created MutedPlayer object
*/
MutedPlayer mplayer(string username);
/**
Create a custom MutedPlayer object for a given player
@param username The name of the player to mute
@param vgs If the player's VGS should be muted
@param text If the player's text messages should be muted
@param pm If the player's private messages should be muted
@return The created MutedPlayer object
*/
MutedPlayer mplayer_custom(string username, bool vgs, bool text, bool pm);
/**
Mute a player using the given MutedPlayer object
@param muted_player The object to use to mute the player
*/
void mutePlayer(MutedPlayer muted_player);
/**
The mode to use for custom hitsounds
The custom sound has to be located in your config folder, in the "sounds" subfolder as "hit.wav"
0: no custom hitsounds, use default one
1: static custom hitsound, at 1.0 pitch
2: dynamic custom hitsounds, depending on the damage dealt. Higher damage results in lower pitch
3: reverse dynamic custom hitsounds, depending on the damage dealt. Higher damage results in lower pitch
*/
number hitSoundMode;
/**
If a custom sound should be used for air mails
The sound has to be in yout config folder, in the "sounds" subfolder as "airmail.wav"
*/
boolean customAirMailSound;
/**
If a custom sound should be used for blue plates
The sound has to be in yout config folder, in the "sounds" subfolder as "blueplate.wav"
*/
boolean customBluePlateSound;
/**
The minimal pitch used for the dynamic hitsounds
*/
number hitSoundPitchMin;
/**
The maximal pitch used for the dynamic hitsounds
*/
number hitSoundPitchMax;
/**
Reference damage, used for dynamic hitsounds pitch computation
The default value is at 600
*/
number hitSoundDamageRef;
/**
The volume used to play hitsounds, used by both vanilla and custom sounds
Set this value to 0 to disable hitsounds
*/
number volumeHitSound;
/**
The volume used to play headshots
*/
number volumeHeadShot;
/**
The volume used to play the blue plate sound
*/
number volumeBluePlate;
/**
The volume used to play the air mail sound
*/
number volumeAirMail;
| 21.823529 | 104 | 0.755487 | [
"object"
] |
2241e82206fc4a5d6daac0a398c06ed49ed08cf6 | 1,603 | h | C | util/StringUtil.h | kami-lang/madex-redex | 90ae1bc46c6e20a0aed2c128183b9f289cecee34 | [
"MIT"
] | null | null | null | util/StringUtil.h | kami-lang/madex-redex | 90ae1bc46c6e20a0aed2c128183b9f289cecee34 | [
"MIT"
] | null | null | null | util/StringUtil.h | kami-lang/madex-redex | 90ae1bc46c6e20a0aed2c128183b9f289cecee34 | [
"MIT"
] | null | null | null | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include <cstring>
#include <memory>
#include <string>
#include <unordered_set>
#include <vector>
inline std::string str_copy(std::string_view str) { return std::string(str); }
inline std::string operator+(const std::string_view s,
const std::string_view t) {
auto tmp = str_copy(s);
tmp.append(t);
return tmp;
}
inline std::string operator+(const char* s, const std::string_view t) {
std::string tmp(s);
tmp.append(t);
return tmp;
}
inline std::string operator+(const std::string_view s, const char* t) {
auto tmp = str_copy(s);
tmp.append(t);
return tmp;
}
inline std::string operator+(char s, const std::string_view t) {
std::string tmp(1, s);
tmp.append(t);
return tmp;
}
inline std::string operator+(const std::string_view s, char t) {
auto tmp = str_copy(s);
tmp.append(1, t);
return tmp;
}
class StringStorage {
private:
std::unordered_set<std::string_view> m_set;
std::vector<std::unique_ptr<char[]>> m_storage;
public:
std::string_view operator[](std::string_view str) {
auto it = m_set.find(str);
if (it == m_set.end()) {
auto data = std::make_unique<char[]>(str.size());
auto data_ptr = data.get();
memcpy(data_ptr, str.data(), str.size());
m_storage.push_back(std::move(data));
it = m_set.emplace(std::string_view(data_ptr, str.size())).first;
}
return *it;
}
};
| 23.925373 | 78 | 0.653774 | [
"vector"
] |
067603a9923930eb3624c12d4d2c4764084ab651 | 2,364 | h | C | graphics/cgal/Surface_mesher/doc/Surface_mesher/Concepts/SurfaceMeshFacetsCriteria_3.h | hlzz/dotfiles | 0591f71230c919c827ba569099eb3b75897e163e | [
"BSD-3-Clause"
] | 4 | 2016-03-30T14:31:52.000Z | 2019-02-02T05:01:32.000Z | graphics/cgal/Surface_mesher/doc/Surface_mesher/Concepts/SurfaceMeshFacetsCriteria_3.h | hlzz/dotfiles | 0591f71230c919c827ba569099eb3b75897e163e | [
"BSD-3-Clause"
] | null | null | null | graphics/cgal/Surface_mesher/doc/Surface_mesher/Concepts/SurfaceMeshFacetsCriteria_3.h | hlzz/dotfiles | 0591f71230c919c827ba569099eb3b75897e163e | [
"BSD-3-Clause"
] | null | null | null |
/*!
\ingroup PkgSurfaceMesher3Concepts
\cgalConcept
The Delaunay refinement process involved in the
function template `CGAL::make_surface_mesh()`
is guided by a set of refinement criteria.
The concept `SurfaceMeshFacetsCriteria_3` describes the type which
handles those criteria.
It corresponds to the requirements for the template parameter
`FacetsCriteria` of the surface mesher function
`CGAL::make_surface_mesh<SurfaceMeshC2T3,Surface,FacetsCriteria,Tag>()`.
Typically the meshing criteria are a set
of elementary criteria, each of which
has to be met by the facets of the final mesh.
The meshing algorithm eliminates in turn <I>bad</I> facets, i.e.,
facets that do not meet all the criteria.
The size and quality of the final mesh
depends on the order according to which bad facets
are handled. Therefore, the meshing algorithm
needs to be able to quantify the facet qualities and to compare
the qualities of different faces.
The type `SurfaceMeshFacetsCriteria_3::Quality` measures
the quality of a mesh facet.
Typically this quality
is a multicomponent variable. Each component corresponds to
one criterion and measures how much the facet deviates from
meeting this criterion. Then, the comparison operator on qualities
is just a lexicographical comparison. The meshing algorithm handles facets
with lowest quality first. The qualities are computed by a function
`is_bad(const Facet& f, const Quality& q)`.
\cgalHasModel `CGAL::Surface_mesh_default_criteria_3<Tr>`
\sa `CGAL::make_surface_mesh()`
*/
class SurfaceMeshFacetsCriteria_3 {
public:
/// \name Types
/// @{
/*!
The type of facets. This type has to match
the `Facet` type in the triangulation type used by
the mesher function. (This triangulation type
is the type `SurfaceMeshC2T3::Triangulation`
provided by the model of
`SurfaceMeshComplex_2InTriangulation_3` plugged
as first template parameter of
`CGAL::make_surface_mesh()`).
*/
typedef unspecified_type Facet;
/*!
Default constructible, copy constructible,
assignable, and less-than comparable type.
*/
typedef unspecified_type Quality;
/// @}
/// \name Operations
/// @{
/*!
Assigns the quality
of the facet `f` to `q`, and returns `true` is `f` does
not meet the criteria.
*/
bool is_bad (const Facet& f, const Quality& q);
/// @}
}; /* end SurfaceMeshFacetsCriteria_3 */
| 28.829268 | 75 | 0.766497 | [
"mesh",
"model"
] |
06793122c046b5cebacb6dfd60e5a28788307ce1 | 3,146 | c | C | nitan/kungfu/skill/ttjian.c | cantona/NT6 | 073f4d491b3cfe6bfbe02fbad12db8983c1b9201 | [
"MIT"
] | 1 | 2019-03-27T07:25:16.000Z | 2019-03-27T07:25:16.000Z | nitan/kungfu/skill/ttjian.c | cantona/NT6 | 073f4d491b3cfe6bfbe02fbad12db8983c1b9201 | [
"MIT"
] | null | null | null | nitan/kungfu/skill/ttjian.c | cantona/NT6 | 073f4d491b3cfe6bfbe02fbad12db8983c1b9201 | [
"MIT"
] | null | null | null | // yunlong-jian.c 雲龍劍
// Last Modified by sir 10.22.2001
#include <ansi.h>;
inherit SKILL;
string type() { return "martial"; }
string martialtype() { return "skill"; }
mapping *action = ({
([ "action":"\n$N使一式"GRN"「第一招」"NOR",手中$w嗡嗡微振,幻成一條白光刺向$n的$l",
"lvl" : 0,
"dodge" : -100000,
"parry" : -100000,
"force" : 1,
"damage" : 1,
"skill_name" : "悠悠順自然"
]),
([ "action" : "$N募的使一招"HIR"「第二招」"NOR",頓時劍光中幾朵血花灑向$n全身",
"dodge" : 100000,
"parry" : 100000,
"force" : 1,
"damage" : 1,
"lvl" : 0,
"skill_name" : "紅葉舞秋山"
]),
([ "action" : "$N募的使一招"HIR"「第三招」"NOR",頓時劍光中幾朵血花灑向$n全身",
"dodge" : -100000,
"parry" : 100000,
"force" : 1,
"damage" : 1,
"lvl" : 0,
"skill_name" : "紅葉舞秋山"
]),
([ "action" : "$N募的使一招"HIR"「第四招」"NOR",頓時劍光中幾朵血花灑向$n全身",
"dodge" : 100000,
"parry" : -100000,
"force" : 1,
"damage" : 1,
"lvl" : 0,
"skill_name" : "紅葉舞秋山"
]),
});
int valid_enable(string usage) { return usage == "sword" || usage == "parry"; }
int valid_learn(object me)
{
if( query("max_neili", me)<200 )
return notify_fail("你的內力不夠。\n");
if ((int)me->query_skill("yunlong-shengong", 1) < 20)
return notify_fail("你的雲龍神功火候太淺。\n");
if ((int)me->query_skill("yunlong-xinfa", 1) < 20)
return notify_fail("你的雲龍心法火候太淺。\n");
if ((int)me->query_skill("force", 1) < 40)
return notify_fail("你的基本內功火候太淺。\n");
return 1;
}
int practice_skill(object me)
{
object weapon;
if( !objectp(weapon=query_temp("weapon", me) )
|| query("skill_type", weapon) != "sword" )
return notify_fail("你使用的武器不對。\n");
if ((int)me->query_skill("yunlong-shengong", 1) < 20)
return notify_fail("你的雲龍神功火候太淺。\n");
if( query("qi", me)<55 || query("neili", me)<40 )
return notify_fail("你的內力或氣不夠練雲龍劍法。\n");
me->receive_damage("qi", 50);
addn("neili", -35, me);
return 1;
}
string query_skill_name(int level)
{
int i;
for(i = sizeof(action); i > 0; i--)
if(level >= action[i-1]["lvl"])
return action[i-1]["skill_name"];
}
mapping query_action(object me, object weapon)
{
return action[random(sizeof(action))];
}
int learn_bonus() { return 5; }
int practice_bonus() { return 5; }
int success() { return 5; }
int power_point() { return 1.0; }
string perform_action_file(string action)
{
return __DIR__"yunlong-jian/" + action;
}
int help(object me)
{
write(HIC"\n雲龍劍法:"NOR"\n");
write(@HELP
天地會看家本領,其特殊攻擊法威力奇大,堪稱武林一絕。
學習要求:
基本內功40級
雲龍神功20級
雲龍心法20級
內力200
HELP
);
return 1;
}
| 29.12963 | 79 | 0.475524 | [
"object"
] |
0679671fc44e43dfd37bfc8f48044a6610d1a24a | 8,583 | h | C | eurasia_km/services4/srvkm/hwdefs/sgxfeaturedefs.h | shaqfu786/GFX_Linux_DDK | f184ac914561fa100a5c92a488df777de8785f93 | [
"FSFAP"
] | 3 | 2020-03-13T23:37:00.000Z | 2021-09-03T06:34:04.000Z | eurasia_km/services4/srvkm/hwdefs/sgxfeaturedefs.h | zzpianoman/GFX_Linux_DDK | f184ac914561fa100a5c92a488df777de8785f93 | [
"FSFAP"
] | null | null | null | eurasia_km/services4/srvkm/hwdefs/sgxfeaturedefs.h | zzpianoman/GFX_Linux_DDK | f184ac914561fa100a5c92a488df777de8785f93 | [
"FSFAP"
] | 6 | 2015-02-05T03:01:01.000Z | 2021-07-24T01:07:18.000Z | /**********************************************************************
*
* Copyright (C) Imagination Technologies Ltd. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful but, except
* as otherwise stated in writing, 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 St - Fifth Floor, Boston, MA 02110-1301 USA.
*
* The full GNU General Public License is included in this distribution in
* the file called "COPYING".
*
* Contact Information:
* Imagination Technologies Ltd. <gpl-support@imgtec.com>
* Home Park Estate, Kings Langley, Herts, WD4 8LZ, UK
*
******************************************************************************/
#if defined(SGX520)
#define SGX_CORE_FRIENDLY_NAME "SGX520"
#define SGX_CORE_ID SGX_CORE_ID_520
#define SGX_FEATURE_ADDRESS_SPACE_SIZE (28)
#define SGX_FEATURE_NUM_USE_PIPES (1)
#define SGX_FEATURE_AUTOCLOCKGATING
#else
#if defined(SGX530)
#define SGX_CORE_FRIENDLY_NAME "SGX530"
#define SGX_CORE_ID SGX_CORE_ID_530
#define SGX_FEATURE_ADDRESS_SPACE_SIZE (28)
#define SGX_FEATURE_NUM_USE_PIPES (2)
#define SGX_FEATURE_AUTOCLOCKGATING
#else
#if defined(SGX531)
#define SGX_CORE_FRIENDLY_NAME "SGX531"
#define SGX_CORE_ID SGX_CORE_ID_531
#define SGX_FEATURE_ADDRESS_SPACE_SIZE (28)
#define SGX_FEATURE_NUM_USE_PIPES (2)
#define SGX_FEATURE_AUTOCLOCKGATING
#define SGX_FEATURE_MULTI_EVENT_KICK
#else
#if defined(SGX535)
#define SGX_CORE_FRIENDLY_NAME "SGX535"
#define SGX_CORE_ID SGX_CORE_ID_535
#define SGX_FEATURE_ADDRESS_SPACE_SIZE (32)
#define SGX_FEATURE_MULTIPLE_MEM_CONTEXTS
#define SGX_FEATURE_BIF_NUM_DIRLISTS (16)
#define SGX_FEATURE_2D_HARDWARE
#define SGX_FEATURE_NUM_USE_PIPES (2)
#define SGX_FEATURE_AUTOCLOCKGATING
#define SUPPORT_SGX_GENERAL_MAPPING_HEAP
#define SGX_FEATURE_EDM_VERTEX_PDSADDR_FULL_RANGE
#else
#if defined(SGX540)
#define SGX_CORE_FRIENDLY_NAME "SGX540"
#define SGX_CORE_ID SGX_CORE_ID_540
#define SGX_FEATURE_ADDRESS_SPACE_SIZE (28)
#define SGX_FEATURE_NUM_USE_PIPES (4)
#define SGX_FEATURE_AUTOCLOCKGATING
#define SGX_FEATURE_MULTI_EVENT_KICK
#else
#if defined(SGX543)
#define SGX_CORE_FRIENDLY_NAME "SGX543"
#define SGX_CORE_ID SGX_CORE_ID_543
#define SGX_FEATURE_USE_NO_INSTRUCTION_PAIRING
#define SGX_FEATURE_USE_UNLIMITED_PHASES
#define SGX_FEATURE_ADDRESS_SPACE_SIZE (32)
#define SGX_FEATURE_MULTIPLE_MEM_CONTEXTS
#define SGX_FEATURE_BIF_NUM_DIRLISTS (8)
#define SGX_FEATURE_NUM_USE_PIPES (4)
#define SGX_FEATURE_AUTOCLOCKGATING
#define SGX_FEATURE_MONOLITHIC_UKERNEL
#define SGX_FEATURE_MULTI_EVENT_KICK
#define SGX_FEATURE_DATA_BREAKPOINTS
#define SGX_FEATURE_PERPIPE_BKPT_REGS
#define SGX_FEATURE_PERPIPE_BKPT_REGS_NUMPIPES (2)
#define SGX_FEATURE_2D_HARDWARE
#define SGX_FEATURE_PTLA
#define SGX_FEATURE_EXTENDED_PERF_COUNTERS
#define SGX_FEATURE_EDM_VERTEX_PDSADDR_FULL_RANGE
#if defined(SUPPORT_SGX_LOW_LATENCY_SCHEDULING)
#if defined(SGX_FEATURE_MP)
#define SGX_FEATURE_MASTER_VDM_CONTEXT_SWITCH
#endif
#define SGX_FEATURE_SLAVE_VDM_CONTEXT_SWITCH
#define SGX_FEATURE_SW_ISP_CONTEXT_SWITCH
#endif
#else
#if defined(SGX544)
#define SGX_CORE_FRIENDLY_NAME "SGX544"
#define SGX_CORE_ID SGX_CORE_ID_544
#define SGX_FEATURE_USE_NO_INSTRUCTION_PAIRING
#define SGX_FEATURE_USE_UNLIMITED_PHASES
#define SGX_FEATURE_ADDRESS_SPACE_SIZE (32)
#define SGX_FEATURE_MULTIPLE_MEM_CONTEXTS
#define SGX_FEATURE_BIF_NUM_DIRLISTS (8)
#define SGX_FEATURE_NUM_USE_PIPES (4)
#define SGX_FEATURE_AUTOCLOCKGATING
#define SGX_FEATURE_MONOLITHIC_UKERNEL
#define SGX_FEATURE_MULTI_EVENT_KICK
#define SGX_FEATURE_EXTENDED_PERF_COUNTERS
#define SGX_FEATURE_EDM_VERTEX_PDSADDR_FULL_RANGE
#if defined(SUPPORT_SGX_LOW_LATENCY_SCHEDULING)
#if defined(SGX_FEATURE_MP)
#define SGX_FEATURE_MASTER_VDM_CONTEXT_SWITCH
#define SGX_FEATURE_SLAVE_VDM_CONTEXT_SWITCH
#endif
#define SGX_FEATURE_SW_ISP_CONTEXT_SWITCH
#endif
#else
#if defined(SGX545)
#define SGX_CORE_FRIENDLY_NAME "SGX545"
#define SGX_CORE_ID SGX_CORE_ID_545
#define SGX_FEATURE_ADDRESS_SPACE_SIZE (32)
#define SGX_FEATURE_AUTOCLOCKGATING
#define SGX_FEATURE_USE_NO_INSTRUCTION_PAIRING
#define SGX_FEATURE_USE_UNLIMITED_PHASES
#define SGX_FEATURE_VOLUME_TEXTURES
#define SGX_FEATURE_HOST_ALLOC_FROM_DPM
#define SGX_FEATURE_MULTIPLE_MEM_CONTEXTS
#define SGX_FEATURE_BIF_NUM_DIRLISTS (16)
#define SGX_FEATURE_NUM_USE_PIPES (4)
#define SGX_FEATURE_TEXTURESTRIDE_EXTENSION
#define SGX_FEATURE_PDS_DATA_INTERLEAVE_2DWORDS
#define SGX_FEATURE_MONOLITHIC_UKERNEL
#define SGX_FEATURE_ZLS_EXTERNALZ
#define SGX_FEATURE_NUM_PDS_PIPES (2)
#define SGX_FEATURE_NATIVE_BACKWARD_BLIT
#define SGX_FEATURE_MAX_TA_RENDER_TARGETS (512)
#define SGX_FEATURE_SECONDARY_REQUIRES_USE_KICK
#define SGX_FEATURE_WRITEBACK_DCU
#define SGX_FEATURE_BIF_WIDE_TILING_AND_4K_ADDRESS
#define SGX_FEATURE_MULTI_EVENT_KICK
#define SGX_FEATURE_EDM_VERTEX_PDSADDR_FULL_RANGE
#if defined(SUPPORT_SGX_LOW_LATENCY_SCHEDULING)
#define SGX_FEATURE_SW_ISP_CONTEXT_SWITCH
#endif
#else
#if defined(SGX554)
#define SGX_CORE_FRIENDLY_NAME "SGX554"
#define SGX_CORE_ID SGX_CORE_ID_554
#define SGX_FEATURE_USE_NO_INSTRUCTION_PAIRING
#define SGX_FEATURE_USE_UNLIMITED_PHASES
#define SGX_FEATURE_ADDRESS_SPACE_SIZE (32)
#define SGX_FEATURE_MULTIPLE_MEM_CONTEXTS
#define SGX_FEATURE_BIF_NUM_DIRLISTS (8)
#define SGX_FEATURE_NUM_USE_PIPES (8)
#define SGX_FEATURE_AUTOCLOCKGATING
#define SGX_FEATURE_MONOLITHIC_UKERNEL
#define SGX_FEATURE_MULTI_EVENT_KICK
#define SGX_FEATURE_2D_HARDWARE
#define SGX_FEATURE_PTLA
#define SGX_FEATURE_EXTENDED_PERF_COUNTERS
#define SGX_FEATURE_EDM_VERTEX_PDSADDR_FULL_RANGE
#if defined(SUPPORT_SGX_LOW_LATENCY_SCHEDULING)
#if defined(SGX_FEATURE_MP)
#define SGX_FEATURE_MASTER_VDM_CONTEXT_SWITCH
#endif
#define SGX_FEATURE_SLAVE_VDM_CONTEXT_SWITCH
#define SGX_FEATURE_SW_ISP_CONTEXT_SWITCH
#endif
#endif
#endif
#endif
#endif
#endif
#endif
#endif
#endif
#endif
#if defined(SGX_FEATURE_SLAVE_VDM_CONTEXT_SWITCH) \
|| defined(SGX_FEATURE_MASTER_VDM_CONTEXT_SWITCH)
#define SGX_FEATURE_VDM_CONTEXT_SWITCH
#endif
#if defined(FIX_HW_BRN_22693)
#undef SGX_FEATURE_AUTOCLOCKGATING
#endif
#if defined(FIX_HW_BRN_27266)
#undef SGX_FEATURE_36BIT_MMU
#endif
#if defined(FIX_HW_BRN_27456)
#undef SGX_FEATURE_BIF_WIDE_TILING_AND_4K_ADDRESS
#endif
#if defined(FIX_HW_BRN_22934) \
|| defined(FIX_HW_BRN_25499)
#undef SGX_FEATURE_MULTI_EVENT_KICK
#endif
#if defined(SGX_FEATURE_SYSTEM_CACHE)
#if defined(SGX_FEATURE_36BIT_MMU)
#error SGX_FEATURE_SYSTEM_CACHE is incompatible with SGX_FEATURE_36BIT_MMU
#endif
#if defined(FIX_HW_BRN_26620) && !defined(SGX_FEATURE_MULTI_EVENT_KICK)
#define SGX_BYPASS_SYSTEM_CACHE
#endif
#endif
#if defined(FIX_HW_BRN_29954)
#undef SGX_FEATURE_PERPIPE_BKPT_REGS
#endif
#if defined(FIX_HW_BRN_31620)
#undef SGX_FEATURE_MULTIPLE_MEM_CONTEXTS
#undef SGX_FEATURE_BIF_NUM_DIRLISTS
#endif
#if defined(SGX_FEATURE_MP)
#if defined(SGX_FEATURE_MP_CORE_COUNT_TA) && defined(SGX_FEATURE_MP_CORE_COUNT_3D)
#if (SGX_FEATURE_MP_CORE_COUNT_TA > SGX_FEATURE_MP_CORE_COUNT_3D)
#error Number of TA cores larger than number of 3D cores not supported in current driver
#endif
#else
#if defined(SGX_FEATURE_MP_CORE_COUNT)
#define SGX_FEATURE_MP_CORE_COUNT_TA (SGX_FEATURE_MP_CORE_COUNT)
#define SGX_FEATURE_MP_CORE_COUNT_3D (SGX_FEATURE_MP_CORE_COUNT)
#else
#error Either SGX_FEATURE_MP_CORE_COUNT or \
both SGX_FEATURE_MP_CORE_COUNT_TA and SGX_FEATURE_MP_CORE_COUNT_3D \
must be defined when SGX_FEATURE_MP is defined
#endif
#endif
#else
#define SGX_FEATURE_MP_CORE_COUNT (1)
#define SGX_FEATURE_MP_CORE_COUNT_TA (1)
#define SGX_FEATURE_MP_CORE_COUNT_3D (1)
#endif
#if defined(SUPPORT_SGX_LOW_LATENCY_SCHEDULING) && !defined(SUPPORT_SGX_PRIORITY_SCHEDULING)
#define SUPPORT_SGX_PRIORITY_SCHEDULING
#endif
#include "img_types.h"
| 34.608871 | 92 | 0.803915 | [
"3d"
] |
068053f898fc56ffe3cc0b41e45c821699073018 | 1,330 | h | C | minix/servers/vfs/vnode.h | calmsacibis995/minix | dfba95598f553b6560131d35a76658f1f8c9cf38 | [
"Unlicense"
] | 3 | 2021-10-07T18:19:37.000Z | 2021-10-07T19:02:14.000Z | minix/servers/vfs/vnode.h | calmsacibis995/minix | dfba95598f553b6560131d35a76658f1f8c9cf38 | [
"Unlicense"
] | null | null | null | minix/servers/vfs/vnode.h | calmsacibis995/minix | dfba95598f553b6560131d35a76658f1f8c9cf38 | [
"Unlicense"
] | 3 | 2021-12-02T11:09:09.000Z | 2022-01-25T21:31:23.000Z | #ifndef __VFS_VNODE_H__
#define __VFS_VNODE_H__
EXTERN struct vnode {
endpoint_t v_fs_e; /* FS process' endpoint number */
endpoint_t v_mapfs_e; /* mapped FS process' endpoint number */
ino_t v_inode_nr; /* inode number on its (minor) device */
ino_t v_mapinode_nr; /* mapped inode number of mapped FS. */
mode_t v_mode; /* file type, protection, etc. */
uid_t v_uid; /* uid of inode. */
gid_t v_gid; /* gid of inode. */
off_t v_size; /* current file size in bytes */
int v_ref_count; /* # times vnode used; 0 means slot is free */
int v_fs_count; /* # reference at the underlying FS */
int v_mapfs_count; /* # reference at the underlying mapped FS */
endpoint_t v_bfs_e; /* endpoint number for the FS proces in case
of a block special file */
dev_t v_dev; /* device number on which the corresponding
inode resides */
dev_t v_sdev; /* device number for special files */
struct vmnt *v_vmnt; /* vmnt object of the partition */
tll_t v_lock; /* three-level-lock */
} vnode[NR_VNODES];
/* vnode lock types mapping */
#define VNODE_NONE TLL_NONE /* used only for get_filp2 to avoid locking */
#define VNODE_READ TLL_READ
#define VNODE_OPCL TLL_READSER
#define VNODE_WRITE TLL_WRITE
#endif
| 42.903226 | 75 | 0.657895 | [
"object"
] |
0681905ac8984afc45cbe0ab51fba411cee50fe4 | 670 | h | C | samples/learn/HeroData.h | swarmfarm/cppgraphqlgen | 87c334da120ac81c66ae80a0dd599b8711a32b90 | [
"MIT"
] | 52 | 2018-08-12T15:36:12.000Z | 2019-05-04T09:22:34.000Z | samples/learn/HeroData.h | swarmfarm/cppgraphqlgen | 87c334da120ac81c66ae80a0dd599b8711a32b90 | [
"MIT"
] | 30 | 2018-09-10T18:05:16.000Z | 2019-05-02T00:43:01.000Z | samples/learn/HeroData.h | swarmfarm/cppgraphqlgen | 87c334da120ac81c66ae80a0dd599b8711a32b90 | [
"MIT"
] | 13 | 2018-08-20T03:40:22.000Z | 2019-04-19T08:15:46.000Z | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#pragma once
#ifndef HERODATA_H
#define HERODATA_H
#include <memory>
#include <variant>
namespace graphql::learn {
class Droid;
class Human;
using SharedHero = std::variant<std::shared_ptr<Human>, std::shared_ptr<Droid>>;
using WeakHero = std::variant<std::weak_ptr<Human>, std::weak_ptr<Droid>>;
namespace object {
class Character;
} // namespace object
std::shared_ptr<object::Character> make_hero(const SharedHero& hero) noexcept;
std::shared_ptr<object::Character> make_hero(const WeakHero& hero) noexcept;
} // namespace graphql::learn
#endif // HERODATA_H
| 20.9375 | 80 | 0.753731 | [
"object"
] |
0688322860450fdb62a5d2a233fddde7bba199c6 | 14,571 | c | C | dehydration_emb_sys/dehydration/Node_server/src/main_server.c | pseudoincorrect/Dehydration | c6b966b71d124f54ac644a47bcde78ef61151750 | [
"MIT"
] | null | null | null | dehydration_emb_sys/dehydration/Node_server/src/main_server.c | pseudoincorrect/Dehydration | c6b966b71d124f54ac644a47bcde78ef61151750 | [
"MIT"
] | null | null | null | dehydration_emb_sys/dehydration/Node_server/src/main_server.c | pseudoincorrect/Dehydration | c6b966b71d124f54ac644a47bcde78ef61151750 | [
"MIT"
] | null | null | null | /*888888888 .d88888b. 8888888b. .d88888b.
888 d88P" "Y88b 888 "Y88b d88P" "Y88b
888 888 888 888 888 888 888
888 888 888 888 888 888 888 d8b
888 888 888 888 888 888 888 Y8P
888 888 888 888 888 888 888
888 Y88b. .d88P 888 .d88P Y88b. .d88P d8b
888 "Y88888P" 8888888P" "Y88888P" Y*/
// on all address
// set advertising time
// notif all
//
// on this address
// status led to confirm addr/name
// send a quick update of the ADCs
#include "main_server.h"
//***************************************************************************
// Static data
//***************************************************************************
volatile uint8_t state = 1;
static dehydration_server_t m_server;
// sensors states
static int8_t state_dehydration;
static int8_t state_ambient_humidity;
static int8_t state_ambient_temperature;
static int8_t state_skin_temperature;
static int8_t state_heart_rate;
//
static int state_msg;
static advertiser_t m_advertiser;
static uint8_t m_adv_buffer[ADVERTISER_BUFFER_SIZE];
static ble_gap_addr_t node_addr_p;
static int FLAG_sending_notif;
static dht22_data data_dht;
/*8b d888 d8888 8888888 888b 888
8888b d8888 d88888 888 8888b 888
88888b.d88888 d88P888 888 88888b 888
888Y88888P888 d88P 888 888 888Y88b 888
888 Y888P 888 d88P 888 888 888 Y88b888
888 Y8P 888 d88P 888 888 888 Y88888
888 " 888 d8888888888 888 888 Y8888
888 888 d88P 888 8888888 888 Y8*/
int main(void)
{
temperature_buffer temp_buffer;
temp_buffer.index_buffer = 0;
state_msg = 0;
FLAG_sending_notif = 0;
nodeHal_init(OUTS_MASK, OUTPUT_DIR);
nodeHal_write(LED_DEBUG, LED_OFF);
nodeHal_init(PIN_TEMP_VDD_MASK, OUTPUT_DIR);
nodeHal_write(PIN_TEMP_VDD, STD_ON);
// SENSOR
nodeHal_init( PIN_DHT_VDD_MASK , OUTPUT_DIR);
nodeHal_write(PIN_DHT_VDD, STD_ON);
DHT22_Init();
nodeHal_buttons_init(button_event_handler);
__LOG_INIT(LOG_SRC_APP, LOG_LEVEL_INFO, log_callback_rtt);
__LOG(LOG_SRC_APP, LOG_LEVEL_INFO, "----- Bluetooth Mesh Beacon -----\n");
static const uint8_t static_auth_data[NRF_MESH_KEY_SIZE] = STATIC_AUTH_DATA;
static nrf_mesh_node_config_params_t config_params = {
.prov_caps = NRF_MESH_PROV_OOB_CAPS_DEFAULT(ACCESS_ELEMENT_COUNT)};
config_params.p_static_data = static_auth_data;
config_params.complete_callback = provisioning_complete;
config_params.setup_callback = configuration_setup;
config_params.irq_priority = NRF_MESH_IRQ_PRIORITY_LOWEST;
config_params.lf_clk_cfg.source = NRF_CLOCK_LF_SRC_SYNTH;
config_params.lf_clk_cfg.xtal_accuracy = NRF_CLOCK_LF_XTAL_ACCURACY_250_PPM;
// config_params.lf_clk_cfg.source = NRF_CLOCK_LF_SRC_XTAL;
// config_params.lf_clk_cfg.xtal_accuracy = NRF_CLOCK_LF_XTAL_ACCURACY_20_PPM;
ERROR_CHECK(nrf_mesh_node_config(&config_params));
// Start listening for incoming packets
nrf_mesh_rx_cb_set(rx_callback);
// Start Advertising own beacon
init_advertiser();
// set the addr variable used to know if a message if for us
set_addr();
uint8_t* msg_str = "Here we are!";
// advertiser_enable(&m_advertiser);
start_advertiser(msg_str);
__LOG(LOG_SRC_APP, LOG_LEVEL_INFO, "Initialization complete!\n");
// nodeHal_saadc_init(saadc_callback);
nodeHal_saadc_init_simple();
while (true) {
(void)sd_app_evt_wait();
get_ambient_temp_humid();
get_temperature_mean(&temp_buffer);
get_heart_rate();
SEGGER_PRINTF("Ambient Temp = %d \n\r", state_ambient_temperature);
SEGGER_PRINTF("Ambient Humid = %d \n\r", state_ambient_humidity);
SEGGER_PRINTF("Skin Temp = %d \n\r", state_skin_temperature);
SEGGER_PRINTF("Heart Rate = %d \n\n\r", state_heart_rate);
if (!FLAG_sending_notif) {
change_ADC_data_advertiser();
}
nrf_delay_ms(1000);
}
}
/*8b d888 8888888888 .d8888b. 888 888 8888888b. Y88b d88P
8888b d8888 888 d88P Y88b 888 888 888 Y88b Y88b d88P
88888b.d88888 888 Y88b. 888 888 888 888 Y88o88P
888Y88888P888 8888888 "Y888b. 8888888888 888 d88P Y888P
888 Y888P 888 888 "Y88b. 888 888 8888888P" d888b
888 Y8P 888 888 "888 888 888 888 T88b d88888b
888 " 888 888 Y88b d88P 888 888 888 T88b d88P Y88b
888 888 8888888888 "Y8888P" 888 888 888 T88b d88P Y8*/
static void rx_callback(const nrf_mesh_adv_packet_rx_data_t* p_rx_data) {
int i = 0;
static int j = 0;
char msg_addr[128];
char msg[128];
memset(msg_addr, 0, sizeof(msg_addr));
(void)sprintf(msg_addr,
"[%02x:%02x:%02x:%02x:%02x:%02x]",
p_rx_data->p_metadata->params.scanner.adv_addr.addr[0],
p_rx_data->p_metadata->params.scanner.adv_addr.addr[1],
p_rx_data->p_metadata->params.scanner.adv_addr.addr[2],
p_rx_data->p_metadata->params.scanner.adv_addr.addr[3],
p_rx_data->p_metadata->params.scanner.adv_addr.addr[4],
p_rx_data->p_metadata->params.scanner.adv_addr.addr[5]);
memset(msg, 0, sizeof(msg));
memcpy(msg, (uint8_t*)p_rx_data->p_payload, (uint8_t)p_rx_data->length);
process_msg(&msg[2], p_rx_data->length - 1);
}
static void process_msg(uint8_t* msg_ptr, int msg_len) {
char cmd_single;
if (msg_ptr[0] == TO_ALL) {
if (msg_ptr[1] == NOTIF_ALL) {
SEGGER_PRINTF("%s", "process_notif_all()\n\r");
process_notif_all();
}
} else if (msg_ptr[0] == TO_SINGLE) {
if (compare_addr(&msg_ptr[1], BLE_GAP_ADDR_LEN)) {
cmd_single = msg_ptr[CMD_CHAR_POS];
if (cmd_single == NOTIF) {
SEGGER_PRINTF("%s", "process_notif()\n\r");
process_notif();
} else if (cmd_single == DRINK_NOTIF) {
SEGGER_PRINTF("%s", "process_notif_drink()\n\r");
process_notif_drink();
} else {
SEGGER_PRINTF("Unknown command %c\n\r", msg_ptr[BLE_GAP_ADDR_LEN + 1]);
}
}
// else not my address
}
}
static void print_my_addr(uint8_t* msg_ptr) {
int i;
SEGGER_PRINTF("received addr : %02x%02x%02x%02x%02x%02x\n\r",
*(msg_ptr + 1),
*(msg_ptr + 2),
*(msg_ptr + 3),
*(msg_ptr + 4),
*(msg_ptr + 5),
*(msg_ptr + 6));
SEGGER_PRINTF("My addr : %s", "");
for (i = 0; i < BLE_GAP_ADDR_LEN; i++) {
SEGGER_PRINTF("%02x", node_addr_p.addr[i]);
}
SEGGER_PRINTF("\n\r%s", "");
}
static int compare_addr(uint8_t* addr_ptr, int addr_len) {
int i;
for (i = 0; i < BLE_GAP_ADDR_LEN; i++) {
if (addr_ptr[i] != (node_addr_p.addr)[i]) {
return 0;
}
}
return 1;
}
static void set_addr(void) {
advertiser_address_default_get(&node_addr_p);
}
/*8888b. 8888888888 88888888888 d8888 8888888b. 888 888
d88P Y88b 888 888 d88888 888 "Y88b 888 888
Y88b. 888 888 d88P888 888 888 888 888
"Y888b. 8888888 888 d88P 888 888 888 Y88b d88P
"Y88b. 888 888 d88P 888 888 888 Y88b d88P
"888 888 888 d88P 888 888 888 Y88o88P
Y88b d88P 888 888 d8888888888 888 .d88P Y888P
"Y8888P" 8888888888 888 d88P 888 8888888P" Y*/
static void mesh_send_notif(void) {
static char adv_msg_notif[2];
FLAG_sending_notif = 1;
advertiser_interval_set(&m_advertiser, ADVERTISER_PERIOD_FAST);
adv_msg_notif[0] = NOTIF_CMD;
adv_msg_notif[1] = 1; // to be implemented
set_advertiser(adv_msg_notif, sizeof(adv_msg_notif), ADVERTISER_REPEAT_ONCE);
FLAG_sending_notif = 0;
}
static void change_ADC_data_advertiser(void) {
int t_h_diff;
static char adv_msg_update[7];
adv_msg_update[0] = UPDATE_CMD;
adv_msg_update[1] = (int8_t)(state_dehydration);
adv_msg_update[2] = (int8_t)(state_ambient_humidity);
adv_msg_update[3] = (int8_t)(state_ambient_temperature);
adv_msg_update[4] = (int8_t)(state_skin_temperature);
adv_msg_update[5] = (int8_t)(state_heart_rate);
adv_msg_update[6] = 0;
advertiser_interval_set(&m_advertiser, ADVERTISER_PERIOD_FAST);
set_advertiser(adv_msg_update, sizeof(adv_msg_update), ADVERTISER_REPEAT_ONCE);
}
static void set_advertiser(char* msg_str, int len_msg, int repeat) {
static uint8_t adv_data[128];
memset(adv_data, 0, sizeof(adv_data));
adv_data[0] = len_msg + 1;
adv_data[1] = 0x2A;
memcpy(&adv_data[2], msg_str, len_msg);
/* Allocate packet */
adv_packet_t* p_packet = advertiser_packet_alloc(&m_advertiser, len_msg + 2);
if (p_packet) {
/* Construct packet contents */
memcpy(p_packet->packet.payload, adv_data, len_msg + 2);
/* Repeat forever */
p_packet->config.repeats = repeat;
advertiser_packet_send(&m_advertiser, p_packet);
}
}
static void init_advertiser(void) {
advertiser_instance_dehydration_init(
&m_advertiser, NULL, m_adv_buffer, ADVERTISER_BUFFER_SIZE, ADVERTISER_PERIOD_SLOW);
}
static void start_advertiser(uint8_t* msg_str) {
advertiser_enable(&m_advertiser);
static uint8_t adv_data[128];
memset(adv_data, 0, sizeof(adv_data));
adv_data[0] = ((uint8_t)strlen(msg_str) + 1);
adv_data[1] = 0x2A;
strncpy(&adv_data[2], msg_str, strlen(msg_str));
/* Allocate packet */
adv_packet_t* p_packet = advertiser_packet_alloc(&m_advertiser, strlen(msg_str) + 2);
if (p_packet) {
/* Construct packet contents */
memcpy(p_packet->packet.payload, adv_data, strlen(msg_str) + 2);
/* Repeat forever */
p_packet->config.repeats = ADVERTISER_REPEAT_INFINITE;
advertiser_packet_send(&m_advertiser, p_packet);
}
}
static void configuration_setup(void* p_unused) {
__LOG(LOG_SRC_APP, LOG_LEVEL_INFO, "Initializing and adding models\n");
// Add model initialization here, if you wish to support
// a mesh model on this node.
nodeHal_blink(LED_STATUS, 200, 4);
}
static void provisioning_complete(void* p_unused) {
__LOG(LOG_SRC_APP, LOG_LEVEL_INFO, "Successfully provisioned\n");
nodeHal_blink(LED_STATUS, 200, 4);
}
/*8888b. d8888 d8888 8888888b. .d8888b.
d88P Y88b d88888 d88888 888 "Y88b d88P Y88b
Y88b. d88P888 d88P888 888 888 888 888
"Y888b. d88P 888 d88P 888 888 888 888
"Y88b. d88P 888 d88P 888 888 888 888
"888 d88P 888 d88P 888 888 888 888 888
Y88b d88P d8888888888 d8888888888 888 .d88P Y88b d88P
"Y8888P" d88P 888 d88P 888 8888888P" "Y8888*/
// void saadc_callback(nrf_drv_saadc_evt_t const* p_event) {
// if (p_event->type == NRF_DRV_SAADC_EVT_DONE) {
// ret_code_t err_code;
// err_code = nrf_drv_saadc_buffer_convert(p_event->data.done.p_buffer, SAMPLES_IN_BUFFER);
// ERROR_CHECK(err_code);
// SEGGER_PRINTF("SAADC = %d \n\r", p_event->data.done.p_buffer[0]);
// }
// if (!FLAG_sending_notif) {
// change_ADC_data_advertiser();
// }
// }
void get_temperature_mean(temperature_buffer* temp_buff)
{
char temp_str[32];
int16_t temp_result = 0;
int16_t temp_mean_result = 0;
int index = 0;
int i = 0;
float temperature_f;
int temperature_i;
index = temp_buff->index_buffer;
nodeHal_saadc_sample_simple(NRF_SAADC_INPUT_AIN4, (int16_t *) &temp_result);
// nodeHal_saadc_sample_simple(SAADC_CH_PSELP_PSELP_VDD, (int16_t *) &temp_result);
temp_buff->buffer[index] = temp_result;
index = (index >= TEMP_BUFFER_SIZE) ? 0 : index + 1;
temp_buff->index_buffer = index;
for (i=0; i < TEMP_BUFFER_SIZE; i++){
temp_mean_result += temp_buff->buffer[i];
}
temp_mean_result = temp_mean_result / TEMP_BUFFER_SIZE;
temperature_f = (((float) temp_mean_result /4563) - 0.500)*100;
temperature_i = (int) temperature_f;
state_skin_temperature = 0x00FF & temperature_i;
// sprintf(temp_str, "%f", temperature_f);
// SEGGER_PRINTF("temperature_f = %s \n\r", temp_str);
// SEGGER_PRINTF("temperature_i = %d \n\r", temperature_i);
}
void get_heart_rate(void)
{
int16_t heart_buff;
nodeHal_saadc_sample_simple(NRF_SAADC_INPUT_AIN5, (int16_t *) &heart_buff);
state_heart_rate = 0x00FF & (heart_buff / 120);
}
void get_ambient_temp_humid(void)
{
char humidity[32];
char temperature[32];
bool err_dht;
ret_code_t err_code;
err_dht = DHT22_Read (&data_dht);
if (!err_dht) {
SEGGER_PRINTF("DHT status = %d \n\r", err_dht);
}
else {
sprintf(temperature, "%f", data_dht.temperature);
sprintf(humidity, "%f", data_dht.humidity);
state_dehydration = 0;
state_ambient_humidity = 0x000000FF & (int) data_dht.humidity;
state_ambient_temperature = 0x000000FF & (int) data_dht.temperature;
}
}
/*8888b. 888 888 d8888 888b 888 8888888b.
888 "88b 888 888 d88888 8888b 888 888 "Y88b
888 .88P 888 888 d88P888 88888b 888 888 888
8888888K. 8888888888 d88P 888 888Y88b 888 888 888
888 "Y88b 888 888 d88P 888 888 Y88b888 888 888
888 888 888 888 d88P 888 888 Y88888 888 888
888 d88P 888 888 d8888888888 888 Y8888 888 .d88P
8888888P" 88888888 888 888 d88P 888 888 Y888 8888888*/
static void button_event_handler(void) {
uint32_t nrf_status = NRF_SUCCESS;
SEGGER_PRINTF("Button pressed %s\r\n", "");
mesh_send_notif();
nodeHal_blink(LED_STATUS, 50, 5);
nodeHal_notif(MOT_NOTIF, 600, 1);
}
static void process_notif_all(void) {
nodeHal_blink(LED_STATUS, 100, 5);
nodeHal_notif(MOT_NOTIF, 600, 3);
}
static void process_notif(void) {
nodeHal_blink(LED_STATUS, 100, 5);
nodeHal_notif(MOT_NOTIF, 100, 10);
}
static void process_notif_drink(void) {
nodeHal_blink(LED_STATUS, 100, 5);
nodeHal_notif(MOT_NOTIF, 300, 4);
}
| 33.65127 | 96 | 0.635372 | [
"mesh",
"model"
] |
068bac5136071ae47940ae2f6f555e5a1ba3b373 | 5,887 | h | C | Plugins/org.mitk.lancet.robot/src/api/vega/capisample/CAPIcommon/src/include/TcpConnection.h | zhaomengxiao/MITK | a09fd849a4328276806008bfa92487f83a9e2437 | [
"BSD-3-Clause"
] | null | null | null | Plugins/org.mitk.lancet.robot/src/api/vega/capisample/CAPIcommon/src/include/TcpConnection.h | zhaomengxiao/MITK | a09fd849a4328276806008bfa92487f83a9e2437 | [
"BSD-3-Clause"
] | 1 | 2021-12-22T10:19:02.000Z | 2021-12-22T10:19:02.000Z | Plugins/org.mitk.lancet.robot/src/api/vega/capisample/CAPIcommon/src/include/TcpConnection.h | zhaomengxiao/MITK_lancet | a09fd849a4328276806008bfa92487f83a9e2437 | [
"BSD-3-Clause"
] | null | null | null | //----------------------------------------------------------------------------
//
// Copyright (C) 2017, Northern Digital Inc. All rights reserved.
//
// All Northern Digital Inc. ("NDI") Media and/or Sample Code and/or Sample Code
// Documentation (collectively referred to as "Sample Code") is licensed and provided "as
// is" without warranty of any kind. The licensee, by use of the Sample Code, warrants to
// NDI that the Sample Code is fit for the use and purpose for which the licensee intends to
// use the Sample Code. NDI makes no warranties, express or implied, that the functions
// contained in the Sample Code will meet the licensee's requirements or that the operation
// of the programs contained therein will be error free. This warranty as expressed herein is
// exclusive and NDI expressly disclaims any and all express and/or implied, in fact or in
// law, warranties, representations, and conditions of every kind pertaining in any way to
// the Sample Code licensed and provided by NDI hereunder, including without limitation,
// each warranty and/or condition of quality, merchantability, description, operation,
// adequacy, suitability, fitness for particular purpose, title, interference with use or
// enjoyment, and/or non infringement, whether express or implied by statute, common law,
// usage of trade, course of dealing, custom, or otherwise. No NDI dealer, distributor, agent
// or employee is authorized to make any modification or addition to this warranty.
// In no event shall NDI nor any of its employees be liable for any direct, indirect,
// incidental, special, exemplary, or consequential damages, sundry damages or any
// damages whatsoever, including, but not limited to, procurement of substitute goods or
// services, loss of use, data or profits, or business interruption, however caused. In no
// event shall NDI's liability to the licensee exceed the amount paid by the licensee for the
// Sample Code or any NDI products that accompany the Sample Code. The said limitations
// and exclusions of liability shall apply whether or not any such damages are construed as
// arising from a breach of a representation, warranty, guarantee, covenant, obligation,
// condition or fundamental term or 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
// the Sample Code even if advised of the possibility of such damage. In no event shall
// NDI be liable for any claims, losses, damages, judgments, costs, awards, expenses or
// liabilities of any kind whatsoever arising directly or indirectly from any injury to person
// or property, arising from the Sample Code or any use thereof
//
//----------------------------------------------------------------------------
#ifndef TCP_CONNECTION_HPP
#define TCP_CONNECTION_HPP
#ifdef _WIN32
// Include the DLL for socket programming
// Confusingly, the 64-bit library has 32 in its name as well...
// See: http://stackoverflow.com/questions/5507607/winsock-and-x64-target
#pragma comment(lib, "Ws2_32.lib")
#include <winsock2.h> // for Windows Socket API (WSA)
#include <ws2tcpip.h> // for getaddrinfo() etc...
#else
// Mac and Linux use a different API for sockets
#include <sys/socket.h>
#include <sys/types.h>
#include <netdb.h>
#include <unistd.h>
#endif
#include "Connection.h"
/**
* @brief A cross platform socket implementation.
*/
class TcpConnection : public Connection
{
public:
/** Constructs a socket object that is cross-platform. */
TcpConnection();
/**
* @brief Constructs a socket object and connects immediately.
* @param hostname The hostname or IP address of the measurement system.
* @param port The port to connect on. Port 8765 is default for Vega systems.
*/
TcpConnection(const char* hostname, const char* port = "8765");
/**
* @brief Closes the socket connection and frees memory.
*/
virtual ~TcpConnection();
/**
* @brief Closes any existing connection, and connects to the new device.
* @param hostname The hostname or IP address of the device.
* @param port The port number to connect on.
*/
bool connect(const char* hostname, const char* port);
/**
* @brief Closes any existing connection, and connects to the new device on port 8765.
* @param hostname The hostname or IP address of the device.
*/
bool connect(const char* hostname);
/** @brief Closes the socket connection */
void disconnect();
/** @brief Returns true if the socket connection succeeded */
bool isConnected() const;
/**
* @brief Reads 'length' bytes from the socket into 'buffer'
* @param buffer The buffer to read into.
* @param length The number of bytes to read.
*/
int read(byte_t* buffer, int length) const;
/**
* @brief Reads 'length' chars from the socket into 'buffer'
* @param buffer The buffer to read into.
* @param length The number of chars to read.
*/
int read(char* buffer, int length) const;
/**
* @brief Writes 'length' bytes from 'buffer' to the socket
* @param buffer The buffer to write from.
* @param length The number of bytes to write.
*/
int write(byte_t* buffer, int length) const;
/**
* @brief Writes 'length' chars from 'buffer' to the socket
* @param buffer The buffer to write from.
* @param length The number of chars to write.
*/
int write(const char* buffer, int length) const;
private:
static const int NUM_CONNECTION_RETRIES = 3;
//! Setup method common to all constructors.
void init();
//! Returns true if the socket is valid, otherwise false
bool socketIsValid() const;
/* Private Members */
bool isConnected_;
#ifdef _WIN32 // Windows socket implementation
WSADATA wsaData_;
SOCKET ndiSocket_;
#else // Mac or Linux
//! File descriptor for the socket
int ndiSocket_;
#endif
};
#endif // TCP_CONNECTION_HPP
| 40.047619 | 95 | 0.715984 | [
"object"
] |
068f1af1035c8255124f4da3e9b5f6459157cae9 | 4,189 | h | C | src/avt/Pipeline/Data/avtRayFunction.h | visit-dav/vis | c08bc6e538ecd7d30ddc6399ec3022b9e062127e | [
"BSD-3-Clause"
] | 226 | 2018-12-29T01:13:49.000Z | 2022-03-30T19:16:31.000Z | src/avt/Pipeline/Data/avtRayFunction.h | visit-dav/vis | c08bc6e538ecd7d30ddc6399ec3022b9e062127e | [
"BSD-3-Clause"
] | 5,100 | 2019-01-14T18:19:25.000Z | 2022-03-31T23:08:36.000Z | src/avt/Pipeline/Data/avtRayFunction.h | visit-dav/vis | c08bc6e538ecd7d30ddc6399ec3022b9e062127e | [
"BSD-3-Clause"
] | 84 | 2019-01-24T17:41:50.000Z | 2022-03-10T10:01:46.000Z | // Copyright (c) Lawrence Livermore National Security, LLC and other VisIt
// Project developers. See the top-level LICENSE file for dates and other
// details. No copyright assignment is required to contribute to VisIt.
// ************************************************************************* //
// avtRayFunction.h //
// ************************************************************************* //
#ifndef AVT_RAY_FUNCTION_H
#define AVT_RAY_FUNCTION_H
#include <pipeline_exports.h>
#include <avtCellTypes.h>
class avtGradients;
class avtLightingModel;
class avtRay;
// ****************************************************************************
// Class: avtRayFunction
//
// Purpose:
// This is the base type for any ray function. A ray function is a
// routine that takes a series of sample points along a ray (avtRay) and
// a lighting model and determines what the shading for the pixel should
// be.
//
// Programmer: Hank Childs
// Creation: December 1, 2000
//
// Modifications:
//
// Hank Childs, Sat Feb 3 20:14:19 PST 2001
// Made the output of GetRayValue be a pixel instead of a value.
//
// Hank Childs, Thu Feb 5 17:11:06 PST 2004
// Moved inlined constructor and destructor definitions to .C files
// because certain compilers have problems with them.
//
// Hank Childs, Mon Sep 11 14:59:30 PDT 2006
// Add method SetPrimaryIndex. Also add methods for needing pixel
// indices.
//
// Hank Childs, Tue Dec 18 10:04:43 PST 2007
// Define private copy constructor and assignment operator to prevent
// accidental use of default, bitwise copy implementations.
//
// Hank Childs, Sun Aug 31 08:04:42 PDT 2008
// Remove infrastructure for gradients. This is now done a different way.
// Add support for lighting using gradients.
//
// ****************************************************************************
class PIPELINE_API avtRayFunction
{
public:
avtRayFunction(avtLightingModel *);
virtual ~avtRayFunction();
void SetPrimaryVariableIndex(int vi)
{ primaryVariableIndex = vi; };
virtual void GetRayValue(const avtRay *,
unsigned char rgb[3], double) = 0;
virtual bool CanContributeToPicture(int,
const double (*)[AVT_VARIABLE_LIMIT]);
virtual bool NeedPixelIndices(void) { return false; };
void SetPixelIndex(int i, int j)
{ pixelIndexI = i; pixelIndexJ = j; };
void SetGradientVariableIndex(int gvi);
virtual int GetOpacityVariableIndex() const { return -1; }
virtual int GetWeightVariableIndex() const { return -1; }
protected:
avtLightingModel *lighting;
int gradientVariableIndex;
int primaryVariableIndex;
int pixelIndexI, pixelIndexJ;
inline int IndexOfDepth(const double &, const int &);
private:
// These methods are defined to prevent accidental use of bitwise copy
// implementations. If you want to re-define them to do something
// meaningful, that's fine.
avtRayFunction(const avtRayFunction &) {;};
avtRayFunction &operator=(const avtRayFunction &) { return *this; };
};
// ****************************************************************************
// Method: avtRayFunction::IndexOfDepth
//
// Purpose:
// Determines the index of a depth in the z-buffer. Assumes 0. is the
// near plane, 1. is the far plane.
//
// Programmer: Hank Childs
// Creation: February 13, 2001
//
// ****************************************************************************
inline int
avtRayFunction::IndexOfDepth(const double &depth, const int &numSamples)
{
int rv = (int) (depth*numSamples);
if (rv >= numSamples)
{
rv = numSamples-1;
}
else if (rv < 0)
{
rv = 0;
}
return rv;
}
#endif
| 32.472868 | 80 | 0.542373 | [
"model"
] |
0691502f5cdad01c0ce8b11a5b3dc1decb2d9bd0 | 7,340 | c | C | sdk/project/test_posixapi/test_stdio.c | doyaGu/C0501Q_HWJL01 | 07a71328bd9038453cbb1cf9c276a3dd1e416d63 | [
"MIT"
] | 1 | 2021-10-09T08:05:50.000Z | 2021-10-09T08:05:50.000Z | sdk/project/test_posixapi/test_stdio.c | doyaGu/C0501Q_HWJL01 | 07a71328bd9038453cbb1cf9c276a3dd1e416d63 | [
"MIT"
] | null | null | null | sdk/project/test_posixapi/test_stdio.c | doyaGu/C0501Q_HWJL01 | 07a71328bd9038453cbb1cf9c276a3dd1e416d63 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include "ite/itp.h"
/* This example is to print the answer of variables */
void test_printf()
{
int a,b;
float c,d;
a = 15;
b = a / 2;
printf("%d\n",b);
printf("%3d\n",b);
printf("%03d\n",b);
c = 15.3;
d = c / 3;
printf("%3.2f\n",d);
}
/*
This example opens a file myfile.dat for reading as a stream and then
closes the file.
*/
void test_fclose()
{
FILE *stream;
stream = fopen("myfile.dat", "r");
if (fclose(stream)) // Close the stream.
printf("fclose error\n");
else
printf("fclose successful\n");
}
/*
This example attempts to read NUM_ALPHA characters from the
file myfile.dat.
If there are any errors with either &fread. or &fopen., a
message is printed.
*/
void test_fread()
{
int NUM_ALPHA = 50;
FILE * stream;
int num; // number of characters read from stream
// Do not forget that the '\0' char occupies one character too!
char buffer[NUM_ALPHA + 1];
buffer[NUM_ALPHA] = '\0';
if (( stream = fopen("myfile.dat", "r"))!= NULL )
{
num = fread( buffer, sizeof( char ), NUM_ALPHA, stream );
if (num == NUM_ALPHA) { // fread success
printf( "Number of characters read = %i\n", num );
printf( "buffer = %s\n", buffer );
fclose( stream );
}
else
{ // fread failed
if ( ferror(stream) ) // possibility 1
printf( "Error reading myfile.dat" );
else if ( feof(stream))
{ // possibility 2
printf( "EOF found\n" );
printf( "Number of characters read %d\n", num );
printf( "buffer = %.*s\n", num, buffer);
}
}
}
else
printf( "Error opening myfile.dat\n" );
}
/*
This example opens a file myfile.dat for reading.
After performing input operations (not shown), it moves the file
pointer to the beginning of the file.
*/
void test_fseek()
{
FILE *stream;
int result;
if (stream = fopen("myfile.dat", "r"))
{ // successful
if (fseek(stream, 0L, SEEK_SET)) // moves pointer to the beginning of the file
printf("if not equal to 0, then error ...\n");
else
printf("fseek() successful\n");
fclose(stream);
}
}
/*
This example writes NUM characters to a stream.
It checks that the &fopen. function is successful and that
100 items are written to the stream.
*/
void test_fwrite()
{
int NUM =100;
FILE *stream;
char list[NUM];
int numwritten, number;
if((stream = fopen("myfile.dat", "w")) != NULL )
{
for (number = 0; number < NUM; ++number)
list[number] = (char)(number+32);
numwritten = fwrite(list, sizeof(char), NUM, stream);
printf("number of characters written is %d\n",numwritten);
fclose(stream);
}
else
printf("fopen error\n");
}
/*
This example gets a line of input from the stdin stream.
You can also use getc(stdin) instead of &getchar. in the for
statement to get a line of input from stdin.
*/
void test_getchar()
{
int LINE = 80;
char buffer[LINE+1];
int i;
int ch;
printf( "Please enter string and wait 10s to show the result.\n" );
//Keep reading until either:
//1. the length of LINE is exceeded or
//2. the input character is EOF or
//3. the input character is a new-line character
sleep(10); //Wait for User input...10 seconds
for ( i = 0; ( i < LINE ) && (( ch = getchar()) != EOF) &&
( ch !='\n' ); ++i )
buffer[i] = ch;
buffer[i] = '\0'; // a string should always end with '\0' !
printf( "The string is %s\n", buffer );
}
/* This example writes "Hello World" to stdout. */
void test_puts()
{
if ( puts("Hello World") == EOF )
printf( "Error in puts\n" );
}
/*
When you invoke this example with a file name, the program attempts to
remove that file.
It issues a message if an error occurs.
*/
void test_remove()
{
char *s1;
s1="Nenamed.dat"; //remove file name
if ( remove( s1 ) != 0 )
printf( "Could not remove file\n" );
else
printf( "Remove successful!\n" );
}
/*
This example takes two file names as input and uses rename() to change
the file name from the first name to the second name.
*/
void test_rename()
{
char *s1,*s2;
s1="myfile.dat"; //original file name
s2="Nenamed.dat"; //rename file name
if ( rename( s1, s2 ) == 0 )
printf( "Usage: %s old_fn new_fn %s\n", s1, s2 );
else
printf( "Could not rename file\n" );
}
void* TestFunc(void* arg)
{
itpInit();
// wait mouting USB storage
#ifndef _WIN32
sleep(3);
#endif
printf("\nTest : printf()\n-----------------\n");
test_printf();
printf("\nTest : fwrite()\n-----------------\n");
test_fwrite();
printf("\nTest : fclose()\n-----------------\n");
test_fclose();
printf("\nTest : fread()\n-----------------\n");
test_fread();
printf("\nTest : fseek()\n-----------------\n");
test_fseek();
printf("\nTest : puts()\n-----------------\n");
test_puts();
printf("\nTest : rename()\n-----------------\n");
test_rename();
printf("\nTest : remove()\n-----------------\n");
test_remove();
printf("\nTest : getchar()\n-----------------\n");
test_getchar();
printf("\nEnd the test\n");
}
| 29.596774 | 159 | 0.414441 | [
"3d"
] |
0695cd576291df20cbc00acab4c61ca73a23150f | 2,186 | h | C | ThirdParty/fides/vtkfides/fides/predefined/InternalMetadataSource.h | cclauss/VTK | f62a52cce9044159efb4adb7cc0cfd7ec0bc8b6d | [
"BSD-3-Clause"
] | 1,755 | 2015-01-03T06:55:00.000Z | 2022-03-29T05:23:26.000Z | ThirdParty/fides/vtkfides/fides/predefined/InternalMetadataSource.h | cclauss/VTK | f62a52cce9044159efb4adb7cc0cfd7ec0bc8b6d | [
"BSD-3-Clause"
] | 29 | 2015-04-23T20:58:30.000Z | 2022-03-02T16:16:42.000Z | ThirdParty/fides/vtkfides/fides/predefined/InternalMetadataSource.h | cclauss/VTK | f62a52cce9044159efb4adb7cc0cfd7ec0bc8b6d | [
"BSD-3-Clause"
] | 1,044 | 2015-01-05T22:48:27.000Z | 2022-03-31T02:38:26.000Z | //============================================================================
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt for details.
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notice for more information.
//
//============================================================================
#ifndef fides_datamodel_InternalMetadataSource_H
#define fides_datamodel_InternalMetadataSource_H
#include <fides/DataSource.h>
#include <fides/predefined/SupportedDataModels.h>
#include <memory>
#include <string>
#include <vector>
namespace fides
{
namespace predefined
{
/// \brief InternalMetadataSource is a DataSource that has attributes containing
/// info that can be used to generate a data model (instead of providing Fides
/// with a user-created data model).
class InternalMetadataSource
{
public:
/// Constructor. filename is a path to the file containing the attribute
/// information
InternalMetadataSource(const std::string& filename);
~InternalMetadataSource();
/// Get the name of the data model for Fides to generate
std::string GetDataModelName(const std::string& attrName = "Fides_Data_Model");
/// Same as GetDataModelName, except the string is converted to an DataModelTypes enum.
DataModelTypes GetDataModelType(const std::string& attrName = "Fides_Data_Model");
/// Gets the cell type. Not used by all data models
std::string GetDataModelCellType(const std::string& attrName = "Fides_Cell_Type");
/// Reads the attribute specified by attrName
template <typename AttributeType>
std::vector<AttributeType> GetAttribute(const std::string& attrName);
/// Gets the type of the attribute specified by attrName
std::string GetAttributeType(const std::string& attrName);
private:
std::shared_ptr<fides::io::DataSource> Source = nullptr;
};
template <typename AttributeType>
std::vector<AttributeType> InternalMetadataSource::GetAttribute(const std::string& attrName)
{
auto attr = this->Source->ReadAttribute<AttributeType>(attrName);
return attr;
}
}
}
#endif
| 31.681159 | 92 | 0.71043 | [
"vector",
"model"
] |
06973f2069233dadd0f316dd3b185bfe1ac59c7d | 1,394 | h | C | code/engine.vc2008/xrGame/rat_state_manager.h | Rikoshet-234/xray-oxygen | eaac3fa4780639152684f3251b8b4452abb8e439 | [
"Apache-2.0"
] | 7 | 2018-03-27T12:36:07.000Z | 2020-06-26T11:31:52.000Z | code/engine.vc2008/xrGame/rat_state_manager.h | Rikoshet-234/xray-oxygen | eaac3fa4780639152684f3251b8b4452abb8e439 | [
"Apache-2.0"
] | 2 | 2018-05-26T23:17:14.000Z | 2019-04-14T18:33:27.000Z | code/engine.vc2008/xrGame/rat_state_manager.h | Rikoshet-234/xray-oxygen | eaac3fa4780639152684f3251b8b4452abb8e439 | [
"Apache-2.0"
] | 5 | 2020-10-18T11:55:26.000Z | 2022-03-28T07:21:35.000Z | ////////////////////////////////////////////////////////////////////////////
// Module : rat_state_manager.h
// Created : 31.08.2007
// Modified : 31.08.2007
// Author : Dmitriy Iassenev
// Description : rat state manager class
////////////////////////////////////////////////////////////////////////////
#ifndef RAT_STATE_MANAGER_H_INCLUDED
#define RAT_STATE_MANAGER_H_INCLUDED
#include "associative_vector.h"
class rat_state_base;
class CAI_Rat;
class rat_state_manager {
private:
typedef u32 state_id_type;
typedef associative_vector<state_id_type, rat_state_base*> States;
typedef xr_stack<state_id_type> Stack;
private:
CAI_Rat *m_object;
States m_states;
Stack m_stack;
state_id_type m_last_state_id;
private:
rat_state_base *state (state_id_type const &state_id);
public:
rat_state_manager ();
rat_state_manager(const rat_state_manager& other) = delete;
rat_state_manager& operator=(const rat_state_manager& other) = delete;
~rat_state_manager ();
void construct (CAI_Rat *object);
IC void change_state (state_id_type const &state_id);
void push_state (state_id_type const &state_id);
void pop_state ();
void add_state (state_id_type const &state_id, rat_state_base *state);
void update ();
};
#include "rat_state_manager_inline.h"
#endif // RAT_STATE_MANAGER_H_INCLUDED | 29.041667 | 77 | 0.650646 | [
"object"
] |
069af3d3a085d7d74fac87fc2929aaaa1b3962ff | 6,560 | h | C | LibFoundation/Mathematics/Wm4Matrix2.h | wjezxujian/WildMagic4 | 249a17f8c447cf57c6283408e01009039810206a | [
"BSL-1.0"
] | 3 | 2021-08-02T04:03:03.000Z | 2022-01-04T07:31:20.000Z | LibFoundation/Mathematics/Wm4Matrix2.h | wjezxujian/WildMagic4 | 249a17f8c447cf57c6283408e01009039810206a | [
"BSL-1.0"
] | null | null | null | LibFoundation/Mathematics/Wm4Matrix2.h | wjezxujian/WildMagic4 | 249a17f8c447cf57c6283408e01009039810206a | [
"BSL-1.0"
] | 5 | 2019-10-13T02:44:19.000Z | 2021-08-02T04:03:10.000Z | // Geometric Tools, Inc.
// http://www.geometrictools.com
// Copyright (c) 1998-2006. All Rights Reserved
//
// The Wild Magic Version 4 Foundation Library source code is supplied
// under the terms of the license agreement
// http://www.geometrictools.com/License/Wm4FoundationLicense.pdf
// and may not be copied or disclosed except in accordance with the terms
// of that agreement.
#ifndef WM4MATRIX2_H
#define WM4MATRIX2_H
// Matrix operations are applied on the left. For example, given a matrix M
// and a vector V, matrix-times-vector is M*V. That is, V is treated as a
// column vector. Some graphics APIs use V*M where V is treated as a row
// vector. In this context the "M" matrix is really a transpose of the M as
// represented in Wild Magic. Similarly, to apply two matrix operations M0
// and M1, in that order, you compute M1*M0 so that the transform of a vector
// is (M1*M0)*V = M1*(M0*V). Some graphics APIs use M0*M1, but again these
// matrices are the transpose of those as represented in Wild Magic. You
// must therefore be careful about how you interface the transformation code
// with graphics APIS.
//
// For memory organization it might seem natural to chose Real[N][N] for the
// matrix storage, but this can be a problem on a platform/console that
// chooses to store the data in column-major rather than row-major format.
// To avoid potential portability problems, the matrix is stored as Real[N*N]
// and organized in row-major order. That is, the entry of the matrix in row
// r (0 <= r < N) and column c (0 <= c < N) is stored at index i = c+N*r
// (0 <= i < N*N).
// Rotation matrices are of the form
// R = cos(t) -sin(t)
// sin(t) cos(t)
// where t > 0 indicates a counterclockwise rotation in the xy-plane.
#include "Wm4FoundationLIB.h"
#include "Wm4Vector2.h"
namespace Wm4
{
template <class Real>
class Matrix2
{
public:
// If bZero is true, create the zero matrix. Otherwise, create the
// identity matrix.
Matrix2 (bool bZero = true);
// copy constructor
Matrix2 (const Matrix2& rkM);
// input Mrc is in row r, column c.
Matrix2 (Real fM00, Real fM01, Real fM10, Real fM11);
// Create a matrix from an array of numbers. The input array is
// interpreted based on the Boolean input as
// true: entry[0..3] = {m00,m01,m10,m11} [row major]
// false: entry[0..3] = {m00,m10,m01,m11} [column major]
Matrix2 (const Real afEntry[4], bool bRowMajor);
// Create matrices based on vector input. The Boolean is interpreted as
// true: vectors are columns of the matrix
// false: vectors are rows of the matrix
Matrix2 (const Vector2<Real>& rkU, const Vector2<Real>& rkV,
bool bColumns);
Matrix2 (const Vector2<Real>* akV, bool bColumns);
// create a diagonal matrix
Matrix2 (Real fM00, Real fM11);
// create a rotation matrix (positive angle - counterclockwise)
Matrix2 (Real fAngle);
// create a tensor product U*V^T
Matrix2 (const Vector2<Real>& rkU, const Vector2<Real>& rkV);
// create various matrices
void MakeZero ();
void MakeIdentity ();
void MakeDiagonal (Real fM00, Real fM11);
void FromAngle (Real fAngle);
void MakeTensorProduct (const Vector2<Real>& rkU,
const Vector2<Real>& rkV);
// member access
operator const Real* () const;
operator Real* ();
const Real* operator[] (int iRow) const;
Real* operator[] (int iRow);
Real operator() (int iRow, int iCol) const;
Real& operator() (int iRow, int iCol);
void SetRow (int iRow, const Vector2<Real>& rkV);
Vector2<Real> GetRow (int iRow) const;
void SetColumn (int iCol, const Vector2<Real>& rkV);
Vector2<Real> GetColumn (int iCol) const;
void GetColumnMajor (Real* afCMajor) const;
// assignment
Matrix2& operator= (const Matrix2& rkM);
// comparison
bool operator== (const Matrix2& rkM) const;
bool operator!= (const Matrix2& rkM) const;
bool operator< (const Matrix2& rkM) const;
bool operator<= (const Matrix2& rkM) const;
bool operator> (const Matrix2& rkM) const;
bool operator>= (const Matrix2& rkM) const;
// arithmetic operations
Matrix2 operator+ (const Matrix2& rkM) const;
Matrix2 operator- (const Matrix2& rkM) const;
Matrix2 operator* (const Matrix2& rkM) const;
Matrix2 operator* (Real fScalar) const;
Matrix2 operator/ (Real fScalar) const;
Matrix2 operator- () const;
// arithmetic updates
Matrix2& operator+= (const Matrix2& rkM);
Matrix2& operator-= (const Matrix2& rkM);
Matrix2& operator*= (Real fScalar);
Matrix2& operator/= (Real fScalar);
// matrix times vector
Vector2<Real> operator* (const Vector2<Real>& rkV) const; // M * v
// other operations
Matrix2 Transpose () const; // M^T
Matrix2 TransposeTimes (const Matrix2& rkM) const; // this^T * M
Matrix2 TimesTranspose (const Matrix2& rkM) const; // this * M^T
Matrix2 Inverse () const;
Matrix2 Adjoint () const;
Real Determinant () const;
Real QForm (const Vector2<Real>& rkU,
const Vector2<Real>& rkV) const; // u^T*M*v
// The matrix must be a rotation for these functions to be valid. The
// last function uses Gram-Schmidt orthonormalization applied to the
// columns of the rotation matrix. The angle must be in radians, not
// degrees.
void ToAngle (Real& rfAngle) const;
void Orthonormalize ();
// The matrix must be symmetric. Factor M = R * D * R^T where
// R = [u0|u1] is a rotation matrix with columns u0 and u1 and
// D = diag(d0,d1) is a diagonal matrix whose diagonal entries are d0 and
// d1. The eigenvector u[i] corresponds to eigenvector d[i]. The
// eigenvalues are ordered as d0 <= d1.
void EigenDecomposition (Matrix2& rkRot, Matrix2& rkDiag) const;
WM4_FOUNDATION_ITEM static const Matrix2 ZERO;
WM4_FOUNDATION_ITEM static const Matrix2 IDENTITY;
private:
// for indexing into the 1D array of the matrix, iCol+N*iRow
static int I (int iRow, int iCol);
// support for comparisons
int CompareArrays (const Matrix2& rkM) const;
// matrix stored in row-major order
Real m_afEntry[4];
};
// c * M
template <class Real>
Matrix2<Real> operator* (Real fScalar, const Matrix2<Real>& rkM);
// v^T * M
template <class Real>
Vector2<Real> operator* (const Vector2<Real>& rkV, const Matrix2<Real>& rkM);
#include "Wm4Matrix2.inl"
typedef Matrix2<float> Matrix2f;
typedef Matrix2<double> Matrix2d;
}
#endif
| 35.846995 | 77 | 0.679573 | [
"vector",
"transform"
] |
069eef521f0ad20d2c74e6cb057f5c588a31d85c | 9,099 | h | C | include/Solver.h | lucasbekker/CMaT | 5d3fdbf8aaaccda471bf73399ae8d3cc7d144d0a | [
"MIT"
] | 1 | 2019-08-02T09:16:56.000Z | 2019-08-02T09:16:56.000Z | include/Solver.h | lucasbekker/CMaT | 5d3fdbf8aaaccda471bf73399ae8d3cc7d144d0a | [
"MIT"
] | 10 | 2019-01-18T12:32:33.000Z | 2019-01-28T16:38:48.000Z | include/Solver.h | lucasbekker/CMaT | 5d3fdbf8aaaccda471bf73399ae8d3cc7d144d0a | [
"MIT"
] | null | null | null | #pragma once
extern int num_iter = 0;
struct SOLVER_data {
// Matrix A.
GPU_Sparse * A_g;
GPU_Sparse_f * A_gf;
CPU_Sparse * A_c;
CPU_Sparse_f * A_cf;
// Vector b.
GPU_Dense * b_g;
GPU_Dense_f * b_gf;
CPU_Dense * b_c;
CPU_Dense_f * b_cf;
// Vector x.
GPU_Dense * x_g;
GPU_Dense_f * x_gf;
CPU_Dense * x_c;
CPU_Dense_f * x_cf;
// Size parameters.
int n;
int nnz;
};
class SOLVER_AmgX {
public:
// Data
// AMGX configuration specification.
std::string config_spec;
// AMGX handles.
AMGX_config_handle config;
AMGX_resources_handle resources;
AMGX_solver_handle solver;
AMGX_Mode mode;
// AMGX problem data.
int n;
int nnz;
AMGX_matrix_handle A;
AMGX_vector_handle b;
AMGX_vector_handle x;
// Methods.
// Setup and call the solver.
void solve ( ) {
// Solve Ax=b.
AMGX_solver_setup(solver, A);
AMGX_solver_solve(solver, b, x);
}
// Gather the result.
void download ( SOLVER_data & Axb ) {
// Initialize pointer.
void * x_pointer = NULL;
// Generate correct address.
if ( mode == AMGX_mode_dDDI ) {
x_pointer = (void *) thrust::raw_pointer_cast(&(Axb.x_g->Values[0]));
} else if ( mode == AMGX_mode_dFFI ) {
x_pointer = (void *) thrust::raw_pointer_cast(&(Axb.x_gf->Values[0]));
} else if ( mode == AMGX_mode_hDDI ) {
x_pointer = (void *) thrust::raw_pointer_cast(&(Axb.x_c->Values[0]));
} else {
x_pointer = (void *) thrust::raw_pointer_cast(&(Axb.x_cf->Values[0]));
}
// Store values of output vector.
AMGX_vector_download(x, x_pointer);
}
// Retrieve the input data.
void upload ( SOLVER_data & Axb ) {
// Initialize pointers.
int * A_row_ptr = NULL;
int * A_col_ind = NULL;
void * A_data = NULL;
void * b_pointer = NULL;
void * x_pointer = NULL;
// Initialize temporary I vector.
thrust::host_vector<int> I_temp;
// Generate correct addresses.
if ( mode == AMGX_mode_dDDI ) {
x_pointer = (void *) thrust::raw_pointer_cast(&(Axb.x_g->Values[0]));
b_pointer = (void *) thrust::raw_pointer_cast(&(Axb.b_g->Values[0]));
A_data = (void *) thrust::raw_pointer_cast(&(Axb.A_g->Values[0]));
A_col_ind = thrust::raw_pointer_cast(&(Axb.A_g->J[0]));
A_row_ptr = thrust::raw_pointer_cast(&(Axb.A_g->I[0]));
} else if ( mode == AMGX_mode_dFFI ) {
x_pointer = (void *) thrust::raw_pointer_cast(&(Axb.x_gf->Values[0]));
b_pointer = (void *) thrust::raw_pointer_cast(&(Axb.b_gf->Values[0]));
A_data = (void *) thrust::raw_pointer_cast(&(Axb.A_gf->Values[0]));
A_col_ind = thrust::raw_pointer_cast(&(Axb.A_gf->J[0]));
A_row_ptr = thrust::raw_pointer_cast(&(Axb.A_gf->I[0]));
} else if ( mode == AMGX_mode_hDDI ) {
x_pointer = (void *) thrust::raw_pointer_cast(&(Axb.x_c->Values[0]));
b_pointer = (void *) thrust::raw_pointer_cast(&(Axb.b_c->Values[0]));
A_data = (void *) thrust::raw_pointer_cast(&(Axb.A_c->Values[0]));
A_col_ind = thrust::raw_pointer_cast(&(Axb.A_c->J[0]));
int * Ib_begin = thrust::raw_pointer_cast(&(Axb.A_c->Ib[0]));
int * Ie_end = thrust::raw_pointer_cast(&(Axb.A_c->Ie[(n - 1)]));
I_temp.insert(I_temp.begin(),Ib_begin,(Ib_begin + n));
I_temp.insert(I_temp.end(),Ie_end,(Ie_end + 1));
A_row_ptr = thrust::raw_pointer_cast(&I_temp[0]);
} else {
x_pointer = (void *) thrust::raw_pointer_cast(&(Axb.x_cf->Values[0]));
b_pointer = (void *) thrust::raw_pointer_cast(&(Axb.b_cf->Values[0]));
A_data = (void *) thrust::raw_pointer_cast(&(Axb.A_cf->Values[0]));
A_col_ind = thrust::raw_pointer_cast(&(Axb.A_cf->J[0]));
int * Ib_begin = thrust::raw_pointer_cast(&(Axb.A_cf->Ib[0]));
int * Ie_end = thrust::raw_pointer_cast(&(Axb.A_cf->Ie[(n - 1)]));
I_temp.insert(I_temp.begin(),Ib_begin,(Ib_begin + n));
I_temp.insert(I_temp.end(),Ie_end,(Ie_end + 1));
A_row_ptr = thrust::raw_pointer_cast(&I_temp[0]);
}
// Upload A, b and x to AMGX.
AMGX_matrix_upload_all(A, n, nnz, 1, 1, A_row_ptr, A_col_ind, A_data, 0);
AMGX_vector_upload(b, n, 1, b_pointer);
AMGX_vector_upload(x, n, 1, x_pointer);
}
// Clean the AMGX related objects.
void destroy ( ) {
// Destroy AMGX objects.
AMGX_solver_destroy(solver);
AMGX_matrix_destroy(A);
AMGX_vector_destroy(b);
AMGX_vector_destroy(x);
AMGX_resources_destroy(resources);
AMGX_config_destroy(config);
// Finalize AMGX library.
AMGX_reset_signal_handler();
AMGX_finalize_plugins();
AMGX_finalize();
}
// Constructor.
SOLVER_AmgX ( std::string input_config, AMGX_Mode input_mode, SOLVER_data & Axb ) {
// Store the input.
n = Axb.n;
nnz = Axb.nnz;
mode = input_mode;
config_spec = input_config;
// Initialize AMGX library.
AMGX_initialize();
AMGX_initialize_plugins();
AMGX_install_signal_handler();
// Create AMGX configuration, resources and solver.
AMGX_config_create_from_file(&config, config_spec.c_str());
AMGX_resources_create_simple(&resources, config);
AMGX_solver_create(&solver, resources, mode, config);
// Create the AMGX matrix and vectors.
AMGX_matrix_create(&A, resources, mode);
AMGX_vector_create(&b, resources, mode);
AMGX_vector_create(&x, resources, mode);
// Upload the data.
upload(Axb);
// Solve Ax=b.
solve();
// Get the number of iterations
AMGX_solver_get_iterations_number(solver,&num_iter);
num_iter--;
// Store the results.
download(Axb);
}
// Destructor.
~SOLVER_AmgX ( ) {
destroy();
}
};
CPU_Dense CPU_Sparse::solve ( CPU_Dense & b, std::string config_spec ) {
// Initialize output vector and fill with initial guess.
CPU_Dense x = b.clone();
// Initialize solver data and fill with addresses.
SOLVER_data Axb;
Axb.A_c = this;
Axb.b_c = &b;
Axb.x_c = &x;
Axb.n = Size[0];
Axb.nnz = Size[2];
// Specify AMGX configuration.
AMGX_Mode mode = AMGX_mode_hDDI;
// Start the solving procedure.
SOLVER_AmgX AMGX(config_spec, mode, Axb);
// Return the output vector.
return x;
}
CPU_Dense_f CPU_Sparse_f::solve ( CPU_Dense_f & b, std::string config_spec ) {
// Initialize output vector and fill with initial guess.
CPU_Dense_f x = b.clone();
// Initialize solver data and fill with addresses.
SOLVER_data Axb;
Axb.A_cf = this;
Axb.b_cf = &b;
Axb.x_cf = &x;
Axb.n = Size[0];
Axb.nnz = Size[2];
// Specify AMGX configuration.
AMGX_Mode mode = AMGX_mode_hFFI;
// Start the solving procedure.
SOLVER_AmgX AMGX(config_spec, mode, Axb);
// Return the output vector.
return x;
}
GPU_Dense GPU_Sparse::solve ( GPU_Dense & b, std::string config_spec ) {
// Initialize output vector and fill with initial guess.
GPU_Dense x = b.clone();
// Initialize solver data and fill with addresses.
SOLVER_data Axb;
Axb.A_g = this;
Axb.b_g = &b;
Axb.x_g = &x;
Axb.n = Size[0];
Axb.nnz = Size[2];
// Specify AMGX configuration.
AMGX_Mode mode = AMGX_mode_dDDI;
// Start the solving procedure.
SOLVER_AmgX AMGX(config_spec, mode, Axb);
// Return the output vector.
return x;
}
GPU_Dense GPU_Sparse::solve ( GPU_Dense & b, GPU_Dense & x0, std::string config_spec ) {
// Initialize output vector and fill with initial guess.
GPU_Dense x = x0.clone();
// Initialize solver data and fill with addresses.
SOLVER_data Axb;
Axb.A_g = this;
Axb.b_g = &b;
Axb.x_g = &x;
Axb.n = Size[0];
Axb.nnz = Size[2];
// Specify AMGX configuration.
AMGX_Mode mode = AMGX_mode_dDDI;
// Start the solving procedure.
SOLVER_AmgX AMGX(config_spec, mode, Axb);
// Return the output vector.
return x;
}
GPU_Dense_f GPU_Sparse_f::solve ( GPU_Dense_f & b, std::string config_spec ) {
// Initialize output vector and fill with initial guess.
GPU_Dense_f x = b.clone();
// Initialize solver data and fill with addresses.
SOLVER_data Axb;
Axb.A_gf = this;
Axb.b_gf = &b;
Axb.x_gf = &x;
Axb.n = Size[0];
Axb.nnz = Size[2];
// Specify AMGX configuration.
AMGX_Mode mode = AMGX_mode_dFFI;
// Start the solving procedure.
SOLVER_AmgX AMGX(config_spec, mode, Axb);
// Return the output vector.
return x;
} | 28.434375 | 94 | 0.593252 | [
"vector"
] |
06b1a68cf896b21eb033cb41934f5c3278298ca1 | 873 | h | C | src/ClientSymbols/include/ClientSymbols/QSettingsBasedStorageManager.h | ioperations/orbit | c7935085023cce1abb70ce96dd03339f47a1c826 | [
"BSD-2-Clause"
] | 716 | 2017-09-22T11:50:40.000Z | 2020-03-14T21:52:22.000Z | src/ClientSymbols/include/ClientSymbols/QSettingsBasedStorageManager.h | ioperations/orbit | c7935085023cce1abb70ce96dd03339f47a1c826 | [
"BSD-2-Clause"
] | 132 | 2017-09-24T11:48:18.000Z | 2020-03-17T17:39:45.000Z | src/ClientSymbols/include/ClientSymbols/QSettingsBasedStorageManager.h | ioperations/orbit | c7935085023cce1abb70ce96dd03339f47a1c826 | [
"BSD-2-Clause"
] | 49 | 2017-09-23T10:23:59.000Z | 2020-03-14T09:27:49.000Z | // Copyright (c) 2022 The Orbit Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CLIENT_SYMBOLS_Q_SETTINGS_BASED_STORAGE_MANAGER_H_
#define CLIENT_SYMBOLS_Q_SETTINGS_BASED_STORAGE_MANAGER_H_
#include "ClientSymbols/PersistentStorageManager.h"
namespace orbit_client_symbols {
class QSettingsBasedStorageManager : public PersistentStorageManager {
public:
void SavePaths(absl::Span<const std::filesystem::path> paths) override;
[[nodiscard]] std::vector<std::filesystem::path> LoadPaths() override;
void SaveModuleSymbolFileMappings(const ModuleSymbolFileMappings& mappings) override;
[[nodiscard]] ModuleSymbolFileMappings LoadModuleSymbolFileMappings() override;
};
} // namespace orbit_client_symbols
#endif // CLIENT_SYMBOLS_Q_SETTINGS_BASED_STORAGE_MANAGER_H_ | 39.681818 | 87 | 0.82016 | [
"vector"
] |
06c0724db67512ac9f9689a7fd6cde648e8a025e | 7,853 | h | C | libs/opengl/include/mrpt/opengl/CMeshFast.h | feroze/mrpt-shivang | 95bf524c5e10ed2e622bd199f1b0597951b45370 | [
"BSD-3-Clause"
] | 2 | 2017-03-25T18:09:17.000Z | 2017-05-22T08:14:48.000Z | libs/opengl/include/mrpt/opengl/CMeshFast.h | feroze/mrpt-shivang | 95bf524c5e10ed2e622bd199f1b0597951b45370 | [
"BSD-3-Clause"
] | null | null | null | libs/opengl/include/mrpt/opengl/CMeshFast.h | feroze/mrpt-shivang | 95bf524c5e10ed2e622bd199f1b0597951b45370 | [
"BSD-3-Clause"
] | 1 | 2018-07-29T09:40:46.000Z | 2018-07-29T09:40:46.000Z | /* +---------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| http://www.mrpt.org/ |
| |
| Copyright (c) 2005-2017, Individual contributors, see AUTHORS file |
| See: http://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See details in http://www.mrpt.org/License |
+---------------------------------------------------------------------------+ */
#ifndef opengl_CMeshFast_H
#define opengl_CMeshFast_H
#include <mrpt/opengl/CRenderizableDisplayList.h>
#include <mrpt/math/CMatrix.h>
#include <mrpt/utils/CImage.h>
#include <mrpt/utils/color_maps.h>
namespace mrpt
{
namespace opengl
{
// This must be added to any CSerializable derived class:
DEFINE_SERIALIZABLE_PRE_CUSTOM_BASE_LINKAGE( CMeshFast, CRenderizableDisplayList, OPENGL_IMPEXP )
/** A planar (XY) grid where each cell has an associated height and, optionally, a texture map.
* To make it faster to render, instead of drawing lines and triangles it draws a point at each
* gridcell.
* A typical usage example would be an elevation map or a 3D model of a terrain.
* \sa opengl::COpenGLScene
*
* <div align="center">
* <table border="0" cellspan="4" cellspacing="4" style="border-width: 1px; border-style: solid;">
* <tr> <td> mrpt::opengl::CMeshFast </td> <td> \image html preview_CMeshFast.png </td> </tr>
* </table>
* </div>
*
* \ingroup mrpt_opengl_grp
*/
class OPENGL_IMPEXP CMeshFast : public CRenderizableDisplayList
{
DEFINE_SERIALIZABLE( CMeshFast )
protected:
mrpt::utils::CImage m_textureImage;
bool m_enableTransparency;
bool m_colorFromZ;
bool m_isImage;
mutable math::CMatrix X; //!< X(x,y): X-coordinate of the point (x,y)
mutable math::CMatrix Y; //!< Y(x,y): Y-coordinate of the point (x,y)
mutable math::CMatrix Z; //!< Z(x,y): Z-coordinate of the point (x,y)
mutable math::CMatrix C; //!< Grayscale Color [0,1] for each cell, updated by updateColorsMatrix
mutable math::CMatrix C_r; //!< Red Component of the Color [0,1] for each cell, updated by updateColorsMatrix
mutable math::CMatrix C_g; //!< Green Component of the Color [0,1] for each cell, updated by updateColorsMatrix
mutable math::CMatrix C_b; //!< Blue Component of the Color [0,1] for each cell, updated by updateColorsMatrix
mrpt::utils::TColormap m_colorMap; //!< Used when m_colorFromZ is true
float m_pointSize; //!< By default is 1.0
bool m_pointSmooth; //!< Default: false
mutable bool m_modified_Z; //!< Whether C is not up-to-date wrt to Z
mutable bool m_modified_Image; //!< Whether C is not up-to-date wrt to the texture image
void updateColorsMatrix() const; //!< Called internally to assure C is updated.
void updatePoints() const;
float xMin,xMax,yMin,yMax; //!< Mesh bounds
mutable bool pointsUpToDate; //!<Whether the coordinates of the points needs to be recalculated
public:
inline void setPointSize(float p) { m_pointSize=p; } //!< By default is 1.0
inline float getPointSize() const { return m_pointSize; }
inline void enablePointSmooth(bool enable=true) { m_pointSmooth=enable; }
inline void disablePointSmooth() { m_pointSmooth=false; }
void setGridLimits(float xmin,float xmax, float ymin, float ymax)
{
xMin=xmin; xMax = xmax;
yMin=ymin; yMax = ymax;
CRenderizableDisplayList::notifyChange();
}
void getGridLimits(float &xmin,float &xmax, float &ymin, float &ymax) const
{
xmin=xMin; xmax=xMax;
ymin=yMin; ymax=yMax;
}
void enableTransparency( bool v ) { m_enableTransparency = v; CRenderizableDisplayList::notifyChange(); }
void enableColorFromZ( bool v, mrpt::utils::TColormap colorMap = mrpt::utils::cmJET )
{
m_colorFromZ = v;
m_colorMap = colorMap;
CRenderizableDisplayList::notifyChange();
}
/** This method sets the matrix of heights for each position (cell) in the mesh grid */
void setZ( const mrpt::math::CMatrixTemplateNumeric<float> &in_Z );
/** Returns a reference to the internal Z matrix, allowing changing it efficiently */
inline void getZ(mrpt::math::CMatrixFloat &out) const { out=Z; }
inline float getXMin() const { return xMin; }
inline float getXMax() const { return xMax; }
inline float getYMin() const { return yMin; }
inline float getYMax() const { return yMax; }
inline void setXMin(const float &nxm) {
xMin=nxm;
pointsUpToDate=false; CRenderizableDisplayList::notifyChange();
}
inline void setXMax(const float &nxm) {
xMax=nxm;
pointsUpToDate=false; CRenderizableDisplayList::notifyChange();
}
inline void setYMin(const float &nym) {
yMin=nym;
pointsUpToDate=false; CRenderizableDisplayList::notifyChange();
}
inline void setYMax(const float &nym) {
yMax=nym;
pointsUpToDate=false; CRenderizableDisplayList::notifyChange();
}
inline void getXBounds(float &min,float &max) const {
min=xMin;
max=xMax;
}
inline void getYBounds(float &min,float &max) const {
min=yMin;
max=yMax;
}
inline void setXBounds(const float &min,const float &max) {
xMin=min;
xMax=max;
pointsUpToDate=false; CRenderizableDisplayList::notifyChange();
}
inline void setYBounds(const float &min,const float &max) {
yMin=min;
yMax=max;
pointsUpToDate=false; CRenderizableDisplayList::notifyChange();
}
/** Class factory */
static CMeshFastPtr Create(bool enableTransparency, float xMin = -1.0f, float xMax = 1.0f, float yMin = -1.0f, float yMax = 1.0f );
/** Render
*/
void render_dl() const MRPT_OVERRIDE;
/** Evaluates the bounding box of this object (including possible children) in the coordinate frame of the object parent. */
void getBoundingBox(mrpt::math::TPoint3D &bb_min, mrpt::math::TPoint3D &bb_max) const MRPT_OVERRIDE;
/** Assigns a texture image, and disable transparency.
*/
void assignImage(const mrpt::utils::CImage& img );
/** Assigns a texture image and Z simultaneously, and disable transparency.
*/
void assignImageAndZ( const mrpt::utils::CImage& img, const mrpt::math::CMatrixTemplateNumeric<float> &in_Z);
/** Adjust grid limits according to the image aspect ratio, maintaining the X limits and resizing in the Y direction.
*/
inline void adjustGridToImageAR() {
ASSERT_(m_isImage);
const float ycenter = 0.5*(yMin+yMax);
const float xwidth = xMax - xMin;
const float newratio = float(m_textureImage.getWidth())/float(m_textureImage.getHeight());
yMax = ycenter + 0.5*newratio*xwidth;
yMin = ycenter - 0.5*newratio*xwidth;
CRenderizableDisplayList::notifyChange();
}
private:
/** Constructor
*/
CMeshFast( bool enableTransparency = false, float xMin = -1.0f, float xMax = 1.0f, float yMin = -1.0f, float yMax = 1.0f ) :
m_textureImage(0,0),
m_enableTransparency(enableTransparency),
m_colorFromZ(false),
m_isImage(false),
X(0,0), Y(0,0), Z(0,0), C(0,0), C_r(0,0), C_g(0,0), C_b(0,0),
m_colorMap( mrpt::utils::cmJET ),
m_modified_Z(true),
m_modified_Image(false),
xMin(xMin), xMax(xMax), yMin(yMin), yMax(yMax),
pointsUpToDate(false)
{
m_color.A = 255;
m_color.R = 0;
m_color.G = 0;
m_color.B = 150;
}
/** Private, virtual destructor: only can be deleted from smart pointers */
virtual ~CMeshFast() { }
};
DEFINE_SERIALIZABLE_POST_CUSTOM_BASE_LINKAGE( CMeshFast, CRenderizableDisplayList, OPENGL_IMPEXP )
} // end namespace
} // End of namespace
#endif
| 37.042453 | 134 | 0.655673 | [
"mesh",
"render",
"object",
"model",
"3d",
"solid"
] |
06cd071f43bd900a8877d474d4b27d8bd4a8b08f | 3,432 | h | C | Dusty/src/math/Vector3.h | ProjectElon/Dusty | cdec985b046adfb10420d93ee10668fafff41a9a | [
"MIT"
] | 3 | 2019-06-04T12:06:24.000Z | 2019-06-04T23:57:09.000Z | Dusty/src/math/Vector3.h | ProjectElon/Dusty | cdec985b046adfb10420d93ee10668fafff41a9a | [
"MIT"
] | null | null | null | Dusty/src/math/Vector3.h | ProjectElon/Dusty | cdec985b046adfb10420d93ee10668fafff41a9a | [
"MIT"
] | null | null | null | #pragma once
#include "Functions.h"
#include <cstdio>
#include <cassert>
#include <string>
#define STR(x) std::to_string((x))
namespace math
{
class Vector2;
class Vector3
{
public:
float x;
float y;
float z;
Vector3();
Vector3(const float& newX, const float& newY, const float& newZ);
Vector3(const math::Vector2& v, const float& newZ);
Vector3(const Vector3& vector);
~Vector3() = default;
inline float LengthSq() const
{
return x * x + y * y + z * z;
}
inline float Length() const
{
return Sqrt(LengthSq());
}
inline void Normalize()
{
if (IsZero())
{
printf("division by zero\n");
assert(false);
}
float inv = 1.0f / Length();
x *= inv;
y *= inv;
z *= inv;
}
inline Vector3 Normalized() const
{
Vector3 temp = *this;
temp.Normalize();
return temp;
}
inline bool IsUnit() const
{
return IsEqual(LengthSq(), 1.0f);
}
inline bool IsZero() const
{
return NearZero(LengthSq());
}
inline bool operator==(const Vector3& vector) const
{
return IsEqual(x, vector.x) && IsEqual(y, vector.y) && IsEqual(z, vector.z);
}
inline bool operator!=(const Vector3& vector) const
{
return !(*this == vector);
}
inline Vector3 operator+(const Vector3& vector) const
{
return Vector3(x + vector.x, y + vector.y, z + vector.z);
}
inline Vector3 operator-(const Vector3& vector) const
{
return Vector3(x - vector.x, y - vector.y, z - vector.z);
}
inline Vector3 operator-() const
{
return Vector3(-x, -y, -z);
}
inline Vector3& operator+=(const Vector3& vector)
{
x += vector.x;
y += vector.y;
z += vector.z;
return *this;
}
inline Vector3& operator-=(const Vector3& vector)
{
x -= vector.x;
y -= vector.y;
z -= vector.z;
return *this;
}
inline Vector3 operator*(const float& scalar) const
{
return Vector3(x * scalar, y * scalar, z * scalar);
}
inline Vector3& operator*=(const float& scalar)
{
x *= scalar;
y *= scalar;
z *= scalar;
return *this;
}
inline Vector3 operator/(const float& scalar) const
{
if (NearZero(scalar))
{
printf("division by zero\n");
assert(false);
}
float inv = 1.0f / scalar;
return Vector3(x * inv, y * inv, z * inv);
}
inline Vector3& operator/=(const float& scalar)
{
if (NearZero(scalar))
{
printf("division by zero\n");
assert(false);
}
float inv = 1.0f / scalar;
x *= inv;
y *= inv;
z *= inv;
return *this;
}
static inline float Dot(const Vector3& lhs, const Vector3& rhs)
{
return lhs.x * rhs.x + lhs.y * rhs.y + lhs.z * rhs.z;
}
static inline Vector3 Cross(const Vector3& lhs, const Vector3& rhs)
{
return Vector3(
lhs.y * rhs.z - lhs.z * rhs.y,
lhs.z * rhs.x - lhs.x * rhs.z,
lhs.x * rhs.y - lhs.y * rhs.x
);
}
static inline Vector3 Hadamard(const Vector3& lhs, const Vector3& rhs)
{
return Vector3(
lhs.x * rhs.x,
lhs.y * rhs.y,
lhs.z * rhs.z
);
}
std::string ToString() const
{
return "(" + STR(x) + ", " + STR(y) + ", " + STR(z) + ")";
}
static const Vector3 Zero;
static const Vector3 UnitX;
static const Vector3 UnitY;
static const Vector3 UnitZ;
static const Vector3 NegUnitX;
static const Vector3 NegUnitY;
static const Vector3 NegUnitZ;
static const Vector3 Infinity;
static const Vector3 NegInfinity;
};
} | 17.782383 | 79 | 0.598485 | [
"vector"
] |
06d9fd84b52eb74dcedd1224d015afe43ac8e758 | 1,636 | h | C | toonz/sources/include/toonz/navigationtags.h | OpenAnimationLibrary/tahoma2d | a1ce875f354b0a5aa2925c3038ed35d730395d2d | [
"BSD-3-Clause"
] | 30 | 2020-05-27T10:18:56.000Z | 2020-09-29T20:36:12.000Z | toonz/sources/include/toonz/navigationtags.h | manongjohn/tahoma | 7a440ac58e6a398aad35e41a2e36616758422742 | [
"BSD-3-Clause"
] | 270 | 2020-09-30T14:23:49.000Z | 2020-11-22T19:17:17.000Z | toonz/sources/include/toonz/navigationtags.h | manongjohn/tahoma | 7a440ac58e6a398aad35e41a2e36616758422742 | [
"BSD-3-Clause"
] | 13 | 2020-06-01T17:10:19.000Z | 2020-09-29T09:28:05.000Z | #pragma once
#ifndef NAVIGATION_TAGS_INCLUDED
#define NAVIGATION_TAGS_INCLUDED
#include "tcommon.h"
#undef DVAPI
#undef DVVAR
#ifdef TOONZLIB_EXPORTS
#define DVAPI DV_EXPORT_API
#define DVVAR DV_EXPORT_VAR
#else
#define DVAPI DV_IMPORT_API
#define DVVAR DV_IMPORT_VAR
#endif
#include <QString>
#include <QColor>
class TOStream;
class TIStream;
class DVAPI NavigationTags {
public:
struct Tag {
int m_frame;
QString m_label;
QColor m_color;
Tag() : m_frame(-1), m_label(), m_color(Qt::magenta) {}
Tag(int frame) : m_frame(frame), m_label(), m_color(Qt::magenta) {}
Tag(int frame, QString label)
: m_frame(frame), m_label(label), m_color(Qt::magenta) {}
Tag(int frame, QString label, QColor color)
: m_frame(frame), m_label(label), m_color(color) {}
~Tag() {}
bool operator<(const Tag &otherTag) const {
return (m_frame < otherTag.m_frame);
}
};
std::vector<Tag> m_tags;
QColor m_lastTagColorUsed;
NavigationTags();
~NavigationTags() {}
std::vector<Tag> getTags() { return m_tags; }
int getCount() const;
Tag getTag(int frame);
void addTag(int frame, QString label = "");
void removeTag(int frame);
void clearTags();
bool isTagged(int frame);
int getPrevTag(int currentFrame);
int getNextTag(int currentFrame);
void moveTag(int fromFrame, int toFrame);
void shiftTags(int startFrame, int shift);
QString getTagLabel(int frame);
void setTagLabel(int frame, QString label);
QColor getTagColor(int frame);
void setTagColor(int frame, QColor color);
void saveData(TOStream &os);
void loadData(TIStream &is);
};
#endif
| 22.108108 | 71 | 0.7011 | [
"vector"
] |
06db7218585364a1c421d5b9f9dd1955acc78ed8 | 244 | h | C | CRIC-IN/src/team.h | ritesh0402/Cricket-Game | 73c8a5645687badad13683791d3740900c649148 | [
"MIT"
] | null | null | null | CRIC-IN/src/team.h | ritesh0402/Cricket-Game | 73c8a5645687badad13683791d3740900c649148 | [
"MIT"
] | null | null | null | CRIC-IN/src/team.h | ritesh0402/Cricket-Game | 73c8a5645687badad13683791d3740900c649148 | [
"MIT"
] | null | null | null | #pragma once
#include <vector>
#include "player.h"
class Team
{
public:
Team();
std::string name;
int totalRunsScored ;
int ballsPlayed ;
int totalBallsBowled ;
int wicketsLost ;
std::vector<Player> players;
};
| 14.352941 | 31 | 0.639344 | [
"vector"
] |
06df102129533fba19caa48734380edd530328d7 | 2,189 | h | C | _thirdPartyLibs/include/GLV/glv_buttons.h | stratosger/glGA-edu | de8d8e72e732921f63ef15cd787899f454787ab0 | [
"BSD-4-Clause-UC"
] | 4 | 2018-08-22T03:43:30.000Z | 2021-03-11T18:20:27.000Z | _thirdPartyLibs/include/GLV/glv_buttons.h | stratosger/glGA-edu | de8d8e72e732921f63ef15cd787899f454787ab0 | [
"BSD-4-Clause-UC"
] | 7 | 2020-10-06T16:34:12.000Z | 2020-12-06T17:29:22.000Z | _thirdPartyLibs/include/GLV/glv_buttons.h | stratosger/glGA-edu | de8d8e72e732921f63ef15cd787899f454787ab0 | [
"BSD-4-Clause-UC"
] | 71 | 2015-03-26T10:28:04.000Z | 2021-11-07T10:09:12.000Z | #ifndef INC_GLV_BUTTONS_H
#define INC_GLV_BUTTONS_H
/* Graphics Library of Views (GLV) - GUI Building Toolkit
See COPYRIGHT file for authors and license information */
#include "glv_core.h"
#include "glv_icon.h"
#include "glv_widget.h"
namespace glv {
/// One or more buttons on a grid
class Buttons : public Widget {
public:
/// @param[in] r geometry
/// @param[in] nx number along x
/// @param[in] ny number along y
/// @param[in] momentary whether the button state matches button press state
/// @param[in] mutExc whether multiple buttons can be on
/// @param[in] on the on state symbol
/// @param[in] off the off state symbol
Buttons(
const Rect& r=Rect(), int nx=1, int ny=1,
bool momentary=false, bool mutExc=false,
SymbolFunc on=draw::rectangle, SymbolFunc off=0
);
/// Get off state symbol
const SymbolFunc& symbolOff() const { return mSymOff; }
/// Get on state symbol
const SymbolFunc& symbolOn () const { return mSymOn; }
/// Set on/off symbols
Buttons& symbol(const SymbolFunc& f){ symbolOff(f); return symbolOn(f); }
/// Set off state symbol
Buttons& symbolOff(const SymbolFunc& f){ mSymOff=f; return *this; }
/// Set on state symbol
Buttons& symbolOn (const SymbolFunc& f){ mSymOn =f; return *this; }
virtual const char * className() const { return "Buttons"; }
virtual void onDraw(GLV& g);
virtual bool onEvent(Event::t e, GLV& g);
bool getValue() const { return Widget::getValue<bool>(); }
bool getValue(int i) const { return Widget::getValue<bool>(i); }
bool getValue(int i1, int i2) const { return Widget::getValue<bool>(i1, i2); }
protected:
SymbolFunc mSymOff, mSymOn; // state symbols
// Icon * mIconOff, mIconOn;
};
/// Single button
class Button : public Buttons {
public:
/// @param[in] r geometry
/// @param[in] momentary whether the button state matches button press state
/// @param[in] on the on state symbol
/// @param[in] off the off state symbol
Button(const Rect& r=Rect(20), bool momentary=false, SymbolFunc on=draw::rectangle, SymbolFunc off=0)
: Buttons(r, 1,1, momentary, false, on, off)
{}
virtual const char * className() const { return "Button"; }
};
} // glv::
#endif
| 27.708861 | 102 | 0.689356 | [
"geometry"
] |
06e41018d72bc8394fb6a18071e223bdc41101e9 | 2,549 | h | C | Editor/UI/Widgets/Widget_Properties.h | ValtoForks/Directus3D | 32b2c38bdf88e8b3e29010b17c313a26dcd9fbbd | [
"MIT"
] | null | null | null | Editor/UI/Widgets/Widget_Properties.h | ValtoForks/Directus3D | 32b2c38bdf88e8b3e29010b17c313a26dcd9fbbd | [
"MIT"
] | null | null | null | Editor/UI/Widgets/Widget_Properties.h | ValtoForks/Directus3D | 32b2c38bdf88e8b3e29010b17c313a26dcd9fbbd | [
"MIT"
] | null | null | null | /*
Copyright(c) 2016-2018 Panos Karabelas
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.
*/
#pragma once
//= INCLUDES ======
#include "Widget.h"
#include <memory>
//=================
namespace Directus
{
class Actor;
class Transform;
class Light;
class Renderable;
class RigidBody;
class Collider;
class Constraint;
class Material;
class Camera;
class AudioSource;
class AudioListener;
class Script;
class IComponent;
}
class Widget_Properties : public Widget
{
public:
Widget_Properties(Directus::Context* context);
void Tick(float deltaTime) override;
static void Inspect(std::weak_ptr<Directus::Actor> actor);
static void Inspect(std::weak_ptr<Directus::Material> material);
private:
void ShowTransform(std::shared_ptr<Directus::Transform>& transform);
void ShowLight(std::shared_ptr<Directus::Light>& light);
void ShowRenderable(std::shared_ptr<Directus::Renderable>& renderable);
void ShowRigidBody(std::shared_ptr<Directus::RigidBody>& rigidBody);
void ShowCollider(std::shared_ptr<Directus::Collider>& collider);
void ShowConstraint(std::shared_ptr<Directus::Constraint>& constraint);
void ShowMaterial(std::shared_ptr<Directus::Material>& material);
void ShowCamera(std::shared_ptr<Directus::Camera>& camera);
void ShowAudioSource(std::shared_ptr<Directus::AudioSource>& audioSource);
void ShowAudioListener(std::shared_ptr<Directus::AudioListener>& audioListener);
void ShowScript(std::shared_ptr<Directus::Script>& script);
void ShowAddComponentButton();
void ComponentContextMenu_Add();
void Drop_AutoAddComponents();
};
| 35.402778 | 81 | 0.781875 | [
"transform"
] |
06fe52e5340cbea857603fa8f91b1b383dd67ce9 | 11,123 | h | C | trunk/libs/angsys/include/ang/collections/array.h | ChuyX3/angsys | 89b2eaee866bcfd11e66efda49b38acc7468c780 | [
"Apache-2.0"
] | null | null | null | trunk/libs/angsys/include/ang/collections/array.h | ChuyX3/angsys | 89b2eaee866bcfd11e66efda49b38acc7468c780 | [
"Apache-2.0"
] | null | null | null | trunk/libs/angsys/include/ang/collections/array.h | ChuyX3/angsys | 89b2eaee866bcfd11e66efda49b38acc7468c780 | [
"Apache-2.0"
] | null | null | null | /*********************************************************************************************************************/
/* File Name: ang/collections/array.h */
/* Author: Ing. Jesus Rocha <chuyangel.rm@gmail.com>, July 2016. */
/* File description: this file is exposes many native types and wrappers for them as well as useful macros. */
/* */
/* Copyright (C) angsys, Jesus Angel Rocha Morales */
/* You may opt to use, copy, modify, merge, publish and/or distribute copies of the Software, and permit persons */
/* to whom the Software is furnished to do so. */
/* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. */
/* */
/*********************************************************************************************************************/
#ifndef __ANG_COLLECTIONS_H__
#elif !defined __ANG_COLLECTIONS_ARRAY_H__
#define __ANG_COLLECTIONS_ARRAY_H__
namespace ang
{
template<typename T>
struct smart_ptr_type<T[], false, false> {
static constexpr ang::smart_type smart_type = ang::smart_type::none;
using smart_ptr_t = smart_array<T>;
using type = collections::array_buffer<T>;
};
template<typename T, wsize N>
struct smart_ptr_type<T[N], false, false> {
static constexpr ang::smart_type smart_type = ang::smart_type::none;
using smart_ptr_t = smart_array<T>;
using type = collections::array_buffer<T>;
};
template<typename T, template<typename>class A>
struct smart_ptr_type<array<T, A>, false, false> {
static constexpr ang::smart_type smart_type = ang::smart_type::none;
using smart_ptr_t = smart_array<T>;
using type = collections::array_buffer<T, A>;
};
namespace collections
{
/******************************************************************/
/* template class array_buffer : */
/* -> implements the memory buffer of an array object */
/******************************************************************/
template<typename T, template<typename> class A>
class array_buffer final
: public implement<array_buffer<T, A>
, iid("ang::collections::array")
, ivariable
, ibuffer
, ibuffer_view
, iarray<T>
, ifinder<T>
, ienum<T>>
, public array<typename auto_type<T>::type, A>
{
public:
static_assert(!is_const<T>::value, "T is constant type");
using element_type = typename auto_type<T>::type;
using type = element_type *;
using const_type = element_type const*;
using iarray_t = iarray<T>;
using ienum_type = ienum<T>;
using base_iterator_t = collections::base_iterator<T>;
using iterator_t = collections::iterator<T>;
using const_iterator_t = collections::const_iterator<T>;
using forward_iterator_t = collections::forward_iterator<T>;
using const_forward_iterator_t = collections::const_forward_iterator<T>;
using backward_iterator_t = collections::backward_iterator<T>;
using const_backward_iterator_t = collections::const_backward_iterator<T>;
public:
array_buffer();
array_buffer(const ang::nullptr_t&);
array_buffer(wsize sz);
array_buffer(array<element_type, A> && ar);
array_buffer(array<element_type, A> const& ar);
array_buffer(array_buffer&& ar);
array_buffer(const array_buffer& ar);
array_buffer(const ienum_ptr<T>& store);
template<typename T2>
array_buffer(ang::initializer_list<T2> list);
template<typename T2>
array_buffer(array_view<T2> const&);
template<typename IT>
array_buffer(IT first, IT last);
private:
virtual ~array_buffer();
public: /*methods*/
using array::copy;
template<typename T2> void copy(ienum_ptr<T2> const&);
protected: //overrides
void dispose()override;
private: /*ivariable overrides*/
rtti_t const& value_type()const override;
bool set_value(rtti_t const&, unknown_t)override;
bool get_value(rtti_t const&, unknown_t)const override;
variant clone()const override;
public: /*ivariable overrides*/
string to_string()const override;
string to_string(text::text_format_t)const override;
private: /*ibuffer overrides*/
bool is_readonly()const override;
text::encoding_t encoding()const override;
pointer buffer_ptr() override;
const_pointer buffer_ptr()const override;
wsize buffer_size()const override;
wsize mem_copy(wsize, pointer, text::encoding_t = text::encoding::binary) override;
ibuffer_view_t map_buffer(windex, wsize) override;
bool unmap_buffer(ibuffer_view_t&, wsize) override;
bool can_realloc_buffer()const override;
bool realloc_buffer(wsize) override;
public: //ienum overrides
wsize counter()const override;
typename auto_type<T>::return_type at(base_iterator_t const&) override;
bool increase(base_iterator_t&)const override;
bool increase(base_iterator_t&, int offset)const override;
bool decrease(base_iterator_t&)const override;
bool decrease(base_iterator_t&, int offset)const override;
forward_iterator_t begin() override;
forward_iterator_t end() override;
const_forward_iterator_t begin()const override;
const_forward_iterator_t end()const override;
forward_iterator_t last() override;
const_forward_iterator_t last()const override;
backward_iterator_t rbegin() override;
backward_iterator_t rend() override;
const_backward_iterator_t rbegin()const override;
const_backward_iterator_t rend()const override;
iterator_t find(function<bool(typename auto_type<T>::arg_type const&)>, bool invert = false)const override;
iterator_t find(function<bool(typename auto_type<T>::arg_type const&)>, base_iterator_t next_to, bool invert = false)const override;
ienum_ptr<T> find_all(function<bool(typename auto_type<T>::arg_type const&)>)const override;
public: //iarray overrides
iterator_t at(windex) override;
const_iterator_t at(windex)const override;
void copy(const ienum_ptr<T>&) override;
private:
ienum_ptr<T> items()const override;
};
}//collections
/******************************************************************/
/* template class ang::object_wrapper<array_buffer> : */
/* -> specialization of object_wrapper<array_buffer> -> array */
/******************************************************************/
template<typename T, template<typename> class A>
class object_wrapper<collections::array_buffer<T, A>>
{
public:
typedef collections::array_buffer<T, A> type;
typedef typename collections::array_buffer<T, A>::type data_type;
typedef typename collections::array_buffer<T, A>::element_type element_type;
private:
collections::array_buffer<T, A>* m_ptr;
public:
object_wrapper();
object_wrapper(type* ar);
object_wrapper(object_wrapper &&);
object_wrapper(object_wrapper const&);
object_wrapper(const ang::nullptr_t&);
object_wrapper(data_type arr, wsize sz);
object_wrapper(wsize sz);
object_wrapper(array<typename collections::auto_type<T>::type, A> && ar);
object_wrapper(array<typename collections::auto_type<T>::type, A> const& ar);
object_wrapper(const collections::ienum_ptr<T>& store);
template<typename T2>
object_wrapper(ang::initializer_list<T2> list)
: m_ptr(null) {
set(new type(ang::forward<ang::initializer_list<T2>>(list)));
}
template<typename T2>
object_wrapper(array_view<T2> const& ar)
: m_ptr(null) {
set(new type(ar));
}
template<typename T2, wsize N>
object_wrapper(T2(&ar)[N])
: m_ptr(null) {
set(new type(ang::to_array(ang::forward<T2(&)[N]>(ar))));
}
~object_wrapper();
public:
void reset();
void reset_unsafe();
bool is_empty()const;
collections::array_buffer<T, A>* get(void)const;
void set(collections::array_buffer<T, A>*);
collections::array_buffer<T, A>** addres_of(void);
collections::forward_iterator<T> begin() { return m_ptr ? m_ptr->begin() : collections::iterator<T>(); }
collections::forward_iterator<T> end() { return m_ptr ? m_ptr->end() : collections::iterator<T>(); }
collections::forward_iterator<const T> begin()const { return m_ptr ? m_ptr->begin() : collections::iterator<const T>(); }
collections::forward_iterator<const T> end()const { return m_ptr ? m_ptr->end() : collections::iterator<const T>(); }
public:
object_wrapper& operator = (collections::array_buffer<T, A>*);
object_wrapper& operator = (const ang::nullptr_t&);
object_wrapper& operator = (object_wrapper &&);
object_wrapper& operator = (object_wrapper const&);
template<wsize N>
object_wrapper& operator = (typename collections::auto_type<T>::type(&ar)[N]) {
if (is_empty())
set(new collections::array_buffer<T, A>(ang::to_array(ang::forward<typename collections::auto_type<T>::type(&)[N]>(ar))));
else
get()->copy(ang::to_array(ang::forward<typename collections::auto_type<T>::type(&)[N]>(ar)));
return *this;
}
template<typename T2>
object_wrapper& operator = (collections::ienum_ptr<T2> const items) {
if (is_empty())
set(new collections::array_buffer<T, A>());
get()->copy(items);
return *this;
}
object_wrapper_ptr<collections::array_buffer<T, A>> operator & (void);
collections::array_buffer<T, A> * operator -> (void)const;
explicit operator collections::array_buffer<T, A> * (void);
explicit operator collections::array_buffer<T, A> const* (void)const;
operator array_view<T>()const { return m_ptr ? to_array((T*)m_ptr->begin(), (T*)m_ptr->end()) : array_view<T>(); }
operator array_view<const T>()const { return m_ptr ? to_array((const T*)m_ptr->begin(), m_ptr->end()) : array_view<T>(); }
template<typename I>typename collections::auto_type<T>::type& operator[](I const& idx);
template<typename I>typename collections::auto_type<T>::type const& operator[](I const& idx)const;
};
template<typename T, template<typename>class A>
struct property_helper<smart_array<T,A>, smart_type::none> {
using type = smart_array<T, A>;
using ret_type = type&;
using ptr_type = collections::array_buffer<T, A>*;
using arg_type = array_view<T>;
using property_class = base_property;
using getter_type = ret_type(*)(property_class const*);
using setter_type = void(*)(property_class*, arg_type);
};
template<typename T, template<typename>class A>
struct property_helper<const smart_array<T, A>, smart_type::none> {
using type = smart_array<T, A>;
using ret_type = array_view<const T>;
using ptr_type = collections::array_buffer<T,A>*;
using arg_type = array_view<T>;
using property_class = base_property;
using getter_type = ret_type(*)(property_class const*);
using setter_type = void(*)(property_class*, arg_type);
};
}//ang
#endif //__ANG_COLLECTIONS_ITERATORS_H__
| 41.349442 | 135 | 0.65459 | [
"object"
] |
660188b27326499d11933e15edb0ef0b1660cb6a | 2,323 | c | C | gurba/lib/domains/nokicliffs/lib/properties.c | DEFCON-MUD/defcon-28-mud-source | b25b5bd15fee6a4acda5119ea864bde4dff62714 | [
"Unlicense"
] | 4 | 2021-07-21T17:49:01.000Z | 2022-03-11T20:50:59.000Z | gurba/lib/domains/nokicliffs/lib/properties.c | DEFCON-MUD/defcon-28-mud-source | b25b5bd15fee6a4acda5119ea864bde4dff62714 | [
"Unlicense"
] | null | null | null | gurba/lib/domains/nokicliffs/lib/properties.c | DEFCON-MUD/defcon-28-mud-source | b25b5bd15fee6a4acda5119ea864bde4dff62714 | [
"Unlicense"
] | 1 | 2021-12-31T00:55:05.000Z | 2021-12-31T00:55:05.000Z | #include "../domain.h"
inherit "/sys/lib/modules/m_properties";
#define PROPERTIES_LOG NOKICLIFFS_LOG_DIR + "/properties.log"
static mapping tmp_properties;
static string properties_file_name;
static int was_warning;
int query_was_warning(void) {
return was_warning;
}
private void init_tmp_properties(void) {
if (!tmp_properties) {
tmp_properties = ([ ]);
}
}
private void properties_warn(string warning) {
was_warning = 1;
write_file(PROPERTIES_LOG,
ctime(time()) + ":" +
properties_file_name + ": "
+ warning + "\n");
}
private void read_property_line(string property_line, int line) {
string key, val;
int parse_results;
if (empty_str(property_line) || property_line[0] == '#') {
return;
}
parse_results = sscanf(property_line, "%s=%s", key, val);
if (parse_results == 2) {
if (property(key)) {
properties_warn("Key from file found in object: " + key);
}
if (member_map(key, tmp_properties)) {
properties_warn("Key from file found in file: " + key);
}
tmp_properties[key] = val;
return;
}
properties_warn("Invalid line: " + line);
}
private void load_tmp_properties(void) {
string *keys;
int i, dim;
keys = map_indices(tmp_properties);
dim = sizeof(keys);
for (i = 0; i < dim; i++) {
set_property(keys[i], tmp_properties[keys[i]]);
}
}
/* set_property_file() is nomasked anyway. */
int load_properties(string file_name) {
string *lines;
int i, dim;
if (empty_str(file_name)) {
return -1;
}
properties_file_name = file_name;
if (file_exists(file_name) < 1) {
return -2;
}
was_warning = 0;
tmp_properties = ([ ]);
dim = file_size(properties_file_name);
lines = explode(read_file(properties_file_name, 0, dim), "\n");
dim = sizeof(lines);
for (i = 0; i < dim; i++) {
read_property_line(lines[i], (i + 1));
}
load_tmp_properties();
return 1;
}
int write_properties(string file_name) {
string *keys;
int i, dim;
if (empty_str(file_name)) {
return -1;
}
keys = map_indices(properties);
dim = sizeof(keys);
for (i = 0; i < dim; i++) {
write_file(file_name, keys[i] + "=" +
property(keys[i]) + "\n");
}
return 1;
}
| 22.12381 | 66 | 0.609557 | [
"object"
] |
66086ba32f47cdb0752a4816cbd604d855875ad6 | 1,538 | h | C | PhysLib/particle.h | oldpocket/SciCpp | 2d7bbd552566b08b776fc682a59286931ba1abe2 | [
"MIT"
] | null | null | null | PhysLib/particle.h | oldpocket/SciCpp | 2d7bbd552566b08b776fc682a59286931ba1abe2 | [
"MIT"
] | null | null | null | PhysLib/particle.h | oldpocket/SciCpp | 2d7bbd552566b08b776fc682a59286931ba1abe2 | [
"MIT"
] | null | null | null | /****************************************************************
* File: mass.h
* Description: Represents a Particle, to be used in physics simulations
* Author: Fabio Andreozzi Godoy
* Date: 01/02/2006 - Modified: 24/06/2006
*/
#ifndef PARTICLE_H_INCLUDED
#define PARTICLE_H_INCLUDED
#include "../Util/general.h"
#include "../MathLib/vector_3d.h"
// class Particle discribe a simple particle (or object)
template <class T> class Particle {
private:
T m; // The mass value
T e; // Energy of the mass
T q; // The charge value (integer multiple of 'e')
public:
// Constructor
Particle(T m_, T e_, T q_) {
this->m = m_;
this->e = e_;
this->q = q_;
pos = Vector3D<T>();
vel = Vector3D<T>();
force = Vector3D<T>();
init();
}
// Access (read and write) to private members
void M(T m_) { m = m_; } // Set a value to the mass
T M() { return m; } // Return the value of the mass
void E(T e_) { e = e_; } // Set a value to the energy of the particle
T E() { return e; } // Return the energy of the mass
void Q(T q_) { q = q_; } // Set a value to the charge of the particle
T Q() { return q; } // Return the value of the charge
Vector3D<T> pos; // Position in space
Vector3D<T> vel; // Velocity
Vector3D<T> force; // Force applied on this mass at an instance
// Sets the force values to zero
void init() { force.set(.0f, .0f, .0f); }
};
#endif // PARTICLE_H_INCLUDED
| 30.76 | 76 | 0.564369 | [
"object"
] |
6609162fc0395478e9e2f2b2c4f6d7ec0af80eb4 | 18,675 | h | C | include/nsepisod/nsclasser.h | prometheusorg/epiClassifier | 8f3a41e1f68f713fcbcd6372d77ac6a0ed1d3347 | [
"Apache-2.0"
] | 3 | 2017-05-22T14:57:13.000Z | 2018-02-08T15:47:37.000Z | include/nsepisod/nsclasser.h | prometheusorg/epiClassifier | 8f3a41e1f68f713fcbcd6372d77ac6a0ed1d3347 | [
"Apache-2.0"
] | 13 | 2017-01-24T16:28:22.000Z | 2018-01-22T00:12:50.000Z | include/nsepisod/nsclasser.h | prometheusorg/epiClassifier | 8f3a41e1f68f713fcbcd6372d77ac6a0ed1d3347 | [
"Apache-2.0"
] | null | null | null | // --------------------------------------------------------------------------
// NSCLASSER.H
// --------------------------------------------------------------------------
// Fabrice LE PERRU - Aout 2001
// source : Remi SPAAK - Mai 1997
// --------------------------------------------------------------------------
#if !defined(__NSCLASSER_H__)
#define __NSCLASSER_H__
class ParseElem;
class ParseElemArray;
class NSEpiFlechiesDB;
//class NVLdVTemps;
class NSThesaurus;
class NSThesaurusInfo;
class NSPatholog;
class NSPhraseur;
class NsProposition;
class NSGenerateurFr;
class NSEpiClassifInfoArray;
class NSEpiClassifInfo;
class NSEpiClassif;
class VectString;
class NSPathologData;
#include "partage/nsvector.h"
#ifndef _ENTERPRISE_DLL
#include <owl\edit.h>
#include "partage\nsglobal.h"
#include "nsepisod/eptables.h"
#else
#include "enterpriseLus/nsglobalLus.h"
using namespace std;
// #include "enterpriseLus/nsglobalLus.h"
#endif
#ifndef __linux__
# if defined(_EPISODUSDLL)
# define _EPISODUS __export
# else
# define _EPISODUS __import
# endif
#endif
enum INDBLEVEL { INDBdatabaseError = 1, INDBnotAtAll, INDBasABegining, INDBcompleteTerm };
#ifndef __linux__
class _EPISODUS Classify : public NSRoot
#else
class Classify : public NSRoot
#endif
{
public:
Classify(NSContexte* pCtx, string* psClassif, string* psConcept, string* psPath);
~Classify();
void computeParsing( string *psClassifResultO,
string *psClassifResultP,
string *psClassifResultI);
void searchTermsInLexique(string *sLibelle, string *psClassifResultO, string *psClassifResultP, std::string *psClassifResultI);
vector<string *> *Purge(string *sLibelle);
bool findInLexiq(string s2Find);
string getCodeLexiq(string s2Find);
ParseElem *findGroup(ParseElem *pElem, ParseElemArray *pArray);
protected:
std::string pResultCodeClassif;
std::string *psClassification; // Classification
std::string *psSOAPChemin;
std::string *psSOAP2Parse;
std::string *psResultParsing;
std::string *pElement;
std::string *pChemin;
};
#ifndef __linux__
class _EPISODUS ParseSOAP : public NSRoot
#else
class ParseSOAP : public NSRoot
#endif
{
public:
ParseSOAP(NSContexte* pCtx, string *sClassifier);
~ParseSOAP();
void ChangeSOAPEdit(std::string *psSOAPEdit);
bool ParsingEq();
std::string *getLibelleParsing();
std::string *getCodeParsing();
void ConvertitMajuscule(char* chaine);
std::string ConvertitMajuscule(string sChaine);
void computeParsing( std::string *sLibelle,
std::string *sChemin,
std::string *psClassifResultO,
std::string *psClassifResultP,
std::string *psClassifResultI,
std::string *psClassifResult3);
bool computeParsingElem( std::string *sLibelle,
std::string *sChemin,
std::string *psClassifResultO,
std::string *psClassifResultP,
std::string *psClassifResultI,
std::string *psClassifResult3);
void searchTermsInLexique(std::string *sLibelle, std::string *psClassifResultO, std::string *psClassifResultP, std::string *psClassifResultI, std::string *psClassifResult3, bool bUse3BT = true);
vector<string *>* Purge(string *sLibelle);
void initParseElemArray(string* psLibelle, ParseElemArray* pParseResult);
void initGroupElemArray(ParseElemArray* pLoneWords, ParseElemArray* pGroups);
void cleanGroupElemArray(ParseElemArray* pGroups);
bool findInLexiq(string s2Find, NSEpiFlechiesDB* pFlechies = 0, INDBLEVEL* pLevel = 0);
string getCodeLexiq(string s2Find);
ParseElem* findLargerGroup(ParseElem *pElem, ParseElemArray *pArray, NSEpiFlechiesDB* pFlechies = 0);
void addAllGroups(ParseElemArray *pLoneArray, ParseElemArray *pGroupArray, NSEpiFlechiesDB* pFlechies = 0);
protected:
string pResultCodeClassif;
string *psClassifier; // Classification
string *psSOAPChemin;
string *psSOAP2Parse;
string *psResultParsing;
NSPatholog *pPatho;
};
class ElemSet;
class ElemSetArray;
typedef vector<string *> pstringVector;
typedef pstringVector::iterator pstringIterator;
#ifndef __linux__
class _EPISODUS ParseCategory
#else
class ParseCategory
#endif
{
public:
// ParseCategory(string sObligatoire, string sPossible, string sInterdit);
ParseCategory(int nb, string label, string pattern);
~ParseCategory();
void DefObligatoire(string sDefine);
void DefObligatoire(ElemSetArray *pElemSetArray);
void DefPossible(string sDefine);
void DefPossible(ElemSetArray *pElemSetArray);
void DefInterdit(string sDefine);
void DefInterdit(ElemSetArray *pElemSetArray);
void Def3BT(string sDefine);
void Def3BT(ElemSetArray *pElemSetArray);
void DefCritere(string sDefO, string sDefP, string sDefI, string sDef3);
ElemSetArray *DefDomain(string sDomain);
ElemSetArray *getObligatoireDomain() { return pDomainObligatoire; }
string getsObligatoire() { return sObligatoire; }
ElemSetArray *getPossibleDomain() { return pDomainPossible; }
string getsPossible() { return sPossible; }
ElemSetArray *getInterditDomain() { return pDomainInterdit; }
string getsInterdit() { return sInterdit; }
ElemSetArray *get3btDomain() { return pDomain3BT; }
string get3BT() { return s3BT; }
vector<string *> *getPattern() { return psPattern; }
protected:
int nbDigit;
string sLabel;
vector<string *> *psPattern;
string sObligatoire;
ElemSetArray *pDomainObligatoire;
string sPossible;
ElemSetArray *pDomainPossible;
string sInterdit;
ElemSetArray *pDomainInterdit;
string s3BT;
ElemSetArray *pDomain3BT;
};
//
// Represente un element de classification ou un intervalle
//
#ifndef __linux__
class _EPISODUS ElemSet
#else
class ElemSet
#endif
{
private:
static long lObjectCount;
public:
ElemSet(string sElem);
ElemSet(string sElemBegin, string sElemEnd);
ElemSet(string sElemBegin, string sElemEnd, bool bElemEmpty);
ElemSet(ElemSet& rv);
~ElemSet() { lObjectCount--; };
// int CountJoker(string sElem);
// ElemSetArray *ComputeJoker(vector<string *> *psPattern);
void ComputeJoker(vector<string *> psPattern, ElemSetArray *pElemSetResult);
// void ComputeJokerInterval();
// void ReplaceJoker(string sBorn, string s2Replace);
bool HasJoker();
string getBegin() { return sBegin; }
void setBegin(string s2Replace) { sBegin = s2Replace; }
string getEnd() { return sEnd; };
void setEnd(string s2Replace) { sEnd = s2Replace; }
bool isEmptySet() { return bEmptySet; }
void setEmptySet(bool b2Replace) { bEmptySet = b2Replace; }
string toString();
bool intersect(ElemSet *pElem);
ElemSet *Smaller(ElemSet* pElem);
ElemSetArray *inter(ElemSetArray *Elems);
ElemSetArray *minus(ElemSet *pElem);
void ComputeUnion(ElemSetArray *pElems);
bool doesContain(string sCode);
void reorder();
ElemSet& operator=(ElemSet src);
bool operator==(ElemSet src);
static long getNbInstance() { return lObjectCount; }
static void initNbInstance() { lObjectCount = 0; }
protected:
string sBegin;
string sEnd;
bool bEmptySet;
};
typedef vector<ElemSet*> ElemSetVector;
typedef ElemSetVector::iterator ElemSetIterator;
//
// Represente un ensemble d'elements ou d'intervalles
//
#ifndef __linux__
class _EPISODUS ElemSetArray : public ElemSetVector
#else
class ElemSetArray : public ElemSetVector
#endif
{
private:
static long lObjectCount;
public:
ElemSetArray() : ElemSetVector() { lObjectCount++; };
ElemSetArray(string sDomaine);
~ElemSetArray();
ElemSetArray(ElemSetArray& rv);
ElemSetArray *ComputeIntersection(ElemSetArray *pElems);
void ComputeUnion();
void minus(ElemSet *pTerm);
void minus(ElemSetArray *pTerms);
void print(char *);
string toString();
bool isEmpty();
bool doesContain(string sCode);
void vider();
ElemSetArray& operator=(ElemSetArray src);
static long getNbInstance() { return lObjectCount; }
static void initNbInstance() { lObjectCount = 0; }
};
typedef vector<ParseCategory *> ParseCategoryVector;
typedef ParseCategoryVector::iterator ParseCategoryIterator;
#ifndef __linux__
class _EPISODUS TermsParser : public ParseCategoryVector, public NSRoot
#else
class TermsParser : public ParseCategoryVector, public NSRoot
#endif
{
private:
static long lObjectCount;
public:
TermsParser(NSContexte* pCtx, string sClassif, bool bUse3bt = true);
~TermsParser();
ElemSetArray *Compute();
ElemSetArray *ComputeWithPIntersection();
ElemSetArray *ComputeWithPUnion();
ElemSetArray *Compute(ParseElemArray *);
ElemSetArray *ComputeWithPIntersection(ParseElemArray *);
ElemSetArray *ComputeWithPUnion(ParseElemArray *);
bool ComputeElements(ParseElemArray *);
#ifndef _ENTERPRISE_DLL
bool FindClinicalTerm(NSThesaurus *pClinicalBase, string* pElement);
string FindAllClinicalTermsStartingWith(NSThesaurus *pClinicalBase, string* pElement, string sClassif);
string FindAllSentinelTermsStartingWith(NSThesaurus *pClinicalBase, string* pElement, string sClassif);
bool FindFlexClinicalTerm(NSThesaurus *pClinicalBase, string* pLexiqueCode);
#else
bool FindClinicalTerm(NSThesaurusInfo *pClinicalBase, string* pElement);
string FindAllClinicalTermsStartingWith(NSThesaurusInfo *pClinicalBase, string* pElement, string sClassif);
string FindAllSentinelTermsStartingWith(NSThesaurusInfo *pClinicalBase, string* pElement, string sClassif);
bool FindFlexClinicalTerm(NSThesaurusInfo *pClinicalBase, string* pLexiqueCode);
#endif
void ComputePUnion();
void ComputePIntersection();
void ComputeIUnion();
void ComputeOIntersection();
void Compute3btIntersection();
void CheckI(ElemSetArray *pResult);
string getsObligatoire() { return pObligatoire->toString(); }
string getsPossible() { return pPossible->toString(); }
string getsInterdit() { return pInterdit->toString(); }
void vider();
string sBasicOnlyAddNewcodes(string sExistingSet, string incomingSet);
static long getNbInstance() { return lObjectCount; }
static void initNbInstance() { lObjectCount = 0; }
protected:
string sClassification;
ElemSetArray *pObligatoire;
ElemSetArray *pPossible;
ElemSetArray *pInterdit;
bool _bUse3bt;
};
#ifndef __linux__
class _EPISODUS NSEpiFlechiesDB : public NSRoot
#else
class NSEpiFlechiesDB : public NSRoot
#endif
{
public:
NSEpiFlechiesDB(NSContexte* pCtx);
~NSEpiFlechiesDB();
#ifndef _ENTERPRISE_DLL
void CreateDatabaseFlechies(bool* pContinuer = 0, OWL::TEdit* pAffichage = 0);
void rempliDatabase(NSPathologData *pDonnees);
#endif
bool traiteFormeFlechie(string sAvant, string sApres, string sCode, int iDep = 0);
bool rempliDatabaseFlechies(string sLibelle, string sCode);
bool findElem(string sLibelle, string sCode);
bool isInDB(string *sLibelle, INDBLEVEL* pLevel = 0);
bool isInDB(string *sLibelle, char cTypeCode);
string getCodeLexiq(string sLibelle);
string getCodeLexiq(string sLibelle, char cTypeCode);
bool getAllLabelsForCode(string sCode, VectString *pLabels);
void ConvertitMajuscule(char* chaine);
string ConvertitMajuscule(string sChaine);
string getCodeSens(string sLibelle);
void incrementeIdCpt();
private:
NSPatholog* pPatho;
NSPhraseur* pPhraseur;
NsProposition* pPropos;
NSGenerateurFr* pGenFR;
string sIdCpt;
};
#ifndef __linux__
class _EPISODUS ParseElem
#else
class ParseElem
#endif
{
private:
static long lObjectCount;
public:
ParseElem(string sElem) { lObjectCount++; sContent = sElem; bNotInFirst = false; nbOfTerms = 1; iPos = 0; }
ParseElem(string sElem, int nbTerms, int Pos) { lObjectCount++; sContent = sElem; bNotInFirst = false; nbOfTerms = nbTerms; iPos = Pos; }
ParseElem(ParseElem& rv);
~ParseElem() { lObjectCount--; };
ParseElem& operator=(ParseElem src);
bool getNotInFirst() { return bNotInFirst; }
void setNotInFirst(bool bValue) { bNotInFirst = bValue; }
string getContent() { return sContent; }
int getNbOfTerms() { return nbOfTerms; }
void setNbOfTerms(int i) { nbOfTerms = i; }
int getPos() { return iPos; }
void setPos(int Pos) { iPos = Pos; }
static long getNbInstance() { return lObjectCount; }
static void initNbInstance() { lObjectCount = 0; }
protected:
bool bNotInFirst;
string sContent;
int nbOfTerms;
int iPos;
};
typedef vector<ParseElem *> ParseElemVector;
typedef ParseElemVector::iterator ParseElemIter;
#ifndef __linux__
class _EPISODUS ParseElemArray : public ParseElemVector
#else
class ParseElemArray : public ParseElemVector
#endif
{
private:
static long lObjectCount;
public:
ParseElemArray() { lObjectCount++; };
ParseElemArray(vector<string *> *pList);
ParseElemArray(ParseElemArray& rv);
~ParseElemArray();
void vider();
void setAllPos();
ParseElemArray& operator=(ParseElemArray src);
static long getNbInstance() { return lObjectCount; }
static void initNbInstance() { lObjectCount = 0; }
};
#ifndef __linux__
class _EPISODUS ClassifElem
#else
class ClassifElem
#endif
{
private:
static long lObjectCount;
string sCode;
string sLibelle;
public:
ClassifElem(string s2Code, string s2Libelle) { lObjectCount++; sCode = s2Code; sLibelle = s2Libelle; }
~ClassifElem() { lObjectCount--; }
string getCode();
string getLibelle() { return sLibelle; }
static long getNbInstance() { return lObjectCount; }
static void initNbInstance() { lObjectCount = 0; }
};
typedef vector<ClassifElem *> ClassifElemVector;
typedef ClassifElemVector::iterator ClassifElemIter;
#ifndef __linux__
class _EPISODUS ClassifElemArray : public ClassifElemVector
#else
class ClassifElemArray : public ClassifElemVector
#endif
{
private:
static long lObjectCount;
public:
ClassifElemArray() { lObjectCount++; }
~ClassifElemArray();
void vider();
static long getNbInstance() { return lObjectCount; }
static void initNbInstance() { lObjectCount = 0; }
};
#ifndef __linux__
class _EPISODUS NSEpiClassifDB : public NSRoot
#else
class NSEpiClassifDB : public NSRoot
#endif
{
public:
NSEpiClassifDB(NSContexte* pCtx);
~NSEpiClassifDB();
// rempli la table avec les codes CISP
void rempliClassifCISP(string sFileCISP);
void rempliClassifCIM(string sFileCIM);
void searchDomainInClassif(string sClassification, ElemSetArray *pDomain, NSEpiClassifInfoArray *pArrayClassif);
// cette methode doit a partir d'un domaine ajouter a l'array pArrayClassif (s'ils n'y sont pas deja)
// les NSEpiClassifInfo des codes contenus dans le pDomain, en verifiant qu'ils existent dans classif.db
// d'ou array de NSepiClassifInfo
bool searchCode(string sClassification, string sCode, NSEpiClassifInfo *pClassifInfo);
private:
ClassifElemArray *pChap;
ClassifElemArray *pLibelle;
};
class SOAPObject;
#ifndef __linux__
class _EPISODUS classifExpert : public NSRoot
#else
class classifExpert : public NSRoot
#endif
{
public:
enum NIVEAU { niveauPreselection = 1, niveauAutorises, niveauTous};
classifExpert(NSContexte* pCtx);
~classifExpert();
string donnePattern(string sClassification);
int donneCodeSize(string sClassification);
void donneInterdits(string sClassification, string sCase,
ElemSetArray *pForbidenDomain);
void donneClassifArray(SOAPObject* pObjet,
NSEpiClassifInfoArray *pArrayClassif,
int iNiveau);
void fillList(string sClassification, ElemSetArray *pDomain,
NSEpiClassifInfoArray *pArrayClassif,
string sCase);
/*string chooseCode(string sClassification, ElemSetArray* pDomain,
string sCase);
string chooseCode(string sClassif, string sDomain, string sCase); */
string chooseCode(SOAPObject* pObjet);
void setDomain(string sClassification, string sDomain, ElemSetArray* pDomain);
/* void setControlString(string* pCtrlData, string sClassification, string sCase,
string sTexteInitial, int iInitialLevel,
NSEpiClassifInfoArray* pArrayClassif,
NVLdVTemps* pTpsDebut, NVLdVTemps* pTpsFin,
string sResult, string sCodeSens = "");*/
/* void setControlString(string* pCtrlData, SOAPObject* pObjet,
int iInitialLevel, NSEpiClassifInfoArray* pArrayClassif,
NVLdVTemps* pTpsDebut, NVLdVTemps* pTpsFin,
string sResult, string sCodeSens = "");*/
void storeControlData(string sCtrlData);
protected:
#ifndef _ENTERPRISE_DLL
NSEpiClassif _DBcurseur;
#endif
};
#endif // __NSCLASSER_H__
| 29.832268 | 212 | 0.648461 | [
"vector"
] |
617736ea6b8a9828b245e9c58fb60d4f61e28fa3 | 735 | h | C | bullet.h | ficusss/Game_BombProtection | 11fac7efb08434b4463855cb2a763ef23e14ca06 | [
"MIT"
] | null | null | null | bullet.h | ficusss/Game_BombProtection | 11fac7efb08434b4463855cb2a763ef23e14ca06 | [
"MIT"
] | null | null | null | bullet.h | ficusss/Game_BombProtection | 11fac7efb08434b4463855cb2a763ef23e14ca06 | [
"MIT"
] | null | null | null | #pragma once
#include "vector.h"
#include "object.h"
#include <memory>
static Vector_t StartBulletSpeed = Vector_t(0, 0.2);
static Vector_t ScaleBullet = Vector_t(0.1, 0.1);
class Bullet_t : public Object_t {
public:
Bullet_t(Vector_t &_position, std::shared_ptr<sf::Texture> texture, Vector_t &_scale = ScaleBullet, Vector_t &_speed = StartBulletSpeed) :
Object_t(texture, _position, _scale, _speed) {};
void update(float time) { position -= speed * time; }
void draw(sf::RenderWindow &window, std::shared_ptr<sf::Texture> texture)
{
sf::Sprite es;
es.setTexture(*texture);
es.setScale((float)scale.getX(), (float)scale.getY());
es.setPosition((float)position.getX(), (float)position.getY());
window.draw(es);
}
}; | 31.956522 | 139 | 0.715646 | [
"object",
"vector"
] |
6179288f33f563fecd85b1bcb5bf4751ecc14cbb | 5,910 | c | C | Script.c | NanolathingStuff/bijective-bzip2-1.0.6 | ea429ae74ec0d9bcf2cc4984522d9c41ce2db93b | [
"bzip2-1.0.6"
] | null | null | null | Script.c | NanolathingStuff/bijective-bzip2-1.0.6 | ea429ae74ec0d9bcf2cc4984522d9c41ce2db93b | [
"bzip2-1.0.6"
] | null | null | null | Script.c | NanolathingStuff/bijective-bzip2-1.0.6 | ea429ae74ec0d9bcf2cc4984522d9c41ce2db93b | [
"bzip2-1.0.6"
] | null | null | null | #include <sys/time.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <libgen.h>
#define SUBDIR "./Test-files/"
#define DEF "bzip2 -k "
#define MINE "./"
#define COMPRESSED ".bz2"
#define NFILES 53
struct timeval tv1, tv2;
struct stat buffer;
///INSERT file names to try here
const char *filenames[1000] = {"Steps.txt", "Sempty.txt", "bij-transform.c","a-bijective.pdf","4.mp3", "r1000", "r5000",
"zeros", "x", "x1", "x2","x3","x4","x5","x6","x7","x8","x9","x10", "tcgen.exe", "tcgen.cpp",
"Galaxy.bmp","Wolf.bmp","Galaxy.eps","Wolf.eps","Galaxy.exr","Wolf.exr","Galaxy.gif","Wolf.gif",
"Galaxy.ico","Wolf.ico","Galaxy.jpg","Wolf.jpg","Galaxy.png","Wolf.png","Galaxy.tga","Wolf.tga",
"Galaxy.tiff","Wolf.tiff","Galaxy.svg","Wolf.svg","Galaxy.wbmp","Wolf.wbmp","test.py","jmock.zip",
"mainwindow.h","Curriculum.docx", "asgal.py","CurrencyConverter.java","detectEventsPaired.py",
"formatSAMPaired.py","HelloWorldServlet.java","SpliceAwareAlignerPaired.cpp"};
int main(){
if( access("results.txt" , F_OK) != -1 ) { //file exists
fprintf(stderr, "File already exist. Replacing;\n"); //replace with new one
remove("results.txt");
}
FILE *file = fopen("results.txt", "w"); //FILE *file = fopen(filename, mode);
fprintf(file, "DEFAULT BZIP2: \t\t\t\t MY IMPLEMENT:\t\t\t\t\t RISPARMIO\n");
char *command1, *command2, *output;
int i = 0, status, size, corr, tmp1 ;
double tmp2, totT = 0.0, totS = 0.0, totC = 0.0, totB = 0.0, totM = 0.0;
/*COPY FROM FOLDER
int src_fd, dst_fd, err, n;
unsigned char buff[4096];
char * src_path, * dst_path;
src_path = SUBDIR;
dst_path = "./";
src_fd = open(src_path, O_RDONLY);
dst_fd = open(dst_path, O_CREAT | O_WRONLY);
////END copy*/
for(i = 0; i < NFILES; i++){ //while()...{
/*copy file
err = read(src_fd, buff, 4096);
if (err == -1) {
printf("Error reading file.\n");
exit(1); }
if (err == 0) break;
n = err;
err = write(dst_fd, buff, n);
if (err == -1) {
printf("Error writing to file.\n");
exit(1);
}*/
/* stuff to do! */
corr = 0;
command1 = malloc(60*sizeof(char));//char command[60]; //string = malloc (60 chars);
command2 = malloc(62*sizeof(char));
output = malloc(30*sizeof(char));
//printf("%s\n", filenames[i]);
strcpy(output, filenames[i]);
strcat(output, COMPRESSED);
//BZIP2
strcpy(command1, DEF);//string = strcat(default, filenames[i])
//strcat(command1, SUBDIR);
strcat(command1, filenames[i]); //strcat(str, "strings ");
gettimeofday(&tv1, NULL);
system(command1);//("bzip2 -k Steps.txt "); //exe
gettimeofday(&tv2, NULL);
//TOT dimension before compression
status = lstat(filenames[i], &buffer);//("Steps.txt.bz2", &buffer);
if(status == 0) {
totB += buffer.st_size;
}else { corr = 1; } //corruption
strcat(command1, COMPRESSED);//string = strcat(default, filenames[i], compressed)
status = stat(output, &buffer);//("Steps.txt.bz2", &buffer);
if(status == 0) {
size = buffer.st_size; // size of file is in member buffer.st_size;
}else { corr = 1; } //corruption
status = remove(output);//("Steps.txt.bz2"); DELETE FILE
if (status != 0) return 1;
if(corr == 0)
fprintf(file, "Total time = %f seconds, size %d \t\t",(double) (tv2.tv_usec - tv1.tv_usec) / 1000000 + (double) (tv2.tv_sec - tv1.tv_sec), size);
else
fprintf(file, "Total time = %f seconds, file corrupted \t\t",(double) (tv2.tv_usec - tv1.tv_usec) / 1000000 + (double) (tv2.tv_sec - tv1.tv_sec));
//printf("%s\n", command1);
free(command1);//free(string)
tmp1 = size;
tmp2 = (double) (tv2.tv_usec - tv1.tv_usec) / 1000000 + (double) (tv2.tv_sec - tv1.tv_sec);
///MY
strcpy(command2, MINE); //string = strcat(mine, default, filenames[i])
strcat(command2, DEF);
//strcat(command2, SUBDIR);
strcat(command2, filenames[i]);
gettimeofday(&tv1, NULL);
system(command2); //("bzip2 -k Steps.txt ");
gettimeofday(&tv2, NULL);
//strcat(command2, COMPRESSED);//string = strcat(mine, default, filenames[i],compressed)
status = stat(output, &buffer); //stat("./Steps.txt.bz2", &buffer);
if(status == 0) {
size = buffer.st_size; // size of file is in member buffer.st_size;
totC += size;
}else { corr = 1; } //corruption
status = remove(output);//("Steps.txt.bz2"); DELETE FILE
if (status != 0) return 1;
if(corr == 0)
fprintf(file, "Total time = %f seconds, size %d \t\t",(double) (tv2.tv_usec - tv1.tv_usec) / 1000000 + (double) (tv2.tv_sec - tv1.tv_sec), size);
else
fprintf(file, "Total time = %f seconds, file corrupted \t\t",(double) (tv2.tv_usec - tv1.tv_usec) / 1000000 + (double) (tv2.tv_sec - tv1.tv_sec));
//printf("%s\n", command2);
free(command2);//free(string)
free(output);
fprintf(file, " Risparmio = %f seconds, %d bytes, percent compression more: %f '%' \n", tmp2 - (double) (tv2.tv_usec - tv1.tv_usec) / 1000000 + (double) (tv2.tv_sec - tv1.tv_sec),
tmp1 - size, ((double)tmp1 - (double)size)*100/tmp1);
totS += (double)tmp1 - (double)size;
totT += tmp2 - (double) (tv2.tv_usec - tv1.tv_usec) / 1000000 + (double) (tv2.tv_sec - tv1.tv_sec);
totM += ((double)tmp1 - (double)size)*100/tmp1;
/*file copyed
close(src_fd);
close(dst_fd);
status = remove(filenames[i]);
if (status != 0) return 1;*/
}
fprintf(file, "\nRisparmio tot = %f seconds, %d bytes \n", totT, (int)totS);
fprintf(file, "compressione media percentuale = %f, in più: %f % \n", (double)(((totB-totC)*100/(totB))), (double)totM/(double)NFILES);
fclose(file);
return 0;
}
| 39.139073 | 183 | 0.601184 | [
"transform"
] |
6194031cf1ba862d79ecd310eb818d5790fe1686 | 4,910 | h | C | corelib/include/rtabmap/core/Odometry.h | nuclearsandwich-ros/rtabmap-release | c6ee39bea83b6a5edf9da3214494d67c6c055a2e | [
"BSD-3-Clause"
] | null | null | null | corelib/include/rtabmap/core/Odometry.h | nuclearsandwich-ros/rtabmap-release | c6ee39bea83b6a5edf9da3214494d67c6c055a2e | [
"BSD-3-Clause"
] | null | null | null | corelib/include/rtabmap/core/Odometry.h | nuclearsandwich-ros/rtabmap-release | c6ee39bea83b6a5edf9da3214494d67c6c055a2e | [
"BSD-3-Clause"
] | null | null | null | /*
Copyright (c) 2010-2016, Mathieu Labbe - IntRoLab - Universite de Sherbrooke
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 Universite de Sherbrooke 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.
*/
#ifndef ODOMETRY_H_
#define ODOMETRY_H_
#include <rtabmap/core/RtabmapExp.h>
#include <rtabmap/core/Transform.h>
#include <rtabmap/core/SensorData.h>
#include <rtabmap/core/Parameters.h>
namespace rtabmap {
class OdometryInfo;
class ParticleFilter;
class RTABMAP_EXP Odometry
{
public:
enum Type {
kTypeUndef = -1,
kTypeF2M = 0,
kTypeF2F = 1,
kTypeFovis = 2,
kTypeViso2 = 3,
kTypeDVO = 4,
kTypeORBSLAM = 5,
kTypeOkvis = 6,
kTypeLOAM = 7,
kTypeMSCKF = 8,
kTypeVINS = 9,
kTypeOpenVINS = 10,
kTypeFLOAM = 11,
kTypeOpen3D = 12
};
public:
static Odometry * create(const ParametersMap & parameters = ParametersMap());
static Odometry * create(Type & type, const ParametersMap & parameters = ParametersMap());
public:
virtual ~Odometry();
Transform process(SensorData & data, OdometryInfo * info = 0);
Transform process(SensorData & data, const Transform & guess, OdometryInfo * info = 0);
virtual void reset(const Transform & initialPose = Transform::getIdentity());
virtual Odometry::Type getType() = 0;
virtual bool canProcessRawImages() const {return false;}
virtual bool canProcessAsyncIMU() const {return false;}
//getters
const Transform & getPose() const {return _pose;}
bool isInfoDataFilled() const {return _fillInfoData;}
RTABMAP_DEPRECATED(const Transform & previousVelocityTransform() const, "Use getVelocityGuess() instead.");
const Transform & getVelocityGuess() const {return velocityGuess_;}
double previousStamp() const {return previousStamp_;}
unsigned int framesProcessed() const {return framesProcessed_;}
bool imagesAlreadyRectified() const {return _imagesAlreadyRectified;}
protected:
const std::map<double, Transform> & imus() const {return imus_;}
private:
virtual Transform computeTransform(SensorData & data, const Transform & guess = Transform(), OdometryInfo * info = 0) = 0;
void initKalmanFilter(const Transform & initialPose = Transform::getIdentity(), float vx=0.0f, float vy=0.0f, float vz=0.0f, float vroll=0.0f, float vpitch=0.0f, float vyaw=0.0f);
void predictKalmanFilter(float dt, float * vx=0, float * vy=0, float * vz=0, float * vroll=0, float * vpitch=0, float * vyaw=0);
void updateKalmanFilter(float & vx, float & vy, float & vz, float & vroll, float & vpitch, float & vyaw);
private:
int _resetCountdown;
bool _force3DoF;
bool _holonomic;
bool guessFromMotion_;
float guessSmoothingDelay_;
int _filteringStrategy;
int _particleSize;
float _particleNoiseT;
float _particleLambdaT;
float _particleNoiseR;
float _particleLambdaR;
bool _fillInfoData;
float _kalmanProcessNoise;
float _kalmanMeasurementNoise;
unsigned int _imageDecimation;
bool _alignWithGround;
bool _publishRAMUsage;
bool _imagesAlreadyRectified;
Transform _pose;
int _resetCurrentCount;
double previousStamp_;
std::list<std::pair<std::vector<float>, double> > previousVelocities_;
Transform velocityGuess_;
Transform imuLastTransform_;
Transform previousGroundTruthPose_;
float distanceTravelled_;
unsigned int framesProcessed_;
std::vector<ParticleFilter *> particleFilters_;
cv::KalmanFilter kalmanFilter_;
StereoCameraModel stereoModel_;
std::vector<CameraModel> models_;
std::map<double, Transform> imus_;
protected:
Odometry(const rtabmap::ParametersMap & parameters);
};
} /* namespace rtabmap */
#endif /* ODOMETRY_H_ */
| 36.37037 | 180 | 0.770265 | [
"vector",
"transform"
] |
61a5a6fa34f40cf07ee25e2c499f02b343b007b0 | 1,298 | h | C | test/testHelpers.h | fsaporito/KVCache | 4d4402396426c1ca25e7fb9ae5f4fb181a0fa1f2 | [
"BSL-1.0"
] | null | null | null | test/testHelpers.h | fsaporito/KVCache | 4d4402396426c1ca25e7fb9ae5f4fb181a0fa1f2 | [
"BSL-1.0"
] | null | null | null | test/testHelpers.h | fsaporito/KVCache | 4d4402396426c1ca25e7fb9ae5f4fb181a0fa1f2 | [
"BSL-1.0"
] | null | null | null | #pragma once
#include <string>
#include <utility>
#include <vector>
namespace TestHelper
{
// This method will generate a longValue of generic, by default of size 0.1 MB
inline std::string generateLongValueOfGivenSize(size_t size = (1024 * 1024) / 10, char value = '0')
{
std::string valueStr;
valueStr.reserve(size);
for (size_t i = 0; i < size; i++)
{
valueStr.push_back(value);
}
return valueStr;
};
inline std::pair<std::vector<std::string>, std::vector<std::string>> generateKVPairs(const size_t sampleNum,
const std::string& keyBaseContent = "Key",
const std::string& valueBaseContent = "Value")
{
std::vector<std::string> keys;
keys.reserve(sampleNum);
std::vector<std::string> values;
values.reserve(sampleNum);
for (size_t i = 0; i < sampleNum; i++)
{
keys.push_back(keyBaseContent + std::to_string(i));
values.push_back(valueBaseContent + std::to_string(i));
}
return std::make_pair(keys, values);
};
} // namespace TestHelper
| 33.282051 | 135 | 0.525424 | [
"vector"
] |
61ac98c76e137120abaa377d16bc686ea569082e | 1,664 | h | C | tf_opt/optimize/mip/inequality_checker.h | google-research/tf-opt | 0704531e1cd85b31e5e07051767f6f9608d090c4 | [
"Apache-2.0"
] | 23 | 2020-10-22T02:35:17.000Z | 2022-03-09T22:01:54.000Z | tf_opt/optimize/mip/inequality_checker.h | google-research/tf-opt | 0704531e1cd85b31e5e07051767f6f9608d090c4 | [
"Apache-2.0"
] | null | null | null | tf_opt/optimize/mip/inequality_checker.h | google-research/tf-opt | 0704531e1cd85b31e5e07051767f6f9608d090c4 | [
"Apache-2.0"
] | 6 | 2021-01-09T20:01:59.000Z | 2022-01-16T12:58:32.000Z | // Copyright 2021 The tf.opt 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.
#ifndef TF_OPT_OPTIMIZE_MIP_INEQUALITY_CHECKER_H_
#define TF_OPT_OPTIMIZE_MIP_INEQUALITY_CHECKER_H_
#include "ortools/linear_solver/linear_expr.h"
#include "ortools/linear_solver/linear_solver.h"
namespace tf_opt {
// Returns the gap between a (one-sided) inequality and the tightest inequality
// modeled by solver with the same coefficients. If negative, this implies that
// the inequality is not valid. This solves a (copy of the) full model and may
// be slow, and it is intended to be used mainly for analysis and debugging.
double ComputeInequalityGap(const operations_research::MPSolver& solver,
const operations_research::LinearRange inequality);
// Returns true if inequality is valid with respect to model in solver. No
// tolerance is used. This solves (a copy of) the full model in the process.
bool CheckValidInequality(const operations_research::MPSolver& solver,
const operations_research::LinearRange inequality);
} // namespace tf_opt
#endif // TF_OPT_OPTIMIZE_MIP_INEQUALITY_CHECKER_H_
| 43.789474 | 79 | 0.760817 | [
"model"
] |
61ad135c5ca167e7b0383f6c2ec6951e074adc19 | 930 | h | C | cudarecv/utils/inc/functional.h | Stanford-NavLab/NAVLab-DPE-SDR | 2420a859be9dfe68df62f6db3f7bbd6f151f2936 | [
"Unlicense"
] | 20 | 2020-06-29T23:13:49.000Z | 2022-02-12T14:11:38.000Z | cudarecv/utils/inc/functional.h | Stanford-NavLab/NAVLab-DPE-SDR | 2420a859be9dfe68df62f6db3f7bbd6f151f2936 | [
"Unlicense"
] | 3 | 2021-03-10T13:32:08.000Z | 2021-03-15T03:06:26.000Z | cudarecv/utils/inc/functional.h | Stanford-NavLab/NAVLab-DPE-SDR | 2420a859be9dfe68df62f6db3f7bbd6f151f2936 | [
"Unlicense"
] | 8 | 2020-07-04T01:54:01.000Z | 2022-03-03T08:22:12.000Z | #ifndef __INC_UTILS_FUNCTIONAL_H_
#define __INC_UTILS_FUNCTIONAL_H_
#include <vector>
#include <numeric>
#include "function_traits.h"
#include "arithmetic.h"
namespace dsp { namespace utils {
struct identity {
template<typename U>
constexpr auto operator()(U&& v) const noexcept
-> decltype(std::forward<U>(v))
{
return std::forward<U>(v);
}
};
template<class T, class Func>
std::vector<typename function_traits<Func>::result_type>
map(const std::vector<T> input, Func func) {
typedef typename function_traits<Func>::result_type ResultType;
std::vector<ResultType> output(input.size());
std::transform(input.begin(), input.end(), output.begin(), func);
return output;
}
template<class T>
T sum(std::vector<T> inputs) {
return std::accumulate(inputs.begin() + 1, inputs.end(), inputs[0], [](T a, T b) { return a + b; });
}
} } // namespace utils; namespace dsp
#endif
| 25.135135 | 104 | 0.67957 | [
"vector",
"transform"
] |
61b016526214ad109d4844c5948aecc2a1307708 | 1,385 | h | C | Furiosity/Math/Intersections.h | enci/Furiosity | 0f823b31ba369a6f20a69ca079627dccd4b4549a | [
"MIT"
] | 7 | 2015-05-14T18:36:18.000Z | 2020-08-30T19:09:33.000Z | Furiosity/Math/Intersections.h | enci/Furiosity | 0f823b31ba369a6f20a69ca079627dccd4b4549a | [
"MIT"
] | 1 | 2015-10-23T14:24:08.000Z | 2015-10-23T14:24:08.000Z | Furiosity/Math/Intersections.h | enci/Furiosity | 0f823b31ba369a6f20a69ca079627dccd4b4549a | [
"MIT"
] | 1 | 2020-07-31T23:34:49.000Z | 2020-07-31T23:34:49.000Z | ////////////////////////////////////////////////////////////////////////////////
// Intersections.h
// Furiosity
//
// Created by Bojan Endrovski on 11/28/12.
// Copyright (c) 2012 Bojan Endrovski. All rights reserved.
////////////////////////////////////////////////////////////////////////////////
#pragma once
#include <vector>
#include "Vector2.h"
#include "Vector3.h"
using std::vector;
namespace Furiosity
{
/// Intersection between two line segments
bool LineSegmentsInteresection(const Vector2& p,
const Vector2& pr,
const Vector2& q,
const Vector2& qs,
Vector2& res);
/// Finds an intersection between a ray and a sphere
/// if there is one.
bool RayToSphere(const Vector3& rayOrigin,
const Vector3& rayDirection,
const Vector3& sphereOrigin,
float sphereRadius,
Vector3& res);
///
/// Checks if a point is inside a convex polygon
///
/// @return True if are inside the polygo
/// @param point Point to check
/// @param polyVerts The vertices that make up the polygon, in clockwise order
bool PointInsideConvexPoly(const Vector2& point, const vector<Vector2>& polyVerts);
}
| 32.209302 | 87 | 0.499639 | [
"vector"
] |
61c4fd2309abc92753c3c01245bf10afea20a8a3 | 627 | h | C | Source/BotGame/DestinationMarker.h | itsdatnguyen/bot-game | 2e4bf510c4876a49c03b2f563aab16d3e6984469 | [
"MIT"
] | 1 | 2020-01-24T15:19:30.000Z | 2020-01-24T15:19:30.000Z | Source/BotGame/DestinationMarker.h | itsdatnguyen/bot-game | 2e4bf510c4876a49c03b2f563aab16d3e6984469 | [
"MIT"
] | null | null | null | Source/BotGame/DestinationMarker.h | itsdatnguyen/bot-game | 2e4bf510c4876a49c03b2f563aab16d3e6984469 | [
"MIT"
] | 1 | 2019-05-05T22:31:03.000Z | 2019-05-05T22:31:03.000Z | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "GameFramework/Actor.h"
#include "DestinationMarker.generated.h"
UCLASS()
class BOTGAME_API ADestinationMarker : public AActor
{
GENERATED_BODY()
public:
UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = "Static Mesh")
class UStaticMeshComponent* StaticMesh;
public:
// Sets default values for this actor's properties
ADestinationMarker();
// Called when the game starts or when spawned
virtual void BeginPlay() override;
// Called every frame
virtual void Tick( float DeltaSeconds ) override;
};
| 20.9 | 78 | 0.767145 | [
"mesh"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.